From bb4d48383722addbcf6715ef4952f3bff9e4a715 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes Date: Sat, 26 May 2018 11:27:53 -0400 Subject: [PATCH 1/6] Update go dependencies --- .travis.yml | 2 +- Gopkg.lock | 140 +- Gopkg.toml | 18 +- Makefile | 1 + vendor/cloud.google.com/go/.travis.yml | 9 +- vendor/cloud.google.com/go/CONTRIBUTING.md | 37 +- vendor/cloud.google.com/go/CONTRIBUTORS | 3 + vendor/cloud.google.com/go/LICENSE | 2 +- vendor/cloud.google.com/go/README.md | 283 +- vendor/cloud.google.com/go/RELEASING.md | 13 + .../cloud.google.com/go/authexample_test.go | 49 - vendor/cloud.google.com/go/cloud.go | 61 +- .../go/compute/metadata/metadata_test.go | 48 - vendor/cloud.google.com/go/issue_template.md | 17 + vendor/cloud.google.com/go/license_test.go | 70 - vendor/cloud.google.com/go/old-news.md | 110 + vendor/cloud.google.com/go/regen-gapic.sh | 68 + vendor/cloud.google.com/go/run-tests.sh | 4 +- .../github.com/Azure/go-autorest/CHANGELOG.md | 95 +- .../Azure/go-autorest/autorest/adal/README.md | 34 + .../Azure/go-autorest/autorest/adal/config.go | 16 + .../go-autorest/autorest/adal/config_test.go | 44 - .../autorest/adal/devicetoken_test.go | 330 - .../go-autorest/autorest/adal/persist_test.go | 171 - .../Azure/go-autorest/autorest/adal/token.go | 261 +- .../go-autorest/autorest/adal/token_test.go | 654 - .../go-autorest/autorest/authorization.go | 81 +- .../autorest/authorization_test.go | 188 - .../go-autorest/autorest/autorest_test.go | 140 - .../Azure/go-autorest/autorest/azure/async.go | 33 +- .../go-autorest/autorest/azure/async_test.go | 1327 -- .../go-autorest/autorest/azure/azure_test.go | 513 - .../autorest/azure/environments.go | 4 +- .../autorest/azure/environments_test.go | 284 - .../Azure/go-autorest/autorest/azure/rp.go | 4 +- .../go-autorest/autorest/azure/rp_test.go | 81 - .../Azure/go-autorest/autorest/client.go | 11 +- .../Azure/go-autorest/autorest/client_test.go | 402 - .../go-autorest/autorest/date/date_test.go | 237 - .../go-autorest/autorest/date/time_test.go | 277 - .../autorest/date/timerfc1123_test.go | 226 - .../autorest/date/unixtime_test.go | 283 - .../Azure/go-autorest/autorest/error_test.go | 202 - .../Azure/go-autorest/autorest/preparer.go | 46 +- .../go-autorest/autorest/preparer_test.go | 766 - .../go-autorest/autorest/responder_test.go | 665 - .../Azure/go-autorest/autorest/sender.go | 12 +- .../Azure/go-autorest/autorest/sender_test.go | 811 - .../Azure/go-autorest/autorest/utility.go | 72 +- .../go-autorest/autorest/utility_test.go | 382 - .../Azure/go-autorest/autorest/version.go | 6 +- .../armon/go-proxyproto/protocol.go | 9 +- .../armon/go-proxyproto/protocol_test.go | 383 - .../beorn7/perks/quantile/bench_test.go | 63 - .../beorn7/perks/quantile/example_test.go | 121 - .../beorn7/perks/quantile/stream.go | 34 +- .../beorn7/perks/quantile/stream_test.go | 215 - .../davecgh/go-spew/spew/common_test.go | 298 - .../davecgh/go-spew/spew/dump_test.go | 1042 - .../davecgh/go-spew/spew/dumpcgo_test.go | 99 - .../davecgh/go-spew/spew/dumpnocgo_test.go | 26 - .../davecgh/go-spew/spew/example_test.go | 226 - .../davecgh/go-spew/spew/format_test.go | 1558 -- .../davecgh/go-spew/spew/internal_test.go | 87 - .../go-spew/spew/internalunsafe_test.go | 102 - .../davecgh/go-spew/spew/spew_test.go | 320 - vendor/github.com/dgrijalva/jwt-go/README.md | 27 +- .../dgrijalva/jwt-go/VERSION_HISTORY.md | 7 + vendor/github.com/dgrijalva/jwt-go/ecdsa.go | 1 + .../github.com/dgrijalva/jwt-go/ecdsa_test.go | 100 - .../dgrijalva/jwt-go/example_test.go | 114 - vendor/github.com/dgrijalva/jwt-go/hmac.go | 3 +- .../dgrijalva/jwt-go/hmac_example_test.go | 66 - .../github.com/dgrijalva/jwt-go/hmac_test.go | 91 - .../dgrijalva/jwt-go/http_example_test.go | 216 - .../github.com/dgrijalva/jwt-go/none_test.go | 72 - vendor/github.com/dgrijalva/jwt-go/parser.go | 113 +- .../dgrijalva/jwt-go/parser_test.go | 261 - vendor/github.com/dgrijalva/jwt-go/rsa.go | 5 +- .../dgrijalva/jwt-go/rsa_pss_test.go | 96 - .../github.com/dgrijalva/jwt-go/rsa_test.go | 176 - .../github.com/dgrijalva/jwt-go/rsa_utils.go | 32 + .../docker/distribution/digestset/set_test.go | 371 - .../distribution/reference/normalize_test.go | 625 - .../distribution/reference/reference_test.go | 659 - .../distribution/reference/regexp_test.go | 553 - .../docker/spdystream/priority_test.go | 108 - .../docker/spdystream/spdy/spdy_test.go | 644 - .../docker/spdystream/spdy_bench_test.go | 113 - .../github.com/docker/spdystream/spdy_test.go | 1171 - .../eapache/channels/batching_channel_test.go | 45 - .../eapache/channels/black_hole_test.go | 26 - .../eapache/channels/channels_test.go | 265 - .../eapache/channels/infinite_channel_test.go | 48 - .../eapache/channels/native_channel_test.go | 58 - .../channels/overflowing_channel_test.go | 49 - .../channels/resizable_channel_test.go | 61 - .../eapache/channels/ring_channel_test.go | 49 - .../eapache/channels/shared_buffer_test.go | 127 - vendor/github.com/eapache/queue/queue_test.go | 178 - .../github.com/fsnotify/fsnotify/.travis.yml | 4 +- vendor/github.com/fsnotify/fsnotify/AUTHORS | 6 + .../github.com/fsnotify/fsnotify/CHANGELOG.md | 16 +- .../fsnotify/fsnotify/CONTRIBUTING.md | 6 +- vendor/github.com/fsnotify/fsnotify/README.md | 37 +- .../fsnotify/fsnotify/example_test.go | 42 - .../github.com/fsnotify/fsnotify/fsnotify.go | 4 + .../fsnotify/fsnotify/fsnotify_test.go | 40 - .../github.com/fsnotify/fsnotify/inotify.go | 66 +- .../fsnotify/fsnotify/inotify_poller_test.go | 229 - .../fsnotify/fsnotify/inotify_test.go | 360 - .../fsnotify/integration_darwin_test.go | 147 - .../fsnotify/fsnotify/integration_test.go | 1237 - vendor/github.com/fsnotify/fsnotify/kqueue.go | 62 +- .../github.com/fullsailor/pkcs7/.travis.yml | 5 +- .../github.com/fullsailor/pkcs7/ber_test.go | 97 - vendor/github.com/fullsailor/pkcs7/pkcs7.go | 36 +- .../github.com/fullsailor/pkcs7/pkcs7_test.go | 678 - vendor/github.com/fullsailor/pkcs7/x509.go | 133 + vendor/github.com/ghodss/yaml/yaml_test.go | 287 - vendor/github.com/gogo/protobuf/.travis.yml | 10 +- vendor/github.com/gogo/protobuf/CONTRIBUTORS | 1 + vendor/github.com/gogo/protobuf/Makefile | 1 + vendor/github.com/gogo/protobuf/README | 1 + vendor/github.com/gogo/protobuf/Readme.md | 27 +- vendor/github.com/gogo/protobuf/extensions.md | 2 +- .../gogo/protobuf/gogoproto/Makefile | 2 +- .../gogo/protobuf/gogoproto/gogo.pb.go | 155 +- .../gogo/protobuf/gogoproto/gogo.proto | 1 + .../gogo/protobuf/install-protobuf.sh | 4 - .../gogo/protobuf/proto/all_test.go | 2278 -- .../gogo/protobuf/proto/any_test.go | 300 - .../gogo/protobuf/proto/clone_test.go | 300 - .../gogo/protobuf/proto/decode_test.go | 262 - .../github.com/gogo/protobuf/proto/discard.go | 151 + .../gogo/protobuf/proto/encode_test.go | 84 - .../gogo/protobuf/proto/equal_test.go | 224 - .../gogo/protobuf/proto/extensions_test.go | 538 - .../gogo/protobuf/proto/map_test.go | 46 - .../gogo/protobuf/proto/message_set_test.go | 66 - .../gogo/protobuf/proto/proto3_test.go | 135 - .../gogo/protobuf/proto/size2_test.go | 63 - .../gogo/protobuf/proto/size_test.go | 164 - .../gogo/protobuf/proto/text_parser_test.go | 673 - .../gogo/protobuf/proto/text_test.go | 474 - .../descriptor/descriptor.pb.go | 375 +- .../descriptor/descriptor_gostring.gen.go | 33 +- .../descriptor/descriptor_test.go | 31 - vendor/github.com/golang/glog/glog_test.go | 415 - .../github.com/golang/groupcache/.travis.yml | 18 + .../golang/groupcache/byteview_test.go | 147 - .../golang/groupcache/groupcache_test.go | 456 - .../github.com/golang/groupcache/http_test.go | 166 - .../golang/groupcache/lru/lru_test.go | 97 - vendor/github.com/golang/groupcache/sinks.go | 2 +- vendor/github.com/golang/protobuf/.gitignore | 5 +- vendor/github.com/golang/protobuf/.travis.yml | 24 +- .../github.com/golang/protobuf/Make.protobuf | 40 - vendor/github.com/golang/protobuf/Makefile | 15 +- vendor/github.com/golang/protobuf/README.md | 65 +- .../github.com/golang/protobuf/proto/Makefile | 43 - .../golang/protobuf/proto/all_test.go | 2278 -- .../golang/protobuf/proto/any_test.go | 300 - .../github.com/golang/protobuf/proto/clone.go | 46 +- .../golang/protobuf/proto/clone_test.go | 300 - .../golang/protobuf/proto/decode.go | 668 +- .../golang/protobuf/proto/decode_test.go | 258 - .../golang/protobuf/proto/discard.go | 350 + .../golang/protobuf/proto/encode.go | 1191 +- .../golang/protobuf/proto/encode_test.go | 85 - .../github.com/golang/protobuf/proto/equal.go | 30 +- .../golang/protobuf/proto/equal_test.go | 224 - .../golang/protobuf/proto/extensions.go | 204 +- .../golang/protobuf/proto/extensions_test.go | 536 - .../github.com/golang/protobuf/proto/lib.go | 70 +- .../golang/protobuf/proto/map_test.go | 46 - .../golang/protobuf/proto/message_set.go | 81 +- .../golang/protobuf/proto/message_set_test.go | 66 - .../golang/protobuf/proto/pointer_reflect.go | 595 +- .../golang/protobuf/proto/pointer_unsafe.go | 366 +- .../golang/protobuf/proto/properties.go | 424 +- .../golang/protobuf/proto/proto3_test.go | 135 - .../golang/protobuf/proto/size2_test.go | 63 - .../golang/protobuf/proto/size_test.go | 164 - .../golang/protobuf/proto/table_marshal.go | 2681 +++ .../golang/protobuf/proto/table_merge.go | 654 + .../golang/protobuf/proto/table_unmarshal.go | 1967 ++ .../github.com/golang/protobuf/proto/text.go | 61 +- .../golang/protobuf/proto/text_parser.go | 77 +- .../golang/protobuf/proto/text_parser_test.go | 673 - .../golang/protobuf/proto/text_test.go | 474 - .../golang/protobuf/ptypes/any/any.pb.go | 49 +- .../golang/protobuf/ptypes/any_test.go | 113 - .../protobuf/ptypes/duration/duration.pb.go | 51 +- .../golang/protobuf/ptypes/duration_test.go | 121 - .../golang/protobuf/ptypes/regen.sh | 43 - .../protobuf/ptypes/timestamp/timestamp.pb.go | 53 +- .../protobuf/ptypes/timestamp/timestamp.proto | 2 +- .../golang/protobuf/ptypes/timestamp_test.go | 153 - .../github.com/golang/protobuf/regenerate.sh | 53 + .../github.com/google/gofuzz/example_test.go | 225 - vendor/github.com/google/gofuzz/fuzz_test.go | 472 - .../github.com/googleapis/gnostic/.gitignore | 7 + .../github.com/googleapis/gnostic/.travis.yml | 5 +- .../googleapis/gnostic/COMPILE-PROTOS.sh | 1 + .../googleapis/gnostic/OpenAPIv2/OpenAPIv2.go | 616 +- .../gnostic/OpenAPIv2/OpenAPIv2.pb.go | 5 +- .../github.com/googleapis/gnostic/README.md | 12 +- .../googleapis/gnostic/compiler/reader.go | 4 +- .../gnostic/extensions/extension.pb.go | 53 +- .../gnostic/extensions/extension.proto | 4 +- .../github.com/googleapis/gnostic/gnostic.go | 90 +- .../googleapis/gnostic/gnostic_test.go | 453 - .../gophercloud/gophercloud/.gitignore | 1 + .../gophercloud/gophercloud/.travis.yml | 4 +- .../gophercloud/gophercloud/.zuul.yaml | 64 + .../github.com/gophercloud/gophercloud/FAQ.md | 148 - .../gophercloud/gophercloud/MIGRATING.md | 32 - .../gophercloud/gophercloud/README.md | 18 +- .../gophercloud/gophercloud/STYLEGUIDE.md | 74 - .../gophercloud/gophercloud/auth_options.go | 75 +- .../gophercloud/gophercloud/errors.go | 50 +- .../gophercloud/openstack/auth_env.go | 29 +- .../gophercloud/openstack/client.go | 106 +- .../openstack/endpoint_location.go | 2 +- .../openstack/identity/v3/tokens/requests.go | 73 +- .../openstack/identity/v3/tokens/results.go | 1 + .../openstack/utils/base_endpoint.go | 29 + .../gophercloud/gophercloud/params.go | 30 +- .../gophercloud/provider_client.go | 99 +- .../gophercloud/gophercloud/results.go | 21 + .../gophercloud/gophercloud/service_client.go | 28 + vendor/github.com/hashicorp/golang-lru/2q.go | 21 +- .../hashicorp/golang-lru/2q_test.go | 306 - vendor/github.com/hashicorp/golang-lru/arc.go | 16 +- .../hashicorp/golang-lru/arc_test.go | 377 - vendor/github.com/hashicorp/golang-lru/doc.go | 21 + vendor/github.com/hashicorp/golang-lru/lru.go | 28 +- .../hashicorp/golang-lru/lru_test.go | 221 - .../hashicorp/golang-lru/simplelru/lru.go | 17 +- .../golang-lru/simplelru/lru_interface.go | 37 + .../golang-lru/simplelru/lru_test.go | 167 - vendor/github.com/howeyc/gopass/pass_test.go | 225 - .../github.com/imdario/mergo/issue17_test.go | 25 - .../github.com/imdario/mergo/issue23_test.go | 27 - .../github.com/imdario/mergo/issue38_test.go | 59 - vendor/github.com/imdario/mergo/mergo_test.go | 662 - vendor/github.com/json-iterator/go/.gitignore | 5 +- vendor/github.com/json-iterator/go/Gopkg.lock | 21 + vendor/github.com/json-iterator/go/Gopkg.toml | 26 + vendor/github.com/json-iterator/go/README.md | 2 + .../go/{feature_adapter.go => adapter.go} | 39 +- .../go/{feature_any.go => any.go} | 85 +- .../go/{feature_any_array.go => any_array.go} | 0 .../go/{feature_any_bool.go => any_bool.go} | 0 .../go/{feature_any_float.go => any_float.go} | 0 .../go/{feature_any_int32.go => any_int32.go} | 0 .../go/{feature_any_int64.go => any_int64.go} | 0 ...{feature_any_invalid.go => any_invalid.go} | 0 .../go/{feature_any_nil.go => any_nil.go} | 0 .../{feature_any_number.go => any_number.go} | 37 +- .../{feature_any_object.go => any_object.go} | 0 .../go/{feature_any_string.go => any_str.go} | 2 +- .../{feature_any_uint32.go => any_uint32.go} | 0 .../{feature_any_uint64.go => any_uint64.go} | 0 vendor/github.com/json-iterator/go/build.sh | 12 + .../go/{feature_config.go => config.go} | 273 +- .../json-iterator/go/example_test.go | 95 - .../json-iterator/go/feature_json_number.go | 31 - .../json-iterator/go/feature_reflect.go | 703 - .../json-iterator/go/feature_reflect_array.go | 99 - .../json-iterator/go/feature_reflect_map.go | 244 - .../go/feature_reflect_native.go | 764 - .../json-iterator/go/feature_reflect_slice.go | 149 - .../json-iterator/go/feature_stream_int.go | 320 - .../go/{feature_iter.go => iter.go} | 3 +- .../{feature_iter_array.go => iter_array.go} | 0 .../{feature_iter_float.go => iter_float.go} | 6 + .../go/{feature_iter_int.go => iter_int.go} | 87 + ...{feature_iter_object.go => iter_object.go} | 98 +- .../go/{feature_iter_skip.go => iter_skip.go} | 0 ...ter_skip_sloppy.go => iter_skip_sloppy.go} | 2 +- ...ter_skip_strict.go => iter_skip_strict.go} | 2 +- .../{feature_iter_string.go => iter_str.go} | 0 .../go/jsoniter_1dot8_only_test.go | 45 - .../json-iterator/go/jsoniter_adapter_test.go | 84 - .../json-iterator/go/jsoniter_alias_test.go | 62 - .../go/jsoniter_any_array_test.go | 122 - .../go/jsoniter_any_bool_test.go | 64 - .../go/jsoniter_any_float_test.go | 102 - .../json-iterator/go/jsoniter_any_int_test.go | 197 - .../json-iterator/go/jsoniter_any_map_test.go | 14 - .../go/jsoniter_any_null_test.go | 15 - .../go/jsoniter_any_object_test.go | 107 - .../go/jsoniter_any_string_test.go | 56 - .../json-iterator/go/jsoniter_array_test.go | 213 - .../json-iterator/go/jsoniter_bool_test.go | 113 - .../go/jsoniter_customize_test.go | 341 - .../json-iterator/go/jsoniter_demo_test.go | 87 - .../go/jsoniter_encode_interface_test.go | 42 - .../go/jsoniter_enum_marshaler_test.go | 50 - .../go/jsoniter_fixed_array_test.go | 37 - .../json-iterator/go/jsoniter_float_test.go | 210 - .../json-iterator/go/jsoniter_int_test.go | 561 - .../go/jsoniter_interface_test.go | 560 - .../json-iterator/go/jsoniter_invalid_test.go | 138 - .../json-iterator/go/jsoniter_io_test.go | 65 - .../go/jsoniter_iterator_test.go | 66 - .../go/jsoniter_large_file_test.go | 157 - .../json-iterator/go/jsoniter_map_test.go | 160 - .../go/jsoniter_must_be_valid_test.go | 71 - .../json-iterator/go/jsoniter_nested_test.go | 88 - .../json-iterator/go/jsoniter_null_test.go | 168 - .../json-iterator/go/jsoniter_object_test.go | 330 - .../go/jsoniter_optional_test.go | 46 - .../go/jsoniter_raw_message_test.go | 114 - .../json-iterator/go/jsoniter_reader_test.go | 57 - .../go/jsoniter_reflect_native_test.go | 154 - .../json-iterator/go/jsoniter_skip_test.go | 179 - .../json-iterator/go/jsoniter_sloppy_test.go | 162 - .../json-iterator/go/jsoniter_stream_test.go | 69 - .../json-iterator/go/jsoniter_string_test.go | 261 - .../go/jsoniter_struct_decoder_test.go | 267 - .../go/jsoniter_struct_encoder_test.go | 52 - .../json-iterator/go/jsoniter_wrap_test.go | 118 - .../go/{feature_pool.go => pool.go} | 36 +- vendor/github.com/json-iterator/go/reflect.go | 321 + .../json-iterator/go/reflect_array.go | 104 + .../json-iterator/go/reflect_dynamic.go | 70 + ...lect_extension.go => reflect_extension.go} | 282 +- .../json-iterator/go/reflect_json_number.go | 112 + .../go/reflect_json_raw_message.go | 60 + .../json-iterator/go/reflect_map.go | 318 + .../json-iterator/go/reflect_marshaler.go | 218 + .../json-iterator/go/reflect_native.go | 455 + .../json-iterator/go/reflect_optional.go | 133 + .../json-iterator/go/reflect_slice.go | 99 + ...t_decoder.go => reflect_struct_decoder.go} | 492 +- ...ct_object.go => reflect_struct_encoder.go} | 158 +- .../go/{feature_stream.go => stream.go} | 168 +- ...eature_stream_float.go => stream_float.go} | 14 +- .../github.com/json-iterator/go/stream_int.go | 190 + ...feature_stream_string.go => stream_str.go} | 40 +- vendor/github.com/json-iterator/go/test.sh | 2 +- .../json-iterator/go/unmarshal_input_test.go | 72 - vendor/github.com/kr/pty/README.md | 64 + vendor/github.com/kr/pty/mktypes.bash | 2 +- vendor/github.com/kr/pty/pty_darwin.go | 12 +- vendor/github.com/kr/pty/pty_dragonfly.go | 12 +- vendor/github.com/kr/pty/pty_freebsd.go | 19 +- vendor/github.com/kr/pty/pty_linux.go | 9 +- vendor/github.com/kr/pty/pty_openbsd.go | 33 + vendor/github.com/kr/pty/pty_unsupported.go | 2 +- vendor/github.com/kr/pty/types_openbsd.go | 14 + vendor/github.com/kr/pty/util.go | 47 +- .../github.com/kr/pty/ztypes_openbsd_amd64.go | 13 + .../kylelemons/godebug/diff/diff_test.go | 166 - .../godebug/pretty/examples_test.go | 310 - .../kylelemons/godebug/pretty/public_test.go | 128 - .../kylelemons/godebug/pretty/reflect_test.go | 236 - .../godebug/pretty/structure_test.go | 316 - .../pbutil/all_test.go | 177 - .../pbutil/decode_test.go | 99 - .../pbutil/encode_test.go | 67 - .../pbutil/fixtures_test.go | 103 - .../mitchellh/go-ps/process_darwin_test.go | 11 - .../mitchellh/go-ps/process_test.go | 45 - .../mitchellh/go-ps/process_unix_test.go | 11 - .../mitchellh/mapstructure/.travis.yml | 11 +- .../mitchellh/mapstructure/README.md | 2 +- .../mitchellh/mapstructure/decode_hooks.go | 19 + .../mapstructure/decode_hooks_test.go | 229 - .../mitchellh/mapstructure/mapstructure.go | 363 +- .../mapstructure_benchmark_test.go | 279 - .../mapstructure/mapstructure_bugs_test.go | 260 - .../mapstructure_examples_test.go | 203 - .../mapstructure/mapstructure_test.go | 1193 - .../modern-go/concurrent/.gitignore | 1 + .../modern-go/concurrent/.travis.yml | 14 + .../github.com/modern-go/concurrent/LICENSE | 201 + .../github.com/modern-go/concurrent/README.md | 49 + .../modern-go/concurrent/executor.go | 14 + .../modern-go/concurrent/go_above_19.go | 15 + .../modern-go/concurrent/go_below_19.go | 33 + vendor/github.com/modern-go/concurrent/log.go | 13 + .../github.com/modern-go/concurrent/test.sh | 12 + .../concurrent/unbounded_executor.go | 119 + .../github.com/modern-go/reflect2/.gitignore | 1 + .../github.com/modern-go/reflect2/Gopkg.lock | 15 + .../github.com/modern-go/reflect2}/Gopkg.toml | 7 +- vendor/github.com/modern-go/reflect2/LICENSE | 201 + .../github.com/modern-go/reflect2/README.md | 2 + .../modern-go/reflect2/go_above_17.go | 8 + .../modern-go/reflect2/go_above_19.go | 14 + .../modern-go/reflect2/go_below_17.go | 9 + .../modern-go/reflect2/go_below_19.go | 14 + .../github.com/modern-go/reflect2/reflect2.go | 282 + .../modern-go/reflect2/reflect2_amd64.s} | 0 .../modern-go/reflect2/reflect2_kind.go | 30 + .../modern-go/reflect2/relfect2_386.s | 0 .../modern-go/reflect2/relfect2_amd64p32.s | 0 .../modern-go/reflect2/relfect2_arm.s | 0 .../modern-go/reflect2/relfect2_arm64.s | 0 .../modern-go/reflect2/relfect2_mips64x.s | 0 .../modern-go/reflect2/relfect2_mipsx.s | 0 .../modern-go/reflect2/relfect2_ppc64x.s | 0 .../modern-go/reflect2/relfect2_s390x.s | 0 .../modern-go/reflect2/safe_field.go | 58 + .../github.com/modern-go/reflect2/safe_map.go | 101 + .../modern-go/reflect2/safe_slice.go | 92 + .../modern-go/reflect2/safe_struct.go | 13 + .../modern-go/reflect2/safe_type.go | 78 + .../github.com/modern-go/reflect2/type_map.go | 72 + .../modern-go/reflect2/unsafe_array.go | 65 + .../modern-go/reflect2/unsafe_eface.go | 59 + .../modern-go/reflect2/unsafe_field.go | 74 + .../modern-go/reflect2/unsafe_iface.go | 64 + .../modern-go/reflect2/unsafe_link.go | 70 + .../modern-go/reflect2/unsafe_map.go | 138 + .../modern-go/reflect2/unsafe_ptr.go | 46 + .../modern-go/reflect2/unsafe_slice.go | 177 + .../modern-go/reflect2/unsafe_struct.go | 59 + .../modern-go/reflect2/unsafe_type.go | 85 + .../moul/http2curl/http2curl_test.go | 101 - .../process-exporter/proc/base_test.go | 26 - .../process-exporter/proc/grouper_test.go | 268 - .../process-exporter/proc/read_test.go | 120 - .../process-exporter/proc/tracker_test.go | 94 - vendor/github.com/onsi/ginkgo/.gitignore | 3 +- vendor/github.com/onsi/ginkgo/.travis.yml | 5 +- vendor/github.com/onsi/ginkgo/CHANGELOG.md | 31 + vendor/github.com/onsi/ginkgo/CONTRIBUTING.md | 3 +- vendor/github.com/onsi/ginkgo/README.md | 32 +- vendor/github.com/onsi/ginkgo/RELEASING.md | 14 + vendor/github.com/onsi/ginkgo/before_pr.sh | 13 + .../github.com/onsi/ginkgo/config/config.go | 10 +- vendor/github.com/onsi/ginkgo/ginkgo_dsl.go | 59 +- .../codelocation/code_location_suite_test.go | 13 - .../codelocation/code_location_test.go | 79 - .../container_node_suite_test.go | 13 - .../containernode/container_node_test.go | 212 - .../internal/failer/failer_suite_test.go | 13 - .../ginkgo/internal/failer/failer_test.go | 141 - .../ginkgo/internal/leafnodes/benchmarker.go | 4 +- .../onsi/ginkgo/internal/leafnodes/it_node.go | 3 +- .../ginkgo/internal/leafnodes/it_node_test.go | 22 - .../leafnodes/leaf_node_suite_test.go | 13 - .../ginkgo/internal/leafnodes/measure_node.go | 3 +- .../internal/leafnodes/measure_node_test.go | 154 - .../onsi/ginkgo/internal/leafnodes/runner.go | 5 +- .../ginkgo/internal/leafnodes/setup_nodes.go | 3 +- .../internal/leafnodes/setup_nodes_test.go | 40 - .../internal/leafnodes/shared_runner_test.go | 356 - .../ginkgo/internal/leafnodes/suite_nodes.go | 3 +- .../internal/leafnodes/suite_nodes_test.go | 230 - .../synchronized_after_suite_node.go | 5 +- .../synchronized_after_suite_node_test.go | 196 - .../synchronized_before_suite_node.go | 7 +- .../synchronized_before_suite_node_test.go | 445 - .../onsi/ginkgo/internal/remote/aggregator.go | 2 +- .../ginkgo/internal/remote/aggregator_test.go | 315 - .../remote/fake_output_interceptor_test.go | 17 - .../internal/remote/fake_poster_test.go | 33 - .../remote/forwarding_reporter_test.go | 180 - .../internal/remote/remote_suite_test.go | 13 - .../onsi/ginkgo/internal/remote/server.go | 2 +- .../ginkgo/internal/remote/server_test.go | 269 - .../remote/syscall_dup_linux_arm64.go | 2 +- .../internal/remote/syscall_dup_solaris.go | 2 +- .../internal/remote/syscall_dup_unix.go | 2 +- .../onsi/ginkgo/internal/spec/spec.go | 71 +- .../ginkgo/internal/spec/spec_suite_test.go | 13 - .../onsi/ginkgo/internal/spec/spec_test.go | 657 - .../onsi/ginkgo/internal/spec/specs_test.go | 287 - .../spec_iterator/index_computer_test.go | 149 - .../spec_iterator/parallel_spec_iterator.go | 3 +- .../parallel_spec_iterator_test.go | 112 - .../serial_spec_iterator_test.go | 64 - .../sharded_parallel_spec_iterator_test.go | 62 - .../spec_iterator/spec_iterator_suite_test.go | 13 - .../ginkgo/internal/specrunner/spec_runner.go | 7 +- .../specrunner/spec_runner_suite_test.go | 13 - .../internal/specrunner/spec_runner_test.go | 779 - .../onsi/ginkgo/internal/suite/suite.go | 10 +- .../ginkgo/internal/suite/suite_suite_test.go | 35 - .../onsi/ginkgo/internal/suite/suite_test.go | 371 - .../internal/writer/writer_suite_test.go | 13 - .../ginkgo/internal/writer/writer_test.go | 75 - .../onsi/ginkgo/reporters/default_reporter.go | 2 +- .../ginkgo/reporters/default_reporter_test.go | 414 - .../onsi/ginkgo/reporters/junit_reporter.go | 2 + .../ginkgo/reporters/junit_reporter_test.go | 247 - .../ginkgo/reporters/reporters_suite_test.go | 13 - .../reporters/stenographer/stenographer.go | 2 +- .../ginkgo/reporters/teamcity_reporter.go | 5 +- .../reporters/teamcity_reporter_test.go | 213 - .../onsi/ginkgo/types/types_suite_test.go | 13 - .../onsi/ginkgo/types/types_test.go | 99 - vendor/github.com/onsi/gomega/.travis.yml | 10 +- vendor/github.com/onsi/gomega/CHANGELOG.md | 25 + vendor/github.com/onsi/gomega/CONTRIBUTING.md | 5 +- vendor/github.com/onsi/gomega/RELEASING.md | 12 + .../github.com/onsi/gomega/format/format.go | 7 +- .../onsi/gomega/format/format_suite_test.go | 13 - .../onsi/gomega/format/format_test.go | 590 - vendor/github.com/onsi/gomega/gomega_dsl.go | 65 +- .../assertion/assertion_suite_test.go | 13 - .../internal/assertion/assertion_test.go | 252 - .../async_assertion_suite_test.go | 13 - .../asyncassertion/async_assertion_test.go | 345 - .../testingtsupport/testing_t_support_test.go | 12 - vendor/github.com/onsi/gomega/matchers.go | 76 +- .../onsi/gomega/matchers/and_test.go | 103 - .../matchers/assignable_to_type_of_matcher.go | 6 +- .../assignable_to_type_of_matcher_test.go | 30 - .../onsi/gomega/matchers/attributes_slice.go | 14 + .../gomega/matchers/be_a_directory_test.go | 40 - .../gomega/matchers/be_a_regular_file_test.go | 40 - .../matchers/be_an_existing_file_test.go | 40 - .../onsi/gomega/matchers/be_closed_matcher.go | 3 +- .../gomega/matchers/be_closed_matcher_test.go | 70 - .../onsi/gomega/matchers/be_empty_matcher.go | 1 + .../gomega/matchers/be_empty_matcher_test.go | 52 - .../matchers/be_equivalent_to_matcher.go | 3 +- .../matchers/be_equivalent_to_matcher_test.go | 50 - .../onsi/gomega/matchers/be_false_matcher.go | 1 + .../gomega/matchers/be_false_matcher_test.go | 20 - .../gomega/matchers/be_identical_to_test.go | 61 - .../gomega/matchers/be_nil_matcher_test.go | 28 - .../matchers/be_numerically_matcher_test.go | 148 - .../gomega/matchers/be_sent_matcher_test.go | 106 - .../gomega/matchers/be_temporally_matcher.go | 3 +- .../matchers/be_temporally_matcher_test.go | 98 - .../onsi/gomega/matchers/be_true_matcher.go | 1 + .../gomega/matchers/be_true_matcher_test.go | 20 - .../onsi/gomega/matchers/be_zero_matcher.go | 3 +- .../gomega/matchers/be_zero_matcher_test.go | 30 - .../onsi/gomega/matchers/consist_of_test.go | 75 - .../matchers/contain_element_matcher_test.go | 76 - .../matchers/contain_substring_matcher.go | 3 +- .../contain_substring_matcher_test.go | 36 - .../onsi/gomega/matchers/equal_matcher.go | 9 + .../gomega/matchers/equal_matcher_test.go | 78 - .../gomega/matchers/have_cap_matcher_test.go | 50 - .../onsi/gomega/matchers/have_key_matcher.go | 3 +- .../gomega/matchers/have_key_matcher_test.go | 73 - .../matchers/have_key_with_value_matcher.go | 3 +- .../have_key_with_value_matcher_test.go | 82 - .../onsi/gomega/matchers/have_len_matcher.go | 1 + .../gomega/matchers/have_len_matcher_test.go | 53 - .../matchers/have_occurred_matcher_test.go | 58 - .../gomega/matchers/have_prefix_matcher.go | 1 + .../matchers/have_prefix_matcher_test.go | 36 - .../gomega/matchers/have_suffix_matcher.go | 1 + .../matchers/have_suffix_matcher_test.go | 36 - .../gomega/matchers/match_error_matcher.go | 11 +- .../matchers/match_error_matcher_test.go | 93 - .../matchers/match_json_matcher_test.go | 97 - .../gomega/matchers/match_regexp_matcher.go | 3 +- .../matchers/match_regexp_matcher_test.go | 44 - .../onsi/gomega/matchers/match_xml_matcher.go | 3 + .../gomega/matchers/match_xml_matcher_test.go | 90 - .../matchers/match_yaml_matcher_test.go | 94 - .../matchers/matcher_tests_suite_test.go | 50 - .../onsi/gomega/matchers/not_test.go | 57 - .../onsi/gomega/matchers/or_test.go | 85 - .../gomega/matchers/panic_matcher_test.go | 45 - .../gomega/matchers/receive_matcher_test.go | 280 - .../gomega/matchers/succeed_matcher_test.go | 62 - .../goraph/bipartitegraph/bipartitegraph.go | 6 +- .../gomega/matchers/with_transform_test.go | 102 - vendor/github.com/onsi/gomega/types/types.go | 2 +- .../go-digest/algorithm_test.go | 114 - .../opencontainers/go-digest/digest_test.go | 134 - .../go-digest/verifiers_test.go | 80 - .../parnurzeal/gorequest/gorequest_test.go | 1776 -- .../github.com/pborman/uuid/marshal_test.go | 124 - vendor/github.com/pborman/uuid/seq_test.go | 66 - vendor/github.com/pborman/uuid/sql_test.go | 96 - vendor/github.com/pborman/uuid/uuid_test.go | 543 - vendor/github.com/pkg/errors/bench_test.go | 59 - vendor/github.com/pkg/errors/errors_test.go | 226 - vendor/github.com/pkg/errors/example_test.go | 205 - vendor/github.com/pkg/errors/format_test.go | 535 - vendor/github.com/pkg/errors/stack_test.go | 292 - .../prometheus/benchmark_test.go | 183 - .../client_golang/prometheus/counter_test.go | 58 - .../prometheus/example_clustermanager_test.go | 118 - .../client_golang/prometheus/examples_test.go | 751 - .../prometheus/expvar_collector_test.go | 97 - .../client_golang/prometheus/gauge_test.go | 182 - .../prometheus/go_collector_test.go | 123 - .../prometheus/histogram_test.go | 326 - .../client_golang/prometheus/http_test.go | 121 - .../prometheus/process_collector_test.go | 58 - .../prometheus/promhttp/http_test.go | 137 - .../client_golang/prometheus/registry_test.go | 545 - .../client_golang/prometheus/summary_test.go | 347 - .../client_golang/prometheus/vec_test.go | 312 - .../prometheus/client_model/Makefile | 1 + vendor/github.com/prometheus/common/README.md | 2 +- .../prometheus/common/expfmt/bench_test.go | 167 - .../prometheus/common/expfmt/decode.go | 4 +- .../prometheus/common/expfmt/decode_test.go | 435 - .../prometheus/common/expfmt/expfmt.go | 2 +- .../common/expfmt/text_create_test.go | 443 - .../prometheus/common/expfmt/text_parse.go | 4 +- .../common/expfmt/text_parse_test.go | 593 - .../ww/goautoneg/autoneg_test.go | 33 - .../prometheus/common/model/alert_test.go | 118 - .../prometheus/common/model/labels_test.go | 140 - .../prometheus/common/model/metric_test.go | 132 - .../prometheus/common/model/signature_test.go | 314 - .../prometheus/common/model/silence.go | 4 +- .../prometheus/common/model/silence_test.go | 228 - .../prometheus/common/model/time.go | 3 + .../prometheus/common/model/time_test.go | 129 - .../prometheus/common/model/value.go | 4 +- .../prometheus/common/model/value_test.go | 468 - .../github.com/prometheus/procfs/.gitignore | 1 + .../github.com/prometheus/procfs/.travis.yml | 14 +- vendor/github.com/prometheus/procfs/Makefile | 77 +- .../github.com/prometheus/procfs/buddyinfo.go | 2 +- .../prometheus/procfs/buddyinfo_test.go | 64 - .../prometheus/procfs/fixtures.ttar | 446 + vendor/github.com/prometheus/procfs/fs.go | 36 + .../github.com/prometheus/procfs/fs_test.go | 26 - .../prometheus/procfs/internal/util/parse.go | 46 + vendor/github.com/prometheus/procfs/ipvs.go | 23 +- .../github.com/prometheus/procfs/ipvs_test.go | 237 - vendor/github.com/prometheus/procfs/mdstat.go | 13 + .../prometheus/procfs/mdstat_test.go | 31 - .../prometheus/procfs/mountstats.go | 13 + .../prometheus/procfs/mountstats_test.go | 273 - .../github.com/prometheus/procfs/net_dev.go | 216 + .../github.com/prometheus/procfs/nfs/nfs.go | 263 + .../github.com/prometheus/procfs/nfs/parse.go | 317 + .../prometheus/procfs/nfs/parse_nfs.go | 67 + .../prometheus/procfs/nfs/parse_nfsd.go | 89 + vendor/github.com/prometheus/procfs/proc.go | 16 +- .../github.com/prometheus/procfs/proc_io.go | 18 +- .../prometheus/procfs/proc_io_test.go | 33 - .../prometheus/procfs/proc_limits.go | 13 + .../prometheus/procfs/proc_limits_test.go | 31 - .../github.com/prometheus/procfs/proc_ns.go | 68 + .../github.com/prometheus/procfs/proc_stat.go | 13 + .../prometheus/procfs/proc_stat_test.go | 110 - .../github.com/prometheus/procfs/proc_test.go | 160 - vendor/github.com/prometheus/procfs/stat.go | 13 + .../github.com/prometheus/procfs/stat_test.go | 61 - vendor/github.com/prometheus/procfs/ttar | 133 +- .../github.com/prometheus/procfs/xfrm_test.go | 66 - .../github.com/prometheus/procfs/xfs/parse.go | 37 +- .../prometheus/procfs/xfs/parse_test.go | 442 - vendor/github.com/spf13/afero/.travis.yml | 4 +- vendor/github.com/spf13/afero/afero_test.go | 699 - vendor/github.com/spf13/afero/basepath.go | 47 +- .../github.com/spf13/afero/basepath_test.go | 142 - .../github.com/spf13/afero/cacheOnReadFs.go | 6 +- .../github.com/spf13/afero/composite_test.go | 404 - .../github.com/spf13/afero/copyOnWriteFs.go | 53 +- .../spf13/afero/copyOnWriteFs_test.go | 39 - vendor/github.com/spf13/afero/ioutil_test.go | 112 - .../metric_test.go => spf13/afero/lstater.go} | 34 +- vendor/github.com/spf13/afero/match.go | 4 +- vendor/github.com/spf13/afero/match_test.go | 183 - vendor/github.com/spf13/afero/mem/file.go | 3 + .../github.com/spf13/afero/mem/file_test.go | 154 - vendor/github.com/spf13/afero/memmap_test.go | 421 - vendor/github.com/spf13/afero/os.go | 7 + vendor/github.com/spf13/afero/path.go | 18 +- vendor/github.com/spf13/afero/path_test.go | 69 - vendor/github.com/spf13/afero/readonlyfs.go | 10 + .../github.com/spf13/afero/ro_regexp_test.go | 96 - vendor/github.com/spf13/afero/unionFile.go | 189 +- vendor/github.com/spf13/afero/util.go | 3 +- vendor/github.com/spf13/afero/util_test.go | 450 - .../github.com/spf13/pflag/bool_slice_test.go | 215 - vendor/github.com/spf13/pflag/bool_test.go | 179 - vendor/github.com/spf13/pflag/bytes.go | 105 + vendor/github.com/spf13/pflag/count.go | 12 +- vendor/github.com/spf13/pflag/count_test.go | 52 - .../github.com/spf13/pflag/duration_slice.go | 128 + vendor/github.com/spf13/pflag/example_test.go | 36 - vendor/github.com/spf13/pflag/export_test.go | 29 - vendor/github.com/spf13/pflag/flag.go | 155 +- vendor/github.com/spf13/pflag/flag_test.go | 1085 - vendor/github.com/spf13/pflag/golangflag.go | 4 + .../github.com/spf13/pflag/golangflag_test.go | 39 - vendor/github.com/spf13/pflag/int16.go | 88 + .../github.com/spf13/pflag/int_slice_test.go | 165 - .../github.com/spf13/pflag/ip_slice_test.go | 222 - vendor/github.com/spf13/pflag/ip_test.go | 63 - vendor/github.com/spf13/pflag/ipnet_test.go | 70 - vendor/github.com/spf13/pflag/string_array.go | 8 +- .../spf13/pflag/string_array_test.go | 233 - vendor/github.com/spf13/pflag/string_slice.go | 20 + .../spf13/pflag/string_slice_test.go | 253 - .../github.com/spf13/pflag/uint_slice_test.go | 161 - .../certUtil/chain_test.go | 33 - .../cert-chain-resolver/certUtil/io_test.go | 11 - vendor/golang.org/x/crypto/CONTRIBUTING.md | 15 +- vendor/golang.org/x/crypto/ed25519/ed25519.go | 13 +- .../x/crypto/ed25519/ed25519_test.go | 183 - .../internal/edwards25519/edwards25519.go | 22 + .../golang.org/x/crypto/ssh/benchmark_test.go | 122 - vendor/golang.org/x/crypto/ssh/buffer_test.go | 87 - vendor/golang.org/x/crypto/ssh/certs.go | 8 +- vendor/golang.org/x/crypto/ssh/certs_test.go | 222 - vendor/golang.org/x/crypto/ssh/channel.go | 142 +- vendor/golang.org/x/crypto/ssh/cipher.go | 247 +- vendor/golang.org/x/crypto/ssh/cipher_test.go | 129 - vendor/golang.org/x/crypto/ssh/client.go | 25 +- vendor/golang.org/x/crypto/ssh/client_auth.go | 121 +- .../x/crypto/ssh/client_auth_test.go | 628 - vendor/golang.org/x/crypto/ssh/client_test.go | 81 - vendor/golang.org/x/crypto/ssh/common.go | 20 +- .../golang.org/x/crypto/ssh/example_test.go | 320 - vendor/golang.org/x/crypto/ssh/handshake.go | 6 + .../golang.org/x/crypto/ssh/handshake_test.go | 559 - vendor/golang.org/x/crypto/ssh/kex.go | 24 +- vendor/golang.org/x/crypto/ssh/kex_test.go | 50 - vendor/golang.org/x/crypto/ssh/keys.go | 47 +- vendor/golang.org/x/crypto/ssh/keys_test.go | 500 - .../golang.org/x/crypto/ssh/mempipe_test.go | 110 - vendor/golang.org/x/crypto/ssh/messages.go | 38 +- .../golang.org/x/crypto/ssh/messages_test.go | 288 - vendor/golang.org/x/crypto/ssh/mux.go | 6 +- vendor/golang.org/x/crypto/ssh/mux_test.go | 505 - vendor/golang.org/x/crypto/ssh/server.go | 42 +- vendor/golang.org/x/crypto/ssh/session.go | 2 +- .../golang.org/x/crypto/ssh/session_test.go | 774 - vendor/golang.org/x/crypto/ssh/streamlocal.go | 1 + vendor/golang.org/x/crypto/ssh/tcpip.go | 9 + vendor/golang.org/x/crypto/ssh/tcpip_test.go | 20 - .../x/crypto/ssh/terminal/terminal.go | 2 +- .../x/crypto/ssh/terminal/terminal_test.go | 350 - .../golang.org/x/crypto/ssh/terminal/util.go | 4 +- .../x/crypto/ssh/terminal/util_solaris.go | 40 +- .../x/crypto/ssh/terminal/util_windows.go | 23 +- .../golang.org/x/crypto/ssh/testdata_test.go | 63 - vendor/golang.org/x/crypto/ssh/transport.go | 70 +- .../golang.org/x/crypto/ssh/transport_test.go | 109 - vendor/golang.org/x/net/CONTRIBUTING.md | 15 +- .../golang.org/x/net/context/context_test.go | 583 - .../x/net/context/ctxhttp/ctxhttp_17_test.go | 29 - .../net/context/ctxhttp/ctxhttp_pre17_test.go | 79 - .../x/net/context/ctxhttp/ctxhttp_test.go | 105 - .../x/net/context/withtimeout_test.go | 31 - .../golang.org/x/net/html/atom/atom_test.go | 109 - vendor/golang.org/x/net/html/atom/gen.go | 5 +- vendor/golang.org/x/net/html/atom/table.go | 1444 +- .../golang.org/x/net/html/atom/table_test.go | 373 - .../x/net/html/charset/charset_test.go | 237 - vendor/golang.org/x/net/html/const.go | 2 +- vendor/golang.org/x/net/html/doc.go | 8 +- vendor/golang.org/x/net/html/entity.go | 4154 ++-- vendor/golang.org/x/net/html/entity_test.go | 29 - vendor/golang.org/x/net/html/escape_test.go | 97 - vendor/golang.org/x/net/html/example_test.go | 40 - vendor/golang.org/x/net/html/foreign.go | 6 +- vendor/golang.org/x/net/html/node.go | 33 +- vendor/golang.org/x/net/html/node_test.go | 146 - vendor/golang.org/x/net/html/parse.go | 361 +- vendor/golang.org/x/net/html/parse_test.go | 388 - vendor/golang.org/x/net/html/render_test.go | 156 - vendor/golang.org/x/net/html/token.go | 4 +- vendor/golang.org/x/net/html/token_test.go | 748 - vendor/golang.org/x/net/http/httpguts/guts.go | 65 + .../{lex/httplex => http/httpguts}/httplex.go | 7 +- vendor/golang.org/x/net/http2/ciphers.go | 2 +- vendor/golang.org/x/net/http2/ciphers_test.go | 309 - .../x/net/http2/configure_transport.go | 2 +- .../golang.org/x/net/http2/databuffer_test.go | 157 - vendor/golang.org/x/net/http2/errors_test.go | 24 - vendor/golang.org/x/net/http2/flow_test.go | 53 - vendor/golang.org/x/net/http2/frame.go | 4 +- vendor/golang.org/x/net/http2/frame_test.go | 1191 - vendor/golang.org/x/net/http2/go18_test.go | 79 - vendor/golang.org/x/net/http2/go19_test.go | 60 - vendor/golang.org/x/net/http2/gotrack_test.go | 33 - vendor/golang.org/x/net/http2/hpack/encode.go | 2 +- .../x/net/http2/hpack/encode_test.go | 386 - vendor/golang.org/x/net/http2/hpack/hpack.go | 6 + .../x/net/http2/hpack/hpack_test.go | 722 - .../x/net/http2/hpack/tables_test.go | 214 - vendor/golang.org/x/net/http2/http2.go | 8 +- vendor/golang.org/x/net/http2/http2_test.go | 199 - vendor/golang.org/x/net/http2/pipe_test.go | 130 - vendor/golang.org/x/net/http2/server.go | 112 +- .../x/net/http2/server_push_test.go | 521 - vendor/golang.org/x/net/http2/server_test.go | 3728 --- vendor/golang.org/x/net/http2/transport.go | 102 +- .../golang.org/x/net/http2/transport_test.go | 3796 ---- vendor/golang.org/x/net/http2/write.go | 8 +- .../x/net/http2/writesched_priority_test.go | 541 - .../x/net/http2/writesched_random_test.go | 44 - .../golang.org/x/net/http2/writesched_test.go | 125 - vendor/golang.org/x/net/http2/z_spec_test.go | 356 - vendor/golang.org/x/net/idna/example_test.go | 70 - vendor/golang.org/x/net/idna/idna_test.go | 108 - vendor/golang.org/x/net/idna/punycode_test.go | 198 - .../internal/timeseries/timeseries_test.go | 170 - .../x/net/lex/httplex/httplex_test.go | 119 - .../x/net/publicsuffix/list_test.go | 416 - vendor/golang.org/x/net/publicsuffix/table.go | 18713 ++++++++-------- .../x/net/publicsuffix/table_test.go | 16756 -------------- .../golang.org/x/net/trace/histogram_test.go | 325 - vendor/golang.org/x/net/trace/trace.go | 59 +- vendor/golang.org/x/net/trace/trace_test.go | 178 - vendor/golang.org/x/oauth2/CONTRIBUTING.md | 15 +- .../golang.org/x/oauth2/client_appengine.go | 25 - vendor/golang.org/x/oauth2/example_test.go | 89 - vendor/golang.org/x/oauth2/google/default.go | 68 +- vendor/golang.org/x/oauth2/google/doc_go19.go | 42 + .../x/oauth2/google/doc_not_go19.go | 43 + .../x/oauth2/google/example_test.go | 150 - vendor/golang.org/x/oauth2/google/go19.go | 57 + vendor/golang.org/x/oauth2/google/google.go | 12 +- .../golang.org/x/oauth2/google/google_test.go | 116 - vendor/golang.org/x/oauth2/google/jwt_test.go | 91 - vendor/golang.org/x/oauth2/google/not_go19.go | 54 + vendor/golang.org/x/oauth2/google/sdk.go | 33 +- vendor/golang.org/x/oauth2/google/sdk_test.go | 46 - .../x/oauth2/internal/client_appengine.go | 13 + vendor/golang.org/x/oauth2/internal/oauth2.go | 38 - .../x/oauth2/internal/oauth2_test.go | 61 - vendor/golang.org/x/oauth2/internal/token.go | 32 +- .../x/oauth2/internal/token_test.go | 104 - .../golang.org/x/oauth2/internal/transport.go | 46 +- .../x/oauth2/internal/transport_test.go | 38 - vendor/golang.org/x/oauth2/jws/jws_test.go | 46 - .../golang.org/x/oauth2/jwt/example_test.go | 33 - vendor/golang.org/x/oauth2/jwt/jwt.go | 5 +- vendor/golang.org/x/oauth2/jwt/jwt_test.go | 190 - vendor/golang.org/x/oauth2/oauth2.go | 45 +- vendor/golang.org/x/oauth2/oauth2_test.go | 490 - vendor/golang.org/x/oauth2/token.go | 19 +- vendor/golang.org/x/oauth2/token_test.go | 72 - vendor/golang.org/x/oauth2/transport_test.go | 108 - vendor/golang.org/x/sys/CONTRIBUTING.md | 15 +- vendor/golang.org/x/sys/unix/.gitignore | 1 + .../golang.org/x/sys/unix/affinity_linux.go | 124 + .../x/sys/unix/asm_dragonfly_amd64.s | 10 +- vendor/golang.org/x/sys/unix/asm_linux_386.s | 36 +- .../golang.org/x/sys/unix/asm_linux_amd64.s | 30 +- vendor/golang.org/x/sys/unix/asm_linux_arm.s | 35 +- .../golang.org/x/sys/unix/asm_linux_arm64.s | 30 +- .../golang.org/x/sys/unix/asm_linux_mips64x.s | 36 +- .../golang.org/x/sys/unix/asm_linux_mipsx.s | 33 +- .../golang.org/x/sys/unix/asm_linux_ppc64x.s | 30 +- .../golang.org/x/sys/unix/asm_linux_s390x.s | 28 + vendor/golang.org/x/sys/unix/cap_freebsd.go | 30 +- vendor/golang.org/x/sys/unix/creds_test.go | 136 - .../golang.org/x/sys/unix/dev_darwin_test.go | 49 - .../x/sys/unix/dev_dragonfly_test.go | 48 - .../golang.org/x/sys/unix/dev_linux_test.go | 51 - .../golang.org/x/sys/unix/dev_netbsd_test.go | 50 - .../golang.org/x/sys/unix/dev_openbsd_test.go | 52 - .../golang.org/x/sys/unix/dev_solaris_test.go | 49 - vendor/golang.org/x/sys/unix/dirent.go | 89 +- vendor/golang.org/x/sys/unix/env_unix.go | 4 + vendor/golang.org/x/sys/unix/env_unset.go | 14 - vendor/golang.org/x/sys/unix/export_test.go | 9 - .../x/sys/unix/{flock.go => fcntl.go} | 6 + ...ck_linux_32bit.go => fcntl_linux_32bit.go} | 0 vendor/golang.org/x/sys/unix/gccgo.go | 15 + vendor/golang.org/x/sys/unix/gccgo_c.c | 6 + vendor/golang.org/x/sys/unix/mkall.sh | 6 - vendor/golang.org/x/sys/unix/mkerrors.sh | 67 +- vendor/golang.org/x/sys/unix/mkpost.go | 23 +- vendor/golang.org/x/sys/unix/mksyscall.pl | 17 +- .../golang.org/x/sys/unix/mmap_unix_test.go | 35 - .../golang.org/x/sys/unix/openbsd_pledge.go | 4 +- vendor/golang.org/x/sys/unix/openbsd_test.go | 113 - vendor/golang.org/x/sys/unix/syscall.go | 11 +- vendor/golang.org/x/sys/unix/syscall_bsd.go | 49 +- .../golang.org/x/sys/unix/syscall_bsd_test.go | 62 - .../golang.org/x/sys/unix/syscall_darwin.go | 154 +- .../x/sys/unix/syscall_darwin_arm.go | 4 + .../x/sys/unix/syscall_dragonfly.go | 99 +- .../golang.org/x/sys/unix/syscall_freebsd.go | 104 +- .../x/sys/unix/syscall_freebsd_test.go | 297 - vendor/golang.org/x/sys/unix/syscall_linux.go | 142 +- .../x/sys/unix/syscall_linux_386.go | 1 + .../x/sys/unix/syscall_linux_amd64.go | 18 +- .../x/sys/unix/syscall_linux_arm.go | 1 + .../x/sys/unix/syscall_linux_arm64.go | 8 +- .../golang.org/x/sys/unix/syscall_linux_gc.go | 14 + .../x/sys/unix/syscall_linux_gccgo.go | 21 + .../x/sys/unix/syscall_linux_mips64x.go | 9 +- .../x/sys/unix/syscall_linux_mipsx.go | 4 +- .../x/sys/unix/syscall_linux_ppc64x.go | 2 + .../x/sys/unix/syscall_linux_s390x.go | 1 + .../x/sys/unix/syscall_linux_sparc64.go | 2 + .../x/sys/unix/syscall_linux_test.go | 230 - .../golang.org/x/sys/unix/syscall_netbsd.go | 80 +- .../golang.org/x/sys/unix/syscall_no_getwd.go | 11 - .../golang.org/x/sys/unix/syscall_openbsd.go | 104 +- .../x/sys/unix/syscall_openbsd_amd64.go | 4 + .../golang.org/x/sys/unix/syscall_solaris.go | 49 +- .../x/sys/unix/syscall_solaris_amd64.go | 5 - .../x/sys/unix/syscall_solaris_test.go | 34 - vendor/golang.org/x/sys/unix/syscall_test.go | 50 - vendor/golang.org/x/sys/unix/syscall_unix.go | 101 + .../x/sys/unix/syscall_unix_test.go | 398 - vendor/golang.org/x/sys/unix/timestruct.go | 20 + vendor/golang.org/x/sys/unix/types_darwin.go | 5 + .../golang.org/x/sys/unix/types_dragonfly.go | 11 + vendor/golang.org/x/sys/unix/types_freebsd.go | 11 + vendor/golang.org/x/sys/unix/types_netbsd.go | 22 + vendor/golang.org/x/sys/unix/types_openbsd.go | 11 + .../x/sys/unix/zerrors_darwin_386.go | 299 +- .../x/sys/unix/zerrors_darwin_amd64.go | 299 +- .../x/sys/unix/zerrors_darwin_arm.go | 299 +- .../x/sys/unix/zerrors_darwin_arm64.go | 299 +- .../x/sys/unix/zerrors_dragonfly_amd64.go | 288 +- .../x/sys/unix/zerrors_freebsd_386.go | 277 +- .../x/sys/unix/zerrors_freebsd_amd64.go | 277 +- .../x/sys/unix/zerrors_freebsd_arm.go | 277 +- .../x/sys/unix/zerrors_linux_386.go | 650 +- .../x/sys/unix/zerrors_linux_amd64.go | 649 +- .../x/sys/unix/zerrors_linux_arm.go | 651 +- .../x/sys/unix/zerrors_linux_arm64.go | 650 +- .../x/sys/unix/zerrors_linux_mips.go | 654 +- .../x/sys/unix/zerrors_linux_mips64.go | 654 +- .../x/sys/unix/zerrors_linux_mips64le.go | 654 +- .../x/sys/unix/zerrors_linux_mipsle.go | 654 +- .../x/sys/unix/zerrors_linux_ppc64.go | 650 +- .../x/sys/unix/zerrors_linux_ppc64le.go | 650 +- .../x/sys/unix/zerrors_linux_s390x.go | 648 +- .../x/sys/unix/zerrors_netbsd_386.go | 278 +- .../x/sys/unix/zerrors_netbsd_amd64.go | 278 +- .../x/sys/unix/zerrors_netbsd_arm.go | 278 +- .../x/sys/unix/zerrors_openbsd_386.go | 268 +- .../x/sys/unix/zerrors_openbsd_amd64.go | 515 +- .../x/sys/unix/zerrors_openbsd_arm.go | 268 +- .../x/sys/unix/zerrors_solaris_amd64.go | 336 +- .../x/sys/unix/zsyscall_darwin_386.go | 92 + .../x/sys/unix/zsyscall_darwin_amd64.go | 92 + .../x/sys/unix/zsyscall_darwin_arm.go | 94 +- .../x/sys/unix/zsyscall_darwin_arm64.go | 92 + .../x/sys/unix/zsyscall_dragonfly_amd64.go | 47 + .../x/sys/unix/zsyscall_freebsd_386.go | 49 + .../x/sys/unix/zsyscall_freebsd_amd64.go | 49 + .../x/sys/unix/zsyscall_freebsd_arm.go | 49 + .../x/sys/unix/zsyscall_linux_386.go | 61 +- .../x/sys/unix/zsyscall_linux_amd64.go | 87 +- .../x/sys/unix/zsyscall_linux_arm.go | 61 +- .../x/sys/unix/zsyscall_linux_arm64.go | 56 +- .../x/sys/unix/zsyscall_linux_mips.go | 77 +- .../x/sys/unix/zsyscall_linux_mips64.go | 71 +- .../x/sys/unix/zsyscall_linux_mips64le.go | 71 +- .../x/sys/unix/zsyscall_linux_mipsle.go | 77 +- .../x/sys/unix/zsyscall_linux_ppc64.go | 71 +- .../x/sys/unix/zsyscall_linux_ppc64le.go | 71 +- .../x/sys/unix/zsyscall_linux_s390x.go | 61 +- .../x/sys/unix/zsyscall_linux_sparc64.go | 10 + .../x/sys/unix/zsyscall_netbsd_386.go | 57 + .../x/sys/unix/zsyscall_netbsd_amd64.go | 57 + .../x/sys/unix/zsyscall_netbsd_arm.go | 57 + .../x/sys/unix/zsyscall_openbsd_386.go | 68 + .../x/sys/unix/zsyscall_openbsd_amd64.go | 68 + .../x/sys/unix/zsyscall_openbsd_arm.go | 68 + .../x/sys/unix/zsyscall_solaris_amd64.go | 39 + .../x/sys/unix/zsysctl_openbsd_amd64.go | 51 +- .../x/sys/unix/zsysnum_linux_ppc64.go | 3 + .../x/sys/unix/zsysnum_linux_ppc64le.go | 3 + .../x/sys/unix/zsysnum_linux_s390x.go | 45 +- .../x/sys/unix/zsysnum_openbsd_amd64.go | 24 +- .../x/sys/unix/zsysnum_solaris_amd64.go | 13 - .../x/sys/unix/ztypes_darwin_386.go | 120 +- .../x/sys/unix/ztypes_darwin_amd64.go | 166 +- .../x/sys/unix/ztypes_darwin_arm.go | 120 +- .../x/sys/unix/ztypes_darwin_arm64.go | 166 +- .../x/sys/unix/ztypes_dragonfly_amd64.go | 112 +- .../x/sys/unix/ztypes_freebsd_386.go | 12 + .../x/sys/unix/ztypes_freebsd_amd64.go | 12 + .../x/sys/unix/ztypes_freebsd_arm.go | 12 + .../golang.org/x/sys/unix/ztypes_linux_386.go | 1330 +- .../x/sys/unix/ztypes_linux_amd64.go | 1334 +- .../golang.org/x/sys/unix/ztypes_linux_arm.go | 1348 +- .../x/sys/unix/ztypes_linux_arm64.go | 1336 +- .../x/sys/unix/ztypes_linux_mips.go | 1308 +- .../x/sys/unix/ztypes_linux_mips64.go | 1332 +- .../x/sys/unix/ztypes_linux_mips64le.go | 1332 +- .../x/sys/unix/ztypes_linux_mipsle.go | 1308 +- .../x/sys/unix/ztypes_linux_ppc64.go | 1342 +- .../x/sys/unix/ztypes_linux_ppc64le.go | 1342 +- .../x/sys/unix/ztypes_linux_s390x.go | 1242 +- .../x/sys/unix/ztypes_linux_sparc64.go | 208 +- .../x/sys/unix/ztypes_netbsd_386.go | 21 + .../x/sys/unix/ztypes_netbsd_amd64.go | 21 + .../x/sys/unix/ztypes_netbsd_arm.go | 21 + .../x/sys/unix/ztypes_openbsd_386.go | 12 + .../x/sys/unix/ztypes_openbsd_amd64.go | 103 +- .../x/sys/unix/ztypes_openbsd_arm.go | 12 + .../x/sys/unix/ztypes_solaris_amd64.go | 174 +- .../x/sys/windows/asm_windows_386.s | 4 +- .../x/sys/windows/asm_windows_amd64.s | 2 +- vendor/golang.org/x/sys/windows/env_unset.go | 15 - .../golang.org/x/sys/windows/env_windows.go | 4 + .../x/sys/windows/security_windows.go | 41 + vendor/golang.org/x/sys/windows/service.go | 1 + vendor/golang.org/x/sys/windows/syscall.go | 3 + .../golang.org/x/sys/windows/syscall_test.go | 53 - .../x/sys/windows/syscall_windows.go | 62 +- .../x/sys/windows/syscall_windows_test.go | 107 - .../golang.org/x/sys/windows/types_windows.go | 23 +- .../x/sys/windows/zsyscall_windows.go | 272 + vendor/golang.org/x/text/README.md | 14 +- .../x/text/collate/build/builder_test.go | 290 - .../x/text/collate/build/colelem_test.go | 215 - .../x/text/collate/build/contract_test.go | 266 - .../x/text/collate/build/order_test.go | 229 - .../x/text/collate/build/trie_test.go | 107 - .../golang.org/x/text/collate/collate_test.go | 482 - .../golang.org/x/text/collate/export_test.go | 51 - .../golang.org/x/text/collate/option_test.go | 209 - vendor/golang.org/x/text/collate/reg_test.go | 230 - vendor/golang.org/x/text/collate/sort_test.go | 55 - .../golang.org/x/text/collate/table_test.go | 291 - .../x/text/encoding/charmap/charmap_test.go | 258 - .../x/text/encoding/encoding_test.go | 290 - .../x/text/encoding/example_test.go | 42 - .../text/encoding/htmlindex/htmlindex_test.go | 144 - .../x/text/encoding/japanese/all_test.go | 248 - .../x/text/encoding/korean/all_test.go | 94 - .../encoding/simplifiedchinese/all_test.go | 143 - .../encoding/traditionalchinese/all_test.go | 114 - .../x/text/encoding/unicode/unicode_test.go | 499 - vendor/golang.org/x/text/gen.go | 9 +- .../x/text/internal/colltab/collate_test.go | 121 - .../x/text/internal/colltab/collelem_test.go | 183 - .../x/text/internal/colltab/colltab_test.go | 64 - .../x/text/internal/colltab/contract_test.go | 131 - .../x/text/internal/colltab/iter_test.go | 63 - .../x/text/internal/colltab/numeric_test.go | 159 - .../x/text/internal/colltab/trie_test.go | 106 - .../x/text/internal/colltab/weighter_test.go | 42 - vendor/golang.org/x/text/internal/gen/code.go | 24 +- vendor/golang.org/x/text/internal/gen/gen.go | 64 +- vendor/golang.org/x/text/internal/gen_test.go | 38 - .../x/text/internal/internal_test.go | 38 - .../golang.org/x/text/internal/match_test.go | 56 - vendor/golang.org/x/text/internal/tables.go | 171 +- .../x/text/internal/tag/tag_test.go | 67 - .../x/text/internal/triegen/data_test.go | 875 - .../internal/triegen/example_compact_test.go | 71 - .../x/text/internal/triegen/example_test.go | 148 - .../x/text/internal/triegen/gen_test.go | 68 - .../x/text/internal/ucd/example_test.go | 81 - .../x/text/internal/ucd/ucd_test.go | 105 - .../x/text/language/coverage_test.go | 154 - .../x/text/language/examples_test.go | 413 - vendor/golang.org/x/text/language/gen.go | 10 +- .../golang.org/x/text/language/gen_index.go | 2 +- .../x/text/language/httpexample_test.go | 48 - vendor/golang.org/x/text/language/index.go | 1372 +- vendor/golang.org/x/text/language/language.go | 20 + .../x/text/language/language_test.go | 878 - .../golang.org/x/text/language/lookup_test.go | 457 - .../golang.org/x/text/language/match_test.go | 505 - .../golang.org/x/text/language/parse_test.go | 517 - vendor/golang.org/x/text/language/tables.go | 4877 ++-- vendor/golang.org/x/text/runes/cond_test.go | 282 - .../golang.org/x/text/runes/example_test.go | 60 - vendor/golang.org/x/text/runes/runes_test.go | 664 - .../x/text/secure/bidirule/bench_test.go | 54 - .../x/text/secure/bidirule/bidirule.go | 4 - .../x/text/secure/bidirule/bidirule10.0.0.go | 11 + .../x/text/secure/bidirule/bidirule9.0.0.go | 14 + .../x/text/secure/bidirule/bidirule_test.go | 851 - .../x/text/transform/examples_test.go | 37 - .../x/text/transform/transform_test.go | 1317 -- .../x/text/unicode/bidi/core_test.go | 224 - vendor/golang.org/x/text/unicode/bidi/gen.go | 2 +- .../x/text/unicode/bidi/ranges_test.go | 53 - .../bidi/{tables.go => tables10.0.0.go} | 2 + .../x/text/unicode/bidi/tables9.0.0.go | 1781 ++ .../x/text/unicode/bidi/tables_test.go | 82 - .../x/text/unicode/cldr/cldr_test.go | 27 - .../x/text/unicode/cldr/collate_test.go | 275 - .../x/text/unicode/cldr/data_test.go | 186 - .../x/text/unicode/cldr/examples_test.go | 21 - .../x/text/unicode/cldr/resolve_test.go | 368 - .../x/text/unicode/cldr/slice_test.go | 175 - vendor/golang.org/x/text/unicode/cldr/xml.go | 9 +- .../x/text/unicode/norm/composition_test.go | 130 - .../x/text/unicode/norm/example_iter_test.go | 82 - .../x/text/unicode/norm/example_test.go | 27 - .../x/text/unicode/norm/forminfo_test.go | 54 - .../x/text/unicode/norm/iter_test.go | 98 - .../x/text/unicode/norm/maketables.go | 4 +- .../x/text/unicode/norm/normalize_test.go | 1287 -- .../x/text/unicode/norm/readwriter_test.go | 56 - .../norm/{tables.go => tables10.0.0.go} | 2 + .../x/text/unicode/norm/tables9.0.0.go | 7633 +++++++ .../x/text/unicode/norm/transform_test.go | 101 - .../x/text/unicode/norm/ucd_test.go | 275 - .../x/text/unicode/rangetable/gen.go | 2 +- .../x/text/unicode/rangetable/merge_test.go | 184 - .../unicode/rangetable/rangetable_test.go | 55 - .../rangetable/{tables.go => tables10.0.0.go} | 2 + .../x/text/unicode/rangetable/tables9.0.0.go | 5737 +++++ vendor/golang.org/x/time/rate/rate.go | 8 +- vendor/golang.org/x/time/rate/rate_test.go | 449 - .../appengine/appengine_test.go | 49 - .../appengine/internal/api_race_test.go | 9 - .../appengine/internal/api_test.go | 467 - .../appengine/internal/app_id_test.go | 34 - .../appengine/internal/internal_vm_test.go | 60 - .../appengine/internal/net_test.go | 58 - .../appengine/namespace_test.go | 39 - .../googleapis/rpc/status/status.pb.go | 51 +- vendor/google.golang.org/grpc/.travis.yml | 14 +- vendor/google.golang.org/grpc/CONTRIBUTING.md | 6 +- vendor/google.golang.org/grpc/Makefile | 13 +- vendor/google.golang.org/grpc/README.md | 4 +- vendor/google.golang.org/grpc/backoff.go | 14 +- vendor/google.golang.org/grpc/balancer.go | 16 +- .../grpc/balancer/balancer.go | 44 +- .../grpc/balancer/base/balancer.go | 208 + .../grpc/balancer/base/base.go | 52 + .../grpc/balancer/roundrobin/roundrobin.go | 79 + .../grpc/balancer_conn_wrappers.go | 68 +- .../google.golang.org/grpc/balancer_test.go | 798 - .../grpc/balancer_v1_wrapper.go | 45 +- vendor/google.golang.org/grpc/call.go | 308 +- vendor/google.golang.org/grpc/call_test.go | 292 - .../google.golang.org/grpc/channelz/funcs.go | 573 + .../google.golang.org/grpc/channelz/types.go | 418 + vendor/google.golang.org/grpc/clientconn.go | 947 +- .../google.golang.org/grpc/clientconn_test.go | 390 - vendor/google.golang.org/grpc/codec.go | 88 +- .../grpc/codec_benchmark_test.go | 100 - vendor/google.golang.org/grpc/codec_test.go | 128 - .../grpc/codes/code_string.go | 66 +- vendor/google.golang.org/grpc/codes/codes.go | 66 +- .../grpc/credentials/credentials.go | 31 +- .../grpc/credentials/credentials_test.go | 206 - .../grpc/encoding/encoding.go | 118 + .../grpc/encoding/proto/proto.go | 110 + .../{naming/go18_test.go => envconfig.go} | 34 +- vendor/google.golang.org/grpc/go16.go | 70 + vendor/google.golang.org/grpc/go17.go | 71 + vendor/google.golang.org/grpc/grpclb.go | 821 +- .../grpclb/grpc_lb_v1/messages/messages.pb.go | 410 +- .../grpclb/grpc_lb_v1/messages/messages.proto | 2 +- .../grpc/grpclb/grpclb_test.go | 891 - .../google.golang.org/grpc/grpclb_picker.go | 159 + .../grpc/grpclb_remote_balancer.go | 266 + vendor/google.golang.org/grpc/grpclb_util.go | 214 + .../google.golang.org/grpc/grpclog/grpclog.go | 3 + .../google.golang.org/grpc/grpclog/logger.go | 2 + .../grpc/grpclog/loggerv2_test.go | 62 - vendor/google.golang.org/grpc/interceptor.go | 4 +- .../grpc/internal/internal.go | 7 - .../grpc/metadata/metadata.go | 89 +- .../grpc/metadata/metadata_test.go | 71 - .../grpc/naming/dns_resolver.go | 6 +- .../grpc/naming/dns_resolver_test.go | 315 - vendor/google.golang.org/grpc/naming/go17.go | 2 +- .../google.golang.org/grpc/naming/naming.go | 12 +- .../google.golang.org/grpc/picker_wrapper.go | 198 +- .../grpc/picker_wrapper_test.go | 160 - vendor/google.golang.org/grpc/pickfirst.go | 17 +- .../google.golang.org/grpc/pickfirst_test.go | 352 - vendor/google.golang.org/grpc/proxy.go | 3 +- vendor/google.golang.org/grpc/proxy_test.go | 182 - .../grpc/resolver/dns/dns_resolver.go | 379 + .../go17_test.go => resolver/dns/go17.go} | 23 +- .../{backoff_test.go => resolver/dns/go18.go} | 18 +- .../grpc/resolver/passthrough/passthrough.go | 57 + .../grpc/resolver/resolver.go | 47 +- .../grpc/resolver_conn_wrapper.go | 67 +- .../grpc/resolver_conn_wrapper_test.go | 47 - vendor/google.golang.org/grpc/rpc_util.go | 571 +- .../google.golang.org/grpc/rpc_util_test.go | 237 - vendor/google.golang.org/grpc/server.go | 553 +- vendor/google.golang.org/grpc/server_test.go | 102 - .../google.golang.org/grpc/service_config.go | 233 + vendor/google.golang.org/grpc/stats/stats.go | 2 + .../grpc/stats/stats_test.go | 1265 -- .../google.golang.org/grpc/status/status.go | 31 +- .../grpc/status/status_test.go | 261 - vendor/google.golang.org/grpc/stream.go | 642 +- .../grpc/transport/bdp_estimator.go | 9 +- .../grpc/transport/controlbuf.go | 769 + .../transport/{control.go => flowcontrol.go} | 247 +- .../google.golang.org/grpc/transport/go16.go | 51 + .../google.golang.org/grpc/transport/go17.go | 52 + .../grpc/transport/handler_server.go | 109 +- .../grpc/transport/handler_server_test.go | 462 - .../grpc/transport/http2_client.go | 1112 +- .../grpc/transport/http2_server.go | 790 +- .../grpc/transport/http_util.go | 147 +- .../grpc/transport/http_util_test.go | 175 - .../grpc/transport/transport.go | 408 +- .../grpc/transport/transport_test.go | 2158 -- vendor/google.golang.org/grpc/vet.sh | 37 +- .../fsnotify/fsnotify.v1/example_test.go | 42 - .../fsnotify/fsnotify.v1/fsnotify_test.go | 70 - .../fsnotify.v1/inotify_poller_test.go | 229 - .../fsnotify/fsnotify.v1/inotify_test.go | 449 - .../fsnotify.v1/integration_darwin_test.go | 147 - .../fsnotify/fsnotify.v1/integration_test.go | 1237 - .../pool.v3/batch_limited_test.go | 172 - .../pool.v3/batch_unlimited_test.go | 172 - .../pool.v3/limited_pool_benchmarks_test.go | 185 - .../pool.v3/limited_pool_test.go | 177 - .../go-playground/pool.v3/pool_test.go | 36 - .../pool.v3/unlimited_pool_benchmarks_test.go | 185 - .../pool.v3/unlimited_pool_test.go | 194 - vendor/gopkg.in/inf.v0/benchmark_test.go | 210 - vendor/gopkg.in/inf.v0/dec.go | 2 +- vendor/gopkg.in/inf.v0/dec_go1_2_test.go | 33 - vendor/gopkg.in/inf.v0/dec_internal_test.go | 40 - vendor/gopkg.in/inf.v0/dec_test.go | 379 - vendor/gopkg.in/inf.v0/example_test.go | 62 - .../gopkg.in/inf.v0/rounder_example_test.go | 72 - vendor/gopkg.in/inf.v0/rounder_test.go | 109 - .../square/go-jose.v2/asymmetric_test.go | 504 - .../square/go-jose.v2/cipher/cbc_hmac_test.go | 498 - .../go-jose.v2/cipher/concat_kdf_test.go | 150 - .../square/go-jose.v2/cipher/ecdh_es_test.go | 115 - .../square/go-jose.v2/cipher/key_wrap_test.go | 133 - .../square/go-jose.v2/crypter_test.go | 838 - vendor/gopkg.in/square/go-jose.v2/doc_test.go | 201 - .../square/go-jose.v2/encoding_test.go | 122 - .../square/go-jose.v2/json/bench_test.go | 223 - .../square/go-jose.v2/json/decode_test.go | 1474 -- .../square/go-jose.v2/json/encode_test.go | 538 - .../square/go-jose.v2/json/number_test.go | 133 - .../square/go-jose.v2/json/scanner_test.go | 316 - .../square/go-jose.v2/json/stream_test.go | 354 - .../square/go-jose.v2/json/tagkey_test.go | 115 - .../square/go-jose.v2/json/tags_test.go | 28 - vendor/gopkg.in/square/go-jose.v2/jwe_test.go | 543 - vendor/gopkg.in/square/go-jose.v2/jwk_test.go | 715 - vendor/gopkg.in/square/go-jose.v2/jws_test.go | 616 - .../square/go-jose.v2/jwt/builder_test.go | 507 - .../square/go-jose.v2/jwt/claims_test.go | 80 - .../square/go-jose.v2/jwt/example_test.go | 340 - .../square/go-jose.v2/jwt/jwt_test.go | 137 - .../square/go-jose.v2/jwt/validation_test.go | 92 - .../square/go-jose.v2/signing_test.go | 523 - .../square/go-jose.v2/symmetric_test.go | 131 - .../gopkg.in/square/go-jose.v2/utils_test.go | 70 - vendor/gopkg.in/yaml.v2/.travis.yml | 3 + .../doc.go => vendor/gopkg.in/yaml.v2/NOTICE | 7 +- vendor/gopkg.in/yaml.v2/README.md | 4 +- vendor/gopkg.in/yaml.v2/apic.go | 55 +- vendor/gopkg.in/yaml.v2/decode.go | 240 +- vendor/gopkg.in/yaml.v2/decode_test.go | 1017 - vendor/gopkg.in/yaml.v2/emitterc.go | 11 +- vendor/gopkg.in/yaml.v2/encode.go | 136 +- vendor/gopkg.in/yaml.v2/encode_test.go | 501 - .../gopkg.in/yaml.v2/example_embedded_test.go | 41 - vendor/gopkg.in/yaml.v2/go.mod | 5 + vendor/gopkg.in/yaml.v2/readerc.go | 20 +- vendor/gopkg.in/yaml.v2/resolve.go | 80 +- vendor/gopkg.in/yaml.v2/scannerc.go | 29 +- vendor/gopkg.in/yaml.v2/sorter.go | 9 + vendor/gopkg.in/yaml.v2/suite_test.go | 12 - vendor/gopkg.in/yaml.v2/writerc.go | 65 +- vendor/gopkg.in/yaml.v2/yaml.go | 125 +- vendor/gopkg.in/yaml.v2/yamlh.go | 30 +- .../api/admissionregistration/v1alpha1/BUILD | 44 - .../api/admissionregistration/v1beta1/BUILD | 44 - vendor/k8s.io/api/apps/v1/BUILD | 43 - vendor/k8s.io/api/apps/v1beta1/BUILD | 47 - vendor/k8s.io/api/apps/v1beta2/BUILD | 47 - vendor/k8s.io/api/authentication/v1/BUILD | 46 - .../k8s.io/api/authentication/v1beta1/BUILD | 45 - vendor/k8s.io/api/authorization/v1/BUILD | 45 - vendor/k8s.io/api/authorization/v1beta1/BUILD | 45 - vendor/k8s.io/api/autoscaling/v1/BUILD | 46 - vendor/k8s.io/api/autoscaling/v2beta1/BUILD | 46 - vendor/k8s.io/api/batch/v1/BUILD | 45 - vendor/k8s.io/api/batch/v1beta1/BUILD | 46 - vendor/k8s.io/api/batch/v2alpha1/BUILD | 46 - vendor/k8s.io/api/certificates/v1beta1/BUILD | 45 - vendor/k8s.io/api/core/v1/BUILD | 64 - vendor/k8s.io/api/core/v1/taint_test.go | 122 - vendor/k8s.io/api/core/v1/toleration_test.go | 123 - vendor/k8s.io/api/core/v1/types.go | 6 + vendor/k8s.io/api/events/v1beta1/BUILD | 42 - vendor/k8s.io/api/extensions/v1beta1/BUILD | 49 - vendor/k8s.io/api/networking/v1/BUILD | 46 - vendor/k8s.io/api/policy/v1beta1/BUILD | 47 - vendor/k8s.io/api/rbac/v1/BUILD | 44 - vendor/k8s.io/api/rbac/v1alpha1/BUILD | 44 - vendor/k8s.io/api/rbac/v1beta1/BUILD | 44 - vendor/k8s.io/api/scheduling/v1alpha1/BUILD | 44 - vendor/k8s.io/api/settings/v1alpha1/BUILD | 45 - vendor/k8s.io/api/storage/v1/BUILD | 43 - vendor/k8s.io/api/storage/v1alpha1/BUILD | 42 - vendor/k8s.io/api/storage/v1beta1/BUILD | 43 - vendor/k8s.io/apiextensions-apiserver/BUILD | 55 - .../pkg/apis/apiextensions/BUILD | 52 - .../pkg/apis/apiextensions/helpers_test.go | 90 - .../pkg/apis/apiextensions/v1beta1/BUILD | 68 - .../apiextensions/v1beta1/conversion_test.go | 113 - .../apiextensions/v1beta1/marshal_test.go | 150 - .../pkg/client/clientset/clientset/BUILD | 40 - .../client/clientset/clientset/scheme/BUILD | 35 - .../typed/apiextensions/v1beta1/BUILD | 42 - .../pkg/features/BUILD | 26 - .../apimachinery/pkg/api/equality/BUILD | 32 - .../k8s.io/apimachinery/pkg/api/errors/BUILD | 47 - .../pkg/api/errors/errors_test.go | 222 - vendor/k8s.io/apimachinery/pkg/api/meta/BUILD | 72 - .../apimachinery/pkg/api/meta/meta_test.go | 51 - .../pkg/api/meta/multirestmapper_test.go | 391 - .../pkg/api/meta/priority_test.go | 346 - .../pkg/api/meta/restmapper_test.go | 751 - .../apimachinery/pkg/api/resource/BUILD | 69 - .../pkg/api/resource/amount_test.go | 133 - .../pkg/api/resource/math_test.go | 211 - .../pkg/api/resource/quantity_example_test.go | 59 - .../pkg/api/resource/quantity_proto_test.go | 103 - .../pkg/api/resource/quantity_test.go | 1368 -- .../pkg/api/resource/scale_int_test.go | 85 - .../apimachinery/pkg/api/validation/BUILD | 53 - .../pkg/api/validation/objectmeta_test.go | 500 - .../apimachinery/pkg/apimachinery/BUILD | 45 - .../pkg/apimachinery/announced/BUILD | 45 - .../apimachinery/announced/announced_test.go | 64 - .../pkg/apimachinery/registered/BUILD | 43 - .../registered/registered_test.go | 71 - .../pkg/apimachinery/types_test.go | 43 - .../pkg/apis/meta/internalversion/BUILD | 59 - .../meta/internalversion/register_test.go | 89 - .../meta/internalversion/roundtrip_test.go | 28 - .../apimachinery/pkg/apis/meta/v1/BUILD | 101 - .../pkg/apis/meta/v1/controller_ref_test.go | 133 - .../pkg/apis/meta/v1/conversion_test.go | 49 - .../pkg/apis/meta/v1/duration_test.go | 153 - .../pkg/apis/meta/v1/group_version_test.go | 78 - .../pkg/apis/meta/v1/helpers_test.go | 154 - .../pkg/apis/meta/v1/labels_test.go | 123 - .../pkg/apis/meta/v1/micro_time_test.go | 139 - .../pkg/apis/meta/v1/time_test.go | 197 - .../pkg/apis/meta/v1/types_test.go | 134 - .../pkg/apis/meta/v1/unstructured/BUILD | 53 - .../apis/meta/v1/unstructured/helpers_test.go | 60 - .../v1/unstructured/unstructured_list_test.go | 86 - .../pkg/apis/meta/v1/validation/BUILD | 38 - .../meta/v1/validation/validation_test.go | 94 - .../apimachinery/pkg/apis/meta/v1beta1/BUILD | 45 - .../k8s.io/apimachinery/pkg/conversion/BUILD | 49 - .../pkg/conversion/converter_test.go | 826 - .../pkg/conversion/helper_test.go | 38 - .../pkg/conversion/queryparams/BUILD | 39 - .../conversion/queryparams/convert_test.go | 215 - vendor/k8s.io/apimachinery/pkg/fields/BUILD | 41 - .../apimachinery/pkg/fields/fields_test.go | 57 - .../apimachinery/pkg/fields/selector_test.go | 397 - vendor/k8s.io/apimachinery/pkg/labels/BUILD | 50 - .../apimachinery/pkg/labels/labels_test.go | 231 - .../apimachinery/pkg/labels/selector_test.go | 575 - vendor/k8s.io/apimachinery/pkg/runtime/BUILD | 98 - .../pkg/runtime/conversion_test.go | 115 - .../pkg/runtime/converter_test.go | 597 - .../apimachinery/pkg/runtime/embedded_test.go | 256 - .../pkg/runtime/extension_test.go | 113 - .../apimachinery/pkg/runtime/schema/BUILD | 43 - .../pkg/runtime/schema/group_version_test.go | 136 - .../apimachinery/pkg/runtime/scheme_test.go | 1035 - .../apimachinery/pkg/runtime/serializer/BUILD | 64 - .../pkg/runtime/serializer/codec_test.go | 339 - .../pkg/runtime/serializer/json/BUILD | 55 - .../pkg/runtime/serializer/json/json_test.go | 293 - .../pkg/runtime/serializer/json/meta_test.go | 45 - .../pkg/runtime/serializer/protobuf/BUILD | 35 - .../pkg/runtime/serializer/recognizer/BUILD | 32 - .../pkg/runtime/serializer/streaming/BUILD | 41 - .../serializer/streaming/streaming_test.go | 84 - .../pkg/runtime/serializer/versioning/BUILD | 41 - .../serializer/versioning/versioning_test.go | 381 - .../pkg/runtime/swagger_doc_generator_test.go | 43 - .../k8s.io/apimachinery/pkg/selection/BUILD | 25 - vendor/k8s.io/apimachinery/pkg/types/BUILD | 31 - .../k8s.io/apimachinery/pkg/util/cache/BUILD | 43 - .../apimachinery/pkg/util/cache/cache_test.go | 90 - .../pkg/util/cache/lruexpirecache_test.go | 68 - .../k8s.io/apimachinery/pkg/util/clock/BUILD | 32 - .../apimachinery/pkg/util/clock/clock_test.go | 184 - .../k8s.io/apimachinery/pkg/util/diff/BUILD | 36 - .../apimachinery/pkg/util/diff/diff_test.go | 96 - .../k8s.io/apimachinery/pkg/util/errors/BUILD | 35 - .../pkg/util/errors/errors_test.go | 368 - .../k8s.io/apimachinery/pkg/util/framer/BUILD | 32 - .../pkg/util/framer/framer_test.go | 176 - .../apimachinery/pkg/util/httpstream/BUILD | 38 - .../pkg/util/httpstream/httpstream_test.go | 125 - .../pkg/util/httpstream/spdy/BUILD | 56 - .../util/httpstream/spdy/connection_test.go | 164 - .../util/httpstream/spdy/roundtripper_test.go | 529 - .../pkg/util/httpstream/spdy/upgrade_test.go | 93 - .../k8s.io/apimachinery/pkg/util/intstr/BUILD | 47 - .../pkg/util/intstr/intstr_test.go | 176 - .../k8s.io/apimachinery/pkg/util/json/BUILD | 32 - .../apimachinery/pkg/util/json/json_test.go | 319 - .../apimachinery/pkg/util/mergepatch/BUILD | 39 - .../pkg/util/mergepatch/util_test.go | 138 - vendor/k8s.io/apimachinery/pkg/util/net/BUILD | 50 - .../k8s.io/apimachinery/pkg/util/net/http.go | 3 + .../apimachinery/pkg/util/net/http_test.go | 282 - .../pkg/util/net/interface_test.go | 725 - .../pkg/util/net/port_range_test.go | 69 - .../pkg/util/net/port_split_test.go | 121 - .../apimachinery/pkg/util/net/util_test.go | 68 - .../apimachinery/pkg/util/remotecommand/BUILD | 26 - .../apimachinery/pkg/util/runtime/BUILD | 33 - .../pkg/util/runtime/runtime_test.go | 71 - .../k8s.io/apimachinery/pkg/util/sets/BUILD | 71 - .../apimachinery/pkg/util/sets/set_test.go | 270 - .../pkg/util/strategicpatch/BUILD | 60 - .../pkg/util/strategicpatch/patch_test.go | 6763 ------ .../k8s.io/apimachinery/pkg/util/uuid/BUILD | 29 - .../apimachinery/pkg/util/validation/BUILD | 37 - .../pkg/util/validation/field/BUILD | 42 - .../pkg/util/validation/field/errors_test.go | 175 - .../pkg/util/validation/field/path_test.go | 123 - .../pkg/util/validation/validation_test.go | 513 - .../k8s.io/apimachinery/pkg/util/wait/BUILD | 37 - .../apimachinery/pkg/util/wait/wait_test.go | 501 - .../k8s.io/apimachinery/pkg/util/yaml/BUILD | 36 - .../pkg/util/yaml/decoder_test.go | 405 - vendor/k8s.io/apimachinery/pkg/version/BUILD | 28 - vendor/k8s.io/apimachinery/pkg/watch/BUILD | 69 - .../apimachinery/pkg/watch/filter_test.go | 84 - .../k8s.io/apimachinery/pkg/watch/mux_test.go | 176 - .../pkg/watch/streamwatcher_test.go | 68 - .../apimachinery/pkg/watch/until_test.go | 172 - .../apimachinery/pkg/watch/watch_test.go | 137 - .../third_party/forked/golang/json/BUILD | 32 - .../forked/golang/json/fields_test.go | 30 - .../third_party/forked/golang/netutil/BUILD | 25 - .../third_party/forked/golang/reflect/BUILD | 32 - .../forked/golang/reflect/deep_equal_test.go | 137 - .../pkg/authentication/authenticator/BUILD | 26 - .../pkg/authentication/serviceaccount/BUILD | 33 - .../serviceaccount/util_test.go | 82 - .../apiserver/pkg/authentication/user/BUILD | 28 - vendor/k8s.io/apiserver/pkg/features/BUILD | 26 - vendor/k8s.io/apiserver/pkg/server/BUILD | 172 - .../pkg/server/config_selfclient_test.go | 68 - .../apiserver/pkg/server/config_test.go | 153 - .../pkg/server/genericapiserver_test.go | 581 - .../k8s.io/apiserver/pkg/server/healthz/BUILD | 36 - .../pkg/server/healthz/healthz_test.go | 112 - .../k8s.io/apiserver/pkg/util/feature/BUILD | 40 - .../pkg/util/feature/feature_gate_test.go | 191 - vendor/k8s.io/apiserver/pkg/util/logs/BUILD | 30 - .../discovery/discovery_client_test.go | 864 - .../discovery/fake/discovery_test.go | 46 - .../discovery/helper_blackbox_test.go | 184 - .../client-go/discovery/restmapper_test.go | 384 - .../v1beta1/daemonset_expansion_test.go | 152 - .../pkg/client/auth/azure/azure_test.go | 133 - .../plugin/pkg/client/auth/exec/exec_test.go | 413 - .../plugin/pkg/client/auth/gcp/gcp_test.go | 497 - .../plugin/pkg/client/auth/oidc/oidc_test.go | 138 - .../client/auth/openstack/openstack_test.go | 116 - vendor/k8s.io/client-go/rest/client_test.go | 343 - vendor/k8s.io/client-go/rest/config_test.go | 376 - vendor/k8s.io/client-go/rest/plugin_test.go | 311 - vendor/k8s.io/client-go/rest/request_test.go | 1789 -- .../k8s.io/client-go/rest/url_utils_test.go | 61 - .../k8s.io/client-go/rest/urlbackoff_test.go | 79 - .../client-go/rest/watch/decoder_test.go | 123 - .../client-go/rest/watch/encoder_test.go | 84 - .../k8s.io/client-go/testing/fixture_test.go | 192 - .../client-go/tools/auth/clientauth_test.go | 69 - .../client-go/tools/cache/controller_test.go | 405 - .../client-go/tools/cache/delta_fifo_test.go | 492 - .../tools/cache/expiration_cache_test.go | 189 - .../k8s.io/client-go/tools/cache/fifo_test.go | 280 - .../k8s.io/client-go/tools/cache/heap_test.go | 382 - .../client-go/tools/cache/index_test.go | 163 - .../tools/cache/mutation_detector_test.go | 81 - .../tools/cache/processor_listener_test.go | 58 - .../client-go/tools/cache/reflector_test.go | 389 - .../tools/cache/shared_informer_test.go | 265 - .../client-go/tools/cache/store_test.go | 156 - .../tools/cache/undelta_store_test.go | 131 - .../tools/clientcmd/api/helpers_test.go | 301 - .../tools/clientcmd/api/types_test.go | 135 - .../tools/clientcmd/client_config_test.go | 528 - .../client-go/tools/clientcmd/loader_test.go | 594 - .../clientcmd/merged_client_builder_test.go | 328 - .../tools/clientcmd/overrides_test.go | 50 - .../tools/clientcmd/validation_test.go | 574 - .../leaderelection/leaderelection_test.go | 292 - .../client-go/tools/pager/pager_test.go | 206 - .../client-go/tools/record/event_test.go | 924 - .../tools/record/events_cache_test.go | 287 - .../client-go/tools/remotecommand/v2_test.go | 228 - .../client-go/tools/remotecommand/v4_test.go | 71 - vendor/k8s.io/client-go/transport/cache.go | 6 +- .../k8s.io/client-go/transport/cache_test.go | 128 - .../transport/round_trippers_test.go | 218 - .../k8s.io/client-go/transport/transport.go | 2 +- .../client-go/transport/transport_test.go | 204 - .../util/buffer/ring_growing_test.go | 50 - vendor/k8s.io/client-go/util/cert/csr_test.go | 75 - vendor/k8s.io/client-go/util/cert/pem_test.go | 197 - .../util/flowcontrol/backoff_test.go | 195 - .../util/flowcontrol/throttle_test.go | 153 - .../client-go/util/integer/integer_test.go | 244 - .../client-go/util/jsonpath/jsonpath_test.go | 371 - .../client-go/util/jsonpath/parser_test.go | 152 - .../k8s.io/client-go/util/retry/util_test.go | 71 - .../workqueue/default_rate_limiters_test.go | 184 - .../util/workqueue/delaying_queue_test.go | 255 - .../client-go/util/workqueue/queue_test.go | 161 - .../workqueue/rate_limitting_queue_test.go | 75 - vendor/k8s.io/kube-openapi/OWNERS | 4 + vendor/k8s.io/kube-openapi/code-of-conduct.md | 3 + .../kube-openapi/pkg/util/proto/document.go | 14 +- .../kube-openapi/pkg/util/proto/openapi.go | 25 + .../pkg/util/proto/openapi_suite_test.go | 49 - .../pkg/util/proto/openapi_test.go | 207 - vendor/k8s.io/kubernetes/CHANGELOG-1.10.md | 901 +- .../kubernetes/pkg/api/service/util_test.go | 216 - .../kubernetes/pkg/api/v1/pod/util_test.go | 522 - .../pkg/apis/core/helper/helpers_test.go | 491 - .../pkg/apis/core/install/install_test.go | 140 - .../pkg/apis/core/pods/helpers_test.go | 87 - .../kubernetes/pkg/apis/core/taint_test.go | 120 - .../pkg/apis/core/toleration_test.go | 136 - .../k8s.io/kubernetes/pkg/apis/core/types.go | 6 + .../pkg/apis/core/v1/conversion_test.go | 348 - .../pkg/apis/core/v1/defaults_test.go | 1386 -- .../pkg/apis/core/v1/helper/helpers_test.go | 655 - .../pkg/apis/core/validation/events_test.go | 392 - .../pkg/apis/core/validation/validation.go | 8 +- .../apis/core/validation/validation_test.go | 12688 ----------- .../pkg/apis/extensions/helpers_test.go | 62 - .../pkg/capabilities/capabilities_test.go | 50 - .../controller/controller_ref_manager_test.go | 181 - .../pkg/controller/controller_utils_test.go | 821 - .../pkg/fieldpath/fieldpath_test.go | 241 - .../pkg/kubelet/active_deadline_test.go | 95 - .../pkg/kubelet/container/cache_test.go | 210 - .../pkg/kubelet/container/helpers_test.go | 322 - .../pkg/kubelet/container/ref_test.go | 213 - .../kubelet/container/runtime_cache_test.go | 74 - .../pkg/kubelet/container/sync_result_test.go | 68 - .../k8s.io/kubernetes/pkg/kubelet/kubelet.go | 5 + .../pkg/kubelet/kubelet_getters_test.go | 69 - .../pkg/kubelet/kubelet_network_test.go | 206 - .../pkg/kubelet/kubelet_node_status.go | 3 + .../pkg/kubelet/kubelet_node_status_test.go | 1418 -- .../kubernetes/pkg/kubelet/kubelet_pods.go | 26 +- .../pkg/kubelet/kubelet_pods_test.go | 2551 --- .../pkg/kubelet/kubelet_pods_windows_test.go | 102 - .../pkg/kubelet/kubelet_resources_test.go | 111 - .../kubernetes/pkg/kubelet/kubelet_test.go | 2239 -- .../pkg/kubelet/kubelet_volumes_test.go | 470 - .../pkg/kubelet/oom_watcher_test.go | 38 - .../pkg/kubelet/pod_container_deletor_test.go | 203 - .../pkg/kubelet/pod_workers_test.go | 355 - .../pkg/kubelet/reason_cache_test.go | 69 - .../kubernetes/pkg/kubelet/runonce_test.go | 175 - .../pkg/kubelet/types/labels_test.go | 119 - .../pkg/kubelet/types/pod_update_test.go | 178 - .../pkg/kubelet/types/types_test.go | 138 - .../pkg/kubelet/util/format/resources_test.go | 35 - .../util/sliceutils/sliceutils_test.go | 222 - .../kubernetes/pkg/kubelet/util/util_test.go | 64 - .../pkg/master/client_ca_hook_test.go | 223 - .../kubernetes/pkg/master/controller_test.go | 948 - .../pkg/master/import_known_versions_test.go | 187 - .../pkg/master/master_openapi_test.go | 97 - .../kubernetes/pkg/master/master_test.go | 360 - .../pkg/scheduler/scheduler_test.go | 838 - .../pkg/security/apparmor/validate_test.go | 198 - .../pkg/serviceaccount/claims_test.go | 184 - .../kubernetes/pkg/serviceaccount/jwt_test.go | 325 - .../pkg/serviceaccount/util_test.go | 103 - .../kubernetes/pkg/util/file/file_test.go | 149 - .../kubernetes/pkg/util/hash/hash_test.go | 147 - vendor/k8s.io/kubernetes/pkg/util/mount/BUILD | 1 + .../pkg/util/mount/exec_mount_test.go | 165 - .../k8s.io/kubernetes/pkg/util/mount/fake.go | 12 +- .../k8s.io/kubernetes/pkg/util/mount/mount.go | 45 +- .../kubernetes/pkg/util/mount/mount_linux.go | 33 +- .../pkg/util/mount/mount_linux_test.go | 1661 -- .../pkg/util/mount/mount_windows.go | 26 +- .../pkg/util/mount/mount_windows_test.go | 553 - .../pkg/util/mount/nsenter_mount.go | 7 +- .../pkg/util/mount/nsenter_mount_test.go | 191 - .../util/mount/safe_format_and_mount_test.go | 242 - .../kubernetes/pkg/util/net/net_test.go | 286 - .../pkg/util/net/sets/ipnet_test.go | 155 - .../pkg/util/parsers/parsers_test.go | 51 - .../pkg/util/pointer/pointer_test.go | 66 - .../kubernetes/pkg/util/taints/taints_test.go | 687 - .../kubernetes/pkg/volume/metrics_du_test.go | 112 - .../kubernetes/pkg/volume/metrics_nil_test.go | 33 - .../pkg/volume/metrics_statfs_test.go | 67 - .../kubernetes/pkg/volume/plugins_test.go | 167 - .../pkg/volume/util/atomic_writer.go | 2 +- .../pkg/volume/util/atomic_writer_test.go | 813 - .../pkg/volume/util/device_util_linux_test.go | 160 - .../pkg/volume/util/nested_volumes_test.go | 233 - .../recyclerclient/recycler_client_test.go | 235 - .../pkg/volume/util/resize_util_test.go | 167 - .../k8s.io/kubernetes/pkg/volume/util/util.go | 31 +- .../kubernetes/pkg/volume/util/util_test.go | 1091 - .../forked/golang/expansion/expand_test.go | 284 - vendor/k8s.io/utils/.travis.yml | 2 - vendor/k8s.io/utils/README.md | 5 +- vendor/k8s.io/utils/code-of-conduct.md | 6 +- vendor/k8s.io/utils/exec/exec.go | 53 +- vendor/k8s.io/utils/exec/exec_test.go | 103 - vendor/k8s.io/utils/exec/new_test.go | 37 - 1621 files changed, 86224 insertions(+), 284248 deletions(-) create mode 100644 vendor/cloud.google.com/go/RELEASING.md delete mode 100644 vendor/cloud.google.com/go/authexample_test.go delete mode 100644 vendor/cloud.google.com/go/compute/metadata/metadata_test.go create mode 100644 vendor/cloud.google.com/go/issue_template.md delete mode 100644 vendor/cloud.google.com/go/license_test.go create mode 100755 vendor/cloud.google.com/go/regen-gapic.sh delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/adal/config_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/adal/persist_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/adal/token_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/authorization_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/autorest_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/async_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/azure_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/environments_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/azure/rp_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/client_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/date/date_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/date/time_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/date/unixtime_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/error_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/preparer_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/responder_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/sender_test.go delete mode 100644 vendor/github.com/Azure/go-autorest/autorest/utility_test.go delete mode 100644 vendor/github.com/armon/go-proxyproto/protocol_test.go delete mode 100644 vendor/github.com/beorn7/perks/quantile/bench_test.go delete mode 100644 vendor/github.com/beorn7/perks/quantile/example_test.go delete mode 100644 vendor/github.com/beorn7/perks/quantile/stream_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/common_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/dump_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/example_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/format_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/internal_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go delete mode 100644 vendor/github.com/davecgh/go-spew/spew/spew_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/example_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/hmac_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/http_example_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/none_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/parser_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go delete mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa_test.go delete mode 100644 vendor/github.com/docker/distribution/digestset/set_test.go delete mode 100644 vendor/github.com/docker/distribution/reference/normalize_test.go delete mode 100644 vendor/github.com/docker/distribution/reference/reference_test.go delete mode 100644 vendor/github.com/docker/distribution/reference/regexp_test.go delete mode 100644 vendor/github.com/docker/spdystream/priority_test.go delete mode 100644 vendor/github.com/docker/spdystream/spdy/spdy_test.go delete mode 100644 vendor/github.com/docker/spdystream/spdy_bench_test.go delete mode 100644 vendor/github.com/docker/spdystream/spdy_test.go delete mode 100644 vendor/github.com/eapache/channels/batching_channel_test.go delete mode 100644 vendor/github.com/eapache/channels/black_hole_test.go delete mode 100644 vendor/github.com/eapache/channels/channels_test.go delete mode 100644 vendor/github.com/eapache/channels/infinite_channel_test.go delete mode 100644 vendor/github.com/eapache/channels/native_channel_test.go delete mode 100644 vendor/github.com/eapache/channels/overflowing_channel_test.go delete mode 100644 vendor/github.com/eapache/channels/resizable_channel_test.go delete mode 100644 vendor/github.com/eapache/channels/ring_channel_test.go delete mode 100644 vendor/github.com/eapache/channels/shared_buffer_test.go delete mode 100644 vendor/github.com/eapache/queue/queue_test.go delete mode 100644 vendor/github.com/fsnotify/fsnotify/example_test.go delete mode 100644 vendor/github.com/fsnotify/fsnotify/fsnotify_test.go delete mode 100644 vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go delete mode 100644 vendor/github.com/fsnotify/fsnotify/inotify_test.go delete mode 100644 vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go delete mode 100644 vendor/github.com/fsnotify/fsnotify/integration_test.go delete mode 100644 vendor/github.com/fullsailor/pkcs7/ber_test.go delete mode 100644 vendor/github.com/fullsailor/pkcs7/pkcs7_test.go create mode 100644 vendor/github.com/fullsailor/pkcs7/x509.go delete mode 100644 vendor/github.com/ghodss/yaml/yaml_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/all_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/any_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/clone_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/decode_test.go create mode 100644 vendor/github.com/gogo/protobuf/proto/discard.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/encode_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/equal_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/extensions_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/map_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/message_set_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/proto3_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/size2_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/size_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/text_parser_test.go delete mode 100644 vendor/github.com/gogo/protobuf/proto/text_test.go delete mode 100644 vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_test.go delete mode 100644 vendor/github.com/golang/glog/glog_test.go create mode 100644 vendor/github.com/golang/groupcache/.travis.yml delete mode 100644 vendor/github.com/golang/groupcache/byteview_test.go delete mode 100644 vendor/github.com/golang/groupcache/groupcache_test.go delete mode 100644 vendor/github.com/golang/groupcache/http_test.go delete mode 100644 vendor/github.com/golang/groupcache/lru/lru_test.go delete mode 100644 vendor/github.com/golang/protobuf/Make.protobuf delete mode 100644 vendor/github.com/golang/protobuf/proto/Makefile delete mode 100644 vendor/github.com/golang/protobuf/proto/all_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/any_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/clone_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/decode_test.go create mode 100644 vendor/github.com/golang/protobuf/proto/discard.go delete mode 100644 vendor/github.com/golang/protobuf/proto/encode_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/equal_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/extensions_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/map_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/message_set_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/proto3_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/size2_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/size_test.go create mode 100644 vendor/github.com/golang/protobuf/proto/table_marshal.go create mode 100644 vendor/github.com/golang/protobuf/proto/table_merge.go create mode 100644 vendor/github.com/golang/protobuf/proto/table_unmarshal.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_parser_test.go delete mode 100644 vendor/github.com/golang/protobuf/proto/text_test.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/any_test.go delete mode 100644 vendor/github.com/golang/protobuf/ptypes/duration_test.go delete mode 100755 vendor/github.com/golang/protobuf/ptypes/regen.sh delete mode 100644 vendor/github.com/golang/protobuf/ptypes/timestamp_test.go create mode 100755 vendor/github.com/golang/protobuf/regenerate.sh delete mode 100644 vendor/github.com/google/gofuzz/example_test.go delete mode 100644 vendor/github.com/google/gofuzz/fuzz_test.go delete mode 100644 vendor/github.com/googleapis/gnostic/gnostic_test.go delete mode 100644 vendor/github.com/gophercloud/gophercloud/FAQ.md delete mode 100644 vendor/github.com/gophercloud/gophercloud/MIGRATING.md delete mode 100644 vendor/github.com/gophercloud/gophercloud/STYLEGUIDE.md create mode 100644 vendor/github.com/gophercloud/gophercloud/openstack/utils/base_endpoint.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/2q_test.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/arc_test.go create mode 100644 vendor/github.com/hashicorp/golang-lru/doc.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/lru_test.go create mode 100644 vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go delete mode 100644 vendor/github.com/hashicorp/golang-lru/simplelru/lru_test.go delete mode 100644 vendor/github.com/howeyc/gopass/pass_test.go delete mode 100644 vendor/github.com/imdario/mergo/issue17_test.go delete mode 100644 vendor/github.com/imdario/mergo/issue23_test.go delete mode 100644 vendor/github.com/imdario/mergo/issue38_test.go delete mode 100644 vendor/github.com/imdario/mergo/mergo_test.go create mode 100644 vendor/github.com/json-iterator/go/Gopkg.lock create mode 100644 vendor/github.com/json-iterator/go/Gopkg.toml rename vendor/github.com/json-iterator/go/{feature_adapter.go => adapter.go} (78%) rename vendor/github.com/json-iterator/go/{feature_any.go => any.go} (74%) rename vendor/github.com/json-iterator/go/{feature_any_array.go => any_array.go} (100%) rename vendor/github.com/json-iterator/go/{feature_any_bool.go => any_bool.go} (100%) rename vendor/github.com/json-iterator/go/{feature_any_float.go => any_float.go} (100%) rename vendor/github.com/json-iterator/go/{feature_any_int32.go => any_int32.go} (100%) rename vendor/github.com/json-iterator/go/{feature_any_int64.go => any_int64.go} (100%) rename vendor/github.com/json-iterator/go/{feature_any_invalid.go => any_invalid.go} (100%) rename vendor/github.com/json-iterator/go/{feature_any_nil.go => any_nil.go} (100%) rename vendor/github.com/json-iterator/go/{feature_any_number.go => any_number.go} (76%) rename vendor/github.com/json-iterator/go/{feature_any_object.go => any_object.go} (100%) rename vendor/github.com/json-iterator/go/{feature_any_string.go => any_str.go} (97%) rename vendor/github.com/json-iterator/go/{feature_any_uint32.go => any_uint32.go} (100%) rename vendor/github.com/json-iterator/go/{feature_any_uint64.go => any_uint64.go} (100%) create mode 100755 vendor/github.com/json-iterator/go/build.sh rename vendor/github.com/json-iterator/go/{feature_config.go => config.go} (52%) delete mode 100644 vendor/github.com/json-iterator/go/example_test.go delete mode 100644 vendor/github.com/json-iterator/go/feature_json_number.go delete mode 100644 vendor/github.com/json-iterator/go/feature_reflect.go delete mode 100644 vendor/github.com/json-iterator/go/feature_reflect_array.go delete mode 100644 vendor/github.com/json-iterator/go/feature_reflect_map.go delete mode 100644 vendor/github.com/json-iterator/go/feature_reflect_native.go delete mode 100644 vendor/github.com/json-iterator/go/feature_reflect_slice.go delete mode 100644 vendor/github.com/json-iterator/go/feature_stream_int.go rename vendor/github.com/json-iterator/go/{feature_iter.go => iter.go} (97%) rename vendor/github.com/json-iterator/go/{feature_iter_array.go => iter_array.go} (100%) rename vendor/github.com/json-iterator/go/{feature_iter_float.go => iter_float.go} (98%) rename vendor/github.com/json-iterator/go/{feature_iter_int.go => iter_int.go} (72%) rename vendor/github.com/json-iterator/go/{feature_iter_object.go => iter_object.go} (67%) rename vendor/github.com/json-iterator/go/{feature_iter_skip.go => iter_skip.go} (100%) rename vendor/github.com/json-iterator/go/{feature_iter_skip_sloppy.go => iter_skip_sloppy.go} (99%) rename vendor/github.com/json-iterator/go/{feature_iter_skip_strict.go => iter_skip_strict.go} (98%) rename vendor/github.com/json-iterator/go/{feature_iter_string.go => iter_str.go} (100%) delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_1dot8_only_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_adapter_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_alias_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_any_array_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_any_bool_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_any_float_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_any_int_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_any_map_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_any_null_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_any_object_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_any_string_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_array_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_bool_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_customize_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_demo_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_encode_interface_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_enum_marshaler_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_fixed_array_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_float_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_int_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_interface_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_invalid_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_io_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_iterator_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_large_file_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_map_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_must_be_valid_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_nested_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_null_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_object_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_optional_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_raw_message_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_reader_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_reflect_native_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_skip_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_sloppy_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_stream_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_string_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_struct_decoder_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_struct_encoder_test.go delete mode 100644 vendor/github.com/json-iterator/go/jsoniter_wrap_test.go rename vendor/github.com/json-iterator/go/{feature_pool.go => pool.go} (62%) create mode 100644 vendor/github.com/json-iterator/go/reflect.go create mode 100644 vendor/github.com/json-iterator/go/reflect_array.go create mode 100644 vendor/github.com/json-iterator/go/reflect_dynamic.go rename vendor/github.com/json-iterator/go/{feature_reflect_extension.go => reflect_extension.go} (55%) create mode 100644 vendor/github.com/json-iterator/go/reflect_json_number.go create mode 100644 vendor/github.com/json-iterator/go/reflect_json_raw_message.go create mode 100644 vendor/github.com/json-iterator/go/reflect_map.go create mode 100644 vendor/github.com/json-iterator/go/reflect_marshaler.go create mode 100644 vendor/github.com/json-iterator/go/reflect_native.go create mode 100644 vendor/github.com/json-iterator/go/reflect_optional.go create mode 100644 vendor/github.com/json-iterator/go/reflect_slice.go rename vendor/github.com/json-iterator/go/{feature_reflect_struct_decoder.go => reflect_struct_decoder.go} (68%) rename vendor/github.com/json-iterator/go/{feature_reflect_object.go => reflect_struct_encoder.go} (50%) rename vendor/github.com/json-iterator/go/{feature_stream.go => stream.go} (60%) rename vendor/github.com/json-iterator/go/{feature_stream_float.go => stream_float.go} (85%) create mode 100644 vendor/github.com/json-iterator/go/stream_int.go rename vendor/github.com/json-iterator/go/{feature_stream_string.go => stream_str.go} (91%) delete mode 100644 vendor/github.com/json-iterator/go/unmarshal_input_test.go create mode 100644 vendor/github.com/kr/pty/pty_openbsd.go create mode 100644 vendor/github.com/kr/pty/types_openbsd.go create mode 100644 vendor/github.com/kr/pty/ztypes_openbsd_amd64.go delete mode 100644 vendor/github.com/kylelemons/godebug/diff/diff_test.go delete mode 100644 vendor/github.com/kylelemons/godebug/pretty/examples_test.go delete mode 100644 vendor/github.com/kylelemons/godebug/pretty/public_test.go delete mode 100644 vendor/github.com/kylelemons/godebug/pretty/reflect_test.go delete mode 100644 vendor/github.com/kylelemons/godebug/pretty/structure_test.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode_test.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode_test.go delete mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go delete mode 100644 vendor/github.com/mitchellh/go-ps/process_darwin_test.go delete mode 100644 vendor/github.com/mitchellh/go-ps/process_test.go delete mode 100644 vendor/github.com/mitchellh/go-ps/process_unix_test.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go delete mode 100644 vendor/github.com/mitchellh/mapstructure/mapstructure_test.go create mode 100644 vendor/github.com/modern-go/concurrent/.gitignore create mode 100644 vendor/github.com/modern-go/concurrent/.travis.yml create mode 100644 vendor/github.com/modern-go/concurrent/LICENSE create mode 100644 vendor/github.com/modern-go/concurrent/README.md create mode 100644 vendor/github.com/modern-go/concurrent/executor.go create mode 100644 vendor/github.com/modern-go/concurrent/go_above_19.go create mode 100644 vendor/github.com/modern-go/concurrent/go_below_19.go create mode 100644 vendor/github.com/modern-go/concurrent/log.go create mode 100755 vendor/github.com/modern-go/concurrent/test.sh create mode 100644 vendor/github.com/modern-go/concurrent/unbounded_executor.go create mode 100644 vendor/github.com/modern-go/reflect2/.gitignore create mode 100644 vendor/github.com/modern-go/reflect2/Gopkg.lock rename {images/grpc-fortune-teller => vendor/github.com/modern-go/reflect2}/Gopkg.toml (70%) create mode 100644 vendor/github.com/modern-go/reflect2/LICENSE create mode 100644 vendor/github.com/modern-go/reflect2/README.md create mode 100644 vendor/github.com/modern-go/reflect2/go_above_17.go create mode 100644 vendor/github.com/modern-go/reflect2/go_above_19.go create mode 100644 vendor/github.com/modern-go/reflect2/go_below_17.go create mode 100644 vendor/github.com/modern-go/reflect2/go_below_19.go create mode 100644 vendor/github.com/modern-go/reflect2/reflect2.go rename vendor/{google.golang.org/grpc/.please-update => github.com/modern-go/reflect2/reflect2_amd64.s} (100%) create mode 100644 vendor/github.com/modern-go/reflect2/reflect2_kind.go create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_386.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_amd64p32.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_arm.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_arm64.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_mips64x.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_mipsx.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_ppc64x.s create mode 100644 vendor/github.com/modern-go/reflect2/relfect2_s390x.s create mode 100644 vendor/github.com/modern-go/reflect2/safe_field.go create mode 100644 vendor/github.com/modern-go/reflect2/safe_map.go create mode 100644 vendor/github.com/modern-go/reflect2/safe_slice.go create mode 100644 vendor/github.com/modern-go/reflect2/safe_struct.go create mode 100644 vendor/github.com/modern-go/reflect2/safe_type.go create mode 100644 vendor/github.com/modern-go/reflect2/type_map.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_array.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_eface.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_field.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_iface.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_link.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_map.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_ptr.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_slice.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_struct.go create mode 100644 vendor/github.com/modern-go/reflect2/unsafe_type.go delete mode 100644 vendor/github.com/moul/http2curl/http2curl_test.go delete mode 100644 vendor/github.com/ncabatoff/process-exporter/proc/base_test.go delete mode 100644 vendor/github.com/ncabatoff/process-exporter/proc/grouper_test.go delete mode 100644 vendor/github.com/ncabatoff/process-exporter/proc/read_test.go delete mode 100644 vendor/github.com/ncabatoff/process-exporter/proc/tracker_test.go create mode 100644 vendor/github.com/onsi/ginkgo/RELEASING.md create mode 100755 vendor/github.com/onsi/ginkgo/before_pr.sh delete mode 100644 vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/containernode/container_node_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/failer/failer_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/aggregator_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/remote/server_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec/spec_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec/specs_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/suite/suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/internal/writer/writer_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/default_reporter_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/junit_reporter_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/reporters_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/types/types_suite_test.go delete mode 100644 vendor/github.com/onsi/ginkgo/types/types_test.go create mode 100644 vendor/github.com/onsi/gomega/RELEASING.md delete mode 100644 vendor/github.com/onsi/gomega/format/format_suite_test.go delete mode 100644 vendor/github.com/onsi/gomega/format/format_test.go delete mode 100644 vendor/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go delete mode 100644 vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go delete mode 100644 vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go delete mode 100644 vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go delete mode 100644 vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/and_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go create mode 100644 vendor/github.com/onsi/gomega/matchers/attributes_slice.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_a_directory_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_a_regular_file_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_an_existing_file_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_closed_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_empty_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_false_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_identical_to_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_nil_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_sent_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_true_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/be_zero_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/consist_of_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/contain_element_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/equal_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_cap_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_key_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_len_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/match_error_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/match_xml_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/match_yaml_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/not_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/or_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/panic_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/receive_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/succeed_matcher_test.go delete mode 100644 vendor/github.com/onsi/gomega/matchers/with_transform_test.go delete mode 100644 vendor/github.com/opencontainers/go-digest/algorithm_test.go delete mode 100644 vendor/github.com/opencontainers/go-digest/digest_test.go delete mode 100644 vendor/github.com/opencontainers/go-digest/verifiers_test.go delete mode 100644 vendor/github.com/parnurzeal/gorequest/gorequest_test.go delete mode 100644 vendor/github.com/pborman/uuid/marshal_test.go delete mode 100644 vendor/github.com/pborman/uuid/seq_test.go delete mode 100644 vendor/github.com/pborman/uuid/sql_test.go delete mode 100644 vendor/github.com/pborman/uuid/uuid_test.go delete mode 100644 vendor/github.com/pkg/errors/bench_test.go delete mode 100644 vendor/github.com/pkg/errors/errors_test.go delete mode 100644 vendor/github.com/pkg/errors/example_test.go delete mode 100644 vendor/github.com/pkg/errors/format_test.go delete mode 100644 vendor/github.com/pkg/errors/stack_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/counter_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/examples_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/http_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/registry_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/summary_test.go delete mode 100644 vendor/github.com/prometheus/client_golang/prometheus/vec_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/bench_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/decode_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_create_test.go delete mode 100644 vendor/github.com/prometheus/common/expfmt/text_parse_test.go delete mode 100644 vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go delete mode 100644 vendor/github.com/prometheus/common/model/alert_test.go delete mode 100644 vendor/github.com/prometheus/common/model/labels_test.go delete mode 100644 vendor/github.com/prometheus/common/model/metric_test.go delete mode 100644 vendor/github.com/prometheus/common/model/signature_test.go delete mode 100644 vendor/github.com/prometheus/common/model/silence_test.go delete mode 100644 vendor/github.com/prometheus/common/model/time_test.go delete mode 100644 vendor/github.com/prometheus/common/model/value_test.go create mode 100644 vendor/github.com/prometheus/procfs/.gitignore delete mode 100644 vendor/github.com/prometheus/procfs/buddyinfo_test.go create mode 100644 vendor/github.com/prometheus/procfs/fixtures.ttar delete mode 100644 vendor/github.com/prometheus/procfs/fs_test.go create mode 100644 vendor/github.com/prometheus/procfs/internal/util/parse.go delete mode 100644 vendor/github.com/prometheus/procfs/ipvs_test.go delete mode 100644 vendor/github.com/prometheus/procfs/mdstat_test.go delete mode 100644 vendor/github.com/prometheus/procfs/mountstats_test.go create mode 100644 vendor/github.com/prometheus/procfs/net_dev.go create mode 100644 vendor/github.com/prometheus/procfs/nfs/nfs.go create mode 100644 vendor/github.com/prometheus/procfs/nfs/parse.go create mode 100644 vendor/github.com/prometheus/procfs/nfs/parse_nfs.go create mode 100644 vendor/github.com/prometheus/procfs/nfs/parse_nfsd.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_io_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_limits_test.go create mode 100644 vendor/github.com/prometheus/procfs/proc_ns.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_stat_test.go delete mode 100644 vendor/github.com/prometheus/procfs/proc_test.go delete mode 100644 vendor/github.com/prometheus/procfs/stat_test.go delete mode 100644 vendor/github.com/prometheus/procfs/xfrm_test.go delete mode 100644 vendor/github.com/prometheus/procfs/xfs/parse_test.go delete mode 100644 vendor/github.com/spf13/afero/afero_test.go delete mode 100644 vendor/github.com/spf13/afero/basepath_test.go delete mode 100644 vendor/github.com/spf13/afero/composite_test.go delete mode 100644 vendor/github.com/spf13/afero/copyOnWriteFs_test.go delete mode 100644 vendor/github.com/spf13/afero/ioutil_test.go rename vendor/github.com/{prometheus/client_golang/prometheus/metric_test.go => spf13/afero/lstater.go} (50%) delete mode 100644 vendor/github.com/spf13/afero/match_test.go delete mode 100644 vendor/github.com/spf13/afero/mem/file_test.go delete mode 100644 vendor/github.com/spf13/afero/memmap_test.go delete mode 100644 vendor/github.com/spf13/afero/path_test.go delete mode 100644 vendor/github.com/spf13/afero/ro_regexp_test.go delete mode 100644 vendor/github.com/spf13/afero/util_test.go delete mode 100644 vendor/github.com/spf13/pflag/bool_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/bool_test.go create mode 100644 vendor/github.com/spf13/pflag/bytes.go delete mode 100644 vendor/github.com/spf13/pflag/count_test.go create mode 100644 vendor/github.com/spf13/pflag/duration_slice.go delete mode 100644 vendor/github.com/spf13/pflag/example_test.go delete mode 100644 vendor/github.com/spf13/pflag/export_test.go delete mode 100644 vendor/github.com/spf13/pflag/flag_test.go delete mode 100644 vendor/github.com/spf13/pflag/golangflag_test.go create mode 100644 vendor/github.com/spf13/pflag/int16.go delete mode 100644 vendor/github.com/spf13/pflag/int_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/ip_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/ip_test.go delete mode 100644 vendor/github.com/spf13/pflag/ipnet_test.go delete mode 100644 vendor/github.com/spf13/pflag/string_array_test.go delete mode 100644 vendor/github.com/spf13/pflag/string_slice_test.go delete mode 100644 vendor/github.com/spf13/pflag/uint_slice_test.go delete mode 100644 vendor/github.com/zakjan/cert-chain-resolver/certUtil/chain_test.go delete mode 100644 vendor/github.com/zakjan/cert-chain-resolver/certUtil/io_test.go delete mode 100644 vendor/golang.org/x/crypto/ed25519/ed25519_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/benchmark_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/buffer_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/certs_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/cipher_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/client_auth_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/client_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/example_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/handshake_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/kex_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/keys_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/mempipe_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/messages_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/mux_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/session_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/tcpip_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/terminal/terminal_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/testdata_test.go delete mode 100644 vendor/golang.org/x/crypto/ssh/transport_test.go delete mode 100644 vendor/golang.org/x/net/context/context_test.go delete mode 100644 vendor/golang.org/x/net/context/ctxhttp/ctxhttp_17_test.go delete mode 100644 vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17_test.go delete mode 100644 vendor/golang.org/x/net/context/ctxhttp/ctxhttp_test.go delete mode 100644 vendor/golang.org/x/net/context/withtimeout_test.go delete mode 100644 vendor/golang.org/x/net/html/atom/atom_test.go delete mode 100644 vendor/golang.org/x/net/html/atom/table_test.go delete mode 100644 vendor/golang.org/x/net/html/charset/charset_test.go delete mode 100644 vendor/golang.org/x/net/html/entity_test.go delete mode 100644 vendor/golang.org/x/net/html/escape_test.go delete mode 100644 vendor/golang.org/x/net/html/example_test.go delete mode 100644 vendor/golang.org/x/net/html/node_test.go delete mode 100644 vendor/golang.org/x/net/html/parse_test.go delete mode 100644 vendor/golang.org/x/net/html/render_test.go delete mode 100644 vendor/golang.org/x/net/html/token_test.go create mode 100644 vendor/golang.org/x/net/http/httpguts/guts.go rename vendor/golang.org/x/net/{lex/httplex => http/httpguts}/httplex.go (97%) delete mode 100644 vendor/golang.org/x/net/http2/ciphers_test.go delete mode 100644 vendor/golang.org/x/net/http2/databuffer_test.go delete mode 100644 vendor/golang.org/x/net/http2/errors_test.go delete mode 100644 vendor/golang.org/x/net/http2/flow_test.go delete mode 100644 vendor/golang.org/x/net/http2/frame_test.go delete mode 100644 vendor/golang.org/x/net/http2/go18_test.go delete mode 100644 vendor/golang.org/x/net/http2/go19_test.go delete mode 100644 vendor/golang.org/x/net/http2/gotrack_test.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/encode_test.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/hpack_test.go delete mode 100644 vendor/golang.org/x/net/http2/hpack/tables_test.go delete mode 100644 vendor/golang.org/x/net/http2/http2_test.go delete mode 100644 vendor/golang.org/x/net/http2/pipe_test.go delete mode 100644 vendor/golang.org/x/net/http2/server_push_test.go delete mode 100644 vendor/golang.org/x/net/http2/server_test.go delete mode 100644 vendor/golang.org/x/net/http2/transport_test.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_priority_test.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_random_test.go delete mode 100644 vendor/golang.org/x/net/http2/writesched_test.go delete mode 100644 vendor/golang.org/x/net/http2/z_spec_test.go delete mode 100644 vendor/golang.org/x/net/idna/example_test.go delete mode 100644 vendor/golang.org/x/net/idna/idna_test.go delete mode 100644 vendor/golang.org/x/net/idna/punycode_test.go delete mode 100644 vendor/golang.org/x/net/internal/timeseries/timeseries_test.go delete mode 100644 vendor/golang.org/x/net/lex/httplex/httplex_test.go delete mode 100644 vendor/golang.org/x/net/publicsuffix/list_test.go delete mode 100644 vendor/golang.org/x/net/publicsuffix/table_test.go delete mode 100644 vendor/golang.org/x/net/trace/histogram_test.go delete mode 100644 vendor/golang.org/x/net/trace/trace_test.go delete mode 100644 vendor/golang.org/x/oauth2/client_appengine.go delete mode 100644 vendor/golang.org/x/oauth2/example_test.go create mode 100644 vendor/golang.org/x/oauth2/google/doc_go19.go create mode 100644 vendor/golang.org/x/oauth2/google/doc_not_go19.go delete mode 100644 vendor/golang.org/x/oauth2/google/example_test.go create mode 100644 vendor/golang.org/x/oauth2/google/go19.go delete mode 100644 vendor/golang.org/x/oauth2/google/google_test.go delete mode 100644 vendor/golang.org/x/oauth2/google/jwt_test.go create mode 100644 vendor/golang.org/x/oauth2/google/not_go19.go delete mode 100644 vendor/golang.org/x/oauth2/google/sdk_test.go create mode 100644 vendor/golang.org/x/oauth2/internal/client_appengine.go delete mode 100644 vendor/golang.org/x/oauth2/internal/oauth2_test.go delete mode 100644 vendor/golang.org/x/oauth2/internal/token_test.go delete mode 100644 vendor/golang.org/x/oauth2/internal/transport_test.go delete mode 100644 vendor/golang.org/x/oauth2/jws/jws_test.go delete mode 100644 vendor/golang.org/x/oauth2/jwt/example_test.go delete mode 100644 vendor/golang.org/x/oauth2/jwt/jwt_test.go delete mode 100644 vendor/golang.org/x/oauth2/oauth2_test.go delete mode 100644 vendor/golang.org/x/oauth2/token_test.go delete mode 100644 vendor/golang.org/x/oauth2/transport_test.go create mode 100644 vendor/golang.org/x/sys/unix/affinity_linux.go delete mode 100644 vendor/golang.org/x/sys/unix/creds_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_darwin_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_dragonfly_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_linux_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_netbsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_openbsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/dev_solaris_test.go delete mode 100644 vendor/golang.org/x/sys/unix/env_unset.go delete mode 100644 vendor/golang.org/x/sys/unix/export_test.go rename vendor/golang.org/x/sys/unix/{flock.go => fcntl.go} (74%) rename vendor/golang.org/x/sys/unix/{flock_linux_32bit.go => fcntl_linux_32bit.go} (100%) delete mode 100644 vendor/golang.org/x/sys/unix/mmap_unix_test.go delete mode 100644 vendor/golang.org/x/sys/unix/openbsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_bsd_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_freebsd_test.go create mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gc.go create mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_gccgo.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_linux_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_no_getwd.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_solaris_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_test.go delete mode 100644 vendor/golang.org/x/sys/unix/syscall_unix_test.go delete mode 100644 vendor/golang.org/x/sys/unix/zsysnum_solaris_amd64.go delete mode 100644 vendor/golang.org/x/sys/windows/env_unset.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall_test.go delete mode 100644 vendor/golang.org/x/sys/windows/syscall_windows_test.go delete mode 100644 vendor/golang.org/x/text/collate/build/builder_test.go delete mode 100644 vendor/golang.org/x/text/collate/build/colelem_test.go delete mode 100644 vendor/golang.org/x/text/collate/build/contract_test.go delete mode 100644 vendor/golang.org/x/text/collate/build/order_test.go delete mode 100644 vendor/golang.org/x/text/collate/build/trie_test.go delete mode 100644 vendor/golang.org/x/text/collate/collate_test.go delete mode 100644 vendor/golang.org/x/text/collate/export_test.go delete mode 100644 vendor/golang.org/x/text/collate/option_test.go delete mode 100644 vendor/golang.org/x/text/collate/reg_test.go delete mode 100644 vendor/golang.org/x/text/collate/sort_test.go delete mode 100644 vendor/golang.org/x/text/collate/table_test.go delete mode 100644 vendor/golang.org/x/text/encoding/charmap/charmap_test.go delete mode 100644 vendor/golang.org/x/text/encoding/encoding_test.go delete mode 100644 vendor/golang.org/x/text/encoding/example_test.go delete mode 100644 vendor/golang.org/x/text/encoding/htmlindex/htmlindex_test.go delete mode 100644 vendor/golang.org/x/text/encoding/japanese/all_test.go delete mode 100644 vendor/golang.org/x/text/encoding/korean/all_test.go delete mode 100644 vendor/golang.org/x/text/encoding/simplifiedchinese/all_test.go delete mode 100644 vendor/golang.org/x/text/encoding/traditionalchinese/all_test.go delete mode 100644 vendor/golang.org/x/text/encoding/unicode/unicode_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/collate_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/collelem_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/colltab_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/contract_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/iter_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/numeric_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/trie_test.go delete mode 100644 vendor/golang.org/x/text/internal/colltab/weighter_test.go delete mode 100644 vendor/golang.org/x/text/internal/gen_test.go delete mode 100644 vendor/golang.org/x/text/internal/internal_test.go delete mode 100644 vendor/golang.org/x/text/internal/match_test.go delete mode 100644 vendor/golang.org/x/text/internal/tag/tag_test.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/data_test.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/example_compact_test.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/example_test.go delete mode 100644 vendor/golang.org/x/text/internal/triegen/gen_test.go delete mode 100644 vendor/golang.org/x/text/internal/ucd/example_test.go delete mode 100644 vendor/golang.org/x/text/internal/ucd/ucd_test.go delete mode 100644 vendor/golang.org/x/text/language/coverage_test.go delete mode 100644 vendor/golang.org/x/text/language/examples_test.go delete mode 100644 vendor/golang.org/x/text/language/httpexample_test.go delete mode 100644 vendor/golang.org/x/text/language/language_test.go delete mode 100644 vendor/golang.org/x/text/language/lookup_test.go delete mode 100644 vendor/golang.org/x/text/language/match_test.go delete mode 100644 vendor/golang.org/x/text/language/parse_test.go delete mode 100644 vendor/golang.org/x/text/runes/cond_test.go delete mode 100644 vendor/golang.org/x/text/runes/example_test.go delete mode 100644 vendor/golang.org/x/text/runes/runes_test.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bench_test.go create mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go create mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go delete mode 100644 vendor/golang.org/x/text/secure/bidirule/bidirule_test.go delete mode 100644 vendor/golang.org/x/text/transform/examples_test.go delete mode 100644 vendor/golang.org/x/text/transform/transform_test.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/core_test.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/ranges_test.go rename vendor/golang.org/x/text/unicode/bidi/{tables.go => tables10.0.0.go} (99%) create mode 100644 vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/bidi/tables_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/cldr_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/collate_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/data_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/examples_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/resolve_test.go delete mode 100644 vendor/golang.org/x/text/unicode/cldr/slice_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/composition_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/example_iter_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/example_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/forminfo_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/iter_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/normalize_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/readwriter_test.go rename vendor/golang.org/x/text/unicode/norm/{tables.go => tables10.0.0.go} (99%) create mode 100644 vendor/golang.org/x/text/unicode/norm/tables9.0.0.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/transform_test.go delete mode 100644 vendor/golang.org/x/text/unicode/norm/ucd_test.go delete mode 100644 vendor/golang.org/x/text/unicode/rangetable/merge_test.go delete mode 100644 vendor/golang.org/x/text/unicode/rangetable/rangetable_test.go rename vendor/golang.org/x/text/unicode/rangetable/{tables.go => tables10.0.0.go} (99%) create mode 100644 vendor/golang.org/x/text/unicode/rangetable/tables9.0.0.go delete mode 100644 vendor/golang.org/x/time/rate/rate_test.go delete mode 100644 vendor/google.golang.org/appengine/appengine_test.go delete mode 100644 vendor/google.golang.org/appengine/internal/api_race_test.go delete mode 100644 vendor/google.golang.org/appengine/internal/api_test.go delete mode 100644 vendor/google.golang.org/appengine/internal/app_id_test.go delete mode 100644 vendor/google.golang.org/appengine/internal/internal_vm_test.go delete mode 100644 vendor/google.golang.org/appengine/internal/net_test.go delete mode 100644 vendor/google.golang.org/appengine/namespace_test.go create mode 100644 vendor/google.golang.org/grpc/balancer/base/balancer.go create mode 100644 vendor/google.golang.org/grpc/balancer/base/base.go create mode 100644 vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go delete mode 100644 vendor/google.golang.org/grpc/balancer_test.go delete mode 100644 vendor/google.golang.org/grpc/call_test.go create mode 100644 vendor/google.golang.org/grpc/channelz/funcs.go create mode 100644 vendor/google.golang.org/grpc/channelz/types.go delete mode 100644 vendor/google.golang.org/grpc/clientconn_test.go delete mode 100644 vendor/google.golang.org/grpc/codec_benchmark_test.go delete mode 100644 vendor/google.golang.org/grpc/codec_test.go delete mode 100644 vendor/google.golang.org/grpc/credentials/credentials_test.go create mode 100644 vendor/google.golang.org/grpc/encoding/encoding.go create mode 100644 vendor/google.golang.org/grpc/encoding/proto/proto.go rename vendor/google.golang.org/grpc/{naming/go18_test.go => envconfig.go} (54%) create mode 100644 vendor/google.golang.org/grpc/go16.go create mode 100644 vendor/google.golang.org/grpc/go17.go delete mode 100644 vendor/google.golang.org/grpc/grpclb/grpclb_test.go create mode 100644 vendor/google.golang.org/grpc/grpclb_picker.go create mode 100644 vendor/google.golang.org/grpc/grpclb_remote_balancer.go create mode 100644 vendor/google.golang.org/grpc/grpclb_util.go delete mode 100644 vendor/google.golang.org/grpc/grpclog/loggerv2_test.go delete mode 100644 vendor/google.golang.org/grpc/metadata/metadata_test.go delete mode 100644 vendor/google.golang.org/grpc/naming/dns_resolver_test.go delete mode 100644 vendor/google.golang.org/grpc/picker_wrapper_test.go delete mode 100644 vendor/google.golang.org/grpc/pickfirst_test.go delete mode 100644 vendor/google.golang.org/grpc/proxy_test.go create mode 100644 vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go rename vendor/google.golang.org/grpc/{naming/go17_test.go => resolver/dns/go17.go} (65%) rename vendor/google.golang.org/grpc/{backoff_test.go => resolver/dns/go18.go} (70%) create mode 100644 vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go delete mode 100644 vendor/google.golang.org/grpc/resolver_conn_wrapper_test.go delete mode 100644 vendor/google.golang.org/grpc/rpc_util_test.go delete mode 100644 vendor/google.golang.org/grpc/server_test.go create mode 100644 vendor/google.golang.org/grpc/service_config.go delete mode 100644 vendor/google.golang.org/grpc/stats/stats_test.go delete mode 100644 vendor/google.golang.org/grpc/status/status_test.go create mode 100644 vendor/google.golang.org/grpc/transport/controlbuf.go rename vendor/google.golang.org/grpc/transport/{control.go => flowcontrol.go} (51%) create mode 100644 vendor/google.golang.org/grpc/transport/go16.go create mode 100644 vendor/google.golang.org/grpc/transport/go17.go delete mode 100644 vendor/google.golang.org/grpc/transport/handler_server_test.go delete mode 100644 vendor/google.golang.org/grpc/transport/http_util_test.go delete mode 100644 vendor/google.golang.org/grpc/transport/transport_test.go delete mode 100644 vendor/gopkg.in/fsnotify/fsnotify.v1/example_test.go delete mode 100644 vendor/gopkg.in/fsnotify/fsnotify.v1/fsnotify_test.go delete mode 100644 vendor/gopkg.in/fsnotify/fsnotify.v1/inotify_poller_test.go delete mode 100644 vendor/gopkg.in/fsnotify/fsnotify.v1/inotify_test.go delete mode 100644 vendor/gopkg.in/fsnotify/fsnotify.v1/integration_darwin_test.go delete mode 100644 vendor/gopkg.in/fsnotify/fsnotify.v1/integration_test.go delete mode 100644 vendor/gopkg.in/go-playground/pool.v3/batch_limited_test.go delete mode 100644 vendor/gopkg.in/go-playground/pool.v3/batch_unlimited_test.go delete mode 100644 vendor/gopkg.in/go-playground/pool.v3/limited_pool_benchmarks_test.go delete mode 100644 vendor/gopkg.in/go-playground/pool.v3/limited_pool_test.go delete mode 100644 vendor/gopkg.in/go-playground/pool.v3/pool_test.go delete mode 100644 vendor/gopkg.in/go-playground/pool.v3/unlimited_pool_benchmarks_test.go delete mode 100644 vendor/gopkg.in/go-playground/pool.v3/unlimited_pool_test.go delete mode 100644 vendor/gopkg.in/inf.v0/benchmark_test.go delete mode 100644 vendor/gopkg.in/inf.v0/dec_go1_2_test.go delete mode 100644 vendor/gopkg.in/inf.v0/dec_internal_test.go delete mode 100644 vendor/gopkg.in/inf.v0/dec_test.go delete mode 100644 vendor/gopkg.in/inf.v0/example_test.go delete mode 100644 vendor/gopkg.in/inf.v0/rounder_example_test.go delete mode 100644 vendor/gopkg.in/inf.v0/rounder_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/asymmetric_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/cipher/cbc_hmac_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/cipher/concat_kdf_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/cipher/ecdh_es_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/cipher/key_wrap_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/crypter_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/doc_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/encoding_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/json/bench_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/json/decode_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/json/encode_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/json/number_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/json/scanner_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/json/stream_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/json/tagkey_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/json/tags_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwe_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwk_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jws_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwt/builder_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwt/claims_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwt/example_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwt/jwt_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/jwt/validation_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/signing_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/symmetric_test.go delete mode 100644 vendor/gopkg.in/square/go-jose.v2/utils_test.go rename images/grpc-fortune-teller/proto/fortune/doc.go => vendor/gopkg.in/yaml.v2/NOTICE (79%) delete mode 100644 vendor/gopkg.in/yaml.v2/decode_test.go delete mode 100644 vendor/gopkg.in/yaml.v2/encode_test.go delete mode 100644 vendor/gopkg.in/yaml.v2/example_embedded_test.go create mode 100644 vendor/gopkg.in/yaml.v2/go.mod delete mode 100644 vendor/gopkg.in/yaml.v2/suite_test.go delete mode 100644 vendor/k8s.io/api/admissionregistration/v1alpha1/BUILD delete mode 100644 vendor/k8s.io/api/admissionregistration/v1beta1/BUILD delete mode 100644 vendor/k8s.io/api/apps/v1/BUILD delete mode 100644 vendor/k8s.io/api/apps/v1beta1/BUILD delete mode 100644 vendor/k8s.io/api/apps/v1beta2/BUILD delete mode 100644 vendor/k8s.io/api/authentication/v1/BUILD delete mode 100644 vendor/k8s.io/api/authentication/v1beta1/BUILD delete mode 100644 vendor/k8s.io/api/authorization/v1/BUILD delete mode 100644 vendor/k8s.io/api/authorization/v1beta1/BUILD delete mode 100644 vendor/k8s.io/api/autoscaling/v1/BUILD delete mode 100644 vendor/k8s.io/api/autoscaling/v2beta1/BUILD delete mode 100644 vendor/k8s.io/api/batch/v1/BUILD delete mode 100644 vendor/k8s.io/api/batch/v1beta1/BUILD delete mode 100644 vendor/k8s.io/api/batch/v2alpha1/BUILD delete mode 100644 vendor/k8s.io/api/certificates/v1beta1/BUILD delete mode 100644 vendor/k8s.io/api/core/v1/BUILD delete mode 100644 vendor/k8s.io/api/core/v1/taint_test.go delete mode 100644 vendor/k8s.io/api/core/v1/toleration_test.go delete mode 100644 vendor/k8s.io/api/events/v1beta1/BUILD delete mode 100644 vendor/k8s.io/api/extensions/v1beta1/BUILD delete mode 100644 vendor/k8s.io/api/networking/v1/BUILD delete mode 100644 vendor/k8s.io/api/policy/v1beta1/BUILD delete mode 100644 vendor/k8s.io/api/rbac/v1/BUILD delete mode 100644 vendor/k8s.io/api/rbac/v1alpha1/BUILD delete mode 100644 vendor/k8s.io/api/rbac/v1beta1/BUILD delete mode 100644 vendor/k8s.io/api/scheduling/v1alpha1/BUILD delete mode 100644 vendor/k8s.io/api/settings/v1alpha1/BUILD delete mode 100644 vendor/k8s.io/api/storage/v1/BUILD delete mode 100644 vendor/k8s.io/api/storage/v1alpha1/BUILD delete mode 100644 vendor/k8s.io/api/storage/v1beta1/BUILD delete mode 100644 vendor/k8s.io/apiextensions-apiserver/BUILD delete mode 100644 vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/BUILD delete mode 100644 vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers_test.go delete mode 100644 vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/BUILD delete mode 100644 vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/conversion_test.go delete mode 100644 vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal_test.go delete mode 100644 vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/BUILD delete mode 100644 vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme/BUILD delete mode 100644 vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/BUILD delete mode 100644 vendor/k8s.io/apiextensions-apiserver/pkg/features/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/equality/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/errors/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/errors/errors_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/meta/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/meta/meta_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/meta/priority_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/meta/restmapper_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/amount_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/math_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/quantity_example_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/quantity_proto_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/quantity_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/resource/scale_int_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/validation/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apimachinery/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/apimachinery/announced/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/apimachinery/announced/announced_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apimachinery/registered/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/apimachinery/registered/registered_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apimachinery/types_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/roundtrip_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/conversion_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/duration_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/group_version_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/labels_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/conversion/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/conversion/converter_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/conversion/helper_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/conversion/queryparams/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/fields/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/fields/fields_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/fields/selector_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/labels/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/labels/labels_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/labels/selector_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/conversion_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/converter_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/embedded_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/extension_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/schema/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/schema/group_version_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/scheme_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/meta_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/selection/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/types/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/cache/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/cache/cache_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/clock/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/clock/clock_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/diff/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/diff/diff_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/errors/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/errors/errors_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/framer/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/framer/framer_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/httpstream/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/httpstream/httpstream_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/intstr/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/intstr/intstr_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/json/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/json/json_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/mergepatch/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/mergepatch/util_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/http_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/interface_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/port_range_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/port_split_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/net/util_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/remotecommand/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/runtime/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/runtime/runtime_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/sets/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/sets/set_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/strategicpatch/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/uuid/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/validation/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/validation/field/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/validation/field/errors_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/validation/field/path_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/validation/validation_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/wait/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/wait/wait_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/yaml/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/util/yaml/decoder_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/version/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/watch/BUILD delete mode 100644 vendor/k8s.io/apimachinery/pkg/watch/filter_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/watch/mux_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/watch/streamwatcher_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/watch/until_test.go delete mode 100644 vendor/k8s.io/apimachinery/pkg/watch/watch_test.go delete mode 100644 vendor/k8s.io/apimachinery/third_party/forked/golang/json/BUILD delete mode 100644 vendor/k8s.io/apimachinery/third_party/forked/golang/json/fields_test.go delete mode 100644 vendor/k8s.io/apimachinery/third_party/forked/golang/netutil/BUILD delete mode 100644 vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/BUILD delete mode 100644 vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal_test.go delete mode 100644 vendor/k8s.io/apiserver/pkg/authentication/authenticator/BUILD delete mode 100644 vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/BUILD delete mode 100644 vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/util_test.go delete mode 100644 vendor/k8s.io/apiserver/pkg/authentication/user/BUILD delete mode 100644 vendor/k8s.io/apiserver/pkg/features/BUILD delete mode 100644 vendor/k8s.io/apiserver/pkg/server/BUILD delete mode 100644 vendor/k8s.io/apiserver/pkg/server/config_selfclient_test.go delete mode 100644 vendor/k8s.io/apiserver/pkg/server/config_test.go delete mode 100644 vendor/k8s.io/apiserver/pkg/server/genericapiserver_test.go delete mode 100644 vendor/k8s.io/apiserver/pkg/server/healthz/BUILD delete mode 100644 vendor/k8s.io/apiserver/pkg/server/healthz/healthz_test.go delete mode 100644 vendor/k8s.io/apiserver/pkg/util/feature/BUILD delete mode 100644 vendor/k8s.io/apiserver/pkg/util/feature/feature_gate_test.go delete mode 100644 vendor/k8s.io/apiserver/pkg/util/logs/BUILD delete mode 100644 vendor/k8s.io/client-go/discovery/discovery_client_test.go delete mode 100644 vendor/k8s.io/client-go/discovery/fake/discovery_test.go delete mode 100644 vendor/k8s.io/client-go/discovery/helper_blackbox_test.go delete mode 100644 vendor/k8s.io/client-go/discovery/restmapper_test.go delete mode 100644 vendor/k8s.io/client-go/listers/extensions/v1beta1/daemonset_expansion_test.go delete mode 100644 vendor/k8s.io/client-go/plugin/pkg/client/auth/azure/azure_test.go delete mode 100644 vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec_test.go delete mode 100644 vendor/k8s.io/client-go/plugin/pkg/client/auth/gcp/gcp_test.go delete mode 100644 vendor/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc_test.go delete mode 100644 vendor/k8s.io/client-go/plugin/pkg/client/auth/openstack/openstack_test.go delete mode 100644 vendor/k8s.io/client-go/rest/client_test.go delete mode 100644 vendor/k8s.io/client-go/rest/config_test.go delete mode 100644 vendor/k8s.io/client-go/rest/plugin_test.go delete mode 100755 vendor/k8s.io/client-go/rest/request_test.go delete mode 100644 vendor/k8s.io/client-go/rest/url_utils_test.go delete mode 100644 vendor/k8s.io/client-go/rest/urlbackoff_test.go delete mode 100644 vendor/k8s.io/client-go/rest/watch/decoder_test.go delete mode 100644 vendor/k8s.io/client-go/rest/watch/encoder_test.go delete mode 100644 vendor/k8s.io/client-go/testing/fixture_test.go delete mode 100644 vendor/k8s.io/client-go/tools/auth/clientauth_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/controller_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/delta_fifo_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/expiration_cache_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/fifo_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/heap_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/index_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/mutation_detector_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/processor_listener_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/reflector_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/shared_informer_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/store_test.go delete mode 100644 vendor/k8s.io/client-go/tools/cache/undelta_store_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/helpers_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/api/types_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/client_config_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/loader_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/overrides_test.go delete mode 100644 vendor/k8s.io/client-go/tools/clientcmd/validation_test.go delete mode 100644 vendor/k8s.io/client-go/tools/leaderelection/leaderelection_test.go delete mode 100644 vendor/k8s.io/client-go/tools/pager/pager_test.go delete mode 100644 vendor/k8s.io/client-go/tools/record/event_test.go delete mode 100644 vendor/k8s.io/client-go/tools/record/events_cache_test.go delete mode 100644 vendor/k8s.io/client-go/tools/remotecommand/v2_test.go delete mode 100644 vendor/k8s.io/client-go/tools/remotecommand/v4_test.go delete mode 100644 vendor/k8s.io/client-go/transport/cache_test.go delete mode 100644 vendor/k8s.io/client-go/transport/round_trippers_test.go delete mode 100644 vendor/k8s.io/client-go/transport/transport_test.go delete mode 100644 vendor/k8s.io/client-go/util/buffer/ring_growing_test.go delete mode 100644 vendor/k8s.io/client-go/util/cert/csr_test.go delete mode 100644 vendor/k8s.io/client-go/util/cert/pem_test.go delete mode 100644 vendor/k8s.io/client-go/util/flowcontrol/backoff_test.go delete mode 100644 vendor/k8s.io/client-go/util/flowcontrol/throttle_test.go delete mode 100644 vendor/k8s.io/client-go/util/integer/integer_test.go delete mode 100644 vendor/k8s.io/client-go/util/jsonpath/jsonpath_test.go delete mode 100644 vendor/k8s.io/client-go/util/jsonpath/parser_test.go delete mode 100644 vendor/k8s.io/client-go/util/retry/util_test.go delete mode 100644 vendor/k8s.io/client-go/util/workqueue/default_rate_limiters_test.go delete mode 100644 vendor/k8s.io/client-go/util/workqueue/delaying_queue_test.go delete mode 100644 vendor/k8s.io/client-go/util/workqueue/queue_test.go delete mode 100644 vendor/k8s.io/client-go/util/workqueue/rate_limitting_queue_test.go create mode 100644 vendor/k8s.io/kube-openapi/code-of-conduct.md delete mode 100644 vendor/k8s.io/kube-openapi/pkg/util/proto/openapi_suite_test.go delete mode 100644 vendor/k8s.io/kube-openapi/pkg/util/proto/openapi_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/api/service/util_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/api/v1/pod/util_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/core/helper/helpers_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/core/install/install_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/core/pods/helpers_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/core/taint_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/core/toleration_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/core/v1/conversion_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/core/v1/defaults_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/core/v1/helper/helpers_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/core/validation/events_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/core/validation/validation_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/apis/extensions/helpers_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/capabilities/capabilities_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/controller/controller_ref_manager_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/controller/controller_utils_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/fieldpath/fieldpath_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/active_deadline_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/container/cache_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/container/helpers_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/container/ref_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/container/sync_result_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_getters_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_network_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods_windows_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_resources_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_volumes_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/oom_watcher_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/pod_container_deletor_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/pod_workers_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/reason_cache_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/runonce_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/types/labels_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/types/pod_update_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/types/types_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/util/format/resources_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/util/sliceutils/sliceutils_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/kubelet/util/util_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/master/client_ca_hook_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/master/controller_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/master/import_known_versions_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/master/master_openapi_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/master/master_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/scheduler/scheduler_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/security/apparmor/validate_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/serviceaccount/claims_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/serviceaccount/jwt_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/serviceaccount/util_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/file/file_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/hash/hash_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/mount/exec_mount_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/mount/mount_windows_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/mount/safe_format_and_mount_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/net/net_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/net/sets/ipnet_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/parsers/parsers_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/pointer/pointer_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/util/taints/taints_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/volume/metrics_du_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/volume/metrics_nil_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/volume/metrics_statfs_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/volume/plugins_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/volume/util/device_util_linux_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/volume/util/nested_volumes_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/volume/util/recyclerclient/recycler_client_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/volume/util/resize_util_test.go delete mode 100644 vendor/k8s.io/kubernetes/pkg/volume/util/util_test.go delete mode 100644 vendor/k8s.io/kubernetes/third_party/forked/golang/expansion/expand_test.go delete mode 100644 vendor/k8s.io/utils/exec/exec_test.go delete mode 100644 vendor/k8s.io/utils/exec/new_test.go diff --git a/.travis.yml b/.travis.yml index 0437f44a26..1ca90fc44a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -18,7 +18,7 @@ notifications: on_success: never go: - - 1.10.1 + - 1.10.2 go_import_path: k8s.io/ingress-nginx diff --git a/Gopkg.lock b/Gopkg.lock index 8fc5e9a268..a51286fc64 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -4,8 +4,8 @@ [[projects]] name = "cloud.google.com/go" packages = ["compute/metadata"] - revision = "2d3a6656c17a60b0815b7e06ab0be04eacb6e613" - version = "v0.16.0" + revision = "0fd7230b2a7505833d5f69b75cbd6c9582401479" + version = "v0.23.0" [[projects]] name = "github.com/Azure/go-autorest" @@ -15,20 +15,19 @@ "autorest/azure", "autorest/date" ] - revision = "ab5671379918d9af294b6f0e3d8aaa98c829416d" - version = "v9.4.0" + revision = "d4e6b95c12a08b4de2d48b45d5b4d594e5d32fab" [[projects]] branch = "master" name = "github.com/armon/go-proxyproto" packages = ["."] - revision = "48572f11356f1843b694f21a290d4f1006bc5e47" + revision = "5b7edb60ff5f69b60d1950397f7bde6171f1807d" [[projects]] branch = "master" name = "github.com/beorn7/perks" packages = ["quantile"] - revision = "4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9" + revision = "3a771d992973f24aa725d07868b467d1ddfceafb" [[projects]] name = "github.com/davecgh/go-spew" @@ -39,8 +38,8 @@ [[projects]] name = "github.com/dgrijalva/jwt-go" packages = ["."] - revision = "dbeaa9332f19a944acb5736b4456cfcc02140e29" - version = "v3.1.0" + revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" + version = "v3.2.0" [[projects]] name = "github.com/docker/distribution" @@ -74,14 +73,14 @@ [[projects]] name = "github.com/fsnotify/fsnotify" packages = ["."] - revision = "629574ca2a5df945712d3079857300b5e4da0236" - version = "v1.4.2" + revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" + version = "v1.4.7" [[projects]] branch = "master" name = "github.com/fullsailor/pkcs7" packages = ["."] - revision = "a009d8d7de53d9503c797cb8ec66fa3b21eed209" + revision = "ae226422660e5ca10db350d33f81c6608f3fbcdd" [[projects]] name = "github.com/ghodss/yaml" @@ -97,8 +96,8 @@ "protoc-gen-gogo/descriptor", "sortkeys" ] - revision = "342cbe0a04158f6dcb03ca0079991a51a4248c02" - version = "v0.5" + revision = "1adfc126b41513cc696b209667c8656ea7aac67c" + version = "v1.0.0" [[projects]] branch = "master" @@ -110,10 +109,9 @@ branch = "master" name = "github.com/golang/groupcache" packages = ["lru"] - revision = "84a468cf14b4376def5d68c722b139b881c450a4" + revision = "24b0969c4cb722950103eed87108c8d291a8df00" [[projects]] - branch = "master" name = "github.com/golang/protobuf" packages = [ "proto", @@ -122,7 +120,8 @@ "ptypes/duration", "ptypes/timestamp" ] - revision = "1643683e1b54a9e88ad26d98f81400c8c9d9f4f9" + revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" + version = "v1.1.0" [[projects]] branch = "master" @@ -137,8 +136,8 @@ "compiler", "extensions" ] - revision = "ee43cbb60db7bd22502942cccbc39059117352ab" - version = "v0.1.0" + revision = "7c663266750e7d82587642f65e60bc4083f1f84e" + version = "v0.2.0" [[projects]] branch = "master" @@ -152,7 +151,7 @@ "openstack/utils", "pagination" ] - revision = "0b6b13c4dd9e07a89f83cbe4617c13ad646d6362" + revision = "282f25e4025de0a42015d2e2b5faef1d920aad3c" [[projects]] branch = "master" @@ -161,7 +160,7 @@ ".", "simplelru" ] - revision = "0a025b7e63adc15a622f29b0b2c4c3848243bbf6" + revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3" [[projects]] branch = "master" @@ -178,14 +177,14 @@ [[projects]] name = "github.com/json-iterator/go" packages = ["."] - revision = "6240e1e7983a85228f7fd9c3e1b6932d46ec58e2" - version = "1.0.3" + revision = "ca39e5af3ece67bbcda3d0f4f56a8e24d9f2dad4" + version = "1.1.3" [[projects]] name = "github.com/kr/pty" packages = ["."] - revision = "95d05c1eef33a45bd58676b6ce28d105839b8d0b" - version = "v1.0.1" + revision = "282ce0e5322c82529687d609ee670fac7c7d917c" + version = "v1.1.1" [[projects]] branch = "master" @@ -212,7 +211,19 @@ branch = "master" name = "github.com/mitchellh/mapstructure" packages = ["."] - revision = "06020f85339e21b2478f756a78e295255ffa4d6a" + revision = "bb74f1db0675b241733089d5a1faa5dd8b0ef57b" + +[[projects]] + name = "github.com/modern-go/concurrent" + packages = ["."] + revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94" + version = "1.0.3" + +[[projects]] + name = "github.com/modern-go/reflect2" + packages = ["."] + revision = "1df9eeb2bb81f327b96228865c5687bc2194af3f" + version = "1.0.0" [[projects]] branch = "master" @@ -252,8 +263,8 @@ "reporters/stenographer/support/go-isatty", "types" ] - revision = "9eda700730cba42af70d53180f9dcce9266bc2bc" - version = "v1.4.0" + revision = "fa5fabab2a1bfbd924faf4c067d07ae414e2aedf" + version = "v1.5.0" [[projects]] name = "github.com/onsi/gomega" @@ -271,8 +282,8 @@ "matchers/support/goraph/util", "types" ] - revision = "c893efa28eb45626cdaa76c9f653b62488858837" - version = "v1.2.0" + revision = "62bff4df71bdbc266561a0caee19f0594b17c240" + version = "v1.4.0" [[projects]] name = "github.com/opencontainers/go-digest" @@ -317,7 +328,7 @@ branch = "master" name = "github.com/prometheus/client_model" packages = ["go"] - revision = "6f3806018612930941127f2a7c6c453ba2c527d2" + revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c" [[projects]] branch = "master" @@ -327,16 +338,18 @@ "internal/bitbucket.org/ww/goautoneg", "model" ] - revision = "e3fb1a1acd7605367a2b378bc2e2f893c05174b7" + revision = "7600349dcfe1abd18d72d3a1770870d9800a7801" [[projects]] branch = "master" name = "github.com/prometheus/procfs" packages = [ ".", + "internal/util", + "nfs", "xfs" ] - revision = "a6e9df898b1336106c743392c48ee0b71f5c4efa" + revision = "8b1c2da0d56deffdbb9e48d4414b4e674bd8083e" [[projects]] name = "github.com/spf13/afero" @@ -344,14 +357,14 @@ ".", "mem" ] - revision = "8d919cbe7e2627e417f3e45c3c0e489a5b7e2536" - version = "v1.0.0" + revision = "63644898a8da0bc22138abf860edaf5277b6102e" + version = "v1.1.0" [[projects]] name = "github.com/spf13/pflag" packages = ["."] - revision = "e57e3eeb33f795204c1ca35f56c44f83227c6e66" - version = "v1.0.0" + revision = "583c0c0531f06d5278b7d917446061adc344b5cd" + version = "v1.0.1" [[projects]] name = "github.com/zakjan/cert-chain-resolver" @@ -367,7 +380,7 @@ "ed25519/internal/edwards25519", "ssh/terminal" ] - revision = "6a293f2d4b14b8e6d3f0539e383f6d0d30fce3fd" + revision = "a3beeb748656e13e54256fd2cde19e058f41f60f" [[projects]] branch = "master" @@ -378,15 +391,15 @@ "html", "html/atom", "html/charset", + "http/httpguts", "http2", "http2/hpack", "idna", "internal/timeseries", - "lex/httplex", "publicsuffix", "trace" ] - revision = "a337091b0525af65de94df2eb7e98bd9962dcbe2" + revision = "dfa909b99c79129e1100513e5cd36307665e5723" [[projects]] branch = "master" @@ -398,7 +411,7 @@ "jws", "jwt" ] - revision = "9ff8ebcc8e241d46f52ecc5bff0e5a2f2dbef402" + revision = "770e5ebd4ab27c4d70b0983674d138217f5e2c72" [[projects]] branch = "master" @@ -407,10 +420,9 @@ "unix", "windows" ] - revision = "1e2299c37cc91a509f1b12369872d27be0ce98a6" + revision = "c11f84a56e43e20a78cee75a7c034031ecf57d1f" [[projects]] - branch = "master" name = "golang.org/x/text" packages = [ "collate", @@ -440,13 +452,14 @@ "unicode/norm", "unicode/rangetable" ] - revision = "88f656faf3f37f690df1a32515b479415e1a6769" + revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" + version = "v0.3.0" [[projects]] branch = "master" name = "golang.org/x/time" packages = ["rate"] - revision = "26559e0f760e39c24d730d3224364aef164ee23f" + revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" [[projects]] name = "google.golang.org/appengine" @@ -469,16 +482,21 @@ branch = "master" name = "google.golang.org/genproto" packages = ["googleapis/rpc/status"] - revision = "11c7f9e547da6db876260ce49ea7536985904c9b" + revision = "694d95ba50e67b2e363f3483057db5d4910c18f9" [[projects]] name = "google.golang.org/grpc" packages = [ ".", "balancer", + "balancer/base", + "balancer/roundrobin", + "channelz", "codes", "connectivity", "credentials", + "encoding", + "encoding/proto", "grpclb/grpc_lb_v1/messages", "grpclog", "internal", @@ -487,13 +505,15 @@ "naming", "peer", "resolver", + "resolver/dns", + "resolver/passthrough", "stats", "status", "tap", "transport" ] - revision = "5ffe3083946d5603a0578721101dc8165b1d5b5f" - version = "v1.7.2" + revision = "41344da2231b913fa3d983840a57a6b1b7b631a1" + version = "v1.12.0" [[projects]] name = "gopkg.in/fsnotify/fsnotify.v1" @@ -510,8 +530,8 @@ [[projects]] name = "gopkg.in/inf.v0" packages = ["."] - revision = "3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4" - version = "v0.9.0" + revision = "d2d2541c53f18d2a059457998ce2876cc8e67cbf" + version = "v0.9.1" [[projects]] name = "gopkg.in/square/go-jose.v2" @@ -525,10 +545,10 @@ version = "v2.1.6" [[projects]] - branch = "v2" name = "gopkg.in/yaml.v2" packages = ["."] - revision = "eb3733d160e74a9c7e442f435eb3bea458e1d19f" + revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" + version = "v2.2.1" [[projects]] name = "k8s.io/api" @@ -562,7 +582,7 @@ "storage/v1alpha1", "storage/v1beta1" ] - revision = "kubernetes-1.10.1" + revision = "kubernetes-1.10.3" [[projects]] name = "k8s.io/apiextensions-apiserver" @@ -574,7 +594,7 @@ "pkg/client/clientset/clientset/typed/apiextensions/v1beta1", "pkg/features" ] - revision = "kubernetes-1.10.1" + revision = "kubernetes-1.10.3" [[projects]] name = "k8s.io/apimachinery" @@ -632,7 +652,7 @@ "third_party/forked/golang/netutil", "third_party/forked/golang/reflect" ] - revision = "kubernetes-1.10.1" + revision = "kubernetes-1.10.3" [[projects]] name = "k8s.io/apiserver" @@ -645,7 +665,7 @@ "pkg/util/feature", "pkg/util/logs" ] - revision = "kubernetes-1.10.1" + revision = "kubernetes-1.10.3" [[projects]] name = "k8s.io/client-go" @@ -814,13 +834,13 @@ "util/retry", "util/workqueue" ] - revision = "kubernetes-1.10.1" + revision = "kubernetes-1.10.3" [[projects]] branch = "master" name = "k8s.io/kube-openapi" packages = ["pkg/util/proto"] - revision = "39a7bf85c140f972372c2a0d1ee40adbf0c8bfe1" + revision = "41e43949ca69d04b66104069ed3ffd619b289b3d" [[projects]] name = "k8s.io/kubernetes" @@ -869,17 +889,17 @@ "pkg/volume/util/recyclerclient", "third_party/forked/golang/expansion" ] - revision = "v1.10.1" + revision = "v1.10.3" [[projects]] branch = "master" name = "k8s.io/utils" packages = ["exec"] - revision = "bf963466fd3fea33c428098b12a89d8ecd012f25" + revision = "258e2a2fa64568210fbd6267cf1d8fd87c3cb86e" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "62df75064eae4ba4c59404c14d995f4d54774da2675b33295f8a14088886fa82" + inputs-digest = "5feeef324f0cbac72e0234d5f649fc7c4233f4e2bb4477e454e047b5461d7569" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 90f1f7a561..2d03b3d13c 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -25,6 +25,12 @@ go-tests = true unused-packages = true +# Don't prune helper scripts from code-generator +[[prune.project]] + name = "k8s.io/code-generator" + unused-packages = false + non-go = false + [[override]] name = "github.com/docker/distribution" revision = "edc3ab29cdff8694dd6feb85cfeb4b5f1b38ed9c" @@ -92,24 +98,24 @@ [[constraint]] name = "k8s.io/kubernetes" - revision = "v1.10.1" + revision = "v1.10.3" [[constraint]] name = "k8s.io/api" - revision = "kubernetes-1.10.1" + revision = "kubernetes-1.10.3" [[constraint]] name = "k8s.io/apimachinery" - revision = "kubernetes-1.10.1" + revision = "kubernetes-1.10.3" [[constraint]] name = "k8s.io/client-go" - revision = "kubernetes-1.10.1" + revision = "kubernetes-1.10.3" [[constraint]] name = "k8s.io/apiextensions-apiserver" - revision = "kubernetes-1.10.1" + revision = "kubernetes-1.10.3" [[constraint]] name = "k8s.io/apiserver" - revision = "kubernetes-1.10.1" + revision = "kubernetes-1.10.3" diff --git a/Makefile b/Makefile index feadb43404..3e21b33462 100644 --- a/Makefile +++ b/Makefile @@ -202,6 +202,7 @@ dep-ensure: dep version || go get -u github.com/golang/dep/cmd/dep dep ensure -v dep prune -v + find vendor -name '*_test.go' -delete .PHONY: dev-env dev-env: diff --git a/vendor/cloud.google.com/go/.travis.yml b/vendor/cloud.google.com/go/.travis.yml index decefd6bff..7dd0be2e07 100644 --- a/vendor/cloud.google.com/go/.travis.yml +++ b/vendor/cloud.google.com/go/.travis.yml @@ -1,10 +1,10 @@ sudo: false language: go go: -- 1.6 -- 1.7 -- 1.8 -- 1.9 +- 1.6.x +- 1.7.x +- 1.8.x +- 1.9.x install: - go get -v cloud.google.com/go/... script: @@ -14,6 +14,7 @@ script: GCLOUD_TESTS_GOLANG_KEY="$(pwd)/dulcet-port-762-key.json" GCLOUD_TESTS_GOLANG_FIRESTORE_PROJECT_ID="gcloud-golang-firestore-tests" GCLOUD_TESTS_GOLANG_FIRESTORE_KEY="$(pwd)/gcloud-golang-firestore-tests-key.json" + GCLOUD_TESTS_GOLANG_KEYRING="projects/dulcet-port-762/locations/us/keyRings/go-integration-test" ./run-tests.sh $TRAVIS_COMMIT env: matrix: diff --git a/vendor/cloud.google.com/go/CONTRIBUTING.md b/vendor/cloud.google.com/go/CONTRIBUTING.md index 95c94a48b4..09ded8fb25 100644 --- a/vendor/cloud.google.com/go/CONTRIBUTING.md +++ b/vendor/cloud.google.com/go/CONTRIBUTING.md @@ -31,11 +31,11 @@ To run the integrations tests, creating and configuration of a project in the Google Developers Console is required. After creating a project, you must [create a service account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#creatinganaccount). -Ensure the project-level **Owner** +Ensure the project-level **Owner** [IAM role](console.cloud.google.com/iam-admin/iam/project) role is added to the service account. Alternatively, the account can be granted all of the following roles: -- **Editor** -- **Logs Configuration Writer** +- **Editor** +- **Logs Configuration Writer** - **PubSub Admin** Once you create a project, set the following environment variables to be able to @@ -43,13 +43,19 @@ run the against the actual APIs. - **GCLOUD_TESTS_GOLANG_PROJECT_ID**: Developers Console project's ID (e.g. bamboo-shift-455) - **GCLOUD_TESTS_GOLANG_KEY**: The path to the JSON key file. -- **GCLOUD_TESTS_API_KEY**: Your API key. -Firestore requires a different project and key: +Some packages require additional environment variables to be set: -- **GCLOUD_TESTS_GOLANG_FIRESTORE_PROJECT_ID**: Developers Console project's ID - supporting Firestore -- **GCLOUD_TESTS_GOLANG_FIRESTORE_KEY**: The path to the JSON key file. +- firestore + - **GCLOUD_TESTS_GOLANG_FIRESTORE_PROJECT_ID**: project ID for Firestore. + - **GCLOUD_TESTS_GOLANG_FIRESTORE_KEY**: The path to the JSON key file. +- storage + - **GCLOUD_TESTS_GOLANG_KEYRING**: The full name of the keyring for the tests, in the + form "projects/P/locations/L/keyRings/R". +- translate + - **GCLOUD_TESTS_API_KEY**: API key for using the Translate API. +- profiler + - **GCLOUD_TESTS_GOLANG_ZONE**: Compute Engine zone. Install the [gcloud command-line tool][gcloudcli] to your machine and use it to create some resources used in integration tests. @@ -80,11 +86,20 @@ $ gcloud beta spanner instances create go-integration-test --config regional-us- # NOTE: Spanner instances are priced by the node-hour, so you may want to delete # the instance after testing with 'gcloud beta spanner instances delete'. - +# For Storage integration tests: +# Enable KMS for your project in the Cloud Console. +# Create a KMS keyring, in the same location as the default location for your project's buckets. +$ gcloud kms keyrings create MY_KEYRING --location MY_LOCATION +# Create two keys in the keyring, named key1 and key2. +$ gcloud kms keys create key1 --keyring MY_KEYRING --location MY_LOCATION --purpose encryption +$ gcloud kms keys create key2 --keyring MY_KEYRING --location MY_LOCATION --purpose encryption +# As mentioned above, set the GCLOUD_TESTS_GOLANG_KEYRING environment variable. +$ export GCLOUD_TESTS_GOLANG_KEYRING=projects/$GCLOUD_TESTS_GOLANG_PROJECT_ID/locations/MY_LOCATION/keyRings/MY_KEYRING +# Authorize Google Cloud Storage to encrypt and decrypt using key1. +gsutil kms authorize -p $GCLOUD_TESTS_GOLANG_PROJECT_ID -k $GCLOUD_TESTS_GOLANG_KEYRING/cryptoKeys/key1 ``` -Once you've set the environment variables, you can run the integration tests by -running: +Once you've done the necessary setup, you can run the integration tests by running: ``` sh $ go test -v cloud.google.com/go/... diff --git a/vendor/cloud.google.com/go/CONTRIBUTORS b/vendor/cloud.google.com/go/CONTRIBUTORS index d4b376c7cc..3b3cbed98e 100644 --- a/vendor/cloud.google.com/go/CONTRIBUTORS +++ b/vendor/cloud.google.com/go/CONTRIBUTORS @@ -22,10 +22,13 @@ David Symonds Filippo Valsorda Glenn Lewis Ingo Oeser +James Hall Johan Euphrosine Jonathan Amsterdam +Kunpei Sakai Luna Duclos Magnus Hiie +Mario Castro Michael McGreevy Omar Jarjur Paweł Knap diff --git a/vendor/cloud.google.com/go/LICENSE b/vendor/cloud.google.com/go/LICENSE index a4c5efd822..d645695673 100644 --- a/vendor/cloud.google.com/go/LICENSE +++ b/vendor/cloud.google.com/go/LICENSE @@ -187,7 +187,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2014 Google Inc. + 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. diff --git a/vendor/cloud.google.com/go/README.md b/vendor/cloud.google.com/go/README.md index 2dbfefc198..ac66000bc7 100644 --- a/vendor/cloud.google.com/go/README.md +++ b/vendor/cloud.google.com/go/README.md @@ -33,114 +33,221 @@ make backwards-incompatible changes. ## News -_October 30, 2017_ +_May 18, 2018_ -*v0.16.0* +*v0.23.0* -- Other bigquery changes: - - `JobIterator.Next` returns `*Job`; removed `JobInfo` (BREAKING CHANGE). - - UseStandardSQL is deprecated; set UseLegacySQL to true if you need - Legacy SQL. - - Uploader.Put will generate a random insert ID if you do not provide one. - - Support time partitioning for load jobs. - - Support dry-run queries. - - A `Job` remembers its last retrieved status. - - Support retrieving job configuration. - - Support labels for jobs and tables. - - Support dataset access lists. - - Improve support for external data sources, including data from Bigtable and - Google Sheets, and tables with external data. - - Support updating a table's view configuration. - - Fix uploading civil times with nanoseconds. +- bigquery: Add DDL stats to query statistics. +- bigtable: + - cbt: Add cells-per-column limit for row lookup. + - cbt: Make it possible to combine read filters. +- dlp: v2beta2 client removed. Use the v2 client instead. +- firestore, spanner: Fix compilation errors due to protobuf changes. -- storage: - - Support PubSub notifications. - - Support Requester Pays buckets. +_May 8, 2018_ -- profiler: Support goroutine and mutex profile types. +*v0.22.0* +- bigtable: + - cbt: Support cells per column limit for row read. + - bttest: Correctly handle empty RowSet. + - Fix ReadModifyWrite operation in emulator. + - Fix API path in GetCluster. -_October 3, 2017_ +- bigquery: + - BEHAVIOR CHANGE: Retry on 503 status code. + - Add dataset.DeleteWithContents. + - Add SchemaUpdateOptions for query jobs. + - Add Timeline to QueryStatistics. + - Add more stats to ExplainQueryStage. + - Support Parquet data format. -*v0.15.0* +- datastore: + - Support omitempty for times. -- firestore: beta release. See the - [announcement](https://firebase.googleblog.com/2017/10/introducing-cloud-firestore.html). +- dlp: + - **BREAKING CHANGE:** Remove v1beta1 client. Please migrate to the v2 client, + which is now out of beta. + - Add v2 client. -- errorreporting: The existing package has been redesigned. +- firestore: + - BEHAVIOR CHANGE: Treat set({}, MergeAll) as valid. -- errors: This package has been removed. Use errorreporting. +- iam: + - Support JWT signing via SignJwt callopt. +- profiler: + - BEHAVIOR CHANGE: PollForSerialOutput returns an error when context.Done. + - BEHAVIOR CHANGE: Increase the initial backoff to 1 minute. + - Avoid returning empty serial port output. -_September 28, 2017_ +- pubsub: + - BEHAVIOR CHANGE: Don't backoff during next retryable error once stream is healthy. + - BEHAVIOR CHANGE: Don't backoff on EOF. + - pstest: Support Acknowledge and ModifyAckDeadline RPCs. -*v0.14.0* +- redis: + - Add v1 beta Redis client. -- bigquery BREAKING CHANGES: - - Standard SQL is the default for queries and views. - - `Table.Create` takes `TableMetadata` as a second argument, instead of - options. - - `Dataset.Create` takes `DatasetMetadata` as a second argument. - - `DatasetMetadata` field `ID` renamed to `FullID` - - `TableMetadata` field `ID` renamed to `FullID` +- spanner: + - Support SessionLabels. -- Other bigquery changes: - - The client will append a random suffix to a provided job ID if you set - `AddJobIDSuffix` to true in a job config. - - Listing jobs is supported. - - Better retry logic. +- speech: + - Add api v1 beta1 client. -- vision, language, speech: clients are now stable +- storage: + - BEHAVIOR CHANGE: Retry reads when retryable error occurs. + - Fix delete of object in requester-pays bucket. + - Support KMS integration. -- monitoring: client is now beta +_April 9, 2018_ -- profiler: - - Rename InstanceName to Instance, ZoneName to Zone - - Auto-detect service name and version on AppEngine. +*v0.21.0* + +- bigquery: + - Add OpenCensus tracing. + +- firestore: + - **BREAKING CHANGE:** If a document does not exist, return a DocumentSnapshot + whose Exists method returns false. DocumentRef.Get and Transaction.Get + return the non-nil DocumentSnapshot in addition to a NotFound error. + **DocumentRef.GetAll and Transaction.GetAll return a non-nil + DocumentSnapshot instead of nil.** + - Add DocumentIterator.Stop. **Call Stop whenever you are done with a + DocumentIterator.** + - Added Query.Snapshots and DocumentRef.Snapshots, which provide realtime + notification of updates. See https://cloud.google.com/firestore/docs/query-data/listen. + - Canceling an RPC now always returns a grpc.Status with codes.Canceled. + +- spanner: + - Add `CommitTimestamp`, which supports inserting the commit timestamp of a + transaction into a column. + +_March 22, 2018_ + +*v0.20.0* + +- bigquery: Support SchemaUpdateOptions for load jobs. + +- bigtable: + - Add SampleRowKeys. + - cbt: Support union, intersection GCPolicy. + - Retry admin RPCS. + - Add trace spans to retries. + +- datastore: Add OpenCensus tracing. + +- firestore: + - Fix queries involving Null and NaN. + - Allow Timestamp protobuffers for time values. + +- logging: Add a WriteTimeout option. + +- spanner: Support Batch API. + +- storage: Add OpenCensus tracing. + + +_February 26, 2018_ + +*v0.19.0* + +- bigquery: + - Support customer-managed encryption keys. -_September 8, 2017_ +- bigtable: + - Improved emulator support. + - Support GetCluster. -*v0.13.0* +- datastore: + - Add general mutations. + - Support pointer struct fields. + - Support transaction options. -- bigquery: UseLegacySQL options for CreateTable and QueryConfig. Use these - options to continue using Legacy SQL after the client switches its default - to Standard SQL. +- firestore: + - Add Transaction.GetAll. + - Support document cursors. -- bigquery: Support for updating dataset labels. +- logging: + - Support concurrent RPCs to the service. + - Support per-entry resources. -- bigquery: Set DatasetIterator.ProjectID to list datasets in a project other - than the client's. DatasetsInProject is no longer needed and is deprecated. +- profiler: + - Add config options to disable heap and thread profiling. + - Read the project ID from $GOOGLE_CLOUD_PROJECT when it's set. + +- pubsub: + - BEHAVIOR CHANGE: Release flow control after ack/nack (instead of after the + callback returns). + - Add SubscriptionInProject. + - Add OpenCensus instrumentation for streaming pull. + +- storage: + - Support CORS. + + +_January 18, 2018_ -- bigtable: Fail ListInstances when any zones fail. +*v0.18.0* -- spanner: support decoding of slices of basic types (e.g. []string, []int64, - etc.) +- bigquery: + - Marked stable. + - Schema inference of nullable fields supported. + - Added TimePartitioning to QueryConfig. -- logging/logadmin: UpdateSink no longer creates a sink if it is missing - (actually a change to the underlying service, not the client) +- firestore: Data provided to DocumentRef.Set with a Merge option can contain + Delete sentinels. -- profiler: Service and ServiceVersion replace Target in Config. +- logging: Clients can accept parent resources other than projects. -_August 22, 2017_ +- pubsub: + - pubsub/pstest: A lighweight fake for pubsub. Experimental; feedback welcome. + - Support updating more subscription metadata: AckDeadline, + RetainAckedMessages and RetentionDuration. -*v0.12.0* +- oslogin/apiv1beta: New client for the Cloud OS Login API. -- pubsub: Subscription.Receive now uses streaming pull. +- rpcreplay: A package for recording and replaying gRPC traffic. -- pubsub: add Client.TopicInProject to access topics in a different project - than the client. +- spanner: + - Add a ReadWithOptions that supports a row limit, as well as an index. + - Support query plan and execution statistics. + - Added [OpenCensus](http://opencensus.io) support. -- errors: renamed errorreporting. The errors package will be removed shortly. +- storage: Clarify checksum validation for gzipped files (it is not validated + when the file is served uncompressed). -- datastore: improved retry behavior. -- bigquery: support updates to dataset metadata, with etags. +_December 11, 2017_ -- bigquery: add etag support to Table.Update (BREAKING: etag argument added). +*v0.17.0* -- bigquery: generate all job IDs on the client. +- firestore BREAKING CHANGES: + - Remove UpdateMap and UpdateStruct; rename UpdatePaths to Update. + Change + `docref.UpdateMap(ctx, map[string]interface{}{"a.b", 1})` + to + `docref.Update(ctx, []firestore.Update{{Path: "a.b", Value: 1}})` -- storage: support bucket lifecycle configurations. + Change + `docref.UpdateStruct(ctx, []string{"Field"}, aStruct)` + to + `docref.Update(ctx, []firestore.Update{{Path: "Field", Value: aStruct.Field}})` + - Rename MergePaths to Merge; require args to be FieldPaths + - A value stored as an integer can be read into a floating-point field, and vice versa. +- bigtable/cmd/cbt: + - Support deleting a column. + - Add regex option for row read. +- spanner: Mark stable. +- storage: + - Add Reader.ContentEncoding method. + - Fix handling of SignedURL headers. +- bigquery: + - If Uploader.Put is called with no rows, it returns nil without making a + call. + - Schema inference supports the "nullable" option in struct tags for + non-required fields. + - TimePartitioning supports "Field". [Older news](https://github.com/GoogleCloudPlatform/google-cloud-go/blob/master/old-news.md) @@ -149,22 +256,25 @@ _August 22, 2017_ Google API | Status | Package ---------------------------------|--------------|----------------------------------------------------------- +[BigQuery][cloud-bigquery] | stable | [`cloud.google.com/go/bigquery`][cloud-bigquery-ref] +[Bigtable][cloud-bigtable] | stable | [`cloud.google.com/go/bigtable`][cloud-bigtable-ref] +[Container][cloud-container] | alpha | [`cloud.google.com/go/container/apiv1`][cloud-container-ref] +[Data Loss Prevention][cloud-dlp]| alpha | [`cloud.google.com/go/dlp/apiv2beta1`][cloud-dlp-ref] [Datastore][cloud-datastore] | stable | [`cloud.google.com/go/datastore`][cloud-datastore-ref] +[Debugger][cloud-debugger] | alpha | [`cloud.google.com/go/debugger/apiv2`][cloud-debugger-ref] +[ErrorReporting][cloud-errors] | alpha | [`cloud.google.com/go/errorreporting`][cloud-errors-ref] [Firestore][cloud-firestore] | beta | [`cloud.google.com/go/firestore`][cloud-firestore-ref] -[Storage][cloud-storage] | stable | [`cloud.google.com/go/storage`][cloud-storage-ref] -[Bigtable][cloud-bigtable] | beta | [`cloud.google.com/go/bigtable`][cloud-bigtable-ref] -[BigQuery][cloud-bigquery] | beta | [`cloud.google.com/go/bigquery`][cloud-bigquery-ref] +[Language][cloud-language] | stable | [`cloud.google.com/go/language/apiv1`][cloud-language-ref] [Logging][cloud-logging] | stable | [`cloud.google.com/go/logging`][cloud-logging-ref] [Monitoring][cloud-monitoring] | beta | [`cloud.google.com/go/monitoring/apiv3`][cloud-monitoring-ref] +[OS Login][cloud-oslogin] | alpha | [`cloud.google.com/compute/docs/oslogin/rest`][cloud-oslogin-ref] [Pub/Sub][cloud-pubsub] | beta | [`cloud.google.com/go/pubsub`][cloud-pubsub-ref] -[Vision][cloud-vision] | stable | [`cloud.google.com/go/vision/apiv1`][cloud-vision-ref] -[Language][cloud-language] | stable | [`cloud.google.com/go/language/apiv1`][cloud-language-ref] +[Spanner][cloud-spanner] | stable | [`cloud.google.com/go/spanner`][cloud-spanner-ref] [Speech][cloud-speech] | stable | [`cloud.google.com/go/speech/apiv1`][cloud-speech-ref] -[Spanner][cloud-spanner] | beta | [`cloud.google.com/go/spanner`][cloud-spanner-ref] +[Storage][cloud-storage] | stable | [`cloud.google.com/go/storage`][cloud-storage-ref] [Translation][cloud-translation] | stable | [`cloud.google.com/go/translate`][cloud-translation-ref] -[Trace][cloud-trace] | alpha | [`cloud.google.com/go/trace`][cloud-trace-ref] [Video Intelligence][cloud-video]| beta | [`cloud.google.com/go/videointelligence/apiv1beta1`][cloud-video-ref] -[ErrorReporting][cloud-errors] | alpha | [`cloud.google.com/go/errorreporting`][cloud-errors-ref] +[Vision][cloud-vision] | stable | [`cloud.google.com/go/vision/apiv1`][cloud-vision-ref] > **Alpha status**: the API is still being actively developed. As a @@ -519,6 +629,9 @@ for more information. [cloud-language]: https://cloud.google.com/natural-language [cloud-language-ref]: https://godoc.org/cloud.google.com/go/language/apiv1 +[cloud-oslogin]: https://cloud.google.com/compute/docs/oslogin/rest +[cloud-oslogin-ref]: https://cloud.google.com/compute/docs/oslogin/rest + [cloud-speech]: https://cloud.google.com/speech [cloud-speech-ref]: https://godoc.org/cloud.google.com/go/speech/apiv1 @@ -529,13 +642,19 @@ for more information. [cloud-translation]: https://cloud.google.com/translation [cloud-translation-ref]: https://godoc.org/cloud.google.com/go/translation -[cloud-trace]: https://cloud.google.com/trace/ -[cloud-trace-ref]: https://godoc.org/cloud.google.com/go/trace - [cloud-video]: https://cloud.google.com/video-intelligence/ [cloud-video-ref]: https://godoc.org/cloud.google.com/go/videointelligence/apiv1beta1 [cloud-errors]: https://cloud.google.com/error-reporting/ [cloud-errors-ref]: https://godoc.org/cloud.google.com/go/errorreporting +[cloud-container]: https://cloud.google.com/containers/ +[cloud-container-ref]: https://godoc.org/cloud.google.com/go/container/apiv1 + +[cloud-debugger]: https://cloud.google.com/debugger/ +[cloud-debugger-ref]: https://godoc.org/cloud.google.com/go/debugger/apiv2 + +[cloud-dlp]: https://cloud.google.com/dlp/ +[cloud-dlp-ref]: https://godoc.org/cloud.google.com/go/dlp/apiv2beta1 + [default-creds]: https://developers.google.com/identity/protocols/application-default-credentials diff --git a/vendor/cloud.google.com/go/RELEASING.md b/vendor/cloud.google.com/go/RELEASING.md new file mode 100644 index 0000000000..c2735c53b3 --- /dev/null +++ b/vendor/cloud.google.com/go/RELEASING.md @@ -0,0 +1,13 @@ +# How to Release this Repo + +1. Determine the current release version with `git tag -l`. It should look + something like `vX.Y.Z`. We'll call the current + version `$CV` and the new version `$NV`. +1. On master, run `git log $CV..` to list all the changes since the last + release. +1. Edit the News section of `README.md` to include a summary of the changes. +1. Mail the CL containing the `README.md` changes. When the CL is approved, submit it. +1. Without submitting any other CLs: + a. Switch to master. + b. Tag the repo with the next version: `git tag $NV`. + c. Push the tag: `git push origin $NV`. diff --git a/vendor/cloud.google.com/go/authexample_test.go b/vendor/cloud.google.com/go/authexample_test.go deleted file mode 100644 index fe75467f94..0000000000 --- a/vendor/cloud.google.com/go/authexample_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cloud_test - -import ( - "cloud.google.com/go/datastore" - "golang.org/x/net/context" - "google.golang.org/api/option" -) - -func Example_applicationDefaultCredentials() { - // Google Application Default Credentials is the recommended way to authorize - // and authenticate clients. - // - // See the following link on how to create and obtain Application Default Credentials: - // https://developers.google.com/identity/protocols/application-default-credentials. - client, err := datastore.NewClient(context.Background(), "project-id") - if err != nil { - // TODO: handle error. - } - _ = client // Use the client. -} - -func Example_serviceAccountFile() { - // Use a JSON key file associated with a Google service account to - // authenticate and authorize. Service Account keys can be created and - // downloaded from https://console.developers.google.com/permissions/serviceaccounts. - // - // Note: This example uses the datastore client, but the same steps apply to - // the other client libraries underneath this package. - client, err := datastore.NewClient(context.Background(), - "project-id", option.WithServiceAccountFile("/path/to/service-account-key.json")) - if err != nil { - // TODO: handle error. - } - _ = client // Use the client. -} diff --git a/vendor/cloud.google.com/go/cloud.go b/vendor/cloud.google.com/go/cloud.go index 6ba428dc63..5c85221463 100644 --- a/vendor/cloud.google.com/go/cloud.go +++ b/vendor/cloud.google.com/go/cloud.go @@ -12,9 +12,60 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package cloud is the root of the packages used to access Google Cloud -// Services. See https://godoc.org/cloud.google.com/go for a full list -// of sub-packages. -// -// This package documents how to authorize and authenticate the sub packages. +/* +Package cloud is the root of the packages used to access Google Cloud +Services. See https://godoc.org/cloud.google.com/go for a full list +of sub-packages. + + +Authentication and Authorization + +All the clients in sub-packages support authentication via Google Application Default +Credentials (see https://cloud.google.com/docs/authentication/production), or +by providing a JSON key file for a Service Account. See the authentication examples +in this package for details. + + +Timeouts and Cancellation + +By default, all requests in sub-packages will run indefinitely, retrying on transient +errors when correctness allows. To set timeouts or arrange for cancellation, use +contexts. See the examples for details. + +Do not attempt to control the initial connection (dialing) of a service by setting a +timeout on the context passed to NewClient. Dialing is non-blocking, so timeouts +would be ineffective and would only interfere with credential refreshing, which uses +the same context. + + +Connection Pooling + +Connection pooling differs in clients based on their transport. Cloud +clients either rely on HTTP or gRPC transports to communicate +with Google Cloud. + +Cloud clients that use HTTP (bigquery, compute, storage, and translate) rely on the +underlying HTTP transport to cache connections for later re-use. These are cached to +the default http.MaxIdleConns and http.MaxIdleConnsPerHost settings in +http.DefaultTransport. + +For gPRC clients (all others in this repo), connection pooling is configurable. Users +of cloud client libraries may specify option.WithGRPCConnectionPool(n) as a client +option to NewClient calls. This configures the underlying gRPC connections to be +pooled and addressed in a round robin fashion. + + +Using the Libraries with Docker + +Minimal docker images like Alpine lack CA certificates. This causes RPCs to appear to +hang, because gRPC retries indefinitely. See https://github.com/GoogleCloudPlatform/google-cloud-go/issues/928 +for more information. + +Debugging + +To see gRPC logs, set the environment variable GRPC_GO_LOG_SEVERITY_LEVEL. See +https://godoc.org/google.golang.org/grpc/grpclog for more information. + +For HTTP logging, set the GODEBUG environment variable to "http2debug=1" or "http2debug=2". +*/ package cloud // import "cloud.google.com/go" diff --git a/vendor/cloud.google.com/go/compute/metadata/metadata_test.go b/vendor/cloud.google.com/go/compute/metadata/metadata_test.go deleted file mode 100644 index 9ac5926918..0000000000 --- a/vendor/cloud.google.com/go/compute/metadata/metadata_test.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package metadata - -import ( - "os" - "sync" - "testing" -) - -func TestOnGCE_Stress(t *testing.T) { - if testing.Short() { - t.Skip("skipping in -short mode") - } - var last bool - for i := 0; i < 100; i++ { - onGCEOnce = sync.Once{} - - now := OnGCE() - if i > 0 && now != last { - t.Errorf("%d. changed from %v to %v", i, last, now) - } - last = now - } - t.Logf("OnGCE() = %v", last) -} - -func TestOnGCE_Force(t *testing.T) { - onGCEOnce = sync.Once{} - old := os.Getenv(metadataHostEnv) - defer os.Setenv(metadataHostEnv, old) - os.Setenv(metadataHostEnv, "127.0.0.1") - if !OnGCE() { - t.Error("OnGCE() = false; want true") - } -} diff --git a/vendor/cloud.google.com/go/issue_template.md b/vendor/cloud.google.com/go/issue_template.md new file mode 100644 index 0000000000..e2ccef3e78 --- /dev/null +++ b/vendor/cloud.google.com/go/issue_template.md @@ -0,0 +1,17 @@ +(delete this for feature requests) + +## Client + +e.g. PubSub + +## Describe Your Environment + +e.g. Alpine Docker on GKE + +## Expected Behavior + +e.g. Messages arrive really fast. + +## Actual Behavior + +e.g. Messages arrive really slowly. \ No newline at end of file diff --git a/vendor/cloud.google.com/go/license_test.go b/vendor/cloud.google.com/go/license_test.go deleted file mode 100644 index 4b87878a02..0000000000 --- a/vendor/cloud.google.com/go/license_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2016 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package cloud - -import ( - "bytes" - "io/ioutil" - "os" - "path/filepath" - "strings" - "testing" -) - -var sentinels = []string{ - "Copyright", - "Google Inc", - `Licensed under the Apache License, Version 2.0 (the "License");`, -} - -func TestLicense(t *testing.T) { - err := filepath.Walk(".", func(path string, fi os.FileInfo, err error) error { - if err != nil { - return err - } - - if ext := filepath.Ext(path); ext != ".go" && ext != ".proto" { - return nil - } - if strings.HasSuffix(path, ".pb.go") { - // .pb.go files are generated from the proto files. - // .proto files must have license headers. - return nil - } - if path == "bigtable/cmd/cbt/cbtdoc.go" { - // Automatically generated. - return nil - } - - src, err := ioutil.ReadFile(path) - if err != nil { - return nil - } - src = src[:140] // Ensure all of the sentinel values are at the top of the file. - - // Find license - for _, sentinel := range sentinels { - if !bytes.Contains(src, []byte(sentinel)) { - t.Errorf("%v: license header not present. want %q", path, sentinel) - return nil - } - } - - return nil - }) - if err != nil { - t.Fatal(err) - } -} diff --git a/vendor/cloud.google.com/go/old-news.md b/vendor/cloud.google.com/go/old-news.md index 896980d96c..a0bd83be93 100644 --- a/vendor/cloud.google.com/go/old-news.md +++ b/vendor/cloud.google.com/go/old-news.md @@ -1,3 +1,113 @@ +_October 30, 2017_ + +*v0.16.0* + +- Other bigquery changes: + - `JobIterator.Next` returns `*Job`; removed `JobInfo` (BREAKING CHANGE). + - UseStandardSQL is deprecated; set UseLegacySQL to true if you need + Legacy SQL. + - Uploader.Put will generate a random insert ID if you do not provide one. + - Support time partitioning for load jobs. + - Support dry-run queries. + - A `Job` remembers its last retrieved status. + - Support retrieving job configuration. + - Support labels for jobs and tables. + - Support dataset access lists. + - Improve support for external data sources, including data from Bigtable and + Google Sheets, and tables with external data. + - Support updating a table's view configuration. + - Fix uploading civil times with nanoseconds. + +- storage: + - Support PubSub notifications. + - Support Requester Pays buckets. + +- profiler: Support goroutine and mutex profile types. + + +_October 3, 2017_ + +*v0.15.0* + +- firestore: beta release. See the + [announcement](https://firebase.googleblog.com/2017/10/introducing-cloud-firestore.html). + +- errorreporting: The existing package has been redesigned. + +- errors: This package has been removed. Use errorreporting. + + +_September 28, 2017_ + +*v0.14.0* + +- bigquery BREAKING CHANGES: + - Standard SQL is the default for queries and views. + - `Table.Create` takes `TableMetadata` as a second argument, instead of + options. + - `Dataset.Create` takes `DatasetMetadata` as a second argument. + - `DatasetMetadata` field `ID` renamed to `FullID` + - `TableMetadata` field `ID` renamed to `FullID` + +- Other bigquery changes: + - The client will append a random suffix to a provided job ID if you set + `AddJobIDSuffix` to true in a job config. + - Listing jobs is supported. + - Better retry logic. + +- vision, language, speech: clients are now stable + +- monitoring: client is now beta + +- profiler: + - Rename InstanceName to Instance, ZoneName to Zone + - Auto-detect service name and version on AppEngine. + +_September 8, 2017_ + +*v0.13.0* + +- bigquery: UseLegacySQL options for CreateTable and QueryConfig. Use these + options to continue using Legacy SQL after the client switches its default + to Standard SQL. + +- bigquery: Support for updating dataset labels. + +- bigquery: Set DatasetIterator.ProjectID to list datasets in a project other + than the client's. DatasetsInProject is no longer needed and is deprecated. + +- bigtable: Fail ListInstances when any zones fail. + +- spanner: support decoding of slices of basic types (e.g. []string, []int64, + etc.) + +- logging/logadmin: UpdateSink no longer creates a sink if it is missing + (actually a change to the underlying service, not the client) + +- profiler: Service and ServiceVersion replace Target in Config. + +_August 22, 2017_ + +*v0.12.0* + +- pubsub: Subscription.Receive now uses streaming pull. + +- pubsub: add Client.TopicInProject to access topics in a different project + than the client. + +- errors: renamed errorreporting. The errors package will be removed shortly. + +- datastore: improved retry behavior. + +- bigquery: support updates to dataset metadata, with etags. + +- bigquery: add etag support to Table.Update (BREAKING: etag argument added). + +- bigquery: generate all job IDs on the client. + +- storage: support bucket lifecycle configurations. + + _July 31, 2017_ *v0.11.0* diff --git a/vendor/cloud.google.com/go/regen-gapic.sh b/vendor/cloud.google.com/go/regen-gapic.sh new file mode 100755 index 0000000000..eede862693 --- /dev/null +++ b/vendor/cloud.google.com/go/regen-gapic.sh @@ -0,0 +1,68 @@ +#!/bin/bash + +# This script generates all GAPIC clients in this repo. +# One-time setup: +# cd path/to/googleapis # https://github.com/googleapis/googleapis +# virtualenv env +# . env/bin/activate +# pip install googleapis-artman +# deactivate +# +# Regenerate: +# cd path/to/googleapis +# . env/bin/activate +# $GOPATH/src/cloud.google.com/go/regen-gapic.sh +# deactivate +# +# Being in googleapis directory is important; +# that's where we find YAML files and where artman puts the "artman-genfiles" directory. +# +# NOTE: This script does not generate the "raw" gRPC client found in google.golang.org/genproto. +# To do that, use the regen.sh script in the genproto repo instead. + +set -ex + +APIS=( +google/iam/artman_iam_admin.yaml +google/cloud/bigquery/datatransfer/artman_bigquerydatatransfer.yaml +google/cloud/dataproc/artman_dataproc_v1.yaml +google/cloud/dialogflow/artman_dialogflow_v2.yaml +google/cloud/language/artman_language_v1.yaml +google/cloud/language/artman_language_v1beta2.yaml +google/cloud/oslogin/artman_oslogin_v1beta.yaml +google/cloud/redis/artman_redis_v1beta1.yaml +google/cloud/speech/artman_speech_v1.yaml +google/cloud/speech/artman_speech_v1beta1.yaml +google/cloud/speech/artman_speech_v1p1beta1.yaml +google/cloud/tasks/artman_cloudtasks.yaml +google/cloud/videointelligence/artman_videointelligence_v1beta1.yaml +google/cloud/videointelligence/artman_videointelligence_v1beta2.yaml +google/cloud/vision/artman_vision_v1.yaml +google/cloud/vision/artman_vision_v1p1beta1.yaml +google/container/artman_container.yaml +google/devtools/artman_clouddebugger.yaml +google/devtools/clouderrorreporting/artman_errorreporting.yaml +google/devtools/cloudtrace/artman_cloudtrace_v1.yaml +google/devtools/cloudtrace/artman_cloudtrace_v2.yaml +google/firestore/artman_firestore.yaml +google/logging/artman_logging.yaml +google/longrunning/artman_longrunning.yaml +google/monitoring/artman_monitoring.yaml +google/privacy/dlp/artman_dlp_v2.yaml +google/pubsub/artman_pubsub.yaml +google/spanner/admin/database/artman_spanner_admin_database.yaml +google/spanner/admin/instance/artman_spanner_admin_instance.yaml +google/spanner/artman_spanner.yaml +) + +for api in "${APIS[@]}"; do + rm -rf artman-genfiles/* + artman --config "$api" generate go_gapic + cp -r artman-genfiles/gapi-*/cloud.google.com/go/* $GOPATH/src/cloud.google.com/go/ +done + +#go list cloud.google.com/go/... | grep apiv | xargs go test + +#go test -short cloud.google.com/go/... + +#echo "googleapis version: $(git rev-parse HEAD)" diff --git a/vendor/cloud.google.com/go/run-tests.sh b/vendor/cloud.google.com/go/run-tests.sh index f47ff50a5e..a643e61c47 100755 --- a/vendor/cloud.google.com/go/run-tests.sh +++ b/vendor/cloud.google.com/go/run-tests.sh @@ -70,8 +70,8 @@ function depends_on_changed_package { return 1 } -# Collect the packages into two separate lists. (It is faster go test a list of -# packages than to individually go test each one.) +# Collect the packages into two separate lists. (It is faster to call "go test" on a +# list of packages than to individually "go test" each one.) shorts= fulls= diff --git a/vendor/github.com/Azure/go-autorest/CHANGELOG.md b/vendor/github.com/Azure/go-autorest/CHANGELOG.md index dbfd85fbe0..c4169b0bbf 100644 --- a/vendor/github.com/Azure/go-autorest/CHANGELOG.md +++ b/vendor/github.com/Azure/go-autorest/CHANGELOG.md @@ -1,5 +1,98 @@ # CHANGELOG +## v9.9.0 + +### New Features + +- Added EventGridKeyAuthorizer for key authorization with event grid topics. + +### Bug Fixes + +- Fixed race condition when auto-refreshing service principal tokens. + +## v9.8.1 + +### Bug Fixes + +- Added http.StatusNoContent (204) to the list of expected status codes for long-running operations. +- Updated runtime version info so it's current. + +## v9.8.0 + +### New Features + +- Added type azure.AsyncOpIncompleteError to be returned from a future's Result() method when the operation has not completed. + +## v9.7.1 + +### Bug Fixes + +- Use correct AAD and Graph endpoints for US Gov environment. + +## v9.7.0 + +### New Features + +- Added support for application/octet-stream MIME types. + +## v9.6.1 + +### Bug Fixes + +- Ensure Authorization header is added to request when polling for registration status. + +## v9.6.0 + +### New Features + +- Added support for acquiring tokens via MSI with a user assigned identity. + +## v9.5.3 + +### Bug Fixes +- Don't remove encoding of existing URL Query parameters when calling autorest.WithQueryParameters. +- Set correct Content Type when using autorest.WithFormData. + +## v9.5.2 + +### Bug Fixes + +- Check for nil *http.Response before dereferencing it. + +## v9.5.1 + +### Bug Fixes + +- Don't count http.StatusTooManyRequests (429) against the retry cap. +- Use retry logic when SkipResourceProviderRegistration is set to true. + +## v9.5.0 + +### New Features + +- Added support for username + password, API key, authoriazation code and cognitive services authentication. +- Added field SkipResourceProviderRegistration to clients to provide a way to skip auto-registration of RPs. +- Added utility function AsStringSlice() to convert its parameters to a string slice. + +### Bug Fixes + +- When checking for authentication failures look at the error type not the status code as it could vary. + +## v9.4.2 + +### Bug Fixes + +- Validate parameters when creating credentials. +- Don't retry requests if the returned status is a 401 (http.StatusUnauthorized) as it will never succeed. + +## v9.4.1 + +### Bug Fixes + +- Update the AccessTokensPath() to read access tokens path through AZURE_ACCESS_TOKEN_FILE. If this + environment variable is not set, it will fall back to use default path set by Azure CLI. +- Use case-insensitive string comparison for polling states. + ## v9.4.0 ### New Features @@ -106,7 +199,7 @@ Support for UNIX time. - Added telemetry. ## v7.2.3 -- Fixing bug in calls to `DelayForBackoff` that caused doubling of delay +- Fixing bug in calls to `DelayForBackoff` that caused doubling of delay duration. ## v7.2.2 diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/README.md b/vendor/github.com/Azure/go-autorest/autorest/adal/README.md index a17cf98c62..08966c9cf8 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/README.md +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/README.md @@ -218,6 +218,40 @@ if (err == nil) { } ``` +#### Username password authenticate + +```Go +spt, err := adal.NewServicePrincipalTokenFromUsernamePassword( + oauthConfig, + applicationID, + username, + password, + resource, + callbacks...) + +if (err == nil) { + token := spt.Token +} +``` + +#### Authorization code authenticate + +``` Go +spt, err := adal.NewServicePrincipalTokenFromAuthorizationCode( + oauthConfig, + applicationID, + clientSecret, + authorizationCode, + redirectURI, + resource, + callbacks...) + +err = spt.Refresh() +if (err == nil) { + token := spt.Token +} +``` + ### Command Line Tool A command line tool is available in `cmd/adal.go` that can acquire a token for a given resource. It supports all flows mentioned above. diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/config.go b/vendor/github.com/Azure/go-autorest/autorest/adal/config.go index 49e9214d59..f570d540a6 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/config.go +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/config.go @@ -32,8 +32,24 @@ type OAuthConfig struct { DeviceCodeEndpoint url.URL } +// IsZero returns true if the OAuthConfig object is zero-initialized. +func (oac OAuthConfig) IsZero() bool { + return oac == OAuthConfig{} +} + +func validateStringParam(param, name string) error { + if len(param) == 0 { + return fmt.Errorf("parameter '" + name + "' cannot be empty") + } + return nil +} + // NewOAuthConfig returns an OAuthConfig with tenant specific urls func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { + if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil { + return nil, err + } + // it's legal for tenantID to be empty so don't validate it const activeDirectoryEndpointTemplate = "%s/oauth2/%s?api-version=%s" u, err := url.Parse(activeDirectoryEndpoint) if err != nil { diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/config_test.go b/vendor/github.com/Azure/go-autorest/autorest/adal/config_test.go deleted file mode 100644 index 304280f664..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/config_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "testing" -) - -func TestNewOAuthConfig(t *testing.T) { - const testActiveDirectoryEndpoint = "https://login.test.com" - const testTenantID = "tenant-id-test" - - config, err := NewOAuthConfig(testActiveDirectoryEndpoint, testTenantID) - if err != nil { - t.Fatalf("autorest/adal: Unexpected error while creating oauth configuration for tenant: %v.", err) - } - - expected := "https://login.test.com/tenant-id-test/oauth2/authorize?api-version=1.0" - if config.AuthorizeEndpoint.String() != expected { - t.Fatalf("autorest/adal: Incorrect authorize url for Tenant from Environment. expected(%s). actual(%v).", expected, config.AuthorizeEndpoint) - } - - expected = "https://login.test.com/tenant-id-test/oauth2/token?api-version=1.0" - if config.TokenEndpoint.String() != expected { - t.Fatalf("autorest/adal: Incorrect authorize url for Tenant from Environment. expected(%s). actual(%v).", expected, config.TokenEndpoint) - } - - expected = "https://login.test.com/tenant-id-test/oauth2/devicecode?api-version=1.0" - if config.DeviceCodeEndpoint.String() != expected { - t.Fatalf("autorest/adal Incorrect devicecode url for Tenant from Environment. expected(%s). actual(%v).", expected, config.DeviceCodeEndpoint) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken_test.go b/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken_test.go deleted file mode 100644 index 6beee161fa..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken_test.go +++ /dev/null @@ -1,330 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" - "testing" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -const ( - TestResource = "SomeResource" - TestClientID = "SomeClientID" - TestTenantID = "SomeTenantID" - TestActiveDirectoryEndpoint = "https://login.test.com/" -) - -var ( - testOAuthConfig, _ = NewOAuthConfig(TestActiveDirectoryEndpoint, TestTenantID) - TestOAuthConfig = *testOAuthConfig -) - -const MockDeviceCodeResponse = ` -{ - "device_code": "10000-40-1234567890", - "user_code": "ABCDEF", - "verification_url": "http://aka.ms/deviceauth", - "expires_in": "900", - "interval": "0" -} -` - -const MockDeviceTokenResponse = `{ - "access_token": "accessToken", - "refresh_token": "refreshToken", - "expires_in": "1000", - "expires_on": "2000", - "not_before": "3000", - "resource": "resource", - "token_type": "type" -} -` - -func TestDeviceCodeIncludesResource(t *testing.T) { - sender := mocks.NewSender() - sender.AppendResponse(mocks.NewResponseWithContent(MockDeviceCodeResponse)) - - code, err := InitiateDeviceAuth(sender, TestOAuthConfig, TestClientID, TestResource) - if err != nil { - t.Fatalf("adal: unexpected error initiating device auth") - } - - if code.Resource != TestResource { - t.Fatalf("adal: InitiateDeviceAuth failed to stash the resource in the DeviceCode struct") - } -} - -func TestDeviceCodeReturnsErrorIfSendingFails(t *testing.T) { - sender := mocks.NewSender() - sender.SetError(fmt.Errorf("this is an error")) - - _, err := InitiateDeviceAuth(sender, TestOAuthConfig, TestClientID, TestResource) - if err == nil || !strings.Contains(err.Error(), errCodeSendingFails) { - t.Fatalf("adal: failed to get correct error expected(%s) actual(%s)", errCodeSendingFails, err.Error()) - } -} - -func TestDeviceCodeReturnsErrorIfBadRequest(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody("doesn't matter") - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusBadRequest, "Bad Request")) - - _, err := InitiateDeviceAuth(sender, TestOAuthConfig, TestClientID, TestResource) - if err == nil || !strings.Contains(err.Error(), errCodeHandlingFails) { - t.Fatalf("adal: failed to get correct error expected(%s) actual(%s)", errCodeHandlingFails, err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceCodeReturnsErrorIfCannotDeserializeDeviceCode(t *testing.T) { - gibberishJSON := strings.Replace(MockDeviceCodeResponse, "expires_in", "\":, :gibberish", -1) - sender := mocks.NewSender() - body := mocks.NewBody(gibberishJSON) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK")) - - _, err := InitiateDeviceAuth(sender, TestOAuthConfig, TestClientID, TestResource) - if err == nil || !strings.Contains(err.Error(), errCodeHandlingFails) { - t.Fatalf("adal: failed to get correct error expected(%s) actual(%s)", errCodeHandlingFails, err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceCodeReturnsErrorIfEmptyDeviceCode(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody("") - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK")) - - _, err := InitiateDeviceAuth(sender, TestOAuthConfig, TestClientID, TestResource) - if err != ErrDeviceCodeEmpty { - t.Fatalf("adal: failed to get correct error expected(%s) actual(%s)", ErrDeviceCodeEmpty, err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func deviceCode() *DeviceCode { - var deviceCode DeviceCode - _ = json.Unmarshal([]byte(MockDeviceCodeResponse), &deviceCode) - deviceCode.Resource = TestResource - deviceCode.ClientID = TestClientID - return &deviceCode -} - -func TestDeviceTokenReturns(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(MockDeviceTokenResponse) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK")) - - _, err := WaitForUserCompletion(sender, deviceCode()) - if err != nil { - t.Fatalf("adal: got error unexpectedly") - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorIfSendingFails(t *testing.T) { - sender := mocks.NewSender() - sender.SetError(fmt.Errorf("this is an error")) - - _, err := WaitForUserCompletion(sender, deviceCode()) - if err == nil || !strings.Contains(err.Error(), errTokenSendingFails) { - t.Fatalf("adal: failed to get correct error expected(%s) actual(%s)", errTokenSendingFails, err.Error()) - } -} - -func TestDeviceTokenReturnsErrorIfServerError(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody("") - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusInternalServerError, "Internal Server Error")) - - _, err := WaitForUserCompletion(sender, deviceCode()) - if err == nil || !strings.Contains(err.Error(), errTokenHandlingFails) { - t.Fatalf("adal: failed to get correct error expected(%s) actual(%s)", errTokenHandlingFails, err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorIfCannotDeserializeDeviceToken(t *testing.T) { - gibberishJSON := strings.Replace(MockDeviceTokenResponse, "expires_in", ";:\"gibberish", -1) - sender := mocks.NewSender() - body := mocks.NewBody(gibberishJSON) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK")) - - _, err := WaitForUserCompletion(sender, deviceCode()) - if err == nil || !strings.Contains(err.Error(), errTokenHandlingFails) { - t.Fatalf("adal: failed to get correct error expected(%s) actual(%s)", errTokenHandlingFails, err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func errorDeviceTokenResponse(message string) string { - return `{ "error": "` + message + `" }` -} - -func TestDeviceTokenReturnsErrorIfAuthorizationPending(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(errorDeviceTokenResponse("authorization_pending")) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusBadRequest, "Bad Request")) - - _, err := CheckForUserCompletion(sender, deviceCode()) - if err != ErrDeviceAuthorizationPending { - t.Fatalf("!!!") - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorIfSlowDown(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(errorDeviceTokenResponse("slow_down")) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusBadRequest, "Bad Request")) - - _, err := CheckForUserCompletion(sender, deviceCode()) - if err != ErrDeviceSlowDown { - t.Fatalf("!!!") - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -type deviceTokenSender struct { - errorString string - attempts int -} - -func newDeviceTokenSender(deviceErrorString string) *deviceTokenSender { - return &deviceTokenSender{errorString: deviceErrorString, attempts: 0} -} - -func (s *deviceTokenSender) Do(req *http.Request) (*http.Response, error) { - var resp *http.Response - if s.attempts < 1 { - s.attempts++ - resp = mocks.NewResponseWithContent(errorDeviceTokenResponse(s.errorString)) - } else { - resp = mocks.NewResponseWithContent(MockDeviceTokenResponse) - } - return resp, nil -} - -// since the above only exercise CheckForUserCompletion, we repeat the test here, -// but with the intent of showing that WaitForUserCompletion loops properly. -func TestDeviceTokenSucceedsWithIntermediateAuthPending(t *testing.T) { - sender := newDeviceTokenSender("authorization_pending") - - _, err := WaitForUserCompletion(sender, deviceCode()) - if err != nil { - t.Fatalf("unexpected error occurred") - } -} - -// same as above but with SlowDown now -func TestDeviceTokenSucceedsWithIntermediateSlowDown(t *testing.T) { - sender := newDeviceTokenSender("slow_down") - - _, err := WaitForUserCompletion(sender, deviceCode()) - if err != nil { - t.Fatalf("unexpected error occurred") - } -} - -func TestDeviceTokenReturnsErrorIfAccessDenied(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(errorDeviceTokenResponse("access_denied")) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusBadRequest, "Bad Request")) - - _, err := WaitForUserCompletion(sender, deviceCode()) - if err != ErrDeviceAccessDenied { - t.Fatalf("adal: got wrong error expected(%s) actual(%s)", ErrDeviceAccessDenied.Error(), err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorIfCodeExpired(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(errorDeviceTokenResponse("code_expired")) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusBadRequest, "Bad Request")) - - _, err := WaitForUserCompletion(sender, deviceCode()) - if err != ErrDeviceCodeExpired { - t.Fatalf("adal: got wrong error expected(%s) actual(%s)", ErrDeviceCodeExpired.Error(), err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorForUnknownError(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody(errorDeviceTokenResponse("unknown_error")) - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusBadRequest, "Bad Request")) - - _, err := WaitForUserCompletion(sender, deviceCode()) - if err == nil { - t.Fatalf("failed to get error") - } - if err != ErrDeviceGeneric { - t.Fatalf("adal: got wrong error expected(%s) actual(%s)", ErrDeviceGeneric.Error(), err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} - -func TestDeviceTokenReturnsErrorIfTokenEmptyAndStatusOK(t *testing.T) { - sender := mocks.NewSender() - body := mocks.NewBody("") - sender.AppendResponse(mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK")) - - _, err := WaitForUserCompletion(sender, deviceCode()) - if err != ErrOAuthTokenEmpty { - t.Fatalf("adal: got wrong error expected(%s) actual(%s)", ErrOAuthTokenEmpty.Error(), err.Error()) - } - - if body.IsOpen() { - t.Fatalf("response body was left open!") - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/persist_test.go b/vendor/github.com/Azure/go-autorest/autorest/adal/persist_test.go deleted file mode 100644 index a9c287c6dd..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/persist_test.go +++ /dev/null @@ -1,171 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "io/ioutil" - "os" - "path" - "reflect" - "runtime" - "strings" - "testing" -) - -const MockTokenJSON string = `{ - "access_token": "accessToken", - "refresh_token": "refreshToken", - "expires_in": "1000", - "expires_on": "2000", - "not_before": "3000", - "resource": "resource", - "token_type": "type" -}` - -var TestToken = Token{ - AccessToken: "accessToken", - RefreshToken: "refreshToken", - ExpiresIn: "1000", - ExpiresOn: "2000", - NotBefore: "3000", - Resource: "resource", - Type: "type", -} - -func writeTestTokenFile(t *testing.T, suffix string, contents string) *os.File { - f, err := ioutil.TempFile(os.TempDir(), suffix) - if err != nil { - t.Fatalf("azure: unexpected error when creating temp file: %v", err) - } - defer f.Close() - - _, err = f.Write([]byte(contents)) - if err != nil { - t.Fatalf("azure: unexpected error when writing temp test file: %v", err) - } - - return f -} - -func TestLoadToken(t *testing.T) { - f := writeTestTokenFile(t, "testloadtoken", MockTokenJSON) - defer os.Remove(f.Name()) - - expectedToken := TestToken - actualToken, err := LoadToken(f.Name()) - if err != nil { - t.Fatalf("azure: unexpected error loading token from file: %v", err) - } - - if *actualToken != expectedToken { - t.Fatalf("azure: failed to decode properly expected(%v) actual(%v)", expectedToken, *actualToken) - } - - // test that LoadToken closes the file properly - err = SaveToken(f.Name(), 0600, *actualToken) - if err != nil { - t.Fatalf("azure: could not save token after LoadToken: %v", err) - } -} - -func TestLoadTokenFailsBadPath(t *testing.T) { - _, err := LoadToken("/tmp/this_file_should_never_exist_really") - expectedSubstring := "failed to open file" - if err == nil || !strings.Contains(err.Error(), expectedSubstring) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", expectedSubstring, err.Error()) - } -} - -func TestLoadTokenFailsBadJson(t *testing.T) { - gibberishJSON := strings.Replace(MockTokenJSON, "expires_on", ";:\"gibberish", -1) - f := writeTestTokenFile(t, "testloadtokenfailsbadjson", gibberishJSON) - defer os.Remove(f.Name()) - - _, err := LoadToken(f.Name()) - expectedSubstring := "failed to decode contents of file" - if err == nil || !strings.Contains(err.Error(), expectedSubstring) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%s)", expectedSubstring, err.Error()) - } -} - -func token() *Token { - var token Token - json.Unmarshal([]byte(MockTokenJSON), &token) - return &token -} - -func TestSaveToken(t *testing.T) { - f, err := ioutil.TempFile("", "testloadtoken") - if err != nil { - t.Fatalf("azure: unexpected error when creating temp file: %v", err) - } - defer os.Remove(f.Name()) - f.Close() - - mode := os.ModePerm & 0642 - err = SaveToken(f.Name(), mode, *token()) - if err != nil { - t.Fatalf("azure: unexpected error saving token to file: %v", err) - } - fi, err := os.Stat(f.Name()) // open a new stat as held ones are not fresh - if err != nil { - t.Fatalf("azure: stat failed: %v", err) - } - if runtime.GOOS != "windows" { // permissions don't work on Windows - if perm := fi.Mode().Perm(); perm != mode { - t.Fatalf("azure: wrong file perm. got:%s; expected:%s file :%s", perm, mode, f.Name()) - } - } - - var actualToken Token - var expectedToken Token - - json.Unmarshal([]byte(MockTokenJSON), expectedToken) - - contents, err := ioutil.ReadFile(f.Name()) - if err != nil { - t.Fatal("!!") - } - json.Unmarshal(contents, actualToken) - - if !reflect.DeepEqual(actualToken, expectedToken) { - t.Fatal("azure: token was not serialized correctly") - } -} - -func TestSaveTokenFailsNoPermission(t *testing.T) { - pathWhereWeShouldntHavePermission := "/usr/thiswontwork/atall" - if runtime.GOOS == "windows" { - pathWhereWeShouldntHavePermission = path.Join(os.Getenv("windir"), "system32\\mytokendir\\mytoken") - } - err := SaveToken(pathWhereWeShouldntHavePermission, 0644, *token()) - expectedSubstring := "failed to create directory" - if err == nil || !strings.Contains(err.Error(), expectedSubstring) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%v)", expectedSubstring, err) - } -} - -func TestSaveTokenFailsCantCreate(t *testing.T) { - tokenPath := "/thiswontwork" - if runtime.GOOS == "windows" { - tokenPath = path.Join(os.Getenv("windir"), "system32") - } - err := SaveToken(tokenPath, 0644, *token()) - expectedSubstring := "failed to create the temp file to write the token" - if err == nil || !strings.Contains(err.Error(), expectedSubstring) { - t.Fatalf("azure: failed to get correct error expected(%s) actual(%v)", expectedSubstring, err) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/token.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token.go index 67dd97a18c..941af281b5 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/token.go +++ b/vendor/github.com/Azure/go-autorest/autorest/adal/token.go @@ -27,6 +27,7 @@ import ( "net/url" "strconv" "strings" + "sync" "time" "github.com/Azure/go-autorest/autorest/date" @@ -42,9 +43,15 @@ const ( // OAuthGrantTypeClientCredentials is the "grant_type" identifier used in credential flows OAuthGrantTypeClientCredentials = "client_credentials" + // OAuthGrantTypeUserPass is the "grant_type" identifier used in username and password auth flows + OAuthGrantTypeUserPass = "password" + // OAuthGrantTypeRefreshToken is the "grant_type" identifier used in refresh token flows OAuthGrantTypeRefreshToken = "refresh_token" + // OAuthGrantTypeAuthorizationCode is the "grant_type" identifier used in authorization code flows + OAuthGrantTypeAuthorizationCode = "authorization_code" + // metadataHeader is the header required by MSI extension metadataHeader = "Metadata" ) @@ -54,6 +61,12 @@ type OAuthTokenProvider interface { OAuthToken() string } +// TokenRefreshError is an interface used by errors returned during token refresh. +type TokenRefreshError interface { + error + Response() *http.Response +} + // Refresher is an interface for token refresh functionality type Refresher interface { Refresh() error @@ -78,6 +91,11 @@ type Token struct { Type string `json:"token_type"` } +// IsZero returns true if the token object is zero-initialized. +func (t Token) IsZero() bool { + return t == Token{} +} + // Expires returns the time.Time when the Token expires. func (t Token) Expires() time.Time { s, err := strconv.Atoi(t.ExpiresOn) @@ -145,6 +163,34 @@ type ServicePrincipalCertificateSecret struct { type ServicePrincipalMSISecret struct { } +// ServicePrincipalUsernamePasswordSecret implements ServicePrincipalSecret for username and password auth. +type ServicePrincipalUsernamePasswordSecret struct { + Username string + Password string +} + +// ServicePrincipalAuthorizationCodeSecret implements ServicePrincipalSecret for authorization code auth. +type ServicePrincipalAuthorizationCodeSecret struct { + ClientSecret string + AuthorizationCode string + RedirectURI string +} + +// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. +func (secret *ServicePrincipalAuthorizationCodeSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { + v.Set("code", secret.AuthorizationCode) + v.Set("client_secret", secret.ClientSecret) + v.Set("redirect_uri", secret.RedirectURI) + return nil +} + +// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. +func (secret *ServicePrincipalUsernamePasswordSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { + v.Set("username", secret.Username) + v.Set("password", secret.Password) + return nil +} + // SetAuthenticationValues is a method of the interface ServicePrincipalSecret. func (msiSecret *ServicePrincipalMSISecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { return nil @@ -199,25 +245,46 @@ func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *Se type ServicePrincipalToken struct { Token - secret ServicePrincipalSecret - oauthConfig OAuthConfig - clientID string - resource string - autoRefresh bool - refreshWithin time.Duration - sender Sender + secret ServicePrincipalSecret + oauthConfig OAuthConfig + clientID string + resource string + autoRefresh bool + autoRefreshLock *sync.Mutex + refreshWithin time.Duration + sender Sender refreshCallbacks []TokenRefreshCallback } +func validateOAuthConfig(oac OAuthConfig) error { + if oac.IsZero() { + return fmt.Errorf("parameter 'oauthConfig' cannot be zero-initialized") + } + return nil +} + // NewServicePrincipalTokenWithSecret create a ServicePrincipalToken using the supplied ServicePrincipalSecret implementation. func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + if err := validateOAuthConfig(oauthConfig); err != nil { + return nil, err + } + if err := validateStringParam(id, "id"); err != nil { + return nil, err + } + if err := validateStringParam(resource, "resource"); err != nil { + return nil, err + } + if secret == nil { + return nil, fmt.Errorf("parameter 'secret' cannot be nil") + } spt := &ServicePrincipalToken{ oauthConfig: oauthConfig, secret: secret, clientID: id, resource: resource, autoRefresh: true, + autoRefreshLock: &sync.Mutex{}, refreshWithin: defaultRefresh, sender: &http.Client{}, refreshCallbacks: callbacks, @@ -227,6 +294,18 @@ func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, reso // NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + if err := validateOAuthConfig(oauthConfig); err != nil { + return nil, err + } + if err := validateStringParam(clientID, "clientID"); err != nil { + return nil, err + } + if err := validateStringParam(resource, "resource"); err != nil { + return nil, err + } + if token.IsZero() { + return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized") + } spt, err := NewServicePrincipalTokenWithSecret( oauthConfig, clientID, @@ -245,6 +324,18 @@ func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID s // NewServicePrincipalToken creates a ServicePrincipalToken from the supplied Service Principal // credentials scoped to the named resource. func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + if err := validateOAuthConfig(oauthConfig); err != nil { + return nil, err + } + if err := validateStringParam(clientID, "clientID"); err != nil { + return nil, err + } + if err := validateStringParam(secret, "secret"); err != nil { + return nil, err + } + if err := validateStringParam(resource, "resource"); err != nil { + return nil, err + } return NewServicePrincipalTokenWithSecret( oauthConfig, clientID, @@ -256,8 +347,23 @@ func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret s ) } -// NewServicePrincipalTokenFromCertificate create a ServicePrincipalToken from the supplied pkcs12 bytes. +// NewServicePrincipalTokenFromCertificate creates a ServicePrincipalToken from the supplied pkcs12 bytes. func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + if err := validateOAuthConfig(oauthConfig); err != nil { + return nil, err + } + if err := validateStringParam(clientID, "clientID"); err != nil { + return nil, err + } + if err := validateStringParam(resource, "resource"); err != nil { + return nil, err + } + if certificate == nil { + return nil, fmt.Errorf("parameter 'certificate' cannot be nil") + } + if privateKey == nil { + return nil, fmt.Errorf("parameter 'privateKey' cannot be nil") + } return NewServicePrincipalTokenWithSecret( oauthConfig, clientID, @@ -270,6 +376,70 @@ func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID s ) } +// NewServicePrincipalTokenFromUsernamePassword creates a ServicePrincipalToken from the username and password. +func NewServicePrincipalTokenFromUsernamePassword(oauthConfig OAuthConfig, clientID string, username string, password string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + if err := validateOAuthConfig(oauthConfig); err != nil { + return nil, err + } + if err := validateStringParam(clientID, "clientID"); err != nil { + return nil, err + } + if err := validateStringParam(username, "username"); err != nil { + return nil, err + } + if err := validateStringParam(password, "password"); err != nil { + return nil, err + } + if err := validateStringParam(resource, "resource"); err != nil { + return nil, err + } + return NewServicePrincipalTokenWithSecret( + oauthConfig, + clientID, + resource, + &ServicePrincipalUsernamePasswordSecret{ + Username: username, + Password: password, + }, + callbacks..., + ) +} + +// NewServicePrincipalTokenFromAuthorizationCode creates a ServicePrincipalToken from the +func NewServicePrincipalTokenFromAuthorizationCode(oauthConfig OAuthConfig, clientID string, clientSecret string, authorizationCode string, redirectURI string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + + if err := validateOAuthConfig(oauthConfig); err != nil { + return nil, err + } + if err := validateStringParam(clientID, "clientID"); err != nil { + return nil, err + } + if err := validateStringParam(clientSecret, "clientSecret"); err != nil { + return nil, err + } + if err := validateStringParam(authorizationCode, "authorizationCode"); err != nil { + return nil, err + } + if err := validateStringParam(redirectURI, "redirectURI"); err != nil { + return nil, err + } + if err := validateStringParam(resource, "resource"); err != nil { + return nil, err + } + + return NewServicePrincipalTokenWithSecret( + oauthConfig, + clientID, + resource, + &ServicePrincipalAuthorizationCodeSecret{ + ClientSecret: clientSecret, + AuthorizationCode: authorizationCode, + RedirectURI: redirectURI, + }, + callbacks..., + ) +} + // GetMSIVMEndpoint gets the MSI endpoint on Virtual Machines. func GetMSIVMEndpoint() (string, error) { return getMSIVMEndpoint(msiPath) @@ -293,7 +463,29 @@ func getMSIVMEndpoint(path string) (string, error) { } // NewServicePrincipalTokenFromMSI creates a ServicePrincipalToken via the MSI VM Extension. +// It will use the system assigned identity when creating the token. func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + return newServicePrincipalTokenFromMSI(msiEndpoint, resource, nil, callbacks...) +} + +// NewServicePrincipalTokenFromMSIWithUserAssignedID creates a ServicePrincipalToken via the MSI VM Extension. +// It will use the specified user assigned identity when creating the token. +func NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, resource string, userAssignedID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + return newServicePrincipalTokenFromMSI(msiEndpoint, resource, &userAssignedID, callbacks...) +} + +func newServicePrincipalTokenFromMSI(msiEndpoint, resource string, userAssignedID *string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { + if err := validateStringParam(msiEndpoint, "msiEndpoint"); err != nil { + return nil, err + } + if err := validateStringParam(resource, "resource"); err != nil { + return nil, err + } + if userAssignedID != nil { + if err := validateStringParam(*userAssignedID, "userAssignedID"); err != nil { + return nil, err + } + } // We set the oauth config token endpoint to be MSI's endpoint msiEndpointURL, err := url.Parse(msiEndpoint) if err != nil { @@ -310,19 +502,49 @@ func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ... secret: &ServicePrincipalMSISecret{}, resource: resource, autoRefresh: true, + autoRefreshLock: &sync.Mutex{}, refreshWithin: defaultRefresh, sender: &http.Client{}, refreshCallbacks: callbacks, } + if userAssignedID != nil { + spt.clientID = *userAssignedID + } + return spt, nil } +// internal type that implements TokenRefreshError +type tokenRefreshError struct { + message string + resp *http.Response +} + +// Error implements the error interface which is part of the TokenRefreshError interface. +func (tre tokenRefreshError) Error() string { + return tre.message +} + +// Response implements the TokenRefreshError interface, it returns the raw HTTP response from the refresh operation. +func (tre tokenRefreshError) Response() *http.Response { + return tre.resp +} + +func newTokenRefreshError(message string, resp *http.Response) TokenRefreshError { + return tokenRefreshError{message: message, resp: resp} +} + // EnsureFresh will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. +// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. func (spt *ServicePrincipalToken) EnsureFresh() error { if spt.autoRefresh && spt.WillExpireIn(spt.refreshWithin) { - return spt.Refresh() + // take the lock then check to see if the token was already refreshed + spt.autoRefreshLock.Lock() + defer spt.autoRefreshLock.Unlock() + if spt.WillExpireIn(spt.refreshWithin) { + return spt.Refresh() + } } return nil } @@ -341,15 +563,28 @@ func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { } // Refresh obtains a fresh token for the Service Principal. +// This method is not safe for concurrent use and should be syncrhonized. func (spt *ServicePrincipalToken) Refresh() error { return spt.refreshInternal(spt.resource) } // RefreshExchange refreshes the token, but for a different resource. +// This method is not safe for concurrent use and should be syncrhonized. func (spt *ServicePrincipalToken) RefreshExchange(resource string) error { return spt.refreshInternal(resource) } +func (spt *ServicePrincipalToken) getGrantType() string { + switch spt.secret.(type) { + case *ServicePrincipalUsernamePasswordSecret: + return OAuthGrantTypeUserPass + case *ServicePrincipalAuthorizationCodeSecret: + return OAuthGrantTypeAuthorizationCode + default: + return OAuthGrantTypeClientCredentials + } +} + func (spt *ServicePrincipalToken) refreshInternal(resource string) error { v := url.Values{} v.Set("client_id", spt.clientID) @@ -359,7 +594,7 @@ func (spt *ServicePrincipalToken) refreshInternal(resource string) error { v.Set("grant_type", OAuthGrantTypeRefreshToken) v.Set("refresh_token", spt.RefreshToken) } else { - v.Set("grant_type", OAuthGrantTypeClientCredentials) + v.Set("grant_type", spt.getGrantType()) err := spt.secret.SetAuthenticationValues(spt, &v) if err != nil { return err @@ -388,9 +623,9 @@ func (spt *ServicePrincipalToken) refreshInternal(resource string) error { if resp.StatusCode != http.StatusOK { if err != nil { - return fmt.Errorf("adal: Refresh request failed. Status Code = '%d'. Failed reading response body", resp.StatusCode) + return newTokenRefreshError(fmt.Sprintf("adal: Refresh request failed. Status Code = '%d'. Failed reading response body", resp.StatusCode), resp) } - return fmt.Errorf("adal: Refresh request failed. Status Code = '%d'. Response body: %s", resp.StatusCode, string(rb)) + return newTokenRefreshError(fmt.Sprintf("adal: Refresh request failed. Status Code = '%d'. Response body: %s", resp.StatusCode, string(rb)), resp) } if err != nil { diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/token_test.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token_test.go deleted file mode 100644 index 73c848ba00..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/token_test.go +++ /dev/null @@ -1,654 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "fmt" - "io/ioutil" - "math/big" - "net/http" - "net/url" - "os" - "reflect" - "strconv" - "strings" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest/date" - "github.com/Azure/go-autorest/autorest/mocks" -) - -const ( - defaultFormData = "client_id=id&client_secret=secret&grant_type=client_credentials&resource=resource" - defaultManualFormData = "client_id=id&grant_type=refresh_token&refresh_token=refreshtoken&resource=resource" -) - -func TestTokenExpires(t *testing.T) { - tt := time.Now().Add(5 * time.Second) - tk := newTokenExpiresAt(tt) - - if tk.Expires().Equal(tt) { - t.Fatalf("adal: Token#Expires miscalculated expiration time -- received %v, expected %v", tk.Expires(), tt) - } -} - -func TestTokenIsExpired(t *testing.T) { - tk := newTokenExpiresAt(time.Now().Add(-5 * time.Second)) - - if !tk.IsExpired() { - t.Fatalf("adal: Token#IsExpired failed to mark a stale token as expired -- now %v, token expires at %v", - time.Now().UTC(), tk.Expires()) - } -} - -func TestTokenIsExpiredUninitialized(t *testing.T) { - tk := &Token{} - - if !tk.IsExpired() { - t.Fatalf("adal: An uninitialized Token failed to mark itself as expired (expiration time %v)", tk.Expires()) - } -} - -func TestTokenIsNoExpired(t *testing.T) { - tk := newTokenExpiresAt(time.Now().Add(1000 * time.Second)) - - if tk.IsExpired() { - t.Fatalf("adal: Token marked a fresh token as expired -- now %v, token expires at %v", time.Now().UTC(), tk.Expires()) - } -} - -func TestTokenWillExpireIn(t *testing.T) { - d := 5 * time.Second - tk := newTokenExpiresIn(d) - - if !tk.WillExpireIn(d) { - t.Fatal("adal: Token#WillExpireIn mismeasured expiration time") - } -} - -func TestServicePrincipalTokenSetAutoRefresh(t *testing.T) { - spt := newServicePrincipalToken() - - if !spt.autoRefresh { - t.Fatal("adal: ServicePrincipalToken did not default to automatic token refreshing") - } - - spt.SetAutoRefresh(false) - if spt.autoRefresh { - t.Fatal("adal: ServicePrincipalToken#SetAutoRefresh did not disable automatic token refreshing") - } -} - -func TestServicePrincipalTokenSetRefreshWithin(t *testing.T) { - spt := newServicePrincipalToken() - - if spt.refreshWithin != defaultRefresh { - t.Fatal("adal: ServicePrincipalToken did not correctly set the default refresh interval") - } - - spt.SetRefreshWithin(2 * defaultRefresh) - if spt.refreshWithin != 2*defaultRefresh { - t.Fatal("adal: ServicePrincipalToken#SetRefreshWithin did not set the refresh interval") - } -} - -func TestServicePrincipalTokenSetSender(t *testing.T) { - spt := newServicePrincipalToken() - - c := &http.Client{} - spt.SetSender(c) - if !reflect.DeepEqual(c, spt.sender) { - t.Fatal("adal: ServicePrincipalToken#SetSender did not set the sender") - } -} - -func TestServicePrincipalTokenRefreshUsesPOST(t *testing.T) { - spt := newServicePrincipalToken() - - body := mocks.NewBody(newTokenJSON("test", "test")) - resp := mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK") - - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - if r.Method != "POST" { - t.Fatalf("adal: ServicePrincipalToken#Refresh did not correctly set HTTP method -- expected %v, received %v", "POST", r.Method) - } - return resp, nil - }) - } - })()) - spt.SetSender(s) - err := spt.Refresh() - if err != nil { - t.Fatalf("adal: ServicePrincipalToken#Refresh returned an unexpected error (%v)", err) - } - - if body.IsOpen() { - t.Fatalf("the response was not closed!") - } -} - -func TestServicePrincipalTokenFromMSIRefreshUsesPOST(t *testing.T) { - resource := "https://resource" - cb := func(token Token) error { return nil } - - spt, err := NewServicePrincipalTokenFromMSI("http://msiendpoint/", resource, cb) - if err != nil { - t.Fatalf("Failed to get MSI SPT: %v", err) - } - - body := mocks.NewBody(newTokenJSON("test", "test")) - resp := mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK") - - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - if r.Method != "POST" { - t.Fatalf("adal: ServicePrincipalToken#Refresh did not correctly set HTTP method -- expected %v, received %v", "POST", r.Method) - } - if h := r.Header.Get("Metadata"); h != "true" { - t.Fatalf("adal: ServicePrincipalToken#Refresh did not correctly set Metadata header for MSI") - } - return resp, nil - }) - } - })()) - spt.SetSender(s) - err = spt.Refresh() - if err != nil { - t.Fatalf("adal: ServicePrincipalToken#Refresh returned an unexpected error (%v)", err) - } - - if body.IsOpen() { - t.Fatalf("the response was not closed!") - } -} - -func TestServicePrincipalTokenRefreshSetsMimeType(t *testing.T) { - spt := newServicePrincipalToken() - - body := mocks.NewBody(newTokenJSON("test", "test")) - resp := mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK") - - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - if r.Header.Get(http.CanonicalHeaderKey("Content-Type")) != "application/x-www-form-urlencoded" { - t.Fatalf("adal: ServicePrincipalToken#Refresh did not correctly set Content-Type -- expected %v, received %v", - "application/x-form-urlencoded", - r.Header.Get(http.CanonicalHeaderKey("Content-Type"))) - } - return resp, nil - }) - } - })()) - spt.SetSender(s) - err := spt.Refresh() - if err != nil { - t.Fatalf("adal: ServicePrincipalToken#Refresh returned an unexpected error (%v)", err) - } -} - -func TestServicePrincipalTokenRefreshSetsURL(t *testing.T) { - spt := newServicePrincipalToken() - - body := mocks.NewBody(newTokenJSON("test", "test")) - resp := mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK") - - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - if r.URL.String() != TestOAuthConfig.TokenEndpoint.String() { - t.Fatalf("adal: ServicePrincipalToken#Refresh did not correctly set the URL -- expected %v, received %v", - TestOAuthConfig.TokenEndpoint, r.URL) - } - return resp, nil - }) - } - })()) - spt.SetSender(s) - err := spt.Refresh() - if err != nil { - t.Fatalf("adal: ServicePrincipalToken#Refresh returned an unexpected error (%v)", err) - } -} - -func testServicePrincipalTokenRefreshSetsBody(t *testing.T, spt *ServicePrincipalToken, f func(*testing.T, []byte)) { - body := mocks.NewBody(newTokenJSON("test", "test")) - resp := mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK") - - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("adal: Failed to read body of Service Principal token request (%v)", err) - } - f(t, b) - return resp, nil - }) - } - })()) - spt.SetSender(s) - err := spt.Refresh() - if err != nil { - t.Fatalf("adal: ServicePrincipalToken#Refresh returned an unexpected error (%v)", err) - } -} - -func TestServicePrincipalTokenManualRefreshSetsBody(t *testing.T) { - sptManual := newServicePrincipalTokenManual() - testServicePrincipalTokenRefreshSetsBody(t, sptManual, func(t *testing.T, b []byte) { - if string(b) != defaultManualFormData { - t.Fatalf("adal: ServicePrincipalToken#Refresh did not correctly set the HTTP Request Body -- expected %v, received %v", - defaultManualFormData, string(b)) - } - }) -} - -func TestServicePrincipalTokenCertficateRefreshSetsBody(t *testing.T) { - sptCert := newServicePrincipalTokenCertificate(t) - testServicePrincipalTokenRefreshSetsBody(t, sptCert, func(t *testing.T, b []byte) { - body := string(b) - - values, _ := url.ParseQuery(body) - if values["client_assertion_type"][0] != "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" || - values["client_id"][0] != "id" || - values["grant_type"][0] != "client_credentials" || - values["resource"][0] != "resource" { - t.Fatalf("adal: ServicePrincipalTokenCertificate#Refresh did not correctly set the HTTP Request Body.") - } - }) -} - -func TestServicePrincipalTokenSecretRefreshSetsBody(t *testing.T) { - spt := newServicePrincipalToken() - testServicePrincipalTokenRefreshSetsBody(t, spt, func(t *testing.T, b []byte) { - if string(b) != defaultFormData { - t.Fatalf("adal: ServicePrincipalToken#Refresh did not correctly set the HTTP Request Body -- expected %v, received %v", - defaultFormData, string(b)) - } - - }) -} - -func TestServicePrincipalTokenRefreshClosesRequestBody(t *testing.T) { - spt := newServicePrincipalToken() - - body := mocks.NewBody(newTokenJSON("test", "test")) - resp := mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK") - - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return resp, nil - }) - } - })()) - spt.SetSender(s) - err := spt.Refresh() - if err != nil { - t.Fatalf("adal: ServicePrincipalToken#Refresh returned an unexpected error (%v)", err) - } - if resp.Body.(*mocks.Body).IsOpen() { - t.Fatal("adal: ServicePrincipalToken#Refresh failed to close the HTTP Response Body") - } -} - -func TestServicePrincipalTokenRefreshRejectsResponsesWithStatusNotOK(t *testing.T) { - spt := newServicePrincipalToken() - - body := mocks.NewBody(newTokenJSON("test", "test")) - resp := mocks.NewResponseWithBodyAndStatus(body, http.StatusUnauthorized, "Unauthorized") - - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return resp, nil - }) - } - })()) - spt.SetSender(s) - err := spt.Refresh() - if err == nil { - t.Fatalf("adal: ServicePrincipalToken#Refresh should reject a response with status != %d", http.StatusOK) - } -} - -func TestServicePrincipalTokenRefreshRejectsEmptyBody(t *testing.T) { - spt := newServicePrincipalToken() - - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return mocks.NewResponse(), nil - }) - } - })()) - spt.SetSender(s) - err := spt.Refresh() - if err == nil { - t.Fatal("adal: ServicePrincipalToken#Refresh should reject an empty token") - } -} - -func TestServicePrincipalTokenRefreshPropagatesErrors(t *testing.T) { - spt := newServicePrincipalToken() - - c := mocks.NewSender() - c.SetError(fmt.Errorf("Faux Error")) - spt.SetSender(c) - - err := spt.Refresh() - if err == nil { - t.Fatal("adal: Failed to propagate the request error") - } -} - -func TestServicePrincipalTokenRefreshReturnsErrorIfNotOk(t *testing.T) { - spt := newServicePrincipalToken() - - c := mocks.NewSender() - c.AppendResponse(mocks.NewResponseWithStatus("401 NotAuthorized", http.StatusUnauthorized)) - spt.SetSender(c) - - err := spt.Refresh() - if err == nil { - t.Fatalf("adal: Failed to return an when receiving a status code other than HTTP %d", http.StatusOK) - } -} - -func TestServicePrincipalTokenRefreshUnmarshals(t *testing.T) { - spt := newServicePrincipalToken() - - expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(date.UnixEpoch()).Seconds())) - j := newTokenJSON(expiresOn, "resource") - resp := mocks.NewResponseWithContent(j) - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return resp, nil - }) - } - })()) - spt.SetSender(s) - - err := spt.Refresh() - if err != nil { - t.Fatalf("adal: ServicePrincipalToken#Refresh returned an unexpected error (%v)", err) - } else if spt.AccessToken != "accessToken" || - spt.ExpiresIn != "3600" || - spt.ExpiresOn != expiresOn || - spt.NotBefore != expiresOn || - spt.Resource != "resource" || - spt.Type != "Bearer" { - t.Fatalf("adal: ServicePrincipalToken#Refresh failed correctly unmarshal the JSON -- expected %v, received %v", - j, *spt) - } -} - -func TestServicePrincipalTokenEnsureFreshRefreshes(t *testing.T) { - spt := newServicePrincipalToken() - expireToken(&spt.Token) - - body := mocks.NewBody(newTokenJSON("test", "test")) - resp := mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK") - - f := false - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - f = true - return resp, nil - }) - } - })()) - spt.SetSender(s) - err := spt.EnsureFresh() - if err != nil { - t.Fatalf("adal: ServicePrincipalToken#EnsureFresh returned an unexpected error (%v)", err) - } - if !f { - t.Fatal("adal: ServicePrincipalToken#EnsureFresh failed to call Refresh for stale token") - } -} - -func TestServicePrincipalTokenEnsureFreshSkipsIfFresh(t *testing.T) { - spt := newServicePrincipalToken() - setTokenToExpireIn(&spt.Token, 1000*time.Second) - - f := false - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - f = true - return mocks.NewResponse(), nil - }) - } - })()) - spt.SetSender(s) - err := spt.EnsureFresh() - if err != nil { - t.Fatalf("adal: ServicePrincipalToken#EnsureFresh returned an unexpected error (%v)", err) - } - if f { - t.Fatal("adal: ServicePrincipalToken#EnsureFresh invoked Refresh for fresh token") - } -} - -func TestRefreshCallback(t *testing.T) { - callbackTriggered := false - spt := newServicePrincipalToken(func(Token) error { - callbackTriggered = true - return nil - }) - - expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(date.UnixEpoch()).Seconds())) - - sender := mocks.NewSender() - j := newTokenJSON(expiresOn, "resource") - sender.AppendResponse(mocks.NewResponseWithContent(j)) - spt.SetSender(sender) - err := spt.Refresh() - if err != nil { - t.Fatalf("adal: ServicePrincipalToken#Refresh returned an unexpected error (%v)", err) - } - if !callbackTriggered { - t.Fatalf("adal: RefreshCallback failed to trigger call callback") - } -} - -func TestRefreshCallbackErrorPropagates(t *testing.T) { - errorText := "this is an error text" - spt := newServicePrincipalToken(func(Token) error { - return fmt.Errorf(errorText) - }) - - expiresOn := strconv.Itoa(int(time.Now().Add(3600 * time.Second).Sub(date.UnixEpoch()).Seconds())) - - sender := mocks.NewSender() - j := newTokenJSON(expiresOn, "resource") - sender.AppendResponse(mocks.NewResponseWithContent(j)) - spt.SetSender(sender) - err := spt.Refresh() - - if err == nil || !strings.Contains(err.Error(), errorText) { - t.Fatalf("adal: RefreshCallback failed to propagate error") - } -} - -// This demonstrates the danger of manual token without a refresh token -func TestServicePrincipalTokenManualRefreshFailsWithoutRefresh(t *testing.T) { - spt := newServicePrincipalTokenManual() - spt.RefreshToken = "" - err := spt.Refresh() - if err == nil { - t.Fatalf("adal: ServicePrincipalToken#Refresh should have failed with a ManualTokenSecret without a refresh token") - } -} - -func TestNewServicePrincipalTokenFromMSI(t *testing.T) { - resource := "https://resource" - cb := func(token Token) error { return nil } - - spt, err := NewServicePrincipalTokenFromMSI("http://msiendpoint/", resource, cb) - if err != nil { - t.Fatalf("Failed to get MSI SPT: %v", err) - } - - // check some of the SPT fields - if _, ok := spt.secret.(*ServicePrincipalMSISecret); !ok { - t.Fatal("SPT secret was not of MSI type") - } - - if spt.resource != resource { - t.Fatal("SPT came back with incorrect resource") - } - - if len(spt.refreshCallbacks) != 1 { - t.Fatal("SPT had incorrect refresh callbacks.") - } -} - -func TestGetVMEndpoint(t *testing.T) { - tempSettingsFile, err := ioutil.TempFile("", "ManagedIdentity-Settings") - if err != nil { - t.Fatal("Couldn't write temp settings file") - } - defer os.Remove(tempSettingsFile.Name()) - - settingsContents := []byte(`{ - "url": "http://msiendpoint/" - }`) - - if _, err := tempSettingsFile.Write(settingsContents); err != nil { - t.Fatal("Couldn't fill temp settings file") - } - - endpoint, err := getMSIVMEndpoint(tempSettingsFile.Name()) - if err != nil { - t.Fatal("Coudn't get VM endpoint") - } - - if endpoint != "http://msiendpoint/" { - t.Fatal("Didn't get correct endpoint") - } -} - -func newToken() *Token { - return &Token{ - AccessToken: "ASECRETVALUE", - Resource: "https://azure.microsoft.com/", - Type: "Bearer", - } -} - -func newTokenJSON(expiresOn string, resource string) string { - return fmt.Sprintf(`{ - "access_token" : "accessToken", - "expires_in" : "3600", - "expires_on" : "%s", - "not_before" : "%s", - "resource" : "%s", - "token_type" : "Bearer" - }`, - expiresOn, expiresOn, resource) -} - -func newTokenExpiresIn(expireIn time.Duration) *Token { - return setTokenToExpireIn(newToken(), expireIn) -} - -func newTokenExpiresAt(expireAt time.Time) *Token { - return setTokenToExpireAt(newToken(), expireAt) -} - -func expireToken(t *Token) *Token { - return setTokenToExpireIn(t, 0) -} - -func setTokenToExpireAt(t *Token, expireAt time.Time) *Token { - t.ExpiresIn = "3600" - t.ExpiresOn = strconv.Itoa(int(expireAt.Sub(date.UnixEpoch()).Seconds())) - t.NotBefore = t.ExpiresOn - return t -} - -func setTokenToExpireIn(t *Token, expireIn time.Duration) *Token { - return setTokenToExpireAt(t, time.Now().Add(expireIn)) -} - -func newServicePrincipalToken(callbacks ...TokenRefreshCallback) *ServicePrincipalToken { - spt, _ := NewServicePrincipalToken(TestOAuthConfig, "id", "secret", "resource", callbacks...) - return spt -} - -func newServicePrincipalTokenManual() *ServicePrincipalToken { - token := newToken() - token.RefreshToken = "refreshtoken" - spt, _ := NewServicePrincipalTokenFromManualToken(TestOAuthConfig, "id", "resource", *token) - return spt -} - -func newServicePrincipalTokenCertificate(t *testing.T) *ServicePrincipalToken { - template := x509.Certificate{ - SerialNumber: big.NewInt(0), - Subject: pkix.Name{CommonName: "test"}, - BasicConstraintsValid: true, - } - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Fatal(err) - } - certificateBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) - if err != nil { - t.Fatal(err) - } - certificate, err := x509.ParseCertificate(certificateBytes) - if err != nil { - t.Fatal(err) - } - - spt, _ := NewServicePrincipalTokenFromCertificate(TestOAuthConfig, "id", certificate, privateKey, "resource") - return spt -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization.go b/vendor/github.com/Azure/go-autorest/autorest/authorization.go index 71e3ced2d6..4a602f6760 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/authorization.go +++ b/vendor/github.com/Azure/go-autorest/autorest/authorization.go @@ -24,9 +24,12 @@ import ( ) const ( - bearerChallengeHeader = "Www-Authenticate" - bearer = "Bearer" - tenantID = "tenantID" + bearerChallengeHeader = "Www-Authenticate" + bearer = "Bearer" + tenantID = "tenantID" + apiKeyAuthorizerHeader = "Ocp-Apim-Subscription-Key" + bingAPISdkHeader = "X-BingApis-SDK-Client" + golangBingAPISdkHeaderValue = "Go-SDK" ) // Authorizer is the interface that provides a PrepareDecorator used to supply request @@ -44,6 +47,53 @@ func (na NullAuthorizer) WithAuthorization() PrepareDecorator { return WithNothing() } +// APIKeyAuthorizer implements API Key authorization. +type APIKeyAuthorizer struct { + headers map[string]interface{} + queryParameters map[string]interface{} +} + +// NewAPIKeyAuthorizerWithHeaders creates an ApiKeyAuthorizer with headers. +func NewAPIKeyAuthorizerWithHeaders(headers map[string]interface{}) *APIKeyAuthorizer { + return NewAPIKeyAuthorizer(headers, nil) +} + +// NewAPIKeyAuthorizerWithQueryParameters creates an ApiKeyAuthorizer with query parameters. +func NewAPIKeyAuthorizerWithQueryParameters(queryParameters map[string]interface{}) *APIKeyAuthorizer { + return NewAPIKeyAuthorizer(nil, queryParameters) +} + +// NewAPIKeyAuthorizer creates an ApiKeyAuthorizer with headers. +func NewAPIKeyAuthorizer(headers map[string]interface{}, queryParameters map[string]interface{}) *APIKeyAuthorizer { + return &APIKeyAuthorizer{headers: headers, queryParameters: queryParameters} +} + +// WithAuthorization returns a PrepareDecorator that adds an HTTP headers and Query Paramaters +func (aka *APIKeyAuthorizer) WithAuthorization() PrepareDecorator { + return func(p Preparer) Preparer { + return DecoratePreparer(p, WithHeaders(aka.headers), WithQueryParameters(aka.queryParameters)) + } +} + +// CognitiveServicesAuthorizer implements authorization for Cognitive Services. +type CognitiveServicesAuthorizer struct { + subscriptionKey string +} + +// NewCognitiveServicesAuthorizer is +func NewCognitiveServicesAuthorizer(subscriptionKey string) *CognitiveServicesAuthorizer { + return &CognitiveServicesAuthorizer{subscriptionKey: subscriptionKey} +} + +// WithAuthorization is +func (csa *CognitiveServicesAuthorizer) WithAuthorization() PrepareDecorator { + headers := make(map[string]interface{}) + headers[apiKeyAuthorizerHeader] = csa.subscriptionKey + headers[bingAPISdkHeader] = golangBingAPISdkHeaderValue + + return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() +} + // BearerAuthorizer implements the bearer authorization type BearerAuthorizer struct { tokenProvider adal.OAuthTokenProvider @@ -69,7 +119,11 @@ func (ba *BearerAuthorizer) WithAuthorization() PrepareDecorator { if ok { err := refresher.EnsureFresh() if err != nil { - return r, NewErrorWithError(err, "azure.BearerAuthorizer", "WithAuthorization", nil, + var resp *http.Response + if tokError, ok := err.(adal.TokenRefreshError); ok { + resp = tokError.Response() + } + return r, NewErrorWithError(err, "azure.BearerAuthorizer", "WithAuthorization", resp, "Failed to refresh the Token for request to %s", r.URL) } } @@ -179,3 +233,22 @@ func newBearerChallenge(resp *http.Response) (bc bearerChallenge, err error) { return bc, err } + +// EventGridKeyAuthorizer implements authorization for event grid using key authentication. +type EventGridKeyAuthorizer struct { + topicKey string +} + +// NewEventGridKeyAuthorizer creates a new EventGridKeyAuthorizer +// with the specified topic key. +func NewEventGridKeyAuthorizer(topicKey string) EventGridKeyAuthorizer { + return EventGridKeyAuthorizer{topicKey: topicKey} +} + +// WithAuthorization returns a PrepareDecorator that adds the aeg-sas-key authentication header. +func (egta EventGridKeyAuthorizer) WithAuthorization() PrepareDecorator { + headers := map[string]interface{}{ + "aeg-sas-key": egta.topicKey, + } + return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization_test.go b/vendor/github.com/Azure/go-autorest/autorest/authorization_test.go deleted file mode 100644 index 635fcfd7f8..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/authorization_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "net/http" - "reflect" - "testing" - - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/mocks" -) - -const ( - TestTenantID = "TestTenantID" - TestActiveDirectoryEndpoint = "https://login/test.com/" -) - -func TestWithAuthorizer(t *testing.T) { - r1 := mocks.NewRequest() - - na := &NullAuthorizer{} - r2, err := Prepare(r1, - na.WithAuthorization()) - if err != nil { - t.Fatalf("autorest: NullAuthorizer#WithAuthorization returned an unexpected error (%v)", err) - } else if !reflect.DeepEqual(r1, r2) { - t.Fatalf("autorest: NullAuthorizer#WithAuthorization modified the request -- received %v, expected %v", r2, r1) - } -} - -func TestTokenWithAuthorization(t *testing.T) { - token := &adal.Token{ - AccessToken: "TestToken", - Resource: "https://azure.microsoft.com/", - Type: "Bearer", - } - - ba := NewBearerAuthorizer(token) - req, err := Prepare(&http.Request{}, ba.WithAuthorization()) - if err != nil { - t.Fatalf("azure: BearerAuthorizer#WithAuthorization returned an error (%v)", err) - } else if req.Header.Get(http.CanonicalHeaderKey("Authorization")) != fmt.Sprintf("Bearer %s", token.AccessToken) { - t.Fatal("azure: BearerAuthorizer#WithAuthorization failed to set Authorization header") - } -} - -func TestServicePrincipalTokenWithAuthorizationNoRefresh(t *testing.T) { - oauthConfig, err := adal.NewOAuthConfig(TestActiveDirectoryEndpoint, TestTenantID) - if err != nil { - t.Fatalf("azure: BearerAuthorizer#WithAuthorization returned an error (%v)", err) - } - spt, err := adal.NewServicePrincipalToken(*oauthConfig, "id", "secret", "resource", nil) - if err != nil { - t.Fatalf("azure: BearerAuthorizer#WithAuthorization returned an error (%v)", err) - } - spt.SetAutoRefresh(false) - s := mocks.NewSender() - spt.SetSender(s) - - ba := NewBearerAuthorizer(spt) - req, err := Prepare(mocks.NewRequest(), ba.WithAuthorization()) - if err != nil { - t.Fatalf("azure: BearerAuthorizer#WithAuthorization returned an error (%v)", err) - } else if req.Header.Get(http.CanonicalHeaderKey("Authorization")) != fmt.Sprintf("Bearer %s", spt.AccessToken) { - t.Fatal("azure: BearerAuthorizer#WithAuthorization failed to set Authorization header") - } -} - -func TestServicePrincipalTokenWithAuthorizationRefresh(t *testing.T) { - - oauthConfig, err := adal.NewOAuthConfig(TestActiveDirectoryEndpoint, TestTenantID) - if err != nil { - t.Fatalf("azure: BearerAuthorizer#WithAuthorization returned an error (%v)", err) - } - refreshed := false - spt, err := adal.NewServicePrincipalToken(*oauthConfig, "id", "secret", "resource", func(t adal.Token) error { - refreshed = true - return nil - }) - if err != nil { - t.Fatalf("azure: BearerAuthorizer#WithAuthorization returned an error (%v)", err) - } - - jwt := `{ - "access_token" : "accessToken", - "expires_in" : "3600", - "expires_on" : "test", - "not_before" : "test", - "resource" : "test", - "token_type" : "Bearer" - }` - body := mocks.NewBody(jwt) - resp := mocks.NewResponseWithBodyAndStatus(body, http.StatusOK, "OK") - c := mocks.NewSender() - s := DecorateSender(c, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return resp, nil - }) - } - })()) - spt.SetSender(s) - - ba := NewBearerAuthorizer(spt) - req, err := Prepare(mocks.NewRequest(), ba.WithAuthorization()) - if err != nil { - t.Fatalf("azure: BearerAuthorizer#WithAuthorization returned an error (%v)", err) - } else if req.Header.Get(http.CanonicalHeaderKey("Authorization")) != fmt.Sprintf("Bearer %s", spt.AccessToken) { - t.Fatal("azure: BearerAuthorizer#WithAuthorization failed to set Authorization header") - } - - if !refreshed { - t.Fatal("azure: BearerAuthorizer#WithAuthorization must refresh the token") - } -} - -func TestServicePrincipalTokenWithAuthorizationReturnsErrorIfConnotRefresh(t *testing.T) { - oauthConfig, err := adal.NewOAuthConfig(TestActiveDirectoryEndpoint, TestTenantID) - if err != nil { - t.Fatalf("azure: BearerAuthorizer#WithAuthorization returned an error (%v)", err) - } - spt, err := adal.NewServicePrincipalToken(*oauthConfig, "id", "secret", "resource", nil) - if err != nil { - t.Fatalf("azure: BearerAuthorizer#WithAuthorization returned an error (%v)", err) - } - - s := mocks.NewSender() - s.AppendResponse(mocks.NewResponseWithStatus("400 Bad Request", http.StatusBadRequest)) - spt.SetSender(s) - - ba := NewBearerAuthorizer(spt) - _, err = Prepare(mocks.NewRequest(), ba.WithAuthorization()) - if err == nil { - t.Fatal("azure: BearerAuthorizer#WithAuthorization failed to return an error when refresh fails") - } -} - -func TestBearerAuthorizerCallback(t *testing.T) { - tenantString := "123-tenantID-456" - resourceString := "https://fake.resource.net" - - s := mocks.NewSender() - resp := mocks.NewResponseWithStatus("401 Unauthorized", http.StatusUnauthorized) - mocks.SetResponseHeader(resp, bearerChallengeHeader, bearer+" \"authorization\"=\"https://fake.net/"+tenantString+"\",\"resource\"=\""+resourceString+"\"") - s.AppendResponse(resp) - - auth := NewBearerAuthorizerCallback(s, func(tenantID, resource string) (*BearerAuthorizer, error) { - if tenantID != tenantString { - t.Fatal("BearerAuthorizerCallback: bad tenant ID") - } - if resource != resourceString { - t.Fatal("BearerAuthorizerCallback: bad resource") - } - - oauthConfig, err := adal.NewOAuthConfig(TestActiveDirectoryEndpoint, tenantID) - if err != nil { - t.Fatalf("azure: NewOAuthConfig returned an error (%v)", err) - } - - spt, err := adal.NewServicePrincipalToken(*oauthConfig, "id", "secret", resource) - if err != nil { - t.Fatalf("azure: NewServicePrincipalToken returned an error (%v)", err) - } - - spt.SetSender(s) - return NewBearerAuthorizer(spt), nil - }) - - _, err := Prepare(mocks.NewRequest(), auth.WithAuthorization()) - if err == nil { - t.Fatal("azure: BearerAuthorizerCallback#WithAuthorization failed to return an error when refresh fails") - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/autorest_test.go b/vendor/github.com/Azure/go-autorest/autorest/autorest_test.go deleted file mode 100644 index 467ea438b2..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/autorest_test.go +++ /dev/null @@ -1,140 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "net/http" - "testing" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -func TestResponseHasStatusCode(t *testing.T) { - codes := []int{http.StatusOK, http.StatusAccepted} - resp := &http.Response{StatusCode: http.StatusAccepted} - if !ResponseHasStatusCode(resp, codes...) { - t.Fatalf("autorest: ResponseHasStatusCode failed to find %v in %v", resp.StatusCode, codes) - } -} - -func TestResponseHasStatusCodeNotPresent(t *testing.T) { - codes := []int{http.StatusOK, http.StatusAccepted} - resp := &http.Response{StatusCode: http.StatusInternalServerError} - if ResponseHasStatusCode(resp, codes...) { - t.Fatalf("autorest: ResponseHasStatusCode unexpectedly found %v in %v", resp.StatusCode, codes) - } -} - -func TestNewPollingRequestDoesNotReturnARequestWhenLocationHeaderIsMissing(t *testing.T) { - resp := mocks.NewResponseWithStatus("500 InternalServerError", http.StatusInternalServerError) - - req, _ := NewPollingRequest(resp, nil) - if req != nil { - t.Fatal("autorest: NewPollingRequest returned an http.Request when the Location header was missing") - } -} - -func TestNewPollingRequestReturnsAnErrorWhenPrepareFails(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - resp.Header.Set(http.CanonicalHeaderKey(HeaderLocation), mocks.TestBadURL) - - _, err := NewPollingRequest(resp, nil) - if err == nil { - t.Fatal("autorest: NewPollingRequest failed to return an error when Prepare fails") - } -} - -func TestNewPollingRequestDoesNotReturnARequestWhenPrepareFails(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - resp.Header.Set(http.CanonicalHeaderKey(HeaderLocation), mocks.TestBadURL) - - req, _ := NewPollingRequest(resp, nil) - if req != nil { - t.Fatal("autorest: NewPollingRequest returned an http.Request when Prepare failed") - } -} - -func TestNewPollingRequestReturnsAGetRequest(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - - req, _ := NewPollingRequest(resp, nil) - if req.Method != "GET" { - t.Fatalf("autorest: NewPollingRequest did not create an HTTP GET request -- actual method %v", req.Method) - } -} - -func TestNewPollingRequestProvidesTheURL(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - - req, _ := NewPollingRequest(resp, nil) - if req.URL.String() != mocks.TestURL { - t.Fatalf("autorest: NewPollingRequest did not create an HTTP with the expected URL -- received %v, expected %v", req.URL, mocks.TestURL) - } -} - -func TestGetLocation(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - - l := GetLocation(resp) - if len(l) == 0 { - t.Fatalf("autorest: GetLocation failed to return Location header -- expected %v, received %v", mocks.TestURL, l) - } -} - -func TestGetLocationReturnsEmptyStringForMissingLocation(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - - l := GetLocation(resp) - if len(l) != 0 { - t.Fatalf("autorest: GetLocation return a value without a Location header -- received %v", l) - } -} - -func TestGetRetryAfter(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - - d := GetRetryAfter(resp, DefaultPollingDelay) - if d != mocks.TestDelay { - t.Fatalf("autorest: GetRetryAfter failed to returned the expected delay -- expected %v, received %v", mocks.TestDelay, d) - } -} - -func TestGetRetryAfterReturnsDefaultDelayIfRetryHeaderIsMissing(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - - d := GetRetryAfter(resp, DefaultPollingDelay) - if d != DefaultPollingDelay { - t.Fatalf("autorest: GetRetryAfter failed to returned the default delay for a missing Retry-After header -- expected %v, received %v", - DefaultPollingDelay, d) - } -} - -func TestGetRetryAfterReturnsDefaultDelayIfRetryHeaderIsMalformed(t *testing.T) { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - resp.Header.Set(http.CanonicalHeaderKey(HeaderRetryAfter), "a very bad non-integer value") - - d := GetRetryAfter(resp, DefaultPollingDelay) - if d != DefaultPollingDelay { - t.Fatalf("autorest: GetRetryAfter failed to returned the default delay for a malformed Retry-After header -- expected %v, received %v", - DefaultPollingDelay, d) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go index c8f495d853..366fc53793 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go @@ -39,7 +39,7 @@ const ( operationSucceeded string = "Succeeded" ) -var pollingCodes = [...]int{http.StatusAccepted, http.StatusCreated, http.StatusOK} +var pollingCodes = [...]int{http.StatusNoContent, http.StatusAccepted, http.StatusCreated, http.StatusOK} // Future provides a mechanism to access the status and results of an asynchronous request. // Since futures are stateful they should be passed by value to avoid race conditions. @@ -234,20 +234,15 @@ func getAsyncOperation(resp *http.Response) string { } func hasSucceeded(state string) bool { - return state == operationSucceeded + return strings.EqualFold(state, operationSucceeded) } func hasTerminated(state string) bool { - switch state { - case operationCanceled, operationFailed, operationSucceeded: - return true - default: - return false - } + return strings.EqualFold(state, operationCanceled) || strings.EqualFold(state, operationFailed) || strings.EqualFold(state, operationSucceeded) } func hasFailed(state string) bool { - return state == operationFailed + return strings.EqualFold(state, operationFailed) } type provisioningTracker interface { @@ -426,7 +421,7 @@ func updatePollingState(resp *http.Response, ps *pollingState) error { } } - if ps.State == operationInProgress && ps.URI == "" { + if strings.EqualFold(ps.State, operationInProgress) && ps.URI == "" { return autorest.NewError("azure", "updatePollingState", "Azure Polling Error - Unable to obtain polling URI for %s %s", resp.Request.Method, resp.Request.URL) } @@ -463,3 +458,21 @@ func newPollingRequest(ps pollingState) (*http.Request, error) { return reqPoll, nil } + +// AsyncOpIncompleteError is the type that's returned from a future that has not completed. +type AsyncOpIncompleteError struct { + // FutureType is the name of the type composed of a azure.Future. + FutureType string +} + +// Error returns an error message including the originating type name of the error. +func (e AsyncOpIncompleteError) Error() string { + return fmt.Sprintf("%s: asynchronous operation has not completed", e.FutureType) +} + +// NewAsyncOpIncompleteError creates a new AsyncOpIncompleteError with the specified parameters. +func NewAsyncOpIncompleteError(futureType string) AsyncOpIncompleteError { + return AsyncOpIncompleteError{ + FutureType: futureType, + } +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async_test.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async_test.go deleted file mode 100644 index 5757e25c22..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/async_test.go +++ /dev/null @@ -1,1327 +0,0 @@ -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "reflect" - "strings" - "sync" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/mocks" -) - -func TestGetAsyncOperation_ReturnsAzureAsyncOperationHeader(t *testing.T) { - r := newAsynchronousResponse() - - if getAsyncOperation(r) != mocks.TestAzureAsyncURL { - t.Fatalf("azure: getAsyncOperation failed to extract the Azure-AsyncOperation header -- expected %v, received %v", mocks.TestURL, getAsyncOperation(r)) - } -} - -func TestGetAsyncOperation_ReturnsEmptyStringIfHeaderIsAbsent(t *testing.T) { - r := mocks.NewResponse() - - if len(getAsyncOperation(r)) != 0 { - t.Fatalf("azure: getAsyncOperation failed to return empty string when the Azure-AsyncOperation header is absent -- received %v", getAsyncOperation(r)) - } -} - -func TestHasSucceeded_ReturnsTrueForSuccess(t *testing.T) { - if !hasSucceeded(operationSucceeded) { - t.Fatal("azure: hasSucceeded failed to return true for success") - } -} - -func TestHasSucceeded_ReturnsFalseOtherwise(t *testing.T) { - if hasSucceeded("not a success string") { - t.Fatal("azure: hasSucceeded returned true for a non-success") - } -} - -func TestHasTerminated_ReturnsTrueForValidTerminationStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - if !hasTerminated(state) { - t.Fatalf("azure: hasTerminated failed to return true for the '%s' state", state) - } - } -} - -func TestHasTerminated_ReturnsFalseForUnknownStates(t *testing.T) { - if hasTerminated("not a known state") { - t.Fatal("azure: hasTerminated returned true for an unknown state") - } -} - -func TestOperationError_ErrorReturnsAString(t *testing.T) { - s := (ServiceError{Code: "server code", Message: "server error"}).Error() - if s == "" { - t.Fatalf("azure: operationError#Error failed to return an error") - } - if !strings.Contains(s, "server code") || !strings.Contains(s, "server error") { - t.Fatalf("azure: operationError#Error returned a malformed error -- error='%v'", s) - } -} - -func TestOperationResource_StateReturnsState(t *testing.T) { - if (operationResource{Status: "state"}).state() != "state" { - t.Fatalf("azure: operationResource#state failed to return the correct state") - } -} - -func TestOperationResource_HasSucceededReturnsFalseIfNotSuccess(t *testing.T) { - if (operationResource{Status: "not a success string"}).hasSucceeded() { - t.Fatalf("azure: operationResource#hasSucceeded failed to return false for a canceled operation") - } -} - -func TestOperationResource_HasSucceededReturnsTrueIfSuccessful(t *testing.T) { - if !(operationResource{Status: operationSucceeded}).hasSucceeded() { - t.Fatalf("azure: operationResource#hasSucceeded failed to return true for a successful operation") - } -} - -func TestOperationResource_HasTerminatedReturnsTrueForKnownStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - if !(operationResource{Status: state}).hasTerminated() { - t.Fatalf("azure: operationResource#hasTerminated failed to return true for the '%s' state", state) - } - } -} - -func TestOperationResource_HasTerminatedReturnsFalseForUnknownStates(t *testing.T) { - if (operationResource{Status: "not a known state"}).hasTerminated() { - t.Fatalf("azure: operationResource#hasTerminated returned true for a non-terminal operation") - } -} - -func TestProvisioningStatus_StateReturnsState(t *testing.T) { - if (provisioningStatus{Properties: provisioningProperties{"state"}}).state() != "state" { - t.Fatalf("azure: provisioningStatus#state failed to return the correct state") - } -} - -func TestProvisioningStatus_HasSucceededReturnsFalseIfNotSuccess(t *testing.T) { - if (provisioningStatus{Properties: provisioningProperties{"not a success string"}}).hasSucceeded() { - t.Fatalf("azure: provisioningStatus#hasSucceeded failed to return false for a canceled operation") - } -} - -func TestProvisioningStatus_HasSucceededReturnsTrueIfSuccessful(t *testing.T) { - if !(provisioningStatus{Properties: provisioningProperties{operationSucceeded}}).hasSucceeded() { - t.Fatalf("azure: provisioningStatus#hasSucceeded failed to return true for a successful operation") - } -} - -func TestProvisioningStatus_HasTerminatedReturnsTrueForKnownStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - if !(provisioningStatus{Properties: provisioningProperties{state}}).hasTerminated() { - t.Fatalf("azure: provisioningStatus#hasTerminated failed to return true for the '%s' state", state) - } - } -} - -func TestProvisioningStatus_HasTerminatedReturnsFalseForUnknownStates(t *testing.T) { - if (provisioningStatus{Properties: provisioningProperties{"not a known state"}}).hasTerminated() { - t.Fatalf("azure: provisioningStatus#hasTerminated returned true for a non-terminal operation") - } -} - -func TestPollingState_HasSucceededReturnsFalseIfNotSuccess(t *testing.T) { - if (pollingState{State: "not a success string"}).hasSucceeded() { - t.Fatalf("azure: pollingState#hasSucceeded failed to return false for a canceled operation") - } -} - -func TestPollingState_HasSucceededReturnsTrueIfSuccessful(t *testing.T) { - if !(pollingState{State: operationSucceeded}).hasSucceeded() { - t.Fatalf("azure: pollingState#hasSucceeded failed to return true for a successful operation") - } -} - -func TestPollingState_HasTerminatedReturnsTrueForKnownStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - if !(pollingState{State: state}).hasTerminated() { - t.Fatalf("azure: pollingState#hasTerminated failed to return true for the '%s' state", state) - } - } -} - -func TestPollingState_HasTerminatedReturnsFalseForUnknownStates(t *testing.T) { - if (pollingState{State: "not a known state"}).hasTerminated() { - t.Fatalf("azure: pollingState#hasTerminated returned true for a non-terminal operation") - } -} - -func TestUpdatePollingState_ReturnsAnErrorIfOneOccurs(t *testing.T) { - resp := mocks.NewResponseWithContent(operationResourceIllegal) - err := updatePollingState(resp, &pollingState{}) - if err == nil { - t.Fatalf("azure: updatePollingState failed to return an error after a JSON parsing error") - } -} - -func TestUpdatePollingState_ReturnsTerminatedForKnownProvisioningStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - resp := mocks.NewResponseWithContent(fmt.Sprintf(pollingStateFormat, state)) - resp.StatusCode = 42 - ps := &pollingState{PollingMethod: PollingLocation} - updatePollingState(resp, ps) - if !ps.hasTerminated() { - t.Fatalf("azure: updatePollingState failed to return a terminating pollingState for the '%s' state", state) - } - } -} - -func TestUpdatePollingState_ReturnsSuccessForSuccessfulProvisioningState(t *testing.T) { - resp := mocks.NewResponseWithContent(fmt.Sprintf(pollingStateFormat, operationSucceeded)) - resp.StatusCode = 42 - ps := &pollingState{PollingMethod: PollingLocation} - updatePollingState(resp, ps) - if !ps.hasSucceeded() { - t.Fatalf("azure: updatePollingState failed to return a successful pollingState for the '%s' state", operationSucceeded) - } -} - -func TestUpdatePollingState_ReturnsInProgressForAllOtherProvisioningStates(t *testing.T) { - s := "not a recognized state" - resp := mocks.NewResponseWithContent(fmt.Sprintf(pollingStateFormat, s)) - resp.StatusCode = 42 - ps := &pollingState{PollingMethod: PollingLocation} - updatePollingState(resp, ps) - if ps.hasTerminated() { - t.Fatalf("azure: updatePollingState returned terminated for unknown state '%s'", s) - } -} - -func TestUpdatePollingState_ReturnsSuccessWhenProvisioningStateFieldIsAbsentForSuccessStatusCodes(t *testing.T) { - for _, sc := range []int{http.StatusOK, http.StatusCreated, http.StatusNoContent} { - resp := mocks.NewResponseWithContent(pollingStateEmpty) - resp.StatusCode = sc - ps := &pollingState{PollingMethod: PollingLocation} - updatePollingState(resp, ps) - if !ps.hasSucceeded() { - t.Fatalf("azure: updatePollingState failed to return success when the provisionState field is absent for Status Code %d", sc) - } - } -} - -func TestUpdatePollingState_ReturnsInProgressWhenProvisioningStateFieldIsAbsentForAccepted(t *testing.T) { - resp := mocks.NewResponseWithContent(pollingStateEmpty) - resp.StatusCode = http.StatusAccepted - ps := &pollingState{PollingMethod: PollingLocation} - updatePollingState(resp, ps) - if ps.hasTerminated() { - t.Fatalf("azure: updatePollingState returned terminated when the provisionState field is absent for Status Code Accepted") - } -} - -func TestUpdatePollingState_ReturnsFailedWhenProvisioningStateFieldIsAbsentForUnknownStatusCodes(t *testing.T) { - resp := mocks.NewResponseWithContent(pollingStateEmpty) - resp.StatusCode = 42 - ps := &pollingState{PollingMethod: PollingLocation} - updatePollingState(resp, ps) - if !ps.hasTerminated() || ps.hasSucceeded() { - t.Fatalf("azure: updatePollingState did not return failed when the provisionState field is absent for an unknown Status Code") - } -} - -func TestUpdatePollingState_ReturnsTerminatedForKnownOperationResourceStates(t *testing.T) { - for _, state := range []string{operationSucceeded, operationCanceled, operationFailed} { - resp := mocks.NewResponseWithContent(fmt.Sprintf(operationResourceFormat, state)) - resp.StatusCode = 42 - ps := &pollingState{PollingMethod: PollingAsyncOperation} - updatePollingState(resp, ps) - if !ps.hasTerminated() { - t.Fatalf("azure: updatePollingState failed to return a terminating pollingState for the '%s' state", state) - } - } -} - -func TestUpdatePollingState_ReturnsSuccessForSuccessfulOperationResourceState(t *testing.T) { - resp := mocks.NewResponseWithContent(fmt.Sprintf(operationResourceFormat, operationSucceeded)) - resp.StatusCode = 42 - ps := &pollingState{PollingMethod: PollingAsyncOperation} - updatePollingState(resp, ps) - if !ps.hasSucceeded() { - t.Fatalf("azure: updatePollingState failed to return a successful pollingState for the '%s' state", operationSucceeded) - } -} - -func TestUpdatePollingState_ReturnsInProgressForAllOtherOperationResourceStates(t *testing.T) { - s := "not a recognized state" - resp := mocks.NewResponseWithContent(fmt.Sprintf(operationResourceFormat, s)) - resp.StatusCode = 42 - ps := &pollingState{PollingMethod: PollingAsyncOperation} - updatePollingState(resp, ps) - if ps.hasTerminated() { - t.Fatalf("azure: updatePollingState returned terminated for unknown state '%s'", s) - } -} - -func TestUpdatePollingState_CopiesTheResponseBody(t *testing.T) { - s := fmt.Sprintf(pollingStateFormat, operationSucceeded) - resp := mocks.NewResponseWithContent(s) - resp.StatusCode = 42 - ps := &pollingState{PollingMethod: PollingAsyncOperation} - updatePollingState(resp, ps) - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Fatalf("azure: updatePollingState failed to replace the http.Response Body -- Error='%v'", err) - } - if string(b) != s { - t.Fatalf("azure: updatePollingState failed to copy the http.Response Body -- Expected='%s' Received='%s'", s, string(b)) - } -} - -func TestUpdatePollingState_ClosesTheOriginalResponseBody(t *testing.T) { - resp := mocks.NewResponse() - b := resp.Body.(*mocks.Body) - ps := &pollingState{PollingMethod: PollingLocation} - updatePollingState(resp, ps) - if b.IsOpen() { - t.Fatal("azure: updatePollingState failed to close the original http.Response Body") - } -} - -func TestUpdatePollingState_FailsWhenResponseLacksRequest(t *testing.T) { - resp := newAsynchronousResponse() - resp.Request = nil - - ps := pollingState{} - err := updatePollingState(resp, &ps) - if err == nil { - t.Fatal("azure: updatePollingState failed to return an error when the http.Response lacked the original http.Request") - } -} - -func TestUpdatePollingState_SetsThePollingMethodWhenUsingTheAzureAsyncOperationHeader(t *testing.T) { - ps := pollingState{} - updatePollingState(newAsynchronousResponse(), &ps) - - if ps.PollingMethod != PollingAsyncOperation { - t.Fatal("azure: updatePollingState failed to set the correct response format when using the Azure-AsyncOperation header") - } -} - -func TestUpdatePollingState_SetsThePollingMethodWhenUsingTheAzureAsyncOperationHeaderIsMissing(t *testing.T) { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - ps := pollingState{} - updatePollingState(resp, &ps) - - if ps.PollingMethod != PollingLocation { - t.Fatal("azure: updatePollingState failed to set the correct response format when the Azure-AsyncOperation header is absent") - } -} - -func TestUpdatePollingState_DoesNotChangeAnExistingReponseFormat(t *testing.T) { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - ps := pollingState{PollingMethod: PollingAsyncOperation} - updatePollingState(resp, &ps) - - if ps.PollingMethod != PollingAsyncOperation { - t.Fatal("azure: updatePollingState failed to leave an existing response format setting") - } -} - -func TestUpdatePollingState_PrefersTheAzureAsyncOperationHeader(t *testing.T) { - resp := newAsynchronousResponse() - - ps := pollingState{} - updatePollingState(resp, &ps) - - if ps.URI != mocks.TestAzureAsyncURL { - t.Fatal("azure: updatePollingState failed to prefer the Azure-AsyncOperation header") - } -} - -func TestUpdatePollingState_PrefersLocationWhenTheAzureAsyncOperationHeaderMissing(t *testing.T) { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - ps := pollingState{} - updatePollingState(resp, &ps) - - if ps.URI != mocks.TestLocationURL { - t.Fatal("azure: updatePollingState failed to prefer the Location header when the Azure-AsyncOperation header is missing") - } -} - -func TestUpdatePollingState_UsesTheObjectLocationIfAsyncHeadersAreMissing(t *testing.T) { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - resp.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation)) - resp.Request.Method = http.MethodPatch - - ps := pollingState{} - updatePollingState(resp, &ps) - - if ps.URI != mocks.TestURL { - t.Fatal("azure: updatePollingState failed to use the Object URL when the asynchronous headers are missing") - } -} - -func TestUpdatePollingState_RecognizesLowerCaseHTTPVerbs(t *testing.T) { - for _, m := range []string{strings.ToLower(http.MethodPatch), strings.ToLower(http.MethodPut), strings.ToLower(http.MethodGet)} { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - resp.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation)) - resp.Request.Method = m - - ps := pollingState{} - updatePollingState(resp, &ps) - - if ps.URI != mocks.TestURL { - t.Fatalf("azure: updatePollingState failed to recognize the lower-case HTTP verb '%s'", m) - } - } -} - -func TestUpdatePollingState_ReturnsAnErrorIfAsyncHeadersAreMissingForANewOrDeletedObject(t *testing.T) { - resp := newAsynchronousResponse() - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - resp.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation)) - - for _, m := range []string{http.MethodDelete, http.MethodPost} { - resp.Request.Method = m - err := updatePollingState(resp, &pollingState{}) - if err == nil { - t.Fatalf("azure: updatePollingState failed to return an error even though it could not determine the polling URL for Method '%s'", m) - } - } -} - -func TestNewPollingRequest_ReturnsAnErrorWhenPrepareFails(t *testing.T) { - _, err := newPollingRequest(pollingState{PollingMethod: PollingAsyncOperation, URI: mocks.TestBadURL}) - if err == nil { - t.Fatal("azure: newPollingRequest failed to return an error when Prepare fails") - } -} - -func TestNewPollingRequest_DoesNotReturnARequestWhenPrepareFails(t *testing.T) { - req, _ := newPollingRequest(pollingState{PollingMethod: PollingAsyncOperation, URI: mocks.TestBadURL}) - if req != nil { - t.Fatal("azure: newPollingRequest returned an http.Request when Prepare failed") - } -} - -func TestNewPollingRequest_ReturnsAGetRequest(t *testing.T) { - req, _ := newPollingRequest(pollingState{PollingMethod: PollingAsyncOperation, URI: mocks.TestAzureAsyncURL}) - if req.Method != "GET" { - t.Fatalf("azure: newPollingRequest did not create an HTTP GET request -- actual method %v", req.Method) - } -} - -func TestDoPollForAsynchronous_IgnoresUnspecifiedStatusCodes(t *testing.T) { - client := mocks.NewSender() - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Duration(0))) - - if client.Attempts() != 1 { - t.Fatalf("azure: DoPollForAsynchronous polled for unspecified status code") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsForSpecifiedStatusCodes(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAsynchronousResponse()) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() != 2 { - t.Fatalf("azure: DoPollForAsynchronous failed to poll for specified status code") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_CanBeCanceled(t *testing.T) { - cancel := make(chan struct{}) - delay := 5 * time.Second - - r1 := newAsynchronousResponse() - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(newOperationResourceResponse("Busy"), -1) - - var wg sync.WaitGroup - wg.Add(1) - start := time.Now() - go func() { - req := mocks.NewRequest() - req.Cancel = cancel - - wg.Done() - - r, _ := autorest.SendWithSender(client, req, - DoPollForAsynchronous(10*time.Second)) - autorest.Respond(r, - autorest.ByClosing()) - }() - wg.Wait() - close(cancel) - time.Sleep(5 * time.Millisecond) - if time.Since(start) >= delay { - t.Fatalf("azure: DoPollForAsynchronous failed to cancel") - } -} - -func TestDoPollForAsynchronous_ClosesAllNonreturnedResponseBodiesWhenPolling(t *testing.T) { - r1 := newAsynchronousResponse() - b1 := r1.Body.(*mocks.Body) - r2 := newOperationResourceResponse("busy") - b2 := r2.Body.(*mocks.Body) - r3 := newOperationResourceResponse(operationSucceeded) - b3 := r3.Body.(*mocks.Body) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendResponse(r3) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if b1.IsOpen() || b2.IsOpen() || b3.IsOpen() { - t.Fatalf("azure: DoPollForAsynchronous did not close unreturned response bodies") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_LeavesLastResponseBodyOpen(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationSucceeded) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendResponse(r3) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - b, err := ioutil.ReadAll(r.Body) - if len(b) <= 0 || err != nil { - t.Fatalf("azure: DoPollForAsynchronous did not leave open the body of the last response - Error='%v'", err) - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_DoesNotPollIfOriginalRequestReturnedAnError(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendResponse(r2) - client.SetError(fmt.Errorf("Faux Error")) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() != 1 { - t.Fatalf("azure: DoPollForAsynchronous tried to poll after receiving an error") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_DoesNotPollIfCreatingOperationRequestFails(t *testing.T) { - r1 := newAsynchronousResponse() - mocks.SetResponseHeader(r1, http.CanonicalHeaderKey(headerAsyncOperation), mocks.TestBadURL) - r2 := newOperationResourceResponse("busy") - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() > 1 { - t.Fatalf("azure: DoPollForAsynchronous polled with an invalidly formed operation request") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_StopsPollingAfterAnError(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.SetError(fmt.Errorf("Faux Error")) - client.SetEmitErrorAfter(2) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() > 3 { - t.Fatalf("azure: DoPollForAsynchronous failed to stop polling after receiving an error") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsPollingError(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(newAsynchronousResponse(), 5) - client.SetError(fmt.Errorf("Faux Error")) - client.SetEmitErrorAfter(1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if err == nil { - t.Fatalf("azure: DoPollForAsynchronous failed to return error from polling") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsForStatusAccepted(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Status = "202 Accepted" - r1.StatusCode = http.StatusAccepted - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationCanceled) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < client.NumResponses() { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsForStatusCreated(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Status = "201 Created" - r1.StatusCode = http.StatusCreated - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationCanceled) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < client.NumResponses() { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsUntilProvisioningStatusTerminates(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3 := newProvisioningStatusResponse(operationCanceled) - r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < client.NumResponses() { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsUntilProvisioningStatusSucceeds(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3 := newProvisioningStatusResponse(operationSucceeded) - r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < client.NumResponses() { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsUntilOperationResourceHasTerminated(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationCanceled) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < client.NumResponses() { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_PollsUntilOperationResourceHasSucceeded(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationSucceeded) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() < client.NumResponses() { - t.Fatalf("azure: DoPollForAsynchronous stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_StopsPollingWhenOperationResourceHasTerminated(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse(operationCanceled) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 2) - - r, _ := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() > 4 { - t.Fatalf("azure: DoPollForAsynchronous failed to stop after receiving a terminated OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsAnErrorForCanceledOperations(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceErrorResponse(operationCanceled) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if err == nil || !strings.Contains(fmt.Sprintf("%v", err), "Canceled") { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error for a canceled OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsAnErrorForFailedOperations(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceErrorResponse(operationFailed) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if err == nil || !strings.Contains(fmt.Sprintf("%v", err), "Failed") { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error for a canceled OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_WithNilURI(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r1.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation)) - - r2 := newOperationResourceResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2.Header.Del(http.CanonicalHeaderKey(autorest.HeaderLocation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendResponse(r2) - - req, _ := http.NewRequest("POST", "https://microsoft.com/a/b/c/", mocks.NewBody("")) - r, err := autorest.SendWithSender(client, req, - DoPollForAsynchronous(time.Millisecond)) - - if err == nil { - t.Fatalf("azure: DoPollForAsynchronous failed to return error for nil URI. got: nil; want: Azure Polling Error - Unable to obtain polling URI for POST") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsAnUnknownErrorForFailedOperations(t *testing.T) { - // Return unknown error if error not present in last response - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3 := newProvisioningStatusResponse(operationFailed) - r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - expected := makeLongRunningOperationErrorString("Unknown", "None") - if err.Error() != expected { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for an unknown error. \n expected=%q \n got=%q", - expected, err.Error()) - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsErrorForLastErrorResponse(t *testing.T) { - // Return error code and message if error present in last response - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3 := newAsynchronousResponseWithError("400 Bad Request", http.StatusBadRequest) - r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - expected := makeLongRunningOperationErrorString("InvalidParameter", "tom-service-DISCOVERY-server-base-v1.core.local' is not a valid captured VHD blob name prefix.") - if err.Error() != expected { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for an unknown error. \n expected=%q \n got=%q", - expected, err.Error()) - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsOperationResourceErrorForFailedOperations(t *testing.T) { - // Return Operation resource response with error code and message in last operation resource response - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceErrorResponse(operationFailed) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - expected := makeLongRunningOperationErrorString("BadArgument", "The provided database 'foo' has an invalid username.") - if err.Error() != expected { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for a failed Operations. \n expected=%q \n got=%q", - expected, err.Error()) - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_ReturnsErrorForFirstPutRequest(t *testing.T) { - // Return 400 bad response with error code and message in first put - r1 := newAsynchronousResponseWithError("400 Bad Request", http.StatusBadRequest) - client := mocks.NewSender() - client.AppendResponse(r1) - - res, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - if err != nil { - t.Fatalf("azure: DoPollForAsynchronous failed to return an appropriate error message for a failed Operations. \n expected=%q \n got=%q", - errorResponse, err.Error()) - } - - err = autorest.Respond(res, - WithErrorUnlessStatusCode(http.StatusAccepted, http.StatusCreated, http.StatusOK), - autorest.ByClosing()) - - reqError, ok := err.(*RequestError) - if !ok { - t.Fatalf("azure: returned error is not azure.RequestError: %T", err) - } - - expected := &RequestError{ - ServiceError: &ServiceError{ - Code: "InvalidParameter", - Message: "tom-service-DISCOVERY-server-base-v1.core.local' is not a valid captured VHD blob name prefix.", - }, - DetailedError: autorest.DetailedError{ - StatusCode: 400, - }, - } - if !reflect.DeepEqual(reqError, expected) { - t.Fatalf("azure: wrong error. expected=%q\ngot=%q", expected, reqError) - } - - defer res.Body.Close() - b, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if string(b) != errorResponse { - t.Fatalf("azure: Response body is wrong. got=%q expected=%q", string(b), errorResponse) - } - -} - -func TestDoPollForAsynchronous_ReturnsNoErrorForSuccessfulOperations(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceErrorResponse(operationSucceeded) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if err != nil { - t.Fatalf("azure: DoPollForAsynchronous returned an error for a successful OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestDoPollForAsynchronous_StopsPollingIfItReceivesAnInvalidOperationResource(t *testing.T) { - r1 := newAsynchronousResponse() - r2 := newOperationResourceResponse("busy") - r3 := newOperationResourceResponse("busy") - r3.Body = mocks.NewBody(operationResourceIllegal) - r4 := newOperationResourceResponse(operationSucceeded) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendAndRepeatResponse(r3, 1) - client.AppendAndRepeatResponse(r4, 1) - - r, err := autorest.SendWithSender(client, mocks.NewRequest(), - DoPollForAsynchronous(time.Millisecond)) - - if client.Attempts() > 4 { - t.Fatalf("azure: DoPollForAsynchronous failed to stop polling after receiving an invalid OperationResource") - } - if err == nil { - t.Fatalf("azure: DoPollForAsynchronous failed to return an error after receving an invalid OperationResource") - } - - autorest.Respond(r, - autorest.ByClosing()) -} - -func TestFuture_PollsUntilProvisioningStatusSucceeds(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3 := newProvisioningStatusResponse(operationSucceeded) - r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - client := mocks.NewSender() - client.AppendResponse(r1) - client.AppendAndRepeatResponse(r2, 2) - client.AppendResponse(r3) - - future := NewFuture(mocks.NewRequest()) - - for done, err := future.Done(client); !done; done, err = future.Done(client) { - if future.PollingMethod() != PollingLocation { - t.Fatalf("azure: wrong future polling method") - } - if err != nil { - t.Fatalf("azure: TestFuture polling Done failed") - } - delay, ok := future.GetPollingDelay() - if !ok { - t.Fatalf("expected Retry-After value") - } - time.Sleep(delay) - } - - if client.Attempts() < client.NumResponses() { - t.Fatalf("azure: TestFuture stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(future.Response(), - autorest.ByClosing()) -} - -func TestFuture_Marshalling(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAsynchronousResponse()) - - future := NewFuture(mocks.NewRequest()) - done, err := future.Done(client) - if err != nil { - t.Fatalf("azure: TestFuture marshalling Done failed") - } - if done { - t.Fatalf("azure: TestFuture marshalling shouldn't be done") - } - if future.PollingMethod() != PollingAsyncOperation { - t.Fatalf("azure: wrong future polling method") - } - - data, err := json.Marshal(future) - if err != nil { - t.Fatalf("azure: TestFuture failed to marshal") - } - - var future2 Future - err = json.Unmarshal(data, &future2) - if err != nil { - t.Fatalf("azure: TestFuture failed to unmarshal") - } - - if future.ps.Code != future2.ps.Code { - t.Fatalf("azure: TestFuture marshalling codes don't match") - } - if future.ps.Message != future2.ps.Message { - t.Fatalf("azure: TestFuture marshalling messages don't match") - } - if future.ps.PollingMethod != future2.ps.PollingMethod { - t.Fatalf("azure: TestFuture marshalling response formats don't match") - } - if future.ps.State != future2.ps.State { - t.Fatalf("azure: TestFuture marshalling states don't match") - } - if future.ps.URI != future2.ps.URI { - t.Fatalf("azure: TestFuture marshalling URIs don't match") - } -} - -func TestFuture_WaitForCompletion(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3 := newAsynchronousResponseWithError("Internal server error", http.StatusInternalServerError) - r3.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r3.Header.Del(http.CanonicalHeaderKey("Retry-After")) - r4 := newProvisioningStatusResponse(operationSucceeded) - r4.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - sender := mocks.NewSender() - sender.AppendResponse(r1) - sender.AppendError(errors.New("transient network failure")) - sender.AppendAndRepeatResponse(r2, 2) - sender.AppendResponse(r3) - sender.AppendResponse(r4) - - future := NewFuture(mocks.NewRequest()) - - client := autorest.Client{ - PollingDelay: 1 * time.Second, - PollingDuration: autorest.DefaultPollingDuration, - RetryAttempts: autorest.DefaultRetryAttempts, - RetryDuration: 1 * time.Second, - Sender: sender, - } - - err := future.WaitForCompletion(context.Background(), client) - if err != nil { - t.Fatalf("azure: WaitForCompletion returned non-nil error") - } - - if sender.Attempts() < sender.NumResponses() { - t.Fatalf("azure: TestFuture stopped polling before receiving a terminated OperationResource") - } - - autorest.Respond(future.Response(), - autorest.ByClosing()) -} - -func TestFuture_WaitForCompletionTimedOut(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - sender := mocks.NewSender() - sender.AppendResponse(r1) - sender.AppendAndRepeatResponseWithDelay(r2, 1*time.Second, 5) - - future := NewFuture(mocks.NewRequest()) - - client := autorest.Client{ - PollingDelay: autorest.DefaultPollingDelay, - PollingDuration: 2 * time.Second, - RetryAttempts: autorest.DefaultRetryAttempts, - RetryDuration: 1 * time.Second, - Sender: sender, - } - - err := future.WaitForCompletion(context.Background(), client) - if err == nil { - t.Fatalf("azure: WaitForCompletion returned nil error, should have timed out") - } -} - -func TestFuture_WaitForCompletionRetriesExceeded(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - sender := mocks.NewSender() - sender.AppendResponse(r1) - sender.AppendAndRepeatError(errors.New("transient network failure"), autorest.DefaultRetryAttempts+1) - - future := NewFuture(mocks.NewRequest()) - - client := autorest.Client{ - PollingDelay: autorest.DefaultPollingDelay, - PollingDuration: autorest.DefaultPollingDuration, - RetryAttempts: autorest.DefaultRetryAttempts, - RetryDuration: 100 * time.Millisecond, - Sender: sender, - } - - err := future.WaitForCompletion(context.Background(), client) - if err == nil { - t.Fatalf("azure: WaitForCompletion returned nil error, should have errored out") - } -} - -func TestFuture_WaitForCompletionCancelled(t *testing.T) { - r1 := newAsynchronousResponse() - r1.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - r2 := newProvisioningStatusResponse("busy") - r2.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - - sender := mocks.NewSender() - sender.AppendResponse(r1) - sender.AppendAndRepeatResponseWithDelay(r2, 1*time.Second, 5) - - future := NewFuture(mocks.NewRequest()) - - client := autorest.Client{ - PollingDelay: autorest.DefaultPollingDelay, - PollingDuration: autorest.DefaultPollingDuration, - RetryAttempts: autorest.DefaultRetryAttempts, - RetryDuration: autorest.DefaultRetryDuration, - Sender: sender, - } - - ctx, cancel := context.WithCancel(context.Background()) - go func() { - time.Sleep(2 * time.Second) - cancel() - }() - - err := future.WaitForCompletion(ctx, client) - if err == nil { - t.Fatalf("azure: WaitForCompletion returned nil error, should have been cancelled") - } -} - -const ( - operationResourceIllegal = ` - This is not JSON and should fail...badly. - ` - pollingStateFormat = ` - { - "unused" : { - "somefield" : 42 - }, - "properties" : { - "provisioningState": "%s" - } - } - ` - - errorResponse = ` - { - "error" : { - "code" : "InvalidParameter", - "message" : "tom-service-DISCOVERY-server-base-v1.core.local' is not a valid captured VHD blob name prefix." - } - } - ` - - pollingStateEmpty = ` - { - "unused" : { - "somefield" : 42 - }, - "properties" : { - } - } - ` - - operationResourceFormat = ` - { - "id": "/subscriptions/id/locations/westus/operationsStatus/sameguid", - "name": "sameguid", - "status" : "%s", - "startTime" : "2006-01-02T15:04:05Z", - "endTime" : "2006-01-02T16:04:05Z", - "percentComplete" : 50.00, - - "properties" : {} - } - ` - - operationResourceErrorFormat = ` - { - "id": "/subscriptions/id/locations/westus/operationsStatus/sameguid", - "name": "sameguid", - "status" : "%s", - "startTime" : "2006-01-02T15:04:05Z", - "endTime" : "2006-01-02T16:04:05Z", - "percentComplete" : 50.00, - - "properties" : {}, - "error" : { - "code" : "BadArgument", - "message" : "The provided database 'foo' has an invalid username." - } - } - ` -) - -func newAsynchronousResponse() *http.Response { - r := mocks.NewResponseWithStatus("201 Created", http.StatusCreated) - r.Body = mocks.NewBody(fmt.Sprintf(pollingStateFormat, operationInProgress)) - mocks.SetResponseHeader(r, http.CanonicalHeaderKey(headerAsyncOperation), mocks.TestAzureAsyncURL) - mocks.SetResponseHeader(r, http.CanonicalHeaderKey(autorest.HeaderLocation), mocks.TestLocationURL) - mocks.SetRetryHeader(r, retryDelay) - r.Request = mocks.NewRequestForURL(mocks.TestURL) - return r -} - -func newAsynchronousResponseWithError(response string, status int) *http.Response { - r := mocks.NewResponseWithStatus(response, status) - mocks.SetRetryHeader(r, retryDelay) - r.Request = mocks.NewRequestForURL(mocks.TestURL) - r.Body = mocks.NewBody(errorResponse) - return r -} - -func newOperationResourceResponse(status string) *http.Response { - r := newAsynchronousResponse() - r.Body = mocks.NewBody(fmt.Sprintf(operationResourceFormat, status)) - return r -} - -func newOperationResourceErrorResponse(status string) *http.Response { - r := newAsynchronousResponse() - r.Body = mocks.NewBody(fmt.Sprintf(operationResourceErrorFormat, status)) - return r -} - -func newProvisioningStatusResponse(status string) *http.Response { - r := newAsynchronousResponse() - r.Body = mocks.NewBody(fmt.Sprintf(pollingStateFormat, status)) - return r -} - -func makeLongRunningOperationErrorString(code string, message string) string { - return fmt.Sprintf("Long running operation terminated with status 'Failed': Code=%q Message=%q", code, message) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/azure_test.go b/vendor/github.com/Azure/go-autorest/autorest/azure/azure_test.go deleted file mode 100644 index e8bddbbfd4..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/azure_test.go +++ /dev/null @@ -1,513 +0,0 @@ -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/mocks" -) - -const ( - headerAuthorization = "Authorization" - longDelay = 5 * time.Second - retryDelay = 10 * time.Millisecond - testLogPrefix = "azure:" -) - -// Use a Client Inspector to set the request identifier. -func ExampleWithClientID() { - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - req, _ := autorest.Prepare(&http.Request{}, - autorest.AsGet(), - autorest.WithBaseURL("https://microsoft.com/a/b/c/")) - - c := autorest.Client{Sender: mocks.NewSender()} - c.RequestInspector = WithReturningClientID(uuid) - - autorest.SendWithSender(c, req) - fmt.Printf("Inspector added the %s header with the value %s\n", - HeaderClientID, req.Header.Get(HeaderClientID)) - fmt.Printf("Inspector added the %s header with the value %s\n", - HeaderReturnClientID, req.Header.Get(HeaderReturnClientID)) - // Output: - // Inspector added the x-ms-client-request-id header with the value 71FDB9F4-5E49-4C12-B266-DE7B4FD999A6 - // Inspector added the x-ms-return-client-request-id header with the value true -} - -func TestWithReturningClientIDReturnsError(t *testing.T) { - var errIn error - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - _, errOut := autorest.Prepare(&http.Request{}, - withErrorPrepareDecorator(&errIn), - WithReturningClientID(uuid)) - - if errOut == nil || errIn != errOut { - t.Fatalf("azure: WithReturningClientID failed to exit early when receiving an error -- expected (%v), received (%v)", - errIn, errOut) - } -} - -func TestWithClientID(t *testing.T) { - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - req, _ := autorest.Prepare(&http.Request{}, - WithClientID(uuid)) - - if req.Header.Get(HeaderClientID) != uuid { - t.Fatalf("azure: WithClientID failed to set %s -- expected %s, received %s", - HeaderClientID, uuid, req.Header.Get(HeaderClientID)) - } -} - -func TestWithReturnClientID(t *testing.T) { - b := false - req, _ := autorest.Prepare(&http.Request{}, - WithReturnClientID(b)) - - if req.Header.Get(HeaderReturnClientID) != strconv.FormatBool(b) { - t.Fatalf("azure: WithReturnClientID failed to set %s -- expected %s, received %s", - HeaderClientID, strconv.FormatBool(b), req.Header.Get(HeaderClientID)) - } -} - -func TestExtractClientID(t *testing.T) { - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - resp := mocks.NewResponse() - mocks.SetResponseHeader(resp, HeaderClientID, uuid) - - if ExtractClientID(resp) != uuid { - t.Fatalf("azure: ExtractClientID failed to extract the %s -- expected %s, received %s", - HeaderClientID, uuid, ExtractClientID(resp)) - } -} - -func TestExtractRequestID(t *testing.T) { - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - resp := mocks.NewResponse() - mocks.SetResponseHeader(resp, HeaderRequestID, uuid) - - if ExtractRequestID(resp) != uuid { - t.Fatalf("azure: ExtractRequestID failed to extract the %s -- expected %s, received %s", - HeaderRequestID, uuid, ExtractRequestID(resp)) - } -} - -func TestIsAzureError_ReturnsTrueForAzureError(t *testing.T) { - if !IsAzureError(&RequestError{}) { - t.Fatalf("azure: IsAzureError failed to return true for an Azure Service error") - } -} - -func TestIsAzureError_ReturnsFalseForNonAzureError(t *testing.T) { - if IsAzureError(fmt.Errorf("An Error")) { - t.Fatalf("azure: IsAzureError return true for an non-Azure Service error") - } -} - -func TestNewErrorWithError_UsesReponseStatusCode(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("Error"), "packageType", "method", mocks.NewResponseWithStatus("Forbidden", http.StatusForbidden), "message") - if e.StatusCode != http.StatusForbidden { - t.Fatalf("azure: NewErrorWithError failed to use the Status Code of the passed Response -- expected %v, received %v", http.StatusForbidden, e.StatusCode) - } -} - -func TestNewErrorWithError_ReturnsUnwrappedError(t *testing.T) { - e1 := RequestError{} - e1.ServiceError = &ServiceError{Code: "42", Message: "A Message"} - e1.StatusCode = 200 - e1.RequestID = "A RequestID" - e2 := NewErrorWithError(&e1, "packageType", "method", nil, "message") - - if !reflect.DeepEqual(e1, e2) { - t.Fatalf("azure: NewErrorWithError wrapped an RequestError -- expected %T, received %T", e1, e2) - } -} - -func TestNewErrorWithError_WrapsAnError(t *testing.T) { - e1 := fmt.Errorf("Inner Error") - var e2 interface{} = NewErrorWithError(e1, "packageType", "method", nil, "message") - - if _, ok := e2.(RequestError); !ok { - t.Fatalf("azure: NewErrorWithError failed to wrap a standard error -- received %T", e2) - } -} - -func TestWithErrorUnlessStatusCode_NotAnAzureError(t *testing.T) { - body := ` - - IIS Error page - - Some non-JSON error page - ` - r := mocks.NewResponseWithContent(body) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusBadRequest - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - ok, _ := err.(*RequestError) - if ok != nil { - t.Fatalf("azure: azure.RequestError returned from malformed response: %v", err) - } - - // the error body should still be there - defer r.Body.Close() - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - if string(b) != body { - t.Fatalf("response body is wrong. got=%q exptected=%q", string(b), body) - } -} - -func TestWithErrorUnlessStatusCode_FoundAzureErrorWithoutDetails(t *testing.T) { - j := `{ - "error": { - "code": "InternalError", - "message": "Azure is having trouble right now." - } - }` - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - r := mocks.NewResponseWithContent(j) - mocks.SetResponseHeader(r, HeaderRequestID, uuid) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusInternalServerError - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - - if err == nil { - t.Fatalf("azure: returned nil error for proper error response") - } - azErr, ok := err.(*RequestError) - if !ok { - t.Fatalf("azure: returned error is not azure.RequestError: %T", err) - } - - expected := "autorest/azure: Service returned an error. Status=500 Code=\"InternalError\" Message=\"Azure is having trouble right now.\"" - if !reflect.DeepEqual(expected, azErr.Error()) { - t.Fatalf("azure: service error is not unmarshaled properly.\nexpected=%v\ngot=%v", expected, azErr.Error()) - } - - if expected := http.StatusInternalServerError; azErr.StatusCode != expected { - t.Fatalf("azure: got wrong StatusCode=%d Expected=%d", azErr.StatusCode, expected) - } - if expected := uuid; azErr.RequestID != expected { - t.Fatalf("azure: wrong request ID in error. expected=%q; got=%q", expected, azErr.RequestID) - } - - _ = azErr.Error() - - // the error body should still be there - defer r.Body.Close() - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - if string(b) != j { - t.Fatalf("response body is wrong. got=%q expected=%q", string(b), j) - } - -} - -func TestWithErrorUnlessStatusCode_FoundAzureErrorWithDetails(t *testing.T) { - j := `{ - "error": { - "code": "InternalError", - "message": "Azure is having trouble right now.", - "details": [{"code": "conflict1", "message":"error message1"}, - {"code": "conflict2", "message":"error message2"}] - } - }` - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - r := mocks.NewResponseWithContent(j) - mocks.SetResponseHeader(r, HeaderRequestID, uuid) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusInternalServerError - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - - if err == nil { - t.Fatalf("azure: returned nil error for proper error response") - } - azErr, ok := err.(*RequestError) - if !ok { - t.Fatalf("azure: returned error is not azure.RequestError: %T", err) - } - - if expected := "InternalError"; azErr.ServiceError.Code != expected { - t.Fatalf("azure: wrong error code. expected=%q; got=%q", expected, azErr.ServiceError.Code) - } - if azErr.ServiceError.Message == "" { - t.Fatalf("azure: error message is not unmarshaled properly") - } - b, _ := json.Marshal(*azErr.ServiceError.Details) - if string(b) != `[{"code":"conflict1","message":"error message1"},{"code":"conflict2","message":"error message2"}]` { - t.Fatalf("azure: error details is not unmarshaled properly") - } - - if expected := http.StatusInternalServerError; azErr.StatusCode != expected { - t.Fatalf("azure: got wrong StatusCode=%v Expected=%d", azErr.StatusCode, expected) - } - if expected := uuid; azErr.RequestID != expected { - t.Fatalf("azure: wrong request ID in error. expected=%q; got=%q", expected, azErr.RequestID) - } - - _ = azErr.Error() - - // the error body should still be there - defer r.Body.Close() - b, err = ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - if string(b) != j { - t.Fatalf("response body is wrong. got=%q expected=%q", string(b), j) - } - -} - -func TestWithErrorUnlessStatusCode_NoAzureError(t *testing.T) { - j := `{ - "Status":"NotFound" - }` - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - r := mocks.NewResponseWithContent(j) - mocks.SetResponseHeader(r, HeaderRequestID, uuid) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusInternalServerError - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - if err == nil { - t.Fatalf("azure: returned nil error for proper error response") - } - azErr, ok := err.(*RequestError) - if !ok { - t.Fatalf("azure: returned error is not azure.RequestError: %T", err) - } - - expected := &ServiceError{ - Code: "Unknown", - Message: "Unknown service error", - } - - if !reflect.DeepEqual(expected, azErr.ServiceError) { - t.Fatalf("azure: service error is not unmarshaled properly. expected=%q\ngot=%q", expected, azErr.ServiceError) - } - - if expected := http.StatusInternalServerError; azErr.StatusCode != expected { - t.Fatalf("azure: got wrong StatusCode=%v Expected=%d", azErr.StatusCode, expected) - } - if expected := uuid; azErr.RequestID != expected { - t.Fatalf("azure: wrong request ID in error. expected=%q; got=%q", expected, azErr.RequestID) - } - - _ = azErr.Error() - - // the error body should still be there - defer r.Body.Close() - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - if string(b) != j { - t.Fatalf("response body is wrong. got=%q expected=%q", string(b), j) - } - -} - -func TestWithErrorUnlessStatusCode_UnwrappedError(t *testing.T) { - j := `{ - "target": null, - "code": "InternalError", - "message": "Azure is having trouble right now.", - "details": [{"code": "conflict1", "message":"error message1"}, - {"code": "conflict2", "message":"error message2"}], - "innererror": [] -}` - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - r := mocks.NewResponseWithContent(j) - mocks.SetResponseHeader(r, HeaderRequestID, uuid) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusInternalServerError - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - - if err == nil { - t.Fatal("azure: returned nil error for proper error response") - } - - azErr, ok := err.(*RequestError) - if !ok { - t.Fatalf("returned error is not azure.RequestError: %T", err) - } - - if expected := http.StatusInternalServerError; azErr.StatusCode != expected { - t.Logf("Incorrect StatusCode got: %v want: %d", azErr.StatusCode, expected) - t.Fail() - } - - if expected := "Azure is having trouble right now."; azErr.ServiceError.Message != expected { - t.Logf("Incorrect Message\n\tgot: %q\n\twant: %q", azErr.Message, expected) - t.Fail() - } - - if expected := uuid; azErr.RequestID != expected { - t.Logf("Incorrect request ID\n\tgot: %q\n\twant: %q", azErr.RequestID, expected) - t.Fail() - } - - expectedServiceErrorDetails := `[{"code":"conflict1","message":"error message1"},{"code":"conflict2","message":"error message2"}]` - if azErr.ServiceError == nil { - t.Logf("`ServiceError` was nil when it shouldn't have been.") - t.Fail() - } else if azErr.ServiceError.Details == nil { - t.Logf("`ServiceError.Details` was nil when it should have been %q", expectedServiceErrorDetails) - t.Fail() - } else if details, _ := json.Marshal(*azErr.ServiceError.Details); expectedServiceErrorDetails != string(details) { - t.Logf("Error detaisl was not unmarshaled properly.\n\tgot: %q\n\twant: %q", string(details), expectedServiceErrorDetails) - t.Fail() - } - - // the error body should still be there - defer r.Body.Close() - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Error(err) - } - if string(b) != j { - t.Fatalf("response body is wrong. got=%q expected=%q", string(b), j) - } - -} - -func TestRequestErrorString_WithError(t *testing.T) { - j := `{ - "error": { - "code": "InternalError", - "message": "Conflict", - "details": [{"code": "conflict1", "message":"error message1"}] - } - }` - uuid := "71FDB9F4-5E49-4C12-B266-DE7B4FD999A6" - r := mocks.NewResponseWithContent(j) - mocks.SetResponseHeader(r, HeaderRequestID, uuid) - r.Request = mocks.NewRequest() - r.StatusCode = http.StatusInternalServerError - r.Status = http.StatusText(r.StatusCode) - - err := autorest.Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - - if err == nil { - t.Fatalf("azure: returned nil error for proper error response") - } - azErr, _ := err.(*RequestError) - expected := "autorest/azure: Service returned an error. Status=500 Code=\"InternalError\" Message=\"Conflict\" Details=[{\"code\":\"conflict1\",\"message\":\"error message1\"}]" - if expected != azErr.Error() { - t.Fatalf("azure: send wrong RequestError.\nexpected=%v\ngot=%v", expected, azErr.Error()) - } -} - -func withErrorPrepareDecorator(e *error) autorest.PrepareDecorator { - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - *e = fmt.Errorf("azure: Faux Prepare Error") - return r, *e - }) - } -} - -func withAsyncResponseDecorator(n int) autorest.SendDecorator { - i := 0 - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil { - if i < n { - resp.StatusCode = http.StatusCreated - resp.Header = http.Header{} - resp.Header.Add(http.CanonicalHeaderKey(headerAsyncOperation), mocks.TestURL) - i++ - } else { - resp.StatusCode = http.StatusOK - resp.Header.Del(http.CanonicalHeaderKey(headerAsyncOperation)) - } - } - return resp, err - }) - } -} - -type mockAuthorizer struct{} - -func (ma mockAuthorizer) WithAuthorization() autorest.PrepareDecorator { - return autorest.WithHeader(headerAuthorization, mocks.TestAuthorizationHeader) -} - -type mockFailingAuthorizer struct{} - -func (mfa mockFailingAuthorizer) WithAuthorization() autorest.PrepareDecorator { - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - return r, fmt.Errorf("ERROR: mockFailingAuthorizer returned expected error") - }) - } -} - -type mockInspector struct { - wasInvoked bool -} - -func (mi *mockInspector) WithInspection() autorest.PrepareDecorator { - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - mi.wasInvoked = true - return p.Prepare(r) - }) - } -} - -func (mi *mockInspector) ByInspecting() autorest.RespondDecorator { - return func(r autorest.Responder) autorest.Responder { - return autorest.ResponderFunc(func(resp *http.Response) error { - mi.wasInvoked = true - return r.Respond(resp) - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go index efdab6a110..936836493b 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go @@ -83,10 +83,10 @@ var ( PublishSettingsURL: "https://manage.windowsazure.us/publishsettings/index", ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/", ResourceManagerEndpoint: "https://management.usgovcloudapi.net/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", + ActiveDirectoryEndpoint: "https://login.microsoftonline.us/", GalleryEndpoint: "https://gallery.usgovcloudapi.net/", KeyVaultEndpoint: "https://vault.usgovcloudapi.net/", - GraphEndpoint: "https://graph.usgovcloudapi.net/", + GraphEndpoint: "https://graph.windows.net/", StorageEndpointSuffix: "core.usgovcloudapi.net", SQLDatabaseDNSSuffix: "database.usgovcloudapi.net", TrafficManagerDNSSuffix: "usgovtrafficmanager.net", diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments_test.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments_test.go deleted file mode 100644 index 9cee30b7d0..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/environments_test.go +++ /dev/null @@ -1,284 +0,0 @@ -// test -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "os" - "path" - "path/filepath" - "runtime" - "testing" -) - -// This correlates to the expected contents of ./testdata/test_environment_1.json -var testEnvironment1 = Environment{ - Name: "--unit-test--", - ManagementPortalURL: "--management-portal-url", - PublishSettingsURL: "--publish-settings-url--", - ServiceManagementEndpoint: "--service-management-endpoint--", - ResourceManagerEndpoint: "--resource-management-endpoint--", - ActiveDirectoryEndpoint: "--active-directory-endpoint--", - GalleryEndpoint: "--gallery-endpoint--", - KeyVaultEndpoint: "--key-vault--endpoint--", - GraphEndpoint: "--graph-endpoint--", - StorageEndpointSuffix: "--storage-endpoint-suffix--", - SQLDatabaseDNSSuffix: "--sql-database-dns-suffix--", - TrafficManagerDNSSuffix: "--traffic-manager-dns-suffix--", - KeyVaultDNSSuffix: "--key-vault-dns-suffix--", - ServiceBusEndpointSuffix: "--service-bus-endpoint-suffix--", - ServiceManagementVMDNSSuffix: "--asm-vm-dns-suffix--", - ResourceManagerVMDNSSuffix: "--arm-vm-dns-suffix--", - ContainerRegistryDNSSuffix: "--container-registry-dns-suffix--", -} - -func TestEnvironment_EnvironmentFromFile(t *testing.T) { - got, err := EnvironmentFromFile(filepath.Join("testdata", "test_environment_1.json")) - if err != nil { - t.Error(err) - } - - if got != testEnvironment1 { - t.Logf("got: %v want: %v", got, testEnvironment1) - t.Fail() - } -} - -func TestEnvironment_EnvironmentFromName_Stack(t *testing.T) { - _, currentFile, _, _ := runtime.Caller(0) - prevEnvFilepathValue := os.Getenv(EnvironmentFilepathName) - os.Setenv(EnvironmentFilepathName, filepath.Join(path.Dir(currentFile), "testdata", "test_environment_1.json")) - defer os.Setenv(EnvironmentFilepathName, prevEnvFilepathValue) - - got, err := EnvironmentFromName("AZURESTACKCLOUD") - if err != nil { - t.Error(err) - } - - if got != testEnvironment1 { - t.Logf("got: %v want: %v", got, testEnvironment1) - t.Fail() - } -} - -func TestEnvironmentFromName(t *testing.T) { - name := "azurechinacloud" - if env, _ := EnvironmentFromName(name); env != ChinaCloud { - t.Errorf("Expected to get ChinaCloud for %q", name) - } - - name = "AzureChinaCloud" - if env, _ := EnvironmentFromName(name); env != ChinaCloud { - t.Errorf("Expected to get ChinaCloud for %q", name) - } - - name = "azuregermancloud" - if env, _ := EnvironmentFromName(name); env != GermanCloud { - t.Errorf("Expected to get GermanCloud for %q", name) - } - - name = "AzureGermanCloud" - if env, _ := EnvironmentFromName(name); env != GermanCloud { - t.Errorf("Expected to get GermanCloud for %q", name) - } - - name = "azurepubliccloud" - if env, _ := EnvironmentFromName(name); env != PublicCloud { - t.Errorf("Expected to get PublicCloud for %q", name) - } - - name = "AzurePublicCloud" - if env, _ := EnvironmentFromName(name); env != PublicCloud { - t.Errorf("Expected to get PublicCloud for %q", name) - } - - name = "azureusgovernmentcloud" - if env, _ := EnvironmentFromName(name); env != USGovernmentCloud { - t.Errorf("Expected to get USGovernmentCloud for %q", name) - } - - name = "AzureUSGovernmentCloud" - if env, _ := EnvironmentFromName(name); env != USGovernmentCloud { - t.Errorf("Expected to get USGovernmentCloud for %q", name) - } - - name = "thisisnotarealcloudenv" - if _, err := EnvironmentFromName(name); err == nil { - t.Errorf("Expected to get an error for %q", name) - } -} - -func TestDeserializeEnvironment(t *testing.T) { - env := `{ - "name": "--name--", - "ActiveDirectoryEndpoint": "--active-directory-endpoint--", - "galleryEndpoint": "--gallery-endpoint--", - "graphEndpoint": "--graph-endpoint--", - "keyVaultDNSSuffix": "--key-vault-dns-suffix--", - "keyVaultEndpoint": "--key-vault-endpoint--", - "managementPortalURL": "--management-portal-url--", - "publishSettingsURL": "--publish-settings-url--", - "resourceManagerEndpoint": "--resource-manager-endpoint--", - "serviceBusEndpointSuffix": "--service-bus-endpoint-suffix--", - "serviceManagementEndpoint": "--service-management-endpoint--", - "sqlDatabaseDNSSuffix": "--sql-database-dns-suffix--", - "storageEndpointSuffix": "--storage-endpoint-suffix--", - "trafficManagerDNSSuffix": "--traffic-manager-dns-suffix--", - "serviceManagementVMDNSSuffix": "--asm-vm-dns-suffix--", - "resourceManagerVMDNSSuffix": "--arm-vm-dns-suffix--", - "containerRegistryDNSSuffix": "--container-registry-dns-suffix--" - }` - - testSubject := Environment{} - err := json.Unmarshal([]byte(env), &testSubject) - if err != nil { - t.Fatalf("failed to unmarshal: %s", err) - } - - if "--name--" != testSubject.Name { - t.Errorf("Expected Name to be \"--name--\", but got %q", testSubject.Name) - } - if "--management-portal-url--" != testSubject.ManagementPortalURL { - t.Errorf("Expected ManagementPortalURL to be \"--management-portal-url--\", but got %q", testSubject.ManagementPortalURL) - } - if "--publish-settings-url--" != testSubject.PublishSettingsURL { - t.Errorf("Expected PublishSettingsURL to be \"--publish-settings-url--\", but got %q", testSubject.PublishSettingsURL) - } - if "--service-management-endpoint--" != testSubject.ServiceManagementEndpoint { - t.Errorf("Expected ServiceManagementEndpoint to be \"--service-management-endpoint--\", but got %q", testSubject.ServiceManagementEndpoint) - } - if "--resource-manager-endpoint--" != testSubject.ResourceManagerEndpoint { - t.Errorf("Expected ResourceManagerEndpoint to be \"--resource-manager-endpoint--\", but got %q", testSubject.ResourceManagerEndpoint) - } - if "--active-directory-endpoint--" != testSubject.ActiveDirectoryEndpoint { - t.Errorf("Expected ActiveDirectoryEndpoint to be \"--active-directory-endpoint--\", but got %q", testSubject.ActiveDirectoryEndpoint) - } - if "--gallery-endpoint--" != testSubject.GalleryEndpoint { - t.Errorf("Expected GalleryEndpoint to be \"--gallery-endpoint--\", but got %q", testSubject.GalleryEndpoint) - } - if "--key-vault-endpoint--" != testSubject.KeyVaultEndpoint { - t.Errorf("Expected KeyVaultEndpoint to be \"--key-vault-endpoint--\", but got %q", testSubject.KeyVaultEndpoint) - } - if "--graph-endpoint--" != testSubject.GraphEndpoint { - t.Errorf("Expected GraphEndpoint to be \"--graph-endpoint--\", but got %q", testSubject.GraphEndpoint) - } - if "--storage-endpoint-suffix--" != testSubject.StorageEndpointSuffix { - t.Errorf("Expected StorageEndpointSuffix to be \"--storage-endpoint-suffix--\", but got %q", testSubject.StorageEndpointSuffix) - } - if "--sql-database-dns-suffix--" != testSubject.SQLDatabaseDNSSuffix { - t.Errorf("Expected sql-database-dns-suffix to be \"--sql-database-dns-suffix--\", but got %q", testSubject.SQLDatabaseDNSSuffix) - } - if "--key-vault-dns-suffix--" != testSubject.KeyVaultDNSSuffix { - t.Errorf("Expected StorageEndpointSuffix to be \"--key-vault-dns-suffix--\", but got %q", testSubject.KeyVaultDNSSuffix) - } - if "--service-bus-endpoint-suffix--" != testSubject.ServiceBusEndpointSuffix { - t.Errorf("Expected StorageEndpointSuffix to be \"--service-bus-endpoint-suffix--\", but got %q", testSubject.ServiceBusEndpointSuffix) - } - if "--asm-vm-dns-suffix--" != testSubject.ServiceManagementVMDNSSuffix { - t.Errorf("Expected ServiceManagementVMDNSSuffix to be \"--asm-vm-dns-suffix--\", but got %q", testSubject.ServiceManagementVMDNSSuffix) - } - if "--arm-vm-dns-suffix--" != testSubject.ResourceManagerVMDNSSuffix { - t.Errorf("Expected ResourceManagerVMDNSSuffix to be \"--arm-vm-dns-suffix--\", but got %q", testSubject.ResourceManagerVMDNSSuffix) - } - if "--container-registry-dns-suffix--" != testSubject.ContainerRegistryDNSSuffix { - t.Errorf("Expected ContainerRegistryDNSSuffix to be \"--container-registry-dns-suffix--\", but got %q", testSubject.ContainerRegistryDNSSuffix) - } -} - -func TestRoundTripSerialization(t *testing.T) { - env := Environment{ - Name: "--unit-test--", - ManagementPortalURL: "--management-portal-url", - PublishSettingsURL: "--publish-settings-url--", - ServiceManagementEndpoint: "--service-management-endpoint--", - ResourceManagerEndpoint: "--resource-management-endpoint--", - ActiveDirectoryEndpoint: "--active-directory-endpoint--", - GalleryEndpoint: "--gallery-endpoint--", - KeyVaultEndpoint: "--key-vault--endpoint--", - GraphEndpoint: "--graph-endpoint--", - StorageEndpointSuffix: "--storage-endpoint-suffix--", - SQLDatabaseDNSSuffix: "--sql-database-dns-suffix--", - TrafficManagerDNSSuffix: "--traffic-manager-dns-suffix--", - KeyVaultDNSSuffix: "--key-vault-dns-suffix--", - ServiceBusEndpointSuffix: "--service-bus-endpoint-suffix--", - ServiceManagementVMDNSSuffix: "--asm-vm-dns-suffix--", - ResourceManagerVMDNSSuffix: "--arm-vm-dns-suffix--", - ContainerRegistryDNSSuffix: "--container-registry-dns-suffix--", - } - - bytes, err := json.Marshal(env) - if err != nil { - t.Fatalf("failed to marshal: %s", err) - } - - testSubject := Environment{} - err = json.Unmarshal(bytes, &testSubject) - if err != nil { - t.Fatalf("failed to unmarshal: %s", err) - } - - if env.Name != testSubject.Name { - t.Errorf("Expected Name to be %q, but got %q", env.Name, testSubject.Name) - } - if env.ManagementPortalURL != testSubject.ManagementPortalURL { - t.Errorf("Expected ManagementPortalURL to be %q, but got %q", env.ManagementPortalURL, testSubject.ManagementPortalURL) - } - if env.PublishSettingsURL != testSubject.PublishSettingsURL { - t.Errorf("Expected PublishSettingsURL to be %q, but got %q", env.PublishSettingsURL, testSubject.PublishSettingsURL) - } - if env.ServiceManagementEndpoint != testSubject.ServiceManagementEndpoint { - t.Errorf("Expected ServiceManagementEndpoint to be %q, but got %q", env.ServiceManagementEndpoint, testSubject.ServiceManagementEndpoint) - } - if env.ResourceManagerEndpoint != testSubject.ResourceManagerEndpoint { - t.Errorf("Expected ResourceManagerEndpoint to be %q, but got %q", env.ResourceManagerEndpoint, testSubject.ResourceManagerEndpoint) - } - if env.ActiveDirectoryEndpoint != testSubject.ActiveDirectoryEndpoint { - t.Errorf("Expected ActiveDirectoryEndpoint to be %q, but got %q", env.ActiveDirectoryEndpoint, testSubject.ActiveDirectoryEndpoint) - } - if env.GalleryEndpoint != testSubject.GalleryEndpoint { - t.Errorf("Expected GalleryEndpoint to be %q, but got %q", env.GalleryEndpoint, testSubject.GalleryEndpoint) - } - if env.KeyVaultEndpoint != testSubject.KeyVaultEndpoint { - t.Errorf("Expected KeyVaultEndpoint to be %q, but got %q", env.KeyVaultEndpoint, testSubject.KeyVaultEndpoint) - } - if env.GraphEndpoint != testSubject.GraphEndpoint { - t.Errorf("Expected GraphEndpoint to be %q, but got %q", env.GraphEndpoint, testSubject.GraphEndpoint) - } - if env.StorageEndpointSuffix != testSubject.StorageEndpointSuffix { - t.Errorf("Expected StorageEndpointSuffix to be %q, but got %q", env.StorageEndpointSuffix, testSubject.StorageEndpointSuffix) - } - if env.SQLDatabaseDNSSuffix != testSubject.SQLDatabaseDNSSuffix { - t.Errorf("Expected SQLDatabaseDNSSuffix to be %q, but got %q", env.SQLDatabaseDNSSuffix, testSubject.SQLDatabaseDNSSuffix) - } - if env.TrafficManagerDNSSuffix != testSubject.TrafficManagerDNSSuffix { - t.Errorf("Expected TrafficManagerDNSSuffix to be %q, but got %q", env.TrafficManagerDNSSuffix, testSubject.TrafficManagerDNSSuffix) - } - if env.KeyVaultDNSSuffix != testSubject.KeyVaultDNSSuffix { - t.Errorf("Expected KeyVaultDNSSuffix to be %q, but got %q", env.KeyVaultDNSSuffix, testSubject.KeyVaultDNSSuffix) - } - if env.ServiceBusEndpointSuffix != testSubject.ServiceBusEndpointSuffix { - t.Errorf("Expected ServiceBusEndpointSuffix to be %q, but got %q", env.ServiceBusEndpointSuffix, testSubject.ServiceBusEndpointSuffix) - } - if env.ServiceManagementVMDNSSuffix != testSubject.ServiceManagementVMDNSSuffix { - t.Errorf("Expected ServiceManagementVMDNSSuffix to be %q, but got %q", env.ServiceManagementVMDNSSuffix, testSubject.ServiceManagementVMDNSSuffix) - } - if env.ResourceManagerVMDNSSuffix != testSubject.ResourceManagerVMDNSSuffix { - t.Errorf("Expected ResourceManagerVMDNSSuffix to be %q, but got %q", env.ResourceManagerVMDNSSuffix, testSubject.ResourceManagerVMDNSSuffix) - } - if env.ContainerRegistryDNSSuffix != testSubject.ContainerRegistryDNSSuffix { - t.Errorf("Expected ContainerRegistryDNSSuffix to be %q, but got %q", env.ContainerRegistryDNSSuffix, testSubject.ContainerRegistryDNSSuffix) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go b/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go index 66d1c8c2b3..b6b95d6fdb 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go +++ b/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go @@ -44,7 +44,7 @@ func DoRetryWithRegistration(client autorest.Client) autorest.SendDecorator { return resp, err } - if resp.StatusCode != http.StatusConflict { + if resp.StatusCode != http.StatusConflict || client.SkipResourceProviderRegistration { return resp, err } var re RequestError @@ -159,7 +159,7 @@ func register(client autorest.Client, originalReq *http.Request, re RequestError } req.Cancel = originalReq.Cancel - resp, err := autorest.SendWithSender(client.Sender, req, + resp, err := autorest.SendWithSender(client, req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), ) if err != nil { diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/rp_test.go b/vendor/github.com/Azure/go-autorest/autorest/azure/rp_test.go deleted file mode 100644 index b069430578..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/rp_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package azure - -import ( - "net/http" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/mocks" -) - -func TestDoRetryWithRegistration(t *testing.T) { - client := mocks.NewSender() - // first response, should retry because it is a transient error - client.AppendResponse(mocks.NewResponseWithStatus("Internal server error", http.StatusInternalServerError)) - // response indicates the resource provider has not been registered - client.AppendResponse(mocks.NewResponseWithBodyAndStatus(mocks.NewBody(`{ - "error":{ - "code":"MissingSubscriptionRegistration", - "message":"The subscription registration is in 'Unregistered' state. The subscription must be registered to use namespace 'Microsoft.EventGrid'. See https://aka.ms/rps-not-found for how to register subscriptions.", - "details":[ - { - "code":"MissingSubscriptionRegistration", - "target":"Microsoft.EventGrid", - "message":"The subscription registration is in 'Unregistered' state. The subscription must be registered to use namespace 'Microsoft.EventGrid'. See https://aka.ms/rps-not-found for how to register subscriptions." - } - ] - } -} -`), http.StatusConflict, "MissingSubscriptionRegistration")) - // first poll response, still not ready - client.AppendResponse(mocks.NewResponseWithBodyAndStatus(mocks.NewBody(`{ - "registrationState": "Registering" -} -`), http.StatusOK, "200 OK")) - // last poll response, respurce provider has been registered - client.AppendResponse(mocks.NewResponseWithBodyAndStatus(mocks.NewBody(`{ - "registrationState": "Registered" -} -`), http.StatusOK, "200 OK")) - // retry original request, response is successful - client.AppendResponse(mocks.NewResponseWithStatus("200 OK", http.StatusOK)) - - req := mocks.NewRequestForURL("https://lol/subscriptions/rofl") - req.Body = mocks.NewBody("lolol") - r, err := autorest.SendWithSender(client, req, - DoRetryWithRegistration(autorest.Client{ - PollingDelay: time.Second, - PollingDuration: time.Second * 10, - RetryAttempts: 5, - RetryDuration: time.Second, - Sender: client, - }), - ) - if err != nil { - t.Fatalf("got error: %v", err) - } - - autorest.Respond(r, - autorest.ByDiscardingBody(), - autorest.ByClosing(), - ) - - if r.StatusCode != http.StatusOK { - t.Fatalf("azure: Sender#DoRetryWithRegistration -- Got: StatusCode %v; Want: StatusCode 200 OK", r.StatusCode) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/client.go b/vendor/github.com/Azure/go-autorest/autorest/client.go index 9eebd83bf8..d329cb7377 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/client.go +++ b/vendor/github.com/Azure/go-autorest/autorest/client.go @@ -166,6 +166,9 @@ type Client struct { UserAgent string Jar http.CookieJar + + // Set to true to skip attempted registration of resource providers (false by default). + SkipResourceProviderRegistration bool } // NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed @@ -204,7 +207,13 @@ func (c Client) Do(r *http.Request) (*http.Response, error) { c.WithInspection(), c.WithAuthorization()) if err != nil { - return nil, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed") + var resp *http.Response + if detErr, ok := err.(DetailedError); ok { + // if the authorization failed (e.g. invalid credentials) there will + // be a response associated with the error, be sure to return it. + resp = detErr.Response + } + return resp, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed") } resp, err := SendWithSender(c.sender(), r) diff --git a/vendor/github.com/Azure/go-autorest/autorest/client_test.go b/vendor/github.com/Azure/go-autorest/autorest/client_test.go deleted file mode 100644 index 151f8eedb2..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/client_test.go +++ /dev/null @@ -1,402 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "fmt" - "io/ioutil" - "log" - "math/rand" - "net/http" - "net/http/httptest" - "reflect" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -func TestLoggingInspectorWithInspection(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.RequestInspector = li.WithInspection() - - Prepare(mocks.NewRequestWithContent("Content"), - c.WithInspection()) - - if len(b.String()) <= 0 { - t.Fatal("autorest: LoggingInspector#WithInspection did not record Request to the log") - } -} - -func TestLoggingInspectorWithInspectionEmitsErrors(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - r := mocks.NewRequestWithContent("Content") - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.RequestInspector = li.WithInspection() - - if _, err := Prepare(r, - c.WithInspection()); err != nil { - t.Error(err) - } - - if len(b.String()) <= 0 { - t.Fatal("autorest: LoggingInspector#WithInspection did not record Request to the log") - } -} - -func TestLoggingInspectorWithInspectionRestoresBody(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - r := mocks.NewRequestWithContent("Content") - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.RequestInspector = li.WithInspection() - - Prepare(r, - c.WithInspection()) - - s, _ := ioutil.ReadAll(r.Body) - if len(s) <= 0 { - t.Fatal("autorest: LoggingInspector#WithInspection did not restore the Request body") - } -} - -func TestLoggingInspectorByInspecting(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.ResponseInspector = li.ByInspecting() - - Respond(mocks.NewResponseWithContent("Content"), - c.ByInspecting()) - - if len(b.String()) <= 0 { - t.Fatal("autorest: LoggingInspector#ByInspection did not record Response to the log") - } -} - -func TestLoggingInspectorByInspectingEmitsErrors(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - r := mocks.NewResponseWithContent("Content") - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.ResponseInspector = li.ByInspecting() - - if err := Respond(r, - c.ByInspecting()); err != nil { - t.Fatal(err) - } - - if len(b.String()) <= 0 { - t.Fatal("autorest: LoggingInspector#ByInspection did not record Response to the log") - } -} - -func TestLoggingInspectorByInspectingRestoresBody(t *testing.T) { - b := bytes.Buffer{} - c := Client{} - r := mocks.NewResponseWithContent("Content") - li := LoggingInspector{Logger: log.New(&b, "", 0)} - c.ResponseInspector = li.ByInspecting() - - Respond(r, - c.ByInspecting()) - - s, _ := ioutil.ReadAll(r.Body) - if len(s) <= 0 { - t.Fatal("autorest: LoggingInspector#ByInspecting did not restore the Response body") - } -} - -func TestNewClientWithUserAgent(t *testing.T) { - ua := "UserAgent" - c := NewClientWithUserAgent(ua) - completeUA := fmt.Sprintf("%s %s", defaultUserAgent, ua) - - if c.UserAgent != completeUA { - t.Fatalf("autorest: NewClientWithUserAgent failed to set the UserAgent -- expected %s, received %s", - completeUA, c.UserAgent) - } -} - -func TestAddToUserAgent(t *testing.T) { - ua := "UserAgent" - c := NewClientWithUserAgent(ua) - ext := "extension" - err := c.AddToUserAgent(ext) - if err != nil { - t.Fatalf("autorest: AddToUserAgent returned error -- expected nil, received %s", err) - } - completeUA := fmt.Sprintf("%s %s %s", defaultUserAgent, ua, ext) - - if c.UserAgent != completeUA { - t.Fatalf("autorest: AddToUserAgent failed to add an extension to the UserAgent -- expected %s, received %s", - completeUA, c.UserAgent) - } - - err = c.AddToUserAgent("") - if err == nil { - t.Fatalf("autorest: AddToUserAgent didn't return error -- expected %s, received nil", - fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent)) - } - if c.UserAgent != completeUA { - t.Fatalf("autorest: AddToUserAgent failed to not add an empty extension to the UserAgent -- expected %s, received %s", - completeUA, c.UserAgent) - } -} - -func TestClientSenderReturnsHttpClientByDefault(t *testing.T) { - c := Client{} - - if fmt.Sprintf("%T", c.sender()) != "*http.Client" { - t.Fatal("autorest: Client#sender failed to return http.Client by default") - } -} - -func TestClientSenderReturnsSetSender(t *testing.T) { - c := Client{} - - s := mocks.NewSender() - c.Sender = s - - if c.sender() != s { - t.Fatal("autorest: Client#sender failed to return set Sender") - } -} - -func TestClientDoInvokesSender(t *testing.T) { - c := Client{} - - s := mocks.NewSender() - c.Sender = s - - c.Do(&http.Request{}) - if s.Attempts() != 1 { - t.Fatal("autorest: Client#Do failed to invoke the Sender") - } -} - -func TestClientDoSetsUserAgent(t *testing.T) { - ua := "UserAgent" - c := Client{UserAgent: ua} - r := mocks.NewRequest() - s := mocks.NewSender() - c.Sender = s - - c.Do(r) - - if r.UserAgent() != ua { - t.Fatalf("autorest: Client#Do failed to correctly set User-Agent header: %s=%s", - http.CanonicalHeaderKey(headerUserAgent), r.UserAgent()) - } -} - -func TestClientDoSetsAuthorization(t *testing.T) { - r := mocks.NewRequest() - s := mocks.NewSender() - c := Client{Authorizer: mockAuthorizer{}, Sender: s} - - c.Do(r) - if len(r.Header.Get(http.CanonicalHeaderKey(headerAuthorization))) <= 0 { - t.Fatalf("autorest: Client#Send failed to set Authorization header -- %s=%s", - http.CanonicalHeaderKey(headerAuthorization), - r.Header.Get(http.CanonicalHeaderKey(headerAuthorization))) - } -} - -func TestClientDoInvokesRequestInspector(t *testing.T) { - r := mocks.NewRequest() - s := mocks.NewSender() - i := &mockInspector{} - c := Client{RequestInspector: i.WithInspection(), Sender: s} - - c.Do(r) - if !i.wasInvoked { - t.Fatal("autorest: Client#Send failed to invoke the RequestInspector") - } -} - -func TestClientDoInvokesResponseInspector(t *testing.T) { - r := mocks.NewRequest() - s := mocks.NewSender() - i := &mockInspector{} - c := Client{ResponseInspector: i.ByInspecting(), Sender: s} - - c.Do(r) - if !i.wasInvoked { - t.Fatal("autorest: Client#Send failed to invoke the ResponseInspector") - } -} - -func TestClientDoReturnsErrorIfPrepareFails(t *testing.T) { - c := Client{} - s := mocks.NewSender() - c.Authorizer = mockFailingAuthorizer{} - c.Sender = s - - _, err := c.Do(&http.Request{}) - if err == nil { - t.Fatalf("autorest: Client#Do failed to return an error when Prepare failed") - } -} - -func TestClientDoDoesNotSendIfPrepareFails(t *testing.T) { - c := Client{} - s := mocks.NewSender() - c.Authorizer = mockFailingAuthorizer{} - c.Sender = s - - c.Do(&http.Request{}) - if s.Attempts() > 0 { - t.Fatal("autorest: Client#Do failed to invoke the Sender") - } -} - -func TestClientAuthorizerReturnsNullAuthorizerByDefault(t *testing.T) { - c := Client{} - - if fmt.Sprintf("%T", c.authorizer()) != "autorest.NullAuthorizer" { - t.Fatal("autorest: Client#authorizer failed to return the NullAuthorizer by default") - } -} - -func TestClientAuthorizerReturnsSetAuthorizer(t *testing.T) { - c := Client{} - c.Authorizer = mockAuthorizer{} - - if fmt.Sprintf("%T", c.authorizer()) != "autorest.mockAuthorizer" { - t.Fatal("autorest: Client#authorizer failed to return the set Authorizer") - } -} - -func TestClientWithAuthorizer(t *testing.T) { - c := Client{} - c.Authorizer = mockAuthorizer{} - - req, _ := Prepare(&http.Request{}, - c.WithAuthorization()) - - if req.Header.Get(headerAuthorization) == "" { - t.Fatal("autorest: Client#WithAuthorizer failed to return the WithAuthorizer from the active Authorizer") - } -} - -func TestClientWithInspection(t *testing.T) { - c := Client{} - r := &mockInspector{} - c.RequestInspector = r.WithInspection() - - Prepare(&http.Request{}, - c.WithInspection()) - - if !r.wasInvoked { - t.Fatal("autorest: Client#WithInspection failed to invoke RequestInspector") - } -} - -func TestClientWithInspectionSetsDefault(t *testing.T) { - c := Client{} - - r1 := &http.Request{} - r2, _ := Prepare(r1, - c.WithInspection()) - - if !reflect.DeepEqual(r1, r2) { - t.Fatal("autorest: Client#WithInspection failed to provide a default RequestInspector") - } -} - -func TestClientByInspecting(t *testing.T) { - c := Client{} - r := &mockInspector{} - c.ResponseInspector = r.ByInspecting() - - Respond(&http.Response{}, - c.ByInspecting()) - - if !r.wasInvoked { - t.Fatal("autorest: Client#ByInspecting failed to invoke ResponseInspector") - } -} - -func TestClientByInspectingSetsDefault(t *testing.T) { - c := Client{} - - r := &http.Response{} - Respond(r, - c.ByInspecting()) - - if !reflect.DeepEqual(r, &http.Response{}) { - t.Fatal("autorest: Client#ByInspecting failed to provide a default ResponseInspector") - } -} - -func TestCookies(t *testing.T) { - second := "second" - expected := http.Cookie{ - Name: "tastes", - Value: "delicious", - } - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.SetCookie(w, &expected) - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: ioutil.ReadAll failed reading request body: %s", err) - } - if string(b) == second { - cookie, err := r.Cookie(expected.Name) - if err != nil { - t.Fatalf("autorest: r.Cookie could not get request cookie: %s", err) - } - if cookie == nil { - t.Fatalf("autorest: got nil cookie, expecting %v", expected) - } - if cookie.Value != expected.Value { - t.Fatalf("autorest: got cookie value '%s', expecting '%s'", cookie.Value, expected.Name) - } - } - })) - defer server.Close() - - client := NewClientWithUserAgent("") - _, err := SendWithSender(client, mocks.NewRequestForURL(server.URL)) - if err != nil { - t.Fatalf("autorest: first request failed: %s", err) - } - - r2, err := http.NewRequest(http.MethodGet, server.URL, mocks.NewBody(second)) - if err != nil { - t.Fatalf("autorest: failed creating second request: %s", err) - } - - _, err = SendWithSender(client, r2) - if err != nil { - t.Fatalf("autorest: second request failed: %s", err) - } -} - -func randomString(n int) string { - const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" - r := rand.New(rand.NewSource(time.Now().UTC().UnixNano())) - s := make([]byte, n) - for i := range s { - s[i] = chars[r.Intn(len(chars))] - } - return string(s) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/date_test.go b/vendor/github.com/Azure/go-autorest/autorest/date/date_test.go deleted file mode 100644 index 4a40bbc3e1..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/date_test.go +++ /dev/null @@ -1,237 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "reflect" - "testing" - "time" -) - -func ExampleParseDate() { - d, err := ParseDate("2001-02-03") - if err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2001-02-03 -} - -func ExampleDate() { - d, err := ParseDate("2001-02-03") - if err != nil { - fmt.Println(err) - } - - t, err := time.Parse(time.RFC3339, "2001-02-04T00:00:00Z") - if err != nil { - fmt.Println(err) - } - - // Date acts as time.Time when the receiver - if d.Before(t) { - fmt.Printf("Before ") - } else { - fmt.Printf("After ") - } - - // Convert Date when needing a time.Time - if t.After(d.ToTime()) { - fmt.Printf("After") - } else { - fmt.Printf("Before") - } - // Output: Before After -} - -func ExampleDate_MarshalBinary() { - d, err := ParseDate("2001-02-03") - if err != nil { - fmt.Println(err) - } - t, err := d.MarshalBinary() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(t)) - // Output: 2001-02-03 -} - -func ExampleDate_UnmarshalBinary() { - d := Date{} - t := "2001-02-03" - - if err := d.UnmarshalBinary([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2001-02-03 -} - -func ExampleDate_MarshalJSON() { - d, err := ParseDate("2001-02-03") - if err != nil { - fmt.Println(err) - } - j, err := json.Marshal(d) - if err != nil { - fmt.Println(err) - } - fmt.Println(string(j)) - // Output: "2001-02-03" -} - -func ExampleDate_UnmarshalJSON() { - var d struct { - Date Date `json:"date"` - } - j := `{"date" : "2001-02-03"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - fmt.Println(err) - } - fmt.Println(d.Date) - // Output: 2001-02-03 -} - -func ExampleDate_MarshalText() { - d, err := ParseDate("2001-02-03") - if err != nil { - fmt.Println(err) - } - t, err := d.MarshalText() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(t)) - // Output: 2001-02-03 -} - -func ExampleDate_UnmarshalText() { - d := Date{} - t := "2001-02-03" - - if err := d.UnmarshalText([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2001-02-03 -} - -func TestDateString(t *testing.T) { - d, err := ParseDate("2001-02-03") - if err != nil { - t.Fatalf("date: String failed (%v)", err) - } - if d.String() != "2001-02-03" { - t.Fatalf("date: String failed (%v)", d.String()) - } -} - -func TestDateBinaryRoundTrip(t *testing.T) { - d1, err := ParseDate("2001-02-03") - if err != nil { - t.Fatalf("date: ParseDate failed (%v)", err) - } - t1, err := d1.MarshalBinary() - if err != nil { - t.Fatalf("date: MarshalBinary failed (%v)", err) - } - - d2 := Date{} - if err = d2.UnmarshalBinary(t1); err != nil { - t.Fatalf("date: UnmarshalBinary failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip Binary failed (%v, %v)", d1, d2) - } -} - -func TestDateJSONRoundTrip(t *testing.T) { - type s struct { - Date Date `json:"date"` - } - var err error - d1 := s{} - d1.Date, err = ParseDate("2001-02-03") - if err != nil { - t.Fatalf("date: ParseDate failed (%v)", err) - } - - j, err := json.Marshal(d1) - if err != nil { - t.Fatalf("date: MarshalJSON failed (%v)", err) - } - - d2 := s{} - if err = json.Unmarshal(j, &d2); err != nil { - t.Fatalf("date: UnmarshalJSON failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip JSON failed (%v, %v)", d1, d2) - } -} - -func TestDateTextRoundTrip(t *testing.T) { - d1, err := ParseDate("2001-02-03") - if err != nil { - t.Fatalf("date: ParseDate failed (%v)", err) - } - t1, err := d1.MarshalText() - if err != nil { - t.Fatalf("date: MarshalText failed (%v)", err) - } - d2 := Date{} - if err = d2.UnmarshalText(t1); err != nil { - t.Fatalf("date: UnmarshalText failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip Text failed (%v, %v)", d1, d2) - } -} - -func TestDateToTime(t *testing.T) { - var d Date - d, err := ParseDate("2001-02-03") - if err != nil { - t.Fatalf("date: ParseDate failed (%v)", err) - } - var _ time.Time = d.ToTime() -} - -func TestDateUnmarshalJSONReturnsError(t *testing.T) { - var d struct { - Date Date `json:"date"` - } - j := `{"date" : "February 3, 2001"}` - - if err := json.Unmarshal([]byte(j), &d); err == nil { - t.Fatal("date: Date failed to return error for malformed JSON date") - } -} - -func TestDateUnmarshalTextReturnsError(t *testing.T) { - d := Date{} - txt := "February 3, 2001" - - if err := d.UnmarshalText([]byte(txt)); err == nil { - t.Fatal("date: Date failed to return error for malformed Text date") - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/time_test.go b/vendor/github.com/Azure/go-autorest/autorest/date/time_test.go deleted file mode 100644 index d8c811707a..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/time_test.go +++ /dev/null @@ -1,277 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "reflect" - "testing" - "time" -) - -func ExampleParseTime() { - d, _ := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - fmt.Println(d) - // Output: 2001-02-03 04:05:06 +0000 UTC -} - -func ExampleTime_MarshalBinary() { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - fmt.Println(err) - } - d := Time{ti} - t, err := d.MarshalBinary() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(t)) - // Output: 2001-02-03T04:05:06Z -} - -func ExampleTime_UnmarshalBinary() { - d := Time{} - t := "2001-02-03T04:05:06Z" - - if err := d.UnmarshalBinary([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2001-02-03T04:05:06Z -} - -func ExampleTime_MarshalJSON() { - d, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - fmt.Println(err) - } - j, err := json.Marshal(d) - if err != nil { - fmt.Println(err) - } - fmt.Println(string(j)) - // Output: "2001-02-03T04:05:06Z" -} - -func ExampleTime_UnmarshalJSON() { - var d struct { - Time Time `json:"datetime"` - } - j := `{"datetime" : "2001-02-03T04:05:06Z"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - fmt.Println(err) - } - fmt.Println(d.Time) - // Output: 2001-02-03T04:05:06Z -} - -func ExampleTime_MarshalText() { - d, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - fmt.Println(err) - } - t, err := d.MarshalText() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(t)) - // Output: 2001-02-03T04:05:06Z -} - -func ExampleTime_UnmarshalText() { - d := Time{} - t := "2001-02-03T04:05:06Z" - - if err := d.UnmarshalText([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2001-02-03T04:05:06Z -} - -func TestUnmarshalTextforInvalidDate(t *testing.T) { - d := Time{} - dt := "2001-02-03T04:05:06AAA" - - if err := d.UnmarshalText([]byte(dt)); err == nil { - t.Fatalf("date: Time#Unmarshal was expecting error for invalid date") - } -} - -func TestUnmarshalJSONforInvalidDate(t *testing.T) { - d := Time{} - dt := `"2001-02-03T04:05:06AAA"` - - if err := d.UnmarshalJSON([]byte(dt)); err == nil { - t.Fatalf("date: Time#Unmarshal was expecting error for invalid date") - } -} - -func TestTimeString(t *testing.T) { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - fmt.Println(err) - } - d := Time{ti} - if d.String() != "2001-02-03T04:05:06Z" { - t.Fatalf("date: Time#String failed (%v)", d.String()) - } -} - -func TestTimeStringReturnsEmptyStringForError(t *testing.T) { - d := Time{Time: time.Date(20000, 01, 01, 01, 01, 01, 01, time.UTC)} - if d.String() != "" { - t.Fatalf("date: Time#String failed empty string for an error") - } -} - -func TestTimeBinaryRoundTrip(t *testing.T) { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - t.Fatalf("date: Time#ParseTime failed (%v)", err) - } - d1 := Time{ti} - t1, err := d1.MarshalBinary() - if err != nil { - t.Fatalf("date: Time#MarshalBinary failed (%v)", err) - } - - d2 := Time{} - if err = d2.UnmarshalBinary(t1); err != nil { - t.Fatalf("date: Time#UnmarshalBinary failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date:Round-trip Binary failed (%v, %v)", d1, d2) - } -} - -func TestTimeJSONRoundTrip(t *testing.T) { - type s struct { - Time Time `json:"datetime"` - } - - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - t.Fatalf("date: Time#ParseTime failed (%v)", err) - } - - d1 := s{Time: Time{ti}} - j, err := json.Marshal(d1) - if err != nil { - t.Fatalf("date: Time#MarshalJSON failed (%v)", err) - } - - d2 := s{} - if err = json.Unmarshal(j, &d2); err != nil { - t.Fatalf("date: Time#UnmarshalJSON failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip JSON failed (%v, %v)", d1, d2) - } -} - -func TestTimeTextRoundTrip(t *testing.T) { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - t.Fatalf("date: Time#ParseTime failed (%v)", err) - } - d1 := Time{Time: ti} - t1, err := d1.MarshalText() - if err != nil { - t.Fatalf("date: Time#MarshalText failed (%v)", err) - } - - d2 := Time{} - if err = d2.UnmarshalText(t1); err != nil { - t.Fatalf("date: Time#UnmarshalText failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip Text failed (%v, %v)", d1, d2) - } -} - -func TestTimeToTime(t *testing.T) { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - d := Time{ti} - if err != nil { - t.Fatalf("date: Time#ParseTime failed (%v)", err) - } - var _ time.Time = d.ToTime() -} - -func TestUnmarshalJSONNoOffset(t *testing.T) { - var d struct { - Time Time `json:"datetime"` - } - j := `{"datetime" : "2001-02-03T04:05:06.789"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - t.Fatalf("date: Time#Unmarshal failed (%v)", err) - } -} - -func TestUnmarshalJSONPosOffset(t *testing.T) { - var d struct { - Time Time `json:"datetime"` - } - j := `{"datetime" : "1980-01-02T00:11:35.01+01:00"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - t.Fatalf("date: Time#Unmarshal failed (%v)", err) - } -} - -func TestUnmarshalJSONNegOffset(t *testing.T) { - var d struct { - Time Time `json:"datetime"` - } - j := `{"datetime" : "1492-10-12T10:15:01.789-08:00"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - t.Fatalf("date: Time#Unmarshal failed (%v)", err) - } -} - -func TestUnmarshalTextNoOffset(t *testing.T) { - d := Time{} - t1 := "2001-02-03T04:05:06" - - if err := d.UnmarshalText([]byte(t1)); err != nil { - t.Fatalf("date: Time#UnmarshalText failed (%v)", err) - } -} - -func TestUnmarshalTextPosOffset(t *testing.T) { - d := Time{} - t1 := "2001-02-03T04:05:06+00:30" - - if err := d.UnmarshalText([]byte(t1)); err != nil { - t.Fatalf("date: Time#UnmarshalText failed (%v)", err) - } -} - -func TestUnmarshalTextNegOffset(t *testing.T) { - d := Time{} - t1 := "2001-02-03T04:05:06-11:00" - - if err := d.UnmarshalText([]byte(t1)); err != nil { - t.Fatalf("date: Time#UnmarshalText failed (%v)", err) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123_test.go b/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123_test.go deleted file mode 100644 index dfd640513d..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123_test.go +++ /dev/null @@ -1,226 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "reflect" - "testing" - "time" -) - -func ExampleTimeRFC1123() { - d, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: 2006-01-02 15:04:05 +0000 MST -} - -func ExampleTimeRFC1123_MarshalBinary() { - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - fmt.Println(err) - } - d := TimeRFC1123{ti} - b, err := d.MarshalBinary() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(b)) - // Output: Mon, 02 Jan 2006 15:04:05 MST -} - -func ExampleTimeRFC1123_UnmarshalBinary() { - d := TimeRFC1123{} - t := "Mon, 02 Jan 2006 15:04:05 MST" - if err := d.UnmarshalBinary([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: Mon, 02 Jan 2006 15:04:05 MST -} - -func ExampleTimeRFC1123_MarshalJSON() { - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - fmt.Println(err) - } - d := TimeRFC1123{ti} - j, err := json.Marshal(d) - if err != nil { - fmt.Println(err) - } - fmt.Println(string(j)) - // Output: "Mon, 02 Jan 2006 15:04:05 MST" -} - -func TestTimeRFC1123MarshalJSONInvalid(t *testing.T) { - ti := time.Date(20000, 01, 01, 00, 00, 00, 00, time.UTC) - d := TimeRFC1123{ti} - if _, err := json.Marshal(d); err == nil { - t.Fatalf("date: TimeRFC1123#Marshal failed for invalid date") - } -} - -func ExampleTimeRFC1123_UnmarshalJSON() { - var d struct { - Time TimeRFC1123 `json:"datetime"` - } - j := `{"datetime" : "Mon, 02 Jan 2006 15:04:05 MST"}` - - if err := json.Unmarshal([]byte(j), &d); err != nil { - fmt.Println(err) - } - fmt.Println(d.Time) - // Output: Mon, 02 Jan 2006 15:04:05 MST -} - -func ExampleTimeRFC1123_MarshalText() { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - fmt.Println(err) - } - d := TimeRFC1123{ti} - t, err := d.MarshalText() - if err != nil { - fmt.Println(err) - } - fmt.Println(string(t)) - // Output: Sat, 03 Feb 2001 04:05:06 UTC -} - -func ExampleTimeRFC1123_UnmarshalText() { - d := TimeRFC1123{} - t := "Sat, 03 Feb 2001 04:05:06 UTC" - - if err := d.UnmarshalText([]byte(t)); err != nil { - fmt.Println(err) - } - fmt.Println(d) - // Output: Sat, 03 Feb 2001 04:05:06 UTC -} - -func TestUnmarshalJSONforInvalidDateRfc1123(t *testing.T) { - dt := `"Mon, 02 Jan 2000000 15:05 MST"` - d := TimeRFC1123{} - if err := d.UnmarshalJSON([]byte(dt)); err == nil { - t.Fatalf("date: TimeRFC1123#Unmarshal failed for invalid date") - } -} - -func TestUnmarshalTextforInvalidDateRfc1123(t *testing.T) { - dt := "Mon, 02 Jan 2000000 15:05 MST" - d := TimeRFC1123{} - if err := d.UnmarshalText([]byte(dt)); err == nil { - t.Fatalf("date: TimeRFC1123#Unmarshal failed for invalid date") - } -} - -func TestTimeStringRfc1123(t *testing.T) { - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - fmt.Println(err) - } - d := TimeRFC1123{ti} - if d.String() != "Mon, 02 Jan 2006 15:04:05 MST" { - t.Fatalf("date: TimeRFC1123#String failed (%v)", d.String()) - } -} - -func TestTimeStringReturnsEmptyStringForErrorRfc1123(t *testing.T) { - d := TimeRFC1123{Time: time.Date(20000, 01, 01, 01, 01, 01, 01, time.UTC)} - if d.String() != "" { - t.Fatalf("date: TimeRFC1123#String failed empty string for an error") - } -} - -func TestTimeBinaryRoundTripRfc1123(t *testing.T) { - ti, err := ParseTime(rfc3339, "2001-02-03T04:05:06Z") - if err != nil { - t.Fatalf("date: TimeRFC1123#ParseTime failed (%v)", err) - } - d1 := TimeRFC1123{ti} - t1, err := d1.MarshalBinary() - if err != nil { - t.Fatalf("date: TimeRFC1123#MarshalBinary failed (%v)", err) - } - - d2 := TimeRFC1123{} - if err = d2.UnmarshalBinary(t1); err != nil { - t.Fatalf("date: TimeRFC1123#UnmarshalBinary failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip Binary failed (%v, %v)", d1, d2) - } -} - -func TestTimeJSONRoundTripRfc1123(t *testing.T) { - type s struct { - Time TimeRFC1123 `json:"datetime"` - } - var err error - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - t.Fatalf("date: TimeRFC1123#ParseTime failed (%v)", err) - } - d1 := s{Time: TimeRFC1123{ti}} - j, err := json.Marshal(d1) - if err != nil { - t.Fatalf("date: TimeRFC1123#MarshalJSON failed (%v)", err) - } - - d2 := s{} - if err = json.Unmarshal(j, &d2); err != nil { - t.Fatalf("date: TimeRFC1123#UnmarshalJSON failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip JSON failed (%v, %v)", d1, d2) - } -} - -func TestTimeTextRoundTripRfc1123(t *testing.T) { - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - if err != nil { - t.Fatalf("date: TimeRFC1123#ParseTime failed (%v)", err) - } - d1 := TimeRFC1123{Time: ti} - t1, err := d1.MarshalText() - if err != nil { - t.Fatalf("date: TimeRFC1123#MarshalText failed (%v)", err) - } - - d2 := TimeRFC1123{} - if err = d2.UnmarshalText(t1); err != nil { - t.Fatalf("date: TimeRFC1123#UnmarshalText failed (%v)", err) - } - - if !reflect.DeepEqual(d1, d2) { - t.Fatalf("date: Round-trip Text failed (%v, %v)", d1, d2) - } -} - -func TestTimeToTimeRFC1123(t *testing.T) { - ti, err := ParseTime(rfc1123, "Mon, 02 Jan 2006 15:04:05 MST") - d := TimeRFC1123{ti} - if err != nil { - t.Fatalf("date: TimeRFC1123#ParseTime failed (%v)", err) - } - var _ time.Time = d.ToTime() -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/unixtime_test.go b/vendor/github.com/Azure/go-autorest/autorest/date/unixtime_test.go deleted file mode 100644 index 3fa347c00c..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/unixtime_test.go +++ /dev/null @@ -1,283 +0,0 @@ -// +build go1.7 - -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "fmt" - "math" - "testing" - "time" -) - -func ExampleUnixTime_MarshalJSON() { - epoch := UnixTime(UnixEpoch()) - text, _ := json.Marshal(epoch) - fmt.Print(string(text)) - // Output: 0 -} - -func ExampleUnixTime_UnmarshalJSON() { - var myTime UnixTime - json.Unmarshal([]byte("1.3e2"), &myTime) - fmt.Printf("%v", time.Time(myTime)) - // Output: 1970-01-01 00:02:10 +0000 UTC -} - -func TestUnixTime_MarshalJSON(t *testing.T) { - testCases := []time.Time{ - UnixEpoch().Add(-1 * time.Second), // One second befote the Unix Epoch - time.Date(2017, time.April, 14, 20, 27, 47, 0, time.UTC), // The time this test was written - UnixEpoch(), - time.Date(1800, 01, 01, 0, 0, 0, 0, time.UTC), - time.Date(2200, 12, 29, 00, 01, 37, 82, time.UTC), - } - - for _, tc := range testCases { - t.Run(tc.String(), func(subT *testing.T) { - var actual, expected float64 - var marshaled []byte - - target := UnixTime(tc) - expected = float64(target.Duration().Nanoseconds()) / 1e9 - - if temp, err := json.Marshal(target); err == nil { - marshaled = temp - } else { - subT.Error(err) - return - } - - dec := json.NewDecoder(bytes.NewReader(marshaled)) - if err := dec.Decode(&actual); err != nil { - subT.Error(err) - return - } - - diff := math.Abs(actual - expected) - subT.Logf("\ngot :\t%g\nwant:\t%g\ndiff:\t%g", actual, expected, diff) - if diff > 1e-9 { //Must be within 1 nanosecond of one another - subT.Fail() - } - }) - } -} - -func TestUnixTime_UnmarshalJSON(t *testing.T) { - testCases := []struct { - text string - expected time.Time - }{ - {"1", UnixEpoch().Add(time.Second)}, - {"0", UnixEpoch()}, - {"1492203742", time.Date(2017, time.April, 14, 21, 02, 22, 0, time.UTC)}, // The time this test was written - {"-1", time.Date(1969, time.December, 31, 23, 59, 59, 0, time.UTC)}, - {"1.5", UnixEpoch().Add(1500 * time.Millisecond)}, - {"0e1", UnixEpoch()}, // See http://json.org for 'number' format definition. - {"1.3e+2", UnixEpoch().Add(130 * time.Second)}, - {"1.6E-10", UnixEpoch()}, // This is so small, it should get truncated into the UnixEpoch - {"2E-6", UnixEpoch().Add(2 * time.Microsecond)}, - {"1.289345e9", UnixEpoch().Add(1289345000 * time.Second)}, - {"1e-9", UnixEpoch().Add(time.Nanosecond)}, - } - - for _, tc := range testCases { - t.Run(tc.text, func(subT *testing.T) { - var rehydrated UnixTime - if err := json.Unmarshal([]byte(tc.text), &rehydrated); err != nil { - subT.Error(err) - return - } - - if time.Time(rehydrated) != tc.expected { - subT.Logf("\ngot: \t%v\nwant:\t%v\ndiff:\t%v", time.Time(rehydrated), tc.expected, time.Time(rehydrated).Sub(tc.expected)) - subT.Fail() - } - }) - } -} - -func TestUnixTime_JSONRoundTrip(t *testing.T) { - testCases := []time.Time{ - UnixEpoch(), - time.Date(2005, time.November, 5, 0, 0, 0, 0, time.UTC), // The day V for Vendetta (film) was released. - UnixEpoch().Add(-6 * time.Second), - UnixEpoch().Add(800 * time.Hour), - UnixEpoch().Add(time.Nanosecond), - time.Date(2015, time.September, 05, 4, 30, 12, 9992, time.UTC), - } - - for _, tc := range testCases { - t.Run(tc.String(), func(subT *testing.T) { - subject := UnixTime(tc) - var marshaled []byte - if temp, err := json.Marshal(subject); err == nil { - marshaled = temp - } else { - subT.Error(err) - return - } - - var unmarshaled UnixTime - if err := json.Unmarshal(marshaled, &unmarshaled); err != nil { - subT.Error(err) - } - - actual := time.Time(unmarshaled) - diff := actual.Sub(tc) - subT.Logf("\ngot :\t%s\nwant:\t%s\ndiff:\t%s", actual.String(), tc.String(), diff.String()) - - if diff > time.Duration(100) { // We lose some precision be working in floats. We shouldn't lose more than 100 nanoseconds. - subT.Fail() - } - }) - } -} - -func TestUnixTime_MarshalBinary(t *testing.T) { - testCases := []struct { - expected int64 - subject time.Time - }{ - {0, UnixEpoch()}, - {-15 * int64(time.Second), UnixEpoch().Add(-15 * time.Second)}, - {54, UnixEpoch().Add(54 * time.Nanosecond)}, - } - - for _, tc := range testCases { - t.Run("", func(subT *testing.T) { - var marshaled []byte - - if temp, err := UnixTime(tc.subject).MarshalBinary(); err == nil { - marshaled = temp - } else { - subT.Error(err) - return - } - - var unmarshaled int64 - if err := binary.Read(bytes.NewReader(marshaled), binary.LittleEndian, &unmarshaled); err != nil { - subT.Error(err) - return - } - - if unmarshaled != tc.expected { - subT.Logf("\ngot: \t%d\nwant:\t%d", unmarshaled, tc.expected) - subT.Fail() - } - }) - } -} - -func TestUnixTime_BinaryRoundTrip(t *testing.T) { - testCases := []time.Time{ - UnixEpoch(), - UnixEpoch().Add(800 * time.Minute), - UnixEpoch().Add(7 * time.Hour), - UnixEpoch().Add(-1 * time.Nanosecond), - } - - for _, tc := range testCases { - t.Run(tc.String(), func(subT *testing.T) { - original := UnixTime(tc) - var marshaled []byte - - if temp, err := original.MarshalBinary(); err == nil { - marshaled = temp - } else { - subT.Error(err) - return - } - - var traveled UnixTime - if err := traveled.UnmarshalBinary(marshaled); err != nil { - subT.Error(err) - return - } - - if traveled != original { - subT.Logf("\ngot: \t%s\nwant:\t%s", time.Time(original).String(), time.Time(traveled).String()) - subT.Fail() - } - }) - } -} - -func TestUnixTime_MarshalText(t *testing.T) { - testCases := []time.Time{ - UnixEpoch(), - UnixEpoch().Add(45 * time.Second), - UnixEpoch().Add(time.Nanosecond), - UnixEpoch().Add(-100000 * time.Second), - } - - for _, tc := range testCases { - expected, _ := tc.MarshalText() - t.Run("", func(subT *testing.T) { - var marshaled []byte - - if temp, err := UnixTime(tc).MarshalText(); err == nil { - marshaled = temp - } else { - subT.Error(err) - return - } - - if string(marshaled) != string(expected) { - subT.Logf("\ngot: \t%s\nwant:\t%s", string(marshaled), string(expected)) - subT.Fail() - } - }) - } -} - -func TestUnixTime_TextRoundTrip(t *testing.T) { - testCases := []time.Time{ - UnixEpoch(), - UnixEpoch().Add(-1 * time.Nanosecond), - UnixEpoch().Add(1 * time.Nanosecond), - time.Date(2017, time.April, 17, 21, 00, 00, 00, time.UTC), - } - - for _, tc := range testCases { - t.Run(tc.String(), func(subT *testing.T) { - unixTC := UnixTime(tc) - - var marshaled []byte - - if temp, err := unixTC.MarshalText(); err == nil { - marshaled = temp - } else { - subT.Error(err) - return - } - - var unmarshaled UnixTime - if err := unmarshaled.UnmarshalText(marshaled); err != nil { - subT.Error(err) - return - } - - if unmarshaled != unixTC { - t.Logf("\ngot: \t%s\nwant:\t%s", time.Time(unmarshaled).String(), tc.String()) - t.Fail() - } - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/error_test.go b/vendor/github.com/Azure/go-autorest/autorest/error_test.go deleted file mode 100644 index f4f5d75ef5..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/error_test.go +++ /dev/null @@ -1,202 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "net/http" - "reflect" - "regexp" - "testing" -) - -func TestNewErrorWithError_AssignsPackageType(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if e.PackageType != "packageType" { - t.Fatalf("autorest: Error failed to set package type -- expected %v, received %v", "packageType", e.PackageType) - } -} - -func TestNewErrorWithError_AssignsMethod(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if e.Method != "method" { - t.Fatalf("autorest: Error failed to set method -- expected %v, received %v", "method", e.Method) - } -} - -func TestNewErrorWithError_AssignsMessage(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if e.Message != "message" { - t.Fatalf("autorest: Error failed to set message -- expected %v, received %v", "message", e.Message) - } -} - -func TestNewErrorWithError_AssignsUndefinedStatusCodeIfRespNil(t *testing.T) { - e := NewErrorWithError(nil, "packageType", "method", nil, "message") - if e.StatusCode != UndefinedStatusCode { - t.Fatalf("autorest: Error failed to set status code -- expected %v, received %v", UndefinedStatusCode, e.StatusCode) - } -} - -func TestNewErrorWithError_AssignsStatusCode(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", &http.Response{ - StatusCode: http.StatusBadRequest, - Status: http.StatusText(http.StatusBadRequest)}, "message") - - if e.StatusCode != http.StatusBadRequest { - t.Fatalf("autorest: Error failed to set status code -- expected %v, received %v", http.StatusBadRequest, e.StatusCode) - } -} - -func TestNewErrorWithError_AcceptsArgs(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message %s", "arg") - - if matched, _ := regexp.MatchString(`.*arg.*`, e.Message); !matched { - t.Fatalf("autorest: Error failed to apply message arguments -- expected %v, received %v", - `.*arg.*`, e.Message) - } -} - -func TestNewErrorWithError_AssignsError(t *testing.T) { - err := fmt.Errorf("original") - e := NewErrorWithError(err, "packageType", "method", nil, "message") - - if e.Original != err { - t.Fatalf("autorest: Error failed to set error -- expected %v, received %v", err, e.Original) - } -} - -func TestNewErrorWithResponse_ContainsStatusCode(t *testing.T) { - e := NewErrorWithResponse("packageType", "method", &http.Response{ - StatusCode: http.StatusBadRequest, - Status: http.StatusText(http.StatusBadRequest)}, "message") - - if e.StatusCode != http.StatusBadRequest { - t.Fatalf("autorest: Error failed to set status code -- expected %v, received %v", http.StatusBadRequest, e.StatusCode) - } -} - -func TestNewErrorWithResponse_nilResponse_ReportsUndefinedStatusCode(t *testing.T) { - e := NewErrorWithResponse("packageType", "method", nil, "message") - - if e.StatusCode != UndefinedStatusCode { - t.Fatalf("autorest: Error failed to set status code -- expected %v, received %v", UndefinedStatusCode, e.StatusCode) - } -} - -func TestNewErrorWithResponse_Forwards(t *testing.T) { - e1 := NewError("packageType", "method", "message %s", "arg") - e2 := NewErrorWithResponse("packageType", "method", nil, "message %s", "arg") - - if !reflect.DeepEqual(e1, e2) { - t.Fatal("autorest: NewError did not return an error equivelent to NewErrorWithError") - } -} - -func TestNewErrorWithError_Forwards(t *testing.T) { - e1 := NewError("packageType", "method", "message %s", "arg") - e2 := NewErrorWithError(nil, "packageType", "method", nil, "message %s", "arg") - - if !reflect.DeepEqual(e1, e2) { - t.Fatal("autorest: NewError did not return an error equivelent to NewErrorWithError") - } -} - -func TestNewErrorWithError_DoesNotWrapADetailedError(t *testing.T) { - e1 := NewError("packageType1", "method1", "message1 %s", "arg1") - e2 := NewErrorWithError(e1, "packageType2", "method2", nil, "message2 %s", "arg2") - - if !reflect.DeepEqual(e1, e2) { - t.Fatalf("autorest: NewErrorWithError incorrectly wrapped a DetailedError -- expected %v, received %v", e1, e2) - } -} - -func TestNewErrorWithError_WrapsAnError(t *testing.T) { - e1 := fmt.Errorf("Inner Error") - var e2 interface{} = NewErrorWithError(e1, "packageType", "method", nil, "message") - - if _, ok := e2.(DetailedError); !ok { - t.Fatalf("autorest: NewErrorWithError failed to wrap a standard error -- received %T", e2) - } -} - -func TestDetailedError(t *testing.T) { - err := fmt.Errorf("original") - e := NewErrorWithError(err, "packageType", "method", nil, "message") - - if matched, _ := regexp.MatchString(`.*original.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#Error failed to return original error message -- expected %v, received %v", - `.*original.*`, e.Error()) - } -} - -func TestDetailedErrorConstainsPackageType(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if matched, _ := regexp.MatchString(`.*packageType.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#String failed to include PackageType -- expected %v, received %v", - `.*packageType.*`, e.Error()) - } -} - -func TestDetailedErrorConstainsMethod(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if matched, _ := regexp.MatchString(`.*method.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#String failed to include Method -- expected %v, received %v", - `.*method.*`, e.Error()) - } -} - -func TestDetailedErrorConstainsMessage(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if matched, _ := regexp.MatchString(`.*message.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#String failed to include Message -- expected %v, received %v", - `.*message.*`, e.Error()) - } -} - -func TestDetailedErrorConstainsStatusCode(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", &http.Response{ - StatusCode: http.StatusBadRequest, - Status: http.StatusText(http.StatusBadRequest)}, "message") - - if matched, _ := regexp.MatchString(`.*400.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#String failed to include Status Code -- expected %v, received %v", - `.*400.*`, e.Error()) - } -} - -func TestDetailedErrorConstainsOriginal(t *testing.T) { - e := NewErrorWithError(fmt.Errorf("original"), "packageType", "method", nil, "message") - - if matched, _ := regexp.MatchString(`.*original.*`, e.Error()); !matched { - t.Fatalf("autorest: Error#String failed to include Original error -- expected %v, received %v", - `.*original.*`, e.Error()) - } -} - -func TestDetailedErrorSkipsOriginal(t *testing.T) { - e := NewError("packageType", "method", "message") - - if matched, _ := regexp.MatchString(`.*Original.*`, e.Error()); matched { - t.Fatalf("autorest: Error#String included missing Original error -- unexpected %v, received %v", - `.*Original.*`, e.Error()) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/preparer.go b/vendor/github.com/Azure/go-autorest/autorest/preparer.go index 2290c40100..6d67bd7337 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/preparer.go +++ b/vendor/github.com/Azure/go-autorest/autorest/preparer.go @@ -27,8 +27,9 @@ import ( ) const ( - mimeTypeJSON = "application/json" - mimeTypeFormPost = "application/x-www-form-urlencoded" + mimeTypeJSON = "application/json" + mimeTypeOctetStream = "application/octet-stream" + mimeTypeFormPost = "application/x-www-form-urlencoded" headerAuthorization = "Authorization" headerContentType = "Content-Type" @@ -112,6 +113,28 @@ func WithHeader(header string, value string) PrepareDecorator { } } +// WithHeaders returns a PrepareDecorator that sets the specified HTTP headers of the http.Request to +// the passed value. It canonicalizes the passed headers name (via http.CanonicalHeaderKey) before +// adding them. +func WithHeaders(headers map[string]interface{}) PrepareDecorator { + h := ensureValueStrings(headers) + return func(p Preparer) Preparer { + return PreparerFunc(func(r *http.Request) (*http.Request, error) { + r, err := p.Prepare(r) + if err == nil { + if r.Header == nil { + r.Header = make(http.Header) + } + + for name, value := range h { + r.Header.Set(http.CanonicalHeaderKey(name), value) + } + } + return r, err + }) + } +} + // WithBearerAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose // value is "Bearer " followed by the supplied token. func WithBearerAuthorization(token string) PrepareDecorator { @@ -142,6 +165,11 @@ func AsJSON() PrepareDecorator { return AsContentType(mimeTypeJSON) } +// AsOctetStream returns a PrepareDecorator that adds the "application/octet-stream" Content-Type header. +func AsOctetStream() PrepareDecorator { + return AsContentType(mimeTypeOctetStream) +} + // WithMethod returns a PrepareDecorator that sets the HTTP method of the passed request. The // decorator does not validate that the passed method string is a known HTTP method. func WithMethod(method string) PrepareDecorator { @@ -215,6 +243,11 @@ func WithFormData(v url.Values) PrepareDecorator { r, err := p.Prepare(r) if err == nil { s := v.Encode() + + if r.Header == nil { + r.Header = make(http.Header) + } + r.Header.Set(http.CanonicalHeaderKey(headerContentType), mimeTypeFormPost) r.ContentLength = int64(len(s)) r.Body = ioutil.NopCloser(strings.NewReader(s)) } @@ -430,11 +463,16 @@ func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorato if r.URL == nil { return r, NewError("autorest", "WithQueryParameters", "Invoked with a nil URL") } + v := r.URL.Query() for key, value := range parameters { - v.Add(key, value) + d, err := url.QueryUnescape(value) + if err != nil { + return r, err + } + v.Add(key, d) } - r.URL.RawQuery = createQuery(v) + r.URL.RawQuery = v.Encode() } return r, err }) diff --git a/vendor/github.com/Azure/go-autorest/autorest/preparer_test.go b/vendor/github.com/Azure/go-autorest/autorest/preparer_test.go deleted file mode 100644 index 9ba608a8fa..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/preparer_test.go +++ /dev/null @@ -1,766 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "strconv" - "strings" - "testing" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -// PrepareDecorators wrap and invoke a Preparer. Most often, the decorator invokes the passed -// Preparer and decorates the response. -func ExamplePrepareDecorator() { - path := "a/b/c/" - pd := func() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, fmt.Errorf("ERROR: URL is not set") - } - r.URL.Path += path - } - return r, err - }) - } - } - - r, _ := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - pd()) - - fmt.Printf("Path is %s\n", r.URL) - // Output: Path is https://microsoft.com/a/b/c/ -} - -// PrepareDecorators may also modify and then invoke the Preparer. -func ExamplePrepareDecorator_pre() { - pd := func() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r.Header.Add(http.CanonicalHeaderKey("ContentType"), "application/json") - return p.Prepare(r) - }) - } - } - - r, _ := Prepare(&http.Request{Header: http.Header{}}, - pd()) - - fmt.Printf("ContentType is %s\n", r.Header.Get("ContentType")) - // Output: ContentType is application/json -} - -// Create a sequence of three Preparers that build up the URL path. -func ExampleCreatePreparer() { - p := CreatePreparer( - WithBaseURL("https://microsoft.com/"), - WithPath("a"), - WithPath("b"), - WithPath("c")) - r, err := p.Prepare(&http.Request{}) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c -} - -// Create and apply separate Preparers -func ExampleCreatePreparer_multiple() { - params := map[string]interface{}{ - "param1": "a", - "param2": "c", - } - - p1 := CreatePreparer(WithBaseURL("https://microsoft.com/")) - p2 := CreatePreparer(WithPathParameters("/{param1}/b/{param2}/", params)) - - r, err := p1.Prepare(&http.Request{}) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } - - r, err = p2.Prepare(r) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c/ -} - -// Create and chain separate Preparers -func ExampleCreatePreparer_chain() { - params := map[string]interface{}{ - "param1": "a", - "param2": "c", - } - - p := CreatePreparer(WithBaseURL("https://microsoft.com/")) - p = DecoratePreparer(p, WithPathParameters("/{param1}/b/{param2}/", params)) - - r, err := p.Prepare(&http.Request{}) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c/ -} - -// Create and prepare an http.Request in one call -func ExamplePrepare() { - r, err := Prepare(&http.Request{}, - AsGet(), - WithBaseURL("https://microsoft.com/"), - WithPath("a/b/c/")) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Printf("%s %s", r.Method, r.URL) - } - // Output: GET https://microsoft.com/a/b/c/ -} - -// Create a request for a supplied base URL and path -func ExampleWithBaseURL() { - r, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/a/b/c/")) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c/ -} - -func ExampleWithBaseURL_second() { - _, err := Prepare(&http.Request{}, WithBaseURL(":")) - fmt.Println(err) - // Output: parse :: missing protocol scheme -} - -func ExampleWithCustomBaseURL() { - r, err := Prepare(&http.Request{}, - WithCustomBaseURL("https://{account}.{service}.core.windows.net/", - map[string]interface{}{ - "account": "myaccount", - "service": "blob", - })) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://myaccount.blob.core.windows.net/ -} - -func ExampleWithCustomBaseURL_second() { - _, err := Prepare(&http.Request{}, - WithCustomBaseURL(":", map[string]interface{}{})) - fmt.Println(err) - // Output: parse :: missing protocol scheme -} - -// Create a request with a custom HTTP header -func ExampleWithHeader() { - r, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/a/b/c/"), - WithHeader("x-foo", "bar")) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Printf("Header %s=%s\n", "x-foo", r.Header.Get("x-foo")) - } - // Output: Header x-foo=bar -} - -// Create a request whose Body is the JSON encoding of a structure -func ExampleWithFormData() { - v := url.Values{} - v.Add("name", "Rob Pike") - v.Add("age", "42") - - r, err := Prepare(&http.Request{}, - WithFormData(v)) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Printf("Request Body contains %s\n", string(b)) - } - // Output: Request Body contains age=42&name=Rob+Pike -} - -// Create a request whose Body is the JSON encoding of a structure -func ExampleWithJSON() { - t := mocks.T{Name: "Rob Pike", Age: 42} - - r, err := Prepare(&http.Request{}, - WithJSON(&t)) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Printf("Request Body contains %s\n", string(b)) - } - // Output: Request Body contains {"name":"Rob Pike","age":42} -} - -// Create a request from a path with escaped parameters -func ExampleWithEscapedPathParameters() { - params := map[string]interface{}{ - "param1": "a b c", - "param2": "d e f", - } - r, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithEscapedPathParameters("/{param1}/b/{param2}/", params)) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a+b+c/b/d+e+f/ -} - -// Create a request from a path with parameters -func ExampleWithPathParameters() { - params := map[string]interface{}{ - "param1": "a", - "param2": "c", - } - r, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPathParameters("/{param1}/b/{param2}/", params)) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c/ -} - -// Create a request with query parameters -func ExampleWithQueryParameters() { - params := map[string]interface{}{ - "q1": "value1", - "q2": "value2", - } - r, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPath("/a/b/c/"), - WithQueryParameters(params)) - if err != nil { - fmt.Printf("ERROR: %v\n", err) - } else { - fmt.Println(r.URL) - } - // Output: https://microsoft.com/a/b/c/?q1=value1&q2=value2 -} - -func TestWithCustomBaseURL(t *testing.T) { - r, err := Prepare(&http.Request{}, WithCustomBaseURL("https://{account}.{service}.core.windows.net/", - map[string]interface{}{ - "account": "myaccount", - "service": "blob", - })) - if err != nil { - t.Fatalf("autorest: WithCustomBaseURL should not fail") - } - if r.URL.String() != "https://myaccount.blob.core.windows.net/" { - t.Fatalf("autorest: WithCustomBaseURL expected https://myaccount.blob.core.windows.net/, got %s", r.URL) - } -} - -func TestWithCustomBaseURLwithInvalidURL(t *testing.T) { - _, err := Prepare(&http.Request{}, WithCustomBaseURL("hello/{account}.{service}.core.windows.net/", - map[string]interface{}{ - "account": "myaccount", - "service": "blob", - })) - if err == nil { - t.Fatalf("autorest: WithCustomBaseURL should fail fo URL parse error") - } -} - -func TestWithPathWithInvalidPath(t *testing.T) { - p := "path%2*end" - if _, err := Prepare(&http.Request{}, WithBaseURL("https://microsoft.com/"), WithPath(p)); err == nil { - t.Fatalf("autorest: WithPath should fail for invalid URL escape error for path '%v' ", p) - } - -} - -func TestWithPathParametersWithInvalidPath(t *testing.T) { - p := "path%2*end" - m := map[string]interface{}{ - "path1": p, - } - if _, err := Prepare(&http.Request{}, WithBaseURL("https://microsoft.com/"), WithPathParameters("/{path1}/", m)); err == nil { - t.Fatalf("autorest: WithPath should fail for invalid URL escape for path '%v' ", p) - } - -} - -func TestCreatePreparerDoesNotModify(t *testing.T) { - r1 := &http.Request{} - p := CreatePreparer() - r2, err := p.Prepare(r1) - if err != nil { - t.Fatalf("autorest: CreatePreparer failed (%v)", err) - } - if !reflect.DeepEqual(r1, r2) { - t.Fatalf("autorest: CreatePreparer without decorators modified the request") - } -} - -func TestCreatePreparerRunsDecoratorsInOrder(t *testing.T) { - p := CreatePreparer(WithBaseURL("https://microsoft.com/"), WithPath("1"), WithPath("2"), WithPath("3")) - r, err := p.Prepare(&http.Request{}) - if err != nil { - t.Fatalf("autorest: CreatePreparer failed (%v)", err) - } - if r.URL.String() != "https:/1/2/3" && r.URL.Host != "microsoft.com" { - t.Fatalf("autorest: CreatePreparer failed to run decorators in order") - } -} - -func TestAsContentType(t *testing.T) { - r, err := Prepare(mocks.NewRequest(), AsContentType("application/text")) - if err != nil { - fmt.Printf("ERROR: %v", err) - } - if r.Header.Get(headerContentType) != "application/text" { - t.Fatalf("autorest: AsContentType failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType)) - } -} - -func TestAsFormURLEncoded(t *testing.T) { - r, err := Prepare(mocks.NewRequest(), AsFormURLEncoded()) - if err != nil { - fmt.Printf("ERROR: %v", err) - } - if r.Header.Get(headerContentType) != mimeTypeFormPost { - t.Fatalf("autorest: AsFormURLEncoded failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType)) - } -} - -func TestAsJSON(t *testing.T) { - r, err := Prepare(mocks.NewRequest(), AsJSON()) - if err != nil { - fmt.Printf("ERROR: %v", err) - } - if r.Header.Get(headerContentType) != mimeTypeJSON { - t.Fatalf("autorest: AsJSON failed to add header (%s=%s)", headerContentType, r.Header.Get(headerContentType)) - } -} - -func TestWithNothing(t *testing.T) { - r1 := mocks.NewRequest() - r2, err := Prepare(r1, WithNothing()) - if err != nil { - t.Fatalf("autorest: WithNothing returned an unexpected error (%v)", err) - } - - if !reflect.DeepEqual(r1, r2) { - t.Fatal("azure: WithNothing modified the passed HTTP Request") - } -} - -func TestWithBearerAuthorization(t *testing.T) { - r, err := Prepare(mocks.NewRequest(), WithBearerAuthorization("SOME-TOKEN")) - if err != nil { - fmt.Printf("ERROR: %v", err) - } - if r.Header.Get(headerAuthorization) != "Bearer SOME-TOKEN" { - t.Fatalf("autorest: WithBearerAuthorization failed to add header (%s=%s)", headerAuthorization, r.Header.Get(headerAuthorization)) - } -} - -func TestWithUserAgent(t *testing.T) { - ua := "User Agent Go" - r, err := Prepare(mocks.NewRequest(), WithUserAgent(ua)) - if err != nil { - fmt.Printf("ERROR: %v", err) - } - if r.UserAgent() != ua || r.Header.Get(headerUserAgent) != ua { - t.Fatalf("autorest: WithUserAgent failed to add header (%s=%s)", headerUserAgent, r.Header.Get(headerUserAgent)) - } -} - -func TestWithMethod(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), WithMethod("HEAD")) - if r.Method != "HEAD" { - t.Fatal("autorest: WithMethod failed to set HTTP method header") - } -} - -func TestAsDelete(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsDelete()) - if r.Method != "DELETE" { - t.Fatal("autorest: AsDelete failed to set HTTP method header to DELETE") - } -} - -func TestAsGet(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsGet()) - if r.Method != "GET" { - t.Fatal("autorest: AsGet failed to set HTTP method header to GET") - } -} - -func TestAsHead(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsHead()) - if r.Method != "HEAD" { - t.Fatal("autorest: AsHead failed to set HTTP method header to HEAD") - } -} - -func TestAsOptions(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsOptions()) - if r.Method != "OPTIONS" { - t.Fatal("autorest: AsOptions failed to set HTTP method header to OPTIONS") - } -} - -func TestAsPatch(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsPatch()) - if r.Method != "PATCH" { - t.Fatal("autorest: AsPatch failed to set HTTP method header to PATCH") - } -} - -func TestAsPost(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsPost()) - if r.Method != "POST" { - t.Fatal("autorest: AsPost failed to set HTTP method header to POST") - } -} - -func TestAsPut(t *testing.T) { - r, _ := Prepare(mocks.NewRequest(), AsPut()) - if r.Method != "PUT" { - t.Fatal("autorest: AsPut failed to set HTTP method header to PUT") - } -} - -func TestPrepareWithNullRequest(t *testing.T) { - _, err := Prepare(nil) - if err == nil { - t.Fatal("autorest: Prepare failed to return an error when given a null http.Request") - } -} - -func TestWithFormDataSetsContentLength(t *testing.T) { - v := url.Values{} - v.Add("name", "Rob Pike") - v.Add("age", "42") - - r, err := Prepare(&http.Request{}, - WithFormData(v)) - if err != nil { - t.Fatalf("autorest: WithFormData failed with error (%v)", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithFormData failed with error (%v)", err) - } - - expected := "name=Rob+Pike&age=42" - if !(string(b) == "name=Rob+Pike&age=42" || string(b) == "age=42&name=Rob+Pike") { - t.Fatalf("autorest:WithFormData failed to return correct string got (%v), expected (%v)", string(b), expected) - } - - if r.ContentLength != int64(len(b)) { - t.Fatalf("autorest:WithFormData set Content-Length to %v, expected %v", r.ContentLength, len(b)) - } -} - -func TestWithMultiPartFormDataSetsContentLength(t *testing.T) { - v := map[string]interface{}{ - "file": ioutil.NopCloser(strings.NewReader("Hello Gopher")), - "age": "42", - } - - r, err := Prepare(&http.Request{}, - WithMultiPartFormData(v)) - if err != nil { - t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err) - } - - if r.ContentLength != int64(len(b)) { - t.Fatalf("autorest:WithMultiPartFormData set Content-Length to %v, expected %v", r.ContentLength, len(b)) - } -} - -func TestWithMultiPartFormDataWithNoFile(t *testing.T) { - v := map[string]interface{}{ - "file": "no file", - "age": "42", - } - - r, err := Prepare(&http.Request{}, - WithMultiPartFormData(v)) - if err != nil { - t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithMultiPartFormData failed with error (%v)", err) - } - - if r.ContentLength != int64(len(b)) { - t.Fatalf("autorest:WithMultiPartFormData set Content-Length to %v, expected %v", r.ContentLength, len(b)) - } -} - -func TestWithFile(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithFile(ioutil.NopCloser(strings.NewReader("Hello Gopher")))) - if err != nil { - t.Fatalf("autorest: WithFile failed with error (%v)", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithFile failed with error (%v)", err) - } - if r.ContentLength != int64(len(b)) { - t.Fatalf("autorest:WithFile set Content-Length to %v, expected %v", r.ContentLength, len(b)) - } -} - -func TestWithBool_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithBool(false)) - if err != nil { - t.Fatalf("autorest: WithBool failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithBool failed with error (%v)", err) - } - - if r.ContentLength != int64(len(fmt.Sprintf("%v", false))) { - t.Fatalf("autorest: WithBool set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", false)))) - } - - v, err := strconv.ParseBool(string(s)) - if err != nil || v { - t.Fatalf("autorest: WithBool incorrectly encoded the boolean as %v", s) - } -} - -func TestWithFloat32_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithFloat32(42.0)) - if err != nil { - t.Fatalf("autorest: WithFloat32 failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithFloat32 failed with error (%v)", err) - } - - if r.ContentLength != int64(len(fmt.Sprintf("%v", 42.0))) { - t.Fatalf("autorest: WithFloat32 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42.0)))) - } - - v, err := strconv.ParseFloat(string(s), 32) - if err != nil || float32(v) != float32(42.0) { - t.Fatalf("autorest: WithFloat32 incorrectly encoded the boolean as %v", s) - } -} - -func TestWithFloat64_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithFloat64(42.0)) - if err != nil { - t.Fatalf("autorest: WithFloat64 failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithFloat64 failed with error (%v)", err) - } - - if r.ContentLength != int64(len(fmt.Sprintf("%v", 42.0))) { - t.Fatalf("autorest: WithFloat64 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42.0)))) - } - - v, err := strconv.ParseFloat(string(s), 64) - if err != nil || v != float64(42.0) { - t.Fatalf("autorest: WithFloat64 incorrectly encoded the boolean as %v", s) - } -} - -func TestWithInt32_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithInt32(42)) - if err != nil { - t.Fatalf("autorest: WithInt32 failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithInt32 failed with error (%v)", err) - } - - if r.ContentLength != int64(len(fmt.Sprintf("%v", 42))) { - t.Fatalf("autorest: WithInt32 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42)))) - } - - v, err := strconv.ParseInt(string(s), 10, 32) - if err != nil || int32(v) != int32(42) { - t.Fatalf("autorest: WithInt32 incorrectly encoded the boolean as %v", s) - } -} - -func TestWithInt64_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithInt64(42)) - if err != nil { - t.Fatalf("autorest: WithInt64 failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithInt64 failed with error (%v)", err) - } - - if r.ContentLength != int64(len(fmt.Sprintf("%v", 42))) { - t.Fatalf("autorest: WithInt64 set Content-Length to %v, expected %v", r.ContentLength, int64(len(fmt.Sprintf("%v", 42)))) - } - - v, err := strconv.ParseInt(string(s), 10, 64) - if err != nil || v != int64(42) { - t.Fatalf("autorest: WithInt64 incorrectly encoded the boolean as %v", s) - } -} - -func TestWithString_SetsTheBody(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithString("value")) - if err != nil { - t.Fatalf("autorest: WithString failed with error (%v)", err) - } - - s, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithString failed with error (%v)", err) - } - - if r.ContentLength != int64(len("value")) { - t.Fatalf("autorest: WithString set Content-Length to %v, expected %v", r.ContentLength, int64(len("value"))) - } - - if string(s) != "value" { - t.Fatalf("autorest: WithString incorrectly encoded the string as %v", s) - } -} - -func TestWithJSONSetsContentLength(t *testing.T) { - r, err := Prepare(&http.Request{}, - WithJSON(&mocks.T{Name: "Rob Pike", Age: 42})) - if err != nil { - t.Fatalf("autorest: WithJSON failed with error (%v)", err) - } - - b, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: WithJSON failed with error (%v)", err) - } - - if r.ContentLength != int64(len(b)) { - t.Fatalf("autorest:WithJSON set Content-Length to %v, expected %v", r.ContentLength, len(b)) - } -} - -func TestWithHeaderAllocatesHeaders(t *testing.T) { - r, err := Prepare(mocks.NewRequest(), WithHeader("x-foo", "bar")) - if err != nil { - t.Fatalf("autorest: WithHeader failed (%v)", err) - } - if r.Header.Get("x-foo") != "bar" { - t.Fatalf("autorest: WithHeader failed to add header (%s=%s)", "x-foo", r.Header.Get("x-foo")) - } -} - -func TestWithPathCatchesNilURL(t *testing.T) { - _, err := Prepare(&http.Request{}, WithPath("a")) - if err == nil { - t.Fatalf("autorest: WithPath failed to catch a nil URL") - } -} - -func TestWithEscapedPathParametersCatchesNilURL(t *testing.T) { - _, err := Prepare(&http.Request{}, WithEscapedPathParameters("", map[string]interface{}{"foo": "bar"})) - if err == nil { - t.Fatalf("autorest: WithEscapedPathParameters failed to catch a nil URL") - } -} - -func TestWithPathParametersCatchesNilURL(t *testing.T) { - _, err := Prepare(&http.Request{}, WithPathParameters("", map[string]interface{}{"foo": "bar"})) - if err == nil { - t.Fatalf("autorest: WithPathParameters failed to catch a nil URL") - } -} - -func TestWithQueryParametersCatchesNilURL(t *testing.T) { - _, err := Prepare(&http.Request{}, WithQueryParameters(map[string]interface{}{"foo": "bar"})) - if err == nil { - t.Fatalf("autorest: WithQueryParameters failed to catch a nil URL") - } -} - -func TestModifyingExistingRequest(t *testing.T) { - r, err := Prepare(mocks.NewRequestForURL("https://bing.com"), WithPath("search"), WithQueryParameters(map[string]interface{}{"q": "golang"})) - if err != nil { - t.Fatalf("autorest: Preparing an existing request returned an error (%v)", err) - } - if r.URL.String() != "https:/search?q=golang" && r.URL.Host != "bing.com" { - t.Fatalf("autorest: Preparing an existing request failed (%s)", r.URL) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/responder_test.go b/vendor/github.com/Azure/go-autorest/autorest/responder_test.go deleted file mode 100644 index 4a57b1e3b1..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/responder_test.go +++ /dev/null @@ -1,665 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "reflect" - "strings" - "testing" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -func ExampleWithErrorUnlessOK() { - r := mocks.NewResponse() - r.Request = mocks.NewRequest() - - // Respond and leave the response body open (for a subsequent responder to close) - err := Respond(r, - WithErrorUnlessOK(), - ByDiscardingBody(), - ByClosingIfError()) - - if err == nil { - fmt.Printf("%s of %s returned HTTP 200", r.Request.Method, r.Request.URL) - - // Complete handling the response and close the body - Respond(r, - ByDiscardingBody(), - ByClosing()) - } - // Output: GET of https://microsoft.com/a/b/c/ returned HTTP 200 -} - -func ExampleByUnmarshallingJSON() { - c := ` - { - "name" : "Rob Pike", - "age" : 42 - } - ` - - type V struct { - Name string `json:"name"` - Age int `json:"age"` - } - - v := &V{} - - Respond(mocks.NewResponseWithContent(c), - ByUnmarshallingJSON(v), - ByClosing()) - - fmt.Printf("%s is %d years old\n", v.Name, v.Age) - // Output: Rob Pike is 42 years old -} - -func ExampleByUnmarshallingXML() { - c := ` - - Rob Pike - 42 - ` - - type V struct { - Name string `xml:"Name"` - Age int `xml:"Age"` - } - - v := &V{} - - Respond(mocks.NewResponseWithContent(c), - ByUnmarshallingXML(v), - ByClosing()) - - fmt.Printf("%s is %d years old\n", v.Name, v.Age) - // Output: Rob Pike is 42 years old -} - -func TestCreateResponderDoesNotModify(t *testing.T) { - r1 := mocks.NewResponse() - r2 := mocks.NewResponse() - p := CreateResponder() - err := p.Respond(r1) - if err != nil { - t.Fatalf("autorest: CreateResponder failed (%v)", err) - } - if !reflect.DeepEqual(r1, r2) { - t.Fatalf("autorest: CreateResponder without decorators modified the response") - } -} - -func TestCreateResponderRunsDecoratorsInOrder(t *testing.T) { - s := "" - - d := func(n int) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - s += fmt.Sprintf("%d", n) - } - return err - }) - } - } - - p := CreateResponder(d(1), d(2), d(3)) - err := p.Respond(&http.Response{}) - if err != nil { - t.Fatalf("autorest: Respond failed (%v)", err) - } - - if s != "123" { - t.Fatalf("autorest: CreateResponder invoked decorators in an incorrect order; expected '123', received '%s'", s) - } -} - -func TestByIgnoring(t *testing.T) { - r := mocks.NewResponse() - - Respond(r, - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(r2 *http.Response) error { - r1 := mocks.NewResponse() - if !reflect.DeepEqual(r1, r2) { - t.Fatalf("autorest: ByIgnoring modified the HTTP Response -- received %v, expected %v", r2, r1) - } - return nil - }) - } - })(), - ByIgnoring(), - ByClosing()) -} - -func TestByCopying_Copies(t *testing.T) { - r := mocks.NewResponseWithContent(jsonT) - b := &bytes.Buffer{} - - err := Respond(r, - ByCopying(b), - ByUnmarshallingJSON(&mocks.T{}), - ByClosing()) - if err != nil { - t.Fatalf("autorest: ByCopying returned an unexpected error -- %v", err) - } - if b.String() != jsonT { - t.Fatalf("autorest: ByCopying failed to copy the bytes read") - } -} - -func TestByCopying_ReturnsNestedErrors(t *testing.T) { - r := mocks.NewResponseWithContent(jsonT) - - r.Body.Close() - err := Respond(r, - ByCopying(&bytes.Buffer{}), - ByUnmarshallingJSON(&mocks.T{}), - ByClosing()) - if err == nil { - t.Fatalf("autorest: ByCopying failed to return the expected error") - } -} - -func TestByCopying_AcceptsNilReponse(t *testing.T) { - r := mocks.NewResponse() - - Respond(r, - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - r.Respond(nil) - return nil - }) - } - })(), - ByCopying(&bytes.Buffer{})) -} - -func TestByCopying_AcceptsNilBody(t *testing.T) { - r := mocks.NewResponse() - - Respond(r, - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - resp.Body = nil - r.Respond(resp) - return nil - }) - } - })(), - ByCopying(&bytes.Buffer{})) -} - -func TestByClosing(t *testing.T) { - r := mocks.NewResponse() - err := Respond(r, ByClosing()) - if err != nil { - t.Fatalf("autorest: ByClosing failed (%v)", err) - } - if r.Body.(*mocks.Body).IsOpen() { - t.Fatalf("autorest: ByClosing did not close the response body") - } -} - -func TestByClosingAcceptsNilResponse(t *testing.T) { - r := mocks.NewResponse() - - Respond(r, - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - r.Respond(nil) - return nil - }) - } - })(), - ByClosing()) -} - -func TestByClosingAcceptsNilBody(t *testing.T) { - r := mocks.NewResponse() - - Respond(r, - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - resp.Body = nil - r.Respond(resp) - return nil - }) - } - })(), - ByClosing()) -} - -func TestByClosingClosesEvenAfterErrors(t *testing.T) { - var e error - - r := mocks.NewResponse() - Respond(r, - withErrorRespondDecorator(&e), - ByClosing()) - - if r.Body.(*mocks.Body).IsOpen() { - t.Fatalf("autorest: ByClosing did not close the response body after an error occurred") - } -} - -func TestByClosingClosesReturnsNestedErrors(t *testing.T) { - var e error - - r := mocks.NewResponse() - err := Respond(r, - withErrorRespondDecorator(&e), - ByClosing()) - - if err == nil || !reflect.DeepEqual(e, err) { - t.Fatalf("autorest: ByClosing failed to return a nested error") - } -} - -func TestByClosingIfErrorAcceptsNilResponse(t *testing.T) { - var e error - - r := mocks.NewResponse() - - Respond(r, - withErrorRespondDecorator(&e), - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - r.Respond(nil) - return nil - }) - } - })(), - ByClosingIfError()) -} - -func TestByClosingIfErrorAcceptsNilBody(t *testing.T) { - var e error - - r := mocks.NewResponse() - - Respond(r, - withErrorRespondDecorator(&e), - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - resp.Body = nil - r.Respond(resp) - return nil - }) - } - })(), - ByClosingIfError()) -} - -func TestByClosingIfErrorClosesIfAnErrorOccurs(t *testing.T) { - var e error - - r := mocks.NewResponse() - Respond(r, - withErrorRespondDecorator(&e), - ByClosingIfError()) - - if r.Body.(*mocks.Body).IsOpen() { - t.Fatalf("autorest: ByClosingIfError did not close the response body after an error occurred") - } -} - -func TestByClosingIfErrorDoesNotClosesIfNoErrorOccurs(t *testing.T) { - r := mocks.NewResponse() - Respond(r, - ByClosingIfError()) - - if !r.Body.(*mocks.Body).IsOpen() { - t.Fatalf("autorest: ByClosingIfError closed the response body even though no error occurred") - } -} - -func TestByDiscardingBody(t *testing.T) { - r := mocks.NewResponse() - err := Respond(r, - ByDiscardingBody()) - if err != nil { - t.Fatalf("autorest: ByDiscardingBody failed (%v)", err) - } - buf, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatalf("autorest: Reading result of ByDiscardingBody failed (%v)", err) - } - - if len(buf) != 0 { - t.Logf("autorest: Body was not empty after calling ByDiscardingBody.") - t.Fail() - } -} - -func TestByDiscardingBodyAcceptsNilResponse(t *testing.T) { - var e error - - r := mocks.NewResponse() - - Respond(r, - withErrorRespondDecorator(&e), - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - r.Respond(nil) - return nil - }) - } - })(), - ByDiscardingBody()) -} - -func TestByDiscardingBodyAcceptsNilBody(t *testing.T) { - var e error - - r := mocks.NewResponse() - - Respond(r, - withErrorRespondDecorator(&e), - (func() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - resp.Body.Close() - resp.Body = nil - r.Respond(resp) - return nil - }) - } - })(), - ByDiscardingBody()) -} - -func TestByUnmarshallingJSON(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err != nil { - t.Fatalf("autorest: ByUnmarshallingJSON failed (%v)", err) - } - if v.Name != "Rob Pike" || v.Age != 42 { - t.Fatalf("autorest: ByUnmarshallingJSON failed to properly unmarshal") - } -} - -func TestByUnmarshallingJSON_HandlesReadErrors(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - r.Body.(*mocks.Body).Close() - - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err == nil { - t.Fatalf("autorest: ByUnmarshallingJSON failed to receive / respond to read error") - } -} - -func TestByUnmarshallingJSONIncludesJSONInErrors(t *testing.T) { - v := &mocks.T{} - j := jsonT[0 : len(jsonT)-2] - r := mocks.NewResponseWithContent(j) - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err == nil || !strings.Contains(err.Error(), j) { - t.Fatalf("autorest: ByUnmarshallingJSON failed to return JSON in error (%v)", err) - } -} - -func TestByUnmarshallingJSONEmptyInput(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(``) - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err != nil { - t.Fatalf("autorest: ByUnmarshallingJSON failed to return nil in case of empty JSON (%v)", err) - } -} - -func TestByUnmarshallingXML(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(xmlT) - err := Respond(r, - ByUnmarshallingXML(v), - ByClosing()) - if err != nil { - t.Fatalf("autorest: ByUnmarshallingXML failed (%v)", err) - } - if v.Name != "Rob Pike" || v.Age != 42 { - t.Fatalf("autorest: ByUnmarshallingXML failed to properly unmarshal") - } -} - -func TestByUnmarshallingXML_HandlesReadErrors(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(xmlT) - r.Body.(*mocks.Body).Close() - - err := Respond(r, - ByUnmarshallingXML(v), - ByClosing()) - if err == nil { - t.Fatalf("autorest: ByUnmarshallingXML failed to receive / respond to read error") - } -} - -func TestByUnmarshallingXMLIncludesXMLInErrors(t *testing.T) { - v := &mocks.T{} - x := xmlT[0 : len(xmlT)-2] - r := mocks.NewResponseWithContent(x) - err := Respond(r, - ByUnmarshallingXML(v), - ByClosing()) - if err == nil || !strings.Contains(err.Error(), x) { - t.Fatalf("autorest: ByUnmarshallingXML failed to return XML in error (%v)", err) - } -} - -func TestRespondAcceptsNullResponse(t *testing.T) { - err := Respond(nil) - if err != nil { - t.Fatalf("autorest: Respond returned an unexpected error when given a null Response (%v)", err) - } -} - -func TestWithErrorUnlessStatusCodeOKResponse(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - err := Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - ByUnmarshallingJSON(v), - ByClosing()) - - if err != nil { - t.Fatalf("autorest: WithErrorUnlessStatusCode(http.StatusOK) failed on okay response. (%v)", err) - } - - if v.Name != "Rob Pike" || v.Age != 42 { - t.Fatalf("autorest: WithErrorUnlessStatusCode(http.StatusOK) corrupted the response body of okay response.") - } -} - -func TesWithErrorUnlessStatusCodeErrorResponse(t *testing.T) { - v := &mocks.T{} - e := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - r.Status = "400 BadRequest" - r.StatusCode = http.StatusBadRequest - - err := Respond(r, - WithErrorUnlessStatusCode(http.StatusOK), - ByUnmarshallingJSON(v), - ByClosing()) - - if err == nil { - t.Fatal("autorest: WithErrorUnlessStatusCode(http.StatusOK) did not return error, on a response to a bad request.") - } - - var errorRespBody []byte - if derr, ok := err.(DetailedError); !ok { - t.Fatalf("autorest: WithErrorUnlessStatusCode(http.StatusOK) got wrong error type : %T, expected: DetailedError, on a response to a bad request.", err) - } else { - errorRespBody = derr.ServiceError - } - - if errorRespBody == nil { - t.Fatalf("autorest: WithErrorUnlessStatusCode(http.StatusOK) ServiceError not returned in DetailedError on a response to a bad request.") - } - - err = json.Unmarshal(errorRespBody, e) - if err != nil { - t.Fatalf("autorest: WithErrorUnlessStatusCode(http.StatusOK) cannot parse error returned in ServiceError into json. %v", err) - } - - expected := &mocks.T{Name: "Rob Pike", Age: 42} - if e != expected { - t.Fatalf("autorest: WithErrorUnlessStatusCode(http.StatusOK wrong value from parsed ServiceError: got=%#v expected=%#v", e, expected) - } -} - -func TestWithErrorUnlessStatusCode(t *testing.T) { - r := mocks.NewResponse() - r.Request = mocks.NewRequest() - r.Status = "400 BadRequest" - r.StatusCode = http.StatusBadRequest - - err := Respond(r, - WithErrorUnlessStatusCode(http.StatusBadRequest, http.StatusUnauthorized, http.StatusInternalServerError), - ByClosingIfError()) - - if err != nil { - t.Fatalf("autorest: WithErrorUnlessStatusCode returned an error (%v) for an acceptable status code (%s)", err, r.Status) - } -} - -func TestWithErrorUnlessStatusCodeEmitsErrorForUnacceptableStatusCode(t *testing.T) { - r := mocks.NewResponse() - r.Request = mocks.NewRequest() - r.Status = "400 BadRequest" - r.StatusCode = http.StatusBadRequest - - err := Respond(r, - WithErrorUnlessStatusCode(http.StatusOK, http.StatusUnauthorized, http.StatusInternalServerError), - ByClosingIfError()) - - if err == nil { - t.Fatalf("autorest: WithErrorUnlessStatusCode failed to return an error for an unacceptable status code (%s)", r.Status) - } -} - -func TestWithErrorUnlessOK(t *testing.T) { - r := mocks.NewResponse() - r.Request = mocks.NewRequest() - - err := Respond(r, - WithErrorUnlessOK(), - ByClosingIfError()) - - if err != nil { - t.Fatalf("autorest: WithErrorUnlessOK returned an error for OK status code (%v)", err) - } -} - -func TestWithErrorUnlessOKEmitsErrorIfNotOK(t *testing.T) { - r := mocks.NewResponse() - r.Request = mocks.NewRequest() - r.Status = "400 BadRequest" - r.StatusCode = http.StatusBadRequest - - err := Respond(r, - WithErrorUnlessOK(), - ByClosingIfError()) - - if err == nil { - t.Fatalf("autorest: WithErrorUnlessOK failed to return an error for a non-OK status code (%v)", err) - } -} - -func TestExtractHeader(t *testing.T) { - r := mocks.NewResponse() - v := []string{"v1", "v2", "v3"} - mocks.SetResponseHeaderValues(r, mocks.TestHeader, v) - - if !reflect.DeepEqual(ExtractHeader(mocks.TestHeader, r), v) { - t.Fatalf("autorest: ExtractHeader failed to retrieve the expected header -- expected [%s]%v, received [%s]%v", - mocks.TestHeader, v, mocks.TestHeader, ExtractHeader(mocks.TestHeader, r)) - } -} - -func TestExtractHeaderHandlesMissingHeader(t *testing.T) { - var v []string - r := mocks.NewResponse() - - if !reflect.DeepEqual(ExtractHeader(mocks.TestHeader, r), v) { - t.Fatalf("autorest: ExtractHeader failed to handle a missing header -- expected %v, received %v", - v, ExtractHeader(mocks.TestHeader, r)) - } -} - -func TestExtractHeaderValue(t *testing.T) { - r := mocks.NewResponse() - v := "v1" - mocks.SetResponseHeader(r, mocks.TestHeader, v) - - if ExtractHeaderValue(mocks.TestHeader, r) != v { - t.Fatalf("autorest: ExtractHeader failed to retrieve the expected header -- expected [%s]%v, received [%s]%v", - mocks.TestHeader, v, mocks.TestHeader, ExtractHeaderValue(mocks.TestHeader, r)) - } -} - -func TestExtractHeaderValueHandlesMissingHeader(t *testing.T) { - r := mocks.NewResponse() - v := "" - - if ExtractHeaderValue(mocks.TestHeader, r) != v { - t.Fatalf("autorest: ExtractHeader failed to retrieve the expected header -- expected [%s]%v, received [%s]%v", - mocks.TestHeader, v, mocks.TestHeader, ExtractHeaderValue(mocks.TestHeader, r)) - } -} - -func TestExtractHeaderValueRetrievesFirstValue(t *testing.T) { - r := mocks.NewResponse() - v := []string{"v1", "v2", "v3"} - mocks.SetResponseHeaderValues(r, mocks.TestHeader, v) - - if ExtractHeaderValue(mocks.TestHeader, r) != v[0] { - t.Fatalf("autorest: ExtractHeader failed to retrieve the expected header -- expected [%s]%v, received [%s]%v", - mocks.TestHeader, v[0], mocks.TestHeader, ExtractHeaderValue(mocks.TestHeader, r)) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/sender.go b/vendor/github.com/Azure/go-autorest/autorest/sender.go index e1ec49573f..c5efd59a21 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/sender.go +++ b/vendor/github.com/Azure/go-autorest/autorest/sender.go @@ -215,20 +215,26 @@ func DoRetryForStatusCodes(attempts int, backoff time.Duration, codes ...int) Se rr := NewRetriableRequest(r) // Increment to add the first call (attempts denotes number of retries) attempts++ - for attempt := 0; attempt < attempts; attempt++ { + for attempt := 0; attempt < attempts; { err = rr.Prepare() if err != nil { return resp, err } resp, err = s.Do(rr.Request()) - // we want to retry if err is not nil (e.g. transient network failure) - if err == nil && !ResponseHasStatusCode(resp, codes...) { + // we want to retry if err is not nil (e.g. transient network failure). note that for failed authentication + // resp and err will both have a value, so in this case we don't want to retry as it will never succeed. + if err == nil && !ResponseHasStatusCode(resp, codes...) || IsTokenRefreshError(err) { return resp, err } delayed := DelayWithRetryAfter(resp, r.Cancel) if !delayed { DelayForBackoff(backoff, attempt, r.Cancel) } + // don't count a 429 against the number of attempts + // so that we continue to retry until it succeeds + if resp == nil || resp.StatusCode != http.StatusTooManyRequests { + attempt++ + } } return resp, err }) diff --git a/vendor/github.com/Azure/go-autorest/autorest/sender_test.go b/vendor/github.com/Azure/go-autorest/autorest/sender_test.go deleted file mode 100644 index a72731d41f..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/sender_test.go +++ /dev/null @@ -1,811 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "fmt" - "log" - "net/http" - "os" - "reflect" - "sync" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -func ExampleSendWithSender() { - r := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(r) - - client := mocks.NewSender() - client.AppendAndRepeatResponse(r, 10) - - logger := log.New(os.Stdout, "autorest: ", 0) - na := NullAuthorizer{} - - req, _ := Prepare(&http.Request{}, - AsGet(), - WithBaseURL("https://microsoft.com/a/b/c/"), - na.WithAuthorization()) - - r, _ = SendWithSender(client, req, - WithLogging(logger), - DoErrorIfStatusCode(http.StatusAccepted), - DoCloseIfError(), - DoRetryForAttempts(5, time.Duration(0))) - - Respond(r, - ByDiscardingBody(), - ByClosing()) - - // Output: - // autorest: Sending GET https://microsoft.com/a/b/c/ - // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted - // autorest: Sending GET https://microsoft.com/a/b/c/ - // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted - // autorest: Sending GET https://microsoft.com/a/b/c/ - // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted - // autorest: Sending GET https://microsoft.com/a/b/c/ - // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted - // autorest: Sending GET https://microsoft.com/a/b/c/ - // autorest: GET https://microsoft.com/a/b/c/ received 202 Accepted -} - -func ExampleDoRetryForAttempts() { - client := mocks.NewSender() - client.SetAndRepeatError(fmt.Errorf("Faux Error"), 10) - - // Retry with backoff -- ensure returned Bodies are closed - r, _ := SendWithSender(client, mocks.NewRequest(), - DoCloseIfError(), - DoRetryForAttempts(5, time.Duration(0))) - - Respond(r, - ByDiscardingBody(), - ByClosing()) - - fmt.Printf("Retry stopped after %d attempts", client.Attempts()) - // Output: Retry stopped after 5 attempts -} - -func ExampleDoErrorIfStatusCode() { - client := mocks.NewSender() - client.AppendAndRepeatResponse(mocks.NewResponseWithStatus("204 NoContent", http.StatusNoContent), 10) - - // Chain decorators to retry the request, up to five times, if the status code is 204 - r, _ := SendWithSender(client, mocks.NewRequest(), - DoErrorIfStatusCode(http.StatusNoContent), - DoCloseIfError(), - DoRetryForAttempts(5, time.Duration(0))) - - Respond(r, - ByDiscardingBody(), - ByClosing()) - - fmt.Printf("Retry stopped after %d attempts with code %s", client.Attempts(), r.Status) - // Output: Retry stopped after 5 attempts with code 204 NoContent -} - -func TestSendWithSenderRunsDecoratorsInOrder(t *testing.T) { - client := mocks.NewSender() - s := "" - - r, err := SendWithSender(client, mocks.NewRequest(), - withMessage(&s, "a"), - withMessage(&s, "b"), - withMessage(&s, "c")) - if err != nil { - t.Fatalf("autorest: SendWithSender returned an error (%v)", err) - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) - - if s != "abc" { - t.Fatalf("autorest: SendWithSender invoke decorators out of order; expected 'abc', received '%s'", s) - } -} - -func TestCreateSender(t *testing.T) { - f := false - - s := CreateSender( - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - f = true - return nil, nil - }) - } - })()) - s.Do(&http.Request{}) - - if !f { - t.Fatal("autorest: CreateSender failed to apply supplied decorator") - } -} - -func TestSend(t *testing.T) { - f := false - - Send(&http.Request{}, - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - f = true - return nil, nil - }) - } - })()) - - if !f { - t.Fatal("autorest: Send failed to apply supplied decorator") - } -} - -func TestAfterDelayWaits(t *testing.T) { - client := mocks.NewSender() - - d := 2 * time.Second - - tt := time.Now() - r, _ := SendWithSender(client, mocks.NewRequest(), - AfterDelay(d)) - s := time.Since(tt) - if s < d { - t.Fatal("autorest: AfterDelay failed to wait for at least the specified duration") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestAfterDelay_Cancels(t *testing.T) { - client := mocks.NewSender() - cancel := make(chan struct{}) - delay := 5 * time.Second - - var wg sync.WaitGroup - wg.Add(1) - tt := time.Now() - go func() { - req := mocks.NewRequest() - req.Cancel = cancel - wg.Done() - SendWithSender(client, req, - AfterDelay(delay)) - }() - wg.Wait() - close(cancel) - time.Sleep(5 * time.Millisecond) - if time.Since(tt) >= delay { - t.Fatal("autorest: AfterDelay failed to cancel") - } -} - -func TestAfterDelayDoesNotWaitTooLong(t *testing.T) { - client := mocks.NewSender() - - d := 5 * time.Millisecond - start := time.Now() - r, _ := SendWithSender(client, mocks.NewRequest(), - AfterDelay(d)) - - if time.Since(start) > (5 * d) { - t.Fatal("autorest: AfterDelay waited too long (exceeded 5 times specified duration)") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestAsIs(t *testing.T) { - client := mocks.NewSender() - - r1 := mocks.NewResponse() - client.AppendResponse(r1) - - r2, err := SendWithSender(client, mocks.NewRequest(), - AsIs()) - if err != nil { - t.Fatalf("autorest: AsIs returned an unexpected error (%v)", err) - } else if !reflect.DeepEqual(r1, r2) { - t.Fatalf("autorest: AsIs modified the response -- received %v, expected %v", r2, r1) - } - - Respond(r1, - ByDiscardingBody(), - ByClosing()) - Respond(r2, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoCloseIfError(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(mocks.NewResponseWithStatus("400 BadRequest", http.StatusBadRequest)) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoErrorIfStatusCode(http.StatusBadRequest), - DoCloseIfError()) - - if r.Body.(*mocks.Body).IsOpen() { - t.Fatal("autorest: Expected DoCloseIfError to close response body -- it was left open") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoCloseIfErrorAcceptsNilResponse(t *testing.T) { - client := mocks.NewSender() - - SendWithSender(client, mocks.NewRequest(), - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err != nil { - resp.Body.Close() - } - return nil, fmt.Errorf("Faux Error") - }) - } - })(), - DoCloseIfError()) -} - -func TestDoCloseIfErrorAcceptsNilBody(t *testing.T) { - client := mocks.NewSender() - - SendWithSender(client, mocks.NewRequest(), - (func() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err != nil { - resp.Body.Close() - } - resp.Body = nil - return resp, fmt.Errorf("Faux Error") - }) - } - })(), - DoCloseIfError()) -} - -func TestDoErrorIfStatusCode(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(mocks.NewResponseWithStatus("400 BadRequest", http.StatusBadRequest)) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoErrorIfStatusCode(http.StatusBadRequest), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: DoErrorIfStatusCode failed to emit an error for passed code") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoErrorIfStatusCodeIgnoresStatusCodes(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAcceptedResponse()) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoErrorIfStatusCode(http.StatusBadRequest), - DoCloseIfError()) - if err != nil { - t.Fatal("autorest: DoErrorIfStatusCode failed to ignore a status code") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoErrorUnlessStatusCode(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(mocks.NewResponseWithStatus("400 BadRequest", http.StatusBadRequest)) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoErrorUnlessStatusCode(http.StatusAccepted), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: DoErrorUnlessStatusCode failed to emit an error for an unknown status code") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoErrorUnlessStatusCodeIgnoresStatusCodes(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAcceptedResponse()) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoErrorUnlessStatusCode(http.StatusAccepted), - DoCloseIfError()) - if err != nil { - t.Fatal("autorest: DoErrorUnlessStatusCode emitted an error for a knonwn status code") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoRetryForAttemptsStopsAfterSuccess(t *testing.T) { - client := mocks.NewSender() - - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForAttempts(5, time.Duration(0))) - if client.Attempts() != 1 { - t.Fatalf("autorest: DoRetryForAttempts failed to stop after success -- expected attempts %v, actual %v", - 1, client.Attempts()) - } - if err != nil { - t.Fatalf("autorest: DoRetryForAttempts returned an unexpected error (%v)", err) - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoRetryForAttemptsStopsAfterAttempts(t *testing.T) { - client := mocks.NewSender() - client.SetAndRepeatError(fmt.Errorf("Faux Error"), 10) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForAttempts(5, time.Duration(0)), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: Mock client failed to emit errors") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) - - if client.Attempts() != 5 { - t.Fatal("autorest: DoRetryForAttempts failed to stop after specified number of attempts") - } -} - -func TestDoRetryForAttemptsReturnsResponse(t *testing.T) { - client := mocks.NewSender() - client.SetError(fmt.Errorf("Faux Error")) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForAttempts(1, time.Duration(0))) - if err == nil { - t.Fatal("autorest: Mock client failed to emit errors") - } - - if r == nil { - t.Fatal("autorest: DoRetryForAttempts failed to return the underlying response") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoRetryForDurationStopsAfterSuccess(t *testing.T) { - client := mocks.NewSender() - - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForDuration(10*time.Millisecond, time.Duration(0))) - if client.Attempts() != 1 { - t.Fatalf("autorest: DoRetryForDuration failed to stop after success -- expected attempts %v, actual %v", - 1, client.Attempts()) - } - if err != nil { - t.Fatalf("autorest: DoRetryForDuration returned an unexpected error (%v)", err) - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoRetryForDurationStopsAfterDuration(t *testing.T) { - client := mocks.NewSender() - client.SetAndRepeatError(fmt.Errorf("Faux Error"), -1) - - d := 5 * time.Millisecond - start := time.Now() - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForDuration(d, time.Duration(0)), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: Mock client failed to emit errors") - } - - if time.Since(start) < d { - t.Fatal("autorest: DoRetryForDuration failed stopped too soon") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoRetryForDurationStopsWithinReason(t *testing.T) { - client := mocks.NewSender() - client.SetAndRepeatError(fmt.Errorf("Faux Error"), -1) - - d := 5 * time.Second - start := time.Now() - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForDuration(d, time.Duration(0)), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: Mock client failed to emit errors") - } - - if time.Since(start) > (5 * d) { - t.Fatal("autorest: DoRetryForDuration failed stopped soon enough (exceeded 5 times specified duration)") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoRetryForDurationReturnsResponse(t *testing.T) { - client := mocks.NewSender() - client.SetAndRepeatError(fmt.Errorf("Faux Error"), -1) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoRetryForDuration(10*time.Millisecond, time.Duration(0)), - DoCloseIfError()) - if err == nil { - t.Fatal("autorest: Mock client failed to emit errors") - } - - if r == nil { - t.Fatal("autorest: DoRetryForDuration failed to return the underlying response") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDelayForBackoff(t *testing.T) { - d := 2 * time.Second - start := time.Now() - DelayForBackoff(d, 0, nil) - if time.Since(start) < d { - t.Fatal("autorest: DelayForBackoff did not delay as long as expected") - } -} - -func TestDelayForBackoff_Cancels(t *testing.T) { - cancel := make(chan struct{}) - delay := 5 * time.Second - - var wg sync.WaitGroup - wg.Add(1) - start := time.Now() - go func() { - wg.Done() - DelayForBackoff(delay, 0, cancel) - }() - wg.Wait() - close(cancel) - time.Sleep(5 * time.Millisecond) - if time.Since(start) >= delay { - t.Fatal("autorest: DelayForBackoff failed to cancel") - } -} - -func TestDelayForBackoffWithinReason(t *testing.T) { - d := 5 * time.Second - maxCoefficient := 2 - start := time.Now() - DelayForBackoff(d, 0, nil) - if time.Since(start) > (time.Duration(maxCoefficient) * d) { - - t.Fatalf("autorest: DelayForBackoff delayed too long (exceeded %d times the specified duration)", maxCoefficient) - } -} - -func TestDoPollForStatusCodes_IgnoresUnspecifiedStatusCodes(t *testing.T) { - client := mocks.NewSender() - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Duration(0), time.Duration(0))) - - if client.Attempts() != 1 { - t.Fatalf("autorest: Sender#DoPollForStatusCodes polled for unspecified status code") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoPollForStatusCodes_PollsForSpecifiedStatusCodes(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAcceptedResponse()) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - - if client.Attempts() != 2 { - t.Fatalf("autorest: Sender#DoPollForStatusCodes failed to poll for specified status code") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoPollForStatusCodes_CanBeCanceled(t *testing.T) { - cancel := make(chan struct{}) - delay := 5 * time.Second - - r := mocks.NewResponse() - mocks.SetAcceptedHeaders(r) - client := mocks.NewSender() - client.AppendAndRepeatResponse(r, 100) - - var wg sync.WaitGroup - wg.Add(1) - start := time.Now() - go func() { - wg.Done() - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - Respond(r, - ByDiscardingBody(), - ByClosing()) - }() - wg.Wait() - close(cancel) - time.Sleep(5 * time.Millisecond) - if time.Since(start) >= delay { - t.Fatalf("autorest: Sender#DoPollForStatusCodes failed to cancel") - } -} - -func TestDoPollForStatusCodes_ClosesAllNonreturnedResponseBodiesWhenPolling(t *testing.T) { - resp := newAcceptedResponse() - - client := mocks.NewSender() - client.AppendAndRepeatResponse(resp, 2) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - - if resp.Body.(*mocks.Body).IsOpen() || resp.Body.(*mocks.Body).CloseAttempts() < 2 { - t.Fatalf("autorest: Sender#DoPollForStatusCodes did not close unreturned response bodies") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoPollForStatusCodes_LeavesLastResponseBodyOpen(t *testing.T) { - client := mocks.NewSender() - client.AppendResponse(newAcceptedResponse()) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - - if !r.Body.(*mocks.Body).IsOpen() { - t.Fatalf("autorest: Sender#DoPollForStatusCodes did not leave open the body of the last response") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoPollForStatusCodes_StopsPollingAfterAnError(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(newAcceptedResponse(), 5) - client.SetError(fmt.Errorf("Faux Error")) - client.SetEmitErrorAfter(1) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - - if client.Attempts() > 2 { - t.Fatalf("autorest: Sender#DoPollForStatusCodes failed to stop polling after receiving an error") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoPollForStatusCodes_ReturnsPollingError(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(newAcceptedResponse(), 5) - client.SetError(fmt.Errorf("Faux Error")) - client.SetEmitErrorAfter(1) - - r, err := SendWithSender(client, mocks.NewRequest(), - DoPollForStatusCodes(time.Millisecond, time.Millisecond, http.StatusAccepted)) - - if err == nil { - t.Fatalf("autorest: Sender#DoPollForStatusCodes failed to return error from polling") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestWithLogging_Logs(t *testing.T) { - buf := &bytes.Buffer{} - logger := log.New(buf, "autorest: ", 0) - client := mocks.NewSender() - - r, _ := SendWithSender(client, &http.Request{}, - WithLogging(logger)) - - if buf.String() == "" { - t.Fatal("autorest: Sender#WithLogging failed to log the request") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestWithLogging_HandlesMissingResponse(t *testing.T) { - buf := &bytes.Buffer{} - logger := log.New(buf, "autorest: ", 0) - client := mocks.NewSender() - client.AppendResponse(nil) - client.SetError(fmt.Errorf("Faux Error")) - - r, err := SendWithSender(client, &http.Request{}, - WithLogging(logger)) - - if r != nil || err == nil { - t.Fatal("autorest: Sender#WithLogging returned a valid response -- expecting nil") - } - if buf.String() == "" { - t.Fatal("autorest: Sender#WithLogging failed to log the request for a nil response") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) -} - -func TestDoRetryForStatusCodesWithSuccess(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(mocks.NewResponseWithStatus("408 Request Timeout", http.StatusRequestTimeout), 2) - client.AppendResponse(mocks.NewResponseWithStatus("200 OK", http.StatusOK)) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoRetryForStatusCodes(5, time.Duration(2*time.Second), http.StatusRequestTimeout), - ) - - Respond(r, - ByDiscardingBody(), - ByClosing()) - - if client.Attempts() != 3 { - t.Fatalf("autorest: Sender#DoRetryForStatusCodes -- Got: StatusCode %v in %v attempts; Want: StatusCode 200 OK in 2 attempts -- ", - r.Status, client.Attempts()-1) - } -} - -func TestDoRetryForStatusCodesWithNoSuccess(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(mocks.NewResponseWithStatus("504 Gateway Timeout", http.StatusGatewayTimeout), 5) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoRetryForStatusCodes(2, time.Duration(2*time.Second), http.StatusGatewayTimeout), - ) - Respond(r, - ByDiscardingBody(), - ByClosing()) - - if client.Attempts() != 3 { - t.Fatalf("autorest: Sender#DoRetryForStatusCodes -- Got: failed stop after %v retry attempts; Want: Stop after 2 retry attempts", - client.Attempts()-1) - } -} - -func TestDoRetryForStatusCodes_CodeNotInRetryList(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(mocks.NewResponseWithStatus("204 No Content", http.StatusNoContent), 1) - - r, _ := SendWithSender(client, mocks.NewRequest(), - DoRetryForStatusCodes(6, time.Duration(2*time.Second), http.StatusGatewayTimeout), - ) - - Respond(r, - ByDiscardingBody(), - ByClosing()) - - if client.Attempts() != 1 || r.Status != "204 No Content" { - t.Fatalf("autorest: Sender#DoRetryForStatusCodes -- Got: Retry attempts %v for StatusCode %v; Want: 0 attempts for StatusCode 204", - client.Attempts(), r.Status) - } -} - -func TestDoRetryForStatusCodes_RequestBodyReadError(t *testing.T) { - client := mocks.NewSender() - client.AppendAndRepeatResponse(mocks.NewResponseWithStatus("204 No Content", http.StatusNoContent), 2) - - r, err := SendWithSender(client, mocks.NewRequestWithCloseBody(), - DoRetryForStatusCodes(6, time.Duration(2*time.Second), http.StatusGatewayTimeout), - ) - - Respond(r, - ByDiscardingBody(), - ByClosing()) - - if err == nil || client.Attempts() != 0 { - t.Fatalf("autorest: Sender#DoRetryForStatusCodes -- Got: Not failed for request body read error; Want: Failed for body read error - %v", err) - } -} - -func newAcceptedResponse() *http.Response { - resp := mocks.NewResponseWithStatus("202 Accepted", http.StatusAccepted) - mocks.SetAcceptedHeaders(resp) - return resp -} - -func TestDelayWithRetryAfterWithSuccess(t *testing.T) { - after, retries := 5, 2 - totalSecs := after * retries - - client := mocks.NewSender() - resp := mocks.NewResponseWithStatus("429 Too many requests", http.StatusTooManyRequests) - mocks.SetResponseHeader(resp, "Retry-After", fmt.Sprintf("%v", after)) - client.AppendAndRepeatResponse(resp, retries) - client.AppendResponse(mocks.NewResponseWithStatus("200 OK", http.StatusOK)) - - d := time.Second * time.Duration(totalSecs) - start := time.Now() - r, _ := SendWithSender(client, mocks.NewRequest(), - DoRetryForStatusCodes(5, time.Duration(time.Second), http.StatusTooManyRequests), - ) - - if time.Since(start) < d { - t.Fatal("autorest: DelayWithRetryAfter failed stopped too soon") - } - - Respond(r, - ByDiscardingBody(), - ByClosing()) - - if client.Attempts() != 3 { - t.Fatalf("autorest: Sender#DelayWithRetryAfter -- Got: StatusCode %v in %v attempts; Want: StatusCode 200 OK in 2 attempts -- ", - r.Status, client.Attempts()-1) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility.go b/vendor/github.com/Azure/go-autorest/autorest/utility.go index 1ef4575fa0..afb3e4e161 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/utility.go +++ b/vendor/github.com/Azure/go-autorest/autorest/utility.go @@ -23,8 +23,9 @@ import ( "net/http" "net/url" "reflect" - "sort" "strings" + + "github.com/Azure/go-autorest/autorest/adal" ) // EncodedAs is a series of constants specifying various data encodings @@ -138,13 +139,38 @@ func MapToValues(m map[string]interface{}) url.Values { return v } +// AsStringSlice method converts interface{} to []string. This expects a +//that the parameter passed to be a slice or array of a type that has the underlying +//type a string. +func AsStringSlice(s interface{}) ([]string, error) { + v := reflect.ValueOf(s) + if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { + return nil, NewError("autorest", "AsStringSlice", "the value's type is not an array.") + } + stringSlice := make([]string, 0, v.Len()) + + for i := 0; i < v.Len(); i++ { + stringSlice = append(stringSlice, v.Index(i).String()) + } + return stringSlice, nil +} + // String method converts interface v to string. If interface is a list, it -// joins list elements using separator. +// joins list elements using the seperator. Note that only sep[0] will be used for +// joining if any separator is specified. func String(v interface{}, sep ...string) string { - if len(sep) > 0 { - return ensureValueString(strings.Join(v.([]string), sep[0])) + if len(sep) == 0 { + return ensureValueString(v) + } + stringSlice, ok := v.([]string) + if ok == false { + var err error + stringSlice, err = AsStringSlice(v) + if err != nil { + panic(fmt.Sprintf("autorest: Couldn't convert value to a string %s.", err)) + } } - return ensureValueString(v) + return ensureValueString(strings.Join(stringSlice, sep[0])) } // Encode method encodes url path and query parameters. @@ -168,30 +194,6 @@ func queryEscape(s string) string { return url.QueryEscape(s) } -// This method is same as Encode() method of "net/url" go package, -// except it does not encode the query parameters because they -// already come encoded. It formats values map in query format (bar=foo&a=b). -func createQuery(v url.Values) string { - var buf bytes.Buffer - keys := make([]string, 0, len(v)) - for k := range v { - keys = append(keys, k) - } - sort.Strings(keys) - for _, k := range keys { - vs := v[k] - prefix := url.QueryEscape(k) + "=" - for _, v := range vs { - if buf.Len() > 0 { - buf.WriteByte('&') - } - buf.WriteString(prefix) - buf.WriteString(v) - } - } - return buf.String() -} - // ChangeToGet turns the specified http.Request into a GET (it assumes it wasn't). // This is mainly useful for long-running operations that use the Azure-AsyncOperation // header, so we change the initial PUT into a GET to retrieve the final result. @@ -202,3 +204,15 @@ func ChangeToGet(req *http.Request) *http.Request { req.Header.Del("Content-Length") return req } + +// IsTokenRefreshError returns true if the specified error implements the TokenRefreshError +// interface. If err is a DetailedError it will walk the chain of Original errors. +func IsTokenRefreshError(err error) bool { + if _, ok := err.(adal.TokenRefreshError); ok { + return true + } + if de, ok := err.(DetailedError); ok { + return IsTokenRefreshError(de.Original) + } + return false +} diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility_test.go b/vendor/github.com/Azure/go-autorest/autorest/utility_test.go deleted file mode 100644 index 1cda8758f8..0000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/utility_test.go +++ /dev/null @@ -1,382 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "net/http" - "net/url" - "reflect" - "sort" - "strings" - "testing" - - "github.com/Azure/go-autorest/autorest/mocks" -) - -const ( - jsonT = ` - { - "name":"Rob Pike", - "age":42 - }` - xmlT = ` - - Rob Pike - 42 - ` -) - -func TestNewDecoderCreatesJSONDecoder(t *testing.T) { - d := NewDecoder(EncodedAsJSON, strings.NewReader(jsonT)) - _, ok := d.(*json.Decoder) - if d == nil || !ok { - t.Fatal("autorest: NewDecoder failed to create a JSON decoder when requested") - } -} - -func TestNewDecoderCreatesXMLDecoder(t *testing.T) { - d := NewDecoder(EncodedAsXML, strings.NewReader(xmlT)) - _, ok := d.(*xml.Decoder) - if d == nil || !ok { - t.Fatal("autorest: NewDecoder failed to create an XML decoder when requested") - } -} - -func TestNewDecoderReturnsNilForUnknownEncoding(t *testing.T) { - d := NewDecoder("unknown", strings.NewReader(xmlT)) - if d != nil { - t.Fatal("autorest: NewDecoder created a decoder for an unknown encoding") - } -} - -func TestCopyAndDecodeDecodesJSON(t *testing.T) { - _, err := CopyAndDecode(EncodedAsJSON, strings.NewReader(jsonT), &mocks.T{}) - if err != nil { - t.Fatalf("autorest: CopyAndDecode returned an error with valid JSON - %v", err) - } -} - -func TestCopyAndDecodeDecodesXML(t *testing.T) { - _, err := CopyAndDecode(EncodedAsXML, strings.NewReader(xmlT), &mocks.T{}) - if err != nil { - t.Fatalf("autorest: CopyAndDecode returned an error with valid XML - %v", err) - } -} - -func TestCopyAndDecodeReturnsJSONDecodingErrors(t *testing.T) { - _, err := CopyAndDecode(EncodedAsJSON, strings.NewReader(jsonT[0:len(jsonT)-2]), &mocks.T{}) - if err == nil { - t.Fatalf("autorest: CopyAndDecode failed to return an error with invalid JSON") - } -} - -func TestCopyAndDecodeReturnsXMLDecodingErrors(t *testing.T) { - _, err := CopyAndDecode(EncodedAsXML, strings.NewReader(xmlT[0:len(xmlT)-2]), &mocks.T{}) - if err == nil { - t.Fatalf("autorest: CopyAndDecode failed to return an error with invalid XML") - } -} - -func TestCopyAndDecodeAlwaysReturnsACopy(t *testing.T) { - b, _ := CopyAndDecode(EncodedAsJSON, strings.NewReader(jsonT), &mocks.T{}) - if b.String() != jsonT { - t.Fatalf("autorest: CopyAndDecode failed to return a valid copy of the data - %v", b.String()) - } -} - -func TestTeeReadCloser_Copies(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - b := &bytes.Buffer{} - - r.Body = TeeReadCloser(r.Body, b) - - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err != nil { - t.Fatalf("autorest: TeeReadCloser returned an unexpected error -- %v", err) - } - if b.String() != jsonT { - t.Fatalf("autorest: TeeReadCloser failed to copy the bytes read") - } -} - -func TestTeeReadCloser_PassesReadErrors(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - - r.Body.(*mocks.Body).Close() - r.Body = TeeReadCloser(r.Body, &bytes.Buffer{}) - - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err == nil { - t.Fatalf("autorest: TeeReadCloser failed to return the expected error") - } -} - -func TestTeeReadCloser_ClosesWrappedReader(t *testing.T) { - v := &mocks.T{} - r := mocks.NewResponseWithContent(jsonT) - - b := r.Body.(*mocks.Body) - r.Body = TeeReadCloser(r.Body, &bytes.Buffer{}) - err := Respond(r, - ByUnmarshallingJSON(v), - ByClosing()) - if err != nil { - t.Fatalf("autorest: TeeReadCloser returned an unexpected error -- %v", err) - } - if b.IsOpen() { - t.Fatalf("autorest: TeeReadCloser failed to close the nested io.ReadCloser") - } -} - -func TestContainsIntFindsValue(t *testing.T) { - ints := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - v := 5 - if !containsInt(ints, v) { - t.Fatalf("autorest: containsInt failed to find %v in %v", v, ints) - } -} - -func TestContainsIntDoesNotFindValue(t *testing.T) { - ints := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} - v := 42 - if containsInt(ints, v) { - t.Fatalf("autorest: containsInt unexpectedly found %v in %v", v, ints) - } -} - -func TestContainsIntAcceptsEmptyList(t *testing.T) { - ints := make([]int, 10) - if containsInt(ints, 42) { - t.Fatalf("autorest: containsInt failed to handle an empty list") - } -} - -func TestContainsIntAcceptsNilList(t *testing.T) { - var ints []int - if containsInt(ints, 42) { - t.Fatalf("autorest: containsInt failed to handle an nil list") - } -} - -func TestEscapeStrings(t *testing.T) { - m := map[string]string{ - "string": "a long string with = odd characters", - "int": "42", - "nil": "", - } - r := map[string]string{ - "string": "a+long+string+with+%3D+odd+characters", - "int": "42", - "nil": "", - } - v := escapeValueStrings(m) - if !reflect.DeepEqual(v, r) { - t.Fatalf("autorest: ensureValueStrings returned %v\n", v) - } -} - -func TestEnsureStrings(t *testing.T) { - m := map[string]interface{}{ - "string": "string", - "int": 42, - "nil": nil, - "bytes": []byte{255, 254, 253}, - } - r := map[string]string{ - "string": "string", - "int": "42", - "nil": "", - "bytes": string([]byte{255, 254, 253}), - } - v := ensureValueStrings(m) - if !reflect.DeepEqual(v, r) { - t.Fatalf("autorest: ensureValueStrings returned %v\n", v) - } -} - -func ExampleString() { - m := []string{ - "string1", - "string2", - "string3", - } - - fmt.Println(String(m, ",")) - // Output: string1,string2,string3 -} - -func TestStringWithValidString(t *testing.T) { - i := 123 - if String(i) != "123" { - t.Fatal("autorest: String method failed to convert integer 123 to string") - } -} - -func TestEncodeWithValidPath(t *testing.T) { - s := Encode("Path", "Hello Gopher") - if s != "Hello%20Gopher" { - t.Fatalf("autorest: Encode method failed for valid path encoding. Got: %v; Want: %v", s, "Hello%20Gopher") - } -} - -func TestEncodeWithValidQuery(t *testing.T) { - s := Encode("Query", "Hello Gopher") - if s != "Hello+Gopher" { - t.Fatalf("autorest: Encode method failed for valid query encoding. Got: '%v'; Want: 'Hello+Gopher'", s) - } -} - -func TestEncodeWithValidNotPathQuery(t *testing.T) { - s := Encode("Host", "Hello Gopher") - if s != "Hello Gopher" { - t.Fatalf("autorest: Encode method failed for parameter not query or path. Got: '%v'; Want: 'Hello Gopher'", s) - } -} - -func TestMapToValues(t *testing.T) { - m := map[string]interface{}{ - "a": "a", - "b": 2, - } - v := url.Values{} - v.Add("a", "a") - v.Add("b", "2") - if !isEqual(v, MapToValues(m)) { - t.Fatalf("autorest: MapToValues method failed to return correct values - expected(%v) got(%v)", v, MapToValues(m)) - } -} - -func TestMapToValuesWithArrayValues(t *testing.T) { - m := map[string]interface{}{ - "a": []string{"a", "b"}, - "b": 2, - "c": []int{3, 4}, - } - v := url.Values{} - v.Add("a", "a") - v.Add("a", "b") - v.Add("b", "2") - v.Add("c", "3") - v.Add("c", "4") - - if !isEqual(v, MapToValues(m)) { - t.Fatalf("autorest: MapToValues method failed to return correct values - expected(%v) got(%v)", v, MapToValues(m)) - } -} - -func isEqual(v, u url.Values) bool { - for key, value := range v { - if len(u[key]) == 0 { - return false - } - sort.Strings(value) - sort.Strings(u[key]) - for i := range value { - if value[i] != u[key][i] { - return false - } - } - u.Del(key) - } - if len(u) > 0 { - return false - } - return true -} - -func doEnsureBodyClosed(t *testing.T) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if resp != nil && resp.Body != nil && resp.Body.(*mocks.Body).IsOpen() { - t.Fatal("autorest: Expected Body to be closed -- it was left open") - } - return resp, err - }) - } -} - -type mockAuthorizer struct{} - -func (ma mockAuthorizer) WithAuthorization() PrepareDecorator { - return WithHeader(headerAuthorization, mocks.TestAuthorizationHeader) -} - -type mockFailingAuthorizer struct{} - -func (mfa mockFailingAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - return r, fmt.Errorf("ERROR: mockFailingAuthorizer returned expected error") - }) - } -} - -type mockInspector struct { - wasInvoked bool -} - -func (mi *mockInspector) WithInspection() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - mi.wasInvoked = true - return p.Prepare(r) - }) - } -} - -func (mi *mockInspector) ByInspecting() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - mi.wasInvoked = true - return r.Respond(resp) - }) - } -} - -func withMessage(output *string, msg string) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil { - *output += msg - } - return resp, err - }) - } -} - -func withErrorRespondDecorator(e *error) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err != nil { - return err - } - *e = fmt.Errorf("autorest: Faux Respond Error") - return *e - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/version.go b/vendor/github.com/Azure/go-autorest/autorest/version.go index f588807dbb..a19c0d35a2 100644 --- a/vendor/github.com/Azure/go-autorest/autorest/version.go +++ b/vendor/github.com/Azure/go-autorest/autorest/version.go @@ -22,9 +22,9 @@ import ( ) const ( - major = 8 - minor = 0 - patch = 0 + major = 9 + minor = 8 + patch = 1 tag = "" ) diff --git a/vendor/github.com/armon/go-proxyproto/protocol.go b/vendor/github.com/armon/go-proxyproto/protocol.go index 576507294f..38bb6cbb1f 100644 --- a/vendor/github.com/armon/go-proxyproto/protocol.go +++ b/vendor/github.com/armon/go-proxyproto/protocol.go @@ -28,12 +28,13 @@ var ( // passed in as an argument. If the function returns an error due to the source // being disallowed, it should return ErrInvalidUpstream. // -// Behavior is as follows: -// * If error is not nil, the call to Accept() will fail. If the reason for +// If error is not nil, the call to Accept() will fail. If the reason for // triggering this failure is due to a disallowed source, it should return // ErrInvalidUpstream. -// * If bool is true, the PROXY-set address is used. -// * If bool is false, the connection's remote address is used, rather than the +// +// If bool is true, the PROXY-set address is used. +// +// If bool is false, the connection's remote address is used, rather than the // address claimed in the PROXY info. type SourceChecker func(net.Addr) (bool, error) diff --git a/vendor/github.com/armon/go-proxyproto/protocol_test.go b/vendor/github.com/armon/go-proxyproto/protocol_test.go deleted file mode 100644 index 04a9bc8593..0000000000 --- a/vendor/github.com/armon/go-proxyproto/protocol_test.go +++ /dev/null @@ -1,383 +0,0 @@ -package proxyproto - -import ( - "bytes" - "net" - "testing" - "time" -) - -const ( - goodAddr = "127.0.0.1" - badAddr = "127.0.0.2" - errAddr = "9999.0.0.2" -) - -var ( - checkAddr string -) - -func TestPassthrough(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("err: %v", err) - } - - pl := &Listener{Listener: l} - - go func() { - conn, err := net.Dial("tcp", pl.Addr().String()) - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - conn.Write([]byte("ping")) - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err != nil { - t.Fatalf("err: %v", err) - } - if !bytes.Equal(recv, []byte("pong")) { - t.Fatalf("bad: %v", recv) - } - }() - - conn, err := pl.Accept() - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err != nil { - t.Fatalf("err: %v", err) - } - if !bytes.Equal(recv, []byte("ping")) { - t.Fatalf("bad: %v", recv) - } - - if _, err := conn.Write([]byte("pong")); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestTimeout(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("err: %v", err) - } - - clientWriteDelay := 200 * time.Millisecond - proxyHeaderTimeout := 50 * time.Millisecond - pl := &Listener{Listener: l, ProxyHeaderTimeout: proxyHeaderTimeout} - - go func() { - conn, err := net.Dial("tcp", pl.Addr().String()) - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - // Do not send data for a while - time.Sleep(clientWriteDelay) - - conn.Write([]byte("ping")) - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err != nil { - t.Fatalf("err: %v", err) - } - if !bytes.Equal(recv, []byte("pong")) { - t.Fatalf("bad: %v", recv) - } - }() - - conn, err := pl.Accept() - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - // Check the remote addr is the original 127.0.0.1 - remoteAddrStartTime := time.Now() - addr := conn.RemoteAddr().(*net.TCPAddr) - if addr.IP.String() != "127.0.0.1" { - t.Fatalf("bad: %v", addr) - } - remoteAddrDuration := time.Since(remoteAddrStartTime) - - // Check RemoteAddr() call did timeout - if remoteAddrDuration >= clientWriteDelay { - t.Fatalf("RemoteAddr() took longer than the specified timeout: %v < %v", proxyHeaderTimeout, remoteAddrDuration) - } - - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err != nil { - t.Fatalf("err: %v", err) - } - if !bytes.Equal(recv, []byte("ping")) { - t.Fatalf("bad: %v", recv) - } - - if _, err := conn.Write([]byte("pong")); err != nil { - t.Fatalf("err: %v", err) - } -} - -func TestParse_ipv4(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("err: %v", err) - } - - pl := &Listener{Listener: l} - - go func() { - conn, err := net.Dial("tcp", pl.Addr().String()) - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - // Write out the header! - header := "PROXY TCP4 10.1.1.1 20.2.2.2 1000 2000\r\n" - conn.Write([]byte(header)) - - conn.Write([]byte("ping")) - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err != nil { - t.Fatalf("err: %v", err) - } - if !bytes.Equal(recv, []byte("pong")) { - t.Fatalf("bad: %v", recv) - } - }() - - conn, err := pl.Accept() - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err != nil { - t.Fatalf("err: %v", err) - } - if !bytes.Equal(recv, []byte("ping")) { - t.Fatalf("bad: %v", recv) - } - - if _, err := conn.Write([]byte("pong")); err != nil { - t.Fatalf("err: %v", err) - } - - // Check the remote addr - addr := conn.RemoteAddr().(*net.TCPAddr) - if addr.IP.String() != "10.1.1.1" { - t.Fatalf("bad: %v", addr) - } - if addr.Port != 1000 { - t.Fatalf("bad: %v", addr) - } -} - -func TestParse_ipv6(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("err: %v", err) - } - - pl := &Listener{Listener: l} - - go func() { - conn, err := net.Dial("tcp", pl.Addr().String()) - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - // Write out the header! - header := "PROXY TCP6 ffff::ffff ffff::ffff 1000 2000\r\n" - conn.Write([]byte(header)) - - conn.Write([]byte("ping")) - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err != nil { - t.Fatalf("err: %v", err) - } - if !bytes.Equal(recv, []byte("pong")) { - t.Fatalf("bad: %v", recv) - } - }() - - conn, err := pl.Accept() - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err != nil { - t.Fatalf("err: %v", err) - } - if !bytes.Equal(recv, []byte("ping")) { - t.Fatalf("bad: %v", recv) - } - - if _, err := conn.Write([]byte("pong")); err != nil { - t.Fatalf("err: %v", err) - } - - // Check the remote addr - addr := conn.RemoteAddr().(*net.TCPAddr) - if addr.IP.String() != "ffff::ffff" { - t.Fatalf("bad: %v", addr) - } - if addr.Port != 1000 { - t.Fatalf("bad: %v", addr) - } -} - -func TestParse_BadHeader(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("err: %v", err) - } - - pl := &Listener{Listener: l} - - go func() { - conn, err := net.Dial("tcp", pl.Addr().String()) - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - // Write out the header! - header := "PROXY TCP4 what 127.0.0.1 1000 2000\r\n" - conn.Write([]byte(header)) - - conn.Write([]byte("ping")) - - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err == nil { - t.Fatalf("err: %v", err) - } - }() - - conn, err := pl.Accept() - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - // Check the remote addr, should be the local addr - addr := conn.RemoteAddr().(*net.TCPAddr) - if addr.IP.String() != "127.0.0.1" { - t.Fatalf("bad: %v", addr) - } - - // Read should fail - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err == nil { - t.Fatalf("err: %v", err) - } -} - -func TestParse_ipv4_checkfunc(t *testing.T) { - checkAddr = goodAddr - testParse_ipv4_checkfunc(t) - checkAddr = badAddr - testParse_ipv4_checkfunc(t) - checkAddr = errAddr - testParse_ipv4_checkfunc(t) -} - -func testParse_ipv4_checkfunc(t *testing.T) { - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("err: %v", err) - } - - checkFunc := func(addr net.Addr) (bool, error) { - tcpAddr := addr.(*net.TCPAddr) - if tcpAddr.IP.String() == checkAddr { - return true, nil - } - return false, nil - } - - pl := &Listener{Listener: l, SourceCheck: checkFunc} - - go func() { - conn, err := net.Dial("tcp", pl.Addr().String()) - if err != nil { - t.Fatalf("err: %v", err) - } - defer conn.Close() - - // Write out the header! - header := "PROXY TCP4 10.1.1.1 20.2.2.2 1000 2000\r\n" - conn.Write([]byte(header)) - - conn.Write([]byte("ping")) - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err != nil { - t.Fatalf("err: %v", err) - } - if !bytes.Equal(recv, []byte("pong")) { - t.Fatalf("bad: %v", recv) - } - }() - - conn, err := pl.Accept() - if err != nil { - if checkAddr == badAddr { - return - } - t.Fatalf("err: %v", err) - } - defer conn.Close() - - recv := make([]byte, 4) - _, err = conn.Read(recv) - if err != nil { - t.Fatalf("err: %v", err) - } - if !bytes.Equal(recv, []byte("ping")) { - t.Fatalf("bad: %v", recv) - } - - if _, err := conn.Write([]byte("pong")); err != nil { - t.Fatalf("err: %v", err) - } - - // Check the remote addr - addr := conn.RemoteAddr().(*net.TCPAddr) - switch checkAddr { - case goodAddr: - if addr.IP.String() != "10.1.1.1" { - t.Fatalf("bad: %v", addr) - } - if addr.Port != 1000 { - t.Fatalf("bad: %v", addr) - } - case badAddr: - if addr.IP.String() != "127.0.0.1" { - t.Fatalf("bad: %v", addr) - } - if addr.Port == 1000 { - t.Fatalf("bad: %v", addr) - } - } -} diff --git a/vendor/github.com/beorn7/perks/quantile/bench_test.go b/vendor/github.com/beorn7/perks/quantile/bench_test.go deleted file mode 100644 index 0bd0e4e775..0000000000 --- a/vendor/github.com/beorn7/perks/quantile/bench_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package quantile - -import ( - "testing" -) - -func BenchmarkInsertTargeted(b *testing.B) { - b.ReportAllocs() - - s := NewTargeted(Targets) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertTargetedSmallEpsilon(b *testing.B) { - s := NewTargeted(TargetsSmallEpsilon) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertBiased(b *testing.B) { - s := NewLowBiased(0.01) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkInsertBiasedSmallEpsilon(b *testing.B) { - s := NewLowBiased(0.0001) - b.ResetTimer() - for i := float64(0); i < float64(b.N); i++ { - s.Insert(i) - } -} - -func BenchmarkQuery(b *testing.B) { - s := NewTargeted(Targets) - for i := float64(0); i < 1e6; i++ { - s.Insert(i) - } - b.ResetTimer() - n := float64(b.N) - for i := float64(0); i < n; i++ { - s.Query(i / n) - } -} - -func BenchmarkQuerySmallEpsilon(b *testing.B) { - s := NewTargeted(TargetsSmallEpsilon) - for i := float64(0); i < 1e6; i++ { - s.Insert(i) - } - b.ResetTimer() - n := float64(b.N) - for i := float64(0); i < n; i++ { - s.Query(i / n) - } -} diff --git a/vendor/github.com/beorn7/perks/quantile/example_test.go b/vendor/github.com/beorn7/perks/quantile/example_test.go deleted file mode 100644 index ab3293aaf2..0000000000 --- a/vendor/github.com/beorn7/perks/quantile/example_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// +build go1.1 - -package quantile_test - -import ( - "bufio" - "fmt" - "log" - "os" - "strconv" - "time" - - "github.com/beorn7/perks/quantile" -) - -func Example_simple() { - ch := make(chan float64) - go sendFloats(ch) - - // Compute the 50th, 90th, and 99th percentile. - q := quantile.NewTargeted(map[float64]float64{ - 0.50: 0.005, - 0.90: 0.001, - 0.99: 0.0001, - }) - for v := range ch { - q.Insert(v) - } - - fmt.Println("perc50:", q.Query(0.50)) - fmt.Println("perc90:", q.Query(0.90)) - fmt.Println("perc99:", q.Query(0.99)) - fmt.Println("count:", q.Count()) - // Output: - // perc50: 5 - // perc90: 16 - // perc99: 223 - // count: 2388 -} - -func Example_mergeMultipleStreams() { - // Scenario: - // We have multiple database shards. On each shard, there is a process - // collecting query response times from the database logs and inserting - // them into a Stream (created via NewTargeted(0.90)), much like the - // Simple example. These processes expose a network interface for us to - // ask them to serialize and send us the results of their - // Stream.Samples so we may Merge and Query them. - // - // NOTES: - // * These sample sets are small, allowing us to get them - // across the network much faster than sending the entire list of data - // points. - // - // * For this to work correctly, we must supply the same quantiles - // a priori the process collecting the samples supplied to NewTargeted, - // even if we do not plan to query them all here. - ch := make(chan quantile.Samples) - getDBQuerySamples(ch) - q := quantile.NewTargeted(map[float64]float64{0.90: 0.001}) - for samples := range ch { - q.Merge(samples) - } - fmt.Println("perc90:", q.Query(0.90)) -} - -func Example_window() { - // Scenario: We want the 90th, 95th, and 99th percentiles for each - // minute. - - ch := make(chan float64) - go sendStreamValues(ch) - - tick := time.NewTicker(1 * time.Minute) - q := quantile.NewTargeted(map[float64]float64{ - 0.90: 0.001, - 0.95: 0.0005, - 0.99: 0.0001, - }) - for { - select { - case t := <-tick.C: - flushToDB(t, q.Samples()) - q.Reset() - case v := <-ch: - q.Insert(v) - } - } -} - -func sendStreamValues(ch chan float64) { - // Use your imagination -} - -func flushToDB(t time.Time, samples quantile.Samples) { - // Use your imagination -} - -// This is a stub for the above example. In reality this would hit the remote -// servers via http or something like it. -func getDBQuerySamples(ch chan quantile.Samples) {} - -func sendFloats(ch chan<- float64) { - f, err := os.Open("exampledata.txt") - if err != nil { - log.Fatal(err) - } - sc := bufio.NewScanner(f) - for sc.Scan() { - b := sc.Bytes() - v, err := strconv.ParseFloat(string(b), 64) - if err != nil { - log.Fatal(err) - } - ch <- v - } - if sc.Err() != nil { - log.Fatal(sc.Err()) - } - close(ch) -} diff --git a/vendor/github.com/beorn7/perks/quantile/stream.go b/vendor/github.com/beorn7/perks/quantile/stream.go index f4cabd6695..d7d14f8eb6 100644 --- a/vendor/github.com/beorn7/perks/quantile/stream.go +++ b/vendor/github.com/beorn7/perks/quantile/stream.go @@ -77,15 +77,20 @@ func NewHighBiased(epsilon float64) *Stream { // is guaranteed to be within (Quantile±Epsilon). // // See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties. -func NewTargeted(targets map[float64]float64) *Stream { +func NewTargeted(targetMap map[float64]float64) *Stream { + // Convert map to slice to avoid slow iterations on a map. + // ƒ is called on the hot path, so converting the map to a slice + // beforehand results in significant CPU savings. + targets := targetMapToSlice(targetMap) + ƒ := func(s *stream, r float64) float64 { var m = math.MaxFloat64 var f float64 - for quantile, epsilon := range targets { - if quantile*s.n <= r { - f = (2 * epsilon * r) / quantile + for _, t := range targets { + if t.quantile*s.n <= r { + f = (2 * t.epsilon * r) / t.quantile } else { - f = (2 * epsilon * (s.n - r)) / (1 - quantile) + f = (2 * t.epsilon * (s.n - r)) / (1 - t.quantile) } if f < m { m = f @@ -96,6 +101,25 @@ func NewTargeted(targets map[float64]float64) *Stream { return newStream(ƒ) } +type target struct { + quantile float64 + epsilon float64 +} + +func targetMapToSlice(targetMap map[float64]float64) []target { + targets := make([]target, 0, len(targetMap)) + + for quantile, epsilon := range targetMap { + t := target{ + quantile: quantile, + epsilon: epsilon, + } + targets = append(targets, t) + } + + return targets +} + // Stream computes quantiles for a stream of float64s. It is not thread-safe by // design. Take care when using across multiple goroutines. type Stream struct { diff --git a/vendor/github.com/beorn7/perks/quantile/stream_test.go b/vendor/github.com/beorn7/perks/quantile/stream_test.go deleted file mode 100644 index 855195097e..0000000000 --- a/vendor/github.com/beorn7/perks/quantile/stream_test.go +++ /dev/null @@ -1,215 +0,0 @@ -package quantile - -import ( - "math" - "math/rand" - "sort" - "testing" -) - -var ( - Targets = map[float64]float64{ - 0.01: 0.001, - 0.10: 0.01, - 0.50: 0.05, - 0.90: 0.01, - 0.99: 0.001, - } - TargetsSmallEpsilon = map[float64]float64{ - 0.01: 0.0001, - 0.10: 0.001, - 0.50: 0.005, - 0.90: 0.001, - 0.99: 0.0001, - } - LowQuantiles = []float64{0.01, 0.1, 0.5} - HighQuantiles = []float64{0.99, 0.9, 0.5} -) - -const RelativeEpsilon = 0.01 - -func verifyPercsWithAbsoluteEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for quantile, epsilon := range Targets { - n := float64(len(a)) - k := int(quantile * n) - if k < 1 { - k = 1 - } - lower := int((quantile - epsilon) * n) - if lower < 1 { - lower = 1 - } - upper := int(math.Ceil((quantile + epsilon) * n)) - if upper > len(a) { - upper = len(a) - } - w, min, max := a[k-1], a[lower-1], a[upper-1] - if g := s.Query(quantile); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", quantile, w, min, max, g) - } - } -} - -func verifyLowPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for _, qu := range LowQuantiles { - n := float64(len(a)) - k := int(qu * n) - - lowerRank := int((1 - RelativeEpsilon) * qu * n) - upperRank := int(math.Ceil((1 + RelativeEpsilon) * qu * n)) - w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] - if g := s.Query(qu); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) - } - } -} - -func verifyHighPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { - sort.Float64s(a) - for _, qu := range HighQuantiles { - n := float64(len(a)) - k := int(qu * n) - - lowerRank := int((1 - (1+RelativeEpsilon)*(1-qu)) * n) - upperRank := int(math.Ceil((1 - (1-RelativeEpsilon)*(1-qu)) * n)) - w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] - if g := s.Query(qu); g < min || g > max { - t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) - } - } -} - -func populateStream(s *Stream) []float64 { - a := make([]float64, 0, 1e5+100) - for i := 0; i < cap(a); i++ { - v := rand.NormFloat64() - // Add 5% asymmetric outliers. - if i%20 == 0 { - v = v*v + 1 - } - s.Insert(v) - a = append(a, v) - } - return a -} - -func TestTargetedQuery(t *testing.T) { - rand.Seed(42) - s := NewTargeted(Targets) - a := populateStream(s) - verifyPercsWithAbsoluteEpsilon(t, a, s) -} - -func TestTargetedQuerySmallSampleSize(t *testing.T) { - rand.Seed(42) - s := NewTargeted(TargetsSmallEpsilon) - a := []float64{1, 2, 3, 4, 5} - for _, v := range a { - s.Insert(v) - } - verifyPercsWithAbsoluteEpsilon(t, a, s) - // If not yet flushed, results should be precise: - if !s.flushed() { - for φ, want := range map[float64]float64{ - 0.01: 1, - 0.10: 1, - 0.50: 3, - 0.90: 5, - 0.99: 5, - } { - if got := s.Query(φ); got != want { - t.Errorf("want %f for φ=%f, got %f", want, φ, got) - } - } - } -} - -func TestLowBiasedQuery(t *testing.T) { - rand.Seed(42) - s := NewLowBiased(RelativeEpsilon) - a := populateStream(s) - verifyLowPercsWithRelativeEpsilon(t, a, s) -} - -func TestHighBiasedQuery(t *testing.T) { - rand.Seed(42) - s := NewHighBiased(RelativeEpsilon) - a := populateStream(s) - verifyHighPercsWithRelativeEpsilon(t, a, s) -} - -// BrokenTestTargetedMerge is broken, see Merge doc comment. -func BrokenTestTargetedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewTargeted(Targets) - s2 := NewTargeted(Targets) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyPercsWithAbsoluteEpsilon(t, a, s1) -} - -// BrokenTestLowBiasedMerge is broken, see Merge doc comment. -func BrokenTestLowBiasedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewLowBiased(RelativeEpsilon) - s2 := NewLowBiased(RelativeEpsilon) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyLowPercsWithRelativeEpsilon(t, a, s2) -} - -// BrokenTestHighBiasedMerge is broken, see Merge doc comment. -func BrokenTestHighBiasedMerge(t *testing.T) { - rand.Seed(42) - s1 := NewHighBiased(RelativeEpsilon) - s2 := NewHighBiased(RelativeEpsilon) - a := populateStream(s1) - a = append(a, populateStream(s2)...) - s1.Merge(s2.Samples()) - verifyHighPercsWithRelativeEpsilon(t, a, s2) -} - -func TestUncompressed(t *testing.T) { - q := NewTargeted(Targets) - for i := 100; i > 0; i-- { - q.Insert(float64(i)) - } - if g := q.Count(); g != 100 { - t.Errorf("want count 100, got %d", g) - } - // Before compression, Query should have 100% accuracy. - for quantile := range Targets { - w := quantile * 100 - if g := q.Query(quantile); g != w { - t.Errorf("want %f, got %f", w, g) - } - } -} - -func TestUncompressedSamples(t *testing.T) { - q := NewTargeted(map[float64]float64{0.99: 0.001}) - for i := 1; i <= 100; i++ { - q.Insert(float64(i)) - } - if g := q.Samples().Len(); g != 100 { - t.Errorf("want count 100, got %d", g) - } -} - -func TestUncompressedOne(t *testing.T) { - q := NewTargeted(map[float64]float64{0.99: 0.01}) - q.Insert(3.14) - if g := q.Query(0.90); g != 3.14 { - t.Error("want PI, got", g) - } -} - -func TestDefaults(t *testing.T) { - if g := NewTargeted(map[float64]float64{0.99: 0.001}).Query(0.99); g != 0 { - t.Errorf("want 0, got %f", g) - } -} diff --git a/vendor/github.com/davecgh/go-spew/spew/common_test.go b/vendor/github.com/davecgh/go-spew/spew/common_test.go deleted file mode 100644 index 0f5ce47dca..0000000000 --- a/vendor/github.com/davecgh/go-spew/spew/common_test.go +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - "reflect" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -// custom type to test Stinger interface on non-pointer receiver. -type stringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with non-pointer receivers. -func (s stringer) String() string { - return "stringer " + string(s) -} - -// custom type to test Stinger interface on pointer receiver. -type pstringer string - -// String implements the Stringer interface for testing invocation of custom -// stringers on types with only pointer receivers. -func (s *pstringer) String() string { - return "stringer " + string(*s) -} - -// xref1 and xref2 are cross referencing structs for testing circular reference -// detection. -type xref1 struct { - ps2 *xref2 -} -type xref2 struct { - ps1 *xref1 -} - -// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular -// reference for testing detection. -type indirCir1 struct { - ps2 *indirCir2 -} -type indirCir2 struct { - ps3 *indirCir3 -} -type indirCir3 struct { - ps1 *indirCir1 -} - -// embed is used to test embedded structures. -type embed struct { - a string -} - -// embedwrap is used to test embedded structures. -type embedwrap struct { - *embed - e *embed -} - -// panicer is used to intentionally cause a panic for testing spew properly -// handles them -type panicer int - -func (p panicer) String() string { - panic("test panic") -} - -// customError is used to test custom error interface invocation. -type customError int - -func (e customError) Error() string { - return fmt.Sprintf("error: %d", int(e)) -} - -// stringizeWants converts a slice of wanted test output into a format suitable -// for a test error message. -func stringizeWants(wants []string) string { - s := "" - for i, want := range wants { - if i > 0 { - s += fmt.Sprintf("want%d: %s", i+1, want) - } else { - s += "want: " + want - } - } - return s -} - -// testFailed returns whether or not a test failed by checking if the result -// of the test is in the slice of wanted strings. -func testFailed(result string, wants []string) bool { - for _, want := range wants { - if result == want { - return false - } - } - return true -} - -type sortableStruct struct { - x int -} - -func (ss sortableStruct) String() string { - return fmt.Sprintf("ss.%d", ss.x) -} - -type unsortableStruct struct { - x int -} - -type sortTestCase struct { - input []reflect.Value - expected []reflect.Value -} - -func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) { - getInterfaces := func(values []reflect.Value) []interface{} { - interfaces := []interface{}{} - for _, v := range values { - interfaces = append(interfaces, v.Interface()) - } - return interfaces - } - - for _, test := range tests { - spew.SortValues(test.input, cs) - // reflect.DeepEqual cannot really make sense of reflect.Value, - // probably because of all the pointer tricks. For instance, - // v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{} - // instead. - input := getInterfaces(test.input) - expected := getInterfaces(test.expected) - if !reflect.DeepEqual(input, expected) { - t.Errorf("Sort mismatch:\n %v != %v", input, expected) - } - } -} - -// TestSortValues ensures the sort functionality for relect.Value based sorting -// works as intended. -func TestSortValues(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - embedA := v(embed{"a"}) - embedB := v(embed{"b"}) - embedC := v(embed{"c"}) - tests := []sortTestCase{ - // No values. - { - []reflect.Value{}, - []reflect.Value{}, - }, - // Bools. - { - []reflect.Value{v(false), v(true), v(false)}, - []reflect.Value{v(false), v(false), v(true)}, - }, - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Uints. - { - []reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))}, - []reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))}, - }, - // Floats. - { - []reflect.Value{v(2.0), v(1.0), v(3.0)}, - []reflect.Value{v(1.0), v(2.0), v(3.0)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // Array - { - []reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})}, - []reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})}, - }, - // Uintptrs. - { - []reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))}, - []reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))}, - }, - // SortableStructs. - { - // Note: not sorted - DisableMethods is set. - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - // Invalid. - { - []reflect.Value{embedB, embedA, embedC}, - []reflect.Value{embedB, embedA, embedC}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithMethods ensures the sort functionality for relect.Value -// based sorting works as intended when using string methods. -func TestSortValuesWithMethods(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - // Note: not sorted - SpewKeys is false. - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: false, SpewKeys: false} - helpTestSortValues(tests, &cs, t) -} - -// TestSortValuesWithSpew ensures the sort functionality for relect.Value -// based sorting works as intended when using spew to stringify keys. -func TestSortValuesWithSpew(t *testing.T) { - v := reflect.ValueOf - - a := v("a") - b := v("b") - c := v("c") - tests := []sortTestCase{ - // Ints. - { - []reflect.Value{v(2), v(1), v(3)}, - []reflect.Value{v(1), v(2), v(3)}, - }, - // Strings. - { - []reflect.Value{b, a, c}, - []reflect.Value{a, b, c}, - }, - // SortableStructs. - { - []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, - []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, - }, - // UnsortableStructs. - { - []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, - []reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})}, - }, - } - cs := spew.ConfigState{DisableMethods: true, SpewKeys: true} - helpTestSortValues(tests, &cs, t) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/dump_test.go b/vendor/github.com/davecgh/go-spew/spew/dump_test.go deleted file mode 100644 index 5aad9c7af0..0000000000 --- a/vendor/github.com/davecgh/go-spew/spew/dump_test.go +++ /dev/null @@ -1,1042 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Array containing bytes -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Slice containing bytes -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// dumpTest is used to describe a test to be performed against the Dump method. -type dumpTest struct { - in interface{} - wants []string -} - -// dumpTests houses all of the tests to be performed against the Dump method. -var dumpTests = make([]dumpTest, 0) - -// addDumpTest is a helper method to append the passed input and desired result -// to dumpTests -func addDumpTest(in interface{}, wants ...string) { - test := dumpTest{in, wants} - dumpTests = append(dumpTests, test) -} - -func addIntDumpTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addUintDumpTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addBoolDumpTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFloatDumpTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addComplexDumpTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addArrayDumpTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" + - vt + ") 2,\n (" + vt + ") 3\n}" - addDumpTest(v, "([3]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[3]"+vt+")()\n") - - // Array containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := [3]pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2sp := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + - ") (len=" + v2i0Len + ") stringer 1,\n (" + v2t + - ") (len=" + v2i1Len + ") stringer 2,\n (" + v2t + - ") (len=" + v2i2Len + ") " + "stringer 3\n}" - v2s := v2sp - if spew.UnsafeDisabled { - v2s = "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + - ") (len=" + v2i0Len + ") \"1\",\n (" + v2t + ") (len=" + - v2i1Len + ") \"2\",\n (" + v2t + ") (len=" + v2i2Len + - ") " + "\"3\"\n}" - } - addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2sp+")\n") - addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2sp+")\n") - addDumpTest(nv2, "(*[3]"+v2t+")()\n") - - // Array containing interfaces. - v3i0 := "one" - v3 := [3]interface{}{v3i0, int(2), uint(3)} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Array containing bytes. - v4 := [34]byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[34]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[34]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addSliceDumpTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - vLen := fmt.Sprintf("%d", len(v)) - vCap := fmt.Sprintf("%d", cap(v)) - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" + - vt + ") 6.28,\n (" + vt + ") 12.56\n}" - addDumpTest(v, "([]"+vt+") "+vs+"\n") - addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*[]"+vt+")()\n") - - // Slice containing type with custom formatter on pointer receiver only. - v2i0 := pstringer("1") - v2i1 := pstringer("2") - v2i2 := pstringer("3") - v2 := []pstringer{v2i0, v2i1, v2i2} - v2i0Len := fmt.Sprintf("%d", len(v2i0)) - v2i1Len := fmt.Sprintf("%d", len(v2i1)) - v2i2Len := fmt.Sprintf("%d", len(v2i2)) - v2Len := fmt.Sprintf("%d", len(v2)) - v2Cap := fmt.Sprintf("%d", cap(v2)) - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.pstringer" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + - v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + - ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + - "stringer 3\n}" - addDumpTest(v2, "([]"+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*[]"+v2t+")()\n") - - // Slice containing interfaces. - v3i0 := "one" - v3 := []interface{}{v3i0, int(2), uint(3), nil} - v3i0Len := fmt.Sprintf("%d", len(v3i0)) - v3Len := fmt.Sprintf("%d", len(v3)) - v3Cap := fmt.Sprintf("%d", cap(v3)) - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + - "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + - v3t4 + ") 3,\n (" + v3t5 + ") \n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Slice containing bytes. - v4 := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - v4Len := fmt.Sprintf("%d", len(v4)) - v4Cap := fmt.Sprintf("%d", cap(v4)) - nv4 := (*[]byte)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]uint8" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + - " |............... |\n" + - " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + - " |!\"#$%&'()*+,-./0|\n" + - " 00000020 31 32 " + - " |12|\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") - - // Nil slice. - v5 := []int(nil) - nv5 := (*[]int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "[]int" - v5s := "" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") - addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") - addDumpTest(nv5, "(*"+v5t+")()\n") -} - -func addStringDumpTests() { - // Standard string. - v := "test" - vLen := fmt.Sprintf("%d", len(v)) - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "(len=" + vLen + ") \"test\"" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addInterfaceDumpTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addMapDumpTests() { - // Map with string keys and int vals. - k := "one" - kk := "two" - m := map[string]int{k: 1, kk: 2} - klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up - kkLen := fmt.Sprintf("%d", len(kk)) - mLen := fmt.Sprintf("%d", len(m)) - nilMap := map[string]int(nil) - nm := (*map[string]int)(nil) - pm := &m - mAddr := fmt.Sprintf("%p", pm) - pmAddr := fmt.Sprintf("%p", &pm) - mt := "map[string]int" - mt1 := "string" - mt2 := "int" - ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " + - "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen + - ") \"two\": (" + mt2 + ") 2\n}" - ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " + - "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen + - ") \"one\": (" + mt2 + ") 1\n}" - addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n") - addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n", - "(*"+mt+")("+mAddr+")("+ms2+")\n") - addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n", - "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n") - addDumpTest(nm, "(*"+mt+")()\n") - addDumpTest(nilMap, "("+mt+") \n") - - // Map with custom formatter type on pointer receiver only keys and vals. - k2 := pstringer("one") - v2 := pstringer("1") - m2 := map[pstringer]pstringer{k2: v2} - k2Len := fmt.Sprintf("%d", len(k2)) - v2Len := fmt.Sprintf("%d", len(v2)) - m2Len := fmt.Sprintf("%d", len(m2)) - nilMap2 := map[pstringer]pstringer(nil) - nm2 := (*map[pstringer]pstringer)(nil) - pm2 := &m2 - m2Addr := fmt.Sprintf("%p", pm2) - pm2Addr := fmt.Sprintf("%p", &pm2) - m2t := "map[spew_test.pstringer]spew_test.pstringer" - m2t1 := "spew_test.pstringer" - m2t2 := "spew_test.pstringer" - m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " + - "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}" - if spew.UnsafeDisabled { - m2s = "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + - ") " + "\"one\": (" + m2t2 + ") (len=" + v2Len + - ") \"1\"\n}" - } - addDumpTest(m2, "("+m2t+") "+m2s+"\n") - addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n") - addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n") - addDumpTest(nm2, "(*"+m2t+")()\n") - addDumpTest(nilMap2, "("+m2t+") \n") - - // Map with interface keys and values. - k3 := "one" - k3Len := fmt.Sprintf("%d", len(k3)) - m3 := map[interface{}]interface{}{k3: 1} - m3Len := fmt.Sprintf("%d", len(m3)) - nilMap3 := map[interface{}]interface{}(nil) - nm3 := (*map[interface{}]interface{})(nil) - pm3 := &m3 - m3Addr := fmt.Sprintf("%p", pm3) - pm3Addr := fmt.Sprintf("%p", &pm3) - m3t := "map[interface {}]interface {}" - m3t1 := "string" - m3t2 := "int" - m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " + - "\"one\": (" + m3t2 + ") 1\n}" - addDumpTest(m3, "("+m3t+") "+m3s+"\n") - addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n") - addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n") - addDumpTest(nm3, "(*"+m3t+")()\n") - addDumpTest(nilMap3, "("+m3t+") \n") - - // Map with nil interface value. - k4 := "nil" - k4Len := fmt.Sprintf("%d", len(k4)) - m4 := map[string]interface{}{k4: nil} - m4Len := fmt.Sprintf("%d", len(m4)) - nilMap4 := map[string]interface{}(nil) - nm4 := (*map[string]interface{})(nil) - pm4 := &m4 - m4Addr := fmt.Sprintf("%p", pm4) - pm4Addr := fmt.Sprintf("%p", &pm4) - m4t := "map[string]interface {}" - m4t1 := "string" - m4t2 := "interface {}" - m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" + - " \"nil\": (" + m4t2 + ") \n}" - addDumpTest(m4, "("+m4t+") "+m4s+"\n") - addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n") - addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n") - addDumpTest(nm4, "(*"+m4t+")()\n") - addDumpTest(nilMap4, "("+m4t+") \n") -} - -func addStructDumpTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" + - v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 + - ") (len=5) stringer test2\n}" - v3sp := v3s - if spew.UnsafeDisabled { - v3s = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" + - v3t2 + ") (len=5) \"test2\"\n}" - v3sp = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" + - v3t2 + ") (len=5) stringer test2\n}" - } - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3sp+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3sp+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - eLen := fmt.Sprintf("%d", len("embedstr")) - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 + - ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 + - ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" + - " \"embedstr\"\n })\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") - addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") - addDumpTest(nv4, "(*"+v4t+")()\n") -} - -func addUintptrDumpTests() { - // Null pointer. - v := uintptr(0) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - nv2 := (*uintptr)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") -} - -func addUnsafePointerDumpTests() { - // Null pointer. - v := unsafe.Pointer(uintptr(0)) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addChanDumpTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") -} - -func addFuncDumpTests() { - // Function with no params and no returns. - v := addIntDumpTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") - - // Function with param and no returns. - v2 := TestDump - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") - addDumpTest(nv2, "(*"+v2t+")()\n") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") - addDumpTest(nv3, "(*"+v3t+")()\n") -} - -func addCircularDumpTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" + - vAddr + ")()\n })\n}" - vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")()\n}" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n") - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr + - ")()\n })\n })\n}" - v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + - ")(" + v2Addr + ")()\n })\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n") - addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n") - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr + - ")()\n })\n })\n })\n}" - v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + - ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + - ")()\n })\n })\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n") - addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n") - addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n") -} - -func addPanicDumpTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -func addErrorDumpTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addDumpTest(v, "("+vt+") "+vs+"\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") - addDumpTest(nv, "(*"+vt+")()\n") -} - -// TestDump executes all of the tests described by dumpTests. -func TestDump(t *testing.T) { - // Setup tests. - addIntDumpTests() - addUintDumpTests() - addBoolDumpTests() - addFloatDumpTests() - addComplexDumpTests() - addArrayDumpTests() - addSliceDumpTests() - addStringDumpTests() - addInterfaceDumpTests() - addMapDumpTests() - addStructDumpTests() - addUintptrDumpTests() - addUnsafePointerDumpTests() - addChanDumpTests() - addFuncDumpTests() - addCircularDumpTests() - addPanicDumpTests() - addErrorDumpTests() - addCgoDumpTests() - - t.Logf("Running %d tests", len(dumpTests)) - for i, test := range dumpTests { - buf := new(bytes.Buffer) - spew.Fdump(buf, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants)) - continue - } - } -} - -func TestDumpSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := "(map[int]string) (len=3) {\n(int) 1: (string) (len=1) " + - "\"1\",\n(int) 2: (string) (len=1) \"2\",\n(int) 3: (string) " + - "(len=1) \"3\"\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = "(map[spew_test.stringer]int) (len=3) {\n" + - "(spew_test.stringer) (len=1) stringer 1: (int) 1,\n" + - "(spew_test.stringer) (len=1) stringer 2: (int) 2,\n" + - "(spew_test.stringer) (len=1) stringer 3: (int) 3\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = "(map[spew_test.pstringer]int) (len=3) {\n" + - "(spew_test.pstringer) (len=1) stringer 1: (int) 1,\n" + - "(spew_test.pstringer) (len=1) stringer 2: (int) 2,\n" + - "(spew_test.pstringer) (len=1) stringer 3: (int) 3\n" + - "}\n" - if spew.UnsafeDisabled { - expected = "(map[spew_test.pstringer]int) (len=3) {\n" + - "(spew_test.pstringer) (len=1) \"1\": (int) 1,\n" + - "(spew_test.pstringer) (len=1) \"2\": (int) 2,\n" + - "(spew_test.pstringer) (len=1) \"3\": (int) 3\n" + - "}\n" - } - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - - s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = "(map[spew_test.customError]int) (len=3) {\n" + - "(spew_test.customError) error: 1: (int) 1,\n" + - "(spew_test.customError) error: 2: (int) 2,\n" + - "(spew_test.customError) error: 3: (int) 3\n" + - "}\n" - if s != expected { - t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) - } - -} diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go deleted file mode 100644 index 6ab180809a..0000000000 --- a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) 2013-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when both cgo is supported and "-tags testcgo" is added to the go test -// command line. This means the cgo tests are only added (and hence run) when -// specifially requested. This configuration is used because spew itself -// does not require cgo to run even though it does handle certain cgo types -// specially. Rather than forcing all clients to require cgo and an external -// C compiler just to run the tests, this scheme makes them optional. -// +build cgo,testcgo - -package spew_test - -import ( - "fmt" - - "github.com/davecgh/go-spew/spew/testdata" -) - -func addCgoDumpTests() { - // C char pointer. - v := testdata.GetCgoCharPointer() - nv := testdata.GetCgoNullCharPointer() - pv := &v - vcAddr := fmt.Sprintf("%p", v) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "*testdata._Ctype_char" - vs := "116" - addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n") - addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n") - addDumpTest(nv, "("+vt+")()\n") - - // C char array. - v2, v2l, v2c := testdata.GetCgoCharArray() - v2Len := fmt.Sprintf("%d", v2l) - v2Cap := fmt.Sprintf("%d", v2c) - v2t := "[6]testdata._Ctype_char" - v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " + - "{\n 00000000 74 65 73 74 32 00 " + - " |test2.|\n}" - addDumpTest(v2, "("+v2t+") "+v2s+"\n") - - // C unsigned char array. - v3, v3l, v3c := testdata.GetCgoUnsignedCharArray() - v3Len := fmt.Sprintf("%d", v3l) - v3Cap := fmt.Sprintf("%d", v3c) - v3t := "[6]testdata._Ctype_unsignedchar" - v3t2 := "[6]testdata._Ctype_uchar" - v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " + - "{\n 00000000 74 65 73 74 33 00 " + - " |test3.|\n}" - addDumpTest(v3, "("+v3t+") "+v3s+"\n", "("+v3t2+") "+v3s+"\n") - - // C signed char array. - v4, v4l, v4c := testdata.GetCgoSignedCharArray() - v4Len := fmt.Sprintf("%d", v4l) - v4Cap := fmt.Sprintf("%d", v4c) - v4t := "[6]testdata._Ctype_schar" - v4t2 := "testdata._Ctype_schar" - v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + - "{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 + - ") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 + - ") 0\n}" - addDumpTest(v4, "("+v4t+") "+v4s+"\n") - - // C uint8_t array. - v5, v5l, v5c := testdata.GetCgoUint8tArray() - v5Len := fmt.Sprintf("%d", v5l) - v5Cap := fmt.Sprintf("%d", v5c) - v5t := "[6]testdata._Ctype_uint8_t" - v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " + - "{\n 00000000 74 65 73 74 35 00 " + - " |test5.|\n}" - addDumpTest(v5, "("+v5t+") "+v5s+"\n") - - // C typedefed unsigned char array. - v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray() - v6Len := fmt.Sprintf("%d", v6l) - v6Cap := fmt.Sprintf("%d", v6c) - v6t := "[6]testdata._Ctype_custom_uchar_t" - v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " + - "{\n 00000000 74 65 73 74 36 00 " + - " |test6.|\n}" - addDumpTest(v6, "("+v6t+") "+v6s+"\n") -} diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go deleted file mode 100644 index 52a0971fb3..0000000000 --- a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2013 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when either cgo is not supported or "-tags testcgo" is not added to the go -// test command line. This file intentionally does not setup any cgo tests in -// this scenario. -// +build !cgo !testcgo - -package spew_test - -func addCgoDumpTests() { - // Don't add any tests for cgo since this file is only compiled when - // there should not be any cgo tests. -} diff --git a/vendor/github.com/davecgh/go-spew/spew/example_test.go b/vendor/github.com/davecgh/go-spew/spew/example_test.go deleted file mode 100644 index c6ec8c6d59..0000000000 --- a/vendor/github.com/davecgh/go-spew/spew/example_test.go +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "fmt" - - "github.com/davecgh/go-spew/spew" -) - -type Flag int - -const ( - flagOne Flag = iota - flagTwo -) - -var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", -} - -func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) -} - -type Bar struct { - data uintptr -} - -type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} -} - -// This example demonstrates how to use Dump to dump variables to stdout. -func ExampleDump() { - // The following package level declarations are assumed for this example: - /* - type Flag int - - const ( - flagOne Flag = iota - flagTwo - ) - - var flagStrings = map[Flag]string{ - flagOne: "flagOne", - flagTwo: "flagTwo", - } - - func (f Flag) String() string { - if s, ok := flagStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown flag (%d)", int(f)) - } - - type Bar struct { - data uintptr - } - - type Foo struct { - unexportedField Bar - ExportedField map[interface{}]interface{} - } - */ - - // Setup some sample data structures for the example. - bar := Bar{uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - f := Flag(5) - b := []byte{ - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, - 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, - 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, - 0x31, 0x32, - } - - // Dump! - spew.Dump(s1, f, b) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Flag) Unknown flag (5) - // ([]uint8) (len=34 cap=34) { - // 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - // 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - // 00000020 31 32 |12| - // } - // -} - -// This example demonstrates how to use Printf to display a variable with a -// format string and inline formatting. -func ExamplePrintf() { - // Create a double pointer to a uint 8. - ui8 := uint8(5) - pui8 := &ui8 - ppui8 := &pui8 - - // Create a circular data type. - type circular struct { - ui8 uint8 - c *circular - } - c := circular{ui8: 1} - c.c = &c - - // Print! - spew.Printf("ppui8: %v\n", ppui8) - spew.Printf("circular: %v\n", c) - - // Output: - // ppui8: <**>5 - // circular: {1 <*>{1 <*>}} -} - -// This example demonstrates how to use a ConfigState. -func ExampleConfigState() { - // Modify the indent level of the ConfigState only. The global - // configuration is not modified. - scs := spew.ConfigState{Indent: "\t"} - - // Output using the ConfigState instance. - v := map[string]int{"one": 1} - scs.Printf("v: %v\n", v) - scs.Dump(v) - - // Output: - // v: map[one:1] - // (map[string]int) (len=1) { - // (string) (len=3) "one": (int) 1 - // } -} - -// This example demonstrates how to use ConfigState.Dump to dump variables to -// stdout -func ExampleConfigState_Dump() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances with different indentation. - scs := spew.ConfigState{Indent: "\t"} - scs2 := spew.ConfigState{Indent: " "} - - // Setup some sample data structures for the example. - bar := Bar{uintptr(0)} - s1 := Foo{bar, map[interface{}]interface{}{"one": true}} - - // Dump using the ConfigState instances. - scs.Dump(s1) - scs2.Dump(s1) - - // Output: - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // (spew_test.Foo) { - // unexportedField: (spew_test.Bar) { - // data: (uintptr) - // }, - // ExportedField: (map[interface {}]interface {}) (len=1) { - // (string) (len=3) "one": (bool) true - // } - // } - // -} - -// This example demonstrates how to use ConfigState.Printf to display a variable -// with a format string and inline formatting. -func ExampleConfigState_Printf() { - // See the top-level Dump example for details on the types used in this - // example. - - // Create two ConfigState instances and modify the method handling of the - // first ConfigState only. - scs := spew.NewDefaultConfig() - scs2 := spew.NewDefaultConfig() - scs.DisableMethods = true - - // Alternatively - // scs := spew.ConfigState{Indent: " ", DisableMethods: true} - // scs2 := spew.ConfigState{Indent: " "} - - // This is of type Flag which implements a Stringer and has raw value 1. - f := flagTwo - - // Dump using the ConfigState instances. - scs.Printf("f: %v\n", f) - scs2.Printf("f: %v\n", f) - - // Output: - // f: 1 - // f: flagTwo -} diff --git a/vendor/github.com/davecgh/go-spew/spew/format_test.go b/vendor/github.com/davecgh/go-spew/spew/format_test.go deleted file mode 100644 index f9b93abe86..0000000000 --- a/vendor/github.com/davecgh/go-spew/spew/format_test.go +++ /dev/null @@ -1,1558 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Test Summary: -NOTE: For each test, a nil pointer, a single pointer and double pointer to the -base test element are also tested to ensure proper indirection across all types. - -- Max int8, int16, int32, int64, int -- Max uint8, uint16, uint32, uint64, uint -- Boolean true and false -- Standard complex64 and complex128 -- Array containing standard ints -- Array containing type with custom formatter on pointer receiver only -- Array containing interfaces -- Slice containing standard float32 values -- Slice containing type with custom formatter on pointer receiver only -- Slice containing interfaces -- Nil slice -- Standard string -- Nil interface -- Sub-interface -- Map with string keys and int vals -- Map with custom formatter type on pointer receiver only keys and vals -- Map with interface keys and values -- Map with nil interface value -- Struct with primitives -- Struct that contains another struct -- Struct that contains custom type with Stringer pointer interface via both - exported and unexported fields -- Struct that contains embedded struct and field to same struct -- Uintptr to 0 (null pointer) -- Uintptr address of real variable -- Unsafe.Pointer to 0 (null pointer) -- Unsafe.Pointer to address of real variable -- Nil channel -- Standard int channel -- Function with no params and no returns -- Function with param and no returns -- Function with multiple params and multiple returns -- Struct that is circular through self referencing -- Structs that are circular through cross referencing -- Structs that are indirectly circular -- Type that panics in its Stringer interface -- Type that has a custom Error interface -- %x passthrough with uint -- %#x passthrough with uint -- %f passthrough with precision -- %f passthrough with width and precision -- %d passthrough with width -- %q passthrough with string -*/ - -package spew_test - -import ( - "bytes" - "fmt" - "testing" - "unsafe" - - "github.com/davecgh/go-spew/spew" -) - -// formatterTest is used to describe a test to be performed against NewFormatter. -type formatterTest struct { - format string - in interface{} - wants []string -} - -// formatterTests houses all of the tests to be performed against NewFormatter. -var formatterTests = make([]formatterTest, 0) - -// addFormatterTest is a helper method to append the passed input and desired -// result to formatterTests. -func addFormatterTest(format string, in interface{}, wants ...string) { - test := formatterTest{format, in, wants} - formatterTests = append(formatterTests, test) -} - -func addIntFormatterTests() { - // Max int8. - v := int8(127) - nv := (*int8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "int8" - vs := "127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max int16. - v2 := int16(32767) - nv2 := (*int16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "int16" - v2s := "32767" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max int32. - v3 := int32(2147483647) - nv3 := (*int32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "int32" - v3s := "2147483647" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max int64. - v4 := int64(9223372036854775807) - nv4 := (*int64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "int64" - v4s := "9223372036854775807" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max int. - v5 := int(2147483647) - nv5 := (*int)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "int" - v5s := "2147483647" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"") -} - -func addUintFormatterTests() { - // Max uint8. - v := uint8(255) - nv := (*uint8)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uint8" - vs := "255" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Max uint16. - v2 := uint16(65535) - nv2 := (*uint16)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Max uint32. - v3 := uint32(4294967295) - nv3 := (*uint32)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "uint32" - v3s := "4294967295" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - - // Max uint64. - v4 := uint64(18446744073709551615) - nv4 := (*uint64)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "uint64" - v4s := "18446744073709551615" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") - - // Max uint. - v5 := uint(4294967295) - nv5 := (*uint)(nil) - pv5 := &v5 - v5Addr := fmt.Sprintf("%p", pv5) - pv5Addr := fmt.Sprintf("%p", &pv5) - v5t := "uint" - v5s := "4294967295" - addFormatterTest("%v", v5, v5s) - addFormatterTest("%v", pv5, "<*>"+v5s) - addFormatterTest("%v", &pv5, "<**>"+v5s) - addFormatterTest("%v", nv5, "") - addFormatterTest("%+v", v5, v5s) - addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) - addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%+v", nv5, "") - addFormatterTest("%#v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) - addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") - addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) - addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) - addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) - addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") -} - -func addBoolFormatterTests() { - // Boolean true. - v := bool(true) - nv := (*bool)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "bool" - vs := "true" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Boolean false. - v2 := bool(false) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "bool" - v2s := "false" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFloatFormatterTests() { - // Standard float32. - v := float32(3.1415) - nv := (*float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "float32" - vs := "3.1415" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard float64. - v2 := float64(3.1415926) - nv2 := (*float64)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "float64" - v2s := "3.1415926" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addComplexFormatterTests() { - // Standard complex64. - v := complex(float32(6), -2) - nv := (*complex64)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "complex64" - vs := "(6-2i)" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Standard complex128. - v2 := complex(float64(-6), 2) - nv2 := (*complex128)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "complex128" - v2s := "(-6+2i)" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") -} - -func addArrayFormatterTests() { - // Array containing standard ints. - v := [3]int{1, 2, 3} - nv := (*[3]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[3]int" - vs := "[1 2 3]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Array containing type with custom formatter on pointer receiver only. - v2 := [3]pstringer{"1", "2", "3"} - nv2 := (*[3]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[3]spew_test.pstringer" - v2sp := "[stringer 1 stringer 2 stringer 3]" - v2s := v2sp - if spew.UnsafeDisabled { - v2s = "[1 2 3]" - } - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2sp) - addFormatterTest("%v", &pv2, "<**>"+v2sp) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2sp) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2sp) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2sp) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2sp) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2sp) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2sp) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Array containing interfaces. - v3 := [3]interface{}{"one", int(2), uint(3)} - nv3 := (*[3]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[3]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3s := "[one 2 3]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addSliceFormatterTests() { - // Slice containing standard float32 values. - v := []float32{3.14, 6.28, 12.56} - nv := (*[]float32)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "[]float32" - vs := "[3.14 6.28 12.56]" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Slice containing type with custom formatter on pointer receiver only. - v2 := []pstringer{"1", "2", "3"} - nv2 := (*[]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "[]spew_test.pstringer" - v2s := "[stringer 1 stringer 2 stringer 3]" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Slice containing interfaces. - v3 := []interface{}{"one", int(2), uint(3), nil} - nv3 := (*[]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "[]interface {}" - v3t2 := "string" - v3t3 := "int" - v3t4 := "uint" - v3t5 := "interface {}" - v3s := "[one 2 3 ]" - v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 + - ")]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Nil slice. - var v4 []int - nv4 := (*[]int)(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "[]int" - v4s := "" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStringFormatterTests() { - // Standard string. - v := "test" - nv := (*string)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "string" - vs := "test" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addInterfaceFormatterTests() { - // Nil interface. - var v interface{} - nv := (*interface{})(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "interface {}" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Sub-interface. - v2 := interface{}(uint16(65535)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uint16" - v2s := "65535" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addMapFormatterTests() { - // Map with string keys and int vals. - v := map[string]int{"one": 1, "two": 2} - nilMap := map[string]int(nil) - nv := (*map[string]int)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "map[string]int" - vs := "map[one:1 two:2]" - vs2 := "map[two:2 one:1]" - addFormatterTest("%v", v, vs, vs2) - addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs, - "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nilMap, "") - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2) - addFormatterTest("%#v", nilMap, "("+vt+")"+"") - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs, - "(*"+vt+")("+vAddr+")"+vs2) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs, - "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%#+v", nilMap, "("+vt+")"+"") - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Map with custom formatter type on pointer receiver only keys and vals. - v2 := map[pstringer]pstringer{"one": "1"} - nv2 := (*map[pstringer]pstringer)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "map[spew_test.pstringer]spew_test.pstringer" - v2s := "map[stringer one:stringer 1]" - if spew.UnsafeDisabled { - v2s = "map[one:1]" - } - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Map with interface keys and values. - v3 := map[interface{}]interface{}{"one": 1} - nv3 := (*map[interface{}]interface{})(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "map[interface {}]interface {}" - v3t1 := "string" - v3t2 := "int" - v3s := "map[one:1]" - v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Map with nil interface value - v4 := map[string]interface{}{"nil": nil} - nv4 := (*map[string]interface{})(nil) - pv4 := &v4 - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "map[string]interface {}" - v4t1 := "interface {}" - v4s := "map[nil:]" - v4s2 := "map[nil:(" + v4t1 + ")]" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addStructFormatterTests() { - // Struct with primitives. - type s1 struct { - a int8 - b uint8 - } - v := s1{127, 255} - nv := (*s1)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.s1" - vt2 := "int8" - vt3 := "uint8" - vs := "{127 255}" - vs2 := "{a:127 b:255}" - vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs2) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs3) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs3) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs3) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Struct that contains another struct. - type s2 struct { - s1 s1 - b bool - } - v2 := s2{s1{127, 255}, true} - nv2 := (*s2)(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.s2" - v2t2 := "spew_test.s1" - v2t3 := "int8" - v2t4 := "uint8" - v2t5 := "bool" - v2s := "{{127 255} true}" - v2s2 := "{s1:{a:127 b:255} b:true}" - v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" + - v2t5 + ")true}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s2) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Struct that contains custom type with Stringer pointer interface via both - // exported and unexported fields. - type s3 struct { - s pstringer - S pstringer - } - v3 := s3{"test", "test2"} - nv3 := (*s3)(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.s3" - v3t2 := "spew_test.pstringer" - v3s := "{stringer test stringer test2}" - v3sp := v3s - v3s2 := "{s:stringer test S:stringer test2}" - v3s2p := v3s2 - v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}" - v3s3p := v3s3 - if spew.UnsafeDisabled { - v3s = "{test test2}" - v3sp = "{test stringer test2}" - v3s2 = "{s:test S:test2}" - v3s2p = "{s:test S:stringer test2}" - v3s3 = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")test2}" - v3s3p = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")stringer test2}" - } - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3sp) - addFormatterTest("%v", &pv3, "<**>"+v3sp) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s2) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2p) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2p) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3p) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3p) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3p) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3p) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") - - // Struct that contains embedded struct and field to same struct. - e := embed{"embedstr"} - v4 := embedwrap{embed: &e, e: &e} - nv4 := (*embedwrap)(nil) - pv4 := &v4 - eAddr := fmt.Sprintf("%p", &e) - v4Addr := fmt.Sprintf("%p", pv4) - pv4Addr := fmt.Sprintf("%p", &pv4) - v4t := "spew_test.embedwrap" - v4t2 := "spew_test.embed" - v4t3 := "string" - v4s := "{<*>{embedstr} <*>{embedstr}}" - v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr + - "){a:embedstr}}" - v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 + - "){a:(" + v4t3 + ")embedstr}}" - v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + - ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}" - addFormatterTest("%v", v4, v4s) - addFormatterTest("%v", pv4, "<*>"+v4s) - addFormatterTest("%v", &pv4, "<**>"+v4s) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%+v", v4, v4s2) - addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2) - addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2) - addFormatterTest("%+v", nv4, "") - addFormatterTest("%#v", v4, "("+v4t+")"+v4s3) - addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3) - addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3) - addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") - addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4) - addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4) - addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4) - addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") -} - -func addUintptrFormatterTests() { - // Null pointer. - v := uintptr(0) - nv := (*uintptr)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "uintptr" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := uintptr(unsafe.Pointer(&i)) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "uintptr" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addUnsafePointerFormatterTests() { - // Null pointer. - v := unsafe.Pointer(uintptr(0)) - nv := (*unsafe.Pointer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "unsafe.Pointer" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Address of real variable. - i := 1 - v2 := unsafe.Pointer(&i) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "unsafe.Pointer" - v2s := fmt.Sprintf("%p", &i) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addChanFormatterTests() { - // Nil channel. - var v chan int - pv := &v - nv := (*chan int)(nil) - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "chan int" - vs := "" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Real channel. - v2 := make(chan int) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "chan int" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) -} - -func addFuncFormatterTests() { - // Function with no params and no returns. - v := addIntFormatterTests - nv := (*func())(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "func()" - vs := fmt.Sprintf("%p", v) - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") - - // Function with param and no returns. - v2 := TestFormatter - nv2 := (*func(*testing.T))(nil) - pv2 := &v2 - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "func(*testing.T)" - v2s := fmt.Sprintf("%p", v2) - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s) - addFormatterTest("%v", &pv2, "<**>"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%+v", v2, v2s) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%+v", nv2, "") - addFormatterTest("%#v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) - addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) - addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") - - // Function with multiple params and multiple returns. - var v3 = func(i int, s string) (b bool, err error) { - return true, nil - } - nv3 := (*func(int, string) (bool, error))(nil) - pv3 := &v3 - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "func(int, string) (bool, error)" - v3s := fmt.Sprintf("%p", v3) - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s) - addFormatterTest("%v", &pv3, "<**>"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%+v", v3, v3s) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%+v", nv3, "") - addFormatterTest("%#v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) - addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) - addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") -} - -func addCircularFormatterTests() { - // Struct that is circular through self referencing. - type circular struct { - c *circular - } - v := circular{nil} - v.c = &v - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.circular" - vs := "{<*>{<*>}}" - vs2 := "{<*>}" - vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")}}" - vs4 := "{c:<*>(" + vAddr + ")}" - vs5 := "{c:(*" + vt + "){c:(*" + vt + ")}}" - vs6 := "{c:(*" + vt + ")}" - vs7 := "{c:(*" + vt + ")(" + vAddr + "){c:(*" + vt + ")(" + vAddr + - ")}}" - vs8 := "{c:(*" + vt + ")(" + vAddr + ")}" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs2) - addFormatterTest("%v", &pv, "<**>"+vs2) - addFormatterTest("%+v", v, vs3) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs4) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs4) - addFormatterTest("%#v", v, "("+vt+")"+vs5) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs6) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs6) - addFormatterTest("%#+v", v, "("+vt+")"+vs7) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs8) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs8) - - // Structs that are circular through cross referencing. - v2 := xref1{nil} - ts2 := xref2{&v2} - v2.ps2 = &ts2 - pv2 := &v2 - ts2Addr := fmt.Sprintf("%p", &ts2) - v2Addr := fmt.Sprintf("%p", pv2) - pv2Addr := fmt.Sprintf("%p", &pv2) - v2t := "spew_test.xref1" - v2t2 := "spew_test.xref2" - v2s := "{<*>{<*>{<*>}}}" - v2s2 := "{<*>{<*>}}" - v2s3 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + "){ps2:<*>(" + - ts2Addr + ")}}}" - v2s4 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + ")}}" - v2s5 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + "){ps2:(*" + v2t2 + - ")}}}" - v2s6 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + ")}}" - v2s7 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + "){ps2:(*" + v2t2 + ")(" + ts2Addr + - ")}}}" - v2s8 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + - ")(" + v2Addr + ")}}" - addFormatterTest("%v", v2, v2s) - addFormatterTest("%v", pv2, "<*>"+v2s2) - addFormatterTest("%v", &pv2, "<**>"+v2s2) - addFormatterTest("%+v", v2, v2s3) - addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s4) - addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s4) - addFormatterTest("%#v", v2, "("+v2t+")"+v2s5) - addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s6) - addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s6) - addFormatterTest("%#+v", v2, "("+v2t+")"+v2s7) - addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s8) - addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s8) - - // Structs that are indirectly circular. - v3 := indirCir1{nil} - tic2 := indirCir2{nil} - tic3 := indirCir3{&v3} - tic2.ps3 = &tic3 - v3.ps2 = &tic2 - pv3 := &v3 - tic2Addr := fmt.Sprintf("%p", &tic2) - tic3Addr := fmt.Sprintf("%p", &tic3) - v3Addr := fmt.Sprintf("%p", pv3) - pv3Addr := fmt.Sprintf("%p", &pv3) - v3t := "spew_test.indirCir1" - v3t2 := "spew_test.indirCir2" - v3t3 := "spew_test.indirCir3" - v3s := "{<*>{<*>{<*>{<*>}}}}" - v3s2 := "{<*>{<*>{<*>}}}" - v3s3 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + "){ps2:<*>(" + tic2Addr + ")}}}}" - v3s4 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + - v3Addr + ")}}}" - v3s5 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - "){ps2:(*" + v3t2 + ")}}}}" - v3s6 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + - ")}}}" - v3s7 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + "){ps2:(*" + v3t2 + - ")(" + tic2Addr + ")}}}}" - v3s8 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + - tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + ")}}}" - addFormatterTest("%v", v3, v3s) - addFormatterTest("%v", pv3, "<*>"+v3s2) - addFormatterTest("%v", &pv3, "<**>"+v3s2) - addFormatterTest("%+v", v3, v3s3) - addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s4) - addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s4) - addFormatterTest("%#v", v3, "("+v3t+")"+v3s5) - addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s6) - addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s6) - addFormatterTest("%#+v", v3, "("+v3t+")"+v3s7) - addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s8) - addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s8) -} - -func addPanicFormatterTests() { - // Type that panics in its Stringer interface. - v := panicer(127) - nv := (*panicer)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.panicer" - vs := "(PANIC=test panic)127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addErrorFormatterTests() { - // Type that has a custom Error interface. - v := customError(127) - nv := (*customError)(nil) - pv := &v - vAddr := fmt.Sprintf("%p", pv) - pvAddr := fmt.Sprintf("%p", &pv) - vt := "spew_test.customError" - vs := "error: 127" - addFormatterTest("%v", v, vs) - addFormatterTest("%v", pv, "<*>"+vs) - addFormatterTest("%v", &pv, "<**>"+vs) - addFormatterTest("%v", nv, "") - addFormatterTest("%+v", v, vs) - addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) - addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%+v", nv, "") - addFormatterTest("%#v", v, "("+vt+")"+vs) - addFormatterTest("%#v", pv, "(*"+vt+")"+vs) - addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) - addFormatterTest("%#v", nv, "(*"+vt+")"+"") - addFormatterTest("%#+v", v, "("+vt+")"+vs) - addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) - addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) - addFormatterTest("%#+v", nv, "(*"+vt+")"+"") -} - -func addPassthroughFormatterTests() { - // %x passthrough with uint. - v := uint(4294967295) - pv := &v - vAddr := fmt.Sprintf("%x", pv) - pvAddr := fmt.Sprintf("%x", &pv) - vs := "ffffffff" - addFormatterTest("%x", v, vs) - addFormatterTest("%x", pv, vAddr) - addFormatterTest("%x", &pv, pvAddr) - - // %#x passthrough with uint. - v2 := int(2147483647) - pv2 := &v2 - v2Addr := fmt.Sprintf("%#x", pv2) - pv2Addr := fmt.Sprintf("%#x", &pv2) - v2s := "0x7fffffff" - addFormatterTest("%#x", v2, v2s) - addFormatterTest("%#x", pv2, v2Addr) - addFormatterTest("%#x", &pv2, pv2Addr) - - // %f passthrough with precision. - addFormatterTest("%.2f", 3.1415, "3.14") - addFormatterTest("%.3f", 3.1415, "3.142") - addFormatterTest("%.4f", 3.1415, "3.1415") - - // %f passthrough with width and precision. - addFormatterTest("%5.2f", 3.1415, " 3.14") - addFormatterTest("%6.3f", 3.1415, " 3.142") - addFormatterTest("%7.4f", 3.1415, " 3.1415") - - // %d passthrough with width. - addFormatterTest("%3d", 127, "127") - addFormatterTest("%4d", 127, " 127") - addFormatterTest("%5d", 127, " 127") - - // %q passthrough with string. - addFormatterTest("%q", "test", "\"test\"") -} - -// TestFormatter executes all of the tests described by formatterTests. -func TestFormatter(t *testing.T) { - // Setup tests. - addIntFormatterTests() - addUintFormatterTests() - addBoolFormatterTests() - addFloatFormatterTests() - addComplexFormatterTests() - addArrayFormatterTests() - addSliceFormatterTests() - addStringFormatterTests() - addInterfaceFormatterTests() - addMapFormatterTests() - addStructFormatterTests() - addUintptrFormatterTests() - addUnsafePointerFormatterTests() - addChanFormatterTests() - addFuncFormatterTests() - addCircularFormatterTests() - addPanicFormatterTests() - addErrorFormatterTests() - addPassthroughFormatterTests() - - t.Logf("Running %d tests", len(formatterTests)) - for i, test := range formatterTests { - buf := new(bytes.Buffer) - spew.Fprintf(buf, test.format, test.in) - s := buf.String() - if testFailed(s, test.wants) { - t.Errorf("Formatter #%d format: %s got: %s %s", i, test.format, s, - stringizeWants(test.wants)) - continue - } - } -} - -type testStruct struct { - x int -} - -func (ts testStruct) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -type testStructP struct { - x int -} - -func (ts *testStructP) String() string { - return fmt.Sprintf("ts.%d", ts.x) -} - -func TestPrintSortedKeys(t *testing.T) { - cfg := spew.ConfigState{SortKeys: true} - s := cfg.Sprint(map[int]string{1: "1", 3: "3", 2: "2"}) - expected := "map[1:1 2:2 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 1:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[stringer]int{"1": 1, "3": 3, "2": 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 2:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) - expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" - if spew.UnsafeDisabled { - expected = "map[1:1 2:2 3:3]" - } - if s != expected { - t.Errorf("Sorted keys mismatch 3:\n %v %v", s, expected) - } - - s = cfg.Sprint(map[testStruct]int{testStruct{1}: 1, testStruct{3}: 3, testStruct{2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 4:\n %v %v", s, expected) - } - - if !spew.UnsafeDisabled { - s = cfg.Sprint(map[testStructP]int{testStructP{1}: 1, testStructP{3}: 3, testStructP{2}: 2}) - expected = "map[ts.1:1 ts.2:2 ts.3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 5:\n %v %v", s, expected) - } - } - - s = cfg.Sprint(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) - expected = "map[error: 1:1 error: 2:2 error: 3:3]" - if s != expected { - t.Errorf("Sorted keys mismatch 6:\n %v %v", s, expected) - } -} diff --git a/vendor/github.com/davecgh/go-spew/spew/internal_test.go b/vendor/github.com/davecgh/go-spew/spew/internal_test.go deleted file mode 100644 index 20a9cfefc6..0000000000 --- a/vendor/github.com/davecgh/go-spew/spew/internal_test.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -This test file is part of the spew package rather than than the spew_test -package because it needs access to internals to properly test certain cases -which are not possible via the public interface since they should never happen. -*/ - -package spew - -import ( - "bytes" - "reflect" - "testing" -) - -// dummyFmtState implements a fake fmt.State to use for testing invalid -// reflect.Value handling. This is necessary because the fmt package catches -// invalid values before invoking the formatter on them. -type dummyFmtState struct { - bytes.Buffer -} - -func (dfs *dummyFmtState) Flag(f int) bool { - if f == int('+') { - return true - } - return false -} - -func (dfs *dummyFmtState) Precision() (int, bool) { - return 0, false -} - -func (dfs *dummyFmtState) Width() (int, bool) { - return 0, false -} - -// TestInvalidReflectValue ensures the dump and formatter code handles an -// invalid reflect value properly. This needs access to internal state since it -// should never happen in real code and therefore can't be tested via the public -// API. -func TestInvalidReflectValue(t *testing.T) { - i := 1 - - // Dump invalid reflect value. - v := new(reflect.Value) - buf := new(bytes.Buffer) - d := dumpState{w: buf, cs: &Config} - d.dump(*v) - s := buf.String() - want := "" - if s != want { - t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want) - } - i++ - - // Formatter invalid reflect value. - buf2 := new(dummyFmtState) - f := formatState{value: *v, cs: &Config, fs: buf2} - f.format(*v) - s = buf2.String() - want = "" - if s != want { - t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want) - } -} - -// SortValues makes the internal sortValues function available to the test -// package. -func SortValues(values []reflect.Value, cs *ConfigState) { - sortValues(values, cs) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go b/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go deleted file mode 100644 index a0c612ec3d..0000000000 --- a/vendor/github.com/davecgh/go-spew/spew/internalunsafe_test.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright (c) 2013-2016 Dave Collins - -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. - -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is not running on Google App Engine, compiled by GopherJS, and -// "-tags safe" is not added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// +build !js,!appengine,!safe,!disableunsafe - -/* -This test file is part of the spew package rather than than the spew_test -package because it needs access to internals to properly test certain cases -which are not possible via the public interface since they should never happen. -*/ - -package spew - -import ( - "bytes" - "reflect" - "testing" - "unsafe" -) - -// changeKind uses unsafe to intentionally change the kind of a reflect.Value to -// the maximum kind value which does not exist. This is needed to test the -// fallback code which punts to the standard fmt library for new types that -// might get added to the language. -func changeKind(v *reflect.Value, readOnly bool) { - rvf := (*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + offsetFlag)) - *rvf = *rvf | ((1< - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew_test - -import ( - "bytes" - "fmt" - "io/ioutil" - "os" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -// spewFunc is used to identify which public function of the spew package or -// ConfigState a test applies to. -type spewFunc int - -const ( - fCSFdump spewFunc = iota - fCSFprint - fCSFprintf - fCSFprintln - fCSPrint - fCSPrintln - fCSSdump - fCSSprint - fCSSprintf - fCSSprintln - fCSErrorf - fCSNewFormatter - fErrorf - fFprint - fFprintln - fPrint - fPrintln - fSdump - fSprint - fSprintf - fSprintln -) - -// Map of spewFunc values to names for pretty printing. -var spewFuncStrings = map[spewFunc]string{ - fCSFdump: "ConfigState.Fdump", - fCSFprint: "ConfigState.Fprint", - fCSFprintf: "ConfigState.Fprintf", - fCSFprintln: "ConfigState.Fprintln", - fCSSdump: "ConfigState.Sdump", - fCSPrint: "ConfigState.Print", - fCSPrintln: "ConfigState.Println", - fCSSprint: "ConfigState.Sprint", - fCSSprintf: "ConfigState.Sprintf", - fCSSprintln: "ConfigState.Sprintln", - fCSErrorf: "ConfigState.Errorf", - fCSNewFormatter: "ConfigState.NewFormatter", - fErrorf: "spew.Errorf", - fFprint: "spew.Fprint", - fFprintln: "spew.Fprintln", - fPrint: "spew.Print", - fPrintln: "spew.Println", - fSdump: "spew.Sdump", - fSprint: "spew.Sprint", - fSprintf: "spew.Sprintf", - fSprintln: "spew.Sprintln", -} - -func (f spewFunc) String() string { - if s, ok := spewFuncStrings[f]; ok { - return s - } - return fmt.Sprintf("Unknown spewFunc (%d)", int(f)) -} - -// spewTest is used to describe a test to be performed against the public -// functions of the spew package or ConfigState. -type spewTest struct { - cs *spew.ConfigState - f spewFunc - format string - in interface{} - want string -} - -// spewTests houses the tests to be performed against the public functions of -// the spew package and ConfigState. -// -// These tests are only intended to ensure the public functions are exercised -// and are intentionally not exhaustive of types. The exhaustive type -// tests are handled in the dump and format tests. -var spewTests []spewTest - -// redirStdout is a helper function to return the standard output from f as a -// byte slice. -func redirStdout(f func()) ([]byte, error) { - tempFile, err := ioutil.TempFile("", "ss-test") - if err != nil { - return nil, err - } - fileName := tempFile.Name() - defer os.Remove(fileName) // Ignore error - - origStdout := os.Stdout - os.Stdout = tempFile - f() - os.Stdout = origStdout - tempFile.Close() - - return ioutil.ReadFile(fileName) -} - -func initSpewTests() { - // Config states with various settings. - scsDefault := spew.NewDefaultConfig() - scsNoMethods := &spew.ConfigState{Indent: " ", DisableMethods: true} - scsNoPmethods := &spew.ConfigState{Indent: " ", DisablePointerMethods: true} - scsMaxDepth := &spew.ConfigState{Indent: " ", MaxDepth: 1} - scsContinue := &spew.ConfigState{Indent: " ", ContinueOnMethod: true} - scsNoPtrAddr := &spew.ConfigState{DisablePointerAddresses: true} - scsNoCap := &spew.ConfigState{DisableCapacities: true} - - // Variables for tests on types which implement Stringer interface with and - // without a pointer receiver. - ts := stringer("test") - tps := pstringer("test") - - type ptrTester struct { - s *struct{} - } - tptr := &ptrTester{s: &struct{}{}} - - // depthTester is used to test max depth handling for structs, array, slices - // and maps. - type depthTester struct { - ic indirCir1 - arr [1]string - slice []string - m map[string]int - } - dt := depthTester{indirCir1{nil}, [1]string{"arr"}, []string{"slice"}, - map[string]int{"one": 1}} - - // Variable for tests on types which implement error interface. - te := customError(10) - - spewTests = []spewTest{ - {scsDefault, fCSFdump, "", int8(127), "(int8) 127\n"}, - {scsDefault, fCSFprint, "", int16(32767), "32767"}, - {scsDefault, fCSFprintf, "%v", int32(2147483647), "2147483647"}, - {scsDefault, fCSFprintln, "", int(2147483647), "2147483647\n"}, - {scsDefault, fCSPrint, "", int64(9223372036854775807), "9223372036854775807"}, - {scsDefault, fCSPrintln, "", uint8(255), "255\n"}, - {scsDefault, fCSSdump, "", uint8(64), "(uint8) 64\n"}, - {scsDefault, fCSSprint, "", complex(1, 2), "(1+2i)"}, - {scsDefault, fCSSprintf, "%v", complex(float32(3), 4), "(3+4i)"}, - {scsDefault, fCSSprintln, "", complex(float64(5), 6), "(5+6i)\n"}, - {scsDefault, fCSErrorf, "%#v", uint16(65535), "(uint16)65535"}, - {scsDefault, fCSNewFormatter, "%v", uint32(4294967295), "4294967295"}, - {scsDefault, fErrorf, "%v", uint64(18446744073709551615), "18446744073709551615"}, - {scsDefault, fFprint, "", float32(3.14), "3.14"}, - {scsDefault, fFprintln, "", float64(6.28), "6.28\n"}, - {scsDefault, fPrint, "", true, "true"}, - {scsDefault, fPrintln, "", false, "false\n"}, - {scsDefault, fSdump, "", complex(-10, -20), "(complex128) (-10-20i)\n"}, - {scsDefault, fSprint, "", complex(-1, -2), "(-1-2i)"}, - {scsDefault, fSprintf, "%v", complex(float32(-3), -4), "(-3-4i)"}, - {scsDefault, fSprintln, "", complex(float64(-5), -6), "(-5-6i)\n"}, - {scsNoMethods, fCSFprint, "", ts, "test"}, - {scsNoMethods, fCSFprint, "", &ts, "<*>test"}, - {scsNoMethods, fCSFprint, "", tps, "test"}, - {scsNoMethods, fCSFprint, "", &tps, "<*>test"}, - {scsNoPmethods, fCSFprint, "", ts, "stringer test"}, - {scsNoPmethods, fCSFprint, "", &ts, "<*>stringer test"}, - {scsNoPmethods, fCSFprint, "", tps, "test"}, - {scsNoPmethods, fCSFprint, "", &tps, "<*>stringer test"}, - {scsMaxDepth, fCSFprint, "", dt, "{{} [] [] map[]}"}, - {scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" + - " ic: (spew_test.indirCir1) {\n \n },\n" + - " arr: ([1]string) (len=1 cap=1) {\n \n },\n" + - " slice: ([]string) (len=1 cap=1) {\n \n },\n" + - " m: (map[string]int) (len=1) {\n \n }\n}\n"}, - {scsContinue, fCSFprint, "", ts, "(stringer test) test"}, - {scsContinue, fCSFdump, "", ts, "(spew_test.stringer) " + - "(len=4) (stringer test) \"test\"\n"}, - {scsContinue, fCSFprint, "", te, "(error: 10) 10"}, - {scsContinue, fCSFdump, "", te, "(spew_test.customError) " + - "(error: 10) 10\n"}, - {scsNoPtrAddr, fCSFprint, "", tptr, "<*>{<*>{}}"}, - {scsNoPtrAddr, fCSSdump, "", tptr, "(*spew_test.ptrTester)({\ns: (*struct {})({\n})\n})\n"}, - {scsNoCap, fCSSdump, "", make([]string, 0, 10), "([]string) {\n}\n"}, - {scsNoCap, fCSSdump, "", make([]string, 1, 10), "([]string) (len=1) {\n(string) \"\"\n}\n"}, - } -} - -// TestSpew executes all of the tests described by spewTests. -func TestSpew(t *testing.T) { - initSpewTests() - - t.Logf("Running %d tests", len(spewTests)) - for i, test := range spewTests { - buf := new(bytes.Buffer) - switch test.f { - case fCSFdump: - test.cs.Fdump(buf, test.in) - - case fCSFprint: - test.cs.Fprint(buf, test.in) - - case fCSFprintf: - test.cs.Fprintf(buf, test.format, test.in) - - case fCSFprintln: - test.cs.Fprintln(buf, test.in) - - case fCSPrint: - b, err := redirStdout(func() { test.cs.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSPrintln: - b, err := redirStdout(func() { test.cs.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fCSSdump: - str := test.cs.Sdump(test.in) - buf.WriteString(str) - - case fCSSprint: - str := test.cs.Sprint(test.in) - buf.WriteString(str) - - case fCSSprintf: - str := test.cs.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fCSSprintln: - str := test.cs.Sprintln(test.in) - buf.WriteString(str) - - case fCSErrorf: - err := test.cs.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fCSNewFormatter: - fmt.Fprintf(buf, test.format, test.cs.NewFormatter(test.in)) - - case fErrorf: - err := spew.Errorf(test.format, test.in) - buf.WriteString(err.Error()) - - case fFprint: - spew.Fprint(buf, test.in) - - case fFprintln: - spew.Fprintln(buf, test.in) - - case fPrint: - b, err := redirStdout(func() { spew.Print(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fPrintln: - b, err := redirStdout(func() { spew.Println(test.in) }) - if err != nil { - t.Errorf("%v #%d %v", test.f, i, err) - continue - } - buf.Write(b) - - case fSdump: - str := spew.Sdump(test.in) - buf.WriteString(str) - - case fSprint: - str := spew.Sprint(test.in) - buf.WriteString(str) - - case fSprintf: - str := spew.Sprintf(test.format, test.in) - buf.WriteString(str) - - case fSprintln: - str := spew.Sprintln(test.in) - buf.WriteString(str) - - default: - t.Errorf("%v #%d unrecognized function", test.f, i) - continue - } - s := buf.String() - if test.want != s { - t.Errorf("ConfigState #%d\n got: %s want: %s", i, s, test.want) - continue - } - } -} diff --git a/vendor/github.com/dgrijalva/jwt-go/README.md b/vendor/github.com/dgrijalva/jwt-go/README.md index 25aec486c6..d358d881b8 100644 --- a/vendor/github.com/dgrijalva/jwt-go/README.md +++ b/vendor/github.com/dgrijalva/jwt-go/README.md @@ -1,11 +1,15 @@ -A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) +# jwt-go [![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go) +[![GoDoc](https://godoc.org/github.com/dgrijalva/jwt-go?status.svg)](https://godoc.org/github.com/dgrijalva/jwt-go) + +A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) -**BREAKING CHANGES:*** Version 3.0.0 is here. It includes _a lot_ of changes including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. +**NEW VERSION COMING:** There have been a lot of improvements suggested since the version 3.0.0 released in 2016. I'm working now on cutting two different releases: 3.2.0 will contain any non-breaking changes or enhancements. 4.0.0 will follow shortly which will include breaking changes. See the 4.0.0 milestone to get an idea of what's coming. If you have other ideas, or would like to participate in 4.0.0, now's the time. If you depend on this library and don't want to be interrupted, I recommend you use your dependency mangement tool to pin to version 3. -**NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided. +**SECURITY NOTICE:** Some older versions of Go have a security issue in the cryotp/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #216 for more detail. +**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided. ## What the heck is a JWT? @@ -37,7 +41,7 @@ Here's an example of an extension that integrates with the Google App Engine sig ## Compliance -This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences: +This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences: * In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. @@ -47,7 +51,10 @@ This library is considered production ready. Feedback and feature requests are This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases). -While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v2`. It will do the right thing WRT semantic versioning. +While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v3`. It will do the right thing WRT semantic versioning. + +**BREAKING CHANGES:*** +* Version 3.0.0 includes _a lot_ of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. ## Usage Tips @@ -68,6 +75,14 @@ Symmetric signing methods, such as HSA, use only a single secret. This is probab Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. +### Signing Methods and Key Types + +Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: + +* The [HMAC signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation +* The [RSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation +* The [ECDSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation + ### JWT and OAuth It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. @@ -77,7 +92,7 @@ Without going too far down the rabbit hole, here's a description of the interact * OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. * OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. * Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. - + ## More Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go). diff --git a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md index c21551f6bb..6370298313 100644 --- a/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md +++ b/vendor/github.com/dgrijalva/jwt-go/VERSION_HISTORY.md @@ -1,5 +1,12 @@ ## `jwt-go` Version History +#### 3.2.0 + +* Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation +* HMAC signing method returns `ErrInvalidKeyType` instead of `ErrInvalidKey` where appropriate +* Added options to `request.ParseFromRequest`, which allows for an arbitrary list of modifiers to parsing behavior. Initial set include `WithClaims` and `WithParser`. Existing usage of this function will continue to work as before. +* Deprecated `ParseFromRequestWithClaims` to simplify API in the future. + #### 3.1.0 * Improvements to `jwt` command line tool diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go index 2f59a22236..f977381240 100644 --- a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go +++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go @@ -14,6 +14,7 @@ var ( ) // Implements the ECDSA family of signing methods signing methods +// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification type SigningMethodECDSA struct { Name string Hash crypto.Hash diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go deleted file mode 100644 index 753047b1ec..0000000000 --- a/vendor/github.com/dgrijalva/jwt-go/ecdsa_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package jwt_test - -import ( - "crypto/ecdsa" - "io/ioutil" - "strings" - "testing" - - "github.com/dgrijalva/jwt-go" -) - -var ecdsaTestData = []struct { - name string - keys map[string]string - tokenString string - alg string - claims map[string]interface{} - valid bool -}{ - { - "Basic ES256", - map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"}, - "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJmb28iOiJiYXIifQ.feG39E-bn8HXAKhzDZq7yEAPWYDhZlwTn3sePJnU9VrGMmwdXAIEyoOnrjreYlVM_Z4N13eK9-TmMTWyfKJtHQ", - "ES256", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic ES384", - map[string]string{"private": "test/ec384-private.pem", "public": "test/ec384-public.pem"}, - "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzM4NCJ9.eyJmb28iOiJiYXIifQ.ngAfKMbJUh0WWubSIYe5GMsA-aHNKwFbJk_wq3lq23aPp8H2anb1rRILIzVR0gUf4a8WzDtrzmiikuPWyCS6CN4-PwdgTk-5nehC7JXqlaBZU05p3toM3nWCwm_LXcld", - "ES384", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic ES512", - map[string]string{"private": "test/ec512-private.pem", "public": "test/ec512-public.pem"}, - "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzUxMiJ9.eyJmb28iOiJiYXIifQ.AAU0TvGQOcdg2OvrwY73NHKgfk26UDekh9Prz-L_iWuTBIBqOFCWwwLsRiHB1JOddfKAls5do1W0jR_F30JpVd-6AJeTjGKA4C1A1H6gIKwRY0o_tFDIydZCl_lMBMeG5VNFAjO86-WCSKwc3hqaGkq1MugPRq_qrF9AVbuEB4JPLyL5", - "ES512", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "basic ES256 invalid: foo => bar", - map[string]string{"private": "test/ec256-private.pem", "public": "test/ec256-public.pem"}, - "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.MEQCIHoSJnmGlPaVQDqacx_2XlXEhhqtWceVopjomc2PJLtdAiAUTeGPoNYxZw0z8mgOnnIcjoxRuNDVZvybRZF3wR1l8W", - "ES256", - map[string]interface{}{"foo": "bar"}, - false, - }, -} - -func TestECDSAVerify(t *testing.T) { - for _, data := range ecdsaTestData { - var err error - - key, _ := ioutil.ReadFile(data.keys["public"]) - - var ecdsaKey *ecdsa.PublicKey - if ecdsaKey, err = jwt.ParseECPublicKeyFromPEM(key); err != nil { - t.Errorf("Unable to parse ECDSA public key: %v", err) - } - - parts := strings.Split(data.tokenString, ".") - - method := jwt.GetSigningMethod(data.alg) - err = method.Verify(strings.Join(parts[0:2], "."), parts[2], ecdsaKey) - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying key: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid key passed validation", data.name) - } - } -} - -func TestECDSASign(t *testing.T) { - for _, data := range ecdsaTestData { - var err error - key, _ := ioutil.ReadFile(data.keys["private"]) - - var ecdsaKey *ecdsa.PrivateKey - if ecdsaKey, err = jwt.ParseECPrivateKeyFromPEM(key); err != nil { - t.Errorf("Unable to parse ECDSA private key: %v", err) - } - - if data.valid { - parts := strings.Split(data.tokenString, ".") - method := jwt.GetSigningMethod(data.alg) - sig, err := method.Sign(strings.Join(parts[0:2], "."), ecdsaKey) - if err != nil { - t.Errorf("[%v] Error signing token: %v", data.name, err) - } - if sig == parts[2] { - t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig) - } - } - } -} diff --git a/vendor/github.com/dgrijalva/jwt-go/example_test.go b/vendor/github.com/dgrijalva/jwt-go/example_test.go deleted file mode 100644 index ae8b788a0b..0000000000 --- a/vendor/github.com/dgrijalva/jwt-go/example_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package jwt_test - -import ( - "fmt" - "github.com/dgrijalva/jwt-go" - "time" -) - -// Example (atypical) using the StandardClaims type by itself to parse a token. -// The StandardClaims type is designed to be embedded into your custom types -// to provide standard validation features. You can use it alone, but there's -// no way to retrieve other fields after parsing. -// See the CustomClaimsType example for intended usage. -func ExampleNewWithClaims_standardClaims() { - mySigningKey := []byte("AllYourBase") - - // Create the Claims - claims := &jwt.StandardClaims{ - ExpiresAt: 15000, - Issuer: "test", - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - ss, err := token.SignedString(mySigningKey) - fmt.Printf("%v %v", ss, err) - //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.QsODzZu3lUZMVdhbO76u3Jv02iYCvEHcYVUI1kOWEU0 -} - -// Example creating a token using a custom claims type. The StandardClaim is embedded -// in the custom type to allow for easy encoding, parsing and validation of standard claims. -func ExampleNewWithClaims_customClaimsType() { - mySigningKey := []byte("AllYourBase") - - type MyCustomClaims struct { - Foo string `json:"foo"` - jwt.StandardClaims - } - - // Create the Claims - claims := MyCustomClaims{ - "bar", - jwt.StandardClaims{ - ExpiresAt: 15000, - Issuer: "test", - }, - } - - token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - ss, err := token.SignedString(mySigningKey) - fmt.Printf("%v %v", ss, err) - //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c -} - -// Example creating a token using a custom claims type. The StandardClaim is embedded -// in the custom type to allow for easy encoding, parsing and validation of standard claims. -func ExampleParseWithClaims_customClaimsType() { - tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" - - type MyCustomClaims struct { - Foo string `json:"foo"` - jwt.StandardClaims - } - - // sample token is expired. override time so it parses as valid - at(time.Unix(0, 0), func() { - token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { - return []byte("AllYourBase"), nil - }) - - if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid { - fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt) - } else { - fmt.Println(err) - } - }) - - // Output: bar 15000 -} - -// Override time value for tests. Restore default value after. -func at(t time.Time, f func()) { - jwt.TimeFunc = func() time.Time { - return t - } - f() - jwt.TimeFunc = time.Now -} - -// An example of parsing the error types using bitfield checks -func ExampleParse_errorChecking() { - // Token from another example. This token is expired - var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" - - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { - return []byte("AllYourBase"), nil - }) - - if token.Valid { - fmt.Println("You look nice today") - } else if ve, ok := err.(*jwt.ValidationError); ok { - if ve.Errors&jwt.ValidationErrorMalformed != 0 { - fmt.Println("That's not even a token") - } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 { - // Token is either expired or not active yet - fmt.Println("Timing is everything") - } else { - fmt.Println("Couldn't handle this token:", err) - } - } else { - fmt.Println("Couldn't handle this token:", err) - } - - // Output: Timing is everything -} diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/dgrijalva/jwt-go/hmac.go index c229919254..addbe5d401 100644 --- a/vendor/github.com/dgrijalva/jwt-go/hmac.go +++ b/vendor/github.com/dgrijalva/jwt-go/hmac.go @@ -7,6 +7,7 @@ import ( ) // Implements the HMAC-SHA family of signing methods signing methods +// Expects key type of []byte for both signing and validation type SigningMethodHMAC struct { Name string Hash crypto.Hash @@ -90,5 +91,5 @@ func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, return EncodeSegment(hasher.Sum(nil)), nil } - return "", ErrInvalidKey + return "", ErrInvalidKeyType } diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go b/vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go deleted file mode 100644 index 0027831474..0000000000 --- a/vendor/github.com/dgrijalva/jwt-go/hmac_example_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package jwt_test - -import ( - "fmt" - "github.com/dgrijalva/jwt-go" - "io/ioutil" - "time" -) - -// For HMAC signing method, the key can be any []byte. It is recommended to generate -// a key using crypto/rand or something equivalent. You need the same key for signing -// and validating. -var hmacSampleSecret []byte - -func init() { - // Load sample key data - if keyData, e := ioutil.ReadFile("test/hmacTestKey"); e == nil { - hmacSampleSecret = keyData - } else { - panic(e) - } -} - -// Example creating, signing, and encoding a JWT token using the HMAC signing method -func ExampleNew_hmac() { - // Create a new token object, specifying signing method and the claims - // you would like it to contain. - token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ - "foo": "bar", - "nbf": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(), - }) - - // Sign and get the complete encoded token as a string using the secret - tokenString, err := token.SignedString(hmacSampleSecret) - - fmt.Println(tokenString, err) - // Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU -} - -// Example parsing and validating a token using the HMAC signing method -func ExampleParse_hmac() { - // sample token string taken from the New example - tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU" - - // Parse takes the token string and a function for looking up the key. The latter is especially - // useful if you use multiple keys for your application. The standard is to use 'kid' in the - // head of the token to identify which key to use, but the parsed token (head and claims) is provided - // to the callback, providing flexibility. - token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { - // Don't forget to validate the alg is what you expect: - if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { - return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"]) - } - - // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key") - return hmacSampleSecret, nil - }) - - if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { - fmt.Println(claims["foo"], claims["nbf"]) - } else { - fmt.Println(err) - } - - // Output: bar 1.4444784e+09 -} diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac_test.go b/vendor/github.com/dgrijalva/jwt-go/hmac_test.go deleted file mode 100644 index c7e114f4f9..0000000000 --- a/vendor/github.com/dgrijalva/jwt-go/hmac_test.go +++ /dev/null @@ -1,91 +0,0 @@ -package jwt_test - -import ( - "github.com/dgrijalva/jwt-go" - "io/ioutil" - "strings" - "testing" -) - -var hmacTestData = []struct { - name string - tokenString string - alg string - claims map[string]interface{} - valid bool -}{ - { - "web sample", - "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk", - "HS256", - map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, - true, - }, - { - "HS384", - "eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.KWZEuOD5lbBxZ34g7F-SlVLAQ_r5KApWNWlZIIMyQVz5Zs58a7XdNzj5_0EcNoOy", - "HS384", - map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, - true, - }, - { - "HS512", - "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEuMzAwODE5MzhlKzA5LCJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZSwiaXNzIjoiam9lIn0.CN7YijRX6Aw1n2jyI2Id1w90ja-DEMYiWixhYCyHnrZ1VfJRaFQz1bEbjjA5Fn4CLYaUG432dEYmSbS4Saokmw", - "HS512", - map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, - true, - }, - { - "web sample: invalid", - "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFtcGxlLmNvbS9pc19yb290Ijp0cnVlfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXo", - "HS256", - map[string]interface{}{"iss": "joe", "exp": 1300819380, "http://example.com/is_root": true}, - false, - }, -} - -// Sample data from http://tools.ietf.org/html/draft-jones-json-web-signature-04#appendix-A.1 -var hmacTestKey, _ = ioutil.ReadFile("test/hmacTestKey") - -func TestHMACVerify(t *testing.T) { - for _, data := range hmacTestData { - parts := strings.Split(data.tokenString, ".") - - method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], hmacTestKey) - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying key: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid key passed validation", data.name) - } - } -} - -func TestHMACSign(t *testing.T) { - for _, data := range hmacTestData { - if data.valid { - parts := strings.Split(data.tokenString, ".") - method := jwt.GetSigningMethod(data.alg) - sig, err := method.Sign(strings.Join(parts[0:2], "."), hmacTestKey) - if err != nil { - t.Errorf("[%v] Error signing token: %v", data.name, err) - } - if sig != parts[2] { - t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) - } - } - } -} - -func BenchmarkHS256Signing(b *testing.B) { - benchmarkSigning(b, jwt.SigningMethodHS256, hmacTestKey) -} - -func BenchmarkHS384Signing(b *testing.B) { - benchmarkSigning(b, jwt.SigningMethodHS384, hmacTestKey) -} - -func BenchmarkHS512Signing(b *testing.B) { - benchmarkSigning(b, jwt.SigningMethodHS512, hmacTestKey) -} diff --git a/vendor/github.com/dgrijalva/jwt-go/http_example_test.go b/vendor/github.com/dgrijalva/jwt-go/http_example_test.go deleted file mode 100644 index 82e9c50a41..0000000000 --- a/vendor/github.com/dgrijalva/jwt-go/http_example_test.go +++ /dev/null @@ -1,216 +0,0 @@ -package jwt_test - -// Example HTTP auth using asymmetric crypto/RSA keys -// This is based on a (now outdated) example at https://gist.github.com/cryptix/45c33ecf0ae54828e63b - -import ( - "bytes" - "crypto/rsa" - "fmt" - "github.com/dgrijalva/jwt-go" - "github.com/dgrijalva/jwt-go/request" - "io" - "io/ioutil" - "log" - "net" - "net/http" - "net/url" - "strings" - "time" -) - -// location of the files used for signing and verification -const ( - privKeyPath = "test/sample_key" // openssl genrsa -out app.rsa keysize - pubKeyPath = "test/sample_key.pub" // openssl rsa -in app.rsa -pubout > app.rsa.pub -) - -var ( - verifyKey *rsa.PublicKey - signKey *rsa.PrivateKey - serverPort int - // storing sample username/password pairs - // don't do this on a real server - users = map[string]string{ - "test": "known", - } -) - -// read the key files before starting http handlers -func init() { - signBytes, err := ioutil.ReadFile(privKeyPath) - fatal(err) - - signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes) - fatal(err) - - verifyBytes, err := ioutil.ReadFile(pubKeyPath) - fatal(err) - - verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes) - fatal(err) - - http.HandleFunc("/authenticate", authHandler) - http.HandleFunc("/restricted", restrictedHandler) - - // Setup listener - listener, err := net.ListenTCP("tcp", &net.TCPAddr{}) - serverPort = listener.Addr().(*net.TCPAddr).Port - - log.Println("Listening...") - go func() { - fatal(http.Serve(listener, nil)) - }() -} - -var start func() - -func fatal(err error) { - if err != nil { - log.Fatal(err) - } -} - -// Define some custom types were going to use within our tokens -type CustomerInfo struct { - Name string - Kind string -} - -type CustomClaimsExample struct { - *jwt.StandardClaims - TokenType string - CustomerInfo -} - -func Example_getTokenViaHTTP() { - // See func authHandler for an example auth handler that produces a token - res, err := http.PostForm(fmt.Sprintf("http://localhost:%v/authenticate", serverPort), url.Values{ - "user": {"test"}, - "pass": {"known"}, - }) - if err != nil { - fatal(err) - } - - if res.StatusCode != 200 { - fmt.Println("Unexpected status code", res.StatusCode) - } - - // Read the token out of the response body - buf := new(bytes.Buffer) - io.Copy(buf, res.Body) - res.Body.Close() - tokenString := strings.TrimSpace(buf.String()) - - // Parse the token - token, err := jwt.ParseWithClaims(tokenString, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) { - // since we only use the one private key to sign the tokens, - // we also only use its public counter part to verify - return verifyKey, nil - }) - fatal(err) - - claims := token.Claims.(*CustomClaimsExample) - fmt.Println(claims.CustomerInfo.Name) - - //Output: test -} - -func Example_useTokenViaHTTP() { - - // Make a sample token - // In a real world situation, this token will have been acquired from - // some other API call (see Example_getTokenViaHTTP) - token, err := createToken("foo") - fatal(err) - - // Make request. See func restrictedHandler for example request processor - req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:%v/restricted", serverPort), nil) - fatal(err) - req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token)) - res, err := http.DefaultClient.Do(req) - fatal(err) - - // Read the response body - buf := new(bytes.Buffer) - io.Copy(buf, res.Body) - res.Body.Close() - fmt.Println(buf.String()) - - // Output: Welcome, foo -} - -func createToken(user string) (string, error) { - // create a signer for rsa 256 - t := jwt.New(jwt.GetSigningMethod("RS256")) - - // set our claims - t.Claims = &CustomClaimsExample{ - &jwt.StandardClaims{ - // set the expire time - // see http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-20#section-4.1.4 - ExpiresAt: time.Now().Add(time.Minute * 1).Unix(), - }, - "level1", - CustomerInfo{user, "human"}, - } - - // Creat token string - return t.SignedString(signKey) -} - -// reads the form values, checks them and creates the token -func authHandler(w http.ResponseWriter, r *http.Request) { - // make sure its post - if r.Method != "POST" { - w.WriteHeader(http.StatusBadRequest) - fmt.Fprintln(w, "No POST", r.Method) - return - } - - user := r.FormValue("user") - pass := r.FormValue("pass") - - log.Printf("Authenticate: user[%s] pass[%s]\n", user, pass) - - // check values - if user != "test" || pass != "known" { - w.WriteHeader(http.StatusForbidden) - fmt.Fprintln(w, "Wrong info") - return - } - - tokenString, err := createToken(user) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintln(w, "Sorry, error while Signing Token!") - log.Printf("Token Signing error: %v\n", err) - return - } - - w.Header().Set("Content-Type", "application/jwt") - w.WriteHeader(http.StatusOK) - fmt.Fprintln(w, tokenString) -} - -// only accessible with a valid token -func restrictedHandler(w http.ResponseWriter, r *http.Request) { - // Get token from request - token, err := request.ParseFromRequestWithClaims(r, request.OAuth2Extractor, &CustomClaimsExample{}, func(token *jwt.Token) (interface{}, error) { - // since we only use the one private key to sign the tokens, - // we also only use its public counter part to verify - return verifyKey, nil - }) - - // If the token is missing or invalid, return error - if err != nil { - w.WriteHeader(http.StatusUnauthorized) - fmt.Fprintln(w, "Invalid token:", err) - return - } - - // Token is valid - fmt.Fprintln(w, "Welcome,", token.Claims.(*CustomClaimsExample).Name) - return -} diff --git a/vendor/github.com/dgrijalva/jwt-go/none_test.go b/vendor/github.com/dgrijalva/jwt-go/none_test.go deleted file mode 100644 index 29a69efef7..0000000000 --- a/vendor/github.com/dgrijalva/jwt-go/none_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package jwt_test - -import ( - "github.com/dgrijalva/jwt-go" - "strings" - "testing" -) - -var noneTestData = []struct { - name string - tokenString string - alg string - key interface{} - claims map[string]interface{} - valid bool -}{ - { - "Basic", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.", - "none", - jwt.UnsafeAllowNoneSignatureType, - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic - no key", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.", - "none", - nil, - map[string]interface{}{"foo": "bar"}, - false, - }, - { - "Signed", - "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw", - "none", - jwt.UnsafeAllowNoneSignatureType, - map[string]interface{}{"foo": "bar"}, - false, - }, -} - -func TestNoneVerify(t *testing.T) { - for _, data := range noneTestData { - parts := strings.Split(data.tokenString, ".") - - method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], data.key) - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying key: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid key passed validation", data.name) - } - } -} - -func TestNoneSign(t *testing.T) { - for _, data := range noneTestData { - if data.valid { - parts := strings.Split(data.tokenString, ".") - method := jwt.GetSigningMethod(data.alg) - sig, err := method.Sign(strings.Join(parts[0:2], "."), data.key) - if err != nil { - t.Errorf("[%v] Error signing token: %v", data.name, err) - } - if sig != parts[2] { - t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) - } - } - } -} diff --git a/vendor/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/dgrijalva/jwt-go/parser.go index 7bf1c4ea08..d6901d9adb 100644 --- a/vendor/github.com/dgrijalva/jwt-go/parser.go +++ b/vendor/github.com/dgrijalva/jwt-go/parser.go @@ -21,55 +21,9 @@ func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { } func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - parts := strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) - } - - var err error - token := &Token{Raw: tokenString} - - // parse Header - var headerBytes []byte - if headerBytes, err = DecodeSegment(parts[0]); err != nil { - if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) - } - return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // parse Claims - var claimBytes []byte - token.Claims = claims - - if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.UseJSONNumber { - dec.UseNumber() - } - // JSON Decode. Special case for map type to avoid weird pointer behavior - if c, ok := token.Claims.(MapClaims); ok { - err = dec.Decode(&c) - } else { - err = dec.Decode(&claims) - } - // Handle decode error + token, parts, err := p.ParseUnverified(tokenString, claims) if err != nil { - return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // Lookup signature method - if method, ok := token.Header["alg"].(string); ok { - if token.Method = GetSigningMethod(method); token.Method == nil { - return token, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) - } - } else { - return token, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) + return token, err } // Verify signing method is in the required set @@ -96,6 +50,9 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf } if key, err = keyFunc(token); err != nil { // keyFunc returned an error + if ve, ok := err.(*ValidationError); ok { + return token, ve + } return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} } @@ -129,3 +86,63 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf return token, vErr } + +// WARNING: Don't use this method unless you know what you're doing +// +// This method parses the token but doesn't validate the signature. It's only +// ever useful in cases where you know the signature is valid (because it has +// been checked previously in the stack) and you want to extract values from +// it. +func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { + parts = strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) + } + + token = &Token{Raw: tokenString} + + // parse Header + var headerBytes []byte + if headerBytes, err = DecodeSegment(parts[0]); err != nil { + if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { + return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) + } + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + if err = json.Unmarshal(headerBytes, &token.Header); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + + // parse Claims + var claimBytes []byte + token.Claims = claims + + if claimBytes, err = DecodeSegment(parts[1]); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + if p.UseJSONNumber { + dec.UseNumber() + } + // JSON Decode. Special case for map type to avoid weird pointer behavior + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } + // Handle decode error + if err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + + // Lookup signature method + if method, ok := token.Header["alg"].(string); ok { + if token.Method = GetSigningMethod(method); token.Method == nil { + return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) + } + } else { + return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) + } + + return token, parts, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/parser_test.go b/vendor/github.com/dgrijalva/jwt-go/parser_test.go deleted file mode 100644 index f8ad6f9083..0000000000 --- a/vendor/github.com/dgrijalva/jwt-go/parser_test.go +++ /dev/null @@ -1,261 +0,0 @@ -package jwt_test - -import ( - "crypto/rsa" - "encoding/json" - "fmt" - "reflect" - "testing" - "time" - - "github.com/dgrijalva/jwt-go" - "github.com/dgrijalva/jwt-go/test" -) - -var keyFuncError error = fmt.Errorf("error loading key") - -var ( - jwtTestDefaultKey *rsa.PublicKey - defaultKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return jwtTestDefaultKey, nil } - emptyKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, nil } - errorKeyFunc jwt.Keyfunc = func(t *jwt.Token) (interface{}, error) { return nil, keyFuncError } - nilKeyFunc jwt.Keyfunc = nil -) - -func init() { - jwtTestDefaultKey = test.LoadRSAPublicKeyFromDisk("test/sample_key.pub") -} - -var jwtTestData = []struct { - name string - tokenString string - keyfunc jwt.Keyfunc - claims jwt.Claims - valid bool - errors uint32 - parser *jwt.Parser -}{ - { - "basic", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - defaultKeyFunc, - jwt.MapClaims{"foo": "bar"}, - true, - 0, - nil, - }, - { - "basic expired", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "exp": float64(time.Now().Unix() - 100)}, - false, - jwt.ValidationErrorExpired, - nil, - }, - { - "basic nbf", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)}, - false, - jwt.ValidationErrorNotValidYet, - nil, - }, - { - "expired and nbf", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)}, - false, - jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired, - nil, - }, - { - "basic invalid", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - defaultKeyFunc, - jwt.MapClaims{"foo": "bar"}, - false, - jwt.ValidationErrorSignatureInvalid, - nil, - }, - { - "basic nokeyfunc", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - nilKeyFunc, - jwt.MapClaims{"foo": "bar"}, - false, - jwt.ValidationErrorUnverifiable, - nil, - }, - { - "basic nokey", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - emptyKeyFunc, - jwt.MapClaims{"foo": "bar"}, - false, - jwt.ValidationErrorSignatureInvalid, - nil, - }, - { - "basic errorkey", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - errorKeyFunc, - jwt.MapClaims{"foo": "bar"}, - false, - jwt.ValidationErrorUnverifiable, - nil, - }, - { - "invalid signing method", - "", - defaultKeyFunc, - jwt.MapClaims{"foo": "bar"}, - false, - jwt.ValidationErrorSignatureInvalid, - &jwt.Parser{ValidMethods: []string{"HS256"}}, - }, - { - "valid signing method", - "", - defaultKeyFunc, - jwt.MapClaims{"foo": "bar"}, - true, - 0, - &jwt.Parser{ValidMethods: []string{"RS256", "HS256"}}, - }, - { - "JSON Number", - "", - defaultKeyFunc, - jwt.MapClaims{"foo": json.Number("123.4")}, - true, - 0, - &jwt.Parser{UseJSONNumber: true}, - }, - { - "Standard Claims", - "", - defaultKeyFunc, - &jwt.StandardClaims{ - ExpiresAt: time.Now().Add(time.Second * 10).Unix(), - }, - true, - 0, - &jwt.Parser{UseJSONNumber: true}, - }, - { - "JSON Number - basic expired", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))}, - false, - jwt.ValidationErrorExpired, - &jwt.Parser{UseJSONNumber: true}, - }, - { - "JSON Number - basic nbf", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))}, - false, - jwt.ValidationErrorNotValidYet, - &jwt.Parser{UseJSONNumber: true}, - }, - { - "JSON Number - expired and nbf", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100)), "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))}, - false, - jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired, - &jwt.Parser{UseJSONNumber: true}, - }, - { - "SkipClaimsValidation during token parsing", - "", // autogen - defaultKeyFunc, - jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))}, - true, - 0, - &jwt.Parser{UseJSONNumber: true, SkipClaimsValidation: true}, - }, -} - -func TestParser_Parse(t *testing.T) { - privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key") - - // Iterate over test data set and run tests - for _, data := range jwtTestData { - // If the token string is blank, use helper function to generate string - if data.tokenString == "" { - data.tokenString = test.MakeSampleToken(data.claims, privateKey) - } - - // Parse the token - var token *jwt.Token - var err error - var parser = data.parser - if parser == nil { - parser = new(jwt.Parser) - } - // Figure out correct claims type - switch data.claims.(type) { - case jwt.MapClaims: - token, err = parser.ParseWithClaims(data.tokenString, jwt.MapClaims{}, data.keyfunc) - case *jwt.StandardClaims: - token, err = parser.ParseWithClaims(data.tokenString, &jwt.StandardClaims{}, data.keyfunc) - } - - // Verify result matches expectation - if !reflect.DeepEqual(data.claims, token.Claims) { - t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) - } - - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying token: %T:%v", data.name, err, err) - } - - if !data.valid && err == nil { - t.Errorf("[%v] Invalid token passed validation", data.name) - } - - if (err == nil && !token.Valid) || (err != nil && token.Valid) { - t.Errorf("[%v] Inconsistent behavior between returned error and token.Valid", data.name) - } - - if data.errors != 0 { - if err == nil { - t.Errorf("[%v] Expecting error. Didn't get one.", data.name) - } else { - - ve := err.(*jwt.ValidationError) - // compare the bitfield part of the error - if e := ve.Errors; e != data.errors { - t.Errorf("[%v] Errors don't match expectation. %v != %v", data.name, e, data.errors) - } - - if err.Error() == keyFuncError.Error() && ve.Inner != keyFuncError { - t.Errorf("[%v] Inner error does not match expectation. %v != %v", data.name, ve.Inner, keyFuncError) - } - } - } - if data.valid && token.Signature == "" { - t.Errorf("[%v] Signature is left unpopulated after parsing", data.name) - } - } -} - -// Helper method for benchmarking various methods -func benchmarkSigning(b *testing.B, method jwt.SigningMethod, key interface{}) { - t := jwt.New(method) - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - if _, err := t.SignedString(key); err != nil { - b.Fatal(err) - } - } - }) - -} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/dgrijalva/jwt-go/rsa.go index 0ae0b1984e..e4caf1ca4a 100644 --- a/vendor/github.com/dgrijalva/jwt-go/rsa.go +++ b/vendor/github.com/dgrijalva/jwt-go/rsa.go @@ -7,6 +7,7 @@ import ( ) // Implements the RSA family of signing methods signing methods +// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation type SigningMethodRSA struct { Name string Hash crypto.Hash @@ -44,7 +45,7 @@ func (m *SigningMethodRSA) Alg() string { } // Implements the Verify method from SigningMethod -// For this signing method, must be an rsa.PublicKey structure. +// For this signing method, must be an *rsa.PublicKey structure. func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { var err error @@ -73,7 +74,7 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface } // Implements the Sign method from SigningMethod -// For this signing method, must be an rsa.PrivateKey structure. +// For this signing method, must be an *rsa.PrivateKey structure. func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { var rsaKey *rsa.PrivateKey var ok bool diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go deleted file mode 100644 index 9045aaf349..0000000000 --- a/vendor/github.com/dgrijalva/jwt-go/rsa_pss_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// +build go1.4 - -package jwt_test - -import ( - "crypto/rsa" - "io/ioutil" - "strings" - "testing" - - "github.com/dgrijalva/jwt-go" -) - -var rsaPSSTestData = []struct { - name string - tokenString string - alg string - claims map[string]interface{} - valid bool -}{ - { - "Basic PS256", - "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9w", - "PS256", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic PS384", - "eyJhbGciOiJQUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.w7-qqgj97gK4fJsq_DCqdYQiylJjzWONvD0qWWWhqEOFk2P1eDULPnqHRnjgTXoO4HAw4YIWCsZPet7nR3Xxq4ZhMqvKW8b7KlfRTb9cH8zqFvzMmybQ4jv2hKc3bXYqVow3AoR7hN_CWXI3Dv6Kd2X5xhtxRHI6IL39oTVDUQ74LACe-9t4c3QRPuj6Pq1H4FAT2E2kW_0KOc6EQhCLWEhm2Z2__OZskDC8AiPpP8Kv4k2vB7l0IKQu8Pr4RcNBlqJdq8dA5D3hk5TLxP8V5nG1Ib80MOMMqoS3FQvSLyolFX-R_jZ3-zfq6Ebsqr0yEb0AH2CfsECF7935Pa0FKQ", - "PS384", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic PS512", - "eyJhbGciOiJQUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.GX1HWGzFaJevuSLavqqFYaW8_TpvcjQ8KfC5fXiSDzSiT9UD9nB_ikSmDNyDILNdtjZLSvVKfXxZJqCfefxAtiozEDDdJthZ-F0uO4SPFHlGiXszvKeodh7BuTWRI2wL9-ZO4mFa8nq3GMeQAfo9cx11i7nfN8n2YNQ9SHGovG7_T_AvaMZB_jT6jkDHpwGR9mz7x1sycckEo6teLdHRnH_ZdlHlxqknmyTu8Odr5Xh0sJFOL8BepWbbvIIn-P161rRHHiDWFv6nhlHwZnVzjx7HQrWSGb6-s2cdLie9QL_8XaMcUpjLkfOMKkDOfHo6AvpL7Jbwi83Z2ZTHjJWB-A", - "PS512", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "basic PS256 invalid: foo => bar", - "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.PPG4xyDVY8ffp4CcxofNmsTDXsrVG2npdQuibLhJbv4ClyPTUtR5giNSvuxo03kB6I8VXVr0Y9X7UxhJVEoJOmULAwRWaUsDnIewQa101cVhMa6iR8X37kfFoiZ6NkS-c7henVkkQWu2HtotkEtQvN5hFlk8IevXXPmvZlhQhwzB1sGzGYnoi1zOfuL98d3BIjUjtlwii5w6gYG2AEEzp7HnHCsb3jIwUPdq86Oe6hIFjtBwduIK90ca4UqzARpcfwxHwVLMpatKask00AgGVI0ysdk0BLMjmLutquD03XbThHScC2C2_Pp4cHWgMzvbgLU2RYYZcZRKr46QeNgz9W", - "PS256", - map[string]interface{}{"foo": "bar"}, - false, - }, -} - -func TestRSAPSSVerify(t *testing.T) { - var err error - - key, _ := ioutil.ReadFile("test/sample_key.pub") - var rsaPSSKey *rsa.PublicKey - if rsaPSSKey, err = jwt.ParseRSAPublicKeyFromPEM(key); err != nil { - t.Errorf("Unable to parse RSA public key: %v", err) - } - - for _, data := range rsaPSSTestData { - parts := strings.Split(data.tokenString, ".") - - method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], rsaPSSKey) - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying key: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid key passed validation", data.name) - } - } -} - -func TestRSAPSSSign(t *testing.T) { - var err error - - key, _ := ioutil.ReadFile("test/sample_key") - var rsaPSSKey *rsa.PrivateKey - if rsaPSSKey, err = jwt.ParseRSAPrivateKeyFromPEM(key); err != nil { - t.Errorf("Unable to parse RSA private key: %v", err) - } - - for _, data := range rsaPSSTestData { - if data.valid { - parts := strings.Split(data.tokenString, ".") - method := jwt.GetSigningMethod(data.alg) - sig, err := method.Sign(strings.Join(parts[0:2], "."), rsaPSSKey) - if err != nil { - t.Errorf("[%v] Error signing token: %v", data.name, err) - } - if sig == parts[2] { - t.Errorf("[%v] Signatures shouldn't match\nnew:\n%v\noriginal:\n%v", data.name, sig, parts[2]) - } - } - } -} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_test.go b/vendor/github.com/dgrijalva/jwt-go/rsa_test.go deleted file mode 100644 index 2e0f785361..0000000000 --- a/vendor/github.com/dgrijalva/jwt-go/rsa_test.go +++ /dev/null @@ -1,176 +0,0 @@ -package jwt_test - -import ( - "github.com/dgrijalva/jwt-go" - "io/ioutil" - "strings" - "testing" -) - -var rsaTestData = []struct { - name string - tokenString string - alg string - claims map[string]interface{} - valid bool -}{ - { - "Basic RS256", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - "RS256", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic RS384", - "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.W-jEzRfBigtCWsinvVVuldiuilzVdU5ty0MvpLaSaqK9PlAWWlDQ1VIQ_qSKzwL5IXaZkvZFJXT3yL3n7OUVu7zCNJzdwznbC8Z-b0z2lYvcklJYi2VOFRcGbJtXUqgjk2oGsiqUMUMOLP70TTefkpsgqDxbRh9CDUfpOJgW-dU7cmgaoswe3wjUAUi6B6G2YEaiuXC0XScQYSYVKIzgKXJV8Zw-7AN_DBUI4GkTpsvQ9fVVjZM9csQiEXhYekyrKu1nu_POpQonGd8yqkIyXPECNmmqH5jH4sFiF67XhD7_JpkvLziBpI-uh86evBUadmHhb9Otqw3uV3NTaXLzJw", - "RS384", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "Basic RS512", - "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIifQ.zBlLlmRrUxx4SJPUbV37Q1joRcI9EW13grnKduK3wtYKmDXbgDpF1cZ6B-2Jsm5RB8REmMiLpGms-EjXhgnyh2TSHE-9W2gA_jvshegLWtwRVDX40ODSkTb7OVuaWgiy9y7llvcknFBTIg-FnVPVpXMmeV_pvwQyhaz1SSwSPrDyxEmksz1hq7YONXhXPpGaNbMMeDTNP_1oj8DZaqTIL9TwV8_1wb2Odt_Fy58Ke2RVFijsOLdnyEAjt2n9Mxihu9i3PhNBkkxa2GbnXBfq3kzvZ_xxGGopLdHhJjcGWXO-NiwI9_tiu14NRv4L2xC0ItD9Yz68v2ZIZEp_DuzwRQ", - "RS512", - map[string]interface{}{"foo": "bar"}, - true, - }, - { - "basic invalid: foo => bar", - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.EhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", - "RS256", - map[string]interface{}{"foo": "bar"}, - false, - }, -} - -func TestRSAVerify(t *testing.T) { - keyData, _ := ioutil.ReadFile("test/sample_key.pub") - key, _ := jwt.ParseRSAPublicKeyFromPEM(keyData) - - for _, data := range rsaTestData { - parts := strings.Split(data.tokenString, ".") - - method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], key) - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying key: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid key passed validation", data.name) - } - } -} - -func TestRSASign(t *testing.T) { - keyData, _ := ioutil.ReadFile("test/sample_key") - key, _ := jwt.ParseRSAPrivateKeyFromPEM(keyData) - - for _, data := range rsaTestData { - if data.valid { - parts := strings.Split(data.tokenString, ".") - method := jwt.GetSigningMethod(data.alg) - sig, err := method.Sign(strings.Join(parts[0:2], "."), key) - if err != nil { - t.Errorf("[%v] Error signing token: %v", data.name, err) - } - if sig != parts[2] { - t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) - } - } - } -} - -func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) { - key, _ := ioutil.ReadFile("test/sample_key.pub") - parsedKey, err := jwt.ParseRSAPublicKeyFromPEM(key) - if err != nil { - t.Fatal(err) - } - testData := rsaTestData[0] - parts := strings.Split(testData.tokenString, ".") - err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), parts[2], parsedKey) - if err != nil { - t.Errorf("[%v] Error while verifying key: %v", testData.name, err) - } -} - -func TestRSAWithPreParsedPrivateKey(t *testing.T) { - key, _ := ioutil.ReadFile("test/sample_key") - parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) - if err != nil { - t.Fatal(err) - } - testData := rsaTestData[0] - parts := strings.Split(testData.tokenString, ".") - sig, err := jwt.SigningMethodRS256.Sign(strings.Join(parts[0:2], "."), parsedKey) - if err != nil { - t.Errorf("[%v] Error signing token: %v", testData.name, err) - } - if sig != parts[2] { - t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", testData.name, sig, parts[2]) - } -} - -func TestRSAKeyParsing(t *testing.T) { - key, _ := ioutil.ReadFile("test/sample_key") - pubKey, _ := ioutil.ReadFile("test/sample_key.pub") - badKey := []byte("All your base are belong to key") - - // Test parsePrivateKey - if _, e := jwt.ParseRSAPrivateKeyFromPEM(key); e != nil { - t.Errorf("Failed to parse valid private key: %v", e) - } - - if k, e := jwt.ParseRSAPrivateKeyFromPEM(pubKey); e == nil { - t.Errorf("Parsed public key as valid private key: %v", k) - } - - if k, e := jwt.ParseRSAPrivateKeyFromPEM(badKey); e == nil { - t.Errorf("Parsed invalid key as valid private key: %v", k) - } - - // Test parsePublicKey - if _, e := jwt.ParseRSAPublicKeyFromPEM(pubKey); e != nil { - t.Errorf("Failed to parse valid public key: %v", e) - } - - if k, e := jwt.ParseRSAPublicKeyFromPEM(key); e == nil { - t.Errorf("Parsed private key as valid public key: %v", k) - } - - if k, e := jwt.ParseRSAPublicKeyFromPEM(badKey); e == nil { - t.Errorf("Parsed invalid key as valid private key: %v", k) - } - -} - -func BenchmarkRS256Signing(b *testing.B) { - key, _ := ioutil.ReadFile("test/sample_key") - parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) - if err != nil { - b.Fatal(err) - } - - benchmarkSigning(b, jwt.SigningMethodRS256, parsedKey) -} - -func BenchmarkRS384Signing(b *testing.B) { - key, _ := ioutil.ReadFile("test/sample_key") - parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) - if err != nil { - b.Fatal(err) - } - - benchmarkSigning(b, jwt.SigningMethodRS384, parsedKey) -} - -func BenchmarkRS512Signing(b *testing.B) { - key, _ := ioutil.ReadFile("test/sample_key") - parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key) - if err != nil { - b.Fatal(err) - } - - benchmarkSigning(b, jwt.SigningMethodRS512, parsedKey) -} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go index 213a90dbbf..a5ababf956 100644 --- a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go +++ b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go @@ -39,6 +39,38 @@ func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { return pkey, nil } +// Parse PEM encoded PKCS1 or PKCS8 private key protected with password +func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + var parsedKey interface{} + + var blockDecrypted []byte + if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { + return nil, err + } + + if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { + return nil, err + } + } + + var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } + + return pkey, nil +} + // Parse PEM encoded PKCS1 or PKCS8 public key func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { var err error diff --git a/vendor/github.com/docker/distribution/digestset/set_test.go b/vendor/github.com/docker/distribution/digestset/set_test.go deleted file mode 100644 index 89c5729d00..0000000000 --- a/vendor/github.com/docker/distribution/digestset/set_test.go +++ /dev/null @@ -1,371 +0,0 @@ -package digestset - -import ( - "crypto/sha256" - _ "crypto/sha512" - "encoding/binary" - "math/rand" - "testing" - - digest "github.com/opencontainers/go-digest" -) - -func assertEqualDigests(t *testing.T, d1, d2 digest.Digest) { - if d1 != d2 { - t.Fatalf("Digests do not match:\n\tActual: %s\n\tExpected: %s", d1, d2) - } -} - -func TestLookup(t *testing.T) { - digests := []digest.Digest{ - "sha256:1234511111111111111111111111111111111111111111111111111111111111", - "sha256:1234111111111111111111111111111111111111111111111111111111111111", - "sha256:1234611111111111111111111111111111111111111111111111111111111111", - "sha256:5432111111111111111111111111111111111111111111111111111111111111", - "sha256:6543111111111111111111111111111111111111111111111111111111111111", - "sha256:6432111111111111111111111111111111111111111111111111111111111111", - "sha256:6542111111111111111111111111111111111111111111111111111111111111", - "sha256:6532111111111111111111111111111111111111111111111111111111111111", - } - - dset := NewSet() - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - t.Fatal(err) - } - } - - dgst, err := dset.Lookup("54") - if err != nil { - t.Fatal(err) - } - assertEqualDigests(t, dgst, digests[3]) - - dgst, err = dset.Lookup("1234") - if err == nil { - t.Fatal("Expected ambiguous error looking up: 1234") - } - if err != ErrDigestAmbiguous { - t.Fatal(err) - } - - dgst, err = dset.Lookup("9876") - if err == nil { - t.Fatal("Expected ambiguous error looking up: 9876") - } - if err != ErrDigestNotFound { - t.Fatal(err) - } - - dgst, err = dset.Lookup("sha256:1234") - if err == nil { - t.Fatal("Expected ambiguous error looking up: sha256:1234") - } - if err != ErrDigestAmbiguous { - t.Fatal(err) - } - - dgst, err = dset.Lookup("sha256:12345") - if err != nil { - t.Fatal(err) - } - assertEqualDigests(t, dgst, digests[0]) - - dgst, err = dset.Lookup("sha256:12346") - if err != nil { - t.Fatal(err) - } - assertEqualDigests(t, dgst, digests[2]) - - dgst, err = dset.Lookup("12346") - if err != nil { - t.Fatal(err) - } - assertEqualDigests(t, dgst, digests[2]) - - dgst, err = dset.Lookup("12345") - if err != nil { - t.Fatal(err) - } - assertEqualDigests(t, dgst, digests[0]) -} - -func TestAddDuplication(t *testing.T) { - digests := []digest.Digest{ - "sha256:1234111111111111111111111111111111111111111111111111111111111111", - "sha256:1234511111111111111111111111111111111111111111111111111111111111", - "sha256:1234611111111111111111111111111111111111111111111111111111111111", - "sha256:5432111111111111111111111111111111111111111111111111111111111111", - "sha256:6543111111111111111111111111111111111111111111111111111111111111", - "sha512:65431111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", - "sha512:65421111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", - "sha512:65321111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", - } - - dset := NewSet() - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - t.Fatal(err) - } - } - - if len(dset.entries) != 8 { - t.Fatal("Invalid dset size") - } - - if err := dset.Add(digest.Digest("sha256:1234511111111111111111111111111111111111111111111111111111111111")); err != nil { - t.Fatal(err) - } - - if len(dset.entries) != 8 { - t.Fatal("Duplicate digest insert allowed") - } - - if err := dset.Add(digest.Digest("sha384:123451111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111")); err != nil { - t.Fatal(err) - } - - if len(dset.entries) != 9 { - t.Fatal("Insert with different algorithm not allowed") - } -} - -func TestRemove(t *testing.T) { - digests, err := createDigests(10) - if err != nil { - t.Fatal(err) - } - - dset := NewSet() - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - t.Fatal(err) - } - } - - dgst, err := dset.Lookup(digests[0].String()) - if err != nil { - t.Fatal(err) - } - if dgst != digests[0] { - t.Fatalf("Unexpected digest value:\n\tExpected: %s\n\tActual: %s", digests[0], dgst) - } - - if err := dset.Remove(digests[0]); err != nil { - t.Fatal(err) - } - - if _, err := dset.Lookup(digests[0].String()); err != ErrDigestNotFound { - t.Fatalf("Expected error %v when looking up removed digest, got %v", ErrDigestNotFound, err) - } -} - -func TestAll(t *testing.T) { - digests, err := createDigests(100) - if err != nil { - t.Fatal(err) - } - - dset := NewSet() - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - t.Fatal(err) - } - } - - all := map[digest.Digest]struct{}{} - for _, dgst := range dset.All() { - all[dgst] = struct{}{} - } - - if len(all) != len(digests) { - t.Fatalf("Unexpected number of unique digests found:\n\tExpected: %d\n\tActual: %d", len(digests), len(all)) - } - - for i, dgst := range digests { - if _, ok := all[dgst]; !ok { - t.Fatalf("Missing element at position %d: %s", i, dgst) - } - } - -} - -func assertEqualShort(t *testing.T, actual, expected string) { - if actual != expected { - t.Fatalf("Unexpected short value:\n\tExpected: %s\n\tActual: %s", expected, actual) - } -} - -func TestShortCodeTable(t *testing.T) { - digests := []digest.Digest{ - "sha256:1234111111111111111111111111111111111111111111111111111111111111", - "sha256:1234511111111111111111111111111111111111111111111111111111111111", - "sha256:1234611111111111111111111111111111111111111111111111111111111111", - "sha256:5432111111111111111111111111111111111111111111111111111111111111", - "sha256:6543111111111111111111111111111111111111111111111111111111111111", - "sha256:6432111111111111111111111111111111111111111111111111111111111111", - "sha256:6542111111111111111111111111111111111111111111111111111111111111", - "sha256:6532111111111111111111111111111111111111111111111111111111111111", - } - - dset := NewSet() - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - t.Fatal(err) - } - } - - dump := ShortCodeTable(dset, 2) - - if len(dump) < len(digests) { - t.Fatalf("Error unexpected size: %d, expecting %d", len(dump), len(digests)) - } - assertEqualShort(t, dump[digests[0]], "12341") - assertEqualShort(t, dump[digests[1]], "12345") - assertEqualShort(t, dump[digests[2]], "12346") - assertEqualShort(t, dump[digests[3]], "54") - assertEqualShort(t, dump[digests[4]], "6543") - assertEqualShort(t, dump[digests[5]], "64") - assertEqualShort(t, dump[digests[6]], "6542") - assertEqualShort(t, dump[digests[7]], "653") -} - -func createDigests(count int) ([]digest.Digest, error) { - r := rand.New(rand.NewSource(25823)) - digests := make([]digest.Digest, count) - for i := range digests { - h := sha256.New() - if err := binary.Write(h, binary.BigEndian, r.Int63()); err != nil { - return nil, err - } - digests[i] = digest.NewDigest("sha256", h) - } - return digests, nil -} - -func benchAddNTable(b *testing.B, n int) { - digests, err := createDigests(n) - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))} - for j := range digests { - if err = dset.Add(digests[j]); err != nil { - b.Fatal(err) - } - } - } -} - -func benchLookupNTable(b *testing.B, n int, shortLen int) { - digests, err := createDigests(n) - if err != nil { - b.Fatal(err) - } - dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))} - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - b.Fatal(err) - } - } - shorts := make([]string, 0, n) - for _, short := range ShortCodeTable(dset, shortLen) { - shorts = append(shorts, short) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err = dset.Lookup(shorts[i%n]); err != nil { - b.Fatal(err) - } - } -} - -func benchRemoveNTable(b *testing.B, n int) { - digests, err := createDigests(n) - if err != nil { - b.Fatal(err) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))} - b.StopTimer() - for j := range digests { - if err = dset.Add(digests[j]); err != nil { - b.Fatal(err) - } - } - b.StartTimer() - for j := range digests { - if err = dset.Remove(digests[j]); err != nil { - b.Fatal(err) - } - } - } -} - -func benchShortCodeNTable(b *testing.B, n int, shortLen int) { - digests, err := createDigests(n) - if err != nil { - b.Fatal(err) - } - dset := &Set{entries: digestEntries(make([]*digestEntry, 0, n))} - for i := range digests { - if err := dset.Add(digests[i]); err != nil { - b.Fatal(err) - } - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - ShortCodeTable(dset, shortLen) - } -} - -func BenchmarkAdd10(b *testing.B) { - benchAddNTable(b, 10) -} - -func BenchmarkAdd100(b *testing.B) { - benchAddNTable(b, 100) -} - -func BenchmarkAdd1000(b *testing.B) { - benchAddNTable(b, 1000) -} - -func BenchmarkRemove10(b *testing.B) { - benchRemoveNTable(b, 10) -} - -func BenchmarkRemove100(b *testing.B) { - benchRemoveNTable(b, 100) -} - -func BenchmarkRemove1000(b *testing.B) { - benchRemoveNTable(b, 1000) -} - -func BenchmarkLookup10(b *testing.B) { - benchLookupNTable(b, 10, 12) -} - -func BenchmarkLookup100(b *testing.B) { - benchLookupNTable(b, 100, 12) -} - -func BenchmarkLookup1000(b *testing.B) { - benchLookupNTable(b, 1000, 12) -} - -func BenchmarkShortCode10(b *testing.B) { - benchShortCodeNTable(b, 10, 12) -} -func BenchmarkShortCode100(b *testing.B) { - benchShortCodeNTable(b, 100, 12) -} -func BenchmarkShortCode1000(b *testing.B) { - benchShortCodeNTable(b, 1000, 12) -} diff --git a/vendor/github.com/docker/distribution/reference/normalize_test.go b/vendor/github.com/docker/distribution/reference/normalize_test.go deleted file mode 100644 index a881972acc..0000000000 --- a/vendor/github.com/docker/distribution/reference/normalize_test.go +++ /dev/null @@ -1,625 +0,0 @@ -package reference - -import ( - "strconv" - "testing" - - "github.com/docker/distribution/digestset" - "github.com/opencontainers/go-digest" -) - -func TestValidateReferenceName(t *testing.T) { - validRepoNames := []string{ - "docker/docker", - "library/debian", - "debian", - "docker.io/docker/docker", - "docker.io/library/debian", - "docker.io/debian", - "index.docker.io/docker/docker", - "index.docker.io/library/debian", - "index.docker.io/debian", - "127.0.0.1:5000/docker/docker", - "127.0.0.1:5000/library/debian", - "127.0.0.1:5000/debian", - "thisisthesongthatneverendsitgoesonandonandonthisisthesongthatnev", - - // This test case was moved from invalid to valid since it is valid input - // when specified with a hostname, it removes the ambiguity from about - // whether the value is an identifier or repository name - "docker.io/1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a", - } - invalidRepoNames := []string{ - "https://github.com/docker/docker", - "docker/Docker", - "-docker", - "-docker/docker", - "-docker.io/docker/docker", - "docker///docker", - "docker.io/docker/Docker", - "docker.io/docker///docker", - "1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a", - } - - for _, name := range invalidRepoNames { - _, err := ParseNormalizedNamed(name) - if err == nil { - t.Fatalf("Expected invalid repo name for %q", name) - } - } - - for _, name := range validRepoNames { - _, err := ParseNormalizedNamed(name) - if err != nil { - t.Fatalf("Error parsing repo name %s, got: %q", name, err) - } - } -} - -func TestValidateRemoteName(t *testing.T) { - validRepositoryNames := []string{ - // Sanity check. - "docker/docker", - - // Allow 64-character non-hexadecimal names (hexadecimal names are forbidden). - "thisisthesongthatneverendsitgoesonandonandonthisisthesongthatnev", - - // Allow embedded hyphens. - "docker-rules/docker", - - // Allow multiple hyphens as well. - "docker---rules/docker", - - //Username doc and image name docker being tested. - "doc/docker", - - // single character names are now allowed. - "d/docker", - "jess/t", - - // Consecutive underscores. - "dock__er/docker", - } - for _, repositoryName := range validRepositoryNames { - _, err := ParseNormalizedNamed(repositoryName) - if err != nil { - t.Errorf("Repository name should be valid: %v. Error: %v", repositoryName, err) - } - } - - invalidRepositoryNames := []string{ - // Disallow capital letters. - "docker/Docker", - - // Only allow one slash. - "docker///docker", - - // Disallow 64-character hexadecimal. - "1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a", - - // Disallow leading and trailing hyphens in namespace. - "-docker/docker", - "docker-/docker", - "-docker-/docker", - - // Don't allow underscores everywhere (as opposed to hyphens). - "____/____", - - "_docker/_docker", - - // Disallow consecutive periods. - "dock..er/docker", - "dock_.er/docker", - "dock-.er/docker", - - // No repository. - "docker/", - - //namespace too long - "this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255_this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255_this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255_this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255/docker", - } - for _, repositoryName := range invalidRepositoryNames { - if _, err := ParseNormalizedNamed(repositoryName); err == nil { - t.Errorf("Repository name should be invalid: %v", repositoryName) - } - } -} - -func TestParseRepositoryInfo(t *testing.T) { - type tcase struct { - RemoteName, FamiliarName, FullName, AmbiguousName, Domain string - } - - tcases := []tcase{ - { - RemoteName: "fooo/bar", - FamiliarName: "fooo/bar", - FullName: "docker.io/fooo/bar", - AmbiguousName: "index.docker.io/fooo/bar", - Domain: "docker.io", - }, - { - RemoteName: "library/ubuntu", - FamiliarName: "ubuntu", - FullName: "docker.io/library/ubuntu", - AmbiguousName: "library/ubuntu", - Domain: "docker.io", - }, - { - RemoteName: "nonlibrary/ubuntu", - FamiliarName: "nonlibrary/ubuntu", - FullName: "docker.io/nonlibrary/ubuntu", - AmbiguousName: "", - Domain: "docker.io", - }, - { - RemoteName: "other/library", - FamiliarName: "other/library", - FullName: "docker.io/other/library", - AmbiguousName: "", - Domain: "docker.io", - }, - { - RemoteName: "private/moonbase", - FamiliarName: "127.0.0.1:8000/private/moonbase", - FullName: "127.0.0.1:8000/private/moonbase", - AmbiguousName: "", - Domain: "127.0.0.1:8000", - }, - { - RemoteName: "privatebase", - FamiliarName: "127.0.0.1:8000/privatebase", - FullName: "127.0.0.1:8000/privatebase", - AmbiguousName: "", - Domain: "127.0.0.1:8000", - }, - { - RemoteName: "private/moonbase", - FamiliarName: "example.com/private/moonbase", - FullName: "example.com/private/moonbase", - AmbiguousName: "", - Domain: "example.com", - }, - { - RemoteName: "privatebase", - FamiliarName: "example.com/privatebase", - FullName: "example.com/privatebase", - AmbiguousName: "", - Domain: "example.com", - }, - { - RemoteName: "private/moonbase", - FamiliarName: "example.com:8000/private/moonbase", - FullName: "example.com:8000/private/moonbase", - AmbiguousName: "", - Domain: "example.com:8000", - }, - { - RemoteName: "privatebasee", - FamiliarName: "example.com:8000/privatebasee", - FullName: "example.com:8000/privatebasee", - AmbiguousName: "", - Domain: "example.com:8000", - }, - { - RemoteName: "library/ubuntu-12.04-base", - FamiliarName: "ubuntu-12.04-base", - FullName: "docker.io/library/ubuntu-12.04-base", - AmbiguousName: "index.docker.io/library/ubuntu-12.04-base", - Domain: "docker.io", - }, - { - RemoteName: "library/foo", - FamiliarName: "foo", - FullName: "docker.io/library/foo", - AmbiguousName: "docker.io/foo", - Domain: "docker.io", - }, - { - RemoteName: "library/foo/bar", - FamiliarName: "library/foo/bar", - FullName: "docker.io/library/foo/bar", - AmbiguousName: "", - Domain: "docker.io", - }, - { - RemoteName: "store/foo/bar", - FamiliarName: "store/foo/bar", - FullName: "docker.io/store/foo/bar", - AmbiguousName: "", - Domain: "docker.io", - }, - } - - for _, tcase := range tcases { - refStrings := []string{tcase.FamiliarName, tcase.FullName} - if tcase.AmbiguousName != "" { - refStrings = append(refStrings, tcase.AmbiguousName) - } - - var refs []Named - for _, r := range refStrings { - named, err := ParseNormalizedNamed(r) - if err != nil { - t.Fatal(err) - } - refs = append(refs, named) - } - - for _, r := range refs { - if expected, actual := tcase.FamiliarName, FamiliarName(r); expected != actual { - t.Fatalf("Invalid normalized reference for %q. Expected %q, got %q", r, expected, actual) - } - if expected, actual := tcase.FullName, r.String(); expected != actual { - t.Fatalf("Invalid canonical reference for %q. Expected %q, got %q", r, expected, actual) - } - if expected, actual := tcase.Domain, Domain(r); expected != actual { - t.Fatalf("Invalid domain for %q. Expected %q, got %q", r, expected, actual) - } - if expected, actual := tcase.RemoteName, Path(r); expected != actual { - t.Fatalf("Invalid remoteName for %q. Expected %q, got %q", r, expected, actual) - } - - } - } -} - -func TestParseReferenceWithTagAndDigest(t *testing.T) { - shortRef := "busybox:latest@sha256:86e0e091d0da6bde2456dbb48306f3956bbeb2eae1b5b9a43045843f69fe4aaa" - ref, err := ParseNormalizedNamed(shortRef) - if err != nil { - t.Fatal(err) - } - if expected, actual := "docker.io/library/"+shortRef, ref.String(); actual != expected { - t.Fatalf("Invalid parsed reference for %q: expected %q, got %q", ref, expected, actual) - } - - if _, isTagged := ref.(NamedTagged); !isTagged { - t.Fatalf("Reference from %q should support tag", ref) - } - if _, isCanonical := ref.(Canonical); !isCanonical { - t.Fatalf("Reference from %q should support digest", ref) - } - if expected, actual := shortRef, FamiliarString(ref); actual != expected { - t.Fatalf("Invalid parsed reference for %q: expected %q, got %q", ref, expected, actual) - } -} - -func TestInvalidReferenceComponents(t *testing.T) { - if _, err := ParseNormalizedNamed("-foo"); err == nil { - t.Fatal("Expected WithName to detect invalid name") - } - ref, err := ParseNormalizedNamed("busybox") - if err != nil { - t.Fatal(err) - } - if _, err := WithTag(ref, "-foo"); err == nil { - t.Fatal("Expected WithName to detect invalid tag") - } - if _, err := WithDigest(ref, digest.Digest("foo")); err == nil { - t.Fatal("Expected WithDigest to detect invalid digest") - } -} - -func equalReference(r1, r2 Reference) bool { - switch v1 := r1.(type) { - case digestReference: - if v2, ok := r2.(digestReference); ok { - return v1 == v2 - } - case repository: - if v2, ok := r2.(repository); ok { - return v1 == v2 - } - case taggedReference: - if v2, ok := r2.(taggedReference); ok { - return v1 == v2 - } - case canonicalReference: - if v2, ok := r2.(canonicalReference); ok { - return v1 == v2 - } - case reference: - if v2, ok := r2.(reference); ok { - return v1 == v2 - } - } - return false -} - -func TestParseAnyReference(t *testing.T) { - tcases := []struct { - Reference string - Equivalent string - Expected Reference - Digests []digest.Digest - }{ - { - Reference: "redis", - Equivalent: "docker.io/library/redis", - }, - { - Reference: "redis:latest", - Equivalent: "docker.io/library/redis:latest", - }, - { - Reference: "docker.io/library/redis:latest", - Equivalent: "docker.io/library/redis:latest", - }, - { - Reference: "redis@sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - Equivalent: "docker.io/library/redis@sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - }, - { - Reference: "docker.io/library/redis@sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - Equivalent: "docker.io/library/redis@sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - }, - { - Reference: "dmcgowan/myapp", - Equivalent: "docker.io/dmcgowan/myapp", - }, - { - Reference: "dmcgowan/myapp:latest", - Equivalent: "docker.io/dmcgowan/myapp:latest", - }, - { - Reference: "docker.io/mcgowan/myapp:latest", - Equivalent: "docker.io/mcgowan/myapp:latest", - }, - { - Reference: "dmcgowan/myapp@sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - Equivalent: "docker.io/dmcgowan/myapp@sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - }, - { - Reference: "docker.io/dmcgowan/myapp@sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - Equivalent: "docker.io/dmcgowan/myapp@sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - }, - { - Reference: "dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - Expected: digestReference("sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - Equivalent: "sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - }, - { - Reference: "sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - Expected: digestReference("sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - Equivalent: "sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - }, - { - Reference: "dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9", - Equivalent: "docker.io/library/dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9", - }, - { - Reference: "dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9", - Expected: digestReference("sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - Equivalent: "sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - Digests: []digest.Digest{ - digest.Digest("sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - digest.Digest("sha256:abcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - }, - }, - { - Reference: "dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9", - Equivalent: "docker.io/library/dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9", - Digests: []digest.Digest{ - digest.Digest("sha256:abcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - }, - }, - { - Reference: "dbcc1c", - Expected: digestReference("sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - Equivalent: "sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c", - Digests: []digest.Digest{ - digest.Digest("sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - digest.Digest("sha256:abcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - }, - }, - { - Reference: "dbcc1", - Equivalent: "docker.io/library/dbcc1", - Digests: []digest.Digest{ - digest.Digest("sha256:dbcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - digest.Digest("sha256:abcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - }, - }, - { - Reference: "dbcc1c", - Equivalent: "docker.io/library/dbcc1c", - Digests: []digest.Digest{ - digest.Digest("sha256:abcc1c35ac38df41fd2f5e4130b32ffdb93ebae8b3dbe638c23575912276fc9c"), - }, - }, - } - - for _, tcase := range tcases { - var ref Reference - var err error - if len(tcase.Digests) == 0 { - ref, err = ParseAnyReference(tcase.Reference) - } else { - ds := digestset.NewSet() - for _, dgst := range tcase.Digests { - if err := ds.Add(dgst); err != nil { - t.Fatalf("Error adding digest %s: %v", dgst.String(), err) - } - } - ref, err = ParseAnyReferenceWithSet(tcase.Reference, ds) - } - if err != nil { - t.Fatalf("Error parsing reference %s: %v", tcase.Reference, err) - } - if ref.String() != tcase.Equivalent { - t.Fatalf("Unexpected string: %s, expected %s", ref.String(), tcase.Equivalent) - } - - expected := tcase.Expected - if expected == nil { - expected, err = Parse(tcase.Equivalent) - if err != nil { - t.Fatalf("Error parsing reference %s: %v", tcase.Equivalent, err) - } - } - if !equalReference(ref, expected) { - t.Errorf("Unexpected reference %#v, expected %#v", ref, expected) - } - } -} - -func TestNormalizedSplitHostname(t *testing.T) { - testcases := []struct { - input string - domain string - name string - }{ - { - input: "test.com/foo", - domain: "test.com", - name: "foo", - }, - { - input: "test_com/foo", - domain: "docker.io", - name: "test_com/foo", - }, - { - input: "docker/migrator", - domain: "docker.io", - name: "docker/migrator", - }, - { - input: "test.com:8080/foo", - domain: "test.com:8080", - name: "foo", - }, - { - input: "test-com:8080/foo", - domain: "test-com:8080", - name: "foo", - }, - { - input: "foo", - domain: "docker.io", - name: "library/foo", - }, - { - input: "xn--n3h.com/foo", - domain: "xn--n3h.com", - name: "foo", - }, - { - input: "xn--n3h.com:18080/foo", - domain: "xn--n3h.com:18080", - name: "foo", - }, - { - input: "docker.io/foo", - domain: "docker.io", - name: "library/foo", - }, - { - input: "docker.io/library/foo", - domain: "docker.io", - name: "library/foo", - }, - { - input: "docker.io/library/foo/bar", - domain: "docker.io", - name: "library/foo/bar", - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.input)+": "+format, v...) - t.Fail() - } - - named, err := ParseNormalizedNamed(testcase.input) - if err != nil { - failf("error parsing name: %s", err) - } - domain, name := SplitHostname(named) - if domain != testcase.domain { - failf("unexpected domain: got %q, expected %q", domain, testcase.domain) - } - if name != testcase.name { - failf("unexpected name: got %q, expected %q", name, testcase.name) - } - } -} - -func TestMatchError(t *testing.T) { - named, err := ParseAnyReference("foo") - if err != nil { - t.Fatal(err) - } - _, err = FamiliarMatch("[-x]", named) - if err == nil { - t.Fatalf("expected an error, got nothing") - } -} - -func TestMatch(t *testing.T) { - matchCases := []struct { - reference string - pattern string - expected bool - }{ - { - reference: "foo", - pattern: "foo/**/ba[rz]", - expected: false, - }, - { - reference: "foo/any/bat", - pattern: "foo/**/ba[rz]", - expected: false, - }, - { - reference: "foo/a/bar", - pattern: "foo/**/ba[rz]", - expected: true, - }, - { - reference: "foo/b/baz", - pattern: "foo/**/ba[rz]", - expected: true, - }, - { - reference: "foo/c/baz:tag", - pattern: "foo/**/ba[rz]", - expected: true, - }, - { - reference: "foo/c/baz:tag", - pattern: "foo/*/baz:tag", - expected: true, - }, - { - reference: "foo/c/baz:tag", - pattern: "foo/c/baz:tag", - expected: true, - }, - { - reference: "example.com/foo/c/baz:tag", - pattern: "*/foo/c/baz", - expected: true, - }, - { - reference: "example.com/foo/c/baz:tag", - pattern: "example.com/foo/c/baz", - expected: true, - }, - } - for _, c := range matchCases { - named, err := ParseAnyReference(c.reference) - if err != nil { - t.Fatal(err) - } - actual, err := FamiliarMatch(c.pattern, named) - if err != nil { - t.Fatal(err) - } - if actual != c.expected { - t.Fatalf("expected %s match %s to be %v, was %v", c.reference, c.pattern, c.expected, actual) - } - } -} diff --git a/vendor/github.com/docker/distribution/reference/reference_test.go b/vendor/github.com/docker/distribution/reference/reference_test.go deleted file mode 100644 index 16b871f987..0000000000 --- a/vendor/github.com/docker/distribution/reference/reference_test.go +++ /dev/null @@ -1,659 +0,0 @@ -package reference - -import ( - _ "crypto/sha256" - _ "crypto/sha512" - "encoding/json" - "strconv" - "strings" - "testing" - - "github.com/opencontainers/go-digest" -) - -func TestReferenceParse(t *testing.T) { - // referenceTestcases is a unified set of testcases for - // testing the parsing of references - referenceTestcases := []struct { - // input is the repository name or name component testcase - input string - // err is the error expected from Parse, or nil - err error - // repository is the string representation for the reference - repository string - // domain is the domain expected in the reference - domain string - // tag is the tag for the reference - tag string - // digest is the digest for the reference (enforces digest reference) - digest string - }{ - { - input: "test_com", - repository: "test_com", - }, - { - input: "test.com:tag", - repository: "test.com", - tag: "tag", - }, - { - input: "test.com:5000", - repository: "test.com", - tag: "5000", - }, - { - input: "test.com/repo:tag", - domain: "test.com", - repository: "test.com/repo", - tag: "tag", - }, - { - input: "test:5000/repo", - domain: "test:5000", - repository: "test:5000/repo", - }, - { - input: "test:5000/repo:tag", - domain: "test:5000", - repository: "test:5000/repo", - tag: "tag", - }, - { - input: "test:5000/repo@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - domain: "test:5000", - repository: "test:5000/repo", - digest: "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - }, - { - input: "test:5000/repo:tag@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - domain: "test:5000", - repository: "test:5000/repo", - tag: "tag", - digest: "sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - }, - { - input: "test:5000/repo", - domain: "test:5000", - repository: "test:5000/repo", - }, - { - input: "", - err: ErrNameEmpty, - }, - { - input: ":justtag", - err: ErrReferenceInvalidFormat, - }, - { - input: "@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - err: ErrReferenceInvalidFormat, - }, - { - input: "repo@sha256:ffffffffffffffffffffffffffffffffff", - err: digest.ErrDigestInvalidLength, - }, - { - input: "validname@invaliddigest:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - err: digest.ErrDigestUnsupported, - }, - { - input: "Uppercase:tag", - err: ErrNameContainsUppercase, - }, - // FIXME "Uppercase" is incorrectly handled as a domain-name here, therefore passes. - // See https://github.com/docker/distribution/pull/1778, and https://github.com/docker/docker/pull/20175 - //{ - // input: "Uppercase/lowercase:tag", - // err: ErrNameContainsUppercase, - //}, - { - input: "test:5000/Uppercase/lowercase:tag", - err: ErrNameContainsUppercase, - }, - { - input: "lowercase:Uppercase", - repository: "lowercase", - tag: "Uppercase", - }, - { - input: strings.Repeat("a/", 128) + "a:tag", - err: ErrNameTooLong, - }, - { - input: strings.Repeat("a/", 127) + "a:tag-puts-this-over-max", - domain: "a", - repository: strings.Repeat("a/", 127) + "a", - tag: "tag-puts-this-over-max", - }, - { - input: "aa/asdf$$^/aa", - err: ErrReferenceInvalidFormat, - }, - { - input: "sub-dom1.foo.com/bar/baz/quux", - domain: "sub-dom1.foo.com", - repository: "sub-dom1.foo.com/bar/baz/quux", - }, - { - input: "sub-dom1.foo.com/bar/baz/quux:some-long-tag", - domain: "sub-dom1.foo.com", - repository: "sub-dom1.foo.com/bar/baz/quux", - tag: "some-long-tag", - }, - { - input: "b.gcr.io/test.example.com/my-app:test.example.com", - domain: "b.gcr.io", - repository: "b.gcr.io/test.example.com/my-app", - tag: "test.example.com", - }, - { - input: "xn--n3h.com/myimage:xn--n3h.com", // ☃.com in punycode - domain: "xn--n3h.com", - repository: "xn--n3h.com/myimage", - tag: "xn--n3h.com", - }, - { - input: "xn--7o8h.com/myimage:xn--7o8h.com@sha512:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", // 🐳.com in punycode - domain: "xn--7o8h.com", - repository: "xn--7o8h.com/myimage", - tag: "xn--7o8h.com", - digest: "sha512:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - }, - { - input: "foo_bar.com:8080", - repository: "foo_bar.com", - tag: "8080", - }, - { - input: "foo/foo_bar.com:8080", - domain: "foo", - repository: "foo/foo_bar.com", - tag: "8080", - }, - } - for _, testcase := range referenceTestcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.input)+": "+format, v...) - t.Fail() - } - - repo, err := Parse(testcase.input) - if testcase.err != nil { - if err == nil { - failf("missing expected error: %v", testcase.err) - } else if testcase.err != err { - failf("mismatched error: got %v, expected %v", err, testcase.err) - } - continue - } else if err != nil { - failf("unexpected parse error: %v", err) - continue - } - if repo.String() != testcase.input { - failf("mismatched repo: got %q, expected %q", repo.String(), testcase.input) - } - - if named, ok := repo.(Named); ok { - if named.Name() != testcase.repository { - failf("unexpected repository: got %q, expected %q", named.Name(), testcase.repository) - } - domain, _ := SplitHostname(named) - if domain != testcase.domain { - failf("unexpected domain: got %q, expected %q", domain, testcase.domain) - } - } else if testcase.repository != "" || testcase.domain != "" { - failf("expected named type, got %T", repo) - } - - tagged, ok := repo.(Tagged) - if testcase.tag != "" { - if ok { - if tagged.Tag() != testcase.tag { - failf("unexpected tag: got %q, expected %q", tagged.Tag(), testcase.tag) - } - } else { - failf("expected tagged type, got %T", repo) - } - } else if ok { - failf("unexpected tagged type") - } - - digested, ok := repo.(Digested) - if testcase.digest != "" { - if ok { - if digested.Digest().String() != testcase.digest { - failf("unexpected digest: got %q, expected %q", digested.Digest().String(), testcase.digest) - } - } else { - failf("expected digested type, got %T", repo) - } - } else if ok { - failf("unexpected digested type") - } - - } -} - -// TestWithNameFailure tests cases where WithName should fail. Cases where it -// should succeed are covered by TestSplitHostname, below. -func TestWithNameFailure(t *testing.T) { - testcases := []struct { - input string - err error - }{ - { - input: "", - err: ErrNameEmpty, - }, - { - input: ":justtag", - err: ErrReferenceInvalidFormat, - }, - { - input: "@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - err: ErrReferenceInvalidFormat, - }, - { - input: "validname@invaliddigest:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - err: ErrReferenceInvalidFormat, - }, - { - input: strings.Repeat("a/", 128) + "a:tag", - err: ErrNameTooLong, - }, - { - input: "aa/asdf$$^/aa", - err: ErrReferenceInvalidFormat, - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.input)+": "+format, v...) - t.Fail() - } - - _, err := WithName(testcase.input) - if err == nil { - failf("no error parsing name. expected: %s", testcase.err) - } - } -} - -func TestSplitHostname(t *testing.T) { - testcases := []struct { - input string - domain string - name string - }{ - { - input: "test.com/foo", - domain: "test.com", - name: "foo", - }, - { - input: "test_com/foo", - domain: "", - name: "test_com/foo", - }, - { - input: "test:8080/foo", - domain: "test:8080", - name: "foo", - }, - { - input: "test.com:8080/foo", - domain: "test.com:8080", - name: "foo", - }, - { - input: "test-com:8080/foo", - domain: "test-com:8080", - name: "foo", - }, - { - input: "xn--n3h.com:18080/foo", - domain: "xn--n3h.com:18080", - name: "foo", - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.input)+": "+format, v...) - t.Fail() - } - - named, err := WithName(testcase.input) - if err != nil { - failf("error parsing name: %s", err) - } - domain, name := SplitHostname(named) - if domain != testcase.domain { - failf("unexpected domain: got %q, expected %q", domain, testcase.domain) - } - if name != testcase.name { - failf("unexpected name: got %q, expected %q", name, testcase.name) - } - } -} - -type serializationType struct { - Description string - Field Field -} - -func TestSerialization(t *testing.T) { - testcases := []struct { - description string - input string - name string - tag string - digest string - err error - }{ - { - description: "empty value", - err: ErrNameEmpty, - }, - { - description: "just a name", - input: "example.com:8000/named", - name: "example.com:8000/named", - }, - { - description: "name with a tag", - input: "example.com:8000/named:tagged", - name: "example.com:8000/named", - tag: "tagged", - }, - { - description: "name with digest", - input: "other.com/named@sha256:1234567890098765432112345667890098765432112345667890098765432112", - name: "other.com/named", - digest: "sha256:1234567890098765432112345667890098765432112345667890098765432112", - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.input)+": "+format, v...) - t.Fail() - } - - m := map[string]string{ - "Description": testcase.description, - "Field": testcase.input, - } - b, err := json.Marshal(m) - if err != nil { - failf("error marshalling: %v", err) - } - t := serializationType{} - - if err := json.Unmarshal(b, &t); err != nil { - if testcase.err == nil { - failf("error unmarshalling: %v", err) - } - if err != testcase.err { - failf("wrong error, expected %v, got %v", testcase.err, err) - } - - continue - } else if testcase.err != nil { - failf("expected error unmarshalling: %v", testcase.err) - } - - if t.Description != testcase.description { - failf("wrong description, expected %q, got %q", testcase.description, t.Description) - } - - ref := t.Field.Reference() - - if named, ok := ref.(Named); ok { - if named.Name() != testcase.name { - failf("unexpected repository: got %q, expected %q", named.Name(), testcase.name) - } - } else if testcase.name != "" { - failf("expected named type, got %T", ref) - } - - tagged, ok := ref.(Tagged) - if testcase.tag != "" { - if ok { - if tagged.Tag() != testcase.tag { - failf("unexpected tag: got %q, expected %q", tagged.Tag(), testcase.tag) - } - } else { - failf("expected tagged type, got %T", ref) - } - } else if ok { - failf("unexpected tagged type") - } - - digested, ok := ref.(Digested) - if testcase.digest != "" { - if ok { - if digested.Digest().String() != testcase.digest { - failf("unexpected digest: got %q, expected %q", digested.Digest().String(), testcase.digest) - } - } else { - failf("expected digested type, got %T", ref) - } - } else if ok { - failf("unexpected digested type") - } - - t = serializationType{ - Description: testcase.description, - Field: AsField(ref), - } - - b2, err := json.Marshal(t) - if err != nil { - failf("error marshing serialization type: %v", err) - } - - if string(b) != string(b2) { - failf("unexpected serialized value: expected %q, got %q", string(b), string(b2)) - } - - // Ensure t.Field is not implementing "Reference" directly, getting - // around the Reference type system - var fieldInterface interface{} = t.Field - if _, ok := fieldInterface.(Reference); ok { - failf("field should not implement Reference interface") - } - - } -} - -func TestWithTag(t *testing.T) { - testcases := []struct { - name string - digest digest.Digest - tag string - combined string - }{ - { - name: "test.com/foo", - tag: "tag", - combined: "test.com/foo:tag", - }, - { - name: "foo", - tag: "tag2", - combined: "foo:tag2", - }, - { - name: "test.com:8000/foo", - tag: "tag4", - combined: "test.com:8000/foo:tag4", - }, - { - name: "test.com:8000/foo", - tag: "TAG5", - combined: "test.com:8000/foo:TAG5", - }, - { - name: "test.com:8000/foo", - digest: "sha256:1234567890098765432112345667890098765", - tag: "TAG5", - combined: "test.com:8000/foo:TAG5@sha256:1234567890098765432112345667890098765", - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.name)+": "+format, v...) - t.Fail() - } - - named, err := WithName(testcase.name) - if err != nil { - failf("error parsing name: %s", err) - } - if testcase.digest != "" { - canonical, err := WithDigest(named, testcase.digest) - if err != nil { - failf("error adding digest") - } - named = canonical - } - - tagged, err := WithTag(named, testcase.tag) - if err != nil { - failf("WithTag failed: %s", err) - } - if tagged.String() != testcase.combined { - failf("unexpected: got %q, expected %q", tagged.String(), testcase.combined) - } - } -} - -func TestWithDigest(t *testing.T) { - testcases := []struct { - name string - digest digest.Digest - tag string - combined string - }{ - { - name: "test.com/foo", - digest: "sha256:1234567890098765432112345667890098765", - combined: "test.com/foo@sha256:1234567890098765432112345667890098765", - }, - { - name: "foo", - digest: "sha256:1234567890098765432112345667890098765", - combined: "foo@sha256:1234567890098765432112345667890098765", - }, - { - name: "test.com:8000/foo", - digest: "sha256:1234567890098765432112345667890098765", - combined: "test.com:8000/foo@sha256:1234567890098765432112345667890098765", - }, - { - name: "test.com:8000/foo", - digest: "sha256:1234567890098765432112345667890098765", - tag: "latest", - combined: "test.com:8000/foo:latest@sha256:1234567890098765432112345667890098765", - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.name)+": "+format, v...) - t.Fail() - } - - named, err := WithName(testcase.name) - if err != nil { - failf("error parsing name: %s", err) - } - if testcase.tag != "" { - tagged, err := WithTag(named, testcase.tag) - if err != nil { - failf("error adding tag") - } - named = tagged - } - digested, err := WithDigest(named, testcase.digest) - if err != nil { - failf("WithDigest failed: %s", err) - } - if digested.String() != testcase.combined { - failf("unexpected: got %q, expected %q", digested.String(), testcase.combined) - } - } -} - -func TestParseNamed(t *testing.T) { - testcases := []struct { - input string - domain string - name string - err error - }{ - { - input: "test.com/foo", - domain: "test.com", - name: "foo", - }, - { - input: "test:8080/foo", - domain: "test:8080", - name: "foo", - }, - { - input: "test_com/foo", - err: ErrNameNotCanonical, - }, - { - input: "test.com", - err: ErrNameNotCanonical, - }, - { - input: "foo", - err: ErrNameNotCanonical, - }, - { - input: "library/foo", - err: ErrNameNotCanonical, - }, - { - input: "docker.io/library/foo", - domain: "docker.io", - name: "library/foo", - }, - // Ambiguous case, parser will add "library/" to foo - { - input: "docker.io/foo", - err: ErrNameNotCanonical, - }, - } - for _, testcase := range testcases { - failf := func(format string, v ...interface{}) { - t.Logf(strconv.Quote(testcase.input)+": "+format, v...) - t.Fail() - } - - named, err := ParseNamed(testcase.input) - if err != nil && testcase.err == nil { - failf("error parsing name: %s", err) - continue - } else if err == nil && testcase.err != nil { - failf("parsing succeded: expected error %v", testcase.err) - continue - } else if err != testcase.err { - failf("unexpected error %v, expected %v", err, testcase.err) - continue - } else if err != nil { - continue - } - - domain, name := SplitHostname(named) - if domain != testcase.domain { - failf("unexpected domain: got %q, expected %q", domain, testcase.domain) - } - if name != testcase.name { - failf("unexpected name: got %q, expected %q", name, testcase.name) - } - } -} diff --git a/vendor/github.com/docker/distribution/reference/regexp_test.go b/vendor/github.com/docker/distribution/reference/regexp_test.go deleted file mode 100644 index 09bc819275..0000000000 --- a/vendor/github.com/docker/distribution/reference/regexp_test.go +++ /dev/null @@ -1,553 +0,0 @@ -package reference - -import ( - "regexp" - "strings" - "testing" -) - -type regexpMatch struct { - input string - match bool - subs []string -} - -func checkRegexp(t *testing.T, r *regexp.Regexp, m regexpMatch) { - matches := r.FindStringSubmatch(m.input) - if m.match && matches != nil { - if len(matches) != (r.NumSubexp()+1) || matches[0] != m.input { - t.Fatalf("Bad match result %#v for %q", matches, m.input) - } - if len(matches) < (len(m.subs) + 1) { - t.Errorf("Expected %d sub matches, only have %d for %q", len(m.subs), len(matches)-1, m.input) - } - for i := range m.subs { - if m.subs[i] != matches[i+1] { - t.Errorf("Unexpected submatch %d: %q, expected %q for %q", i+1, matches[i+1], m.subs[i], m.input) - } - } - } else if m.match { - t.Errorf("Expected match for %q", m.input) - } else if matches != nil { - t.Errorf("Unexpected match for %q", m.input) - } -} - -func TestDomainRegexp(t *testing.T) { - hostcases := []regexpMatch{ - { - input: "test.com", - match: true, - }, - { - input: "test.com:10304", - match: true, - }, - { - input: "test.com:http", - match: false, - }, - { - input: "localhost", - match: true, - }, - { - input: "localhost:8080", - match: true, - }, - { - input: "a", - match: true, - }, - { - input: "a.b", - match: true, - }, - { - input: "ab.cd.com", - match: true, - }, - { - input: "a-b.com", - match: true, - }, - { - input: "-ab.com", - match: false, - }, - { - input: "ab-.com", - match: false, - }, - { - input: "ab.c-om", - match: true, - }, - { - input: "ab.-com", - match: false, - }, - { - input: "ab.com-", - match: false, - }, - { - input: "0101.com", - match: true, // TODO(dmcgowan): valid if this should be allowed - }, - { - input: "001a.com", - match: true, - }, - { - input: "b.gbc.io:443", - match: true, - }, - { - input: "b.gbc.io", - match: true, - }, - { - input: "xn--n3h.com", // ☃.com in punycode - match: true, - }, - { - input: "Asdf.com", // uppercase character - match: true, - }, - } - r := regexp.MustCompile(`^` + DomainRegexp.String() + `$`) - for i := range hostcases { - checkRegexp(t, r, hostcases[i]) - } -} - -func TestFullNameRegexp(t *testing.T) { - if anchoredNameRegexp.NumSubexp() != 2 { - t.Fatalf("anchored name regexp should have two submatches: %v, %v != 2", - anchoredNameRegexp, anchoredNameRegexp.NumSubexp()) - } - - testcases := []regexpMatch{ - { - input: "", - match: false, - }, - { - input: "short", - match: true, - subs: []string{"", "short"}, - }, - { - input: "simple/name", - match: true, - subs: []string{"simple", "name"}, - }, - { - input: "library/ubuntu", - match: true, - subs: []string{"library", "ubuntu"}, - }, - { - input: "docker/stevvooe/app", - match: true, - subs: []string{"docker", "stevvooe/app"}, - }, - { - input: "aa/aa/aa/aa/aa/aa/aa/aa/aa/bb/bb/bb/bb/bb/bb", - match: true, - subs: []string{"aa", "aa/aa/aa/aa/aa/aa/aa/aa/bb/bb/bb/bb/bb/bb"}, - }, - { - input: "aa/aa/bb/bb/bb", - match: true, - subs: []string{"aa", "aa/bb/bb/bb"}, - }, - { - input: "a/a/a/a", - match: true, - subs: []string{"a", "a/a/a"}, - }, - { - input: "a/a/a/a/", - match: false, - }, - { - input: "a//a/a", - match: false, - }, - { - input: "a", - match: true, - subs: []string{"", "a"}, - }, - { - input: "a/aa", - match: true, - subs: []string{"a", "aa"}, - }, - { - input: "a/aa/a", - match: true, - subs: []string{"a", "aa/a"}, - }, - { - input: "foo.com", - match: true, - subs: []string{"", "foo.com"}, - }, - { - input: "foo.com/", - match: false, - }, - { - input: "foo.com:8080/bar", - match: true, - subs: []string{"foo.com:8080", "bar"}, - }, - { - input: "foo.com:http/bar", - match: false, - }, - { - input: "foo.com/bar", - match: true, - subs: []string{"foo.com", "bar"}, - }, - { - input: "foo.com/bar/baz", - match: true, - subs: []string{"foo.com", "bar/baz"}, - }, - { - input: "localhost:8080/bar", - match: true, - subs: []string{"localhost:8080", "bar"}, - }, - { - input: "sub-dom1.foo.com/bar/baz/quux", - match: true, - subs: []string{"sub-dom1.foo.com", "bar/baz/quux"}, - }, - { - input: "blog.foo.com/bar/baz", - match: true, - subs: []string{"blog.foo.com", "bar/baz"}, - }, - { - input: "a^a", - match: false, - }, - { - input: "aa/asdf$$^/aa", - match: false, - }, - { - input: "asdf$$^/aa", - match: false, - }, - { - input: "aa-a/a", - match: true, - subs: []string{"aa-a", "a"}, - }, - { - input: strings.Repeat("a/", 128) + "a", - match: true, - subs: []string{"a", strings.Repeat("a/", 127) + "a"}, - }, - { - input: "a-/a/a/a", - match: false, - }, - { - input: "foo.com/a-/a/a", - match: false, - }, - { - input: "-foo/bar", - match: false, - }, - { - input: "foo/bar-", - match: false, - }, - { - input: "foo-/bar", - match: false, - }, - { - input: "foo/-bar", - match: false, - }, - { - input: "_foo/bar", - match: false, - }, - { - input: "foo_bar", - match: true, - subs: []string{"", "foo_bar"}, - }, - { - input: "foo_bar.com", - match: true, - subs: []string{"", "foo_bar.com"}, - }, - { - input: "foo_bar.com:8080", - match: false, - }, - { - input: "foo_bar.com:8080/app", - match: false, - }, - { - input: "foo.com/foo_bar", - match: true, - subs: []string{"foo.com", "foo_bar"}, - }, - { - input: "____/____", - match: false, - }, - { - input: "_docker/_docker", - match: false, - }, - { - input: "docker_/docker_", - match: false, - }, - { - input: "b.gcr.io/test.example.com/my-app", - match: true, - subs: []string{"b.gcr.io", "test.example.com/my-app"}, - }, - { - input: "xn--n3h.com/myimage", // ☃.com in punycode - match: true, - subs: []string{"xn--n3h.com", "myimage"}, - }, - { - input: "xn--7o8h.com/myimage", // 🐳.com in punycode - match: true, - subs: []string{"xn--7o8h.com", "myimage"}, - }, - { - input: "example.com/xn--7o8h.com/myimage", // 🐳.com in punycode - match: true, - subs: []string{"example.com", "xn--7o8h.com/myimage"}, - }, - { - input: "example.com/some_separator__underscore/myimage", - match: true, - subs: []string{"example.com", "some_separator__underscore/myimage"}, - }, - { - input: "example.com/__underscore/myimage", - match: false, - }, - { - input: "example.com/..dots/myimage", - match: false, - }, - { - input: "example.com/.dots/myimage", - match: false, - }, - { - input: "example.com/nodouble..dots/myimage", - match: false, - }, - { - input: "example.com/nodouble..dots/myimage", - match: false, - }, - { - input: "docker./docker", - match: false, - }, - { - input: ".docker/docker", - match: false, - }, - { - input: "docker-/docker", - match: false, - }, - { - input: "-docker/docker", - match: false, - }, - { - input: "do..cker/docker", - match: false, - }, - { - input: "do__cker:8080/docker", - match: false, - }, - { - input: "do__cker/docker", - match: true, - subs: []string{"", "do__cker/docker"}, - }, - { - input: "b.gcr.io/test.example.com/my-app", - match: true, - subs: []string{"b.gcr.io", "test.example.com/my-app"}, - }, - { - input: "registry.io/foo/project--id.module--name.ver---sion--name", - match: true, - subs: []string{"registry.io", "foo/project--id.module--name.ver---sion--name"}, - }, - { - input: "Asdf.com/foo/bar", // uppercase character in hostname - match: true, - }, - { - input: "Foo/FarB", // uppercase characters in remote name - match: false, - }, - } - for i := range testcases { - checkRegexp(t, anchoredNameRegexp, testcases[i]) - } -} - -func TestReferenceRegexp(t *testing.T) { - if ReferenceRegexp.NumSubexp() != 3 { - t.Fatalf("anchored name regexp should have three submatches: %v, %v != 3", - ReferenceRegexp, ReferenceRegexp.NumSubexp()) - } - - testcases := []regexpMatch{ - { - input: "registry.com:8080/myapp:tag", - match: true, - subs: []string{"registry.com:8080/myapp", "tag", ""}, - }, - { - input: "registry.com:8080/myapp@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: true, - subs: []string{"registry.com:8080/myapp", "", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"}, - }, - { - input: "registry.com:8080/myapp:tag2@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: true, - subs: []string{"registry.com:8080/myapp", "tag2", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"}, - }, - { - input: "registry.com:8080/myapp@sha256:badbadbadbad", - match: false, - }, - { - input: "registry.com:8080/myapp:invalid~tag", - match: false, - }, - { - input: "bad_hostname.com:8080/myapp:tag", - match: false, - }, - { - input:// localhost treated as name, missing tag with 8080 as tag - "localhost:8080@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: true, - subs: []string{"localhost", "8080", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"}, - }, - { - input: "localhost:8080/name@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: true, - subs: []string{"localhost:8080/name", "", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"}, - }, - { - input: "localhost:http/name@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: false, - }, - { - // localhost will be treated as an image name without a host - input: "localhost@sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912", - match: true, - subs: []string{"localhost", "", "sha256:be178c0543eb17f5f3043021c9e5fcf30285e557a4fc309cce97ff9ca6182912"}, - }, - { - input: "registry.com:8080/myapp@bad", - match: false, - }, - { - input: "registry.com:8080/myapp@2bad", - match: false, // TODO(dmcgowan): Support this as valid - }, - } - - for i := range testcases { - checkRegexp(t, ReferenceRegexp, testcases[i]) - } - -} - -func TestIdentifierRegexp(t *testing.T) { - fullCases := []regexpMatch{ - { - input: "da304e823d8ca2b9d863a3c897baeb852ba21ea9a9f1414736394ae7fcaf9821", - match: true, - }, - { - input: "7EC43B381E5AEFE6E04EFB0B3F0693FF2A4A50652D64AEC573905F2DB5889A1C", - match: false, - }, - { - input: "da304e823d8ca2b9d863a3c897baeb852ba21ea9a9f1414736394ae7fcaf", - match: false, - }, - { - input: "sha256:da304e823d8ca2b9d863a3c897baeb852ba21ea9a9f1414736394ae7fcaf9821", - match: false, - }, - { - input: "da304e823d8ca2b9d863a3c897baeb852ba21ea9a9f1414736394ae7fcaf98218482", - match: false, - }, - } - - shortCases := []regexpMatch{ - { - input: "da304e823d8ca2b9d863a3c897baeb852ba21ea9a9f1414736394ae7fcaf9821", - match: true, - }, - { - input: "7EC43B381E5AEFE6E04EFB0B3F0693FF2A4A50652D64AEC573905F2DB5889A1C", - match: false, - }, - { - input: "da304e823d8ca2b9d863a3c897baeb852ba21ea9a9f1414736394ae7fcaf", - match: true, - }, - { - input: "sha256:da304e823d8ca2b9d863a3c897baeb852ba21ea9a9f1414736394ae7fcaf9821", - match: false, - }, - { - input: "da304e823d8ca2b9d863a3c897baeb852ba21ea9a9f1414736394ae7fcaf98218482", - match: false, - }, - { - input: "da304", - match: false, - }, - { - input: "da304e", - match: true, - }, - } - - for i := range fullCases { - checkRegexp(t, anchoredIdentifierRegexp, fullCases[i]) - } - - for i := range shortCases { - checkRegexp(t, anchoredShortIdentifierRegexp, shortCases[i]) - } -} diff --git a/vendor/github.com/docker/spdystream/priority_test.go b/vendor/github.com/docker/spdystream/priority_test.go deleted file mode 100644 index 0746be2a80..0000000000 --- a/vendor/github.com/docker/spdystream/priority_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package spdystream - -import ( - "sync" - "testing" - "time" - - "github.com/docker/spdystream/spdy" -) - -func TestPriorityQueueOrdering(t *testing.T) { - queue := NewPriorityFrameQueue(150) - data1 := &spdy.DataFrame{} - data2 := &spdy.DataFrame{} - data3 := &spdy.DataFrame{} - data4 := &spdy.DataFrame{} - queue.Push(data1, 2) - queue.Push(data2, 1) - queue.Push(data3, 1) - queue.Push(data4, 0) - - if queue.Pop() != data4 { - t.Fatalf("Wrong order, expected data4 first") - } - if queue.Pop() != data2 { - t.Fatalf("Wrong order, expected data2 second") - } - if queue.Pop() != data3 { - t.Fatalf("Wrong order, expected data3 third") - } - if queue.Pop() != data1 { - t.Fatalf("Wrong order, expected data1 fourth") - } - - // Insert 50 Medium priority frames - for i := spdy.StreamId(50); i < 100; i++ { - queue.Push(&spdy.DataFrame{StreamId: i}, 1) - } - // Insert 50 low priority frames - for i := spdy.StreamId(100); i < 150; i++ { - queue.Push(&spdy.DataFrame{StreamId: i}, 2) - } - // Insert 50 high priority frames - for i := spdy.StreamId(0); i < 50; i++ { - queue.Push(&spdy.DataFrame{StreamId: i}, 0) - } - - for i := spdy.StreamId(0); i < 150; i++ { - frame := queue.Pop() - if frame.(*spdy.DataFrame).StreamId != i { - t.Fatalf("Wrong frame\nActual: %d\nExpecting: %d", frame.(*spdy.DataFrame).StreamId, i) - } - } -} - -func TestPriorityQueueSync(t *testing.T) { - queue := NewPriorityFrameQueue(150) - var wg sync.WaitGroup - insertRange := func(start, stop spdy.StreamId, priority uint8) { - for i := start; i < stop; i++ { - queue.Push(&spdy.DataFrame{StreamId: i}, priority) - } - wg.Done() - } - wg.Add(3) - go insertRange(spdy.StreamId(100), spdy.StreamId(150), 2) - go insertRange(spdy.StreamId(0), spdy.StreamId(50), 0) - go insertRange(spdy.StreamId(50), spdy.StreamId(100), 1) - - wg.Wait() - for i := spdy.StreamId(0); i < 150; i++ { - frame := queue.Pop() - if frame.(*spdy.DataFrame).StreamId != i { - t.Fatalf("Wrong frame\nActual: %d\nExpecting: %d", frame.(*spdy.DataFrame).StreamId, i) - } - } -} - -func TestPriorityQueueBlocking(t *testing.T) { - queue := NewPriorityFrameQueue(15) - for i := 0; i < 15; i++ { - queue.Push(&spdy.DataFrame{}, 2) - } - doneChan := make(chan bool) - go func() { - queue.Push(&spdy.DataFrame{}, 2) - close(doneChan) - }() - select { - case <-doneChan: - t.Fatalf("Push succeeded, expected to block") - case <-time.After(time.Millisecond): - break - } - - queue.Pop() - - select { - case <-doneChan: - break - case <-time.After(time.Millisecond): - t.Fatalf("Push should have succeeded, but timeout reached") - } - - for i := 0; i < 15; i++ { - queue.Pop() - } -} diff --git a/vendor/github.com/docker/spdystream/spdy/spdy_test.go b/vendor/github.com/docker/spdystream/spdy/spdy_test.go deleted file mode 100644 index ce581f1d05..0000000000 --- a/vendor/github.com/docker/spdystream/spdy/spdy_test.go +++ /dev/null @@ -1,644 +0,0 @@ -// Copyright 2011 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 spdy - -import ( - "bytes" - "compress/zlib" - "encoding/base64" - "io" - "io/ioutil" - "net/http" - "reflect" - "testing" -) - -var HeadersFixture = http.Header{ - "Url": []string{"http://www.google.com/"}, - "Method": []string{"get"}, - "Version": []string{"http/1.1"}, -} - -func TestHeaderParsing(t *testing.T) { - var headerValueBlockBuf bytes.Buffer - writeHeaderValueBlock(&headerValueBlockBuf, HeadersFixture) - const bogusStreamId = 1 - newHeaders, err := parseHeaderValueBlock(&headerValueBlockBuf, bogusStreamId) - if err != nil { - t.Fatal("parseHeaderValueBlock:", err) - } - if !reflect.DeepEqual(HeadersFixture, newHeaders) { - t.Fatal("got: ", newHeaders, "\nwant: ", HeadersFixture) - } -} - -func TestCreateParseSynStreamFrameCompressionDisable(t *testing.T) { - buffer := new(bytes.Buffer) - // Fixture framer for no compression test. - framer := &Framer{ - headerCompressionDisabled: true, - w: buffer, - headerBuf: new(bytes.Buffer), - r: buffer, - } - synStreamFrame := SynStreamFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSynStream, - }, - StreamId: 2, - Headers: HeadersFixture, - } - if err := framer.WriteFrame(&synStreamFrame); err != nil { - t.Fatal("WriteFrame without compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame without compression:", err) - } - parsedSynStreamFrame, ok := frame.(*SynStreamFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { - t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) - } -} - -func TestCreateParseSynStreamFrameCompressionEnable(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - synStreamFrame := SynStreamFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSynStream, - }, - StreamId: 2, - Headers: HeadersFixture, - } - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - if err := framer.WriteFrame(&synStreamFrame); err != nil { - t.Fatal("WriteFrame with compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame with compression:", err) - } - parsedSynStreamFrame, ok := frame.(*SynStreamFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { - t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) - } -} - -func TestCreateParseSynReplyFrameCompressionDisable(t *testing.T) { - buffer := new(bytes.Buffer) - framer := &Framer{ - headerCompressionDisabled: true, - w: buffer, - headerBuf: new(bytes.Buffer), - r: buffer, - } - synReplyFrame := SynReplyFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSynReply, - }, - StreamId: 2, - Headers: HeadersFixture, - } - if err := framer.WriteFrame(&synReplyFrame); err != nil { - t.Fatal("WriteFrame without compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame without compression:", err) - } - parsedSynReplyFrame, ok := frame.(*SynReplyFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(synReplyFrame, *parsedSynReplyFrame) { - t.Fatal("got: ", *parsedSynReplyFrame, "\nwant: ", synReplyFrame) - } -} - -func TestCreateParseSynReplyFrameCompressionEnable(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - synReplyFrame := SynReplyFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSynReply, - }, - StreamId: 2, - Headers: HeadersFixture, - } - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - if err := framer.WriteFrame(&synReplyFrame); err != nil { - t.Fatal("WriteFrame with compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame with compression:", err) - } - parsedSynReplyFrame, ok := frame.(*SynReplyFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(synReplyFrame, *parsedSynReplyFrame) { - t.Fatal("got: ", *parsedSynReplyFrame, "\nwant: ", synReplyFrame) - } -} - -func TestCreateParseRstStream(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - rstStreamFrame := RstStreamFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeRstStream, - }, - StreamId: 1, - Status: InvalidStream, - } - if err := framer.WriteFrame(&rstStreamFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedRstStreamFrame, ok := frame.(*RstStreamFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(rstStreamFrame, *parsedRstStreamFrame) { - t.Fatal("got: ", *parsedRstStreamFrame, "\nwant: ", rstStreamFrame) - } -} - -func TestCreateParseSettings(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - settingsFrame := SettingsFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSettings, - }, - FlagIdValues: []SettingsFlagIdValue{ - {FlagSettingsPersistValue, SettingsCurrentCwnd, 10}, - {FlagSettingsPersisted, SettingsUploadBandwidth, 1}, - }, - } - if err := framer.WriteFrame(&settingsFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedSettingsFrame, ok := frame.(*SettingsFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(settingsFrame, *parsedSettingsFrame) { - t.Fatal("got: ", *parsedSettingsFrame, "\nwant: ", settingsFrame) - } -} - -func TestCreateParsePing(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - pingFrame := PingFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypePing, - }, - Id: 31337, - } - if err := framer.WriteFrame(&pingFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - if pingFrame.CFHeader.Flags != 0 { - t.Fatal("Incorrect frame type:", pingFrame) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedPingFrame, ok := frame.(*PingFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if parsedPingFrame.CFHeader.Flags != 0 { - t.Fatal("Parsed incorrect frame type:", parsedPingFrame) - } - if !reflect.DeepEqual(pingFrame, *parsedPingFrame) { - t.Fatal("got: ", *parsedPingFrame, "\nwant: ", pingFrame) - } -} - -func TestCreateParseGoAway(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - goAwayFrame := GoAwayFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeGoAway, - }, - LastGoodStreamId: 31337, - Status: 1, - } - if err := framer.WriteFrame(&goAwayFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - if goAwayFrame.CFHeader.Flags != 0 { - t.Fatal("Incorrect frame type:", goAwayFrame) - } - if goAwayFrame.CFHeader.length != 8 { - t.Fatal("Incorrect frame type:", goAwayFrame) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedGoAwayFrame, ok := frame.(*GoAwayFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if parsedGoAwayFrame.CFHeader.Flags != 0 { - t.Fatal("Incorrect frame type:", parsedGoAwayFrame) - } - if parsedGoAwayFrame.CFHeader.length != 8 { - t.Fatal("Incorrect frame type:", parsedGoAwayFrame) - } - if !reflect.DeepEqual(goAwayFrame, *parsedGoAwayFrame) { - t.Fatal("got: ", *parsedGoAwayFrame, "\nwant: ", goAwayFrame) - } -} - -func TestCreateParseHeadersFrame(t *testing.T) { - buffer := new(bytes.Buffer) - framer := &Framer{ - headerCompressionDisabled: true, - w: buffer, - headerBuf: new(bytes.Buffer), - r: buffer, - } - headersFrame := HeadersFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeHeaders, - }, - StreamId: 2, - } - headersFrame.Headers = HeadersFixture - if err := framer.WriteFrame(&headersFrame); err != nil { - t.Fatal("WriteFrame without compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame without compression:", err) - } - parsedHeadersFrame, ok := frame.(*HeadersFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { - t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) - } -} - -func TestCreateParseHeadersFrameCompressionEnable(t *testing.T) { - buffer := new(bytes.Buffer) - headersFrame := HeadersFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeHeaders, - }, - StreamId: 2, - } - headersFrame.Headers = HeadersFixture - - framer, err := NewFramer(buffer, buffer) - if err := framer.WriteFrame(&headersFrame); err != nil { - t.Fatal("WriteFrame with compression:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame with compression:", err) - } - parsedHeadersFrame, ok := frame.(*HeadersFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { - t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) - } -} - -func TestCreateParseWindowUpdateFrame(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - windowUpdateFrame := WindowUpdateFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeWindowUpdate, - }, - StreamId: 31337, - DeltaWindowSize: 1, - } - if err := framer.WriteFrame(&windowUpdateFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - if windowUpdateFrame.CFHeader.Flags != 0 { - t.Fatal("Incorrect frame type:", windowUpdateFrame) - } - if windowUpdateFrame.CFHeader.length != 8 { - t.Fatal("Incorrect frame type:", windowUpdateFrame) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedWindowUpdateFrame, ok := frame.(*WindowUpdateFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if parsedWindowUpdateFrame.CFHeader.Flags != 0 { - t.Fatal("Incorrect frame type:", parsedWindowUpdateFrame) - } - if parsedWindowUpdateFrame.CFHeader.length != 8 { - t.Fatal("Incorrect frame type:", parsedWindowUpdateFrame) - } - if !reflect.DeepEqual(windowUpdateFrame, *parsedWindowUpdateFrame) { - t.Fatal("got: ", *parsedWindowUpdateFrame, "\nwant: ", windowUpdateFrame) - } -} - -func TestCreateParseDataFrame(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - dataFrame := DataFrame{ - StreamId: 1, - Data: []byte{'h', 'e', 'l', 'l', 'o'}, - } - if err := framer.WriteFrame(&dataFrame); err != nil { - t.Fatal("WriteFrame:", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame:", err) - } - parsedDataFrame, ok := frame.(*DataFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(dataFrame, *parsedDataFrame) { - t.Fatal("got: ", *parsedDataFrame, "\nwant: ", dataFrame) - } -} - -func TestCompressionContextAcrossFrames(t *testing.T) { - buffer := new(bytes.Buffer) - framer, err := NewFramer(buffer, buffer) - if err != nil { - t.Fatal("Failed to create new framer:", err) - } - headersFrame := HeadersFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeHeaders, - }, - StreamId: 2, - Headers: HeadersFixture, - } - if err := framer.WriteFrame(&headersFrame); err != nil { - t.Fatal("WriteFrame (HEADERS):", err) - } - synStreamFrame := SynStreamFrame{ - ControlFrameHeader{ - Version, - TypeSynStream, - 0, // Flags - 0, // length - }, - 2, // StreamId - 0, // AssociatedTOStreamID - 0, // Priority - 1, // Slot - nil, // Headers - } - synStreamFrame.Headers = HeadersFixture - - if err := framer.WriteFrame(&synStreamFrame); err != nil { - t.Fatal("WriteFrame (SYN_STREAM):", err) - } - frame, err := framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame (HEADERS):", err, buffer.Bytes()) - } - parsedHeadersFrame, ok := frame.(*HeadersFrame) - if !ok { - t.Fatalf("expected HeadersFrame; got %T %v", frame, frame) - } - if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { - t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) - } - frame, err = framer.ReadFrame() - if err != nil { - t.Fatal("ReadFrame (SYN_STREAM):", err, buffer.Bytes()) - } - parsedSynStreamFrame, ok := frame.(*SynStreamFrame) - if !ok { - t.Fatalf("expected SynStreamFrame; got %T %v", frame, frame) - } - if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { - t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) - } -} - -func TestMultipleSPDYFrames(t *testing.T) { - // Initialize the framers. - pr1, pw1 := io.Pipe() - pr2, pw2 := io.Pipe() - writer, err := NewFramer(pw1, pr2) - if err != nil { - t.Fatal("Failed to create writer:", err) - } - reader, err := NewFramer(pw2, pr1) - if err != nil { - t.Fatal("Failed to create reader:", err) - } - - // Set up the frames we're actually transferring. - headersFrame := HeadersFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeHeaders, - }, - StreamId: 2, - Headers: HeadersFixture, - } - synStreamFrame := SynStreamFrame{ - CFHeader: ControlFrameHeader{ - version: Version, - frameType: TypeSynStream, - }, - StreamId: 2, - Headers: HeadersFixture, - } - - // Start the goroutines to write the frames. - go func() { - if err := writer.WriteFrame(&headersFrame); err != nil { - t.Fatal("WriteFrame (HEADERS): ", err) - } - if err := writer.WriteFrame(&synStreamFrame); err != nil { - t.Fatal("WriteFrame (SYN_STREAM): ", err) - } - }() - - // Read the frames and verify they look as expected. - frame, err := reader.ReadFrame() - if err != nil { - t.Fatal("ReadFrame (HEADERS): ", err) - } - parsedHeadersFrame, ok := frame.(*HeadersFrame) - if !ok { - t.Fatal("Parsed incorrect frame type:", frame) - } - if !reflect.DeepEqual(headersFrame, *parsedHeadersFrame) { - t.Fatal("got: ", *parsedHeadersFrame, "\nwant: ", headersFrame) - } - frame, err = reader.ReadFrame() - if err != nil { - t.Fatal("ReadFrame (SYN_STREAM):", err) - } - parsedSynStreamFrame, ok := frame.(*SynStreamFrame) - if !ok { - t.Fatal("Parsed incorrect frame type.") - } - if !reflect.DeepEqual(synStreamFrame, *parsedSynStreamFrame) { - t.Fatal("got: ", *parsedSynStreamFrame, "\nwant: ", synStreamFrame) - } -} - -func TestReadMalformedZlibHeader(t *testing.T) { - // These were constructed by corrupting the first byte of the zlib - // header after writing. - malformedStructs := map[string]string{ - "SynStreamFrame": "gAIAAQAAABgAAAACAAAAAAAAF/nfolGyYmAAAAAA//8=", - "SynReplyFrame": "gAIAAgAAABQAAAACAAAX+d+iUbJiYAAAAAD//w==", - "HeadersFrame": "gAIACAAAABQAAAACAAAX+d+iUbJiYAAAAAD//w==", - } - for name, bad := range malformedStructs { - b, err := base64.StdEncoding.DecodeString(bad) - if err != nil { - t.Errorf("Unable to decode base64 encoded frame %s: %v", name, err) - } - buf := bytes.NewBuffer(b) - reader, err := NewFramer(buf, buf) - if err != nil { - t.Fatalf("NewFramer: %v", err) - } - _, err = reader.ReadFrame() - if err != zlib.ErrHeader { - t.Errorf("Frame %s, expected: %#v, actual: %#v", name, zlib.ErrHeader, err) - } - } -} - -// TODO: these tests are too weak for updating SPDY spec. Fix me. - -type zeroStream struct { - frame Frame - encoded string -} - -var streamIdZeroFrames = map[string]zeroStream{ - "SynStreamFrame": { - &SynStreamFrame{StreamId: 0}, - "gAIAAQAAABgAAAAAAAAAAAAAePnfolGyYmAAAAAA//8=", - }, - "SynReplyFrame": { - &SynReplyFrame{StreamId: 0}, - "gAIAAgAAABQAAAAAAAB4+d+iUbJiYAAAAAD//w==", - }, - "RstStreamFrame": { - &RstStreamFrame{StreamId: 0}, - "gAIAAwAAAAgAAAAAAAAAAA==", - }, - "HeadersFrame": { - &HeadersFrame{StreamId: 0}, - "gAIACAAAABQAAAAAAAB4+d+iUbJiYAAAAAD//w==", - }, - "DataFrame": { - &DataFrame{StreamId: 0}, - "AAAAAAAAAAA=", - }, - "PingFrame": { - &PingFrame{Id: 0}, - "gAIABgAAAAQAAAAA", - }, -} - -func TestNoZeroStreamId(t *testing.T) { - t.Log("skipping") // TODO: update to work with SPDY3 - return - - for name, f := range streamIdZeroFrames { - b, err := base64.StdEncoding.DecodeString(f.encoded) - if err != nil { - t.Errorf("Unable to decode base64 encoded frame %s: %v", f, err) - continue - } - framer, err := NewFramer(ioutil.Discard, bytes.NewReader(b)) - if err != nil { - t.Fatalf("NewFramer: %v", err) - } - err = framer.WriteFrame(f.frame) - checkZeroStreamId(t, name, "WriteFrame", err) - - _, err = framer.ReadFrame() - checkZeroStreamId(t, name, "ReadFrame", err) - } -} - -func checkZeroStreamId(t *testing.T, frame string, method string, err error) { - if err == nil { - t.Errorf("%s ZeroStreamId, no error on %s", method, frame) - return - } - eerr, ok := err.(*Error) - if !ok || eerr.Err != ZeroStreamId { - t.Errorf("%s ZeroStreamId, incorrect error %#v, frame %s", method, eerr, frame) - } -} diff --git a/vendor/github.com/docker/spdystream/spdy_bench_test.go b/vendor/github.com/docker/spdystream/spdy_bench_test.go deleted file mode 100644 index 6f9e491015..0000000000 --- a/vendor/github.com/docker/spdystream/spdy_bench_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package spdystream - -import ( - "fmt" - "io" - "net" - "net/http" - "sync" - "testing" -) - -func configureServer() (io.Closer, string, *sync.WaitGroup) { - authenticated = true - wg := &sync.WaitGroup{} - server, listen, serverErr := runServer(wg) - - if serverErr != nil { - panic(serverErr) - } - - return server, listen, wg -} - -func BenchmarkDial10000(b *testing.B) { - server, addr, wg := configureServer() - - defer func() { - server.Close() - wg.Wait() - }() - - for i := 0; i < b.N; i++ { - conn, dialErr := net.Dial("tcp", addr) - if dialErr != nil { - panic(fmt.Sprintf("Error dialing server: %s", dialErr)) - } - conn.Close() - } -} - -func BenchmarkDialWithSPDYStream10000(b *testing.B) { - server, addr, wg := configureServer() - - defer func() { - server.Close() - wg.Wait() - }() - - for i := 0; i < b.N; i++ { - conn, dialErr := net.Dial("tcp", addr) - if dialErr != nil { - b.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - b.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - closeErr := spdyConn.Close() - if closeErr != nil { - b.Fatalf("Error closing connection: %s, closeErr") - } - } -} - -func benchmarkStreamWithDataAndSize(size uint64, b *testing.B) { - server, addr, wg := configureServer() - - defer func() { - server.Close() - wg.Wait() - }() - - for i := 0; i < b.N; i++ { - conn, dialErr := net.Dial("tcp", addr) - if dialErr != nil { - b.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - b.Fatalf("Error creating spdy connection: %s", spdyErr) - } - - go spdyConn.Serve(MirrorStreamHandler) - - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - - writer := make([]byte, size) - - stream.Write(writer) - - if err != nil { - panic(err) - } - - reader := make([]byte, size) - stream.Read(reader) - - stream.Close() - - closeErr := spdyConn.Close() - if closeErr != nil { - b.Fatalf("Error closing connection: %s, closeErr") - } - } -} - -func BenchmarkStreamWith1Byte10000(b *testing.B) { benchmarkStreamWithDataAndSize(1, b) } -func BenchmarkStreamWith1KiloByte10000(b *testing.B) { benchmarkStreamWithDataAndSize(1024, b) } -func BenchmarkStreamWith1Megabyte10000(b *testing.B) { benchmarkStreamWithDataAndSize(1024*1024, b) } diff --git a/vendor/github.com/docker/spdystream/spdy_test.go b/vendor/github.com/docker/spdystream/spdy_test.go deleted file mode 100644 index 7f0e3a4487..0000000000 --- a/vendor/github.com/docker/spdystream/spdy_test.go +++ /dev/null @@ -1,1171 +0,0 @@ -package spdystream - -import ( - "bufio" - "bytes" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/http/httptest" - "sync" - "testing" - "time" - - "github.com/docker/spdystream/spdy" -) - -func TestSpdyStreams(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - waitErr := stream.Wait() - if waitErr != nil { - t.Fatalf("Error waiting for stream: %s", waitErr) - } - - message := []byte("hello") - writeErr := stream.WriteData(message, false) - if writeErr != nil { - t.Fatalf("Error writing data") - } - - buf := make([]byte, 10) - n, readErr := stream.Read(buf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 5 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 5", n) - } - if bytes.Compare(buf[:n], message) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", buf, message) - } - - headers := http.Header{ - "TestKey": []string{"TestVal"}, - } - sendErr := stream.SendHeader(headers, false) - if sendErr != nil { - t.Fatalf("Error sending headers: %s", sendErr) - } - receiveHeaders, receiveErr := stream.ReceiveHeader() - if receiveErr != nil { - t.Fatalf("Error receiving headers: %s", receiveErr) - } - if len(receiveHeaders) != 1 { - t.Fatalf("Unexpected number of headers:\nActual: %d\nExpecting:%d", len(receiveHeaders), 1) - } - testVal := receiveHeaders.Get("TestKey") - if testVal != "TestVal" { - t.Fatalf("Wrong test value:\nActual: %q\nExpecting: %q", testVal, "TestVal") - } - - writeErr = stream.WriteData(message, true) - if writeErr != nil { - t.Fatalf("Error writing data") - } - - smallBuf := make([]byte, 3) - n, readErr = stream.Read(smallBuf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 3 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 3", n) - } - if bytes.Compare(smallBuf[:n], []byte("hel")) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", smallBuf[:n], message) - } - n, readErr = stream.Read(smallBuf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 2 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 2", n) - } - if bytes.Compare(smallBuf[:n], []byte("lo")) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpected: lo", smallBuf[:n]) - } - - n, readErr = stream.Read(buf) - if readErr != io.EOF { - t.Fatalf("Expected EOF reading from finished stream, read %d bytes", n) - } - - // Closing again should return error since stream is already closed - streamCloseErr := stream.Close() - if streamCloseErr == nil { - t.Fatalf("No error closing finished stream") - } - if streamCloseErr != ErrWriteClosedStream { - t.Fatalf("Unexpected error closing stream: %s", streamCloseErr) - } - - streamResetErr := stream.Reset() - if streamResetErr != nil { - t.Fatalf("Error reseting stream: %s", streamResetErr) - } - - authenticated = false - badStream, badStreamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if badStreamErr != nil { - t.Fatalf("Error creating stream: %s", badStreamErr) - } - - waitErr = badStream.Wait() - if waitErr == nil { - t.Fatalf("Did not receive error creating stream") - } - if waitErr != ErrReset { - t.Fatalf("Unexpected error creating stream: %s", waitErr) - } - streamCloseErr = badStream.Close() - if streamCloseErr == nil { - t.Fatalf("No error closing bad stream") - } - - spdyCloseErr := spdyConn.Close() - if spdyCloseErr != nil { - t.Fatalf("Error closing spdy connection: %s", spdyCloseErr) - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestPing(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - pingTime, pingErr := spdyConn.Ping() - if pingErr != nil { - t.Fatalf("Error pinging server: %s", pingErr) - } - if pingTime == time.Duration(0) { - t.Fatalf("Expecting non-zero ping time") - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestHalfClose(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - waitErr := stream.Wait() - if waitErr != nil { - t.Fatalf("Error waiting for stream: %s", waitErr) - } - - message := []byte("hello and will read after close") - writeErr := stream.WriteData(message, false) - if writeErr != nil { - t.Fatalf("Error writing data") - } - - streamCloseErr := stream.Close() - if streamCloseErr != nil { - t.Fatalf("Error closing stream: %s", streamCloseErr) - } - - buf := make([]byte, 40) - n, readErr := stream.Read(buf) - if readErr != nil { - t.Fatalf("Error reading data from stream: %s", readErr) - } - if n != 31 { - t.Fatalf("Unexpected number of bytes read:\nActual: %d\nExpected: 5", n) - } - if bytes.Compare(buf[:n], message) != 0 { - t.Fatalf("Did not receive expected message:\nActual: %s\nExpectd: %s", buf, message) - } - - spdyCloseErr := spdyConn.Close() - if spdyCloseErr != nil { - t.Fatalf("Error closing spdy connection: %s", spdyCloseErr) - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestUnexpectedRemoteConnectionClosed(t *testing.T) { - tt := []struct { - closeReceiver bool - closeSender bool - }{ - {closeReceiver: true, closeSender: false}, - {closeReceiver: false, closeSender: true}, - {closeReceiver: false, closeSender: false}, - } - for tix, tc := range tt { - listener, listenErr := net.Listen("tcp", "localhost:0") - if listenErr != nil { - t.Fatalf("Error listening: %v", listenErr) - } - - var serverConn net.Conn - var connErr error - go func() { - serverConn, connErr = listener.Accept() - if connErr != nil { - t.Fatalf("Error accepting: %v", connErr) - } - - serverSpdyConn, _ := NewConnection(serverConn, true) - go serverSpdyConn.Serve(func(stream *Stream) { - stream.SendReply(http.Header{}, tc.closeSender) - }) - }() - - conn, dialErr := net.Dial("tcp", listener.Addr().String()) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - waitErr := stream.Wait() - if waitErr != nil { - t.Fatalf("Error waiting for stream: %s", waitErr) - } - - if tc.closeReceiver { - // make stream half closed, receive only - stream.Close() - } - - streamch := make(chan error, 1) - go func() { - b := make([]byte, 1) - _, err := stream.Read(b) - streamch <- err - }() - - closeErr := serverConn.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - - select { - case e := <-streamch: - if e == nil || e != io.EOF { - t.Fatalf("(%d) Expected to get an EOF stream error", tix) - } - } - - closeErr = conn.Close() - if closeErr != nil { - t.Fatalf("Error closing client connection: %s", closeErr) - } - - listenErr = listener.Close() - if listenErr != nil { - t.Fatalf("Error closing listener: %s", listenErr) - } - } -} - -func TestCloseNotification(t *testing.T) { - listener, listenErr := net.Listen("tcp", "localhost:0") - if listenErr != nil { - t.Fatalf("Error listening: %v", listenErr) - } - listen := listener.Addr().String() - - serverConnChan := make(chan net.Conn) - go func() { - serverConn, err := listener.Accept() - if err != nil { - t.Fatalf("Error accepting: %v", err) - } - - serverSpdyConn, err := NewConnection(serverConn, true) - if err != nil { - t.Fatalf("Error creating server connection: %v", err) - } - go serverSpdyConn.Serve(NoOpStreamHandler) - <-serverSpdyConn.CloseChan() - serverConnChan <- serverConn - }() - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - // close client conn - err := conn.Close() - if err != nil { - t.Fatalf("Error closing client connection: %v", err) - } - - var serverConn net.Conn - select { - case serverConn = <-serverConnChan: - } - - err = serverConn.Close() - if err != nil { - t.Fatalf("Error closing serverConn: %v", err) - } - - listenErr = listener.Close() - if listenErr != nil { - t.Fatalf("Error closing listener: %s", listenErr) - } -} - -func TestIdleShutdownRace(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("Error creating stream: %v", err) - } - - spdyConn.SetIdleTimeout(5 * time.Millisecond) - go func() { - time.Sleep(5 * time.Millisecond) - stream.Reset() - }() - - select { - case <-spdyConn.CloseChan(): - case <-time.After(20 * time.Millisecond): - t.Fatal("Timed out waiting for idle connection closure") - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestIdleNoTimeoutSet(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - select { - case <-spdyConn.CloseChan(): - t.Fatal("Unexpected connection closure") - case <-time.After(10 * time.Millisecond): - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestIdleClearTimeout(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - spdyConn.SetIdleTimeout(10 * time.Millisecond) - spdyConn.SetIdleTimeout(0) - select { - case <-spdyConn.CloseChan(): - t.Fatal("Unexpected connection closure") - case <-time.After(20 * time.Millisecond): - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestIdleNoData(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - spdyConn.SetIdleTimeout(10 * time.Millisecond) - <-spdyConn.CloseChan() - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestIdleWithData(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - spdyConn.SetIdleTimeout(25 * time.Millisecond) - - authenticated = true - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("Error creating stream: %v", err) - } - - writeCh := make(chan struct{}) - - go func() { - b := []byte{1, 2, 3, 4, 5} - for i := 0; i < 10; i++ { - _, err = stream.Write(b) - if err != nil { - t.Fatalf("Error writing to stream: %v", err) - } - time.Sleep(10 * time.Millisecond) - } - close(writeCh) - }() - - writesFinished := false - -Loop: - for { - select { - case <-writeCh: - writesFinished = true - case <-spdyConn.CloseChan(): - if !writesFinished { - t.Fatal("Connection closed before all writes finished") - } - break Loop - } - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestIdleRace(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - spdyConn.SetIdleTimeout(10 * time.Millisecond) - - authenticated = true - - for i := 0; i < 10; i++ { - _, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("Error creating stream: %v", err) - } - } - - <-spdyConn.CloseChan() - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestHalfClosedIdleTimeout(t *testing.T) { - listener, listenErr := net.Listen("tcp", "localhost:0") - if listenErr != nil { - t.Fatalf("Error listening: %v", listenErr) - } - listen := listener.Addr().String() - - go func() { - serverConn, err := listener.Accept() - if err != nil { - t.Fatalf("Error accepting: %v", err) - } - - serverSpdyConn, err := NewConnection(serverConn, true) - if err != nil { - t.Fatalf("Error creating server connection: %v", err) - } - go serverSpdyConn.Serve(func(s *Stream) { - s.SendReply(http.Header{}, true) - }) - serverSpdyConn.SetIdleTimeout(10 * time.Millisecond) - }() - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("Error creating stream: %v", err) - } - - time.Sleep(20 * time.Millisecond) - - stream.Reset() - - err = spdyConn.Close() - if err != nil { - t.Fatalf("Error closing client spdy conn: %v", err) - } -} - -func TestStreamReset(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - buf := []byte("dskjahfkdusahfkdsahfkdsafdkas") - for i := 0; i < 10; i++ { - if _, err := stream.Write(buf); err != nil { - t.Fatalf("Error writing to stream: %s", err) - } - } - for i := 0; i < 10; i++ { - if _, err := stream.Read(buf); err != nil { - t.Fatalf("Error reading from stream: %s", err) - } - } - - // fmt.Printf("Resetting...\n") - if err := stream.Reset(); err != nil { - t.Fatalf("Error reseting stream: %s", err) - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -func TestStreamResetWithDataRemaining(t *testing.T) { - var wg sync.WaitGroup - server, listen, serverErr := runServer(&wg) - if serverErr != nil { - t.Fatalf("Error initializing server: %s", serverErr) - } - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - authenticated = true - stream, streamErr := spdyConn.CreateStream(http.Header{}, nil, false) - if streamErr != nil { - t.Fatalf("Error creating stream: %s", streamErr) - } - - buf := []byte("dskjahfkdusahfkdsahfkdsafdkas") - for i := 0; i < 10; i++ { - if _, err := stream.Write(buf); err != nil { - t.Fatalf("Error writing to stream: %s", err) - } - } - - // read a bit to make sure a goroutine gets to <-dataChan - if _, err := stream.Read(buf); err != nil { - t.Fatalf("Error reading from stream: %s", err) - } - - // fmt.Printf("Resetting...\n") - if err := stream.Reset(); err != nil { - t.Fatalf("Error reseting stream: %s", err) - } - - closeErr := server.Close() - if closeErr != nil { - t.Fatalf("Error shutting down server: %s", closeErr) - } - wg.Wait() -} - -type roundTripper struct { - conn net.Conn -} - -func (s *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - r := *req - req = &r - - conn, err := net.Dial("tcp", req.URL.Host) - if err != nil { - return nil, err - } - - err = req.Write(conn) - if err != nil { - return nil, err - } - - resp, err := http.ReadResponse(bufio.NewReader(conn), req) - if err != nil { - return nil, err - } - - s.conn = conn - - return resp, nil -} - -// see https://github.com/GoogleCloudPlatform/kubernetes/issues/4882 -func TestFramingAfterRemoteConnectionClosed(t *testing.T) { - server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - streamCh := make(chan *Stream) - - w.WriteHeader(http.StatusSwitchingProtocols) - - netconn, _, _ := w.(http.Hijacker).Hijack() - conn, _ := NewConnection(netconn, true) - go conn.Serve(func(s *Stream) { - s.SendReply(http.Header{}, false) - streamCh <- s - }) - - stream := <-streamCh - io.Copy(stream, stream) - - closeChan := make(chan struct{}) - go func() { - stream.Reset() - conn.Close() - close(closeChan) - }() - - <-closeChan - })) - - server.Start() - defer server.Close() - - req, err := http.NewRequest("GET", server.URL, nil) - if err != nil { - t.Fatalf("Error creating request: %s", err) - } - - rt := &roundTripper{} - client := &http.Client{Transport: rt} - - _, err = client.Do(req) - if err != nil { - t.Fatalf("unexpected error from client.Do: %s", err) - } - - conn, err := NewConnection(rt.conn, false) - go conn.Serve(NoOpStreamHandler) - - stream, err := conn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("error creating client stream: %s", err) - } - - n, err := stream.Write([]byte("hello")) - if err != nil { - t.Fatalf("error writing to stream: %s", err) - } - if n != 5 { - t.Fatalf("Expected to write 5 bytes, but actually wrote %d", n) - } - - b := make([]byte, 5) - n, err = stream.Read(b) - if err != nil { - t.Fatalf("error reading from stream: %s", err) - } - if n != 5 { - t.Fatalf("Expected to read 5 bytes, but actually read %d", n) - } - if e, a := "hello", string(b[0:n]); e != a { - t.Fatalf("expected '%s', got '%s'", e, a) - } - - stream.Reset() - conn.Close() -} - -func TestGoAwayRace(t *testing.T) { - var done sync.WaitGroup - listener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Error listening: %v", err) - } - listen := listener.Addr().String() - - processDataFrame := make(chan struct{}) - serverClosed := make(chan struct{}) - - done.Add(1) - go func() { - defer done.Done() - serverConn, err := listener.Accept() - if err != nil { - t.Fatalf("Error accepting: %v", err) - } - - serverSpdyConn, err := NewConnection(serverConn, true) - if err != nil { - t.Fatalf("Error creating server connection: %v", err) - } - go func() { - <-serverSpdyConn.CloseChan() - close(serverClosed) - }() - - // force the data frame handler to sleep before delivering the frame - serverSpdyConn.dataFrameHandler = func(frame *spdy.DataFrame) error { - <-processDataFrame - return serverSpdyConn.handleDataFrame(frame) - } - - streamCh := make(chan *Stream) - go serverSpdyConn.Serve(func(s *Stream) { - s.SendReply(http.Header{}, false) - streamCh <- s - }) - - stream, ok := <-streamCh - if !ok { - t.Fatalf("didn't get a stream") - } - stream.Close() - data, err := ioutil.ReadAll(stream) - if err != nil { - t.Error(err) - } - if e, a := "hello1hello2hello3hello4hello5", string(data); e != a { - t.Errorf("Expected %q, got %q", e, a) - } - }() - - dialConn, err := net.Dial("tcp", listen) - if err != nil { - t.Fatalf("Error dialing server: %s", err) - } - conn, err := NewConnection(dialConn, false) - if err != nil { - t.Fatalf("Error creating client connectin: %v", err) - } - go conn.Serve(NoOpStreamHandler) - - stream, err := conn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("error creating client stream: %s", err) - } - if err := stream.Wait(); err != nil { - t.Fatalf("error waiting for stream creation: %v", err) - } - - fmt.Fprint(stream, "hello1") - fmt.Fprint(stream, "hello2") - fmt.Fprint(stream, "hello3") - fmt.Fprint(stream, "hello4") - fmt.Fprint(stream, "hello5") - - stream.Close() - conn.Close() - - // wait for the server to get the go away frame - <-serverClosed - - // allow the data frames to be delivered to the server's stream - close(processDataFrame) - - done.Wait() -} - -func TestSetIdleTimeoutAfterRemoteConnectionClosed(t *testing.T) { - listener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Error listening: %v", err) - } - listen := listener.Addr().String() - - serverConns := make(chan *Connection, 1) - go func() { - conn, connErr := listener.Accept() - if connErr != nil { - t.Fatal(connErr) - } - serverSpdyConn, err := NewConnection(conn, true) - if err != nil { - t.Fatalf("Error creating server connection: %v", err) - } - go serverSpdyConn.Serve(NoOpStreamHandler) - serverConns <- serverSpdyConn - }() - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - if err := spdyConn.Close(); err != nil { - t.Fatal(err) - } - - serverConn := <-serverConns - defer serverConn.Close() - <-serverConn.closeChan - - serverConn.SetIdleTimeout(10 * time.Second) -} - -func TestClientConnectionStopsServingAfterGoAway(t *testing.T) { - listener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Error listening: %v", err) - } - listen := listener.Addr().String() - - serverConns := make(chan *Connection, 1) - go func() { - conn, connErr := listener.Accept() - if connErr != nil { - t.Fatal(connErr) - } - serverSpdyConn, err := NewConnection(conn, true) - if err != nil { - t.Fatalf("Error creating server connection: %v", err) - } - go serverSpdyConn.Serve(NoOpStreamHandler) - serverConns <- serverSpdyConn - }() - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("Error creating stream: %v", err) - } - if err := stream.WaitTimeout(30 * time.Second); err != nil { - t.Fatalf("Timed out waiting for stream: %v", err) - } - - readChan := make(chan struct{}) - go func() { - _, err := ioutil.ReadAll(stream) - if err != nil { - t.Fatalf("Error reading stream: %v", err) - } - close(readChan) - }() - - serverConn := <-serverConns - serverConn.Close() - - // make sure the client conn breaks out of the main loop in Serve() - <-spdyConn.closeChan - // make sure the remote channels are closed and the stream read is unblocked - <-readChan -} - -func TestStreamReadUnblocksAfterCloseThenReset(t *testing.T) { - listener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Error listening: %v", err) - } - listen := listener.Addr().String() - - serverConns := make(chan *Connection, 1) - go func() { - conn, connErr := listener.Accept() - if connErr != nil { - t.Fatal(connErr) - } - serverSpdyConn, err := NewConnection(conn, true) - if err != nil { - t.Fatalf("Error creating server connection: %v", err) - } - go serverSpdyConn.Serve(NoOpStreamHandler) - serverConns <- serverSpdyConn - }() - - conn, dialErr := net.Dial("tcp", listen) - if dialErr != nil { - t.Fatalf("Error dialing server: %s", dialErr) - } - - spdyConn, spdyErr := NewConnection(conn, false) - if spdyErr != nil { - t.Fatalf("Error creating spdy connection: %s", spdyErr) - } - go spdyConn.Serve(NoOpStreamHandler) - - stream, err := spdyConn.CreateStream(http.Header{}, nil, false) - if err != nil { - t.Fatalf("Error creating stream: %v", err) - } - if err := stream.WaitTimeout(30 * time.Second); err != nil { - t.Fatalf("Timed out waiting for stream: %v", err) - } - - readChan := make(chan struct{}) - go func() { - _, err := ioutil.ReadAll(stream) - if err != nil { - t.Fatalf("Error reading stream: %v", err) - } - close(readChan) - }() - - serverConn := <-serverConns - defer serverConn.Close() - - if err := stream.Close(); err != nil { - t.Fatal(err) - } - if err := stream.Reset(); err != nil { - t.Fatal(err) - } - - // make sure close followed by reset unblocks stream.Read() - select { - case <-readChan: - case <-time.After(10 * time.Second): - t.Fatal("Timed out waiting for stream read to unblock") - } -} - -var authenticated bool - -func authStreamHandler(stream *Stream) { - if !authenticated { - stream.Refuse() - } - MirrorStreamHandler(stream) -} - -func runServer(wg *sync.WaitGroup) (io.Closer, string, error) { - listener, listenErr := net.Listen("tcp", "localhost:0") - if listenErr != nil { - return nil, "", listenErr - } - wg.Add(1) - go func() { - for { - conn, connErr := listener.Accept() - if connErr != nil { - break - } - - spdyConn, _ := NewConnection(conn, true) - go spdyConn.Serve(authStreamHandler) - - } - wg.Done() - }() - return listener, listener.Addr().String(), nil -} diff --git a/vendor/github.com/eapache/channels/batching_channel_test.go b/vendor/github.com/eapache/channels/batching_channel_test.go deleted file mode 100644 index 8fa329c9c8..0000000000 --- a/vendor/github.com/eapache/channels/batching_channel_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package channels - -import "testing" - -func testBatches(t *testing.T, ch Channel) { - go func() { - for i := 0; i < 1000; i++ { - ch.In() <- i - } - ch.Close() - }() - - i := 0 - for val := range ch.Out() { - for _, elem := range val.([]interface{}) { - if i != elem.(int) { - t.Fatal("batching channel expected", i, "but got", elem.(int)) - } - i++ - } - } -} - -func TestBatchingChannel(t *testing.T) { - ch := NewBatchingChannel(Infinity) - testBatches(t, ch) - - ch = NewBatchingChannel(2) - testBatches(t, ch) - - ch = NewBatchingChannel(1) - testChannelConcurrentAccessors(t, "batching channel", ch) -} - -func TestBatchingChannelCap(t *testing.T) { - ch := NewBatchingChannel(Infinity) - if ch.Cap() != Infinity { - t.Error("incorrect capacity on infinite channel") - } - - ch = NewBatchingChannel(5) - if ch.Cap() != 5 { - t.Error("incorrect capacity on infinite channel") - } -} diff --git a/vendor/github.com/eapache/channels/black_hole_test.go b/vendor/github.com/eapache/channels/black_hole_test.go deleted file mode 100644 index c149da6b03..0000000000 --- a/vendor/github.com/eapache/channels/black_hole_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package channels - -import "testing" - -func TestBlackHole(t *testing.T) { - discard := NewBlackHole() - - for i := 0; i < 1000; i++ { - discard.In() <- i - } - - discard.Close() - - if discard.Len() != 1000 { - t.Error("blackhole expected 1000 was", discard.Len()) - } - - // no asserts here, this is just for the race detector's benefit - ch := NewBlackHole() - go ch.Len() - go ch.Cap() - - go func() { - ch.In() <- nil - }() -} diff --git a/vendor/github.com/eapache/channels/channels_test.go b/vendor/github.com/eapache/channels/channels_test.go deleted file mode 100644 index 1ca17a0eec..0000000000 --- a/vendor/github.com/eapache/channels/channels_test.go +++ /dev/null @@ -1,265 +0,0 @@ -package channels - -import ( - "math/rand" - "testing" - "time" -) - -func testChannel(t *testing.T, name string, ch Channel) { - go func() { - for i := 0; i < 1000; i++ { - ch.In() <- i - } - ch.Close() - }() - for i := 0; i < 1000; i++ { - val := <-ch.Out() - if i != val.(int) { - t.Fatal(name, "expected", i, "but got", val.(int)) - } - } -} - -func testChannelPair(t *testing.T, name string, in InChannel, out OutChannel) { - go func() { - for i := 0; i < 1000; i++ { - in.In() <- i - } - in.Close() - }() - for i := 0; i < 1000; i++ { - val := <-out.Out() - if i != val.(int) { - t.Fatal("pair", name, "expected", i, "but got", val.(int)) - } - } -} - -func testChannelConcurrentAccessors(t *testing.T, name string, ch Channel) { - // no asserts here, this is just for the race detector's benefit - go ch.Len() - go ch.Cap() - - go func() { - ch.In() <- nil - }() - - go func() { - <-ch.Out() - }() -} - -func TestPipe(t *testing.T) { - a := NewNativeChannel(None) - b := NewNativeChannel(None) - - Pipe(a, b) - - testChannelPair(t, "pipe", a, b) -} - -func TestWeakPipe(t *testing.T) { - a := NewNativeChannel(None) - b := NewNativeChannel(None) - - WeakPipe(a, b) - - testChannelPair(t, "pipe", a, b) -} - -func testMultiplex(t *testing.T, multi func(output SimpleInChannel, inputs ...SimpleOutChannel)) { - a := NewNativeChannel(None) - b := NewNativeChannel(None) - - multi(b, a) - - testChannelPair(t, "simple multiplex", a, b) - - a = NewNativeChannel(None) - inputs := []Channel{ - NewNativeChannel(None), - NewNativeChannel(None), - NewNativeChannel(None), - NewNativeChannel(None), - } - - multi(a, inputs[0], inputs[1], inputs[2], inputs[3]) - - go func() { - rand.Seed(time.Now().Unix()) - for i := 0; i < 1000; i++ { - inputs[rand.Intn(len(inputs))].In() <- i - } - for i := range inputs { - inputs[i].Close() - } - }() - for i := 0; i < 1000; i++ { - val := <-a.Out() - if i != val.(int) { - t.Fatal("multiplexing expected", i, "but got", val.(int)) - } - } -} - -func TestMultiplex(t *testing.T) { - testMultiplex(t, Multiplex) -} - -func TestWeakMultiplex(t *testing.T) { - testMultiplex(t, WeakMultiplex) -} - -func testTee(t *testing.T, tee func(input SimpleOutChannel, outputs ...SimpleInChannel)) { - a := NewNativeChannel(None) - b := NewNativeChannel(None) - - tee(a, b) - - testChannelPair(t, "simple tee", a, b) - - a = NewNativeChannel(None) - outputs := []Channel{ - NewNativeChannel(None), - NewNativeChannel(None), - NewNativeChannel(None), - NewNativeChannel(None), - } - - tee(a, outputs[0], outputs[1], outputs[2], outputs[3]) - - go func() { - for i := 0; i < 1000; i++ { - a.In() <- i - } - a.Close() - }() - for i := 0; i < 1000; i++ { - for _, output := range outputs { - val := <-output.Out() - if i != val.(int) { - t.Fatal("teeing expected", i, "but got", val.(int)) - } - } - } -} - -func TestTee(t *testing.T) { - testTee(t, Tee) -} - -func TestWeakTee(t *testing.T) { - testTee(t, WeakTee) -} - -func testDistribute(t *testing.T, dist func(input SimpleOutChannel, outputs ...SimpleInChannel)) { - a := NewNativeChannel(None) - b := NewNativeChannel(None) - - dist(a, b) - - testChannelPair(t, "simple distribute", a, b) - - a = NewNativeChannel(None) - outputs := []Channel{ - NewNativeChannel(None), - NewNativeChannel(None), - NewNativeChannel(None), - NewNativeChannel(None), - } - - dist(a, outputs[0], outputs[1], outputs[2], outputs[3]) - - go func() { - for i := 0; i < 1000; i++ { - a.In() <- i - } - a.Close() - }() - - received := make([]bool, 1000) - for _ = range received { - var val interface{} - select { - case val = <-outputs[0].Out(): - case val = <-outputs[1].Out(): - case val = <-outputs[2].Out(): - case val = <-outputs[3].Out(): - } - if received[val.(int)] { - t.Fatal("distribute got value twice", val.(int)) - } - received[val.(int)] = true - } - for i := range received { - if !received[i] { - t.Fatal("distribute missed", i) - } - } -} - -func TestDistribute(t *testing.T) { - testDistribute(t, Distribute) -} - -func TestWeakDistribute(t *testing.T) { - testDistribute(t, WeakDistribute) -} - -func TestWrap(t *testing.T) { - rawChan := make(chan int, 5) - ch := Wrap(rawChan) - - for i := 0; i < 5; i++ { - rawChan <- i - } - close(rawChan) - - for i := 0; i < 5; i++ { - x := (<-ch.Out()).(int) - if x != i { - t.Error("Wrapped value", x, "was expecting", i) - } - } - _, ok := <-ch.Out() - if ok { - t.Error("Wrapped channel didn't close") - } -} - -func TestUnwrap(t *testing.T) { - rawChan := make(chan int) - ch := NewNativeChannel(5) - Unwrap(ch, rawChan) - - for i := 0; i < 5; i++ { - ch.In() <- i - } - ch.Close() - - for i := 0; i < 5; i++ { - x := <-rawChan - if x != i { - t.Error("Unwrapped value", x, "was expecting", i) - } - } - _, ok := <-rawChan - if ok { - t.Error("Unwrapped channel didn't close") - } -} - -func ExampleChannel() { - var ch Channel - - ch = NewInfiniteChannel() - - for i := 0; i < 10; i++ { - ch.In() <- nil - } - - for i := 0; i < 10; i++ { - <-ch.Out() - } -} diff --git a/vendor/github.com/eapache/channels/infinite_channel_test.go b/vendor/github.com/eapache/channels/infinite_channel_test.go deleted file mode 100644 index a3b2a297ed..0000000000 --- a/vendor/github.com/eapache/channels/infinite_channel_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package channels - -import "testing" - -func TestInfiniteChannel(t *testing.T) { - var ch Channel - - ch = NewInfiniteChannel() - testChannel(t, "infinite channel", ch) - - ch = NewInfiniteChannel() - testChannelPair(t, "infinite channel", ch, ch) - - ch = NewInfiniteChannel() - testChannelConcurrentAccessors(t, "infinite channel", ch) -} - -func BenchmarkInfiniteChannelSerial(b *testing.B) { - ch := NewInfiniteChannel() - for i := 0; i < b.N; i++ { - ch.In() <- nil - } - for i := 0; i < b.N; i++ { - <-ch.Out() - } -} - -func BenchmarkInfiniteChannelParallel(b *testing.B) { - ch := NewInfiniteChannel() - go func() { - for i := 0; i < b.N; i++ { - <-ch.Out() - } - ch.Close() - }() - for i := 0; i < b.N; i++ { - ch.In() <- nil - } - <-ch.Out() -} - -func BenchmarkInfiniteChannelTickTock(b *testing.B) { - ch := NewInfiniteChannel() - for i := 0; i < b.N; i++ { - ch.In() <- nil - <-ch.Out() - } -} diff --git a/vendor/github.com/eapache/channels/native_channel_test.go b/vendor/github.com/eapache/channels/native_channel_test.go deleted file mode 100644 index c871bd65e2..0000000000 --- a/vendor/github.com/eapache/channels/native_channel_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package channels - -import "testing" - -func TestNativeChannels(t *testing.T) { - var ch Channel - - ch = NewNativeChannel(None) - testChannel(t, "bufferless native channel", ch) - - ch = NewNativeChannel(None) - testChannelPair(t, "bufferless native channel", ch, ch) - - ch = NewNativeChannel(5) - testChannel(t, "5-buffer native channel", ch) - - ch = NewNativeChannel(5) - testChannelPair(t, "5-buffer native channel", ch, ch) - - ch = NewNativeChannel(None) - testChannelConcurrentAccessors(t, "native channel", ch) -} - -func TestNativeInOutChannels(t *testing.T) { - ch1 := make(chan interface{}) - ch2 := make(chan interface{}) - - Pipe(NativeOutChannel(ch1), NativeInChannel(ch2)) - NativeInChannel(ch1).Close() -} - -func TestDeadChannel(t *testing.T) { - ch := NewDeadChannel() - - if ch.Len() != 0 { - t.Error("dead channel length not 0") - } - if ch.Cap() != 0 { - t.Error("dead channel cap not 0") - } - - select { - case <-ch.Out(): - t.Error("read from a dead channel") - default: - } - - select { - case ch.In() <- nil: - t.Error("wrote to a dead channel") - default: - } - - ch.Close() - - ch = NewDeadChannel() - testChannelConcurrentAccessors(t, "dead channel", ch) -} diff --git a/vendor/github.com/eapache/channels/overflowing_channel_test.go b/vendor/github.com/eapache/channels/overflowing_channel_test.go deleted file mode 100644 index 46837a7936..0000000000 --- a/vendor/github.com/eapache/channels/overflowing_channel_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package channels - -import "testing" - -func TestOverflowingChannel(t *testing.T) { - var ch Channel - - ch = NewOverflowingChannel(Infinity) // yes this is rather silly, but it should work - testChannel(t, "infinite overflowing channel", ch) - - ch = NewOverflowingChannel(None) - go func() { - for i := 0; i < 1000; i++ { - ch.In() <- i - } - ch.Close() - }() - prev := -1 - for i := range ch.Out() { - if prev >= i.(int) { - t.Fatal("overflowing channel prev", prev, "but got", i.(int)) - } - } - - ch = NewOverflowingChannel(10) - for i := 0; i < 1000; i++ { - ch.In() <- i - } - ch.Close() - for i := 0; i < 10; i++ { - val := <-ch.Out() - if i != val.(int) { - t.Fatal("overflowing channel expected", i, "but got", val.(int)) - } - } - if val, open := <-ch.Out(); open == true { - t.Fatal("overflowing channel expected closed but got", val) - } - - ch = NewOverflowingChannel(None) - ch.In() <- 0 - ch.Close() - if val, open := <-ch.Out(); open == true { - t.Fatal("overflowing channel expected closed but got", val) - } - - ch = NewOverflowingChannel(2) - testChannelConcurrentAccessors(t, "overflowing channel", ch) -} diff --git a/vendor/github.com/eapache/channels/resizable_channel_test.go b/vendor/github.com/eapache/channels/resizable_channel_test.go deleted file mode 100644 index 58b5fd19e6..0000000000 --- a/vendor/github.com/eapache/channels/resizable_channel_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package channels - -import ( - "math/rand" - "testing" -) - -func TestResizableChannel(t *testing.T) { - var ch *ResizableChannel - - ch = NewResizableChannel() - testChannel(t, "default resizable channel", ch) - - ch = NewResizableChannel() - testChannelPair(t, "default resizable channel", ch, ch) - - ch = NewResizableChannel() - ch.Resize(Infinity) - testChannel(t, "infinite resizable channel", ch) - - ch = NewResizableChannel() - ch.Resize(Infinity) - testChannelPair(t, "infinite resizable channel", ch, ch) - - ch = NewResizableChannel() - ch.Resize(5) - testChannel(t, "5-buffer resizable channel", ch) - - ch = NewResizableChannel() - ch.Resize(5) - testChannelPair(t, "5-buffer resizable channel", ch, ch) - - ch = NewResizableChannel() - testChannelConcurrentAccessors(t, "resizable channel", ch) -} - -func TestResizableChannelOnline(t *testing.T) { - stopper := make(chan bool) - ch := NewResizableChannel() - go func() { - for i := 0; i < 1000; i++ { - ch.In() <- i - } - <-stopper - ch.Close() - }() - - go func() { - for i := 0; i < 1000; i++ { - ch.Resize(BufferCap(rand.Intn(50) + 1)) - } - close(stopper) - }() - - for i := 0; i < 1000; i++ { - val := <-ch.Out() - if i != val.(int) { - t.Fatal("resizable channel expected", i, "but got", val.(int)) - } - } -} diff --git a/vendor/github.com/eapache/channels/ring_channel_test.go b/vendor/github.com/eapache/channels/ring_channel_test.go deleted file mode 100644 index 92b851a55e..0000000000 --- a/vendor/github.com/eapache/channels/ring_channel_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package channels - -import "testing" - -func TestRingChannel(t *testing.T) { - var ch Channel - - ch = NewRingChannel(Infinity) // yes this is rather silly, but it should work - testChannel(t, "infinite ring-buffer channel", ch) - - ch = NewRingChannel(None) - go func() { - for i := 0; i < 1000; i++ { - ch.In() <- i - } - ch.Close() - }() - prev := -1 - for i := range ch.Out() { - if prev >= i.(int) { - t.Fatal("ring channel prev", prev, "but got", i.(int)) - } - } - - ch = NewRingChannel(10) - for i := 0; i < 1000; i++ { - ch.In() <- i - } - ch.Close() - for i := 990; i < 1000; i++ { - val := <-ch.Out() - if i != val.(int) { - t.Fatal("ring channel expected", i, "but got", val.(int)) - } - } - if val, open := <-ch.Out(); open == true { - t.Fatal("ring channel expected closed but got", val) - } - - ch = NewRingChannel(None) - ch.In() <- 0 - ch.Close() - if val, open := <-ch.Out(); open == true { - t.Fatal("ring channel expected closed but got", val) - } - - ch = NewRingChannel(2) - testChannelConcurrentAccessors(t, "ring channel", ch) -} diff --git a/vendor/github.com/eapache/channels/shared_buffer_test.go b/vendor/github.com/eapache/channels/shared_buffer_test.go deleted file mode 100644 index 79a17b3108..0000000000 --- a/vendor/github.com/eapache/channels/shared_buffer_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package channels - -import "testing" - -func TestSharedBufferSingleton(t *testing.T) { - buf := NewSharedBuffer(3) - - ch := buf.NewChannel() - for i := 0; i < 5; i++ { - ch.In() <- (*int)(nil) - ch.In() <- (*int)(nil) - ch.In() <- (*int)(nil) - select { - case ch.In() <- (*int)(nil): - t.Error("Wrote to full shared-buffer") - default: - } - - <-ch.Out() - <-ch.Out() - <-ch.Out() - select { - case <-ch.Out(): - t.Error("Read from empty shared-buffer") - default: - } - } - - ch.Close() - buf.Close() -} - -func TestSharedBufferMultiple(t *testing.T) { - buf := NewSharedBuffer(3) - - ch1 := buf.NewChannel() - ch2 := buf.NewChannel() - - ch1.In() <- (*int)(nil) - ch1.In() <- (*int)(nil) - ch1.In() <- (*int)(nil) - - select { - case ch2.In() <- (*int)(nil): - t.Error("Wrote to full shared-buffer") - case <-ch2.Out(): - t.Error("Read from empty channel") - default: - } - - <-ch1.Out() - - for i := 0; i < 10; i++ { - ch2.In() <- (*int)(nil) - - select { - case ch1.In() <- (*int)(nil): - t.Error("Wrote to full shared-buffer") - case ch2.In() <- (*int)(nil): - t.Error("Wrote to full shared-buffer") - default: - } - - <-ch2.Out() - } - - <-ch1.Out() - <-ch1.Out() - - ch1.Close() - ch2.Close() - buf.Close() -} - -func TestSharedBufferConcurrent(t *testing.T) { - const threads = 10 - const iters = 200 - - buf := NewSharedBuffer(3) - done := make(chan bool) - - for i := 0; i < threads; i++ { - go func() { - ch := buf.NewChannel() - for i := 0; i < iters; i++ { - ch.In() <- i - val := <-ch.Out() - if val.(int) != i { - t.Error("Mismatched value out of channel") - } - } - ch.Close() - done <- true - }() - } - - for i := 0; i < threads; i++ { - <-done - } - close(done) - buf.Close() -} - -func ExampleSharedBuffer() { - // never more than 3 elements in the pipeline at once - buf := NewSharedBuffer(3) - - ch1 := buf.NewChannel() - ch2 := buf.NewChannel() - - // or, instead of a straight pipe, implement your pipeline step - Pipe(ch1, ch2) - - // inputs - go func() { - for i := 0; i < 20; i++ { - ch1.In() <- i - } - ch1.Close() - }() - - for _ = range ch2.Out() { - // outputs - } - - buf.Close() -} diff --git a/vendor/github.com/eapache/queue/queue_test.go b/vendor/github.com/eapache/queue/queue_test.go deleted file mode 100644 index a87584883e..0000000000 --- a/vendor/github.com/eapache/queue/queue_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package queue - -import "testing" - -func TestQueueSimple(t *testing.T) { - q := New() - - for i := 0; i < minQueueLen; i++ { - q.Add(i) - } - for i := 0; i < minQueueLen; i++ { - if q.Peek().(int) != i { - t.Error("peek", i, "had value", q.Peek()) - } - x := q.Remove() - if x != i { - t.Error("remove", i, "had value", x) - } - } -} - -func TestQueueWrapping(t *testing.T) { - q := New() - - for i := 0; i < minQueueLen; i++ { - q.Add(i) - } - for i := 0; i < 3; i++ { - q.Remove() - q.Add(minQueueLen + i) - } - - for i := 0; i < minQueueLen; i++ { - if q.Peek().(int) != i+3 { - t.Error("peek", i, "had value", q.Peek()) - } - q.Remove() - } -} - -func TestQueueLength(t *testing.T) { - q := New() - - if q.Length() != 0 { - t.Error("empty queue length not 0") - } - - for i := 0; i < 1000; i++ { - q.Add(i) - if q.Length() != i+1 { - t.Error("adding: queue with", i, "elements has length", q.Length()) - } - } - for i := 0; i < 1000; i++ { - q.Remove() - if q.Length() != 1000-i-1 { - t.Error("removing: queue with", 1000-i-i, "elements has length", q.Length()) - } - } -} - -func TestQueueGet(t *testing.T) { - q := New() - - for i := 0; i < 1000; i++ { - q.Add(i) - for j := 0; j < q.Length(); j++ { - if q.Get(j).(int) != j { - t.Errorf("index %d doesn't contain %d", j, j) - } - } - } -} - -func TestQueueGetNegative(t *testing.T) { - q := New() - - for i := 0; i < 1000; i++ { - q.Add(i) - for j := 1; j <= q.Length(); j++ { - if q.Get(-j).(int) != q.Length()-j { - t.Errorf("index %d doesn't contain %d", -j, q.Length()-j) - } - } - } -} - -func TestQueueGetOutOfRangePanics(t *testing.T) { - q := New() - - q.Add(1) - q.Add(2) - q.Add(3) - - assertPanics(t, "should panic when negative index", func() { - q.Get(-4) - }) - - assertPanics(t, "should panic when index greater than length", func() { - q.Get(4) - }) -} - -func TestQueuePeekOutOfRangePanics(t *testing.T) { - q := New() - - assertPanics(t, "should panic when peeking empty queue", func() { - q.Peek() - }) - - q.Add(1) - q.Remove() - - assertPanics(t, "should panic when peeking emptied queue", func() { - q.Peek() - }) -} - -func TestQueueRemoveOutOfRangePanics(t *testing.T) { - q := New() - - assertPanics(t, "should panic when removing empty queue", func() { - q.Remove() - }) - - q.Add(1) - q.Remove() - - assertPanics(t, "should panic when removing emptied queue", func() { - q.Remove() - }) -} - -func assertPanics(t *testing.T, name string, f func()) { - defer func() { - if r := recover(); r == nil { - t.Errorf("%s: didn't panic as expected", name) - } - }() - - f() -} - -// General warning: Go's benchmark utility (go test -bench .) increases the number of -// iterations until the benchmarks take a reasonable amount of time to run; memory usage -// is *NOT* considered. On my machine, these benchmarks hit around ~1GB before they've had -// enough, but if you have less than that available and start swapping, then all bets are off. - -func BenchmarkQueueSerial(b *testing.B) { - q := New() - for i := 0; i < b.N; i++ { - q.Add(nil) - } - for i := 0; i < b.N; i++ { - q.Peek() - q.Remove() - } -} - -func BenchmarkQueueGet(b *testing.B) { - q := New() - for i := 0; i < b.N; i++ { - q.Add(i) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - q.Get(i) - } -} - -func BenchmarkQueueTickTock(b *testing.B) { - q := New() - for i := 0; i < b.N; i++ { - q.Add(nil) - q.Peek() - q.Remove() - } -} diff --git a/vendor/github.com/fsnotify/fsnotify/.travis.yml b/vendor/github.com/fsnotify/fsnotify/.travis.yml index 3a5c933bc0..981d1bb813 100644 --- a/vendor/github.com/fsnotify/fsnotify/.travis.yml +++ b/vendor/github.com/fsnotify/fsnotify/.travis.yml @@ -2,12 +2,14 @@ sudo: false language: go go: - - 1.6.3 + - 1.8.x + - 1.9.x - tip matrix: allow_failures: - go: tip + fast_finish: true before_script: - go get -u github.com/golang/lint/golint diff --git a/vendor/github.com/fsnotify/fsnotify/AUTHORS b/vendor/github.com/fsnotify/fsnotify/AUTHORS index 0a5bf8f617..5ab5d41c54 100644 --- a/vendor/github.com/fsnotify/fsnotify/AUTHORS +++ b/vendor/github.com/fsnotify/fsnotify/AUTHORS @@ -8,8 +8,10 @@ # Please keep the list sorted. +Aaron L Adrien Bustany Amit Krishnan +Anmol Sethi Bjørn Erik Pedersen Bruno Bigras Caleb Spare @@ -26,6 +28,7 @@ Kelvin Fo Ken-ichirou MATSUZAWA Matt Layher Nathan Youngman +Nickolai Zeldovich Patrick Paul Hammond Pawel Knap @@ -33,12 +36,15 @@ Pieter Droogendijk Pursuit92 Riku Voipio Rob Figueiredo +Rodrigo Chiossi Slawek Ligus Soge Zhang Tiffany Jernigan Tilak Sharma +Tom Payne Travis Cline Tudor Golubenco +Vahe Khachikyan Yukang bronze1man debrando diff --git a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md index 40d7660d58..be4d7ea2c1 100644 --- a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md +++ b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## v1.4.7 / 2018-01-09 + +* BSD/macOS: Fix possible deadlock on closing the watcher on kqueue (thanks @nhooyr and @glycerine) +* Tests: Fix missing verb on format string (thanks @rchiossi) +* Linux: Fix deadlock in Remove (thanks @aarondl) +* Linux: Watch.Add improvements (avoid race, fix consistency, reduce garbage) (thanks @twpayne) +* Docs: Moved FAQ into the README (thanks @vahe) +* Linux: Properly handle inotify's IN_Q_OVERFLOW event (thanks @zeldovich) +* Docs: replace references to OS X with macOS + ## v1.4.2 / 2016-10-10 * Linux: use InotifyInit1 with IN_CLOEXEC to stop leaking a file descriptor to a child process when using fork/exec [#178](https://github.com/fsnotify/fsnotify/pull/178) (thanks @pattyshack) @@ -79,7 +89,7 @@ kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsn ## v1.0.2 / 2014-08-17 -* [Fix] Missing create events on OS X. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) +* [Fix] Missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) * [Fix] Make ./path and path equivalent. (thanks @zhsso) ## v1.0.0 / 2014-08-15 @@ -142,7 +152,7 @@ kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsn ## v0.9.2 / 2014-08-17 -* [Backport] Fix missing create events on OS X. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) +* [Backport] Fix missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) ## v0.9.1 / 2014-06-12 @@ -161,7 +171,7 @@ kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsn ## v0.8.11 / 2013-11-02 * [Doc] Add Changelog [#72][] (thanks @nathany) -* [Doc] Spotlight and double modify events on OS X [#62][] (reported by @paulhammond) +* [Doc] Spotlight and double modify events on macOS [#62][] (reported by @paulhammond) ## v0.8.10 / 2013-10-19 diff --git a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md index 6a81ba4890..828a60b24b 100644 --- a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md +++ b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md @@ -17,7 +17,7 @@ Please indicate that you have signed the CLA in your pull request. ### How fsnotify is Developed * Development is done on feature branches. -* Tests are run on BSD, Linux, OS X and Windows. +* Tests are run on BSD, Linux, macOS and Windows. * Pull requests are reviewed and [applied to master][am] using [hub][]. * Maintainers may modify or squash commits rather than asking contributors to. * To issue a new release, the maintainers will: @@ -44,7 +44,7 @@ This workflow is [thoroughly explained by Katrina Owen](https://splice.com/blog/ ### Testing -fsnotify uses build tags to compile different code on Linux, BSD, OS X, and Windows. +fsnotify uses build tags to compile different code on Linux, BSD, macOS, and Windows. Before doing a pull request, please do your best to test your changes on multiple platforms, and list which platforms you were able/unable to test on. @@ -58,7 +58,7 @@ To aid in cross-platform testing there is a Vagrantfile for Linux and BSD. Notice: fsnotify file system events won't trigger in shared folders. The tests get around this limitation by using the /tmp directory. -Right now there is no equivalent solution for Windows and OS X, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads). +Right now there is no equivalent solution for Windows and macOS, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads). ### Maintainers diff --git a/vendor/github.com/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md index 3c891e349b..3993207413 100644 --- a/vendor/github.com/fsnotify/fsnotify/README.md +++ b/vendor/github.com/fsnotify/fsnotify/README.md @@ -8,14 +8,14 @@ fsnotify utilizes [golang.org/x/sys](https://godoc.org/golang.org/x/sys) rather go get -u golang.org/x/sys/... ``` -Cross platform: Windows, Linux, BSD and OS X. +Cross platform: Windows, Linux, BSD and macOS. |Adapter |OS |Status | |----------|----------|----------| |inotify |Linux 2.6.27 or later, Android\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)| -|kqueue |BSD, OS X, iOS\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)| +|kqueue |BSD, macOS, iOS\*|Supported [![Build Status](https://travis-ci.org/fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/fsnotify/fsnotify)| |ReadDirectoryChangesW|Windows|Supported [![Build status](https://ci.appveyor.com/api/projects/status/ivwjubaih4r0udeh/branch/master?svg=true)](https://ci.appveyor.com/project/NathanYoungman/fsnotify/branch/master)| -|FSEvents |OS X |[Planned](https://github.com/fsnotify/fsnotify/issues/11)| +|FSEvents |macOS |[Planned](https://github.com/fsnotify/fsnotify/issues/11)| |FEN |Solaris 11 |[In Progress](https://github.com/fsnotify/fsnotify/issues/12)| |fanotify |Linux 2.6.37+ | | |USN Journals |Windows |[Maybe](https://github.com/fsnotify/fsnotify/issues/53)| @@ -23,7 +23,7 @@ Cross platform: Windows, Linux, BSD and OS X. \* Android and iOS are untested. -Please see [the documentation](https://godoc.org/github.com/fsnotify/fsnotify) for usage. Consult the [Wiki](https://github.com/fsnotify/fsnotify/wiki) for the FAQ and further information. +Please see [the documentation](https://godoc.org/github.com/fsnotify/fsnotify) and consult the [FAQ](#faq) for usage information. ## API stability @@ -41,6 +41,35 @@ Please refer to [CONTRIBUTING][] before opening an issue or pull request. See [example_test.go](https://github.com/fsnotify/fsnotify/blob/master/example_test.go). +## FAQ + +**When a file is moved to another directory is it still being watched?** + +No (it shouldn't be, unless you are watching where it was moved to). + +**When I watch a directory, are all subdirectories watched as well?** + +No, you must add watches for any directory you want to watch (a recursive watcher is on the roadmap [#18][]). + +**Do I have to watch the Error and Event channels in a separate goroutine?** + +As of now, yes. Looking into making this single-thread friendly (see [howeyc #7][#7]) + +**Why am I receiving multiple events for the same file on OS X?** + +Spotlight indexing on OS X can result in multiple events (see [howeyc #62][#62]). A temporary workaround is to add your folder(s) to the *Spotlight Privacy settings* until we have a native FSEvents implementation (see [#11][]). + +**How many files can be watched at once?** + +There are OS-specific limits as to how many watches can be created: +* Linux: /proc/sys/fs/inotify/max_user_watches contains the limit, reaching this limit results in a "no space left on device" error. +* BSD / OSX: sysctl variables "kern.maxfiles" and "kern.maxfilesperproc", reaching these limits results in a "too many open files" error. + +[#62]: https://github.com/howeyc/fsnotify/issues/62 +[#18]: https://github.com/fsnotify/fsnotify/issues/18 +[#11]: https://github.com/fsnotify/fsnotify/issues/11 +[#7]: https://github.com/howeyc/fsnotify/issues/7 + [contributing]: https://github.com/fsnotify/fsnotify/blob/master/CONTRIBUTING.md ## Related Projects diff --git a/vendor/github.com/fsnotify/fsnotify/example_test.go b/vendor/github.com/fsnotify/fsnotify/example_test.go deleted file mode 100644 index 700502cb3a..0000000000 --- a/vendor/github.com/fsnotify/fsnotify/example_test.go +++ /dev/null @@ -1,42 +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 !plan9 - -package fsnotify_test - -import ( - "log" - - "github.com/fsnotify/fsnotify" -) - -func ExampleNewWatcher() { - watcher, err := fsnotify.NewWatcher() - if err != nil { - log.Fatal(err) - } - defer watcher.Close() - - done := make(chan bool) - go func() { - for { - select { - case event := <-watcher.Events: - log.Println("event:", event) - if event.Op&fsnotify.Write == fsnotify.Write { - log.Println("modified file:", event.Name) - } - case err := <-watcher.Errors: - log.Println("error:", err) - } - } - }() - - err = watcher.Add("/tmp/foo") - if err != nil { - log.Fatal(err) - } - <-done -} diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go index e7f55fee7a..190bf0de57 100644 --- a/vendor/github.com/fsnotify/fsnotify/fsnotify.go +++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go @@ -9,6 +9,7 @@ package fsnotify import ( "bytes" + "errors" "fmt" ) @@ -60,3 +61,6 @@ func (op Op) String() string { func (e Event) String() string { return fmt.Sprintf("%q: %s", e.Name, e.Op.String()) } + +// Common errors that can be reported by a watcher +var ErrEventOverflow = errors.New("fsnotify queue overflow") diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go b/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go deleted file mode 100644 index 9d6d72afc5..0000000000 --- a/vendor/github.com/fsnotify/fsnotify/fsnotify_test.go +++ /dev/null @@ -1,40 +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. - -// +build !plan9 - -package fsnotify - -import "testing" - -func TestEventStringWithValue(t *testing.T) { - for opMask, expectedString := range map[Op]string{ - Chmod | Create: `"/usr/someFile": CREATE|CHMOD`, - Rename: `"/usr/someFile": RENAME`, - Remove: `"/usr/someFile": REMOVE`, - Write | Chmod: `"/usr/someFile": WRITE|CHMOD`, - } { - event := Event{Name: "/usr/someFile", Op: opMask} - if event.String() != expectedString { - t.Fatalf("Expected %s, got: %v", expectedString, event.String()) - } - - } -} - -func TestEventOpStringWithValue(t *testing.T) { - expectedOpString := "WRITE|CHMOD" - event := Event{Name: "someFile", Op: Write | Chmod} - if event.Op.String() != expectedOpString { - t.Fatalf("Expected %s, got: %v", expectedOpString, event.Op.String()) - } -} - -func TestEventOpStringWithNoValue(t *testing.T) { - expectedOpString := "" - event := Event{Name: "testFile", Op: 0} - if event.Op.String() != expectedOpString { - t.Fatalf("Expected %s, got: %v", expectedOpString, event.Op.String()) - } -} diff --git a/vendor/github.com/fsnotify/fsnotify/inotify.go b/vendor/github.com/fsnotify/fsnotify/inotify.go index f3b74c51f0..d9fd1b88a0 100644 --- a/vendor/github.com/fsnotify/fsnotify/inotify.go +++ b/vendor/github.com/fsnotify/fsnotify/inotify.go @@ -24,7 +24,6 @@ type Watcher struct { Events chan Event Errors chan error mu sync.Mutex // Map access - cv *sync.Cond // sync removing on rm_watch with IN_IGNORE fd int poller *fdPoller watches map[string]*watch // Map of inotify watches (key: path) @@ -56,7 +55,6 @@ func NewWatcher() (*Watcher, error) { done: make(chan struct{}), doneResp: make(chan struct{}), } - w.cv = sync.NewCond(&w.mu) go w.readEvents() return w, nil @@ -103,21 +101,23 @@ func (w *Watcher) Add(name string) error { var flags uint32 = agnosticEvents w.mu.Lock() - watchEntry, found := w.watches[name] - w.mu.Unlock() - if found { - watchEntry.flags |= flags - flags |= unix.IN_MASK_ADD + defer w.mu.Unlock() + watchEntry := w.watches[name] + if watchEntry != nil { + flags |= watchEntry.flags | unix.IN_MASK_ADD } wd, errno := unix.InotifyAddWatch(w.fd, name, flags) if wd == -1 { return errno } - w.mu.Lock() - w.watches[name] = &watch{wd: uint32(wd), flags: flags} - w.paths[wd] = name - w.mu.Unlock() + if watchEntry == nil { + w.watches[name] = &watch{wd: uint32(wd), flags: flags} + w.paths[wd] = name + } else { + watchEntry.wd = uint32(wd) + watchEntry.flags = flags + } return nil } @@ -135,6 +135,13 @@ func (w *Watcher) Remove(name string) error { if !ok { return fmt.Errorf("can't remove non-existent inotify watch for: %s", name) } + + // We successfully removed the watch if InotifyRmWatch doesn't return an + // error, we need to clean up our internal state to ensure it matches + // inotify's kernel state. + delete(w.paths, int(watch.wd)) + delete(w.watches, name) + // inotify_rm_watch will return EINVAL if the file has been deleted; // the inotify will already have been removed. // watches and pathes are deleted in ignoreLinux() implicitly and asynchronously @@ -152,13 +159,6 @@ func (w *Watcher) Remove(name string) error { return errno } - // wait until ignoreLinux() deleting maps - exists := true - for exists { - w.cv.Wait() - _, exists = w.watches[name] - } - return nil } @@ -245,13 +245,31 @@ func (w *Watcher) readEvents() { mask := uint32(raw.Mask) nameLen := uint32(raw.Len) + + if mask&unix.IN_Q_OVERFLOW != 0 { + select { + case w.Errors <- ErrEventOverflow: + case <-w.done: + return + } + } + // If the event happened to the watched directory or the watched file, the kernel // doesn't append the filename to the event, but we would like to always fill the // the "Name" field with a valid filename. We retrieve the path of the watch from // the "paths" map. w.mu.Lock() - name := w.paths[int(raw.Wd)] + name, ok := w.paths[int(raw.Wd)] + // IN_DELETE_SELF occurs when the file/directory being watched is removed. + // This is a sign to clean up the maps, otherwise we are no longer in sync + // with the inotify kernel state which has already deleted the watch + // automatically. + if ok && mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { + delete(w.paths, int(raw.Wd)) + delete(w.watches, name) + } w.mu.Unlock() + if nameLen > 0 { // Point "bytes" at the first byte of the filename bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&buf[offset+unix.SizeofInotifyEvent])) @@ -262,7 +280,7 @@ func (w *Watcher) readEvents() { event := newEvent(name, mask) // Send the events that are not ignored on the events channel - if !event.ignoreLinux(w, raw.Wd, mask) { + if !event.ignoreLinux(mask) { select { case w.Events <- event: case <-w.done: @@ -279,15 +297,9 @@ func (w *Watcher) readEvents() { // Certain types of events can be "ignored" and not sent over the Events // channel. Such as events marked ignore by the kernel, or MODIFY events // against files that do not exist. -func (e *Event) ignoreLinux(w *Watcher, wd int32, mask uint32) bool { +func (e *Event) ignoreLinux(mask uint32) bool { // Ignore anything the inotify API says to ignore if mask&unix.IN_IGNORED == unix.IN_IGNORED { - w.mu.Lock() - defer w.mu.Unlock() - name := w.paths[int(wd)] - delete(w.paths, int(wd)) - delete(w.watches, name) - w.cv.Broadcast() return true } diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go b/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go deleted file mode 100644 index 26623efeff..0000000000 --- a/vendor/github.com/fsnotify/fsnotify/inotify_poller_test.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2015 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 - -package fsnotify - -import ( - "testing" - "time" - - "golang.org/x/sys/unix" -) - -type testFd [2]int - -func makeTestFd(t *testing.T) testFd { - var tfd testFd - errno := unix.Pipe(tfd[:]) - if errno != nil { - t.Fatalf("Failed to create pipe: %v", errno) - } - return tfd -} - -func (tfd testFd) fd() int { - return tfd[0] -} - -func (tfd testFd) closeWrite(t *testing.T) { - errno := unix.Close(tfd[1]) - if errno != nil { - t.Fatalf("Failed to close write end of pipe: %v", errno) - } -} - -func (tfd testFd) put(t *testing.T) { - buf := make([]byte, 10) - _, errno := unix.Write(tfd[1], buf) - if errno != nil { - t.Fatalf("Failed to write to pipe: %v", errno) - } -} - -func (tfd testFd) get(t *testing.T) { - buf := make([]byte, 10) - _, errno := unix.Read(tfd[0], buf) - if errno != nil { - t.Fatalf("Failed to read from pipe: %v", errno) - } -} - -func (tfd testFd) close() { - unix.Close(tfd[1]) - unix.Close(tfd[0]) -} - -func makePoller(t *testing.T) (testFd, *fdPoller) { - tfd := makeTestFd(t) - poller, err := newFdPoller(tfd.fd()) - if err != nil { - t.Fatalf("Failed to create poller: %v", err) - } - return tfd, poller -} - -func TestPollerWithBadFd(t *testing.T) { - _, err := newFdPoller(-1) - if err != unix.EBADF { - t.Fatalf("Expected EBADF, got: %v", err) - } -} - -func TestPollerWithData(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - tfd.put(t) - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } - tfd.get(t) -} - -func TestPollerWithWakeup(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - err := poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if ok { - t.Fatalf("expected poller to return false") - } -} - -func TestPollerWithClose(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - tfd.closeWrite(t) - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } -} - -func TestPollerWithWakeupAndData(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - tfd.put(t) - err := poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - - // both data and wakeup - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } - - // data is still in the buffer, wakeup is cleared - ok, err = poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } - - tfd.get(t) - // data is gone, only wakeup now - err = poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - ok, err = poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if ok { - t.Fatalf("expected poller to return false") - } -} - -func TestPollerConcurrent(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - oks := make(chan bool) - live := make(chan bool) - defer close(live) - go func() { - defer close(oks) - for { - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - oks <- ok - if !<-live { - return - } - } - }() - - // Try a write - select { - case <-time.After(50 * time.Millisecond): - case <-oks: - t.Fatalf("poller did not wait") - } - tfd.put(t) - if !<-oks { - t.Fatalf("expected true") - } - tfd.get(t) - live <- true - - // Try a wakeup - select { - case <-time.After(50 * time.Millisecond): - case <-oks: - t.Fatalf("poller did not wait") - } - err := poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - if <-oks { - t.Fatalf("expected false") - } - live <- true - - // Try a close - select { - case <-time.After(50 * time.Millisecond): - case <-oks: - t.Fatalf("poller did not wait") - } - tfd.closeWrite(t) - if !<-oks { - t.Fatalf("expected true") - } - tfd.get(t) -} diff --git a/vendor/github.com/fsnotify/fsnotify/inotify_test.go b/vendor/github.com/fsnotify/fsnotify/inotify_test.go deleted file mode 100644 index a4bb202d1f..0000000000 --- a/vendor/github.com/fsnotify/fsnotify/inotify_test.go +++ /dev/null @@ -1,360 +0,0 @@ -// Copyright 2015 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 - -package fsnotify - -import ( - "fmt" - "os" - "path/filepath" - "strings" - "testing" - "time" -) - -func TestInotifyCloseRightAway(t *testing.T) { - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - - // Close immediately; it won't even reach the first unix.Read. - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func TestInotifyCloseSlightlyLater(t *testing.T) { - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - - // Wait until readEvents has reached unix.Read, and Close. - <-time.After(50 * time.Millisecond) - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func TestInotifyCloseSlightlyLaterWithWatch(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - w.Add(testDir) - - // Wait until readEvents has reached unix.Read, and Close. - <-time.After(50 * time.Millisecond) - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func TestInotifyCloseAfterRead(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - - err = w.Add(testDir) - if err != nil { - t.Fatalf("Failed to add .") - } - - // Generate an event. - os.Create(filepath.Join(testDir, "somethingSOMETHINGsomethingSOMETHING")) - - // Wait for readEvents to read the event, then close the watcher. - <-time.After(50 * time.Millisecond) - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func isWatcherReallyClosed(t *testing.T, w *Watcher) { - select { - case err, ok := <-w.Errors: - if ok { - t.Fatalf("w.Errors is not closed; readEvents is still alive after closing (error: %v)", err) - } - default: - t.Fatalf("w.Errors would have blocked; readEvents is still alive!") - } - - select { - case _, ok := <-w.Events: - if ok { - t.Fatalf("w.Events is not closed; readEvents is still alive after closing") - } - default: - t.Fatalf("w.Events would have blocked; readEvents is still alive!") - } -} - -func TestInotifyCloseCreate(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testDir) - if err != nil { - t.Fatalf("Failed to add testDir: %v", err) - } - h, err := os.Create(filepath.Join(testDir, "testfile")) - if err != nil { - t.Fatalf("Failed to create file in testdir: %v", err) - } - h.Close() - select { - case _ = <-w.Events: - case err := <-w.Errors: - t.Fatalf("Error from watcher: %v", err) - case <-time.After(50 * time.Millisecond): - t.Fatalf("Took too long to wait for event") - } - - // At this point, we've received one event, so the goroutine is ready. - // It's also blocking on unix.Read. - // Now we try to swap the file descriptor under its nose. - w.Close() - w, err = NewWatcher() - defer w.Close() - if err != nil { - t.Fatalf("Failed to create second watcher: %v", err) - } - - <-time.After(50 * time.Millisecond) - err = w.Add(testDir) - if err != nil { - t.Fatalf("Error adding testDir again: %v", err) - } -} - -// This test verifies the watcher can keep up with file creations/deletions -// when under load. -func TestInotifyStress(t *testing.T) { - maxNumToCreate := 1000 - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - testFilePrefix := filepath.Join(testDir, "testfile") - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testDir) - if err != nil { - t.Fatalf("Failed to add testDir: %v", err) - } - - doneChan := make(chan struct{}) - // The buffer ensures that the file generation goroutine is never blocked. - errChan := make(chan error, 2*maxNumToCreate) - - go func() { - for i := 0; i < maxNumToCreate; i++ { - testFile := fmt.Sprintf("%s%d", testFilePrefix, i) - - handle, err := os.Create(testFile) - if err != nil { - errChan <- fmt.Errorf("Create failed: %v", err) - continue - } - - err = handle.Close() - if err != nil { - errChan <- fmt.Errorf("Close failed: %v", err) - continue - } - } - - // If we delete a newly created file too quickly, inotify will skip the - // create event and only send the delete event. - time.Sleep(100 * time.Millisecond) - - for i := 0; i < maxNumToCreate; i++ { - testFile := fmt.Sprintf("%s%d", testFilePrefix, i) - err = os.Remove(testFile) - if err != nil { - errChan <- fmt.Errorf("Remove failed: %v", err) - } - } - - close(doneChan) - }() - - creates := 0 - removes := 0 - - finished := false - after := time.After(10 * time.Second) - for !finished { - select { - case <-after: - t.Fatalf("Not done") - case <-doneChan: - finished = true - case err := <-errChan: - t.Fatalf("Got an error from file creator goroutine: %v", err) - case err := <-w.Errors: - t.Fatalf("Got an error from watcher: %v", err) - case evt := <-w.Events: - if !strings.HasPrefix(evt.Name, testFilePrefix) { - t.Fatalf("Got an event for an unknown file: %s", evt.Name) - } - if evt.Op == Create { - creates++ - } - if evt.Op == Remove { - removes++ - } - } - } - - // Drain remaining events from channels - count := 0 - for count < 10 { - select { - case err := <-errChan: - t.Fatalf("Got an error from file creator goroutine: %v", err) - case err := <-w.Errors: - t.Fatalf("Got an error from watcher: %v", err) - case evt := <-w.Events: - if !strings.HasPrefix(evt.Name, testFilePrefix) { - t.Fatalf("Got an event for an unknown file: %s", evt.Name) - } - if evt.Op == Create { - creates++ - } - if evt.Op == Remove { - removes++ - } - count = 0 - default: - count++ - // Give the watcher chances to fill the channels. - time.Sleep(time.Millisecond) - } - } - - if creates-removes > 1 || creates-removes < -1 { - t.Fatalf("Creates and removes should not be off by more than one: %d creates, %d removes", creates, removes) - } - if creates < 50 { - t.Fatalf("Expected at least 50 creates, got %d", creates) - } -} - -func TestInotifyRemoveTwice(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - testFile := filepath.Join(testDir, "testfile") - - handle, err := os.Create(testFile) - if err != nil { - t.Fatalf("Create failed: %v", err) - } - handle.Close() - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testFile) - if err != nil { - t.Fatalf("Failed to add testFile: %v", err) - } - - err = os.Remove(testFile) - if err != nil { - t.Fatalf("Failed to remove testFile: %v", err) - } - - err = w.Remove(testFile) - if err == nil { - t.Fatalf("no error on removing invalid file") - } - s1 := fmt.Sprintf("%s", err) - - err = w.Remove(testFile) - if err == nil { - t.Fatalf("no error on removing invalid file") - } - s2 := fmt.Sprintf("%s", err) - - if s1 != s2 { - t.Fatalf("receive different error - %s / %s", s1, s2) - } -} - -func TestInotifyInnerMapLength(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - testFile := filepath.Join(testDir, "testfile") - - handle, err := os.Create(testFile) - if err != nil { - t.Fatalf("Create failed: %v", err) - } - handle.Close() - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testFile) - if err != nil { - t.Fatalf("Failed to add testFile: %v", err) - } - go func() { - for err := range w.Errors { - t.Fatalf("error received: %s", err) - } - }() - - err = os.Remove(testFile) - if err != nil { - t.Fatalf("Failed to remove testFile: %v", err) - } - _ = <-w.Events // consume Remove event - <-time.After(50 * time.Millisecond) // wait IN_IGNORE propagated - - w.mu.Lock() - defer w.mu.Unlock() - if len(w.watches) != 0 { - t.Fatalf("Expected watches len is 0, but got: %d, %v", len(w.watches), w.watches) - } - if len(w.paths) != 0 { - t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths) - } -} diff --git a/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go b/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go deleted file mode 100644 index 5564554f72..0000000000 --- a/vendor/github.com/fsnotify/fsnotify/integration_darwin_test.go +++ /dev/null @@ -1,147 +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 fsnotify - -import ( - "os" - "path/filepath" - "testing" - "time" - - "golang.org/x/sys/unix" -) - -// testExchangedataForWatcher tests the watcher with the exchangedata operation on OS X. -// -// This is widely used for atomic saves on OS X, e.g. TextMate and in Apple's NSDocument. -// -// See https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/exchangedata.2.html -// Also see: https://github.com/textmate/textmate/blob/cd016be29489eba5f3c09b7b70b06da134dda550/Frameworks/io/src/swap_file_data.cc#L20 -func testExchangedataForWatcher(t *testing.T, watchDir bool) { - // Create directory to watch - testDir1 := tempMkdir(t) - - // For the intermediate file - testDir2 := tempMkdir(t) - - defer os.RemoveAll(testDir1) - defer os.RemoveAll(testDir2) - - resolvedFilename := "TestFsnotifyEvents.file" - - // TextMate does: - // - // 1. exchangedata (intermediate, resolved) - // 2. unlink intermediate - // - // Let's try to simulate that: - resolved := filepath.Join(testDir1, resolvedFilename) - intermediate := filepath.Join(testDir2, resolvedFilename+"~") - - // Make sure we create the file before we start watching - createAndSyncFile(t, resolved) - - watcher := newWatcher(t) - - // Test both variants in isolation - if watchDir { - addWatch(t, watcher, testDir1) - } else { - addWatch(t, watcher, resolved) - } - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var removeReceived counter - var createReceived counter - - done := make(chan bool) - - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(resolved) { - if event.Op&Remove == Remove { - removeReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - } - t.Logf("event received: %s", event) - } - done <- true - }() - - // Repeat to make sure the watched file/directory "survives" the REMOVE/CREATE loop. - for i := 1; i <= 3; i++ { - // The intermediate file is created in a folder outside the watcher - createAndSyncFile(t, intermediate) - - // 1. Swap - if err := unix.Exchangedata(intermediate, resolved, 0); err != nil { - t.Fatalf("[%d] exchangedata failed: %s", i, err) - } - - time.Sleep(50 * time.Millisecond) - - // 2. Delete the intermediate file - err := os.Remove(intermediate) - - if err != nil { - t.Fatalf("[%d] remove %s failed: %s", i, intermediate, err) - } - - time.Sleep(50 * time.Millisecond) - - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - - // The events will be (CHMOD + REMOVE + CREATE) X 2. Let's focus on the last two: - if removeReceived.value() < 3 { - t.Fatal("fsnotify remove events have not been received after 500 ms") - } - - if createReceived.value() < 3 { - t.Fatal("fsnotify create events have not been received after 500 ms") - } - - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -// TestExchangedataInWatchedDir test exchangedata operation on file in watched dir. -func TestExchangedataInWatchedDir(t *testing.T) { - testExchangedataForWatcher(t, true) -} - -// TestExchangedataInWatchedDir test exchangedata operation on watched file. -func TestExchangedataInWatchedFile(t *testing.T) { - testExchangedataForWatcher(t, false) -} - -func createAndSyncFile(t *testing.T, filepath string) { - f1, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating %s failed: %s", filepath, err) - } - f1.Sync() - f1.Close() -} diff --git a/vendor/github.com/fsnotify/fsnotify/integration_test.go b/vendor/github.com/fsnotify/fsnotify/integration_test.go deleted file mode 100644 index 8b7e9d3ec8..0000000000 --- a/vendor/github.com/fsnotify/fsnotify/integration_test.go +++ /dev/null @@ -1,1237 +0,0 @@ -// Copyright 2010 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 !plan9,!solaris - -package fsnotify - -import ( - "io/ioutil" - "os" - "os/exec" - "path" - "path/filepath" - "runtime" - "sync/atomic" - "testing" - "time" -) - -// An atomic counter -type counter struct { - val int32 -} - -func (c *counter) increment() { - atomic.AddInt32(&c.val, 1) -} - -func (c *counter) value() int32 { - return atomic.LoadInt32(&c.val) -} - -func (c *counter) reset() { - atomic.StoreInt32(&c.val, 0) -} - -// tempMkdir makes a temporary directory -func tempMkdir(t *testing.T) string { - dir, err := ioutil.TempDir("", "fsnotify") - if err != nil { - t.Fatalf("failed to create test directory: %s", err) - } - return dir -} - -// tempMkFile makes a temporary file. -func tempMkFile(t *testing.T, dir string) string { - f, err := ioutil.TempFile(dir, "fsnotify") - if err != nil { - t.Fatalf("failed to create test file: %v", err) - } - defer f.Close() - return f.Name() -} - -// newWatcher initializes an fsnotify Watcher instance. -func newWatcher(t *testing.T) *Watcher { - watcher, err := NewWatcher() - if err != nil { - t.Fatalf("NewWatcher() failed: %s", err) - } - return watcher -} - -// addWatch adds a watch for a directory -func addWatch(t *testing.T, watcher *Watcher, dir string) { - if err := watcher.Add(dir); err != nil { - t.Fatalf("watcher.Add(%q) failed: %s", dir, err) - } -} - -func TestFsnotifyMultipleOperations(t *testing.T) { - watcher := newWatcher(t) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create directory that's not watched - testDirToMoveFiles := tempMkdir(t) - defer os.RemoveAll(testDirToMoveFiles) - - testFile := filepath.Join(testDir, "TestFsnotifySeq.testfile") - testFileRenamed := filepath.Join(testDirToMoveFiles, "TestFsnotifySeqRename.testfile") - - addWatch(t, watcher, testDir) - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, modifyReceived, deleteReceived, renameReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - if event.Op&Write == Write { - modifyReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - if event.Op&Rename == Rename { - renameReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // Modify the file outside of the watched dir - f, err = os.Open(testFileRenamed) - if err != nil { - t.Fatalf("open test renamed file failed: %s", err) - } - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Recreate the file that was moved - f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Close() - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 2 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2) - } - mReceived := modifyReceived.value() - if mReceived != 1 { - t.Fatalf("incorrect number of modify events received after 500 ms (%d vs %d)", mReceived, 1) - } - dReceived := deleteReceived.value() - rReceived := renameReceived.value() - if dReceived+rReceived != 1 { - t.Fatalf("incorrect number of rename+delete events received after 500 ms (%d vs %d)", rReceived+dReceived, 1) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyMultipleCreates(t *testing.T) { - watcher := newWatcher(t) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - testFile := filepath.Join(testDir, "TestFsnotifySeq.testfile") - - addWatch(t, watcher, testDir) - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, modifyReceived, deleteReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - if event.Op&Write == Write { - modifyReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - os.Remove(testFile) - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Recreate the file - f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Close() - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Modify - f, err = os.OpenFile(testFile, os.O_WRONLY, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Modify - f, err = os.OpenFile(testFile, os.O_WRONLY, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 2 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2) - } - mReceived := modifyReceived.value() - if mReceived < 3 { - t.Fatalf("incorrect number of modify events received after 500 ms (%d vs atleast %d)", mReceived, 3) - } - dReceived := deleteReceived.value() - if dReceived != 1 { - t.Fatalf("incorrect number of rename+delete events received after 500 ms (%d vs %d)", dReceived, 1) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyDirOnly(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - // This should NOT add any events to the fsnotify event queue - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDir, "TestFsnotifyDirOnly.testfile") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, modifyReceived, deleteReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileAlreadyExists) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - if event.Op&Write == Write { - modifyReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - os.Remove(testFile) - os.Remove(testFileAlreadyExists) - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 1 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 1) - } - mReceived := modifyReceived.value() - if mReceived != 1 { - t.Fatalf("incorrect number of modify events received after 500 ms (%d vs %d)", mReceived, 1) - } - dReceived := deleteReceived.value() - if dReceived != 2 { - t.Fatalf("incorrect number of delete events received after 500 ms (%d vs %d)", dReceived, 2) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyDeleteWatchedDir(t *testing.T) { - watcher := newWatcher(t) - defer watcher.Close() - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - addWatch(t, watcher, testDir) - - // Add a watch for testFile - addWatch(t, watcher, testFileAlreadyExists) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var deleteReceived counter - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFileAlreadyExists) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - }() - - os.RemoveAll(testDir) - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - dReceived := deleteReceived.value() - if dReceived < 2 { - t.Fatalf("did not receive at least %d delete events, received %d after 500 ms", 2, dReceived) - } -} - -func TestFsnotifySubDir(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - testFile1 := filepath.Join(testDir, "TestFsnotifyFile1.testfile") - testSubDir := filepath.Join(testDir, "sub") - testSubDirFile := filepath.Join(testDir, "sub/TestFsnotifyFile1.testfile") - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, deleteReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testSubDir) || event.Name == filepath.Clean(testFile1) { - t.Logf("event received: %s", event) - if event.Op&Create == Create { - createReceived.increment() - } - if event.Op&Remove == Remove { - deleteReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - addWatch(t, watcher, testDir) - - // Create sub-directory - if err := os.Mkdir(testSubDir, 0777); err != nil { - t.Fatalf("failed to create test sub-directory: %s", err) - } - - // Create a file - var f *os.File - f, err := os.OpenFile(testFile1, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - - // Create a file (Should not see this! we are not watching subdir) - var fs *os.File - fs, err = os.OpenFile(testSubDirFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - fs.Sync() - fs.Close() - - time.Sleep(200 * time.Millisecond) - - // Make sure receive deletes for both file and sub-directory - os.RemoveAll(testSubDir) - os.Remove(testFile1) - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 2 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2) - } - dReceived := deleteReceived.value() - if dReceived != 2 { - t.Fatalf("incorrect number of delete events received after 500 ms (%d vs %d)", dReceived, 2) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyRename(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDir, "TestFsnotifyEvents.testfile") - testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var renameReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileRenamed) { - if event.Op&Rename == Rename { - renameReceived.increment() - } - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - f.WriteString("data") - f.Sync() - f.Close() - - // Add a watch for testFile - addWatch(t, watcher, testFile) - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - if renameReceived.value() == 0 { - t.Fatal("fsnotify rename events have not been received after 500 ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } - - os.Remove(testFileRenamed) -} - -func TestFsnotifyRenameToCreate(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create directory to get file - testDirFrom := tempMkdir(t) - defer os.RemoveAll(testDirFrom) - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDirFrom, "TestFsnotifyEvents.testfile") - testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileRenamed) { - if event.Op&Create == Create { - createReceived.increment() - } - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - if createReceived.value() == 0 { - t.Fatal("fsnotify create events have not been received after 500 ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } - - os.Remove(testFileRenamed) -} - -func TestFsnotifyRenameToOverwrite(t *testing.T) { - switch runtime.GOOS { - case "plan9", "windows": - t.Skipf("skipping test on %q (os.Rename over existing file does not create event).", runtime.GOOS) - } - - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create directory to get file - testDirFrom := tempMkdir(t) - defer os.RemoveAll(testDirFrom) - - testFile := filepath.Join(testDirFrom, "TestFsnotifyEvents.testfile") - testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed") - - // Create a file - var fr *os.File - fr, err := os.OpenFile(testFileRenamed, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - fr.Sync() - fr.Close() - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var eventReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testFileRenamed) { - eventReceived.increment() - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - if eventReceived.value() == 0 { - t.Fatal("fsnotify events have not been received after 500 ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } - - os.Remove(testFileRenamed) -} - -func TestRemovalOfWatch(t *testing.T) { - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - watcher := newWatcher(t) - defer watcher.Close() - - addWatch(t, watcher, testDir) - if err := watcher.Remove(testDir); err != nil { - t.Fatalf("Could not remove the watch: %v\n", err) - } - - go func() { - select { - case ev := <-watcher.Events: - t.Fatalf("We received event: %v\n", ev) - case <-time.After(500 * time.Millisecond): - t.Log("No event received, as expected.") - } - }() - - time.Sleep(200 * time.Millisecond) - // Modify the file outside of the watched dir - f, err := os.Open(testFileAlreadyExists) - if err != nil { - t.Fatalf("Open test file failed: %s", err) - } - f.WriteString("data") - f.Sync() - f.Close() - if err := os.Chmod(testFileAlreadyExists, 0700); err != nil { - t.Fatalf("chmod failed: %s", err) - } - time.Sleep(400 * time.Millisecond) -} - -func TestFsnotifyAttrib(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("attributes don't work on Windows.") - } - - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDir, "TestFsnotifyAttrib.testfile") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - // The modifyReceived counter counts IsModify events that are not IsAttrib, - // and the attribReceived counts IsAttrib events (which are also IsModify as - // a consequence). - var modifyReceived counter - var attribReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) { - if event.Op&Write == Write { - modifyReceived.increment() - } - if event.Op&Chmod == Chmod { - attribReceived.increment() - } - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - f.WriteString("data") - f.Sync() - f.Close() - - // Add a watch for testFile - addWatch(t, watcher, testFile) - - if err := os.Chmod(testFile, 0700); err != nil { - t.Fatalf("chmod failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - // Creating/writing a file changes also the mtime, so IsAttrib should be set to true here - time.Sleep(500 * time.Millisecond) - if modifyReceived.value() != 0 { - t.Fatal("received an unexpected modify event when creating a test file") - } - if attribReceived.value() == 0 { - t.Fatal("fsnotify attribute events have not received after 500 ms") - } - - // Modifying the contents of the file does not set the attrib flag (although eg. the mtime - // might have been modified). - modifyReceived.reset() - attribReceived.reset() - - f, err = os.OpenFile(testFile, os.O_WRONLY, 0) - if err != nil { - t.Fatalf("reopening test file failed: %s", err) - } - - f.WriteString("more data") - f.Sync() - f.Close() - - time.Sleep(500 * time.Millisecond) - - if modifyReceived.value() != 1 { - t.Fatal("didn't receive a modify event after changing test file contents") - } - - if attribReceived.value() != 0 { - t.Fatal("did receive an unexpected attrib event after changing test file contents") - } - - modifyReceived.reset() - attribReceived.reset() - - // Doing a chmod on the file should trigger an event with the "attrib" flag set (the contents - // of the file are not changed though) - if err := os.Chmod(testFile, 0600); err != nil { - t.Fatalf("chmod failed: %s", err) - } - - time.Sleep(500 * time.Millisecond) - - if attribReceived.value() != 1 { - t.Fatal("didn't receive an attribute change after 500ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(1e9): - t.Fatal("event stream was not closed after 1 second") - } - - os.Remove(testFile) -} - -func TestFsnotifyClose(t *testing.T) { - watcher := newWatcher(t) - watcher.Close() - - var done int32 - go func() { - watcher.Close() - atomic.StoreInt32(&done, 1) - }() - - time.Sleep(50e6) // 50 ms - if atomic.LoadInt32(&done) == 0 { - t.Fatal("double Close() test failed: second Close() call didn't return") - } - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - if err := watcher.Add(testDir); err == nil { - t.Fatal("expected error on Watch() after Close(), got nil") - } -} - -func TestFsnotifyFakeSymlink(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("symlinks don't work on Windows.") - } - - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - var errorsReceived counter - // Receive errors on the error channel on a separate goroutine - go func() { - for errors := range watcher.Errors { - t.Logf("Received error: %s", errors) - errorsReceived.increment() - } - }() - - // Count the CREATE events received - var createEventsReceived, otherEventsReceived counter - go func() { - for ev := range watcher.Events { - t.Logf("event received: %s", ev) - if ev.Op&Create == Create { - createEventsReceived.increment() - } else { - otherEventsReceived.increment() - } - } - }() - - addWatch(t, watcher, testDir) - - if err := os.Symlink(filepath.Join(testDir, "zzz"), filepath.Join(testDir, "zzznew")); err != nil { - t.Fatalf("Failed to create bogus symlink: %s", err) - } - t.Logf("Created bogus symlink") - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - - // Should not be error, just no events for broken links (watching nothing) - if errorsReceived.value() > 0 { - t.Fatal("fsnotify errors have been received.") - } - if otherEventsReceived.value() > 0 { - t.Fatal("fsnotify other events received on the broken link") - } - - // Except for 1 create event (for the link itself) - if createEventsReceived.value() == 0 { - t.Fatal("fsnotify create events were not received after 500 ms") - } - if createEventsReceived.value() > 1 { - t.Fatal("fsnotify more create events received than expected") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() -} - -func TestCyclicSymlink(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("symlinks don't work on Windows.") - } - - watcher := newWatcher(t) - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - link := path.Join(testDir, "link") - if err := os.Symlink(".", link); err != nil { - t.Fatalf("could not make symlink: %v", err) - } - addWatch(t, watcher, testDir) - - var createEventsReceived counter - go func() { - for ev := range watcher.Events { - if ev.Op&Create == Create { - createEventsReceived.increment() - } - } - }() - - if err := os.Remove(link); err != nil { - t.Fatalf("Error removing link: %v", err) - } - - // It would be nice to be able to expect a delete event here, but kqueue has - // no way for us to get events on symlinks themselves, because opening them - // opens an fd to the file to which they point. - - if err := ioutil.WriteFile(link, []byte("foo"), 0700); err != nil { - t.Fatalf("could not make symlink: %v", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - - if got := createEventsReceived.value(); got == 0 { - t.Errorf("want at least 1 create event got %v", got) - } - - watcher.Close() -} - -// TestConcurrentRemovalOfWatch tests that concurrent calls to RemoveWatch do not race. -// See https://codereview.appspot.com/103300045/ -// go test -test.run=TestConcurrentRemovalOfWatch -test.cpu=1,1,1,1,1 -race -func TestConcurrentRemovalOfWatch(t *testing.T) { - if runtime.GOOS != "darwin" { - t.Skip("regression test for race only present on darwin") - } - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - watcher := newWatcher(t) - defer watcher.Close() - - addWatch(t, watcher, testDir) - - // Test that RemoveWatch can be invoked concurrently, with no data races. - removed1 := make(chan struct{}) - go func() { - defer close(removed1) - watcher.Remove(testDir) - }() - removed2 := make(chan struct{}) - go func() { - close(removed2) - watcher.Remove(testDir) - }() - <-removed1 - <-removed2 -} - -func TestClose(t *testing.T) { - // Regression test for #59 bad file descriptor from Close - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - watcher := newWatcher(t) - if err := watcher.Add(testDir); err != nil { - t.Fatalf("Expected no error on Add, got %v", err) - } - err := watcher.Close() - if err != nil { - t.Fatalf("Expected no error on Close, got %v.", err) - } -} - -// TestRemoveWithClose tests if one can handle Remove events and, at the same -// time, close Watcher object without any data races. -func TestRemoveWithClose(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - const fileN = 200 - tempFiles := make([]string, 0, fileN) - for i := 0; i < fileN; i++ { - tempFiles = append(tempFiles, tempMkFile(t, testDir)) - } - watcher := newWatcher(t) - if err := watcher.Add(testDir); err != nil { - t.Fatalf("Expected no error on Add, got %v", err) - } - startC, stopC := make(chan struct{}), make(chan struct{}) - errC := make(chan error) - go func() { - for { - select { - case <-watcher.Errors: - case <-watcher.Events: - case <-stopC: - return - } - } - }() - go func() { - <-startC - for _, fileName := range tempFiles { - os.Remove(fileName) - } - }() - go func() { - <-startC - errC <- watcher.Close() - }() - close(startC) - defer close(stopC) - if err := <-errC; err != nil { - t.Fatalf("Expected no error on Close, got %v.", err) - } -} - -func testRename(file1, file2 string) error { - switch runtime.GOOS { - case "windows", "plan9": - return os.Rename(file1, file2) - default: - cmd := exec.Command("mv", file1, file2) - return cmd.Run() - } -} diff --git a/vendor/github.com/fsnotify/fsnotify/kqueue.go b/vendor/github.com/fsnotify/fsnotify/kqueue.go index c2b4acb18d..86e76a3d67 100644 --- a/vendor/github.com/fsnotify/fsnotify/kqueue.go +++ b/vendor/github.com/fsnotify/fsnotify/kqueue.go @@ -22,7 +22,7 @@ import ( type Watcher struct { Events chan Event Errors chan error - done chan bool // Channel for sending a "quit message" to the reader goroutine + done chan struct{} // Channel for sending a "quit message" to the reader goroutine kq int // File descriptor (as returned by the kqueue() syscall). @@ -56,7 +56,7 @@ func NewWatcher() (*Watcher, error) { externalWatches: make(map[string]bool), Events: make(chan Event), Errors: make(chan error), - done: make(chan bool), + done: make(chan struct{}), } go w.readEvents() @@ -71,10 +71,8 @@ func (w *Watcher) Close() error { return nil } w.isClosed = true - w.mu.Unlock() // copy paths to remove while locked - w.mu.Lock() var pathsToRemove = make([]string, 0, len(w.watches)) for name := range w.watches { pathsToRemove = append(pathsToRemove, name) @@ -82,15 +80,12 @@ func (w *Watcher) Close() error { w.mu.Unlock() // unlock before calling Remove, which also locks - var err error for _, name := range pathsToRemove { - if e := w.Remove(name); e != nil && err == nil { - err = e - } + w.Remove(name) } - // Send "quit" message to the reader goroutine: - w.done <- true + // send a "quit" message to the reader goroutine + close(w.done) return nil } @@ -266,17 +261,12 @@ func (w *Watcher) addWatch(name string, flags uint32) (string, error) { func (w *Watcher) readEvents() { eventBuffer := make([]unix.Kevent_t, 10) +loop: for { // See if there is a message on the "done" channel select { case <-w.done: - err := unix.Close(w.kq) - if err != nil { - w.Errors <- err - } - close(w.Events) - close(w.Errors) - return + break loop default: } @@ -284,7 +274,11 @@ func (w *Watcher) readEvents() { kevents, err := read(w.kq, eventBuffer, &keventWaitTime) // EINTR is okay, the syscall was interrupted before timeout expired. if err != nil && err != unix.EINTR { - w.Errors <- err + select { + case w.Errors <- err: + case <-w.done: + break loop + } continue } @@ -319,8 +313,12 @@ func (w *Watcher) readEvents() { if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) { w.sendDirectoryChangeEvents(event.Name) } else { - // Send the event on the Events channel - w.Events <- event + // Send the event on the Events channel. + select { + case w.Events <- event: + case <-w.done: + break loop + } } if event.Op&Remove == Remove { @@ -352,6 +350,18 @@ func (w *Watcher) readEvents() { kevents = kevents[1:] } } + + // cleanup + err := unix.Close(w.kq) + if err != nil { + // only way the previous loop breaks is if w.done was closed so we need to async send to w.Errors. + select { + case w.Errors <- err: + default: + } + } + close(w.Events) + close(w.Errors) } // newEvent returns an platform-independent Event based on kqueue Fflags. @@ -407,7 +417,11 @@ func (w *Watcher) sendDirectoryChangeEvents(dirPath string) { // Get all files files, err := ioutil.ReadDir(dirPath) if err != nil { - w.Errors <- err + select { + case w.Errors <- err: + case <-w.done: + return + } } // Search for new files @@ -428,7 +442,11 @@ func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInf w.mu.Unlock() if !doesExist { // Send create event - w.Events <- newCreateEvent(filePath) + select { + case w.Events <- newCreateEvent(filePath): + case <-w.done: + return + } } // like watchDirectoryFiles (but without doing another ReadDir) diff --git a/vendor/github.com/fullsailor/pkcs7/.travis.yml b/vendor/github.com/fullsailor/pkcs7/.travis.yml index c7154e46c3..bc12043763 100644 --- a/vendor/github.com/fullsailor/pkcs7/.travis.yml +++ b/vendor/github.com/fullsailor/pkcs7/.travis.yml @@ -1,6 +1,7 @@ language: go go: - - 1.6 - - 1.7 + - 1.8 + - 1.9 + - "1.10" - tip diff --git a/vendor/github.com/fullsailor/pkcs7/ber_test.go b/vendor/github.com/fullsailor/pkcs7/ber_test.go deleted file mode 100644 index 19a0f514c2..0000000000 --- a/vendor/github.com/fullsailor/pkcs7/ber_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package pkcs7 - -import ( - "bytes" - "encoding/asn1" - "strings" - "testing" -) - -func TestBer2Der(t *testing.T) { - // indefinite length fixture - ber := []byte{0x30, 0x80, 0x02, 0x01, 0x01, 0x00, 0x00} - expected := []byte{0x30, 0x03, 0x02, 0x01, 0x01} - der, err := ber2der(ber) - if err != nil { - t.Fatalf("ber2der failed with error: %v", err) - } - if bytes.Compare(der, expected) != 0 { - t.Errorf("ber2der result did not match.\n\tExpected: % X\n\tActual: % X", expected, der) - } - - if der2, err := ber2der(der); err != nil { - t.Errorf("ber2der on DER bytes failed with error: %v", err) - } else { - if !bytes.Equal(der, der2) { - t.Error("ber2der is not idempotent") - } - } - var thing struct { - Number int - } - rest, err := asn1.Unmarshal(der, &thing) - if err != nil { - t.Errorf("Cannot parse resulting DER because: %v", err) - } else if len(rest) > 0 { - t.Errorf("Resulting DER has trailing data: % X", rest) - } -} - -func TestBer2Der_Negatives(t *testing.T) { - fixtures := []struct { - Input []byte - ErrorContains string - }{ - {[]byte{0x30, 0x85}, "length too long"}, - {[]byte{0x30, 0x84, 0x80, 0x0, 0x0, 0x0}, "length is negative"}, - {[]byte{0x30, 0x82, 0x0, 0x1}, "length has leading zero"}, - {[]byte{0x30, 0x80, 0x1, 0x2, 0x1, 0x2}, "Invalid BER format"}, - {[]byte{0x30, 0x03, 0x01, 0x02}, "length is more than available data"}, - } - - for _, fixture := range fixtures { - _, err := ber2der(fixture.Input) - if err == nil { - t.Errorf("No error thrown. Expected: %s", fixture.ErrorContains) - } - if !strings.Contains(err.Error(), fixture.ErrorContains) { - t.Errorf("Unexpected error thrown.\n\tExpected: /%s/\n\tActual: %s", fixture.ErrorContains, err.Error()) - } - } -} - -func TestBer2Der_NestedMultipleIndefinite(t *testing.T) { - // indefinite length fixture - ber := []byte{0x30, 0x80, 0x30, 0x80, 0x02, 0x01, 0x01, 0x00, 0x00, 0x30, 0x80, 0x02, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00} - expected := []byte{0x30, 0x0A, 0x30, 0x03, 0x02, 0x01, 0x01, 0x30, 0x03, 0x02, 0x01, 0x02} - - der, err := ber2der(ber) - if err != nil { - t.Fatalf("ber2der failed with error: %v", err) - } - if bytes.Compare(der, expected) != 0 { - t.Errorf("ber2der result did not match.\n\tExpected: % X\n\tActual: % X", expected, der) - } - - if der2, err := ber2der(der); err != nil { - t.Errorf("ber2der on DER bytes failed with error: %v", err) - } else { - if !bytes.Equal(der, der2) { - t.Error("ber2der is not idempotent") - } - } - var thing struct { - Nest1 struct { - Number int - } - Nest2 struct { - Number int - } - } - rest, err := asn1.Unmarshal(der, &thing) - if err != nil { - t.Errorf("Cannot parse resulting DER because: %v", err) - } else if len(rest) > 0 { - t.Errorf("Resulting DER has trailing data: % X", rest) - } -} diff --git a/vendor/github.com/fullsailor/pkcs7/pkcs7.go b/vendor/github.com/fullsailor/pkcs7/pkcs7.go index 8d5af853ad..cde0e10dd5 100644 --- a/vendor/github.com/fullsailor/pkcs7/pkcs7.go +++ b/vendor/github.com/fullsailor/pkcs7/pkcs7.go @@ -84,7 +84,7 @@ type recipientInfo struct { type encryptedContentInfo struct { ContentType asn1.ObjectIdentifier ContentEncryptionAlgorithm pkix.AlgorithmIdentifier - EncryptedContent asn1.RawValue `asn1:"tag:0,optional,explicit"` + EncryptedContent asn1.RawValue `asn1:"tag:0,optional"` } type attribute struct { @@ -222,6 +222,10 @@ func (p7 *PKCS7) Verify() (err error) { func verifySignature(p7 *PKCS7, signer signerInfo) error { signedData := p7.Content + hash, err := getHashForOID(signer.DigestAlgorithm.Algorithm) + if err != nil { + return err + } if len(signer.AuthenticatedAttributes) > 0 { // TODO(fullsailor): First check the content type match var digest []byte @@ -229,10 +233,6 @@ func verifySignature(p7 *PKCS7, signer signerInfo) error { if err != nil { return err } - hash, err := getHashForOID(signer.DigestAlgorithm.Algorithm) - if err != nil { - return err - } h := hash.New() h.Write(p7.Content) computed := h.Sum(nil) @@ -254,7 +254,18 @@ func verifySignature(p7 *PKCS7, signer signerInfo) error { return errors.New("pkcs7: No certificate for signer") } - algo := x509.SHA1WithRSA + algo := getSignatureAlgorithmFromAI(signer.DigestEncryptionAlgorithm) + if algo == x509.UnknownSignatureAlgorithm { + // I'm not sure what the spec here is, and the openssl sources were not + // helpful. But, this is what App Store receipts appear to do. + // The DigestEncryptionAlgorithm is just "rsaEncryption (PKCS #1)" + // But we're expecting a digest + encryption algorithm. So... we're going + // to determine an algorithm based on the DigestAlgorithm and this + // encryption algorithm. + if signer.DigestEncryptionAlgorithm.Algorithm.Equal(oidEncryptionAlgorithmRSA) { + algo = getRSASignatureAlgorithmForDigestAlgorithm(hash) + } + } return cert.CheckSignature(algo, signedData, signer.EncryptedDigest) } @@ -294,6 +305,15 @@ func getHashForOID(oid asn1.ObjectIdentifier) (crypto.Hash, error) { return crypto.Hash(0), ErrUnsupportedAlgorithm } +func getRSASignatureAlgorithmForDigestAlgorithm(hash crypto.Hash) x509.SignatureAlgorithm { + for _, details := range signatureAlgorithmDetails { + if details.pubKeyAlgo == x509.RSA && details.hash == hash { + return details.algo + } + } + return x509.UnknownSignatureAlgorithm +} + // GetOnlySigner returns an x509.Certificate for the first signer of the signed // data payload. If there are more or less than one signer, nil is returned func (p7 *PKCS7) GetOnlySigner() *x509.Certificate { @@ -633,7 +653,7 @@ func (sd *SignedData) AddSigner(cert *x509.Certificate, pkey crypto.PrivateKey, signer := signerInfo{ AuthenticatedAttributes: finalAttrs, DigestAlgorithm: pkix.AlgorithmIdentifier{Algorithm: oidDigestAlgorithmSHA1}, - DigestEncryptionAlgorithm: pkix.AlgorithmIdentifier{Algorithm: oidEncryptionAlgorithmRSA}, + DigestEncryptionAlgorithm: pkix.AlgorithmIdentifier{Algorithm: oidSignatureSHA1WithRSA}, IssuerAndSerialNumber: ias, EncryptedDigest: signature, Version: 1, @@ -652,7 +672,7 @@ func (sd *SignedData) AddCertificate(cert *x509.Certificate) { // Detach removes content from the signed data struct to make it a detached signature. // This must be called right before Finish() func (sd *SignedData) Detach() { - sd.sd.ContentInfo = contentInfo{ContentType: oidSignedData} + sd.sd.ContentInfo = contentInfo{ContentType: oidData} } // Finish marshals the content and its signers diff --git a/vendor/github.com/fullsailor/pkcs7/pkcs7_test.go b/vendor/github.com/fullsailor/pkcs7/pkcs7_test.go deleted file mode 100644 index cbe2c5cad1..0000000000 --- a/vendor/github.com/fullsailor/pkcs7/pkcs7_test.go +++ /dev/null @@ -1,678 +0,0 @@ -package pkcs7 - -import ( - "bytes" - "crypto" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/pem" - "fmt" - "io" - "io/ioutil" - "math/big" - "os" - "os/exec" - "testing" - "time" -) - -func TestVerify(t *testing.T) { - fixture := UnmarshalTestFixture(SignedTestFixture) - p7, err := Parse(fixture.Input) - if err != nil { - t.Errorf("Parse encountered unexpected error: %v", err) - } - - if err := p7.Verify(); err != nil { - t.Errorf("Verify failed with error: %v", err) - } - expected := []byte("We the People") - if bytes.Compare(p7.Content, expected) != 0 { - t.Errorf("Signed content does not match.\n\tExpected:%s\n\tActual:%s", expected, p7.Content) - - } -} - -func TestVerifyEC2(t *testing.T) { - fixture := UnmarshalTestFixture(EC2IdentityDocumentFixture) - p7, err := Parse(fixture.Input) - if err != nil { - t.Errorf("Parse encountered unexpected error: %v", err) - } - p7.Certificates = []*x509.Certificate{fixture.Certificate} - if err := p7.Verify(); err != nil { - t.Errorf("Verify failed with error: %v", err) - } -} - -func TestVerifyAppStore(t *testing.T) { - fixture := UnmarshalTestFixture(AppStoreRecieptFixture) - p7, err := Parse(fixture.Input) - if err != nil { - t.Errorf("Parse encountered unexpected error: %v", err) - } - if err := p7.Verify(); err != nil { - t.Errorf("Verify failed with error: %v", err) - } -} - -func TestDecrypt(t *testing.T) { - fixture := UnmarshalTestFixture(EncryptedTestFixture) - p7, err := Parse(fixture.Input) - if err != nil { - t.Fatal(err) - } - content, err := p7.Decrypt(fixture.Certificate, fixture.PrivateKey) - if err != nil { - t.Errorf("Cannot Decrypt with error: %v", err) - } - expected := []byte("This is a test") - if bytes.Compare(content, expected) != 0 { - t.Errorf("Decrypted result does not match.\n\tExpected:%s\n\tActual:%s", expected, content) - } -} - -func TestDegenerateCertificate(t *testing.T) { - cert, err := createTestCertificate() - if err != nil { - t.Fatal(err) - } - deg, err := DegenerateCertificate(cert.Certificate.Raw) - if err != nil { - t.Fatal(err) - } - testOpenSSLParse(t, deg) - pem.Encode(os.Stdout, &pem.Block{Type: "PKCS7", Bytes: deg}) -} - -// writes the cert to a temporary file and tests that openssl can read it. -func testOpenSSLParse(t *testing.T, certBytes []byte) { - tmpCertFile, err := ioutil.TempFile("", "testCertificate") - if err != nil { - t.Fatal(err) - } - defer os.Remove(tmpCertFile.Name()) // clean up - - if _, err := tmpCertFile.Write(certBytes); err != nil { - t.Fatal(err) - } - - opensslCMD := exec.Command("openssl", "pkcs7", "-inform", "der", "-in", tmpCertFile.Name()) - _, err = opensslCMD.Output() - if err != nil { - t.Fatal(err) - } - - if err := tmpCertFile.Close(); err != nil { - t.Fatal(err) - } - -} - -func TestSign(t *testing.T) { - cert, err := createTestCertificate() - if err != nil { - t.Fatal(err) - } - content := []byte("Hello World") - for _, testDetach := range []bool{false, true} { - toBeSigned, err := NewSignedData(content) - if err != nil { - t.Fatalf("Cannot initialize signed data: %s", err) - } - if err := toBeSigned.AddSigner(cert.Certificate, cert.PrivateKey, SignerInfoConfig{}); err != nil { - t.Fatalf("Cannot add signer: %s", err) - } - if testDetach { - t.Log("Testing detached signature") - toBeSigned.Detach() - } else { - t.Log("Testing attached signature") - } - signed, err := toBeSigned.Finish() - if err != nil { - t.Fatalf("Cannot finish signing data: %s", err) - } - pem.Encode(os.Stdout, &pem.Block{Type: "PKCS7", Bytes: signed}) - p7, err := Parse(signed) - if err != nil { - t.Fatalf("Cannot parse our signed data: %s", err) - } - if testDetach { - p7.Content = content - } - if bytes.Compare(content, p7.Content) != 0 { - t.Errorf("Our content was not in the parsed data:\n\tExpected: %s\n\tActual: %s", content, p7.Content) - } - if err := p7.Verify(); err != nil { - t.Errorf("Cannot verify our signed data: %s", err) - } - } -} - -func ExampleSignedData() { - // generate a signing cert or load a key pair - cert, err := createTestCertificate() - if err != nil { - fmt.Printf("Cannot create test certificates: %s", err) - } - - // Initialize a SignedData struct with content to be signed - signedData, err := NewSignedData([]byte("Example data to be signed")) - if err != nil { - fmt.Printf("Cannot initialize signed data: %s", err) - } - - // Add the signing cert and private key - if err := signedData.AddSigner(cert.Certificate, cert.PrivateKey, SignerInfoConfig{}); err != nil { - fmt.Printf("Cannot add signer: %s", err) - } - - // Call Detach() is you want to remove content from the signature - // and generate an S/MIME detached signature - signedData.Detach() - - // Finish() to obtain the signature bytes - detachedSignature, err := signedData.Finish() - if err != nil { - fmt.Printf("Cannot finish signing data: %s", err) - } - pem.Encode(os.Stdout, &pem.Block{Type: "PKCS7", Bytes: detachedSignature}) -} - -func TestOpenSSLVerifyDetachedSignature(t *testing.T) { - rootCert, err := createTestCertificateByIssuer("PKCS7 Test Root CA", nil) - if err != nil { - t.Fatalf("Cannot generate root cert: %s", err) - } - signerCert, err := createTestCertificateByIssuer("PKCS7 Test Signer Cert", rootCert) - if err != nil { - t.Fatalf("Cannot generate signer cert: %s", err) - } - content := []byte("Hello World") - toBeSigned, err := NewSignedData(content) - if err != nil { - t.Fatalf("Cannot initialize signed data: %s", err) - } - if err := toBeSigned.AddSigner(signerCert.Certificate, signerCert.PrivateKey, SignerInfoConfig{}); err != nil { - t.Fatalf("Cannot add signer: %s", err) - } - toBeSigned.Detach() - signed, err := toBeSigned.Finish() - if err != nil { - t.Fatalf("Cannot finish signing data: %s", err) - } - - // write the root cert to a temp file - tmpRootCertFile, err := ioutil.TempFile("", "pkcs7TestRootCA") - if err != nil { - t.Fatal(err) - } - defer os.Remove(tmpRootCertFile.Name()) // clean up - fd, err := os.OpenFile(tmpRootCertFile.Name(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755) - if err != nil { - t.Fatal(err) - } - pem.Encode(fd, &pem.Block{Type: "CERTIFICATE", Bytes: rootCert.Certificate.Raw}) - fd.Close() - - // write the signature to a temp file - tmpSignatureFile, err := ioutil.TempFile("", "pkcs7Signature") - if err != nil { - t.Fatal(err) - } - defer os.Remove(tmpSignatureFile.Name()) // clean up - ioutil.WriteFile(tmpSignatureFile.Name(), signed, 0755) - - // write the content to a temp file - tmpContentFile, err := ioutil.TempFile("", "pkcs7Content") - if err != nil { - t.Fatal(err) - } - defer os.Remove(tmpContentFile.Name()) // clean up - ioutil.WriteFile(tmpContentFile.Name(), content, 0755) - - // call openssl to verify the signature on the content using the root - opensslCMD := exec.Command("openssl", "smime", "-verify", - "-in", tmpSignatureFile.Name(), "-inform", "DER", - "-content", tmpContentFile.Name(), - "-CAfile", tmpRootCertFile.Name()) - out, err := opensslCMD.Output() - t.Logf("%s", out) - if err != nil { - t.Fatalf("openssl command failed with %s", err) - } -} - -func TestEncrypt(t *testing.T) { - modes := []int{ - EncryptionAlgorithmDESCBC, - EncryptionAlgorithmAES128GCM, - } - - for _, mode := range modes { - ContentEncryptionAlgorithm = mode - - plaintext := []byte("Hello Secret World!") - cert, err := createTestCertificate() - if err != nil { - t.Fatal(err) - } - encrypted, err := Encrypt(plaintext, []*x509.Certificate{cert.Certificate}) - if err != nil { - t.Fatal(err) - } - p7, err := Parse(encrypted) - if err != nil { - t.Fatalf("cannot Parse encrypted result: %s", err) - } - result, err := p7.Decrypt(cert.Certificate, cert.PrivateKey) - if err != nil { - t.Fatalf("cannot Decrypt encrypted result: %s", err) - } - if bytes.Compare(plaintext, result) != 0 { - t.Errorf("encrypted data does not match plaintext:\n\tExpected: %s\n\tActual: %s", plaintext, result) - } - } -} - -func TestUnmarshalSignedAttribute(t *testing.T) { - cert, err := createTestCertificate() - if err != nil { - t.Fatal(err) - } - content := []byte("Hello World") - toBeSigned, err := NewSignedData(content) - if err != nil { - t.Fatalf("Cannot initialize signed data: %s", err) - } - oidTest := asn1.ObjectIdentifier{2, 3, 4, 5, 6, 7} - testValue := "TestValue" - if err := toBeSigned.AddSigner(cert.Certificate, cert.PrivateKey, SignerInfoConfig{ - ExtraSignedAttributes: []Attribute{Attribute{Type: oidTest, Value: testValue}}, - }); err != nil { - t.Fatalf("Cannot add signer: %s", err) - } - signed, err := toBeSigned.Finish() - if err != nil { - t.Fatalf("Cannot finish signing data: %s", err) - } - p7, err := Parse(signed) - var actual string - err = p7.UnmarshalSignedAttribute(oidTest, &actual) - if err != nil { - t.Fatalf("Cannot unmarshal test value: %s", err) - } - if testValue != actual { - t.Errorf("Attribute does not match test value\n\tExpected: %s\n\tActual: %s", testValue, actual) - } -} - -func TestPad(t *testing.T) { - tests := []struct { - Original []byte - Expected []byte - BlockSize int - }{ - {[]byte{0x1, 0x2, 0x3, 0x10}, []byte{0x1, 0x2, 0x3, 0x10, 0x4, 0x4, 0x4, 0x4}, 8}, - {[]byte{0x1, 0x2, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0}, []byte{0x1, 0x2, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8}, 8}, - } - for _, test := range tests { - padded, err := pad(test.Original, test.BlockSize) - if err != nil { - t.Errorf("pad encountered error: %s", err) - continue - } - if bytes.Compare(test.Expected, padded) != 0 { - t.Errorf("pad results mismatch:\n\tExpected: %X\n\tActual: %X", test.Expected, padded) - } - } -} - -type certKeyPair struct { - Certificate *x509.Certificate - PrivateKey *rsa.PrivateKey -} - -func createTestCertificate() (certKeyPair, error) { - signer, err := createTestCertificateByIssuer("Eddard Stark", nil) - if err != nil { - return certKeyPair{}, err - } - fmt.Println("Created root cert") - pem.Encode(os.Stdout, &pem.Block{Type: "CERTIFICATE", Bytes: signer.Certificate.Raw}) - pair, err := createTestCertificateByIssuer("Jon Snow", signer) - if err != nil { - return certKeyPair{}, err - } - fmt.Println("Created signer cert") - pem.Encode(os.Stdout, &pem.Block{Type: "CERTIFICATE", Bytes: pair.Certificate.Raw}) - return *pair, nil -} - -func createTestCertificateByIssuer(name string, issuer *certKeyPair) (*certKeyPair, error) { - priv, err := rsa.GenerateKey(rand.Reader, 1024) - if err != nil { - return nil, err - } - serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 32) - serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) - if err != nil { - return nil, err - } - - template := x509.Certificate{ - SerialNumber: serialNumber, - SignatureAlgorithm: x509.SHA256WithRSA, - Subject: pkix.Name{ - CommonName: name, - Organization: []string{"Acme Co"}, - }, - NotBefore: time.Now(), - NotAfter: time.Now().AddDate(1, 0, 0), - KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageEmailProtection}, - } - var issuerCert *x509.Certificate - var issuerKey crypto.PrivateKey - if issuer != nil { - issuerCert = issuer.Certificate - issuerKey = issuer.PrivateKey - } else { - template.IsCA = true - template.KeyUsage |= x509.KeyUsageCertSign - issuerCert = &template - issuerKey = priv - } - cert, err := x509.CreateCertificate(rand.Reader, &template, issuerCert, priv.Public(), issuerKey) - if err != nil { - return nil, err - } - leaf, err := x509.ParseCertificate(cert) - if err != nil { - return nil, err - } - return &certKeyPair{ - Certificate: leaf, - PrivateKey: priv, - }, nil -} - -type TestFixture struct { - Input []byte - Certificate *x509.Certificate - PrivateKey *rsa.PrivateKey -} - -func UnmarshalTestFixture(testPEMBlock string) TestFixture { - var result TestFixture - var derBlock *pem.Block - var pemBlock = []byte(testPEMBlock) - for { - derBlock, pemBlock = pem.Decode(pemBlock) - if derBlock == nil { - break - } - switch derBlock.Type { - case "PKCS7": - result.Input = derBlock.Bytes - case "CERTIFICATE": - result.Certificate, _ = x509.ParseCertificate(derBlock.Bytes) - case "PRIVATE KEY": - result.PrivateKey, _ = x509.ParsePKCS1PrivateKey(derBlock.Bytes) - } - } - - return result -} - -func MarshalTestFixture(t TestFixture, w io.Writer) { - if t.Input != nil { - pem.Encode(w, &pem.Block{Type: "PKCS7", Bytes: t.Input}) - } - if t.Certificate != nil { - pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: t.Certificate.Raw}) - } - if t.PrivateKey != nil { - pem.Encode(w, &pem.Block{Type: "PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(t.PrivateKey)}) - } -} - -var SignedTestFixture = ` ------BEGIN PKCS7----- -MIIDVgYJKoZIhvcNAQcCoIIDRzCCA0MCAQExCTAHBgUrDgMCGjAcBgkqhkiG9w0B -BwGgDwQNV2UgdGhlIFBlb3BsZaCCAdkwggHVMIIBQKADAgECAgRpuDctMAsGCSqG -SIb3DQEBCzApMRAwDgYDVQQKEwdBY21lIENvMRUwEwYDVQQDEwxFZGRhcmQgU3Rh -cmswHhcNMTUwNTA2MDQyNDQ4WhcNMTYwNTA2MDQyNDQ4WjAlMRAwDgYDVQQKEwdB -Y21lIENvMREwDwYDVQQDEwhKb24gU25vdzCBnzANBgkqhkiG9w0BAQEFAAOBjQAw -gYkCgYEAqr+tTF4mZP5rMwlXp1y+crRtFpuLXF1zvBZiYMfIvAHwo1ta8E1IcyEP -J1jIiKMcwbzeo6kAmZzIJRCTezq9jwXUsKbQTvcfOH9HmjUmXBRWFXZYoQs/OaaF -a45deHmwEeMQkuSWEtYiVKKZXtJOtflKIT3MryJEDiiItMkdybUCAwEAAaMSMBAw -DgYDVR0PAQH/BAQDAgCgMAsGCSqGSIb3DQEBCwOBgQDK1EweZWRL+f7Z+J0kVzY8 -zXptcBaV4Lf5wGZJLJVUgp33bpLNpT3yadS++XQJ+cvtW3wADQzBSTMduyOF8Zf+ -L7TjjrQ2+F2HbNbKUhBQKudxTfv9dJHdKbD+ngCCdQJYkIy2YexsoNG0C8nQkggy -axZd/J69xDVx6pui3Sj8sDGCATYwggEyAgEBMDEwKTEQMA4GA1UEChMHQWNtZSBD -bzEVMBMGA1UEAxMMRWRkYXJkIFN0YXJrAgRpuDctMAcGBSsOAwIaoGEwGAYJKoZI -hvcNAQkDMQsGCSqGSIb3DQEHATAgBgkqhkiG9w0BCQUxExcRMTUwNTA2MDAyNDQ4 -LTA0MDAwIwYJKoZIhvcNAQkEMRYEFG9D7gcTh9zfKiYNJ1lgB0yTh4sZMAsGCSqG -SIb3DQEBAQSBgFF3sGDU9PtXty/QMtpcFa35vvIOqmWQAIZt93XAskQOnBq4OloX -iL9Ct7t1m4pzjRm0o9nDkbaSLZe7HKASHdCqijroScGlI8M+alJ8drHSFv6ZIjnM -FIwIf0B2Lko6nh9/6mUXq7tbbIHa3Gd1JUVire/QFFtmgRXMbXYk8SIS ------END PKCS7----- ------BEGIN CERTIFICATE----- -MIIB1TCCAUCgAwIBAgIEabg3LTALBgkqhkiG9w0BAQswKTEQMA4GA1UEChMHQWNt -ZSBDbzEVMBMGA1UEAxMMRWRkYXJkIFN0YXJrMB4XDTE1MDUwNjA0MjQ0OFoXDTE2 -MDUwNjA0MjQ0OFowJTEQMA4GA1UEChMHQWNtZSBDbzERMA8GA1UEAxMISm9uIFNu -b3cwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAKq/rUxeJmT+azMJV6dcvnK0 -bRabi1xdc7wWYmDHyLwB8KNbWvBNSHMhDydYyIijHMG83qOpAJmcyCUQk3s6vY8F -1LCm0E73Hzh/R5o1JlwUVhV2WKELPzmmhWuOXXh5sBHjEJLklhLWIlSimV7STrX5 -SiE9zK8iRA4oiLTJHcm1AgMBAAGjEjAQMA4GA1UdDwEB/wQEAwIAoDALBgkqhkiG -9w0BAQsDgYEAytRMHmVkS/n+2fidJFc2PM16bXAWleC3+cBmSSyVVIKd926SzaU9 -8mnUvvl0CfnL7Vt8AA0MwUkzHbsjhfGX/i+04460Nvhdh2zWylIQUCrncU37/XSR -3Smw/p4AgnUCWJCMtmHsbKDRtAvJ0JIIMmsWXfyevcQ1ceqbot0o/LA= ------END CERTIFICATE----- ------BEGIN PRIVATE KEY----- -MIICXgIBAAKBgQCqv61MXiZk/mszCVenXL5ytG0Wm4tcXXO8FmJgx8i8AfCjW1rw -TUhzIQ8nWMiIoxzBvN6jqQCZnMglEJN7Or2PBdSwptBO9x84f0eaNSZcFFYVdlih -Cz85poVrjl14ebAR4xCS5JYS1iJUople0k61+UohPcyvIkQOKIi0yR3JtQIDAQAB -AoGBAIPLCR9N+IKxodq11lNXEaUFwMHXc1zqwP8no+2hpz3+nVfplqqubEJ4/PJY -5AgbJoIfnxVhyBXJXu7E+aD/OPneKZrgp58YvHKgGvvPyJg2gpC/1Fh0vQB0HNpI -1ZzIZUl8ZTUtVgtnCBUOh5JGI4bFokAqrT//Uvcfd+idgxqBAkEA1ZbP/Kseld14 -qbWmgmU5GCVxsZRxgR1j4lG3UVjH36KXMtRTm1atAam1uw3OEGa6Y3ANjpU52FaB -Hep5rkk4FQJBAMynMo1L1uiN5GP+KYLEF5kKRxK+FLjXR0ywnMh+gpGcZDcOae+J -+t1gLoWBIESH/Xt639T7smuSfrZSA9V0EyECQA8cvZiWDvLxmaEAXkipmtGPjKzQ -4PsOtkuEFqFl07aKDYKmLUg3aMROWrJidqsIabWxbvQgsNgSvs38EiH3wkUCQQCg -ndxb7piVXb9RBwm3OoU2tE1BlXMX+sVXmAkEhd2dwDsaxrI3sHf1xGXem5AimQRF -JBOFyaCnMotGNioSHY5hAkEAxyXcNixQ2RpLXJTQZtwnbk0XDcbgB+fBgXnv/4f3 -BCvcu85DqJeJyQv44Oe1qsXEX9BfcQIOVaoep35RPlKi9g== ------END PRIVATE KEY-----` - -// Content is "This is a test" -var EncryptedTestFixture = ` ------BEGIN PKCS7----- -MIIBFwYJKoZIhvcNAQcDoIIBCDCCAQQCAQAxgcowgccCAQAwMjApMRAwDgYDVQQK -EwdBY21lIENvMRUwEwYDVQQDEwxFZGRhcmQgU3RhcmsCBQDL+CvWMAsGCSqGSIb3 -DQEBAQSBgKyP/5WlRTZD3dWMrLOX6QRNDrXEkQjhmToRwFZdY3LgUh25ZU0S/q4G -dHPV21Fv9lQD+q7l3vfeHw8M6Z1PKi9sHMVfxAkQpvaI96DTIT3YHtuLC1w3geCO -8eFWTq2qS4WChSuS/yhYosjA1kTkE0eLnVZcGw0z/WVuEZznkdyIMDIGCSqGSIb3 -DQEHATARBgUrDgMCBwQImpKsUyMPpQigEgQQRcWWrCRXqpD5Njs0GkJl+g== ------END PKCS7----- ------BEGIN CERTIFICATE----- -MIIB1jCCAUGgAwIBAgIFAMv4K9YwCwYJKoZIhvcNAQELMCkxEDAOBgNVBAoTB0Fj -bWUgQ28xFTATBgNVBAMTDEVkZGFyZCBTdGFyazAeFw0xNTA1MDYwMzU2NDBaFw0x -NjA1MDYwMzU2NDBaMCUxEDAOBgNVBAoTB0FjbWUgQ28xETAPBgNVBAMTCEpvbiBT -bm93MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDK6NU0R0eiCYVquU4RcjKc -LzGfx0aa1lMr2TnLQUSeLFZHFxsyyMXXuMPig3HK4A7SGFHupO+/1H/sL4xpH5zg -8+Zg2r8xnnney7abxcuv0uATWSIeKlNnb1ZO1BAxFnESc3GtyOCr2dUwZHX5mRVP -+Zxp2ni5qHNraf3wE2VPIQIDAQABoxIwEDAOBgNVHQ8BAf8EBAMCAKAwCwYJKoZI -hvcNAQELA4GBAIr2F7wsqmEU/J/kLyrCgEVXgaV/sKZq4pPNnzS0tBYk8fkV3V18 -sBJyHKRLL/wFZASvzDcVGCplXyMdAOCyfd8jO3F9Ac/xdlz10RrHJT75hNu3a7/n -9KNwKhfN4A1CQv2x372oGjRhCW5bHNCWx4PIVeNzCyq/KZhyY9sxHE6f ------END CERTIFICATE----- ------BEGIN PRIVATE KEY----- -MIICXgIBAAKBgQDK6NU0R0eiCYVquU4RcjKcLzGfx0aa1lMr2TnLQUSeLFZHFxsy -yMXXuMPig3HK4A7SGFHupO+/1H/sL4xpH5zg8+Zg2r8xnnney7abxcuv0uATWSIe -KlNnb1ZO1BAxFnESc3GtyOCr2dUwZHX5mRVP+Zxp2ni5qHNraf3wE2VPIQIDAQAB -AoGBALyvnSt7KUquDen7nXQtvJBudnf9KFPt//OjkdHHxNZNpoF/JCSqfQeoYkeu -MdAVYNLQGMiRifzZz4dDhA9xfUAuy7lcGQcMCxEQ1dwwuFaYkawbS0Tvy2PFlq2d -H5/HeDXU4EDJ3BZg0eYj2Bnkt1sJI35UKQSxblQ0MY2q0uFBAkEA5MMOogkgUx1C -67S1tFqMUSM8D0mZB0O5vOJZC5Gtt2Urju6vywge2ArExWRXlM2qGl8afFy2SgSv -Xk5eybcEiQJBAOMRwwbEoW5NYHuFFbSJyWll4n71CYuWuQOCzehDPyTb80WFZGLV -i91kFIjeERyq88eDE5xVB3ZuRiXqaShO/9kCQQCKOEkpInaDgZSjskZvuJ47kByD -6CYsO4GIXQMMeHML8ncFH7bb6AYq5ybJVb2NTU7QLFJmfeYuhvIm+xdOreRxAkEA -o5FC5Jg2FUfFzZSDmyZ6IONUsdF/i78KDV5nRv1R+hI6/oRlWNCtTNBv/lvBBd6b -dseUE9QoaQZsn5lpILEvmQJAZ0B+Or1rAYjnbjnUhdVZoy9kC4Zov+4UH3N/BtSy -KJRWUR0wTWfZBPZ5hAYZjTBEAFULaYCXlQKsODSp0M1aQA== ------END PRIVATE KEY-----` - -var EC2IdentityDocumentFixture = ` ------BEGIN PKCS7----- -MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAaCA -JIAEggGmewogICJwcml2YXRlSXAiIDogIjE3Mi4zMC4wLjI1MiIsCiAgImRldnBh -eVByb2R1Y3RDb2RlcyIgOiBudWxsLAogICJhdmFpbGFiaWxpdHlab25lIiA6ICJ1 -cy1lYXN0LTFhIiwKICAidmVyc2lvbiIgOiAiMjAxMC0wOC0zMSIsCiAgImluc3Rh -bmNlSWQiIDogImktZjc5ZmU1NmMiLAogICJiaWxsaW5nUHJvZHVjdHMiIDogbnVs -bCwKICAiaW5zdGFuY2VUeXBlIiA6ICJ0Mi5taWNybyIsCiAgImFjY291bnRJZCIg -OiAiMTIxNjU5MDE0MzM0IiwKICAiaW1hZ2VJZCIgOiAiYW1pLWZjZTNjNjk2IiwK -ICAicGVuZGluZ1RpbWUiIDogIjIwMTYtMDQtMDhUMDM6MDE6MzhaIiwKICAiYXJj -aGl0ZWN0dXJlIiA6ICJ4ODZfNjQiLAogICJrZXJuZWxJZCIgOiBudWxsLAogICJy -YW1kaXNrSWQiIDogbnVsbCwKICAicmVnaW9uIiA6ICJ1cy1lYXN0LTEiCn0AAAAA -AAAxggEYMIIBFAIBATBpMFwxCzAJBgNVBAYTAlVTMRkwFwYDVQQIExBXYXNoaW5n -dG9uIFN0YXRlMRAwDgYDVQQHEwdTZWF0dGxlMSAwHgYDVQQKExdBbWF6b24gV2Vi -IFNlcnZpY2VzIExMQwIJAJa6SNnlXhpnMAkGBSsOAwIaBQCgXTAYBgkqhkiG9w0B -CQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xNjA0MDgwMzAxNDRaMCMG -CSqGSIb3DQEJBDEWBBTuUc28eBXmImAautC+wOjqcFCBVjAJBgcqhkjOOAQDBC8w -LQIVAKA54NxGHWWCz5InboDmY/GHs33nAhQ6O/ZI86NwjA9Vz3RNMUJrUPU5tAAA -AAAAAA== ------END PKCS7----- ------BEGIN CERTIFICATE----- -MIIC7TCCAq0CCQCWukjZ5V4aZzAJBgcqhkjOOAQDMFwxCzAJBgNVBAYTAlVTMRkw -FwYDVQQIExBXYXNoaW5ndG9uIFN0YXRlMRAwDgYDVQQHEwdTZWF0dGxlMSAwHgYD -VQQKExdBbWF6b24gV2ViIFNlcnZpY2VzIExMQzAeFw0xMjAxMDUxMjU2MTJaFw0z -ODAxMDUxMjU2MTJaMFwxCzAJBgNVBAYTAlVTMRkwFwYDVQQIExBXYXNoaW5ndG9u -IFN0YXRlMRAwDgYDVQQHEwdTZWF0dGxlMSAwHgYDVQQKExdBbWF6b24gV2ViIFNl -cnZpY2VzIExMQzCCAbcwggEsBgcqhkjOOAQBMIIBHwKBgQCjkvcS2bb1VQ4yt/5e -ih5OO6kK/n1Lzllr7D8ZwtQP8fOEpp5E2ng+D6Ud1Z1gYipr58Kj3nssSNpI6bX3 -VyIQzK7wLclnd/YozqNNmgIyZecN7EglK9ITHJLP+x8FtUpt3QbyYXJdmVMegN6P -hviYt5JH/nYl4hh3Pa1HJdskgQIVALVJ3ER11+Ko4tP6nwvHwh6+ERYRAoGBAI1j -k+tkqMVHuAFcvAGKocTgsjJem6/5qomzJuKDmbJNu9Qxw3rAotXau8Qe+MBcJl/U -hhy1KHVpCGl9fueQ2s6IL0CaO/buycU1CiYQk40KNHCcHfNiZbdlx1E9rpUp7bnF -lRa2v1ntMX3caRVDdbtPEWmdxSCYsYFDk4mZrOLBA4GEAAKBgEbmeve5f8LIE/Gf -MNmP9CM5eovQOGx5ho8WqD+aTebs+k2tn92BBPqeZqpWRa5P/+jrdKml1qx4llHW -MXrs3IgIb6+hUIB+S8dz8/mmO0bpr76RoZVCXYab2CZedFut7qc3WUH9+EUAH5mw -vSeDCOUMYQR7R9LINYwouHIziqQYMAkGByqGSM44BAMDLwAwLAIUWXBlk40xTwSw -7HX32MxXYruse9ACFBNGmdX2ZBrVNGrN9N2f6ROk0k9K ------END CERTIFICATE-----` - -var AppStoreRecieptFixture = ` ------BEGIN PKCS7----- -MIITtgYJKoZIhvcNAQcCoIITpzCCE6MCAQExCzAJBgUrDgMCGgUAMIIDVwYJKoZI -hvcNAQcBoIIDSASCA0QxggNAMAoCAQgCAQEEAhYAMAoCARQCAQEEAgwAMAsCAQEC -AQEEAwIBADALAgEDAgEBBAMMATEwCwIBCwIBAQQDAgEAMAsCAQ8CAQEEAwIBADAL -AgEQAgEBBAMCAQAwCwIBGQIBAQQDAgEDMAwCAQoCAQEEBBYCNCswDAIBDgIBAQQE -AgIAjTANAgENAgEBBAUCAwFgvTANAgETAgEBBAUMAzEuMDAOAgEJAgEBBAYCBFAy -NDcwGAIBAgIBAQQQDA5jb20uemhpaHUudGVzdDAYAgEEAgECBBCS+ZODNMHwT1Nz -gWYDXyWZMBsCAQACAQEEEwwRUHJvZHVjdGlvblNhbmRib3gwHAIBBQIBAQQU4nRh -YCEZx70Flzv7hvJRjJZckYIwHgIBDAIBAQQWFhQyMDE2LTA3LTIzVDA2OjIxOjEx -WjAeAgESAgEBBBYWFDIwMTMtMDgtMDFUMDc6MDA6MDBaMD0CAQYCAQEENbR21I+a -8+byMXo3NPRoDWQmSXQF2EcCeBoD4GaL//ZCRETp9rGFPSg1KekCP7Kr9HAqw09m -MEICAQcCAQEEOlVJozYYBdugybShbiiMsejDMNeCbZq6CrzGBwW6GBy+DGWxJI91 -Y3ouXN4TZUhuVvLvN1b0m5T3ggQwggFaAgERAgEBBIIBUDGCAUwwCwICBqwCAQEE -AhYAMAsCAgatAgEBBAIMADALAgIGsAIBAQQCFgAwCwICBrICAQEEAgwAMAsCAgaz -AgEBBAIMADALAgIGtAIBAQQCDAAwCwICBrUCAQEEAgwAMAsCAga2AgEBBAIMADAM -AgIGpQIBAQQDAgEBMAwCAgarAgEBBAMCAQEwDAICBq4CAQEEAwIBADAMAgIGrwIB -AQQDAgEAMAwCAgaxAgEBBAMCAQAwGwICBqcCAQEEEgwQMTAwMDAwMDIyNTMyNTkw -MTAbAgIGqQIBAQQSDBAxMDAwMDAwMjI1MzI1OTAxMB8CAgaoAgEBBBYWFDIwMTYt -MDctMjNUMDY6MjE6MTFaMB8CAgaqAgEBBBYWFDIwMTYtMDctMjNUMDY6MjE6MTFa -MCACAgamAgEBBBcMFWNvbS56aGlodS50ZXN0LnRlc3RfMaCCDmUwggV8MIIEZKAD -AgECAggO61eH554JjTANBgkqhkiG9w0BAQUFADCBljELMAkGA1UEBhMCVVMxEzAR -BgNVBAoMCkFwcGxlIEluYy4xLDAqBgNVBAsMI0FwcGxlIFdvcmxkd2lkZSBEZXZl -bG9wZXIgUmVsYXRpb25zMUQwQgYDVQQDDDtBcHBsZSBXb3JsZHdpZGUgRGV2ZWxv -cGVyIFJlbGF0aW9ucyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0xNTExMTMw -MjE1MDlaFw0yMzAyMDcyMTQ4NDdaMIGJMTcwNQYDVQQDDC5NYWMgQXBwIFN0b3Jl -IGFuZCBpVHVuZXMgU3RvcmUgUmVjZWlwdCBTaWduaW5nMSwwKgYDVQQLDCNBcHBs -ZSBXb3JsZHdpZGUgRGV2ZWxvcGVyIFJlbGF0aW9uczETMBEGA1UECgwKQXBwbGUg -SW5jLjELMAkGA1UEBhMCVVMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB -AQClz4H9JaKBW9aH7SPaMxyO4iPApcQmyz3Gn+xKDVWG/6QC15fKOVRtfX+yVBid -xCxScY5ke4LOibpJ1gjltIhxzz9bRi7GxB24A6lYogQ+IXjV27fQjhKNg0xbKmg3 -k8LyvR7E0qEMSlhSqxLj7d0fmBWQNS3CzBLKjUiB91h4VGvojDE2H0oGDEdU8zeQ -uLKSiX1fpIVK4cCc4Lqku4KXY/Qrk8H9Pm/KwfU8qY9SGsAlCnYO3v6Z/v/Ca/Vb -XqxzUUkIVonMQ5DMjoEC0KCXtlyxoWlph5AQaCYmObgdEHOwCl3Fc9DfdjvYLdmI -HuPsB8/ijtDT+iZVge/iA0kjAgMBAAGjggHXMIIB0zA/BggrBgEFBQcBAQQzMDEw -LwYIKwYBBQUHMAGGI2h0dHA6Ly9vY3NwLmFwcGxlLmNvbS9vY3NwMDMtd3dkcjA0 -MB0GA1UdDgQWBBSRpJz8xHa3n6CK9E31jzZd7SsEhTAMBgNVHRMBAf8EAjAAMB8G -A1UdIwQYMBaAFIgnFwmpthhgi+zruvZHWcVSVKO3MIIBHgYDVR0gBIIBFTCCAREw -ggENBgoqhkiG92NkBQYBMIH+MIHDBggrBgEFBQcCAjCBtgyBs1JlbGlhbmNlIG9u -IHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFzc3VtZXMgYWNjZXB0YW5j -ZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJkIHRlcm1zIGFuZCBjb25k -aXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5IGFuZCBjZXJ0aWZpY2F0 -aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMDYGCCsGAQUFBwIBFipodHRwOi8vd3d3 -LmFwcGxlLmNvbS9jZXJ0aWZpY2F0ZWF1dGhvcml0eS8wDgYDVR0PAQH/BAQDAgeA -MBAGCiqGSIb3Y2QGCwEEAgUAMA0GCSqGSIb3DQEBBQUAA4IBAQANphvTLj3jWysH -bkKWbNPojEMwgl/gXNGNvr0PvRr8JZLbjIXDgFnf4+LXLgUUrA3btrj+/DUufMut -F2uOfx/kd7mxZ5W0E16mGYZ2+FogledjjA9z/Ojtxh+umfhlSFyg4Cg6wBA3Lbmg -BDkfc7nIBf3y3n8aKipuKwH8oCBc2et9J6Yz+PWY4L5E27FMZ/xuCk/J4gao0pfz -p45rUaJahHVl0RYEYuPBX/UIqc9o2ZIAycGMs/iNAGS6WGDAfK+PdcppuVsq1h1o -bphC9UynNxmbzDscehlD86Ntv0hgBgw2kivs3hi1EdotI9CO/KBpnBcbnoB7OUdF -MGEvxxOoMIIEIjCCAwqgAwIBAgIIAd68xDltoBAwDQYJKoZIhvcNAQEFBQAwYjEL -MAkGA1UEBhMCVVMxEzARBgNVBAoTCkFwcGxlIEluYy4xJjAkBgNVBAsTHUFwcGxl -IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRYwFAYDVQQDEw1BcHBsZSBSb290IENB -MB4XDTEzMDIwNzIxNDg0N1oXDTIzMDIwNzIxNDg0N1owgZYxCzAJBgNVBAYTAlVT -MRMwEQYDVQQKDApBcHBsZSBJbmMuMSwwKgYDVQQLDCNBcHBsZSBXb3JsZHdpZGUg -RGV2ZWxvcGVyIFJlbGF0aW9uczFEMEIGA1UEAww7QXBwbGUgV29ybGR3aWRlIERl -dmVsb3BlciBSZWxhdGlvbnMgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEiMA0G -CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDKOFSmy1aqyCQ5SOmM7uxfuH8mkbw0 -U3rOfGOAYXdkXqUHI7Y5/lAtFVZYcC1+xG7BSoU+L/DehBqhV8mvexj/avoVEkkV -CBmsqtsqMu2WY2hSFT2Miuy/axiV4AOsAX2XBWfODoWVN2rtCbauZ81RZJ/GXNG8 -V25nNYB2NqSHgW44j9grFU57Jdhav06DwY3Sk9UacbVgnJ0zTlX5ElgMhrgWDcHl -d0WNUEi6Ky3klIXh6MSdxmilsKP8Z35wugJZS3dCkTm59c3hTO/AO0iMpuUhXf1q -arunFjVg0uat80YpyejDi+l5wGphZxWy8P3laLxiX27Pmd3vG2P+kmWrAgMBAAGj -gaYwgaMwHQYDVR0OBBYEFIgnFwmpthhgi+zruvZHWcVSVKO3MA8GA1UdEwEB/wQF -MAMBAf8wHwYDVR0jBBgwFoAUK9BpR5R2Cf70a40uQKb3R01/CF4wLgYDVR0fBCcw -JTAjoCGgH4YdaHR0cDovL2NybC5hcHBsZS5jb20vcm9vdC5jcmwwDgYDVR0PAQH/ -BAQDAgGGMBAGCiqGSIb3Y2QGAgEEAgUAMA0GCSqGSIb3DQEBBQUAA4IBAQBPz+9Z -viz1smwvj+4ThzLoBTWobot9yWkMudkXvHcs1Gfi/ZptOllc34MBvbKuKmFysa/N -w0Uwj6ODDc4dR7Txk4qjdJukw5hyhzs+r0ULklS5MruQGFNrCk4QttkdUGwhgAqJ -TleMa1s8Pab93vcNIx0LSiaHP7qRkkykGRIZbVf1eliHe2iK5IaMSuviSRSqpd1V -AKmuu0swruGgsbwpgOYJd+W+NKIByn/c4grmO7i77LpilfMFY0GCzQ87HUyVpNur -+cmV6U/kTecmmYHpvPm0KdIBembhLoz2IYrF+Hjhga6/05Cdqa3zr/04GpZnMBxR -pVzscYqCtGwPDBUfMIIEuzCCA6OgAwIBAgIBAjANBgkqhkiG9w0BAQUFADBiMQsw -CQYDVQQGEwJVUzETMBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUg -Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0Ew -HhcNMDYwNDI1MjE0MDM2WhcNMzUwMjA5MjE0MDM2WjBiMQswCQYDVQQGEwJVUzET -MBEGA1UEChMKQXBwbGUgSW5jLjEmMCQGA1UECxMdQXBwbGUgQ2VydGlmaWNhdGlv -biBBdXRob3JpdHkxFjAUBgNVBAMTDUFwcGxlIFJvb3QgQ0EwggEiMA0GCSqGSIb3 -DQEBAQUAA4IBDwAwggEKAoIBAQDkkakJH5HbHkdQ6wXtXnmELes2oldMVeyLGYne -+Uts9QerIjAC6Bg++FAJ039BqJj50cpmnCRrEdCju+QbKsMflZ56DKRHi1vUFjcz -y8QPTc4UadHJGXL1XQ7Vf1+b8iUDulWPTV0N8WQ1IxVLFVkds5T39pyez1C6wVhQ -Z48ItCD3y6wsIG9wtj8BMIy3Q88PnT3zK0koGsj+zrW5DtleHNbLPbU6rfQPDgCS -C7EhFi501TwN22IWq6NxkkdTVcGvL0Gz+PvjcM3mo0xFfh9Ma1CWQYnEdGILEINB -hzOKgbEwWOxaBDKMaLOPHd5lc/9nXmW8Sdh2nzMUZaF3lMktAgMBAAGjggF6MIIB -djAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUK9Bp -R5R2Cf70a40uQKb3R01/CF4wHwYDVR0jBBgwFoAUK9BpR5R2Cf70a40uQKb3R01/ -CF4wggERBgNVHSAEggEIMIIBBDCCAQAGCSqGSIb3Y2QFATCB8jAqBggrBgEFBQcC -ARYeaHR0cHM6Ly93d3cuYXBwbGUuY29tL2FwcGxlY2EvMIHDBggrBgEFBQcCAjCB -thqBs1JlbGlhbmNlIG9uIHRoaXMgY2VydGlmaWNhdGUgYnkgYW55IHBhcnR5IGFz -c3VtZXMgYWNjZXB0YW5jZSBvZiB0aGUgdGhlbiBhcHBsaWNhYmxlIHN0YW5kYXJk -IHRlcm1zIGFuZCBjb25kaXRpb25zIG9mIHVzZSwgY2VydGlmaWNhdGUgcG9saWN5 -IGFuZCBjZXJ0aWZpY2F0aW9uIHByYWN0aWNlIHN0YXRlbWVudHMuMA0GCSqGSIb3 -DQEBBQUAA4IBAQBcNplMLXi37Yyb3PN3m/J20ncwT8EfhYOFG5k9RzfyqZtAjizU -sZAS2L70c5vu0mQPy3lPNNiiPvl4/2vIB+x9OYOLUyDTOMSxv5pPCmv/K/xZpwUJ -fBdAVhEedNO3iyM7R6PVbyTi69G3cN8PReEnyvFteO3ntRcXqNx+IjXKJdXZD9Zr -1KIkIxH3oayPc4FgxhtbCS+SsvhESPBgOJ4V9T0mZyCKM2r3DYLP3uujL/lTaltk -wGMzd/c6ByxW69oPIQ7aunMZT7XZNn/Bh1XZp5m5MkL72NVxnn6hUrcbvZNCJBIq -xw8dtk2cXmPIS4AXUKqK1drk/NAJBzewdXUhMYIByzCCAccCAQEwgaMwgZYxCzAJ -BgNVBAYTAlVTMRMwEQYDVQQKDApBcHBsZSBJbmMuMSwwKgYDVQQLDCNBcHBsZSBX -b3JsZHdpZGUgRGV2ZWxvcGVyIFJlbGF0aW9uczFEMEIGA1UEAww7QXBwbGUgV29y -bGR3aWRlIERldmVsb3BlciBSZWxhdGlvbnMgQ2VydGlmaWNhdGlvbiBBdXRob3Jp -dHkCCA7rV4fnngmNMAkGBSsOAwIaBQAwDQYJKoZIhvcNAQEBBQAEggEAasPtnide -NWyfUtewW9OSgcQA8pW+5tWMR0469cBPZR84uJa0gyfmPspySvbNOAwnrwzZHYLa -ujOxZLip4DUw4F5s3QwUa3y4BXpF4J+NSn9XNvxNtnT/GcEQtCuFwgJ0o3F0ilhv -MTHrwiwyx/vr+uNDqlORK8lfK+1qNp+A/kzh8eszMrn4JSeTh9ZYxLHE56WkTQGD -VZXl0gKgxSOmDrcp1eQxdlymzrPv9U60wUJ0bkPfrU9qZj3mJrmrkQk61JTe3j6/ -QfjfFBG9JG2mUmYQP1KQ3SypGHzDW8vngvsGu//tNU0NFfOqQu4bYU4VpQl0nPtD -4B85NkrgvQsWAQ== ------END PKCS7-----` diff --git a/vendor/github.com/fullsailor/pkcs7/x509.go b/vendor/github.com/fullsailor/pkcs7/x509.go new file mode 100644 index 0000000000..195fd0e4bb --- /dev/null +++ b/vendor/github.com/fullsailor/pkcs7/x509.go @@ -0,0 +1,133 @@ +// 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 go/golang LICENSE file. + +package pkcs7 + +// These are private constants and functions from the crypto/x509 package that +// are useful when dealing with signatures verified by x509 certificates + +import ( + "bytes" + "crypto" + "crypto/x509" + "crypto/x509/pkix" + "encoding/asn1" +) + +var ( + oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2} + oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4} + oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5} + oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11} + oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12} + oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13} + oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10} + oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3} + oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2} + oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1} + oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2} + oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3} + oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4} + + oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1} + oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2} + oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3} + + oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8} + + // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA + // but it's specified by ISO. Microsoft's makecert.exe has been known + // to produce certificates with this OID. + oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29} +) + +var signatureAlgorithmDetails = []struct { + algo x509.SignatureAlgorithm + name string + oid asn1.ObjectIdentifier + pubKeyAlgo x509.PublicKeyAlgorithm + hash crypto.Hash +}{ + {x509.MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, x509.RSA, crypto.Hash(0) /* no value for MD2 */}, + {x509.MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, x509.RSA, crypto.MD5}, + {x509.SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, x509.RSA, crypto.SHA1}, + {x509.SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, x509.RSA, crypto.SHA1}, + {x509.SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, x509.RSA, crypto.SHA256}, + {x509.SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, x509.RSA, crypto.SHA384}, + {x509.SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, x509.RSA, crypto.SHA512}, + {x509.SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, x509.RSA, crypto.SHA256}, + {x509.SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, x509.RSA, crypto.SHA384}, + {x509.SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, x509.RSA, crypto.SHA512}, + {x509.DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, x509.DSA, crypto.SHA1}, + {x509.DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, x509.DSA, crypto.SHA256}, + {x509.ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, x509.ECDSA, crypto.SHA1}, + {x509.ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, x509.ECDSA, crypto.SHA256}, + {x509.ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, x509.ECDSA, crypto.SHA384}, + {x509.ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, x509.ECDSA, crypto.SHA512}, +} + +// pssParameters reflects the parameters in an AlgorithmIdentifier that +// specifies RSA PSS. See https://tools.ietf.org/html/rfc3447#appendix-A.2.3 +type pssParameters struct { + // The following three fields are not marked as + // optional because the default values specify SHA-1, + // which is no longer suitable for use in signatures. + Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"` + MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"` + SaltLength int `asn1:"explicit,tag:2"` + TrailerField int `asn1:"optional,explicit,tag:3,default:1"` +} + +// asn1.NullBytes is not available prior to Go 1.9 +var nullBytes = []byte{5, 0} + +func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) x509.SignatureAlgorithm { + if !ai.Algorithm.Equal(oidSignatureRSAPSS) { + for _, details := range signatureAlgorithmDetails { + if ai.Algorithm.Equal(details.oid) { + return details.algo + } + } + return x509.UnknownSignatureAlgorithm + } + + // RSA PSS is special because it encodes important parameters + // in the Parameters. + + var params pssParameters + if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil { + return x509.UnknownSignatureAlgorithm + } + + var mgf1HashFunc pkix.AlgorithmIdentifier + if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil { + return x509.UnknownSignatureAlgorithm + } + + // PSS is greatly overburdened with options. This code forces + // them into three buckets by requiring that the MGF1 hash + // function always match the message hash function (as + // recommended in + // https://tools.ietf.org/html/rfc3447#section-8.1), that the + // salt length matches the hash length, and that the trailer + // field has the default value. + if !bytes.Equal(params.Hash.Parameters.FullBytes, nullBytes) || + !params.MGF.Algorithm.Equal(oidMGF1) || + !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) || + !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, nullBytes) || + params.TrailerField != 1 { + return x509.UnknownSignatureAlgorithm + } + + switch { + case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32: + return x509.SHA256WithRSAPSS + case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48: + return x509.SHA384WithRSAPSS + case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64: + return x509.SHA512WithRSAPSS + } + + return x509.UnknownSignatureAlgorithm +} diff --git a/vendor/github.com/ghodss/yaml/yaml_test.go b/vendor/github.com/ghodss/yaml/yaml_test.go deleted file mode 100644 index 505af45301..0000000000 --- a/vendor/github.com/ghodss/yaml/yaml_test.go +++ /dev/null @@ -1,287 +0,0 @@ -package yaml - -import ( - "fmt" - "math" - "reflect" - "strconv" - "testing" -) - -type MarshalTest struct { - A string - B int64 - // Would like to test float64, but it's not supported in go-yaml. - // (See https://github.com/go-yaml/yaml/issues/83.) - C float32 -} - -func TestMarshal(t *testing.T) { - f32String := strconv.FormatFloat(math.MaxFloat32, 'g', -1, 32) - s := MarshalTest{"a", math.MaxInt64, math.MaxFloat32} - e := []byte(fmt.Sprintf("A: a\nB: %d\nC: %s\n", math.MaxInt64, f32String)) - - y, err := Marshal(s) - if err != nil { - t.Errorf("error marshaling YAML: %v", err) - } - - if !reflect.DeepEqual(y, e) { - t.Errorf("marshal YAML was unsuccessful, expected: %#v, got: %#v", - string(e), string(y)) - } -} - -type UnmarshalString struct { - A string - True string -} - -type UnmarshalStringMap struct { - A map[string]string -} - -type UnmarshalNestedString struct { - A NestedString -} - -type NestedString struct { - A string -} - -type UnmarshalSlice struct { - A []NestedSlice -} - -type NestedSlice struct { - B string - C *string -} - -func TestUnmarshal(t *testing.T) { - y := []byte("a: 1") - s1 := UnmarshalString{} - e1 := UnmarshalString{A: "1"} - unmarshal(t, y, &s1, &e1) - - y = []byte("a: true") - s1 = UnmarshalString{} - e1 = UnmarshalString{A: "true"} - unmarshal(t, y, &s1, &e1) - - y = []byte("true: 1") - s1 = UnmarshalString{} - e1 = UnmarshalString{True: "1"} - unmarshal(t, y, &s1, &e1) - - y = []byte("a:\n a: 1") - s2 := UnmarshalNestedString{} - e2 := UnmarshalNestedString{NestedString{"1"}} - unmarshal(t, y, &s2, &e2) - - y = []byte("a:\n - b: abc\n c: def\n - b: 123\n c: 456\n") - s3 := UnmarshalSlice{} - e3 := UnmarshalSlice{[]NestedSlice{NestedSlice{"abc", strPtr("def")}, NestedSlice{"123", strPtr("456")}}} - unmarshal(t, y, &s3, &e3) - - y = []byte("a:\n b: 1") - s4 := UnmarshalStringMap{} - e4 := UnmarshalStringMap{map[string]string{"b": "1"}} - unmarshal(t, y, &s4, &e4) - - y = []byte(` -a: - name: TestA -b: - name: TestB -`) - type NamedThing struct { - Name string `json:"name"` - } - s5 := map[string]*NamedThing{} - e5 := map[string]*NamedThing{ - "a": &NamedThing{Name: "TestA"}, - "b": &NamedThing{Name: "TestB"}, - } - unmarshal(t, y, &s5, &e5) -} - -func unmarshal(t *testing.T, y []byte, s, e interface{}) { - err := Unmarshal(y, s) - if err != nil { - t.Errorf("error unmarshaling YAML: %v", err) - } - - if !reflect.DeepEqual(s, e) { - t.Errorf("unmarshal YAML was unsuccessful, expected: %+#v, got: %+#v", - e, s) - } -} - -type Case struct { - input string - output string - // By default we test that reversing the output == input. But if there is a - // difference in the reversed output, you can optionally specify it here. - reverse *string -} - -type RunType int - -const ( - RunTypeJSONToYAML RunType = iota - RunTypeYAMLToJSON -) - -func TestJSONToYAML(t *testing.T) { - cases := []Case{ - { - `{"t":"a"}`, - "t: a\n", - nil, - }, { - `{"t":null}`, - "t: null\n", - nil, - }, - } - - runCases(t, RunTypeJSONToYAML, cases) -} - -func TestYAMLToJSON(t *testing.T) { - cases := []Case{ - { - "t: a\n", - `{"t":"a"}`, - nil, - }, { - "t: \n", - `{"t":null}`, - strPtr("t: null\n"), - }, { - "t: null\n", - `{"t":null}`, - nil, - }, { - "1: a\n", - `{"1":"a"}`, - strPtr("\"1\": a\n"), - }, { - "1000000000000000000000000000000000000: a\n", - `{"1e+36":"a"}`, - strPtr("\"1e+36\": a\n"), - }, { - "1e+36: a\n", - `{"1e+36":"a"}`, - strPtr("\"1e+36\": a\n"), - }, { - "\"1e+36\": a\n", - `{"1e+36":"a"}`, - nil, - }, { - "\"1.2\": a\n", - `{"1.2":"a"}`, - nil, - }, { - "- t: a\n", - `[{"t":"a"}]`, - nil, - }, { - "- t: a\n" + - "- t:\n" + - " b: 1\n" + - " c: 2\n", - `[{"t":"a"},{"t":{"b":1,"c":2}}]`, - nil, - }, { - `[{t: a}, {t: {b: 1, c: 2}}]`, - `[{"t":"a"},{"t":{"b":1,"c":2}}]`, - strPtr("- t: a\n" + - "- t:\n" + - " b: 1\n" + - " c: 2\n"), - }, { - "- t: \n", - `[{"t":null}]`, - strPtr("- t: null\n"), - }, { - "- t: null\n", - `[{"t":null}]`, - nil, - }, - } - - // Cases that should produce errors. - _ = []Case{ - { - "~: a", - `{"null":"a"}`, - nil, - }, { - "a: !!binary gIGC\n", - "{\"a\":\"\x80\x81\x82\"}", - nil, - }, - } - - runCases(t, RunTypeYAMLToJSON, cases) -} - -func runCases(t *testing.T, runType RunType, cases []Case) { - var f func([]byte) ([]byte, error) - var invF func([]byte) ([]byte, error) - var msg string - var invMsg string - if runType == RunTypeJSONToYAML { - f = JSONToYAML - invF = YAMLToJSON - msg = "JSON to YAML" - invMsg = "YAML back to JSON" - } else { - f = YAMLToJSON - invF = JSONToYAML - msg = "YAML to JSON" - invMsg = "JSON back to YAML" - } - - for _, c := range cases { - // Convert the string. - t.Logf("converting %s\n", c.input) - output, err := f([]byte(c.input)) - if err != nil { - t.Errorf("Failed to convert %s, input: `%s`, err: %v", msg, c.input, err) - } - - // Check it against the expected output. - if string(output) != c.output { - t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", - msg, c.input, c.output, string(output)) - } - - // Set the string that we will compare the reversed output to. - reverse := c.input - // If a special reverse string was specified, use that instead. - if c.reverse != nil { - reverse = *c.reverse - } - - // Reverse the output. - input, err := invF(output) - if err != nil { - t.Errorf("Failed to convert %s, input: `%s`, err: %v", invMsg, string(output), err) - } - - // Check the reverse is equal to the input (or to *c.reverse). - if string(input) != reverse { - t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", - invMsg, string(output), reverse, string(input)) - } - } - -} - -// To be able to easily fill in the *Case.reverse string above. -func strPtr(s string) *string { - return &s -} diff --git a/vendor/github.com/gogo/protobuf/.travis.yml b/vendor/github.com/gogo/protobuf/.travis.yml index 7f69fba09e..12302e0065 100644 --- a/vendor/github.com/gogo/protobuf/.travis.yml +++ b/vendor/github.com/gogo/protobuf/.travis.yml @@ -1,7 +1,7 @@ env: - PROTOBUF_VERSION=2.6.1 - PROTOBUF_VERSION=3.0.2 - - PROTOBUF_VERSION=3.4.0 + - PROTOBUF_VERSION=3.5.1 before_install: - ./install-protobuf.sh @@ -10,11 +10,11 @@ before_install: script: - PATH=/home/travis/bin:$PATH make buildserverall - echo $TRAVIS_GO_VERSION - - if [ "$TRAVIS_GO_VERSION" == 1.9 ] && [[ "$PROTOBUF_VERSION" == 3.4.0 ]]; then ! git status --porcelain | read || (git status; git diff; exit 1); fi + - if [[ "$PROTOBUF_VERSION" == "3.5.1" ]] && [[ "$TRAVIS_GO_VERSION" =~ ^1\.9\.[0-9]+$ ]]; then ! git status --porcelain | read || (git status; git diff; exit 1); fi language: go go: - - 1.8.3 - - 1.9 - + - 1.8.x + - 1.9.x + - 1.10beta1 diff --git a/vendor/github.com/gogo/protobuf/CONTRIBUTORS b/vendor/github.com/gogo/protobuf/CONTRIBUTORS index b1abc4d305..1b4f6c208a 100644 --- a/vendor/github.com/gogo/protobuf/CONTRIBUTORS +++ b/vendor/github.com/gogo/protobuf/CONTRIBUTORS @@ -11,6 +11,7 @@ John Shahid John Tuley Laurent Patrick Lee +Peter Edge Roger Johansson Sam Nguyen Sergio Arbeo diff --git a/vendor/github.com/gogo/protobuf/Makefile b/vendor/github.com/gogo/protobuf/Makefile index 17e329367f..1d9ad1f562 100644 --- a/vendor/github.com/gogo/protobuf/Makefile +++ b/vendor/github.com/gogo/protobuf/Makefile @@ -88,6 +88,7 @@ regenerate: make -C test/issue42order regenerate make -C proto generate-test-pbs make -C test/importdedup regenerate + make -C test/importduplicate regenerate make -C test/custombytesnonstruct regenerate make -C test/required regenerate make -C test/casttype regenerate diff --git a/vendor/github.com/gogo/protobuf/README b/vendor/github.com/gogo/protobuf/README index c820827238..035426df55 100644 --- a/vendor/github.com/gogo/protobuf/README +++ b/vendor/github.com/gogo/protobuf/README @@ -123,6 +123,7 @@ When the .proto file specifies `syntax="proto3"`, there are some differences: Consider file test.proto, containing ```proto + syntax = "proto2"; package example; enum FOO { X = 17; }; diff --git a/vendor/github.com/gogo/protobuf/Readme.md b/vendor/github.com/gogo/protobuf/Readme.md index b8eb4d14e4..a4ad3eecd0 100644 --- a/vendor/github.com/gogo/protobuf/Readme.md +++ b/vendor/github.com/gogo/protobuf/Readme.md @@ -43,8 +43,9 @@ These projects use gogoprotobuf: - nakama - proteus - carbonzipper stack - - SendGrid - + - sendgrid + - zero-os/0-stor + Please let us know if you are using gogoprotobuf by posting on our GoogleGroup. ### Mentioned @@ -64,10 +65,10 @@ After that you can choose: ### Installation -To install it, you must first have Go (at least version 1.6.3) installed (see [http://golang.org/doc/install](http://golang.org/doc/install)). Go 1.8.3 and 1.9 are continuously tested. +To install it, you must first have Go (at least version 1.6.3) installed (see [http://golang.org/doc/install](http://golang.org/doc/install)). Latest patch versions of Go 1.8, 1.9 and 1.10 are continuously tested. Next, install the standard protocol buffer implementation from [https://github.com/google/protobuf](https://github.com/google/protobuf). -Most versions from 2.3.1 should not give any problems, but 2.6.1, 3.0.2 and 3.4.0 are continuously tested. +Most versions from 2.3.1 should not give any problems, but 2.6.1, 3.0.2 and 3.5.1 are continuously tested. ### Speed @@ -98,7 +99,23 @@ Installing any of these binaries is easy. Simply run: go get github.com/gogo/protobuf/{binary} go get github.com/gogo/protobuf/gogoproto -These binaries allow you to using gogoprotobuf [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md). +These binaries allow you to use gogoprotobuf [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md). You can also use your own binary. + +To generate the code, you also need to set the include path properly. + + protoc -I=. -I=$GOPATH/src -I=$GOPATH/src/github.com/gogo/protobuf/protobuf --{binary}_out=. myproto.proto + +To use proto files from "google/protobuf" you need to add additional args to protoc. + + protoc -I=. -I=$GOPATH/src -I=$GOPATH/src/github.com/gogo/protobuf/protobuf --{binary}_out=\ + Mgoogle/protobuf/any.proto=github.com/gogo/protobuf/types,\ + Mgoogle/protobuf/duration.proto=github.com/gogo/protobuf/types,\ + Mgoogle/protobuf/struct.proto=github.com/gogo/protobuf/types,\ + Mgoogle/protobuf/timestamp.proto=github.com/gogo/protobuf/types,\ + Mgoogle/protobuf/wrappers.proto=github.com/gogo/protobuf/types:. \ + myproto.proto + +Note that in the protoc command, {binary} does not contain the initial prefix of "protoc-gen". ### Most Speed and most customization diff --git a/vendor/github.com/gogo/protobuf/extensions.md b/vendor/github.com/gogo/protobuf/extensions.md index fcfe17af26..35dfee16f6 100644 --- a/vendor/github.com/gogo/protobuf/extensions.md +++ b/vendor/github.com/gogo/protobuf/extensions.md @@ -81,7 +81,7 @@ Helper methods, functions and interfaces can be generated by triggering certain - + diff --git a/vendor/github.com/gogo/protobuf/gogoproto/Makefile b/vendor/github.com/gogo/protobuf/gogoproto/Makefile index 02f9c62c2c..0b4659b731 100644 --- a/vendor/github.com/gogo/protobuf/gogoproto/Makefile +++ b/vendor/github.com/gogo/protobuf/gogoproto/Makefile @@ -28,7 +28,7 @@ regenerate: go install github.com/gogo/protobuf/protoc-gen-gogo - protoc --gogo_out=Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor:. --proto_path=../../../../:../protobuf/:. *.proto + protoc --gogo_out=Mgoogle/protobuf/descriptor.proto=github.com/gogo/protobuf/protoc-gen-gogo/descriptor:../../../../ --proto_path=../../../../:../protobuf/:. *.proto restore: cp gogo.pb.golden gogo.pb.go diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go index fa88040f11..5765acb153 100644 --- a/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go +++ b/vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go @@ -723,81 +723,82 @@ func init() { func init() { proto.RegisterFile("gogo.proto", fileDescriptorGogo) } var fileDescriptorGogo = []byte{ - // 1201 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x98, 0xcb, 0x6f, 0x1c, 0x45, - 0x13, 0xc0, 0xf5, 0xe9, 0x73, 0x64, 0x6f, 0xf9, 0x85, 0xd7, 0xc6, 0x84, 0x08, 0x44, 0x72, 0xe3, - 0xe4, 0x9c, 0x22, 0x94, 0xb6, 0x22, 0xcb, 0xb1, 0x1c, 0x2b, 0x11, 0x06, 0x63, 0xe2, 0x00, 0xe2, - 0xb0, 0x9a, 0xdd, 0x6d, 0x4f, 0x06, 0x66, 0xa6, 0x87, 0x99, 0x9e, 0x28, 0xce, 0x0d, 0x85, 0x87, - 0x10, 0xe2, 0x8d, 0x04, 0x09, 0x49, 0x80, 0x03, 0xef, 0x67, 0x78, 0x1f, 0xb9, 0xf0, 0xb8, 0xf2, - 0x3f, 0x70, 0x01, 0xcc, 0xdb, 0x37, 0x5f, 0x50, 0xcd, 0x56, 0xcd, 0xf6, 0xac, 0x57, 0xea, 0xde, - 0xdb, 0xec, 0xba, 0x7f, 0xbf, 0xad, 0xa9, 0x9a, 0xae, 0xea, 0x31, 0x80, 0xaf, 0x7c, 0x35, 0x97, - 0xa4, 0x4a, 0xab, 0x7a, 0x0d, 0xaf, 0x8b, 0xcb, 0x03, 0x07, 0x7d, 0xa5, 0xfc, 0x50, 0x1e, 0x2e, - 0x3e, 0x35, 0xf3, 0xcd, 0xc3, 0x6d, 0x99, 0xb5, 0xd2, 0x20, 0xd1, 0x2a, 0xed, 0x2c, 0x16, 0x77, - 0xc1, 0x34, 0x2d, 0x6e, 0xc8, 0x38, 0x8f, 0x1a, 0x49, 0x2a, 0x37, 0x83, 0xf3, 0xf5, 0x5b, 0xe6, - 0x3a, 0xe4, 0x1c, 0x93, 0x73, 0xcb, 0x71, 0x1e, 0xdd, 0x9d, 0xe8, 0x40, 0xc5, 0xd9, 0xfe, 0xeb, - 0x3f, 0xff, 0xff, 0xe0, 0xff, 0x6e, 0x1f, 0x59, 0x9f, 0x22, 0x14, 0xff, 0xb6, 0x56, 0x80, 0x62, - 0x1d, 0x6e, 0xac, 0xf8, 0x32, 0x9d, 0x06, 0xb1, 0x2f, 0x53, 0x8b, 0xf1, 0x3b, 0x32, 0x4e, 0x1b, - 0xc6, 0x7b, 0x09, 0x15, 0x4b, 0x30, 0x3e, 0x88, 0xeb, 0x7b, 0x72, 0x8d, 0x49, 0x53, 0xb2, 0x02, - 0x93, 0x85, 0xa4, 0x95, 0x67, 0x5a, 0x45, 0xb1, 0x17, 0x49, 0x8b, 0xe6, 0x87, 0x42, 0x53, 0x5b, - 0x9f, 0x40, 0x6c, 0xa9, 0xa4, 0x84, 0x80, 0x11, 0xfc, 0xa6, 0x2d, 0x5b, 0xa1, 0xc5, 0xf0, 0x23, - 0x05, 0x52, 0xae, 0x17, 0x67, 0x60, 0x06, 0xaf, 0xcf, 0x79, 0x61, 0x2e, 0xcd, 0x48, 0x0e, 0xf5, - 0xf5, 0x9c, 0xc1, 0x65, 0x2c, 0xfb, 0xe9, 0xe2, 0x50, 0x11, 0xce, 0x74, 0x29, 0x30, 0x62, 0x32, - 0xaa, 0xe8, 0x4b, 0xad, 0x65, 0x9a, 0x35, 0xbc, 0xb0, 0x5f, 0x78, 0x27, 0x82, 0xb0, 0x34, 0x5e, - 0xda, 0xae, 0x56, 0x71, 0xa5, 0x43, 0x2e, 0x86, 0xa1, 0xd8, 0x80, 0x9b, 0xfa, 0x3c, 0x15, 0x0e, - 0xce, 0xcb, 0xe4, 0x9c, 0xd9, 0xf3, 0x64, 0xa0, 0x76, 0x0d, 0xf8, 0xfb, 0xb2, 0x96, 0x0e, 0xce, - 0xd7, 0xc8, 0x59, 0x27, 0x96, 0x4b, 0x8a, 0xc6, 0x53, 0x30, 0x75, 0x4e, 0xa6, 0x4d, 0x95, 0xc9, - 0x86, 0x7c, 0x24, 0xf7, 0x42, 0x07, 0xdd, 0x15, 0xd2, 0x4d, 0x12, 0xb8, 0x8c, 0x1c, 0xba, 0x8e, - 0xc2, 0xc8, 0xa6, 0xd7, 0x92, 0x0e, 0x8a, 0xab, 0xa4, 0x18, 0xc6, 0xf5, 0x88, 0x2e, 0xc2, 0x98, - 0xaf, 0x3a, 0xb7, 0xe4, 0x80, 0x5f, 0x23, 0x7c, 0x94, 0x19, 0x52, 0x24, 0x2a, 0xc9, 0x43, 0x4f, - 0xbb, 0x44, 0xf0, 0x3a, 0x2b, 0x98, 0x21, 0xc5, 0x00, 0x69, 0x7d, 0x83, 0x15, 0x99, 0x91, 0xcf, - 0x05, 0x18, 0x55, 0x71, 0xb8, 0xa5, 0x62, 0x97, 0x20, 0xde, 0x24, 0x03, 0x10, 0x82, 0x82, 0x79, - 0xa8, 0xb9, 0x16, 0xe2, 0xad, 0x6d, 0xde, 0x1e, 0x5c, 0x81, 0x15, 0x98, 0xe4, 0x06, 0x15, 0xa8, - 0xd8, 0x41, 0xf1, 0x36, 0x29, 0x26, 0x0c, 0x8c, 0x6e, 0x43, 0xcb, 0x4c, 0xfb, 0xd2, 0x45, 0xf2, - 0x0e, 0xdf, 0x06, 0x21, 0x94, 0xca, 0xa6, 0x8c, 0x5b, 0x67, 0xdd, 0x0c, 0xef, 0x72, 0x2a, 0x99, - 0x41, 0xc5, 0x12, 0x8c, 0x47, 0x5e, 0x9a, 0x9d, 0xf5, 0x42, 0xa7, 0x72, 0xbc, 0x47, 0x8e, 0xb1, - 0x12, 0xa2, 0x8c, 0xe4, 0xf1, 0x20, 0x9a, 0xf7, 0x39, 0x23, 0x06, 0x46, 0x5b, 0x2f, 0xd3, 0x5e, - 0x33, 0x94, 0x8d, 0x41, 0x6c, 0x1f, 0xf0, 0xd6, 0xeb, 0xb0, 0xab, 0xa6, 0x71, 0x1e, 0x6a, 0x59, - 0x70, 0xc1, 0x49, 0xf3, 0x21, 0x57, 0xba, 0x00, 0x10, 0x7e, 0x00, 0x6e, 0xee, 0x3b, 0x26, 0x1c, - 0x64, 0x1f, 0x91, 0x6c, 0xb6, 0xcf, 0xa8, 0xa0, 0x96, 0x30, 0xa8, 0xf2, 0x63, 0x6e, 0x09, 0xb2, - 0xc7, 0xb5, 0x06, 0x33, 0x79, 0x9c, 0x79, 0x9b, 0x83, 0x65, 0xed, 0x13, 0xce, 0x5a, 0x87, 0xad, - 0x64, 0xed, 0x34, 0xcc, 0x92, 0x71, 0xb0, 0xba, 0x7e, 0xca, 0x8d, 0xb5, 0x43, 0x6f, 0x54, 0xab, - 0xfb, 0x20, 0x1c, 0x28, 0xd3, 0x79, 0x5e, 0xcb, 0x38, 0x43, 0xa6, 0x11, 0x79, 0x89, 0x83, 0xf9, - 0x3a, 0x99, 0xb9, 0xe3, 0x2f, 0x97, 0x82, 0x55, 0x2f, 0x41, 0xf9, 0xfd, 0xb0, 0x9f, 0xe5, 0x79, - 0x9c, 0xca, 0x96, 0xf2, 0xe3, 0xe0, 0x82, 0x6c, 0x3b, 0xa8, 0x3f, 0xeb, 0x29, 0xd5, 0x86, 0x81, - 0xa3, 0xf9, 0x24, 0xdc, 0x50, 0x9e, 0x55, 0x1a, 0x41, 0x94, 0xa8, 0x54, 0x5b, 0x8c, 0x9f, 0x73, - 0xa5, 0x4a, 0xee, 0x64, 0x81, 0x89, 0x65, 0x98, 0x28, 0x3e, 0xba, 0x3e, 0x92, 0x5f, 0x90, 0x68, - 0xbc, 0x4b, 0x51, 0xe3, 0x68, 0xa9, 0x28, 0xf1, 0x52, 0x97, 0xfe, 0xf7, 0x25, 0x37, 0x0e, 0x42, - 0xa8, 0x71, 0xe8, 0xad, 0x44, 0xe2, 0xb4, 0x77, 0x30, 0x7c, 0xc5, 0x8d, 0x83, 0x19, 0x52, 0xf0, - 0x81, 0xc1, 0x41, 0xf1, 0x35, 0x2b, 0x98, 0x41, 0xc5, 0x3d, 0xdd, 0x41, 0x9b, 0x4a, 0x3f, 0xc8, - 0x74, 0xea, 0xe1, 0x6a, 0x8b, 0xea, 0x9b, 0xed, 0xea, 0x21, 0x6c, 0xdd, 0x40, 0xc5, 0x29, 0x98, - 0xec, 0x39, 0x62, 0xd4, 0x6f, 0xdb, 0x63, 0x5b, 0x95, 0x59, 0xe6, 0xf9, 0xa5, 0xf0, 0xd1, 0x1d, - 0x6a, 0x46, 0xd5, 0x13, 0x86, 0xb8, 0x13, 0xeb, 0x5e, 0x3d, 0x07, 0xd8, 0x65, 0x17, 0x77, 0xca, - 0xd2, 0x57, 0x8e, 0x01, 0xe2, 0x04, 0x8c, 0x57, 0xce, 0x00, 0x76, 0xd5, 0x63, 0xa4, 0x1a, 0x33, - 0x8f, 0x00, 0xe2, 0x08, 0x0c, 0xe1, 0x3c, 0xb7, 0xe3, 0x8f, 0x13, 0x5e, 0x2c, 0x17, 0xc7, 0x60, - 0x84, 0xe7, 0xb8, 0x1d, 0x7d, 0x82, 0xd0, 0x12, 0x41, 0x9c, 0x67, 0xb8, 0x1d, 0x7f, 0x92, 0x71, - 0x46, 0x10, 0x77, 0x4f, 0xe1, 0xb7, 0x4f, 0x0f, 0x51, 0x1f, 0xe6, 0xdc, 0xcd, 0xc3, 0x30, 0x0d, - 0x6f, 0x3b, 0xfd, 0x14, 0xfd, 0x38, 0x13, 0xe2, 0x0e, 0xd8, 0xe7, 0x98, 0xf0, 0x67, 0x08, 0xed, - 0xac, 0x17, 0x4b, 0x30, 0x6a, 0x0c, 0x6c, 0x3b, 0xfe, 0x2c, 0xe1, 0x26, 0x85, 0xa1, 0xd3, 0xc0, - 0xb6, 0x0b, 0x9e, 0xe3, 0xd0, 0x89, 0xc0, 0xb4, 0xf1, 0xac, 0xb6, 0xd3, 0xcf, 0x73, 0xd6, 0x19, - 0x11, 0x0b, 0x50, 0x2b, 0xfb, 0xaf, 0x9d, 0x7f, 0x81, 0xf8, 0x2e, 0x83, 0x19, 0x30, 0xfa, 0xbf, - 0x5d, 0xf1, 0x22, 0x67, 0xc0, 0xa0, 0x70, 0x1b, 0xf5, 0xce, 0x74, 0xbb, 0xe9, 0x25, 0xde, 0x46, - 0x3d, 0x23, 0x1d, 0xab, 0x59, 0xb4, 0x41, 0xbb, 0xe2, 0x65, 0xae, 0x66, 0xb1, 0x1e, 0xc3, 0xe8, - 0x1d, 0x92, 0x76, 0xc7, 0x2b, 0x1c, 0x46, 0xcf, 0x8c, 0x14, 0x6b, 0x50, 0xdf, 0x3b, 0x20, 0xed, - 0xbe, 0x57, 0xc9, 0x37, 0xb5, 0x67, 0x3e, 0x8a, 0xfb, 0x60, 0xb6, 0xff, 0x70, 0xb4, 0x5b, 0x2f, - 0xed, 0xf4, 0xbc, 0xce, 0x98, 0xb3, 0x51, 0x9c, 0xee, 0x76, 0x59, 0x73, 0x30, 0xda, 0xb5, 0x97, - 0x77, 0xaa, 0x8d, 0xd6, 0x9c, 0x8b, 0x62, 0x11, 0xa0, 0x3b, 0x93, 0xec, 0xae, 0x2b, 0xe4, 0x32, - 0x20, 0xdc, 0x1a, 0x34, 0x92, 0xec, 0xfc, 0x55, 0xde, 0x1a, 0x44, 0xe0, 0xd6, 0xe0, 0x69, 0x64, - 0xa7, 0xaf, 0xf1, 0xd6, 0x60, 0x44, 0xcc, 0xc3, 0x48, 0x9c, 0x87, 0x21, 0x3e, 0x5b, 0xf5, 0x5b, - 0xfb, 0x8c, 0x1b, 0x19, 0xb6, 0x19, 0xfe, 0x65, 0x97, 0x60, 0x06, 0xc4, 0x11, 0xd8, 0x27, 0xa3, - 0xa6, 0x6c, 0xdb, 0xc8, 0x5f, 0x77, 0xb9, 0x9f, 0xe0, 0x6a, 0xb1, 0x00, 0xd0, 0x79, 0x99, 0xc6, - 0x28, 0x6c, 0xec, 0x6f, 0xbb, 0x9d, 0xf7, 0x7a, 0x03, 0xe9, 0x0a, 0x8a, 0xb7, 0x71, 0x8b, 0x60, - 0xbb, 0x2a, 0x28, 0x5e, 0xc0, 0x8f, 0xc2, 0xf0, 0x43, 0x99, 0x8a, 0xb5, 0xe7, 0xdb, 0xe8, 0xdf, - 0x89, 0xe6, 0xf5, 0x98, 0xb0, 0x48, 0xa5, 0x52, 0x7b, 0x7e, 0x66, 0x63, 0xff, 0x20, 0xb6, 0x04, - 0x10, 0x6e, 0x79, 0x99, 0x76, 0xb9, 0xef, 0x3f, 0x19, 0x66, 0x00, 0x83, 0xc6, 0xeb, 0x87, 0xe5, - 0x96, 0x8d, 0xfd, 0x8b, 0x83, 0xa6, 0xf5, 0xe2, 0x18, 0xd4, 0xf0, 0xb2, 0xf8, 0x3f, 0x84, 0x0d, - 0xfe, 0x9b, 0xe0, 0x2e, 0x81, 0xbf, 0x9c, 0xe9, 0xb6, 0x0e, 0xec, 0xc9, 0xfe, 0x87, 0x2a, 0xcd, - 0xeb, 0xc5, 0x22, 0x8c, 0x66, 0xba, 0xdd, 0xce, 0xe9, 0x44, 0x63, 0xc1, 0xff, 0xdd, 0x2d, 0x5f, - 0x72, 0x4b, 0xe6, 0xf8, 0x21, 0x98, 0x6e, 0xa9, 0xa8, 0x17, 0x3c, 0x0e, 0x2b, 0x6a, 0x45, 0xad, - 0x15, 0xbb, 0xe8, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x0a, 0x9c, 0xec, 0xd8, 0x50, 0x13, 0x00, - 0x00, + // 1220 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x98, 0x4b, 0x6f, 0x1c, 0x45, + 0x10, 0x80, 0x85, 0x48, 0x14, 0x6f, 0xd9, 0x8e, 0xf1, 0xda, 0x98, 0x10, 0x81, 0x08, 0x9c, 0x38, + 0xd9, 0xa7, 0x08, 0xa5, 0xad, 0xc8, 0x72, 0x2c, 0xc7, 0x4a, 0x84, 0xc1, 0x98, 0x38, 0xbc, 0x0e, + 0xab, 0xd9, 0xdd, 0xf6, 0x78, 0x60, 0x66, 0x7a, 0x98, 0xe9, 0x89, 0xe2, 0xdc, 0x50, 0x78, 0x08, + 0x21, 0xde, 0x48, 0x90, 0x90, 0x04, 0x38, 0xf0, 0x7e, 0x86, 0xf7, 0x91, 0x0b, 0x8f, 0x2b, 0xff, + 0x81, 0x0b, 0x60, 0xde, 0xbe, 0xf9, 0x82, 0x6a, 0xb6, 0x6a, 0xb6, 0x67, 0xbd, 0x52, 0xf7, 0xde, + 0xc6, 0xeb, 0xfe, 0xbe, 0xad, 0xa9, 0x9a, 0xae, 0xea, 0x59, 0x00, 0x5f, 0xf9, 0x6a, 0x3a, 0x49, + 0x95, 0x56, 0xf5, 0x1a, 0x5e, 0x17, 0x97, 0x07, 0x0f, 0xf9, 0x4a, 0xf9, 0xa1, 0x9c, 0x29, 0xfe, + 0x6a, 0xe6, 0xeb, 0x33, 0x6d, 0x99, 0xb5, 0xd2, 0x20, 0xd1, 0x2a, 0xed, 0x2c, 0x16, 0x77, 0xc1, + 0x04, 0x2d, 0x6e, 0xc8, 0x38, 0x8f, 0x1a, 0x49, 0x2a, 0xd7, 0x83, 0xb3, 0xf5, 0x9b, 0xa6, 0x3b, + 0xe4, 0x34, 0x93, 0xd3, 0x8b, 0x71, 0x1e, 0xdd, 0x9d, 0xe8, 0x40, 0xc5, 0xd9, 0x81, 0xab, 0xbf, + 0x5c, 0x7b, 0xe8, 0x9a, 0xdb, 0x87, 0x56, 0xc7, 0x09, 0xc5, 0xff, 0xad, 0x14, 0xa0, 0x58, 0x85, + 0xeb, 0x2b, 0xbe, 0x4c, 0xa7, 0x41, 0xec, 0xcb, 0xd4, 0x62, 0xfc, 0x9e, 0x8c, 0x13, 0x86, 0xf1, + 0x5e, 0x42, 0xc5, 0x02, 0x8c, 0x0e, 0xe2, 0xfa, 0x81, 0x5c, 0x23, 0xd2, 0x94, 0x2c, 0xc1, 0x58, + 0x21, 0x69, 0xe5, 0x99, 0x56, 0x51, 0xec, 0x45, 0xd2, 0xa2, 0xf9, 0xb1, 0xd0, 0xd4, 0x56, 0xf7, + 0x23, 0xb6, 0x50, 0x52, 0x42, 0xc0, 0x10, 0x7e, 0xd2, 0x96, 0xad, 0xd0, 0x62, 0xf8, 0x89, 0x02, + 0x29, 0xd7, 0x8b, 0xd3, 0x30, 0x89, 0xd7, 0x67, 0xbc, 0x30, 0x97, 0x66, 0x24, 0xb7, 0xf6, 0xf5, + 0x9c, 0xc6, 0x65, 0x2c, 0xfb, 0xf9, 0xfc, 0x9e, 0x22, 0x9c, 0x89, 0x52, 0x60, 0xc4, 0x64, 0x54, + 0xd1, 0x97, 0x5a, 0xcb, 0x34, 0x6b, 0x78, 0x61, 0xbf, 0xf0, 0x8e, 0x07, 0x61, 0x69, 0xbc, 0xb0, + 0x55, 0xad, 0xe2, 0x52, 0x87, 0x9c, 0x0f, 0x43, 0xb1, 0x06, 0x37, 0xf4, 0x79, 0x2a, 0x1c, 0x9c, + 0x17, 0xc9, 0x39, 0xb9, 0xeb, 0xc9, 0x40, 0xed, 0x0a, 0xf0, 0xe7, 0x65, 0x2d, 0x1d, 0x9c, 0xaf, + 0x93, 0xb3, 0x4e, 0x2c, 0x97, 0x14, 0x8d, 0x27, 0x61, 0xfc, 0x8c, 0x4c, 0x9b, 0x2a, 0x93, 0x0d, + 0xf9, 0x68, 0xee, 0x85, 0x0e, 0xba, 0x4b, 0xa4, 0x1b, 0x23, 0x70, 0x11, 0x39, 0x74, 0x1d, 0x81, + 0xa1, 0x75, 0xaf, 0x25, 0x1d, 0x14, 0x97, 0x49, 0xb1, 0x0f, 0xd7, 0x23, 0x3a, 0x0f, 0x23, 0xbe, + 0xea, 0xdc, 0x92, 0x03, 0x7e, 0x85, 0xf0, 0x61, 0x66, 0x48, 0x91, 0xa8, 0x24, 0x0f, 0x3d, 0xed, + 0x12, 0xc1, 0x1b, 0xac, 0x60, 0x86, 0x14, 0x03, 0xa4, 0xf5, 0x4d, 0x56, 0x64, 0x46, 0x3e, 0xe7, + 0x60, 0x58, 0xc5, 0xe1, 0xa6, 0x8a, 0x5d, 0x82, 0x78, 0x8b, 0x0c, 0x40, 0x08, 0x0a, 0x66, 0xa1, + 0xe6, 0x5a, 0x88, 0xb7, 0xb7, 0x78, 0x7b, 0x70, 0x05, 0x96, 0x60, 0x8c, 0x1b, 0x54, 0xa0, 0x62, + 0x07, 0xc5, 0x3b, 0xa4, 0xd8, 0x6f, 0x60, 0x74, 0x1b, 0x5a, 0x66, 0xda, 0x97, 0x2e, 0x92, 0x77, + 0xf9, 0x36, 0x08, 0xa1, 0x54, 0x36, 0x65, 0xdc, 0xda, 0x70, 0x33, 0xbc, 0xc7, 0xa9, 0x64, 0x06, + 0x15, 0x0b, 0x30, 0x1a, 0x79, 0x69, 0xb6, 0xe1, 0x85, 0x4e, 0xe5, 0x78, 0x9f, 0x1c, 0x23, 0x25, + 0x44, 0x19, 0xc9, 0xe3, 0x41, 0x34, 0x1f, 0x70, 0x46, 0x0c, 0x8c, 0xb6, 0x5e, 0xa6, 0xbd, 0x66, + 0x28, 0x1b, 0x83, 0xd8, 0x3e, 0xe4, 0xad, 0xd7, 0x61, 0x97, 0x4d, 0xe3, 0x2c, 0xd4, 0xb2, 0xe0, + 0x9c, 0x93, 0xe6, 0x23, 0xae, 0x74, 0x01, 0x20, 0xfc, 0x00, 0xdc, 0xd8, 0x77, 0x4c, 0x38, 0xc8, + 0x3e, 0x26, 0xd9, 0x54, 0x9f, 0x51, 0x41, 0x2d, 0x61, 0x50, 0xe5, 0x27, 0xdc, 0x12, 0x64, 0x8f, + 0x6b, 0x05, 0x26, 0xf3, 0x38, 0xf3, 0xd6, 0x07, 0xcb, 0xda, 0xa7, 0x9c, 0xb5, 0x0e, 0x5b, 0xc9, + 0xda, 0x29, 0x98, 0x22, 0xe3, 0x60, 0x75, 0xfd, 0x8c, 0x1b, 0x6b, 0x87, 0x5e, 0xab, 0x56, 0xf7, + 0x21, 0x38, 0x58, 0xa6, 0xf3, 0xac, 0x96, 0x71, 0x86, 0x4c, 0x23, 0xf2, 0x12, 0x07, 0xf3, 0x55, + 0x32, 0x73, 0xc7, 0x5f, 0x2c, 0x05, 0xcb, 0x5e, 0x82, 0xf2, 0xfb, 0xe1, 0x00, 0xcb, 0xf3, 0x38, + 0x95, 0x2d, 0xe5, 0xc7, 0xc1, 0x39, 0xd9, 0x76, 0x50, 0x7f, 0xde, 0x53, 0xaa, 0x35, 0x03, 0x47, + 0xf3, 0x09, 0xb8, 0xae, 0x3c, 0xab, 0x34, 0x82, 0x28, 0x51, 0xa9, 0xb6, 0x18, 0xbf, 0xe0, 0x4a, + 0x95, 0xdc, 0x89, 0x02, 0x13, 0x8b, 0xb0, 0xbf, 0xf8, 0xd3, 0xf5, 0x91, 0xfc, 0x92, 0x44, 0xa3, + 0x5d, 0x8a, 0x1a, 0x47, 0x4b, 0x45, 0x89, 0x97, 0xba, 0xf4, 0xbf, 0xaf, 0xb8, 0x71, 0x10, 0x42, + 0x8d, 0x43, 0x6f, 0x26, 0x12, 0xa7, 0xbd, 0x83, 0xe1, 0x6b, 0x6e, 0x1c, 0xcc, 0x90, 0x82, 0x0f, + 0x0c, 0x0e, 0x8a, 0x6f, 0x58, 0xc1, 0x0c, 0x2a, 0xee, 0xe9, 0x0e, 0xda, 0x54, 0xfa, 0x41, 0xa6, + 0x53, 0x0f, 0x57, 0x5b, 0x54, 0xdf, 0x6e, 0x55, 0x0f, 0x61, 0xab, 0x06, 0x2a, 0x4e, 0xc2, 0x58, + 0xcf, 0x11, 0xa3, 0x7e, 0xcb, 0x2e, 0xdb, 0xb2, 0xcc, 0x32, 0xcf, 0x2f, 0x85, 0x8f, 0x6d, 0x53, + 0x33, 0xaa, 0x9e, 0x30, 0xc4, 0x9d, 0x58, 0xf7, 0xea, 0x39, 0xc0, 0x2e, 0x3b, 0xbf, 0x5d, 0x96, + 0xbe, 0x72, 0x0c, 0x10, 0xc7, 0x61, 0xb4, 0x72, 0x06, 0xb0, 0xab, 0x1e, 0x27, 0xd5, 0x88, 0x79, + 0x04, 0x10, 0x87, 0x61, 0x0f, 0xce, 0x73, 0x3b, 0xfe, 0x04, 0xe1, 0xc5, 0x72, 0x71, 0x14, 0x86, + 0x78, 0x8e, 0xdb, 0xd1, 0x27, 0x09, 0x2d, 0x11, 0xc4, 0x79, 0x86, 0xdb, 0xf1, 0xa7, 0x18, 0x67, + 0x04, 0x71, 0xf7, 0x14, 0x7e, 0xf7, 0xcc, 0x1e, 0xea, 0xc3, 0x9c, 0xbb, 0x59, 0xd8, 0x47, 0xc3, + 0xdb, 0x4e, 0x3f, 0x4d, 0x5f, 0xce, 0x84, 0xb8, 0x03, 0xf6, 0x3a, 0x26, 0xfc, 0x59, 0x42, 0x3b, + 0xeb, 0xc5, 0x02, 0x0c, 0x1b, 0x03, 0xdb, 0x8e, 0x3f, 0x47, 0xb8, 0x49, 0x61, 0xe8, 0x34, 0xb0, + 0xed, 0x82, 0xe7, 0x39, 0x74, 0x22, 0x30, 0x6d, 0x3c, 0xab, 0xed, 0xf4, 0x0b, 0x9c, 0x75, 0x46, + 0xc4, 0x1c, 0xd4, 0xca, 0xfe, 0x6b, 0xe7, 0x5f, 0x24, 0xbe, 0xcb, 0x60, 0x06, 0x8c, 0xfe, 0x6f, + 0x57, 0xbc, 0xc4, 0x19, 0x30, 0x28, 0xdc, 0x46, 0xbd, 0x33, 0xdd, 0x6e, 0x7a, 0x99, 0xb7, 0x51, + 0xcf, 0x48, 0xc7, 0x6a, 0x16, 0x6d, 0xd0, 0xae, 0x78, 0x85, 0xab, 0x59, 0xac, 0xc7, 0x30, 0x7a, + 0x87, 0xa4, 0xdd, 0xf1, 0x2a, 0x87, 0xd1, 0x33, 0x23, 0xc5, 0x0a, 0xd4, 0x77, 0x0f, 0x48, 0xbb, + 0xef, 0x35, 0xf2, 0x8d, 0xef, 0x9a, 0x8f, 0xe2, 0x3e, 0x98, 0xea, 0x3f, 0x1c, 0xed, 0xd6, 0x0b, + 0xdb, 0x3d, 0xaf, 0x33, 0xe6, 0x6c, 0x14, 0xa7, 0xba, 0x5d, 0xd6, 0x1c, 0x8c, 0x76, 0xed, 0xc5, + 0xed, 0x6a, 0xa3, 0x35, 0xe7, 0xa2, 0x98, 0x07, 0xe8, 0xce, 0x24, 0xbb, 0xeb, 0x12, 0xb9, 0x0c, + 0x08, 0xb7, 0x06, 0x8d, 0x24, 0x3b, 0x7f, 0x99, 0xb7, 0x06, 0x11, 0xb8, 0x35, 0x78, 0x1a, 0xd9, + 0xe9, 0x2b, 0xbc, 0x35, 0x18, 0x11, 0xb3, 0x30, 0x14, 0xe7, 0x61, 0x88, 0xcf, 0x56, 0xfd, 0xe6, + 0x3e, 0xe3, 0x46, 0x86, 0x6d, 0x86, 0x7f, 0xdd, 0x21, 0x98, 0x01, 0x71, 0x18, 0xf6, 0xca, 0xa8, + 0x29, 0xdb, 0x36, 0xf2, 0xb7, 0x1d, 0xee, 0x27, 0xb8, 0x5a, 0xcc, 0x01, 0x74, 0x5e, 0xa6, 0x31, + 0x0a, 0x1b, 0xfb, 0xfb, 0x4e, 0xe7, 0xbd, 0xde, 0x40, 0xba, 0x82, 0xe2, 0x6d, 0xdc, 0x22, 0xd8, + 0xaa, 0x0a, 0x8a, 0x17, 0xf0, 0x23, 0xb0, 0xef, 0xe1, 0x4c, 0xc5, 0xda, 0xf3, 0x6d, 0xf4, 0x1f, + 0x44, 0xf3, 0x7a, 0x4c, 0x58, 0xa4, 0x52, 0xa9, 0x3d, 0x3f, 0xb3, 0xb1, 0x7f, 0x12, 0x5b, 0x02, + 0x08, 0xb7, 0xbc, 0x4c, 0xbb, 0xdc, 0xf7, 0x5f, 0x0c, 0x33, 0x80, 0x41, 0xe3, 0xf5, 0x23, 0x72, + 0xd3, 0xc6, 0xfe, 0xcd, 0x41, 0xd3, 0x7a, 0x71, 0x14, 0x6a, 0x78, 0x59, 0xfc, 0x0e, 0x61, 0x83, + 0xff, 0x21, 0xb8, 0x4b, 0xe0, 0x37, 0x67, 0xba, 0xad, 0x03, 0x7b, 0xb2, 0xff, 0xa5, 0x4a, 0xf3, + 0x7a, 0x31, 0x0f, 0xc3, 0x99, 0x6e, 0xb7, 0x73, 0x3a, 0xd1, 0x58, 0xf0, 0xff, 0x76, 0xca, 0x97, + 0xdc, 0x92, 0x39, 0xb6, 0x08, 0x13, 0x2d, 0x15, 0xf5, 0x82, 0xc7, 0x60, 0x49, 0x2d, 0xa9, 0x95, + 0x62, 0x17, 0x3d, 0x78, 0x9b, 0x1f, 0xe8, 0x8d, 0xbc, 0x39, 0xdd, 0x52, 0xd1, 0x0c, 0x1e, 0x35, + 0xbb, 0xbf, 0xa0, 0x95, 0x07, 0xcf, 0xff, 0x03, 0x00, 0x00, 0xff, 0xff, 0xed, 0x5f, 0x6c, 0x20, + 0x74, 0x13, 0x00, 0x00, } diff --git a/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto b/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto index fbca44cd48..7f09979358 100644 --- a/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto +++ b/vendor/github.com/gogo/protobuf/gogoproto/gogo.proto @@ -33,6 +33,7 @@ import "google/protobuf/descriptor.proto"; option java_package = "com.google.protobuf"; option java_outer_classname = "GoGoProtos"; +option go_package = "github.com/gogo/protobuf/gogoproto"; extend google.protobuf.EnumOptions { optional bool goproto_enum_prefix = 62001; diff --git a/vendor/github.com/gogo/protobuf/install-protobuf.sh b/vendor/github.com/gogo/protobuf/install-protobuf.sh index fc40642e40..f42fc9e631 100755 --- a/vendor/github.com/gogo/protobuf/install-protobuf.sh +++ b/vendor/github.com/gogo/protobuf/install-protobuf.sh @@ -26,7 +26,3 @@ case "$PROTOBUF_VERSION" in die "unknown protobuf version: $PROTOBUF_VERSION" ;; esac - - - - diff --git a/vendor/github.com/gogo/protobuf/proto/all_test.go b/vendor/github.com/gogo/protobuf/proto/all_test.go deleted file mode 100644 index b5f8709d85..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/all_test.go +++ /dev/null @@ -1,2278 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "testing" - "time" - - . "github.com/gogo/protobuf/proto" - . "github.com/gogo/protobuf/proto/testdata" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { - data := b.Bytes() - ld := len(data) - ls := len(s) / 2 - - fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) - - // find the interesting spot - n - n := ls - if ld < ls { - n = ld - } - j := 0 - for i := 0; i < n; i++ { - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - if data[i] == bs { - continue - } - n = i - break - } - l := n - 10 - if l < 0 { - l = 0 - } - h := n + 10 - - // find the interesting spot - n - fmt.Printf("is[%d]:", l) - for i := l; i < h; i++ { - if i >= ld { - fmt.Printf(" --") - continue - } - fmt.Printf(" %.2x", data[i]) - } - fmt.Printf("\n") - - fmt.Printf("sb[%d]:", l) - for i := l; i < h; i++ { - if i >= ls { - fmt.Printf(" --") - continue - } - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - fmt.Printf(" %.2x", bs) - } - fmt.Printf("\n") - - t.Fail() - - // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) - // Print the output in a partially-decoded format; can - // be helpful when updating the test. It produces the output - // that is pasted, with minor edits, into the argument to verify(). - // data := b.Bytes() - // nesting := 0 - // for b.Len() > 0 { - // start := len(data) - b.Len() - // var u uint64 - // u, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // wire := u & 0x7 - // tag := u >> 3 - // switch wire { - // case WireVarint: - // v, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed32: - // v, err := DecodeFixed32(b) - // if err != nil { - // fmt.Printf("decode error on fixed32:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed64: - // v, err := DecodeFixed64(b) - // if err != nil { - // fmt.Printf("decode error on fixed64:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireBytes: - // nb, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // after_tag := len(data) - b.Len() - // str := make([]byte, nb) - // _, err = b.Read(str) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", - // data[start:after_tag], str, tag, wire) - // case WireStartGroup: - // nesting++ - // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // case WireEndGroup: - // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // nesting-- - // default: - // fmt.Printf("unrecognized wire type %d\n", wire) - // return - // } - // } -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } -func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } -func (f *fakeMarshaler) ProtoMessage() {} -func (f *fakeMarshaler) Reset() {} - -type msgWithFakeMarshaler struct { - M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` -} - -func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } -func (m *msgWithFakeMarshaler) ProtoMessage() {} -func (m *msgWithFakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - errType reflect.Type - }{ - { - name: "Marshaler that fails", - m: &fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since the Marshal method returned bytes, they should be written to the - // buffer. (For efficiency, we assume that Marshal implementations are - // always correct w.r.t. RequiredNotSetError and output.) - want: []byte{5, 6, 7}, - errType: reflect.TypeOf(errors.New("some marshal err")), - }, - { - name: "Marshaler that fails with RequiredNotSetError", - m: &msgWithFakeMarshaler{ - M: &fakeMarshaler{ - err: &RequiredNotSetError{}, - b: []byte{5, 6, 7}, - }, - }, - // Since there's an error that can be continued after, - // the buffer should be written. - want: []byte{ - 10, 3, // for &msgWithFakeMarshaler - 5, 6, 7, // for &fakeMarshaler - }, - errType: reflect.TypeOf(&RequiredNotSetError{}), - }, - { - name: "Marshaler that succeeds", - m: &fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if reflect.TypeOf(err) != test.errType { - t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - if size := Size(test.m); size != len(b.Bytes()) { - t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes())) - } - - m, mErr := Marshal(test.m) - if !bytes.Equal(b.Bytes(), m) { - t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes()) - } - if !reflect.DeepEqual(err, mErr) { - t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q", - test.name, fmt.Sprint(mErr), fmt.Sprint(err)) - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if strings.Index(err.Error(), "Kind") < 0 { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f") // field 103, encoding 0, 0x7f zigzag64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f") // value 64, value -64 -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err = Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - var x uint64 - x = uint64(pbd.F_Sint64Repeated[i]) - if x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - x = uint64(pbd.F_Sint32Repeated[i]) - if x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - x = uint64(pbd.F_DoubleRepeated[i]) - if x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - x = uint64(pbd.F_FloatRepeated[i]) - if x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - x = pbd.F_Uint64Repeated[i] - if x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - x = uint64(pbd.F_Uint32Repeated[i]) - if x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - x = pbd.F_Fixed64Repeated[i] - if x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - x = uint64(pbd.F_Fixed32Repeated[i]) - if x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - x = uint64(pbd.F_Int64Repeated[i]) - if x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - x = uint64(pbd.F_Int32Repeated[i]) - if x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if pbd.F_BoolRepeated[i] != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -// Verify we give a useful message when decoding to the wrong structure type. -func TestTypeMismatch(t *testing.T) { - pb1 := initGoTest(true) - - // Marshal - o := old() - o.Marshal(pb1) - - // Now Unmarshal it to the wrong type. - pb2 := initGoTestField() - err := o.Unmarshal(pb2) - if err == nil { - t.Error("expected error, got no error") - } else if !strings.Contains(err.Error(), "bad wiretype") { - t.Error("expected bad wiretype error, got", err) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - err := o.Marshal(pb) - if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - _ = fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -// Verify that absent required fields in groups cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcementGroups(t *testing.T) { - pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}} - if _, err := Marshal(pb); err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") { - t.Errorf("marshal: bad error type: %v", err) - } - - buf := []byte{11, 12} - if err := Unmarshal(buf, pb); err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - { - var m *GoEnum - if _, err := Marshal(m); err != ErrNil { - t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err) - } - } - - { - m := &Communique{Union: &Communique_Msg{Msg: nil}} - if _, err := Marshal(m); err == nil || err == ErrNil { - t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err) - } - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -// A type that implements the Marshaler interface and is nillable. -type nillableMessage struct { - x uint64 -} - -func (nm *nillableMessage) Marshal() ([]byte, error) { - return EncodeVarint(nm.x), nil -} - -type NMMessage struct { - nm *nillableMessage -} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { - m := &MyMessage{ - Pet: []string{"turtle", "wombat"}, - } - expected := Clone(m) - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err = Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" // field 103, encoding 0, 0x7f zigzag64 - - o := old() - mbytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", mbytes) - t.Fatalf("expected = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(mbytes, expected, t) { - o.DebugPrint("neq 1", mbytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(mbytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", mbytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { - t.Errorf("unmarshal wrong err msg: %v", err) - } - mbytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", mbytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(mbytes, expected, t) { - o.DebugPrint("neq 2", mbytes) - t.Fatalf("string = %s", expected) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: {F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for _, pair := range [][2]interface{}{ - {m.NameMapping, m2.NameMapping}, - {m.MsgMapping, m2.MsgMapping}, - {m.ByteMapping, m2.ByteMapping}, - } { - if !reflect.DeepEqual(pair[0], pair[1]) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) - } - } -} - -func TestMapFieldWithNil(t *testing.T) { - m1 := &MessageWithMap{ - MsgMapping: map[int64]*FloatingPoint{ - 1: nil, - }, - } - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.MsgMapping[1]; !ok { - t.Error("msg_mapping[1] not present") - } else if v != nil { - t.Errorf("msg_mapping[1] not nil: %v", v) - } -} - -func TestMapFieldWithNilBytes(t *testing.T) { - m1 := &MessageWithMap{ - ByteMapping: map[bool][]byte{ - false: {}, - true: nil, - }, - } - n := Size(m1) - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if n != len(b) { - t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b)) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.ByteMapping[false]; !ok { - t.Error("byte_mapping[false] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[false] not empty: %#v", v) - } - if v, ok := m2.ByteMapping[true]; !ok { - t.Error("byte_mapping[true] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[true] not empty: %#v", v) - } -} - -func TestDecodeMapFieldMissingKey(t *testing.T) { - b := []byte{ - 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes - // no key - 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m" - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing key: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want) - } -} - -func TestDecodeMapFieldMissingValue(t *testing.T) { - b := []byte{ - 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes - 0x08, 0x01, // varint key, value 1 - // no value - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing value: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{1: ""}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want) - } -} - -func TestOneof(t *testing.T) { - m := &Communique{} - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal of empty message with oneof: %v", err) - } - if len(b) != 0 { - t.Errorf("Marshal of empty message yielded too many bytes: %v", b) - } - - m = &Communique{ - Union: &Communique_Name{Name: "Barry"}, - } - - // Round-trip. - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof: %v", err) - } - if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) - t.Errorf("Incorrect marshal of message with oneof: %v", b) - } - m.Reset() - if err = Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof: %v", err) - } - if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { - t.Errorf("After round trip, Union = %+v", m.Union) - } - if name := m.GetName(); name != "Barry" { - t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") - } - - // Let's try with a message in the oneof. - m.Union = &Communique_Msg{Msg: &Strings{StringField: String("deep deep string")}} - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof set to message: %v", err) - } - if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) - t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof set to message: %v", err) - } - ss, ok := m.Union.(*Communique_Msg) - if !ok || ss.Msg.GetStringField() != "deep deep string" { - t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) - } -} - -func TestInefficientPackedBool(t *testing.T) { - // https://github.com/golang/protobuf/issues/76 - inp := []byte{ - 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes - // Usually a bool should take a single byte, - // but it is permitted to be any varint. - 0xb9, 0x30, - } - if err := Unmarshal(inp, new(MoreRepeated)); err != nil { - t.Error(err) - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/any_test.go b/vendor/github.com/gogo/protobuf/proto/any_test.go deleted file mode 100644 index f098d8287e..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/any_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "strings" - "testing" - - "github.com/gogo/protobuf/proto" - - pb "github.com/gogo/protobuf/proto/proto3_proto" - testpb "github.com/gogo/protobuf/proto/testdata" - "github.com/gogo/protobuf/types" -) - -var ( - expandedMarshaler = proto.TextMarshaler{ExpandAny: true} - expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true} -) - -// anyEqual reports whether two messages which may be google.protobuf.Any or may -// contain google.protobuf.Any fields are equal. We can't use proto.Equal for -// comparison, because semantically equivalent messages may be marshaled to -// binary in different tag order. Instead, trust that TextMarshaler with -// ExpandAny option works and compare the text marshaling results. -func anyEqual(got, want proto.Message) bool { - // if messages are proto.Equal, no need to marshal. - if proto.Equal(got, want) { - return true - } - g := expandedMarshaler.Text(got) - w := expandedMarshaler.Text(want) - return g == w -} - -type golden struct { - m proto.Message - t, c string -} - -var goldenMessages = makeGolden() - -func makeGolden() []golden { - nested := &pb.Nested{Bunny: "Monty"} - nb, err := proto.Marshal(nested) - if err != nil { - panic(err) - } - m1 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &types.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m2 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &types.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m3 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &types.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb}, - } - m4 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &types.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb}, - } - m5 := &types.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb} - - any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")} - proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")}) - proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar")) - any1b, err := proto.Marshal(any1) - if err != nil { - panic(err) - } - any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}} - proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")}) - any2b, err := proto.Marshal(any2) - if err != nil { - panic(err) - } - m6 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &types.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - ManyThings: []*types.Any{ - {TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b}, - {TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - }, - } - - const ( - m1Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m2Golden = ` -name: "David" -result_count: 47 -anything: < - ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m3Golden = ` -name: "David" -result_count: 47 -anything: < - ["type.googleapis.com/\"/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m4Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m5Golden = ` -[type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" -> -` - m6Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 42 - bikeshed: GREEN - rep_bytes: "roboto" - [testdata.Ext.more]: < - data: "baz" - > - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -` - ) - return []golden{ - {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "}, - {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "}, - {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "}, - {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "}, - {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "}, - {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "}, - } -} - -func TestMarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want { - t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want) - } - if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want { - t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want) - } - } -} - -func TestUnmarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - want := tt.m - got := proto.Clone(tt.m) - got.Reset() - if err := proto.UnmarshalText(tt.t, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want) - } - got.Reset() - if err := proto.UnmarshalText(tt.c, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want) - } - } -} - -func TestMarshalUnknownAny(t *testing.T) { - m := &pb.Message{ - Anything: &types.Any{ - TypeUrl: "foo", - Value: []byte("bar"), - }, - } - want := `anything: < - type_url: "foo" - value: "bar" -> -` - got := expandedMarshaler.Text(m) - if got != want { - t.Errorf("got\n`%s`\nwant\n`%s`", got, want) - } -} - -func TestAmbiguousAny(t *testing.T) { - pb := &types.Any{} - err := proto.UnmarshalText(` - type_url: "ttt/proto3_proto.Nested" - value: "\n\x05Monty" - `, pb) - t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err) - if err != nil { - t.Errorf("failed to parse ambiguous Any message: %v", err) - } -} - -func TestUnmarshalOverwriteAny(t *testing.T) { - pb := &types.Any{} - err := proto.UnmarshalText(` - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 7: Any message unpacked multiple times, or "type_url" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} - -func TestUnmarshalAnyMixAndMatch(t *testing.T) { - pb := &types.Any{} - err := proto.UnmarshalText(` - value: "\n\x05Monty" - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 5: Any message unpacked multiple times, or "value" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/clone_test.go b/vendor/github.com/gogo/protobuf/proto/clone_test.go deleted file mode 100644 index 1a16eb5549..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/clone_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "testing" - - "github.com/gogo/protobuf/proto" - - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Errorf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: {F: proto.Float64(2.0)}, - 0x4002: { - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4002: { - F: proto.Float64(3.0), - Exact: proto.Bool(true), - }, // the entire message should be overwritten - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: {F: proto.Float64(2.0)}, - 0x4002: { - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, - // proto3 shouldn't merge zero values, - // in the same way that proto2 shouldn't merge nils. - { - src: &proto3pb.Message{ - Name: "Aaron", - Data: []byte(""), // zero value, but not nil - }, - dst: &proto3pb.Message{ - HeightInCm: 176, - Data: []byte("texas!"), - }, - want: &proto3pb.Message{ - Name: "Aaron", - HeightInCm: 176, - Data: []byte("texas!"), - }, - }, - // Oneof fields should merge by assignment. - { - src: &pb.Communique{ - Union: &pb.Communique_Number{Number: 41}, - }, - dst: &pb.Communique{ - Union: &pb.Communique_Name{Name: "Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Number{Number: 41}, - }, - }, - // Oneof nil is the same as not set. - { - src: &pb.Communique{}, - dst: &pb.Communique{ - Union: &pb.Communique_Name{Name: "Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Name{Name: "Bobby Tables"}, - }, - }, - { - src: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": {Cute: true}, // replace - "kay_b": {Bunny: "rabbit"}, // insert - }, - }, - dst: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": {Bunny: "lost"}, // replaced - "kay_c": {Bunny: "bunny"}, // keep - }, - }, - want: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": {Cute: true}, - "kay_b": {Bunny: "rabbit"}, - "kay_c": {Bunny: "bunny"}, - }, - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/decode_test.go b/vendor/github.com/gogo/protobuf/proto/decode_test.go deleted file mode 100644 index 64d4decd9d..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/decode_test.go +++ /dev/null @@ -1,262 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -// +build go1.7 - -package proto_test - -import ( - "testing" - - "github.com/gogo/protobuf/proto" - tpb "github.com/gogo/protobuf/proto/proto3_proto" -) - -var ( - bytesBlackhole []byte - msgBlackhole = new(tpb.Message) -) - -// Disabled this Benchmark because it is using features (b.Run) from go1.7 and gogoprotobuf still have compatibility with go1.5 -// BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and -// 2 bytes long). -// func BenchmarkVarint32ArraySmall(b *testing.B) { -// for i := uint(1); i <= 10; i++ { -// dist := genInt32Dist([7]int{0, 3, 1}, 1<unmarshal. -} - -func TestMarshalUnmarshalRepeatedExtension(t *testing.T) { - // Add a repeated extension to the result. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - // Marshal message with a repeated extension. - msg1 := new(pb.OtherMessage) - err := proto.SetExtension(msg1, pb.E_RComplex, test.ext) - if err != nil { - t.Fatalf("[%s] Error setting extension: %v", test.name, err) - } - b, err := proto.Marshal(msg1) - if err != nil { - t.Fatalf("[%s] Error marshaling message: %v", test.name, err) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err = proto.Unmarshal(b, msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_RComplex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.([]*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(ext, test.ext) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, test.ext) - } - } -} - -func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) { - // We may see multiple instances of the same extension in the wire - // format. For example, the proto compiler may encode custom options in - // this way. Here, we verify that we merge the extensions together. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - var buf bytes.Buffer - var want pb.ComplexExtension - - // Generate a serialized representation of a repeated extension - // by catenating bytes together. - for i, e := range test.ext { - // Merge to create the wanted proto. - proto.Merge(&want, e) - - // serialize the message - msg := new(pb.OtherMessage) - err := proto.SetExtension(msg, pb.E_Complex, e) - if err != nil { - t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err) - } - b, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err) - } - buf.Write(b) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err := proto.Unmarshal(buf.Bytes(), msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_Complex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.(*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(*ext, want) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, want) - } - } -} - -func TestClearAllExtensions(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - m := &pb.MyMessage{} - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - if !proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got false, want true", proto.MarshalTextString(m)) - } - proto.ClearAllExtensions(m) - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } -} - -func TestMarshalRace(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - - m := &pb.MyMessage{Count: proto.Int32(4)} - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - - errChan := make(chan error, 3) - for n := 3; n > 0; n-- { - go func() { - _, err := proto.Marshal(m) - errChan <- err - }() - } - for i := 0; i < 3; i++ { - err := <-errChan - if err != nil { - t.Fatal(err) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/map_test.go b/vendor/github.com/gogo/protobuf/proto/map_test.go deleted file mode 100644 index 18b946d00e..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/map_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package proto_test - -import ( - "fmt" - "testing" - - "github.com/gogo/protobuf/proto" - ppb "github.com/gogo/protobuf/proto/proto3_proto" -) - -func marshalled() []byte { - m := &ppb.IntMaps{} - for i := 0; i < 1000; i++ { - m.Maps = append(m.Maps, &ppb.IntMap{ - Rtt: map[int32]int32{1: 2}, - }) - } - b, err := proto.Marshal(m) - if err != nil { - panic(fmt.Sprintf("Can't marshal %+v: %v", m, err)) - } - return b -} - -func BenchmarkConcurrentMapUnmarshal(b *testing.B) { - in := marshalled() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } - }) -} - -func BenchmarkSequentialMapUnmarshal(b *testing.B) { - in := marshalled() - b.ResetTimer() - for i := 0; i < b.N; i++ { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/message_set_test.go b/vendor/github.com/gogo/protobuf/proto/message_set_test.go deleted file mode 100644 index 353a3ea769..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &messageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - var extensions XXX_InternalExtensions - if err := UnmarshalMessageSet(b, &extensions); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := extensions.p.extensionMap[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/proto3_test.go b/vendor/github.com/gogo/protobuf/proto/proto3_test.go deleted file mode 100644 index 75b66c1797..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "testing" - - "github.com/gogo/protobuf/proto" - pb "github.com/gogo/protobuf/proto/proto3_proto" - tpb "github.com/gogo/protobuf/proto/testdata" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} - -func TestGettersForBasicTypesExist(t *testing.T) { - var m pb.Message - if got := m.GetNested().GetBunny(); got != "" { - t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got) - } - if got := m.GetNested().GetCute(); got { - t.Errorf("m.GetNested().GetCute() = %t, want false", got) - } -} - -func TestProto3SetDefaults(t *testing.T) { - in := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: new(tpb.SubDefaults), - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": new(tpb.SubDefaults), - }, - } - - got := proto.Clone(in).(*pb.Message) - proto.SetDefaults(got) - - // There are no defaults in proto3. Everything should be the zero value, but - // we need to remember to set defaults for nested proto2 messages. - want := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": {N: proto.Int64(7)}, - }, - } - - if !proto.Equal(got, want) { - t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/size2_test.go b/vendor/github.com/gogo/protobuf/proto/size2_test.go deleted file mode 100644 index a2729c39a1..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := sizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/size_test.go b/vendor/github.com/gogo/protobuf/proto/size_test.go deleted file mode 100644 index 0a6c1772b4..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/size_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "log" - "strings" - "testing" - - . "github.com/gogo/protobuf/proto" - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: {}}}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: {F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, - {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: {}}}}, - - {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, - {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, - {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, - - {"oneof not set", &pb.Oneof{}}, - {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{F_Bool: true}}}, - {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{F_Int32: 0}}}, - {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{F_Int32: 1 << 20}}}, - {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{F_Int64: 42}}}, - {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{F_Fixed32: 43}}}, - {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{F_Fixed64: 44}}}, - {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{F_Uint32: 45}}}, - {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{F_Uint64: 46}}}, - {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{F_Float: 47.1}}}, - {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{F_Double: 48.9}}}, - {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{F_String: "Rhythmic Fman"}}}, - {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{F_Bytes: []byte("let go")}}}, - {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{F_Sint32: 50}}}, - {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{F_Sint64: 51}}}, - {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{F_Enum: pb.MyMessage_BLUE}}}, - {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}}, - {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{F_Message: &pb.GoTestField{Label: String("k"), Type: String("v")}}}}, - {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{FGroup: &pb.Oneof_F_Group{X: Int32(52)}}}}, - {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{F_Largest_Tag: 1}}}, - {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{F_Int32: 1}, Tormato: &pb.Oneof_Value{Value: 2}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/proto/text_parser_test.go b/vendor/github.com/gogo/protobuf/proto/text_parser_test.go deleted file mode 100644 index 9a3a447ce7..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,673 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "math" - "reflect" - "testing" - - . "github.com/gogo/protobuf/proto" - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - . "github.com/gogo/protobuf/proto/testdata" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation with double quotes - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenation with single quotes - { - in: "count:42 name: 'My name is '\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenations with mixed quotes - { - in: "count:42 name: 'My name is '\n\"elsewhere\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - { - in: "count:42 name: \"My name is \"\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\xAB'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\xAB"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated field with list notation - { - in: `count:42 pet: ["horsey", "bunny"]`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: `proto: required field "testdata.MyMessage.count" not set`, - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Missing required field in a required submessage - { - in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`, - err: `proto: required field "testdata.InnerMessage.host" not set`, - out: &MyMessage{ - Count: Int32(42), - WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}}, - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Boolean false - { - in: `count:42 inner { host: "example.com" connected: false }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean true - { - in: `count:42 inner { host: "example.com" connected: true }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean 0 - { - in: `count:42 inner { host: "example.com" connected: 0 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean 1 - { - in: `count:42 inner { host: "example.com" connected: 1 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean f - { - in: `count:42 inner { host: "example.com" connected: f }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean t - { - in: `count:42 inner { host: "example.com" connected: t }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean False - { - in: `count:42 inner { host: "example.com" connected: False }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean True - { - in: `count:42 inner { host: "example.com" connected: True }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - - // Extension - buildExtStructTest(`count: 42 [testdata.Ext.more]:`), - buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:,>` + // separating commas are okay - `msg_mapping>` + // no colon after "value" - `msg_mapping:>` + // omitted key - `msg_mapping:` + // omitted value - `byte_mapping:` + - `byte_mapping:<>` // omitted key and value - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - -2: {F: Float64(4.0)}, - 0: {F: Float64(5.0)}, - 1: nil, - }, - ByteMapping: map[bool][]byte{ - false: nil, - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestOneofParsing(t *testing.T) { - const in = `name:"Shrek"` - m := new(Communique) - want := &Communique{Union: &Communique_Name{Name: "Shrek"}} - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } - - const inOverwrite = `name:"Shrek" number:42` - m = new(Communique) - testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'" - if err := UnmarshalText(inOverwrite, m); err == nil { - t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr) - } else if err.Error() != testErr { - t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v", - err.Error(), testErr) - } - -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/vendor/github.com/gogo/protobuf/proto/text_test.go b/vendor/github.com/gogo/protobuf/proto/text_test.go deleted file mode 100644 index 27df6cb9b4..0000000000 --- a/vendor/github.com/gogo/protobuf/proto/text_test.go +++ /dev/null @@ -1,474 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "testing" - - "github.com/gogo/protobuf/proto" - - proto3pb "github.com/gogo/protobuf/proto/proto3_proto" - pb "github.com/gogo/protobuf/proto/testdata" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[testdata.Ext.more]: < - data: "Big gobs for big rats" -> -[testdata.greeting]: "adg" -[testdata.greeting]: "easy" -[testdata.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func TestTextOneof(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&pb.Communique{}, ``}, - // scalar field - {&pb.Communique{Union: &pb.Communique_Number{Number: 4}}, `number:4`}, - // message field - {&pb.Communique{Union: &pb.Communique_Msg{ - Msg: &pb.Strings{StringField: proto.String("why hello!")}, - }}, `msg:`}, - // bad oneof (should not panic) - {&pb.Communique{Union: &pb.Communique_Msg{Msg: nil}}, `msg:/* nil */`}, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pbStrings := new(pb.Strings) - if err := proto.UnmarshalText(s, pbStrings); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pbStrings, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pbStrings) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - { - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; map format is the same as a repeated struct, - // and they are sorted by key (numerically for numeric keys). - { - &pb.MessageWithMap{NameMapping: map[int32]string{ - -1: "Negatory", - 7: "Lucky", - 1234: "Feist", - 6345789: "Otis", - }}, - `name_mapping: ` + - `name_mapping: ` + - `name_mapping: ` + - `name_mapping:`, - }, - // map with nil value; not well-defined, but we shouldn't crash - { - &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, - `msg_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go index 82623f0497..4174cbd9f3 100644 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go +++ b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go @@ -805,10 +805,17 @@ func (m *OneofDescriptorProto) GetOptions() *OneofOptions { // Describes an enum type. type EnumDescriptorProto struct { - Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` - Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` - Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` - XXX_unrecognized []byte `json:"-"` + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` + Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` + // Range of reserved numeric values. Reserved numeric values may not be used + // by enum values in the same enum declaration. Reserved ranges may not + // overlap. + ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"` + // Reserved enum value names, which may not be reused. A given name may only + // be reserved once. + ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"` + XXX_unrecognized []byte `json:"-"` } func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } @@ -837,6 +844,53 @@ func (m *EnumDescriptorProto) GetOptions() *EnumOptions { return nil } +func (m *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange { + if m != nil { + return m.ReservedRange + } + return nil +} + +func (m *EnumDescriptorProto) GetReservedName() []string { + if m != nil { + return m.ReservedName + } + return nil +} + +// Range of reserved numeric values. Reserved values may not be used by +// entries in the same enum. Reserved ranges may not overlap. +// +// Note that this is distinct from DescriptorProto.ReservedRange in that it +// is inclusive such that it can appropriately represent the entire int32 +// domain. +type EnumDescriptorProto_EnumReservedRange struct { + Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` + End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} } +func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) } +func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {} +func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) { + return fileDescriptorDescriptor, []int{6, 0} +} + +func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 { + if m != nil && m.Start != nil { + return *m.Start + } + return 0 +} + +func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 { + if m != nil && m.End != nil { + return *m.End + } + return 0 +} + // Describes a value within an enum. type EnumValueDescriptorProto struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` @@ -1020,7 +1074,7 @@ type FileOptions struct { CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"` JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"` PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"` - PhpGenericServices *bool `protobuf:"varint,19,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` + PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"` // Is this file deprecated? // Depending on the target platform, this can emit Deprecated annotations // for everything in the file, or it will be completely ignored; in the very @@ -2037,6 +2091,7 @@ func init() { proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto") proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto") proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto") + proto.RegisterType((*EnumDescriptorProto_EnumReservedRange)(nil), "google.protobuf.EnumDescriptorProto.EnumReservedRange") proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto") proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto") proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto") @@ -2065,159 +2120,161 @@ func init() { func init() { proto.RegisterFile("descriptor.proto", fileDescriptorDescriptor) } var fileDescriptorDescriptor = []byte{ - // 2451 bytes of a gzipped FileDescriptorProto + // 2487 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xcd, 0x6f, 0xdb, 0xc8, - 0x15, 0x5f, 0x7d, 0x5a, 0x7a, 0x92, 0xe5, 0xf1, 0xd8, 0x9b, 0x30, 0xce, 0x66, 0xe3, 0x28, 0xc9, - 0xc6, 0x49, 0x5a, 0x65, 0xe1, 0x7c, 0xae, 0xb7, 0xd8, 0x56, 0x96, 0x18, 0xaf, 0x52, 0x59, 0x52, - 0x29, 0xb9, 0x9b, 0xec, 0x85, 0x18, 0x93, 0x23, 0x89, 0x09, 0x45, 0x72, 0x49, 0x2a, 0x89, 0x83, - 0x1e, 0x02, 0xf4, 0xd4, 0xff, 0xa0, 0x28, 0x8a, 0x1e, 0xf6, 0xb2, 0x40, 0xaf, 0x05, 0x0a, 0xb4, - 0xf7, 0x5e, 0x0b, 0xf4, 0xde, 0x43, 0x0f, 0x05, 0xda, 0x3f, 0xa3, 0x98, 0x19, 0x92, 0xa2, 0xbe, - 0x12, 0x77, 0x81, 0x64, 0x4f, 0xf6, 0xfc, 0xde, 0xef, 0xbd, 0x79, 0xf3, 0xf8, 0x66, 0xde, 0x9b, - 0x11, 0x20, 0x9d, 0x7a, 0x9a, 0x6b, 0x38, 0xbe, 0xed, 0x56, 0x1c, 0xd7, 0xf6, 0x6d, 0xbc, 0x36, - 0xb0, 0xed, 0x81, 0x49, 0xc5, 0xe8, 0x78, 0xdc, 0x2f, 0x1f, 0xc2, 0xfa, 0x43, 0xc3, 0xa4, 0xf5, - 0x88, 0xd8, 0xa5, 0x3e, 0x7e, 0x00, 0xe9, 0xbe, 0x61, 0x52, 0x29, 0xb1, 0x9d, 0xda, 0x29, 0xec, - 0x5e, 0xa9, 0xcc, 0x28, 0x55, 0xa6, 0x35, 0x3a, 0x0c, 0x56, 0xb8, 0x46, 0xf9, 0xdf, 0x69, 0xd8, - 0x58, 0x20, 0xc5, 0x18, 0xd2, 0x16, 0x19, 0x31, 0x8b, 0x89, 0x9d, 0xbc, 0xc2, 0xff, 0xc7, 0x12, - 0xac, 0x38, 0x44, 0x7b, 0x46, 0x06, 0x54, 0x4a, 0x72, 0x38, 0x1c, 0xe2, 0x8f, 0x01, 0x74, 0xea, - 0x50, 0x4b, 0xa7, 0x96, 0x76, 0x22, 0xa5, 0xb6, 0x53, 0x3b, 0x79, 0x25, 0x86, 0xe0, 0x9b, 0xb0, - 0xee, 0x8c, 0x8f, 0x4d, 0x43, 0x53, 0x63, 0x34, 0xd8, 0x4e, 0xed, 0x64, 0x14, 0x24, 0x04, 0xf5, - 0x09, 0xf9, 0x1a, 0xac, 0xbd, 0xa0, 0xe4, 0x59, 0x9c, 0x5a, 0xe0, 0xd4, 0x12, 0x83, 0x63, 0xc4, - 0x1a, 0x14, 0x47, 0xd4, 0xf3, 0xc8, 0x80, 0xaa, 0xfe, 0x89, 0x43, 0xa5, 0x34, 0x5f, 0xfd, 0xf6, - 0xdc, 0xea, 0x67, 0x57, 0x5e, 0x08, 0xb4, 0x7a, 0x27, 0x0e, 0xc5, 0x55, 0xc8, 0x53, 0x6b, 0x3c, - 0x12, 0x16, 0x32, 0x4b, 0xe2, 0x27, 0x5b, 0xe3, 0xd1, 0xac, 0x95, 0x1c, 0x53, 0x0b, 0x4c, 0xac, - 0x78, 0xd4, 0x7d, 0x6e, 0x68, 0x54, 0xca, 0x72, 0x03, 0xd7, 0xe6, 0x0c, 0x74, 0x85, 0x7c, 0xd6, - 0x46, 0xa8, 0x87, 0x6b, 0x90, 0xa7, 0x2f, 0x7d, 0x6a, 0x79, 0x86, 0x6d, 0x49, 0x2b, 0xdc, 0xc8, - 0xd5, 0x05, 0x5f, 0x91, 0x9a, 0xfa, 0xac, 0x89, 0x89, 0x1e, 0xbe, 0x07, 0x2b, 0xb6, 0xe3, 0x1b, - 0xb6, 0xe5, 0x49, 0xb9, 0xed, 0xc4, 0x4e, 0x61, 0xf7, 0xa3, 0x85, 0x89, 0xd0, 0x16, 0x1c, 0x25, - 0x24, 0xe3, 0x06, 0x20, 0xcf, 0x1e, 0xbb, 0x1a, 0x55, 0x35, 0x5b, 0xa7, 0xaa, 0x61, 0xf5, 0x6d, - 0x29, 0xcf, 0x0d, 0x5c, 0x9c, 0x5f, 0x08, 0x27, 0xd6, 0x6c, 0x9d, 0x36, 0xac, 0xbe, 0xad, 0x94, - 0xbc, 0xa9, 0x31, 0x3e, 0x03, 0x59, 0xef, 0xc4, 0xf2, 0xc9, 0x4b, 0xa9, 0xc8, 0x33, 0x24, 0x18, - 0x95, 0xff, 0x92, 0x85, 0xb5, 0xd3, 0xa4, 0xd8, 0xe7, 0x90, 0xe9, 0xb3, 0x55, 0x4a, 0xc9, 0xff, - 0x27, 0x06, 0x42, 0x67, 0x3a, 0x88, 0xd9, 0xef, 0x19, 0xc4, 0x2a, 0x14, 0x2c, 0xea, 0xf9, 0x54, - 0x17, 0x19, 0x91, 0x3a, 0x65, 0x4e, 0x81, 0x50, 0x9a, 0x4f, 0xa9, 0xf4, 0xf7, 0x4a, 0xa9, 0xc7, - 0xb0, 0x16, 0xb9, 0xa4, 0xba, 0xc4, 0x1a, 0x84, 0xb9, 0x79, 0xeb, 0x6d, 0x9e, 0x54, 0xe4, 0x50, - 0x4f, 0x61, 0x6a, 0x4a, 0x89, 0x4e, 0x8d, 0x71, 0x1d, 0xc0, 0xb6, 0xa8, 0xdd, 0x57, 0x75, 0xaa, - 0x99, 0x52, 0x6e, 0x49, 0x94, 0xda, 0x8c, 0x32, 0x17, 0x25, 0x5b, 0xa0, 0x9a, 0x89, 0x3f, 0x9b, - 0xa4, 0xda, 0xca, 0x92, 0x4c, 0x39, 0x14, 0x9b, 0x6c, 0x2e, 0xdb, 0x8e, 0xa0, 0xe4, 0x52, 0x96, - 0xf7, 0x54, 0x0f, 0x56, 0x96, 0xe7, 0x4e, 0x54, 0xde, 0xba, 0x32, 0x25, 0x50, 0x13, 0x0b, 0x5b, - 0x75, 0xe3, 0x43, 0x7c, 0x19, 0x22, 0x40, 0xe5, 0x69, 0x05, 0xfc, 0x14, 0x2a, 0x86, 0x60, 0x8b, - 0x8c, 0xe8, 0xd6, 0x2b, 0x28, 0x4d, 0x87, 0x07, 0x6f, 0x42, 0xc6, 0xf3, 0x89, 0xeb, 0xf3, 0x2c, - 0xcc, 0x28, 0x62, 0x80, 0x11, 0xa4, 0xa8, 0xa5, 0xf3, 0x53, 0x2e, 0xa3, 0xb0, 0x7f, 0xf1, 0xcf, - 0x26, 0x0b, 0x4e, 0xf1, 0x05, 0x7f, 0x32, 0xff, 0x45, 0xa7, 0x2c, 0xcf, 0xae, 0x7b, 0xeb, 0x3e, - 0xac, 0x4e, 0x2d, 0xe0, 0xb4, 0x53, 0x97, 0x7f, 0x05, 0x1f, 0x2e, 0x34, 0x8d, 0x1f, 0xc3, 0xe6, - 0xd8, 0x32, 0x2c, 0x9f, 0xba, 0x8e, 0x4b, 0x59, 0xc6, 0x8a, 0xa9, 0xa4, 0xff, 0xac, 0x2c, 0xc9, - 0xb9, 0xa3, 0x38, 0x5b, 0x58, 0x51, 0x36, 0xc6, 0xf3, 0xe0, 0x8d, 0x7c, 0xee, 0xbf, 0x2b, 0xe8, - 0xf5, 0xeb, 0xd7, 0xaf, 0x93, 0xe5, 0xdf, 0x66, 0x61, 0x73, 0xd1, 0x9e, 0x59, 0xb8, 0x7d, 0xcf, - 0x40, 0xd6, 0x1a, 0x8f, 0x8e, 0xa9, 0xcb, 0x83, 0x94, 0x51, 0x82, 0x11, 0xae, 0x42, 0xc6, 0x24, - 0xc7, 0xd4, 0x94, 0xd2, 0xdb, 0x89, 0x9d, 0xd2, 0xee, 0xcd, 0x53, 0xed, 0xca, 0x4a, 0x93, 0xa9, - 0x28, 0x42, 0x13, 0x7f, 0x01, 0xe9, 0xe0, 0x88, 0x66, 0x16, 0x6e, 0x9c, 0xce, 0x02, 0xdb, 0x4b, - 0x0a, 0xd7, 0xc3, 0xe7, 0x21, 0xcf, 0xfe, 0x8a, 0xdc, 0xc8, 0x72, 0x9f, 0x73, 0x0c, 0x60, 0x79, - 0x81, 0xb7, 0x20, 0xc7, 0xb7, 0x89, 0x4e, 0xc3, 0xd2, 0x16, 0x8d, 0x59, 0x62, 0xe9, 0xb4, 0x4f, - 0xc6, 0xa6, 0xaf, 0x3e, 0x27, 0xe6, 0x98, 0xf2, 0x84, 0xcf, 0x2b, 0xc5, 0x00, 0xfc, 0x25, 0xc3, - 0xf0, 0x45, 0x28, 0x88, 0x5d, 0x65, 0x58, 0x3a, 0x7d, 0xc9, 0x4f, 0xcf, 0x8c, 0x22, 0x36, 0x5a, - 0x83, 0x21, 0x6c, 0xfa, 0xa7, 0x9e, 0x6d, 0x85, 0xa9, 0xc9, 0xa7, 0x60, 0x00, 0x9f, 0xfe, 0xfe, - 0xec, 0xc1, 0x7d, 0x61, 0xf1, 0xf2, 0x66, 0x73, 0xaa, 0xfc, 0xe7, 0x24, 0xa4, 0xf9, 0x79, 0xb1, - 0x06, 0x85, 0xde, 0x93, 0x8e, 0xac, 0xd6, 0xdb, 0x47, 0xfb, 0x4d, 0x19, 0x25, 0x70, 0x09, 0x80, - 0x03, 0x0f, 0x9b, 0xed, 0x6a, 0x0f, 0x25, 0xa3, 0x71, 0xa3, 0xd5, 0xbb, 0x77, 0x07, 0xa5, 0x22, - 0x85, 0x23, 0x01, 0xa4, 0xe3, 0x84, 0xdb, 0xbb, 0x28, 0x83, 0x11, 0x14, 0x85, 0x81, 0xc6, 0x63, - 0xb9, 0x7e, 0xef, 0x0e, 0xca, 0x4e, 0x23, 0xb7, 0x77, 0xd1, 0x0a, 0x5e, 0x85, 0x3c, 0x47, 0xf6, - 0xdb, 0xed, 0x26, 0xca, 0x45, 0x36, 0xbb, 0x3d, 0xa5, 0xd1, 0x3a, 0x40, 0xf9, 0xc8, 0xe6, 0x81, - 0xd2, 0x3e, 0xea, 0x20, 0x88, 0x2c, 0x1c, 0xca, 0xdd, 0x6e, 0xf5, 0x40, 0x46, 0x85, 0x88, 0xb1, - 0xff, 0xa4, 0x27, 0x77, 0x51, 0x71, 0xca, 0xad, 0xdb, 0xbb, 0x68, 0x35, 0x9a, 0x42, 0x6e, 0x1d, - 0x1d, 0xa2, 0x12, 0x5e, 0x87, 0x55, 0x31, 0x45, 0xe8, 0xc4, 0xda, 0x0c, 0x74, 0xef, 0x0e, 0x42, - 0x13, 0x47, 0x84, 0x95, 0xf5, 0x29, 0xe0, 0xde, 0x1d, 0x84, 0xcb, 0x35, 0xc8, 0xf0, 0xec, 0xc2, - 0x18, 0x4a, 0xcd, 0xea, 0xbe, 0xdc, 0x54, 0xdb, 0x9d, 0x5e, 0xa3, 0xdd, 0xaa, 0x36, 0x51, 0x62, - 0x82, 0x29, 0xf2, 0x2f, 0x8e, 0x1a, 0x8a, 0x5c, 0x47, 0xc9, 0x38, 0xd6, 0x91, 0xab, 0x3d, 0xb9, - 0x8e, 0x52, 0x65, 0x0d, 0x36, 0x17, 0x9d, 0x93, 0x0b, 0x77, 0x46, 0xec, 0x13, 0x27, 0x97, 0x7c, - 0x62, 0x6e, 0x6b, 0xee, 0x13, 0x7f, 0x9b, 0x80, 0x8d, 0x05, 0xb5, 0x62, 0xe1, 0x24, 0x3f, 0x85, - 0x8c, 0x48, 0x51, 0x51, 0x3d, 0xaf, 0x2f, 0x2c, 0x3a, 0x3c, 0x61, 0xe7, 0x2a, 0x28, 0xd7, 0x8b, - 0x77, 0x10, 0xa9, 0x25, 0x1d, 0x04, 0x33, 0x31, 0xe7, 0xe4, 0xaf, 0x13, 0x20, 0x2d, 0xb3, 0xfd, - 0x96, 0x83, 0x22, 0x39, 0x75, 0x50, 0x7c, 0x3e, 0xeb, 0xc0, 0xa5, 0xe5, 0x6b, 0x98, 0xf3, 0xe2, - 0xbb, 0x04, 0x9c, 0x59, 0xdc, 0x68, 0x2d, 0xf4, 0xe1, 0x0b, 0xc8, 0x8e, 0xa8, 0x3f, 0xb4, 0xc3, - 0x66, 0xe3, 0x93, 0x05, 0x25, 0x8c, 0x89, 0x67, 0x63, 0x15, 0x68, 0xc5, 0x6b, 0x60, 0x6a, 0x59, - 0xb7, 0x24, 0xbc, 0x99, 0xf3, 0xf4, 0x37, 0x49, 0xf8, 0x70, 0xa1, 0xf1, 0x85, 0x8e, 0x5e, 0x00, - 0x30, 0x2c, 0x67, 0xec, 0x8b, 0x86, 0x42, 0x9c, 0x4f, 0x79, 0x8e, 0xf0, 0xbd, 0xcf, 0xce, 0x9e, - 0xb1, 0x1f, 0xc9, 0x53, 0x5c, 0x0e, 0x02, 0xe2, 0x84, 0x07, 0x13, 0x47, 0xd3, 0xdc, 0xd1, 0x8f, - 0x97, 0xac, 0x74, 0xae, 0x56, 0x7f, 0x0a, 0x48, 0x33, 0x0d, 0x6a, 0xf9, 0xaa, 0xe7, 0xbb, 0x94, - 0x8c, 0x0c, 0x6b, 0xc0, 0x0f, 0xe0, 0xdc, 0x5e, 0xa6, 0x4f, 0x4c, 0x8f, 0x2a, 0x6b, 0x42, 0xdc, - 0x0d, 0xa5, 0x4c, 0x83, 0xd7, 0x38, 0x37, 0xa6, 0x91, 0x9d, 0xd2, 0x10, 0xe2, 0x48, 0xa3, 0xfc, - 0xa7, 0x1c, 0x14, 0x62, 0x6d, 0x29, 0xbe, 0x04, 0xc5, 0xa7, 0xe4, 0x39, 0x51, 0xc3, 0xab, 0x86, - 0x88, 0x44, 0x81, 0x61, 0x9d, 0xe0, 0xba, 0xf1, 0x29, 0x6c, 0x72, 0x8a, 0x3d, 0xf6, 0xa9, 0xab, - 0x6a, 0x26, 0xf1, 0x3c, 0x1e, 0xb4, 0x1c, 0xa7, 0x62, 0x26, 0x6b, 0x33, 0x51, 0x2d, 0x94, 0xe0, - 0xbb, 0xb0, 0xc1, 0x35, 0x46, 0x63, 0xd3, 0x37, 0x1c, 0x93, 0xaa, 0xec, 0xf2, 0xe3, 0xf1, 0x83, - 0x38, 0xf2, 0x6c, 0x9d, 0x31, 0x0e, 0x03, 0x02, 0xf3, 0xc8, 0xc3, 0x75, 0xb8, 0xc0, 0xd5, 0x06, - 0xd4, 0xa2, 0x2e, 0xf1, 0xa9, 0x4a, 0xbf, 0x19, 0x13, 0xd3, 0x53, 0x89, 0xa5, 0xab, 0x43, 0xe2, - 0x0d, 0xa5, 0x4d, 0x66, 0x60, 0x3f, 0x29, 0x25, 0x94, 0x73, 0x8c, 0x78, 0x10, 0xf0, 0x64, 0x4e, - 0xab, 0x5a, 0xfa, 0x97, 0xc4, 0x1b, 0xe2, 0x3d, 0x38, 0xc3, 0xad, 0x78, 0xbe, 0x6b, 0x58, 0x03, - 0x55, 0x1b, 0x52, 0xed, 0x99, 0x3a, 0xf6, 0xfb, 0x0f, 0xa4, 0xf3, 0xf1, 0xf9, 0xb9, 0x87, 0x5d, - 0xce, 0xa9, 0x31, 0xca, 0x91, 0xdf, 0x7f, 0x80, 0xbb, 0x50, 0x64, 0x1f, 0x63, 0x64, 0xbc, 0xa2, - 0x6a, 0xdf, 0x76, 0x79, 0x65, 0x29, 0x2d, 0xd8, 0xd9, 0xb1, 0x08, 0x56, 0xda, 0x81, 0xc2, 0xa1, - 0xad, 0xd3, 0xbd, 0x4c, 0xb7, 0x23, 0xcb, 0x75, 0xa5, 0x10, 0x5a, 0x79, 0x68, 0xbb, 0x2c, 0xa1, - 0x06, 0x76, 0x14, 0xe0, 0x82, 0x48, 0xa8, 0x81, 0x1d, 0x86, 0xf7, 0x2e, 0x6c, 0x68, 0x9a, 0x58, - 0xb3, 0xa1, 0xa9, 0xc1, 0x15, 0xc5, 0x93, 0xd0, 0x54, 0xb0, 0x34, 0xed, 0x40, 0x10, 0x82, 0x1c, - 0xf7, 0xf0, 0x67, 0xf0, 0xe1, 0x24, 0x58, 0x71, 0xc5, 0xf5, 0xb9, 0x55, 0xce, 0xaa, 0xde, 0x85, - 0x0d, 0xe7, 0x64, 0x5e, 0x11, 0x4f, 0xcd, 0xe8, 0x9c, 0xcc, 0xaa, 0xdd, 0x87, 0x4d, 0x67, 0xe8, - 0xcc, 0xeb, 0x6d, 0xc4, 0xf5, 0xb0, 0x33, 0x74, 0x66, 0x15, 0xaf, 0xf2, 0xfb, 0xaa, 0x4b, 0x35, - 0xe2, 0x53, 0x5d, 0x3a, 0x1b, 0xa7, 0xc7, 0x04, 0xf8, 0x16, 0x20, 0x4d, 0x53, 0xa9, 0x45, 0x8e, - 0x4d, 0xaa, 0x12, 0x97, 0x5a, 0xc4, 0x93, 0x2e, 0xc6, 0xc9, 0x25, 0x4d, 0x93, 0xb9, 0xb4, 0xca, - 0x85, 0xf8, 0x06, 0xac, 0xdb, 0xc7, 0x4f, 0x35, 0x91, 0x92, 0xaa, 0xe3, 0xd2, 0xbe, 0xf1, 0x52, - 0xba, 0xc2, 0xe3, 0xbb, 0xc6, 0x04, 0x3c, 0x21, 0x3b, 0x1c, 0xc6, 0xd7, 0x01, 0x69, 0xde, 0x90, - 0xb8, 0x0e, 0xef, 0x09, 0x3c, 0x87, 0x68, 0x54, 0xba, 0x2a, 0xa8, 0x02, 0x6f, 0x85, 0x30, 0xdb, - 0x12, 0xde, 0x0b, 0xa3, 0xef, 0x87, 0x16, 0xaf, 0x89, 0x2d, 0xc1, 0xb1, 0xc0, 0xda, 0x0e, 0x20, - 0x16, 0x8a, 0xa9, 0x89, 0x77, 0x38, 0xad, 0xe4, 0x0c, 0x9d, 0xf8, 0xbc, 0x97, 0x61, 0x95, 0x31, - 0x27, 0x93, 0x5e, 0x17, 0xfd, 0x8c, 0x33, 0x8c, 0xcd, 0xf8, 0xce, 0x5a, 0xcb, 0xf2, 0x1e, 0x14, - 0xe3, 0xf9, 0x89, 0xf3, 0x20, 0x32, 0x14, 0x25, 0x58, 0xad, 0xaf, 0xb5, 0xeb, 0xac, 0x4a, 0x7f, - 0x2d, 0xa3, 0x24, 0xeb, 0x16, 0x9a, 0x8d, 0x9e, 0xac, 0x2a, 0x47, 0xad, 0x5e, 0xe3, 0x50, 0x46, - 0xa9, 0x78, 0x5b, 0xfa, 0xb7, 0x24, 0x94, 0xa6, 0x6f, 0x18, 0xf8, 0x27, 0x70, 0x36, 0x7c, 0x0e, - 0xf0, 0xa8, 0xaf, 0xbe, 0x30, 0x5c, 0xbe, 0x65, 0x46, 0x44, 0x74, 0xd8, 0xd1, 0x47, 0xdb, 0x0c, - 0x58, 0x5d, 0xea, 0x7f, 0x65, 0xb8, 0x6c, 0x43, 0x8c, 0x88, 0x8f, 0x9b, 0x70, 0xd1, 0xb2, 0x55, - 0xcf, 0x27, 0x96, 0x4e, 0x5c, 0x5d, 0x9d, 0x3c, 0xc4, 0xa8, 0x44, 0xd3, 0xa8, 0xe7, 0xd9, 0xa2, - 0x54, 0x45, 0x56, 0x3e, 0xb2, 0xec, 0x6e, 0x40, 0x9e, 0x9c, 0xe1, 0xd5, 0x80, 0x3a, 0x93, 0x60, - 0xa9, 0x65, 0x09, 0x76, 0x1e, 0xf2, 0x23, 0xe2, 0xa8, 0xd4, 0xf2, 0xdd, 0x13, 0xde, 0x57, 0xe6, - 0x94, 0xdc, 0x88, 0x38, 0x32, 0x1b, 0xbf, 0x9f, 0xf6, 0xfe, 0x9f, 0x29, 0x28, 0xc6, 0x7b, 0x4b, - 0xd6, 0xaa, 0x6b, 0xbc, 0x8e, 0x24, 0xf8, 0x49, 0x73, 0xf9, 0x8d, 0x9d, 0x68, 0xa5, 0xc6, 0x0a, - 0xcc, 0x5e, 0x56, 0x74, 0x7c, 0x8a, 0xd0, 0x64, 0xc5, 0x9d, 0x9d, 0x2d, 0x54, 0xdc, 0x62, 0x72, - 0x4a, 0x30, 0xc2, 0x07, 0x90, 0x7d, 0xea, 0x71, 0xdb, 0x59, 0x6e, 0xfb, 0xca, 0x9b, 0x6d, 0x3f, - 0xea, 0x72, 0xe3, 0xf9, 0x47, 0x5d, 0xb5, 0xd5, 0x56, 0x0e, 0xab, 0x4d, 0x25, 0x50, 0xc7, 0xe7, - 0x20, 0x6d, 0x92, 0x57, 0x27, 0xd3, 0xa5, 0x88, 0x43, 0xa7, 0x0d, 0xfc, 0x39, 0x48, 0xbf, 0xa0, - 0xe4, 0xd9, 0x74, 0x01, 0xe0, 0xd0, 0x3b, 0x4c, 0xfd, 0x5b, 0x90, 0xe1, 0xf1, 0xc2, 0x00, 0x41, - 0xc4, 0xd0, 0x07, 0x38, 0x07, 0xe9, 0x5a, 0x5b, 0x61, 0xe9, 0x8f, 0xa0, 0x28, 0x50, 0xb5, 0xd3, - 0x90, 0x6b, 0x32, 0x4a, 0x96, 0xef, 0x42, 0x56, 0x04, 0x81, 0x6d, 0x8d, 0x28, 0x0c, 0xe8, 0x83, - 0x60, 0x18, 0xd8, 0x48, 0x84, 0xd2, 0xa3, 0xc3, 0x7d, 0x59, 0x41, 0xc9, 0xf8, 0xe7, 0xf5, 0xa0, - 0x18, 0x6f, 0x2b, 0xdf, 0x4f, 0x4e, 0xfd, 0x35, 0x01, 0x85, 0x58, 0x9b, 0xc8, 0x1a, 0x14, 0x62, - 0x9a, 0xf6, 0x0b, 0x95, 0x98, 0x06, 0xf1, 0x82, 0xa4, 0x00, 0x0e, 0x55, 0x19, 0x72, 0xda, 0x8f, - 0xf6, 0x5e, 0x9c, 0xff, 0x43, 0x02, 0xd0, 0x6c, 0x8b, 0x39, 0xe3, 0x60, 0xe2, 0x07, 0x75, 0xf0, - 0xf7, 0x09, 0x28, 0x4d, 0xf7, 0x95, 0x33, 0xee, 0x5d, 0xfa, 0x41, 0xdd, 0xfb, 0x57, 0x12, 0x56, - 0xa7, 0xba, 0xc9, 0xd3, 0x7a, 0xf7, 0x0d, 0xac, 0x1b, 0x3a, 0x1d, 0x39, 0xb6, 0x4f, 0x2d, 0xed, - 0x44, 0x35, 0xe9, 0x73, 0x6a, 0x4a, 0x65, 0x7e, 0x50, 0xdc, 0x7a, 0x73, 0xbf, 0x5a, 0x69, 0x4c, - 0xf4, 0x9a, 0x4c, 0x6d, 0x6f, 0xa3, 0x51, 0x97, 0x0f, 0x3b, 0xed, 0x9e, 0xdc, 0xaa, 0x3d, 0x51, - 0x8f, 0x5a, 0x3f, 0x6f, 0xb5, 0xbf, 0x6a, 0x29, 0xc8, 0x98, 0xa1, 0xbd, 0xc3, 0xad, 0xde, 0x01, - 0x34, 0xeb, 0x14, 0x3e, 0x0b, 0x8b, 0xdc, 0x42, 0x1f, 0xe0, 0x0d, 0x58, 0x6b, 0xb5, 0xd5, 0x6e, - 0xa3, 0x2e, 0xab, 0xf2, 0xc3, 0x87, 0x72, 0xad, 0xd7, 0x15, 0x17, 0xf8, 0x88, 0xdd, 0x9b, 0xde, - 0xd4, 0xbf, 0x4b, 0xc1, 0xc6, 0x02, 0x4f, 0x70, 0x35, 0xb8, 0x3b, 0x88, 0xeb, 0xcc, 0x8f, 0x4f, - 0xe3, 0x7d, 0x85, 0x95, 0xfc, 0x0e, 0x71, 0xfd, 0xe0, 0xaa, 0x71, 0x1d, 0x58, 0x94, 0x2c, 0xdf, - 0xe8, 0x1b, 0xd4, 0x0d, 0xde, 0x3b, 0xc4, 0x85, 0x62, 0x6d, 0x82, 0x8b, 0x27, 0x8f, 0x1f, 0x01, - 0x76, 0x6c, 0xcf, 0xf0, 0x8d, 0xe7, 0x54, 0x35, 0xac, 0xf0, 0x71, 0x84, 0x5d, 0x30, 0xd2, 0x0a, - 0x0a, 0x25, 0x0d, 0xcb, 0x8f, 0xd8, 0x16, 0x1d, 0x90, 0x19, 0x36, 0x3b, 0xc0, 0x53, 0x0a, 0x0a, - 0x25, 0x11, 0xfb, 0x12, 0x14, 0x75, 0x7b, 0xcc, 0xba, 0x2e, 0xc1, 0x63, 0xf5, 0x22, 0xa1, 0x14, - 0x04, 0x16, 0x51, 0x82, 0x7e, 0x7a, 0xf2, 0x2a, 0x53, 0x54, 0x0a, 0x02, 0x13, 0x94, 0x6b, 0xb0, - 0x46, 0x06, 0x03, 0x97, 0x19, 0x0f, 0x0d, 0x89, 0x1b, 0x42, 0x29, 0x82, 0x39, 0x71, 0xeb, 0x11, - 0xe4, 0xc2, 0x38, 0xb0, 0x92, 0xcc, 0x22, 0xa1, 0x3a, 0xe2, 0x65, 0x2e, 0xb9, 0x93, 0x57, 0x72, - 0x56, 0x28, 0xbc, 0x04, 0x45, 0xc3, 0x53, 0x27, 0x8f, 0xcc, 0xc9, 0xed, 0xe4, 0x4e, 0x4e, 0x29, - 0x18, 0x5e, 0xf4, 0x40, 0x57, 0xfe, 0x2e, 0x09, 0xa5, 0xe9, 0x47, 0x72, 0x5c, 0x87, 0x9c, 0x69, - 0x6b, 0x84, 0xa7, 0x96, 0xf8, 0x85, 0x66, 0xe7, 0x2d, 0xef, 0xea, 0x95, 0x66, 0xc0, 0x57, 0x22, - 0xcd, 0xad, 0xbf, 0x27, 0x20, 0x17, 0xc2, 0xf8, 0x0c, 0xa4, 0x1d, 0xe2, 0x0f, 0xb9, 0xb9, 0xcc, - 0x7e, 0x12, 0x25, 0x14, 0x3e, 0x66, 0xb8, 0xe7, 0x10, 0x8b, 0xa7, 0x40, 0x80, 0xb3, 0x31, 0xfb, - 0xae, 0x26, 0x25, 0x3a, 0xbf, 0x7e, 0xd8, 0xa3, 0x11, 0xb5, 0x7c, 0x2f, 0xfc, 0xae, 0x01, 0x5e, - 0x0b, 0x60, 0x7c, 0x13, 0xd6, 0x7d, 0x97, 0x18, 0xe6, 0x14, 0x37, 0xcd, 0xb9, 0x28, 0x14, 0x44, - 0xe4, 0x3d, 0x38, 0x17, 0xda, 0xd5, 0xa9, 0x4f, 0xb4, 0x21, 0xd5, 0x27, 0x4a, 0x59, 0xfe, 0x02, - 0x7b, 0x36, 0x20, 0xd4, 0x03, 0x79, 0xa8, 0x5b, 0xfe, 0x47, 0x02, 0xd6, 0xc3, 0x0b, 0x93, 0x1e, - 0x05, 0xeb, 0x10, 0x80, 0x58, 0x96, 0xed, 0xc7, 0xc3, 0x35, 0x9f, 0xca, 0x73, 0x7a, 0x95, 0x6a, - 0xa4, 0xa4, 0xc4, 0x0c, 0x6c, 0x8d, 0x00, 0x26, 0x92, 0xa5, 0x61, 0xbb, 0x08, 0x85, 0xe0, 0x17, - 0x10, 0xfe, 0x33, 0x9a, 0xb8, 0x62, 0x83, 0x80, 0xd8, 0xcd, 0x0a, 0x6f, 0x42, 0xe6, 0x98, 0x0e, - 0x0c, 0x2b, 0x78, 0xd7, 0x14, 0x83, 0xf0, 0xad, 0x36, 0x1d, 0xbd, 0xd5, 0xee, 0x3f, 0x86, 0x0d, - 0xcd, 0x1e, 0xcd, 0xba, 0xbb, 0x8f, 0x66, 0xae, 0xf9, 0xde, 0x97, 0x89, 0xaf, 0x61, 0xd2, 0x62, - 0x7e, 0x9b, 0x4c, 0x1d, 0x74, 0xf6, 0xff, 0x98, 0xdc, 0x3a, 0x10, 0x7a, 0x9d, 0x70, 0x99, 0x0a, - 0xed, 0x9b, 0x54, 0x63, 0xae, 0xff, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x6b, 0x03, 0xf1, 0x99, 0x1b, - 0x1c, 0x00, 0x00, + 0x15, 0x5f, 0x7d, 0x5a, 0x7a, 0x92, 0xe5, 0xf1, 0xd8, 0x9b, 0x30, 0xde, 0x8f, 0x38, 0xda, 0x8f, + 0x38, 0x49, 0xab, 0x2c, 0x9c, 0xc4, 0xc9, 0x3a, 0xc5, 0xb6, 0xb2, 0xc4, 0x78, 0x95, 0xca, 0x92, + 0x4a, 0xc9, 0xdd, 0x64, 0x8b, 0x82, 0x18, 0x93, 0x23, 0x89, 0x09, 0x45, 0x72, 0x49, 0x2a, 0x89, + 0x83, 0x1e, 0x02, 0xf4, 0xd4, 0xff, 0xa0, 0x28, 0x8a, 0x1e, 0x7a, 0x59, 0xa0, 0xd7, 0x02, 0x05, + 0xda, 0x7b, 0xaf, 0x05, 0x7a, 0xef, 0xa1, 0x40, 0x0b, 0xb4, 0x7f, 0x42, 0x8f, 0xc5, 0xcc, 0x90, + 0x14, 0xf5, 0x95, 0x78, 0x17, 0x48, 0xf6, 0x64, 0xcf, 0xef, 0xfd, 0xde, 0xe3, 0x9b, 0x37, 0x6f, + 0xde, 0xbc, 0x19, 0x01, 0xd2, 0xa9, 0xa7, 0xb9, 0x86, 0xe3, 0xdb, 0x6e, 0xc5, 0x71, 0x6d, 0xdf, + 0xc6, 0x6b, 0x03, 0xdb, 0x1e, 0x98, 0x54, 0x8c, 0x4e, 0xc6, 0xfd, 0xf2, 0x11, 0xac, 0xdf, 0x33, + 0x4c, 0x5a, 0x8f, 0x88, 0x5d, 0xea, 0xe3, 0x3b, 0x90, 0xee, 0x1b, 0x26, 0x95, 0x12, 0xdb, 0xa9, + 0x9d, 0xc2, 0xee, 0x87, 0x95, 0x19, 0xa5, 0xca, 0xb4, 0x46, 0x87, 0xc1, 0x0a, 0xd7, 0x28, 0xff, + 0x3b, 0x0d, 0x1b, 0x0b, 0xa4, 0x18, 0x43, 0xda, 0x22, 0x23, 0x66, 0x31, 0xb1, 0x93, 0x57, 0xf8, + 0xff, 0x58, 0x82, 0x15, 0x87, 0x68, 0x8f, 0xc9, 0x80, 0x4a, 0x49, 0x0e, 0x87, 0x43, 0xfc, 0x3e, + 0x80, 0x4e, 0x1d, 0x6a, 0xe9, 0xd4, 0xd2, 0x4e, 0xa5, 0xd4, 0x76, 0x6a, 0x27, 0xaf, 0xc4, 0x10, + 0x7c, 0x0d, 0xd6, 0x9d, 0xf1, 0x89, 0x69, 0x68, 0x6a, 0x8c, 0x06, 0xdb, 0xa9, 0x9d, 0x8c, 0x82, + 0x84, 0xa0, 0x3e, 0x21, 0x5f, 0x86, 0xb5, 0xa7, 0x94, 0x3c, 0x8e, 0x53, 0x0b, 0x9c, 0x5a, 0x62, + 0x70, 0x8c, 0x58, 0x83, 0xe2, 0x88, 0x7a, 0x1e, 0x19, 0x50, 0xd5, 0x3f, 0x75, 0xa8, 0x94, 0xe6, + 0xb3, 0xdf, 0x9e, 0x9b, 0xfd, 0xec, 0xcc, 0x0b, 0x81, 0x56, 0xef, 0xd4, 0xa1, 0xb8, 0x0a, 0x79, + 0x6a, 0x8d, 0x47, 0xc2, 0x42, 0x66, 0x49, 0xfc, 0x64, 0x6b, 0x3c, 0x9a, 0xb5, 0x92, 0x63, 0x6a, + 0x81, 0x89, 0x15, 0x8f, 0xba, 0x4f, 0x0c, 0x8d, 0x4a, 0x59, 0x6e, 0xe0, 0xf2, 0x9c, 0x81, 0xae, + 0x90, 0xcf, 0xda, 0x08, 0xf5, 0x70, 0x0d, 0xf2, 0xf4, 0x99, 0x4f, 0x2d, 0xcf, 0xb0, 0x2d, 0x69, + 0x85, 0x1b, 0xf9, 0x68, 0xc1, 0x2a, 0x52, 0x53, 0x9f, 0x35, 0x31, 0xd1, 0xc3, 0x7b, 0xb0, 0x62, + 0x3b, 0xbe, 0x61, 0x5b, 0x9e, 0x94, 0xdb, 0x4e, 0xec, 0x14, 0x76, 0xdf, 0x5d, 0x98, 0x08, 0x6d, + 0xc1, 0x51, 0x42, 0x32, 0x6e, 0x00, 0xf2, 0xec, 0xb1, 0xab, 0x51, 0x55, 0xb3, 0x75, 0xaa, 0x1a, + 0x56, 0xdf, 0x96, 0xf2, 0xdc, 0xc0, 0xc5, 0xf9, 0x89, 0x70, 0x62, 0xcd, 0xd6, 0x69, 0xc3, 0xea, + 0xdb, 0x4a, 0xc9, 0x9b, 0x1a, 0xe3, 0x73, 0x90, 0xf5, 0x4e, 0x2d, 0x9f, 0x3c, 0x93, 0x8a, 0x3c, + 0x43, 0x82, 0x51, 0xf9, 0xcf, 0x59, 0x58, 0x3b, 0x4b, 0x8a, 0xdd, 0x85, 0x4c, 0x9f, 0xcd, 0x52, + 0x4a, 0x7e, 0x93, 0x18, 0x08, 0x9d, 0xe9, 0x20, 0x66, 0xbf, 0x65, 0x10, 0xab, 0x50, 0xb0, 0xa8, + 0xe7, 0x53, 0x5d, 0x64, 0x44, 0xea, 0x8c, 0x39, 0x05, 0x42, 0x69, 0x3e, 0xa5, 0xd2, 0xdf, 0x2a, + 0xa5, 0x1e, 0xc0, 0x5a, 0xe4, 0x92, 0xea, 0x12, 0x6b, 0x10, 0xe6, 0xe6, 0xf5, 0x57, 0x79, 0x52, + 0x91, 0x43, 0x3d, 0x85, 0xa9, 0x29, 0x25, 0x3a, 0x35, 0xc6, 0x75, 0x00, 0xdb, 0xa2, 0x76, 0x5f, + 0xd5, 0xa9, 0x66, 0x4a, 0xb9, 0x25, 0x51, 0x6a, 0x33, 0xca, 0x5c, 0x94, 0x6c, 0x81, 0x6a, 0x26, + 0xfe, 0x74, 0x92, 0x6a, 0x2b, 0x4b, 0x32, 0xe5, 0x48, 0x6c, 0xb2, 0xb9, 0x6c, 0x3b, 0x86, 0x92, + 0x4b, 0x59, 0xde, 0x53, 0x3d, 0x98, 0x59, 0x9e, 0x3b, 0x51, 0x79, 0xe5, 0xcc, 0x94, 0x40, 0x4d, + 0x4c, 0x6c, 0xd5, 0x8d, 0x0f, 0xf1, 0x07, 0x10, 0x01, 0x2a, 0x4f, 0x2b, 0xe0, 0x55, 0xa8, 0x18, + 0x82, 0x2d, 0x32, 0xa2, 0x5b, 0xcf, 0xa1, 0x34, 0x1d, 0x1e, 0xbc, 0x09, 0x19, 0xcf, 0x27, 0xae, + 0xcf, 0xb3, 0x30, 0xa3, 0x88, 0x01, 0x46, 0x90, 0xa2, 0x96, 0xce, 0xab, 0x5c, 0x46, 0x61, 0xff, + 0xe2, 0x1f, 0x4d, 0x26, 0x9c, 0xe2, 0x13, 0xfe, 0x78, 0x7e, 0x45, 0xa7, 0x2c, 0xcf, 0xce, 0x7b, + 0xeb, 0x36, 0xac, 0x4e, 0x4d, 0xe0, 0xac, 0x9f, 0x2e, 0xff, 0x02, 0xde, 0x5e, 0x68, 0x1a, 0x3f, + 0x80, 0xcd, 0xb1, 0x65, 0x58, 0x3e, 0x75, 0x1d, 0x97, 0xb2, 0x8c, 0x15, 0x9f, 0x92, 0xfe, 0xb3, + 0xb2, 0x24, 0xe7, 0x8e, 0xe3, 0x6c, 0x61, 0x45, 0xd9, 0x18, 0xcf, 0x83, 0x57, 0xf3, 0xb9, 0xff, + 0xae, 0xa0, 0x17, 0x2f, 0x5e, 0xbc, 0x48, 0x96, 0x7f, 0x9d, 0x85, 0xcd, 0x45, 0x7b, 0x66, 0xe1, + 0xf6, 0x3d, 0x07, 0x59, 0x6b, 0x3c, 0x3a, 0xa1, 0x2e, 0x0f, 0x52, 0x46, 0x09, 0x46, 0xb8, 0x0a, + 0x19, 0x93, 0x9c, 0x50, 0x53, 0x4a, 0x6f, 0x27, 0x76, 0x4a, 0xbb, 0xd7, 0xce, 0xb4, 0x2b, 0x2b, + 0x4d, 0xa6, 0xa2, 0x08, 0x4d, 0xfc, 0x19, 0xa4, 0x83, 0x12, 0xcd, 0x2c, 0x5c, 0x3d, 0x9b, 0x05, + 0xb6, 0x97, 0x14, 0xae, 0x87, 0xdf, 0x81, 0x3c, 0xfb, 0x2b, 0x72, 0x23, 0xcb, 0x7d, 0xce, 0x31, + 0x80, 0xe5, 0x05, 0xde, 0x82, 0x1c, 0xdf, 0x26, 0x3a, 0x0d, 0x8f, 0xb6, 0x68, 0xcc, 0x12, 0x4b, + 0xa7, 0x7d, 0x32, 0x36, 0x7d, 0xf5, 0x09, 0x31, 0xc7, 0x94, 0x27, 0x7c, 0x5e, 0x29, 0x06, 0xe0, + 0x4f, 0x19, 0x86, 0x2f, 0x42, 0x41, 0xec, 0x2a, 0xc3, 0xd2, 0xe9, 0x33, 0x5e, 0x3d, 0x33, 0x8a, + 0xd8, 0x68, 0x0d, 0x86, 0xb0, 0xcf, 0x3f, 0xf2, 0x6c, 0x2b, 0x4c, 0x4d, 0xfe, 0x09, 0x06, 0xf0, + 0xcf, 0xdf, 0x9e, 0x2d, 0xdc, 0xef, 0x2d, 0x9e, 0xde, 0x6c, 0x4e, 0x95, 0xff, 0x94, 0x84, 0x34, + 0xaf, 0x17, 0x6b, 0x50, 0xe8, 0x3d, 0xec, 0xc8, 0x6a, 0xbd, 0x7d, 0x7c, 0xd0, 0x94, 0x51, 0x02, + 0x97, 0x00, 0x38, 0x70, 0xaf, 0xd9, 0xae, 0xf6, 0x50, 0x32, 0x1a, 0x37, 0x5a, 0xbd, 0xbd, 0x9b, + 0x28, 0x15, 0x29, 0x1c, 0x0b, 0x20, 0x1d, 0x27, 0xdc, 0xd8, 0x45, 0x19, 0x8c, 0xa0, 0x28, 0x0c, + 0x34, 0x1e, 0xc8, 0xf5, 0xbd, 0x9b, 0x28, 0x3b, 0x8d, 0xdc, 0xd8, 0x45, 0x2b, 0x78, 0x15, 0xf2, + 0x1c, 0x39, 0x68, 0xb7, 0x9b, 0x28, 0x17, 0xd9, 0xec, 0xf6, 0x94, 0x46, 0xeb, 0x10, 0xe5, 0x23, + 0x9b, 0x87, 0x4a, 0xfb, 0xb8, 0x83, 0x20, 0xb2, 0x70, 0x24, 0x77, 0xbb, 0xd5, 0x43, 0x19, 0x15, + 0x22, 0xc6, 0xc1, 0xc3, 0x9e, 0xdc, 0x45, 0xc5, 0x29, 0xb7, 0x6e, 0xec, 0xa2, 0xd5, 0xe8, 0x13, + 0x72, 0xeb, 0xf8, 0x08, 0x95, 0xf0, 0x3a, 0xac, 0x8a, 0x4f, 0x84, 0x4e, 0xac, 0xcd, 0x40, 0x7b, + 0x37, 0x11, 0x9a, 0x38, 0x22, 0xac, 0xac, 0x4f, 0x01, 0x7b, 0x37, 0x11, 0x2e, 0xd7, 0x20, 0xc3, + 0xb3, 0x0b, 0x63, 0x28, 0x35, 0xab, 0x07, 0x72, 0x53, 0x6d, 0x77, 0x7a, 0x8d, 0x76, 0xab, 0xda, + 0x44, 0x89, 0x09, 0xa6, 0xc8, 0x3f, 0x39, 0x6e, 0x28, 0x72, 0x1d, 0x25, 0xe3, 0x58, 0x47, 0xae, + 0xf6, 0xe4, 0x3a, 0x4a, 0x95, 0x35, 0xd8, 0x5c, 0x54, 0x27, 0x17, 0xee, 0x8c, 0xd8, 0x12, 0x27, + 0x97, 0x2c, 0x31, 0xb7, 0x35, 0xb7, 0xc4, 0xff, 0x4a, 0xc2, 0xc6, 0x82, 0xb3, 0x62, 0xe1, 0x47, + 0x7e, 0x08, 0x19, 0x91, 0xa2, 0xe2, 0xf4, 0xbc, 0xb2, 0xf0, 0xd0, 0xe1, 0x09, 0x3b, 0x77, 0x82, + 0x72, 0xbd, 0x78, 0x07, 0x91, 0x5a, 0xd2, 0x41, 0x30, 0x13, 0x73, 0x35, 0xfd, 0xe7, 0x73, 0x35, + 0x5d, 0x1c, 0x7b, 0x7b, 0x67, 0x39, 0xf6, 0x38, 0xf6, 0xcd, 0x6a, 0x7b, 0x66, 0x41, 0x6d, 0xbf, + 0x0b, 0xeb, 0x73, 0x86, 0xce, 0x5c, 0x63, 0x7f, 0x99, 0x00, 0x69, 0x59, 0x70, 0x5e, 0x51, 0xe9, + 0x92, 0x53, 0x95, 0xee, 0xee, 0x6c, 0x04, 0x2f, 0x2d, 0x5f, 0x84, 0xb9, 0xb5, 0xfe, 0x3a, 0x01, + 0xe7, 0x16, 0x77, 0x8a, 0x0b, 0x7d, 0xf8, 0x0c, 0xb2, 0x23, 0xea, 0x0f, 0xed, 0xb0, 0x5b, 0xfa, + 0x78, 0xc1, 0x19, 0xcc, 0xc4, 0xb3, 0x8b, 0x1d, 0x68, 0xc5, 0x0f, 0xf1, 0xd4, 0xb2, 0x76, 0x4f, + 0x78, 0x33, 0xe7, 0xe9, 0xaf, 0x92, 0xf0, 0xf6, 0x42, 0xe3, 0x0b, 0x1d, 0x7d, 0x0f, 0xc0, 0xb0, + 0x9c, 0xb1, 0x2f, 0x3a, 0x22, 0x51, 0x60, 0xf3, 0x1c, 0xe1, 0xc5, 0x8b, 0x15, 0xcf, 0xb1, 0x1f, + 0xc9, 0x53, 0x5c, 0x0e, 0x02, 0xe2, 0x84, 0x3b, 0x13, 0x47, 0xd3, 0xdc, 0xd1, 0xf7, 0x97, 0xcc, + 0x74, 0x2e, 0x31, 0x3f, 0x01, 0xa4, 0x99, 0x06, 0xb5, 0x7c, 0xd5, 0xf3, 0x5d, 0x4a, 0x46, 0x86, + 0x35, 0xe0, 0x27, 0x48, 0x6e, 0x3f, 0xd3, 0x27, 0xa6, 0x47, 0x95, 0x35, 0x21, 0xee, 0x86, 0x52, + 0xa6, 0xc1, 0x13, 0xc8, 0x8d, 0x69, 0x64, 0xa7, 0x34, 0x84, 0x38, 0xd2, 0x28, 0xff, 0x31, 0x07, + 0x85, 0x58, 0x5f, 0x8d, 0x2f, 0x41, 0xf1, 0x11, 0x79, 0x42, 0xd4, 0xf0, 0xae, 0x24, 0x22, 0x51, + 0x60, 0x58, 0x27, 0xb8, 0x2f, 0x7d, 0x02, 0x9b, 0x9c, 0x62, 0x8f, 0x7d, 0xea, 0xaa, 0x9a, 0x49, + 0x3c, 0x8f, 0x07, 0x2d, 0xc7, 0xa9, 0x98, 0xc9, 0xda, 0x4c, 0x54, 0x0b, 0x25, 0xf8, 0x16, 0x6c, + 0x70, 0x8d, 0xd1, 0xd8, 0xf4, 0x0d, 0xc7, 0xa4, 0x2a, 0xbb, 0xbd, 0x79, 0xfc, 0x24, 0x89, 0x3c, + 0x5b, 0x67, 0x8c, 0xa3, 0x80, 0xc0, 0x3c, 0xf2, 0x70, 0x1d, 0xde, 0xe3, 0x6a, 0x03, 0x6a, 0x51, + 0x97, 0xf8, 0x54, 0xa5, 0x5f, 0x8d, 0x89, 0xe9, 0xa9, 0xc4, 0xd2, 0xd5, 0x21, 0xf1, 0x86, 0xd2, + 0x26, 0x33, 0x70, 0x90, 0x94, 0x12, 0xca, 0x05, 0x46, 0x3c, 0x0c, 0x78, 0x32, 0xa7, 0x55, 0x2d, + 0xfd, 0x73, 0xe2, 0x0d, 0xf1, 0x3e, 0x9c, 0xe3, 0x56, 0x3c, 0xdf, 0x35, 0xac, 0x81, 0xaa, 0x0d, + 0xa9, 0xf6, 0x58, 0x1d, 0xfb, 0xfd, 0x3b, 0xd2, 0x3b, 0xf1, 0xef, 0x73, 0x0f, 0xbb, 0x9c, 0x53, + 0x63, 0x94, 0x63, 0xbf, 0x7f, 0x07, 0x77, 0xa1, 0xc8, 0x16, 0x63, 0x64, 0x3c, 0xa7, 0x6a, 0xdf, + 0x76, 0xf9, 0xd1, 0x58, 0x5a, 0x50, 0x9a, 0x62, 0x11, 0xac, 0xb4, 0x03, 0x85, 0x23, 0x5b, 0xa7, + 0xfb, 0x99, 0x6e, 0x47, 0x96, 0xeb, 0x4a, 0x21, 0xb4, 0x72, 0xcf, 0x76, 0x59, 0x42, 0x0d, 0xec, + 0x28, 0xc0, 0x05, 0x91, 0x50, 0x03, 0x3b, 0x0c, 0xef, 0x2d, 0xd8, 0xd0, 0x34, 0x31, 0x67, 0x43, + 0x53, 0x83, 0x3b, 0x96, 0x27, 0xa1, 0xa9, 0x60, 0x69, 0xda, 0xa1, 0x20, 0x04, 0x39, 0xee, 0xe1, + 0x4f, 0xe1, 0xed, 0x49, 0xb0, 0xe2, 0x8a, 0xeb, 0x73, 0xb3, 0x9c, 0x55, 0xbd, 0x05, 0x1b, 0xce, + 0xe9, 0xbc, 0x22, 0x9e, 0xfa, 0xa2, 0x73, 0x3a, 0xab, 0x76, 0x1b, 0x36, 0x9d, 0xa1, 0x33, 0xaf, + 0x77, 0x35, 0xae, 0x87, 0x9d, 0xa1, 0x33, 0xab, 0xf8, 0x11, 0xbf, 0x70, 0xbb, 0x54, 0x23, 0x3e, + 0xd5, 0xa5, 0xf3, 0x71, 0x7a, 0x4c, 0x80, 0xaf, 0x03, 0xd2, 0x34, 0x95, 0x5a, 0xe4, 0xc4, 0xa4, + 0x2a, 0x71, 0xa9, 0x45, 0x3c, 0xe9, 0x62, 0x9c, 0x5c, 0xd2, 0x34, 0x99, 0x4b, 0xab, 0x5c, 0x88, + 0xaf, 0xc2, 0xba, 0x7d, 0xf2, 0x48, 0x13, 0x29, 0xa9, 0x3a, 0x2e, 0xed, 0x1b, 0xcf, 0xa4, 0x0f, + 0x79, 0x7c, 0xd7, 0x98, 0x80, 0x27, 0x64, 0x87, 0xc3, 0xf8, 0x0a, 0x20, 0xcd, 0x1b, 0x12, 0xd7, + 0xe1, 0x35, 0xd9, 0x73, 0x88, 0x46, 0xa5, 0x8f, 0x04, 0x55, 0xe0, 0xad, 0x10, 0x66, 0x5b, 0xc2, + 0x7b, 0x6a, 0xf4, 0xfd, 0xd0, 0xe2, 0x65, 0xb1, 0x25, 0x38, 0x16, 0x58, 0xdb, 0x01, 0xc4, 0x42, + 0x31, 0xf5, 0xe1, 0x1d, 0x4e, 0x2b, 0x39, 0x43, 0x27, 0xfe, 0xdd, 0x0f, 0x60, 0x95, 0x31, 0x27, + 0x1f, 0xbd, 0x22, 0x1a, 0x32, 0x67, 0x18, 0xfb, 0xe2, 0x6b, 0xeb, 0x8d, 0xcb, 0xfb, 0x50, 0x8c, + 0xe7, 0x27, 0xce, 0x83, 0xc8, 0x50, 0x94, 0x60, 0xcd, 0x4a, 0xad, 0x5d, 0x67, 0x6d, 0xc6, 0x97, + 0x32, 0x4a, 0xb2, 0x76, 0xa7, 0xd9, 0xe8, 0xc9, 0xaa, 0x72, 0xdc, 0xea, 0x35, 0x8e, 0x64, 0x94, + 0x8a, 0xf7, 0xd5, 0x7f, 0x4d, 0x42, 0x69, 0xfa, 0x8a, 0x84, 0x7f, 0x00, 0xe7, 0xc3, 0xf7, 0x0c, + 0x8f, 0xfa, 0xea, 0x53, 0xc3, 0xe5, 0x5b, 0x66, 0x44, 0xc4, 0xf1, 0x15, 0x2d, 0xda, 0x66, 0xc0, + 0xea, 0x52, 0xff, 0x0b, 0xc3, 0x65, 0x1b, 0x62, 0x44, 0x7c, 0xdc, 0x84, 0x8b, 0x96, 0xad, 0x7a, + 0x3e, 0xb1, 0x74, 0xe2, 0xea, 0xea, 0xe4, 0x25, 0x49, 0x25, 0x9a, 0x46, 0x3d, 0xcf, 0x16, 0x47, + 0x55, 0x64, 0xe5, 0x5d, 0xcb, 0xee, 0x06, 0xe4, 0x49, 0x0d, 0xaf, 0x06, 0xd4, 0x99, 0x04, 0x4b, + 0x2d, 0x4b, 0xb0, 0x77, 0x20, 0x3f, 0x22, 0x8e, 0x4a, 0x2d, 0xdf, 0x3d, 0xe5, 0x8d, 0x71, 0x4e, + 0xc9, 0x8d, 0x88, 0x23, 0xb3, 0xf1, 0x9b, 0xb9, 0x9f, 0xfc, 0x23, 0x05, 0xc5, 0x78, 0x73, 0xcc, + 0xee, 0x1a, 0x1a, 0x3f, 0x47, 0x12, 0xbc, 0xd2, 0x7c, 0xf0, 0xd2, 0x56, 0xba, 0x52, 0x63, 0x07, + 0xcc, 0x7e, 0x56, 0xb4, 0xac, 0x8a, 0xd0, 0x64, 0x87, 0x3b, 0xab, 0x2d, 0x54, 0xb4, 0x08, 0x39, + 0x25, 0x18, 0xe1, 0x43, 0xc8, 0x3e, 0xf2, 0xb8, 0xed, 0x2c, 0xb7, 0xfd, 0xe1, 0xcb, 0x6d, 0xdf, + 0xef, 0x72, 0xe3, 0xf9, 0xfb, 0x5d, 0xb5, 0xd5, 0x56, 0x8e, 0xaa, 0x4d, 0x25, 0x50, 0xc7, 0x17, + 0x20, 0x6d, 0x92, 0xe7, 0xa7, 0xd3, 0x47, 0x11, 0x87, 0xce, 0x1a, 0xf8, 0x0b, 0x90, 0x7e, 0x4a, + 0xc9, 0xe3, 0xe9, 0x03, 0x80, 0x43, 0xaf, 0x31, 0xf5, 0xaf, 0x43, 0x86, 0xc7, 0x0b, 0x03, 0x04, + 0x11, 0x43, 0x6f, 0xe1, 0x1c, 0xa4, 0x6b, 0x6d, 0x85, 0xa5, 0x3f, 0x82, 0xa2, 0x40, 0xd5, 0x4e, + 0x43, 0xae, 0xc9, 0x28, 0x59, 0xbe, 0x05, 0x59, 0x11, 0x04, 0xb6, 0x35, 0xa2, 0x30, 0xa0, 0xb7, + 0x82, 0x61, 0x60, 0x23, 0x11, 0x4a, 0x8f, 0x8f, 0x0e, 0x64, 0x05, 0x25, 0xe3, 0xcb, 0xeb, 0x41, + 0x31, 0xde, 0x17, 0xbf, 0x99, 0x9c, 0xfa, 0x4b, 0x02, 0x0a, 0xb1, 0x3e, 0x97, 0x35, 0x28, 0xc4, + 0x34, 0xed, 0xa7, 0x2a, 0x31, 0x0d, 0xe2, 0x05, 0x49, 0x01, 0x1c, 0xaa, 0x32, 0xe4, 0xac, 0x8b, + 0xf6, 0x46, 0x9c, 0xff, 0x5d, 0x02, 0xd0, 0x6c, 0x8b, 0x39, 0xe3, 0x60, 0xe2, 0x3b, 0x75, 0xf0, + 0xb7, 0x09, 0x28, 0x4d, 0xf7, 0x95, 0x33, 0xee, 0x5d, 0xfa, 0x4e, 0xdd, 0xfb, 0x67, 0x12, 0x56, + 0xa7, 0xba, 0xc9, 0xb3, 0x7a, 0xf7, 0x15, 0xac, 0x1b, 0x3a, 0x1d, 0x39, 0xb6, 0x4f, 0x2d, 0xed, + 0x54, 0x35, 0xe9, 0x13, 0x6a, 0x4a, 0x65, 0x5e, 0x28, 0xae, 0xbf, 0xbc, 0x5f, 0xad, 0x34, 0x26, + 0x7a, 0x4d, 0xa6, 0xb6, 0xbf, 0xd1, 0xa8, 0xcb, 0x47, 0x9d, 0x76, 0x4f, 0x6e, 0xd5, 0x1e, 0xaa, + 0xc7, 0xad, 0x1f, 0xb7, 0xda, 0x5f, 0xb4, 0x14, 0x64, 0xcc, 0xd0, 0x5e, 0xe3, 0x56, 0xef, 0x00, + 0x9a, 0x75, 0x0a, 0x9f, 0x87, 0x45, 0x6e, 0xa1, 0xb7, 0xf0, 0x06, 0xac, 0xb5, 0xda, 0x6a, 0xb7, + 0x51, 0x97, 0x55, 0xf9, 0xde, 0x3d, 0xb9, 0xd6, 0xeb, 0x8a, 0x17, 0x88, 0x88, 0xdd, 0x9b, 0xde, + 0xd4, 0xbf, 0x49, 0xc1, 0xc6, 0x02, 0x4f, 0x70, 0x35, 0xb8, 0x3b, 0x88, 0xeb, 0xcc, 0xf7, 0xcf, + 0xe2, 0x7d, 0x85, 0x1d, 0xf9, 0x1d, 0xe2, 0xfa, 0xc1, 0x55, 0xe3, 0x0a, 0xb0, 0x28, 0x59, 0xbe, + 0xd1, 0x37, 0xa8, 0x1b, 0x3c, 0xd8, 0x88, 0x0b, 0xc5, 0xda, 0x04, 0x17, 0x6f, 0x36, 0xdf, 0x03, + 0xec, 0xd8, 0x9e, 0xe1, 0x1b, 0x4f, 0xa8, 0x6a, 0x58, 0xe1, 0xeb, 0x0e, 0xbb, 0x60, 0xa4, 0x15, + 0x14, 0x4a, 0x1a, 0x96, 0x1f, 0xb1, 0x2d, 0x3a, 0x20, 0x33, 0x6c, 0x56, 0xc0, 0x53, 0x0a, 0x0a, + 0x25, 0x11, 0xfb, 0x12, 0x14, 0x75, 0x7b, 0xcc, 0xba, 0x2e, 0xc1, 0x63, 0xe7, 0x45, 0x42, 0x29, + 0x08, 0x2c, 0xa2, 0x04, 0xfd, 0xf4, 0xe4, 0x59, 0xa9, 0xa8, 0x14, 0x04, 0x26, 0x28, 0x97, 0x61, + 0x8d, 0x0c, 0x06, 0x2e, 0x33, 0x1e, 0x1a, 0x12, 0x37, 0x84, 0x52, 0x04, 0x73, 0xe2, 0xd6, 0x7d, + 0xc8, 0x85, 0x71, 0x60, 0x47, 0x32, 0x8b, 0x84, 0xea, 0x88, 0x6b, 0x6f, 0x72, 0x27, 0xaf, 0xe4, + 0xac, 0x50, 0x78, 0x09, 0x8a, 0x86, 0xa7, 0x4e, 0x5e, 0xc9, 0x93, 0xdb, 0xc9, 0x9d, 0x9c, 0x52, + 0x30, 0xbc, 0xe8, 0x85, 0xb1, 0xfc, 0x75, 0x12, 0x4a, 0xd3, 0xaf, 0xfc, 0xb8, 0x0e, 0x39, 0xd3, + 0xd6, 0x08, 0x4f, 0x2d, 0xf1, 0x13, 0xd3, 0xce, 0x2b, 0x7e, 0x18, 0xa8, 0x34, 0x03, 0xbe, 0x12, + 0x69, 0x6e, 0xfd, 0x2d, 0x01, 0xb9, 0x10, 0xc6, 0xe7, 0x20, 0xed, 0x10, 0x7f, 0xc8, 0xcd, 0x65, + 0x0e, 0x92, 0x28, 0xa1, 0xf0, 0x31, 0xc3, 0x3d, 0x87, 0x58, 0x3c, 0x05, 0x02, 0x9c, 0x8d, 0xd9, + 0xba, 0x9a, 0x94, 0xe8, 0xfc, 0xfa, 0x61, 0x8f, 0x46, 0xd4, 0xf2, 0xbd, 0x70, 0x5d, 0x03, 0xbc, + 0x16, 0xc0, 0xf8, 0x1a, 0xac, 0xfb, 0x2e, 0x31, 0xcc, 0x29, 0x6e, 0x9a, 0x73, 0x51, 0x28, 0x88, + 0xc8, 0xfb, 0x70, 0x21, 0xb4, 0xab, 0x53, 0x9f, 0x68, 0x43, 0xaa, 0x4f, 0x94, 0xb2, 0xfc, 0x99, + 0xe1, 0x7c, 0x40, 0xa8, 0x07, 0xf2, 0x50, 0xb7, 0xfc, 0xf7, 0x04, 0xac, 0x87, 0x17, 0x26, 0x3d, + 0x0a, 0xd6, 0x11, 0x00, 0xb1, 0x2c, 0xdb, 0x8f, 0x87, 0x6b, 0x3e, 0x95, 0xe7, 0xf4, 0x2a, 0xd5, + 0x48, 0x49, 0x89, 0x19, 0xd8, 0x1a, 0x01, 0x4c, 0x24, 0x4b, 0xc3, 0x76, 0x11, 0x0a, 0xc1, 0x4f, + 0x38, 0xfc, 0x77, 0x40, 0x71, 0xc5, 0x06, 0x01, 0xb1, 0x9b, 0x15, 0xde, 0x84, 0xcc, 0x09, 0x1d, + 0x18, 0x56, 0xf0, 0x30, 0x2b, 0x06, 0xe1, 0x43, 0x48, 0x3a, 0x7a, 0x08, 0x39, 0xf8, 0x19, 0x6c, + 0x68, 0xf6, 0x68, 0xd6, 0xdd, 0x03, 0x34, 0x73, 0xcd, 0xf7, 0x3e, 0x4f, 0x7c, 0x09, 0x93, 0x16, + 0xf3, 0x7f, 0x89, 0xc4, 0xef, 0x93, 0xa9, 0xc3, 0xce, 0xc1, 0x1f, 0x92, 0x5b, 0x87, 0x42, 0xb5, + 0x13, 0xce, 0x54, 0xa1, 0x7d, 0x93, 0x6a, 0xcc, 0xfb, 0xff, 0x07, 0x00, 0x00, 0xff, 0xff, 0xa3, + 0x58, 0x22, 0x30, 0xdf, 0x1c, 0x00, 0x00, } diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go index be534f0fa1..3b95a77575 100644 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go +++ b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_gostring.gen.go @@ -34,11 +34,10 @@ package descriptor import fmt "fmt" import strings "strings" -import github_com_gogo_protobuf_proto "github.com/gogo/protobuf/proto" +import proto "github.com/gogo/protobuf/proto" import sort "sort" import strconv "strconv" import reflect "reflect" -import proto "github.com/gogo/protobuf/proto" import math "math" // Reference imports to suppress errors if they are not otherwise used. @@ -270,7 +269,7 @@ func (this *EnumDescriptorProto) GoString() string { if this == nil { return "nil" } - s := make([]string, 0, 7) + s := make([]string, 0, 9) s = append(s, "&descriptor.EnumDescriptorProto{") if this.Name != nil { s = append(s, "Name: "+valueToGoStringDescriptor(this.Name, "string")+",\n") @@ -281,6 +280,30 @@ func (this *EnumDescriptorProto) GoString() string { if this.Options != nil { s = append(s, "Options: "+fmt.Sprintf("%#v", this.Options)+",\n") } + if this.ReservedRange != nil { + s = append(s, "ReservedRange: "+fmt.Sprintf("%#v", this.ReservedRange)+",\n") + } + if this.ReservedName != nil { + s = append(s, "ReservedName: "+fmt.Sprintf("%#v", this.ReservedName)+",\n") + } + if this.XXX_unrecognized != nil { + s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") + } + s = append(s, "}") + return strings.Join(s, "") +} +func (this *EnumDescriptorProto_EnumReservedRange) GoString() string { + if this == nil { + return "nil" + } + s := make([]string, 0, 6) + s = append(s, "&descriptor.EnumDescriptorProto_EnumReservedRange{") + if this.Start != nil { + s = append(s, "Start: "+valueToGoStringDescriptor(this.Start, "int32")+",\n") + } + if this.End != nil { + s = append(s, "End: "+valueToGoStringDescriptor(this.End, "int32")+",\n") + } if this.XXX_unrecognized != nil { s = append(s, "XXX_unrecognized:"+fmt.Sprintf("%#v", this.XXX_unrecognized)+",\n") } @@ -729,8 +752,8 @@ func valueToGoStringDescriptor(v interface{}, typ string) string { pv := reflect.Indirect(rv).Interface() return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) } -func extensionToGoStringDescriptor(m github_com_gogo_protobuf_proto.Message) string { - e := github_com_gogo_protobuf_proto.GetUnsafeExtensionsMap(m) +func extensionToGoStringDescriptor(m proto.Message) string { + e := proto.GetUnsafeExtensionsMap(m) if e == nil { return "nil" } diff --git a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_test.go b/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_test.go deleted file mode 100644 index d4248b4833..0000000000 --- a/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package descriptor_test - -import ( - "fmt" - "testing" - - tpb "github.com/gogo/protobuf/proto/testdata" - "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" -) - -func TestMessage(t *testing.T) { - var msg *descriptor.DescriptorProto - fd, md := descriptor.ForMessage(msg) - if pkg, want := fd.GetPackage(), "google.protobuf"; pkg != want { - t.Errorf("descriptor.ForMessage(%T).GetPackage() = %q; want %q", msg, pkg, want) - } - if name, want := md.GetName(), "DescriptorProto"; name != want { - t.Fatalf("descriptor.ForMessage(%T).GetName() = %q; want %q", msg, name, want) - } -} - -func Example_Options() { - var msg *tpb.MyMessageSet - _, md := descriptor.ForMessage(msg) - if md.GetOptions().GetMessageSetWireFormat() { - fmt.Printf("%v uses option message_set_wire_format.\n", md.GetName()) - } - - // Output: - // MyMessageSet uses option message_set_wire_format. -} diff --git a/vendor/github.com/golang/glog/glog_test.go b/vendor/github.com/golang/glog/glog_test.go deleted file mode 100644 index 0fb376e1fd..0000000000 --- a/vendor/github.com/golang/glog/glog_test.go +++ /dev/null @@ -1,415 +0,0 @@ -// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ -// -// Copyright 2013 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package glog - -import ( - "bytes" - "fmt" - stdLog "log" - "path/filepath" - "runtime" - "strconv" - "strings" - "testing" - "time" -) - -// Test that shortHostname works as advertised. -func TestShortHostname(t *testing.T) { - for hostname, expect := range map[string]string{ - "": "", - "host": "host", - "host.google.com": "host", - } { - if got := shortHostname(hostname); expect != got { - t.Errorf("shortHostname(%q): expected %q, got %q", hostname, expect, got) - } - } -} - -// flushBuffer wraps a bytes.Buffer to satisfy flushSyncWriter. -type flushBuffer struct { - bytes.Buffer -} - -func (f *flushBuffer) Flush() error { - return nil -} - -func (f *flushBuffer) Sync() error { - return nil -} - -// swap sets the log writers and returns the old array. -func (l *loggingT) swap(writers [numSeverity]flushSyncWriter) (old [numSeverity]flushSyncWriter) { - l.mu.Lock() - defer l.mu.Unlock() - old = l.file - for i, w := range writers { - logging.file[i] = w - } - return -} - -// newBuffers sets the log writers to all new byte buffers and returns the old array. -func (l *loggingT) newBuffers() [numSeverity]flushSyncWriter { - return l.swap([numSeverity]flushSyncWriter{new(flushBuffer), new(flushBuffer), new(flushBuffer), new(flushBuffer)}) -} - -// contents returns the specified log value as a string. -func contents(s severity) string { - return logging.file[s].(*flushBuffer).String() -} - -// contains reports whether the string is contained in the log. -func contains(s severity, str string, t *testing.T) bool { - return strings.Contains(contents(s), str) -} - -// setFlags configures the logging flags how the test expects them. -func setFlags() { - logging.toStderr = false -} - -// Test that Info works as advertised. -func TestInfo(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -func TestInfoDepth(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - - f := func() { InfoDepth(1, "depth-test1") } - - // The next three lines must stay together - _, _, wantLine, _ := runtime.Caller(0) - InfoDepth(0, "depth-test0") - f() - - msgs := strings.Split(strings.TrimSuffix(contents(infoLog), "\n"), "\n") - if len(msgs) != 2 { - t.Fatalf("Got %d lines, expected 2", len(msgs)) - } - - for i, m := range msgs { - if !strings.HasPrefix(m, "I") { - t.Errorf("InfoDepth[%d] has wrong character: %q", i, m) - } - w := fmt.Sprintf("depth-test%d", i) - if !strings.Contains(m, w) { - t.Errorf("InfoDepth[%d] missing %q: %q", i, w, m) - } - - // pull out the line number (between : and ]) - msg := m[strings.LastIndex(m, ":")+1:] - x := strings.Index(msg, "]") - if x < 0 { - t.Errorf("InfoDepth[%d]: missing ']': %q", i, m) - continue - } - line, err := strconv.Atoi(msg[:x]) - if err != nil { - t.Errorf("InfoDepth[%d]: bad line number: %q", i, m) - continue - } - wantLine++ - if wantLine != line { - t.Errorf("InfoDepth[%d]: got line %d, want %d", i, line, wantLine) - } - } -} - -func init() { - CopyStandardLogTo("INFO") -} - -// Test that CopyStandardLogTo panics on bad input. -func TestCopyStandardLogToPanic(t *testing.T) { - defer func() { - if s, ok := recover().(string); !ok || !strings.Contains(s, "LOG") { - t.Errorf(`CopyStandardLogTo("LOG") should have panicked: %v`, s) - } - }() - CopyStandardLogTo("LOG") -} - -// Test that using the standard log package logs to INFO. -func TestStandardLog(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - stdLog.Print("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that the header has the correct format. -func TestHeader(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - defer func(previous func() time.Time) { timeNow = previous }(timeNow) - timeNow = func() time.Time { - return time.Date(2006, 1, 2, 15, 4, 5, .067890e9, time.Local) - } - pid = 1234 - Info("test") - var line int - format := "I0102 15:04:05.067890 1234 glog_test.go:%d] test\n" - n, err := fmt.Sscanf(contents(infoLog), format, &line) - if n != 1 || err != nil { - t.Errorf("log format error: %d elements, error %s:\n%s", n, err, contents(infoLog)) - } - // Scanf treats multiple spaces as equivalent to a single space, - // so check for correct space-padding also. - want := fmt.Sprintf(format, line) - if contents(infoLog) != want { - t.Errorf("log format error: got:\n\t%q\nwant:\t%q", contents(infoLog), want) - } -} - -// Test that an Error log goes to Warning and Info. -// Even in the Info log, the source character will be E, so the data should -// all be identical. -func TestError(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Error("test") - if !contains(errorLog, "E", t) { - t.Errorf("Error has wrong character: %q", contents(errorLog)) - } - if !contains(errorLog, "test", t) { - t.Error("Error failed") - } - str := contents(errorLog) - if !contains(warningLog, str, t) { - t.Error("Warning failed") - } - if !contains(infoLog, str, t) { - t.Error("Info failed") - } -} - -// Test that a Warning log goes to Info. -// Even in the Info log, the source character will be W, so the data should -// all be identical. -func TestWarning(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - Warning("test") - if !contains(warningLog, "W", t) { - t.Errorf("Warning has wrong character: %q", contents(warningLog)) - } - if !contains(warningLog, "test", t) { - t.Error("Warning failed") - } - str := contents(warningLog) - if !contains(infoLog, str, t) { - t.Error("Info failed") - } -} - -// Test that a V log goes to Info. -func TestV(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.verbosity.Set("2") - defer logging.verbosity.Set("0") - V(2).Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that a vmodule enables a log in this file. -func TestVmoduleOn(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.vmodule.Set("glog_test=2") - defer logging.vmodule.Set("") - if !V(1) { - t.Error("V not enabled for 1") - } - if !V(2) { - t.Error("V not enabled for 2") - } - if V(3) { - t.Error("V enabled for 3") - } - V(2).Info("test") - if !contains(infoLog, "I", t) { - t.Errorf("Info has wrong character: %q", contents(infoLog)) - } - if !contains(infoLog, "test", t) { - t.Error("Info failed") - } -} - -// Test that a vmodule of another file does not enable a log in this file. -func TestVmoduleOff(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - logging.vmodule.Set("notthisfile=2") - defer logging.vmodule.Set("") - for i := 1; i <= 3; i++ { - if V(Level(i)) { - t.Errorf("V enabled for %d", i) - } - } - V(2).Info("test") - if contents(infoLog) != "" { - t.Error("V logged incorrectly") - } -} - -// vGlobs are patterns that match/don't match this file at V=2. -var vGlobs = map[string]bool{ - // Easy to test the numeric match here. - "glog_test=1": false, // If -vmodule sets V to 1, V(2) will fail. - "glog_test=2": true, - "glog_test=3": true, // If -vmodule sets V to 1, V(3) will succeed. - // These all use 2 and check the patterns. All are true. - "*=2": true, - "?l*=2": true, - "????_*=2": true, - "??[mno]?_*t=2": true, - // These all use 2 and check the patterns. All are false. - "*x=2": false, - "m*=2": false, - "??_*=2": false, - "?[abc]?_*t=2": false, -} - -// Test that vmodule globbing works as advertised. -func testVmoduleGlob(pat string, match bool, t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - defer logging.vmodule.Set("") - logging.vmodule.Set(pat) - if V(2) != Verbose(match) { - t.Errorf("incorrect match for %q: got %t expected %t", pat, V(2), match) - } -} - -// Test that a vmodule globbing works as advertised. -func TestVmoduleGlob(t *testing.T) { - for glob, match := range vGlobs { - testVmoduleGlob(glob, match, t) - } -} - -func TestRollover(t *testing.T) { - setFlags() - var err error - defer func(previous func(error)) { logExitFunc = previous }(logExitFunc) - logExitFunc = func(e error) { - err = e - } - defer func(previous uint64) { MaxSize = previous }(MaxSize) - MaxSize = 512 - - Info("x") // Be sure we have a file. - info, ok := logging.file[infoLog].(*syncBuffer) - if !ok { - t.Fatal("info wasn't created") - } - if err != nil { - t.Fatalf("info has initial error: %v", err) - } - fname0 := info.file.Name() - Info(strings.Repeat("x", int(MaxSize))) // force a rollover - if err != nil { - t.Fatalf("info has error after big write: %v", err) - } - - // Make sure the next log file gets a file name with a different - // time stamp. - // - // TODO: determine whether we need to support subsecond log - // rotation. C++ does not appear to handle this case (nor does it - // handle Daylight Savings Time properly). - time.Sleep(1 * time.Second) - - Info("x") // create a new file - if err != nil { - t.Fatalf("error after rotation: %v", err) - } - fname1 := info.file.Name() - if fname0 == fname1 { - t.Errorf("info.f.Name did not change: %v", fname0) - } - if info.nbytes >= MaxSize { - t.Errorf("file size was not reset: %d", info.nbytes) - } -} - -func TestLogBacktraceAt(t *testing.T) { - setFlags() - defer logging.swap(logging.newBuffers()) - // The peculiar style of this code simplifies line counting and maintenance of the - // tracing block below. - var infoLine string - setTraceLocation := func(file string, line int, ok bool, delta int) { - if !ok { - t.Fatal("could not get file:line") - } - _, file = filepath.Split(file) - infoLine = fmt.Sprintf("%s:%d", file, line+delta) - err := logging.traceLocation.Set(infoLine) - if err != nil { - t.Fatal("error setting log_backtrace_at: ", err) - } - } - { - // Start of tracing block. These lines know about each other's relative position. - _, file, line, ok := runtime.Caller(0) - setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. - Info("we want a stack trace here") - } - numAppearances := strings.Count(contents(infoLog), infoLine) - if numAppearances < 2 { - // Need 2 appearances, one in the log header and one in the trace: - // log_test.go:281: I0511 16:36:06.952398 02238 log_test.go:280] we want a stack trace here - // ... - // github.com/glog/glog_test.go:280 (0x41ba91) - // ... - // We could be more precise but that would require knowing the details - // of the traceback format, which may not be dependable. - t.Fatal("got no trace back; log is ", contents(infoLog)) - } -} - -func BenchmarkHeader(b *testing.B) { - for i := 0; i < b.N; i++ { - buf, _, _ := logging.header(infoLog, 0) - logging.putBuffer(buf) - } -} diff --git a/vendor/github.com/golang/groupcache/.travis.yml b/vendor/github.com/golang/groupcache/.travis.yml new file mode 100644 index 0000000000..ef6e676332 --- /dev/null +++ b/vendor/github.com/golang/groupcache/.travis.yml @@ -0,0 +1,18 @@ +language: go +go_import_path: github.com/golang/groupcache + +os: linux +dist: trusty +sudo: false + +script: + - go test ./... + +go: + - 1.9.x + - 1.10.x + - master + +cache: + directories: + - $GOPATH/pkg diff --git a/vendor/github.com/golang/groupcache/byteview_test.go b/vendor/github.com/golang/groupcache/byteview_test.go deleted file mode 100644 index a09757aa82..0000000000 --- a/vendor/github.com/golang/groupcache/byteview_test.go +++ /dev/null @@ -1,147 +0,0 @@ -/* -Copyright 2012 Google 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 groupcache - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "testing" -) - -func TestByteView(t *testing.T) { - for _, s := range []string{"", "x", "yy"} { - for _, v := range []ByteView{of([]byte(s)), of(s)} { - name := fmt.Sprintf("string %q, view %+v", s, v) - if v.Len() != len(s) { - t.Errorf("%s: Len = %d; want %d", name, v.Len(), len(s)) - } - if v.String() != s { - t.Errorf("%s: String = %q; want %q", name, v.String(), s) - } - var longDest [3]byte - if n := v.Copy(longDest[:]); n != len(s) { - t.Errorf("%s: long Copy = %d; want %d", name, n, len(s)) - } - var shortDest [1]byte - if n := v.Copy(shortDest[:]); n != min(len(s), 1) { - t.Errorf("%s: short Copy = %d; want %d", name, n, min(len(s), 1)) - } - if got, err := ioutil.ReadAll(v.Reader()); err != nil || string(got) != s { - t.Errorf("%s: Reader = %q, %v; want %q", name, got, err, s) - } - if got, err := ioutil.ReadAll(io.NewSectionReader(v, 0, int64(len(s)))); err != nil || string(got) != s { - t.Errorf("%s: SectionReader of ReaderAt = %q, %v; want %q", name, got, err, s) - } - var dest bytes.Buffer - if _, err := v.WriteTo(&dest); err != nil || !bytes.Equal(dest.Bytes(), []byte(s)) { - t.Errorf("%s: WriteTo = %q, %v; want %q", name, dest.Bytes(), err, s) - } - } - } -} - -// of returns a byte view of the []byte or string in x. -func of(x interface{}) ByteView { - if bytes, ok := x.([]byte); ok { - return ByteView{b: bytes} - } - return ByteView{s: x.(string)} -} - -func TestByteViewEqual(t *testing.T) { - tests := []struct { - a interface{} // string or []byte - b interface{} // string or []byte - want bool - }{ - {"x", "x", true}, - {"x", "y", false}, - {"x", "yy", false}, - {[]byte("x"), []byte("x"), true}, - {[]byte("x"), []byte("y"), false}, - {[]byte("x"), []byte("yy"), false}, - {[]byte("x"), "x", true}, - {[]byte("x"), "y", false}, - {[]byte("x"), "yy", false}, - {"x", []byte("x"), true}, - {"x", []byte("y"), false}, - {"x", []byte("yy"), false}, - } - for i, tt := range tests { - va := of(tt.a) - if bytes, ok := tt.b.([]byte); ok { - if got := va.EqualBytes(bytes); got != tt.want { - t.Errorf("%d. EqualBytes = %v; want %v", i, got, tt.want) - } - } else { - if got := va.EqualString(tt.b.(string)); got != tt.want { - t.Errorf("%d. EqualString = %v; want %v", i, got, tt.want) - } - } - if got := va.Equal(of(tt.b)); got != tt.want { - t.Errorf("%d. Equal = %v; want %v", i, got, tt.want) - } - } -} - -func TestByteViewSlice(t *testing.T) { - tests := []struct { - in string - from int - to interface{} // nil to mean the end (SliceFrom); else int - want string - }{ - { - in: "abc", - from: 1, - to: 2, - want: "b", - }, - { - in: "abc", - from: 1, - want: "bc", - }, - { - in: "abc", - to: 2, - want: "ab", - }, - } - for i, tt := range tests { - for _, v := range []ByteView{of([]byte(tt.in)), of(tt.in)} { - name := fmt.Sprintf("test %d, view %+v", i, v) - if tt.to != nil { - v = v.Slice(tt.from, tt.to.(int)) - } else { - v = v.SliceFrom(tt.from) - } - if v.String() != tt.want { - t.Errorf("%s: got %q; want %q", name, v.String(), tt.want) - } - } - } -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} diff --git a/vendor/github.com/golang/groupcache/groupcache_test.go b/vendor/github.com/golang/groupcache/groupcache_test.go deleted file mode 100644 index ea05cac4aa..0000000000 --- a/vendor/github.com/golang/groupcache/groupcache_test.go +++ /dev/null @@ -1,456 +0,0 @@ -/* -Copyright 2012 Google 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. -*/ - -// Tests for groupcache. - -package groupcache - -import ( - "errors" - "fmt" - "hash/crc32" - "math/rand" - "reflect" - "sync" - "testing" - "time" - "unsafe" - - "github.com/golang/protobuf/proto" - - pb "github.com/golang/groupcache/groupcachepb" - testpb "github.com/golang/groupcache/testpb" -) - -var ( - once sync.Once - stringGroup, protoGroup Getter - - stringc = make(chan string) - - dummyCtx Context - - // cacheFills is the number of times stringGroup or - // protoGroup's Getter have been called. Read using the - // cacheFills function. - cacheFills AtomicInt -) - -const ( - stringGroupName = "string-group" - protoGroupName = "proto-group" - testMessageType = "google3/net/groupcache/go/test_proto.TestMessage" - fromChan = "from-chan" - cacheSize = 1 << 20 -) - -func testSetup() { - stringGroup = NewGroup(stringGroupName, cacheSize, GetterFunc(func(_ Context, key string, dest Sink) error { - if key == fromChan { - key = <-stringc - } - cacheFills.Add(1) - return dest.SetString("ECHO:" + key) - })) - - protoGroup = NewGroup(protoGroupName, cacheSize, GetterFunc(func(_ Context, key string, dest Sink) error { - if key == fromChan { - key = <-stringc - } - cacheFills.Add(1) - return dest.SetProto(&testpb.TestMessage{ - Name: proto.String("ECHO:" + key), - City: proto.String("SOME-CITY"), - }) - })) -} - -// tests that a Getter's Get method is only called once with two -// outstanding callers. This is the string variant. -func TestGetDupSuppressString(t *testing.T) { - once.Do(testSetup) - // Start two getters. The first should block (waiting reading - // from stringc) and the second should latch on to the first - // one. - resc := make(chan string, 2) - for i := 0; i < 2; i++ { - go func() { - var s string - if err := stringGroup.Get(dummyCtx, fromChan, StringSink(&s)); err != nil { - resc <- "ERROR:" + err.Error() - return - } - resc <- s - }() - } - - // Wait a bit so both goroutines get merged together via - // singleflight. - // TODO(bradfitz): decide whether there are any non-offensive - // debug/test hooks that could be added to singleflight to - // make a sleep here unnecessary. - time.Sleep(250 * time.Millisecond) - - // Unblock the first getter, which should unblock the second - // as well. - stringc <- "foo" - - for i := 0; i < 2; i++ { - select { - case v := <-resc: - if v != "ECHO:foo" { - t.Errorf("got %q; want %q", v, "ECHO:foo") - } - case <-time.After(5 * time.Second): - t.Errorf("timeout waiting on getter #%d of 2", i+1) - } - } -} - -// tests that a Getter's Get method is only called once with two -// outstanding callers. This is the proto variant. -func TestGetDupSuppressProto(t *testing.T) { - once.Do(testSetup) - // Start two getters. The first should block (waiting reading - // from stringc) and the second should latch on to the first - // one. - resc := make(chan *testpb.TestMessage, 2) - for i := 0; i < 2; i++ { - go func() { - tm := new(testpb.TestMessage) - if err := protoGroup.Get(dummyCtx, fromChan, ProtoSink(tm)); err != nil { - tm.Name = proto.String("ERROR:" + err.Error()) - } - resc <- tm - }() - } - - // Wait a bit so both goroutines get merged together via - // singleflight. - // TODO(bradfitz): decide whether there are any non-offensive - // debug/test hooks that could be added to singleflight to - // make a sleep here unnecessary. - time.Sleep(250 * time.Millisecond) - - // Unblock the first getter, which should unblock the second - // as well. - stringc <- "Fluffy" - want := &testpb.TestMessage{ - Name: proto.String("ECHO:Fluffy"), - City: proto.String("SOME-CITY"), - } - for i := 0; i < 2; i++ { - select { - case v := <-resc: - if !reflect.DeepEqual(v, want) { - t.Errorf(" Got: %v\nWant: %v", proto.CompactTextString(v), proto.CompactTextString(want)) - } - case <-time.After(5 * time.Second): - t.Errorf("timeout waiting on getter #%d of 2", i+1) - } - } -} - -func countFills(f func()) int64 { - fills0 := cacheFills.Get() - f() - return cacheFills.Get() - fills0 -} - -func TestCaching(t *testing.T) { - once.Do(testSetup) - fills := countFills(func() { - for i := 0; i < 10; i++ { - var s string - if err := stringGroup.Get(dummyCtx, "TestCaching-key", StringSink(&s)); err != nil { - t.Fatal(err) - } - } - }) - if fills != 1 { - t.Errorf("expected 1 cache fill; got %d", fills) - } -} - -func TestCacheEviction(t *testing.T) { - once.Do(testSetup) - testKey := "TestCacheEviction-key" - getTestKey := func() { - var res string - for i := 0; i < 10; i++ { - if err := stringGroup.Get(dummyCtx, testKey, StringSink(&res)); err != nil { - t.Fatal(err) - } - } - } - fills := countFills(getTestKey) - if fills != 1 { - t.Fatalf("expected 1 cache fill; got %d", fills) - } - - g := stringGroup.(*Group) - evict0 := g.mainCache.nevict - - // Trash the cache with other keys. - var bytesFlooded int64 - // cacheSize/len(testKey) is approximate - for bytesFlooded < cacheSize+1024 { - var res string - key := fmt.Sprintf("dummy-key-%d", bytesFlooded) - stringGroup.Get(dummyCtx, key, StringSink(&res)) - bytesFlooded += int64(len(key) + len(res)) - } - evicts := g.mainCache.nevict - evict0 - if evicts <= 0 { - t.Errorf("evicts = %v; want more than 0", evicts) - } - - // Test that the key is gone. - fills = countFills(getTestKey) - if fills != 1 { - t.Fatalf("expected 1 cache fill after cache trashing; got %d", fills) - } -} - -type fakePeer struct { - hits int - fail bool -} - -func (p *fakePeer) Get(_ Context, in *pb.GetRequest, out *pb.GetResponse) error { - p.hits++ - if p.fail { - return errors.New("simulated error from peer") - } - out.Value = []byte("got:" + in.GetKey()) - return nil -} - -type fakePeers []ProtoGetter - -func (p fakePeers) PickPeer(key string) (peer ProtoGetter, ok bool) { - if len(p) == 0 { - return - } - n := crc32.Checksum([]byte(key), crc32.IEEETable) % uint32(len(p)) - return p[n], p[n] != nil -} - -// tests that peers (virtual, in-process) are hit, and how much. -func TestPeers(t *testing.T) { - once.Do(testSetup) - rand.Seed(123) - peer0 := &fakePeer{} - peer1 := &fakePeer{} - peer2 := &fakePeer{} - peerList := fakePeers([]ProtoGetter{peer0, peer1, peer2, nil}) - const cacheSize = 0 // disabled - localHits := 0 - getter := func(_ Context, key string, dest Sink) error { - localHits++ - return dest.SetString("got:" + key) - } - testGroup := newGroup("TestPeers-group", cacheSize, GetterFunc(getter), peerList) - run := func(name string, n int, wantSummary string) { - // Reset counters - localHits = 0 - for _, p := range []*fakePeer{peer0, peer1, peer2} { - p.hits = 0 - } - - for i := 0; i < n; i++ { - key := fmt.Sprintf("key-%d", i) - want := "got:" + key - var got string - err := testGroup.Get(dummyCtx, key, StringSink(&got)) - if err != nil { - t.Errorf("%s: error on key %q: %v", name, key, err) - continue - } - if got != want { - t.Errorf("%s: for key %q, got %q; want %q", name, key, got, want) - } - } - summary := func() string { - return fmt.Sprintf("localHits = %d, peers = %d %d %d", localHits, peer0.hits, peer1.hits, peer2.hits) - } - if got := summary(); got != wantSummary { - t.Errorf("%s: got %q; want %q", name, got, wantSummary) - } - } - resetCacheSize := func(maxBytes int64) { - g := testGroup - g.cacheBytes = maxBytes - g.mainCache = cache{} - g.hotCache = cache{} - } - - // Base case; peers all up, with no problems. - resetCacheSize(1 << 20) - run("base", 200, "localHits = 49, peers = 51 49 51") - - // Verify cache was hit. All localHits are gone, and some of - // the peer hits (the ones randomly selected to be maybe hot) - run("cached_base", 200, "localHits = 0, peers = 49 47 48") - resetCacheSize(0) - - // With one of the peers being down. - // TODO(bradfitz): on a peer number being unavailable, the - // consistent hashing should maybe keep trying others to - // spread the load out. Currently it fails back to local - // execution if the first consistent-hash slot is unavailable. - peerList[0] = nil - run("one_peer_down", 200, "localHits = 100, peers = 0 49 51") - - // Failing peer - peerList[0] = peer0 - peer0.fail = true - run("peer0_failing", 200, "localHits = 100, peers = 51 49 51") -} - -func TestTruncatingByteSliceTarget(t *testing.T) { - var buf [100]byte - s := buf[:] - if err := stringGroup.Get(dummyCtx, "short", TruncatingByteSliceSink(&s)); err != nil { - t.Fatal(err) - } - if want := "ECHO:short"; string(s) != want { - t.Errorf("short key got %q; want %q", s, want) - } - - s = buf[:6] - if err := stringGroup.Get(dummyCtx, "truncated", TruncatingByteSliceSink(&s)); err != nil { - t.Fatal(err) - } - if want := "ECHO:t"; string(s) != want { - t.Errorf("truncated key got %q; want %q", s, want) - } -} - -func TestAllocatingByteSliceTarget(t *testing.T) { - var dst []byte - sink := AllocatingByteSliceSink(&dst) - - inBytes := []byte("some bytes") - sink.SetBytes(inBytes) - if want := "some bytes"; string(dst) != want { - t.Errorf("SetBytes resulted in %q; want %q", dst, want) - } - v, err := sink.view() - if err != nil { - t.Fatalf("view after SetBytes failed: %v", err) - } - if &inBytes[0] == &dst[0] { - t.Error("inBytes and dst share memory") - } - if &inBytes[0] == &v.b[0] { - t.Error("inBytes and view share memory") - } - if &dst[0] == &v.b[0] { - t.Error("dst and view share memory") - } -} - -// orderedFlightGroup allows the caller to force the schedule of when -// orig.Do will be called. This is useful to serialize calls such -// that singleflight cannot dedup them. -type orderedFlightGroup struct { - mu sync.Mutex - stage1 chan bool - stage2 chan bool - orig flightGroup -} - -func (g *orderedFlightGroup) Do(key string, fn func() (interface{}, error)) (interface{}, error) { - <-g.stage1 - <-g.stage2 - g.mu.Lock() - defer g.mu.Unlock() - return g.orig.Do(key, fn) -} - -// TestNoDedup tests invariants on the cache size when singleflight is -// unable to dedup calls. -func TestNoDedup(t *testing.T) { - const testkey = "testkey" - const testval = "testval" - g := newGroup("testgroup", 1024, GetterFunc(func(_ Context, key string, dest Sink) error { - return dest.SetString(testval) - }), nil) - - orderedGroup := &orderedFlightGroup{ - stage1: make(chan bool), - stage2: make(chan bool), - orig: g.loadGroup, - } - // Replace loadGroup with our wrapper so we can control when - // loadGroup.Do is entered for each concurrent request. - g.loadGroup = orderedGroup - - // Issue two idential requests concurrently. Since the cache is - // empty, it will miss. Both will enter load(), but we will only - // allow one at a time to enter singleflight.Do, so the callback - // function will be called twice. - resc := make(chan string, 2) - for i := 0; i < 2; i++ { - go func() { - var s string - if err := g.Get(dummyCtx, testkey, StringSink(&s)); err != nil { - resc <- "ERROR:" + err.Error() - return - } - resc <- s - }() - } - - // Ensure both goroutines have entered the Do routine. This implies - // both concurrent requests have checked the cache, found it empty, - // and called load(). - orderedGroup.stage1 <- true - orderedGroup.stage1 <- true - orderedGroup.stage2 <- true - orderedGroup.stage2 <- true - - for i := 0; i < 2; i++ { - if s := <-resc; s != testval { - t.Errorf("result is %s want %s", s, testval) - } - } - - const wantItems = 1 - if g.mainCache.items() != wantItems { - t.Errorf("mainCache has %d items, want %d", g.mainCache.items(), wantItems) - } - - // If the singleflight callback doesn't double-check the cache again - // upon entry, we would increment nbytes twice but the entry would - // only be in the cache once. - const wantBytes = int64(len(testkey) + len(testval)) - if g.mainCache.nbytes != wantBytes { - t.Errorf("cache has %d bytes, want %d", g.mainCache.nbytes, wantBytes) - } -} - -func TestGroupStatsAlignment(t *testing.T) { - var g Group - off := unsafe.Offsetof(g.Stats) - if off%8 != 0 { - t.Fatal("Stats structure is not 8-byte aligned.") - } -} - -// TODO(bradfitz): port the Google-internal full integration test into here, -// using HTTP requests instead of our RPC system. diff --git a/vendor/github.com/golang/groupcache/http_test.go b/vendor/github.com/golang/groupcache/http_test.go deleted file mode 100644 index b42edd7f09..0000000000 --- a/vendor/github.com/golang/groupcache/http_test.go +++ /dev/null @@ -1,166 +0,0 @@ -/* -Copyright 2013 Google 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 groupcache - -import ( - "errors" - "flag" - "log" - "net" - "net/http" - "os" - "os/exec" - "strconv" - "strings" - "sync" - "testing" - "time" -) - -var ( - peerAddrs = flag.String("test_peer_addrs", "", "Comma-separated list of peer addresses; used by TestHTTPPool") - peerIndex = flag.Int("test_peer_index", -1, "Index of which peer this child is; used by TestHTTPPool") - peerChild = flag.Bool("test_peer_child", false, "True if running as a child process; used by TestHTTPPool") -) - -func TestHTTPPool(t *testing.T) { - if *peerChild { - beChildForTestHTTPPool() - os.Exit(0) - } - - const ( - nChild = 4 - nGets = 100 - ) - - var childAddr []string - for i := 0; i < nChild; i++ { - childAddr = append(childAddr, pickFreeAddr(t)) - } - - var cmds []*exec.Cmd - var wg sync.WaitGroup - for i := 0; i < nChild; i++ { - cmd := exec.Command(os.Args[0], - "--test.run=TestHTTPPool", - "--test_peer_child", - "--test_peer_addrs="+strings.Join(childAddr, ","), - "--test_peer_index="+strconv.Itoa(i), - ) - cmds = append(cmds, cmd) - wg.Add(1) - if err := cmd.Start(); err != nil { - t.Fatal("failed to start child process: ", err) - } - go awaitAddrReady(t, childAddr[i], &wg) - } - defer func() { - for i := 0; i < nChild; i++ { - if cmds[i].Process != nil { - cmds[i].Process.Kill() - } - } - }() - wg.Wait() - - // Use a dummy self address so that we don't handle gets in-process. - p := NewHTTPPool("should-be-ignored") - p.Set(addrToURL(childAddr)...) - - // Dummy getter function. Gets should go to children only. - // The only time this process will handle a get is when the - // children can't be contacted for some reason. - getter := GetterFunc(func(ctx Context, key string, dest Sink) error { - return errors.New("parent getter called; something's wrong") - }) - g := NewGroup("httpPoolTest", 1<<20, getter) - - for _, key := range testKeys(nGets) { - var value string - if err := g.Get(nil, key, StringSink(&value)); err != nil { - t.Fatal(err) - } - if suffix := ":" + key; !strings.HasSuffix(value, suffix) { - t.Errorf("Get(%q) = %q, want value ending in %q", key, value, suffix) - } - t.Logf("Get key=%q, value=%q (peer:key)", key, value) - } -} - -func testKeys(n int) (keys []string) { - keys = make([]string, n) - for i := range keys { - keys[i] = strconv.Itoa(i) - } - return -} - -func beChildForTestHTTPPool() { - addrs := strings.Split(*peerAddrs, ",") - - p := NewHTTPPool("http://" + addrs[*peerIndex]) - p.Set(addrToURL(addrs)...) - - getter := GetterFunc(func(ctx Context, key string, dest Sink) error { - dest.SetString(strconv.Itoa(*peerIndex) + ":" + key) - return nil - }) - NewGroup("httpPoolTest", 1<<20, getter) - - log.Fatal(http.ListenAndServe(addrs[*peerIndex], p)) -} - -// This is racy. Another process could swoop in and steal the port between the -// call to this function and the next listen call. Should be okay though. -// The proper way would be to pass the l.File() as ExtraFiles to the child -// process, and then close your copy once the child starts. -func pickFreeAddr(t *testing.T) string { - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - defer l.Close() - return l.Addr().String() -} - -func addrToURL(addr []string) []string { - url := make([]string, len(addr)) - for i := range addr { - url[i] = "http://" + addr[i] - } - return url -} - -func awaitAddrReady(t *testing.T, addr string, wg *sync.WaitGroup) { - defer wg.Done() - const max = 1 * time.Second - tries := 0 - for { - tries++ - c, err := net.Dial("tcp", addr) - if err == nil { - c.Close() - return - } - delay := time.Duration(tries) * 25 * time.Millisecond - if delay > max { - delay = max - } - time.Sleep(delay) - } -} diff --git a/vendor/github.com/golang/groupcache/lru/lru_test.go b/vendor/github.com/golang/groupcache/lru/lru_test.go deleted file mode 100644 index b7d9d8acf4..0000000000 --- a/vendor/github.com/golang/groupcache/lru/lru_test.go +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright 2013 Google 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 lru - -import ( - "fmt" - "testing" -) - -type simpleStruct struct { - int - string -} - -type complexStruct struct { - int - simpleStruct -} - -var getTests = []struct { - name string - keyToAdd interface{} - keyToGet interface{} - expectedOk bool -}{ - {"string_hit", "myKey", "myKey", true}, - {"string_miss", "myKey", "nonsense", false}, - {"simple_struct_hit", simpleStruct{1, "two"}, simpleStruct{1, "two"}, true}, - {"simeple_struct_miss", simpleStruct{1, "two"}, simpleStruct{0, "noway"}, false}, - {"complex_struct_hit", complexStruct{1, simpleStruct{2, "three"}}, - complexStruct{1, simpleStruct{2, "three"}}, true}, -} - -func TestGet(t *testing.T) { - for _, tt := range getTests { - lru := New(0) - lru.Add(tt.keyToAdd, 1234) - val, ok := lru.Get(tt.keyToGet) - if ok != tt.expectedOk { - t.Fatalf("%s: cache hit = %v; want %v", tt.name, ok, !ok) - } else if ok && val != 1234 { - t.Fatalf("%s expected get to return 1234 but got %v", tt.name, val) - } - } -} - -func TestRemove(t *testing.T) { - lru := New(0) - lru.Add("myKey", 1234) - if val, ok := lru.Get("myKey"); !ok { - t.Fatal("TestRemove returned no match") - } else if val != 1234 { - t.Fatalf("TestRemove failed. Expected %d, got %v", 1234, val) - } - - lru.Remove("myKey") - if _, ok := lru.Get("myKey"); ok { - t.Fatal("TestRemove returned a removed entry") - } -} - -func TestEvict(t *testing.T) { - evictedKeys := make([]Key, 0) - onEvictedFun := func(key Key, value interface{}) { - evictedKeys = append(evictedKeys, key) - } - - lru := New(20) - lru.OnEvicted = onEvictedFun - for i := 0; i < 22; i++ { - lru.Add(fmt.Sprintf("myKey%d", i), 1234) - } - - if len(evictedKeys) != 2 { - t.Fatalf("got %d evicted keys; want 2", len(evictedKeys)) - } - if evictedKeys[0] != Key("myKey0") { - t.Fatalf("got %v in first evicted key; want %s", evictedKeys[0], "myKey0") - } - if evictedKeys[1] != Key("myKey1") { - t.Fatalf("got %v in second evicted key; want %s", evictedKeys[1], "myKey1") - } -} diff --git a/vendor/github.com/golang/groupcache/sinks.go b/vendor/github.com/golang/groupcache/sinks.go index cb42b41b4d..6c0b8be5cc 100644 --- a/vendor/github.com/golang/groupcache/sinks.go +++ b/vendor/github.com/golang/groupcache/sinks.go @@ -159,7 +159,7 @@ func ProtoSink(m proto.Message) Sink { } type protoSink struct { - dst proto.Message // authorative value + dst proto.Message // authoritative value typ string v ByteView // encoded diff --git a/vendor/github.com/golang/protobuf/.gitignore b/vendor/github.com/golang/protobuf/.gitignore index 8f5b596b14..c7dd40587c 100644 --- a/vendor/github.com/golang/protobuf/.gitignore +++ b/vendor/github.com/golang/protobuf/.gitignore @@ -12,5 +12,6 @@ core _obj _test _testmain.go -protoc-gen-go/testdata/multi/*.pb.go -_conformance/_conformance + +# Conformance test output and transient files. +conformance/failing_tests.txt diff --git a/vendor/github.com/golang/protobuf/.travis.yml b/vendor/github.com/golang/protobuf/.travis.yml index 93c67805b9..455fa660c8 100644 --- a/vendor/github.com/golang/protobuf/.travis.yml +++ b/vendor/github.com/golang/protobuf/.travis.yml @@ -2,17 +2,29 @@ sudo: false language: go go: - 1.6.x -- 1.7.x -- 1.8.x -- 1.9.x +- 1.10.x +- 1.x install: - go get -v -d -t github.com/golang/protobuf/... - - curl -L https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip -o /tmp/protoc.zip - - unzip /tmp/protoc.zip -d $HOME/protoc + - curl -L https://github.com/google/protobuf/releases/download/v3.5.1/protoc-3.5.1-linux-x86_64.zip -o /tmp/protoc.zip + - unzip /tmp/protoc.zip -d "$HOME"/protoc + - mkdir -p "$HOME"/src && ln -s "$HOME"/protoc "$HOME"/src/protobuf env: - PATH=$HOME/protoc/bin:$PATH script: - - make all test + - make all + - make regenerate + # TODO(tamird): When https://github.com/travis-ci/gimme/pull/130 is + # released, make this look for "1.x". + - if [[ "$TRAVIS_GO_VERSION" == 1.10* ]]; then + if [[ "$(git status --porcelain 2>&1)" != "" ]]; then + git status >&2; + git diff -a >&2; + exit 1; + fi; + echo "git status is clean."; + fi; + - make test diff --git a/vendor/github.com/golang/protobuf/Make.protobuf b/vendor/github.com/golang/protobuf/Make.protobuf deleted file mode 100644 index 15071de101..0000000000 --- a/vendor/github.com/golang/protobuf/Make.protobuf +++ /dev/null @@ -1,40 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# 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. - -# Includable Makefile to add a rule for generating .pb.go files from .proto files -# (Google protocol buffer descriptions). -# Typical use if myproto.proto is a file in package mypackage in this directory: -# -# include $(GOROOT)/src/pkg/github.com/golang/protobuf/Make.protobuf - -%.pb.go: %.proto - protoc --go_out=. $< - diff --git a/vendor/github.com/golang/protobuf/Makefile b/vendor/github.com/golang/protobuf/Makefile index a1421d8b73..2bc2621aaf 100644 --- a/vendor/github.com/golang/protobuf/Makefile +++ b/vendor/github.com/golang/protobuf/Makefile @@ -29,16 +29,14 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - all: install install: - go install ./proto ./jsonpb ./ptypes - go install ./protoc-gen-go + go install ./proto ./jsonpb ./ptypes ./protoc-gen-go test: - go test ./proto ./jsonpb ./ptypes - make -C protoc-gen-go/testdata test + go test ./... ./protoc-gen-go/testdata + make -C conformance test clean: go clean ./... @@ -47,9 +45,4 @@ nuke: go clean -i ./... regenerate: - make -C protoc-gen-go/descriptor regenerate - make -C protoc-gen-go/plugin regenerate - make -C protoc-gen-go/testdata regenerate - make -C proto/testdata regenerate - make -C jsonpb/jsonpb_test_proto regenerate - make -C _conformance regenerate + ./regenerate.sh diff --git a/vendor/github.com/golang/protobuf/README.md b/vendor/github.com/golang/protobuf/README.md index 9c4c815c02..01b29daf26 100644 --- a/vendor/github.com/golang/protobuf/README.md +++ b/vendor/github.com/golang/protobuf/README.md @@ -7,7 +7,7 @@ Google's data interchange format. Copyright 2010 The Go Authors. https://github.com/golang/protobuf -This package and the code it generates requires at least Go 1.4. +This package and the code it generates requires at least Go 1.6. This software implements Go bindings for protocol buffers. For information about protocol buffers themselves, see @@ -56,13 +56,49 @@ parameter set to the directory you want to output the Go code to. The generated files will be suffixed .pb.go. See the Test code below for an example using such a file. +## Packages and input paths ## + +The protocol buffer language has a concept of "packages" which does not +correspond well to the Go notion of packages. In generated Go code, +each source `.proto` file is associated with a single Go package. The +name and import path for this package is specified with the `go_package` +proto option: + + option go_package = "github.com/golang/protobuf/ptypes/any"; + +The protocol buffer compiler will attempt to derive a package name and +import path if a `go_package` option is not present, but it is +best to always specify one explicitly. + +There is a one-to-one relationship between source `.proto` files and +generated `.pb.go` files, but any number of `.pb.go` files may be +contained in the same Go package. + +The output name of a generated file is produced by replacing the +`.proto` suffix with `.pb.go` (e.g., `foo.proto` produces `foo.pb.go`). +However, the output directory is selected in one of two ways. Let +us say we have `inputs/x.proto` with a `go_package` option of +`github.com/golang/protobuf/p`. The corresponding output file may +be: + +- Relative to the import path: + + protoc --go_out=. inputs/x.proto + # writes ./github.com/golang/protobuf/p/x.pb.go + + (This can work well with `--go_out=$GOPATH`.) + +- Relative to the input file: + + protoc --go_out=paths=source_relative:. inputs/x.proto + # generate ./inputs/x.pb.go + +## Generated code ## The package comment for the proto library contains text describing the interface provided in Go for protocol buffers. Here is an edited version. -========== - The proto package converts data structures to and from the wire format of protocol buffers. It works in concert with the Go source code generated for .proto files by the protocol compiler. @@ -114,9 +150,9 @@ Consider file test.proto, containing ```proto syntax = "proto2"; package example; - + enum FOO { X = 17; }; - + message Test { required string label = 1; optional int32 type = 2 [default=77]; @@ -170,22 +206,25 @@ To create and play with a Test object from the example package, To pass extra parameters to the plugin, use a comma-separated parameter list separated from the output directory by a colon: - protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto - -- `import_prefix=xxx` - a prefix that is added onto the beginning of - all imports. Useful for things like generating protos in a - subdirectory, or regenerating vendored protobufs in-place. -- `import_path=foo/bar` - used as the package if no input files - declare `go_package`. If it contains slashes, everything up to the - rightmost slash is ignored. +- `paths=(import | source_relative)` - specifies how the paths of + generated files are structured. See the "Packages and imports paths" + section above. The default is `import`. - `plugins=plugin1+plugin2` - specifies the list of sub-plugins to load. The only plugin in this repo is `grpc`. - `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is associated with Go package quux/shme. This is subject to the import_prefix parameter. +The following parameters are deprecated and should not be used: + +- `import_prefix=xxx` - a prefix that is added onto the beginning of + all imports. +- `import_path=foo/bar` - used as the package if no input files + declare `go_package`. If it contains slashes, everything up to the + rightmost slash is ignored. + ## gRPC Support ## If a proto file specifies RPC services, protoc-gen-go can be instructed to diff --git a/vendor/github.com/golang/protobuf/proto/Makefile b/vendor/github.com/golang/protobuf/proto/Makefile deleted file mode 100644 index e2e0651a93..0000000000 --- a/vendor/github.com/golang/protobuf/proto/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# 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. - -install: - go install - -test: install generate-test-pbs - go test - - -generate-test-pbs: - make install - make -C testdata - protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. proto3_proto/proto3.proto - make diff --git a/vendor/github.com/golang/protobuf/proto/all_test.go b/vendor/github.com/golang/protobuf/proto/all_test.go deleted file mode 100644 index 41451a4073..0000000000 --- a/vendor/github.com/golang/protobuf/proto/all_test.go +++ /dev/null @@ -1,2278 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "math" - "math/rand" - "reflect" - "runtime/debug" - "strings" - "testing" - "time" - - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -var globalO *Buffer - -func old() *Buffer { - if globalO == nil { - globalO = NewBuffer(nil) - } - globalO.Reset() - return globalO -} - -func equalbytes(b1, b2 []byte, t *testing.T) { - if len(b1) != len(b2) { - t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) - return - } - for i := 0; i < len(b1); i++ { - if b1[i] != b2[i] { - t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) - } - } -} - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} - -func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { - data := b.Bytes() - ld := len(data) - ls := len(s) / 2 - - fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) - - // find the interesting spot - n - n := ls - if ld < ls { - n = ld - } - j := 0 - for i := 0; i < n; i++ { - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - if data[i] == bs { - continue - } - n = i - break - } - l := n - 10 - if l < 0 { - l = 0 - } - h := n + 10 - - // find the interesting spot - n - fmt.Printf("is[%d]:", l) - for i := l; i < h; i++ { - if i >= ld { - fmt.Printf(" --") - continue - } - fmt.Printf(" %.2x", data[i]) - } - fmt.Printf("\n") - - fmt.Printf("sb[%d]:", l) - for i := l; i < h; i++ { - if i >= ls { - fmt.Printf(" --") - continue - } - bs := hex(s[j])*16 + hex(s[j+1]) - j += 2 - fmt.Printf(" %.2x", bs) - } - fmt.Printf("\n") - - t.Fail() - - // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) - // Print the output in a partially-decoded format; can - // be helpful when updating the test. It produces the output - // that is pasted, with minor edits, into the argument to verify(). - // data := b.Bytes() - // nesting := 0 - // for b.Len() > 0 { - // start := len(data) - b.Len() - // var u uint64 - // u, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // wire := u & 0x7 - // tag := u >> 3 - // switch wire { - // case WireVarint: - // v, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on varint:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed32: - // v, err := DecodeFixed32(b) - // if err != nil { - // fmt.Printf("decode error on fixed32:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireFixed64: - // v, err := DecodeFixed64(b) - // if err != nil { - // fmt.Printf("decode error on fixed64:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", - // data[start:len(data)-b.Len()], tag, wire, v) - // case WireBytes: - // nb, err := DecodeVarint(b) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // after_tag := len(data) - b.Len() - // str := make([]byte, nb) - // _, err = b.Read(str) - // if err != nil { - // fmt.Printf("decode error on bytes:", err) - // return - // } - // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", - // data[start:after_tag], str, tag, wire) - // case WireStartGroup: - // nesting++ - // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // case WireEndGroup: - // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", - // data[start:len(data)-b.Len()], tag, nesting) - // nesting-- - // default: - // fmt.Printf("unrecognized wire type %d\n", wire) - // return - // } - // } -} - -func hex(c uint8) uint8 { - if '0' <= c && c <= '9' { - return c - '0' - } - if 'a' <= c && c <= 'f' { - return 10 + c - 'a' - } - if 'A' <= c && c <= 'F' { - return 10 + c - 'A' - } - return 0 -} - -func equal(b []byte, s string, t *testing.T) bool { - if 2*len(b) != len(s) { - // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) - fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) - return false - } - for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { - x := hex(s[j])*16 + hex(s[j+1]) - if b[i] != x { - // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) - fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) - return false - } - } - return true -} - -func overify(t *testing.T, pb *GoTest, expected string) { - o := old() - err := o.Marshal(pb) - if err != nil { - fmt.Printf("overify marshal-1 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 1", o.Bytes()) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = o.Unmarshal(pbd) - if err != nil { - t.Fatalf("overify unmarshal err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - o.Reset() - err = o.Marshal(pbd) - if err != nil { - t.Errorf("overify marshal-2 err = %v", err) - o.DebugPrint("", o.Bytes()) - t.Fatalf("string = %s", expected) - } - if !equal(o.Bytes(), expected, t) { - o.DebugPrint("overify neq 2", o.Bytes()) - t.Fatalf("string = %s", expected) - } -} - -// Simple tests for numeric encode/decode primitives (varint, etc.) -func TestNumericPrimitives(t *testing.T) { - for i := uint64(0); i < 1e6; i += 111 { - o := old() - if o.EncodeVarint(i) != nil { - t.Error("EncodeVarint") - break - } - x, e := o.DecodeVarint() - if e != nil { - t.Fatal("DecodeVarint") - } - if x != i { - t.Fatal("varint decode fail:", i, x) - } - - o = old() - if o.EncodeFixed32(i) != nil { - t.Fatal("encFixed32") - } - x, e = o.DecodeFixed32() - if e != nil { - t.Fatal("decFixed32") - } - if x != i { - t.Fatal("fixed32 decode fail:", i, x) - } - - o = old() - if o.EncodeFixed64(i*1234567) != nil { - t.Error("encFixed64") - break - } - x, e = o.DecodeFixed64() - if e != nil { - t.Error("decFixed64") - break - } - if x != i*1234567 { - t.Error("fixed64 decode fail:", i*1234567, x) - break - } - - o = old() - i32 := int32(i - 12345) - if o.EncodeZigzag32(uint64(i32)) != nil { - t.Fatal("EncodeZigzag32") - } - x, e = o.DecodeZigzag32() - if e != nil { - t.Fatal("DecodeZigzag32") - } - if x != uint64(uint32(i32)) { - t.Fatal("zigzag32 decode fail:", i32, x) - } - - o = old() - i64 := int64(i - 12345) - if o.EncodeZigzag64(uint64(i64)) != nil { - t.Fatal("EncodeZigzag64") - } - x, e = o.DecodeZigzag64() - if e != nil { - t.Fatal("DecodeZigzag64") - } - if x != uint64(i64) { - t.Fatal("zigzag64 decode fail:", i64, x) - } - } -} - -// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. -type fakeMarshaler struct { - b []byte - err error -} - -func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } -func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } -func (f *fakeMarshaler) ProtoMessage() {} -func (f *fakeMarshaler) Reset() {} - -type msgWithFakeMarshaler struct { - M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` -} - -func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } -func (m *msgWithFakeMarshaler) ProtoMessage() {} -func (m *msgWithFakeMarshaler) Reset() {} - -// Simple tests for proto messages that implement the Marshaler interface. -func TestMarshalerEncoding(t *testing.T) { - tests := []struct { - name string - m Message - want []byte - errType reflect.Type - }{ - { - name: "Marshaler that fails", - m: &fakeMarshaler{ - err: errors.New("some marshal err"), - b: []byte{5, 6, 7}, - }, - // Since the Marshal method returned bytes, they should be written to the - // buffer. (For efficiency, we assume that Marshal implementations are - // always correct w.r.t. RequiredNotSetError and output.) - want: []byte{5, 6, 7}, - errType: reflect.TypeOf(errors.New("some marshal err")), - }, - { - name: "Marshaler that fails with RequiredNotSetError", - m: &msgWithFakeMarshaler{ - M: &fakeMarshaler{ - err: &RequiredNotSetError{}, - b: []byte{5, 6, 7}, - }, - }, - // Since there's an error that can be continued after, - // the buffer should be written. - want: []byte{ - 10, 3, // for &msgWithFakeMarshaler - 5, 6, 7, // for &fakeMarshaler - }, - errType: reflect.TypeOf(&RequiredNotSetError{}), - }, - { - name: "Marshaler that succeeds", - m: &fakeMarshaler{ - b: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - want: []byte{0, 1, 2, 3, 4, 127, 255}, - }, - } - for _, test := range tests { - b := NewBuffer(nil) - err := b.Marshal(test.m) - if reflect.TypeOf(err) != test.errType { - t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType) - } - if !reflect.DeepEqual(test.want, b.Bytes()) { - t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) - } - if size := Size(test.m); size != len(b.Bytes()) { - t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes())) - } - - m, mErr := Marshal(test.m) - if !bytes.Equal(b.Bytes(), m) { - t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes()) - } - if !reflect.DeepEqual(err, mErr) { - t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q", - test.name, fmt.Sprint(mErr), fmt.Sprint(err)) - } - } -} - -// Simple tests for bytes -func TestBytesPrimitives(t *testing.T) { - o := old() - bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} - if o.EncodeRawBytes(bytes) != nil { - t.Error("EncodeRawBytes") - } - decb, e := o.DecodeRawBytes(false) - if e != nil { - t.Error("DecodeRawBytes") - } - equalbytes(bytes, decb, t) -} - -// Simple tests for strings -func TestStringPrimitives(t *testing.T) { - o := old() - s := "now is the time" - if o.EncodeStringBytes(s) != nil { - t.Error("enc_string") - } - decs, e := o.DecodeStringBytes() - if e != nil { - t.Error("dec_string") - } - if s != decs { - t.Error("string encode/decode fail:", s, decs) - } -} - -// Do we catch the "required bit not set" case? -func TestRequiredBit(t *testing.T) { - o := old() - pb := new(GoTest) - err := o.Marshal(pb) - if err == nil { - t.Error("did not catch missing required fields") - } else if strings.Index(err.Error(), "Kind") < 0 { - t.Error("wrong error type:", err) - } -} - -// Check that all fields are nil. -// Clearly silly, and a residue from a more interesting test with an earlier, -// different initialization property, but it once caught a compiler bug so -// it lives. -func checkInitialized(pb *GoTest, t *testing.T) { - if pb.F_BoolDefaulted != nil { - t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) - } - if pb.F_Int32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) - } - if pb.F_Int64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) - } - if pb.F_Fixed32Defaulted != nil { - t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) - } - if pb.F_Fixed64Defaulted != nil { - t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) - } - if pb.F_Uint32Defaulted != nil { - t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) - } - if pb.F_Uint64Defaulted != nil { - t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) - } - if pb.F_FloatDefaulted != nil { - t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) - } - if pb.F_DoubleDefaulted != nil { - t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) - } - if pb.F_StringDefaulted != nil { - t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) - } - if pb.F_BytesDefaulted != nil { - t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) - } - if pb.F_Sint32Defaulted != nil { - t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) - } - if pb.F_Sint64Defaulted != nil { - t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) - } -} - -// Does Reset() reset? -func TestReset(t *testing.T) { - pb := initGoTest(true) - // muck with some values - pb.F_BoolDefaulted = Bool(false) - pb.F_Int32Defaulted = Int32(237) - pb.F_Int64Defaulted = Int64(12346) - pb.F_Fixed32Defaulted = Uint32(32000) - pb.F_Fixed64Defaulted = Uint64(666) - pb.F_Uint32Defaulted = Uint32(323232) - pb.F_Uint64Defaulted = nil - pb.F_FloatDefaulted = nil - pb.F_DoubleDefaulted = Float64(0) - pb.F_StringDefaulted = String("gotcha") - pb.F_BytesDefaulted = []byte("asdfasdf") - pb.F_Sint32Defaulted = Int32(123) - pb.F_Sint64Defaulted = Int64(789) - pb.Reset() - checkInitialized(pb, t) -} - -// All required fields set, no defaults provided. -func TestEncodeDecode1(t *testing.T) { - pb := initGoTest(false) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 0x20 - "714000000000000000"+ // field 14, encoding 1, value 0x40 - "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 - "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" - "b304"+ // field 70, encoding 3, start group - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // field 70, encoding 4, end group - "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f") // field 103, encoding 0, 0x7f zigzag64 -} - -// All required fields set, defaults provided. -func TestEncodeDecode2(t *testing.T) { - pb := initGoTest(true) - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All default fields set to their default value by hand -func TestEncodeDecode3(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolDefaulted = Bool(true) - pb.F_Int32Defaulted = Int32(32) - pb.F_Int64Defaulted = Int64(64) - pb.F_Fixed32Defaulted = Uint32(320) - pb.F_Fixed64Defaulted = Uint64(640) - pb.F_Uint32Defaulted = Uint32(3200) - pb.F_Uint64Defaulted = Uint64(6400) - pb.F_FloatDefaulted = Float32(314159) - pb.F_DoubleDefaulted = Float64(271828) - pb.F_StringDefaulted = String("hello, \"world!\"\n") - pb.F_BytesDefaulted = []byte("Bignose") - pb.F_Sint32Defaulted = Int32(-32) - pb.F_Sint64Defaulted = Int64(-64) - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all non-defaulted optional fields have values. -func TestEncodeDecode4(t *testing.T) { - pb := initGoTest(true) - pb.Table = String("hello") - pb.Param = Int32(7) - pb.OptionalField = initGoTestField() - pb.F_BoolOptional = Bool(true) - pb.F_Int32Optional = Int32(32) - pb.F_Int64Optional = Int64(64) - pb.F_Fixed32Optional = Uint32(3232) - pb.F_Fixed64Optional = Uint64(6464) - pb.F_Uint32Optional = Uint32(323232) - pb.F_Uint64Optional = Uint64(646464) - pb.F_FloatOptional = Float32(32.) - pb.F_DoubleOptional = Float64(64.) - pb.F_StringOptional = String("hello") - pb.F_BytesOptional = []byte("Bignose") - pb.F_Sint32Optional = Int32(-32) - pb.F_Sint64Optional = Int64(-64) - pb.Optionalgroup = initGoTest_OptionalGroup() - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" - "1807"+ // field 3, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "f00101"+ // field 30, encoding 0, value 1 - "f80120"+ // field 31, encoding 0, value 32 - "800240"+ // field 32, encoding 0, value 64 - "8d02a00c0000"+ // field 33, encoding 5, value 3232 - "91024019000000000000"+ // field 34, encoding 1, value 6464 - "9802a0dd13"+ // field 35, encoding 0, value 323232 - "a002c0ba27"+ // field 36, encoding 0, value 646464 - "ad0200000042"+ // field 37, encoding 5, value 32.0 - "b1020000000000005040"+ // field 38, encoding 1, value 64.0 - "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "d305"+ // start group field 90 level 1 - "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" - "d405"+ // end group field 90 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" - "f0123f"+ // field 302, encoding 0, value 63 - "f8127f"+ // field 303, encoding 0, value 127 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestEncodeDecode5(t *testing.T) { - pb := initGoTest(true) - pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} - pb.F_BoolRepeated = []bool{false, true} - pb.F_Int32Repeated = []int32{32, 33} - pb.F_Int64Repeated = []int64{64, 65} - pb.F_Fixed32Repeated = []uint32{3232, 3333} - pb.F_Fixed64Repeated = []uint64{6464, 6565} - pb.F_Uint32Repeated = []uint32{323232, 333333} - pb.F_Uint64Repeated = []uint64{646464, 656565} - pb.F_FloatRepeated = []float32{32., 33.} - pb.F_DoubleRepeated = []float64{64., 65.} - pb.F_StringRepeated = []string{"hello", "sailor"} - pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} - pb.F_Sint32Repeated = []int32{32, -32} - pb.F_Sint64Repeated = []int64{64, -64} - pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "a00100"+ // field 20, encoding 0, value 0 - "a00101"+ // field 20, encoding 0, value 1 - "a80120"+ // field 21, encoding 0, value 32 - "a80121"+ // field 21, encoding 0, value 33 - "b00140"+ // field 22, encoding 0, value 64 - "b00141"+ // field 22, encoding 0, value 65 - "bd01a00c0000"+ // field 23, encoding 5, value 3232 - "bd01050d0000"+ // field 23, encoding 5, value 3333 - "c1014019000000000000"+ // field 24, encoding 1, value 6464 - "c101a519000000000000"+ // field 24, encoding 1, value 6565 - "c801a0dd13"+ // field 25, encoding 0, value 323232 - "c80195ac14"+ // field 25, encoding 0, value 333333 - "d001c0ba27"+ // field 26, encoding 0, value 646464 - "d001b58928"+ // field 26, encoding 0, value 656565 - "dd0100000042"+ // field 27, encoding 5, value 32.0 - "dd0100000442"+ // field 27, encoding 5, value 33.0 - "e1010000000000005040"+ // field 28, encoding 1, value 64.0 - "e1010000000000405040"+ // field 28, encoding 1, value 65.0 - "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" - "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" - "c00201"+ // field 40, encoding 0, value 1 - "c80220"+ // field 41, encoding 0, value 32 - "d00240"+ // field 42, encoding 0, value 64 - "dd0240010000"+ // field 43, encoding 5, value 320 - "e1028002000000000000"+ // field 44, encoding 1, value 640 - "e8028019"+ // field 45, encoding 0, value 3200 - "f0028032"+ // field 46, encoding 0, value 6400 - "fd02e0659948"+ // field 47, encoding 5, value 314159.0 - "81030000000050971041"+ // field 48, encoding 1, value 271828.0 - "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "8305"+ // start group field 80 level 1 - "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" - "8405"+ // end group field 80 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "ca0c03"+"626967"+ // field 201, encoding 2, string "big" - "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" - "d00c40"+ // field 202, encoding 0, value 32 - "d00c3f"+ // field 202, encoding 0, value -32 - "d80c8001"+ // field 203, encoding 0, value 64 - "d80c7f"+ // field 203, encoding 0, value -64 - "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" - "90193f"+ // field 402, encoding 0, value 63 - "98197f") // field 403, encoding 0, value 127 - -} - -// All required fields set, all packed repeated fields given two values. -func TestEncodeDecode6(t *testing.T) { - pb := initGoTest(false) - pb.F_BoolRepeatedPacked = []bool{false, true} - pb.F_Int32RepeatedPacked = []int32{32, 33} - pb.F_Int64RepeatedPacked = []int64{64, 65} - pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} - pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} - pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} - pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} - pb.F_FloatRepeatedPacked = []float32{32., 33.} - pb.F_DoubleRepeatedPacked = []float64{64., 65.} - pb.F_Sint32RepeatedPacked = []int32{32, -32} - pb.F_Sint64RepeatedPacked = []int64{64, -64} - - overify(t, pb, - "0807"+ // field 1, encoding 0, value 7 - "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) - "5001"+ // field 10, encoding 0, value 1 - "5803"+ // field 11, encoding 0, value 3 - "6006"+ // field 12, encoding 0, value 6 - "6d20000000"+ // field 13, encoding 5, value 32 - "714000000000000000"+ // field 14, encoding 1, value 64 - "78a019"+ // field 15, encoding 0, value 3232 - "8001c032"+ // field 16, encoding 0, value 6464 - "8d0100004a45"+ // field 17, encoding 5, value 3232.0 - "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 - "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" - "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 - "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 - "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 - "aa0308"+ // field 53, encoding 2, 8 bytes - "a00c0000050d0000"+ // value 3232, value 3333 - "b20310"+ // field 54, encoding 2, 16 bytes - "4019000000000000a519000000000000"+ // value 6464, value 6565 - "ba0306"+ // field 55, encoding 2, 6 bytes - "a0dd1395ac14"+ // value 323232, value 333333 - "c20306"+ // field 56, encoding 2, 6 bytes - "c0ba27b58928"+ // value 646464, value 656565 - "ca0308"+ // field 57, encoding 2, 8 bytes - "0000004200000442"+ // value 32.0, value 33.0 - "d20310"+ // field 58, encoding 2, 16 bytes - "00000000000050400000000000405040"+ // value 64.0, value 65.0 - "b304"+ // start group field 70 level 1 - "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" - "b404"+ // end group field 70 level 1 - "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" - "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 - "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 - "b21f02"+ // field 502, encoding 2, 2 bytes - "403f"+ // value 32, value -32 - "ba1f03"+ // field 503, encoding 2, 3 bytes - "80017f") // value 64, value -64 -} - -// Test that we can encode empty bytes fields. -func TestEncodeDecodeBytes1(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRequired = []byte{} - pb.F_BytesRepeated = [][]byte{{}} - pb.F_BytesOptional = []byte{} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { - t.Error("required empty bytes field is incorrect") - } - if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { - t.Error("repeated empty bytes field is incorrect") - } - if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { - t.Error("optional empty bytes field is incorrect") - } -} - -// Test that we encode nil-valued fields of a repeated bytes field correctly. -// Since entries in a repeated field cannot be nil, nil must mean empty value. -func TestEncodeDecodeBytes2(t *testing.T) { - pb := initGoTest(false) - - // Create our bytes - pb.F_BytesRepeated = [][]byte{nil} - - d, err := Marshal(pb) - if err != nil { - t.Error(err) - } - - pbd := new(GoTest) - if err := Unmarshal(d, pbd); err != nil { - t.Error(err) - } - - if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { - t.Error("Unexpected value for repeated bytes field") - } -} - -// All required fields set, defaults provided, all repeated fields given two values. -func TestSkippingUnrecognizedFields(t *testing.T) { - o := old() - pb := initGoTestField() - - // Marshal it normally. - o.Marshal(pb) - - // Now new a GoSkipTest record. - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - // Marshal it into same buffer. - o.Marshal(skip) - - pbd := new(GoTestField) - o.Unmarshal(pbd) - - // The __unrecognized field should be a marshaling of GoSkipTest - skipd := new(GoSkipTest) - - o.SetBuf(pbd.XXX_unrecognized) - o.Unmarshal(skipd) - - if *skipd.SkipInt32 != *skip.SkipInt32 { - t.Error("skip int32", skipd.SkipInt32) - } - if *skipd.SkipFixed32 != *skip.SkipFixed32 { - t.Error("skip fixed32", skipd.SkipFixed32) - } - if *skipd.SkipFixed64 != *skip.SkipFixed64 { - t.Error("skip fixed64", skipd.SkipFixed64) - } - if *skipd.SkipString != *skip.SkipString { - t.Error("skip string", *skipd.SkipString) - } - if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { - t.Error("skip group int32", skipd.Skipgroup.GroupInt32) - } - if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { - t.Error("skip group string", *skipd.Skipgroup.GroupString) - } -} - -// Check that unrecognized fields of a submessage are preserved. -func TestSubmessageUnrecognizedFields(t *testing.T) { - nm := &NewMessage{ - Nested: &NewMessage_Nested{ - Name: String("Nigel"), - FoodGroup: String("carbs"), - }, - } - b, err := Marshal(nm) - if err != nil { - t.Fatalf("Marshal of NewMessage: %v", err) - } - - // Unmarshal into an OldMessage. - om := new(OldMessage) - if err := Unmarshal(b, om); err != nil { - t.Fatalf("Unmarshal to OldMessage: %v", err) - } - exp := &OldMessage{ - Nested: &OldMessage_Nested{ - Name: String("Nigel"), - // normal protocol buffer users should not do this - XXX_unrecognized: []byte("\x12\x05carbs"), - }, - } - if !Equal(om, exp) { - t.Errorf("om = %v, want %v", om, exp) - } - - // Clone the OldMessage. - om = Clone(om).(*OldMessage) - if !Equal(om, exp) { - t.Errorf("Clone(om) = %v, want %v", om, exp) - } - - // Marshal the OldMessage, then unmarshal it into an empty NewMessage. - if b, err = Marshal(om); err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - t.Logf("Marshal(%v) -> %q", om, b) - nm2 := new(NewMessage) - if err := Unmarshal(b, nm2); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - if !Equal(nm, nm2) { - t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) - } -} - -// Check that an int32 field can be upgraded to an int64 field. -func TestNegativeInt32(t *testing.T) { - om := &OldMessage{ - Num: Int32(-1), - } - b, err := Marshal(om) - if err != nil { - t.Fatalf("Marshal of OldMessage: %v", err) - } - - // Check the size. It should be 11 bytes; - // 1 for the field/wire type, and 10 for the negative number. - if len(b) != 11 { - t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) - } - - // Unmarshal into a NewMessage. - nm := new(NewMessage) - if err := Unmarshal(b, nm); err != nil { - t.Fatalf("Unmarshal to NewMessage: %v", err) - } - want := &NewMessage{ - Num: Int64(-1), - } - if !Equal(nm, want) { - t.Errorf("nm = %v, want %v", nm, want) - } -} - -// Check that we can grow an array (repeated field) to have many elements. -// This test doesn't depend only on our encoding; for variety, it makes sure -// we create, encode, and decode the correct contents explicitly. It's therefore -// a bit messier. -// This test also uses (and hence tests) the Marshal/Unmarshal functions -// instead of the methods. -func TestBigRepeated(t *testing.T) { - pb := initGoTest(true) - - // Create the arrays - const N = 50 // Internally the library starts much smaller. - pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) - pb.F_Sint64Repeated = make([]int64, N) - pb.F_Sint32Repeated = make([]int32, N) - pb.F_BytesRepeated = make([][]byte, N) - pb.F_StringRepeated = make([]string, N) - pb.F_DoubleRepeated = make([]float64, N) - pb.F_FloatRepeated = make([]float32, N) - pb.F_Uint64Repeated = make([]uint64, N) - pb.F_Uint32Repeated = make([]uint32, N) - pb.F_Fixed64Repeated = make([]uint64, N) - pb.F_Fixed32Repeated = make([]uint32, N) - pb.F_Int64Repeated = make([]int64, N) - pb.F_Int32Repeated = make([]int32, N) - pb.F_BoolRepeated = make([]bool, N) - pb.RepeatedField = make([]*GoTestField, N) - - // Fill in the arrays with checkable values. - igtf := initGoTestField() - igtrg := initGoTest_RepeatedGroup() - for i := 0; i < N; i++ { - pb.Repeatedgroup[i] = igtrg - pb.F_Sint64Repeated[i] = int64(i) - pb.F_Sint32Repeated[i] = int32(i) - s := fmt.Sprint(i) - pb.F_BytesRepeated[i] = []byte(s) - pb.F_StringRepeated[i] = s - pb.F_DoubleRepeated[i] = float64(i) - pb.F_FloatRepeated[i] = float32(i) - pb.F_Uint64Repeated[i] = uint64(i) - pb.F_Uint32Repeated[i] = uint32(i) - pb.F_Fixed64Repeated[i] = uint64(i) - pb.F_Fixed32Repeated[i] = uint32(i) - pb.F_Int64Repeated[i] = int64(i) - pb.F_Int32Repeated[i] = int32(i) - pb.F_BoolRepeated[i] = i%2 == 0 - pb.RepeatedField[i] = igtf - } - - // Marshal. - buf, _ := Marshal(pb) - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - Unmarshal(buf, pbd) - - // Check the checkable values - for i := uint64(0); i < N; i++ { - if pbd.Repeatedgroup[i] == nil { // TODO: more checking? - t.Error("pbd.Repeatedgroup bad") - } - var x uint64 - x = uint64(pbd.F_Sint64Repeated[i]) - if x != i { - t.Error("pbd.F_Sint64Repeated bad", x, i) - } - x = uint64(pbd.F_Sint32Repeated[i]) - if x != i { - t.Error("pbd.F_Sint32Repeated bad", x, i) - } - s := fmt.Sprint(i) - equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) - if pbd.F_StringRepeated[i] != s { - t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) - } - x = uint64(pbd.F_DoubleRepeated[i]) - if x != i { - t.Error("pbd.F_DoubleRepeated bad", x, i) - } - x = uint64(pbd.F_FloatRepeated[i]) - if x != i { - t.Error("pbd.F_FloatRepeated bad", x, i) - } - x = pbd.F_Uint64Repeated[i] - if x != i { - t.Error("pbd.F_Uint64Repeated bad", x, i) - } - x = uint64(pbd.F_Uint32Repeated[i]) - if x != i { - t.Error("pbd.F_Uint32Repeated bad", x, i) - } - x = pbd.F_Fixed64Repeated[i] - if x != i { - t.Error("pbd.F_Fixed64Repeated bad", x, i) - } - x = uint64(pbd.F_Fixed32Repeated[i]) - if x != i { - t.Error("pbd.F_Fixed32Repeated bad", x, i) - } - x = uint64(pbd.F_Int64Repeated[i]) - if x != i { - t.Error("pbd.F_Int64Repeated bad", x, i) - } - x = uint64(pbd.F_Int32Repeated[i]) - if x != i { - t.Error("pbd.F_Int32Repeated bad", x, i) - } - if pbd.F_BoolRepeated[i] != (i%2 == 0) { - t.Error("pbd.F_BoolRepeated bad", x, i) - } - if pbd.RepeatedField[i] == nil { // TODO: more checking? - t.Error("pbd.RepeatedField bad") - } - } -} - -// Verify we give a useful message when decoding to the wrong structure type. -func TestTypeMismatch(t *testing.T) { - pb1 := initGoTest(true) - - // Marshal - o := old() - o.Marshal(pb1) - - // Now Unmarshal it to the wrong type. - pb2 := initGoTestField() - err := o.Unmarshal(pb2) - if err == nil { - t.Error("expected error, got no error") - } else if !strings.Contains(err.Error(), "bad wiretype") { - t.Error("expected bad wiretype error, got", err) - } -} - -func encodeDecode(t *testing.T, in, out Message, msg string) { - buf, err := Marshal(in) - if err != nil { - t.Fatalf("failed marshaling %v: %v", msg, err) - } - if err := Unmarshal(buf, out); err != nil { - t.Fatalf("failed unmarshaling %v: %v", msg, err) - } -} - -func TestPackedNonPackedDecoderSwitching(t *testing.T) { - np, p := new(NonPackedTest), new(PackedTest) - - // non-packed -> packed - np.A = []int32{0, 1, 1, 2, 3, 5} - encodeDecode(t, np, p, "non-packed -> packed") - if !reflect.DeepEqual(np.A, p.B) { - t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) - } - - // packed -> non-packed - np.Reset() - p.B = []int32{3, 1, 4, 1, 5, 9} - encodeDecode(t, p, np, "packed -> non-packed") - if !reflect.DeepEqual(p.B, np.A) { - t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) - } -} - -func TestProto1RepeatedGroup(t *testing.T) { - pb := &MessageList{ - Message: []*MessageList_Message{ - { - Name: String("blah"), - Count: Int32(7), - }, - // NOTE: pb.Message[1] is a nil - nil, - }, - } - - o := old() - err := o.Marshal(pb) - if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { - t.Fatalf("unexpected or no error when marshaling: %v", err) - } -} - -// Test that enums work. Checks for a bug introduced by making enums -// named types instead of int32: newInt32FromUint64 would crash with -// a type mismatch in reflect.PointTo. -func TestEnum(t *testing.T) { - pb := new(GoEnum) - pb.Foo = FOO_FOO1.Enum() - o := old() - if err := o.Marshal(pb); err != nil { - t.Fatal("error encoding enum:", err) - } - pb1 := new(GoEnum) - if err := o.Unmarshal(pb1); err != nil { - t.Fatal("error decoding enum:", err) - } - if *pb1.Foo != FOO_FOO1 { - t.Error("expected 7 but got ", *pb1.Foo) - } -} - -// Enum types have String methods. Check that enum fields can be printed. -// We don't care what the value actually is, just as long as it doesn't crash. -func TestPrintingNilEnumFields(t *testing.T) { - pb := new(GoEnum) - _ = fmt.Sprintf("%+v", pb) -} - -// Verify that absent required fields cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcement(t *testing.T) { - pb := new(GoTestField) - _, err := Marshal(pb) - if err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") { - t.Errorf("marshal: bad error type: %v", err) - } - - // A slightly sneaky, yet valid, proto. It encodes the same required field twice, - // so simply counting the required fields is insufficient. - // field 1, encoding 2, value "hi" - buf := []byte("\x0A\x02hi\x0A\x02hi") - err = Unmarshal(buf, pb) - if err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -// Verify that absent required fields in groups cause Marshal/Unmarshal to return errors. -func TestRequiredFieldEnforcementGroups(t *testing.T) { - pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}} - if _, err := Marshal(pb); err == nil { - t.Error("marshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") { - t.Errorf("marshal: bad error type: %v", err) - } - - buf := []byte{11, 12} - if err := Unmarshal(buf, pb); err == nil { - t.Error("unmarshal: expected error, got nil") - } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") { - t.Errorf("unmarshal: bad error type: %v", err) - } -} - -func TestTypedNilMarshal(t *testing.T) { - // A typed nil should return ErrNil and not crash. - { - var m *GoEnum - if _, err := Marshal(m); err != ErrNil { - t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err) - } - } - - { - m := &Communique{Union: &Communique_Msg{nil}} - if _, err := Marshal(m); err == nil || err == ErrNil { - t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err) - } - } -} - -// A type that implements the Marshaler interface, but is not nillable. -type nonNillableInt uint64 - -func (nni nonNillableInt) Marshal() ([]byte, error) { - return EncodeVarint(uint64(nni)), nil -} - -type NNIMessage struct { - nni nonNillableInt -} - -func (*NNIMessage) Reset() {} -func (*NNIMessage) String() string { return "" } -func (*NNIMessage) ProtoMessage() {} - -// A type that implements the Marshaler interface and is nillable. -type nillableMessage struct { - x uint64 -} - -func (nm *nillableMessage) Marshal() ([]byte, error) { - return EncodeVarint(nm.x), nil -} - -type NMMessage struct { - nm *nillableMessage -} - -func (*NMMessage) Reset() {} -func (*NMMessage) String() string { return "" } -func (*NMMessage) ProtoMessage() {} - -// Verify a type that uses the Marshaler interface, but has a nil pointer. -func TestNilMarshaler(t *testing.T) { - // Try a struct with a Marshaler field that is nil. - // It should be directly marshable. - nmm := new(NMMessage) - if _, err := Marshal(nmm); err != nil { - t.Error("unexpected error marshaling nmm: ", err) - } - - // Try a struct with a Marshaler field that is not nillable. - nnim := new(NNIMessage) - nnim.nni = 7 - var _ Marshaler = nnim.nni // verify it is truly a Marshaler - if _, err := Marshal(nnim); err != nil { - t.Error("unexpected error marshaling nnim: ", err) - } -} - -func TestAllSetDefaults(t *testing.T) { - // Exercise SetDefaults with all scalar field types. - m := &Defaults{ - // NaN != NaN, so override that here. - F_Nan: Float32(1.7), - } - expected := &Defaults{ - F_Bool: Bool(true), - F_Int32: Int32(32), - F_Int64: Int64(64), - F_Fixed32: Uint32(320), - F_Fixed64: Uint64(640), - F_Uint32: Uint32(3200), - F_Uint64: Uint64(6400), - F_Float: Float32(314159), - F_Double: Float64(271828), - F_String: String(`hello, "world!"` + "\n"), - F_Bytes: []byte("Bignose"), - F_Sint32: Int32(-32), - F_Sint64: Int64(-64), - F_Enum: Defaults_GREEN.Enum(), - F_Pinf: Float32(float32(math.Inf(1))), - F_Ninf: Float32(float32(math.Inf(-1))), - F_Nan: Float32(1.7), - StrZero: String(""), - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithSetField(t *testing.T) { - // Check that a set value is not overridden. - m := &Defaults{ - F_Int32: Int32(12), - } - SetDefaults(m) - if v := m.GetF_Int32(); v != 12 { - t.Errorf("m.FInt32 = %v, want 12", v) - } -} - -func TestSetDefaultsWithSubMessage(t *testing.T) { - m := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - }, - } - expected := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("gopher"), - Port: Int32(4000), - }, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { - m := &MyMessage{ - RepInner: []*InnerMessage{{}}, - } - expected := &MyMessage{ - RepInner: []*InnerMessage{{ - Port: Int32(4000), - }}, - } - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { - m := &MyMessage{ - Pet: []string{"turtle", "wombat"}, - } - expected := Clone(m) - SetDefaults(m) - if !Equal(m, expected) { - t.Errorf("\n got %v\nwant %v", m, expected) - } -} - -func TestMaximumTagNumber(t *testing.T) { - m := &MaxTag{ - LastField: String("natural goat essence"), - } - buf, err := Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal failed: %v", err) - } - m2 := new(MaxTag) - if err := Unmarshal(buf, m2); err != nil { - t.Fatalf("proto.Unmarshal failed: %v", err) - } - if got, want := m2.GetLastField(), *m.LastField; got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestJSON(t *testing.T) { - m := &MyMessage{ - Count: Int32(4), - Pet: []string{"bunny", "kitty"}, - Inner: &InnerMessage{ - Host: String("cauchy"), - }, - Bikeshed: MyMessage_GREEN.Enum(), - } - const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` - - b, err := json.Marshal(m) - if err != nil { - t.Fatalf("json.Marshal failed: %v", err) - } - s := string(b) - if s != expected { - t.Errorf("got %s\nwant %s", s, expected) - } - - received := new(MyMessage) - if err := json.Unmarshal(b, received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } - - // Test unmarshalling of JSON with symbolic enum name. - const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` - received.Reset() - if err := json.Unmarshal([]byte(old), received); err != nil { - t.Fatalf("json.Unmarshal failed: %v", err) - } - if !Equal(received, m) { - t.Fatalf("got %s, want %s", received, m) - } -} - -func TestBadWireType(t *testing.T) { - b := []byte{7<<3 | 6} // field 7, wire type 6 - pb := new(OtherMessage) - if err := Unmarshal(b, pb); err == nil { - t.Errorf("Unmarshal did not fail") - } else if !strings.Contains(err.Error(), "unknown wire type") { - t.Errorf("wrong error: %v", err) - } -} - -func TestBytesWithInvalidLength(t *testing.T) { - // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. - b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} - Unmarshal(b, new(MyMessage)) -} - -func TestLengthOverflow(t *testing.T) { - // Overflowing a length should not panic. - b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} - Unmarshal(b, new(MyMessage)) -} - -func TestVarintOverflow(t *testing.T) { - // Overflowing a 64-bit length should not be allowed. - b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} - if err := Unmarshal(b, new(MyMessage)); err == nil { - t.Fatalf("Overflowed uint64 length without error") - } -} - -func TestUnmarshalFuzz(t *testing.T) { - const N = 1000 - seed := time.Now().UnixNano() - t.Logf("RNG seed is %d", seed) - rng := rand.New(rand.NewSource(seed)) - buf := make([]byte, 20) - for i := 0; i < N; i++ { - for j := range buf { - buf[j] = byte(rng.Intn(256)) - } - fuzzUnmarshal(t, buf) - } -} - -func TestMergeMessages(t *testing.T) { - pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} - data, err := Marshal(pb) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - pb1 := new(MessageList) - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("first Unmarshal: %v", err) - } - if err := Unmarshal(data, pb1); err != nil { - t.Fatalf("second Unmarshal: %v", err) - } - if len(pb1.Message) != 1 { - t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) - } - - pb2 := new(MessageList) - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("first UnmarshalMerge: %v", err) - } - if err := UnmarshalMerge(data, pb2); err != nil { - t.Fatalf("second UnmarshalMerge: %v", err) - } - if len(pb2.Message) != 2 { - t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) - } -} - -func TestExtensionMarshalOrder(t *testing.T) { - m := &MyMessage{Count: Int(123)} - if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { - t.Fatalf("SetExtension: %v", err) - } - if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { - t.Fatalf("SetExtension: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - var orig []byte - for i := 0; i < 100; i++ { - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if i == 0 { - orig = b - continue - } - if !bytes.Equal(b, orig) { - t.Errorf("Bytes differ on attempt #%d", i) - } - } -} - -// Many extensions, because small maps might not iterate differently on each iteration. -var exts = []*ExtensionDesc{ - E_X201, - E_X202, - E_X203, - E_X204, - E_X205, - E_X206, - E_X207, - E_X208, - E_X209, - E_X210, - E_X211, - E_X212, - E_X213, - E_X214, - E_X215, - E_X216, - E_X217, - E_X218, - E_X219, - E_X220, - E_X221, - E_X222, - E_X223, - E_X224, - E_X225, - E_X226, - E_X227, - E_X228, - E_X229, - E_X230, - E_X231, - E_X232, - E_X233, - E_X234, - E_X235, - E_X236, - E_X237, - E_X238, - E_X239, - E_X240, - E_X241, - E_X242, - E_X243, - E_X244, - E_X245, - E_X246, - E_X247, - E_X248, - E_X249, - E_X250, -} - -func TestMessageSetMarshalOrder(t *testing.T) { - m := &MyMessageSet{} - for _, x := range exts { - if err := SetExtension(m, x, &Empty{}); err != nil { - t.Fatalf("SetExtension: %v", err) - } - } - - buf, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // Serialize m several times, and check we get the same bytes each time. - for i := 0; i < 10; i++ { - b1, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(b1, buf) { - t.Errorf("Bytes differ on re-Marshal #%d", i) - } - - m2 := &MyMessageSet{} - if err := Unmarshal(buf, m2); err != nil { - t.Errorf("Unmarshal: %v", err) - } - b2, err := Marshal(m2) - if err != nil { - t.Errorf("re-Marshal: %v", err) - } - if !bytes.Equal(b2, buf) { - t.Errorf("Bytes differ on round-trip #%d", i) - } - } -} - -func TestUnmarshalMergesMessages(t *testing.T) { - // If a nested message occurs twice in the input, - // the fields should be merged when decoding. - a := &OtherMessage{ - Key: Int64(123), - Inner: &InnerMessage{ - Host: String("polhode"), - Port: Int32(1234), - }, - } - aData, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal(a): %v", err) - } - b := &OtherMessage{ - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Connected: Bool(true), - }, - } - bData, err := Marshal(b) - if err != nil { - t.Fatalf("Marshal(b): %v", err) - } - want := &OtherMessage{ - Key: Int64(123), - Weight: Float32(1.2), - Inner: &InnerMessage{ - Host: String("herpolhode"), - Port: Int32(1234), - Connected: Bool(true), - }, - } - got := new(OtherMessage) - if err := Unmarshal(append(aData, bData...), got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !Equal(got, want) { - t.Errorf("\n got %v\nwant %v", got, want) - } -} - -func TestEncodingSizes(t *testing.T) { - tests := []struct { - m Message - n int - }{ - {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, - {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, - {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, - {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, - } - for _, test := range tests { - b, err := Marshal(test.m) - if err != nil { - t.Errorf("Marshal(%v): %v", test.m, err) - continue - } - if len(b) != test.n { - t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) - } - } -} - -func TestRequiredNotSetError(t *testing.T) { - pb := initGoTest(false) - pb.RequiredField.Label = nil - pb.F_Int32Required = nil - pb.F_Int64Required = nil - - expected := "0807" + // field 1, encoding 0, value 7 - "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) - "5001" + // field 10, encoding 0, value 1 - "6d20000000" + // field 13, encoding 5, value 0x20 - "714000000000000000" + // field 14, encoding 1, value 0x40 - "78a019" + // field 15, encoding 0, value 0xca0 = 3232 - "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 - "8d0100004a45" + // field 17, encoding 5, value 3232.0 - "9101000000000040b940" + // field 18, encoding 1, value 6464.0 - "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" - "b304" + // field 70, encoding 3, start group - "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" - "b404" + // field 70, encoding 4, end group - "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" - "b0063f" + // field 102, encoding 0, 0x3f zigzag32 - "b8067f" // field 103, encoding 0, 0x7f zigzag64 - - o := old() - bytes, err := Marshal(pb) - if _, ok := err.(*RequiredNotSetError); !ok { - fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("expected = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-1 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 1", bytes) - t.Fatalf("expected = %s", expected) - } - - // Now test Unmarshal by recreating the original buffer. - pbd := new(GoTest) - err = Unmarshal(bytes, pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { - t.Errorf("unmarshal wrong err msg: %v", err) - } - bytes, err = Marshal(pbd) - if _, ok := err.(*RequiredNotSetError); !ok { - t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) - o.DebugPrint("", bytes) - t.Fatalf("string = %s", expected) - } - if strings.Index(err.Error(), "RequiredField.Label") < 0 { - t.Errorf("marshal-2 wrong err msg: %v", err) - } - if !equal(bytes, expected, t) { - o.DebugPrint("neq 2", bytes) - t.Fatalf("string = %s", expected) - } -} - -func fuzzUnmarshal(t *testing.T, data []byte) { - defer func() { - if e := recover(); e != nil { - t.Errorf("These bytes caused a panic: %+v", data) - t.Logf("Stack:\n%s", debug.Stack()) - t.FailNow() - } - }() - - pb := new(MyMessage) - Unmarshal(data, pb) -} - -func TestMapFieldMarshal(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - // b should be the concatenation of these three byte sequences in some order. - parts := []string{ - "\n\a\b\x01\x12\x03Rob", - "\n\a\b\x04\x12\x03Ian", - "\n\b\b\x08\x12\x04Dave", - } - ok := false - for i := range parts { - for j := range parts { - if j == i { - continue - } - for k := range parts { - if k == i || k == j { - continue - } - try := parts[i] + parts[j] + parts[k] - if bytes.Equal(b, []byte(try)) { - ok = true - break - } - } - } - } - if !ok { - t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) - } - t.Logf("FYI b: %q", b) - - (new(Buffer)).DebugPrint("Dump of b", b) -} - -func TestMapFieldRoundTrips(t *testing.T) { - m := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Rob", - 4: "Ian", - 8: "Dave", - }, - MsgMapping: map[int64]*FloatingPoint{ - 0x7001: &FloatingPoint{F: Float64(2.0)}, - }, - ByteMapping: map[bool][]byte{ - false: []byte("that's not right!"), - true: []byte("aye, 'tis true!"), - }, - } - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("FYI b: %q", b) - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - for _, pair := range [][2]interface{}{ - {m.NameMapping, m2.NameMapping}, - {m.MsgMapping, m2.MsgMapping}, - {m.ByteMapping, m2.ByteMapping}, - } { - if !reflect.DeepEqual(pair[0], pair[1]) { - t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) - } - } -} - -func TestMapFieldWithNil(t *testing.T) { - m1 := &MessageWithMap{ - MsgMapping: map[int64]*FloatingPoint{ - 1: nil, - }, - } - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.MsgMapping[1]; !ok { - t.Error("msg_mapping[1] not present") - } else if v != nil { - t.Errorf("msg_mapping[1] not nil: %v", v) - } -} - -func TestMapFieldWithNilBytes(t *testing.T) { - m1 := &MessageWithMap{ - ByteMapping: map[bool][]byte{ - false: []byte{}, - true: nil, - }, - } - n := Size(m1) - b, err := Marshal(m1) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if n != len(b) { - t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b)) - } - m2 := new(MessageWithMap) - if err := Unmarshal(b, m2); err != nil { - t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b) - } - if v, ok := m2.ByteMapping[false]; !ok { - t.Error("byte_mapping[false] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[false] not empty: %#v", v) - } - if v, ok := m2.ByteMapping[true]; !ok { - t.Error("byte_mapping[true] not present") - } else if len(v) != 0 { - t.Errorf("byte_mapping[true] not empty: %#v", v) - } -} - -func TestDecodeMapFieldMissingKey(t *testing.T) { - b := []byte{ - 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes - // no key - 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m" - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing key: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want) - } -} - -func TestDecodeMapFieldMissingValue(t *testing.T) { - b := []byte{ - 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes - 0x08, 0x01, // varint key, value 1 - // no value - } - got := &MessageWithMap{} - err := Unmarshal(b, got) - if err != nil { - t.Fatalf("failed to marshal map with missing value: %v", err) - } - want := &MessageWithMap{NameMapping: map[int32]string{1: ""}} - if !Equal(got, want) { - t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want) - } -} - -func TestOneof(t *testing.T) { - m := &Communique{} - b, err := Marshal(m) - if err != nil { - t.Fatalf("Marshal of empty message with oneof: %v", err) - } - if len(b) != 0 { - t.Errorf("Marshal of empty message yielded too many bytes: %v", b) - } - - m = &Communique{ - Union: &Communique_Name{"Barry"}, - } - - // Round-trip. - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof: %v", err) - } - if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) - t.Errorf("Incorrect marshal of message with oneof: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof: %v", err) - } - if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { - t.Errorf("After round trip, Union = %+v", m.Union) - } - if name := m.GetName(); name != "Barry" { - t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") - } - - // Let's try with a message in the oneof. - m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}} - b, err = Marshal(m) - if err != nil { - t.Fatalf("Marshal of message with oneof set to message: %v", err) - } - if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) - t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) - } - m.Reset() - if err := Unmarshal(b, m); err != nil { - t.Fatalf("Unmarshal of message with oneof set to message: %v", err) - } - ss, ok := m.Union.(*Communique_Msg) - if !ok || ss.Msg.GetStringField() != "deep deep string" { - t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) - } -} - -func TestInefficientPackedBool(t *testing.T) { - // https://github.com/golang/protobuf/issues/76 - inp := []byte{ - 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes - // Usually a bool should take a single byte, - // but it is permitted to be any varint. - 0xb9, 0x30, - } - if err := Unmarshal(inp, new(MoreRepeated)); err != nil { - t.Error(err) - } -} - -// Benchmarks - -func testMsg() *GoTest { - pb := initGoTest(true) - const N = 1000 // Internally the library starts much smaller. - pb.F_Int32Repeated = make([]int32, N) - pb.F_DoubleRepeated = make([]float64, N) - for i := 0; i < N; i++ { - pb.F_Int32Repeated[i] = int32(i) - pb.F_DoubleRepeated[i] = float64(i) - } - return pb -} - -func bytesMsg() *GoTest { - pb := initGoTest(true) - buf := make([]byte, 4000) - for i := range buf { - buf[i] = byte(i) - } - pb.F_BytesDefaulted = buf - return pb -} - -func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { - d, _ := marshal(pb) - b.SetBytes(int64(len(d))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - marshal(pb) - } -} - -func benchmarkBufferMarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - p.Reset() - err := p.Marshal(pb0) - return p.Bytes(), err - }) -} - -func benchmarkSize(b *testing.B, pb Message) { - benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { - Size(pb) - return nil, nil - }) -} - -func newOf(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - return reflect.New(in.Type().Elem()).Interface().(Message) -} - -func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { - d, _ := Marshal(pb) - b.SetBytes(int64(len(d))) - pbd := newOf(pb) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - unmarshal(d, pbd) - } -} - -func benchmarkBufferUnmarshal(b *testing.B, pb Message) { - p := NewBuffer(nil) - benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { - p.SetBuf(d) - return p.Unmarshal(pb0) - }) -} - -// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} - -func BenchmarkMarshal(b *testing.B) { - benchmarkMarshal(b, testMsg(), Marshal) -} - -func BenchmarkBufferMarshal(b *testing.B) { - benchmarkBufferMarshal(b, testMsg()) -} - -func BenchmarkSize(b *testing.B) { - benchmarkSize(b, testMsg()) -} - -func BenchmarkUnmarshal(b *testing.B) { - benchmarkUnmarshal(b, testMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshal(b *testing.B) { - benchmarkBufferUnmarshal(b, testMsg()) -} - -func BenchmarkMarshalBytes(b *testing.B) { - benchmarkMarshal(b, bytesMsg(), Marshal) -} - -func BenchmarkBufferMarshalBytes(b *testing.B) { - benchmarkBufferMarshal(b, bytesMsg()) -} - -func BenchmarkSizeBytes(b *testing.B) { - benchmarkSize(b, bytesMsg()) -} - -func BenchmarkUnmarshalBytes(b *testing.B) { - benchmarkUnmarshal(b, bytesMsg(), Unmarshal) -} - -func BenchmarkBufferUnmarshalBytes(b *testing.B) { - benchmarkBufferUnmarshal(b, bytesMsg()) -} - -func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { - b.StopTimer() - pb := initGoTestField() - skip := &GoSkipTest{ - SkipInt32: Int32(32), - SkipFixed32: Uint32(3232), - SkipFixed64: Uint64(6464), - SkipString: String("skipper"), - Skipgroup: &GoSkipTest_SkipGroup{ - GroupInt32: Int32(75), - GroupString: String("wxyz"), - }, - } - - pbd := new(GoTestField) - p := NewBuffer(nil) - p.Marshal(pb) - p.Marshal(skip) - p2 := NewBuffer(nil) - - b.StartTimer() - for i := 0; i < b.N; i++ { - p2.SetBuf(p.Bytes()) - p2.Unmarshal(pbd) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/any_test.go b/vendor/github.com/golang/protobuf/proto/any_test.go deleted file mode 100644 index 1a3c22ed41..0000000000 --- a/vendor/github.com/golang/protobuf/proto/any_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - pb "github.com/golang/protobuf/proto/proto3_proto" - testpb "github.com/golang/protobuf/proto/testdata" - anypb "github.com/golang/protobuf/ptypes/any" -) - -var ( - expandedMarshaler = proto.TextMarshaler{ExpandAny: true} - expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true} -) - -// anyEqual reports whether two messages which may be google.protobuf.Any or may -// contain google.protobuf.Any fields are equal. We can't use proto.Equal for -// comparison, because semantically equivalent messages may be marshaled to -// binary in different tag order. Instead, trust that TextMarshaler with -// ExpandAny option works and compare the text marshaling results. -func anyEqual(got, want proto.Message) bool { - // if messages are proto.Equal, no need to marshal. - if proto.Equal(got, want) { - return true - } - g := expandedMarshaler.Text(got) - w := expandedMarshaler.Text(want) - return g == w -} - -type golden struct { - m proto.Message - t, c string -} - -var goldenMessages = makeGolden() - -func makeGolden() []golden { - nested := &pb.Nested{Bunny: "Monty"} - nb, err := proto.Marshal(nested) - if err != nil { - panic(err) - } - m1 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m2 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb}, - } - m3 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb}, - } - m4 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb}, - } - m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb} - - any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")} - proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")}) - proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar")) - any1b, err := proto.Marshal(any1) - if err != nil { - panic(err) - } - any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}} - proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")}) - any2b, err := proto.Marshal(any2) - if err != nil { - panic(err) - } - m6 := &pb.Message{ - Name: "David", - ResultCount: 47, - Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - ManyThings: []*anypb.Any{ - &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b}, - &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b}, - }, - } - - const ( - m1Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m2Golden = ` -name: "David" -result_count: 47 -anything: < - ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m3Golden = ` -name: "David" -result_count: 47 -anything: < - ["type.googleapis.com/\"/proto3_proto.Nested"]: < - bunny: "Monty" - > -> -` - m4Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > -> -` - m5Golden = ` -[type.googleapis.com/proto3_proto.Nested]: < - bunny: "Monty" -> -` - m6Golden = ` -name: "David" -result_count: 47 -anything: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 42 - bikeshed: GREEN - rep_bytes: "roboto" - [testdata.Ext.more]: < - data: "baz" - > - > -> -many_things: < - [type.googleapis.com/testdata.MyMessage]: < - count: 47 - name: "David" - [testdata.Ext.more]: < - data: "foo" - > - [testdata.Ext.text]: "bar" - > -> -` - ) - return []golden{ - {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "}, - {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "}, - {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "}, - {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "}, - {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "}, - {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "}, - } -} - -func TestMarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want { - t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want) - } - if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want { - t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want) - } - } -} - -func TestUnmarshalGolden(t *testing.T) { - for _, tt := range goldenMessages { - want := tt.m - got := proto.Clone(tt.m) - got.Reset() - if err := proto.UnmarshalText(tt.t, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want) - } - got.Reset() - if err := proto.UnmarshalText(tt.c, got); err != nil { - t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err) - } - if !anyEqual(got, want) { - t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want) - } - } -} - -func TestMarshalUnknownAny(t *testing.T) { - m := &pb.Message{ - Anything: &anypb.Any{ - TypeUrl: "foo", - Value: []byte("bar"), - }, - } - want := `anything: < - type_url: "foo" - value: "bar" -> -` - got := expandedMarshaler.Text(m) - if got != want { - t.Errorf("got\n`%s`\nwant\n`%s`", got, want) - } -} - -func TestAmbiguousAny(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - type_url: "ttt/proto3_proto.Nested" - value: "\n\x05Monty" - `, pb) - t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err) - if err != nil { - t.Errorf("failed to parse ambiguous Any message: %v", err) - } -} - -func TestUnmarshalOverwriteAny(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Monty" - > - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 7: Any message unpacked multiple times, or "type_url" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} - -func TestUnmarshalAnyMixAndMatch(t *testing.T) { - pb := &anypb.Any{} - err := proto.UnmarshalText(` - value: "\n\x05Monty" - [type.googleapis.com/a/path/proto3_proto.Nested]: < - bunny: "Rabbit of Caerbannog" - > - `, pb) - want := `line 5: Any message unpacked multiple times, or "value" already set` - if err.Error() != want { - t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go index e392575b35..3cd3249f70 100644 --- a/vendor/github.com/golang/protobuf/proto/clone.go +++ b/vendor/github.com/golang/protobuf/proto/clone.go @@ -35,22 +35,39 @@ package proto import ( + "fmt" "log" "reflect" "strings" ) // Clone returns a deep copy of a protocol buffer. -func Clone(pb Message) Message { - in := reflect.ValueOf(pb) +func Clone(src Message) Message { + in := reflect.ValueOf(src) if in.IsNil() { - return pb + return src } - out := reflect.New(in.Type().Elem()) - // out is empty so a merge is a deep copy. - mergeStruct(out.Elem(), in.Elem()) - return out.Interface().(Message) + dst := out.Interface().(Message) + Merge(dst, src) + return dst +} + +// Merger is the interface representing objects that can merge messages of the same type. +type Merger interface { + // Merge merges src into this message. + // Required and optional fields that are set in src will be set to that value in dst. + // Elements of repeated fields will be appended. + // + // Merge may panic if called with a different argument type than the receiver. + Merge(src Message) +} + +// generatedMerger is the custom merge method that generated protos will have. +// We must add this method since a generate Merge method will conflict with +// many existing protos that have a Merge data field already defined. +type generatedMerger interface { + XXX_Merge(src Message) } // Merge merges src into dst. @@ -58,17 +75,24 @@ func Clone(pb Message) Message { // Elements of repeated fields will be appended. // Merge panics if src and dst are not the same type, or if dst is nil. func Merge(dst, src Message) { + if m, ok := dst.(Merger); ok { + m.Merge(src) + return + } + in := reflect.ValueOf(src) out := reflect.ValueOf(dst) if out.IsNil() { panic("proto: nil destination") } if in.Type() != out.Type() { - // Explicit test prior to mergeStruct so that mistyped nils will fail - panic("proto: type mismatch") + panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src)) } if in.IsNil() { - // Merging nil into non-nil is a quiet no-op + return // Merge from nil src is a noop + } + if m, ok := dst.(generatedMerger); ok { + m.XXX_Merge(src) return } mergeStruct(out.Elem(), in.Elem()) @@ -84,7 +108,7 @@ func mergeStruct(out, in reflect.Value) { mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) } - if emIn, ok := extendable(in.Addr().Interface()); ok { + if emIn, err := extendable(in.Addr().Interface()); err == nil { emOut, _ := extendable(out.Addr().Interface()) mIn, muIn := emIn.extensionsRead() if mIn != nil { diff --git a/vendor/github.com/golang/protobuf/proto/clone_test.go b/vendor/github.com/golang/protobuf/proto/clone_test.go deleted file mode 100644 index f607ff49eb..0000000000 --- a/vendor/github.com/golang/protobuf/proto/clone_test.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -var cloneTestMessage = &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, -} - -func init() { - ext := &pb.Ext{ - Data: proto.String("extension"), - } - if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { - panic("SetExtension: " + err.Error()) - } -} - -func TestClone(t *testing.T) { - m := proto.Clone(cloneTestMessage).(*pb.MyMessage) - if !proto.Equal(m, cloneTestMessage) { - t.Errorf("Clone(%v) = %v", cloneTestMessage, m) - } - - // Verify it was a deep copy. - *m.Inner.Port++ - if proto.Equal(m, cloneTestMessage) { - t.Error("Mutating clone changed the original") - } - // Byte fields and repeated fields should be copied. - if &m.Pet[0] == &cloneTestMessage.Pet[0] { - t.Error("Pet: repeated field not copied") - } - if &m.Others[0] == &cloneTestMessage.Others[0] { - t.Error("Others: repeated field not copied") - } - if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { - t.Error("Others[0].Value: bytes field not copied") - } - if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { - t.Error("RepBytes: repeated field not copied") - } - if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { - t.Error("RepBytes[0]: bytes field not copied") - } -} - -func TestCloneNil(t *testing.T) { - var m *pb.MyMessage - if c := proto.Clone(m); !proto.Equal(m, c) { - t.Errorf("Clone(%v) = %v", m, c) - } -} - -var mergeTests = []struct { - src, dst, want proto.Message -}{ - { - src: &pb.MyMessage{ - Count: proto.Int32(42), - }, - dst: &pb.MyMessage{ - Name: proto.String("Dave"), - }, - want: &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - }, - }, - { - src: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - }, - Pet: []string{"horsey"}, - Others: []*pb.OtherMessage{ - { - Value: []byte("some bytes"), - }, - }, - }, - dst: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("niles"), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - { - // Explicitly test a src=nil field - Inner: nil, - }, - }, - }, - want: &pb.MyMessage{ - Inner: &pb.InnerMessage{ - Host: proto.String("hey"), - Connected: proto.Bool(true), - Port: proto.Int32(9099), - }, - Pet: []string{"bunny", "kitty", "horsey"}, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(31415926535), - }, - {}, - { - Value: []byte("some bytes"), - }, - }, - }, - }, - { - src: &pb.MyMessage{ - RepBytes: [][]byte{[]byte("wow")}, - }, - dst: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham")}, - }, - want: &pb.MyMessage{ - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(6), - }, - RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, - }, - }, - // Check that a scalar bytes field replaces rather than appends. - { - src: &pb.OtherMessage{Value: []byte("foo")}, - dst: &pb.OtherMessage{Value: []byte("bar")}, - want: &pb.OtherMessage{Value: []byte("foo")}, - }, - { - src: &pb.MessageWithMap{ - NameMapping: map[int32]string{6: "Nigel"}, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - dst: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Bruce", // should be overwritten - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(3.0), - Exact: proto.Bool(true), - }, // the entire message should be overwritten - }, - }, - want: &pb.MessageWithMap{ - NameMapping: map[int32]string{ - 6: "Nigel", - 7: "Andrew", - }, - MsgMapping: map[int64]*pb.FloatingPoint{ - 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, - 0x4002: &pb.FloatingPoint{ - F: proto.Float64(2.0), - }, - }, - ByteMapping: map[bool][]byte{true: []byte("wowsa")}, - }, - }, - // proto3 shouldn't merge zero values, - // in the same way that proto2 shouldn't merge nils. - { - src: &proto3pb.Message{ - Name: "Aaron", - Data: []byte(""), // zero value, but not nil - }, - dst: &proto3pb.Message{ - HeightInCm: 176, - Data: []byte("texas!"), - }, - want: &proto3pb.Message{ - Name: "Aaron", - HeightInCm: 176, - Data: []byte("texas!"), - }, - }, - // Oneof fields should merge by assignment. - { - src: &pb.Communique{ - Union: &pb.Communique_Number{41}, - }, - dst: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Number{41}, - }, - }, - // Oneof nil is the same as not set. - { - src: &pb.Communique{}, - dst: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - want: &pb.Communique{ - Union: &pb.Communique_Name{"Bobby Tables"}, - }, - }, - { - src: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Cute: true}, // replace - "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, // insert - }, - }, - dst: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Bunny: "lost"}, // replaced - "kay_c": &proto3pb.Nested{Bunny: "bunny"}, // keep - }, - }, - want: &proto3pb.Message{ - Terrain: map[string]*proto3pb.Nested{ - "kay_a": &proto3pb.Nested{Cute: true}, - "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, - "kay_c": &proto3pb.Nested{Bunny: "bunny"}, - }, - }, - }, -} - -func TestMerge(t *testing.T) { - for _, m := range mergeTests { - got := proto.Clone(m.dst) - proto.Merge(got, m.src) - if !proto.Equal(got, m.want) { - t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go index aa207298f9..d9aa3c42d6 100644 --- a/vendor/github.com/golang/protobuf/proto/decode.go +++ b/vendor/github.com/golang/protobuf/proto/decode.go @@ -39,8 +39,6 @@ import ( "errors" "fmt" "io" - "os" - "reflect" ) // errOverflow is returned when an integer is too large to be represented. @@ -50,10 +48,6 @@ var errOverflow = errors.New("proto: integer overflow") // wire type is encountered. It does not get returned to user code. var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") -// The fundamental decoders that interpret bytes on the wire. -// Those that take integer types all return uint64 and are -// therefore of type valueDecoder. - // DecodeVarint reads a varint-encoded integer from the slice. // It returns the integer and the number of bytes consumed, or // zero if there is not enough. @@ -267,9 +261,6 @@ func (p *Buffer) DecodeZigzag32() (x uint64, err error) { return } -// These are not ValueDecoders: they produce an array of bytes or a string. -// bytes, embedded messages - // DecodeRawBytes reads a count-delimited byte buffer from the Buffer. // This is the format used for the bytes protocol buffer // type and for embedded messages. @@ -311,81 +302,29 @@ func (p *Buffer) DecodeStringBytes() (s string, err error) { return string(buf), nil } -// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. -// If the protocol buffer has extensions, and the field matches, add it as an extension. -// Otherwise, if the XXX_unrecognized field exists, append the skipped data there. -func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { - oi := o.index - - err := o.skip(t, tag, wire) - if err != nil { - return err - } - - if !unrecField.IsValid() { - return nil - } - - ptr := structPointer_Bytes(base, unrecField) - - // Add the skipped field to struct field - obuf := o.buf - - o.buf = *ptr - o.EncodeVarint(uint64(tag<<3 | wire)) - *ptr = append(o.buf, obuf[oi:o.index]...) - - o.buf = obuf - - return nil -} - -// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. -func (o *Buffer) skip(t reflect.Type, tag, wire int) error { - - var u uint64 - var err error - - switch wire { - case WireVarint: - _, err = o.DecodeVarint() - case WireFixed64: - _, err = o.DecodeFixed64() - case WireBytes: - _, err = o.DecodeRawBytes(false) - case WireFixed32: - _, err = o.DecodeFixed32() - case WireStartGroup: - for { - u, err = o.DecodeVarint() - if err != nil { - break - } - fwire := int(u & 0x7) - if fwire == WireEndGroup { - break - } - ftag := int(u >> 3) - err = o.skip(t, ftag, fwire) - if err != nil { - break - } - } - default: - err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) - } - return err -} - // Unmarshaler is the interface representing objects that can -// unmarshal themselves. The method should reset the receiver before -// decoding starts. The argument points to data that may be +// unmarshal themselves. The argument points to data that may be // overwritten, so implementations should not keep references to the // buffer. +// Unmarshal implementations should not clear the receiver. +// Any unmarshaled data should be merged into the receiver. +// Callers of Unmarshal that do not want to retain existing data +// should Reset the receiver before calling Unmarshal. type Unmarshaler interface { Unmarshal([]byte) error } +// newUnmarshaler is the interface representing objects that can +// unmarshal themselves. The semantics are identical to Unmarshaler. +// +// This exists to support protoc-gen-go generated messages. +// The proto package will stop type-asserting to this interface in the future. +// +// DO NOT DEPEND ON THIS. +type newUnmarshaler interface { + XXX_Unmarshal([]byte) error +} + // Unmarshal parses the protocol buffer representation in buf and places the // decoded result in pb. If the struct underlying pb does not match // the data in buf, the results can be unpredictable. @@ -395,7 +334,13 @@ type Unmarshaler interface { // to preserve and append to existing data. func Unmarshal(buf []byte, pb Message) error { pb.Reset() - return UnmarshalMerge(buf, pb) + if u, ok := pb.(newUnmarshaler); ok { + return u.XXX_Unmarshal(buf) + } + if u, ok := pb.(Unmarshaler); ok { + return u.Unmarshal(buf) + } + return NewBuffer(buf).Unmarshal(pb) } // UnmarshalMerge parses the protocol buffer representation in buf and @@ -405,8 +350,16 @@ func Unmarshal(buf []byte, pb Message) error { // UnmarshalMerge merges into existing data in pb. // Most code should use Unmarshal instead. func UnmarshalMerge(buf []byte, pb Message) error { - // If the object can unmarshal itself, let it. + if u, ok := pb.(newUnmarshaler); ok { + return u.XXX_Unmarshal(buf) + } if u, ok := pb.(Unmarshaler); ok { + // NOTE: The history of proto have unfortunately been inconsistent + // whether Unmarshaler should or should not implicitly clear itself. + // Some implementations do, most do not. + // Thus, calling this here may or may not do what people want. + // + // See https://github.com/golang/protobuf/issues/424 return u.Unmarshal(buf) } return NewBuffer(buf).Unmarshal(pb) @@ -422,12 +375,17 @@ func (p *Buffer) DecodeMessage(pb Message) error { } // DecodeGroup reads a tag-delimited group from the Buffer. +// StartGroup tag is already consumed. This function consumes +// EndGroup tag. func (p *Buffer) DecodeGroup(pb Message) error { - typ, base, err := getbase(pb) - if err != nil { - return err + b := p.buf[p.index:] + x, y := findEndGroup(b) + if x < 0 { + return io.ErrUnexpectedEOF } - return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base) + err := Unmarshal(b[:x], pb) + p.index += y + return err } // Unmarshal parses the protocol buffer representation in the @@ -438,533 +396,33 @@ func (p *Buffer) DecodeGroup(pb Message) error { // Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. func (p *Buffer) Unmarshal(pb Message) error { // If the object can unmarshal itself, let it. - if u, ok := pb.(Unmarshaler); ok { - err := u.Unmarshal(p.buf[p.index:]) + if u, ok := pb.(newUnmarshaler); ok { + err := u.XXX_Unmarshal(p.buf[p.index:]) p.index = len(p.buf) return err } - - typ, base, err := getbase(pb) - if err != nil { - return err - } - - err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) - - if collectStats { - stats.Decode++ - } - - return err -} - -// unmarshalType does the work of unmarshaling a structure. -func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { - var state errorState - required, reqFields := prop.reqCount, uint64(0) - - var err error - for err == nil && o.index < len(o.buf) { - oi := o.index - var u uint64 - u, err = o.DecodeVarint() - if err != nil { - break - } - wire := int(u & 0x7) - if wire == WireEndGroup { - if is_group { - if required > 0 { - // Not enough information to determine the exact field. - // (See below.) - return &RequiredNotSetError{"{Unknown}"} - } - return nil // input is satisfied - } - return fmt.Errorf("proto: %s: wiretype end group for non-group", st) - } - tag := int(u >> 3) - if tag <= 0 { - return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire) - } - fieldnum, ok := prop.decoderTags.get(tag) - if !ok { - // Maybe it's an extension? - if prop.extendable { - if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) { - if err = o.skip(st, tag, wire); err == nil { - extmap := e.extensionsWrite() - ext := extmap[int32(tag)] // may be missing - ext.enc = append(ext.enc, o.buf[oi:o.index]...) - extmap[int32(tag)] = ext - } - continue - } - } - // Maybe it's a oneof? - if prop.oneofUnmarshaler != nil { - m := structPointer_Interface(base, st).(Message) - // First return value indicates whether tag is a oneof field. - ok, err = prop.oneofUnmarshaler(m, tag, wire, o) - if err == ErrInternalBadWireType { - // Map the error to something more descriptive. - // Do the formatting here to save generated code space. - err = fmt.Errorf("bad wiretype for oneof field in %T", m) - } - if ok { - continue - } - } - err = o.skipAndSave(st, tag, wire, base, prop.unrecField) - continue - } - p := prop.Prop[fieldnum] - - if p.dec == nil { - fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) - continue - } - dec := p.dec - if wire != WireStartGroup && wire != p.WireType { - if wire == WireBytes && p.packedDec != nil { - // a packable field - dec = p.packedDec - } else { - err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) - continue - } - } - decErr := dec(o, p, base) - if decErr != nil && !state.shouldContinue(decErr, p) { - err = decErr - } - if err == nil && p.Required { - // Successfully decoded a required field. - if tag <= 64 { - // use bitmap for fields 1-64 to catch field reuse. - var mask uint64 = 1 << uint64(tag-1) - if reqFields&mask == 0 { - // new required field - reqFields |= mask - required-- - } - } else { - // This is imprecise. It can be fooled by a required field - // with a tag > 64 that is encoded twice; that's very rare. - // A fully correct implementation would require allocating - // a data structure, which we would like to avoid. - required-- - } - } - } - if err == nil { - if is_group { - return io.ErrUnexpectedEOF - } - if state.err != nil { - return state.err - } - if required > 0 { - // Not enough information to determine the exact field. If we use extra - // CPU, we could determine the field only if the missing required field - // has a tag <= 64 and we check reqFields. - return &RequiredNotSetError{"{Unknown}"} - } - } - return err -} - -// Individual type decoders -// For each, -// u is the decoded value, -// v is a pointer to the field (pointer) in the struct - -// Sizes of the pools to allocate inside the Buffer. -// The goal is modest amortization and allocation -// on at least 16-byte boundaries. -const ( - boolPoolSize = 16 - uint32PoolSize = 8 - uint64PoolSize = 4 -) - -// Decode a bool. -func (o *Buffer) dec_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - if len(o.bools) == 0 { - o.bools = make([]bool, boolPoolSize) - } - o.bools[0] = u != 0 - *structPointer_Bool(base, p.field) = &o.bools[0] - o.bools = o.bools[1:] - return nil -} - -func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - *structPointer_BoolVal(base, p.field) = u != 0 - return nil -} - -// Decode an int32. -func (o *Buffer) dec_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) - return nil -} - -func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u)) - return nil -} - -// Decode an int64. -func (o *Buffer) dec_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word64_Set(structPointer_Word64(base, p.field), o, u) - return nil -} - -func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word64Val_Set(structPointer_Word64Val(base, p.field), o, u) - return nil -} - -// Decode a string. -func (o *Buffer) dec_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - *structPointer_String(base, p.field) = &s - return nil -} - -func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - *structPointer_StringVal(base, p.field) = s - return nil -} - -// Decode a slice of bytes ([]byte). -func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - *structPointer_Bytes(base, p.field) = b - return nil -} - -// Decode a slice of bools ([]bool). -func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - v := structPointer_BoolSlice(base, p.field) - *v = append(*v, u != 0) - return nil -} - -// Decode a slice of bools ([]bool) in packed format. -func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { - v := structPointer_BoolSlice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded bools - fin := o.index + nb - if fin < o.index { - return errOverflow - } - - y := *v - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - y = append(y, u != 0) - } - - *v = y - return nil -} - -// Decode a slice of int32s ([]int32). -func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - structPointer_Word32Slice(base, p.field).Append(uint32(u)) - return nil -} - -// Decode a slice of int32s ([]int32) in packed format. -func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Slice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded int32s - - fin := o.index + nb - if fin < o.index { - return errOverflow - } - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - v.Append(uint32(u)) - } - return nil -} - -// Decode a slice of int64s ([]int64). -func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - - structPointer_Word64Slice(base, p.field).Append(u) - return nil -} - -// Decode a slice of int64s ([]int64) in packed format. -func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Slice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded int64s - - fin := o.index + nb - if fin < o.index { - return errOverflow - } - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - v.Append(u) - } - return nil -} - -// Decode a slice of strings ([]string). -func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - v := structPointer_StringSlice(base, p.field) - *v = append(*v, s) - return nil -} - -// Decode a slice of slice of bytes ([][]byte). -func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - v := structPointer_BytesSlice(base, p.field) - *v = append(*v, b) - return nil -} - -// Decode a map field. -func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { - raw, err := o.DecodeRawBytes(false) - if err != nil { - return err - } - oi := o.index // index at the end of this map entry - o.index -= len(raw) // move buffer back to start of map entry - - mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V - if mptr.Elem().IsNil() { - mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) - } - v := mptr.Elem() // map[K]V - - // Prepare addressable doubly-indirect placeholders for the key and value types. - // See enc_new_map for why. - keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K - keybase := toStructPointer(keyptr.Addr()) // **K - - var valbase structPointer - var valptr reflect.Value - switch p.mtype.Elem().Kind() { - case reflect.Slice: - // []byte - var dummy []byte - valptr = reflect.ValueOf(&dummy) // *[]byte - valbase = toStructPointer(valptr) // *[]byte - case reflect.Ptr: - // message; valptr is **Msg; need to allocate the intermediate pointer - valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V - valptr.Set(reflect.New(valptr.Type().Elem())) - valbase = toStructPointer(valptr) - default: - // everything else - valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V - valbase = toStructPointer(valptr.Addr()) // **V - } - - // Decode. - // This parses a restricted wire format, namely the encoding of a message - // with two fields. See enc_new_map for the format. - for o.index < oi { - // tagcode for key and value properties are always a single byte - // because they have tags 1 and 2. - tagcode := o.buf[o.index] - o.index++ - switch tagcode { - case p.mkeyprop.tagcode[0]: - if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil { - return err - } - case p.mvalprop.tagcode[0]: - if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil { - return err - } - default: - // TODO: Should we silently skip this instead? - return fmt.Errorf("proto: bad map data tag %d", raw[0]) - } - } - keyelem, valelem := keyptr.Elem(), valptr.Elem() - if !keyelem.IsValid() { - keyelem = reflect.Zero(p.mtype.Key()) - } - if !valelem.IsValid() { - valelem = reflect.Zero(p.mtype.Elem()) - } - - v.SetMapIndex(keyelem, valelem) - return nil -} - -// Decode a group. -func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { - bas := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(bas) { - // allocate new nested message - bas = toStructPointer(reflect.New(p.stype)) - structPointer_SetStructPointer(base, p.field, bas) - } - return o.unmarshalType(p.stype, p.sprop, true, bas) -} - -// Decode an embedded message. -func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { - raw, e := o.DecodeRawBytes(false) - if e != nil { - return e - } - - bas := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(bas) { - // allocate new nested message - bas = toStructPointer(reflect.New(p.stype)) - structPointer_SetStructPointer(base, p.field, bas) - } - - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - iv := structPointer_Interface(bas, p.stype) - return iv.(Unmarshaler).Unmarshal(raw) - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, false, bas) - o.buf = obuf - o.index = oi - - return err -} - -// Decode a slice of embedded messages. -func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { - return o.dec_slice_struct(p, false, base) -} - -// Decode a slice of embedded groups. -func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { - return o.dec_slice_struct(p, true, base) -} - -// Decode a slice of structs ([]*struct). -func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { - v := reflect.New(p.stype) - bas := toStructPointer(v) - structPointer_StructPointerSlice(base, p.field).Append(bas) - - if is_group { - err := o.unmarshalType(p.stype, p.sprop, is_group, bas) - return err - } - - raw, err := o.DecodeRawBytes(false) - if err != nil { + if u, ok := pb.(Unmarshaler); ok { + // NOTE: The history of proto have unfortunately been inconsistent + // whether Unmarshaler should or should not implicitly clear itself. + // Some implementations do, most do not. + // Thus, calling this here may or may not do what people want. + // + // See https://github.com/golang/protobuf/issues/424 + err := u.Unmarshal(p.buf[p.index:]) + p.index = len(p.buf) return err } - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - iv := v.Interface() - return iv.(Unmarshaler).Unmarshal(raw) - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, is_group, bas) - - o.buf = obuf - o.index = oi - + // Slow workaround for messages that aren't Unmarshalers. + // This includes some hand-coded .pb.go files and + // bootstrap protos. + // TODO: fix all of those and then add Unmarshal to + // the Message interface. Then: + // The cast above and code below can be deleted. + // The old unmarshaler can be deleted. + // Clients can call Unmarshal directly (can already do that, actually). + var info InternalMessageInfo + err := info.Unmarshal(pb, p.buf[p.index:]) + p.index = len(p.buf) return err } diff --git a/vendor/github.com/golang/protobuf/proto/decode_test.go b/vendor/github.com/golang/protobuf/proto/decode_test.go deleted file mode 100644 index 2c4c31d127..0000000000 --- a/vendor/github.com/golang/protobuf/proto/decode_test.go +++ /dev/null @@ -1,258 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -// +build go1.7 - -package proto_test - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - tpb "github.com/golang/protobuf/proto/proto3_proto" -) - -var ( - bytesBlackhole []byte - msgBlackhole = new(tpb.Message) -) - -// BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and -// 2 bytes long). -func BenchmarkVarint32ArraySmall(b *testing.B) { - for i := uint(1); i <= 10; i++ { - dist := genInt32Dist([7]int{0, 3, 1}, 1<>= 7 - if x == 0 { - break - } - } - return n + switch { + case x < 1<<7: + return 1 + case x < 1<<14: + return 2 + case x < 1<<21: + return 3 + case x < 1<<28: + return 4 + case x < 1<<35: + return 5 + case x < 1<<42: + return 6 + case x < 1<<49: + return 7 + case x < 1<<56: + return 8 + case x < 1<<63: + return 9 + } + return 10 } // EncodeFixed64 writes a 64-bit integer to the Buffer. @@ -149,10 +153,6 @@ func (p *Buffer) EncodeFixed64(x uint64) error { return nil } -func sizeFixed64(x uint64) int { - return 8 -} - // EncodeFixed32 writes a 32-bit integer to the Buffer. // This is the format for the // fixed32, sfixed32, and float protocol buffer types. @@ -165,20 +165,12 @@ func (p *Buffer) EncodeFixed32(x uint64) error { return nil } -func sizeFixed32(x uint64) int { - return 4 -} - // EncodeZigzag64 writes a zigzag-encoded 64-bit integer // to the Buffer. // This is the format used for the sint64 protocol buffer type. func (p *Buffer) EncodeZigzag64(x uint64) error { // use signed number to get arithmetic right shift. - return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63))) -} - -func sizeZigzag64(x uint64) int { - return sizeVarint((x << 1) ^ uint64((int64(x) >> 63))) + return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } // EncodeZigzag32 writes a zigzag-encoded 32-bit integer @@ -189,10 +181,6 @@ func (p *Buffer) EncodeZigzag32(x uint64) error { return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) } -func sizeZigzag32(x uint64) int { - return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - // EncodeRawBytes writes a count-delimited byte buffer to the Buffer. // This is the format used for the bytes protocol buffer // type and for embedded messages. @@ -202,11 +190,6 @@ func (p *Buffer) EncodeRawBytes(b []byte) error { return nil } -func sizeRawBytes(b []byte) int { - return sizeVarint(uint64(len(b))) + - len(b) -} - // EncodeStringBytes writes an encoded string to the Buffer. // This is the format used for the proto2 string type. func (p *Buffer) EncodeStringBytes(s string) error { @@ -215,319 +198,17 @@ func (p *Buffer) EncodeStringBytes(s string) error { return nil } -func sizeStringBytes(s string) int { - return sizeVarint(uint64(len(s))) + - len(s) -} - // Marshaler is the interface representing objects that can marshal themselves. type Marshaler interface { Marshal() ([]byte, error) } -// Marshal takes the protocol buffer -// and encodes it into the wire format, returning the data. -func Marshal(pb Message) ([]byte, error) { - // Can the object marshal itself? - if m, ok := pb.(Marshaler); ok { - return m.Marshal() - } - p := NewBuffer(nil) - err := p.Marshal(pb) - if p.buf == nil && err == nil { - // Return a non-nil slice on success. - return []byte{}, nil - } - return p.buf, err -} - // EncodeMessage writes the protocol buffer to the Buffer, // prefixed by a varint-encoded length. func (p *Buffer) EncodeMessage(pb Message) error { - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return ErrNil - } - if err == nil { - var state errorState - err = p.enc_len_struct(GetProperties(t.Elem()), base, &state) - } - return err -} - -// Marshal takes the protocol buffer -// and encodes it into the wire format, writing the result to the -// Buffer. -func (p *Buffer) Marshal(pb Message) error { - // Can the object marshal itself? - if m, ok := pb.(Marshaler); ok { - data, err := m.Marshal() - p.buf = append(p.buf, data...) - return err - } - - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return ErrNil - } - if err == nil { - err = p.enc_struct(GetProperties(t.Elem()), base) - } - - if collectStats { - (stats).Encode++ // Parens are to work around a goimports bug. - } - - if len(p.buf) > maxMarshalSize { - return ErrTooLarge - } - return err -} - -// Size returns the encoded size of a protocol buffer. -func Size(pb Message) (n int) { - // Can the object marshal itself? If so, Size is slow. - // TODO: add Size to Marshaler, or add a Sizer interface. - if m, ok := pb.(Marshaler); ok { - b, _ := m.Marshal() - return len(b) - } - - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return 0 - } - if err == nil { - n = size_struct(GetProperties(t.Elem()), base) - } - - if collectStats { - (stats).Size++ // Parens are to work around a goimports bug. - } - - return -} - -// Individual type encoders. - -// Encode a bool. -func (o *Buffer) enc_bool(p *Properties, base structPointer) error { - v := *structPointer_Bool(base, p.field) - if v == nil { - return ErrNil - } - x := 0 - if *v { - x = 1 - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error { - v := *structPointer_BoolVal(base, p.field) - if !v { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, 1) - return nil -} - -func size_bool(p *Properties, base structPointer) int { - v := *structPointer_Bool(base, p.field) - if v == nil { - return 0 - } - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -func size_proto3_bool(p *Properties, base structPointer) int { - v := *structPointer_BoolVal(base, p.field) - if !v && !p.oneof { - return 0 - } - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -// Encode an int32. -func (o *Buffer) enc_int32(p *Properties, base structPointer) error { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return ErrNil - } - x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_int32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return 0 - } - x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -func size_proto3_int32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode a uint32. -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return ErrNil - } - x := word32_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return 0 - } - x := word32_Get(v) - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -func size_proto3_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode an int64. -func (o *Buffer) enc_int64(p *Properties, base structPointer) error { - v := structPointer_Word64(base, p.field) - if word64_IsNil(v) { - return ErrNil - } - x := word64_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func size_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64(base, p.field) - if word64_IsNil(v) { - return 0 - } - x := word64_Get(v) - n += len(p.tagcode) - n += p.valSize(x) - return -} - -func size_proto3_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(x) - return -} - -// Encode a string. -func (o *Buffer) enc_string(p *Properties, base structPointer) error { - v := *structPointer_String(base, p.field) - if v == nil { - return ErrNil - } - x := *v - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(x) - return nil -} - -func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error { - v := *structPointer_StringVal(base, p.field) - if v == "" { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(v) - return nil -} - -func size_string(p *Properties, base structPointer) (n int) { - v := *structPointer_String(base, p.field) - if v == nil { - return 0 - } - x := *v - n += len(p.tagcode) - n += sizeStringBytes(x) - return -} - -func size_proto3_string(p *Properties, base structPointer) (n int) { - v := *structPointer_StringVal(base, p.field) - if v == "" && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeStringBytes(v) - return + siz := Size(pb) + p.EncodeVarint(uint64(siz)) + return p.Marshal(pb) } // All protocol buffer fields are nillable, but be careful. @@ -538,825 +219,3 @@ func isNil(v reflect.Value) bool { } return false } - -// Encode a message struct. -func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { - var state errorState - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return ErrNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return state.err - } - - o.buf = append(o.buf, p.tagcode...) - return o.enc_len_struct(p.sprop, structp, &state) -} - -func size_struct_message(p *Properties, base structPointer) int { - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return 0 - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n0 := len(p.tagcode) - n1 := sizeRawBytes(data) - return n0 + n1 - } - - n0 := len(p.tagcode) - n1 := size_struct(p.sprop, structp) - n2 := sizeVarint(uint64(n1)) // size of encoded length - return n0 + n1 + n2 -} - -// Encode a group struct. -func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error { - var state errorState - b := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(b) { - return ErrNil - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) - err := o.enc_struct(p.sprop, b) - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) - return state.err -} - -func size_struct_group(p *Properties, base structPointer) (n int) { - b := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(b) { - return 0 - } - - n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup)) - n += size_struct(p.sprop, b) - n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup)) - return -} - -// Encode a slice of bools ([]bool). -func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return ErrNil - } - for _, x := range s { - o.buf = append(o.buf, p.tagcode...) - v := uint64(0) - if x { - v = 1 - } - p.valEnc(o, v) - } - return nil -} - -func size_slice_bool(p *Properties, base structPointer) int { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return 0 - } - return l * (len(p.tagcode) + 1) // each bool takes exactly one byte -} - -// Encode a slice of bools ([]bool) in packed format. -func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(l)) // each bool takes exactly one byte - for _, x := range s { - v := uint64(0) - if x { - v = 1 - } - p.valEnc(o, v) - } - return nil -} - -func size_slice_packed_bool(p *Properties, base structPointer) (n int) { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return 0 - } - n += len(p.tagcode) - n += sizeVarint(uint64(l)) - n += l // each bool takes exactly one byte - return -} - -// Encode a slice of bytes ([]byte). -func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if s == nil { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(s) - return nil -} - -func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if len(s) == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(s) - return nil -} - -func size_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if s == nil && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeRawBytes(s) - return -} - -func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if len(s) == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeRawBytes(s) - return -} - -// Encode a slice of int32s ([]int32). -func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - p.valEnc(o, uint64(x)) - } - return nil -} - -func size_slice_int32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - n += p.valSize(uint64(x)) - } - return -} - -// Encode a slice of int32s ([]int32) in packed format. -func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - p.valEnc(buf, uint64(x)) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_int32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - bufSize += p.valSize(uint64(x)) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of uint32s ([]uint32). -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - x := s.Index(i) - p.valEnc(o, uint64(x)) - } - return nil -} - -func size_slice_uint32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - x := s.Index(i) - n += p.valSize(uint64(x)) - } - return -} - -// Encode a slice of uint32s ([]uint32) in packed format. -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - p.valEnc(buf, uint64(s.Index(i))) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_uint32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - bufSize += p.valSize(uint64(s.Index(i))) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of int64s ([]int64). -func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, s.Index(i)) - } - return nil -} - -func size_slice_int64(p *Properties, base structPointer) (n int) { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - n += p.valSize(s.Index(i)) - } - return -} - -// Encode a slice of int64s ([]int64) in packed format. -func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - p.valEnc(buf, s.Index(i)) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_int64(p *Properties, base structPointer) (n int) { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - bufSize += p.valSize(s.Index(i)) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of slice of bytes ([][]byte). -func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error { - ss := *structPointer_BytesSlice(base, p.field) - l := len(ss) - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(ss[i]) - } - return nil -} - -func size_slice_slice_byte(p *Properties, base structPointer) (n int) { - ss := *structPointer_BytesSlice(base, p.field) - l := len(ss) - if l == 0 { - return 0 - } - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - n += sizeRawBytes(ss[i]) - } - return -} - -// Encode a slice of strings ([]string). -func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error { - ss := *structPointer_StringSlice(base, p.field) - l := len(ss) - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(ss[i]) - } - return nil -} - -func size_slice_string(p *Properties, base structPointer) (n int) { - ss := *structPointer_StringSlice(base, p.field) - l := len(ss) - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - n += sizeStringBytes(ss[i]) - } - return -} - -// Encode a slice of message structs ([]*struct). -func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error { - var state errorState - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - for i := 0; i < l; i++ { - structp := s.Index(i) - if structPointer_IsNil(structp) { - return errRepeatedHasNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - continue - } - - o.buf = append(o.buf, p.tagcode...) - err := o.enc_len_struct(p.sprop, structp, &state) - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - } - return state.err -} - -func size_slice_struct_message(p *Properties, base structPointer) (n int) { - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - structp := s.Index(i) - if structPointer_IsNil(structp) { - return // return the size up to this point - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n += sizeRawBytes(data) - continue - } - - n0 := size_struct(p.sprop, structp) - n1 := sizeVarint(uint64(n0)) // size of encoded length - n += n0 + n1 - } - return -} - -// Encode a slice of group structs ([]*struct). -func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error { - var state errorState - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - for i := 0; i < l; i++ { - b := s.Index(i) - if structPointer_IsNil(b) { - return errRepeatedHasNil - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) - - err := o.enc_struct(p.sprop, b) - - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) - } - return state.err -} - -func size_slice_struct_group(p *Properties, base structPointer) (n int) { - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup)) - n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup)) - for i := 0; i < l; i++ { - b := s.Index(i) - if structPointer_IsNil(b) { - return // return size up to this point - } - - n += size_struct(p.sprop, b) - } - return -} - -// Encode an extension map. -func (o *Buffer) enc_map(p *Properties, base structPointer) error { - exts := structPointer_ExtMap(base, p.field) - if err := encodeExtensionsMap(*exts); err != nil { - return err - } - - return o.enc_map_body(*exts) -} - -func (o *Buffer) enc_exts(p *Properties, base structPointer) error { - exts := structPointer_Extensions(base, p.field) - - v, mu := exts.extensionsRead() - if v == nil { - return nil - } - - mu.Lock() - defer mu.Unlock() - if err := encodeExtensionsMap(v); err != nil { - return err - } - - return o.enc_map_body(v) -} - -func (o *Buffer) enc_map_body(v map[int32]Extension) error { - // Fast-path for common cases: zero or one extensions. - if len(v) <= 1 { - for _, e := range v { - o.buf = append(o.buf, e.enc...) - } - return nil - } - - // Sort keys to provide a deterministic encoding. - keys := make([]int, 0, len(v)) - for k := range v { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - o.buf = append(o.buf, v[int32(k)].enc...) - } - return nil -} - -func size_map(p *Properties, base structPointer) int { - v := structPointer_ExtMap(base, p.field) - return extensionsMapSize(*v) -} - -func size_exts(p *Properties, base structPointer) int { - v := structPointer_Extensions(base, p.field) - return extensionsSize(v) -} - -// Encode a map field. -func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { - var state errorState // XXX: or do we need to plumb this through? - - /* - A map defined as - map map_field = N; - is encoded in the same way as - message MapFieldEntry { - key_type key = 1; - value_type value = 2; - } - repeated MapFieldEntry map_field = N; - */ - - v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V - if v.Len() == 0 { - return nil - } - - keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) - - enc := func() error { - if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil { - return err - } - if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil { - return err - } - return nil - } - - // Don't sort map keys. It is not required by the spec, and C++ doesn't do it. - for _, key := range v.MapKeys() { - val := v.MapIndex(key) - - keycopy.Set(key) - valcopy.Set(val) - - o.buf = append(o.buf, p.tagcode...) - if err := o.enc_len_thing(enc, &state); err != nil { - return err - } - } - return nil -} - -func size_new_map(p *Properties, base structPointer) int { - v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V - - keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) - - n := 0 - for _, key := range v.MapKeys() { - val := v.MapIndex(key) - keycopy.Set(key) - valcopy.Set(val) - - // Tag codes for key and val are the responsibility of the sub-sizer. - keysize := p.mkeyprop.size(p.mkeyprop, keybase) - valsize := p.mvalprop.size(p.mvalprop, valbase) - entry := keysize + valsize - // Add on tag code and length of map entry itself. - n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry - } - return n -} - -// mapEncodeScratch returns a new reflect.Value matching the map's value type, -// and a structPointer suitable for passing to an encoder or sizer. -func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { - // Prepare addressable doubly-indirect placeholders for the key and value types. - // This is needed because the element-type encoders expect **T, but the map iteration produces T. - - keycopy = reflect.New(mapType.Key()).Elem() // addressable K - keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K - keyptr.Set(keycopy.Addr()) // - keybase = toStructPointer(keyptr.Addr()) // **K - - // Value types are more varied and require special handling. - switch mapType.Elem().Kind() { - case reflect.Slice: - // []byte - var dummy []byte - valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte - valbase = toStructPointer(valcopy.Addr()) - case reflect.Ptr: - // message; the generated field type is map[K]*Msg (so V is *Msg), - // so we only need one level of indirection. - valcopy = reflect.New(mapType.Elem()).Elem() // addressable V - valbase = toStructPointer(valcopy.Addr()) - default: - // everything else - valcopy = reflect.New(mapType.Elem()).Elem() // addressable V - valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V - valptr.Set(valcopy.Addr()) // - valbase = toStructPointer(valptr.Addr()) // **V - } - return -} - -// Encode a struct. -func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { - var state errorState - // Encode fields in tag order so that decoders may use optimizations - // that depend on the ordering. - // https://developers.google.com/protocol-buffers/docs/encoding#order - for _, i := range prop.order { - p := prop.Prop[i] - if p.enc != nil { - err := p.enc(o, p, base) - if err != nil { - if err == ErrNil { - if p.Required && state.err == nil { - state.err = &RequiredNotSetError{p.Name} - } - } else if err == errRepeatedHasNil { - // Give more context to nil values in repeated fields. - return errors.New("repeated field " + p.OrigName + " has nil element") - } else if !state.shouldContinue(err, p) { - return err - } - } - if len(o.buf) > maxMarshalSize { - return ErrTooLarge - } - } - } - - // Do oneof fields. - if prop.oneofMarshaler != nil { - m := structPointer_Interface(base, prop.stype).(Message) - if err := prop.oneofMarshaler(m, o); err == ErrNil { - return errOneofHasNil - } else if err != nil { - return err - } - } - - // Add unrecognized fields at the end. - if prop.unrecField.IsValid() { - v := *structPointer_Bytes(base, prop.unrecField) - if len(o.buf)+len(v) > maxMarshalSize { - return ErrTooLarge - } - if len(v) > 0 { - o.buf = append(o.buf, v...) - } - } - - return state.err -} - -func size_struct(prop *StructProperties, base structPointer) (n int) { - for _, i := range prop.order { - p := prop.Prop[i] - if p.size != nil { - n += p.size(p, base) - } - } - - // Add unrecognized fields at the end. - if prop.unrecField.IsValid() { - v := *structPointer_Bytes(base, prop.unrecField) - n += len(v) - } - - // Factor in any oneof fields. - if prop.oneofSizer != nil { - m := structPointer_Interface(base, prop.stype).(Message) - n += prop.oneofSizer(m) - } - - return -} - -var zeroes [20]byte // longer than any conceivable sizeVarint - -// Encode a struct, preceded by its encoded length (as a varint). -func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error { - return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state) -} - -// Encode something, preceded by its encoded length (as a varint). -func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error { - iLen := len(o.buf) - o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length - iMsg := len(o.buf) - err := enc() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - lMsg := len(o.buf) - iMsg - lLen := sizeVarint(uint64(lMsg)) - switch x := lLen - (iMsg - iLen); { - case x > 0: // actual length is x bytes larger than the space we reserved - // Move msg x bytes right. - o.buf = append(o.buf, zeroes[:x]...) - copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) - case x < 0: // actual length is x bytes smaller than the space we reserved - // Move msg x bytes left. - copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) - o.buf = o.buf[:len(o.buf)+x] // x is negative - } - // Encode the length in the reserved space. - o.buf = o.buf[:iLen] - o.EncodeVarint(uint64(lMsg)) - o.buf = o.buf[:len(o.buf)+lMsg] - return state.err -} - -// errorState maintains the first error that occurs and updates that error -// with additional context. -type errorState struct { - err error -} - -// shouldContinue reports whether encoding should continue upon encountering the -// given error. If the error is RequiredNotSetError, shouldContinue returns true -// and, if this is the first appearance of that error, remembers it for future -// reporting. -// -// If prop is not nil, it may update any error with additional context about the -// field with the error. -func (s *errorState) shouldContinue(err error, prop *Properties) bool { - // Ignore unset required fields. - reqNotSet, ok := err.(*RequiredNotSetError) - if !ok { - return false - } - if s.err == nil { - if prop != nil { - err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field} - } - s.err = err - } - return true -} diff --git a/vendor/github.com/golang/protobuf/proto/encode_test.go b/vendor/github.com/golang/protobuf/proto/encode_test.go deleted file mode 100644 index a7209475f1..0000000000 --- a/vendor/github.com/golang/protobuf/proto/encode_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -// +build go1.7 - -package proto_test - -import ( - "strconv" - "testing" - - "github.com/golang/protobuf/proto" - tpb "github.com/golang/protobuf/proto/proto3_proto" - "github.com/golang/protobuf/ptypes" -) - -var ( - blackhole []byte -) - -// BenchmarkAny creates increasingly large arbitrary Any messages. The type is always the -// same. -func BenchmarkAny(b *testing.B) { - data := make([]byte, 1<<20) - quantum := 1 << 10 - for i := uint(0); i <= 10; i++ { - b.Run(strconv.Itoa(quantum<= len(o.buf) { + if len(b) == 0 { break } } @@ -473,9 +429,9 @@ func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { // GetExtensions returns a slice of the extensions present in pb that are also listed in es. // The returned slice has the same length as es; missing extensions will appear as nil elements. func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { - epb, ok := extendable(pb) - if !ok { - return nil, errors.New("proto: not an extendable proto") + epb, err := extendable(pb) + if err != nil { + return nil, err } extensions = make([]interface{}, len(es)) for i, e := range es { @@ -494,9 +450,9 @@ func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, e // For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing // just the Field field, which defines the extension's field number. func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { - epb, ok := extendable(pb) - if !ok { - return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb) + epb, err := extendable(pb) + if err != nil { + return nil, err } registeredExtensions := RegisteredExtensions(pb) @@ -523,9 +479,9 @@ func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { // SetExtension sets the specified extension of pb to the specified value. func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { - epb, ok := extendable(pb) - if !ok { - return errors.New("proto: not an extendable proto") + epb, err := extendable(pb) + if err != nil { + return err } if err := checkExtensionTypes(epb, extension); err != nil { return err @@ -550,8 +506,8 @@ func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error // ClearAllExtensions clears all extensions from pb. func ClearAllExtensions(pb Message) { - epb, ok := extendable(pb) - if !ok { + epb, err := extendable(pb) + if err != nil { return } m := epb.extensionsWrite() diff --git a/vendor/github.com/golang/protobuf/proto/extensions_test.go b/vendor/github.com/golang/protobuf/proto/extensions_test.go deleted file mode 100644 index b6d9114c56..0000000000 --- a/vendor/github.com/golang/protobuf/proto/extensions_test.go +++ /dev/null @@ -1,536 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "bytes" - "fmt" - "reflect" - "sort" - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/proto/testdata" - "golang.org/x/sync/errgroup" -) - -func TestGetExtensionsWithMissingExtensions(t *testing.T) { - msg := &pb.MyMessage{} - ext1 := &pb.Ext{} - if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { - t.Fatalf("Could not set ext1: %s", err) - } - exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{ - pb.E_Ext_More, - pb.E_Ext_Text, - }) - if err != nil { - t.Fatalf("GetExtensions() failed: %s", err) - } - if exts[0] != ext1 { - t.Errorf("ext1 not in returned extensions: %T %v", exts[0], exts[0]) - } - if exts[1] != nil { - t.Errorf("ext2 in returned extensions: %T %v", exts[1], exts[1]) - } -} - -func TestExtensionDescsWithMissingExtensions(t *testing.T) { - msg := &pb.MyMessage{Count: proto.Int32(0)} - extdesc1 := pb.E_Ext_More - if descs, err := proto.ExtensionDescs(msg); len(descs) != 0 || err != nil { - t.Errorf("proto.ExtensionDescs: got %d descs, error %v; want 0, nil", len(descs), err) - } - - ext1 := &pb.Ext{} - if err := proto.SetExtension(msg, extdesc1, ext1); err != nil { - t.Fatalf("Could not set ext1: %s", err) - } - extdesc2 := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 123456789, - Name: "a.b", - Tag: "varint,123456789,opt", - } - ext2 := proto.Bool(false) - if err := proto.SetExtension(msg, extdesc2, ext2); err != nil { - t.Fatalf("Could not set ext2: %s", err) - } - - b, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("Could not marshal msg: %v", err) - } - if err := proto.Unmarshal(b, msg); err != nil { - t.Fatalf("Could not unmarshal into msg: %v", err) - } - - descs, err := proto.ExtensionDescs(msg) - if err != nil { - t.Fatalf("proto.ExtensionDescs: got error %v", err) - } - sortExtDescs(descs) - wantDescs := []*proto.ExtensionDesc{extdesc1, &proto.ExtensionDesc{Field: extdesc2.Field}} - if !reflect.DeepEqual(descs, wantDescs) { - t.Errorf("proto.ExtensionDescs(msg) sorted extension ids: got %+v, want %+v", descs, wantDescs) - } -} - -type ExtensionDescSlice []*proto.ExtensionDesc - -func (s ExtensionDescSlice) Len() int { return len(s) } -func (s ExtensionDescSlice) Less(i, j int) bool { return s[i].Field < s[j].Field } -func (s ExtensionDescSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -func sortExtDescs(s []*proto.ExtensionDesc) { - sort.Sort(ExtensionDescSlice(s)) -} - -func TestGetExtensionStability(t *testing.T) { - check := func(m *pb.MyMessage) bool { - ext1, err := proto.GetExtension(m, pb.E_Ext_More) - if err != nil { - t.Fatalf("GetExtension() failed: %s", err) - } - ext2, err := proto.GetExtension(m, pb.E_Ext_More) - if err != nil { - t.Fatalf("GetExtension() failed: %s", err) - } - return ext1 == ext2 - } - msg := &pb.MyMessage{Count: proto.Int32(4)} - ext0 := &pb.Ext{} - if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil { - t.Fatalf("Could not set ext1: %s", ext0) - } - if !check(msg) { - t.Errorf("GetExtension() not stable before marshaling") - } - bb, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("Marshal() failed: %s", err) - } - msg1 := &pb.MyMessage{} - err = proto.Unmarshal(bb, msg1) - if err != nil { - t.Fatalf("Unmarshal() failed: %s", err) - } - if !check(msg1) { - t.Errorf("GetExtension() not stable after unmarshaling") - } -} - -func TestGetExtensionDefaults(t *testing.T) { - var setFloat64 float64 = 1 - var setFloat32 float32 = 2 - var setInt32 int32 = 3 - var setInt64 int64 = 4 - var setUint32 uint32 = 5 - var setUint64 uint64 = 6 - var setBool = true - var setBool2 = false - var setString = "Goodnight string" - var setBytes = []byte("Goodnight bytes") - var setEnum = pb.DefaultsMessage_TWO - - type testcase struct { - ext *proto.ExtensionDesc // Extension we are testing. - want interface{} // Expected value of extension, or nil (meaning that GetExtension will fail). - def interface{} // Expected value of extension after ClearExtension(). - } - tests := []testcase{ - {pb.E_NoDefaultDouble, setFloat64, nil}, - {pb.E_NoDefaultFloat, setFloat32, nil}, - {pb.E_NoDefaultInt32, setInt32, nil}, - {pb.E_NoDefaultInt64, setInt64, nil}, - {pb.E_NoDefaultUint32, setUint32, nil}, - {pb.E_NoDefaultUint64, setUint64, nil}, - {pb.E_NoDefaultSint32, setInt32, nil}, - {pb.E_NoDefaultSint64, setInt64, nil}, - {pb.E_NoDefaultFixed32, setUint32, nil}, - {pb.E_NoDefaultFixed64, setUint64, nil}, - {pb.E_NoDefaultSfixed32, setInt32, nil}, - {pb.E_NoDefaultSfixed64, setInt64, nil}, - {pb.E_NoDefaultBool, setBool, nil}, - {pb.E_NoDefaultBool, setBool2, nil}, - {pb.E_NoDefaultString, setString, nil}, - {pb.E_NoDefaultBytes, setBytes, nil}, - {pb.E_NoDefaultEnum, setEnum, nil}, - {pb.E_DefaultDouble, setFloat64, float64(3.1415)}, - {pb.E_DefaultFloat, setFloat32, float32(3.14)}, - {pb.E_DefaultInt32, setInt32, int32(42)}, - {pb.E_DefaultInt64, setInt64, int64(43)}, - {pb.E_DefaultUint32, setUint32, uint32(44)}, - {pb.E_DefaultUint64, setUint64, uint64(45)}, - {pb.E_DefaultSint32, setInt32, int32(46)}, - {pb.E_DefaultSint64, setInt64, int64(47)}, - {pb.E_DefaultFixed32, setUint32, uint32(48)}, - {pb.E_DefaultFixed64, setUint64, uint64(49)}, - {pb.E_DefaultSfixed32, setInt32, int32(50)}, - {pb.E_DefaultSfixed64, setInt64, int64(51)}, - {pb.E_DefaultBool, setBool, true}, - {pb.E_DefaultBool, setBool2, true}, - {pb.E_DefaultString, setString, "Hello, string"}, - {pb.E_DefaultBytes, setBytes, []byte("Hello, bytes")}, - {pb.E_DefaultEnum, setEnum, pb.DefaultsMessage_ONE}, - } - - checkVal := func(test testcase, msg *pb.DefaultsMessage, valWant interface{}) error { - val, err := proto.GetExtension(msg, test.ext) - if err != nil { - if valWant != nil { - return fmt.Errorf("GetExtension(): %s", err) - } - if want := proto.ErrMissingExtension; err != want { - return fmt.Errorf("Unexpected error: got %v, want %v", err, want) - } - return nil - } - - // All proto2 extension values are either a pointer to a value or a slice of values. - ty := reflect.TypeOf(val) - tyWant := reflect.TypeOf(test.ext.ExtensionType) - if got, want := ty, tyWant; got != want { - return fmt.Errorf("unexpected reflect.TypeOf(): got %v want %v", got, want) - } - tye := ty.Elem() - tyeWant := tyWant.Elem() - if got, want := tye, tyeWant; got != want { - return fmt.Errorf("unexpected reflect.TypeOf().Elem(): got %v want %v", got, want) - } - - // Check the name of the type of the value. - // If it is an enum it will be type int32 with the name of the enum. - if got, want := tye.Name(), tye.Name(); got != want { - return fmt.Errorf("unexpected reflect.TypeOf().Elem().Name(): got %v want %v", got, want) - } - - // Check that value is what we expect. - // If we have a pointer in val, get the value it points to. - valExp := val - if ty.Kind() == reflect.Ptr { - valExp = reflect.ValueOf(val).Elem().Interface() - } - if got, want := valExp, valWant; !reflect.DeepEqual(got, want) { - return fmt.Errorf("unexpected reflect.DeepEqual(): got %v want %v", got, want) - } - - return nil - } - - setTo := func(test testcase) interface{} { - setTo := reflect.ValueOf(test.want) - if typ := reflect.TypeOf(test.ext.ExtensionType); typ.Kind() == reflect.Ptr { - setTo = reflect.New(typ).Elem() - setTo.Set(reflect.New(setTo.Type().Elem())) - setTo.Elem().Set(reflect.ValueOf(test.want)) - } - return setTo.Interface() - } - - for _, test := range tests { - msg := &pb.DefaultsMessage{} - name := test.ext.Name - - // Check the initial value. - if err := checkVal(test, msg, test.def); err != nil { - t.Errorf("%s: %v", name, err) - } - - // Set the per-type value and check value. - name = fmt.Sprintf("%s (set to %T %v)", name, test.want, test.want) - if err := proto.SetExtension(msg, test.ext, setTo(test)); err != nil { - t.Errorf("%s: SetExtension(): %v", name, err) - continue - } - if err := checkVal(test, msg, test.want); err != nil { - t.Errorf("%s: %v", name, err) - continue - } - - // Set and check the value. - name += " (cleared)" - proto.ClearExtension(msg, test.ext) - if err := checkVal(test, msg, test.def); err != nil { - t.Errorf("%s: %v", name, err) - } - } -} - -func TestExtensionsRoundTrip(t *testing.T) { - msg := &pb.MyMessage{} - ext1 := &pb.Ext{ - Data: proto.String("hi"), - } - ext2 := &pb.Ext{ - Data: proto.String("there"), - } - exists := proto.HasExtension(msg, pb.E_Ext_More) - if exists { - t.Error("Extension More present unexpectedly") - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { - t.Error(err) - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil { - t.Error(err) - } - e, err := proto.GetExtension(msg, pb.E_Ext_More) - if err != nil { - t.Error(err) - } - x, ok := e.(*pb.Ext) - if !ok { - t.Errorf("e has type %T, expected testdata.Ext", e) - } else if *x.Data != "there" { - t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x) - } - proto.ClearExtension(msg, pb.E_Ext_More) - if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension { - t.Errorf("got %v, expected ErrMissingExtension", e) - } - if _, err := proto.GetExtension(msg, pb.E_X215); err == nil { - t.Error("expected bad extension error, got nil") - } - if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil { - t.Error("expected extension err") - } - if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil { - t.Error("expected some sort of type mismatch error, got nil") - } -} - -func TestNilExtension(t *testing.T) { - msg := &pb.MyMessage{ - Count: proto.Int32(1), - } - if err := proto.SetExtension(msg, pb.E_Ext_Text, proto.String("hello")); err != nil { - t.Fatal(err) - } - if err := proto.SetExtension(msg, pb.E_Ext_More, (*pb.Ext)(nil)); err == nil { - t.Error("expected SetExtension to fail due to a nil extension") - } else if want := "proto: SetExtension called with nil value of type *testdata.Ext"; err.Error() != want { - t.Errorf("expected error %v, got %v", want, err) - } - // Note: if the behavior of Marshal is ever changed to ignore nil extensions, update - // this test to verify that E_Ext_Text is properly propagated through marshal->unmarshal. -} - -func TestMarshalUnmarshalRepeatedExtension(t *testing.T) { - // Add a repeated extension to the result. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - // Marshal message with a repeated extension. - msg1 := new(pb.OtherMessage) - err := proto.SetExtension(msg1, pb.E_RComplex, test.ext) - if err != nil { - t.Fatalf("[%s] Error setting extension: %v", test.name, err) - } - b, err := proto.Marshal(msg1) - if err != nil { - t.Fatalf("[%s] Error marshaling message: %v", test.name, err) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err = proto.Unmarshal(b, msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_RComplex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.([]*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(ext, test.ext) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, test.ext) - } - } -} - -func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) { - // We may see multiple instances of the same extension in the wire - // format. For example, the proto compiler may encode custom options in - // this way. Here, we verify that we merge the extensions together. - tests := []struct { - name string - ext []*pb.ComplexExtension - }{ - { - "two fields", - []*pb.ComplexExtension{ - {First: proto.Int32(7)}, - {Second: proto.Int32(11)}, - }, - }, - { - "repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {Third: []int32{2000}}, - }, - }, - { - "two fields and repeated field", - []*pb.ComplexExtension{ - {Third: []int32{1000}}, - {First: proto.Int32(9)}, - {Second: proto.Int32(21)}, - {Third: []int32{2000}}, - }, - }, - } - for _, test := range tests { - var buf bytes.Buffer - var want pb.ComplexExtension - - // Generate a serialized representation of a repeated extension - // by catenating bytes together. - for i, e := range test.ext { - // Merge to create the wanted proto. - proto.Merge(&want, e) - - // serialize the message - msg := new(pb.OtherMessage) - err := proto.SetExtension(msg, pb.E_Complex, e) - if err != nil { - t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err) - } - b, err := proto.Marshal(msg) - if err != nil { - t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err) - } - buf.Write(b) - } - - // Unmarshal and read the merged proto. - msg2 := new(pb.OtherMessage) - err := proto.Unmarshal(buf.Bytes(), msg2) - if err != nil { - t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) - } - e, err := proto.GetExtension(msg2, pb.E_Complex) - if err != nil { - t.Fatalf("[%s] Error getting extension: %v", test.name, err) - } - ext := e.(*pb.ComplexExtension) - if ext == nil { - t.Fatalf("[%s] Invalid extension", test.name) - } - if !reflect.DeepEqual(*ext, want) { - t.Errorf("[%s] Wrong value for ComplexExtension: got: %s want: %s\n", test.name, ext, want) - } - } -} - -func TestClearAllExtensions(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - m := &pb.MyMessage{} - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - if !proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got false, want true", proto.MarshalTextString(m)) - } - proto.ClearAllExtensions(m) - if proto.HasExtension(m, desc) { - t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m)) - } -} - -func TestMarshalRace(t *testing.T) { - // unregistered extension - desc := &proto.ExtensionDesc{ - ExtendedType: (*pb.MyMessage)(nil), - ExtensionType: (*bool)(nil), - Field: 101010100, - Name: "emptyextension", - Tag: "varint,0,opt", - } - - m := &pb.MyMessage{Count: proto.Int32(4)} - if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil { - t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err) - } - - var g errgroup.Group - for n := 3; n > 0; n-- { - g.Go(func() error { - _, err := proto.Marshal(m) - return err - }) - } - if err := g.Wait(); err != nil { - t.Fatal(err) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go index 1c225504a0..0e2191b8ad 100644 --- a/vendor/github.com/golang/protobuf/proto/lib.go +++ b/vendor/github.com/golang/protobuf/proto/lib.go @@ -265,6 +265,7 @@ package proto import ( "encoding/json" + "errors" "fmt" "log" "reflect" @@ -273,6 +274,8 @@ import ( "sync" ) +var errInvalidUTF8 = errors.New("proto: invalid UTF-8 string") + // Message is implemented by generated protocol buffer messages. type Message interface { Reset() @@ -309,16 +312,7 @@ type Buffer struct { buf []byte // encode/decode byte stream index int // read point - // pools of basic types to amortize allocation. - bools []bool - uint32s []uint32 - uint64s []uint64 - - // extra pools, only used with pointer_reflect.go - int32s []int32 - int64s []int64 - float32s []float32 - float64s []float64 + deterministic bool } // NewBuffer allocates a new Buffer and initializes its internal data to @@ -343,6 +337,30 @@ func (p *Buffer) SetBuf(s []byte) { // Bytes returns the contents of the Buffer. func (p *Buffer) Bytes() []byte { return p.buf } +// SetDeterministic sets whether to use deterministic serialization. +// +// Deterministic serialization guarantees that for a given binary, equal +// messages will always be serialized to the same bytes. This implies: +// +// - Repeated serialization of a message will return the same bytes. +// - Different processes of the same binary (which may be executing on +// different machines) will serialize equal messages to the same bytes. +// +// Note that the deterministic serialization is NOT canonical across +// languages. It is not guaranteed to remain stable over time. It is unstable +// across different builds with schema changes due to unknown fields. +// Users who need canonical serialization (e.g., persistent storage in a +// canonical form, fingerprinting, etc.) should define their own +// canonicalization specification and implement their own serializer rather +// than relying on this API. +// +// If deterministic serialization is requested, map entries will be sorted +// by keys in lexographical order. This is an implementation detail and +// subject to change. +func (p *Buffer) SetDeterministic(deterministic bool) { + p.deterministic = deterministic +} + /* * Helper routines for simplifying the creation of optional fields of basic type. */ @@ -831,22 +849,12 @@ func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMes return sf, false, nil } +// mapKeys returns a sort.Interface to be used for sorting the map keys. // Map fields may have key types of non-float scalars, strings and enums. -// The easiest way to sort them in some deterministic order is to use fmt. -// If this turns out to be inefficient we can always consider other options, -// such as doing a Schwartzian transform. - func mapKeys(vs []reflect.Value) sort.Interface { - s := mapKeySorter{ - vs: vs, - // default Less function: textual comparison - less: func(a, b reflect.Value) bool { - return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface()) - }, - } + s := mapKeySorter{vs: vs} - // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps; - // numeric keys are sorted numerically. + // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps. if len(vs) == 0 { return s } @@ -855,6 +863,12 @@ func mapKeys(vs []reflect.Value) sort.Interface { s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } case reflect.Uint32, reflect.Uint64: s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } + case reflect.Bool: + s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true + case reflect.String: + s.less = func(a, b reflect.Value) bool { return a.String() < b.String() } + default: + panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind())) } return s @@ -895,3 +909,13 @@ const ProtoPackageIsVersion2 = true // ProtoPackageIsVersion1 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const ProtoPackageIsVersion1 = true + +// InternalMessageInfo is a type used internally by generated .pb.go files. +// This type is not intended to be used by non-generated code. +// This type is not subject to any compatibility guarantee. +type InternalMessageInfo struct { + marshal *marshalInfo + unmarshal *unmarshalInfo + merge *mergeInfo + discard *discardInfo +} diff --git a/vendor/github.com/golang/protobuf/proto/map_test.go b/vendor/github.com/golang/protobuf/proto/map_test.go deleted file mode 100644 index 313e879245..0000000000 --- a/vendor/github.com/golang/protobuf/proto/map_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package proto_test - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - ppb "github.com/golang/protobuf/proto/proto3_proto" -) - -func marshalled() []byte { - m := &ppb.IntMaps{} - for i := 0; i < 1000; i++ { - m.Maps = append(m.Maps, &ppb.IntMap{ - Rtt: map[int32]int32{1: 2}, - }) - } - b, err := proto.Marshal(m) - if err != nil { - panic(fmt.Sprintf("Can't marshal %+v: %v", m, err)) - } - return b -} - -func BenchmarkConcurrentMapUnmarshal(b *testing.B) { - in := marshalled() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } - }) -} - -func BenchmarkSequentialMapUnmarshal(b *testing.B) { - in := marshalled() - b.ResetTimer() - for i := 0; i < b.N; i++ { - var out ppb.IntMaps - if err := proto.Unmarshal(in, &out); err != nil { - b.Errorf("Can't unmarshal ppb.IntMaps: %v", err) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go index fd982decd6..3b6ca41d5e 100644 --- a/vendor/github.com/golang/protobuf/proto/message_set.go +++ b/vendor/github.com/golang/protobuf/proto/message_set.go @@ -42,6 +42,7 @@ import ( "fmt" "reflect" "sort" + "sync" ) // errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. @@ -94,10 +95,7 @@ func (ms *messageSet) find(pb Message) *_MessageSet_Item { } func (ms *messageSet) Has(pb Message) bool { - if ms.find(pb) != nil { - return true - } - return false + return ms.find(pb) != nil } func (ms *messageSet) Unmarshal(pb Message) error { @@ -150,46 +148,42 @@ func skipVarint(buf []byte) []byte { // MarshalMessageSet encodes the extension map represented by m in the message set wire format. // It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. func MarshalMessageSet(exts interface{}) ([]byte, error) { - var m map[int32]Extension + return marshalMessageSet(exts, false) +} + +// marshaMessageSet implements above function, with the opt to turn on / off deterministic during Marshal. +func marshalMessageSet(exts interface{}, deterministic bool) ([]byte, error) { switch exts := exts.(type) { case *XXX_InternalExtensions: - if err := encodeExtensions(exts); err != nil { - return nil, err - } - m, _ = exts.extensionsRead() + var u marshalInfo + siz := u.sizeMessageSet(exts) + b := make([]byte, 0, siz) + return u.appendMessageSet(b, exts, deterministic) + case map[int32]Extension: - if err := encodeExtensionsMap(exts); err != nil { - return nil, err + // This is an old-style extension map. + // Wrap it in a new-style XXX_InternalExtensions. + ie := XXX_InternalExtensions{ + p: &struct { + mu sync.Mutex + extensionMap map[int32]Extension + }{ + extensionMap: exts, + }, } - m = exts + + var u marshalInfo + siz := u.sizeMessageSet(&ie) + b := make([]byte, 0, siz) + return u.appendMessageSet(b, &ie, deterministic) + default: return nil, errors.New("proto: not an extension map") } - - // Sort extension IDs to provide a deterministic encoding. - // See also enc_map in encode.go. - ids := make([]int, 0, len(m)) - for id := range m { - ids = append(ids, int(id)) - } - sort.Ints(ids) - - ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))} - for _, id := range ids { - e := m[int32(id)] - // Remove the wire type and field number varint, as well as the length varint. - msg := skipVarint(skipVarint(e.enc)) - - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: Int32(int32(id)), - Message: msg, - }) - } - return Marshal(ms) } // UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. -// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. +// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. func UnmarshalMessageSet(buf []byte, exts interface{}) error { var m map[int32]Extension switch exts := exts.(type) { @@ -235,7 +229,15 @@ func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { var m map[int32]Extension switch exts := exts.(type) { case *XXX_InternalExtensions: - m, _ = exts.extensionsRead() + var mu sync.Locker + m, mu = exts.extensionsRead() + if m != nil { + // Keep the extensions map locked until we're done marshaling to prevent + // races between marshaling and unmarshaling the lazily-{en,de}coded + // values. + mu.Lock() + defer mu.Unlock() + } case map[int32]Extension: m = exts default: @@ -253,15 +255,16 @@ func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { for i, id := range ids { ext := m[id] - if i > 0 { - b.WriteByte(',') - } - msd, ok := messageSetMap[id] if !ok { // Unknown type; we can't render it, so skip it. continue } + + if i > 0 && b.Len() > 1 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `"[%s]":`, msd.name) x := ext.value diff --git a/vendor/github.com/golang/protobuf/proto/message_set_test.go b/vendor/github.com/golang/protobuf/proto/message_set_test.go deleted file mode 100644 index 353a3ea769..0000000000 --- a/vendor/github.com/golang/protobuf/proto/message_set_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import ( - "bytes" - "testing" -) - -func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { - // Check that a repeated message set entry will be concatenated. - in := &messageSet{ - Item: []*_MessageSet_Item{ - {TypeId: Int32(12345), Message: []byte("hoo")}, - {TypeId: Int32(12345), Message: []byte("hah")}, - }, - } - b, err := Marshal(in) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - t.Logf("Marshaled bytes: %q", b) - - var extensions XXX_InternalExtensions - if err := UnmarshalMessageSet(b, &extensions); err != nil { - t.Fatalf("UnmarshalMessageSet: %v", err) - } - ext, ok := extensions.p.extensionMap[12345] - if !ok { - t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap) - } - // Skip wire type/field number and length varints. - got := skipVarint(skipVarint(ext.enc)) - if want := []byte("hoohah"); !bytes.Equal(got, want) { - t.Errorf("Combined extension is %q, want %q", got, want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go index fb512e2e16..b6cad90834 100644 --- a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go +++ b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go @@ -29,7 +29,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +build appengine js +// +build purego appengine js // This file contains an implementation of proto field accesses using package reflect. // It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can @@ -38,32 +38,13 @@ package proto import ( - "math" "reflect" + "sync" ) -// A structPointer is a pointer to a struct. -type structPointer struct { - v reflect.Value -} - -// toStructPointer returns a structPointer equivalent to the given reflect value. -// The reflect value must itself be a pointer to a struct. -func toStructPointer(v reflect.Value) structPointer { - return structPointer{v} -} - -// IsNil reports whether p is nil. -func structPointer_IsNil(p structPointer) bool { - return p.v.IsNil() -} +const unsafeAllowed = false -// Interface returns the struct pointer as an interface value. -func structPointer_Interface(p structPointer, _ reflect.Type) interface{} { - return p.v.Interface() -} - -// A field identifies a field in a struct, accessible from a structPointer. +// A field identifies a field in a struct, accessible from a pointer. // In this implementation, a field is identified by the sequence of field indices // passed to reflect's FieldByIndex. type field []int @@ -76,409 +57,301 @@ func toField(f *reflect.StructField) field { // invalidField is an invalid field identifier. var invalidField = field(nil) +// zeroField is a noop when calling pointer.offset. +var zeroField = field([]int{}) + // IsValid reports whether the field identifier is valid. func (f field) IsValid() bool { return f != nil } -// field returns the given field in the struct as a reflect value. -func structPointer_field(p structPointer, f field) reflect.Value { - // Special case: an extension map entry with a value of type T - // passes a *T to the struct-handling code with a zero field, - // expecting that it will be treated as equivalent to *struct{ X T }, - // which has the same memory layout. We have to handle that case - // specially, because reflect will panic if we call FieldByIndex on a - // non-struct. - if f == nil { - return p.v.Elem() - } - - return p.v.Elem().FieldByIndex(f) +// The pointer type is for the table-driven decoder. +// The implementation here uses a reflect.Value of pointer type to +// create a generic pointer. In pointer_unsafe.go we use unsafe +// instead of reflect to implement the same (but faster) interface. +type pointer struct { + v reflect.Value } -// ifield returns the given field in the struct as an interface value. -func structPointer_ifield(p structPointer, f field) interface{} { - return structPointer_field(p, f).Addr().Interface() +// toPointer converts an interface of pointer type to a pointer +// that points to the same target. +func toPointer(i *Message) pointer { + return pointer{v: reflect.ValueOf(*i)} } -// Bytes returns the address of a []byte field in the struct. -func structPointer_Bytes(p structPointer, f field) *[]byte { - return structPointer_ifield(p, f).(*[]byte) +// toAddrPointer converts an interface to a pointer that points to +// the interface data. +func toAddrPointer(i *interface{}, isptr bool) pointer { + v := reflect.ValueOf(*i) + u := reflect.New(v.Type()) + u.Elem().Set(v) + return pointer{v: u} } -// BytesSlice returns the address of a [][]byte field in the struct. -func structPointer_BytesSlice(p structPointer, f field) *[][]byte { - return structPointer_ifield(p, f).(*[][]byte) +// valToPointer converts v to a pointer. v must be of pointer type. +func valToPointer(v reflect.Value) pointer { + return pointer{v: v} } -// Bool returns the address of a *bool field in the struct. -func structPointer_Bool(p structPointer, f field) **bool { - return structPointer_ifield(p, f).(**bool) +// offset converts from a pointer to a structure to a pointer to +// one of its fields. +func (p pointer) offset(f field) pointer { + return pointer{v: p.v.Elem().FieldByIndex(f).Addr()} } -// BoolVal returns the address of a bool field in the struct. -func structPointer_BoolVal(p structPointer, f field) *bool { - return structPointer_ifield(p, f).(*bool) +func (p pointer) isNil() bool { + return p.v.IsNil() } -// BoolSlice returns the address of a []bool field in the struct. -func structPointer_BoolSlice(p structPointer, f field) *[]bool { - return structPointer_ifield(p, f).(*[]bool) +// grow updates the slice s in place to make it one element longer. +// s must be addressable. +// Returns the (addressable) new element. +func grow(s reflect.Value) reflect.Value { + n, m := s.Len(), s.Cap() + if n < m { + s.SetLen(n + 1) + } else { + s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem()))) + } + return s.Index(n) } -// String returns the address of a *string field in the struct. -func structPointer_String(p structPointer, f field) **string { - return structPointer_ifield(p, f).(**string) +func (p pointer) toInt64() *int64 { + return p.v.Interface().(*int64) } - -// StringVal returns the address of a string field in the struct. -func structPointer_StringVal(p structPointer, f field) *string { - return structPointer_ifield(p, f).(*string) +func (p pointer) toInt64Ptr() **int64 { + return p.v.Interface().(**int64) } - -// StringSlice returns the address of a []string field in the struct. -func structPointer_StringSlice(p structPointer, f field) *[]string { - return structPointer_ifield(p, f).(*[]string) +func (p pointer) toInt64Slice() *[]int64 { + return p.v.Interface().(*[]int64) } -// Extensions returns the address of an extension map field in the struct. -func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { - return structPointer_ifield(p, f).(*XXX_InternalExtensions) -} +var int32ptr = reflect.TypeOf((*int32)(nil)) -// ExtMap returns the address of an extension map field in the struct. -func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { - return structPointer_ifield(p, f).(*map[int32]Extension) +func (p pointer) toInt32() *int32 { + return p.v.Convert(int32ptr).Interface().(*int32) } -// NewAt returns the reflect.Value for a pointer to a field in the struct. -func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { - return structPointer_field(p, f).Addr() +// The toInt32Ptr/Slice methods don't work because of enums. +// Instead, we must use set/get methods for the int32ptr/slice case. +/* + func (p pointer) toInt32Ptr() **int32 { + return p.v.Interface().(**int32) } - -// SetStructPointer writes a *struct field in the struct. -func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { - structPointer_field(p, f).Set(q.v) + func (p pointer) toInt32Slice() *[]int32 { + return p.v.Interface().(*[]int32) } - -// GetStructPointer reads a *struct field in the struct. -func structPointer_GetStructPointer(p structPointer, f field) structPointer { - return structPointer{structPointer_field(p, f)} +*/ +func (p pointer) getInt32Ptr() *int32 { + if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { + // raw int32 type + return p.v.Elem().Interface().(*int32) + } + // an enum + return p.v.Elem().Convert(int32PtrType).Interface().(*int32) +} +func (p pointer) setInt32Ptr(v int32) { + // Allocate value in a *int32. Possibly convert that to a *enum. + // Then assign it to a **int32 or **enum. + // Note: we can convert *int32 to *enum, but we can't convert + // **int32 to **enum! + p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem())) +} + +// getInt32Slice copies []int32 from p as a new slice. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) getInt32Slice() []int32 { + if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { + // raw int32 type + return p.v.Elem().Interface().([]int32) + } + // an enum + // Allocate a []int32, then assign []enum's values into it. + // Note: we can't convert []enum to []int32. + slice := p.v.Elem() + s := make([]int32, slice.Len()) + for i := 0; i < slice.Len(); i++ { + s[i] = int32(slice.Index(i).Int()) + } + return s } -// StructPointerSlice the address of a []*struct field in the struct. -func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice { - return structPointerSlice{structPointer_field(p, f)} +// setInt32Slice copies []int32 into p as a new slice. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) setInt32Slice(v []int32) { + if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) { + // raw int32 type + p.v.Elem().Set(reflect.ValueOf(v)) + return + } + // an enum + // Allocate a []enum, then assign []int32's values into it. + // Note: we can't convert []enum to []int32. + slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v)) + for i, x := range v { + slice.Index(i).SetInt(int64(x)) + } + p.v.Elem().Set(slice) } - -// A structPointerSlice represents the address of a slice of pointers to structs -// (themselves messages or groups). That is, v.Type() is *[]*struct{...}. -type structPointerSlice struct { - v reflect.Value +func (p pointer) appendInt32Slice(v int32) { + grow(p.v.Elem()).SetInt(int64(v)) } -func (p structPointerSlice) Len() int { return p.v.Len() } -func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} } -func (p structPointerSlice) Append(q structPointer) { - p.v.Set(reflect.Append(p.v, q.v)) +func (p pointer) toUint64() *uint64 { + return p.v.Interface().(*uint64) } - -var ( - int32Type = reflect.TypeOf(int32(0)) - uint32Type = reflect.TypeOf(uint32(0)) - float32Type = reflect.TypeOf(float32(0)) - int64Type = reflect.TypeOf(int64(0)) - uint64Type = reflect.TypeOf(uint64(0)) - float64Type = reflect.TypeOf(float64(0)) -) - -// A word32 represents a field of type *int32, *uint32, *float32, or *enum. -// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable. -type word32 struct { - v reflect.Value +func (p pointer) toUint64Ptr() **uint64 { + return p.v.Interface().(**uint64) } - -// IsNil reports whether p is nil. -func word32_IsNil(p word32) bool { - return p.v.IsNil() +func (p pointer) toUint64Slice() *[]uint64 { + return p.v.Interface().(*[]uint64) } - -// Set sets p to point at a newly allocated word with bits set to x. -func word32_Set(p word32, o *Buffer, x uint32) { - t := p.v.Type().Elem() - switch t { - case int32Type: - if len(o.int32s) == 0 { - o.int32s = make([]int32, uint32PoolSize) - } - o.int32s[0] = int32(x) - p.v.Set(reflect.ValueOf(&o.int32s[0])) - o.int32s = o.int32s[1:] - return - case uint32Type: - if len(o.uint32s) == 0 { - o.uint32s = make([]uint32, uint32PoolSize) - } - o.uint32s[0] = x - p.v.Set(reflect.ValueOf(&o.uint32s[0])) - o.uint32s = o.uint32s[1:] - return - case float32Type: - if len(o.float32s) == 0 { - o.float32s = make([]float32, uint32PoolSize) - } - o.float32s[0] = math.Float32frombits(x) - p.v.Set(reflect.ValueOf(&o.float32s[0])) - o.float32s = o.float32s[1:] - return - } - - // must be enum - p.v.Set(reflect.New(t)) - p.v.Elem().SetInt(int64(int32(x))) +func (p pointer) toUint32() *uint32 { + return p.v.Interface().(*uint32) } - -// Get gets the bits pointed at by p, as a uint32. -func word32_Get(p word32) uint32 { - elem := p.v.Elem() - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") +func (p pointer) toUint32Ptr() **uint32 { + return p.v.Interface().(**uint32) } - -// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32(p structPointer, f field) word32 { - return word32{structPointer_field(p, f)} +func (p pointer) toUint32Slice() *[]uint32 { + return p.v.Interface().(*[]uint32) } - -// A word32Val represents a field of type int32, uint32, float32, or enum. -// That is, v.Type() is int32, uint32, float32, or enum and v is assignable. -type word32Val struct { - v reflect.Value +func (p pointer) toBool() *bool { + return p.v.Interface().(*bool) } - -// Set sets *p to x. -func word32Val_Set(p word32Val, x uint32) { - switch p.v.Type() { - case int32Type: - p.v.SetInt(int64(x)) - return - case uint32Type: - p.v.SetUint(uint64(x)) - return - case float32Type: - p.v.SetFloat(float64(math.Float32frombits(x))) - return - } - - // must be enum - p.v.SetInt(int64(int32(x))) +func (p pointer) toBoolPtr() **bool { + return p.v.Interface().(**bool) } - -// Get gets the bits pointed at by p, as a uint32. -func word32Val_Get(p word32Val) uint32 { - elem := p.v - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") +func (p pointer) toBoolSlice() *[]bool { + return p.v.Interface().(*[]bool) } - -// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct. -func structPointer_Word32Val(p structPointer, f field) word32Val { - return word32Val{structPointer_field(p, f)} +func (p pointer) toFloat64() *float64 { + return p.v.Interface().(*float64) } - -// A word32Slice is a slice of 32-bit values. -// That is, v.Type() is []int32, []uint32, []float32, or []enum. -type word32Slice struct { - v reflect.Value +func (p pointer) toFloat64Ptr() **float64 { + return p.v.Interface().(**float64) } - -func (p word32Slice) Append(x uint32) { - n, m := p.v.Len(), p.v.Cap() - if n < m { - p.v.SetLen(n + 1) - } else { - t := p.v.Type().Elem() - p.v.Set(reflect.Append(p.v, reflect.Zero(t))) - } - elem := p.v.Index(n) - switch elem.Kind() { - case reflect.Int32: - elem.SetInt(int64(int32(x))) - case reflect.Uint32: - elem.SetUint(uint64(x)) - case reflect.Float32: - elem.SetFloat(float64(math.Float32frombits(x))) - } +func (p pointer) toFloat64Slice() *[]float64 { + return p.v.Interface().(*[]float64) } - -func (p word32Slice) Len() int { - return p.v.Len() +func (p pointer) toFloat32() *float32 { + return p.v.Interface().(*float32) } - -func (p word32Slice) Index(i int) uint32 { - elem := p.v.Index(i) - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") +func (p pointer) toFloat32Ptr() **float32 { + return p.v.Interface().(**float32) } - -// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct. -func structPointer_Word32Slice(p structPointer, f field) word32Slice { - return word32Slice{structPointer_field(p, f)} +func (p pointer) toFloat32Slice() *[]float32 { + return p.v.Interface().(*[]float32) } - -// word64 is like word32 but for 64-bit values. -type word64 struct { - v reflect.Value +func (p pointer) toString() *string { + return p.v.Interface().(*string) } - -func word64_Set(p word64, o *Buffer, x uint64) { - t := p.v.Type().Elem() - switch t { - case int64Type: - if len(o.int64s) == 0 { - o.int64s = make([]int64, uint64PoolSize) - } - o.int64s[0] = int64(x) - p.v.Set(reflect.ValueOf(&o.int64s[0])) - o.int64s = o.int64s[1:] - return - case uint64Type: - if len(o.uint64s) == 0 { - o.uint64s = make([]uint64, uint64PoolSize) - } - o.uint64s[0] = x - p.v.Set(reflect.ValueOf(&o.uint64s[0])) - o.uint64s = o.uint64s[1:] - return - case float64Type: - if len(o.float64s) == 0 { - o.float64s = make([]float64, uint64PoolSize) - } - o.float64s[0] = math.Float64frombits(x) - p.v.Set(reflect.ValueOf(&o.float64s[0])) - o.float64s = o.float64s[1:] - return - } - panic("unreachable") +func (p pointer) toStringPtr() **string { + return p.v.Interface().(**string) } - -func word64_IsNil(p word64) bool { - return p.v.IsNil() +func (p pointer) toStringSlice() *[]string { + return p.v.Interface().(*[]string) } - -func word64_Get(p word64) uint64 { - elem := p.v.Elem() - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return elem.Uint() - case reflect.Float64: - return math.Float64bits(elem.Float()) - } - panic("unreachable") +func (p pointer) toBytes() *[]byte { + return p.v.Interface().(*[]byte) } - -func structPointer_Word64(p structPointer, f field) word64 { - return word64{structPointer_field(p, f)} +func (p pointer) toBytesSlice() *[][]byte { + return p.v.Interface().(*[][]byte) +} +func (p pointer) toExtensions() *XXX_InternalExtensions { + return p.v.Interface().(*XXX_InternalExtensions) +} +func (p pointer) toOldExtensions() *map[int32]Extension { + return p.v.Interface().(*map[int32]Extension) +} +func (p pointer) getPointer() pointer { + return pointer{v: p.v.Elem()} +} +func (p pointer) setPointer(q pointer) { + p.v.Elem().Set(q.v) +} +func (p pointer) appendPointer(q pointer) { + grow(p.v.Elem()).Set(q.v) } -// word64Val is like word32Val but for 64-bit values. -type word64Val struct { - v reflect.Value +// getPointerSlice copies []*T from p as a new []pointer. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) getPointerSlice() []pointer { + if p.v.IsNil() { + return nil + } + n := p.v.Elem().Len() + s := make([]pointer, n) + for i := 0; i < n; i++ { + s[i] = pointer{v: p.v.Elem().Index(i)} + } + return s } -func word64Val_Set(p word64Val, o *Buffer, x uint64) { - switch p.v.Type() { - case int64Type: - p.v.SetInt(int64(x)) - return - case uint64Type: - p.v.SetUint(x) - return - case float64Type: - p.v.SetFloat(math.Float64frombits(x)) +// setPointerSlice copies []pointer into p as a new []*T. +// This behavior differs from the implementation in pointer_unsafe.go. +func (p pointer) setPointerSlice(v []pointer) { + if v == nil { + p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem()) return } - panic("unreachable") + s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v)) + for _, p := range v { + s = reflect.Append(s, p.v) + } + p.v.Elem().Set(s) } -func word64Val_Get(p word64Val) uint64 { - elem := p.v - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return elem.Uint() - case reflect.Float64: - return math.Float64bits(elem.Float()) +// getInterfacePointer returns a pointer that points to the +// interface data of the interface pointed by p. +func (p pointer) getInterfacePointer() pointer { + if p.v.Elem().IsNil() { + return pointer{v: p.v.Elem()} } - panic("unreachable") + return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct } -func structPointer_Word64Val(p structPointer, f field) word64Val { - return word64Val{structPointer_field(p, f)} +func (p pointer) asPointerTo(t reflect.Type) reflect.Value { + // TODO: check that p.v.Type().Elem() == t? + return p.v } -type word64Slice struct { - v reflect.Value +func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p } - -func (p word64Slice) Append(x uint64) { - n, m := p.v.Len(), p.v.Cap() - if n < m { - p.v.SetLen(n + 1) - } else { - t := p.v.Type().Elem() - p.v.Set(reflect.Append(p.v, reflect.Zero(t))) - } - elem := p.v.Index(n) - switch elem.Kind() { - case reflect.Int64: - elem.SetInt(int64(int64(x))) - case reflect.Uint64: - elem.SetUint(uint64(x)) - case reflect.Float64: - elem.SetFloat(float64(math.Float64frombits(x))) - } +func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v } - -func (p word64Slice) Len() int { - return p.v.Len() +func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p } - -func (p word64Slice) Index(i int) uint64 { - elem := p.v.Index(i) - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return uint64(elem.Uint()) - case reflect.Float64: - return math.Float64bits(float64(elem.Float())) - } - panic("unreachable") +func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v } - -func structPointer_Word64Slice(p structPointer, f field) word64Slice { - return word64Slice{structPointer_field(p, f)} +func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p +} +func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v } +func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { + atomicLock.Lock() + defer atomicLock.Unlock() + return *p +} +func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { + atomicLock.Lock() + defer atomicLock.Unlock() + *p = v +} + +var atomicLock sync.Mutex diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go index 6b5567d47c..d55a335d94 100644 --- a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go +++ b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go @@ -29,7 +29,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +build !appengine,!js +// +build !purego,!appengine,!js // This file contains the implementation of the proto field accesses using package unsafe. @@ -37,38 +37,13 @@ package proto import ( "reflect" + "sync/atomic" "unsafe" ) -// NOTE: These type_Foo functions would more idiomatically be methods, -// but Go does not allow methods on pointer types, and we must preserve -// some pointer type for the garbage collector. We use these -// funcs with clunky names as our poor approximation to methods. -// -// An alternative would be -// type structPointer struct { p unsafe.Pointer } -// but that does not registerize as well. - -// A structPointer is a pointer to a struct. -type structPointer unsafe.Pointer - -// toStructPointer returns a structPointer equivalent to the given reflect value. -func toStructPointer(v reflect.Value) structPointer { - return structPointer(unsafe.Pointer(v.Pointer())) -} - -// IsNil reports whether p is nil. -func structPointer_IsNil(p structPointer) bool { - return p == nil -} - -// Interface returns the struct pointer, assumed to have element type t, -// as an interface value. -func structPointer_Interface(p structPointer, t reflect.Type) interface{} { - return reflect.NewAt(t, unsafe.Pointer(p)).Interface() -} +const unsafeAllowed = true -// A field identifies a field in a struct, accessible from a structPointer. +// A field identifies a field in a struct, accessible from a pointer. // In this implementation, a field is identified by its byte offset from the start of the struct. type field uintptr @@ -80,191 +55,254 @@ func toField(f *reflect.StructField) field { // invalidField is an invalid field identifier. const invalidField = ^field(0) +// zeroField is a noop when calling pointer.offset. +const zeroField = field(0) + // IsValid reports whether the field identifier is valid. func (f field) IsValid() bool { - return f != ^field(0) + return f != invalidField } -// Bytes returns the address of a []byte field in the struct. -func structPointer_Bytes(p structPointer, f field) *[]byte { - return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// The pointer type below is for the new table-driven encoder/decoder. +// The implementation here uses unsafe.Pointer to create a generic pointer. +// In pointer_reflect.go we use reflect instead of unsafe to implement +// the same (but slower) interface. +type pointer struct { + p unsafe.Pointer } -// BytesSlice returns the address of a [][]byte field in the struct. -func structPointer_BytesSlice(p structPointer, f field) *[][]byte { - return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} +// size of pointer +var ptrSize = unsafe.Sizeof(uintptr(0)) -// Bool returns the address of a *bool field in the struct. -func structPointer_Bool(p structPointer, f field) **bool { - return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// toPointer converts an interface of pointer type to a pointer +// that points to the same target. +func toPointer(i *Message) pointer { + // Super-tricky - read pointer out of data word of interface value. + // Saves ~25ns over the equivalent: + // return valToPointer(reflect.ValueOf(*i)) + return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} } -// BoolVal returns the address of a bool field in the struct. -func structPointer_BoolVal(p structPointer, f field) *bool { - return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// toAddrPointer converts an interface to a pointer that points to +// the interface data. +func toAddrPointer(i *interface{}, isptr bool) pointer { + // Super-tricky - read or get the address of data word of interface value. + if isptr { + // The interface is of pointer type, thus it is a direct interface. + // The data word is the pointer data itself. We take its address. + return pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)} + } + // The interface is not of pointer type. The data word is the pointer + // to the data. + return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} } -// BoolSlice returns the address of a []bool field in the struct. -func structPointer_BoolSlice(p structPointer, f field) *[]bool { - return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// valToPointer converts v to a pointer. v must be of pointer type. +func valToPointer(v reflect.Value) pointer { + return pointer{p: unsafe.Pointer(v.Pointer())} } -// String returns the address of a *string field in the struct. -func structPointer_String(p structPointer, f field) **string { - return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// offset converts from a pointer to a structure to a pointer to +// one of its fields. +func (p pointer) offset(f field) pointer { + // For safety, we should panic if !f.IsValid, however calling panic causes + // this to no longer be inlineable, which is a serious performance cost. + /* + if !f.IsValid() { + panic("invalid field") + } + */ + return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} } -// StringVal returns the address of a string field in the struct. -func structPointer_StringVal(p structPointer, f field) *string { - return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) isNil() bool { + return p.p == nil } -// StringSlice returns the address of a []string field in the struct. -func structPointer_StringSlice(p structPointer, f field) *[]string { - return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) toInt64() *int64 { + return (*int64)(p.p) } - -// ExtMap returns the address of an extension map field in the struct. -func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { - return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) toInt64Ptr() **int64 { + return (**int64)(p.p) } - -func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { - return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) toInt64Slice() *[]int64 { + return (*[]int64)(p.p) } - -// NewAt returns the reflect.Value for a pointer to a field in the struct. -func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { - return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f))) +func (p pointer) toInt32() *int32 { + return (*int32)(p.p) } -// SetStructPointer writes a *struct field in the struct. -func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { - *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q +// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist. +/* + func (p pointer) toInt32Ptr() **int32 { + return (**int32)(p.p) + } + func (p pointer) toInt32Slice() *[]int32 { + return (*[]int32)(p.p) + } +*/ +func (p pointer) getInt32Ptr() *int32 { + return *(**int32)(p.p) } - -// GetStructPointer reads a *struct field in the struct. -func structPointer_GetStructPointer(p structPointer, f field) structPointer { - return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) setInt32Ptr(v int32) { + *(**int32)(p.p) = &v } -// StructPointerSlice the address of a []*struct field in the struct. -func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice { - return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +// getInt32Slice loads a []int32 from p. +// The value returned is aliased with the original slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) getInt32Slice() []int32 { + return *(*[]int32)(p.p) } -// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups). -type structPointerSlice []structPointer - -func (v *structPointerSlice) Len() int { return len(*v) } -func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] } -func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) } - -// A word32 is the address of a "pointer to 32-bit value" field. -type word32 **uint32 - -// IsNil reports whether *v is nil. -func word32_IsNil(p word32) bool { - return *p == nil +// setInt32Slice stores a []int32 to p. +// The value set is aliased with the input slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) setInt32Slice(v []int32) { + *(*[]int32)(p.p) = v } -// Set sets *v to point at a newly allocated word set to x. -func word32_Set(p word32, o *Buffer, x uint32) { - if len(o.uint32s) == 0 { - o.uint32s = make([]uint32, uint32PoolSize) - } - o.uint32s[0] = x - *p = &o.uint32s[0] - o.uint32s = o.uint32s[1:] +// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead? +func (p pointer) appendInt32Slice(v int32) { + s := (*[]int32)(p.p) + *s = append(*s, v) } -// Get gets the value pointed at by *v. -func word32_Get(p word32) uint32 { - return **p +func (p pointer) toUint64() *uint64 { + return (*uint64)(p.p) } - -// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32(p structPointer, f field) word32 { - return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +func (p pointer) toUint64Ptr() **uint64 { + return (**uint64)(p.p) } - -// A word32Val is the address of a 32-bit value field. -type word32Val *uint32 - -// Set sets *p to x. -func word32Val_Set(p word32Val, x uint32) { - *p = x +func (p pointer) toUint64Slice() *[]uint64 { + return (*[]uint64)(p.p) } - -// Get gets the value pointed at by p. -func word32Val_Get(p word32Val) uint32 { - return *p +func (p pointer) toUint32() *uint32 { + return (*uint32)(p.p) } - -// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32Val(p structPointer, f field) word32Val { - return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +func (p pointer) toUint32Ptr() **uint32 { + return (**uint32)(p.p) } - -// A word32Slice is a slice of 32-bit values. -type word32Slice []uint32 - -func (v *word32Slice) Append(x uint32) { *v = append(*v, x) } -func (v *word32Slice) Len() int { return len(*v) } -func (v *word32Slice) Index(i int) uint32 { return (*v)[i] } - -// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct. -func structPointer_Word32Slice(p structPointer, f field) *word32Slice { - return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func (p pointer) toUint32Slice() *[]uint32 { + return (*[]uint32)(p.p) } - -// word64 is like word32 but for 64-bit values. -type word64 **uint64 - -func word64_Set(p word64, o *Buffer, x uint64) { - if len(o.uint64s) == 0 { - o.uint64s = make([]uint64, uint64PoolSize) - } - o.uint64s[0] = x - *p = &o.uint64s[0] - o.uint64s = o.uint64s[1:] +func (p pointer) toBool() *bool { + return (*bool)(p.p) } - -func word64_IsNil(p word64) bool { - return *p == nil +func (p pointer) toBoolPtr() **bool { + return (**bool)(p.p) } - -func word64_Get(p word64) uint64 { - return **p +func (p pointer) toBoolSlice() *[]bool { + return (*[]bool)(p.p) +} +func (p pointer) toFloat64() *float64 { + return (*float64)(p.p) +} +func (p pointer) toFloat64Ptr() **float64 { + return (**float64)(p.p) +} +func (p pointer) toFloat64Slice() *[]float64 { + return (*[]float64)(p.p) +} +func (p pointer) toFloat32() *float32 { + return (*float32)(p.p) +} +func (p pointer) toFloat32Ptr() **float32 { + return (**float32)(p.p) +} +func (p pointer) toFloat32Slice() *[]float32 { + return (*[]float32)(p.p) +} +func (p pointer) toString() *string { + return (*string)(p.p) +} +func (p pointer) toStringPtr() **string { + return (**string)(p.p) +} +func (p pointer) toStringSlice() *[]string { + return (*[]string)(p.p) +} +func (p pointer) toBytes() *[]byte { + return (*[]byte)(p.p) +} +func (p pointer) toBytesSlice() *[][]byte { + return (*[][]byte)(p.p) +} +func (p pointer) toExtensions() *XXX_InternalExtensions { + return (*XXX_InternalExtensions)(p.p) +} +func (p pointer) toOldExtensions() *map[int32]Extension { + return (*map[int32]Extension)(p.p) } -func structPointer_Word64(p structPointer, f field) word64 { - return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +// getPointerSlice loads []*T from p as a []pointer. +// The value returned is aliased with the original slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) getPointerSlice() []pointer { + // Super-tricky - p should point to a []*T where T is a + // message type. We load it as []pointer. + return *(*[]pointer)(p.p) } -// word64Val is like word32Val but for 64-bit values. -type word64Val *uint64 +// setPointerSlice stores []pointer into p as a []*T. +// The value set is aliased with the input slice. +// This behavior differs from the implementation in pointer_reflect.go. +func (p pointer) setPointerSlice(v []pointer) { + // Super-tricky - p should point to a []*T where T is a + // message type. We store it as []pointer. + *(*[]pointer)(p.p) = v +} -func word64Val_Set(p word64Val, o *Buffer, x uint64) { - *p = x +// getPointer loads the pointer at p and returns it. +func (p pointer) getPointer() pointer { + return pointer{p: *(*unsafe.Pointer)(p.p)} } -func word64Val_Get(p word64Val) uint64 { - return *p +// setPointer stores the pointer q at p. +func (p pointer) setPointer(q pointer) { + *(*unsafe.Pointer)(p.p) = q.p } -func structPointer_Word64Val(p structPointer, f field) word64Val { - return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) +// append q to the slice pointed to by p. +func (p pointer) appendPointer(q pointer) { + s := (*[]unsafe.Pointer)(p.p) + *s = append(*s, q.p) } -// word64Slice is like word32Slice but for 64-bit values. -type word64Slice []uint64 +// getInterfacePointer returns a pointer that points to the +// interface data of the interface pointed by p. +func (p pointer) getInterfacePointer() pointer { + // Super-tricky - read pointer out of data word of interface value. + return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]} +} -func (v *word64Slice) Append(x uint64) { *v = append(*v, x) } -func (v *word64Slice) Len() int { return len(*v) } -func (v *word64Slice) Index(i int) uint64 { return (*v)[i] } +// asPointerTo returns a reflect.Value that is a pointer to an +// object of type t stored at p. +func (p pointer) asPointerTo(t reflect.Type) reflect.Value { + return reflect.NewAt(t, p.p) +} -func structPointer_Word64Slice(p structPointer, f field) *word64Slice { - return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) +func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { + return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) +} +func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { + return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) +} +func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { + return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) +} +func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { + return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) +} +func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { + atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) } diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go index ec2289c005..f710adab09 100644 --- a/vendor/github.com/golang/protobuf/proto/properties.go +++ b/vendor/github.com/golang/protobuf/proto/properties.go @@ -58,42 +58,6 @@ const ( WireFixed32 = 5 ) -const startSize = 10 // initial slice/string sizes - -// Encoders are defined in encode.go -// An encoder outputs the full representation of a field, including its -// tag and encoder type. -type encoder func(p *Buffer, prop *Properties, base structPointer) error - -// A valueEncoder encodes a single integer in a particular encoding. -type valueEncoder func(o *Buffer, x uint64) error - -// Sizers are defined in encode.go -// A sizer returns the encoded size of a field, including its tag and encoder -// type. -type sizer func(prop *Properties, base structPointer) int - -// A valueSizer returns the encoded size of a single integer in a particular -// encoding. -type valueSizer func(x uint64) int - -// Decoders are defined in decode.go -// A decoder creates a value from its wire representation. -// Unrecognized subelements are saved in unrec. -type decoder func(p *Buffer, prop *Properties, base structPointer) error - -// A valueDecoder decodes a single integer in a particular encoding. -type valueDecoder func(o *Buffer) (x uint64, err error) - -// A oneofMarshaler does the marshaling for all oneof fields in a message. -type oneofMarshaler func(Message, *Buffer) error - -// A oneofUnmarshaler does the unmarshaling for a oneof field in a message. -type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error) - -// A oneofSizer does the sizing for all oneof fields in a message. -type oneofSizer func(Message) int - // tagMap is an optimization over map[int]int for typical protocol buffer // use-cases. Encoded protocol buffers are often in tag order with small tag // numbers. @@ -140,13 +104,6 @@ type StructProperties struct { decoderTags tagMap // map from proto tag to struct field number decoderOrigNames map[string]int // map from original name to struct field number order []int // list of struct field numbers in tag order - unrecField field // field id of the XXX_unrecognized []byte field - extendable bool // is this an extendable proto - - oneofMarshaler oneofMarshaler - oneofUnmarshaler oneofUnmarshaler - oneofSizer oneofSizer - stype reflect.Type // OneofTypes contains information about the oneof fields in this message. // It is keyed by the original name of a field. @@ -187,36 +144,19 @@ type Properties struct { Default string // default value HasDefault bool // whether an explicit default was provided - def_uint64 uint64 - - enc encoder - valEnc valueEncoder // set for bool and numeric types only - field field - tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType) - tagbuf [8]byte - stype reflect.Type // set for struct types only - sprop *StructProperties // set for struct types only - isMarshaler bool - isUnmarshaler bool + + stype reflect.Type // set for struct types only + sprop *StructProperties // set for struct types only mtype reflect.Type // set for map types only mkeyprop *Properties // set for map types only mvalprop *Properties // set for map types only - - size sizer - valSize valueSizer // set for bool and numeric types only - - dec decoder - valDec valueDecoder // set for bool and numeric types only - - // If this is a packable field, this will be the decoder for the packed version of the field. - packedDec decoder } // String formats the properties in the protobuf struct field tag style. func (p *Properties) String() string { s := p.Wire - s = "," + s += "," s += strconv.Itoa(p.Tag) if p.Required { s += ",req" @@ -262,29 +202,14 @@ func (p *Properties) Parse(s string) { switch p.Wire { case "varint": p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeVarint - p.valDec = (*Buffer).DecodeVarint - p.valSize = sizeVarint case "fixed32": p.WireType = WireFixed32 - p.valEnc = (*Buffer).EncodeFixed32 - p.valDec = (*Buffer).DecodeFixed32 - p.valSize = sizeFixed32 case "fixed64": p.WireType = WireFixed64 - p.valEnc = (*Buffer).EncodeFixed64 - p.valDec = (*Buffer).DecodeFixed64 - p.valSize = sizeFixed64 case "zigzag32": p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeZigzag32 - p.valDec = (*Buffer).DecodeZigzag32 - p.valSize = sizeZigzag32 case "zigzag64": p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeZigzag64 - p.valDec = (*Buffer).DecodeZigzag64 - p.valSize = sizeZigzag64 case "bytes", "group": p.WireType = WireBytes // no numeric converter for non-numeric types @@ -299,6 +224,7 @@ func (p *Properties) Parse(s string) { return } +outer: for i := 2; i < len(fields); i++ { f := fields[i] switch { @@ -326,229 +252,28 @@ func (p *Properties) Parse(s string) { if i+1 < len(fields) { // Commas aren't escaped, and def is always last. p.Default += "," + strings.Join(fields[i+1:], ",") - break + break outer } } } } -func logNoSliceEnc(t1, t2 reflect.Type) { - fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2) -} - var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() -// Initialize the fields for encoding and decoding. -func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - p.enc = nil - p.dec = nil - p.size = nil - +// setFieldProps initializes the field properties for submessages and maps. +func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { switch t1 := typ; t1.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1) - - // proto3 scalar types - - case reflect.Bool: - p.enc = (*Buffer).enc_proto3_bool - p.dec = (*Buffer).dec_proto3_bool - p.size = size_proto3_bool - case reflect.Int32: - p.enc = (*Buffer).enc_proto3_int32 - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_proto3_int32 - case reflect.Uint32: - p.enc = (*Buffer).enc_proto3_uint32 - p.dec = (*Buffer).dec_proto3_int32 // can reuse - p.size = size_proto3_uint32 - case reflect.Int64, reflect.Uint64: - p.enc = (*Buffer).enc_proto3_int64 - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_proto3_int64 - case reflect.Float32: - p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_proto3_uint32 - case reflect.Float64: - p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_proto3_int64 - case reflect.String: - p.enc = (*Buffer).enc_proto3_string - p.dec = (*Buffer).dec_proto3_string - p.size = size_proto3_string - case reflect.Ptr: - switch t2 := t1.Elem(); t2.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2) - break - case reflect.Bool: - p.enc = (*Buffer).enc_bool - p.dec = (*Buffer).dec_bool - p.size = size_bool - case reflect.Int32: - p.enc = (*Buffer).enc_int32 - p.dec = (*Buffer).dec_int32 - p.size = size_int32 - case reflect.Uint32: - p.enc = (*Buffer).enc_uint32 - p.dec = (*Buffer).dec_int32 // can reuse - p.size = size_uint32 - case reflect.Int64, reflect.Uint64: - p.enc = (*Buffer).enc_int64 - p.dec = (*Buffer).dec_int64 - p.size = size_int64 - case reflect.Float32: - p.enc = (*Buffer).enc_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_int32 - p.size = size_uint32 - case reflect.Float64: - p.enc = (*Buffer).enc_int64 // can just treat them as bits - p.dec = (*Buffer).dec_int64 - p.size = size_int64 - case reflect.String: - p.enc = (*Buffer).enc_string - p.dec = (*Buffer).dec_string - p.size = size_string - case reflect.Struct: + if t1.Elem().Kind() == reflect.Struct { p.stype = t1.Elem() - p.isMarshaler = isMarshaler(t1) - p.isUnmarshaler = isUnmarshaler(t1) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_struct_message - p.dec = (*Buffer).dec_struct_message - p.size = size_struct_message - } else { - p.enc = (*Buffer).enc_struct_group - p.dec = (*Buffer).dec_struct_group - p.size = size_struct_group - } } case reflect.Slice: - switch t2 := t1.Elem(); t2.Kind() { - default: - logNoSliceEnc(t1, t2) - break - case reflect.Bool: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_bool - p.size = size_slice_packed_bool - } else { - p.enc = (*Buffer).enc_slice_bool - p.size = size_slice_bool - } - p.dec = (*Buffer).dec_slice_bool - p.packedDec = (*Buffer).dec_slice_packed_bool - case reflect.Int32: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int32 - p.size = size_slice_packed_int32 - } else { - p.enc = (*Buffer).enc_slice_int32 - p.size = size_slice_int32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case reflect.Uint32: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_uint32 - p.size = size_slice_packed_uint32 - } else { - p.enc = (*Buffer).enc_slice_uint32 - p.size = size_slice_uint32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case reflect.Int64, reflect.Uint64: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int64 - p.size = size_slice_packed_int64 - } else { - p.enc = (*Buffer).enc_slice_int64 - p.size = size_slice_int64 - } - p.dec = (*Buffer).dec_slice_int64 - p.packedDec = (*Buffer).dec_slice_packed_int64 - case reflect.Uint8: - p.dec = (*Buffer).dec_slice_byte - if p.proto3 { - p.enc = (*Buffer).enc_proto3_slice_byte - p.size = size_proto3_slice_byte - } else { - p.enc = (*Buffer).enc_slice_byte - p.size = size_slice_byte - } - case reflect.Float32, reflect.Float64: - switch t2.Bits() { - case 32: - // can just treat them as bits - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_uint32 - p.size = size_slice_packed_uint32 - } else { - p.enc = (*Buffer).enc_slice_uint32 - p.size = size_slice_uint32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case 64: - // can just treat them as bits - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int64 - p.size = size_slice_packed_int64 - } else { - p.enc = (*Buffer).enc_slice_int64 - p.size = size_slice_int64 - } - p.dec = (*Buffer).dec_slice_int64 - p.packedDec = (*Buffer).dec_slice_packed_int64 - default: - logNoSliceEnc(t1, t2) - break - } - case reflect.String: - p.enc = (*Buffer).enc_slice_string - p.dec = (*Buffer).dec_slice_string - p.size = size_slice_string - case reflect.Ptr: - switch t3 := t2.Elem(); t3.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3) - break - case reflect.Struct: - p.stype = t2.Elem() - p.isMarshaler = isMarshaler(t2) - p.isUnmarshaler = isUnmarshaler(t2) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_slice_struct_message - p.dec = (*Buffer).dec_slice_struct_message - p.size = size_slice_struct_message - } else { - p.enc = (*Buffer).enc_slice_struct_group - p.dec = (*Buffer).dec_slice_struct_group - p.size = size_slice_struct_group - } - } - case reflect.Slice: - switch t2.Elem().Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem()) - break - case reflect.Uint8: - p.enc = (*Buffer).enc_slice_slice_byte - p.dec = (*Buffer).dec_slice_slice_byte - p.size = size_slice_slice_byte - } + if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct { + p.stype = t2.Elem() } case reflect.Map: - p.enc = (*Buffer).enc_new_map - p.dec = (*Buffer).dec_new_map - p.size = size_new_map - p.mtype = t1 p.mkeyprop = &Properties{} p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) @@ -562,20 +287,6 @@ func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lock p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) } - // precalculate tag code - wire := p.WireType - if p.Packed { - wire = WireBytes - } - x := uint32(p.Tag)<<3 | uint32(wire) - i := 0 - for i = 0; x > 127; i++ { - p.tagbuf[i] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - p.tagbuf[i] = uint8(x) - p.tagcode = p.tagbuf[0 : i+1] - if p.stype != nil { if lockGetProp { p.sprop = GetProperties(p.stype) @@ -586,32 +297,9 @@ func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lock } var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() - unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() + marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() ) -// isMarshaler reports whether type t implements Marshaler. -func isMarshaler(t reflect.Type) bool { - // We're checking for (likely) pointer-receiver methods - // so if t is not a pointer, something is very wrong. - // The calls above only invoke isMarshaler on pointer types. - if t.Kind() != reflect.Ptr { - panic("proto: misuse of isMarshaler") - } - return t.Implements(marshalerType) -} - -// isUnmarshaler reports whether type t implements Unmarshaler. -func isUnmarshaler(t reflect.Type) bool { - // We're checking for (likely) pointer-receiver methods - // so if t is not a pointer, something is very wrong. - // The calls above only invoke isUnmarshaler on pointer types. - if t.Kind() != reflect.Ptr { - panic("proto: misuse of isUnmarshaler") - } - return t.Implements(unmarshalerType) -} - // Init populates the properties from a protocol buffer struct tag. func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { p.init(typ, name, tag, f, true) @@ -621,14 +309,11 @@ func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructF // "bytes,49,opt,def=hello!" p.Name = name p.OrigName = name - if f != nil { - p.field = toField(f) - } if tag == "" { return } p.Parse(tag) - p.setEncAndDec(typ, f, lockGetProp) + p.setFieldProps(typ, f, lockGetProp) } var ( @@ -678,9 +363,6 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { propertiesMap[t] = prop // build properties - prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) || - reflect.PtrTo(t).Implements(extendableProtoV1Type) - prop.unrecField = invalidField prop.Prop = make([]*Properties, t.NumField()) prop.order = make([]int, t.NumField()) @@ -690,17 +372,6 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { name := f.Name p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) - if f.Name == "XXX_InternalExtensions" { // special case - p.enc = (*Buffer).enc_exts - p.dec = nil // not needed - p.size = size_exts - } else if f.Name == "XXX_extensions" { // special case - p.enc = (*Buffer).enc_map - p.dec = nil // not needed - p.size = size_map - } else if f.Name == "XXX_unrecognized" { // special case - prop.unrecField = toField(&f) - } oneof := f.Tag.Get("protobuf_oneof") // special case if oneof != "" { // Oneof fields don't use the traditional protobuf tag. @@ -715,9 +386,6 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { } print("\n") } - if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" { - fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") - } } // Re-order prop.order. @@ -728,8 +396,7 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { } if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { var oots []interface{} - prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs() - prop.stype = t + _, _, _, oots = om.XXX_OneofFuncs() // Interpret oneof metadata. prop.OneofTypes = make(map[string]*OneofProperties) @@ -779,30 +446,6 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { return prop } -// Return the Properties object for the x[0]'th field of the structure. -func propByIndex(t reflect.Type, x []int) *Properties { - if len(x) != 1 { - fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t) - return nil - } - prop := GetProperties(t) - return prop.Prop[x[0]] -} - -// Get the address and type of a pointer to a struct from an interface. -func getbase(pb Message) (t reflect.Type, b structPointer, err error) { - if pb == nil { - err = ErrNil - return - } - // get the reflect type of the pointer to the struct. - t = reflect.TypeOf(pb) - // get the address of the struct. - value := reflect.ValueOf(pb) - b = toStructPointer(value) - return -} - // A global registry of enum types. // The generated code will register the generated maps by calling RegisterEnum. @@ -826,20 +469,42 @@ func EnumValueMap(enumType string) map[string]int32 { // A registry of all linked message types. // The string is a fully-qualified proto name ("pkg.Message"). var ( - protoTypes = make(map[string]reflect.Type) - revProtoTypes = make(map[reflect.Type]string) + protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers + protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types + revProtoTypes = make(map[reflect.Type]string) ) // RegisterType is called from generated code and maps from the fully qualified // proto name to the type (pointer to struct) of the protocol buffer. func RegisterType(x Message, name string) { - if _, ok := protoTypes[name]; ok { + if _, ok := protoTypedNils[name]; ok { // TODO: Some day, make this a panic. log.Printf("proto: duplicate proto type registered: %s", name) return } t := reflect.TypeOf(x) - protoTypes[name] = t + if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 { + // Generated code always calls RegisterType with nil x. + // This check is just for extra safety. + protoTypedNils[name] = x + } else { + protoTypedNils[name] = reflect.Zero(t).Interface().(Message) + } + revProtoTypes[t] = name +} + +// RegisterMapType is called from generated code and maps from the fully qualified +// proto name to the native map type of the proto map definition. +func RegisterMapType(x interface{}, name string) { + if reflect.TypeOf(x).Kind() != reflect.Map { + panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name)) + } + if _, ok := protoMapTypes[name]; ok { + log.Printf("proto: duplicate proto type registered: %s", name) + return + } + t := reflect.TypeOf(x) + protoMapTypes[name] = t revProtoTypes[t] = name } @@ -855,7 +520,14 @@ func MessageName(x Message) string { } // MessageType returns the message type (pointer to struct) for a named message. -func MessageType(name string) reflect.Type { return protoTypes[name] } +// The type is not guaranteed to implement proto.Message if the name refers to a +// map entry. +func MessageType(name string) reflect.Type { + if t, ok := protoTypedNils[name]; ok { + return reflect.TypeOf(t) + } + return protoMapTypes[name] +} // A registry of all linked proto files. var ( diff --git a/vendor/github.com/golang/protobuf/proto/proto3_test.go b/vendor/github.com/golang/protobuf/proto/proto3_test.go deleted file mode 100644 index 735837f2de..0000000000 --- a/vendor/github.com/golang/protobuf/proto/proto3_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2014 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/proto/proto3_proto" - tpb "github.com/golang/protobuf/proto/testdata" -) - -func TestProto3ZeroValues(t *testing.T) { - tests := []struct { - desc string - m proto.Message - }{ - {"zero message", &pb.Message{}}, - {"empty bytes field", &pb.Message{Data: []byte{}}}, - } - for _, test := range tests { - b, err := proto.Marshal(test.m) - if err != nil { - t.Errorf("%s: proto.Marshal: %v", test.desc, err) - continue - } - if len(b) > 0 { - t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) - } - } -} - -func TestRoundTripProto3(t *testing.T) { - m := &pb.Message{ - Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" - Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 - HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 - Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" - ResultCount: 47, // (0 | 7<<3): 0x38 0x2f - TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 - Score: 8.1, // (5 | 9<<3): 0x4d <8.1> - - Key: []uint64{1, 0xdeadbeef}, - Nested: &pb.Nested{ - Bunny: "Monty", - }, - } - t.Logf(" m: %v", m) - - b, err := proto.Marshal(m) - if err != nil { - t.Fatalf("proto.Marshal: %v", err) - } - t.Logf(" b: %q", b) - - m2 := new(pb.Message) - if err := proto.Unmarshal(b, m2); err != nil { - t.Fatalf("proto.Unmarshal: %v", err) - } - t.Logf("m2: %v", m2) - - if !proto.Equal(m, m2) { - t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) - } -} - -func TestGettersForBasicTypesExist(t *testing.T) { - var m pb.Message - if got := m.GetNested().GetBunny(); got != "" { - t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got) - } - if got := m.GetNested().GetCute(); got { - t.Errorf("m.GetNested().GetCute() = %t, want false", got) - } -} - -func TestProto3SetDefaults(t *testing.T) { - in := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: new(tpb.SubDefaults), - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": new(tpb.SubDefaults), - }, - } - - got := proto.Clone(in).(*pb.Message) - proto.SetDefaults(got) - - // There are no defaults in proto3. Everything should be the zero value, but - // we need to remember to set defaults for nested proto2 messages. - want := &pb.Message{ - Terrain: map[string]*pb.Nested{ - "meadow": new(pb.Nested), - }, - Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, - Proto2Value: map[string]*tpb.SubDefaults{ - "badlands": &tpb.SubDefaults{N: proto.Int64(7)}, - }, - } - - if !proto.Equal(got, want) { - t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) - } -} diff --git a/vendor/github.com/golang/protobuf/proto/size2_test.go b/vendor/github.com/golang/protobuf/proto/size2_test.go deleted file mode 100644 index a2729c39a1..0000000000 --- a/vendor/github.com/golang/protobuf/proto/size2_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto - -import ( - "testing" -) - -// This is a separate file and package from size_test.go because that one uses -// generated messages and thus may not be in package proto without having a circular -// dependency, whereas this file tests unexported details of size.go. - -func TestVarintSize(t *testing.T) { - // Check the edge cases carefully. - testCases := []struct { - n uint64 - size int - }{ - {0, 1}, - {1, 1}, - {127, 1}, - {128, 2}, - {16383, 2}, - {16384, 3}, - {1<<63 - 1, 9}, - {1 << 63, 10}, - } - for _, tc := range testCases { - size := sizeVarint(tc.n) - if size != tc.size { - t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/size_test.go b/vendor/github.com/golang/protobuf/proto/size_test.go deleted file mode 100644 index af1034dc7b..0000000000 --- a/vendor/github.com/golang/protobuf/proto/size_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "log" - "strings" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} - -// messageWithExtension2 is in equal_test.go. -var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} - -func init() { - if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { - log.Panicf("SetExtension: %v", err) - } - - // Force messageWithExtension3 to have the extension encoded. - Marshal(messageWithExtension3) - -} - -var SizeTests = []struct { - desc string - pb Message -}{ - {"empty", &pb.OtherMessage{}}, - // Basic types. - {"bool", &pb.Defaults{F_Bool: Bool(true)}}, - {"int32", &pb.Defaults{F_Int32: Int32(12)}}, - {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, - {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, - {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, - {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, - {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, - {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, - {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, - {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, - {"float", &pb.Defaults{F_Float: Float32(12.6)}}, - {"double", &pb.Defaults{F_Double: Float64(13.9)}}, - {"string", &pb.Defaults{F_String: String("niles")}}, - {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, - {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, - {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, - {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, - {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, - // Repeated. - {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, - {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, - {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, - {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, - {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, - {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ - // Need enough large numbers to verify that the header is counting the number of bytes - // for the field, not the number of elements. - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, - }}}, - {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, - {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, - // Nested. - {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, - {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, - // Other things. - {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, - {"extension (unencoded)", messageWithExtension1}, - {"extension (encoded)", messageWithExtension3}, - // proto3 message - {"proto3 empty", &proto3pb.Message{}}, - {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, - {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, - {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, - {"proto3 float", &proto3pb.Message{Score: 12.6}}, - {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, - {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, - {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, - {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, - {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}}, - - {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, - {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, - {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, - {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}}, - - {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, - {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, - {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, - - {"oneof not set", &pb.Oneof{}}, - {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{true}}}, - {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{0}}}, - {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{1 << 20}}}, - {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{42}}}, - {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{43}}}, - {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{44}}}, - {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{45}}}, - {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{46}}}, - {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{47.1}}}, - {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{48.9}}}, - {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{"Rhythmic Fman"}}}, - {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{[]byte("let go")}}}, - {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{50}}}, - {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{51}}}, - {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{pb.MyMessage_BLUE}}}, - {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}}, - {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{&pb.GoTestField{Label: String("k"), Type: String("v")}}}}, - {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{&pb.Oneof_F_Group{X: Int32(52)}}}}, - {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{1}}}, - {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{1}, Tormato: &pb.Oneof_Value{2}}}, -} - -func TestSize(t *testing.T) { - for _, tc := range SizeTests { - size := Size(tc.pb) - b, err := Marshal(tc.pb) - if err != nil { - t.Errorf("%v: Marshal failed: %v", tc.desc, err) - continue - } - if size != len(b) { - t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) - t.Logf("%v: bytes: %#v", tc.desc, b) - } - } -} diff --git a/vendor/github.com/golang/protobuf/proto/table_marshal.go b/vendor/github.com/golang/protobuf/proto/table_marshal.go new file mode 100644 index 0000000000..0f212b3029 --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/table_marshal.go @@ -0,0 +1,2681 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// 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. + +package proto + +import ( + "errors" + "fmt" + "math" + "reflect" + "sort" + "strconv" + "strings" + "sync" + "sync/atomic" + "unicode/utf8" +) + +// a sizer takes a pointer to a field and the size of its tag, computes the size of +// the encoded data. +type sizer func(pointer, int) int + +// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), +// marshals the field to the end of the slice, returns the slice and error (if any). +type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) + +// marshalInfo is the information used for marshaling a message. +type marshalInfo struct { + typ reflect.Type + fields []*marshalFieldInfo + unrecognized field // offset of XXX_unrecognized + extensions field // offset of XXX_InternalExtensions + v1extensions field // offset of XXX_extensions + sizecache field // offset of XXX_sizecache + initialized int32 // 0 -- only typ is set, 1 -- fully initialized + messageset bool // uses message set wire format + hasmarshaler bool // has custom marshaler + sync.RWMutex // protect extElems map, also for initialization + extElems map[int32]*marshalElemInfo // info of extension elements +} + +// marshalFieldInfo is the information used for marshaling a field of a message. +type marshalFieldInfo struct { + field field + wiretag uint64 // tag in wire format + tagsize int // size of tag in wire format + sizer sizer + marshaler marshaler + isPointer bool + required bool // field is required + name string // name of the field, for error reporting + oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements +} + +// marshalElemInfo is the information used for marshaling an extension or oneof element. +type marshalElemInfo struct { + wiretag uint64 // tag in wire format + tagsize int // size of tag in wire format + sizer sizer + marshaler marshaler + isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) +} + +var ( + marshalInfoMap = map[reflect.Type]*marshalInfo{} + marshalInfoLock sync.Mutex +) + +// getMarshalInfo returns the information to marshal a given type of message. +// The info it returns may not necessarily initialized. +// t is the type of the message (NOT the pointer to it). +func getMarshalInfo(t reflect.Type) *marshalInfo { + marshalInfoLock.Lock() + u, ok := marshalInfoMap[t] + if !ok { + u = &marshalInfo{typ: t} + marshalInfoMap[t] = u + } + marshalInfoLock.Unlock() + return u +} + +// Size is the entry point from generated code, +// and should be ONLY called by generated code. +// It computes the size of encoded data of msg. +// a is a pointer to a place to store cached marshal info. +func (a *InternalMessageInfo) Size(msg Message) int { + u := getMessageMarshalInfo(msg, a) + ptr := toPointer(&msg) + if ptr.isNil() { + // We get here if msg is a typed nil ((*SomeMessage)(nil)), + // so it satisfies the interface, and msg == nil wouldn't + // catch it. We don't want crash in this case. + return 0 + } + return u.size(ptr) +} + +// Marshal is the entry point from generated code, +// and should be ONLY called by generated code. +// It marshals msg to the end of b. +// a is a pointer to a place to store cached marshal info. +func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { + u := getMessageMarshalInfo(msg, a) + ptr := toPointer(&msg) + if ptr.isNil() { + // We get here if msg is a typed nil ((*SomeMessage)(nil)), + // so it satisfies the interface, and msg == nil wouldn't + // catch it. We don't want crash in this case. + return b, ErrNil + } + return u.marshal(b, ptr, deterministic) +} + +func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { + // u := a.marshal, but atomically. + // We use an atomic here to ensure memory consistency. + u := atomicLoadMarshalInfo(&a.marshal) + if u == nil { + // Get marshal information from type of message. + t := reflect.ValueOf(msg).Type() + if t.Kind() != reflect.Ptr { + panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) + } + u = getMarshalInfo(t.Elem()) + // Store it in the cache for later users. + // a.marshal = u, but atomically. + atomicStoreMarshalInfo(&a.marshal, u) + } + return u +} + +// size is the main function to compute the size of the encoded data of a message. +// ptr is the pointer to the message. +func (u *marshalInfo) size(ptr pointer) int { + if atomic.LoadInt32(&u.initialized) == 0 { + u.computeMarshalInfo() + } + + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + if u.hasmarshaler { + m := ptr.asPointerTo(u.typ).Interface().(Marshaler) + b, _ := m.Marshal() + return len(b) + } + + n := 0 + for _, f := range u.fields { + if f.isPointer && ptr.offset(f.field).getPointer().isNil() { + // nil pointer always marshals to nothing + continue + } + n += f.sizer(ptr.offset(f.field), f.tagsize) + } + if u.extensions.IsValid() { + e := ptr.offset(u.extensions).toExtensions() + if u.messageset { + n += u.sizeMessageSet(e) + } else { + n += u.sizeExtensions(e) + } + } + if u.v1extensions.IsValid() { + m := *ptr.offset(u.v1extensions).toOldExtensions() + n += u.sizeV1Extensions(m) + } + if u.unrecognized.IsValid() { + s := *ptr.offset(u.unrecognized).toBytes() + n += len(s) + } + // cache the result for use in marshal + if u.sizecache.IsValid() { + atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) + } + return n +} + +// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), +// fall back to compute the size. +func (u *marshalInfo) cachedsize(ptr pointer) int { + if u.sizecache.IsValid() { + return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) + } + return u.size(ptr) +} + +// marshal is the main function to marshal a message. It takes a byte slice and appends +// the encoded data to the end of the slice, returns the slice and error (if any). +// ptr is the pointer to the message. +// If deterministic is true, map is marshaled in deterministic order. +func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { + if atomic.LoadInt32(&u.initialized) == 0 { + u.computeMarshalInfo() + } + + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + if u.hasmarshaler { + m := ptr.asPointerTo(u.typ).Interface().(Marshaler) + b1, err := m.Marshal() + b = append(b, b1...) + return b, err + } + + var err, errreq error + // The old marshaler encodes extensions at beginning. + if u.extensions.IsValid() { + e := ptr.offset(u.extensions).toExtensions() + if u.messageset { + b, err = u.appendMessageSet(b, e, deterministic) + } else { + b, err = u.appendExtensions(b, e, deterministic) + } + if err != nil { + return b, err + } + } + if u.v1extensions.IsValid() { + m := *ptr.offset(u.v1extensions).toOldExtensions() + b, err = u.appendV1Extensions(b, m, deterministic) + if err != nil { + return b, err + } + } + for _, f := range u.fields { + if f.required && errreq == nil { + if ptr.offset(f.field).getPointer().isNil() { + // Required field is not set. + // We record the error but keep going, to give a complete marshaling. + errreq = &RequiredNotSetError{f.name} + continue + } + } + if f.isPointer && ptr.offset(f.field).getPointer().isNil() { + // nil pointer always marshals to nothing + continue + } + b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) + if err != nil { + if err1, ok := err.(*RequiredNotSetError); ok { + // Required field in submessage is not set. + // We record the error but keep going, to give a complete marshaling. + if errreq == nil { + errreq = &RequiredNotSetError{f.name + "." + err1.field} + } + continue + } + if err == errRepeatedHasNil { + err = errors.New("proto: repeated field " + f.name + " has nil element") + } + return b, err + } + } + if u.unrecognized.IsValid() { + s := *ptr.offset(u.unrecognized).toBytes() + b = append(b, s...) + } + return b, errreq +} + +// computeMarshalInfo initializes the marshal info. +func (u *marshalInfo) computeMarshalInfo() { + u.Lock() + defer u.Unlock() + if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock + return + } + + t := u.typ + u.unrecognized = invalidField + u.extensions = invalidField + u.v1extensions = invalidField + u.sizecache = invalidField + + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + if reflect.PtrTo(t).Implements(marshalerType) { + u.hasmarshaler = true + atomic.StoreInt32(&u.initialized, 1) + return + } + + // get oneof implementers + var oneofImplementers []interface{} + if m, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { + _, _, _, oneofImplementers = m.XXX_OneofFuncs() + } + + n := t.NumField() + + // deal with XXX fields first + for i := 0; i < t.NumField(); i++ { + f := t.Field(i) + if !strings.HasPrefix(f.Name, "XXX_") { + continue + } + switch f.Name { + case "XXX_sizecache": + u.sizecache = toField(&f) + case "XXX_unrecognized": + u.unrecognized = toField(&f) + case "XXX_InternalExtensions": + u.extensions = toField(&f) + u.messageset = f.Tag.Get("protobuf_messageset") == "1" + case "XXX_extensions": + u.v1extensions = toField(&f) + case "XXX_NoUnkeyedLiteral": + // nothing to do + default: + panic("unknown XXX field: " + f.Name) + } + n-- + } + + // normal fields + fields := make([]marshalFieldInfo, n) // batch allocation + u.fields = make([]*marshalFieldInfo, 0, n) + for i, j := 0, 0; i < t.NumField(); i++ { + f := t.Field(i) + + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + field := &fields[j] + j++ + field.name = f.Name + u.fields = append(u.fields, field) + if f.Tag.Get("protobuf_oneof") != "" { + field.computeOneofFieldInfo(&f, oneofImplementers) + continue + } + if f.Tag.Get("protobuf") == "" { + // field has no tag (not in generated message), ignore it + u.fields = u.fields[:len(u.fields)-1] + j-- + continue + } + field.computeMarshalFieldInfo(&f) + } + + // fields are marshaled in tag order on the wire. + sort.Sort(byTag(u.fields)) + + atomic.StoreInt32(&u.initialized, 1) +} + +// helper for sorting fields by tag +type byTag []*marshalFieldInfo + +func (a byTag) Len() int { return len(a) } +func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } + +// getExtElemInfo returns the information to marshal an extension element. +// The info it returns is initialized. +func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { + // get from cache first + u.RLock() + e, ok := u.extElems[desc.Field] + u.RUnlock() + if ok { + return e + } + + t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct + tags := strings.Split(desc.Tag, ",") + tag, err := strconv.Atoi(tags[1]) + if err != nil { + panic("tag is not an integer") + } + wt := wiretype(tags[0]) + sizer, marshaler := typeMarshaler(t, tags, false, false) + e = &marshalElemInfo{ + wiretag: uint64(tag)<<3 | wt, + tagsize: SizeVarint(uint64(tag) << 3), + sizer: sizer, + marshaler: marshaler, + isptr: t.Kind() == reflect.Ptr, + } + + // update cache + u.Lock() + if u.extElems == nil { + u.extElems = make(map[int32]*marshalElemInfo) + } + u.extElems[desc.Field] = e + u.Unlock() + return e +} + +// computeMarshalFieldInfo fills up the information to marshal a field. +func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { + // parse protobuf tag of the field. + // tag has format of "bytes,49,opt,name=foo,def=hello!" + tags := strings.Split(f.Tag.Get("protobuf"), ",") + if tags[0] == "" { + return + } + tag, err := strconv.Atoi(tags[1]) + if err != nil { + panic("tag is not an integer") + } + wt := wiretype(tags[0]) + if tags[2] == "req" { + fi.required = true + } + fi.setTag(f, tag, wt) + fi.setMarshaler(f, tags) +} + +func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { + fi.field = toField(f) + fi.wiretag = 1<<31 - 1 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. + fi.isPointer = true + fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) + fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) + + ityp := f.Type // interface type + for _, o := range oneofImplementers { + t := reflect.TypeOf(o) + if !t.Implements(ityp) { + continue + } + sf := t.Elem().Field(0) // oneof implementer is a struct with a single field + tags := strings.Split(sf.Tag.Get("protobuf"), ",") + tag, err := strconv.Atoi(tags[1]) + if err != nil { + panic("tag is not an integer") + } + wt := wiretype(tags[0]) + sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value + fi.oneofElems[t.Elem()] = &marshalElemInfo{ + wiretag: uint64(tag)<<3 | wt, + tagsize: SizeVarint(uint64(tag) << 3), + sizer: sizer, + marshaler: marshaler, + } + } +} + +type oneofMessage interface { + XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) +} + +// wiretype returns the wire encoding of the type. +func wiretype(encoding string) uint64 { + switch encoding { + case "fixed32": + return WireFixed32 + case "fixed64": + return WireFixed64 + case "varint", "zigzag32", "zigzag64": + return WireVarint + case "bytes": + return WireBytes + case "group": + return WireStartGroup + } + panic("unknown wire type " + encoding) +} + +// setTag fills up the tag (in wire format) and its size in the info of a field. +func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { + fi.field = toField(f) + fi.wiretag = uint64(tag)<<3 | wt + fi.tagsize = SizeVarint(uint64(tag) << 3) +} + +// setMarshaler fills up the sizer and marshaler in the info of a field. +func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { + switch f.Type.Kind() { + case reflect.Map: + // map field + fi.isPointer = true + fi.sizer, fi.marshaler = makeMapMarshaler(f) + return + case reflect.Ptr, reflect.Slice: + fi.isPointer = true + } + fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) +} + +// typeMarshaler returns the sizer and marshaler of a given field. +// t is the type of the field. +// tags is the generated "protobuf" tag of the field. +// If nozero is true, zero value is not marshaled to the wire. +// If oneof is true, it is a oneof field. +func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { + encoding := tags[0] + + pointer := false + slice := false + if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { + slice = true + t = t.Elem() + } + if t.Kind() == reflect.Ptr { + pointer = true + t = t.Elem() + } + + packed := false + proto3 := false + for i := 2; i < len(tags); i++ { + if tags[i] == "packed" { + packed = true + } + if tags[i] == "proto3" { + proto3 = true + } + } + + switch t.Kind() { + case reflect.Bool: + if pointer { + return sizeBoolPtr, appendBoolPtr + } + if slice { + if packed { + return sizeBoolPackedSlice, appendBoolPackedSlice + } + return sizeBoolSlice, appendBoolSlice + } + if nozero { + return sizeBoolValueNoZero, appendBoolValueNoZero + } + return sizeBoolValue, appendBoolValue + case reflect.Uint32: + switch encoding { + case "fixed32": + if pointer { + return sizeFixed32Ptr, appendFixed32Ptr + } + if slice { + if packed { + return sizeFixed32PackedSlice, appendFixed32PackedSlice + } + return sizeFixed32Slice, appendFixed32Slice + } + if nozero { + return sizeFixed32ValueNoZero, appendFixed32ValueNoZero + } + return sizeFixed32Value, appendFixed32Value + case "varint": + if pointer { + return sizeVarint32Ptr, appendVarint32Ptr + } + if slice { + if packed { + return sizeVarint32PackedSlice, appendVarint32PackedSlice + } + return sizeVarint32Slice, appendVarint32Slice + } + if nozero { + return sizeVarint32ValueNoZero, appendVarint32ValueNoZero + } + return sizeVarint32Value, appendVarint32Value + } + case reflect.Int32: + switch encoding { + case "fixed32": + if pointer { + return sizeFixedS32Ptr, appendFixedS32Ptr + } + if slice { + if packed { + return sizeFixedS32PackedSlice, appendFixedS32PackedSlice + } + return sizeFixedS32Slice, appendFixedS32Slice + } + if nozero { + return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero + } + return sizeFixedS32Value, appendFixedS32Value + case "varint": + if pointer { + return sizeVarintS32Ptr, appendVarintS32Ptr + } + if slice { + if packed { + return sizeVarintS32PackedSlice, appendVarintS32PackedSlice + } + return sizeVarintS32Slice, appendVarintS32Slice + } + if nozero { + return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero + } + return sizeVarintS32Value, appendVarintS32Value + case "zigzag32": + if pointer { + return sizeZigzag32Ptr, appendZigzag32Ptr + } + if slice { + if packed { + return sizeZigzag32PackedSlice, appendZigzag32PackedSlice + } + return sizeZigzag32Slice, appendZigzag32Slice + } + if nozero { + return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero + } + return sizeZigzag32Value, appendZigzag32Value + } + case reflect.Uint64: + switch encoding { + case "fixed64": + if pointer { + return sizeFixed64Ptr, appendFixed64Ptr + } + if slice { + if packed { + return sizeFixed64PackedSlice, appendFixed64PackedSlice + } + return sizeFixed64Slice, appendFixed64Slice + } + if nozero { + return sizeFixed64ValueNoZero, appendFixed64ValueNoZero + } + return sizeFixed64Value, appendFixed64Value + case "varint": + if pointer { + return sizeVarint64Ptr, appendVarint64Ptr + } + if slice { + if packed { + return sizeVarint64PackedSlice, appendVarint64PackedSlice + } + return sizeVarint64Slice, appendVarint64Slice + } + if nozero { + return sizeVarint64ValueNoZero, appendVarint64ValueNoZero + } + return sizeVarint64Value, appendVarint64Value + } + case reflect.Int64: + switch encoding { + case "fixed64": + if pointer { + return sizeFixedS64Ptr, appendFixedS64Ptr + } + if slice { + if packed { + return sizeFixedS64PackedSlice, appendFixedS64PackedSlice + } + return sizeFixedS64Slice, appendFixedS64Slice + } + if nozero { + return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero + } + return sizeFixedS64Value, appendFixedS64Value + case "varint": + if pointer { + return sizeVarintS64Ptr, appendVarintS64Ptr + } + if slice { + if packed { + return sizeVarintS64PackedSlice, appendVarintS64PackedSlice + } + return sizeVarintS64Slice, appendVarintS64Slice + } + if nozero { + return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero + } + return sizeVarintS64Value, appendVarintS64Value + case "zigzag64": + if pointer { + return sizeZigzag64Ptr, appendZigzag64Ptr + } + if slice { + if packed { + return sizeZigzag64PackedSlice, appendZigzag64PackedSlice + } + return sizeZigzag64Slice, appendZigzag64Slice + } + if nozero { + return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero + } + return sizeZigzag64Value, appendZigzag64Value + } + case reflect.Float32: + if pointer { + return sizeFloat32Ptr, appendFloat32Ptr + } + if slice { + if packed { + return sizeFloat32PackedSlice, appendFloat32PackedSlice + } + return sizeFloat32Slice, appendFloat32Slice + } + if nozero { + return sizeFloat32ValueNoZero, appendFloat32ValueNoZero + } + return sizeFloat32Value, appendFloat32Value + case reflect.Float64: + if pointer { + return sizeFloat64Ptr, appendFloat64Ptr + } + if slice { + if packed { + return sizeFloat64PackedSlice, appendFloat64PackedSlice + } + return sizeFloat64Slice, appendFloat64Slice + } + if nozero { + return sizeFloat64ValueNoZero, appendFloat64ValueNoZero + } + return sizeFloat64Value, appendFloat64Value + case reflect.String: + if pointer { + return sizeStringPtr, appendStringPtr + } + if slice { + return sizeStringSlice, appendStringSlice + } + if nozero { + return sizeStringValueNoZero, appendStringValueNoZero + } + return sizeStringValue, appendStringValue + case reflect.Slice: + if slice { + return sizeBytesSlice, appendBytesSlice + } + if oneof { + // Oneof bytes field may also have "proto3" tag. + // We want to marshal it as a oneof field. Do this + // check before the proto3 check. + return sizeBytesOneof, appendBytesOneof + } + if proto3 { + return sizeBytes3, appendBytes3 + } + return sizeBytes, appendBytes + case reflect.Struct: + switch encoding { + case "group": + if slice { + return makeGroupSliceMarshaler(getMarshalInfo(t)) + } + return makeGroupMarshaler(getMarshalInfo(t)) + case "bytes": + if slice { + return makeMessageSliceMarshaler(getMarshalInfo(t)) + } + return makeMessageMarshaler(getMarshalInfo(t)) + } + } + panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) +} + +// Below are functions to size/marshal a specific type of a field. +// They are stored in the field's info, and called by function pointers. +// They have type sizer or marshaler. + +func sizeFixed32Value(_ pointer, tagsize int) int { + return 4 + tagsize +} +func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint32() + if v == 0 { + return 0 + } + return 4 + tagsize +} +func sizeFixed32Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint32Ptr() + if p == nil { + return 0 + } + return 4 + tagsize +} +func sizeFixed32Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + return (4 + tagsize) * len(s) +} +func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return 0 + } + return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize +} +func sizeFixedS32Value(_ pointer, tagsize int) int { + return 4 + tagsize +} +func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + if v == 0 { + return 0 + } + return 4 + tagsize +} +func sizeFixedS32Ptr(ptr pointer, tagsize int) int { + p := ptr.getInt32Ptr() + if p == nil { + return 0 + } + return 4 + tagsize +} +func sizeFixedS32Slice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + return (4 + tagsize) * len(s) +} +func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + if len(s) == 0 { + return 0 + } + return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize +} +func sizeFloat32Value(_ pointer, tagsize int) int { + return 4 + tagsize +} +func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { + v := math.Float32bits(*ptr.toFloat32()) + if v == 0 { + return 0 + } + return 4 + tagsize +} +func sizeFloat32Ptr(ptr pointer, tagsize int) int { + p := *ptr.toFloat32Ptr() + if p == nil { + return 0 + } + return 4 + tagsize +} +func sizeFloat32Slice(ptr pointer, tagsize int) int { + s := *ptr.toFloat32Slice() + return (4 + tagsize) * len(s) +} +func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toFloat32Slice() + if len(s) == 0 { + return 0 + } + return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize +} +func sizeFixed64Value(_ pointer, tagsize int) int { + return 8 + tagsize +} +func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint64() + if v == 0 { + return 0 + } + return 8 + tagsize +} +func sizeFixed64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint64Ptr() + if p == nil { + return 0 + } + return 8 + tagsize +} +func sizeFixed64Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + return (8 + tagsize) * len(s) +} +func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return 0 + } + return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize +} +func sizeFixedS64Value(_ pointer, tagsize int) int { + return 8 + tagsize +} +func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + if v == 0 { + return 0 + } + return 8 + tagsize +} +func sizeFixedS64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toInt64Ptr() + if p == nil { + return 0 + } + return 8 + tagsize +} +func sizeFixedS64Slice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + return (8 + tagsize) * len(s) +} +func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return 0 + } + return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize +} +func sizeFloat64Value(_ pointer, tagsize int) int { + return 8 + tagsize +} +func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { + v := math.Float64bits(*ptr.toFloat64()) + if v == 0 { + return 0 + } + return 8 + tagsize +} +func sizeFloat64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toFloat64Ptr() + if p == nil { + return 0 + } + return 8 + tagsize +} +func sizeFloat64Slice(ptr pointer, tagsize int) int { + s := *ptr.toFloat64Slice() + return (8 + tagsize) * len(s) +} +func sizeFloat64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toFloat64Slice() + if len(s) == 0 { + return 0 + } + return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize +} +func sizeVarint32Value(ptr pointer, tagsize int) int { + v := *ptr.toUint32() + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint32() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarint32Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint32Ptr() + if p == nil { + return 0 + } + return SizeVarint(uint64(*p)) + tagsize +} +func sizeVarint32Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + tagsize + } + return n +} +func sizeVarint32PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeVarintS32Value(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS32Ptr(ptr pointer, tagsize int) int { + p := ptr.getInt32Ptr() + if p == nil { + return 0 + } + return SizeVarint(uint64(*p)) + tagsize +} +func sizeVarintS32Slice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + tagsize + } + return n +} +func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeVarint64Value(ptr pointer, tagsize int) int { + v := *ptr.toUint64() + return SizeVarint(v) + tagsize +} +func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toUint64() + if v == 0 { + return 0 + } + return SizeVarint(v) + tagsize +} +func sizeVarint64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toUint64Ptr() + if p == nil { + return 0 + } + return SizeVarint(*p) + tagsize +} +func sizeVarint64Slice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + n := 0 + for _, v := range s { + n += SizeVarint(v) + tagsize + } + return n +} +func sizeVarint64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(v) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeVarintS64Value(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v)) + tagsize +} +func sizeVarintS64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toInt64Ptr() + if p == nil { + return 0 + } + return SizeVarint(uint64(*p)) + tagsize +} +func sizeVarintS64Slice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + tagsize + } + return n +} +func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeZigzag32Value(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize +} +func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt32() + if v == 0 { + return 0 + } + return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize +} +func sizeZigzag32Ptr(ptr pointer, tagsize int) int { + p := ptr.getInt32Ptr() + if p == nil { + return 0 + } + v := *p + return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize +} +func sizeZigzag32Slice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize + } + return n +} +func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int { + s := ptr.getInt32Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeZigzag64Value(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize +} +func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toInt64() + if v == 0 { + return 0 + } + return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize +} +func sizeZigzag64Ptr(ptr pointer, tagsize int) int { + p := *ptr.toInt64Ptr() + if p == nil { + return 0 + } + v := *p + return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize +} +func sizeZigzag64Slice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize + } + return n +} +func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return 0 + } + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) + } + return n + SizeVarint(uint64(n)) + tagsize +} +func sizeBoolValue(_ pointer, tagsize int) int { + return 1 + tagsize +} +func sizeBoolValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toBool() + if !v { + return 0 + } + return 1 + tagsize +} +func sizeBoolPtr(ptr pointer, tagsize int) int { + p := *ptr.toBoolPtr() + if p == nil { + return 0 + } + return 1 + tagsize +} +func sizeBoolSlice(ptr pointer, tagsize int) int { + s := *ptr.toBoolSlice() + return (1 + tagsize) * len(s) +} +func sizeBoolPackedSlice(ptr pointer, tagsize int) int { + s := *ptr.toBoolSlice() + if len(s) == 0 { + return 0 + } + return len(s) + SizeVarint(uint64(len(s))) + tagsize +} +func sizeStringValue(ptr pointer, tagsize int) int { + v := *ptr.toString() + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeStringValueNoZero(ptr pointer, tagsize int) int { + v := *ptr.toString() + if v == "" { + return 0 + } + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeStringPtr(ptr pointer, tagsize int) int { + p := *ptr.toStringPtr() + if p == nil { + return 0 + } + v := *p + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeStringSlice(ptr pointer, tagsize int) int { + s := *ptr.toStringSlice() + n := 0 + for _, v := range s { + n += len(v) + SizeVarint(uint64(len(v))) + tagsize + } + return n +} +func sizeBytes(ptr pointer, tagsize int) int { + v := *ptr.toBytes() + if v == nil { + return 0 + } + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeBytes3(ptr pointer, tagsize int) int { + v := *ptr.toBytes() + if len(v) == 0 { + return 0 + } + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeBytesOneof(ptr pointer, tagsize int) int { + v := *ptr.toBytes() + return len(v) + SizeVarint(uint64(len(v))) + tagsize +} +func sizeBytesSlice(ptr pointer, tagsize int) int { + s := *ptr.toBytesSlice() + n := 0 + for _, v := range s { + n += len(v) + SizeVarint(uint64(len(v))) + tagsize + } + return n +} + +// appendFixed32 appends an encoded fixed32 to b. +func appendFixed32(b []byte, v uint32) []byte { + b = append(b, + byte(v), + byte(v>>8), + byte(v>>16), + byte(v>>24)) + return b +} + +// appendFixed64 appends an encoded fixed64 to b. +func appendFixed64(b []byte, v uint64) []byte { + b = append(b, + byte(v), + byte(v>>8), + byte(v>>16), + byte(v>>24), + byte(v>>32), + byte(v>>40), + byte(v>>48), + byte(v>>56)) + return b +} + +// appendVarint appends an encoded varint to b. +func appendVarint(b []byte, v uint64) []byte { + // TODO: make 1-byte (maybe 2-byte) case inline-able, once we + // have non-leaf inliner. + switch { + case v < 1<<7: + b = append(b, byte(v)) + case v < 1<<14: + b = append(b, + byte(v&0x7f|0x80), + byte(v>>7)) + case v < 1<<21: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte(v>>14)) + case v < 1<<28: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte(v>>21)) + case v < 1<<35: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte(v>>28)) + case v < 1<<42: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte(v>>35)) + case v < 1<<49: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte(v>>42)) + case v < 1<<56: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte(v>>49)) + case v < 1<<63: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte((v>>49)&0x7f|0x80), + byte(v>>56)) + default: + b = append(b, + byte(v&0x7f|0x80), + byte((v>>7)&0x7f|0x80), + byte((v>>14)&0x7f|0x80), + byte((v>>21)&0x7f|0x80), + byte((v>>28)&0x7f|0x80), + byte((v>>35)&0x7f|0x80), + byte((v>>42)&0x7f|0x80), + byte((v>>49)&0x7f|0x80), + byte((v>>56)&0x7f|0x80), + 1) + } + return b +} + +func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, *p) + return b, nil +} +func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + } + return b, nil +} +func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(4*len(s))) + for _, v := range s { + b = appendFixed32(b, v) + } + return b, nil +} +func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(v)) + return b, nil +} +func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(v)) + return b, nil +} +func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := ptr.getInt32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(*p)) + return b, nil +} +func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed32(b, uint32(v)) + } + return b, nil +} +func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(4*len(s))) + for _, v := range s { + b = appendFixed32(b, uint32(v)) + } + return b, nil +} +func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float32bits(*ptr.toFloat32()) + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float32bits(*ptr.toFloat32()) + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, v) + return b, nil +} +func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toFloat32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed32(b, math.Float32bits(*p)) + return b, nil +} +func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed32(b, math.Float32bits(v)) + } + return b, nil +} +func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(4*len(s))) + for _, v := range s { + b = appendFixed32(b, math.Float32bits(v)) + } + return b, nil +} +func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, *p) + return b, nil +} +func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + } + return b, nil +} +func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(8*len(s))) + for _, v := range s { + b = appendFixed64(b, v) + } + return b, nil +} +func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(v)) + return b, nil +} +func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(v)) + return b, nil +} +func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toInt64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(*p)) + return b, nil +} +func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed64(b, uint64(v)) + } + return b, nil +} +func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(8*len(s))) + for _, v := range s { + b = appendFixed64(b, uint64(v)) + } + return b, nil +} +func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float64bits(*ptr.toFloat64()) + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := math.Float64bits(*ptr.toFloat64()) + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, v) + return b, nil +} +func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toFloat64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendFixed64(b, math.Float64bits(*p)) + return b, nil +} +func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendFixed64(b, math.Float64bits(v)) + } + return b, nil +} +func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toFloat64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(8*len(s))) + for _, v := range s { + b = appendFixed64(b, math.Float64bits(v)) + } + return b, nil +} +func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(*p)) + return b, nil +} +func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := ptr.getInt32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(*p)) + return b, nil +} +func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + b = appendVarint(b, wiretag) + b = appendVarint(b, v) + return b, nil +} +func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toUint64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, v) + return b, nil +} +func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toUint64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, *p) + return b, nil +} +func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, v) + } + return b, nil +} +func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toUint64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(v) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, v) + } + return b, nil +} +func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + return b, nil +} +func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toInt64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(*p)) + return b, nil +} +func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v)) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v)) + } + return b, nil +} +func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + return b, nil +} +func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt32() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + return b, nil +} +func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := ptr.getInt32Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + v := *p + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + return b, nil +} +func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + } + return b, nil +} +func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := ptr.getInt32Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31)))) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + } + return b, nil +} +func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + return b, nil +} +func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toInt64() + if v == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + return b, nil +} +func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toInt64Ptr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + v := *p + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + return b, nil +} +func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + } + return b, nil +} +func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toInt64Slice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + // compute size + n := 0 + for _, v := range s { + n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63))) + } + b = appendVarint(b, uint64(n)) + for _, v := range s { + b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63))) + } + return b, nil +} +func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBool() + b = appendVarint(b, wiretag) + if v { + b = append(b, 1) + } else { + b = append(b, 0) + } + return b, nil +} +func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBool() + if !v { + return b, nil + } + b = appendVarint(b, wiretag) + b = append(b, 1) + return b, nil +} + +func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toBoolPtr() + if p == nil { + return b, nil + } + b = appendVarint(b, wiretag) + if *p { + b = append(b, 1) + } else { + b = append(b, 0) + } + return b, nil +} +func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toBoolSlice() + for _, v := range s { + b = appendVarint(b, wiretag) + if v { + b = append(b, 1) + } else { + b = append(b, 0) + } + } + return b, nil +} +func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toBoolSlice() + if len(s) == 0 { + return b, nil + } + b = appendVarint(b, wiretag&^7|WireBytes) + b = appendVarint(b, uint64(len(s))) + for _, v := range s { + if v { + b = append(b, 1) + } else { + b = append(b, 0) + } + } + return b, nil +} +func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toString() + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toString() + if v == "" { + return b, nil + } + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + p := *ptr.toStringPtr() + if p == nil { + return b, nil + } + v := *p + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toStringSlice() + for _, v := range s { + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + } + return b, nil +} +func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBytes() + if v == nil { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBytes() + if len(v) == 0 { + return b, nil + } + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + v := *ptr.toBytes() + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + return b, nil +} +func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) { + s := *ptr.toBytesSlice() + for _, v := range s { + b = appendVarint(b, wiretag) + b = appendVarint(b, uint64(len(v))) + b = append(b, v...) + } + return b, nil +} + +// makeGroupMarshaler returns the sizer and marshaler for a group. +// u is the marshal info of the underlying message. +func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + p := ptr.getPointer() + if p.isNil() { + return 0 + } + return u.size(p) + 2*tagsize + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + p := ptr.getPointer() + if p.isNil() { + return b, nil + } + var err error + b = appendVarint(b, wiretag) // start group + b, err = u.marshal(b, p, deterministic) + b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group + return b, err + } +} + +// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice. +// u is the marshal info of the underlying message. +func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getPointerSlice() + n := 0 + for _, v := range s { + if v.isNil() { + continue + } + n += u.size(v) + 2*tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getPointerSlice() + var err, errreq error + for _, v := range s { + if v.isNil() { + return b, errRepeatedHasNil + } + b = appendVarint(b, wiretag) // start group + b, err = u.marshal(b, v, deterministic) + b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group + if err != nil { + if _, ok := err.(*RequiredNotSetError); ok { + // Required field in submessage is not set. + // We record the error but keep going, to give a complete marshaling. + if errreq == nil { + errreq = err + } + continue + } + if err == ErrNil { + err = errRepeatedHasNil + } + return b, err + } + } + return b, errreq + } +} + +// makeMessageMarshaler returns the sizer and marshaler for a message field. +// u is the marshal info of the message. +func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + p := ptr.getPointer() + if p.isNil() { + return 0 + } + siz := u.size(p) + return siz + SizeVarint(uint64(siz)) + tagsize + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + p := ptr.getPointer() + if p.isNil() { + return b, nil + } + b = appendVarint(b, wiretag) + siz := u.cachedsize(p) + b = appendVarint(b, uint64(siz)) + return u.marshal(b, p, deterministic) + } +} + +// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice. +// u is the marshal info of the message. +func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) { + return func(ptr pointer, tagsize int) int { + s := ptr.getPointerSlice() + n := 0 + for _, v := range s { + if v.isNil() { + continue + } + siz := u.size(v) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) { + s := ptr.getPointerSlice() + var err, errreq error + for _, v := range s { + if v.isNil() { + return b, errRepeatedHasNil + } + b = appendVarint(b, wiretag) + siz := u.cachedsize(v) + b = appendVarint(b, uint64(siz)) + b, err = u.marshal(b, v, deterministic) + + if err != nil { + if _, ok := err.(*RequiredNotSetError); ok { + // Required field in submessage is not set. + // We record the error but keep going, to give a complete marshaling. + if errreq == nil { + errreq = err + } + continue + } + if err == ErrNil { + err = errRepeatedHasNil + } + return b, err + } + } + return b, errreq + } +} + +// makeMapMarshaler returns the sizer and marshaler for a map field. +// f is the pointer to the reflect data structure of the field. +func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) { + // figure out key and value type + t := f.Type + keyType := t.Key() + valType := t.Elem() + keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",") + valTags := strings.Split(f.Tag.Get("protobuf_val"), ",") + keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map + valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map + keyWireTag := 1<<3 | wiretype(keyTags[0]) + valWireTag := 2<<3 | wiretype(valTags[0]) + + // We create an interface to get the addresses of the map key and value. + // If value is pointer-typed, the interface is a direct interface, the + // idata itself is the value. Otherwise, the idata is the pointer to the + // value. + // Key cannot be pointer-typed. + valIsPtr := valType.Kind() == reflect.Ptr + return func(ptr pointer, tagsize int) int { + m := ptr.asPointerTo(t).Elem() // the map + n := 0 + for _, k := range m.MapKeys() { + ki := k.Interface() + vi := m.MapIndex(k).Interface() + kaddr := toAddrPointer(&ki, false) // pointer to key + vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value + siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) + n += siz + SizeVarint(uint64(siz)) + tagsize + } + return n + }, + func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) { + m := ptr.asPointerTo(t).Elem() // the map + var err error + keys := m.MapKeys() + if len(keys) > 1 && deterministic { + sort.Sort(mapKeys(keys)) + } + for _, k := range keys { + ki := k.Interface() + vi := m.MapIndex(k).Interface() + kaddr := toAddrPointer(&ki, false) // pointer to key + vaddr := toAddrPointer(&vi, valIsPtr) // pointer to value + b = appendVarint(b, tag) + siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1) + b = appendVarint(b, uint64(siz)) + b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic) + if err != nil { + return b, err + } + b, err = valMarshaler(b, vaddr, valWireTag, deterministic) + if err != nil && err != ErrNil { // allow nil value in map + return b, err + } + } + return b, nil + } +} + +// makeOneOfMarshaler returns the sizer and marshaler for a oneof field. +// fi is the marshal info of the field. +// f is the pointer to the reflect data structure of the field. +func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) { + // Oneof field is an interface. We need to get the actual data type on the fly. + t := f.Type + return func(ptr pointer, _ int) int { + p := ptr.getInterfacePointer() + if p.isNil() { + return 0 + } + v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct + telem := v.Type() + e := fi.oneofElems[telem] + return e.sizer(p, e.tagsize) + }, + func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) { + p := ptr.getInterfacePointer() + if p.isNil() { + return b, nil + } + v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct + telem := v.Type() + if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() { + return b, errOneofHasNil + } + e := fi.oneofElems[telem] + return e.marshaler(b, p, e.wiretag, deterministic) + } +} + +// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field. +func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int { + m, mu := ext.extensionsRead() + if m == nil { + return 0 + } + mu.Lock() + + n := 0 + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + n += len(e.enc) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + n += ei.sizer(p, ei.tagsize) + } + mu.Unlock() + return n +} + +// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b. +func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { + m, mu := ext.extensionsRead() + if m == nil { + return b, nil + } + mu.Lock() + defer mu.Unlock() + + var err error + + // Fast-path for common cases: zero or one extensions. + // Don't bother sorting the keys. + if len(m) <= 1 { + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + b = append(b, e.enc...) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, ei.wiretag, deterministic) + if err != nil { + return b, err + } + } + return b, nil + } + + // Sort the keys to provide a deterministic encoding. + // Not sure this is required, but the old code does it. + keys := make([]int, 0, len(m)) + for k := range m { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + for _, k := range keys { + e := m[int32(k)] + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + b = append(b, e.enc...) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, ei.wiretag, deterministic) + if err != nil { + return b, err + } + } + return b, nil +} + +// message set format is: +// message MessageSet { +// repeated group Item = 1 { +// required int32 type_id = 2; +// required string message = 3; +// }; +// } + +// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field +// in message set format (above). +func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int { + m, mu := ext.extensionsRead() + if m == nil { + return 0 + } + mu.Lock() + + n := 0 + for id, e := range m { + n += 2 // start group, end group. tag = 1 (size=1) + n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1) + + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint + siz := len(msgWithLen) + n += siz + 1 // message, tag = 3 (size=1) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + n += ei.sizer(p, 1) // message, tag = 3 (size=1) + } + mu.Unlock() + return n +} + +// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above) +// to the end of byte slice b. +func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) { + m, mu := ext.extensionsRead() + if m == nil { + return b, nil + } + mu.Lock() + defer mu.Unlock() + + var err error + + // Fast-path for common cases: zero or one extensions. + // Don't bother sorting the keys. + if len(m) <= 1 { + for id, e := range m { + b = append(b, 1<<3|WireStartGroup) + b = append(b, 2<<3|WireVarint) + b = appendVarint(b, uint64(id)) + + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint + b = append(b, 3<<3|WireBytes) + b = append(b, msgWithLen...) + b = append(b, 1<<3|WireEndGroup) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) + if err != nil { + return b, err + } + b = append(b, 1<<3|WireEndGroup) + } + return b, nil + } + + // Sort the keys to provide a deterministic encoding. + keys := make([]int, 0, len(m)) + for k := range m { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + for _, id := range keys { + e := m[int32(id)] + b = append(b, 1<<3|WireStartGroup) + b = append(b, 2<<3|WireVarint) + b = appendVarint(b, uint64(id)) + + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint + b = append(b, 3<<3|WireBytes) + b = append(b, msgWithLen...) + b = append(b, 1<<3|WireEndGroup) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic) + b = append(b, 1<<3|WireEndGroup) + if err != nil { + return b, err + } + } + return b, nil +} + +// sizeV1Extensions computes the size of encoded data for a V1-API extension field. +func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int { + if m == nil { + return 0 + } + + n := 0 + for _, e := range m { + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + n += len(e.enc) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + n += ei.sizer(p, ei.tagsize) + } + return n +} + +// appendV1Extensions marshals a V1-API extension field to the end of byte slice b. +func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) { + if m == nil { + return b, nil + } + + // Sort the keys to provide a deterministic encoding. + keys := make([]int, 0, len(m)) + for k := range m { + keys = append(keys, int(k)) + } + sort.Ints(keys) + + var err error + for _, k := range keys { + e := m[int32(k)] + if e.value == nil || e.desc == nil { + // Extension is only in its encoded form. + b = append(b, e.enc...) + continue + } + + // We don't skip extensions that have an encoded form set, + // because the extension value may have been mutated after + // the last time this function was called. + + ei := u.getExtElemInfo(e.desc) + v := e.value + p := toAddrPointer(&v, ei.isptr) + b, err = ei.marshaler(b, p, ei.wiretag, deterministic) + if err != nil { + return b, err + } + } + return b, nil +} + +// newMarshaler is the interface representing objects that can marshal themselves. +// +// This exists to support protoc-gen-go generated messages. +// The proto package will stop type-asserting to this interface in the future. +// +// DO NOT DEPEND ON THIS. +type newMarshaler interface { + XXX_Size() int + XXX_Marshal(b []byte, deterministic bool) ([]byte, error) +} + +// Size returns the encoded size of a protocol buffer message. +// This is the main entry point. +func Size(pb Message) int { + if m, ok := pb.(newMarshaler); ok { + return m.XXX_Size() + } + if m, ok := pb.(Marshaler); ok { + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + b, _ := m.Marshal() + return len(b) + } + // in case somehow we didn't generate the wrapper + if pb == nil { + return 0 + } + var info InternalMessageInfo + return info.Size(pb) +} + +// Marshal takes a protocol buffer message +// and encodes it into the wire format, returning the data. +// This is the main entry point. +func Marshal(pb Message) ([]byte, error) { + if m, ok := pb.(newMarshaler); ok { + siz := m.XXX_Size() + b := make([]byte, 0, siz) + return m.XXX_Marshal(b, false) + } + if m, ok := pb.(Marshaler); ok { + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + return m.Marshal() + } + // in case somehow we didn't generate the wrapper + if pb == nil { + return nil, ErrNil + } + var info InternalMessageInfo + siz := info.Size(pb) + b := make([]byte, 0, siz) + return info.Marshal(b, pb, false) +} + +// Marshal takes a protocol buffer message +// and encodes it into the wire format, writing the result to the +// Buffer. +// This is an alternative entry point. It is not necessary to use +// a Buffer for most applications. +func (p *Buffer) Marshal(pb Message) error { + var err error + if m, ok := pb.(newMarshaler); ok { + siz := m.XXX_Size() + p.grow(siz) // make sure buf has enough capacity + p.buf, err = m.XXX_Marshal(p.buf, p.deterministic) + return err + } + if m, ok := pb.(Marshaler); ok { + // If the message can marshal itself, let it do it, for compatibility. + // NOTE: This is not efficient. + b, err := m.Marshal() + p.buf = append(p.buf, b...) + return err + } + // in case somehow we didn't generate the wrapper + if pb == nil { + return ErrNil + } + var info InternalMessageInfo + siz := info.Size(pb) + p.grow(siz) // make sure buf has enough capacity + p.buf, err = info.Marshal(p.buf, pb, p.deterministic) + return err +} + +// grow grows the buffer's capacity, if necessary, to guarantee space for +// another n bytes. After grow(n), at least n bytes can be written to the +// buffer without another allocation. +func (p *Buffer) grow(n int) { + need := len(p.buf) + n + if need <= cap(p.buf) { + return + } + newCap := len(p.buf) * 2 + if newCap < need { + newCap = need + } + p.buf = append(make([]byte, 0, newCap), p.buf...) +} diff --git a/vendor/github.com/golang/protobuf/proto/table_merge.go b/vendor/github.com/golang/protobuf/proto/table_merge.go new file mode 100644 index 0000000000..5525def6a5 --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/table_merge.go @@ -0,0 +1,654 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// 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. + +package proto + +import ( + "fmt" + "reflect" + "strings" + "sync" + "sync/atomic" +) + +// Merge merges the src message into dst. +// This assumes that dst and src of the same type and are non-nil. +func (a *InternalMessageInfo) Merge(dst, src Message) { + mi := atomicLoadMergeInfo(&a.merge) + if mi == nil { + mi = getMergeInfo(reflect.TypeOf(dst).Elem()) + atomicStoreMergeInfo(&a.merge, mi) + } + mi.merge(toPointer(&dst), toPointer(&src)) +} + +type mergeInfo struct { + typ reflect.Type + + initialized int32 // 0: only typ is valid, 1: everything is valid + lock sync.Mutex + + fields []mergeFieldInfo + unrecognized field // Offset of XXX_unrecognized +} + +type mergeFieldInfo struct { + field field // Offset of field, guaranteed to be valid + + // isPointer reports whether the value in the field is a pointer. + // This is true for the following situations: + // * Pointer to struct + // * Pointer to basic type (proto2 only) + // * Slice (first value in slice header is a pointer) + // * String (first value in string header is a pointer) + isPointer bool + + // basicWidth reports the width of the field assuming that it is directly + // embedded in the struct (as is the case for basic types in proto3). + // The possible values are: + // 0: invalid + // 1: bool + // 4: int32, uint32, float32 + // 8: int64, uint64, float64 + basicWidth int + + // Where dst and src are pointers to the types being merged. + merge func(dst, src pointer) +} + +var ( + mergeInfoMap = map[reflect.Type]*mergeInfo{} + mergeInfoLock sync.Mutex +) + +func getMergeInfo(t reflect.Type) *mergeInfo { + mergeInfoLock.Lock() + defer mergeInfoLock.Unlock() + mi := mergeInfoMap[t] + if mi == nil { + mi = &mergeInfo{typ: t} + mergeInfoMap[t] = mi + } + return mi +} + +// merge merges src into dst assuming they are both of type *mi.typ. +func (mi *mergeInfo) merge(dst, src pointer) { + if dst.isNil() { + panic("proto: nil destination") + } + if src.isNil() { + return // Nothing to do. + } + + if atomic.LoadInt32(&mi.initialized) == 0 { + mi.computeMergeInfo() + } + + for _, fi := range mi.fields { + sfp := src.offset(fi.field) + + // As an optimization, we can avoid the merge function call cost + // if we know for sure that the source will have no effect + // by checking if it is the zero value. + if unsafeAllowed { + if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string + continue + } + if fi.basicWidth > 0 { + switch { + case fi.basicWidth == 1 && !*sfp.toBool(): + continue + case fi.basicWidth == 4 && *sfp.toUint32() == 0: + continue + case fi.basicWidth == 8 && *sfp.toUint64() == 0: + continue + } + } + } + + dfp := dst.offset(fi.field) + fi.merge(dfp, sfp) + } + + // TODO: Make this faster? + out := dst.asPointerTo(mi.typ).Elem() + in := src.asPointerTo(mi.typ).Elem() + if emIn, err := extendable(in.Addr().Interface()); err == nil { + emOut, _ := extendable(out.Addr().Interface()) + mIn, muIn := emIn.extensionsRead() + if mIn != nil { + mOut := emOut.extensionsWrite() + muIn.Lock() + mergeExtension(mOut, mIn) + muIn.Unlock() + } + } + + if mi.unrecognized.IsValid() { + if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { + *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) + } + } +} + +func (mi *mergeInfo) computeMergeInfo() { + mi.lock.Lock() + defer mi.lock.Unlock() + if mi.initialized != 0 { + return + } + t := mi.typ + n := t.NumField() + + props := GetProperties(t) + for i := 0; i < n; i++ { + f := t.Field(i) + if strings.HasPrefix(f.Name, "XXX_") { + continue + } + + mfi := mergeFieldInfo{field: toField(&f)} + tf := f.Type + + // As an optimization, we can avoid the merge function call cost + // if we know for sure that the source will have no effect + // by checking if it is the zero value. + if unsafeAllowed { + switch tf.Kind() { + case reflect.Ptr, reflect.Slice, reflect.String: + // As a special case, we assume slices and strings are pointers + // since we know that the first field in the SliceSlice or + // StringHeader is a data pointer. + mfi.isPointer = true + case reflect.Bool: + mfi.basicWidth = 1 + case reflect.Int32, reflect.Uint32, reflect.Float32: + mfi.basicWidth = 4 + case reflect.Int64, reflect.Uint64, reflect.Float64: + mfi.basicWidth = 8 + } + } + + // Unwrap tf to get at its most basic type. + var isPointer, isSlice bool + if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { + isSlice = true + tf = tf.Elem() + } + if tf.Kind() == reflect.Ptr { + isPointer = true + tf = tf.Elem() + } + if isPointer && isSlice && tf.Kind() != reflect.Struct { + panic("both pointer and slice for basic type in " + tf.Name()) + } + + switch tf.Kind() { + case reflect.Int32: + switch { + case isSlice: // E.g., []int32 + mfi.merge = func(dst, src pointer) { + // NOTE: toInt32Slice is not defined (see pointer_reflect.go). + /* + sfsp := src.toInt32Slice() + if *sfsp != nil { + dfsp := dst.toInt32Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []int64{} + } + } + */ + sfs := src.getInt32Slice() + if sfs != nil { + dfs := dst.getInt32Slice() + dfs = append(dfs, sfs...) + if dfs == nil { + dfs = []int32{} + } + dst.setInt32Slice(dfs) + } + } + case isPointer: // E.g., *int32 + mfi.merge = func(dst, src pointer) { + // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). + /* + sfpp := src.toInt32Ptr() + if *sfpp != nil { + dfpp := dst.toInt32Ptr() + if *dfpp == nil { + *dfpp = Int32(**sfpp) + } else { + **dfpp = **sfpp + } + } + */ + sfp := src.getInt32Ptr() + if sfp != nil { + dfp := dst.getInt32Ptr() + if dfp == nil { + dst.setInt32Ptr(*sfp) + } else { + *dfp = *sfp + } + } + } + default: // E.g., int32 + mfi.merge = func(dst, src pointer) { + if v := *src.toInt32(); v != 0 { + *dst.toInt32() = v + } + } + } + case reflect.Int64: + switch { + case isSlice: // E.g., []int64 + mfi.merge = func(dst, src pointer) { + sfsp := src.toInt64Slice() + if *sfsp != nil { + dfsp := dst.toInt64Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []int64{} + } + } + } + case isPointer: // E.g., *int64 + mfi.merge = func(dst, src pointer) { + sfpp := src.toInt64Ptr() + if *sfpp != nil { + dfpp := dst.toInt64Ptr() + if *dfpp == nil { + *dfpp = Int64(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., int64 + mfi.merge = func(dst, src pointer) { + if v := *src.toInt64(); v != 0 { + *dst.toInt64() = v + } + } + } + case reflect.Uint32: + switch { + case isSlice: // E.g., []uint32 + mfi.merge = func(dst, src pointer) { + sfsp := src.toUint32Slice() + if *sfsp != nil { + dfsp := dst.toUint32Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []uint32{} + } + } + } + case isPointer: // E.g., *uint32 + mfi.merge = func(dst, src pointer) { + sfpp := src.toUint32Ptr() + if *sfpp != nil { + dfpp := dst.toUint32Ptr() + if *dfpp == nil { + *dfpp = Uint32(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., uint32 + mfi.merge = func(dst, src pointer) { + if v := *src.toUint32(); v != 0 { + *dst.toUint32() = v + } + } + } + case reflect.Uint64: + switch { + case isSlice: // E.g., []uint64 + mfi.merge = func(dst, src pointer) { + sfsp := src.toUint64Slice() + if *sfsp != nil { + dfsp := dst.toUint64Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []uint64{} + } + } + } + case isPointer: // E.g., *uint64 + mfi.merge = func(dst, src pointer) { + sfpp := src.toUint64Ptr() + if *sfpp != nil { + dfpp := dst.toUint64Ptr() + if *dfpp == nil { + *dfpp = Uint64(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., uint64 + mfi.merge = func(dst, src pointer) { + if v := *src.toUint64(); v != 0 { + *dst.toUint64() = v + } + } + } + case reflect.Float32: + switch { + case isSlice: // E.g., []float32 + mfi.merge = func(dst, src pointer) { + sfsp := src.toFloat32Slice() + if *sfsp != nil { + dfsp := dst.toFloat32Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []float32{} + } + } + } + case isPointer: // E.g., *float32 + mfi.merge = func(dst, src pointer) { + sfpp := src.toFloat32Ptr() + if *sfpp != nil { + dfpp := dst.toFloat32Ptr() + if *dfpp == nil { + *dfpp = Float32(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., float32 + mfi.merge = func(dst, src pointer) { + if v := *src.toFloat32(); v != 0 { + *dst.toFloat32() = v + } + } + } + case reflect.Float64: + switch { + case isSlice: // E.g., []float64 + mfi.merge = func(dst, src pointer) { + sfsp := src.toFloat64Slice() + if *sfsp != nil { + dfsp := dst.toFloat64Slice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []float64{} + } + } + } + case isPointer: // E.g., *float64 + mfi.merge = func(dst, src pointer) { + sfpp := src.toFloat64Ptr() + if *sfpp != nil { + dfpp := dst.toFloat64Ptr() + if *dfpp == nil { + *dfpp = Float64(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., float64 + mfi.merge = func(dst, src pointer) { + if v := *src.toFloat64(); v != 0 { + *dst.toFloat64() = v + } + } + } + case reflect.Bool: + switch { + case isSlice: // E.g., []bool + mfi.merge = func(dst, src pointer) { + sfsp := src.toBoolSlice() + if *sfsp != nil { + dfsp := dst.toBoolSlice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []bool{} + } + } + } + case isPointer: // E.g., *bool + mfi.merge = func(dst, src pointer) { + sfpp := src.toBoolPtr() + if *sfpp != nil { + dfpp := dst.toBoolPtr() + if *dfpp == nil { + *dfpp = Bool(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., bool + mfi.merge = func(dst, src pointer) { + if v := *src.toBool(); v { + *dst.toBool() = v + } + } + } + case reflect.String: + switch { + case isSlice: // E.g., []string + mfi.merge = func(dst, src pointer) { + sfsp := src.toStringSlice() + if *sfsp != nil { + dfsp := dst.toStringSlice() + *dfsp = append(*dfsp, *sfsp...) + if *dfsp == nil { + *dfsp = []string{} + } + } + } + case isPointer: // E.g., *string + mfi.merge = func(dst, src pointer) { + sfpp := src.toStringPtr() + if *sfpp != nil { + dfpp := dst.toStringPtr() + if *dfpp == nil { + *dfpp = String(**sfpp) + } else { + **dfpp = **sfpp + } + } + } + default: // E.g., string + mfi.merge = func(dst, src pointer) { + if v := *src.toString(); v != "" { + *dst.toString() = v + } + } + } + case reflect.Slice: + isProto3 := props.Prop[i].proto3 + switch { + case isPointer: + panic("bad pointer in byte slice case in " + tf.Name()) + case tf.Elem().Kind() != reflect.Uint8: + panic("bad element kind in byte slice case in " + tf.Name()) + case isSlice: // E.g., [][]byte + mfi.merge = func(dst, src pointer) { + sbsp := src.toBytesSlice() + if *sbsp != nil { + dbsp := dst.toBytesSlice() + for _, sb := range *sbsp { + if sb == nil { + *dbsp = append(*dbsp, nil) + } else { + *dbsp = append(*dbsp, append([]byte{}, sb...)) + } + } + if *dbsp == nil { + *dbsp = [][]byte{} + } + } + } + default: // E.g., []byte + mfi.merge = func(dst, src pointer) { + sbp := src.toBytes() + if *sbp != nil { + dbp := dst.toBytes() + if !isProto3 || len(*sbp) > 0 { + *dbp = append([]byte{}, *sbp...) + } + } + } + } + case reflect.Struct: + switch { + case !isPointer: + panic(fmt.Sprintf("message field %s without pointer", tf)) + case isSlice: // E.g., []*pb.T + mi := getMergeInfo(tf) + mfi.merge = func(dst, src pointer) { + sps := src.getPointerSlice() + if sps != nil { + dps := dst.getPointerSlice() + for _, sp := range sps { + var dp pointer + if !sp.isNil() { + dp = valToPointer(reflect.New(tf)) + mi.merge(dp, sp) + } + dps = append(dps, dp) + } + if dps == nil { + dps = []pointer{} + } + dst.setPointerSlice(dps) + } + } + default: // E.g., *pb.T + mi := getMergeInfo(tf) + mfi.merge = func(dst, src pointer) { + sp := src.getPointer() + if !sp.isNil() { + dp := dst.getPointer() + if dp.isNil() { + dp = valToPointer(reflect.New(tf)) + dst.setPointer(dp) + } + mi.merge(dp, sp) + } + } + } + case reflect.Map: + switch { + case isPointer || isSlice: + panic("bad pointer or slice in map case in " + tf.Name()) + default: // E.g., map[K]V + mfi.merge = func(dst, src pointer) { + sm := src.asPointerTo(tf).Elem() + if sm.Len() == 0 { + return + } + dm := dst.asPointerTo(tf).Elem() + if dm.IsNil() { + dm.Set(reflect.MakeMap(tf)) + } + + switch tf.Elem().Kind() { + case reflect.Ptr: // Proto struct (e.g., *T) + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + val = reflect.ValueOf(Clone(val.Interface().(Message))) + dm.SetMapIndex(key, val) + } + case reflect.Slice: // E.g. Bytes type (e.g., []byte) + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) + dm.SetMapIndex(key, val) + } + default: // Basic type (e.g., string) + for _, key := range sm.MapKeys() { + val := sm.MapIndex(key) + dm.SetMapIndex(key, val) + } + } + } + } + case reflect.Interface: + // Must be oneof field. + switch { + case isPointer || isSlice: + panic("bad pointer or slice in interface case in " + tf.Name()) + default: // E.g., interface{} + // TODO: Make this faster? + mfi.merge = func(dst, src pointer) { + su := src.asPointerTo(tf).Elem() + if !su.IsNil() { + du := dst.asPointerTo(tf).Elem() + typ := su.Elem().Type() + if du.IsNil() || du.Elem().Type() != typ { + du.Set(reflect.New(typ.Elem())) // Initialize interface if empty + } + sv := su.Elem().Elem().Field(0) + if sv.Kind() == reflect.Ptr && sv.IsNil() { + return + } + dv := du.Elem().Elem().Field(0) + if dv.Kind() == reflect.Ptr && dv.IsNil() { + dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty + } + switch sv.Type().Kind() { + case reflect.Ptr: // Proto struct (e.g., *T) + Merge(dv.Interface().(Message), sv.Interface().(Message)) + case reflect.Slice: // E.g. Bytes type (e.g., []byte) + dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) + default: // Basic type (e.g., string) + dv.Set(sv) + } + } + } + } + default: + panic(fmt.Sprintf("merger not found for type:%s", tf)) + } + mi.fields = append(mi.fields, mfi) + } + + mi.unrecognized = invalidField + if f, ok := t.FieldByName("XXX_unrecognized"); ok { + if f.Type != reflect.TypeOf([]byte{}) { + panic("expected XXX_unrecognized to be of type []byte") + } + mi.unrecognized = toField(&f) + } + + atomic.StoreInt32(&mi.initialized, 1) +} diff --git a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go b/vendor/github.com/golang/protobuf/proto/table_unmarshal.go new file mode 100644 index 0000000000..55f0340a3f --- /dev/null +++ b/vendor/github.com/golang/protobuf/proto/table_unmarshal.go @@ -0,0 +1,1967 @@ +// Go support for Protocol Buffers - Google's data interchange format +// +// Copyright 2016 The Go Authors. All rights reserved. +// https://github.com/golang/protobuf +// +// 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. + +package proto + +import ( + "errors" + "fmt" + "io" + "math" + "reflect" + "strconv" + "strings" + "sync" + "sync/atomic" + "unicode/utf8" +) + +// Unmarshal is the entry point from the generated .pb.go files. +// This function is not intended to be used by non-generated code. +// This function is not subject to any compatibility guarantee. +// msg contains a pointer to a protocol buffer struct. +// b is the data to be unmarshaled into the protocol buffer. +// a is a pointer to a place to store cached unmarshal information. +func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { + // Load the unmarshal information for this message type. + // The atomic load ensures memory consistency. + u := atomicLoadUnmarshalInfo(&a.unmarshal) + if u == nil { + // Slow path: find unmarshal info for msg, update a with it. + u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) + atomicStoreUnmarshalInfo(&a.unmarshal, u) + } + // Then do the unmarshaling. + err := u.unmarshal(toPointer(&msg), b) + return err +} + +type unmarshalInfo struct { + typ reflect.Type // type of the protobuf struct + + // 0 = only typ field is initialized + // 1 = completely initialized + initialized int32 + lock sync.Mutex // prevents double initialization + dense []unmarshalFieldInfo // fields indexed by tag # + sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # + reqFields []string // names of required fields + reqMask uint64 // 1< 0 { + // Read tag and wire type. + // Special case 1 and 2 byte varints. + var x uint64 + if b[0] < 128 { + x = uint64(b[0]) + b = b[1:] + } else if len(b) >= 2 && b[1] < 128 { + x = uint64(b[0]&0x7f) + uint64(b[1])<<7 + b = b[2:] + } else { + var n int + x, n = decodeVarint(b) + if n == 0 { + return io.ErrUnexpectedEOF + } + b = b[n:] + } + tag := x >> 3 + wire := int(x) & 7 + + // Dispatch on the tag to one of the unmarshal* functions below. + var f unmarshalFieldInfo + if tag < uint64(len(u.dense)) { + f = u.dense[tag] + } else { + f = u.sparse[tag] + } + if fn := f.unmarshal; fn != nil { + var err error + b, err = fn(b, m.offset(f.field), wire) + if err == nil { + reqMask |= f.reqMask + continue + } + if r, ok := err.(*RequiredNotSetError); ok { + // Remember this error, but keep parsing. We need to produce + // a full parse even if a required field is missing. + rnse = r + reqMask |= f.reqMask + continue + } + if err != errInternalBadWireType { + return err + } + // Fragments with bad wire type are treated as unknown fields. + } + + // Unknown tag. + if !u.unrecognized.IsValid() { + // Don't keep unrecognized data; just skip it. + var err error + b, err = skipField(b, wire) + if err != nil { + return err + } + continue + } + // Keep unrecognized data around. + // maybe in extensions, maybe in the unrecognized field. + z := m.offset(u.unrecognized).toBytes() + var emap map[int32]Extension + var e Extension + for _, r := range u.extensionRanges { + if uint64(r.Start) <= tag && tag <= uint64(r.End) { + if u.extensions.IsValid() { + mp := m.offset(u.extensions).toExtensions() + emap = mp.extensionsWrite() + e = emap[int32(tag)] + z = &e.enc + break + } + if u.oldExtensions.IsValid() { + p := m.offset(u.oldExtensions).toOldExtensions() + emap = *p + if emap == nil { + emap = map[int32]Extension{} + *p = emap + } + e = emap[int32(tag)] + z = &e.enc + break + } + panic("no extensions field available") + } + } + + // Use wire type to skip data. + var err error + b0 := b + b, err = skipField(b, wire) + if err != nil { + return err + } + *z = encodeVarint(*z, tag<<3|uint64(wire)) + *z = append(*z, b0[:len(b0)-len(b)]...) + + if emap != nil { + emap[int32(tag)] = e + } + } + if rnse != nil { + // A required field of a submessage/group is missing. Return that error. + return rnse + } + if reqMask != u.reqMask { + // A required field of this message is missing. + for _, n := range u.reqFields { + if reqMask&1 == 0 { + return &RequiredNotSetError{n} + } + reqMask >>= 1 + } + } + return nil +} + +// computeUnmarshalInfo fills in u with information for use +// in unmarshaling protocol buffers of type u.typ. +func (u *unmarshalInfo) computeUnmarshalInfo() { + u.lock.Lock() + defer u.lock.Unlock() + if u.initialized != 0 { + return + } + t := u.typ + n := t.NumField() + + // Set up the "not found" value for the unrecognized byte buffer. + // This is the default for proto3. + u.unrecognized = invalidField + u.extensions = invalidField + u.oldExtensions = invalidField + + // List of the generated type and offset for each oneof field. + type oneofField struct { + ityp reflect.Type // interface type of oneof field + field field // offset in containing message + } + var oneofFields []oneofField + + for i := 0; i < n; i++ { + f := t.Field(i) + if f.Name == "XXX_unrecognized" { + // The byte slice used to hold unrecognized input is special. + if f.Type != reflect.TypeOf(([]byte)(nil)) { + panic("bad type for XXX_unrecognized field: " + f.Type.Name()) + } + u.unrecognized = toField(&f) + continue + } + if f.Name == "XXX_InternalExtensions" { + // Ditto here. + if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { + panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) + } + u.extensions = toField(&f) + if f.Tag.Get("protobuf_messageset") == "1" { + u.isMessageSet = true + } + continue + } + if f.Name == "XXX_extensions" { + // An older form of the extensions field. + if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) { + panic("bad type for XXX_extensions field: " + f.Type.Name()) + } + u.oldExtensions = toField(&f) + continue + } + if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { + continue + } + + oneof := f.Tag.Get("protobuf_oneof") + if oneof != "" { + oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) + // The rest of oneof processing happens below. + continue + } + + tags := f.Tag.Get("protobuf") + tagArray := strings.Split(tags, ",") + if len(tagArray) < 2 { + panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) + } + tag, err := strconv.Atoi(tagArray[1]) + if err != nil { + panic("protobuf tag field not an integer: " + tagArray[1]) + } + + name := "" + for _, tag := range tagArray[3:] { + if strings.HasPrefix(tag, "name=") { + name = tag[5:] + } + } + + // Extract unmarshaling function from the field (its type and tags). + unmarshal := fieldUnmarshaler(&f) + + // Required field? + var reqMask uint64 + if tagArray[2] == "req" { + bit := len(u.reqFields) + u.reqFields = append(u.reqFields, name) + reqMask = uint64(1) << uint(bit) + // TODO: if we have more than 64 required fields, we end up + // not verifying that all required fields are present. + // Fix this, perhaps using a count of required fields? + } + + // Store the info in the correct slot in the message. + u.setTag(tag, toField(&f), unmarshal, reqMask) + } + + // Find any types associated with oneof fields. + // TODO: XXX_OneofFuncs returns more info than we need. Get rid of some of it? + fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("XXX_OneofFuncs") + if fn.IsValid() { + res := fn.Call(nil)[3] // last return value from XXX_OneofFuncs: []interface{} + for i := res.Len() - 1; i >= 0; i-- { + v := res.Index(i) // interface{} + tptr := reflect.ValueOf(v.Interface()).Type() // *Msg_X + typ := tptr.Elem() // Msg_X + + f := typ.Field(0) // oneof implementers have one field + baseUnmarshal := fieldUnmarshaler(&f) + tagstr := strings.Split(f.Tag.Get("protobuf"), ",")[1] + tag, err := strconv.Atoi(tagstr) + if err != nil { + panic("protobuf tag field not an integer: " + tagstr) + } + + // Find the oneof field that this struct implements. + // Might take O(n^2) to process all of the oneofs, but who cares. + for _, of := range oneofFields { + if tptr.Implements(of.ityp) { + // We have found the corresponding interface for this struct. + // That lets us know where this struct should be stored + // when we encounter it during unmarshaling. + unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) + u.setTag(tag, of.field, unmarshal, 0) + } + } + } + } + + // Get extension ranges, if any. + fn = reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") + if fn.IsValid() { + if !u.extensions.IsValid() && !u.oldExtensions.IsValid() { + panic("a message with extensions, but no extensions field in " + t.Name()) + } + u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) + } + + // Explicitly disallow tag 0. This will ensure we flag an error + // when decoding a buffer of all zeros. Without this code, we + // would decode and skip an all-zero buffer of even length. + // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. + u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { + return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) + }, 0) + + // Set mask for required field check. + u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? + for len(u.dense) <= tag { + u.dense = append(u.dense, unmarshalFieldInfo{}) + } + u.dense[tag] = i + return + } + if u.sparse == nil { + u.sparse = map[uint64]unmarshalFieldInfo{} + } + u.sparse[uint64(tag)] = i +} + +// fieldUnmarshaler returns an unmarshaler for the given field. +func fieldUnmarshaler(f *reflect.StructField) unmarshaler { + if f.Type.Kind() == reflect.Map { + return makeUnmarshalMap(f) + } + return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) +} + +// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. +func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { + tagArray := strings.Split(tags, ",") + encoding := tagArray[0] + name := "unknown" + for _, tag := range tagArray[3:] { + if strings.HasPrefix(tag, "name=") { + name = tag[5:] + } + } + + // Figure out packaging (pointer, slice, or both) + slice := false + pointer := false + if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { + slice = true + t = t.Elem() + } + if t.Kind() == reflect.Ptr { + pointer = true + t = t.Elem() + } + + // We'll never have both pointer and slice for basic types. + if pointer && slice && t.Kind() != reflect.Struct { + panic("both pointer and slice for basic type in " + t.Name()) + } + + switch t.Kind() { + case reflect.Bool: + if pointer { + return unmarshalBoolPtr + } + if slice { + return unmarshalBoolSlice + } + return unmarshalBoolValue + case reflect.Int32: + switch encoding { + case "fixed32": + if pointer { + return unmarshalFixedS32Ptr + } + if slice { + return unmarshalFixedS32Slice + } + return unmarshalFixedS32Value + case "varint": + // this could be int32 or enum + if pointer { + return unmarshalInt32Ptr + } + if slice { + return unmarshalInt32Slice + } + return unmarshalInt32Value + case "zigzag32": + if pointer { + return unmarshalSint32Ptr + } + if slice { + return unmarshalSint32Slice + } + return unmarshalSint32Value + } + case reflect.Int64: + switch encoding { + case "fixed64": + if pointer { + return unmarshalFixedS64Ptr + } + if slice { + return unmarshalFixedS64Slice + } + return unmarshalFixedS64Value + case "varint": + if pointer { + return unmarshalInt64Ptr + } + if slice { + return unmarshalInt64Slice + } + return unmarshalInt64Value + case "zigzag64": + if pointer { + return unmarshalSint64Ptr + } + if slice { + return unmarshalSint64Slice + } + return unmarshalSint64Value + } + case reflect.Uint32: + switch encoding { + case "fixed32": + if pointer { + return unmarshalFixed32Ptr + } + if slice { + return unmarshalFixed32Slice + } + return unmarshalFixed32Value + case "varint": + if pointer { + return unmarshalUint32Ptr + } + if slice { + return unmarshalUint32Slice + } + return unmarshalUint32Value + } + case reflect.Uint64: + switch encoding { + case "fixed64": + if pointer { + return unmarshalFixed64Ptr + } + if slice { + return unmarshalFixed64Slice + } + return unmarshalFixed64Value + case "varint": + if pointer { + return unmarshalUint64Ptr + } + if slice { + return unmarshalUint64Slice + } + return unmarshalUint64Value + } + case reflect.Float32: + if pointer { + return unmarshalFloat32Ptr + } + if slice { + return unmarshalFloat32Slice + } + return unmarshalFloat32Value + case reflect.Float64: + if pointer { + return unmarshalFloat64Ptr + } + if slice { + return unmarshalFloat64Slice + } + return unmarshalFloat64Value + case reflect.Map: + panic("map type in typeUnmarshaler in " + t.Name()) + case reflect.Slice: + if pointer { + panic("bad pointer in slice case in " + t.Name()) + } + if slice { + return unmarshalBytesSlice + } + return unmarshalBytesValue + case reflect.String: + if pointer { + return unmarshalStringPtr + } + if slice { + return unmarshalStringSlice + } + return unmarshalStringValue + case reflect.Struct: + // message or group field + if !pointer { + panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding)) + } + switch encoding { + case "bytes": + if slice { + return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) + } + return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) + case "group": + if slice { + return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) + } + return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) + } + } + panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) +} + +// Below are all the unmarshalers for individual fields of various types. + +func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + *f.toInt64() = v + return b, nil +} + +func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + *f.toInt64Ptr() = &v + return b, nil +} + +func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + s := f.toInt64Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x) + s := f.toInt64Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + *f.toInt64() = v + return b, nil +} + +func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + *f.toInt64Ptr() = &v + return b, nil +} + +func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + s := f.toInt64Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int64(x>>1) ^ int64(x)<<63>>63 + s := f.toInt64Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + *f.toUint64() = v + return b, nil +} + +func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + *f.toUint64Ptr() = &v + return b, nil +} + +func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + s := f.toUint64Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint64(x) + s := f.toUint64Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + *f.toInt32() = v + return b, nil +} + +func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + f.setInt32Ptr(v) + return b, nil +} + +func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + f.appendInt32Slice(v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x) + f.appendInt32Slice(v) + return b, nil +} + +func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + *f.toInt32() = v + return b, nil +} + +func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + f.setInt32Ptr(v) + return b, nil +} + +func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + f.appendInt32Slice(v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := int32(x>>1) ^ int32(x)<<31>>31 + f.appendInt32Slice(v) + return b, nil +} + +func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + *f.toUint32() = v + return b, nil +} + +func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + *f.toUint32Ptr() = &v + return b, nil +} + +func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + s := f.toUint32Slice() + *s = append(*s, v) + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + v := uint32(x) + s := f.toUint32Slice() + *s = append(*s, v) + return b, nil +} + +func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := 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 + *f.toUint64() = v + return b[8:], nil +} + +func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := 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 + *f.toUint64Ptr() = &v + return b[8:], nil +} + +func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := 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 + s := f.toUint64Slice() + *s = append(*s, v) + b = b[8:] + } + return res, nil + } + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := 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 + s := f.toUint64Slice() + *s = append(*s, v) + return b[8:], nil +} + +func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + *f.toInt64() = v + return b[8:], nil +} + +func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + *f.toInt64Ptr() = &v + return b[8:], nil +} + +func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + s := f.toInt64Slice() + *s = append(*s, v) + b = b[8:] + } + return res, nil + } + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56 + s := f.toInt64Slice() + *s = append(*s, v) + return b[8:], nil +} + +func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + *f.toUint32() = v + return b[4:], nil +} + +func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + *f.toUint32Ptr() = &v + return b[4:], nil +} + +func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + s := f.toUint32Slice() + *s = append(*s, v) + b = b[4:] + } + return res, nil + } + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 + s := f.toUint32Slice() + *s = append(*s, v) + return b[4:], nil +} + +func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + *f.toInt32() = v + return b[4:], nil +} + +func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + f.setInt32Ptr(v) + return b[4:], nil +} + +func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + f.appendInt32Slice(v) + b = b[4:] + } + return res, nil + } + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24 + f.appendInt32Slice(v) + return b[4:], nil +} + +func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + // Note: any length varint is allowed, even though any sane + // encoder will use one byte. + // See https://github.com/golang/protobuf/issues/76 + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + // TODO: check if x>1? Tests seem to indicate no. + v := x != 0 + *f.toBool() = v + return b[n:], nil +} + +func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + v := x != 0 + *f.toBoolPtr() = &v + return b[n:], nil +} + +func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + x, n = decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + v := x != 0 + s := f.toBoolSlice() + *s = append(*s, v) + b = b[n:] + } + return res, nil + } + if w != WireVarint { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + v := x != 0 + s := f.toBoolSlice() + *s = append(*s, v) + return b[n:], nil +} + +func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(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) + *f.toFloat64() = v + return b[8:], nil +} + +func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(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) + *f.toFloat64Ptr() = &v + return b[8:], nil +} + +func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(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) + s := f.toFloat64Slice() + *s = append(*s, v) + b = b[8:] + } + return res, nil + } + if w != WireFixed64 { + return b, errInternalBadWireType + } + if len(b) < 8 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float64frombits(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) + s := f.toFloat64Slice() + *s = append(*s, v) + return b[8:], nil +} + +func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + *f.toFloat32() = v + return b[4:], nil +} + +func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + *f.toFloat32Ptr() = &v + return b[4:], nil +} + +func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) { + if w == WireBytes { // packed + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + res := b[x:] + b = b[:x] + for len(b) > 0 { + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + s := f.toFloat32Slice() + *s = append(*s, v) + b = b[4:] + } + return res, nil + } + if w != WireFixed32 { + return b, errInternalBadWireType + } + if len(b) < 4 { + return nil, io.ErrUnexpectedEOF + } + v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24) + s := f.toFloat32Slice() + *s = append(*s, v) + return b[4:], nil +} + +func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + *f.toString() = v + return b[x:], nil +} + +func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + *f.toStringPtr() = &v + return b[x:], nil +} + +func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := string(b[:x]) + if !utf8.ValidString(v) { + return nil, errInvalidUTF8 + } + s := f.toStringSlice() + *s = append(*s, v) + return b[x:], nil +} + +var emptyBuf [0]byte + +func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + // The use of append here is a trick which avoids the zeroing + // that would be required if we used a make/copy pair. + // We append to emptyBuf instead of nil because we want + // a non-nil result even when the length is 0. + v := append(emptyBuf[:], b[:x]...) + *f.toBytes() = v + return b[x:], nil +} + +func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := append(emptyBuf[:], b[:x]...) + s := f.toBytesSlice() + *s = append(*s, v) + return b[x:], nil +} + +func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + // First read the message field to see if something is there. + // The semantics of multiple submessages are weird. Instead of + // the last one winning (as it is for all other fields), multiple + // submessages are merged. + v := f.getPointer() + if v.isNil() { + v = valToPointer(reflect.New(sub.typ)) + f.setPointer(v) + } + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + return b[x:], err + } +} + +func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireBytes { + return b, errInternalBadWireType + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + v := valToPointer(reflect.New(sub.typ)) + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + f.appendPointer(v) + return b[x:], err + } +} + +func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireStartGroup { + return b, errInternalBadWireType + } + x, y := findEndGroup(b) + if x < 0 { + return nil, io.ErrUnexpectedEOF + } + v := f.getPointer() + if v.isNil() { + v = valToPointer(reflect.New(sub.typ)) + f.setPointer(v) + } + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + return b[y:], err + } +} + +func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler { + return func(b []byte, f pointer, w int) ([]byte, error) { + if w != WireStartGroup { + return b, errInternalBadWireType + } + x, y := findEndGroup(b) + if x < 0 { + return nil, io.ErrUnexpectedEOF + } + v := valToPointer(reflect.New(sub.typ)) + err := sub.unmarshal(v, b[:x]) + if err != nil { + if r, ok := err.(*RequiredNotSetError); ok { + r.field = name + "." + r.field + } else { + return nil, err + } + } + f.appendPointer(v) + return b[y:], err + } +} + +func makeUnmarshalMap(f *reflect.StructField) unmarshaler { + t := f.Type + kt := t.Key() + vt := t.Elem() + unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key")) + unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val")) + return func(b []byte, f pointer, w int) ([]byte, error) { + // The map entry is a submessage. Figure out how big it is. + if w != WireBytes { + return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes) + } + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + b = b[n:] + if x > uint64(len(b)) { + return nil, io.ErrUnexpectedEOF + } + r := b[x:] // unused data to return + b = b[:x] // data for map entry + + // Note: we could use #keys * #values ~= 200 functions + // to do map decoding without reflection. Probably not worth it. + // Maps will be somewhat slow. Oh well. + + // Read key and value from data. + k := reflect.New(kt) + v := reflect.New(vt) + for len(b) > 0 { + x, n := decodeVarint(b) + if n == 0 { + return nil, io.ErrUnexpectedEOF + } + wire := int(x) & 7 + b = b[n:] + + var err error + switch x >> 3 { + case 1: + b, err = unmarshalKey(b, valToPointer(k), wire) + case 2: + b, err = unmarshalVal(b, valToPointer(v), wire) + default: + err = errInternalBadWireType // skip unknown tag + } + + if err == nil { + continue + } + if err != errInternalBadWireType { + return nil, err + } + + // Skip past unknown fields. + b, err = skipField(b, wire) + if err != nil { + return nil, err + } + } + + // Get map, allocate if needed. + m := f.asPointerTo(t).Elem() // an addressable map[K]T + if m.IsNil() { + m.Set(reflect.MakeMap(t)) + } + + // Insert into map. + m.SetMapIndex(k.Elem(), v.Elem()) + + return r, nil + } +} + +// makeUnmarshalOneof makes an unmarshaler for oneof fields. +// for: +// message Msg { +// oneof F { +// int64 X = 1; +// float64 Y = 2; +// } +// } +// typ is the type of the concrete entry for a oneof case (e.g. Msg_X). +// ityp is the interface type of the oneof field (e.g. isMsg_F). +// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64). +// Note that this function will be called once for each case in the oneof. +func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler { + sf := typ.Field(0) + field0 := toField(&sf) + return func(b []byte, f pointer, w int) ([]byte, error) { + // Allocate holder for value. + v := reflect.New(typ) + + // Unmarshal data into holder. + // We unmarshal into the first field of the holder object. + var err error + b, err = unmarshal(b, valToPointer(v).offset(field0), w) + if err != nil { + return nil, err + } + + // Write pointer to holder into target field. + f.asPointerTo(ityp).Elem().Set(v) + + return b, nil + } +} + +// Error used by decode internally. +var errInternalBadWireType = errors.New("proto: internal error: bad wiretype") + +// skipField skips past a field of type wire and returns the remaining bytes. +func skipField(b []byte, wire int) ([]byte, error) { + switch wire { + case WireVarint: + _, k := decodeVarint(b) + if k == 0 { + return b, io.ErrUnexpectedEOF + } + b = b[k:] + case WireFixed32: + if len(b) < 4 { + return b, io.ErrUnexpectedEOF + } + b = b[4:] + case WireFixed64: + if len(b) < 8 { + return b, io.ErrUnexpectedEOF + } + b = b[8:] + case WireBytes: + m, k := decodeVarint(b) + if k == 0 || uint64(len(b)-k) < m { + return b, io.ErrUnexpectedEOF + } + b = b[uint64(k)+m:] + case WireStartGroup: + _, i := findEndGroup(b) + if i == -1 { + return b, io.ErrUnexpectedEOF + } + b = b[i:] + default: + return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire) + } + return b, nil +} + +// findEndGroup finds the index of the next EndGroup tag. +// Groups may be nested, so the "next" EndGroup tag is the first +// unpaired EndGroup. +// findEndGroup returns the indexes of the start and end of the EndGroup tag. +// Returns (-1,-1) if it can't find one. +func findEndGroup(b []byte) (int, int) { + depth := 1 + i := 0 + for { + x, n := decodeVarint(b[i:]) + if n == 0 { + return -1, -1 + } + j := i + i += n + switch x & 7 { + case WireVarint: + _, k := decodeVarint(b[i:]) + if k == 0 { + return -1, -1 + } + i += k + case WireFixed32: + if len(b)-4 < i { + return -1, -1 + } + i += 4 + case WireFixed64: + if len(b)-8 < i { + return -1, -1 + } + i += 8 + case WireBytes: + m, k := decodeVarint(b[i:]) + if k == 0 { + return -1, -1 + } + i += k + if uint64(len(b)-i) < m { + return -1, -1 + } + i += int(m) + case WireStartGroup: + depth++ + case WireEndGroup: + depth-- + if depth == 0 { + return j, i + } + default: + return -1, -1 + } + } +} + +// encodeVarint appends a varint-encoded integer to b and returns the result. +func encodeVarint(b []byte, x uint64) []byte { + for x >= 1<<7 { + b = append(b, byte(x&0x7f|0x80)) + x >>= 7 + } + return append(b, byte(x)) +} + +// decodeVarint reads a varint-encoded integer from b. +// Returns the decoded integer and the number of bytes read. +// If there is an error, it returns 0,0. +func decodeVarint(b []byte) (uint64, int) { + var x, y uint64 + if len(b) <= 0 { + goto bad + } + x = uint64(b[0]) + if x < 0x80 { + return x, 1 + } + x -= 0x80 + + if len(b) <= 1 { + goto bad + } + y = uint64(b[1]) + x += y << 7 + if y < 0x80 { + return x, 2 + } + x -= 0x80 << 7 + + if len(b) <= 2 { + goto bad + } + y = uint64(b[2]) + x += y << 14 + if y < 0x80 { + return x, 3 + } + x -= 0x80 << 14 + + if len(b) <= 3 { + goto bad + } + y = uint64(b[3]) + x += y << 21 + if y < 0x80 { + return x, 4 + } + x -= 0x80 << 21 + + if len(b) <= 4 { + goto bad + } + y = uint64(b[4]) + x += y << 28 + if y < 0x80 { + return x, 5 + } + x -= 0x80 << 28 + + if len(b) <= 5 { + goto bad + } + y = uint64(b[5]) + x += y << 35 + if y < 0x80 { + return x, 6 + } + x -= 0x80 << 35 + + if len(b) <= 6 { + goto bad + } + y = uint64(b[6]) + x += y << 42 + if y < 0x80 { + return x, 7 + } + x -= 0x80 << 42 + + if len(b) <= 7 { + goto bad + } + y = uint64(b[7]) + x += y << 49 + if y < 0x80 { + return x, 8 + } + x -= 0x80 << 49 + + if len(b) <= 8 { + goto bad + } + y = uint64(b[8]) + x += y << 56 + if y < 0x80 { + return x, 9 + } + x -= 0x80 << 56 + + if len(b) <= 9 { + goto bad + } + y = uint64(b[9]) + x += y << 63 + if y < 2 { + return x, 10 + } + +bad: + return 0, 0 +} diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go index 965876bf03..2205fdaadf 100644 --- a/vendor/github.com/golang/protobuf/proto/text.go +++ b/vendor/github.com/golang/protobuf/proto/text.go @@ -50,7 +50,6 @@ import ( var ( newline = []byte("\n") spaces = []byte(" ") - gtNewline = []byte(">\n") endBraceNewline = []byte("}\n") backslashN = []byte{'\\', 'n'} backslashR = []byte{'\\', 'r'} @@ -170,11 +169,6 @@ func writeName(w *textWriter, props *Properties) error { return nil } -// raw is the interface satisfied by RawMessage. -type raw interface { - Bytes() []byte -} - func requiresQuotes(u string) bool { // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. for _, ch := range u { @@ -269,6 +263,10 @@ func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { props := sprops.Prop[i] name := st.Field(i).Name + if name == "XXX_NoUnkeyedLiteral" { + continue + } + if strings.HasPrefix(name, "XXX_") { // There are two XXX_ fields: // XXX_unrecognized []byte @@ -436,12 +434,6 @@ func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { return err } } - if b, ok := fv.Interface().(raw); ok { - if err := writeRaw(w, b.Bytes()); err != nil { - return err - } - continue - } // Enums have a String method, so writeAny will work fine. if err := tm.writeAny(w, fv, props); err != nil { @@ -455,7 +447,7 @@ func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { // Extensions (the XXX_extensions field). pv := sv.Addr() - if _, ok := extendable(pv.Interface()); ok { + if _, err := extendable(pv.Interface()); err == nil { if err := tm.writeExtensions(w, pv); err != nil { return err } @@ -464,27 +456,6 @@ func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { return nil } -// writeRaw writes an uninterpreted raw message. -func writeRaw(w *textWriter, b []byte) error { - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if err := writeUnknownStruct(w, b); err != nil { - return err - } - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - return nil -} - // writeAny writes an arbitrary field. func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { v = reflect.Indirect(v) @@ -535,6 +506,19 @@ func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Propert } } w.indent() + if v.CanAddr() { + // Calling v.Interface on a struct causes the reflect package to + // copy the entire struct. This is racy with the new Marshaler + // since we atomically update the XXX_sizecache. + // + // Thus, we retrieve a pointer to the struct if possible to avoid + // a race since v.Interface on the pointer doesn't copy the struct. + // + // If v is not addressable, then we are not worried about a race + // since it implies that the binary Marshaler cannot possibly be + // mutating this value. + v = v.Addr() + } if etm, ok := v.Interface().(encoding.TextMarshaler); ok { text, err := etm.MarshalText() if err != nil { @@ -543,8 +527,13 @@ func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Propert if _, err = w.Write(text); err != nil { return err } - } else if err := tm.writeStruct(w, v); err != nil { - return err + } else { + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + if err := tm.writeStruct(w, v); err != nil { + return err + } } w.unindent() if err := w.WriteByte(ket); err != nil { diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go index 5e14513f28..0685bae36d 100644 --- a/vendor/github.com/golang/protobuf/proto/text_parser.go +++ b/vendor/github.com/golang/protobuf/proto/text_parser.go @@ -206,7 +206,6 @@ func (p *textParser) advance() { var ( errBadUTF8 = errors.New("proto: bad UTF-8") - errBadHex = errors.New("proto: bad hexadecimal") ) func unquoteC(s string, quote rune) (string, error) { @@ -277,60 +276,47 @@ func unescape(s string) (ch string, tail string, err error) { return "?", s, nil // trigraph workaround case '\'', '"', '\\': return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X': + case '0', '1', '2', '3', '4', '5', '6', '7': if len(s) < 2 { return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) } - base := 8 - ss := s[:2] + ss := string(r) + s[:2] s = s[2:] - if r == 'x' || r == 'X' { - base = 16 - } else { - ss = string(r) + ss - } - i, err := strconv.ParseUint(ss, base, 8) + i, err := strconv.ParseUint(ss, 8, 8) if err != nil { - return "", "", err + return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) } return string([]byte{byte(i)}), s, nil - case 'u', 'U': - n := 4 - if r == 'U' { + case 'x', 'X', 'u', 'U': + var n int + switch r { + case 'x', 'X': + n = 2 + case 'u': + n = 4 + case 'U': n = 8 } if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d digits`, r, n) - } - - bs := make([]byte, n/2) - for i := 0; i < n; i += 2 { - a, ok1 := unhex(s[i]) - b, ok2 := unhex(s[i+1]) - if !ok1 || !ok2 { - return "", "", errBadHex - } - bs[i/2] = a<<4 | b + return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) } + ss := s[:n] s = s[n:] - return string(bs), s, nil + i, err := strconv.ParseUint(ss, 16, 64) + if err != nil { + return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) + } + if r == 'x' || r == 'X' { + return string([]byte{byte(i)}), s, nil + } + if i > utf8.MaxRune { + return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) + } + return string(i), s, nil } return "", "", fmt.Errorf(`unknown escape \%c`, r) } -// Adapted from src/pkg/strconv/quote.go. -func unhex(b byte) (v byte, ok bool) { - switch { - case '0' <= b && b <= '9': - return b - '0', true - case 'a' <= b && b <= 'f': - return b - 'a' + 10, true - case 'A' <= b && b <= 'F': - return b - 'A' + 10, true - } - return 0, false -} - // Back off the parser by one token. Can only be done between calls to next(). // It makes the next advance() a no-op. func (p *textParser) back() { p.backed = true } @@ -728,6 +714,9 @@ func (p *textParser) consumeExtName() (string, error) { if tok.err != nil { return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) } + if p.done && tok.value != "]" { + return "", p.errorf("unclosed type_url or extension name") + } } return strings.Join(parts, ""), nil } @@ -865,7 +854,7 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error { return p.readStruct(fv, terminator) case reflect.Uint32: if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(x) + fv.SetUint(uint64(x)) return nil } case reflect.Uint64: @@ -883,13 +872,9 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error { // UnmarshalText returns *RequiredNotSetError. func UnmarshalText(s string, pb Message) error { if um, ok := pb.(encoding.TextUnmarshaler); ok { - err := um.UnmarshalText([]byte(s)) - return err + return um.UnmarshalText([]byte(s)) } pb.Reset() v := reflect.ValueOf(pb) - if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil { - return pe - } - return nil + return newTextParser(s).readStruct(v.Elem(), "") } diff --git a/vendor/github.com/golang/protobuf/proto/text_parser_test.go b/vendor/github.com/golang/protobuf/proto/text_parser_test.go deleted file mode 100644 index 8f7cb4d274..0000000000 --- a/vendor/github.com/golang/protobuf/proto/text_parser_test.go +++ /dev/null @@ -1,673 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "math" - "reflect" - "testing" - - . "github.com/golang/protobuf/proto" - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - . "github.com/golang/protobuf/proto/testdata" -) - -type UnmarshalTextTest struct { - in string - err string // if "", no error expected - out *MyMessage -} - -func buildExtStructTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_More, &Ext{ - Data: String("Hello, world!"), - }) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtDataTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - SetExtension(msg, E_Ext_Text, String("Hello, world!")) - SetExtension(msg, E_Ext_Number, Int32(1729)) - return UnmarshalTextTest{in: text, out: msg} -} - -func buildExtRepStringTest(text string) UnmarshalTextTest { - msg := &MyMessage{ - Count: Int32(42), - } - if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { - panic(err) - } - return UnmarshalTextTest{in: text, out: msg} -} - -var unMarshalTextTests = []UnmarshalTextTest{ - // Basic - { - in: " count:42\n name:\"Dave\" ", - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - }, - }, - - // Empty quoted string - { - in: `count:42 name:""`, - out: &MyMessage{ - Count: Int32(42), - Name: String(""), - }, - }, - - // Quoted string concatenation with double quotes - { - in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenation with single quotes - { - in: "count:42 name: 'My name is '\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string concatenations with mixed quotes - { - in: "count:42 name: 'My name is '\n\"elsewhere\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - { - in: "count:42 name: \"My name is \"\n'elsewhere'", - out: &MyMessage{ - Count: Int32(42), - Name: String("My name is elsewhere"), - }, - }, - - // Quoted string with escaped apostrophe - { - in: `count:42 name: "HOLIDAY - New Year\'s Day"`, - out: &MyMessage{ - Count: Int32(42), - Name: String("HOLIDAY - New Year's Day"), - }, - }, - - // Quoted string with single quote - { - in: `count:42 name: 'Roger "The Ramster" Ramjet'`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`Roger "The Ramster" Ramjet`), - }, - }, - - // Quoted string with all the accepted special characters from the C++ test - { - in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", - out: &MyMessage{ - Count: Int32(42), - Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), - }, - }, - - // Quoted string with quoted backslash - { - in: `count:42 name: "\\'xyz"`, - out: &MyMessage{ - Count: Int32(42), - Name: String(`\'xyz`), - }, - }, - - // Quoted string with UTF-8 bytes. - { - in: "count:42 name: '\303\277\302\201\xAB'", - out: &MyMessage{ - Count: Int32(42), - Name: String("\303\277\302\201\xAB"), - }, - }, - - // Bad quoted string - { - in: `inner: < host: "\0" >` + "\n", - err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, - }, - - // Number too large for int64 - { - in: "count: 1 others { key: 123456789012345678901 }", - err: "line 1.23: invalid int64: 123456789012345678901", - }, - - // Number too large for int32 - { - in: "count: 1234567890123", - err: "line 1.7: invalid int32: 1234567890123", - }, - - // Number in hexadecimal - { - in: "count: 0x2beef", - out: &MyMessage{ - Count: Int32(0x2beef), - }, - }, - - // Number in octal - { - in: "count: 024601", - out: &MyMessage{ - Count: Int32(024601), - }, - }, - - // Floating point number with "f" suffix - { - in: "count: 4 others:< weight: 17.0f >", - out: &MyMessage{ - Count: Int32(4), - Others: []*OtherMessage{ - { - Weight: Float32(17), - }, - }, - }, - }, - - // Floating point positive infinity - { - in: "count: 4 bigfloat: inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(1)), - }, - }, - - // Floating point negative infinity - { - in: "count: 4 bigfloat: -inf", - out: &MyMessage{ - Count: Int32(4), - Bigfloat: Float64(math.Inf(-1)), - }, - }, - - // Number too large for float32 - { - in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", - err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", - }, - - // Number posing as a quoted string - { - in: `inner: < host: 12 >` + "\n", - err: `line 1.15: invalid string: 12`, - }, - - // Quoted string posing as int32 - { - in: `count: "12"`, - err: `line 1.7: invalid int32: "12"`, - }, - - // Quoted string posing a float32 - { - in: `others:< weight: "17.4" >`, - err: `line 1.17: invalid float32: "17.4"`, - }, - - // Enum - { - in: `count:42 bikeshed: BLUE`, - out: &MyMessage{ - Count: Int32(42), - Bikeshed: MyMessage_BLUE.Enum(), - }, - }, - - // Repeated field - { - in: `count:42 pet: "horsey" pet:"bunny"`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated field with list notation - { - in: `count:42 pet: ["horsey", "bunny"]`, - out: &MyMessage{ - Count: Int32(42), - Pet: []string{"horsey", "bunny"}, - }, - }, - - // Repeated message with/without colon and <>/{} - { - in: `count:42 others:{} others{} others:<> others:{}`, - out: &MyMessage{ - Count: Int32(42), - Others: []*OtherMessage{ - {}, - {}, - {}, - {}, - }, - }, - }, - - // Missing colon for inner message - { - in: `count:42 inner < host: "cauchy.syd" >`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("cauchy.syd"), - }, - }, - }, - - // Missing colon for string field - { - in: `name "Dave"`, - err: `line 1.5: expected ':', found "\"Dave\""`, - }, - - // Missing colon for int32 field - { - in: `count 42`, - err: `line 1.6: expected ':', found "42"`, - }, - - // Missing required field - { - in: `name: "Pawel"`, - err: `proto: required field "testdata.MyMessage.count" not set`, - out: &MyMessage{ - Name: String("Pawel"), - }, - }, - - // Missing required field in a required submessage - { - in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`, - err: `proto: required field "testdata.InnerMessage.host" not set`, - out: &MyMessage{ - Count: Int32(42), - WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}}, - }, - }, - - // Repeated non-repeated field - { - in: `name: "Rob" name: "Russ"`, - err: `line 1.12: non-repeated field "name" was repeated`, - }, - - // Group - { - in: `count: 17 SomeGroup { group_field: 12 }`, - out: &MyMessage{ - Count: Int32(17), - Somegroup: &MyMessage_SomeGroup{ - GroupField: Int32(12), - }, - }, - }, - - // Semicolon between fields - { - in: `count:3;name:"Calvin"`, - out: &MyMessage{ - Count: Int32(3), - Name: String("Calvin"), - }, - }, - // Comma between fields - { - in: `count:4,name:"Ezekiel"`, - out: &MyMessage{ - Count: Int32(4), - Name: String("Ezekiel"), - }, - }, - - // Boolean false - { - in: `count:42 inner { host: "example.com" connected: false }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean true - { - in: `count:42 inner { host: "example.com" connected: true }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean 0 - { - in: `count:42 inner { host: "example.com" connected: 0 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean 1 - { - in: `count:42 inner { host: "example.com" connected: 1 }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean f - { - in: `count:42 inner { host: "example.com" connected: f }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean t - { - in: `count:42 inner { host: "example.com" connected: t }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - // Boolean False - { - in: `count:42 inner { host: "example.com" connected: False }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(false), - }, - }, - }, - // Boolean True - { - in: `count:42 inner { host: "example.com" connected: True }`, - out: &MyMessage{ - Count: Int32(42), - Inner: &InnerMessage{ - Host: String("example.com"), - Connected: Bool(true), - }, - }, - }, - - // Extension - buildExtStructTest(`count: 42 [testdata.Ext.more]:`), - buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), - buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), - buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), - - // Big all-in-one - { - in: "count:42 # Meaning\n" + - `name:"Dave" ` + - `quote:"\"I didn't want to go.\"" ` + - `pet:"bunny" ` + - `pet:"kitty" ` + - `pet:"horsey" ` + - `inner:<` + - ` host:"footrest.syd" ` + - ` port:7001 ` + - ` connected:true ` + - `> ` + - `others:<` + - ` key:3735928559 ` + - ` value:"\x01A\a\f" ` + - `> ` + - `others:<` + - " weight:58.9 # Atomic weight of Co\n" + - ` inner:<` + - ` host:"lesha.mtv" ` + - ` port:8002 ` + - ` >` + - `>`, - out: &MyMessage{ - Count: Int32(42), - Name: String("Dave"), - Quote: String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &InnerMessage{ - Host: String("footrest.syd"), - Port: Int32(7001), - Connected: Bool(true), - }, - Others: []*OtherMessage{ - { - Key: Int64(3735928559), - Value: []byte{0x1, 'A', '\a', '\f'}, - }, - { - Weight: Float32(58.9), - Inner: &InnerMessage{ - Host: String("lesha.mtv"), - Port: Int32(8002), - }, - }, - }, - }, - }, -} - -func TestUnmarshalText(t *testing.T) { - for i, test := range unMarshalTextTests { - pb := new(MyMessage) - err := UnmarshalText(test.in, pb) - if test.err == "" { - // We don't expect failure. - if err != nil { - t.Errorf("Test %d: Unexpected error: %v", i, err) - } else if !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } else { - // We do expect failure. - if err == nil { - t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) - } else if err.Error() != test.err { - t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", - i, err.Error(), test.err) - } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { - t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", - i, pb, test.out) - } - } - } -} - -func TestUnmarshalTextCustomMessage(t *testing.T) { - msg := &textMessage{} - if err := UnmarshalText("custom", msg); err != nil { - t.Errorf("Unexpected error from custom unmarshal: %v", err) - } - if UnmarshalText("not custom", msg) == nil { - t.Errorf("Didn't get expected error from custom unmarshal") - } -} - -// Regression test; this caused a panic. -func TestRepeatedEnum(t *testing.T) { - pb := new(RepeatedEnum) - if err := UnmarshalText("color: RED", pb); err != nil { - t.Fatal(err) - } - exp := &RepeatedEnum{ - Color: []RepeatedEnum_Color{RepeatedEnum_RED}, - } - if !Equal(pb, exp) { - t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) - } -} - -func TestProto3TextParsing(t *testing.T) { - m := new(proto3pb.Message) - const in = `name: "Wallace" true_scotsman: true` - want := &proto3pb.Message{ - Name: "Wallace", - TrueScotsman: true, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestMapParsing(t *testing.T) { - m := new(MessageWithMap) - const in = `name_mapping: name_mapping:` + - `msg_mapping:,>` + // separating commas are okay - `msg_mapping>` + // no colon after "value" - `msg_mapping:>` + // omitted key - `msg_mapping:` + // omitted value - `byte_mapping:` + - `byte_mapping:<>` // omitted key and value - want := &MessageWithMap{ - NameMapping: map[int32]string{ - 1: "Beatles", - 1234: "Feist", - }, - MsgMapping: map[int64]*FloatingPoint{ - -4: {F: Float64(2.0)}, - -2: {F: Float64(4.0)}, - 0: {F: Float64(5.0)}, - 1: nil, - }, - ByteMapping: map[bool][]byte{ - false: nil, - true: []byte("so be it"), - }, - } - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } -} - -func TestOneofParsing(t *testing.T) { - const in = `name:"Shrek"` - m := new(Communique) - want := &Communique{Union: &Communique_Name{"Shrek"}} - if err := UnmarshalText(in, m); err != nil { - t.Fatal(err) - } - if !Equal(m, want) { - t.Errorf("\n got %v\nwant %v", m, want) - } - - const inOverwrite = `name:"Shrek" number:42` - m = new(Communique) - testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'" - if err := UnmarshalText(inOverwrite, m); err == nil { - t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr) - } else if err.Error() != testErr { - t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v", - err.Error(), testErr) - } - -} - -var benchInput string - -func init() { - benchInput = "count: 4\n" - for i := 0; i < 1000; i++ { - benchInput += "pet: \"fido\"\n" - } - - // Check it is valid input. - pb := new(MyMessage) - err := UnmarshalText(benchInput, pb) - if err != nil { - panic("Bad benchmark input: " + err.Error()) - } -} - -func BenchmarkUnmarshalText(b *testing.B) { - pb := new(MyMessage) - for i := 0; i < b.N; i++ { - UnmarshalText(benchInput, pb) - } - b.SetBytes(int64(len(benchInput))) -} diff --git a/vendor/github.com/golang/protobuf/proto/text_test.go b/vendor/github.com/golang/protobuf/proto/text_test.go deleted file mode 100644 index 3eabacac8f..0000000000 --- a/vendor/github.com/golang/protobuf/proto/text_test.go +++ /dev/null @@ -1,474 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package proto_test - -import ( - "bytes" - "errors" - "io/ioutil" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - proto3pb "github.com/golang/protobuf/proto/proto3_proto" - pb "github.com/golang/protobuf/proto/testdata" -) - -// textMessage implements the methods that allow it to marshal and unmarshal -// itself as text. -type textMessage struct { -} - -func (*textMessage) MarshalText() ([]byte, error) { - return []byte("custom"), nil -} - -func (*textMessage) UnmarshalText(bytes []byte) error { - if string(bytes) != "custom" { - return errors.New("expected 'custom'") - } - return nil -} - -func (*textMessage) Reset() {} -func (*textMessage) String() string { return "" } -func (*textMessage) ProtoMessage() {} - -func newTestMessage() *pb.MyMessage { - msg := &pb.MyMessage{ - Count: proto.Int32(42), - Name: proto.String("Dave"), - Quote: proto.String(`"I didn't want to go."`), - Pet: []string{"bunny", "kitty", "horsey"}, - Inner: &pb.InnerMessage{ - Host: proto.String("footrest.syd"), - Port: proto.Int32(7001), - Connected: proto.Bool(true), - }, - Others: []*pb.OtherMessage{ - { - Key: proto.Int64(0xdeadbeef), - Value: []byte{1, 65, 7, 12}, - }, - { - Weight: proto.Float32(6.022), - Inner: &pb.InnerMessage{ - Host: proto.String("lesha.mtv"), - Port: proto.Int32(8002), - }, - }, - }, - Bikeshed: pb.MyMessage_BLUE.Enum(), - Somegroup: &pb.MyMessage_SomeGroup{ - GroupField: proto.Int32(8), - }, - // One normally wouldn't do this. - // This is an undeclared tag 13, as a varint (wire type 0) with value 4. - XXX_unrecognized: []byte{13<<3 | 0, 4}, - } - ext := &pb.Ext{ - Data: proto.String("Big gobs for big rats"), - } - if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { - panic(err) - } - greetings := []string{"adg", "easy", "cow"} - if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { - panic(err) - } - - // Add an unknown extension. We marshal a pb.Ext, and fake the ID. - b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) - if err != nil { - panic(err) - } - b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) - proto.SetRawExtension(msg, 201, b) - - // Extensions can be plain fields, too, so let's test that. - b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) - proto.SetRawExtension(msg, 202, b) - - return msg -} - -const text = `count: 42 -name: "Dave" -quote: "\"I didn't want to go.\"" -pet: "bunny" -pet: "kitty" -pet: "horsey" -inner: < - host: "footrest.syd" - port: 7001 - connected: true -> -others: < - key: 3735928559 - value: "\001A\007\014" -> -others: < - weight: 6.022 - inner: < - host: "lesha.mtv" - port: 8002 - > -> -bikeshed: BLUE -SomeGroup { - group_field: 8 -} -/* 2 unknown bytes */ -13: 4 -[testdata.Ext.more]: < - data: "Big gobs for big rats" -> -[testdata.greeting]: "adg" -[testdata.greeting]: "easy" -[testdata.greeting]: "cow" -/* 13 unknown bytes */ -201: "\t3G skiing" -/* 3 unknown bytes */ -202: 19 -` - -func TestMarshalText(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, newTestMessage()); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != text { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) - } -} - -func TestMarshalTextCustomMessage(t *testing.T) { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, &textMessage{}); err != nil { - t.Fatalf("proto.MarshalText: %v", err) - } - s := buf.String() - if s != "custom" { - t.Errorf("Got %q, expected %q", s, "custom") - } -} -func TestMarshalTextNil(t *testing.T) { - want := "" - tests := []proto.Message{nil, (*pb.MyMessage)(nil)} - for i, test := range tests { - buf := new(bytes.Buffer) - if err := proto.MarshalText(buf, test); err != nil { - t.Fatal(err) - } - if got := buf.String(); got != want { - t.Errorf("%d: got %q want %q", i, got, want) - } - } -} - -func TestMarshalTextUnknownEnum(t *testing.T) { - // The Color enum only specifies values 0-2. - m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} - got := m.String() - const want = `bikeshed:3 ` - if got != want { - t.Errorf("\n got %q\nwant %q", got, want) - } -} - -func TestTextOneof(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&pb.Communique{}, ``}, - // scalar field - {&pb.Communique{Union: &pb.Communique_Number{4}}, `number:4`}, - // message field - {&pb.Communique{Union: &pb.Communique_Msg{ - &pb.Strings{StringField: proto.String("why hello!")}, - }}, `msg:`}, - // bad oneof (should not panic) - {&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`}, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} - -func BenchmarkMarshalTextBuffered(b *testing.B) { - buf := new(bytes.Buffer) - m := newTestMessage() - for i := 0; i < b.N; i++ { - buf.Reset() - proto.MarshalText(buf, m) - } -} - -func BenchmarkMarshalTextUnbuffered(b *testing.B) { - w := ioutil.Discard - m := newTestMessage() - for i := 0; i < b.N; i++ { - proto.MarshalText(w, m) - } -} - -func compact(src string) string { - // s/[ \n]+/ /g; s/ $//; - dst := make([]byte, len(src)) - space, comment := false, false - j := 0 - for i := 0; i < len(src); i++ { - if strings.HasPrefix(src[i:], "/*") { - comment = true - i++ - continue - } - if comment && strings.HasPrefix(src[i:], "*/") { - comment = false - i++ - continue - } - if comment { - continue - } - c := src[i] - if c == ' ' || c == '\n' { - space = true - continue - } - if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { - space = false - } - if c == '{' { - space = false - } - if space { - dst[j] = ' ' - j++ - space = false - } - dst[j] = c - j++ - } - if space { - dst[j] = ' ' - j++ - } - return string(dst[0:j]) -} - -var compactText = compact(text) - -func TestCompactText(t *testing.T) { - s := proto.CompactTextString(newTestMessage()) - if s != compactText { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) - } -} - -func TestStringEscaping(t *testing.T) { - testCases := []struct { - in *pb.Strings - out string - }{ - { - // Test data from C++ test (TextFormatTest.StringEscape). - // Single divergence: we don't escape apostrophes. - &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, - "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", - }, - { - // Test data from the same C++ test. - &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, - "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", - }, - { - // Some UTF-8. - &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, - `string_field: "\000\001\377\201"` + "\n", - }, - } - - for i, tc := range testCases { - var buf bytes.Buffer - if err := proto.MarshalText(&buf, tc.in); err != nil { - t.Errorf("proto.MarsalText: %v", err) - continue - } - s := buf.String() - if s != tc.out { - t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) - continue - } - - // Check round-trip. - pb := new(pb.Strings) - if err := proto.UnmarshalText(s, pb); err != nil { - t.Errorf("#%d: UnmarshalText: %v", i, err) - continue - } - if !proto.Equal(pb, tc.in) { - t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) - } - } -} - -// A limitedWriter accepts some output before it fails. -// This is a proxy for something like a nearly-full or imminently-failing disk, -// or a network connection that is about to die. -type limitedWriter struct { - b bytes.Buffer - limit int -} - -var outOfSpace = errors.New("proto: insufficient space") - -func (w *limitedWriter) Write(p []byte) (n int, err error) { - var avail = w.limit - w.b.Len() - if avail <= 0 { - return 0, outOfSpace - } - if len(p) <= avail { - return w.b.Write(p) - } - n, _ = w.b.Write(p[:avail]) - return n, outOfSpace -} - -func TestMarshalTextFailing(t *testing.T) { - // Try lots of different sizes to exercise more error code-paths. - for lim := 0; lim < len(text); lim++ { - buf := new(limitedWriter) - buf.limit = lim - err := proto.MarshalText(buf, newTestMessage()) - // We expect a certain error, but also some partial results in the buffer. - if err != outOfSpace { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) - } - s := buf.b.String() - x := text[:buf.limit] - if s != x { - t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) - } - } -} - -func TestFloats(t *testing.T) { - tests := []struct { - f float64 - want string - }{ - {0, "0"}, - {4.7, "4.7"}, - {math.Inf(1), "inf"}, - {math.Inf(-1), "-inf"}, - {math.NaN(), "nan"}, - } - for _, test := range tests { - msg := &pb.FloatingPoint{F: &test.f} - got := strings.TrimSpace(msg.String()) - want := `f:` + test.want - if got != want { - t.Errorf("f=%f: got %q, want %q", test.f, got, want) - } - } -} - -func TestRepeatedNilText(t *testing.T) { - m := &pb.MessageList{ - Message: []*pb.MessageList_Message{ - nil, - &pb.MessageList_Message{ - Name: proto.String("Horse"), - }, - nil, - }, - } - want := `Message -Message { - name: "Horse" -} -Message -` - if s := proto.MarshalTextString(m); s != want { - t.Errorf(" got: %s\nwant: %s", s, want) - } -} - -func TestProto3Text(t *testing.T) { - tests := []struct { - m proto.Message - want string - }{ - // zero message - {&proto3pb.Message{}, ``}, - // zero message except for an empty byte slice - {&proto3pb.Message{Data: []byte{}}, ``}, - // trivial case - {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, - // empty map - {&pb.MessageWithMap{}, ``}, - // non-empty map; map format is the same as a repeated struct, - // and they are sorted by key (numerically for numeric keys). - { - &pb.MessageWithMap{NameMapping: map[int32]string{ - -1: "Negatory", - 7: "Lucky", - 1234: "Feist", - 6345789: "Otis", - }}, - `name_mapping: ` + - `name_mapping: ` + - `name_mapping: ` + - `name_mapping:`, - }, - // map with nil value; not well-defined, but we shouldn't crash - { - &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, - `msg_mapping:`, - }, - } - for _, test := range tests { - got := strings.TrimSpace(test.m.String()) - if got != test.want { - t.Errorf("\n got %s\nwant %s", got, test.want) - } - } -} diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go index f34601723d..f67edc7dc2 100644 --- a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go +++ b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go @@ -1,16 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/any.proto -/* -Package any is a generated protocol buffer package. - -It is generated from these files: - google/protobuf/any.proto - -It has these top-level messages: - Any -*/ -package any +package any // import "github.com/golang/protobuf/ptypes/any" import proto "github.com/golang/protobuf/proto" import fmt "fmt" @@ -132,14 +123,36 @@ type Any struct { // TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl" json:"type_url,omitempty"` // Must be a valid serialized protocol buffer of the above specified type. - Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Any) Reset() { *m = Any{} } +func (m *Any) String() string { return proto.CompactTextString(m) } +func (*Any) ProtoMessage() {} +func (*Any) Descriptor() ([]byte, []int) { + return fileDescriptor_any_744b9ca530f228db, []int{0} +} +func (*Any) XXX_WellKnownType() string { return "Any" } +func (m *Any) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Any.Unmarshal(m, b) +} +func (m *Any) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Any.Marshal(b, m, deterministic) +} +func (dst *Any) XXX_Merge(src proto.Message) { + xxx_messageInfo_Any.Merge(dst, src) +} +func (m *Any) XXX_Size() int { + return xxx_messageInfo_Any.Size(m) +} +func (m *Any) XXX_DiscardUnknown() { + xxx_messageInfo_Any.DiscardUnknown(m) } -func (m *Any) Reset() { *m = Any{} } -func (m *Any) String() string { return proto.CompactTextString(m) } -func (*Any) ProtoMessage() {} -func (*Any) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } -func (*Any) XXX_WellKnownType() string { return "Any" } +var xxx_messageInfo_Any proto.InternalMessageInfo func (m *Any) GetTypeUrl() string { if m != nil { @@ -159,9 +172,9 @@ func init() { proto.RegisterType((*Any)(nil), "google.protobuf.Any") } -func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor0) } +func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor_any_744b9ca530f228db) } -var fileDescriptor0 = []byte{ +var fileDescriptor_any_744b9ca530f228db = []byte{ // 185 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4, diff --git a/vendor/github.com/golang/protobuf/ptypes/any_test.go b/vendor/github.com/golang/protobuf/ptypes/any_test.go deleted file mode 100644 index ed675b489c..0000000000 --- a/vendor/github.com/golang/protobuf/ptypes/any_test.go +++ /dev/null @@ -1,113 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package ptypes - -import ( - "testing" - - "github.com/golang/protobuf/proto" - pb "github.com/golang/protobuf/protoc-gen-go/descriptor" - "github.com/golang/protobuf/ptypes/any" -) - -func TestMarshalUnmarshal(t *testing.T) { - orig := &any.Any{Value: []byte("test")} - - packed, err := MarshalAny(orig) - if err != nil { - t.Errorf("MarshalAny(%+v): got: _, %v exp: _, nil", orig, err) - } - - unpacked := &any.Any{} - err = UnmarshalAny(packed, unpacked) - if err != nil || !proto.Equal(unpacked, orig) { - t.Errorf("got: %v, %+v; want nil, %+v", err, unpacked, orig) - } -} - -func TestIs(t *testing.T) { - a, err := MarshalAny(&pb.FileDescriptorProto{}) - if err != nil { - t.Fatal(err) - } - if Is(a, &pb.DescriptorProto{}) { - t.Error("FileDescriptorProto is not a DescriptorProto, but Is says it is") - } - if !Is(a, &pb.FileDescriptorProto{}) { - t.Error("FileDescriptorProto is indeed a FileDescriptorProto, but Is says it is not") - } -} - -func TestIsDifferentUrlPrefixes(t *testing.T) { - m := &pb.FileDescriptorProto{} - a := &any.Any{TypeUrl: "foo/bar/" + proto.MessageName(m)} - if !Is(a, m) { - t.Errorf("message with type url %q didn't satisfy Is for type %q", a.TypeUrl, proto.MessageName(m)) - } -} - -func TestUnmarshalDynamic(t *testing.T) { - want := &pb.FileDescriptorProto{Name: proto.String("foo")} - a, err := MarshalAny(want) - if err != nil { - t.Fatal(err) - } - var got DynamicAny - if err := UnmarshalAny(a, &got); err != nil { - t.Fatal(err) - } - if !proto.Equal(got.Message, want) { - t.Errorf("invalid result from UnmarshalAny, got %q want %q", got.Message, want) - } -} - -func TestEmpty(t *testing.T) { - want := &pb.FileDescriptorProto{} - a, err := MarshalAny(want) - if err != nil { - t.Fatal(err) - } - got, err := Empty(a) - if err != nil { - t.Fatal(err) - } - if !proto.Equal(got, want) { - t.Errorf("unequal empty message, got %q, want %q", got, want) - } - - // that's a valid type_url for a message which shouldn't be linked into this - // test binary. We want an error. - a.TypeUrl = "type.googleapis.com/google.protobuf.FieldMask" - if _, err := Empty(a); err == nil { - t.Errorf("got no error for an attempt to create a message of type %q, which shouldn't be linked in", a.TypeUrl) - } -} diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go index b2410a098e..4d75473b8b 100644 --- a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go +++ b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go @@ -1,16 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/duration.proto -/* -Package duration is a generated protocol buffer package. - -It is generated from these files: - google/protobuf/duration.proto - -It has these top-level messages: - Duration -*/ -package duration +package duration // import "github.com/golang/protobuf/ptypes/duration" import proto "github.com/golang/protobuf/proto" import fmt "fmt" @@ -98,14 +89,36 @@ type Duration struct { // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` + Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *Duration) Reset() { *m = Duration{} } -func (m *Duration) String() string { return proto.CompactTextString(m) } -func (*Duration) ProtoMessage() {} -func (*Duration) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } -func (*Duration) XXX_WellKnownType() string { return "Duration" } +func (m *Duration) Reset() { *m = Duration{} } +func (m *Duration) String() string { return proto.CompactTextString(m) } +func (*Duration) ProtoMessage() {} +func (*Duration) Descriptor() ([]byte, []int) { + return fileDescriptor_duration_e7d612259e3f0613, []int{0} +} +func (*Duration) XXX_WellKnownType() string { return "Duration" } +func (m *Duration) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Duration.Unmarshal(m, b) +} +func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Duration.Marshal(b, m, deterministic) +} +func (dst *Duration) XXX_Merge(src proto.Message) { + xxx_messageInfo_Duration.Merge(dst, src) +} +func (m *Duration) XXX_Size() int { + return xxx_messageInfo_Duration.Size(m) +} +func (m *Duration) XXX_DiscardUnknown() { + xxx_messageInfo_Duration.DiscardUnknown(m) +} + +var xxx_messageInfo_Duration proto.InternalMessageInfo func (m *Duration) GetSeconds() int64 { if m != nil { @@ -125,9 +138,11 @@ func init() { proto.RegisterType((*Duration)(nil), "google.protobuf.Duration") } -func init() { proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor0) } +func init() { + proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor_duration_e7d612259e3f0613) +} -var fileDescriptor0 = []byte{ +var fileDescriptor_duration_e7d612259e3f0613 = []byte{ // 190 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a, diff --git a/vendor/github.com/golang/protobuf/ptypes/duration_test.go b/vendor/github.com/golang/protobuf/ptypes/duration_test.go deleted file mode 100644 index e00491a34f..0000000000 --- a/vendor/github.com/golang/protobuf/ptypes/duration_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package ptypes - -import ( - "math" - "testing" - "time" - - "github.com/golang/protobuf/proto" - durpb "github.com/golang/protobuf/ptypes/duration" -) - -const ( - minGoSeconds = math.MinInt64 / int64(1e9) - maxGoSeconds = math.MaxInt64 / int64(1e9) -) - -var durationTests = []struct { - proto *durpb.Duration - isValid bool - inRange bool - dur time.Duration -}{ - // The zero duration. - {&durpb.Duration{Seconds: 0, Nanos: 0}, true, true, 0}, - // Some ordinary non-zero durations. - {&durpb.Duration{Seconds: 100, Nanos: 0}, true, true, 100 * time.Second}, - {&durpb.Duration{Seconds: -100, Nanos: 0}, true, true, -100 * time.Second}, - {&durpb.Duration{Seconds: 100, Nanos: 987}, true, true, 100*time.Second + 987}, - {&durpb.Duration{Seconds: -100, Nanos: -987}, true, true, -(100*time.Second + 987)}, - // The largest duration representable in Go. - {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, true, math.MaxInt64}, - // The smallest duration representable in Go. - {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, true, math.MinInt64}, - {nil, false, false, 0}, - {&durpb.Duration{Seconds: -100, Nanos: 987}, false, false, 0}, - {&durpb.Duration{Seconds: 100, Nanos: -987}, false, false, 0}, - {&durpb.Duration{Seconds: math.MinInt64, Nanos: 0}, false, false, 0}, - {&durpb.Duration{Seconds: math.MaxInt64, Nanos: 0}, false, false, 0}, - // The largest valid duration. - {&durpb.Duration{Seconds: maxSeconds, Nanos: 1e9 - 1}, true, false, 0}, - // The smallest valid duration. - {&durpb.Duration{Seconds: minSeconds, Nanos: -(1e9 - 1)}, true, false, 0}, - // The smallest invalid duration above the valid range. - {&durpb.Duration{Seconds: maxSeconds + 1, Nanos: 0}, false, false, 0}, - // The largest invalid duration below the valid range. - {&durpb.Duration{Seconds: minSeconds - 1, Nanos: -(1e9 - 1)}, false, false, 0}, - // One nanosecond past the largest duration representable in Go. - {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64-1e9*maxGoSeconds) + 1}, true, false, 0}, - // One nanosecond past the smallest duration representable in Go. - {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64-1e9*minGoSeconds) - 1}, true, false, 0}, - // One second past the largest duration representable in Go. - {&durpb.Duration{Seconds: maxGoSeconds + 1, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, false, 0}, - // One second past the smallest duration representable in Go. - {&durpb.Duration{Seconds: minGoSeconds - 1, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, false, 0}, -} - -func TestValidateDuration(t *testing.T) { - for _, test := range durationTests { - err := validateDuration(test.proto) - gotValid := (err == nil) - if gotValid != test.isValid { - t.Errorf("validateDuration(%v) = %t, want %t", test.proto, gotValid, test.isValid) - } - } -} - -func TestDuration(t *testing.T) { - for _, test := range durationTests { - got, err := Duration(test.proto) - gotOK := (err == nil) - wantOK := test.isValid && test.inRange - if gotOK != wantOK { - t.Errorf("Duration(%v) ok = %t, want %t", test.proto, gotOK, wantOK) - } - if err == nil && got != test.dur { - t.Errorf("Duration(%v) = %v, want %v", test.proto, got, test.dur) - } - } -} - -func TestDurationProto(t *testing.T) { - for _, test := range durationTests { - if test.isValid && test.inRange { - got := DurationProto(test.dur) - if !proto.Equal(got, test.proto) { - t.Errorf("DurationProto(%v) = %v, want %v", test.dur, got, test.proto) - } - } - } -} diff --git a/vendor/github.com/golang/protobuf/ptypes/regen.sh b/vendor/github.com/golang/protobuf/ptypes/regen.sh deleted file mode 100755 index b50a9414ac..0000000000 --- a/vendor/github.com/golang/protobuf/ptypes/regen.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/bin/bash -e -# -# This script fetches and rebuilds the "well-known types" protocol buffers. -# To run this you will need protoc and goprotobuf installed; -# see https://github.com/golang/protobuf for instructions. -# You also need Go and Git installed. - -PKG=github.com/golang/protobuf/ptypes -UPSTREAM=https://github.com/google/protobuf -UPSTREAM_SUBDIR=src/google/protobuf -PROTO_FILES=(any duration empty struct timestamp wrappers) - -function die() { - echo 1>&2 $* - exit 1 -} - -# Sanity check that the right tools are accessible. -for tool in go git protoc protoc-gen-go; do - q=$(which $tool) || die "didn't find $tool" - echo 1>&2 "$tool: $q" -done - -tmpdir=$(mktemp -d -t regen-wkt.XXXXXX) -trap 'rm -rf $tmpdir' EXIT - -echo -n 1>&2 "finding package dir... " -pkgdir=$(go list -f '{{.Dir}}' $PKG) -echo 1>&2 $pkgdir -base=$(echo $pkgdir | sed "s,/$PKG\$,,") -echo 1>&2 "base: $base" -cd "$base" - -echo 1>&2 "fetching latest protos... " -git clone -q $UPSTREAM $tmpdir - -for file in ${PROTO_FILES[@]}; do - echo 1>&2 "* $file" - protoc --go_out=. -I$tmpdir/src $tmpdir/src/google/protobuf/$file.proto || die - cp $tmpdir/src/google/protobuf/$file.proto $PKG/$file -done - -echo 1>&2 "All OK" diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go index e23e4a25da..e9c2222821 100644 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go +++ b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go @@ -1,16 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/timestamp.proto -/* -Package timestamp is a generated protocol buffer package. - -It is generated from these files: - google/protobuf/timestamp.proto - -It has these top-level messages: - Timestamp -*/ -package timestamp +package timestamp // import "github.com/golang/protobuf/ptypes/timestamp" import proto "github.com/golang/protobuf/proto" import fmt "fmt" @@ -101,7 +92,7 @@ const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package // to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) // with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one // can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()) +// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--) // to obtain a formatter capable of generating timestamps in this format. // // @@ -114,14 +105,36 @@ type Timestamp struct { // 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. - Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` + Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *Timestamp) Reset() { *m = Timestamp{} } -func (m *Timestamp) String() string { return proto.CompactTextString(m) } -func (*Timestamp) ProtoMessage() {} -func (*Timestamp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } -func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" } +func (m *Timestamp) Reset() { *m = Timestamp{} } +func (m *Timestamp) String() string { return proto.CompactTextString(m) } +func (*Timestamp) ProtoMessage() {} +func (*Timestamp) Descriptor() ([]byte, []int) { + return fileDescriptor_timestamp_b826e8e5fba671a8, []int{0} +} +func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" } +func (m *Timestamp) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Timestamp.Unmarshal(m, b) +} +func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic) +} +func (dst *Timestamp) XXX_Merge(src proto.Message) { + xxx_messageInfo_Timestamp.Merge(dst, src) +} +func (m *Timestamp) XXX_Size() int { + return xxx_messageInfo_Timestamp.Size(m) +} +func (m *Timestamp) XXX_DiscardUnknown() { + xxx_messageInfo_Timestamp.DiscardUnknown(m) +} + +var xxx_messageInfo_Timestamp proto.InternalMessageInfo func (m *Timestamp) GetSeconds() int64 { if m != nil { @@ -141,9 +154,11 @@ func init() { proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp") } -func init() { proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor0) } +func init() { + proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor_timestamp_b826e8e5fba671a8) +} -var fileDescriptor0 = []byte{ +var fileDescriptor_timestamp_b826e8e5fba671a8 = []byte{ // 191 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d, diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto index b7cbd17502..06750ab1f1 100644 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto +++ b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto @@ -114,7 +114,7 @@ option objc_class_prefix = "GPB"; // to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) // with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one // can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( -// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()) +// http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime--) // to obtain a formatter capable of generating timestamps in this format. // // diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go b/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go deleted file mode 100644 index 6e3c969b94..0000000000 --- a/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go +++ /dev/null @@ -1,153 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2016 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// 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. - -package ptypes - -import ( - "math" - "testing" - "time" - - "github.com/golang/protobuf/proto" - tspb "github.com/golang/protobuf/ptypes/timestamp" -) - -var tests = []struct { - ts *tspb.Timestamp - valid bool - t time.Time -}{ - // The timestamp representing the Unix epoch date. - {&tspb.Timestamp{Seconds: 0, Nanos: 0}, true, utcDate(1970, 1, 1)}, - // The smallest representable timestamp. - {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: math.MinInt32}, false, - time.Unix(math.MinInt64, math.MinInt32).UTC()}, - // The smallest representable timestamp with non-negative nanos. - {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: 0}, false, time.Unix(math.MinInt64, 0).UTC()}, - // The earliest valid timestamp. - {&tspb.Timestamp{Seconds: minValidSeconds, Nanos: 0}, true, utcDate(1, 1, 1)}, - //"0001-01-01T00:00:00Z"}, - // The largest representable timestamp. - {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: math.MaxInt32}, false, - time.Unix(math.MaxInt64, math.MaxInt32).UTC()}, - // The largest representable timestamp with nanos in range. - {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: 1e9 - 1}, false, - time.Unix(math.MaxInt64, 1e9-1).UTC()}, - // The largest valid timestamp. - {&tspb.Timestamp{Seconds: maxValidSeconds - 1, Nanos: 1e9 - 1}, true, - time.Date(9999, 12, 31, 23, 59, 59, 1e9-1, time.UTC)}, - // The smallest invalid timestamp that is larger than the valid range. - {&tspb.Timestamp{Seconds: maxValidSeconds, Nanos: 0}, false, time.Unix(maxValidSeconds, 0).UTC()}, - // A date before the epoch. - {&tspb.Timestamp{Seconds: -281836800, Nanos: 0}, true, utcDate(1961, 1, 26)}, - // A date after the epoch. - {&tspb.Timestamp{Seconds: 1296000000, Nanos: 0}, true, utcDate(2011, 1, 26)}, - // A date after the epoch, in the middle of the day. - {&tspb.Timestamp{Seconds: 1296012345, Nanos: 940483}, true, - time.Date(2011, 1, 26, 3, 25, 45, 940483, time.UTC)}, -} - -func TestValidateTimestamp(t *testing.T) { - for _, s := range tests { - got := validateTimestamp(s.ts) - if (got == nil) != s.valid { - t.Errorf("validateTimestamp(%v) = %v, want %v", s.ts, got, s.valid) - } - } -} - -func TestTimestamp(t *testing.T) { - for _, s := range tests { - got, err := Timestamp(s.ts) - if (err == nil) != s.valid { - t.Errorf("Timestamp(%v) error = %v, but valid = %t", s.ts, err, s.valid) - } else if s.valid && got != s.t { - t.Errorf("Timestamp(%v) = %v, want %v", s.ts, got, s.t) - } - } - // Special case: a nil Timestamp is an error, but returns the 0 Unix time. - got, err := Timestamp(nil) - want := time.Unix(0, 0).UTC() - if got != want { - t.Errorf("Timestamp(nil) = %v, want %v", got, want) - } - if err == nil { - t.Errorf("Timestamp(nil) error = nil, expected error") - } -} - -func TestTimestampProto(t *testing.T) { - for _, s := range tests { - got, err := TimestampProto(s.t) - if (err == nil) != s.valid { - t.Errorf("TimestampProto(%v) error = %v, but valid = %t", s.t, err, s.valid) - } else if s.valid && !proto.Equal(got, s.ts) { - t.Errorf("TimestampProto(%v) = %v, want %v", s.t, got, s.ts) - } - } - // No corresponding special case here: no time.Time results in a nil Timestamp. -} - -func TestTimestampString(t *testing.T) { - for _, test := range []struct { - ts *tspb.Timestamp - want string - }{ - // Not much testing needed because presumably time.Format is - // well-tested. - {&tspb.Timestamp{Seconds: 0, Nanos: 0}, "1970-01-01T00:00:00Z"}, - {&tspb.Timestamp{Seconds: minValidSeconds - 1, Nanos: 0}, "(timestamp: seconds:-62135596801 before 0001-01-01)"}, - } { - got := TimestampString(test.ts) - if got != test.want { - t.Errorf("TimestampString(%v) = %q, want %q", test.ts, got, test.want) - } - } -} - -func utcDate(year, month, day int) time.Time { - return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) -} - -func TestTimestampNow(t *testing.T) { - // Bracket the expected time. - before := time.Now() - ts := TimestampNow() - after := time.Now() - - tm, err := Timestamp(ts) - if err != nil { - t.Errorf("between %v and %v\nTimestampNow() = %v\nwhich is invalid (%v)", before, after, ts, err) - } - if tm.Before(before) || tm.After(after) { - t.Errorf("between %v and %v\nTimestamp(TimestampNow()) = %v", before, after, tm) - } -} diff --git a/vendor/github.com/golang/protobuf/regenerate.sh b/vendor/github.com/golang/protobuf/regenerate.sh new file mode 100755 index 0000000000..dc7e2d1f61 --- /dev/null +++ b/vendor/github.com/golang/protobuf/regenerate.sh @@ -0,0 +1,53 @@ +#!/bin/bash + +set -e + +# Install the working tree's protoc-gen-gen in a tempdir. +tmpdir=$(mktemp -d -t regen-wkt.XXXXXX) +trap 'rm -rf $tmpdir' EXIT +mkdir -p $tmpdir/bin +PATH=$tmpdir/bin:$PATH +GOBIN=$tmpdir/bin go install ./protoc-gen-go + +# Public imports require at least Go 1.9. +supportTypeAliases="" +if go list -f '{{context.ReleaseTags}}' runtime | grep -q go1.9; then + supportTypeAliases=1 +fi + +# Generate various test protos. +PROTO_DIRS=( + conformance/internal/conformance_proto + jsonpb/jsonpb_test_proto + proto + protoc-gen-go/testdata +) +for dir in ${PROTO_DIRS[@]}; do + for p in `find $dir -name "*.proto"`; do + if [[ $p == */import_public/* && ! $supportTypeAliases ]]; then + echo "# $p (skipped)" + continue; + fi + echo "# $p" + protoc -I$dir --go_out=plugins=grpc,paths=source_relative:$dir $p + done +done + +# Deriving the location of the source protos from the path to the +# protoc binary may be a bit odd, but this is what protoc itself does. +PROTO_INCLUDE=$(dirname $(dirname $(which protoc)))/include + +# Well-known types. +WKT_PROTOS=(any duration empty struct timestamp wrappers) +for p in ${WKT_PROTOS[@]}; do + echo "# google/protobuf/$p.proto" + protoc --go_out=paths=source_relative:$tmpdir google/protobuf/$p.proto + cp $tmpdir/google/protobuf/$p.pb.go ptypes/$p + cp $PROTO_INCLUDE/google/protobuf/$p.proto ptypes/$p +done + +# descriptor.proto. +echo "# google/protobuf/descriptor.proto" +protoc --go_out=paths=source_relative:$tmpdir google/protobuf/descriptor.proto +cp $tmpdir/google/protobuf/descriptor.pb.go protoc-gen-go/descriptor +cp $PROTO_INCLUDE/google/protobuf/descriptor.proto protoc-gen-go/descriptor diff --git a/vendor/github.com/google/gofuzz/example_test.go b/vendor/github.com/google/gofuzz/example_test.go deleted file mode 100644 index 792707a3a1..0000000000 --- a/vendor/github.com/google/gofuzz/example_test.go +++ /dev/null @@ -1,225 +0,0 @@ -/* -Copyright 2014 Google Inc. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fuzz_test - -import ( - "encoding/json" - "fmt" - "math/rand" - - "github.com/google/gofuzz" -) - -func ExampleSimple() { - type MyType struct { - A string - B string - C int - D struct { - E float64 - } - } - - f := fuzz.New() - object := MyType{} - - uniqueObjects := map[MyType]int{} - - for i := 0; i < 1000; i++ { - f.Fuzz(&object) - uniqueObjects[object]++ - } - fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) - // Output: - // Got 1000 unique objects. -} - -func ExampleCustom() { - type MyType struct { - A int - B string - } - - counter := 0 - f := fuzz.New().Funcs( - func(i *int, c fuzz.Continue) { - *i = counter - counter++ - }, - ) - object := MyType{} - - uniqueObjects := map[MyType]int{} - - for i := 0; i < 100; i++ { - f.Fuzz(&object) - if object.A != i { - fmt.Printf("Unexpected value: %#v\n", object) - } - uniqueObjects[object]++ - } - fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) - // Output: - // Got 100 unique objects. -} - -func ExampleComplex() { - type OtherType struct { - A string - B string - } - type MyType struct { - Pointer *OtherType - Map map[string]OtherType - PointerMap *map[string]OtherType - Slice []OtherType - SlicePointer []*OtherType - PointerSlicePointer *[]*OtherType - } - - f := fuzz.New().RandSource(rand.NewSource(0)).NilChance(0).NumElements(1, 1).Funcs( - func(o *OtherType, c fuzz.Continue) { - o.A = "Foo" - o.B = "Bar" - }, - func(op **OtherType, c fuzz.Continue) { - *op = &OtherType{"A", "B"} - }, - func(m map[string]OtherType, c fuzz.Continue) { - m["Works Because"] = OtherType{ - "Fuzzer", - "Preallocated", - } - }, - ) - object := MyType{} - f.Fuzz(&object) - bytes, err := json.MarshalIndent(&object, "", " ") - if err != nil { - fmt.Printf("error: %v\n", err) - } - fmt.Printf("%s\n", string(bytes)) - // Output: - // { - // "Pointer": { - // "A": "A", - // "B": "B" - // }, - // "Map": { - // "Works Because": { - // "A": "Fuzzer", - // "B": "Preallocated" - // } - // }, - // "PointerMap": { - // "Works Because": { - // "A": "Fuzzer", - // "B": "Preallocated" - // } - // }, - // "Slice": [ - // { - // "A": "Foo", - // "B": "Bar" - // } - // ], - // "SlicePointer": [ - // { - // "A": "A", - // "B": "B" - // } - // ], - // "PointerSlicePointer": [ - // { - // "A": "A", - // "B": "B" - // } - // ] - // } -} - -func ExampleMap() { - f := fuzz.New().NilChance(0).NumElements(1, 1) - var myMap map[struct{ A, B, C int }]string - f.Fuzz(&myMap) - fmt.Printf("myMap has %v element(s).\n", len(myMap)) - // Output: - // myMap has 1 element(s). -} - -func ExampleSingle() { - f := fuzz.New() - var i int - f.Fuzz(&i) - - // Technically, we'd expect this to fail one out of 2 billion attempts... - fmt.Printf("(i == 0) == %v", i == 0) - // Output: - // (i == 0) == false -} - -func ExampleEnum() { - type MyEnum string - const ( - A MyEnum = "A" - B MyEnum = "B" - ) - type MyInfo struct { - Type MyEnum - AInfo *string - BInfo *string - } - - f := fuzz.New().NilChance(0).Funcs( - func(e *MyInfo, c fuzz.Continue) { - // Note c's embedded Rand allows for direct use. - // We could also use c.RandBool() here. - switch c.Intn(2) { - case 0: - e.Type = A - c.Fuzz(&e.AInfo) - case 1: - e.Type = B - c.Fuzz(&e.BInfo) - } - }, - ) - - for i := 0; i < 100; i++ { - var myObject MyInfo - f.Fuzz(&myObject) - switch myObject.Type { - case A: - if myObject.AInfo == nil { - fmt.Println("AInfo should have been set!") - } - if myObject.BInfo != nil { - fmt.Println("BInfo should NOT have been set!") - } - case B: - if myObject.BInfo == nil { - fmt.Println("BInfo should have been set!") - } - if myObject.AInfo != nil { - fmt.Println("AInfo should NOT have been set!") - } - default: - fmt.Println("Invalid enum value!") - } - } - // Output: -} diff --git a/vendor/github.com/google/gofuzz/fuzz_test.go b/vendor/github.com/google/gofuzz/fuzz_test.go deleted file mode 100644 index 4059ea6feb..0000000000 --- a/vendor/github.com/google/gofuzz/fuzz_test.go +++ /dev/null @@ -1,472 +0,0 @@ -/* -Copyright 2014 Google Inc. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fuzz - -import ( - "reflect" - "testing" - "time" -) - -func TestFuzz_basic(t *testing.T) { - obj := &struct { - I int - I8 int8 - I16 int16 - I32 int32 - I64 int64 - U uint - U8 uint8 - U16 uint16 - U32 uint32 - U64 uint64 - Uptr uintptr - S string - B bool - T time.Time - }{} - - failed := map[string]int{} - for i := 0; i < 10; i++ { - New().Fuzz(obj) - - if n, v := "i", obj.I; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i8", obj.I8; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i16", obj.I16; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i32", obj.I32; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "i64", obj.I64; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u", obj.U; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u8", obj.U8; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u16", obj.U16; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u32", obj.U32; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "u64", obj.U64; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "uptr", obj.Uptr; v == 0 { - failed[n] = failed[n] + 1 - } - if n, v := "s", obj.S; v == "" { - failed[n] = failed[n] + 1 - } - if n, v := "b", obj.B; v == false { - failed[n] = failed[n] + 1 - } - if n, v := "t", obj.T; v.IsZero() { - failed[n] = failed[n] + 1 - } - } - checkFailed(t, failed) -} - -func checkFailed(t *testing.T, failed map[string]int) { - for k, v := range failed { - if v > 8 { - t.Errorf("%v seems to not be getting set, was zero value %v times", k, v) - } - } -} - -func TestFuzz_structptr(t *testing.T) { - obj := &struct { - A *struct { - S string - } - }{} - - f := New().NilChance(.5) - failed := map[string]int{} - for i := 0; i < 10; i++ { - f.Fuzz(obj) - - if n, v := "a not nil", obj.A; v == nil { - failed[n] = failed[n] + 1 - } - if n, v := "a nil", obj.A; v != nil { - failed[n] = failed[n] + 1 - } - if n, v := "as", obj.A; v == nil || v.S == "" { - failed[n] = failed[n] + 1 - } - } - checkFailed(t, failed) -} - -// tryFuzz tries fuzzing up to 20 times. Fail if check() never passes, report the highest -// stage it ever got to. -func tryFuzz(t *testing.T, f *Fuzzer, obj interface{}, check func() (stage int, passed bool)) { - maxStage := 0 - for i := 0; i < 20; i++ { - f.Fuzz(obj) - stage, passed := check() - if stage > maxStage { - maxStage = stage - } - if passed { - return - } - } - t.Errorf("Only ever got to stage %v", maxStage) -} - -func TestFuzz_structmap(t *testing.T) { - obj := &struct { - A map[struct { - S string - }]struct { - S2 string - } - B map[string]string - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - if len(obj.A) == 0 { - return 2, false - } - for k, v := range obj.A { - if k.S == "" { - return 3, false - } - if v.S2 == "" { - return 4, false - } - } - - if obj.B == nil { - return 5, false - } - if len(obj.B) == 0 { - return 6, false - } - for k, v := range obj.B { - if k == "" { - return 7, false - } - if v == "" { - return 8, false - } - } - return 9, true - }) -} - -func TestFuzz_structslice(t *testing.T) { - obj := &struct { - A []struct { - S string - } - B []string - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - if len(obj.A) == 0 { - return 2, false - } - for _, v := range obj.A { - if v.S == "" { - return 3, false - } - } - - if obj.B == nil { - return 4, false - } - if len(obj.B) == 0 { - return 5, false - } - for _, v := range obj.B { - if v == "" { - return 6, false - } - } - return 7, true - }) -} - -func TestFuzz_structarray(t *testing.T) { - obj := &struct { - A [3]struct { - S string - } - B [2]int - }{} - - tryFuzz(t, New(), obj, func() (int, bool) { - for _, v := range obj.A { - if v.S == "" { - return 1, false - } - } - - for _, v := range obj.B { - if v == 0 { - return 2, false - } - } - return 3, true - }) -} - -func TestFuzz_custom(t *testing.T) { - obj := &struct { - A string - B *string - C map[string]string - D *map[string]string - }{} - - testPhrase := "gotcalled" - testMap := map[string]string{"C": "D"} - f := New().Funcs( - func(s *string, c Continue) { - *s = testPhrase - }, - func(m map[string]string, c Continue) { - m["C"] = "D" - }, - ) - - tryFuzz(t, f, obj, func() (int, bool) { - if obj.A != testPhrase { - return 1, false - } - if obj.B == nil { - return 2, false - } - if *obj.B != testPhrase { - return 3, false - } - if e, a := testMap, obj.C; !reflect.DeepEqual(e, a) { - return 4, false - } - if obj.D == nil { - return 5, false - } - if e, a := testMap, *obj.D; !reflect.DeepEqual(e, a) { - return 6, false - } - return 7, true - }) -} - -type SelfFuzzer string - -// Implement fuzz.Interface. -func (sf *SelfFuzzer) Fuzz(c Continue) { - *sf = selfFuzzerTestPhrase -} - -const selfFuzzerTestPhrase = "was fuzzed" - -func TestFuzz_interface(t *testing.T) { - f := New() - - var obj1 SelfFuzzer - tryFuzz(t, f, &obj1, func() (int, bool) { - if obj1 != selfFuzzerTestPhrase { - return 1, false - } - return 1, true - }) - - var obj2 map[int]SelfFuzzer - tryFuzz(t, f, &obj2, func() (int, bool) { - for _, v := range obj2 { - if v != selfFuzzerTestPhrase { - return 1, false - } - } - return 1, true - }) -} - -func TestFuzz_interfaceAndFunc(t *testing.T) { - const privateTestPhrase = "private phrase" - f := New().Funcs( - // This should take precedence over SelfFuzzer.Fuzz(). - func(s *SelfFuzzer, c Continue) { - *s = privateTestPhrase - }, - ) - - var obj1 SelfFuzzer - tryFuzz(t, f, &obj1, func() (int, bool) { - if obj1 != privateTestPhrase { - return 1, false - } - return 1, true - }) - - var obj2 map[int]SelfFuzzer - tryFuzz(t, f, &obj2, func() (int, bool) { - for _, v := range obj2 { - if v != privateTestPhrase { - return 1, false - } - } - return 1, true - }) -} - -func TestFuzz_noCustom(t *testing.T) { - type Inner struct { - Str string - } - type Outer struct { - Str string - In Inner - } - - testPhrase := "gotcalled" - f := New().Funcs( - func(outer *Outer, c Continue) { - outer.Str = testPhrase - c.Fuzz(&outer.In) - }, - func(inner *Inner, c Continue) { - inner.Str = testPhrase - }, - ) - c := Continue{fc: &fuzzerContext{fuzzer: f}, Rand: f.r} - - // Fuzzer.Fuzz() - obj1 := Outer{} - f.Fuzz(&obj1) - if obj1.Str != testPhrase { - t.Errorf("expected Outer custom function to have been called") - } - if obj1.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Continue.Fuzz() - obj2 := Outer{} - c.Fuzz(&obj2) - if obj2.Str != testPhrase { - t.Errorf("expected Outer custom function to have been called") - } - if obj2.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Fuzzer.FuzzNoCustom() - obj3 := Outer{} - f.FuzzNoCustom(&obj3) - if obj3.Str == testPhrase { - t.Errorf("expected Outer custom function to not have been called") - } - if obj3.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } - - // Continue.FuzzNoCustom() - obj4 := Outer{} - c.FuzzNoCustom(&obj4) - if obj4.Str == testPhrase { - t.Errorf("expected Outer custom function to not have been called") - } - if obj4.In.Str != testPhrase { - t.Errorf("expected Inner custom function to have been called") - } -} - -func TestFuzz_NumElements(t *testing.T) { - f := New().NilChance(0).NumElements(0, 1) - obj := &struct { - A []int - }{} - - tryFuzz(t, f, obj, func() (int, bool) { - if obj.A == nil { - return 1, false - } - return 2, len(obj.A) == 0 - }) - tryFuzz(t, f, obj, func() (int, bool) { - if obj.A == nil { - return 3, false - } - return 4, len(obj.A) == 1 - }) -} - -func TestFuzz_Maxdepth(t *testing.T) { - type S struct { - S *S - } - - f := New().NilChance(0) - - f.MaxDepth(1) - for i := 0; i < 100; i++ { - obj := S{} - f.Fuzz(&obj) - - if obj.S != nil { - t.Errorf("Expected nil") - } - } - - f.MaxDepth(3) // field, ptr - for i := 0; i < 100; i++ { - obj := S{} - f.Fuzz(&obj) - - if obj.S == nil { - t.Errorf("Expected obj.S not nil") - } else if obj.S.S != nil { - t.Errorf("Expected obj.S.S nil") - } - } - - f.MaxDepth(5) // field, ptr, field, ptr - for i := 0; i < 100; i++ { - obj := S{} - f.Fuzz(&obj) - - if obj.S == nil { - t.Errorf("Expected obj.S not nil") - } else if obj.S.S == nil { - t.Errorf("Expected obj.S.S not nil") - } else if obj.S.S.S != nil { - t.Errorf("Expected obj.S.S.S nil") - } - } -} diff --git a/vendor/github.com/googleapis/gnostic/.gitignore b/vendor/github.com/googleapis/gnostic/.gitignore index 63149fddab..2a9d09b79d 100644 --- a/vendor/github.com/googleapis/gnostic/.gitignore +++ b/vendor/github.com/googleapis/gnostic/.gitignore @@ -1,3 +1,5 @@ +# IntelliJ IDEA +.idea # Eclipse .checkstyle .project @@ -5,6 +7,10 @@ # Swift .build Packages +# Node +node_modules +package-lock.json +bundle.json # vi *.swp # vscode @@ -12,3 +18,4 @@ Packages .DS_Store *~ Package.resolved +extensions/sample/generated diff --git a/vendor/github.com/googleapis/gnostic/.travis.yml b/vendor/github.com/googleapis/gnostic/.travis.yml index d31126d162..c3d2791fc5 100644 --- a/vendor/github.com/googleapis/gnostic/.travis.yml +++ b/vendor/github.com/googleapis/gnostic/.travis.yml @@ -32,13 +32,16 @@ script: - pushd plugins/gnostic-go-generator/examples/v2.0/bookstore - make test - popd + - pushd plugins/gnostic-go-generator/examples/v2.0/sample + - make test + - popd - pushd plugins/gnostic-go-generator/examples/v3.0/bookstore - make test - popd - export PATH=.:$HOME/local/bin:$PATH - export LD_LIBRARY_PATH=$HOME/local/lib - pushd plugins/gnostic-swift-generator - - make + - make install - cd examples/bookstore - make - .build/debug/Server & diff --git a/vendor/github.com/googleapis/gnostic/COMPILE-PROTOS.sh b/vendor/github.com/googleapis/gnostic/COMPILE-PROTOS.sh index 017dab670e..584878a10f 100755 --- a/vendor/github.com/googleapis/gnostic/COMPILE-PROTOS.sh +++ b/vendor/github.com/googleapis/gnostic/COMPILE-PROTOS.sh @@ -22,6 +22,7 @@ protoc \ OpenAPIv2/OpenAPIv2.proto protoc \ +-I.:$GOPATH/src \ --go_out=:. \ plugins/plugin.proto diff --git a/vendor/github.com/googleapis/gnostic/OpenAPIv2/OpenAPIv2.go b/vendor/github.com/googleapis/gnostic/OpenAPIv2/OpenAPIv2.go index 0e32451a32..5351f36f36 100644 --- a/vendor/github.com/googleapis/gnostic/OpenAPIv2/OpenAPIv2.go +++ b/vendor/github.com/googleapis/gnostic/OpenAPIv2/OpenAPIv2.go @@ -7106,20 +7106,20 @@ func (m *Any) ToRawInfo() interface{} { func (m *ApiKeySecurity) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.In != "" { - info = append(info, yaml.MapItem{"in", m.In}) + info = append(info, yaml.MapItem{Key: "in", Value: m.In}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7130,14 +7130,14 @@ func (m *ApiKeySecurity) ToRawInfo() interface{} { func (m *BasicAuthenticationSecurity) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7148,24 +7148,24 @@ func (m *BasicAuthenticationSecurity) ToRawInfo() interface{} { func (m *BodyParameter) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.In != "" { - info = append(info, yaml.MapItem{"in", m.In}) + info = append(info, yaml.MapItem{Key: "in", Value: m.In}) } if m.Required != false { - info = append(info, yaml.MapItem{"required", m.Required}) + info = append(info, yaml.MapItem{Key: "required", Value: m.Required}) } if m.Schema != nil { - info = append(info, yaml.MapItem{"schema", m.Schema.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "schema", Value: m.Schema.ToRawInfo()}) } // &{Name:schema Type:Schema StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7176,17 +7176,17 @@ func (m *BodyParameter) ToRawInfo() interface{} { func (m *Contact) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.Url != "" { - info = append(info, yaml.MapItem{"url", m.Url}) + info = append(info, yaml.MapItem{Key: "url", Value: m.Url}) } if m.Email != "" { - info = append(info, yaml.MapItem{"email", m.Email}) + info = append(info, yaml.MapItem{Key: "email", Value: m.Email}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7198,7 +7198,7 @@ func (m *Default) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.AdditionalProperties != nil { for _, item := range m.AdditionalProperties { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:additionalProperties Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern: Implicit:false Description:} @@ -7210,7 +7210,7 @@ func (m *Definitions) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.AdditionalProperties != nil { for _, item := range m.AdditionalProperties { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:additionalProperties Type:NamedSchema StringEnumValues:[] MapType:Schema Repeated:true Pattern: Implicit:true Description:} @@ -7221,41 +7221,41 @@ func (m *Definitions) ToRawInfo() interface{} { func (m *Document) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Swagger != "" { - info = append(info, yaml.MapItem{"swagger", m.Swagger}) + info = append(info, yaml.MapItem{Key: "swagger", Value: m.Swagger}) } if m.Info != nil { - info = append(info, yaml.MapItem{"info", m.Info.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "info", Value: m.Info.ToRawInfo()}) } // &{Name:info Type:Info StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Host != "" { - info = append(info, yaml.MapItem{"host", m.Host}) + info = append(info, yaml.MapItem{Key: "host", Value: m.Host}) } if m.BasePath != "" { - info = append(info, yaml.MapItem{"basePath", m.BasePath}) + info = append(info, yaml.MapItem{Key: "basePath", Value: m.BasePath}) } if len(m.Schemes) != 0 { - info = append(info, yaml.MapItem{"schemes", m.Schemes}) + info = append(info, yaml.MapItem{Key: "schemes", Value: m.Schemes}) } if len(m.Consumes) != 0 { - info = append(info, yaml.MapItem{"consumes", m.Consumes}) + info = append(info, yaml.MapItem{Key: "consumes", Value: m.Consumes}) } if len(m.Produces) != 0 { - info = append(info, yaml.MapItem{"produces", m.Produces}) + info = append(info, yaml.MapItem{Key: "produces", Value: m.Produces}) } if m.Paths != nil { - info = append(info, yaml.MapItem{"paths", m.Paths.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "paths", Value: m.Paths.ToRawInfo()}) } // &{Name:paths Type:Paths StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Definitions != nil { - info = append(info, yaml.MapItem{"definitions", m.Definitions.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "definitions", Value: m.Definitions.ToRawInfo()}) } // &{Name:definitions Type:Definitions StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Parameters != nil { - info = append(info, yaml.MapItem{"parameters", m.Parameters.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "parameters", Value: m.Parameters.ToRawInfo()}) } // &{Name:parameters Type:ParameterDefinitions StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Responses != nil { - info = append(info, yaml.MapItem{"responses", m.Responses.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "responses", Value: m.Responses.ToRawInfo()}) } // &{Name:responses Type:ResponseDefinitions StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if len(m.Security) != 0 { @@ -7263,11 +7263,11 @@ func (m *Document) ToRawInfo() interface{} { for _, item := range m.Security { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"security", items}) + info = append(info, yaml.MapItem{Key: "security", Value: items}) } // &{Name:security Type:SecurityRequirement StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.SecurityDefinitions != nil { - info = append(info, yaml.MapItem{"securityDefinitions", m.SecurityDefinitions.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "securityDefinitions", Value: m.SecurityDefinitions.ToRawInfo()}) } // &{Name:securityDefinitions Type:SecurityDefinitions StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if len(m.Tags) != 0 { @@ -7275,16 +7275,16 @@ func (m *Document) ToRawInfo() interface{} { for _, item := range m.Tags { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"tags", items}) + info = append(info, yaml.MapItem{Key: "tags", Value: items}) } // &{Name:tags Type:Tag StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.ExternalDocs != nil { - info = append(info, yaml.MapItem{"externalDocs", m.ExternalDocs.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "externalDocs", Value: m.ExternalDocs.ToRawInfo()}) } // &{Name:externalDocs Type:ExternalDocs StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7296,7 +7296,7 @@ func (m *Examples) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.AdditionalProperties != nil { for _, item := range m.AdditionalProperties { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:additionalProperties Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern: Implicit:true Description:} @@ -7307,14 +7307,14 @@ func (m *Examples) ToRawInfo() interface{} { func (m *ExternalDocs) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.Url != "" { - info = append(info, yaml.MapItem{"url", m.Url}) + info = append(info, yaml.MapItem{Key: "url", Value: m.Url}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7325,38 +7325,38 @@ func (m *ExternalDocs) ToRawInfo() interface{} { func (m *FileSchema) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Format != "" { - info = append(info, yaml.MapItem{"format", m.Format}) + info = append(info, yaml.MapItem{Key: "format", Value: m.Format}) } if m.Title != "" { - info = append(info, yaml.MapItem{"title", m.Title}) + info = append(info, yaml.MapItem{Key: "title", Value: m.Title}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.Default != nil { - info = append(info, yaml.MapItem{"default", m.Default.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "default", Value: m.Default.ToRawInfo()}) } // &{Name:default Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if len(m.Required) != 0 { - info = append(info, yaml.MapItem{"required", m.Required}) + info = append(info, yaml.MapItem{Key: "required", Value: m.Required}) } if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.ReadOnly != false { - info = append(info, yaml.MapItem{"readOnly", m.ReadOnly}) + info = append(info, yaml.MapItem{Key: "readOnly", Value: m.ReadOnly}) } if m.ExternalDocs != nil { - info = append(info, yaml.MapItem{"externalDocs", m.ExternalDocs.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "externalDocs", Value: m.ExternalDocs.ToRawInfo()}) } // &{Name:externalDocs Type:ExternalDocs StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Example != nil { - info = append(info, yaml.MapItem{"example", m.Example.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "example", Value: m.Example.ToRawInfo()}) } // &{Name:example Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7367,81 +7367,81 @@ func (m *FileSchema) ToRawInfo() interface{} { func (m *FormDataParameterSubSchema) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Required != false { - info = append(info, yaml.MapItem{"required", m.Required}) + info = append(info, yaml.MapItem{Key: "required", Value: m.Required}) } if m.In != "" { - info = append(info, yaml.MapItem{"in", m.In}) + info = append(info, yaml.MapItem{Key: "in", Value: m.In}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.AllowEmptyValue != false { - info = append(info, yaml.MapItem{"allowEmptyValue", m.AllowEmptyValue}) + info = append(info, yaml.MapItem{Key: "allowEmptyValue", Value: m.AllowEmptyValue}) } if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Format != "" { - info = append(info, yaml.MapItem{"format", m.Format}) + info = append(info, yaml.MapItem{Key: "format", Value: m.Format}) } if m.Items != nil { - info = append(info, yaml.MapItem{"items", m.Items.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "items", Value: m.Items.ToRawInfo()}) } // &{Name:items Type:PrimitivesItems StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.CollectionFormat != "" { - info = append(info, yaml.MapItem{"collectionFormat", m.CollectionFormat}) + info = append(info, yaml.MapItem{Key: "collectionFormat", Value: m.CollectionFormat}) } if m.Default != nil { - info = append(info, yaml.MapItem{"default", m.Default.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "default", Value: m.Default.ToRawInfo()}) } // &{Name:default Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Maximum != 0.0 { - info = append(info, yaml.MapItem{"maximum", m.Maximum}) + info = append(info, yaml.MapItem{Key: "maximum", Value: m.Maximum}) } if m.ExclusiveMaximum != false { - info = append(info, yaml.MapItem{"exclusiveMaximum", m.ExclusiveMaximum}) + info = append(info, yaml.MapItem{Key: "exclusiveMaximum", Value: m.ExclusiveMaximum}) } if m.Minimum != 0.0 { - info = append(info, yaml.MapItem{"minimum", m.Minimum}) + info = append(info, yaml.MapItem{Key: "minimum", Value: m.Minimum}) } if m.ExclusiveMinimum != false { - info = append(info, yaml.MapItem{"exclusiveMinimum", m.ExclusiveMinimum}) + info = append(info, yaml.MapItem{Key: "exclusiveMinimum", Value: m.ExclusiveMinimum}) } if m.MaxLength != 0 { - info = append(info, yaml.MapItem{"maxLength", m.MaxLength}) + info = append(info, yaml.MapItem{Key: "maxLength", Value: m.MaxLength}) } if m.MinLength != 0 { - info = append(info, yaml.MapItem{"minLength", m.MinLength}) + info = append(info, yaml.MapItem{Key: "minLength", Value: m.MinLength}) } if m.Pattern != "" { - info = append(info, yaml.MapItem{"pattern", m.Pattern}) + info = append(info, yaml.MapItem{Key: "pattern", Value: m.Pattern}) } if m.MaxItems != 0 { - info = append(info, yaml.MapItem{"maxItems", m.MaxItems}) + info = append(info, yaml.MapItem{Key: "maxItems", Value: m.MaxItems}) } if m.MinItems != 0 { - info = append(info, yaml.MapItem{"minItems", m.MinItems}) + info = append(info, yaml.MapItem{Key: "minItems", Value: m.MinItems}) } if m.UniqueItems != false { - info = append(info, yaml.MapItem{"uniqueItems", m.UniqueItems}) + info = append(info, yaml.MapItem{Key: "uniqueItems", Value: m.UniqueItems}) } if len(m.Enum) != 0 { items := make([]interface{}, 0) for _, item := range m.Enum { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"enum", items}) + info = append(info, yaml.MapItem{Key: "enum", Value: items}) } // &{Name:enum Type:Any StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.MultipleOf != 0.0 { - info = append(info, yaml.MapItem{"multipleOf", m.MultipleOf}) + info = append(info, yaml.MapItem{Key: "multipleOf", Value: m.MultipleOf}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7452,69 +7452,69 @@ func (m *FormDataParameterSubSchema) ToRawInfo() interface{} { func (m *Header) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Format != "" { - info = append(info, yaml.MapItem{"format", m.Format}) + info = append(info, yaml.MapItem{Key: "format", Value: m.Format}) } if m.Items != nil { - info = append(info, yaml.MapItem{"items", m.Items.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "items", Value: m.Items.ToRawInfo()}) } // &{Name:items Type:PrimitivesItems StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.CollectionFormat != "" { - info = append(info, yaml.MapItem{"collectionFormat", m.CollectionFormat}) + info = append(info, yaml.MapItem{Key: "collectionFormat", Value: m.CollectionFormat}) } if m.Default != nil { - info = append(info, yaml.MapItem{"default", m.Default.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "default", Value: m.Default.ToRawInfo()}) } // &{Name:default Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Maximum != 0.0 { - info = append(info, yaml.MapItem{"maximum", m.Maximum}) + info = append(info, yaml.MapItem{Key: "maximum", Value: m.Maximum}) } if m.ExclusiveMaximum != false { - info = append(info, yaml.MapItem{"exclusiveMaximum", m.ExclusiveMaximum}) + info = append(info, yaml.MapItem{Key: "exclusiveMaximum", Value: m.ExclusiveMaximum}) } if m.Minimum != 0.0 { - info = append(info, yaml.MapItem{"minimum", m.Minimum}) + info = append(info, yaml.MapItem{Key: "minimum", Value: m.Minimum}) } if m.ExclusiveMinimum != false { - info = append(info, yaml.MapItem{"exclusiveMinimum", m.ExclusiveMinimum}) + info = append(info, yaml.MapItem{Key: "exclusiveMinimum", Value: m.ExclusiveMinimum}) } if m.MaxLength != 0 { - info = append(info, yaml.MapItem{"maxLength", m.MaxLength}) + info = append(info, yaml.MapItem{Key: "maxLength", Value: m.MaxLength}) } if m.MinLength != 0 { - info = append(info, yaml.MapItem{"minLength", m.MinLength}) + info = append(info, yaml.MapItem{Key: "minLength", Value: m.MinLength}) } if m.Pattern != "" { - info = append(info, yaml.MapItem{"pattern", m.Pattern}) + info = append(info, yaml.MapItem{Key: "pattern", Value: m.Pattern}) } if m.MaxItems != 0 { - info = append(info, yaml.MapItem{"maxItems", m.MaxItems}) + info = append(info, yaml.MapItem{Key: "maxItems", Value: m.MaxItems}) } if m.MinItems != 0 { - info = append(info, yaml.MapItem{"minItems", m.MinItems}) + info = append(info, yaml.MapItem{Key: "minItems", Value: m.MinItems}) } if m.UniqueItems != false { - info = append(info, yaml.MapItem{"uniqueItems", m.UniqueItems}) + info = append(info, yaml.MapItem{Key: "uniqueItems", Value: m.UniqueItems}) } if len(m.Enum) != 0 { items := make([]interface{}, 0) for _, item := range m.Enum { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"enum", items}) + info = append(info, yaml.MapItem{Key: "enum", Value: items}) } // &{Name:enum Type:Any StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.MultipleOf != 0.0 { - info = append(info, yaml.MapItem{"multipleOf", m.MultipleOf}) + info = append(info, yaml.MapItem{Key: "multipleOf", Value: m.MultipleOf}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7525,78 +7525,78 @@ func (m *Header) ToRawInfo() interface{} { func (m *HeaderParameterSubSchema) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Required != false { - info = append(info, yaml.MapItem{"required", m.Required}) + info = append(info, yaml.MapItem{Key: "required", Value: m.Required}) } if m.In != "" { - info = append(info, yaml.MapItem{"in", m.In}) + info = append(info, yaml.MapItem{Key: "in", Value: m.In}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Format != "" { - info = append(info, yaml.MapItem{"format", m.Format}) + info = append(info, yaml.MapItem{Key: "format", Value: m.Format}) } if m.Items != nil { - info = append(info, yaml.MapItem{"items", m.Items.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "items", Value: m.Items.ToRawInfo()}) } // &{Name:items Type:PrimitivesItems StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.CollectionFormat != "" { - info = append(info, yaml.MapItem{"collectionFormat", m.CollectionFormat}) + info = append(info, yaml.MapItem{Key: "collectionFormat", Value: m.CollectionFormat}) } if m.Default != nil { - info = append(info, yaml.MapItem{"default", m.Default.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "default", Value: m.Default.ToRawInfo()}) } // &{Name:default Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Maximum != 0.0 { - info = append(info, yaml.MapItem{"maximum", m.Maximum}) + info = append(info, yaml.MapItem{Key: "maximum", Value: m.Maximum}) } if m.ExclusiveMaximum != false { - info = append(info, yaml.MapItem{"exclusiveMaximum", m.ExclusiveMaximum}) + info = append(info, yaml.MapItem{Key: "exclusiveMaximum", Value: m.ExclusiveMaximum}) } if m.Minimum != 0.0 { - info = append(info, yaml.MapItem{"minimum", m.Minimum}) + info = append(info, yaml.MapItem{Key: "minimum", Value: m.Minimum}) } if m.ExclusiveMinimum != false { - info = append(info, yaml.MapItem{"exclusiveMinimum", m.ExclusiveMinimum}) + info = append(info, yaml.MapItem{Key: "exclusiveMinimum", Value: m.ExclusiveMinimum}) } if m.MaxLength != 0 { - info = append(info, yaml.MapItem{"maxLength", m.MaxLength}) + info = append(info, yaml.MapItem{Key: "maxLength", Value: m.MaxLength}) } if m.MinLength != 0 { - info = append(info, yaml.MapItem{"minLength", m.MinLength}) + info = append(info, yaml.MapItem{Key: "minLength", Value: m.MinLength}) } if m.Pattern != "" { - info = append(info, yaml.MapItem{"pattern", m.Pattern}) + info = append(info, yaml.MapItem{Key: "pattern", Value: m.Pattern}) } if m.MaxItems != 0 { - info = append(info, yaml.MapItem{"maxItems", m.MaxItems}) + info = append(info, yaml.MapItem{Key: "maxItems", Value: m.MaxItems}) } if m.MinItems != 0 { - info = append(info, yaml.MapItem{"minItems", m.MinItems}) + info = append(info, yaml.MapItem{Key: "minItems", Value: m.MinItems}) } if m.UniqueItems != false { - info = append(info, yaml.MapItem{"uniqueItems", m.UniqueItems}) + info = append(info, yaml.MapItem{Key: "uniqueItems", Value: m.UniqueItems}) } if len(m.Enum) != 0 { items := make([]interface{}, 0) for _, item := range m.Enum { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"enum", items}) + info = append(info, yaml.MapItem{Key: "enum", Value: items}) } // &{Name:enum Type:Any StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.MultipleOf != 0.0 { - info = append(info, yaml.MapItem{"multipleOf", m.MultipleOf}) + info = append(info, yaml.MapItem{Key: "multipleOf", Value: m.MultipleOf}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7608,7 +7608,7 @@ func (m *Headers) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.AdditionalProperties != nil { for _, item := range m.AdditionalProperties { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:additionalProperties Type:NamedHeader StringEnumValues:[] MapType:Header Repeated:true Pattern: Implicit:true Description:} @@ -7619,28 +7619,28 @@ func (m *Headers) ToRawInfo() interface{} { func (m *Info) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Title != "" { - info = append(info, yaml.MapItem{"title", m.Title}) + info = append(info, yaml.MapItem{Key: "title", Value: m.Title}) } if m.Version != "" { - info = append(info, yaml.MapItem{"version", m.Version}) + info = append(info, yaml.MapItem{Key: "version", Value: m.Version}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.TermsOfService != "" { - info = append(info, yaml.MapItem{"termsOfService", m.TermsOfService}) + info = append(info, yaml.MapItem{Key: "termsOfService", Value: m.TermsOfService}) } if m.Contact != nil { - info = append(info, yaml.MapItem{"contact", m.Contact.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "contact", Value: m.Contact.ToRawInfo()}) } // &{Name:contact Type:Contact StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.License != nil { - info = append(info, yaml.MapItem{"license", m.License.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "license", Value: m.License.ToRawInfo()}) } // &{Name:license Type:License StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7655,7 +7655,7 @@ func (m *ItemsItem) ToRawInfo() interface{} { for _, item := range m.Schema { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"schema", items}) + info = append(info, yaml.MapItem{Key: "schema", Value: items}) } // &{Name:schema Type:Schema StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} return info @@ -7665,10 +7665,10 @@ func (m *ItemsItem) ToRawInfo() interface{} { func (m *JsonReference) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.XRef != "" { - info = append(info, yaml.MapItem{"$ref", m.XRef}) + info = append(info, yaml.MapItem{Key: "$ref", Value: m.XRef}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } return info } @@ -7677,14 +7677,14 @@ func (m *JsonReference) ToRawInfo() interface{} { func (m *License) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.Url != "" { - info = append(info, yaml.MapItem{"url", m.Url}) + info = append(info, yaml.MapItem{Key: "url", Value: m.Url}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7695,7 +7695,7 @@ func (m *License) ToRawInfo() interface{} { func (m *NamedAny) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } // &{Name:value Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:Mapped value} return info @@ -7705,7 +7705,7 @@ func (m *NamedAny) ToRawInfo() interface{} { func (m *NamedHeader) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } // &{Name:value Type:Header StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:Mapped value} return info @@ -7715,7 +7715,7 @@ func (m *NamedHeader) ToRawInfo() interface{} { func (m *NamedParameter) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } // &{Name:value Type:Parameter StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:Mapped value} return info @@ -7725,7 +7725,7 @@ func (m *NamedParameter) ToRawInfo() interface{} { func (m *NamedPathItem) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } // &{Name:value Type:PathItem StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:Mapped value} return info @@ -7735,7 +7735,7 @@ func (m *NamedPathItem) ToRawInfo() interface{} { func (m *NamedResponse) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } // &{Name:value Type:Response StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:Mapped value} return info @@ -7745,7 +7745,7 @@ func (m *NamedResponse) ToRawInfo() interface{} { func (m *NamedResponseValue) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } // &{Name:value Type:ResponseValue StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:Mapped value} return info @@ -7755,7 +7755,7 @@ func (m *NamedResponseValue) ToRawInfo() interface{} { func (m *NamedSchema) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } // &{Name:value Type:Schema StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:Mapped value} return info @@ -7765,7 +7765,7 @@ func (m *NamedSchema) ToRawInfo() interface{} { func (m *NamedSecurityDefinitionsItem) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } // &{Name:value Type:SecurityDefinitionsItem StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:Mapped value} return info @@ -7775,10 +7775,10 @@ func (m *NamedSecurityDefinitionsItem) ToRawInfo() interface{} { func (m *NamedString) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.Value != "" { - info = append(info, yaml.MapItem{"value", m.Value}) + info = append(info, yaml.MapItem{Key: "value", Value: m.Value}) } return info } @@ -7787,7 +7787,7 @@ func (m *NamedString) ToRawInfo() interface{} { func (m *NamedStringArray) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } // &{Name:value Type:StringArray StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:Mapped value} return info @@ -7824,27 +7824,27 @@ func (m *NonBodyParameter) ToRawInfo() interface{} { func (m *Oauth2AccessCodeSecurity) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Flow != "" { - info = append(info, yaml.MapItem{"flow", m.Flow}) + info = append(info, yaml.MapItem{Key: "flow", Value: m.Flow}) } if m.Scopes != nil { - info = append(info, yaml.MapItem{"scopes", m.Scopes.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "scopes", Value: m.Scopes.ToRawInfo()}) } // &{Name:scopes Type:Oauth2Scopes StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.AuthorizationUrl != "" { - info = append(info, yaml.MapItem{"authorizationUrl", m.AuthorizationUrl}) + info = append(info, yaml.MapItem{Key: "authorizationUrl", Value: m.AuthorizationUrl}) } if m.TokenUrl != "" { - info = append(info, yaml.MapItem{"tokenUrl", m.TokenUrl}) + info = append(info, yaml.MapItem{Key: "tokenUrl", Value: m.TokenUrl}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7855,24 +7855,24 @@ func (m *Oauth2AccessCodeSecurity) ToRawInfo() interface{} { func (m *Oauth2ApplicationSecurity) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Flow != "" { - info = append(info, yaml.MapItem{"flow", m.Flow}) + info = append(info, yaml.MapItem{Key: "flow", Value: m.Flow}) } if m.Scopes != nil { - info = append(info, yaml.MapItem{"scopes", m.Scopes.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "scopes", Value: m.Scopes.ToRawInfo()}) } // &{Name:scopes Type:Oauth2Scopes StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.TokenUrl != "" { - info = append(info, yaml.MapItem{"tokenUrl", m.TokenUrl}) + info = append(info, yaml.MapItem{Key: "tokenUrl", Value: m.TokenUrl}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7883,24 +7883,24 @@ func (m *Oauth2ApplicationSecurity) ToRawInfo() interface{} { func (m *Oauth2ImplicitSecurity) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Flow != "" { - info = append(info, yaml.MapItem{"flow", m.Flow}) + info = append(info, yaml.MapItem{Key: "flow", Value: m.Flow}) } if m.Scopes != nil { - info = append(info, yaml.MapItem{"scopes", m.Scopes.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "scopes", Value: m.Scopes.ToRawInfo()}) } // &{Name:scopes Type:Oauth2Scopes StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.AuthorizationUrl != "" { - info = append(info, yaml.MapItem{"authorizationUrl", m.AuthorizationUrl}) + info = append(info, yaml.MapItem{Key: "authorizationUrl", Value: m.AuthorizationUrl}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7911,24 +7911,24 @@ func (m *Oauth2ImplicitSecurity) ToRawInfo() interface{} { func (m *Oauth2PasswordSecurity) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Flow != "" { - info = append(info, yaml.MapItem{"flow", m.Flow}) + info = append(info, yaml.MapItem{Key: "flow", Value: m.Flow}) } if m.Scopes != nil { - info = append(info, yaml.MapItem{"scopes", m.Scopes.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "scopes", Value: m.Scopes.ToRawInfo()}) } // &{Name:scopes Type:Oauth2Scopes StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.TokenUrl != "" { - info = append(info, yaml.MapItem{"tokenUrl", m.TokenUrl}) + info = append(info, yaml.MapItem{Key: "tokenUrl", Value: m.TokenUrl}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -7946,56 +7946,56 @@ func (m *Oauth2Scopes) ToRawInfo() interface{} { func (m *Operation) ToRawInfo() interface{} { info := yaml.MapSlice{} if len(m.Tags) != 0 { - info = append(info, yaml.MapItem{"tags", m.Tags}) + info = append(info, yaml.MapItem{Key: "tags", Value: m.Tags}) } if m.Summary != "" { - info = append(info, yaml.MapItem{"summary", m.Summary}) + info = append(info, yaml.MapItem{Key: "summary", Value: m.Summary}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.ExternalDocs != nil { - info = append(info, yaml.MapItem{"externalDocs", m.ExternalDocs.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "externalDocs", Value: m.ExternalDocs.ToRawInfo()}) } // &{Name:externalDocs Type:ExternalDocs StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.OperationId != "" { - info = append(info, yaml.MapItem{"operationId", m.OperationId}) + info = append(info, yaml.MapItem{Key: "operationId", Value: m.OperationId}) } if len(m.Produces) != 0 { - info = append(info, yaml.MapItem{"produces", m.Produces}) + info = append(info, yaml.MapItem{Key: "produces", Value: m.Produces}) } if len(m.Consumes) != 0 { - info = append(info, yaml.MapItem{"consumes", m.Consumes}) + info = append(info, yaml.MapItem{Key: "consumes", Value: m.Consumes}) } if len(m.Parameters) != 0 { items := make([]interface{}, 0) for _, item := range m.Parameters { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"parameters", items}) + info = append(info, yaml.MapItem{Key: "parameters", Value: items}) } // &{Name:parameters Type:ParametersItem StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:The parameters needed to send a valid API call.} if m.Responses != nil { - info = append(info, yaml.MapItem{"responses", m.Responses.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "responses", Value: m.Responses.ToRawInfo()}) } // &{Name:responses Type:Responses StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if len(m.Schemes) != 0 { - info = append(info, yaml.MapItem{"schemes", m.Schemes}) + info = append(info, yaml.MapItem{Key: "schemes", Value: m.Schemes}) } if m.Deprecated != false { - info = append(info, yaml.MapItem{"deprecated", m.Deprecated}) + info = append(info, yaml.MapItem{Key: "deprecated", Value: m.Deprecated}) } if len(m.Security) != 0 { items := make([]interface{}, 0) for _, item := range m.Security { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"security", items}) + info = append(info, yaml.MapItem{Key: "security", Value: items}) } // &{Name:security Type:SecurityRequirement StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -8024,7 +8024,7 @@ func (m *ParameterDefinitions) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.AdditionalProperties != nil { for _, item := range m.AdditionalProperties { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:additionalProperties Type:NamedParameter StringEnumValues:[] MapType:Parameter Repeated:true Pattern: Implicit:true Description:} @@ -8052,34 +8052,34 @@ func (m *ParametersItem) ToRawInfo() interface{} { func (m *PathItem) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.XRef != "" { - info = append(info, yaml.MapItem{"$ref", m.XRef}) + info = append(info, yaml.MapItem{Key: "$ref", Value: m.XRef}) } if m.Get != nil { - info = append(info, yaml.MapItem{"get", m.Get.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "get", Value: m.Get.ToRawInfo()}) } // &{Name:get Type:Operation StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Put != nil { - info = append(info, yaml.MapItem{"put", m.Put.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "put", Value: m.Put.ToRawInfo()}) } // &{Name:put Type:Operation StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Post != nil { - info = append(info, yaml.MapItem{"post", m.Post.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "post", Value: m.Post.ToRawInfo()}) } // &{Name:post Type:Operation StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Delete != nil { - info = append(info, yaml.MapItem{"delete", m.Delete.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "delete", Value: m.Delete.ToRawInfo()}) } // &{Name:delete Type:Operation StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Options != nil { - info = append(info, yaml.MapItem{"options", m.Options.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "options", Value: m.Options.ToRawInfo()}) } // &{Name:options Type:Operation StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Head != nil { - info = append(info, yaml.MapItem{"head", m.Head.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "head", Value: m.Head.ToRawInfo()}) } // &{Name:head Type:Operation StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Patch != nil { - info = append(info, yaml.MapItem{"patch", m.Patch.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "patch", Value: m.Patch.ToRawInfo()}) } // &{Name:patch Type:Operation StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if len(m.Parameters) != 0 { @@ -8087,12 +8087,12 @@ func (m *PathItem) ToRawInfo() interface{} { for _, item := range m.Parameters { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"parameters", items}) + info = append(info, yaml.MapItem{Key: "parameters", Value: items}) } // &{Name:parameters Type:ParametersItem StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:The parameters needed to send a valid API call.} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -8103,78 +8103,78 @@ func (m *PathItem) ToRawInfo() interface{} { func (m *PathParameterSubSchema) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Required != false { - info = append(info, yaml.MapItem{"required", m.Required}) + info = append(info, yaml.MapItem{Key: "required", Value: m.Required}) } if m.In != "" { - info = append(info, yaml.MapItem{"in", m.In}) + info = append(info, yaml.MapItem{Key: "in", Value: m.In}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Format != "" { - info = append(info, yaml.MapItem{"format", m.Format}) + info = append(info, yaml.MapItem{Key: "format", Value: m.Format}) } if m.Items != nil { - info = append(info, yaml.MapItem{"items", m.Items.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "items", Value: m.Items.ToRawInfo()}) } // &{Name:items Type:PrimitivesItems StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.CollectionFormat != "" { - info = append(info, yaml.MapItem{"collectionFormat", m.CollectionFormat}) + info = append(info, yaml.MapItem{Key: "collectionFormat", Value: m.CollectionFormat}) } if m.Default != nil { - info = append(info, yaml.MapItem{"default", m.Default.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "default", Value: m.Default.ToRawInfo()}) } // &{Name:default Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Maximum != 0.0 { - info = append(info, yaml.MapItem{"maximum", m.Maximum}) + info = append(info, yaml.MapItem{Key: "maximum", Value: m.Maximum}) } if m.ExclusiveMaximum != false { - info = append(info, yaml.MapItem{"exclusiveMaximum", m.ExclusiveMaximum}) + info = append(info, yaml.MapItem{Key: "exclusiveMaximum", Value: m.ExclusiveMaximum}) } if m.Minimum != 0.0 { - info = append(info, yaml.MapItem{"minimum", m.Minimum}) + info = append(info, yaml.MapItem{Key: "minimum", Value: m.Minimum}) } if m.ExclusiveMinimum != false { - info = append(info, yaml.MapItem{"exclusiveMinimum", m.ExclusiveMinimum}) + info = append(info, yaml.MapItem{Key: "exclusiveMinimum", Value: m.ExclusiveMinimum}) } if m.MaxLength != 0 { - info = append(info, yaml.MapItem{"maxLength", m.MaxLength}) + info = append(info, yaml.MapItem{Key: "maxLength", Value: m.MaxLength}) } if m.MinLength != 0 { - info = append(info, yaml.MapItem{"minLength", m.MinLength}) + info = append(info, yaml.MapItem{Key: "minLength", Value: m.MinLength}) } if m.Pattern != "" { - info = append(info, yaml.MapItem{"pattern", m.Pattern}) + info = append(info, yaml.MapItem{Key: "pattern", Value: m.Pattern}) } if m.MaxItems != 0 { - info = append(info, yaml.MapItem{"maxItems", m.MaxItems}) + info = append(info, yaml.MapItem{Key: "maxItems", Value: m.MaxItems}) } if m.MinItems != 0 { - info = append(info, yaml.MapItem{"minItems", m.MinItems}) + info = append(info, yaml.MapItem{Key: "minItems", Value: m.MinItems}) } if m.UniqueItems != false { - info = append(info, yaml.MapItem{"uniqueItems", m.UniqueItems}) + info = append(info, yaml.MapItem{Key: "uniqueItems", Value: m.UniqueItems}) } if len(m.Enum) != 0 { items := make([]interface{}, 0) for _, item := range m.Enum { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"enum", items}) + info = append(info, yaml.MapItem{Key: "enum", Value: items}) } // &{Name:enum Type:Any StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.MultipleOf != 0.0 { - info = append(info, yaml.MapItem{"multipleOf", m.MultipleOf}) + info = append(info, yaml.MapItem{Key: "multipleOf", Value: m.MultipleOf}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -8186,13 +8186,13 @@ func (m *Paths) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} if m.Path != nil { for _, item := range m.Path { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:Path Type:NamedPathItem StringEnumValues:[] MapType:PathItem Repeated:true Pattern:^/ Implicit:true Description:} @@ -8203,66 +8203,66 @@ func (m *Paths) ToRawInfo() interface{} { func (m *PrimitivesItems) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Format != "" { - info = append(info, yaml.MapItem{"format", m.Format}) + info = append(info, yaml.MapItem{Key: "format", Value: m.Format}) } if m.Items != nil { - info = append(info, yaml.MapItem{"items", m.Items.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "items", Value: m.Items.ToRawInfo()}) } // &{Name:items Type:PrimitivesItems StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.CollectionFormat != "" { - info = append(info, yaml.MapItem{"collectionFormat", m.CollectionFormat}) + info = append(info, yaml.MapItem{Key: "collectionFormat", Value: m.CollectionFormat}) } if m.Default != nil { - info = append(info, yaml.MapItem{"default", m.Default.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "default", Value: m.Default.ToRawInfo()}) } // &{Name:default Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Maximum != 0.0 { - info = append(info, yaml.MapItem{"maximum", m.Maximum}) + info = append(info, yaml.MapItem{Key: "maximum", Value: m.Maximum}) } if m.ExclusiveMaximum != false { - info = append(info, yaml.MapItem{"exclusiveMaximum", m.ExclusiveMaximum}) + info = append(info, yaml.MapItem{Key: "exclusiveMaximum", Value: m.ExclusiveMaximum}) } if m.Minimum != 0.0 { - info = append(info, yaml.MapItem{"minimum", m.Minimum}) + info = append(info, yaml.MapItem{Key: "minimum", Value: m.Minimum}) } if m.ExclusiveMinimum != false { - info = append(info, yaml.MapItem{"exclusiveMinimum", m.ExclusiveMinimum}) + info = append(info, yaml.MapItem{Key: "exclusiveMinimum", Value: m.ExclusiveMinimum}) } if m.MaxLength != 0 { - info = append(info, yaml.MapItem{"maxLength", m.MaxLength}) + info = append(info, yaml.MapItem{Key: "maxLength", Value: m.MaxLength}) } if m.MinLength != 0 { - info = append(info, yaml.MapItem{"minLength", m.MinLength}) + info = append(info, yaml.MapItem{Key: "minLength", Value: m.MinLength}) } if m.Pattern != "" { - info = append(info, yaml.MapItem{"pattern", m.Pattern}) + info = append(info, yaml.MapItem{Key: "pattern", Value: m.Pattern}) } if m.MaxItems != 0 { - info = append(info, yaml.MapItem{"maxItems", m.MaxItems}) + info = append(info, yaml.MapItem{Key: "maxItems", Value: m.MaxItems}) } if m.MinItems != 0 { - info = append(info, yaml.MapItem{"minItems", m.MinItems}) + info = append(info, yaml.MapItem{Key: "minItems", Value: m.MinItems}) } if m.UniqueItems != false { - info = append(info, yaml.MapItem{"uniqueItems", m.UniqueItems}) + info = append(info, yaml.MapItem{Key: "uniqueItems", Value: m.UniqueItems}) } if len(m.Enum) != 0 { items := make([]interface{}, 0) for _, item := range m.Enum { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"enum", items}) + info = append(info, yaml.MapItem{Key: "enum", Value: items}) } // &{Name:enum Type:Any StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.MultipleOf != 0.0 { - info = append(info, yaml.MapItem{"multipleOf", m.MultipleOf}) + info = append(info, yaml.MapItem{Key: "multipleOf", Value: m.MultipleOf}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -8274,7 +8274,7 @@ func (m *Properties) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.AdditionalProperties != nil { for _, item := range m.AdditionalProperties { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:additionalProperties Type:NamedSchema StringEnumValues:[] MapType:Schema Repeated:true Pattern: Implicit:true Description:} @@ -8285,81 +8285,81 @@ func (m *Properties) ToRawInfo() interface{} { func (m *QueryParameterSubSchema) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Required != false { - info = append(info, yaml.MapItem{"required", m.Required}) + info = append(info, yaml.MapItem{Key: "required", Value: m.Required}) } if m.In != "" { - info = append(info, yaml.MapItem{"in", m.In}) + info = append(info, yaml.MapItem{Key: "in", Value: m.In}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.AllowEmptyValue != false { - info = append(info, yaml.MapItem{"allowEmptyValue", m.AllowEmptyValue}) + info = append(info, yaml.MapItem{Key: "allowEmptyValue", Value: m.AllowEmptyValue}) } if m.Type != "" { - info = append(info, yaml.MapItem{"type", m.Type}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type}) } if m.Format != "" { - info = append(info, yaml.MapItem{"format", m.Format}) + info = append(info, yaml.MapItem{Key: "format", Value: m.Format}) } if m.Items != nil { - info = append(info, yaml.MapItem{"items", m.Items.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "items", Value: m.Items.ToRawInfo()}) } // &{Name:items Type:PrimitivesItems StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.CollectionFormat != "" { - info = append(info, yaml.MapItem{"collectionFormat", m.CollectionFormat}) + info = append(info, yaml.MapItem{Key: "collectionFormat", Value: m.CollectionFormat}) } if m.Default != nil { - info = append(info, yaml.MapItem{"default", m.Default.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "default", Value: m.Default.ToRawInfo()}) } // &{Name:default Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Maximum != 0.0 { - info = append(info, yaml.MapItem{"maximum", m.Maximum}) + info = append(info, yaml.MapItem{Key: "maximum", Value: m.Maximum}) } if m.ExclusiveMaximum != false { - info = append(info, yaml.MapItem{"exclusiveMaximum", m.ExclusiveMaximum}) + info = append(info, yaml.MapItem{Key: "exclusiveMaximum", Value: m.ExclusiveMaximum}) } if m.Minimum != 0.0 { - info = append(info, yaml.MapItem{"minimum", m.Minimum}) + info = append(info, yaml.MapItem{Key: "minimum", Value: m.Minimum}) } if m.ExclusiveMinimum != false { - info = append(info, yaml.MapItem{"exclusiveMinimum", m.ExclusiveMinimum}) + info = append(info, yaml.MapItem{Key: "exclusiveMinimum", Value: m.ExclusiveMinimum}) } if m.MaxLength != 0 { - info = append(info, yaml.MapItem{"maxLength", m.MaxLength}) + info = append(info, yaml.MapItem{Key: "maxLength", Value: m.MaxLength}) } if m.MinLength != 0 { - info = append(info, yaml.MapItem{"minLength", m.MinLength}) + info = append(info, yaml.MapItem{Key: "minLength", Value: m.MinLength}) } if m.Pattern != "" { - info = append(info, yaml.MapItem{"pattern", m.Pattern}) + info = append(info, yaml.MapItem{Key: "pattern", Value: m.Pattern}) } if m.MaxItems != 0 { - info = append(info, yaml.MapItem{"maxItems", m.MaxItems}) + info = append(info, yaml.MapItem{Key: "maxItems", Value: m.MaxItems}) } if m.MinItems != 0 { - info = append(info, yaml.MapItem{"minItems", m.MinItems}) + info = append(info, yaml.MapItem{Key: "minItems", Value: m.MinItems}) } if m.UniqueItems != false { - info = append(info, yaml.MapItem{"uniqueItems", m.UniqueItems}) + info = append(info, yaml.MapItem{Key: "uniqueItems", Value: m.UniqueItems}) } if len(m.Enum) != 0 { items := make([]interface{}, 0) for _, item := range m.Enum { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"enum", items}) + info = append(info, yaml.MapItem{Key: "enum", Value: items}) } // &{Name:enum Type:Any StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.MultipleOf != 0.0 { - info = append(info, yaml.MapItem{"multipleOf", m.MultipleOf}) + info = append(info, yaml.MapItem{Key: "multipleOf", Value: m.MultipleOf}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -8370,23 +8370,23 @@ func (m *QueryParameterSubSchema) ToRawInfo() interface{} { func (m *Response) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.Schema != nil { - info = append(info, yaml.MapItem{"schema", m.Schema.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "schema", Value: m.Schema.ToRawInfo()}) } // &{Name:schema Type:SchemaItem StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Headers != nil { - info = append(info, yaml.MapItem{"headers", m.Headers.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "headers", Value: m.Headers.ToRawInfo()}) } // &{Name:headers Type:Headers StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Examples != nil { - info = append(info, yaml.MapItem{"examples", m.Examples.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "examples", Value: m.Examples.ToRawInfo()}) } // &{Name:examples Type:Examples StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -8398,7 +8398,7 @@ func (m *ResponseDefinitions) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.AdditionalProperties != nil { for _, item := range m.AdditionalProperties { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:additionalProperties Type:NamedResponse StringEnumValues:[] MapType:Response Repeated:true Pattern: Implicit:true Description:} @@ -8427,13 +8427,13 @@ func (m *Responses) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.ResponseCode != nil { for _, item := range m.ResponseCode { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:ResponseCode Type:NamedResponseValue StringEnumValues:[] MapType:ResponseValue Repeated:true Pattern:^([0-9]{3})$|^(default)$ Implicit:true Description:} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -8444,80 +8444,80 @@ func (m *Responses) ToRawInfo() interface{} { func (m *Schema) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.XRef != "" { - info = append(info, yaml.MapItem{"$ref", m.XRef}) + info = append(info, yaml.MapItem{Key: "$ref", Value: m.XRef}) } if m.Format != "" { - info = append(info, yaml.MapItem{"format", m.Format}) + info = append(info, yaml.MapItem{Key: "format", Value: m.Format}) } if m.Title != "" { - info = append(info, yaml.MapItem{"title", m.Title}) + info = append(info, yaml.MapItem{Key: "title", Value: m.Title}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.Default != nil { - info = append(info, yaml.MapItem{"default", m.Default.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "default", Value: m.Default.ToRawInfo()}) } // &{Name:default Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.MultipleOf != 0.0 { - info = append(info, yaml.MapItem{"multipleOf", m.MultipleOf}) + info = append(info, yaml.MapItem{Key: "multipleOf", Value: m.MultipleOf}) } if m.Maximum != 0.0 { - info = append(info, yaml.MapItem{"maximum", m.Maximum}) + info = append(info, yaml.MapItem{Key: "maximum", Value: m.Maximum}) } if m.ExclusiveMaximum != false { - info = append(info, yaml.MapItem{"exclusiveMaximum", m.ExclusiveMaximum}) + info = append(info, yaml.MapItem{Key: "exclusiveMaximum", Value: m.ExclusiveMaximum}) } if m.Minimum != 0.0 { - info = append(info, yaml.MapItem{"minimum", m.Minimum}) + info = append(info, yaml.MapItem{Key: "minimum", Value: m.Minimum}) } if m.ExclusiveMinimum != false { - info = append(info, yaml.MapItem{"exclusiveMinimum", m.ExclusiveMinimum}) + info = append(info, yaml.MapItem{Key: "exclusiveMinimum", Value: m.ExclusiveMinimum}) } if m.MaxLength != 0 { - info = append(info, yaml.MapItem{"maxLength", m.MaxLength}) + info = append(info, yaml.MapItem{Key: "maxLength", Value: m.MaxLength}) } if m.MinLength != 0 { - info = append(info, yaml.MapItem{"minLength", m.MinLength}) + info = append(info, yaml.MapItem{Key: "minLength", Value: m.MinLength}) } if m.Pattern != "" { - info = append(info, yaml.MapItem{"pattern", m.Pattern}) + info = append(info, yaml.MapItem{Key: "pattern", Value: m.Pattern}) } if m.MaxItems != 0 { - info = append(info, yaml.MapItem{"maxItems", m.MaxItems}) + info = append(info, yaml.MapItem{Key: "maxItems", Value: m.MaxItems}) } if m.MinItems != 0 { - info = append(info, yaml.MapItem{"minItems", m.MinItems}) + info = append(info, yaml.MapItem{Key: "minItems", Value: m.MinItems}) } if m.UniqueItems != false { - info = append(info, yaml.MapItem{"uniqueItems", m.UniqueItems}) + info = append(info, yaml.MapItem{Key: "uniqueItems", Value: m.UniqueItems}) } if m.MaxProperties != 0 { - info = append(info, yaml.MapItem{"maxProperties", m.MaxProperties}) + info = append(info, yaml.MapItem{Key: "maxProperties", Value: m.MaxProperties}) } if m.MinProperties != 0 { - info = append(info, yaml.MapItem{"minProperties", m.MinProperties}) + info = append(info, yaml.MapItem{Key: "minProperties", Value: m.MinProperties}) } if len(m.Required) != 0 { - info = append(info, yaml.MapItem{"required", m.Required}) + info = append(info, yaml.MapItem{Key: "required", Value: m.Required}) } if len(m.Enum) != 0 { items := make([]interface{}, 0) for _, item := range m.Enum { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"enum", items}) + info = append(info, yaml.MapItem{Key: "enum", Value: items}) } // &{Name:enum Type:Any StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.AdditionalProperties != nil { - info = append(info, yaml.MapItem{"additionalProperties", m.AdditionalProperties.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "additionalProperties", Value: m.AdditionalProperties.ToRawInfo()}) } // &{Name:additionalProperties Type:AdditionalPropertiesItem StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Type != nil { if len(m.Type.Value) == 1 { - info = append(info, yaml.MapItem{"type", m.Type.Value[0]}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type.Value[0]}) } else { - info = append(info, yaml.MapItem{"type", m.Type.Value}) + info = append(info, yaml.MapItem{Key: "type", Value: m.Type.Value}) } } // &{Name:type Type:TypeItem StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} @@ -8526,7 +8526,7 @@ func (m *Schema) ToRawInfo() interface{} { for _, item := range m.Items.Schema { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"items", items[0]}) + info = append(info, yaml.MapItem{Key: "items", Value: items[0]}) } // &{Name:items Type:ItemsItem StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if len(m.AllOf) != 0 { @@ -8534,34 +8534,34 @@ func (m *Schema) ToRawInfo() interface{} { for _, item := range m.AllOf { items = append(items, item.ToRawInfo()) } - info = append(info, yaml.MapItem{"allOf", items}) + info = append(info, yaml.MapItem{Key: "allOf", Value: items}) } // &{Name:allOf Type:Schema StringEnumValues:[] MapType: Repeated:true Pattern: Implicit:false Description:} if m.Properties != nil { - info = append(info, yaml.MapItem{"properties", m.Properties.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "properties", Value: m.Properties.ToRawInfo()}) } // &{Name:properties Type:Properties StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Discriminator != "" { - info = append(info, yaml.MapItem{"discriminator", m.Discriminator}) + info = append(info, yaml.MapItem{Key: "discriminator", Value: m.Discriminator}) } if m.ReadOnly != false { - info = append(info, yaml.MapItem{"readOnly", m.ReadOnly}) + info = append(info, yaml.MapItem{Key: "readOnly", Value: m.ReadOnly}) } if m.Xml != nil { - info = append(info, yaml.MapItem{"xml", m.Xml.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "xml", Value: m.Xml.ToRawInfo()}) } // &{Name:xml Type:Xml StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.ExternalDocs != nil { - info = append(info, yaml.MapItem{"externalDocs", m.ExternalDocs.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "externalDocs", Value: m.ExternalDocs.ToRawInfo()}) } // &{Name:externalDocs Type:ExternalDocs StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.Example != nil { - info = append(info, yaml.MapItem{"example", m.Example.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "example", Value: m.Example.ToRawInfo()}) } // &{Name:example Type:Any StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -8590,7 +8590,7 @@ func (m *SecurityDefinitions) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.AdditionalProperties != nil { for _, item := range m.AdditionalProperties { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:additionalProperties Type:NamedSecurityDefinitionsItem StringEnumValues:[] MapType:SecurityDefinitionsItem Repeated:true Pattern: Implicit:true Description:} @@ -8639,7 +8639,7 @@ func (m *SecurityRequirement) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.AdditionalProperties != nil { for _, item := range m.AdditionalProperties { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:additionalProperties Type:NamedStringArray StringEnumValues:[] MapType:StringArray Repeated:true Pattern: Implicit:true Description:} @@ -8655,18 +8655,18 @@ func (m *StringArray) ToRawInfo() interface{} { func (m *Tag) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.Description != "" { - info = append(info, yaml.MapItem{"description", m.Description}) + info = append(info, yaml.MapItem{Key: "description", Value: m.Description}) } if m.ExternalDocs != nil { - info = append(info, yaml.MapItem{"externalDocs", m.ExternalDocs.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: "externalDocs", Value: m.ExternalDocs.ToRawInfo()}) } // &{Name:externalDocs Type:ExternalDocs StringEnumValues:[] MapType: Repeated:false Pattern: Implicit:false Description:} if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} @@ -8677,7 +8677,7 @@ func (m *Tag) ToRawInfo() interface{} { func (m *TypeItem) ToRawInfo() interface{} { info := yaml.MapSlice{} if len(m.Value) != 0 { - info = append(info, yaml.MapItem{"value", m.Value}) + info = append(info, yaml.MapItem{Key: "value", Value: m.Value}) } return info } @@ -8687,7 +8687,7 @@ func (m *VendorExtension) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.AdditionalProperties != nil { for _, item := range m.AdditionalProperties { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:additionalProperties Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern: Implicit:true Description:} @@ -8698,23 +8698,23 @@ func (m *VendorExtension) ToRawInfo() interface{} { func (m *Xml) ToRawInfo() interface{} { info := yaml.MapSlice{} if m.Name != "" { - info = append(info, yaml.MapItem{"name", m.Name}) + info = append(info, yaml.MapItem{Key: "name", Value: m.Name}) } if m.Namespace != "" { - info = append(info, yaml.MapItem{"namespace", m.Namespace}) + info = append(info, yaml.MapItem{Key: "namespace", Value: m.Namespace}) } if m.Prefix != "" { - info = append(info, yaml.MapItem{"prefix", m.Prefix}) + info = append(info, yaml.MapItem{Key: "prefix", Value: m.Prefix}) } if m.Attribute != false { - info = append(info, yaml.MapItem{"attribute", m.Attribute}) + info = append(info, yaml.MapItem{Key: "attribute", Value: m.Attribute}) } if m.Wrapped != false { - info = append(info, yaml.MapItem{"wrapped", m.Wrapped}) + info = append(info, yaml.MapItem{Key: "wrapped", Value: m.Wrapped}) } if m.VendorExtension != nil { for _, item := range m.VendorExtension { - info = append(info, yaml.MapItem{item.Name, item.Value.ToRawInfo()}) + info = append(info, yaml.MapItem{Key: item.Name, Value: item.Value.ToRawInfo()}) } } // &{Name:VendorExtension Type:NamedAny StringEnumValues:[] MapType:Any Repeated:true Pattern:^x- Implicit:true Description:} diff --git a/vendor/github.com/googleapis/gnostic/OpenAPIv2/OpenAPIv2.pb.go b/vendor/github.com/googleapis/gnostic/OpenAPIv2/OpenAPIv2.pb.go index 37da7df256..a030fa6765 100644 --- a/vendor/github.com/googleapis/gnostic/OpenAPIv2/OpenAPIv2.pb.go +++ b/vendor/github.com/googleapis/gnostic/OpenAPIv2/OpenAPIv2.pb.go @@ -1,6 +1,5 @@ -// Code generated by protoc-gen-go. +// Code generated by protoc-gen-go. DO NOT EDIT. // source: OpenAPIv2/OpenAPIv2.proto -// DO NOT EDIT! /* Package openapi_v2 is a generated protocol buffer package. @@ -4257,7 +4256,7 @@ func init() { proto.RegisterFile("OpenAPIv2/OpenAPIv2.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ // 3129 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xec, 0x3b, 0x4b, 0x73, 0x1c, 0x57, + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x3b, 0x4b, 0x73, 0x1c, 0x57, 0xd5, 0xf3, 0x7e, 0x1c, 0x69, 0x46, 0xa3, 0x96, 0x2c, 0xb7, 0x24, 0xc7, 0x71, 0xe4, 0x3c, 0x6c, 0xe7, 0xb3, 0x9c, 0x4f, 0x29, 0x48, 0x05, 0x2a, 0x05, 0xf2, 0xab, 0xc6, 0xc4, 0x44, 0x4a, 0xcb, 0x0e, 0x09, 0x04, 0xba, 0xae, 0x66, 0xee, 0x48, 0x9d, 0x74, 0xf7, 0x6d, 0x77, 0xf7, 0xc8, 0x1a, diff --git a/vendor/github.com/googleapis/gnostic/README.md b/vendor/github.com/googleapis/gnostic/README.md index d350f3f013..97de63590c 100644 --- a/vendor/github.com/googleapis/gnostic/README.md +++ b/vendor/github.com/googleapis/gnostic/README.md @@ -61,8 +61,14 @@ buffers. Pre-generated versions of these files are in the OpenAPIv2 directory. 3. [Optional] Generate Protocol Buffer support code. A pre-generated version of this file is checked into the OpenAPIv2 directory. -This step requires a local installation of protoc, the Protocol Buffer Compiler. +This step requires a local installation of protoc, the Protocol Buffer Compiler, +and the Go protoc plugin. You can get protoc [here](https://github.com/google/protobuf). +You can install the plugin with this command: + + go get -u github.com/golang/protobuf/protoc-gen-go + +Then use the following to recompile the Gnostic Protocol Buffer models: ./COMPILE-PROTOS.sh @@ -74,7 +80,7 @@ You can get protoc [here](https://github.com/google/protobuf). 5. Run **gnostic**. This will create a file in the current directory named "petstore.pb" that contains a binary Protocol Buffer description of a sample API. - gnostic --pb-out=. examples/petstore.json + gnostic --pb-out=. examples/v2.0/json/petstore.json 6. You can also compile files that you specify with a URL. Here's another way to compile the previous example. This time we're creating "petstore.text", which contains a textual representation of the @@ -92,7 +98,7 @@ that reports some basic information about an API. The "-" causes the plugin to write its output to stdout. go install github.com/googleapis/gnostic/plugins/gnostic-go-sample - gnostic examples/petstore.json --go-sample-out=- + gnostic examples/v2.0/json/petstore.json --go-sample-out=- ## Copyright diff --git a/vendor/github.com/googleapis/gnostic/compiler/reader.go b/vendor/github.com/googleapis/gnostic/compiler/reader.go index 2d4b3303db..c954a2d9b2 100644 --- a/vendor/github.com/googleapis/gnostic/compiler/reader.go +++ b/vendor/github.com/googleapis/gnostic/compiler/reader.go @@ -110,7 +110,9 @@ func ReadInfoFromBytes(filename string, bytes []byte) (interface{}, error) { if err != nil { return nil, err } - infoCache[filename] = info + if len(filename) > 0 { + infoCache[filename] = info + } return info, nil } diff --git a/vendor/github.com/googleapis/gnostic/extensions/extension.pb.go b/vendor/github.com/googleapis/gnostic/extensions/extension.pb.go index 7c6b914967..749ff78416 100644 --- a/vendor/github.com/googleapis/gnostic/extensions/extension.pb.go +++ b/vendor/github.com/googleapis/gnostic/extensions/extension.pb.go @@ -1,6 +1,5 @@ -// Code generated by protoc-gen-go. +// Code generated by protoc-gen-go. DO NOT EDIT. // source: extension.proto -// DO NOT EDIT! /* Package openapiextension_v1 is a generated protocol buffer package. @@ -78,7 +77,7 @@ func (m *Version) GetSuffix() string { // An encoded Request is written to the ExtensionHandler's stdin. type ExtensionHandlerRequest struct { // The OpenAPI descriptions that were explicitly listed on the command line. - // The specifications will appear in the order they are specified to openapic. + // The specifications will appear in the order they are specified to gnostic. Wrapper *Wrapper `protobuf:"bytes,1,opt,name=wrapper" json:"wrapper,omitempty"` // The version number of openapi compiler. CompilerVersion *Version `protobuf:"bytes,3,opt,name=compiler_version,json=compilerVersion" json:"compiler_version,omitempty"` @@ -192,28 +191,28 @@ func init() { func init() { proto.RegisterFile("extension.proto", fileDescriptor0) } var fileDescriptor0 = []byte{ - // 355 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0x4d, 0x4b, 0xf3, 0x40, - 0x1c, 0xc4, 0x49, 0xdf, 0xf2, 0x64, 0x1f, 0xb4, 0xb2, 0x16, 0x8d, 0xe2, 0xa1, 0x04, 0x84, 0x22, - 0xb8, 0xa5, 0x0a, 0xde, 0x5b, 0x28, 0xea, 0xc5, 0x96, 0x3d, 0xd4, 0x9b, 0x65, 0x9b, 0xfe, 0xdb, - 0x46, 0x92, 0xdd, 0x75, 0xf3, 0x62, 0xfb, 0x55, 0x3c, 0xfa, 0x49, 0x25, 0xbb, 0xd9, 0x7a, 0x50, - 0x6f, 0x99, 0x1f, 0x93, 0xfc, 0x67, 0x26, 0xa8, 0x0d, 0xdb, 0x0c, 0x78, 0x1a, 0x09, 0x4e, 0xa4, - 0x12, 0x99, 0xc0, 0xc7, 0x42, 0x02, 0x67, 0x32, 0xfa, 0xe6, 0xc5, 0xe0, 0xfc, 0x6c, 0x2d, 0xc4, - 0x3a, 0x86, 0xbe, 0xb6, 0x2c, 0xf2, 0x55, 0x9f, 0xf1, 0x9d, 0xf1, 0x07, 0x21, 0x72, 0x67, 0xa0, - 0x4a, 0x23, 0xee, 0xa0, 0x66, 0xc2, 0x5e, 0x85, 0xf2, 0x9d, 0xae, 0xd3, 0x6b, 0x52, 0x23, 0x34, - 0x8d, 0xb8, 0x50, 0x7e, 0xad, 0xa2, 0xa5, 0x28, 0xa9, 0x64, 0x59, 0xb8, 0xf1, 0xeb, 0x86, 0x6a, - 0x81, 0x4f, 0x50, 0x2b, 0xcd, 0x57, 0xab, 0x68, 0xeb, 0x37, 0xba, 0x4e, 0xcf, 0xa3, 0x95, 0x0a, - 0x3e, 0x1c, 0x74, 0x3a, 0xb6, 0x81, 0x1e, 0x18, 0x5f, 0xc6, 0xa0, 0x28, 0xbc, 0xe5, 0x90, 0x66, - 0xf8, 0x0e, 0xb9, 0xef, 0x8a, 0x49, 0x09, 0xe6, 0xee, 0xff, 0x9b, 0x0b, 0xf2, 0x4b, 0x05, 0xf2, - 0x6c, 0x3c, 0xd4, 0x9a, 0xf1, 0x3d, 0x3a, 0x0a, 0x45, 0x22, 0xa3, 0x18, 0xd4, 0xbc, 0x30, 0x0d, - 0x74, 0x98, 0xbf, 0x3e, 0x50, 0xb5, 0xa4, 0x6d, 0xfb, 0x56, 0x05, 0x82, 0x02, 0xf9, 0x3f, 0xb3, - 0xa5, 0x52, 0xf0, 0x14, 0xb0, 0x8f, 0xdc, 0x8d, 0x46, 0x4b, 0x1d, 0xee, 0x1f, 0xb5, 0xb2, 0x1c, - 0x00, 0x94, 0xd2, 0xb3, 0xd4, 0x7b, 0x1e, 0x35, 0x02, 0x5f, 0xa1, 0x66, 0xc1, 0xe2, 0x1c, 0xaa, - 0x24, 0x1d, 0x62, 0x86, 0x27, 0x76, 0x78, 0x32, 0xe4, 0x3b, 0x6a, 0x2c, 0xc1, 0x0b, 0x72, 0xab, - 0x52, 0xe5, 0x19, 0x5b, 0xc1, 0xd1, 0xc3, 0x59, 0x89, 0x2f, 0xd1, 0xe1, 0xbe, 0xc5, 0x9c, 0xb3, - 0x04, 0xf4, 0x6f, 0xf0, 0xe8, 0xc1, 0x9e, 0x3e, 0xb1, 0x04, 0x30, 0x46, 0x8d, 0x1d, 0x4b, 0x62, - 0x7d, 0xd6, 0xa3, 0xfa, 0x79, 0x74, 0x8d, 0xda, 0x42, 0xad, 0xed, 0x16, 0x21, 0x29, 0x06, 0x23, - 0x3c, 0x91, 0xc0, 0x87, 0xd3, 0xc7, 0x7d, 0xdf, 0xd9, 0x60, 0xea, 0x7c, 0xd6, 0xea, 0x93, 0xe1, - 0x78, 0xd1, 0xd2, 0x19, 0x6f, 0xbf, 0x02, 0x00, 0x00, 0xff, 0xff, 0xfc, 0x56, 0x40, 0x4d, 0x52, - 0x02, 0x00, 0x00, + // 357 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x91, 0x4d, 0x4b, 0xc3, 0x40, + 0x18, 0x84, 0x49, 0xbf, 0x62, 0x56, 0x6c, 0x65, 0x2d, 0x1a, 0xc5, 0x43, 0x09, 0x08, 0x45, 0x64, + 0x4b, 0x15, 0xbc, 0xb7, 0x50, 0xd4, 0x8b, 0x2d, 0x7b, 0xa8, 0x37, 0xcb, 0x36, 0x7d, 0x9b, 0x46, + 0x92, 0xdd, 0x75, 0xf3, 0x61, 0xfb, 0x57, 0x3c, 0xfa, 0x4b, 0x25, 0xbb, 0x49, 0x3d, 0xa8, 0xb7, + 0xcc, 0xc3, 0x24, 0xef, 0xcc, 0x04, 0x75, 0x60, 0x9b, 0x02, 0x4f, 0x42, 0xc1, 0x89, 0x54, 0x22, + 0x15, 0xf8, 0x44, 0x48, 0xe0, 0x4c, 0x86, 0x3f, 0x3c, 0x1f, 0x5e, 0x9c, 0x07, 0x42, 0x04, 0x11, + 0x0c, 0xb4, 0x65, 0x99, 0xad, 0x07, 0x8c, 0xef, 0x8c, 0xdf, 0xf3, 0x91, 0x3d, 0x07, 0x55, 0x18, + 0x71, 0x17, 0x35, 0x63, 0xf6, 0x26, 0x94, 0x6b, 0xf5, 0xac, 0x7e, 0x93, 0x1a, 0xa1, 0x69, 0xc8, + 0x85, 0x72, 0x6b, 0x25, 0x2d, 0x44, 0x41, 0x25, 0x4b, 0xfd, 0x8d, 0x5b, 0x37, 0x54, 0x0b, 0x7c, + 0x8a, 0x5a, 0x49, 0xb6, 0x5e, 0x87, 0x5b, 0xb7, 0xd1, 0xb3, 0xfa, 0x0e, 0x2d, 0x95, 0xf7, 0x69, + 0xa1, 0xb3, 0x49, 0x15, 0xe8, 0x91, 0xf1, 0x55, 0x04, 0x8a, 0xc2, 0x7b, 0x06, 0x49, 0x8a, 0xef, + 0x91, 0xfd, 0xa1, 0x98, 0x94, 0x60, 0xee, 0x1e, 0xde, 0x5e, 0x92, 0x3f, 0x2a, 0x90, 0x17, 0xe3, + 0xa1, 0x95, 0x19, 0x3f, 0xa0, 0x63, 0x5f, 0xc4, 0x32, 0x8c, 0x40, 0x2d, 0x72, 0xd3, 0x40, 0x87, + 0xf9, 0xef, 0x03, 0x65, 0x4b, 0xda, 0xa9, 0xde, 0x2a, 0x81, 0x97, 0x23, 0xf7, 0x77, 0xb6, 0x44, + 0x0a, 0x9e, 0x00, 0x76, 0x91, 0xbd, 0xd1, 0x68, 0xa5, 0xc3, 0x1d, 0xd0, 0x4a, 0x16, 0x03, 0x80, + 0x52, 0x7a, 0x96, 0x7a, 0xdf, 0xa1, 0x46, 0xe0, 0x6b, 0xd4, 0xcc, 0x59, 0x94, 0x41, 0x99, 0xa4, + 0x4b, 0xcc, 0xf0, 0xa4, 0x1a, 0x9e, 0x8c, 0xf8, 0x8e, 0x1a, 0x8b, 0xf7, 0x8a, 0xec, 0xb2, 0x54, + 0x71, 0xa6, 0xaa, 0x60, 0xe9, 0xe1, 0x2a, 0x89, 0xaf, 0x50, 0x7b, 0xdf, 0x62, 0xc1, 0x59, 0x0c, + 0xfa, 0x37, 0x38, 0xf4, 0x68, 0x4f, 0x9f, 0x59, 0x0c, 0x18, 0xa3, 0xc6, 0x8e, 0xc5, 0x91, 0x3e, + 0xeb, 0x50, 0xfd, 0x3c, 0xbe, 0x41, 0x6d, 0xa1, 0x02, 0x12, 0x70, 0x91, 0xa4, 0xa1, 0x4f, 0xf2, + 0xe1, 0x18, 0x4f, 0x25, 0xf0, 0xd1, 0xec, 0x69, 0x5f, 0x77, 0x3e, 0x9c, 0x59, 0x5f, 0xb5, 0xfa, + 0x74, 0x34, 0x59, 0xb6, 0x74, 0xc4, 0xbb, 0xef, 0x00, 0x00, 0x00, 0xff, 0xff, 0x84, 0x5c, 0x6b, + 0x80, 0x51, 0x02, 0x00, 0x00, } diff --git a/vendor/github.com/googleapis/gnostic/extensions/extension.proto b/vendor/github.com/googleapis/gnostic/extensions/extension.proto index 806760a132..04856f913b 100644 --- a/vendor/github.com/googleapis/gnostic/extensions/extension.proto +++ b/vendor/github.com/googleapis/gnostic/extensions/extension.proto @@ -29,7 +29,7 @@ option java_multiple_files = true; option java_outer_classname = "OpenAPIExtensionV1"; // The Java package name must be proto package name with proper prefix. -option java_package = "org.openapic.v1"; +option java_package = "org.gnostic.v1"; // A reasonable prefix for the Objective-C symbols generated from the package. // It should at a minimum be 3 characters long, all uppercase, and convention @@ -53,7 +53,7 @@ message Version { message ExtensionHandlerRequest { // The OpenAPI descriptions that were explicitly listed on the command line. - // The specifications will appear in the order they are specified to openapic. + // The specifications will appear in the order they are specified to gnostic. Wrapper wrapper = 1; // The version number of openapi compiler. diff --git a/vendor/github.com/googleapis/gnostic/gnostic.go b/vendor/github.com/googleapis/gnostic/gnostic.go index 80e050503c..960041521d 100644 --- a/vendor/github.com/googleapis/gnostic/gnostic.go +++ b/vendor/github.com/googleapis/gnostic/gnostic.go @@ -41,6 +41,7 @@ import ( "path/filepath" "regexp" "strings" + "time" "github.com/golang/protobuf/proto" "github.com/googleapis/gnostic/OpenAPIv2" @@ -92,7 +93,7 @@ type pluginCall struct { } // Invokes a plugin. -func (p *pluginCall) perform(document proto.Message, sourceFormat int, sourceName string) error { +func (p *pluginCall) perform(document proto.Message, sourceFormat int, sourceName string, timePlugins bool) ([]*plugins.Message, error) { if p.Name != "" { request := &plugins.Request{} @@ -112,7 +113,7 @@ func (p *pluginCall) perform(document proto.Message, sourceFormat int, sourceNam // invocationRegex := regexp.MustCompile(`^([\w-_\/\.]+=[\w-_\/\.]+(,[\w-_\/\.]+=[\w-_\/\.]+)*:)?[^,:=]+$`) if !invocationRegex.Match([]byte(p.Invocation)) { - return fmt.Errorf("Invalid invocation of %s: %s", executableName, invocation) + return nil, fmt.Errorf("Invalid invocation of %s: %s", executableName, invocation) } invocationParts := strings.Split(p.Invocation, ":") @@ -145,11 +146,21 @@ func (p *pluginCall) perform(document proto.Message, sourceFormat int, sourceNam request.SourceName = sourceName switch sourceFormat { case SourceFormatOpenAPI2: - request.Openapi2 = document.(*openapi_v2.Document) - request.Surface, _ = surface.NewModelFromOpenAPI2(request.Openapi2) + request.AddModel("openapi.v2.Document", document) + // include experimental API surface model + surfaceModel, err := surface.NewModelFromOpenAPI2(document.(*openapi_v2.Document)) + if err == nil { + request.AddModel("surface.v1.Model", surfaceModel) + } case SourceFormatOpenAPI3: - request.Openapi3 = document.(*openapi_v3.Document) - request.Surface, _ = surface.NewModelFromOpenAPI3(request.Openapi3) + request.AddModel("openapi.v3.Document", document) + // include experimental API surface model + surfaceModel, err := surface.NewModelFromOpenAPI3(document.(*openapi_v3.Document)) + if err == nil { + request.AddModel("surface.v1.Model", surfaceModel) + } + case SourceFormatDiscovery: + request.AddModel("discovery.v1.Document", document) default: } @@ -158,19 +169,27 @@ func (p *pluginCall) perform(document proto.Message, sourceFormat int, sourceNam cmd := exec.Command(executableName, "-plugin") cmd.Stdin = bytes.NewReader(requestBytes) cmd.Stderr = os.Stderr + pluginStartTime := time.Now() output, err := cmd.Output() + pluginElapsedTime := time.Since(pluginStartTime) + if timePlugins { + fmt.Printf("> %s (%s)\n", executableName, pluginElapsedTime) + } if err != nil { - return err + return nil, err } response := &plugins.Response{} err = proto.Unmarshal(output, response) if err != nil { - return err + // Gnostic expects plugins to only write the + // response message to stdout. Be sure that + // any logging messages are written to stderr only. + return nil, errors.New("Invalid plugin response (plugins must write log messages to stderr, not stdout).") } - plugins.HandleResponse(response, outputLocation) + return response.Messages, nil } - return nil + return nil, nil } func isFile(path string) bool { @@ -233,10 +252,12 @@ type Gnostic struct { yamlOutputPath string jsonOutputPath string errorOutputPath string + messageOutputPath string resolveReferences bool pluginCalls []*pluginCall extensionHandlers []compiler.ExtensionHandler sourceFormat int + timePlugins bool } // Initialize a structure to store global application state. @@ -244,20 +265,27 @@ func newGnostic() *Gnostic { g := &Gnostic{} // Option fields initialize to their default values. g.usage = ` -Usage: gnostic OPENAPI_SOURCE [OPTIONS] - OPENAPI_SOURCE is the filename or URL of an OpenAPI description to read. +Usage: gnostic SOURCE [OPTIONS] + SOURCE is the filename or URL of an API description. Options: --pb-out=PATH Write a binary proto to the specified location. --text-out=PATH Write a text proto to the specified location. --json-out=PATH Write a json API description to the specified location. --yaml-out=PATH Write a yaml API description to the specified location. --errors-out=PATH Write compilation errors to the specified location. - --PLUGIN-out=PATH Run the plugin named gnostic_PLUGIN and write results + --messages-out=PATH Write messages generated by plugins to the specified + location. Messages from all plugin invocations are + written to a single common file. + --PLUGIN-out=PATH Run the plugin named gnostic-PLUGIN and write results to the specified location. + --PLUGIN Run the plugin named gnostic-PLUGIN but don't write any + results. Used for plugins that return messages only. + PLUGIN must not match any other gnostic option. --x-EXTENSION Use the extension named gnostic-x-EXTENSION to process OpenAPI specification extensions. --resolve-refs Explicitly resolve $ref references. This could have problems with recursive definitions. + --time-plugins Report plugin runtimes. ` // Initialize internal structures. g.pluginCalls = make([]*pluginCall, 0) @@ -292,6 +320,8 @@ func (g *Gnostic) readOptions() { g.yamlOutputPath = invocation case "errors": g.errorOutputPath = invocation + case "messages": + g.messageOutputPath = invocation default: p := &pluginCall{Name: pluginName, Invocation: invocation} g.pluginCalls = append(g.pluginCalls, p) @@ -302,6 +332,13 @@ func (g *Gnostic) readOptions() { g.extensionHandlers = append(g.extensionHandlers, extensionHandler) } else if arg == "--resolve-refs" { g.resolveReferences = true + } else if arg == "--time-plugins" { + g.timePlugins = true + } else if arg[0] == '-' && arg[1] == '-' { + // try letting the option specify a plugin with no output files (or unwanted output files) + // this is useful for calling plugins like linters that only return messages + p := &pluginCall{Name: arg[2:len(arg)], Invocation: "!"} + g.pluginCalls = append(g.pluginCalls, p) } else if arg[0] == '-' { fmt.Fprintf(os.Stderr, "Unknown option: %s.\n%s\n", arg, g.usage) os.Exit(-1) @@ -467,6 +504,17 @@ func (g *Gnostic) writeJSONYAMLOutput(message proto.Message) { } } +// Write messages. +func (g *Gnostic) writeMessagesOutput(message proto.Message) { + protoBytes, err := proto.Marshal(message) + if err != nil { + writeFile(g.messageOutputPath, g.errorBytes(err), g.sourceName, "errors") + defer os.Exit(-1) + } else { + writeFile(g.messageOutputPath, protoBytes, g.sourceName, "messages.pb") + } +} + // Perform all actions specified in the command-line options. func (g *Gnostic) performActions(message proto.Message) (err error) { // Optionally resolve internal references. @@ -490,17 +538,29 @@ func (g *Gnostic) performActions(message proto.Message) (err error) { if g.textOutputPath != "" { g.writeTextOutput(message) } - // Optionaly write document in yaml and/or json formats. + // Optionally write document in yaml and/or json formats. if g.yamlOutputPath != "" || g.jsonOutputPath != "" { g.writeJSONYAMLOutput(message) } // Call all specified plugins. + messages := make([]*plugins.Message, 0) for _, p := range g.pluginCalls { - err := p.perform(message, g.sourceFormat, g.sourceName) + pluginMessages, err := p.perform(message, g.sourceFormat, g.sourceName, g.timePlugins) if err != nil { writeFile(g.errorOutputPath, g.errorBytes(err), g.sourceName, "errors") defer os.Exit(-1) // run all plugins, even when some have errors } + messages = append(messages, pluginMessages...) + } + if g.messageOutputPath != "" { + g.writeMessagesOutput(&plugins.Messages{Messages: messages}) + } else { + // Print any messages from the plugins + if len(messages) > 0 { + for _, message := range messages { + fmt.Printf("%+v\n", message) + } + } } return nil } diff --git a/vendor/github.com/googleapis/gnostic/gnostic_test.go b/vendor/github.com/googleapis/gnostic/gnostic_test.go deleted file mode 100644 index 22eaee8275..0000000000 --- a/vendor/github.com/googleapis/gnostic/gnostic_test.go +++ /dev/null @@ -1,453 +0,0 @@ -package main - -import ( - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" -) - -func testCompiler(t *testing.T, inputFile string, referenceFile string, expectErrors bool) { - textFile := strings.Replace(filepath.Base(inputFile), filepath.Ext(inputFile), ".text", 1) - errorsFile := strings.Replace(filepath.Base(inputFile), filepath.Ext(inputFile), ".errors", 1) - // remove any preexisting output files - os.Remove(textFile) - os.Remove(errorsFile) - // run the compiler - var err error - var cmd = exec.Command( - "gnostic", - inputFile, - "--text-out=.", - "--errors-out=.", - "--resolve-refs") - //t.Log(cmd.Args) - err = cmd.Run() - if err != nil && !expectErrors { - t.Logf("Compile failed: %+v", err) - t.FailNow() - } - // verify the output against a reference - var outputFile string - if expectErrors { - outputFile = errorsFile - } else { - outputFile = textFile - } - err = exec.Command("diff", outputFile, referenceFile).Run() - if err != nil { - t.Logf("Diff failed: %+v", err) - t.FailNow() - } else { - // if the test succeeded, clean up - os.Remove(textFile) - os.Remove(errorsFile) - } -} - -func testNormal(t *testing.T, inputFile string, referenceFile string) { - testCompiler(t, inputFile, referenceFile, false) -} - -func testErrors(t *testing.T, inputFile string, referenceFile string) { - testCompiler(t, inputFile, referenceFile, true) -} - -func TestPetstoreJSON(t *testing.T) { - testNormal(t, - "examples/v2.0/json/petstore.json", - "test/v2.0/petstore.text") -} - -func TestPetstoreYAML(t *testing.T) { - testNormal(t, - "examples/v2.0/yaml/petstore.yaml", - "test/v2.0/petstore.text") -} - -func TestSeparateYAML(t *testing.T) { - testNormal(t, - "examples/v2.0/yaml/petstore-separate/spec/swagger.yaml", - "test/v2.0/yaml/petstore-separate/spec/swagger.text") -} - -func TestSeparateJSON(t *testing.T) { - testNormal(t, - "examples/v2.0/json/petstore-separate/spec/swagger.json", - "test/v2.0/yaml/petstore-separate/spec/swagger.text") // yaml and json results should be identical -} - -func TestRemotePetstoreJSON(t *testing.T) { - testNormal(t, - "https://raw.githubusercontent.com/googleapis/openapi-compiler/master/examples/v2.0/json/petstore.json", - "test/v2.0/petstore.text") -} - -func TestRemotePetstoreYAML(t *testing.T) { - testNormal(t, - "https://raw.githubusercontent.com/googleapis/openapi-compiler/master/examples/v2.0/yaml/petstore.yaml", - "test/v2.0/petstore.text") -} - -func TestRemoteSeparateYAML(t *testing.T) { - testNormal(t, - "https://raw.githubusercontent.com/googleapis/openapi-compiler/master/examples/v2.0/yaml/petstore-separate/spec/swagger.yaml", - "test/v2.0/yaml/petstore-separate/spec/swagger.text") -} - -func TestRemoteSeparateJSON(t *testing.T) { - testNormal(t, - "https://raw.githubusercontent.com/googleapis/openapi-compiler/master/examples/v2.0/json/petstore-separate/spec/swagger.json", - "test/v2.0/yaml/petstore-separate/spec/swagger.text") -} - -func TestErrorBadProperties(t *testing.T) { - testErrors(t, - "examples/errors/petstore-badproperties.yaml", - "test/errors/petstore-badproperties.errors") -} - -func TestErrorUnresolvedRefs(t *testing.T) { - testErrors(t, - "examples/errors/petstore-unresolvedrefs.yaml", - "test/errors/petstore-unresolvedrefs.errors") -} - -func TestErrorMissingVersion(t *testing.T) { - testErrors(t, - "examples/errors/petstore-missingversion.yaml", - "test/errors/petstore-missingversion.errors") -} - -func testPlugin(t *testing.T, plugin string, inputFile string, outputFile string, referenceFile string) { - // remove any preexisting output files - os.Remove(outputFile) - // run the compiler - var err error - output, err := exec.Command( - "gnostic", - "--"+plugin+"-out=-", - inputFile).Output() - if err != nil { - t.Logf("Compile failed: %+v", err) - t.FailNow() - } - _ = ioutil.WriteFile(outputFile, output, 0644) - err = exec.Command("diff", outputFile, referenceFile).Run() - if err != nil { - t.Logf("Diff failed: %+v", err) - t.FailNow() - } else { - // if the test succeeded, clean up - os.Remove(outputFile) - } -} - -func TestSamplePluginWithPetstore(t *testing.T) { - testPlugin(t, - "summary", - "examples/v2.0/yaml/petstore.yaml", - "sample-petstore.out", - "test/v2.0/yaml/sample-petstore.out") -} - -func TestErrorInvalidPluginInvocations(t *testing.T) { - var err error - output, err := exec.Command( - "gnostic", - "examples/v2.0/yaml/petstore.yaml", - "--errors-out=-", - "--plugin-out=foo=bar,:abc", - "--plugin-out=,foo=bar:abc", - "--plugin-out=foo=:abc", - "--plugin-out==bar:abc", - "--plugin-out=,,:abc", - "--plugin-out=foo=bar=baz:abc", - ).Output() - if err == nil { - t.Logf("Invalid invocations were accepted") - t.FailNow() - } - outputFile := "invalid-plugin-invocation.errors" - _ = ioutil.WriteFile(outputFile, output, 0644) - err = exec.Command("diff", outputFile, "test/errors/invalid-plugin-invocation.errors").Run() - if err != nil { - t.Logf("Diff failed: %+v", err) - t.FailNow() - } else { - // if the test succeeded, clean up - os.Remove(outputFile) - } -} - -func TestValidPluginInvocations(t *testing.T) { - var err error - output, err := exec.Command( - "gnostic", - "examples/v2.0/yaml/petstore.yaml", - "--errors-out=-", - // verify an invocation with no parameters - "--summary-out=!", // "!" indicates that no output should be generated - // verify single pair of parameters - "--summary-out=a=b:!", - // verify multiple parameters - "--summary-out=a=b,c=123,xyz=alphabetagammadelta:!", - // verify that special characters / . - _ can be included in parameter keys and values - "--summary-out=a/b/c=x/y/z:!", - "--summary-out=a.b.c=x.y.z:!", - "--summary-out=a-b-c=x-y-z:!", - "--summary-out=a_b_c=x_y_z:!", - ).Output() - if len(output) != 0 { - t.Logf("Valid invocations generated invalid errors\n%s", string(output)) - t.FailNow() - } - if err != nil { - t.Logf("Valid invocations were not accepted") - t.FailNow() - } -} - -func TestExtensionHandlerWithLibraryExample(t *testing.T) { - outputFile := "library-example-with-ext.text.out" - inputFile := "test/library-example-with-ext.json" - referenceFile := "test/library-example-with-ext.text.out" - - os.Remove(outputFile) - // run the compiler - var err error - - command := exec.Command( - "gnostic", - "--x-sampleone", - "--x-sampletwo", - "--text-out="+outputFile, - "--resolve-refs", - inputFile) - - _, err = command.Output() - if err != nil { - t.Logf("Compile failed for command %v: %+v", command, err) - t.FailNow() - } - //_ = ioutil.WriteFile(outputFile, output, 0644) - err = exec.Command("diff", outputFile, referenceFile).Run() - if err != nil { - t.Logf("Diff failed: %+v", err) - t.FailNow() - } else { - // if the test succeeded, clean up - os.Remove(outputFile) - } -} - -func TestJSONOutput(t *testing.T) { - inputFile := "test/library-example-with-ext.json" - - textFile := "sample.text" - jsonFile := "sample.json" - textFile2 := "sample2.text" - jsonFile2 := "sample2.json" - - os.Remove(textFile) - os.Remove(jsonFile) - os.Remove(textFile2) - os.Remove(jsonFile2) - - var err error - - // Run the compiler once. - command := exec.Command( - "gnostic", - "--text-out="+textFile, - "--json-out="+jsonFile, - inputFile) - _, err = command.Output() - if err != nil { - t.Logf("Compile failed for command %v: %+v", command, err) - t.FailNow() - } - - // Run the compiler again, this time on the generated output. - command = exec.Command( - "gnostic", - "--text-out="+textFile2, - "--json-out="+jsonFile2, - jsonFile) - _, err = command.Output() - if err != nil { - t.Logf("Compile failed for command %v: %+v", command, err) - t.FailNow() - } - - // Verify that both models have the same internal representation. - err = exec.Command("diff", textFile, textFile2).Run() - if err != nil { - t.Logf("Diff failed: %+v", err) - t.FailNow() - } else { - // if the test succeeded, clean up - os.Remove(textFile) - os.Remove(jsonFile) - os.Remove(textFile2) - os.Remove(jsonFile2) - } -} - -func TestYAMLOutput(t *testing.T) { - inputFile := "test/library-example-with-ext.json" - - textFile := "sample.text" - yamlFile := "sample.yaml" - textFile2 := "sample2.text" - yamlFile2 := "sample2.yaml" - - os.Remove(textFile) - os.Remove(yamlFile) - os.Remove(textFile2) - os.Remove(yamlFile2) - - var err error - - // Run the compiler once. - command := exec.Command( - "gnostic", - "--text-out="+textFile, - "--yaml-out="+yamlFile, - inputFile) - _, err = command.Output() - if err != nil { - t.Logf("Compile failed for command %v: %+v", command, err) - t.FailNow() - } - - // Run the compiler again, this time on the generated output. - command = exec.Command( - "gnostic", - "--text-out="+textFile2, - "--yaml-out="+yamlFile2, - yamlFile) - _, err = command.Output() - if err != nil { - t.Logf("Compile failed for command %v: %+v", command, err) - t.FailNow() - } - - // Verify that both models have the same internal representation. - err = exec.Command("diff", textFile, textFile2).Run() - if err != nil { - t.Logf("Diff failed: %+v", err) - t.FailNow() - } else { - // if the test succeeded, clean up - os.Remove(textFile) - os.Remove(yamlFile) - os.Remove(textFile2) - os.Remove(yamlFile2) - } -} - -func testBuilder(version string, t *testing.T) { - var err error - - pbFile := "petstore-" + version + ".pb" - yamlFile := "petstore.yaml" - jsonFile := "petstore.json" - textFile := "petstore.text" - textReference := "test/" + version + ".0/petstore.text" - - os.Remove(pbFile) - os.Remove(textFile) - os.Remove(yamlFile) - os.Remove(jsonFile) - - // Generate petstore.pb. - command := exec.Command( - "petstore-builder", - "--"+version) - _, err = command.Output() - if err != nil { - t.Logf("Command %v failed: %+v", command, err) - t.FailNow() - } - - // Convert petstore.pb to yaml and json. - command = exec.Command( - "gnostic", - pbFile, - "--json-out="+jsonFile, - "--yaml-out="+yamlFile) - _, err = command.Output() - if err != nil { - t.Logf("Command %v failed: %+v", command, err) - t.FailNow() - } - - // Read petstore.yaml, resolve references, and export text. - command = exec.Command( - "gnostic", - yamlFile, - "--resolve-refs", - "--text-out="+textFile) - _, err = command.Output() - if err != nil { - t.Logf("Command %v failed: %+v", command, err) - t.FailNow() - } - - // Verify that the generated text matches our reference. - err = exec.Command("diff", textFile, textReference).Run() - if err != nil { - t.Logf("Diff failed: %+v", err) - t.FailNow() - } - - // Read petstore.json, resolve references, and export text. - command = exec.Command( - "gnostic", - jsonFile, - "--resolve-refs", - "--text-out="+textFile) - _, err = command.Output() - if err != nil { - t.Logf("Command %v failed: %+v", command, err) - t.FailNow() - } - - // Verify that the generated text matches our reference. - err = exec.Command("diff", textFile, textReference).Run() - if err != nil { - t.Logf("Diff failed: %+v", err) - t.FailNow() - } - - // if the test succeeded, clean up - os.Remove(pbFile) - os.Remove(textFile) - os.Remove(yamlFile) - os.Remove(jsonFile) -} - -func TestBuilderV2(t *testing.T) { - testBuilder("v2", t) -} - -func TestBuilderV3(t *testing.T) { - testBuilder("v3", t) -} - -// OpenAPI 3.0 tests - -func TestPetstoreYAML_30(t *testing.T) { - testNormal(t, - "examples/v3.0/yaml/petstore.yaml", - "test/v3.0/petstore.text") -} - -func TestPetstoreJSON_30(t *testing.T) { - testNormal(t, - "examples/v3.0/json/petstore.json", - "test/v3.0/petstore.text") -} diff --git a/vendor/github.com/gophercloud/gophercloud/.gitignore b/vendor/github.com/gophercloud/gophercloud/.gitignore index df9048a010..dd91ed2055 100644 --- a/vendor/github.com/gophercloud/gophercloud/.gitignore +++ b/vendor/github.com/gophercloud/gophercloud/.gitignore @@ -1,2 +1,3 @@ **/*.swp .idea +.vscode diff --git a/vendor/github.com/gophercloud/gophercloud/.travis.yml b/vendor/github.com/gophercloud/gophercloud/.travis.yml index 59c4194952..02728f4968 100644 --- a/vendor/github.com/gophercloud/gophercloud/.travis.yml +++ b/vendor/github.com/gophercloud/gophercloud/.travis.yml @@ -7,8 +7,8 @@ install: - go get github.com/mattn/goveralls - go get golang.org/x/tools/cmd/goimports go: -- 1.8 -- tip +- "1.10" +- "tip" env: global: - secure: "xSQsAG5wlL9emjbCdxzz/hYQsSpJ/bABO1kkbwMSISVcJ3Nk0u4ywF+LS4bgeOnwPfmFvNTOqVDu3RwEvMeWXSI76t1piCPcObutb2faKLVD/hLoAS76gYX+Z8yGWGHrSB7Do5vTPj1ERe2UljdrnsSeOXzoDwFxYRaZLX4bBOB4AyoGvRniil5QXPATiA1tsWX1VMicj8a4F8X+xeESzjt1Q5Iy31e7vkptu71bhvXCaoo5QhYwT+pLR9dN0S1b7Ro0KVvkRefmr1lUOSYd2e74h6Lc34tC1h3uYZCS4h47t7v5cOXvMNxinEj2C51RvbjvZI1RLVdkuAEJD1Iz4+Ote46nXbZ//6XRZMZz/YxQ13l7ux1PFjgEB6HAapmF5Xd8PRsgeTU9LRJxpiTJ3P5QJ3leS1va8qnziM5kYipj/Rn+V8g2ad/rgkRox9LSiR9VYZD2Pe45YCb1mTKSl2aIJnV7nkOqsShY5LNB4JZSg7xIffA+9YVDktw8dJlATjZqt7WvJJ49g6A61mIUV4C15q2JPGKTkZzDiG81NtmS7hFa7k0yaE2ELgYocbcuyUcAahhxntYTC0i23nJmEHVNiZmBO3u7EgpWe4KGVfumU+lt12tIn5b3dZRBBUk3QakKKozSK1QPHGpk/AZGrhu7H6l8to6IICKWtDcyMPQ=" diff --git a/vendor/github.com/gophercloud/gophercloud/.zuul.yaml b/vendor/github.com/gophercloud/gophercloud/.zuul.yaml index c259d03e18..3d4798fe6f 100644 --- a/vendor/github.com/gophercloud/gophercloud/.zuul.yaml +++ b/vendor/github.com/gophercloud/gophercloud/.zuul.yaml @@ -1,3 +1,58 @@ +- job: + name: gophercloud-unittest + parent: golang-test + description: | + Run gophercloud unit test + run: .zuul/playbooks/gophercloud-unittest/run.yaml + nodeset: ubuntu-xenial-ut + +- job: + name: gophercloud-acceptance-test + parent: golang-test + description: | + Run gophercloud acceptance test on master branch + run: .zuul/playbooks/gophercloud-acceptance-test/run.yaml + +- job: + name: gophercloud-acceptance-test-queens + parent: gophercloud-acceptance-test + description: | + Run gophercloud acceptance test on queens branch + vars: + os_branch: 'stable/queens' + +- job: + name: gophercloud-acceptance-test-pike + parent: gophercloud-acceptance-test + description: | + Run gophercloud acceptance test on pike branch + vars: + os_branch: 'stable/pike' +- job: + name: gophercloud-acceptance-test-ocata + parent: gophercloud-acceptance-test + description: | + Run gophercloud acceptance test on ocata branch + vars: + os_branch: 'stable/ocata' + +- job: + name: gophercloud-acceptance-test-newton + parent: gophercloud-acceptance-test + description: | + Run gophercloud acceptance test on newton branch + vars: + os_branch: 'stable/newton' + +- job: + name: gophercloud-acceptance-test-mitaka + parent: gophercloud-acceptance-test + description: | + Run gophercloud acceptance test on mitaka branch + vars: + os_branch: 'stable/mitaka' + nodeset: ubuntu-trusty + - project: name: gophercloud/gophercloud check: @@ -7,6 +62,15 @@ recheck-mitaka: jobs: - gophercloud-acceptance-test-mitaka + recheck-newton: + jobs: + - gophercloud-acceptance-test-newton + recheck-ocata: + jobs: + - gophercloud-acceptance-test-ocata recheck-pike: jobs: - gophercloud-acceptance-test-pike + recheck-queens: + jobs: + - gophercloud-acceptance-test-queens diff --git a/vendor/github.com/gophercloud/gophercloud/FAQ.md b/vendor/github.com/gophercloud/gophercloud/FAQ.md deleted file mode 100644 index 88a366a288..0000000000 --- a/vendor/github.com/gophercloud/gophercloud/FAQ.md +++ /dev/null @@ -1,148 +0,0 @@ -# Tips - -## Implementing default logging and re-authentication attempts - -You can implement custom logging and/or limit re-auth attempts by creating a custom HTTP client -like the following and setting it as the provider client's HTTP Client (via the -`gophercloud.ProviderClient.HTTPClient` field): - -```go -//... - -// LogRoundTripper satisfies the http.RoundTripper interface and is used to -// customize the default Gophercloud RoundTripper to allow for logging. -type LogRoundTripper struct { - rt http.RoundTripper - numReauthAttempts int -} - -// newHTTPClient return a custom HTTP client that allows for logging relevant -// information before and after the HTTP request. -func newHTTPClient() http.Client { - return http.Client{ - Transport: &LogRoundTripper{ - rt: http.DefaultTransport, - }, - } -} - -// RoundTrip performs a round-trip HTTP request and logs relevant information about it. -func (lrt *LogRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { - glog.Infof("Request URL: %s\n", request.URL) - - response, err := lrt.rt.RoundTrip(request) - if response == nil { - return nil, err - } - - if response.StatusCode == http.StatusUnauthorized { - if lrt.numReauthAttempts == 3 { - return response, fmt.Errorf("Tried to re-authenticate 3 times with no success.") - } - lrt.numReauthAttempts++ - } - - glog.Debugf("Response Status: %s\n", response.Status) - - return response, nil -} - -endpoint := "https://127.0.0.1/auth" -pc := openstack.NewClient(endpoint) -pc.HTTPClient = newHTTPClient() - -//... -``` - - -## Implementing custom objects - -OpenStack request/response objects may differ among variable names or types. - -### Custom request objects - -To pass custom options to a request, implement the desired `OptsBuilder` interface. For -example, to pass in - -```go -type MyCreateServerOpts struct { - Name string - Size int -} -``` - -to `servers.Create`, simply implement the `servers.CreateOptsBuilder` interface: - -```go -func (o MyCreateServeropts) ToServerCreateMap() (map[string]interface{}, error) { - return map[string]interface{}{ - "name": o.Name, - "size": o.Size, - }, nil -} -``` - -create an instance of your custom options object, and pass it to `servers.Create`: - -```go -// ... -myOpts := MyCreateServerOpts{ - Name: "s1", - Size: "100", -} -server, err := servers.Create(computeClient, myOpts).Extract() -// ... -``` - -### Custom response objects - -Some OpenStack services have extensions. Extensions that are supported in Gophercloud can be -combined to create a custom object: - -```go -// ... -type MyVolume struct { - volumes.Volume - tenantattr.VolumeExt -} - -var v struct { - MyVolume `json:"volume"` -} - -err := volumes.Get(client, volID).ExtractInto(&v) -// ... -``` - -## Overriding default `UnmarshalJSON` method - -For some response objects, a field may be a custom type or may be allowed to take on -different types. In these cases, overriding the default `UnmarshalJSON` method may be -necessary. To do this, declare the JSON `struct` field tag as "-" and create an `UnmarshalJSON` -method on the type: - -```go -// ... -type MyVolume struct { - ID string `json: "id"` - TimeCreated time.Time `json: "-"` -} - -func (r *MyVolume) UnmarshalJSON(b []byte) error { - type tmp MyVolume - var s struct { - tmp - TimeCreated gophercloud.JSONRFC3339MilliNoZ `json:"created_at"` - } - err := json.Unmarshal(b, &s) - if err != nil { - return err - } - *r = Volume(s.tmp) - - r.TimeCreated = time.Time(s.CreatedAt) - - return err -} -// ... -``` diff --git a/vendor/github.com/gophercloud/gophercloud/MIGRATING.md b/vendor/github.com/gophercloud/gophercloud/MIGRATING.md deleted file mode 100644 index aa383c9cc9..0000000000 --- a/vendor/github.com/gophercloud/gophercloud/MIGRATING.md +++ /dev/null @@ -1,32 +0,0 @@ -# Compute - -## Floating IPs - -* `github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingip` is now `github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/floatingips` -* `floatingips.Associate` and `floatingips.Disassociate` have been removed. -* `floatingips.DisassociateOpts` is now required to disassociate a Floating IP. - -## Security Groups - -* `secgroups.AddServerToGroup` is now `secgroups.AddServer`. -* `secgroups.RemoveServerFromGroup` is now `secgroups.RemoveServer`. - -## Servers - -* `servers.Reboot` now requires a `servers.RebootOpts` struct: - - ```golang - rebootOpts := &servers.RebootOpts{ - Type: servers.SoftReboot, - } - res := servers.Reboot(client, server.ID, rebootOpts) - ``` - -# Identity - -## V3 - -### Tokens - -* `Token.ExpiresAt` is now of type `gophercloud.JSONRFC3339Milli` instead of - `time.Time` diff --git a/vendor/github.com/gophercloud/gophercloud/README.md b/vendor/github.com/gophercloud/gophercloud/README.md index 60ca479de8..8c5bfce796 100644 --- a/vendor/github.com/gophercloud/gophercloud/README.md +++ b/vendor/github.com/gophercloud/gophercloud/README.md @@ -127,7 +127,7 @@ new resource in the `server` variable (a ## Advanced Usage -Have a look at the [FAQ](./FAQ.md) for some tips on customizing the way Gophercloud works. +Have a look at the [FAQ](./docs/FAQ.md) for some tips on customizing the way Gophercloud works. ## Backwards-Compatibility Guarantees @@ -141,3 +141,19 @@ See the [contributing guide](./.github/CONTRIBUTING.md). If you're struggling with something or have spotted a potential bug, feel free to submit an issue to our [bug tracker](/issues). + +## Thank You + +We'd like to extend special thanks and appreciation to the following: + +### OpenLab + + + +OpenLab is providing a full CI environment to test each PR and merge for a variety of OpenStack releases. + +### VEXXHOST + + + +VEXXHOST is providing their services to assist with the development and testing of Gophercloud. diff --git a/vendor/github.com/gophercloud/gophercloud/STYLEGUIDE.md b/vendor/github.com/gophercloud/gophercloud/STYLEGUIDE.md deleted file mode 100644 index e7531a83d9..0000000000 --- a/vendor/github.com/gophercloud/gophercloud/STYLEGUIDE.md +++ /dev/null @@ -1,74 +0,0 @@ - -## On Pull Requests - -- Before you start a PR there needs to be a Github issue and a discussion about it - on that issue with a core contributor, even if it's just a 'SGTM'. - -- A PR's description must reference the issue it closes with a `For ` (e.g. For #293). - -- A PR's description must contain link(s) to the line(s) in the OpenStack - source code (on Github) that prove(s) the PR code to be valid. Links to documentation - are not good enough. The link(s) should be to a non-`master` branch. For example, - a pull request implementing the creation of a Neutron v2 subnet might put the - following link in the description: - - https://github.com/openstack/neutron/blob/stable/mitaka/neutron/api/v2/attributes.py#L749 - - From that link, a reviewer (or user) can verify the fields in the request/response - objects in the PR. - -- A PR that is in-progress should have `[wip]` in front of the PR's title. When - ready for review, remove the `[wip]` and ping a core contributor with an `@`. - -- Forcing PRs to be small can have the effect of users submitting PRs in a hierarchical chain, with - one depending on the next. If a PR depends on another one, it should have a [Pending #PRNUM] - prefix in the PR title. In addition, it will be the PR submitter's responsibility to remove the - [Pending #PRNUM] tag once the PR has been updated with the merged, dependent PR. That will - let reviewers know it is ready to review. - -- A PR should be small. Even if you intend on implementing an entire - service, a PR should only be one route of that service - (e.g. create server or get server, but not both). - -- Unless explicitly asked, do not squash commits in the middle of a review; only - append. It makes it difficult for the reviewer to see what's changed from one - review to the next. - -## On Code - -- In re design: follow as closely as is reasonable the code already in the library. - Most operations (e.g. create, delete) admit the same design. - -- Unit tests and acceptance (integration) tests must be written to cover each PR. - Tests for operations with several options (e.g. list, create) should include all - the options in the tests. This will allow users to verify an operation on their - own infrastructure and see an example of usage. - -- If in doubt, ask in-line on the PR. - -### File Structure - -- The following should be used in most cases: - - - `requests.go`: contains all the functions that make HTTP requests and the - types associated with the HTTP request (parameters for URL, body, etc) - - `results.go`: contains all the response objects and their methods - - `urls.go`: contains the endpoints to which the requests are made - -### Naming - -- For methods on a type in `results.go`, the receiver should be named `r` and the - variable into which it will be unmarshalled `s`. - -- Functions in `requests.go`, with the exception of functions that return a - `pagination.Pager`, should be named returns of the name `r`. - -- Functions in `requests.go` that accept request bodies should accept as their - last parameter an `interface` named `OptsBuilder` (eg `CreateOptsBuilder`). - This `interface` should have at the least a method named `ToMap` - (eg `ToPortCreateMap`). - -- Functions in `requests.go` that accept query strings should accept as their - last parameter an `interface` named `OptsBuilder` (eg `ListOptsBuilder`). - This `interface` should have at the least a method named `ToQuery` - (eg `ToServerListQuery`). diff --git a/vendor/github.com/gophercloud/gophercloud/auth_options.go b/vendor/github.com/gophercloud/gophercloud/auth_options.go index 4211470020..5e693585c2 100644 --- a/vendor/github.com/gophercloud/gophercloud/auth_options.go +++ b/vendor/github.com/gophercloud/gophercloud/auth_options.go @@ -81,6 +81,17 @@ type AuthOptions struct { // TokenID allows users to authenticate (possibly as another user) with an // authentication token ID. TokenID string `json:"-"` + + // Scope determines the scoping of the authentication request. + Scope *AuthScope `json:"-"` +} + +// AuthScope allows a created token to be limited to a specific domain or project. +type AuthScope struct { + ProjectID string + ProjectName string + DomainID string + DomainName string } // ToTokenV2CreateMap allows AuthOptions to satisfy the AuthOptionsBuilder @@ -263,85 +274,83 @@ func (opts *AuthOptions) ToTokenV3CreateMap(scope map[string]interface{}) (map[s } func (opts *AuthOptions) ToTokenV3ScopeMap() (map[string]interface{}, error) { - - var scope struct { - ProjectID string - ProjectName string - DomainID string - DomainName string - } - - if opts.TenantID != "" { - scope.ProjectID = opts.TenantID - } else { - if opts.TenantName != "" { - scope.ProjectName = opts.TenantName - scope.DomainID = opts.DomainID - scope.DomainName = opts.DomainName + // For backwards compatibility. + // If AuthOptions.Scope was not set, try to determine it. + // This works well for common scenarios. + if opts.Scope == nil { + opts.Scope = new(AuthScope) + if opts.TenantID != "" { + opts.Scope.ProjectID = opts.TenantID + } else { + if opts.TenantName != "" { + opts.Scope.ProjectName = opts.TenantName + opts.Scope.DomainID = opts.DomainID + opts.Scope.DomainName = opts.DomainName + } } } - if scope.ProjectName != "" { + if opts.Scope.ProjectName != "" { // ProjectName provided: either DomainID or DomainName must also be supplied. // ProjectID may not be supplied. - if scope.DomainID == "" && scope.DomainName == "" { + if opts.Scope.DomainID == "" && opts.Scope.DomainName == "" { return nil, ErrScopeDomainIDOrDomainName{} } - if scope.ProjectID != "" { + if opts.Scope.ProjectID != "" { return nil, ErrScopeProjectIDOrProjectName{} } - if scope.DomainID != "" { + if opts.Scope.DomainID != "" { // ProjectName + DomainID return map[string]interface{}{ "project": map[string]interface{}{ - "name": &scope.ProjectName, - "domain": map[string]interface{}{"id": &scope.DomainID}, + "name": &opts.Scope.ProjectName, + "domain": map[string]interface{}{"id": &opts.Scope.DomainID}, }, }, nil } - if scope.DomainName != "" { + if opts.Scope.DomainName != "" { // ProjectName + DomainName return map[string]interface{}{ "project": map[string]interface{}{ - "name": &scope.ProjectName, - "domain": map[string]interface{}{"name": &scope.DomainName}, + "name": &opts.Scope.ProjectName, + "domain": map[string]interface{}{"name": &opts.Scope.DomainName}, }, }, nil } - } else if scope.ProjectID != "" { + } else if opts.Scope.ProjectID != "" { // ProjectID provided. ProjectName, DomainID, and DomainName may not be provided. - if scope.DomainID != "" { + if opts.Scope.DomainID != "" { return nil, ErrScopeProjectIDAlone{} } - if scope.DomainName != "" { + if opts.Scope.DomainName != "" { return nil, ErrScopeProjectIDAlone{} } // ProjectID return map[string]interface{}{ "project": map[string]interface{}{ - "id": &scope.ProjectID, + "id": &opts.Scope.ProjectID, }, }, nil - } else if scope.DomainID != "" { + } else if opts.Scope.DomainID != "" { // DomainID provided. ProjectID, ProjectName, and DomainName may not be provided. - if scope.DomainName != "" { + if opts.Scope.DomainName != "" { return nil, ErrScopeDomainIDOrDomainName{} } // DomainID return map[string]interface{}{ "domain": map[string]interface{}{ - "id": &scope.DomainID, + "id": &opts.Scope.DomainID, }, }, nil - } else if scope.DomainName != "" { + } else if opts.Scope.DomainName != "" { // DomainName return map[string]interface{}{ "domain": map[string]interface{}{ - "name": &scope.DomainName, + "name": &opts.Scope.DomainName, }, }, nil } diff --git a/vendor/github.com/gophercloud/gophercloud/errors.go b/vendor/github.com/gophercloud/gophercloud/errors.go index 88fd2ac676..5088eda0d9 100644 --- a/vendor/github.com/gophercloud/gophercloud/errors.go +++ b/vendor/github.com/gophercloud/gophercloud/errors.go @@ -1,6 +1,9 @@ package gophercloud -import "fmt" +import ( + "fmt" + "strings" +) // BaseError is an error type that all other error types embed. type BaseError struct { @@ -43,6 +46,33 @@ func (e ErrInvalidInput) Error() string { return e.choseErrString() } +// ErrMissingEnvironmentVariable is the error when environment variable is required +// in a particular situation but not provided by the user +type ErrMissingEnvironmentVariable struct { + BaseError + EnvironmentVariable string +} + +func (e ErrMissingEnvironmentVariable) Error() string { + e.DefaultErrString = fmt.Sprintf("Missing environment variable [%s]", e.EnvironmentVariable) + return e.choseErrString() +} + +// ErrMissingAnyoneOfEnvironmentVariables is the error when anyone of the environment variables +// is required in a particular situation but not provided by the user +type ErrMissingAnyoneOfEnvironmentVariables struct { + BaseError + EnvironmentVariables []string +} + +func (e ErrMissingAnyoneOfEnvironmentVariables) Error() string { + e.DefaultErrString = fmt.Sprintf( + "Missing one of the following environment variables [%s]", + strings.Join(e.EnvironmentVariables, ", "), + ) + return e.choseErrString() +} + // ErrUnexpectedResponseCode is returned by the Request method when a response code other than // those listed in OkCodes is encountered. type ErrUnexpectedResponseCode struct { @@ -72,6 +102,11 @@ type ErrDefault401 struct { ErrUnexpectedResponseCode } +// ErrDefault403 is the default error type returned on a 403 HTTP response code. +type ErrDefault403 struct { + ErrUnexpectedResponseCode +} + // ErrDefault404 is the default error type returned on a 404 HTTP response code. type ErrDefault404 struct { ErrUnexpectedResponseCode @@ -108,6 +143,13 @@ func (e ErrDefault400) Error() string { func (e ErrDefault401) Error() string { return "Authentication failed" } +func (e ErrDefault403) Error() string { + e.DefaultErrString = fmt.Sprintf( + "Request forbidden: [%s %s], error message: %s", + e.Method, e.URL, e.Body, + ) + return e.choseErrString() +} func (e ErrDefault404) Error() string { return "Resource not found" } @@ -141,6 +183,12 @@ type Err401er interface { Error401(ErrUnexpectedResponseCode) error } +// Err403er is the interface resource error types implement to override the error message +// from a 403 error. +type Err403er interface { + Error403(ErrUnexpectedResponseCode) error +} + // Err404er is the interface resource error types implement to override the error message // from a 404 error. type Err404er interface { diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/auth_env.go b/vendor/github.com/gophercloud/gophercloud/openstack/auth_env.go index 95286041d6..994b5550c9 100644 --- a/vendor/github.com/gophercloud/gophercloud/openstack/auth_env.go +++ b/vendor/github.com/gophercloud/gophercloud/openstack/auth_env.go @@ -16,7 +16,12 @@ The following variables provide sources of truth: OS_AUTH_URL, OS_USERNAME, OS_PASSWORD, OS_TENANT_ID, and OS_TENANT_NAME. Of these, OS_USERNAME, OS_PASSWORD, and OS_AUTH_URL must have settings, -or an error will result. OS_TENANT_ID and OS_TENANT_NAME are optional. +or an error will result. OS_TENANT_ID, OS_TENANT_NAME, OS_PROJECT_ID, and +OS_PROJECT_NAME are optional. + +OS_TENANT_ID and OS_TENANT_NAME are mutually exclusive to OS_PROJECT_ID and +OS_PROJECT_NAME. If OS_PROJECT_ID and OS_PROJECT_NAME are set, they will +still be referred as "tenant" in Gophercloud. To use this function, first set the OS_* environment variables (for example, by sourcing an `openrc` file), then: @@ -34,18 +39,34 @@ func AuthOptionsFromEnv() (gophercloud.AuthOptions, error) { domainID := os.Getenv("OS_DOMAIN_ID") domainName := os.Getenv("OS_DOMAIN_NAME") + // If OS_PROJECT_ID is set, overwrite tenantID with the value. + if v := os.Getenv("OS_PROJECT_ID"); v != "" { + tenantID = v + } + + // If OS_PROJECT_NAME is set, overwrite tenantName with the value. + if v := os.Getenv("OS_PROJECT_NAME"); v != "" { + tenantName = v + } + if authURL == "" { - err := gophercloud.ErrMissingInput{Argument: "authURL"} + err := gophercloud.ErrMissingEnvironmentVariable{ + EnvironmentVariable: "OS_AUTH_URL", + } return nilOptions, err } if username == "" && userID == "" { - err := gophercloud.ErrMissingInput{Argument: "username"} + err := gophercloud.ErrMissingAnyoneOfEnvironmentVariables{ + EnvironmentVariables: []string{"OS_USERNAME", "OS_USERID"}, + } return nilOptions, err } if password == "" { - err := gophercloud.ErrMissingInput{Argument: "password"} + err := gophercloud.ErrMissingEnvironmentVariable{ + EnvironmentVariable: "OS_PASSWORD", + } return nilOptions, err } diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/client.go b/vendor/github.com/gophercloud/gophercloud/openstack/client.go index adcf90bcef..e554b7bc37 100644 --- a/vendor/github.com/gophercloud/gophercloud/openstack/client.go +++ b/vendor/github.com/gophercloud/gophercloud/openstack/client.go @@ -2,10 +2,7 @@ package openstack import ( "fmt" - "net/url" "reflect" - "regexp" - "strings" "github.com/gophercloud/gophercloud" tokens2 "github.com/gophercloud/gophercloud/openstack/identity/v2/tokens" @@ -38,29 +35,20 @@ A basic example of using this would be: client, err := openstack.NewIdentityV3(provider, gophercloud.EndpointOpts{}) */ func NewClient(endpoint string) (*gophercloud.ProviderClient, error) { - u, err := url.Parse(endpoint) + base, err := utils.BaseEndpoint(endpoint) if err != nil { return nil, err } - u.RawQuery, u.Fragment = "", "" - - var base string - versionRe := regexp.MustCompile("v[0-9.]+/?") - if version := versionRe.FindString(u.Path); version != "" { - base = strings.Replace(u.String(), version, "", -1) - } else { - base = u.String() - } - endpoint = gophercloud.NormalizeURL(endpoint) base = gophercloud.NormalizeURL(base) - return &gophercloud.ProviderClient{ - IdentityBase: base, - IdentityEndpoint: endpoint, - }, nil + p := new(gophercloud.ProviderClient) + p.IdentityBase = base + p.IdentityEndpoint = endpoint + p.UseTokenLock() + return p, nil } /* @@ -158,9 +146,21 @@ func v2auth(client *gophercloud.ProviderClient, endpoint string, options gopherc } if options.AllowReauth { + // here we're creating a throw-away client (tac). it's a copy of the user's provider client, but + // with the token and reauth func zeroed out. combined with setting `AllowReauth` to `false`, + // this should retry authentication only once + tac := *client + tac.ReauthFunc = nil + tac.TokenID = "" + tao := options + tao.AllowReauth = false client.ReauthFunc = func() error { - client.TokenID = "" - return v2auth(client, endpoint, options, eo) + err := v2auth(&tac, endpoint, tao, eo) + if err != nil { + return err + } + client.TokenID = tac.TokenID + return nil } } client.TokenID = token.ID @@ -202,9 +202,32 @@ func v3auth(client *gophercloud.ProviderClient, endpoint string, opts tokens3.Au client.TokenID = token.ID if opts.CanReauth() { + // here we're creating a throw-away client (tac). it's a copy of the user's provider client, but + // with the token and reauth func zeroed out. combined with setting `AllowReauth` to `false`, + // this should retry authentication only once + tac := *client + tac.ReauthFunc = nil + tac.TokenID = "" + var tao tokens3.AuthOptionsBuilder + switch ot := opts.(type) { + case *gophercloud.AuthOptions: + o := *ot + o.AllowReauth = false + tao = &o + case *tokens3.AuthOptions: + o := *ot + o.AllowReauth = false + tao = &o + default: + tao = opts + } client.ReauthFunc = func() error { - client.TokenID = "" - return v3auth(client, endpoint, opts, eo) + err := v3auth(&tac, endpoint, tao, eo) + if err != nil { + return err + } + client.TokenID = tac.TokenID + return nil } } client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) { @@ -251,11 +274,17 @@ func NewIdentityV3(client *gophercloud.ProviderClient, eo gophercloud.EndpointOp // Ensure endpoint still has a suffix of v3. // This is because EndpointLocator might have found a versionless - // endpoint and requests will fail unless targeted at /v3. - if !strings.HasSuffix(endpoint, "v3/") { - endpoint = endpoint + "v3/" + // endpoint or the published endpoint is still /v2.0. In both + // cases, we need to fix the endpoint to point to /v3. + base, err := utils.BaseEndpoint(endpoint) + if err != nil { + return nil, err } + base = gophercloud.NormalizeURL(base) + + endpoint = base + "v3/" + return &gophercloud.ServiceClient{ ProviderClient: client, Endpoint: endpoint, @@ -308,8 +337,12 @@ func NewBlockStorageV2(client *gophercloud.ProviderClient, eo gophercloud.Endpoi return initClientOpts(client, eo, "volumev2") } -// NewSharedFileSystemV2 creates a ServiceClient that may be used to access the -// v2 shared file system service. +// NewBlockStorageV3 creates a ServiceClient that may be used to access the v3 block storage service. +func NewBlockStorageV3(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { + return initClientOpts(client, eo, "volumev3") +} + +// NewSharedFileSystemV2 creates a ServiceClient that may be used to access the v2 shared file system service. func NewSharedFileSystemV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { return initClientOpts(client, eo, "sharev2") } @@ -354,3 +387,22 @@ func NewLoadBalancerV2(client *gophercloud.ProviderClient, eo gophercloud.Endpoi sc.ResourceBase = sc.Endpoint + "v2.0/" return sc, err } + +// NewClusteringV1 creates a ServiceClient that may be used with the v1 clustering +// package. +func NewClusteringV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { + return initClientOpts(client, eo, "clustering") +} + +// NewMessagingV2 creates a ServiceClient that may be used with the v2 messaging +// service. +func NewMessagingV2(client *gophercloud.ProviderClient, clientID string, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { + sc, err := initClientOpts(client, eo, "messaging") + sc.MoreHeaders = map[string]string{"Client-ID": clientID} + return sc, err +} + +// NewContainerV1 creates a ServiceClient that may be used with v1 container package +func NewContainerV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) { + return initClientOpts(client, eo, "container") +} diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/endpoint_location.go b/vendor/github.com/gophercloud/gophercloud/openstack/endpoint_location.go index 070ea7cbef..12c8aebcf7 100644 --- a/vendor/github.com/gophercloud/gophercloud/openstack/endpoint_location.go +++ b/vendor/github.com/gophercloud/gophercloud/openstack/endpoint_location.go @@ -84,7 +84,7 @@ func V3EndpointURL(catalog *tokens3.ServiceCatalog, opts gophercloud.EndpointOpt return "", err } if (opts.Availability == gophercloud.Availability(endpoint.Interface)) && - (opts.Region == "" || endpoint.Region == opts.Region) { + (opts.Region == "" || endpoint.Region == opts.Region || endpoint.RegionID == opts.Region) { endpoints = append(endpoints, endpoint) } } diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/requests.go b/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/requests.go index ca35851e4a..6e99a793c5 100644 --- a/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/requests.go +++ b/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/requests.go @@ -72,72 +72,15 @@ func (opts *AuthOptions) ToTokenV3CreateMap(scope map[string]interface{}) (map[s // ToTokenV3CreateMap builds a scope request body from AuthOptions. func (opts *AuthOptions) ToTokenV3ScopeMap() (map[string]interface{}, error) { - if opts.Scope.ProjectName != "" { - // ProjectName provided: either DomainID or DomainName must also be supplied. - // ProjectID may not be supplied. - if opts.Scope.DomainID == "" && opts.Scope.DomainName == "" { - return nil, gophercloud.ErrScopeDomainIDOrDomainName{} - } - if opts.Scope.ProjectID != "" { - return nil, gophercloud.ErrScopeProjectIDOrProjectName{} - } - - if opts.Scope.DomainID != "" { - // ProjectName + DomainID - return map[string]interface{}{ - "project": map[string]interface{}{ - "name": &opts.Scope.ProjectName, - "domain": map[string]interface{}{"id": &opts.Scope.DomainID}, - }, - }, nil - } - - if opts.Scope.DomainName != "" { - // ProjectName + DomainName - return map[string]interface{}{ - "project": map[string]interface{}{ - "name": &opts.Scope.ProjectName, - "domain": map[string]interface{}{"name": &opts.Scope.DomainName}, - }, - }, nil - } - } else if opts.Scope.ProjectID != "" { - // ProjectID provided. ProjectName, DomainID, and DomainName may not be provided. - if opts.Scope.DomainID != "" { - return nil, gophercloud.ErrScopeProjectIDAlone{} - } - if opts.Scope.DomainName != "" { - return nil, gophercloud.ErrScopeProjectIDAlone{} - } - - // ProjectID - return map[string]interface{}{ - "project": map[string]interface{}{ - "id": &opts.Scope.ProjectID, - }, - }, nil - } else if opts.Scope.DomainID != "" { - // DomainID provided. ProjectID, ProjectName, and DomainName may not be provided. - if opts.Scope.DomainName != "" { - return nil, gophercloud.ErrScopeDomainIDOrDomainName{} - } - - // DomainID - return map[string]interface{}{ - "domain": map[string]interface{}{ - "id": &opts.Scope.DomainID, - }, - }, nil - } else if opts.Scope.DomainName != "" { - // DomainName - return map[string]interface{}{ - "domain": map[string]interface{}{ - "name": &opts.Scope.DomainName, - }, - }, nil + scope := gophercloud.AuthScope(opts.Scope) + + gophercloudAuthOpts := gophercloud.AuthOptions{ + Scope: &scope, + DomainID: opts.DomainID, + DomainName: opts.DomainName, } - return nil, nil + return gophercloudAuthOpts.ToTokenV3ScopeMap() } func (opts *AuthOptions) CanReauth() bool { @@ -190,7 +133,7 @@ func Get(c *gophercloud.ServiceClient, token string) (r GetResult) { // Validate determines if a specified token is valid or not. func Validate(c *gophercloud.ServiceClient, token string) (bool, error) { - resp, err := c.Request("HEAD", tokenURL(c), &gophercloud.RequestOpts{ + resp, err := c.Head(tokenURL(c), &gophercloud.RequestOpts{ MoreHeaders: subjectTokenHeaders(c, token), OkCodes: []int{200, 204, 404}, }) diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/results.go b/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/results.go index 6e78d1cbdb..ebdca58f65 100644 --- a/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/results.go +++ b/vendor/github.com/gophercloud/gophercloud/openstack/identity/v3/tokens/results.go @@ -13,6 +13,7 @@ import ( type Endpoint struct { ID string `json:"id"` Region string `json:"region"` + RegionID string `json:"region_id"` Interface string `json:"interface"` URL string `json:"url"` } diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/utils/base_endpoint.go b/vendor/github.com/gophercloud/gophercloud/openstack/utils/base_endpoint.go new file mode 100644 index 0000000000..d6f9e34eaa --- /dev/null +++ b/vendor/github.com/gophercloud/gophercloud/openstack/utils/base_endpoint.go @@ -0,0 +1,29 @@ +package utils + +import ( + "net/url" + "regexp" + "strings" +) + +// BaseEndpoint will return a URL without the /vX.Y +// portion of the URL. +func BaseEndpoint(endpoint string) (string, error) { + var base string + + u, err := url.Parse(endpoint) + if err != nil { + return base, err + } + + u.RawQuery, u.Fragment = "", "" + + versionRe := regexp.MustCompile("v[0-9.]+/?") + if version := versionRe.FindString(u.Path); version != "" { + base = strings.Replace(u.String(), version, "", -1) + } else { + base = u.String() + } + + return base, nil +} diff --git a/vendor/github.com/gophercloud/gophercloud/params.go b/vendor/github.com/gophercloud/gophercloud/params.go index 6afc8f8b72..19b8cf7bf8 100644 --- a/vendor/github.com/gophercloud/gophercloud/params.go +++ b/vendor/github.com/gophercloud/gophercloud/params.go @@ -115,10 +115,15 @@ func BuildRequestBody(opts interface{}, parent string) (map[string]interface{}, } } + jsonTag := f.Tag.Get("json") + if jsonTag == "-" { + continue + } + if v.Kind() == reflect.Struct || (v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct) { if zero { //fmt.Printf("value before change: %+v\n", optsValue.Field(i)) - if jsonTag := f.Tag.Get("json"); jsonTag != "" { + if jsonTag != "" { jsonTagPieces := strings.Split(jsonTag, ",") if len(jsonTagPieces) > 1 && jsonTagPieces[1] == "omitempty" { if v.CanSet() { @@ -347,12 +352,20 @@ func BuildQueryString(opts interface{}) (*url.URL, error) { params.Add(tags[0], v.Index(i).String()) } } + case reflect.Map: + if v.Type().Key().Kind() == reflect.String && v.Type().Elem().Kind() == reflect.String { + var s []string + for _, k := range v.MapKeys() { + value := v.MapIndex(k).String() + s = append(s, fmt.Sprintf("'%s':'%s'", k.String(), value)) + } + params.Add(tags[0], fmt.Sprintf("{%s}", strings.Join(s, ", "))) + } } } else { - // Otherwise, the field is not set. - if len(tags) == 2 && tags[1] == "required" { - // And the field is required. Return an error. - return nil, fmt.Errorf("Required query parameter [%s] not set.", f.Name) + // if the field has a 'required' tag, it can't have a zero-value + if requiredTag := f.Tag.Get("required"); requiredTag == "true" { + return &url.URL{}, fmt.Errorf("Required query parameter [%s] not set.", f.Name) } } } @@ -425,10 +438,9 @@ func BuildHeaders(opts interface{}) (map[string]string, error) { optsMap[tags[0]] = strconv.FormatBool(v.Bool()) } } else { - // Otherwise, the field is not set. - if len(tags) == 2 && tags[1] == "required" { - // And the field is required. Return an error. - return optsMap, fmt.Errorf("Required header not set.") + // if the field has a 'required' tag, it can't have a zero-value + if requiredTag := f.Tag.Get("required"); requiredTag == "true" { + return optsMap, fmt.Errorf("Required header [%s] not set.", f.Name) } } } diff --git a/vendor/github.com/gophercloud/gophercloud/provider_client.go b/vendor/github.com/gophercloud/gophercloud/provider_client.go index 01b3010739..17e4512743 100644 --- a/vendor/github.com/gophercloud/gophercloud/provider_client.go +++ b/vendor/github.com/gophercloud/gophercloud/provider_client.go @@ -7,6 +7,7 @@ import ( "io/ioutil" "net/http" "strings" + "sync" ) // DefaultUserAgent is the default User-Agent string set in the request header. @@ -51,6 +52,8 @@ type ProviderClient struct { IdentityEndpoint string // TokenID is the ID of the most recently issued valid token. + // NOTE: Aside from within a custom ReauthFunc, this field shouldn't be set by an application. + // To safely read or write this value, call `Token` or `SetToken`, respectively TokenID string // EndpointLocator describes how this provider discovers the endpoints for @@ -68,16 +71,89 @@ type ProviderClient struct { // authentication functions for different Identity service versions. ReauthFunc func() error - Debug bool + mut *sync.RWMutex + + reauthmut *reauthlock +} + +type reauthlock struct { + sync.RWMutex + reauthing bool } // AuthenticatedHeaders returns a map of HTTP headers that are common for all // authenticated service requests. -func (client *ProviderClient) AuthenticatedHeaders() map[string]string { - if client.TokenID == "" { - return map[string]string{} +func (client *ProviderClient) AuthenticatedHeaders() (m map[string]string) { + if client.reauthmut != nil { + client.reauthmut.RLock() + if client.reauthmut.reauthing { + client.reauthmut.RUnlock() + return + } + client.reauthmut.RUnlock() + } + t := client.Token() + if t == "" { + return + } + return map[string]string{"X-Auth-Token": t} +} + +// UseTokenLock creates a mutex that is used to allow safe concurrent access to the auth token. +// If the application's ProviderClient is not used concurrently, this doesn't need to be called. +func (client *ProviderClient) UseTokenLock() { + client.mut = new(sync.RWMutex) + client.reauthmut = new(reauthlock) +} + +// Token safely reads the value of the auth token from the ProviderClient. Applications should +// call this method to access the token instead of the TokenID field +func (client *ProviderClient) Token() string { + if client.mut != nil { + client.mut.RLock() + defer client.mut.RUnlock() + } + return client.TokenID +} + +// SetToken safely sets the value of the auth token in the ProviderClient. Applications may +// use this method in a custom ReauthFunc +func (client *ProviderClient) SetToken(t string) { + if client.mut != nil { + client.mut.Lock() + defer client.mut.Unlock() + } + client.TokenID = t +} + +//Reauthenticate calls client.ReauthFunc in a thread-safe way. If this is +//called because of a 401 response, the caller may pass the previous token. In +//this case, the reauthentication can be skipped if another thread has already +//reauthenticated in the meantime. If no previous token is known, an empty +//string should be passed instead to force unconditional reauthentication. +func (client *ProviderClient) Reauthenticate(previousToken string) (err error) { + if client.ReauthFunc == nil { + return nil + } + + if client.mut == nil { + return client.ReauthFunc() } - return map[string]string{"X-Auth-Token": client.TokenID} + client.mut.Lock() + defer client.mut.Unlock() + + client.reauthmut.Lock() + client.reauthmut.reauthing = true + client.reauthmut.Unlock() + + if previousToken == "" || client.TokenID == previousToken { + err = client.ReauthFunc() + } + + client.reauthmut.Lock() + client.reauthmut.reauthing = false + client.reauthmut.Unlock() + return } // RequestOpts customizes the behavior of the provider.Request() method. @@ -166,6 +242,8 @@ func (client *ProviderClient) Request(method, url string, options *RequestOpts) // Set connection parameter to close the connection immediately when we've got the response req.Close = true + prereqtok := req.Header.Get("X-Auth-Token") + // Issue the request. resp, err := client.HTTPClient.Do(req) if err != nil { @@ -189,9 +267,6 @@ func (client *ProviderClient) Request(method, url string, options *RequestOpts) if !ok { body, _ := ioutil.ReadAll(resp.Body) resp.Body.Close() - //pc := make([]uintptr, 1) - //runtime.Callers(2, pc) - //f := runtime.FuncForPC(pc[0]) respErr := ErrUnexpectedResponseCode{ URL: url, Method: method, @@ -199,7 +274,6 @@ func (client *ProviderClient) Request(method, url string, options *RequestOpts) Actual: resp.StatusCode, Body: body, } - //respErr.Function = "gophercloud.ProviderClient.Request" errType := options.ErrorContext switch resp.StatusCode { @@ -210,7 +284,7 @@ func (client *ProviderClient) Request(method, url string, options *RequestOpts) } case http.StatusUnauthorized: if client.ReauthFunc != nil { - err = client.ReauthFunc() + err = client.Reauthenticate(prereqtok) if err != nil { e := &ErrUnableToReauthenticate{} e.ErrOriginal = respErr @@ -240,6 +314,11 @@ func (client *ProviderClient) Request(method, url string, options *RequestOpts) if error401er, ok := errType.(Err401er); ok { err = error401er.Error401(respErr) } + case http.StatusForbidden: + err = ErrDefault403{respErr} + if error403er, ok := errType.(Err403er); ok { + err = error403er.Error403(respErr) + } case http.StatusNotFound: err = ErrDefault404{respErr} if error404er, ok := errType.(Err404er); ok { diff --git a/vendor/github.com/gophercloud/gophercloud/results.go b/vendor/github.com/gophercloud/gophercloud/results.go index e64feee19e..fdd4830ec1 100644 --- a/vendor/github.com/gophercloud/gophercloud/results.go +++ b/vendor/github.com/gophercloud/gophercloud/results.go @@ -345,6 +345,27 @@ func (jt *JSONRFC3339NoZ) UnmarshalJSON(data []byte) error { return nil } +// RFC3339ZNoT is the time format used in Zun (Containers Service). +const RFC3339ZNoT = "2006-01-02 15:04:05-07:00" + +type JSONRFC3339ZNoT time.Time + +func (jt *JSONRFC3339ZNoT) UnmarshalJSON(data []byte) error { + var s string + if err := json.Unmarshal(data, &s); err != nil { + return err + } + if s == "" { + return nil + } + t, err := time.Parse(RFC3339ZNoT, s) + if err != nil { + return err + } + *jt = JSONRFC3339ZNoT(t) + return nil +} + /* Link is an internal type to be used in packages of collection resources that are paginated in a certain way. diff --git a/vendor/github.com/gophercloud/gophercloud/service_client.go b/vendor/github.com/gophercloud/gophercloud/service_client.go index 1160fefa7c..2734510e1b 100644 --- a/vendor/github.com/gophercloud/gophercloud/service_client.go +++ b/vendor/github.com/gophercloud/gophercloud/service_client.go @@ -28,6 +28,10 @@ type ServiceClient struct { // The microversion of the service to use. Set this to use a particular microversion. Microversion string + + // MoreHeaders allows users (or Gophercloud) to set service-wide headers on requests. Put another way, + // values set in this field will be set on all the HTTP requests the service client sends. + MoreHeaders map[string]string } // ResourceBaseURL returns the base URL of any resources used by this service. It MUST end with a /. @@ -108,15 +112,39 @@ func (client *ServiceClient) Delete(url string, opts *RequestOpts) (*http.Respon return client.Request("DELETE", url, opts) } +// Head calls `Request` with the "HEAD" HTTP verb. +func (client *ServiceClient) Head(url string, opts *RequestOpts) (*http.Response, error) { + if opts == nil { + opts = new(RequestOpts) + } + client.initReqOpts(url, nil, nil, opts) + return client.Request("HEAD", url, opts) +} + func (client *ServiceClient) setMicroversionHeader(opts *RequestOpts) { switch client.Type { case "compute": opts.MoreHeaders["X-OpenStack-Nova-API-Version"] = client.Microversion case "sharev2": opts.MoreHeaders["X-OpenStack-Manila-API-Version"] = client.Microversion + case "volume": + opts.MoreHeaders["X-OpenStack-Volume-API-Version"] = client.Microversion } if client.Type != "" { opts.MoreHeaders["OpenStack-API-Version"] = client.Type + " " + client.Microversion } } + +// Request carries out the HTTP operation for the service client +func (client *ServiceClient) Request(method, url string, options *RequestOpts) (*http.Response, error) { + if len(client.MoreHeaders) > 0 { + if options == nil { + options = new(RequestOpts) + } + for k, v := range client.MoreHeaders { + options.MoreHeaders[k] = v + } + } + return client.ProviderClient.Request(method, url, options) +} diff --git a/vendor/github.com/hashicorp/golang-lru/2q.go b/vendor/github.com/hashicorp/golang-lru/2q.go index 337d963296..e474cd0758 100644 --- a/vendor/github.com/hashicorp/golang-lru/2q.go +++ b/vendor/github.com/hashicorp/golang-lru/2q.go @@ -30,9 +30,9 @@ type TwoQueueCache struct { size int recentSize int - recent *simplelru.LRU - frequent *simplelru.LRU - recentEvict *simplelru.LRU + recent simplelru.LRUCache + frequent simplelru.LRUCache + recentEvict simplelru.LRUCache lock sync.RWMutex } @@ -84,7 +84,8 @@ func New2QParams(size int, recentRatio float64, ghostRatio float64) (*TwoQueueCa return c, nil } -func (c *TwoQueueCache) Get(key interface{}) (interface{}, bool) { +// Get looks up a key's value from the cache. +func (c *TwoQueueCache) Get(key interface{}) (value interface{}, ok bool) { c.lock.Lock() defer c.lock.Unlock() @@ -105,6 +106,7 @@ func (c *TwoQueueCache) Get(key interface{}) (interface{}, bool) { return nil, false } +// Add adds a value to the cache. func (c *TwoQueueCache) Add(key, value interface{}) { c.lock.Lock() defer c.lock.Unlock() @@ -160,12 +162,15 @@ func (c *TwoQueueCache) ensureSpace(recentEvict bool) { c.frequent.RemoveOldest() } +// Len returns the number of items in the cache. func (c *TwoQueueCache) Len() int { c.lock.RLock() defer c.lock.RUnlock() return c.recent.Len() + c.frequent.Len() } +// Keys returns a slice of the keys in the cache. +// The frequently used keys are first in the returned slice. func (c *TwoQueueCache) Keys() []interface{} { c.lock.RLock() defer c.lock.RUnlock() @@ -174,6 +179,7 @@ func (c *TwoQueueCache) Keys() []interface{} { return append(k1, k2...) } +// Remove removes the provided key from the cache. func (c *TwoQueueCache) Remove(key interface{}) { c.lock.Lock() defer c.lock.Unlock() @@ -188,6 +194,7 @@ func (c *TwoQueueCache) Remove(key interface{}) { } } +// Purge is used to completely clear the cache. func (c *TwoQueueCache) Purge() { c.lock.Lock() defer c.lock.Unlock() @@ -196,13 +203,17 @@ func (c *TwoQueueCache) Purge() { c.recentEvict.Purge() } +// Contains is used to check if the cache contains a key +// without updating recency or frequency. func (c *TwoQueueCache) Contains(key interface{}) bool { c.lock.RLock() defer c.lock.RUnlock() return c.frequent.Contains(key) || c.recent.Contains(key) } -func (c *TwoQueueCache) Peek(key interface{}) (interface{}, bool) { +// Peek is used to inspect the cache value of a key +// without updating recency or frequency. +func (c *TwoQueueCache) Peek(key interface{}) (value interface{}, ok bool) { c.lock.RLock() defer c.lock.RUnlock() if val, ok := c.frequent.Peek(key); ok { diff --git a/vendor/github.com/hashicorp/golang-lru/2q_test.go b/vendor/github.com/hashicorp/golang-lru/2q_test.go deleted file mode 100644 index 1b0f351817..0000000000 --- a/vendor/github.com/hashicorp/golang-lru/2q_test.go +++ /dev/null @@ -1,306 +0,0 @@ -package lru - -import ( - "math/rand" - "testing" -) - -func Benchmark2Q_Rand(b *testing.B) { - l, err := New2Q(8192) - if err != nil { - b.Fatalf("err: %v", err) - } - - trace := make([]int64, b.N*2) - for i := 0; i < b.N*2; i++ { - trace[i] = rand.Int63() % 32768 - } - - b.ResetTimer() - - var hit, miss int - for i := 0; i < 2*b.N; i++ { - if i%2 == 0 { - l.Add(trace[i], trace[i]) - } else { - _, ok := l.Get(trace[i]) - if ok { - hit++ - } else { - miss++ - } - } - } - b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) -} - -func Benchmark2Q_Freq(b *testing.B) { - l, err := New2Q(8192) - if err != nil { - b.Fatalf("err: %v", err) - } - - trace := make([]int64, b.N*2) - for i := 0; i < b.N*2; i++ { - if i%2 == 0 { - trace[i] = rand.Int63() % 16384 - } else { - trace[i] = rand.Int63() % 32768 - } - } - - b.ResetTimer() - - for i := 0; i < b.N; i++ { - l.Add(trace[i], trace[i]) - } - var hit, miss int - for i := 0; i < b.N; i++ { - _, ok := l.Get(trace[i]) - if ok { - hit++ - } else { - miss++ - } - } - b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) -} - -func Test2Q_RandomOps(t *testing.T) { - size := 128 - l, err := New2Q(128) - if err != nil { - t.Fatalf("err: %v", err) - } - - n := 200000 - for i := 0; i < n; i++ { - key := rand.Int63() % 512 - r := rand.Int63() - switch r % 3 { - case 0: - l.Add(key, key) - case 1: - l.Get(key) - case 2: - l.Remove(key) - } - - if l.recent.Len()+l.frequent.Len() > size { - t.Fatalf("bad: recent: %d freq: %d", - l.recent.Len(), l.frequent.Len()) - } - } -} - -func Test2Q_Get_RecentToFrequent(t *testing.T) { - l, err := New2Q(128) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Touch all the entries, should be in t1 - for i := 0; i < 128; i++ { - l.Add(i, i) - } - if n := l.recent.Len(); n != 128 { - t.Fatalf("bad: %d", n) - } - if n := l.frequent.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - - // Get should upgrade to t2 - for i := 0; i < 128; i++ { - _, ok := l.Get(i) - if !ok { - t.Fatalf("missing: %d", i) - } - } - if n := l.recent.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if n := l.frequent.Len(); n != 128 { - t.Fatalf("bad: %d", n) - } - - // Get be from t2 - for i := 0; i < 128; i++ { - _, ok := l.Get(i) - if !ok { - t.Fatalf("missing: %d", i) - } - } - if n := l.recent.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if n := l.frequent.Len(); n != 128 { - t.Fatalf("bad: %d", n) - } -} - -func Test2Q_Add_RecentToFrequent(t *testing.T) { - l, err := New2Q(128) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Add initially to recent - l.Add(1, 1) - if n := l.recent.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - if n := l.frequent.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - - // Add should upgrade to frequent - l.Add(1, 1) - if n := l.recent.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if n := l.frequent.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - - // Add should remain in frequent - l.Add(1, 1) - if n := l.recent.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if n := l.frequent.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } -} - -func Test2Q_Add_RecentEvict(t *testing.T) { - l, err := New2Q(4) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Add 1,2,3,4,5 -> Evict 1 - l.Add(1, 1) - l.Add(2, 2) - l.Add(3, 3) - l.Add(4, 4) - l.Add(5, 5) - if n := l.recent.Len(); n != 4 { - t.Fatalf("bad: %d", n) - } - if n := l.recentEvict.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - if n := l.frequent.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - - // Pull in the recently evicted - l.Add(1, 1) - if n := l.recent.Len(); n != 3 { - t.Fatalf("bad: %d", n) - } - if n := l.recentEvict.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - if n := l.frequent.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - - // Add 6, should cause another recent evict - l.Add(6, 6) - if n := l.recent.Len(); n != 3 { - t.Fatalf("bad: %d", n) - } - if n := l.recentEvict.Len(); n != 2 { - t.Fatalf("bad: %d", n) - } - if n := l.frequent.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } -} - -func Test2Q(t *testing.T) { - l, err := New2Q(128) - if err != nil { - t.Fatalf("err: %v", err) - } - - for i := 0; i < 256; i++ { - l.Add(i, i) - } - if l.Len() != 128 { - t.Fatalf("bad len: %v", l.Len()) - } - - for i, k := range l.Keys() { - if v, ok := l.Get(k); !ok || v != k || v != i+128 { - t.Fatalf("bad key: %v", k) - } - } - for i := 0; i < 128; i++ { - _, ok := l.Get(i) - if ok { - t.Fatalf("should be evicted") - } - } - for i := 128; i < 256; i++ { - _, ok := l.Get(i) - if !ok { - t.Fatalf("should not be evicted") - } - } - for i := 128; i < 192; i++ { - l.Remove(i) - _, ok := l.Get(i) - if ok { - t.Fatalf("should be deleted") - } - } - - l.Purge() - if l.Len() != 0 { - t.Fatalf("bad len: %v", l.Len()) - } - if _, ok := l.Get(200); ok { - t.Fatalf("should contain nothing") - } -} - -// Test that Contains doesn't update recent-ness -func Test2Q_Contains(t *testing.T) { - l, err := New2Q(2) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - if !l.Contains(1) { - t.Errorf("1 should be contained") - } - - l.Add(3, 3) - if l.Contains(1) { - t.Errorf("Contains should not have updated recent-ness of 1") - } -} - -// Test that Peek doesn't update recent-ness -func Test2Q_Peek(t *testing.T) { - l, err := New2Q(2) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - if v, ok := l.Peek(1); !ok || v != 1 { - t.Errorf("1 should be set to 1: %v, %v", v, ok) - } - - l.Add(3, 3) - if l.Contains(1) { - t.Errorf("should not have updated recent-ness of 1") - } -} diff --git a/vendor/github.com/hashicorp/golang-lru/arc.go b/vendor/github.com/hashicorp/golang-lru/arc.go index a2a2528173..555225a218 100644 --- a/vendor/github.com/hashicorp/golang-lru/arc.go +++ b/vendor/github.com/hashicorp/golang-lru/arc.go @@ -18,11 +18,11 @@ type ARCCache struct { size int // Size is the total capacity of the cache p int // P is the dynamic preference towards T1 or T2 - t1 *simplelru.LRU // T1 is the LRU for recently accessed items - b1 *simplelru.LRU // B1 is the LRU for evictions from t1 + t1 simplelru.LRUCache // T1 is the LRU for recently accessed items + b1 simplelru.LRUCache // B1 is the LRU for evictions from t1 - t2 *simplelru.LRU // T2 is the LRU for frequently accessed items - b2 *simplelru.LRU // B2 is the LRU for evictions from t2 + t2 simplelru.LRUCache // T2 is the LRU for frequently accessed items + b2 simplelru.LRUCache // B2 is the LRU for evictions from t2 lock sync.RWMutex } @@ -60,11 +60,11 @@ func NewARC(size int) (*ARCCache, error) { } // Get looks up a key's value from the cache. -func (c *ARCCache) Get(key interface{}) (interface{}, bool) { +func (c *ARCCache) Get(key interface{}) (value interface{}, ok bool) { c.lock.Lock() defer c.lock.Unlock() - // Ff the value is contained in T1 (recent), then + // If the value is contained in T1 (recent), then // promote it to T2 (frequent) if val, ok := c.t1.Peek(key); ok { c.t1.Remove(key) @@ -153,7 +153,7 @@ func (c *ARCCache) Add(key, value interface{}) { // Remove from B2 c.b2.Remove(key) - // Add the key to the frequntly used list + // Add the key to the frequently used list c.t2.Add(key, value) return } @@ -247,7 +247,7 @@ func (c *ARCCache) Contains(key interface{}) bool { // Peek is used to inspect the cache value of a key // without updating recency or frequency. -func (c *ARCCache) Peek(key interface{}) (interface{}, bool) { +func (c *ARCCache) Peek(key interface{}) (value interface{}, ok bool) { c.lock.RLock() defer c.lock.RUnlock() if val, ok := c.t1.Peek(key); ok { diff --git a/vendor/github.com/hashicorp/golang-lru/arc_test.go b/vendor/github.com/hashicorp/golang-lru/arc_test.go deleted file mode 100644 index e2d9b68c6a..0000000000 --- a/vendor/github.com/hashicorp/golang-lru/arc_test.go +++ /dev/null @@ -1,377 +0,0 @@ -package lru - -import ( - "math/rand" - "testing" - "time" -) - -func init() { - rand.Seed(time.Now().Unix()) -} - -func BenchmarkARC_Rand(b *testing.B) { - l, err := NewARC(8192) - if err != nil { - b.Fatalf("err: %v", err) - } - - trace := make([]int64, b.N*2) - for i := 0; i < b.N*2; i++ { - trace[i] = rand.Int63() % 32768 - } - - b.ResetTimer() - - var hit, miss int - for i := 0; i < 2*b.N; i++ { - if i%2 == 0 { - l.Add(trace[i], trace[i]) - } else { - _, ok := l.Get(trace[i]) - if ok { - hit++ - } else { - miss++ - } - } - } - b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) -} - -func BenchmarkARC_Freq(b *testing.B) { - l, err := NewARC(8192) - if err != nil { - b.Fatalf("err: %v", err) - } - - trace := make([]int64, b.N*2) - for i := 0; i < b.N*2; i++ { - if i%2 == 0 { - trace[i] = rand.Int63() % 16384 - } else { - trace[i] = rand.Int63() % 32768 - } - } - - b.ResetTimer() - - for i := 0; i < b.N; i++ { - l.Add(trace[i], trace[i]) - } - var hit, miss int - for i := 0; i < b.N; i++ { - _, ok := l.Get(trace[i]) - if ok { - hit++ - } else { - miss++ - } - } - b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) -} - -func TestARC_RandomOps(t *testing.T) { - size := 128 - l, err := NewARC(128) - if err != nil { - t.Fatalf("err: %v", err) - } - - n := 200000 - for i := 0; i < n; i++ { - key := rand.Int63() % 512 - r := rand.Int63() - switch r % 3 { - case 0: - l.Add(key, key) - case 1: - l.Get(key) - case 2: - l.Remove(key) - } - - if l.t1.Len()+l.t2.Len() > size { - t.Fatalf("bad: t1: %d t2: %d b1: %d b2: %d p: %d", - l.t1.Len(), l.t2.Len(), l.b1.Len(), l.b2.Len(), l.p) - } - if l.b1.Len()+l.b2.Len() > size { - t.Fatalf("bad: t1: %d t2: %d b1: %d b2: %d p: %d", - l.t1.Len(), l.t2.Len(), l.b1.Len(), l.b2.Len(), l.p) - } - } -} - -func TestARC_Get_RecentToFrequent(t *testing.T) { - l, err := NewARC(128) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Touch all the entries, should be in t1 - for i := 0; i < 128; i++ { - l.Add(i, i) - } - if n := l.t1.Len(); n != 128 { - t.Fatalf("bad: %d", n) - } - if n := l.t2.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - - // Get should upgrade to t2 - for i := 0; i < 128; i++ { - _, ok := l.Get(i) - if !ok { - t.Fatalf("missing: %d", i) - } - } - if n := l.t1.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if n := l.t2.Len(); n != 128 { - t.Fatalf("bad: %d", n) - } - - // Get be from t2 - for i := 0; i < 128; i++ { - _, ok := l.Get(i) - if !ok { - t.Fatalf("missing: %d", i) - } - } - if n := l.t1.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if n := l.t2.Len(); n != 128 { - t.Fatalf("bad: %d", n) - } -} - -func TestARC_Add_RecentToFrequent(t *testing.T) { - l, err := NewARC(128) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Add initially to t1 - l.Add(1, 1) - if n := l.t1.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - if n := l.t2.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - - // Add should upgrade to t2 - l.Add(1, 1) - if n := l.t1.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if n := l.t2.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - - // Add should remain in t2 - l.Add(1, 1) - if n := l.t1.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if n := l.t2.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } -} - -func TestARC_Adaptive(t *testing.T) { - l, err := NewARC(4) - if err != nil { - t.Fatalf("err: %v", err) - } - - // Fill t1 - for i := 0; i < 4; i++ { - l.Add(i, i) - } - if n := l.t1.Len(); n != 4 { - t.Fatalf("bad: %d", n) - } - - // Move to t2 - l.Get(0) - l.Get(1) - if n := l.t2.Len(); n != 2 { - t.Fatalf("bad: %d", n) - } - - // Evict from t1 - l.Add(4, 4) - if n := l.b1.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - - // Current state - // t1 : (MRU) [4, 3] (LRU) - // t2 : (MRU) [1, 0] (LRU) - // b1 : (MRU) [2] (LRU) - // b2 : (MRU) [] (LRU) - - // Add 2, should cause hit on b1 - l.Add(2, 2) - if n := l.b1.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - if l.p != 1 { - t.Fatalf("bad: %d", l.p) - } - if n := l.t2.Len(); n != 3 { - t.Fatalf("bad: %d", n) - } - - // Current state - // t1 : (MRU) [4] (LRU) - // t2 : (MRU) [2, 1, 0] (LRU) - // b1 : (MRU) [3] (LRU) - // b2 : (MRU) [] (LRU) - - // Add 4, should migrate to t2 - l.Add(4, 4) - if n := l.t1.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if n := l.t2.Len(); n != 4 { - t.Fatalf("bad: %d", n) - } - - // Current state - // t1 : (MRU) [] (LRU) - // t2 : (MRU) [4, 2, 1, 0] (LRU) - // b1 : (MRU) [3] (LRU) - // b2 : (MRU) [] (LRU) - - // Add 4, should evict to b2 - l.Add(5, 5) - if n := l.t1.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - if n := l.t2.Len(); n != 3 { - t.Fatalf("bad: %d", n) - } - if n := l.b2.Len(); n != 1 { - t.Fatalf("bad: %d", n) - } - - // Current state - // t1 : (MRU) [5] (LRU) - // t2 : (MRU) [4, 2, 1] (LRU) - // b1 : (MRU) [3] (LRU) - // b2 : (MRU) [0] (LRU) - - // Add 0, should decrease p - l.Add(0, 0) - if n := l.t1.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if n := l.t2.Len(); n != 4 { - t.Fatalf("bad: %d", n) - } - if n := l.b1.Len(); n != 2 { - t.Fatalf("bad: %d", n) - } - if n := l.b2.Len(); n != 0 { - t.Fatalf("bad: %d", n) - } - if l.p != 0 { - t.Fatalf("bad: %d", l.p) - } - - // Current state - // t1 : (MRU) [] (LRU) - // t2 : (MRU) [0, 4, 2, 1] (LRU) - // b1 : (MRU) [5, 3] (LRU) - // b2 : (MRU) [0] (LRU) -} - -func TestARC(t *testing.T) { - l, err := NewARC(128) - if err != nil { - t.Fatalf("err: %v", err) - } - - for i := 0; i < 256; i++ { - l.Add(i, i) - } - if l.Len() != 128 { - t.Fatalf("bad len: %v", l.Len()) - } - - for i, k := range l.Keys() { - if v, ok := l.Get(k); !ok || v != k || v != i+128 { - t.Fatalf("bad key: %v", k) - } - } - for i := 0; i < 128; i++ { - _, ok := l.Get(i) - if ok { - t.Fatalf("should be evicted") - } - } - for i := 128; i < 256; i++ { - _, ok := l.Get(i) - if !ok { - t.Fatalf("should not be evicted") - } - } - for i := 128; i < 192; i++ { - l.Remove(i) - _, ok := l.Get(i) - if ok { - t.Fatalf("should be deleted") - } - } - - l.Purge() - if l.Len() != 0 { - t.Fatalf("bad len: %v", l.Len()) - } - if _, ok := l.Get(200); ok { - t.Fatalf("should contain nothing") - } -} - -// Test that Contains doesn't update recent-ness -func TestARC_Contains(t *testing.T) { - l, err := NewARC(2) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - if !l.Contains(1) { - t.Errorf("1 should be contained") - } - - l.Add(3, 3) - if l.Contains(1) { - t.Errorf("Contains should not have updated recent-ness of 1") - } -} - -// Test that Peek doesn't update recent-ness -func TestARC_Peek(t *testing.T) { - l, err := NewARC(2) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - if v, ok := l.Peek(1); !ok || v != 1 { - t.Errorf("1 should be set to 1: %v, %v", v, ok) - } - - l.Add(3, 3) - if l.Contains(1) { - t.Errorf("should not have updated recent-ness of 1") - } -} diff --git a/vendor/github.com/hashicorp/golang-lru/doc.go b/vendor/github.com/hashicorp/golang-lru/doc.go new file mode 100644 index 0000000000..2547df979d --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/doc.go @@ -0,0 +1,21 @@ +// Package lru provides three different LRU caches of varying sophistication. +// +// Cache is a simple LRU cache. It is based on the +// LRU implementation in groupcache: +// https://github.com/golang/groupcache/tree/master/lru +// +// TwoQueueCache tracks frequently used and recently used entries separately. +// This avoids a burst of accesses from taking out frequently used entries, +// at the cost of about 2x computational overhead and some extra bookkeeping. +// +// ARCCache is an adaptive replacement cache. It tracks recent evictions as +// well as recent usage in both the frequent and recent caches. Its +// computational overhead is comparable to TwoQueueCache, but the memory +// overhead is linear with the size of the cache. +// +// ARC has been patented by IBM, so do not use it if that is problematic for +// your program. +// +// All caches in this package take locks while operating, and are therefore +// thread-safe for consumers. +package lru diff --git a/vendor/github.com/hashicorp/golang-lru/lru.go b/vendor/github.com/hashicorp/golang-lru/lru.go index a6285f989e..c8d9b0a230 100644 --- a/vendor/github.com/hashicorp/golang-lru/lru.go +++ b/vendor/github.com/hashicorp/golang-lru/lru.go @@ -1,6 +1,3 @@ -// This package provides a simple LRU cache. It is based on the -// LRU implementation in groupcache: -// https://github.com/golang/groupcache/tree/master/lru package lru import ( @@ -11,11 +8,11 @@ import ( // Cache is a thread-safe fixed size LRU cache. type Cache struct { - lru *simplelru.LRU + lru simplelru.LRUCache lock sync.RWMutex } -// New creates an LRU of the given size +// New creates an LRU of the given size. func New(size int) (*Cache, error) { return NewWithEvict(size, nil) } @@ -33,7 +30,7 @@ func NewWithEvict(size int, onEvicted func(key interface{}, value interface{})) return c, nil } -// Purge is used to completely clear the cache +// Purge is used to completely clear the cache. func (c *Cache) Purge() { c.lock.Lock() c.lru.Purge() @@ -41,30 +38,30 @@ func (c *Cache) Purge() { } // Add adds a value to the cache. Returns true if an eviction occurred. -func (c *Cache) Add(key, value interface{}) bool { +func (c *Cache) Add(key, value interface{}) (evicted bool) { c.lock.Lock() defer c.lock.Unlock() return c.lru.Add(key, value) } // Get looks up a key's value from the cache. -func (c *Cache) Get(key interface{}) (interface{}, bool) { +func (c *Cache) Get(key interface{}) (value interface{}, ok bool) { c.lock.Lock() defer c.lock.Unlock() return c.lru.Get(key) } -// Check if a key is in the cache, without updating the recent-ness -// or deleting it for being stale. +// Contains checks if a key is in the cache, without updating the +// recent-ness or deleting it for being stale. func (c *Cache) Contains(key interface{}) bool { c.lock.RLock() defer c.lock.RUnlock() return c.lru.Contains(key) } -// Returns the key value (or undefined if not found) without updating +// Peek returns the key value (or undefined if not found) without updating // the "recently used"-ness of the key. -func (c *Cache) Peek(key interface{}) (interface{}, bool) { +func (c *Cache) Peek(key interface{}) (value interface{}, ok bool) { c.lock.RLock() defer c.lock.RUnlock() return c.lru.Peek(key) @@ -73,16 +70,15 @@ func (c *Cache) Peek(key interface{}) (interface{}, bool) { // ContainsOrAdd checks if a key is in the cache without updating the // recent-ness or deleting it for being stale, and if not, adds the value. // Returns whether found and whether an eviction occurred. -func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evict bool) { +func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evicted bool) { c.lock.Lock() defer c.lock.Unlock() if c.lru.Contains(key) { return true, false - } else { - evict := c.lru.Add(key, value) - return false, evict } + evicted = c.lru.Add(key, value) + return false, evicted } // Remove removes the provided key from the cache. diff --git a/vendor/github.com/hashicorp/golang-lru/lru_test.go b/vendor/github.com/hashicorp/golang-lru/lru_test.go deleted file mode 100644 index 2b31218b07..0000000000 --- a/vendor/github.com/hashicorp/golang-lru/lru_test.go +++ /dev/null @@ -1,221 +0,0 @@ -package lru - -import ( - "math/rand" - "testing" -) - -func BenchmarkLRU_Rand(b *testing.B) { - l, err := New(8192) - if err != nil { - b.Fatalf("err: %v", err) - } - - trace := make([]int64, b.N*2) - for i := 0; i < b.N*2; i++ { - trace[i] = rand.Int63() % 32768 - } - - b.ResetTimer() - - var hit, miss int - for i := 0; i < 2*b.N; i++ { - if i%2 == 0 { - l.Add(trace[i], trace[i]) - } else { - _, ok := l.Get(trace[i]) - if ok { - hit++ - } else { - miss++ - } - } - } - b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) -} - -func BenchmarkLRU_Freq(b *testing.B) { - l, err := New(8192) - if err != nil { - b.Fatalf("err: %v", err) - } - - trace := make([]int64, b.N*2) - for i := 0; i < b.N*2; i++ { - if i%2 == 0 { - trace[i] = rand.Int63() % 16384 - } else { - trace[i] = rand.Int63() % 32768 - } - } - - b.ResetTimer() - - for i := 0; i < b.N; i++ { - l.Add(trace[i], trace[i]) - } - var hit, miss int - for i := 0; i < b.N; i++ { - _, ok := l.Get(trace[i]) - if ok { - hit++ - } else { - miss++ - } - } - b.Logf("hit: %d miss: %d ratio: %f", hit, miss, float64(hit)/float64(miss)) -} - -func TestLRU(t *testing.T) { - evictCounter := 0 - onEvicted := func(k interface{}, v interface{}) { - if k != v { - t.Fatalf("Evict values not equal (%v!=%v)", k, v) - } - evictCounter += 1 - } - l, err := NewWithEvict(128, onEvicted) - if err != nil { - t.Fatalf("err: %v", err) - } - - for i := 0; i < 256; i++ { - l.Add(i, i) - } - if l.Len() != 128 { - t.Fatalf("bad len: %v", l.Len()) - } - - if evictCounter != 128 { - t.Fatalf("bad evict count: %v", evictCounter) - } - - for i, k := range l.Keys() { - if v, ok := l.Get(k); !ok || v != k || v != i+128 { - t.Fatalf("bad key: %v", k) - } - } - for i := 0; i < 128; i++ { - _, ok := l.Get(i) - if ok { - t.Fatalf("should be evicted") - } - } - for i := 128; i < 256; i++ { - _, ok := l.Get(i) - if !ok { - t.Fatalf("should not be evicted") - } - } - for i := 128; i < 192; i++ { - l.Remove(i) - _, ok := l.Get(i) - if ok { - t.Fatalf("should be deleted") - } - } - - l.Get(192) // expect 192 to be last key in l.Keys() - - for i, k := range l.Keys() { - if (i < 63 && k != i+193) || (i == 63 && k != 192) { - t.Fatalf("out of order key: %v", k) - } - } - - l.Purge() - if l.Len() != 0 { - t.Fatalf("bad len: %v", l.Len()) - } - if _, ok := l.Get(200); ok { - t.Fatalf("should contain nothing") - } -} - -// test that Add returns true/false if an eviction occurred -func TestLRUAdd(t *testing.T) { - evictCounter := 0 - onEvicted := func(k interface{}, v interface{}) { - evictCounter += 1 - } - - l, err := NewWithEvict(1, onEvicted) - if err != nil { - t.Fatalf("err: %v", err) - } - - if l.Add(1, 1) == true || evictCounter != 0 { - t.Errorf("should not have an eviction") - } - if l.Add(2, 2) == false || evictCounter != 1 { - t.Errorf("should have an eviction") - } -} - -// test that Contains doesn't update recent-ness -func TestLRUContains(t *testing.T) { - l, err := New(2) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - if !l.Contains(1) { - t.Errorf("1 should be contained") - } - - l.Add(3, 3) - if l.Contains(1) { - t.Errorf("Contains should not have updated recent-ness of 1") - } -} - -// test that Contains doesn't update recent-ness -func TestLRUContainsOrAdd(t *testing.T) { - l, err := New(2) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - contains, evict := l.ContainsOrAdd(1, 1) - if !contains { - t.Errorf("1 should be contained") - } - if evict { - t.Errorf("nothing should be evicted here") - } - - l.Add(3, 3) - contains, evict = l.ContainsOrAdd(1, 1) - if contains { - t.Errorf("1 should not have been contained") - } - if !evict { - t.Errorf("an eviction should have occurred") - } - if !l.Contains(1) { - t.Errorf("now 1 should be contained") - } -} - -// test that Peek doesn't update recent-ness -func TestLRUPeek(t *testing.T) { - l, err := New(2) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - if v, ok := l.Peek(1); !ok || v != 1 { - t.Errorf("1 should be set to 1: %v, %v", v, ok) - } - - l.Add(3, 3) - if l.Contains(1) { - t.Errorf("should not have updated recent-ness of 1") - } -} diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go index cb416b394f..5673773b22 100644 --- a/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go +++ b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go @@ -36,7 +36,7 @@ func NewLRU(size int, onEvict EvictCallback) (*LRU, error) { return c, nil } -// Purge is used to completely clear the cache +// Purge is used to completely clear the cache. func (c *LRU) Purge() { for k, v := range c.items { if c.onEvict != nil { @@ -48,7 +48,7 @@ func (c *LRU) Purge() { } // Add adds a value to the cache. Returns true if an eviction occurred. -func (c *LRU) Add(key, value interface{}) bool { +func (c *LRU) Add(key, value interface{}) (evicted bool) { // Check for existing item if ent, ok := c.items[key]; ok { c.evictList.MoveToFront(ent) @@ -78,17 +78,18 @@ func (c *LRU) Get(key interface{}) (value interface{}, ok bool) { return } -// Check if a key is in the cache, without updating the recent-ness +// Contains checks if a key is in the cache, without updating the recent-ness // or deleting it for being stale. func (c *LRU) Contains(key interface{}) (ok bool) { _, ok = c.items[key] return ok } -// Returns the key value (or undefined if not found) without updating +// Peek returns the key value (or undefined if not found) without updating // the "recently used"-ness of the key. func (c *LRU) Peek(key interface{}) (value interface{}, ok bool) { - if ent, ok := c.items[key]; ok { + var ent *list.Element + if ent, ok = c.items[key]; ok { return ent.Value.(*entry).value, true } return nil, ok @@ -96,7 +97,7 @@ func (c *LRU) Peek(key interface{}) (value interface{}, ok bool) { // Remove removes the provided key from the cache, returning if the // key was contained. -func (c *LRU) Remove(key interface{}) bool { +func (c *LRU) Remove(key interface{}) (present bool) { if ent, ok := c.items[key]; ok { c.removeElement(ent) return true @@ -105,7 +106,7 @@ func (c *LRU) Remove(key interface{}) bool { } // RemoveOldest removes the oldest item from the cache. -func (c *LRU) RemoveOldest() (interface{}, interface{}, bool) { +func (c *LRU) RemoveOldest() (key interface{}, value interface{}, ok bool) { ent := c.evictList.Back() if ent != nil { c.removeElement(ent) @@ -116,7 +117,7 @@ func (c *LRU) RemoveOldest() (interface{}, interface{}, bool) { } // GetOldest returns the oldest entry -func (c *LRU) GetOldest() (interface{}, interface{}, bool) { +func (c *LRU) GetOldest() (key interface{}, value interface{}, ok bool) { ent := c.evictList.Back() if ent != nil { kv := ent.Value.(*entry) diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go new file mode 100644 index 0000000000..744cac01c6 --- /dev/null +++ b/vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go @@ -0,0 +1,37 @@ +package simplelru + + +// LRUCache is the interface for simple LRU cache. +type LRUCache interface { + // Adds a value to the cache, returns true if an eviction occurred and + // updates the "recently used"-ness of the key. + Add(key, value interface{}) bool + + // Returns key's value from the cache and + // updates the "recently used"-ness of the key. #value, isFound + Get(key interface{}) (value interface{}, ok bool) + + // Check if a key exsists in cache without updating the recent-ness. + Contains(key interface{}) (ok bool) + + // Returns key's value without updating the "recently used"-ness of the key. + Peek(key interface{}) (value interface{}, ok bool) + + // Removes a key from the cache. + Remove(key interface{}) bool + + // Removes the oldest entry from cache. + RemoveOldest() (interface{}, interface{}, bool) + + // Returns the oldest entry from the cache. #key, value, isFound + GetOldest() (interface{}, interface{}, bool) + + // Returns a slice of the keys in the cache, from oldest to newest. + Keys() []interface{} + + // Returns the number of items in the cache. + Len() int + + // Clear all cache entries + Purge() +} diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru_test.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru_test.go deleted file mode 100644 index a958934f64..0000000000 --- a/vendor/github.com/hashicorp/golang-lru/simplelru/lru_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package simplelru - -import "testing" - -func TestLRU(t *testing.T) { - evictCounter := 0 - onEvicted := func(k interface{}, v interface{}) { - if k != v { - t.Fatalf("Evict values not equal (%v!=%v)", k, v) - } - evictCounter += 1 - } - l, err := NewLRU(128, onEvicted) - if err != nil { - t.Fatalf("err: %v", err) - } - - for i := 0; i < 256; i++ { - l.Add(i, i) - } - if l.Len() != 128 { - t.Fatalf("bad len: %v", l.Len()) - } - - if evictCounter != 128 { - t.Fatalf("bad evict count: %v", evictCounter) - } - - for i, k := range l.Keys() { - if v, ok := l.Get(k); !ok || v != k || v != i+128 { - t.Fatalf("bad key: %v", k) - } - } - for i := 0; i < 128; i++ { - _, ok := l.Get(i) - if ok { - t.Fatalf("should be evicted") - } - } - for i := 128; i < 256; i++ { - _, ok := l.Get(i) - if !ok { - t.Fatalf("should not be evicted") - } - } - for i := 128; i < 192; i++ { - ok := l.Remove(i) - if !ok { - t.Fatalf("should be contained") - } - ok = l.Remove(i) - if ok { - t.Fatalf("should not be contained") - } - _, ok = l.Get(i) - if ok { - t.Fatalf("should be deleted") - } - } - - l.Get(192) // expect 192 to be last key in l.Keys() - - for i, k := range l.Keys() { - if (i < 63 && k != i+193) || (i == 63 && k != 192) { - t.Fatalf("out of order key: %v", k) - } - } - - l.Purge() - if l.Len() != 0 { - t.Fatalf("bad len: %v", l.Len()) - } - if _, ok := l.Get(200); ok { - t.Fatalf("should contain nothing") - } -} - -func TestLRU_GetOldest_RemoveOldest(t *testing.T) { - l, err := NewLRU(128, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - for i := 0; i < 256; i++ { - l.Add(i, i) - } - k, _, ok := l.GetOldest() - if !ok { - t.Fatalf("missing") - } - if k.(int) != 128 { - t.Fatalf("bad: %v", k) - } - - k, _, ok = l.RemoveOldest() - if !ok { - t.Fatalf("missing") - } - if k.(int) != 128 { - t.Fatalf("bad: %v", k) - } - - k, _, ok = l.RemoveOldest() - if !ok { - t.Fatalf("missing") - } - if k.(int) != 129 { - t.Fatalf("bad: %v", k) - } -} - -// Test that Add returns true/false if an eviction occurred -func TestLRU_Add(t *testing.T) { - evictCounter := 0 - onEvicted := func(k interface{}, v interface{}) { - evictCounter += 1 - } - - l, err := NewLRU(1, onEvicted) - if err != nil { - t.Fatalf("err: %v", err) - } - - if l.Add(1, 1) == true || evictCounter != 0 { - t.Errorf("should not have an eviction") - } - if l.Add(2, 2) == false || evictCounter != 1 { - t.Errorf("should have an eviction") - } -} - -// Test that Contains doesn't update recent-ness -func TestLRU_Contains(t *testing.T) { - l, err := NewLRU(2, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - if !l.Contains(1) { - t.Errorf("1 should be contained") - } - - l.Add(3, 3) - if l.Contains(1) { - t.Errorf("Contains should not have updated recent-ness of 1") - } -} - -// Test that Peek doesn't update recent-ness -func TestLRU_Peek(t *testing.T) { - l, err := NewLRU(2, nil) - if err != nil { - t.Fatalf("err: %v", err) - } - - l.Add(1, 1) - l.Add(2, 2) - if v, ok := l.Peek(1); !ok || v != 1 { - t.Errorf("1 should be set to 1: %v, %v", v, ok) - } - - l.Add(3, 3) - if l.Contains(1) { - t.Errorf("should not have updated recent-ness of 1") - } -} diff --git a/vendor/github.com/howeyc/gopass/pass_test.go b/vendor/github.com/howeyc/gopass/pass_test.go deleted file mode 100644 index 7ac3151357..0000000000 --- a/vendor/github.com/howeyc/gopass/pass_test.go +++ /dev/null @@ -1,225 +0,0 @@ -package gopass - -import ( - "bufio" - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "testing" - "time" -) - -// TestGetPasswd tests the password creation and output based on a byte buffer -// as input to mock the underlying getch() methods. -func TestGetPasswd(t *testing.T) { - type testData struct { - input []byte - - // Due to how backspaces are written, it is easier to manually write - // each expected output for the masked cases. - masked string - password string - byesLeft int - reason string - } - - ds := []testData{ - testData{[]byte("abc\n"), "***", "abc", 0, "Password parsing should stop at \\n"}, - testData{[]byte("abc\r"), "***", "abc", 0, "Password parsing should stop at \\r"}, - testData{[]byte("a\nbc\n"), "*", "a", 3, "Password parsing should stop at \\n"}, - testData{[]byte("*!]|\n"), "****", "*!]|", 0, "Special characters shouldn't affect the password."}, - - testData{[]byte("abc\r\n"), "***", "abc", 1, - "Password parsing should stop at \\r; Windows LINE_MODE should be unset so \\r is not converted to \\r\\n."}, - - testData{[]byte{'a', 'b', 'c', 8, '\n'}, "***\b \b", "ab", 0, "Backspace byte should remove the last read byte."}, - testData{[]byte{'a', 'b', 127, 'c', '\n'}, "**\b \b*", "ac", 0, "Delete byte should remove the last read byte."}, - testData{[]byte{'a', 'b', 127, 'c', 8, 127, '\n'}, "**\b \b*\b \b\b \b", "", 0, "Successive deletes continue to delete."}, - testData{[]byte{8, 8, 8, '\n'}, "", "", 0, "Deletes before characters are noops."}, - testData{[]byte{8, 8, 8, 'a', 'b', 'c', '\n'}, "***", "abc", 0, "Deletes before characters are noops."}, - - testData{[]byte{'a', 'b', 0, 'c', '\n'}, "***", "abc", 0, - "Nil byte should be ignored due; may get unintended nil bytes from syscalls on Windows."}, - } - - // Redirecting output for tests as they print to os.Stdout but we want to - // capture and test the output. - for _, masked := range []bool{true, false} { - for _, d := range ds { - pipeBytesToStdin(d.input) - - r, w, err := os.Pipe() - if err != nil { - t.Fatal(err.Error()) - } - - result, err := getPasswd("", masked, os.Stdin, w) - if err != nil { - t.Errorf("Error getting password: %s", err.Error()) - } - leftOnBuffer := flushStdin() - - // Test output (masked and unmasked). Delete/backspace actually - // deletes, overwrites and deletes again. As a result, we need to - // remove those from the pipe afterwards to mimic the console's - // interpretation of those bytes. - w.Close() - output, err := ioutil.ReadAll(r) - if err != nil { - t.Fatal(err.Error()) - } - var expectedOutput []byte - if masked { - expectedOutput = []byte(d.masked) - } else { - expectedOutput = []byte("") - } - if bytes.Compare(expectedOutput, output) != 0 { - t.Errorf("Expected output to equal %v (%q) but got %v (%q) instead when masked=%v. %s", expectedOutput, string(expectedOutput), output, string(output), masked, d.reason) - } - - if string(result) != d.password { - t.Errorf("Expected %q but got %q instead when masked=%v. %s", d.password, result, masked, d.reason) - } - - if leftOnBuffer != d.byesLeft { - t.Errorf("Expected %v bytes left on buffer but instead got %v when masked=%v. %s", d.byesLeft, leftOnBuffer, masked, d.reason) - } - } - } -} - -// TestPipe ensures we get our expected pipe behavior. -func TestPipe(t *testing.T) { - type testData struct { - input string - password string - expError error - } - ds := []testData{ - testData{"abc", "abc", io.EOF}, - testData{"abc\n", "abc", nil}, - testData{"abc\r", "abc", nil}, - testData{"abc\r\n", "abc", nil}, - } - - for _, d := range ds { - _, err := pipeToStdin(d.input) - if err != nil { - t.Log("Error writing input to stdin:", err) - t.FailNow() - } - pass, err := GetPasswd() - if string(pass) != d.password { - t.Errorf("Expected %q but got %q instead.", d.password, string(pass)) - } - if err != d.expError { - t.Errorf("Expected %v but got %q instead.", d.expError, err) - } - } -} - -// flushStdin reads from stdin for .5 seconds to ensure no bytes are left on -// the buffer. Returns the number of bytes read. -func flushStdin() int { - ch := make(chan byte) - go func(ch chan byte) { - reader := bufio.NewReader(os.Stdin) - for { - b, err := reader.ReadByte() - if err != nil { // Maybe log non io.EOF errors, if you want - close(ch) - return - } - ch <- b - } - close(ch) - }(ch) - - numBytes := 0 - for { - select { - case _, ok := <-ch: - if !ok { - return numBytes - } - numBytes++ - case <-time.After(500 * time.Millisecond): - return numBytes - } - } - return numBytes -} - -// pipeToStdin pipes the given string onto os.Stdin by replacing it with an -// os.Pipe. The write end of the pipe is closed so that EOF is read after the -// final byte. -func pipeToStdin(s string) (int, error) { - pipeReader, pipeWriter, err := os.Pipe() - if err != nil { - fmt.Println("Error getting os pipes:", err) - os.Exit(1) - } - os.Stdin = pipeReader - w, err := pipeWriter.WriteString(s) - pipeWriter.Close() - return w, err -} - -func pipeBytesToStdin(b []byte) (int, error) { - return pipeToStdin(string(b)) -} - -// TestGetPasswd_Err tests errors are properly handled from getch() -func TestGetPasswd_Err(t *testing.T) { - var inBuffer *bytes.Buffer - getch = func(io.Reader) (byte, error) { - b, err := inBuffer.ReadByte() - if err != nil { - return 13, err - } - if b == 'z' { - return 'z', fmt.Errorf("Forced error; byte returned should not be considered accurate.") - } - return b, nil - } - defer func() { getch = defaultGetCh }() - - for input, expectedPassword := range map[string]string{"abc": "abc", "abzc": "ab"} { - inBuffer = bytes.NewBufferString(input) - p, err := GetPasswdMasked() - if string(p) != expectedPassword { - t.Errorf("Expected %q but got %q instead.", expectedPassword, p) - } - if err == nil { - t.Errorf("Expected error to be returned.") - } - } -} - -func TestMaxPasswordLength(t *testing.T) { - type testData struct { - input []byte - expectedErr error - - // Helper field to output in case of failure; rather than hundreds of - // bytes. - inputDesc string - } - - ds := []testData{ - testData{append(bytes.Repeat([]byte{'a'}, maxLength), '\n'), nil, fmt.Sprintf("%v 'a' bytes followed by a newline", maxLength)}, - testData{append(bytes.Repeat([]byte{'a'}, maxLength+1), '\n'), ErrMaxLengthExceeded, fmt.Sprintf("%v 'a' bytes followed by a newline", maxLength+1)}, - testData{append(bytes.Repeat([]byte{0x00}, maxLength+1), '\n'), ErrMaxLengthExceeded, fmt.Sprintf("%v 0x00 bytes followed by a newline", maxLength+1)}, - } - - for _, d := range ds { - pipeBytesToStdin(d.input) - _, err := GetPasswd() - if err != d.expectedErr { - t.Errorf("Expected error to be %v; isntead got %v from %v", d.expectedErr, err, d.inputDesc) - } - } -} diff --git a/vendor/github.com/imdario/mergo/issue17_test.go b/vendor/github.com/imdario/mergo/issue17_test.go deleted file mode 100644 index 0ee96f3771..0000000000 --- a/vendor/github.com/imdario/mergo/issue17_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package mergo - -import ( - "encoding/json" - "testing" -) - -var ( - request = `{"timestamp":null, "name": "foo"}` - maprequest = map[string]interface{}{ - "timestamp": nil, - "name": "foo", - "newStuff": "foo", - } -) - -func TestIssue17MergeWithOverwrite(t *testing.T) { - var something map[string]interface{} - if err := json.Unmarshal([]byte(request), &something); err != nil { - t.Errorf("Error while Unmarshalling maprequest %s", err) - } - if err := MergeWithOverwrite(&something, maprequest); err != nil { - t.Errorf("Error while merging %s", err) - } -} diff --git a/vendor/github.com/imdario/mergo/issue23_test.go b/vendor/github.com/imdario/mergo/issue23_test.go deleted file mode 100644 index 9c32584131..0000000000 --- a/vendor/github.com/imdario/mergo/issue23_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package mergo - -import ( - "testing" - "time" -) - -type document struct { - Created *time.Time -} - -func TestIssue23MergeWithOverwrite(t *testing.T) { - now := time.Now() - dst := document{ - &now, - } - expected := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) - src := document{ - &expected, - } - if err := MergeWithOverwrite(&dst, src); err != nil { - t.Errorf("Error while merging %s", err) - } - if dst.Created != src.Created { - t.Fatalf("Created not merged in properly: dst.Created(%v) != src.Created(%v)", dst.Created, src.Created) - } -} diff --git a/vendor/github.com/imdario/mergo/issue38_test.go b/vendor/github.com/imdario/mergo/issue38_test.go deleted file mode 100644 index 286b68cb1c..0000000000 --- a/vendor/github.com/imdario/mergo/issue38_test.go +++ /dev/null @@ -1,59 +0,0 @@ -package mergo - -import ( - "testing" - "time" -) - -type structWithoutTimePointer struct { - Created time.Time -} - -func TestIssue38Merge(t *testing.T) { - dst := structWithoutTimePointer{ - time.Now(), - } - - expected := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) - src := structWithoutTimePointer{ - expected, - } - if err := Merge(&dst, src); err != nil { - t.Errorf("Error while merging %s", err) - } - if dst.Created == src.Created { - t.Fatalf("Created merged unexpectedly: dst.Created(%v) == src.Created(%v)", dst.Created, src.Created) - } -} - -func TestIssue38MergeEmptyStruct(t *testing.T) { - dst := structWithoutTimePointer{} - - expected := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) - src := structWithoutTimePointer{ - expected, - } - if err := Merge(&dst, src); err != nil { - t.Errorf("Error while merging %s", err) - } - if dst.Created == src.Created { - t.Fatalf("Created merged unexpectedly: dst.Created(%v) == src.Created(%v)", dst.Created, src.Created) - } -} - -func TestIssue38MergeWithOverwrite(t *testing.T) { - dst := structWithoutTimePointer{ - time.Now(), - } - - expected := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) - src := structWithoutTimePointer{ - expected, - } - if err := MergeWithOverwrite(&dst, src); err != nil { - t.Errorf("Error while merging %s", err) - } - if dst.Created != src.Created { - t.Fatalf("Created not merged in properly: dst.Created(%v) != src.Created(%v)", dst.Created, src.Created) - } -} diff --git a/vendor/github.com/imdario/mergo/mergo_test.go b/vendor/github.com/imdario/mergo/mergo_test.go deleted file mode 100644 index e167c332ab..0000000000 --- a/vendor/github.com/imdario/mergo/mergo_test.go +++ /dev/null @@ -1,662 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// 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 mergo - -import ( - "gopkg.in/yaml.v2" - "io/ioutil" - "reflect" - "testing" - "time" -) - -type simpleTest struct { - Value int -} - -type complexTest struct { - St simpleTest - sz int - ID string -} - -type mapTest struct { - M map[int]int -} - -type ifcTest struct { - I interface{} -} - -type moreComplextText struct { - Ct complexTest - St simpleTest - Nt simpleTest -} - -type pointerTest struct { - C *simpleTest -} - -type sliceTest struct { - S []int -} - -func TestKb(t *testing.T) { - type testStruct struct { - Name string - KeyValue map[string]interface{} - } - - akv := make(map[string]interface{}) - akv["Key1"] = "not value 1" - akv["Key2"] = "value2" - a := testStruct{} - a.Name = "A" - a.KeyValue = akv - - bkv := make(map[string]interface{}) - bkv["Key1"] = "value1" - bkv["Key3"] = "value3" - b := testStruct{} - b.Name = "B" - b.KeyValue = bkv - - ekv := make(map[string]interface{}) - ekv["Key1"] = "value1" - ekv["Key2"] = "value2" - ekv["Key3"] = "value3" - expected := testStruct{} - expected.Name = "B" - expected.KeyValue = ekv - - Merge(&b, a) - - if !reflect.DeepEqual(b, expected) { - t.Errorf("Actual: %#v did not match \nExpected: %#v", b, expected) - } -} - -func TestNil(t *testing.T) { - if err := Merge(nil, nil); err != ErrNilArguments { - t.Fail() - } -} - -func TestDifferentTypes(t *testing.T) { - a := simpleTest{42} - b := 42 - if err := Merge(&a, b); err != ErrDifferentArgumentsTypes { - t.Fail() - } -} - -func TestSimpleStruct(t *testing.T) { - a := simpleTest{} - b := simpleTest{42} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.Value != 42 { - t.Fatalf("b not merged in properly: a.Value(%d) != b.Value(%d)", a.Value, b.Value) - } - if !reflect.DeepEqual(a, b) { - t.FailNow() - } -} - -func TestComplexStruct(t *testing.T) { - a := complexTest{} - a.ID = "athing" - b := complexTest{simpleTest{42}, 1, "bthing"} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.St.Value != 42 { - t.Fatalf("b not merged in properly: a.St.Value(%d) != b.St.Value(%d)", a.St.Value, b.St.Value) - } - if a.sz == 1 { - t.Fatalf("a's private field sz not preserved from merge: a.sz(%d) == b.sz(%d)", a.sz, b.sz) - } - if a.ID == b.ID { - t.Fatalf("a's field ID merged unexpectedly: a.ID(%s) == b.ID(%s)", a.ID, b.ID) - } -} - -func TestComplexStructWithOverwrite(t *testing.T) { - a := complexTest{simpleTest{1}, 1, "do-not-overwrite-with-empty-value"} - b := complexTest{simpleTest{42}, 2, ""} - - expect := complexTest{simpleTest{42}, 1, "do-not-overwrite-with-empty-value"} - if err := MergeWithOverwrite(&a, b); err != nil { - t.FailNow() - } - - if !reflect.DeepEqual(a, expect) { - t.Fatalf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", a, expect) - } -} - -func TestPointerStruct(t *testing.T) { - s1 := simpleTest{} - s2 := simpleTest{19} - a := pointerTest{&s1} - b := pointerTest{&s2} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.C.Value != b.C.Value { - t.Fatalf("b not merged in properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value) - } -} - -type embeddingStruct struct { - embeddedStruct -} - -type embeddedStruct struct { - A string -} - -func TestEmbeddedStruct(t *testing.T) { - tests := []struct { - src embeddingStruct - dst embeddingStruct - expected embeddingStruct - }{ - { - src: embeddingStruct{ - embeddedStruct{"foo"}, - }, - dst: embeddingStruct{ - embeddedStruct{""}, - }, - expected: embeddingStruct{ - embeddedStruct{"foo"}, - }, - }, - { - src: embeddingStruct{ - embeddedStruct{""}, - }, - dst: embeddingStruct{ - embeddedStruct{"bar"}, - }, - expected: embeddingStruct{ - embeddedStruct{"bar"}, - }, - }, - { - src: embeddingStruct{ - embeddedStruct{"foo"}, - }, - dst: embeddingStruct{ - embeddedStruct{"bar"}, - }, - expected: embeddingStruct{ - embeddedStruct{"bar"}, - }, - }, - } - - for _, test := range tests { - err := Merge(&test.dst, test.src) - if err != nil { - t.Errorf("unexpected error: %v", err) - continue - } - if !reflect.DeepEqual(test.dst, test.expected) { - t.Errorf("unexpected output\nexpected:\n%+v\nsaw:\n%+v\n", test.expected, test.dst) - } - } -} - -func TestPointerStructNil(t *testing.T) { - a := pointerTest{nil} - b := pointerTest{&simpleTest{19}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.C.Value != b.C.Value { - t.Fatalf("b not merged in a properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value) - } -} - -func TestSliceStruct(t *testing.T) { - a := sliceTest{} - b := sliceTest{[]int{1, 2, 3}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if len(b.S) != 3 { - t.FailNow() - } - if len(a.S) != len(b.S) { - t.Fatalf("b not merged in a proper way %d != %d", len(a.S), len(b.S)) - } - - a = sliceTest{[]int{1}} - b = sliceTest{[]int{1, 2, 3}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if len(a.S) != 1 { - t.FailNow() - } - if len(a.S) == len(b.S) { - t.Fatalf("b merged unexpectedly %d != %d", len(a.S), len(b.S)) - } -} - -func TestEmptyMaps(t *testing.T) { - a := mapTest{} - b := mapTest{ - map[int]int{}, - } - if err := Merge(&a, b); err != nil { - t.Fail() - } - if !reflect.DeepEqual(a, b) { - t.FailNow() - } -} - -func TestEmptyToEmptyMaps(t *testing.T) { - a := mapTest{} - b := mapTest{} - if err := Merge(&a, b); err != nil { - t.Fail() - } - if !reflect.DeepEqual(a, b) { - t.FailNow() - } -} - -func TestEmptyToNotEmptyMaps(t *testing.T) { - a := mapTest{map[int]int{ - 1: 2, - 3: 4, - }} - aa := mapTest{map[int]int{ - 1: 2, - 3: 4, - }} - b := mapTest{ - map[int]int{}, - } - if err := Merge(&a, b); err != nil { - t.Fail() - } - if !reflect.DeepEqual(a, aa) { - t.FailNow() - } -} - -func TestMapsWithOverwrite(t *testing.T) { - m := map[string]simpleTest{ - "a": {}, // overwritten by 16 - "b": {42}, // not overwritten by empty value - "c": {13}, // overwritten by 12 - "d": {61}, - } - n := map[string]simpleTest{ - "a": {16}, - "b": {}, - "c": {12}, - "e": {14}, - } - expect := map[string]simpleTest{ - "a": {16}, - "b": {}, - "c": {12}, - "d": {61}, - "e": {14}, - } - - if err := MergeWithOverwrite(&m, n); err != nil { - t.Fatalf(err.Error()) - } - - if !reflect.DeepEqual(m, expect) { - t.Fatalf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", m, expect) - } -} - -func TestMaps(t *testing.T) { - m := map[string]simpleTest{ - "a": {}, - "b": {42}, - "c": {13}, - "d": {61}, - } - n := map[string]simpleTest{ - "a": {16}, - "b": {}, - "c": {12}, - "e": {14}, - } - expect := map[string]simpleTest{ - "a": {0}, - "b": {42}, - "c": {13}, - "d": {61}, - "e": {14}, - } - - if err := Merge(&m, n); err != nil { - t.Fatalf(err.Error()) - } - - if !reflect.DeepEqual(m, expect) { - t.Fatalf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", m, expect) - } - if m["a"].Value != 0 { - t.Fatalf(`n merged in m because I solved non-addressable map values TODO: m["a"].Value(%d) != n["a"].Value(%d)`, m["a"].Value, n["a"].Value) - } - if m["b"].Value != 42 { - t.Fatalf(`n wrongly merged in m: m["b"].Value(%d) != n["b"].Value(%d)`, m["b"].Value, n["b"].Value) - } - if m["c"].Value != 13 { - t.Fatalf(`n overwritten in m: m["c"].Value(%d) != n["c"].Value(%d)`, m["c"].Value, n["c"].Value) - } -} - -func TestYAMLMaps(t *testing.T) { - thing := loadYAML("testdata/thing.yml") - license := loadYAML("testdata/license.yml") - ft := thing["fields"].(map[interface{}]interface{}) - fl := license["fields"].(map[interface{}]interface{}) - // license has one extra field (site) and another already existing in thing (author) that Mergo won't override. - expectedLength := len(ft) + len(fl) - 1 - if err := Merge(&license, thing); err != nil { - t.Fatal(err.Error()) - } - currentLength := len(license["fields"].(map[interface{}]interface{})) - if currentLength != expectedLength { - t.Fatalf(`thing not merged in license properly, license must have %d elements instead of %d`, expectedLength, currentLength) - } - fields := license["fields"].(map[interface{}]interface{}) - if _, ok := fields["id"]; !ok { - t.Fatalf(`thing not merged in license properly, license must have a new id field from thing`) - } -} - -func TestTwoPointerValues(t *testing.T) { - a := &simpleTest{} - b := &simpleTest{42} - if err := Merge(a, b); err != nil { - t.Fatalf(`Boom. You crossed the streams: %s`, err) - } -} - -func TestMap(t *testing.T) { - a := complexTest{} - a.ID = "athing" - c := moreComplextText{a, simpleTest{}, simpleTest{}} - b := map[string]interface{}{ - "ct": map[string]interface{}{ - "st": map[string]interface{}{ - "value": 42, - }, - "sz": 1, - "id": "bthing", - }, - "st": &simpleTest{144}, // Mapping a reference - "zt": simpleTest{299}, // Mapping a missing field (zt doesn't exist) - "nt": simpleTest{3}, - } - if err := Map(&c, b); err != nil { - t.FailNow() - } - m := b["ct"].(map[string]interface{}) - n := m["st"].(map[string]interface{}) - o := b["st"].(*simpleTest) - p := b["nt"].(simpleTest) - if c.Ct.St.Value != 42 { - t.Fatalf("b not merged in properly: c.Ct.St.Value(%d) != b.Ct.St.Value(%d)", c.Ct.St.Value, n["value"]) - } - if c.St.Value != 144 { - t.Fatalf("b not merged in properly: c.St.Value(%d) != b.St.Value(%d)", c.St.Value, o.Value) - } - if c.Nt.Value != 3 { - t.Fatalf("b not merged in properly: c.Nt.Value(%d) != b.Nt.Value(%d)", c.St.Value, p.Value) - } - if c.Ct.sz == 1 { - t.Fatalf("a's private field sz not preserved from merge: c.Ct.sz(%d) == b.Ct.sz(%d)", c.Ct.sz, m["sz"]) - } - if c.Ct.ID == m["id"] { - t.Fatalf("a's field ID merged unexpectedly: c.Ct.ID(%s) == b.Ct.ID(%s)", c.Ct.ID, m["id"]) - } -} - -func TestSimpleMap(t *testing.T) { - a := simpleTest{} - b := map[string]interface{}{ - "value": 42, - } - if err := Map(&a, b); err != nil { - t.FailNow() - } - if a.Value != 42 { - t.Fatalf("b not merged in properly: a.Value(%d) != b.Value(%v)", a.Value, b["value"]) - } -} - -func TestIfcMap(t *testing.T) { - a := ifcTest{} - b := ifcTest{42} - if err := Map(&a, b); err != nil { - t.FailNow() - } - if a.I != 42 { - t.Fatalf("b not merged in properly: a.I(%d) != b.I(%d)", a.I, b.I) - } - if !reflect.DeepEqual(a, b) { - t.FailNow() - } -} - -func TestIfcMapNoOverwrite(t *testing.T) { - a := ifcTest{13} - b := ifcTest{42} - if err := Map(&a, b); err != nil { - t.FailNow() - } - if a.I != 13 { - t.Fatalf("a not left alone: a.I(%d) == b.I(%d)", a.I, b.I) - } -} - -func TestIfcMapWithOverwrite(t *testing.T) { - a := ifcTest{13} - b := ifcTest{42} - if err := MapWithOverwrite(&a, b); err != nil { - t.FailNow() - } - if a.I != 42 { - t.Fatalf("b not merged in properly: a.I(%d) != b.I(%d)", a.I, b.I) - } - if !reflect.DeepEqual(a, b) { - t.FailNow() - } -} - -type pointerMapTest struct { - A int - hidden int - B *simpleTest -} - -func TestBackAndForth(t *testing.T) { - pt := pointerMapTest{42, 1, &simpleTest{66}} - m := make(map[string]interface{}) - if err := Map(&m, pt); err != nil { - t.FailNow() - } - var ( - v interface{} - ok bool - ) - if v, ok = m["a"]; v.(int) != pt.A || !ok { - t.Fatalf("pt not merged in properly: m[`a`](%d) != pt.A(%d)", v, pt.A) - } - if v, ok = m["b"]; !ok { - t.Fatalf("pt not merged in properly: B is missing in m") - } - var st *simpleTest - if st = v.(*simpleTest); st.Value != 66 { - t.Fatalf("something went wrong while mapping pt on m, B wasn't copied") - } - bpt := pointerMapTest{} - if err := Map(&bpt, m); err != nil { - t.Fatal(err) - } - if bpt.A != pt.A { - t.Fatalf("pt not merged in properly: bpt.A(%d) != pt.A(%d)", bpt.A, pt.A) - } - if bpt.hidden == pt.hidden { - t.Fatalf("pt unexpectedly merged: bpt.hidden(%d) == pt.hidden(%d)", bpt.hidden, pt.hidden) - } - if bpt.B.Value != pt.B.Value { - t.Fatalf("pt not merged in properly: bpt.B.Value(%d) != pt.B.Value(%d)", bpt.B.Value, pt.B.Value) - } -} - -func TestEmbeddedPointerUnpacking(t *testing.T) { - tests := []struct{ input pointerMapTest }{ - {pointerMapTest{42, 1, nil}}, - {pointerMapTest{42, 1, &simpleTest{66}}}, - } - newValue := 77 - m := map[string]interface{}{ - "b": map[string]interface{}{ - "value": newValue, - }, - } - for _, test := range tests { - pt := test.input - if err := MapWithOverwrite(&pt, m); err != nil { - t.FailNow() - } - if pt.B.Value != newValue { - t.Fatalf("pt not mapped properly: pt.A.Value(%d) != m[`b`][`value`](%d)", pt.B.Value, newValue) - } - - } -} - -type structWithTimePointer struct { - Birth *time.Time -} - -func TestTime(t *testing.T) { - now := time.Now() - dataStruct := structWithTimePointer{ - Birth: &now, - } - dataMap := map[string]interface{}{ - "Birth": &now, - } - b := structWithTimePointer{} - if err := Merge(&b, dataStruct); err != nil { - t.FailNow() - } - if b.Birth.IsZero() { - t.Fatalf("time.Time not merged in properly: b.Birth(%v) != dataStruct['Birth'](%v)", b.Birth, dataStruct.Birth) - } - if b.Birth != dataStruct.Birth { - t.Fatalf("time.Time not merged in properly: b.Birth(%v) != dataStruct['Birth'](%v)", b.Birth, dataStruct.Birth) - } - b = structWithTimePointer{} - if err := Map(&b, dataMap); err != nil { - t.FailNow() - } - if b.Birth.IsZero() { - t.Fatalf("time.Time not merged in properly: b.Birth(%v) != dataMap['Birth'](%v)", b.Birth, dataMap["Birth"]) - } -} - -type simpleNested struct { - A int -} - -type structWithNestedPtrValueMap struct { - NestedPtrValue map[string]*simpleNested -} - -func TestNestedPtrValueInMap(t *testing.T) { - src := &structWithNestedPtrValueMap{ - NestedPtrValue: map[string]*simpleNested{ - "x": { - A: 1, - }, - }, - } - dst := &structWithNestedPtrValueMap{ - NestedPtrValue: map[string]*simpleNested{ - "x": {}, - }, - } - if err := Map(dst, src); err != nil { - t.FailNow() - } - if dst.NestedPtrValue["x"].A == 0 { - t.Fatalf("Nested Ptr value not merged in properly: dst.NestedPtrValue[\"x\"].A(%v) != src.NestedPtrValue[\"x\"].A(%v)", dst.NestedPtrValue["x"].A, src.NestedPtrValue["x"].A) - } -} - -func loadYAML(path string) (m map[string]interface{}) { - m = make(map[string]interface{}) - raw, _ := ioutil.ReadFile(path) - _ = yaml.Unmarshal(raw, &m) - return -} - -type structWithMap struct { - m map[string]structWithUnexportedProperty -} - -type structWithUnexportedProperty struct { - s string -} - -func TestUnexportedProperty(t *testing.T) { - a := structWithMap{map[string]structWithUnexportedProperty{ - "key": structWithUnexportedProperty{"hello"}, - }} - b := structWithMap{map[string]structWithUnexportedProperty{ - "key": structWithUnexportedProperty{"hi"}, - }} - defer func() { - if r := recover(); r != nil { - t.Errorf("Should not have panicked") - } - }() - Merge(&a, b) -} - -type structWithBoolPointer struct { - C *bool -} - -func TestBooleanPointer(t *testing.T) { - bt, bf := true, false - src := structWithBoolPointer{ - &bt, - } - dst := structWithBoolPointer{ - &bf, - } - if err := Merge(&dst, src); err != nil { - t.FailNow() - } - if dst.C == src.C { - t.Fatalf("dst.C should be a different pointer than src.C") - } - if *dst.C != *src.C { - t.Fatalf("dst.C should be true") - } -} diff --git a/vendor/github.com/json-iterator/go/.gitignore b/vendor/github.com/json-iterator/go/.gitignore index 501fcdc9a6..15556530a8 100644 --- a/vendor/github.com/json-iterator/go/.gitignore +++ b/vendor/github.com/json-iterator/go/.gitignore @@ -1,3 +1,4 @@ -.idea +/vendor +/bug_test.go /coverage.txt -/profile.out +/.idea diff --git a/vendor/github.com/json-iterator/go/Gopkg.lock b/vendor/github.com/json-iterator/go/Gopkg.lock new file mode 100644 index 0000000000..338f1c68a5 --- /dev/null +++ b/vendor/github.com/json-iterator/go/Gopkg.lock @@ -0,0 +1,21 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + name = "github.com/modern-go/concurrent" + packages = ["."] + revision = "e0a39a4cb4216ea8db28e22a69f4ec25610d513a" + version = "1.0.0" + +[[projects]] + name = "github.com/modern-go/reflect2" + packages = ["."] + revision = "1df9eeb2bb81f327b96228865c5687bc2194af3f" + version = "1.0.0" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "ac7003b5a981716353a43055ab7d4c5357403cb30a60de2dbdeb446c1544beaa" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/vendor/github.com/json-iterator/go/Gopkg.toml b/vendor/github.com/json-iterator/go/Gopkg.toml new file mode 100644 index 0000000000..5801ffa1e9 --- /dev/null +++ b/vendor/github.com/json-iterator/go/Gopkg.toml @@ -0,0 +1,26 @@ +# Gopkg.toml example +# +# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" + +ignored = ["github.com/davecgh/go-spew*","github.com/google/gofuzz*","github.com/stretchr/testify*"] + +[[constraint]] + name = "github.com/modern-go/reflect2" + version = "1.0.0" diff --git a/vendor/github.com/json-iterator/go/README.md b/vendor/github.com/json-iterator/go/README.md index 3a0d680983..9f404aaa34 100644 --- a/vendor/github.com/json-iterator/go/README.md +++ b/vendor/github.com/json-iterator/go/README.md @@ -8,6 +8,8 @@ A high-performance 100% compatible drop-in replacement of "encoding/json" +You can also use thrift like JSON using [thrift-iterator](https://github.com/thrift-iterator/go) + ``` Go开发者们请加入我们,滴滴出行平台技术部 taowen@didichuxing.com ``` diff --git a/vendor/github.com/json-iterator/go/feature_adapter.go b/vendor/github.com/json-iterator/go/adapter.go similarity index 78% rename from vendor/github.com/json-iterator/go/feature_adapter.go rename to vendor/github.com/json-iterator/go/adapter.go index 40a701ab6b..3a494eeb46 100644 --- a/vendor/github.com/json-iterator/go/feature_adapter.go +++ b/vendor/github.com/json-iterator/go/adapter.go @@ -16,15 +16,6 @@ func Unmarshal(data []byte, v interface{}) error { return ConfigDefault.Unmarshal(data, v) } -func lastNotSpacePos(data []byte) int { - for i := len(data) - 1; i >= 0; i-- { - if data[i] != ' ' && data[i] != '\t' && data[i] != '\r' && data[i] != '\n' { - return i + 1 - } - } - return 0 -} - // UnmarshalFromString convenient method to read from string instead of []byte func UnmarshalFromString(str string, v interface{}) error { return ConfigDefault.UnmarshalFromString(str, v) @@ -71,6 +62,11 @@ type Decoder struct { // Decode decode JSON into interface{} func (adapter *Decoder) Decode(obj interface{}) error { + if adapter.iter.head == adapter.iter.tail && adapter.iter.reader != nil { + if !adapter.iter.loadMore() { + return io.EOF + } + } adapter.iter.ReadVal(obj) err := adapter.iter.Error if err == io.EOF { @@ -90,11 +86,21 @@ func (adapter *Decoder) Buffered() io.Reader { return bytes.NewReader(remaining) } -// UseNumber for number JSON element, use float64 or json.NumberValue (alias of string) +// UseNumber causes the Decoder to unmarshal a number into an interface{} as a +// Number instead of as a float64. func (adapter *Decoder) UseNumber() { - origCfg := adapter.iter.cfg.configBeforeFrozen - origCfg.UseNumber = true - adapter.iter.cfg = origCfg.Froze().(*frozenConfig) + cfg := adapter.iter.cfg.configBeforeFrozen + cfg.UseNumber = true + adapter.iter.cfg = cfg.frozeWithCacheReuse() +} + +// DisallowUnknownFields causes the Decoder to return an error when the destination +// is a struct and the input contains object keys which do not match any +// non-ignored, exported fields in the destination. +func (adapter *Decoder) DisallowUnknownFields() { + cfg := adapter.iter.cfg.configBeforeFrozen + cfg.DisallowUnknownFields = true + adapter.iter.cfg = cfg.frozeWithCacheReuse() } // NewEncoder same as json.NewEncoder @@ -110,20 +116,23 @@ type Encoder struct { // Encode encode interface{} as JSON to io.Writer func (adapter *Encoder) Encode(val interface{}) error { adapter.stream.WriteVal(val) + adapter.stream.WriteRaw("\n") adapter.stream.Flush() return adapter.stream.Error } // SetIndent set the indention. Prefix is not supported func (adapter *Encoder) SetIndent(prefix, indent string) { - adapter.stream.cfg.indentionStep = len(indent) + config := adapter.stream.cfg.configBeforeFrozen + config.IndentionStep = len(indent) + adapter.stream.cfg = config.frozeWithCacheReuse() } // SetEscapeHTML escape html by default, set to false to disable func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) { config := adapter.stream.cfg.configBeforeFrozen config.EscapeHTML = escapeHTML - adapter.stream.cfg = config.Froze().(*frozenConfig) + adapter.stream.cfg = config.frozeWithCacheReuse() } // Valid reports whether data is a valid JSON encoding. diff --git a/vendor/github.com/json-iterator/go/feature_any.go b/vendor/github.com/json-iterator/go/any.go similarity index 74% rename from vendor/github.com/json-iterator/go/feature_any.go rename to vendor/github.com/json-iterator/go/any.go index 6733dce4cc..daecfed615 100644 --- a/vendor/github.com/json-iterator/go/feature_any.go +++ b/vendor/github.com/json-iterator/go/any.go @@ -1,9 +1,13 @@ package jsoniter import ( + "errors" "fmt" + "github.com/modern-go/reflect2" "io" "reflect" + "strconv" + "unsafe" ) // Any generic object representation. @@ -24,7 +28,6 @@ type Any interface { ToString() string ToVal(val interface{}) Get(path ...interface{}) Any - // TODO: add Set Size() int Keys() []string GetInterface() interface{} @@ -34,7 +37,7 @@ type Any interface { type baseAny struct{} func (any *baseAny) Get(path ...interface{}) Any { - return &invalidAny{baseAny{}, fmt.Errorf("Get %v from simple value", path)} + return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} } func (any *baseAny) Size() int { @@ -88,7 +91,7 @@ func Wrap(val interface{}) Any { if isAny { return asAny } - typ := reflect.TypeOf(val) + typ := reflect2.TypeOf(val) switch typ.Kind() { case reflect.Slice: return wrapArray(val) @@ -99,6 +102,9 @@ func Wrap(val interface{}) Any { case reflect.String: return WrapString(val.(string)) case reflect.Int: + if strconv.IntSize == 32 { + return WrapInt32(int32(val.(int))) + } return WrapInt64(int64(val.(int))) case reflect.Int8: return WrapInt32(int32(val.(int8))) @@ -109,7 +115,15 @@ func Wrap(val interface{}) Any { case reflect.Int64: return WrapInt64(val.(int64)) case reflect.Uint: + if strconv.IntSize == 32 { + return WrapUint32(uint32(val.(uint))) + } return WrapUint64(uint64(val.(uint))) + case reflect.Uintptr: + if ptrSize == 32 { + return WrapUint32(uint32(val.(uintptr))) + } + return WrapUint64(uint64(val.(uintptr))) case reflect.Uint8: return WrapUint32(uint32(val.(uint8))) case reflect.Uint16: @@ -157,6 +171,8 @@ func (iter *Iterator) readAny() Any { return iter.readArrayAny() case '-': return iter.readNumberAny(false) + case 0: + return &invalidAny{baseAny{}, errors.New("input is empty")} default: return iter.readNumberAny(true) } @@ -240,3 +256,66 @@ func locatePath(iter *Iterator, path []interface{}) Any { } return iter.readAny() } + +var anyType = reflect2.TypeOfPtr((*Any)(nil)).Elem() + +func createDecoderOfAny(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ == anyType { + return &directAnyCodec{} + } + if typ.Implements(anyType) { + return &anyCodec{ + valType: typ, + } + } + return nil +} + +func createEncoderOfAny(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == anyType { + return &directAnyCodec{} + } + if typ.Implements(anyType) { + return &anyCodec{ + valType: typ, + } + } + return nil +} + +type anyCodec struct { + valType reflect2.Type +} + +func (codec *anyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + panic("not implemented") +} + +func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := codec.valType.UnsafeIndirect(ptr) + any := obj.(Any) + any.WriteTo(stream) +} + +func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool { + obj := codec.valType.UnsafeIndirect(ptr) + any := obj.(Any) + return any.Size() == 0 +} + +type directAnyCodec struct { +} + +func (codec *directAnyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *(*Any)(ptr) = iter.readAny() +} + +func (codec *directAnyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + any := *(*Any)(ptr) + any.WriteTo(stream) +} + +func (codec *directAnyCodec) IsEmpty(ptr unsafe.Pointer) bool { + any := *(*Any)(ptr) + return any.Size() == 0 +} diff --git a/vendor/github.com/json-iterator/go/feature_any_array.go b/vendor/github.com/json-iterator/go/any_array.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_any_array.go rename to vendor/github.com/json-iterator/go/any_array.go diff --git a/vendor/github.com/json-iterator/go/feature_any_bool.go b/vendor/github.com/json-iterator/go/any_bool.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_any_bool.go rename to vendor/github.com/json-iterator/go/any_bool.go diff --git a/vendor/github.com/json-iterator/go/feature_any_float.go b/vendor/github.com/json-iterator/go/any_float.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_any_float.go rename to vendor/github.com/json-iterator/go/any_float.go diff --git a/vendor/github.com/json-iterator/go/feature_any_int32.go b/vendor/github.com/json-iterator/go/any_int32.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_any_int32.go rename to vendor/github.com/json-iterator/go/any_int32.go diff --git a/vendor/github.com/json-iterator/go/feature_any_int64.go b/vendor/github.com/json-iterator/go/any_int64.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_any_int64.go rename to vendor/github.com/json-iterator/go/any_int64.go diff --git a/vendor/github.com/json-iterator/go/feature_any_invalid.go b/vendor/github.com/json-iterator/go/any_invalid.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_any_invalid.go rename to vendor/github.com/json-iterator/go/any_invalid.go diff --git a/vendor/github.com/json-iterator/go/feature_any_nil.go b/vendor/github.com/json-iterator/go/any_nil.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_any_nil.go rename to vendor/github.com/json-iterator/go/any_nil.go diff --git a/vendor/github.com/json-iterator/go/feature_any_number.go b/vendor/github.com/json-iterator/go/any_number.go similarity index 76% rename from vendor/github.com/json-iterator/go/feature_any_number.go rename to vendor/github.com/json-iterator/go/any_number.go index 4e1c27641d..9d1e901a66 100644 --- a/vendor/github.com/json-iterator/go/feature_any_number.go +++ b/vendor/github.com/json-iterator/go/any_number.go @@ -1,6 +1,9 @@ package jsoniter -import "unsafe" +import ( + "io" + "unsafe" +) type numberLazyAny struct { baseAny @@ -29,7 +32,9 @@ func (any *numberLazyAny) ToInt() int { iter := any.cfg.BorrowIterator(any.buf) defer any.cfg.ReturnIterator(iter) val := iter.ReadInt() - any.err = iter.Error + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } return val } @@ -37,7 +42,9 @@ func (any *numberLazyAny) ToInt32() int32 { iter := any.cfg.BorrowIterator(any.buf) defer any.cfg.ReturnIterator(iter) val := iter.ReadInt32() - any.err = iter.Error + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } return val } @@ -45,7 +52,9 @@ func (any *numberLazyAny) ToInt64() int64 { iter := any.cfg.BorrowIterator(any.buf) defer any.cfg.ReturnIterator(iter) val := iter.ReadInt64() - any.err = iter.Error + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } return val } @@ -53,7 +62,9 @@ func (any *numberLazyAny) ToUint() uint { iter := any.cfg.BorrowIterator(any.buf) defer any.cfg.ReturnIterator(iter) val := iter.ReadUint() - any.err = iter.Error + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } return val } @@ -61,7 +72,9 @@ func (any *numberLazyAny) ToUint32() uint32 { iter := any.cfg.BorrowIterator(any.buf) defer any.cfg.ReturnIterator(iter) val := iter.ReadUint32() - any.err = iter.Error + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } return val } @@ -69,7 +82,9 @@ func (any *numberLazyAny) ToUint64() uint64 { iter := any.cfg.BorrowIterator(any.buf) defer any.cfg.ReturnIterator(iter) val := iter.ReadUint64() - any.err = iter.Error + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } return val } @@ -77,7 +92,9 @@ func (any *numberLazyAny) ToFloat32() float32 { iter := any.cfg.BorrowIterator(any.buf) defer any.cfg.ReturnIterator(iter) val := iter.ReadFloat32() - any.err = iter.Error + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } return val } @@ -85,7 +102,9 @@ func (any *numberLazyAny) ToFloat64() float64 { iter := any.cfg.BorrowIterator(any.buf) defer any.cfg.ReturnIterator(iter) val := iter.ReadFloat64() - any.err = iter.Error + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } return val } diff --git a/vendor/github.com/json-iterator/go/feature_any_object.go b/vendor/github.com/json-iterator/go/any_object.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_any_object.go rename to vendor/github.com/json-iterator/go/any_object.go diff --git a/vendor/github.com/json-iterator/go/feature_any_string.go b/vendor/github.com/json-iterator/go/any_str.go similarity index 97% rename from vendor/github.com/json-iterator/go/feature_any_string.go rename to vendor/github.com/json-iterator/go/any_str.go index abf060bd59..a4b93c78c8 100644 --- a/vendor/github.com/json-iterator/go/feature_any_string.go +++ b/vendor/github.com/json-iterator/go/any_str.go @@ -14,7 +14,7 @@ func (any *stringAny) Get(path ...interface{}) Any { if len(path) == 0 { return any } - return &invalidAny{baseAny{}, fmt.Errorf("Get %v from simple value", path)} + return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} } func (any *stringAny) Parse() *Iterator { diff --git a/vendor/github.com/json-iterator/go/feature_any_uint32.go b/vendor/github.com/json-iterator/go/any_uint32.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_any_uint32.go rename to vendor/github.com/json-iterator/go/any_uint32.go diff --git a/vendor/github.com/json-iterator/go/feature_any_uint64.go b/vendor/github.com/json-iterator/go/any_uint64.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_any_uint64.go rename to vendor/github.com/json-iterator/go/any_uint64.go diff --git a/vendor/github.com/json-iterator/go/build.sh b/vendor/github.com/json-iterator/go/build.sh new file mode 100755 index 0000000000..b45ef68831 --- /dev/null +++ b/vendor/github.com/json-iterator/go/build.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +set -x + +if [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then + mkdir -p /tmp/build-golang/src/github.com/json-iterator + ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go +fi +export GOPATH=/tmp/build-golang +go get -u github.com/golang/dep/cmd/dep +cd /tmp/build-golang/src/github.com/json-iterator/go +exec $GOPATH/bin/dep ensure -update diff --git a/vendor/github.com/json-iterator/go/feature_config.go b/vendor/github.com/json-iterator/go/config.go similarity index 52% rename from vendor/github.com/json-iterator/go/feature_config.go rename to vendor/github.com/json-iterator/go/config.go index 687210820b..bd66947d7c 100644 --- a/vendor/github.com/json-iterator/go/feature_config.go +++ b/vendor/github.com/json-iterator/go/config.go @@ -2,34 +2,27 @@ package jsoniter import ( "encoding/json" - "errors" + "github.com/modern-go/concurrent" + "github.com/modern-go/reflect2" "io" "reflect" - "sync/atomic" + "sync" "unsafe" ) // Config customize how the API should behave. // The API is created from Config by Froze. type Config struct { - IndentionStep int - MarshalFloatWith6Digits bool - EscapeHTML bool - SortMapKeys bool - UseNumber bool - TagKey string - ValidateJsonRawMessage bool -} - -type frozenConfig struct { - configBeforeFrozen Config - sortMapKeys bool - indentionStep int - decoderCache unsafe.Pointer - encoderCache unsafe.Pointer - extensions []Extension - streamPool chan *Stream - iteratorPool chan *Iterator + IndentionStep int + MarshalFloatWith6Digits bool + EscapeHTML bool + SortMapKeys bool + UseNumber bool + DisallowUnknownFields bool + TagKey string + OnlyTaggedField bool + ValidateJsonRawMessage bool + ObjectFieldMustBeSimpleString bool } // API the public interface of this package. @@ -46,6 +39,9 @@ type API interface { NewEncoder(writer io.Writer) *Encoder NewDecoder(reader io.Reader) *Decoder Valid(data []byte) bool + RegisterExtension(extension Extension) + DecoderOf(typ reflect2.Type) ValDecoder + EncoderOf(typ reflect2.Type) ValEncoder } // ConfigDefault the default API @@ -62,38 +58,123 @@ var ConfigCompatibleWithStandardLibrary = Config{ // ConfigFastest marshals float with only 6 digits precision var ConfigFastest = Config{ - EscapeHTML: false, - MarshalFloatWith6Digits: true, + EscapeHTML: false, + MarshalFloatWith6Digits: true, // will lose precession + ObjectFieldMustBeSimpleString: true, // do not unescape object field }.Froze() +type frozenConfig struct { + configBeforeFrozen Config + sortMapKeys bool + indentionStep int + objectFieldMustBeSimpleString bool + onlyTaggedField bool + disallowUnknownFields bool + decoderCache *concurrent.Map + encoderCache *concurrent.Map + extensions []Extension + streamPool *sync.Pool + iteratorPool *sync.Pool +} + +func (cfg *frozenConfig) initCache() { + cfg.decoderCache = concurrent.NewMap() + cfg.encoderCache = concurrent.NewMap() +} + +func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) { + cfg.decoderCache.Store(cacheKey, decoder) +} + +func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) { + cfg.encoderCache.Store(cacheKey, encoder) +} + +func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder { + decoder, found := cfg.decoderCache.Load(cacheKey) + if found { + return decoder.(ValDecoder) + } + return nil +} + +func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder { + encoder, found := cfg.encoderCache.Load(cacheKey) + if found { + return encoder.(ValEncoder) + } + return nil +} + +var cfgCache = concurrent.NewMap() + +func getFrozenConfigFromCache(cfg Config) *frozenConfig { + obj, found := cfgCache.Load(cfg) + if found { + return obj.(*frozenConfig) + } + return nil +} + +func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) { + cfgCache.Store(cfg, frozenConfig) +} + // Froze forge API from config func (cfg Config) Froze() API { - // TODO: cache frozen config - frozenConfig := &frozenConfig{ - sortMapKeys: cfg.SortMapKeys, - indentionStep: cfg.IndentionStep, - streamPool: make(chan *Stream, 16), - iteratorPool: make(chan *Iterator, 16), + api := &frozenConfig{ + sortMapKeys: cfg.SortMapKeys, + indentionStep: cfg.IndentionStep, + objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, + onlyTaggedField: cfg.OnlyTaggedField, + disallowUnknownFields: cfg.DisallowUnknownFields, + } + api.streamPool = &sync.Pool{ + New: func() interface{} { + return NewStream(api, nil, 512) + }, + } + api.iteratorPool = &sync.Pool{ + New: func() interface{} { + return NewIterator(api) + }, } - atomic.StorePointer(&frozenConfig.decoderCache, unsafe.Pointer(&map[string]ValDecoder{})) - atomic.StorePointer(&frozenConfig.encoderCache, unsafe.Pointer(&map[string]ValEncoder{})) + api.initCache() + encoderExtension := EncoderExtension{} + decoderExtension := DecoderExtension{} if cfg.MarshalFloatWith6Digits { - frozenConfig.marshalFloatWith6Digits() + api.marshalFloatWith6Digits(encoderExtension) } if cfg.EscapeHTML { - frozenConfig.escapeHTML() + api.escapeHTML(encoderExtension) } if cfg.UseNumber { - frozenConfig.useNumber() + api.useNumber(decoderExtension) } if cfg.ValidateJsonRawMessage { - frozenConfig.validateJsonRawMessage() + api.validateJsonRawMessage(encoderExtension) + } + if len(encoderExtension) > 0 { + api.extensions = append(api.extensions, encoderExtension) + } + if len(decoderExtension) > 0 { + api.extensions = append(api.extensions, decoderExtension) + } + api.configBeforeFrozen = cfg + return api +} + +func (cfg Config) frozeWithCacheReuse() *frozenConfig { + api := getFrozenConfigFromCache(cfg) + if api != nil { + return api } - frozenConfig.configBeforeFrozen = cfg - return frozenConfig + api = cfg.Froze().(*frozenConfig) + addFrozenConfigToCache(cfg, api) + return api } -func (cfg *frozenConfig) validateJsonRawMessage() { +func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) { encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) { rawMessage := *(*json.RawMessage)(ptr) iter := cfg.BorrowIterator([]byte(rawMessage)) @@ -107,18 +188,23 @@ func (cfg *frozenConfig) validateJsonRawMessage() { }, func(ptr unsafe.Pointer) bool { return false }} - cfg.addEncoderToCache(reflect.TypeOf((*json.RawMessage)(nil)).Elem(), encoder) - cfg.addEncoderToCache(reflect.TypeOf((*RawMessage)(nil)).Elem(), encoder) + extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder + extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder } -func (cfg *frozenConfig) useNumber() { - cfg.addDecoderToCache(reflect.TypeOf((*interface{})(nil)).Elem(), &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { +func (cfg *frozenConfig) useNumber(extension DecoderExtension) { + extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { + exitingValue := *((*interface{})(ptr)) + if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr { + iter.ReadVal(exitingValue) + return + } if iter.WhatIsNext() == NumberValue { *((*interface{})(ptr)) = json.Number(iter.readNumberAsString()) } else { *((*interface{})(ptr)) = iter.Read() } - }}) + }} } func (cfg *frozenConfig) getTagKey() string { tagKey := cfg.configBeforeFrozen.TagKey @@ -128,7 +214,7 @@ func (cfg *frozenConfig) getTagKey() string { return tagKey } -func (cfg *frozenConfig) registerExtension(extension Extension) { +func (cfg *frozenConfig) RegisterExtension(extension Extension) { cfg.extensions = append(cfg.extensions, extension) } @@ -139,10 +225,6 @@ func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteFloat32Lossy(*((*float32)(ptr))) } -func (encoder *lossyFloat32Encoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*float32)(ptr)) == 0 } @@ -154,20 +236,16 @@ func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteFloat64Lossy(*((*float64)(ptr))) } -func (encoder *lossyFloat64Encoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*float64)(ptr)) == 0 } // EnableLossyFloatMarshalling keeps 10**(-6) precision // for float variables for better performance. -func (cfg *frozenConfig) marshalFloatWith6Digits() { +func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) { // for better performance - cfg.addEncoderToCache(reflect.TypeOf((*float32)(nil)).Elem(), &lossyFloat32Encoder{}) - cfg.addEncoderToCache(reflect.TypeOf((*float64)(nil)).Elem(), &lossyFloat64Encoder{}) + extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{} + extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{} } type htmlEscapedStringEncoder struct { @@ -178,56 +256,12 @@ func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stre stream.WriteStringWithHTMLEscaped(str) } -func (encoder *htmlEscapedStringEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { return *((*string)(ptr)) == "" } -func (cfg *frozenConfig) escapeHTML() { - cfg.addEncoderToCache(reflect.TypeOf((*string)(nil)).Elem(), &htmlEscapedStringEncoder{}) -} - -func (cfg *frozenConfig) addDecoderToCache(cacheKey reflect.Type, decoder ValDecoder) { - done := false - for !done { - ptr := atomic.LoadPointer(&cfg.decoderCache) - cache := *(*map[reflect.Type]ValDecoder)(ptr) - copied := map[reflect.Type]ValDecoder{} - for k, v := range cache { - copied[k] = v - } - copied[cacheKey] = decoder - done = atomic.CompareAndSwapPointer(&cfg.decoderCache, ptr, unsafe.Pointer(&copied)) - } -} - -func (cfg *frozenConfig) addEncoderToCache(cacheKey reflect.Type, encoder ValEncoder) { - done := false - for !done { - ptr := atomic.LoadPointer(&cfg.encoderCache) - cache := *(*map[reflect.Type]ValEncoder)(ptr) - copied := map[reflect.Type]ValEncoder{} - for k, v := range cache { - copied[k] = v - } - copied[cacheKey] = encoder - done = atomic.CompareAndSwapPointer(&cfg.encoderCache, ptr, unsafe.Pointer(&copied)) - } -} - -func (cfg *frozenConfig) getDecoderFromCache(cacheKey reflect.Type) ValDecoder { - ptr := atomic.LoadPointer(&cfg.decoderCache) - cache := *(*map[reflect.Type]ValDecoder)(ptr) - return cache[cacheKey] -} - -func (cfg *frozenConfig) getEncoderFromCache(cacheKey reflect.Type) ValEncoder { - ptr := atomic.LoadPointer(&cfg.encoderCache) - cache := *(*map[reflect.Type]ValEncoder)(ptr) - return cache[cacheKey] +func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) { + encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{} } func (cfg *frozenConfig) cleanDecoders() { @@ -276,24 +310,22 @@ func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([] } newCfg := cfg.configBeforeFrozen newCfg.IndentionStep = len(indent) - return newCfg.Froze().Marshal(v) + return newCfg.frozeWithCacheReuse().Marshal(v) } func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error { data := []byte(str) - data = data[:lastNotSpacePos(data)] iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) iter.ReadVal(v) - if iter.head == iter.tail { - iter.loadMore() - } - if iter.Error == io.EOF { - return nil - } - if iter.Error == nil { - iter.ReportError("UnmarshalFromString", "there are bytes left after unmarshal") + c := iter.nextToken() + if c == 0 { + if iter.Error == io.EOF { + return nil + } + return iter.Error } + iter.ReportError("Unmarshal", "there are bytes left after unmarshal") return iter.Error } @@ -304,24 +336,17 @@ func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any { } func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error { - data = data[:lastNotSpacePos(data)] iter := cfg.BorrowIterator(data) defer cfg.ReturnIterator(iter) - typ := reflect.TypeOf(v) - if typ.Kind() != reflect.Ptr { - // return non-pointer error - return errors.New("the second param must be ptr type") - } iter.ReadVal(v) - if iter.head == iter.tail { - iter.loadMore() - } - if iter.Error == io.EOF { - return nil - } - if iter.Error == nil { - iter.ReportError("Unmarshal", "there are bytes left after unmarshal") + c := iter.nextToken() + if c == 0 { + if iter.Error == io.EOF { + return nil + } + return iter.Error } + iter.ReportError("Unmarshal", "there are bytes left after unmarshal") return iter.Error } diff --git a/vendor/github.com/json-iterator/go/example_test.go b/vendor/github.com/json-iterator/go/example_test.go deleted file mode 100644 index 1c8f341c14..0000000000 --- a/vendor/github.com/json-iterator/go/example_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package jsoniter - -import ( - "fmt" - "os" -) - -func ExampleMarshal() { - type ColorGroup struct { - ID int - Name string - Colors []string - } - group := ColorGroup{ - ID: 1, - Name: "Reds", - Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, - } - b, err := Marshal(group) - if err != nil { - fmt.Println("error:", err) - } - os.Stdout.Write(b) - // Output: - // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} -} - -func ExampleUnmarshal() { - var jsonBlob = []byte(`[ - {"Name": "Platypus", "Order": "Monotremata"}, - {"Name": "Quoll", "Order": "Dasyuromorphia"} - ]`) - type Animal struct { - Name string - Order string - } - var animals []Animal - err := Unmarshal(jsonBlob, &animals) - if err != nil { - fmt.Println("error:", err) - } - fmt.Printf("%+v", animals) - // Output: - // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] -} - -func ExampleConfigFastest_Marshal() { - type ColorGroup struct { - ID int - Name string - Colors []string - } - group := ColorGroup{ - ID: 1, - Name: "Reds", - Colors: []string{"Crimson", "Red", "Ruby", "Maroon"}, - } - stream := ConfigFastest.BorrowStream(nil) - defer ConfigFastest.ReturnStream(stream) - stream.WriteVal(group) - if stream.Error != nil { - fmt.Println("error:", stream.Error) - } - os.Stdout.Write(stream.Buffer()) - // Output: - // {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]} -} - -func ExampleConfigFastest_Unmarshal() { - var jsonBlob = []byte(`[ - {"Name": "Platypus", "Order": "Monotremata"}, - {"Name": "Quoll", "Order": "Dasyuromorphia"} - ]`) - type Animal struct { - Name string - Order string - } - var animals []Animal - iter := ConfigFastest.BorrowIterator(jsonBlob) - defer ConfigFastest.ReturnIterator(iter) - iter.ReadVal(&animals) - if iter.Error != nil { - fmt.Println("error:", iter.Error) - } - fmt.Printf("%+v", animals) - // Output: - // [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}] -} - -func ExampleGet() { - val := []byte(`{"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}`) - fmt.Printf(Get(val, "Colors", 0).ToString()) - // Output: - // Crimson -} diff --git a/vendor/github.com/json-iterator/go/feature_json_number.go b/vendor/github.com/json-iterator/go/feature_json_number.go deleted file mode 100644 index e187b200a9..0000000000 --- a/vendor/github.com/json-iterator/go/feature_json_number.go +++ /dev/null @@ -1,31 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "strconv" -) - -type Number string - -// String returns the literal text of the number. -func (n Number) String() string { return string(n) } - -// Float64 returns the number as a float64. -func (n Number) Float64() (float64, error) { - return strconv.ParseFloat(string(n), 64) -} - -// Int64 returns the number as an int64. -func (n Number) Int64() (int64, error) { - return strconv.ParseInt(string(n), 10, 64) -} - -func CastJsonNumber(val interface{}) (string, bool) { - switch typedVal := val.(type) { - case json.Number: - return string(typedVal), true - case Number: - return string(typedVal), true - } - return "", false -} diff --git a/vendor/github.com/json-iterator/go/feature_reflect.go b/vendor/github.com/json-iterator/go/feature_reflect.go deleted file mode 100644 index 4483e34b84..0000000000 --- a/vendor/github.com/json-iterator/go/feature_reflect.go +++ /dev/null @@ -1,703 +0,0 @@ -package jsoniter - -import ( - "encoding" - "encoding/json" - "fmt" - "reflect" - "time" - "unsafe" -) - -// ValDecoder is an internal type registered to cache as needed. -// Don't confuse jsoniter.ValDecoder with json.Decoder. -// For json.Decoder's adapter, refer to jsoniter.AdapterDecoder(todo link). -// -// Reflection on type to create decoders, which is then cached -// Reflection on value is avoided as we can, as the reflect.Value itself will allocate, with following exceptions -// 1. create instance of new value, for example *int will need a int to be allocated -// 2. append to slice, if the existing cap is not enough, allocate will be done using Reflect.New -// 3. assignment to map, both key and value will be reflect.Value -// For a simple struct binding, it will be reflect.Value free and allocation free -type ValDecoder interface { - Decode(ptr unsafe.Pointer, iter *Iterator) -} - -// ValEncoder is an internal type registered to cache as needed. -// Don't confuse jsoniter.ValEncoder with json.Encoder. -// For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link). -type ValEncoder interface { - IsEmpty(ptr unsafe.Pointer) bool - Encode(ptr unsafe.Pointer, stream *Stream) - EncodeInterface(val interface{}, stream *Stream) -} - -type checkIsEmpty interface { - IsEmpty(ptr unsafe.Pointer) bool -} - -// WriteToStream the default implementation for TypeEncoder method EncodeInterface -func WriteToStream(val interface{}, stream *Stream, encoder ValEncoder) { - e := (*emptyInterface)(unsafe.Pointer(&val)) - if e.word == nil { - stream.WriteNil() - return - } - if reflect.TypeOf(val).Kind() == reflect.Ptr { - encoder.Encode(unsafe.Pointer(&e.word), stream) - } else { - encoder.Encode(e.word, stream) - } -} - -var jsonNumberType reflect.Type -var jsoniterNumberType reflect.Type -var jsonRawMessageType reflect.Type -var jsoniterRawMessageType reflect.Type -var anyType reflect.Type -var marshalerType reflect.Type -var unmarshalerType reflect.Type -var textMarshalerType reflect.Type -var textUnmarshalerType reflect.Type - -func init() { - jsonNumberType = reflect.TypeOf((*json.Number)(nil)).Elem() - jsoniterNumberType = reflect.TypeOf((*Number)(nil)).Elem() - jsonRawMessageType = reflect.TypeOf((*json.RawMessage)(nil)).Elem() - jsoniterRawMessageType = reflect.TypeOf((*RawMessage)(nil)).Elem() - anyType = reflect.TypeOf((*Any)(nil)).Elem() - marshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem() - unmarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() - textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() - textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() -} - -type optionalDecoder struct { - valueType reflect.Type - valueDecoder ValDecoder -} - -func (decoder *optionalDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.ReadNil() { - *((*unsafe.Pointer)(ptr)) = nil - } else { - if *((*unsafe.Pointer)(ptr)) == nil { - //pointer to null, we have to allocate memory to hold the value - value := reflect.New(decoder.valueType) - newPtr := extractInterface(value.Interface()).word - decoder.valueDecoder.Decode(newPtr, iter) - *((*uintptr)(ptr)) = uintptr(newPtr) - } else { - //reuse existing instance - decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) - } - } -} - -type deferenceDecoder struct { - // only to deference a pointer - valueType reflect.Type - valueDecoder ValDecoder -} - -func (decoder *deferenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - if *((*unsafe.Pointer)(ptr)) == nil { - //pointer to null, we have to allocate memory to hold the value - value := reflect.New(decoder.valueType) - newPtr := extractInterface(value.Interface()).word - decoder.valueDecoder.Decode(newPtr, iter) - *((*uintptr)(ptr)) = uintptr(newPtr) - } else { - //reuse existing instance - decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) - } -} - -type optionalEncoder struct { - valueEncoder ValEncoder -} - -func (encoder *optionalEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - if *((*unsafe.Pointer)(ptr)) == nil { - stream.WriteNil() - } else { - encoder.valueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) - } -} - -func (encoder *optionalEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - -func (encoder *optionalEncoder) IsEmpty(ptr unsafe.Pointer) bool { - if *((*unsafe.Pointer)(ptr)) == nil { - return true - } - return false -} - -type placeholderEncoder struct { - cfg *frozenConfig - cacheKey reflect.Type -} - -func (encoder *placeholderEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - encoder.getRealEncoder().Encode(ptr, stream) -} - -func (encoder *placeholderEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - -func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.getRealEncoder().IsEmpty(ptr) -} - -func (encoder *placeholderEncoder) getRealEncoder() ValEncoder { - for i := 0; i < 500; i++ { - realDecoder := encoder.cfg.getEncoderFromCache(encoder.cacheKey) - _, isPlaceholder := realDecoder.(*placeholderEncoder) - if isPlaceholder { - time.Sleep(10 * time.Millisecond) - } else { - return realDecoder - } - } - panic(fmt.Sprintf("real encoder not found for cache key: %v", encoder.cacheKey)) -} - -type placeholderDecoder struct { - cfg *frozenConfig - cacheKey reflect.Type -} - -func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - for i := 0; i < 500; i++ { - realDecoder := decoder.cfg.getDecoderFromCache(decoder.cacheKey) - _, isPlaceholder := realDecoder.(*placeholderDecoder) - if isPlaceholder { - time.Sleep(10 * time.Millisecond) - } else { - realDecoder.Decode(ptr, iter) - return - } - } - panic(fmt.Sprintf("real decoder not found for cache key: %v", decoder.cacheKey)) -} - -// emptyInterface is the header for an interface{} value. -type emptyInterface struct { - typ unsafe.Pointer - word unsafe.Pointer -} - -// emptyInterface is the header for an interface with method (not interface{}) -type nonEmptyInterface struct { - // see ../runtime/iface.go:/Itab - itab *struct { - ityp unsafe.Pointer // static interface type - typ unsafe.Pointer // dynamic concrete type - link unsafe.Pointer - bad int32 - unused int32 - fun [100000]unsafe.Pointer // method table - } - word unsafe.Pointer -} - -// ReadVal copy the underlying JSON into go interface, same as json.Unmarshal -func (iter *Iterator) ReadVal(obj interface{}) { - typ := reflect.TypeOf(obj) - cacheKey := typ.Elem() - decoder, err := decoderOfType(iter.cfg, cacheKey) - if err != nil { - iter.Error = err - return - } - e := (*emptyInterface)(unsafe.Pointer(&obj)) - decoder.Decode(e.word, iter) -} - -// WriteVal copy the go interface into underlying JSON, same as json.Marshal -func (stream *Stream) WriteVal(val interface{}) { - if nil == val { - stream.WriteNil() - return - } - typ := reflect.TypeOf(val) - cacheKey := typ - encoder, err := encoderOfType(stream.cfg, cacheKey) - if err != nil { - stream.Error = err - return - } - encoder.EncodeInterface(val, stream) -} - -type prefix string - -func (p prefix) addToDecoder(decoder ValDecoder, err error) (ValDecoder, error) { - if err != nil { - return nil, fmt.Errorf("%s: %s", p, err.Error()) - } - return decoder, err -} - -func (p prefix) addToEncoder(encoder ValEncoder, err error) (ValEncoder, error) { - if err != nil { - return nil, fmt.Errorf("%s: %s", p, err.Error()) - } - return encoder, err -} - -func decoderOfType(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) { - cacheKey := typ - decoder := cfg.getDecoderFromCache(cacheKey) - if decoder != nil { - return decoder, nil - } - decoder = getTypeDecoderFromExtension(typ) - if decoder != nil { - cfg.addDecoderToCache(cacheKey, decoder) - return decoder, nil - } - decoder = &placeholderDecoder{cfg: cfg, cacheKey: cacheKey} - cfg.addDecoderToCache(cacheKey, decoder) - decoder, err := createDecoderOfType(cfg, typ) - for _, extension := range extensions { - decoder = extension.DecorateDecoder(typ, decoder) - } - cfg.addDecoderToCache(cacheKey, decoder) - return decoder, err -} - -func createDecoderOfType(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) { - typeName := typ.String() - if typ == jsonRawMessageType { - return &jsonRawMessageCodec{}, nil - } - if typ == jsoniterRawMessageType { - return &jsoniterRawMessageCodec{}, nil - } - if typ.AssignableTo(jsonNumberType) { - return &jsonNumberCodec{}, nil - } - if typ.AssignableTo(jsoniterNumberType) { - return &jsoniterNumberCodec{}, nil - } - if typ.Implements(unmarshalerType) { - templateInterface := reflect.New(typ).Elem().Interface() - var decoder ValDecoder = &unmarshalerDecoder{extractInterface(templateInterface)} - if typ.Kind() == reflect.Ptr { - decoder = &optionalDecoder{typ.Elem(), decoder} - } - return decoder, nil - } - if reflect.PtrTo(typ).Implements(unmarshalerType) { - templateInterface := reflect.New(typ).Interface() - var decoder ValDecoder = &unmarshalerDecoder{extractInterface(templateInterface)} - return decoder, nil - } - if typ.Implements(textUnmarshalerType) { - templateInterface := reflect.New(typ).Elem().Interface() - var decoder ValDecoder = &textUnmarshalerDecoder{extractInterface(templateInterface)} - if typ.Kind() == reflect.Ptr { - decoder = &optionalDecoder{typ.Elem(), decoder} - } - return decoder, nil - } - if reflect.PtrTo(typ).Implements(textUnmarshalerType) { - templateInterface := reflect.New(typ).Interface() - var decoder ValDecoder = &textUnmarshalerDecoder{extractInterface(templateInterface)} - return decoder, nil - } - if typ.Kind() == reflect.Slice && typ.Elem().Kind() == reflect.Uint8 { - sliceDecoder, err := prefix("[slice]").addToDecoder(decoderOfSlice(cfg, typ)) - if err != nil { - return nil, err - } - return &base64Codec{sliceDecoder: sliceDecoder}, nil - } - if typ.Implements(anyType) { - return &anyCodec{}, nil - } - switch typ.Kind() { - case reflect.String: - if typeName != "string" { - return decoderOfType(cfg, reflect.TypeOf((*string)(nil)).Elem()) - } - return &stringCodec{}, nil - case reflect.Int: - if typeName != "int" { - return decoderOfType(cfg, reflect.TypeOf((*int)(nil)).Elem()) - } - return &intCodec{}, nil - case reflect.Int8: - if typeName != "int8" { - return decoderOfType(cfg, reflect.TypeOf((*int8)(nil)).Elem()) - } - return &int8Codec{}, nil - case reflect.Int16: - if typeName != "int16" { - return decoderOfType(cfg, reflect.TypeOf((*int16)(nil)).Elem()) - } - return &int16Codec{}, nil - case reflect.Int32: - if typeName != "int32" { - return decoderOfType(cfg, reflect.TypeOf((*int32)(nil)).Elem()) - } - return &int32Codec{}, nil - case reflect.Int64: - if typeName != "int64" { - return decoderOfType(cfg, reflect.TypeOf((*int64)(nil)).Elem()) - } - return &int64Codec{}, nil - case reflect.Uint: - if typeName != "uint" { - return decoderOfType(cfg, reflect.TypeOf((*uint)(nil)).Elem()) - } - return &uintCodec{}, nil - case reflect.Uint8: - if typeName != "uint8" { - return decoderOfType(cfg, reflect.TypeOf((*uint8)(nil)).Elem()) - } - return &uint8Codec{}, nil - case reflect.Uint16: - if typeName != "uint16" { - return decoderOfType(cfg, reflect.TypeOf((*uint16)(nil)).Elem()) - } - return &uint16Codec{}, nil - case reflect.Uint32: - if typeName != "uint32" { - return decoderOfType(cfg, reflect.TypeOf((*uint32)(nil)).Elem()) - } - return &uint32Codec{}, nil - case reflect.Uintptr: - if typeName != "uintptr" { - return decoderOfType(cfg, reflect.TypeOf((*uintptr)(nil)).Elem()) - } - return &uintptrCodec{}, nil - case reflect.Uint64: - if typeName != "uint64" { - return decoderOfType(cfg, reflect.TypeOf((*uint64)(nil)).Elem()) - } - return &uint64Codec{}, nil - case reflect.Float32: - if typeName != "float32" { - return decoderOfType(cfg, reflect.TypeOf((*float32)(nil)).Elem()) - } - return &float32Codec{}, nil - case reflect.Float64: - if typeName != "float64" { - return decoderOfType(cfg, reflect.TypeOf((*float64)(nil)).Elem()) - } - return &float64Codec{}, nil - case reflect.Bool: - if typeName != "bool" { - return decoderOfType(cfg, reflect.TypeOf((*bool)(nil)).Elem()) - } - return &boolCodec{}, nil - case reflect.Interface: - if typ.NumMethod() == 0 { - return &emptyInterfaceCodec{}, nil - } - return &nonEmptyInterfaceCodec{}, nil - case reflect.Struct: - return prefix(fmt.Sprintf("[%s]", typeName)).addToDecoder(decoderOfStruct(cfg, typ)) - case reflect.Array: - return prefix("[array]").addToDecoder(decoderOfArray(cfg, typ)) - case reflect.Slice: - return prefix("[slice]").addToDecoder(decoderOfSlice(cfg, typ)) - case reflect.Map: - return prefix("[map]").addToDecoder(decoderOfMap(cfg, typ)) - case reflect.Ptr: - return prefix("[optional]").addToDecoder(decoderOfOptional(cfg, typ)) - default: - return nil, fmt.Errorf("unsupported type: %v", typ) - } -} - -func encoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { - cacheKey := typ - encoder := cfg.getEncoderFromCache(cacheKey) - if encoder != nil { - return encoder, nil - } - encoder = getTypeEncoderFromExtension(typ) - if encoder != nil { - cfg.addEncoderToCache(cacheKey, encoder) - return encoder, nil - } - encoder = &placeholderEncoder{cfg: cfg, cacheKey: cacheKey} - cfg.addEncoderToCache(cacheKey, encoder) - encoder, err := createEncoderOfType(cfg, typ) - for _, extension := range extensions { - encoder = extension.DecorateEncoder(typ, encoder) - } - cfg.addEncoderToCache(cacheKey, encoder) - return encoder, err -} - -func createEncoderOfType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { - if typ == jsonRawMessageType { - return &jsonRawMessageCodec{}, nil - } - if typ == jsoniterRawMessageType { - return &jsoniterRawMessageCodec{}, nil - } - if typ.AssignableTo(jsonNumberType) { - return &jsonNumberCodec{}, nil - } - if typ.AssignableTo(jsoniterNumberType) { - return &jsoniterNumberCodec{}, nil - } - if typ.Implements(marshalerType) { - checkIsEmpty, err := createCheckIsEmpty(typ) - if err != nil { - return nil, err - } - templateInterface := reflect.New(typ).Elem().Interface() - var encoder ValEncoder = &marshalerEncoder{ - templateInterface: extractInterface(templateInterface), - checkIsEmpty: checkIsEmpty, - } - if typ.Kind() == reflect.Ptr { - encoder = &optionalEncoder{encoder} - } - return encoder, nil - } - if reflect.PtrTo(typ).Implements(marshalerType) { - checkIsEmpty, err := createCheckIsEmpty(reflect.PtrTo(typ)) - if err != nil { - return nil, err - } - templateInterface := reflect.New(typ).Interface() - var encoder ValEncoder = &marshalerEncoder{ - templateInterface: extractInterface(templateInterface), - checkIsEmpty: checkIsEmpty, - } - return encoder, nil - } - if typ.Implements(textMarshalerType) { - checkIsEmpty, err := createCheckIsEmpty(typ) - if err != nil { - return nil, err - } - templateInterface := reflect.New(typ).Elem().Interface() - var encoder ValEncoder = &textMarshalerEncoder{ - templateInterface: extractInterface(templateInterface), - checkIsEmpty: checkIsEmpty, - } - if typ.Kind() == reflect.Ptr { - encoder = &optionalEncoder{encoder} - } - return encoder, nil - } - if typ.Kind() == reflect.Slice && typ.Elem().Kind() == reflect.Uint8 { - return &base64Codec{}, nil - } - if typ.Implements(anyType) { - return &anyCodec{}, nil - } - return createEncoderOfSimpleType(cfg, typ) -} - -func createCheckIsEmpty(typ reflect.Type) (checkIsEmpty, error) { - kind := typ.Kind() - switch kind { - case reflect.String: - return &stringCodec{}, nil - case reflect.Int: - return &intCodec{}, nil - case reflect.Int8: - return &int8Codec{}, nil - case reflect.Int16: - return &int16Codec{}, nil - case reflect.Int32: - return &int32Codec{}, nil - case reflect.Int64: - return &int64Codec{}, nil - case reflect.Uint: - return &uintCodec{}, nil - case reflect.Uint8: - return &uint8Codec{}, nil - case reflect.Uint16: - return &uint16Codec{}, nil - case reflect.Uint32: - return &uint32Codec{}, nil - case reflect.Uintptr: - return &uintptrCodec{}, nil - case reflect.Uint64: - return &uint64Codec{}, nil - case reflect.Float32: - return &float32Codec{}, nil - case reflect.Float64: - return &float64Codec{}, nil - case reflect.Bool: - return &boolCodec{}, nil - case reflect.Interface: - if typ.NumMethod() == 0 { - return &emptyInterfaceCodec{}, nil - } - return &nonEmptyInterfaceCodec{}, nil - case reflect.Struct: - return &structEncoder{}, nil - case reflect.Array: - return &arrayEncoder{}, nil - case reflect.Slice: - return &sliceEncoder{}, nil - case reflect.Map: - return &mapEncoder{}, nil - case reflect.Ptr: - return &optionalEncoder{}, nil - default: - return nil, fmt.Errorf("unsupported type: %v", typ) - } -} - -func createEncoderOfSimpleType(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { - typeName := typ.String() - kind := typ.Kind() - switch kind { - case reflect.String: - if typeName != "string" { - return encoderOfType(cfg, reflect.TypeOf((*string)(nil)).Elem()) - } - return &stringCodec{}, nil - case reflect.Int: - if typeName != "int" { - return encoderOfType(cfg, reflect.TypeOf((*int)(nil)).Elem()) - } - return &intCodec{}, nil - case reflect.Int8: - if typeName != "int8" { - return encoderOfType(cfg, reflect.TypeOf((*int8)(nil)).Elem()) - } - return &int8Codec{}, nil - case reflect.Int16: - if typeName != "int16" { - return encoderOfType(cfg, reflect.TypeOf((*int16)(nil)).Elem()) - } - return &int16Codec{}, nil - case reflect.Int32: - if typeName != "int32" { - return encoderOfType(cfg, reflect.TypeOf((*int32)(nil)).Elem()) - } - return &int32Codec{}, nil - case reflect.Int64: - if typeName != "int64" { - return encoderOfType(cfg, reflect.TypeOf((*int64)(nil)).Elem()) - } - return &int64Codec{}, nil - case reflect.Uint: - if typeName != "uint" { - return encoderOfType(cfg, reflect.TypeOf((*uint)(nil)).Elem()) - } - return &uintCodec{}, nil - case reflect.Uint8: - if typeName != "uint8" { - return encoderOfType(cfg, reflect.TypeOf((*uint8)(nil)).Elem()) - } - return &uint8Codec{}, nil - case reflect.Uint16: - if typeName != "uint16" { - return encoderOfType(cfg, reflect.TypeOf((*uint16)(nil)).Elem()) - } - return &uint16Codec{}, nil - case reflect.Uint32: - if typeName != "uint32" { - return encoderOfType(cfg, reflect.TypeOf((*uint32)(nil)).Elem()) - } - return &uint32Codec{}, nil - case reflect.Uintptr: - if typeName != "uintptr" { - return encoderOfType(cfg, reflect.TypeOf((*uintptr)(nil)).Elem()) - } - return &uintptrCodec{}, nil - case reflect.Uint64: - if typeName != "uint64" { - return encoderOfType(cfg, reflect.TypeOf((*uint64)(nil)).Elem()) - } - return &uint64Codec{}, nil - case reflect.Float32: - if typeName != "float32" { - return encoderOfType(cfg, reflect.TypeOf((*float32)(nil)).Elem()) - } - return &float32Codec{}, nil - case reflect.Float64: - if typeName != "float64" { - return encoderOfType(cfg, reflect.TypeOf((*float64)(nil)).Elem()) - } - return &float64Codec{}, nil - case reflect.Bool: - if typeName != "bool" { - return encoderOfType(cfg, reflect.TypeOf((*bool)(nil)).Elem()) - } - return &boolCodec{}, nil - case reflect.Interface: - if typ.NumMethod() == 0 { - return &emptyInterfaceCodec{}, nil - } - return &nonEmptyInterfaceCodec{}, nil - case reflect.Struct: - return prefix(fmt.Sprintf("[%s]", typeName)).addToEncoder(encoderOfStruct(cfg, typ)) - case reflect.Array: - return prefix("[array]").addToEncoder(encoderOfArray(cfg, typ)) - case reflect.Slice: - return prefix("[slice]").addToEncoder(encoderOfSlice(cfg, typ)) - case reflect.Map: - return prefix("[map]").addToEncoder(encoderOfMap(cfg, typ)) - case reflect.Ptr: - return prefix("[optional]").addToEncoder(encoderOfOptional(cfg, typ)) - default: - return nil, fmt.Errorf("unsupported type: %v", typ) - } -} - -func decoderOfOptional(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) { - elemType := typ.Elem() - decoder, err := decoderOfType(cfg, elemType) - if err != nil { - return nil, err - } - return &optionalDecoder{elemType, decoder}, nil -} - -func encoderOfOptional(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { - elemType := typ.Elem() - elemEncoder, err := encoderOfType(cfg, elemType) - if err != nil { - return nil, err - } - encoder := &optionalEncoder{elemEncoder} - if elemType.Kind() == reflect.Map { - encoder = &optionalEncoder{encoder} - } - return encoder, nil -} - -func decoderOfMap(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) { - decoder, err := decoderOfType(cfg, typ.Elem()) - if err != nil { - return nil, err - } - mapInterface := reflect.New(typ).Interface() - return &mapDecoder{typ, typ.Key(), typ.Elem(), decoder, extractInterface(mapInterface)}, nil -} - -func extractInterface(val interface{}) emptyInterface { - return *((*emptyInterface)(unsafe.Pointer(&val))) -} - -func encoderOfMap(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { - elemType := typ.Elem() - encoder, err := encoderOfType(cfg, elemType) - if err != nil { - return nil, err - } - mapInterface := reflect.New(typ).Elem().Interface() - if cfg.sortMapKeys { - return &sortKeysMapEncoder{typ, elemType, encoder, *((*emptyInterface)(unsafe.Pointer(&mapInterface)))}, nil - } - return &mapEncoder{typ, elemType, encoder, *((*emptyInterface)(unsafe.Pointer(&mapInterface)))}, nil -} diff --git a/vendor/github.com/json-iterator/go/feature_reflect_array.go b/vendor/github.com/json-iterator/go/feature_reflect_array.go deleted file mode 100644 index e23f187b7c..0000000000 --- a/vendor/github.com/json-iterator/go/feature_reflect_array.go +++ /dev/null @@ -1,99 +0,0 @@ -package jsoniter - -import ( - "fmt" - "io" - "reflect" - "unsafe" -) - -func decoderOfArray(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) { - decoder, err := decoderOfType(cfg, typ.Elem()) - if err != nil { - return nil, err - } - return &arrayDecoder{typ, typ.Elem(), decoder}, nil -} - -func encoderOfArray(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { - encoder, err := encoderOfType(cfg, typ.Elem()) - if err != nil { - return nil, err - } - if typ.Elem().Kind() == reflect.Map { - encoder = &optionalEncoder{encoder} - } - return &arrayEncoder{typ, typ.Elem(), encoder}, nil -} - -type arrayEncoder struct { - arrayType reflect.Type - elemType reflect.Type - elemEncoder ValEncoder -} - -func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteArrayStart() - elemPtr := unsafe.Pointer(ptr) - encoder.elemEncoder.Encode(elemPtr, stream) - for i := 1; i < encoder.arrayType.Len(); i++ { - stream.WriteMore() - elemPtr = unsafe.Pointer(uintptr(elemPtr) + encoder.elemType.Size()) - encoder.elemEncoder.Encode(unsafe.Pointer(elemPtr), stream) - } - stream.WriteArrayEnd() - if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%v: %s", encoder.arrayType, stream.Error.Error()) - } -} - -func (encoder *arrayEncoder) EncodeInterface(val interface{}, stream *Stream) { - // special optimization for interface{} - e := (*emptyInterface)(unsafe.Pointer(&val)) - if e.word == nil { - stream.WriteArrayStart() - stream.WriteNil() - stream.WriteArrayEnd() - return - } - elemType := encoder.arrayType.Elem() - if encoder.arrayType.Len() == 1 && (elemType.Kind() == reflect.Ptr || elemType.Kind() == reflect.Map) { - ptr := uintptr(e.word) - e.word = unsafe.Pointer(&ptr) - } - if reflect.TypeOf(val).Kind() == reflect.Ptr { - encoder.Encode(unsafe.Pointer(&e.word), stream) - } else { - encoder.Encode(e.word, stream) - } -} - -func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return false -} - -type arrayDecoder struct { - arrayType reflect.Type - elemType reflect.Type - elemDecoder ValDecoder -} - -func (decoder *arrayDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.doDecode(ptr, iter) - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.arrayType, iter.Error.Error()) - } -} - -func (decoder *arrayDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { - offset := uintptr(0) - iter.ReadArrayCB(func(iter *Iterator) bool { - if offset < decoder.arrayType.Size() { - decoder.elemDecoder.Decode(unsafe.Pointer(uintptr(ptr)+offset), iter) - offset += decoder.elemType.Size() - } else { - iter.Skip() - } - return true - }) -} diff --git a/vendor/github.com/json-iterator/go/feature_reflect_map.go b/vendor/github.com/json-iterator/go/feature_reflect_map.go deleted file mode 100644 index 005671e01b..0000000000 --- a/vendor/github.com/json-iterator/go/feature_reflect_map.go +++ /dev/null @@ -1,244 +0,0 @@ -package jsoniter - -import ( - "encoding" - "encoding/json" - "reflect" - "sort" - "strconv" - "unsafe" -) - -type mapDecoder struct { - mapType reflect.Type - keyType reflect.Type - elemType reflect.Type - elemDecoder ValDecoder - mapInterface emptyInterface -} - -func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - // dark magic to cast unsafe.Pointer back to interface{} using reflect.Type - mapInterface := decoder.mapInterface - mapInterface.word = ptr - realInterface := (*interface{})(unsafe.Pointer(&mapInterface)) - realVal := reflect.ValueOf(*realInterface).Elem() - if iter.ReadNil() { - realVal.Set(reflect.Zero(decoder.mapType)) - return - } - if realVal.IsNil() { - realVal.Set(reflect.MakeMap(realVal.Type())) - } - iter.ReadMapCB(func(iter *Iterator, keyStr string) bool { - elem := reflect.New(decoder.elemType) - decoder.elemDecoder.Decode(unsafe.Pointer(elem.Pointer()), iter) - // to put into map, we have to use reflection - keyType := decoder.keyType - // TODO: remove this from loop - switch { - case keyType.Kind() == reflect.String: - realVal.SetMapIndex(reflect.ValueOf(keyStr).Convert(keyType), elem.Elem()) - return true - case keyType.Implements(textUnmarshalerType): - textUnmarshaler := reflect.New(keyType.Elem()).Interface().(encoding.TextUnmarshaler) - err := textUnmarshaler.UnmarshalText([]byte(keyStr)) - if err != nil { - iter.ReportError("read map key as TextUnmarshaler", err.Error()) - return false - } - realVal.SetMapIndex(reflect.ValueOf(textUnmarshaler), elem.Elem()) - return true - case reflect.PtrTo(keyType).Implements(textUnmarshalerType): - textUnmarshaler := reflect.New(keyType).Interface().(encoding.TextUnmarshaler) - err := textUnmarshaler.UnmarshalText([]byte(keyStr)) - if err != nil { - iter.ReportError("read map key as TextUnmarshaler", err.Error()) - return false - } - realVal.SetMapIndex(reflect.ValueOf(textUnmarshaler).Elem(), elem.Elem()) - return true - default: - switch keyType.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - n, err := strconv.ParseInt(keyStr, 10, 64) - if err != nil || reflect.Zero(keyType).OverflowInt(n) { - iter.ReportError("read map key as int64", "read int64 failed") - return false - } - realVal.SetMapIndex(reflect.ValueOf(n).Convert(keyType), elem.Elem()) - return true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - n, err := strconv.ParseUint(keyStr, 10, 64) - if err != nil || reflect.Zero(keyType).OverflowUint(n) { - iter.ReportError("read map key as uint64", "read uint64 failed") - return false - } - realVal.SetMapIndex(reflect.ValueOf(n).Convert(keyType), elem.Elem()) - return true - } - } - iter.ReportError("read map key", "unexpected map key type "+keyType.String()) - return true - }) -} - -type mapEncoder struct { - mapType reflect.Type - elemType reflect.Type - elemEncoder ValEncoder - mapInterface emptyInterface -} - -func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - mapInterface := encoder.mapInterface - mapInterface.word = ptr - realInterface := (*interface{})(unsafe.Pointer(&mapInterface)) - realVal := reflect.ValueOf(*realInterface) - stream.WriteObjectStart() - for i, key := range realVal.MapKeys() { - if i != 0 { - stream.WriteMore() - } - encodeMapKey(key, stream) - if stream.indention > 0 { - stream.writeTwoBytes(byte(':'), byte(' ')) - } else { - stream.writeByte(':') - } - val := realVal.MapIndex(key).Interface() - encoder.elemEncoder.EncodeInterface(val, stream) - } - stream.WriteObjectEnd() -} - -func encodeMapKey(key reflect.Value, stream *Stream) { - if key.Kind() == reflect.String { - stream.WriteString(key.String()) - return - } - if tm, ok := key.Interface().(encoding.TextMarshaler); ok { - buf, err := tm.MarshalText() - if err != nil { - stream.Error = err - return - } - stream.writeByte('"') - stream.Write(buf) - stream.writeByte('"') - return - } - switch key.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - stream.writeByte('"') - stream.WriteInt64(key.Int()) - stream.writeByte('"') - return - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - stream.writeByte('"') - stream.WriteUint64(key.Uint()) - stream.writeByte('"') - return - } - stream.Error = &json.UnsupportedTypeError{Type: key.Type()} -} - -func (encoder *mapEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - -func (encoder *mapEncoder) IsEmpty(ptr unsafe.Pointer) bool { - mapInterface := encoder.mapInterface - mapInterface.word = ptr - realInterface := (*interface{})(unsafe.Pointer(&mapInterface)) - realVal := reflect.ValueOf(*realInterface) - return realVal.Len() == 0 -} - -type sortKeysMapEncoder struct { - mapType reflect.Type - elemType reflect.Type - elemEncoder ValEncoder - mapInterface emptyInterface -} - -func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - mapInterface := encoder.mapInterface - mapInterface.word = ptr - realInterface := (*interface{})(unsafe.Pointer(&mapInterface)) - realVal := reflect.ValueOf(*realInterface) - - // Extract and sort the keys. - keys := realVal.MapKeys() - sv := stringValues(make([]reflectWithString, len(keys))) - for i, v := range keys { - sv[i].v = v - if err := sv[i].resolve(); err != nil { - stream.Error = err - return - } - } - sort.Sort(sv) - - stream.WriteObjectStart() - for i, key := range sv { - if i != 0 { - stream.WriteMore() - } - stream.WriteVal(key.s) // might need html escape, so can not WriteString directly - if stream.indention > 0 { - stream.writeTwoBytes(byte(':'), byte(' ')) - } else { - stream.writeByte(':') - } - val := realVal.MapIndex(key.v).Interface() - encoder.elemEncoder.EncodeInterface(val, stream) - } - stream.WriteObjectEnd() -} - -// stringValues is a slice of reflect.Value holding *reflect.StringValue. -// It implements the methods to sort by string. -type stringValues []reflectWithString - -type reflectWithString struct { - v reflect.Value - s string -} - -func (w *reflectWithString) resolve() error { - if w.v.Kind() == reflect.String { - w.s = w.v.String() - return nil - } - if tm, ok := w.v.Interface().(encoding.TextMarshaler); ok { - buf, err := tm.MarshalText() - w.s = string(buf) - return err - } - switch w.v.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - w.s = strconv.FormatInt(w.v.Int(), 10) - return nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - w.s = strconv.FormatUint(w.v.Uint(), 10) - return nil - } - return &json.UnsupportedTypeError{Type: w.v.Type()} -} - -func (sv stringValues) Len() int { return len(sv) } -func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } -func (sv stringValues) Less(i, j int) bool { return sv[i].s < sv[j].s } - -func (encoder *sortKeysMapEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - -func (encoder *sortKeysMapEncoder) IsEmpty(ptr unsafe.Pointer) bool { - mapInterface := encoder.mapInterface - mapInterface.word = ptr - realInterface := (*interface{})(unsafe.Pointer(&mapInterface)) - realVal := reflect.ValueOf(*realInterface) - return realVal.Len() == 0 -} diff --git a/vendor/github.com/json-iterator/go/feature_reflect_native.go b/vendor/github.com/json-iterator/go/feature_reflect_native.go deleted file mode 100644 index 95bd1e87cc..0000000000 --- a/vendor/github.com/json-iterator/go/feature_reflect_native.go +++ /dev/null @@ -1,764 +0,0 @@ -package jsoniter - -import ( - "encoding" - "encoding/base64" - "encoding/json" - "reflect" - "unsafe" -) - -type stringCodec struct { -} - -func (codec *stringCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - *((*string)(ptr)) = iter.ReadString() -} - -func (codec *stringCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - str := *((*string)(ptr)) - stream.WriteString(str) -} - -func (codec *stringCodec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *stringCodec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*string)(ptr)) == "" -} - -type intCodec struct { -} - -func (codec *intCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int)(ptr)) = iter.ReadInt() - } -} - -func (codec *intCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt(*((*int)(ptr))) -} - -func (codec *intCodec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *intCodec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int)(ptr)) == 0 -} - -type uintptrCodec struct { -} - -func (codec *uintptrCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uintptr)(ptr)) = uintptr(iter.ReadUint64()) - } -} - -func (codec *uintptrCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint64(uint64(*((*uintptr)(ptr)))) -} - -func (codec *uintptrCodec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *uintptrCodec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uintptr)(ptr)) == 0 -} - -type int8Codec struct { -} - -func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int8)(ptr)) = iter.ReadInt8() - } -} - -func (codec *int8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt8(*((*int8)(ptr))) -} - -func (codec *int8Codec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int8)(ptr)) == 0 -} - -type int16Codec struct { -} - -func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int16)(ptr)) = iter.ReadInt16() - } -} - -func (codec *int16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt16(*((*int16)(ptr))) -} - -func (codec *int16Codec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int16)(ptr)) == 0 -} - -type int32Codec struct { -} - -func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int32)(ptr)) = iter.ReadInt32() - } -} - -func (codec *int32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt32(*((*int32)(ptr))) -} - -func (codec *int32Codec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int32)(ptr)) == 0 -} - -type int64Codec struct { -} - -func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*int64)(ptr)) = iter.ReadInt64() - } -} - -func (codec *int64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteInt64(*((*int64)(ptr))) -} - -func (codec *int64Codec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*int64)(ptr)) == 0 -} - -type uintCodec struct { -} - -func (codec *uintCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint)(ptr)) = iter.ReadUint() - return - } -} - -func (codec *uintCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint(*((*uint)(ptr))) -} - -func (codec *uintCodec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *uintCodec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint)(ptr)) == 0 -} - -type uint8Codec struct { -} - -func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint8)(ptr)) = iter.ReadUint8() - } -} - -func (codec *uint8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint8(*((*uint8)(ptr))) -} - -func (codec *uint8Codec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint8)(ptr)) == 0 -} - -type uint16Codec struct { -} - -func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint16)(ptr)) = iter.ReadUint16() - } -} - -func (codec *uint16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint16(*((*uint16)(ptr))) -} - -func (codec *uint16Codec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint16)(ptr)) == 0 -} - -type uint32Codec struct { -} - -func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint32)(ptr)) = iter.ReadUint32() - } -} - -func (codec *uint32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint32(*((*uint32)(ptr))) -} - -func (codec *uint32Codec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint32)(ptr)) == 0 -} - -type uint64Codec struct { -} - -func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*uint64)(ptr)) = iter.ReadUint64() - } -} - -func (codec *uint64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteUint64(*((*uint64)(ptr))) -} - -func (codec *uint64Codec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*uint64)(ptr)) == 0 -} - -type float32Codec struct { -} - -func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*float32)(ptr)) = iter.ReadFloat32() - } -} - -func (codec *float32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteFloat32(*((*float32)(ptr))) -} - -func (codec *float32Codec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*float32)(ptr)) == 0 -} - -type float64Codec struct { -} - -func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*float64)(ptr)) = iter.ReadFloat64() - } -} - -func (codec *float64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteFloat64(*((*float64)(ptr))) -} - -func (codec *float64Codec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return *((*float64)(ptr)) == 0 -} - -type boolCodec struct { -} - -func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if !iter.ReadNil() { - *((*bool)(ptr)) = iter.ReadBool() - } -} - -func (codec *boolCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteBool(*((*bool)(ptr))) -} - -func (codec *boolCodec) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, codec) -} - -func (codec *boolCodec) IsEmpty(ptr unsafe.Pointer) bool { - return !(*((*bool)(ptr))) -} - -type emptyInterfaceCodec struct { -} - -func (codec *emptyInterfaceCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - existing := *((*interface{})(ptr)) - - // Checking for both typed and untyped nil pointers. - if existing != nil && - reflect.TypeOf(existing).Kind() == reflect.Ptr && - !reflect.ValueOf(existing).IsNil() { - - var ptrToExisting interface{} - for { - elem := reflect.ValueOf(existing).Elem() - if elem.Kind() != reflect.Ptr || elem.IsNil() { - break - } - ptrToExisting = existing - existing = elem.Interface() - } - - if iter.ReadNil() { - if ptrToExisting != nil { - nilPtr := reflect.Zero(reflect.TypeOf(ptrToExisting).Elem()) - reflect.ValueOf(ptrToExisting).Elem().Set(nilPtr) - } else { - *((*interface{})(ptr)) = nil - } - } else { - iter.ReadVal(existing) - } - - return - } - - if iter.ReadNil() { - *((*interface{})(ptr)) = nil - } else { - *((*interface{})(ptr)) = iter.Read() - } -} - -func (codec *emptyInterfaceCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteVal(*((*interface{})(ptr))) -} - -func (codec *emptyInterfaceCodec) EncodeInterface(val interface{}, stream *Stream) { - stream.WriteVal(val) -} - -func (codec *emptyInterfaceCodec) IsEmpty(ptr unsafe.Pointer) bool { - emptyInterface := (*emptyInterface)(ptr) - return emptyInterface.typ == nil -} - -type nonEmptyInterfaceCodec struct { -} - -func (codec *nonEmptyInterfaceCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - nonEmptyInterface := (*nonEmptyInterface)(ptr) - if nonEmptyInterface.itab == nil { - iter.ReportError("read non-empty interface", "do not know which concrete type to decode to") - return - } - var i interface{} - e := (*emptyInterface)(unsafe.Pointer(&i)) - e.typ = nonEmptyInterface.itab.typ - e.word = nonEmptyInterface.word - iter.ReadVal(&i) - if e.word == nil { - nonEmptyInterface.itab = nil - } - nonEmptyInterface.word = e.word -} - -func (codec *nonEmptyInterfaceCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - nonEmptyInterface := (*nonEmptyInterface)(ptr) - var i interface{} - if nonEmptyInterface.itab != nil { - e := (*emptyInterface)(unsafe.Pointer(&i)) - e.typ = nonEmptyInterface.itab.typ - e.word = nonEmptyInterface.word - } - stream.WriteVal(i) -} - -func (codec *nonEmptyInterfaceCodec) EncodeInterface(val interface{}, stream *Stream) { - stream.WriteVal(val) -} - -func (codec *nonEmptyInterfaceCodec) IsEmpty(ptr unsafe.Pointer) bool { - nonEmptyInterface := (*nonEmptyInterface)(ptr) - return nonEmptyInterface.word == nil -} - -type anyCodec struct { -} - -func (codec *anyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - *((*Any)(ptr)) = iter.ReadAny() -} - -func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - (*((*Any)(ptr))).WriteTo(stream) -} - -func (codec *anyCodec) EncodeInterface(val interface{}, stream *Stream) { - (val.(Any)).WriteTo(stream) -} - -func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool { - return (*((*Any)(ptr))).Size() == 0 -} - -type jsonNumberCodec struct { -} - -func (codec *jsonNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - switch iter.WhatIsNext() { - case StringValue: - *((*json.Number)(ptr)) = json.Number(iter.ReadString()) - case NilValue: - iter.skipFourBytes('n', 'u', 'l', 'l') - *((*json.Number)(ptr)) = "" - default: - *((*json.Number)(ptr)) = json.Number([]byte(iter.readNumberAsString())) - } -} - -func (codec *jsonNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteRaw(string(*((*json.Number)(ptr)))) -} - -func (codec *jsonNumberCodec) EncodeInterface(val interface{}, stream *Stream) { - stream.WriteRaw(string(val.(json.Number))) -} - -func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*json.Number)(ptr))) == 0 -} - -type jsoniterNumberCodec struct { -} - -func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - switch iter.WhatIsNext() { - case StringValue: - *((*Number)(ptr)) = Number(iter.ReadString()) - case NilValue: - iter.skipFourBytes('n', 'u', 'l', 'l') - *((*Number)(ptr)) = "" - default: - *((*Number)(ptr)) = Number([]byte(iter.readNumberAsString())) - } -} - -func (codec *jsoniterNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteRaw(string(*((*Number)(ptr)))) -} - -func (codec *jsoniterNumberCodec) EncodeInterface(val interface{}, stream *Stream) { - stream.WriteRaw(string(val.(Number))) -} - -func (codec *jsoniterNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*Number)(ptr))) == 0 -} - -type jsonRawMessageCodec struct { -} - -func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - *((*json.RawMessage)(ptr)) = json.RawMessage(iter.SkipAndReturnBytes()) -} - -func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteRaw(string(*((*json.RawMessage)(ptr)))) -} - -func (codec *jsonRawMessageCodec) EncodeInterface(val interface{}, stream *Stream) { - stream.WriteRaw(string(val.(json.RawMessage))) -} - -func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*json.RawMessage)(ptr))) == 0 -} - -type jsoniterRawMessageCodec struct { -} - -func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { - *((*RawMessage)(ptr)) = RawMessage(iter.SkipAndReturnBytes()) -} - -func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.WriteRaw(string(*((*RawMessage)(ptr)))) -} - -func (codec *jsoniterRawMessageCodec) EncodeInterface(val interface{}, stream *Stream) { - stream.WriteRaw(string(val.(RawMessage))) -} - -func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*RawMessage)(ptr))) == 0 -} - -type base64Codec struct { - sliceDecoder ValDecoder -} - -func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { - if iter.ReadNil() { - ptrSlice := (*sliceHeader)(ptr) - ptrSlice.Len = 0 - ptrSlice.Cap = 0 - ptrSlice.Data = nil - return - } - switch iter.WhatIsNext() { - case StringValue: - encoding := base64.StdEncoding - src := iter.SkipAndReturnBytes() - src = src[1 : len(src)-1] - decodedLen := encoding.DecodedLen(len(src)) - dst := make([]byte, decodedLen) - len, err := encoding.Decode(dst, src) - if err != nil { - iter.ReportError("decode base64", err.Error()) - } else { - dst = dst[:len] - dstSlice := (*sliceHeader)(unsafe.Pointer(&dst)) - ptrSlice := (*sliceHeader)(ptr) - ptrSlice.Data = dstSlice.Data - ptrSlice.Cap = dstSlice.Cap - ptrSlice.Len = dstSlice.Len - } - case ArrayValue: - codec.sliceDecoder.Decode(ptr, iter) - default: - iter.ReportError("base64Codec", "invalid input") - } -} - -func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { - src := *((*[]byte)(ptr)) - if len(src) == 0 { - stream.WriteNil() - return - } - encoding := base64.StdEncoding - stream.writeByte('"') - toGrow := encoding.EncodedLen(len(src)) - stream.ensure(toGrow) - encoding.Encode(stream.buf[stream.n:], src) - stream.n += toGrow - stream.writeByte('"') -} - -func (codec *base64Codec) EncodeInterface(val interface{}, stream *Stream) { - ptr := extractInterface(val).word - src := *((*[]byte)(ptr)) - if len(src) == 0 { - stream.WriteNil() - return - } - encoding := base64.StdEncoding - stream.writeByte('"') - toGrow := encoding.EncodedLen(len(src)) - stream.ensure(toGrow) - encoding.Encode(stream.buf[stream.n:], src) - stream.n += toGrow - stream.writeByte('"') -} - -func (codec *base64Codec) IsEmpty(ptr unsafe.Pointer) bool { - return len(*((*[]byte)(ptr))) == 0 -} - -type stringModeNumberDecoder struct { - elemDecoder ValDecoder -} - -func (decoder *stringModeNumberDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - c := iter.nextToken() - if c != '"' { - iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) - return - } - decoder.elemDecoder.Decode(ptr, iter) - if iter.Error != nil { - return - } - c = iter.readByte() - if c != '"' { - iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) - return - } -} - -type stringModeStringDecoder struct { - elemDecoder ValDecoder - cfg *frozenConfig -} - -func (decoder *stringModeStringDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.elemDecoder.Decode(ptr, iter) - str := *((*string)(ptr)) - tempIter := decoder.cfg.BorrowIterator([]byte(str)) - defer decoder.cfg.ReturnIterator(tempIter) - *((*string)(ptr)) = tempIter.ReadString() -} - -type stringModeNumberEncoder struct { - elemEncoder ValEncoder -} - -func (encoder *stringModeNumberEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - stream.writeByte('"') - encoder.elemEncoder.Encode(ptr, stream) - stream.writeByte('"') -} - -func (encoder *stringModeNumberEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - -func (encoder *stringModeNumberEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.elemEncoder.IsEmpty(ptr) -} - -type stringModeStringEncoder struct { - elemEncoder ValEncoder - cfg *frozenConfig -} - -func (encoder *stringModeStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - tempStream := encoder.cfg.BorrowStream(nil) - defer encoder.cfg.ReturnStream(tempStream) - encoder.elemEncoder.Encode(ptr, tempStream) - stream.WriteString(string(tempStream.Buffer())) -} - -func (encoder *stringModeStringEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - -func (encoder *stringModeStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.elemEncoder.IsEmpty(ptr) -} - -type marshalerEncoder struct { - templateInterface emptyInterface - checkIsEmpty checkIsEmpty -} - -func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - templateInterface := encoder.templateInterface - templateInterface.word = ptr - realInterface := (*interface{})(unsafe.Pointer(&templateInterface)) - marshaler, ok := (*realInterface).(json.Marshaler) - if !ok { - stream.WriteVal(nil) - return - } - - bytes, err := marshaler.MarshalJSON() - if err != nil { - stream.Error = err - } else { - stream.Write(bytes) - } -} -func (encoder *marshalerEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - -func (encoder *marshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.checkIsEmpty.IsEmpty(ptr) -} - -type textMarshalerEncoder struct { - templateInterface emptyInterface - checkIsEmpty checkIsEmpty -} - -func (encoder *textMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - templateInterface := encoder.templateInterface - templateInterface.word = ptr - realInterface := (*interface{})(unsafe.Pointer(&templateInterface)) - marshaler := (*realInterface).(encoding.TextMarshaler) - bytes, err := marshaler.MarshalText() - if err != nil { - stream.Error = err - } else { - stream.WriteString(string(bytes)) - } -} - -func (encoder *textMarshalerEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - -func (encoder *textMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { - return encoder.checkIsEmpty.IsEmpty(ptr) -} - -type unmarshalerDecoder struct { - templateInterface emptyInterface -} - -func (decoder *unmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - templateInterface := decoder.templateInterface - templateInterface.word = ptr - realInterface := (*interface{})(unsafe.Pointer(&templateInterface)) - unmarshaler := (*realInterface).(json.Unmarshaler) - iter.nextToken() - iter.unreadByte() // skip spaces - bytes := iter.SkipAndReturnBytes() - err := unmarshaler.UnmarshalJSON(bytes) - if err != nil { - iter.ReportError("unmarshalerDecoder", err.Error()) - } -} - -type textUnmarshalerDecoder struct { - templateInterface emptyInterface -} - -func (decoder *textUnmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - templateInterface := decoder.templateInterface - templateInterface.word = ptr - realInterface := (*interface{})(unsafe.Pointer(&templateInterface)) - unmarshaler := (*realInterface).(encoding.TextUnmarshaler) - str := iter.ReadString() - err := unmarshaler.UnmarshalText([]byte(str)) - if err != nil { - iter.ReportError("textUnmarshalerDecoder", err.Error()) - } -} diff --git a/vendor/github.com/json-iterator/go/feature_reflect_slice.go b/vendor/github.com/json-iterator/go/feature_reflect_slice.go deleted file mode 100644 index 7377eec7b3..0000000000 --- a/vendor/github.com/json-iterator/go/feature_reflect_slice.go +++ /dev/null @@ -1,149 +0,0 @@ -package jsoniter - -import ( - "fmt" - "io" - "reflect" - "unsafe" -) - -func decoderOfSlice(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) { - decoder, err := decoderOfType(cfg, typ.Elem()) - if err != nil { - return nil, err - } - return &sliceDecoder{typ, typ.Elem(), decoder}, nil -} - -func encoderOfSlice(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { - encoder, err := encoderOfType(cfg, typ.Elem()) - if err != nil { - return nil, err - } - if typ.Elem().Kind() == reflect.Map { - encoder = &optionalEncoder{encoder} - } - return &sliceEncoder{typ, typ.Elem(), encoder}, nil -} - -type sliceEncoder struct { - sliceType reflect.Type - elemType reflect.Type - elemEncoder ValEncoder -} - -func (encoder *sliceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - slice := (*sliceHeader)(ptr) - if slice.Data == nil { - stream.WriteNil() - return - } - if slice.Len == 0 { - stream.WriteEmptyArray() - return - } - stream.WriteArrayStart() - elemPtr := unsafe.Pointer(slice.Data) - encoder.elemEncoder.Encode(unsafe.Pointer(elemPtr), stream) - for i := 1; i < slice.Len; i++ { - stream.WriteMore() - elemPtr = unsafe.Pointer(uintptr(elemPtr) + encoder.elemType.Size()) - encoder.elemEncoder.Encode(unsafe.Pointer(elemPtr), stream) - } - stream.WriteArrayEnd() - if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%v: %s", encoder.sliceType, stream.Error.Error()) - } -} - -func (encoder *sliceEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - -func (encoder *sliceEncoder) IsEmpty(ptr unsafe.Pointer) bool { - slice := (*sliceHeader)(ptr) - return slice.Len == 0 -} - -type sliceDecoder struct { - sliceType reflect.Type - elemType reflect.Type - elemDecoder ValDecoder -} - -// sliceHeader is a safe version of SliceHeader used within this package. -type sliceHeader struct { - Data unsafe.Pointer - Len int - Cap int -} - -func (decoder *sliceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - decoder.doDecode(ptr, iter) - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.sliceType, iter.Error.Error()) - } -} - -func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { - slice := (*sliceHeader)(ptr) - if iter.ReadNil() { - slice.Len = 0 - slice.Cap = 0 - slice.Data = nil - return - } - reuseSlice(slice, decoder.sliceType, 4) - slice.Len = 0 - offset := uintptr(0) - iter.ReadArrayCB(func(iter *Iterator) bool { - growOne(slice, decoder.sliceType, decoder.elemType) - decoder.elemDecoder.Decode(unsafe.Pointer(uintptr(slice.Data)+offset), iter) - offset += decoder.elemType.Size() - return true - }) -} - -// grow grows the slice s so that it can hold extra more values, allocating -// more capacity if needed. It also returns the old and new slice lengths. -func growOne(slice *sliceHeader, sliceType reflect.Type, elementType reflect.Type) { - newLen := slice.Len + 1 - if newLen <= slice.Cap { - slice.Len = newLen - return - } - newCap := slice.Cap - if newCap == 0 { - newCap = 1 - } else { - for newCap < newLen { - if slice.Len < 1024 { - newCap += newCap - } else { - newCap += newCap / 4 - } - } - } - newVal := reflect.MakeSlice(sliceType, newLen, newCap) - dst := unsafe.Pointer(newVal.Pointer()) - // copy old array into new array - originalBytesCount := uintptr(slice.Len) * elementType.Size() - srcPtr := (*[1 << 30]byte)(slice.Data) - dstPtr := (*[1 << 30]byte)(dst) - for i := uintptr(0); i < originalBytesCount; i++ { - dstPtr[i] = srcPtr[i] - } - slice.Data = dst - slice.Len = newLen - slice.Cap = newCap -} - -func reuseSlice(slice *sliceHeader, sliceType reflect.Type, expectedCap int) { - if expectedCap <= slice.Cap { - return - } - newVal := reflect.MakeSlice(sliceType, 0, expectedCap) - dst := unsafe.Pointer(newVal.Pointer()) - slice.Data = dst - slice.Cap = expectedCap -} diff --git a/vendor/github.com/json-iterator/go/feature_stream_int.go b/vendor/github.com/json-iterator/go/feature_stream_int.go deleted file mode 100644 index 7cfd522c10..0000000000 --- a/vendor/github.com/json-iterator/go/feature_stream_int.go +++ /dev/null @@ -1,320 +0,0 @@ -package jsoniter - -var digits []uint32 - -func init() { - digits = make([]uint32, 1000) - for i := uint32(0); i < 1000; i++ { - digits[i] = (((i / 100) + '0') << 16) + ((((i / 10) % 10) + '0') << 8) + i%10 + '0' - if i < 10 { - digits[i] += 2 << 24 - } else if i < 100 { - digits[i] += 1 << 24 - } - } -} - -func writeFirstBuf(buf []byte, v uint32, n int) int { - start := v >> 24 - if start == 0 { - buf[n] = byte(v >> 16) - n++ - buf[n] = byte(v >> 8) - n++ - } else if start == 1 { - buf[n] = byte(v >> 8) - n++ - } - buf[n] = byte(v) - n++ - return n -} - -func writeBuf(buf []byte, v uint32, n int) { - buf[n] = byte(v >> 16) - buf[n+1] = byte(v >> 8) - buf[n+2] = byte(v) -} - -// WriteUint8 write uint8 to stream -func (stream *Stream) WriteUint8(val uint8) { - stream.ensure(3) - stream.n = writeFirstBuf(stream.buf, digits[val], stream.n) -} - -// WriteInt8 write int8 to stream -func (stream *Stream) WriteInt8(nval int8) { - stream.ensure(4) - n := stream.n - var val uint8 - if nval < 0 { - val = uint8(-nval) - stream.buf[n] = '-' - n++ - } else { - val = uint8(nval) - } - stream.n = writeFirstBuf(stream.buf, digits[val], n) -} - -// WriteUint16 write uint16 to stream -func (stream *Stream) WriteUint16(val uint16) { - stream.ensure(5) - q1 := val / 1000 - if q1 == 0 { - stream.n = writeFirstBuf(stream.buf, digits[val], stream.n) - return - } - r1 := val - q1*1000 - n := writeFirstBuf(stream.buf, digits[q1], stream.n) - writeBuf(stream.buf, digits[r1], n) - stream.n = n + 3 - return -} - -// WriteInt16 write int16 to stream -func (stream *Stream) WriteInt16(nval int16) { - stream.ensure(6) - n := stream.n - var val uint16 - if nval < 0 { - val = uint16(-nval) - stream.buf[n] = '-' - n++ - } else { - val = uint16(nval) - } - q1 := val / 1000 - if q1 == 0 { - stream.n = writeFirstBuf(stream.buf, digits[val], n) - return - } - r1 := val - q1*1000 - n = writeFirstBuf(stream.buf, digits[q1], n) - writeBuf(stream.buf, digits[r1], n) - stream.n = n + 3 - return -} - -// WriteUint32 write uint32 to stream -func (stream *Stream) WriteUint32(val uint32) { - stream.ensure(10) - n := stream.n - q1 := val / 1000 - if q1 == 0 { - stream.n = writeFirstBuf(stream.buf, digits[val], n) - return - } - r1 := val - q1*1000 - q2 := q1 / 1000 - if q2 == 0 { - n := writeFirstBuf(stream.buf, digits[q1], n) - writeBuf(stream.buf, digits[r1], n) - stream.n = n + 3 - return - } - r2 := q1 - q2*1000 - q3 := q2 / 1000 - if q3 == 0 { - n = writeFirstBuf(stream.buf, digits[q2], n) - } else { - r3 := q2 - q3*1000 - stream.buf[n] = byte(q3 + '0') - n++ - writeBuf(stream.buf, digits[r3], n) - n += 3 - } - writeBuf(stream.buf, digits[r2], n) - writeBuf(stream.buf, digits[r1], n+3) - stream.n = n + 6 -} - -// WriteInt32 write int32 to stream -func (stream *Stream) WriteInt32(nval int32) { - stream.ensure(11) - n := stream.n - var val uint32 - if nval < 0 { - val = uint32(-nval) - stream.buf[n] = '-' - n++ - } else { - val = uint32(nval) - } - q1 := val / 1000 - if q1 == 0 { - stream.n = writeFirstBuf(stream.buf, digits[val], n) - return - } - r1 := val - q1*1000 - q2 := q1 / 1000 - if q2 == 0 { - n := writeFirstBuf(stream.buf, digits[q1], n) - writeBuf(stream.buf, digits[r1], n) - stream.n = n + 3 - return - } - r2 := q1 - q2*1000 - q3 := q2 / 1000 - if q3 == 0 { - n = writeFirstBuf(stream.buf, digits[q2], n) - } else { - r3 := q2 - q3*1000 - stream.buf[n] = byte(q3 + '0') - n++ - writeBuf(stream.buf, digits[r3], n) - n += 3 - } - writeBuf(stream.buf, digits[r2], n) - writeBuf(stream.buf, digits[r1], n+3) - stream.n = n + 6 -} - -// WriteUint64 write uint64 to stream -func (stream *Stream) WriteUint64(val uint64) { - stream.ensure(20) - n := stream.n - q1 := val / 1000 - if q1 == 0 { - stream.n = writeFirstBuf(stream.buf, digits[val], n) - return - } - r1 := val - q1*1000 - q2 := q1 / 1000 - if q2 == 0 { - n := writeFirstBuf(stream.buf, digits[q1], n) - writeBuf(stream.buf, digits[r1], n) - stream.n = n + 3 - return - } - r2 := q1 - q2*1000 - q3 := q2 / 1000 - if q3 == 0 { - n = writeFirstBuf(stream.buf, digits[q2], n) - writeBuf(stream.buf, digits[r2], n) - writeBuf(stream.buf, digits[r1], n+3) - stream.n = n + 6 - return - } - r3 := q2 - q3*1000 - q4 := q3 / 1000 - if q4 == 0 { - n = writeFirstBuf(stream.buf, digits[q3], n) - writeBuf(stream.buf, digits[r3], n) - writeBuf(stream.buf, digits[r2], n+3) - writeBuf(stream.buf, digits[r1], n+6) - stream.n = n + 9 - return - } - r4 := q3 - q4*1000 - q5 := q4 / 1000 - if q5 == 0 { - n = writeFirstBuf(stream.buf, digits[q4], n) - writeBuf(stream.buf, digits[r4], n) - writeBuf(stream.buf, digits[r3], n+3) - writeBuf(stream.buf, digits[r2], n+6) - writeBuf(stream.buf, digits[r1], n+9) - stream.n = n + 12 - return - } - r5 := q4 - q5*1000 - q6 := q5 / 1000 - if q6 == 0 { - n = writeFirstBuf(stream.buf, digits[q5], n) - } else { - n = writeFirstBuf(stream.buf, digits[q6], n) - r6 := q5 - q6*1000 - writeBuf(stream.buf, digits[r6], n) - n += 3 - } - writeBuf(stream.buf, digits[r5], n) - writeBuf(stream.buf, digits[r4], n+3) - writeBuf(stream.buf, digits[r3], n+6) - writeBuf(stream.buf, digits[r2], n+9) - writeBuf(stream.buf, digits[r1], n+12) - stream.n = n + 15 -} - -// WriteInt64 write int64 to stream -func (stream *Stream) WriteInt64(nval int64) { - stream.ensure(20) - n := stream.n - var val uint64 - if nval < 0 { - val = uint64(-nval) - stream.buf[n] = '-' - n++ - } else { - val = uint64(nval) - } - q1 := val / 1000 - if q1 == 0 { - stream.n = writeFirstBuf(stream.buf, digits[val], n) - return - } - r1 := val - q1*1000 - q2 := q1 / 1000 - if q2 == 0 { - n := writeFirstBuf(stream.buf, digits[q1], n) - writeBuf(stream.buf, digits[r1], n) - stream.n = n + 3 - return - } - r2 := q1 - q2*1000 - q3 := q2 / 1000 - if q3 == 0 { - n = writeFirstBuf(stream.buf, digits[q2], n) - writeBuf(stream.buf, digits[r2], n) - writeBuf(stream.buf, digits[r1], n+3) - stream.n = n + 6 - return - } - r3 := q2 - q3*1000 - q4 := q3 / 1000 - if q4 == 0 { - n = writeFirstBuf(stream.buf, digits[q3], n) - writeBuf(stream.buf, digits[r3], n) - writeBuf(stream.buf, digits[r2], n+3) - writeBuf(stream.buf, digits[r1], n+6) - stream.n = n + 9 - return - } - r4 := q3 - q4*1000 - q5 := q4 / 1000 - if q5 == 0 { - n = writeFirstBuf(stream.buf, digits[q4], n) - writeBuf(stream.buf, digits[r4], n) - writeBuf(stream.buf, digits[r3], n+3) - writeBuf(stream.buf, digits[r2], n+6) - writeBuf(stream.buf, digits[r1], n+9) - stream.n = n + 12 - return - } - r5 := q4 - q5*1000 - q6 := q5 / 1000 - if q6 == 0 { - n = writeFirstBuf(stream.buf, digits[q5], n) - } else { - stream.buf[n] = byte(q6 + '0') - n++ - r6 := q5 - q6*1000 - writeBuf(stream.buf, digits[r6], n) - n += 3 - } - writeBuf(stream.buf, digits[r5], n) - writeBuf(stream.buf, digits[r4], n+3) - writeBuf(stream.buf, digits[r3], n+6) - writeBuf(stream.buf, digits[r2], n+9) - writeBuf(stream.buf, digits[r1], n+12) - stream.n = n + 15 -} - -// WriteInt write int to stream -func (stream *Stream) WriteInt(val int) { - stream.WriteInt64(int64(val)) -} - -// WriteUint write uint to stream -func (stream *Stream) WriteUint(val uint) { - stream.WriteUint64(uint64(val)) -} diff --git a/vendor/github.com/json-iterator/go/feature_iter.go b/vendor/github.com/json-iterator/go/iter.go similarity index 97% rename from vendor/github.com/json-iterator/go/feature_iter.go rename to vendor/github.com/json-iterator/go/iter.go index 54a3a0fd9c..95ae54fbfe 100644 --- a/vendor/github.com/json-iterator/go/feature_iter.go +++ b/vendor/github.com/json-iterator/go/iter.go @@ -77,6 +77,7 @@ type Iterator struct { captureStartedAt int captured []byte Error error + Attachment interface{} // open for customized decoder } // NewIterator creates an empty Iterator instance @@ -167,7 +168,7 @@ func (iter *Iterator) isObjectEnd() bool { if c == '}' { return true } - iter.ReportError("isObjectEnd", "object ended prematurely") + iter.ReportError("isObjectEnd", "object ended prematurely, unexpected char "+string([]byte{c})) return true } diff --git a/vendor/github.com/json-iterator/go/feature_iter_array.go b/vendor/github.com/json-iterator/go/iter_array.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_iter_array.go rename to vendor/github.com/json-iterator/go/iter_array.go diff --git a/vendor/github.com/json-iterator/go/feature_iter_float.go b/vendor/github.com/json-iterator/go/iter_float.go similarity index 98% rename from vendor/github.com/json-iterator/go/feature_iter_float.go rename to vendor/github.com/json-iterator/go/iter_float.go index 86f4599122..4f883c0959 100644 --- a/vendor/github.com/json-iterator/go/feature_iter_float.go +++ b/vendor/github.com/json-iterator/go/iter_float.go @@ -1,6 +1,7 @@ package jsoniter import ( + "encoding/json" "io" "math/big" "strconv" @@ -339,3 +340,8 @@ func validateFloat(str string) string { } return "" } + +// ReadNumber read json.Number +func (iter *Iterator) ReadNumber() (ret json.Number) { + return json.Number(iter.readNumberAsString()) +} diff --git a/vendor/github.com/json-iterator/go/feature_iter_int.go b/vendor/github.com/json-iterator/go/iter_int.go similarity index 72% rename from vendor/github.com/json-iterator/go/feature_iter_int.go rename to vendor/github.com/json-iterator/go/iter_int.go index 886879efdb..2142320355 100644 --- a/vendor/github.com/json-iterator/go/feature_iter_int.go +++ b/vendor/github.com/json-iterator/go/iter_int.go @@ -22,11 +22,17 @@ func init() { // ReadUint read uint func (iter *Iterator) ReadUint() uint { + if strconv.IntSize == 32 { + return uint(iter.ReadUint32()) + } return uint(iter.ReadUint64()) } // ReadInt read int func (iter *Iterator) ReadInt() int { + if strconv.IntSize == 32 { + return int(iter.ReadInt32()) + } return int(iter.ReadInt64()) } @@ -115,6 +121,7 @@ func (iter *Iterator) ReadUint32() (ret uint32) { func (iter *Iterator) readUint32(c byte) (ret uint32) { ind := intDigits[c] if ind == 0 { + iter.assertInteger() return 0 // single zero } if ind == invalidCharForNumber { @@ -127,12 +134,14 @@ func (iter *Iterator) readUint32(c byte) (ret uint32) { ind2 := intDigits[iter.buf[i]] if ind2 == invalidCharForNumber { iter.head = i + iter.assertInteger() return value } i++ ind3 := intDigits[iter.buf[i]] if ind3 == invalidCharForNumber { iter.head = i + iter.assertInteger() return value*10 + uint32(ind2) } //iter.head = i + 1 @@ -141,30 +150,35 @@ func (iter *Iterator) readUint32(c byte) (ret uint32) { ind4 := intDigits[iter.buf[i]] if ind4 == invalidCharForNumber { iter.head = i + iter.assertInteger() return value*100 + uint32(ind2)*10 + uint32(ind3) } i++ ind5 := intDigits[iter.buf[i]] if ind5 == invalidCharForNumber { iter.head = i + iter.assertInteger() return value*1000 + uint32(ind2)*100 + uint32(ind3)*10 + uint32(ind4) } i++ ind6 := intDigits[iter.buf[i]] if ind6 == invalidCharForNumber { iter.head = i + iter.assertInteger() return value*10000 + uint32(ind2)*1000 + uint32(ind3)*100 + uint32(ind4)*10 + uint32(ind5) } i++ ind7 := intDigits[iter.buf[i]] if ind7 == invalidCharForNumber { iter.head = i + iter.assertInteger() return value*100000 + uint32(ind2)*10000 + uint32(ind3)*1000 + uint32(ind4)*100 + uint32(ind5)*10 + uint32(ind6) } i++ ind8 := intDigits[iter.buf[i]] if ind8 == invalidCharForNumber { iter.head = i + iter.assertInteger() return value*1000000 + uint32(ind2)*100000 + uint32(ind3)*10000 + uint32(ind4)*1000 + uint32(ind5)*100 + uint32(ind6)*10 + uint32(ind7) } i++ @@ -172,6 +186,7 @@ func (iter *Iterator) readUint32(c byte) (ret uint32) { value = value*10000000 + uint32(ind2)*1000000 + uint32(ind3)*100000 + uint32(ind4)*10000 + uint32(ind5)*1000 + uint32(ind6)*100 + uint32(ind7)*10 + uint32(ind8) iter.head = i if ind9 == invalidCharForNumber { + iter.assertInteger() return value } } @@ -180,6 +195,7 @@ func (iter *Iterator) readUint32(c byte) (ret uint32) { ind = intDigits[iter.buf[i]] if ind == invalidCharForNumber { iter.head = i + iter.assertInteger() return value } if value > uint32SafeToMultiply10 { @@ -194,6 +210,7 @@ func (iter *Iterator) readUint32(c byte) (ret uint32) { value = (value << 3) + (value << 1) + uint32(ind) } if !iter.loadMore() { + iter.assertInteger() return value } } @@ -226,6 +243,7 @@ func (iter *Iterator) ReadUint64() uint64 { func (iter *Iterator) readUint64(c byte) (ret uint64) { ind := intDigits[c] if ind == 0 { + iter.assertInteger() return 0 // single zero } if ind == invalidCharForNumber { @@ -233,11 +251,73 @@ func (iter *Iterator) readUint64(c byte) (ret uint64) { return } value := uint64(ind) + if iter.tail-iter.head > 10 { + i := iter.head + ind2 := intDigits[iter.buf[i]] + if ind2 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + i++ + ind3 := intDigits[iter.buf[i]] + if ind3 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10 + uint64(ind2) + } + //iter.head = i + 1 + //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) + i++ + ind4 := intDigits[iter.buf[i]] + if ind4 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100 + uint64(ind2)*10 + uint64(ind3) + } + i++ + ind5 := intDigits[iter.buf[i]] + if ind5 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000 + uint64(ind2)*100 + uint64(ind3)*10 + uint64(ind4) + } + i++ + ind6 := intDigits[iter.buf[i]] + if ind6 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10000 + uint64(ind2)*1000 + uint64(ind3)*100 + uint64(ind4)*10 + uint64(ind5) + } + i++ + ind7 := intDigits[iter.buf[i]] + if ind7 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100000 + uint64(ind2)*10000 + uint64(ind3)*1000 + uint64(ind4)*100 + uint64(ind5)*10 + uint64(ind6) + } + i++ + ind8 := intDigits[iter.buf[i]] + if ind8 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000000 + uint64(ind2)*100000 + uint64(ind3)*10000 + uint64(ind4)*1000 + uint64(ind5)*100 + uint64(ind6)*10 + uint64(ind7) + } + i++ + ind9 := intDigits[iter.buf[i]] + value = value*10000000 + uint64(ind2)*1000000 + uint64(ind3)*100000 + uint64(ind4)*10000 + uint64(ind5)*1000 + uint64(ind6)*100 + uint64(ind7)*10 + uint64(ind8) + iter.head = i + if ind9 == invalidCharForNumber { + iter.assertInteger() + return value + } + } for { for i := iter.head; i < iter.tail; i++ { ind = intDigits[iter.buf[i]] if ind == invalidCharForNumber { iter.head = i + iter.assertInteger() return value } if value > uint64SafeToMultiple10 { @@ -252,7 +332,14 @@ func (iter *Iterator) readUint64(c byte) (ret uint64) { value = (value << 3) + (value << 1) + uint64(ind) } if !iter.loadMore() { + iter.assertInteger() return value } } } + +func (iter *Iterator) assertInteger() { + if iter.head < len(iter.buf) && iter.buf[iter.head] == '.' { + iter.ReportError("assertInteger", "can not decode float as int") + } +} diff --git a/vendor/github.com/json-iterator/go/feature_iter_object.go b/vendor/github.com/json-iterator/go/iter_object.go similarity index 67% rename from vendor/github.com/json-iterator/go/feature_iter_object.go rename to vendor/github.com/json-iterator/go/iter_object.go index 6ec8fb7fd7..ebd3da8951 100644 --- a/vendor/github.com/json-iterator/go/feature_iter_object.go +++ b/vendor/github.com/json-iterator/go/iter_object.go @@ -3,7 +3,6 @@ package jsoniter import ( "fmt" "unicode" - "unsafe" ) // ReadObject read one field from object. @@ -19,7 +18,12 @@ func (iter *Iterator) ReadObject() (ret string) { c = iter.nextToken() if c == '"' { iter.unreadByte() - return string(iter.readObjectFieldAsBytes()) + field := iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + return field } if c == '}' { return "" // end of object @@ -27,7 +31,12 @@ func (iter *Iterator) ReadObject() (ret string) { iter.ReportError("ReadObject", `expect " after {, but found `+string([]byte{c})) return case ',': - return string(iter.readObjectFieldAsBytes()) + field := iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + return field case '}': return "" // end of object default: @@ -36,62 +45,89 @@ func (iter *Iterator) ReadObject() (ret string) { } } -func (iter *Iterator) readFieldHash() int32 { +// CaseInsensitive +func (iter *Iterator) readFieldHash() int64 { hash := int64(0x811c9dc5) c := iter.nextToken() - if c == '"' { - for { - for i := iter.head; i < iter.tail; i++ { - // require ascii string and no escape - b := iter.buf[i] - if 'A' <= b && b <= 'Z' { - b += 'a' - 'A' - } - if b == '"' { - iter.head = i + 1 - c = iter.nextToken() - if c != ':' { - iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) + if c != '"' { + iter.ReportError("readFieldHash", `expect ", but found `+string([]byte{c})) + return 0 + } + for { + for i := iter.head; i < iter.tail; i++ { + // require ascii string and no escape + b := iter.buf[i] + if b == '\\' { + iter.head = i + for _, b := range iter.readStringSlowPath() { + if 'A' <= b && b <= 'Z' { + b += 'a' - 'A' } - return int32(hash) + hash ^= int64(b) + hash *= 0x1000193 + } + c = iter.nextToken() + if c != ':' { + iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) + return 0 } - hash ^= int64(b) - hash *= 0x1000193 + return hash } - if !iter.loadMore() { - iter.ReportError("readFieldHash", `incomplete field name`) - return 0 + if b == '"' { + iter.head = i + 1 + c = iter.nextToken() + if c != ':' { + iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) + return 0 + } + return hash } + if 'A' <= b && b <= 'Z' { + b += 'a' - 'A' + } + hash ^= int64(b) + hash *= 0x1000193 + } + if !iter.loadMore() { + iter.ReportError("readFieldHash", `incomplete field name`) + return 0 } } - iter.ReportError("readFieldHash", `expect ", but found `+string([]byte{c})) - return 0 } -func calcHash(str string) int32 { +func calcHash(str string) int64 { hash := int64(0x811c9dc5) for _, b := range str { hash ^= int64(unicode.ToLower(b)) hash *= 0x1000193 } - return int32(hash) + return int64(hash) } // ReadObjectCB read object with callback, the key is ascii only and field name not copied func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool { c := iter.nextToken() + var field string if c == '{' { c = iter.nextToken() if c == '"' { iter.unreadByte() - field := iter.readObjectFieldAsBytes() - if !callback(iter, *(*string)(unsafe.Pointer(&field))) { + field = iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + if !callback(iter, field) { return false } c = iter.nextToken() for c == ',' { - field = iter.readObjectFieldAsBytes() - if !callback(iter, *(*string)(unsafe.Pointer(&field))) { + field = iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + if !callback(iter, field) { return false } c = iter.nextToken() diff --git a/vendor/github.com/json-iterator/go/feature_iter_skip.go b/vendor/github.com/json-iterator/go/iter_skip.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_iter_skip.go rename to vendor/github.com/json-iterator/go/iter_skip.go diff --git a/vendor/github.com/json-iterator/go/feature_iter_skip_sloppy.go b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go similarity index 99% rename from vendor/github.com/json-iterator/go/feature_iter_skip_sloppy.go rename to vendor/github.com/json-iterator/go/iter_skip_sloppy.go index 047d58a4bc..8fcdc3b69b 100644 --- a/vendor/github.com/json-iterator/go/feature_iter_skip_sloppy.go +++ b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go @@ -1,4 +1,4 @@ -//+build jsoniter-sloppy +//+build jsoniter_sloppy package jsoniter diff --git a/vendor/github.com/json-iterator/go/feature_iter_skip_strict.go b/vendor/github.com/json-iterator/go/iter_skip_strict.go similarity index 98% rename from vendor/github.com/json-iterator/go/feature_iter_skip_strict.go rename to vendor/github.com/json-iterator/go/iter_skip_strict.go index cc1933de2e..f67bc2e831 100644 --- a/vendor/github.com/json-iterator/go/feature_iter_skip_strict.go +++ b/vendor/github.com/json-iterator/go/iter_skip_strict.go @@ -1,4 +1,4 @@ -//+build !jsoniter-sloppy +//+build !jsoniter_sloppy package jsoniter diff --git a/vendor/github.com/json-iterator/go/feature_iter_string.go b/vendor/github.com/json-iterator/go/iter_str.go similarity index 100% rename from vendor/github.com/json-iterator/go/feature_iter_string.go rename to vendor/github.com/json-iterator/go/iter_str.go diff --git a/vendor/github.com/json-iterator/go/jsoniter_1dot8_only_test.go b/vendor/github.com/json-iterator/go/jsoniter_1dot8_only_test.go deleted file mode 100644 index 7a0886a2de..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_1dot8_only_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// +build go1.8 - -package jsoniter - -import ( - "bytes" - "encoding/json" - "testing" - "unicode/utf8" - - "github.com/stretchr/testify/require" -) - -func Test_new_encoder(t *testing.T) { - should := require.New(t) - buf1 := &bytes.Buffer{} - encoder1 := json.NewEncoder(buf1) - encoder1.SetEscapeHTML(false) - encoder1.Encode([]int{1}) - should.Equal("[1]\n", buf1.String()) - buf2 := &bytes.Buffer{} - encoder2 := NewEncoder(buf2) - encoder2.SetEscapeHTML(false) - encoder2.Encode([]int{1}) - should.Equal("[1]", buf2.String()) -} - -func Test_string_encode_with_std_without_html_escape(t *testing.T) { - api := Config{EscapeHTML: false}.Froze() - should := require.New(t) - for i := 0; i < utf8.RuneSelf; i++ { - input := string([]byte{byte(i)}) - buf := &bytes.Buffer{} - encoder := json.NewEncoder(buf) - encoder.SetEscapeHTML(false) - err := encoder.Encode(input) - should.Nil(err) - stdOutput := buf.String() - stdOutput = stdOutput[:len(stdOutput)-1] - jsoniterOutputBytes, err := api.Marshal(input) - should.Nil(err) - jsoniterOutput := string(jsoniterOutputBytes) - should.Equal(stdOutput, jsoniterOutput) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_adapter_test.go b/vendor/github.com/json-iterator/go/jsoniter_adapter_test.go deleted file mode 100644 index 30f03deb6b..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_adapter_test.go +++ /dev/null @@ -1,84 +0,0 @@ -package jsoniter - -import ( - "bytes" - "encoding/json" - "github.com/stretchr/testify/require" - "io/ioutil" - "testing" -) - -func Test_new_decoder(t *testing.T) { - should := require.New(t) - decoder1 := json.NewDecoder(bytes.NewBufferString(`[1][2]`)) - decoder2 := NewDecoder(bytes.NewBufferString(`[1][2]`)) - arr1 := []int{} - should.Nil(decoder1.Decode(&arr1)) - should.Equal([]int{1}, arr1) - arr2 := []int{} - should.True(decoder1.More()) - buffered, _ := ioutil.ReadAll(decoder1.Buffered()) - should.Equal("[2]", string(buffered)) - should.Nil(decoder2.Decode(&arr2)) - should.Equal([]int{1}, arr2) - should.True(decoder2.More()) - buffered, _ = ioutil.ReadAll(decoder2.Buffered()) - should.Equal("[2]", string(buffered)) - - should.Nil(decoder1.Decode(&arr1)) - should.Equal([]int{2}, arr1) - should.False(decoder1.More()) - should.Nil(decoder2.Decode(&arr2)) - should.Equal([]int{2}, arr2) - should.False(decoder2.More()) -} - -func Test_use_number(t *testing.T) { - should := require.New(t) - decoder1 := json.NewDecoder(bytes.NewBufferString(`123`)) - decoder1.UseNumber() - decoder2 := NewDecoder(bytes.NewBufferString(`123`)) - decoder2.UseNumber() - var obj1 interface{} - should.Nil(decoder1.Decode(&obj1)) - should.Equal(json.Number("123"), obj1) - var obj2 interface{} - should.Nil(decoder2.Decode(&obj2)) - should.Equal(json.Number("123"), obj2) -} - -func Test_use_number_for_unmarshal(t *testing.T) { - should := require.New(t) - api := Config{UseNumber: true}.Froze() - var obj interface{} - should.Nil(api.UnmarshalFromString("123", &obj)) - should.Equal(json.Number("123"), obj) -} - -func Test_marshal_indent(t *testing.T) { - should := require.New(t) - obj := struct { - F1 int - F2 []int - }{1, []int{2, 3, 4}} - output, err := json.MarshalIndent(obj, "", " ") - should.Nil(err) - should.Equal("{\n \"F1\": 1,\n \"F2\": [\n 2,\n 3,\n 4\n ]\n}", string(output)) - output, err = MarshalIndent(obj, "", " ") - should.Nil(err) - should.Equal("{\n \"F1\": 1,\n \"F2\": [\n 2,\n 3,\n 4\n ]\n}", string(output)) -} - -func Test_marshal_indent_map(t *testing.T) { - should := require.New(t) - obj := map[int]int{1: 2} - output, err := json.MarshalIndent(obj, "", " ") - should.Nil(err) - should.Equal("{\n \"1\": 2\n}", string(output)) - output, err = MarshalIndent(obj, "", " ") - should.Nil(err) - should.Equal("{\n \"1\": 2\n}", string(output)) - output, err = ConfigCompatibleWithStandardLibrary.MarshalIndent(obj, "", " ") - should.Nil(err) - should.Equal("{\n \"1\": 2\n}", string(output)) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_alias_test.go b/vendor/github.com/json-iterator/go/jsoniter_alias_test.go deleted file mode 100644 index 246651f758..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_alias_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package jsoniter - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_alias(t *testing.T) { - should := require.New(t) - type myint int - type myint8 int8 - type myint16 int16 - type myint32 int32 - type myint64 int64 - type myuint uint - type myuint8 uint8 - type myuint16 uint16 - type myuint32 uint32 - type myuint64 uint64 - type myfloat32 float32 - type myfloat64 float64 - type mystring string - type mybool bool - type myuintptr uintptr - var a struct { - A myint8 `json:"a"` - B myint16 `json:"stream"` - C myint32 `json:"c"` - D myint64 `json:"d"` - E myuint8 `json:"e"` - F myuint16 `json:"f"` - G myuint32 `json:"g"` - H myuint64 `json:"h"` - I myfloat32 `json:"i"` - J myfloat64 `json:"j"` - K mystring `json:"k"` - L myint `json:"l"` - M myuint `json:"m"` - N mybool `json:"n"` - O myuintptr `json:"o"` - } - - should.Nil(UnmarshalFromString(`{"a" : 1, "stream" : 1, "c": 1, "d" : 1, "e" : 1, "f" : 1, "g" : 1, "h": 1, "i" : 1, "j" : 1, "k" :"xxxx", "l" : 1, "m":1, "n": true, "o" : 1}`, &a)) - should.Equal(myfloat32(1), a.I) - should.Equal(myfloat64(1), a.J) - should.Equal(myint8(1), a.A) - should.Equal(myint16(1), a.B) - should.Equal(myint32(1), a.C) - should.Equal(myint64(1), a.D) - should.Equal(myuint8(1), a.E) - should.Equal(myuint16(1), a.F) - should.Equal(myuint32(1), a.G) - should.Equal(myuint64(1), a.H) - should.Equal(mystring("xxxx"), a.K) - should.Equal(mybool(true), a.N) - should.Equal(myuintptr(1), a.O) - b, err := Marshal(a) - should.Nil(err) - should.Equal(`{"a":1,"stream":1,"c":1,"d":1,"e":1,"f":1,"g":1,"h":1,"i":1,"j":1,"k":"xxxx","l":1,"m":1,"n":true,"o":1}`, string(b)) - -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_any_array_test.go b/vendor/github.com/json-iterator/go/jsoniter_any_array_test.go deleted file mode 100644 index dbffd822df..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_any_array_test.go +++ /dev/null @@ -1,122 +0,0 @@ -package jsoniter - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_read_empty_array_as_any(t *testing.T) { - should := require.New(t) - any := Get([]byte("[]")) - should.Equal(ArrayValue, any.Get().ValueType()) - should.Equal(InvalidValue, any.Get(0.3).ValueType()) - should.Equal(0, any.Size()) - should.Equal(ArrayValue, any.ValueType()) - should.Nil(any.LastError()) - should.Equal(0, any.ToInt()) - should.Equal(int32(0), any.ToInt32()) - should.Equal(int64(0), any.ToInt64()) - should.Equal(uint(0), any.ToUint()) - should.Equal(uint32(0), any.ToUint32()) - should.Equal(uint64(0), any.ToUint64()) - should.Equal(float32(0), any.ToFloat32()) - should.Equal(float64(0), any.ToFloat64()) -} - -func Test_read_one_element_array_as_any(t *testing.T) { - should := require.New(t) - any := Get([]byte("[1]")) - should.Equal(1, any.Size()) -} - -func Test_read_two_element_array_as_any(t *testing.T) { - should := require.New(t) - any := Get([]byte("[1,2]")) - should.Equal(1, any.Get(0).ToInt()) - should.Equal(2, any.Size()) - should.True(any.ToBool()) - should.Equal(1, any.ToInt()) - should.Equal([]interface{}{float64(1), float64(2)}, any.GetInterface()) - stream := NewStream(ConfigDefault, nil, 32) - any.WriteTo(stream) - should.Equal("[1,2]", string(stream.Buffer())) - arr := []int{} - any.ToVal(&arr) - should.Equal([]int{1, 2}, arr) -} - -func Test_wrap_array_and_convert_to_any(t *testing.T) { - should := require.New(t) - any := Wrap([]int{1, 2, 3}) - any2 := Wrap([]int{}) - - should.Equal("[1,2,3]", any.ToString()) - should.True(any.ToBool()) - should.False(any2.ToBool()) - - should.Equal(1, any.ToInt()) - should.Equal(0, any2.ToInt()) - should.Equal(int32(1), any.ToInt32()) - should.Equal(int32(0), any2.ToInt32()) - should.Equal(int64(1), any.ToInt64()) - should.Equal(int64(0), any2.ToInt64()) - should.Equal(uint(1), any.ToUint()) - should.Equal(uint(0), any2.ToUint()) - should.Equal(uint32(1), any.ToUint32()) - should.Equal(uint32(0), any2.ToUint32()) - should.Equal(uint64(1), any.ToUint64()) - should.Equal(uint64(0), any2.ToUint64()) - should.Equal(float32(1), any.ToFloat32()) - should.Equal(float32(0), any2.ToFloat32()) - should.Equal(float64(1), any.ToFloat64()) - should.Equal(float64(0), any2.ToFloat64()) - should.Equal(3, any.Size()) - should.Equal(0, any2.Size()) - - var i interface{} = []int{1, 2, 3} - should.Equal(i, any.GetInterface()) -} - -func Test_array_lazy_any_get(t *testing.T) { - should := require.New(t) - any := Get([]byte("[1,[2,3],4]")) - should.Equal(3, any.Get(1, 1).ToInt()) - should.Equal("[1,[2,3],4]", any.ToString()) -} - -func Test_array_lazy_any_get_all(t *testing.T) { - should := require.New(t) - any := Get([]byte("[[1],[2],[3,4]]")) - should.Equal("[1,2,3]", any.Get('*', 0).ToString()) - any = Get([]byte("[[[1],[2],[3,4]]]"), 0, '*', 0) - should.Equal("[1,2,3]", any.ToString()) -} - -func Test_array_wrapper_any_get_all(t *testing.T) { - should := require.New(t) - any := wrapArray([][]int{ - {1, 2}, - {3, 4}, - {5, 6}, - }) - should.Equal("[1,3,5]", any.Get('*', 0).ToString()) - should.Equal(ArrayValue, any.ValueType()) - should.True(any.ToBool()) - should.Equal(1, any.Get(0, 0).ToInt()) -} - -func Test_array_lazy_any_get_invalid(t *testing.T) { - should := require.New(t) - any := Get([]byte("[]")) - should.Equal(InvalidValue, any.Get(1, 1).ValueType()) - should.NotNil(any.Get(1, 1).LastError()) - should.Equal(InvalidValue, any.Get("1").ValueType()) - should.NotNil(any.Get("1").LastError()) -} - -func Test_invalid_array(t *testing.T) { - should := require.New(t) - any := Get([]byte("["), 0) - should.Equal(InvalidValue, any.ValueType()) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_any_bool_test.go b/vendor/github.com/json-iterator/go/jsoniter_any_bool_test.go deleted file mode 100644 index a71743a645..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_any_bool_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package jsoniter - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" -) - -var boolConvertMap = map[string]bool{ - "null": false, - "true": true, - "false": false, - - `"true"`: true, - `"false"`: true, - - "123": true, - `"123"`: true, - "0": false, - `"0"`: false, - "-1": true, - `"-1"`: true, - - "1.1": true, - "0.0": false, - "-1.1": true, - `""`: false, - "[1,2]": true, - "[]": false, - "{}": true, - `{"abc":1}`: true, -} - -func Test_read_bool_as_any(t *testing.T) { - should := require.New(t) - - var any Any - for k, v := range boolConvertMap { - any = Get([]byte(k)) - if v { - should.True(any.ToBool(), fmt.Sprintf("origin val is %v", k)) - } else { - should.False(any.ToBool(), fmt.Sprintf("origin val is %v", k)) - } - } - -} - -func Test_write_bool_to_stream(t *testing.T) { - should := require.New(t) - any := Get([]byte("true")) - stream := NewStream(ConfigDefault, nil, 32) - any.WriteTo(stream) - should.Equal("true", string(stream.Buffer())) - should.Equal(any.ValueType(), BoolValue) - - any = Get([]byte("false")) - stream = NewStream(ConfigDefault, nil, 32) - any.WriteTo(stream) - should.Equal("false", string(stream.Buffer())) - - should.Equal(any.ValueType(), BoolValue) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_any_float_test.go b/vendor/github.com/json-iterator/go/jsoniter_any_float_test.go deleted file mode 100644 index 391ac32a87..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_any_float_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package jsoniter - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -var floatConvertMap = map[string]float64{ - "null": 0, - "true": 1, - "false": 0, - - `"true"`: 0, - `"false"`: 0, - - "1e1": 10, - "1e+1": 10, - "1e-1": .1, - "1E1": 10, - "1E+1": 10, - "1E-1": .1, - - "-1e1": -10, - "-1e+1": -10, - "-1e-1": -.1, - "-1E1": -10, - "-1E+1": -10, - "-1E-1": -.1, - - `"1e1"`: 10, - `"1e+1"`: 10, - `"1e-1"`: .1, - `"1E1"`: 10, - `"1E+1"`: 10, - `"1E-1"`: .1, - - `"-1e1"`: -10, - `"-1e+1"`: -10, - `"-1e-1"`: -.1, - `"-1E1"`: -10, - `"-1E+1"`: -10, - `"-1E-1"`: -.1, - - "123": 123, - `"123true"`: 123, - `"+"`: 0, - `"-"`: 0, - - `"-123true"`: -123, - `"-99.9true"`: -99.9, - "0": 0, - `"0"`: 0, - "-1": -1, - - "1.1": 1.1, - "0.0": 0, - "-1.1": -1.1, - `"+1.1"`: 1.1, - `""`: 0, - "[1,2]": 1, - "[]": 0, - "{}": 0, - `{"abc":1}`: 0, -} - -func Test_read_any_to_float(t *testing.T) { - should := require.New(t) - for k, v := range floatConvertMap { - any := Get([]byte(k)) - should.Equal(float64(v), any.ToFloat64(), "the original val is "+k) - } - - for k, v := range floatConvertMap { - any := Get([]byte(k)) - should.Equal(float32(v), any.ToFloat32(), "the original val is "+k) - } -} - -func Test_read_float_to_any(t *testing.T) { - should := require.New(t) - any := WrapFloat64(12.3) - anyFloat64 := float64(12.3) - //negaAnyFloat64 := float64(-1.1) - any2 := WrapFloat64(-1.1) - should.Equal(float64(12.3), any.ToFloat64()) - //should.Equal("12.3", any.ToString()) - should.True(any.ToBool()) - should.Equal(float32(anyFloat64), any.ToFloat32()) - should.Equal(int(anyFloat64), any.ToInt()) - should.Equal(int32(anyFloat64), any.ToInt32()) - should.Equal(int64(anyFloat64), any.ToInt64()) - should.Equal(uint(anyFloat64), any.ToUint()) - should.Equal(uint32(anyFloat64), any.ToUint32()) - should.Equal(uint64(anyFloat64), any.ToUint64()) - should.Equal(uint(0), any2.ToUint()) - should.Equal(uint32(0), any2.ToUint32()) - should.Equal(uint64(0), any2.ToUint64()) - should.Equal(any.ValueType(), NumberValue) - - should.Equal("1.23E+01", any.ToString()) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_any_int_test.go b/vendor/github.com/json-iterator/go/jsoniter_any_int_test.go deleted file mode 100644 index 2328085287..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_any_int_test.go +++ /dev/null @@ -1,197 +0,0 @@ -package jsoniter - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" -) - -var intConvertMap = map[string]int{ - "null": 0, - "321.1": 321, - "-321.1": -321, - `"1.1"`: 1, - `"-321.1"`: -321, - "0.0": 0, - "0": 0, - `"0"`: 0, - `"0.0"`: 0, - "-1.1": -1, - "true": 1, - "false": 0, - `"true"`: 0, - `"false"`: 0, - `"true123"`: 0, - `"123true"`: 123, - `"-123true"`: -123, - `"1.2332e6"`: 1, - `""`: 0, - "+": 0, - "-": 0, - "[]": 0, - "[1,2]": 1, - `["1","2"]`: 1, - // object in php cannot convert to int - "{}": 0, -} - -func Test_read_any_to_int(t *testing.T) { - should := require.New(t) - - // int - for k, v := range intConvertMap { - any := Get([]byte(k)) - should.Equal(v, any.ToInt(), fmt.Sprintf("origin val %v", k)) - } - - // int32 - for k, v := range intConvertMap { - any := Get([]byte(k)) - should.Equal(int32(v), any.ToInt32(), fmt.Sprintf("original val is %v", k)) - } - - // int64 - for k, v := range intConvertMap { - any := Get([]byte(k)) - should.Equal(int64(v), any.ToInt64(), fmt.Sprintf("original val is %v", k)) - } - -} - -var uintConvertMap = map[string]int{ - "null": 0, - "321.1": 321, - `"1.1"`: 1, - `"-123.1"`: 0, - "0.0": 0, - "0": 0, - `"0"`: 0, - `"0.0"`: 0, - `"00.0"`: 0, - "true": 1, - "false": 0, - `"true"`: 0, - `"false"`: 0, - `"true123"`: 0, - `"+1"`: 1, - `"123true"`: 123, - `"-123true"`: 0, - `"1.2332e6"`: 1, - `""`: 0, - "+": 0, - "-": 0, - ".": 0, - "[]": 0, - "[1,2]": 1, - "{}": 0, - "{1,2}": 0, - "-1.1": 0, - "-321.1": 0, -} - -func Test_read_any_to_uint(t *testing.T) { - should := require.New(t) - - for k, v := range uintConvertMap { - any := Get([]byte(k)) - should.Equal(uint64(v), any.ToUint64(), fmt.Sprintf("origin val %v", k)) - } - - for k, v := range uintConvertMap { - any := Get([]byte(k)) - should.Equal(uint32(v), any.ToUint32(), fmt.Sprintf("origin val %v", k)) - } - - for k, v := range uintConvertMap { - any := Get([]byte(k)) - should.Equal(uint(v), any.ToUint(), fmt.Sprintf("origin val %v", k)) - } - -} - -func Test_read_int64_to_any(t *testing.T) { - should := require.New(t) - any := WrapInt64(12345) - should.Equal(12345, any.ToInt()) - should.Equal(int32(12345), any.ToInt32()) - should.Equal(int64(12345), any.ToInt64()) - should.Equal(uint(12345), any.ToUint()) - should.Equal(uint32(12345), any.ToUint32()) - should.Equal(uint64(12345), any.ToUint64()) - should.Equal(float32(12345), any.ToFloat32()) - should.Equal(float64(12345), any.ToFloat64()) - should.Equal("12345", any.ToString()) - should.Equal(true, any.ToBool()) - should.Equal(any.ValueType(), NumberValue) - stream := NewStream(ConfigDefault, nil, 32) - any.WriteTo(stream) - should.Equal("12345", string(stream.Buffer())) -} -func Test_read_int32_to_any(t *testing.T) { - should := require.New(t) - any := WrapInt32(12345) - should.Equal(12345, any.ToInt()) - should.Equal(int32(12345), any.ToInt32()) - should.Equal(int64(12345), any.ToInt64()) - should.Equal(uint(12345), any.ToUint()) - should.Equal(uint32(12345), any.ToUint32()) - should.Equal(uint64(12345), any.ToUint64()) - should.Equal(float32(12345), any.ToFloat32()) - should.Equal(float64(12345), any.ToFloat64()) - should.Equal("12345", any.ToString()) - should.Equal(true, any.ToBool()) - should.Equal(any.ValueType(), NumberValue) - stream := NewStream(ConfigDefault, nil, 32) - any.WriteTo(stream) - should.Equal("12345", string(stream.Buffer())) -} - -func Test_read_uint32_to_any(t *testing.T) { - should := require.New(t) - any := WrapUint32(12345) - should.Equal(12345, any.ToInt()) - should.Equal(int32(12345), any.ToInt32()) - should.Equal(int64(12345), any.ToInt64()) - should.Equal(uint(12345), any.ToUint()) - should.Equal(uint32(12345), any.ToUint32()) - should.Equal(uint64(12345), any.ToUint64()) - should.Equal(float32(12345), any.ToFloat32()) - should.Equal(float64(12345), any.ToFloat64()) - should.Equal("12345", any.ToString()) - should.Equal(true, any.ToBool()) - should.Equal(any.ValueType(), NumberValue) - stream := NewStream(ConfigDefault, nil, 32) - any.WriteTo(stream) - should.Equal("12345", string(stream.Buffer())) -} - -func Test_read_uint64_to_any(t *testing.T) { - should := require.New(t) - any := WrapUint64(12345) - should.Equal(12345, any.ToInt()) - should.Equal(int32(12345), any.ToInt32()) - should.Equal(int64(12345), any.ToInt64()) - should.Equal(uint(12345), any.ToUint()) - should.Equal(uint32(12345), any.ToUint32()) - should.Equal(uint64(12345), any.ToUint64()) - should.Equal(float32(12345), any.ToFloat32()) - should.Equal(float64(12345), any.ToFloat64()) - should.Equal("12345", any.ToString()) - should.Equal(true, any.ToBool()) - should.Equal(any.ValueType(), NumberValue) - stream := NewStream(ConfigDefault, nil, 32) - any.WriteTo(stream) - should.Equal("12345", string(stream.Buffer())) - stream = NewStream(ConfigDefault, nil, 32) - stream.WriteUint(uint(123)) - should.Equal("123", string(stream.Buffer())) -} - -func Test_int_lazy_any_get(t *testing.T) { - should := require.New(t) - any := Get([]byte("1234")) - // panic!! - //should.Equal(any.LastError(), io.EOF) - should.Equal(InvalidValue, any.Get(1, "2").ValueType()) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_any_map_test.go b/vendor/github.com/json-iterator/go/jsoniter_any_map_test.go deleted file mode 100644 index f93ea4e61d..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_any_map_test.go +++ /dev/null @@ -1,14 +0,0 @@ -package jsoniter - -import ( - "github.com/stretchr/testify/require" - "testing" -) - -func Test_wrap_map(t *testing.T) { - should := require.New(t) - any := Wrap(map[string]string{"Field1": "hello"}) - should.Equal("hello", any.Get("Field1").ToString()) - any = Wrap(map[string]string{"Field1": "hello"}) - should.Equal(1, any.Size()) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_any_null_test.go b/vendor/github.com/json-iterator/go/jsoniter_any_null_test.go deleted file mode 100644 index eb09497b98..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_any_null_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package jsoniter - -import ( - "github.com/stretchr/testify/require" - "testing" -) - -func Test_read_null_as_any(t *testing.T) { - should := require.New(t) - any := Get([]byte(`null`)) - should.Equal(0, any.ToInt()) - should.Equal(float64(0), any.ToFloat64()) - should.Equal("", any.ToString()) - should.False(any.ToBool()) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_any_object_test.go b/vendor/github.com/json-iterator/go/jsoniter_any_object_test.go deleted file mode 100644 index 9b215f95e8..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_any_object_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package jsoniter - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_read_object_as_any(t *testing.T) { - should := require.New(t) - any := Get([]byte(`{"a":"stream","c":"d"}`)) - should.Equal(`{"a":"stream","c":"d"}`, any.ToString()) - // partial parse - should.Equal("stream", any.Get("a").ToString()) - should.Equal("d", any.Get("c").ToString()) - should.Equal(2, len(any.Keys())) - any = Get([]byte(`{"a":"stream","c":"d"}`)) - // full parse - should.Equal(2, len(any.Keys())) - should.Equal(2, any.Size()) - should.True(any.ToBool()) - should.Equal(0, any.ToInt()) - should.Equal(ObjectValue, any.ValueType()) - should.Nil(any.LastError()) - obj := struct { - A string - }{} - any.ToVal(&obj) - should.Equal("stream", obj.A) -} - -func Test_object_lazy_any_get(t *testing.T) { - should := require.New(t) - any := Get([]byte(`{"a":{"stream":{"c":"d"}}}`)) - should.Equal("d", any.Get("a", "stream", "c").ToString()) -} - -func Test_object_lazy_any_get_all(t *testing.T) { - should := require.New(t) - any := Get([]byte(`{"a":[0],"stream":[1]}`)) - should.Contains(any.Get('*', 0).ToString(), `"a":0`) -} - -func Test_object_lazy_any_get_invalid(t *testing.T) { - should := require.New(t) - any := Get([]byte(`{}`)) - should.Equal(InvalidValue, any.Get("a", "stream", "c").ValueType()) - should.Equal(InvalidValue, any.Get(1).ValueType()) -} - -func Test_wrap_map_and_convert_to_any(t *testing.T) { - should := require.New(t) - any := Wrap(map[string]interface{}{"a": 1}) - should.True(any.ToBool()) - should.Equal(0, any.ToInt()) - should.Equal(int32(0), any.ToInt32()) - should.Equal(int64(0), any.ToInt64()) - should.Equal(float32(0), any.ToFloat32()) - should.Equal(float64(0), any.ToFloat64()) - should.Equal(uint(0), any.ToUint()) - should.Equal(uint32(0), any.ToUint32()) - should.Equal(uint64(0), any.ToUint64()) -} - -func Test_wrap_object_and_convert_to_any(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - field2 string - } - any := Wrap(TestObject{"hello", "world"}) - should.Equal("hello", any.Get("Field1").ToString()) - any = Wrap(TestObject{"hello", "world"}) - should.Equal(2, any.Size()) - should.Equal(`{"Field1":"hello"}`, any.Get('*').ToString()) - - should.Equal(0, any.ToInt()) - should.Equal(int32(0), any.ToInt32()) - should.Equal(int64(0), any.ToInt64()) - should.Equal(float32(0), any.ToFloat32()) - should.Equal(float64(0), any.ToFloat64()) - should.Equal(uint(0), any.ToUint()) - should.Equal(uint32(0), any.ToUint32()) - should.Equal(uint64(0), any.ToUint64()) - should.True(any.ToBool()) - should.Equal(`{"Field1":"hello"}`, any.ToString()) - - // cannot pass! - //stream := NewStream(ConfigDefault, nil, 32) - //any.WriteTo(stream) - //should.Equal(`{"Field1":"hello"}`, string(stream.Buffer())) - // cannot pass! - -} - -func Test_any_within_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 Any - Field2 Any - } - obj := TestObject{} - err := UnmarshalFromString(`{"Field1": "hello", "Field2": [1,2,3]}`, &obj) - should.Nil(err) - should.Equal("hello", obj.Field1.ToString()) - should.Equal("[1,2,3]", obj.Field2.ToString()) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_any_string_test.go b/vendor/github.com/json-iterator/go/jsoniter_any_string_test.go deleted file mode 100644 index 119f7d27d3..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_any_string_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package jsoniter - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -var stringConvertMap = map[string]string{ - "null": "", - "321.1": "321.1", - `"1.1"`: "1.1", - `"-123.1"`: "-123.1", - "0.0": "0.0", - "0": "0", - `"0"`: "0", - `"0.0"`: "0.0", - `"00.0"`: "00.0", - "true": "true", - "false": "false", - `"true"`: "true", - `"false"`: "false", - `"true123"`: "true123", - `"+1"`: "+1", - "[]": "[]", - "[1,2]": "[1,2]", - "{}": "{}", - `{"a":1, "stream":true}`: `{"a":1, "stream":true}`, -} - -func Test_read_any_to_string(t *testing.T) { - should := require.New(t) - for k, v := range stringConvertMap { - any := Get([]byte(k)) - should.Equal(v, any.ToString(), "original val "+k) - } -} - -func Test_read_string_as_any(t *testing.T) { - should := require.New(t) - any := Get([]byte(`"hello"`)) - should.Equal("hello", any.ToString()) - should.True(any.ToBool()) - any = Get([]byte(`" "`)) - should.False(any.ToBool()) - any = Get([]byte(`"false"`)) - should.True(any.ToBool()) - any = Get([]byte(`"123"`)) - should.Equal(123, any.ToInt()) -} - -func Test_wrap_string(t *testing.T) { - should := require.New(t) - any := WrapString("123") - should.Equal(123, any.ToInt()) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_array_test.go b/vendor/github.com/json-iterator/go/jsoniter_array_test.go deleted file mode 100644 index 0f71ecb684..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_array_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package jsoniter - -import ( - "bytes" - "encoding/json" - "github.com/stretchr/testify/require" - "testing" -) - -func Test_empty_array(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `[]`) - cont := iter.ReadArray() - should.False(cont) - iter = ParseString(ConfigDefault, `[]`) - iter.ReadArrayCB(func(iter *Iterator) bool { - should.FailNow("should not call") - return true - }) -} - -func Test_one_element(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `[1]`) - should.True(iter.ReadArray()) - should.Equal(1, iter.ReadInt()) - should.False(iter.ReadArray()) - iter = ParseString(ConfigDefault, `[1]`) - iter.ReadArrayCB(func(iter *Iterator) bool { - should.Equal(1, iter.ReadInt()) - return true - }) -} - -func Test_two_elements(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `[1,2]`) - should.True(iter.ReadArray()) - should.Equal(int64(1), iter.ReadInt64()) - should.True(iter.ReadArray()) - should.Equal(int64(2), iter.ReadInt64()) - should.False(iter.ReadArray()) - iter = ParseString(ConfigDefault, `[1,2]`) - should.Equal([]interface{}{float64(1), float64(2)}, iter.Read()) -} - -func Test_whitespace_in_head(t *testing.T) { - iter := ParseString(ConfigDefault, ` [1]`) - cont := iter.ReadArray() - if cont != true { - t.FailNow() - } - if iter.ReadUint64() != 1 { - t.FailNow() - } -} - -func Test_whitespace_after_array_start(t *testing.T) { - iter := ParseString(ConfigDefault, `[ 1]`) - cont := iter.ReadArray() - if cont != true { - t.FailNow() - } - if iter.ReadUint64() != 1 { - t.FailNow() - } -} - -func Test_whitespace_before_array_end(t *testing.T) { - iter := ParseString(ConfigDefault, `[1 ]`) - cont := iter.ReadArray() - if cont != true { - t.FailNow() - } - if iter.ReadUint64() != 1 { - t.FailNow() - } - cont = iter.ReadArray() - if cont != false { - t.FailNow() - } -} - -func Test_whitespace_before_comma(t *testing.T) { - iter := ParseString(ConfigDefault, `[1 ,2]`) - cont := iter.ReadArray() - if cont != true { - t.FailNow() - } - if iter.ReadUint64() != 1 { - t.FailNow() - } - cont = iter.ReadArray() - if cont != true { - t.FailNow() - } - if iter.ReadUint64() != 2 { - t.FailNow() - } - cont = iter.ReadArray() - if cont != false { - t.FailNow() - } -} - -func Test_write_array(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(Config{IndentionStep: 2}.Froze(), buf, 4096) - stream.WriteArrayStart() - stream.WriteInt(1) - stream.WriteMore() - stream.WriteInt(2) - stream.WriteArrayEnd() - stream.Flush() - should.Nil(stream.Error) - should.Equal("[\n 1,\n 2\n]", buf.String()) -} - -func Test_write_val_array(t *testing.T) { - should := require.New(t) - val := []int{1, 2, 3} - str, err := MarshalToString(&val) - should.Nil(err) - should.Equal("[1,2,3]", str) -} - -func Test_write_val_empty_array(t *testing.T) { - should := require.New(t) - val := []int{} - str, err := MarshalToString(val) - should.Nil(err) - should.Equal("[]", str) -} - -func Test_write_array_of_interface_in_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field []interface{} - Field2 string - } - val := TestObject{[]interface{}{1, 2}, ""} - str, err := MarshalToString(val) - should.Nil(err) - should.Contains(str, `"Field":[1,2]`) - should.Contains(str, `"Field2":""`) -} - -func Test_encode_byte_array(t *testing.T) { - should := require.New(t) - bytes, err := json.Marshal([]byte{1, 2, 3}) - should.Nil(err) - should.Equal(`"AQID"`, string(bytes)) - bytes, err = Marshal([]byte{1, 2, 3}) - should.Nil(err) - should.Equal(`"AQID"`, string(bytes)) -} - -func Test_decode_byte_array_from_base64(t *testing.T) { - should := require.New(t) - data := []byte{} - err := json.Unmarshal([]byte(`"AQID"`), &data) - should.Nil(err) - should.Equal([]byte{1, 2, 3}, data) - err = Unmarshal([]byte(`"AQID"`), &data) - should.Nil(err) - should.Equal([]byte{1, 2, 3}, data) -} - -func Test_decode_byte_array_from_array(t *testing.T) { - should := require.New(t) - data := []byte{} - err := json.Unmarshal([]byte(`[1,2,3]`), &data) - should.Nil(err) - should.Equal([]byte{1, 2, 3}, data) - err = Unmarshal([]byte(`[1,2,3]`), &data) - should.Nil(err) - should.Equal([]byte{1, 2, 3}, data) -} - -func Test_decode_slice(t *testing.T) { - should := require.New(t) - slice := make([]string, 0, 5) - UnmarshalFromString(`["hello", "world"]`, &slice) - should.Equal([]string{"hello", "world"}, slice) -} - -func Test_decode_large_slice(t *testing.T) { - should := require.New(t) - slice := make([]int, 0, 1) - UnmarshalFromString(`[1,2,3,4,5,6,7,8,9]`, &slice) - should.Equal([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, slice) -} - -func Benchmark_jsoniter_array(b *testing.B) { - b.ReportAllocs() - input := []byte(`[1,2,3,4,5,6,7,8,9]`) - iter := ParseBytes(ConfigDefault, input) - b.ResetTimer() - for n := 0; n < b.N; n++ { - iter.ResetBytes(input) - for iter.ReadArray() { - iter.ReadUint64() - } - } -} - -func Benchmark_json_array(b *testing.B) { - for n := 0; n < b.N; n++ { - result := []interface{}{} - json.Unmarshal([]byte(`[1,2,3]`), &result) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_bool_test.go b/vendor/github.com/json-iterator/go/jsoniter_bool_test.go deleted file mode 100644 index 461b88ba3c..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_bool_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package jsoniter - -import ( - "bytes" - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_true(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `true`) - should.True(iter.ReadBool()) - iter = ParseString(ConfigDefault, `true`) - should.Equal(true, iter.Read()) -} - -func Test_false(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `false`) - should.False(iter.ReadBool()) -} - -func Test_write_true_false(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteTrue() - stream.WriteFalse() - stream.WriteBool(false) - stream.Flush() - should.Nil(stream.Error) - should.Equal("truefalsefalse", buf.String()) -} - -func Test_write_val_bool(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(true) - should.Equal(stream.Buffered(), 4) - stream.Flush() - should.Equal(stream.Buffered(), 0) - should.Nil(stream.Error) - should.Equal("true", buf.String()) -} - -func Test_encode_string_bool(t *testing.T) { - type TestObject struct { - Field bool `json:",omitempty,string"` - } - should := require.New(t) - output, err := json.Marshal(TestObject{true}) - should.Nil(err) - should.Equal(`{"Field":"true"}`, string(output)) - output, err = Marshal(TestObject{true}) - should.Nil(err) - should.Equal(`{"Field":"true"}`, string(output)) -} - -func Test_decode_string_bool(t *testing.T) { - type TestObject struct { - Field bool `json:",omitempty,string"` - } - should := require.New(t) - obj := TestObject{} - err := json.Unmarshal([]byte(`{"Field":"true"}`), &obj) - should.Nil(err) - should.True(obj.Field) - - obj = TestObject{} - err = json.Unmarshal([]byte(`{"Field":true}`), &obj) - should.NotNil(err) - - obj = TestObject{} - err = Unmarshal([]byte(`{"Field":"true"}`), &obj) - should.Nil(err) - should.True(obj.Field) - - obj = TestObject{} - err = Unmarshal([]byte(`{"Field":true}`), &obj) - should.NotNil(err) -} - -func Test_bool_can_be_null(t *testing.T) { - type TestData struct { - Field bool `json:"field"` - } - should := require.New(t) - - obj := TestData{} - data1 := []byte(`{"field": true}`) - err := Unmarshal(data1, &obj) - should.NoError(err) - should.Equal(true, obj.Field) - - data2 := []byte(`{"field": null}`) - err = Unmarshal(data2, &obj) - should.NoError(err) - // Same behavior as stdlib, not touching the existing value. - should.Equal(true, obj.Field) - - // Checking stdlib behavior as well - obj2 := TestData{} - err = json.Unmarshal(data1, &obj2) - should.NoError(err) - should.Equal(true, obj2.Field) - - err = json.Unmarshal(data2, &obj2) - should.NoError(err) - should.Equal(true, obj2.Field) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_customize_test.go b/vendor/github.com/json-iterator/go/jsoniter_customize_test.go deleted file mode 100644 index 628f89e457..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_customize_test.go +++ /dev/null @@ -1,341 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "strconv" - "testing" - "time" - "unsafe" - - "github.com/stretchr/testify/require" -) - -func Test_customize_type_decoder(t *testing.T) { - RegisterTypeDecoderFunc("time.Time", func(ptr unsafe.Pointer, iter *Iterator) { - t, err := time.ParseInLocation("2006-01-02 15:04:05", iter.ReadString(), time.UTC) - if err != nil { - iter.Error = err - return - } - *((*time.Time)(ptr)) = t - }) - defer ConfigDefault.(*frozenConfig).cleanDecoders() - val := time.Time{} - err := Unmarshal([]byte(`"2016-12-05 08:43:28"`), &val) - if err != nil { - t.Fatal(err) - } - year, month, day := val.Date() - if year != 2016 || month != 12 || day != 5 { - t.Fatal(val) - } -} - -func Test_customize_type_encoder(t *testing.T) { - should := require.New(t) - RegisterTypeEncoderFunc("time.Time", func(ptr unsafe.Pointer, stream *Stream) { - t := *((*time.Time)(ptr)) - stream.WriteString(t.UTC().Format("2006-01-02 15:04:05")) - }, nil) - defer ConfigDefault.(*frozenConfig).cleanEncoders() - val := time.Unix(0, 0) - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`"1970-01-01 00:00:00"`, str) -} - -func Test_customize_byte_array_encoder(t *testing.T) { - ConfigDefault.(*frozenConfig).cleanEncoders() - should := require.New(t) - RegisterTypeEncoderFunc("[]uint8", func(ptr unsafe.Pointer, stream *Stream) { - t := *((*[]byte)(ptr)) - stream.WriteString(string(t)) - }, nil) - defer ConfigDefault.(*frozenConfig).cleanEncoders() - val := []byte("abc") - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`"abc"`, str) -} - -func Test_customize_float_marshal(t *testing.T) { - should := require.New(t) - json := Config{MarshalFloatWith6Digits: true}.Froze() - str, err := json.MarshalToString(float32(1.23456789)) - should.Nil(err) - should.Equal("1.234568", str) -} - -type Tom struct { - field1 string -} - -func Test_customize_field_decoder(t *testing.T) { - RegisterFieldDecoderFunc("jsoniter.Tom", "field1", func(ptr unsafe.Pointer, iter *Iterator) { - *((*string)(ptr)) = strconv.Itoa(iter.ReadInt()) - }) - defer ConfigDefault.(*frozenConfig).cleanDecoders() - tom := Tom{} - err := Unmarshal([]byte(`{"field1": 100}`), &tom) - if err != nil { - t.Fatal(err) - } -} - -type TestObject1 struct { - Field1 string -} - -type testExtension struct { - DummyExtension -} - -func (extension *testExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { - if structDescriptor.Type.String() != "jsoniter.TestObject1" { - return - } - binding := structDescriptor.GetField("Field1") - binding.Encoder = &funcEncoder{fun: func(ptr unsafe.Pointer, stream *Stream) { - str := *((*string)(ptr)) - val, _ := strconv.Atoi(str) - stream.WriteInt(val) - }} - binding.Decoder = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { - *((*string)(ptr)) = strconv.Itoa(iter.ReadInt()) - }} - binding.ToNames = []string{"field-1"} - binding.FromNames = []string{"field-1"} -} - -func Test_customize_field_by_extension(t *testing.T) { - should := require.New(t) - RegisterExtension(&testExtension{}) - obj := TestObject1{} - err := UnmarshalFromString(`{"field-1": 100}`, &obj) - should.Nil(err) - should.Equal("100", obj.Field1) - str, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{"field-1":100}`, str) -} - -type timeImplementedMarshaler time.Time - -func (obj timeImplementedMarshaler) MarshalJSON() ([]byte, error) { - seconds := time.Time(obj).Unix() - return []byte(strconv.FormatInt(seconds, 10)), nil -} - -func Test_marshaler(t *testing.T) { - type TestObject struct { - Field timeImplementedMarshaler - } - should := require.New(t) - val := timeImplementedMarshaler(time.Unix(123, 0)) - obj := TestObject{val} - bytes, err := json.Marshal(obj) - should.Nil(err) - should.Equal(`{"Field":123}`, string(bytes)) - str, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{"Field":123}`, str) -} - -func Test_marshaler_and_encoder(t *testing.T) { - type TestObject struct { - Field *timeImplementedMarshaler - } - ConfigDefault.(*frozenConfig).cleanEncoders() - should := require.New(t) - RegisterTypeEncoderFunc("jsoniter.timeImplementedMarshaler", func(ptr unsafe.Pointer, stream *Stream) { - stream.WriteString("hello from encoder") - }, nil) - val := timeImplementedMarshaler(time.Unix(123, 0)) - obj := TestObject{&val} - bytes, err := json.Marshal(obj) - should.Nil(err) - should.Equal(`{"Field":123}`, string(bytes)) - str, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{"Field":"hello from encoder"}`, str) -} - -type ObjectImplementedUnmarshaler int - -func (obj *ObjectImplementedUnmarshaler) UnmarshalJSON(s []byte) error { - val, _ := strconv.ParseInt(string(s[1:len(s)-1]), 10, 64) - *obj = ObjectImplementedUnmarshaler(val) - return nil -} - -func Test_unmarshaler(t *testing.T) { - should := require.New(t) - var obj ObjectImplementedUnmarshaler - err := json.Unmarshal([]byte(` "100" `), &obj) - should.Nil(err) - should.Equal(100, int(obj)) - iter := ParseString(ConfigDefault, ` "100" `) - iter.ReadVal(&obj) - should.Nil(err) - should.Equal(100, int(obj)) -} - -func Test_unmarshaler_and_decoder(t *testing.T) { - type TestObject struct { - Field *ObjectImplementedUnmarshaler - Field2 string - } - ConfigDefault.(*frozenConfig).cleanDecoders() - should := require.New(t) - RegisterTypeDecoderFunc("jsoniter.ObjectImplementedUnmarshaler", func(ptr unsafe.Pointer, iter *Iterator) { - *(*ObjectImplementedUnmarshaler)(ptr) = 10 - iter.Skip() - }) - obj := TestObject{} - val := ObjectImplementedUnmarshaler(0) - obj.Field = &val - err := json.Unmarshal([]byte(`{"Field":"100"}`), &obj) - should.Nil(err) - should.Equal(100, int(*obj.Field)) - err = Unmarshal([]byte(`{"Field":"100"}`), &obj) - should.Nil(err) - should.Equal(10, int(*obj.Field)) -} - -type tmString string -type tmStruct struct { - String tmString -} - -func (s tmStruct) MarshalJSON() ([]byte, error) { - var b []byte - b = append(b, '"') - b = append(b, s.String...) - b = append(b, '"') - return b, nil -} - -func Test_marshaler_on_struct(t *testing.T) { - fixed := tmStruct{"hello"} - //json.Marshal(fixed) - Marshal(fixed) -} - -type withChan struct { - F2 chan []byte -} - -func (q withChan) MarshalJSON() ([]byte, error) { - return []byte(`""`), nil -} - -func (q *withChan) UnmarshalJSON(value []byte) error { - return nil -} - -func Test_marshal_json_with_chan(t *testing.T) { - type TestObject struct { - F1 withChan - } - should := require.New(t) - output, err := MarshalToString(TestObject{}) - should.Nil(err) - should.Equal(`{"F1":""}`, output) -} - -type withTime struct { - time.Time -} - -func (t *withTime) UnmarshalJSON(b []byte) error { - return nil -} -func (t withTime) MarshalJSON() ([]byte, error) { - return []byte(`"fake"`), nil -} - -func Test_marshal_json_with_time(t *testing.T) { - type S1 struct { - F1 withTime - F2 *withTime - } - type TestObject struct { - TF1 S1 - } - should := require.New(t) - obj := TestObject{ - S1{ - F1: withTime{ - time.Unix(0, 0), - }, - F2: &withTime{ - time.Unix(0, 0), - }, - }, - } - output, err := json.Marshal(obj) - should.Nil(err) - should.Equal(`{"TF1":{"F1":"fake","F2":"fake"}}`, string(output)) - output, err = Marshal(obj) - should.Nil(err) - should.Equal(`{"TF1":{"F1":"fake","F2":"fake"}}`, string(output)) - obj = TestObject{} - should.Nil(json.Unmarshal([]byte(`{"TF1":{"F1":"fake","F2":"fake"}}`), &obj)) - should.NotNil(obj.TF1.F2) - obj = TestObject{} - should.Nil(Unmarshal([]byte(`{"TF1":{"F1":"fake","F2":"fake"}}`), &obj)) - should.NotNil(obj.TF1.F2) -} - -func Test_customize_tag_key(t *testing.T) { - - type TestObject struct { - Field string `orm:"field"` - } - - should := require.New(t) - json := Config{TagKey: "orm"}.Froze() - str, err := json.MarshalToString(TestObject{"hello"}) - should.Nil(err) - should.Equal(`{"field":"hello"}`, str) -} - -func Test_recursive_empty_interface_customization(t *testing.T) { - t.Skip() - var obj interface{} - RegisterTypeDecoderFunc("interface {}", func(ptr unsafe.Pointer, iter *Iterator) { - switch iter.WhatIsNext() { - case NumberValue: - *(*interface{})(ptr) = iter.ReadInt64() - default: - *(*interface{})(ptr) = iter.Read() - } - }) - should := require.New(t) - Unmarshal([]byte("[100]"), &obj) - should.Equal([]interface{}{int64(100)}, obj) -} - -type GeoLocation struct { - Id string `json:"id,omitempty" db:"id"` -} - -func (p *GeoLocation) MarshalJSON() ([]byte, error) { - return []byte(`{}`), nil -} - -func (p *GeoLocation) UnmarshalJSON(input []byte) error { - p.Id = "hello" - return nil -} - -func Test_marshal_and_unmarshal_on_non_pointer(t *testing.T) { - should := require.New(t) - locations := []GeoLocation{{"000"}} - bytes, err := Marshal(locations) - should.Nil(err) - should.Equal("[{}]", string(bytes)) - err = Unmarshal([]byte("[1]"), &locations) - should.Nil(err) - should.Equal("hello", locations[0].Id) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_demo_test.go b/vendor/github.com/json-iterator/go/jsoniter_demo_test.go deleted file mode 100644 index 85718d1b26..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_demo_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_bind_api_demo(t *testing.T) { - should := require.New(t) - val := []int{} - err := UnmarshalFromString(`[0,1,2,3] `, &val) - should.Nil(err) - should.Equal([]int{0, 1, 2, 3}, val) -} - -func Test_iterator_api_demo(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `[0,1,2,3]`) - total := 0 - for iter.ReadArray() { - total += iter.ReadInt() - } - should.Equal(6, total) -} - -type People struct { - Name string - Gender string - Age int - Address string - Mobile string - Country string - Height int -} - -func jsoniterMarshal(p *People) error { - _, err := Marshal(p) - if nil != err { - return err - } - return nil -} -func stdMarshal(p *People) error { - _, err := json.Marshal(p) - if nil != err { - return err - } - return nil -} - -func BenchmarkJosniterMarshal(b *testing.B) { - var p People - p.Address = "上海市徐汇区漕宝路" - p.Age = 30 - p.Country = "中国" - p.Gender = "male" - p.Height = 170 - p.Mobile = "18502120533" - p.Name = "Elvin" - b.ReportAllocs() - for i := 0; i < b.N; i++ { - err := jsoniterMarshal(&p) - if nil != err { - b.Error(err) - } - } -} - -func BenchmarkStdMarshal(b *testing.B) { - var p People - p.Address = "上海市徐汇区漕宝路" - p.Age = 30 - p.Country = "中国" - p.Gender = "male" - p.Height = 170 - p.Mobile = "18502120533" - p.Name = "Elvin" - b.ReportAllocs() - for i := 0; i < b.N; i++ { - err := stdMarshal(&p) - if nil != err { - b.Error(err) - } - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_encode_interface_test.go b/vendor/github.com/json-iterator/go/jsoniter_encode_interface_test.go deleted file mode 100644 index 14b7add9a6..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_encode_interface_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_encode_interface(t *testing.T) { - should := require.New(t) - var a interface{} - a = int8(10) - str, err := MarshalToString(a) - should.Nil(err) - should.Equal(str, "10") - a = float32(3) - str, err = MarshalToString(a) - should.Nil(err) - should.Equal(str, "3") - a = map[string]interface{}{"abc": 1} - str, err = MarshalToString(a) - should.Nil(err) - should.Equal(str, `{"abc":1}`) - a = uintptr(1) - str, err = MarshalToString(a) - should.Nil(err) - should.Equal(str, "1") - a = uint(1) - str, err = MarshalToString(a) - should.Nil(err) - should.Equal(str, "1") - a = uint8(1) - str, err = MarshalToString(a) - should.Nil(err) - should.Equal(str, "1") - a = json.RawMessage("abc") - MarshalToString(a) - str, err = MarshalToString(a) - should.Nil(err) - should.Equal(str, "abc") -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_enum_marshaler_test.go b/vendor/github.com/json-iterator/go/jsoniter_enum_marshaler_test.go deleted file mode 100644 index 69e1e8cd3e..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_enum_marshaler_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package jsoniter - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" -) - -type MyEnum int64 - -const ( - MyEnumA MyEnum = iota - MyEnumB -) - -func (m *MyEnum) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf(`"foo-%d"`, int(*m))), nil -} - -func (m *MyEnum) UnmarshalJSON(jb []byte) error { - switch string(jb) { - case `"foo-1"`: - *m = MyEnumB - default: - *m = MyEnumA - } - return nil -} - -func Test_custom_marshaler_on_enum(t *testing.T) { - type Wrapper struct { - Payload interface{} - } - type Wrapper2 struct { - Payload MyEnum - } - should := require.New(t) - - w := Wrapper{Payload: MyEnumB} - - jb, err := Marshal(w) - should.NoError(err) - should.Equal(`{"Payload":"foo-1"}`, string(jb)) - - var w2 Wrapper2 - err = Unmarshal(jb, &w2) - should.NoError(err) - should.Equal(MyEnumB, w2.Payload) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_fixed_array_test.go b/vendor/github.com/json-iterator/go/jsoniter_fixed_array_test.go deleted file mode 100644 index 6824b11969..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_fixed_array_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "github.com/stretchr/testify/require" - "testing" -) - -func Test_encode_fixed_array(t *testing.T) { - should := require.New(t) - type FixedArray [2]float64 - fixed := FixedArray{0.1, 1.0} - output, err := MarshalToString(fixed) - should.Nil(err) - should.Equal("[0.1,1]", output) -} - -func Test_encode_fixed_array_of_map(t *testing.T) { - should := require.New(t) - type FixedArray [2]map[string]string - fixed := FixedArray{map[string]string{"1": "2"}, map[string]string{"3": "4"}} - output, err := MarshalToString(fixed) - should.Nil(err) - should.Equal(`[{"1":"2"},{"3":"4"}]`, output) -} - -func Test_decode_fixed_array(t *testing.T) { - should := require.New(t) - type FixedArray [2]float64 - var fixed FixedArray - should.Nil(json.Unmarshal([]byte("[1,2,3]"), &fixed)) - should.Equal(float64(1), fixed[0]) - should.Equal(float64(2), fixed[1]) - should.Nil(Unmarshal([]byte("[1,2,3]"), &fixed)) - should.Equal(float64(1), fixed[0]) - should.Equal(float64(2), fixed[1]) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_float_test.go b/vendor/github.com/json-iterator/go/jsoniter_float_test.go deleted file mode 100644 index d90ff2bd57..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_float_test.go +++ /dev/null @@ -1,210 +0,0 @@ -// +build go1.8 - -package jsoniter - -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_read_big_float(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `12.3`) - val := iter.ReadBigFloat() - val64, _ := val.Float64() - should.Equal(12.3, val64) -} - -func Test_read_big_int(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `92233720368547758079223372036854775807`) - val := iter.ReadBigInt() - should.NotNil(val) - should.Equal(`92233720368547758079223372036854775807`, val.String()) -} - -func Test_read_float(t *testing.T) { - inputs := []string{ - `1.1`, `1000`, `9223372036854775807`, `12.3`, `-12.3`, `720368.54775807`, `720368.547758075`, - `1e1`, `1e+1`, `1e-1`, `1E1`, `1E+1`, `1E-1`, `-1e1`, `-1e+1`, `-1e-1`, - } - for _, input := range inputs { - // non-streaming - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input+",") - expected, err := strconv.ParseFloat(input, 32) - should.Nil(err) - should.Equal(float32(expected), iter.ReadFloat32()) - }) - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input+",") - expected, err := strconv.ParseFloat(input, 64) - should.Nil(err) - should.Equal(expected, iter.ReadFloat64()) - }) - // streaming - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := Parse(ConfigDefault, bytes.NewBufferString(input+","), 2) - expected, err := strconv.ParseFloat(input, 32) - should.Nil(err) - should.Equal(float32(expected), iter.ReadFloat32()) - }) - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := Parse(ConfigDefault, bytes.NewBufferString(input+","), 2) - val := float64(0) - err := json.Unmarshal([]byte(input), &val) - should.Nil(err) - should.Equal(val, iter.ReadFloat64()) - }) - } -} - -func Test_read_float_as_interface(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `12.3`) - should.Equal(float64(12.3), iter.Read()) -} - -func Test_wrap_float(t *testing.T) { - should := require.New(t) - str, err := MarshalToString(WrapFloat64(12.3)) - should.Nil(err) - should.Equal("12.3", str) -} - -func Test_write_float32(t *testing.T) { - vals := []float32{0, 1, -1, 99, 0xff, 0xfff, 0xffff, 0xfffff, 0xffffff, 0x4ffffff, 0xfffffff, - -0x4ffffff, -0xfffffff, 1.2345, 1.23456, 1.234567, 1.001} - for _, val := range vals { - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteFloat32Lossy(val) - stream.Flush() - should.Nil(stream.Error) - output, err := json.Marshal(val) - should.Nil(err) - should.Equal(string(output), buf.String()) - }) - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(val) - stream.Flush() - should.Nil(stream.Error) - output, err := json.Marshal(val) - should.Nil(err) - should.Equal(string(output), buf.String()) - }) - } - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 10) - stream.WriteRaw("abcdefg") - stream.WriteFloat32Lossy(1.123456) - stream.Flush() - should.Nil(stream.Error) - should.Equal("abcdefg1.123456", buf.String()) - - stream = NewStream(ConfigDefault, nil, 0) - stream.WriteFloat32(float32(0.0000001)) - should.Equal("1e-07", string(stream.buf)) -} - -func Test_write_float64(t *testing.T) { - vals := []float64{0, 1, -1, 99, 0xff, 0xfff, 0xffff, 0xfffff, 0xffffff, 0x4ffffff, 0xfffffff, - -0x4ffffff, -0xfffffff, 1.2345, 1.23456, 1.234567, 1.001} - for _, val := range vals { - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteFloat64Lossy(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatFloat(val, 'f', -1, 64), buf.String()) - }) - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatFloat(val, 'f', -1, 64), buf.String()) - }) - } - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 10) - stream.WriteRaw("abcdefg") - stream.WriteFloat64Lossy(1.123456) - stream.Flush() - should.Nil(stream.Error) - should.Equal("abcdefg1.123456", buf.String()) - - stream = NewStream(ConfigDefault, nil, 0) - stream.WriteFloat64(float64(0.0000001)) - should.Equal("1e-07", string(stream.buf)) -} - -func Test_read_float64_cursor(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, "[1.23456789\n,2,3]") - should.True(iter.ReadArray()) - should.Equal(1.23456789, iter.Read()) - should.True(iter.ReadArray()) - should.Equal(float64(2), iter.Read()) -} - -func Test_read_float_scientific(t *testing.T) { - should := require.New(t) - var obj interface{} - should.Nil(UnmarshalFromString(`1e1`, &obj)) - should.Equal(float64(10), obj) - should.Nil(json.Unmarshal([]byte(`1e1`), &obj)) - should.Equal(float64(10), obj) - should.Nil(UnmarshalFromString(`1.0e1`, &obj)) - should.Equal(float64(10), obj) - should.Nil(json.Unmarshal([]byte(`1.0e1`), &obj)) - should.Equal(float64(10), obj) -} - -func Test_lossy_float_marshal(t *testing.T) { - should := require.New(t) - api := Config{MarshalFloatWith6Digits: true}.Froze() - output, err := api.MarshalToString(float64(0.1234567)) - should.Nil(err) - should.Equal("0.123457", output) - output, err = api.MarshalToString(float32(0.1234567)) - should.Nil(err) - should.Equal("0.123457", output) -} - -func Benchmark_jsoniter_float(b *testing.B) { - b.ReportAllocs() - input := []byte(`1.1123,`) - iter := NewIterator(ConfigDefault) - for n := 0; n < b.N; n++ { - iter.ResetBytes(input) - iter.ReadFloat64() - } -} - -func Benchmark_json_float(b *testing.B) { - for n := 0; n < b.N; n++ { - result := float64(0) - json.Unmarshal([]byte(`1.1`), &result) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_int_test.go b/vendor/github.com/json-iterator/go/jsoniter_int_test.go deleted file mode 100644 index e0c80294d5..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_int_test.go +++ /dev/null @@ -1,561 +0,0 @@ -// +build go1.8 - -package jsoniter - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "strconv" - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_read_uint64_invalid(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, ",") - iter.ReadUint64() - should.NotNil(iter.Error) -} - -func Test_read_int_from_null(t *testing.T) { - - type TestObject struct { - F1 int8 - F2 int16 - F3 int32 - F4 int64 - F5 int - F6 uint8 - F7 uint16 - F8 uint32 - F9 uint64 - F10 uint - F11 float32 - F12 float64 - F13 uintptr - } - - should := require.New(t) - obj := TestObject{} - err := Unmarshal([]byte(`{ - "f1":null, - "f2":null, - "f3":null, - "f4":null, - "f5":null, - "f6":null, - "f7":null, - "f8":null, - "f9":null, - "f10":null, - "f11":null, - "f12":null, - "f13":null - }`), &obj) - should.Nil(err) -} - -func _int8(t *testing.T) { - inputs := []string{`127`, `-128`} - for _, input := range inputs { - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input) - expected, err := strconv.ParseInt(input, 10, 8) - should.Nil(err) - should.Equal(int8(expected), iter.ReadInt8()) - }) - } -} - -func Test_read_int16(t *testing.T) { - inputs := []string{`32767`, `-32768`} - for _, input := range inputs { - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input) - expected, err := strconv.ParseInt(input, 10, 16) - should.Nil(err) - should.Equal(int16(expected), iter.ReadInt16()) - }) - } -} - -func Test_read_int32(t *testing.T) { - inputs := []string{`1`, `12`, `123`, `1234`, `12345`, `123456`, `2147483647`, `-2147483648`} - for _, input := range inputs { - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input) - expected, err := strconv.ParseInt(input, 10, 32) - should.Nil(err) - should.Equal(int32(expected), iter.ReadInt32()) - }) - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := Parse(ConfigDefault, bytes.NewBufferString(input), 2) - expected, err := strconv.ParseInt(input, 10, 32) - should.Nil(err) - should.Equal(int32(expected), iter.ReadInt32()) - }) - } -} - -func Test_read_int32_array(t *testing.T) { - should := require.New(t) - input := `[123,456,789]` - val := make([]int32, 0) - UnmarshalFromString(input, &val) - should.Equal(3, len(val)) -} - -func Test_read_int64_array(t *testing.T) { - should := require.New(t) - input := `[123,456,789]` - val := make([]int64, 0) - UnmarshalFromString(input, &val) - should.Equal(3, len(val)) -} - -func Test_read_int_overflow(t *testing.T) { - should := require.New(t) - inputArr := []string{"123451", "-123451"} - for _, s := range inputArr { - iter := ParseString(ConfigDefault, s) - iter.ReadInt8() - should.NotNil(iter.Error) - - iterU := ParseString(ConfigDefault, s) - iterU.ReadUint8() - should.NotNil(iterU.Error) - - } - - inputArr = []string{"12345678912", "-12345678912"} - for _, s := range inputArr { - iter := ParseString(ConfigDefault, s) - iter.ReadInt16() - should.NotNil(iter.Error) - - iterUint := ParseString(ConfigDefault, s) - iterUint.ReadUint16() - should.NotNil(iterUint.Error) - } - - inputArr = []string{"3111111111", "-3111111111", "1234232323232323235678912", "-1234567892323232323212"} - for _, s := range inputArr { - iter := ParseString(ConfigDefault, s) - iter.ReadInt32() - should.NotNil(iter.Error) - - iterUint := ParseString(ConfigDefault, s) - iterUint.ReadUint32() - should.NotNil(iterUint.Error) - } - - inputArr = []string{"9223372036854775811", "-9523372036854775807", "1234232323232323235678912", "-1234567892323232323212"} - for _, s := range inputArr { - iter := ParseString(ConfigDefault, s) - iter.ReadInt64() - should.NotNil(iter.Error) - - iterUint := ParseString(ConfigDefault, s) - iterUint.ReadUint64() - should.NotNil(iterUint.Error) - } -} - -func Test_read_int64(t *testing.T) { - inputs := []string{`1`, `12`, `123`, `1234`, `12345`, `123456`, `9223372036854775807`, `-9223372036854775808`} - for _, input := range inputs { - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input) - expected, err := strconv.ParseInt(input, 10, 64) - should.Nil(err) - should.Equal(expected, iter.ReadInt64()) - }) - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := Parse(ConfigDefault, bytes.NewBufferString(input), 2) - expected, err := strconv.ParseInt(input, 10, 64) - should.Nil(err) - should.Equal(expected, iter.ReadInt64()) - }) - } -} - -func Test_read_int64_overflow(t *testing.T) { - should := require.New(t) - input := "123456789123456789123456789123456789," - iter := ParseString(ConfigDefault, input) - iter.ReadInt64() - should.NotNil(iter.Error) -} - -func Test_wrap_int(t *testing.T) { - should := require.New(t) - str, err := MarshalToString(WrapInt64(100)) - should.Nil(err) - should.Equal("100", str) -} - -func Test_write_uint8(t *testing.T) { - vals := []uint8{0, 1, 11, 111, 255} - for _, val := range vals { - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteUint8(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatUint(uint64(val), 10), buf.String()) - }) - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatUint(uint64(val), 10), buf.String()) - }) - } - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 3) - stream.WriteRaw("a") - stream.WriteUint8(100) // should clear buffer - stream.Flush() - should.Nil(stream.Error) - should.Equal("a100", buf.String()) -} - -func Test_write_int8(t *testing.T) { - vals := []int8{0, 1, -1, 99, 0x7f, -0x80} - for _, val := range vals { - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteInt8(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatInt(int64(val), 10), buf.String()) - }) - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatInt(int64(val), 10), buf.String()) - }) - } - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4) - stream.WriteRaw("a") - stream.WriteInt8(-100) // should clear buffer - stream.Flush() - should.Nil(stream.Error) - should.Equal("a-100", buf.String()) -} - -func Test_write_uint16(t *testing.T) { - vals := []uint16{0, 1, 11, 111, 255, 0xfff, 0xffff} - for _, val := range vals { - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteUint16(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatUint(uint64(val), 10), buf.String()) - }) - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatUint(uint64(val), 10), buf.String()) - }) - } - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 5) - stream.WriteRaw("a") - stream.WriteUint16(10000) // should clear buffer - stream.Flush() - should.Nil(stream.Error) - should.Equal("a10000", buf.String()) -} - -func Test_write_int16(t *testing.T) { - vals := []int16{0, 1, 11, 111, 255, 0xfff, 0x7fff, -0x8000} - for _, val := range vals { - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteInt16(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatInt(int64(val), 10), buf.String()) - }) - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatInt(int64(val), 10), buf.String()) - }) - } - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 6) - stream.WriteRaw("a") - stream.WriteInt16(-10000) // should clear buffer - stream.Flush() - should.Nil(stream.Error) - should.Equal("a-10000", buf.String()) -} - -func Test_write_uint32(t *testing.T) { - vals := []uint32{0, 1, 11, 111, 255, 999999, 0xfff, 0xffff, 0xfffff, 0xffffff, 0xfffffff, 0xffffffff} - for _, val := range vals { - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteUint32(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatUint(uint64(val), 10), buf.String()) - }) - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatUint(uint64(val), 10), buf.String()) - }) - } - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 10) - stream.WriteRaw("a") - stream.WriteUint32(0xffffffff) // should clear buffer - stream.Flush() - should.Nil(stream.Error) - should.Equal("a4294967295", buf.String()) -} - -func Test_write_int32(t *testing.T) { - vals := []int32{0, 1, 11, 111, 255, 999999, 0xfff, 0xffff, 0xfffff, 0xffffff, 0xfffffff, 0x7fffffff, -0x80000000} - for _, val := range vals { - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteInt32(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatInt(int64(val), 10), buf.String()) - }) - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatInt(int64(val), 10), buf.String()) - }) - } - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 11) - stream.WriteRaw("a") - stream.WriteInt32(-0x7fffffff) // should clear buffer - stream.Flush() - should.Nil(stream.Error) - should.Equal("a-2147483647", buf.String()) -} - -func Test_write_uint64(t *testing.T) { - vals := []uint64{0, 1, 11, 111, 255, 999999, 0xfff, 0xffff, 0xfffff, 0xffffff, 0xfffffff, 0xffffffff, - 0xfffffffff, 0xffffffffff, 0xfffffffffff, 0xffffffffffff, 0xfffffffffffff, 0xffffffffffffff, - 0xfffffffffffffff, 0xffffffffffffffff} - for _, val := range vals { - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteUint64(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatUint(uint64(val), 10), buf.String()) - }) - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatUint(uint64(val), 10), buf.String()) - }) - } - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 10) - stream.WriteRaw("a") - stream.WriteUint64(0xffffffff) // should clear buffer - stream.Flush() - should.Nil(stream.Error) - should.Equal("a4294967295", buf.String()) -} - -func Test_write_int64(t *testing.T) { - vals := []int64{0, 1, 11, 111, 255, 999999, 0xfff, 0xffff, 0xfffff, 0xffffff, 0xfffffff, 0xffffffff, - 0xfffffffff, 0xffffffffff, 0xfffffffffff, 0xffffffffffff, 0xfffffffffffff, 0xffffffffffffff, - 0xfffffffffffffff, 0x7fffffffffffffff, -0x8000000000000000} - for _, val := range vals { - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteInt64(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatInt(val, 10), buf.String()) - }) - t.Run(fmt.Sprintf("%v", val), func(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(val) - stream.Flush() - should.Nil(stream.Error) - should.Equal(strconv.FormatInt(val, 10), buf.String()) - }) - } - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 10) - stream.WriteRaw("a") - stream.WriteInt64(0xffffffff) // should clear buffer - stream.Flush() - should.Nil(stream.Error) - should.Equal("a4294967295", buf.String()) -} - -func Test_write_val_int(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal(1001) - stream.Flush() - should.Nil(stream.Error) - should.Equal("1001", buf.String()) -} - -func Test_write_val_int_ptr(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - val := 1001 - stream.WriteVal(&val) - stream.Flush() - should.Nil(stream.Error) - should.Equal("1001", buf.String()) -} - -func Test_json_number(t *testing.T) { - should := require.New(t) - var arr []json.Number - err := Unmarshal([]byte(`[1]`), &arr) - should.Nil(err) - should.Equal(json.Number("1"), arr[0]) - str, err := MarshalToString(arr) - should.Nil(err) - should.Equal(`[1]`, str) -} - -func Test_jsoniter_number(t *testing.T) { - should := require.New(t) - var arr []Number - err := Unmarshal([]byte(`[1]`), &arr) - should.Nil(err) - should.Equal(Number("1"), arr[0]) - str, isNumber := CastJsonNumber(arr[0]) - should.True(isNumber) - should.Equal("1", str) -} - -func Test_non_numeric_as_number(t *testing.T) { - should := require.New(t) - var v1 json.Number - err := Unmarshal([]byte(`"500"`), &v1) - should.Nil(err) - should.Equal("500", string(v1)) - var v2 Number - err = Unmarshal([]byte(`"500"`), &v2) - should.Nil(err) - should.Equal("500", string(v2)) -} - -func Test_null_as_number(t *testing.T) { - should := require.New(t) - var v1 json.Number - err := json.Unmarshal([]byte(`null`), &v1) - should.Nil(err) - should.Equal("", string(v1)) - var v2 Number - err = Unmarshal([]byte(`null`), &v2) - should.Nil(err) - should.Equal("", string(v2)) -} - -func Benchmark_jsoniter_encode_int(b *testing.B) { - stream := NewStream(ConfigDefault, ioutil.Discard, 64) - for n := 0; n < b.N; n++ { - stream.n = 0 - stream.WriteUint64(0xffffffff) - } -} - -func Benchmark_itoa(b *testing.B) { - for n := 0; n < b.N; n++ { - strconv.FormatInt(0xffffffff, 10) - } -} - -func Benchmark_jsoniter_int(b *testing.B) { - iter := NewIterator(ConfigDefault) - input := []byte(`100`) - for n := 0; n < b.N; n++ { - iter.ResetBytes(input) - iter.ReadInt64() - } -} - -func Benchmark_json_int(b *testing.B) { - for n := 0; n < b.N; n++ { - result := int64(0) - json.Unmarshal([]byte(`-100`), &result) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_interface_test.go b/vendor/github.com/json-iterator/go/jsoniter_interface_test.go deleted file mode 100644 index 5a0528865b..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_interface_test.go +++ /dev/null @@ -1,560 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "fmt" - "testing" - "unsafe" - - "github.com/stretchr/testify/require" -) - -func Test_write_array_of_interface(t *testing.T) { - should := require.New(t) - array := []interface{}{"hello"} - str, err := MarshalToString(array) - should.Nil(err) - should.Equal(`["hello"]`, str) -} - -func Test_write_map_of_interface(t *testing.T) { - should := require.New(t) - val := map[string]interface{}{"hello": "world"} - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`{"hello":"world"}`, str) -} - -func Test_write_map_of_interface_in_struct(t *testing.T) { - type TestObject struct { - Field map[string]interface{} - } - should := require.New(t) - val := TestObject{map[string]interface{}{"hello": "world"}} - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`{"Field":{"hello":"world"}}`, str) -} - -func Test_write_map_of_interface_in_struct_with_two_fields(t *testing.T) { - type TestObject struct { - Field map[string]interface{} - Field2 string - } - should := require.New(t) - val := TestObject{map[string]interface{}{"hello": "world"}, ""} - str, err := MarshalToString(val) - should.Nil(err) - should.Contains(str, `"Field":{"hello":"world"}`) -} - -type MyInterface interface { - Hello() string -} - -type MyString string - -func (ms MyString) Hello() string { - return string(ms) -} - -func Test_write_map_of_custom_interface(t *testing.T) { - should := require.New(t) - myStr := MyString("world") - should.Equal("world", myStr.Hello()) - val := map[string]MyInterface{"hello": myStr} - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`{"hello":"world"}`, str) -} - -func Test_write_interface(t *testing.T) { - should := require.New(t) - var val interface{} - val = "hello" - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`"hello"`, str) -} - -func Test_read_interface(t *testing.T) { - should := require.New(t) - var val interface{} - err := UnmarshalFromString(`"hello"`, &val) - should.Nil(err) - should.Equal("hello", val) - err = UnmarshalFromString(`1e1`, &val) - should.Nil(err) - should.Equal(float64(10), val) - err = UnmarshalFromString(`1.0e1`, &val) - should.Nil(err) - should.Equal(float64(10), val) - err = json.Unmarshal([]byte(`1.0e1`), &val) - should.Nil(err) - should.Equal(float64(10), val) -} - -func Test_read_custom_interface(t *testing.T) { - should := require.New(t) - var val MyInterface - RegisterTypeDecoderFunc("jsoniter.MyInterface", func(ptr unsafe.Pointer, iter *Iterator) { - *((*MyInterface)(ptr)) = MyString(iter.ReadString()) - }) - err := UnmarshalFromString(`"hello"`, &val) - should.Nil(err) - should.Equal("hello", val.Hello()) -} - -func Test_decode_object_contain_empty_interface(t *testing.T) { - type TestObject struct { - Field interface{} - } - should := require.New(t) - obj := TestObject{} - obj.Field = 1024 - should.Nil(UnmarshalFromString(`{"Field": "hello"}`, &obj)) - should.Equal("hello", obj.Field) -} - -func Test_decode_object_contain_non_empty_interface(t *testing.T) { - type TestObject struct { - Field MyInterface - } - should := require.New(t) - obj := TestObject{} - obj.Field = MyString("abc") - should.Nil(UnmarshalFromString(`{"Field": "hello"}`, &obj)) - should.Equal(MyString("hello"), obj.Field) -} - -func Test_encode_object_contain_empty_interface(t *testing.T) { - type TestObject struct { - Field interface{} - } - should := require.New(t) - obj := TestObject{} - obj.Field = 1024 - str, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{"Field":1024}`, str) -} - -func Test_encode_object_contain_non_empty_interface(t *testing.T) { - type TestObject struct { - Field MyInterface - } - should := require.New(t) - obj := TestObject{} - obj.Field = MyString("hello") - str, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{"Field":"hello"}`, str) -} - -func Test_nil_non_empty_interface(t *testing.T) { - ConfigDefault.(*frozenConfig).cleanEncoders() - ConfigDefault.(*frozenConfig).cleanDecoders() - type TestObject struct { - Field []MyInterface - } - should := require.New(t) - obj := TestObject{} - b := []byte(`{"Field":["AAA"]}`) - should.NotNil(json.Unmarshal(b, &obj)) - should.NotNil(Unmarshal(b, &obj)) -} - -func Test_read_large_number_as_interface(t *testing.T) { - should := require.New(t) - var val interface{} - err := Config{UseNumber: true}.Froze().UnmarshalFromString(`123456789123456789123456789`, &val) - should.Nil(err) - output, err := MarshalToString(val) - should.Nil(err) - should.Equal(`123456789123456789123456789`, output) -} - -func Test_nested_one_field_struct(t *testing.T) { - should := require.New(t) - type YetYetAnotherObject struct { - Field string - } - type YetAnotherObject struct { - Field *YetYetAnotherObject - } - type AnotherObject struct { - Field *YetAnotherObject - } - type TestObject struct { - Me *AnotherObject - } - obj := TestObject{&AnotherObject{&YetAnotherObject{&YetYetAnotherObject{"abc"}}}} - str, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{"Me":{"Field":{"Field":{"Field":"abc"}}}}`, str) - str, err = MarshalToString(&obj) - should.Nil(err) - should.Equal(`{"Me":{"Field":{"Field":{"Field":"abc"}}}}`, str) -} - -func Test_struct_with_embedded_ptr_with_tag(t *testing.T) { - type O1 struct { - O1F string - } - - type Option struct { - O1 *O1 - } - - type T struct { - Option `json:","` - } - var obj T - should := require.New(t) - output, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{"O1":null}`, output) -} - -func Test_struct_with_one_nil(t *testing.T) { - type TestObject struct { - F *float64 - } - var obj TestObject - should := require.New(t) - output, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{"F":null}`, output) -} - -func Test_struct_with_one_nil_embedded(t *testing.T) { - type Parent struct { - Field1 string - Field2 string - } - type TestObject struct { - *Parent - } - obj := TestObject{} - should := require.New(t) - bytes, err := json.Marshal(obj) - should.Nil(err) - should.Equal("{}", string(bytes)) - output, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{}`, output) -} - -func Test_struct_with_not_nil_embedded(t *testing.T) { - type Parent struct { - Field0 string - Field1 []string - Field2 map[string]interface{} - } - type TestObject struct { - *Parent - } - should := require.New(t) - var obj TestObject - err := UnmarshalFromString(`{"Field0":"1","Field1":null,"Field2":{"K":"V"}}`, &obj) - should.Nil(err) - should.Nil(obj.Field1) - should.Equal(map[string]interface{}{"K": "V"}, obj.Field2) - should.Equal("1", obj.Field0) -} - -func Test_array_with_one_nil_ptr(t *testing.T) { - obj := [1]*float64{nil} - should := require.New(t) - output, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`[null]`, output) -} - -func Test_array_with_one_not_nil_ptr(t *testing.T) { - two := float64(2) - obj := [1]*float64{&two} - should := require.New(t) - output, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`[2]`, output) -} - -func Test_embedded_array_with_one_nil(t *testing.T) { - type TestObject struct { - Field1 int - Field2 [1]*float64 - } - var obj TestObject - should := require.New(t) - output, err := MarshalToString(obj) - should.Nil(err) - should.Contains(output, `"Field2":[null]`) -} - -func Test_array_with_nothing(t *testing.T) { - var obj [2]*float64 - should := require.New(t) - output, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`[null,null]`, output) -} - -func Test_unmarshal_ptr_to_interface(t *testing.T) { - type TestData struct { - Name string `json:"name"` - } - should := require.New(t) - var obj interface{} = &TestData{} - err := json.Unmarshal([]byte(`{"name":"value"}`), &obj) - should.Nil(err) - should.Equal("&{value}", fmt.Sprintf("%v", obj)) - obj = interface{}(&TestData{}) - err = Unmarshal([]byte(`{"name":"value"}`), &obj) - should.Nil(err) - should.Equal("&{value}", fmt.Sprintf("%v", obj)) -} - -func Test_nil_out_null_interface(t *testing.T) { - type TestData struct { - Field interface{} `json:"field"` - } - should := require.New(t) - - var boolVar bool - obj := TestData{ - Field: &boolVar, - } - - data1 := []byte(`{"field": true}`) - - err := Unmarshal(data1, &obj) - should.NoError(err) - should.Equal(true, *(obj.Field.(*bool))) - - data2 := []byte(`{"field": null}`) - - err = Unmarshal(data2, &obj) - should.NoError(err) - should.Equal(nil, obj.Field) - - // Checking stdlib behavior matches. - obj2 := TestData{ - Field: &boolVar, - } - - err = json.Unmarshal(data1, &obj2) - should.NoError(err) - should.Equal(true, *(obj2.Field.(*bool))) - - err = json.Unmarshal(data2, &obj2) - should.NoError(err) - should.Equal(nil, obj2.Field) -} - -func Test_omitempty_nil_interface(t *testing.T) { - type TestData struct { - Field interface{} `json:"field,omitempty"` - } - should := require.New(t) - - obj := TestData{ - Field: nil, - } - - js, err := json.Marshal(obj) - should.NoError(err) - should.Equal("{}", string(js)) - - str, err := MarshalToString(obj) - should.NoError(err) - should.Equal(string(js), str) -} - -func Test_omitempty_nil_nonempty_interface(t *testing.T) { - type TestData struct { - Field MyInterface `json:"field,omitempty"` - } - should := require.New(t) - - obj := TestData{ - Field: nil, - } - - js, err := json.Marshal(obj) - should.NoError(err) - should.Equal("{}", string(js)) - - str, err := MarshalToString(obj) - should.NoError(err) - should.Equal(string(js), str) - - obj.Field = MyString("hello") - err = UnmarshalFromString(`{"field":null}`, &obj) - should.NoError(err) - should.Equal(nil, obj.Field) -} - -func Test_marshal_nil_marshaler_interface(t *testing.T) { - type TestData struct { - Field json.Marshaler `json:"field"` - } - should := require.New(t) - - obj := TestData{ - Field: nil, - } - - js, err := json.Marshal(obj) - should.NoError(err) - should.Equal(`{"field":null}`, string(js)) - - str, err := MarshalToString(obj) - should.NoError(err) - should.Equal(string(js), str) -} - -func Test_marshal_nil_nonempty_interface(t *testing.T) { - type TestData struct { - Field MyInterface `json:"field"` - } - should := require.New(t) - - obj := TestData{ - Field: nil, - } - - js, err := json.Marshal(obj) - should.NoError(err) - should.Equal(`{"field":null}`, string(js)) - - str, err := MarshalToString(obj) - should.NoError(err) - should.Equal(string(js), str) - - obj.Field = MyString("hello") - err = Unmarshal(js, &obj) - should.NoError(err) - should.Equal(nil, obj.Field) -} - -func Test_overwrite_interface_ptr_value_with_nil(t *testing.T) { - type Wrapper struct { - Payload interface{} `json:"payload,omitempty"` - } - type Payload struct { - Value int `json:"val,omitempty"` - } - - should := require.New(t) - - payload := &Payload{} - wrapper := &Wrapper{ - Payload: &payload, - } - - err := json.Unmarshal([]byte(`{"payload": {"val": 42}}`), &wrapper) - should.Equal(nil, err) - should.Equal(&payload, wrapper.Payload) - should.Equal(42, (*(wrapper.Payload.(**Payload))).Value) - - err = json.Unmarshal([]byte(`{"payload": null}`), &wrapper) - should.Equal(nil, err) - should.Equal(&payload, wrapper.Payload) - should.Equal((*Payload)(nil), payload) - - payload = &Payload{} - wrapper = &Wrapper{ - Payload: &payload, - } - - err = Unmarshal([]byte(`{"payload": {"val": 42}}`), &wrapper) - should.Equal(nil, err) - should.Equal(&payload, wrapper.Payload) - should.Equal(42, (*(wrapper.Payload.(**Payload))).Value) - - err = Unmarshal([]byte(`{"payload": null}`), &wrapper) - should.Equal(nil, err) - should.Equal(&payload, wrapper.Payload) - should.Equal((*Payload)(nil), payload) -} - -func Test_overwrite_interface_value_with_nil(t *testing.T) { - type Wrapper struct { - Payload interface{} `json:"payload,omitempty"` - } - type Payload struct { - Value int `json:"val,omitempty"` - } - - should := require.New(t) - - payload := &Payload{} - wrapper := &Wrapper{ - Payload: payload, - } - - err := json.Unmarshal([]byte(`{"payload": {"val": 42}}`), &wrapper) - should.Equal(nil, err) - should.Equal(42, (*(wrapper.Payload.(*Payload))).Value) - - err = json.Unmarshal([]byte(`{"payload": null}`), &wrapper) - should.Equal(nil, err) - should.Equal(nil, wrapper.Payload) - should.Equal(42, payload.Value) - - payload = &Payload{} - wrapper = &Wrapper{ - Payload: payload, - } - - err = Unmarshal([]byte(`{"payload": {"val": 42}}`), &wrapper) - should.Equal(nil, err) - should.Equal(42, (*(wrapper.Payload.(*Payload))).Value) - - err = Unmarshal([]byte(`{"payload": null}`), &wrapper) - should.Equal(nil, err) - should.Equal(nil, wrapper.Payload) - should.Equal(42, payload.Value) -} - -func Test_unmarshal_into_nil(t *testing.T) { - type Payload struct { - Value int `json:"val,omitempty"` - } - type Wrapper struct { - Payload interface{} `json:"payload,omitempty"` - } - - should := require.New(t) - - var payload *Payload - wrapper := &Wrapper{ - Payload: payload, - } - - err := json.Unmarshal([]byte(`{"payload": {"val": 42}}`), &wrapper) - should.Nil(err) - should.NotNil(wrapper.Payload) - should.Nil(payload) - - err = json.Unmarshal([]byte(`{"payload": null}`), &wrapper) - should.Nil(err) - should.Nil(wrapper.Payload) - should.Nil(payload) - - payload = nil - wrapper = &Wrapper{ - Payload: payload, - } - - err = Unmarshal([]byte(`{"payload": {"val": 42}}`), &wrapper) - should.Nil(err) - should.NotNil(wrapper.Payload) - should.Nil(payload) - - err = Unmarshal([]byte(`{"payload": null}`), &wrapper) - should.Nil(err) - should.Nil(wrapper.Payload) - should.Nil(payload) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_invalid_test.go b/vendor/github.com/json-iterator/go/jsoniter_invalid_test.go deleted file mode 100644 index 69be4dc531..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_invalid_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package jsoniter - -import ( - "bytes" - "encoding/json" - "github.com/stretchr/testify/require" - "io" - "testing" -) - -func Test_missing_object_end(t *testing.T) { - should := require.New(t) - type TestObject struct { - Metric string `json:"metric"` - Tags map[string]interface{} `json:"tags"` - } - obj := TestObject{} - should.NotNil(UnmarshalFromString(`{"metric": "sys.777","tags": {"a":"123"}`, &obj)) -} - -func Test_missing_array_end(t *testing.T) { - should := require.New(t) - should.NotNil(UnmarshalFromString(`[1,2,3`, &[]int{})) -} - -func Test_invalid_any(t *testing.T) { - should := require.New(t) - any := Get([]byte("[]")) - should.Equal(InvalidValue, any.Get(0.3).ValueType()) - // is nil correct ? - should.Equal(nil, any.Get(0.3).GetInterface()) - - any = any.Get(0.3) - should.Equal(false, any.ToBool()) - should.Equal(int(0), any.ToInt()) - should.Equal(int32(0), any.ToInt32()) - should.Equal(int64(0), any.ToInt64()) - should.Equal(uint(0), any.ToUint()) - should.Equal(uint32(0), any.ToUint32()) - should.Equal(uint64(0), any.ToUint64()) - should.Equal(float32(0), any.ToFloat32()) - should.Equal(float64(0), any.ToFloat64()) - should.Equal("", any.ToString()) - - should.Equal(InvalidValue, any.Get(0.1).Get(1).ValueType()) -} - -func Test_invalid_struct_input(t *testing.T) { - should := require.New(t) - type TestObject struct{} - input := []byte{54, 141, 30} - obj := TestObject{} - should.NotNil(Unmarshal(input, &obj)) -} - -func Test_invalid_slice_input(t *testing.T) { - should := require.New(t) - type TestObject struct{} - input := []byte{93} - obj := []string{} - should.NotNil(Unmarshal(input, &obj)) -} - -func Test_invalid_array_input(t *testing.T) { - should := require.New(t) - type TestObject struct{} - input := []byte{93} - obj := [0]string{} - should.NotNil(Unmarshal(input, &obj)) -} - -func Test_invalid_float(t *testing.T) { - inputs := []string{ - `1.e1`, // dot without following digit - `1.`, // dot can not be the last char - ``, // empty number - `01`, // extra leading zero - `-`, // negative without digit - `--`, // double negative - `--2`, // double negative - } - for _, input := range inputs { - t.Run(input, func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input+",") - iter.Skip() - should.NotEqual(io.EOF, iter.Error) - should.NotNil(iter.Error) - v := float64(0) - should.NotNil(json.Unmarshal([]byte(input), &v)) - iter = ParseString(ConfigDefault, input+",") - iter.ReadFloat64() - should.NotEqual(io.EOF, iter.Error) - should.NotNil(iter.Error) - iter = ParseString(ConfigDefault, input+",") - iter.ReadFloat32() - should.NotEqual(io.EOF, iter.Error) - should.NotNil(iter.Error) - }) - } -} - -func Test_chan(t *testing.T) { - t.Skip("do not support chan") - - type TestObject struct { - MyChan chan bool - MyField int - } - - should := require.New(t) - obj := TestObject{} - str, err := json.Marshal(obj) - should.Nil(err) - should.Equal(``, str) -} - -func Test_invalid_number(t *testing.T) { - type Message struct { - Number int `json:"number"` - } - obj := Message{} - decoder := ConfigCompatibleWithStandardLibrary.NewDecoder(bytes.NewBufferString(`{"number":"5"}`)) - err := decoder.Decode(&obj) - invalidStr := err.Error() - result, err := ConfigCompatibleWithStandardLibrary.Marshal(invalidStr) - should := require.New(t) - should.Nil(err) - result2, err := json.Marshal(invalidStr) - should.Nil(err) - should.Equal(string(result2), string(result)) -} - -func Test_valid(t *testing.T) { - should := require.New(t) - should.True(Valid([]byte(`{}`))) - should.False(Valid([]byte(`{`))) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_io_test.go b/vendor/github.com/json-iterator/go/jsoniter_io_test.go deleted file mode 100644 index 5046ccc40b..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_io_test.go +++ /dev/null @@ -1,65 +0,0 @@ -package jsoniter - -import ( - "bytes" - "github.com/stretchr/testify/require" - "io" - "testing" -) - -func Test_read_by_one(t *testing.T) { - iter := Parse(ConfigDefault, bytes.NewBufferString("abc"), 1) - b := iter.readByte() - if iter.Error != nil { - t.Fatal(iter.Error) - } - if b != 'a' { - t.Fatal(b) - } - iter.unreadByte() - if iter.Error != nil { - t.Fatal(iter.Error) - } - b = iter.readByte() - if iter.Error != nil { - t.Fatal(iter.Error) - } - if b != 'a' { - t.Fatal(b) - } -} - -func Test_read_by_two(t *testing.T) { - should := require.New(t) - iter := Parse(ConfigDefault, bytes.NewBufferString("abc"), 2) - b := iter.readByte() - should.Nil(iter.Error) - should.Equal(byte('a'), b) - b = iter.readByte() - should.Nil(iter.Error) - should.Equal(byte('b'), b) - iter.unreadByte() - should.Nil(iter.Error) - iter.unreadByte() - should.Nil(iter.Error) - b = iter.readByte() - should.Nil(iter.Error) - should.Equal(byte('a'), b) -} - -func Test_read_until_eof(t *testing.T) { - iter := Parse(ConfigDefault, bytes.NewBufferString("abc"), 2) - iter.readByte() - iter.readByte() - b := iter.readByte() - if iter.Error != nil { - t.Fatal(iter.Error) - } - if b != 'c' { - t.Fatal(b) - } - iter.readByte() - if iter.Error != io.EOF { - t.Fatal(iter.Error) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_iterator_test.go b/vendor/github.com/json-iterator/go/jsoniter_iterator_test.go deleted file mode 100644 index 951574d8db..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_iterator_test.go +++ /dev/null @@ -1,66 +0,0 @@ -package jsoniter - -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_bad_case(t *testing.T) { - // field := *(*string)(unsafe.Pointer(&str)) - // caused this issue - iter := Parse(ConfigDefault, bytes.NewBufferString(`{"Info":{"InfoHash":"4lzhP/fwlVLRgalC31YbfBSiqwo=","InfoHashstr":"E25CE13FF7F09552D181A942DF561B7C14A2AB0A","AnnounceList":["http://tracker.nwps.ws:6969/announce","http://tracker.nwps.ws:6969/announce","http://tracker.winglai.com/announce","http://fr33dom.h33t.com:3310/announce","http://exodus.desync.com:6969/announce","http://torrent.gresille.org/announce","http://tracker.trackerfix.com/announce","udp://tracker.btzoo.eu:80/announce","http://tracker.windsormetalbattery.com/announce","udp://10.rarbg.me:80/announce","udp://ipv4.tracker.harry.lu:80/announce","udp://tracker.ilibr.org:6969/announce","udp://tracker.zond.org:80/announce","http://torrent-tracker.ru/announce.php","http://bigfoot1942.sektori.org:6969/announce","http://tracker.best-torrents.net:6969/announce","http://announce.torrentsmd.com:6969/announce","udp://tracker.token.ro:80/announce","udp://tracker.coppersurfer.tk:80","http://tracker.thepiratebay.org/announce","udp://9.rarbg.com:2710/announce","udp://open.demonii.com:1337/announce","udp://tracker.ccc.de:80/announce","udp://tracker.istole.it:80/announce","udp://tracker.publicbt.com:80/announce","udp://tracker.openbittorrent.com:80/announce","udp://tracker.istole.it:80/announce","http://tracker.istole.it/announce","udp://tracker.publicbt.com:80/announce","http://tracker.publicbt.com/announce","udp://open.demonii.com:1337/announce"],"Length":2434793890,"PieceSize":524288,"PieceNum":4645},"InfoHashstr":"E25CE13FF7F09552D181A942DF561B7C14A2AB0A","SectionNum":32,"PieceNum":4645,"PieceSize":16384,"Finished":false,"SparseSize":104857600,"Bit":[{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},{"Size":4645,"EndIndex":580,"EndMask":248,"Good":0,"Flush":false,"Bit":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}]}`), 4096) - count := 0 - for field := iter.ReadObject(); field != ""; field = iter.ReadObject() { - if field == "Bit" { - for iter.ReadArray() { - for field := iter.ReadObject(); field != ""; field = iter.ReadObject() { - if field == "Bit" { - iter.ReadStringAsSlice() - } else { - if field != "Size" && field != "EndIndex" && field != "EndMask" && field != "Good" && field != "Flush" { - t.Fatal(field) - } - iter.Skip() - } - } - count++ - } - } else { - iter.Skip() - } - } - if count != 32 { - t.Fatal(count) - } -} - -func Test_iterator_use_number(t *testing.T) { - // Test UseNumber with iterator Read() - inputs := []string{`2147483647`, `-2147483648`} - for _, input := range inputs { - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := ParseString(Config{UseNumber: true}.Froze(), input) - expected := json.Number(input) - should.Equal(expected, iter.Read()) - }) - } -} - -func Test_iterator_without_number(t *testing.T) { - inputs := []string{`2147483647`, `-2147483648`} - for _, input := range inputs { - t.Run(fmt.Sprintf("%v", input), func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input) - expected, err := strconv.ParseInt(input, 10, 32) - should.Nil(err) - should.Equal(float64(expected), iter.Read()) - }) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_large_file_test.go b/vendor/github.com/json-iterator/go/jsoniter_large_file_test.go deleted file mode 100644 index 29eb58b165..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_large_file_test.go +++ /dev/null @@ -1,157 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "io/ioutil" - "os" - "testing" -) - -//func Test_large_file(t *testing.T) { -// file, err := os.Open("/tmp/large-file.json") -// if err != nil { -// t.Fatal(err) -// } -// iter := Parse(file, 4096) -// count := 0 -// for iter.ReadArray() { -// iter.Skip() -// count++ -// } -// if count != 11351 { -// t.Fatal(count) -// } -//} - -func init() { - ioutil.WriteFile("/tmp/large-file.json", []byte(`[{ - "person": { - "id": "d50887ca-a6ce-4e59-b89f-14f0b5d03b03", - "name": { - "fullName": "Leonid Bugaev", - "givenName": "Leonid", - "familyName": "Bugaev" - }, - "email": "leonsbox@gmail.com", - "gender": "male", - "location": "Saint Petersburg, Saint Petersburg, RU", - "geo": { - "city": "Saint Petersburg", - "state": "Saint Petersburg", - "country": "Russia", - "lat": 59.9342802, - "lng": 30.3350986 - }, - "bio": "Senior engineer at Granify.com", - "site": "http://flickfaver.com", - "avatar": "https://d1ts43dypk8bqh.cloudfront.net/v1/avatars/d50887ca-a6ce-4e59-b89f-14f0b5d03b03", - "employment": { - "name": "www.latera.ru", - "title": "Software Engineer", - "domain": "gmail.com" - }, - "facebook": { - "handle": "leonid.bugaev" - }, - "github": { - "handle": "buger", - "id": 14009, - "avatar": "https://avatars.githubusercontent.com/u/14009?v=3", - "company": "Granify", - "blog": "http://leonsbox.com", - "followers": 95, - "following": 10 - }, - "twitter": { - "handle": "flickfaver", - "id": 77004410, - "bio": null, - "followers": 2, - "following": 1, - "statuses": 5, - "favorites": 0, - "location": "", - "site": "http://flickfaver.com", - "avatar": null - }, - "linkedin": { - "handle": "in/leonidbugaev" - }, - "googleplus": { - "handle": null - }, - "angellist": { - "handle": "leonid-bugaev", - "id": 61541, - "bio": "Senior engineer at Granify.com", - "blog": "http://buger.github.com", - "site": "http://buger.github.com", - "followers": 41, - "avatar": "https://d1qb2nb5cznatu.cloudfront.net/users/61541-medium_jpg?1405474390" - }, - "klout": { - "handle": null, - "score": null - }, - "foursquare": { - "handle": null - }, - "aboutme": { - "handle": "leonid.bugaev", - "bio": null, - "avatar": null - }, - "gravatar": { - "handle": "buger", - "urls": [ - ], - "avatar": "http://1.gravatar.com/avatar/f7c8edd577d13b8930d5522f28123510", - "avatars": [ - { - "url": "http://1.gravatar.com/avatar/f7c8edd577d13b8930d5522f28123510", - "type": "thumbnail" - } - ] - }, - "fuzzy": false - }, - "company": "hello" -}]`), 0666) -} - -/* -200000 8886 ns/op 4336 B/op 6 allocs/op -50000 34244 ns/op 6744 B/op 14 allocs/op -*/ -func Benchmark_jsoniter_large_file(b *testing.B) { - b.ReportAllocs() - for n := 0; n < b.N; n++ { - file, _ := os.Open("/tmp/large-file.json") - iter := Parse(ConfigDefault, file, 4096) - count := 0 - iter.ReadArrayCB(func(iter *Iterator) bool { - // Skip() is strict by default, use --tags jsoniter-sloppy to skip without validation - iter.Skip() - count++ - return true - }) - file.Close() - if iter.Error != nil { - b.Error(iter.Error) - } - } -} - -func Benchmark_json_large_file(b *testing.B) { - b.ReportAllocs() - for n := 0; n < b.N; n++ { - file, _ := os.Open("/tmp/large-file.json") - bytes, _ := ioutil.ReadAll(file) - file.Close() - result := []struct{}{} - err := json.Unmarshal(bytes, &result) - if err != nil { - b.Error(err) - } - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_map_test.go b/vendor/github.com/json-iterator/go/jsoniter_map_test.go deleted file mode 100644 index 0865428f50..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_map_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "math/big" - "testing" - - "github.com/stretchr/testify/require" - "strings" -) - -func Test_read_map(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `{"hello": "world"}`) - m := map[string]string{"1": "2"} - iter.ReadVal(&m) - copy(iter.buf, []byte{0, 0, 0, 0, 0, 0}) - should.Equal(map[string]string{"1": "2", "hello": "world"}, m) -} - -func Test_read_map_of_interface(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `{"hello": "world"}`) - m := map[string]interface{}{"1": "2"} - iter.ReadVal(&m) - should.Equal(map[string]interface{}{"1": "2", "hello": "world"}, m) - iter = ParseString(ConfigDefault, `{"hello": "world"}`) - should.Equal(map[string]interface{}{"hello": "world"}, iter.Read()) -} - -func Test_map_wrapper_any_get_all(t *testing.T) { - should := require.New(t) - any := Wrap(map[string][]int{"Field1": {1, 2}}) - should.Equal(`{"Field1":1}`, any.Get('*', 0).ToString()) - should.Contains(any.Keys(), "Field1") - - // map write to - stream := NewStream(ConfigDefault, nil, 0) - any.WriteTo(stream) - // TODO cannot pass - //should.Equal(string(stream.buf), "") -} - -func Test_write_val_map(t *testing.T) { - should := require.New(t) - val := map[string]string{"1": "2"} - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`{"1":"2"}`, str) -} - -func Test_slice_of_map(t *testing.T) { - should := require.New(t) - val := []map[string]string{{"1": "2"}} - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`[{"1":"2"}]`, str) - val = []map[string]string{} - should.Nil(UnmarshalFromString(str, &val)) - should.Equal("2", val[0]["1"]) -} - -func Test_encode_int_key_map(t *testing.T) { - should := require.New(t) - val := map[int]string{1: "2"} - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`{"1":"2"}`, str) -} - -func Test_decode_int_key_map(t *testing.T) { - should := require.New(t) - var val map[int]string - should.Nil(UnmarshalFromString(`{"1":"2"}`, &val)) - should.Equal(map[int]string{1: "2"}, val) -} - -func Test_encode_TextMarshaler_key_map(t *testing.T) { - should := require.New(t) - f, _, _ := big.ParseFloat("1", 10, 64, big.ToZero) - val := map[*big.Float]string{f: "2"} - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`{"1":"2"}`, str) -} - -func Test_decode_TextMarshaler_key_map(t *testing.T) { - should := require.New(t) - var val map[*big.Float]string - should.Nil(UnmarshalFromString(`{"1":"2"}`, &val)) - str, err := MarshalToString(val) - should.Nil(err) - should.Equal(`{"1":"2"}`, str) -} - -func Test_map_key_with_escaped_char(t *testing.T) { - type Ttest struct { - Map map[string]string - } - var jsonBytes = []byte(` - { - "Map":{ - "k\"ey": "val" - } - }`) - should := require.New(t) - { - var obj Ttest - should.Nil(json.Unmarshal(jsonBytes, &obj)) - should.Equal(map[string]string{"k\"ey": "val"}, obj.Map) - } - { - var obj Ttest - should.Nil(Unmarshal(jsonBytes, &obj)) - should.Equal(map[string]string{"k\"ey": "val"}, obj.Map) - } -} - -func Test_encode_map_with_sorted_keys(t *testing.T) { - should := require.New(t) - m := map[string]interface{}{ - "3": 3, - "1": 1, - "2": 2, - } - bytes, err := json.Marshal(m) - should.Nil(err) - output, err := ConfigCompatibleWithStandardLibrary.MarshalToString(m) - should.Nil(err) - should.Equal(string(bytes), output) -} - -func Test_encode_map_uint_keys(t *testing.T) { - should := require.New(t) - m := map[uint64]interface{}{ - uint64(1): "a", - uint64(2): "a", - uint64(4): "a", - } - - bytes, err := json.Marshal(m) - should.Nil(err) - - output, err := ConfigCompatibleWithStandardLibrary.MarshalToString(m) - should.Nil(err) - should.Equal(string(bytes), output) -} - -func Test_read_map_with_reader(t *testing.T) { - should := require.New(t) - input := `{"branch":"beta","change_log":"add the rows{10}","channel":"fros","create_time":"2017-06-13 16:39:08","firmware_list":"","md5":"80dee2bf7305bcf179582088e29fd7b9","note":{"CoreServices":{"md5":"d26975c0a8c7369f70ed699f2855cc2e","package_name":"CoreServices","version_code":"76","version_name":"1.0.76"},"FrDaemon":{"md5":"6b1f0626673200bc2157422cd2103f5d","package_name":"FrDaemon","version_code":"390","version_name":"1.0.390"},"FrGallery":{"md5":"90d767f0f31bcd3c1d27281ec979ba65","package_name":"FrGallery","version_code":"349","version_name":"1.0.349"},"FrLocal":{"md5":"f15a215b2c070a80a01f07bde4f219eb","package_name":"FrLocal","version_code":"791","version_name":"1.0.791"}},"pack_region_urls":{"CN":"https://s3.cn-north-1.amazonaws.com.cn/xxx-os/ttt_xxx_android_1.5.3.344.393.zip","default":"http://192.168.8.78/ttt_xxx_android_1.5.3.344.393.zip","local":"http://192.168.8.78/ttt_xxx_android_1.5.3.344.393.zip"},"pack_version":"1.5.3.344.393","pack_version_code":393,"region":"all","release_flag":0,"revision":62,"size":38966875,"status":3}` - reader := strings.NewReader(input) - decoder := ConfigCompatibleWithStandardLibrary.NewDecoder(reader) - m1 := map[string]interface{}{} - should.Nil(decoder.Decode(&m1)) - m2 := map[string]interface{}{} - should.Nil(json.Unmarshal([]byte(input), &m2)) - should.Equal(m2, m1) - should.Equal("1.0.76", m1["note"].(map[string]interface{})["CoreServices"].(map[string]interface{})["version_name"]) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_must_be_valid_test.go b/vendor/github.com/json-iterator/go/jsoniter_must_be_valid_test.go deleted file mode 100644 index 01a91c90fd..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_must_be_valid_test.go +++ /dev/null @@ -1,71 +0,0 @@ -package jsoniter - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -// if must be valid is useless, just drop this test -func Test_must_be_valid(t *testing.T) { - should := require.New(t) - any := Get([]byte("123")) - should.Equal(any.MustBeValid().ToInt(), 123) - - any = Wrap(int8(10)) - should.Equal(any.MustBeValid().ToInt(), 10) - - any = Wrap(int16(10)) - should.Equal(any.MustBeValid().ToInt(), 10) - - any = Wrap(int32(10)) - should.Equal(any.MustBeValid().ToInt(), 10) - - any = Wrap(int64(10)) - should.Equal(any.MustBeValid().ToInt(), 10) - - any = Wrap(uint(10)) - should.Equal(any.MustBeValid().ToInt(), 10) - - any = Wrap(uint8(10)) - should.Equal(any.MustBeValid().ToInt(), 10) - - any = Wrap(uint16(10)) - should.Equal(any.MustBeValid().ToInt(), 10) - - any = Wrap(uint32(10)) - should.Equal(any.MustBeValid().ToInt(), 10) - - any = Wrap(uint64(10)) - should.Equal(any.MustBeValid().ToInt(), 10) - - any = Wrap(float32(10)) - should.Equal(any.MustBeValid().ToFloat64(), float64(10)) - - any = Wrap(float64(10)) - should.Equal(any.MustBeValid().ToFloat64(), float64(10)) - - any = Wrap(true) - should.Equal(any.MustBeValid().ToFloat64(), float64(1)) - - any = Wrap(false) - should.Equal(any.MustBeValid().ToFloat64(), float64(0)) - - any = Wrap(nil) - should.Equal(any.MustBeValid().ToFloat64(), float64(0)) - - any = Wrap(struct{ age int }{age: 1}) - should.Equal(any.MustBeValid().ToFloat64(), float64(0)) - - any = Wrap(map[string]interface{}{"abc": 1}) - should.Equal(any.MustBeValid().ToFloat64(), float64(0)) - - any = Wrap("abc") - should.Equal(any.MustBeValid().ToFloat64(), float64(0)) - - any = Wrap([]int{}) - should.Equal(any.MustBeValid().ToFloat64(), float64(0)) - - any = Wrap([]int{1, 2}) - should.Equal(any.MustBeValid().ToFloat64(), float64(1)) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_nested_test.go b/vendor/github.com/json-iterator/go/jsoniter_nested_test.go deleted file mode 100644 index 29f8cee84c..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_nested_test.go +++ /dev/null @@ -1,88 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "reflect" - "testing" -) - -type Level1 struct { - Hello []Level2 -} - -type Level2 struct { - World string -} - -func Test_nested(t *testing.T) { - iter := ParseString(ConfigDefault, `{"hello": [{"world": "value1"}, {"world": "value2"}]}`) - l1 := Level1{} - for l1Field := iter.ReadObject(); l1Field != ""; l1Field = iter.ReadObject() { - switch l1Field { - case "hello": - l2Array := []Level2{} - for iter.ReadArray() { - l2 := Level2{} - for l2Field := iter.ReadObject(); l2Field != ""; l2Field = iter.ReadObject() { - switch l2Field { - case "world": - l2.World = iter.ReadString() - default: - iter.ReportError("bind l2", "unexpected field: "+l2Field) - } - } - l2Array = append(l2Array, l2) - } - l1.Hello = l2Array - default: - iter.ReportError("bind l1", "unexpected field: "+l1Field) - } - } - if !reflect.DeepEqual(l1, Level1{ - Hello: []Level2{ - {World: "value1"}, - {World: "value2"}, - }, - }) { - t.Fatal(l1) - } -} - -func Benchmark_jsoniter_nested(b *testing.B) { - for n := 0; n < b.N; n++ { - iter := ParseString(ConfigDefault, `{"hello": [{"world": "value1"}, {"world": "value2"}]}`) - l1 := Level1{} - for l1Field := iter.ReadObject(); l1Field != ""; l1Field = iter.ReadObject() { - switch l1Field { - case "hello": - l1.Hello = readLevel1Hello(iter) - default: - iter.Skip() - } - } - } -} - -func readLevel1Hello(iter *Iterator) []Level2 { - l2Array := make([]Level2, 0, 2) - for iter.ReadArray() { - l2 := Level2{} - for l2Field := iter.ReadObject(); l2Field != ""; l2Field = iter.ReadObject() { - switch l2Field { - case "world": - l2.World = iter.ReadString() - default: - iter.Skip() - } - } - l2Array = append(l2Array, l2) - } - return l2Array -} - -func Benchmark_json_nested(b *testing.B) { - for n := 0; n < b.N; n++ { - l1 := Level1{} - json.Unmarshal([]byte(`{"hello": [{"world": "value1"}, {"world": "value2"}]}`), &l1) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_null_test.go b/vendor/github.com/json-iterator/go/jsoniter_null_test.go deleted file mode 100644 index 8c891470f3..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_null_test.go +++ /dev/null @@ -1,168 +0,0 @@ -package jsoniter - -import ( - "bytes" - "encoding/json" - "io" - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_read_null(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `null`) - should.True(iter.ReadNil()) - iter = ParseString(ConfigDefault, `null`) - should.Nil(iter.Read()) - iter = ParseString(ConfigDefault, `navy`) - iter.Read() - should.True(iter.Error != nil && iter.Error != io.EOF) - iter = ParseString(ConfigDefault, `navy`) - iter.ReadNil() - should.True(iter.Error != nil && iter.Error != io.EOF) -} - -func Test_write_null(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteNil() - stream.Flush() - should.Nil(stream.Error) - should.Equal("null", buf.String()) -} - -func Test_encode_null(t *testing.T) { - should := require.New(t) - str, err := MarshalToString(nil) - should.Nil(err) - should.Equal("null", str) -} - -func Test_decode_null_object_field(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `[null,"a"]`) - iter.ReadArray() - if iter.ReadObject() != "" { - t.FailNow() - } - iter.ReadArray() - if iter.ReadString() != "a" { - t.FailNow() - } - type TestObject struct { - Field string - } - objs := []TestObject{} - should.Nil(UnmarshalFromString("[null]", &objs)) - should.Len(objs, 1) -} - -func Test_decode_null_array_element(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `[null,"a"]`) - should.True(iter.ReadArray()) - should.True(iter.ReadNil()) - should.True(iter.ReadArray()) - should.Equal("a", iter.ReadString()) -} - -func Test_decode_null_array(t *testing.T) { - should := require.New(t) - arr := []string{} - should.Nil(UnmarshalFromString("null", &arr)) - should.Nil(arr) -} - -func Test_decode_null_map(t *testing.T) { - should := require.New(t) - arr := map[string]string{} - should.Nil(UnmarshalFromString("null", &arr)) - should.Nil(arr) -} - -func Test_decode_null_string(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `[null,"a"]`) - should.True(iter.ReadArray()) - should.Equal("", iter.ReadString()) - should.True(iter.ReadArray()) - should.Equal("a", iter.ReadString()) -} - -func Test_decode_null_skip(t *testing.T) { - iter := ParseString(ConfigDefault, `[null,"a"]`) - iter.ReadArray() - iter.Skip() - iter.ReadArray() - if iter.ReadString() != "a" { - t.FailNow() - } -} - -func Test_encode_nil_map(t *testing.T) { - should := require.New(t) - type Ttest map[string]string - var obj1 Ttest - output, err := json.Marshal(obj1) - should.Nil(err) - should.Equal("null", string(output)) - output, err = json.Marshal(&obj1) - should.Nil(err) - should.Equal("null", string(output)) - output, err = Marshal(obj1) - should.Nil(err) - should.Equal("null", string(output)) - output, err = Marshal(&obj1) - should.Nil(err) - should.Equal("null", string(output)) -} - -func Test_encode_nil_array(t *testing.T) { - should := require.New(t) - type Ttest []string - var obj1 Ttest - output, err := json.Marshal(obj1) - should.Nil(err) - should.Equal("null", string(output)) - output, err = json.Marshal(&obj1) - should.Nil(err) - should.Equal("null", string(output)) - output, err = Marshal(obj1) - should.Nil(err) - should.Equal("null", string(output)) - output, err = Marshal(&obj1) - should.Nil(err) - should.Equal("null", string(output)) -} - -func Test_decode_nil_num(t *testing.T) { - type TestData struct { - Field int `json:"field"` - } - should := require.New(t) - - data1 := []byte(`{"field": 42}`) - data2 := []byte(`{"field": null}`) - - // Checking stdlib behavior as well - obj2 := TestData{} - err := json.Unmarshal(data1, &obj2) - should.Equal(nil, err) - should.Equal(42, obj2.Field) - - err = json.Unmarshal(data2, &obj2) - should.Equal(nil, err) - should.Equal(42, obj2.Field) - - obj := TestData{} - - err = Unmarshal(data1, &obj) - should.Equal(nil, err) - should.Equal(42, obj.Field) - - err = Unmarshal(data2, &obj) - should.Equal(nil, err) - should.Equal(42, obj.Field) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_object_test.go b/vendor/github.com/json-iterator/go/jsoniter_object_test.go deleted file mode 100644 index d1a9aa06d6..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_object_test.go +++ /dev/null @@ -1,330 +0,0 @@ -package jsoniter - -import ( - "bytes" - "fmt" - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_empty_object(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `{}`) - field := iter.ReadObject() - should.Equal("", field) - iter = ParseString(ConfigDefault, `{}`) - iter.ReadObjectCB(func(iter *Iterator, field string) bool { - should.FailNow("should not call") - return true - }) -} - -func Test_one_field(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `{"a": "stream"}`) - field := iter.ReadObject() - should.Equal("a", field) - value := iter.ReadString() - should.Equal("stream", value) - field = iter.ReadObject() - should.Equal("", field) - iter = ParseString(ConfigDefault, `{"a": "stream"}`) - should.True(iter.ReadObjectCB(func(iter *Iterator, field string) bool { - should.Equal("a", field) - iter.Skip() - return true - })) - -} - -func Test_two_field(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `{ "a": "stream" , "c": "d" }`) - field := iter.ReadObject() - should.Equal("a", field) - value := iter.ReadString() - should.Equal("stream", value) - field = iter.ReadObject() - should.Equal("c", field) - value = iter.ReadString() - should.Equal("d", value) - field = iter.ReadObject() - should.Equal("", field) - iter = ParseString(ConfigDefault, `{"field1": "1", "field2": 2}`) - for field := iter.ReadObject(); field != ""; field = iter.ReadObject() { - switch field { - case "field1": - iter.ReadString() - case "field2": - iter.ReadInt64() - default: - iter.ReportError("bind object", "unexpected field") - } - } -} - -func Test_object_wrapper_any_get_all(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 []int - Field2 []int - } - any := Wrap(TestObject{[]int{1, 2}, []int{3, 4}}) - should.Contains(any.Get('*', 0).ToString(), `"Field2":3`) - should.Contains(any.Keys(), "Field1") - should.Contains(any.Keys(), "Field2") - should.NotContains(any.Keys(), "Field3") - - //should.Contains(any.GetObject()["Field1"].GetArray()[0], 1) -} - -func Test_write_object(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(Config{IndentionStep: 2}.Froze(), buf, 4096) - stream.WriteObjectStart() - stream.WriteObjectField("hello") - stream.WriteInt(1) - stream.WriteMore() - stream.WriteObjectField("world") - stream.WriteInt(2) - stream.WriteObjectEnd() - stream.Flush() - should.Nil(stream.Error) - should.Equal("{\n \"hello\": 1,\n \"world\": 2\n}", buf.String()) -} - -func Test_write_val_zero_field_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - } - obj := TestObject{} - str, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{}`, str) -} - -func Test_write_val_one_field_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string `json:"field-1"` - } - obj := TestObject{"hello"} - str, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{"field-1":"hello"}`, str) -} - -func Test_mixed(t *testing.T) { - should := require.New(t) - type AA struct { - ID int `json:"id"` - Payload map[string]interface{} `json:"payload"` - buf *bytes.Buffer - } - aa := AA{} - err := UnmarshalFromString(` {"id":1, "payload":{"account":"123","password":"456"}}`, &aa) - should.Nil(err) - should.Equal(1, aa.ID) - should.Equal("123", aa.Payload["account"]) -} - -func Test_omit_empty(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string `json:"field-1,omitempty"` - Field2 string `json:"field-2,omitempty"` - Field3 string `json:"field-3,omitempty"` - } - obj := TestObject{} - obj.Field2 = "hello" - str, err := MarshalToString(&obj) - should.Nil(err) - should.Equal(`{"field-2":"hello"}`, str) -} - -func Test_ignore_field_on_not_valid_type(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string `json:"field-1,omitempty"` - Field2 func() `json:"-"` - } - obj := TestObject{} - obj.Field1 = "hello world" - obj.Field2 = func() {} - str, err := MarshalToString(&obj) - should.Nil(err) - should.Equal(`{"field-1":"hello world"}`, str) -} - -func Test_recursive_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Me *TestObject - } - obj := TestObject{} - str, err := MarshalToString(obj) - should.Nil(err) - should.Contains(str, `"Field1":""`) - should.Contains(str, `"Me":null`) - err = UnmarshalFromString(str, &obj) - should.Nil(err) -} - -func Test_encode_anonymous_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field string - } - str, err := MarshalToString(struct { - TestObject - Field int - }{ - Field: 100, - }) - should.Nil(err) - should.Equal(`{"Field":100}`, str) -} - -func Test_decode_anonymous_struct(t *testing.T) { - should := require.New(t) - type Inner struct { - Key string `json:"key"` - } - - type Outer struct { - Inner - } - var outer Outer - j := []byte("{\"key\":\"value\"}") - should.Nil(Unmarshal(j, &outer)) - should.Equal("value", outer.Key) -} - -func Test_multiple_level_anonymous_struct(t *testing.T) { - type Level1 struct { - Field1 string - } - type Level2 struct { - Level1 - Field2 string - } - type Level3 struct { - Level2 - Field3 string - } - should := require.New(t) - obj := Level3{Level2{Level1{"1"}, "2"}, "3"} - output, err := MarshalToString(obj) - should.Nil(err) - should.Equal(`{"Field1":"1","Field2":"2","Field3":"3"}`, output) -} - -func Test_multiple_level_anonymous_struct_with_ptr(t *testing.T) { - type Level1 struct { - Field1 string - Field2 string - Field4 string - } - type Level2 struct { - *Level1 - Field2 string - Field3 string - } - type Level3 struct { - *Level2 - Field3 string - } - should := require.New(t) - obj := Level3{&Level2{&Level1{"1", "", "4"}, "2", ""}, "3"} - output, err := MarshalToString(obj) - should.Nil(err) - should.Contains(output, `"Field1":"1"`) - should.Contains(output, `"Field2":"2"`) - should.Contains(output, `"Field3":"3"`) - should.Contains(output, `"Field4":"4"`) -} - -func Test_shadow_struct_field(t *testing.T) { - should := require.New(t) - type omit *struct{} - type CacheItem struct { - Key string `json:"key"` - MaxAge int `json:"cacheAge"` - } - output, err := MarshalToString(struct { - *CacheItem - - // Omit bad keys - OmitMaxAge omit `json:"cacheAge,omitempty"` - - // Add nice keys - MaxAge int `json:"max_age"` - }{ - CacheItem: &CacheItem{ - Key: "value", - MaxAge: 100, - }, - MaxAge: 20, - }) - should.Nil(err) - should.Contains(output, `"key":"value"`) - should.Contains(output, `"max_age":20`) -} - -func Test_embedded_order(t *testing.T) { - type A struct { - Field2 string - } - - type C struct { - Field5 string - } - - type B struct { - Field4 string - C - Field6 string - } - - type TestObject struct { - Field1 string - A - Field3 string - B - Field7 string - } - should := require.New(t) - s := TestObject{} - output, err := MarshalToString(s) - should.Nil(err) - should.Equal(`{"Field1":"","Field2":"","Field3":"","Field4":"","Field5":"","Field6":"","Field7":""}`, output) -} - -func Test_decode_nested(t *testing.T) { - type StructOfString struct { - Field1 string - Field2 string - } - iter := ParseString(ConfigDefault, `[{"field1": "hello"}, null, {"field2": "world"}]`) - slice := []*StructOfString{} - iter.ReadVal(&slice) - if len(slice) != 3 { - fmt.Println(iter.Error) - t.Fatal(len(slice)) - } - if slice[0].Field1 != "hello" { - fmt.Println(iter.Error) - t.Fatal(slice[0]) - } - if slice[1] != nil { - fmt.Println(iter.Error) - t.Fatal(slice[1]) - } - if slice[2].Field2 != "world" { - fmt.Println(iter.Error) - t.Fatal(slice[2]) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_optional_test.go b/vendor/github.com/json-iterator/go/jsoniter_optional_test.go deleted file mode 100644 index 82b789b50c..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_optional_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package jsoniter - -import ( - "github.com/stretchr/testify/require" - "testing" -) - -func Test_encode_optional_int_pointer(t *testing.T) { - should := require.New(t) - var ptr *int - str, err := MarshalToString(ptr) - should.Nil(err) - should.Equal("null", str) - val := 100 - ptr = &val - str, err = MarshalToString(ptr) - should.Nil(err) - should.Equal("100", str) -} - -func Test_decode_struct_with_optional_field(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 *string - Field2 *string - } - obj := TestObject{} - UnmarshalFromString(`{"field1": null, "field2": "world"}`, &obj) - should.Nil(obj.Field1) - should.Equal("world", *obj.Field2) -} - -func Test_encode_struct_with_optional_field(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 *string - Field2 *string - } - obj := TestObject{} - world := "world" - obj.Field2 = &world - str, err := MarshalToString(obj) - should.Nil(err) - should.Contains(str, `"Field1":null`) - should.Contains(str, `"Field2":"world"`) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_raw_message_test.go b/vendor/github.com/json-iterator/go/jsoniter_raw_message_test.go deleted file mode 100644 index 4fba33f89e..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_raw_message_test.go +++ /dev/null @@ -1,114 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "github.com/stretchr/testify/require" - "strings" - "testing" -) - -func Test_json_RawMessage(t *testing.T) { - should := require.New(t) - var data json.RawMessage - should.Nil(Unmarshal([]byte(`[1,2,3]`), &data)) - should.Equal(`[1,2,3]`, string(data)) - str, err := MarshalToString(data) - should.Nil(err) - should.Equal(`[1,2,3]`, str) -} - -func Test_jsoniter_RawMessage(t *testing.T) { - should := require.New(t) - var data RawMessage - should.Nil(Unmarshal([]byte(`[1,2,3]`), &data)) - should.Equal(`[1,2,3]`, string(data)) - str, err := MarshalToString(data) - should.Nil(err) - should.Equal(`[1,2,3]`, str) -} - -func Test_json_RawMessage_in_struct(t *testing.T) { - type TestObject struct { - Field1 string - Field2 json.RawMessage - } - should := require.New(t) - var data TestObject - should.Nil(Unmarshal([]byte(`{"field1": "hello", "field2": [1,2,3]}`), &data)) - should.Equal(` [1,2,3]`, string(data.Field2)) - should.Equal(`hello`, data.Field1) -} - -func Test_decode_map_of_raw_message(t *testing.T) { - should := require.New(t) - type RawMap map[string]*json.RawMessage - b := []byte("{\"test\":[{\"key\":\"value\"}]}") - var rawMap RawMap - should.Nil(Unmarshal(b, &rawMap)) - should.Equal(`[{"key":"value"}]`, string(*rawMap["test"])) - type Inner struct { - Key string `json:"key"` - } - var inner []Inner - Unmarshal(*rawMap["test"], &inner) - should.Equal("value", inner[0].Key) -} - -func Test_encode_map_of_raw_message(t *testing.T) { - should := require.New(t) - type RawMap map[string]*json.RawMessage - value := json.RawMessage("[]") - rawMap := RawMap{"hello": &value} - output, err := MarshalToString(rawMap) - should.Nil(err) - should.Equal(`{"hello":[]}`, output) -} - -func Test_encode_map_of_jsoniter_raw_message(t *testing.T) { - should := require.New(t) - type RawMap map[string]*RawMessage - value := RawMessage("[]") - rawMap := RawMap{"hello": &value} - output, err := MarshalToString(rawMap) - should.Nil(err) - should.Equal(`{"hello":[]}`, output) -} - -func Test_marshal_invalid_json_raw_message(t *testing.T) { - type A struct { - Raw json.RawMessage `json:"raw"` - } - message := []byte(`{}`) - - a := A{} - should := require.New(t) - should.Nil(ConfigCompatibleWithStandardLibrary.Unmarshal(message, &a)) - aout, aouterr := ConfigCompatibleWithStandardLibrary.Marshal(&a) - should.Equal(`{"raw":null}`, string(aout)) - should.Nil(aouterr) -} - -func Test_raw_message_memory_not_copied_issue(t *testing.T) { - jsonStream := `{"name":"xxxxx","bundle_id":"com.zonst.majiang","app_platform":"ios","app_category":"100103", "budget_day":1000,"bidding_min":1,"bidding_max":2,"bidding_type":"CPM", "freq":{"open":true,"type":"day","num":100},"speed":1, "targeting":{"vendor":{"open":true,"list":["zonst"]}, "geo_code":{"open":true,"list":["156110100"]},"app_category":{"open":true,"list":["100101"]}, "day_parting":{"open":true,"list":["100409","100410"]},"device_type":{"open":true,"list":["ipad"]}, "os_version":{"open":true,"list":[10]},"carrier":{"open":true,"list":["mobile"]}, "network":{"open":true,"list":["4G"]}},"url":{"tracking_imp_url":"http://www.baidu.com", "tracking_clk_url":"http://www.baidu.com","jump_url":"http://www.baidu.com","deep_link_url":"http://www.baidu.com"}}` - type IteratorObject struct { - Name *string `json:"name"` - BundleId *string `json:"bundle_id"` - AppCategory *string `json:"app_category"` - AppPlatform *string `json:"app_platform"` - BudgetDay *float32 `json:"budget_day"` - BiddingMax *float32 `json:"bidding_max"` - BiddingMin *float32 `json:"bidding_min"` - BiddingType *string `json:"bidding_type"` - Freq *RawMessage `json:"freq"` - Targeting *RawMessage `json:"targeting"` - Url *RawMessage `json:"url"` - Speed *int `json:"speed" db:"speed"` - } - - obj := &IteratorObject{} - decoder := NewDecoder(strings.NewReader(jsonStream)) - err := decoder.Decode(obj) - should := require.New(t) - should.Nil(err) - should.Equal(`{"open":true,"type":"day","num":100}`, string(*obj.Freq)) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_reader_test.go b/vendor/github.com/json-iterator/go/jsoniter_reader_test.go deleted file mode 100644 index b3b3588e13..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_reader_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package jsoniter - -import ( - "github.com/stretchr/testify/require" - "strings" - "testing" - "time" -) - -func Test_reader_and_load_more(t *testing.T) { - should := require.New(t) - type TestObject struct { - CreatedAt time.Time - } - reader := strings.NewReader(` -{ - "agency": null, - "candidateId": 0, - "candidate": "Blah Blah", - "bookingId": 0, - "shiftId": 1, - "shiftTypeId": 0, - "shift": "Standard", - "bonus": 0, - "bonusNI": 0, - "days": [], - "totalHours": 27, - "expenses": [], - "weekEndingDateSystem": "2016-10-09", - "weekEndingDateClient": "2016-10-09", - "submittedAt": null, - "submittedById": null, - "approvedAt": "2016-10-10T18:38:04Z", - "approvedById": 0, - "authorisedAt": "2016-10-10T18:38:04Z", - "authorisedById": 0, - "invoicedAt": "2016-10-10T20:00:00Z", - "revokedAt": null, - "revokedById": null, - "revokeReason": null, - "rejectedAt": null, - "rejectedById": null, - "rejectReasonCode": null, - "rejectReason": null, - "createdAt": "2016-10-03T00:00:00Z", - "updatedAt": "2016-11-09T10:26:13Z", - "updatedById": null, - "overrides": [], - "bookingApproverId": null, - "bookingApprover": null, - "status": "approved" -} - `) - decoder := ConfigCompatibleWithStandardLibrary.NewDecoder(reader) - obj := TestObject{} - should.Nil(decoder.Decode(&obj)) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_reflect_native_test.go b/vendor/github.com/json-iterator/go/jsoniter_reflect_native_test.go deleted file mode 100644 index 0e2d68bba7..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_reflect_native_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package jsoniter - -import ( - "fmt" - "testing" -) - -func Test_reflect_str(t *testing.T) { - iter := ParseString(ConfigDefault, `"hello"`) - str := "" - iter.ReadVal(&str) - if str != "hello" { - fmt.Println(iter.Error) - t.Fatal(str) - } -} - -func Test_reflect_ptr_str(t *testing.T) { - iter := ParseString(ConfigDefault, `"hello"`) - var str *string - iter.ReadVal(&str) - if *str != "hello" { - t.Fatal(str) - } -} - -func Test_reflect_int(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := int(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_int8(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := int8(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_int16(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := int16(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_int32(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := int32(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_int64(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := int64(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_uint(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := uint(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_uint8(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := uint8(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_uint16(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := uint16(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_uint32(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := uint32(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_uint64(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := uint64(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_byte(t *testing.T) { - iter := ParseString(ConfigDefault, `123`) - val := byte(0) - iter.ReadVal(&val) - if val != 123 { - t.Fatal(val) - } -} - -func Test_reflect_float32(t *testing.T) { - iter := ParseString(ConfigDefault, `1.23`) - val := float32(0) - iter.ReadVal(&val) - if val != 1.23 { - fmt.Println(iter.Error) - t.Fatal(val) - } -} - -func Test_reflect_float64(t *testing.T) { - iter := ParseString(ConfigDefault, `1.23`) - val := float64(0) - iter.ReadVal(&val) - if val != 1.23 { - fmt.Println(iter.Error) - t.Fatal(val) - } -} - -func Test_reflect_bool(t *testing.T) { - iter := ParseString(ConfigDefault, `true`) - val := false - iter.ReadVal(&val) - if val != true { - fmt.Println(iter.Error) - t.Fatal(val) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_skip_test.go b/vendor/github.com/json-iterator/go/jsoniter_skip_test.go deleted file mode 100644 index 524fd5da2c..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_skip_test.go +++ /dev/null @@ -1,179 +0,0 @@ -package jsoniter - -import ( - "bytes" - "encoding/json" - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_skip_number_in_array(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `[-0.12, "stream"]`) - iter.ReadArray() - iter.Skip() - iter.ReadArray() - should.Nil(iter.Error) - should.Equal("stream", iter.ReadString()) -} - -func Test_skip_string_in_array(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `["hello", "stream"]`) - iter.ReadArray() - iter.Skip() - iter.ReadArray() - should.Nil(iter.Error) - should.Equal("stream", iter.ReadString()) -} - -func Test_skip_null(t *testing.T) { - iter := ParseString(ConfigDefault, `[null , "stream"]`) - iter.ReadArray() - iter.Skip() - iter.ReadArray() - if iter.ReadString() != "stream" { - t.FailNow() - } -} - -func Test_skip_true(t *testing.T) { - iter := ParseString(ConfigDefault, `[true , "stream"]`) - iter.ReadArray() - iter.Skip() - iter.ReadArray() - if iter.ReadString() != "stream" { - t.FailNow() - } -} - -func Test_skip_false(t *testing.T) { - iter := ParseString(ConfigDefault, `[false , "stream"]`) - iter.ReadArray() - iter.Skip() - iter.ReadArray() - if iter.ReadString() != "stream" { - t.FailNow() - } -} - -func Test_skip_array(t *testing.T) { - iter := ParseString(ConfigDefault, `[[1, [2, [3], 4]], "stream"]`) - iter.ReadArray() - iter.Skip() - iter.ReadArray() - if iter.ReadString() != "stream" { - t.FailNow() - } -} - -func Test_skip_empty_array(t *testing.T) { - iter := ParseString(ConfigDefault, `[ [ ], "stream"]`) - iter.ReadArray() - iter.Skip() - iter.ReadArray() - if iter.ReadString() != "stream" { - t.FailNow() - } -} - -func Test_skip_nested(t *testing.T) { - iter := ParseString(ConfigDefault, `[ {"a" : [{"stream": "c"}], "d": 102 }, "stream"]`) - iter.ReadArray() - iter.Skip() - iter.ReadArray() - if iter.ReadString() != "stream" { - t.FailNow() - } -} - -func Test_skip_and_return_bytes(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `[ {"a" : [{"stream": "c"}], "d": 102 }, "stream"]`) - iter.ReadArray() - skipped := iter.SkipAndReturnBytes() - should.Equal(`{"a" : [{"stream": "c"}], "d": 102 }`, string(skipped)) -} - -func Test_skip_and_return_bytes_with_reader(t *testing.T) { - should := require.New(t) - iter := Parse(ConfigDefault, bytes.NewBufferString(`[ {"a" : [{"stream": "c"}], "d": 102 }, "stream"]`), 4) - iter.ReadArray() - skipped := iter.SkipAndReturnBytes() - should.Equal(`{"a" : [{"stream": "c"}], "d": 102 }`, string(skipped)) -} - -type TestResp struct { - Code uint64 -} - -func Benchmark_jsoniter_skip(b *testing.B) { - input := []byte(` -{ - "_shards":{ - "total" : 5, - "successful" : 5, - "failed" : 0 - }, - "hits":{ - "total" : 1, - "hits" : [ - { - "_index" : "twitter", - "_type" : "tweet", - "_id" : "1", - "_source" : { - "user" : "kimchy", - "postDate" : "2009-11-15T14:12:12", - "message" : "trying out Elasticsearch" - } - } - ] - }, - "code": 200 -}`) - for n := 0; n < b.N; n++ { - result := TestResp{} - iter := ParseBytes(ConfigDefault, input) - for field := iter.ReadObject(); field != ""; field = iter.ReadObject() { - switch field { - case "code": - result.Code = iter.ReadUint64() - default: - iter.Skip() - } - } - } -} - -func Benchmark_json_skip(b *testing.B) { - input := []byte(` -{ - "_shards":{ - "total" : 5, - "successful" : 5, - "failed" : 0 - }, - "hits":{ - "total" : 1, - "hits" : [ - { - "_index" : "twitter", - "_type" : "tweet", - "_id" : "1", - "_source" : { - "user" : "kimchy", - "postDate" : "2009-11-15T14:12:12", - "message" : "trying out Elasticsearch" - } - } - ] - }, - "code": 200 -}`) - for n := 0; n < b.N; n++ { - result := TestResp{} - json.Unmarshal(input, &result) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_sloppy_test.go b/vendor/github.com/json-iterator/go/jsoniter_sloppy_test.go deleted file mode 100644 index 487713ae7f..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_sloppy_test.go +++ /dev/null @@ -1,162 +0,0 @@ -//+build jsoniter-sloppy - -package jsoniter - -import ( - "github.com/stretchr/testify/require" - "io" - "testing" -) - -func Test_string_end(t *testing.T) { - end, escaped := ParseString(ConfigDefault, `abc"`).findStringEnd() - if end != 4 { - t.Fatal(end) - } - if escaped != false { - t.Fatal(escaped) - } - end, escaped = ParseString(ConfigDefault, `abc\\"`).findStringEnd() - if end != 6 { - t.Fatal(end) - } - if escaped != true { - t.Fatal(escaped) - } - end, escaped = ParseString(ConfigDefault, `abc\\\\"`).findStringEnd() - if end != 8 { - t.Fatal(end) - } - if escaped != true { - t.Fatal(escaped) - } - end, escaped = ParseString(ConfigDefault, `abc\"`).findStringEnd() - if end != -1 { - t.Fatal(end) - } - if escaped != false { - t.Fatal(escaped) - } - end, escaped = ParseString(ConfigDefault, `abc\`).findStringEnd() - if end != -1 { - t.Fatal(end) - } - if escaped != true { - t.Fatal(escaped) - } - end, escaped = ParseString(ConfigDefault, `abc\\`).findStringEnd() - if end != -1 { - t.Fatal(end) - } - if escaped != false { - t.Fatal(escaped) - } - end, escaped = ParseString(ConfigDefault, `\\`).findStringEnd() - if end != -1 { - t.Fatal(end) - } - if escaped != false { - t.Fatal(escaped) - } - end, escaped = ParseString(ConfigDefault, `\`).findStringEnd() - if end != -1 { - t.Fatal(end) - } - if escaped != true { - t.Fatal(escaped) - } -} - -type StagedReader struct { - r1 string - r2 string - r3 string - r int -} - -func (reader *StagedReader) Read(p []byte) (n int, err error) { - reader.r++ - switch reader.r { - case 1: - copy(p, []byte(reader.r1)) - return len(reader.r1), nil - case 2: - copy(p, []byte(reader.r2)) - return len(reader.r2), nil - case 3: - copy(p, []byte(reader.r3)) - return len(reader.r3), nil - default: - return 0, io.EOF - } -} - -func Test_skip_string(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `"abc`) - iter.skipString() - should.Equal(1, iter.head) - iter = ParseString(ConfigDefault, `\""abc`) - iter.skipString() - should.Equal(3, iter.head) - reader := &StagedReader{ - r1: `abc`, - r2: `"`, - } - iter = Parse(ConfigDefault, reader, 4096) - iter.skipString() - should.Equal(1, iter.head) - reader = &StagedReader{ - r1: `abc`, - r2: `1"`, - } - iter = Parse(ConfigDefault, reader, 4096) - iter.skipString() - should.Equal(2, iter.head) - reader = &StagedReader{ - r1: `abc\`, - r2: `"`, - } - iter = Parse(ConfigDefault, reader, 4096) - iter.skipString() - should.NotNil(iter.Error) - reader = &StagedReader{ - r1: `abc\`, - r2: `""`, - } - iter = Parse(ConfigDefault, reader, 4096) - iter.skipString() - should.Equal(2, iter.head) -} - -func Test_skip_object(t *testing.T) { - iter := ParseString(ConfigDefault, `}`) - iter.skipObject() - if iter.head != 1 { - t.Fatal(iter.head) - } - iter = ParseString(ConfigDefault, `a}`) - iter.skipObject() - if iter.head != 2 { - t.Fatal(iter.head) - } - iter = ParseString(ConfigDefault, `{}}a`) - iter.skipObject() - if iter.head != 3 { - t.Fatal(iter.head) - } - reader := &StagedReader{ - r1: `{`, - r2: `}}a`, - } - iter = Parse(ConfigDefault, reader, 4096) - iter.skipObject() - if iter.head != 2 { - t.Fatal(iter.head) - } - iter = ParseString(ConfigDefault, `"}"}a`) - iter.skipObject() - if iter.head != 4 { - t.Fatal(iter.head) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_stream_test.go b/vendor/github.com/json-iterator/go/jsoniter_stream_test.go deleted file mode 100644 index 8df96b9f33..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_stream_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package jsoniter - -import ( - "github.com/stretchr/testify/require" - "testing" -) - -func Test_writeByte_should_grow_buffer(t *testing.T) { - should := require.New(t) - stream := NewStream(ConfigDefault, nil, 1) - stream.writeByte('1') - should.Equal("1", string(stream.Buffer())) - should.Equal(1, len(stream.buf)) - stream.writeByte('2') - should.Equal("12", string(stream.Buffer())) - should.Equal(2, len(stream.buf)) - stream.writeThreeBytes('3', '4', '5') - should.Equal("12345", string(stream.Buffer())) -} - -func Test_writeBytes_should_grow_buffer(t *testing.T) { - should := require.New(t) - stream := NewStream(ConfigDefault, nil, 1) - stream.Write([]byte{'1', '2'}) - should.Equal("12", string(stream.Buffer())) - should.Equal(3, len(stream.buf)) - stream.Write([]byte{'3', '4', '5', '6', '7'}) - should.Equal("1234567", string(stream.Buffer())) - should.Equal(8, len(stream.buf)) -} - -func Test_writeIndention_should_grow_buffer(t *testing.T) { - should := require.New(t) - stream := NewStream(Config{IndentionStep: 2}.Froze(), nil, 1) - stream.WriteVal([]int{1, 2, 3}) - should.Equal("[\n 1,\n 2,\n 3\n]", string(stream.Buffer())) -} - -func Test_writeRaw_should_grow_buffer(t *testing.T) { - should := require.New(t) - stream := NewStream(ConfigDefault, nil, 1) - stream.WriteRaw("123") - should.Nil(stream.Error) - should.Equal("123", string(stream.Buffer())) -} - -func Test_writeString_should_grow_buffer(t *testing.T) { - should := require.New(t) - stream := NewStream(ConfigDefault, nil, 0) - stream.WriteString("123") - should.Nil(stream.Error) - should.Equal(`"123"`, string(stream.Buffer())) -} - -type NopWriter struct { - bufferSize int -} - -func (w *NopWriter) Write(p []byte) (n int, err error) { - w.bufferSize = cap(p) - return len(p), nil -} - -func Test_flush_buffer_should_stop_grow_buffer(t *testing.T) { - writer := new(NopWriter) - NewEncoder(writer).Encode(make([]int, 10000000)) - should := require.New(t) - should.Equal(512, writer.bufferSize) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_string_test.go b/vendor/github.com/json-iterator/go/jsoniter_string_test.go deleted file mode 100644 index 61c0f33b3f..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_string_test.go +++ /dev/null @@ -1,261 +0,0 @@ -// +build go1.8 - -package jsoniter - -import ( - "bytes" - "encoding/json" - "fmt" - "testing" - "unicode/utf8" - - "github.com/stretchr/testify/require" -) - -func Test_read_string(t *testing.T) { - badInputs := []string{ - ``, - `"`, - `"\"`, - `"\\\"`, - "\"\n\"", - `"\U0001f64f"`, - `"\uD83D\u00"`, - } - for i := 0; i < 32; i++ { - // control characters are invalid - badInputs = append(badInputs, string([]byte{'"', byte(i), '"'})) - } - - for _, input := range badInputs { - testReadString(t, input, "", true, "json.Unmarshal", json.Unmarshal) - testReadString(t, input, "", true, "jsoniter.Unmarshal", Unmarshal) - testReadString(t, input, "", true, "jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal", ConfigCompatibleWithStandardLibrary.Unmarshal) - } - - goodInputs := []struct { - input string - expectValue string - }{ - {`""`, ""}, - {`"a"`, "a"}, - {`null`, ""}, - {`"Iñtërnâtiônàlizætiøn,💝🐹🌇⛔"`, "Iñtërnâtiônàlizætiøn,💝🐹🌇⛔"}, - {`"\uD83D"`, string([]byte{239, 191, 189})}, - {`"\uD83D\\"`, string([]byte{239, 191, 189, '\\'})}, - {`"\uD83D\ub000"`, string([]byte{239, 191, 189, 235, 128, 128})}, - {`"\uD83D\ude04"`, "😄"}, - {`"\uDEADBEEF"`, string([]byte{239, 191, 189, 66, 69, 69, 70})}, - } - - for _, tc := range goodInputs { - testReadString(t, tc.input, tc.expectValue, false, "json.Unmarshal", json.Unmarshal) - testReadString(t, tc.input, tc.expectValue, false, "jsoniter.Unmarshal", Unmarshal) - testReadString(t, tc.input, tc.expectValue, false, "jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal", ConfigCompatibleWithStandardLibrary.Unmarshal) - } -} - -func testReadString(t *testing.T, input string, expectValue string, expectError bool, marshalerName string, marshaler func([]byte, interface{}) error) { - var value string - err := marshaler([]byte(input), &value) - if expectError != (err != nil) { - t.Errorf("%q: %s: expected error %v, got %v", input, marshalerName, expectError, err) - return - } - if value != expectValue { - t.Errorf("%q: %s: expected %q, got %q", input, marshalerName, expectValue, value) - return - } -} - -func Test_read_normal_string(t *testing.T) { - cases := map[string]string{ - `"0123456789012345678901234567890123456789"`: `0123456789012345678901234567890123456789`, - `""`: ``, - `"hello"`: `hello`, - } - for input, output := range cases { - t.Run(fmt.Sprintf("%v:%v", input, output), func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input) - should.Equal(output, iter.ReadString()) - }) - t.Run(fmt.Sprintf("%v:%v", input, output), func(t *testing.T) { - should := require.New(t) - iter := Parse(ConfigDefault, bytes.NewBufferString(input), 2) - should.Equal(output, iter.ReadString()) - }) - t.Run(fmt.Sprintf("%v:%v", input, output), func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input) - should.Equal(output, string(iter.ReadStringAsSlice())) - }) - t.Run(fmt.Sprintf("%v:%v", input, output), func(t *testing.T) { - should := require.New(t) - iter := Parse(ConfigDefault, bytes.NewBufferString(input), 2) - should.Equal(output, string(iter.ReadStringAsSlice())) - }) - } -} - -func Test_read_exotic_string(t *testing.T) { - cases := map[string]string{ - `"hel\"lo"`: `hel"lo`, - `"hel\\\/lo"`: `hel\/lo`, - `"hel\\blo"`: `hel\blo`, - `"hel\\\blo"`: "hel\\\blo", - `"hel\\nlo"`: `hel\nlo`, - `"hel\\\nlo"`: "hel\\\nlo", - `"hel\\tlo"`: `hel\tlo`, - `"hel\\flo"`: `hel\flo`, - `"hel\\\flo"`: "hel\\\flo", - `"hel\\\rlo"`: "hel\\\rlo", - `"hel\\\tlo"`: "hel\\\tlo", - `"\u4e2d\u6587"`: "中文", - `"\ud83d\udc4a"`: "\xf0\x9f\x91\x8a", // surrogate - } - for input, output := range cases { - t.Run(fmt.Sprintf("%v:%v", input, output), func(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, input) - var v string - should.Nil(json.Unmarshal([]byte(input), &v)) - should.Equal(v, iter.ReadString()) - }) - t.Run(fmt.Sprintf("%v:%v", input, output), func(t *testing.T) { - should := require.New(t) - iter := Parse(ConfigDefault, bytes.NewBufferString(input), 2) - should.Equal(output, iter.ReadString()) - }) - } -} - -func Test_read_string_as_interface(t *testing.T) { - should := require.New(t) - iter := ParseString(ConfigDefault, `"hello"`) - should.Equal("hello", iter.Read()) -} - -func Test_write_string(t *testing.T) { - should := require.New(t) - str, err := MarshalToString("hello") - should.Equal(`"hello"`, str) - should.Nil(err) - str, err = MarshalToString(`hel"lo`) - should.Equal(`"hel\"lo"`, str) - should.Nil(err) -} - -func Test_write_val_string(t *testing.T) { - should := require.New(t) - buf := &bytes.Buffer{} - stream := NewStream(ConfigDefault, buf, 4096) - stream.WriteVal("hello") - stream.Flush() - should.Nil(stream.Error) - should.Equal(`"hello"`, buf.String()) -} - -func Test_decode_slash(t *testing.T) { - should := require.New(t) - var obj interface{} - should.NotNil(json.Unmarshal([]byte("\\"), &obj)) - should.NotNil(UnmarshalFromString("\\", &obj)) -} - -func Test_html_escape(t *testing.T) { - should := require.New(t) - output, err := json.Marshal(`>`) - should.Nil(err) - should.Equal(`"\u003e"`, string(output)) - output, err = ConfigCompatibleWithStandardLibrary.Marshal(`>`) - should.Nil(err) - should.Equal(`"\u003e"`, string(output)) - type MyString string - output, err = ConfigCompatibleWithStandardLibrary.Marshal(MyString(`>`)) - should.Nil(err) - should.Equal(`"\u003e"`, string(output)) -} - -func Test_string_encode_with_std(t *testing.T) { - should := require.New(t) - for i := 0; i < utf8.RuneSelf; i++ { - input := string([]byte{byte(i)}) - stdOutputBytes, err := json.Marshal(input) - should.Nil(err) - stdOutput := string(stdOutputBytes) - jsoniterOutputBytes, err := ConfigCompatibleWithStandardLibrary.Marshal(input) - should.Nil(err) - jsoniterOutput := string(jsoniterOutputBytes) - should.Equal(stdOutput, jsoniterOutput) - } -} - -func Test_unicode(t *testing.T) { - should := require.New(t) - output, _ := MarshalToString(map[string]interface{}{"a": "数字山谷"}) - should.Equal(`{"a":"数字山谷"}`, output) - output, _ = Config{EscapeHTML: false}.Froze().MarshalToString(map[string]interface{}{"a": "数字山谷"}) - should.Equal(`{"a":"数字山谷"}`, output) -} - -func Test_unicode_and_escape(t *testing.T) { - should := require.New(t) - output, err := MarshalToString(`"数字山谷"`) - should.Nil(err) - should.Equal(`"\"数字山谷\""`, output) - output, err = ConfigFastest.MarshalToString(`"数字山谷"`) - should.Nil(err) - should.Equal(`"\"数字山谷\""`, output) -} - -func Test_unsafe_unicode(t *testing.T) { - ConfigDefault.(*frozenConfig).cleanEncoders() - should := require.New(t) - output, err := ConfigDefault.MarshalToString("he\u2029\u2028he") - should.Nil(err) - should.Equal(`"he\u2029\u2028he"`, output) - output, err = ConfigFastest.MarshalToString("he\u2029\u2028he") - should.Nil(err) - should.Equal("\"he\u2029\u2028he\"", output) -} - -func Benchmark_jsoniter_unicode(b *testing.B) { - for n := 0; n < b.N; n++ { - iter := ParseString(ConfigDefault, `"\ud83d\udc4a"`) - iter.ReadString() - } -} - -func Benchmark_jsoniter_ascii(b *testing.B) { - iter := NewIterator(ConfigDefault) - input := []byte(`"hello, world! hello, world!"`) - b.ResetTimer() - for n := 0; n < b.N; n++ { - iter.ResetBytes(input) - iter.ReadString() - } -} - -func Benchmark_jsoniter_string_as_bytes(b *testing.B) { - iter := ParseString(ConfigDefault, `"hello, world!"`) - b.ResetTimer() - for n := 0; n < b.N; n++ { - iter.ResetBytes(iter.buf) - iter.ReadStringAsSlice() - } -} - -func Benchmark_json_unicode(b *testing.B) { - for n := 0; n < b.N; n++ { - result := "" - json.Unmarshal([]byte(`"\ud83d\udc4a"`), &result) - } -} - -func Benchmark_json_ascii(b *testing.B) { - for n := 0; n < b.N; n++ { - result := "" - json.Unmarshal([]byte(`"hello"`), &result) - } -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_struct_decoder_test.go b/vendor/github.com/json-iterator/go/jsoniter_struct_decoder_test.go deleted file mode 100644 index 257bbdb657..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_struct_decoder_test.go +++ /dev/null @@ -1,267 +0,0 @@ -package jsoniter - -import ( - "github.com/stretchr/testify/require" - "testing" -) - -func Test_decode_one_field_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"field1": "hello"}`, &obj)) - should.Equal("hello", obj.Field1) -} - -func Test_decode_two_fields_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Field2 string - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream"}`, &obj)) - should.Equal("a", obj.Field1) - should.Equal("stream", obj.Field2) -} - -func Test_decode_three_fields_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Field2 string - Field3 string - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c"}`, &obj)) - should.Equal("a", obj.Field1) - should.Equal("stream", obj.Field2) - should.Equal("c", obj.Field3) -} - -func Test_decode_four_fields_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Field2 string - Field3 string - Field4 string - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d"}`, &obj)) - should.Equal("a", obj.Field1) - should.Equal("stream", obj.Field2) - should.Equal("c", obj.Field3) - should.Equal("d", obj.Field4) -} - -func Test_decode_five_fields_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Field2 string - Field3 string - Field4 string - Field5 string - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj)) - should.Equal("a", obj.Field1) - should.Equal("stream", obj.Field2) - should.Equal("c", obj.Field3) - should.Equal("d", obj.Field4) - should.Equal("e", obj.Field5) -} - -func Test_decode_six_fields_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Field2 string - Field3 string - Field4 string - Field5 string - Field6 string - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field6": "x"}`, &obj)) - should.Equal("a", obj.Field1) - should.Equal("stream", obj.Field2) - should.Equal("c", obj.Field3) - should.Equal("d", obj.Field4) - should.Equal("e", obj.Field5) - should.Equal("x", obj.Field6) -} - -func Test_decode_seven_fields_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Field2 string - Field3 string - Field4 string - Field5 string - Field6 string - Field7 string - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field6": "x", "Field7":"y"}`, &obj)) - should.Equal("a", obj.Field1) - should.Equal("stream", obj.Field2) - should.Equal("c", obj.Field3) - should.Equal("d", obj.Field4) - should.Equal("e", obj.Field5) - should.Equal("x", obj.Field6) - should.Equal("y", obj.Field7) -} - -func Test_decode_eight_fields_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Field2 string - Field3 string - Field4 string - Field5 string - Field6 string - Field7 string - Field8 string - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"Field8":"1", "Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field6": "x", "Field7":"y"}`, &obj)) - should.Equal("a", obj.Field1) - should.Equal("stream", obj.Field2) - should.Equal("c", obj.Field3) - should.Equal("d", obj.Field4) - should.Equal("e", obj.Field5) - should.Equal("x", obj.Field6) - should.Equal("y", obj.Field7) - should.Equal("1", obj.Field8) -} - -func Test_decode_nine_fields_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Field2 string - Field3 string - Field4 string - Field5 string - Field6 string - Field7 string - Field8 string - Field9 string - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"Field8" : "zzzzzzzzzzz", "Field7": "zz", "Field6" : "xx", "Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e", "Field9":"f"}`, &obj)) - should.Equal("a", obj.Field1) - should.Equal("stream", obj.Field2) - should.Equal("c", obj.Field3) - should.Equal("d", obj.Field4) - should.Equal("e", obj.Field5) - should.Equal("xx", obj.Field6) - should.Equal("zz", obj.Field7) - should.Equal("zzzzzzzzzzz", obj.Field8) - should.Equal("f", obj.Field9) -} - -func Test_decode_ten_fields_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Field2 string - Field3 string - Field4 string - Field5 string - Field6 string - Field7 string - Field8 string - Field9 string - Field10 string - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"Field10":"x", "Field9": "x", "Field8":"x", "Field7":"x", "Field6":"x", "Field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj)) - should.Equal("a", obj.Field1) - should.Equal("stream", obj.Field2) - should.Equal("c", obj.Field3) - should.Equal("d", obj.Field4) - should.Equal("e", obj.Field5) - should.Equal("x", obj.Field6) - should.Equal("x", obj.Field7) - should.Equal("x", obj.Field8) - should.Equal("x", obj.Field9) - should.Equal("x", obj.Field10) -} - -func Test_decode_more_than_ten_fields_struct(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string - Field2 string - Field3 string - Field4 string - Field5 string - Field6 string - Field7 string - Field8 string - Field9 string - Field10 string - Field11 int - } - obj := TestObject{} - should.Nil(UnmarshalFromString(`{}`, &obj)) - should.Equal("", obj.Field1) - should.Nil(UnmarshalFromString(`{"field11":1, "field1": "a", "Field2": "stream", "Field3": "c", "Field4": "d", "Field5": "e"}`, &obj)) - should.Equal("a", obj.Field1) - should.Equal("stream", obj.Field2) - should.Equal("c", obj.Field3) - should.Equal("d", obj.Field4) - should.Equal("e", obj.Field5) - should.Equal(1, obj.Field11) -} - -func Test_decode_struct_field_with_tag(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 string `json:"field-1"` - Field2 string `json:"-"` - Field3 int `json:",string"` - } - obj := TestObject{Field2: "world"} - UnmarshalFromString(`{"field-1": "hello", "field2": "", "Field3": "100"}`, &obj) - should.Equal("hello", obj.Field1) - should.Equal("world", obj.Field2) - should.Equal(100, obj.Field3) -} - -func Test_decode_struct_field_with_tag_string(t *testing.T) { - should := require.New(t) - type TestObject struct { - Field1 int `json:",string"` - } - obj := TestObject{Field1: 100} - should.Nil(UnmarshalFromString(`{"Field1": "100"}`, &obj)) - should.Equal(100, obj.Field1) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_struct_encoder_test.go b/vendor/github.com/json-iterator/go/jsoniter_struct_encoder_test.go deleted file mode 100644 index 0e3e541884..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_struct_encoder_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "testing" - "time" - - "github.com/stretchr/testify/require" -) - -func Test_encode_unexported_field(t *testing.T) { - type TestData struct { - a int - b <-chan int - C int - d *time.Timer - } - - should := require.New(t) - - testChan := make(<-chan int, 10) - testTimer := time.NewTimer(10 * time.Second) - - obj := &TestData{ - a: 42, - b: testChan, - C: 21, - d: testTimer, - } - - jb, err := json.Marshal(obj) - should.NoError(err) - should.Equal([]byte(`{"C":21}`), jb) - - err = json.Unmarshal([]byte(`{"a": 444, "b":"bad", "C":55, "d":{"not": "a timer"}}`), obj) - should.NoError(err) - should.Equal(42, obj.a) - should.Equal(testChan, obj.b) - should.Equal(55, obj.C) - should.Equal(testTimer, obj.d) - - jb, err = Marshal(obj) - should.NoError(err) - should.Equal(jb, []byte(`{"C":55}`)) - - err = Unmarshal([]byte(`{"a": 444, "b":"bad", "C":256, "d":{"not":"a timer"}}`), obj) - should.NoError(err) - should.Equal(42, obj.a) - should.Equal(testChan, obj.b) - should.Equal(256, obj.C) - should.Equal(testTimer, obj.d) -} diff --git a/vendor/github.com/json-iterator/go/jsoniter_wrap_test.go b/vendor/github.com/json-iterator/go/jsoniter_wrap_test.go deleted file mode 100644 index b300fb5911..0000000000 --- a/vendor/github.com/json-iterator/go/jsoniter_wrap_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package jsoniter - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func Test_wrap_and_valuetype_everything(t *testing.T) { - should := require.New(t) - var i interface{} - any := Get([]byte("123")) - // default of number type is float64 - i = float64(123) - should.Equal(i, any.GetInterface()) - - any = Wrap(int8(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - // get interface is not int8 interface - // i = int8(10) - // should.Equal(i, any.GetInterface()) - - any = Wrap(int16(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - //i = int16(10) - //should.Equal(i, any.GetInterface()) - - any = Wrap(int32(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - i = int32(10) - should.Equal(i, any.GetInterface()) - any = Wrap(int64(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - i = int64(10) - should.Equal(i, any.GetInterface()) - - any = Wrap(uint(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - // not equal - //i = uint(10) - //should.Equal(i, any.GetInterface()) - any = Wrap(uint8(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - // not equal - // i = uint8(10) - // should.Equal(i, any.GetInterface()) - any = Wrap(uint16(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - any = Wrap(uint32(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - i = uint32(10) - should.Equal(i, any.GetInterface()) - any = Wrap(uint64(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - i = uint64(10) - should.Equal(i, any.GetInterface()) - - any = Wrap(float32(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - // not equal - //i = float32(10) - //should.Equal(i, any.GetInterface()) - any = Wrap(float64(10)) - should.Equal(any.ValueType(), NumberValue) - should.Equal(any.LastError(), nil) - i = float64(10) - should.Equal(i, any.GetInterface()) - - any = Wrap(true) - should.Equal(any.ValueType(), BoolValue) - should.Equal(any.LastError(), nil) - i = true - should.Equal(i, any.GetInterface()) - any = Wrap(false) - should.Equal(any.ValueType(), BoolValue) - should.Equal(any.LastError(), nil) - i = false - should.Equal(i, any.GetInterface()) - - any = Wrap(nil) - should.Equal(any.ValueType(), NilValue) - should.Equal(any.LastError(), nil) - i = nil - should.Equal(i, any.GetInterface()) - - stream := NewStream(ConfigDefault, nil, 32) - any.WriteTo(stream) - should.Equal("null", string(stream.Buffer())) - should.Equal(any.LastError(), nil) - - any = Wrap(struct{ age int }{age: 1}) - should.Equal(any.ValueType(), ObjectValue) - should.Equal(any.LastError(), nil) - i = struct{ age int }{age: 1} - should.Equal(i, any.GetInterface()) - - any = Wrap(map[string]interface{}{"abc": 1}) - should.Equal(any.ValueType(), ObjectValue) - should.Equal(any.LastError(), nil) - i = map[string]interface{}{"abc": 1} - should.Equal(i, any.GetInterface()) - - any = Wrap("abc") - i = "abc" - should.Equal(i, any.GetInterface()) - should.Equal(nil, any.LastError()) - -} diff --git a/vendor/github.com/json-iterator/go/feature_pool.go b/vendor/github.com/json-iterator/go/pool.go similarity index 62% rename from vendor/github.com/json-iterator/go/feature_pool.go rename to vendor/github.com/json-iterator/go/pool.go index 73962bc6f6..735062684b 100644 --- a/vendor/github.com/json-iterator/go/feature_pool.go +++ b/vendor/github.com/json-iterator/go/pool.go @@ -17,41 +17,25 @@ type StreamPool interface { } func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream { - select { - case stream := <-cfg.streamPool: - stream.Reset(writer) - return stream - default: - return NewStream(cfg, writer, 512) - } + stream := cfg.streamPool.Get().(*Stream) + stream.Reset(writer) + return stream } func (cfg *frozenConfig) ReturnStream(stream *Stream) { stream.Error = nil - select { - case cfg.streamPool <- stream: - return - default: - return - } + stream.Attachment = nil + cfg.streamPool.Put(stream) } func (cfg *frozenConfig) BorrowIterator(data []byte) *Iterator { - select { - case iter := <-cfg.iteratorPool: - iter.ResetBytes(data) - return iter - default: - return ParseBytes(cfg, data) - } + iter := cfg.iteratorPool.Get().(*Iterator) + iter.ResetBytes(data) + return iter } func (cfg *frozenConfig) ReturnIterator(iter *Iterator) { iter.Error = nil - select { - case cfg.iteratorPool <- iter: - return - default: - return - } + iter.Attachment = nil + cfg.iteratorPool.Put(iter) } diff --git a/vendor/github.com/json-iterator/go/reflect.go b/vendor/github.com/json-iterator/go/reflect.go new file mode 100644 index 0000000000..5c7d3a8a03 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect.go @@ -0,0 +1,321 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "reflect" + "unsafe" +) + +// ValDecoder is an internal type registered to cache as needed. +// Don't confuse jsoniter.ValDecoder with json.Decoder. +// For json.Decoder's adapter, refer to jsoniter.AdapterDecoder(todo link). +// +// Reflection on type to create decoders, which is then cached +// Reflection on value is avoided as we can, as the reflect.Value itself will allocate, with following exceptions +// 1. create instance of new value, for example *int will need a int to be allocated +// 2. append to slice, if the existing cap is not enough, allocate will be done using Reflect.New +// 3. assignment to map, both key and value will be reflect.Value +// For a simple struct binding, it will be reflect.Value free and allocation free +type ValDecoder interface { + Decode(ptr unsafe.Pointer, iter *Iterator) +} + +// ValEncoder is an internal type registered to cache as needed. +// Don't confuse jsoniter.ValEncoder with json.Encoder. +// For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link). +type ValEncoder interface { + IsEmpty(ptr unsafe.Pointer) bool + Encode(ptr unsafe.Pointer, stream *Stream) +} + +type checkIsEmpty interface { + IsEmpty(ptr unsafe.Pointer) bool +} + +type ctx struct { + *frozenConfig + prefix string + encoders map[reflect2.Type]ValEncoder + decoders map[reflect2.Type]ValDecoder +} + +func (b *ctx) append(prefix string) *ctx { + return &ctx{ + frozenConfig: b.frozenConfig, + prefix: b.prefix + " " + prefix, + encoders: b.encoders, + decoders: b.decoders, + } +} + +// ReadVal copy the underlying JSON into go interface, same as json.Unmarshal +func (iter *Iterator) ReadVal(obj interface{}) { + cacheKey := reflect2.RTypeOf(obj) + decoder := iter.cfg.getDecoderFromCache(cacheKey) + if decoder == nil { + typ := reflect2.TypeOf(obj) + if typ.Kind() != reflect.Ptr { + iter.ReportError("ReadVal", "can only unmarshal into pointer") + return + } + decoder = iter.cfg.DecoderOf(typ) + } + ptr := reflect2.PtrOf(obj) + if ptr == nil { + iter.ReportError("ReadVal", "can not read into nil pointer") + return + } + decoder.Decode(ptr, iter) +} + +// WriteVal copy the go interface into underlying JSON, same as json.Marshal +func (stream *Stream) WriteVal(val interface{}) { + if nil == val { + stream.WriteNil() + return + } + cacheKey := reflect2.RTypeOf(val) + encoder := stream.cfg.getEncoderFromCache(cacheKey) + if encoder == nil { + typ := reflect2.TypeOf(val) + encoder = stream.cfg.EncoderOf(typ) + } + encoder.Encode(reflect2.PtrOf(val), stream) +} + +func (cfg *frozenConfig) DecoderOf(typ reflect2.Type) ValDecoder { + cacheKey := typ.RType() + decoder := cfg.getDecoderFromCache(cacheKey) + if decoder != nil { + return decoder + } + ctx := &ctx{ + frozenConfig: cfg, + prefix: "", + decoders: map[reflect2.Type]ValDecoder{}, + encoders: map[reflect2.Type]ValEncoder{}, + } + ptrType := typ.(*reflect2.UnsafePtrType) + decoder = decoderOfType(ctx, ptrType.Elem()) + cfg.addDecoderToCache(cacheKey, decoder) + return decoder +} + +func decoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := getTypeDecoderFromExtension(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfType(ctx, typ) + for _, extension := range extensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + for _, extension := range ctx.extensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + return decoder +} + +func createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := ctx.decoders[typ] + if decoder != nil { + return decoder + } + placeholder := &placeholderDecoder{} + ctx.decoders[typ] = placeholder + decoder = _createDecoderOfType(ctx, typ) + placeholder.decoder = decoder + return decoder +} + +func _createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := createDecoderOfJsonRawMessage(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfJsonNumber(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfMarshaler(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfAny(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfNative(ctx, typ) + if decoder != nil { + return decoder + } + switch typ.Kind() { + case reflect.Interface: + ifaceType, isIFace := typ.(*reflect2.UnsafeIFaceType) + if isIFace { + return &ifaceDecoder{valType: ifaceType} + } + return &efaceDecoder{} + case reflect.Struct: + return decoderOfStruct(ctx, typ) + case reflect.Array: + return decoderOfArray(ctx, typ) + case reflect.Slice: + return decoderOfSlice(ctx, typ) + case reflect.Map: + return decoderOfMap(ctx, typ) + case reflect.Ptr: + return decoderOfOptional(ctx, typ) + default: + return &lazyErrorDecoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} + } +} + +func (cfg *frozenConfig) EncoderOf(typ reflect2.Type) ValEncoder { + cacheKey := typ.RType() + encoder := cfg.getEncoderFromCache(cacheKey) + if encoder != nil { + return encoder + } + ctx := &ctx{ + frozenConfig: cfg, + prefix: "", + decoders: map[reflect2.Type]ValDecoder{}, + encoders: map[reflect2.Type]ValEncoder{}, + } + encoder = encoderOfType(ctx, typ) + if typ.LikePtr() { + encoder = &onePtrEncoder{encoder} + } + cfg.addEncoderToCache(cacheKey, encoder) + return encoder +} + +type onePtrEncoder struct { + encoder ValEncoder +} + +func (encoder *onePtrEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) +} + +func (encoder *onePtrEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) +} + +func encoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := getTypeEncoderFromExtension(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfType(ctx, typ) + for _, extension := range extensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + for _, extension := range ctx.extensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + return encoder +} + +func createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := ctx.encoders[typ] + if encoder != nil { + return encoder + } + placeholder := &placeholderEncoder{} + ctx.encoders[typ] = placeholder + encoder = _createEncoderOfType(ctx, typ) + placeholder.encoder = encoder + return encoder +} +func _createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := createEncoderOfJsonRawMessage(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfJsonNumber(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfMarshaler(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfAny(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfNative(ctx, typ) + if encoder != nil { + return encoder + } + kind := typ.Kind() + switch kind { + case reflect.Interface: + return &dynamicEncoder{typ} + case reflect.Struct: + return encoderOfStruct(ctx, typ) + case reflect.Array: + return encoderOfArray(ctx, typ) + case reflect.Slice: + return encoderOfSlice(ctx, typ) + case reflect.Map: + return encoderOfMap(ctx, typ) + case reflect.Ptr: + return encoderOfOptional(ctx, typ) + default: + return &lazyErrorEncoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} + } +} + +type lazyErrorDecoder struct { + err error +} + +func (decoder *lazyErrorDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.WhatIsNext() != NilValue { + if iter.Error == nil { + iter.Error = decoder.err + } + } else { + iter.Skip() + } +} + +type lazyErrorEncoder struct { + err error +} + +func (encoder *lazyErrorEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if ptr == nil { + stream.WriteNil() + } else if stream.Error == nil { + stream.Error = encoder.err + } +} + +func (encoder *lazyErrorEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type placeholderDecoder struct { + decoder ValDecoder +} + +func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.decoder.Decode(ptr, iter) +} + +type placeholderEncoder struct { + encoder ValEncoder +} + +func (encoder *placeholderEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(ptr, stream) +} + +func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(ptr) +} diff --git a/vendor/github.com/json-iterator/go/reflect_array.go b/vendor/github.com/json-iterator/go/reflect_array.go new file mode 100644 index 0000000000..13a0b7b087 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_array.go @@ -0,0 +1,104 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "unsafe" +) + +func decoderOfArray(ctx *ctx, typ reflect2.Type) ValDecoder { + arrayType := typ.(*reflect2.UnsafeArrayType) + decoder := decoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) + return &arrayDecoder{arrayType, decoder} +} + +func encoderOfArray(ctx *ctx, typ reflect2.Type) ValEncoder { + arrayType := typ.(*reflect2.UnsafeArrayType) + if arrayType.Len() == 0 { + return emptyArrayEncoder{} + } + encoder := encoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) + return &arrayEncoder{arrayType, encoder} +} + +type emptyArrayEncoder struct{} + +func (encoder emptyArrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteEmptyArray() +} + +func (encoder emptyArrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return true +} + +type arrayEncoder struct { + arrayType *reflect2.UnsafeArrayType + elemEncoder ValEncoder +} + +func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteArrayStart() + elemPtr := unsafe.Pointer(ptr) + encoder.elemEncoder.Encode(elemPtr, stream) + for i := 1; i < encoder.arrayType.Len(); i++ { + stream.WriteMore() + elemPtr = encoder.arrayType.UnsafeGetIndex(ptr, i) + encoder.elemEncoder.Encode(elemPtr, stream) + } + stream.WriteArrayEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v: %s", encoder.arrayType, stream.Error.Error()) + } +} + +func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type arrayDecoder struct { + arrayType *reflect2.UnsafeArrayType + elemDecoder ValDecoder +} + +func (decoder *arrayDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.doDecode(ptr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v: %s", decoder.arrayType, iter.Error.Error()) + } +} + +func (decoder *arrayDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + arrayType := decoder.arrayType + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return + } + if c != '[' { + iter.ReportError("decode array", "expect [ or n, but found "+string([]byte{c})) + return + } + c = iter.nextToken() + if c == ']' { + return + } + iter.unreadByte() + elemPtr := arrayType.UnsafeGetIndex(ptr, 0) + decoder.elemDecoder.Decode(elemPtr, iter) + length := 1 + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + if length >= arrayType.Len() { + iter.Skip() + continue + } + idx := length + length += 1 + elemPtr = arrayType.UnsafeGetIndex(ptr, idx) + decoder.elemDecoder.Decode(elemPtr, iter) + } + if c != ']' { + iter.ReportError("decode array", "expect ], but found "+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_dynamic.go b/vendor/github.com/json-iterator/go/reflect_dynamic.go new file mode 100644 index 0000000000..8b6bc8b433 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_dynamic.go @@ -0,0 +1,70 @@ +package jsoniter + +import ( + "github.com/modern-go/reflect2" + "reflect" + "unsafe" +) + +type dynamicEncoder struct { + valType reflect2.Type +} + +func (encoder *dynamicEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + stream.WriteVal(obj) +} + +func (encoder *dynamicEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.valType.UnsafeIndirect(ptr) == nil +} + +type efaceDecoder struct { +} + +func (decoder *efaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + pObj := (*interface{})(ptr) + obj := *pObj + if obj == nil { + *pObj = iter.Read() + return + } + typ := reflect2.TypeOf(obj) + if typ.Kind() != reflect.Ptr { + *pObj = iter.Read() + return + } + ptrType := typ.(*reflect2.UnsafePtrType) + ptrElemType := ptrType.Elem() + if iter.WhatIsNext() == NilValue { + if ptrElemType.Kind() != reflect.Ptr { + iter.skipFourBytes('n', 'u', 'l', 'l') + *pObj = nil + return + } + } + if reflect2.IsNil(obj) { + obj := ptrElemType.New() + iter.ReadVal(obj) + *pObj = obj + return + } + iter.ReadVal(obj) +} + +type ifaceDecoder struct { + valType *reflect2.UnsafeIFaceType +} + +func (decoder *ifaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + decoder.valType.UnsafeSet(ptr, decoder.valType.UnsafeNew()) + return + } + obj := decoder.valType.UnsafeIndirect(ptr) + if reflect2.IsNil(obj) { + iter.ReportError("decode non empty interface", "can not unmarshal into nil") + return + } + iter.ReadVal(obj) +} diff --git a/vendor/github.com/json-iterator/go/feature_reflect_extension.go b/vendor/github.com/json-iterator/go/reflect_extension.go similarity index 55% rename from vendor/github.com/json-iterator/go/feature_reflect_extension.go rename to vendor/github.com/json-iterator/go/reflect_extension.go index 74f4b8babb..917bbe84ec 100644 --- a/vendor/github.com/json-iterator/go/feature_reflect_extension.go +++ b/vendor/github.com/json-iterator/go/reflect_extension.go @@ -2,6 +2,7 @@ package jsoniter import ( "fmt" + "github.com/modern-go/reflect2" "reflect" "sort" "strings" @@ -17,17 +18,15 @@ var extensions = []Extension{} // StructDescriptor describe how should we encode/decode the struct type StructDescriptor struct { - onePtrEmbedded bool - onePtrOptimization bool - Type reflect.Type - Fields []*Binding + Type reflect2.Type + Fields []*Binding } // GetField get one field from the descriptor by its name. // Can not use map here to keep field orders. func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding { for _, binding := range structDescriptor.Fields { - if binding.Field.Name == fieldName { + if binding.Field.Name() == fieldName { return binding } } @@ -37,7 +36,7 @@ func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding { // Binding describe how should we encode/decode the struct field type Binding struct { levels []int - Field *reflect.StructField + Field reflect2.StructField FromNames []string ToNames []string Encoder ValEncoder @@ -48,10 +47,12 @@ type Binding struct { // Can also rename fields by UpdateStructDescriptor. type Extension interface { UpdateStructDescriptor(structDescriptor *StructDescriptor) - CreateDecoder(typ reflect.Type) ValDecoder - CreateEncoder(typ reflect.Type) ValEncoder - DecorateDecoder(typ reflect.Type, decoder ValDecoder) ValDecoder - DecorateEncoder(typ reflect.Type, encoder ValEncoder) ValEncoder + CreateMapKeyDecoder(typ reflect2.Type) ValDecoder + CreateMapKeyEncoder(typ reflect2.Type) ValEncoder + CreateDecoder(typ reflect2.Type) ValDecoder + CreateEncoder(typ reflect2.Type) ValEncoder + DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder + DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder } // DummyExtension embed this type get dummy implementation for all methods of Extension @@ -62,23 +63,105 @@ type DummyExtension struct { func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { } +// CreateMapKeyDecoder No-op +func (extension *DummyExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension *DummyExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + // CreateDecoder No-op -func (extension *DummyExtension) CreateDecoder(typ reflect.Type) ValDecoder { +func (extension *DummyExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateEncoder No-op +func (extension *DummyExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension *DummyExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension *DummyExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type EncoderExtension map[reflect2.Type]ValEncoder + +// UpdateStructDescriptor No-op +func (extension EncoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateDecoder No-op +func (extension EncoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateEncoder get encoder from map +func (extension EncoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return extension[typ] +} + +// CreateMapKeyDecoder No-op +func (extension EncoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension EncoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension EncoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension EncoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type DecoderExtension map[reflect2.Type]ValDecoder + +// UpdateStructDescriptor No-op +func (extension DecoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateMapKeyDecoder No-op +func (extension DecoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension DecoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { return nil } +// CreateDecoder get decoder from map +func (extension DecoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return extension[typ] +} + // CreateEncoder No-op -func (extension *DummyExtension) CreateEncoder(typ reflect.Type) ValEncoder { +func (extension DecoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { return nil } // DecorateDecoder No-op -func (extension *DummyExtension) DecorateDecoder(typ reflect.Type, decoder ValDecoder) ValDecoder { +func (extension DecoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { return decoder } // DecorateEncoder No-op -func (extension *DummyExtension) DecorateEncoder(typ reflect.Type, encoder ValEncoder) ValEncoder { +func (extension DecoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { return encoder } @@ -99,10 +182,6 @@ func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { encoder.fun(ptr, stream) } -func (encoder *funcEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool { if encoder.isEmptyFunc == nil { return false @@ -161,132 +240,141 @@ func RegisterExtension(extension Extension) { extensions = append(extensions, extension) } -func getTypeDecoderFromExtension(typ reflect.Type) ValDecoder { - decoder := _getTypeDecoderFromExtension(typ) +func getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := _getTypeDecoderFromExtension(ctx, typ) if decoder != nil { for _, extension := range extensions { decoder = extension.DecorateDecoder(typ, decoder) } + for _, extension := range ctx.extensions { + decoder = extension.DecorateDecoder(typ, decoder) + } } return decoder } -func _getTypeDecoderFromExtension(typ reflect.Type) ValDecoder { +func _getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { for _, extension := range extensions { decoder := extension.CreateDecoder(typ) if decoder != nil { return decoder } } + for _, extension := range ctx.extensions { + decoder := extension.CreateDecoder(typ) + if decoder != nil { + return decoder + } + } typeName := typ.String() decoder := typeDecoders[typeName] if decoder != nil { return decoder } if typ.Kind() == reflect.Ptr { - decoder := typeDecoders[typ.Elem().String()] + ptrType := typ.(*reflect2.UnsafePtrType) + decoder := typeDecoders[ptrType.Elem().String()] if decoder != nil { - return &optionalDecoder{typ.Elem(), decoder} + return &OptionalDecoder{ptrType.Elem(), decoder} } } return nil } -func getTypeEncoderFromExtension(typ reflect.Type) ValEncoder { - encoder := _getTypeEncoderFromExtension(typ) +func getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := _getTypeEncoderFromExtension(ctx, typ) if encoder != nil { for _, extension := range extensions { encoder = extension.DecorateEncoder(typ, encoder) } + for _, extension := range ctx.extensions { + encoder = extension.DecorateEncoder(typ, encoder) + } } return encoder } -func _getTypeEncoderFromExtension(typ reflect.Type) ValEncoder { +func _getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { for _, extension := range extensions { encoder := extension.CreateEncoder(typ) if encoder != nil { return encoder } } + for _, extension := range ctx.extensions { + encoder := extension.CreateEncoder(typ) + if encoder != nil { + return encoder + } + } typeName := typ.String() encoder := typeEncoders[typeName] if encoder != nil { return encoder } if typ.Kind() == reflect.Ptr { - encoder := typeEncoders[typ.Elem().String()] + typePtr := typ.(*reflect2.UnsafePtrType) + encoder := typeEncoders[typePtr.Elem().String()] if encoder != nil { - return &optionalEncoder{encoder} + return &OptionalEncoder{encoder} } } return nil } -func describeStruct(cfg *frozenConfig, typ reflect.Type) (*StructDescriptor, error) { +func describeStruct(ctx *ctx, typ reflect2.Type) *StructDescriptor { + structType := typ.(*reflect2.UnsafeStructType) embeddedBindings := []*Binding{} bindings := []*Binding{} - for i := 0; i < typ.NumField(); i++ { - field := typ.Field(i) - tag := field.Tag.Get(cfg.getTagKey()) + for i := 0; i < structType.NumField(); i++ { + field := structType.Field(i) + tag, hastag := field.Tag().Lookup(ctx.getTagKey()) + if ctx.onlyTaggedField && !hastag { + continue + } tagParts := strings.Split(tag, ",") if tag == "-" { continue } - if field.Anonymous && (tag == "" || tagParts[0] == "") { - if field.Type.Kind() == reflect.Struct { - structDescriptor, err := describeStruct(cfg, field.Type) - if err != nil { - return nil, err - } + if field.Anonymous() && (tag == "" || tagParts[0] == "") { + if field.Type().Kind() == reflect.Struct { + structDescriptor := describeStruct(ctx, field.Type()) for _, binding := range structDescriptor.Fields { binding.levels = append([]int{i}, binding.levels...) omitempty := binding.Encoder.(*structFieldEncoder).omitempty - binding.Encoder = &structFieldEncoder{&field, binding.Encoder, omitempty} - binding.Decoder = &structFieldDecoder{&field, binding.Decoder} + binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} + binding.Decoder = &structFieldDecoder{field, binding.Decoder} embeddedBindings = append(embeddedBindings, binding) } continue - } else if field.Type.Kind() == reflect.Ptr && field.Type.Elem().Kind() == reflect.Struct { - structDescriptor, err := describeStruct(cfg, field.Type.Elem()) - if err != nil { - return nil, err - } - for _, binding := range structDescriptor.Fields { - binding.levels = append([]int{i}, binding.levels...) - omitempty := binding.Encoder.(*structFieldEncoder).omitempty - binding.Encoder = &optionalEncoder{binding.Encoder} - binding.Encoder = &structFieldEncoder{&field, binding.Encoder, omitempty} - binding.Decoder = &deferenceDecoder{field.Type.Elem(), binding.Decoder} - binding.Decoder = &structFieldDecoder{&field, binding.Decoder} - embeddedBindings = append(embeddedBindings, binding) + } else if field.Type().Kind() == reflect.Ptr { + ptrType := field.Type().(*reflect2.UnsafePtrType) + if ptrType.Elem().Kind() == reflect.Struct { + structDescriptor := describeStruct(ctx, ptrType.Elem()) + for _, binding := range structDescriptor.Fields { + binding.levels = append([]int{i}, binding.levels...) + omitempty := binding.Encoder.(*structFieldEncoder).omitempty + binding.Encoder = &dereferenceEncoder{binding.Encoder} + binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} + binding.Decoder = &dereferenceDecoder{ptrType.Elem(), binding.Decoder} + binding.Decoder = &structFieldDecoder{field, binding.Decoder} + embeddedBindings = append(embeddedBindings, binding) + } + continue } - continue } } - fieldNames := calcFieldNames(field.Name, tagParts[0], tag) - fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name) + fieldNames := calcFieldNames(field.Name(), tagParts[0], tag) + fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name()) decoder := fieldDecoders[fieldCacheKey] if decoder == nil { - var err error - decoder, err = decoderOfType(cfg, field.Type) - if len(fieldNames) > 0 && err != nil { - return nil, err - } + decoder = decoderOfType(ctx.append(field.Name()), field.Type()) } encoder := fieldEncoders[fieldCacheKey] if encoder == nil { - var err error - encoder, err = encoderOfType(cfg, field.Type) - if len(fieldNames) > 0 && err != nil { - return nil, err - } - // map is stored as pointer in the struct - if encoder != nil && field.Type.Kind() == reflect.Map { - encoder = &optionalEncoder{encoder} - } + encoder = encoderOfType(ctx.append(field.Name()), field.Type()) } binding := &Binding{ - Field: &field, + Field: field, FromNames: fieldNames, ToNames: fieldNames, Decoder: decoder, @@ -295,35 +383,20 @@ func describeStruct(cfg *frozenConfig, typ reflect.Type) (*StructDescriptor, err binding.levels = []int{i} bindings = append(bindings, binding) } - return createStructDescriptor(cfg, typ, bindings, embeddedBindings), nil -} -func createStructDescriptor(cfg *frozenConfig, typ reflect.Type, bindings []*Binding, embeddedBindings []*Binding) *StructDescriptor { - onePtrEmbedded := false - onePtrOptimization := false - if typ.NumField() == 1 { - firstField := typ.Field(0) - switch firstField.Type.Kind() { - case reflect.Ptr: - if firstField.Anonymous && firstField.Type.Elem().Kind() == reflect.Struct { - onePtrEmbedded = true - } - fallthrough - case reflect.Map: - onePtrOptimization = true - case reflect.Struct: - onePtrOptimization = isStructOnePtr(firstField.Type) - } - } + return createStructDescriptor(ctx, typ, bindings, embeddedBindings) +} +func createStructDescriptor(ctx *ctx, typ reflect2.Type, bindings []*Binding, embeddedBindings []*Binding) *StructDescriptor { structDescriptor := &StructDescriptor{ - onePtrEmbedded: onePtrEmbedded, - onePtrOptimization: onePtrOptimization, - Type: typ, - Fields: bindings, + Type: typ, + Fields: bindings, } for _, extension := range extensions { extension.UpdateStructDescriptor(structDescriptor) } - processTags(structDescriptor, cfg) + for _, extension := range ctx.extensions { + extension.UpdateStructDescriptor(structDescriptor) + } + processTags(structDescriptor, ctx.frozenConfig) // merge normal & embedded bindings & sort with original order allBindings := sortableBindings(append(embeddedBindings, structDescriptor.Fields...)) sort.Sort(allBindings) @@ -331,21 +404,6 @@ func createStructDescriptor(cfg *frozenConfig, typ reflect.Type, bindings []*Bin return structDescriptor } -func isStructOnePtr(typ reflect.Type) bool { - if typ.NumField() == 1 { - firstField := typ.Field(0) - switch firstField.Type.Kind() { - case reflect.Ptr: - return true - case reflect.Map: - return true - case reflect.Struct: - return isStructOnePtr(firstField.Type) - } - } - return false -} - type sortableBindings []*Binding func (bindings sortableBindings) Len() int { @@ -373,12 +431,12 @@ func (bindings sortableBindings) Swap(i, j int) { func processTags(structDescriptor *StructDescriptor, cfg *frozenConfig) { for _, binding := range structDescriptor.Fields { shouldOmitEmpty := false - tagParts := strings.Split(binding.Field.Tag.Get(cfg.getTagKey()), ",") + tagParts := strings.Split(binding.Field.Tag().Get(cfg.getTagKey()), ",") for _, tagPart := range tagParts[1:] { if tagPart == "omitempty" { shouldOmitEmpty = true } else if tagPart == "string" { - if binding.Field.Type.Kind() == reflect.String { + if binding.Field.Type().Kind() == reflect.String { binding.Decoder = &stringModeStringDecoder{binding.Decoder, cfg} binding.Encoder = &stringModeStringEncoder{binding.Encoder, cfg} } else { diff --git a/vendor/github.com/json-iterator/go/reflect_json_number.go b/vendor/github.com/json-iterator/go/reflect_json_number.go new file mode 100644 index 0000000000..98d45c1ec2 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_json_number.go @@ -0,0 +1,112 @@ +package jsoniter + +import ( + "encoding/json" + "github.com/modern-go/reflect2" + "strconv" + "unsafe" +) + +type Number string + +// String returns the literal text of the number. +func (n Number) String() string { return string(n) } + +// Float64 returns the number as a float64. +func (n Number) Float64() (float64, error) { + return strconv.ParseFloat(string(n), 64) +} + +// Int64 returns the number as an int64. +func (n Number) Int64() (int64, error) { + return strconv.ParseInt(string(n), 10, 64) +} + +func CastJsonNumber(val interface{}) (string, bool) { + switch typedVal := val.(type) { + case json.Number: + return string(typedVal), true + case Number: + return string(typedVal), true + } + return "", false +} + +var jsonNumberType = reflect2.TypeOfPtr((*json.Number)(nil)).Elem() +var jsoniterNumberType = reflect2.TypeOfPtr((*Number)(nil)).Elem() + +func createDecoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ.AssignableTo(jsonNumberType) { + return &jsonNumberCodec{} + } + if typ.AssignableTo(jsoniterNumberType) { + return &jsoniterNumberCodec{} + } + return nil +} + +func createEncoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ.AssignableTo(jsonNumberType) { + return &jsonNumberCodec{} + } + if typ.AssignableTo(jsoniterNumberType) { + return &jsoniterNumberCodec{} + } + return nil +} + +type jsonNumberCodec struct { +} + +func (codec *jsonNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + switch iter.WhatIsNext() { + case StringValue: + *((*json.Number)(ptr)) = json.Number(iter.ReadString()) + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + *((*json.Number)(ptr)) = "" + default: + *((*json.Number)(ptr)) = json.Number([]byte(iter.readNumberAsString())) + } +} + +func (codec *jsonNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + number := *((*json.Number)(ptr)) + if len(number) == 0 { + stream.writeByte('0') + } else { + stream.WriteRaw(string(number)) + } +} + +func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*json.Number)(ptr))) == 0 +} + +type jsoniterNumberCodec struct { +} + +func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + switch iter.WhatIsNext() { + case StringValue: + *((*Number)(ptr)) = Number(iter.ReadString()) + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + *((*Number)(ptr)) = "" + default: + *((*Number)(ptr)) = Number([]byte(iter.readNumberAsString())) + } +} + +func (codec *jsoniterNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + number := *((*Number)(ptr)) + if len(number) == 0 { + stream.writeByte('0') + } else { + stream.WriteRaw(string(number)) + } +} + +func (codec *jsoniterNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*Number)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go new file mode 100644 index 0000000000..f2619936c8 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go @@ -0,0 +1,60 @@ +package jsoniter + +import ( + "encoding/json" + "github.com/modern-go/reflect2" + "unsafe" +) + +var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem() +var jsoniterRawMessageType = reflect2.TypeOfPtr((*RawMessage)(nil)).Elem() + +func createEncoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == jsonRawMessageType { + return &jsonRawMessageCodec{} + } + if typ == jsoniterRawMessageType { + return &jsoniterRawMessageCodec{} + } + return nil +} + +func createDecoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ == jsonRawMessageType { + return &jsonRawMessageCodec{} + } + if typ == jsoniterRawMessageType { + return &jsoniterRawMessageCodec{} + } + return nil +} + +type jsonRawMessageCodec struct { +} + +func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *((*json.RawMessage)(ptr)) = json.RawMessage(iter.SkipAndReturnBytes()) +} + +func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteRaw(string(*((*json.RawMessage)(ptr)))) +} + +func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*json.RawMessage)(ptr))) == 0 +} + +type jsoniterRawMessageCodec struct { +} + +func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *((*RawMessage)(ptr)) = RawMessage(iter.SkipAndReturnBytes()) +} + +func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteRaw(string(*((*RawMessage)(ptr)))) +} + +func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*RawMessage)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_map.go b/vendor/github.com/json-iterator/go/reflect_map.go new file mode 100644 index 0000000000..8812f08501 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_map.go @@ -0,0 +1,318 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "reflect" + "sort" + "unsafe" +) + +func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder { + mapType := typ.(*reflect2.UnsafeMapType) + keyDecoder := decoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()) + elemDecoder := decoderOfType(ctx.append("[mapElem]"), mapType.Elem()) + return &mapDecoder{ + mapType: mapType, + keyType: mapType.Key(), + elemType: mapType.Elem(), + keyDecoder: keyDecoder, + elemDecoder: elemDecoder, + } +} + +func encoderOfMap(ctx *ctx, typ reflect2.Type) ValEncoder { + mapType := typ.(*reflect2.UnsafeMapType) + if ctx.sortMapKeys { + return &sortKeysMapEncoder{ + mapType: mapType, + keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), + elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), + } + } + return &mapEncoder{ + mapType: mapType, + keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), + elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), + } +} + +func decoderOfMapKey(ctx *ctx, typ reflect2.Type) ValDecoder { + for _, extension := range ctx.extensions { + decoder := extension.CreateMapKeyDecoder(typ) + if decoder != nil { + return decoder + } + } + switch typ.Kind() { + case reflect.String: + return decoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) + case reflect.Bool, + reflect.Uint8, reflect.Int8, + reflect.Uint16, reflect.Int16, + reflect.Uint32, reflect.Int32, + reflect.Uint64, reflect.Int64, + reflect.Uint, reflect.Int, + reflect.Float32, reflect.Float64, + reflect.Uintptr: + typ = reflect2.DefaultTypeOfKind(typ.Kind()) + return &numericMapKeyDecoder{decoderOfType(ctx, typ)} + default: + ptrType := reflect2.PtrTo(typ) + if ptrType.Implements(textMarshalerType) { + return &referenceDecoder{ + &textUnmarshalerDecoder{ + valType: ptrType, + }, + } + } + if typ.Implements(textMarshalerType) { + return &textUnmarshalerDecoder{ + valType: typ, + } + } + return &lazyErrorDecoder{err: fmt.Errorf("unsupported map key type: %v", typ)} + } +} + +func encoderOfMapKey(ctx *ctx, typ reflect2.Type) ValEncoder { + for _, extension := range ctx.extensions { + encoder := extension.CreateMapKeyEncoder(typ) + if encoder != nil { + return encoder + } + } + switch typ.Kind() { + case reflect.String: + return encoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) + case reflect.Bool, + reflect.Uint8, reflect.Int8, + reflect.Uint16, reflect.Int16, + reflect.Uint32, reflect.Int32, + reflect.Uint64, reflect.Int64, + reflect.Uint, reflect.Int, + reflect.Float32, reflect.Float64, + reflect.Uintptr: + typ = reflect2.DefaultTypeOfKind(typ.Kind()) + return &numericMapKeyEncoder{encoderOfType(ctx, typ)} + default: + if typ == textMarshalerType { + return &directTextMarshalerEncoder{ + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + } + if typ.Implements(textMarshalerType) { + return &textMarshalerEncoder{ + valType: typ, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + } + if typ.Kind() == reflect.Interface { + return &dynamicMapKeyEncoder{ctx, typ} + } + return &lazyErrorEncoder{err: fmt.Errorf("unsupported map key type: %v", typ)} + } +} + +type mapDecoder struct { + mapType *reflect2.UnsafeMapType + keyType reflect2.Type + elemType reflect2.Type + keyDecoder ValDecoder + elemDecoder ValDecoder +} + +func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + mapType := decoder.mapType + c := iter.nextToken() + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + *(*unsafe.Pointer)(ptr) = nil + mapType.UnsafeSet(ptr, mapType.UnsafeNew()) + return + } + if mapType.UnsafeIsNil(ptr) { + mapType.UnsafeSet(ptr, mapType.UnsafeMakeMap(0)) + } + if c != '{' { + iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) + return + } + c = iter.nextToken() + if c == '}' { + return + } + if c != '"' { + iter.ReportError("ReadMapCB", `expect " after }, but found `+string([]byte{c})) + return + } + iter.unreadByte() + key := decoder.keyType.UnsafeNew() + decoder.keyDecoder.Decode(key, iter) + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + return + } + elem := decoder.elemType.UnsafeNew() + decoder.elemDecoder.Decode(elem, iter) + decoder.mapType.UnsafeSetIndex(ptr, key, elem) + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + key := decoder.keyType.UnsafeNew() + decoder.keyDecoder.Decode(key, iter) + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + return + } + elem := decoder.elemType.UnsafeNew() + decoder.elemDecoder.Decode(elem, iter) + decoder.mapType.UnsafeSetIndex(ptr, key, elem) + } + if c != '}' { + iter.ReportError("ReadMapCB", `expect }, but found `+string([]byte{c})) + } +} + +type numericMapKeyDecoder struct { + decoder ValDecoder +} + +func (decoder *numericMapKeyDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + if c != '"' { + iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) + return + } + decoder.decoder.Decode(ptr, iter) + c = iter.nextToken() + if c != '"' { + iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) + return + } +} + +type numericMapKeyEncoder struct { + encoder ValEncoder +} + +func (encoder *numericMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.writeByte('"') + encoder.encoder.Encode(ptr, stream) + stream.writeByte('"') +} + +func (encoder *numericMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type dynamicMapKeyEncoder struct { + ctx *ctx + valType reflect2.Type +} + +func (encoder *dynamicMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).Encode(reflect2.PtrOf(obj), stream) +} + +func (encoder *dynamicMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { + obj := encoder.valType.UnsafeIndirect(ptr) + return encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).IsEmpty(reflect2.PtrOf(obj)) +} + +type mapEncoder struct { + mapType *reflect2.UnsafeMapType + keyEncoder ValEncoder + elemEncoder ValEncoder +} + +func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteObjectStart() + iter := encoder.mapType.UnsafeIterate(ptr) + for i := 0; iter.HasNext(); i++ { + if i != 0 { + stream.WriteMore() + } + key, elem := iter.UnsafeNext() + encoder.keyEncoder.Encode(key, stream) + if stream.indention > 0 { + stream.writeTwoBytes(byte(':'), byte(' ')) + } else { + stream.writeByte(':') + } + encoder.elemEncoder.Encode(elem, stream) + } + stream.WriteObjectEnd() +} + +func (encoder *mapEncoder) IsEmpty(ptr unsafe.Pointer) bool { + iter := encoder.mapType.UnsafeIterate(ptr) + return !iter.HasNext() +} + +type sortKeysMapEncoder struct { + mapType *reflect2.UnsafeMapType + keyEncoder ValEncoder + elemEncoder ValEncoder +} + +func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *(*unsafe.Pointer)(ptr) == nil { + stream.WriteNil() + return + } + stream.WriteObjectStart() + mapIter := encoder.mapType.UnsafeIterate(ptr) + subStream := stream.cfg.BorrowStream(nil) + subIter := stream.cfg.BorrowIterator(nil) + keyValues := encodedKeyValues{} + for mapIter.HasNext() { + subStream.buf = make([]byte, 0, 64) + key, elem := mapIter.UnsafeNext() + encoder.keyEncoder.Encode(key, subStream) + if subStream.Error != nil && subStream.Error != io.EOF && stream.Error == nil { + stream.Error = subStream.Error + } + encodedKey := subStream.Buffer() + subIter.ResetBytes(encodedKey) + decodedKey := subIter.ReadString() + if stream.indention > 0 { + subStream.writeTwoBytes(byte(':'), byte(' ')) + } else { + subStream.writeByte(':') + } + encoder.elemEncoder.Encode(elem, subStream) + keyValues = append(keyValues, encodedKV{ + key: decodedKey, + keyValue: subStream.Buffer(), + }) + } + sort.Sort(keyValues) + for i, keyValue := range keyValues { + if i != 0 { + stream.WriteMore() + } + stream.Write(keyValue.keyValue) + } + stream.WriteObjectEnd() + stream.cfg.ReturnStream(subStream) + stream.cfg.ReturnIterator(subIter) +} + +func (encoder *sortKeysMapEncoder) IsEmpty(ptr unsafe.Pointer) bool { + iter := encoder.mapType.UnsafeIterate(ptr) + return !iter.HasNext() +} + +type encodedKeyValues []encodedKV + +type encodedKV struct { + key string + keyValue []byte +} + +func (sv encodedKeyValues) Len() int { return len(sv) } +func (sv encodedKeyValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } +func (sv encodedKeyValues) Less(i, j int) bool { return sv[i].key < sv[j].key } diff --git a/vendor/github.com/json-iterator/go/reflect_marshaler.go b/vendor/github.com/json-iterator/go/reflect_marshaler.go new file mode 100644 index 0000000000..58ac959ad8 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_marshaler.go @@ -0,0 +1,218 @@ +package jsoniter + +import ( + "encoding" + "encoding/json" + "github.com/modern-go/reflect2" + "unsafe" +) + +var marshalerType = reflect2.TypeOfPtr((*json.Marshaler)(nil)).Elem() +var unmarshalerType = reflect2.TypeOfPtr((*json.Unmarshaler)(nil)).Elem() +var textMarshalerType = reflect2.TypeOfPtr((*encoding.TextMarshaler)(nil)).Elem() +var textUnmarshalerType = reflect2.TypeOfPtr((*encoding.TextUnmarshaler)(nil)).Elem() + +func createDecoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValDecoder { + ptrType := reflect2.PtrTo(typ) + if ptrType.Implements(unmarshalerType) { + return &referenceDecoder{ + &unmarshalerDecoder{ptrType}, + } + } + if ptrType.Implements(textUnmarshalerType) { + return &referenceDecoder{ + &textUnmarshalerDecoder{ptrType}, + } + } + return nil +} + +func createEncoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == marshalerType { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &directMarshalerEncoder{ + checkIsEmpty: checkIsEmpty, + } + return encoder + } + if typ.Implements(marshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &marshalerEncoder{ + valType: typ, + checkIsEmpty: checkIsEmpty, + } + return encoder + } + ptrType := reflect2.PtrTo(typ) + if ctx.prefix != "" && ptrType.Implements(marshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, ptrType) + var encoder ValEncoder = &marshalerEncoder{ + valType: ptrType, + checkIsEmpty: checkIsEmpty, + } + return &referenceEncoder{encoder} + } + if typ == textMarshalerType { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &directTextMarshalerEncoder{ + checkIsEmpty: checkIsEmpty, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + return encoder + } + if typ.Implements(textMarshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &textMarshalerEncoder{ + valType: typ, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + checkIsEmpty: checkIsEmpty, + } + return encoder + } + // if prefix is empty, the type is the root type + if ctx.prefix != "" && ptrType.Implements(textMarshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, ptrType) + var encoder ValEncoder = &textMarshalerEncoder{ + valType: ptrType, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + checkIsEmpty: checkIsEmpty, + } + return &referenceEncoder{encoder} + } + return nil +} + +type marshalerEncoder struct { + checkIsEmpty checkIsEmpty + valType reflect2.Type +} + +func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + if encoder.valType.IsNullable() && reflect2.IsNil(obj) { + stream.WriteNil() + return + } + marshaler := obj.(json.Marshaler) + bytes, err := marshaler.MarshalJSON() + if err != nil { + stream.Error = err + } else { + stream.Write(bytes) + } +} + +func (encoder *marshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type directMarshalerEncoder struct { + checkIsEmpty checkIsEmpty +} + +func (encoder *directMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + marshaler := *(*json.Marshaler)(ptr) + if marshaler == nil { + stream.WriteNil() + return + } + bytes, err := marshaler.MarshalJSON() + if err != nil { + stream.Error = err + } else { + stream.Write(bytes) + } +} + +func (encoder *directMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type textMarshalerEncoder struct { + valType reflect2.Type + stringEncoder ValEncoder + checkIsEmpty checkIsEmpty +} + +func (encoder *textMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + if encoder.valType.IsNullable() && reflect2.IsNil(obj) { + stream.WriteNil() + return + } + marshaler := (obj).(encoding.TextMarshaler) + bytes, err := marshaler.MarshalText() + if err != nil { + stream.Error = err + } else { + str := string(bytes) + encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) + } +} + +func (encoder *textMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type directTextMarshalerEncoder struct { + stringEncoder ValEncoder + checkIsEmpty checkIsEmpty +} + +func (encoder *directTextMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + marshaler := *(*encoding.TextMarshaler)(ptr) + if marshaler == nil { + stream.WriteNil() + return + } + bytes, err := marshaler.MarshalText() + if err != nil { + stream.Error = err + } else { + str := string(bytes) + encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) + } +} + +func (encoder *directTextMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type unmarshalerDecoder struct { + valType reflect2.Type +} + +func (decoder *unmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valType := decoder.valType + obj := valType.UnsafeIndirect(ptr) + unmarshaler := obj.(json.Unmarshaler) + iter.nextToken() + iter.unreadByte() // skip spaces + bytes := iter.SkipAndReturnBytes() + err := unmarshaler.UnmarshalJSON(bytes) + if err != nil { + iter.ReportError("unmarshalerDecoder", err.Error()) + } +} + +type textUnmarshalerDecoder struct { + valType reflect2.Type +} + +func (decoder *textUnmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valType := decoder.valType + obj := valType.UnsafeIndirect(ptr) + if reflect2.IsNil(obj) { + ptrType := valType.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + elem := elemType.UnsafeNew() + ptrType.UnsafeSet(ptr, unsafe.Pointer(&elem)) + obj = valType.UnsafeIndirect(ptr) + } + unmarshaler := (obj).(encoding.TextUnmarshaler) + str := iter.ReadString() + err := unmarshaler.UnmarshalText([]byte(str)) + if err != nil { + iter.ReportError("textUnmarshalerDecoder", err.Error()) + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_native.go b/vendor/github.com/json-iterator/go/reflect_native.go new file mode 100644 index 0000000000..7f1e2464d2 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_native.go @@ -0,0 +1,455 @@ +package jsoniter + +import ( + "encoding/base64" + "github.com/modern-go/reflect2" + "reflect" + "strconv" + "unsafe" +) + +const ptrSize = 32 << uintptr(^uintptr(0)>>63) + +func createEncoderOfNative(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { + sliceDecoder := decoderOfSlice(ctx, typ) + return &base64Codec{sliceDecoder: sliceDecoder} + } + typeName := typ.String() + kind := typ.Kind() + switch kind { + case reflect.String: + if typeName != "string" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) + } + return &stringCodec{} + case reflect.Int: + if typeName != "int" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &int32Codec{} + } + return &int64Codec{} + case reflect.Int8: + if typeName != "int8" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) + } + return &int8Codec{} + case reflect.Int16: + if typeName != "int16" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) + } + return &int16Codec{} + case reflect.Int32: + if typeName != "int32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) + } + return &int32Codec{} + case reflect.Int64: + if typeName != "int64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) + } + return &int64Codec{} + case reflect.Uint: + if typeName != "uint" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint8: + if typeName != "uint8" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) + } + return &uint8Codec{} + case reflect.Uint16: + if typeName != "uint16" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) + } + return &uint16Codec{} + case reflect.Uint32: + if typeName != "uint32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) + } + return &uint32Codec{} + case reflect.Uintptr: + if typeName != "uintptr" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) + } + if ptrSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint64: + if typeName != "uint64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) + } + return &uint64Codec{} + case reflect.Float32: + if typeName != "float32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) + } + return &float32Codec{} + case reflect.Float64: + if typeName != "float64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) + } + return &float64Codec{} + case reflect.Bool: + if typeName != "bool" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) + } + return &boolCodec{} + } + return nil +} + +func createDecoderOfNative(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { + sliceDecoder := decoderOfSlice(ctx, typ) + return &base64Codec{sliceDecoder: sliceDecoder} + } + typeName := typ.String() + switch typ.Kind() { + case reflect.String: + if typeName != "string" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) + } + return &stringCodec{} + case reflect.Int: + if typeName != "int" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &int32Codec{} + } + return &int64Codec{} + case reflect.Int8: + if typeName != "int8" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) + } + return &int8Codec{} + case reflect.Int16: + if typeName != "int16" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) + } + return &int16Codec{} + case reflect.Int32: + if typeName != "int32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) + } + return &int32Codec{} + case reflect.Int64: + if typeName != "int64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) + } + return &int64Codec{} + case reflect.Uint: + if typeName != "uint" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint8: + if typeName != "uint8" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) + } + return &uint8Codec{} + case reflect.Uint16: + if typeName != "uint16" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) + } + return &uint16Codec{} + case reflect.Uint32: + if typeName != "uint32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) + } + return &uint32Codec{} + case reflect.Uintptr: + if typeName != "uintptr" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) + } + if ptrSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint64: + if typeName != "uint64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) + } + return &uint64Codec{} + case reflect.Float32: + if typeName != "float32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) + } + return &float32Codec{} + case reflect.Float64: + if typeName != "float64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) + } + return &float64Codec{} + case reflect.Bool: + if typeName != "bool" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) + } + return &boolCodec{} + } + return nil +} + +type stringCodec struct { +} + +func (codec *stringCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *((*string)(ptr)) = iter.ReadString() +} + +func (codec *stringCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + str := *((*string)(ptr)) + stream.WriteString(str) +} + +func (codec *stringCodec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*string)(ptr)) == "" +} + +type int8Codec struct { +} + +func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int8)(ptr)) = iter.ReadInt8() + } +} + +func (codec *int8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt8(*((*int8)(ptr))) +} + +func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int8)(ptr)) == 0 +} + +type int16Codec struct { +} + +func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int16)(ptr)) = iter.ReadInt16() + } +} + +func (codec *int16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt16(*((*int16)(ptr))) +} + +func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int16)(ptr)) == 0 +} + +type int32Codec struct { +} + +func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int32)(ptr)) = iter.ReadInt32() + } +} + +func (codec *int32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt32(*((*int32)(ptr))) +} + +func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int32)(ptr)) == 0 +} + +type int64Codec struct { +} + +func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int64)(ptr)) = iter.ReadInt64() + } +} + +func (codec *int64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt64(*((*int64)(ptr))) +} + +func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int64)(ptr)) == 0 +} + +type uint8Codec struct { +} + +func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint8)(ptr)) = iter.ReadUint8() + } +} + +func (codec *uint8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint8(*((*uint8)(ptr))) +} + +func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint8)(ptr)) == 0 +} + +type uint16Codec struct { +} + +func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint16)(ptr)) = iter.ReadUint16() + } +} + +func (codec *uint16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint16(*((*uint16)(ptr))) +} + +func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint16)(ptr)) == 0 +} + +type uint32Codec struct { +} + +func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint32)(ptr)) = iter.ReadUint32() + } +} + +func (codec *uint32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint32(*((*uint32)(ptr))) +} + +func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint32)(ptr)) == 0 +} + +type uint64Codec struct { +} + +func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint64)(ptr)) = iter.ReadUint64() + } +} + +func (codec *uint64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint64(*((*uint64)(ptr))) +} + +func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint64)(ptr)) == 0 +} + +type float32Codec struct { +} + +func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*float32)(ptr)) = iter.ReadFloat32() + } +} + +func (codec *float32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat32(*((*float32)(ptr))) +} + +func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float32)(ptr)) == 0 +} + +type float64Codec struct { +} + +func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*float64)(ptr)) = iter.ReadFloat64() + } +} + +func (codec *float64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat64(*((*float64)(ptr))) +} + +func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float64)(ptr)) == 0 +} + +type boolCodec struct { +} + +func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*bool)(ptr)) = iter.ReadBool() + } +} + +func (codec *boolCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteBool(*((*bool)(ptr))) +} + +func (codec *boolCodec) IsEmpty(ptr unsafe.Pointer) bool { + return !(*((*bool)(ptr))) +} + +type base64Codec struct { + sliceType *reflect2.UnsafeSliceType + sliceDecoder ValDecoder +} + +func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + codec.sliceType.UnsafeSetNil(ptr) + return + } + switch iter.WhatIsNext() { + case StringValue: + encoding := base64.StdEncoding + src := iter.SkipAndReturnBytes() + src = src[1 : len(src)-1] + decodedLen := encoding.DecodedLen(len(src)) + dst := make([]byte, decodedLen) + len, err := encoding.Decode(dst, src) + if err != nil { + iter.ReportError("decode base64", err.Error()) + } else { + dst = dst[:len] + codec.sliceType.UnsafeSet(ptr, unsafe.Pointer(&dst)) + } + case ArrayValue: + codec.sliceDecoder.Decode(ptr, iter) + default: + iter.ReportError("base64Codec", "invalid input") + } +} + +func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + src := *((*[]byte)(ptr)) + if len(src) == 0 { + stream.WriteNil() + return + } + encoding := base64.StdEncoding + stream.writeByte('"') + size := encoding.EncodedLen(len(src)) + buf := make([]byte, size) + encoding.Encode(buf, src) + stream.buf = append(stream.buf, buf...) + stream.writeByte('"') +} + +func (codec *base64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*[]byte)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_optional.go b/vendor/github.com/json-iterator/go/reflect_optional.go new file mode 100644 index 0000000000..43ec71d6da --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_optional.go @@ -0,0 +1,133 @@ +package jsoniter + +import ( + "github.com/modern-go/reflect2" + "reflect" + "unsafe" +) + +func decoderOfOptional(ctx *ctx, typ reflect2.Type) ValDecoder { + ptrType := typ.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + decoder := decoderOfType(ctx, elemType) + if ctx.prefix == "" && elemType.Kind() == reflect.Ptr { + return &dereferenceDecoder{elemType, decoder} + } + return &OptionalDecoder{elemType, decoder} +} + +func encoderOfOptional(ctx *ctx, typ reflect2.Type) ValEncoder { + ptrType := typ.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + elemEncoder := encoderOfType(ctx, elemType) + encoder := &OptionalEncoder{elemEncoder} + return encoder +} + +type OptionalDecoder struct { + ValueType reflect2.Type + ValueDecoder ValDecoder +} + +func (decoder *OptionalDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*unsafe.Pointer)(ptr)) = nil + } else { + if *((*unsafe.Pointer)(ptr)) == nil { + //pointer to null, we have to allocate memory to hold the value + newPtr := decoder.ValueType.UnsafeNew() + decoder.ValueDecoder.Decode(newPtr, iter) + *((*unsafe.Pointer)(ptr)) = newPtr + } else { + //reuse existing instance + decoder.ValueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) + } + } +} + +type dereferenceDecoder struct { + // only to deference a pointer + valueType reflect2.Type + valueDecoder ValDecoder +} + +func (decoder *dereferenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if *((*unsafe.Pointer)(ptr)) == nil { + //pointer to null, we have to allocate memory to hold the value + newPtr := decoder.valueType.UnsafeNew() + decoder.valueDecoder.Decode(newPtr, iter) + *((*unsafe.Pointer)(ptr)) = newPtr + } else { + //reuse existing instance + decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) + } +} + +type OptionalEncoder struct { + ValueEncoder ValEncoder +} + +func (encoder *OptionalEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*unsafe.Pointer)(ptr)) == nil { + stream.WriteNil() + } else { + encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) + } +} + +func (encoder *OptionalEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*unsafe.Pointer)(ptr)) == nil +} + +type dereferenceEncoder struct { + ValueEncoder ValEncoder +} + +func (encoder *dereferenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*unsafe.Pointer)(ptr)) == nil { + stream.WriteNil() + } else { + encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) + } +} + +func (encoder *dereferenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + dePtr := *((*unsafe.Pointer)(ptr)) + if dePtr == nil { + return true + } + return encoder.ValueEncoder.IsEmpty(dePtr) +} + +func (encoder *dereferenceEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { + deReferenced := *((*unsafe.Pointer)(ptr)) + if deReferenced == nil { + return true + } + isEmbeddedPtrNil, converted := encoder.ValueEncoder.(IsEmbeddedPtrNil) + if !converted { + return false + } + fieldPtr := unsafe.Pointer(deReferenced) + return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) +} + +type referenceEncoder struct { + encoder ValEncoder +} + +func (encoder *referenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) +} + +func (encoder *referenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) +} + +type referenceDecoder struct { + decoder ValDecoder +} + +func (decoder *referenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.decoder.Decode(unsafe.Pointer(&ptr), iter) +} diff --git a/vendor/github.com/json-iterator/go/reflect_slice.go b/vendor/github.com/json-iterator/go/reflect_slice.go new file mode 100644 index 0000000000..9441d79df3 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_slice.go @@ -0,0 +1,99 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "unsafe" +) + +func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder { + sliceType := typ.(*reflect2.UnsafeSliceType) + decoder := decoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) + return &sliceDecoder{sliceType, decoder} +} + +func encoderOfSlice(ctx *ctx, typ reflect2.Type) ValEncoder { + sliceType := typ.(*reflect2.UnsafeSliceType) + encoder := encoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) + return &sliceEncoder{sliceType, encoder} +} + +type sliceEncoder struct { + sliceType *reflect2.UnsafeSliceType + elemEncoder ValEncoder +} + +func (encoder *sliceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if encoder.sliceType.UnsafeIsNil(ptr) { + stream.WriteNil() + return + } + length := encoder.sliceType.UnsafeLengthOf(ptr) + if length == 0 { + stream.WriteEmptyArray() + return + } + stream.WriteArrayStart() + encoder.elemEncoder.Encode(encoder.sliceType.UnsafeGetIndex(ptr, 0), stream) + for i := 1; i < length; i++ { + stream.WriteMore() + elemPtr := encoder.sliceType.UnsafeGetIndex(ptr, i) + encoder.elemEncoder.Encode(elemPtr, stream) + } + stream.WriteArrayEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v: %s", encoder.sliceType, stream.Error.Error()) + } +} + +func (encoder *sliceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.sliceType.UnsafeLengthOf(ptr) == 0 +} + +type sliceDecoder struct { + sliceType *reflect2.UnsafeSliceType + elemDecoder ValDecoder +} + +func (decoder *sliceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.doDecode(ptr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v: %s", decoder.sliceType, iter.Error.Error()) + } +} + +func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + sliceType := decoder.sliceType + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + sliceType.UnsafeSetNil(ptr) + return + } + if c != '[' { + iter.ReportError("decode slice", "expect [ or n, but found "+string([]byte{c})) + return + } + c = iter.nextToken() + if c == ']' { + sliceType.UnsafeSet(ptr, sliceType.UnsafeMakeSlice(0, 0)) + return + } + iter.unreadByte() + sliceType.UnsafeGrow(ptr, 1) + elemPtr := sliceType.UnsafeGetIndex(ptr, 0) + decoder.elemDecoder.Decode(elemPtr, iter) + length := 1 + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + idx := length + length += 1 + sliceType.UnsafeGrow(ptr, length) + elemPtr = sliceType.UnsafeGetIndex(ptr, idx) + decoder.elemDecoder.Decode(elemPtr, iter) + } + if c != ']' { + iter.ReportError("decode slice", "expect ], but found "+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/feature_reflect_struct_decoder.go b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go similarity index 68% rename from vendor/github.com/json-iterator/go/feature_reflect_struct_decoder.go rename to vendor/github.com/json-iterator/go/reflect_struct_decoder.go index b3417fd73a..e718722aff 100644 --- a/vendor/github.com/json-iterator/go/feature_reflect_struct_decoder.go +++ b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go @@ -2,39 +2,68 @@ package jsoniter import ( "fmt" + "github.com/modern-go/reflect2" "io" - "reflect" "strings" "unsafe" ) -func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder) (ValDecoder, error) { - knownHash := map[int32]struct{}{ +func decoderOfStruct(ctx *ctx, typ reflect2.Type) ValDecoder { + bindings := map[string]*Binding{} + structDescriptor := describeStruct(ctx, typ) + for _, binding := range structDescriptor.Fields { + for _, fromName := range binding.FromNames { + old := bindings[fromName] + if old == nil { + bindings[fromName] = binding + continue + } + ignoreOld, ignoreNew := resolveConflictBinding(ctx.frozenConfig, old, binding) + if ignoreOld { + delete(bindings, fromName) + } + if !ignoreNew { + bindings[fromName] = binding + } + } + } + fields := map[string]*structFieldDecoder{} + for k, binding := range bindings { + fields[k] = binding.Decoder.(*structFieldDecoder) + } + return createStructDecoder(ctx, typ, fields) +} + +func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structFieldDecoder) ValDecoder { + if ctx.disallowUnknownFields { + return &generalStructDecoder{typ: typ, fields: fields, disallowUnknownFields: true} + } + knownHash := map[int64]struct{}{ 0: {}, } switch len(fields) { case 0: - return &skipObjectDecoder{typ}, nil + return &skipObjectDecoder{typ} case 1: for fieldName, fieldDecoder := range fields { fieldHash := calcHash(fieldName) _, known := knownHash[fieldHash] if known { - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } knownHash[fieldHash] = struct{}{} - return &oneFieldStructDecoder{typ, fieldHash, fieldDecoder}, nil + return &oneFieldStructDecoder{typ, fieldHash, fieldDecoder} } case 2: - var fieldHash1 int32 - var fieldHash2 int32 + var fieldHash1 int64 + var fieldHash2 int64 var fieldDecoder1 *structFieldDecoder var fieldDecoder2 *structFieldDecoder for fieldName, fieldDecoder := range fields { fieldHash := calcHash(fieldName) _, known := knownHash[fieldHash] if known { - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } knownHash[fieldHash] = struct{}{} if fieldHash1 == 0 { @@ -45,11 +74,11 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder fieldDecoder2 = fieldDecoder } } - return &twoFieldsStructDecoder{typ, fieldHash1, fieldDecoder1, fieldHash2, fieldDecoder2}, nil + return &twoFieldsStructDecoder{typ, fieldHash1, fieldDecoder1, fieldHash2, fieldDecoder2} case 3: - var fieldName1 int32 - var fieldName2 int32 - var fieldName3 int32 + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 var fieldDecoder1 *structFieldDecoder var fieldDecoder2 *structFieldDecoder var fieldDecoder3 *structFieldDecoder @@ -57,7 +86,7 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder fieldHash := calcHash(fieldName) _, known := knownHash[fieldHash] if known { - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } knownHash[fieldHash] = struct{}{} if fieldName1 == 0 { @@ -72,12 +101,14 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder } } return &threeFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3}, nil + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3} case 4: - var fieldName1 int32 - var fieldName2 int32 - var fieldName3 int32 - var fieldName4 int32 + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 var fieldDecoder1 *structFieldDecoder var fieldDecoder2 *structFieldDecoder var fieldDecoder3 *structFieldDecoder @@ -86,7 +117,7 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder fieldHash := calcHash(fieldName) _, known := knownHash[fieldHash] if known { - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } knownHash[fieldHash] = struct{}{} if fieldName1 == 0 { @@ -104,14 +135,16 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder } } return &fourFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4}, nil + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4} case 5: - var fieldName1 int32 - var fieldName2 int32 - var fieldName3 int32 - var fieldName4 int32 - var fieldName5 int32 + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 var fieldDecoder1 *structFieldDecoder var fieldDecoder2 *structFieldDecoder var fieldDecoder3 *structFieldDecoder @@ -121,7 +154,7 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder fieldHash := calcHash(fieldName) _, known := knownHash[fieldHash] if known { - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } knownHash[fieldHash] = struct{}{} if fieldName1 == 0 { @@ -142,15 +175,18 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder } } return &fiveFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, fieldName5, fieldDecoder5}, nil + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5} case 6: - var fieldName1 int32 - var fieldName2 int32 - var fieldName3 int32 - var fieldName4 int32 - var fieldName5 int32 - var fieldName6 int32 + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 var fieldDecoder1 *structFieldDecoder var fieldDecoder2 *structFieldDecoder var fieldDecoder3 *structFieldDecoder @@ -161,7 +197,7 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder fieldHash := calcHash(fieldName) _, known := knownHash[fieldHash] if known { - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } knownHash[fieldHash] = struct{}{} if fieldName1 == 0 { @@ -185,16 +221,20 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder } } return &sixFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6}, nil + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6} case 7: - var fieldName1 int32 - var fieldName2 int32 - var fieldName3 int32 - var fieldName4 int32 - var fieldName5 int32 - var fieldName6 int32 - var fieldName7 int32 + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 var fieldDecoder1 *structFieldDecoder var fieldDecoder2 *structFieldDecoder var fieldDecoder3 *structFieldDecoder @@ -206,7 +246,7 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder fieldHash := calcHash(fieldName) _, known := knownHash[fieldHash] if known { - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } knownHash[fieldHash] = struct{}{} if fieldName1 == 0 { @@ -233,18 +273,22 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder } } return &sevenFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7}, nil + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7} case 8: - var fieldName1 int32 - var fieldName2 int32 - var fieldName3 int32 - var fieldName4 int32 - var fieldName5 int32 - var fieldName6 int32 - var fieldName7 int32 - var fieldName8 int32 + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 var fieldDecoder1 *structFieldDecoder var fieldDecoder2 *structFieldDecoder var fieldDecoder3 *structFieldDecoder @@ -257,7 +301,7 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder fieldHash := calcHash(fieldName) _, known := knownHash[fieldHash] if known { - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } knownHash[fieldHash] = struct{}{} if fieldName1 == 0 { @@ -287,19 +331,24 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder } } return &eightFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7, fieldName8, fieldDecoder8}, nil + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8} case 9: - var fieldName1 int32 - var fieldName2 int32 - var fieldName3 int32 - var fieldName4 int32 - var fieldName5 int32 - var fieldName6 int32 - var fieldName7 int32 - var fieldName8 int32 - var fieldName9 int32 + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldName9 int64 var fieldDecoder1 *structFieldDecoder var fieldDecoder2 *structFieldDecoder var fieldDecoder3 *structFieldDecoder @@ -313,7 +362,7 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder fieldHash := calcHash(fieldName) _, known := knownHash[fieldHash] if known { - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } knownHash[fieldHash] = struct{}{} if fieldName1 == 0 { @@ -346,20 +395,26 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder } } return &nineFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7, fieldName8, fieldDecoder8, fieldName9, fieldDecoder9}, nil + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8, + fieldName9, fieldDecoder9} case 10: - var fieldName1 int32 - var fieldName2 int32 - var fieldName3 int32 - var fieldName4 int32 - var fieldName5 int32 - var fieldName6 int32 - var fieldName7 int32 - var fieldName8 int32 - var fieldName9 int32 - var fieldName10 int32 + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldName9 int64 + var fieldName10 int64 var fieldDecoder1 *structFieldDecoder var fieldDecoder2 *structFieldDecoder var fieldDecoder3 *structFieldDecoder @@ -374,7 +429,7 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder fieldHash := calcHash(fieldName) _, known := knownHash[fieldHash] if known { - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } knownHash[fieldHash] = struct{}{} if fieldName1 == 0 { @@ -410,48 +465,77 @@ func createStructDecoder(typ reflect.Type, fields map[string]*structFieldDecoder } } return &tenFieldsStructDecoder{typ, - fieldName1, fieldDecoder1, fieldName2, fieldDecoder2, fieldName3, fieldDecoder3, - fieldName4, fieldDecoder4, fieldName5, fieldDecoder5, fieldName6, fieldDecoder6, - fieldName7, fieldDecoder7, fieldName8, fieldDecoder8, fieldName9, fieldDecoder9, - fieldName10, fieldDecoder10}, nil + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8, + fieldName9, fieldDecoder9, + fieldName10, fieldDecoder10} } - return &generalStructDecoder{typ, fields}, nil + return &generalStructDecoder{typ, fields, false} } type generalStructDecoder struct { - typ reflect.Type - fields map[string]*structFieldDecoder + typ reflect2.Type + fields map[string]*structFieldDecoder + disallowUnknownFields bool } func (decoder *generalStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { if !iter.readObjectStart() { return } - fieldBytes := iter.readObjectFieldAsBytes() - field := *(*string)(unsafe.Pointer(&fieldBytes)) - fieldDecoder := decoder.fields[strings.ToLower(field)] - if fieldDecoder == nil { - iter.Skip() - } else { - fieldDecoder.Decode(ptr, iter) - } + decoder.decodeOneField(ptr, iter) for iter.nextToken() == ',' { - fieldBytes = iter.readObjectFieldAsBytes() + decoder.decodeOneField(ptr, iter) + } + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } +} + +func (decoder *generalStructDecoder) decodeOneField(ptr unsafe.Pointer, iter *Iterator) { + var field string + var fieldDecoder *structFieldDecoder + if iter.cfg.objectFieldMustBeSimpleString { + fieldBytes := iter.ReadStringAsSlice() field = *(*string)(unsafe.Pointer(&fieldBytes)) - fieldDecoder = decoder.fields[strings.ToLower(field)] + fieldDecoder = decoder.fields[field] if fieldDecoder == nil { - iter.Skip() - } else { - fieldDecoder.Decode(ptr, iter) + fieldDecoder = decoder.fields[strings.ToLower(field)] + } + } else { + field = iter.ReadString() + fieldDecoder = decoder.fields[field] + if fieldDecoder == nil { + fieldDecoder = decoder.fields[strings.ToLower(field)] } } - if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + if fieldDecoder == nil { + msg := "found unknown field: " + field + if decoder.disallowUnknownFields { + iter.ReportError("ReadObject", msg) + } + c := iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + iter.Skip() + return + } + c := iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) } + fieldDecoder.Decode(ptr, iter) } type skipObjectDecoder struct { - typ reflect.Type + typ reflect2.Type } func (decoder *skipObjectDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { @@ -464,8 +548,8 @@ func (decoder *skipObjectDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { } type oneFieldStructDecoder struct { - typ reflect.Type - fieldHash int32 + typ reflect2.Type + fieldHash int64 fieldDecoder *structFieldDecoder } @@ -484,15 +568,15 @@ func (decoder *oneFieldStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) } } if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) } } type twoFieldsStructDecoder struct { - typ reflect.Type - fieldHash1 int32 + typ reflect2.Type + fieldHash1 int64 fieldDecoder1 *structFieldDecoder - fieldHash2 int32 + fieldHash2 int64 fieldDecoder2 *structFieldDecoder } @@ -514,17 +598,17 @@ func (decoder *twoFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator } } if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) } } type threeFieldsStructDecoder struct { - typ reflect.Type - fieldHash1 int32 + typ reflect2.Type + fieldHash1 int64 fieldDecoder1 *structFieldDecoder - fieldHash2 int32 + fieldHash2 int64 fieldDecoder2 *structFieldDecoder - fieldHash3 int32 + fieldHash3 int64 fieldDecoder3 *structFieldDecoder } @@ -548,19 +632,19 @@ func (decoder *threeFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterat } } if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) } } type fourFieldsStructDecoder struct { - typ reflect.Type - fieldHash1 int32 + typ reflect2.Type + fieldHash1 int64 fieldDecoder1 *structFieldDecoder - fieldHash2 int32 + fieldHash2 int64 fieldDecoder2 *structFieldDecoder - fieldHash3 int32 + fieldHash3 int64 fieldDecoder3 *structFieldDecoder - fieldHash4 int32 + fieldHash4 int64 fieldDecoder4 *structFieldDecoder } @@ -586,21 +670,21 @@ func (decoder *fourFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterato } } if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) } } type fiveFieldsStructDecoder struct { - typ reflect.Type - fieldHash1 int32 + typ reflect2.Type + fieldHash1 int64 fieldDecoder1 *structFieldDecoder - fieldHash2 int32 + fieldHash2 int64 fieldDecoder2 *structFieldDecoder - fieldHash3 int32 + fieldHash3 int64 fieldDecoder3 *structFieldDecoder - fieldHash4 int32 + fieldHash4 int64 fieldDecoder4 *structFieldDecoder - fieldHash5 int32 + fieldHash5 int64 fieldDecoder5 *structFieldDecoder } @@ -628,23 +712,23 @@ func (decoder *fiveFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterato } } if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) } } type sixFieldsStructDecoder struct { - typ reflect.Type - fieldHash1 int32 + typ reflect2.Type + fieldHash1 int64 fieldDecoder1 *structFieldDecoder - fieldHash2 int32 + fieldHash2 int64 fieldDecoder2 *structFieldDecoder - fieldHash3 int32 + fieldHash3 int64 fieldDecoder3 *structFieldDecoder - fieldHash4 int32 + fieldHash4 int64 fieldDecoder4 *structFieldDecoder - fieldHash5 int32 + fieldHash5 int64 fieldDecoder5 *structFieldDecoder - fieldHash6 int32 + fieldHash6 int64 fieldDecoder6 *structFieldDecoder } @@ -674,25 +758,25 @@ func (decoder *sixFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator } } if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) } } type sevenFieldsStructDecoder struct { - typ reflect.Type - fieldHash1 int32 + typ reflect2.Type + fieldHash1 int64 fieldDecoder1 *structFieldDecoder - fieldHash2 int32 + fieldHash2 int64 fieldDecoder2 *structFieldDecoder - fieldHash3 int32 + fieldHash3 int64 fieldDecoder3 *structFieldDecoder - fieldHash4 int32 + fieldHash4 int64 fieldDecoder4 *structFieldDecoder - fieldHash5 int32 + fieldHash5 int64 fieldDecoder5 *structFieldDecoder - fieldHash6 int32 + fieldHash6 int64 fieldDecoder6 *structFieldDecoder - fieldHash7 int32 + fieldHash7 int64 fieldDecoder7 *structFieldDecoder } @@ -724,27 +808,27 @@ func (decoder *sevenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterat } } if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) } } type eightFieldsStructDecoder struct { - typ reflect.Type - fieldHash1 int32 + typ reflect2.Type + fieldHash1 int64 fieldDecoder1 *structFieldDecoder - fieldHash2 int32 + fieldHash2 int64 fieldDecoder2 *structFieldDecoder - fieldHash3 int32 + fieldHash3 int64 fieldDecoder3 *structFieldDecoder - fieldHash4 int32 + fieldHash4 int64 fieldDecoder4 *structFieldDecoder - fieldHash5 int32 + fieldHash5 int64 fieldDecoder5 *structFieldDecoder - fieldHash6 int32 + fieldHash6 int64 fieldDecoder6 *structFieldDecoder - fieldHash7 int32 + fieldHash7 int64 fieldDecoder7 *structFieldDecoder - fieldHash8 int32 + fieldHash8 int64 fieldDecoder8 *structFieldDecoder } @@ -778,29 +862,29 @@ func (decoder *eightFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterat } } if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) } } type nineFieldsStructDecoder struct { - typ reflect.Type - fieldHash1 int32 + typ reflect2.Type + fieldHash1 int64 fieldDecoder1 *structFieldDecoder - fieldHash2 int32 + fieldHash2 int64 fieldDecoder2 *structFieldDecoder - fieldHash3 int32 + fieldHash3 int64 fieldDecoder3 *structFieldDecoder - fieldHash4 int32 + fieldHash4 int64 fieldDecoder4 *structFieldDecoder - fieldHash5 int32 + fieldHash5 int64 fieldDecoder5 *structFieldDecoder - fieldHash6 int32 + fieldHash6 int64 fieldDecoder6 *structFieldDecoder - fieldHash7 int32 + fieldHash7 int64 fieldDecoder7 *structFieldDecoder - fieldHash8 int32 + fieldHash8 int64 fieldDecoder8 *structFieldDecoder - fieldHash9 int32 + fieldHash9 int64 fieldDecoder9 *structFieldDecoder } @@ -836,31 +920,31 @@ func (decoder *nineFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterato } } if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) } } type tenFieldsStructDecoder struct { - typ reflect.Type - fieldHash1 int32 + typ reflect2.Type + fieldHash1 int64 fieldDecoder1 *structFieldDecoder - fieldHash2 int32 + fieldHash2 int64 fieldDecoder2 *structFieldDecoder - fieldHash3 int32 + fieldHash3 int64 fieldDecoder3 *structFieldDecoder - fieldHash4 int32 + fieldHash4 int64 fieldDecoder4 *structFieldDecoder - fieldHash5 int32 + fieldHash5 int64 fieldDecoder5 *structFieldDecoder - fieldHash6 int32 + fieldHash6 int64 fieldDecoder6 *structFieldDecoder - fieldHash7 int32 + fieldHash7 int64 fieldDecoder7 *structFieldDecoder - fieldHash8 int32 + fieldHash8 int64 fieldDecoder8 *structFieldDecoder - fieldHash9 int32 + fieldHash9 int64 fieldDecoder9 *structFieldDecoder - fieldHash10 int32 + fieldHash10 int64 fieldDecoder10 *structFieldDecoder } @@ -898,19 +982,53 @@ func (decoder *tenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator } } if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%v: %s", decoder.typ, iter.Error.Error()) + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) } } type structFieldDecoder struct { - field *reflect.StructField + field reflect2.StructField fieldDecoder ValDecoder } func (decoder *structFieldDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { - fieldPtr := unsafe.Pointer(uintptr(ptr) + decoder.field.Offset) + fieldPtr := decoder.field.UnsafeGet(ptr) decoder.fieldDecoder.Decode(fieldPtr, iter) if iter.Error != nil && iter.Error != io.EOF { - iter.Error = fmt.Errorf("%s: %s", decoder.field.Name, iter.Error.Error()) + iter.Error = fmt.Errorf("%s: %s", decoder.field.Name(), iter.Error.Error()) + } +} + +type stringModeStringDecoder struct { + elemDecoder ValDecoder + cfg *frozenConfig +} + +func (decoder *stringModeStringDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.elemDecoder.Decode(ptr, iter) + str := *((*string)(ptr)) + tempIter := decoder.cfg.BorrowIterator([]byte(str)) + defer decoder.cfg.ReturnIterator(tempIter) + *((*string)(ptr)) = tempIter.ReadString() +} + +type stringModeNumberDecoder struct { + elemDecoder ValDecoder +} + +func (decoder *stringModeNumberDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + if c != '"' { + iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) + return + } + decoder.elemDecoder.Decode(ptr, iter) + if iter.Error != nil { + return + } + c = iter.readByte() + if c != '"' { + iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) + return } } diff --git a/vendor/github.com/json-iterator/go/feature_reflect_object.go b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go similarity index 50% rename from vendor/github.com/json-iterator/go/feature_reflect_object.go rename to vendor/github.com/json-iterator/go/reflect_struct_encoder.go index 59b1235c0d..d0759cf641 100644 --- a/vendor/github.com/json-iterator/go/feature_reflect_object.go +++ b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go @@ -2,23 +2,20 @@ package jsoniter import ( "fmt" + "github.com/modern-go/reflect2" "io" "reflect" - "strings" "unsafe" ) -func encoderOfStruct(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { +func encoderOfStruct(ctx *ctx, typ reflect2.Type) ValEncoder { type bindingTo struct { binding *Binding toName string ignored bool } orderedBindings := []*bindingTo{} - structDescriptor, err := describeStruct(cfg, typ) - if err != nil { - return nil, err - } + structDescriptor := describeStruct(ctx, typ) for _, binding := range structDescriptor.Fields { for _, toName := range binding.ToNames { new := &bindingTo{ @@ -29,13 +26,13 @@ func encoderOfStruct(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { if old.toName != toName { continue } - old.ignored, new.ignored = resolveConflictBinding(cfg, old.binding, new.binding) + old.ignored, new.ignored = resolveConflictBinding(ctx.frozenConfig, old.binding, new.binding) } orderedBindings = append(orderedBindings, new) } } if len(orderedBindings) == 0 { - return &emptyStructEncoder{}, nil + return &emptyStructEncoder{} } finalOrderedFields := []structFieldTo{} for _, bindingTo := range orderedBindings { @@ -46,12 +43,36 @@ func encoderOfStruct(cfg *frozenConfig, typ reflect.Type) (ValEncoder, error) { }) } } - return &structEncoder{structDescriptor.onePtrEmbedded, structDescriptor.onePtrOptimization, finalOrderedFields}, nil + return &structEncoder{typ, finalOrderedFields} +} + +func createCheckIsEmpty(ctx *ctx, typ reflect2.Type) checkIsEmpty { + encoder := createEncoderOfNative(ctx, typ) + if encoder != nil { + return encoder + } + kind := typ.Kind() + switch kind { + case reflect.Interface: + return &dynamicEncoder{typ} + case reflect.Struct: + return &structEncoder{typ: typ} + case reflect.Array: + return &arrayEncoder{} + case reflect.Slice: + return &sliceEncoder{} + case reflect.Map: + return encoderOfMap(ctx, typ) + case reflect.Ptr: + return &OptionalEncoder{} + default: + return &lazyErrorEncoder{err: fmt.Errorf("unsupported type: %v", typ)} + } } func resolveConflictBinding(cfg *frozenConfig, old, new *Binding) (ignoreOld, ignoreNew bool) { - newTagged := new.Field.Tag.Get(cfg.getTagKey()) != "" - oldTagged := old.Field.Tag.Get(cfg.getTagKey()) != "" + newTagged := new.Field.Tag().Get(cfg.getTagKey()) != "" + oldTagged := old.Field.Tag().Get(cfg.getTagKey()) != "" if newTagged { if oldTagged { if len(old.levels) > len(new.levels) { @@ -78,62 +99,41 @@ func resolveConflictBinding(cfg *frozenConfig, old, new *Binding) (ignoreOld, ig } } -func decoderOfStruct(cfg *frozenConfig, typ reflect.Type) (ValDecoder, error) { - bindings := map[string]*Binding{} - structDescriptor, err := describeStruct(cfg, typ) - if err != nil { - return nil, err - } - for _, binding := range structDescriptor.Fields { - for _, fromName := range binding.FromNames { - old := bindings[fromName] - if old == nil { - bindings[fromName] = binding - continue - } - ignoreOld, ignoreNew := resolveConflictBinding(cfg, old, binding) - if ignoreOld { - delete(bindings, fromName) - } - if !ignoreNew { - bindings[fromName] = binding - } - } - } - fields := map[string]*structFieldDecoder{} - for k, binding := range bindings { - fields[strings.ToLower(k)] = binding.Decoder.(*structFieldDecoder) - } - return createStructDecoder(typ, fields) -} - type structFieldEncoder struct { - field *reflect.StructField + field reflect2.StructField fieldEncoder ValEncoder omitempty bool } func (encoder *structFieldEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { - fieldPtr := unsafe.Pointer(uintptr(ptr) + encoder.field.Offset) + fieldPtr := encoder.field.UnsafeGet(ptr) encoder.fieldEncoder.Encode(fieldPtr, stream) if stream.Error != nil && stream.Error != io.EOF { - stream.Error = fmt.Errorf("%s: %s", encoder.field.Name, stream.Error.Error()) + stream.Error = fmt.Errorf("%s: %s", encoder.field.Name(), stream.Error.Error()) } } -func (encoder *structFieldEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - func (encoder *structFieldEncoder) IsEmpty(ptr unsafe.Pointer) bool { - fieldPtr := unsafe.Pointer(uintptr(ptr) + encoder.field.Offset) + fieldPtr := encoder.field.UnsafeGet(ptr) return encoder.fieldEncoder.IsEmpty(fieldPtr) } +func (encoder *structFieldEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { + isEmbeddedPtrNil, converted := encoder.fieldEncoder.(IsEmbeddedPtrNil) + if !converted { + return false + } + fieldPtr := encoder.field.UnsafeGet(ptr) + return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) +} + +type IsEmbeddedPtrNil interface { + IsEmbeddedPtrNil(ptr unsafe.Pointer) bool +} + type structEncoder struct { - onePtrEmbedded bool - onePtrOptimization bool - fields []structFieldTo + typ reflect2.Type + fields []structFieldTo } type structFieldTo struct { @@ -148,6 +148,9 @@ func (encoder *structEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { if field.encoder.omitempty && field.encoder.IsEmpty(ptr) { continue } + if field.encoder.IsEmbeddedPtrNil(ptr) { + continue + } if isNotFirst { stream.WriteMore() } @@ -156,23 +159,8 @@ func (encoder *structEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { isNotFirst = true } stream.WriteObjectEnd() -} - -func (encoder *structEncoder) EncodeInterface(val interface{}, stream *Stream) { - e := (*emptyInterface)(unsafe.Pointer(&val)) - if encoder.onePtrOptimization { - if e.word == nil && encoder.onePtrEmbedded { - stream.WriteObjectStart() - stream.WriteObjectEnd() - return - } - ptr := uintptr(e.word) - e.word = unsafe.Pointer(&ptr) - } - if reflect.TypeOf(val).Kind() == reflect.Ptr { - encoder.Encode(unsafe.Pointer(&e.word), stream) - } else { - encoder.Encode(e.word, stream) + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v.%s", encoder.typ, stream.Error.Error()) } } @@ -187,10 +175,36 @@ func (encoder *emptyStructEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { stream.WriteEmptyObject() } -func (encoder *emptyStructEncoder) EncodeInterface(val interface{}, stream *Stream) { - WriteToStream(val, stream, encoder) -} - func (encoder *emptyStructEncoder) IsEmpty(ptr unsafe.Pointer) bool { return false } + +type stringModeNumberEncoder struct { + elemEncoder ValEncoder +} + +func (encoder *stringModeNumberEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.writeByte('"') + encoder.elemEncoder.Encode(ptr, stream) + stream.writeByte('"') +} + +func (encoder *stringModeNumberEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.elemEncoder.IsEmpty(ptr) +} + +type stringModeStringEncoder struct { + elemEncoder ValEncoder + cfg *frozenConfig +} + +func (encoder *stringModeStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + tempStream := encoder.cfg.BorrowStream(nil) + defer encoder.cfg.ReturnStream(tempStream) + encoder.elemEncoder.Encode(ptr, tempStream) + stream.WriteString(string(tempStream.Buffer())) +} + +func (encoder *stringModeStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.elemEncoder.IsEmpty(ptr) +} diff --git a/vendor/github.com/json-iterator/go/feature_stream.go b/vendor/github.com/json-iterator/go/stream.go similarity index 60% rename from vendor/github.com/json-iterator/go/feature_stream.go rename to vendor/github.com/json-iterator/go/stream.go index 9323848398..17662fdedc 100644 --- a/vendor/github.com/json-iterator/go/feature_stream.go +++ b/vendor/github.com/json-iterator/go/stream.go @@ -4,15 +4,15 @@ import ( "io" ) -// Stream is a io.Writer like object, with JSON specific write functions. +// stream is a io.Writer like object, with JSON specific write functions. // Error is not returned as return value, but stored as Error member on this stream instance. type Stream struct { - cfg *frozenConfig - out io.Writer - buf []byte - n int - Error error - indention int + cfg *frozenConfig + out io.Writer + buf []byte + Error error + indention int + Attachment interface{} // open for customized encoder } // NewStream create new stream instance. @@ -23,8 +23,7 @@ func NewStream(cfg API, out io.Writer, bufSize int) *Stream { return &Stream{ cfg: cfg.(*frozenConfig), out: out, - buf: make([]byte, bufSize), - n: 0, + buf: make([]byte, 0, bufSize), Error: nil, indention: 0, } @@ -38,22 +37,27 @@ func (stream *Stream) Pool() StreamPool { // Reset reuse this stream instance by assign a new writer func (stream *Stream) Reset(out io.Writer) { stream.out = out - stream.n = 0 + stream.buf = stream.buf[:0] } // Available returns how many bytes are unused in the buffer. func (stream *Stream) Available() int { - return len(stream.buf) - stream.n + return cap(stream.buf) - len(stream.buf) } // Buffered returns the number of bytes that have been written into the current buffer. func (stream *Stream) Buffered() int { - return stream.n + return len(stream.buf) } // Buffer if writer is nil, use this method to take the result func (stream *Stream) Buffer() []byte { - return stream.buf[:stream.n] + return stream.buf +} + +// SetBuffer allows to append to the internal buffer directly +func (stream *Stream) SetBuffer(buf []byte) { + stream.buf = buf } // Write writes the contents of p into the buffer. @@ -61,97 +65,34 @@ func (stream *Stream) Buffer() []byte { // If nn < len(p), it also returns an error explaining // why the write is short. func (stream *Stream) Write(p []byte) (nn int, err error) { - for len(p) > stream.Available() && stream.Error == nil { - if stream.out == nil { - stream.growAtLeast(len(p)) - } else { - var n int - if stream.Buffered() == 0 { - // Large write, empty buffer. - // Write directly from p to avoid copy. - n, stream.Error = stream.out.Write(p) - } else { - n = copy(stream.buf[stream.n:], p) - stream.n += n - stream.Flush() - } - nn += n - p = p[n:] - } - } - if stream.Error != nil { - return nn, stream.Error + stream.buf = append(stream.buf, p...) + if stream.out != nil { + nn, err = stream.out.Write(stream.buf) + stream.buf = stream.buf[nn:] + return } - n := copy(stream.buf[stream.n:], p) - stream.n += n - nn += n - return nn, nil + return len(p), nil } // WriteByte writes a single byte. func (stream *Stream) writeByte(c byte) { - if stream.Error != nil { - return - } - if stream.Available() < 1 { - stream.growAtLeast(1) - } - stream.buf[stream.n] = c - stream.n++ + stream.buf = append(stream.buf, c) } func (stream *Stream) writeTwoBytes(c1 byte, c2 byte) { - if stream.Error != nil { - return - } - if stream.Available() < 2 { - stream.growAtLeast(2) - } - stream.buf[stream.n] = c1 - stream.buf[stream.n+1] = c2 - stream.n += 2 + stream.buf = append(stream.buf, c1, c2) } func (stream *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) { - if stream.Error != nil { - return - } - if stream.Available() < 3 { - stream.growAtLeast(3) - } - stream.buf[stream.n] = c1 - stream.buf[stream.n+1] = c2 - stream.buf[stream.n+2] = c3 - stream.n += 3 + stream.buf = append(stream.buf, c1, c2, c3) } func (stream *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byte) { - if stream.Error != nil { - return - } - if stream.Available() < 4 { - stream.growAtLeast(4) - } - stream.buf[stream.n] = c1 - stream.buf[stream.n+1] = c2 - stream.buf[stream.n+2] = c3 - stream.buf[stream.n+3] = c4 - stream.n += 4 + stream.buf = append(stream.buf, c1, c2, c3, c4) } func (stream *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byte, c5 byte) { - if stream.Error != nil { - return - } - if stream.Available() < 5 { - stream.growAtLeast(5) - } - stream.buf[stream.n] = c1 - stream.buf[stream.n+1] = c2 - stream.buf[stream.n+2] = c3 - stream.buf[stream.n+3] = c4 - stream.buf[stream.n+4] = c5 - stream.n += 5 + stream.buf = append(stream.buf, c1, c2, c3, c4, c5) } // Flush writes any buffered data to the underlying io.Writer. @@ -162,56 +103,20 @@ func (stream *Stream) Flush() error { if stream.Error != nil { return stream.Error } - if stream.n == 0 { - return nil - } - n, err := stream.out.Write(stream.buf[0:stream.n]) - if n < stream.n && err == nil { - err = io.ErrShortWrite - } + n, err := stream.out.Write(stream.buf) if err != nil { - if n > 0 && n < stream.n { - copy(stream.buf[0:stream.n-n], stream.buf[n:stream.n]) + if stream.Error == nil { + stream.Error = err } - stream.n -= n - stream.Error = err return err } - stream.n = 0 + stream.buf = stream.buf[n:] return nil } -func (stream *Stream) ensure(minimal int) { - available := stream.Available() - if available < minimal { - stream.growAtLeast(minimal) - } -} - -func (stream *Stream) growAtLeast(minimal int) { - if stream.out != nil { - stream.Flush() - if stream.Available() >= minimal { - return - } - } - toGrow := len(stream.buf) - if toGrow < minimal { - toGrow = minimal - } - newBuf := make([]byte, len(stream.buf)+toGrow) - copy(newBuf, stream.Buffer()) - stream.buf = newBuf -} - // WriteRaw write string out without quotes, just like []byte func (stream *Stream) WriteRaw(s string) { - stream.ensure(len(s)) - if stream.Error != nil { - return - } - n := copy(stream.buf[stream.n:], s) - stream.n += n + stream.buf = append(stream.buf, s...) } // WriteNil write null to stream @@ -272,6 +177,7 @@ func (stream *Stream) WriteEmptyObject() { func (stream *Stream) WriteMore() { stream.writeByte(',') stream.writeIndention(0) + stream.Flush() } // WriteArrayStart write [ with possible indention @@ -299,9 +205,7 @@ func (stream *Stream) writeIndention(delta int) { } stream.writeByte('\n') toWrite := stream.indention - delta - stream.ensure(toWrite) - for i := 0; i < toWrite && stream.n < len(stream.buf); i++ { - stream.buf[stream.n] = ' ' - stream.n++ + for i := 0; i < toWrite; i++ { + stream.buf = append(stream.buf, ' ') } } diff --git a/vendor/github.com/json-iterator/go/feature_stream_float.go b/vendor/github.com/json-iterator/go/stream_float.go similarity index 85% rename from vendor/github.com/json-iterator/go/feature_stream_float.go rename to vendor/github.com/json-iterator/go/stream_float.go index 9a404e11d4..f318d2c59d 100644 --- a/vendor/github.com/json-iterator/go/feature_stream_float.go +++ b/vendor/github.com/json-iterator/go/stream_float.go @@ -21,7 +21,7 @@ func (stream *Stream) WriteFloat32(val float32) { fmt = 'e' } } - stream.WriteRaw(strconv.FormatFloat(float64(val), fmt, -1, 32)) + stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 32) } // WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster @@ -43,13 +43,12 @@ func (stream *Stream) WriteFloat32Lossy(val float32) { return } stream.writeByte('.') - stream.ensure(10) for p := precision - 1; p > 0 && fval < pow10[p]; p-- { stream.writeByte('0') } stream.WriteUint64(fval) - for stream.buf[stream.n-1] == '0' { - stream.n-- + for stream.buf[len(stream.buf)-1] == '0' { + stream.buf = stream.buf[:len(stream.buf)-1] } } @@ -63,7 +62,7 @@ func (stream *Stream) WriteFloat64(val float64) { fmt = 'e' } } - stream.WriteRaw(strconv.FormatFloat(float64(val), fmt, -1, 64)) + stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 64) } // WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster @@ -85,12 +84,11 @@ func (stream *Stream) WriteFloat64Lossy(val float64) { return } stream.writeByte('.') - stream.ensure(10) for p := precision - 1; p > 0 && fval < pow10[p]; p-- { stream.writeByte('0') } stream.WriteUint64(fval) - for stream.buf[stream.n-1] == '0' { - stream.n-- + for stream.buf[len(stream.buf)-1] == '0' { + stream.buf = stream.buf[:len(stream.buf)-1] } } diff --git a/vendor/github.com/json-iterator/go/stream_int.go b/vendor/github.com/json-iterator/go/stream_int.go new file mode 100644 index 0000000000..d1059ee4c2 --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream_int.go @@ -0,0 +1,190 @@ +package jsoniter + +var digits []uint32 + +func init() { + digits = make([]uint32, 1000) + for i := uint32(0); i < 1000; i++ { + digits[i] = (((i / 100) + '0') << 16) + ((((i / 10) % 10) + '0') << 8) + i%10 + '0' + if i < 10 { + digits[i] += 2 << 24 + } else if i < 100 { + digits[i] += 1 << 24 + } + } +} + +func writeFirstBuf(space []byte, v uint32) []byte { + start := v >> 24 + if start == 0 { + space = append(space, byte(v>>16), byte(v>>8)) + } else if start == 1 { + space = append(space, byte(v>>8)) + } + space = append(space, byte(v)) + return space +} + +func writeBuf(buf []byte, v uint32) []byte { + return append(buf, byte(v>>16), byte(v>>8), byte(v)) +} + +// WriteUint8 write uint8 to stream +func (stream *Stream) WriteUint8(val uint8) { + stream.buf = writeFirstBuf(stream.buf, digits[val]) +} + +// WriteInt8 write int8 to stream +func (stream *Stream) WriteInt8(nval int8) { + var val uint8 + if nval < 0 { + val = uint8(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint8(nval) + } + stream.buf = writeFirstBuf(stream.buf, digits[val]) +} + +// WriteUint16 write uint16 to stream +func (stream *Stream) WriteUint16(val uint16) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return +} + +// WriteInt16 write int16 to stream +func (stream *Stream) WriteInt16(nval int16) { + var val uint16 + if nval < 0 { + val = uint16(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint16(nval) + } + stream.WriteUint16(val) +} + +// WriteUint32 write uint32 to stream +func (stream *Stream) WriteUint32(val uint32) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + q2 := q1 / 1000 + if q2 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r2 := q1 - q2*1000 + q3 := q2 / 1000 + if q3 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q2]) + } else { + r3 := q2 - q3*1000 + stream.buf = append(stream.buf, byte(q3+'0')) + stream.buf = writeBuf(stream.buf, digits[r3]) + } + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) +} + +// WriteInt32 write int32 to stream +func (stream *Stream) WriteInt32(nval int32) { + var val uint32 + if nval < 0 { + val = uint32(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint32(nval) + } + stream.WriteUint32(val) +} + +// WriteUint64 write uint64 to stream +func (stream *Stream) WriteUint64(val uint64) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + q2 := q1 / 1000 + if q2 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r2 := q1 - q2*1000 + q3 := q2 / 1000 + if q3 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q2]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r3 := q2 - q3*1000 + q4 := q3 / 1000 + if q4 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q3]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r4 := q3 - q4*1000 + q5 := q4 / 1000 + if q5 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q4]) + stream.buf = writeBuf(stream.buf, digits[r4]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r5 := q4 - q5*1000 + q6 := q5 / 1000 + if q6 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q5]) + } else { + stream.buf = writeFirstBuf(stream.buf, digits[q6]) + r6 := q5 - q6*1000 + stream.buf = writeBuf(stream.buf, digits[r6]) + } + stream.buf = writeBuf(stream.buf, digits[r5]) + stream.buf = writeBuf(stream.buf, digits[r4]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) +} + +// WriteInt64 write int64 to stream +func (stream *Stream) WriteInt64(nval int64) { + var val uint64 + if nval < 0 { + val = uint64(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint64(nval) + } + stream.WriteUint64(val) +} + +// WriteInt write int to stream +func (stream *Stream) WriteInt(val int) { + stream.WriteInt64(int64(val)) +} + +// WriteUint write uint to stream +func (stream *Stream) WriteUint(val uint) { + stream.WriteUint64(uint64(val)) +} diff --git a/vendor/github.com/json-iterator/go/feature_stream_string.go b/vendor/github.com/json-iterator/go/stream_str.go similarity index 91% rename from vendor/github.com/json-iterator/go/feature_stream_string.go rename to vendor/github.com/json-iterator/go/stream_str.go index 334282f05f..54c2ba0b3a 100644 --- a/vendor/github.com/json-iterator/go/feature_stream_string.go +++ b/vendor/github.com/json-iterator/go/stream_str.go @@ -219,34 +219,22 @@ var hex = "0123456789abcdef" // WriteStringWithHTMLEscaped write string to stream with html special characters escaped func (stream *Stream) WriteStringWithHTMLEscaped(s string) { - stream.ensure(32) valLen := len(s) - toWriteLen := valLen - bufLengthMinusTwo := len(stream.buf) - 2 // make room for the quotes - if stream.n+toWriteLen > bufLengthMinusTwo { - toWriteLen = bufLengthMinusTwo - stream.n - } - n := stream.n - stream.buf[n] = '"' - n++ + stream.buf = append(stream.buf, '"') // write string, the fast path, without utf8 and escape support i := 0 - for ; i < toWriteLen; i++ { + for ; i < valLen; i++ { c := s[i] if c < utf8.RuneSelf && htmlSafeSet[c] { - stream.buf[n] = c - n++ + stream.buf = append(stream.buf, c) } else { break } } if i == valLen { - stream.buf[n] = '"' - n++ - stream.n = n + stream.buf = append(stream.buf, '"') return } - stream.n = n writeStringSlowPathWithHTMLEscaped(stream, i, s, valLen) } @@ -321,34 +309,22 @@ func writeStringSlowPathWithHTMLEscaped(stream *Stream, i int, s string, valLen // WriteString write string to stream without html escape func (stream *Stream) WriteString(s string) { - stream.ensure(32) valLen := len(s) - toWriteLen := valLen - bufLengthMinusTwo := len(stream.buf) - 2 // make room for the quotes - if stream.n+toWriteLen > bufLengthMinusTwo { - toWriteLen = bufLengthMinusTwo - stream.n - } - n := stream.n - stream.buf[n] = '"' - n++ + stream.buf = append(stream.buf, '"') // write string, the fast path, without utf8 and escape support i := 0 - for ; i < toWriteLen; i++ { + for ; i < valLen; i++ { c := s[i] if c > 31 && c != '"' && c != '\\' { - stream.buf[n] = c - n++ + stream.buf = append(stream.buf, c) } else { break } } if i == valLen { - stream.buf[n] = '"' - n++ - stream.n = n + stream.buf = append(stream.buf, '"') return } - stream.n = n writeStringSlowPath(stream, i, s, valLen) } diff --git a/vendor/github.com/json-iterator/go/test.sh b/vendor/github.com/json-iterator/go/test.sh index 466f1141ae..f4e7c0b2c9 100755 --- a/vendor/github.com/json-iterator/go/test.sh +++ b/vendor/github.com/json-iterator/go/test.sh @@ -4,7 +4,7 @@ set -e echo "" > coverage.txt for d in $(go list ./... | grep -v vendor); do - go test -coverprofile=profile.out $d + go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d if [ -f profile.out ]; then cat profile.out >> coverage.txt rm profile.out diff --git a/vendor/github.com/json-iterator/go/unmarshal_input_test.go b/vendor/github.com/json-iterator/go/unmarshal_input_test.go deleted file mode 100644 index 9d7b99c5f9..0000000000 --- a/vendor/github.com/json-iterator/go/unmarshal_input_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package jsoniter - -import ( - "encoding/json" - "reflect" - "testing" - - fuzz "github.com/google/gofuzz" -) - -func Test_NilInput(t *testing.T) { - var jb []byte // nil - var out string - err := Unmarshal(jb, &out) - if err == nil { - t.Errorf("Expected error") - } -} - -func Test_EmptyInput(t *testing.T) { - jb := []byte("") - var out string - err := Unmarshal(jb, &out) - if err == nil { - t.Errorf("Expected error") - } -} - -func Test_RandomInput_Bytes(t *testing.T) { - fz := fuzz.New().NilChance(0) - for i := 0; i < 10000; i++ { - var jb []byte - fz.Fuzz(&jb) - testRandomInput(t, jb) - } -} - -func Test_RandomInput_String(t *testing.T) { - fz := fuzz.New().NilChance(0) - for i := 0; i < 10000; i++ { - var js string - fz.Fuzz(&js) - jb := []byte(js) - testRandomInput(t, jb) - } -} - -func testRandomInput(t *testing.T, jb []byte) { - var outString string - testRandomInputTo(t, jb, &outString) - - var outInt int - testRandomInputTo(t, jb, &outInt) - - var outStruct struct{} - testRandomInputTo(t, jb, &outStruct) - - var outSlice []string - testRandomInputTo(t, jb, &outSlice) -} - -func testRandomInputTo(t *testing.T, jb []byte, out interface{}) { - err := Unmarshal(jb, out) - if err == nil { - // Cross-check stdlib to see if we just happened to fuzz a legit value. - err := json.Unmarshal(jb, out) - if err != nil { - t.Fatalf("Expected error unmarshaling as %s:\nas string: %q\nas bytes: %v", - reflect.TypeOf(out).Elem().Kind(), string(jb), jb) - } - } -} diff --git a/vendor/github.com/kr/pty/README.md b/vendor/github.com/kr/pty/README.md index 7b7900c3ae..f9bb002e03 100644 --- a/vendor/github.com/kr/pty/README.md +++ b/vendor/github.com/kr/pty/README.md @@ -8,6 +8,8 @@ Pty is a Go package for using unix pseudo-terminals. ## Example +### Command + ```go package main @@ -34,3 +36,65 @@ func main() { io.Copy(os.Stdout, f) } ``` + +### Shell + +```go +package main + +import ( + "io" + "log" + "os" + "os/exec" + "os/signal" + "syscall" + + "github.com/kr/pty" + "golang.org/x/crypto/ssh/terminal" +) + +func test() error { + // Create arbitrary command. + c := exec.Command("bash") + + // Start the command with a pty. + ptmx, err := pty.Start(c) + if err != nil { + return err + } + // Make sure to close the pty at the end. + defer func() { _ = ptmx.Close() }() // Best effort. + + // Handle pty size. + ch := make(chan os.Signal, 1) + signal.Notify(ch, syscall.SIGWINCH) + go func() { + for range ch { + if err := pty.InheritSize(os.Stdin, ptmx); err != nil { + log.Printf("error resizing pty: %s", err) + } + } + }() + ch <- syscall.SIGWINCH // Initial resize. + + // Set stdin in raw mode. + oldState, err := terminal.MakeRaw(int(os.Stdin.Fd())) + if err != nil { + panic(err) + } + defer func() { _ = terminal.Restore(int(os.Stdin.Fd()), oldState) }() // Best effort. + + // Copy stdin to the pty and the pty to stdout. + go func() { _, _ = io.Copy(ptmx, os.Stdin) }() + _, _ = io.Copy(os.Stdout, ptmx) + + return nil +} + +func main() { + if err := test(); err != nil { + log.Fatal(err) + } +} +``` diff --git a/vendor/github.com/kr/pty/mktypes.bash b/vendor/github.com/kr/pty/mktypes.bash index 0c076809b2..82ee16721c 100755 --- a/vendor/github.com/kr/pty/mktypes.bash +++ b/vendor/github.com/kr/pty/mktypes.bash @@ -13,7 +13,7 @@ GODEFS="go tool cgo -godefs" $GODEFS types.go |gofmt > ztypes_$GOARCH.go case $GOOS in -freebsd|dragonfly) +freebsd|dragonfly|openbsd) $GODEFS types_$GOOS.go |gofmt > ztypes_$GOOSARCH.go ;; esac diff --git a/vendor/github.com/kr/pty/pty_darwin.go b/vendor/github.com/kr/pty/pty_darwin.go index 93415430d2..6344b6b0ef 100644 --- a/vendor/github.com/kr/pty/pty_darwin.go +++ b/vendor/github.com/kr/pty/pty_darwin.go @@ -13,19 +13,23 @@ func open() (pty, tty *os.File, err error) { return nil, nil, err } p := os.NewFile(uintptr(pFD), "/dev/ptmx") + // In case of error after this point, make sure we close the ptmx fd. + defer func() { + if err != nil { + _ = p.Close() // Best effort. + } + }() sname, err := ptsname(p) if err != nil { return nil, nil, err } - err = grantpt(p) - if err != nil { + if err := grantpt(p); err != nil { return nil, nil, err } - err = unlockpt(p) - if err != nil { + if err := unlockpt(p); err != nil { return nil, nil, err } diff --git a/vendor/github.com/kr/pty/pty_dragonfly.go b/vendor/github.com/kr/pty/pty_dragonfly.go index 5431fb5aec..b7d1f20f29 100644 --- a/vendor/github.com/kr/pty/pty_dragonfly.go +++ b/vendor/github.com/kr/pty/pty_dragonfly.go @@ -14,19 +14,23 @@ func open() (pty, tty *os.File, err error) { if err != nil { return nil, nil, err } + // In case of error after this point, make sure we close the ptmx fd. + defer func() { + if err != nil { + _ = p.Close() // Best effort. + } + }() sname, err := ptsname(p) if err != nil { return nil, nil, err } - err = grantpt(p) - if err != nil { + if err := grantpt(p); err != nil { return nil, nil, err } - err = unlockpt(p) - if err != nil { + if err := unlockpt(p); err != nil { return nil, nil, err } diff --git a/vendor/github.com/kr/pty/pty_freebsd.go b/vendor/github.com/kr/pty/pty_freebsd.go index b341babd05..63b6d91337 100644 --- a/vendor/github.com/kr/pty/pty_freebsd.go +++ b/vendor/github.com/kr/pty/pty_freebsd.go @@ -7,22 +7,28 @@ import ( "unsafe" ) -func posix_openpt(oflag int) (fd int, err error) { +func posixOpenpt(oflag int) (fd int, err error) { r0, _, e1 := syscall.Syscall(syscall.SYS_POSIX_OPENPT, uintptr(oflag), 0, 0) fd = int(r0) if e1 != 0 { err = e1 } - return + return fd, err } func open() (pty, tty *os.File, err error) { - fd, err := posix_openpt(syscall.O_RDWR | syscall.O_CLOEXEC) + fd, err := posixOpenpt(syscall.O_RDWR | syscall.O_CLOEXEC) if err != nil { return nil, nil, err } - p := os.NewFile(uintptr(fd), "/dev/pts") + // In case of error after this point, make sure we close the pts fd. + defer func() { + if err != nil { + _ = p.Close() // Best effort. + } + }() + sname, err := ptsname(p) if err != nil { return nil, nil, err @@ -42,7 +48,7 @@ func isptmaster(fd uintptr) (bool, error) { var ( emptyFiodgnameArg fiodgnameArg - ioctl_FIODGNAME = _IOW('f', 120, unsafe.Sizeof(emptyFiodgnameArg)) + ioctlFIODGNAME = _IOW('f', 120, unsafe.Sizeof(emptyFiodgnameArg)) ) func ptsname(f *os.File) (string, error) { @@ -59,8 +65,7 @@ func ptsname(f *os.File) (string, error) { buf = make([]byte, n) arg = fiodgnameArg{Len: n, Buf: (*byte)(unsafe.Pointer(&buf[0]))} ) - err = ioctl(f.Fd(), ioctl_FIODGNAME, uintptr(unsafe.Pointer(&arg))) - if err != nil { + if err := ioctl(f.Fd(), ioctlFIODGNAME, uintptr(unsafe.Pointer(&arg))); err != nil { return "", err } diff --git a/vendor/github.com/kr/pty/pty_linux.go b/vendor/github.com/kr/pty/pty_linux.go index cb901a21e0..296dd21298 100644 --- a/vendor/github.com/kr/pty/pty_linux.go +++ b/vendor/github.com/kr/pty/pty_linux.go @@ -12,14 +12,19 @@ func open() (pty, tty *os.File, err error) { if err != nil { return nil, nil, err } + // In case of error after this point, make sure we close the ptmx fd. + defer func() { + if err != nil { + _ = p.Close() // Best effort. + } + }() sname, err := ptsname(p) if err != nil { return nil, nil, err } - err = unlockpt(p) - if err != nil { + if err := unlockpt(p); err != nil { return nil, nil, err } diff --git a/vendor/github.com/kr/pty/pty_openbsd.go b/vendor/github.com/kr/pty/pty_openbsd.go new file mode 100644 index 0000000000..6e7aeae7c0 --- /dev/null +++ b/vendor/github.com/kr/pty/pty_openbsd.go @@ -0,0 +1,33 @@ +package pty + +import ( + "os" + "syscall" + "unsafe" +) + +func open() (pty, tty *os.File, err error) { + /* + * from ptm(4): + * The PTMGET command allocates a free pseudo terminal, changes its + * ownership to the caller, revokes the access privileges for all previous + * users, opens the file descriptors for the master and slave devices and + * returns them to the caller in struct ptmget. + */ + + p, err := os.OpenFile("/dev/ptm", os.O_RDWR|syscall.O_CLOEXEC, 0) + if err != nil { + return nil, nil, err + } + defer p.Close() + + var ptm ptmget + if err := ioctl(p.Fd(), uintptr(ioctl_PTMGET), uintptr(unsafe.Pointer(&ptm))); err != nil { + return nil, nil, err + } + + pty = os.NewFile(uintptr(ptm.Cfd), "/dev/ptm") + tty = os.NewFile(uintptr(ptm.Sfd), "/dev/ptm") + + return pty, tty, nil +} diff --git a/vendor/github.com/kr/pty/pty_unsupported.go b/vendor/github.com/kr/pty/pty_unsupported.go index bd3d1e7e0e..9a3e721bc4 100644 --- a/vendor/github.com/kr/pty/pty_unsupported.go +++ b/vendor/github.com/kr/pty/pty_unsupported.go @@ -1,4 +1,4 @@ -// +build !linux,!darwin,!freebsd,!dragonfly +// +build !linux,!darwin,!freebsd,!dragonfly,!openbsd package pty diff --git a/vendor/github.com/kr/pty/types_openbsd.go b/vendor/github.com/kr/pty/types_openbsd.go new file mode 100644 index 0000000000..47701b5f9e --- /dev/null +++ b/vendor/github.com/kr/pty/types_openbsd.go @@ -0,0 +1,14 @@ +// +build ignore + +package pty + +/* +#include +#include +#include +*/ +import "C" + +type ptmget C.struct_ptmget + +var ioctl_PTMGET = C.PTMGET diff --git a/vendor/github.com/kr/pty/util.go b/vendor/github.com/kr/pty/util.go index a4fab9a7ce..68a8584cfe 100644 --- a/vendor/github.com/kr/pty/util.go +++ b/vendor/github.com/kr/pty/util.go @@ -8,26 +8,53 @@ import ( "unsafe" ) +// InheritSize applies the terminal size of master to slave. This should be run +// in a signal handler for syscall.SIGWINCH to automatically resize the slave when +// the master receives a window size change notification. +func InheritSize(master, slave *os.File) error { + size, err := GetsizeFull(master) + if err != nil { + return err + } + err = Setsize(slave, size) + if err != nil { + return err + } + return nil +} + +// Setsize resizes t to s. +func Setsize(t *os.File, ws *Winsize) error { + return windowRectCall(ws, t.Fd(), syscall.TIOCSWINSZ) +} + +// GetsizeFull returns the full terminal size description. +func GetsizeFull(t *os.File) (size *Winsize, err error) { + var ws Winsize + err = windowRectCall(&ws, t.Fd(), syscall.TIOCGWINSZ) + return &ws, err +} + // Getsize returns the number of rows (lines) and cols (positions // in each line) in terminal t. func Getsize(t *os.File) (rows, cols int, err error) { - var ws winsize - err = windowrect(&ws, t.Fd()) - return int(ws.ws_row), int(ws.ws_col), err + ws, err := GetsizeFull(t) + return int(ws.Rows), int(ws.Cols), err } -type winsize struct { - ws_row uint16 - ws_col uint16 - ws_xpixel uint16 - ws_ypixel uint16 +// Winsize describes the terminal size. +type Winsize struct { + Rows uint16 // ws_row: Number of rows (in cells) + Cols uint16 // ws_col: Number of columns (in cells) + X uint16 // ws_xpixel: Width in pixels + Y uint16 // ws_ypixel: Height in pixels } -func windowrect(ws *winsize, fd uintptr) error { +func windowRectCall(ws *Winsize, fd, a2 uintptr) error { _, _, errno := syscall.Syscall( syscall.SYS_IOCTL, fd, - syscall.TIOCGWINSZ, + a2, uintptr(unsafe.Pointer(ws)), ) if errno != 0 { diff --git a/vendor/github.com/kr/pty/ztypes_openbsd_amd64.go b/vendor/github.com/kr/pty/ztypes_openbsd_amd64.go new file mode 100644 index 0000000000..e67051688f --- /dev/null +++ b/vendor/github.com/kr/pty/ztypes_openbsd_amd64.go @@ -0,0 +1,13 @@ +// Created by cgo -godefs - DO NOT EDIT +// cgo -godefs types_openbsd.go + +package pty + +type ptmget struct { + Cfd int32 + Sfd int32 + Cn [16]int8 + Sn [16]int8 +} + +var ioctl_PTMGET = 0x40287401 diff --git a/vendor/github.com/kylelemons/godebug/diff/diff_test.go b/vendor/github.com/kylelemons/godebug/diff/diff_test.go deleted file mode 100644 index 1426eceb8b..0000000000 --- a/vendor/github.com/kylelemons/godebug/diff/diff_test.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2013 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package diff - -import ( - "fmt" - "reflect" - "strings" - "testing" -) - -func TestDiff(t *testing.T) { - tests := []struct { - desc string - A, B []string - chunks []Chunk - }{ - { - desc: "nil", - }, - { - desc: "empty", - A: []string{}, - B: []string{}, - }, - { - desc: "same", - A: []string{"foo"}, - B: []string{"foo"}, - }, - { - desc: "a empty", - A: []string{}, - }, - { - desc: "b empty", - B: []string{}, - }, - { - desc: "b nil", - A: []string{"foo"}, - chunks: []Chunk{ - 0: {Deleted: []string{"foo"}}, - }, - }, - { - desc: "a nil", - B: []string{"foo"}, - chunks: []Chunk{ - 0: {Added: []string{"foo"}}, - }, - }, - { - desc: "start with change", - A: []string{"a", "b", "c"}, - B: []string{"A", "b", "c"}, - chunks: []Chunk{ - 0: {Deleted: []string{"a"}}, - 1: {Added: []string{"A"}, Equal: []string{"b", "c"}}, - }, - }, - { - desc: "constitution", - A: []string{ - "We the People of the United States, in Order to form a more perfect Union,", - "establish Justice, insure domestic Tranquility, provide for the common defence,", - "and secure the Blessings of Liberty to ourselves", - "and our Posterity, do ordain and establish this Constitution for the United", - "States of America.", - }, - B: []string{ - "We the People of the United States, in Order to form a more perfect Union,", - "establish Justice, insure domestic Tranquility, provide for the common defence,", - "promote the general Welfare, and secure the Blessings of Liberty to ourselves", - "and our Posterity, do ordain and establish this Constitution for the United", - "States of America.", - }, - chunks: []Chunk{ - 0: { - Equal: []string{ - "We the People of the United States, in Order to form a more perfect Union,", - "establish Justice, insure domestic Tranquility, provide for the common defence,", - }, - }, - 1: { - Deleted: []string{ - "and secure the Blessings of Liberty to ourselves", - }, - }, - 2: { - Added: []string{ - "promote the general Welfare, and secure the Blessings of Liberty to ourselves", - }, - Equal: []string{ - "and our Posterity, do ordain and establish this Constitution for the United", - "States of America.", - }, - }, - }, - }, - } - - for _, test := range tests { - t.Run(test.desc, func(t *testing.T) { - got := DiffChunks(test.A, test.B) - if got, want := len(got), len(test.chunks); got != want { - t.Errorf("edit distance = %v, want %v", got-1, want-1) - return - } - for i := range got { - got, want := got[i], test.chunks[i] - if got, want := got.Added, want.Added; !reflect.DeepEqual(got, want) { - t.Errorf("chunks[%d]: Added = %v, want %v", i, got, want) - } - if got, want := got.Deleted, want.Deleted; !reflect.DeepEqual(got, want) { - t.Errorf("chunks[%d]: Deleted = %v, want %v", i, got, want) - } - if got, want := got.Equal, want.Equal; !reflect.DeepEqual(got, want) { - t.Errorf("chunks[%d]: Equal = %v, want %v", i, got, want) - } - } - }) - } -} - -func ExampleDiff() { - constitution := strings.TrimSpace(` -We the People of the United States, in Order to form a more perfect Union, -establish Justice, insure domestic Tranquility, provide for the common defence, -promote the general Welfare, and secure the Blessings of Liberty to ourselves -and our Posterity, do ordain and establish this Constitution for the United -States of America. -`) - - got := strings.TrimSpace(` -:wq -We the People of the United States, in Order to form a more perfect Union, -establish Justice, insure domestic Tranquility, provide for the common defence, -and secure the Blessings of Liberty to ourselves -and our Posterity, do ordain and establish this Constitution for the United -States of America. -`) - - fmt.Println(Diff(got, constitution)) - - // Output: - // -:wq - // We the People of the United States, in Order to form a more perfect Union, - // establish Justice, insure domestic Tranquility, provide for the common defence, - // -and secure the Blessings of Liberty to ourselves - // +promote the general Welfare, and secure the Blessings of Liberty to ourselves - // and our Posterity, do ordain and establish this Constitution for the United - // States of America. -} diff --git a/vendor/github.com/kylelemons/godebug/pretty/examples_test.go b/vendor/github.com/kylelemons/godebug/pretty/examples_test.go deleted file mode 100644 index df3b32e07c..0000000000 --- a/vendor/github.com/kylelemons/godebug/pretty/examples_test.go +++ /dev/null @@ -1,310 +0,0 @@ -// Copyright 2013 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pretty_test - -import ( - "fmt" - "net" - "reflect" - - "github.com/kylelemons/godebug/pretty" -) - -func ExampleConfig_Sprint() { - type Pair [2]int - type Map struct { - Name string - Players map[string]Pair - Obstacles map[Pair]string - } - - m := Map{ - Name: "Rock Creek", - Players: map[string]Pair{ - "player1": {1, 3}, - "player2": {0, -1}, - }, - Obstacles: map[Pair]string{ - Pair{0, 0}: "rock", - Pair{2, 1}: "pond", - Pair{1, 1}: "stream", - Pair{0, 1}: "stream", - }, - } - - // Specific output formats - compact := &pretty.Config{ - Compact: true, - } - diffable := &pretty.Config{ - Diffable: true, - } - - // Print out a summary - fmt.Printf("Players: %s\n", compact.Sprint(m.Players)) - - // Print diffable output - fmt.Printf("Map State:\n%s", diffable.Sprint(m)) - - // Output: - // Players: {player1:[1,3],player2:[0,-1]} - // Map State: - // { - // Name: "Rock Creek", - // Players: { - // player1: [ - // 1, - // 3, - // ], - // player2: [ - // 0, - // -1, - // ], - // }, - // Obstacles: { - // [0,0]: "rock", - // [0,1]: "stream", - // [1,1]: "stream", - // [2,1]: "pond", - // }, - // } -} - -func ExampleConfig_fmtFormatter() { - pretty.DefaultFormatter[reflect.TypeOf(&net.IPNet{})] = fmt.Sprint - pretty.DefaultFormatter[reflect.TypeOf(net.HardwareAddr{})] = fmt.Sprint - pretty.Print(&net.IPNet{ - IP: net.IPv4(192, 168, 1, 100), - Mask: net.CIDRMask(24, 32), - }) - pretty.Print(net.HardwareAddr{1, 2, 3, 4, 5, 6}) - - // Output: - // 192.168.1.100/24 - // 01:02:03:04:05:06 -} - -func ExampleConfig_customFormatter() { - pretty.DefaultFormatter[reflect.TypeOf(&net.IPNet{})] = func(n *net.IPNet) string { - return fmt.Sprintf("CIDR=%s", n) - } - pretty.Print(&net.IPNet{ - IP: net.IPv4(192, 168, 1, 100), - Mask: net.CIDRMask(24, 32), - }) - - // Output: - // CIDR=192.168.1.100/24 -} - -func ExamplePrint() { - type ShipManifest struct { - Name string - Crew map[string]string - Androids int - Stolen bool - } - - manifest := &ShipManifest{ - Name: "Spaceship Heart of Gold", - Crew: map[string]string{ - "Zaphod Beeblebrox": "Galactic President", - "Trillian": "Human", - "Ford Prefect": "A Hoopy Frood", - "Arthur Dent": "Along for the Ride", - }, - Androids: 1, - Stolen: true, - } - - pretty.Print(manifest) - - // Output: - // {Name: "Spaceship Heart of Gold", - // Crew: {Arthur Dent: "Along for the Ride", - // Ford Prefect: "A Hoopy Frood", - // Trillian: "Human", - // Zaphod Beeblebrox: "Galactic President"}, - // Androids: 1, - // Stolen: true} -} - -var t = struct { - Errorf func(string, ...interface{}) -}{ - Errorf: func(format string, args ...interface{}) { - fmt.Println(fmt.Sprintf(format, args...) + "\n") - }, -} - -func ExampleCompare_testing() { - // Code under test: - - type ShipManifest struct { - Name string - Crew map[string]string - Androids int - Stolen bool - } - - // AddCrew tries to add the given crewmember to the manifest. - AddCrew := func(m *ShipManifest, name, title string) { - if m.Crew == nil { - m.Crew = make(map[string]string) - } - m.Crew[title] = name - } - - // Test function: - tests := []struct { - desc string - before *ShipManifest - name, title string - after *ShipManifest - }{ - { - desc: "add first", - before: &ShipManifest{}, - name: "Zaphod Beeblebrox", - title: "Galactic President", - after: &ShipManifest{ - Crew: map[string]string{ - "Zaphod Beeblebrox": "Galactic President", - }, - }, - }, - { - desc: "add another", - before: &ShipManifest{ - Crew: map[string]string{ - "Zaphod Beeblebrox": "Galactic President", - }, - }, - name: "Trillian", - title: "Human", - after: &ShipManifest{ - Crew: map[string]string{ - "Zaphod Beeblebrox": "Galactic President", - "Trillian": "Human", - }, - }, - }, - { - desc: "overwrite", - before: &ShipManifest{ - Crew: map[string]string{ - "Zaphod Beeblebrox": "Galactic President", - }, - }, - name: "Zaphod Beeblebrox", - title: "Just this guy, you know?", - after: &ShipManifest{ - Crew: map[string]string{ - "Zaphod Beeblebrox": "Just this guy, you know?", - }, - }, - }, - } - - for _, test := range tests { - AddCrew(test.before, test.name, test.title) - if diff := pretty.Compare(test.before, test.after); diff != "" { - t.Errorf("%s: post-AddCrew diff: (-got +want)\n%s", test.desc, diff) - } - } - - // Output: - // add first: post-AddCrew diff: (-got +want) - // { - // Name: "", - // Crew: { - // - Galactic President: "Zaphod Beeblebrox", - // + Zaphod Beeblebrox: "Galactic President", - // }, - // Androids: 0, - // Stolen: false, - // } - // - // add another: post-AddCrew diff: (-got +want) - // { - // Name: "", - // Crew: { - // - Human: "Trillian", - // + Trillian: "Human", - // Zaphod Beeblebrox: "Galactic President", - // }, - // Androids: 0, - // Stolen: false, - // } - // - // overwrite: post-AddCrew diff: (-got +want) - // { - // Name: "", - // Crew: { - // - Just this guy, you know?: "Zaphod Beeblebrox", - // - Zaphod Beeblebrox: "Galactic President", - // + Zaphod Beeblebrox: "Just this guy, you know?", - // }, - // Androids: 0, - // Stolen: false, - // } -} - -func ExampleCompare_debugging() { - type ShipManifest struct { - Name string - Crew map[string]string - Androids int - Stolen bool - } - - reported := &ShipManifest{ - Name: "Spaceship Heart of Gold", - Crew: map[string]string{ - "Zaphod Beeblebrox": "Galactic President", - "Trillian": "Human", - "Ford Prefect": "A Hoopy Frood", - "Arthur Dent": "Along for the Ride", - }, - Androids: 1, - Stolen: true, - } - - expected := &ShipManifest{ - Name: "Spaceship Heart of Gold", - Crew: map[string]string{ - "Trillian": "Human", - "Rowan Artosok": "Captain", - }, - Androids: 1, - Stolen: false, - } - - fmt.Println(pretty.Compare(reported, expected)) - // Output: - // { - // Name: "Spaceship Heart of Gold", - // Crew: { - // - Arthur Dent: "Along for the Ride", - // - Ford Prefect: "A Hoopy Frood", - // + Rowan Artosok: "Captain", - // Trillian: "Human", - // - Zaphod Beeblebrox: "Galactic President", - // }, - // Androids: 1, - // - Stolen: true, - // + Stolen: false, - // } -} diff --git a/vendor/github.com/kylelemons/godebug/pretty/public_test.go b/vendor/github.com/kylelemons/godebug/pretty/public_test.go deleted file mode 100644 index 01fd3ffe31..0000000000 --- a/vendor/github.com/kylelemons/godebug/pretty/public_test.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2013 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pretty - -import ( - "testing" -) - -func TestDiff(t *testing.T) { - type example struct { - Name string - Age int - Friends []string - } - - tests := []struct { - desc string - got, want interface{} - diff string - }{ - { - desc: "basic struct", - got: example{ - Name: "Zaphd", - Age: 42, - Friends: []string{ - "Ford Prefect", - "Trillian", - "Marvin", - }, - }, - want: example{ - Name: "Zaphod", - Age: 42, - Friends: []string{ - "Ford Prefect", - "Trillian", - }, - }, - diff: ` { -- Name: "Zaphd", -+ Name: "Zaphod", - Age: 42, - Friends: [ - "Ford Prefect", - "Trillian", -- "Marvin", - ], - }`, - }, - } - - for _, test := range tests { - if got, want := Compare(test.got, test.want), test.diff; got != want { - t.Errorf("%s:", test.desc) - t.Errorf(" got: %q", got) - t.Errorf(" want: %q", want) - } - } -} - -func TestSkipZeroFields(t *testing.T) { - type example struct { - Name string - Species string - Age int - Friends []string - } - - tests := []struct { - desc string - got, want interface{} - diff string - }{ - { - desc: "basic struct", - got: example{ - Name: "Zaphd", - Species: "Betelgeusian", - Age: 42, - }, - want: example{ - Name: "Zaphod", - Species: "Betelgeusian", - Age: 42, - Friends: []string{ - "Ford Prefect", - "Trillian", - "", - }, - }, - diff: ` { -- Name: "Zaphd", -+ Name: "Zaphod", - Species: "Betelgeusian", - Age: 42, -+ Friends: [ -+ "Ford Prefect", -+ "Trillian", -+ "", -+ ], - }`, - }, - } - - cfg := *CompareConfig - cfg.SkipZeroFields = true - - for _, test := range tests { - if got, want := cfg.Compare(test.got, test.want), test.diff; got != want { - t.Errorf("%s:", test.desc) - t.Errorf(" got: %q", got) - t.Errorf(" want: %q", want) - } - } -} diff --git a/vendor/github.com/kylelemons/godebug/pretty/reflect_test.go b/vendor/github.com/kylelemons/godebug/pretty/reflect_test.go deleted file mode 100644 index ef5008ec63..0000000000 --- a/vendor/github.com/kylelemons/godebug/pretty/reflect_test.go +++ /dev/null @@ -1,236 +0,0 @@ -// Copyright 2013 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pretty - -import ( - "fmt" - "net" - "reflect" - "testing" - "time" -) - -func TestVal2nodeDefault(t *testing.T) { - err := fmt.Errorf("err") - var errNil error - - tests := []struct { - desc string - raw interface{} - want node - }{ - { - desc: "nil", - raw: nil, - want: rawVal("nil"), - }, - { - desc: "nil ptr", - raw: (*int)(nil), - want: rawVal("nil"), - }, - { - desc: "nil slice", - raw: []string(nil), - want: list{}, - }, - { - desc: "nil map", - raw: map[string]string(nil), - want: keyvals{}, - }, - { - desc: "string", - raw: "zaphod", - want: stringVal("zaphod"), - }, - { - desc: "slice", - raw: []string{"a", "b"}, - want: list{stringVal("a"), stringVal("b")}, - }, - { - desc: "map", - raw: map[string]string{ - "zaphod": "beeblebrox", - "ford": "prefect", - }, - want: keyvals{ - {"ford", stringVal("prefect")}, - {"zaphod", stringVal("beeblebrox")}, - }, - }, - { - desc: "map of [2]int", - raw: map[[2]int]string{ - [2]int{-1, 2}: "school", - [2]int{0, 0}: "origin", - [2]int{1, 3}: "home", - }, - want: keyvals{ - {"[-1,2]", stringVal("school")}, - {"[0,0]", stringVal("origin")}, - {"[1,3]", stringVal("home")}, - }, - }, - { - desc: "struct", - raw: struct{ Zaphod, Ford string }{"beeblebrox", "prefect"}, - want: keyvals{ - {"Zaphod", stringVal("beeblebrox")}, - {"Ford", stringVal("prefect")}, - }, - }, - { - desc: "int", - raw: 3, - want: rawVal("3"), - }, - { - desc: "time.Time", - raw: time.Unix(1257894000, 0).UTC(), - want: rawVal("2009-11-10 23:00:00 +0000 UTC"), - }, - { - desc: "net.IP", - raw: net.IPv4(127, 0, 0, 1), - want: rawVal("127.0.0.1"), - }, - { - desc: "error", - raw: &err, - want: rawVal("err"), - }, - { - desc: "nil error", - raw: &errNil, - want: rawVal(""), - }, - } - - for _, test := range tests { - if got, want := DefaultConfig.val2node(reflect.ValueOf(test.raw)), test.want; !reflect.DeepEqual(got, want) { - t.Errorf("%s: got %#v, want %#v", test.desc, got, want) - } - } -} - -func TestVal2node(t *testing.T) { - tests := []struct { - desc string - raw interface{} - cfg *Config - want node - }{ - { - desc: "struct default", - raw: struct{ Zaphod, Ford, foo string }{"beeblebrox", "prefect", "BAD"}, - cfg: DefaultConfig, - want: keyvals{ - {"Zaphod", stringVal("beeblebrox")}, - {"Ford", stringVal("prefect")}, - }, - }, - { - desc: "struct w/ IncludeUnexported", - raw: struct{ Zaphod, Ford, foo string }{"beeblebrox", "prefect", "GOOD"}, - cfg: &Config{ - IncludeUnexported: true, - }, - want: keyvals{ - {"Zaphod", stringVal("beeblebrox")}, - {"Ford", stringVal("prefect")}, - {"foo", stringVal("GOOD")}, - }, - }, - { - desc: "time default", - raw: struct{ Date time.Time }{time.Unix(1234567890, 0).UTC()}, - cfg: DefaultConfig, - want: keyvals{ - {"Date", rawVal("2009-02-13 23:31:30 +0000 UTC")}, - }, - }, - { - desc: "time w/ nil Formatter", - raw: struct{ Date time.Time }{time.Unix(1234567890, 0).UTC()}, - cfg: &Config{ - PrintStringers: true, - Formatter: map[reflect.Type]interface{}{ - reflect.TypeOf(time.Time{}): nil, - }, - }, - want: keyvals{ - {"Date", keyvals{}}, - }, - }, - { - desc: "time w/ PrintTextMarshalers", - raw: struct{ Date time.Time }{time.Unix(1234567890, 0).UTC()}, - cfg: &Config{ - PrintTextMarshalers: true, - }, - want: keyvals{ - {"Date", stringVal("2009-02-13T23:31:30Z")}, - }, - }, - { - desc: "time w/ PrintStringers", - raw: struct{ Date time.Time }{time.Unix(1234567890, 0).UTC()}, - cfg: &Config{ - PrintStringers: true, - }, - want: keyvals{ - {"Date", stringVal("2009-02-13 23:31:30 +0000 UTC")}, - }, - }, - } - - for _, test := range tests { - if got, want := test.cfg.val2node(reflect.ValueOf(test.raw)), test.want; !reflect.DeepEqual(got, want) { - t.Errorf("%s: got %#v, want %#v", test.desc, got, want) - } - } -} - -func BenchmarkVal2node(b *testing.B) { - benchmarks := []struct { - desc string - cfg *Config - raw interface{} - }{ - { - desc: "struct", - cfg: DefaultConfig, - raw: struct{ Zaphod, Ford string }{"beeblebrox", "prefect"}}, - { - desc: "map", - cfg: DefaultConfig, - raw: map[[2]int]string{ - [2]int{-1, 2}: "school", - [2]int{0, 0}: "origin", - [2]int{1, 3}: "home", - }, - }, - } - - for _, bench := range benchmarks { - b.Run(bench.desc, func(b *testing.B) { - for i := 0; i < b.N; i++ { - bench.cfg.val2node(reflect.ValueOf(bench.raw)) - } - }) - } -} diff --git a/vendor/github.com/kylelemons/godebug/pretty/structure_test.go b/vendor/github.com/kylelemons/godebug/pretty/structure_test.go deleted file mode 100644 index 5fd2d9a5db..0000000000 --- a/vendor/github.com/kylelemons/godebug/pretty/structure_test.go +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright 2013 Google Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pretty - -import ( - "bytes" - "strings" - "testing" -) - -func TestWriteTo(t *testing.T) { - tests := []struct { - desc string - node node - - // All strings have a leading newline trimmed before comparison: - normal string - diffable string - }{ - { - desc: "string", - node: stringVal("zaphod"), - normal: `"zaphod"`, - diffable: `"zaphod"`, - }, - { - desc: "raw", - node: rawVal("42"), - normal: `42`, - diffable: `42`, - }, - { - desc: "keyvals", - node: keyvals{ - {"name", stringVal("zaphod")}, - {"age", rawVal("42")}, - }, - normal: ` -{name: "zaphod", - age: 42}`, - diffable: ` -{ - name: "zaphod", - age: 42, -}`, - }, - { - desc: "empty list", - node: list{}, - normal: ` -[]`, - diffable: ` -[ -]`, - }, - { - desc: "empty nested list", - node: list{list{}}, - normal: ` -[[]]`, - diffable: ` -[ - [ - ], -]`, - }, - { - desc: "list", - node: list{ - stringVal("zaphod"), - rawVal("42"), - }, - normal: ` -["zaphod", - 42]`, - diffable: ` -[ - "zaphod", - 42, -]`, - }, - { - desc: "empty keyvals", - node: keyvals{}, - normal: ` -{}`, - diffable: ` -{ -}`, - }, - { - desc: "empty nested keyvals", - node: keyvals{{"k", keyvals{}}}, - normal: ` -{k: {}}`, - diffable: ` -{ - k: { - }, -}`, - }, - { - desc: "nested", - node: list{ - stringVal("first"), - list{rawVal("1"), rawVal("2"), rawVal("3")}, - keyvals{ - {"trillian", keyvals{ - {"race", stringVal("human")}, - {"age", rawVal("36")}, - }}, - {"zaphod", keyvals{ - {"occupation", stringVal("president of the galaxy")}, - {"features", stringVal("two heads")}, - }}, - }, - keyvals{}, - }, - normal: ` -["first", - [1, - 2, - 3], - {trillian: {race: "human", - age: 36}, - zaphod: {occupation: "president of the galaxy", - features: "two heads"}}, - {}]`, - diffable: ` -[ - "first", - [ - 1, - 2, - 3, - ], - { - trillian: { - race: "human", - age: 36, - }, - zaphod: { - occupation: "president of the galaxy", - features: "two heads", - }, - }, - { - }, -]`, - }, - } - - for _, test := range tests { - // For readability, we have a newline that won't be there in the output - test.normal = strings.TrimPrefix(test.normal, "\n") - test.diffable = strings.TrimPrefix(test.diffable, "\n") - - buf := new(bytes.Buffer) - test.node.WriteTo(buf, "", &Config{}) - if got, want := buf.String(), test.normal; got != want { - t.Errorf("%s: normal rendendered incorrectly\ngot:\n%s\nwant:\n%s", test.desc, got, want) - } - buf.Reset() - test.node.WriteTo(buf, "", &Config{Diffable: true}) - if got, want := buf.String(), test.diffable; got != want { - t.Errorf("%s: diffable rendendered incorrectly\ngot:\n%s\nwant:\n%s", test.desc, got, want) - } - } -} - -func TestCompactString(t *testing.T) { - tests := []struct { - node - compact string - }{ - { - stringVal("abc"), - "abc", - }, - { - rawVal("2"), - "2", - }, - { - list{ - rawVal("2"), - rawVal("3"), - }, - "[2,3]", - }, - { - keyvals{ - {"name", stringVal("zaphod")}, - {"age", rawVal("42")}, - }, - `{name:"zaphod",age:42}`, - }, - { - list{ - list{ - rawVal("0"), - rawVal("1"), - rawVal("2"), - rawVal("3"), - }, - list{ - rawVal("1"), - rawVal("2"), - rawVal("3"), - rawVal("0"), - }, - list{ - rawVal("2"), - rawVal("3"), - rawVal("0"), - rawVal("1"), - }, - }, - `[[0,1,2,3],[1,2,3,0],[2,3,0,1]]`, - }, - } - - for _, test := range tests { - if got, want := compactString(test.node), test.compact; got != want { - t.Errorf("%#v: compact = %q, want %q", test.node, got, want) - } - } -} - -func TestShortList(t *testing.T) { - cfg := &Config{ - ShortList: 16, - } - - tests := []struct { - node - want string - }{ - { - list{ - list{ - rawVal("0"), - rawVal("1"), - rawVal("2"), - rawVal("3"), - }, - list{ - rawVal("1"), - rawVal("2"), - rawVal("3"), - rawVal("0"), - }, - list{ - rawVal("2"), - rawVal("3"), - rawVal("0"), - rawVal("1"), - }, - }, - `[[0,1,2,3], - [1,2,3,0], - [2,3,0,1]]`, - }, - } - - for _, test := range tests { - buf := new(bytes.Buffer) - test.node.WriteTo(buf, "", cfg) - if got, want := buf.String(), test.want; got != want { - t.Errorf("%#v: got:\n%s\nwant:\n%s", test.node, got, want) - } - } -} - -var benchNode = keyvals{ - {"list", list{ - rawVal("0"), - rawVal("1"), - rawVal("2"), - rawVal("3"), - }}, - {"keyvals", keyvals{ - {"a", stringVal("b")}, - {"c", stringVal("e")}, - {"d", stringVal("f")}, - }}, -} - -func benchOpts(b *testing.B, cfg *Config) { - buf := new(bytes.Buffer) - benchNode.WriteTo(buf, "", cfg) - b.SetBytes(int64(buf.Len())) - b.ResetTimer() - - for i := 0; i < b.N; i++ { - buf.Reset() - benchNode.WriteTo(buf, "", cfg) - } -} - -func BenchmarkWriteDefault(b *testing.B) { benchOpts(b, DefaultConfig) } -func BenchmarkWriteShortList(b *testing.B) { benchOpts(b, &Config{ShortList: 16}) } -func BenchmarkWriteCompact(b *testing.B) { benchOpts(b, &Config{Compact: true}) } -func BenchmarkWriteDiffable(b *testing.B) { benchOpts(b, &Config{Diffable: true}) } diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go deleted file mode 100644 index 5c463722d4..0000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2013 Matt T. Proud -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pbutil - -import ( - "bytes" - "testing" - - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -func TestWriteDelimited(t *testing.T) { - t.Parallel() - for _, test := range []struct { - msg Message - buf []byte - n int - err error - }{ - { - msg: &Empty{}, - n: 1, - buf: []byte{0}, - }, - { - msg: &GoEnum{Foo: FOO_FOO1.Enum()}, - n: 3, - buf: []byte{2, 8, 1}, - }, - { - msg: &Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }, - n: 271, - buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109, - 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104, - 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73, - 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101, - 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102, - 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32, - 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32, - 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122, - 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114, - 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32, - 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103, - 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104, - 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112, - 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120, - 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101, - 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110, - 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32, - 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46}, - }, - } { - var buf bytes.Buffer - if n, err := WriteDelimited(&buf, test.msg); n != test.n || err != test.err { - t.Fatalf("WriteDelimited(buf, %#v) = %v, %v; want %v, %v", test.msg, n, err, test.n, test.err) - } - if out := buf.Bytes(); !bytes.Equal(out, test.buf) { - t.Fatalf("WriteDelimited(buf, %#v); buf = %v; want %v", test.msg, out, test.buf) - } - } -} - -func TestReadDelimited(t *testing.T) { - t.Parallel() - for _, test := range []struct { - buf []byte - msg Message - n int - err error - }{ - { - buf: []byte{0}, - msg: &Empty{}, - n: 1, - }, - { - n: 3, - buf: []byte{2, 8, 1}, - msg: &GoEnum{Foo: FOO_FOO1.Enum()}, - }, - { - buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109, - 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104, - 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73, - 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101, - 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102, - 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32, - 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32, - 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122, - 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114, - 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32, - 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103, - 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104, - 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112, - 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120, - 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101, - 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110, - 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32, - 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46}, - msg: &Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }, - n: 271, - }, - } { - msg := Clone(test.msg) - msg.Reset() - if n, err := ReadDelimited(bytes.NewBuffer(test.buf), msg); n != test.n || err != test.err { - t.Fatalf("ReadDelimited(%v, msg) = %v, %v; want %v, %v", test.buf, n, err, test.n, test.err) - } - if !Equal(msg, test.msg) { - t.Fatalf("ReadDelimited(%v, msg); msg = %v; want %v", test.buf, msg, test.msg) - } - } -} - -func TestEndToEndValid(t *testing.T) { - t.Parallel() - for _, test := range [][]Message{ - {&Empty{}}, - {&GoEnum{Foo: FOO_FOO1.Enum()}, &Empty{}, &GoEnum{Foo: FOO_FOO1.Enum()}}, - {&GoEnum{Foo: FOO_FOO1.Enum()}}, - {&Strings{ - StringField: String(`This is my gigantic, unhappy string. It exceeds -the encoding size of a single byte varint. We are using it to fuzz test the -correctness of the header decoding mechanisms, which may prove problematic. -I expect it may. Let's hope you enjoy testing as much as we do.`), - }}, - } { - var buf bytes.Buffer - var written int - for i, msg := range test { - n, err := WriteDelimited(&buf, msg) - if err != nil { - // Assumption: TestReadDelimited and TestWriteDelimited are sufficient - // and inputs for this test are explicitly exercised there. - t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", test, i, err) - } - written += n - } - var read int - for i, msg := range test { - out := Clone(msg) - out.Reset() - n, _ := ReadDelimited(&buf, out) - // Decide to do EOF checking? - read += n - if !Equal(out, msg) { - t.Fatalf("out = %v; want %v[%d] = %#v", out, test, i, msg) - } - } - if read != written { - t.Fatalf("%v read = %d; want %d", test, read, written) - } - } -} diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode_test.go deleted file mode 100644 index 364a7b7997..0000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode_test.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2016 Matt T. Proud -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pbutil - -import ( - "bytes" - "io" - "testing" - "testing/iotest" -) - -func TestReadDelimitedIllegalVarint(t *testing.T) { - t.Parallel() - var tests = []struct { - in []byte - n int - err error - }{ - { - in: []byte{255, 255, 255, 255, 255}, - n: 5, - err: errInvalidVarint, - }, - { - in: []byte{255, 255, 255, 255, 255, 255}, - n: 5, - err: errInvalidVarint, - }, - } - for _, test := range tests { - n, err := ReadDelimited(bytes.NewReader(test.in), nil) - if got, want := n, test.n; got != want { - t.Errorf("ReadDelimited(%#v, nil) = %#v, ?; want = %v#, ?", test.in, got, want) - } - if got, want := err, test.err; got != want { - t.Errorf("ReadDelimited(%#v, nil) = ?, %#v; want = ?, %#v", test.in, got, want) - } - } -} - -func TestReadDelimitedPrematureHeader(t *testing.T) { - t.Parallel() - var data = []byte{128, 5} // 256 + 256 + 128 - n, err := ReadDelimited(bytes.NewReader(data[0:1]), nil) - if got, want := n, 1; got != want { - t.Errorf("ReadDelimited(%#v, nil) = %#v, ?; want = %v#, ?", data[0:1], got, want) - } - if got, want := err, io.EOF; got != want { - t.Errorf("ReadDelimited(%#v, nil) = ?, %#v; want = ?, %#v", data[0:1], got, want) - } -} - -func TestReadDelimitedPrematureBody(t *testing.T) { - t.Parallel() - var data = []byte{128, 5, 0, 0, 0} // 256 + 256 + 128 - n, err := ReadDelimited(bytes.NewReader(data[:]), nil) - if got, want := n, 5; got != want { - t.Errorf("ReadDelimited(%#v, nil) = %#v, ?; want = %v#, ?", data, got, want) - } - if got, want := err, io.ErrUnexpectedEOF; got != want { - t.Errorf("ReadDelimited(%#v, nil) = ?, %#v; want = ?, %#v", data, got, want) - } -} - -func TestReadDelimitedPrematureHeaderIncremental(t *testing.T) { - t.Parallel() - var data = []byte{128, 5} // 256 + 256 + 128 - n, err := ReadDelimited(iotest.OneByteReader(bytes.NewReader(data[0:1])), nil) - if got, want := n, 1; got != want { - t.Errorf("ReadDelimited(%#v, nil) = %#v, ?; want = %v#, ?", data[0:1], got, want) - } - if got, want := err, io.EOF; got != want { - t.Errorf("ReadDelimited(%#v, nil) = ?, %#v; want = ?, %#v", data[0:1], got, want) - } -} - -func TestReadDelimitedPrematureBodyIncremental(t *testing.T) { - t.Parallel() - var data = []byte{128, 5, 0, 0, 0} // 256 + 256 + 128 - n, err := ReadDelimited(iotest.OneByteReader(bytes.NewReader(data[:])), nil) - if got, want := n, 5; got != want { - t.Errorf("ReadDelimited(%#v, nil) = %#v, ?; want = %v#, ?", data, got, want) - } - if got, want := err, io.ErrUnexpectedEOF; got != want { - t.Errorf("ReadDelimited(%#v, nil) = ?, %#v; want = ?, %#v", data, got, want) - } -} diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode_test.go deleted file mode 100644 index f92632b0be..0000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode_test.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2016 Matt T. Proud -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package pbutil - -import ( - "bytes" - "errors" - "testing" - - "github.com/golang/protobuf/proto" -) - -var errMarshal = errors.New("pbutil: can't marshal") - -type cantMarshal struct{ proto.Message } - -func (cantMarshal) Marshal() ([]byte, error) { return nil, errMarshal } - -var _ proto.Message = cantMarshal{} - -func TestWriteDelimitedMarshalErr(t *testing.T) { - t.Parallel() - var data cantMarshal - var buf bytes.Buffer - n, err := WriteDelimited(&buf, data) - if got, want := n, 0; got != want { - t.Errorf("WriteDelimited(buf, %#v) = %#v, ?; want = %v#, ?", data, got, want) - } - if got, want := err, errMarshal; got != want { - t.Errorf("WriteDelimited(buf, %#v) = ?, %#v; want = ?, %#v", data, got, want) - } -} - -type canMarshal struct{ proto.Message } - -func (canMarshal) Marshal() ([]byte, error) { return []byte{0, 1, 2, 3, 4, 5}, nil } - -var errWrite = errors.New("pbutil: can't write") - -type cantWrite struct{} - -func (cantWrite) Write([]byte) (int, error) { return 0, errWrite } - -func TestWriteDelimitedWriteErr(t *testing.T) { - t.Parallel() - var data canMarshal - var buf cantWrite - n, err := WriteDelimited(buf, data) - if got, want := n, 0; got != want { - t.Errorf("WriteDelimited(buf, %#v) = %#v, ?; want = %v#, ?", data, got, want) - } - if got, want := err, errWrite; got != want { - t.Errorf("WriteDelimited(buf, %#v) = ?, %#v; want = ?, %#v", data, got, want) - } -} diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go deleted file mode 100644 index d6d9b25594..0000000000 --- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// http://github.com/golang/protobuf/ -// -// 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. - -package pbutil - -import ( - . "github.com/golang/protobuf/proto" - . "github.com/golang/protobuf/proto/testdata" -) - -// FROM https://github.com/golang/protobuf/blob/master/proto/all_test.go. - -func initGoTestField() *GoTestField { - f := new(GoTestField) - f.Label = String("label") - f.Type = String("type") - return f -} - -// These are all structurally equivalent but the tag numbers differ. -// (It's remarkable that required, optional, and repeated all have -// 8 letters.) -func initGoTest_RequiredGroup() *GoTest_RequiredGroup { - return &GoTest_RequiredGroup{ - RequiredField: String("required"), - } -} - -func initGoTest_OptionalGroup() *GoTest_OptionalGroup { - return &GoTest_OptionalGroup{ - RequiredField: String("optional"), - } -} - -func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { - return &GoTest_RepeatedGroup{ - RequiredField: String("repeated"), - } -} - -func initGoTest(setdefaults bool) *GoTest { - pb := new(GoTest) - if setdefaults { - pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) - pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) - pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) - pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) - pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) - pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) - pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) - pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) - pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) - pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) - pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted - pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) - pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) - } - - pb.Kind = GoTest_TIME.Enum() - pb.RequiredField = initGoTestField() - pb.F_BoolRequired = Bool(true) - pb.F_Int32Required = Int32(3) - pb.F_Int64Required = Int64(6) - pb.F_Fixed32Required = Uint32(32) - pb.F_Fixed64Required = Uint64(64) - pb.F_Uint32Required = Uint32(3232) - pb.F_Uint64Required = Uint64(6464) - pb.F_FloatRequired = Float32(3232) - pb.F_DoubleRequired = Float64(6464) - pb.F_StringRequired = String("string") - pb.F_BytesRequired = []byte("bytes") - pb.F_Sint32Required = Int32(-32) - pb.F_Sint64Required = Int64(-64) - pb.Requiredgroup = initGoTest_RequiredGroup() - - return pb -} diff --git a/vendor/github.com/mitchellh/go-ps/process_darwin_test.go b/vendor/github.com/mitchellh/go-ps/process_darwin_test.go deleted file mode 100644 index ee04c5c284..0000000000 --- a/vendor/github.com/mitchellh/go-ps/process_darwin_test.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build darwin - -package ps - -import ( - "testing" -) - -func TestDarwinProcess_impl(t *testing.T) { - var _ Process = new(DarwinProcess) -} diff --git a/vendor/github.com/mitchellh/go-ps/process_test.go b/vendor/github.com/mitchellh/go-ps/process_test.go deleted file mode 100644 index 1bcbc3279d..0000000000 --- a/vendor/github.com/mitchellh/go-ps/process_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package ps - -import ( - "os" - "testing" -) - -func TestFindProcess(t *testing.T) { - p, err := FindProcess(os.Getpid()) - if err != nil { - t.Fatalf("err: %s", err) - } - if p == nil { - t.Fatal("should have process") - } - - if p.Pid() != os.Getpid() { - t.Fatalf("bad: %#v", p.Pid()) - } -} - -func TestProcesses(t *testing.T) { - // This test works because there will always be SOME processes - // running. - p, err := Processes() - if err != nil { - t.Fatalf("err: %s", err) - } - - if len(p) <= 0 { - t.Fatal("should have processes") - } - - found := false - for _, p1 := range p { - if p1.Executable() == "go" || p1.Executable() == "go.exe" { - found = true - break - } - } - - if !found { - t.Fatal("should have Go") - } -} diff --git a/vendor/github.com/mitchellh/go-ps/process_unix_test.go b/vendor/github.com/mitchellh/go-ps/process_unix_test.go deleted file mode 100644 index 754073e550..0000000000 --- a/vendor/github.com/mitchellh/go-ps/process_unix_test.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build linux solaris - -package ps - -import ( - "testing" -) - -func TestUnixProcess_impl(t *testing.T) { - var _ Process = new(UnixProcess) -} diff --git a/vendor/github.com/mitchellh/mapstructure/.travis.yml b/vendor/github.com/mitchellh/mapstructure/.travis.yml index 5c14c1339d..d9deadb86d 100644 --- a/vendor/github.com/mitchellh/mapstructure/.travis.yml +++ b/vendor/github.com/mitchellh/mapstructure/.travis.yml @@ -1,7 +1,8 @@ -language: go +language: go + +go: + - 1.9.x + - tip -go: - - 1.8.1 - script: - - go test + - go test diff --git a/vendor/github.com/mitchellh/mapstructure/README.md b/vendor/github.com/mitchellh/mapstructure/README.md index 659d6885fc..0018dc7d9f 100644 --- a/vendor/github.com/mitchellh/mapstructure/README.md +++ b/vendor/github.com/mitchellh/mapstructure/README.md @@ -1,4 +1,4 @@ -# mapstructure +# mapstructure [![Godoc](https://godoc.org/github.com/mitchellh/mapstructure?status.svg)](https://godoc.org/github.com/mitchellh/mapstructure) mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling. diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go index afcfd5eed6..2a727575a3 100644 --- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go +++ b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go @@ -115,6 +115,25 @@ func StringToTimeDurationHookFunc() DecodeHookFunc { } } +// StringToTimeHookFunc returns a DecodeHookFunc that converts +// strings to time.Time. +func StringToTimeHookFunc(layout string) DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(time.Time{}) { + return data, nil + } + + // Convert it by parsing + return time.Parse(layout, data.(string)) + } +} + // WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to // the decoder. // diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go deleted file mode 100644 index 53289afcfb..0000000000 --- a/vendor/github.com/mitchellh/mapstructure/decode_hooks_test.go +++ /dev/null @@ -1,229 +0,0 @@ -package mapstructure - -import ( - "errors" - "reflect" - "testing" - "time" -) - -func TestComposeDecodeHookFunc(t *testing.T) { - f1 := func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - return data.(string) + "foo", nil - } - - f2 := func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - return data.(string) + "bar", nil - } - - f := ComposeDecodeHookFunc(f1, f2) - - result, err := DecodeHookExec( - f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), "") - if err != nil { - t.Fatalf("bad: %s", err) - } - if result.(string) != "foobar" { - t.Fatalf("bad: %#v", result) - } -} - -func TestComposeDecodeHookFunc_err(t *testing.T) { - f1 := func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) { - return nil, errors.New("foo") - } - - f2 := func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) { - panic("NOPE") - } - - f := ComposeDecodeHookFunc(f1, f2) - - _, err := DecodeHookExec( - f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), 42) - if err.Error() != "foo" { - t.Fatalf("bad: %s", err) - } -} - -func TestComposeDecodeHookFunc_kinds(t *testing.T) { - var f2From reflect.Kind - - f1 := func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - return int(42), nil - } - - f2 := func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - f2From = f - return data, nil - } - - f := ComposeDecodeHookFunc(f1, f2) - - _, err := DecodeHookExec( - f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), "") - if err != nil { - t.Fatalf("bad: %s", err) - } - if f2From != reflect.Int { - t.Fatalf("bad: %#v", f2From) - } -} - -func TestStringToSliceHookFunc(t *testing.T) { - f := StringToSliceHookFunc(",") - - strType := reflect.TypeOf("") - sliceType := reflect.TypeOf([]byte("")) - cases := []struct { - f, t reflect.Type - data interface{} - result interface{} - err bool - }{ - {sliceType, sliceType, 42, 42, false}, - {strType, strType, 42, 42, false}, - { - strType, - sliceType, - "foo,bar,baz", - []string{"foo", "bar", "baz"}, - false, - }, - { - strType, - sliceType, - "", - []string{}, - false, - }, - } - - for i, tc := range cases { - actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data) - if tc.err != (err != nil) { - t.Fatalf("case %d: expected err %#v", i, tc.err) - } - if !reflect.DeepEqual(actual, tc.result) { - t.Fatalf( - "case %d: expected %#v, got %#v", - i, tc.result, actual) - } - } -} - -func TestStringToTimeDurationHookFunc(t *testing.T) { - f := StringToTimeDurationHookFunc() - - strType := reflect.TypeOf("") - timeType := reflect.TypeOf(time.Duration(5)) - cases := []struct { - f, t reflect.Type - data interface{} - result interface{} - err bool - }{ - {strType, timeType, "5s", 5 * time.Second, false}, - {strType, timeType, "5", time.Duration(0), true}, - {strType, strType, "5", "5", false}, - } - - for i, tc := range cases { - actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data) - if tc.err != (err != nil) { - t.Fatalf("case %d: expected err %#v", i, tc.err) - } - if !reflect.DeepEqual(actual, tc.result) { - t.Fatalf( - "case %d: expected %#v, got %#v", - i, tc.result, actual) - } - } -} - -func TestWeaklyTypedHook(t *testing.T) { - var f DecodeHookFunc = WeaklyTypedHook - - boolType := reflect.TypeOf(true) - strType := reflect.TypeOf("") - sliceType := reflect.TypeOf([]byte("")) - cases := []struct { - f, t reflect.Type - data interface{} - result interface{} - err bool - }{ - // TO STRING - { - boolType, - strType, - false, - "0", - false, - }, - - { - boolType, - strType, - true, - "1", - false, - }, - - { - reflect.TypeOf(float32(1)), - strType, - float32(7), - "7", - false, - }, - - { - reflect.TypeOf(int(1)), - strType, - int(7), - "7", - false, - }, - - { - sliceType, - strType, - []uint8("foo"), - "foo", - false, - }, - - { - reflect.TypeOf(uint(1)), - strType, - uint(7), - "7", - false, - }, - } - - for i, tc := range cases { - actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data) - if tc.err != (err != nil) { - t.Fatalf("case %d: expected err %#v", i, tc.err) - } - if !reflect.DeepEqual(actual, tc.result) { - t.Fatalf( - "case %d: expected %#v, got %#v", - i, tc.result, actual) - } - } -} diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go index 30a9957c65..13cc5e3d67 100644 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ b/vendor/github.com/mitchellh/mapstructure/mapstructure.go @@ -114,12 +114,12 @@ type Metadata struct { Unused []string } -// Decode takes a map and uses reflection to convert it into the -// given Go native structure. val must be a pointer to a struct. -func Decode(m interface{}, rawVal interface{}) error { +// Decode takes an input structure and uses reflection to translate it to +// the output structure. output must be a pointer to a map or struct. +func Decode(input interface{}, output interface{}) error { config := &DecoderConfig{ Metadata: nil, - Result: rawVal, + Result: output, } decoder, err := NewDecoder(config) @@ -127,7 +127,7 @@ func Decode(m interface{}, rawVal interface{}) error { return err } - return decoder.Decode(m) + return decoder.Decode(input) } // WeakDecode is the same as Decode but is shorthand to enable @@ -147,6 +147,40 @@ func WeakDecode(input, output interface{}) error { return decoder.Decode(input) } +// DecodeMetadata is the same as Decode, but is shorthand to +// enable metadata collection. See DecoderConfig for more info. +func DecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { + config := &DecoderConfig{ + Metadata: metadata, + Result: output, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + +// WeakDecodeMetadata is the same as Decode, but is shorthand to +// enable both WeaklyTypedInput and metadata collection. See +// DecoderConfig for more info. +func WeakDecodeMetadata(input interface{}, output interface{}, metadata *Metadata) error { + config := &DecoderConfig{ + Metadata: metadata, + Result: output, + WeaklyTypedInput: true, + } + + decoder, err := NewDecoder(config) + if err != nil { + return err + } + + return decoder.Decode(input) +} + // NewDecoder returns a new decoder for the given configuration. Once // a decoder has been returned, the same configuration must not be used // again. @@ -184,68 +218,81 @@ func NewDecoder(config *DecoderConfig) (*Decoder, error) { // Decode decodes the given raw interface to the target pointer specified // by the configuration. -func (d *Decoder) Decode(raw interface{}) error { - return d.decode("", raw, reflect.ValueOf(d.config.Result).Elem()) +func (d *Decoder) Decode(input interface{}) error { + return d.decode("", input, reflect.ValueOf(d.config.Result).Elem()) } // Decodes an unknown data type into a specific reflection value. -func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error { - if data == nil { - // If the data is nil, then we don't set anything. +func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) error { + if input == nil { + // If the data is nil, then we don't set anything, unless ZeroFields is set + // to true. + if d.config.ZeroFields { + outVal.Set(reflect.Zero(outVal.Type())) + + if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } + } return nil } - dataVal := reflect.ValueOf(data) - if !dataVal.IsValid() { - // If the data value is invalid, then we just set the value + inputVal := reflect.ValueOf(input) + if !inputVal.IsValid() { + // If the input value is invalid, then we just set the value // to be the zero value. - val.Set(reflect.Zero(val.Type())) + outVal.Set(reflect.Zero(outVal.Type())) + if d.config.Metadata != nil && name != "" { + d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) + } return nil } if d.config.DecodeHook != nil { - // We have a DecodeHook, so let's pre-process the data. + // We have a DecodeHook, so let's pre-process the input. var err error - data, err = DecodeHookExec( + input, err = DecodeHookExec( d.config.DecodeHook, - dataVal.Type(), val.Type(), data) + inputVal.Type(), outVal.Type(), input) if err != nil { return fmt.Errorf("error decoding '%s': %s", name, err) } } var err error - dataKind := getKind(val) - switch dataKind { + inputKind := getKind(outVal) + switch inputKind { case reflect.Bool: - err = d.decodeBool(name, data, val) + err = d.decodeBool(name, input, outVal) case reflect.Interface: - err = d.decodeBasic(name, data, val) + err = d.decodeBasic(name, input, outVal) case reflect.String: - err = d.decodeString(name, data, val) + err = d.decodeString(name, input, outVal) case reflect.Int: - err = d.decodeInt(name, data, val) + err = d.decodeInt(name, input, outVal) case reflect.Uint: - err = d.decodeUint(name, data, val) + err = d.decodeUint(name, input, outVal) case reflect.Float32: - err = d.decodeFloat(name, data, val) + err = d.decodeFloat(name, input, outVal) case reflect.Struct: - err = d.decodeStruct(name, data, val) + err = d.decodeStruct(name, input, outVal) case reflect.Map: - err = d.decodeMap(name, data, val) + err = d.decodeMap(name, input, outVal) case reflect.Ptr: - err = d.decodePtr(name, data, val) + err = d.decodePtr(name, input, outVal) case reflect.Slice: - err = d.decodeSlice(name, data, val) + err = d.decodeSlice(name, input, outVal) + case reflect.Array: + err = d.decodeArray(name, input, outVal) case reflect.Func: - err = d.decodeFunc(name, data, val) + err = d.decodeFunc(name, input, outVal) default: // If we reached this point then we weren't able to decode it - return fmt.Errorf("%s: unsupported type: %s", name, dataKind) + return fmt.Errorf("%s: unsupported type: %s", name, inputKind) } // If we reached here, then we successfully decoded SOMETHING, so - // mark the key as used if we're tracking metadata. + // mark the key as used if we're tracking metainput. if d.config.Metadata != nil && name != "" { d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) } @@ -256,6 +303,9 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error // This decodes a basic type (bool, int, string, etc.) and sets the // value to "data" of that type. func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { + if val.IsValid() && val.Elem().IsValid() { + return d.decode(name, data, val.Elem()) + } dataVal := reflect.ValueOf(data) if !dataVal.IsValid() { dataVal = reflect.Zero(val.Type()) @@ -292,12 +342,22 @@ func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) val.SetString(strconv.FormatUint(dataVal.Uint(), 10)) case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64)) - case dataKind == reflect.Slice && d.config.WeaklyTypedInput: + case dataKind == reflect.Slice && d.config.WeaklyTypedInput, + dataKind == reflect.Array && d.config.WeaklyTypedInput: dataType := dataVal.Type() elemKind := dataType.Elem().Kind() - switch { - case elemKind == reflect.Uint8: - val.SetString(string(dataVal.Interface().([]uint8))) + switch elemKind { + case reflect.Uint8: + var uints []uint8 + if dataKind == reflect.Array { + uints = make([]uint8, dataVal.Len(), dataVal.Len()) + for i := range uints { + uints[i] = dataVal.Index(i).Interface().(uint8) + } + } else { + uints = dataVal.Interface().([]uint8) + } + val.SetString(string(uints)) default: converted = false } @@ -487,34 +547,50 @@ func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) er valMap = reflect.MakeMap(mapType) } - // Check input type + // Check input type and based on the input type jump to the proper func dataVal := reflect.Indirect(reflect.ValueOf(data)) - if dataVal.Kind() != reflect.Map { - // In weak mode, we accept a slice of maps as an input... - if d.config.WeaklyTypedInput { - switch dataVal.Kind() { - case reflect.Array, reflect.Slice: - // Special case for BC reasons (covered by tests) - if dataVal.Len() == 0 { - val.Set(valMap) - return nil - } + switch dataVal.Kind() { + case reflect.Map: + return d.decodeMapFromMap(name, dataVal, val, valMap) - for i := 0; i < dataVal.Len(); i++ { - err := d.decode( - fmt.Sprintf("%s[%d]", name, i), - dataVal.Index(i).Interface(), val) - if err != nil { - return err - } - } + case reflect.Struct: + return d.decodeMapFromStruct(name, dataVal, val, valMap) - return nil - } + case reflect.Array, reflect.Slice: + if d.config.WeaklyTypedInput { + return d.decodeMapFromSlice(name, dataVal, val, valMap) } + fallthrough + + default: return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) } +} + +func (d *Decoder) decodeMapFromSlice(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + // Special case for BC reasons (covered by tests) + if dataVal.Len() == 0 { + val.Set(valMap) + return nil + } + + for i := 0; i < dataVal.Len(); i++ { + err := d.decode( + fmt.Sprintf("%s[%d]", name, i), + dataVal.Index(i).Interface(), val) + if err != nil { + return err + } + } + + return nil +} + +func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + valType := val.Type() + valKeyType := valType.Key() + valElemType := valType.Elem() // Accumulate errors errors := make([]string, 0) @@ -551,22 +627,106 @@ func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) er return nil } +func (d *Decoder) decodeMapFromStruct(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { + typ := dataVal.Type() + for i := 0; i < typ.NumField(); i++ { + // Get the StructField first since this is a cheap operation. If the + // field is unexported, then ignore it. + f := typ.Field(i) + if f.PkgPath != "" { + continue + } + + // Next get the actual value of this field and verify it is assignable + // to the map value. + v := dataVal.Field(i) + if !v.Type().AssignableTo(valMap.Type().Elem()) { + return fmt.Errorf("cannot assign type '%s' to map value field of type '%s'", v.Type(), valMap.Type().Elem()) + } + + tagValue := f.Tag.Get(d.config.TagName) + tagParts := strings.Split(tagValue, ",") + + // Determine the name of the key in the map + keyName := f.Name + if tagParts[0] != "" { + if tagParts[0] == "-" { + continue + } + keyName = tagParts[0] + } + + // If "squash" is specified in the tag, we squash the field down. + squash := false + for _, tag := range tagParts[1:] { + if tag == "squash" { + squash = true + break + } + } + if squash && v.Kind() != reflect.Struct { + return fmt.Errorf("cannot squash non-struct type '%s'", v.Type()) + } + + switch v.Kind() { + // this is an embedded struct, so handle it differently + case reflect.Struct: + x := reflect.New(v.Type()) + x.Elem().Set(v) + + vType := valMap.Type() + vKeyType := vType.Key() + vElemType := vType.Elem() + mType := reflect.MapOf(vKeyType, vElemType) + vMap := reflect.MakeMap(mType) + + err := d.decode(keyName, x.Interface(), vMap) + if err != nil { + return err + } + + if squash { + for _, k := range vMap.MapKeys() { + valMap.SetMapIndex(k, vMap.MapIndex(k)) + } + } else { + valMap.SetMapIndex(reflect.ValueOf(keyName), vMap) + } + + default: + valMap.SetMapIndex(reflect.ValueOf(keyName), v) + } + } + + if val.CanAddr() { + val.Set(valMap) + } + + return nil +} + func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) error { // Create an element of the concrete (non pointer) type and decode // into that. Then set the value of the pointer to this type. valType := val.Type() valElemType := valType.Elem() - realVal := val - if realVal.IsNil() || d.config.ZeroFields { - realVal = reflect.New(valElemType) - } + if val.CanSet() { + realVal := val + if realVal.IsNil() || d.config.ZeroFields { + realVal = reflect.New(valElemType) + } - if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { - return err - } + if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { + return err + } - val.Set(realVal) + val.Set(realVal) + } else { + if err := d.decode(name, data, reflect.Indirect(val)); err != nil { + return err + } + } return nil } @@ -602,7 +762,8 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) val.Set(reflect.MakeSlice(sliceType, 0, 0)) return nil } - + case dataValKind == reflect.String && valElemType.Kind() == reflect.Uint8: + return d.decodeSlice(name, []byte(dataVal.String()), val) // All other types we try to convert to the slice type // and "lift" it into it. i.e. a string becomes a string slice. default: @@ -610,7 +771,6 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) return d.decodeSlice(name, []interface{}{data}, val) } } - return fmt.Errorf( "'%s': source data must be an array or slice, got %s", name, dataValKind) @@ -647,6 +807,73 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) return nil } +func (d *Decoder) decodeArray(name string, data interface{}, val reflect.Value) error { + dataVal := reflect.Indirect(reflect.ValueOf(data)) + dataValKind := dataVal.Kind() + valType := val.Type() + valElemType := valType.Elem() + arrayType := reflect.ArrayOf(valType.Len(), valElemType) + + valArray := val + + if valArray.Interface() == reflect.Zero(valArray.Type()).Interface() || d.config.ZeroFields { + // Check input type + if dataValKind != reflect.Array && dataValKind != reflect.Slice { + if d.config.WeaklyTypedInput { + switch { + // Empty maps turn into empty arrays + case dataValKind == reflect.Map: + if dataVal.Len() == 0 { + val.Set(reflect.Zero(arrayType)) + return nil + } + + // All other types we try to convert to the array type + // and "lift" it into it. i.e. a string becomes a string array. + default: + // Just re-try this function with data as a slice. + return d.decodeArray(name, []interface{}{data}, val) + } + } + + return fmt.Errorf( + "'%s': source data must be an array or slice, got %s", name, dataValKind) + + } + if dataVal.Len() > arrayType.Len() { + return fmt.Errorf( + "'%s': expected source data to have length less or equal to %d, got %d", name, arrayType.Len(), dataVal.Len()) + + } + + // Make a new array to hold our result, same size as the original data. + valArray = reflect.New(arrayType).Elem() + } + + // Accumulate any errors + errors := make([]string, 0) + + for i := 0; i < dataVal.Len(); i++ { + currentData := dataVal.Index(i).Interface() + currentField := valArray.Index(i) + + fieldName := fmt.Sprintf("%s[%d]", name, i) + if err := d.decode(fieldName, currentData, currentField); err != nil { + errors = appendErrors(errors, err) + } + } + + // Finally, set the value to the array we built up + val.Set(valArray) + + // If there were errors, we return those + if len(errors) > 0 { + return &Error{errors} + } + + return nil +} + func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) @@ -716,7 +943,7 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) errors = appendErrors(errors, fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind)) } else { - structs = append(structs, val.FieldByName(fieldType.Name)) + structs = append(structs, structVal.FieldByName(fieldType.Name)) } continue } diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go deleted file mode 100644 index 41d2a41f75..0000000000 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure_benchmark_test.go +++ /dev/null @@ -1,279 +0,0 @@ -package mapstructure - -import ( - "encoding/json" - "testing" -) - -func Benchmark_Decode(b *testing.B) { - type Person struct { - Name string - Age int - Emails []string - Extra map[string]string - } - - input := map[string]interface{}{ - "name": "Mitchell", - "age": 91, - "emails": []string{"one", "two", "three"}, - "extra": map[string]string{ - "twitter": "mitchellh", - }, - } - - var result Person - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -// decodeViaJSON takes the map data and passes it through encoding/json to convert it into the -// given Go native structure pointed to by v. v must be a pointer to a struct. -func decodeViaJSON(data interface{}, v interface{}) error { - // Perform the task by simply marshalling the input into JSON, - // then unmarshalling it into target native Go struct. - b, err := json.Marshal(data) - if err != nil { - return err - } - return json.Unmarshal(b, v) -} - -func Benchmark_DecodeViaJSON(b *testing.B) { - type Person struct { - Name string - Age int - Emails []string - Extra map[string]string - } - - input := map[string]interface{}{ - "name": "Mitchell", - "age": 91, - "emails": []string{"one", "two", "three"}, - "extra": map[string]string{ - "twitter": "mitchellh", - }, - } - - var result Person - for i := 0; i < b.N; i++ { - decodeViaJSON(input, &result) - } -} - -func Benchmark_DecodeBasic(b *testing.B) { - input := map[string]interface{}{ - "vstring": "foo", - "vint": 42, - "Vuint": 42, - "vbool": true, - "Vfloat": 42.42, - "vsilent": true, - "vdata": 42, - } - - var result Basic - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeEmbedded(b *testing.B) { - input := map[string]interface{}{ - "vstring": "foo", - "Basic": map[string]interface{}{ - "vstring": "innerfoo", - }, - "vunique": "bar", - } - - var result Embedded - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeTypeConversion(b *testing.B) { - input := map[string]interface{}{ - "IntToFloat": 42, - "IntToUint": 42, - "IntToBool": 1, - "IntToString": 42, - "UintToInt": 42, - "UintToFloat": 42, - "UintToBool": 42, - "UintToString": 42, - "BoolToInt": true, - "BoolToUint": true, - "BoolToFloat": true, - "BoolToString": true, - "FloatToInt": 42.42, - "FloatToUint": 42.42, - "FloatToBool": 42.42, - "FloatToString": 42.42, - "StringToInt": "42", - "StringToUint": "42", - "StringToBool": "1", - "StringToFloat": "42.42", - "SliceToMap": []interface{}{}, - "MapToSlice": map[string]interface{}{}, - } - - var resultStrict TypeConversionResult - for i := 0; i < b.N; i++ { - Decode(input, &resultStrict) - } -} - -func Benchmark_DecodeMap(b *testing.B) { - input := map[string]interface{}{ - "vfoo": "foo", - "vother": map[interface{}]interface{}{ - "foo": "foo", - "bar": "bar", - }, - } - - var result Map - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeMapOfStruct(b *testing.B) { - input := map[string]interface{}{ - "value": map[string]interface{}{ - "foo": map[string]string{"vstring": "one"}, - "bar": map[string]string{"vstring": "two"}, - }, - } - - var result MapOfStruct - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeSlice(b *testing.B) { - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": []string{"foo", "bar", "baz"}, - } - - var result Slice - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeSliceOfStruct(b *testing.B) { - input := map[string]interface{}{ - "value": []map[string]interface{}{ - {"vstring": "one"}, - {"vstring": "two"}, - }, - } - - var result SliceOfStruct - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} - -func Benchmark_DecodeWeaklyTypedInput(b *testing.B) { - type Person struct { - Name string - Age int - Emails []string - } - - // This input can come from anywhere, but typically comes from - // something like decoding JSON, generated by a weakly typed language - // such as PHP. - input := map[string]interface{}{ - "name": 123, // number => string - "age": "42", // string => number - "emails": map[string]interface{}{}, // empty map => empty array - } - - var result Person - config := &DecoderConfig{ - WeaklyTypedInput: true, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - panic(err) - } - - for i := 0; i < b.N; i++ { - decoder.Decode(input) - } -} - -func Benchmark_DecodeMetadata(b *testing.B) { - type Person struct { - Name string - Age int - } - - input := map[string]interface{}{ - "name": "Mitchell", - "age": 91, - "email": "foo@bar.com", - } - - var md Metadata - var result Person - config := &DecoderConfig{ - Metadata: &md, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - panic(err) - } - - for i := 0; i < b.N; i++ { - decoder.Decode(input) - } -} - -func Benchmark_DecodeMetadataEmbedded(b *testing.B) { - input := map[string]interface{}{ - "vstring": "foo", - "vunique": "bar", - } - - var md Metadata - var result EmbeddedSquash - config := &DecoderConfig{ - Metadata: &md, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - b.Fatalf("err: %s", err) - } - - for i := 0; i < b.N; i++ { - decoder.Decode(input) - } -} - -func Benchmark_DecodeTagged(b *testing.B) { - input := map[string]interface{}{ - "foo": "bar", - "bar": "value", - } - - var result Tagged - for i := 0; i < b.N; i++ { - Decode(input, &result) - } -} diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go deleted file mode 100644 index 08e495664f..0000000000 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure_bugs_test.go +++ /dev/null @@ -1,260 +0,0 @@ -package mapstructure - -import "testing" - -// GH-1 -func TestDecode_NilValue(t *testing.T) { - input := map[string]interface{}{ - "vfoo": nil, - "vother": nil, - } - - var result Map - err := Decode(input, &result) - if err != nil { - t.Fatalf("should not error: %s", err) - } - - if result.Vfoo != "" { - t.Fatalf("value should be default: %s", result.Vfoo) - } - - if result.Vother != nil { - t.Fatalf("Vother should be nil: %s", result.Vother) - } -} - -// GH-10 -func TestDecode_mapInterfaceInterface(t *testing.T) { - input := map[interface{}]interface{}{ - "vfoo": nil, - "vother": nil, - } - - var result Map - err := Decode(input, &result) - if err != nil { - t.Fatalf("should not error: %s", err) - } - - if result.Vfoo != "" { - t.Fatalf("value should be default: %s", result.Vfoo) - } - - if result.Vother != nil { - t.Fatalf("Vother should be nil: %s", result.Vother) - } -} - -// #48 -func TestNestedTypePointerWithDefaults(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": map[string]interface{}{ - "vstring": "foo", - "vint": 42, - "vbool": true, - }, - } - - result := NestedPointer{ - Vbar: &Basic{ - Vuint: 42, - }, - } - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - if result.Vbar.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring) - } - - if result.Vbar.Vint != 42 { - t.Errorf("vint value should be 42: %#v", result.Vbar.Vint) - } - - if result.Vbar.Vbool != true { - t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool) - } - - if result.Vbar.Vextra != "" { - t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra) - } - - // this is the error - if result.Vbar.Vuint != 42 { - t.Errorf("vuint value should be 42: %#v", result.Vbar.Vuint) - } - -} - -type NestedSlice struct { - Vfoo string - Vbars []Basic - Vempty []Basic -} - -// #48 -func TestNestedTypeSliceWithDefaults(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbars": []map[string]interface{}{ - {"vstring": "foo", "vint": 42, "vbool": true}, - {"vint": 42, "vbool": true}, - }, - "vempty": []map[string]interface{}{ - {"vstring": "foo", "vint": 42, "vbool": true}, - {"vint": 42, "vbool": true}, - }, - } - - result := NestedSlice{ - Vbars: []Basic{ - {Vuint: 42}, - {Vstring: "foo"}, - }, - } - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - if result.Vbars[0].Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vbars[0].Vstring) - } - // this is the error - if result.Vbars[0].Vuint != 42 { - t.Errorf("vuint value should be 42: %#v", result.Vbars[0].Vuint) - } -} - -// #48 workaround -func TestNestedTypeWithDefaults(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": map[string]interface{}{ - "vstring": "foo", - "vint": 42, - "vbool": true, - }, - } - - result := Nested{ - Vbar: Basic{ - Vuint: 42, - }, - } - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - if result.Vbar.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring) - } - - if result.Vbar.Vint != 42 { - t.Errorf("vint value should be 42: %#v", result.Vbar.Vint) - } - - if result.Vbar.Vbool != true { - t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool) - } - - if result.Vbar.Vextra != "" { - t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra) - } - - // this is the error - if result.Vbar.Vuint != 42 { - t.Errorf("vuint value should be 42: %#v", result.Vbar.Vuint) - } - -} - -// #67 panic() on extending slices (decodeSlice with disabled ZeroValues) -func TestDecodeSliceToEmptySliceWOZeroing(t *testing.T) { - t.Parallel() - - type TestStruct struct { - Vfoo []string - } - - decode := func(m interface{}, rawVal interface{}) error { - config := &DecoderConfig{ - Metadata: nil, - Result: rawVal, - ZeroFields: false, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(m) - } - - { - input := map[string]interface{}{ - "vfoo": []string{"1"}, - } - - result := &TestStruct{} - - err := decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - } - - { - input := map[string]interface{}{ - "vfoo": []string{"1"}, - } - - result := &TestStruct{ - Vfoo: []string{}, - } - - err := decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - } - - { - input := map[string]interface{}{ - "vfoo": []string{"2", "3"}, - } - - result := &TestStruct{ - Vfoo: []string{"1"}, - } - - err := decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - } -} diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go deleted file mode 100644 index f17c214a8a..0000000000 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure_examples_test.go +++ /dev/null @@ -1,203 +0,0 @@ -package mapstructure - -import ( - "fmt" -) - -func ExampleDecode() { - type Person struct { - Name string - Age int - Emails []string - Extra map[string]string - } - - // This input can come from anywhere, but typically comes from - // something like decoding JSON where we're not quite sure of the - // struct initially. - input := map[string]interface{}{ - "name": "Mitchell", - "age": 91, - "emails": []string{"one", "two", "three"}, - "extra": map[string]string{ - "twitter": "mitchellh", - }, - } - - var result Person - err := Decode(input, &result) - if err != nil { - panic(err) - } - - fmt.Printf("%#v", result) - // Output: - // mapstructure.Person{Name:"Mitchell", Age:91, Emails:[]string{"one", "two", "three"}, Extra:map[string]string{"twitter":"mitchellh"}} -} - -func ExampleDecode_errors() { - type Person struct { - Name string - Age int - Emails []string - Extra map[string]string - } - - // This input can come from anywhere, but typically comes from - // something like decoding JSON where we're not quite sure of the - // struct initially. - input := map[string]interface{}{ - "name": 123, - "age": "bad value", - "emails": []int{1, 2, 3}, - } - - var result Person - err := Decode(input, &result) - if err == nil { - panic("should have an error") - } - - fmt.Println(err.Error()) - // Output: - // 5 error(s) decoding: - // - // * 'Age' expected type 'int', got unconvertible type 'string' - // * 'Emails[0]' expected type 'string', got unconvertible type 'int' - // * 'Emails[1]' expected type 'string', got unconvertible type 'int' - // * 'Emails[2]' expected type 'string', got unconvertible type 'int' - // * 'Name' expected type 'string', got unconvertible type 'int' -} - -func ExampleDecode_metadata() { - type Person struct { - Name string - Age int - } - - // This input can come from anywhere, but typically comes from - // something like decoding JSON where we're not quite sure of the - // struct initially. - input := map[string]interface{}{ - "name": "Mitchell", - "age": 91, - "email": "foo@bar.com", - } - - // For metadata, we make a more advanced DecoderConfig so we can - // more finely configure the decoder that is used. In this case, we - // just tell the decoder we want to track metadata. - var md Metadata - var result Person - config := &DecoderConfig{ - Metadata: &md, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - panic(err) - } - - if err := decoder.Decode(input); err != nil { - panic(err) - } - - fmt.Printf("Unused keys: %#v", md.Unused) - // Output: - // Unused keys: []string{"email"} -} - -func ExampleDecode_weaklyTypedInput() { - type Person struct { - Name string - Age int - Emails []string - } - - // This input can come from anywhere, but typically comes from - // something like decoding JSON, generated by a weakly typed language - // such as PHP. - input := map[string]interface{}{ - "name": 123, // number => string - "age": "42", // string => number - "emails": map[string]interface{}{}, // empty map => empty array - } - - var result Person - config := &DecoderConfig{ - WeaklyTypedInput: true, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - panic(err) - } - - err = decoder.Decode(input) - if err != nil { - panic(err) - } - - fmt.Printf("%#v", result) - // Output: mapstructure.Person{Name:"123", Age:42, Emails:[]string{}} -} - -func ExampleDecode_tags() { - // Note that the mapstructure tags defined in the struct type - // can indicate which fields the values are mapped to. - type Person struct { - Name string `mapstructure:"person_name"` - Age int `mapstructure:"person_age"` - } - - input := map[string]interface{}{ - "person_name": "Mitchell", - "person_age": 91, - } - - var result Person - err := Decode(input, &result) - if err != nil { - panic(err) - } - - fmt.Printf("%#v", result) - // Output: - // mapstructure.Person{Name:"Mitchell", Age:91} -} - -func ExampleDecode_embeddedStruct() { - // Squashing multiple embedded structs is allowed using the squash tag. - // This is demonstrated by creating a composite struct of multiple types - // and decoding into it. In this case, a person can carry with it both - // a Family and a Location, as well as their own FirstName. - type Family struct { - LastName string - } - type Location struct { - City string - } - type Person struct { - Family `mapstructure:",squash"` - Location `mapstructure:",squash"` - FirstName string - } - - input := map[string]interface{}{ - "FirstName": "Mitchell", - "LastName": "Hashimoto", - "City": "San Francisco", - } - - var result Person - err := Decode(input, &result) - if err != nil { - panic(err) - } - - fmt.Printf("%s %s, %s", result.FirstName, result.LastName, result.City) - // Output: - // Mitchell Hashimoto, San Francisco -} diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure_test.go b/vendor/github.com/mitchellh/mapstructure/mapstructure_test.go deleted file mode 100644 index 547af73318..0000000000 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure_test.go +++ /dev/null @@ -1,1193 +0,0 @@ -package mapstructure - -import ( - "encoding/json" - "io" - "reflect" - "sort" - "strings" - "testing" -) - -type Basic struct { - Vstring string - Vint int - Vuint uint - Vbool bool - Vfloat float64 - Vextra string - vsilent bool - Vdata interface{} - VjsonInt int - VjsonFloat float64 - VjsonNumber json.Number -} - -type BasicSquash struct { - Test Basic `mapstructure:",squash"` -} - -type Embedded struct { - Basic - Vunique string -} - -type EmbeddedPointer struct { - *Basic - Vunique string -} - -type EmbeddedSquash struct { - Basic `mapstructure:",squash"` - Vunique string -} - -type SliceAlias []string - -type EmbeddedSlice struct { - SliceAlias `mapstructure:"slice_alias"` - Vunique string -} - -type SquashOnNonStructType struct { - InvalidSquashType int `mapstructure:",squash"` -} - -type Map struct { - Vfoo string - Vother map[string]string -} - -type MapOfStruct struct { - Value map[string]Basic -} - -type Nested struct { - Vfoo string - Vbar Basic -} - -type NestedPointer struct { - Vfoo string - Vbar *Basic -} - -type NilInterface struct { - W io.Writer -} - -type Slice struct { - Vfoo string - Vbar []string -} - -type SliceOfStruct struct { - Value []Basic -} - -type Func struct { - Foo func() string -} - -type Tagged struct { - Extra string `mapstructure:"bar,what,what"` - Value string `mapstructure:"foo"` -} - -type TypeConversionResult struct { - IntToFloat float32 - IntToUint uint - IntToBool bool - IntToString string - UintToInt int - UintToFloat float32 - UintToBool bool - UintToString string - BoolToInt int - BoolToUint uint - BoolToFloat float32 - BoolToString string - FloatToInt int - FloatToUint uint - FloatToBool bool - FloatToString string - SliceUint8ToString string - StringToInt int - StringToUint uint - StringToBool bool - StringToFloat float32 - StringToStrSlice []string - StringToIntSlice []int - SliceToMap map[string]interface{} - MapToSlice []interface{} -} - -func TestBasicTypes(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - "vint": 42, - "Vuint": 42, - "vbool": true, - "Vfloat": 42.42, - "vsilent": true, - "vdata": 42, - "vjsonInt": json.Number("1234"), - "vjsonFloat": json.Number("1234.5"), - "vjsonNumber": json.Number("1234.5"), - } - - var result Basic - err := Decode(input, &result) - if err != nil { - t.Errorf("got an err: %s", err.Error()) - t.FailNow() - } - - if result.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vstring) - } - - if result.Vint != 42 { - t.Errorf("vint value should be 42: %#v", result.Vint) - } - - if result.Vuint != 42 { - t.Errorf("vuint value should be 42: %#v", result.Vuint) - } - - if result.Vbool != true { - t.Errorf("vbool value should be true: %#v", result.Vbool) - } - - if result.Vfloat != 42.42 { - t.Errorf("vfloat value should be 42.42: %#v", result.Vfloat) - } - - if result.Vextra != "" { - t.Errorf("vextra value should be empty: %#v", result.Vextra) - } - - if result.vsilent != false { - t.Error("vsilent should not be set, it is unexported") - } - - if result.Vdata != 42 { - t.Error("vdata should be valid") - } - - if result.VjsonInt != 1234 { - t.Errorf("vjsonint value should be 1234: %#v", result.VjsonInt) - } - - if result.VjsonFloat != 1234.5 { - t.Errorf("vjsonfloat value should be 1234.5: %#v", result.VjsonFloat) - } - - if !reflect.DeepEqual(result.VjsonNumber, json.Number("1234.5")) { - t.Errorf("vjsonnumber value should be '1234.5': %T, %#v", result.VjsonNumber, result.VjsonNumber) - } -} - -func TestBasic_IntWithFloat(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vint": float64(42), - } - - var result Basic - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err) - } -} - -func TestBasic_Merge(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vint": 42, - } - - var result Basic - result.Vuint = 100 - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - expected := Basic{ - Vint: 42, - Vuint: 100, - } - if !reflect.DeepEqual(result, expected) { - t.Fatalf("bad: %#v", result) - } -} - -func TestDecode_BasicSquash(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - } - - var result BasicSquash - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Test.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Test.Vstring) - } -} - -func TestDecode_Embedded(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - "Basic": map[string]interface{}{ - "vstring": "innerfoo", - }, - "vunique": "bar", - } - - var result Embedded - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vstring != "innerfoo" { - t.Errorf("vstring value should be 'innerfoo': %#v", result.Vstring) - } - - if result.Vunique != "bar" { - t.Errorf("vunique value should be 'bar': %#v", result.Vunique) - } -} - -func TestDecode_EmbeddedPointer(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - "Basic": map[string]interface{}{ - "vstring": "innerfoo", - }, - "vunique": "bar", - } - - var result EmbeddedPointer - err := Decode(input, &result) - if err != nil { - t.Fatalf("err: %s", err) - } - - expected := EmbeddedPointer{ - Basic: &Basic{ - Vstring: "innerfoo", - }, - Vunique: "bar", - } - if !reflect.DeepEqual(result, expected) { - t.Fatalf("bad: %#v", result) - } -} - -func TestDecode_EmbeddedSlice(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "slice_alias": []string{"foo", "bar"}, - "vunique": "bar", - } - - var result EmbeddedSlice - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if !reflect.DeepEqual(result.SliceAlias, SliceAlias([]string{"foo", "bar"})) { - t.Errorf("slice value: %#v", result.SliceAlias) - } - - if result.Vunique != "bar" { - t.Errorf("vunique value should be 'bar': %#v", result.Vunique) - } -} - -func TestDecode_EmbeddedSquash(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - "vunique": "bar", - } - - var result EmbeddedSquash - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vstring) - } - - if result.Vunique != "bar" { - t.Errorf("vunique value should be 'bar': %#v", result.Vunique) - } -} - -func TestDecode_SquashOnNonStructType(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "InvalidSquashType": 42, - } - - var result SquashOnNonStructType - err := Decode(input, &result) - if err == nil { - t.Fatal("unexpected success decoding invalid squash field type") - } else if !strings.Contains(err.Error(), "unsupported type for squash") { - t.Fatalf("unexpected error message for invalid squash field type: %s", err) - } -} - -func TestDecode_DecodeHook(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vint": "WHAT", - } - - decodeHook := func(from reflect.Kind, to reflect.Kind, v interface{}) (interface{}, error) { - if from == reflect.String && to != reflect.String { - return 5, nil - } - - return v, nil - } - - var result Basic - config := &DecoderConfig{ - DecodeHook: decodeHook, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - if result.Vint != 5 { - t.Errorf("vint should be 5: %#v", result.Vint) - } -} - -func TestDecode_DecodeHookType(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vint": "WHAT", - } - - decodeHook := func(from reflect.Type, to reflect.Type, v interface{}) (interface{}, error) { - if from.Kind() == reflect.String && - to.Kind() != reflect.String { - return 5, nil - } - - return v, nil - } - - var result Basic - config := &DecoderConfig{ - DecodeHook: decodeHook, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - if result.Vint != 5 { - t.Errorf("vint should be 5: %#v", result.Vint) - } -} - -func TestDecode_Nil(t *testing.T) { - t.Parallel() - - var input interface{} - result := Basic{ - Vstring: "foo", - } - - err := Decode(input, &result) - if err != nil { - t.Fatalf("err: %s", err) - } - - if result.Vstring != "foo" { - t.Fatalf("bad: %#v", result.Vstring) - } -} - -func TestDecode_NilInterfaceHook(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "w": "", - } - - decodeHook := func(f, t reflect.Type, v interface{}) (interface{}, error) { - if t.String() == "io.Writer" { - return nil, nil - } - - return v, nil - } - - var result NilInterface - config := &DecoderConfig{ - DecodeHook: decodeHook, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - if result.W != nil { - t.Errorf("W should be nil: %#v", result.W) - } -} - -func TestDecode_FuncHook(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "foo": "baz", - } - - decodeHook := func(f, t reflect.Type, v interface{}) (interface{}, error) { - if t.Kind() != reflect.Func { - return v, nil - } - val := v.(string) - return func() string { return val }, nil - } - - var result Func - config := &DecoderConfig{ - DecodeHook: decodeHook, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - if result.Foo() != "baz" { - t.Errorf("Foo call result should be 'baz': %s", result.Foo()) - } -} - -func TestDecode_NonStruct(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "foo": "bar", - "bar": "baz", - } - - var result map[string]string - err := Decode(input, &result) - if err != nil { - t.Fatalf("err: %s", err) - } - - if result["foo"] != "bar" { - t.Fatal("foo is not bar") - } -} - -func TestDecode_StructMatch(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vbar": Basic{ - Vstring: "foo", - }, - } - - var result Nested - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vbar.Vstring != "foo" { - t.Errorf("bad: %#v", result) - } -} - -func TestDecode_TypeConversion(t *testing.T) { - input := map[string]interface{}{ - "IntToFloat": 42, - "IntToUint": 42, - "IntToBool": 1, - "IntToString": 42, - "UintToInt": 42, - "UintToFloat": 42, - "UintToBool": 42, - "UintToString": 42, - "BoolToInt": true, - "BoolToUint": true, - "BoolToFloat": true, - "BoolToString": true, - "FloatToInt": 42.42, - "FloatToUint": 42.42, - "FloatToBool": 42.42, - "FloatToString": 42.42, - "SliceUint8ToString": []uint8("foo"), - "StringToInt": "42", - "StringToUint": "42", - "StringToBool": "1", - "StringToFloat": "42.42", - "StringToStrSlice": "A", - "StringToIntSlice": "42", - "SliceToMap": []interface{}{}, - "MapToSlice": map[string]interface{}{}, - } - - expectedResultStrict := TypeConversionResult{ - IntToFloat: 42.0, - IntToUint: 42, - UintToInt: 42, - UintToFloat: 42, - BoolToInt: 0, - BoolToUint: 0, - BoolToFloat: 0, - FloatToInt: 42, - FloatToUint: 42, - } - - expectedResultWeak := TypeConversionResult{ - IntToFloat: 42.0, - IntToUint: 42, - IntToBool: true, - IntToString: "42", - UintToInt: 42, - UintToFloat: 42, - UintToBool: true, - UintToString: "42", - BoolToInt: 1, - BoolToUint: 1, - BoolToFloat: 1, - BoolToString: "1", - FloatToInt: 42, - FloatToUint: 42, - FloatToBool: true, - FloatToString: "42.42", - SliceUint8ToString: "foo", - StringToInt: 42, - StringToUint: 42, - StringToBool: true, - StringToFloat: 42.42, - StringToStrSlice: []string{"A"}, - StringToIntSlice: []int{42}, - SliceToMap: map[string]interface{}{}, - MapToSlice: []interface{}{}, - } - - // Test strict type conversion - var resultStrict TypeConversionResult - err := Decode(input, &resultStrict) - if err == nil { - t.Errorf("should return an error") - } - if !reflect.DeepEqual(resultStrict, expectedResultStrict) { - t.Errorf("expected %v, got: %v", expectedResultStrict, resultStrict) - } - - // Test weak type conversion - var decoder *Decoder - var resultWeak TypeConversionResult - - config := &DecoderConfig{ - WeaklyTypedInput: true, - Result: &resultWeak, - } - - decoder, err = NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - if !reflect.DeepEqual(resultWeak, expectedResultWeak) { - t.Errorf("expected \n%#v, got: \n%#v", expectedResultWeak, resultWeak) - } -} - -func TestDecoder_ErrorUnused(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "hello", - "foo": "bar", - } - - var result Basic - config := &DecoderConfig{ - ErrorUnused: true, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err == nil { - t.Fatal("expected error") - } -} - -func TestMap(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vother": map[interface{}]interface{}{ - "foo": "foo", - "bar": "bar", - }, - } - - var result Map - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an error: %s", err) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - if result.Vother == nil { - t.Fatal("vother should not be nil") - } - - if len(result.Vother) != 2 { - t.Error("vother should have two items") - } - - if result.Vother["foo"] != "foo" { - t.Errorf("'foo' key should be foo, got: %#v", result.Vother["foo"]) - } - - if result.Vother["bar"] != "bar" { - t.Errorf("'bar' key should be bar, got: %#v", result.Vother["bar"]) - } -} - -func TestMapMerge(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vother": map[interface{}]interface{}{ - "foo": "foo", - "bar": "bar", - }, - } - - var result Map - result.Vother = map[string]string{"hello": "world"} - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an error: %s", err) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - expected := map[string]string{ - "foo": "foo", - "bar": "bar", - "hello": "world", - } - if !reflect.DeepEqual(result.Vother, expected) { - t.Errorf("bad: %#v", result.Vother) - } -} - -func TestMapOfStruct(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "value": map[string]interface{}{ - "foo": map[string]string{"vstring": "one"}, - "bar": map[string]string{"vstring": "two"}, - }, - } - - var result MapOfStruct - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err) - } - - if result.Value == nil { - t.Fatal("value should not be nil") - } - - if len(result.Value) != 2 { - t.Error("value should have two items") - } - - if result.Value["foo"].Vstring != "one" { - t.Errorf("foo value should be 'one', got: %s", result.Value["foo"].Vstring) - } - - if result.Value["bar"].Vstring != "two" { - t.Errorf("bar value should be 'two', got: %s", result.Value["bar"].Vstring) - } -} - -func TestNestedType(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": map[string]interface{}{ - "vstring": "foo", - "vint": 42, - "vbool": true, - }, - } - - var result Nested - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - if result.Vbar.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring) - } - - if result.Vbar.Vint != 42 { - t.Errorf("vint value should be 42: %#v", result.Vbar.Vint) - } - - if result.Vbar.Vbool != true { - t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool) - } - - if result.Vbar.Vextra != "" { - t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra) - } -} - -func TestNestedTypePointer(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": &map[string]interface{}{ - "vstring": "foo", - "vint": 42, - "vbool": true, - }, - } - - var result NestedPointer - err := Decode(input, &result) - if err != nil { - t.Fatalf("got an err: %s", err.Error()) - } - - if result.Vfoo != "foo" { - t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) - } - - if result.Vbar.Vstring != "foo" { - t.Errorf("vstring value should be 'foo': %#v", result.Vbar.Vstring) - } - - if result.Vbar.Vint != 42 { - t.Errorf("vint value should be 42: %#v", result.Vbar.Vint) - } - - if result.Vbar.Vbool != true { - t.Errorf("vbool value should be true: %#v", result.Vbar.Vbool) - } - - if result.Vbar.Vextra != "" { - t.Errorf("vextra value should be empty: %#v", result.Vbar.Vextra) - } -} - -func TestSlice(t *testing.T) { - t.Parallel() - - inputStringSlice := map[string]interface{}{ - "vfoo": "foo", - "vbar": []string{"foo", "bar", "baz"}, - } - - inputStringSlicePointer := map[string]interface{}{ - "vfoo": "foo", - "vbar": &[]string{"foo", "bar", "baz"}, - } - - outputStringSlice := &Slice{ - "foo", - []string{"foo", "bar", "baz"}, - } - - testSliceInput(t, inputStringSlice, outputStringSlice) - testSliceInput(t, inputStringSlicePointer, outputStringSlice) -} - -func TestInvalidSlice(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": 42, - } - - result := Slice{} - err := Decode(input, &result) - if err == nil { - t.Errorf("expected failure") - } -} - -func TestSliceOfStruct(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "value": []map[string]interface{}{ - {"vstring": "one"}, - {"vstring": "two"}, - }, - } - - var result SliceOfStruct - err := Decode(input, &result) - if err != nil { - t.Fatalf("got unexpected error: %s", err) - } - - if len(result.Value) != 2 { - t.Fatalf("expected two values, got %d", len(result.Value)) - } - - if result.Value[0].Vstring != "one" { - t.Errorf("first value should be 'one', got: %s", result.Value[0].Vstring) - } - - if result.Value[1].Vstring != "two" { - t.Errorf("second value should be 'two', got: %s", result.Value[1].Vstring) - } -} - -func TestSliceToMap(t *testing.T) { - t.Parallel() - - input := []map[string]interface{}{ - { - "foo": "bar", - }, - { - "bar": "baz", - }, - } - - var result map[string]interface{} - err := WeakDecode(input, &result) - if err != nil { - t.Fatalf("got an error: %s", err) - } - - expected := map[string]interface{}{ - "foo": "bar", - "bar": "baz", - } - if !reflect.DeepEqual(result, expected) { - t.Errorf("bad: %#v", result) - } -} - -func TestInvalidType(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": 42, - } - - var result Basic - err := Decode(input, &result) - if err == nil { - t.Fatal("error should exist") - } - - derr, ok := err.(*Error) - if !ok { - t.Fatalf("error should be kind of Error, instead: %#v", err) - } - - if derr.Errors[0] != "'Vstring' expected type 'string', got unconvertible type 'int'" { - t.Errorf("got unexpected error: %s", err) - } - - inputNegIntUint := map[string]interface{}{ - "vuint": -42, - } - - err = Decode(inputNegIntUint, &result) - if err == nil { - t.Fatal("error should exist") - } - - derr, ok = err.(*Error) - if !ok { - t.Fatalf("error should be kind of Error, instead: %#v", err) - } - - if derr.Errors[0] != "cannot parse 'Vuint', -42 overflows uint" { - t.Errorf("got unexpected error: %s", err) - } - - inputNegFloatUint := map[string]interface{}{ - "vuint": -42.0, - } - - err = Decode(inputNegFloatUint, &result) - if err == nil { - t.Fatal("error should exist") - } - - derr, ok = err.(*Error) - if !ok { - t.Fatalf("error should be kind of Error, instead: %#v", err) - } - - if derr.Errors[0] != "cannot parse 'Vuint', -42.000000 overflows uint" { - t.Errorf("got unexpected error: %s", err) - } -} - -func TestMetadata(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vfoo": "foo", - "vbar": map[string]interface{}{ - "vstring": "foo", - "Vuint": 42, - "foo": "bar", - }, - "bar": "nil", - } - - var md Metadata - var result Nested - config := &DecoderConfig{ - Metadata: &md, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("err: %s", err.Error()) - } - - expectedKeys := []string{"Vbar", "Vbar.Vstring", "Vbar.Vuint", "Vfoo"} - sort.Strings(md.Keys) - if !reflect.DeepEqual(md.Keys, expectedKeys) { - t.Fatalf("bad keys: %#v", md.Keys) - } - - expectedUnused := []string{"Vbar.foo", "bar"} - if !reflect.DeepEqual(md.Unused, expectedUnused) { - t.Fatalf("bad unused: %#v", md.Unused) - } -} - -func TestMetadata_Embedded(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "vstring": "foo", - "vunique": "bar", - } - - var md Metadata - var result EmbeddedSquash - config := &DecoderConfig{ - Metadata: &md, - Result: &result, - } - - decoder, err := NewDecoder(config) - if err != nil { - t.Fatalf("err: %s", err) - } - - err = decoder.Decode(input) - if err != nil { - t.Fatalf("err: %s", err.Error()) - } - - expectedKeys := []string{"Vstring", "Vunique"} - - sort.Strings(md.Keys) - if !reflect.DeepEqual(md.Keys, expectedKeys) { - t.Fatalf("bad keys: %#v", md.Keys) - } - - expectedUnused := []string{} - if !reflect.DeepEqual(md.Unused, expectedUnused) { - t.Fatalf("bad unused: %#v", md.Unused) - } -} - -func TestNonPtrValue(t *testing.T) { - t.Parallel() - - err := Decode(map[string]interface{}{}, Basic{}) - if err == nil { - t.Fatal("error should exist") - } - - if err.Error() != "result must be a pointer" { - t.Errorf("got unexpected error: %s", err) - } -} - -func TestTagged(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "foo": "bar", - "bar": "value", - } - - var result Tagged - err := Decode(input, &result) - if err != nil { - t.Fatalf("unexpected error: %s", err) - } - - if result.Value != "bar" { - t.Errorf("value should be 'bar', got: %#v", result.Value) - } - - if result.Extra != "value" { - t.Errorf("extra should be 'value', got: %#v", result.Extra) - } -} - -func TestWeakDecode(t *testing.T) { - t.Parallel() - - input := map[string]interface{}{ - "foo": "4", - "bar": "value", - } - - var result struct { - Foo int - Bar string - } - - if err := WeakDecode(input, &result); err != nil { - t.Fatalf("err: %s", err) - } - if result.Foo != 4 { - t.Fatalf("bad: %#v", result) - } - if result.Bar != "value" { - t.Fatalf("bad: %#v", result) - } -} - -func testSliceInput(t *testing.T, input map[string]interface{}, expected *Slice) { - var result Slice - err := Decode(input, &result) - if err != nil { - t.Fatalf("got error: %s", err) - } - - if result.Vfoo != expected.Vfoo { - t.Errorf("Vfoo expected '%s', got '%s'", expected.Vfoo, result.Vfoo) - } - - if result.Vbar == nil { - t.Fatalf("Vbar a slice, got '%#v'", result.Vbar) - } - - if len(result.Vbar) != len(expected.Vbar) { - t.Errorf("Vbar length should be %d, got %d", len(expected.Vbar), len(result.Vbar)) - } - - for i, v := range result.Vbar { - if v != expected.Vbar[i] { - t.Errorf( - "Vbar[%d] should be '%#v', got '%#v'", - i, expected.Vbar[i], v) - } - } -} diff --git a/vendor/github.com/modern-go/concurrent/.gitignore b/vendor/github.com/modern-go/concurrent/.gitignore new file mode 100644 index 0000000000..3f2bc47416 --- /dev/null +++ b/vendor/github.com/modern-go/concurrent/.gitignore @@ -0,0 +1 @@ +/coverage.txt diff --git a/vendor/github.com/modern-go/concurrent/.travis.yml b/vendor/github.com/modern-go/concurrent/.travis.yml new file mode 100644 index 0000000000..449e67cd01 --- /dev/null +++ b/vendor/github.com/modern-go/concurrent/.travis.yml @@ -0,0 +1,14 @@ +language: go + +go: + - 1.8.x + - 1.x + +before_install: + - go get -t -v ./... + +script: + - ./test.sh + +after_success: + - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/modern-go/concurrent/LICENSE b/vendor/github.com/modern-go/concurrent/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/vendor/github.com/modern-go/concurrent/LICENSE @@ -0,0 +1,201 @@ + 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/modern-go/concurrent/README.md b/vendor/github.com/modern-go/concurrent/README.md new file mode 100644 index 0000000000..acab3200aa --- /dev/null +++ b/vendor/github.com/modern-go/concurrent/README.md @@ -0,0 +1,49 @@ +# concurrent + +[![Sourcegraph](https://sourcegraph.com/github.com/modern-go/concurrent/-/badge.svg)](https://sourcegraph.com/github.com/modern-go/concurrent?badge) +[![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/modern-go/concurrent) +[![Build Status](https://travis-ci.org/modern-go/concurrent.svg?branch=master)](https://travis-ci.org/modern-go/concurrent) +[![codecov](https://codecov.io/gh/modern-go/concurrent/branch/master/graph/badge.svg)](https://codecov.io/gh/modern-go/concurrent) +[![rcard](https://goreportcard.com/badge/github.com/modern-go/concurrent)](https://goreportcard.com/report/github.com/modern-go/concurrent) +[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://raw.githubusercontent.com/modern-go/concurrent/master/LICENSE) + +* concurrent.Map: backport sync.Map for go below 1.9 +* concurrent.Executor: goroutine with explicit ownership and cancellable + +# concurrent.Map + +because sync.Map is only available in go 1.9, we can use concurrent.Map to make code portable + +```go +m := concurrent.NewMap() +m.Store("hello", "world") +elem, found := m.Load("hello") +// elem will be "world" +// found will be true +``` + +# concurrent.Executor + +```go +executor := concurrent.NewUnboundedExecutor() +executor.Go(func(ctx context.Context) { + everyMillisecond := time.NewTicker(time.Millisecond) + for { + select { + case <-ctx.Done(): + fmt.Println("goroutine exited") + return + case <-everyMillisecond.C: + // do something + } + } +}) +time.Sleep(time.Second) +executor.StopAndWaitForever() +fmt.Println("executor stopped") +``` + +attach goroutine to executor instance, so that we can + +* cancel it by stop the executor with Stop/StopAndWait/StopAndWaitForever +* handle panic by callback: the default behavior will no longer crash your application \ No newline at end of file diff --git a/vendor/github.com/modern-go/concurrent/executor.go b/vendor/github.com/modern-go/concurrent/executor.go new file mode 100644 index 0000000000..623dba1ac0 --- /dev/null +++ b/vendor/github.com/modern-go/concurrent/executor.go @@ -0,0 +1,14 @@ +package concurrent + +import "context" + +// Executor replace go keyword to start a new goroutine +// the goroutine should cancel itself if the context passed in has been cancelled +// the goroutine started by the executor, is owned by the executor +// we can cancel all executors owned by the executor just by stop the executor itself +// however Executor interface does not Stop method, the one starting and owning executor +// should use the concrete type of executor, instead of this interface. +type Executor interface { + // Go starts a new goroutine controlled by the context + Go(handler func(ctx context.Context)) +} diff --git a/vendor/github.com/modern-go/concurrent/go_above_19.go b/vendor/github.com/modern-go/concurrent/go_above_19.go new file mode 100644 index 0000000000..aeabf8c4f9 --- /dev/null +++ b/vendor/github.com/modern-go/concurrent/go_above_19.go @@ -0,0 +1,15 @@ +//+build go1.9 + +package concurrent + +import "sync" + +// Map is a wrapper for sync.Map introduced in go1.9 +type Map struct { + sync.Map +} + +// NewMap creates a thread safe Map +func NewMap() *Map { + return &Map{} +} diff --git a/vendor/github.com/modern-go/concurrent/go_below_19.go b/vendor/github.com/modern-go/concurrent/go_below_19.go new file mode 100644 index 0000000000..b9c8df7f41 --- /dev/null +++ b/vendor/github.com/modern-go/concurrent/go_below_19.go @@ -0,0 +1,33 @@ +//+build !go1.9 + +package concurrent + +import "sync" + +// Map implements a thread safe map for go version below 1.9 using mutex +type Map struct { + lock sync.RWMutex + data map[interface{}]interface{} +} + +// NewMap creates a thread safe map +func NewMap() *Map { + return &Map{ + data: make(map[interface{}]interface{}, 32), + } +} + +// Load is same as sync.Map Load +func (m *Map) Load(key interface{}) (elem interface{}, found bool) { + m.lock.RLock() + elem, found = m.data[key] + m.lock.RUnlock() + return +} + +// Load is same as sync.Map Store +func (m *Map) Store(key interface{}, elem interface{}) { + m.lock.Lock() + m.data[key] = elem + m.lock.Unlock() +} diff --git a/vendor/github.com/modern-go/concurrent/log.go b/vendor/github.com/modern-go/concurrent/log.go new file mode 100644 index 0000000000..9756fcc75a --- /dev/null +++ b/vendor/github.com/modern-go/concurrent/log.go @@ -0,0 +1,13 @@ +package concurrent + +import ( + "os" + "log" + "io/ioutil" +) + +// ErrorLogger is used to print out error, can be set to writer other than stderr +var ErrorLogger = log.New(os.Stderr, "", 0) + +// InfoLogger is used to print informational message, default to off +var InfoLogger = log.New(ioutil.Discard, "", 0) \ No newline at end of file diff --git a/vendor/github.com/modern-go/concurrent/test.sh b/vendor/github.com/modern-go/concurrent/test.sh new file mode 100755 index 0000000000..d1e6b2ec55 --- /dev/null +++ b/vendor/github.com/modern-go/concurrent/test.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash + +set -e +echo "" > coverage.txt + +for d in $(go list ./... | grep -v vendor); do + go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d + if [ -f profile.out ]; then + cat profile.out >> coverage.txt + rm profile.out + fi +done diff --git a/vendor/github.com/modern-go/concurrent/unbounded_executor.go b/vendor/github.com/modern-go/concurrent/unbounded_executor.go new file mode 100644 index 0000000000..05a77dceb1 --- /dev/null +++ b/vendor/github.com/modern-go/concurrent/unbounded_executor.go @@ -0,0 +1,119 @@ +package concurrent + +import ( + "context" + "fmt" + "runtime" + "runtime/debug" + "sync" + "time" + "reflect" +) + +// HandlePanic logs goroutine panic by default +var HandlePanic = func(recovered interface{}, funcName string) { + ErrorLogger.Println(fmt.Sprintf("%s panic: %v", funcName, recovered)) + ErrorLogger.Println(string(debug.Stack())) +} + +// UnboundedExecutor is a executor without limits on counts of alive goroutines +// it tracks the goroutine started by it, and can cancel them when shutdown +type UnboundedExecutor struct { + ctx context.Context + cancel context.CancelFunc + activeGoroutinesMutex *sync.Mutex + activeGoroutines map[string]int + HandlePanic func(recovered interface{}, funcName string) +} + +// GlobalUnboundedExecutor has the life cycle of the program itself +// any goroutine want to be shutdown before main exit can be started from this executor +// GlobalUnboundedExecutor expects the main function to call stop +// it does not magically knows the main function exits +var GlobalUnboundedExecutor = NewUnboundedExecutor() + +// NewUnboundedExecutor creates a new UnboundedExecutor, +// UnboundedExecutor can not be created by &UnboundedExecutor{} +// HandlePanic can be set with a callback to override global HandlePanic +func NewUnboundedExecutor() *UnboundedExecutor { + ctx, cancel := context.WithCancel(context.TODO()) + return &UnboundedExecutor{ + ctx: ctx, + cancel: cancel, + activeGoroutinesMutex: &sync.Mutex{}, + activeGoroutines: map[string]int{}, + } +} + +// Go starts a new goroutine and tracks its lifecycle. +// Panic will be recovered and logged automatically, except for StopSignal +func (executor *UnboundedExecutor) Go(handler func(ctx context.Context)) { + pc := reflect.ValueOf(handler).Pointer() + f := runtime.FuncForPC(pc) + funcName := f.Name() + file, line := f.FileLine(pc) + executor.activeGoroutinesMutex.Lock() + defer executor.activeGoroutinesMutex.Unlock() + startFrom := fmt.Sprintf("%s:%d", file, line) + executor.activeGoroutines[startFrom] += 1 + go func() { + defer func() { + recovered := recover() + // if you want to quit a goroutine without trigger HandlePanic + // use runtime.Goexit() to quit + if recovered != nil { + if executor.HandlePanic == nil { + HandlePanic(recovered, funcName) + } else { + executor.HandlePanic(recovered, funcName) + } + } + executor.activeGoroutinesMutex.Lock() + executor.activeGoroutines[startFrom] -= 1 + executor.activeGoroutinesMutex.Unlock() + }() + handler(executor.ctx) + }() +} + +// Stop cancel all goroutines started by this executor without wait +func (executor *UnboundedExecutor) Stop() { + executor.cancel() +} + +// StopAndWaitForever cancel all goroutines started by this executor and +// wait until all goroutines exited +func (executor *UnboundedExecutor) StopAndWaitForever() { + executor.StopAndWait(context.Background()) +} + +// StopAndWait cancel all goroutines started by this executor and wait. +// Wait can be cancelled by the context passed in. +func (executor *UnboundedExecutor) StopAndWait(ctx context.Context) { + executor.cancel() + for { + oneHundredMilliseconds := time.NewTimer(time.Millisecond * 100) + select { + case <-oneHundredMilliseconds.C: + if executor.checkNoActiveGoroutines() { + return + } + case <-ctx.Done(): + return + } + } +} + +func (executor *UnboundedExecutor) checkNoActiveGoroutines() bool { + executor.activeGoroutinesMutex.Lock() + defer executor.activeGoroutinesMutex.Unlock() + for startFrom, count := range executor.activeGoroutines { + if count > 0 { + InfoLogger.Println("UnboundedExecutor is still waiting goroutines to quit", + "startFrom", startFrom, + "count", count) + return false + } + } + return true +} diff --git a/vendor/github.com/modern-go/reflect2/.gitignore b/vendor/github.com/modern-go/reflect2/.gitignore new file mode 100644 index 0000000000..61ead86667 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/.gitignore @@ -0,0 +1 @@ +/vendor diff --git a/vendor/github.com/modern-go/reflect2/Gopkg.lock b/vendor/github.com/modern-go/reflect2/Gopkg.lock new file mode 100644 index 0000000000..2a3a69893b --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/Gopkg.lock @@ -0,0 +1,15 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + name = "github.com/modern-go/concurrent" + packages = ["."] + revision = "e0a39a4cb4216ea8db28e22a69f4ec25610d513a" + version = "1.0.0" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "daee8a88b3498b61c5640056665b8b9eea062006f5e596bbb6a3ed9119a11ec7" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/images/grpc-fortune-teller/Gopkg.toml b/vendor/github.com/modern-go/reflect2/Gopkg.toml similarity index 70% rename from images/grpc-fortune-teller/Gopkg.toml rename to vendor/github.com/modern-go/reflect2/Gopkg.toml index 24f0f1758c..3593fd0417 100644 --- a/images/grpc-fortune-teller/Gopkg.toml +++ b/vendor/github.com/modern-go/reflect2/Gopkg.toml @@ -1,6 +1,6 @@ # Gopkg.toml example # -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md +# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html # for detailed Gopkg.toml documentation. # # required = ["github.com/user/thing/cmd/thing"] @@ -24,6 +24,11 @@ # go-tests = true # unused-packages = true +ignored = ["github.com/modern-go/test","github.com/modern-go/test/must","github.com/modern-go/test/should"] + +[[constraint]] + name = "github.com/modern-go/concurrent" + version = "1.0.0" [prune] go-tests = true diff --git a/vendor/github.com/modern-go/reflect2/LICENSE b/vendor/github.com/modern-go/reflect2/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/LICENSE @@ -0,0 +1,201 @@ + 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/modern-go/reflect2/README.md b/vendor/github.com/modern-go/reflect2/README.md new file mode 100644 index 0000000000..6b429efdd5 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/README.md @@ -0,0 +1,2 @@ +# reflect2 +reflect api that avoids runtime reflect.Value cost diff --git a/vendor/github.com/modern-go/reflect2/go_above_17.go b/vendor/github.com/modern-go/reflect2/go_above_17.go new file mode 100644 index 0000000000..5c1cea8683 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/go_above_17.go @@ -0,0 +1,8 @@ +//+build go1.7 + +package reflect2 + +import "unsafe" + +//go:linkname resolveTypeOff reflect.resolveTypeOff +func resolveTypeOff(rtype unsafe.Pointer, off int32) unsafe.Pointer diff --git a/vendor/github.com/modern-go/reflect2/go_above_19.go b/vendor/github.com/modern-go/reflect2/go_above_19.go new file mode 100644 index 0000000000..c7e3b78011 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/go_above_19.go @@ -0,0 +1,14 @@ +//+build go1.9 + +package reflect2 + +import ( + "unsafe" +) + +//go:linkname makemap reflect.makemap +func makemap(rtype unsafe.Pointer, cap int) (m unsafe.Pointer) + +func makeMapWithSize(rtype unsafe.Pointer, cap int) unsafe.Pointer { + return makemap(rtype, cap) +} diff --git a/vendor/github.com/modern-go/reflect2/go_below_17.go b/vendor/github.com/modern-go/reflect2/go_below_17.go new file mode 100644 index 0000000000..81142317a9 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/go_below_17.go @@ -0,0 +1,9 @@ +//+build !go1.7 + +package reflect2 + +import "unsafe" + +func resolveTypeOff(rtype unsafe.Pointer, off int32) unsafe.Pointer { + return nil +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/go_below_19.go b/vendor/github.com/modern-go/reflect2/go_below_19.go new file mode 100644 index 0000000000..b050ef70cd --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/go_below_19.go @@ -0,0 +1,14 @@ +//+build !go1.9 + +package reflect2 + +import ( + "unsafe" +) + +//go:linkname makemap reflect.makemap +func makemap(rtype unsafe.Pointer) (m unsafe.Pointer) + +func makeMapWithSize(rtype unsafe.Pointer, cap int) unsafe.Pointer { + return makemap(rtype) +} diff --git a/vendor/github.com/modern-go/reflect2/reflect2.go b/vendor/github.com/modern-go/reflect2/reflect2.go new file mode 100644 index 0000000000..feabb610dc --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/reflect2.go @@ -0,0 +1,282 @@ +package reflect2 + +import ( + "reflect" + "unsafe" + "github.com/modern-go/concurrent" +) + +type Type interface { + Kind() reflect.Kind + // New return pointer to data of this type + New() interface{} + // UnsafeNew return the allocated space pointed by unsafe.Pointer + UnsafeNew() unsafe.Pointer + // PackEFace cast a unsafe pointer to object represented pointer + PackEFace(ptr unsafe.Pointer) interface{} + // Indirect dereference object represented pointer to this type + Indirect(obj interface{}) interface{} + // UnsafeIndirect dereference pointer to this type + UnsafeIndirect(ptr unsafe.Pointer) interface{} + // Type1 returns reflect.Type + Type1() reflect.Type + Implements(thatType Type) bool + String() string + RType() uintptr + // interface{} of this type has pointer like behavior + LikePtr() bool + IsNullable() bool + IsNil(obj interface{}) bool + UnsafeIsNil(ptr unsafe.Pointer) bool + Set(obj interface{}, val interface{}) + UnsafeSet(ptr unsafe.Pointer, val unsafe.Pointer) + AssignableTo(anotherType Type) bool +} + +type ListType interface { + Type + Elem() Type + SetIndex(obj interface{}, index int, elem interface{}) + UnsafeSetIndex(obj unsafe.Pointer, index int, elem unsafe.Pointer) + GetIndex(obj interface{}, index int) interface{} + UnsafeGetIndex(obj unsafe.Pointer, index int) unsafe.Pointer +} + +type ArrayType interface { + ListType + Len() int +} + +type SliceType interface { + ListType + MakeSlice(length int, cap int) interface{} + UnsafeMakeSlice(length int, cap int) unsafe.Pointer + Grow(obj interface{}, newLength int) + UnsafeGrow(ptr unsafe.Pointer, newLength int) + Append(obj interface{}, elem interface{}) + UnsafeAppend(obj unsafe.Pointer, elem unsafe.Pointer) + LengthOf(obj interface{}) int + UnsafeLengthOf(ptr unsafe.Pointer) int + SetNil(obj interface{}) + UnsafeSetNil(ptr unsafe.Pointer) + Cap(obj interface{}) int + UnsafeCap(ptr unsafe.Pointer) int +} + +type StructType interface { + Type + NumField() int + Field(i int) StructField + FieldByName(name string) StructField + FieldByIndex(index []int) StructField + FieldByNameFunc(match func(string) bool) StructField +} + +type StructField interface { + Offset() uintptr + Name() string + PkgPath() string + Type() Type + Tag() reflect.StructTag + Index() []int + Anonymous() bool + Set(obj interface{}, value interface{}) + UnsafeSet(obj unsafe.Pointer, value unsafe.Pointer) + Get(obj interface{}) interface{} + UnsafeGet(obj unsafe.Pointer) unsafe.Pointer +} + +type MapType interface { + Type + Key() Type + Elem() Type + MakeMap(cap int) interface{} + UnsafeMakeMap(cap int) unsafe.Pointer + SetIndex(obj interface{}, key interface{}, elem interface{}) + UnsafeSetIndex(obj unsafe.Pointer, key unsafe.Pointer, elem unsafe.Pointer) + TryGetIndex(obj interface{}, key interface{}) (interface{}, bool) + GetIndex(obj interface{}, key interface{}) interface{} + UnsafeGetIndex(obj unsafe.Pointer, key unsafe.Pointer) unsafe.Pointer + Iterate(obj interface{}) MapIterator + UnsafeIterate(obj unsafe.Pointer) MapIterator +} + +type MapIterator interface { + HasNext() bool + Next() (key interface{}, elem interface{}) + UnsafeNext() (key unsafe.Pointer, elem unsafe.Pointer) +} + +type PtrType interface { + Type + Elem() Type +} + +type InterfaceType interface { + NumMethod() int +} + +type Config struct { + UseSafeImplementation bool +} + +type API interface { + TypeOf(obj interface{}) Type + Type2(type1 reflect.Type) Type +} + +var ConfigUnsafe = Config{UseSafeImplementation: false}.Froze() +var ConfigSafe = Config{UseSafeImplementation: true}.Froze() + +type frozenConfig struct { + useSafeImplementation bool + cache *concurrent.Map +} + +func (cfg Config) Froze() *frozenConfig { + return &frozenConfig{ + useSafeImplementation: cfg.UseSafeImplementation, + cache: concurrent.NewMap(), + } +} + +func (cfg *frozenConfig) TypeOf(obj interface{}) Type { + cacheKey := uintptr(unpackEFace(obj).rtype) + typeObj, found := cfg.cache.Load(cacheKey) + if found { + return typeObj.(Type) + } + return cfg.Type2(reflect.TypeOf(obj)) +} + +func (cfg *frozenConfig) Type2(type1 reflect.Type) Type { + cacheKey := uintptr(unpackEFace(type1).data) + typeObj, found := cfg.cache.Load(cacheKey) + if found { + return typeObj.(Type) + } + type2 := cfg.wrapType(type1) + cfg.cache.Store(cacheKey, type2) + return type2 +} + +func (cfg *frozenConfig) wrapType(type1 reflect.Type) Type { + safeType := safeType{Type: type1, cfg: cfg} + switch type1.Kind() { + case reflect.Struct: + if cfg.useSafeImplementation { + return &safeStructType{safeType} + } + return newUnsafeStructType(cfg, type1) + case reflect.Array: + if cfg.useSafeImplementation { + return &safeSliceType{safeType} + } + return newUnsafeArrayType(cfg, type1) + case reflect.Slice: + if cfg.useSafeImplementation { + return &safeSliceType{safeType} + } + return newUnsafeSliceType(cfg, type1) + case reflect.Map: + if cfg.useSafeImplementation { + return &safeMapType{safeType} + } + return newUnsafeMapType(cfg, type1) + case reflect.Ptr, reflect.Chan, reflect.Func: + if cfg.useSafeImplementation { + return &safeMapType{safeType} + } + return newUnsafePtrType(cfg, type1) + case reflect.Interface: + if cfg.useSafeImplementation { + return &safeMapType{safeType} + } + if type1.NumMethod() == 0 { + return newUnsafeEFaceType(cfg, type1) + } + return newUnsafeIFaceType(cfg, type1) + default: + if cfg.useSafeImplementation { + return &safeType + } + return newUnsafeType(cfg, type1) + } +} + +func TypeOf(obj interface{}) Type { + return ConfigUnsafe.TypeOf(obj) +} + +func TypeOfPtr(obj interface{}) PtrType { + return TypeOf(obj).(PtrType) +} + +func Type2(type1 reflect.Type) Type { + return ConfigUnsafe.Type2(type1) +} + +func PtrTo(typ Type) Type { + return Type2(reflect.PtrTo(typ.Type1())) +} + +func PtrOf(obj interface{}) unsafe.Pointer { + return unpackEFace(obj).data +} + +func RTypeOf(obj interface{}) uintptr { + return uintptr(unpackEFace(obj).rtype) +} + +func IsNil(obj interface{}) bool { + if obj == nil { + return true + } + return unpackEFace(obj).data == nil +} + +func IsNullable(kind reflect.Kind) bool { + switch kind { + case reflect.Ptr, reflect.Map, reflect.Chan, reflect.Func, reflect.Slice, reflect.Interface: + return true + } + return false +} + +func likePtrKind(kind reflect.Kind) bool { + switch kind { + case reflect.Ptr, reflect.Map, reflect.Chan, reflect.Func: + return true + } + return false +} + +func likePtrType(typ reflect.Type) bool { + if likePtrKind(typ.Kind()) { + return true + } + if typ.Kind() == reflect.Struct { + if typ.NumField() != 1 { + return false + } + return likePtrType(typ.Field(0).Type) + } + if typ.Kind() == reflect.Array { + if typ.Len() != 1 { + return false + } + return likePtrType(typ.Elem()) + } + return false +} + +// NoEscape hides a pointer from escape analysis. noescape is +// the identity function but escape analysis doesn't think the +// output depends on the input. noescape is inlined and currently +// compiles down to zero instructions. +// USE CAREFULLY! +//go:nosplit +func NoEscape(p unsafe.Pointer) unsafe.Pointer { + x := uintptr(p) + return unsafe.Pointer(x ^ 0) +} \ No newline at end of file diff --git a/vendor/google.golang.org/grpc/.please-update b/vendor/github.com/modern-go/reflect2/reflect2_amd64.s similarity index 100% rename from vendor/google.golang.org/grpc/.please-update rename to vendor/github.com/modern-go/reflect2/reflect2_amd64.s diff --git a/vendor/github.com/modern-go/reflect2/reflect2_kind.go b/vendor/github.com/modern-go/reflect2/reflect2_kind.go new file mode 100644 index 0000000000..f13cbe13dd --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/reflect2_kind.go @@ -0,0 +1,30 @@ +package reflect2 + +import ( + "reflect" + "unsafe" +) + +// DefaultTypeOfKind return the non aliased default type for the kind +func DefaultTypeOfKind(kind reflect.Kind) Type { + return kindTypes[kind] +} + +var kindTypes = map[reflect.Kind]Type{ + reflect.Bool: TypeOf(true), + reflect.Uint8: TypeOf(uint8(0)), + reflect.Int8: TypeOf(int8(0)), + reflect.Uint16: TypeOf(uint16(0)), + reflect.Int16: TypeOf(int16(0)), + reflect.Uint32: TypeOf(uint32(0)), + reflect.Int32: TypeOf(int32(0)), + reflect.Uint64: TypeOf(uint64(0)), + reflect.Int64: TypeOf(int64(0)), + reflect.Uint: TypeOf(uint(0)), + reflect.Int: TypeOf(int(0)), + reflect.Float32: TypeOf(float32(0)), + reflect.Float64: TypeOf(float64(0)), + reflect.Uintptr: TypeOf(uintptr(0)), + reflect.String: TypeOf(""), + reflect.UnsafePointer: TypeOf(unsafe.Pointer(nil)), +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/relfect2_386.s b/vendor/github.com/modern-go/reflect2/relfect2_386.s new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/github.com/modern-go/reflect2/relfect2_amd64p32.s b/vendor/github.com/modern-go/reflect2/relfect2_amd64p32.s new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/github.com/modern-go/reflect2/relfect2_arm.s b/vendor/github.com/modern-go/reflect2/relfect2_arm.s new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/github.com/modern-go/reflect2/relfect2_arm64.s b/vendor/github.com/modern-go/reflect2/relfect2_arm64.s new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/github.com/modern-go/reflect2/relfect2_mips64x.s b/vendor/github.com/modern-go/reflect2/relfect2_mips64x.s new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/github.com/modern-go/reflect2/relfect2_mipsx.s b/vendor/github.com/modern-go/reflect2/relfect2_mipsx.s new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/github.com/modern-go/reflect2/relfect2_ppc64x.s b/vendor/github.com/modern-go/reflect2/relfect2_ppc64x.s new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/github.com/modern-go/reflect2/relfect2_s390x.s b/vendor/github.com/modern-go/reflect2/relfect2_s390x.s new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/github.com/modern-go/reflect2/safe_field.go b/vendor/github.com/modern-go/reflect2/safe_field.go new file mode 100644 index 0000000000..f68de456a3 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/safe_field.go @@ -0,0 +1,58 @@ +package reflect2 + +import ( + "reflect" + "unsafe" +) + +type safeField struct { + reflect.StructField +} + +func (field *safeField) Offset() uintptr { + return field.StructField.Offset +} + +func (field *safeField) Name() string { + return field.StructField.Name +} + +func (field *safeField) PkgPath() string { + return field.StructField.PkgPath +} + +func (field *safeField) Type() Type { + panic("not implemented") +} + +func (field *safeField) Tag() reflect.StructTag { + return field.StructField.Tag +} + +func (field *safeField) Index() []int { + return field.StructField.Index +} + +func (field *safeField) Anonymous() bool { + return field.StructField.Anonymous +} + +func (field *safeField) Set(obj interface{}, value interface{}) { + val := reflect.ValueOf(obj).Elem() + val.FieldByIndex(field.Index()).Set(reflect.ValueOf(value).Elem()) +} + +func (field *safeField) UnsafeSet(obj unsafe.Pointer, value unsafe.Pointer) { + panic("unsafe operation is not supported") +} + +func (field *safeField) Get(obj interface{}) interface{} { + val := reflect.ValueOf(obj).Elem().FieldByIndex(field.Index()) + ptr := reflect.New(val.Type()) + ptr.Elem().Set(val) + return ptr.Interface() +} + +func (field *safeField) UnsafeGet(obj unsafe.Pointer) unsafe.Pointer { + panic("does not support unsafe operation") +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/safe_map.go b/vendor/github.com/modern-go/reflect2/safe_map.go new file mode 100644 index 0000000000..6a1ba23d57 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/safe_map.go @@ -0,0 +1,101 @@ +package reflect2 + +import ( + "reflect" + "unsafe" +) + +type safeMapType struct { + safeType +} + +func (type2 *safeMapType) Key() Type { + return type2.safeType.cfg.Type2(type2.Type.Key()) +} + +func (type2 *safeMapType) MakeMap(cap int) interface{} { + ptr := reflect.New(type2.Type) + ptr.Elem().Set(reflect.MakeMap(type2.Type)) + return ptr.Interface() +} + +func (type2 *safeMapType) UnsafeMakeMap(cap int) unsafe.Pointer { + panic("does not support unsafe operation") +} + +func (type2 *safeMapType) SetIndex(obj interface{}, key interface{}, elem interface{}) { + keyVal := reflect.ValueOf(key) + elemVal := reflect.ValueOf(elem) + val := reflect.ValueOf(obj) + val.Elem().SetMapIndex(keyVal.Elem(), elemVal.Elem()) +} + +func (type2 *safeMapType) UnsafeSetIndex(obj unsafe.Pointer, key unsafe.Pointer, elem unsafe.Pointer) { + panic("does not support unsafe operation") +} + +func (type2 *safeMapType) TryGetIndex(obj interface{}, key interface{}) (interface{}, bool) { + keyVal := reflect.ValueOf(key) + if key == nil { + keyVal = reflect.New(type2.Type.Key()).Elem() + } + val := reflect.ValueOf(obj).MapIndex(keyVal) + if !val.IsValid() { + return nil, false + } + return val.Interface(), true +} + +func (type2 *safeMapType) GetIndex(obj interface{}, key interface{}) interface{} { + val := reflect.ValueOf(obj).Elem() + keyVal := reflect.ValueOf(key).Elem() + elemVal := val.MapIndex(keyVal) + if !elemVal.IsValid() { + ptr := reflect.New(reflect.PtrTo(val.Type().Elem())) + return ptr.Elem().Interface() + } + ptr := reflect.New(elemVal.Type()) + ptr.Elem().Set(elemVal) + return ptr.Interface() +} + +func (type2 *safeMapType) UnsafeGetIndex(obj unsafe.Pointer, key unsafe.Pointer) unsafe.Pointer { + panic("does not support unsafe operation") +} + +func (type2 *safeMapType) Iterate(obj interface{}) MapIterator { + m := reflect.ValueOf(obj).Elem() + return &safeMapIterator{ + m: m, + keys: m.MapKeys(), + } +} + +func (type2 *safeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { + panic("does not support unsafe operation") +} + +type safeMapIterator struct { + i int + m reflect.Value + keys []reflect.Value +} + +func (iter *safeMapIterator) HasNext() bool { + return iter.i != len(iter.keys) +} + +func (iter *safeMapIterator) Next() (interface{}, interface{}) { + key := iter.keys[iter.i] + elem := iter.m.MapIndex(key) + iter.i += 1 + keyPtr := reflect.New(key.Type()) + keyPtr.Elem().Set(key) + elemPtr := reflect.New(elem.Type()) + elemPtr.Elem().Set(elem) + return keyPtr.Interface(), elemPtr.Interface() +} + +func (iter *safeMapIterator) UnsafeNext() (unsafe.Pointer, unsafe.Pointer) { + panic("does not support unsafe operation") +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/safe_slice.go b/vendor/github.com/modern-go/reflect2/safe_slice.go new file mode 100644 index 0000000000..7e348c1aca --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/safe_slice.go @@ -0,0 +1,92 @@ +package reflect2 + +import ( + "reflect" + "unsafe" +) + +type safeSliceType struct { + safeType +} + +func (type2 *safeSliceType) SetIndex(obj interface{}, index int, value interface{}) { + val := reflect.ValueOf(obj).Elem() + elem := reflect.ValueOf(value).Elem() + val.Index(index).Set(elem) +} + +func (type2 *safeSliceType) UnsafeSetIndex(obj unsafe.Pointer, index int, value unsafe.Pointer) { + panic("does not support unsafe operation") +} + +func (type2 *safeSliceType) GetIndex(obj interface{}, index int) interface{} { + val := reflect.ValueOf(obj).Elem() + elem := val.Index(index) + ptr := reflect.New(elem.Type()) + ptr.Elem().Set(elem) + return ptr.Interface() +} + +func (type2 *safeSliceType) UnsafeGetIndex(obj unsafe.Pointer, index int) unsafe.Pointer { + panic("does not support unsafe operation") +} + +func (type2 *safeSliceType) MakeSlice(length int, cap int) interface{} { + val := reflect.MakeSlice(type2.Type, length, cap) + ptr := reflect.New(val.Type()) + ptr.Elem().Set(val) + return ptr.Interface() +} + +func (type2 *safeSliceType) UnsafeMakeSlice(length int, cap int) unsafe.Pointer { + panic("does not support unsafe operation") +} + +func (type2 *safeSliceType) Grow(obj interface{}, newLength int) { + oldCap := type2.Cap(obj) + oldSlice := reflect.ValueOf(obj).Elem() + delta := newLength - oldCap + deltaVals := make([]reflect.Value, delta) + newSlice := reflect.Append(oldSlice, deltaVals...) + oldSlice.Set(newSlice) +} + +func (type2 *safeSliceType) UnsafeGrow(ptr unsafe.Pointer, newLength int) { + panic("does not support unsafe operation") +} + +func (type2 *safeSliceType) Append(obj interface{}, elem interface{}) { + val := reflect.ValueOf(obj).Elem() + elemVal := reflect.ValueOf(elem).Elem() + newVal := reflect.Append(val, elemVal) + val.Set(newVal) +} + +func (type2 *safeSliceType) UnsafeAppend(obj unsafe.Pointer, elem unsafe.Pointer) { + panic("does not support unsafe operation") +} + +func (type2 *safeSliceType) SetNil(obj interface{}) { + val := reflect.ValueOf(obj).Elem() + val.Set(reflect.Zero(val.Type())) +} + +func (type2 *safeSliceType) UnsafeSetNil(ptr unsafe.Pointer) { + panic("does not support unsafe operation") +} + +func (type2 *safeSliceType) LengthOf(obj interface{}) int { + return reflect.ValueOf(obj).Elem().Len() +} + +func (type2 *safeSliceType) UnsafeLengthOf(ptr unsafe.Pointer) int { + panic("does not support unsafe operation") +} + +func (type2 *safeSliceType) Cap(obj interface{}) int { + return reflect.ValueOf(obj).Elem().Cap() +} + +func (type2 *safeSliceType) UnsafeCap(ptr unsafe.Pointer) int { + panic("does not support unsafe operation") +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/safe_struct.go b/vendor/github.com/modern-go/reflect2/safe_struct.go new file mode 100644 index 0000000000..d8eb453484 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/safe_struct.go @@ -0,0 +1,13 @@ +package reflect2 + +type safeStructType struct { + safeType +} + +func (type2 *safeStructType) FieldByName(name string) StructField { + field, found := type2.Type.FieldByName(name) + if !found { + panic("field " + name + " not found") + } + return &safeField{StructField: field} +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/safe_type.go b/vendor/github.com/modern-go/reflect2/safe_type.go new file mode 100644 index 0000000000..3cd6331ae2 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/safe_type.go @@ -0,0 +1,78 @@ +package reflect2 + +import ( + "reflect" + "unsafe" +) + +type safeType struct { + reflect.Type + cfg *frozenConfig +} + +func (type2 *safeType) New() interface{} { + return reflect.New(type2.Type).Interface() +} + +func (type2 *safeType) UnsafeNew() unsafe.Pointer { + panic("does not support unsafe operation") +} + +func (type2 *safeType) Elem() Type { + return type2.cfg.Type2(type2.Type.Elem()) +} + +func (type2 *safeType) Type1() reflect.Type { + return type2.Type +} + +func (type2 *safeType) PackEFace(ptr unsafe.Pointer) interface{} { + panic("does not support unsafe operation") +} + +func (type2 *safeType) Implements(thatType Type) bool { + return type2.Type.Implements(thatType.Type1()) +} + +func (type2 *safeType) RType() uintptr { + panic("does not support unsafe operation") +} + +func (type2 *safeType) Indirect(obj interface{}) interface{} { + return reflect.Indirect(reflect.ValueOf(obj)).Interface() +} + +func (type2 *safeType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { + panic("does not support unsafe operation") +} + +func (type2 *safeType) LikePtr() bool { + panic("does not support unsafe operation") +} + +func (type2 *safeType) IsNullable() bool { + return IsNullable(type2.Kind()) +} + +func (type2 *safeType) IsNil(obj interface{}) bool { + if obj == nil { + return true + } + return reflect.ValueOf(obj).Elem().IsNil() +} + +func (type2 *safeType) UnsafeIsNil(ptr unsafe.Pointer) bool { + panic("does not support unsafe operation") +} + +func (type2 *safeType) Set(obj interface{}, val interface{}) { + reflect.ValueOf(obj).Elem().Set(reflect.ValueOf(val).Elem()) +} + +func (type2 *safeType) UnsafeSet(ptr unsafe.Pointer, val unsafe.Pointer) { + panic("does not support unsafe operation") +} + +func (type2 *safeType) AssignableTo(anotherType Type) bool { + return type2.Type1().AssignableTo(anotherType.Type1()) +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/type_map.go b/vendor/github.com/modern-go/reflect2/type_map.go new file mode 100644 index 0000000000..122141f811 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/type_map.go @@ -0,0 +1,72 @@ +package reflect2 + +import ( + "unsafe" + "reflect" + "runtime" + "strings" +) + +// typelinks1 for 1.5 ~ 1.6 +//go:linkname typelinks1 reflect.typelinks +func typelinks1() [][]unsafe.Pointer + +// typelinks2 for 1.7 ~ +//go:linkname typelinks2 reflect.typelinks +func typelinks2() (sections []unsafe.Pointer, offset [][]int32) + +var types = map[string]reflect.Type{} + +func init() { + ver := runtime.Version() + if ver == "go1.5" || strings.HasPrefix(ver, "go1.5.") { + loadGo15Types() + } else if ver == "go1.6" || strings.HasPrefix(ver, "go1.6.") { + loadGo15Types() + } else { + loadGo17Types() + } +} + +func loadGo15Types() { + var obj interface{} = reflect.TypeOf(0) + typePtrss := typelinks1() + for _, typePtrs := range typePtrss { + for _, typePtr := range typePtrs { + (*emptyInterface)(unsafe.Pointer(&obj)).word = typePtr + typ := obj.(reflect.Type) + if typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct { + types[typ.Elem().String()] = typ.Elem() + } + if typ.Kind() == reflect.Slice && typ.Elem().Kind() == reflect.Ptr && + typ.Elem().Elem().Kind() == reflect.Struct { + types[typ.Elem().Elem().String()] = typ.Elem().Elem() + } + } + } +} + +func loadGo17Types() { + var obj interface{} = reflect.TypeOf(0) + sections, offset := typelinks2() + for i, offs := range offset { + rodata := sections[i] + for _, off := range offs { + (*emptyInterface)(unsafe.Pointer(&obj)).word = resolveTypeOff(unsafe.Pointer(rodata), off) + typ := obj.(reflect.Type) + if typ.Kind() == reflect.Ptr && typ.Elem().Kind() == reflect.Struct { + types[typ.Elem().String()] = typ.Elem() + } + } + } +} + +type emptyInterface struct { + typ unsafe.Pointer + word unsafe.Pointer +} + +// TypeByName return the type by its name, just like Class.forName in java +func TypeByName(typeName string) Type { + return Type2(types[typeName]) +} diff --git a/vendor/github.com/modern-go/reflect2/unsafe_array.go b/vendor/github.com/modern-go/reflect2/unsafe_array.go new file mode 100644 index 0000000000..924b0262b8 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/unsafe_array.go @@ -0,0 +1,65 @@ +package reflect2 + +import ( + "unsafe" + "reflect" +) + +type UnsafeArrayType struct { + unsafeType + elemRType unsafe.Pointer + pElemRType unsafe.Pointer + elemSize uintptr + likePtr bool +} + +func newUnsafeArrayType(cfg *frozenConfig, type1 reflect.Type) *UnsafeArrayType { + return &UnsafeArrayType{ + unsafeType: *newUnsafeType(cfg, type1), + elemRType: unpackEFace(type1.Elem()).data, + pElemRType: unpackEFace(reflect.PtrTo(type1.Elem())).data, + elemSize: type1.Elem().Size(), + likePtr: likePtrType(type1), + } +} + +func (type2 *UnsafeArrayType) LikePtr() bool { + return type2.likePtr +} + +func (type2 *UnsafeArrayType) Indirect(obj interface{}) interface{} { + objEFace := unpackEFace(obj) + assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIndirect(objEFace.data) +} + +func (type2 *UnsafeArrayType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { + if type2.likePtr { + return packEFace(type2.rtype, *(*unsafe.Pointer)(ptr)) + } + return packEFace(type2.rtype, ptr) +} + +func (type2 *UnsafeArrayType) SetIndex(obj interface{}, index int, elem interface{}) { + objEFace := unpackEFace(obj) + assertType("ArrayType.SetIndex argument 1", type2.ptrRType, objEFace.rtype) + elemEFace := unpackEFace(elem) + assertType("ArrayType.SetIndex argument 3", type2.pElemRType, elemEFace.rtype) + type2.UnsafeSetIndex(objEFace.data, index, elemEFace.data) +} + +func (type2 *UnsafeArrayType) UnsafeSetIndex(obj unsafe.Pointer, index int, elem unsafe.Pointer) { + elemPtr := arrayAt(obj, index, type2.elemSize, "i < s.Len") + typedmemmove(type2.elemRType, elemPtr, elem) +} + +func (type2 *UnsafeArrayType) GetIndex(obj interface{}, index int) interface{} { + objEFace := unpackEFace(obj) + assertType("ArrayType.GetIndex argument 1", type2.ptrRType, objEFace.rtype) + elemPtr := type2.UnsafeGetIndex(objEFace.data, index) + return packEFace(type2.pElemRType, elemPtr) +} + +func (type2 *UnsafeArrayType) UnsafeGetIndex(obj unsafe.Pointer, index int) unsafe.Pointer { + return arrayAt(obj, index, type2.elemSize, "i < s.Len") +} diff --git a/vendor/github.com/modern-go/reflect2/unsafe_eface.go b/vendor/github.com/modern-go/reflect2/unsafe_eface.go new file mode 100644 index 0000000000..446f4206cd --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/unsafe_eface.go @@ -0,0 +1,59 @@ +package reflect2 + +import ( + "unsafe" + "reflect" +) + +type eface struct { + rtype unsafe.Pointer + data unsafe.Pointer +} + +func unpackEFace(obj interface{}) *eface { + return (*eface)(unsafe.Pointer(&obj)) +} + +func packEFace(rtype unsafe.Pointer, data unsafe.Pointer) interface{} { + var i interface{} + e := (*eface)(unsafe.Pointer(&i)) + e.rtype = rtype + e.data = data + return i +} + +type UnsafeEFaceType struct { + unsafeType +} + +func newUnsafeEFaceType(cfg *frozenConfig, type1 reflect.Type) *UnsafeEFaceType { + return &UnsafeEFaceType{ + unsafeType: *newUnsafeType(cfg, type1), + } +} + +func (type2 *UnsafeEFaceType) IsNil(obj interface{}) bool { + if obj == nil { + return true + } + objEFace := unpackEFace(obj) + assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIsNil(objEFace.data) +} + +func (type2 *UnsafeEFaceType) UnsafeIsNil(ptr unsafe.Pointer) bool { + if ptr == nil { + return true + } + return unpackEFace(*(*interface{})(ptr)).data == nil +} + +func (type2 *UnsafeEFaceType) Indirect(obj interface{}) interface{} { + objEFace := unpackEFace(obj) + assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIndirect(objEFace.data) +} + +func (type2 *UnsafeEFaceType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { + return *(*interface{})(ptr) +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/unsafe_field.go b/vendor/github.com/modern-go/reflect2/unsafe_field.go new file mode 100644 index 0000000000..5eb53130a2 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/unsafe_field.go @@ -0,0 +1,74 @@ +package reflect2 + +import ( + "reflect" + "unsafe" +) + +type UnsafeStructField struct { + reflect.StructField + structType *UnsafeStructType + rtype unsafe.Pointer + ptrRType unsafe.Pointer +} + +func newUnsafeStructField(structType *UnsafeStructType, structField reflect.StructField) *UnsafeStructField { + return &UnsafeStructField{ + StructField: structField, + rtype: unpackEFace(structField.Type).data, + ptrRType: unpackEFace(reflect.PtrTo(structField.Type)).data, + structType: structType, + } +} + +func (field *UnsafeStructField) Offset() uintptr { + return field.StructField.Offset +} + +func (field *UnsafeStructField) Name() string { + return field.StructField.Name +} + +func (field *UnsafeStructField) PkgPath() string { + return field.StructField.PkgPath +} + +func (field *UnsafeStructField) Type() Type { + return field.structType.cfg.Type2(field.StructField.Type) +} + +func (field *UnsafeStructField) Tag() reflect.StructTag { + return field.StructField.Tag +} + +func (field *UnsafeStructField) Index() []int { + return field.StructField.Index +} + +func (field *UnsafeStructField) Anonymous() bool { + return field.StructField.Anonymous +} + +func (field *UnsafeStructField) Set(obj interface{}, value interface{}) { + objEFace := unpackEFace(obj) + assertType("StructField.SetIndex argument 1", field.structType.ptrRType, objEFace.rtype) + valueEFace := unpackEFace(value) + assertType("StructField.SetIndex argument 2", field.ptrRType, valueEFace.rtype) + field.UnsafeSet(objEFace.data, valueEFace.data) +} + +func (field *UnsafeStructField) UnsafeSet(obj unsafe.Pointer, value unsafe.Pointer) { + fieldPtr := add(obj, field.StructField.Offset, "same as non-reflect &v.field") + typedmemmove(field.rtype, fieldPtr, value) +} + +func (field *UnsafeStructField) Get(obj interface{}) interface{} { + objEFace := unpackEFace(obj) + assertType("StructField.GetIndex argument 1", field.structType.ptrRType, objEFace.rtype) + value := field.UnsafeGet(objEFace.data) + return packEFace(field.ptrRType, value) +} + +func (field *UnsafeStructField) UnsafeGet(obj unsafe.Pointer) unsafe.Pointer { + return add(obj, field.StructField.Offset, "same as non-reflect &v.field") +} diff --git a/vendor/github.com/modern-go/reflect2/unsafe_iface.go b/vendor/github.com/modern-go/reflect2/unsafe_iface.go new file mode 100644 index 0000000000..8f451ca367 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/unsafe_iface.go @@ -0,0 +1,64 @@ +package reflect2 + +import ( + "unsafe" + "reflect" +) + +type iface struct { + itab *itab + data unsafe.Pointer +} + +type itab struct { + ignore unsafe.Pointer + rtype unsafe.Pointer +} + +func IFaceToEFace(ptr unsafe.Pointer) interface{} { + iface := (*iface)(ptr) + if iface.itab == nil { + return nil + } + return packEFace(iface.itab.rtype, iface.data) +} + +type UnsafeIFaceType struct { + unsafeType +} + +func newUnsafeIFaceType(cfg *frozenConfig, type1 reflect.Type) *UnsafeIFaceType { + return &UnsafeIFaceType{ + unsafeType: *newUnsafeType(cfg, type1), + } +} + +func (type2 *UnsafeIFaceType) Indirect(obj interface{}) interface{} { + objEFace := unpackEFace(obj) + assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIndirect(objEFace.data) +} + +func (type2 *UnsafeIFaceType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { + return IFaceToEFace(ptr) +} + +func (type2 *UnsafeIFaceType) IsNil(obj interface{}) bool { + if obj == nil { + return true + } + objEFace := unpackEFace(obj) + assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIsNil(objEFace.data) +} + +func (type2 *UnsafeIFaceType) UnsafeIsNil(ptr unsafe.Pointer) bool { + if ptr == nil { + return true + } + iface := (*iface)(ptr) + if iface.itab == nil { + return true + } + return false +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/unsafe_link.go b/vendor/github.com/modern-go/reflect2/unsafe_link.go new file mode 100644 index 0000000000..a25a5f4d07 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/unsafe_link.go @@ -0,0 +1,70 @@ +package reflect2 + +import "unsafe" + +//go:linkname unsafe_New reflect.unsafe_New +func unsafe_New(rtype unsafe.Pointer) unsafe.Pointer + +//go:linkname typedmemmove reflect.typedmemmove +func typedmemmove(rtype unsafe.Pointer, dst, src unsafe.Pointer) + +//go:linkname unsafe_NewArray reflect.unsafe_NewArray +func unsafe_NewArray(rtype unsafe.Pointer, length int) unsafe.Pointer + +// typedslicecopy copies a slice of elemType values from src to dst, +// returning the number of elements copied. +//go:linkname typedslicecopy reflect.typedslicecopy +//go:noescape +func typedslicecopy(elemType unsafe.Pointer, dst, src sliceHeader) int + +//go:linkname mapassign reflect.mapassign +//go:noescape +func mapassign(rtype unsafe.Pointer, m unsafe.Pointer, key, val unsafe.Pointer) + +//go:linkname mapaccess reflect.mapaccess +//go:noescape +func mapaccess(rtype unsafe.Pointer, m unsafe.Pointer, key unsafe.Pointer) (val unsafe.Pointer) + +// m escapes into the return value, but the caller of mapiterinit +// doesn't let the return value escape. +//go:noescape +//go:linkname mapiterinit reflect.mapiterinit +func mapiterinit(rtype unsafe.Pointer, m unsafe.Pointer) *hiter + +//go:noescape +//go:linkname mapiternext reflect.mapiternext +func mapiternext(it *hiter) + +//go:linkname ifaceE2I reflect.ifaceE2I +func ifaceE2I(rtype unsafe.Pointer, src interface{}, dst unsafe.Pointer) + +// A hash iteration structure. +// If you modify hiter, also change cmd/internal/gc/reflect.go to indicate +// the layout of this structure. +type hiter struct { + key unsafe.Pointer // Must be in first position. Write nil to indicate iteration end (see cmd/internal/gc/range.go). + value unsafe.Pointer // Must be in second position (see cmd/internal/gc/range.go). + // rest fields are ignored +} + +// add returns p+x. +// +// The whySafe string is ignored, so that the function still inlines +// as efficiently as p+x, but all call sites should use the string to +// record why the addition is safe, which is to say why the addition +// does not cause x to advance to the very end of p's allocation +// and therefore point incorrectly at the next block in memory. +func add(p unsafe.Pointer, x uintptr, whySafe string) unsafe.Pointer { + return unsafe.Pointer(uintptr(p) + x) +} + +// arrayAt returns the i-th element of p, +// an array whose elements are eltSize bytes wide. +// The array pointed at by p must have at least i+1 elements: +// it is invalid (but impossible to check here) to pass i >= len, +// because then the result will point outside the array. +// whySafe must explain why i < len. (Passing "i < len" is fine; +// the benefit is to surface this assumption at the call site.) +func arrayAt(p unsafe.Pointer, i int, eltSize uintptr, whySafe string) unsafe.Pointer { + return add(p, uintptr(i)*eltSize, "i < len") +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/unsafe_map.go b/vendor/github.com/modern-go/reflect2/unsafe_map.go new file mode 100644 index 0000000000..f2e76e6bb1 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/unsafe_map.go @@ -0,0 +1,138 @@ +package reflect2 + +import ( + "reflect" + "unsafe" +) + +type UnsafeMapType struct { + unsafeType + pKeyRType unsafe.Pointer + pElemRType unsafe.Pointer +} + +func newUnsafeMapType(cfg *frozenConfig, type1 reflect.Type) MapType { + return &UnsafeMapType{ + unsafeType: *newUnsafeType(cfg, type1), + pKeyRType: unpackEFace(reflect.PtrTo(type1.Key())).data, + pElemRType: unpackEFace(reflect.PtrTo(type1.Elem())).data, + } +} + +func (type2 *UnsafeMapType) IsNil(obj interface{}) bool { + if obj == nil { + return true + } + objEFace := unpackEFace(obj) + assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIsNil(objEFace.data) +} + +func (type2 *UnsafeMapType) UnsafeIsNil(ptr unsafe.Pointer) bool { + if ptr == nil { + return true + } + return *(*unsafe.Pointer)(ptr) == nil +} + +func (type2 *UnsafeMapType) LikePtr() bool { + return true +} + +func (type2 *UnsafeMapType) Indirect(obj interface{}) interface{} { + objEFace := unpackEFace(obj) + assertType("MapType.Indirect argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIndirect(objEFace.data) +} + +func (type2 *UnsafeMapType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { + return packEFace(type2.rtype, *(*unsafe.Pointer)(ptr)) +} + +func (type2 *UnsafeMapType) Key() Type { + return type2.cfg.Type2(type2.Type.Key()) +} + +func (type2 *UnsafeMapType) MakeMap(cap int) interface{} { + return packEFace(type2.ptrRType, type2.UnsafeMakeMap(cap)) +} + +func (type2 *UnsafeMapType) UnsafeMakeMap(cap int) unsafe.Pointer { + m := makeMapWithSize(type2.rtype, cap) + return unsafe.Pointer(&m) +} + +func (type2 *UnsafeMapType) SetIndex(obj interface{}, key interface{}, elem interface{}) { + objEFace := unpackEFace(obj) + assertType("MapType.SetIndex argument 1", type2.ptrRType, objEFace.rtype) + keyEFace := unpackEFace(key) + assertType("MapType.SetIndex argument 2", type2.pKeyRType, keyEFace.rtype) + elemEFace := unpackEFace(elem) + assertType("MapType.SetIndex argument 3", type2.pElemRType, elemEFace.rtype) + type2.UnsafeSetIndex(objEFace.data, keyEFace.data, elemEFace.data) +} + +func (type2 *UnsafeMapType) UnsafeSetIndex(obj unsafe.Pointer, key unsafe.Pointer, elem unsafe.Pointer) { + mapassign(type2.rtype, *(*unsafe.Pointer)(obj), key, elem) +} + +func (type2 *UnsafeMapType) TryGetIndex(obj interface{}, key interface{}) (interface{}, bool) { + objEFace := unpackEFace(obj) + assertType("MapType.TryGetIndex argument 1", type2.ptrRType, objEFace.rtype) + keyEFace := unpackEFace(key) + assertType("MapType.TryGetIndex argument 2", type2.pKeyRType, keyEFace.rtype) + elemPtr := type2.UnsafeGetIndex(objEFace.data, keyEFace.data) + if elemPtr == nil { + return nil, false + } + return packEFace(type2.pElemRType, elemPtr), true +} + +func (type2 *UnsafeMapType) GetIndex(obj interface{}, key interface{}) interface{} { + objEFace := unpackEFace(obj) + assertType("MapType.GetIndex argument 1", type2.ptrRType, objEFace.rtype) + keyEFace := unpackEFace(key) + assertType("MapType.GetIndex argument 2", type2.pKeyRType, keyEFace.rtype) + elemPtr := type2.UnsafeGetIndex(objEFace.data, keyEFace.data) + return packEFace(type2.pElemRType, elemPtr) +} + +func (type2 *UnsafeMapType) UnsafeGetIndex(obj unsafe.Pointer, key unsafe.Pointer) unsafe.Pointer { + return mapaccess(type2.rtype, *(*unsafe.Pointer)(obj), key) +} + +func (type2 *UnsafeMapType) Iterate(obj interface{}) MapIterator { + objEFace := unpackEFace(obj) + assertType("MapType.Iterate argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIterate(objEFace.data) +} + +func (type2 *UnsafeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { + return &UnsafeMapIterator{ + hiter: mapiterinit(type2.rtype, *(*unsafe.Pointer)(obj)), + pKeyRType: type2.pKeyRType, + pElemRType: type2.pElemRType, + } +} + +type UnsafeMapIterator struct { + *hiter + pKeyRType unsafe.Pointer + pElemRType unsafe.Pointer +} + +func (iter *UnsafeMapIterator) HasNext() bool { + return iter.key != nil +} + +func (iter *UnsafeMapIterator) Next() (interface{}, interface{}) { + key, elem := iter.UnsafeNext() + return packEFace(iter.pKeyRType, key), packEFace(iter.pElemRType, elem) +} + +func (iter *UnsafeMapIterator) UnsafeNext() (unsafe.Pointer, unsafe.Pointer) { + key := iter.key + elem := iter.value + mapiternext(iter.hiter) + return key, elem +} diff --git a/vendor/github.com/modern-go/reflect2/unsafe_ptr.go b/vendor/github.com/modern-go/reflect2/unsafe_ptr.go new file mode 100644 index 0000000000..843724d8c6 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/unsafe_ptr.go @@ -0,0 +1,46 @@ +package reflect2 + +import ( + "unsafe" + "reflect" +) + +type UnsafePtrType struct { + unsafeType +} + +func newUnsafePtrType(cfg *frozenConfig, type1 reflect.Type) *UnsafePtrType { + return &UnsafePtrType{ + unsafeType: *newUnsafeType(cfg, type1), + } +} + +func (type2 *UnsafePtrType) IsNil(obj interface{}) bool { + if obj == nil { + return true + } + objEFace := unpackEFace(obj) + assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIsNil(objEFace.data) +} + +func (type2 *UnsafePtrType) UnsafeIsNil(ptr unsafe.Pointer) bool { + if ptr == nil { + return true + } + return *(*unsafe.Pointer)(ptr) == nil +} + +func (type2 *UnsafePtrType) LikePtr() bool { + return true +} + +func (type2 *UnsafePtrType) Indirect(obj interface{}) interface{} { + objEFace := unpackEFace(obj) + assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIndirect(objEFace.data) +} + +func (type2 *UnsafePtrType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { + return packEFace(type2.rtype, *(*unsafe.Pointer)(ptr)) +} diff --git a/vendor/github.com/modern-go/reflect2/unsafe_slice.go b/vendor/github.com/modern-go/reflect2/unsafe_slice.go new file mode 100644 index 0000000000..5ce85afbbe --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/unsafe_slice.go @@ -0,0 +1,177 @@ +package reflect2 + +import ( + "unsafe" + "reflect" +) + +// sliceHeader is a safe version of SliceHeader used within this package. +type sliceHeader struct { + Data unsafe.Pointer + Len int + Cap int +} + +type UnsafeSliceType struct { + unsafeType + elemRType unsafe.Pointer + pElemRType unsafe.Pointer + elemSize uintptr +} + +func newUnsafeSliceType(cfg *frozenConfig, type1 reflect.Type) SliceType { + elemType := type1.Elem() + return &UnsafeSliceType{ + unsafeType: *newUnsafeType(cfg, type1), + pElemRType: unpackEFace(reflect.PtrTo(elemType)).data, + elemRType: unpackEFace(elemType).data, + elemSize: elemType.Size(), + } +} + +func (type2 *UnsafeSliceType) Set(obj interface{}, val interface{}) { + objEFace := unpackEFace(obj) + assertType("Type.Set argument 1", type2.ptrRType, objEFace.rtype) + valEFace := unpackEFace(val) + assertType("Type.Set argument 2", type2.ptrRType, valEFace.rtype) + type2.UnsafeSet(objEFace.data, valEFace.data) +} + +func (type2 *UnsafeSliceType) UnsafeSet(ptr unsafe.Pointer, val unsafe.Pointer) { + *(*sliceHeader)(ptr) = *(*sliceHeader)(val) +} + +func (type2 *UnsafeSliceType) IsNil(obj interface{}) bool { + if obj == nil { + return true + } + objEFace := unpackEFace(obj) + assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIsNil(objEFace.data) +} + +func (type2 *UnsafeSliceType) UnsafeIsNil(ptr unsafe.Pointer) bool { + if ptr == nil { + return true + } + return (*sliceHeader)(ptr).Data == nil +} + +func (type2 *UnsafeSliceType) SetNil(obj interface{}) { + objEFace := unpackEFace(obj) + assertType("SliceType.SetNil argument 1", type2.ptrRType, objEFace.rtype) + type2.UnsafeSetNil(objEFace.data) +} + +func (type2 *UnsafeSliceType) UnsafeSetNil(ptr unsafe.Pointer) { + header := (*sliceHeader)(ptr) + header.Len = 0 + header.Cap = 0 + header.Data = nil +} + +func (type2 *UnsafeSliceType) MakeSlice(length int, cap int) interface{} { + return packEFace(type2.ptrRType, type2.UnsafeMakeSlice(length, cap)) +} + +func (type2 *UnsafeSliceType) UnsafeMakeSlice(length int, cap int) unsafe.Pointer { + header := &sliceHeader{unsafe_NewArray(type2.elemRType, cap), length, cap} + return unsafe.Pointer(header) +} + +func (type2 *UnsafeSliceType) LengthOf(obj interface{}) int { + objEFace := unpackEFace(obj) + assertType("SliceType.Len argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeLengthOf(objEFace.data) +} + +func (type2 *UnsafeSliceType) UnsafeLengthOf(obj unsafe.Pointer) int { + header := (*sliceHeader)(obj) + return header.Len +} + +func (type2 *UnsafeSliceType) SetIndex(obj interface{}, index int, elem interface{}) { + objEFace := unpackEFace(obj) + assertType("SliceType.SetIndex argument 1", type2.ptrRType, objEFace.rtype) + elemEFace := unpackEFace(elem) + assertType("SliceType.SetIndex argument 3", type2.pElemRType, elemEFace.rtype) + type2.UnsafeSetIndex(objEFace.data, index, elemEFace.data) +} + +func (type2 *UnsafeSliceType) UnsafeSetIndex(obj unsafe.Pointer, index int, elem unsafe.Pointer) { + header := (*sliceHeader)(obj) + elemPtr := arrayAt(header.Data, index, type2.elemSize, "i < s.Len") + typedmemmove(type2.elemRType, elemPtr, elem) +} + +func (type2 *UnsafeSliceType) GetIndex(obj interface{}, index int) interface{} { + objEFace := unpackEFace(obj) + assertType("SliceType.GetIndex argument 1", type2.ptrRType, objEFace.rtype) + elemPtr := type2.UnsafeGetIndex(objEFace.data, index) + return packEFace(type2.pElemRType, elemPtr) +} + +func (type2 *UnsafeSliceType) UnsafeGetIndex(obj unsafe.Pointer, index int) unsafe.Pointer { + header := (*sliceHeader)(obj) + return arrayAt(header.Data, index, type2.elemSize, "i < s.Len") +} + +func (type2 *UnsafeSliceType) Append(obj interface{}, elem interface{}) { + objEFace := unpackEFace(obj) + assertType("SliceType.Append argument 1", type2.ptrRType, objEFace.rtype) + elemEFace := unpackEFace(elem) + assertType("SliceType.Append argument 2", type2.pElemRType, elemEFace.rtype) + type2.UnsafeAppend(objEFace.data, elemEFace.data) +} + +func (type2 *UnsafeSliceType) UnsafeAppend(obj unsafe.Pointer, elem unsafe.Pointer) { + header := (*sliceHeader)(obj) + oldLen := header.Len + type2.UnsafeGrow(obj, oldLen+1) + type2.UnsafeSetIndex(obj, oldLen, elem) +} + +func (type2 *UnsafeSliceType) Cap(obj interface{}) int { + objEFace := unpackEFace(obj) + assertType("SliceType.Cap argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeCap(objEFace.data) +} + +func (type2 *UnsafeSliceType) UnsafeCap(ptr unsafe.Pointer) int { + return (*sliceHeader)(ptr).Cap +} + +func (type2 *UnsafeSliceType) Grow(obj interface{}, newLength int) { + objEFace := unpackEFace(obj) + assertType("SliceType.Grow argument 1", type2.ptrRType, objEFace.rtype) + type2.UnsafeGrow(objEFace.data, newLength) +} + +func (type2 *UnsafeSliceType) UnsafeGrow(obj unsafe.Pointer, newLength int) { + header := (*sliceHeader)(obj) + if newLength <= header.Cap { + header.Len = newLength + return + } + newCap := calcNewCap(header.Cap, newLength) + newHeader := (*sliceHeader)(type2.UnsafeMakeSlice(header.Len, newCap)) + typedslicecopy(type2.elemRType, *newHeader, *header) + header.Data = newHeader.Data + header.Cap = newHeader.Cap + header.Len = newLength +} + +func calcNewCap(cap int, expectedCap int) int { + if cap == 0 { + cap = expectedCap + } else { + for cap < expectedCap { + if cap < 1024 { + cap += cap + } else { + cap += cap / 4 + } + } + } + return cap +} diff --git a/vendor/github.com/modern-go/reflect2/unsafe_struct.go b/vendor/github.com/modern-go/reflect2/unsafe_struct.go new file mode 100644 index 0000000000..f91ef17927 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/unsafe_struct.go @@ -0,0 +1,59 @@ +package reflect2 + +import ( + "reflect" + "unsafe" +) + +type UnsafeStructType struct { + unsafeType + likePtr bool +} + +func newUnsafeStructType(cfg *frozenConfig, type1 reflect.Type) *UnsafeStructType { + return &UnsafeStructType{ + unsafeType: *newUnsafeType(cfg, type1), + likePtr: likePtrType(type1), + } +} + +func (type2 *UnsafeStructType) LikePtr() bool { + return type2.likePtr +} + +func (type2 *UnsafeStructType) Indirect(obj interface{}) interface{} { + objEFace := unpackEFace(obj) + assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIndirect(objEFace.data) +} + +func (type2 *UnsafeStructType) UnsafeIndirect(ptr unsafe.Pointer) interface{} { + if type2.likePtr { + return packEFace(type2.rtype, *(*unsafe.Pointer)(ptr)) + } + return packEFace(type2.rtype, ptr) +} + +func (type2 *UnsafeStructType) FieldByName(name string) StructField { + structField, found := type2.Type.FieldByName(name) + if !found { + return nil + } + return newUnsafeStructField(type2, structField) +} + +func (type2 *UnsafeStructType) Field(i int) StructField { + return newUnsafeStructField(type2, type2.Type.Field(i)) +} + +func (type2 *UnsafeStructType) FieldByIndex(index []int) StructField { + return newUnsafeStructField(type2, type2.Type.FieldByIndex(index)) +} + +func (type2 *UnsafeStructType) FieldByNameFunc(match func(string) bool) StructField { + structField, found := type2.Type.FieldByNameFunc(match) + if !found { + panic("field match condition not found in " + type2.Type.String()) + } + return newUnsafeStructField(type2, structField) +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/unsafe_type.go b/vendor/github.com/modern-go/reflect2/unsafe_type.go new file mode 100644 index 0000000000..e7ad4a6552 --- /dev/null +++ b/vendor/github.com/modern-go/reflect2/unsafe_type.go @@ -0,0 +1,85 @@ +package reflect2 + +import ( + "unsafe" + "reflect" +) + +type unsafeType struct { + safeType + rtype unsafe.Pointer + ptrRType unsafe.Pointer +} + +func newUnsafeType(cfg *frozenConfig, type1 reflect.Type) *unsafeType { + return &unsafeType{ + safeType: safeType{ + Type: type1, + cfg: cfg, + }, + rtype: unpackEFace(type1).data, + ptrRType: unpackEFace(reflect.PtrTo(type1)).data, + } +} + +func (type2 *unsafeType) Set(obj interface{}, val interface{}) { + objEFace := unpackEFace(obj) + assertType("Type.Set argument 1", type2.ptrRType, objEFace.rtype) + valEFace := unpackEFace(val) + assertType("Type.Set argument 2", type2.ptrRType, valEFace.rtype) + type2.UnsafeSet(objEFace.data, valEFace.data) +} + +func (type2 *unsafeType) UnsafeSet(ptr unsafe.Pointer, val unsafe.Pointer) { + typedmemmove(type2.rtype, ptr, val) +} + +func (type2 *unsafeType) IsNil(obj interface{}) bool { + objEFace := unpackEFace(obj) + assertType("Type.IsNil argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIsNil(objEFace.data) +} + +func (type2 *unsafeType) UnsafeIsNil(ptr unsafe.Pointer) bool { + return ptr == nil +} + +func (type2 *unsafeType) UnsafeNew() unsafe.Pointer { + return unsafe_New(type2.rtype) +} + +func (type2 *unsafeType) New() interface{} { + return packEFace(type2.ptrRType, type2.UnsafeNew()) +} + +func (type2 *unsafeType) PackEFace(ptr unsafe.Pointer) interface{} { + return packEFace(type2.ptrRType, ptr) +} + +func (type2 *unsafeType) RType() uintptr { + return uintptr(type2.rtype) +} + +func (type2 *unsafeType) Indirect(obj interface{}) interface{} { + objEFace := unpackEFace(obj) + assertType("Type.Indirect argument 1", type2.ptrRType, objEFace.rtype) + return type2.UnsafeIndirect(objEFace.data) +} + +func (type2 *unsafeType) UnsafeIndirect(obj unsafe.Pointer) interface{} { + return packEFace(type2.rtype, obj) +} + +func (type2 *unsafeType) LikePtr() bool { + return false +} + +func assertType(where string, expectRType unsafe.Pointer, actualRType unsafe.Pointer) { + if expectRType != actualRType { + expectType := reflect.TypeOf(0) + (*iface)(unsafe.Pointer(&expectType)).data = expectRType + actualType := reflect.TypeOf(0) + (*iface)(unsafe.Pointer(&actualType)).data = actualRType + panic(where + ": expect " + expectType.String() + ", actual " + actualType.String()) + } +} diff --git a/vendor/github.com/moul/http2curl/http2curl_test.go b/vendor/github.com/moul/http2curl/http2curl_test.go deleted file mode 100644 index 0cd28169c2..0000000000 --- a/vendor/github.com/moul/http2curl/http2curl_test.go +++ /dev/null @@ -1,101 +0,0 @@ -package http2curl - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "testing" - - . "github.com/smartystreets/goconvey/convey" -) - -func ExampleGetCurlCommand() { - form := url.Values{} - form.Add("age", "10") - form.Add("name", "Hudson") - body := form.Encode() - - req, _ := http.NewRequest(http.MethodPost, "http://foo.com/cats", ioutil.NopCloser(bytes.NewBufferString(body))) - req.Header.Set("API_KEY", "123") - - command, _ := GetCurlCommand(req) - fmt.Println(command) - - // Output: - // curl -X 'POST' -d 'age=10&name=Hudson' -H 'Api_key: 123' 'http://foo.com/cats' -} - -func ExampleGetCurlCommand_json() { - req, _ := http.NewRequest("PUT", "http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu", bytes.NewBufferString(`{"hello":"world","answer":42}`)) - req.Header.Set("Content-Type", "application/json") - - command, _ := GetCurlCommand(req) - fmt.Println(command) - - // Output: - // curl -X 'PUT' -d '{"hello":"world","answer":42}' -H 'Content-Type: application/json' 'http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu' -} - -func ExampleGetCurlCommand_noBody() { - req, _ := http.NewRequest("PUT", "http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu", nil) - req.Header.Set("Content-Type", "application/json") - - command, _ := GetCurlCommand(req) - fmt.Println(command) - - // Output: - // curl -X 'PUT' -H 'Content-Type: application/json' 'http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu' -} - -func ExampleGetCurlCommand_emptyStringBody() { - req, _ := http.NewRequest("PUT", "http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu", bytes.NewBufferString("")) - req.Header.Set("Content-Type", "application/json") - - command, _ := GetCurlCommand(req) - fmt.Println(command) - - // Output: - // curl -X 'PUT' -d '' -H 'Content-Type: application/json' 'http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu' -} - -func ExampleGetCurlCommand_newlineInBody() { - req, _ := http.NewRequest("POST", "http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu", bytes.NewBufferString("hello\nworld")) - req.Header.Set("Content-Type", "application/json") - - command, _ := GetCurlCommand(req) - fmt.Println(command) - - // Output: - // curl -X 'POST' -d 'hello - // world' -H 'Content-Type: application/json' 'http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu' -} - -func ExampleGetCurlCommand_specialCharsInBody() { - req, _ := http.NewRequest("POST", "http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu", bytes.NewBufferString(`Hello $123 o'neill -"-`)) - req.Header.Set("Content-Type", "application/json") - - command, _ := GetCurlCommand(req) - fmt.Println(command) - - // Output: - // curl -X 'POST' -d 'Hello $123 o'\''neill -"-' -H 'Content-Type: application/json' 'http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu' -} - -func TestGetCurlCommand(t *testing.T) { - Convey("Testing http2curl", t, func() { - uri := "http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu" - payload := new(bytes.Buffer) - payload.Write([]byte(`{"hello":"world","answer":42}`)) - req, err := http.NewRequest("PUT", uri, payload) - So(err, ShouldBeNil) - req.Header.Set("X-Auth-Token", "private-token") - req.Header.Set("Content-Type", "application/json") - - command, err := GetCurlCommand(req) - So(err, ShouldBeNil) - expected := `curl -X 'PUT' -d '{"hello":"world","answer":42}' -H 'Content-Type: application/json' -H 'X-Auth-Token: private-token' 'http://www.example.com/abc/def.ghi?jlk=mno&pqr=stu'` - So(command.String(), ShouldEqual, expected) - }) -} diff --git a/vendor/github.com/ncabatoff/process-exporter/proc/base_test.go b/vendor/github.com/ncabatoff/process-exporter/proc/base_test.go deleted file mode 100644 index 6c902b7f2b..0000000000 --- a/vendor/github.com/ncabatoff/process-exporter/proc/base_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package proc - -import ( - . "gopkg.in/check.v1" - "testing" -) - -// Hook up gocheck into the "go test" runner. -func Test(t *testing.T) { TestingT(t) } - -type MySuite struct{} - -var _ = Suite(&MySuite{}) - -// read everything in the iterator -func consumeIter(pi ProcIter) ([]ProcIdInfo, error) { - infos := []ProcIdInfo{} - for pi.Next() { - info, err := Info(pi) - if err != nil { - return nil, err - } - infos = append(infos, info) - } - return infos, nil -} diff --git a/vendor/github.com/ncabatoff/process-exporter/proc/grouper_test.go b/vendor/github.com/ncabatoff/process-exporter/proc/grouper_test.go deleted file mode 100644 index f629cc310a..0000000000 --- a/vendor/github.com/ncabatoff/process-exporter/proc/grouper_test.go +++ /dev/null @@ -1,268 +0,0 @@ -package proc - -import ( - "github.com/kylelemons/godebug/pretty" - common "github.com/ncabatoff/process-exporter" - . "gopkg.in/check.v1" - "time" -) - -type namer map[string]struct{} - -func newNamer(names ...string) namer { - nr := make(namer, len(names)) - for _, name := range names { - nr[name] = struct{}{} - } - return nr -} - -func (n namer) MatchAndName(nacl common.NameAndCmdline) (bool, string) { - if _, ok := n[nacl.Name]; ok { - return true, nacl.Name - } - return false, "" -} - -// Test core group() functionality, i.e things not related to namers or parents -// or processes that have exited. -func (s MySuite) TestGrouperBasic(c *C) { - newProc := func(pid int, name string, m ProcMetrics) ProcIdInfo { - pis := newProcIdStatic(pid, 0, 0, name, nil) - return ProcIdInfo{ - ProcId: pis.ProcId, - ProcStatic: pis.ProcStatic, - ProcMetrics: m, - } - } - gr := NewGrouper(false, newNamer("g1", "g2")) - p1 := newProc(1, "g1", ProcMetrics{1, 2, 3, 4, 5, 4, 400}) - p2 := newProc(2, "g2", ProcMetrics{2, 3, 4, 5, 6, 40, 400}) - p3 := newProc(3, "g3", ProcMetrics{}) - - _, err := gr.Update(procInfoIter(p1, p2, p3)) - c.Assert(err, IsNil) - - got1 := gr.groups() - want1 := GroupCountMap{ - "g1": GroupCounts{Counts{0, 0, 0}, 1, 4, 5, time.Time{}, 4, 0.01}, - "g2": GroupCounts{Counts{0, 0, 0}, 1, 5, 6, time.Time{}, 40, 0.1}, - } - c.Check(got1, DeepEquals, want1, Commentf("diff %s", pretty.Compare(got1, want1))) - - // Now increment counts and memory and make sure group counts updated. - p1.ProcMetrics = ProcMetrics{2, 3, 4, 5, 6, 4, 400} - p2.ProcMetrics = ProcMetrics{4, 5, 6, 7, 8, 40, 400} - - _, err = gr.Update(procInfoIter(p1, p2, p3)) - c.Assert(err, IsNil) - - got2 := gr.groups() - want2 := GroupCountMap{ - "g1": GroupCounts{Counts{1, 1, 1}, 1, 5, 6, time.Time{}, 4, 0.01}, - "g2": GroupCounts{Counts{2, 2, 2}, 1, 7, 8, time.Time{}, 40, 0.1}, - } - c.Check(got2, DeepEquals, want2, Commentf("diff %s", pretty.Compare(got2, want2))) - - // Now add a new proc and update p2's metrics. The - // counts for p4 won't be factored into the total yet - // because we only add to counts starting with the - // second time we see a proc. Memory and FDs are affected - // though. - p4 := newProc(4, "g2", ProcMetrics{1, 1, 1, 1, 1, 80, 400}) - p2.ProcMetrics = ProcMetrics{5, 6, 7, 8, 9, 40, 400} - - _, err = gr.Update(procInfoIter(p1, p2, p3, p4)) - c.Assert(err, IsNil) - - got3 := gr.groups() - want3 := GroupCountMap{ - "g1": GroupCounts{Counts{0, 0, 0}, 1, 5, 6, time.Time{}, 4, 0.01}, - "g2": GroupCounts{Counts{1, 1, 1}, 2, 9, 10, time.Time{}, 120, 0.2}, - } - c.Check(got3, DeepEquals, want3, Commentf("diff %s", pretty.Compare(got3, want3))) - - p4.ProcMetrics = ProcMetrics{2, 2, 2, 2, 2, 100, 400} - p2.ProcMetrics = ProcMetrics{6, 7, 8, 8, 9, 40, 400} - - _, err = gr.Update(procInfoIter(p1, p2, p3, p4)) - c.Assert(err, IsNil) - - got4 := gr.groups() - want4 := GroupCountMap{ - "g1": GroupCounts{Counts{0, 0, 0}, 1, 5, 6, time.Time{}, 4, 0.01}, - "g2": GroupCounts{Counts{2, 2, 2}, 2, 10, 11, time.Time{}, 140, 0.25}, - } - c.Check(got4, DeepEquals, want4, Commentf("diff %s", pretty.Compare(got4, want4))) - -} - -// Test that if a proc is tracked, we track its descendants, and if not as -// before it gets ignored. We won't bother testing metric accumulation since -// that should be covered by TestGrouperBasic. -func (s MySuite) TestGrouperParents(c *C) { - newProc := func(pid, ppid int, name string) ProcIdInfo { - pis := newProcIdStatic(pid, ppid, 0, name, nil) - return ProcIdInfo{ - ProcId: pis.ProcId, - ProcStatic: pis.ProcStatic, - ProcMetrics: ProcMetrics{}, - } - } - gr := NewGrouper(true, newNamer("g1", "g2")) - p1 := newProc(1, 0, "g1") - p2 := newProc(2, 0, "g2") - p3 := newProc(3, 0, "g3") - - _, err := gr.Update(procInfoIter(p1, p2, p3)) - c.Assert(err, IsNil) - - got1 := gr.groups() - want1 := GroupCountMap{ - "g1": GroupCounts{Counts{}, 1, 0, 0, time.Time{}, 0, 0}, - "g2": GroupCounts{Counts{}, 1, 0, 0, time.Time{}, 0, 0}, - } - c.Check(got1, DeepEquals, want1, Commentf("diff %s", pretty.Compare(got1, want1))) - - // Now we'll give each of the procs a child and test that the count of procs - // in each group is incremented. - - p4 := newProc(4, p1.Pid, "") - p5 := newProc(5, p2.Pid, "") - p6 := newProc(6, p3.Pid, "") - - _, err = gr.Update(procInfoIter(p1, p2, p3, p4, p5, p6)) - c.Assert(err, IsNil) - - got2 := gr.groups() - want2 := GroupCountMap{ - "g1": GroupCounts{Counts{}, 2, 0, 0, time.Time{}, 0, 0}, - "g2": GroupCounts{Counts{}, 2, 0, 0, time.Time{}, 0, 0}, - } - c.Check(got2, DeepEquals, want2, Commentf("diff %s", pretty.Compare(got2, want2))) - - // Now we'll let p4 die, and give p5 a child and grandchild and great-grandchild. - - p7 := newProc(7, p5.Pid, "") - p8 := newProc(8, p7.Pid, "") - p9 := newProc(9, p8.Pid, "") - - _, err = gr.Update(procInfoIter(p1, p2, p3, p5, p6, p7, p8, p9)) - c.Assert(err, IsNil) - - got3 := gr.groups() - want3 := GroupCountMap{ - "g1": GroupCounts{Counts{}, 1, 0, 0, time.Time{}, 0, 0}, - "g2": GroupCounts{Counts{}, 5, 0, 0, time.Time{}, 0, 0}, - } - c.Check(got3, DeepEquals, want3, Commentf("diff %s", pretty.Compare(got3, want3))) -} - -// Test that Groups() reports on new CPU/IO activity, even if some processes in the -// group have gone away. -func (s MySuite) TestGrouperGroup(c *C) { - newProc := func(pid int, name string, m ProcMetrics) ProcIdInfo { - pis := newProcIdStatic(pid, 0, 0, name, nil) - return ProcIdInfo{ - ProcId: pis.ProcId, - ProcStatic: pis.ProcStatic, - ProcMetrics: m, - } - } - gr := NewGrouper(false, newNamer("g1")) - - // First call should return zero CPU/IO. - p1 := newProc(1, "g1", ProcMetrics{1, 2, 3, 4, 5, 8, 400}) - _, err := gr.Update(procInfoIter(p1)) - c.Assert(err, IsNil) - got1 := gr.Groups() - want1 := GroupCountMap{ - "g1": GroupCounts{Counts{0, 0, 0}, 1, 4, 5, time.Time{}, 8, 0.02}, - } - c.Check(got1, DeepEquals, want1) - - // Second call should return the delta CPU/IO from first observance, - // as well as latest memory/proccount. - p1.ProcMetrics = ProcMetrics{2, 3, 4, 5, 6, 12, 400} - _, err = gr.Update(procInfoIter(p1)) - c.Assert(err, IsNil) - got2 := gr.Groups() - want2 := GroupCountMap{ - "g1": GroupCounts{Counts{1, 1, 1}, 1, 5, 6, time.Time{}, 12, 0.03}, - } - c.Check(got2, DeepEquals, want2) - - // Third call: process hasn't changed, nor should our group stats. - _, err = gr.Update(procInfoIter(p1)) - c.Assert(err, IsNil) - got3 := gr.Groups() - want3 := GroupCountMap{ - "g1": GroupCounts{Counts{1, 1, 1}, 1, 5, 6, time.Time{}, 12, 0.03}, - } - c.Check(got3, DeepEquals, want3, Commentf("diff %s", pretty.Compare(got3, want3))) -} - -// Test that Groups() reports on new CPU/IO activity, even if some processes in the -// group have gone away. -func (s MySuite) TestGrouperNonDecreasing(c *C) { - newProc := func(pid int, name string, m ProcMetrics) ProcIdInfo { - pis := newProcIdStatic(pid, 0, 0, name, nil) - return ProcIdInfo{ - ProcId: pis.ProcId, - ProcStatic: pis.ProcStatic, - ProcMetrics: m, - } - } - gr := NewGrouper(false, newNamer("g1", "g2")) - p1 := newProc(1, "g1", ProcMetrics{1, 2, 3, 4, 5, 4, 400}) - p2 := newProc(2, "g2", ProcMetrics{2, 3, 4, 5, 6, 40, 400}) - - _, err := gr.Update(procInfoIter(p1, p2)) - c.Assert(err, IsNil) - - got1 := gr.Groups() - want1 := GroupCountMap{ - "g1": GroupCounts{Counts{0, 0, 0}, 1, 4, 5, time.Time{}, 4, 0.01}, - "g2": GroupCounts{Counts{0, 0, 0}, 1, 5, 6, time.Time{}, 40, 0.1}, - } - c.Check(got1, DeepEquals, want1, Commentf("diff %s", pretty.Compare(got1, want1))) - - // Now add a new proc p3 to g2, and increment p1/p2's metrics. - p1.ProcMetrics = ProcMetrics{2, 3, 4, 5, 6, 8, 400} - p2.ProcMetrics = ProcMetrics{4, 5, 6, 7, 8, 80, 400} - p3 := newProc(3, "g2", ProcMetrics{1, 1, 1, 1, 1, 8, 400}) - _, err = gr.Update(procInfoIter(p1, p2, p3)) - c.Assert(err, IsNil) - - got2 := gr.Groups() - want2 := GroupCountMap{ - "g1": GroupCounts{Counts{1, 1, 1}, 1, 5, 6, time.Time{}, 8, 0.02}, - "g2": GroupCounts{Counts{2, 2, 2}, 2, 8, 9, time.Time{}, 88, 0.2}, - } - c.Check(got2, DeepEquals, want2, Commentf("diff %s", pretty.Compare(got2, want2))) - - // Now update p3's metrics and kill p2. - p3.ProcMetrics = ProcMetrics{2, 3, 4, 5, 6, 8, 400} - _, err = gr.Update(procInfoIter(p1, p3)) - c.Assert(err, IsNil) - - got3 := gr.Groups() - want3 := GroupCountMap{ - "g1": GroupCounts{Counts{1, 1, 1}, 1, 5, 6, time.Time{}, 8, 0.02}, - "g2": GroupCounts{Counts{3, 4, 5}, 1, 5, 6, time.Time{}, 8, 0.02}, - } - c.Check(got3, DeepEquals, want3, Commentf("diff %s", pretty.Compare(got3, want3))) - - // Now update p3's metrics and kill p1. - p3.ProcMetrics = ProcMetrics{4, 4, 4, 2, 1, 4, 400} - _, err = gr.Update(procInfoIter(p3)) - c.Assert(err, IsNil) - - got4 := gr.Groups() - want4 := GroupCountMap{ - "g1": GroupCounts{Counts{1, 1, 1}, 0, 0, 0, time.Time{}, 0, 0}, - "g2": GroupCounts{Counts{5, 5, 5}, 1, 2, 1, time.Time{}, 4, 0.01}, - } - c.Check(got4, DeepEquals, want4, Commentf("diff %s\n%s", pretty.Compare(got4, want4), pretty.Sprint(gr))) - -} diff --git a/vendor/github.com/ncabatoff/process-exporter/proc/read_test.go b/vendor/github.com/ncabatoff/process-exporter/proc/read_test.go deleted file mode 100644 index 0d48e1bc95..0000000000 --- a/vendor/github.com/ncabatoff/process-exporter/proc/read_test.go +++ /dev/null @@ -1,120 +0,0 @@ -package proc - -import ( - . "gopkg.in/check.v1" - "os" - "os/exec" -) - -var fs *FS - -func init() { - fs, _ = NewFS("/proc") -} - -// Basic test of proc reading: does AllProcs return at least two procs, one of which is us. -func (s MySuite) TestAllProcs(c *C) { - procs := fs.AllProcs() - count := 0 - for procs.Next() { - count++ - if procs.GetPid() != os.Getpid() { - continue - } - procid, err := procs.GetProcId() - c.Assert(err, IsNil) - c.Check(procid.Pid, Equals, os.Getpid()) - static, err := procs.GetStatic() - c.Assert(err, IsNil) - c.Check(static.ParentPid, Equals, os.Getppid()) - } - err := procs.Close() - c.Assert(err, IsNil) - c.Check(count, Not(Equals), 0) -} - -// Test that we can observe the absence of a child process before it spawns and after it exits, -// and its presence during its lifetime. -func (s MySuite) TestAllProcsSpawn(c *C) { - childprocs := func() ([]ProcIdStatic, error) { - found := []ProcIdStatic{} - procs := fs.AllProcs() - mypid := os.Getpid() - for procs.Next() { - procid, err := procs.GetProcId() - if err != nil { - continue - } - static, err := procs.GetStatic() - if err != nil { - continue - } - if static.ParentPid == mypid { - found = append(found, ProcIdStatic{procid, static}) - } - } - err := procs.Close() - if err != nil { - return nil, err - } - return found, nil - } - - children1, err := childprocs() - c.Assert(err, IsNil) - - cmd := exec.Command("/bin/cat") - wc, err := cmd.StdinPipe() - c.Assert(err, IsNil) - err = cmd.Start() - c.Assert(err, IsNil) - - children2, err := childprocs() - c.Assert(err, IsNil) - - err = wc.Close() - c.Assert(err, IsNil) - err = cmd.Wait() - c.Assert(err, IsNil) - - children3, err := childprocs() - c.Assert(err, IsNil) - - foundcat := func(procs []ProcIdStatic) bool { - for _, proc := range procs { - if proc.Name == "cat" { - return true - } - } - return false - } - - c.Check(foundcat(children1), Equals, false) - c.Check(foundcat(children2), Equals, true) - c.Check(foundcat(children3), Equals, false) -} - -func (s MySuite) TestIterator(c *C) { - // create a new proc with zero metrics, cmdline, starttime, ppid - newProc := func(pid int, name string) ProcIdInfo { - pis := newProcIdStatic(pid, 0, 0, name, nil) - return ProcIdInfo{ - ProcId: pis.ProcId, - ProcStatic: pis.ProcStatic, - ProcMetrics: ProcMetrics{}, - } - } - p1 := newProc(1, "p1") - want1 := []ProcIdInfo{p1} - pi1 := procInfoIter(want1...) - got, err := consumeIter(pi1) - c.Assert(err, IsNil) - c.Check(got, DeepEquals, want1) - - p2 := newProc(2, "p2") - want2 := []ProcIdInfo{p1, p2} - pi2 := procInfoIter(want2...) - got2, err := consumeIter(pi2) - c.Assert(err, IsNil) - c.Check(got2, DeepEquals, want2) -} diff --git a/vendor/github.com/ncabatoff/process-exporter/proc/tracker_test.go b/vendor/github.com/ncabatoff/process-exporter/proc/tracker_test.go deleted file mode 100644 index 8986aaff85..0000000000 --- a/vendor/github.com/ncabatoff/process-exporter/proc/tracker_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package proc - -import ( - . "gopkg.in/check.v1" -) - -// Verify that the tracker accurately reports new procs that aren't ignored or tracked. -func (s MySuite) TestTrackerBasic(c *C) { - // create a new proc with zero metrics, cmdline, starttime, ppid - newProc := func(pid int, startTime uint64, name string) ProcIdInfo { - pis := newProcIdStatic(pid, 0, 0, name, nil) - return ProcIdInfo{ - ProcId: pis.ProcId, - ProcStatic: pis.ProcStatic, - ProcMetrics: ProcMetrics{}, - } - } - tr := NewTracker() - - // Test that p1 is seen as new - p1 := newProc(1, 1, "p1") - want1 := []ProcIdInfo{p1} - got1, _, err := tr.Update(procInfoIter(want1...)) - c.Assert(err, IsNil) - c.Check(got1, DeepEquals, want1) - - // Test that p1 is no longer seen as new once tracked - tr.Track("g1", p1) - got2, _, err := tr.Update(procInfoIter(want1...)) - c.Assert(err, IsNil) - c.Check(got2, DeepEquals, []ProcIdInfo(nil)) - - // Test that p2 is new now, but p1 is still not - p2 := newProc(2, 2, "p2") - want2 := []ProcIdInfo{p2} - got3, _, err := tr.Update(procInfoIter(p1, p2)) - c.Assert(err, IsNil) - c.Check(got3, DeepEquals, want2) - - // Test that p2 stops being new once ignored - tr.Ignore(p2.ProcId) - got4, _, err := tr.Update(procInfoIter(p1, p2)) - c.Assert(err, IsNil) - c.Check(got4, DeepEquals, []ProcIdInfo(nil)) - - // TODO test that starttime is taken into account, i.e. pid recycling is handled. -} - -// Verify that the tracker accurately reports metric changes. -func (s MySuite) TestTrackerCounts(c *C) { - // create a new proc with cmdline, starttime, ppid - newProc := func(pid int, startTime uint64, name string, m ProcMetrics) ProcIdInfo { - pis := newProcIdStatic(pid, 0, 0, name, nil) - return ProcIdInfo{ - ProcId: pis.ProcId, - ProcStatic: pis.ProcStatic, - ProcMetrics: m, - } - } - tr := NewTracker() - - // Test that p1 is seen as new - p1 := newProc(1, 1, "p1", ProcMetrics{1, 2, 3, 4, 5, 6, 4096}) - want1 := []ProcIdInfo{p1} - got1, _, err := tr.Update(procInfoIter(p1)) - c.Assert(err, IsNil) - c.Check(got1, DeepEquals, want1) - - // Test that p1 is no longer seen as new once tracked - tr.Track("g1", p1) - got2, _, err := tr.Update(procInfoIter(p1)) - c.Assert(err, IsNil) - c.Check(got2, DeepEquals, []ProcIdInfo(nil)) - - // Now update p1's metrics - p1.ProcMetrics = ProcMetrics{2, 3, 4, 5, 6, 7, 4096} - got3, _, err := tr.Update(procInfoIter(p1)) - c.Assert(err, IsNil) - c.Check(got3, DeepEquals, []ProcIdInfo(nil)) - - // Test that counts are correct - c.Check(tr.Tracked[p1.ProcId].accum, Equals, Counts{1, 1, 1}) - c.Check(tr.Tracked[p1.ProcId].info, DeepEquals, ProcInfo{p1.ProcStatic, p1.ProcMetrics}) - - // Now update p1's metrics again - p1.ProcMetrics = ProcMetrics{4, 6, 8, 9, 10, 11, 4096} - got4, _, err := tr.Update(procInfoIter(p1)) - c.Assert(err, IsNil) - c.Check(got4, DeepEquals, []ProcIdInfo(nil)) - - // Test that counts are correct - c.Check(tr.Tracked[p1.ProcId].accum, Equals, Counts{3, 4, 5}) - c.Check(tr.Tracked[p1.ProcId].info, DeepEquals, ProcInfo{p1.ProcStatic, p1.ProcMetrics}) -} diff --git a/vendor/github.com/onsi/ginkgo/.gitignore b/vendor/github.com/onsi/ginkgo/.gitignore index 34f02dccf7..f69b042c38 100644 --- a/vendor/github.com/onsi/ginkgo/.gitignore +++ b/vendor/github.com/onsi/ginkgo/.gitignore @@ -2,4 +2,5 @@ TODO tmp/**/* *.coverprofile -.vscode \ No newline at end of file +.vscode +.idea/ \ No newline at end of file diff --git a/vendor/github.com/onsi/ginkgo/.travis.yml b/vendor/github.com/onsi/ginkgo/.travis.yml index f50fc02310..7ad39b78f6 100644 --- a/vendor/github.com/onsi/ginkgo/.travis.yml +++ b/vendor/github.com/onsi/ginkgo/.travis.yml @@ -1,9 +1,10 @@ language: go go: - - 1.5.x - 1.6.x - 1.7.x - 1.8.x + - 1.9.x + - 1.10.x install: - go get -v -t ./... @@ -12,4 +13,4 @@ install: - go install github.com/onsi/ginkgo/ginkgo - export PATH=$PATH:$HOME/gopath/bin -script: $HOME/gopath/bin/ginkgo -r --randomizeAllSpecs --randomizeSuites --race --trace +script: $HOME/gopath/bin/ginkgo -r --randomizeAllSpecs --randomizeSuites --race --trace && go vet diff --git a/vendor/github.com/onsi/ginkgo/CHANGELOG.md b/vendor/github.com/onsi/ginkgo/CHANGELOG.md index b00b52ffa4..b7e787d5be 100644 --- a/vendor/github.com/onsi/ginkgo/CHANGELOG.md +++ b/vendor/github.com/onsi/ginkgo/CHANGELOG.md @@ -1,3 +1,34 @@ +## 1.5.0 5/10/2018 + +### New Features +- Supports go v1.10 (#443, #446, #451) [e873237, 468e89e, e37dbfe, a37f4c0, c0b857d, bca5260, 4177ca8] +- Add a When() synonym for Context() (#386) [747514b, 7484dad, 7354a07, dd826c8] +- Re-add noisySkippings flag [652e15c] +- Allow coverage to be displayed for focused specs (#367) [11459a8] +- Handle -outputdir flag (#364) [228e3a8] +- Handle -coverprofile flag (#355) [43392d5] + +### Fixes +- When using custom reporters register the custom reporters *before* the default reporter. This allows users to see the output of any print statements in their customer reporters. (#365) [8382b23] +- When running a test and calculating the coverage using the `-coverprofile` and `-outputdir` flags, Ginkgo fails with an error if the directory does not exist. This is due to an [issue in go 1.10](https://github.com/golang/go/issues/24588) (#446) [b36a6e0] +- `unfocus` command ignores vendor folder (#459) [e5e551c, c556e43, a3b6351, 9a820dd] +- Ignore packages whose tests are all ignored by go (#456) [7430ca7, 6d8be98] +- Increase the threshold when checking time measuments (#455) [2f714bf, 68f622c] +- Fix race condition in coverage tests (#423) [a5a8ff7, ab9c08b] +- Add an extra new line after reporting spec run completion for test2json [874520d] +- added name name field to junit reported testsuite [ae61c63] +- Do not set the run time of a spec when the dryRun flag is used (#438) [457e2d9, ba8e856] +- Process FWhen and FSpecify when unfocusing (#434) [9008c7b, ee65bd, df87dfe] +- Synchronise the access to the state of specs to avoid race conditions (#430) [7d481bc, ae6829d] +- Added Duration on GinkgoTestDescription (#383) [5f49dad, 528417e, 0747408, 329d7ed] +- Fix Ginkgo stack trace on failure for Specify (#415) [b977ede, 65ca40e, 6c46eb8] +- Update README with Go 1.6+, Golang -> Go (#409) [17f6b97, bc14b66, 20d1598] +- Use fmt.Errorf instead of errors.New(fmt.Sprintf (#401) [a299f56, 44e2eaa] +- Imports in generated code should follow conventions (#398) [0bec0b0, e8536d8] +- Prevent data race error when Recording a benchmark value from multiple go routines (#390) [c0c4881, 7a241e9] +- Replace GOPATH in Environment [4b883f0] + + ## 1.4.0 7/16/2017 - `ginkgo` now provides a hint if you accidentally forget to run `ginkgo bootstrap` to generate a `*_suite_test.go` file that actually invokes the Ginkgo test runner. [#345](https://github.com/onsi/ginkgo/pull/345) diff --git a/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md b/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md index bc0c54fe2b..8559e01363 100644 --- a/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md +++ b/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md @@ -7,6 +7,7 @@ Your contributions to Ginkgo are essential for its long-term maintenance and imp - If you're adding functionality to the Ginkgo library, make sure to add appropriate unit and/or integration tests (under the `integration` folder). - If you're adding functionality to the Ginkgo CLI note that there are very few unit tests. Please add an integration test. - Please run all tests locally (`ginkgo -r -p`) and make sure they go green before submitting the PR + - Please run following linter locally `go vet ./...` and make sure output does not contain any warnings - Update the documentation. In addition to standard `godoc` comments Ginkgo has extensive documentation on the `gh-pages` branch. If relevant, please submit a docs PR to that branch alongside your code PR. -Thanks for supporting Ginkgo! \ No newline at end of file +Thanks for supporting Ginkgo! diff --git a/vendor/github.com/onsi/ginkgo/README.md b/vendor/github.com/onsi/ginkgo/README.md index d309798998..7165b7ec55 100644 --- a/vendor/github.com/onsi/ginkgo/README.md +++ b/vendor/github.com/onsi/ginkgo/README.md @@ -1,4 +1,4 @@ -![Ginkgo: A Golang BDD Testing Framework](http://onsi.github.io/ginkgo/images/ginkgo.png) +![Ginkgo: A Go BDD Testing Framework](http://onsi.github.io/ginkgo/images/ginkgo.png) [![Build Status](https://travis-ci.org/onsi/ginkgo.svg)](https://travis-ci.org/onsi/ginkgo) @@ -11,9 +11,9 @@ If you have a question, comment, bug report, feature request, etc. please open a - Ginkgo uses Go's `testing` package and can live alongside your existing `testing` tests. It's easy to [bootstrap](http://onsi.github.io/ginkgo/#bootstrapping-a-suite) and start writing your [first tests](http://onsi.github.io/ginkgo/#adding-specs-to-a-suite) - Structure your BDD-style tests expressively: - - Nestable [`Describe` and `Context` container blocks](http://onsi.github.io/ginkgo/#organizing-specs-with-containers-describe-and-context) + - Nestable [`Describe`, `Context` and `When` container blocks](http://onsi.github.io/ginkgo/#organizing-specs-with-containers-describe-and-context) - [`BeforeEach` and `AfterEach` blocks](http://onsi.github.io/ginkgo/#extracting-common-setup-beforeeach) for setup and teardown - - [`It` blocks](http://onsi.github.io/ginkgo/#individual-specs-) that hold your assertions + - [`It` and `Specify` blocks](http://onsi.github.io/ginkgo/#individual-specs-) that hold your assertions - [`JustBeforeEach` blocks](http://onsi.github.io/ginkgo/#separating-creation-and-configuration-justbeforeeach) that separate creation from configuration (also known as the subject action pattern). - [`BeforeSuite` and `AfterSuite` blocks](http://onsi.github.io/ginkgo/#global-setup-and-teardown-beforesuite-and-aftersuite) to prep for and cleanup after a suite. @@ -25,7 +25,7 @@ If you have a question, comment, bug report, feature request, etc. please open a - `ginkgo`: a command line interface with plenty of handy command line arguments for [running your tests](http://onsi.github.io/ginkgo/#running-tests) and [generating](http://onsi.github.io/ginkgo/#generators) test files. Here are a few choice examples: - `ginkgo -nodes=N` runs your tests in `N` parallel processes and print out coherent output in realtime - - `ginkgo -cover` runs your tests using Golang's code coverage tool + - `ginkgo -cover` runs your tests using Go's code coverage tool - `ginkgo convert` converts an XUnit-style `testing` package to a Ginkgo-style package - `ginkgo -focus="REGEXP"` and `ginkgo -skip="REGEXP"` allow you to specify a subset of tests to run via regular expression - `ginkgo -r` runs all tests suites under the current directory @@ -55,18 +55,18 @@ If you have a question, comment, bug report, feature request, etc. please open a Ginkgo is best paired with Gomega. Learn more about Gomega [here](http://onsi.github.io/gomega/) -## [Agouti](http://github.com/sclevine/agouti): A Golang Acceptance Testing Framework +## [Agouti](http://github.com/sclevine/agouti): A Go Acceptance Testing Framework Agouti allows you run WebDriver integration tests. Learn more about Agouti [here](http://agouti.org) ## Set Me Up! -You'll need Golang v1.3+ (Ubuntu users: you probably have Golang v1.0 -- you'll need to upgrade!) +You'll need the Go command-line tools. Ginkgo is tested with Go 1.6+, but preferably you should get the latest. Follow the [installation instructions](https://golang.org/doc/install) if you don't have it installed. ```bash -go get github.com/onsi/ginkgo/ginkgo # installs the ginkgo CLI -go get github.com/onsi/gomega # fetches the matcher library +go get -u github.com/onsi/ginkgo/ginkgo # installs the ginkgo CLI +go get -u github.com/onsi/gomega/... # fetches the matcher library cd path/to/package/you/want/to/test @@ -85,11 +85,11 @@ Of course, I heartily recommend [Ginkgo](https://github.com/onsi/ginkgo) and [Go With that said, it's great to know what your options are :) -### What Golang gives you out of the box +### What Go gives you out of the box -Testing is a first class citizen in Golang, however Go's built-in testing primitives are somewhat limited: The [testing](http://golang.org/pkg/testing) package provides basic XUnit style tests and no assertion library. +Testing is a first class citizen in Go, however Go's built-in testing primitives are somewhat limited: The [testing](http://golang.org/pkg/testing) package provides basic XUnit style tests and no assertion library. -### Matcher libraries for Golang's XUnit style tests +### Matcher libraries for Go's XUnit style tests A number of matcher libraries have been written to augment Go's built-in XUnit style tests. Here are two that have gained traction: @@ -100,7 +100,7 @@ You can also use Ginkgo's matcher library [Gomega](https://github.com/onsi/gomeg ### BDD style testing frameworks -There are a handful of BDD-style testing frameworks written for Golang. Here are a few: +There are a handful of BDD-style testing frameworks written for Go. Here are a few: - [Ginkgo](https://github.com/onsi/ginkgo) ;) - [GoConvey](https://github.com/smartystreets/goconvey) @@ -108,10 +108,16 @@ There are a handful of BDD-style testing frameworks written for Golang. Here ar - [Mao](https://github.com/azer/mao) - [Zen](https://github.com/pranavraja/zen) -Finally, @shageman has [put together](https://github.com/shageman/gotestit) a comprehensive comparison of golang testing libraries. +Finally, @shageman has [put together](https://github.com/shageman/gotestit) a comprehensive comparison of Go testing libraries. Go explore! ## License Ginkgo is MIT-Licensed + +## Contributing + +Since Ginkgo tests also internal packages, when you fork, you'll have to replace imports with your repository.
+Use `before_pr.sh` for that
+After you finished your changes and before you push your pull request, use `after_pr.sh` to revert those changes diff --git a/vendor/github.com/onsi/ginkgo/RELEASING.md b/vendor/github.com/onsi/ginkgo/RELEASING.md new file mode 100644 index 0000000000..1e298c2da7 --- /dev/null +++ b/vendor/github.com/onsi/ginkgo/RELEASING.md @@ -0,0 +1,14 @@ +A Ginkgo release is a tagged git sha and a GitHub release. To cut a release: + +1. Ensure CHANGELOG.md is up to date. + - Use `git log --pretty=format:'- %s [%h]' HEAD...vX.X.X` to list all the commits since the last release + - Categorize the changes into + - Breaking Changes (requires a major version) + - New Features (minor version) + - Fixes (fix version) + - Maintenance (which in general should not be mentioned in `CHANGELOG.md` as they have no user impact) +1. Update `VERSION` in `config/config.go` +1. Create a commit with the version number as the commit message (e.g. `v1.3.0`) +1. Tag the commit with the version number as the tag name (e.g. `v1.3.0`) +1. Push the commit and tag to GitHub +1. Create a new [GitHub release](https://help.github.com/articles/creating-releases/) with the version number as the tag (e.g. `v1.3.0`). List the key changes in the release notes. diff --git a/vendor/github.com/onsi/ginkgo/before_pr.sh b/vendor/github.com/onsi/ginkgo/before_pr.sh new file mode 100755 index 0000000000..3cf262f388 --- /dev/null +++ b/vendor/github.com/onsi/ginkgo/before_pr.sh @@ -0,0 +1,13 @@ +# Take current path +path=$(pwd) + +# Split it +IFS='\/'; arrIN=($path); unset IFS; + +# Find directory before ginkgo +len=${#arrIN[@]} + +userDir=${arrIN[$len-2]} + +# Replace onsi with userdir +find . -type f -name '*.go' -exec sed -i '' s/github.com\\/onsi\\/ginkgo\\/internal/github.com\\/$userDir\\/ginkgo\\/internal/ {} + \ No newline at end of file diff --git a/vendor/github.com/onsi/ginkgo/config/config.go b/vendor/github.com/onsi/ginkgo/config/config.go index 60d5ea22e8..9b320e387c 100644 --- a/vendor/github.com/onsi/ginkgo/config/config.go +++ b/vendor/github.com/onsi/ginkgo/config/config.go @@ -20,7 +20,7 @@ import ( "fmt" ) -const VERSION = "1.4.0" +const VERSION = "1.5.0" type GinkgoConfigType struct { RandomSeed int64 @@ -47,6 +47,7 @@ type DefaultReporterConfigType struct { NoColor bool SlowSpecThreshold float64 NoisyPendings bool + NoisySkippings bool Succinct bool Verbose bool FullTrace bool @@ -64,7 +65,7 @@ func processPrefix(prefix string) string { func Flags(flagSet *flag.FlagSet, prefix string, includeParallelFlags bool) { prefix = processPrefix(prefix) flagSet.Int64Var(&(GinkgoConfig.RandomSeed), prefix+"seed", time.Now().Unix(), "The seed used to randomize the spec suite.") - flagSet.BoolVar(&(GinkgoConfig.RandomizeAllSpecs), prefix+"randomizeAllSpecs", false, "If set, ginkgo will randomize all specs together. By default, ginkgo only randomizes the top level Describe/Context groups.") + flagSet.BoolVar(&(GinkgoConfig.RandomizeAllSpecs), prefix+"randomizeAllSpecs", false, "If set, ginkgo will randomize all specs together. By default, ginkgo only randomizes the top level Describe, Context and When groups.") flagSet.BoolVar(&(GinkgoConfig.SkipMeasurements), prefix+"skipMeasurements", false, "If set, ginkgo will skip any measurement specs.") flagSet.BoolVar(&(GinkgoConfig.FailOnPending), prefix+"failOnPending", false, "If set, ginkgo will mark the test suite as failed if any specs are pending.") flagSet.BoolVar(&(GinkgoConfig.FailFast), prefix+"failFast", false, "If set, ginkgo will stop running a test suite after a failure occurs.") @@ -90,6 +91,7 @@ func Flags(flagSet *flag.FlagSet, prefix string, includeParallelFlags bool) { flagSet.BoolVar(&(DefaultReporterConfig.NoColor), prefix+"noColor", false, "If set, suppress color output in default reporter.") flagSet.Float64Var(&(DefaultReporterConfig.SlowSpecThreshold), prefix+"slowSpecThreshold", 5.0, "(in seconds) Specs that take longer to run than this threshold are flagged as slow by the default reporter.") flagSet.BoolVar(&(DefaultReporterConfig.NoisyPendings), prefix+"noisyPendings", true, "If set, default reporter will shout about pending tests.") + flagSet.BoolVar(&(DefaultReporterConfig.NoisySkippings), prefix+"noisySkippings", true, "If set, default reporter will shout about skipping tests.") flagSet.BoolVar(&(DefaultReporterConfig.Verbose), prefix+"v", false, "If set, default reporter print out all specs as they begin.") flagSet.BoolVar(&(DefaultReporterConfig.Succinct), prefix+"succinct", false, "If set, default reporter prints out a very succinct report") flagSet.BoolVar(&(DefaultReporterConfig.FullTrace), prefix+"trace", false, "If set, default reporter prints out the full stack trace when a failure occurs") @@ -171,6 +173,10 @@ func BuildFlagArgs(prefix string, ginkgo GinkgoConfigType, reporter DefaultRepor result = append(result, fmt.Sprintf("--%snoisyPendings=false", prefix)) } + if !reporter.NoisySkippings { + result = append(result, fmt.Sprintf("--%snoisySkippings=false", prefix)) + } + if reporter.Verbose { result = append(result, fmt.Sprintf("--%sv", prefix)) } diff --git a/vendor/github.com/onsi/ginkgo/ginkgo_dsl.go b/vendor/github.com/onsi/ginkgo/ginkgo_dsl.go index 8fe0b70a62..ea5b7ccde4 100644 --- a/vendor/github.com/onsi/ginkgo/ginkgo_dsl.go +++ b/vendor/github.com/onsi/ginkgo/ginkgo_dsl.go @@ -149,7 +149,8 @@ type GinkgoTestDescription struct { FileName string LineNumber int - Failed bool + Failed bool + Duration time.Duration } //CurrentGinkgoTestDescripton returns information about the current running test. @@ -169,6 +170,7 @@ func CurrentGinkgoTestDescription() GinkgoTestDescription { FileName: subjectCodeLocation.FileName, LineNumber: subjectCodeLocation.LineNumber, Failed: summary.HasFailureState(), + Duration: summary.RunTime, } } @@ -202,7 +204,7 @@ func RunSpecs(t GinkgoTestingT, description string) bool { //To run your tests with Ginkgo's default reporter and your custom reporter(s), replace //RunSpecs() with this method. func RunSpecsWithDefaultAndCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool { - specReporters = append([]Reporter{buildDefaultReporter()}, specReporters...) + specReporters = append(specReporters, buildDefaultReporter()) return RunSpecsWithCustomReporters(t, description, specReporters) } @@ -216,7 +218,7 @@ func RunSpecsWithCustomReporters(t GinkgoTestingT, description string, specRepor reporters[i] = reporter } passed, hasFocusedTests := globalSuite.Run(t, description, reporters, writer, config.GinkgoConfig) - if passed && hasFocusedTests { + if passed && hasFocusedTests && strings.TrimSpace(os.Getenv("GINKGO_EDITOR_INTEGRATION")) == "" { fmt.Println("PASS | FOCUSED") os.Exit(types.GINKGO_FOCUS_EXIT_CODE) } @@ -233,7 +235,7 @@ func buildDefaultReporter() Reporter { } } -//Skip notifies Ginkgo that the current spec should be skipped. +//Skip notifies Ginkgo that the current spec was skipped. func Skip(message string, callerSkip ...int) { skip := 0 if len(callerSkip) > 0 { @@ -275,9 +277,9 @@ func GinkgoRecover() { //Describe blocks allow you to organize your specs. A Describe block can contain any number of //BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks. // -//In addition you can nest Describe and Context blocks. Describe and Context blocks are functionally +//In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally //equivalent. The difference is purely semantic -- you typical Describe the behavior of an object -//or method and, within that Describe, outline a number of Contexts. +//or method and, within that Describe, outline a number of Contexts and Whens. func Describe(text string, body func()) bool { globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1)) return true @@ -304,9 +306,9 @@ func XDescribe(text string, body func()) bool { //Context blocks allow you to organize your specs. A Context block can contain any number of //BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks. // -//In addition you can nest Describe and Context blocks. Describe and Context blocks are functionally +//In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally //equivalent. The difference is purely semantic -- you typical Describe the behavior of an object -//or method and, within that Describe, outline a number of Contexts. +//or method and, within that Describe, outline a number of Contexts and Whens. func Context(text string, body func()) bool { globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1)) return true @@ -330,6 +332,35 @@ func XContext(text string, body func()) bool { return true } +//When blocks allow you to organize your specs. A When block can contain any number of +//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks. +// +//In addition you can nest Describe, Context and When blocks. Describe, Context and When blocks are functionally +//equivalent. The difference is purely semantic -- you typical Describe the behavior of an object +//or method and, within that Describe, outline a number of Contexts and Whens. +func When(text string, body func()) bool { + globalSuite.PushContainerNode("when "+text, body, types.FlagTypeNone, codelocation.New(1)) + return true +} + +//You can focus the tests within a describe block using FWhen +func FWhen(text string, body func()) bool { + globalSuite.PushContainerNode("when "+text, body, types.FlagTypeFocused, codelocation.New(1)) + return true +} + +//You can mark the tests within a describe block as pending using PWhen +func PWhen(text string, body func()) bool { + globalSuite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1)) + return true +} + +//You can mark the tests within a describe block as pending using XWhen +func XWhen(text string, body func()) bool { + globalSuite.PushContainerNode("when "+text, body, types.FlagTypePending, codelocation.New(1)) + return true +} + //It blocks contain your test code and assertions. You cannot nest any other Ginkgo blocks //within an It block. // @@ -362,22 +393,26 @@ func XIt(text string, _ ...interface{}) bool { //which "It" does not fit into a natural sentence flow. All the same protocols apply for Specify blocks //which apply to It blocks. func Specify(text string, body interface{}, timeout ...float64) bool { - return It(text, body, timeout...) + globalSuite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...)) + return true } //You can focus individual Specifys using FSpecify func FSpecify(text string, body interface{}, timeout ...float64) bool { - return FIt(text, body, timeout...) + globalSuite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...)) + return true } //You can mark Specifys as pending using PSpecify func PSpecify(text string, is ...interface{}) bool { - return PIt(text, is...) + globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0) + return true } //You can mark Specifys as pending using XSpecify func XSpecify(text string, is ...interface{}) bool { - return XIt(text, is...) + globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0) + return true } //By allows you to better document large Its. diff --git a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go deleted file mode 100644 index f06abf3c56..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package codelocation_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestCodelocation(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "CodeLocation Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go b/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go deleted file mode 100644 index 55a9e9d036..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location_test.go +++ /dev/null @@ -1,79 +0,0 @@ -package codelocation_test - -import ( - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "runtime" -) - -var _ = Describe("CodeLocation", func() { - var ( - codeLocation types.CodeLocation - expectedFileName string - expectedLineNumber int - ) - - caller0 := func() { - codeLocation = codelocation.New(1) - } - - caller1 := func() { - _, expectedFileName, expectedLineNumber, _ = runtime.Caller(0) - expectedLineNumber += 2 - caller0() - } - - BeforeEach(func() { - caller1() - }) - - It("should use the passed in skip parameter to pick out the correct file & line number", func() { - Ω(codeLocation.FileName).Should(Equal(expectedFileName)) - Ω(codeLocation.LineNumber).Should(Equal(expectedLineNumber)) - }) - - Describe("stringer behavior", func() { - It("should stringify nicely", func() { - Ω(codeLocation.String()).Should(ContainSubstring("code_location_test.go:%d", expectedLineNumber)) - }) - }) - - //There's no better way than to test this private method as it - //goes out of its way to prune out ginkgo related code in the stack trace - Describe("PruneStack", func() { - It("should remove any references to ginkgo and pkg/testing and pkg/runtime", func() { - input := `/Skip/me -Skip: skip() -/Skip/me -Skip: skip() -/Users/whoever/gospace/src/github.com/onsi/ginkgo/whatever.go:10 (0x12314) -Something: Func() -/Users/whoever/gospace/src/github.com/onsi/ginkgo/whatever_else.go:10 (0x12314) -SomethingInternalToGinkgo: Func() -/usr/goroot/pkg/strings/oops.go:10 (0x12341) -Oops: BlowUp() -/Users/whoever/gospace/src/mycode/code.go:10 (0x12341) -MyCode: Func() -/Users/whoever/gospace/src/mycode/code_test.go:10 (0x12341) -MyCodeTest: Func() -/Users/whoever/gospace/src/mycode/code_suite_test.go:12 (0x37f08) -TestFoo: RunSpecs(t, "Foo Suite") -/usr/goroot/pkg/testing/testing.go:12 (0x37f08) -TestingT: Blah() -/usr/goroot/pkg/runtime/runtime.go:12 (0x37f08) -Something: Func() -` - prunedStack := codelocation.PruneStack(input, 1) - Ω(prunedStack).Should(Equal(`/usr/goroot/pkg/strings/oops.go:10 (0x12341) -Oops: BlowUp() -/Users/whoever/gospace/src/mycode/code.go:10 (0x12341) -MyCode: Func() -/Users/whoever/gospace/src/mycode/code_test.go:10 (0x12341) -MyCodeTest: Func() -/Users/whoever/gospace/src/mycode/code_suite_test.go:12 (0x37f08) -TestFoo: RunSpecs(t, "Foo Suite")`)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go deleted file mode 100644 index c6fc314ff5..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package containernode_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestContainernode(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Containernode Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_test.go b/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_test.go deleted file mode 100644 index b8d61b13fc..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node_test.go +++ /dev/null @@ -1,212 +0,0 @@ -package containernode_test - -import ( - "github.com/onsi/ginkgo/internal/leafnodes" - "math/rand" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - . "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Container Node", func() { - var ( - codeLocation types.CodeLocation - container *ContainerNode - ) - - BeforeEach(func() { - codeLocation = codelocation.New(0) - container = New("description text", types.FlagTypeFocused, codeLocation) - }) - - Describe("creating a container node", func() { - It("can answer questions about itself", func() { - Ω(container.Text()).Should(Equal("description text")) - Ω(container.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(container.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("pushing setup nodes", func() { - It("can append setup nodes of various types and fetch them by type", func() { - befA := leafnodes.NewBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - befB := leafnodes.NewBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - aftA := leafnodes.NewAfterEachNode(func() {}, codelocation.New(0), 0, nil, 0) - aftB := leafnodes.NewAfterEachNode(func() {}, codelocation.New(0), 0, nil, 0) - jusBefA := leafnodes.NewJustBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - jusBefB := leafnodes.NewJustBeforeEachNode(func() {}, codelocation.New(0), 0, nil, 0) - - container.PushSetupNode(befA) - container.PushSetupNode(befB) - container.PushSetupNode(aftA) - container.PushSetupNode(aftB) - container.PushSetupNode(jusBefA) - container.PushSetupNode(jusBefB) - - subject := leafnodes.NewItNode("subject", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(subject) - - Ω(container.SetupNodesOfType(types.SpecComponentTypeBeforeEach)).Should(Equal([]leafnodes.BasicNode{befA, befB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeAfterEach)).Should(Equal([]leafnodes.BasicNode{aftA, aftB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeJustBeforeEach)).Should(Equal([]leafnodes.BasicNode{jusBefA, jusBefB})) - Ω(container.SetupNodesOfType(types.SpecComponentTypeIt)).Should(BeEmpty()) //subjects are not setup nodes - }) - }) - - Context("With appended containers and subject nodes", func() { - var ( - itA, itB, innerItA, innerItB leafnodes.SubjectNode - innerContainer *ContainerNode - ) - - BeforeEach(func() { - itA = leafnodes.NewItNode("Banana", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - itB = leafnodes.NewItNode("Apple", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - innerItB = leafnodes.NewItNode("inner B", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - - innerContainer = New("Orange", types.FlagTypeNone, codelocation.New(0)) - - container.PushSubjectNode(itA) - container.PushContainerNode(innerContainer) - innerContainer.PushSubjectNode(innerItA) - innerContainer.PushSubjectNode(innerItB) - container.PushSubjectNode(itB) - }) - - Describe("Collating", func() { - It("should return a collated set of containers and subject nodes in the correct order", func() { - collated := container.Collate() - Ω(collated).Should(HaveLen(4)) - - Ω(collated[0]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container}, - Subject: itA, - })) - - Ω(collated[1]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container, innerContainer}, - Subject: innerItA, - })) - - Ω(collated[2]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container, innerContainer}, - Subject: innerItB, - })) - - Ω(collated[3]).Should(Equal(CollatedNodes{ - Containers: []*ContainerNode{container}, - Subject: itB, - })) - }) - }) - - Describe("Backpropagating Programmatic Focus", func() { - //This allows inner focused specs to override the focus of outer focussed - //specs and more closely maps to what a developer wants to happen - //when debugging a test suite - - Context("when a parent is focused *and* an inner subject is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypeNone, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeFocused, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should unfocus the parent", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeFocused)) - }) - }) - - Context("when a parent is focused *and* an inner container is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypeFocused, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should unfocus the parent", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeNone)) - }) - }) - - Context("when a parent is pending and a child is focused", func() { - BeforeEach(func() { - container = New("description text", types.FlagTypeFocused, codeLocation) - itA = leafnodes.NewItNode("A", func() {}, types.FlagTypeNone, codelocation.New(0), 0, nil, 0) - container.PushSubjectNode(itA) - - innerContainer = New("Orange", types.FlagTypePending, codelocation.New(0)) - container.PushContainerNode(innerContainer) - innerItA = leafnodes.NewItNode("inner A", func() {}, types.FlagTypeFocused, codelocation.New(0), 0, nil, 0) - innerContainer.PushSubjectNode(innerItA) - }) - - It("should not do anything", func() { - container.BackPropagateProgrammaticFocus() - - Ω(container.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(itA.Flag()).Should(Equal(types.FlagTypeNone)) - Ω(innerContainer.Flag()).Should(Equal(types.FlagTypePending)) - Ω(innerItA.Flag()).Should(Equal(types.FlagTypeFocused)) - }) - }) - }) - - Describe("Shuffling", func() { - var unshuffledCollation []CollatedNodes - BeforeEach(func() { - unshuffledCollation = container.Collate() - - r := rand.New(rand.NewSource(17)) - container.Shuffle(r) - }) - - It("should sort, and then shuffle, the top level contents of the container", func() { - shuffledCollation := container.Collate() - Ω(shuffledCollation).Should(HaveLen(len(unshuffledCollation))) - Ω(shuffledCollation).ShouldNot(Equal(unshuffledCollation)) - - for _, entry := range unshuffledCollation { - Ω(shuffledCollation).Should(ContainElement(entry)) - } - - innerAIndex, innerBIndex := 0, 0 - for i, entry := range shuffledCollation { - if entry.Subject == innerItA { - innerAIndex = i - } else if entry.Subject == innerItB { - innerBIndex = i - } - } - - Ω(innerAIndex).Should(Equal(innerBIndex - 1)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go deleted file mode 100644 index 8dce7be9ac..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/failer/failer_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package failer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestFailer(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Failer Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/failer/failer_test.go b/vendor/github.com/onsi/ginkgo/internal/failer/failer_test.go deleted file mode 100644 index 65210a40a7..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/failer/failer_test.go +++ /dev/null @@ -1,141 +0,0 @@ -package failer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/failer" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Failer", func() { - var ( - failer *Failer - codeLocationA types.CodeLocation - codeLocationB types.CodeLocation - ) - - BeforeEach(func() { - codeLocationA = codelocation.New(0) - codeLocationB = codelocation.New(0) - failer = New() - }) - - Context("with no failures", func() { - It("should return success when drained", func() { - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(BeZero()) - Ω(state).Should(Equal(types.SpecStatePassed)) - }) - }) - - Describe("Skip", func() { - It("should handle failures", func() { - failer.Skip("something skipped", codeLocationA) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "something skipped", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateSkipped)) - }) - }) - - Describe("Fail", func() { - It("should handle failures", func() { - failer.Fail("something failed", codeLocationA) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "something failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - }) - - Describe("Panic", func() { - It("should handle panics", func() { - failer.Panic(codeLocationA, "some forwarded panic") - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Test Panicked", - Location: codeLocationA, - ForwardedPanic: "some forwarded panic", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStatePanicked)) - }) - }) - - Describe("Timeout", func() { - It("should handle timeouts", func() { - failer.Timeout(codeLocationA) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Timed out", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateTimedOut)) - }) - }) - - Context("when multiple failures are registered", func() { - BeforeEach(func() { - failer.Fail("something failed", codeLocationA) - failer.Fail("something else failed", codeLocationA) - }) - - It("should only report the first one when drained", func() { - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "something failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - - It("should report subsequent failures after being drained", func() { - failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - failer.Fail("yet another thing failed", codeLocationA) - - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "yet another thing failed", - Location: codeLocationA, - ForwardedPanic: "", - ComponentType: types.SpecComponentTypeIt, - ComponentIndex: 3, - ComponentCodeLocation: codeLocationB, - })) - Ω(state).Should(Equal(types.SpecStateFailed)) - }) - - It("should report sucess on subsequent drains if no errors occur", func() { - failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - failure, state := failer.Drain(types.SpecComponentTypeIt, 3, codeLocationB) - Ω(failure).Should(BeZero()) - Ω(state).Should(Equal(types.SpecStatePassed)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go index 9c3eed2b6f..d6d54234c2 100644 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go +++ b/vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go @@ -35,15 +35,15 @@ func (b *benchmarker) Time(name string, body func(), info ...interface{}) (elaps } func (b *benchmarker) RecordValue(name string, value float64, info ...interface{}) { - measurement := b.getMeasurement(name, "Smallest", " Largest", " Average", "", 3, info...) b.mu.Lock() + measurement := b.getMeasurement(name, "Smallest", " Largest", " Average", "", 3, info...) defer b.mu.Unlock() measurement.Results = append(measurement.Results, value) } func (b *benchmarker) RecordValueWithPrecision(name string, value float64, units string, precision int, info ...interface{}) { - measurement := b.getMeasurement(name, "Smallest", " Largest", " Average", units, precision, info...) b.mu.Lock() + measurement := b.getMeasurement(name, "Smallest", " Largest", " Average", units, precision, info...) defer b.mu.Unlock() measurement.Results = append(measurement.Results, value) } diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go index c76fe3a451..6eded7b763 100644 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go +++ b/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go @@ -1,9 +1,10 @@ package leafnodes import ( + "time" + "github.com/onsi/ginkgo/internal/failer" "github.com/onsi/ginkgo/types" - "time" ) type ItNode struct { diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go deleted file mode 100644 index 29fa0c6e2a..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node_test.go +++ /dev/null @@ -1,22 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("It Nodes", func() { - It("should report the correct type, text, flag, and code location", func() { - codeLocation := codelocation.New(0) - it := NewItNode("my it node", func() {}, types.FlagTypeFocused, codeLocation, 0, nil, 3) - Ω(it.Type()).Should(Equal(types.SpecComponentTypeIt)) - Ω(it.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(it.Text()).Should(Equal("my it node")) - Ω(it.CodeLocation()).Should(Equal(codeLocation)) - Ω(it.Samples()).Should(Equal(1)) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go deleted file mode 100644 index a7ba9e006e..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/leaf_node_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestLeafNode(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "LeafNode Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go index efc3348c1b..3ab9a6d552 100644 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go +++ b/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go @@ -1,9 +1,10 @@ package leafnodes import ( + "reflect" + "github.com/onsi/ginkgo/internal/failer" "github.com/onsi/ginkgo/types" - "reflect" ) type MeasureNode struct { diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go deleted file mode 100644 index 252065b871..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -var _ = Describe("Measure Nodes", func() { - It("should report the correct type, text, flag, and code location", func() { - codeLocation := codelocation.New(0) - measure := NewMeasureNode("my measure node", func(b Benchmarker) {}, types.FlagTypeFocused, codeLocation, 10, nil, 3) - Ω(measure.Type()).Should(Equal(types.SpecComponentTypeMeasure)) - Ω(measure.Flag()).Should(Equal(types.FlagTypeFocused)) - Ω(measure.Text()).Should(Equal("my measure node")) - Ω(measure.CodeLocation()).Should(Equal(codeLocation)) - Ω(measure.Samples()).Should(Equal(10)) - }) - - Describe("benchmarking", func() { - var measure *MeasureNode - - Describe("Value", func() { - BeforeEach(func() { - measure = NewMeasureNode("the measurement", func(b Benchmarker) { - b.RecordValue("foo", 7, "info!") - b.RecordValue("foo", 2) - b.RecordValue("foo", 3) - b.RecordValue("bar", 0.3) - b.RecordValue("bar", 0.1) - b.RecordValue("bar", 0.5) - b.RecordValue("bar", 0.7) - }, types.FlagTypeFocused, codelocation.New(0), 1, Failer.New(), 3) - Ω(measure.Run()).Should(Equal(types.SpecStatePassed)) - }) - - It("records passed in values and reports on them", func() { - report := measure.MeasurementsReport() - Ω(report).Should(HaveLen(2)) - Ω(report["foo"].Name).Should(Equal("foo")) - Ω(report["foo"].Info).Should(Equal("info!")) - Ω(report["foo"].Order).Should(Equal(0)) - Ω(report["foo"].SmallestLabel).Should(Equal("Smallest")) - Ω(report["foo"].LargestLabel).Should(Equal(" Largest")) - Ω(report["foo"].AverageLabel).Should(Equal(" Average")) - Ω(report["foo"].Units).Should(Equal("")) - Ω(report["foo"].Results).Should(Equal([]float64{7, 2, 3})) - Ω(report["foo"].Smallest).Should(BeNumerically("==", 2)) - Ω(report["foo"].Largest).Should(BeNumerically("==", 7)) - Ω(report["foo"].Average).Should(BeNumerically("==", 4)) - Ω(report["foo"].StdDeviation).Should(BeNumerically("~", 2.16, 0.01)) - - Ω(report["bar"].Name).Should(Equal("bar")) - Ω(report["bar"].Info).Should(BeNil()) - Ω(report["bar"].SmallestLabel).Should(Equal("Smallest")) - Ω(report["bar"].Order).Should(Equal(1)) - Ω(report["bar"].LargestLabel).Should(Equal(" Largest")) - Ω(report["bar"].AverageLabel).Should(Equal(" Average")) - Ω(report["bar"].Units).Should(Equal("")) - Ω(report["bar"].Results).Should(Equal([]float64{0.3, 0.1, 0.5, 0.7})) - Ω(report["bar"].Smallest).Should(BeNumerically("==", 0.1)) - Ω(report["bar"].Largest).Should(BeNumerically("==", 0.7)) - Ω(report["bar"].Average).Should(BeNumerically("==", 0.4)) - Ω(report["bar"].StdDeviation).Should(BeNumerically("~", 0.22, 0.01)) - }) - }) - - Describe("Value with precision", func() { - BeforeEach(func() { - measure = NewMeasureNode("the measurement", func(b Benchmarker) { - b.RecordValueWithPrecision("foo", 7, "ms", 7, "info!") - b.RecordValueWithPrecision("foo", 2, "ms", 6) - b.RecordValueWithPrecision("foo", 3, "ms", 5) - b.RecordValueWithPrecision("bar", 0.3, "ns", 4) - b.RecordValueWithPrecision("bar", 0.1, "ns", 3) - b.RecordValueWithPrecision("bar", 0.5, "ns", 2) - b.RecordValueWithPrecision("bar", 0.7, "ns", 1) - }, types.FlagTypeFocused, codelocation.New(0), 1, Failer.New(), 3) - Ω(measure.Run()).Should(Equal(types.SpecStatePassed)) - }) - - It("records passed in values and reports on them", func() { - report := measure.MeasurementsReport() - Ω(report).Should(HaveLen(2)) - Ω(report["foo"].Name).Should(Equal("foo")) - Ω(report["foo"].Info).Should(Equal("info!")) - Ω(report["foo"].Order).Should(Equal(0)) - Ω(report["foo"].SmallestLabel).Should(Equal("Smallest")) - Ω(report["foo"].LargestLabel).Should(Equal(" Largest")) - Ω(report["foo"].AverageLabel).Should(Equal(" Average")) - Ω(report["foo"].Units).Should(Equal("ms")) - Ω(report["foo"].Results).Should(Equal([]float64{7, 2, 3})) - Ω(report["foo"].Smallest).Should(BeNumerically("==", 2)) - Ω(report["foo"].Largest).Should(BeNumerically("==", 7)) - Ω(report["foo"].Average).Should(BeNumerically("==", 4)) - Ω(report["foo"].StdDeviation).Should(BeNumerically("~", 2.16, 0.01)) - - Ω(report["bar"].Name).Should(Equal("bar")) - Ω(report["bar"].Info).Should(BeNil()) - Ω(report["bar"].SmallestLabel).Should(Equal("Smallest")) - Ω(report["bar"].Order).Should(Equal(1)) - Ω(report["bar"].LargestLabel).Should(Equal(" Largest")) - Ω(report["bar"].AverageLabel).Should(Equal(" Average")) - Ω(report["bar"].Units).Should(Equal("ns")) - Ω(report["bar"].Results).Should(Equal([]float64{0.3, 0.1, 0.5, 0.7})) - Ω(report["bar"].Smallest).Should(BeNumerically("==", 0.1)) - Ω(report["bar"].Largest).Should(BeNumerically("==", 0.7)) - Ω(report["bar"].Average).Should(BeNumerically("==", 0.4)) - Ω(report["bar"].StdDeviation).Should(BeNumerically("~", 0.22, 0.01)) - }) - }) - - Describe("Time", func() { - BeforeEach(func() { - measure = NewMeasureNode("the measurement", func(b Benchmarker) { - b.Time("foo", func() { - time.Sleep(100 * time.Millisecond) - }, "info!") - b.Time("foo", func() { - time.Sleep(200 * time.Millisecond) - }) - b.Time("foo", func() { - time.Sleep(170 * time.Millisecond) - }) - }, types.FlagTypeFocused, codelocation.New(0), 1, Failer.New(), 3) - Ω(measure.Run()).Should(Equal(types.SpecStatePassed)) - }) - - It("records passed in values and reports on them", func() { - report := measure.MeasurementsReport() - Ω(report).Should(HaveLen(1)) - Ω(report["foo"].Name).Should(Equal("foo")) - Ω(report["foo"].Info).Should(Equal("info!")) - Ω(report["foo"].SmallestLabel).Should(Equal("Fastest Time")) - Ω(report["foo"].LargestLabel).Should(Equal("Slowest Time")) - Ω(report["foo"].AverageLabel).Should(Equal("Average Time")) - Ω(report["foo"].Units).Should(Equal("s")) - Ω(report["foo"].Results).Should(HaveLen(3)) - Ω(report["foo"].Results[0]).Should(BeNumerically("~", 0.1, 0.01)) - Ω(report["foo"].Results[1]).Should(BeNumerically("~", 0.2, 0.01)) - Ω(report["foo"].Results[2]).Should(BeNumerically("~", 0.17, 0.01)) - Ω(report["foo"].Smallest).Should(BeNumerically("~", 0.1, 0.01)) - Ω(report["foo"].Largest).Should(BeNumerically("~", 0.2, 0.01)) - Ω(report["foo"].Average).Should(BeNumerically("~", 0.16, 0.01)) - Ω(report["foo"].StdDeviation).Should(BeNumerically("~", 0.04, 0.01)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go index 870ad826da..8b6518b5c8 100644 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go +++ b/vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go @@ -2,11 +2,12 @@ package leafnodes import ( "fmt" + "reflect" + "time" + "github.com/onsi/ginkgo/internal/codelocation" "github.com/onsi/ginkgo/internal/failer" "github.com/onsi/ginkgo/types" - "reflect" - "time" ) type runner struct { diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go index 6b725a6315..b4654cd299 100644 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go +++ b/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go @@ -1,9 +1,10 @@ package leafnodes import ( + "time" + "github.com/onsi/ginkgo/internal/failer" "github.com/onsi/ginkgo/types" - "time" ) type SetupNode struct { diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go deleted file mode 100644 index d5b9251f65..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - - . "github.com/onsi/ginkgo/internal/leafnodes" - - "github.com/onsi/ginkgo/internal/codelocation" -) - -var _ = Describe("Setup Nodes", func() { - Describe("BeforeEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - beforeEach := NewBeforeEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(beforeEach.Type()).Should(Equal(types.SpecComponentTypeBeforeEach)) - Ω(beforeEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("AfterEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - afterEach := NewAfterEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(afterEach.Type()).Should(Equal(types.SpecComponentTypeAfterEach)) - Ω(afterEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) - - Describe("JustBeforeEachNodes", func() { - It("should report the correct type and code location", func() { - codeLocation := codelocation.New(0) - justBeforeEach := NewJustBeforeEachNode(func() {}, codeLocation, 0, nil, 3) - Ω(justBeforeEach.Type()).Should(Equal(types.SpecComponentTypeJustBeforeEach)) - Ω(justBeforeEach.CodeLocation()).Should(Equal(codeLocation)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go deleted file mode 100644 index fcccef488b..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/shared_runner_test.go +++ /dev/null @@ -1,356 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "reflect" - "time" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -type runnable interface { - Run() (outcome types.SpecState, failure types.SpecFailure) - CodeLocation() types.CodeLocation -} - -func SynchronousSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType, componentIndex int) { - var ( - outcome types.SpecState - failure types.SpecFailure - - failer *Failer.Failer - - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - - didRun bool - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - - didRun = false - }) - - Describe("synchronous functions", func() { - Context("when the function passes", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - }, 0, failer, componentCodeLocation).Run() - }) - - It("should have a succesful outcome", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePassed)) - Ω(failure).Should(BeZero()) - }) - }) - - Context("when a failure occurs", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - failer.Fail("bam", innerCodeLocation) - panic("should not matter") - }, 0, failer, componentCodeLocation).Run() - }) - - It("should return the failure", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateFailed)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "bam", - Location: innerCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when a panic occurs", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - innerCodeLocation = codelocation.New(0) - panic("ack!") - }, 0, failer, componentCodeLocation).Run() - }) - - It("should return the panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("ack!")) - }) - }) - - Context("when a panic occurs with a nil value", func() { - BeforeEach(func() { - outcome, failure = build(func() { - didRun = true - innerCodeLocation = codelocation.New(0) - panic(nil) - }, 0, failer, componentCodeLocation).Run() - }) - - It("should return the nil-valued panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("")) - }) - }) - - }) -} - -func AsynchronousSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType, componentIndex int) { - var ( - outcome types.SpecState - failure types.SpecFailure - - failer *Failer.Failer - - componentCodeLocation types.CodeLocation - innerCodeLocation types.CodeLocation - - didRun bool - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - - didRun = false - }) - - Describe("asynchronous functions", func() { - var timeoutDuration time.Duration - - BeforeEach(func() { - timeoutDuration = time.Duration(1 * float64(time.Second)) - }) - - Context("when running", func() { - It("should run the function as a goroutine, and block until it's done", func() { - proveAsync := make(chan bool) - - build(func(done Done) { - didRun = true - proveAsync <- true - close(done) - }, timeoutDuration, failer, componentCodeLocation).Run() - - Eventually(proveAsync).Should(Receive(Equal(true))) - }) - }) - - Context("when the function passes", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - close(done) - }, timeoutDuration, failer, componentCodeLocation).Run() - }) - - It("should have a succesful outcome", func() { - Ω(didRun).Should(BeTrue()) - Ω(outcome).Should(Equal(types.SpecStatePassed)) - Ω(failure).Should(BeZero()) - }) - }) - - Context("when the function fails", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - failer.Fail("bam", innerCodeLocation) - time.Sleep(20 * time.Millisecond) - panic("doesn't matter") - close(done) - }, 10*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the failure", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateFailed)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "bam", - Location: innerCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when the function times out", func() { - var guard chan struct{} - - BeforeEach(func() { - guard = make(chan struct{}) - outcome, failure = build(func(done Done) { - didRun = true - time.Sleep(20 * time.Millisecond) - close(guard) - panic("doesn't matter") - close(done) - }, 10*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the timeout", func() { - <-guard - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStateTimedOut)) - Ω(failure).Should(Equal(types.SpecFailure{ - Message: "Timed out", - Location: componentCodeLocation, - ForwardedPanic: "", - ComponentIndex: componentIndex, - ComponentType: componentType, - ComponentCodeLocation: componentCodeLocation, - })) - }) - }) - - Context("when the function panics", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - innerCodeLocation = codelocation.New(0) - panic("ack!") - }, 100*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("ack!")) - }) - }) - - Context("when the function panics with a nil value", func() { - BeforeEach(func() { - outcome, failure = build(func(done Done) { - didRun = true - innerCodeLocation = codelocation.New(0) - panic(nil) - }, 100*time.Millisecond, failer, componentCodeLocation).Run() - }) - - It("should return the nil-valued panic", func() { - Ω(didRun).Should(BeTrue()) - - Ω(outcome).Should(Equal(types.SpecStatePanicked)) - Ω(failure.ForwardedPanic).Should(Equal("")) - }) - }) - }) -} - -func InvalidSharedRunnerBehaviors(build func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable, componentType types.SpecComponentType) { - var ( - failer *Failer.Failer - componentCodeLocation types.CodeLocation - ) - - BeforeEach(func() { - failer = Failer.New() - componentCodeLocation = codelocation.New(0) - }) - - Describe("invalid functions", func() { - Context("when passed something that's not a function", func() { - It("should panic", func() { - Ω(func() { - build("not a function", 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - - Context("when the function takes the wrong kind of argument", func() { - It("should panic", func() { - Ω(func() { - build(func(oops string) {}, 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - - Context("when the function takes more than one argument", func() { - It("should panic", func() { - Ω(func() { - build(func(done Done, oops string) {}, 0, failer, componentCodeLocation) - }).Should(Panic()) - }) - }) - }) -} - -var _ = Describe("Shared RunnableNode behavior", func() { - Describe("It Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewItNode("", body, types.FlagTypeFocused, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeIt, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeIt, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeIt) - }) - - Describe("Measure Nodes", func() { - build := func(body interface{}, _ time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewMeasureNode("", func(Benchmarker) { - reflect.ValueOf(body).Call([]reflect.Value{}) - }, types.FlagTypeFocused, componentCodeLocation, 10, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeMeasure, 3) - }) - - Describe("BeforeEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewBeforeEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeBeforeEach) - }) - - Describe("AfterEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewAfterEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeAfterEach) - }) - - Describe("JustBeforeEach Nodes", func() { - build := func(body interface{}, timeout time.Duration, failer *Failer.Failer, componentCodeLocation types.CodeLocation) runnable { - return NewJustBeforeEachNode(body, componentCodeLocation, timeout, failer, 3) - } - - SynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach, 3) - AsynchronousSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach, 3) - InvalidSharedRunnerBehaviors(build, types.SpecComponentTypeJustBeforeEach) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go index 2ccc7dc0fb..80f16ed786 100644 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go +++ b/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go @@ -1,9 +1,10 @@ package leafnodes import ( + "time" + "github.com/onsi/ginkgo/internal/failer" "github.com/onsi/ginkgo/types" - "time" ) type SuiteNode interface { diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go deleted file mode 100644 index 246b329fe2..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes_test.go +++ /dev/null @@ -1,230 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - . "github.com/onsi/ginkgo/internal/leafnodes" - - "time" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("SuiteNodes", func() { - Describe("BeforeSuite nodes", func() { - var befSuite SuiteNode - var failer *Failer.Failer - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - - BeforeEach(func() { - failer = Failer.New() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Context("when the body passes", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - time.Sleep(10 * time.Millisecond) - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return true when run and report as passed", func() { - Ω(outcome).Should(BeTrue()) - Ω(befSuite.Passed()).Should(BeTrue()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.CodeLocation).Should(Equal(codeLocation)) - Ω(summary.State).Should(Equal(types.SpecStatePassed)) - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - Ω(summary.Failure).Should(BeZero()) - }) - }) - - Context("when the body fails", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - failer.Fail("oops", innerCodeLocation) - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("oops")) - Ω(summary.Failure.Location).Should(Equal(innerCodeLocation)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body times out", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func(done Done) { - }, codeLocation, time.Millisecond, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateTimedOut)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body panics", func() { - BeforeEach(func() { - befSuite = NewBeforeSuiteNode(func() { - panic("bam") - }, codeLocation, 0, failer) - outcome = befSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(befSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := befSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStatePanicked)) - Ω(summary.Failure.ForwardedPanic).Should(Equal("bam")) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) - - Describe("AfterSuite nodes", func() { - var aftSuite SuiteNode - var failer *Failer.Failer - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - - BeforeEach(func() { - failer = Failer.New() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - }) - - Context("when the body passes", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - time.Sleep(10 * time.Millisecond) - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return true when run and report as passed", func() { - Ω(outcome).Should(BeTrue()) - Ω(aftSuite.Passed()).Should(BeTrue()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.CodeLocation).Should(Equal(codeLocation)) - Ω(summary.State).Should(Equal(types.SpecStatePassed)) - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - Ω(summary.Failure).Should(BeZero()) - }) - }) - - Context("when the body fails", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - failer.Fail("oops", innerCodeLocation) - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("oops")) - Ω(summary.Failure.Location).Should(Equal(innerCodeLocation)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body times out", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func(done Done) { - }, codeLocation, time.Millisecond, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStateTimedOut)) - Ω(summary.Failure.ForwardedPanic).Should(BeEmpty()) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when the body panics", func() { - BeforeEach(func() { - aftSuite = NewAfterSuiteNode(func() { - panic("bam") - }, codeLocation, 0, failer) - outcome = aftSuite.Run(0, 0, "") - }) - - It("should return false when run and report as failed", func() { - Ω(outcome).Should(BeFalse()) - Ω(aftSuite.Passed()).Should(BeFalse()) - }) - - It("should have the correct summary", func() { - summary := aftSuite.Summary() - Ω(summary.State).Should(Equal(types.SpecStatePanicked)) - Ω(summary.Failure.ForwardedPanic).Should(Equal("bam")) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeAfterSuite)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go index e7030d9149..a721d0cf7f 100644 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go +++ b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go @@ -2,11 +2,12 @@ package leafnodes import ( "encoding/json" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" "io/ioutil" "net/http" "time" + + "github.com/onsi/ginkgo/internal/failer" + "github.com/onsi/ginkgo/types" ) type synchronizedAfterSuiteNode struct { diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go deleted file mode 100644 index 4266a4bce6..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node_test.go +++ /dev/null @@ -1,196 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "sync" - - "github.com/onsi/gomega/ghttp" - "net/http" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "time" -) - -var _ = Describe("SynchronizedAfterSuiteNode", func() { - var failer *Failer.Failer - var node SuiteNode - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - var server *ghttp.Server - var things []string - var lock *sync.Mutex - - BeforeEach(func() { - things = []string{} - server = ghttp.NewServer() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - failer = Failer.New() - lock = &sync.Mutex{} - }) - - AfterEach(func() { - server.Close() - }) - - newNode := func(bodyA interface{}, bodyB interface{}) SuiteNode { - return NewSynchronizedAfterSuiteNode(bodyA, bodyB, codeLocation, time.Millisecond, failer) - } - - ranThing := func(thing string) { - lock.Lock() - defer lock.Unlock() - things = append(things, thing) - } - - thingsThatRan := func() []string { - lock.Lock() - defer lock.Unlock() - return things - } - - Context("when not running in parallel", func() { - Context("when all is well", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run A, then B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("when A fails", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - failer.Fail("bam", innerCodeLocation) - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should still run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when B fails", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - failer.Fail("bam", innerCodeLocation) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run all the things", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "B"})) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - }) - - Context("when running in parallel", func() { - Context("as the first node", func() { - BeforeEach(func() { - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request1") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{false}), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request2") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{false}), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/RemoteAfterSuiteData"), - func(writer http.ResponseWriter, request *http.Request) { - ranThing("Request3") - }, - ghttp.RespondWithJSONEncoded(200, types.RemoteAfterSuiteData{true}), - )) - - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(1, 3, server.URL()) - }) - - It("should run A and, when the server says its time, run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A", "Request1", "Request2", "Request3", "B"})) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("as any other node", func() { - BeforeEach(func() { - node = newNode(func() { - ranThing("A") - }, func() { - ranThing("B") - }) - - outcome = node.Run(2, 3, server.URL()) - }) - - It("should run A, and not run B", func() { - Ω(thingsThatRan()).Should(Equal([]string{"A"})) - }) - - It("should not talk to the server", func() { - Ω(server.ReceivedRequests()).Should(BeEmpty()) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go index 76a9679813..d5c8893194 100644 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go +++ b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go @@ -3,12 +3,13 @@ package leafnodes import ( "bytes" "encoding/json" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" "io/ioutil" "net/http" "reflect" "time" + + "github.com/onsi/ginkgo/internal/failer" + "github.com/onsi/ginkgo/types" ) type synchronizedBeforeSuiteNode struct { @@ -109,8 +110,6 @@ func (node *synchronizedBeforeSuiteNode) waitForA(syncHost string) (types.SpecSt time.Sleep(50 * time.Millisecond) } - - return types.SpecStateFailed, failure("Shouldn't get here!") } func (node *synchronizedBeforeSuiteNode) Passed() bool { diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go deleted file mode 100644 index dbf2426748..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node_test.go +++ /dev/null @@ -1,445 +0,0 @@ -package leafnodes_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/leafnodes" - . "github.com/onsi/gomega" - - "github.com/onsi/gomega/ghttp" - "net/http" - - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -var _ = Describe("SynchronizedBeforeSuiteNode", func() { - var failer *Failer.Failer - var node SuiteNode - var codeLocation types.CodeLocation - var innerCodeLocation types.CodeLocation - var outcome bool - var server *ghttp.Server - - BeforeEach(func() { - server = ghttp.NewServer() - codeLocation = codelocation.New(0) - innerCodeLocation = codelocation.New(0) - failer = Failer.New() - }) - - AfterEach(func() { - server.Close() - }) - - newNode := func(bodyA interface{}, bodyB interface{}) SuiteNode { - return NewSynchronizedBeforeSuiteNode(bodyA, bodyB, codeLocation, time.Millisecond, failer) - } - - Describe("when not running in parallel", func() { - Context("when all is well", func() { - var data []byte - BeforeEach(func() { - data = nil - - node = newNode(func() []byte { - return []byte("my data") - }, func(d []byte) { - data = d - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should run A, then B passing the output from A to B", func() { - Ω(data).Should(Equal([]byte("my data"))) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - Ω(node.Summary().State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Context("when A fails", func() { - var ranB bool - BeforeEach(func() { - ranB = false - node = newNode(func() []byte { - failer.Fail("boom", innerCodeLocation) - return nil - }, func([]byte) { - ranB = true - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when B fails", func() { - BeforeEach(func() { - node = newNode(func() []byte { - return nil - }, func([]byte) { - failer.Fail("boom", innerCodeLocation) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateFailed)) - }) - }) - - Context("when A times out", func() { - var ranB bool - BeforeEach(func() { - ranB = false - node = newNode(func(Done) []byte { - time.Sleep(time.Second) - return nil - }, func([]byte) { - ranB = true - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateTimedOut)) - }) - }) - - Context("when B times out", func() { - BeforeEach(func() { - node = newNode(func() []byte { - return nil - }, func([]byte, Done) { - time.Sleep(time.Second) - }) - - outcome = node.Run(1, 1, server.URL()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - Ω(node.Summary().State).Should(Equal(types.SpecStateTimedOut)) - }) - }) - }) - - Describe("when running in parallel", func() { - var ranB bool - var parallelNode, parallelTotal int - BeforeEach(func() { - ranB = false - parallelNode, parallelTotal = 1, 3 - }) - - Context("as the first node, it runs A", func() { - var expectedState types.RemoteBeforeSuiteData - - BeforeEach(func() { - parallelNode, parallelTotal = 1, 3 - }) - - JustBeforeEach(func() { - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("POST", "/BeforeSuiteState"), - ghttp.VerifyJSONRepresenting(expectedState), - )) - - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - Context("when A succeeds", func() { - BeforeEach(func() { - expectedState = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStatePassed} - - node = newNode(func() []byte { - return []byte("my data") - }, func([]byte) { - ranB = true - }) - }) - - It("should post about A succeeding", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(1)) - }) - - It("should run B", func() { - Ω(ranB).Should(BeTrue()) - }) - - It("should report success", func() { - Ω(outcome).Should(BeTrue()) - }) - }) - - Context("when A fails", func() { - BeforeEach(func() { - expectedState = types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateFailed} - - node = newNode(func() []byte { - panic("BAM") - return []byte("my data") - }, func([]byte) { - ranB = true - }) - }) - - It("should post about A failing", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(1)) - }) - - It("should not run B", func() { - Ω(ranB).Should(BeFalse()) - }) - - It("should report failure", func() { - Ω(outcome).Should(BeFalse()) - }) - }) - }) - - Context("as the Nth node", func() { - var statusCode int - var response interface{} - var ranA bool - var bData []byte - - BeforeEach(func() { - ranA = false - bData = nil - - statusCode = http.StatusOK - - server.AppendHandlers(ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWith(http.StatusOK, string((types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}).ToJSON())), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWith(http.StatusOK, string((types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}).ToJSON())), - ), ghttp.CombineHandlers( - ghttp.VerifyRequest("GET", "/BeforeSuiteState"), - ghttp.RespondWithJSONEncodedPtr(&statusCode, &response), - )) - - node = newNode(func() []byte { - ranA = true - return nil - }, func(data []byte) { - bData = data - }) - - parallelNode, parallelTotal = 2, 3 - }) - - Context("when A on node1 succeeds", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStatePassed} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should run B when the polling succeeds", func() { - Ω(bData).Should(Equal([]byte("my data"))) - }) - - It("should succeed", func() { - Ω(outcome).Should(BeTrue()) - Ω(node.Passed()).Should(BeTrue()) - }) - }) - - Context("when A on node1 fails", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStateFailed} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should not run B", func() { - Ω(bData).Should(BeNil()) - }) - - It("should fail", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - - summary := node.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("BeforeSuite on Node 1 failed")) - Ω(summary.Failure.Location).Should(Equal(codeLocation)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - - Context("when node1 disappears", func() { - BeforeEach(func() { - response = types.RemoteBeforeSuiteData{[]byte("my data"), types.RemoteBeforeSuiteStateDisappeared} - outcome = node.Run(parallelNode, parallelTotal, server.URL()) - }) - - It("should not run A", func() { - Ω(ranA).Should(BeFalse()) - }) - - It("should poll for A", func() { - Ω(server.ReceivedRequests()).Should(HaveLen(3)) - }) - - It("should not run B", func() { - Ω(bData).Should(BeNil()) - }) - - It("should fail", func() { - Ω(outcome).Should(BeFalse()) - Ω(node.Passed()).Should(BeFalse()) - - summary := node.Summary() - Ω(summary.State).Should(Equal(types.SpecStateFailed)) - Ω(summary.Failure.Message).Should(Equal("Node 1 disappeared before completing BeforeSuite")) - Ω(summary.Failure.Location).Should(Equal(codeLocation)) - Ω(summary.Failure.ComponentType).Should(Equal(types.SpecComponentTypeBeforeSuite)) - Ω(summary.Failure.ComponentIndex).Should(Equal(0)) - Ω(summary.Failure.ComponentCodeLocation).Should(Equal(codeLocation)) - }) - }) - }) - }) - - Describe("construction", func() { - Describe("the first function", func() { - Context("when the first function returns a byte array", func() { - Context("and takes nothing", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("and takes a done function", func() { - It("should be fine", func() { - Ω(func() { - newNode(func(Done) []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("and takes more than one thing", func() { - It("should panic", func() { - Ω(func() { - newNode(func(Done, Done) []byte { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - - Context("and takes something else", func() { - It("should panic", func() { - Ω(func() { - newNode(func(bool) []byte { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - }) - - Context("when the first function does not return a byte array", func() { - It("should panic", func() { - Ω(func() { - newNode(func() {}, func([]byte) {}) - }).Should(Panic()) - - Ω(func() { - newNode(func() []int { return nil }, func([]byte) {}) - }).Should(Panic()) - }) - }) - }) - - Describe("the second function", func() { - Context("when the second function takes a byte array", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("when it also takes a done channel", func() { - It("should be fine", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte, Done) {}) - }).ShouldNot(Panic()) - }) - }) - - Context("if it takes anything else", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte, chan bool) {}) - }).Should(Panic()) - - Ω(func() { - newNode(func() []byte { return nil }, func(string) {}) - }).Should(Panic()) - }) - }) - - Context("if it takes nothing at all", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func() {}) - }).Should(Panic()) - }) - }) - - Context("if it returns something", func() { - It("should panic", func() { - Ω(func() { - newNode(func() []byte { return nil }, func([]byte) []byte { return nil }) - }).Should(Panic()) - }) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go b/vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go index 522d44e357..6b54afe014 100644 --- a/vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go +++ b/vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go @@ -207,7 +207,7 @@ func (aggregator *Aggregator) announceSpec(specSummary *types.SpecSummary) { case types.SpecStatePending: aggregator.stenographer.AnnouncePendingSpec(specSummary, aggregator.config.NoisyPendings && !aggregator.config.Succinct) case types.SpecStateSkipped: - aggregator.stenographer.AnnounceSkippedSpec(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) + aggregator.stenographer.AnnounceSkippedSpec(specSummary, aggregator.config.Succinct || !aggregator.config.NoisySkippings, aggregator.config.FullTrace) case types.SpecStateTimedOut: aggregator.stenographer.AnnounceSpecTimedOut(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) case types.SpecStatePanicked: diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/aggregator_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/aggregator_test.go deleted file mode 100644 index aedf939278..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/aggregator_test.go +++ /dev/null @@ -1,315 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "time" - - "github.com/onsi/ginkgo/config" - . "github.com/onsi/ginkgo/internal/remote" - st "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Aggregator", func() { - var ( - aggregator *Aggregator - reporterConfig config.DefaultReporterConfigType - stenographer *st.FakeStenographer - result chan bool - - ginkgoConfig1 config.GinkgoConfigType - ginkgoConfig2 config.GinkgoConfigType - - suiteSummary1 *types.SuiteSummary - suiteSummary2 *types.SuiteSummary - - beforeSummary *types.SetupSummary - afterSummary *types.SetupSummary - specSummary *types.SpecSummary - - suiteDescription string - ) - - BeforeEach(func() { - reporterConfig = config.DefaultReporterConfigType{ - NoColor: false, - SlowSpecThreshold: 0.1, - NoisyPendings: true, - Succinct: false, - Verbose: true, - } - stenographer = st.NewFakeStenographer() - result = make(chan bool, 1) - aggregator = NewAggregator(2, result, reporterConfig, stenographer) - - // - // now set up some fixture data - // - - ginkgoConfig1 = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - ParallelNode: 1, - ParallelTotal: 2, - } - - ginkgoConfig2 = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - ParallelNode: 2, - ParallelTotal: 2, - } - - suiteDescription = "My Parallel Suite" - - suiteSummary1 = &types.SuiteSummary{ - SuiteDescription: suiteDescription, - - NumberOfSpecsBeforeParallelization: 30, - NumberOfTotalSpecs: 17, - NumberOfSpecsThatWillBeRun: 15, - NumberOfPendingSpecs: 1, - NumberOfSkippedSpecs: 1, - } - - suiteSummary2 = &types.SuiteSummary{ - SuiteDescription: suiteDescription, - - NumberOfSpecsBeforeParallelization: 30, - NumberOfTotalSpecs: 13, - NumberOfSpecsThatWillBeRun: 8, - NumberOfPendingSpecs: 2, - NumberOfSkippedSpecs: 3, - } - - beforeSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - CapturedOutput: "BeforeSuiteOutput", - } - - afterSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - CapturedOutput: "AfterSuiteOutput", - } - - specSummary = &types.SpecSummary{ - State: types.SpecStatePassed, - CapturedOutput: "SpecOutput", - } - }) - - call := func(method string, args ...interface{}) st.FakeStenographerCall { - return st.NewFakeStenographerCall(method, args...) - } - - beginSuite := func() { - stenographer.Reset() - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - aggregator.SpecSuiteWillBegin(ginkgoConfig1, suiteSummary1) - Eventually(func() interface{} { - return len(stenographer.Calls()) - }).Should(BeNumerically(">=", 3)) - } - - Describe("Announcing the beginning of the suite", func() { - Context("When one of the parallel-suites starts", func() { - BeforeEach(func() { - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - }) - - It("should be silent", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - }) - - Context("once all of the parallel-suites have started", func() { - BeforeEach(func() { - aggregator.SpecSuiteWillBegin(ginkgoConfig2, suiteSummary2) - aggregator.SpecSuiteWillBegin(ginkgoConfig1, suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(3)) - }) - - It("should announce the beginning of the suite", func() { - Ω(stenographer.Calls()).Should(HaveLen(3)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", suiteDescription, ginkgoConfig1.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceTotalNumberOfSpecs", 30, false))) - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceAggregatedParallelRun", 2, false))) - }) - }) - }) - - Describe("Announcing specs and before suites", func() { - Context("when the parallel-suites have not all started", func() { - BeforeEach(func() { - aggregator.BeforeSuiteDidRun(beforeSummary) - aggregator.AfterSuiteDidRun(afterSummary) - aggregator.SpecDidComplete(specSummary) - }) - - It("should not announce any specs", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - - Context("when the parallel-suites subsequently start", func() { - BeforeEach(func() { - beginSuite() - }) - - It("should announce the specs, the before suites and the after suites", func() { - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(ContainElement(call("AnnounceSuccesfulSpec", specSummary))) - - Ω(stenographer.Calls()).Should(ContainElement(call("AnnounceCapturedOutput", beforeSummary.CapturedOutput))) - Ω(stenographer.Calls()).Should(ContainElement(call("AnnounceCapturedOutput", afterSummary.CapturedOutput))) - }) - }) - }) - - Context("When the parallel-suites have all started", func() { - BeforeEach(func() { - beginSuite() - stenographer.Reset() - }) - - Context("When a spec completes", func() { - BeforeEach(func() { - aggregator.BeforeSuiteDidRun(beforeSummary) - aggregator.SpecDidComplete(specSummary) - aggregator.AfterSuiteDidRun(afterSummary) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(5)) - }) - - It("should announce the captured output of the BeforeSuite", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceCapturedOutput", beforeSummary.CapturedOutput))) - }) - - It("should announce that the spec will run (when in verbose mode)", func() { - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceSpecWillRun", specSummary))) - }) - - It("should announce the captured stdout of the spec", func() { - Ω(stenographer.Calls()[2]).Should(Equal(call("AnnounceCapturedOutput", specSummary.CapturedOutput))) - }) - - It("should announce completion", func() { - Ω(stenographer.Calls()[3]).Should(Equal(call("AnnounceSuccesfulSpec", specSummary))) - }) - - It("should announce the captured output of the AfterSuite", func() { - Ω(stenographer.Calls()[4]).Should(Equal(call("AnnounceCapturedOutput", afterSummary.CapturedOutput))) - }) - }) - }) - }) - - Describe("Announcing the end of the suite", func() { - BeforeEach(func() { - beginSuite() - stenographer.Reset() - }) - - Context("When one of the parallel-suites ends", func() { - BeforeEach(func() { - aggregator.SpecSuiteDidEnd(suiteSummary2) - }) - - It("should be silent", func() { - Consistently(func() interface{} { return stenographer.Calls() }).Should(BeEmpty()) - }) - - It("should not notify the channel", func() { - Ω(result).Should(BeEmpty()) - }) - }) - - Context("once all of the parallel-suites end", func() { - BeforeEach(func() { - time.Sleep(200 * time.Millisecond) - - suiteSummary1.SuiteSucceeded = true - suiteSummary1.NumberOfPassedSpecs = 15 - suiteSummary1.NumberOfFailedSpecs = 0 - suiteSummary1.NumberOfFlakedSpecs = 3 - suiteSummary2.SuiteSucceeded = false - suiteSummary2.NumberOfPassedSpecs = 5 - suiteSummary2.NumberOfFailedSpecs = 3 - suiteSummary2.NumberOfFlakedSpecs = 4 - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should announce the end of the suite", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeFalse()) - Ω(compositeSummary.NumberOfSpecsThatWillBeRun).Should(Equal(23)) - Ω(compositeSummary.NumberOfTotalSpecs).Should(Equal(30)) - Ω(compositeSummary.NumberOfPassedSpecs).Should(Equal(20)) - Ω(compositeSummary.NumberOfFailedSpecs).Should(Equal(3)) - Ω(compositeSummary.NumberOfPendingSpecs).Should(Equal(3)) - Ω(compositeSummary.NumberOfSkippedSpecs).Should(Equal(4)) - Ω(compositeSummary.NumberOfFlakedSpecs).Should(Equal(7)) - Ω(compositeSummary.RunTime.Seconds()).Should(BeNumerically(">", 0.2)) - }) - }) - - Context("when all the parallel-suites pass", func() { - BeforeEach(func() { - suiteSummary1.SuiteSucceeded = true - suiteSummary2.SuiteSucceeded = true - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should report success", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeTrue()) - }) - - It("should notify the channel that it succeded", func(done Done) { - Ω(<-result).Should(BeTrue()) - close(done) - }) - }) - - Context("when one of the parallel-suites fails", func() { - BeforeEach(func() { - suiteSummary1.SuiteSucceeded = true - suiteSummary2.SuiteSucceeded = false - - aggregator.SpecSuiteDidEnd(suiteSummary2) - aggregator.SpecSuiteDidEnd(suiteSummary1) - Eventually(func() interface{} { - return stenographer.Calls() - }).Should(HaveLen(2)) - }) - - It("should report failure", func() { - compositeSummary := stenographer.Calls()[1].Args[0].(*types.SuiteSummary) - - Ω(compositeSummary.SuiteSucceeded).Should(BeFalse()) - }) - - It("should notify the channel that it failed", func(done Done) { - Ω(<-result).Should(BeFalse()) - close(done) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go deleted file mode 100644 index a928f93d31..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/fake_output_interceptor_test.go +++ /dev/null @@ -1,17 +0,0 @@ -package remote_test - -type fakeOutputInterceptor struct { - DidStartInterceptingOutput bool - DidStopInterceptingOutput bool - InterceptedOutput string -} - -func (interceptor *fakeOutputInterceptor) StartInterceptingOutput() error { - interceptor.DidStartInterceptingOutput = true - return nil -} - -func (interceptor *fakeOutputInterceptor) StopInterceptingAndReturnOutput() (string, error) { - interceptor.DidStopInterceptingOutput = true - return interceptor.InterceptedOutput, nil -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go deleted file mode 100644 index 3543c59c64..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/fake_poster_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package remote_test - -import ( - "io" - "io/ioutil" - "net/http" -) - -type post struct { - url string - bodyType string - bodyContent []byte -} - -type fakePoster struct { - posts []post -} - -func newFakePoster() *fakePoster { - return &fakePoster{ - posts: make([]post, 0), - } -} - -func (poster *fakePoster) Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) { - bodyContent, _ := ioutil.ReadAll(body) - poster.posts = append(poster.posts, post{ - url: url, - bodyType: bodyType, - bodyContent: bodyContent, - }) - return nil, nil -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go deleted file mode 100644 index e5f3b1e307..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter_test.go +++ /dev/null @@ -1,180 +0,0 @@ -package remote_test - -import ( - "encoding/json" - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - . "github.com/onsi/ginkgo/internal/remote" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("ForwardingReporter", func() { - var ( - reporter *ForwardingReporter - interceptor *fakeOutputInterceptor - poster *fakePoster - suiteSummary *types.SuiteSummary - specSummary *types.SpecSummary - setupSummary *types.SetupSummary - serverHost string - ) - - BeforeEach(func() { - serverHost = "http://127.0.0.1:7788" - - poster = newFakePoster() - - interceptor = &fakeOutputInterceptor{ - InterceptedOutput: "The intercepted output!", - } - - reporter = NewForwardingReporter(serverHost, poster, interceptor) - - suiteSummary = &types.SuiteSummary{ - SuiteDescription: "My Test Suite", - } - - setupSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - } - - specSummary = &types.SpecSummary{ - ComponentTexts: []string{"My", "Spec"}, - State: types.SpecStatePassed, - } - }) - - Context("When a suite begins", func() { - BeforeEach(func() { - reporter.SpecSuiteWillBegin(config.GinkgoConfig, suiteSummary) - }) - - It("should start intercepting output", func() { - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SuiteSummary and Ginkgo Config to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecSuiteWillBegin")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var sentData struct { - SentConfig config.GinkgoConfigType `json:"config"` - SentSuiteSummary *types.SuiteSummary `json:"suite-summary"` - } - - err := json.Unmarshal(poster.posts[0].bodyContent, &sentData) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(sentData.SentConfig).Should(Equal(config.GinkgoConfig)) - Ω(sentData.SentSuiteSummary).Should(Equal(suiteSummary)) - }) - }) - - Context("when a BeforeSuite completes", func() { - BeforeEach(func() { - reporter.BeforeSuiteDidRun(setupSummary) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SetupSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/BeforeSuiteDidRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SetupSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - setupSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(setupSummary)) - }) - }) - - Context("when an AfterSuite completes", func() { - BeforeEach(func() { - reporter.AfterSuiteDidRun(setupSummary) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - - It("should POST the SetupSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/AfterSuiteDidRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SetupSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - setupSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(setupSummary)) - }) - }) - - Context("When a spec will run", func() { - BeforeEach(func() { - reporter.SpecWillRun(specSummary) - }) - - It("should POST the SpecSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecWillRun")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SpecSummary - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - Ω(summary).Should(Equal(specSummary)) - }) - - Context("When a spec completes", func() { - BeforeEach(func() { - specSummary.State = types.SpecStatePanicked - reporter.SpecDidComplete(specSummary) - }) - - It("should POST the SpecSummary to the Ginkgo server and include any intercepted output", func() { - Ω(poster.posts).Should(HaveLen(2)) - Ω(poster.posts[1].url).Should(Equal("http://127.0.0.1:7788/SpecDidComplete")) - Ω(poster.posts[1].bodyType).Should(Equal("application/json")) - - var summary *types.SpecSummary - err := json.Unmarshal(poster.posts[1].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - specSummary.CapturedOutput = interceptor.InterceptedOutput - Ω(summary).Should(Equal(specSummary)) - }) - - It("should stop, then start intercepting output", func() { - Ω(interceptor.DidStopInterceptingOutput).Should(BeTrue()) - Ω(interceptor.DidStartInterceptingOutput).Should(BeTrue()) - }) - }) - }) - - Context("When a suite ends", func() { - BeforeEach(func() { - reporter.SpecSuiteDidEnd(suiteSummary) - }) - - It("should POST the SuiteSummary to the Ginkgo server", func() { - Ω(poster.posts).Should(HaveLen(1)) - Ω(poster.posts[0].url).Should(Equal("http://127.0.0.1:7788/SpecSuiteDidEnd")) - Ω(poster.posts[0].bodyType).Should(Equal("application/json")) - - var summary *types.SuiteSummary - - err := json.Unmarshal(poster.posts[0].bodyContent, &summary) - Ω(err).ShouldNot(HaveOccurred()) - - Ω(summary).Should(Equal(suiteSummary)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go deleted file mode 100644 index e6b4e9f32c..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/remote_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestRemote(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Remote Spec Forwarding Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/server.go b/vendor/github.com/onsi/ginkgo/internal/remote/server.go index 297af2ebff..367c54daff 100644 --- a/vendor/github.com/onsi/ginkgo/internal/remote/server.go +++ b/vendor/github.com/onsi/ginkgo/internal/remote/server.go @@ -45,7 +45,7 @@ func NewServer(parallelTotal int) (*Server, error) { listener: listener, lock: &sync.Mutex{}, alives: make([]func() bool, parallelTotal), - beforeSuiteData: types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}, + beforeSuiteData: types.RemoteBeforeSuiteData{Data: nil, State: types.RemoteBeforeSuiteStatePending}, parallelTotal: parallelTotal, }, nil } diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/server_test.go b/vendor/github.com/onsi/ginkgo/internal/remote/server_test.go deleted file mode 100644 index eb2eefebe0..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/server_test.go +++ /dev/null @@ -1,269 +0,0 @@ -package remote_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/remote" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - - "bytes" - "encoding/json" - "net/http" -) - -var _ = Describe("Server", func() { - var ( - server *Server - ) - - BeforeEach(func() { - var err error - server, err = NewServer(3) - Ω(err).ShouldNot(HaveOccurred()) - - server.Start() - }) - - AfterEach(func() { - server.Close() - }) - - Describe("Streaming endpoints", func() { - var ( - reporterA, reporterB *reporters.FakeReporter - forwardingReporter *ForwardingReporter - - suiteSummary *types.SuiteSummary - setupSummary *types.SetupSummary - specSummary *types.SpecSummary - ) - - BeforeEach(func() { - reporterA = reporters.NewFakeReporter() - reporterB = reporters.NewFakeReporter() - - server.RegisterReporters(reporterA, reporterB) - - forwardingReporter = NewForwardingReporter(server.Address(), &http.Client{}, &fakeOutputInterceptor{}) - - suiteSummary = &types.SuiteSummary{ - SuiteDescription: "My Test Suite", - } - - setupSummary = &types.SetupSummary{ - State: types.SpecStatePassed, - } - - specSummary = &types.SpecSummary{ - ComponentTexts: []string{"My", "Spec"}, - State: types.SpecStatePassed, - } - }) - - It("should make its address available", func() { - Ω(server.Address()).Should(MatchRegexp(`http://127.0.0.1:\d{2,}`)) - }) - - Describe("/SpecSuiteWillBegin", func() { - It("should decode and forward the Ginkgo config and suite summary", func(done Done) { - forwardingReporter.SpecSuiteWillBegin(config.GinkgoConfig, suiteSummary) - Ω(reporterA.Config).Should(Equal(config.GinkgoConfig)) - Ω(reporterB.Config).Should(Equal(config.GinkgoConfig)) - Ω(reporterA.BeginSummary).Should(Equal(suiteSummary)) - Ω(reporterB.BeginSummary).Should(Equal(suiteSummary)) - close(done) - }) - }) - - Describe("/BeforeSuiteDidRun", func() { - It("should decode and forward the setup summary", func() { - forwardingReporter.BeforeSuiteDidRun(setupSummary) - Ω(reporterA.BeforeSuiteSummary).Should(Equal(setupSummary)) - Ω(reporterB.BeforeSuiteSummary).Should(Equal(setupSummary)) - }) - }) - - Describe("/AfterSuiteDidRun", func() { - It("should decode and forward the setup summary", func() { - forwardingReporter.AfterSuiteDidRun(setupSummary) - Ω(reporterA.AfterSuiteSummary).Should(Equal(setupSummary)) - Ω(reporterB.AfterSuiteSummary).Should(Equal(setupSummary)) - }) - }) - - Describe("/SpecWillRun", func() { - It("should decode and forward the spec summary", func(done Done) { - forwardingReporter.SpecWillRun(specSummary) - Ω(reporterA.SpecWillRunSummaries[0]).Should(Equal(specSummary)) - Ω(reporterB.SpecWillRunSummaries[0]).Should(Equal(specSummary)) - close(done) - }) - }) - - Describe("/SpecDidComplete", func() { - It("should decode and forward the spec summary", func(done Done) { - forwardingReporter.SpecDidComplete(specSummary) - Ω(reporterA.SpecSummaries[0]).Should(Equal(specSummary)) - Ω(reporterB.SpecSummaries[0]).Should(Equal(specSummary)) - close(done) - }) - }) - - Describe("/SpecSuiteDidEnd", func() { - It("should decode and forward the suite summary", func(done Done) { - forwardingReporter.SpecSuiteDidEnd(suiteSummary) - Ω(reporterA.EndSummary).Should(Equal(suiteSummary)) - Ω(reporterB.EndSummary).Should(Equal(suiteSummary)) - close(done) - }) - }) - }) - - Describe("Synchronization endpoints", func() { - Describe("GETting and POSTing BeforeSuiteState", func() { - getBeforeSuite := func() types.RemoteBeforeSuiteData { - resp, err := http.Get(server.Address() + "/BeforeSuiteState") - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - - r := types.RemoteBeforeSuiteData{} - decoder := json.NewDecoder(resp.Body) - err = decoder.Decode(&r) - Ω(err).ShouldNot(HaveOccurred()) - - return r - } - - postBeforeSuite := func(r types.RemoteBeforeSuiteData) { - resp, err := http.Post(server.Address()+"/BeforeSuiteState", "application/json", bytes.NewReader(r.ToJSON())) - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - } - - Context("when the first node's Alive has not been registered yet", func() { - It("should return pending", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - }) - }) - - Context("when the first node is Alive but has not responded yet", func() { - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return true - }) - }) - - It("should return pending", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending})) - }) - }) - - Context("when the first node has responded", func() { - var state types.RemoteBeforeSuiteData - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return false - }) - - state = types.RemoteBeforeSuiteData{ - Data: []byte("my data"), - State: types.RemoteBeforeSuiteStatePassed, - } - postBeforeSuite(state) - }) - - It("should return the passed in state", func() { - returnedState := getBeforeSuite() - Ω(returnedState).Should(Equal(state)) - }) - }) - - Context("when the first node is no longer Alive and has not responded yet", func() { - BeforeEach(func() { - server.RegisterAlive(1, func() bool { - return false - }) - }) - - It("should return disappeared", func() { - state := getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateDisappeared})) - - state = getBeforeSuite() - Ω(state).Should(Equal(types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStateDisappeared})) - }) - }) - }) - - Describe("GETting RemoteAfterSuiteData", func() { - getRemoteAfterSuiteData := func() bool { - resp, err := http.Get(server.Address() + "/RemoteAfterSuiteData") - Ω(err).ShouldNot(HaveOccurred()) - Ω(resp.StatusCode).Should(Equal(http.StatusOK)) - - a := types.RemoteAfterSuiteData{} - decoder := json.NewDecoder(resp.Body) - err = decoder.Decode(&a) - Ω(err).ShouldNot(HaveOccurred()) - - return a.CanRun - } - - Context("when there are unregistered nodes", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return false - }) - }) - - It("should return false", func() { - Ω(getRemoteAfterSuiteData()).Should(BeFalse()) - }) - }) - - Context("when all none-node-1 nodes are still running", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return true - }) - - server.RegisterAlive(3, func() bool { - return false - }) - }) - - It("should return false", func() { - Ω(getRemoteAfterSuiteData()).Should(BeFalse()) - }) - }) - - Context("when all none-1 nodes are done", func() { - BeforeEach(func() { - server.RegisterAlive(2, func() bool { - return false - }) - - server.RegisterAlive(3, func() bool { - return false - }) - }) - - It("should return true", func() { - Ω(getRemoteAfterSuiteData()).Should(BeTrue()) - }) - - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go index 5c59728ea9..9550d37b36 100644 --- a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go +++ b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go @@ -8,4 +8,4 @@ import "syscall" // use the nearly identical syscall.Dup3 instead func syscallDup(oldfd int, newfd int) (err error) { return syscall.Dup3(oldfd, newfd, 0) -} \ No newline at end of file +} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go index ecf9cafb66..75ef7fb78e 100644 --- a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go +++ b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go @@ -6,4 +6,4 @@ import "golang.org/x/sys/unix" func syscallDup(oldfd int, newfd int) (err error) { return unix.Dup2(oldfd, newfd) -} \ No newline at end of file +} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go index cacdd0e649..ef62559600 100644 --- a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go +++ b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go @@ -8,4 +8,4 @@ import "syscall" func syscallDup(oldfd int, newfd int) (err error) { return syscall.Dup2(oldfd, newfd) -} \ No newline at end of file +} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/spec.go b/vendor/github.com/onsi/ginkgo/internal/spec/spec.go index d32dec6997..77b23a4c77 100644 --- a/vendor/github.com/onsi/ginkgo/internal/spec/spec.go +++ b/vendor/github.com/onsi/ginkgo/internal/spec/spec.go @@ -5,6 +5,8 @@ import ( "io" "time" + "sync" + "github.com/onsi/ginkgo/internal/containernode" "github.com/onsi/ginkgo/internal/leafnodes" "github.com/onsi/ginkgo/types" @@ -19,8 +21,11 @@ type Spec struct { state types.SpecState runTime time.Duration + startTime time.Time failure types.SpecFailure previousFailures bool + + stateMutex *sync.Mutex } func New(subject leafnodes.SubjectNode, containers []*containernode.ContainerNode, announceProgress bool) *Spec { @@ -29,6 +34,7 @@ func New(subject leafnodes.SubjectNode, containers []*containernode.ContainerNod containers: containers, focused: subject.Flag() == types.FlagTypeFocused, announceProgress: announceProgress, + stateMutex: &sync.Mutex{}, } spec.processFlag(subject.Flag()) @@ -43,32 +49,32 @@ func (spec *Spec) processFlag(flag types.FlagType) { if flag == types.FlagTypeFocused { spec.focused = true } else if flag == types.FlagTypePending { - spec.state = types.SpecStatePending + spec.setState(types.SpecStatePending) } } func (spec *Spec) Skip() { - spec.state = types.SpecStateSkipped + spec.setState(types.SpecStateSkipped) } func (spec *Spec) Failed() bool { - return spec.state == types.SpecStateFailed || spec.state == types.SpecStatePanicked || spec.state == types.SpecStateTimedOut + return spec.getState() == types.SpecStateFailed || spec.getState() == types.SpecStatePanicked || spec.getState() == types.SpecStateTimedOut } func (spec *Spec) Passed() bool { - return spec.state == types.SpecStatePassed + return spec.getState() == types.SpecStatePassed } func (spec *Spec) Flaked() bool { - return spec.state == types.SpecStatePassed && spec.previousFailures + return spec.getState() == types.SpecStatePassed && spec.previousFailures } func (spec *Spec) Pending() bool { - return spec.state == types.SpecStatePending + return spec.getState() == types.SpecStatePending } func (spec *Spec) Skipped() bool { - return spec.state == types.SpecStateSkipped + return spec.getState() == types.SpecStateSkipped } func (spec *Spec) Focused() bool { @@ -91,13 +97,18 @@ func (spec *Spec) Summary(suiteID string) *types.SpecSummary { componentTexts[len(spec.containers)] = spec.subject.Text() componentCodeLocations[len(spec.containers)] = spec.subject.CodeLocation() + runTime := spec.runTime + if runTime == 0 && !spec.startTime.IsZero() { + runTime = time.Since(spec.startTime) + } + return &types.SpecSummary{ IsMeasurement: spec.IsMeasurement(), NumberOfSamples: spec.subject.Samples(), ComponentTexts: componentTexts, ComponentCodeLocations: componentCodeLocations, - State: spec.state, - RunTime: spec.runTime, + State: spec.getState(), + RunTime: runTime, Failure: spec.failure, Measurements: spec.measurementsReport(), SuiteID: suiteID, @@ -114,26 +125,38 @@ func (spec *Spec) ConcatenatedString() string { } func (spec *Spec) Run(writer io.Writer) { - if spec.state == types.SpecStateFailed { + if spec.getState() == types.SpecStateFailed { spec.previousFailures = true } - startTime := time.Now() + spec.startTime = time.Now() defer func() { - spec.runTime = time.Since(startTime) + spec.runTime = time.Since(spec.startTime) }() for sample := 0; sample < spec.subject.Samples(); sample++ { spec.runSample(sample, writer) - if spec.state != types.SpecStatePassed { + if spec.getState() != types.SpecStatePassed { return } } } +func (spec *Spec) getState() types.SpecState { + spec.stateMutex.Lock() + defer spec.stateMutex.Unlock() + return spec.state +} + +func (spec *Spec) setState(state types.SpecState) { + spec.stateMutex.Lock() + defer spec.stateMutex.Unlock() + spec.state = state +} + func (spec *Spec) runSample(sample int, writer io.Writer) { - spec.state = types.SpecStatePassed + spec.setState(types.SpecStatePassed) spec.failure = types.SpecFailure{} innerMostContainerIndexToUnwind := -1 @@ -143,8 +166,8 @@ func (spec *Spec) runSample(sample int, writer io.Writer) { for _, afterEach := range container.SetupNodesOfType(types.SpecComponentTypeAfterEach) { spec.announceSetupNode(writer, "AfterEach", container, afterEach) afterEachState, afterEachFailure := afterEach.Run() - if afterEachState != types.SpecStatePassed && spec.state == types.SpecStatePassed { - spec.state = afterEachState + if afterEachState != types.SpecStatePassed && spec.getState() == types.SpecStatePassed { + spec.setState(afterEachState) spec.failure = afterEachFailure } } @@ -155,8 +178,10 @@ func (spec *Spec) runSample(sample int, writer io.Writer) { innerMostContainerIndexToUnwind = i for _, beforeEach := range container.SetupNodesOfType(types.SpecComponentTypeBeforeEach) { spec.announceSetupNode(writer, "BeforeEach", container, beforeEach) - spec.state, spec.failure = beforeEach.Run() - if spec.state != types.SpecStatePassed { + s, f := beforeEach.Run() + spec.failure = f + spec.setState(s) + if spec.getState() != types.SpecStatePassed { return } } @@ -165,15 +190,19 @@ func (spec *Spec) runSample(sample int, writer io.Writer) { for _, container := range spec.containers { for _, justBeforeEach := range container.SetupNodesOfType(types.SpecComponentTypeJustBeforeEach) { spec.announceSetupNode(writer, "JustBeforeEach", container, justBeforeEach) - spec.state, spec.failure = justBeforeEach.Run() - if spec.state != types.SpecStatePassed { + s, f := justBeforeEach.Run() + spec.failure = f + spec.setState(s) + if spec.getState() != types.SpecStatePassed { return } } } spec.announceSubject(writer, spec.subject) - spec.state, spec.failure = spec.subject.Run() + s, f := spec.subject.Run() + spec.failure = f + spec.setState(s) } func (spec *Spec) announceSetupNode(writer io.Writer, nodeType string, container *containernode.ContainerNode, setupNode leafnodes.BasicNode) { diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go deleted file mode 100644 index 8681a72068..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/spec_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package spec_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestSpec(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Spec Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/spec_test.go b/vendor/github.com/onsi/ginkgo/internal/spec/spec_test.go deleted file mode 100644 index 3bab8887cd..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/spec_test.go +++ /dev/null @@ -1,657 +0,0 @@ -package spec_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo/internal/spec" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -var noneFlag = types.FlagTypeNone -var focusedFlag = types.FlagTypeFocused -var pendingFlag = types.FlagTypePending - -var _ = Describe("Spec", func() { - var ( - failer *Failer.Failer - codeLocation types.CodeLocation - nodesThatRan []string - spec *Spec - buffer *gbytes.Buffer - ) - - newBody := func(text string, fail bool) func() { - return func() { - nodesThatRan = append(nodesThatRan, text) - if fail { - failer.Fail(text, codeLocation) - } - } - } - - newIt := func(text string, flag types.FlagType, fail bool) *leafnodes.ItNode { - return leafnodes.NewItNode(text, newBody(text, fail), flag, codeLocation, 0, failer, 0) - } - - newItWithBody := func(text string, body interface{}) *leafnodes.ItNode { - return leafnodes.NewItNode(text, body, noneFlag, codeLocation, 0, failer, 0) - } - - newMeasure := func(text string, flag types.FlagType, fail bool, samples int) *leafnodes.MeasureNode { - return leafnodes.NewMeasureNode(text, func(Benchmarker) { - nodesThatRan = append(nodesThatRan, text) - if fail { - failer.Fail(text, codeLocation) - } - }, flag, codeLocation, samples, failer, 0) - } - - newBef := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewBeforeEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newAft := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewAfterEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newJusBef := func(text string, fail bool) leafnodes.BasicNode { - return leafnodes.NewJustBeforeEachNode(newBody(text, fail), codeLocation, 0, failer, 0) - } - - newContainer := func(text string, flag types.FlagType, setupNodes ...leafnodes.BasicNode) *containernode.ContainerNode { - c := containernode.New(text, flag, codeLocation) - for _, node := range setupNodes { - c.PushSetupNode(node) - } - return c - } - - containers := func(containers ...*containernode.ContainerNode) []*containernode.ContainerNode { - return containers - } - - BeforeEach(func() { - buffer = gbytes.NewBuffer() - failer = Failer.New() - codeLocation = codelocation.New(0) - nodesThatRan = []string{} - }) - - Describe("marking specs focused and pending", func() { - It("should satisfy various caes", func() { - cases := []struct { - ContainerFlags []types.FlagType - SubjectFlag types.FlagType - Pending bool - Focused bool - }{ - {[]types.FlagType{}, noneFlag, false, false}, - {[]types.FlagType{}, focusedFlag, false, true}, - {[]types.FlagType{}, pendingFlag, true, false}, - {[]types.FlagType{noneFlag}, noneFlag, false, false}, - {[]types.FlagType{focusedFlag}, noneFlag, false, true}, - {[]types.FlagType{pendingFlag}, noneFlag, true, false}, - {[]types.FlagType{noneFlag}, focusedFlag, false, true}, - {[]types.FlagType{focusedFlag}, focusedFlag, false, true}, - {[]types.FlagType{pendingFlag}, focusedFlag, true, true}, - {[]types.FlagType{noneFlag}, pendingFlag, true, false}, - {[]types.FlagType{focusedFlag}, pendingFlag, true, true}, - {[]types.FlagType{pendingFlag}, pendingFlag, true, false}, - {[]types.FlagType{focusedFlag, noneFlag}, noneFlag, false, true}, - {[]types.FlagType{noneFlag, focusedFlag}, noneFlag, false, true}, - {[]types.FlagType{pendingFlag, noneFlag}, noneFlag, true, false}, - {[]types.FlagType{noneFlag, pendingFlag}, noneFlag, true, false}, - {[]types.FlagType{focusedFlag, pendingFlag}, noneFlag, true, true}, - } - - for i, c := range cases { - subject := newIt("it node", c.SubjectFlag, false) - containers := []*containernode.ContainerNode{} - for _, flag := range c.ContainerFlags { - containers = append(containers, newContainer("container", flag)) - } - - spec := New(subject, containers, false) - Ω(spec.Pending()).Should(Equal(c.Pending), "Case %d: %#v", i, c) - Ω(spec.Focused()).Should(Equal(c.Focused), "Case %d: %#v", i, c) - - if c.Pending { - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePending)) - } - } - }) - }) - - Describe("Skip", func() { - It("should be skipped", func() { - spec := New(newIt("it node", noneFlag, false), containers(newContainer("container", noneFlag)), false) - Ω(spec.Skipped()).Should(BeFalse()) - spec.Skip() - Ω(spec.Skipped()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateSkipped)) - }) - }) - - Describe("IsMeasurement", func() { - It("should be true if the subject is a measurement node", func() { - spec := New(newIt("it node", noneFlag, false), containers(newContainer("container", noneFlag)), false) - Ω(spec.IsMeasurement()).Should(BeFalse()) - Ω(spec.Summary("").IsMeasurement).Should(BeFalse()) - Ω(spec.Summary("").NumberOfSamples).Should(Equal(1)) - - spec = New(newMeasure("measure node", noneFlag, false, 10), containers(newContainer("container", noneFlag)), false) - Ω(spec.IsMeasurement()).Should(BeTrue()) - Ω(spec.Summary("").IsMeasurement).Should(BeTrue()) - Ω(spec.Summary("").NumberOfSamples).Should(Equal(10)) - }) - }) - - Describe("Passed", func() { - It("should pass when the subject passed", func() { - spec := New(newIt("it node", noneFlag, false), containers(), false) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePassed)) - Ω(spec.Summary("").Failure).Should(BeZero()) - }) - }) - - Describe("Flaked", func() { - It("should work if Run is called twice and gets different results", func() { - i := 0 - spec := New(newItWithBody("flaky it", func() { - i++ - if i == 1 { - failer.Fail("oops", codeLocation) - } - }), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Flaked()).Should(BeFalse()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateFailed)) - Ω(spec.Summary("").Failure.Message).Should(Equal("oops")) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(spec.Flaked()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePassed)) - }) - }) - - Describe("Failed", func() { - It("should be failed if the failure was panic", func() { - spec := New(newItWithBody("panicky it", func() { - panic("bam") - }), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStatePanicked)) - Ω(spec.Summary("").Failure.Message).Should(Equal("Test Panicked")) - Ω(spec.Summary("").Failure.ForwardedPanic).Should(Equal("bam")) - }) - - It("should be failed if the failure was a timeout", func() { - spec := New(newItWithBody("sleepy it", func(done Done) {}), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateTimedOut)) - Ω(spec.Summary("").Failure.Message).Should(Equal("Timed out")) - }) - - It("should be failed if the failure was... a failure", func() { - spec := New(newItWithBody("failing it", func() { - failer.Fail("bam", codeLocation) - }), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").State).Should(Equal(types.SpecStateFailed)) - Ω(spec.Summary("").Failure.Message).Should(Equal("bam")) - }) - }) - - Describe("Concatenated string", func() { - It("should concatenate the texts of the containers and the subject", func() { - spec := New( - newIt("it node", noneFlag, false), - containers( - newContainer("outer container", noneFlag), - newContainer("inner container", noneFlag), - ), - false, - ) - - Ω(spec.ConcatenatedString()).Should(Equal("outer container inner container it node")) - }) - }) - - Describe("running it specs", func() { - Context("with just an it", func() { - Context("that succeeds", func() { - It("should run the it and report on its success", func() { - spec := New(newIt("it node", noneFlag, false), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{"it node"})) - }) - }) - - Context("that fails", func() { - It("should run the it and report on its success", func() { - spec := New(newIt("it node", noneFlag, true), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - Ω(nodesThatRan).Should(Equal([]string{"it node"})) - }) - }) - }) - - Context("with a full set of setup nodes", func() { - var failingNodes map[string]bool - - BeforeEach(func() { - failingNodes = map[string]bool{} - }) - - JustBeforeEach(func() { - spec = New( - newIt("it node", noneFlag, failingNodes["it node"]), - containers( - newContainer("outer container", noneFlag, - newBef("outer bef A", failingNodes["outer bef A"]), - newBef("outer bef B", failingNodes["outer bef B"]), - newJusBef("outer jusbef A", failingNodes["outer jusbef A"]), - newJusBef("outer jusbef B", failingNodes["outer jusbef B"]), - newAft("outer aft A", failingNodes["outer aft A"]), - newAft("outer aft B", failingNodes["outer aft B"]), - ), - newContainer("inner container", noneFlag, - newBef("inner bef A", failingNodes["inner bef A"]), - newBef("inner bef B", failingNodes["inner bef B"]), - newJusBef("inner jusbef A", failingNodes["inner jusbef A"]), - newJusBef("inner jusbef B", failingNodes["inner jusbef B"]), - newAft("inner aft A", failingNodes["inner aft A"]), - newAft("inner aft B", failingNodes["inner aft B"]), - ), - ), - false, - ) - spec.Run(buffer) - }) - - Context("that all pass", func() { - It("should walk through the nodes in the correct order", func() { - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - }) - }) - - Context("when the subject fails", func() { - BeforeEach(func() { - failingNodes["it node"] = true - }) - - It("should run the afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - }) - }) - - Context("when an inner before fails", func() { - BeforeEach(func() { - failingNodes["inner bef A"] = true - }) - - It("should not run any other befores, but it should run the subsequent afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("inner bef A")) - }) - }) - - Context("when an outer before fails", func() { - BeforeEach(func() { - failingNodes["outer bef B"] = true - }) - - It("should not run any other befores, but it should run the subsequent afters", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("outer bef B")) - }) - }) - - Context("when an after fails", func() { - BeforeEach(func() { - failingNodes["inner aft B"] = true - }) - - It("should run all other afters, but mark the test as failed", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("inner aft B")) - }) - }) - - Context("when a just before each fails", func() { - BeforeEach(func() { - failingNodes["outer jusbef B"] = true - }) - - It("should run the afters, but not the subject", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("outer jusbef B")) - }) - }) - - Context("when an after fails after an earlier node has failed", func() { - BeforeEach(func() { - failingNodes["it node"] = true - failingNodes["inner aft B"] = true - }) - - It("should record the earlier failure", func() { - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "outer bef A", - "outer bef B", - "inner bef A", - "inner bef B", - "outer jusbef A", - "outer jusbef B", - "inner jusbef A", - "inner jusbef B", - "it node", - "inner aft A", - "inner aft B", - "outer aft A", - "outer aft B", - })) - Ω(spec.Summary("").Failure.Message).Should(Equal("it node")) - }) - }) - }) - }) - - Describe("running measurement specs", func() { - Context("when the measurement succeeds", func() { - It("should run N samples", func() { - spec = New( - newMeasure("measure node", noneFlag, false, 3), - containers( - newContainer("container", noneFlag, - newBef("bef A", false), - newJusBef("jusbef A", false), - newAft("aft A", false), - ), - ), - false, - ) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeTrue()) - Ω(spec.Failed()).Should(BeFalse()) - Ω(nodesThatRan).Should(Equal([]string{ - "bef A", - "jusbef A", - "measure node", - "aft A", - "bef A", - "jusbef A", - "measure node", - "aft A", - "bef A", - "jusbef A", - "measure node", - "aft A", - })) - }) - }) - - Context("when the measurement fails", func() { - It("should bail after the failure occurs", func() { - spec = New( - newMeasure("measure node", noneFlag, true, 3), - containers( - newContainer("container", noneFlag, - newBef("bef A", false), - newJusBef("jusbef A", false), - newAft("aft A", false), - ), - ), - false, - ) - spec.Run(buffer) - - Ω(spec.Passed()).Should(BeFalse()) - Ω(spec.Failed()).Should(BeTrue()) - Ω(nodesThatRan).Should(Equal([]string{ - "bef A", - "jusbef A", - "measure node", - "aft A", - })) - }) - }) - }) - - Describe("Summary", func() { - var ( - subjectCodeLocation types.CodeLocation - outerContainerCodeLocation types.CodeLocation - innerContainerCodeLocation types.CodeLocation - summary *types.SpecSummary - ) - - BeforeEach(func() { - subjectCodeLocation = codelocation.New(0) - outerContainerCodeLocation = codelocation.New(0) - innerContainerCodeLocation = codelocation.New(0) - - spec = New( - leafnodes.NewItNode("it node", func() { - time.Sleep(10 * time.Millisecond) - }, noneFlag, subjectCodeLocation, 0, failer, 0), - containers( - containernode.New("outer container", noneFlag, outerContainerCodeLocation), - containernode.New("inner container", noneFlag, innerContainerCodeLocation), - ), - false, - ) - - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - summary = spec.Summary("suite id") - }) - - It("should have the suite id", func() { - Ω(summary.SuiteID).Should(Equal("suite id")) - }) - - It("should have the component texts and code locations", func() { - Ω(summary.ComponentTexts).Should(Equal([]string{"outer container", "inner container", "it node"})) - Ω(summary.ComponentCodeLocations).Should(Equal([]types.CodeLocation{outerContainerCodeLocation, innerContainerCodeLocation, subjectCodeLocation})) - }) - - It("should have a runtime", func() { - Ω(summary.RunTime).Should(BeNumerically(">=", 10*time.Millisecond)) - }) - - It("should not be a measurement, or have a measurement summary", func() { - Ω(summary.IsMeasurement).Should(BeFalse()) - Ω(summary.Measurements).Should(BeEmpty()) - }) - }) - - Describe("Summaries for measurements", func() { - var summary *types.SpecSummary - - BeforeEach(func() { - spec = New(leafnodes.NewMeasureNode("measure node", func(b Benchmarker) { - b.RecordValue("a value", 7, "some info") - b.RecordValueWithPrecision("another value", 8, "ns", 5, "more info") - }, noneFlag, codeLocation, 4, failer, 0), containers(), false) - spec.Run(buffer) - Ω(spec.Passed()).Should(BeTrue()) - summary = spec.Summary("suite id") - }) - - It("should include the number of samples", func() { - Ω(summary.NumberOfSamples).Should(Equal(4)) - }) - - It("should be a measurement", func() { - Ω(summary.IsMeasurement).Should(BeTrue()) - }) - - It("should have the measurements report", func() { - Ω(summary.Measurements).Should(HaveKey("a value")) - report := summary.Measurements["a value"] - Ω(report.Name).Should(Equal("a value")) - Ω(report.Info).Should(Equal("some info")) - Ω(report.Results).Should(Equal([]float64{7, 7, 7, 7})) - - Ω(summary.Measurements).Should(HaveKey("another value")) - report = summary.Measurements["another value"] - Ω(report.Name).Should(Equal("another value")) - Ω(report.Info).Should(Equal("more info")) - Ω(report.Results).Should(Equal([]float64{8, 8, 8, 8})) - Ω(report.Units).Should(Equal("ns")) - Ω(report.Precision).Should(Equal(5)) - }) - }) - - Describe("When told to emit progress", func() { - It("should emit progress to the writer as it runs Befores, JustBefores, Afters, and Its", func() { - spec = New( - newIt("it node", noneFlag, false), - containers( - newContainer("outer container", noneFlag, - newBef("outer bef A", false), - newJusBef("outer jusbef A", false), - newAft("outer aft A", false), - ), - newContainer("inner container", noneFlag, - newBef("inner bef A", false), - newJusBef("inner jusbef A", false), - newAft("inner aft A", false), - ), - ), - true, - ) - spec.Run(buffer) - - Ω(buffer).Should(gbytes.Say(`\[BeforeEach\] outer container`)) - Ω(buffer).Should(gbytes.Say(`\[BeforeEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[JustBeforeEach\] outer container`)) - Ω(buffer).Should(gbytes.Say(`\[JustBeforeEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[It\] it node`)) - Ω(buffer).Should(gbytes.Say(`\[AfterEach\] inner container`)) - Ω(buffer).Should(gbytes.Say(`\[AfterEach\] outer container`)) - }) - - It("should emit progress to the writer as it runs Befores, JustBefores, Afters, and Measures", func() { - spec = New( - newMeasure("measure node", noneFlag, false, 2), - containers(), - true, - ) - spec.Run(buffer) - - Ω(buffer).Should(gbytes.Say(`\[Measure\] measure node`)) - Ω(buffer).Should(gbytes.Say(`\[Measure\] measure node`)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/specs_test.go b/vendor/github.com/onsi/ginkgo/internal/spec/specs_test.go deleted file mode 100644 index 066fbbb3ae..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/specs_test.go +++ /dev/null @@ -1,287 +0,0 @@ -package spec_test - -import ( - "math/rand" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/spec" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Specs", func() { - var specs *Specs - - newSpec := func(text string, flag types.FlagType) *Spec { - subject := leafnodes.NewItNode(text, func() {}, flag, codelocation.New(0), 0, nil, 0) - return New(subject, []*containernode.ContainerNode{}, false) - } - - newMeasureSpec := func(text string, flag types.FlagType) *Spec { - subject := leafnodes.NewMeasureNode(text, func(Benchmarker) {}, flag, codelocation.New(0), 0, nil, 0) - return New(subject, []*containernode.ContainerNode{}, false) - } - - newSpecs := func(args ...interface{}) *Specs { - specs := []*Spec{} - for index := 0; index < len(args)-1; index += 2 { - specs = append(specs, newSpec(args[index].(string), args[index+1].(types.FlagType))) - } - return NewSpecs(specs) - } - - specTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - texts = append(texts, spec.ConcatenatedString()) - } - return texts - } - - willRunTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if !(spec.Skipped() || spec.Pending()) { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - skippedTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if spec.Skipped() { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - pendingTexts := func(specs *Specs) []string { - texts := []string{} - for _, spec := range specs.Specs() { - if spec.Pending() { - texts = append(texts, spec.ConcatenatedString()) - } - } - return texts - } - - Describe("Shuffling specs", func() { - It("should shuffle the specs using the passed in randomizer", func() { - specs17 := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs17.Shuffle(rand.New(rand.NewSource(17))) - texts17 := specTexts(specs17) - - specs17Again := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs17Again.Shuffle(rand.New(rand.NewSource(17))) - texts17Again := specTexts(specs17Again) - - specs15 := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - specs15.Shuffle(rand.New(rand.NewSource(15))) - texts15 := specTexts(specs15) - - specsUnshuffled := newSpecs("C", noneFlag, "A", noneFlag, "B", noneFlag) - textsUnshuffled := specTexts(specsUnshuffled) - - Ω(textsUnshuffled).Should(Equal([]string{"C", "A", "B"})) - - Ω(texts17).Should(Equal(texts17Again)) - Ω(texts17).ShouldNot(Equal(texts15)) - Ω(texts17).ShouldNot(Equal(textsUnshuffled)) - Ω(texts15).ShouldNot(Equal(textsUnshuffled)) - - Ω(texts17).Should(HaveLen(3)) - Ω(texts17).Should(ContainElement("A")) - Ω(texts17).Should(ContainElement("B")) - Ω(texts17).Should(ContainElement("C")) - - Ω(texts15).Should(HaveLen(3)) - Ω(texts15).Should(ContainElement("A")) - Ω(texts15).Should(ContainElement("B")) - Ω(texts15).Should(ContainElement("C")) - }) - }) - - Describe("with no programmatic focus", func() { - BeforeEach(func() { - specs = newSpecs("A1", noneFlag, "A2", noneFlag, "B1", noneFlag, "B2", pendingFlag) - specs.ApplyFocus("", "", "") - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Describe("Applying focus/skip", func() { - var description, focusString, skipString string - - BeforeEach(func() { - description, focusString, skipString = "", "", "" - }) - - JustBeforeEach(func() { - specs = newSpecs("A1", focusedFlag, "A2", noneFlag, "B1", focusedFlag, "B2", pendingFlag) - specs.ApplyFocus(description, focusString, skipString) - }) - - Context("with neither a focus string nor a skip string", func() { - It("should apply the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A2", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeTrue()) - }) - }) - - Context("with a focus regexp", func() { - BeforeEach(func() { - focusString = "A" - }) - - It("should override the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Context("with a focus regexp", func() { - BeforeEach(func() { - focusString = "B" - }) - - It("should not override any pendings", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - }) - - Context("with a description", func() { - BeforeEach(func() { - description = "C" - focusString = "C" - }) - - It("should include the description in the focus determination", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1", "A2", "B1"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - }) - - Context("with a description", func() { - BeforeEach(func() { - description = "C" - skipString = "C" - }) - - It("should include the description in the focus determination", func() { - Ω(willRunTexts(specs)).Should(BeEmpty()) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2", "B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - }) - - Context("with a skip regexp", func() { - BeforeEach(func() { - skipString = "A" - }) - - It("should override the programmatic focus", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"B1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A1", "A2"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"B2"})) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - - Context("with both a focus and a skip regexp", func() { - BeforeEach(func() { - focusString = "1" - skipString = "B" - }) - - It("should AND the two", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A1"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"A2", "B1", "B2"})) - Ω(pendingTexts(specs)).Should(BeEmpty()) - }) - - It("should not report as having programmatic specs", func() { - Ω(specs.HasProgrammaticFocus()).Should(BeFalse()) - }) - }) - }) - - Describe("With a focused spec within a pending context and a pending spec within a focused context", func() { - BeforeEach(func() { - pendingInFocused := New( - leafnodes.NewItNode("PendingInFocused", func() {}, pendingFlag, codelocation.New(0), 0, nil, 0), - []*containernode.ContainerNode{ - containernode.New("", focusedFlag, codelocation.New(0)), - }, false) - - focusedInPending := New( - leafnodes.NewItNode("FocusedInPending", func() {}, focusedFlag, codelocation.New(0), 0, nil, 0), - []*containernode.ContainerNode{ - containernode.New("", pendingFlag, codelocation.New(0)), - }, false) - - specs = NewSpecs([]*Spec{ - newSpec("A", noneFlag), - newSpec("B", noneFlag), - pendingInFocused, - focusedInPending, - }) - specs.ApplyFocus("", "", "") - }) - - It("should not have a programmatic focus and should run all tests", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(ConsistOf(ContainSubstring("PendingInFocused"), ContainSubstring("FocusedInPending"))) - }) - }) - - Describe("skipping measurements", func() { - BeforeEach(func() { - specs = NewSpecs([]*Spec{ - newSpec("A", noneFlag), - newSpec("B", noneFlag), - newSpec("C", pendingFlag), - newMeasureSpec("measurementA", noneFlag), - newMeasureSpec("measurementB", pendingFlag), - }) - }) - - It("should skip measurements", func() { - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B", "measurementA"})) - Ω(skippedTexts(specs)).Should(BeEmpty()) - Ω(pendingTexts(specs)).Should(Equal([]string{"C", "measurementB"})) - - specs.SkipMeasurements() - - Ω(willRunTexts(specs)).Should(Equal([]string{"A", "B"})) - Ω(skippedTexts(specs)).Should(Equal([]string{"measurementA", "measurementB"})) - Ω(pendingTexts(specs)).Should(Equal([]string{"C"})) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer_test.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer_test.go deleted file mode 100644 index 65da9837c6..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package spec_iterator_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/spec_iterator" - . "github.com/onsi/gomega" -) - -var _ = Describe("ParallelizedIndexRange", func() { - var startIndex, count int - - It("should return the correct index range for 4 tests on 2 nodes", func() { - startIndex, count = ParallelizedIndexRange(4, 2, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(4, 2, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - }) - - It("should return the correct index range for 5 tests on 2 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 2, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(3)) - - startIndex, count = ParallelizedIndexRange(5, 2, 2) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(2)) - }) - - It("should return the correct index range for 5 tests on 3 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 3, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 3, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 3, 3) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 4 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 4, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(5, 4, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 4, 3) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 4, 4) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 5 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 5, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 2) - Ω(startIndex).Should(Equal(1)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 3) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 4) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 5, 5) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - }) - - It("should return the correct index range for 5 tests on 6 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 6, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 2) - Ω(startIndex).Should(Equal(1)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 3) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 4) - Ω(startIndex).Should(Equal(3)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 5) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(5, 6, 6) - Ω(count).Should(Equal(0)) - }) - - It("should return the correct index range for 5 tests on 7 nodes", func() { - startIndex, count = ParallelizedIndexRange(5, 7, 6) - Ω(count).Should(Equal(0)) - - startIndex, count = ParallelizedIndexRange(5, 7, 7) - Ω(count).Should(Equal(0)) - }) - - It("should return the correct index range for 11 tests on 7 nodes", func() { - startIndex, count = ParallelizedIndexRange(11, 7, 1) - Ω(startIndex).Should(Equal(0)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 2) - Ω(startIndex).Should(Equal(2)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 3) - Ω(startIndex).Should(Equal(4)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 4) - Ω(startIndex).Should(Equal(6)) - Ω(count).Should(Equal(2)) - - startIndex, count = ParallelizedIndexRange(11, 7, 5) - Ω(startIndex).Should(Equal(8)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(11, 7, 6) - Ω(startIndex).Should(Equal(9)) - Ω(count).Should(Equal(1)) - - startIndex, count = ParallelizedIndexRange(11, 7, 7) - Ω(startIndex).Should(Equal(10)) - Ω(count).Should(Equal(1)) - }) - -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go index 54e61ecb46..99f548bca4 100644 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go +++ b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go @@ -2,7 +2,6 @@ package spec_iterator import ( "encoding/json" - "errors" "fmt" "net/http" @@ -31,7 +30,7 @@ func (s *ParallelIterator) Next() (*spec.Spec, error) { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, errors.New(fmt.Sprintf("unexpected status code %d", resp.StatusCode)) + return nil, fmt.Errorf("unexpected status code %d", resp.StatusCode) } var counter Counter diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator_test.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator_test.go deleted file mode 100644 index d8e05a2d60..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package spec_iterator_test - -import ( - "net/http" - - . "github.com/onsi/ginkgo/internal/spec_iterator" - "github.com/onsi/gomega/ghttp" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - "github.com/onsi/ginkgo/types" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ParallelSpecIterator", func() { - var specs []*spec.Spec - var iterator *ParallelIterator - var server *ghttp.Server - - newSpec := func(text string, flag types.FlagType) *spec.Spec { - subject := leafnodes.NewItNode(text, func() {}, flag, codelocation.New(0), 0, nil, 0) - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - BeforeEach(func() { - specs = []*spec.Spec{ - newSpec("A", types.FlagTypePending), - newSpec("B", types.FlagTypeNone), - newSpec("C", types.FlagTypeNone), - newSpec("D", types.FlagTypeNone), - } - specs[3].Skip() - - server = ghttp.NewServer() - - iterator = NewParallelIterator(specs, "http://"+server.Addr()) - }) - - AfterEach(func() { - server.Close() - }) - - It("should report the total number of specs", func() { - Ω(iterator.NumberOfSpecsPriorToIteration()).Should(Equal(4)) - }) - - It("should not report the number to be processed", func() { - n, known := iterator.NumberOfSpecsToProcessIfKnown() - Ω(n).Should(Equal(-1)) - Ω(known).Should(BeFalse()) - }) - - It("should not report the number that will be run", func() { - n, known := iterator.NumberOfSpecsThatWillBeRunIfKnown() - Ω(n).Should(Equal(-1)) - Ω(known).Should(BeFalse()) - }) - - Describe("iterating", func() { - Describe("when the server returns well-formed responses", func() { - BeforeEach(func() { - server.AppendHandlers( - ghttp.RespondWithJSONEncoded(http.StatusOK, Counter{0}), - ghttp.RespondWithJSONEncoded(http.StatusOK, Counter{1}), - ghttp.RespondWithJSONEncoded(http.StatusOK, Counter{3}), - ghttp.RespondWithJSONEncoded(http.StatusOK, Counter{4}), - ) - }) - - It("should return the specs in question", func() { - Ω(iterator.Next()).Should(Equal(specs[0])) - Ω(iterator.Next()).Should(Equal(specs[1])) - Ω(iterator.Next()).Should(Equal(specs[3])) - spec, err := iterator.Next() - Ω(spec).Should(BeNil()) - Ω(err).Should(MatchError(ErrClosed)) - }) - }) - - Describe("when the server 404s", func() { - BeforeEach(func() { - server.AppendHandlers( - ghttp.RespondWith(http.StatusNotFound, ""), - ) - }) - - It("should return an error", func() { - spec, err := iterator.Next() - Ω(spec).Should(BeNil()) - Ω(err).Should(MatchError("unexpected status code 404")) - }) - }) - - Describe("when the server returns gibberish", func() { - BeforeEach(func() { - server.AppendHandlers( - ghttp.RespondWith(http.StatusOK, "ß"), - ) - }) - - It("should error", func() { - spec, err := iterator.Next() - Ω(spec).Should(BeNil()) - Ω(err).ShouldNot(BeNil()) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator_test.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator_test.go deleted file mode 100644 index dde4a344e8..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package spec_iterator_test - -import ( - . "github.com/onsi/ginkgo/internal/spec_iterator" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - "github.com/onsi/ginkgo/types" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("SerialSpecIterator", func() { - var specs []*spec.Spec - var iterator *SerialIterator - - newSpec := func(text string, flag types.FlagType) *spec.Spec { - subject := leafnodes.NewItNode(text, func() {}, flag, codelocation.New(0), 0, nil, 0) - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - BeforeEach(func() { - specs = []*spec.Spec{ - newSpec("A", types.FlagTypePending), - newSpec("B", types.FlagTypeNone), - newSpec("C", types.FlagTypeNone), - newSpec("D", types.FlagTypeNone), - } - specs[3].Skip() - - iterator = NewSerialIterator(specs) - }) - - It("should report the total number of specs", func() { - Ω(iterator.NumberOfSpecsPriorToIteration()).Should(Equal(4)) - }) - - It("should report the number to be processed", func() { - n, known := iterator.NumberOfSpecsToProcessIfKnown() - Ω(n).Should(Equal(4)) - Ω(known).Should(BeTrue()) - }) - - It("should report the number that will be run", func() { - n, known := iterator.NumberOfSpecsThatWillBeRunIfKnown() - Ω(n).Should(Equal(2)) - Ω(known).Should(BeTrue()) - }) - - Describe("iterating", func() { - It("should return the specs in order", func() { - Ω(iterator.Next()).Should(Equal(specs[0])) - Ω(iterator.Next()).Should(Equal(specs[1])) - Ω(iterator.Next()).Should(Equal(specs[2])) - Ω(iterator.Next()).Should(Equal(specs[3])) - spec, err := iterator.Next() - Ω(spec).Should(BeNil()) - Ω(err).Should(MatchError(ErrClosed)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator_test.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator_test.go deleted file mode 100644 index c3786e03aa..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package spec_iterator_test - -import ( - . "github.com/onsi/ginkgo/internal/spec_iterator" - - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - "github.com/onsi/ginkgo/types" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ShardedParallelSpecIterator", func() { - var specs []*spec.Spec - var iterator *ShardedParallelIterator - - newSpec := func(text string, flag types.FlagType) *spec.Spec { - subject := leafnodes.NewItNode(text, func() {}, flag, codelocation.New(0), 0, nil, 0) - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - BeforeEach(func() { - specs = []*spec.Spec{ - newSpec("A", types.FlagTypePending), - newSpec("B", types.FlagTypeNone), - newSpec("C", types.FlagTypeNone), - newSpec("D", types.FlagTypeNone), - } - specs[3].Skip() - - iterator = NewShardedParallelIterator(specs, 2, 1) - }) - - It("should report the total number of specs", func() { - Ω(iterator.NumberOfSpecsPriorToIteration()).Should(Equal(4)) - }) - - It("should report the number to be processed", func() { - n, known := iterator.NumberOfSpecsToProcessIfKnown() - Ω(n).Should(Equal(2)) - Ω(known).Should(BeTrue()) - }) - - It("should report the number that will be run", func() { - n, known := iterator.NumberOfSpecsThatWillBeRunIfKnown() - Ω(n).Should(Equal(1)) - Ω(known).Should(BeTrue()) - }) - - Describe("iterating", func() { - It("should return the specs in order", func() { - Ω(iterator.Next()).Should(Equal(specs[0])) - Ω(iterator.Next()).Should(Equal(specs[1])) - spec, err := iterator.Next() - Ω(spec).Should(BeNil()) - Ω(err).Should(MatchError(ErrClosed)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator_suite_test.go deleted file mode 100644 index 5c08a77e36..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package spec_iterator_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestSpecIterator(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "SpecIterator Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go b/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go index d4dd909ecf..2c683cb8b9 100644 --- a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go +++ b/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go @@ -56,7 +56,9 @@ func (runner *SpecRunner) Run() bool { } runner.reportSuiteWillBegin() - go runner.registerForInterrupts() + signalRegistered := make(chan struct{}) + go runner.registerForInterrupts(signalRegistered) + <-signalRegistered suitePassed := runner.runBeforeSuite() @@ -213,9 +215,10 @@ func (runner *SpecRunner) CurrentSpecSummary() (*types.SpecSummary, bool) { return runner.runningSpec.Summary(runner.suiteID), true } -func (runner *SpecRunner) registerForInterrupts() { +func (runner *SpecRunner) registerForInterrupts(signalRegistered chan struct{}) { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) + close(signalRegistered) <-c signal.Stop(c) diff --git a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go deleted file mode 100644 index c8388fb6f7..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package specrunner_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestSpecRunner(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Spec Runner Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go b/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go deleted file mode 100644 index 77272e8b86..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner_test.go +++ /dev/null @@ -1,779 +0,0 @@ -package specrunner_test - -import ( - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/internal/spec_iterator" - . "github.com/onsi/ginkgo/internal/specrunner" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/containernode" - Failer "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" -) - -var noneFlag = types.FlagTypeNone -var focusedFlag = types.FlagTypeFocused -var pendingFlag = types.FlagTypePending - -var _ = Describe("Spec Runner", func() { - var ( - reporter1 *reporters.FakeReporter - reporter2 *reporters.FakeReporter - failer *Failer.Failer - writer *Writer.FakeGinkgoWriter - - thingsThatRan []string - - runner *SpecRunner - ) - - newBefSuite := func(text string, fail bool) leafnodes.SuiteNode { - return leafnodes.NewBeforeSuiteNode(func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, codelocation.New(0), 0, failer) - } - - newAftSuite := func(text string, fail bool) leafnodes.SuiteNode { - return leafnodes.NewAfterSuiteNode(func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, codelocation.New(0), 0, failer) - } - - newSpec := func(text string, flag types.FlagType, fail bool) *spec.Spec { - subject := leafnodes.NewItNode(text, func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - if fail { - failer.Fail(text, codelocation.New(0)) - } - }, flag, codelocation.New(0), 0, failer, 0) - - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - newFlakySpec := func(text string, flag types.FlagType, failures int) *spec.Spec { - runs := 0 - subject := leafnodes.NewItNode(text, func() { - writer.AddEvent(text) - thingsThatRan = append(thingsThatRan, text) - runs++ - if runs < failures { - failer.Fail(text, codelocation.New(0)) - } - }, flag, codelocation.New(0), 0, failer, 0) - - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - newSpecWithBody := func(text string, body interface{}) *spec.Spec { - subject := leafnodes.NewItNode(text, body, noneFlag, codelocation.New(0), 0, failer, 0) - - return spec.New(subject, []*containernode.ContainerNode{}, false) - } - - newRunner := func(config config.GinkgoConfigType, beforeSuiteNode leafnodes.SuiteNode, afterSuiteNode leafnodes.SuiteNode, specs ...*spec.Spec) *SpecRunner { - iterator := spec_iterator.NewSerialIterator(specs) - return New("description", beforeSuiteNode, iterator, afterSuiteNode, []reporters.Reporter{reporter1, reporter2}, writer, config) - } - - BeforeEach(func() { - reporter1 = reporters.NewFakeReporter() - reporter2 = reporters.NewFakeReporter() - writer = Writer.NewFake() - failer = Failer.New() - - thingsThatRan = []string{} - }) - - Describe("Running and Reporting", func() { - var specA, pendingSpec, anotherPendingSpec, failedSpec, specB, skippedSpec *spec.Spec - var willRunCalls, didCompleteCalls []string - var conf config.GinkgoConfigType - - JustBeforeEach(func() { - willRunCalls = []string{} - didCompleteCalls = []string{} - specA = newSpec("spec A", noneFlag, false) - pendingSpec = newSpec("pending spec", pendingFlag, false) - anotherPendingSpec = newSpec("another pending spec", pendingFlag, false) - failedSpec = newSpec("failed spec", noneFlag, true) - specB = newSpec("spec B", noneFlag, false) - skippedSpec = newSpec("skipped spec", noneFlag, false) - skippedSpec.Skip() - - reporter1.SpecWillRunStub = func(specSummary *types.SpecSummary) { - willRunCalls = append(willRunCalls, "Reporter1") - } - reporter2.SpecWillRunStub = func(specSummary *types.SpecSummary) { - willRunCalls = append(willRunCalls, "Reporter2") - } - - reporter1.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - didCompleteCalls = append(didCompleteCalls, "Reporter1") - } - reporter2.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - didCompleteCalls = append(didCompleteCalls, "Reporter2") - } - - runner = newRunner(conf, newBefSuite("BefSuite", false), newAftSuite("AftSuite", false), specA, pendingSpec, anotherPendingSpec, failedSpec, specB, skippedSpec) - runner.Run() - }) - - BeforeEach(func() { - conf = config.GinkgoConfigType{RandomSeed: 17} - }) - - It("should skip skipped/pending tests", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "spec A", "failed spec", "spec B", "AftSuite"})) - }) - - It("should report to any attached reporters", func() { - Ω(reporter1.Config).Should(Equal(reporter2.Config)) - Ω(reporter1.BeforeSuiteSummary).Should(Equal(reporter2.BeforeSuiteSummary)) - Ω(reporter1.BeginSummary).Should(Equal(reporter2.BeginSummary)) - Ω(reporter1.SpecWillRunSummaries).Should(Equal(reporter2.SpecWillRunSummaries)) - Ω(reporter1.SpecSummaries).Should(Equal(reporter2.SpecSummaries)) - Ω(reporter1.AfterSuiteSummary).Should(Equal(reporter2.AfterSuiteSummary)) - Ω(reporter1.EndSummary).Should(Equal(reporter2.EndSummary)) - }) - - It("should report that a spec did end in reverse order", func() { - Ω(willRunCalls[0:4]).Should(Equal([]string{"Reporter1", "Reporter2", "Reporter1", "Reporter2"})) - Ω(didCompleteCalls[0:4]).Should(Equal([]string{"Reporter2", "Reporter1", "Reporter2", "Reporter1"})) - }) - - It("should report the passed in config", func() { - Ω(reporter1.Config.RandomSeed).Should(BeNumerically("==", 17)) - }) - - It("should report the beginning of the suite", func() { - Ω(reporter1.BeginSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.BeginSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.BeginSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.BeginSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.BeginSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.BeginSummary.NumberOfPendingSpecs).Should(Equal(-1)) - Ω(reporter1.BeginSummary.NumberOfSkippedSpecs).Should(Equal(-1)) - }) - - It("should report the end of the suite", func() { - Ω(reporter1.EndSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPassedSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(1)) - }) - - Context("when told to perform a dry run", func() { - BeforeEach(func() { - conf.DryRun = true - }) - - It("should report to the reporters", func() { - Ω(reporter1.Config).Should(Equal(reporter2.Config)) - Ω(reporter1.BeforeSuiteSummary).Should(Equal(reporter2.BeforeSuiteSummary)) - Ω(reporter1.BeginSummary).Should(Equal(reporter2.BeginSummary)) - Ω(reporter1.SpecWillRunSummaries).Should(Equal(reporter2.SpecWillRunSummaries)) - Ω(reporter1.SpecSummaries).Should(Equal(reporter2.SpecSummaries)) - Ω(reporter1.AfterSuiteSummary).Should(Equal(reporter2.AfterSuiteSummary)) - Ω(reporter1.EndSummary).Should(Equal(reporter2.EndSummary)) - }) - - It("should not actually run anything", func() { - Ω(thingsThatRan).Should(BeEmpty()) - }) - - It("report before and after suites as passed", func() { - Ω(reporter1.BeforeSuiteSummary.State).Should(Equal(types.SpecStatePassed)) - Ω(reporter1.AfterSuiteSummary.State).Should(Equal(types.SpecStatePassed)) - }) - - It("should report specs as passed", func() { - summaries := reporter1.SpecSummaries - Ω(summaries).Should(HaveLen(6)) - Ω(summaries[0].ComponentTexts).Should(ContainElement("spec A")) - Ω(summaries[0].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[1].ComponentTexts).Should(ContainElement("pending spec")) - Ω(summaries[1].State).Should(Equal(types.SpecStatePending)) - Ω(summaries[2].ComponentTexts).Should(ContainElement("another pending spec")) - Ω(summaries[2].State).Should(Equal(types.SpecStatePending)) - Ω(summaries[3].ComponentTexts).Should(ContainElement("failed spec")) - Ω(summaries[3].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[4].ComponentTexts).Should(ContainElement("spec B")) - Ω(summaries[4].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[5].ComponentTexts).Should(ContainElement("skipped spec")) - Ω(summaries[5].State).Should(Equal(types.SpecStateSkipped)) - }) - - It("should report the end of the suite", func() { - Ω(reporter1.EndSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPassedSpecs).Should(Equal(0)) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - }) - }) - - Describe("reporting on specs", func() { - var proceed chan bool - var ready chan bool - var finished chan bool - BeforeEach(func() { - ready = make(chan bool) - proceed = make(chan bool) - finished = make(chan bool) - skippedSpec := newSpec("SKIP", noneFlag, false) - skippedSpec.Skip() - - runner = newRunner( - config.GinkgoConfigType{}, - newBefSuite("BefSuite", false), - newAftSuite("AftSuite", false), - skippedSpec, - newSpec("PENDING", pendingFlag, false), - newSpecWithBody("RUN", func() { - close(ready) - <-proceed - }), - ) - go func() { - runner.Run() - close(finished) - }() - }) - - It("should report about pending/skipped specs", func() { - <-ready - Ω(reporter1.SpecWillRunSummaries).Should(HaveLen(3)) - - Ω(reporter1.SpecWillRunSummaries[0].ComponentTexts[0]).Should(Equal("SKIP")) - Ω(reporter1.SpecWillRunSummaries[1].ComponentTexts[0]).Should(Equal("PENDING")) - Ω(reporter1.SpecWillRunSummaries[2].ComponentTexts[0]).Should(Equal("RUN")) - - Ω(reporter1.SpecSummaries[0].ComponentTexts[0]).Should(Equal("SKIP")) - Ω(reporter1.SpecSummaries[1].ComponentTexts[0]).Should(Equal("PENDING")) - Ω(reporter1.SpecSummaries).Should(HaveLen(2)) - - close(proceed) - <-finished - - Ω(reporter1.SpecSummaries).Should(HaveLen(3)) - Ω(reporter1.SpecSummaries[2].ComponentTexts[0]).Should(Equal("RUN")) - }) - }) - - Describe("Running and Reporting when there's flakes", func() { - var specA, pendingSpec, flakySpec, failedSpec, specB, skippedSpec *spec.Spec - var willRunCalls, didCompleteCalls []string - var conf config.GinkgoConfigType - var failedSpecFlag = noneFlag - - JustBeforeEach(func() { - willRunCalls = []string{} - didCompleteCalls = []string{} - specA = newSpec("spec A", noneFlag, false) - pendingSpec = newSpec("pending spec", pendingFlag, false) - flakySpec = newFlakySpec("flaky spec", noneFlag, 3) - failedSpec = newSpec("failed spec", failedSpecFlag, true) - specB = newSpec("spec B", noneFlag, false) - skippedSpec = newSpec("skipped spec", noneFlag, false) - skippedSpec.Skip() - - reporter1.SpecWillRunStub = func(specSummary *types.SpecSummary) { - willRunCalls = append(willRunCalls, "Reporter1") - } - reporter2.SpecWillRunStub = func(specSummary *types.SpecSummary) { - willRunCalls = append(willRunCalls, "Reporter2") - } - - reporter1.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - didCompleteCalls = append(didCompleteCalls, "Reporter1") - } - reporter2.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - didCompleteCalls = append(didCompleteCalls, "Reporter2") - } - - runner = newRunner(conf, newBefSuite("BefSuite", false), newAftSuite("AftSuite", false), specA, pendingSpec, flakySpec, failedSpec, specB, skippedSpec) - runner.Run() - }) - - BeforeEach(func() { - failedSpecFlag = noneFlag - conf = config.GinkgoConfigType{ - RandomSeed: 17, - FlakeAttempts: 5, - } - }) - - It("should skip skipped/pending tests", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "spec A", "flaky spec", "flaky spec", "flaky spec", "failed spec", "failed spec", "failed spec", "failed spec", "failed spec", "spec B", "AftSuite"})) - }) - - It("should report to any attached reporters", func() { - Ω(reporter1.Config).Should(Equal(reporter2.Config)) - Ω(reporter1.BeforeSuiteSummary).Should(Equal(reporter2.BeforeSuiteSummary)) - Ω(reporter1.BeginSummary).Should(Equal(reporter2.BeginSummary)) - Ω(reporter1.SpecWillRunSummaries).Should(Equal(reporter2.SpecWillRunSummaries)) - Ω(reporter1.SpecSummaries).Should(Equal(reporter2.SpecSummaries)) - Ω(reporter1.AfterSuiteSummary).Should(Equal(reporter2.AfterSuiteSummary)) - Ω(reporter1.EndSummary).Should(Equal(reporter2.EndSummary)) - }) - - It("should report that a spec did end in reverse order", func() { - Ω(willRunCalls[0:4]).Should(Equal([]string{"Reporter1", "Reporter2", "Reporter1", "Reporter2"})) - Ω(didCompleteCalls[0:4]).Should(Equal([]string{"Reporter2", "Reporter1", "Reporter2", "Reporter1"})) - }) - - It("should report the passed in config", func() { - Ω(reporter1.Config.RandomSeed).Should(BeNumerically("==", 17)) - }) - - It("should report the beginning of the suite", func() { - Ω(reporter1.BeginSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.BeginSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.BeginSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.BeginSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.BeginSummary.NumberOfSpecsThatWillBeRun).Should(Equal(4)) - Ω(reporter1.BeginSummary.NumberOfPendingSpecs).Should(Equal(-1)) - Ω(reporter1.BeginSummary.NumberOfSkippedSpecs).Should(Equal(-1)) - }) - - It("should report the end of the suite", func() { - Ω(reporter1.EndSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(4)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPassedSpecs).Should(Equal(3)) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfFlakedSpecs).Should(Equal(1)) - }) - - Context("when nothing fails", func() { - BeforeEach(func() { - failedSpecFlag = pendingFlag - }) - - It("the suite should pass even with flakes", func() { - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - Ω(reporter1.EndSummary.NumberOfFlakedSpecs).Should(Equal(1)) - }) - }) - - Context("when told to perform a dry run", func() { - BeforeEach(func() { - conf.DryRun = true - }) - - It("should report to the reporters", func() { - Ω(reporter1.Config).Should(Equal(reporter2.Config)) - Ω(reporter1.BeforeSuiteSummary).Should(Equal(reporter2.BeforeSuiteSummary)) - Ω(reporter1.BeginSummary).Should(Equal(reporter2.BeginSummary)) - Ω(reporter1.SpecWillRunSummaries).Should(Equal(reporter2.SpecWillRunSummaries)) - Ω(reporter1.SpecSummaries).Should(Equal(reporter2.SpecSummaries)) - Ω(reporter1.AfterSuiteSummary).Should(Equal(reporter2.AfterSuiteSummary)) - Ω(reporter1.EndSummary).Should(Equal(reporter2.EndSummary)) - }) - - It("should not actually run anything", func() { - Ω(thingsThatRan).Should(BeEmpty()) - }) - - It("report before and after suites as passed", func() { - Ω(reporter1.BeforeSuiteSummary.State).Should(Equal(types.SpecStatePassed)) - Ω(reporter1.AfterSuiteSummary.State).Should(Equal(types.SpecStatePassed)) - }) - - It("should report specs as passed", func() { - summaries := reporter1.SpecSummaries - Ω(summaries).Should(HaveLen(6)) - Ω(summaries[0].ComponentTexts).Should(ContainElement("spec A")) - Ω(summaries[0].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[1].ComponentTexts).Should(ContainElement("pending spec")) - Ω(summaries[1].State).Should(Equal(types.SpecStatePending)) - Ω(summaries[2].ComponentTexts).Should(ContainElement("flaky spec")) - Ω(summaries[2].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[3].ComponentTexts).Should(ContainElement("failed spec")) - Ω(summaries[3].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[4].ComponentTexts).Should(ContainElement("spec B")) - Ω(summaries[4].State).Should(Equal(types.SpecStatePassed)) - Ω(summaries[5].ComponentTexts).Should(ContainElement("skipped spec")) - Ω(summaries[5].State).Should(Equal(types.SpecStateSkipped)) - }) - - It("should report the end of the suite", func() { - Ω(reporter1.EndSummary.SuiteDescription).Should(Equal("description")) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteID).Should(MatchRegexp("[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}")) - Ω(reporter1.EndSummary.NumberOfSpecsBeforeParallelization).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfTotalSpecs).Should(Equal(6)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(4)) - Ω(reporter1.EndSummary.NumberOfPendingSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfPassedSpecs).Should(Equal(0)) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - }) - }) - - Describe("Running BeforeSuite & AfterSuite", func() { - var success bool - var befSuite leafnodes.SuiteNode - var aftSuite leafnodes.SuiteNode - Context("with a nil BeforeSuite & AfterSuite", func() { - BeforeEach(func() { - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should not report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(BeNil()) - }) - - It("should not report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(BeNil()) - }) - - It("should run the specs", func() { - Ω(thingsThatRan).Should(Equal([]string{"A", "B"})) - }) - }) - - Context("when the BeforeSuite & AfterSuite pass", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", false) - aftSuite = newBefSuite("AftSuite", false) - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should run the BeforeSuite, the AfterSuite and the specs", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "A", "B", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report success", func() { - Ω(success).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - - It("should not dump the writer", func() { - Ω(writer.EventStream).ShouldNot(ContainElement("DUMP")) - }) - }) - - Context("when the BeforeSuite fails", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", true) - aftSuite = newBefSuite("AftSuite", false) - - skipped := newSpec("Skipped", noneFlag, false) - skipped.Skip() - - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - newSpec("Pending", pendingFlag, false), - skipped, - ) - success = runner.Run() - }) - - It("should not run the specs, but it should run the AfterSuite", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(2)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(2)) - }) - - It("should dump the writer", func() { - Ω(writer.EventStream).Should(ContainElement("DUMP")) - }) - }) - - Context("when some other test fails", func() { - BeforeEach(func() { - aftSuite = newBefSuite("AftSuite", false) - - runner = newRunner( - config.GinkgoConfigType{}, - nil, - aftSuite, - newSpec("A", noneFlag, true), - ) - success = runner.Run() - }) - - It("should still run the AfterSuite", func() { - Ω(thingsThatRan).Should(Equal([]string{"A", "AftSuite"})) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(1)) - Ω(reporter1.EndSummary.NumberOfSpecsThatWillBeRun).Should(Equal(1)) - }) - }) - - Context("when the AfterSuite fails", func() { - BeforeEach(func() { - befSuite = newBefSuite("BefSuite", false) - aftSuite = newBefSuite("AftSuite", true) - runner = newRunner( - config.GinkgoConfigType{}, - befSuite, - aftSuite, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, false), - ) - success = runner.Run() - }) - - It("should run everything", func() { - Ω(thingsThatRan).Should(Equal([]string{"BefSuite", "A", "B", "AftSuite"})) - }) - - It("should report about the BeforeSuite", func() { - Ω(reporter1.BeforeSuiteSummary).Should(Equal(befSuite.Summary())) - }) - - It("should report about the AfterSuite", func() { - Ω(reporter1.AfterSuiteSummary).Should(Equal(aftSuite.Summary())) - }) - - It("should report failure", func() { - Ω(success).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(reporter1.EndSummary.NumberOfFailedSpecs).Should(Equal(0)) - }) - - It("should dump the writer", func() { - Ω(writer.EventStream).Should(ContainElement("DUMP")) - }) - }) - }) - - Describe("When instructed to fail fast", func() { - BeforeEach(func() { - conf := config.GinkgoConfigType{ - FailFast: true, - } - runner = newRunner(conf, nil, newAftSuite("after-suite", false), newSpec("passing", noneFlag, false), newSpec("failing", noneFlag, true), newSpec("dont-see", noneFlag, true), newSpec("dont-see", noneFlag, true)) - }) - - It("should return false, report failure, and not run anything past the failing test", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - Ω(thingsThatRan).Should(Equal([]string{"passing", "failing", "after-suite"})) - }) - - It("should announce the subsequent specs as skipped", func() { - runner.Run() - Ω(reporter1.SpecSummaries).Should(HaveLen(4)) - Ω(reporter1.SpecSummaries[2].State).Should(Equal(types.SpecStateSkipped)) - Ω(reporter1.SpecSummaries[3].State).Should(Equal(types.SpecStateSkipped)) - }) - - It("should mark all subsequent specs as skipped", func() { - runner.Run() - Ω(reporter1.EndSummary.NumberOfSkippedSpecs).Should(Equal(2)) - }) - }) - - Describe("Marking failure and success", func() { - Context("when all tests pass", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{}, nil, nil, newSpec("passing", noneFlag, false), newSpec("pending", pendingFlag, false)) - }) - - It("should return true and report success", func() { - Ω(runner.Run()).Should(BeTrue()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeTrue()) - }) - }) - - Context("when a test fails", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{}, nil, nil, newSpec("failing", noneFlag, true), newSpec("pending", pendingFlag, false)) - }) - - It("should return false and report failure", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - }) - }) - - Context("when there is a pending test, but pendings count as failures", func() { - BeforeEach(func() { - runner = newRunner(config.GinkgoConfigType{FailOnPending: true}, nil, nil, newSpec("passing", noneFlag, false), newSpec("pending", pendingFlag, false)) - }) - - It("should return false and report failure", func() { - Ω(runner.Run()).Should(BeFalse()) - Ω(reporter1.EndSummary.SuiteSucceeded).Should(BeFalse()) - }) - }) - }) - - Describe("Managing the writer", func() { - BeforeEach(func() { - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpec("B", noneFlag, true), - newSpec("C", noneFlag, false), - ) - reporter1.SpecWillRunStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R1.WillRun") - } - reporter2.SpecWillRunStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R2.WillRun") - } - reporter1.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R1.DidComplete") - } - reporter2.SpecDidCompleteStub = func(specSummary *types.SpecSummary) { - writer.AddEvent("R2.DidComplete") - } - runner.Run() - }) - - It("should truncate between tests, but only dump if a test fails", func() { - Ω(writer.EventStream).Should(Equal([]string{ - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "A", - "R2.DidComplete", - "R1.DidComplete", - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "B", - "BYTES", - "R2.DidComplete", - "DUMP", - "R1.DidComplete", - "TRUNCATE", - "R1.WillRun", - "R2.WillRun", - "C", - "R2.DidComplete", - "R1.DidComplete", - })) - }) - }) - - Describe("CurrentSpecSummary", func() { - It("should return the spec summary for the currently running spec", func() { - var summary *types.SpecSummary - runner = newRunner( - config.GinkgoConfigType{}, - nil, - nil, - newSpec("A", noneFlag, false), - newSpecWithBody("B", func() { - var ok bool - summary, ok = runner.CurrentSpecSummary() - Ω(ok).Should(BeTrue()) - }), - newSpec("C", noneFlag, false), - ) - runner.Run() - - Ω(summary.ComponentTexts).Should(Equal([]string{"B"})) - - summary, ok := runner.CurrentSpecSummary() - Ω(summary).Should(BeNil()) - Ω(ok).Should(BeFalse()) - }) - }) - - Describe("generating a suite id", func() { - It("should generate an id randomly", func() { - runnerA := newRunner(config.GinkgoConfigType{}, nil, nil) - runnerA.Run() - IDA := reporter1.BeginSummary.SuiteID - - runnerB := newRunner(config.GinkgoConfigType{}, nil, nil) - runnerB.Run() - IDB := reporter1.BeginSummary.SuiteID - - IDRegexp := "[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}" - Ω(IDA).Should(MatchRegexp(IDRegexp)) - Ω(IDB).Should(MatchRegexp(IDRegexp)) - - Ω(IDA).ShouldNot(Equal(IDB)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/suite/suite.go b/vendor/github.com/onsi/ginkgo/internal/suite/suite.go index 698a6e5689..f311e9a0d6 100644 --- a/vendor/github.com/onsi/ginkgo/internal/suite/suite.go +++ b/vendor/github.com/onsi/ginkgo/internal/suite/suite.go @@ -149,35 +149,35 @@ func (suite *Suite) PushContainerNode(text string, body func(), flag types.FlagT func (suite *Suite) PushItNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, timeout time.Duration) { if suite.running { - suite.failer.Fail("You may only call It from within a Describe or Context", codeLocation) + suite.failer.Fail("You may only call It from within a Describe, Context or When", codeLocation) } suite.currentContainer.PushSubjectNode(leafnodes.NewItNode(text, body, flag, codeLocation, timeout, suite.failer, suite.containerIndex)) } func (suite *Suite) PushMeasureNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, samples int) { if suite.running { - suite.failer.Fail("You may only call Measure from within a Describe or Context", codeLocation) + suite.failer.Fail("You may only call Measure from within a Describe, Context or When", codeLocation) } suite.currentContainer.PushSubjectNode(leafnodes.NewMeasureNode(text, body, flag, codeLocation, samples, suite.failer, suite.containerIndex)) } func (suite *Suite) PushBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { if suite.running { - suite.failer.Fail("You may only call BeforeEach from within a Describe or Context", codeLocation) + suite.failer.Fail("You may only call BeforeEach from within a Describe, Context or When", codeLocation) } suite.currentContainer.PushSetupNode(leafnodes.NewBeforeEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) } func (suite *Suite) PushJustBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { if suite.running { - suite.failer.Fail("You may only call JustBeforeEach from within a Describe or Context", codeLocation) + suite.failer.Fail("You may only call JustBeforeEach from within a Describe, Context or When", codeLocation) } suite.currentContainer.PushSetupNode(leafnodes.NewJustBeforeEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) } func (suite *Suite) PushAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { if suite.running { - suite.failer.Fail("You may only call AfterEach from within a Describe or Context", codeLocation) + suite.failer.Fail("You may only call AfterEach from within a Describe, Context or When", codeLocation) } suite.currentContainer.PushSetupNode(leafnodes.NewAfterEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) } diff --git a/vendor/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go deleted file mode 100644 index 06fe1d12ab..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/suite/suite_suite_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package suite_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func Test(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Suite") -} - -var numBeforeSuiteRuns = 0 -var numAfterSuiteRuns = 0 - -var _ = BeforeSuite(func() { - numBeforeSuiteRuns++ -}) - -var _ = AfterSuite(func() { - numAfterSuiteRuns++ - Ω(numBeforeSuiteRuns).Should(Equal(1)) - Ω(numAfterSuiteRuns).Should(Equal(1)) -}) - -//Fakes -type fakeTestingT struct { - didFail bool -} - -func (fakeT *fakeTestingT) Fail() { - fakeT.didFail = true -} diff --git a/vendor/github.com/onsi/ginkgo/internal/suite/suite_test.go b/vendor/github.com/onsi/ginkgo/internal/suite/suite_test.go deleted file mode 100644 index b7bcdbd2e1..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/suite/suite_test.go +++ /dev/null @@ -1,371 +0,0 @@ -package suite_test - -import ( - "bytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/suite" - . "github.com/onsi/gomega" - - "math/rand" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - Failer "github.com/onsi/ginkgo/internal/failer" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" -) - -var _ = Describe("Suite", func() { - var ( - specSuite *Suite - fakeT *fakeTestingT - fakeR *reporters.FakeReporter - writer *Writer.FakeGinkgoWriter - failer *Failer.Failer - ) - - BeforeEach(func() { - writer = Writer.NewFake() - fakeT = &fakeTestingT{} - fakeR = reporters.NewFakeReporter() - failer = Failer.New() - specSuite = New(failer) - }) - - Describe("running a suite", func() { - var ( - runOrder []string - randomizeAllSpecs bool - randomSeed int64 - focusString string - parallelNode int - parallelTotal int - runResult bool - hasProgrammaticFocus bool - ) - - var f = func(runText string) func() { - return func() { - runOrder = append(runOrder, runText) - } - } - - BeforeEach(func() { - randomizeAllSpecs = false - randomSeed = 11 - parallelNode = 1 - parallelTotal = 1 - focusString = "" - - runOrder = make([]string, 0) - specSuite.SetBeforeSuiteNode(f("BeforeSuite"), codelocation.New(0), 0) - specSuite.PushBeforeEachNode(f("top BE"), codelocation.New(0), 0) - specSuite.PushJustBeforeEachNode(f("top JBE"), codelocation.New(0), 0) - specSuite.PushAfterEachNode(f("top AE"), codelocation.New(0), 0) - - specSuite.PushContainerNode("container", func() { - specSuite.PushBeforeEachNode(f("BE"), codelocation.New(0), 0) - specSuite.PushJustBeforeEachNode(f("JBE"), codelocation.New(0), 0) - specSuite.PushAfterEachNode(f("AE"), codelocation.New(0), 0) - specSuite.PushItNode("it", f("IT"), types.FlagTypeNone, codelocation.New(0), 0) - - specSuite.PushContainerNode("inner container", func() { - specSuite.PushItNode("inner it", f("inner IT"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0)) - }, types.FlagTypeNone, codelocation.New(0)) - - specSuite.PushContainerNode("container 2", func() { - specSuite.PushBeforeEachNode(f("BE 2"), codelocation.New(0), 0) - specSuite.PushItNode("it 2", f("IT 2"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0)) - - specSuite.PushItNode("top level it", f("top IT"), types.FlagTypeNone, codelocation.New(0), 0) - - specSuite.SetAfterSuiteNode(f("AfterSuite"), codelocation.New(0), 0) - }) - - JustBeforeEach(func() { - runResult, hasProgrammaticFocus = specSuite.Run(fakeT, "suite description", []reporters.Reporter{fakeR}, writer, config.GinkgoConfigType{ - RandomSeed: randomSeed, - RandomizeAllSpecs: randomizeAllSpecs, - FocusString: focusString, - ParallelNode: parallelNode, - ParallelTotal: parallelTotal, - }) - }) - - It("provides the config and suite description to the reporter", func() { - Ω(fakeR.Config.RandomSeed).Should(Equal(int64(randomSeed))) - Ω(fakeR.Config.RandomizeAllSpecs).Should(Equal(randomizeAllSpecs)) - Ω(fakeR.BeginSummary.SuiteDescription).Should(Equal("suite description")) - }) - - It("reports that the BeforeSuite node ran", func() { - Ω(fakeR.BeforeSuiteSummary).ShouldNot(BeNil()) - }) - - It("reports that the AfterSuite node ran", func() { - Ω(fakeR.AfterSuiteSummary).ShouldNot(BeNil()) - }) - - It("provides information about the current test", func() { - description := CurrentGinkgoTestDescription() - Ω(description.ComponentTexts).Should(Equal([]string{"Suite", "running a suite", "provides information about the current test"})) - Ω(description.FullTestText).Should(Equal("Suite running a suite provides information about the current test")) - Ω(description.TestText).Should(Equal("provides information about the current test")) - Ω(description.IsMeasurement).Should(BeFalse()) - Ω(description.FileName).Should(ContainSubstring("suite_test.go")) - Ω(description.LineNumber).Should(BeNumerically(">", 50)) - Ω(description.LineNumber).Should(BeNumerically("<", 150)) - Ω(description.Failed).Should(BeFalse()) - }) - - Measure("should run measurements", func(b Benchmarker) { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - - runtime := b.Time("sleeping", func() { - sleepTime := time.Duration(r.Float64() * 0.01 * float64(time.Second)) - time.Sleep(sleepTime) - }) - Ω(runtime.Seconds()).Should(BeNumerically("<=", 1)) - Ω(runtime.Seconds()).Should(BeNumerically(">=", 0)) - - randomValue := r.Float64() * 10.0 - b.RecordValue("random value", randomValue) - Ω(randomValue).Should(BeNumerically("<=", 10.0)) - Ω(randomValue).Should(BeNumerically(">=", 0.0)) - - b.RecordValueWithPrecision("specific value", 123.4567, "ms", 2) - b.RecordValueWithPrecision("specific value", 234.5678, "ms", 2) - }, 10) - - It("creates a node hierarchy, converts it to a spec collection, and runs it", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "top BE", "top JBE", "top IT", "top AE", - "AfterSuite", - })) - }) - - Context("when told to randomize all specs", func() { - BeforeEach(func() { - randomizeAllSpecs = true - }) - - It("does", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "top IT", "top AE", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE", "top JBE", "JBE", "IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - }) - - Context("when provided with a filter", func() { - BeforeEach(func() { - focusString = `inner|\d` - }) - - It("converts the filter to a regular expression and uses it to filter the running specs", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "BE", "top JBE", "JBE", "inner IT", "AE", "top AE", - "top BE", "BE 2", "top JBE", "IT 2", "top AE", - "AfterSuite", - })) - }) - - It("should not report a programmatic focus", func() { - Ω(hasProgrammaticFocus).Should(BeFalse()) - }) - }) - - Context("with a programatically focused spec", func() { - BeforeEach(func() { - specSuite.PushItNode("focused it", f("focused it"), types.FlagTypeFocused, codelocation.New(0), 0) - - specSuite.PushContainerNode("focused container", func() { - specSuite.PushItNode("inner focused it", f("inner focused it"), types.FlagTypeFocused, codelocation.New(0), 0) - specSuite.PushItNode("inner unfocused it", f("inner unfocused it"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeFocused, codelocation.New(0)) - - }) - - It("should only run the focused test, applying backpropagation to favor most deeply focused leaf nodes", func() { - Ω(runOrder).Should(Equal([]string{ - "BeforeSuite", - "top BE", "top JBE", "focused it", "top AE", - "top BE", "top JBE", "inner focused it", "top AE", - "AfterSuite", - })) - }) - - It("should report a programmatic focus", func() { - Ω(hasProgrammaticFocus).Should(BeTrue()) - }) - }) - - Context("when the specs pass", func() { - It("doesn't report a failure", func() { - Ω(fakeT.didFail).Should(BeFalse()) - }) - - It("should return true", func() { - Ω(runResult).Should(BeTrue()) - }) - }) - - Context("when a spec fails", func() { - var location types.CodeLocation - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - location = codelocation.New(0) - failer.Fail("oops!", location) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should return false", func() { - Ω(runResult).Should(BeFalse()) - }) - - It("reports a failure", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - - It("generates the correct failure data", func() { - Ω(fakeR.SpecSummaries[0].Failure.Message).Should(Equal("oops!")) - Ω(fakeR.SpecSummaries[0].Failure.Location).Should(Equal(location)) - }) - }) - - Context("when runnable nodes are nested within other runnable nodes", func() { - Context("when an It is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushItNode("nested it", f("oops"), types.FlagTypeNone, codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a Measure is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushMeasureNode("nested measure", func(Benchmarker) {}, types.FlagTypeNone, codelocation.New(0), 10) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a BeforeEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushBeforeEachNode(f("nested bef"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a JustBeforeEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushJustBeforeEachNode(f("nested jbef"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - - Context("when a AfterEach is nested", func() { - BeforeEach(func() { - specSuite.PushItNode("top level it", func() { - specSuite.PushAfterEachNode(f("nested aft"), codelocation.New(0), 0) - }, types.FlagTypeNone, codelocation.New(0), 0) - }) - - It("should fail", func() { - Ω(fakeT.didFail).Should(BeTrue()) - }) - }) - }) - }) - - Describe("BeforeSuite", func() { - Context("when setting BeforeSuite more than once", func() { - It("should panic", func() { - specSuite.SetBeforeSuiteNode(func() {}, codelocation.New(0), 0) - - Ω(func() { - specSuite.SetBeforeSuiteNode(func() {}, codelocation.New(0), 0) - }).Should(Panic()) - - }) - }) - }) - - Describe("AfterSuite", func() { - Context("when setting AfterSuite more than once", func() { - It("should panic", func() { - specSuite.SetAfterSuiteNode(func() {}, codelocation.New(0), 0) - - Ω(func() { - specSuite.SetAfterSuiteNode(func() {}, codelocation.New(0), 0) - }).Should(Panic()) - }) - }) - }) - - Describe("By", func() { - It("writes to the GinkgoWriter", func() { - originalGinkgoWriter := GinkgoWriter - buffer := &bytes.Buffer{} - - GinkgoWriter = buffer - By("Saying Hello GinkgoWriter") - GinkgoWriter = originalGinkgoWriter - - Ω(buffer.String()).Should(ContainSubstring("STEP")) - Ω(buffer.String()).Should(ContainSubstring(": Saying Hello GinkgoWriter\n")) - }) - - It("calls the passed-in callback if present", func() { - a := 0 - By("calling the callback", func() { - a = 1 - }) - Ω(a).Should(Equal(1)) - }) - - It("panics if there is more than one callback", func() { - Ω(func() { - By("registering more than one callback", func() {}, func() {}) - }).Should(Panic()) - }) - }) - - Describe("GinkgoRandomSeed", func() { - It("returns the current config's random seed", func() { - Ω(GinkgoRandomSeed()).Should(Equal(config.GinkgoConfig.RandomSeed)) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go b/vendor/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go deleted file mode 100644 index e206577919..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/writer/writer_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package writer_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestWriter(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Writer Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/writer/writer_test.go b/vendor/github.com/onsi/ginkgo/internal/writer/writer_test.go deleted file mode 100644 index 3e1d17c6d5..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/writer/writer_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package writer_test - -import ( - "github.com/onsi/gomega/gbytes" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/internal/writer" - . "github.com/onsi/gomega" -) - -var _ = Describe("Writer", func() { - var writer *Writer - var out *gbytes.Buffer - - BeforeEach(func() { - out = gbytes.NewBuffer() - writer = New(out) - }) - - It("should stream directly to the outbuffer by default", func() { - writer.Write([]byte("foo")) - Ω(out).Should(gbytes.Say("foo")) - }) - - It("should not emit the header when asked to DumpOutWitHeader", func() { - writer.Write([]byte("foo")) - writer.DumpOutWithHeader("my header") - Ω(out).ShouldNot(gbytes.Say("my header")) - Ω(out).Should(gbytes.Say("foo")) - }) - - Context("when told not to stream", func() { - BeforeEach(func() { - writer.SetStream(false) - }) - - It("should only write to the buffer when told to DumpOut", func() { - writer.Write([]byte("foo")) - Ω(out).ShouldNot(gbytes.Say("foo")) - writer.DumpOut() - Ω(out).Should(gbytes.Say("foo")) - }) - - It("should truncate the internal buffer when told to truncate", func() { - writer.Write([]byte("foo")) - writer.Truncate() - writer.DumpOut() - Ω(out).ShouldNot(gbytes.Say("foo")) - - writer.Write([]byte("bar")) - writer.DumpOut() - Ω(out).Should(gbytes.Say("bar")) - }) - - Describe("emitting a header", func() { - Context("when the buffer has content", func() { - It("should emit the header followed by the content", func() { - writer.Write([]byte("foo")) - writer.DumpOutWithHeader("my header") - - Ω(out).Should(gbytes.Say("my header")) - Ω(out).Should(gbytes.Say("foo")) - }) - }) - - Context("when the buffer has no content", func() { - It("should not emit the header", func() { - writer.DumpOutWithHeader("my header") - - Ω(out).ShouldNot(gbytes.Say("my header")) - }) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/reporters/default_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/default_reporter.go index fb82f70a6d..ac58dd5f7a 100644 --- a/vendor/github.com/onsi/ginkgo/reporters/default_reporter.go +++ b/vendor/github.com/onsi/ginkgo/reporters/default_reporter.go @@ -66,7 +66,7 @@ func (reporter *DefaultReporter) SpecDidComplete(specSummary *types.SpecSummary) case types.SpecStatePending: reporter.stenographer.AnnouncePendingSpec(specSummary, reporter.config.NoisyPendings && !reporter.config.Succinct) case types.SpecStateSkipped: - reporter.stenographer.AnnounceSkippedSpec(specSummary, reporter.config.Succinct, reporter.config.FullTrace) + reporter.stenographer.AnnounceSkippedSpec(specSummary, reporter.config.Succinct || !reporter.config.NoisySkippings, reporter.config.FullTrace) case types.SpecStateTimedOut: reporter.stenographer.AnnounceSpecTimedOut(specSummary, reporter.config.Succinct, reporter.config.FullTrace) case types.SpecStatePanicked: diff --git a/vendor/github.com/onsi/ginkgo/reporters/default_reporter_test.go b/vendor/github.com/onsi/ginkgo/reporters/default_reporter_test.go deleted file mode 100644 index 01528448ea..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/default_reporter_test.go +++ /dev/null @@ -1,414 +0,0 @@ -package reporters_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - st "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("DefaultReporter", func() { - var ( - reporter *reporters.DefaultReporter - reporterConfig config.DefaultReporterConfigType - stenographer *st.FakeStenographer - - ginkgoConfig config.GinkgoConfigType - suite *types.SuiteSummary - spec *types.SpecSummary - ) - - BeforeEach(func() { - stenographer = st.NewFakeStenographer() - reporterConfig = config.DefaultReporterConfigType{ - NoColor: false, - SlowSpecThreshold: 0.1, - NoisyPendings: false, - Verbose: true, - FullTrace: true, - } - - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - }) - - call := func(method string, args ...interface{}) st.FakeStenographerCall { - return st.NewFakeStenographerCall(method, args...) - } - - Describe("SpecSuiteWillBegin", func() { - BeforeEach(func() { - suite = &types.SuiteSummary{ - SuiteDescription: "A Sweet Suite", - NumberOfTotalSpecs: 10, - NumberOfSpecsThatWillBeRun: 8, - } - - ginkgoConfig = config.GinkgoConfigType{ - RandomSeed: 1138, - RandomizeAllSpecs: true, - } - }) - - Context("when a serial (non-parallel) suite begins", func() { - BeforeEach(func() { - ginkgoConfig.ParallelTotal = 1 - - reporter.SpecSuiteWillBegin(ginkgoConfig, suite) - }) - - It("should announce the suite, then announce the number of specs", func() { - Ω(stenographer.Calls()).Should(HaveLen(2)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", "A Sweet Suite", ginkgoConfig.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceNumberOfSpecs", 8, 10, false))) - }) - }) - - Context("when a parallel suite begins", func() { - BeforeEach(func() { - ginkgoConfig.ParallelTotal = 2 - ginkgoConfig.ParallelNode = 1 - suite.NumberOfSpecsBeforeParallelization = 20 - - reporter.SpecSuiteWillBegin(ginkgoConfig, suite) - }) - - It("should announce the suite, announce that it's a parallel run, then announce the number of specs", func() { - Ω(stenographer.Calls()).Should(HaveLen(2)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuite", "A Sweet Suite", ginkgoConfig.RandomSeed, true, false))) - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceParallelRun", 1, 2, false))) - }) - }) - }) - - Describe("BeforeSuiteDidRun", func() { - Context("when the BeforeSuite passes", func() { - It("should announce nothing", func() { - reporter.BeforeSuiteDidRun(&types.SetupSummary{ - State: types.SpecStatePassed, - }) - - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("when the BeforeSuite fails", func() { - It("should announce the failure", func() { - summary := &types.SetupSummary{ - State: types.SpecStateFailed, - } - reporter.BeforeSuiteDidRun(summary) - - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceBeforeSuiteFailure", summary, false, true))) - }) - }) - }) - - Describe("AfterSuiteDidRun", func() { - Context("when the AfterSuite passes", func() { - It("should announce nothing", func() { - reporter.AfterSuiteDidRun(&types.SetupSummary{ - State: types.SpecStatePassed, - }) - - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("when the AfterSuite fails", func() { - It("should announce the failure", func() { - summary := &types.SetupSummary{ - State: types.SpecStateFailed, - } - reporter.AfterSuiteDidRun(summary) - - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceAfterSuiteFailure", summary, false, true))) - }) - }) - }) - - Describe("SpecWillRun", func() { - Context("When running in verbose mode", func() { - Context("and the spec will run", func() { - BeforeEach(func() { - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce that the spec will run", func() { - Ω(stenographer.Calls()).Should(HaveLen(1)) - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecWillRun", spec))) - }) - }) - - Context("and the spec will not run", func() { - Context("because it is pending", func() { - BeforeEach(func() { - spec = &types.SpecSummary{ - State: types.SpecStatePending, - } - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("because it is skipped", func() { - BeforeEach(func() { - spec = &types.SpecSummary{ - State: types.SpecStateSkipped, - } - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - }) - }) - - Context("When running in verbose & succinct mode", func() { - BeforeEach(func() { - reporterConfig.Succinct = true - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - - Context("When not running in verbose mode", func() { - BeforeEach(func() { - reporterConfig.Verbose = false - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - spec = &types.SpecSummary{} - reporter.SpecWillRun(spec) - }) - - It("should announce nothing", func() { - Ω(stenographer.Calls()).Should(BeEmpty()) - }) - }) - }) - - Describe("SpecDidComplete", func() { - JustBeforeEach(func() { - reporter.SpecDidComplete(spec) - }) - - BeforeEach(func() { - spec = &types.SpecSummary{} - }) - - Context("When the spec passed", func() { - BeforeEach(func() { - spec.State = types.SpecStatePassed - }) - - Context("When the spec was a measurement", func() { - BeforeEach(func() { - spec.IsMeasurement = true - }) - - It("should announce the measurement", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulMeasurement", spec, false))) - }) - }) - - Context("When the spec is slow", func() { - BeforeEach(func() { - spec.RunTime = time.Second - }) - - It("should announce that it was slow", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSlowSpec", spec, false))) - }) - }) - - Context("Otherwise", func() { - It("should announce the succesful spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSpec", spec))) - }) - }) - }) - - Context("When the spec is pending", func() { - BeforeEach(func() { - spec.State = types.SpecStatePending - }) - - It("should announce the pending spec, succinctly", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnouncePendingSpec", spec, false))) - }) - }) - - Context("When the spec is skipped", func() { - BeforeEach(func() { - spec.State = types.SpecStateSkipped - }) - - It("should announce the skipped spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSkippedSpec", spec, false, true))) - }) - }) - - Context("When the spec timed out", func() { - BeforeEach(func() { - spec.State = types.SpecStateTimedOut - }) - - It("should announce the timedout spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecTimedOut", spec, false, true))) - }) - }) - - Context("When the spec panicked", func() { - BeforeEach(func() { - spec.State = types.SpecStatePanicked - }) - - It("should announce the panicked spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecPanicked", spec, false, true))) - }) - }) - - Context("When the spec failed", func() { - BeforeEach(func() { - spec.State = types.SpecStateFailed - }) - - It("should announce the failed spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecFailed", spec, false, true))) - }) - }) - - Context("in noisy pendings mode", func() { - BeforeEach(func() { - reporterConfig.Succinct = false - reporterConfig.NoisyPendings = true - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - }) - - Context("When the spec is pending", func() { - BeforeEach(func() { - spec.State = types.SpecStatePending - }) - - It("should announce the pending spec, noisily", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnouncePendingSpec", spec, true))) - }) - }) - }) - - Context("in succinct mode", func() { - BeforeEach(func() { - reporterConfig.Succinct = true - reporter = reporters.NewDefaultReporter(reporterConfig, stenographer) - }) - - Context("When the spec passed", func() { - BeforeEach(func() { - spec.State = types.SpecStatePassed - }) - - Context("When the spec was a measurement", func() { - BeforeEach(func() { - spec.IsMeasurement = true - }) - - It("should announce the measurement", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulMeasurement", spec, true))) - }) - }) - - Context("When the spec is slow", func() { - BeforeEach(func() { - spec.RunTime = time.Second - }) - - It("should announce that it was slow", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSlowSpec", spec, true))) - }) - }) - - Context("Otherwise", func() { - It("should announce the succesful spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSuccesfulSpec", spec))) - }) - }) - }) - - Context("When the spec is pending", func() { - BeforeEach(func() { - spec.State = types.SpecStatePending - }) - - It("should announce the pending spec, succinctly", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnouncePendingSpec", spec, false))) - }) - }) - - Context("When the spec is skipped", func() { - BeforeEach(func() { - spec.State = types.SpecStateSkipped - }) - - It("should announce the skipped spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSkippedSpec", spec, true, true))) - }) - }) - - Context("When the spec timed out", func() { - BeforeEach(func() { - spec.State = types.SpecStateTimedOut - }) - - It("should announce the timedout spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecTimedOut", spec, true, true))) - }) - }) - - Context("When the spec panicked", func() { - BeforeEach(func() { - spec.State = types.SpecStatePanicked - }) - - It("should announce the panicked spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecPanicked", spec, true, true))) - }) - }) - - Context("When the spec failed", func() { - BeforeEach(func() { - spec.State = types.SpecStateFailed - }) - - It("should announce the failed spec", func() { - Ω(stenographer.Calls()[0]).Should(Equal(call("AnnounceSpecFailed", spec, true, true))) - }) - }) - }) - }) - - Describe("SpecSuiteDidEnd", func() { - BeforeEach(func() { - suite = &types.SuiteSummary{} - reporter.SpecSuiteDidEnd(suite) - }) - - It("should announce the spec run's completion", func() { - Ω(stenographer.Calls()[1]).Should(Equal(call("AnnounceSpecRunCompletion", suite, false))) - }) - }) -}) diff --git a/vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go index 89b03513fd..a2b5fc6533 100644 --- a/vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go +++ b/vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go @@ -21,6 +21,7 @@ import ( type JUnitTestSuite struct { XMLName xml.Name `xml:"testsuite"` TestCases []JUnitTestCase `xml:"testcase"` + Name string `xml:"name,attr"` Tests int `xml:"tests,attr"` Failures int `xml:"failures,attr"` Time float64 `xml:"time,attr"` @@ -59,6 +60,7 @@ func NewJUnitReporter(filename string) *JUnitReporter { func (reporter *JUnitReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { reporter.suite = JUnitTestSuite{ + Name: summary.SuiteDescription, TestCases: []JUnitTestCase{}, } reporter.testSuiteName = summary.SuiteDescription diff --git a/vendor/github.com/onsi/ginkgo/reporters/junit_reporter_test.go b/vendor/github.com/onsi/ginkgo/reporters/junit_reporter_test.go deleted file mode 100644 index 37a6daabdf..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/junit_reporter_test.go +++ /dev/null @@ -1,247 +0,0 @@ -package reporters_test - -import ( - "encoding/xml" - "io/ioutil" - "os" - "time" - - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" -) - -var _ = Describe("JUnit Reporter", func() { - var ( - outputFile string - reporter Reporter - ) - - readOutputFile := func() reporters.JUnitTestSuite { - bytes, err := ioutil.ReadFile(outputFile) - Ω(err).ShouldNot(HaveOccurred()) - var suite reporters.JUnitTestSuite - err = xml.Unmarshal(bytes, &suite) - Ω(err).ShouldNot(HaveOccurred()) - return suite - } - - BeforeEach(func() { - f, err := ioutil.TempFile("", "output") - Ω(err).ShouldNot(HaveOccurred()) - f.Close() - outputFile = f.Name() - - reporter = reporters.NewJUnitReporter(outputFile) - - reporter.SpecSuiteWillBegin(config.GinkgoConfigType{}, &types.SuiteSummary{ - SuiteDescription: "My test suite", - NumberOfSpecsThatWillBeRun: 1, - }) - }) - - AfterEach(func() { - os.RemoveAll(outputFile) - }) - - Describe("a passing test", func() { - BeforeEach(func() { - beforeSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - afterSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.AfterSuiteDidRun(afterSuite) - - spec := &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: types.SpecStatePassed, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as passing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(0)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases).Should(HaveLen(1)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage).Should(BeNil()) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - Ω(output.TestCases[0].Time).Should(Equal(5.0)) - }) - }) - - Describe("when the BeforeSuite fails", func() { - var beforeSuite *types.SetupSummary - - BeforeEach(func() { - beforeSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup", - ComponentCodeLocation: codelocation.New(0), - Location: codelocation.New(2), - }, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("BeforeSuite")) - Ω(output.TestCases[0].Time).Should(Equal(3.0)) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal("Failure")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("failed to setup")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(beforeSuite.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(beforeSuite.Failure.Location.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - - Describe("when the AfterSuite fails", func() { - var afterSuite *types.SetupSummary - - BeforeEach(func() { - afterSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup", - ComponentCodeLocation: codelocation.New(0), - Location: codelocation.New(2), - }, - } - reporter.AfterSuiteDidRun(afterSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("AfterSuite")) - Ω(output.TestCases[0].Time).Should(Equal(3.0)) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal("Failure")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("failed to setup")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(afterSuite.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(afterSuite.Failure.Location.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - - specStateCases := []struct { - state types.SpecState - message string - }{ - {types.SpecStateFailed, "Failure"}, - {types.SpecStateTimedOut, "Timeout"}, - {types.SpecStatePanicked, "Panic"}, - } - - for _, specStateCase := range specStateCases { - specStateCase := specStateCase - Describe("a failing test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase.state, - RunTime: 5 * time.Second, - Failure: types.SpecFailure{ - ComponentCodeLocation: codelocation.New(0), - Location: codelocation.New(2), - Message: "I failed", - }, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(1)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].ClassName).Should(Equal("My test suite")) - Ω(output.TestCases[0].FailureMessage.Type).Should(Equal(specStateCase.message)) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring("I failed")) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(spec.Failure.ComponentCodeLocation.String())) - Ω(output.TestCases[0].FailureMessage.Message).Should(ContainSubstring(spec.Failure.Location.String())) - Ω(output.TestCases[0].Skipped).Should(BeNil()) - }) - }) - } - - for _, specStateCase := range []types.SpecState{types.SpecStatePending, types.SpecStateSkipped} { - specStateCase := specStateCase - Describe("a skipped test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - output := readOutputFile() - Ω(output.Tests).Should(Equal(1)) - Ω(output.Failures).Should(Equal(0)) - Ω(output.Time).Should(Equal(10.0)) - Ω(output.TestCases[0].Name).Should(Equal("A B C")) - Ω(output.TestCases[0].Skipped).ShouldNot(BeNil()) - }) - }) - } -}) diff --git a/vendor/github.com/onsi/ginkgo/reporters/reporters_suite_test.go b/vendor/github.com/onsi/ginkgo/reporters/reporters_suite_test.go deleted file mode 100644 index cec5a4dbfb..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/reporters_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package reporters_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestReporters(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Reporters Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go index fefd3e182f..600192a0ad 100644 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go +++ b/vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go @@ -178,7 +178,7 @@ func (s *consoleStenographer) AnnounceSpecRunCompletion(summary *types.SuiteSumm } s.print(0, - "%s -- %s | %s | %s | %s ", + "%s -- %s | %s | %s | %s\n", status, s.colorize(greenColor+boldStyle, "%d Passed", summary.NumberOfPassedSpecs), s.colorize(redColor+boldStyle, "%d Failed", summary.NumberOfFailedSpecs)+flakes, diff --git a/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go index 657dfe726e..36ee2a6005 100644 --- a/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go +++ b/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go @@ -10,10 +10,11 @@ package reporters import ( "fmt" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" "io" "strings" + + "github.com/onsi/ginkgo/config" + "github.com/onsi/ginkgo/types" ) const ( diff --git a/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go b/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go deleted file mode 100644 index de87732113..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter_test.go +++ /dev/null @@ -1,213 +0,0 @@ -package reporters_test - -import ( - "bytes" - "fmt" - . "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - "time" -) - -var _ = Describe("TeamCity Reporter", func() { - var ( - buffer bytes.Buffer - reporter Reporter - ) - - BeforeEach(func() { - buffer.Truncate(0) - reporter = reporters.NewTeamCityReporter(&buffer) - reporter.SpecSuiteWillBegin(config.GinkgoConfigType{}, &types.SuiteSummary{ - SuiteDescription: "Foo's test suite", - NumberOfSpecsThatWillBeRun: 1, - }) - }) - - Describe("a passing test", func() { - BeforeEach(func() { - beforeSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - afterSuite := &types.SetupSummary{ - State: types.SpecStatePassed, - } - reporter.AfterSuiteDidRun(afterSuite) - - spec := &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: types.SpecStatePassed, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as passing", func() { - actual := buffer.String() - expected := - "##teamcity[testSuiteStarted name='Foo|'s test suite']" + - "##teamcity[testStarted name='A B C']" + - "##teamcity[testFinished name='A B C' duration='5000']" + - "##teamcity[testSuiteFinished name='Foo|'s test suite']" - Ω(actual).Should(Equal(expected)) - }) - }) - - Describe("when the BeforeSuite fails", func() { - var beforeSuite *types.SetupSummary - - BeforeEach(func() { - beforeSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup\n", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.BeforeSuiteDidRun(beforeSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - actual := buffer.String() - expected := fmt.Sprintf( - "##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='BeforeSuite']"+ - "##teamcity[testFailed name='BeforeSuite' message='%s' details='failed to setup|n']"+ - "##teamcity[testFinished name='BeforeSuite' duration='3000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", beforeSuite.Failure.ComponentCodeLocation.String(), - ) - Ω(actual).Should(Equal(expected)) - }) - }) - - Describe("when the AfterSuite fails", func() { - var afterSuite *types.SetupSummary - - BeforeEach(func() { - afterSuite = &types.SetupSummary{ - State: types.SpecStateFailed, - RunTime: 3 * time.Second, - Failure: types.SpecFailure{ - Message: "failed to setup\n", - ComponentCodeLocation: codelocation.New(0), - }, - } - reporter.AfterSuiteDidRun(afterSuite) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record the test as having failed", func() { - actual := buffer.String() - expected := fmt.Sprintf( - "##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='AfterSuite']"+ - "##teamcity[testFailed name='AfterSuite' message='%s' details='failed to setup|n']"+ - "##teamcity[testFinished name='AfterSuite' duration='3000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", afterSuite.Failure.ComponentCodeLocation.String(), - ) - Ω(actual).Should(Equal(expected)) - }) - }) - specStateCases := []struct { - state types.SpecState - message string - }{ - {types.SpecStateFailed, "Failure"}, - {types.SpecStateTimedOut, "Timeout"}, - {types.SpecStatePanicked, "Panic"}, - } - - for _, specStateCase := range specStateCases { - specStateCase := specStateCase - Describe("a failing test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase.state, - RunTime: 5 * time.Second, - Failure: types.SpecFailure{ - ComponentCodeLocation: codelocation.New(0), - Message: "I failed", - }, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 1, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as failing", func() { - actual := buffer.String() - expected := - fmt.Sprintf("##teamcity[testSuiteStarted name='Foo|'s test suite']"+ - "##teamcity[testStarted name='A B C']"+ - "##teamcity[testFailed name='A B C' message='%s' details='I failed']"+ - "##teamcity[testFinished name='A B C' duration='5000']"+ - "##teamcity[testSuiteFinished name='Foo|'s test suite']", spec.Failure.ComponentCodeLocation.String()) - Ω(actual).Should(Equal(expected)) - }) - }) - } - - for _, specStateCase := range []types.SpecState{types.SpecStatePending, types.SpecStateSkipped} { - specStateCase := specStateCase - Describe("a skipped test", func() { - var spec *types.SpecSummary - BeforeEach(func() { - spec = &types.SpecSummary{ - ComponentTexts: []string{"[Top Level]", "A", "B", "C"}, - State: specStateCase, - RunTime: 5 * time.Second, - } - reporter.SpecWillRun(spec) - reporter.SpecDidComplete(spec) - - reporter.SpecSuiteDidEnd(&types.SuiteSummary{ - NumberOfSpecsThatWillBeRun: 1, - NumberOfFailedSpecs: 0, - RunTime: 10 * time.Second, - }) - }) - - It("should record test as ignored", func() { - actual := buffer.String() - expected := - "##teamcity[testSuiteStarted name='Foo|'s test suite']" + - "##teamcity[testStarted name='A B C']" + - "##teamcity[testIgnored name='A B C']" + - "##teamcity[testFinished name='A B C' duration='5000']" + - "##teamcity[testSuiteFinished name='Foo|'s test suite']" - Ω(actual).Should(Equal(expected)) - }) - }) - } -}) diff --git a/vendor/github.com/onsi/ginkgo/types/types_suite_test.go b/vendor/github.com/onsi/ginkgo/types/types_suite_test.go deleted file mode 100644 index b026169c12..0000000000 --- a/vendor/github.com/onsi/ginkgo/types/types_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package types_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestTypes(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Types Suite") -} diff --git a/vendor/github.com/onsi/ginkgo/types/types_test.go b/vendor/github.com/onsi/ginkgo/types/types_test.go deleted file mode 100644 index a0e161c888..0000000000 --- a/vendor/github.com/onsi/ginkgo/types/types_test.go +++ /dev/null @@ -1,99 +0,0 @@ -package types_test - -import ( - . "github.com/onsi/ginkgo/types" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var specStates = []SpecState{ - SpecStatePassed, - SpecStateTimedOut, - SpecStatePanicked, - SpecStateFailed, - SpecStatePending, - SpecStateSkipped, -} - -func verifySpecSummary(caller func(SpecSummary) bool, trueStates ...SpecState) { - summary := SpecSummary{} - trueStateLookup := map[SpecState]bool{} - for _, state := range trueStates { - trueStateLookup[state] = true - summary.State = state - Ω(caller(summary)).Should(BeTrue()) - } - - for _, state := range specStates { - if trueStateLookup[state] { - continue - } - summary.State = state - Ω(caller(summary)).Should(BeFalse()) - } -} - -var _ = Describe("Types", func() { - Describe("IsFailureState", func() { - It("knows when it is in a failure-like state", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.State.IsFailure() - }, SpecStateTimedOut, SpecStatePanicked, SpecStateFailed) - }) - }) - - Describe("SpecSummary", func() { - It("knows when it is in a failure-like state", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.HasFailureState() - }, SpecStateTimedOut, SpecStatePanicked, SpecStateFailed) - }) - - It("knows when it passed", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Passed() - }, SpecStatePassed) - }) - - It("knows when it has failed", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Failed() - }, SpecStateFailed) - }) - - It("knows when it has panicked", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Panicked() - }, SpecStatePanicked) - }) - - It("knows when it has timed out", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.TimedOut() - }, SpecStateTimedOut) - }) - - It("knows when it is pending", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Pending() - }, SpecStatePending) - }) - - It("knows when it is skipped", func() { - verifySpecSummary(func(summary SpecSummary) bool { - return summary.Skipped() - }, SpecStateSkipped) - }) - }) - - Describe("SpecMeasurement", func() { - It("knows how to format values when the precision is 0", func() { - Ω(SpecMeasurement{}.PrecisionFmt()).Should(Equal("%f")) - }) - - It("knows how to format the values when the precision is 3", func() { - Ω(SpecMeasurement{Precision: 3}.PrecisionFmt()).Should(Equal("%.3f")) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/.travis.yml b/vendor/github.com/onsi/gomega/.travis.yml index 61d0f41faf..8b982a9abb 100644 --- a/vendor/github.com/onsi/gomega/.travis.yml +++ b/vendor/github.com/onsi/gomega/.travis.yml @@ -1,12 +1,14 @@ language: go go: - - 1.6 - - 1.7 - - 1.8 + - 1.6.x + - 1.7.x + - 1.8.x + - 1.9.x + - 1.10.x install: - go get -v ./... - go get github.com/onsi/ginkgo - go install github.com/onsi/ginkgo/ginkgo -script: $HOME/gopath/bin/ginkgo -r --randomizeAllSpecs --failOnPending --randomizeSuites --race +script: $HOME/gopath/bin/ginkgo -p -r --randomizeAllSpecs --failOnPending --randomizeSuites --race && go vet diff --git a/vendor/github.com/onsi/gomega/CHANGELOG.md b/vendor/github.com/onsi/gomega/CHANGELOG.md index a3e8ee4447..2ee5d9b741 100644 --- a/vendor/github.com/onsi/gomega/CHANGELOG.md +++ b/vendor/github.com/onsi/gomega/CHANGELOG.md @@ -1,5 +1,30 @@ ## HEAD +### Features +- Make string pretty diff user configurable (#273) [eb112ce, 649b44d] + +### Fixes +- Use httputil.DumpRequest to pretty-print unhandled requests (#278) [a4ff0fc, b7d1a52] +- fix typo floa32 > float32 (#272) [041ae3b, 6e33911] +- Fix link to documentation on adding your own matchers (#270) [bb2c830, fcebc62] +- Use setters and getters to avoid race condition (#262) [13057c3, a9c79f1] +- Avoid sending a signal if the process is not alive (#259) [b8043e5, 4fc1762] +- Improve message from AssignableToTypeOf when expected value is nil (#281) [9c1fb20] + +## 1.3.0 + +Improvements: + +- The `Equal` matcher matches byte slices more performantly. +- Improved how `MatchError` matches error strings. +- `MatchXML` ignores the order of xml node attributes. +- Improve support for XUnit style golang tests. ([#254](https://github.com/onsi/gomega/issues/254)) + +Bug Fixes: + +- Diff generation now handles multi-byte sequences correctly. +- Multiple goroutines can now call `gexec.Build` concurrently. + ## 1.2.0 Improvements: diff --git a/vendor/github.com/onsi/gomega/CONTRIBUTING.md b/vendor/github.com/onsi/gomega/CONTRIBUTING.md index 73d4020e6b..0d7a099289 100644 --- a/vendor/github.com/onsi/gomega/CONTRIBUTING.md +++ b/vendor/github.com/onsi/gomega/CONTRIBUTING.md @@ -6,6 +6,9 @@ Your contributions to Gomega are essential for its long-term maintenance and imp - Ensure adequate test coverage: - Make sure to add appropriate unit tests - Please run all tests locally (`ginkgo -r -p`) and make sure they go green before submitting the PR + - Please run following linter locally `go vet ./...` and make sure output does not contain any warnings - Update the documentation. In addition to standard `godoc` comments Gomega has extensive documentation on the `gh-pages` branch. If relevant, please submit a docs PR to that branch alongside your code PR. -Thanks for supporting Gomega! \ No newline at end of file +If you're a committer, check out RELEASING.md to learn how to cut a release. + +Thanks for supporting Gomega! diff --git a/vendor/github.com/onsi/gomega/RELEASING.md b/vendor/github.com/onsi/gomega/RELEASING.md new file mode 100644 index 0000000000..998d64ee75 --- /dev/null +++ b/vendor/github.com/onsi/gomega/RELEASING.md @@ -0,0 +1,12 @@ +A Gomega release is a tagged sha and a GitHub release. To cut a release: + +1. Ensure CHANGELOG.md is up to date. + - Use `git log --pretty=format:'- %s [%h]' HEAD...vX.X.X` to list all the commits since the last release + - Categorize the changes into + - Breaking Changes (requires a major version) + - New Features (minor version) + - Fixes (fix version) + - Maintenance (which in general should not be mentioned in `CHANGELOG.md` as they have no user impact) +2. Update GOMEGA_VERSION in `gomega_dsl.go` +3. Push a commit with the version number as the commit message (e.g. `v1.3.0`) +4. Create a new [GitHub release](https://help.github.com/articles/creating-releases/) with the version number as the tag (e.g. `v1.3.0`). List the key changes in the release notes. diff --git a/vendor/github.com/onsi/gomega/format/format.go b/vendor/github.com/onsi/gomega/format/format.go index e206ee59a4..6559525f1c 100644 --- a/vendor/github.com/onsi/gomega/format/format.go +++ b/vendor/github.com/onsi/gomega/format/format.go @@ -30,6 +30,9 @@ Set PrintContextObjects = true to enable printing of the context internals. */ var PrintContextObjects = false +// TruncatedDiff choose if we should display a truncated pretty diff or not +var TruncatedDiff = true + // Ctx interface defined here to keep backwards compatability with go < 1.7 // It matches the context.Context interface type Ctx interface { @@ -82,7 +85,7 @@ to equal | */ func MessageWithDiff(actual, message, expected string) string { - if len(actual) >= truncateThreshold && len(expected) >= truncateThreshold { + if TruncatedDiff && len(actual) >= truncateThreshold && len(expected) >= truncateThreshold { diffPoint := findFirstMismatch(actual, expected) formattedActual := truncateAndFormat(actual, diffPoint) formattedExpected := truncateAndFormat(expected, diffPoint) @@ -123,7 +126,7 @@ func findFirstMismatch(a, b string) int { bSlice := strings.Split(b, "") for index, str := range aSlice { - if index > len(b) - 1 { + if index > len(bSlice)-1 { return index } if str != bSlice[index] { diff --git a/vendor/github.com/onsi/gomega/format/format_suite_test.go b/vendor/github.com/onsi/gomega/format/format_suite_test.go deleted file mode 100644 index 8e65a95292..0000000000 --- a/vendor/github.com/onsi/gomega/format/format_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package format_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestFormat(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Format Suite") -} diff --git a/vendor/github.com/onsi/gomega/format/format_test.go b/vendor/github.com/onsi/gomega/format/format_test.go deleted file mode 100644 index a1a9031640..0000000000 --- a/vendor/github.com/onsi/gomega/format/format_test.go +++ /dev/null @@ -1,590 +0,0 @@ -package format_test - -import ( - "fmt" - "strings" - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/format" - "github.com/onsi/gomega/types" -) - -//recursive struct - -type StringAlias string -type ByteAlias []byte -type IntAlias int - -type AStruct struct { - Exported string -} - -type SimpleStruct struct { - Name string - Enumeration int - Veritas bool - Data []byte - secret uint32 -} - -type ComplexStruct struct { - Strings []string - SimpleThings []*SimpleStruct - DataMaps map[int]ByteAlias -} - -type SecretiveStruct struct { - boolValue bool - intValue int - uintValue uint - uintptrValue uintptr - floatValue float32 - complexValue complex64 - chanValue chan bool - funcValue func() - pointerValue *int - sliceValue []string - byteSliceValue []byte - stringValue string - arrValue [3]int - byteArrValue [3]byte - mapValue map[string]int - structValue AStruct - interfaceValue interface{} -} - -type GoStringer struct { -} - -func (g GoStringer) GoString() string { - return "go-string" -} - -func (g GoStringer) String() string { - return "string" -} - -type Stringer struct { -} - -func (g Stringer) String() string { - return "string" -} - -type ctx struct { -} - -func (c *ctx) Deadline() (deadline time.Time, ok bool) { - return time.Time{}, false -} - -func (c *ctx) Done() <-chan struct{} { - return nil -} - -func (c *ctx) Err() error { - return nil -} - -func (c *ctx) Value(key interface{}) interface{} { - return nil -} - -var _ = Describe("Format", func() { - match := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { - if len(args) > 0 { - valueRepresentation = fmt.Sprintf(valueRepresentation, args...) - } - return Equal(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) - } - - matchRegexp := func(typeRepresentation string, valueRepresentation string, args ...interface{}) types.GomegaMatcher { - if len(args) > 0 { - valueRepresentation = fmt.Sprintf(valueRepresentation, args...) - } - return MatchRegexp(fmt.Sprintf("%s<%s>: %s", Indent, typeRepresentation, valueRepresentation)) - } - - hashMatchingRegexp := func(entries ...string) string { - entriesSwitch := "(" + strings.Join(entries, "|") + ")" - arr := make([]string, len(entries)) - for i := range arr { - arr[i] = entriesSwitch - } - return "{" + strings.Join(arr, ", ") + "}" - } - - Describe("Message", func() { - Context("with only an actual value", func() { - It("should print out an indented formatted representation of the value and the message", func() { - Ω(Message(3, "to be three.")).Should(Equal("Expected\n : 3\nto be three.")) - }) - }) - - Context("with an actual and an expected value", func() { - It("should print out an indented formatted representatino of both values, and the message", func() { - Ω(Message(3, "to equal", 4)).Should(Equal("Expected\n : 3\nto equal\n : 4")) - }) - }) - }) - - Describe("MessageWithDiff", func() { - It("shows the exact point where two long strings differ", func() { - stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - - Ω(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedLongStringFailureMessage)) - }) - - It("truncates the start of long strings that differ only at their end", func() { - stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab" - stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaz" - - Ω(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedTruncatedStartStringFailureMessage)) - }) - - It("truncates the start of long strings that differ only in length", func() { - smallString := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - largeString := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - - Ω(MessageWithDiff(largeString, "to equal", smallString)).Should(Equal(expectedTruncatedStartSizeFailureMessage)) - Ω(MessageWithDiff(smallString, "to equal", largeString)).Should(Equal(expectedTruncatedStartSizeSwappedFailureMessage)) - }) - - It("truncates the end of long strings that differ only at their start", func() { - stringWithB := "baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - stringWithZ := "zaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - - Ω(MessageWithDiff(stringWithB, "to equal", stringWithZ)).Should(Equal(expectedTruncatedEndStringFailureMessage)) - }) - }) - - Describe("IndentString", func() { - It("should indent the string", func() { - Ω(IndentString("foo\n bar\nbaz", 2)).Should(Equal(" foo\n bar\n baz")) - }) - }) - - Describe("Object", func() { - Describe("formatting boolean values", func() { - It("should give the type and format values correctly", func() { - Ω(Object(true, 1)).Should(match("bool", "true")) - Ω(Object(false, 1)).Should(match("bool", "false")) - }) - }) - - Describe("formatting numbers", func() { - It("should give the type and format values correctly", func() { - Ω(Object(int(3), 1)).Should(match("int", "3")) - Ω(Object(int8(3), 1)).Should(match("int8", "3")) - Ω(Object(int16(3), 1)).Should(match("int16", "3")) - Ω(Object(int32(3), 1)).Should(match("int32", "3")) - Ω(Object(int64(3), 1)).Should(match("int64", "3")) - - Ω(Object(uint(3), 1)).Should(match("uint", "3")) - Ω(Object(uint8(3), 1)).Should(match("uint8", "3")) - Ω(Object(uint16(3), 1)).Should(match("uint16", "3")) - Ω(Object(uint32(3), 1)).Should(match("uint32", "3")) - Ω(Object(uint64(3), 1)).Should(match("uint64", "3")) - }) - - It("should handle uintptr differently", func() { - Ω(Object(uintptr(3), 1)).Should(match("uintptr", "0x3")) - }) - }) - - Describe("formatting channels", func() { - It("should give the type and format values correctly", func() { - c := make(chan<- bool, 3) - c <- true - c <- false - Ω(Object(c, 1)).Should(match("chan<- bool | len:2, cap:3", "%v", c)) - }) - }) - - Describe("formatting strings", func() { - It("should give the type and format values correctly", func() { - s := "a\nb\nc" - Ω(Object(s, 1)).Should(match("string", `a - b - c`)) - }) - }) - - Describe("formatting []byte slices", func() { - Context("when the slice is made of printable bytes", func() { - It("should present it as string", func() { - b := []byte("a b c") - Ω(Object(b, 1)).Should(matchRegexp(`\[\]uint8 \| len:5, cap:\d+`, `a b c`)) - }) - }) - Context("when the slice contains non-printable bytes", func() { - It("should present it as slice", func() { - b := []byte("a b c\n\x01\x02\x03\xff\x1bH") - Ω(Object(b, 1)).Should(matchRegexp(`\[\]uint8 \| len:12, cap:\d+`, `\[97, 32, 98, 32, 99, 10, 1, 2, 3, 255, 27, 72\]`)) - }) - }) - }) - - Describe("formatting functions", func() { - It("should give the type and format values correctly", func() { - f := func(a string, b []int) ([]byte, error) { - return []byte("abc"), nil - } - Ω(Object(f, 1)).Should(match("func(string, []int) ([]uint8, error)", "%v", f)) - }) - }) - - Describe("formatting pointers", func() { - It("should give the type and dereference the value to format it correctly", func() { - a := 3 - Ω(Object(&a, 1)).Should(match(fmt.Sprintf("*int | %p", &a), "3")) - }) - - Context("when there are pointers to pointers...", func() { - It("should recursively deference the pointer until it gets to a value", func() { - a := 3 - var b *int - var c **int - var d ***int - b = &a - c = &b - d = &c - - Ω(Object(d, 1)).Should(match(fmt.Sprintf("***int | %p", d), "3")) - }) - }) - - Context("when the pointer points to nil", func() { - It("should say nil and not explode", func() { - var a *AStruct - Ω(Object(a, 1)).Should(match("*format_test.AStruct | 0x0", "nil")) - }) - }) - }) - - Describe("formatting arrays", func() { - It("should give the type and format values correctly", func() { - w := [3]string{"Jed Bartlet", "Toby Ziegler", "CJ Cregg"} - Ω(Object(w, 1)).Should(match("[3]string", `["Jed Bartlet", "Toby Ziegler", "CJ Cregg"]`)) - }) - - Context("with byte arrays", func() { - It("should give the type and format values correctly", func() { - w := [3]byte{17, 28, 19} - Ω(Object(w, 1)).Should(match("[3]uint8", `[17, 28, 19]`)) - }) - }) - }) - - Describe("formatting slices", func() { - It("should include the length and capacity in the type information", func() { - s := make([]bool, 3, 4) - Ω(Object(s, 1)).Should(match("[]bool | len:3, cap:4", "[false, false, false]")) - }) - - Context("when the slice contains long entries", func() { - It("should format the entries with newlines", func() { - w := []string{"Josiah Edward Bartlet", "Toby Ziegler", "CJ Cregg"} - expected := `[ - "Josiah Edward Bartlet", - "Toby Ziegler", - "CJ Cregg", - ]` - Ω(Object(w, 1)).Should(match("[]string | len:3, cap:3", expected)) - }) - }) - }) - - Describe("formatting maps", func() { - It("should include the length in the type information", func() { - m := make(map[int]bool, 5) - m[3] = true - m[4] = false - Ω(Object(m, 1)).Should(matchRegexp(`map\[int\]bool \| len:2`, hashMatchingRegexp("3: true", "4: false"))) - }) - - Context("when the slice contains long entries", func() { - It("should format the entries with newlines", func() { - m := map[string][]byte{} - m["Josiah Edward Bartlet"] = []byte("Martin Sheen") - m["Toby Ziegler"] = []byte("Richard Schiff") - m["CJ Cregg"] = []byte("Allison Janney") - expected := `{ - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - ("Josiah Edward Bartlet": "Martin Sheen"|"Toby Ziegler": "Richard Schiff"|"CJ Cregg": "Allison Janney"), - }` - Ω(Object(m, 1)).Should(matchRegexp(`map\[string\]\[\]uint8 \| len:3`, expected)) - }) - }) - }) - - Describe("formatting structs", func() { - It("should include the struct name and the field names", func() { - s := SimpleStruct{ - Name: "Oswald", - Enumeration: 17, - Veritas: true, - Data: []byte("datum"), - secret: 1983, - } - - Ω(Object(s, 1)).Should(match("format_test.SimpleStruct", `{Name: "Oswald", Enumeration: 17, Veritas: true, Data: "datum", secret: 1983}`)) - }) - - Context("when the struct contains long entries", func() { - It("should format the entries with new lines", func() { - s := &SimpleStruct{ - Name: "Mithrandir Gandalf Greyhame", - Enumeration: 2021, - Veritas: true, - Data: []byte("wizard"), - secret: 3, - } - - Ω(Object(s, 1)).Should(match(fmt.Sprintf("*format_test.SimpleStruct | %p", s), `{ - Name: "Mithrandir Gandalf Greyhame", - Enumeration: 2021, - Veritas: true, - Data: "wizard", - secret: 3, - }`)) - }) - }) - }) - - Describe("formatting nil values", func() { - It("should print out nil", func() { - Ω(Object(nil, 1)).Should(match("nil", "nil")) - var typedNil *AStruct - Ω(Object(typedNil, 1)).Should(match("*format_test.AStruct | 0x0", "nil")) - var c chan<- bool - Ω(Object(c, 1)).Should(match("chan<- bool | len:0, cap:0", "nil")) - var s []string - Ω(Object(s, 1)).Should(match("[]string | len:0, cap:0", "nil")) - var m map[string]bool - Ω(Object(m, 1)).Should(match("map[string]bool | len:0", "nil")) - }) - }) - - Describe("formatting aliased types", func() { - It("should print out the correct alias type", func() { - Ω(Object(StringAlias("alias"), 1)).Should(match("format_test.StringAlias", `alias`)) - Ω(Object(ByteAlias("alias"), 1)).Should(matchRegexp(`format_test\.ByteAlias \| len:5, cap:\d+`, `alias`)) - Ω(Object(IntAlias(3), 1)).Should(match("format_test.IntAlias", "3")) - }) - }) - - Describe("handling nested things", func() { - It("should produce a correctly nested representation", func() { - s := ComplexStruct{ - Strings: []string{"lots", "of", "short", "strings"}, - SimpleThings: []*SimpleStruct{ - {"short", 7, true, []byte("succinct"), 17}, - {"something longer", 427, true, []byte("designed to wrap around nicely"), 30}, - }, - DataMaps: map[int]ByteAlias{ - 17: ByteAlias("some substantially longer chunks of data"), - 1138: ByteAlias("that should make things wrap"), - }, - } - expected := `{ - Strings: \["lots", "of", "short", "strings"\], - SimpleThings: \[ - {Name: "short", Enumeration: 7, Veritas: true, Data: "succinct", secret: 17}, - { - Name: "something longer", - Enumeration: 427, - Veritas: true, - Data: "designed to wrap around nicely", - secret: 30, - }, - \], - DataMaps: { - (17: "some substantially longer chunks of data"|1138: "that should make things wrap"), - (17: "some substantially longer chunks of data"|1138: "that should make things wrap"), - }, - }` - Ω(Object(s, 1)).Should(matchRegexp(`format_test\.ComplexStruct`, expected)) - }) - }) - - Describe("formatting times", func() { - It("should format time as RFC3339", func() { - t := time.Date(2016, 10, 31, 9, 57, 23, 12345, time.UTC) - Ω(Object(t, 1)).Should(match("time.Time", `2016-10-31T09:57:23.000012345Z`)) - }) - }) - }) - - Describe("Handling unexported fields in structs", func() { - It("should handle all the various types correctly", func() { - a := int(5) - s := SecretiveStruct{ - boolValue: true, - intValue: 3, - uintValue: 4, - uintptrValue: 5, - floatValue: 6.0, - complexValue: complex(5.0, 3.0), - chanValue: make(chan bool, 2), - funcValue: func() {}, - pointerValue: &a, - sliceValue: []string{"string", "slice"}, - byteSliceValue: []byte("bytes"), - stringValue: "a string", - arrValue: [3]int{11, 12, 13}, - byteArrValue: [3]byte{17, 20, 32}, - mapValue: map[string]int{"a key": 20, "b key": 30}, - structValue: AStruct{"exported"}, - interfaceValue: map[string]int{"a key": 17}, - } - - expected := fmt.Sprintf(`{ - boolValue: true, - intValue: 3, - uintValue: 4, - uintptrValue: 0x5, - floatValue: 6, - complexValue: \(5\+3i\), - chanValue: %p, - funcValue: %p, - pointerValue: 5, - sliceValue: \["string", "slice"\], - byteSliceValue: "bytes", - stringValue: "a string", - arrValue: \[11, 12, 13\], - byteArrValue: \[17, 20, 32\], - mapValue: %s, - structValue: {Exported: "exported"}, - interfaceValue: {"a key": 17}, - }`, s.chanValue, s.funcValue, hashMatchingRegexp(`"a key": 20`, `"b key": 30`)) - - Ω(Object(s, 1)).Should(matchRegexp(`format_test\.SecretiveStruct`, expected)) - }) - }) - - Describe("Handling interfaces", func() { - It("should unpack the interface", func() { - outerHash := map[string]interface{}{} - innerHash := map[string]int{} - - innerHash["inner"] = 3 - outerHash["integer"] = 2 - outerHash["map"] = innerHash - - expected := hashMatchingRegexp(`"integer": 2`, `"map": {"inner": 3}`) - Ω(Object(outerHash, 1)).Should(matchRegexp(`map\[string\]interface {} \| len:2`, expected)) - }) - }) - - Describe("Handling recursive things", func() { - It("should not go crazy...", func() { - m := map[string]interface{}{} - m["integer"] = 2 - m["map"] = m - Ω(Object(m, 1)).Should(ContainSubstring("...")) - }) - - It("really should not go crazy...", func() { - type complexKey struct { - Value map[interface{}]int - } - - complexObject := complexKey{} - complexObject.Value = make(map[interface{}]int) - - complexObject.Value[&complexObject] = 2 - Ω(Object(complexObject, 1)).Should(ContainSubstring("...")) - }) - }) - - Describe("When instructed to use the Stringer representation", func() { - BeforeEach(func() { - UseStringerRepresentation = true - }) - - AfterEach(func() { - UseStringerRepresentation = false - }) - - Context("when passed a GoStringer", func() { - It("should use what GoString() returns", func() { - Ω(Object(GoStringer{}, 1)).Should(ContainSubstring(": go-string")) - }) - }) - - Context("when passed a stringer", func() { - It("should use what String() returns", func() { - Ω(Object(Stringer{}, 1)).Should(ContainSubstring(": string")) - }) - }) - }) - - Describe("Printing a context.Context field", func() { - - type structWithContext struct { - Context Ctx - Value string - } - - context := ctx{} - objWithContext := structWithContext{Value: "some-value", Context: &context} - - It("Suppresses the content by default", func() { - Ω(Object(objWithContext, 1)).Should(ContainSubstring("")) - }) - - It("Doesn't supress the context if it's the object being printed", func() { - Ω(Object(context, 1)).ShouldNot(MatchRegexp("^.*$")) - }) - - Context("PrintContextObjects is set", func() { - BeforeEach(func() { - PrintContextObjects = true - }) - - AfterEach(func() { - PrintContextObjects = false - }) - - It("Prints the context", func() { - Ω(Object(objWithContext, 1)).ShouldNot(ContainSubstring("")) - }) - }) - }) -}) - -var expectedLongStringFailureMessage = strings.TrimSpace(` -Expected - : "...aaaaabaaaaa..." -to equal | - : "...aaaaazaaaaa..." -`) -var expectedTruncatedEndStringFailureMessage = strings.TrimSpace(` -Expected - : "baaaaa..." -to equal | - : "zaaaaa..." -`) -var expectedTruncatedStartStringFailureMessage = strings.TrimSpace(` -Expected - : "...aaaaab" -to equal | - : "...aaaaaz" -`) -var expectedTruncatedStartSizeFailureMessage = strings.TrimSpace(` -Expected - : "...aaaaaa" -to equal | - : "...aaaaa" -`) -var expectedTruncatedStartSizeSwappedFailureMessage = strings.TrimSpace(` -Expected - : "...aaaa" -to equal | - : "...aaaaa" -`) diff --git a/vendor/github.com/onsi/gomega/gomega_dsl.go b/vendor/github.com/onsi/gomega/gomega_dsl.go index 0d0f563a14..6c75d78bf8 100644 --- a/vendor/github.com/onsi/gomega/gomega_dsl.go +++ b/vendor/github.com/onsi/gomega/gomega_dsl.go @@ -24,11 +24,12 @@ import ( "github.com/onsi/gomega/types" ) -const GOMEGA_VERSION = "1.2.0" +const GOMEGA_VERSION = "1.4.0" const nilFailHandlerPanic = `You are trying to make an assertion, but Gomega's fail handler is nil. If you're using Ginkgo then you probably forgot to put your assertion in an It(). Alternatively, you may have forgotten to register a fail handler with RegisterFailHandler() or RegisterTestingT(). +Depending on your vendoring solution you may be inadvertently importing gomega and subpackages (e.g. ghhtp, gexec,...) from different locations. ` var globalFailHandler types.GomegaFailHandler @@ -45,7 +46,11 @@ func RegisterFailHandler(handler types.GomegaFailHandler) { } //RegisterTestingT connects Gomega to Golang's XUnit style -//Testing.T tests. You'll need to call this at the top of each XUnit style test: +//Testing.T tests. It is now deprecated and you should use NewGomegaWithT() instead. +// +//Legacy Documentation: +// +//You'll need to call this at the top of each XUnit style test: // // func TestFarmHasCow(t *testing.T) { // RegisterTestingT(t) @@ -58,6 +63,8 @@ func RegisterFailHandler(handler types.GomegaFailHandler) { // pass `t` down to the matcher itself). This means that you cannot run the XUnit style tests // in parallel as the global fail handler cannot point to more than one testing.T at a time. // +// NewGomegaWithT() does not have this limitation +// // (As an aside: Ginkgo gets around this limitation by running parallel tests in different *processes*). func RegisterTestingT(t types.GomegaTestingT) { RegisterFailHandler(testingtsupport.BuildTestingTGomegaFailHandler(t)) @@ -308,6 +315,60 @@ type GomegaAssertion interface { //OmegaMatcher is deprecated in favor of the better-named and better-organized types.GomegaMatcher but sticks around to support existing code that uses it type OmegaMatcher types.GomegaMatcher +//GomegaWithT wraps a *testing.T and provides `Expect`, `Eventually`, and `Consistently` methods. This allows you to leverage +//Gomega's rich ecosystem of matchers in standard `testing` test suites. +// +//Use `NewGomegaWithT` to instantiate a `GomegaWithT` +type GomegaWithT struct { + t types.GomegaTestingT +} + +//NewGomegaWithT takes a *testing.T and returngs a `GomegaWithT` allowing you to use `Expect`, `Eventually`, and `Consistently` along with +//Gomega's rich ecosystem of matchers in standard `testing` test suits. +// +// func TestFarmHasCow(t *testing.T) { +// g := GomegaWithT(t) +// +// f := farm.New([]string{"Cow", "Horse"}) +// g.Expect(f.HasCow()).To(BeTrue(), "Farm should have cow") +// } +func NewGomegaWithT(t types.GomegaTestingT) *GomegaWithT { + return &GomegaWithT{ + t: t, + } +} + +//See documentation for Expect +func (g *GomegaWithT) Expect(actual interface{}, extra ...interface{}) GomegaAssertion { + return assertion.New(actual, testingtsupport.BuildTestingTGomegaFailHandler(g.t), 0, extra...) +} + +//See documentation for Eventually +func (g *GomegaWithT) Eventually(actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { + timeoutInterval := defaultEventuallyTimeout + pollingInterval := defaultEventuallyPollingInterval + if len(intervals) > 0 { + timeoutInterval = toDuration(intervals[0]) + } + if len(intervals) > 1 { + pollingInterval = toDuration(intervals[1]) + } + return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, testingtsupport.BuildTestingTGomegaFailHandler(g.t), timeoutInterval, pollingInterval, 0) +} + +//See documentation for Consistently +func (g *GomegaWithT) Consistently(actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { + timeoutInterval := defaultConsistentlyDuration + pollingInterval := defaultConsistentlyPollingInterval + if len(intervals) > 0 { + timeoutInterval = toDuration(intervals[0]) + } + if len(intervals) > 1 { + pollingInterval = toDuration(intervals[1]) + } + return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, testingtsupport.BuildTestingTGomegaFailHandler(g.t), timeoutInterval, pollingInterval, 0) +} + func toDuration(input interface{}) time.Duration { duration, ok := input.(time.Duration) if ok { diff --git a/vendor/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go b/vendor/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go deleted file mode 100644 index dae47a48bf..0000000000 --- a/vendor/github.com/onsi/gomega/internal/assertion/assertion_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package assertion_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestAssertion(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Assertion Suite") -} diff --git a/vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go b/vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go deleted file mode 100644 index c03b7a320c..0000000000 --- a/vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go +++ /dev/null @@ -1,252 +0,0 @@ -package assertion_test - -import ( - "errors" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/internal/assertion" - "github.com/onsi/gomega/internal/fakematcher" -) - -var _ = Describe("Assertion", func() { - var ( - a *Assertion - failureMessage string - failureCallerSkip int - matcher *fakematcher.FakeMatcher - ) - - input := "The thing I'm testing" - - var fakeFailHandler = func(message string, callerSkip ...int) { - failureMessage = message - if len(callerSkip) == 1 { - failureCallerSkip = callerSkip[0] - } - } - - BeforeEach(func() { - matcher = &fakematcher.FakeMatcher{} - failureMessage = "" - failureCallerSkip = 0 - a = New(input, fakeFailHandler, 1) - }) - - Context("when called", func() { - It("should pass the provided input value to the matcher", func() { - a.Should(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.ShouldNot(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.To(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.ToNot(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - matcher.ReceivedActual = "" - - a.NotTo(matcher) - - Ω(matcher.ReceivedActual).Should(Equal(input)) - }) - }) - - Context("when the matcher succeeds", func() { - BeforeEach(func() { - matcher.MatchesToReturn = true - matcher.ErrToReturn = nil - }) - - Context("and a positive assertion is being made", func() { - It("should not call the failure callback", func() { - a.Should(matcher) - Ω(failureMessage).Should(Equal("")) - }) - - It("should be true", func() { - Ω(a.Should(matcher)).Should(BeTrue()) - }) - }) - - Context("and a negative assertion is being made", func() { - It("should call the failure callback", func() { - a.ShouldNot(matcher) - Ω(failureMessage).Should(Equal("negative: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - - It("should be false", func() { - Ω(a.ShouldNot(matcher)).Should(BeFalse()) - }) - }) - }) - - Context("when the matcher fails", func() { - BeforeEach(func() { - matcher.MatchesToReturn = false - matcher.ErrToReturn = nil - }) - - Context("and a positive assertion is being made", func() { - It("should call the failure callback", func() { - a.Should(matcher) - Ω(failureMessage).Should(Equal("positive: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - - It("should be false", func() { - Ω(a.Should(matcher)).Should(BeFalse()) - }) - }) - - Context("and a negative assertion is being made", func() { - It("should not call the failure callback", func() { - a.ShouldNot(matcher) - Ω(failureMessage).Should(Equal("")) - }) - - It("should be true", func() { - Ω(a.ShouldNot(matcher)).Should(BeTrue()) - }) - }) - }) - - Context("When reporting a failure", func() { - BeforeEach(func() { - matcher.MatchesToReturn = false - matcher.ErrToReturn = nil - }) - - Context("and there is an optional description", func() { - It("should append the description to the failure message", func() { - a.Should(matcher, "A description") - Ω(failureMessage).Should(Equal("A description\npositive: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - - Context("and there are multiple arguments to the optional description", func() { - It("should append the formatted description to the failure message", func() { - a.Should(matcher, "A description of [%d]", 3) - Ω(failureMessage).Should(Equal("A description of [3]\npositive: The thing I'm testing")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - }) - - Context("When the matcher returns an error", func() { - BeforeEach(func() { - matcher.ErrToReturn = errors.New("Kaboom!") - }) - - Context("and a positive assertion is being made", func() { - It("should call the failure callback", func() { - matcher.MatchesToReturn = true - a.Should(matcher) - Ω(failureMessage).Should(Equal("Kaboom!")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - - Context("and a negative assertion is being made", func() { - It("should call the failure callback", func() { - matcher.MatchesToReturn = false - a.ShouldNot(matcher) - Ω(failureMessage).Should(Equal("Kaboom!")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - - It("should always be false", func() { - Ω(a.Should(matcher)).Should(BeFalse()) - Ω(a.ShouldNot(matcher)).Should(BeFalse()) - }) - }) - - Context("when there are extra parameters", func() { - It("(a simple example)", func() { - Ω(func() (string, int, error) { - return "foo", 0, nil - }()).Should(Equal("foo")) - }) - - Context("when the parameters are all nil or zero", func() { - It("should invoke the matcher", func() { - matcher.MatchesToReturn = true - matcher.ErrToReturn = nil - - var typedNil []string - a = New(input, fakeFailHandler, 1, 0, nil, typedNil) - - result := a.Should(matcher) - Ω(result).Should(BeTrue()) - Ω(matcher.ReceivedActual).Should(Equal(input)) - - Ω(failureMessage).Should(BeZero()) - }) - }) - - Context("when any of the parameters are not nil or zero", func() { - It("should call the failure callback", func() { - matcher.MatchesToReturn = false - matcher.ErrToReturn = nil - - a = New(input, fakeFailHandler, 1, errors.New("foo")) - result := a.Should(matcher) - Ω(result).Should(BeFalse()) - Ω(matcher.ReceivedActual).Should(BeZero(), "The matcher doesn't even get called") - Ω(failureMessage).Should(ContainSubstring("foo")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 1) - result = a.ShouldNot(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("1")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) - result = a.To(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("foo")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) - result = a.ToNot(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("foo")) - failureMessage = "" - - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) - result = a.NotTo(matcher) - Ω(result).Should(BeFalse()) - Ω(failureMessage).Should(ContainSubstring("foo")) - Ω(failureCallerSkip).Should(Equal(3)) - }) - }) - }) - - Context("Making an assertion without a registered fail handler", func() { - It("should panic", func() { - defer func() { - e := recover() - RegisterFailHandler(Fail) - if e == nil { - Fail("expected a panic to have occurred") - } - }() - - RegisterFailHandler(nil) - Ω(true).Should(BeTrue()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go b/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go deleted file mode 100644 index bdb0c3d220..0000000000 --- a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package asyncassertion_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestAsyncAssertion(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "AsyncAssertion Suite") -} diff --git a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go b/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go deleted file mode 100644 index 3d7e3489d1..0000000000 --- a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go +++ /dev/null @@ -1,345 +0,0 @@ -package asyncassertion_test - -import ( - "errors" - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/internal/asyncassertion" -) - -var _ = Describe("Async Assertion", func() { - var ( - failureMessage string - callerSkip int - ) - - var fakeFailHandler = func(message string, skip ...int) { - failureMessage = message - callerSkip = skip[0] - } - - BeforeEach(func() { - failureMessage = "" - callerSkip = 0 - }) - - Describe("Eventually", func() { - Context("the positive case", func() { - It("should poll the function and matcher", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() int { - counter++ - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(BeNumerically("==", 5)) - Ω(failureMessage).Should(BeZero()) - }) - - It("should continue when the matcher errors", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() interface{} { - counter++ - if counter == 5 { - return "not-a-number" //this should cause the matcher to error - } - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(BeNumerically("==", 5), "My description %d", 2) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - - It("should be able to timeout", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() int { - counter++ - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(BeNumerically(">", 100), "My description %d", 2) - - Ω(counter).Should(BeNumerically(">", 8)) - Ω(counter).Should(BeNumerically("<=", 10)) - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(MatchRegexp(`\: \d`), "Should pass the correct value to the matcher message formatter.") - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("the negative case", func() { - It("should poll the function and matcher", func() { - counter := 0 - a := New(AsyncAssertionTypeEventually, func() int { - counter += 1 - return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(BeNumerically("<", 3)) - - Ω(counter).Should(Equal(3)) - Ω(failureMessage).Should(BeZero()) - }) - - It("should timeout when the matcher errors", func() { - a := New(AsyncAssertionTypeEventually, func() interface{} { - return 0 //this should cause the matcher to error - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(HaveLen(0), "My description %d", 2) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring("Error:")) - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - - It("should be able to timeout", func() { - a := New(AsyncAssertionTypeEventually, func() int { - return 0 - }, fakeFailHandler, time.Duration(0.1*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(Equal(0), "My description %d", 2) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring(": 0"), "Should pass the correct value to the matcher message formatter.") - Ω(failureMessage).Should(ContainSubstring("My description 2")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("with a function that returns multiple values", func() { - It("should eventually succeed if the additional arguments are nil", func() { - i := 0 - Eventually(func() (int, error) { - i++ - return i, nil - }).Should(Equal(10)) - }) - - It("should eventually timeout if the additional arguments are not nil", func() { - i := 0 - a := New(AsyncAssertionTypeEventually, func() (int, error) { - i++ - return i, errors.New("bam") - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - a.Should(Equal(2)) - - Ω(failureMessage).Should(ContainSubstring("Timed out after")) - Ω(failureMessage).Should(ContainSubstring("Error:")) - Ω(failureMessage).Should(ContainSubstring("bam")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("Making an assertion without a registered fail handler", func() { - It("should panic", func() { - defer func() { - e := recover() - RegisterFailHandler(Fail) - if e == nil { - Fail("expected a panic to have occurred") - } - }() - - RegisterFailHandler(nil) - c := make(chan bool, 1) - c <- true - Eventually(c).Should(Receive()) - }) - }) - }) - - Describe("Consistently", func() { - Describe("The positive case", func() { - Context("when the matcher consistently passes for the duration", func() { - It("should pass", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() string { - calls++ - return "foo" - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(Equal("foo")) - Ω(calls).Should(BeNumerically(">", 8)) - Ω(calls).Should(BeNumerically("<=", 10)) - Ω(failureMessage).Should(BeZero()) - }) - }) - - Context("when the matcher fails at some point", func() { - It("should fail", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() interface{} { - calls++ - if calls > 5 { - return "bar" - } - return "foo" - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(Equal("foo")) - Ω(failureMessage).Should(ContainSubstring("to equal")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("when the matcher errors at some point", func() { - It("should fail", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() interface{} { - calls++ - if calls > 5 { - return 3 - } - return []int{1, 2, 3} - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.Should(HaveLen(3)) - Ω(failureMessage).Should(ContainSubstring("HaveLen matcher expects")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - }) - - Describe("The negative case", func() { - Context("when the matcher consistently passes for the duration", func() { - It("should pass", func() { - c := make(chan bool) - a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(Receive()) - Ω(failureMessage).Should(BeZero()) - }) - }) - - Context("when the matcher fails at some point", func() { - It("should fail", func() { - c := make(chan bool) - go func() { - time.Sleep(time.Duration(100 * time.Millisecond)) - c <- true - }() - - a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(Receive()) - Ω(failureMessage).Should(ContainSubstring("not to receive anything")) - }) - }) - - Context("when the matcher errors at some point", func() { - It("should fail", func() { - calls := 0 - a := New(AsyncAssertionTypeConsistently, func() interface{} { - calls++ - return calls - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - - a.ShouldNot(BeNumerically(">", 5)) - Ω(failureMessage).Should(ContainSubstring("not to be >")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - }) - - Context("with a function that returns multiple values", func() { - It("should consistently succeed if the additional arguments are nil", func() { - i := 2 - Consistently(func() (int, error) { - i++ - return i, nil - }).Should(BeNumerically(">=", 2)) - }) - - It("should eventually timeout if the additional arguments are not nil", func() { - i := 2 - a := New(AsyncAssertionTypeEventually, func() (int, error) { - i++ - return i, errors.New("bam") - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) - a.Should(BeNumerically(">=", 2)) - - Ω(failureMessage).Should(ContainSubstring("Error:")) - Ω(failureMessage).Should(ContainSubstring("bam")) - Ω(callerSkip).Should(Equal(4)) - }) - }) - - Context("Making an assertion without a registered fail handler", func() { - It("should panic", func() { - defer func() { - e := recover() - RegisterFailHandler(Fail) - if e == nil { - Fail("expected a panic to have occurred") - } - }() - - RegisterFailHandler(nil) - c := make(chan bool) - Consistently(c).ShouldNot(Receive()) - }) - }) - }) - - Context("when passed a function with the wrong # or arguments & returns", func() { - It("should panic", func() { - Ω(func() { - New(AsyncAssertionTypeEventually, func() {}, fakeFailHandler, 0, 0, 1) - }).Should(Panic()) - - Ω(func() { - New(AsyncAssertionTypeEventually, func(a string) int { return 0 }, fakeFailHandler, 0, 0, 1) - }).Should(Panic()) - - Ω(func() { - New(AsyncAssertionTypeEventually, func() int { return 0 }, fakeFailHandler, 0, 0, 1) - }).ShouldNot(Panic()) - - Ω(func() { - New(AsyncAssertionTypeEventually, func() (int, error) { return 0, nil }, fakeFailHandler, 0, 0, 1) - }).ShouldNot(Panic()) - }) - }) - - Describe("bailing early", func() { - Context("when actual is a value", func() { - It("Eventually should bail out and fail early if the matcher says to", func() { - c := make(chan bool) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(c, 0.1).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically("<", 90*time.Millisecond)) - - Ω(failures).Should(HaveLen(1)) - }) - }) - - Context("when actual is a function", func() { - It("should never bail early", func() { - c := make(chan bool) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(func() chan bool { - return c - }, 0.1).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically(">=", 90*time.Millisecond)) - - Ω(failures).Should(HaveLen(1)) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go b/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go deleted file mode 100644 index b9fbd6c640..0000000000 --- a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package testingtsupport_test - -import ( - . "github.com/onsi/gomega" - - "testing" -) - -func TestTestingT(t *testing.T) { - RegisterTestingT(t) - Ω(true).Should(BeTrue()) -} diff --git a/vendor/github.com/onsi/gomega/matchers.go b/vendor/github.com/onsi/gomega/matchers.go index e6e85d070d..761ec33d86 100644 --- a/vendor/github.com/onsi/gomega/matchers.go +++ b/vendor/github.com/onsi/gomega/matchers.go @@ -53,7 +53,7 @@ func BeFalse() types.GomegaMatcher { //HaveOccurred succeeds if actual is a non-nil error //The typical Go error checking pattern looks like: // err := SomethingThatMightFail() -// Ω(err).ShouldNot(HaveOccurred()) +// Expect(err).ShouldNot(HaveOccurred()) func HaveOccurred() types.GomegaMatcher { return &matchers.HaveOccurredMatcher{} } @@ -61,10 +61,10 @@ func HaveOccurred() types.GomegaMatcher { //Succeed passes if actual is a nil error //Succeed is intended to be used with functions that return a single error value. Instead of // err := SomethingThatMightFail() -// Ω(err).ShouldNot(HaveOccurred()) +// Expect(err).ShouldNot(HaveOccurred()) // //You can write: -// Ω(SomethingThatMightFail()).Should(Succeed()) +// Expect(SomethingThatMightFail()).Should(Succeed()) // //It is a mistake to use Succeed with a function that has multiple return values. Gomega's Ω and Expect //functions automatically trigger failure if any return values after the first return value are non-zero/non-nil. @@ -76,8 +76,8 @@ func Succeed() types.GomegaMatcher { //MatchError succeeds if actual is a non-nil error that matches the passed in string/error. // //These are valid use-cases: -// Ω(err).Should(MatchError("an error")) //asserts that err.Error() == "an error" -// Ω(err).Should(MatchError(SomeError)) //asserts that err == SomeError (via reflect.DeepEqual) +// Expect(err).Should(MatchError("an error")) //asserts that err.Error() == "an error" +// Expect(err).Should(MatchError(SomeError)) //asserts that err == SomeError (via reflect.DeepEqual) // //It is an error for err to be nil or an object that does not implement the Error interface func MatchError(expected interface{}) types.GomegaMatcher { @@ -106,11 +106,11 @@ func BeClosed() types.GomegaMatcher { // //Receive returns immediately and never blocks: // -//- If there is nothing on the channel `c` then Ω(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass. +//- If there is nothing on the channel `c` then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass. // -//- If the channel `c` is closed then Ω(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass. +//- If the channel `c` is closed then Expect(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass. // -//- If there is something on the channel `c` ready to be read, then Ω(c).Should(Receive()) will pass and Ω(c).ShouldNot(Receive()) will fail. +//- If there is something on the channel `c` ready to be read, then Expect(c).Should(Receive()) will pass and Ω(c).ShouldNot(Receive()) will fail. // //If you have a go-routine running in the background that will write to channel `c` you can: // Eventually(c).Should(Receive()) @@ -121,7 +121,7 @@ func BeClosed() types.GomegaMatcher { // Consistently(c).ShouldNot(Receive()) // //You can pass `Receive` a matcher. If you do so, it will match the received object against the matcher. For example: -// Ω(c).Should(Receive(Equal("foo"))) +// Expect(c).Should(Receive(Equal("foo"))) // //When given a matcher, `Receive` will always fail if there is nothing to be received on the channel. // @@ -134,8 +134,8 @@ func BeClosed() types.GomegaMatcher { //Finally, if you want to have a reference to the value *sent* to the channel you can pass the `Receive` matcher a pointer to a variable of the appropriate type: // var myThing thing // Eventually(thingChan).Should(Receive(&myThing)) -// Ω(myThing.Sprocket).Should(Equal("foo")) -// Ω(myThing.IsValid()).Should(BeTrue()) +// Expect(myThing.Sprocket).Should(Equal("foo")) +// Expect(myThing.IsValid()).Should(BeTrue()) func Receive(args ...interface{}) types.GomegaMatcher { var arg interface{} if len(args) > 0 { @@ -153,9 +153,9 @@ func Receive(args ...interface{}) types.GomegaMatcher { // //BeSent never blocks: // -//- If the channel `c` is not ready to receive then Ω(c).Should(BeSent("foo")) will fail immediately +//- If the channel `c` is not ready to receive then Expect(c).Should(BeSent("foo")) will fail immediately //- If the channel `c` is eventually ready to receive then Eventually(c).Should(BeSent("foo")) will succeed.. presuming the channel becomes ready to receive before Eventually's timeout -//- If the channel `c` is closed then Ω(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both fail immediately +//- If the channel `c` is closed then Expect(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both fail immediately // //Of course, the value is actually sent to the channel. The point of `BeSent` is less to make an assertion about the availability of the channel (which is typically an implementation detail that your test should not be concerned with). //Rather, the point of `BeSent` is to make it possible to easily and expressively write tests that can timeout on blocked channel sends. @@ -259,7 +259,7 @@ func BeZero() types.GomegaMatcher { //ContainElement succeeds if actual contains the passed in element. //By default ContainElement() uses Equal() to perform the match, however a //matcher can be passed in instead: -// Ω([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar"))) +// Expect([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar"))) // //Actual must be an array, slice or map. //For maps, ContainElement searches through the map's values. @@ -269,19 +269,19 @@ func ContainElement(element interface{}) types.GomegaMatcher { } } -//ConsistOf succeeds if actual contains preciely the elements passed into the matcher. The ordering of the elements does not matter. +//ConsistOf succeeds if actual contains precisely the elements passed into the matcher. The ordering of the elements does not matter. //By default ConsistOf() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples: // -// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo")) -// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo")) -// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo"))) +// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo")) +// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo")) +// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo"))) // //Actual must be an array, slice or map. For maps, ConsistOf matches against the map's values. // //You typically pass variadic arguments to ConsistOf (as in the examples above). However, if you need to pass in a slice you can provided that it //is the only element passed in to ConsistOf: // -// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"})) +// Expect([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"})) // //Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []interface{} are different types - hence the need for this special rule. func ConsistOf(elements ...interface{}) types.GomegaMatcher { @@ -293,7 +293,7 @@ func ConsistOf(elements ...interface{}) types.GomegaMatcher { //HaveKey succeeds if actual is a map with the passed in key. //By default HaveKey uses Equal() to perform the match, however a //matcher can be passed in instead: -// Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`))) +// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`))) func HaveKey(key interface{}) types.GomegaMatcher { return &matchers.HaveKeyMatcher{ Key: key, @@ -303,8 +303,8 @@ func HaveKey(key interface{}) types.GomegaMatcher { //HaveKeyWithValue succeeds if actual is a map with the passed in key and value. //By default HaveKeyWithValue uses Equal() to perform the match, however a //matcher can be passed in instead: -// Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar")) -// Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar")) +// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar")) +// Expect(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar")) func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher { return &matchers.HaveKeyWithValueMatcher{ Key: key, @@ -314,15 +314,15 @@ func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher { //BeNumerically performs numerical assertions in a type-agnostic way. //Actual and expected should be numbers, though the specific type of -//number is irrelevant (floa32, float64, uint8, etc...). +//number is irrelevant (float32, float64, uint8, etc...). // //There are six, self-explanatory, supported comparators: -// Ω(1.0).Should(BeNumerically("==", 1)) -// Ω(1.0).Should(BeNumerically("~", 0.999, 0.01)) -// Ω(1.0).Should(BeNumerically(">", 0.9)) -// Ω(1.0).Should(BeNumerically(">=", 1.0)) -// Ω(1.0).Should(BeNumerically("<", 3)) -// Ω(1.0).Should(BeNumerically("<=", 1.0)) +// Expect(1.0).Should(BeNumerically("==", 1)) +// Expect(1.0).Should(BeNumerically("~", 0.999, 0.01)) +// Expect(1.0).Should(BeNumerically(">", 0.9)) +// Expect(1.0).Should(BeNumerically(">=", 1.0)) +// Expect(1.0).Should(BeNumerically("<", 3)) +// Expect(1.0).Should(BeNumerically("<=", 1.0)) func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatcher { return &matchers.BeNumericallyMatcher{ Comparator: comparator, @@ -332,8 +332,8 @@ func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatc //BeTemporally compares time.Time's like BeNumerically //Actual and expected must be time.Time. The comparators are the same as for BeNumerically -// Ω(time.Now()).Should(BeTemporally(">", time.Time{})) -// Ω(time.Now()).Should(BeTemporally("~", time.Now(), time.Second)) +// Expect(time.Now()).Should(BeTemporally(">", time.Time{})) +// Expect(time.Now()).Should(BeTemporally("~", time.Now(), time.Second)) func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher { return &matchers.BeTemporallyMatcher{ Comparator: comparator, @@ -344,10 +344,10 @@ func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Dura //BeAssignableToTypeOf succeeds if actual is assignable to the type of expected. //It will return an error when one of the values is nil. -// Ω(0).Should(BeAssignableToTypeOf(0)) // Same values -// Ω(5).Should(BeAssignableToTypeOf(-1)) // different values same type -// Ω("foo").Should(BeAssignableToTypeOf("bar")) // different values same type -// Ω(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{})) +// Expect(0).Should(BeAssignableToTypeOf(0)) // Same values +// Expect(5).Should(BeAssignableToTypeOf(-1)) // different values same type +// Expect("foo").Should(BeAssignableToTypeOf("bar")) // different values same type +// Expect(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{})) func BeAssignableToTypeOf(expected interface{}) types.GomegaMatcher { return &matchers.AssignableToTypeOfMatcher{ Expected: expected, @@ -366,13 +366,13 @@ func BeAnExistingFile() types.GomegaMatcher { return &matchers.BeAnExistingFileMatcher{} } -//BeARegularFile succeeds iff a file exists and is a regular file. +//BeARegularFile succeeds if a file exists and is a regular file. //Actual must be a string representing the abs path to the file being checked. func BeARegularFile() types.GomegaMatcher { return &matchers.BeARegularFileMatcher{} } -//BeADirectory succeeds iff a file exists and is a directory. +//BeADirectory succeeds if a file exists and is a directory. //Actual must be a string representing the abs path to the file being checked. func BeADirectory() types.GomegaMatcher { return &matchers.BeADirectoryMatcher{} @@ -388,7 +388,7 @@ func And(ms ...types.GomegaMatcher) types.GomegaMatcher { } //SatisfyAll is an alias for And(). -// Ω("hi").Should(SatisfyAll(HaveLen(2), Equal("hi"))) +// Expect("hi").Should(SatisfyAll(HaveLen(2), Equal("hi"))) func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher { return And(matchers...) } diff --git a/vendor/github.com/onsi/gomega/matchers/and_test.go b/vendor/github.com/onsi/gomega/matchers/and_test.go deleted file mode 100644 index acf778cd6d..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/and_test.go +++ /dev/null @@ -1,103 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" - "github.com/onsi/gomega/types" -) - -// sample data -var ( - // example input - input = "hi" - // some matchers that succeed against the input - true1 = HaveLen(2) - true2 = Equal("hi") - true3 = MatchRegexp("hi") - // some matchers that fail against the input. - false1 = HaveLen(1) - false2 = Equal("hip") - false3 = MatchRegexp("hope") -) - -// verifyFailureMessage expects the matcher to fail with the given input, and verifies the failure message. -func verifyFailureMessage(m types.GomegaMatcher, input string, expectedFailureMsgFragment string) { - Expect(m.Match(input)).To(BeFalse()) - Expect(m.FailureMessage(input)).To(Equal( - "Expected\n : " + input + "\n" + expectedFailureMsgFragment)) -} - -var _ = Describe("AndMatcher", func() { - It("works with positive cases", func() { - Expect(input).To(And()) - Expect(input).To(And(true1)) - Expect(input).To(And(true1, true2)) - Expect(input).To(And(true1, true2, true3)) - - // use alias - Expect(input).To(SatisfyAll(true1, true2, true3)) - }) - - It("works with negative cases", func() { - Expect(input).ToNot(And(false1, false2)) - Expect(input).ToNot(And(true1, true2, false3)) - Expect(input).ToNot(And(true1, false2, false3)) - Expect(input).ToNot(And(false1, true1, true2)) - }) - - Context("failure messages", func() { - Context("when match fails", func() { - It("gives a descriptive message", func() { - verifyFailureMessage(And(false1, true1), input, "to have length 1") - verifyFailureMessage(And(true1, false2), input, "to equal\n : hip") - verifyFailureMessage(And(true1, true2, false3), input, "to match regular expression\n : hope") - }) - }) - - Context("when match succeeds, but expected it to fail", func() { - It("gives a descriptive message", func() { - verifyFailureMessage(Not(And(true1, true2)), input, - `To not satisfy all of these matchers: [%!s(*matchers.HaveLenMatcher=&{2}) %!s(*matchers.EqualMatcher=&{hi})]`) - }) - }) - }) - - Context("MatchMayChangeInTheFuture", func() { - Context("Match returned false", func() { - Context("returns value of the failed matcher", func() { - It("false if failed matcher not going to change", func() { - // 3 matchers: 1st returns true, 2nd returns false and is not going to change, 3rd is never called - m := And(Not(BeNil()), Or(), Equal(1)) - Expect(m.Match("hi")).To(BeFalse()) - Expect(m.(*AndMatcher).MatchMayChangeInTheFuture("hi")).To(BeFalse()) // empty Or() indicates not going to change - }) - It("true if failed matcher indicates it might change", func() { - // 3 matchers: 1st returns true, 2nd returns false and "might" change, 3rd is never called - m := And(Not(BeNil()), Equal(5), Equal(1)) - Expect(m.Match("hi")).To(BeFalse()) - Expect(m.(*AndMatcher).MatchMayChangeInTheFuture("hi")).To(BeTrue()) // Equal(5) indicates it might change - }) - }) - }) - Context("Match returned true", func() { - It("returns true if any of the matchers could change", func() { - // 3 matchers, all return true, and all could change - m := And(Not(BeNil()), Equal("hi"), HaveLen(2)) - Expect(m.Match("hi")).To(BeTrue()) - Expect(m.(*AndMatcher).MatchMayChangeInTheFuture("hi")).To(BeTrue()) // all 3 of these matchers default to 'true' - }) - It("returns false if none of the matchers could change", func() { - // empty And() has the property of always matching, and never can change since there are no sub-matchers that could change - m := And() - Expect(m.Match("anything")).To(BeTrue()) - Expect(m.(*AndMatcher).MatchMayChangeInTheFuture("anything")).To(BeFalse()) - - // And() with 3 sub-matchers that return true, and can't change - m = And(And(), And(), And()) - Expect(m.Match("hi")).To(BeTrue()) - Expect(m.(*AndMatcher).MatchMayChangeInTheFuture("hi")).To(BeFalse()) // the 3 empty And()'s won't change - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go b/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go index 89a1fc2116..51f8be6ae4 100644 --- a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go @@ -12,8 +12,12 @@ type AssignableToTypeOfMatcher struct { } func (matcher *AssignableToTypeOfMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil || matcher.Expected == nil { + if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") + } else if matcher.Expected == nil { + return false, fmt.Errorf("Refusing to compare type to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") + } else if actual == nil { + return false, nil } actualType := reflect.TypeOf(actual) diff --git a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go deleted file mode 100644 index d2280e0506..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("AssignableToTypeOf", func() { - Context("When asserting assignability between types", func() { - It("should do the right thing", func() { - Ω(0).Should(BeAssignableToTypeOf(0)) - Ω(5).Should(BeAssignableToTypeOf(-1)) - Ω("foo").Should(BeAssignableToTypeOf("bar")) - Ω(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{})) - - Ω(0).ShouldNot(BeAssignableToTypeOf("bar")) - Ω(5).ShouldNot(BeAssignableToTypeOf(struct{ Foo string }{})) - Ω("foo").ShouldNot(BeAssignableToTypeOf(42)) - }) - }) - - Context("When asserting nil values", func() { - It("should error", func() { - success, err := (&AssignableToTypeOfMatcher{Expected: nil}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/attributes_slice.go b/vendor/github.com/onsi/gomega/matchers/attributes_slice.go new file mode 100644 index 0000000000..355b362f4b --- /dev/null +++ b/vendor/github.com/onsi/gomega/matchers/attributes_slice.go @@ -0,0 +1,14 @@ +package matchers + +import ( + "encoding/xml" + "strings" +) + +type attributesSlice []xml.Attr + +func (attrs attributesSlice) Len() int { return len(attrs) } +func (attrs attributesSlice) Less(i, j int) bool { + return strings.Compare(attrs[i].Name.Local, attrs[j].Name.Local) == -1 +} +func (attrs attributesSlice) Swap(i, j int) { attrs[i], attrs[j] = attrs[j], attrs[i] } diff --git a/vendor/github.com/onsi/gomega/matchers/be_a_directory_test.go b/vendor/github.com/onsi/gomega/matchers/be_a_directory_test.go deleted file mode 100644 index e59d769901..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_a_directory_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package matchers_test - -import ( - "io/ioutil" - "os" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeADirectoryMatcher", func() { - Context("when passed a string", func() { - It("should do the right thing", func() { - Ω("/dne/test").ShouldNot(BeADirectory()) - - tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpFile.Name()) - Ω(tmpFile.Name()).ShouldNot(BeADirectory()) - - tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpDir) - Ω(tmpDir).Should(BeADirectory()) - }) - }) - - Context("when passed something else", func() { - It("should error", func() { - success, err := (&BeADirectoryMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeADirectoryMatcher{}).Match(true) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_a_regular_file_test.go b/vendor/github.com/onsi/gomega/matchers/be_a_regular_file_test.go deleted file mode 100644 index 951e750d64..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_a_regular_file_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package matchers_test - -import ( - "io/ioutil" - "os" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeARegularFileMatcher", func() { - Context("when passed a string", func() { - It("should do the right thing", func() { - Ω("/dne/test").ShouldNot(BeARegularFile()) - - tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpFile.Name()) - Ω(tmpFile.Name()).Should(BeARegularFile()) - - tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpDir) - Ω(tmpDir).ShouldNot(BeARegularFile()) - }) - }) - - Context("when passed something else", func() { - It("should error", func() { - success, err := (&BeARegularFileMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeARegularFileMatcher{}).Match(true) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_an_existing_file_test.go b/vendor/github.com/onsi/gomega/matchers/be_an_existing_file_test.go deleted file mode 100644 index 775f7b6aca..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_an_existing_file_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package matchers_test - -import ( - "io/ioutil" - "os" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeAnExistingFileMatcher", func() { - Context("when passed a string", func() { - It("should do the right thing", func() { - Ω("/dne/test").ShouldNot(BeAnExistingFile()) - - tmpFile, err := ioutil.TempFile("", "gomega-test-tempfile") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpFile.Name()) - Ω(tmpFile.Name()).Should(BeAnExistingFile()) - - tmpDir, err := ioutil.TempDir("", "gomega-test-tempdir") - Ω(err).ShouldNot(HaveOccurred()) - defer os.Remove(tmpDir) - Ω(tmpDir).Should(BeAnExistingFile()) - }) - }) - - Context("when passed something else", func() { - It("should error", func() { - success, err := (&BeAnExistingFileMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeAnExistingFileMatcher{}).Match(true) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go index c1b499597d..ed6f69288e 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go @@ -2,8 +2,9 @@ package matchers import ( "fmt" - "github.com/onsi/gomega/format" "reflect" + + "github.com/onsi/gomega/format" ) type BeClosedMatcher struct { diff --git a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_closed_matcher_test.go deleted file mode 100644 index b2c40c9103..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeClosedMatcher", func() { - Context("when passed a channel", func() { - It("should do the right thing", func() { - openChannel := make(chan bool) - Ω(openChannel).ShouldNot(BeClosed()) - - var openReaderChannel <-chan bool - openReaderChannel = openChannel - Ω(openReaderChannel).ShouldNot(BeClosed()) - - closedChannel := make(chan bool) - close(closedChannel) - - Ω(closedChannel).Should(BeClosed()) - - var closedReaderChannel <-chan bool - closedReaderChannel = closedChannel - Ω(closedReaderChannel).Should(BeClosed()) - }) - }) - - Context("when passed a send-only channel", func() { - It("should error", func() { - openChannel := make(chan bool) - var openWriterChannel chan<- bool - openWriterChannel = openChannel - - success, err := (&BeClosedMatcher{}).Match(openWriterChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - closedChannel := make(chan bool) - close(closedChannel) - - var closedWriterChannel chan<- bool - closedWriterChannel = closedChannel - - success, err = (&BeClosedMatcher{}).Match(closedWriterChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - }) - }) - - Context("when passed something else", func() { - It("should error", func() { - var nilChannel chan bool - - success, err := (&BeClosedMatcher{}).Match(nilChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeClosedMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeClosedMatcher{}).Match(7) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go index 55bdd7d15d..8b00311b0d 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go @@ -2,6 +2,7 @@ package matchers import ( "fmt" + "github.com/onsi/gomega/format" ) diff --git a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_empty_matcher_test.go deleted file mode 100644 index 541c1b951e..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeEmpty", func() { - Context("when passed a supported type", func() { - It("should do the right thing", func() { - Ω("").Should(BeEmpty()) - Ω(" ").ShouldNot(BeEmpty()) - - Ω([0]int{}).Should(BeEmpty()) - Ω([1]int{1}).ShouldNot(BeEmpty()) - - Ω([]int{}).Should(BeEmpty()) - Ω([]int{1}).ShouldNot(BeEmpty()) - - Ω(map[string]int{}).Should(BeEmpty()) - Ω(map[string]int{"a": 1}).ShouldNot(BeEmpty()) - - c := make(chan bool, 1) - Ω(c).Should(BeEmpty()) - c <- true - Ω(c).ShouldNot(BeEmpty()) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should be true", func() { - var nilSlice []int - Ω(nilSlice).Should(BeEmpty()) - - var nilMap map[int]string - Ω(nilMap).Should(BeEmpty()) - }) - }) - - Context("when passed an unsupported type", func() { - It("should error", func() { - success, err := (&BeEmptyMatcher{}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeEmptyMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go index 32a0c3108a..97ab20a4ec 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go @@ -2,8 +2,9 @@ package matchers import ( "fmt" - "github.com/onsi/gomega/format" "reflect" + + "github.com/onsi/gomega/format" ) type BeEquivalentToMatcher struct { diff --git a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go deleted file mode 100644 index def5104fa7..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeEquivalentTo", func() { - Context("when asserting that nil is equivalent to nil", func() { - It("should error", func() { - success, err := (&BeEquivalentToMatcher{Expected: nil}).Match(nil) - - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("When asserting on nil", func() { - It("should do the right thing", func() { - Ω("foo").ShouldNot(BeEquivalentTo(nil)) - Ω(nil).ShouldNot(BeEquivalentTo(3)) - Ω([]int{1, 2}).ShouldNot(BeEquivalentTo(nil)) - }) - }) - - Context("When asserting on type aliases", func() { - It("should the right thing", func() { - Ω(StringAlias("foo")).Should(BeEquivalentTo("foo")) - Ω("foo").Should(BeEquivalentTo(StringAlias("foo"))) - Ω(StringAlias("foo")).ShouldNot(BeEquivalentTo("bar")) - Ω("foo").ShouldNot(BeEquivalentTo(StringAlias("bar"))) - }) - }) - - Context("When asserting on numbers", func() { - It("should convert actual to expected and do the right thing", func() { - Ω(5).Should(BeEquivalentTo(5)) - Ω(5.0).Should(BeEquivalentTo(5.0)) - Ω(5).Should(BeEquivalentTo(5.0)) - - Ω(5).ShouldNot(BeEquivalentTo("5")) - Ω(5).ShouldNot(BeEquivalentTo(3)) - - //Here be dragons! - Ω(5.1).Should(BeEquivalentTo(5)) - Ω(5).ShouldNot(BeEquivalentTo(5.1)) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go index 0b224cbbc6..91d3b779ea 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go @@ -2,6 +2,7 @@ package matchers import ( "fmt" + "github.com/onsi/gomega/format" ) diff --git a/vendor/github.com/onsi/gomega/matchers/be_false_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_false_matcher_test.go deleted file mode 100644 index 3965a2c539..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_false_matcher_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeFalse", func() { - It("should handle true and false correctly", func() { - Ω(true).ShouldNot(BeFalse()) - Ω(false).Should(BeFalse()) - }) - - It("should only support booleans", func() { - success, err := (&BeFalseMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_identical_to_test.go b/vendor/github.com/onsi/gomega/matchers/be_identical_to_test.go deleted file mode 100644 index 8b90a1a619..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_identical_to_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package matchers_test - -import ( - "errors" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeIdenticalTo", func() { - Context("when asserting that nil equals nil", func() { - It("should error", func() { - success, err := (&BeIdenticalToMatcher{Expected: nil}).Match(nil) - - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - It("should treat the same pointer to a struct as identical", func() { - mySpecialStruct := myCustomType{} - Ω(&mySpecialStruct).Should(BeIdenticalTo(&mySpecialStruct)) - Ω(&myCustomType{}).ShouldNot(BeIdenticalTo(&mySpecialStruct)) - }) - - It("should be strict about types", func() { - Ω(5).ShouldNot(BeIdenticalTo("5")) - Ω(5).ShouldNot(BeIdenticalTo(5.0)) - Ω(5).ShouldNot(BeIdenticalTo(3)) - }) - - It("should treat primtives as identical", func() { - Ω("5").Should(BeIdenticalTo("5")) - Ω("5").ShouldNot(BeIdenticalTo("55")) - - Ω(5.55).Should(BeIdenticalTo(5.55)) - Ω(5.55).ShouldNot(BeIdenticalTo(6.66)) - - Ω(5).Should(BeIdenticalTo(5)) - Ω(5).ShouldNot(BeIdenticalTo(55)) - }) - - It("should treat the same pointers to a slice as identical", func() { - mySlice := []int{1, 2} - Ω(&mySlice).Should(BeIdenticalTo(&mySlice)) - Ω(&mySlice).ShouldNot(BeIdenticalTo(&[]int{1, 2})) - }) - - It("should treat the same pointers to a map as identical", func() { - myMap := map[string]string{"a": "b", "c": "d"} - Ω(&myMap).Should(BeIdenticalTo(&myMap)) - Ω(myMap).ShouldNot(BeIdenticalTo(map[string]string{"a": "b", "c": "d"})) - }) - - It("should treat the same pointers to an error as identical", func() { - myError := errors.New("foo") - Ω(&myError).Should(BeIdenticalTo(&myError)) - Ω(errors.New("foo")).ShouldNot(BeIdenticalTo(errors.New("bar"))) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_nil_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_nil_matcher_test.go deleted file mode 100644 index 7533253632..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_nil_matcher_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("BeNil", func() { - It("should succeed when passed nil", func() { - Ω(nil).Should(BeNil()) - }) - - It("should succeed when passed a typed nil", func() { - var a []int - Ω(a).Should(BeNil()) - }) - - It("should succeed when passing nil pointer", func() { - var f *struct{} - Ω(f).Should(BeNil()) - }) - - It("should not succeed when not passed nil", func() { - Ω(0).ShouldNot(BeNil()) - Ω(false).ShouldNot(BeNil()) - Ω("").ShouldNot(BeNil()) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go deleted file mode 100644 index 43fdb1fe0b..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeNumerically", func() { - Context("when passed a number", func() { - It("should support ==", func() { - Ω(uint32(5)).Should(BeNumerically("==", 5)) - Ω(float64(5.0)).Should(BeNumerically("==", 5)) - Ω(int8(5)).Should(BeNumerically("==", 5)) - }) - - It("should not have false positives", func() { - Ω(5.1).ShouldNot(BeNumerically("==", 5)) - Ω(5).ShouldNot(BeNumerically("==", 5.1)) - }) - - It("should support >", func() { - Ω(uint32(5)).Should(BeNumerically(">", 4)) - Ω(float64(5.0)).Should(BeNumerically(">", 4.9)) - Ω(int8(5)).Should(BeNumerically(">", 4)) - - Ω(uint32(5)).ShouldNot(BeNumerically(">", 5)) - Ω(float64(5.0)).ShouldNot(BeNumerically(">", 5.0)) - Ω(int8(5)).ShouldNot(BeNumerically(">", 5)) - }) - - It("should support <", func() { - Ω(uint32(5)).Should(BeNumerically("<", 6)) - Ω(float64(5.0)).Should(BeNumerically("<", 5.1)) - Ω(int8(5)).Should(BeNumerically("<", 6)) - - Ω(uint32(5)).ShouldNot(BeNumerically("<", 5)) - Ω(float64(5.0)).ShouldNot(BeNumerically("<", 5.0)) - Ω(int8(5)).ShouldNot(BeNumerically("<", 5)) - }) - - It("should support >=", func() { - Ω(uint32(5)).Should(BeNumerically(">=", 4)) - Ω(float64(5.0)).Should(BeNumerically(">=", 4.9)) - Ω(int8(5)).Should(BeNumerically(">=", 4)) - - Ω(uint32(5)).Should(BeNumerically(">=", 5)) - Ω(float64(5.0)).Should(BeNumerically(">=", 5.0)) - Ω(int8(5)).Should(BeNumerically(">=", 5)) - - Ω(uint32(5)).ShouldNot(BeNumerically(">=", 6)) - Ω(float64(5.0)).ShouldNot(BeNumerically(">=", 5.1)) - Ω(int8(5)).ShouldNot(BeNumerically(">=", 6)) - }) - - It("should support <=", func() { - Ω(uint32(5)).Should(BeNumerically("<=", 6)) - Ω(float64(5.0)).Should(BeNumerically("<=", 5.1)) - Ω(int8(5)).Should(BeNumerically("<=", 6)) - - Ω(uint32(5)).Should(BeNumerically("<=", 5)) - Ω(float64(5.0)).Should(BeNumerically("<=", 5.0)) - Ω(int8(5)).Should(BeNumerically("<=", 5)) - - Ω(uint32(5)).ShouldNot(BeNumerically("<=", 4)) - Ω(float64(5.0)).ShouldNot(BeNumerically("<=", 4.9)) - Ω(int8(5)).Should(BeNumerically("<=", 5)) - }) - - Context("when passed ~", func() { - Context("when passed a float", func() { - Context("and there is no precision parameter", func() { - It("should default to 1e-8", func() { - Ω(5.00000001).Should(BeNumerically("~", 5.00000002)) - Ω(5.00000001).ShouldNot(BeNumerically("~", 5.0000001)) - }) - }) - - Context("and there is a precision parameter", func() { - It("should use the precision parameter", func() { - Ω(5.1).Should(BeNumerically("~", 5.19, 0.1)) - Ω(5.1).Should(BeNumerically("~", 5.01, 0.1)) - Ω(5.1).ShouldNot(BeNumerically("~", 5.22, 0.1)) - Ω(5.1).ShouldNot(BeNumerically("~", 4.98, 0.1)) - }) - }) - }) - - Context("when passed an int/uint", func() { - Context("and there is no precision parameter", func() { - It("should just do strict equality", func() { - Ω(5).Should(BeNumerically("~", 5)) - Ω(5).ShouldNot(BeNumerically("~", 6)) - Ω(uint(5)).ShouldNot(BeNumerically("~", 6)) - }) - }) - - Context("and there is a precision parameter", func() { - It("should use precision paramter", func() { - Ω(5).Should(BeNumerically("~", 6, 2)) - Ω(5).ShouldNot(BeNumerically("~", 8, 2)) - Ω(uint(5)).Should(BeNumerically("~", 6, 1)) - }) - }) - }) - }) - }) - - Context("when passed a non-number", func() { - It("should error", func() { - success, err := (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{5}}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "=="}).Match(5) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "~", CompareTo: []interface{}{3.0, "foo"}}).Match(5.0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match(5) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{"bar"}}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{nil}}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeNumericallyMatcher{Comparator: "==", CompareTo: []interface{}{0}}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed an unsupported comparator", func() { - It("should error", func() { - success, err := (&BeNumericallyMatcher{Comparator: "!=", CompareTo: []interface{}{5}}).Match(4) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_sent_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_sent_matcher_test.go deleted file mode 100644 index 205d71f405..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_sent_matcher_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/gomega/matchers" - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("BeSent", func() { - Context("when passed a channel and a matching type", func() { - Context("when the channel is ready to receive", func() { - It("should succeed and send the value down the channel", func() { - c := make(chan string) - d := make(chan string) - go func() { - val := <-c - d <- val - }() - - time.Sleep(10 * time.Millisecond) - - Ω(c).Should(BeSent("foo")) - Eventually(d).Should(Receive(Equal("foo"))) - }) - - It("should succeed (with a buffered channel)", func() { - c := make(chan string, 1) - Ω(c).Should(BeSent("foo")) - Ω(<-c).Should(Equal("foo")) - }) - }) - - Context("when the channel is not ready to receive", func() { - It("should fail and not send down the channel", func() { - c := make(chan string) - Ω(c).ShouldNot(BeSent("foo")) - Consistently(c).ShouldNot(Receive()) - }) - }) - - Context("when the channel is eventually ready to receive", func() { - It("should succeed", func() { - c := make(chan string) - d := make(chan string) - go func() { - time.Sleep(30 * time.Millisecond) - val := <-c - d <- val - }() - - Eventually(c).Should(BeSent("foo")) - Eventually(d).Should(Receive(Equal("foo"))) - }) - }) - - Context("when the channel is closed", func() { - It("should error", func() { - c := make(chan string) - close(c) - success, err := (&BeSentMatcher{Arg: "foo"}).Match(c) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - - It("should short-circuit Eventually", func() { - c := make(chan string) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(c, 10.0).Should(BeSent("foo")) - }) - Ω(failures).Should(HaveLen(1)) - Ω(time.Since(t)).Should(BeNumerically("<", time.Second)) - }) - }) - }) - - Context("when passed a channel and a non-matching type", func() { - It("should error", func() { - success, err := (&BeSentMatcher{Arg: "foo"}).Match(make(chan int, 1)) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a receive-only channel", func() { - It("should error", func() { - var c <-chan string - c = make(chan string, 1) - success, err := (&BeSentMatcher{Arg: "foo"}).Match(c) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a nonchannel", func() { - It("should error", func() { - success, err := (&BeSentMatcher{Arg: "foo"}).Match("bar") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go index abda4eb1e7..cb7c038ef0 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go @@ -2,8 +2,9 @@ package matchers import ( "fmt" - "github.com/onsi/gomega/format" "time" + + "github.com/onsi/gomega/format" ) type BeTemporallyMatcher struct { diff --git a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go deleted file mode 100644 index feb33e5dc1..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher_test.go +++ /dev/null @@ -1,98 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" - "time" -) - -var _ = Describe("BeTemporally", func() { - - var t0, t1, t2 time.Time - BeforeEach(func() { - t0 = time.Now() - t1 = t0.Add(time.Second) - t2 = t0.Add(-time.Second) - }) - - Context("When comparing times", func() { - - It("should support ==", func() { - Ω(t0).Should(BeTemporally("==", t0)) - Ω(t1).ShouldNot(BeTemporally("==", t0)) - Ω(t0).ShouldNot(BeTemporally("==", t1)) - Ω(t0).ShouldNot(BeTemporally("==", time.Time{})) - }) - - It("should support >", func() { - Ω(t0).Should(BeTemporally(">", t2)) - Ω(t0).ShouldNot(BeTemporally(">", t0)) - Ω(t2).ShouldNot(BeTemporally(">", t0)) - }) - - It("should support <", func() { - Ω(t0).Should(BeTemporally("<", t1)) - Ω(t0).ShouldNot(BeTemporally("<", t0)) - Ω(t1).ShouldNot(BeTemporally("<", t0)) - }) - - It("should support >=", func() { - Ω(t0).Should(BeTemporally(">=", t2)) - Ω(t0).Should(BeTemporally(">=", t0)) - Ω(t0).ShouldNot(BeTemporally(">=", t1)) - }) - - It("should support <=", func() { - Ω(t0).Should(BeTemporally("<=", t1)) - Ω(t0).Should(BeTemporally("<=", t0)) - Ω(t0).ShouldNot(BeTemporally("<=", t2)) - }) - - Context("when passed ~", func() { - Context("and there is no precision parameter", func() { - BeforeEach(func() { - t1 = t0.Add(time.Millisecond / 2) - t2 = t0.Add(-2 * time.Millisecond) - }) - It("should approximate", func() { - Ω(t0).Should(BeTemporally("~", t0)) - Ω(t0).Should(BeTemporally("~", t1)) - Ω(t0).ShouldNot(BeTemporally("~", t2)) - }) - }) - - Context("and there is a precision parameter", func() { - BeforeEach(func() { - t2 = t0.Add(3 * time.Second) - }) - It("should use precision paramter", func() { - d := 2 * time.Second - Ω(t0).Should(BeTemporally("~", t0, d)) - Ω(t0).Should(BeTemporally("~", t1, d)) - Ω(t0).ShouldNot(BeTemporally("~", t2, d)) - }) - }) - }) - }) - - Context("when passed a non-time", func() { - It("should error", func() { - success, err := (&BeTemporallyMatcher{Comparator: "==", CompareTo: t0}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&BeTemporallyMatcher{Comparator: "=="}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed an unsupported comparator", func() { - It("should error", func() { - success, err := (&BeTemporallyMatcher{Comparator: "!=", CompareTo: t0}).Match(t2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go index 1275e5fc9d..ec57c5db4c 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go @@ -2,6 +2,7 @@ package matchers import ( "fmt" + "github.com/onsi/gomega/format" ) diff --git a/vendor/github.com/onsi/gomega/matchers/be_true_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_true_matcher_test.go deleted file mode 100644 index ca32e56bea..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_true_matcher_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("BeTrue", func() { - It("should handle true and false correctly", func() { - Ω(true).Should(BeTrue()) - Ω(false).ShouldNot(BeTrue()) - }) - - It("should only support booleans", func() { - success, err := (&BeTrueMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go index b39c9144be..26196f168f 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go @@ -1,8 +1,9 @@ package matchers import ( - "github.com/onsi/gomega/format" "reflect" + + "github.com/onsi/gomega/format" ) type BeZeroMatcher struct { diff --git a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_zero_matcher_test.go deleted file mode 100644 index 8ec3643c28..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("BeZero", func() { - It("should succeed if the passed in object is the zero value for its type", func() { - Ω(nil).Should(BeZero()) - - Ω("").Should(BeZero()) - Ω(" ").ShouldNot(BeZero()) - - Ω(0).Should(BeZero()) - Ω(1).ShouldNot(BeZero()) - - Ω(0.0).Should(BeZero()) - Ω(0.1).ShouldNot(BeZero()) - - // Ω([]int{}).Should(BeZero()) - Ω([]int{1}).ShouldNot(BeZero()) - - // Ω(map[string]int{}).Should(BeZero()) - Ω(map[string]int{"a": 1}).ShouldNot(BeZero()) - - Ω(myCustomType{}).Should(BeZero()) - Ω(myCustomType{s: "a"}).ShouldNot(BeZero()) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/consist_of_test.go b/vendor/github.com/onsi/gomega/matchers/consist_of_test.go deleted file mode 100644 index dcd1afe947..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/consist_of_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ConsistOf", func() { - Context("with a slice", func() { - It("should do the right thing", func() { - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("baz", "bar", "foo")) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo")) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "foo")) - }) - }) - - Context("with an array", func() { - It("should do the right thing", func() { - Ω([3]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω([3]string{"foo", "bar", "baz"}).Should(ConsistOf("baz", "bar", "foo")) - Ω([3]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo")) - Ω([3]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("baz", "foo")) - }) - }) - - Context("with a map", func() { - It("should apply to the values", func() { - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).Should(ConsistOf("foo", "bar", "baz")) - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).Should(ConsistOf("baz", "bar", "foo")) - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).ShouldNot(ConsistOf("baz", "bar", "foo", "foo")) - Ω(map[int]string{1: "foo", 2: "bar", 3: "baz"}).ShouldNot(ConsistOf("baz", "foo")) - }) - - }) - - Context("with anything else", func() { - It("should error", func() { - failures := InterceptGomegaFailures(func() { - Ω("foo").Should(ConsistOf("f", "o", "o")) - }) - - Ω(failures).Should(HaveLen(1)) - }) - }) - - Context("when passed matchers", func() { - It("should pass if the matchers pass", func() { - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", MatchRegexp("^ba"), "baz")) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"))) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("foo"))) - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("^ba"))) - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf("foo", MatchRegexp("^ba"), MatchRegexp("turducken"))) - }) - - It("should not depend on the order of the matchers", func() { - Ω([][]int{[]int{1, 2}, []int{2}}).Should(ConsistOf(ContainElement(1), ContainElement(2))) - Ω([][]int{[]int{1, 2}, []int{2}}).Should(ConsistOf(ContainElement(2), ContainElement(1))) - }) - - Context("when a matcher errors", func() { - It("should soldier on", func() { - Ω([]string{"foo", "bar", "baz"}).ShouldNot(ConsistOf(BeFalse(), "foo", "bar")) - Ω([]interface{}{"foo", "bar", false}).Should(ConsistOf(BeFalse(), ContainSubstring("foo"), "bar")) - }) - }) - }) - - Context("when passed exactly one argument, and that argument is a slice", func() { - It("should match against the elements of that argument", func() { - Ω([]string{"foo", "bar", "baz"}).Should(ConsistOf([]string{"foo", "bar", "baz"})) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/contain_element_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/contain_element_matcher_test.go deleted file mode 100644 index 38ee518fbc..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/contain_element_matcher_test.go +++ /dev/null @@ -1,76 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("ContainElement", func() { - Context("when passed a supported type", func() { - Context("and expecting a non-matcher", func() { - It("should do the right thing", func() { - Ω([2]int{1, 2}).Should(ContainElement(2)) - Ω([2]int{1, 2}).ShouldNot(ContainElement(3)) - - Ω([]int{1, 2}).Should(ContainElement(2)) - Ω([]int{1, 2}).ShouldNot(ContainElement(3)) - - Ω(map[string]int{"foo": 1, "bar": 2}).Should(ContainElement(2)) - Ω(map[int]int{3: 1, 4: 2}).ShouldNot(ContainElement(3)) - - arr := make([]myCustomType, 2) - arr[0] = myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}} - arr[1] = myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "c"}} - Ω(arr).Should(ContainElement(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}})) - Ω(arr).ShouldNot(ContainElement(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"b", "c"}})) - }) - }) - - Context("and expecting a matcher", func() { - It("should pass each element through the matcher", func() { - Ω([]int{1, 2, 3}).Should(ContainElement(BeNumerically(">=", 3))) - Ω([]int{1, 2, 3}).ShouldNot(ContainElement(BeNumerically(">", 3))) - Ω(map[string]int{"foo": 1, "bar": 2}).Should(ContainElement(BeNumerically(">=", 2))) - Ω(map[string]int{"foo": 1, "bar": 2}).ShouldNot(ContainElement(BeNumerically(">", 2))) - }) - - It("should power through even if the matcher ever fails", func() { - Ω([]interface{}{1, 2, "3", 4}).Should(ContainElement(BeNumerically(">=", 3))) - }) - - It("should fail if the matcher fails", func() { - actual := []interface{}{1, 2, "3", "4"} - success, err := (&ContainElementMatcher{Element: BeNumerically(">=", 3)}).Match(actual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilSlice []int - Ω(nilSlice).ShouldNot(ContainElement(1)) - - var nilMap map[int]string - Ω(nilMap).ShouldNot(ContainElement("foo")) - }) - }) - - Context("when passed an unsupported type", func() { - It("should error", func() { - success, err := (&ContainElementMatcher{Element: 0}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ContainElementMatcher{Element: 0}).Match("abc") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ContainElementMatcher{Element: 0}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go b/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go index 2e7608921a..f8dc41e74f 100644 --- a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go @@ -2,8 +2,9 @@ package matchers import ( "fmt" - "github.com/onsi/gomega/format" "strings" + + "github.com/onsi/gomega/format" ) type ContainSubstringMatcher struct { diff --git a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go deleted file mode 100644 index 6935168e5c..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("ContainSubstringMatcher", func() { - Context("when actual is a string", func() { - It("should match against the string", func() { - Ω("Marvelous").Should(ContainSubstring("rve")) - Ω("Marvelous").ShouldNot(ContainSubstring("boo")) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω("Marvelous3").Should(ContainSubstring("velous%d", 3)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match agains the returned string", func() { - Ω(&myStringer{a: "Abc3"}).Should(ContainSubstring("bc3")) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&ContainSubstringMatcher{Substr: "2"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/equal_matcher.go b/vendor/github.com/onsi/gomega/matchers/equal_matcher.go index 874e6a6229..befb7bdfd8 100644 --- a/vendor/github.com/onsi/gomega/matchers/equal_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/equal_matcher.go @@ -1,6 +1,7 @@ package matchers import ( + "bytes" "fmt" "reflect" @@ -15,6 +16,14 @@ func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) if actual == nil && matcher.Expected == nil { return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") } + // Shortcut for byte slices. + // Comparing long byte slices with reflect.DeepEqual is very slow, + // so use bytes.Equal if actual and expected are both byte slices. + if actualByteSlice, ok := actual.([]byte); ok { + if expectedByteSlice, ok := matcher.Expected.([]byte); ok { + return bytes.Equal(actualByteSlice, expectedByteSlice), nil + } + } return reflect.DeepEqual(actual, matcher.Expected), nil } diff --git a/vendor/github.com/onsi/gomega/matchers/equal_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/equal_matcher_test.go deleted file mode 100644 index 2add0b7499..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/equal_matcher_test.go +++ /dev/null @@ -1,78 +0,0 @@ -package matchers_test - -import ( - "errors" - "strings" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("Equal", func() { - Context("when asserting that nil equals nil", func() { - It("should error", func() { - success, err := (&EqualMatcher{Expected: nil}).Match(nil) - - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("When asserting equality between objects", func() { - It("should do the right thing", func() { - Ω(5).Should(Equal(5)) - Ω(5.0).Should(Equal(5.0)) - - Ω(5).ShouldNot(Equal("5")) - Ω(5).ShouldNot(Equal(5.0)) - Ω(5).ShouldNot(Equal(3)) - - Ω("5").Should(Equal("5")) - Ω([]int{1, 2}).Should(Equal([]int{1, 2})) - Ω([]int{1, 2}).ShouldNot(Equal([]int{2, 1})) - Ω(map[string]string{"a": "b", "c": "d"}).Should(Equal(map[string]string{"a": "b", "c": "d"})) - Ω(map[string]string{"a": "b", "c": "d"}).ShouldNot(Equal(map[string]string{"a": "b", "c": "e"})) - Ω(errors.New("foo")).Should(Equal(errors.New("foo"))) - Ω(errors.New("foo")).ShouldNot(Equal(errors.New("bar"))) - - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).Should(Equal(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "bar", n: 3, f: 2.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 2, f: 2.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 3, f: 3.0, arr: []string{"a", "b"}})) - Ω(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).ShouldNot(Equal(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b", "c"}})) - }) - }) - - Describe("failure messages", func() { - It("shows the two strings simply when they are short", func() { - subject := EqualMatcher{Expected: "eric"} - - failureMessage := subject.FailureMessage("tim") - Ω(failureMessage).To(BeEquivalentTo(expectedShortStringFailureMessage)) - }) - - It("shows the exact point where two long strings differ", func() { - stringWithB := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - stringWithZ := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaazaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - - subject := EqualMatcher{Expected: stringWithZ} - - failureMessage := subject.FailureMessage(stringWithB) - Ω(failureMessage).To(BeEquivalentTo(expectedLongStringFailureMessage)) - }) - }) -}) - -var expectedShortStringFailureMessage = strings.TrimSpace(` -Expected - : tim -to equal - : eric -`) -var expectedLongStringFailureMessage = strings.TrimSpace(` -Expected - : "...aaaaabaaaaa..." -to equal | - : "...aaaaazaaaaa..." -`) diff --git a/vendor/github.com/onsi/gomega/matchers/have_cap_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_cap_matcher_test.go deleted file mode 100644 index a92a177b58..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_cap_matcher_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveCap", func() { - Context("when passed a supported type", func() { - It("should do the right thing", func() { - Ω([0]int{}).Should(HaveCap(0)) - Ω([2]int{1}).Should(HaveCap(2)) - - Ω([]int{}).Should(HaveCap(0)) - Ω([]int{1, 2, 3, 4, 5}[:2]).Should(HaveCap(5)) - Ω(make([]int, 0, 5)).Should(HaveCap(5)) - - c := make(chan bool, 3) - Ω(c).Should(HaveCap(3)) - c <- true - c <- true - Ω(c).Should(HaveCap(3)) - - Ω(make(chan bool)).Should(HaveCap(0)) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilSlice []int - Ω(nilSlice).Should(HaveCap(0)) - - var nilChan chan int - Ω(nilChan).Should(HaveCap(0)) - }) - }) - - Context("when passed an unsupported type", func() { - It("should error", func() { - success, err := (&HaveCapMatcher{Count: 0}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveCapMatcher{Count: 0}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go index 5701ba6e24..ea5b923366 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go @@ -2,8 +2,9 @@ package matchers import ( "fmt" - "github.com/onsi/gomega/format" "reflect" + + "github.com/onsi/gomega/format" ) type HaveKeyMatcher struct { diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_key_matcher_test.go deleted file mode 100644 index c663e302ba..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_key_matcher_test.go +++ /dev/null @@ -1,73 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveKey", func() { - var ( - stringKeys map[string]int - intKeys map[int]string - objKeys map[*myCustomType]string - - customA *myCustomType - customB *myCustomType - ) - BeforeEach(func() { - stringKeys = map[string]int{"foo": 2, "bar": 3} - intKeys = map[int]string{2: "foo", 3: "bar"} - - customA = &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}} - customB = &myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}} - objKeys = map[*myCustomType]string{customA: "aardvark", customB: "kangaroo"} - }) - - Context("when passed a map", func() { - It("should do the right thing", func() { - Ω(stringKeys).Should(HaveKey("foo")) - Ω(stringKeys).ShouldNot(HaveKey("baz")) - - Ω(intKeys).Should(HaveKey(2)) - Ω(intKeys).ShouldNot(HaveKey(4)) - - Ω(objKeys).Should(HaveKey(customA)) - Ω(objKeys).Should(HaveKey(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}})) - Ω(objKeys).ShouldNot(HaveKey(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"apple", "pie"}})) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilMap map[int]string - Ω(nilMap).ShouldNot(HaveKey("foo")) - }) - }) - - Context("when the passed in key is actually a matcher", func() { - It("should pass each element through the matcher", func() { - Ω(stringKeys).Should(HaveKey(ContainSubstring("oo"))) - Ω(stringKeys).ShouldNot(HaveKey(ContainSubstring("foobar"))) - }) - - It("should fail if the matcher ever fails", func() { - actual := map[int]string{1: "a", 3: "b", 2: "c"} - success, err := (&HaveKeyMatcher{Key: ContainSubstring("ar")}).Match(actual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed something that is not a map", func() { - It("should error", func() { - success, err := (&HaveKeyMatcher{Key: "foo"}).Match([]string{"foo"}) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveKeyMatcher{Key: "foo"}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go index 464ac187e9..06355b1e95 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go @@ -2,8 +2,9 @@ package matchers import ( "fmt" - "github.com/onsi/gomega/format" "reflect" + + "github.com/onsi/gomega/format" ) type HaveKeyWithValueMatcher struct { diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go deleted file mode 100644 index 06a2242aec..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveKeyWithValue", func() { - var ( - stringKeys map[string]int - intKeys map[int]string - objKeys map[*myCustomType]*myCustomType - - customA *myCustomType - customB *myCustomType - ) - BeforeEach(func() { - stringKeys = map[string]int{"foo": 2, "bar": 3} - intKeys = map[int]string{2: "foo", 3: "bar"} - - customA = &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}} - customB = &myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}} - objKeys = map[*myCustomType]*myCustomType{customA: customA, customB: customA} - }) - - Context("when passed a map", func() { - It("should do the right thing", func() { - Ω(stringKeys).Should(HaveKeyWithValue("foo", 2)) - Ω(stringKeys).ShouldNot(HaveKeyWithValue("foo", 1)) - Ω(stringKeys).ShouldNot(HaveKeyWithValue("baz", 2)) - Ω(stringKeys).ShouldNot(HaveKeyWithValue("baz", 1)) - - Ω(intKeys).Should(HaveKeyWithValue(2, "foo")) - Ω(intKeys).ShouldNot(HaveKeyWithValue(4, "foo")) - Ω(intKeys).ShouldNot(HaveKeyWithValue(2, "baz")) - - Ω(objKeys).Should(HaveKeyWithValue(customA, customA)) - Ω(objKeys).Should(HaveKeyWithValue(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"cake"}}, &myCustomType{s: "a", n: 2, f: 2.3, arr: []string{"ice", "cream"}})) - Ω(objKeys).ShouldNot(HaveKeyWithValue(&myCustomType{s: "b", n: 4, f: 3.1, arr: []string{"apple", "pie"}}, customA)) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilMap map[int]string - Ω(nilMap).ShouldNot(HaveKeyWithValue("foo", "bar")) - }) - }) - - Context("when the passed in key or value is actually a matcher", func() { - It("should pass each element through the matcher", func() { - Ω(stringKeys).Should(HaveKeyWithValue(ContainSubstring("oo"), 2)) - Ω(intKeys).Should(HaveKeyWithValue(2, ContainSubstring("oo"))) - Ω(stringKeys).ShouldNot(HaveKeyWithValue(ContainSubstring("foobar"), 2)) - }) - - It("should fail if the matcher ever fails", func() { - actual := map[int]string{1: "a", 3: "b", 2: "c"} - success, err := (&HaveKeyWithValueMatcher{Key: ContainSubstring("ar"), Value: 2}).Match(actual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - otherActual := map[string]int{"a": 1, "b": 2, "c": 3} - success, err = (&HaveKeyWithValueMatcher{Key: "a", Value: ContainSubstring("1")}).Match(otherActual) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed something that is not a map", func() { - It("should error", func() { - success, err := (&HaveKeyWithValueMatcher{Key: "foo", Value: "bar"}).Match([]string{"foo"}) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveKeyWithValueMatcher{Key: "foo", Value: "bar"}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go index a183775570..ee4276189d 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go @@ -2,6 +2,7 @@ package matchers import ( "fmt" + "github.com/onsi/gomega/format" ) diff --git a/vendor/github.com/onsi/gomega/matchers/have_len_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_len_matcher_test.go deleted file mode 100644 index 1e6aa69d9d..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_len_matcher_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveLen", func() { - Context("when passed a supported type", func() { - It("should do the right thing", func() { - Ω("").Should(HaveLen(0)) - Ω("AA").Should(HaveLen(2)) - - Ω([0]int{}).Should(HaveLen(0)) - Ω([2]int{1, 2}).Should(HaveLen(2)) - - Ω([]int{}).Should(HaveLen(0)) - Ω([]int{1, 2, 3}).Should(HaveLen(3)) - - Ω(map[string]int{}).Should(HaveLen(0)) - Ω(map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}).Should(HaveLen(4)) - - c := make(chan bool, 3) - Ω(c).Should(HaveLen(0)) - c <- true - c <- true - Ω(c).Should(HaveLen(2)) - }) - }) - - Context("when passed a correctly typed nil", func() { - It("should operate succesfully on the passed in value", func() { - var nilSlice []int - Ω(nilSlice).Should(HaveLen(0)) - - var nilMap map[int]string - Ω(nilMap).Should(HaveLen(0)) - }) - }) - - Context("when passed an unsupported type", func() { - It("should error", func() { - success, err := (&HaveLenMatcher{Count: 0}).Match(0) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveLenMatcher{Count: 0}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go deleted file mode 100644 index 009e23e5fc..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package matchers_test - -import ( - "errors" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -type CustomErr struct { - msg string -} - -func (e *CustomErr) Error() string { - return e.msg -} - -var _ = Describe("HaveOccurred", func() { - It("should succeed if matching an error", func() { - Ω(errors.New("Foo")).Should(HaveOccurred()) - }) - - It("should not succeed with nil", func() { - Ω(nil).ShouldNot(HaveOccurred()) - }) - - It("should only support errors and nil", func() { - success, err := (&HaveOccurredMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&HaveOccurredMatcher{}).Match("") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - - It("doesn't support non-error type", func() { - success, err := (&HaveOccurredMatcher{}).Match(AnyType{}) - Ω(success).Should(BeFalse()) - Ω(err).Should(MatchError("Expected an error-type. Got:\n : {}")) - }) - - It("doesn't support non-error pointer type", func() { - success, err := (&HaveOccurredMatcher{}).Match(&AnyType{}) - Ω(success).Should(BeFalse()) - Ω(err).Should(MatchError(MatchRegexp(`Expected an error-type. Got:\n <*matchers_test.AnyType | 0x[[:xdigit:]]+>: {}`))) - }) - - It("should succeed with pointer types that conform to error interface", func() { - err := &CustomErr{"ohai"} - Ω(err).Should(HaveOccurred()) - }) - - It("should not succeed with nil pointers to types that conform to error interface", func() { - var err *CustomErr = nil - Ω(err).ShouldNot(HaveOccurred()) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go index 8b63a89997..1d8e80270b 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go @@ -2,6 +2,7 @@ package matchers import ( "fmt" + "github.com/onsi/gomega/format" ) diff --git a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go deleted file mode 100644 index bec3f97582..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HavePrefixMatcher", func() { - Context("when actual is a string", func() { - It("should match a string prefix", func() { - Ω("Ab").Should(HavePrefix("A")) - Ω("A").ShouldNot(HavePrefix("Ab")) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω("C3PO").Should(HavePrefix("C%dP", 3)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match against the returned string", func() { - Ω(&myStringer{a: "Ab"}).Should(HavePrefix("A")) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&HavePrefixMatcher{Prefix: "2"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go index afc78fc901..40a3526eb2 100644 --- a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go @@ -2,6 +2,7 @@ package matchers import ( "fmt" + "github.com/onsi/gomega/format" ) diff --git a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go deleted file mode 100644 index 72e8975bae..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("HaveSuffixMatcher", func() { - Context("when actual is a string", func() { - It("should match a string suffix", func() { - Ω("Ab").Should(HaveSuffix("b")) - Ω("A").ShouldNot(HaveSuffix("Ab")) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω("C3PO").Should(HaveSuffix("%dPO", 3)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match against the returned string", func() { - Ω(&myStringer{a: "Ab"}).Should(HaveSuffix("b")) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&HaveSuffixMatcher{Suffix: "2"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go index 03cdf04588..07499ac959 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go @@ -2,8 +2,9 @@ package matchers import ( "fmt" - "github.com/onsi/gomega/format" "reflect" + + "github.com/onsi/gomega/format" ) type MatchErrorMatcher struct { @@ -21,14 +22,14 @@ func (matcher *MatchErrorMatcher) Match(actual interface{}) (success bool, err e actualErr := actual.(error) - if isString(matcher.Expected) { - return reflect.DeepEqual(actualErr.Error(), matcher.Expected), nil - } - if isError(matcher.Expected) { return reflect.DeepEqual(actualErr, matcher.Expected), nil } + if isString(matcher.Expected) { + return actualErr.Error() == matcher.Expected, nil + } + var subMatcher omegaMatcher var hasSubMatcher bool if matcher.Expected != nil { diff --git a/vendor/github.com/onsi/gomega/matchers/match_error_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/match_error_matcher_test.go deleted file mode 100644 index 338b512954..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/match_error_matcher_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package matchers_test - -import ( - "errors" - "fmt" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -type CustomError struct { -} - -func (c CustomError) Error() string { - return "an error" -} - -var _ = Describe("MatchErrorMatcher", func() { - Context("When asserting against an error", func() { - It("should succeed when matching with an error", func() { - err := errors.New("an error") - fmtErr := fmt.Errorf("an error") - customErr := CustomError{} - - Ω(err).Should(MatchError(errors.New("an error"))) - Ω(err).ShouldNot(MatchError(errors.New("another error"))) - - Ω(fmtErr).Should(MatchError(errors.New("an error"))) - Ω(customErr).Should(MatchError(CustomError{})) - }) - - It("should succeed when matching with a string", func() { - err := errors.New("an error") - fmtErr := fmt.Errorf("an error") - customErr := CustomError{} - - Ω(err).Should(MatchError("an error")) - Ω(err).ShouldNot(MatchError("another error")) - - Ω(fmtErr).Should(MatchError("an error")) - Ω(customErr).Should(MatchError("an error")) - }) - - Context("when passed a matcher", func() { - It("should pass if the matcher passes against the error string", func() { - err := errors.New("error 123 abc") - - Ω(err).Should(MatchError(MatchRegexp(`\d{3}`))) - }) - - It("should fail if the matcher fails against the error string", func() { - err := errors.New("no digits") - Ω(err).ShouldNot(MatchError(MatchRegexp(`\d`))) - }) - }) - - It("should fail when passed anything else", func() { - actualErr := errors.New("an error") - _, err := (&MatchErrorMatcher{ - Expected: []byte("an error"), - }).Match(actualErr) - Ω(err).Should(HaveOccurred()) - - _, err = (&MatchErrorMatcher{ - Expected: 3, - }).Match(actualErr) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed nil", func() { - It("should fail", func() { - _, err := (&MatchErrorMatcher{ - Expected: "an error", - }).Match(nil) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a non-error", func() { - It("should fail", func() { - _, err := (&MatchErrorMatcher{ - Expected: "an error", - }).Match("an error") - Ω(err).Should(HaveOccurred()) - - _, err = (&MatchErrorMatcher{ - Expected: "an error", - }).Match(3) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go deleted file mode 100644 index 459448391c..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go +++ /dev/null @@ -1,97 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("MatchJSONMatcher", func() { - Context("When passed stringifiables", func() { - It("should succeed if the JSON matches", func() { - Ω("{}").Should(MatchJSON("{}")) - Ω(`{"a":1}`).Should(MatchJSON(`{"a":1}`)) - Ω(`{ - "a":1 - }`).Should(MatchJSON(`{"a":1}`)) - Ω(`{"a":1, "b":2}`).Should(MatchJSON(`{"b":2, "a":1}`)) - Ω(`{"a":1}`).ShouldNot(MatchJSON(`{"b":2, "a":1}`)) - - Ω(`{"a":"a", "b":"b"}`).ShouldNot(MatchJSON(`{"a":"a", "b":"b", "c":"c"}`)) - Ω(`{"a":"a", "b":"b", "c":"c"}`).ShouldNot(MatchJSON(`{"a":"a", "b":"b"}`)) - - Ω(`{"a":null, "b":null}`).ShouldNot(MatchJSON(`{"c":"c", "d":"d"}`)) - Ω(`{"a":null, "b":null, "c":null}`).ShouldNot(MatchJSON(`{"a":null, "b":null, "d":null}`)) - }) - - It("should work with byte arrays", func() { - Ω([]byte("{}")).Should(MatchJSON([]byte("{}"))) - Ω("{}").Should(MatchJSON([]byte("{}"))) - Ω([]byte("{}")).Should(MatchJSON("{}")) - }) - }) - - Context("when a key mismatch is found", func() { - It("reports the first found mismatch", func() { - subject := MatchJSONMatcher{JSONToMatch: `5`} - actual := `7` - subject.Match(actual) - - failureMessage := subject.FailureMessage(`7`) - Ω(failureMessage).ToNot(ContainSubstring("first mismatched key")) - - subject = MatchJSONMatcher{JSONToMatch: `{"a": 1, "b.g": {"c": 2, "1": ["hello", "see ya"]}}`} - actual = `{"a": 1, "b.g": {"c": 2, "1": ["hello", "goodbye"]}}` - subject.Match(actual) - - failureMessage = subject.FailureMessage(actual) - Ω(failureMessage).To(ContainSubstring(`first mismatched key: "b.g"."1"[1]`)) - }) - }) - - Context("when the expected is not valid JSON", func() { - It("should error and explain why", func() { - success, err := (&MatchJSONMatcher{JSONToMatch: `{}`}).Match(`oops`) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("Actual 'oops' should be valid JSON")) - }) - }) - - Context("when the actual is not valid JSON", func() { - It("should error and explain why", func() { - success, err := (&MatchJSONMatcher{JSONToMatch: `oops`}).Match(`{}`) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("Expected 'oops' should be valid JSON")) - }) - }) - - Context("when the expected is neither a string nor a stringer nor a byte array", func() { - It("should error", func() { - success, err := (&MatchJSONMatcher{JSONToMatch: 2}).Match("{}") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got expected:\n : 2")) - - success, err = (&MatchJSONMatcher{JSONToMatch: nil}).Match("{}") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got expected:\n : nil")) - }) - }) - - Context("when the actual is neither a string nor a stringer nor a byte array", func() { - It("should error", func() { - success, err := (&MatchJSONMatcher{JSONToMatch: "{}"}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n : 2")) - - success, err = (&MatchJSONMatcher{JSONToMatch: "{}"}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n : nil")) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go index 7ca79a15be..adac5db6b8 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go @@ -2,8 +2,9 @@ package matchers import ( "fmt" - "github.com/onsi/gomega/format" "regexp" + + "github.com/onsi/gomega/format" ) type MatchRegexpMatcher struct { diff --git a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go deleted file mode 100644 index bb521cce34..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("MatchRegexp", func() { - Context("when actual is a string", func() { - It("should match against the string", func() { - Ω(" a2!bla").Should(MatchRegexp(`\d!`)) - Ω(" a2!bla").ShouldNot(MatchRegexp(`[A-Z]`)) - }) - }) - - Context("when actual is a stringer", func() { - It("should call the stringer and match agains the returned string", func() { - Ω(&myStringer{a: "Abc3"}).Should(MatchRegexp(`[A-Z][a-z]+\d`)) - }) - }) - - Context("when the matcher is called with multiple arguments", func() { - It("should pass the string and arguments to sprintf", func() { - Ω(" a23!bla").Should(MatchRegexp(`\d%d!`, 3)) - }) - }) - - Context("when actual is neither a string nor a stringer", func() { - It("should error", func() { - success, err := (&MatchRegexpMatcher{Regexp: `\d`}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when the passed in regexp fails to compile", func() { - It("should error", func() { - success, err := (&MatchRegexpMatcher{Regexp: "("}).Match("Foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go index da26562902..3b412ce818 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "reflect" + "sort" "strings" "github.com/onsi/gomega/format" @@ -82,6 +83,8 @@ func parseXmlContent(content string) (*xmlNode, error) { switch tok := tok.(type) { case xml.StartElement: + attrs := attributesSlice(tok.Attr) + sort.Sort(attrs) allNodes = append(allNodes, &xmlNode{XMLName: tok.Name, XMLAttr: tok.Attr}) case xml.EndElement: if len(allNodes) > 1 { diff --git a/vendor/github.com/onsi/gomega/matchers/match_xml_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/match_xml_matcher_test.go deleted file mode 100644 index 16c1922407..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/match_xml_matcher_test.go +++ /dev/null @@ -1,90 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("MatchXMLMatcher", func() { - - var ( - sample_01 = readFileContents("test_data/xml/sample_01.xml") - sample_02 = readFileContents("test_data/xml/sample_02.xml") - sample_03 = readFileContents("test_data/xml/sample_03.xml") - sample_04 = readFileContents("test_data/xml/sample_04.xml") - sample_05 = readFileContents("test_data/xml/sample_05.xml") - sample_06 = readFileContents("test_data/xml/sample_06.xml") - sample_07 = readFileContents("test_data/xml/sample_07.xml") - sample_08 = readFileContents("test_data/xml/sample_08.xml") - sample_09 = readFileContents("test_data/xml/sample_09.xml") - sample_10 = readFileContents("test_data/xml/sample_10.xml") - sample_11 = readFileContents("test_data/xml/sample_11.xml") - ) - - Context("When passed stringifiables", func() { - It("should succeed if the XML matches", func() { - Ω(sample_01).Should(MatchXML(sample_01)) // same XML - Ω(sample_01).Should(MatchXML(sample_02)) // same XML with blank lines - Ω(sample_01).Should(MatchXML(sample_03)) // same XML with different formatting - Ω(sample_01).ShouldNot(MatchXML(sample_04)) // same structures with different values - Ω(sample_01).ShouldNot(MatchXML(sample_05)) // different structures - Ω(sample_06).ShouldNot(MatchXML(sample_07)) // same xml names with different namespaces - Ω(sample_07).ShouldNot(MatchXML(sample_08)) // same structures with different values - Ω(sample_09).ShouldNot(MatchXML(sample_10)) // same structures with different attribute values - Ω(sample_11).Should(MatchXML(sample_11)) // with non UTF-8 encoding - }) - - It("should work with byte arrays", func() { - Ω([]byte(sample_01)).Should(MatchXML([]byte(sample_01))) - Ω([]byte(sample_01)).Should(MatchXML(sample_01)) - Ω(sample_01).Should(MatchXML([]byte(sample_01))) - }) - }) - - Context("when the expected is not valid XML", func() { - It("should error and explain why", func() { - success, err := (&MatchXMLMatcher{XMLToMatch: sample_01}).Match(`oops`) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("Actual 'oops' should be valid XML")) - }) - }) - - Context("when the actual is not valid XML", func() { - It("should error and explain why", func() { - success, err := (&MatchXMLMatcher{XMLToMatch: `oops`}).Match(sample_01) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("Expected 'oops' should be valid XML")) - }) - }) - - Context("when the expected is neither a string nor a stringer nor a byte array", func() { - It("should error", func() { - success, err := (&MatchXMLMatcher{XMLToMatch: 2}).Match(sample_01) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n : 2")) - - success, err = (&MatchXMLMatcher{XMLToMatch: nil}).Match(sample_01) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n : nil")) - }) - }) - - Context("when the actual is neither a string nor a stringer nor a byte array", func() { - It("should error", func() { - success, err := (&MatchXMLMatcher{XMLToMatch: sample_01}).Match(2) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n : 2")) - - success, err = (&MatchXMLMatcher{XMLToMatch: sample_01}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - Ω(err.Error()).Should(ContainSubstring("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n : nil")) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher_test.go deleted file mode 100644 index 8e63de19e3..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher_test.go +++ /dev/null @@ -1,94 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("MatchYAMLMatcher", func() { - Context("When passed stringifiables", func() { - It("should succeed if the YAML matches", func() { - Expect("---").Should(MatchYAML("")) - Expect("a: 1").Should(MatchYAML(`{"a":1}`)) - Expect("a: 1\nb: 2").Should(MatchYAML(`{"b":2, "a":1}`)) - }) - - It("should explain if the YAML does not match when it should", func() { - message := (&MatchYAMLMatcher{YAMLToMatch: "a: 1"}).FailureMessage("b: 2") - Expect(message).To(MatchRegexp(`Expected\s+: b: 2\s+to match YAML of\s+: a: 1`)) - }) - - It("should normalise the expected and actual when explaining if the YAML does not match when it should", func() { - message := (&MatchYAMLMatcher{YAMLToMatch: "a: 'one'"}).FailureMessage("{b: two}") - Expect(message).To(MatchRegexp(`Expected\s+: b: two\s+to match YAML of\s+: a: one`)) - }) - - It("should explain if the YAML matches when it should not", func() { - message := (&MatchYAMLMatcher{YAMLToMatch: "a: 1"}).NegatedFailureMessage("a: 1") - Expect(message).To(MatchRegexp(`Expected\s+: a: 1\s+not to match YAML of\s+: a: 1`)) - }) - - It("should normalise the expected and actual when explaining if the YAML matches when it should not", func() { - message := (&MatchYAMLMatcher{YAMLToMatch: "a: 'one'"}).NegatedFailureMessage("{a: one}") - Expect(message).To(MatchRegexp(`Expected\s+: a: one\s+not to match YAML of\s+: a: one`)) - }) - - It("should fail if the YAML does not match", func() { - Expect("a: 1").ShouldNot(MatchYAML(`{"b":2, "a":1}`)) - }) - - It("should work with byte arrays", func() { - Expect([]byte("a: 1")).Should(MatchYAML([]byte("a: 1"))) - Expect("a: 1").Should(MatchYAML([]byte("a: 1"))) - Expect([]byte("a: 1")).Should(MatchYAML("a: 1")) - }) - }) - - Context("when the expected is not valid YAML", func() { - It("should error and explain why", func() { - success, err := (&MatchYAMLMatcher{YAMLToMatch: ""}).Match("good:\nbad") - Expect(success).Should(BeFalse()) - Expect(err).Should(HaveOccurred()) - Expect(err.Error()).Should(ContainSubstring("Actual 'good:\nbad' should be valid YAML")) - }) - }) - - Context("when the actual is not valid YAML", func() { - It("should error and explain why", func() { - success, err := (&MatchYAMLMatcher{YAMLToMatch: "good:\nbad"}).Match("") - Expect(success).Should(BeFalse()) - Expect(err).Should(HaveOccurred()) - Expect(err.Error()).Should(ContainSubstring("Expected 'good:\nbad' should be valid YAML")) - }) - }) - - Context("when the expected is neither a string nor a stringer nor a byte array", func() { - It("should error", func() { - success, err := (&MatchYAMLMatcher{YAMLToMatch: 2}).Match("") - Expect(success).Should(BeFalse()) - Expect(err).Should(HaveOccurred()) - Expect(err.Error()).Should(ContainSubstring("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n : 2")) - - success, err = (&MatchYAMLMatcher{YAMLToMatch: nil}).Match("") - Expect(success).Should(BeFalse()) - Expect(err).Should(HaveOccurred()) - Expect(err.Error()).Should(ContainSubstring("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n : nil")) - }) - }) - - Context("when the actual is neither a string nor a stringer nor a byte array", func() { - It("should error", func() { - success, err := (&MatchYAMLMatcher{YAMLToMatch: ""}).Match(2) - Expect(success).Should(BeFalse()) - Expect(err).Should(HaveOccurred()) - Expect(err.Error()).Should(ContainSubstring("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n : 2")) - - success, err = (&MatchYAMLMatcher{YAMLToMatch: ""}).Match(nil) - Expect(success).Should(BeFalse()) - Expect(err).Should(HaveOccurred()) - Expect(err.Error()).Should(ContainSubstring("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n : nil")) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go b/vendor/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go deleted file mode 100644 index b5f76c9959..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/matcher_tests_suite_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package matchers_test - -import ( - "fmt" - "io/ioutil" - "os" - "testing" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -type myStringer struct { - a string -} - -func (s *myStringer) String() string { - return s.a -} - -type StringAlias string - -type myCustomType struct { - s string - n int - f float32 - arr []string -} - -func Test(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Gomega Matchers") -} - -func readFileContents(filePath string) []byte { - f := openFile(filePath) - b, err := ioutil.ReadAll(f) - if err != nil { - panic(fmt.Errorf("failed to read file contents: %v", err)) - } - return b -} - -func openFile(filePath string) *os.File { - f, err := os.Open(filePath) - if err != nil { - panic(fmt.Errorf("failed to open file: %v", err)) - } - return f -} diff --git a/vendor/github.com/onsi/gomega/matchers/not_test.go b/vendor/github.com/onsi/gomega/matchers/not_test.go deleted file mode 100644 index b3c1fdbf0b..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/not_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("NotMatcher", func() { - Context("basic examples", func() { - It("works", func() { - Expect(input).To(Not(false1)) - Expect(input).To(Not(Not(true2))) - Expect(input).ToNot(Not(true3)) - Expect(input).ToNot(Not(Not(false1))) - Expect(input).To(Not(Not(Not(false2)))) - }) - }) - - Context("De Morgan's laws", func() { - It("~(A && B) == ~A || ~B", func() { - Expect(input).To(Not(And(false1, false2))) - Expect(input).To(Or(Not(false1), Not(false2))) - }) - It("~(A || B) == ~A && ~B", func() { - Expect(input).To(Not(Or(false1, false2))) - Expect(input).To(And(Not(false1), Not(false2))) - }) - }) - - Context("failure messages are opposite of original matchers' failure messages", func() { - Context("when match fails", func() { - It("gives a descriptive message", func() { - verifyFailureMessage(Not(HaveLen(2)), input, "not to have length 2") - }) - }) - - Context("when match succeeds, but expected it to fail", func() { - It("gives a descriptive message", func() { - verifyFailureMessage(Not(Not(HaveLen(3))), input, "to have length 3") - }) - }) - }) - - Context("MatchMayChangeInTheFuture()", func() { - It("Propagates value from wrapped matcher", func() { - m := Not(Or()) // an empty Or() always returns false, and indicates it cannot change - Expect(m.Match("anything")).To(BeTrue()) - Expect(m.(*NotMatcher).MatchMayChangeInTheFuture("anything")).To(BeFalse()) - }) - It("Defaults to true", func() { - m := Not(Equal(1)) // Equal does not have this method - Expect(m.Match(2)).To(BeTrue()) - Expect(m.(*NotMatcher).MatchMayChangeInTheFuture(2)).To(BeTrue()) // defaults to true - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/or_test.go b/vendor/github.com/onsi/gomega/matchers/or_test.go deleted file mode 100644 index 9589a174da..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/or_test.go +++ /dev/null @@ -1,85 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("OrMatcher", func() { - It("works with positive cases", func() { - Expect(input).To(Or(true1)) - Expect(input).To(Or(true1, true2)) - Expect(input).To(Or(true1, false1)) - Expect(input).To(Or(false1, true2)) - Expect(input).To(Or(true1, true2, true3)) - Expect(input).To(Or(true1, true2, false3)) - Expect(input).To(Or(true1, false2, true3)) - Expect(input).To(Or(false1, true2, true3)) - Expect(input).To(Or(true1, false2, false3)) - Expect(input).To(Or(false1, false2, true3)) - - // use alias - Expect(input).To(SatisfyAny(false1, false2, true3)) - }) - - It("works with negative cases", func() { - Expect(input).ToNot(Or()) - Expect(input).ToNot(Or(false1)) - Expect(input).ToNot(Or(false1, false2)) - Expect(input).ToNot(Or(false1, false2, false3)) - }) - - Context("failure messages", func() { - Context("when match fails", func() { - It("gives a descriptive message", func() { - verifyFailureMessage(Or(false1, false2), input, - "To satisfy at least one of these matchers: [%!s(*matchers.HaveLenMatcher=&{1}) %!s(*matchers.EqualMatcher=&{hip})]") - }) - }) - - Context("when match succeeds, but expected it to fail", func() { - It("gives a descriptive message", func() { - verifyFailureMessage(Not(Or(true1, true2)), input, `not to have length 2`) - }) - }) - }) - - Context("MatchMayChangeInTheFuture", func() { - Context("Match returned false", func() { - It("returns true if any of the matchers could change", func() { - // 3 matchers, all return false, and all could change - m := Or(BeNil(), Equal("hip"), HaveLen(1)) - Expect(m.Match("hi")).To(BeFalse()) - Expect(m.(*OrMatcher).MatchMayChangeInTheFuture("hi")).To(BeTrue()) // all 3 of these matchers default to 'true' - }) - It("returns false if none of the matchers could change", func() { - // empty Or() has the property of never matching, and never can change since there are no sub-matchers that could change - m := Or() - Expect(m.Match("anything")).To(BeFalse()) - Expect(m.(*OrMatcher).MatchMayChangeInTheFuture("anything")).To(BeFalse()) - - // Or() with 3 sub-matchers that return false, and can't change - m = Or(Or(), Or(), Or()) - Expect(m.Match("hi")).To(BeFalse()) - Expect(m.(*OrMatcher).MatchMayChangeInTheFuture("hi")).To(BeFalse()) // the 3 empty Or()'s won't change - }) - }) - Context("Match returned true", func() { - Context("returns value of the successful matcher", func() { - It("false if successful matcher not going to change", func() { - // 3 matchers: 1st returns false, 2nd returns true and is not going to change, 3rd is never called - m := Or(BeNil(), And(), Equal(1)) - Expect(m.Match("hi")).To(BeTrue()) - Expect(m.(*OrMatcher).MatchMayChangeInTheFuture("hi")).To(BeFalse()) - }) - It("true if successful matcher indicates it might change", func() { - // 3 matchers: 1st returns false, 2nd returns true and "might" change, 3rd is never called - m := Or(Not(BeNil()), Equal("hi"), Equal(1)) - Expect(m.Match("hi")).To(BeTrue()) - Expect(m.(*OrMatcher).MatchMayChangeInTheFuture("hi")).To(BeTrue()) // Equal("hi") indicates it might change - }) - }) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/panic_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/panic_matcher_test.go deleted file mode 100644 index 6b859a7e82..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/panic_matcher_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package matchers_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("Panic", func() { - Context("when passed something that's not a function that takes zero arguments and returns nothing", func() { - It("should error", func() { - success, err := (&PanicMatcher{}).Match("foo") - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&PanicMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&PanicMatcher{}).Match(func(foo string) {}) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&PanicMatcher{}).Match(func() string { return "bar" }) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when passed a function of the correct type", func() { - It("should call the function and pass if the function panics", func() { - Ω(func() { panic("ack!") }).Should(Panic()) - Ω(func() {}).ShouldNot(Panic()) - }) - }) - - Context("when assertion fails", func() { - It("should print the object passed to Panic", func() { - failuresMessages := InterceptGomegaFailures(func() { - Ω(func() { panic("ack!") }).ShouldNot(Panic()) - }) - Ω(failuresMessages).Should(ConsistOf(MatchRegexp("not to panic, but panicked with\\s*: ack!"))) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/receive_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/receive_matcher_test.go deleted file mode 100644 index 938c078e6f..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/receive_matcher_test.go +++ /dev/null @@ -1,280 +0,0 @@ -package matchers_test - -import ( - "time" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -type kungFuActor interface { - DrunkenMaster() bool -} - -type jackie struct { - name string -} - -func (j *jackie) DrunkenMaster() bool { - return true -} - -var _ = Describe("ReceiveMatcher", func() { - Context("with no argument", func() { - Context("for a buffered channel", func() { - It("should succeed", func() { - channel := make(chan bool, 1) - - Ω(channel).ShouldNot(Receive()) - - channel <- true - - Ω(channel).Should(Receive()) - }) - }) - - Context("for an unbuffered channel", func() { - It("should succeed (eventually)", func() { - channel := make(chan bool) - - Ω(channel).ShouldNot(Receive()) - - go func() { - time.Sleep(10 * time.Millisecond) - channel <- true - }() - - Eventually(channel).Should(Receive()) - }) - }) - }) - - Context("with a pointer argument", func() { - Context("of the correct type", func() { - It("should write the value received on the channel to the pointer", func() { - channel := make(chan int, 1) - - var value int - - Ω(channel).ShouldNot(Receive(&value)) - Ω(value).Should(BeZero()) - - channel <- 17 - - Ω(channel).Should(Receive(&value)) - Ω(value).Should(Equal(17)) - }) - }) - - Context("to various types of objects", func() { - It("should work", func() { - //channels of strings - stringChan := make(chan string, 1) - stringChan <- "foo" - - var s string - Ω(stringChan).Should(Receive(&s)) - Ω(s).Should(Equal("foo")) - - //channels of slices - sliceChan := make(chan []bool, 1) - sliceChan <- []bool{true, true, false} - - var sl []bool - Ω(sliceChan).Should(Receive(&sl)) - Ω(sl).Should(Equal([]bool{true, true, false})) - - //channels of channels - chanChan := make(chan chan bool, 1) - c := make(chan bool) - chanChan <- c - - var receivedC chan bool - Ω(chanChan).Should(Receive(&receivedC)) - Ω(receivedC).Should(Equal(c)) - - //channels of interfaces - jackieChan := make(chan kungFuActor, 1) - aJackie := &jackie{name: "Jackie Chan"} - jackieChan <- aJackie - - var theJackie kungFuActor - Ω(jackieChan).Should(Receive(&theJackie)) - Ω(theJackie).Should(Equal(aJackie)) - }) - }) - - Context("of the wrong type", func() { - It("should error", func() { - channel := make(chan int) - var incorrectType bool - - success, err := (&ReceiveMatcher{Arg: &incorrectType}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - var notAPointer int - success, err = (&ReceiveMatcher{Arg: notAPointer}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - }) - - Context("with a matcher", func() { - It("should defer to the underlying matcher", func() { - intChannel := make(chan int, 1) - intChannel <- 3 - Ω(intChannel).Should(Receive(Equal(3))) - - intChannel <- 2 - Ω(intChannel).ShouldNot(Receive(Equal(3))) - - stringChannel := make(chan []string, 1) - stringChannel <- []string{"foo", "bar", "baz"} - Ω(stringChannel).Should(Receive(ContainElement(ContainSubstring("fo")))) - - stringChannel <- []string{"foo", "bar", "baz"} - Ω(stringChannel).ShouldNot(Receive(ContainElement(ContainSubstring("archipelago")))) - }) - - It("should defer to the underlying matcher for the message", func() { - matcher := Receive(Equal(3)) - channel := make(chan int, 1) - channel <- 2 - matcher.Match(channel) - Ω(matcher.FailureMessage(channel)).Should(MatchRegexp(`Expected\s+: 2\s+to equal\s+: 3`)) - - channel <- 3 - matcher.Match(channel) - Ω(matcher.NegatedFailureMessage(channel)).Should(MatchRegexp(`Expected\s+: 3\s+not to equal\s+: 3`)) - }) - - It("should work just fine with Eventually", func() { - stringChannel := make(chan string) - - go func() { - time.Sleep(5 * time.Millisecond) - stringChannel <- "A" - time.Sleep(5 * time.Millisecond) - stringChannel <- "B" - }() - - Eventually(stringChannel).Should(Receive(Equal("B"))) - }) - - Context("if the matcher errors", func() { - It("should error", func() { - channel := make(chan int, 1) - channel <- 3 - success, err := (&ReceiveMatcher{Arg: ContainSubstring("three")}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("if nothing is received", func() { - It("should fail", func() { - channel := make(chan int, 1) - success, err := (&ReceiveMatcher{Arg: Equal(1)}).Match(channel) - Ω(success).Should(BeFalse()) - Ω(err).ShouldNot(HaveOccurred()) - }) - }) - }) - - Context("When actual is a *closed* channel", func() { - Context("for a buffered channel", func() { - It("should work until it hits the end of the buffer", func() { - channel := make(chan bool, 1) - channel <- true - - close(channel) - - Ω(channel).Should(Receive()) - Ω(channel).ShouldNot(Receive()) - }) - }) - - Context("for an unbuffered channel", func() { - It("should always fail", func() { - channel := make(chan bool) - close(channel) - - Ω(channel).ShouldNot(Receive()) - }) - }) - }) - - Context("When actual is a send-only channel", func() { - It("should error", func() { - channel := make(chan bool) - - var writerChannel chan<- bool - writerChannel = channel - - success, err := (&ReceiveMatcher{}).Match(writerChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Context("when acutal is a non-channel", func() { - It("should error", func() { - var nilChannel chan bool - - success, err := (&ReceiveMatcher{}).Match(nilChannel) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ReceiveMatcher{}).Match(nil) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - - success, err = (&ReceiveMatcher{}).Match(3) - Ω(success).Should(BeFalse()) - Ω(err).Should(HaveOccurred()) - }) - }) - - Describe("when used with eventually and a custom matcher", func() { - It("should return the matcher's error when a failing value is received on the channel, instead of the must receive something failure", func() { - failures := InterceptGomegaFailures(func() { - c := make(chan string, 0) - Eventually(c, 0.01).Should(Receive(Equal("hello"))) - }) - Ω(failures[0]).Should(ContainSubstring("When passed a matcher, ReceiveMatcher's channel *must* receive something.")) - - failures = InterceptGomegaFailures(func() { - c := make(chan string, 1) - c <- "hi" - Eventually(c, 0.01).Should(Receive(Equal("hello"))) - }) - Ω(failures[0]).Should(ContainSubstring(": hello")) - }) - }) - - Describe("Bailing early", func() { - It("should bail early when passed a closed channel", func() { - c := make(chan bool) - close(c) - - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(c).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - Ω(failures).Should(HaveLen(1)) - }) - - It("should bail early when passed a non-channel", func() { - t := time.Now() - failures := InterceptGomegaFailures(func() { - Eventually(3).Should(Receive()) - }) - Ω(time.Since(t)).Should(BeNumerically("<", 500*time.Millisecond)) - Ω(failures).Should(HaveLen(1)) - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/matchers/succeed_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/succeed_matcher_test.go deleted file mode 100644 index 6b62c8bb26..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/succeed_matcher_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package matchers_test - -import ( - "errors" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -func Erroring() error { - return errors.New("bam") -} - -func NotErroring() error { - return nil -} - -type AnyType struct{} - -func Invalid() *AnyType { - return nil -} - -var _ = Describe("Succeed", func() { - It("should succeed if the function succeeds", func() { - Ω(NotErroring()).Should(Succeed()) - }) - - It("should succeed (in the negated) if the function errored", func() { - Ω(Erroring()).ShouldNot(Succeed()) - }) - - It("should not if passed a non-error", func() { - success, err := (&SucceedMatcher{}).Match(Invalid()) - Ω(success).Should(BeFalse()) - Ω(err).Should(MatchError("Expected an error-type. Got:\n <*matchers_test.AnyType | 0x0>: nil")) - }) - - It("doesn't support non-error type", func() { - success, err := (&SucceedMatcher{}).Match(AnyType{}) - Ω(success).Should(BeFalse()) - Ω(err).Should(MatchError("Expected an error-type. Got:\n : {}")) - }) - - It("doesn't support non-error pointer type", func() { - success, err := (&SucceedMatcher{}).Match(&AnyType{}) - Ω(success).Should(BeFalse()) - Ω(err).Should(MatchError(MatchRegexp(`Expected an error-type. Got:\n <*matchers_test.AnyType | 0x[[:xdigit:]]+>: {}`))) - }) - - It("should not succeed with pointer types that conform to error interface", func() { - err := &CustomErr{"ohai"} - Ω(err).ShouldNot(Succeed()) - }) - - It("should succeed with nil pointers to types that conform to error interface", func() { - var err *CustomErr = nil - Ω(err).Should(Succeed()) - }) - -}) diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go index 119d21ef31..81b3771119 100644 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go +++ b/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go @@ -15,12 +15,12 @@ type BipartiteGraph struct { func NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(interface{}, interface{}) (bool, error)) (*BipartiteGraph, error) { left := NodeOrderedSet{} for i, _ := range leftValues { - left = append(left, Node{i}) + left = append(left, Node{Id: i}) } right := NodeOrderedSet{} for j, _ := range rightValues { - right = append(right, Node{j + len(left)}) + right = append(right, Node{Id: j + len(left)}) } edges := EdgeSet{} @@ -32,7 +32,7 @@ func NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(in } if neighbours { - edges = append(edges, Edge{left[i], right[j]}) + edges = append(edges, Edge{Node1: left[i], Node2: right[j]}) } } } diff --git a/vendor/github.com/onsi/gomega/matchers/with_transform_test.go b/vendor/github.com/onsi/gomega/matchers/with_transform_test.go deleted file mode 100644 index e52bf8e631..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/with_transform_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package matchers_test - -import ( - "errors" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/matchers" -) - -var _ = Describe("WithTransformMatcher", func() { - - var plus1 = func(i int) int { return i + 1 } - - Context("Panic if transform function invalid", func() { - panicsWithTransformer := func(transform interface{}) { - ExpectWithOffset(1, func() { WithTransform(transform, nil) }).To(Panic()) - } - It("nil", func() { - panicsWithTransformer(nil) - }) - Context("Invalid number of args, but correct return value count", func() { - It("zero", func() { - panicsWithTransformer(func() int { return 5 }) - }) - It("two", func() { - panicsWithTransformer(func(i, j int) int { return 5 }) - }) - }) - Context("Invalid number of return values, but correct number of arguments", func() { - It("zero", func() { - panicsWithTransformer(func(i int) {}) - }) - It("two", func() { - panicsWithTransformer(func(i int) (int, int) { return 5, 6 }) - }) - }) - }) - - It("works with positive cases", func() { - Expect(1).To(WithTransform(plus1, Equal(2))) - Expect(1).To(WithTransform(plus1, WithTransform(plus1, Equal(3)))) - Expect(1).To(WithTransform(plus1, And(Equal(2), BeNumerically(">", 1)))) - - // transform expects custom type - type S struct { - A int - B string - } - transformer := func(s S) string { return s.B } - Expect(S{1, "hi"}).To(WithTransform(transformer, Equal("hi"))) - - // transform expects interface - errString := func(e error) string { return e.Error() } - Expect(errors.New("abc")).To(WithTransform(errString, Equal("abc"))) - }) - - It("works with negative cases", func() { - Expect(1).ToNot(WithTransform(plus1, Equal(3))) - Expect(1).ToNot(WithTransform(plus1, WithTransform(plus1, Equal(2)))) - }) - - Context("failure messages", func() { - Context("when match fails", func() { - It("gives a descriptive message", func() { - m := WithTransform(plus1, Equal(3)) - Expect(m.Match(1)).To(BeFalse()) - Expect(m.FailureMessage(1)).To(Equal("Expected\n : 2\nto equal\n : 3")) - }) - }) - - Context("when match succeeds, but expected it to fail", func() { - It("gives a descriptive message", func() { - m := Not(WithTransform(plus1, Equal(3))) - Expect(m.Match(2)).To(BeFalse()) - Expect(m.FailureMessage(2)).To(Equal("Expected\n : 3\nnot to equal\n : 3")) - }) - }) - - Context("actual value is incompatible with transform function's argument type", func() { - It("gracefully fails if transform cannot be performed", func() { - m := WithTransform(plus1, Equal(3)) - result, err := m.Match("hi") // give it a string but transform expects int; doesn't panic - Expect(result).To(BeFalse()) - Expect(err).To(MatchError("Transform function expects 'int' but we have 'string'")) - }) - }) - }) - - Context("MatchMayChangeInTheFuture()", func() { - It("Propagates value from wrapped matcher on the transformed value", func() { - m := WithTransform(plus1, Or()) // empty Or() always returns false, and indicates it cannot change - Expect(m.Match(1)).To(BeFalse()) - Expect(m.(*WithTransformMatcher).MatchMayChangeInTheFuture(1)).To(BeFalse()) // empty Or() indicates cannot change - }) - It("Defaults to true", func() { - m := WithTransform(plus1, Equal(2)) // Equal does not have this method - Expect(m.Match(1)).To(BeTrue()) - Expect(m.(*WithTransformMatcher).MatchMayChangeInTheFuture(1)).To(BeTrue()) // defaults to true - }) - }) -}) diff --git a/vendor/github.com/onsi/gomega/types/types.go b/vendor/github.com/onsi/gomega/types/types.go index a83b40110c..51256ede0f 100644 --- a/vendor/github.com/onsi/gomega/types/types.go +++ b/vendor/github.com/onsi/gomega/types/types.go @@ -9,7 +9,7 @@ type GomegaTestingT interface { //All Gomega matchers must implement the GomegaMatcher interface // -//For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding_your_own_matchers +//For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding-your-own-matchers type GomegaMatcher interface { Match(actual interface{}) (success bool, err error) FailureMessage(actual interface{}) (message string) diff --git a/vendor/github.com/opencontainers/go-digest/algorithm_test.go b/vendor/github.com/opencontainers/go-digest/algorithm_test.go deleted file mode 100644 index d50e8494fa..0000000000 --- a/vendor/github.com/opencontainers/go-digest/algorithm_test.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 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. - -package digest - -import ( - "bytes" - "crypto/rand" - _ "crypto/sha256" - _ "crypto/sha512" - "flag" - "fmt" - "strings" - "testing" -) - -func TestFlagInterface(t *testing.T) { - var ( - alg Algorithm - flagSet flag.FlagSet - ) - - flagSet.Var(&alg, "algorithm", "set the digest algorithm") - for _, testcase := range []struct { - Name string - Args []string - Err error - Expected Algorithm - }{ - { - Name: "Invalid", - Args: []string{"-algorithm", "bean"}, - Err: ErrDigestUnsupported, - }, - { - Name: "Default", - Args: []string{"unrelated"}, - Expected: "sha256", - }, - { - Name: "Other", - Args: []string{"-algorithm", "sha512"}, - Expected: "sha512", - }, - } { - t.Run(testcase.Name, func(t *testing.T) { - alg = Canonical - if err := flagSet.Parse(testcase.Args); err != testcase.Err { - if testcase.Err == nil { - t.Fatal("unexpected error", err) - } - - // check that flag package returns correct error - if !strings.Contains(err.Error(), testcase.Err.Error()) { - t.Fatalf("unexpected error: %v != %v", err, testcase.Err) - } - return - } - - if alg != testcase.Expected { - t.Fatalf("unexpected algorithm: %v != %v", alg, testcase.Expected) - } - }) - } -} - -func TestFroms(t *testing.T) { - p := make([]byte, 1<<20) - rand.Read(p) - - for alg := range algorithms { - h := alg.Hash() - h.Write(p) - expected := Digest(fmt.Sprintf("%s:%x", alg, h.Sum(nil))) - readerDgst, err := alg.FromReader(bytes.NewReader(p)) - if err != nil { - t.Fatalf("error calculating hash from reader: %v", err) - } - - dgsts := []Digest{ - alg.FromBytes(p), - alg.FromString(string(p)), - readerDgst, - } - - if alg == Canonical { - readerDgst, err := FromReader(bytes.NewReader(p)) - if err != nil { - t.Fatalf("error calculating hash from reader: %v", err) - } - - dgsts = append(dgsts, - FromBytes(p), - FromString(string(p)), - readerDgst) - } - for _, dgst := range dgsts { - if dgst != expected { - t.Fatalf("unexpected digest %v != %v", dgst, expected) - } - } - } -} diff --git a/vendor/github.com/opencontainers/go-digest/digest_test.go b/vendor/github.com/opencontainers/go-digest/digest_test.go deleted file mode 100644 index cc3b648a88..0000000000 --- a/vendor/github.com/opencontainers/go-digest/digest_test.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 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. - -package digest - -import ( - "testing" -) - -func TestParseDigest(t *testing.T) { - for _, testcase := range []struct { - input string - err error - algorithm Algorithm - encoded string - }{ - { - input: "sha256:e58fcf7418d4390dec8e8fb69d88c06ec07039d651fedd3aa72af9972e7d046b", - algorithm: "sha256", - encoded: "e58fcf7418d4390dec8e8fb69d88c06ec07039d651fedd3aa72af9972e7d046b", - }, - { - input: "sha384:d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d", - algorithm: "sha384", - encoded: "d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d", - }, - { - // empty hex - input: "sha256:", - err: ErrDigestInvalidFormat, - }, - { - // empty hex - input: ":", - err: ErrDigestInvalidFormat, - }, - { - // just hex - input: "d41d8cd98f00b204e9800998ecf8427e", - err: ErrDigestInvalidFormat, - }, - { - // not hex - input: "sha256:d41d8cd98f00b204e9800m98ecf8427e", - err: ErrDigestInvalidLength, - }, - { - // too short - input: "sha256:abcdef0123456789", - err: ErrDigestInvalidLength, - }, - { - // too short (from different algorithm) - input: "sha512:abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789", - err: ErrDigestInvalidLength, - }, - { - input: "foo:d41d8cd98f00b204e9800998ecf8427e", - err: ErrDigestUnsupported, - }, - { - // repeated separators - input: "sha384__foo+bar:d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d", - err: ErrDigestInvalidFormat, - }, - { - // ensure that we parse, but we don't have support for the algorithm - input: "sha384.foo+bar:d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d", - algorithm: "sha384.foo+bar", - encoded: "d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d", - err: ErrDigestUnsupported, - }, - { - input: "sha384_foo+bar:d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d", - algorithm: "sha384_foo+bar", - encoded: "d3fc7881460b7e22e3d172954463dddd7866d17597e7248453c48b3e9d26d9596bf9c4a9cf8072c9d5bad76e19af801d", - err: ErrDigestUnsupported, - }, - { - input: "sha256+b64:LCa0a2j_xo_5m0U8HTBBNBNCLXBkg7-g-YpeiGJm564", - algorithm: "sha256+b64", - encoded: "LCa0a2j_xo_5m0U8HTBBNBNCLXBkg7-g-YpeiGJm564", - err: ErrDigestUnsupported, - }, - { - input: "sha256:E58FCF7418D4390DEC8E8FB69D88C06EC07039D651FEDD3AA72AF9972E7D046B", - err: ErrDigestInvalidFormat, - }, - } { - digest, err := Parse(testcase.input) - if err != testcase.err { - t.Fatalf("error differed from expected while parsing %q: %v != %v", testcase.input, err, testcase.err) - } - - if testcase.err != nil { - continue - } - - if digest.Algorithm() != testcase.algorithm { - t.Fatalf("incorrect algorithm for parsed digest: %q != %q", digest.Algorithm(), testcase.algorithm) - } - - if digest.Encoded() != testcase.encoded { - t.Fatalf("incorrect hex for parsed digest: %q != %q", digest.Encoded(), testcase.encoded) - } - - // Parse string return value and check equality - newParsed, err := Parse(digest.String()) - - if err != nil { - t.Fatalf("unexpected error parsing input %q: %v", testcase.input, err) - } - - if newParsed != digest { - t.Fatalf("expected equal: %q != %q", newParsed, digest) - } - - newFromHex := NewDigestFromEncoded(newParsed.Algorithm(), newParsed.Encoded()) - if newFromHex != digest { - t.Fatalf("%v != %v", newFromHex, digest) - } - } -} diff --git a/vendor/github.com/opencontainers/go-digest/verifiers_test.go b/vendor/github.com/opencontainers/go-digest/verifiers_test.go deleted file mode 100644 index d67bb1bc65..0000000000 --- a/vendor/github.com/opencontainers/go-digest/verifiers_test.go +++ /dev/null @@ -1,80 +0,0 @@ -// Copyright 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. - -package digest - -import ( - "bytes" - "crypto/rand" - "io" - "reflect" - "testing" -) - -func TestDigestVerifier(t *testing.T) { - p := make([]byte, 1<<20) - rand.Read(p) - digest := FromBytes(p) - - verifier := digest.Verifier() - - io.Copy(verifier, bytes.NewReader(p)) - - if !verifier.Verified() { - t.Fatalf("bytes not verified") - } -} - -// TestVerifierUnsupportedDigest ensures that unsupported digest validation is -// flowing through verifier creation. -func TestVerifierUnsupportedDigest(t *testing.T) { - for _, testcase := range []struct { - Name string - Digest Digest - Expected interface{} // expected panic target - }{ - { - Name: "Empty", - Digest: "", - Expected: "no ':' separator in digest \"\"", - }, - { - Name: "EmptyAlg", - Digest: ":", - Expected: "empty digest algorithm, validate before calling Algorithm.Hash()", - }, - { - Name: "Unsupported", - Digest: Digest("bean:0123456789abcdef"), - Expected: "bean not available (make sure it is imported)", - }, - { - Name: "Garbage", - Digest: Digest("sha256-garbage:pure"), - Expected: "sha256-garbage not available (make sure it is imported)", - }, - } { - t.Run(testcase.Name, func(t *testing.T) { - expected := testcase.Expected - defer func() { - recovered := recover() - if !reflect.DeepEqual(recovered, expected) { - t.Fatalf("unexpected recover: %v != %v", recovered, expected) - } - }() - - _ = testcase.Digest.Verifier() - }) - } -} diff --git a/vendor/github.com/parnurzeal/gorequest/gorequest_test.go b/vendor/github.com/parnurzeal/gorequest/gorequest_test.go deleted file mode 100644 index 2cf5a743b4..0000000000 --- a/vendor/github.com/parnurzeal/gorequest/gorequest_test.go +++ /dev/null @@ -1,1776 +0,0 @@ -package gorequest - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "io/ioutil" - "log" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "strconv" - "strings" - "testing" - "time" - - "mime/multipart" - - "os" - - "github.com/elazarl/goproxy" -) - -type ( - heyYou struct { - Hey string `json:"hey"` - } - testStruct struct { - String string - Int int - Btrue bool - Bfalse bool - Float float64 - StringArray []string - IntArray []int - BoolArray []bool - FloatArray []float64 - } -) - -// Test for changeMapToURLValues -func TestChangeMapToURLValues(t *testing.T) { - - data := map[string]interface{}{ - "s": "a string", - "i": 42, - "bt": true, - "bf": false, - "f": 12.345, - "sa": []string{"s1", "s2"}, - "ia": []int{47, 73}, - "fa": []float64{1.23, 4.56}, - "ba": []bool{true, false}, - } - - urlValues := changeMapToURLValues(data) - - var ( - s string - sd string - ) - - if s := urlValues.Get("s"); s != data["s"] { - t.Errorf("Expected string %v, got %v", data["s"], s) - } - - s = urlValues.Get("i") - sd = strconv.Itoa(data["i"].(int)) - if s != sd { - t.Errorf("Expected int %v, got %v", sd, s) - } - - s = urlValues.Get("bt") - sd = strconv.FormatBool(data["bt"].(bool)) - if s != sd { - t.Errorf("Expected boolean %v, got %v", sd, s) - } - - s = urlValues.Get("bf") - sd = strconv.FormatBool(data["bf"].(bool)) - if s != sd { - t.Errorf("Expected boolean %v, got %v", sd, s) - } - - s = urlValues.Get("f") - sd = strconv.FormatFloat(data["f"].(float64), 'f', -1, 64) - if s != sd { - t.Errorf("Expected float %v, got %v", data["f"], s) - } - - // array cases - // "To access multiple values, use the map directly." - - if size := len(urlValues["sa"]); size != 2 { - t.Fatalf("Expected length %v, got %v", 2, size) - } - if urlValues["sa"][0] != "s1" { - t.Errorf("Expected string %v, got %v", "s1", urlValues["sa"][0]) - } - if urlValues["sa"][1] != "s2" { - t.Errorf("Expected string %v, got %v", "s2", urlValues["sa"][1]) - } - - if size := len(urlValues["ia"]); size != 2 { - t.Fatalf("Expected length %v, got %v", 2, size) - } - if urlValues["ia"][0] != "47" { - t.Errorf("Expected string %v, got %v", "47", urlValues["ia"][0]) - } - if urlValues["ia"][1] != "73" { - t.Errorf("Expected string %v, got %v", "73", urlValues["ia"][1]) - } - - if size := len(urlValues["ba"]); size != 2 { - t.Fatalf("Expected length %v, got %v", 2, size) - } - if urlValues["ba"][0] != "true" { - t.Errorf("Expected string %v, got %v", "true", urlValues["ba"][0]) - } - if urlValues["ba"][1] != "false" { - t.Errorf("Expected string %v, got %v", "false", urlValues["ba"][1]) - } - - if size := len(urlValues["fa"]); size != 2 { - t.Fatalf("Expected length %v, got %v", 2, size) - } - if urlValues["fa"][0] != "1.23" { - t.Errorf("Expected string %v, got %v", "true", urlValues["fa"][0]) - } - if urlValues["fa"][1] != "4.56" { - t.Errorf("Expected string %v, got %v", "false", urlValues["fa"][1]) - } -} - -// Test for Make request -func TestMakeRequest(t *testing.T) { - var err error - var cases = []struct { - m string - s *SuperAgent - }{ - {POST, New().Post("/")}, - {GET, New().Get("/")}, - {HEAD, New().Head("/")}, - {PUT, New().Put("/")}, - {PATCH, New().Patch("/")}, - {DELETE, New().Delete("/")}, - {OPTIONS, New().Options("/")}, - {"TRACE", New().CustomMethod("TRACE", "/")}, // valid HTTP 1.1 method, see W3C RFC 2616 - } - - for _, c := range cases { - _, err = c.s.MakeRequest() - if err != nil { - t.Errorf("Expected nil error for method %q; got %q", c.m, err.Error()) - } - } - - // empty method should fail - _, err = New().CustomMethod("", "/").MakeRequest() - if err == nil { - t.Errorf("Expected non-nil error for empty method; got %q", err.Error()) - } -} - -// testing for Get method -func TestGet(t *testing.T) { - const case1_empty = "/" - const case2_set_header = "/set_header" - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // check method is GET before going to check other features - if r.Method != GET { - t.Errorf("Expected method %q; got %q", GET, r.Method) - } - if r.Header == nil { - t.Error("Expected non-nil request Header") - } - switch r.URL.Path { - default: - t.Errorf("No testing for this case yet : %q", r.URL.Path) - case case1_empty: - t.Logf("case %v ", case1_empty) - case case2_set_header: - t.Logf("case %v ", case2_set_header) - if r.Header.Get("API-Key") != "fookey" { - t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key")) - } - } - })) - - defer ts.Close() - - New().Get(ts.URL + case1_empty). - End() - - New().Get(ts.URL+case2_set_header). - Set("API-Key", "fookey"). - End() -} - -// testing for Get method with retry option -func TestRetryGet(t *testing.T) { - const ( - case1_empty = "/" - case24_after_3_attempt_return_valid = "/retry_3_attempt_then_valid" - retry_count_expected = "3" - ) - - var attempt int - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // check method is GET before going to check other features - if r.Method != GET { - t.Errorf("Expected method %q; got %q", GET, r.Method) - } - - //set return status - - if r.Header == nil { - t.Error("Expected non-nil request Header") - } - switch r.URL.Path { - default: - t.Errorf("No testing for this case yet : %q", r.URL.Path) - case case1_empty: - w.WriteHeader(400) - t.Logf("case %v ", case1_empty) - case case24_after_3_attempt_return_valid: - if attempt == 3 { - w.WriteHeader(200) - } else { - w.WriteHeader(400) - t.Logf("case %v ", case24_after_3_attempt_return_valid) - } - attempt++ - } - - })) - - defer ts.Close() - - resp, _, errs := New().Get(ts.URL+case1_empty). - Retry(3, 1*time.Nanosecond, http.StatusBadRequest). - End() - if errs != nil { - t.Errorf("No testing for this case yet : %q", errs) - } - - retryCountReturn := resp.Header.Get("Retry-Count") - if retryCountReturn != retry_count_expected { - t.Errorf("Expected [%s] retry but was [%s]", retry_count_expected, retryCountReturn) - } - - resp, _, errs = New().Get(ts.URL+case24_after_3_attempt_return_valid). - Retry(4, 1*time.Nanosecond, http.StatusBadRequest). - End() - if errs != nil { - t.Errorf("No testing for this case yet : %q", errs) - } - - retryCountReturn = resp.Header.Get("Retry-Count") - if retryCountReturn != retry_count_expected { - t.Errorf("Expected [%s] retry but was [%s]", retry_count_expected, retryCountReturn) - } -} - -// testing for Options method -func TestOptions(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // check method is OPTIONS before going to check other features - if r.Method != OPTIONS { - t.Errorf("Expected method %q; got %q", OPTIONS, r.Method) - } - t.Log("test Options") - w.Header().Set("Allow", "HEAD, GET") - w.WriteHeader(204) - })) - - defer ts.Close() - - New().Options(ts.URL). - End() -} - -// testing that resp.Body is reusable -func TestResetBody(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Just some text")) - })) - - defer ts.Close() - - resp, _, _ := New().Get(ts.URL).End() - bodyBytes, _ := ioutil.ReadAll(resp.Body) - if string(bodyBytes) != "Just some text" { - t.Error("Expected to be able to reuse the response body") - } -} - -// testing for Param method -func TestParam(t *testing.T) { - paramCode := "123456" - paramFields := "f1;f2;f3" - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Form.Get("code") != paramCode { - t.Errorf("Expected 'code' == %s; got %v", paramCode, r.Form.Get("code")) - } - - if r.Form.Get("fields") != paramFields { - t.Errorf("Expected 'fields' == %s; got %v", paramFields, r.Form.Get("fields")) - } - })) - - defer ts.Close() - - New().Get(ts.URL). - Param("code", paramCode). - Param("fields", paramFields) -} - -// testing for POST method -func TestPost(t *testing.T) { - const case1_empty = "/" - const case2_set_header = "/set_header" - const case3_send_json = "/send_json" - const case4_send_string = "/send_string" - const case5_integration_send_json_string = "/integration_send_json_string" - const case6_set_query = "/set_query" - const case7_integration_send_json_struct = "/integration_send_json_struct" - // Check that the number conversion should be converted as string not float64 - const case8_send_json_with_long_id_number = "/send_json_with_long_id_number" - const case9_send_json_string_with_long_id_number_as_form_result = "/send_json_string_with_long_id_number_as_form_result" - const case10_send_struct_pointer = "/send_struct_pointer" - const case11_send_string_pointer = "/send_string_pointer" - const case12_send_slice_string = "/send_slice_string" - const case13_send_slice_string_pointer = "/send_slice_string_pointer" - const case14_send_int_pointer = "/send_int_pointer" - const case15_send_float_pointer = "/send_float_pointer" - const case16_send_bool_pointer = "/send_bool_pointer" - const case17_send_string_array = "/send_string_array" - const case18_send_string_array_pointer = "/send_string_array_pointer" - const case19_send_struct = "/send_struct" - const case20_send_byte_char = "/send_byte_char" - const case21_send_byte_char_pointer = "/send_byte_char_pointer" - const case22_send_byte_int = "/send_byte_int" - const case22_send_byte_int_pointer = "/send_byte_int_pointer" - const case23_send_duplicate_query_params = "/send_duplicate_query_params" - const case24_send_query_and_request_body = "/send_query_and_request_body" - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // check method is POST before going to check other features - if r.Method != POST { - t.Errorf("Expected method %q; got %q", POST, r.Method) - } - if r.Header == nil { - t.Error("Expected non-nil request Header") - } - switch r.URL.Path { - default: - t.Errorf("No testing for this case yet : %q", r.URL.Path) - case case1_empty: - t.Logf("case %v ", case1_empty) - case case2_set_header: - t.Logf("case %v ", case2_set_header) - if r.Header.Get("API-Key") != "fookey" { - t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key")) - } - case case3_send_json: - t.Logf("case %v ", case3_send_json) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != `{"query1":"test","query2":"test"}` { - t.Error(`Expected Body with {"query1":"test","query2":"test"}`, "| but got", string(body)) - } - case case4_send_string, case11_send_string_pointer: - t.Logf("case %v ", r.URL.Path) - if r.Header.Get("Content-Type") != "application/x-www-form-urlencoded" { - t.Error("Expected Header Content-Type -> application/x-www-form-urlencoded", "| but got", r.Header.Get("Content-Type")) - } - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "query1=test&query2=test" { - t.Error("Expected Body with \"query1=test&query2=test\"", "| but got", string(body)) - } - case case5_integration_send_json_string: - t.Logf("case %v ", case5_integration_send_json_string) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "query1=test&query2=test" { - t.Error("Expected Body with \"query1=test&query2=test\"", "| but got", string(body)) - } - case case6_set_query: - t.Logf("case %v ", case6_set_query) - v := r.URL.Query() - if v["query1"][0] != "test" { - t.Error("Expected query1:test", "| but got", v["query1"][0]) - } - if v["query2"][0] != "test" { - t.Error("Expected query2:test", "| but got", v["query2"][0]) - } - case case7_integration_send_json_struct: - t.Logf("case %v ", case7_integration_send_json_struct) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - comparedBody := []byte(`{"Lower":{"Color":"green","Size":1.7},"Upper":{"Color":"red","Size":0},"a":"a","name":"Cindy"}`) - if !bytes.Equal(body, comparedBody) { - t.Errorf(`Expected correct json but got ` + string(body)) - } - case case8_send_json_with_long_id_number: - t.Logf("case %v ", case8_send_json_with_long_id_number) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != `{"id":123456789,"name":"nemo"}` { - t.Error(`Expected Body with {"id":123456789,"name":"nemo"}`, "| but got", string(body)) - } - case case9_send_json_string_with_long_id_number_as_form_result: - t.Logf("case %v ", case9_send_json_string_with_long_id_number_as_form_result) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != `id=123456789&name=nemo` { - t.Error(`Expected Body with "id=123456789&name=nemo"`, `| but got`, string(body)) - } - case case19_send_struct, case10_send_struct_pointer: - t.Logf("case %v ", r.URL.Path) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - comparedBody := []byte(`{"Bfalse":false,"BoolArray":[true,false],"Btrue":true,"Float":12.345,"FloatArray":[1.23,4.56,7.89],"Int":42,"IntArray":[1,2],"String":"a string","StringArray":["string1","string2"]}`) - if !bytes.Equal(body, comparedBody) { - t.Errorf(`Expected correct json but got ` + string(body)) - } - case case12_send_slice_string, case13_send_slice_string_pointer, case17_send_string_array, case18_send_string_array_pointer: - t.Logf("case %v ", r.URL.Path) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - comparedBody := []byte(`["string1","string2"]`) - if !bytes.Equal(body, comparedBody) { - t.Errorf(`Expected correct json but got ` + string(body)) - } - case case14_send_int_pointer: - t.Logf("case %v ", case14_send_int_pointer) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "42" { - t.Error("Expected Body with \"42\"", "| but got", string(body)) - } - case case15_send_float_pointer: - t.Logf("case %v ", case15_send_float_pointer) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "12.345" { - t.Error("Expected Body with \"12.345\"", "| but got", string(body)) - } - case case16_send_bool_pointer: - t.Logf("case %v ", case16_send_bool_pointer) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "true" { - t.Error("Expected Body with \"true\"", "| but got", string(body)) - } - case case20_send_byte_char, case21_send_byte_char_pointer, case22_send_byte_int, case22_send_byte_int_pointer: - t.Logf("case %v ", r.URL.Path) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "71" { - t.Error("Expected Body with \"71\"", "| but got", string(body)) - } - case case23_send_duplicate_query_params: - t.Logf("case %v ", case23_send_duplicate_query_params) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - sbody := string(body) - if sbody != "param=4¶m=3¶m=2¶m=1" { - t.Error("Expected Body \"param=4¶m=3¶m=2¶m=1\"", "| but got", sbody) - } - values, _ := url.ParseQuery(sbody) - if len(values["param"]) != 4 { - t.Error("Expected Body with 4 params", "| but got", sbody) - } - if values["param"][0] != "4" || values["param"][1] != "3" || values["param"][2] != "2" || values["param"][3] != "1" { - t.Error("Expected Body with 4 params and values", "| but got", sbody) - } - case case24_send_query_and_request_body: - t.Logf("case %v ", case24_send_query_and_request_body) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - sbody := string(body) - if sbody != `{"name":"jkbbwr"}` { - t.Error(`Expected Body "{"name":"jkbbwr"}"`, "| but got", sbody) - } - - v := r.URL.Query() - if v["test"][0] != "true" { - t.Error("Expected test:true", "| but got", v["test"][0]) - } - } - })) - defer ts.Close() - - New().Post(ts.URL + case1_empty). - End() - - New().Post(ts.URL+case2_set_header). - Set("API-Key", "fookey"). - End() - - New().Post(ts.URL + case3_send_json). - Send(`{"query1":"test"}`). - Send(`{"query2":"test"}`). - End() - - New().Post(ts.URL + case4_send_string). - Send("query1=test"). - Send("query2=test"). - End() - - New().Post(ts.URL + case5_integration_send_json_string). - Send("query1=test"). - Send(`{"query2":"test"}`). - End() - - /* TODO: More testing post for application/x-www-form-urlencoded - post.query(json), post.query(string), post.send(json), post.send(string), post.query(both).send(both) - */ - New().Post(ts.URL + case6_set_query). - Query("query1=test"). - Query("query2=test"). - End() - // TODO: - // 1. test 2nd layer nested struct - // 2. test lowercase won't be export to json - // 3. test field tag change to json field name - type Upper struct { - Color string - Size int - note string - } - type Lower struct { - Color string - Size float64 - note string - } - type Style struct { - Upper Upper - Lower Lower - Name string `json:"name"` - } - myStyle := Style{Upper: Upper{Color: "red"}, Name: "Cindy", Lower: Lower{Color: "green", Size: 1.7}} - New().Post(ts.URL + case7_integration_send_json_struct). - Send(`{"a":"a"}`). - Send(myStyle). - End() - - New().Post(ts.URL + case8_send_json_with_long_id_number). - Send(`{"id":123456789, "name":"nemo"}`). - End() - - New().Post(ts.URL + case9_send_json_string_with_long_id_number_as_form_result). - Type("form"). - Send(`{"id":123456789, "name":"nemo"}`). - End() - - payload := testStruct{ - String: "a string", - Int: 42, - Btrue: true, - Bfalse: false, - Float: 12.345, - StringArray: []string{"string1", "string2"}, - IntArray: []int{1, 2}, - BoolArray: []bool{true, false}, - FloatArray: []float64{1.23, 4.56, 7.89}, - } - - New().Post(ts.URL + case10_send_struct_pointer). - Send(&payload). - End() - - New().Post(ts.URL + case19_send_struct). - Send(payload). - End() - - s1 := "query1=test" - s2 := "query2=test" - New().Post(ts.URL + case11_send_string_pointer). - Send(&s1). - Send(&s2). - End() - - New().Post(ts.URL + case12_send_slice_string). - Send([]string{"string1", "string2"}). - End() - - New().Post(ts.URL + case13_send_slice_string_pointer). - Send(&[]string{"string1", "string2"}). - End() - - i := 42 - New().Post(ts.URL + case14_send_int_pointer). - Send(&i). - End() - - f := 12.345 - New().Post(ts.URL + case15_send_float_pointer). - Send(&f). - End() - - b := true - New().Post(ts.URL + case16_send_bool_pointer). - Send(&b). - End() - - var a [2]string - a[0] = "string1" - a[1] = "string2" - New().Post(ts.URL + case17_send_string_array). - Send(a). - End() - - New().Post(ts.URL + case18_send_string_array_pointer). - Send(&a). - End() - - aByte := byte('G') // = 71 dec - New().Post(ts.URL + case20_send_byte_char). - Send(aByte). - End() - - New().Post(ts.URL + case21_send_byte_char_pointer). - Send(&aByte). - End() - - iByte := byte(71) // = 'G' - New().Post(ts.URL + case22_send_byte_int). - Send(iByte). - End() - - New().Post(ts.URL + case22_send_byte_int_pointer). - Send(&iByte). - End() - - New().Post(ts.URL + case23_send_duplicate_query_params). - Send("param=1"). - Send("param=2"). - Send("param=3¶m=4"). - End() - - data24 := struct { - Name string `json:"name"` - }{"jkbbwr"} - New().Post(ts.URL + case24_send_query_and_request_body). - Query("test=true"). - Send(data24). - End() -} - -func checkFile(t *testing.T, fileheader *multipart.FileHeader) { - infile, err := fileheader.Open() - if err != nil { - t.Error(err) - } - defer infile.Close() - b, err := ioutil.ReadAll(infile) - if err != nil { - t.Error(err) - } - if len(b) == 0 { - t.Error("Expected file-content > 0", "| but got", len(b), string(b)) - } -} - -// testing for POST-Request of Type multipart -func TestMultipartRequest(t *testing.T) { - - const case0_send_not_supported_filetype = "/send_not_supported_filetype" - const case1_send_string = "/send_string" - const case2_send_json = "/send_json" - const case3_integration_send_json_string = "/integration_send_json_string" - const case4_set_query = "/set_query" - const case5_send_struct = "/send_struct" - const case6_send_slice_string = "/send_slice_string" - const case6_send_slice_string_with_custom_fieldname = "/send_slice_string_with_custom_fieldname" - const case7_send_array = "/send_array" - const case8_integration_send_json_struct = "/integration_send_json_struct" - const case9_send_duplicate_query_params = "/send_duplicate_query_params" - - const case10_send_file_by_path = "/send_file_by_path" - const case10a_send_file_by_path_with_name = "/send_file_by_path_with_name" - const case10b_send_file_by_path_pointer = "/send_file_by_path_pointer" - const case11_send_file_by_path_without_name = "/send_file_by_path_without_name" - const case12_send_file_by_path_without_name_but_with_fieldname = "/send_file_by_path_without_name_but_with_fieldname" - - const case13_send_file_by_content_without_name = "/send_file_by_content_without_name" - const case13a_send_file_by_content_without_name_pointer = "/send_file_by_content_without_name_pointer" - const case14_send_file_by_content_with_name = "/send_file_by_content_with_name" - - const case15_send_file_by_content_without_name_but_with_fieldname = "/send_file_by_content_without_name_but_with_fieldname" - const case16_send_file_by_content_with_name_and_with_fieldname = "/send_file_by_content_with_name_and_with_fieldname" - - const case17_send_file_multiple_by_path_and_content_without_name = "/send_file_multiple_by_path_and_content_without_name" - const case18_send_file_multiple_by_path_and_content_with_name = "/send_file_multiple_by_path_and_content_with_name" - const case19_integration_send_file_and_data = "/integration_send_file_and_data" - - const case20_send_file_as_osfile = "/send_file_as_osfile" - const case21_send_file_as_osfile_with_name = "/send_file_as_osfile_with_name" - const case22_send_file_as_osfile_with_name_and_with_fieldname = "/send_file_as_osfile_with_name_and_with_fieldname" - - const case23_send_file_with_file_as_fieldname = "/send_file_with_file_as_fieldname" - const case24_send_file_with_name_with_spaces = "/send_file_with_name_with_spaces" - const case25_send_file_with_name_with_spaces_only = "/send_file_with_name_with_spaces_only" - const case26_send_file_with_fieldname_with_spaces = "/send_file_with_fieldname_with_spaces" - const case27_send_file_with_fieldname_with_spaces_only = "/send_file_with_fieldname_with_spaces_only" - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // check method is POST before going to check other features - if r.Method != POST { - t.Errorf("Expected method %q; got %q", POST, r.Method) - } - if !strings.Contains(r.Header.Get("Content-Type"), "multipart/form-data") { - t.Error("Expected Header Content-Type -> multipart/form-data", "| but got", r.Header.Get("Content-Type")) - } - const _24K = (1 << 20) * 24 - err := r.ParseMultipartForm(_24K) - if err != nil { - t.Errorf("Error: %v", err) - } - t.Logf("case %v ", r.URL.Path) - switch r.URL.Path { - default: - t.Errorf("No testing for this case yet : %q", r.URL.Path) - case case0_send_not_supported_filetype: - // will be handled at place - case case1_send_string, case2_send_json, case3_integration_send_json_string: - if len(r.MultipartForm.Value["query1"]) != 1 { - t.Error("Expected length of query1:test == 1", "| but got", len(r.MultipartForm.Value["query1"])) - } - if r.MultipartForm.Value["query1"][0] != "test" { - t.Error("Expected query1:test", "| but got", r.MultipartForm.Value["query1"][0]) - } - if len(r.MultipartForm.Value["query2"]) != 1 { - t.Error("Expected length of query2:test == 1", "| but got", len(r.MultipartForm.Value["query2"])) - } - if r.MultipartForm.Value["query2"][0] != "test" { - t.Error("Expected query2:test", "| but got", r.MultipartForm.Value["query2"][0]) - } - case case4_set_query: - v := r.URL.Query() - if v["query1"][0] != "test" { - t.Error("Expected query1:test", "| but got", v["query1"][0]) - } - if v["query2"][0] != "test" { - t.Error("Expected query2:test", "| but got", v["query2"][0]) - } - if val, ok := r.MultipartForm.Value["query1"]; ok { - t.Error("Expected no value", "| but got", val) - } - if val, ok := r.MultipartForm.Value["query2"]; ok { - t.Error("Expected no value", "| but got", val) - } - case case5_send_struct: - if r.MultipartForm.Value["String"][0] != "a string" { - t.Error("Expected String:'a string'", "| but got", r.MultipartForm.Value["String"][0]) - } - if r.MultipartForm.Value["Int"][0] != "42" { - t.Error("Expected Int:42", "| but got", r.MultipartForm.Value["Int"][0]) - } - if r.MultipartForm.Value["Btrue"][0] != "true" { - t.Error("Expected Btrue:true", "| but got", r.MultipartForm.Value["Btrue"][0]) - } - if r.MultipartForm.Value["Bfalse"][0] != "false" { - t.Error("Expected Btrue:false", "| but got", r.MultipartForm.Value["Bfalse"][0]) - } - if r.MultipartForm.Value["Float"][0] != "12.345" { - t.Error("Expected Float:12.345", "| but got", r.MultipartForm.Value["Float"][0]) - } - if len(r.MultipartForm.Value["StringArray"]) != 2 { - t.Error("Expected length of StringArray:2", "| but got", len(r.MultipartForm.Value["StringArray"])) - } - if r.MultipartForm.Value["StringArray"][0] != "string1" { - t.Error("Expected StringArray:string1", "| but got", r.MultipartForm.Value["StringArray"][0]) - } - if r.MultipartForm.Value["StringArray"][1] != "string2" { - t.Error("Expected StringArray:string2", "| but got", r.MultipartForm.Value["StringArray"][1]) - } - if len(r.MultipartForm.Value["IntArray"]) != 2 { - t.Error("Expected length of IntArray:2", "| but got", len(r.MultipartForm.Value["IntArray"])) - } - if r.MultipartForm.Value["IntArray"][0] != "1" { - t.Error("Expected IntArray:1", "| but got", r.MultipartForm.Value["IntArray"][0]) - } - if r.MultipartForm.Value["IntArray"][1] != "2" { - t.Error("Expected IntArray:2", "| but got", r.MultipartForm.Value["IntArray"][1]) - } - if len(r.MultipartForm.Value["BoolArray"]) != 2 { - t.Error("Expected length of BoolArray:2", "| but got", len(r.MultipartForm.Value["BoolArray"])) - } - if r.MultipartForm.Value["BoolArray"][0] != "true" { - t.Error("Expected BoolArray:true", "| but got", r.MultipartForm.Value["BoolArray"][0]) - } - if r.MultipartForm.Value["BoolArray"][1] != "false" { - t.Error("Expected BoolArray:false", "| but got", r.MultipartForm.Value["BoolArray"][1]) - } - if len(r.MultipartForm.Value["FloatArray"]) != 3 { - t.Error("Expected length of FloatArray:3", "| but got", len(r.MultipartForm.Value["FloatArray"])) - } - if r.MultipartForm.Value["FloatArray"][0] != "1.23" { - t.Error("Expected FloatArray:1.23", "| but got", r.MultipartForm.Value["FloatArray"][0]) - } - if r.MultipartForm.Value["FloatArray"][1] != "4.56" { - t.Error("Expected FloatArray:4.56", "| but got", r.MultipartForm.Value["FloatArray"][1]) - } - if r.MultipartForm.Value["FloatArray"][2] != "7.89" { - t.Error("Expected FloatArray:7.89", "| but got", r.MultipartForm.Value["FloatArray"][2]) - } - case case6_send_slice_string, case7_send_array: - if len(r.MultipartForm.Value["data"]) != 1 { - t.Error("Expected length of data:JSON == 1", "| but got", len(r.MultipartForm.Value["data"])) - } - if r.MultipartForm.Value["data"][0] != `["string1","string2"]` { - t.Error(`Expected 'data' with ["string1","string2"]`, "| but got", r.MultipartForm.Value["data"][0]) - } - case case6_send_slice_string_with_custom_fieldname: - if len(r.MultipartForm.Value["my_custom_data"]) != 1 { - t.Error("Expected length of my_custom_data:JSON == 1", "| but got", len(r.MultipartForm.Value["my_custom_data"])) - } - if r.MultipartForm.Value["my_custom_data"][0] != `["string1","string2"]` { - t.Error(`Expected 'my_custom_data' with ["string1","string2"]`, "| but got", r.MultipartForm.Value["my_custom_data"][0]) - } - case case8_integration_send_json_struct: - if len(r.MultipartForm.Value["query1"]) != 1 { - t.Error("Expected length of query1:test == 1", "| but got", len(r.MultipartForm.Value["query1"])) - } - if r.MultipartForm.Value["query1"][0] != "test" { - t.Error("Expected query1:test", "| but got", r.MultipartForm.Value["query1"][0]) - } - if r.MultipartForm.Value["hey"][0] != "hey" { - t.Error("Expected hey:'hey'", "| but got", r.MultipartForm.Value["Hey"][0]) - } - case case9_send_duplicate_query_params: - if len(r.MultipartForm.Value["param"]) != 4 { - t.Error("Expected length of param:[] == 4", "| but got", len(r.MultipartForm.Value["param"])) - } - if r.MultipartForm.Value["param"][0] != "4" { - t.Error("Expected param:0:4", "| but got", r.MultipartForm.Value["param"][0]) - } - if r.MultipartForm.Value["param"][1] != "3" { - t.Error("Expected param:1:3", "| but got", r.MultipartForm.Value["param"][1]) - } - if r.MultipartForm.Value["param"][2] != "2" { - t.Error("Expected param:2:2", "| but got", r.MultipartForm.Value["param"][2]) - } - if r.MultipartForm.Value["param"][3] != "1" { - t.Error("Expected param:3:1", "| but got", r.MultipartForm.Value["param"][3]) - } - case case10_send_file_by_path, case11_send_file_by_path_without_name, case14_send_file_by_content_with_name, case20_send_file_as_osfile: - if len(r.MultipartForm.File) != 1 { - t.Error("Expected length of files:[] == 1", "| but got", len(r.MultipartForm.File)) - } - if r.MultipartForm.File["file1"][0].Filename != "LICENSE" { - t.Error("Expected Filename:LICENSE", "| but got", r.MultipartForm.File["file1"][0].Filename) - } - if r.MultipartForm.File["file1"][0].Header["Content-Type"][0] != "application/octet-stream" { - t.Error("Expected Header:Content-Type:application/octet-stream", "| but got", r.MultipartForm.File["file1"][0].Header["Content-Type"]) - } - checkFile(t, r.MultipartForm.File["file1"][0]) - case case10a_send_file_by_path_with_name, case10b_send_file_by_path_pointer, case21_send_file_as_osfile_with_name: - if len(r.MultipartForm.File) != 1 { - t.Error("Expected length of files:[] == 1", "| but got", len(r.MultipartForm.File)) - } - if r.MultipartForm.File["file1"][0].Filename != "MY_LICENSE" { - t.Error("Expected Filename:MY_LICENSE", "| but got", r.MultipartForm.File["file1"][0].Filename) - } - case case12_send_file_by_path_without_name_but_with_fieldname: - if len(r.MultipartForm.File) != 1 { - t.Error("Expected length of files:[] == 1", "| but got", len(r.MultipartForm.File)) - } - if _, ok := r.MultipartForm.File["my_fieldname"]; !ok { - keys := reflect.ValueOf(r.MultipartForm.File).MapKeys() - t.Error("Expected Fieldname:my_fieldname", "| but got", keys) - } - if r.MultipartForm.File["my_fieldname"][0].Filename != "LICENSE" { - t.Error("Expected Filename:LICENSE", "| but got", r.MultipartForm.File["my_fieldname"][0].Filename) - } - if r.MultipartForm.File["my_fieldname"][0].Header["Content-Type"][0] != "application/octet-stream" { - t.Error("Expected Header:Content-Type:application/octet-stream", "| but got", r.MultipartForm.File["my_fieldname"][0].Header["Content-Type"]) - } - checkFile(t, r.MultipartForm.File["my_fieldname"][0]) - case case13_send_file_by_content_without_name, case13a_send_file_by_content_without_name_pointer: - if len(r.MultipartForm.File) != 1 { - t.Error("Expected length of files:[] == 1", "| but got", len(r.MultipartForm.File)) - } - if r.MultipartForm.File["file1"][0].Filename != "filename" { - t.Error("Expected Filename:filename", "| but got", r.MultipartForm.File["file1"][0].Filename) - } - if r.MultipartForm.File["file1"][0].Header["Content-Type"][0] != "application/octet-stream" { - t.Error("Expected Header:Content-Type:application/octet-stream", "| but got", r.MultipartForm.File["file1"][0].Header["Content-Type"]) - } - checkFile(t, r.MultipartForm.File["file1"][0]) - case case15_send_file_by_content_without_name_but_with_fieldname: - if len(r.MultipartForm.File) != 1 { - t.Error("Expected length of files:[] == 1", "| but got", len(r.MultipartForm.File)) - } - if _, ok := r.MultipartForm.File["my_fieldname"]; !ok { - keys := reflect.ValueOf(r.MultipartForm.File).MapKeys() - t.Error("Expected Fieldname:my_fieldname", "| but got", keys) - } - if r.MultipartForm.File["my_fieldname"][0].Filename != "filename" { - t.Error("Expected Filename:filename", "| but got", r.MultipartForm.File["my_fieldname"][0].Filename) - } - if r.MultipartForm.File["my_fieldname"][0].Header["Content-Type"][0] != "application/octet-stream" { - t.Error("Expected Header:Content-Type:application/octet-stream", "| but got", r.MultipartForm.File["my_fieldname"][0].Header["Content-Type"]) - } - checkFile(t, r.MultipartForm.File["my_fieldname"][0]) - case case16_send_file_by_content_with_name_and_with_fieldname, case22_send_file_as_osfile_with_name_and_with_fieldname: - if len(r.MultipartForm.File) != 1 { - t.Error("Expected length of files:[] == 1", "| but got", len(r.MultipartForm.File)) - } - if _, ok := r.MultipartForm.File["my_fieldname"]; !ok { - keys := reflect.ValueOf(r.MultipartForm.File).MapKeys() - t.Error("Expected Fieldname:my_fieldname", "| but got", keys) - } - if r.MultipartForm.File["my_fieldname"][0].Filename != "MY_LICENSE" { - t.Error("Expected Filename:MY_LICENSE", "| but got", r.MultipartForm.File["my_fieldname"][0].Filename) - } - if r.MultipartForm.File["my_fieldname"][0].Header["Content-Type"][0] != "application/octet-stream" { - t.Error("Expected Header:Content-Type:application/octet-stream", "| but got", r.MultipartForm.File["my_fieldname"][0].Header["Content-Type"]) - } - checkFile(t, r.MultipartForm.File["my_fieldname"][0]) - case case17_send_file_multiple_by_path_and_content_without_name: - if len(r.MultipartForm.File) != 2 { - t.Error("Expected length of files:[] == 2", "| but got", len(r.MultipartForm.File)) - } - // depends on map iteration order - if r.MultipartForm.File["file1"][0].Filename != "LICENSE" && r.MultipartForm.File["file1"][0].Filename != "filename" { - t.Error("Expected Filename:LICENSE||filename", "| but got", r.MultipartForm.File["file1"][0].Filename) - } - if r.MultipartForm.File["file1"][0].Header["Content-Type"][0] != "application/octet-stream" { - t.Error("Expected Header:Content-Type:application/octet-stream", "| but got", r.MultipartForm.File["file1"][0].Header["Content-Type"]) - } - // depends on map iteration order - if r.MultipartForm.File["file2"][0].Filename != "LICENSE" && r.MultipartForm.File["file2"][0].Filename != "filename" { - t.Error("Expected Filename:LICENSE||filename", "| but got", r.MultipartForm.File["file2"][0].Filename) - } - if r.MultipartForm.File["file2"][0].Header["Content-Type"][0] != "application/octet-stream" { - t.Error("Expected Header:Content-Type:application/octet-stream", "| but got", r.MultipartForm.File["file2"][0].Header["Content-Type"]) - } - checkFile(t, r.MultipartForm.File["file1"][0]) - checkFile(t, r.MultipartForm.File["file2"][0]) - case case18_send_file_multiple_by_path_and_content_with_name: - if len(r.MultipartForm.File) != 2 { - t.Error("Expected length of files:[] == 2", "| but got", len(r.MultipartForm.File)) - } - // depends on map iteration order - if r.MultipartForm.File["file1"][0].Filename != "LICENSE" && r.MultipartForm.File["file1"][0].Filename != "MY_LICENSE" { - t.Error("Expected Filename:LICENSE||MY_LICENSE", "| but got", r.MultipartForm.File["file1"][0].Filename) - } - if r.MultipartForm.File["file1"][0].Header["Content-Type"][0] != "application/octet-stream" { - t.Error("Expected Header:Content-Type:application/octet-stream", "| but got", r.MultipartForm.File["file1"][0].Header["Content-Type"]) - } - // depends on map iteration order - if r.MultipartForm.File["file2"][0].Filename != "LICENSE" && r.MultipartForm.File["file2"][0].Filename != "MY_LICENSE" { - t.Error("Expected Filename:LICENSE||MY_LICENSE", "| but got", r.MultipartForm.File["file2"][0].Filename) - } - if r.MultipartForm.File["file2"][0].Header["Content-Type"][0] != "application/octet-stream" { - t.Error("Expected Header:Content-Type:application/octet-stream", "| but got", r.MultipartForm.File["file2"][0].Header["Content-Type"]) - } - checkFile(t, r.MultipartForm.File["file1"][0]) - checkFile(t, r.MultipartForm.File["file2"][0]) - case case19_integration_send_file_and_data: - if len(r.MultipartForm.File) != 1 { - t.Error("Expected length of files:[] == 1", "| but got", len(r.MultipartForm.File)) - } - if r.MultipartForm.File["file1"][0].Filename != "LICENSE" { - t.Error("Expected Filename:LICENSE", "| but got", r.MultipartForm.File["file1"][0].Filename) - } - if r.MultipartForm.File["file1"][0].Header["Content-Type"][0] != "application/octet-stream" { - t.Error("Expected Header:Content-Type:application/octet-stream", "| but got", r.MultipartForm.File["file1"][0].Header["Content-Type"]) - } - checkFile(t, r.MultipartForm.File["file1"][0]) - if len(r.MultipartForm.Value["query1"]) != 1 { - t.Error("Expected length of query1:test == 1", "| but got", len(r.MultipartForm.Value["query1"])) - } - if r.MultipartForm.Value["query1"][0] != "test" { - t.Error("Expected query1:test", "| but got", r.MultipartForm.Value["query1"][0]) - } - case case23_send_file_with_file_as_fieldname: - if len(r.MultipartForm.File) != 2 { - t.Error("Expected length of files:[] == 2", "| but got", len(r.MultipartForm.File)) - } - if val, ok := r.MultipartForm.File["file1"]; !ok { - t.Error("Expected file with key: file1", "| but got ", val) - } - if val, ok := r.MultipartForm.File["file2"]; !ok { - t.Error("Expected file with key: file2", "| but got ", val) - } - if r.MultipartForm.File["file1"][0].Filename != "b.file" { - t.Error("Expected Filename:b.file", "| but got", r.MultipartForm.File["file1"][0].Filename) - } - if r.MultipartForm.File["file2"][0].Filename != "LICENSE" { - t.Error("Expected Filename:LICENSE", "| but got", r.MultipartForm.File["file2"][0].Filename) - } - checkFile(t, r.MultipartForm.File["file1"][0]) - checkFile(t, r.MultipartForm.File["file2"][0]) - case case24_send_file_with_name_with_spaces, case25_send_file_with_name_with_spaces_only, case27_send_file_with_fieldname_with_spaces_only: - if len(r.MultipartForm.File) != 1 { - t.Error("Expected length of files:[] == 1", "| but got", len(r.MultipartForm.File)) - } - if val, ok := r.MultipartForm.File["file1"]; !ok { - t.Error("Expected file with key: file1", "| but got ", val) - } - if r.MultipartForm.File["file1"][0].Filename != "LICENSE" { - t.Error("Expected Filename:LICENSE", "| but got", r.MultipartForm.File["file1"][0].Filename) - } - checkFile(t, r.MultipartForm.File["file1"][0]) - case case26_send_file_with_fieldname_with_spaces: - if len(r.MultipartForm.File) != 1 { - t.Error("Expected length of files:[] == 1", "| but got", len(r.MultipartForm.File)) - } - if val, ok := r.MultipartForm.File["my_fieldname"]; !ok { - t.Error("Expected file with key: my_fieldname", "| but got ", val) - } - if r.MultipartForm.File["my_fieldname"][0].Filename != "LICENSE" { - t.Error("Expected Filename:LICENSE", "| but got", r.MultipartForm.File["my_fieldname"][0].Filename) - } - checkFile(t, r.MultipartForm.File["my_fieldname"][0]) - } - - })) - defer ts.Close() - - // "the zero case" - t.Logf("case %v ", case0_send_not_supported_filetype) - _, _, errs := New().Post(ts.URL + case0_send_not_supported_filetype). - Type("multipart"). - SendFile(42). - End() - - if len(errs) == 0 { - t.Errorf("Expected error, but got nothing: %v", errs) - } - - New().Post(ts.URL + case1_send_string). - Type("multipart"). - Send("query1=test"). - Send("query2=test"). - End() - - New().Post(ts.URL + case2_send_json). - Type("multipart"). - Send(`{"query1":"test"}`). - Send(`{"query2":"test"}`). - End() - - New().Post(ts.URL + case3_integration_send_json_string). - Type("multipart"). - Send("query1=test"). - Send(`{"query2":"test"}`). - End() - - New().Post(ts.URL + case4_set_query). - Type("multipart"). - Query("query1=test"). - Query("query2=test"). - End() - - New().Post(ts.URL + case5_send_struct). - Type("multipart"). - Send(testStruct{ - String: "a string", - Int: 42, - Btrue: true, - Bfalse: false, - Float: 12.345, - StringArray: []string{"string1", "string2"}, - IntArray: []int{1, 2}, - BoolArray: []bool{true, false}, - FloatArray: []float64{1.23, 4.56, 7.89}, - }). - End() - - New().Post(ts.URL + case6_send_slice_string). - Type("multipart"). - Send([]string{"string1", "string2"}). - End() - - New().Post(ts.URL+case6_send_slice_string_with_custom_fieldname). - Type("multipart"). - Set("json_fieldname", "my_custom_data"). - Send([]string{"string1", "string2"}). - End() - - New().Post(ts.URL + case7_send_array). - Type("multipart"). - Send([2]string{"string1", "string2"}). - End() - - New().Post(ts.URL + case8_integration_send_json_struct). - Type("multipart"). - Send(`{"query1":"test"}`). - Send(heyYou{ - Hey: "hey", - }). - End() - - New().Post(ts.URL + case9_send_duplicate_query_params). - Type("multipart"). - Send("param=1"). - Send("param=2"). - Send("param=3¶m=4"). - End() - - fileByPath := "./LICENSE" - New().Post(ts.URL + case10_send_file_by_path). - Type("multipart"). - SendFile(fileByPath). - End() - - New().Post(ts.URL+case10a_send_file_by_path_with_name). - Type("multipart"). - SendFile(fileByPath, "MY_LICENSE"). - End() - - New().Post(ts.URL+case10b_send_file_by_path_pointer). - Type("multipart"). - SendFile(&fileByPath, "MY_LICENSE"). - End() - - New().Post(ts.URL+case11_send_file_by_path_without_name). - Type("multipart"). - SendFile(fileByPath, ""). - End() - - New().Post(ts.URL+case12_send_file_by_path_without_name_but_with_fieldname). - Type("multipart"). - SendFile(fileByPath, "", "my_fieldname"). - End() - - b, _ := ioutil.ReadFile("./LICENSE") - New().Post(ts.URL + case13_send_file_by_content_without_name). - Type("multipart"). - SendFile(b). - End() - - New().Post(ts.URL + case13a_send_file_by_content_without_name_pointer). - Type("multipart"). - SendFile(&b). - End() - - New().Post(ts.URL+case14_send_file_by_content_with_name). - Type("multipart"). - SendFile(b, "LICENSE"). - End() - - New().Post(ts.URL+case15_send_file_by_content_without_name_but_with_fieldname). - Type("multipart"). - SendFile(b, "", "my_fieldname"). - End() - - New().Post(ts.URL+case16_send_file_by_content_with_name_and_with_fieldname). - Type("multipart"). - SendFile(b, "MY_LICENSE", "my_fieldname"). - End() - - New().Post(ts.URL + case17_send_file_multiple_by_path_and_content_without_name). - Type("multipart"). - SendFile("./LICENSE"). - SendFile(b). - End() - - New().Post(ts.URL+case18_send_file_multiple_by_path_and_content_with_name). - Type("multipart"). - SendFile("./LICENSE"). - SendFile(b, "MY_LICENSE"). - End() - - New().Post(ts.URL + case19_integration_send_file_and_data). - Type("multipart"). - SendFile("./LICENSE"). - Send("query1=test"). - End() - - osFile, _ := os.Open("./LICENSE") - New().Post(ts.URL + case20_send_file_as_osfile). - Type("multipart"). - SendFile(osFile). - End() - - New().Post(ts.URL+case21_send_file_as_osfile_with_name). - Type("multipart"). - SendFile(osFile, "MY_LICENSE"). - End() - - New().Post(ts.URL+case22_send_file_as_osfile_with_name_and_with_fieldname). - Type("multipart"). - SendFile(osFile, "MY_LICENSE", "my_fieldname"). - End() - - New().Post(ts.URL+case23_send_file_with_file_as_fieldname). - Type("multipart"). - SendFile(b, "b.file"). - SendFile(osFile, "", "file"). - End() - - New().Post(ts.URL+case24_send_file_with_name_with_spaces). - Type("multipart"). - SendFile(osFile, " LICENSE "). - End() - - New().Post(ts.URL+case25_send_file_with_name_with_spaces_only). - Type("multipart"). - SendFile(osFile, " "). - End() - - New().Post(ts.URL+case26_send_file_with_fieldname_with_spaces). - Type("multipart"). - SendFile(osFile, "", " my_fieldname "). - End() - - New().Post(ts.URL+case27_send_file_with_fieldname_with_spaces_only). - Type("multipart"). - SendFile(osFile, "", " "). - End() -} - -// testing for Patch method -func TestPatch(t *testing.T) { - const case1_empty = "/" - const case2_set_header = "/set_header" - const case3_send_json = "/send_json" - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // check method is PATCH before going to check other features - if r.Method != PATCH { - t.Errorf("Expected method %q; got %q", PATCH, r.Method) - } - if r.Header == nil { - t.Error("Expected non-nil request Header") - } - switch r.URL.Path { - default: - t.Errorf("No testing for this case yet : %q", r.URL.Path) - case case1_empty: - t.Logf("case %v ", case1_empty) - case case2_set_header: - t.Logf("case %v ", case2_set_header) - if r.Header.Get("API-Key") != "fookey" { - t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key")) - } - case case3_send_json: - t.Logf("case %v ", case3_send_json) - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != `{"query1":"test","query2":"test"}` { - t.Error(`Expected Body with {"query1":"test","query2":"test"}`, "| but got", string(body)) - } - } - })) - - defer ts.Close() - - New().Patch(ts.URL + case1_empty). - End() - - New().Patch(ts.URL+case2_set_header). - Set("API-Key", "fookey"). - End() - - New().Patch(ts.URL + case3_send_json). - Send(`{"query1":"test"}`). - Send(`{"query2":"test"}`). - End() -} - -func checkQuery(t *testing.T, q map[string][]string, key string, want string) { - v, ok := q[key] - if !ok { - t.Error(key, "Not Found") - } else if len(v) < 1 { - t.Error("No values for", key) - } else if v[0] != want { - t.Errorf("Expected %v:%v | but got %v", key, want, v[0]) - } - return -} - -// TODO: more check on url query (all testcases) -func TestQueryFunc(t *testing.T) { - const case1_send_string = "/send_string" - const case2_send_struct = "/send_struct" - const case3_send_string_with_duplicates = "/send_string_with_duplicates" - const case4_send_map = "/send_map" - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != POST { - t.Errorf("Expected method %q; got %q", POST, r.Method) - } - if r.Header == nil { - t.Error("Expected non-nil request Header") - } - v := r.URL.Query() - - switch r.URL.Path { - default: - t.Errorf("No testing for this case yet : %q", r.URL.Path) - case case1_send_string, case2_send_struct: - checkQuery(t, v, "query1", "test1") - checkQuery(t, v, "query2", "test2") - case case3_send_string_with_duplicates: - checkQuery(t, v, "query1", "test1") - checkQuery(t, v, "query2", "test2") - - if len(v["param"]) != 4 { - t.Errorf("Expected Body with 4 params | but got %q", len(v["param"])) - } - if v["param"][0] != "1" || v["param"][1] != "2" || v["param"][2] != "3" || v["param"][3] != "4" { - t.Error("Expected Body with 4 params and values", "| but got", r.URL.RawQuery) - } - case case4_send_map: - checkQuery(t, v, "query1", "test1") - checkQuery(t, v, "query2", "test2") - checkQuery(t, v, "query3", "3.1415926") - checkQuery(t, v, "query4", "true") - } - })) - defer ts.Close() - - New().Post(ts.URL + case1_send_string). - Query("query1=test1"). - Query("query2=test2"). - End() - - qq := struct { - Query1 string - Query2 string - }{ - Query1: "test1", - Query2: "test2", - } - New().Post(ts.URL + case2_send_struct). - Query(qq). - End() - - New().Post(ts.URL + case3_send_string_with_duplicates). - Query("query1=test1"). - Query("query2=test2"). - Query("param=1"). - Query("param=2"). - Query("param=3¶m=4"). - End() - - New().Post(ts.URL + case4_send_map). - Query(map[string]interface{}{ - "query1": "test1", - "query2": "test2", - "query3": 3.1415926, - "query4": true, - }). - End() -} - -// TODO: more tests on redirect -func TestRedirectPolicyFunc(t *testing.T) { - redirectSuccess := false - redirectFuncGetCalled := false - tsRedirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - redirectSuccess = true - })) - defer tsRedirect.Close() - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, tsRedirect.URL, http.StatusMovedPermanently) - })) - defer ts.Close() - - New(). - Get(ts.URL). - RedirectPolicy(func(req Request, via []Request) error { - redirectFuncGetCalled = true - return nil - }).End() - if !redirectSuccess { - t.Error("Expected reaching another redirect url not original one") - } - if !redirectFuncGetCalled { - t.Error("Expected redirect policy func to get called") - } -} - -func TestEndBytes(t *testing.T) { - serverOutput := "hello world" - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(200) - w.Write([]byte(serverOutput)) - })) - defer ts.Close() - - // Callback. - { - resp, bodyBytes, errs := New().Get(ts.URL).EndBytes(func(resp Response, body []byte, errs []error) { - if len(errs) > 0 { - t.Fatalf("Unexpected errors: %s", errs) - } - if resp.StatusCode != 200 { - t.Fatalf("Expected StatusCode=200, actual StatusCode=%v", resp.StatusCode) - } - if string(body) != serverOutput { - t.Errorf("Expected bodyBytes=%s, actual bodyBytes=%s", serverOutput, string(body)) - } - }) - if len(errs) > 0 { - t.Fatalf("Unexpected errors: %s", errs) - } - if resp.StatusCode != 200 { - t.Fatalf("Expected StatusCode=200, actual StatusCode=%v", resp.StatusCode) - } - if string(bodyBytes) != serverOutput { - t.Errorf("Expected bodyBytes=%s, actual bodyBytes=%s", serverOutput, string(bodyBytes)) - } - } - - // No callback. - { - resp, bodyBytes, errs := New().Get(ts.URL).EndBytes() - if len(errs) > 0 { - t.Errorf("Unexpected errors: %s", errs) - } - if resp.StatusCode != 200 { - t.Errorf("Expected StatusCode=200, actual StatusCode=%v", resp.StatusCode) - } - if string(bodyBytes) != serverOutput { - t.Errorf("Expected bodyBytes=%s, actual bodyBytes=%s", serverOutput, string(bodyBytes)) - } - } -} - -func TestEndStruct(t *testing.T) { - var resStruct heyYou - expStruct := heyYou{Hey: "you"} - serverOutput, err := json.Marshal(expStruct) - if err != nil { - t.Errorf("Unexpected errors: %s", err) - } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(200) - w.Write(serverOutput) - })) - defer ts.Close() - - // Callback. - { - resp, bodyBytes, errs := New().Get(ts.URL).EndStruct(func(resp Response, v interface{}, body []byte, errs []error) { - if len(errs) > 0 { - t.Fatalf("Unexpected errors: %s", errs) - } - if resp.StatusCode != 200 { - t.Fatalf("Expected StatusCode=200, actual StatusCode=%v", resp.StatusCode) - } - if !reflect.DeepEqual(expStruct, resStruct) { - resBytes, _ := json.Marshal(resStruct) - t.Errorf("Expected body=%s, actual bodyBytes=%s", serverOutput, string(resBytes)) - } - if !reflect.DeepEqual(body, serverOutput) { - t.Errorf("Expected bodyBytes=%s, actual bodyBytes=%s", serverOutput, string(body)) - } - }) - if len(errs) > 0 { - t.Fatalf("Unexpected errors: %s", errs) - } - if resp.StatusCode != 200 { - t.Fatalf("Expected StatusCode=200, actual StatusCode=%v", resp.StatusCode) - } - if !reflect.DeepEqual(bodyBytes, serverOutput) { - t.Errorf("Expected bodyBytes=%s, actual bodyBytes=%s", serverOutput, string(bodyBytes)) - } - } - - // No callback. - { - resp, bodyBytes, errs := New().Get(ts.URL).EndStruct(&resStruct) - if len(errs) > 0 { - t.Errorf("Unexpected errors: %s", errs) - } - if resp.StatusCode != 200 { - t.Errorf("Expected StatusCode=200, actual StatusCode=%v", resp.StatusCode) - } - if !reflect.DeepEqual(expStruct, resStruct) { - resBytes, _ := json.Marshal(resStruct) - t.Errorf("Expected body=%s, actual bodyBytes=%s", serverOutput, string(resBytes)) - } - if !reflect.DeepEqual(bodyBytes, serverOutput) { - t.Errorf("Expected bodyBytes=%s, actual bodyBytes=%s", serverOutput, string(bodyBytes)) - } - } -} - -func TestProxyFunc(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, "proxy passed") - })) - defer ts.Close() - // start proxy - proxy := goproxy.NewProxyHttpServer() - proxy.OnRequest().DoFunc( - func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) { - return r, nil - }) - ts2 := httptest.NewServer(proxy) - // sending request via Proxy - resp, body, _ := New().Proxy(ts2.URL).Get(ts.URL).End() - if resp.StatusCode != 200 { - t.Error("Expected 200 Status code") - } - if body != "proxy passed" { - t.Error("Expected 'proxy passed' body string") - } -} - -func TestTimeoutFunc(t *testing.T) { - // 1st case, dial timeout - startTime := time.Now() - _, _, errs := New().Timeout(1000 * time.Millisecond).Get("http://www.google.com:81").End() - elapsedTime := time.Since(startTime) - if errs == nil { - t.Error("Expected dial timeout error but get nothing") - } - if elapsedTime < 1000*time.Millisecond || elapsedTime > 1500*time.Millisecond { - t.Errorf("Expected timeout in between 1000 -> 1500 ms | but got %d", elapsedTime) - } - // 2st case, read/write timeout (Can dial to url but want to timeout because too long operation on the server) - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - time.Sleep(1100 * time.Millisecond) // slightly longer than expected - w.WriteHeader(200) - })) - request := New().Timeout(1000 * time.Millisecond) - startTime = time.Now() - _, _, errs = request.Get(ts.URL).End() - elapsedTime = time.Since(startTime) - if errs == nil { - t.Error("Expected dial+read/write timeout | but get nothing") - } - if elapsedTime < 1000*time.Millisecond || elapsedTime > 1500*time.Millisecond { - t.Errorf("Expected timeout in between 1000 -> 1500 ms | but got %d", elapsedTime) - } - // 3rd case, testing reuse of same request - ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - time.Sleep(1100 * time.Millisecond) // slightly longer than expected - w.WriteHeader(200) - })) - startTime = time.Now() - _, _, errs = request.Get(ts.URL).End() - elapsedTime = time.Since(startTime) - if errs == nil { - t.Error("Expected dial+read/write timeout | but get nothing") - } - if elapsedTime < 1000*time.Millisecond || elapsedTime > 1500*time.Millisecond { - t.Errorf("Expected timeout in between 1000 -> 1500 ms | but got %d", elapsedTime) - } - -} - -func TestCookies(t *testing.T) { - request := New().Timeout(60 * time.Second) - _, _, errs := request.Get("https://github.com").End() - if errs != nil { - t.Error("Cookies test request did not complete") - return - } - domain, _ := url.Parse("https://github.com") - if len(request.Client.Jar.Cookies(domain)) == 0 { - t.Error("Expected cookies | but get nothing") - } -} - -func TestGetSetCookie(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != GET { - t.Errorf("Expected method %q; got %q", GET, r.Method) - } - c, err := r.Cookie("API-Cookie-Name") - if err != nil { - t.Error(err) - } - if c == nil { - t.Error("Expected non-nil request Cookie 'API-Cookie-Name'") - } else if c.Value != "api-cookie-value" { - t.Errorf("Expected 'API-Cookie-Name' == %q; got %q", "api-cookie-value", c.Value) - } - })) - defer ts.Close() - - New().Get(ts.URL). - AddCookie(&http.Cookie{Name: "API-Cookie-Name", Value: "api-cookie-value"}). - End() -} - -func TestGetSetCookies(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != GET { - t.Errorf("Expected method %q; got %q", GET, r.Method) - } - c, err := r.Cookie("API-Cookie-Name1") - if err != nil { - t.Error(err) - } - if c == nil { - t.Error("Expected non-nil request Cookie 'API-Cookie-Name1'") - } else if c.Value != "api-cookie-value1" { - t.Errorf("Expected 'API-Cookie-Name1' == %q; got %q", "api-cookie-value1", c.Value) - } - c, err = r.Cookie("API-Cookie-Name2") - if err != nil { - t.Error(err) - } - if c == nil { - t.Error("Expected non-nil request Cookie 'API-Cookie-Name2'") - } else if c.Value != "api-cookie-value2" { - t.Errorf("Expected 'API-Cookie-Name2' == %q; got %q", "api-cookie-value2", c.Value) - } - })) - defer ts.Close() - - New().Get(ts.URL).AddCookies([]*http.Cookie{ - {Name: "API-Cookie-Name1", Value: "api-cookie-value1"}, - {Name: "API-Cookie-Name2", Value: "api-cookie-value2"}, - }).End() -} - -func TestErrorTypeWrongKey(t *testing.T) { - //defer afterTest(t) - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintln(w, "Hello, checkTypeWrongKey") - })) - defer ts.Close() - - _, _, err := New(). - Get(ts.URL). - Type("wrongtype"). - End() - if len(err) != 0 { - if err[0].Error() != "Type func: incorrect type \"wrongtype\"" { - t.Errorf("Wrong error message: " + err[0].Error()) - } - } else { - t.Error("Should have error") - } -} - -func TestBasicAuth(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - auth := strings.SplitN(r.Header["Authorization"][0], " ", 2) - if len(auth) != 2 || auth[0] != "Basic" { - t.Error("bad syntax") - } - payload, _ := base64.StdEncoding.DecodeString(auth[1]) - pair := strings.SplitN(string(payload), ":", 2) - if pair[0] != "myusername" || pair[1] != "mypassword" { - t.Error("Wrong username/password") - } - })) - defer ts.Close() - New().Post(ts.URL). - SetBasicAuth("myusername", "mypassword"). - End() -} - -func TestXml(t *testing.T) { - xml := `ToveJaniReminderDon't forget me this weekend!` - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // check method is PATCH before going to check other features - if r.Method != POST { - t.Errorf("Expected method %q; got %q", POST, r.Method) - } - if r.Header == nil { - t.Error("Expected non-nil request Header") - } - - if r.Header.Get("Content-Type") != "application/xml" { - t.Error("Expected Header Content-Type -> application/xml", "| but got", r.Header.Get("Content-Type")) - } - - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != xml { - t.Error(`Expected XML `, xml, "| but got", string(body)) - } - })) - - defer ts.Close() - - New().Post(ts.URL). - Type("xml"). - Send(xml). - End() - - New().Post(ts.URL). - Set("Content-Type", "application/xml"). - Send(xml). - End() -} - -func TestPlainText(t *testing.T) { - text := `hello world \r\n I am GoRequest` - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // check method is PATCH before going to check other features - if r.Method != POST { - t.Errorf("Expected method %q; got %q", POST, r.Method) - } - if r.Header == nil { - t.Error("Expected non-nil request Header") - } - if r.Header.Get("Content-Type") != "text/plain" { - t.Error("Expected Header Content-Type -> text/plain", "| but got", r.Header.Get("Content-Type")) - } - - defer r.Body.Close() - body, _ := ioutil.ReadAll(r.Body) - if string(body) != text { - t.Error(`Expected text `, text, "| but got", string(body)) - } - })) - - defer ts.Close() - - New().Post(ts.URL). - Type("text"). - Send(text). - End() - - New().Post(ts.URL). - Set("Content-Type", "text/plain"). - Send(text). - End() -} - -func TestAsCurlCommand(t *testing.T) { - var ( - endpoint = "http://github.com/parnurzeal/gorequest" - jsonData = `{"here": "is", "some": {"json": ["data"]}}` - ) - - request := New().Timeout(10*time.Second).Put(endpoint).Set("Content-Type", "application/json").Send(jsonData) - - curlComand, err := request.AsCurlCommand() - if err != nil { - t.Fatal(err) - } - - expected := fmt.Sprintf(`curl -X 'PUT' -d '%v' -H 'Content-Type: application/json' '%v'`, strings.Replace(jsonData, " ", "", -1), endpoint) - if curlComand != expected { - t.Fatalf("\nExpected curlCommand=%v\n but actual result=%v", expected, curlComand) - } -} - -func TestSetDebugByEnvironmentVar(t *testing.T) { - endpoint := "http://github.com/parnurzeal/gorequest" - - var buf bytes.Buffer - logger := log.New(&buf, "[gorequest]", log.LstdFlags) - - os.Setenv("GOREQUEST_DEBUG", "1") - New().SetLogger(logger).Get(endpoint).End() - - if len(buf.String()) == 0 { - t.Fatalf("\nExpected gorequest to log request and response object if GOREQUEST_DEBUG=1") - } - - os.Setenv("GOREQUEST_DEBUG", "") - buf.Reset() - - New().SetLogger(logger).Get(endpoint).End() - - if len(buf.String()) > 0 { - t.Fatalf("\nExpected gorequest not to log request and response object if GOREQUEST_DEBUG is not set.") - } -} diff --git a/vendor/github.com/pborman/uuid/marshal_test.go b/vendor/github.com/pborman/uuid/marshal_test.go deleted file mode 100644 index 4e85b6bab9..0000000000 --- a/vendor/github.com/pborman/uuid/marshal_test.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "bytes" - "encoding/json" - "reflect" - "testing" -) - -var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") -var testArray = testUUID.Array() - -func TestJSON(t *testing.T) { - type S struct { - ID1 UUID - ID2 UUID - } - s1 := S{ID1: testUUID} - data, err := json.Marshal(&s1) - if err != nil { - t.Fatal(err) - } - var s2 S - if err := json.Unmarshal(data, &s2); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(&s1, &s2) { - t.Errorf("got %#v, want %#v", s2, s1) - } -} - -func TestJSONArray(t *testing.T) { - type S struct { - ID1 Array - ID2 Array - } - s1 := S{ID1: testArray} - data, err := json.Marshal(&s1) - if err != nil { - t.Fatal(err) - } - var s2 S - if err := json.Unmarshal(data, &s2); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(&s1, &s2) { - t.Errorf("got %#v, want %#v", s2, s1) - } -} - -func TestMarshal(t *testing.T) { - data, err := testUUID.MarshalBinary() - if err != nil { - t.Fatalf("MarhsalBinary returned unexpected error %v", err) - } - if !bytes.Equal(data, testUUID) { - t.Fatalf("MarhsalBinary returns %x, want %x", data, testUUID) - } - var u UUID - u.UnmarshalBinary(data) - if !Equal(data, u) { - t.Fatalf("UnmarhsalBinary returns %v, want %v", u, testUUID) - } -} - -func TestMarshalArray(t *testing.T) { - data, err := testArray.MarshalBinary() - if err != nil { - t.Fatalf("MarhsalBinary returned unexpected error %v", err) - } - if !bytes.Equal(data, testUUID) { - t.Fatalf("MarhsalBinary returns %x, want %x", data, testUUID) - } - var a Array - a.UnmarshalBinary(data) - if a != testArray { - t.Fatalf("UnmarhsalBinary returns %v, want %v", a, testArray) - } -} - -func TestMarshalTextArray(t *testing.T) { - data, err := testArray.MarshalText() - if err != nil { - t.Fatalf("MarhsalText returned unexpected error %v", err) - } - var a Array - a.UnmarshalText(data) - if a != testArray { - t.Fatalf("UnmarhsalText returns %v, want %v", a, testArray) - } -} - -func BenchmarkUUID_MarshalJSON(b *testing.B) { - x := &struct { - UUID UUID `json:"uuid"` - }{} - x.UUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") - if x.UUID == nil { - b.Fatal("invalid uuid") - } - for i := 0; i < b.N; i++ { - js, err := json.Marshal(x) - if err != nil { - b.Fatalf("marshal json: %#v (%v)", js, err) - } - } -} - -func BenchmarkUUID_UnmarshalJSON(b *testing.B) { - js := []byte(`{"uuid":"f47ac10b-58cc-0372-8567-0e02b2c3d479"}`) - var x *struct { - UUID UUID `json:"uuid"` - } - for i := 0; i < b.N; i++ { - err := json.Unmarshal(js, &x) - if err != nil { - b.Fatalf("marshal json: %#v (%v)", js, err) - } - } -} diff --git a/vendor/github.com/pborman/uuid/seq_test.go b/vendor/github.com/pborman/uuid/seq_test.go deleted file mode 100644 index 3b3d1430d5..0000000000 --- a/vendor/github.com/pborman/uuid/seq_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "flag" - "runtime" - "testing" - "time" -) - -// This test is only run when --regressions is passed on the go test line. -var regressions = flag.Bool("regressions", false, "run uuid regression tests") - -// TestClockSeqRace tests for a particular race condition of returning two -// identical Version1 UUIDs. The duration of 1 minute was chosen as the race -// condition, before being fixed, nearly always occured in under 30 seconds. -func TestClockSeqRace(t *testing.T) { - if !*regressions { - t.Skip("skipping regression tests") - } - duration := time.Minute - - done := make(chan struct{}) - defer close(done) - - ch := make(chan UUID, 10000) - ncpu := runtime.NumCPU() - switch ncpu { - case 0, 1: - // We can't run the test effectively. - t.Skip("skipping race test, only one CPU detected") - return - default: - runtime.GOMAXPROCS(ncpu) - } - for i := 0; i < ncpu; i++ { - go func() { - for { - select { - case <-done: - return - case ch <- NewUUID(): - } - } - }() - } - - uuids := make(map[string]bool) - cnt := 0 - start := time.Now() - for u := range ch { - s := u.String() - if uuids[s] { - t.Errorf("duplicate uuid after %d in %v: %s", cnt, time.Since(start), s) - return - } - uuids[s] = true - if time.Since(start) > duration { - return - } - cnt++ - } -} diff --git a/vendor/github.com/pborman/uuid/sql_test.go b/vendor/github.com/pborman/uuid/sql_test.go deleted file mode 100644 index 1030951569..0000000000 --- a/vendor/github.com/pborman/uuid/sql_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "strings" - "testing" -) - -func TestScan(t *testing.T) { - var stringTest string = "f47ac10b-58cc-0372-8567-0e02b2c3d479" - var byteTest []byte = Parse(stringTest) - var badTypeTest int = 6 - var invalidTest string = "f47ac10b-58cc-0372-8567-0e02b2c3d4" - - // sunny day tests - - var uuid UUID - err := (&uuid).Scan(stringTest) - if err != nil { - t.Fatal(err) - } - - err = (&uuid).Scan([]byte(stringTest)) - if err != nil { - t.Fatal(err) - } - - err = (&uuid).Scan(byteTest) - if err != nil { - t.Fatal(err) - } - - // bad type tests - - err = (&uuid).Scan(badTypeTest) - if err == nil { - t.Error("int correctly parsed and shouldn't have") - } - if !strings.Contains(err.Error(), "unable to scan type") { - t.Error("attempting to parse an int returned an incorrect error message") - } - - // invalid/incomplete uuids - - err = (&uuid).Scan(invalidTest) - if err == nil { - t.Error("invalid uuid was parsed without error") - } - if !strings.Contains(err.Error(), "invalid UUID") { - t.Error("attempting to parse an invalid UUID returned an incorrect error message") - } - - err = (&uuid).Scan(byteTest[:len(byteTest)-2]) - if err == nil { - t.Error("invalid byte uuid was parsed without error") - } - if !strings.Contains(err.Error(), "invalid UUID") { - t.Error("attempting to parse an invalid byte UUID returned an incorrect error message") - } - - // empty tests - - uuid = nil - var emptySlice []byte - err = (&uuid).Scan(emptySlice) - if err != nil { - t.Fatal(err) - } - - if uuid != nil { - t.Error("UUID was not nil after scanning empty byte slice") - } - - uuid = nil - var emptyString string - err = (&uuid).Scan(emptyString) - if err != nil { - t.Fatal(err) - } - - if uuid != nil { - t.Error("UUID was not nil after scanning empty string") - } -} - -func TestValue(t *testing.T) { - stringTest := "f47ac10b-58cc-0372-8567-0e02b2c3d479" - uuid := Parse(stringTest) - val, _ := uuid.Value() - if val != stringTest { - t.Error("Value() did not return expected string") - } -} diff --git a/vendor/github.com/pborman/uuid/uuid_test.go b/vendor/github.com/pborman/uuid/uuid_test.go deleted file mode 100644 index 038723966f..0000000000 --- a/vendor/github.com/pborman/uuid/uuid_test.go +++ /dev/null @@ -1,543 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package uuid - -import ( - "bytes" - "fmt" - "os" - "strings" - "testing" - "time" -) - -type test struct { - in string - version Version - variant Variant - isuuid bool -} - -var tests = []test{ - {"f47ac10b-58cc-0372-8567-0e02b2c3d479", 0, RFC4122, true}, - {"f47ac10b-58cc-1372-8567-0e02b2c3d479", 1, RFC4122, true}, - {"f47ac10b-58cc-2372-8567-0e02b2c3d479", 2, RFC4122, true}, - {"f47ac10b-58cc-3372-8567-0e02b2c3d479", 3, RFC4122, true}, - {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-5372-8567-0e02b2c3d479", 5, RFC4122, true}, - {"f47ac10b-58cc-6372-8567-0e02b2c3d479", 6, RFC4122, true}, - {"f47ac10b-58cc-7372-8567-0e02b2c3d479", 7, RFC4122, true}, - {"f47ac10b-58cc-8372-8567-0e02b2c3d479", 8, RFC4122, true}, - {"f47ac10b-58cc-9372-8567-0e02b2c3d479", 9, RFC4122, true}, - {"f47ac10b-58cc-a372-8567-0e02b2c3d479", 10, RFC4122, true}, - {"f47ac10b-58cc-b372-8567-0e02b2c3d479", 11, RFC4122, true}, - {"f47ac10b-58cc-c372-8567-0e02b2c3d479", 12, RFC4122, true}, - {"f47ac10b-58cc-d372-8567-0e02b2c3d479", 13, RFC4122, true}, - {"f47ac10b-58cc-e372-8567-0e02b2c3d479", 14, RFC4122, true}, - {"f47ac10b-58cc-f372-8567-0e02b2c3d479", 15, RFC4122, true}, - - {"urn:uuid:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, - {"URN:UUID:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-1567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-2567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-3567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-4567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-5567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-6567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-7567-0e02b2c3d479", 4, Reserved, true}, - {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-9567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-a567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-b567-0e02b2c3d479", 4, RFC4122, true}, - {"f47ac10b-58cc-4372-c567-0e02b2c3d479", 4, Microsoft, true}, - {"f47ac10b-58cc-4372-d567-0e02b2c3d479", 4, Microsoft, true}, - {"f47ac10b-58cc-4372-e567-0e02b2c3d479", 4, Future, true}, - {"f47ac10b-58cc-4372-f567-0e02b2c3d479", 4, Future, true}, - - {"f47ac10b158cc-5372-a567-0e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc25372-a567-0e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc-53723a567-0e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc-5372-a56740e02b2c3d479", 0, Invalid, false}, - {"f47ac10b-58cc-5372-a567-0e02-2c3d479", 0, Invalid, false}, - {"g47ac10b-58cc-4372-a567-0e02b2c3d479", 0, Invalid, false}, -} - -var constants = []struct { - c interface{} - name string -}{ - {Person, "Person"}, - {Group, "Group"}, - {Org, "Org"}, - {Invalid, "Invalid"}, - {RFC4122, "RFC4122"}, - {Reserved, "Reserved"}, - {Microsoft, "Microsoft"}, - {Future, "Future"}, - {Domain(17), "Domain17"}, - {Variant(42), "BadVariant42"}, -} - -func testTest(t *testing.T, in string, tt test) { - uuid := Parse(in) - if ok := (uuid != nil); ok != tt.isuuid { - t.Errorf("Parse(%s) got %v expected %v\b", in, ok, tt.isuuid) - } - if uuid == nil { - return - } - - if v := uuid.Variant(); v != tt.variant { - t.Errorf("Variant(%s) got %d expected %d\b", in, v, tt.variant) - } - if v, _ := uuid.Version(); v != tt.version { - t.Errorf("Version(%s) got %d expected %d\b", in, v, tt.version) - } -} - -func TestUUID(t *testing.T) { - for _, tt := range tests { - testTest(t, tt.in, tt) - testTest(t, strings.ToUpper(tt.in), tt) - } -} - -func TestConstants(t *testing.T) { - for x, tt := range constants { - v, ok := tt.c.(fmt.Stringer) - if !ok { - t.Errorf("%x: %v: not a stringer", x, v) - } else if s := v.String(); s != tt.name { - v, _ := tt.c.(int) - t.Errorf("%x: Constant %T:%d gives %q, expected %q", x, tt.c, v, s, tt.name) - } - } -} - -func TestRandomUUID(t *testing.T) { - m := make(map[string]bool) - for x := 1; x < 32; x++ { - uuid := NewRandom() - s := uuid.String() - if m[s] { - t.Errorf("NewRandom returned duplicated UUID %s", s) - } - m[s] = true - if v, _ := uuid.Version(); v != 4 { - t.Errorf("Random UUID of version %s", v) - } - if uuid.Variant() != RFC4122 { - t.Errorf("Random UUID is variant %d", uuid.Variant()) - } - } -} - -func TestNew(t *testing.T) { - m := make(map[string]bool) - for x := 1; x < 32; x++ { - s := New() - if m[s] { - t.Errorf("New returned duplicated UUID %s", s) - } - m[s] = true - uuid := Parse(s) - if uuid == nil { - t.Errorf("New returned %q which does not decode", s) - continue - } - if v, _ := uuid.Version(); v != 4 { - t.Errorf("Random UUID of version %s", v) - } - if uuid.Variant() != RFC4122 { - t.Errorf("Random UUID is variant %d", uuid.Variant()) - } - } -} - -func clockSeq(t *testing.T, uuid UUID) int { - seq, ok := uuid.ClockSequence() - if !ok { - t.Fatalf("%s: invalid clock sequence", uuid) - } - return seq -} - -func TestClockSeq(t *testing.T) { - // Fake time.Now for this test to return a monotonically advancing time; restore it at end. - defer func(orig func() time.Time) { timeNow = orig }(timeNow) - monTime := time.Now() - timeNow = func() time.Time { - monTime = monTime.Add(1 * time.Second) - return monTime - } - - SetClockSequence(-1) - uuid1 := NewUUID() - uuid2 := NewUUID() - - if clockSeq(t, uuid1) != clockSeq(t, uuid2) { - t.Errorf("clock sequence %d != %d", clockSeq(t, uuid1), clockSeq(t, uuid2)) - } - - SetClockSequence(-1) - uuid2 = NewUUID() - - // Just on the very off chance we generated the same sequence - // two times we try again. - if clockSeq(t, uuid1) == clockSeq(t, uuid2) { - SetClockSequence(-1) - uuid2 = NewUUID() - } - if clockSeq(t, uuid1) == clockSeq(t, uuid2) { - t.Errorf("Duplicate clock sequence %d", clockSeq(t, uuid1)) - } - - SetClockSequence(0x1234) - uuid1 = NewUUID() - if seq := clockSeq(t, uuid1); seq != 0x1234 { - t.Errorf("%s: expected seq 0x1234 got 0x%04x", uuid1, seq) - } -} - -func TestCoding(t *testing.T) { - text := "7d444840-9dc0-11d1-b245-5ffdce74fad2" - urn := "urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2" - data := UUID{ - 0x7d, 0x44, 0x48, 0x40, - 0x9d, 0xc0, - 0x11, 0xd1, - 0xb2, 0x45, - 0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2, - } - if v := data.String(); v != text { - t.Errorf("%x: encoded to %s, expected %s", data, v, text) - } - if v := data.URN(); v != urn { - t.Errorf("%x: urn is %s, expected %s", data, v, urn) - } - - uuid := Parse(text) - if !Equal(uuid, data) { - t.Errorf("%s: decoded to %s, expected %s", text, uuid, data) - } -} - -func TestVersion1(t *testing.T) { - uuid1 := NewUUID() - uuid2 := NewUUID() - - if Equal(uuid1, uuid2) { - t.Errorf("%s:duplicate uuid", uuid1) - } - if v, _ := uuid1.Version(); v != 1 { - t.Errorf("%s: version %s expected 1", uuid1, v) - } - if v, _ := uuid2.Version(); v != 1 { - t.Errorf("%s: version %s expected 1", uuid2, v) - } - n1 := uuid1.NodeID() - n2 := uuid2.NodeID() - if !bytes.Equal(n1, n2) { - t.Errorf("Different nodes %x != %x", n1, n2) - } - t1, ok := uuid1.Time() - if !ok { - t.Errorf("%s: invalid time", uuid1) - } - t2, ok := uuid2.Time() - if !ok { - t.Errorf("%s: invalid time", uuid2) - } - q1, ok := uuid1.ClockSequence() - if !ok { - t.Errorf("%s: invalid clock sequence", uuid1) - } - q2, ok := uuid2.ClockSequence() - if !ok { - t.Errorf("%s: invalid clock sequence", uuid2) - } - - switch { - case t1 == t2 && q1 == q2: - t.Error("time stopped") - case t1 > t2 && q1 == q2: - t.Error("time reversed") - case t1 < t2 && q1 != q2: - t.Error("clock sequence chaned unexpectedly") - } -} - -func TestNode(t *testing.T) { - // This test is mostly to make sure we don't leave nodeMu locked. - ifname = "" - if ni := NodeInterface(); ni != "" { - t.Errorf("NodeInterface got %q, want %q", ni, "") - } - if SetNodeInterface("xyzzy") { - t.Error("SetNodeInterface succeeded on a bad interface name") - } - if !SetNodeInterface("") { - t.Error("SetNodeInterface failed") - } - if ni := NodeInterface(); ni == "" { - t.Error("NodeInterface returned an empty string") - } - - ni := NodeID() - if len(ni) != 6 { - t.Errorf("ni got %d bytes, want 6", len(ni)) - } - hasData := false - for _, b := range ni { - if b != 0 { - hasData = true - } - } - if !hasData { - t.Error("nodeid is all zeros") - } - - id := []byte{1, 2, 3, 4, 5, 6, 7, 8} - SetNodeID(id) - ni = NodeID() - if !bytes.Equal(ni, id[:6]) { - t.Errorf("got nodeid %v, want %v", ni, id[:6]) - } - - if ni := NodeInterface(); ni != "user" { - t.Errorf("got inteface %q, want %q", ni, "user") - } -} - -func TestNodeAndTime(t *testing.T) { - // Time is February 5, 1998 12:30:23.136364800 AM GMT - - uuid := Parse("7d444840-9dc0-11d1-b245-5ffdce74fad2") - node := []byte{0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2} - - ts, ok := uuid.Time() - if ok { - c := time.Unix(ts.UnixTime()) - want := time.Date(1998, 2, 5, 0, 30, 23, 136364800, time.UTC) - if !c.Equal(want) { - t.Errorf("Got time %v, want %v", c, want) - } - } else { - t.Errorf("%s: bad time", uuid) - } - if !bytes.Equal(node, uuid.NodeID()) { - t.Errorf("Expected node %v got %v", node, uuid.NodeID()) - } -} - -func TestMD5(t *testing.T) { - uuid := NewMD5(NameSpace_DNS, []byte("python.org")).String() - want := "6fa459ea-ee8a-3ca4-894e-db77e160355e" - if uuid != want { - t.Errorf("MD5: got %q expected %q", uuid, want) - } -} - -func TestSHA1(t *testing.T) { - uuid := NewSHA1(NameSpace_DNS, []byte("python.org")).String() - want := "886313e1-3b8a-5372-9b90-0c9aee199e5d" - if uuid != want { - t.Errorf("SHA1: got %q expected %q", uuid, want) - } -} - -func TestNodeID(t *testing.T) { - nid := []byte{1, 2, 3, 4, 5, 6} - SetNodeInterface("") - s := NodeInterface() - if s == "" || s == "user" { - t.Errorf("NodeInterface %q after SetInteface", s) - } - node1 := NodeID() - if node1 == nil { - t.Error("NodeID nil after SetNodeInterface", s) - } - SetNodeID(nid) - s = NodeInterface() - if s != "user" { - t.Errorf("Expected NodeInterface %q got %q", "user", s) - } - node2 := NodeID() - if node2 == nil { - t.Error("NodeID nil after SetNodeID", s) - } - if bytes.Equal(node1, node2) { - t.Error("NodeID not changed after SetNodeID", s) - } else if !bytes.Equal(nid, node2) { - t.Errorf("NodeID is %x, expected %x", node2, nid) - } -} - -func testDCE(t *testing.T, name string, uuid UUID, domain Domain, id uint32) { - if uuid == nil { - t.Errorf("%s failed", name) - return - } - if v, _ := uuid.Version(); v != 2 { - t.Errorf("%s: %s: expected version 2, got %s", name, uuid, v) - return - } - if v, ok := uuid.Domain(); !ok || v != domain { - if !ok { - t.Errorf("%s: %d: Domain failed", name, uuid) - } else { - t.Errorf("%s: %s: expected domain %d, got %d", name, uuid, domain, v) - } - } - if v, ok := uuid.Id(); !ok || v != id { - if !ok { - t.Errorf("%s: %d: Id failed", name, uuid) - } else { - t.Errorf("%s: %s: expected id %d, got %d", name, uuid, id, v) - } - } -} - -func TestDCE(t *testing.T) { - testDCE(t, "NewDCESecurity", NewDCESecurity(42, 12345678), 42, 12345678) - testDCE(t, "NewDCEPerson", NewDCEPerson(), Person, uint32(os.Getuid())) - testDCE(t, "NewDCEGroup", NewDCEGroup(), Group, uint32(os.Getgid())) -} - -type badRand struct{} - -func (r badRand) Read(buf []byte) (int, error) { - for i, _ := range buf { - buf[i] = byte(i) - } - return len(buf), nil -} - -func TestBadRand(t *testing.T) { - SetRand(badRand{}) - uuid1 := New() - uuid2 := New() - if uuid1 != uuid2 { - t.Errorf("expected duplicates, got %q and %q", uuid1, uuid2) - } - SetRand(nil) - uuid1 = New() - uuid2 = New() - if uuid1 == uuid2 { - t.Errorf("unexpected duplicates, got %q", uuid1) - } -} - -func TestUUID_Array(t *testing.T) { - expect := Array{ - 0xf4, 0x7a, 0xc1, 0x0b, - 0x58, 0xcc, - 0x03, 0x72, - 0x85, 0x67, - 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79, - } - uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") - if uuid == nil { - t.Fatal("invalid uuid") - } - if uuid.Array() != expect { - t.Fatal("invalid array") - } -} - -func TestArray_UUID(t *testing.T) { - array := Array{ - 0xf4, 0x7a, 0xc1, 0x0b, - 0x58, 0xcc, - 0x03, 0x72, - 0x85, 0x67, - 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79, - } - expect := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") - if expect == nil { - t.Fatal("invalid uuid") - } - if !bytes.Equal(array.UUID(), expect) { - t.Fatal("invalid uuid") - } -} - -func BenchmarkParse(b *testing.B) { - for i := 0; i < b.N; i++ { - uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") - if uuid == nil { - b.Fatal("invalid uuid") - } - } -} - -func BenchmarkNew(b *testing.B) { - for i := 0; i < b.N; i++ { - New() - } -} - -func BenchmarkUUID_String(b *testing.B) { - uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") - if uuid == nil { - b.Fatal("invalid uuid") - } - for i := 0; i < b.N; i++ { - if uuid.String() == "" { - b.Fatal("invalid uuid") - } - } -} - -func BenchmarkUUID_URN(b *testing.B) { - uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") - if uuid == nil { - b.Fatal("invalid uuid") - } - for i := 0; i < b.N; i++ { - if uuid.URN() == "" { - b.Fatal("invalid uuid") - } - } -} - -func BenchmarkUUID_Array(b *testing.B) { - expect := Array{ - 0xf4, 0x7a, 0xc1, 0x0b, - 0x58, 0xcc, - 0x03, 0x72, - 0x85, 0x67, - 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79, - } - uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") - if uuid == nil { - b.Fatal("invalid uuid") - } - for i := 0; i < b.N; i++ { - if uuid.Array() != expect { - b.Fatal("invalid array") - } - } -} - -func BenchmarkArray_UUID(b *testing.B) { - array := Array{ - 0xf4, 0x7a, 0xc1, 0x0b, - 0x58, 0xcc, - 0x03, 0x72, - 0x85, 0x67, - 0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79, - } - expect := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") - if expect == nil { - b.Fatal("invalid uuid") - } - for i := 0; i < b.N; i++ { - if !bytes.Equal(array.UUID(), expect) { - b.Fatal("invalid uuid") - } - } -} diff --git a/vendor/github.com/pkg/errors/bench_test.go b/vendor/github.com/pkg/errors/bench_test.go deleted file mode 100644 index 0416a3cbb8..0000000000 --- a/vendor/github.com/pkg/errors/bench_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// +build go1.7 - -package errors - -import ( - "fmt" - "testing" - - stderrors "errors" -) - -func noErrors(at, depth int) error { - if at >= depth { - return stderrors.New("no error") - } - return noErrors(at+1, depth) -} -func yesErrors(at, depth int) error { - if at >= depth { - return New("ye error") - } - return yesErrors(at+1, depth) -} - -func BenchmarkErrors(b *testing.B) { - var toperr error - type run struct { - stack int - std bool - } - runs := []run{ - {10, false}, - {10, true}, - {100, false}, - {100, true}, - {1000, false}, - {1000, true}, - } - for _, r := range runs { - part := "pkg/errors" - if r.std { - part = "errors" - } - name := fmt.Sprintf("%s-stack-%d", part, r.stack) - b.Run(name, func(b *testing.B) { - var err error - f := yesErrors - if r.std { - f = noErrors - } - b.ReportAllocs() - for i := 0; i < b.N; i++ { - err = f(0, r.stack) - } - b.StopTimer() - toperr = err - }) - } -} diff --git a/vendor/github.com/pkg/errors/errors_test.go b/vendor/github.com/pkg/errors/errors_test.go deleted file mode 100644 index 1d8c635586..0000000000 --- a/vendor/github.com/pkg/errors/errors_test.go +++ /dev/null @@ -1,226 +0,0 @@ -package errors - -import ( - "errors" - "fmt" - "io" - "reflect" - "testing" -) - -func TestNew(t *testing.T) { - tests := []struct { - err string - want error - }{ - {"", fmt.Errorf("")}, - {"foo", fmt.Errorf("foo")}, - {"foo", New("foo")}, - {"string with format specifiers: %v", errors.New("string with format specifiers: %v")}, - } - - for _, tt := range tests { - got := New(tt.err) - if got.Error() != tt.want.Error() { - t.Errorf("New.Error(): got: %q, want %q", got, tt.want) - } - } -} - -func TestWrapNil(t *testing.T) { - got := Wrap(nil, "no error") - if got != nil { - t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWrap(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"}, - } - - for _, tt := range tests { - got := Wrap(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) - } - } -} - -type nilError struct{} - -func (nilError) Error() string { return "nil error" } - -func TestCause(t *testing.T) { - x := New("error") - tests := []struct { - err error - want error - }{{ - // nil error is nil - err: nil, - want: nil, - }, { - // explicit nil error is nil - err: (error)(nil), - want: nil, - }, { - // typed nil is nil - err: (*nilError)(nil), - want: (*nilError)(nil), - }, { - // uncaused error is unaffected - err: io.EOF, - want: io.EOF, - }, { - // caused error returns cause - err: Wrap(io.EOF, "ignored"), - want: io.EOF, - }, { - err: x, // return from errors.New - want: x, - }, { - WithMessage(nil, "whoops"), - nil, - }, { - WithMessage(io.EOF, "whoops"), - io.EOF, - }, { - WithStack(nil), - nil, - }, { - WithStack(io.EOF), - io.EOF, - }} - - for i, tt := range tests { - got := Cause(tt.err) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want) - } - } -} - -func TestWrapfNil(t *testing.T) { - got := Wrapf(nil, "no error") - if got != nil { - t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWrapf(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"}, - {Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"}, - } - - for _, tt := range tests { - got := Wrapf(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want) - } - } -} - -func TestErrorf(t *testing.T) { - tests := []struct { - err error - want string - }{ - {Errorf("read error without format specifiers"), "read error without format specifiers"}, - {Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"}, - } - - for _, tt := range tests { - got := tt.err.Error() - if got != tt.want { - t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want) - } - } -} - -func TestWithStackNil(t *testing.T) { - got := WithStack(nil) - if got != nil { - t.Errorf("WithStack(nil): got %#v, expected nil", got) - } -} - -func TestWithStack(t *testing.T) { - tests := []struct { - err error - want string - }{ - {io.EOF, "EOF"}, - {WithStack(io.EOF), "EOF"}, - } - - for _, tt := range tests { - got := WithStack(tt.err).Error() - if got != tt.want { - t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want) - } - } -} - -func TestWithMessageNil(t *testing.T) { - got := WithMessage(nil, "no error") - if got != nil { - t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got) - } -} - -func TestWithMessage(t *testing.T) { - tests := []struct { - err error - message string - want string - }{ - {io.EOF, "read error", "read error: EOF"}, - {WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"}, - } - - for _, tt := range tests { - got := WithMessage(tt.err, tt.message).Error() - if got != tt.want { - t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want) - } - } - -} - -// errors.New, etc values are not expected to be compared by value -// but the change in errors#27 made them incomparable. Assert that -// various kinds of errors have a functional equality operator, even -// if the result of that equality is always false. -func TestErrorEquality(t *testing.T) { - vals := []error{ - nil, - io.EOF, - errors.New("EOF"), - New("EOF"), - Errorf("EOF"), - Wrap(io.EOF, "EOF"), - Wrapf(io.EOF, "EOF%d", 2), - WithMessage(nil, "whoops"), - WithMessage(io.EOF, "whoops"), - WithStack(io.EOF), - WithStack(nil), - } - - for i := range vals { - for j := range vals { - _ = vals[i] == vals[j] // mustn't panic - } - } -} diff --git a/vendor/github.com/pkg/errors/example_test.go b/vendor/github.com/pkg/errors/example_test.go deleted file mode 100644 index c1fc13e384..0000000000 --- a/vendor/github.com/pkg/errors/example_test.go +++ /dev/null @@ -1,205 +0,0 @@ -package errors_test - -import ( - "fmt" - - "github.com/pkg/errors" -) - -func ExampleNew() { - err := errors.New("whoops") - fmt.Println(err) - - // Output: whoops -} - -func ExampleNew_printf() { - err := errors.New("whoops") - fmt.Printf("%+v", err) - - // Example output: - // whoops - // github.com/pkg/errors_test.ExampleNew_printf - // /home/dfc/src/github.com/pkg/errors/example_test.go:17 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 -} - -func ExampleWithMessage() { - cause := errors.New("whoops") - err := errors.WithMessage(cause, "oh noes") - fmt.Println(err) - - // Output: oh noes: whoops -} - -func ExampleWithStack() { - cause := errors.New("whoops") - err := errors.WithStack(cause) - fmt.Println(err) - - // Output: whoops -} - -func ExampleWithStack_printf() { - cause := errors.New("whoops") - err := errors.WithStack(cause) - fmt.Printf("%+v", err) - - // Example Output: - // whoops - // github.com/pkg/errors_test.ExampleWithStack_printf - // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55 - // testing.runExample - // /usr/lib/go/src/testing/example.go:114 - // testing.RunExamples - // /usr/lib/go/src/testing/example.go:38 - // testing.(*M).Run - // /usr/lib/go/src/testing/testing.go:744 - // main.main - // github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /usr/lib/go/src/runtime/proc.go:183 - // runtime.goexit - // /usr/lib/go/src/runtime/asm_amd64.s:2086 - // github.com/pkg/errors_test.ExampleWithStack_printf - // /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56 - // testing.runExample - // /usr/lib/go/src/testing/example.go:114 - // testing.RunExamples - // /usr/lib/go/src/testing/example.go:38 - // testing.(*M).Run - // /usr/lib/go/src/testing/testing.go:744 - // main.main - // github.com/pkg/errors/_test/_testmain.go:106 - // runtime.main - // /usr/lib/go/src/runtime/proc.go:183 - // runtime.goexit - // /usr/lib/go/src/runtime/asm_amd64.s:2086 -} - -func ExampleWrap() { - cause := errors.New("whoops") - err := errors.Wrap(cause, "oh noes") - fmt.Println(err) - - // Output: oh noes: whoops -} - -func fn() error { - e1 := errors.New("error") - e2 := errors.Wrap(e1, "inner") - e3 := errors.Wrap(e2, "middle") - return errors.Wrap(e3, "outer") -} - -func ExampleCause() { - err := fn() - fmt.Println(err) - fmt.Println(errors.Cause(err)) - - // Output: outer: middle: inner: error - // error -} - -func ExampleWrap_extended() { - err := fn() - fmt.Printf("%+v\n", err) - - // Example output: - // error - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:47 - // github.com/pkg/errors_test.ExampleCause_printf - // /home/dfc/src/github.com/pkg/errors/example_test.go:63 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:104 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer -} - -func ExampleWrapf() { - cause := errors.New("whoops") - err := errors.Wrapf(cause, "oh noes #%d", 2) - fmt.Println(err) - - // Output: oh noes #2: whoops -} - -func ExampleErrorf_extended() { - err := errors.Errorf("whoops: %s", "foo") - fmt.Printf("%+v", err) - - // Example output: - // whoops: foo - // github.com/pkg/errors_test.ExampleErrorf - // /home/dfc/src/github.com/pkg/errors/example_test.go:101 - // testing.runExample - // /home/dfc/go/src/testing/example.go:114 - // testing.RunExamples - // /home/dfc/go/src/testing/example.go:38 - // testing.(*M).Run - // /home/dfc/go/src/testing/testing.go:744 - // main.main - // /github.com/pkg/errors/_test/_testmain.go:102 - // runtime.main - // /home/dfc/go/src/runtime/proc.go:183 - // runtime.goexit - // /home/dfc/go/src/runtime/asm_amd64.s:2059 -} - -func Example_stackTrace() { - type stackTracer interface { - StackTrace() errors.StackTrace - } - - err, ok := errors.Cause(fn()).(stackTracer) - if !ok { - panic("oops, err does not implement stackTracer") - } - - st := err.StackTrace() - fmt.Printf("%+v", st[0:2]) // top two frames - - // Example output: - // github.com/pkg/errors_test.fn - // /home/dfc/src/github.com/pkg/errors/example_test.go:47 - // github.com/pkg/errors_test.Example_stackTrace - // /home/dfc/src/github.com/pkg/errors/example_test.go:127 -} - -func ExampleCause_printf() { - err := errors.Wrap(func() error { - return func() error { - return errors.Errorf("hello %s", fmt.Sprintf("world")) - }() - }(), "failed") - - fmt.Printf("%v", err) - - // Output: failed: hello world -} diff --git a/vendor/github.com/pkg/errors/format_test.go b/vendor/github.com/pkg/errors/format_test.go deleted file mode 100644 index 15fd7d89d7..0000000000 --- a/vendor/github.com/pkg/errors/format_test.go +++ /dev/null @@ -1,535 +0,0 @@ -package errors - -import ( - "errors" - "fmt" - "io" - "regexp" - "strings" - "testing" -) - -func TestFormatNew(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - New("error"), - "%s", - "error", - }, { - New("error"), - "%v", - "error", - }, { - New("error"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatNew\n" + - "\t.+/github.com/pkg/errors/format_test.go:26", - }, { - New("error"), - "%q", - `"error"`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatErrorf(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Errorf("%s", "error"), - "%s", - "error", - }, { - Errorf("%s", "error"), - "%v", - "error", - }, { - Errorf("%s", "error"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatErrorf\n" + - "\t.+/github.com/pkg/errors/format_test.go:56", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWrap(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Wrap(New("error"), "error2"), - "%s", - "error2: error", - }, { - Wrap(New("error"), "error2"), - "%v", - "error2: error", - }, { - Wrap(New("error"), "error2"), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:82", - }, { - Wrap(io.EOF, "error"), - "%s", - "error: EOF", - }, { - Wrap(io.EOF, "error"), - "%v", - "error: EOF", - }, { - Wrap(io.EOF, "error"), - "%+v", - "EOF\n" + - "error\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:96", - }, { - Wrap(Wrap(io.EOF, "error1"), "error2"), - "%+v", - "EOF\n" + - "error1\n" + - "github.com/pkg/errors.TestFormatWrap\n" + - "\t.+/github.com/pkg/errors/format_test.go:103\n", - }, { - Wrap(New("error with space"), "context"), - "%q", - `"context: error with space"`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWrapf(t *testing.T) { - tests := []struct { - error - format string - want string - }{{ - Wrapf(io.EOF, "error%d", 2), - "%s", - "error2: EOF", - }, { - Wrapf(io.EOF, "error%d", 2), - "%v", - "error2: EOF", - }, { - Wrapf(io.EOF, "error%d", 2), - "%+v", - "EOF\n" + - "error2\n" + - "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:134", - }, { - Wrapf(New("error"), "error%d", 2), - "%s", - "error2: error", - }, { - Wrapf(New("error"), "error%d", 2), - "%v", - "error2: error", - }, { - Wrapf(New("error"), "error%d", 2), - "%+v", - "error\n" + - "github.com/pkg/errors.TestFormatWrapf\n" + - "\t.+/github.com/pkg/errors/format_test.go:149", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.error, tt.format, tt.want) - } -} - -func TestFormatWithStack(t *testing.T) { - tests := []struct { - error - format string - want []string - }{{ - WithStack(io.EOF), - "%s", - []string{"EOF"}, - }, { - WithStack(io.EOF), - "%v", - []string{"EOF"}, - }, { - WithStack(io.EOF), - "%+v", - []string{"EOF", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:175"}, - }, { - WithStack(New("error")), - "%s", - []string{"error"}, - }, { - WithStack(New("error")), - "%v", - []string{"error"}, - }, { - WithStack(New("error")), - "%+v", - []string{"error", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:189"}, - }, { - WithStack(WithStack(io.EOF)), - "%+v", - []string{"EOF", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:197"}, - }, { - WithStack(WithStack(Wrapf(io.EOF, "message"))), - "%+v", - []string{"EOF", - "message", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:205"}, - }, { - WithStack(Errorf("error%d", 1)), - "%+v", - []string{"error1", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216", - "github.com/pkg/errors.TestFormatWithStack\n" + - "\t.+/github.com/pkg/errors/format_test.go:216"}, - }} - - for i, tt := range tests { - testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) - } -} - -func TestFormatWithMessage(t *testing.T) { - tests := []struct { - error - format string - want []string - }{{ - WithMessage(New("error"), "error2"), - "%s", - []string{"error2: error"}, - }, { - WithMessage(New("error"), "error2"), - "%v", - []string{"error2: error"}, - }, { - WithMessage(New("error"), "error2"), - "%+v", - []string{ - "error", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:244", - "error2"}, - }, { - WithMessage(io.EOF, "addition1"), - "%s", - []string{"addition1: EOF"}, - }, { - WithMessage(io.EOF, "addition1"), - "%v", - []string{"addition1: EOF"}, - }, { - WithMessage(io.EOF, "addition1"), - "%+v", - []string{"EOF", "addition1"}, - }, { - WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), - "%v", - []string{"addition2: addition1: EOF"}, - }, { - WithMessage(WithMessage(io.EOF, "addition1"), "addition2"), - "%+v", - []string{"EOF", "addition1", "addition2"}, - }, { - Wrap(WithMessage(io.EOF, "error1"), "error2"), - "%+v", - []string{"EOF", "error1", "error2", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:272"}, - }, { - WithMessage(Errorf("error%d", 1), "error2"), - "%+v", - []string{"error1", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:278", - "error2"}, - }, { - WithMessage(WithStack(io.EOF), "error"), - "%+v", - []string{ - "EOF", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:285", - "error"}, - }, { - WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"), - "%+v", - []string{ - "EOF", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", - "inside-error", - "github.com/pkg/errors.TestFormatWithMessage\n" + - "\t.+/github.com/pkg/errors/format_test.go:293", - "outside-error"}, - }} - - for i, tt := range tests { - testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true) - } -} - -func TestFormatGeneric(t *testing.T) { - starts := []struct { - err error - want []string - }{ - {New("new-error"), []string{ - "new-error", - "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:315"}, - }, {Errorf("errorf-error"), []string{ - "errorf-error", - "github.com/pkg/errors.TestFormatGeneric\n" + - "\t.+/github.com/pkg/errors/format_test.go:319"}, - }, {errors.New("errors-new-error"), []string{ - "errors-new-error"}, - }, - } - - wrappers := []wrapper{ - { - func(err error) error { return WithMessage(err, "with-message") }, - []string{"with-message"}, - }, { - func(err error) error { return WithStack(err) }, - []string{ - "github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" + - ".+/github.com/pkg/errors/format_test.go:333", - }, - }, { - func(err error) error { return Wrap(err, "wrap-error") }, - []string{ - "wrap-error", - "github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" + - ".+/github.com/pkg/errors/format_test.go:339", - }, - }, { - func(err error) error { return Wrapf(err, "wrapf-error%d", 1) }, - []string{ - "wrapf-error1", - "github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" + - ".+/github.com/pkg/errors/format_test.go:346", - }, - }, - } - - for s := range starts { - err := starts[s].err - want := starts[s].want - testFormatCompleteCompare(t, s, err, "%+v", want, false) - testGenericRecursive(t, err, want, wrappers, 3) - } -} - -func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) { - got := fmt.Sprintf(format, arg) - gotLines := strings.SplitN(got, "\n", -1) - wantLines := strings.SplitN(want, "\n", -1) - - if len(wantLines) > len(gotLines) { - t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want) - return - } - - for i, w := range wantLines { - match, err := regexp.MatchString(w, gotLines[i]) - if err != nil { - t.Fatal(err) - } - if !match { - t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want) - } - } -} - -var stackLineR = regexp.MustCompile(`\.`) - -// parseBlocks parses input into a slice, where: -// - incase entry contains a newline, its a stacktrace -// - incase entry contains no newline, its a solo line. -// -// Detecting stack boundaries only works incase the WithStack-calls are -// to be found on the same line, thats why it is optionally here. -// -// Example use: -// -// for _, e := range blocks { -// if strings.ContainsAny(e, "\n") { -// // Match as stack -// } else { -// // Match as line -// } -// } -// -func parseBlocks(input string, detectStackboundaries bool) ([]string, error) { - var blocks []string - - stack := "" - wasStack := false - lines := map[string]bool{} // already found lines - - for _, l := range strings.Split(input, "\n") { - isStackLine := stackLineR.MatchString(l) - - switch { - case !isStackLine && wasStack: - blocks = append(blocks, stack, l) - stack = "" - lines = map[string]bool{} - case isStackLine: - if wasStack { - // Detecting two stacks after another, possible cause lines match in - // our tests due to WithStack(WithStack(io.EOF)) on same line. - if detectStackboundaries { - if lines[l] { - if len(stack) == 0 { - return nil, errors.New("len of block must not be zero here") - } - - blocks = append(blocks, stack) - stack = l - lines = map[string]bool{l: true} - continue - } - } - - stack = stack + "\n" + l - } else { - stack = l - } - lines[l] = true - case !isStackLine && !wasStack: - blocks = append(blocks, l) - default: - return nil, errors.New("must not happen") - } - - wasStack = isStackLine - } - - // Use up stack - if stack != "" { - blocks = append(blocks, stack) - } - return blocks, nil -} - -func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) { - gotStr := fmt.Sprintf(format, arg) - - got, err := parseBlocks(gotStr, detectStackBoundaries) - if err != nil { - t.Fatal(err) - } - - if len(got) != len(want) { - t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q", - n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr) - } - - for i := range got { - if strings.ContainsAny(want[i], "\n") { - // Match as stack - match, err := regexp.MatchString(want[i], got[i]) - if err != nil { - t.Fatal(err) - } - if !match { - t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n", - n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want)) - } - } else { - // Match as message - if got[i] != want[i] { - t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i]) - } - } - } -} - -type wrapper struct { - wrap func(err error) error - want []string -} - -func prettyBlocks(blocks []string, prefix ...string) string { - var out []string - - for _, b := range blocks { - out = append(out, fmt.Sprintf("%v", b)) - } - - return " " + strings.Join(out, "\n ") -} - -func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) { - if len(beforeWant) == 0 { - panic("beforeWant must not be empty") - } - for _, w := range list { - if len(w.want) == 0 { - panic("want must not be empty") - } - - err := w.wrap(beforeErr) - - // Copy required cause append(beforeWant, ..) modified beforeWant subtly. - beforeCopy := make([]string, len(beforeWant)) - copy(beforeCopy, beforeWant) - - beforeWant := beforeCopy - last := len(beforeWant) - 1 - var want []string - - // Merge two stacks behind each other. - if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") { - want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...) - } else { - want = append(beforeWant, w.want...) - } - - testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false) - if maxDepth > 0 { - testGenericRecursive(t, err, want, list, maxDepth-1) - } - } -} diff --git a/vendor/github.com/pkg/errors/stack_test.go b/vendor/github.com/pkg/errors/stack_test.go deleted file mode 100644 index 510c27a9f9..0000000000 --- a/vendor/github.com/pkg/errors/stack_test.go +++ /dev/null @@ -1,292 +0,0 @@ -package errors - -import ( - "fmt" - "runtime" - "testing" -) - -var initpc, _, _, _ = runtime.Caller(0) - -func TestFrameLine(t *testing.T) { - var tests = []struct { - Frame - want int - }{{ - Frame(initpc), - 9, - }, { - func() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) - }(), - 20, - }, { - func() Frame { - var pc, _, _, _ = runtime.Caller(1) - return Frame(pc) - }(), - 28, - }, { - Frame(0), // invalid PC - 0, - }} - - for _, tt := range tests { - got := tt.Frame.line() - want := tt.want - if want != got { - t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got) - } - } -} - -type X struct{} - -func (x X) val() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) -} - -func (x *X) ptr() Frame { - var pc, _, _, _ = runtime.Caller(0) - return Frame(pc) -} - -func TestFrameFormat(t *testing.T) { - var tests = []struct { - Frame - format string - want string - }{{ - Frame(initpc), - "%s", - "stack_test.go", - }, { - Frame(initpc), - "%+s", - "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go", - }, { - Frame(0), - "%s", - "unknown", - }, { - Frame(0), - "%+s", - "unknown", - }, { - Frame(initpc), - "%d", - "9", - }, { - Frame(0), - "%d", - "0", - }, { - Frame(initpc), - "%n", - "init", - }, { - func() Frame { - var x X - return x.ptr() - }(), - "%n", - `\(\*X\).ptr`, - }, { - func() Frame { - var x X - return x.val() - }(), - "%n", - "X.val", - }, { - Frame(0), - "%n", - "", - }, { - Frame(initpc), - "%v", - "stack_test.go:9", - }, { - Frame(initpc), - "%+v", - "github.com/pkg/errors.init\n" + - "\t.+/github.com/pkg/errors/stack_test.go:9", - }, { - Frame(0), - "%v", - "unknown:0", - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.Frame, tt.format, tt.want) - } -} - -func TestFuncname(t *testing.T) { - tests := []struct { - name, want string - }{ - {"", ""}, - {"runtime.main", "main"}, - {"github.com/pkg/errors.funcname", "funcname"}, - {"funcname", "funcname"}, - {"io.copyBuffer", "copyBuffer"}, - {"main.(*R).Write", "(*R).Write"}, - } - - for _, tt := range tests { - got := funcname(tt.name) - want := tt.want - if got != want { - t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got) - } - } -} - -func TestTrimGOPATH(t *testing.T) { - var tests = []struct { - Frame - want string - }{{ - Frame(initpc), - "github.com/pkg/errors/stack_test.go", - }} - - for i, tt := range tests { - pc := tt.Frame.pc() - fn := runtime.FuncForPC(pc) - file, _ := fn.FileLine(pc) - got := trimGOPATH(fn.Name(), file) - testFormatRegexp(t, i, got, "%s", tt.want) - } -} - -func TestStackTrace(t *testing.T) { - tests := []struct { - err error - want []string - }{{ - New("ooh"), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:172", - }, - }, { - Wrap(New("ooh"), "ahh"), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New - }, - }, { - Cause(Wrap(New("ooh"), "ahh")), []string{ - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New - }, - }, { - func() error { return New("ooh") }(), []string{ - `github.com/pkg/errors.(func·009|TestStackTrace.func1)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller - }, - }, { - Cause(func() error { - return func() error { - return Errorf("hello %s", fmt.Sprintf("world")) - }() - }()), []string{ - `github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf - `github.com/pkg/errors.(func·011|TestStackTrace.func2)` + - "\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller - "github.com/pkg/errors.TestStackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller - }, - }} - for i, tt := range tests { - x, ok := tt.err.(interface { - StackTrace() StackTrace - }) - if !ok { - t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err) - continue - } - st := x.StackTrace() - for j, want := range tt.want { - testFormatRegexp(t, i, st[j], "%+v", want) - } - } -} - -func stackTrace() StackTrace { - const depth = 8 - var pcs [depth]uintptr - n := runtime.Callers(1, pcs[:]) - var st stack = pcs[0:n] - return st.StackTrace() -} - -func TestStackTraceFormat(t *testing.T) { - tests := []struct { - StackTrace - format string - want string - }{{ - nil, - "%s", - `\[\]`, - }, { - nil, - "%v", - `\[\]`, - }, { - nil, - "%+v", - "", - }, { - nil, - "%#v", - `\[\]errors.Frame\(nil\)`, - }, { - make(StackTrace, 0), - "%s", - `\[\]`, - }, { - make(StackTrace, 0), - "%v", - `\[\]`, - }, { - make(StackTrace, 0), - "%+v", - "", - }, { - make(StackTrace, 0), - "%#v", - `\[\]errors.Frame{}`, - }, { - stackTrace()[:2], - "%s", - `\[stack_test.go stack_test.go\]`, - }, { - stackTrace()[:2], - "%v", - `\[stack_test.go:225 stack_test.go:272\]`, - }, { - stackTrace()[:2], - "%+v", - "\n" + - "github.com/pkg/errors.stackTrace\n" + - "\t.+/github.com/pkg/errors/stack_test.go:225\n" + - "github.com/pkg/errors.TestStackTraceFormat\n" + - "\t.+/github.com/pkg/errors/stack_test.go:276", - }, { - stackTrace()[:2], - "%#v", - `\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`, - }} - - for i, tt := range tests { - testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go b/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go deleted file mode 100644 index a3d86698bf..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "sync" - "testing" -) - -func BenchmarkCounterWithLabelValues(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Inc() - } -} - -func BenchmarkCounterWithLabelValuesConcurrent(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - for j := 0; j < b.N/10; j++ { - m.WithLabelValues("eins", "zwei", "drei").Inc() - } - wg.Done() - }() - } - wg.Wait() -} - -func BenchmarkCounterWithMappedLabels(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.With(Labels{"two": "zwei", "one": "eins", "three": "drei"}).Inc() - } -} - -func BenchmarkCounterWithPreparedMappedLabels(b *testing.B) { - m := NewCounterVec( - CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - labels := Labels{"two": "zwei", "one": "eins", "three": "drei"} - for i := 0; i < b.N; i++ { - m.With(labels).Inc() - } -} - -func BenchmarkCounterNoLabels(b *testing.B) { - m := NewCounter(CounterOpts{ - Name: "benchmark_counter", - Help: "A counter to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Inc() - } -} - -func BenchmarkGaugeWithLabelValues(b *testing.B) { - m := NewGaugeVec( - GaugeOpts{ - Name: "benchmark_gauge", - Help: "A gauge to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Set(3.1415) - } -} - -func BenchmarkGaugeNoLabels(b *testing.B) { - m := NewGauge(GaugeOpts{ - Name: "benchmark_gauge", - Help: "A gauge to benchmark it.", - }) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Set(3.1415) - } -} - -func BenchmarkSummaryWithLabelValues(b *testing.B) { - m := NewSummaryVec( - SummaryOpts{ - Name: "benchmark_summary", - Help: "A summary to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) - } -} - -func BenchmarkSummaryNoLabels(b *testing.B) { - m := NewSummary(SummaryOpts{ - Name: "benchmark_summary", - Help: "A summary to benchmark it.", - }, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Observe(3.1415) - } -} - -func BenchmarkHistogramWithLabelValues(b *testing.B) { - m := NewHistogramVec( - HistogramOpts{ - Name: "benchmark_histogram", - Help: "A histogram to benchmark it.", - }, - []string{"one", "two", "three"}, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) - } -} - -func BenchmarkHistogramNoLabels(b *testing.B) { - m := NewHistogram(HistogramOpts{ - Name: "benchmark_histogram", - Help: "A histogram to benchmark it.", - }, - ) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - m.Observe(3.1415) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter_test.go b/vendor/github.com/prometheus/client_golang/prometheus/counter_test.go deleted file mode 100644 index 67391a23aa..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/counter_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "math" - "testing" - - dto "github.com/prometheus/client_model/go" -) - -func TestCounterAdd(t *testing.T) { - counter := NewCounter(CounterOpts{ - Name: "test", - Help: "test help", - ConstLabels: Labels{"a": "1", "b": "2"}, - }).(*counter) - counter.Inc() - if expected, got := 1., math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - counter.Add(42) - if expected, got := 43., math.Float64frombits(counter.valBits); expected != got { - t.Errorf("Expected %f, got %f.", expected, got) - } - - if expected, got := "counter cannot decrease in value", decreaseCounter(counter).Error(); expected != got { - t.Errorf("Expected error %q, got %q.", expected, got) - } - - m := &dto.Metric{} - counter.Write(m) - - if expected, got := `label: label: counter: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} - -func decreaseCounter(c *counter) (err error) { - defer func() { - if e := recover(); e != nil { - err = e.(error) - } - }() - c.Add(-1) - return nil -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go deleted file mode 100644 index 260c1b52de..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus_test - -import "github.com/prometheus/client_golang/prometheus" - -// ClusterManager is an example for a system that might have been built without -// Prometheus in mind. It models a central manager of jobs running in a -// cluster. To turn it into something that collects Prometheus metrics, we -// simply add the two methods required for the Collector interface. -// -// An additional challenge is that multiple instances of the ClusterManager are -// run within the same binary, each in charge of a different zone. We need to -// make use of ConstLabels to be able to register each ClusterManager instance -// with Prometheus. -type ClusterManager struct { - Zone string - OOMCountDesc *prometheus.Desc - RAMUsageDesc *prometheus.Desc - // ... many more fields -} - -// ReallyExpensiveAssessmentOfTheSystemState is a mock for the data gathering a -// real cluster manager would have to do. Since it may actually be really -// expensive, it must only be called once per collection. This implementation, -// obviously, only returns some made-up data. -func (c *ClusterManager) ReallyExpensiveAssessmentOfTheSystemState() ( - oomCountByHost map[string]int, ramUsageByHost map[string]float64, -) { - // Just example fake data. - oomCountByHost = map[string]int{ - "foo.example.org": 42, - "bar.example.org": 2001, - } - ramUsageByHost = map[string]float64{ - "foo.example.org": 6.023e23, - "bar.example.org": 3.14, - } - return -} - -// Describe simply sends the two Descs in the struct to the channel. -func (c *ClusterManager) Describe(ch chan<- *prometheus.Desc) { - ch <- c.OOMCountDesc - ch <- c.RAMUsageDesc -} - -// Collect first triggers the ReallyExpensiveAssessmentOfTheSystemState. Then it -// creates constant metrics for each host on the fly based on the returned data. -// -// Note that Collect could be called concurrently, so we depend on -// ReallyExpensiveAssessmentOfTheSystemState to be concurrency-safe. -func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) { - oomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState() - for host, oomCount := range oomCountByHost { - ch <- prometheus.MustNewConstMetric( - c.OOMCountDesc, - prometheus.CounterValue, - float64(oomCount), - host, - ) - } - for host, ramUsage := range ramUsageByHost { - ch <- prometheus.MustNewConstMetric( - c.RAMUsageDesc, - prometheus.GaugeValue, - ramUsage, - host, - ) - } -} - -// NewClusterManager creates the two Descs OOMCountDesc and RAMUsageDesc. Note -// that the zone is set as a ConstLabel. (It's different in each instance of the -// ClusterManager, but constant over the lifetime of an instance.) Then there is -// a variable label "host", since we want to partition the collected metrics by -// host. Since all Descs created in this way are consistent across instances, -// with a guaranteed distinction by the "zone" label, we can register different -// ClusterManager instances with the same registry. -func NewClusterManager(zone string) *ClusterManager { - return &ClusterManager{ - Zone: zone, - OOMCountDesc: prometheus.NewDesc( - "clustermanager_oom_crashes_total", - "Number of OOM crashes.", - []string{"host"}, - prometheus.Labels{"zone": zone}, - ), - RAMUsageDesc: prometheus.NewDesc( - "clustermanager_ram_usage_bytes", - "RAM usage as reported to the cluster manager.", - []string{"host"}, - prometheus.Labels{"zone": zone}, - ), - } -} - -func ExampleCollector() { - workerDB := NewClusterManager("db") - workerCA := NewClusterManager("ca") - - // Since we are dealing with custom Collector implementations, it might - // be a good idea to try it out with a pedantic registry. - reg := prometheus.NewPedanticRegistry() - reg.MustRegister(workerDB) - reg.MustRegister(workerCA) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go b/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go deleted file mode 100644 index f87f21a8f4..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go +++ /dev/null @@ -1,751 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus_test - -import ( - "bytes" - "fmt" - "math" - "net/http" - "runtime" - "sort" - "strings" - - dto "github.com/prometheus/client_model/go" - "github.com/prometheus/common/expfmt" - - "github.com/golang/protobuf/proto" - - "github.com/prometheus/client_golang/prometheus" -) - -func ExampleGauge() { - opsQueued := prometheus.NewGauge(prometheus.GaugeOpts{ - Namespace: "our_company", - Subsystem: "blob_storage", - Name: "ops_queued", - Help: "Number of blob storage operations waiting to be processed.", - }) - prometheus.MustRegister(opsQueued) - - // 10 operations queued by the goroutine managing incoming requests. - opsQueued.Add(10) - // A worker goroutine has picked up a waiting operation. - opsQueued.Dec() - // And once more... - opsQueued.Dec() -} - -func ExampleGaugeVec() { - opsQueued := prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Namespace: "our_company", - Subsystem: "blob_storage", - Name: "ops_queued", - Help: "Number of blob storage operations waiting to be processed, partitioned by user and type.", - }, - []string{ - // Which user has requested the operation? - "user", - // Of what type is the operation? - "type", - }, - ) - prometheus.MustRegister(opsQueued) - - // Increase a value using compact (but order-sensitive!) WithLabelValues(). - opsQueued.WithLabelValues("bob", "put").Add(4) - // Increase a value with a map using WithLabels. More verbose, but order - // doesn't matter anymore. - opsQueued.With(prometheus.Labels{"type": "delete", "user": "alice"}).Inc() -} - -func ExampleGaugeFunc() { - if err := prometheus.Register(prometheus.NewGaugeFunc( - prometheus.GaugeOpts{ - Subsystem: "runtime", - Name: "goroutines_count", - Help: "Number of goroutines that currently exist.", - }, - func() float64 { return float64(runtime.NumGoroutine()) }, - )); err == nil { - fmt.Println("GaugeFunc 'goroutines_count' registered.") - } - // Note that the count of goroutines is a gauge (and not a counter) as - // it can go up and down. - - // Output: - // GaugeFunc 'goroutines_count' registered. -} - -func ExampleCounter() { - pushCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "repository_pushes", // Note: No help string... - }) - err := prometheus.Register(pushCounter) // ... so this will return an error. - if err != nil { - fmt.Println("Push counter couldn't be registered, no counting will happen:", err) - return - } - - // Try it once more, this time with a help string. - pushCounter = prometheus.NewCounter(prometheus.CounterOpts{ - Name: "repository_pushes", - Help: "Number of pushes to external repository.", - }) - err = prometheus.Register(pushCounter) - if err != nil { - fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err) - return - } - - pushComplete := make(chan struct{}) - // TODO: Start a goroutine that performs repository pushes and reports - // each completion via the channel. - for _ = range pushComplete { - pushCounter.Inc() - } - // Output: - // Push counter couldn't be registered, no counting will happen: descriptor Desc{fqName: "repository_pushes", help: "", constLabels: {}, variableLabels: []} is invalid: empty help string -} - -func ExampleCounterVec() { - httpReqs := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "http_requests_total", - Help: "How many HTTP requests processed, partitioned by status code and HTTP method.", - }, - []string{"code", "method"}, - ) - prometheus.MustRegister(httpReqs) - - httpReqs.WithLabelValues("404", "POST").Add(42) - - // If you have to access the same set of labels very frequently, it - // might be good to retrieve the metric only once and keep a handle to - // it. But beware of deletion of that metric, see below! - m := httpReqs.WithLabelValues("200", "GET") - for i := 0; i < 1000000; i++ { - m.Inc() - } - // Delete a metric from the vector. If you have previously kept a handle - // to that metric (as above), future updates via that handle will go - // unseen (even if you re-create a metric with the same label set - // later). - httpReqs.DeleteLabelValues("200", "GET") - // Same thing with the more verbose Labels syntax. - httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"}) -} - -func ExampleInstrumentHandler() { - // Handle the "/doc" endpoint with the standard http.FileServer handler. - // By wrapping the handler with InstrumentHandler, request count, - // request and response sizes, and request latency are automatically - // exported to Prometheus, partitioned by HTTP status code and method - // and by the handler name (here "fileserver"). - http.Handle("/doc", prometheus.InstrumentHandler( - "fileserver", http.FileServer(http.Dir("/usr/share/doc")), - )) - // The Prometheus handler still has to be registered to handle the - // "/metrics" endpoint. The handler returned by prometheus.Handler() is - // already instrumented - with "prometheus" as the handler name. In this - // example, we want the handler name to be "metrics", so we instrument - // the uninstrumented Prometheus handler ourselves. - http.Handle("/metrics", prometheus.InstrumentHandler( - "metrics", prometheus.UninstrumentedHandler(), - )) -} - -func ExampleLabelPairSorter() { - labelPairs := []*dto.LabelPair{ - &dto.LabelPair{Name: proto.String("status"), Value: proto.String("404")}, - &dto.LabelPair{Name: proto.String("method"), Value: proto.String("get")}, - } - - sort.Sort(prometheus.LabelPairSorter(labelPairs)) - - fmt.Println(labelPairs) - // Output: - // [name:"method" value:"get" name:"status" value:"404" ] -} - -func ExampleRegister() { - // Imagine you have a worker pool and want to count the tasks completed. - taskCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_total", - Help: "Total number of tasks completed.", - }) - // This will register fine. - if err := prometheus.Register(taskCounter); err != nil { - fmt.Println(err) - } else { - fmt.Println("taskCounter registered.") - } - // Don't forget to tell the HTTP server about the Prometheus handler. - // (In a real program, you still need to start the HTTP server...) - http.Handle("/metrics", prometheus.Handler()) - - // Now you can start workers and give every one of them a pointer to - // taskCounter and let it increment it whenever it completes a task. - taskCounter.Inc() // This has to happen somewhere in the worker code. - - // But wait, you want to see how individual workers perform. So you need - // a vector of counters, with one element for each worker. - taskCounterVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_total", - Help: "Total number of tasks completed.", - }, - []string{"worker_id"}, - ) - - // Registering will fail because we already have a metric of that name. - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - - // To fix, first unregister the old taskCounter. - if prometheus.Unregister(taskCounter) { - fmt.Println("taskCounter unregistered.") - } - - // Try registering taskCounterVec again. - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - // Bummer! Still doesn't work. - - // Prometheus will not allow you to ever export metrics with - // inconsistent help strings or label names. After unregistering, the - // unregistered metrics will cease to show up in the /metrics HTTP - // response, but the registry still remembers that those metrics had - // been exported before. For this example, we will now choose a - // different name. (In a real program, you would obviously not export - // the obsolete metric in the first place.) - taskCounterVec = prometheus.NewCounterVec( - prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks_by_id", - Help: "Total number of tasks completed.", - }, - []string{"worker_id"}, - ) - if err := prometheus.Register(taskCounterVec); err != nil { - fmt.Println("taskCounterVec not registered:", err) - } else { - fmt.Println("taskCounterVec registered.") - } - // Finally it worked! - - // The workers have to tell taskCounterVec their id to increment the - // right element in the metric vector. - taskCounterVec.WithLabelValues("42").Inc() // Code from worker 42. - - // Each worker could also keep a reference to their own counter element - // around. Pick the counter at initialization time of the worker. - myCounter := taskCounterVec.WithLabelValues("42") // From worker 42 initialization code. - myCounter.Inc() // Somewhere in the code of that worker. - - // Note that something like WithLabelValues("42", "spurious arg") would - // panic (because you have provided too many label values). If you want - // to get an error instead, use GetMetricWithLabelValues(...) instead. - notMyCounter, err := taskCounterVec.GetMetricWithLabelValues("42", "spurious arg") - if err != nil { - fmt.Println("Worker initialization failed:", err) - } - if notMyCounter == nil { - fmt.Println("notMyCounter is nil.") - } - - // A different (and somewhat tricky) approach is to use - // ConstLabels. ConstLabels are pairs of label names and label values - // that never change. You might ask what those labels are good for (and - // rightfully so - if they never change, they could as well be part of - // the metric name). There are essentially two use-cases: The first is - // if labels are constant throughout the lifetime of a binary execution, - // but they vary over time or between different instances of a running - // binary. The second is what we have here: Each worker creates and - // registers an own Counter instance where the only difference is in the - // value of the ConstLabels. Those Counters can all be registered - // because the different ConstLabel values guarantee that each worker - // will increment a different Counter metric. - counterOpts := prometheus.CounterOpts{ - Subsystem: "worker_pool", - Name: "completed_tasks", - Help: "Total number of tasks completed.", - ConstLabels: prometheus.Labels{"worker_id": "42"}, - } - taskCounterForWorker42 := prometheus.NewCounter(counterOpts) - if err := prometheus.Register(taskCounterForWorker42); err != nil { - fmt.Println("taskCounterVForWorker42 not registered:", err) - } else { - fmt.Println("taskCounterForWorker42 registered.") - } - // Obviously, in real code, taskCounterForWorker42 would be a member - // variable of a worker struct, and the "42" would be retrieved with a - // GetId() method or something. The Counter would be created and - // registered in the initialization code of the worker. - - // For the creation of the next Counter, we can recycle - // counterOpts. Just change the ConstLabels. - counterOpts.ConstLabels = prometheus.Labels{"worker_id": "2001"} - taskCounterForWorker2001 := prometheus.NewCounter(counterOpts) - if err := prometheus.Register(taskCounterForWorker2001); err != nil { - fmt.Println("taskCounterVForWorker2001 not registered:", err) - } else { - fmt.Println("taskCounterForWorker2001 registered.") - } - - taskCounterForWorker2001.Inc() - taskCounterForWorker42.Inc() - taskCounterForWorker2001.Inc() - - // Yet another approach would be to turn the workers themselves into - // Collectors and register them. See the Collector example for details. - - // Output: - // taskCounter registered. - // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string - // taskCounter unregistered. - // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string - // taskCounterVec registered. - // Worker initialization failed: inconsistent label cardinality - // notMyCounter is nil. - // taskCounterForWorker42 registered. - // taskCounterForWorker2001 registered. -} - -func ExampleSummary() { - temps := prometheus.NewSummary(prometheus.SummaryOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - }) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - } - - // Just for demonstration, let's check the state of the summary by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - temps.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // summary: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // quantile: < - // quantile: 0.5 - // value: 31.1 - // > - // quantile: < - // quantile: 0.9 - // value: 41.3 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > -} - -func ExampleSummaryVec() { - temps := prometheus.NewSummaryVec( - prometheus.SummaryOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - }, - []string{"species"}, - ) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.WithLabelValues("litoria-caerulea").Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - temps.WithLabelValues("lithobates-catesbeianus").Observe(32 + math.Floor(100*math.Cos(float64(i)*0.11))/10) - } - - // Create a Summary without any observations. - temps.WithLabelValues("leiopelma-hochstetteri") - - // Just for demonstration, let's check the state of the summary vector - // by registering it with a custom registry and then let it collect the - // metrics. - reg := prometheus.NewRegistry() - reg.MustRegister(temps) - - metricFamilies, err := reg.Gather() - if err != nil || len(metricFamilies) != 1 { - panic("unexpected behavior of custom test registry") - } - fmt.Println(proto.MarshalTextString(metricFamilies[0])) - - // Output: - // name: "pond_temperature_celsius" - // help: "The temperature of the frog pond." - // type: SUMMARY - // metric: < - // label: < - // name: "species" - // value: "leiopelma-hochstetteri" - // > - // summary: < - // sample_count: 0 - // sample_sum: 0 - // quantile: < - // quantile: 0.5 - // value: nan - // > - // quantile: < - // quantile: 0.9 - // value: nan - // > - // quantile: < - // quantile: 0.99 - // value: nan - // > - // > - // > - // metric: < - // label: < - // name: "species" - // value: "lithobates-catesbeianus" - // > - // summary: < - // sample_count: 1000 - // sample_sum: 31956.100000000017 - // quantile: < - // quantile: 0.5 - // value: 32.4 - // > - // quantile: < - // quantile: 0.9 - // value: 41.4 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > - // > - // metric: < - // label: < - // name: "species" - // value: "litoria-caerulea" - // > - // summary: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // quantile: < - // quantile: 0.5 - // value: 31.1 - // > - // quantile: < - // quantile: 0.9 - // value: 41.3 - // > - // quantile: < - // quantile: 0.99 - // value: 41.9 - // > - // > - // > -} - -func ExampleNewConstSummary() { - desc := prometheus.NewDesc( - "http_request_duration_seconds", - "A summary of the HTTP request durations.", - []string{"code", "method"}, - prometheus.Labels{"owner": "example"}, - ) - - // Create a constant summary from values we got from a 3rd party telemetry system. - s := prometheus.MustNewConstSummary( - desc, - 4711, 403.34, - map[float64]float64{0.5: 42.3, 0.9: 323.3}, - "200", "get", - ) - - // Just for demonstration, let's check the state of the summary by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - s.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // label: < - // name: "code" - // value: "200" - // > - // label: < - // name: "method" - // value: "get" - // > - // label: < - // name: "owner" - // value: "example" - // > - // summary: < - // sample_count: 4711 - // sample_sum: 403.34 - // quantile: < - // quantile: 0.5 - // value: 42.3 - // > - // quantile: < - // quantile: 0.9 - // value: 323.3 - // > - // > -} - -func ExampleHistogram() { - temps := prometheus.NewHistogram(prometheus.HistogramOpts{ - Name: "pond_temperature_celsius", - Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. - Buckets: prometheus.LinearBuckets(20, 5, 5), // 5 buckets, each 5 centigrade wide. - }) - - // Simulate some observations. - for i := 0; i < 1000; i++ { - temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) - } - - // Just for demonstration, let's check the state of the histogram by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - temps.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // histogram: < - // sample_count: 1000 - // sample_sum: 29969.50000000001 - // bucket: < - // cumulative_count: 192 - // upper_bound: 20 - // > - // bucket: < - // cumulative_count: 366 - // upper_bound: 25 - // > - // bucket: < - // cumulative_count: 501 - // upper_bound: 30 - // > - // bucket: < - // cumulative_count: 638 - // upper_bound: 35 - // > - // bucket: < - // cumulative_count: 816 - // upper_bound: 40 - // > - // > -} - -func ExampleNewConstHistogram() { - desc := prometheus.NewDesc( - "http_request_duration_seconds", - "A histogram of the HTTP request durations.", - []string{"code", "method"}, - prometheus.Labels{"owner": "example"}, - ) - - // Create a constant histogram from values we got from a 3rd party telemetry system. - h := prometheus.MustNewConstHistogram( - desc, - 4711, 403.34, - map[float64]uint64{25: 121, 50: 2403, 100: 3221, 200: 4233}, - "200", "get", - ) - - // Just for demonstration, let's check the state of the histogram by - // (ab)using its Write method (which is usually only used by Prometheus - // internally). - metric := &dto.Metric{} - h.Write(metric) - fmt.Println(proto.MarshalTextString(metric)) - - // Output: - // label: < - // name: "code" - // value: "200" - // > - // label: < - // name: "method" - // value: "get" - // > - // label: < - // name: "owner" - // value: "example" - // > - // histogram: < - // sample_count: 4711 - // sample_sum: 403.34 - // bucket: < - // cumulative_count: 121 - // upper_bound: 25 - // > - // bucket: < - // cumulative_count: 2403 - // upper_bound: 50 - // > - // bucket: < - // cumulative_count: 3221 - // upper_bound: 100 - // > - // bucket: < - // cumulative_count: 4233 - // upper_bound: 200 - // > - // > -} - -func ExampleAlreadyRegisteredError() { - reqCounter := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "requests_total", - Help: "The total number of requests served.", - }) - if err := prometheus.Register(reqCounter); err != nil { - if are, ok := err.(prometheus.AlreadyRegisteredError); ok { - // A counter for that metric has been registered before. - // Use the old counter from now on. - reqCounter = are.ExistingCollector.(prometheus.Counter) - } else { - // Something else went wrong! - panic(err) - } - } -} - -func ExampleGatherers() { - reg := prometheus.NewRegistry() - temp := prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Name: "temperature_kelvin", - Help: "Temperature in Kelvin.", - }, - []string{"location"}, - ) - reg.MustRegister(temp) - temp.WithLabelValues("outside").Set(273.14) - temp.WithLabelValues("inside").Set(298.44) - - var parser expfmt.TextParser - - text := ` -# TYPE humidity_percent gauge -# HELP humidity_percent Humidity in %. -humidity_percent{location="outside"} 45.4 -humidity_percent{location="inside"} 33.2 -# TYPE temperature_kelvin gauge -# HELP temperature_kelvin Temperature in Kelvin. -temperature_kelvin{location="somewhere else"} 4.5 -` - - parseText := func() ([]*dto.MetricFamily, error) { - parsed, err := parser.TextToMetricFamilies(strings.NewReader(text)) - if err != nil { - return nil, err - } - var result []*dto.MetricFamily - for _, mf := range parsed { - result = append(result, mf) - } - return result, nil - } - - gatherers := prometheus.Gatherers{ - reg, - prometheus.GathererFunc(parseText), - } - - gathering, err := gatherers.Gather() - if err != nil { - fmt.Println(err) - } - - out := &bytes.Buffer{} - for _, mf := range gathering { - if _, err := expfmt.MetricFamilyToText(out, mf); err != nil { - panic(err) - } - } - fmt.Print(out.String()) - fmt.Println("----------") - - // Note how the temperature_kelvin metric family has been merged from - // different sources. Now try - text = ` -# TYPE humidity_percent gauge -# HELP humidity_percent Humidity in %. -humidity_percent{location="outside"} 45.4 -humidity_percent{location="inside"} 33.2 -# TYPE temperature_kelvin gauge -# HELP temperature_kelvin Temperature in Kelvin. -# Duplicate metric: -temperature_kelvin{location="outside"} 265.3 - # Wrong labels: -temperature_kelvin 4.5 -` - - gathering, err = gatherers.Gather() - if err != nil { - fmt.Println(err) - } - // Note that still as many metrics as possible are returned: - out.Reset() - for _, mf := range gathering { - if _, err := expfmt.MetricFamilyToText(out, mf); err != nil { - panic(err) - } - } - fmt.Print(out.String()) - - // Output: - // # HELP humidity_percent Humidity in %. - // # TYPE humidity_percent gauge - // humidity_percent{location="inside"} 33.2 - // humidity_percent{location="outside"} 45.4 - // # HELP temperature_kelvin Temperature in Kelvin. - // # TYPE temperature_kelvin gauge - // temperature_kelvin{location="inside"} 298.44 - // temperature_kelvin{location="outside"} 273.14 - // temperature_kelvin{location="somewhere else"} 4.5 - // ---------- - // 2 error(s) occurred: - // * collected metric temperature_kelvin label: gauge: was collected before with the same name and label values - // * collected metric temperature_kelvin gauge: has label dimensions inconsistent with previously collected metrics in the same metric family - // # HELP humidity_percent Humidity in %. - // # TYPE humidity_percent gauge - // humidity_percent{location="inside"} 33.2 - // humidity_percent{location="outside"} 45.4 - // # HELP temperature_kelvin Temperature in Kelvin. - // # TYPE temperature_kelvin gauge - // temperature_kelvin{location="inside"} 298.44 - // temperature_kelvin{location="outside"} 273.14 -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go deleted file mode 100644 index 5d3128faed..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus_test - -import ( - "expvar" - "fmt" - "sort" - "strings" - - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/client_golang/prometheus" -) - -func ExampleExpvarCollector() { - expvarCollector := prometheus.NewExpvarCollector(map[string]*prometheus.Desc{ - "memstats": prometheus.NewDesc( - "expvar_memstats", - "All numeric memstats as one metric family. Not a good role-model, actually... ;-)", - []string{"type"}, nil, - ), - "lone-int": prometheus.NewDesc( - "expvar_lone_int", - "Just an expvar int as an example.", - nil, nil, - ), - "http-request-map": prometheus.NewDesc( - "expvar_http_request_total", - "How many http requests processed, partitioned by status code and http method.", - []string{"code", "method"}, nil, - ), - }) - prometheus.MustRegister(expvarCollector) - - // The Prometheus part is done here. But to show that this example is - // doing anything, we have to manually export something via expvar. In - // real-life use-cases, some library would already have exported via - // expvar what we want to re-export as Prometheus metrics. - expvar.NewInt("lone-int").Set(42) - expvarMap := expvar.NewMap("http-request-map") - var ( - expvarMap1, expvarMap2 expvar.Map - expvarInt11, expvarInt12, expvarInt21, expvarInt22 expvar.Int - ) - expvarMap1.Init() - expvarMap2.Init() - expvarInt11.Set(3) - expvarInt12.Set(13) - expvarInt21.Set(11) - expvarInt22.Set(212) - expvarMap1.Set("POST", &expvarInt11) - expvarMap1.Set("GET", &expvarInt12) - expvarMap2.Set("POST", &expvarInt21) - expvarMap2.Set("GET", &expvarInt22) - expvarMap.Set("404", &expvarMap1) - expvarMap.Set("200", &expvarMap2) - // Results in the following expvar map: - // "http-request-count": {"200": {"POST": 11, "GET": 212}, "404": {"POST": 3, "GET": 13}} - - // Let's see what the scrape would yield, but exclude the memstats metrics. - metricStrings := []string{} - metric := dto.Metric{} - metricChan := make(chan prometheus.Metric) - go func() { - expvarCollector.Collect(metricChan) - close(metricChan) - }() - for m := range metricChan { - if strings.Index(m.Desc().String(), "expvar_memstats") == -1 { - metric.Reset() - m.Write(&metric) - metricStrings = append(metricStrings, metric.String()) - } - } - sort.Strings(metricStrings) - for _, s := range metricStrings { - fmt.Println(strings.TrimRight(s, " ")) - } - // Output: - // label: label: untyped: - // label: label: untyped: - // label: label: untyped: - // label: label: untyped: - // untyped: -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go deleted file mode 100644 index 48cab46367..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "math" - "math/rand" - "sync" - "testing" - "testing/quick" - - dto "github.com/prometheus/client_model/go" -) - -func listenGaugeStream(vals, result chan float64, done chan struct{}) { - var sum float64 -outer: - for { - select { - case <-done: - close(vals) - for v := range vals { - sum += v - } - break outer - case v := <-vals: - sum += v - } - } - result <- sum - close(result) -} - -func TestGaugeConcurrency(t *testing.T) { - it := func(n uint32) bool { - mutations := int(n % 10000) - concLevel := int(n%15 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sStream := make(chan float64, mutations*concLevel) - result := make(chan float64) - done := make(chan struct{}) - - go listenGaugeStream(sStream, result, done) - go func() { - end.Wait() - close(done) - }() - - gge := NewGauge(GaugeOpts{ - Name: "test_gauge", - Help: "no help can be found here", - }) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - vals[j] = rand.Float64() - 0.5 - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sStream <- v - gge.Add(v) - } - end.Done() - }(vals) - } - start.Done() - - if expected, got := <-result, math.Float64frombits(gge.(*value).valBits); math.Abs(expected-got) > 0.000001 { - t.Fatalf("expected approx. %f, got %f", expected, got) - return false - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } -} - -func TestGaugeVecConcurrency(t *testing.T) { - it := func(n uint32) bool { - mutations := int(n % 10000) - concLevel := int(n%15 + 1) - vecLength := int(n%5 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sStreams := make([]chan float64, vecLength) - results := make([]chan float64, vecLength) - done := make(chan struct{}) - - for i := 0; i < vecLength; i++ { - sStreams[i] = make(chan float64, mutations*concLevel) - results[i] = make(chan float64) - go listenGaugeStream(sStreams[i], results[i], done) - } - - go func() { - end.Wait() - close(done) - }() - - gge := NewGaugeVec( - GaugeOpts{ - Name: "test_gauge", - Help: "no help can be found here", - }, - []string{"label"}, - ) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - pick := make([]int, mutations) - for j := 0; j < mutations; j++ { - vals[j] = rand.Float64() - 0.5 - pick[j] = rand.Intn(vecLength) - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - sStreams[pick[i]] <- v - gge.WithLabelValues(string('A' + pick[i])).Add(v) - } - end.Done() - }(vals) - } - start.Done() - - for i := range sStreams { - if expected, got := <-results[i], math.Float64frombits(gge.WithLabelValues(string('A'+i)).(*value).valBits); math.Abs(expected-got) > 0.000001 { - t.Fatalf("expected approx. %f, got %f", expected, got) - return false - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Fatal(err) - } -} - -func TestGaugeFunc(t *testing.T) { - gf := NewGaugeFunc( - GaugeOpts{ - Name: "test_name", - Help: "test help", - ConstLabels: Labels{"a": "1", "b": "2"}, - }, - func() float64 { return 3.1415 }, - ) - - if expected, got := `Desc{fqName: "test_name", help: "test help", constLabels: {a="1",b="2"}, variableLabels: []}`, gf.Desc().String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } - - m := &dto.Metric{} - gf.Write(m) - - if expected, got := `label: label: gauge: `, m.String(); expected != got { - t.Errorf("expected %q, got %q", expected, got) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go deleted file mode 100644 index 9a8858cbd2..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package prometheus - -import ( - "runtime" - "testing" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func TestGoCollector(t *testing.T) { - var ( - c = NewGoCollector() - ch = make(chan Metric) - waitc = make(chan struct{}) - closec = make(chan struct{}) - old = -1 - ) - defer close(closec) - - go func() { - c.Collect(ch) - go func(c <-chan struct{}) { - <-c - }(closec) - <-waitc - c.Collect(ch) - }() - - for { - select { - case metric := <-ch: - switch m := metric.(type) { - // Attention, this also catches Counter... - case Gauge: - pb := &dto.Metric{} - m.Write(pb) - if pb.GetGauge() == nil { - continue - } - - if old == -1 { - old = int(pb.GetGauge().GetValue()) - close(waitc) - continue - } - - if diff := int(pb.GetGauge().GetValue()) - old; diff != 1 { - // TODO: This is flaky in highly concurrent situations. - t.Errorf("want 1 new goroutine, got %d", diff) - } - - // GoCollector performs two sends per call. - // On line 27 we need to receive the second send - // to shut down cleanly. - <-ch - return - } - case <-time.After(1 * time.Second): - t.Fatalf("expected collect timed out") - } - } -} - -func TestGCCollector(t *testing.T) { - var ( - c = NewGoCollector() - ch = make(chan Metric) - waitc = make(chan struct{}) - closec = make(chan struct{}) - oldGC uint64 - oldPause float64 - ) - defer close(closec) - - go func() { - c.Collect(ch) - // force GC - runtime.GC() - <-waitc - c.Collect(ch) - }() - - first := true - for { - select { - case metric := <-ch: - switch m := metric.(type) { - case *constSummary, *value: - pb := &dto.Metric{} - m.Write(pb) - if pb.GetSummary() == nil { - continue - } - - if len(pb.GetSummary().Quantile) != 5 { - t.Errorf("expected 4 buckets, got %d", len(pb.GetSummary().Quantile)) - } - for idx, want := range []float64{0.0, 0.25, 0.5, 0.75, 1.0} { - if *pb.GetSummary().Quantile[idx].Quantile != want { - t.Errorf("bucket #%d is off, got %f, want %f", idx, *pb.GetSummary().Quantile[idx].Quantile, want) - } - } - if first { - first = false - oldGC = *pb.GetSummary().SampleCount - oldPause = *pb.GetSummary().SampleSum - close(waitc) - continue - } - if diff := *pb.GetSummary().SampleCount - oldGC; diff != 1 { - t.Errorf("want 1 new garbage collection run, got %d", diff) - } - if diff := *pb.GetSummary().SampleSum - oldPause; diff <= 0 { - t.Errorf("want moar pause, got %f", diff) - } - return - } - case <-time.After(1 * time.Second): - t.Fatalf("expected collect timed out") - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go deleted file mode 100644 index d1242e08d6..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go +++ /dev/null @@ -1,326 +0,0 @@ -// Copyright 2015 The Prometheus 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 prometheus - -import ( - "math" - "math/rand" - "reflect" - "sort" - "sync" - "testing" - "testing/quick" - - dto "github.com/prometheus/client_model/go" -) - -func benchmarkHistogramObserve(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewHistogram(HistogramOpts{}) - - for i := 0; i < w; i++ { - go func() { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Observe(float64(i)) - } - - wg.Done() - }() - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkHistogramObserve1(b *testing.B) { - benchmarkHistogramObserve(1, b) -} - -func BenchmarkHistogramObserve2(b *testing.B) { - benchmarkHistogramObserve(2, b) -} - -func BenchmarkHistogramObserve4(b *testing.B) { - benchmarkHistogramObserve(4, b) -} - -func BenchmarkHistogramObserve8(b *testing.B) { - benchmarkHistogramObserve(8, b) -} - -func benchmarkHistogramWrite(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewHistogram(HistogramOpts{}) - - for i := 0; i < 1000000; i++ { - s.Observe(float64(i)) - } - - for j := 0; j < w; j++ { - outs := make([]dto.Metric, b.N) - - go func(o []dto.Metric) { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Write(&o[i]) - } - - wg.Done() - }(outs) - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkHistogramWrite1(b *testing.B) { - benchmarkHistogramWrite(1, b) -} - -func BenchmarkHistogramWrite2(b *testing.B) { - benchmarkHistogramWrite(2, b) -} - -func BenchmarkHistogramWrite4(b *testing.B) { - benchmarkHistogramWrite(4, b) -} - -func BenchmarkHistogramWrite8(b *testing.B) { - benchmarkHistogramWrite(8, b) -} - -// Intentionally adding +Inf here to test if that case is handled correctly. -// Also, getCumulativeCounts depends on it. -var testBuckets = []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)} - -func TestHistogramConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%5 + 1) - total := mutations * concLevel - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewHistogram(HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: testBuckets, - }) - - allVars := make([]float64, total) - var sampleSum float64 - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - allVars[i*mutations+j] = v - sampleSum += v - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sum.Observe(v) - } - end.Done() - }(vals) - } - sort.Float64s(allVars) - start.Done() - end.Wait() - - m := &dto.Metric{} - sum.Write(m) - if got, want := int(*m.Histogram.SampleCount), total; got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Histogram.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - wantCounts := getCumulativeCounts(allVars) - - if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { - t.Errorf("got %d buckets in protobuf, want %d", got, want) - } - for i, wantBound := range testBuckets { - if i == len(testBuckets)-1 { - break // No +Inf bucket in protobuf. - } - if gotBound := *m.Histogram.Bucket[i].UpperBound; gotBound != wantBound { - t.Errorf("got bound %f, want %f", gotBound, wantBound) - } - if gotCount, wantCount := *m.Histogram.Bucket[i].CumulativeCount, wantCounts[i]; gotCount != wantCount { - t.Errorf("got count %d, want %d", gotCount, wantCount) - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestHistogramVecConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%7 + 1) - vecLength := int(n%3 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - his := NewHistogramVec( - HistogramOpts{ - Name: "test_histogram", - Help: "helpless", - Buckets: []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)}, - }, - []string{"label"}, - ) - - allVars := make([][]float64, vecLength) - sampleSums := make([]float64, vecLength) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - picks := make([]int, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - pick := rand.Intn(vecLength) - picks[j] = pick - allVars[pick] = append(allVars[pick], v) - sampleSums[pick] += v - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - his.WithLabelValues(string('A' + picks[i])).Observe(v) - } - end.Done() - }(vals) - } - for _, vars := range allVars { - sort.Float64s(vars) - } - start.Done() - end.Wait() - - for i := 0; i < vecLength; i++ { - m := &dto.Metric{} - s := his.WithLabelValues(string('A' + i)) - s.Write(m) - - if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { - t.Errorf("got %d buckets in protobuf, want %d", got, want) - } - if got, want := int(*m.Histogram.SampleCount), len(allVars[i]); got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Histogram.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - wantCounts := getCumulativeCounts(allVars[i]) - - for j, wantBound := range testBuckets { - if j == len(testBuckets)-1 { - break // No +Inf bucket in protobuf. - } - if gotBound := *m.Histogram.Bucket[j].UpperBound; gotBound != wantBound { - t.Errorf("got bound %f, want %f", gotBound, wantBound) - } - if gotCount, wantCount := *m.Histogram.Bucket[j].CumulativeCount, wantCounts[j]; gotCount != wantCount { - t.Errorf("got count %d, want %d", gotCount, wantCount) - } - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func getCumulativeCounts(vars []float64) []uint64 { - counts := make([]uint64, len(testBuckets)) - for _, v := range vars { - for i := len(testBuckets) - 1; i >= 0; i-- { - if v > testBuckets[i] { - break - } - counts[i]++ - } - } - return counts -} - -func TestBuckets(t *testing.T) { - got := LinearBuckets(-15, 5, 6) - want := []float64{-15, -10, -5, 0, 5, 10} - if !reflect.DeepEqual(got, want) { - t.Errorf("linear buckets: got %v, want %v", got, want) - } - - got = ExponentialBuckets(100, 1.2, 3) - want = []float64{100, 120, 144} - if !reflect.DeepEqual(got, want) { - t.Errorf("linear buckets: got %v, want %v", got, want) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/http_test.go b/vendor/github.com/prometheus/client_golang/prometheus/http_test.go deleted file mode 100644 index ffe0418cf8..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/http_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" - - dto "github.com/prometheus/client_model/go" -) - -type respBody string - -func (b respBody) ServeHTTP(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTeapot) - w.Write([]byte(b)) -} - -func TestInstrumentHandler(t *testing.T) { - defer func(n nower) { - now = n.(nower) - }(now) - - instant := time.Now() - end := instant.Add(30 * time.Second) - now = nowSeries(instant, end) - respBody := respBody("Howdy there!") - - hndlr := InstrumentHandler("test-handler", respBody) - - opts := SummaryOpts{ - Subsystem: "http", - ConstLabels: Labels{"handler": "test-handler"}, - } - - reqCnt := MustRegisterOrGet(NewCounterVec( - CounterOpts{ - Namespace: opts.Namespace, - Subsystem: opts.Subsystem, - Name: "requests_total", - Help: "Total number of HTTP requests made.", - ConstLabels: opts.ConstLabels, - }, - instLabels, - )).(*CounterVec) - - opts.Name = "request_duration_microseconds" - opts.Help = "The HTTP request latencies in microseconds." - reqDur := MustRegisterOrGet(NewSummary(opts)).(Summary) - - opts.Name = "request_size_bytes" - opts.Help = "The HTTP request sizes in bytes." - MustRegisterOrGet(NewSummary(opts)) - - opts.Name = "response_size_bytes" - opts.Help = "The HTTP response sizes in bytes." - MustRegisterOrGet(NewSummary(opts)) - - reqCnt.Reset() - - resp := httptest.NewRecorder() - req := &http.Request{ - Method: "GET", - } - - hndlr.ServeHTTP(resp, req) - - if resp.Code != http.StatusTeapot { - t.Fatalf("expected status %d, got %d", http.StatusTeapot, resp.Code) - } - if string(resp.Body.Bytes()) != "Howdy there!" { - t.Fatalf("expected body %s, got %s", "Howdy there!", string(resp.Body.Bytes())) - } - - out := &dto.Metric{} - reqDur.Write(out) - if want, got := "test-handler", out.Label[0].GetValue(); want != got { - t.Errorf("want label value %q in reqDur, got %q", want, got) - } - if want, got := uint64(1), out.Summary.GetSampleCount(); want != got { - t.Errorf("want sample count %d in reqDur, got %d", want, got) - } - - out.Reset() - if want, got := 1, len(reqCnt.children); want != got { - t.Errorf("want %d children in reqCnt, got %d", want, got) - } - cnt, err := reqCnt.GetMetricWithLabelValues("get", "418") - if err != nil { - t.Fatal(err) - } - cnt.Write(out) - if want, got := "418", out.Label[0].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if want, got := "test-handler", out.Label[1].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if want, got := "get", out.Label[2].GetValue(); want != got { - t.Errorf("want label value %q in reqCnt, got %q", want, got) - } - if out.Counter == nil { - t.Fatal("expected non-nil counter in reqCnt") - } - if want, got := 1., out.Counter.GetValue(); want != got { - t.Errorf("want reqCnt of %f, got %f", want, got) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go deleted file mode 100644 index d3362dae72..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package prometheus - -import ( - "bytes" - "os" - "regexp" - "testing" - - "github.com/prometheus/common/expfmt" - "github.com/prometheus/procfs" -) - -func TestProcessCollector(t *testing.T) { - if _, err := procfs.Self(); err != nil { - t.Skipf("skipping TestProcessCollector, procfs not available: %s", err) - } - - registry := NewRegistry() - if err := registry.Register(NewProcessCollector(os.Getpid(), "")); err != nil { - t.Fatal(err) - } - if err := registry.Register(NewProcessCollectorPIDFn( - func() (int, error) { return os.Getpid(), nil }, "foobar"), - ); err != nil { - t.Fatal(err) - } - - mfs, err := registry.Gather() - if err != nil { - t.Fatal(err) - } - - var buf bytes.Buffer - for _, mf := range mfs { - if _, err := expfmt.MetricFamilyToText(&buf, mf); err != nil { - t.Fatal(err) - } - } - - for _, re := range []*regexp.Regexp{ - regexp.MustCompile("process_cpu_seconds_total [0-9]"), - regexp.MustCompile("process_max_fds [1-9]"), - regexp.MustCompile("process_open_fds [1-9]"), - regexp.MustCompile("process_virtual_memory_bytes [1-9]"), - regexp.MustCompile("process_resident_memory_bytes [1-9]"), - regexp.MustCompile("process_start_time_seconds [0-9.]{10,}"), - regexp.MustCompile("foobar_process_cpu_seconds_total [0-9]"), - regexp.MustCompile("foobar_process_max_fds [1-9]"), - regexp.MustCompile("foobar_process_open_fds [1-9]"), - regexp.MustCompile("foobar_process_virtual_memory_bytes [1-9]"), - regexp.MustCompile("foobar_process_resident_memory_bytes [1-9]"), - regexp.MustCompile("foobar_process_start_time_seconds [0-9.]{10,}"), - } { - if !re.Match(buf.Bytes()) { - t.Errorf("want body to match %s\n%s", re, buf.String()) - } - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go deleted file mode 100644 index d4a7d4a7b5..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright 2016 The Prometheus 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 (c) 2013, The Prometheus 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 promhttp - -import ( - "bytes" - "errors" - "log" - "net/http" - "net/http/httptest" - "testing" - - "github.com/prometheus/client_golang/prometheus" -) - -type errorCollector struct{} - -func (e errorCollector) Describe(ch chan<- *prometheus.Desc) { - ch <- prometheus.NewDesc("invalid_metric", "not helpful", nil, nil) -} - -func (e errorCollector) Collect(ch chan<- prometheus.Metric) { - ch <- prometheus.NewInvalidMetric( - prometheus.NewDesc("invalid_metric", "not helpful", nil, nil), - errors.New("collect error"), - ) -} - -func TestHandlerErrorHandling(t *testing.T) { - - // Create a registry that collects a MetricFamily with two elements, - // another with one, and reports an error. - reg := prometheus.NewRegistry() - - cnt := prometheus.NewCounter(prometheus.CounterOpts{ - Name: "the_count", - Help: "Ah-ah-ah! Thunder and lightning!", - }) - reg.MustRegister(cnt) - - cntVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "name", - Help: "docstring", - ConstLabels: prometheus.Labels{"constname": "constvalue"}, - }, - []string{"labelname"}, - ) - cntVec.WithLabelValues("val1").Inc() - cntVec.WithLabelValues("val2").Inc() - reg.MustRegister(cntVec) - - reg.MustRegister(errorCollector{}) - - logBuf := &bytes.Buffer{} - logger := log.New(logBuf, "", 0) - - writer := httptest.NewRecorder() - request, _ := http.NewRequest("GET", "/", nil) - request.Header.Add("Accept", "test/plain") - - errorHandler := HandlerFor(reg, HandlerOpts{ - ErrorLog: logger, - ErrorHandling: HTTPErrorOnError, - }) - continueHandler := HandlerFor(reg, HandlerOpts{ - ErrorLog: logger, - ErrorHandling: ContinueOnError, - }) - panicHandler := HandlerFor(reg, HandlerOpts{ - ErrorLog: logger, - ErrorHandling: PanicOnError, - }) - wantMsg := `error gathering metrics: error collecting metric Desc{fqName: "invalid_metric", help: "not helpful", constLabels: {}, variableLabels: []}: collect error -` - wantErrorBody := `An error has occurred during metrics gathering: - -error collecting metric Desc{fqName: "invalid_metric", help: "not helpful", constLabels: {}, variableLabels: []}: collect error -` - wantOKBody := `# HELP name docstring -# TYPE name counter -name{constname="constvalue",labelname="val1"} 1 -name{constname="constvalue",labelname="val2"} 1 -# HELP the_count Ah-ah-ah! Thunder and lightning! -# TYPE the_count counter -the_count 0 -` - - errorHandler.ServeHTTP(writer, request) - if got, want := writer.Code, http.StatusInternalServerError; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } - if got := logBuf.String(); got != wantMsg { - t.Errorf("got log message:\n%s\nwant log mesage:\n%s\n", got, wantMsg) - } - if got := writer.Body.String(); got != wantErrorBody { - t.Errorf("got body:\n%s\nwant body:\n%s\n", got, wantErrorBody) - } - logBuf.Reset() - writer.Body.Reset() - writer.Code = http.StatusOK - - continueHandler.ServeHTTP(writer, request) - if got, want := writer.Code, http.StatusOK; got != want { - t.Errorf("got HTTP status code %d, want %d", got, want) - } - if got := logBuf.String(); got != wantMsg { - t.Errorf("got log message %q, want %q", got, wantMsg) - } - if got := writer.Body.String(); got != wantOKBody { - t.Errorf("got body %q, want %q", got, wantOKBody) - } - - defer func() { - if err := recover(); err == nil { - t.Error("expected panic from panicHandler") - } - }() - panicHandler.ServeHTTP(writer, request) -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go b/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go deleted file mode 100644 index 9dacb6256d..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go +++ /dev/null @@ -1,545 +0,0 @@ -// Copyright 2014 The Prometheus 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 (c) 2013, The Prometheus 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 prometheus_test - -import ( - "bytes" - "net/http" - "net/http/httptest" - "testing" - - dto "github.com/prometheus/client_model/go" - - "github.com/golang/protobuf/proto" - "github.com/prometheus/common/expfmt" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" -) - -func testHandler(t testing.TB) { - - metricVec := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "name", - Help: "docstring", - ConstLabels: prometheus.Labels{"constname": "constvalue"}, - }, - []string{"labelname"}, - ) - - metricVec.WithLabelValues("val1").Inc() - metricVec.WithLabelValues("val2").Inc() - - externalMetricFamily := &dto.MetricFamily{ - Name: proto.String("externalname"), - Help: proto.String("externaldocstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("externalconstname"), - Value: proto.String("externalconstvalue"), - }, - { - Name: proto.String("externallabelname"), - Value: proto.String("externalval1"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - }, - } - externalBuf := &bytes.Buffer{} - enc := expfmt.NewEncoder(externalBuf, expfmt.FmtProtoDelim) - if err := enc.Encode(externalMetricFamily); err != nil { - t.Fatal(err) - } - externalMetricFamilyAsBytes := externalBuf.Bytes() - externalMetricFamilyAsText := []byte(`# HELP externalname externaldocstring -# TYPE externalname counter -externalname{externalconstname="externalconstvalue",externallabelname="externalval1"} 1 -`) - externalMetricFamilyAsProtoText := []byte(`name: "externalname" -help: "externaldocstring" -type: COUNTER -metric: < - label: < - name: "externalconstname" - value: "externalconstvalue" - > - label: < - name: "externallabelname" - value: "externalval1" - > - counter: < - value: 1 - > -> - -`) - externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric: label: counter: > -`) - - expectedMetricFamily := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("docstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(1), - }, - }, - }, - } - buf := &bytes.Buffer{} - enc = expfmt.NewEncoder(buf, expfmt.FmtProtoDelim) - if err := enc.Encode(expectedMetricFamily); err != nil { - t.Fatal(err) - } - expectedMetricFamilyAsBytes := buf.Bytes() - expectedMetricFamilyAsText := []byte(`# HELP name docstring -# TYPE name counter -name{constname="constvalue",labelname="val1"} 1 -name{constname="constvalue",labelname="val2"} 1 -`) - expectedMetricFamilyAsProtoText := []byte(`name: "name" -help: "docstring" -type: COUNTER -metric: < - label: < - name: "constname" - value: "constvalue" - > - label: < - name: "labelname" - value: "val1" - > - counter: < - value: 1 - > -> -metric: < - label: < - name: "constname" - value: "constvalue" - > - label: < - name: "labelname" - value: "val2" - > - counter: < - value: 1 - > -> - -`) - expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > -`) - - externalMetricFamilyWithSameName := &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("docstring"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - { - Label: []*dto.LabelPair{ - { - Name: proto.String("constname"), - Value: proto.String("constvalue"), - }, - { - Name: proto.String("labelname"), - Value: proto.String("different_val"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(42), - }, - }, - }, - } - - expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > metric: label: counter: > -`) - - type output struct { - headers map[string]string - body []byte - } - - var scenarios = []struct { - headers map[string]string - out output - collector prometheus.Collector - externalMF []*dto.MetricFamily - }{ - { // 0 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, dings/bums;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 1 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, application/quark;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 2 - headers: map[string]string{ - "Accept": "foo/bar;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 3 - headers: map[string]string{ - "Accept": "text/plain;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.8", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: []byte{}, - }, - }, - { // 4 - headers: map[string]string{ - "Accept": "application/json", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: expectedMetricFamilyAsText, - }, - collector: metricVec, - }, - { // 5 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: expectedMetricFamilyAsBytes, - }, - collector: metricVec, - }, - { // 6 - headers: map[string]string{ - "Accept": "application/json", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: externalMetricFamilyAsText, - }, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 7 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: externalMetricFamilyAsBytes, - }, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 8 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsBytes, - expectedMetricFamilyAsBytes, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 9 - headers: map[string]string{ - "Accept": "text/plain", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: []byte{}, - }, - }, - { // 10 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: expectedMetricFamilyAsText, - }, - collector: metricVec, - }, - { // 11 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5;version=0.0.4", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `text/plain; version=0.0.4`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsText, - expectedMetricFamilyAsText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 12 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.2, text/plain;q=0.5;version=0.0.2", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsBytes, - expectedMetricFamilyAsBytes, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 13 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=text;q=0.5, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.4", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoText, - expectedMetricFamilyAsProtoText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 14 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoCompactText, - expectedMetricFamilyAsProtoCompactText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{externalMetricFamily}, - }, - { // 15 - headers: map[string]string{ - "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", - }, - out: output{ - headers: map[string]string{ - "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, - }, - body: bytes.Join( - [][]byte{ - externalMetricFamilyAsProtoCompactText, - expectedMetricFamilyMergedWithExternalAsProtoCompactText, - }, - []byte{}, - ), - }, - collector: metricVec, - externalMF: []*dto.MetricFamily{ - externalMetricFamily, - externalMetricFamilyWithSameName, - }, - }, - } - for i, scenario := range scenarios { - registry := prometheus.NewPedanticRegistry() - gatherer := prometheus.Gatherer(registry) - if scenario.externalMF != nil { - gatherer = prometheus.Gatherers{ - registry, - prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) { - return scenario.externalMF, nil - }), - } - } - - if scenario.collector != nil { - registry.Register(scenario.collector) - } - writer := httptest.NewRecorder() - handler := prometheus.InstrumentHandler("prometheus", promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{})) - request, _ := http.NewRequest("GET", "/", nil) - for key, value := range scenario.headers { - request.Header.Add(key, value) - } - handler(writer, request) - - for key, value := range scenario.out.headers { - if writer.HeaderMap.Get(key) != value { - t.Errorf( - "%d. expected %q for header %q, got %q", - i, value, key, writer.Header().Get(key), - ) - } - } - - if !bytes.Equal(scenario.out.body, writer.Body.Bytes()) { - t.Errorf( - "%d. expected body:\n%s\ngot body:\n%s\n", - i, scenario.out.body, writer.Body.Bytes(), - ) - } - } -} - -func TestHandler(t *testing.T) { - testHandler(t) -} - -func BenchmarkHandler(b *testing.B) { - for i := 0; i < b.N; i++ { - testHandler(b) - } -} - -func TestRegisterWithOrGet(t *testing.T) { - // Replace the default registerer just to be sure. This is bad, but this - // whole test will go away once RegisterOrGet is removed. - oldRegisterer := prometheus.DefaultRegisterer - defer func() { - prometheus.DefaultRegisterer = oldRegisterer - }() - prometheus.DefaultRegisterer = prometheus.NewRegistry() - original := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "test", - Help: "help", - }, - []string{"foo", "bar"}, - ) - equalButNotSame := prometheus.NewCounterVec( - prometheus.CounterOpts{ - Name: "test", - Help: "help", - }, - []string{"foo", "bar"}, - ) - if err := prometheus.Register(original); err != nil { - t.Fatal(err) - } - if err := prometheus.Register(equalButNotSame); err == nil { - t.Fatal("expected error when registringe equal collector") - } - existing, err := prometheus.RegisterOrGet(equalButNotSame) - if err != nil { - t.Fatal(err) - } - if existing != original { - t.Error("expected original collector but got something else") - } - if existing == equalButNotSame { - t.Error("expected original callector but got new one") - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go b/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go deleted file mode 100644 index c4575ffbd2..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go +++ /dev/null @@ -1,347 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "math" - "math/rand" - "sort" - "sync" - "testing" - "testing/quick" - "time" - - dto "github.com/prometheus/client_model/go" -) - -func benchmarkSummaryObserve(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewSummary(SummaryOpts{}) - - for i := 0; i < w; i++ { - go func() { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Observe(float64(i)) - } - - wg.Done() - }() - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkSummaryObserve1(b *testing.B) { - benchmarkSummaryObserve(1, b) -} - -func BenchmarkSummaryObserve2(b *testing.B) { - benchmarkSummaryObserve(2, b) -} - -func BenchmarkSummaryObserve4(b *testing.B) { - benchmarkSummaryObserve(4, b) -} - -func BenchmarkSummaryObserve8(b *testing.B) { - benchmarkSummaryObserve(8, b) -} - -func benchmarkSummaryWrite(w int, b *testing.B) { - b.StopTimer() - - wg := new(sync.WaitGroup) - wg.Add(w) - - g := new(sync.WaitGroup) - g.Add(1) - - s := NewSummary(SummaryOpts{}) - - for i := 0; i < 1000000; i++ { - s.Observe(float64(i)) - } - - for j := 0; j < w; j++ { - outs := make([]dto.Metric, b.N) - - go func(o []dto.Metric) { - g.Wait() - - for i := 0; i < b.N; i++ { - s.Write(&o[i]) - } - - wg.Done() - }(outs) - } - - b.StartTimer() - g.Done() - wg.Wait() -} - -func BenchmarkSummaryWrite1(b *testing.B) { - benchmarkSummaryWrite(1, b) -} - -func BenchmarkSummaryWrite2(b *testing.B) { - benchmarkSummaryWrite(2, b) -} - -func BenchmarkSummaryWrite4(b *testing.B) { - benchmarkSummaryWrite(4, b) -} - -func BenchmarkSummaryWrite8(b *testing.B) { - benchmarkSummaryWrite(8, b) -} - -func TestSummaryConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%5 + 1) - total := mutations * concLevel - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewSummary(SummaryOpts{ - Name: "test_summary", - Help: "helpless", - }) - - allVars := make([]float64, total) - var sampleSum float64 - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - allVars[i*mutations+j] = v - sampleSum += v - } - - go func(vals []float64) { - start.Wait() - for _, v := range vals { - sum.Observe(v) - } - end.Done() - }(vals) - } - sort.Float64s(allVars) - start.Done() - end.Wait() - - m := &dto.Metric{} - sum.Write(m) - if got, want := int(*m.Summary.SampleCount), total; got != want { - t.Errorf("got sample count %d, want %d", got, want) - } - if got, want := *m.Summary.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f, want %f", got, want) - } - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - for i, wantQ := range objectives { - ε := DefObjectives[wantQ] - gotQ := *m.Summary.Quantile[i].Quantile - gotV := *m.Summary.Quantile[i].Value - min, max := getBounds(allVars, wantQ, ε) - if gotQ != wantQ { - t.Errorf("got quantile %f, want %f", gotQ, wantQ) - } - if gotV < min || gotV > max { - t.Errorf("got %f for quantile %f, want [%f,%f]", gotV, gotQ, min, max) - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestSummaryVecConcurrency(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - } - - rand.Seed(42) - - objectives := make([]float64, 0, len(DefObjectives)) - for qu := range DefObjectives { - - objectives = append(objectives, qu) - } - sort.Float64s(objectives) - - it := func(n uint32) bool { - mutations := int(n%1e4 + 1e4) - concLevel := int(n%7 + 1) - vecLength := int(n%3 + 1) - - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - sum := NewSummaryVec( - SummaryOpts{ - Name: "test_summary", - Help: "helpless", - }, - []string{"label"}, - ) - - allVars := make([][]float64, vecLength) - sampleSums := make([]float64, vecLength) - for i := 0; i < concLevel; i++ { - vals := make([]float64, mutations) - picks := make([]int, mutations) - for j := 0; j < mutations; j++ { - v := rand.NormFloat64() - vals[j] = v - pick := rand.Intn(vecLength) - picks[j] = pick - allVars[pick] = append(allVars[pick], v) - sampleSums[pick] += v - } - - go func(vals []float64) { - start.Wait() - for i, v := range vals { - sum.WithLabelValues(string('A' + picks[i])).Observe(v) - } - end.Done() - }(vals) - } - for _, vars := range allVars { - sort.Float64s(vars) - } - start.Done() - end.Wait() - - for i := 0; i < vecLength; i++ { - m := &dto.Metric{} - s := sum.WithLabelValues(string('A' + i)) - s.Write(m) - if got, want := int(*m.Summary.SampleCount), len(allVars[i]); got != want { - t.Errorf("got sample count %d for label %c, want %d", got, 'A'+i, want) - } - if got, want := *m.Summary.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { - t.Errorf("got sample sum %f for label %c, want %f", got, 'A'+i, want) - } - for j, wantQ := range objectives { - ε := DefObjectives[wantQ] - gotQ := *m.Summary.Quantile[j].Quantile - gotV := *m.Summary.Quantile[j].Value - min, max := getBounds(allVars[i], wantQ, ε) - if gotQ != wantQ { - t.Errorf("got quantile %f for label %c, want %f", gotQ, 'A'+i, wantQ) - } - if gotV < min || gotV > max { - t.Errorf("got %f for quantile %f for label %c, want [%f,%f]", gotV, gotQ, 'A'+i, min, max) - } - } - } - return true - } - - if err := quick.Check(it, nil); err != nil { - t.Error(err) - } -} - -func TestSummaryDecay(t *testing.T) { - if testing.Short() { - t.Skip("Skipping test in short mode.") - // More because it depends on timing than because it is particularly long... - } - - sum := NewSummary(SummaryOpts{ - Name: "test_summary", - Help: "helpless", - MaxAge: 100 * time.Millisecond, - Objectives: map[float64]float64{0.1: 0.001}, - AgeBuckets: 10, - }) - - m := &dto.Metric{} - i := 0 - tick := time.NewTicker(time.Millisecond) - for _ = range tick.C { - i++ - sum.Observe(float64(i)) - if i%10 == 0 { - sum.Write(m) - if got, want := *m.Summary.Quantile[0].Value, math.Max(float64(i)/10, float64(i-90)); math.Abs(got-want) > 20 { - t.Errorf("%d. got %f, want %f", i, got, want) - } - m.Reset() - } - if i >= 1000 { - break - } - } - tick.Stop() - // Wait for MaxAge without observations and make sure quantiles are NaN. - time.Sleep(100 * time.Millisecond) - sum.Write(m) - if got := *m.Summary.Quantile[0].Value; !math.IsNaN(got) { - t.Errorf("got %f, want NaN after expiration", got) - } -} - -func getBounds(vars []float64, q, ε float64) (min, max float64) { - // TODO(beorn7): This currently tolerates an error of up to 2*ε. The - // error must be at most ε, but for some reason, it's sometimes slightly - // higher. That's a bug. - n := float64(len(vars)) - lower := int((q - 2*ε) * n) - upper := int(math.Ceil((q + 2*ε) * n)) - min = vars[0] - if lower > 1 { - min = vars[lower-1] - } - max = vars[len(vars)-1] - if upper < len(vars) { - max = vars[upper-1] - } - return -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go b/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go deleted file mode 100644 index 445a6b39fe..0000000000 --- a/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go +++ /dev/null @@ -1,312 +0,0 @@ -// Copyright 2014 The Prometheus 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 prometheus - -import ( - "fmt" - "testing" - - dto "github.com/prometheus/client_model/go" -) - -func TestDelete(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - testDelete(t, vec) -} - -func TestDeleteWithCollisions(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - vec.hashAdd = func(h uint64, s string) uint64 { return 1 } - vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 } - testDelete(t, vec) -} - -func testDelete(t *testing.T, vec *UntypedVec) { - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - if got, want := vec.Delete(Labels{"l2": "v1", "l1": "v2"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.Delete(Labels{"l1": "v1"}), false; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestDeleteLabelValues(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - testDeleteLabelValues(t, vec) -} - -func TestDeleteLabelValuesWithCollisions(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - vec.hashAdd = func(h uint64, s string) uint64 { return 1 } - vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 } - testDeleteLabelValues(t, vec) -} - -func testDeleteLabelValues(t *testing.T, vec *UntypedVec) { - if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - vec.With(Labels{"l1": "v1", "l2": "v3"}).(Untyped).Set(42) // Add junk data for collision. - if got, want := vec.DeleteLabelValues("v1", "v2"), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1", "v3"), true; got != want { - t.Errorf("got %v, want %v", got, want) - } - - vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) - // Delete out of order. - if got, want := vec.DeleteLabelValues("v2", "v1"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } - if got, want := vec.DeleteLabelValues("v1"), false; got != want { - t.Errorf("got %v, want %v", got, want) - } -} - -func TestMetricVec(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - testMetricVec(t, vec) -} - -func TestMetricVecWithCollisions(t *testing.T) { - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - []string{"l1", "l2"}, - ) - vec.hashAdd = func(h uint64, s string) uint64 { return 1 } - vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 } - testMetricVec(t, vec) -} - -func testMetricVec(t *testing.T, vec *UntypedVec) { - vec.Reset() // Actually test Reset now! - - var pair [2]string - // Keep track of metrics. - expected := map[[2]string]int{} - - for i := 0; i < 1000; i++ { - pair[0], pair[1] = fmt.Sprint(i%4), fmt.Sprint(i%5) // Varying combinations multiples. - expected[pair]++ - vec.WithLabelValues(pair[0], pair[1]).Inc() - - expected[[2]string{"v1", "v2"}]++ - vec.WithLabelValues("v1", "v2").(Untyped).Inc() - } - - var total int - for _, metrics := range vec.children { - for _, metric := range metrics { - total++ - copy(pair[:], metric.values) - - var metricOut dto.Metric - if err := metric.metric.Write(&metricOut); err != nil { - t.Fatal(err) - } - actual := *metricOut.Untyped.Value - - var actualPair [2]string - for i, label := range metricOut.Label { - actualPair[i] = *label.Value - } - - // Test output pair against metric.values to ensure we've selected - // the right one. We check this to ensure the below check means - // anything at all. - if actualPair != pair { - t.Fatalf("unexpected pair association in metric map: %v != %v", actualPair, pair) - } - - if actual != float64(expected[pair]) { - t.Fatalf("incorrect counter value for %v: %v != %v", pair, actual, expected[pair]) - } - } - } - - if total != len(expected) { - t.Fatalf("unexpected number of metrics: %v != %v", total, len(expected)) - } - - vec.Reset() - - if len(vec.children) > 0 { - t.Fatalf("reset failed") - } -} - -func TestCounterVecEndToEndWithCollision(t *testing.T) { - vec := NewCounterVec( - CounterOpts{ - Name: "test", - Help: "helpless", - }, - []string{"labelname"}, - ) - vec.WithLabelValues("77kepQFQ8Kl").Inc() - vec.WithLabelValues("!0IC=VloaY").Add(2) - - m := &dto.Metric{} - if err := vec.WithLabelValues("77kepQFQ8Kl").Write(m); err != nil { - t.Fatal(err) - } - if got, want := m.GetLabel()[0].GetValue(), "77kepQFQ8Kl"; got != want { - t.Errorf("got label value %q, want %q", got, want) - } - if got, want := m.GetCounter().GetValue(), 1.; got != want { - t.Errorf("got value %f, want %f", got, want) - } - m.Reset() - if err := vec.WithLabelValues("!0IC=VloaY").Write(m); err != nil { - t.Fatal(err) - } - if got, want := m.GetLabel()[0].GetValue(), "!0IC=VloaY"; got != want { - t.Errorf("got label value %q, want %q", got, want) - } - if got, want := m.GetCounter().GetValue(), 2.; got != want { - t.Errorf("got value %f, want %f", got, want) - } -} - -func BenchmarkMetricVecWithLabelValuesBasic(b *testing.B) { - benchmarkMetricVecWithLabelValues(b, map[string][]string{ - "l1": []string{"onevalue"}, - "l2": []string{"twovalue"}, - }) -} - -func BenchmarkMetricVecWithLabelValues2Keys10ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 2, 10) -} - -func BenchmarkMetricVecWithLabelValues4Keys10ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 4, 10) -} - -func BenchmarkMetricVecWithLabelValues2Keys100ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 2, 100) -} - -func BenchmarkMetricVecWithLabelValues10Keys100ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 10, 100) -} - -func BenchmarkMetricVecWithLabelValues10Keys1000ValueCardinality(b *testing.B) { - benchmarkMetricVecWithLabelValuesCardinality(b, 10, 1000) -} - -func benchmarkMetricVecWithLabelValuesCardinality(b *testing.B, nkeys, nvalues int) { - labels := map[string][]string{} - - for i := 0; i < nkeys; i++ { - var ( - k = fmt.Sprintf("key-%v", i) - vs = make([]string, 0, nvalues) - ) - for j := 0; j < nvalues; j++ { - vs = append(vs, fmt.Sprintf("value-%v", j)) - } - labels[k] = vs - } - - benchmarkMetricVecWithLabelValues(b, labels) -} - -func benchmarkMetricVecWithLabelValues(b *testing.B, labels map[string][]string) { - var keys []string - for k := range labels { // Map order dependent, who cares though. - keys = append(keys, k) - } - - values := make([]string, len(labels)) // Value cache for permutations. - vec := NewUntypedVec( - UntypedOpts{ - Name: "test", - Help: "helpless", - }, - keys, - ) - - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - // Varies input across provide map entries based on key size. - for j, k := range keys { - candidates := labels[k] - values[j] = candidates[i%len(candidates)] - } - - vec.WithLabelValues(values...) - } -} diff --git a/vendor/github.com/prometheus/client_model/Makefile b/vendor/github.com/prometheus/client_model/Makefile index 9cc23b3408..e147c69dac 100644 --- a/vendor/github.com/prometheus/client_model/Makefile +++ b/vendor/github.com/prometheus/client_model/Makefile @@ -39,6 +39,7 @@ src/main/java/io/prometheus/client/Metrics.java: metrics.proto python: python/prometheus/client/model/metrics_pb2.py python/prometheus/client/model/metrics_pb2.py: metrics.proto + mkdir -p python/prometheus/client/model protoc $< --python_out=python/prometheus/client/model ruby: diff --git a/vendor/github.com/prometheus/common/README.md b/vendor/github.com/prometheus/common/README.md index 11a584945d..47985e4ad2 100644 --- a/vendor/github.com/prometheus/common/README.md +++ b/vendor/github.com/prometheus/common/README.md @@ -9,4 +9,4 @@ components and libraries. * **log**: A logging wrapper around [logrus](https://github.com/sirupsen/logrus) * **model**: Shared data structures * **route**: A routing wrapper around [httprouter](https://github.com/julienschmidt/httprouter) using `context.Context` -* **version**: Version informations and metric +* **version**: Version information and metrics diff --git a/vendor/github.com/prometheus/common/expfmt/bench_test.go b/vendor/github.com/prometheus/common/expfmt/bench_test.go deleted file mode 100644 index e539bfc13a..0000000000 --- a/vendor/github.com/prometheus/common/expfmt/bench_test.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2015 The Prometheus 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 expfmt - -import ( - "bytes" - "compress/gzip" - "io" - "io/ioutil" - "testing" - - "github.com/matttproud/golang_protobuf_extensions/pbutil" - - dto "github.com/prometheus/client_model/go" -) - -var parser TextParser - -// Benchmarks to show how much penalty text format parsing actually inflicts. -// -// Example results on Linux 3.13.0, Intel(R) Core(TM) i7-4700MQ CPU @ 2.40GHz, go1.4. -// -// BenchmarkParseText 1000 1188535 ns/op 205085 B/op 6135 allocs/op -// BenchmarkParseTextGzip 1000 1376567 ns/op 246224 B/op 6151 allocs/op -// BenchmarkParseProto 10000 172790 ns/op 52258 B/op 1160 allocs/op -// BenchmarkParseProtoGzip 5000 324021 ns/op 94931 B/op 1211 allocs/op -// BenchmarkParseProtoMap 10000 187946 ns/op 58714 B/op 1203 allocs/op -// -// CONCLUSION: The overhead for the map is negligible. Text format needs ~5x more allocations. -// Without compression, it needs ~7x longer, but with compression (the more relevant scenario), -// the difference becomes less relevant, only ~4x. -// -// The test data contains 248 samples. - -// BenchmarkParseText benchmarks the parsing of a text-format scrape into metric -// family DTOs. -func BenchmarkParseText(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/text") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - if _, err := parser.TextToMetricFamilies(bytes.NewReader(data)); err != nil { - b.Fatal(err) - } - } -} - -// BenchmarkParseTextGzip benchmarks the parsing of a gzipped text-format scrape -// into metric family DTOs. -func BenchmarkParseTextGzip(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/text.gz") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - in, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - b.Fatal(err) - } - if _, err := parser.TextToMetricFamilies(in); err != nil { - b.Fatal(err) - } - } -} - -// BenchmarkParseProto benchmarks the parsing of a protobuf-format scrape into -// metric family DTOs. Note that this does not build a map of metric families -// (as the text version does), because it is not required for Prometheus -// ingestion either. (However, it is required for the text-format parsing, as -// the metric family might be sprinkled all over the text, while the -// protobuf-format guarantees bundling at one place.) -func BenchmarkParseProto(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - family := &dto.MetricFamily{} - in := bytes.NewReader(data) - for { - family.Reset() - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } - } -} - -// BenchmarkParseProtoGzip is like BenchmarkParseProto above, but parses gzipped -// protobuf format. -func BenchmarkParseProtoGzip(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf.gz") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - family := &dto.MetricFamily{} - in, err := gzip.NewReader(bytes.NewReader(data)) - if err != nil { - b.Fatal(err) - } - for { - family.Reset() - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - } - } -} - -// BenchmarkParseProtoMap is like BenchmarkParseProto but DOES put the parsed -// metric family DTOs into a map. This is not happening during Prometheus -// ingestion. It is just here to measure the overhead of that map creation and -// separate it from the overhead of the text format parsing. -func BenchmarkParseProtoMap(b *testing.B) { - b.StopTimer() - data, err := ioutil.ReadFile("testdata/protobuf") - if err != nil { - b.Fatal(err) - } - b.StartTimer() - - for i := 0; i < b.N; i++ { - families := map[string]*dto.MetricFamily{} - in := bytes.NewReader(data) - for { - family := &dto.MetricFamily{} - if _, err := pbutil.ReadDelimited(in, family); err != nil { - if err == io.EOF { - break - } - b.Fatal(err) - } - families[family.GetName()] = family - } - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go index a7a42d5ef4..c092723e84 100644 --- a/vendor/github.com/prometheus/common/expfmt/decode.go +++ b/vendor/github.com/prometheus/common/expfmt/decode.go @@ -164,9 +164,9 @@ func (sd *SampleDecoder) Decode(s *model.Vector) error { } // ExtractSamples builds a slice of samples from the provided metric -// families. If an error occurs during sample extraction, it continues to +// families. If an error occurrs during sample extraction, it continues to // extract from the remaining metric families. The returned error is the last -// error that has occured. +// error that has occurred. func ExtractSamples(o *DecodeOptions, fams ...*dto.MetricFamily) (model.Vector, error) { var ( all model.Vector diff --git a/vendor/github.com/prometheus/common/expfmt/decode_test.go b/vendor/github.com/prometheus/common/expfmt/decode_test.go deleted file mode 100644 index 82c1130c9d..0000000000 --- a/vendor/github.com/prometheus/common/expfmt/decode_test.go +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright 2015 The Prometheus 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 expfmt - -import ( - "io" - "net/http" - "reflect" - "sort" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" - - "github.com/prometheus/common/model" -) - -func TestTextDecoder(t *testing.T) { - var ( - ts = model.Now() - in = ` -# Only a quite simple scenario with two metric families. -# More complicated tests of the parser itself can be found in the text package. -# TYPE mf2 counter -mf2 3 -mf1{label="value1"} -3.14 123456 -mf1{label="value2"} 42 -mf2 4 -` - out = model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf1", - "label": "value1", - }, - Value: -3.14, - Timestamp: 123456, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf1", - "label": "value2", - }, - Value: 42, - Timestamp: ts, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf2", - }, - Value: 3, - Timestamp: ts, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "mf2", - }, - Value: 4, - Timestamp: ts, - }, - } - ) - - dec := &SampleDecoder{ - Dec: &textDecoder{r: strings.NewReader(in)}, - Opts: &DecodeOptions{ - Timestamp: ts, - }, - } - var all model.Vector - for { - var smpls model.Vector - err := dec.Decode(&smpls) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - all = append(all, smpls...) - } - sort.Sort(all) - sort.Sort(out) - if !reflect.DeepEqual(all, out) { - t.Fatalf("output does not match") - } -} - -func TestProtoDecoder(t *testing.T) { - - var testTime = model.Now() - - scenarios := []struct { - in string - expected model.Vector - fail bool - }{ - { - in: "", - }, - { - in: "\x8f\x01\n\rrequest_count\x12\x12Number of requests\x18\x00\"0\n#\n\x0fsome_!abel_name\x12\x10some_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00E\xc0\"6\n)\n\x12another_label_name\x12\x13another_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00U@", - fail: true, - }, - { - in: "\x8f\x01\n\rrequest_count\x12\x12Number of requests\x18\x00\"0\n#\n\x0fsome_label_name\x12\x10some_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00E\xc0\"6\n)\n\x12another_label_name\x12\x13another_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00U@", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - }, - Value: -42, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "another_label_name": "another_label_value", - }, - Value: 84, - Timestamp: testTime, - }, - }, - }, - { - in: "\xb9\x01\n\rrequest_count\x12\x12Number of requests\x18\x02\"O\n#\n\x0fsome_label_name\x12\x10some_label_value\"(\x1a\x12\t\xaeG\xe1z\x14\xae\xef?\x11\x00\x00\x00\x00\x00\x00E\xc0\x1a\x12\t+\x87\x16\xd9\xce\xf7\xef?\x11\x00\x00\x00\x00\x00\x00U\xc0\"A\n)\n\x12another_label_name\x12\x13another_label_value\"\x14\x1a\x12\t\x00\x00\x00\x00\x00\x00\xe0?\x11\x00\x00\x00\x00\x00\x00$@", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_count", - "some_label_name": "some_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_sum", - "some_label_name": "some_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - "quantile": "0.99", - }, - Value: -42, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "some_label_name": "some_label_value", - "quantile": "0.999", - }, - Value: -84, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_count", - "another_label_name": "another_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count_sum", - "another_label_name": "another_label_value", - }, - Value: 0, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - "another_label_name": "another_label_value", - "quantile": "0.5", - }, - Value: 10, - Timestamp: testTime, - }, - }, - }, - { - in: "\x8d\x01\n\x1drequest_duration_microseconds\x12\x15The response latency.\x18\x04\"S:Q\b\x85\x15\x11\xcd\xcc\xccL\x8f\xcb:A\x1a\v\b{\x11\x00\x00\x00\x00\x00\x00Y@\x1a\f\b\x9c\x03\x11\x00\x00\x00\x00\x00\x00^@\x1a\f\b\xd0\x04\x11\x00\x00\x00\x00\x00\x00b@\x1a\f\b\xf4\v\x11\x9a\x99\x99\x99\x99\x99e@\x1a\f\b\x85\x15\x11\x00\x00\x00\x00\x00\x00\xf0\u007f", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "100", - }, - Value: 123, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "120", - }, - Value: 412, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "144", - }, - Value: 592, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "172.8", - }, - Value: 1524, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_bucket", - "le": "+Inf", - }, - Value: 2693, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_sum", - }, - Value: 1756047.3, - Timestamp: testTime, - }, - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_duration_microseconds_count", - }, - Value: 2693, - Timestamp: testTime, - }, - }, - }, - { - // The metric type is unset in this protobuf, which needs to be handled - // correctly by the decoder. - in: "\x1c\n\rrequest_count\"\v\x1a\t\t\x00\x00\x00\x00\x00\x00\xf0?", - expected: model.Vector{ - &model.Sample{ - Metric: model.Metric{ - model.MetricNameLabel: "request_count", - }, - Value: 1, - Timestamp: testTime, - }, - }, - }, - } - - for i, scenario := range scenarios { - dec := &SampleDecoder{ - Dec: &protoDecoder{r: strings.NewReader(scenario.in)}, - Opts: &DecodeOptions{ - Timestamp: testTime, - }, - } - - var all model.Vector - for { - var smpls model.Vector - err := dec.Decode(&smpls) - if err == io.EOF { - break - } - if scenario.fail { - if err == nil { - t.Fatal("Expected error but got none") - } - break - } - if err != nil { - t.Fatal(err) - } - all = append(all, smpls...) - } - sort.Sort(all) - sort.Sort(scenario.expected) - if !reflect.DeepEqual(all, scenario.expected) { - t.Fatalf("%d. output does not match, want: %#v, got %#v", i, scenario.expected, all) - } - } -} - -func testDiscriminatorHTTPHeader(t testing.TB) { - var scenarios = []struct { - input map[string]string - output Format - err error - }{ - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="delimited"`}, - output: FmtProtoDelim, - }, - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="illegal"; encoding="delimited"`}, - output: FmtUnknown, - }, - { - input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="illegal"`}, - output: FmtUnknown, - }, - { - input: map[string]string{"Content-Type": `text/plain; version=0.0.4`}, - output: FmtText, - }, - { - input: map[string]string{"Content-Type": `text/plain`}, - output: FmtText, - }, - { - input: map[string]string{"Content-Type": `text/plain; version=0.0.3`}, - output: FmtUnknown, - }, - } - - for i, scenario := range scenarios { - var header http.Header - - if len(scenario.input) > 0 { - header = http.Header{} - } - - for key, value := range scenario.input { - header.Add(key, value) - } - - actual := ResponseFormat(header) - - if scenario.output != actual { - t.Errorf("%d. expected %s, got %s", i, scenario.output, actual) - } - } -} - -func TestDiscriminatorHTTPHeader(t *testing.T) { - testDiscriminatorHTTPHeader(t) -} - -func BenchmarkDiscriminatorHTTPHeader(b *testing.B) { - for i := 0; i < b.N; i++ { - testDiscriminatorHTTPHeader(b) - } -} - -func TestExtractSamples(t *testing.T) { - var ( - goodMetricFamily1 = &dto.MetricFamily{ - Name: proto.String("foo"), - Help: proto.String("Help for foo."), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Counter: &dto.Counter{ - Value: proto.Float64(4711), - }, - }, - }, - } - goodMetricFamily2 = &dto.MetricFamily{ - Name: proto.String("bar"), - Help: proto.String("Help for bar."), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Gauge: &dto.Gauge{ - Value: proto.Float64(3.14), - }, - }, - }, - } - badMetricFamily = &dto.MetricFamily{ - Name: proto.String("bad"), - Help: proto.String("Help for bad."), - Type: dto.MetricType(42).Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Gauge: &dto.Gauge{ - Value: proto.Float64(2.7), - }, - }, - }, - } - - opts = &DecodeOptions{ - Timestamp: 42, - } - ) - - got, err := ExtractSamples(opts, goodMetricFamily1, goodMetricFamily2) - if err != nil { - t.Error("Unexpected error from ExtractSamples:", err) - } - want := model.Vector{ - &model.Sample{Metric: model.Metric{model.MetricNameLabel: "foo"}, Value: 4711, Timestamp: 42}, - &model.Sample{Metric: model.Metric{model.MetricNameLabel: "bar"}, Value: 3.14, Timestamp: 42}, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("unexpected samples extracted, got: %v, want: %v", got, want) - } - - got, err = ExtractSamples(opts, goodMetricFamily1, badMetricFamily, goodMetricFamily2) - if err == nil { - t.Error("Expected error from ExtractSamples") - } - if !reflect.DeepEqual(got, want) { - t.Errorf("unexpected samples extracted, got: %v, want: %v", got, want) - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/expfmt.go b/vendor/github.com/prometheus/common/expfmt/expfmt.go index 371ac75037..c71bcb9816 100644 --- a/vendor/github.com/prometheus/common/expfmt/expfmt.go +++ b/vendor/github.com/prometheus/common/expfmt/expfmt.go @@ -26,7 +26,7 @@ const ( // The Content-Type values for the different wire protocols. FmtUnknown Format = `` - FmtText Format = `text/plain; version=` + TextVersion + FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8` FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` FmtProtoText Format = ProtoFmt + ` encoding=text` FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text` diff --git a/vendor/github.com/prometheus/common/expfmt/text_create_test.go b/vendor/github.com/prometheus/common/expfmt/text_create_test.go deleted file mode 100644 index e4cc5d803b..0000000000 --- a/vendor/github.com/prometheus/common/expfmt/text_create_test.go +++ /dev/null @@ -1,443 +0,0 @@ -// Copyright 2014 The Prometheus 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 expfmt - -import ( - "bytes" - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - - dto "github.com/prometheus/client_model/go" -) - -func testCreate(t testing.TB) { - var scenarios = []struct { - in *dto.MetricFamily - out string - }{ - // 0: Counter, NaN as value, timestamp given. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("two-line\n doc str\\ing"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(math.NaN()), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(.23), - }, - TimestampMs: proto.Int64(1234567890), - }, - }, - }, - out: `# HELP name two-line\n doc str\\ing -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name{labelname="val2",basename="basevalue"} 0.23 1234567890 -`, - }, - // 1: Gauge, some escaping required, +Inf as value, multi-byte characters in label values. - { - in: &dto.MetricFamily{ - Name: proto.String("gauge_name"), - Help: proto.String("gauge\ndoc\nstr\"ing"), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("val with\nnew line"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("val with \\backslash and \"quotes\""), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(+1)), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("Björn"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("佖佥"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(3.14E42), - }, - }, - }, - }, - out: `# HELP gauge_name gauge\ndoc\nstr"ing -# TYPE gauge_name gauge -gauge_name{name_1="val with\nnew line",name_2="val with \\backslash and \"quotes\""} +Inf -gauge_name{name_1="Björn",name_2="佖佥"} 3.14e+42 -`, - }, - // 2: Untyped, no help, one sample with no labels and -Inf as value, another sample with one label. - { - in: &dto.MetricFamily{ - Name: proto.String("untyped_name"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("value 1"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(-1.23e-45), - }, - }, - }, - }, - out: `# TYPE untyped_name untyped -untyped_name -Inf -untyped_name{name_1="value 1"} -1.23e-45 -`, - }, - // 3: Summary. - { - in: &dto.MetricFamily{ - Name: proto.String("summary_name"), - Help: proto.String("summary docstring"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Summary: &dto.Summary{ - SampleCount: proto.Uint64(42), - SampleSum: proto.Float64(-3.4567), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(-1.23), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(.2342354), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.99), - Value: proto.Float64(0), - }, - }, - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("name_1"), - Value: proto.String("value 1"), - }, - &dto.LabelPair{ - Name: proto.String("name_2"), - Value: proto.String("value 2"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(4711), - SampleSum: proto.Float64(2010.1971), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(1), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(2), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.99), - Value: proto.Float64(3), - }, - }, - }, - }, - }, - }, - out: `# HELP summary_name summary docstring -# TYPE summary_name summary -summary_name{quantile="0.5"} -1.23 -summary_name{quantile="0.9"} 0.2342354 -summary_name{quantile="0.99"} 0 -summary_name_sum -3.4567 -summary_name_count 42 -summary_name{name_1="value 1",name_2="value 2",quantile="0.5"} 1 -summary_name{name_1="value 1",name_2="value 2",quantile="0.9"} 2 -summary_name{name_1="value 1",name_2="value 2",quantile="0.99"} 3 -summary_name_sum{name_1="value 1",name_2="value 2"} 2010.1971 -summary_name_count{name_1="value 1",name_2="value 2"} 4711 -`, - }, - // 4: Histogram - { - in: &dto.MetricFamily{ - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - &dto.Bucket{ - UpperBound: proto.Float64(math.Inf(+1)), - CumulativeCount: proto.Uint64(2693), - }, - }, - }, - }, - }, - }, - out: `# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - }, - // 5: Histogram with missing +Inf bucket. - { - in: &dto.MetricFamily{ - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - }, - }, - }, - }, - }, - out: `# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - }, - // 6: No metric type, should result in default type Counter. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Metric: []*dto.Metric{ - &dto.Metric{ - Counter: &dto.Counter{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - out: `# HELP name doc string -# TYPE name counter -name -Inf -`, - }, - } - - for i, scenario := range scenarios { - out := bytes.NewBuffer(make([]byte, 0, len(scenario.out))) - n, err := MetricFamilyToText(out, scenario.in) - if err != nil { - t.Errorf("%d. error: %s", i, err) - continue - } - if expected, got := len(scenario.out), n; expected != got { - t.Errorf( - "%d. expected %d bytes written, got %d", - i, expected, got, - ) - } - if expected, got := scenario.out, out.String(); expected != got { - t.Errorf( - "%d. expected out=%q, got %q", - i, expected, got, - ) - } - } - -} - -func TestCreate(t *testing.T) { - testCreate(t) -} - -func BenchmarkCreate(b *testing.B) { - for i := 0; i < b.N; i++ { - testCreate(b) - } -} - -func testCreateError(t testing.TB) { - var scenarios = []struct { - in *dto.MetricFamily - err string - }{ - // 0: No metric. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{}, - }, - err: "MetricFamily has no metrics", - }, - // 1: No metric name. - { - in: &dto.MetricFamily{ - Help: proto.String("doc string"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - err: "MetricFamily has no name", - }, - // 2: Wrong type. - { - in: &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("doc string"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - err: "expected counter in metric", - }, - } - - for i, scenario := range scenarios { - var out bytes.Buffer - _, err := MetricFamilyToText(&out, scenario.in) - if err == nil { - t.Errorf("%d. expected error, got nil", i) - continue - } - if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { - t.Errorf( - "%d. expected error starting with %q, got %q", - i, expected, got, - ) - } - } - -} - -func TestCreateError(t *testing.T) { - testCreateError(t) -} - -func BenchmarkCreateError(b *testing.B) { - for i := 0; i < b.N; i++ { - testCreateError(b) - } -} diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse.go b/vendor/github.com/prometheus/common/expfmt/text_parse.go index 54bcfde294..b86290afa3 100644 --- a/vendor/github.com/prometheus/common/expfmt/text_parse.go +++ b/vendor/github.com/prometheus/common/expfmt/text_parse.go @@ -556,8 +556,8 @@ func (p *TextParser) readTokenUntilWhitespace() { // byte considered is the byte already read (now in p.currentByte). The first // newline byte encountered is still copied into p.currentByte, but not into // p.currentToken. If recognizeEscapeSequence is true, two escape sequences are -// recognized: '\\' tranlates into '\', and '\n' into a line-feed character. All -// other escape sequences are invalid and cause an error. +// recognized: '\\' translates into '\', and '\n' into a line-feed character. +// All other escape sequences are invalid and cause an error. func (p *TextParser) readTokenUntilNewline(recognizeEscapeSequence bool) { p.currentToken.Reset() escaped := false diff --git a/vendor/github.com/prometheus/common/expfmt/text_parse_test.go b/vendor/github.com/prometheus/common/expfmt/text_parse_test.go deleted file mode 100644 index 76c9511853..0000000000 --- a/vendor/github.com/prometheus/common/expfmt/text_parse_test.go +++ /dev/null @@ -1,593 +0,0 @@ -// Copyright 2014 The Prometheus 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 expfmt - -import ( - "math" - "strings" - "testing" - - "github.com/golang/protobuf/proto" - dto "github.com/prometheus/client_model/go" -) - -func testTextParse(t testing.TB) { - var scenarios = []struct { - in string - out []*dto.MetricFamily - }{ - // 0: Empty lines as input. - { - in: ` - -`, - out: []*dto.MetricFamily{}, - }, - // 1: Minimal case. - { - in: ` -minimal_metric 1.234 -another_metric -3e3 103948 -# Even that: -no_labels{} 3 -# HELP line for non-existing metric will be ignored. -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("minimal_metric"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(1.234), - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("another_metric"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(-3e3), - }, - TimestampMs: proto.Int64(103948), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("no_labels"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(3), - }, - }, - }, - }, - }, - }, - // 2: Counters & gauges, docstrings, various whitespace, escape sequences. - { - in: ` -# A normal comment. -# -# TYPE name counter -name{labelname="val1",basename="basevalue"} NaN -name {labelname="val2",basename="base\"v\\al\nue"} 0.23 1234567890 -# HELP name two-line\n doc str\\ing - - # HELP name2 doc str"ing 2 - # TYPE name2 gauge -name2{labelname="val2" ,basename = "basevalue2" } +Inf 54321 -name2{ labelname = "val1" , }-Inf -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("name"), - Help: proto.String("two-line\n doc str\\ing"), - Type: dto.MetricType_COUNTER.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(math.NaN()), - }, - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("base\"v\\al\nue"), - }, - }, - Counter: &dto.Counter{ - Value: proto.Float64(.23), - }, - TimestampMs: proto.Int64(1234567890), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("name2"), - Help: proto.String("doc str\"ing 2"), - Type: dto.MetricType_GAUGE.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("basename"), - Value: proto.String("basevalue2"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(+1)), - }, - TimestampMs: proto.Int64(54321), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("labelname"), - Value: proto.String("val1"), - }, - }, - Gauge: &dto.Gauge{ - Value: proto.Float64(math.Inf(-1)), - }, - }, - }, - }, - }, - }, - // 3: The evil summary, mixed with other types and funny comments. - { - in: ` -# TYPE my_summary summary -my_summary{n1="val1",quantile="0.5"} 110 -decoy -1 -2 -my_summary{n1="val1",quantile="0.9"} 140 1 -my_summary_count{n1="val1"} 42 -# Latest timestamp wins in case of a summary. -my_summary_sum{n1="val1"} 4711 2 -fake_sum{n1="val1"} 2001 -# TYPE another_summary summary -another_summary_count{n2="val2",n1="val1"} 20 -my_summary_count{n2="val2",n1="val1"} 5 5 -another_summary{n1="val1",n2="val2",quantile=".3"} -1.2 -my_summary_sum{n1="val2"} 08 15 -my_summary{n1="val3", quantile="0.2"} 4711 - my_summary{n1="val1",n2="val2",quantile="-12.34",} NaN -# some -# funny comments -# HELP -# HELP -# HELP my_summary -# HELP my_summary -`, - out: []*dto.MetricFamily{ - &dto.MetricFamily{ - Name: proto.String("fake_sum"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Untyped: &dto.Untyped{ - Value: proto.Float64(2001), - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("decoy"), - Type: dto.MetricType_UNTYPED.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Untyped: &dto.Untyped{ - Value: proto.Float64(-1), - }, - TimestampMs: proto.Int64(-2), - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("my_summary"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(42), - SampleSum: proto.Float64(4711), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.5), - Value: proto.Float64(110), - }, - &dto.Quantile{ - Quantile: proto.Float64(0.9), - Value: proto.Float64(140), - }, - }, - }, - TimestampMs: proto.Int64(2), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n2"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(5), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(-12.34), - Value: proto.Float64(math.NaN()), - }, - }, - }, - TimestampMs: proto.Int64(5), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val2"), - }, - }, - Summary: &dto.Summary{ - SampleSum: proto.Float64(8), - }, - TimestampMs: proto.Int64(15), - }, - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val3"), - }, - }, - Summary: &dto.Summary{ - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.2), - Value: proto.Float64(4711), - }, - }, - }, - }, - }, - }, - &dto.MetricFamily{ - Name: proto.String("another_summary"), - Type: dto.MetricType_SUMMARY.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Label: []*dto.LabelPair{ - &dto.LabelPair{ - Name: proto.String("n2"), - Value: proto.String("val2"), - }, - &dto.LabelPair{ - Name: proto.String("n1"), - Value: proto.String("val1"), - }, - }, - Summary: &dto.Summary{ - SampleCount: proto.Uint64(20), - Quantile: []*dto.Quantile{ - &dto.Quantile{ - Quantile: proto.Float64(0.3), - Value: proto.Float64(-1.2), - }, - }, - }, - }, - }, - }, - }, - }, - // 4: The histogram. - { - in: ` -# HELP request_duration_microseconds The response latency. -# TYPE request_duration_microseconds histogram -request_duration_microseconds_bucket{le="100"} 123 -request_duration_microseconds_bucket{le="120"} 412 -request_duration_microseconds_bucket{le="144"} 592 -request_duration_microseconds_bucket{le="172.8"} 1524 -request_duration_microseconds_bucket{le="+Inf"} 2693 -request_duration_microseconds_sum 1.7560473e+06 -request_duration_microseconds_count 2693 -`, - out: []*dto.MetricFamily{ - { - Name: proto.String("request_duration_microseconds"), - Help: proto.String("The response latency."), - Type: dto.MetricType_HISTOGRAM.Enum(), - Metric: []*dto.Metric{ - &dto.Metric{ - Histogram: &dto.Histogram{ - SampleCount: proto.Uint64(2693), - SampleSum: proto.Float64(1756047.3), - Bucket: []*dto.Bucket{ - &dto.Bucket{ - UpperBound: proto.Float64(100), - CumulativeCount: proto.Uint64(123), - }, - &dto.Bucket{ - UpperBound: proto.Float64(120), - CumulativeCount: proto.Uint64(412), - }, - &dto.Bucket{ - UpperBound: proto.Float64(144), - CumulativeCount: proto.Uint64(592), - }, - &dto.Bucket{ - UpperBound: proto.Float64(172.8), - CumulativeCount: proto.Uint64(1524), - }, - &dto.Bucket{ - UpperBound: proto.Float64(math.Inf(+1)), - CumulativeCount: proto.Uint64(2693), - }, - }, - }, - }, - }, - }, - }, - }, - } - - for i, scenario := range scenarios { - out, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) - if err != nil { - t.Errorf("%d. error: %s", i, err) - continue - } - if expected, got := len(scenario.out), len(out); expected != got { - t.Errorf( - "%d. expected %d MetricFamilies, got %d", - i, expected, got, - ) - } - for _, expected := range scenario.out { - got, ok := out[expected.GetName()] - if !ok { - t.Errorf( - "%d. expected MetricFamily %q, found none", - i, expected.GetName(), - ) - continue - } - if expected.String() != got.String() { - t.Errorf( - "%d. expected MetricFamily %s, got %s", - i, expected, got, - ) - } - } - } -} - -func TestTextParse(t *testing.T) { - testTextParse(t) -} - -func BenchmarkTextParse(b *testing.B) { - for i := 0; i < b.N; i++ { - testTextParse(b) - } -} - -func testTextParseError(t testing.TB) { - var scenarios = []struct { - in string - err string - }{ - // 0: No new-line at end of input. - { - in: ` -bla 3.14 -blubber 42`, - err: "text format parsing error in line 3: unexpected end of input stream", - }, - // 1: Invalid escape sequence in label value. - { - in: `metric{label="\t"} 3.14`, - err: "text format parsing error in line 1: invalid escape sequence", - }, - // 2: Newline in label value. - { - in: ` -metric{label="new -line"} 3.14 -`, - err: `text format parsing error in line 2: label value "new" contains unescaped new-line`, - }, - // 3: - { - in: `metric{@="bla"} 3.14`, - err: "text format parsing error in line 1: invalid label name for metric", - }, - // 4: - { - in: `metric{__name__="bla"} 3.14`, - err: `text format parsing error in line 1: label name "__name__" is reserved`, - }, - // 5: - { - in: `metric{label+="bla"} 3.14`, - err: "text format parsing error in line 1: expected '=' after label name", - }, - // 6: - { - in: `metric{label=bla} 3.14`, - err: "text format parsing error in line 1: expected '\"' at start of label value", - }, - // 7: - { - in: ` -# TYPE metric summary -metric{quantile="bla"} 3.14 -`, - err: "text format parsing error in line 3: expected float as value for 'quantile' label", - }, - // 8: - { - in: `metric{label="bla"+} 3.14`, - err: "text format parsing error in line 1: unexpected end of label value", - }, - // 9: - { - in: `metric{label="bla"} 3.14 2.72 -`, - err: "text format parsing error in line 1: expected integer as timestamp", - }, - // 10: - { - in: `metric{label="bla"} 3.14 2 3 -`, - err: "text format parsing error in line 1: spurious string after timestamp", - }, - // 11: - { - in: `metric{label="bla"} blubb -`, - err: "text format parsing error in line 1: expected float as value", - }, - // 12: - { - in: ` -# HELP metric one -# HELP metric two -`, - err: "text format parsing error in line 3: second HELP line for metric name", - }, - // 13: - { - in: ` -# TYPE metric counter -# TYPE metric untyped -`, - err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, - }, - // 14: - { - in: ` -metric 4.12 -# TYPE metric counter -`, - err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, - }, - // 14: - { - in: ` -# TYPE metric bla -`, - err: "text format parsing error in line 2: unknown metric type", - }, - // 15: - { - in: ` -# TYPE met-ric -`, - err: "text format parsing error in line 2: invalid metric name in comment", - }, - // 16: - { - in: `@invalidmetric{label="bla"} 3.14 2`, - err: "text format parsing error in line 1: invalid metric name", - }, - // 17: - { - in: `{label="bla"} 3.14 2`, - err: "text format parsing error in line 1: invalid metric name", - }, - // 18: - { - in: ` -# TYPE metric histogram -metric_bucket{le="bla"} 3.14 -`, - err: "text format parsing error in line 3: expected float as value for 'le' label", - }, - // 19: Invalid UTF-8 in label value. - { - in: "metric{l=\"\xbd\"} 3.14\n", - err: "text format parsing error in line 1: invalid label value \"\\xbd\"", - }, - } - - for i, scenario := range scenarios { - _, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) - if err == nil { - t.Errorf("%d. expected error, got nil", i) - continue - } - if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { - t.Errorf( - "%d. expected error starting with %q, got %q", - i, expected, got, - ) - } - } - -} - -func TestTextParseError(t *testing.T) { - testTextParseError(t) -} - -func BenchmarkParseError(b *testing.B) { - for i := 0; i < b.N; i++ { - testTextParseError(b) - } -} diff --git a/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go deleted file mode 100644 index 41d328f1d5..0000000000 --- a/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package goautoneg - -import ( - "testing" -) - -var chrome = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" - -func TestParseAccept(t *testing.T) { - alternatives := []string{"text/html", "image/png"} - content_type := Negotiate(chrome, alternatives) - if content_type != "image/png" { - t.Errorf("got %s expected image/png", content_type) - } - - alternatives = []string{"text/html", "text/plain", "text/n3"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/html" { - t.Errorf("got %s expected text/html", content_type) - } - - alternatives = []string{"text/n3", "text/plain"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/plain" { - t.Errorf("got %s expected text/plain", content_type) - } - - alternatives = []string{"text/n3", "application/rdf+xml"} - content_type = Negotiate(chrome, alternatives) - if content_type != "text/n3" { - t.Errorf("got %s expected text/n3", content_type) - } -} diff --git a/vendor/github.com/prometheus/common/model/alert_test.go b/vendor/github.com/prometheus/common/model/alert_test.go deleted file mode 100644 index 9692bca210..0000000000 --- a/vendor/github.com/prometheus/common/model/alert_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2013 The Prometheus 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 model - -import ( - "strings" - "testing" - "time" -) - -func TestAlertValidate(t *testing.T) { - ts := time.Now() - - var cases = []struct { - alert *Alert - err string - }{ - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - StartsAt: ts, - }, - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - }, - err: "start time missing", - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - StartsAt: ts, - EndsAt: ts, - }, - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - StartsAt: ts, - EndsAt: ts.Add(1 * time.Minute), - }, - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - StartsAt: ts, - EndsAt: ts.Add(-1 * time.Minute), - }, - err: "start time must be before end time", - }, - { - alert: &Alert{ - StartsAt: ts, - }, - err: "at least one label pair required", - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b", "!bad": "label"}, - StartsAt: ts, - }, - err: "invalid label set: invalid name", - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b", "bad": "\xfflabel"}, - StartsAt: ts, - }, - err: "invalid label set: invalid value", - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - Annotations: LabelSet{"!bad": "label"}, - StartsAt: ts, - }, - err: "invalid annotations: invalid name", - }, - { - alert: &Alert{ - Labels: LabelSet{"a": "b"}, - Annotations: LabelSet{"bad": "\xfflabel"}, - StartsAt: ts, - }, - err: "invalid annotations: invalid value", - }, - } - - for i, c := range cases { - err := c.alert.Validate() - if err == nil { - if c.err == "" { - continue - } - t.Errorf("%d. Expected error %q but got none", i, c.err) - continue - } - if c.err == "" && err != nil { - t.Errorf("%d. Expected no error but got %q", i, err) - continue - } - if !strings.Contains(err.Error(), c.err) { - t.Errorf("%d. Expected error to contain %q but got %q", i, c.err, err) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/labels_test.go b/vendor/github.com/prometheus/common/model/labels_test.go deleted file mode 100644 index e8df28ffac..0000000000 --- a/vendor/github.com/prometheus/common/model/labels_test.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2013 The Prometheus 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 model - -import ( - "sort" - "testing" -) - -func testLabelNames(t testing.TB) { - var scenarios = []struct { - in LabelNames - out LabelNames - }{ - { - in: LabelNames{"ZZZ", "zzz"}, - out: LabelNames{"ZZZ", "zzz"}, - }, - { - in: LabelNames{"aaa", "AAA"}, - out: LabelNames{"AAA", "aaa"}, - }, - } - - for i, scenario := range scenarios { - sort.Sort(scenario.in) - - for j, expected := range scenario.out { - if expected != scenario.in[j] { - t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) - } - } - } -} - -func TestLabelNames(t *testing.T) { - testLabelNames(t) -} - -func BenchmarkLabelNames(b *testing.B) { - for i := 0; i < b.N; i++ { - testLabelNames(b) - } -} - -func testLabelValues(t testing.TB) { - var scenarios = []struct { - in LabelValues - out LabelValues - }{ - { - in: LabelValues{"ZZZ", "zzz"}, - out: LabelValues{"ZZZ", "zzz"}, - }, - { - in: LabelValues{"aaa", "AAA"}, - out: LabelValues{"AAA", "aaa"}, - }, - } - - for i, scenario := range scenarios { - sort.Sort(scenario.in) - - for j, expected := range scenario.out { - if expected != scenario.in[j] { - t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) - } - } - } -} - -func TestLabelValues(t *testing.T) { - testLabelValues(t) -} - -func BenchmarkLabelValues(b *testing.B) { - for i := 0; i < b.N; i++ { - testLabelValues(b) - } -} - -func TestLabelNameIsValid(t *testing.T) { - var scenarios = []struct { - ln LabelName - valid bool - }{ - { - ln: "Avalid_23name", - valid: true, - }, - { - ln: "_Avalid_23name", - valid: true, - }, - { - ln: "1valid_23name", - valid: false, - }, - { - ln: "avalid_23name", - valid: true, - }, - { - ln: "Ava:lid_23name", - valid: false, - }, - { - ln: "a lid_23name", - valid: false, - }, - { - ln: ":leading_colon", - valid: false, - }, - { - ln: "colon:in:the:middle", - valid: false, - }, - } - - for _, s := range scenarios { - if s.ln.IsValid() != s.valid { - t.Errorf("Expected %v for %q using IsValid method", s.valid, s.ln) - } - if LabelNameRE.MatchString(string(s.ln)) != s.valid { - t.Errorf("Expected %v for %q using regexp match", s.valid, s.ln) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/metric_test.go b/vendor/github.com/prometheus/common/model/metric_test.go deleted file mode 100644 index 06f9de525a..0000000000 --- a/vendor/github.com/prometheus/common/model/metric_test.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2013 The Prometheus 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 model - -import "testing" - -func testMetric(t testing.TB) { - var scenarios = []struct { - input LabelSet - fingerprint Fingerprint - fastFingerprint Fingerprint - }{ - { - input: LabelSet{}, - fingerprint: 14695981039346656037, - fastFingerprint: 14695981039346656037, - }, - { - input: LabelSet{ - "first_name": "electro", - "occupation": "robot", - "manufacturer": "westinghouse", - }, - fingerprint: 5911716720268894962, - fastFingerprint: 11310079640881077873, - }, - { - input: LabelSet{ - "x": "y", - }, - fingerprint: 8241431561484471700, - fastFingerprint: 13948396922932177635, - }, - { - input: LabelSet{ - "a": "bb", - "b": "c", - }, - fingerprint: 3016285359649981711, - fastFingerprint: 3198632812309449502, - }, - { - input: LabelSet{ - "a": "b", - "bb": "c", - }, - fingerprint: 7122421792099404749, - fastFingerprint: 5774953389407657638, - }, - } - - for i, scenario := range scenarios { - input := Metric(scenario.input) - - if scenario.fingerprint != input.Fingerprint() { - t.Errorf("%d. expected %d, got %d", i, scenario.fingerprint, input.Fingerprint()) - } - if scenario.fastFingerprint != input.FastFingerprint() { - t.Errorf("%d. expected %d, got %d", i, scenario.fastFingerprint, input.FastFingerprint()) - } - } -} - -func TestMetric(t *testing.T) { - testMetric(t) -} - -func BenchmarkMetric(b *testing.B) { - for i := 0; i < b.N; i++ { - testMetric(b) - } -} - -func TestMetricNameIsValid(t *testing.T) { - var scenarios = []struct { - mn LabelValue - valid bool - }{ - { - mn: "Avalid_23name", - valid: true, - }, - { - mn: "_Avalid_23name", - valid: true, - }, - { - mn: "1valid_23name", - valid: false, - }, - { - mn: "avalid_23name", - valid: true, - }, - { - mn: "Ava:lid_23name", - valid: true, - }, - { - mn: "a lid_23name", - valid: false, - }, - { - mn: ":leading_colon", - valid: true, - }, - { - mn: "colon:in:the:middle", - valid: true, - }, - } - - for _, s := range scenarios { - if IsValidMetricName(s.mn) != s.valid { - t.Errorf("Expected %v for %q using IsValidMetricName function", s.valid, s.mn) - } - if MetricNameRE.MatchString(string(s.mn)) != s.valid { - t.Errorf("Expected %v for %q using regexp matching", s.valid, s.mn) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/signature_test.go b/vendor/github.com/prometheus/common/model/signature_test.go deleted file mode 100644 index d59c8a8c30..0000000000 --- a/vendor/github.com/prometheus/common/model/signature_test.go +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright 2014 The Prometheus 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 model - -import ( - "runtime" - "sync" - "testing" -) - -func TestLabelsToSignature(t *testing.T) { - var scenarios = []struct { - in map[string]string - out uint64 - }{ - { - in: map[string]string{}, - out: 14695981039346656037, - }, - { - in: map[string]string{"name": "garland, briggs", "fear": "love is not enough"}, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := LabelsToSignature(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestMetricToFingerprint(t *testing.T) { - var scenarios = []struct { - in LabelSet - out Fingerprint - }{ - { - in: LabelSet{}, - out: 14695981039346656037, - }, - { - in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := labelSetToFingerprint(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestMetricToFastFingerprint(t *testing.T) { - var scenarios = []struct { - in LabelSet - out Fingerprint - }{ - { - in: LabelSet{}, - out: 14695981039346656037, - }, - { - in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, - out: 12952432476264840823, - }, - } - - for i, scenario := range scenarios { - actual := labelSetToFastFingerprint(scenario.in) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestSignatureForLabels(t *testing.T) { - var scenarios = []struct { - in Metric - labels LabelNames - out uint64 - }{ - { - in: Metric{}, - labels: nil, - out: 14695981039346656037, - }, - { - in: Metric{}, - labels: LabelNames{"empty"}, - out: 7187873163539638612, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{"empty"}, - out: 7187873163539638612, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{"fear", "name"}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, - labels: LabelNames{"fear", "name"}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: LabelNames{}, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: nil, - out: 14695981039346656037, - }, - } - - for i, scenario := range scenarios { - actual := SignatureForLabels(scenario.in, scenario.labels...) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func TestSignatureWithoutLabels(t *testing.T) { - var scenarios = []struct { - in Metric - labels map[LabelName]struct{} - out uint64 - }{ - { - in: Metric{}, - labels: nil, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: map[LabelName]struct{}{"fear": struct{}{}, "name": struct{}{}}, - out: 14695981039346656037, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, - labels: map[LabelName]struct{}{"foo": struct{}{}}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: map[LabelName]struct{}{}, - out: 5799056148416392346, - }, - { - in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, - labels: nil, - out: 5799056148416392346, - }, - } - - for i, scenario := range scenarios { - actual := SignatureWithoutLabels(scenario.in, scenario.labels) - - if actual != scenario.out { - t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) - } - } -} - -func benchmarkLabelToSignature(b *testing.B, l map[string]string, e uint64) { - for i := 0; i < b.N; i++ { - if a := LabelsToSignature(l); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, l, a) - } - } -} - -func BenchmarkLabelToSignatureScalar(b *testing.B) { - benchmarkLabelToSignature(b, nil, 14695981039346656037) -} - -func BenchmarkLabelToSignatureSingle(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value"}, 5146282821936882169) -} - -func BenchmarkLabelToSignatureDouble(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) -} - -func BenchmarkLabelToSignatureTriple(b *testing.B) { - benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) -} - -func benchmarkMetricToFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { - for i := 0; i < b.N; i++ { - if a := labelSetToFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } -} - -func BenchmarkMetricToFingerprintScalar(b *testing.B) { - benchmarkMetricToFingerprint(b, nil, 14695981039346656037) -} - -func BenchmarkMetricToFingerprintSingle(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5146282821936882169) -} - -func BenchmarkMetricToFingerprintDouble(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) -} - -func BenchmarkMetricToFingerprintTriple(b *testing.B) { - benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) -} - -func benchmarkMetricToFastFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { - for i := 0; i < b.N; i++ { - if a := labelSetToFastFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } -} - -func BenchmarkMetricToFastFingerprintScalar(b *testing.B) { - benchmarkMetricToFastFingerprint(b, nil, 14695981039346656037) -} - -func BenchmarkMetricToFastFingerprintSingle(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5147259542624943964) -} - -func BenchmarkMetricToFastFingerprintDouble(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 18269973311206963528) -} - -func BenchmarkMetricToFastFingerprintTriple(b *testing.B) { - benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676) -} - -func BenchmarkEmptyLabelSignature(b *testing.B) { - input := []map[string]string{nil, {}} - - var ms runtime.MemStats - runtime.ReadMemStats(&ms) - - alloc := ms.Alloc - - for _, labels := range input { - LabelsToSignature(labels) - } - - runtime.ReadMemStats(&ms) - - if got := ms.Alloc; alloc != got { - b.Fatal("expected LabelsToSignature with empty labels not to perform allocations") - } -} - -func benchmarkMetricToFastFingerprintConc(b *testing.B, ls LabelSet, e Fingerprint, concLevel int) { - var start, end sync.WaitGroup - start.Add(1) - end.Add(concLevel) - - for i := 0; i < concLevel; i++ { - go func() { - start.Wait() - for j := b.N / concLevel; j >= 0; j-- { - if a := labelSetToFastFingerprint(ls); a != e { - b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) - } - } - end.Done() - }() - } - b.ResetTimer() - start.Done() - end.Wait() -} - -func BenchmarkMetricToFastFingerprintTripleConc1(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 1) -} - -func BenchmarkMetricToFastFingerprintTripleConc2(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 2) -} - -func BenchmarkMetricToFastFingerprintTripleConc4(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 4) -} - -func BenchmarkMetricToFastFingerprintTripleConc8(b *testing.B) { - benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 8) -} diff --git a/vendor/github.com/prometheus/common/model/silence.go b/vendor/github.com/prometheus/common/model/silence.go index 7538e29977..bb99889d2c 100644 --- a/vendor/github.com/prometheus/common/model/silence.go +++ b/vendor/github.com/prometheus/common/model/silence.go @@ -59,8 +59,8 @@ func (m *Matcher) Validate() error { return nil } -// Silence defines the representation of a silence definiton -// in the Prometheus eco-system. +// Silence defines the representation of a silence definition in the Prometheus +// eco-system. type Silence struct { ID uint64 `json:"id,omitempty"` diff --git a/vendor/github.com/prometheus/common/model/silence_test.go b/vendor/github.com/prometheus/common/model/silence_test.go deleted file mode 100644 index 8eaaf0744c..0000000000 --- a/vendor/github.com/prometheus/common/model/silence_test.go +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright 2015 The Prometheus 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 model - -import ( - "strings" - "testing" - "time" -) - -func TestMatcherValidate(t *testing.T) { - var cases = []struct { - matcher *Matcher - err string - }{ - { - matcher: &Matcher{ - Name: "name", - Value: "value", - }, - }, - { - matcher: &Matcher{ - Name: "name", - Value: "value", - IsRegex: true, - }, - }, - { - matcher: &Matcher{ - Name: "name!", - Value: "value", - }, - err: "invalid name", - }, - { - matcher: &Matcher{ - Name: "", - Value: "value", - }, - err: "invalid name", - }, - { - matcher: &Matcher{ - Name: "name", - Value: "value\xff", - }, - err: "invalid value", - }, - { - matcher: &Matcher{ - Name: "name", - Value: "", - }, - err: "invalid value", - }, - } - - for i, c := range cases { - err := c.matcher.Validate() - if err == nil { - if c.err == "" { - continue - } - t.Errorf("%d. Expected error %q but got none", i, c.err) - continue - } - if c.err == "" && err != nil { - t.Errorf("%d. Expected no error but got %q", i, err) - continue - } - if !strings.Contains(err.Error(), c.err) { - t.Errorf("%d. Expected error to contain %q but got %q", i, c.err, err) - } - } -} - -func TestSilenceValidate(t *testing.T) { - ts := time.Now() - - var cases = []struct { - sil *Silence - err string - }{ - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - {Name: "name", Value: "value"}, - {Name: "name", Value: "value"}, - {Name: "name", Value: "value", IsRegex: true}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts.Add(-1 * time.Minute), - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - err: "start time must be before end time", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - err: "end time missing", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - EndsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - err: "start time missing", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "!name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - err: "invalid matcher", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedAt: ts, - CreatedBy: "name", - }, - err: "comment missing", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedBy: "name", - Comment: "comment", - }, - err: "creation timestamp missing", - }, - { - sil: &Silence{ - Matchers: []*Matcher{ - {Name: "name", Value: "value"}, - }, - StartsAt: ts, - EndsAt: ts, - CreatedAt: ts, - Comment: "comment", - }, - err: "creator information missing", - }, - } - - for i, c := range cases { - err := c.sil.Validate() - if err == nil { - if c.err == "" { - continue - } - t.Errorf("%d. Expected error %q but got none", i, c.err) - continue - } - if c.err == "" && err != nil { - t.Errorf("%d. Expected no error but got %q", i, err) - continue - } - if !strings.Contains(err.Error(), c.err) { - t.Errorf("%d. Expected error to contain %q but got %q", i, c.err, err) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/time.go b/vendor/github.com/prometheus/common/model/time.go index 7e87f1ac63..74ed5a9f7e 100644 --- a/vendor/github.com/prometheus/common/model/time.go +++ b/vendor/github.com/prometheus/common/model/time.go @@ -214,6 +214,9 @@ func (d Duration) String() string { ms = int64(time.Duration(d) / time.Millisecond) unit = "ms" ) + if ms == 0 { + return "0s" + } factors := map[string]int64{ "y": 1000 * 60 * 60 * 24 * 365, "w": 1000 * 60 * 60 * 24 * 7, diff --git a/vendor/github.com/prometheus/common/model/time_test.go b/vendor/github.com/prometheus/common/model/time_test.go deleted file mode 100644 index 45ffd872d3..0000000000 --- a/vendor/github.com/prometheus/common/model/time_test.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2013 The Prometheus 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 model - -import ( - "testing" - "time" -) - -func TestComparators(t *testing.T) { - t1a := TimeFromUnix(0) - t1b := TimeFromUnix(0) - t2 := TimeFromUnix(2*second - 1) - - if !t1a.Equal(t1b) { - t.Fatalf("Expected %s to be equal to %s", t1a, t1b) - } - if t1a.Equal(t2) { - t.Fatalf("Expected %s to not be equal to %s", t1a, t2) - } - - if !t1a.Before(t2) { - t.Fatalf("Expected %s to be before %s", t1a, t2) - } - if t1a.Before(t1b) { - t.Fatalf("Expected %s to not be before %s", t1a, t1b) - } - - if !t2.After(t1a) { - t.Fatalf("Expected %s to be after %s", t2, t1a) - } - if t1b.After(t1a) { - t.Fatalf("Expected %s to not be after %s", t1b, t1a) - } -} - -func TestTimeConversions(t *testing.T) { - unixSecs := int64(1136239445) - unixNsecs := int64(123456789) - unixNano := unixSecs*1e9 + unixNsecs - - t1 := time.Unix(unixSecs, unixNsecs-unixNsecs%nanosPerTick) - t2 := time.Unix(unixSecs, unixNsecs) - - ts := TimeFromUnixNano(unixNano) - if !ts.Time().Equal(t1) { - t.Fatalf("Expected %s, got %s", t1, ts.Time()) - } - - // Test available precision. - ts = TimeFromUnixNano(t2.UnixNano()) - if !ts.Time().Equal(t1) { - t.Fatalf("Expected %s, got %s", t1, ts.Time()) - } - - if ts.UnixNano() != unixNano-unixNano%nanosPerTick { - t.Fatalf("Expected %d, got %d", unixNano, ts.UnixNano()) - } -} - -func TestDuration(t *testing.T) { - duration := time.Second + time.Minute + time.Hour - goTime := time.Unix(1136239445, 0) - - ts := TimeFromUnix(goTime.Unix()) - if !goTime.Add(duration).Equal(ts.Add(duration).Time()) { - t.Fatalf("Expected %s to be equal to %s", goTime.Add(duration), ts.Add(duration)) - } - - earlier := ts.Add(-duration) - delta := ts.Sub(earlier) - if delta != duration { - t.Fatalf("Expected %s to be equal to %s", delta, duration) - } -} - -func TestParseDuration(t *testing.T) { - var cases = []struct { - in string - out time.Duration - }{ - { - in: "324ms", - out: 324 * time.Millisecond, - }, { - in: "3s", - out: 3 * time.Second, - }, { - in: "5m", - out: 5 * time.Minute, - }, { - in: "1h", - out: time.Hour, - }, { - in: "4d", - out: 4 * 24 * time.Hour, - }, { - in: "3w", - out: 3 * 7 * 24 * time.Hour, - }, { - in: "10y", - out: 10 * 365 * 24 * time.Hour, - }, - } - - for _, c := range cases { - d, err := ParseDuration(c.in) - if err != nil { - t.Errorf("Unexpected error on input %q", c.in) - } - if time.Duration(d) != c.out { - t.Errorf("Expected %v but got %v", c.out, d) - } - if d.String() != c.in { - t.Errorf("Expected duration string %q but got %q", c.in, d.String()) - } - } -} diff --git a/vendor/github.com/prometheus/common/model/value.go b/vendor/github.com/prometheus/common/model/value.go index c9ed3ffd82..c9d8fb1a28 100644 --- a/vendor/github.com/prometheus/common/model/value.go +++ b/vendor/github.com/prometheus/common/model/value.go @@ -100,7 +100,7 @@ func (s *SamplePair) UnmarshalJSON(b []byte) error { } // Equal returns true if this SamplePair and o have equal Values and equal -// Timestamps. The sematics of Value equality is defined by SampleValue.Equal. +// Timestamps. The semantics of Value equality is defined by SampleValue.Equal. func (s *SamplePair) Equal(o *SamplePair) bool { return s == o || (s.Value.Equal(o.Value) && s.Timestamp.Equal(o.Timestamp)) } @@ -117,7 +117,7 @@ type Sample struct { } // Equal compares first the metrics, then the timestamp, then the value. The -// sematics of value equality is defined by SampleValue.Equal. +// semantics of value equality is defined by SampleValue.Equal. func (s *Sample) Equal(o *Sample) bool { if s == o { return true diff --git a/vendor/github.com/prometheus/common/model/value_test.go b/vendor/github.com/prometheus/common/model/value_test.go deleted file mode 100644 index b97dcf84cf..0000000000 --- a/vendor/github.com/prometheus/common/model/value_test.go +++ /dev/null @@ -1,468 +0,0 @@ -// Copyright 2013 The Prometheus 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 model - -import ( - "encoding/json" - "math" - "reflect" - "sort" - "testing" -) - -func TestEqualValues(t *testing.T) { - tests := map[string]struct { - in1, in2 SampleValue - want bool - }{ - "equal floats": { - in1: 3.14, - in2: 3.14, - want: true, - }, - "unequal floats": { - in1: 3.14, - in2: 3.1415, - want: false, - }, - "positive inifinities": { - in1: SampleValue(math.Inf(+1)), - in2: SampleValue(math.Inf(+1)), - want: true, - }, - "negative inifinities": { - in1: SampleValue(math.Inf(-1)), - in2: SampleValue(math.Inf(-1)), - want: true, - }, - "different inifinities": { - in1: SampleValue(math.Inf(+1)), - in2: SampleValue(math.Inf(-1)), - want: false, - }, - "number and infinity": { - in1: 42, - in2: SampleValue(math.Inf(+1)), - want: false, - }, - "number and NaN": { - in1: 42, - in2: SampleValue(math.NaN()), - want: false, - }, - "NaNs": { - in1: SampleValue(math.NaN()), - in2: SampleValue(math.NaN()), - want: true, // !!! - }, - } - - for name, test := range tests { - got := test.in1.Equal(test.in2) - if got != test.want { - t.Errorf("Comparing %s, %f and %f: got %t, want %t", name, test.in1, test.in2, got, test.want) - } - } -} - -func TestEqualSamples(t *testing.T) { - testSample := &Sample{} - - tests := map[string]struct { - in1, in2 *Sample - want bool - }{ - "equal pointers": { - in1: testSample, - in2: testSample, - want: true, - }, - "different metrics": { - in1: &Sample{Metric: Metric{"foo": "bar"}}, - in2: &Sample{Metric: Metric{"foo": "biz"}}, - want: false, - }, - "different timestamp": { - in1: &Sample{Timestamp: 0}, - in2: &Sample{Timestamp: 1}, - want: false, - }, - "different value": { - in1: &Sample{Value: 0}, - in2: &Sample{Value: 1}, - want: false, - }, - "equal samples": { - in1: &Sample{ - Metric: Metric{"foo": "bar"}, - Timestamp: 0, - Value: 1, - }, - in2: &Sample{ - Metric: Metric{"foo": "bar"}, - Timestamp: 0, - Value: 1, - }, - want: true, - }, - } - - for name, test := range tests { - got := test.in1.Equal(test.in2) - if got != test.want { - t.Errorf("Comparing %s, %v and %v: got %t, want %t", name, test.in1, test.in2, got, test.want) - } - } - -} - -func TestSamplePairJSON(t *testing.T) { - input := []struct { - plain string - value SamplePair - }{ - { - plain: `[1234.567,"123.1"]`, - value: SamplePair{ - Value: 123.1, - Timestamp: 1234567, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sp SamplePair - err = json.Unmarshal(b, &sp) - if err != nil { - t.Error(err) - continue - } - - if sp != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sp) - } - } -} - -func TestSampleJSON(t *testing.T) { - input := []struct { - plain string - value Sample - }{ - { - plain: `{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}`, - value: Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv Sample - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if !reflect.DeepEqual(sv, test.value) { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestVectorJSON(t *testing.T) { - input := []struct { - plain string - value Vector - }{ - { - plain: `[]`, - value: Vector{}, - }, - { - plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}]`, - value: Vector{&Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }}, - }, - { - plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]},{"metric":{"foo":"bar"},"value":[1.234,"+Inf"]}]`, - value: Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "test_metric", - }, - Value: 123.1, - Timestamp: 1234567, - }, - &Sample{ - Metric: Metric{ - "foo": "bar", - }, - Value: SampleValue(math.Inf(1)), - Timestamp: 1234, - }, - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var vec Vector - err = json.Unmarshal(b, &vec) - if err != nil { - t.Error(err) - continue - } - - if !reflect.DeepEqual(vec, test.value) { - t.Errorf("decoding error: expected %v, got %v", test.value, vec) - } - } -} - -func TestScalarJSON(t *testing.T) { - input := []struct { - plain string - value Scalar - }{ - { - plain: `[123.456,"456"]`, - value: Scalar{ - Timestamp: 123456, - Value: 456, - }, - }, - { - plain: `[123123.456,"+Inf"]`, - value: Scalar{ - Timestamp: 123123456, - Value: SampleValue(math.Inf(1)), - }, - }, - { - plain: `[123123.456,"-Inf"]`, - value: Scalar{ - Timestamp: 123123456, - Value: SampleValue(math.Inf(-1)), - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv Scalar - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if sv != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestStringJSON(t *testing.T) { - input := []struct { - plain string - value String - }{ - { - plain: `[123.456,"test"]`, - value: String{ - Timestamp: 123456, - Value: "test", - }, - }, - { - plain: `[123123.456,"台北"]`, - value: String{ - Timestamp: 123123456, - Value: "台北", - }, - }, - } - - for _, test := range input { - b, err := json.Marshal(test.value) - if err != nil { - t.Error(err) - continue - } - - if string(b) != test.plain { - t.Errorf("encoding error: expected %q, got %q", test.plain, b) - continue - } - - var sv String - err = json.Unmarshal(b, &sv) - if err != nil { - t.Error(err) - continue - } - - if sv != test.value { - t.Errorf("decoding error: expected %v, got %v", test.value, sv) - } - } -} - -func TestVectorSort(t *testing.T) { - input := Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 2, - }, - } - - expected := Vector{ - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "A", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "B", - }, - Timestamp: 2, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 1, - }, - &Sample{ - Metric: Metric{ - MetricNameLabel: "C", - }, - Timestamp: 2, - }, - } - - sort.Sort(input) - - for i, actual := range input { - actualFp := actual.Metric.Fingerprint() - expectedFp := expected[i].Metric.Fingerprint() - - if actualFp != expectedFp { - t.Fatalf("%d. Incorrect fingerprint. Got %s; want %s", i, actualFp.String(), expectedFp.String()) - } - - if actual.Timestamp != expected[i].Timestamp { - t.Fatalf("%d. Incorrect timestamp. Got %s; want %s", i, actual.Timestamp, expected[i].Timestamp) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/.gitignore b/vendor/github.com/prometheus/procfs/.gitignore new file mode 100644 index 0000000000..25e3659ab2 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/.gitignore @@ -0,0 +1 @@ +/fixtures/ diff --git a/vendor/github.com/prometheus/procfs/.travis.yml b/vendor/github.com/prometheus/procfs/.travis.yml index ee09bb7339..5416cf8a27 100644 --- a/vendor/github.com/prometheus/procfs/.travis.yml +++ b/vendor/github.com/prometheus/procfs/.travis.yml @@ -1,5 +1,15 @@ sudo: false + language: go + go: - - 1.7.6 - - 1.8.3 +- 1.7.x +- 1.8.x +- 1.9.x +- 1.10.x +- 1.x + +go_import_path: github.com/prometheus/procfs + +script: +- make style check_license vet test staticcheck diff --git a/vendor/github.com/prometheus/procfs/Makefile b/vendor/github.com/prometheus/procfs/Makefile index dd48afdcd4..5c8f726253 100644 --- a/vendor/github.com/prometheus/procfs/Makefile +++ b/vendor/github.com/prometheus/procfs/Makefile @@ -1,18 +1,71 @@ -ci: fmt lint test +# Copyright 2018 The Prometheus 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. -fmt: - ! gofmt -l *.go | read nothing - go vet +# Ensure GOBIN is not set during build so that promu is installed to the correct path +unexport GOBIN -lint: - go get github.com/golang/lint/golint - golint *.go +GO ?= go +GOFMT ?= $(GO)fmt +FIRST_GOPATH := $(firstword $(subst :, ,$(shell $(GO) env GOPATH))) +STATICCHECK := $(FIRST_GOPATH)/bin/staticcheck +pkgs = $(shell $(GO) list ./... | grep -v /vendor/) -test: sysfs/fixtures/.unpacked - go test -v ./... +PREFIX ?= $(shell pwd) +BIN_DIR ?= $(shell pwd) -sysfs/fixtures/.unpacked: sysfs/fixtures.ttar - ./ttar -C sysfs -x -f sysfs/fixtures.ttar +ifdef DEBUG + bindata_flags = -debug +endif + +STATICCHECK_IGNORE = + +all: format staticcheck build test + +style: + @echo ">> checking code style" + @! $(GOFMT) -d $(shell find . -path ./vendor -prune -o -name '*.go' -print) | grep '^' + +check_license: + @echo ">> checking license header" + @./scripts/check_license.sh + +test: fixtures/.unpacked sysfs/fixtures/.unpacked + @echo ">> running all tests" + @$(GO) test -race $(shell $(GO) list ./... | grep -v /vendor/ | grep -v examples) + +format: + @echo ">> formatting code" + @$(GO) fmt $(pkgs) + +vet: + @echo ">> vetting code" + @$(GO) vet $(pkgs) + +staticcheck: $(STATICCHECK) + @echo ">> running staticcheck" + @$(STATICCHECK) -ignore "$(STATICCHECK_IGNORE)" $(pkgs) + +%/.unpacked: %.ttar + ./ttar -C $(dir $*) -x -f $*.ttar touch $@ -.PHONY: fmt lint test ci +$(FIRST_GOPATH)/bin/staticcheck: + @GOOS= GOARCH= $(GO) get -u honnef.co/go/tools/cmd/staticcheck + +.PHONY: all style check_license format test vet staticcheck + +# Declaring the binaries at their default locations as PHONY targets is a hack +# to ensure the latest version is downloaded on every make execution. +# If this is not desired, copy/symlink these binaries to a different path and +# set the respective environment variables. +.PHONY: $(GOPATH)/bin/staticcheck diff --git a/vendor/github.com/prometheus/procfs/buddyinfo.go b/vendor/github.com/prometheus/procfs/buddyinfo.go index 680a9842a4..d3a8268078 100644 --- a/vendor/github.com/prometheus/procfs/buddyinfo.go +++ b/vendor/github.com/prometheus/procfs/buddyinfo.go @@ -62,7 +62,7 @@ func parseBuddyInfo(r io.Reader) ([]BuddyInfo, error) { for scanner.Scan() { var err error line := scanner.Text() - parts := strings.Fields(string(line)) + parts := strings.Fields(line) if len(parts) < 4 { return nil, fmt.Errorf("invalid number of fields when parsing buddyinfo") diff --git a/vendor/github.com/prometheus/procfs/buddyinfo_test.go b/vendor/github.com/prometheus/procfs/buddyinfo_test.go deleted file mode 100644 index bcf9355cab..0000000000 --- a/vendor/github.com/prometheus/procfs/buddyinfo_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2017 The Prometheus 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 procfs - -import ( - "strings" - "testing" -) - -func TestBuddyInfo(t *testing.T) { - buddyInfo, err := FS("fixtures/buddyinfo/valid").NewBuddyInfo() - if err != nil { - t.Fatal(err) - } - - if want, got := "DMA", buddyInfo[0].Zone; want != got { - t.Errorf("want Node 0, Zone %s, got %s", want, got) - } - - if want, got := "Normal", buddyInfo[2].Zone; want != got { - t.Errorf("want Node 0, Zone %s, got %s", want, got) - } - - if want, got := 4381.0, buddyInfo[2].Sizes[0]; want != got { - t.Errorf("want Node 0, Zone Normal %f, got %f", want, got) - } - - if want, got := 572.0, buddyInfo[1].Sizes[1]; want != got { - t.Errorf("want Node 0, Zone DMA32 %f, got %f", want, got) - } -} - -func TestBuddyInfoShort(t *testing.T) { - _, err := FS("fixtures/buddyinfo/short").NewBuddyInfo() - if err == nil { - t.Errorf("expected error, but none occurred") - } - - if want, got := "invalid number of fields when parsing buddyinfo", err.Error(); want != got { - t.Errorf("wrong error returned, wanted %q, got %q", want, got) - } -} - -func TestBuddyInfoSizeMismatch(t *testing.T) { - _, err := FS("fixtures/buddyinfo/sizemismatch").NewBuddyInfo() - if err == nil { - t.Errorf("expected error, but none occurred") - } - - if want, got := "mismatch in number of buddyinfo buckets", err.Error(); !strings.HasPrefix(got, want) { - t.Errorf("wrong error returned, wanted prefix %q, got %q", want, got) - } -} diff --git a/vendor/github.com/prometheus/procfs/fixtures.ttar b/vendor/github.com/prometheus/procfs/fixtures.ttar new file mode 100644 index 0000000000..3ee8291e81 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/fixtures.ttar @@ -0,0 +1,446 @@ +# Archive created by ttar -c -f fixtures.ttar fixtures/ +Directory: fixtures +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26231 +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/cmdline +Lines: 1 +vimNULLBYTEtest.goNULLBYTE+10NULLBYTEEOF +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/comm +Lines: 1 +vim +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/exe +SymlinkTo: /usr/bin/vim +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26231/fd +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/fd/0 +SymlinkTo: ../../symlinktargets/abc +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/fd/1 +SymlinkTo: ../../symlinktargets/def +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/fd/10 +SymlinkTo: ../../symlinktargets/xyz +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/fd/2 +SymlinkTo: ../../symlinktargets/ghi +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/fd/3 +SymlinkTo: ../../symlinktargets/uvw +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/io +Lines: 7 +rchar: 750339 +wchar: 818609 +syscr: 7405 +syscw: 5245 +read_bytes: 1024 +write_bytes: 2048 +cancelled_write_bytes: -1024 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/limits +Lines: 17 +Limit Soft Limit Hard Limit Units +Max cpu time unlimited unlimited seconds +Max file size unlimited unlimited bytes +Max data size unlimited unlimited bytes +Max stack size 8388608 unlimited bytes +Max core file size 0 unlimited bytes +Max resident set unlimited unlimited bytes +Max processes 62898 62898 processes +Max open files 2048 4096 files +Max locked memory 65536 65536 bytes +Max address space 8589934592 unlimited bytes +Max file locks unlimited unlimited locks +Max pending signals 62898 62898 signals +Max msgqueue size 819200 819200 bytes +Max nice priority 0 0 +Max realtime priority 0 0 +Max realtime timeout unlimited unlimited us +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/mountstats +Lines: 19 +device rootfs mounted on / with fstype rootfs +device sysfs mounted on /sys with fstype sysfs +device proc mounted on /proc with fstype proc +device /dev/sda1 mounted on / with fstype ext4 +device 192.168.1.1:/srv/test mounted on /mnt/nfs/test with fstype nfs4 statvers=1.1 + opts: rw,vers=4.0,rsize=1048576,wsize=1048576,namlen=255,acregmin=3,acregmax=60,acdirmin=30,acdirmax=60,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=192.168.1.5,local_lock=none + age: 13968 + caps: caps=0xfff7,wtmult=512,dtsize=32768,bsize=0,namlen=255 + nfsv4: bm0=0xfdffafff,bm1=0xf9be3e,bm2=0x0,acl=0x0,pnfs=not configured + sec: flavor=1,pseudoflavor=1 + events: 52 226 0 0 1 13 398 0 0 331 0 47 0 0 77 0 0 77 0 0 0 0 0 0 0 0 0 + bytes: 1207640230 0 0 0 1210214218 0 295483 0 + RPC iostats version: 1.0 p/v: 100003/4 (nfs) + xprt: tcp 832 0 1 0 11 6428 6428 0 12154 0 24 26 5726 + per-op statistics + NULL: 0 0 0 0 0 0 0 0 + READ: 1298 1298 0 207680 1210292152 6 79386 79407 + WRITE: 0 0 0 0 0 0 0 0 + +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26231/net +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/net/dev +Lines: 4 +Inter-| Receive | Transmit + face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed + lo: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 + eth0: 438 5 0 0 0 0 0 0 648 8 0 0 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26231/ns +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/ns/mnt +SymlinkTo: mnt:[4026531840] +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/ns/net +SymlinkTo: net:[4026531993] +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26231/stat +Lines: 1 +26231 (vim) R 5392 7446 5392 34835 7446 4218880 32533 309516 26 82 1677 44 158 99 20 0 1 0 82375 56274944 1981 18446744073709551615 4194304 6294284 140736914091744 140736914087944 139965136429984 0 0 12288 1870679807 0 0 0 17 0 0 0 31 0 0 8391624 8481048 16420864 140736914093252 140736914093279 140736914093279 140736914096107 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26232 +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/cmdline +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/comm +Lines: 1 +ata_sff +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26232/fd +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/fd/0 +SymlinkTo: ../../symlinktargets/abc +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/fd/1 +SymlinkTo: ../../symlinktargets/def +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/fd/2 +SymlinkTo: ../../symlinktargets/ghi +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/fd/3 +SymlinkTo: ../../symlinktargets/uvw +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/fd/4 +SymlinkTo: ../../symlinktargets/xyz +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/limits +Lines: 17 +Limit Soft Limit Hard Limit Units +Max cpu time unlimited unlimited seconds +Max file size unlimited unlimited bytes +Max data size unlimited unlimited bytes +Max stack size 8388608 unlimited bytes +Max core file size 0 unlimited bytes +Max resident set unlimited unlimited bytes +Max processes 29436 29436 processes +Max open files 1024 4096 files +Max locked memory 65536 65536 bytes +Max address space unlimited unlimited bytes +Max file locks unlimited unlimited locks +Max pending signals 29436 29436 signals +Max msgqueue size 819200 819200 bytes +Max nice priority 0 0 +Max realtime priority 0 0 +Max realtime timeout unlimited unlimited us +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26232/stat +Lines: 1 +33 (ata_sff) S 2 0 0 0 -1 69238880 0 0 0 0 0 0 0 0 0 -20 1 0 5 0 0 18446744073709551615 0 0 0 0 0 0 0 2147483647 0 18446744073709551615 0 0 17 1 0 0 0 0 0 0 0 0 0 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/26233 +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/26233/cmdline +Lines: 1 +com.github.uiautomatorNULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTENULLBYTEEOF +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/584 +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/584/stat +Lines: 2 +1020 ((a b ) ( c d) ) R 28378 1020 28378 34842 1020 4218880 286 0 0 0 0 0 0 0 20 0 1 0 10839175 10395648 155 18446744073709551615 4194304 4238788 140736466511168 140736466511168 140609271124624 0 0 0 0 0 0 0 17 5 0 0 0 0 0 6336016 6337300 25579520 140736466515030 140736466515061 140736466515061 140736466518002 0 +#!/bin/cat /proc/self/stat +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/buddyinfo +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/buddyinfo/short +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/buddyinfo/short/buddyinfo +Lines: 3 +Node 0, zone +Node 0, zone +Node 0, zone +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/buddyinfo/sizemismatch +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/buddyinfo/sizemismatch/buddyinfo +Lines: 3 +Node 0, zone DMA 1 0 1 0 2 1 1 0 1 1 3 +Node 0, zone DMA32 759 572 791 475 194 45 12 0 0 0 0 0 +Node 0, zone Normal 4381 1093 185 1530 567 102 4 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/buddyinfo/valid +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/buddyinfo/valid/buddyinfo +Lines: 3 +Node 0, zone DMA 1 0 1 0 2 1 1 0 1 1 3 +Node 0, zone DMA32 759 572 791 475 194 45 12 0 0 0 0 +Node 0, zone Normal 4381 1093 185 1530 567 102 4 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/fs +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/fs/xfs +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/fs/xfs/stat +Lines: 23 +extent_alloc 92447 97589 92448 93751 +abt 0 0 0 0 +blk_map 1767055 188820 184891 92447 92448 2140766 0 +bmbt 0 0 0 0 +dir 185039 92447 92444 136422 +trans 706 944304 0 +ig 185045 58807 0 126238 0 33637 22 +log 2883 113448 9 17360 739 +push_ail 945014 0 134260 15483 0 3940 464 159985 0 40 +xstrat 92447 0 +rw 107739 94045 +attr 4 0 0 0 +icluster 8677 7849 135802 +vnodes 92601 0 0 0 92444 92444 92444 0 +buf 2666287 7122 2659202 3599 2 7085 0 10297 7085 +abtb2 184941 1277345 13257 13278 0 0 0 0 0 0 0 0 0 0 2746147 +abtc2 345295 2416764 172637 172658 0 0 0 0 0 0 0 0 0 0 21406023 +bmbt2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +ibt2 343004 1358467 0 0 0 0 0 0 0 0 0 0 0 0 0 +fibt2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +qm 0 0 0 0 0 0 0 0 +xpc 399724544 92823103 86219234 +debug 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/mdstat +Lines: 26 +Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10] +md3 : active raid6 sda1[8] sdh1[7] sdg1[6] sdf1[5] sde1[11] sdd1[3] sdc1[10] sdb1[9] + 5853468288 blocks super 1.2 level 6, 64k chunk, algorithm 2 [8/8] [UUUUUUUU] + +md127 : active raid1 sdi2[0] sdj2[1] + 312319552 blocks [2/2] [UU] + +md0 : active raid1 sdk[2](S) sdi1[0] sdj1[1] + 248896 blocks [2/2] [UU] + +md4 : inactive raid1 sda3[0] sdb3[1] + 4883648 blocks [2/2] [UU] + +md6 : active raid1 sdb2[2] sda2[0] + 195310144 blocks [2/1] [U_] + [=>...................] recovery = 8.5% (16775552/195310144) finish=17.0min speed=259783K/sec + +md8 : active raid1 sdb1[1] sda1[0] + 195310144 blocks [2/2] [UU] + [=>...................] resync = 8.5% (16775552/195310144) finish=17.0min speed=259783K/sec + +md7 : active raid6 sdb1[0] sde1[3] sdd1[2] sdc1[1] + 7813735424 blocks super 1.2 level 6, 512k chunk, algorithm 2 [4/3] [U_UU] + bitmap: 0/30 pages [0KB], 65536KB chunk + +unused devices: +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/net +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/dev +Lines: 6 +Inter-| Receive | Transmit + face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed +vethf345468: 648 8 0 0 0 0 0 0 438 5 0 0 0 0 0 0 + lo: 1664039048 1566805 0 0 0 0 0 0 1664039048 1566805 0 0 0 0 0 0 +docker0: 2568 38 0 0 0 0 0 0 438 5 0 0 0 0 0 0 + eth0: 874354587 1036395 0 0 0 0 0 0 563352563 732147 0 0 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/ip_vs +Lines: 21 +IP Virtual Server version 1.2.1 (size=4096) +Prot LocalAddress:Port Scheduler Flags + -> RemoteAddress:Port Forward Weight ActiveConn InActConn +TCP C0A80016:0CEA wlc + -> C0A85216:0CEA Tunnel 100 248 2 + -> C0A85318:0CEA Tunnel 100 248 2 + -> C0A85315:0CEA Tunnel 100 248 1 +TCP C0A80039:0CEA wlc + -> C0A85416:0CEA Tunnel 0 0 0 + -> C0A85215:0CEA Tunnel 100 1499 0 + -> C0A83215:0CEA Tunnel 100 1498 0 +TCP C0A80037:0CEA wlc + -> C0A8321A:0CEA Tunnel 0 0 0 + -> C0A83120:0CEA Tunnel 100 0 0 +TCP [2620:0000:0000:0000:0000:0000:0000:0001]:0050 sh + -> [2620:0000:0000:0000:0000:0000:0000:0002]:0050 Route 1 0 0 + -> [2620:0000:0000:0000:0000:0000:0000:0003]:0050 Route 1 0 0 + -> [2620:0000:0000:0000:0000:0000:0000:0004]:0050 Route 1 1 1 +FWM 10001000 wlc + -> C0A8321A:0CEA Route 0 0 1 + -> C0A83215:0CEA Route 0 0 2 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/ip_vs_stats +Lines: 6 + Total Incoming Outgoing Incoming Outgoing + Conns Packets Packets Bytes Bytes + 16AA370 E33656E5 0 51D8C8883AB3 0 + + Conns/s Pkts/s Pkts/s Bytes/s Bytes/s + 4 1FB3C 0 1282A8F 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/net/rpc +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/rpc/nfs +Lines: 5 +net 18628 0 18628 6 +rpc 4329785 0 4338291 +proc2 18 2 69 0 0 4410 0 0 0 0 0 0 0 0 0 0 0 99 2 +proc3 22 1 4084749 29200 94754 32580 186 47747 7981 8639 0 6356 0 6962 0 7958 0 0 241 4 4 2 39 +proc4 61 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 2 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 0 0 0 0 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/rpc/nfsd +Lines: 11 +rc 0 6 18622 +fh 0 0 0 0 0 +io 157286400 0 +th 8 0 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 0.000 +ra 32 0 0 0 0 0 0 0 0 0 0 0 +net 18628 0 18628 6 +rpc 18628 0 0 0 0 +proc2 18 2 69 0 0 4410 0 0 0 0 0 0 0 0 0 0 0 99 2 +proc3 22 2 112 0 2719 111 0 0 0 0 0 0 0 0 0 0 0 27 216 0 2 1 0 +proc4 2 2 10853 +proc4ops 72 0 0 0 1098 2 0 0 0 0 8179 5896 0 0 0 0 5900 0 0 2 0 2 0 9609 0 2 150 1272 0 0 0 1236 0 0 0 0 3 3 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 0 0 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/net/xfrm_stat +Lines: 28 +XfrmInError 1 +XfrmInBufferError 2 +XfrmInHdrError 4 +XfrmInNoStates 3 +XfrmInStateProtoError 40 +XfrmInStateModeError 100 +XfrmInStateSeqError 6000 +XfrmInStateExpired 4 +XfrmInStateMismatch 23451 +XfrmInStateInvalid 55555 +XfrmInTmplMismatch 51 +XfrmInNoPols 65432 +XfrmInPolBlock 100 +XfrmInPolError 10000 +XfrmOutError 1000000 +XfrmOutBundleGenError 43321 +XfrmOutBundleCheckError 555 +XfrmOutNoStates 869 +XfrmOutStateProtoError 4542 +XfrmOutStateModeError 4 +XfrmOutStateSeqError 543 +XfrmOutStateExpired 565 +XfrmOutPolBlock 43456 +XfrmOutPolDead 7656 +XfrmOutPolError 1454 +XfrmFwdHdrError 6654 +XfrmOutStateInvalid 28765 +XfrmAcquireError 24532 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/self +SymlinkTo: 26231 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/stat +Lines: 16 +cpu 301854 612 111922 8979004 3552 2 3944 0 0 0 +cpu0 44490 19 21045 1087069 220 1 3410 0 0 0 +cpu1 47869 23 16474 1110787 591 0 46 0 0 0 +cpu2 46504 36 15916 1112321 441 0 326 0 0 0 +cpu3 47054 102 15683 1113230 533 0 60 0 0 0 +cpu4 28413 25 10776 1140321 217 0 8 0 0 0 +cpu5 29271 101 11586 1136270 672 0 30 0 0 0 +cpu6 29152 36 10276 1139721 319 0 29 0 0 0 +cpu7 29098 268 10164 1139282 555 0 31 0 0 0 +intr 8885917 17 0 0 0 0 0 0 0 1 79281 0 0 0 0 0 0 0 231237 0 0 0 0 250586 103 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 223424 190745 13 906 1283803 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +ctxt 38014093 +btime 1418183276 +processes 26442 +procs_running 2 +procs_blocked 1 +softirq 5057579 250191 1481983 1647 211099 186066 0 1783454 622196 12499 508444 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Directory: fixtures/symlinktargets +Mode: 755 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/README +Lines: 2 +This directory contains some empty files that are the symlinks the files in the "fd" directory point to. +They are otherwise ignored by the tests +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/abc +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/def +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/ghi +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/uvw +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +Path: fixtures/symlinktargets/xyz +Lines: 0 +Mode: 644 +# ttar - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/vendor/github.com/prometheus/procfs/fs.go b/vendor/github.com/prometheus/procfs/fs.go index 17546756b3..b6c6b2ce1f 100644 --- a/vendor/github.com/prometheus/procfs/fs.go +++ b/vendor/github.com/prometheus/procfs/fs.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus 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 procfs import ( @@ -5,6 +18,7 @@ import ( "os" "path" + "github.com/prometheus/procfs/nfs" "github.com/prometheus/procfs/xfs" ) @@ -44,3 +58,25 @@ func (fs FS) XFSStats() (*xfs.Stats, error) { return xfs.ParseStats(f) } + +// NFSClientRPCStats retrieves NFS client RPC statistics. +func (fs FS) NFSClientRPCStats() (*nfs.ClientRPCStats, error) { + f, err := os.Open(fs.Path("net/rpc/nfs")) + if err != nil { + return nil, err + } + defer f.Close() + + return nfs.ParseClientRPCStats(f) +} + +// NFSdServerRPCStats retrieves NFS daemon RPC statistics. +func (fs FS) NFSdServerRPCStats() (*nfs.ServerRPCStats, error) { + f, err := os.Open(fs.Path("net/rpc/nfsd")) + if err != nil { + return nil, err + } + defer f.Close() + + return nfs.ParseServerRPCStats(f) +} diff --git a/vendor/github.com/prometheus/procfs/fs_test.go b/vendor/github.com/prometheus/procfs/fs_test.go deleted file mode 100644 index e492cde55e..0000000000 --- a/vendor/github.com/prometheus/procfs/fs_test.go +++ /dev/null @@ -1,26 +0,0 @@ -package procfs - -import "testing" - -func TestNewFS(t *testing.T) { - if _, err := NewFS("foobar"); err == nil { - t.Error("want NewFS to fail for non-existing mount point") - } - - if _, err := NewFS("procfs.go"); err == nil { - t.Error("want NewFS to fail if mount point is not a directory") - } -} - -func TestFSXFSStats(t *testing.T) { - stats, err := FS("fixtures").XFSStats() - if err != nil { - t.Fatalf("failed to parse XFS stats: %v", err) - } - - // Very lightweight test just to sanity check the path used - // to open XFS stats. Heavier tests in package xfs. - if want, got := uint32(92447), stats.ExtentAllocation.ExtentsAllocated; want != got { - t.Errorf("unexpected extents allocated:\nwant: %d\nhave: %d", want, got) - } -} diff --git a/vendor/github.com/prometheus/procfs/internal/util/parse.go b/vendor/github.com/prometheus/procfs/internal/util/parse.go new file mode 100644 index 0000000000..1ad21c91a3 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/internal/util/parse.go @@ -0,0 +1,46 @@ +// Copyright 2018 The Prometheus 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 util + +import "strconv" + +// ParseUint32s parses a slice of strings into a slice of uint32s. +func ParseUint32s(ss []string) ([]uint32, error) { + us := make([]uint32, 0, len(ss)) + for _, s := range ss { + u, err := strconv.ParseUint(s, 10, 32) + if err != nil { + return nil, err + } + + us = append(us, uint32(u)) + } + + return us, nil +} + +// ParseUint64s parses a slice of strings into a slice of uint64s. +func ParseUint64s(ss []string) ([]uint64, error) { + us := make([]uint64, 0, len(ss)) + for _, s := range ss { + u, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return nil, err + } + + us = append(us, u) + } + + return us, nil +} diff --git a/vendor/github.com/prometheus/procfs/ipvs.go b/vendor/github.com/prometheus/procfs/ipvs.go index 696d114e73..e36d4a3bd0 100644 --- a/vendor/github.com/prometheus/procfs/ipvs.go +++ b/vendor/github.com/prometheus/procfs/ipvs.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus 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 procfs import ( @@ -31,16 +44,16 @@ type IPVSStats struct { type IPVSBackendStatus struct { // The local (virtual) IP address. LocalAddress net.IP + // The remote (real) IP address. + RemoteAddress net.IP // The local (virtual) port. LocalPort uint16 + // The remote (real) port. + RemotePort uint16 // The local firewall mark LocalMark string // The transport protocol (TCP, UDP). Proto string - // The remote (real) IP address. - RemoteAddress net.IP - // The remote (real) port. - RemotePort uint16 // The current number of active connections for this virtual/real address pair. ActiveConn uint64 // The current number of inactive connections for this virtual/real address pair. @@ -151,7 +164,7 @@ func parseIPVSBackendStatus(file io.Reader) ([]IPVSBackendStatus, error) { ) for scanner.Scan() { - fields := strings.Fields(string(scanner.Text())) + fields := strings.Fields(scanner.Text()) if len(fields) == 0 { continue } diff --git a/vendor/github.com/prometheus/procfs/ipvs_test.go b/vendor/github.com/prometheus/procfs/ipvs_test.go deleted file mode 100644 index 13ceab80ee..0000000000 --- a/vendor/github.com/prometheus/procfs/ipvs_test.go +++ /dev/null @@ -1,237 +0,0 @@ -package procfs - -import ( - "net" - "testing" -) - -var ( - expectedIPVSStats = IPVSStats{ - Connections: 23765872, - IncomingPackets: 3811989221, - OutgoingPackets: 0, - IncomingBytes: 89991519156915, - OutgoingBytes: 0, - } - expectedIPVSBackendStatuses = []IPVSBackendStatus{ - { - LocalAddress: net.ParseIP("192.168.0.22"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.82.22"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 248, - InactConn: 2, - }, - { - LocalAddress: net.ParseIP("192.168.0.22"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.83.24"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 248, - InactConn: 2, - }, - { - LocalAddress: net.ParseIP("192.168.0.22"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.83.21"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 248, - InactConn: 1, - }, - { - LocalAddress: net.ParseIP("192.168.0.57"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.84.22"), - RemotePort: 3306, - Proto: "TCP", - Weight: 0, - ActiveConn: 0, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("192.168.0.57"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.82.21"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 1499, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("192.168.0.57"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.50.21"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 1498, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("192.168.0.55"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.50.26"), - RemotePort: 3306, - Proto: "TCP", - Weight: 0, - ActiveConn: 0, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("192.168.0.55"), - LocalPort: 3306, - RemoteAddress: net.ParseIP("192.168.49.32"), - RemotePort: 3306, - Proto: "TCP", - Weight: 100, - ActiveConn: 0, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("2620::1"), - LocalPort: 80, - RemoteAddress: net.ParseIP("2620::2"), - RemotePort: 80, - Proto: "TCP", - Weight: 1, - ActiveConn: 0, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("2620::1"), - LocalPort: 80, - RemoteAddress: net.ParseIP("2620::3"), - RemotePort: 80, - Proto: "TCP", - Weight: 1, - ActiveConn: 0, - InactConn: 0, - }, - { - LocalAddress: net.ParseIP("2620::1"), - LocalPort: 80, - RemoteAddress: net.ParseIP("2620::4"), - RemotePort: 80, - Proto: "TCP", - Weight: 1, - ActiveConn: 1, - InactConn: 1, - }, - { - LocalMark: "10001000", - RemoteAddress: net.ParseIP("192.168.50.26"), - RemotePort: 3306, - Proto: "FWM", - Weight: 0, - ActiveConn: 0, - InactConn: 1, - }, - { - LocalMark: "10001000", - RemoteAddress: net.ParseIP("192.168.50.21"), - RemotePort: 3306, - Proto: "FWM", - Weight: 0, - ActiveConn: 0, - InactConn: 2, - }, - } -) - -func TestIPVSStats(t *testing.T) { - stats, err := FS("fixtures").NewIPVSStats() - if err != nil { - t.Fatal(err) - } - - if stats != expectedIPVSStats { - t.Errorf("want %+v, have %+v", expectedIPVSStats, stats) - } -} - -func TestParseIPPort(t *testing.T) { - ip := net.ParseIP("192.168.0.22") - port := uint16(3306) - - gotIP, gotPort, err := parseIPPort("C0A80016:0CEA") - if err != nil { - t.Fatal(err) - } - if !(gotIP.Equal(ip) && port == gotPort) { - t.Errorf("want %s:%d, have %s:%d", ip, port, gotIP, gotPort) - } -} - -func TestParseIPPortInvalid(t *testing.T) { - testcases := []string{ - "", - "C0A80016", - "C0A800:1234", - "FOOBARBA:1234", - "C0A80016:0CEA:1234", - } - - for _, s := range testcases { - ip, port, err := parseIPPort(s) - if ip != nil || port != uint16(0) || err == nil { - t.Errorf("Expected error for input %s, have ip = %s, port = %v, err = %v", s, ip, port, err) - } - } -} - -func TestParseIPPortIPv6(t *testing.T) { - ip := net.ParseIP("dead:beef::1") - port := uint16(8080) - - gotIP, gotPort, err := parseIPPort("[DEAD:BEEF:0000:0000:0000:0000:0000:0001]:1F90") - if err != nil { - t.Fatal(err) - } - if !(gotIP.Equal(ip) && port == gotPort) { - t.Errorf("want %s:%d, have %s:%d", ip, port, gotIP, gotPort) - } -} - -func TestIPVSBackendStatus(t *testing.T) { - backendStats, err := FS("fixtures").NewIPVSBackendStatus() - if err != nil { - t.Fatal(err) - } - if want, have := len(expectedIPVSBackendStatuses), len(backendStats); want != have { - t.Fatalf("want %d backend statuses, have %d", want, have) - } - - for idx, expect := range expectedIPVSBackendStatuses { - if !backendStats[idx].LocalAddress.Equal(expect.LocalAddress) { - t.Errorf("want LocalAddress %s, have %s", expect.LocalAddress, backendStats[idx].LocalAddress) - } - if backendStats[idx].LocalPort != expect.LocalPort { - t.Errorf("want LocalPort %d, have %d", expect.LocalPort, backendStats[idx].LocalPort) - } - if !backendStats[idx].RemoteAddress.Equal(expect.RemoteAddress) { - t.Errorf("want RemoteAddress %s, have %s", expect.RemoteAddress, backendStats[idx].RemoteAddress) - } - if backendStats[idx].RemotePort != expect.RemotePort { - t.Errorf("want RemotePort %d, have %d", expect.RemotePort, backendStats[idx].RemotePort) - } - if backendStats[idx].Proto != expect.Proto { - t.Errorf("want Proto %s, have %s", expect.Proto, backendStats[idx].Proto) - } - if backendStats[idx].Weight != expect.Weight { - t.Errorf("want Weight %d, have %d", expect.Weight, backendStats[idx].Weight) - } - if backendStats[idx].ActiveConn != expect.ActiveConn { - t.Errorf("want ActiveConn %d, have %d", expect.ActiveConn, backendStats[idx].ActiveConn) - } - if backendStats[idx].InactConn != expect.InactConn { - t.Errorf("want InactConn %d, have %d", expect.InactConn, backendStats[idx].InactConn) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/mdstat.go b/vendor/github.com/prometheus/procfs/mdstat.go index d7a248c0df..9dc19583d8 100644 --- a/vendor/github.com/prometheus/procfs/mdstat.go +++ b/vendor/github.com/prometheus/procfs/mdstat.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus 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 procfs import ( diff --git a/vendor/github.com/prometheus/procfs/mdstat_test.go b/vendor/github.com/prometheus/procfs/mdstat_test.go deleted file mode 100644 index fa463c2fb1..0000000000 --- a/vendor/github.com/prometheus/procfs/mdstat_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package procfs - -import ( - "testing" -) - -func TestMDStat(t *testing.T) { - mdStates, err := FS("fixtures").ParseMDStat() - if err != nil { - t.Fatalf("parsing of reference-file failed entirely: %s", err) - } - - refs := map[string]MDStat{ - "md3": {"md3", "active", 8, 8, 5853468288, 5853468288}, - "md127": {"md127", "active", 2, 2, 312319552, 312319552}, - "md0": {"md0", "active", 2, 2, 248896, 248896}, - "md4": {"md4", "inactive", 2, 2, 4883648, 4883648}, - "md6": {"md6", "active", 1, 2, 195310144, 16775552}, - "md8": {"md8", "active", 2, 2, 195310144, 16775552}, - "md7": {"md7", "active", 3, 4, 7813735424, 7813735424}, - } - - if want, have := len(refs), len(mdStates); want != have { - t.Errorf("want %d parsed md-devices, have %d", want, have) - } - for _, md := range mdStates { - if want, have := refs[md.Name], md; want != have { - t.Errorf("%s: want %v, have %v", md.Name, want, have) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/mountstats.go b/vendor/github.com/prometheus/procfs/mountstats.go index 6b2b0ba9d9..e95ddbc67c 100644 --- a/vendor/github.com/prometheus/procfs/mountstats.go +++ b/vendor/github.com/prometheus/procfs/mountstats.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus 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 procfs // While implementing parsing of /proc/[pid]/mountstats, this blog was used diff --git a/vendor/github.com/prometheus/procfs/mountstats_test.go b/vendor/github.com/prometheus/procfs/mountstats_test.go deleted file mode 100644 index 8f04f5355c..0000000000 --- a/vendor/github.com/prometheus/procfs/mountstats_test.go +++ /dev/null @@ -1,273 +0,0 @@ -package procfs - -import ( - "fmt" - "reflect" - "strings" - "testing" - "time" -) - -func TestMountStats(t *testing.T) { - tests := []struct { - name string - s string - mounts []*Mount - invalid bool - }{ - { - name: "no devices", - s: `hello`, - }, - { - name: "device has too few fields", - s: `device foo`, - invalid: true, - }, - { - name: "device incorrect format", - s: `device rootfs BAD on / with fstype rootfs`, - invalid: true, - }, - { - name: "device incorrect format", - s: `device rootfs mounted BAD / with fstype rootfs`, - invalid: true, - }, - { - name: "device incorrect format", - s: `device rootfs mounted on / BAD fstype rootfs`, - invalid: true, - }, - { - name: "device incorrect format", - s: `device rootfs mounted on / with BAD rootfs`, - invalid: true, - }, - { - name: "device rootfs cannot have stats", - s: `device rootfs mounted on / with fstype rootfs stats`, - invalid: true, - }, - { - name: "NFSv4 device with too little info", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nhello", - invalid: true, - }, - { - name: "NFSv4 device with bad bytes", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nbytes: 0", - invalid: true, - }, - { - name: "NFSv4 device with bad events", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nevents: 0", - invalid: true, - }, - { - name: "NFSv4 device with bad per-op stats", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nper-op statistics\nFOO 0", - invalid: true, - }, - { - name: "NFSv4 device with bad transport stats", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nxprt: tcp", - invalid: true, - }, - { - name: "NFSv4 device with bad transport version", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=foo\nxprt: tcp 0", - invalid: true, - }, - { - name: "NFSv4 device with bad transport stats version 1.0", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.0\nxprt: tcp 0 0 0 0 0 0 0 0 0 0 0 0 0", - invalid: true, - }, - { - name: "NFSv4 device with bad transport stats version 1.1", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs4 statvers=1.1\nxprt: tcp 0 0 0 0 0 0 0 0 0 0", - invalid: true, - }, - { - name: "NFSv3 device with transport stats version 1.0 OK", - s: "device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs statvers=1.0\nxprt: tcp 1 2 3 4 5 6 7 8 9 10", - mounts: []*Mount{{ - Device: "192.168.1.1:/srv", - Mount: "/mnt/nfs", - Type: "nfs", - Stats: &MountStatsNFS{ - StatVersion: "1.0", - Transport: NFSTransportStats{ - Port: 1, - Bind: 2, - Connect: 3, - ConnectIdleTime: 4, - IdleTime: 5 * time.Second, - Sends: 6, - Receives: 7, - BadTransactionIDs: 8, - CumulativeActiveRequests: 9, - CumulativeBacklog: 10, - }, - }, - }}, - }, - { - name: "device rootfs OK", - s: `device rootfs mounted on / with fstype rootfs`, - mounts: []*Mount{{ - Device: "rootfs", - Mount: "/", - Type: "rootfs", - }}, - }, - { - name: "NFSv3 device with minimal stats OK", - s: `device 192.168.1.1:/srv mounted on /mnt/nfs with fstype nfs statvers=1.1`, - mounts: []*Mount{{ - Device: "192.168.1.1:/srv", - Mount: "/mnt/nfs", - Type: "nfs", - Stats: &MountStatsNFS{ - StatVersion: "1.1", - }, - }}, - }, - { - name: "fixtures OK", - mounts: []*Mount{ - { - Device: "rootfs", - Mount: "/", - Type: "rootfs", - }, - { - Device: "sysfs", - Mount: "/sys", - Type: "sysfs", - }, - { - Device: "proc", - Mount: "/proc", - Type: "proc", - }, - { - Device: "/dev/sda1", - Mount: "/", - Type: "ext4", - }, - { - Device: "192.168.1.1:/srv/test", - Mount: "/mnt/nfs/test", - Type: "nfs4", - Stats: &MountStatsNFS{ - StatVersion: "1.1", - Age: 13968 * time.Second, - Bytes: NFSBytesStats{ - Read: 1207640230, - ReadTotal: 1210214218, - ReadPages: 295483, - }, - Events: NFSEventsStats{ - InodeRevalidate: 52, - DnodeRevalidate: 226, - VFSOpen: 1, - VFSLookup: 13, - VFSAccess: 398, - VFSReadPages: 331, - VFSWritePages: 47, - VFSFlush: 77, - VFSFileRelease: 77, - }, - Operations: []NFSOperationStats{ - { - Operation: "NULL", - }, - { - Operation: "READ", - Requests: 1298, - Transmissions: 1298, - BytesSent: 207680, - BytesReceived: 1210292152, - CumulativeQueueTime: 6 * time.Millisecond, - CumulativeTotalResponseTime: 79386 * time.Millisecond, - CumulativeTotalRequestTime: 79407 * time.Millisecond, - }, - { - Operation: "WRITE", - }, - }, - Transport: NFSTransportStats{ - Port: 832, - Connect: 1, - IdleTime: 11 * time.Second, - Sends: 6428, - Receives: 6428, - CumulativeActiveRequests: 12154, - MaximumRPCSlotsUsed: 24, - CumulativeSendingQueue: 26, - CumulativePendingQueue: 5726, - }, - }, - }, - }, - }, - } - - for i, tt := range tests { - t.Logf("[%02d] test %q", i, tt.name) - - var mounts []*Mount - var err error - - if tt.s != "" { - mounts, err = parseMountStats(strings.NewReader(tt.s)) - } else { - proc, e := FS("fixtures").NewProc(26231) - if e != nil { - t.Fatalf("failed to create proc: %v", err) - } - - mounts, err = proc.MountStats() - } - - if tt.invalid && err == nil { - t.Error("expected an error, but none occurred") - } - if !tt.invalid && err != nil { - t.Errorf("unexpected error: %v", err) - } - - if want, have := tt.mounts, mounts; !reflect.DeepEqual(want, have) { - t.Errorf("mounts:\nwant:\n%v\nhave:\n%v", mountsStr(want), mountsStr(have)) - } - } -} - -func mountsStr(mounts []*Mount) string { - var out string - for i, m := range mounts { - out += fmt.Sprintf("[%d] %q on %q (%q)", i, m.Device, m.Mount, m.Type) - - stats, ok := m.Stats.(*MountStatsNFS) - if !ok { - out += "\n" - continue - } - - out += fmt.Sprintf("\n\t- v%s, age: %s", stats.StatVersion, stats.Age) - out += fmt.Sprintf("\n\t- bytes: %v", stats.Bytes) - out += fmt.Sprintf("\n\t- events: %v", stats.Events) - out += fmt.Sprintf("\n\t- transport: %v", stats.Transport) - out += fmt.Sprintf("\n\t- per-operation stats:") - - for _, o := range stats.Operations { - out += fmt.Sprintf("\n\t\t- %v", o) - } - - out += "\n" - } - - return out -} diff --git a/vendor/github.com/prometheus/procfs/net_dev.go b/vendor/github.com/prometheus/procfs/net_dev.go new file mode 100644 index 0000000000..3f2523371a --- /dev/null +++ b/vendor/github.com/prometheus/procfs/net_dev.go @@ -0,0 +1,216 @@ +// Copyright 2018 The Prometheus 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 procfs + +import ( + "bufio" + "errors" + "os" + "sort" + "strconv" + "strings" +) + +// NetDevLine is single line parsed from /proc/net/dev or /proc/[pid]/net/dev. +type NetDevLine struct { + Name string `json:"name"` // The name of the interface. + RxBytes uint64 `json:"rx_bytes"` // Cumulative count of bytes received. + RxPackets uint64 `json:"rx_packets"` // Cumulative count of packets received. + RxErrors uint64 `json:"rx_errors"` // Cumulative count of receive errors encountered. + RxDropped uint64 `json:"rx_dropped"` // Cumulative count of packets dropped while receiving. + RxFIFO uint64 `json:"rx_fifo"` // Cumulative count of FIFO buffer errors. + RxFrame uint64 `json:"rx_frame"` // Cumulative count of packet framing errors. + RxCompressed uint64 `json:"rx_compressed"` // Cumulative count of compressed packets received by the device driver. + RxMulticast uint64 `json:"rx_multicast"` // Cumulative count of multicast frames received by the device driver. + TxBytes uint64 `json:"tx_bytes"` // Cumulative count of bytes transmitted. + TxPackets uint64 `json:"tx_packets"` // Cumulative count of packets transmitted. + TxErrors uint64 `json:"tx_errors"` // Cumulative count of transmit errors encountered. + TxDropped uint64 `json:"tx_dropped"` // Cumulative count of packets dropped while transmitting. + TxFIFO uint64 `json:"tx_fifo"` // Cumulative count of FIFO buffer errors. + TxCollisions uint64 `json:"tx_collisions"` // Cumulative count of collisions detected on the interface. + TxCarrier uint64 `json:"tx_carrier"` // Cumulative count of carrier losses detected by the device driver. + TxCompressed uint64 `json:"tx_compressed"` // Cumulative count of compressed packets transmitted by the device driver. +} + +// NetDev is parsed from /proc/net/dev or /proc/[pid]/net/dev. The map keys +// are interface names. +type NetDev map[string]NetDevLine + +// NewNetDev returns kernel/system statistics read from /proc/net/dev. +func NewNetDev() (NetDev, error) { + fs, err := NewFS(DefaultMountPoint) + if err != nil { + return nil, err + } + + return fs.NewNetDev() +} + +// NewNetDev returns kernel/system statistics read from /proc/net/dev. +func (fs FS) NewNetDev() (NetDev, error) { + return newNetDev(fs.Path("net/dev")) +} + +// NewNetDev returns kernel/system statistics read from /proc/[pid]/net/dev. +func (p Proc) NewNetDev() (NetDev, error) { + return newNetDev(p.path("net/dev")) +} + +// newNetDev creates a new NetDev from the contents of the given file. +func newNetDev(file string) (NetDev, error) { + f, err := os.Open(file) + if err != nil { + return NetDev{}, err + } + defer f.Close() + + nd := NetDev{} + s := bufio.NewScanner(f) + for n := 0; s.Scan(); n++ { + // Skip the 2 header lines. + if n < 2 { + continue + } + + line, err := nd.parseLine(s.Text()) + if err != nil { + return nd, err + } + + nd[line.Name] = *line + } + + return nd, s.Err() +} + +// parseLine parses a single line from the /proc/net/dev file. Header lines +// must be filtered prior to calling this method. +func (nd NetDev) parseLine(rawLine string) (*NetDevLine, error) { + parts := strings.SplitN(rawLine, ":", 2) + if len(parts) != 2 { + return nil, errors.New("invalid net/dev line, missing colon") + } + fields := strings.Fields(strings.TrimSpace(parts[1])) + + var err error + line := &NetDevLine{} + + // Interface Name + line.Name = strings.TrimSpace(parts[0]) + if line.Name == "" { + return nil, errors.New("invalid net/dev line, empty interface name") + } + + // RX + line.RxBytes, err = strconv.ParseUint(fields[0], 10, 64) + if err != nil { + return nil, err + } + line.RxPackets, err = strconv.ParseUint(fields[1], 10, 64) + if err != nil { + return nil, err + } + line.RxErrors, err = strconv.ParseUint(fields[2], 10, 64) + if err != nil { + return nil, err + } + line.RxDropped, err = strconv.ParseUint(fields[3], 10, 64) + if err != nil { + return nil, err + } + line.RxFIFO, err = strconv.ParseUint(fields[4], 10, 64) + if err != nil { + return nil, err + } + line.RxFrame, err = strconv.ParseUint(fields[5], 10, 64) + if err != nil { + return nil, err + } + line.RxCompressed, err = strconv.ParseUint(fields[6], 10, 64) + if err != nil { + return nil, err + } + line.RxMulticast, err = strconv.ParseUint(fields[7], 10, 64) + if err != nil { + return nil, err + } + + // TX + line.TxBytes, err = strconv.ParseUint(fields[8], 10, 64) + if err != nil { + return nil, err + } + line.TxPackets, err = strconv.ParseUint(fields[9], 10, 64) + if err != nil { + return nil, err + } + line.TxErrors, err = strconv.ParseUint(fields[10], 10, 64) + if err != nil { + return nil, err + } + line.TxDropped, err = strconv.ParseUint(fields[11], 10, 64) + if err != nil { + return nil, err + } + line.TxFIFO, err = strconv.ParseUint(fields[12], 10, 64) + if err != nil { + return nil, err + } + line.TxCollisions, err = strconv.ParseUint(fields[13], 10, 64) + if err != nil { + return nil, err + } + line.TxCarrier, err = strconv.ParseUint(fields[14], 10, 64) + if err != nil { + return nil, err + } + line.TxCompressed, err = strconv.ParseUint(fields[15], 10, 64) + if err != nil { + return nil, err + } + + return line, nil +} + +// Total aggregates the values across interfaces and returns a new NetDevLine. +// The Name field will be a sorted comma separated list of interface names. +func (nd NetDev) Total() NetDevLine { + total := NetDevLine{} + + names := make([]string, 0, len(nd)) + for _, ifc := range nd { + names = append(names, ifc.Name) + total.RxBytes += ifc.RxBytes + total.RxPackets += ifc.RxPackets + total.RxPackets += ifc.RxPackets + total.RxErrors += ifc.RxErrors + total.RxDropped += ifc.RxDropped + total.RxFIFO += ifc.RxFIFO + total.RxFrame += ifc.RxFrame + total.RxCompressed += ifc.RxCompressed + total.RxMulticast += ifc.RxMulticast + total.TxBytes += ifc.TxBytes + total.TxPackets += ifc.TxPackets + total.TxErrors += ifc.TxErrors + total.TxDropped += ifc.TxDropped + total.TxFIFO += ifc.TxFIFO + total.TxCollisions += ifc.TxCollisions + total.TxCarrier += ifc.TxCarrier + total.TxCompressed += ifc.TxCompressed + } + sort.Strings(names) + total.Name = strings.Join(names, ", ") + + return total +} diff --git a/vendor/github.com/prometheus/procfs/nfs/nfs.go b/vendor/github.com/prometheus/procfs/nfs/nfs.go new file mode 100644 index 0000000000..651bf68195 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/nfs/nfs.go @@ -0,0 +1,263 @@ +// Copyright 2018 The Prometheus 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 nfs implements parsing of /proc/net/rpc/nfsd. +// Fields are documented in https://www.svennd.be/nfsd-stats-explained-procnetrpcnfsd/ +package nfs + +// ReplyCache models the "rc" line. +type ReplyCache struct { + Hits uint64 + Misses uint64 + NoCache uint64 +} + +// FileHandles models the "fh" line. +type FileHandles struct { + Stale uint64 + TotalLookups uint64 + AnonLookups uint64 + DirNoCache uint64 + NoDirNoCache uint64 +} + +// InputOutput models the "io" line. +type InputOutput struct { + Read uint64 + Write uint64 +} + +// Threads models the "th" line. +type Threads struct { + Threads uint64 + FullCnt uint64 +} + +// ReadAheadCache models the "ra" line. +type ReadAheadCache struct { + CacheSize uint64 + CacheHistogram []uint64 + NotFound uint64 +} + +// Network models the "net" line. +type Network struct { + NetCount uint64 + UDPCount uint64 + TCPCount uint64 + TCPConnect uint64 +} + +// ClientRPC models the nfs "rpc" line. +type ClientRPC struct { + RPCCount uint64 + Retransmissions uint64 + AuthRefreshes uint64 +} + +// ServerRPC models the nfsd "rpc" line. +type ServerRPC struct { + RPCCount uint64 + BadCnt uint64 + BadFmt uint64 + BadAuth uint64 + BadcInt uint64 +} + +// V2Stats models the "proc2" line. +type V2Stats struct { + Null uint64 + GetAttr uint64 + SetAttr uint64 + Root uint64 + Lookup uint64 + ReadLink uint64 + Read uint64 + WrCache uint64 + Write uint64 + Create uint64 + Remove uint64 + Rename uint64 + Link uint64 + SymLink uint64 + MkDir uint64 + RmDir uint64 + ReadDir uint64 + FsStat uint64 +} + +// V3Stats models the "proc3" line. +type V3Stats struct { + Null uint64 + GetAttr uint64 + SetAttr uint64 + Lookup uint64 + Access uint64 + ReadLink uint64 + Read uint64 + Write uint64 + Create uint64 + MkDir uint64 + SymLink uint64 + MkNod uint64 + Remove uint64 + RmDir uint64 + Rename uint64 + Link uint64 + ReadDir uint64 + ReadDirPlus uint64 + FsStat uint64 + FsInfo uint64 + PathConf uint64 + Commit uint64 +} + +// ClientV4Stats models the nfs "proc4" line. +type ClientV4Stats struct { + Null uint64 + Read uint64 + Write uint64 + Commit uint64 + Open uint64 + OpenConfirm uint64 + OpenNoattr uint64 + OpenDowngrade uint64 + Close uint64 + Setattr uint64 + FsInfo uint64 + Renew uint64 + SetClientID uint64 + SetClientIDConfirm uint64 + Lock uint64 + Lockt uint64 + Locku uint64 + Access uint64 + Getattr uint64 + Lookup uint64 + LookupRoot uint64 + Remove uint64 + Rename uint64 + Link uint64 + Symlink uint64 + Create uint64 + Pathconf uint64 + StatFs uint64 + ReadLink uint64 + ReadDir uint64 + ServerCaps uint64 + DelegReturn uint64 + GetACL uint64 + SetACL uint64 + FsLocations uint64 + ReleaseLockowner uint64 + Secinfo uint64 + FsidPresent uint64 + ExchangeID uint64 + CreateSession uint64 + DestroySession uint64 + Sequence uint64 + GetLeaseTime uint64 + ReclaimComplete uint64 + LayoutGet uint64 + GetDeviceInfo uint64 + LayoutCommit uint64 + LayoutReturn uint64 + SecinfoNoName uint64 + TestStateID uint64 + FreeStateID uint64 + GetDeviceList uint64 + BindConnToSession uint64 + DestroyClientID uint64 + Seek uint64 + Allocate uint64 + DeAllocate uint64 + LayoutStats uint64 + Clone uint64 +} + +// ServerV4Stats models the nfsd "proc4" line. +type ServerV4Stats struct { + Null uint64 + Compound uint64 +} + +// V4Ops models the "proc4ops" line: NFSv4 operations +// Variable list, see: +// v4.0 https://tools.ietf.org/html/rfc3010 (38 operations) +// v4.1 https://tools.ietf.org/html/rfc5661 (58 operations) +// v4.2 https://tools.ietf.org/html/draft-ietf-nfsv4-minorversion2-41 (71 operations) +type V4Ops struct { + //Values uint64 // Variable depending on v4.x sub-version. TODO: Will this always at least include the fields in this struct? + Op0Unused uint64 + Op1Unused uint64 + Op2Future uint64 + Access uint64 + Close uint64 + Commit uint64 + Create uint64 + DelegPurge uint64 + DelegReturn uint64 + GetAttr uint64 + GetFH uint64 + Link uint64 + Lock uint64 + Lockt uint64 + Locku uint64 + Lookup uint64 + LookupRoot uint64 + Nverify uint64 + Open uint64 + OpenAttr uint64 + OpenConfirm uint64 + OpenDgrd uint64 + PutFH uint64 + PutPubFH uint64 + PutRootFH uint64 + Read uint64 + ReadDir uint64 + ReadLink uint64 + Remove uint64 + Rename uint64 + Renew uint64 + RestoreFH uint64 + SaveFH uint64 + SecInfo uint64 + SetAttr uint64 + Verify uint64 + Write uint64 + RelLockOwner uint64 +} + +// ClientRPCStats models all stats from /proc/net/rpc/nfs. +type ClientRPCStats struct { + Network Network + ClientRPC ClientRPC + V2Stats V2Stats + V3Stats V3Stats + ClientV4Stats ClientV4Stats +} + +// ServerRPCStats models all stats from /proc/net/rpc/nfsd. +type ServerRPCStats struct { + ReplyCache ReplyCache + FileHandles FileHandles + InputOutput InputOutput + Threads Threads + ReadAheadCache ReadAheadCache + Network Network + ServerRPC ServerRPC + V2Stats V2Stats + V3Stats V3Stats + ServerV4Stats ServerV4Stats + V4Ops V4Ops +} diff --git a/vendor/github.com/prometheus/procfs/nfs/parse.go b/vendor/github.com/prometheus/procfs/nfs/parse.go new file mode 100644 index 0000000000..95a83cc5bc --- /dev/null +++ b/vendor/github.com/prometheus/procfs/nfs/parse.go @@ -0,0 +1,317 @@ +// Copyright 2018 The Prometheus 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 nfs + +import ( + "fmt" +) + +func parseReplyCache(v []uint64) (ReplyCache, error) { + if len(v) != 3 { + return ReplyCache{}, fmt.Errorf("invalid ReplyCache line %q", v) + } + + return ReplyCache{ + Hits: v[0], + Misses: v[1], + NoCache: v[2], + }, nil +} + +func parseFileHandles(v []uint64) (FileHandles, error) { + if len(v) != 5 { + return FileHandles{}, fmt.Errorf("invalid FileHandles, line %q", v) + } + + return FileHandles{ + Stale: v[0], + TotalLookups: v[1], + AnonLookups: v[2], + DirNoCache: v[3], + NoDirNoCache: v[4], + }, nil +} + +func parseInputOutput(v []uint64) (InputOutput, error) { + if len(v) != 2 { + return InputOutput{}, fmt.Errorf("invalid InputOutput line %q", v) + } + + return InputOutput{ + Read: v[0], + Write: v[1], + }, nil +} + +func parseThreads(v []uint64) (Threads, error) { + if len(v) != 2 { + return Threads{}, fmt.Errorf("invalid Threads line %q", v) + } + + return Threads{ + Threads: v[0], + FullCnt: v[1], + }, nil +} + +func parseReadAheadCache(v []uint64) (ReadAheadCache, error) { + if len(v) != 12 { + return ReadAheadCache{}, fmt.Errorf("invalid ReadAheadCache line %q", v) + } + + return ReadAheadCache{ + CacheSize: v[0], + CacheHistogram: v[1:11], + NotFound: v[11], + }, nil +} + +func parseNetwork(v []uint64) (Network, error) { + if len(v) != 4 { + return Network{}, fmt.Errorf("invalid Network line %q", v) + } + + return Network{ + NetCount: v[0], + UDPCount: v[1], + TCPCount: v[2], + TCPConnect: v[3], + }, nil +} + +func parseServerRPC(v []uint64) (ServerRPC, error) { + if len(v) != 5 { + return ServerRPC{}, fmt.Errorf("invalid RPC line %q", v) + } + + return ServerRPC{ + RPCCount: v[0], + BadCnt: v[1], + BadFmt: v[2], + BadAuth: v[3], + BadcInt: v[4], + }, nil +} + +func parseClientRPC(v []uint64) (ClientRPC, error) { + if len(v) != 3 { + return ClientRPC{}, fmt.Errorf("invalid RPC line %q", v) + } + + return ClientRPC{ + RPCCount: v[0], + Retransmissions: v[1], + AuthRefreshes: v[2], + }, nil +} + +func parseV2Stats(v []uint64) (V2Stats, error) { + values := int(v[0]) + if len(v[1:]) != values || values != 18 { + return V2Stats{}, fmt.Errorf("invalid V2Stats line %q", v) + } + + return V2Stats{ + Null: v[1], + GetAttr: v[2], + SetAttr: v[3], + Root: v[4], + Lookup: v[5], + ReadLink: v[6], + Read: v[7], + WrCache: v[8], + Write: v[9], + Create: v[10], + Remove: v[11], + Rename: v[12], + Link: v[13], + SymLink: v[14], + MkDir: v[15], + RmDir: v[16], + ReadDir: v[17], + FsStat: v[18], + }, nil +} + +func parseV3Stats(v []uint64) (V3Stats, error) { + values := int(v[0]) + if len(v[1:]) != values || values != 22 { + return V3Stats{}, fmt.Errorf("invalid V3Stats line %q", v) + } + + return V3Stats{ + Null: v[1], + GetAttr: v[2], + SetAttr: v[3], + Lookup: v[4], + Access: v[5], + ReadLink: v[6], + Read: v[7], + Write: v[8], + Create: v[9], + MkDir: v[10], + SymLink: v[11], + MkNod: v[12], + Remove: v[13], + RmDir: v[14], + Rename: v[15], + Link: v[16], + ReadDir: v[17], + ReadDirPlus: v[18], + FsStat: v[19], + FsInfo: v[20], + PathConf: v[21], + Commit: v[22], + }, nil +} + +func parseClientV4Stats(v []uint64) (ClientV4Stats, error) { + values := int(v[0]) + if len(v[1:]) != values { + return ClientV4Stats{}, fmt.Errorf("invalid ClientV4Stats line %q", v) + } + + // This function currently supports mapping 59 NFS v4 client stats. Older + // kernels may emit fewer stats, so we must detect this and pad out the + // values to match the expected slice size. + if values < 59 { + newValues := make([]uint64, 60) + copy(newValues, v) + v = newValues + } + + return ClientV4Stats{ + Null: v[1], + Read: v[2], + Write: v[3], + Commit: v[4], + Open: v[5], + OpenConfirm: v[6], + OpenNoattr: v[7], + OpenDowngrade: v[8], + Close: v[9], + Setattr: v[10], + FsInfo: v[11], + Renew: v[12], + SetClientID: v[13], + SetClientIDConfirm: v[14], + Lock: v[15], + Lockt: v[16], + Locku: v[17], + Access: v[18], + Getattr: v[19], + Lookup: v[20], + LookupRoot: v[21], + Remove: v[22], + Rename: v[23], + Link: v[24], + Symlink: v[25], + Create: v[26], + Pathconf: v[27], + StatFs: v[28], + ReadLink: v[29], + ReadDir: v[30], + ServerCaps: v[31], + DelegReturn: v[32], + GetACL: v[33], + SetACL: v[34], + FsLocations: v[35], + ReleaseLockowner: v[36], + Secinfo: v[37], + FsidPresent: v[38], + ExchangeID: v[39], + CreateSession: v[40], + DestroySession: v[41], + Sequence: v[42], + GetLeaseTime: v[43], + ReclaimComplete: v[44], + LayoutGet: v[45], + GetDeviceInfo: v[46], + LayoutCommit: v[47], + LayoutReturn: v[48], + SecinfoNoName: v[49], + TestStateID: v[50], + FreeStateID: v[51], + GetDeviceList: v[52], + BindConnToSession: v[53], + DestroyClientID: v[54], + Seek: v[55], + Allocate: v[56], + DeAllocate: v[57], + LayoutStats: v[58], + Clone: v[59], + }, nil +} + +func parseServerV4Stats(v []uint64) (ServerV4Stats, error) { + values := int(v[0]) + if len(v[1:]) != values || values != 2 { + return ServerV4Stats{}, fmt.Errorf("invalid V4Stats line %q", v) + } + + return ServerV4Stats{ + Null: v[1], + Compound: v[2], + }, nil +} + +func parseV4Ops(v []uint64) (V4Ops, error) { + values := int(v[0]) + if len(v[1:]) != values || values < 39 { + return V4Ops{}, fmt.Errorf("invalid V4Ops line %q", v) + } + + stats := V4Ops{ + Op0Unused: v[1], + Op1Unused: v[2], + Op2Future: v[3], + Access: v[4], + Close: v[5], + Commit: v[6], + Create: v[7], + DelegPurge: v[8], + DelegReturn: v[9], + GetAttr: v[10], + GetFH: v[11], + Link: v[12], + Lock: v[13], + Lockt: v[14], + Locku: v[15], + Lookup: v[16], + LookupRoot: v[17], + Nverify: v[18], + Open: v[19], + OpenAttr: v[20], + OpenConfirm: v[21], + OpenDgrd: v[22], + PutFH: v[23], + PutPubFH: v[24], + PutRootFH: v[25], + Read: v[26], + ReadDir: v[27], + ReadLink: v[28], + Remove: v[29], + Rename: v[30], + Renew: v[31], + RestoreFH: v[32], + SaveFH: v[33], + SecInfo: v[34], + SetAttr: v[35], + Verify: v[36], + Write: v[37], + RelLockOwner: v[38], + } + + return stats, nil +} diff --git a/vendor/github.com/prometheus/procfs/nfs/parse_nfs.go b/vendor/github.com/prometheus/procfs/nfs/parse_nfs.go new file mode 100644 index 0000000000..c0d3a5ad9b --- /dev/null +++ b/vendor/github.com/prometheus/procfs/nfs/parse_nfs.go @@ -0,0 +1,67 @@ +// Copyright 2018 The Prometheus 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 nfs + +import ( + "bufio" + "fmt" + "io" + "strings" + + "github.com/prometheus/procfs/internal/util" +) + +// ParseClientRPCStats returns stats read from /proc/net/rpc/nfs +func ParseClientRPCStats(r io.Reader) (*ClientRPCStats, error) { + stats := &ClientRPCStats{} + + scanner := bufio.NewScanner(r) + for scanner.Scan() { + line := scanner.Text() + parts := strings.Fields(scanner.Text()) + // require at least + if len(parts) < 2 { + return nil, fmt.Errorf("invalid NFS metric line %q", line) + } + + values, err := util.ParseUint64s(parts[1:]) + if err != nil { + return nil, fmt.Errorf("error parsing NFS metric line: %s", err) + } + + switch metricLine := parts[0]; metricLine { + case "net": + stats.Network, err = parseNetwork(values) + case "rpc": + stats.ClientRPC, err = parseClientRPC(values) + case "proc2": + stats.V2Stats, err = parseV2Stats(values) + case "proc3": + stats.V3Stats, err = parseV3Stats(values) + case "proc4": + stats.ClientV4Stats, err = parseClientV4Stats(values) + default: + return nil, fmt.Errorf("unknown NFS metric line %q", metricLine) + } + if err != nil { + return nil, fmt.Errorf("errors parsing NFS metric line: %s", err) + } + } + + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("error scanning NFS file: %s", err) + } + + return stats, nil +} diff --git a/vendor/github.com/prometheus/procfs/nfs/parse_nfsd.go b/vendor/github.com/prometheus/procfs/nfs/parse_nfsd.go new file mode 100644 index 0000000000..57bb4a3585 --- /dev/null +++ b/vendor/github.com/prometheus/procfs/nfs/parse_nfsd.go @@ -0,0 +1,89 @@ +// Copyright 2018 The Prometheus 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 nfs + +import ( + "bufio" + "fmt" + "io" + "strings" + + "github.com/prometheus/procfs/internal/util" +) + +// ParseServerRPCStats returns stats read from /proc/net/rpc/nfsd +func ParseServerRPCStats(r io.Reader) (*ServerRPCStats, error) { + stats := &ServerRPCStats{} + + scanner := bufio.NewScanner(r) + for scanner.Scan() { + line := scanner.Text() + parts := strings.Fields(scanner.Text()) + // require at least + if len(parts) < 2 { + return nil, fmt.Errorf("invalid NFSd metric line %q", line) + } + label := parts[0] + + var values []uint64 + var err error + if label == "th" { + if len(parts) < 3 { + return nil, fmt.Errorf("invalid NFSd th metric line %q", line) + } + values, err = util.ParseUint64s(parts[1:3]) + } else { + values, err = util.ParseUint64s(parts[1:]) + } + if err != nil { + return nil, fmt.Errorf("error parsing NFSd metric line: %s", err) + } + + switch metricLine := parts[0]; metricLine { + case "rc": + stats.ReplyCache, err = parseReplyCache(values) + case "fh": + stats.FileHandles, err = parseFileHandles(values) + case "io": + stats.InputOutput, err = parseInputOutput(values) + case "th": + stats.Threads, err = parseThreads(values) + case "ra": + stats.ReadAheadCache, err = parseReadAheadCache(values) + case "net": + stats.Network, err = parseNetwork(values) + case "rpc": + stats.ServerRPC, err = parseServerRPC(values) + case "proc2": + stats.V2Stats, err = parseV2Stats(values) + case "proc3": + stats.V3Stats, err = parseV3Stats(values) + case "proc4": + stats.ServerV4Stats, err = parseServerV4Stats(values) + case "proc4ops": + stats.V4Ops, err = parseV4Ops(values) + default: + return nil, fmt.Errorf("unknown NFSd metric line %q", metricLine) + } + if err != nil { + return nil, fmt.Errorf("errors parsing NFSd metric line: %s", err) + } + } + + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("error scanning NFSd file: %s", err) + } + + return stats, nil +} diff --git a/vendor/github.com/prometheus/procfs/proc.go b/vendor/github.com/prometheus/procfs/proc.go index 8717e1fe0d..7cf5b8acf9 100644 --- a/vendor/github.com/prometheus/procfs/proc.go +++ b/vendor/github.com/prometheus/procfs/proc.go @@ -1,6 +1,20 @@ +// Copyright 2018 The Prometheus 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 procfs import ( + "bytes" "fmt" "io/ioutil" "os" @@ -113,7 +127,7 @@ func (p Proc) CmdLine() ([]string, error) { return []string{}, nil } - return strings.Split(string(data[:len(data)-1]), string(byte(0))), nil + return strings.Split(string(bytes.TrimRight(data, string("\x00"))), string(byte(0))), nil } // Comm returns the command name of a process. diff --git a/vendor/github.com/prometheus/procfs/proc_io.go b/vendor/github.com/prometheus/procfs/proc_io.go index b4e31d7ba3..0251c83bfe 100644 --- a/vendor/github.com/prometheus/procfs/proc_io.go +++ b/vendor/github.com/prometheus/procfs/proc_io.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus 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 procfs import ( @@ -47,9 +60,6 @@ func (p Proc) NewIO() (ProcIO, error) { _, err = fmt.Sscanf(string(data), ioFormat, &pio.RChar, &pio.WChar, &pio.SyscR, &pio.SyscW, &pio.ReadBytes, &pio.WriteBytes, &pio.CancelledWriteBytes) - if err != nil { - return pio, err - } - return pio, nil + return pio, err } diff --git a/vendor/github.com/prometheus/procfs/proc_io_test.go b/vendor/github.com/prometheus/procfs/proc_io_test.go deleted file mode 100644 index 3aa1a1293f..0000000000 --- a/vendor/github.com/prometheus/procfs/proc_io_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package procfs - -import "testing" - -func TestProcIO(t *testing.T) { - p, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - - s, err := p.NewIO() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int64 - have int64 - }{ - {name: "RChar", want: 750339, have: int64(s.RChar)}, - {name: "WChar", want: 818609, have: int64(s.WChar)}, - {name: "SyscR", want: 7405, have: int64(s.SyscR)}, - {name: "SyscW", want: 5245, have: int64(s.SyscW)}, - {name: "ReadBytes", want: 1024, have: int64(s.ReadBytes)}, - {name: "WriteBytes", want: 2048, have: int64(s.WriteBytes)}, - {name: "CancelledWriteBytes", want: -1024, have: s.CancelledWriteBytes}, - } { - if test.want != test.have { - t.Errorf("want %s %d, have %d", test.name, test.want, test.have) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/proc_limits.go b/vendor/github.com/prometheus/procfs/proc_limits.go index b684a5b55a..f04ba6fda8 100644 --- a/vendor/github.com/prometheus/procfs/proc_limits.go +++ b/vendor/github.com/prometheus/procfs/proc_limits.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus 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 procfs import ( diff --git a/vendor/github.com/prometheus/procfs/proc_limits_test.go b/vendor/github.com/prometheus/procfs/proc_limits_test.go deleted file mode 100644 index ac62a3bb6d..0000000000 --- a/vendor/github.com/prometheus/procfs/proc_limits_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package procfs - -import "testing" - -func TestNewLimits(t *testing.T) { - p, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - - l, err := p.NewLimits() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int64 - have int64 - }{ - {name: "cpu time", want: -1, have: l.CPUTime}, - {name: "open files", want: 2048, have: l.OpenFiles}, - {name: "msgqueue size", want: 819200, have: l.MsqqueueSize}, - {name: "nice priority", want: 0, have: l.NicePriority}, - {name: "address space", want: 8589934592, have: l.AddressSpace}, - } { - if test.want != test.have { - t.Errorf("want %s %d, have %d", test.name, test.want, test.have) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/proc_ns.go b/vendor/github.com/prometheus/procfs/proc_ns.go new file mode 100644 index 0000000000..d06c26ebad --- /dev/null +++ b/vendor/github.com/prometheus/procfs/proc_ns.go @@ -0,0 +1,68 @@ +// Copyright 2018 The Prometheus 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 procfs + +import ( + "fmt" + "os" + "strconv" + "strings" +) + +// Namespace represents a single namespace of a process. +type Namespace struct { + Type string // Namespace type. + Inode uint32 // Inode number of the namespace. If two processes are in the same namespace their inodes will match. +} + +// Namespaces contains all of the namespaces that the process is contained in. +type Namespaces map[string]Namespace + +// NewNamespaces reads from /proc/[pid/ns/* to get the namespaces of which the +// process is a member. +func (p Proc) NewNamespaces() (Namespaces, error) { + d, err := os.Open(p.path("ns")) + if err != nil { + return nil, err + } + defer d.Close() + + names, err := d.Readdirnames(-1) + if err != nil { + return nil, fmt.Errorf("failed to read contents of ns dir: %v", err) + } + + ns := make(Namespaces, len(names)) + for _, name := range names { + target, err := os.Readlink(p.path("ns", name)) + if err != nil { + return nil, err + } + + fields := strings.SplitN(target, ":", 2) + if len(fields) != 2 { + return nil, fmt.Errorf("failed to parse namespace type and inode from '%v'", target) + } + + typ := fields[0] + inode, err := strconv.ParseUint(strings.Trim(fields[1], "[]"), 10, 32) + if err != nil { + return nil, fmt.Errorf("failed to parse inode from '%v': %v", fields[1], err) + } + + ns[name] = Namespace{typ, uint32(inode)} + } + + return ns, nil +} diff --git a/vendor/github.com/prometheus/procfs/proc_stat.go b/vendor/github.com/prometheus/procfs/proc_stat.go index 724e271b9e..3cf2a9f18f 100644 --- a/vendor/github.com/prometheus/procfs/proc_stat.go +++ b/vendor/github.com/prometheus/procfs/proc_stat.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus 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 procfs import ( diff --git a/vendor/github.com/prometheus/procfs/proc_stat_test.go b/vendor/github.com/prometheus/procfs/proc_stat_test.go deleted file mode 100644 index a2ebcde78b..0000000000 --- a/vendor/github.com/prometheus/procfs/proc_stat_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package procfs - -import ( - "os" - "testing" -) - -func TestProcStat(t *testing.T) { - p, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - - s, err := p.NewStat() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int - have int - }{ - {name: "pid", want: 26231, have: s.PID}, - {name: "user time", want: 1677, have: int(s.UTime)}, - {name: "system time", want: 44, have: int(s.STime)}, - {name: "start time", want: 82375, have: int(s.Starttime)}, - {name: "virtual memory size", want: 56274944, have: s.VSize}, - {name: "resident set size", want: 1981, have: s.RSS}, - } { - if test.want != test.have { - t.Errorf("want %s %d, have %d", test.name, test.want, test.have) - } - } -} - -func TestProcStatComm(t *testing.T) { - s1, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - if want, have := "vim", s1.Comm; want != have { - t.Errorf("want comm %s, have %s", want, have) - } - - s2, err := testProcStat(584) - if err != nil { - t.Fatal(err) - } - if want, have := "(a b ) ( c d) ", s2.Comm; want != have { - t.Errorf("want comm %s, have %s", want, have) - } -} - -func TestProcStatVirtualMemory(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, have := 56274944, s.VirtualMemory(); want != have { - t.Errorf("want virtual memory %d, have %d", want, have) - } -} - -func TestProcStatResidentMemory(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, have := 1981*os.Getpagesize(), s.ResidentMemory(); want != have { - t.Errorf("want resident memory %d, have %d", want, have) - } -} - -func TestProcStatStartTime(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - time, err := s.StartTime() - if err != nil { - t.Fatal(err) - } - if want, have := 1418184099.75, time; want != have { - t.Errorf("want start time %f, have %f", want, have) - } -} - -func TestProcStatCPUTime(t *testing.T) { - s, err := testProcStat(26231) - if err != nil { - t.Fatal(err) - } - - if want, have := 17.21, s.CPUTime(); want != have { - t.Errorf("want cpu time %f, have %f", want, have) - } -} - -func testProcStat(pid int) (ProcStat, error) { - p, err := FS("fixtures").NewProc(pid) - if err != nil { - return ProcStat{}, err - } - - return p.NewStat() -} diff --git a/vendor/github.com/prometheus/procfs/proc_test.go b/vendor/github.com/prometheus/procfs/proc_test.go deleted file mode 100644 index 104b3245d8..0000000000 --- a/vendor/github.com/prometheus/procfs/proc_test.go +++ /dev/null @@ -1,160 +0,0 @@ -package procfs - -import ( - "reflect" - "sort" - "testing" -) - -func TestSelf(t *testing.T) { - fs := FS("fixtures") - - p1, err := fs.NewProc(26231) - if err != nil { - t.Fatal(err) - } - p2, err := fs.Self() - if err != nil { - t.Fatal(err) - } - - if !reflect.DeepEqual(p1, p2) { - t.Errorf("want process %v, have %v", p1, p2) - } -} - -func TestAllProcs(t *testing.T) { - procs, err := FS("fixtures").AllProcs() - if err != nil { - t.Fatal(err) - } - sort.Sort(procs) - for i, p := range []*Proc{{PID: 584}, {PID: 26231}} { - if want, have := p.PID, procs[i].PID; want != have { - t.Errorf("want processes %d, have %d", want, have) - } - } -} - -func TestCmdLine(t *testing.T) { - for _, tt := range []struct { - process int - want []string - }{ - {process: 26231, want: []string{"vim", "test.go", "+10"}}, - {process: 26232, want: []string{}}, - } { - p1, err := FS("fixtures").NewProc(tt.process) - if err != nil { - t.Fatal(err) - } - c1, err := p1.CmdLine() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(tt.want, c1) { - t.Errorf("want cmdline %v, have %v", tt.want, c1) - } - } -} - -func TestComm(t *testing.T) { - for _, tt := range []struct { - process int - want string - }{ - {process: 26231, want: "vim"}, - {process: 26232, want: "ata_sff"}, - } { - p1, err := FS("fixtures").NewProc(tt.process) - if err != nil { - t.Fatal(err) - } - c1, err := p1.Comm() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(tt.want, c1) { - t.Errorf("want comm %v, have %v", tt.want, c1) - } - } -} - -func TestExecutable(t *testing.T) { - for _, tt := range []struct { - process int - want string - }{ - {process: 26231, want: "/usr/bin/vim"}, - {process: 26232, want: ""}, - } { - p, err := FS("fixtures").NewProc(tt.process) - if err != nil { - t.Fatal(err) - } - exe, err := p.Executable() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(tt.want, exe) { - t.Errorf("want absolute path to cmdline %v, have %v", tt.want, exe) - } - } -} - -func TestFileDescriptors(t *testing.T) { - p1, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - fds, err := p1.FileDescriptors() - if err != nil { - t.Fatal(err) - } - sort.Sort(byUintptr(fds)) - if want := []uintptr{0, 1, 2, 3, 10}; !reflect.DeepEqual(want, fds) { - t.Errorf("want fds %v, have %v", want, fds) - } -} - -func TestFileDescriptorTargets(t *testing.T) { - p1, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - fds, err := p1.FileDescriptorTargets() - if err != nil { - t.Fatal(err) - } - sort.Strings(fds) - var want = []string{ - "../../symlinktargets/abc", - "../../symlinktargets/def", - "../../symlinktargets/ghi", - "../../symlinktargets/uvw", - "../../symlinktargets/xyz", - } - if !reflect.DeepEqual(want, fds) { - t.Errorf("want fds %v, have %v", want, fds) - } -} - -func TestFileDescriptorsLen(t *testing.T) { - p1, err := FS("fixtures").NewProc(26231) - if err != nil { - t.Fatal(err) - } - l, err := p1.FileDescriptorsLen() - if err != nil { - t.Fatal(err) - } - if want, have := 5, l; want != have { - t.Errorf("want fds %d, have %d", want, have) - } -} - -type byUintptr []uintptr - -func (a byUintptr) Len() int { return len(a) } -func (a byUintptr) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byUintptr) Less(i, j int) bool { return a[i] < a[j] } diff --git a/vendor/github.com/prometheus/procfs/stat.go b/vendor/github.com/prometheus/procfs/stat.go index 701f4df648..61eb6b0e3c 100644 --- a/vendor/github.com/prometheus/procfs/stat.go +++ b/vendor/github.com/prometheus/procfs/stat.go @@ -1,3 +1,16 @@ +// Copyright 2018 The Prometheus 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 procfs import ( diff --git a/vendor/github.com/prometheus/procfs/stat_test.go b/vendor/github.com/prometheus/procfs/stat_test.go deleted file mode 100644 index c34ccce1a8..0000000000 --- a/vendor/github.com/prometheus/procfs/stat_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package procfs - -import "testing" - -func TestStat(t *testing.T) { - s, err := FS("fixtures").NewStat() - if err != nil { - t.Fatal(err) - } - - // cpu - if want, have := float64(301854)/userHZ, s.CPUTotal.User; want != have { - t.Errorf("want cpu/user %v, have %v", want, have) - } - if want, have := float64(31)/userHZ, s.CPU[7].SoftIRQ; want != have { - t.Errorf("want cpu7/softirq %v, have %v", want, have) - } - - // intr - if want, have := uint64(8885917), s.IRQTotal; want != have { - t.Errorf("want irq/total %d, have %d", want, have) - } - if want, have := uint64(1), s.IRQ[8]; want != have { - t.Errorf("want irq8 %d, have %d", want, have) - } - - // ctxt - if want, have := uint64(38014093), s.ContextSwitches; want != have { - t.Errorf("want context switches (ctxt) %d, have %d", want, have) - } - - // btime - if want, have := uint64(1418183276), s.BootTime; want != have { - t.Errorf("want boot time (btime) %d, have %d", want, have) - } - - // processes - if want, have := uint64(26442), s.ProcessCreated; want != have { - t.Errorf("want process created (processes) %d, have %d", want, have) - } - - // procs_running - if want, have := uint64(2), s.ProcessesRunning; want != have { - t.Errorf("want processes running (procs_running) %d, have %d", want, have) - } - - // procs_blocked - if want, have := uint64(1), s.ProcessesBlocked; want != have { - t.Errorf("want processes blocked (procs_blocked) %d, have %d", want, have) - } - - // softirq - if want, have := uint64(5057579), s.SoftIRQTotal; want != have { - t.Errorf("want softirq total %d, have %d", want, have) - } - - if want, have := uint64(508444), s.SoftIRQ.Rcu; want != have { - t.Errorf("want softirq RCU %d, have %d", want, have) - } - -} diff --git a/vendor/github.com/prometheus/procfs/ttar b/vendor/github.com/prometheus/procfs/ttar index 8227a4a376..b0171a12b5 100755 --- a/vendor/github.com/prometheus/procfs/ttar +++ b/vendor/github.com/prometheus/procfs/ttar @@ -1,11 +1,26 @@ #!/usr/bin/env bash + # Purpose: plain text tar format # Limitations: - only suitable for text files, directories, and symlinks # - stores only filename, content, and mode # - not designed for untrusted input - +# # Note: must work with bash version 3.2 (macOS) +# Copyright 2017 Roger Luethi +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + set -o errexit -o nounset # Sanitize environment (for instance, standard sorting of glob matches) @@ -13,6 +28,55 @@ export LC_ALL=C path="" CMD="" +ARG_STRING="$*" + +#------------------------------------------------------------------------------ +# Not all sed implementations can work on null bytes. In order to make ttar +# work out of the box on macOS, use Python as a stream editor. + +USE_PYTHON=0 + +PYTHON_CREATE_FILTER=$(cat << 'PCF' +#!/usr/bin/env python + +import re +import sys + +for line in sys.stdin: + line = re.sub(r'EOF', r'\EOF', line) + line = re.sub(r'NULLBYTE', r'\NULLBYTE', line) + line = re.sub('\x00', r'NULLBYTE', line) + sys.stdout.write(line) +PCF +) + +PYTHON_EXTRACT_FILTER=$(cat << 'PEF' +#!/usr/bin/env python + +import re +import sys + +for line in sys.stdin: + line = re.sub(r'(?/dev/null; then + echo "ERROR Python not found. Aborting." + exit 2 + fi + USE_PYTHON=1 + fi +} + +#------------------------------------------------------------------------------ function usage { bname=$(basename "$0") @@ -23,6 +87,7 @@ Usage: $bname [-C ] -c -f (create archive) Options: -C (change directory) + -v (verbose) Example: Change to sysfs directory, create ttar file from fixtures directory $bname -C sysfs -c -f sysfs/fixtures.ttar fixtures/ @@ -45,6 +110,8 @@ function set_cmd { CMD=$1 } +unset VERBOSE + while getopts :cf:htxvC: opt; do case $opt in c) @@ -142,8 +209,37 @@ function extract { fi while IFS= read -r line; do line_no=$(( line_no + 1 )) + local eof_without_newline if [ "$size" -gt 0 ]; then - echo "$line" >> "$path" + if [[ "$line" =~ [^\\]EOF ]]; then + # An EOF not preceeded by a backslash indicates that the line + # does not end with a newline + eof_without_newline=1 + else + eof_without_newline=0 + fi + # Replace NULLBYTE with null byte if at beginning of line + # Replace NULLBYTE with null byte unless preceeded by backslash + # Remove one backslash in front of NULLBYTE (if any) + # Remove EOF unless preceeded by backslash + # Remove one backslash in front of EOF + if [ $USE_PYTHON -eq 1 ]; then + echo -n "$line" | python -c "$PYTHON_EXTRACT_FILTER" >> "$path" + else + # The repeated pattern makes up for sed's lack of negative + # lookbehind assertions (for consecutive null bytes). + echo -n "$line" | \ + sed -e 's/^NULLBYTE/\x0/g; + s/\([^\\]\)NULLBYTE/\1\x0/g; + s/\([^\\]\)NULLBYTE/\1\x0/g; + s/\\NULLBYTE/NULLBYTE/g; + s/\([^\\]\)EOF/\1/g; + s/\\EOF/EOF/g; + ' >> "$path" + fi + if [[ "$eof_without_newline" -eq 0 ]]; then + echo >> "$path" + fi size=$(( size - 1 )) continue fi @@ -187,11 +283,14 @@ function get_mode { local mfile=$1 if [ -z "${STAT_OPTION:-}" ]; then if stat -c '%a' "$mfile" >/dev/null 2>&1; then + # GNU stat STAT_OPTION='-c' STAT_FORMAT='%a' else + # BSD stat STAT_OPTION='-f' - STAT_FORMAT='%A' + # Octal output, user/group/other (omit file type, sticky bit) + STAT_FORMAT='%OLp' fi fi stat "${STAT_OPTION}" "${STAT_FORMAT}" "$mfile" @@ -200,6 +299,7 @@ function get_mode { function _create { shopt -s nullglob local mode + local eof_without_newline while (( "$#" )); do file=$1 if [ -L "$file" ]; then @@ -223,8 +323,30 @@ function _create { elif [ -f "$file" ]; then echo "Path: $file" lines=$(wc -l "$file"|awk '{print $1}') + eof_without_newline=0 + if [[ "$(wc -c "$file"|awk '{print $1}')" -gt 0 ]] && \ + [[ "$(tail -c 1 "$file" | wc -l)" -eq 0 ]]; then + eof_without_newline=1 + lines=$((lines+1)) + fi echo "Lines: $lines" - cat "$file" + # Add backslash in front of EOF + # Add backslash in front of NULLBYTE + # Replace null byte with NULLBYTE + if [ $USE_PYTHON -eq 1 ]; then + < "$file" python -c "$PYTHON_CREATE_FILTER" + else + < "$file" \ + sed 's/EOF/\\EOF/g; + s/NULLBYTE/\\NULLBYTE/g; + s/\x0/NULLBYTE/g; + ' + fi + if [[ "$eof_without_newline" -eq 1 ]]; then + # Finish line with EOF to indicate that the original line did + # not end with a linefeed + echo "EOF" + fi mode=$(get_mode "$file") echo "Mode: $mode" vecho "$mode $file" @@ -249,9 +371,12 @@ function create { rm "$ttar_file" fi exec > "$ttar_file" + echo "# Archive created by ttar $ARG_STRING" _create "$@" } +test_environment + if [ -n "${CDIR:-}" ]; then if [[ "$ARCHIVE" != /* ]]; then # Relative path: preserve the archive's location before changing diff --git a/vendor/github.com/prometheus/procfs/xfrm_test.go b/vendor/github.com/prometheus/procfs/xfrm_test.go deleted file mode 100644 index 5918c390eb..0000000000 --- a/vendor/github.com/prometheus/procfs/xfrm_test.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2017 Prometheus Team -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package procfs - -import ( - "testing" -) - -func TestXfrmStats(t *testing.T) { - xfrmStats, err := FS("fixtures").NewXfrmStat() - if err != nil { - t.Fatal(err) - } - - for _, test := range []struct { - name string - want int - got int - }{ - {name: "XfrmInError", want: 1, got: xfrmStats.XfrmInError}, - {name: "XfrmInBufferError", want: 2, got: xfrmStats.XfrmInBufferError}, - {name: "XfrmInHdrError", want: 4, got: xfrmStats.XfrmInHdrError}, - {name: "XfrmInNoStates", want: 3, got: xfrmStats.XfrmInNoStates}, - {name: "XfrmInStateProtoError", want: 40, got: xfrmStats.XfrmInStateProtoError}, - {name: "XfrmInStateModeError", want: 100, got: xfrmStats.XfrmInStateModeError}, - {name: "XfrmInStateSeqError", want: 6000, got: xfrmStats.XfrmInStateSeqError}, - {name: "XfrmInStateExpired", want: 4, got: xfrmStats.XfrmInStateExpired}, - {name: "XfrmInStateMismatch", want: 23451, got: xfrmStats.XfrmInStateMismatch}, - {name: "XfrmInStateInvalid", want: 55555, got: xfrmStats.XfrmInStateInvalid}, - {name: "XfrmInTmplMismatch", want: 51, got: xfrmStats.XfrmInTmplMismatch}, - {name: "XfrmInNoPols", want: 65432, got: xfrmStats.XfrmInNoPols}, - {name: "XfrmInPolBlock", want: 100, got: xfrmStats.XfrmInPolBlock}, - {name: "XfrmInPolError", want: 10000, got: xfrmStats.XfrmInPolError}, - {name: "XfrmOutError", want: 1000000, got: xfrmStats.XfrmOutError}, - {name: "XfrmOutBundleGenError", want: 43321, got: xfrmStats.XfrmOutBundleGenError}, - {name: "XfrmOutBundleCheckError", want: 555, got: xfrmStats.XfrmOutBundleCheckError}, - {name: "XfrmOutNoStates", want: 869, got: xfrmStats.XfrmOutNoStates}, - {name: "XfrmOutStateProtoError", want: 4542, got: xfrmStats.XfrmOutStateProtoError}, - {name: "XfrmOutStateModeError", want: 4, got: xfrmStats.XfrmOutStateModeError}, - {name: "XfrmOutStateSeqError", want: 543, got: xfrmStats.XfrmOutStateSeqError}, - {name: "XfrmOutStateExpired", want: 565, got: xfrmStats.XfrmOutStateExpired}, - {name: "XfrmOutPolBlock", want: 43456, got: xfrmStats.XfrmOutPolBlock}, - {name: "XfrmOutPolDead", want: 7656, got: xfrmStats.XfrmOutPolDead}, - {name: "XfrmOutPolError", want: 1454, got: xfrmStats.XfrmOutPolError}, - {name: "XfrmFwdHdrError", want: 6654, got: xfrmStats.XfrmFwdHdrError}, - {name: "XfrmOutStateInvaliad", want: 28765, got: xfrmStats.XfrmOutStateInvalid}, - {name: "XfrmAcquireError", want: 24532, got: xfrmStats.XfrmAcquireError}, - {name: "XfrmInStateInvalid", want: 55555, got: xfrmStats.XfrmInStateInvalid}, - {name: "XfrmOutError", want: 1000000, got: xfrmStats.XfrmOutError}, - } { - if test.want != test.got { - t.Errorf("Want %s %d, have %d", test.name, test.want, test.got) - } - } -} diff --git a/vendor/github.com/prometheus/procfs/xfs/parse.go b/vendor/github.com/prometheus/procfs/xfs/parse.go index c8f6279f39..2bc0ef3427 100644 --- a/vendor/github.com/prometheus/procfs/xfs/parse.go +++ b/vendor/github.com/prometheus/procfs/xfs/parse.go @@ -17,8 +17,9 @@ import ( "bufio" "fmt" "io" - "strconv" "strings" + + "github.com/prometheus/procfs/internal/util" ) // ParseStats parses a Stats from an input io.Reader, using the format @@ -68,7 +69,7 @@ func ParseStats(r io.Reader) (*Stats, error) { // Extended precision counters are uint64 values. if label == fieldXpc { - us, err := parseUint64s(ss[1:]) + us, err := util.ParseUint64s(ss[1:]) if err != nil { return nil, err } @@ -82,7 +83,7 @@ func ParseStats(r io.Reader) (*Stats, error) { } // All other counters are uint32 values. - us, err := parseUint32s(ss[1:]) + us, err := util.ParseUint32s(ss[1:]) if err != nil { return nil, err } @@ -327,33 +328,3 @@ func extendedPrecisionStats(us []uint64) (ExtendedPrecisionStats, error) { ReadBytes: us[2], }, nil } - -// parseUint32s parses a slice of strings into a slice of uint32s. -func parseUint32s(ss []string) ([]uint32, error) { - us := make([]uint32, 0, len(ss)) - for _, s := range ss { - u, err := strconv.ParseUint(s, 10, 32) - if err != nil { - return nil, err - } - - us = append(us, uint32(u)) - } - - return us, nil -} - -// parseUint64s parses a slice of strings into a slice of uint64s. -func parseUint64s(ss []string) ([]uint64, error) { - us := make([]uint64, 0, len(ss)) - for _, s := range ss { - u, err := strconv.ParseUint(s, 10, 64) - if err != nil { - return nil, err - } - - us = append(us, u) - } - - return us, nil -} diff --git a/vendor/github.com/prometheus/procfs/xfs/parse_test.go b/vendor/github.com/prometheus/procfs/xfs/parse_test.go deleted file mode 100644 index 2e946c2c52..0000000000 --- a/vendor/github.com/prometheus/procfs/xfs/parse_test.go +++ /dev/null @@ -1,442 +0,0 @@ -// Copyright 2017 The Prometheus 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 xfs_test - -import ( - "reflect" - "strings" - "testing" - - "github.com/prometheus/procfs" - "github.com/prometheus/procfs/xfs" -) - -func TestParseStats(t *testing.T) { - tests := []struct { - name string - s string - fs bool - stats *xfs.Stats - invalid bool - }{ - { - name: "empty file OK", - }, - { - name: "short or empty lines and unknown labels ignored", - s: "one\n\ntwo 1 2 3\n", - stats: &xfs.Stats{}, - }, - { - name: "bad uint32", - s: "extent_alloc XXX", - invalid: true, - }, - { - name: "bad uint64", - s: "xpc XXX", - invalid: true, - }, - { - name: "extent_alloc bad", - s: "extent_alloc 1", - invalid: true, - }, - { - name: "extent_alloc OK", - s: "extent_alloc 1 2 3 4", - stats: &xfs.Stats{ - ExtentAllocation: xfs.ExtentAllocationStats{ - ExtentsAllocated: 1, - BlocksAllocated: 2, - ExtentsFreed: 3, - BlocksFreed: 4, - }, - }, - }, - { - name: "abt bad", - s: "abt 1", - invalid: true, - }, - { - name: "abt OK", - s: "abt 1 2 3 4", - stats: &xfs.Stats{ - AllocationBTree: xfs.BTreeStats{ - Lookups: 1, - Compares: 2, - RecordsInserted: 3, - RecordsDeleted: 4, - }, - }, - }, - { - name: "blk_map bad", - s: "blk_map 1", - invalid: true, - }, - { - name: "blk_map OK", - s: "blk_map 1 2 3 4 5 6 7", - stats: &xfs.Stats{ - BlockMapping: xfs.BlockMappingStats{ - Reads: 1, - Writes: 2, - Unmaps: 3, - ExtentListInsertions: 4, - ExtentListDeletions: 5, - ExtentListLookups: 6, - ExtentListCompares: 7, - }, - }, - }, - { - name: "bmbt bad", - s: "bmbt 1", - invalid: true, - }, - { - name: "bmbt OK", - s: "bmbt 1 2 3 4", - stats: &xfs.Stats{ - BlockMapBTree: xfs.BTreeStats{ - Lookups: 1, - Compares: 2, - RecordsInserted: 3, - RecordsDeleted: 4, - }, - }, - }, - { - name: "dir bad", - s: "dir 1", - invalid: true, - }, - { - name: "dir OK", - s: "dir 1 2 3 4", - stats: &xfs.Stats{ - DirectoryOperation: xfs.DirectoryOperationStats{ - Lookups: 1, - Creates: 2, - Removes: 3, - Getdents: 4, - }, - }, - }, - { - name: "trans bad", - s: "trans 1", - invalid: true, - }, - { - name: "trans OK", - s: "trans 1 2 3", - stats: &xfs.Stats{ - Transaction: xfs.TransactionStats{ - Sync: 1, - Async: 2, - Empty: 3, - }, - }, - }, - { - name: "ig bad", - s: "ig 1", - invalid: true, - }, - { - name: "ig OK", - s: "ig 1 2 3 4 5 6 7", - stats: &xfs.Stats{ - InodeOperation: xfs.InodeOperationStats{ - Attempts: 1, - Found: 2, - Recycle: 3, - Missed: 4, - Duplicate: 5, - Reclaims: 6, - AttributeChange: 7, - }, - }, - }, - { - name: "log bad", - s: "log 1", - invalid: true, - }, - { - name: "log OK", - s: "log 1 2 3 4 5", - stats: &xfs.Stats{ - LogOperation: xfs.LogOperationStats{ - Writes: 1, - Blocks: 2, - NoInternalBuffers: 3, - Force: 4, - ForceSleep: 5, - }, - }, - }, - { - name: "rw bad", - s: "rw 1", - invalid: true, - }, - { - name: "rw OK", - s: "rw 1 2", - stats: &xfs.Stats{ - ReadWrite: xfs.ReadWriteStats{ - Read: 1, - Write: 2, - }, - }, - }, - { - name: "attr bad", - s: "attr 1", - invalid: true, - }, - { - name: "attr OK", - s: "attr 1 2 3 4", - stats: &xfs.Stats{ - AttributeOperation: xfs.AttributeOperationStats{ - Get: 1, - Set: 2, - Remove: 3, - List: 4, - }, - }, - }, - { - name: "icluster bad", - s: "icluster 1", - invalid: true, - }, - { - name: "icluster OK", - s: "icluster 1 2 3", - stats: &xfs.Stats{ - InodeClustering: xfs.InodeClusteringStats{ - Iflush: 1, - Flush: 2, - FlushInode: 3, - }, - }, - }, - { - name: "vnodes bad", - s: "vnodes 1", - invalid: true, - }, - { - name: "vnodes (missing free) OK", - s: "vnodes 1 2 3 4 5 6 7", - stats: &xfs.Stats{ - Vnode: xfs.VnodeStats{ - Active: 1, - Allocate: 2, - Get: 3, - Hold: 4, - Release: 5, - Reclaim: 6, - Remove: 7, - }, - }, - }, - { - name: "vnodes (with free) OK", - s: "vnodes 1 2 3 4 5 6 7 8", - stats: &xfs.Stats{ - Vnode: xfs.VnodeStats{ - Active: 1, - Allocate: 2, - Get: 3, - Hold: 4, - Release: 5, - Reclaim: 6, - Remove: 7, - Free: 8, - }, - }, - }, - { - name: "buf bad", - s: "buf 1", - invalid: true, - }, - { - name: "buf OK", - s: "buf 1 2 3 4 5 6 7 8 9", - stats: &xfs.Stats{ - Buffer: xfs.BufferStats{ - Get: 1, - Create: 2, - GetLocked: 3, - GetLockedWaited: 4, - BusyLocked: 5, - MissLocked: 6, - PageRetries: 7, - PageFound: 8, - GetRead: 9, - }, - }, - }, - { - name: "xpc bad", - s: "xpc 1", - invalid: true, - }, - { - name: "xpc OK", - s: "xpc 1 2 3", - stats: &xfs.Stats{ - ExtendedPrecision: xfs.ExtendedPrecisionStats{ - FlushBytes: 1, - WriteBytes: 2, - ReadBytes: 3, - }, - }, - }, - { - name: "fixtures OK", - fs: true, - stats: &xfs.Stats{ - ExtentAllocation: xfs.ExtentAllocationStats{ - ExtentsAllocated: 92447, - BlocksAllocated: 97589, - ExtentsFreed: 92448, - BlocksFreed: 93751, - }, - AllocationBTree: xfs.BTreeStats{ - Lookups: 0, - Compares: 0, - RecordsInserted: 0, - RecordsDeleted: 0, - }, - BlockMapping: xfs.BlockMappingStats{ - Reads: 1767055, - Writes: 188820, - Unmaps: 184891, - ExtentListInsertions: 92447, - ExtentListDeletions: 92448, - ExtentListLookups: 2140766, - ExtentListCompares: 0, - }, - BlockMapBTree: xfs.BTreeStats{ - Lookups: 0, - Compares: 0, - RecordsInserted: 0, - RecordsDeleted: 0, - }, - DirectoryOperation: xfs.DirectoryOperationStats{ - Lookups: 185039, - Creates: 92447, - Removes: 92444, - Getdents: 136422, - }, - Transaction: xfs.TransactionStats{ - Sync: 706, - Async: 944304, - Empty: 0, - }, - InodeOperation: xfs.InodeOperationStats{ - Attempts: 185045, - Found: 58807, - Recycle: 0, - Missed: 126238, - Duplicate: 0, - Reclaims: 33637, - AttributeChange: 22, - }, - LogOperation: xfs.LogOperationStats{ - Writes: 2883, - Blocks: 113448, - NoInternalBuffers: 9, - Force: 17360, - ForceSleep: 739, - }, - ReadWrite: xfs.ReadWriteStats{ - Read: 107739, - Write: 94045, - }, - AttributeOperation: xfs.AttributeOperationStats{ - Get: 4, - Set: 0, - Remove: 0, - List: 0, - }, - InodeClustering: xfs.InodeClusteringStats{ - Iflush: 8677, - Flush: 7849, - FlushInode: 135802, - }, - Vnode: xfs.VnodeStats{ - Active: 92601, - Allocate: 0, - Get: 0, - Hold: 0, - Release: 92444, - Reclaim: 92444, - Remove: 92444, - Free: 0, - }, - Buffer: xfs.BufferStats{ - Get: 2666287, - Create: 7122, - GetLocked: 2659202, - GetLockedWaited: 3599, - BusyLocked: 2, - MissLocked: 7085, - PageRetries: 0, - PageFound: 10297, - GetRead: 7085, - }, - ExtendedPrecision: xfs.ExtendedPrecisionStats{ - FlushBytes: 399724544, - WriteBytes: 92823103, - ReadBytes: 86219234, - }, - }, - }, - } - - for _, tt := range tests { - var ( - stats *xfs.Stats - err error - ) - - if tt.s != "" { - stats, err = xfs.ParseStats(strings.NewReader(tt.s)) - } - if tt.fs { - stats, err = procfs.FS("../fixtures").XFSStats() - } - - if tt.invalid && err == nil { - t.Error("expected an error, but none occurred") - } - if !tt.invalid && err != nil { - t.Errorf("unexpected error: %v", err) - } - - if want, have := tt.stats, stats; !reflect.DeepEqual(want, have) { - t.Errorf("unexpected XFS stats:\nwant:\n%v\nhave:\n%v", want, have) - } - } -} diff --git a/vendor/github.com/spf13/afero/.travis.yml b/vendor/github.com/spf13/afero/.travis.yml index 618159a4ea..0637db726d 100644 --- a/vendor/github.com/spf13/afero/.travis.yml +++ b/vendor/github.com/spf13/afero/.travis.yml @@ -2,8 +2,8 @@ sudo: false language: go go: - - 1.7.5 - - 1.8 + - 1.9 + - "1.10" - tip os: diff --git a/vendor/github.com/spf13/afero/afero_test.go b/vendor/github.com/spf13/afero/afero_test.go deleted file mode 100644 index 526afa9758..0000000000 --- a/vendor/github.com/spf13/afero/afero_test.go +++ /dev/null @@ -1,699 +0,0 @@ -// Copyright © 2014 Steve Francia . -// Copyright 2009 The Go Authors. 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 afero - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "runtime" - "strings" - "syscall" - "testing" -) - -var testName = "test.txt" -var Fss = []Fs{&MemMapFs{}, &OsFs{}} - -var testRegistry map[Fs][]string = make(map[Fs][]string) - -func testDir(fs Fs) string { - name, err := TempDir(fs, "", "afero") - if err != nil { - panic(fmt.Sprint("unable to work with test dir", err)) - } - testRegistry[fs] = append(testRegistry[fs], name) - - return name -} - -func tmpFile(fs Fs) File { - x, err := TempFile(fs, "", "afero") - - if err != nil { - panic(fmt.Sprint("unable to work with temp file", err)) - } - - testRegistry[fs] = append(testRegistry[fs], x.Name()) - - return x -} - -//Read with length 0 should not return EOF. -func TestRead0(t *testing.T) { - for _, fs := range Fss { - f := tmpFile(fs) - defer f.Close() - f.WriteString("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.") - - var b []byte - // b := make([]byte, 0) - n, err := f.Read(b) - if n != 0 || err != nil { - t.Errorf("%v: Read(0) = %d, %v, want 0, nil", fs.Name(), n, err) - } - f.Seek(0, 0) - b = make([]byte, 100) - n, err = f.Read(b) - if n <= 0 || err != nil { - t.Errorf("%v: Read(100) = %d, %v, want >0, nil", fs.Name(), n, err) - } - } -} - -func TestOpenFile(t *testing.T) { - defer removeAllTestFiles(t) - for _, fs := range Fss { - tmp := testDir(fs) - path := filepath.Join(tmp, testName) - - f, err := fs.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600) - if err != nil { - t.Error(fs.Name(), "OpenFile (O_CREATE) failed:", err) - continue - } - io.WriteString(f, "initial") - f.Close() - - f, err = fs.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0600) - if err != nil { - t.Error(fs.Name(), "OpenFile (O_APPEND) failed:", err) - continue - } - io.WriteString(f, "|append") - f.Close() - - f, err = fs.OpenFile(path, os.O_RDONLY, 0600) - contents, _ := ioutil.ReadAll(f) - expectedContents := "initial|append" - if string(contents) != expectedContents { - t.Errorf("%v: appending, expected '%v', got: '%v'", fs.Name(), expectedContents, string(contents)) - } - f.Close() - - f, err = fs.OpenFile(path, os.O_RDWR|os.O_TRUNC, 0600) - if err != nil { - t.Error(fs.Name(), "OpenFile (O_TRUNC) failed:", err) - continue - } - contents, _ = ioutil.ReadAll(f) - if string(contents) != "" { - t.Errorf("%v: expected truncated file, got: '%v'", fs.Name(), string(contents)) - } - f.Close() - } -} - -func TestCreate(t *testing.T) { - defer removeAllTestFiles(t) - for _, fs := range Fss { - tmp := testDir(fs) - path := filepath.Join(tmp, testName) - - f, err := fs.Create(path) - if err != nil { - t.Error(fs.Name(), "Create failed:", err) - f.Close() - continue - } - io.WriteString(f, "initial") - f.Close() - - f, err = fs.Create(path) - if err != nil { - t.Error(fs.Name(), "Create failed:", err) - f.Close() - continue - } - secondContent := "second create" - io.WriteString(f, secondContent) - f.Close() - - f, err = fs.Open(path) - if err != nil { - t.Error(fs.Name(), "Open failed:", err) - f.Close() - continue - } - buf, err := ReadAll(f) - if err != nil { - t.Error(fs.Name(), "ReadAll failed:", err) - f.Close() - continue - } - if string(buf) != secondContent { - t.Error(fs.Name(), "Content should be", "\""+secondContent+"\" but is \""+string(buf)+"\"") - f.Close() - continue - } - f.Close() - } -} - -func TestMemFileRead(t *testing.T) { - f := tmpFile(new(MemMapFs)) - // f := MemFileCreate("testfile") - f.WriteString("abcd") - f.Seek(0, 0) - b := make([]byte, 8) - n, err := f.Read(b) - if n != 4 { - t.Errorf("didn't read all bytes: %v %v %v", n, err, b) - } - if err != nil { - t.Errorf("err is not nil: %v %v %v", n, err, b) - } - n, err = f.Read(b) - if n != 0 { - t.Errorf("read more bytes: %v %v %v", n, err, b) - } - if err != io.EOF { - t.Errorf("error is not EOF: %v %v %v", n, err, b) - } -} - -func TestRename(t *testing.T) { - defer removeAllTestFiles(t) - for _, fs := range Fss { - tDir := testDir(fs) - from := filepath.Join(tDir, "/renamefrom") - to := filepath.Join(tDir, "/renameto") - exists := filepath.Join(tDir, "/renameexists") - file, err := fs.Create(from) - if err != nil { - t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err) - } - if err = file.Close(); err != nil { - t.Errorf("%s: close %q failed: %v", fs.Name(), to, err) - } - file, err = fs.Create(exists) - if err != nil { - t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err) - } - if err = file.Close(); err != nil { - t.Errorf("%s: close %q failed: %v", fs.Name(), to, err) - } - err = fs.Rename(from, to) - if err != nil { - t.Fatalf("%s: rename %q, %q failed: %v", fs.Name(), to, from, err) - } - file, err = fs.Create(from) - if err != nil { - t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err) - } - if err = file.Close(); err != nil { - t.Errorf("%s: close %q failed: %v", fs.Name(), to, err) - } - err = fs.Rename(from, exists) - if err != nil { - t.Errorf("%s: rename %q, %q failed: %v", fs.Name(), exists, from, err) - } - names, err := readDirNames(fs, tDir) - if err != nil { - t.Errorf("%s: readDirNames error: %v", fs.Name(), err) - } - found := false - for _, e := range names { - if e == "renamefrom" { - t.Error("File is still called renamefrom") - } - if e == "renameto" { - found = true - } - } - if !found { - t.Error("File was not renamed to renameto") - } - - _, err = fs.Stat(to) - if err != nil { - t.Errorf("%s: stat %q failed: %v", fs.Name(), to, err) - } - } -} - -func TestRemove(t *testing.T) { - for _, fs := range Fss { - - x, err := TempFile(fs, "", "afero") - if err != nil { - t.Error(fmt.Sprint("unable to work with temp file", err)) - } - - path := x.Name() - x.Close() - - tDir := filepath.Dir(path) - - err = fs.Remove(path) - if err != nil { - t.Errorf("%v: Remove() failed: %v", fs.Name(), err) - continue - } - - _, err = fs.Stat(path) - if !os.IsNotExist(err) { - t.Errorf("%v: Remove() didn't remove file", fs.Name()) - continue - } - - // Deleting non-existent file should raise error - err = fs.Remove(path) - if !os.IsNotExist(err) { - t.Errorf("%v: Remove() didn't raise error for non-existent file", fs.Name()) - } - - f, err := fs.Open(tDir) - if err != nil { - t.Error("TestDir should still exist:", err) - } - - names, err := f.Readdirnames(-1) - if err != nil { - t.Error("Readdirnames failed:", err) - } - - for _, e := range names { - if e == testName { - t.Error("File was not removed from parent directory") - } - } - } -} - -func TestTruncate(t *testing.T) { - defer removeAllTestFiles(t) - for _, fs := range Fss { - f := tmpFile(fs) - defer f.Close() - - checkSize(t, f, 0) - f.Write([]byte("hello, world\n")) - checkSize(t, f, 13) - f.Truncate(10) - checkSize(t, f, 10) - f.Truncate(1024) - checkSize(t, f, 1024) - f.Truncate(0) - checkSize(t, f, 0) - _, err := f.Write([]byte("surprise!")) - if err == nil { - checkSize(t, f, 13+9) // wrote at offset past where hello, world was. - } - } -} - -func TestSeek(t *testing.T) { - defer removeAllTestFiles(t) - for _, fs := range Fss { - f := tmpFile(fs) - defer f.Close() - - const data = "hello, world\n" - io.WriteString(f, data) - - type test struct { - in int64 - whence int - out int64 - } - var tests = []test{ - {0, 1, int64(len(data))}, - {0, 0, 0}, - {5, 0, 5}, - {0, 2, int64(len(data))}, - {0, 0, 0}, - {-1, 2, int64(len(data)) - 1}, - {1 << 33, 0, 1 << 33}, - {1 << 33, 2, 1<<33 + int64(len(data))}, - } - for i, tt := range tests { - off, err := f.Seek(tt.in, tt.whence) - if off != tt.out || err != nil { - if e, ok := err.(*os.PathError); ok && e.Err == syscall.EINVAL && tt.out > 1<<32 { - // Reiserfs rejects the big seeks. - // http://code.google.com/p/go/issues/detail?id=91 - break - } - t.Errorf("#%d: Seek(%v, %v) = %v, %v want %v, nil", i, tt.in, tt.whence, off, err, tt.out) - } - } - } -} - -func TestReadAt(t *testing.T) { - defer removeAllTestFiles(t) - for _, fs := range Fss { - f := tmpFile(fs) - defer f.Close() - - const data = "hello, world\n" - io.WriteString(f, data) - - b := make([]byte, 5) - n, err := f.ReadAt(b, 7) - if err != nil || n != len(b) { - t.Fatalf("ReadAt 7: %d, %v", n, err) - } - if string(b) != "world" { - t.Fatalf("ReadAt 7: have %q want %q", string(b), "world") - } - } -} - -func TestWriteAt(t *testing.T) { - defer removeAllTestFiles(t) - for _, fs := range Fss { - f := tmpFile(fs) - defer f.Close() - - const data = "hello, world\n" - io.WriteString(f, data) - - n, err := f.WriteAt([]byte("WORLD"), 7) - if err != nil || n != 5 { - t.Fatalf("WriteAt 7: %d, %v", n, err) - } - - f2, err := fs.Open(f.Name()) - if err != nil { - t.Fatalf("%v: ReadFile %s: %v", fs.Name(), f.Name(), err) - } - defer f2.Close() - buf := new(bytes.Buffer) - buf.ReadFrom(f2) - b := buf.Bytes() - if string(b) != "hello, WORLD\n" { - t.Fatalf("after write: have %q want %q", string(b), "hello, WORLD\n") - } - - } -} - -func setupTestDir(t *testing.T, fs Fs) string { - path := testDir(fs) - return setupTestFiles(t, fs, path) -} - -func setupTestDirRoot(t *testing.T, fs Fs) string { - path := testDir(fs) - setupTestFiles(t, fs, path) - return path -} - -func setupTestDirReusePath(t *testing.T, fs Fs, path string) string { - testRegistry[fs] = append(testRegistry[fs], path) - return setupTestFiles(t, fs, path) -} - -func setupTestFiles(t *testing.T, fs Fs, path string) string { - testSubDir := filepath.Join(path, "more", "subdirectories", "for", "testing", "we") - err := fs.MkdirAll(testSubDir, 0700) - if err != nil && !os.IsExist(err) { - t.Fatal(err) - } - - f, err := fs.Create(filepath.Join(testSubDir, "testfile1")) - if err != nil { - t.Fatal(err) - } - f.WriteString("Testfile 1 content") - f.Close() - - f, err = fs.Create(filepath.Join(testSubDir, "testfile2")) - if err != nil { - t.Fatal(err) - } - f.WriteString("Testfile 2 content") - f.Close() - - f, err = fs.Create(filepath.Join(testSubDir, "testfile3")) - if err != nil { - t.Fatal(err) - } - f.WriteString("Testfile 3 content") - f.Close() - - f, err = fs.Create(filepath.Join(testSubDir, "testfile4")) - if err != nil { - t.Fatal(err) - } - f.WriteString("Testfile 4 content") - f.Close() - return testSubDir -} - -func TestReaddirnames(t *testing.T) { - defer removeAllTestFiles(t) - for _, fs := range Fss { - testSubDir := setupTestDir(t, fs) - tDir := filepath.Dir(testSubDir) - - root, err := fs.Open(tDir) - if err != nil { - t.Fatal(fs.Name(), tDir, err) - } - defer root.Close() - - namesRoot, err := root.Readdirnames(-1) - if err != nil { - t.Fatal(fs.Name(), namesRoot, err) - } - - sub, err := fs.Open(testSubDir) - if err != nil { - t.Fatal(err) - } - defer sub.Close() - - namesSub, err := sub.Readdirnames(-1) - if err != nil { - t.Fatal(fs.Name(), namesSub, err) - } - - findNames(fs, t, tDir, testSubDir, namesRoot, namesSub) - } -} - -func TestReaddirSimple(t *testing.T) { - defer removeAllTestFiles(t) - for _, fs := range Fss { - testSubDir := setupTestDir(t, fs) - tDir := filepath.Dir(testSubDir) - - root, err := fs.Open(tDir) - if err != nil { - t.Fatal(err) - } - defer root.Close() - - rootInfo, err := root.Readdir(1) - if err != nil { - t.Log(myFileInfo(rootInfo)) - t.Error(err) - } - - rootInfo, err = root.Readdir(5) - if err != io.EOF { - t.Log(myFileInfo(rootInfo)) - t.Error(err) - } - - sub, err := fs.Open(testSubDir) - if err != nil { - t.Fatal(err) - } - defer sub.Close() - - subInfo, err := sub.Readdir(5) - if err != nil { - t.Log(myFileInfo(subInfo)) - t.Error(err) - } - } -} - -func TestReaddir(t *testing.T) { - defer removeAllTestFiles(t) - for num := 0; num < 6; num++ { - outputs := make([]string, len(Fss)) - infos := make([]string, len(Fss)) - for i, fs := range Fss { - testSubDir := setupTestDir(t, fs) - //tDir := filepath.Dir(testSubDir) - root, err := fs.Open(testSubDir) - if err != nil { - t.Fatal(err) - } - defer root.Close() - - for j := 0; j < 6; j++ { - info, err := root.Readdir(num) - outputs[i] += fmt.Sprintf("%v Error: %v\n", myFileInfo(info), err) - infos[i] += fmt.Sprintln(len(info), err) - } - } - - fail := false - for i, o := range infos { - if i == 0 { - continue - } - if o != infos[i-1] { - fail = true - break - } - } - if fail { - t.Log("Readdir outputs not equal for Readdir(", num, ")") - for i, o := range outputs { - t.Log(Fss[i].Name()) - t.Log(o) - } - t.Fail() - } - } -} - -type myFileInfo []os.FileInfo - -func (m myFileInfo) String() string { - out := "Fileinfos:\n" - for _, e := range m { - out += " " + e.Name() + "\n" - } - return out -} - -func TestReaddirAll(t *testing.T) { - defer removeAllTestFiles(t) - for _, fs := range Fss { - testSubDir := setupTestDir(t, fs) - tDir := filepath.Dir(testSubDir) - - root, err := fs.Open(tDir) - if err != nil { - t.Fatal(err) - } - defer root.Close() - - rootInfo, err := root.Readdir(-1) - if err != nil { - t.Fatal(err) - } - var namesRoot = []string{} - for _, e := range rootInfo { - namesRoot = append(namesRoot, e.Name()) - } - - sub, err := fs.Open(testSubDir) - if err != nil { - t.Fatal(err) - } - defer sub.Close() - - subInfo, err := sub.Readdir(-1) - if err != nil { - t.Fatal(err) - } - var namesSub = []string{} - for _, e := range subInfo { - namesSub = append(namesSub, e.Name()) - } - - findNames(fs, t, tDir, testSubDir, namesRoot, namesSub) - } -} - -func findNames(fs Fs, t *testing.T, tDir, testSubDir string, root, sub []string) { - var foundRoot bool - for _, e := range root { - f, err := fs.Open(filepath.Join(tDir, e)) - if err != nil { - t.Error("Open", filepath.Join(tDir, e), ":", err) - } - defer f.Close() - - if equal(e, "we") { - foundRoot = true - } - } - if !foundRoot { - t.Logf("Names root: %v", root) - t.Logf("Names sub: %v", sub) - t.Error("Didn't find subdirectory we") - } - - var found1, found2 bool - for _, e := range sub { - f, err := fs.Open(filepath.Join(testSubDir, e)) - if err != nil { - t.Error("Open", filepath.Join(testSubDir, e), ":", err) - } - defer f.Close() - - if equal(e, "testfile1") { - found1 = true - } - if equal(e, "testfile2") { - found2 = true - } - } - - if !found1 { - t.Logf("Names root: %v", root) - t.Logf("Names sub: %v", sub) - t.Error("Didn't find testfile1") - } - if !found2 { - t.Logf("Names root: %v", root) - t.Logf("Names sub: %v", sub) - t.Error("Didn't find testfile2") - } -} - -func removeAllTestFiles(t *testing.T) { - for fs, list := range testRegistry { - for _, path := range list { - if err := fs.RemoveAll(path); err != nil { - t.Error(fs.Name(), err) - } - } - } - testRegistry = make(map[Fs][]string) -} - -func equal(name1, name2 string) (r bool) { - switch runtime.GOOS { - case "windows": - r = strings.ToLower(name1) == strings.ToLower(name2) - default: - r = name1 == name2 - } - return -} - -func checkSize(t *testing.T, f File, size int64) { - dir, err := f.Stat() - if err != nil { - t.Fatalf("Stat %q (looking for size %d): %s", f.Name(), size, err) - } - if dir.Size() != size { - t.Errorf("Stat %q: size %d want %d", f.Name(), dir.Size(), size) - } -} diff --git a/vendor/github.com/spf13/afero/basepath.go b/vendor/github.com/spf13/afero/basepath.go index 5e4fc2ec05..616ff8ff74 100644 --- a/vendor/github.com/spf13/afero/basepath.go +++ b/vendor/github.com/spf13/afero/basepath.go @@ -1,7 +1,6 @@ package afero import ( - "errors" "os" "path/filepath" "runtime" @@ -9,6 +8,8 @@ import ( "time" ) +var _ Lstater = (*BasePathFs)(nil) + // The BasePathFs restricts all operations to a given path within an Fs. // The given file name to the operations on this Fs will be prepended with // the base path before calling the base Fs. @@ -22,6 +23,16 @@ type BasePathFs struct { path string } +type BasePathFile struct { + File + path string +} + +func (f *BasePathFile) Name() string { + sourcename := f.File.Name() + return strings.TrimPrefix(sourcename, filepath.Clean(f.path)) +} + func NewBasePathFs(source Fs, path string) Fs { return &BasePathFs{source: source, path: path} } @@ -30,7 +41,7 @@ func NewBasePathFs(source Fs, path string) Fs { // else the given file with the base path prepended func (b *BasePathFs) RealPath(name string) (path string, err error) { if err := validateBasePathName(name); err != nil { - return "", err + return name, err } bpath := filepath.Clean(b.path) @@ -52,7 +63,7 @@ func validateBasePathName(name string) error { // On Windows a common mistake would be to provide an absolute OS path // We could strip out the base part, but that would not be very portable. if filepath.IsAbs(name) { - return &os.PathError{Op: "realPath", Path: name, Err: errors.New("got a real OS path instead of a virtual")} + return os.ErrNotExist } return nil @@ -111,14 +122,22 @@ func (b *BasePathFs) OpenFile(name string, flag int, mode os.FileMode) (f File, if name, err = b.RealPath(name); err != nil { return nil, &os.PathError{Op: "openfile", Path: name, Err: err} } - return b.source.OpenFile(name, flag, mode) + sourcef, err := b.source.OpenFile(name, flag, mode) + if err != nil { + return nil, err + } + return &BasePathFile{sourcef, b.path}, nil } func (b *BasePathFs) Open(name string) (f File, err error) { if name, err = b.RealPath(name); err != nil { return nil, &os.PathError{Op: "open", Path: name, Err: err} } - return b.source.Open(name) + sourcef, err := b.source.Open(name) + if err != nil { + return nil, err + } + return &BasePathFile{File: sourcef, path: b.path}, nil } func (b *BasePathFs) Mkdir(name string, mode os.FileMode) (err error) { @@ -139,7 +158,23 @@ func (b *BasePathFs) Create(name string) (f File, err error) { if name, err = b.RealPath(name); err != nil { return nil, &os.PathError{Op: "create", Path: name, Err: err} } - return b.source.Create(name) + sourcef, err := b.source.Create(name) + if err != nil { + return nil, err + } + return &BasePathFile{File: sourcef, path: b.path}, nil +} + +func (b *BasePathFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { + name, err := b.RealPath(name) + if err != nil { + return nil, false, &os.PathError{Op: "lstat", Path: name, Err: err} + } + if lstater, ok := b.source.(Lstater); ok { + return lstater.LstatIfPossible(name) + } + fi, err := b.source.Stat(name) + return fi, false, err } // vim: ts=4 sw=4 noexpandtab nolist syn=go diff --git a/vendor/github.com/spf13/afero/basepath_test.go b/vendor/github.com/spf13/afero/basepath_test.go deleted file mode 100644 index abc22b9f64..0000000000 --- a/vendor/github.com/spf13/afero/basepath_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package afero - -import ( - "os" - "path/filepath" - "runtime" - "testing" -) - -func TestBasePath(t *testing.T) { - baseFs := &MemMapFs{} - baseFs.MkdirAll("/base/path/tmp", 0777) - bp := NewBasePathFs(baseFs, "/base/path") - - if _, err := bp.Create("/tmp/foo"); err != nil { - t.Errorf("Failed to set real path") - } - - if fh, err := bp.Create("../tmp/bar"); err == nil { - t.Errorf("succeeded in creating %s ...", fh.Name()) - } -} - -func TestBasePathRoot(t *testing.T) { - baseFs := &MemMapFs{} - baseFs.MkdirAll("/base/path/foo/baz", 0777) - baseFs.MkdirAll("/base/path/boo/", 0777) - bp := NewBasePathFs(baseFs, "/base/path") - - rd, err := ReadDir(bp, string(os.PathSeparator)) - - if len(rd) != 2 { - t.Errorf("base path doesn't respect root") - } - - if err != nil { - t.Error(err) - } -} - -func TestRealPath(t *testing.T) { - fs := NewOsFs() - baseDir, err := TempDir(fs, "", "base") - if err != nil { - t.Fatal("error creating tempDir", err) - } - defer fs.RemoveAll(baseDir) - anotherDir, err := TempDir(fs, "", "another") - if err != nil { - t.Fatal("error creating tempDir", err) - } - defer fs.RemoveAll(anotherDir) - - bp := NewBasePathFs(fs, baseDir).(*BasePathFs) - - subDir := filepath.Join(baseDir, "s1") - - realPath, err := bp.RealPath("/s1") - - if err != nil { - t.Errorf("Got error %s", err) - } - - if realPath != subDir { - t.Errorf("Expected \n%s got \n%s", subDir, realPath) - } - - if runtime.GOOS == "windows" { - _, err = bp.RealPath(anotherDir) - - if err == nil { - t.Errorf("Expected error") - } - - } else { - // on *nix we have no way of just looking at the path and tell that anotherDir - // is not inside the base file system. - // The user will receive an os.ErrNotExist later. - surrealPath, err := bp.RealPath(anotherDir) - - if err != nil { - t.Errorf("Got error %s", err) - } - - excpected := filepath.Join(baseDir, anotherDir) - - if surrealPath != excpected { - t.Errorf("Expected \n%s got \n%s", excpected, surrealPath) - } - } - -} - -func TestNestedBasePaths(t *testing.T) { - type dirSpec struct { - Dir1, Dir2, Dir3 string - } - dirSpecs := []dirSpec{ - dirSpec{Dir1: "/", Dir2: "/", Dir3: "/"}, - dirSpec{Dir1: "/", Dir2: "/path2", Dir3: "/"}, - dirSpec{Dir1: "/path1/dir", Dir2: "/path2/dir/", Dir3: "/path3/dir"}, - dirSpec{Dir1: "C:/path1", Dir2: "path2/dir", Dir3: "/path3/dir/"}, - } - - for _, ds := range dirSpecs { - memFs := NewMemMapFs() - level1Fs := NewBasePathFs(memFs, ds.Dir1) - level2Fs := NewBasePathFs(level1Fs, ds.Dir2) - level3Fs := NewBasePathFs(level2Fs, ds.Dir3) - - type spec struct { - BaseFs Fs - FileName string - } - specs := []spec{ - spec{BaseFs: level3Fs, FileName: "f.txt"}, - spec{BaseFs: level2Fs, FileName: "f.txt"}, - spec{BaseFs: level1Fs, FileName: "f.txt"}, - } - - for _, s := range specs { - if err := s.BaseFs.MkdirAll(s.FileName, 0755); err != nil { - t.Errorf("Got error %s", err.Error()) - } - if _, err := s.BaseFs.Stat(s.FileName); err != nil { - t.Errorf("Got error %s", err.Error()) - } - - if s.BaseFs == level3Fs { - pathToExist := filepath.Join(ds.Dir3, s.FileName) - if _, err := level2Fs.Stat(pathToExist); err != nil { - t.Errorf("Got error %s (path %s)", err.Error(), pathToExist) - } - } else if s.BaseFs == level2Fs { - pathToExist := filepath.Join(ds.Dir2, ds.Dir3, s.FileName) - if _, err := level1Fs.Stat(pathToExist); err != nil { - t.Errorf("Got error %s (path %s)", err.Error(), pathToExist) - } - } - } - } -} diff --git a/vendor/github.com/spf13/afero/cacheOnReadFs.go b/vendor/github.com/spf13/afero/cacheOnReadFs.go index b026e0de83..29a26c67dd 100644 --- a/vendor/github.com/spf13/afero/cacheOnReadFs.go +++ b/vendor/github.com/spf13/afero/cacheOnReadFs.go @@ -205,7 +205,7 @@ func (u *CacheOnReadFs) OpenFile(name string, flag int, perm os.FileMode) (File, bfi.Close() // oops, what if O_TRUNC was set and file opening in the layer failed...? return nil, err } - return &UnionFile{base: bfi, layer: lfi}, nil + return &UnionFile{Base: bfi, Layer: lfi}, nil } return u.layer.OpenFile(name, flag, perm) } @@ -251,7 +251,7 @@ func (u *CacheOnReadFs) Open(name string) (File, error) { if err != nil && bfile == nil { return nil, err } - return &UnionFile{base: bfile, layer: lfile}, nil + return &UnionFile{Base: bfile, Layer: lfile}, nil } func (u *CacheOnReadFs) Mkdir(name string, perm os.FileMode) error { @@ -286,5 +286,5 @@ func (u *CacheOnReadFs) Create(name string) (File, error) { bfh.Close() return nil, err } - return &UnionFile{base: bfh, layer: lfh}, nil + return &UnionFile{Base: bfh, Layer: lfh}, nil } diff --git a/vendor/github.com/spf13/afero/composite_test.go b/vendor/github.com/spf13/afero/composite_test.go deleted file mode 100644 index 8e44611dcb..0000000000 --- a/vendor/github.com/spf13/afero/composite_test.go +++ /dev/null @@ -1,404 +0,0 @@ -package afero - -import ( - "bytes" - "fmt" - "io/ioutil" - "os" - "testing" - "time" -) - -var tempDirs []string - -func NewTempOsBaseFs(t *testing.T) Fs { - name, err := TempDir(NewOsFs(), "", "") - if err != nil { - t.Error("error creating tempDir", err) - } - - tempDirs = append(tempDirs, name) - - return NewBasePathFs(NewOsFs(), name) -} - -func CleanupTempDirs(t *testing.T) { - osfs := NewOsFs() - type ev struct { - path string - e error - } - - errs := []ev{} - - for _, x := range tempDirs { - err := osfs.RemoveAll(x) - if err != nil { - errs = append(errs, ev{path: x, e: err}) - } - } - - for _, e := range errs { - fmt.Println("error removing tempDir", e.path, e.e) - } - - if len(errs) > 0 { - t.Error("error cleaning up tempDirs") - } - tempDirs = []string{} -} - -func TestUnionCreateExisting(t *testing.T) { - base := &MemMapFs{} - roBase := &ReadOnlyFs{source: base} - - ufs := NewCopyOnWriteFs(roBase, &MemMapFs{}) - - base.MkdirAll("/home/test", 0777) - fh, _ := base.Create("/home/test/file.txt") - fh.WriteString("This is a test") - fh.Close() - - fh, err := ufs.OpenFile("/home/test/file.txt", os.O_RDWR, 0666) - if err != nil { - t.Errorf("Failed to open file r/w: %s", err) - } - - _, err = fh.Write([]byte("####")) - if err != nil { - t.Errorf("Failed to write file: %s", err) - } - fh.Seek(0, 0) - data, err := ioutil.ReadAll(fh) - if err != nil { - t.Errorf("Failed to read file: %s", err) - } - if string(data) != "#### is a test" { - t.Errorf("Got wrong data") - } - fh.Close() - - fh, _ = base.Open("/home/test/file.txt") - data, err = ioutil.ReadAll(fh) - if string(data) != "This is a test" { - t.Errorf("Got wrong data in base file") - } - fh.Close() - - fh, err = ufs.Create("/home/test/file.txt") - switch err { - case nil: - if fi, _ := fh.Stat(); fi.Size() != 0 { - t.Errorf("Create did not truncate file") - } - fh.Close() - default: - t.Errorf("Create failed on existing file") - } - -} - -func TestUnionMergeReaddir(t *testing.T) { - base := &MemMapFs{} - roBase := &ReadOnlyFs{source: base} - - ufs := &CopyOnWriteFs{base: roBase, layer: &MemMapFs{}} - - base.MkdirAll("/home/test", 0777) - fh, _ := base.Create("/home/test/file.txt") - fh.WriteString("This is a test") - fh.Close() - - fh, _ = ufs.Create("/home/test/file2.txt") - fh.WriteString("This is a test") - fh.Close() - - fh, _ = ufs.Open("/home/test") - files, err := fh.Readdirnames(-1) - if err != nil { - t.Errorf("Readdirnames failed") - } - if len(files) != 2 { - t.Errorf("Got wrong number of files: %v", files) - } -} - -func TestExistingDirectoryCollisionReaddir(t *testing.T) { - base := &MemMapFs{} - roBase := &ReadOnlyFs{source: base} - overlay := &MemMapFs{} - - ufs := &CopyOnWriteFs{base: roBase, layer: overlay} - - base.MkdirAll("/home/test", 0777) - fh, _ := base.Create("/home/test/file.txt") - fh.WriteString("This is a test") - fh.Close() - - overlay.MkdirAll("home/test", 0777) - fh, _ = overlay.Create("/home/test/file2.txt") - fh.WriteString("This is a test") - fh.Close() - - fh, _ = ufs.Create("/home/test/file3.txt") - fh.WriteString("This is a test") - fh.Close() - - fh, _ = ufs.Open("/home/test") - files, err := fh.Readdirnames(-1) - if err != nil { - t.Errorf("Readdirnames failed") - } - if len(files) != 3 { - t.Errorf("Got wrong number of files in union: %v", files) - } - - fh, _ = overlay.Open("/home/test") - files, err = fh.Readdirnames(-1) - if err != nil { - t.Errorf("Readdirnames failed") - } - if len(files) != 2 { - t.Errorf("Got wrong number of files in overlay: %v", files) - } -} - -func TestNestedDirBaseReaddir(t *testing.T) { - base := &MemMapFs{} - roBase := &ReadOnlyFs{source: base} - overlay := &MemMapFs{} - - ufs := &CopyOnWriteFs{base: roBase, layer: overlay} - - base.MkdirAll("/home/test/foo/bar", 0777) - fh, _ := base.Create("/home/test/file.txt") - fh.WriteString("This is a test") - fh.Close() - - fh, _ = base.Create("/home/test/foo/file2.txt") - fh.WriteString("This is a test") - fh.Close() - fh, _ = base.Create("/home/test/foo/bar/file3.txt") - fh.WriteString("This is a test") - fh.Close() - - overlay.MkdirAll("/", 0777) - - // Opening something only in the base - fh, _ = ufs.Open("/home/test/foo") - list, err := fh.Readdir(-1) - if err != nil { - t.Errorf("Readdir failed %s", err) - } - if len(list) != 2 { - for _, x := range list { - fmt.Println(x.Name()) - } - t.Errorf("Got wrong number of files in union: %v", len(list)) - } -} - -func TestNestedDirOverlayReaddir(t *testing.T) { - base := &MemMapFs{} - roBase := &ReadOnlyFs{source: base} - overlay := &MemMapFs{} - - ufs := &CopyOnWriteFs{base: roBase, layer: overlay} - - base.MkdirAll("/", 0777) - overlay.MkdirAll("/home/test/foo/bar", 0777) - fh, _ := overlay.Create("/home/test/file.txt") - fh.WriteString("This is a test") - fh.Close() - fh, _ = overlay.Create("/home/test/foo/file2.txt") - fh.WriteString("This is a test") - fh.Close() - fh, _ = overlay.Create("/home/test/foo/bar/file3.txt") - fh.WriteString("This is a test") - fh.Close() - - // Opening nested dir only in the overlay - fh, _ = ufs.Open("/home/test/foo") - list, err := fh.Readdir(-1) - if err != nil { - t.Errorf("Readdir failed %s", err) - } - if len(list) != 2 { - for _, x := range list { - fmt.Println(x.Name()) - } - t.Errorf("Got wrong number of files in union: %v", len(list)) - } -} - -func TestNestedDirOverlayOsFsReaddir(t *testing.T) { - defer CleanupTempDirs(t) - base := NewTempOsBaseFs(t) - roBase := &ReadOnlyFs{source: base} - overlay := NewTempOsBaseFs(t) - - ufs := &CopyOnWriteFs{base: roBase, layer: overlay} - - base.MkdirAll("/", 0777) - overlay.MkdirAll("/home/test/foo/bar", 0777) - fh, _ := overlay.Create("/home/test/file.txt") - fh.WriteString("This is a test") - fh.Close() - fh, _ = overlay.Create("/home/test/foo/file2.txt") - fh.WriteString("This is a test") - fh.Close() - fh, _ = overlay.Create("/home/test/foo/bar/file3.txt") - fh.WriteString("This is a test") - fh.Close() - - // Opening nested dir only in the overlay - fh, _ = ufs.Open("/home/test/foo") - list, err := fh.Readdir(-1) - fh.Close() - if err != nil { - t.Errorf("Readdir failed %s", err) - } - if len(list) != 2 { - for _, x := range list { - fmt.Println(x.Name()) - } - t.Errorf("Got wrong number of files in union: %v", len(list)) - } -} - -func TestCopyOnWriteFsWithOsFs(t *testing.T) { - defer CleanupTempDirs(t) - base := NewTempOsBaseFs(t) - roBase := &ReadOnlyFs{source: base} - overlay := NewTempOsBaseFs(t) - - ufs := &CopyOnWriteFs{base: roBase, layer: overlay} - - base.MkdirAll("/home/test", 0777) - fh, _ := base.Create("/home/test/file.txt") - fh.WriteString("This is a test") - fh.Close() - - overlay.MkdirAll("home/test", 0777) - fh, _ = overlay.Create("/home/test/file2.txt") - fh.WriteString("This is a test") - fh.Close() - - fh, _ = ufs.Create("/home/test/file3.txt") - fh.WriteString("This is a test") - fh.Close() - - fh, _ = ufs.Open("/home/test") - files, err := fh.Readdirnames(-1) - fh.Close() - if err != nil { - t.Errorf("Readdirnames failed") - } - if len(files) != 3 { - t.Errorf("Got wrong number of files in union: %v", files) - } - - fh, _ = overlay.Open("/home/test") - files, err = fh.Readdirnames(-1) - fh.Close() - if err != nil { - t.Errorf("Readdirnames failed") - } - if len(files) != 2 { - t.Errorf("Got wrong number of files in overlay: %v", files) - } -} - -func TestUnionCacheWrite(t *testing.T) { - base := &MemMapFs{} - layer := &MemMapFs{} - - ufs := NewCacheOnReadFs(base, layer, 0) - - base.Mkdir("/data", 0777) - - fh, err := ufs.Create("/data/file.txt") - if err != nil { - t.Errorf("Failed to create file") - } - _, err = fh.Write([]byte("This is a test")) - if err != nil { - t.Errorf("Failed to write file") - } - - fh.Seek(0, os.SEEK_SET) - buf := make([]byte, 4) - _, err = fh.Read(buf) - fh.Write([]byte(" IS A")) - fh.Close() - - baseData, _ := ReadFile(base, "/data/file.txt") - layerData, _ := ReadFile(layer, "/data/file.txt") - if string(baseData) != string(layerData) { - t.Errorf("Different data: %s <=> %s", baseData, layerData) - } -} - -func TestUnionCacheExpire(t *testing.T) { - base := &MemMapFs{} - layer := &MemMapFs{} - ufs := &CacheOnReadFs{base: base, layer: layer, cacheTime: 1 * time.Second} - - base.Mkdir("/data", 0777) - - fh, err := ufs.Create("/data/file.txt") - if err != nil { - t.Errorf("Failed to create file") - } - _, err = fh.Write([]byte("This is a test")) - if err != nil { - t.Errorf("Failed to write file") - } - fh.Close() - - fh, _ = base.Create("/data/file.txt") - // sleep some time, so we really get a different time.Now() on write... - time.Sleep(2 * time.Second) - fh.WriteString("Another test") - fh.Close() - - data, _ := ReadFile(ufs, "/data/file.txt") - if string(data) != "Another test" { - t.Errorf("cache time failed: <%s>", data) - } -} - -func TestCacheOnReadFsNotInLayer(t *testing.T) { - base := NewMemMapFs() - layer := NewMemMapFs() - fs := NewCacheOnReadFs(base, layer, 0) - - fh, err := base.Create("/file.txt") - if err != nil { - t.Fatal("unable to create file: ", err) - } - - txt := []byte("This is a test") - fh.Write(txt) - fh.Close() - - fh, err = fs.Open("/file.txt") - if err != nil { - t.Fatal("could not open file: ", err) - } - - b, err := ReadAll(fh) - fh.Close() - - if err != nil { - t.Fatal("could not read file: ", err) - } else if !bytes.Equal(txt, b) { - t.Fatalf("wanted file text %q, got %q", txt, b) - } - - fh, err = layer.Open("/file.txt") - if err != nil { - t.Fatal("could not open file from layer: ", err) - } - fh.Close() -} diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs.go b/vendor/github.com/spf13/afero/copyOnWriteFs.go index f2ebcd2266..9aef39794c 100644 --- a/vendor/github.com/spf13/afero/copyOnWriteFs.go +++ b/vendor/github.com/spf13/afero/copyOnWriteFs.go @@ -8,6 +8,8 @@ import ( "time" ) +var _ Lstater = (*CopyOnWriteFs)(nil) + // The CopyOnWriteFs is a union filesystem: a read only base file system with // a possibly writeable layer on top. Changes to the file system will only // be made in the overlay: Changing an existing file in the base layer which @@ -76,18 +78,55 @@ func (u *CopyOnWriteFs) Chmod(name string, mode os.FileMode) error { func (u *CopyOnWriteFs) Stat(name string) (os.FileInfo, error) { fi, err := u.layer.Stat(name) if err != nil { - origErr := err - if e, ok := err.(*os.PathError); ok { - err = e.Err - } - if err == os.ErrNotExist || err == syscall.ENOENT || err == syscall.ENOTDIR { + isNotExist := u.isNotExist(err) + if isNotExist { return u.base.Stat(name) } - return nil, origErr + return nil, err } return fi, nil } +func (u *CopyOnWriteFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { + llayer, ok1 := u.layer.(Lstater) + lbase, ok2 := u.base.(Lstater) + + if ok1 { + fi, b, err := llayer.LstatIfPossible(name) + if err == nil { + return fi, b, nil + } + + if !u.isNotExist(err) { + return nil, b, err + } + } + + if ok2 { + fi, b, err := lbase.LstatIfPossible(name) + if err == nil { + return fi, b, nil + } + if !u.isNotExist(err) { + return nil, b, err + } + } + + fi, err := u.Stat(name) + + return fi, false, err +} + +func (u *CopyOnWriteFs) isNotExist(err error) bool { + if e, ok := err.(*os.PathError); ok { + err = e.Err + } + if err == os.ErrNotExist || err == syscall.ENOENT || err == syscall.ENOTDIR { + return true + } + return false +} + // Renaming files present only in the base layer is not permitted func (u *CopyOnWriteFs) Rename(oldname, newname string) error { b, err := u.isBaseFile(oldname) @@ -219,7 +258,7 @@ func (u *CopyOnWriteFs) Open(name string) (File, error) { return nil, fmt.Errorf("BaseErr: %v\nOverlayErr: %v", bErr, lErr) } - return &UnionFile{base: bfile, layer: lfile}, nil + return &UnionFile{Base: bfile, Layer: lfile}, nil } func (u *CopyOnWriteFs) Mkdir(name string, perm os.FileMode) error { diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs_test.go b/vendor/github.com/spf13/afero/copyOnWriteFs_test.go deleted file mode 100644 index c6f2c6d625..0000000000 --- a/vendor/github.com/spf13/afero/copyOnWriteFs_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package afero - -import "testing" - -func TestCopyOnWrite(t *testing.T) { - var fs Fs - var err error - base := NewOsFs() - roBase := NewReadOnlyFs(base) - ufs := NewCopyOnWriteFs(roBase, NewMemMapFs()) - fs = ufs - err = fs.MkdirAll("nonexistent/directory/", 0744) - if err != nil { - t.Error(err) - return - } - _, err = fs.Create("nonexistent/directory/newfile") - if err != nil { - t.Error(err) - return - } - -} - -func TestCopyOnWriteFileInMemMapBase(t *testing.T) { - base := &MemMapFs{} - layer := &MemMapFs{} - - if err := WriteFile(base, "base.txt", []byte("base"), 0755); err != nil { - t.Fatalf("Failed to write file: %s", err) - } - - ufs := NewCopyOnWriteFs(base, layer) - - _, err := ufs.Stat("base.txt") - if err != nil { - t.Fatal(err) - } -} diff --git a/vendor/github.com/spf13/afero/ioutil_test.go b/vendor/github.com/spf13/afero/ioutil_test.go deleted file mode 100644 index e7c9f06987..0000000000 --- a/vendor/github.com/spf13/afero/ioutil_test.go +++ /dev/null @@ -1,112 +0,0 @@ -// ©2015 The Go Authors -// Copyright ©2015 Steve Francia -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package afero - -import "testing" - -func checkSizePath(t *testing.T, path string, size int64) { - dir, err := testFS.Stat(path) - if err != nil { - t.Fatalf("Stat %q (looking for size %d): %s", path, size, err) - } - if dir.Size() != size { - t.Errorf("Stat %q: size %d want %d", path, dir.Size(), size) - } -} - -func TestReadFile(t *testing.T) { - testFS = &MemMapFs{} - fsutil := &Afero{Fs: testFS} - - testFS.Create("this_exists.go") - filename := "rumpelstilzchen" - contents, err := fsutil.ReadFile(filename) - if err == nil { - t.Fatalf("ReadFile %s: error expected, none found", filename) - } - - filename = "this_exists.go" - contents, err = fsutil.ReadFile(filename) - if err != nil { - t.Fatalf("ReadFile %s: %v", filename, err) - } - - checkSizePath(t, filename, int64(len(contents))) -} - -func TestWriteFile(t *testing.T) { - testFS = &MemMapFs{} - fsutil := &Afero{Fs: testFS} - f, err := fsutil.TempFile("", "ioutil-test") - if err != nil { - t.Fatal(err) - } - filename := f.Name() - data := "Programming today is a race between software engineers striving to " + - "build bigger and better idiot-proof programs, and the Universe trying " + - "to produce bigger and better idiots. So far, the Universe is winning." - - if err := fsutil.WriteFile(filename, []byte(data), 0644); err != nil { - t.Fatalf("WriteFile %s: %v", filename, err) - } - - contents, err := fsutil.ReadFile(filename) - if err != nil { - t.Fatalf("ReadFile %s: %v", filename, err) - } - - if string(contents) != data { - t.Fatalf("contents = %q\nexpected = %q", string(contents), data) - } - - // cleanup - f.Close() - testFS.Remove(filename) // ignore error -} - -func TestReadDir(t *testing.T) { - testFS = &MemMapFs{} - testFS.Mkdir("/i-am-a-dir", 0777) - testFS.Create("/this_exists.go") - dirname := "rumpelstilzchen" - _, err := ReadDir(testFS, dirname) - if err == nil { - t.Fatalf("ReadDir %s: error expected, none found", dirname) - } - - dirname = ".." - list, err := ReadDir(testFS, dirname) - if err != nil { - t.Fatalf("ReadDir %s: %v", dirname, err) - } - - foundFile := false - foundSubDir := false - for _, dir := range list { - switch { - case !dir.IsDir() && dir.Name() == "this_exists.go": - foundFile = true - case dir.IsDir() && dir.Name() == "i-am-a-dir": - foundSubDir = true - } - } - if !foundFile { - t.Fatalf("ReadDir %s: this_exists.go file not found", dirname) - } - if !foundSubDir { - t.Fatalf("ReadDir %s: i-am-a-dir directory not found", dirname) - } -} diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric_test.go b/vendor/github.com/spf13/afero/lstater.go similarity index 50% rename from vendor/github.com/prometheus/client_golang/prometheus/metric_test.go rename to vendor/github.com/spf13/afero/lstater.go index 7145f5e53c..89c1bfc0a7 100644 --- a/vendor/github.com/prometheus/client_golang/prometheus/metric_test.go +++ b/vendor/github.com/spf13/afero/lstater.go @@ -1,8 +1,8 @@ -// Copyright 2014 The Prometheus Authors +// Copyright © 2018 Steve Francia . +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at -// // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software @@ -11,25 +11,17 @@ // See the License for the specific language governing permissions and // limitations under the License. -package prometheus - -import "testing" +package afero -func TestBuildFQName(t *testing.T) { - scenarios := []struct{ namespace, subsystem, name, result string }{ - {"a", "b", "c", "a_b_c"}, - {"", "b", "c", "b_c"}, - {"a", "", "c", "a_c"}, - {"", "", "c", "c"}, - {"a", "b", "", ""}, - {"a", "", "", ""}, - {"", "b", "", ""}, - {" ", "", "", ""}, - } +import ( + "os" +) - for i, s := range scenarios { - if want, got := s.result, BuildFQName(s.namespace, s.subsystem, s.name); want != got { - t.Errorf("%d. want %s, got %s", i, want, got) - } - } +// Lstater is an optional interface in Afero. It is only implemented by the +// filesystems saying so. +// It will call Lstat if the filesystem iself is, or it delegates to, the os filesystem. +// Else it will call Stat. +// In addtion to the FileInfo, it will return a boolean telling whether Lstat was called or not. +type Lstater interface { + LstatIfPossible(name string) (os.FileInfo, bool, error) } diff --git a/vendor/github.com/spf13/afero/match.go b/vendor/github.com/spf13/afero/match.go index 08b3b7e014..c18a87fb71 100644 --- a/vendor/github.com/spf13/afero/match.go +++ b/vendor/github.com/spf13/afero/match.go @@ -33,8 +33,8 @@ import ( // built-ins from that package. func Glob(fs Fs, pattern string) (matches []string, err error) { if !hasMeta(pattern) { - // afero does not support Lstat directly. - if _, err = lstatIfOs(fs, pattern); err != nil { + // Lstat not supported by a ll filesystems. + if _, err = lstatIfPossible(fs, pattern); err != nil { return nil, nil } return []string{pattern}, nil diff --git a/vendor/github.com/spf13/afero/match_test.go b/vendor/github.com/spf13/afero/match_test.go deleted file mode 100644 index 21e1faecdb..0000000000 --- a/vendor/github.com/spf13/afero/match_test.go +++ /dev/null @@ -1,183 +0,0 @@ -// Copyright © 2014 Steve Francia . -// Copyright 2009 The Go Authors. 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 afero - -import ( - "os" - "path/filepath" - "runtime" - "testing" -) - -// contains returns true if vector contains the string s. -func contains(vector []string, s string) bool { - for _, elem := range vector { - if elem == s { - return true - } - } - return false -} - -func setupGlobDirRoot(t *testing.T, fs Fs) string { - path := testDir(fs) - setupGlobFiles(t, fs, path) - return path -} - -func setupGlobDirReusePath(t *testing.T, fs Fs, path string) string { - testRegistry[fs] = append(testRegistry[fs], path) - return setupGlobFiles(t, fs, path) -} - -func setupGlobFiles(t *testing.T, fs Fs, path string) string { - testSubDir := filepath.Join(path, "globs", "bobs") - err := fs.MkdirAll(testSubDir, 0700) - if err != nil && !os.IsExist(err) { - t.Fatal(err) - } - - f, err := fs.Create(filepath.Join(testSubDir, "/matcher")) - if err != nil { - t.Fatal(err) - } - f.WriteString("Testfile 1 content") - f.Close() - - f, err = fs.Create(filepath.Join(testSubDir, "/../submatcher")) - if err != nil { - t.Fatal(err) - } - f.WriteString("Testfile 2 content") - f.Close() - - f, err = fs.Create(filepath.Join(testSubDir, "/../../match")) - if err != nil { - t.Fatal(err) - } - f.WriteString("Testfile 3 content") - f.Close() - - return testSubDir -} - -func TestGlob(t *testing.T) { - defer removeAllTestFiles(t) - var testDir string - for i, fs := range Fss { - if i == 0 { - testDir = setupGlobDirRoot(t, fs) - } else { - setupGlobDirReusePath(t, fs, testDir) - } - } - - var globTests = []struct { - pattern, result string - }{ - {testDir + "/globs/bobs/matcher", testDir + "/globs/bobs/matcher"}, - {testDir + "/globs/*/mat?her", testDir + "/globs/bobs/matcher"}, - {testDir + "/globs/bobs/../*", testDir + "/globs/submatcher"}, - {testDir + "/match", testDir + "/match"}, - } - - for _, fs := range Fss { - - for _, tt := range globTests { - pattern := tt.pattern - result := tt.result - if runtime.GOOS == "windows" { - pattern = filepath.Clean(pattern) - result = filepath.Clean(result) - } - matches, err := Glob(fs, pattern) - if err != nil { - t.Errorf("Glob error for %q: %s", pattern, err) - continue - } - if !contains(matches, result) { - t.Errorf("Glob(%#q) = %#v want %v", pattern, matches, result) - } - } - for _, pattern := range []string{"no_match", "../*/no_match"} { - matches, err := Glob(fs, pattern) - if err != nil { - t.Errorf("Glob error for %q: %s", pattern, err) - continue - } - if len(matches) != 0 { - t.Errorf("Glob(%#q) = %#v want []", pattern, matches) - } - } - - } -} - -func TestGlobSymlink(t *testing.T) { - defer removeAllTestFiles(t) - - fs := &OsFs{} - testDir := setupGlobDirRoot(t, fs) - - err := os.Symlink("target", filepath.Join(testDir, "symlink")) - if err != nil { - t.Skipf("skipping on %s", runtime.GOOS) - } - - var globSymlinkTests = []struct { - path, dest string - brokenLink bool - }{ - {"test1", "link1", false}, - {"test2", "link2", true}, - } - - for _, tt := range globSymlinkTests { - path := filepath.Join(testDir, tt.path) - dest := filepath.Join(testDir, tt.dest) - f, err := fs.Create(path) - if err != nil { - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } - err = os.Symlink(path, dest) - if err != nil { - t.Fatal(err) - } - if tt.brokenLink { - // Break the symlink. - fs.Remove(path) - } - matches, err := Glob(fs, dest) - if err != nil { - t.Errorf("GlobSymlink error for %q: %s", dest, err) - } - if !contains(matches, dest) { - t.Errorf("Glob(%#q) = %#v want %v", dest, matches, dest) - } - } -} - - -func TestGlobError(t *testing.T) { - for _, fs := range Fss { - _, err := Glob(fs, "[7]") - if err != nil { - t.Error("expected error for bad pattern; got none") - } - } -} diff --git a/vendor/github.com/spf13/afero/mem/file.go b/vendor/github.com/spf13/afero/mem/file.go index 5401a3b7c0..885e554295 100644 --- a/vendor/github.com/spf13/afero/mem/file.go +++ b/vendor/github.com/spf13/afero/mem/file.go @@ -176,6 +176,9 @@ func (f *File) Read(b []byte) (n int, err error) { if len(b) > 0 && int(f.at) == len(f.fileData.data) { return 0, io.EOF } + if int(f.at) > len(f.fileData.data) { + return 0, io.ErrUnexpectedEOF + } if len(f.fileData.data)-int(f.at) >= len(b) { n = len(b) } else { diff --git a/vendor/github.com/spf13/afero/mem/file_test.go b/vendor/github.com/spf13/afero/mem/file_test.go deleted file mode 100644 index 5769067a73..0000000000 --- a/vendor/github.com/spf13/afero/mem/file_test.go +++ /dev/null @@ -1,154 +0,0 @@ -package mem - -import ( - "testing" - "time" -) - -func TestFileDataNameRace(t *testing.T) { - t.Parallel() - const someName = "someName" - const someOtherName = "someOtherName" - d := FileData{ - name: someName, - } - - if d.Name() != someName { - t.Errorf("Failed to read correct Name, was %v", d.Name()) - } - - ChangeFileName(&d, someOtherName) - if d.Name() != someOtherName { - t.Errorf("Failed to set Name, was %v", d.Name()) - } - - go func() { - ChangeFileName(&d, someName) - }() - - if d.Name() != someName && d.Name() != someOtherName { - t.Errorf("Failed to read either Name, was %v", d.Name()) - } -} - -func TestFileDataModTimeRace(t *testing.T) { - t.Parallel() - someTime := time.Now() - someOtherTime := someTime.Add(1 * time.Minute) - - d := FileData{ - modtime: someTime, - } - - s := FileInfo{ - FileData: &d, - } - - if s.ModTime() != someTime { - t.Errorf("Failed to read correct value, was %v", s.ModTime()) - } - - SetModTime(&d, someOtherTime) - if s.ModTime() != someOtherTime { - t.Errorf("Failed to set ModTime, was %v", s.ModTime()) - } - - go func() { - SetModTime(&d, someTime) - }() - - if s.ModTime() != someTime && s.ModTime() != someOtherTime { - t.Errorf("Failed to read either modtime, was %v", s.ModTime()) - } -} - -func TestFileDataModeRace(t *testing.T) { - t.Parallel() - const someMode = 0777 - const someOtherMode = 0660 - - d := FileData{ - mode: someMode, - } - - s := FileInfo{ - FileData: &d, - } - - if s.Mode() != someMode { - t.Errorf("Failed to read correct value, was %v", s.Mode()) - } - - SetMode(&d, someOtherMode) - if s.Mode() != someOtherMode { - t.Errorf("Failed to set Mode, was %v", s.Mode()) - } - - go func() { - SetMode(&d, someMode) - }() - - if s.Mode() != someMode && s.Mode() != someOtherMode { - t.Errorf("Failed to read either mode, was %v", s.Mode()) - } -} - -func TestFileDataIsDirRace(t *testing.T) { - t.Parallel() - - d := FileData{ - dir: true, - } - - s := FileInfo{ - FileData: &d, - } - - if s.IsDir() != true { - t.Errorf("Failed to read correct value, was %v", s.IsDir()) - } - - go func() { - s.Lock() - d.dir = false - s.Unlock() - }() - - //just logging the value to trigger a read: - t.Logf("Value is %v", s.IsDir()) -} - -func TestFileDataSizeRace(t *testing.T) { - t.Parallel() - - const someData = "Hello" - const someOtherDataSize = "Hello World" - - d := FileData{ - data: []byte(someData), - dir: false, - } - - s := FileInfo{ - FileData: &d, - } - - if s.Size() != int64(len(someData)) { - t.Errorf("Failed to read correct value, was %v", s.Size()) - } - - go func() { - s.Lock() - d.data = []byte(someOtherDataSize) - s.Unlock() - }() - - //just logging the value to trigger a read: - t.Logf("Value is %v", s.Size()) - - //Testing the Dir size case - d.dir = true - if s.Size() != int64(42) { - t.Errorf("Failed to read correct value for dir, was %v", s.Size()) - } -} diff --git a/vendor/github.com/spf13/afero/memmap_test.go b/vendor/github.com/spf13/afero/memmap_test.go deleted file mode 100644 index 09d8680f67..0000000000 --- a/vendor/github.com/spf13/afero/memmap_test.go +++ /dev/null @@ -1,421 +0,0 @@ -package afero - -import ( - "fmt" - "os" - "path/filepath" - "runtime" - "testing" - "time" -) - -func TestNormalizePath(t *testing.T) { - type test struct { - input string - expected string - } - - data := []test{ - {".", FilePathSeparator}, - {"./", FilePathSeparator}, - {"..", FilePathSeparator}, - {"../", FilePathSeparator}, - {"./..", FilePathSeparator}, - {"./../", FilePathSeparator}, - } - - for i, d := range data { - cpath := normalizePath(d.input) - if d.expected != cpath { - t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, cpath) - } - } -} - -func TestPathErrors(t *testing.T) { - path := filepath.Join(".", "some", "path") - path2 := filepath.Join(".", "different", "path") - fs := NewMemMapFs() - perm := os.FileMode(0755) - - // relevant functions: - // func (m *MemMapFs) Chmod(name string, mode os.FileMode) error - // func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error - // func (m *MemMapFs) Create(name string) (File, error) - // func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error - // func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error - // func (m *MemMapFs) Open(name string) (File, error) - // func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) - // func (m *MemMapFs) Remove(name string) error - // func (m *MemMapFs) Rename(oldname, newname string) error - // func (m *MemMapFs) Stat(name string) (os.FileInfo, error) - - err := fs.Chmod(path, perm) - checkPathError(t, err, "Chmod") - - err = fs.Chtimes(path, time.Now(), time.Now()) - checkPathError(t, err, "Chtimes") - - // fs.Create doesn't return an error - - err = fs.Mkdir(path2, perm) - if err != nil { - t.Error(err) - } - err = fs.Mkdir(path2, perm) - checkPathError(t, err, "Mkdir") - - err = fs.MkdirAll(path2, perm) - if err != nil { - t.Error("MkdirAll:", err) - } - - _, err = fs.Open(path) - checkPathError(t, err, "Open") - - _, err = fs.OpenFile(path, os.O_RDWR, perm) - checkPathError(t, err, "OpenFile") - - err = fs.Remove(path) - checkPathError(t, err, "Remove") - - err = fs.RemoveAll(path) - if err != nil { - t.Error("RemoveAll:", err) - } - - err = fs.Rename(path, path2) - checkPathError(t, err, "Rename") - - _, err = fs.Stat(path) - checkPathError(t, err, "Stat") -} - -func checkPathError(t *testing.T, err error, op string) { - pathErr, ok := err.(*os.PathError) - if !ok { - t.Error(op+":", err, "is not a os.PathError") - return - } - _, ok = pathErr.Err.(*os.PathError) - if ok { - t.Error(op+":", err, "contains another os.PathError") - } -} - -// Ensure Permissions are set on OpenFile/Mkdir/MkdirAll -func TestPermSet(t *testing.T) { - const fileName = "/myFileTest" - const dirPath = "/myDirTest" - const dirPathAll = "/my/path/to/dir" - - const fileMode = os.FileMode(0765) - // directories will also have the directory bit set - const dirMode = fileMode | os.ModeDir - - fs := NewMemMapFs() - - // Test Openfile - f, err := fs.OpenFile(fileName, os.O_CREATE, fileMode) - if err != nil { - t.Errorf("OpenFile Create failed: %s", err) - return - } - f.Close() - - s, err := fs.Stat(fileName) - if err != nil { - t.Errorf("Stat failed: %s", err) - return - } - if s.Mode().String() != fileMode.String() { - t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), fileMode.String()) - return - } - - // Test Mkdir - err = fs.Mkdir(dirPath, dirMode) - if err != nil { - t.Errorf("MkDir Create failed: %s", err) - return - } - s, err = fs.Stat(dirPath) - if err != nil { - t.Errorf("Stat failed: %s", err) - return - } - // sets File - if s.Mode().String() != dirMode.String() { - t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), dirMode.String()) - return - } - - // Test MkdirAll - err = fs.MkdirAll(dirPathAll, dirMode) - if err != nil { - t.Errorf("MkDir Create failed: %s", err) - return - } - s, err = fs.Stat(dirPathAll) - if err != nil { - t.Errorf("Stat failed: %s", err) - return - } - if s.Mode().String() != dirMode.String() { - t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), dirMode.String()) - return - } -} - -// Fails if multiple file objects use the same file.at counter in MemMapFs -func TestMultipleOpenFiles(t *testing.T) { - defer removeAllTestFiles(t) - const fileName = "afero-demo2.txt" - - var data = make([][]byte, len(Fss)) - - for i, fs := range Fss { - dir := testDir(fs) - path := filepath.Join(dir, fileName) - fh1, err := fs.Create(path) - if err != nil { - t.Error("fs.Create failed: " + err.Error()) - } - _, err = fh1.Write([]byte("test")) - if err != nil { - t.Error("fh.Write failed: " + err.Error()) - } - _, err = fh1.Seek(0, os.SEEK_SET) - if err != nil { - t.Error(err) - } - - fh2, err := fs.OpenFile(path, os.O_RDWR, 0777) - if err != nil { - t.Error("fs.OpenFile failed: " + err.Error()) - } - _, err = fh2.Seek(0, os.SEEK_END) - if err != nil { - t.Error(err) - } - _, err = fh2.Write([]byte("data")) - if err != nil { - t.Error(err) - } - err = fh2.Close() - if err != nil { - t.Error(err) - } - - _, err = fh1.Write([]byte("data")) - if err != nil { - t.Error(err) - } - err = fh1.Close() - if err != nil { - t.Error(err) - } - // the file now should contain "datadata" - data[i], err = ReadFile(fs, path) - if err != nil { - t.Error(err) - } - } - - for i, fs := range Fss { - if i == 0 { - continue - } - if string(data[0]) != string(data[i]) { - t.Errorf("%s and %s don't behave the same\n"+ - "%s: \"%s\"\n%s: \"%s\"\n", - Fss[0].Name(), fs.Name(), Fss[0].Name(), data[0], fs.Name(), data[i]) - } - } -} - -// Test if file.Write() fails when opened as read only -func TestReadOnly(t *testing.T) { - defer removeAllTestFiles(t) - const fileName = "afero-demo.txt" - - for _, fs := range Fss { - dir := testDir(fs) - path := filepath.Join(dir, fileName) - - f, err := fs.Create(path) - if err != nil { - t.Error(fs.Name()+":", "fs.Create failed: "+err.Error()) - } - _, err = f.Write([]byte("test")) - if err != nil { - t.Error(fs.Name()+":", "Write failed: "+err.Error()) - } - f.Close() - - f, err = fs.Open(path) - if err != nil { - t.Error("fs.Open failed: " + err.Error()) - } - _, err = f.Write([]byte("data")) - if err == nil { - t.Error(fs.Name()+":", "No write error") - } - f.Close() - - f, err = fs.OpenFile(path, os.O_RDONLY, 0644) - if err != nil { - t.Error("fs.Open failed: " + err.Error()) - } - _, err = f.Write([]byte("data")) - if err == nil { - t.Error(fs.Name()+":", "No write error") - } - f.Close() - } -} - -func TestWriteCloseTime(t *testing.T) { - defer removeAllTestFiles(t) - const fileName = "afero-demo.txt" - - for _, fs := range Fss { - dir := testDir(fs) - path := filepath.Join(dir, fileName) - - f, err := fs.Create(path) - if err != nil { - t.Error(fs.Name()+":", "fs.Create failed: "+err.Error()) - } - f.Close() - - f, err = fs.Create(path) - if err != nil { - t.Error(fs.Name()+":", "fs.Create failed: "+err.Error()) - } - fi, err := f.Stat() - if err != nil { - t.Error(fs.Name()+":", "Stat failed: "+err.Error()) - } - timeBefore := fi.ModTime() - - // sorry for the delay, but we have to make sure time advances, - // also on non Un*x systems... - switch runtime.GOOS { - case "windows": - time.Sleep(2 * time.Second) - case "darwin": - time.Sleep(1 * time.Second) - default: // depending on the FS, this may work with < 1 second, on my old ext3 it does not - time.Sleep(1 * time.Second) - } - - _, err = f.Write([]byte("test")) - if err != nil { - t.Error(fs.Name()+":", "Write failed: "+err.Error()) - } - f.Close() - fi, err = fs.Stat(path) - if err != nil { - t.Error(fs.Name()+":", "fs.Stat failed: "+err.Error()) - } - if fi.ModTime().Equal(timeBefore) { - t.Error(fs.Name()+":", "ModTime was not set on Close()") - } - } -} - -// This test should be run with the race detector on: -// go test -race -v -timeout 10s -run TestRacingDeleteAndClose -func TestRacingDeleteAndClose(t *testing.T) { - fs := NewMemMapFs() - pathname := "testfile" - f, err := fs.Create(pathname) - if err != nil { - t.Fatal(err) - } - - in := make(chan bool) - - go func() { - <-in - f.Close() - }() - go func() { - <-in - fs.Remove(pathname) - }() - close(in) -} - -// This test should be run with the race detector on: -// go test -run TestMemFsDataRace -race -func TestMemFsDataRace(t *testing.T) { - const dir = "test_dir" - fs := NewMemMapFs() - - if err := fs.MkdirAll(dir, 0777); err != nil { - t.Fatal(err) - } - - const n = 1000 - done := make(chan struct{}) - - go func() { - defer close(done) - for i := 0; i < n; i++ { - fname := filepath.Join(dir, fmt.Sprintf("%d.txt", i)) - if err := WriteFile(fs, fname, []byte(""), 0777); err != nil { - panic(err) - } - if err := fs.Remove(fname); err != nil { - panic(err) - } - } - }() - -loop: - for { - select { - case <-done: - break loop - default: - _, err := ReadDir(fs, dir) - if err != nil { - t.Fatal(err) - } - } - } -} - -func TestMemFsDirMode(t *testing.T) { - fs := NewMemMapFs() - err := fs.Mkdir("/testDir1", 0644) - if err != nil { - t.Error(err) - } - err = fs.MkdirAll("/sub/testDir2", 0644) - if err != nil { - t.Error(err) - } - info, err := fs.Stat("/testDir1") - if err != nil { - t.Error(err) - } - if !info.IsDir() { - t.Error("should be a directory") - } - if !info.Mode().IsDir() { - t.Error("FileMode is not directory") - } - info, err = fs.Stat("/sub/testDir2") - if err != nil { - t.Error(err) - } - if !info.IsDir() { - t.Error("should be a directory") - } - if !info.Mode().IsDir() { - t.Error("FileMode is not directory") - } -} diff --git a/vendor/github.com/spf13/afero/os.go b/vendor/github.com/spf13/afero/os.go index 6b8bce1c50..13cc1b84c9 100644 --- a/vendor/github.com/spf13/afero/os.go +++ b/vendor/github.com/spf13/afero/os.go @@ -19,6 +19,8 @@ import ( "time" ) +var _ Lstater = (*OsFs)(nil) + // OsFs is a Fs implementation that uses functions provided by the os package. // // For details in any method, check the documentation of the os package @@ -92,3 +94,8 @@ func (OsFs) Chmod(name string, mode os.FileMode) error { func (OsFs) Chtimes(name string, atime time.Time, mtime time.Time) error { return os.Chtimes(name, atime, mtime) } + +func (OsFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { + fi, err := os.Lstat(name) + return fi, true, err +} diff --git a/vendor/github.com/spf13/afero/path.go b/vendor/github.com/spf13/afero/path.go index 1d90e46dd0..18f60a0f6b 100644 --- a/vendor/github.com/spf13/afero/path.go +++ b/vendor/github.com/spf13/afero/path.go @@ -60,7 +60,7 @@ func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error for _, name := range names { filename := filepath.Join(path, name) - fileInfo, err := lstatIfOs(fs, filename) + fileInfo, err := lstatIfPossible(fs, filename) if err != nil { if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir { return err @@ -77,15 +77,13 @@ func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error return nil } -// if the filesystem is OsFs use Lstat, else use fs.Stat -func lstatIfOs(fs Fs, path string) (info os.FileInfo, err error) { - _, ok := fs.(*OsFs) - if ok { - info, err = os.Lstat(path) - } else { - info, err = fs.Stat(path) +// if the filesystem supports it, use Lstat, else use fs.Stat +func lstatIfPossible(fs Fs, path string) (os.FileInfo, error) { + if lfs, ok := fs.(Lstater); ok { + fi, _, err := lfs.LstatIfPossible(path) + return fi, err } - return + return fs.Stat(path) } // Walk walks the file tree rooted at root, calling walkFn for each file or @@ -100,7 +98,7 @@ func (a Afero) Walk(root string, walkFn filepath.WalkFunc) error { } func Walk(fs Fs, root string, walkFn filepath.WalkFunc) error { - info, err := lstatIfOs(fs, root) + info, err := lstatIfPossible(fs, root) if err != nil { return walkFn(root, nil, err) } diff --git a/vendor/github.com/spf13/afero/path_test.go b/vendor/github.com/spf13/afero/path_test.go deleted file mode 100644 index 104a6bcbe3..0000000000 --- a/vendor/github.com/spf13/afero/path_test.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright © 2014 Steve Francia . -// Copyright 2009 The Go Authors. 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 afero - -import ( - "fmt" - "os" - "testing" -) - -func TestWalk(t *testing.T) { - defer removeAllTestFiles(t) - var testDir string - for i, fs := range Fss { - if i == 0 { - testDir = setupTestDirRoot(t, fs) - } else { - setupTestDirReusePath(t, fs, testDir) - } - } - - outputs := make([]string, len(Fss)) - for i, fs := range Fss { - walkFn := func(path string, info os.FileInfo, err error) error { - if err != nil { - t.Error("walkFn err:", err) - } - var size int64 - if !info.IsDir() { - size = info.Size() - } - outputs[i] += fmt.Sprintln(path, info.Name(), size, info.IsDir(), err) - return nil - } - err := Walk(fs, testDir, walkFn) - if err != nil { - t.Error(err) - } - } - fail := false - for i, o := range outputs { - if i == 0 { - continue - } - if o != outputs[i-1] { - fail = true - break - } - } - if fail { - t.Log("Walk outputs not equal!") - for i, o := range outputs { - t.Log(Fss[i].Name() + "\n" + o) - } - t.Fail() - } -} diff --git a/vendor/github.com/spf13/afero/readonlyfs.go b/vendor/github.com/spf13/afero/readonlyfs.go index f1fa55bcf4..c6376ec373 100644 --- a/vendor/github.com/spf13/afero/readonlyfs.go +++ b/vendor/github.com/spf13/afero/readonlyfs.go @@ -6,6 +6,8 @@ import ( "time" ) +var _ Lstater = (*ReadOnlyFs)(nil) + type ReadOnlyFs struct { source Fs } @@ -34,6 +36,14 @@ func (r *ReadOnlyFs) Stat(name string) (os.FileInfo, error) { return r.source.Stat(name) } +func (r *ReadOnlyFs) LstatIfPossible(name string) (os.FileInfo, bool, error) { + if lsf, ok := r.source.(Lstater); ok { + return lsf.LstatIfPossible(name) + } + fi, err := r.Stat(name) + return fi, false, err +} + func (r *ReadOnlyFs) Rename(o, n string) error { return syscall.EPERM } diff --git a/vendor/github.com/spf13/afero/ro_regexp_test.go b/vendor/github.com/spf13/afero/ro_regexp_test.go deleted file mode 100644 index ef8a35d0d9..0000000000 --- a/vendor/github.com/spf13/afero/ro_regexp_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package afero - -import ( - "regexp" - "testing" -) - -func TestFilterReadOnly(t *testing.T) { - fs := &ReadOnlyFs{source: &MemMapFs{}} - _, err := fs.Create("/file.txt") - if err == nil { - t.Errorf("Did not fail to create file") - } - // t.Logf("ERR=%s", err) -} - -func TestFilterReadonlyRemoveAndRead(t *testing.T) { - mfs := &MemMapFs{} - fh, err := mfs.Create("/file.txt") - fh.Write([]byte("content here")) - fh.Close() - - fs := NewReadOnlyFs(mfs) - err = fs.Remove("/file.txt") - if err == nil { - t.Errorf("Did not fail to remove file") - } - - fh, err = fs.Open("/file.txt") - if err != nil { - t.Errorf("Failed to open file: %s", err) - } - - buf := make([]byte, len("content here")) - _, err = fh.Read(buf) - fh.Close() - if string(buf) != "content here" { - t.Errorf("Failed to read file: %s", err) - } - - err = mfs.Remove("/file.txt") - if err != nil { - t.Errorf("Failed to remove file") - } - - fh, err = fs.Open("/file.txt") - if err == nil { - fh.Close() - t.Errorf("File still present") - } -} - -func TestFilterRegexp(t *testing.T) { - fs := NewRegexpFs(&MemMapFs{}, regexp.MustCompile(`\.txt$`)) - _, err := fs.Create("/file.html") - if err == nil { - - t.Errorf("Did not fail to create file") - } - // t.Logf("ERR=%s", err) -} - -func TestFilterRORegexpChain(t *testing.T) { - rofs := &ReadOnlyFs{source: &MemMapFs{}} - fs := &RegexpFs{re: regexp.MustCompile(`\.txt$`), source: rofs} - _, err := fs.Create("/file.txt") - if err == nil { - t.Errorf("Did not fail to create file") - } - // t.Logf("ERR=%s", err) -} - -func TestFilterRegexReadDir(t *testing.T) { - mfs := &MemMapFs{} - fs1 := &RegexpFs{re: regexp.MustCompile(`\.txt$`), source: mfs} - fs := &RegexpFs{re: regexp.MustCompile(`^a`), source: fs1} - - mfs.MkdirAll("/dir/sub", 0777) - for _, name := range []string{"afile.txt", "afile.html", "bfile.txt"} { - for _, dir := range []string{"/dir/", "/dir/sub/"} { - fh, _ := mfs.Create(dir + name) - fh.Close() - } - } - - files, _ := ReadDir(fs, "/dir") - if len(files) != 2 { // afile.txt, sub - t.Errorf("Got wrong number of files: %#v", files) - } - - f, _ := fs.Open("/dir/sub") - names, _ := f.Readdirnames(-1) - if len(names) != 1 { - t.Errorf("Got wrong number of names: %v", names) - } -} diff --git a/vendor/github.com/spf13/afero/unionFile.go b/vendor/github.com/spf13/afero/unionFile.go index 99f9e5db27..1e78f7d1ef 100644 --- a/vendor/github.com/spf13/afero/unionFile.go +++ b/vendor/github.com/spf13/afero/unionFile.go @@ -21,32 +21,33 @@ import ( // successful read in the overlay will move the cursor position in the base layer // by the number of bytes read. type UnionFile struct { - base File - layer File - off int - files []os.FileInfo + Base File + Layer File + Merger DirsMerger + off int + files []os.FileInfo } func (f *UnionFile) Close() error { // first close base, so we have a newer timestamp in the overlay. If we'd close // the overlay first, we'd get a cacheStale the next time we access this file // -> cache would be useless ;-) - if f.base != nil { - f.base.Close() + if f.Base != nil { + f.Base.Close() } - if f.layer != nil { - return f.layer.Close() + if f.Layer != nil { + return f.Layer.Close() } return BADFD } func (f *UnionFile) Read(s []byte) (int, error) { - if f.layer != nil { - n, err := f.layer.Read(s) - if (err == nil || err == io.EOF) && f.base != nil { + if f.Layer != nil { + n, err := f.Layer.Read(s) + if (err == nil || err == io.EOF) && f.Base != nil { // advance the file position also in the base file, the next // call may be a write at this position (or a seek with SEEK_CUR) - if _, seekErr := f.base.Seek(int64(n), os.SEEK_CUR); seekErr != nil { + if _, seekErr := f.Base.Seek(int64(n), os.SEEK_CUR); seekErr != nil { // only overwrite err in case the seek fails: we need to // report an eventual io.EOF to the caller err = seekErr @@ -54,105 +55,135 @@ func (f *UnionFile) Read(s []byte) (int, error) { } return n, err } - if f.base != nil { - return f.base.Read(s) + if f.Base != nil { + return f.Base.Read(s) } return 0, BADFD } func (f *UnionFile) ReadAt(s []byte, o int64) (int, error) { - if f.layer != nil { - n, err := f.layer.ReadAt(s, o) - if (err == nil || err == io.EOF) && f.base != nil { - _, err = f.base.Seek(o+int64(n), os.SEEK_SET) + if f.Layer != nil { + n, err := f.Layer.ReadAt(s, o) + if (err == nil || err == io.EOF) && f.Base != nil { + _, err = f.Base.Seek(o+int64(n), os.SEEK_SET) } return n, err } - if f.base != nil { - return f.base.ReadAt(s, o) + if f.Base != nil { + return f.Base.ReadAt(s, o) } return 0, BADFD } func (f *UnionFile) Seek(o int64, w int) (pos int64, err error) { - if f.layer != nil { - pos, err = f.layer.Seek(o, w) - if (err == nil || err == io.EOF) && f.base != nil { - _, err = f.base.Seek(o, w) + if f.Layer != nil { + pos, err = f.Layer.Seek(o, w) + if (err == nil || err == io.EOF) && f.Base != nil { + _, err = f.Base.Seek(o, w) } return pos, err } - if f.base != nil { - return f.base.Seek(o, w) + if f.Base != nil { + return f.Base.Seek(o, w) } return 0, BADFD } func (f *UnionFile) Write(s []byte) (n int, err error) { - if f.layer != nil { - n, err = f.layer.Write(s) - if err == nil && f.base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark? - _, err = f.base.Write(s) + if f.Layer != nil { + n, err = f.Layer.Write(s) + if err == nil && f.Base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark? + _, err = f.Base.Write(s) } return n, err } - if f.base != nil { - return f.base.Write(s) + if f.Base != nil { + return f.Base.Write(s) } return 0, BADFD } func (f *UnionFile) WriteAt(s []byte, o int64) (n int, err error) { - if f.layer != nil { - n, err = f.layer.WriteAt(s, o) - if err == nil && f.base != nil { - _, err = f.base.WriteAt(s, o) + if f.Layer != nil { + n, err = f.Layer.WriteAt(s, o) + if err == nil && f.Base != nil { + _, err = f.Base.WriteAt(s, o) } return n, err } - if f.base != nil { - return f.base.WriteAt(s, o) + if f.Base != nil { + return f.Base.WriteAt(s, o) } return 0, BADFD } func (f *UnionFile) Name() string { - if f.layer != nil { - return f.layer.Name() + if f.Layer != nil { + return f.Layer.Name() } - return f.base.Name() + return f.Base.Name() +} + +// DirsMerger is how UnionFile weaves two directories together. +// It takes the FileInfo slices from the layer and the base and returns a +// single view. +type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) + +var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) { + var files = make(map[string]os.FileInfo) + + for _, fi := range lofi { + files[fi.Name()] = fi + } + + for _, fi := range bofi { + if _, exists := files[fi.Name()]; !exists { + files[fi.Name()] = fi + } + } + + rfi := make([]os.FileInfo, len(files)) + + i := 0 + for _, fi := range files { + rfi[i] = fi + i++ + } + + return rfi, nil + } // Readdir will weave the two directories together and // return a single view of the overlayed directories func (f *UnionFile) Readdir(c int) (ofi []os.FileInfo, err error) { + var merge DirsMerger = f.Merger + if merge == nil { + merge = defaultUnionMergeDirsFn + } + if f.off == 0 { - var files = make(map[string]os.FileInfo) - var rfi []os.FileInfo - if f.layer != nil { - rfi, err = f.layer.Readdir(-1) + var lfi []os.FileInfo + if f.Layer != nil { + lfi, err = f.Layer.Readdir(-1) if err != nil { return nil, err } - for _, fi := range rfi { - files[fi.Name()] = fi - } } - if f.base != nil { - rfi, err = f.base.Readdir(-1) + var bfi []os.FileInfo + if f.Base != nil { + bfi, err = f.Base.Readdir(-1) if err != nil { return nil, err } - for _, fi := range rfi { - if _, exists := files[fi.Name()]; !exists { - files[fi.Name()] = fi - } - } + } - for _, fi := range files { - f.files = append(f.files, fi) + merged, err := merge(lfi, bfi) + if err != nil { + return nil, err } + f.files = append(f.files, merged...) } if c == -1 { return f.files[f.off:], nil @@ -174,53 +205,53 @@ func (f *UnionFile) Readdirnames(c int) ([]string, error) { } func (f *UnionFile) Stat() (os.FileInfo, error) { - if f.layer != nil { - return f.layer.Stat() + if f.Layer != nil { + return f.Layer.Stat() } - if f.base != nil { - return f.base.Stat() + if f.Base != nil { + return f.Base.Stat() } return nil, BADFD } func (f *UnionFile) Sync() (err error) { - if f.layer != nil { - err = f.layer.Sync() - if err == nil && f.base != nil { - err = f.base.Sync() + if f.Layer != nil { + err = f.Layer.Sync() + if err == nil && f.Base != nil { + err = f.Base.Sync() } return err } - if f.base != nil { - return f.base.Sync() + if f.Base != nil { + return f.Base.Sync() } return BADFD } func (f *UnionFile) Truncate(s int64) (err error) { - if f.layer != nil { - err = f.layer.Truncate(s) - if err == nil && f.base != nil { - err = f.base.Truncate(s) + if f.Layer != nil { + err = f.Layer.Truncate(s) + if err == nil && f.Base != nil { + err = f.Base.Truncate(s) } return err } - if f.base != nil { - return f.base.Truncate(s) + if f.Base != nil { + return f.Base.Truncate(s) } return BADFD } func (f *UnionFile) WriteString(s string) (n int, err error) { - if f.layer != nil { - n, err = f.layer.WriteString(s) - if err == nil && f.base != nil { - _, err = f.base.WriteString(s) + if f.Layer != nil { + n, err = f.Layer.WriteString(s) + if err == nil && f.Base != nil { + _, err = f.Base.WriteString(s) } return n, err } - if f.base != nil { - return f.base.WriteString(s) + if f.Base != nil { + return f.Base.WriteString(s) } return 0, BADFD } diff --git a/vendor/github.com/spf13/afero/util.go b/vendor/github.com/spf13/afero/util.go index 7463887fd8..4f253f481e 100644 --- a/vendor/github.com/spf13/afero/util.go +++ b/vendor/github.com/spf13/afero/util.go @@ -20,7 +20,6 @@ import ( "bytes" "fmt" "io" - "log" "os" "path/filepath" "strings" @@ -46,7 +45,7 @@ func WriteReader(fs Fs, path string, r io.Reader) (err error) { err = fs.MkdirAll(ospath, 0777) // rwx, rw, r if err != nil { if err != os.ErrExist { - log.Panicln(err) + return err } } } diff --git a/vendor/github.com/spf13/afero/util_test.go b/vendor/github.com/spf13/afero/util_test.go deleted file mode 100644 index b5852f1840..0000000000 --- a/vendor/github.com/spf13/afero/util_test.go +++ /dev/null @@ -1,450 +0,0 @@ -// Copyright ©2015 Steve Francia -// Portions Copyright ©2015 The Hugo 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 afero - -import ( - "fmt" - "os" - "path/filepath" - "strconv" - "strings" - "testing" - "time" -) - -var testFS = new(MemMapFs) - -func TestDirExists(t *testing.T) { - type test struct { - input string - expected bool - } - - // First create a couple directories so there is something in the filesystem - //testFS := new(MemMapFs) - testFS.MkdirAll("/foo/bar", 0777) - - data := []test{ - {".", true}, - {"./", true}, - {"..", true}, - {"../", true}, - {"./..", true}, - {"./../", true}, - {"/foo/", true}, - {"/foo", true}, - {"/foo/bar", true}, - {"/foo/bar/", true}, - {"/", true}, - {"/some-really-random-directory-name", false}, - {"/some/really/random/directory/name", false}, - {"./some-really-random-local-directory-name", false}, - {"./some/really/random/local/directory/name", false}, - } - - for i, d := range data { - exists, _ := DirExists(testFS, filepath.FromSlash(d.input)) - if d.expected != exists { - t.Errorf("Test %d %q failed. Expected %t got %t", i, d.input, d.expected, exists) - } - } -} - -func TestIsDir(t *testing.T) { - testFS = new(MemMapFs) - - type test struct { - input string - expected bool - } - data := []test{ - {"./", true}, - {"/", true}, - {"./this-directory-does-not-existi", false}, - {"/this-absolute-directory/does-not-exist", false}, - } - - for i, d := range data { - - exists, _ := IsDir(testFS, d.input) - if d.expected != exists { - t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists) - } - } -} - -func TestIsEmpty(t *testing.T) { - testFS = new(MemMapFs) - - zeroSizedFile, _ := createZeroSizedFileInTempDir() - defer deleteFileInTempDir(zeroSizedFile) - nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir() - defer deleteFileInTempDir(nonZeroSizedFile) - emptyDirectory, _ := createEmptyTempDir() - defer deleteTempDir(emptyDirectory) - nonEmptyZeroLengthFilesDirectory, _ := createTempDirWithZeroLengthFiles() - defer deleteTempDir(nonEmptyZeroLengthFilesDirectory) - nonEmptyNonZeroLengthFilesDirectory, _ := createTempDirWithNonZeroLengthFiles() - defer deleteTempDir(nonEmptyNonZeroLengthFilesDirectory) - nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt" - nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/" - - fileDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentFile) - dirDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentDir) - - type test struct { - input string - expectedResult bool - expectedErr error - } - - data := []test{ - {zeroSizedFile.Name(), true, nil}, - {nonZeroSizedFile.Name(), false, nil}, - {emptyDirectory, true, nil}, - {nonEmptyZeroLengthFilesDirectory, false, nil}, - {nonEmptyNonZeroLengthFilesDirectory, false, nil}, - {nonExistentFile, false, fileDoesNotExist}, - {nonExistentDir, false, dirDoesNotExist}, - } - for i, d := range data { - exists, err := IsEmpty(testFS, d.input) - if d.expectedResult != exists { - t.Errorf("Test %d %q failed exists. Expected result %t got %t", i, d.input, d.expectedResult, exists) - } - if d.expectedErr != nil { - if d.expectedErr.Error() != err.Error() { - t.Errorf("Test %d failed with err. Expected %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err) - } - } else { - if d.expectedErr != err { - t.Errorf("Test %d failed. Expected error %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err) - } - } - } -} - -func TestReaderContains(t *testing.T) { - for i, this := range []struct { - v1 string - v2 [][]byte - expect bool - }{ - {"abc", [][]byte{[]byte("a")}, true}, - {"abc", [][]byte{[]byte("b")}, true}, - {"abcdefg", [][]byte{[]byte("efg")}, true}, - {"abc", [][]byte{[]byte("d")}, false}, - {"abc", [][]byte{[]byte("d"), []byte("e")}, false}, - {"abc", [][]byte{[]byte("d"), []byte("a")}, true}, - {"abc", [][]byte{[]byte("b"), []byte("e")}, true}, - {"", nil, false}, - {"", [][]byte{[]byte("a")}, false}, - {"a", [][]byte{[]byte("")}, false}, - {"", [][]byte{[]byte("")}, false}} { - result := readerContainsAny(strings.NewReader(this.v1), this.v2...) - if result != this.expect { - t.Errorf("[%d] readerContains: got %t but expected %t", i, result, this.expect) - } - } - - if readerContainsAny(nil, []byte("a")) { - t.Error("readerContains with nil reader") - } - - if readerContainsAny(nil, nil) { - t.Error("readerContains with nil arguments") - } -} - -func createZeroSizedFileInTempDir() (File, error) { - filePrefix := "_path_test_" - f, e := TempFile(testFS, "", filePrefix) // dir is os.TempDir() - if e != nil { - // if there was an error no file was created. - // => no requirement to delete the file - return nil, e - } - return f, nil -} - -func createNonZeroSizedFileInTempDir() (File, error) { - f, err := createZeroSizedFileInTempDir() - if err != nil { - // no file ?? - } - byteString := []byte("byteString") - err = WriteFile(testFS, f.Name(), byteString, 0644) - if err != nil { - // delete the file - deleteFileInTempDir(f) - return nil, err - } - return f, nil -} - -func deleteFileInTempDir(f File) { - err := testFS.Remove(f.Name()) - if err != nil { - // now what? - } -} - -func createEmptyTempDir() (string, error) { - dirPrefix := "_dir_prefix_" - d, e := TempDir(testFS, "", dirPrefix) // will be in os.TempDir() - if e != nil { - // no directory to delete - it was never created - return "", e - } - return d, nil -} - -func createTempDirWithZeroLengthFiles() (string, error) { - d, dirErr := createEmptyTempDir() - if dirErr != nil { - //now what? - } - filePrefix := "_path_test_" - _, fileErr := TempFile(testFS, d, filePrefix) // dir is os.TempDir() - if fileErr != nil { - // if there was an error no file was created. - // but we need to remove the directory to clean-up - deleteTempDir(d) - return "", fileErr - } - // the dir now has one, zero length file in it - return d, nil - -} - -func createTempDirWithNonZeroLengthFiles() (string, error) { - d, dirErr := createEmptyTempDir() - if dirErr != nil { - //now what? - } - filePrefix := "_path_test_" - f, fileErr := TempFile(testFS, d, filePrefix) // dir is os.TempDir() - if fileErr != nil { - // if there was an error no file was created. - // but we need to remove the directory to clean-up - deleteTempDir(d) - return "", fileErr - } - byteString := []byte("byteString") - fileErr = WriteFile(testFS, f.Name(), byteString, 0644) - if fileErr != nil { - // delete the file - deleteFileInTempDir(f) - // also delete the directory - deleteTempDir(d) - return "", fileErr - } - - // the dir now has one, zero length file in it - return d, nil - -} - -func TestExists(t *testing.T) { - zeroSizedFile, _ := createZeroSizedFileInTempDir() - defer deleteFileInTempDir(zeroSizedFile) - nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir() - defer deleteFileInTempDir(nonZeroSizedFile) - emptyDirectory, _ := createEmptyTempDir() - defer deleteTempDir(emptyDirectory) - nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt" - nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/" - - type test struct { - input string - expectedResult bool - expectedErr error - } - - data := []test{ - {zeroSizedFile.Name(), true, nil}, - {nonZeroSizedFile.Name(), true, nil}, - {emptyDirectory, true, nil}, - {nonExistentFile, false, nil}, - {nonExistentDir, false, nil}, - } - for i, d := range data { - exists, err := Exists(testFS, d.input) - if d.expectedResult != exists { - t.Errorf("Test %d failed. Expected result %t got %t", i, d.expectedResult, exists) - } - if d.expectedErr != err { - t.Errorf("Test %d failed. Expected %q got %q", i, d.expectedErr, err) - } - } - -} - -func TestSafeWriteToDisk(t *testing.T) { - emptyFile, _ := createZeroSizedFileInTempDir() - defer deleteFileInTempDir(emptyFile) - tmpDir, _ := createEmptyTempDir() - defer deleteTempDir(tmpDir) - - randomString := "This is a random string!" - reader := strings.NewReader(randomString) - - fileExists := fmt.Errorf("%v already exists", emptyFile.Name()) - - type test struct { - filename string - expectedErr error - } - - now := time.Now().Unix() - nowStr := strconv.FormatInt(now, 10) - data := []test{ - {emptyFile.Name(), fileExists}, - {tmpDir + "/" + nowStr, nil}, - } - - for i, d := range data { - e := SafeWriteReader(testFS, d.filename, reader) - if d.expectedErr != nil { - if d.expectedErr.Error() != e.Error() { - t.Errorf("Test %d failed. Expected error %q but got %q", i, d.expectedErr.Error(), e.Error()) - } - } else { - if d.expectedErr != e { - t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedErr, e) - } - contents, _ := ReadFile(testFS, d.filename) - if randomString != string(contents) { - t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents)) - } - } - reader.Seek(0, 0) - } -} - -func TestWriteToDisk(t *testing.T) { - emptyFile, _ := createZeroSizedFileInTempDir() - defer deleteFileInTempDir(emptyFile) - tmpDir, _ := createEmptyTempDir() - defer deleteTempDir(tmpDir) - - randomString := "This is a random string!" - reader := strings.NewReader(randomString) - - type test struct { - filename string - expectedErr error - } - - now := time.Now().Unix() - nowStr := strconv.FormatInt(now, 10) - data := []test{ - {emptyFile.Name(), nil}, - {tmpDir + "/" + nowStr, nil}, - } - - for i, d := range data { - e := WriteReader(testFS, d.filename, reader) - if d.expectedErr != e { - t.Errorf("Test %d failed. WriteToDisk Error Expected %q but got %q", i, d.expectedErr, e) - } - contents, e := ReadFile(testFS, d.filename) - if e != nil { - t.Errorf("Test %d failed. Could not read file %s. Reason: %s\n", i, d.filename, e) - } - if randomString != string(contents) { - t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents)) - } - reader.Seek(0, 0) - } -} - -func TestGetTempDir(t *testing.T) { - dir := os.TempDir() - if FilePathSeparator != dir[len(dir)-1:] { - dir = dir + FilePathSeparator - } - testDir := "hugoTestFolder" + FilePathSeparator - tests := []struct { - input string - expected string - }{ - {"", dir}, - {testDir + " Foo bar ", dir + testDir + " Foo bar " + FilePathSeparator}, - {testDir + "Foo.Bar/foo_Bar-Foo", dir + testDir + "Foo.Bar/foo_Bar-Foo" + FilePathSeparator}, - {testDir + "fOO,bar:foo%bAR", dir + testDir + "fOObarfoo%bAR" + FilePathSeparator}, - {testDir + "FOo/BaR.html", dir + testDir + "FOo/BaR.html" + FilePathSeparator}, - {testDir + "трям/трям", dir + testDir + "трям/трям" + FilePathSeparator}, - {testDir + "은행", dir + testDir + "은행" + FilePathSeparator}, - {testDir + "Банковский кассир", dir + testDir + "Банковский кассир" + FilePathSeparator}, - } - - for _, test := range tests { - output := GetTempDir(new(MemMapFs), test.input) - if output != test.expected { - t.Errorf("Expected %#v, got %#v\n", test.expected, output) - } - } -} - -// This function is very dangerous. Don't use it. -func deleteTempDir(d string) { - err := os.RemoveAll(d) - if err != nil { - // now what? - } -} - -func TestFullBaseFsPath(t *testing.T) { - type dirSpec struct { - Dir1, Dir2, Dir3 string - } - dirSpecs := []dirSpec{ - dirSpec{Dir1: "/", Dir2: "/", Dir3: "/"}, - dirSpec{Dir1: "/", Dir2: "/path2", Dir3: "/"}, - dirSpec{Dir1: "/path1/dir", Dir2: "/path2/dir/", Dir3: "/path3/dir"}, - dirSpec{Dir1: "C:/path1", Dir2: "path2/dir", Dir3: "/path3/dir/"}, - } - - for _, ds := range dirSpecs { - memFs := NewMemMapFs() - level1Fs := NewBasePathFs(memFs, ds.Dir1) - level2Fs := NewBasePathFs(level1Fs, ds.Dir2) - level3Fs := NewBasePathFs(level2Fs, ds.Dir3) - - type spec struct { - BaseFs Fs - FileName string - ExpectedPath string - } - specs := []spec{ - spec{BaseFs: level3Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, ds.Dir3, "f.txt")}, - spec{BaseFs: level3Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, ds.Dir3, "")}, - spec{BaseFs: level2Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, "f.txt")}, - spec{BaseFs: level2Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, "")}, - spec{BaseFs: level1Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, "f.txt")}, - spec{BaseFs: level1Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, "")}, - } - - for _, s := range specs { - if actualPath := FullBaseFsPath(s.BaseFs.(*BasePathFs), s.FileName); actualPath != s.ExpectedPath { - t.Errorf("Expected \n%s got \n%s", s.ExpectedPath, actualPath) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/bool_slice_test.go b/vendor/github.com/spf13/pflag/bool_slice_test.go deleted file mode 100644 index b617dd237f..0000000000 --- a/vendor/github.com/spf13/pflag/bool_slice_test.go +++ /dev/null @@ -1,215 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" - "testing" -) - -func setUpBSFlagSet(bsp *[]bool) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.BoolSliceVar(bsp, "bs", []bool{}, "Command separated list!") - return f -} - -func setUpBSFlagSetWithDefault(bsp *[]bool) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.BoolSliceVar(bsp, "bs", []bool{false, true}, "Command separated list!") - return f -} - -func TestEmptyBS(t *testing.T) { - var bs []bool - f := setUpBSFlagSet(&bs) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - if len(getBS) != 0 { - t.Fatalf("got bs %v with len=%d but expected length=0", getBS, len(getBS)) - } -} - -func TestBS(t *testing.T) { - var bs []bool - f := setUpBSFlagSet(&bs) - - vals := []string{"1", "F", "TRUE", "0"} - arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected is[%d] to be %s but got: %t", i, vals[i], v) - } - } - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatalf("got error: %v", err) - } - for i, v := range getBS { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %s but got: %t from GetBoolSlice", i, vals[i], v) - } - } -} - -func TestBSDefault(t *testing.T) { - var bs []bool - f := setUpBSFlagSetWithDefault(&bs) - - vals := []string{"false", "T"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) - } - } - - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - for i, v := range getBS { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) - } - } -} - -func TestBSWithDefault(t *testing.T) { - var bs []bool - f := setUpBSFlagSetWithDefault(&bs) - - vals := []string{"FALSE", "1"} - arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t but got: %t", i, b, v) - } - } - - getBS, err := f.GetBoolSlice("bs") - if err != nil { - t.Fatal("got an error from GetBoolSlice():", err) - } - for i, v := range getBS { - b, err := strconv.ParseBool(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if b != v { - t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v) - } - } -} - -func TestBSCalledTwice(t *testing.T) { - var bs []bool - f := setUpBSFlagSet(&bs) - - in := []string{"T,F", "T"} - expected := []bool{true, false, true} - argfmt := "--bs=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range bs { - if expected[i] != v { - t.Fatalf("expected bs[%d] to be %t but got %t", i, expected[i], v) - } - } -} - -func TestBSBadQuoting(t *testing.T) { - - tests := []struct { - Want []bool - FlagArg []string - }{ - { - Want: []bool{true, false, true}, - FlagArg: []string{"1", "0", "true"}, - }, - { - Want: []bool{true, false}, - FlagArg: []string{"True", "F"}, - }, - { - Want: []bool{true, false}, - FlagArg: []string{"T", "0"}, - }, - { - Want: []bool{true, false}, - FlagArg: []string{"1", "0"}, - }, - { - Want: []bool{true, false, false}, - FlagArg: []string{"true,false", "false"}, - }, - { - Want: []bool{true, false, false, true, false, true, false}, - FlagArg: []string{`"true,false,false,1,0, T"`, " false "}, - }, - { - Want: []bool{false, false, true, false, true, false, true}, - FlagArg: []string{`"0, False, T,false , true,F"`, "true"}, - }, - } - - for i, test := range tests { - - var bs []bool - f := setUpBSFlagSet(&bs) - - if err := f.Parse([]string{fmt.Sprintf("--bs=%s", strings.Join(test.FlagArg, ","))}); err != nil { - t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%#v", - err, test.FlagArg, test.Want[i]) - } - - for j, b := range bs { - if b != test.Want[j] { - t.Fatalf("bad value parsed for test %d on bool %d:\nwant:\t%t\ngot:\t%t", i, j, test.Want[j], b) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/bool_test.go b/vendor/github.com/spf13/pflag/bool_test.go deleted file mode 100644 index a4319e79fc..0000000000 --- a/vendor/github.com/spf13/pflag/bool_test.go +++ /dev/null @@ -1,179 +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 pflag - -import ( - "bytes" - "strconv" - "testing" -) - -// This value can be a boolean ("true", "false") or "maybe" -type triStateValue int - -const ( - triStateFalse triStateValue = 0 - triStateTrue triStateValue = 1 - triStateMaybe triStateValue = 2 -) - -const strTriStateMaybe = "maybe" - -func (v *triStateValue) IsBoolFlag() bool { - return true -} - -func (v *triStateValue) Get() interface{} { - return triStateValue(*v) -} - -func (v *triStateValue) Set(s string) error { - if s == strTriStateMaybe { - *v = triStateMaybe - return nil - } - boolVal, err := strconv.ParseBool(s) - if boolVal { - *v = triStateTrue - } else { - *v = triStateFalse - } - return err -} - -func (v *triStateValue) String() string { - if *v == triStateMaybe { - return strTriStateMaybe - } - return strconv.FormatBool(*v == triStateTrue) -} - -// The type of the flag as required by the pflag.Value interface -func (v *triStateValue) Type() string { - return "version" -} - -func setUpFlagSet(tristate *triStateValue) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - *tristate = triStateFalse - flag := f.VarPF(tristate, "tristate", "t", "tristate value (true, maybe or false)") - flag.NoOptDefVal = "true" - return f -} - -func TestExplicitTrue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=true"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestImplicitTrue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestShortFlag(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"-t"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } -} - -func TestShortFlagExtraArgument(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - // The"maybe"turns into an arg, since short boolean options will only do true/false - err := f.Parse([]string{"-t", "maybe"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateTrue { - t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead") - } - args := f.Args() - if len(args) != 1 || args[0] != "maybe" { - t.Fatal("expected an extra 'maybe' argument to stick around") - } -} - -func TestExplicitMaybe(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=maybe"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateMaybe { - t.Fatal("expected", triStateMaybe, "(triStateMaybe) but got", tristate, "instead") - } -} - -func TestExplicitFalse(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{"--tristate=false"}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateFalse { - t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead") - } -} - -func TestImplicitFalse(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - if tristate != triStateFalse { - t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead") - } -} - -func TestInvalidValue(t *testing.T) { - var tristate triStateValue - f := setUpFlagSet(&tristate) - var buf bytes.Buffer - f.SetOutput(&buf) - err := f.Parse([]string{"--tristate=invalid"}) - if err == nil { - t.Fatal("expected an error but did not get any, tristate has value", tristate) - } -} - -func TestBoolP(t *testing.T) { - b := BoolP("bool", "b", false, "bool value in CommandLine") - c := BoolP("c", "c", false, "other bool value") - args := []string{"--bool"} - if err := CommandLine.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if *b != true { - t.Errorf("expected b=true got b=%v", *b) - } - if *c != false { - t.Errorf("expect c=false got c=%v", *c) - } -} diff --git a/vendor/github.com/spf13/pflag/bytes.go b/vendor/github.com/spf13/pflag/bytes.go new file mode 100644 index 0000000000..12c58db9fe --- /dev/null +++ b/vendor/github.com/spf13/pflag/bytes.go @@ -0,0 +1,105 @@ +package pflag + +import ( + "encoding/hex" + "fmt" + "strings" +) + +// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded +type bytesHexValue []byte + +func (bytesHex bytesHexValue) String() string { + return fmt.Sprintf("%X", []byte(bytesHex)) +} + +func (bytesHex *bytesHexValue) Set(value string) error { + bin, err := hex.DecodeString(strings.TrimSpace(value)) + + if err != nil { + return err + } + + *bytesHex = bin + + return nil +} + +func (*bytesHexValue) Type() string { + return "bytesHex" +} + +func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue { + *p = val + return (*bytesHexValue)(p) +} + +func bytesHexConv(sval string) (interface{}, error) { + + bin, err := hex.DecodeString(sval) + + if err == nil { + return bin, nil + } + + return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err) +} + +// GetBytesHex return the []byte value of a flag with the given name +func (f *FlagSet) GetBytesHex(name string) ([]byte, error) { + val, err := f.getFlagType(name, "bytesHex", bytesHexConv) + + if err != nil { + return []byte{}, err + } + + return val.([]byte), nil +} + +// BytesHexVar defines an []byte flag with specified name, default value, and usage string. +// The argument p points to an []byte variable in which to store the value of the flag. +func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) { + f.VarP(newBytesHexValue(value, p), name, "", usage) +} + +// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { + f.VarP(newBytesHexValue(value, p), name, shorthand, usage) +} + +// BytesHexVar defines an []byte flag with specified name, default value, and usage string. +// The argument p points to an []byte variable in which to store the value of the flag. +func BytesHexVar(p *[]byte, name string, value []byte, usage string) { + CommandLine.VarP(newBytesHexValue(value, p), name, "", usage) +} + +// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. +func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { + CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage) +} + +// BytesHex defines an []byte flag with specified name, default value, and usage string. +// The return value is the address of an []byte variable that stores the value of the flag. +func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte { + p := new([]byte) + f.BytesHexVarP(p, name, "", value, usage) + return p +} + +// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { + p := new([]byte) + f.BytesHexVarP(p, name, shorthand, value, usage) + return p +} + +// BytesHex defines an []byte flag with specified name, default value, and usage string. +// The return value is the address of an []byte variable that stores the value of the flag. +func BytesHex(name string, value []byte, usage string) *[]byte { + return CommandLine.BytesHexP(name, "", value, usage) +} + +// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. +func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { + return CommandLine.BytesHexP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go index 250a43814c..aa126e44d1 100644 --- a/vendor/github.com/spf13/pflag/count.go +++ b/vendor/github.com/spf13/pflag/count.go @@ -11,13 +11,13 @@ func newCountValue(val int, p *int) *countValue { } func (i *countValue) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - // -1 means that no specific value was passed, so increment - if v == -1 { + // "+1" means that no specific value was passed, so increment + if s == "+1" { *i = countValue(*i + 1) - } else { - *i = countValue(v) + return nil } + v, err := strconv.ParseInt(s, 0, 0) + *i = countValue(v) return err } @@ -54,7 +54,7 @@ func (f *FlagSet) CountVar(p *int, name string, usage string) { // CountVarP is like CountVar only take a shorthand for the flag name. func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) { flag := f.VarPF(newCountValue(0, p), name, shorthand, usage) - flag.NoOptDefVal = "-1" + flag.NoOptDefVal = "+1" } // CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set diff --git a/vendor/github.com/spf13/pflag/count_test.go b/vendor/github.com/spf13/pflag/count_test.go deleted file mode 100644 index 460d96a6f1..0000000000 --- a/vendor/github.com/spf13/pflag/count_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package pflag - -import ( - "os" - "testing" -) - -func setUpCount(c *int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.CountVarP(c, "verbose", "v", "a counter") - return f -} - -func TestCount(t *testing.T) { - testCases := []struct { - input []string - success bool - expected int - }{ - {[]string{"-vvv"}, true, 3}, - {[]string{"-v", "-v", "-v"}, true, 3}, - {[]string{"-v", "--verbose", "-v"}, true, 3}, - {[]string{"-v=3", "-v"}, true, 4}, - {[]string{"-v=a"}, false, 0}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var count int - f := setUpCount(&count) - - tc := &testCases[i] - - err := f.Parse(tc.input) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure, got success") - continue - } else if tc.success { - c, err := f.GetCount("verbose") - if err != nil { - t.Errorf("Got error trying to fetch the counter flag") - } - if c != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, c) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/duration_slice.go b/vendor/github.com/spf13/pflag/duration_slice.go new file mode 100644 index 0000000000..52c6b6dc10 --- /dev/null +++ b/vendor/github.com/spf13/pflag/duration_slice.go @@ -0,0 +1,128 @@ +package pflag + +import ( + "fmt" + "strings" + "time" +) + +// -- durationSlice Value +type durationSliceValue struct { + value *[]time.Duration + changed bool +} + +func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue { + dsv := new(durationSliceValue) + dsv.value = p + *dsv.value = val + return dsv +} + +func (s *durationSliceValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make([]time.Duration, len(ss)) + for i, d := range ss { + var err error + out[i], err = time.ParseDuration(d) + if err != nil { + return err + } + + } + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + s.changed = true + return nil +} + +func (s *durationSliceValue) Type() string { + return "durationSlice" +} + +func (s *durationSliceValue) String() string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = fmt.Sprintf("%s", d) + } + return "[" + strings.Join(out, ",") + "]" +} + +func durationSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []time.Duration{}, nil + } + ss := strings.Split(val, ",") + out := make([]time.Duration, len(ss)) + for i, d := range ss { + var err error + out[i], err = time.ParseDuration(d) + if err != nil { + return nil, err + } + + } + return out, nil +} + +// GetDurationSlice returns the []time.Duration value of a flag with the given name +func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) { + val, err := f.getFlagType(name, "durationSlice", durationSliceConv) + if err != nil { + return []time.Duration{}, err + } + return val.([]time.Duration), nil +} + +// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string. +// The argument p points to a []time.Duration variable in which to store the value of the flag. +func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { + f.VarP(newDurationSliceValue(value, p), name, "", usage) +} + +// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { + f.VarP(newDurationSliceValue(value, p), name, shorthand, usage) +} + +// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string. +// The argument p points to a duration[] variable in which to store the value of the flag. +func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { + CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage) +} + +// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. +func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { + CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage) +} + +// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. +// The return value is the address of a []time.Duration variable that stores the value of the flag. +func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { + p := []time.Duration{} + f.DurationSliceVarP(&p, name, "", value, usage) + return &p +} + +// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { + p := []time.Duration{} + f.DurationSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. +// The return value is the address of a []time.Duration variable that stores the value of the flag. +func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { + return CommandLine.DurationSliceP(name, "", value, usage) +} + +// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. +func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { + return CommandLine.DurationSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/example_test.go b/vendor/github.com/spf13/pflag/example_test.go deleted file mode 100644 index abd7806fad..0000000000 --- a/vendor/github.com/spf13/pflag/example_test.go +++ /dev/null @@ -1,36 +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 pflag_test - -import ( - "fmt" - - "github.com/spf13/pflag" -) - -func ExampleShorthandLookup() { - name := "verbose" - short := name[:1] - - pflag.BoolP(name, short, false, "verbose output") - - // len(short) must be == 1 - flag := pflag.ShorthandLookup(short) - - fmt.Println(flag.Name) -} - -func ExampleFlagSet_ShorthandLookup() { - name := "verbose" - short := name[:1] - - fs := pflag.NewFlagSet("Example", pflag.ContinueOnError) - fs.BoolP(name, short, false, "verbose output") - - // len(short) must be == 1 - flag := fs.ShorthandLookup(short) - - fmt.Println(flag.Name) -} diff --git a/vendor/github.com/spf13/pflag/export_test.go b/vendor/github.com/spf13/pflag/export_test.go deleted file mode 100644 index 9318fee00e..0000000000 --- a/vendor/github.com/spf13/pflag/export_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2010 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 pflag - -import ( - "io/ioutil" - "os" -) - -// Additional routines compiled into the package only during testing. - -// ResetForTesting clears all flag state and sets the usage function as directed. -// After calling ResetForTesting, parse errors in flag handling will not -// exit the program. -func ResetForTesting(usage func()) { - CommandLine = &FlagSet{ - name: os.Args[0], - errorHandling: ContinueOnError, - output: ioutil.Discard, - } - Usage = usage -} - -// GetCommandLine returns the default FlagSet. -func GetCommandLine() *FlagSet { - return CommandLine -} diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go index 6f1fc3007a..5eadc84e3c 100644 --- a/vendor/github.com/spf13/pflag/flag.go +++ b/vendor/github.com/spf13/pflag/flag.go @@ -101,6 +101,7 @@ package pflag import ( "bytes" "errors" + goflag "flag" "fmt" "io" "os" @@ -123,6 +124,12 @@ const ( PanicOnError ) +// ParseErrorsWhitelist defines the parsing errors that can be ignored +type ParseErrorsWhitelist struct { + // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags + UnknownFlags bool +} + // NormalizedName is a flag name that has been normalized according to rules // for the FlagSet (e.g. making '-' and '_' equivalent). type NormalizedName string @@ -138,6 +145,9 @@ type FlagSet struct { // help/usage messages. SortFlags bool + // ParseErrorsWhitelist is used to configure a whitelist of errors + ParseErrorsWhitelist ParseErrorsWhitelist + name string parsed bool actual map[NormalizedName]*Flag @@ -153,6 +163,8 @@ type FlagSet struct { output io.Writer // nil means stderr; use out() accessor interspersed bool // allow interspersed option/non-option args normalizeNameFunc func(f *FlagSet, name string) NormalizedName + + addedGoFlagSets []*goflag.FlagSet } // A Flag represents the state of a flag. @@ -202,12 +214,18 @@ func sortFlags(flags map[NormalizedName]*Flag) []*Flag { func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) { f.normalizeNameFunc = n f.sortedFormal = f.sortedFormal[:0] - for k, v := range f.orderedFormal { - delete(f.formal, NormalizedName(v.Name)) - nname := f.normalizeFlagName(v.Name) - v.Name = string(nname) - f.formal[nname] = v - f.orderedFormal[k] = v + for fname, flag := range f.formal { + nname := f.normalizeFlagName(flag.Name) + if fname == nname { + continue + } + flag.Name = string(nname) + delete(f.formal, fname) + f.formal[nname] = flag + if _, set := f.actual[fname]; set { + delete(f.actual, fname) + f.actual[nname] = flag + } } } @@ -261,16 +279,16 @@ func (f *FlagSet) VisitAll(fn func(*Flag)) { } } -// HasFlags returns a bool to indicate if the FlagSet has any flags definied. +// HasFlags returns a bool to indicate if the FlagSet has any flags defined. func (f *FlagSet) HasFlags() bool { return len(f.formal) > 0 } // HasAvailableFlags returns a bool to indicate if the FlagSet has any flags -// definied that are not hidden or deprecated. +// that are not hidden. func (f *FlagSet) HasAvailableFlags() bool { for _, flag := range f.formal { - if !flag.Hidden && len(flag.Deprecated) == 0 { + if !flag.Hidden { return true } } @@ -380,6 +398,7 @@ func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error { return fmt.Errorf("deprecated message for flag %q must be set", name) } flag.Deprecated = usageMessage + flag.Hidden = true return nil } @@ -440,13 +459,15 @@ func (f *FlagSet) Set(name, value string) error { return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err) } - if f.actual == nil { - f.actual = make(map[NormalizedName]*Flag) - } - f.actual[normalName] = flag - f.orderedActual = append(f.orderedActual, flag) + if !flag.Changed { + if f.actual == nil { + f.actual = make(map[NormalizedName]*Flag) + } + f.actual[normalName] = flag + f.orderedActual = append(f.orderedActual, flag) - flag.Changed = true + flag.Changed = true + } if flag.Deprecated != "" { fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) @@ -556,6 +577,14 @@ func UnquoteUsage(flag *Flag) (name string, usage string) { name = "int" case "uint64": name = "uint" + case "stringSlice": + name = "strings" + case "intSlice": + name = "ints" + case "uintSlice": + name = "uints" + case "boolSlice": + name = "bools" } return @@ -570,11 +599,14 @@ func wrapN(i, slop int, s string) (string, string) { return s, "" } - w := strings.LastIndexAny(s[:i], " \t") + w := strings.LastIndexAny(s[:i], " \t\n") if w <= 0 { return s, "" } - + nlPos := strings.LastIndex(s[:i], "\n") + if nlPos > 0 && nlPos < w { + return s[:nlPos], s[nlPos+1:] + } return s[:w], s[w+1:] } @@ -583,7 +615,7 @@ func wrapN(i, slop int, s string) (string, string) { // caller). Pass `w` == 0 to do no wrapping func wrap(i, w int, s string) string { if w == 0 { - return s + return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1) } // space between indent i and end of line width w into which @@ -601,7 +633,7 @@ func wrap(i, w int, s string) string { } // If still not enough space then don't even try to wrap. if wrap < 24 { - return s + return strings.Replace(s, "\n", r, -1) } // Try to avoid short orphan words on the final line, by @@ -613,14 +645,14 @@ func wrap(i, w int, s string) string { // Handle first line, which is indented by the caller (or the // special case above) l, s = wrapN(wrap, slop, s) - r = r + l + r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1) // Now wrap the rest for s != "" { var t string t, s = wrapN(wrap, slop, s) - r = r + "\n" + strings.Repeat(" ", i) + t + r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1) } return r @@ -637,7 +669,7 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string { maxlen := 0 f.VisitAll(func(flag *Flag) { - if flag.Deprecated != "" || flag.Hidden { + if flag.Hidden { return } @@ -660,6 +692,10 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string { if flag.NoOptDefVal != "true" { line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) } + case "count": + if flag.NoOptDefVal != "+1" { + line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) + } default: line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) } @@ -680,6 +716,9 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string { line += fmt.Sprintf(" (default %s)", flag.DefValue) } } + if len(flag.Deprecated) != 0 { + line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated) + } lines = append(lines, line) }) @@ -857,8 +896,10 @@ func VarP(value Value, name, shorthand, usage string) { // returns the error. func (f *FlagSet) failf(format string, a ...interface{}) error { err := fmt.Errorf(format, a...) - fmt.Fprintln(f.out(), err) - f.usage() + if f.errorHandling != ContinueOnError { + fmt.Fprintln(f.out(), err) + f.usage() + } return err } @@ -874,6 +915,25 @@ func (f *FlagSet) usage() { } } +//--unknown (args will be empty) +//--unknown --next-flag ... (args will be --next-flag ...) +//--unknown arg ... (args will be arg ...) +func stripUnknownFlagValue(args []string) []string { + if len(args) == 0 { + //--unknown + return args + } + + first := args[0] + if first[0] == '-' { + //--unknown --next-flag ... + return args + } + + //--unknown arg ... (args will be arg ...) + return args[1:] +} + func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) { a = args name := s[2:] @@ -885,13 +945,24 @@ func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []strin split := strings.SplitN(name, "=", 2) name = split[0] flag, exists := f.formal[f.normalizeFlagName(name)] + if !exists { - if name == "help" { // special case for nice help message. + switch { + case name == "help": f.usage() return a, ErrHelp + case f.ParseErrorsWhitelist.UnknownFlags: + // --unknown=unknownval arg ... + // we do not want to lose arg in this case + if len(split) >= 2 { + return a, nil + } + + return stripUnknownFlagValue(a), nil + default: + err = f.failf("unknown flag: --%s", name) + return } - err = f.failf("unknown flag: --%s", name) - return } var value string @@ -912,6 +983,9 @@ func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []strin } err = fn(flag, value) + if err != nil { + f.failf(err.Error()) + } return } @@ -926,13 +1000,25 @@ func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parse flag, exists := f.shorthands[c] if !exists { - if c == 'h' { // special case for nice help message. + switch { + case c == 'h': f.usage() err = ErrHelp return + case f.ParseErrorsWhitelist.UnknownFlags: + // '-f=arg arg ...' + // we do not want to lose arg in this case + if len(shorthands) > 2 && shorthands[1] == '=' { + outShorts = "" + return + } + + outArgs = stripUnknownFlagValue(outArgs) + return + default: + err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands) + return } - err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands) - return } var value string @@ -962,6 +1048,9 @@ func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parse } err = fn(flag, value) + if err != nil { + f.failf(err.Error()) + } return } @@ -1016,6 +1105,11 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) { // are defined and before flags are accessed by the program. // The return value will be ErrHelp if -help was set but not defined. func (f *FlagSet) Parse(arguments []string) error { + if f.addedGoFlagSets != nil { + for _, goFlagSet := range f.addedGoFlagSets { + goFlagSet.Parse(nil) + } + } f.parsed = true if len(arguments) < 0 { @@ -1034,6 +1128,7 @@ func (f *FlagSet) Parse(arguments []string) error { case ContinueOnError: return err case ExitOnError: + fmt.Println(err) os.Exit(2) case PanicOnError: panic(err) diff --git a/vendor/github.com/spf13/pflag/flag_test.go b/vendor/github.com/spf13/pflag/flag_test.go deleted file mode 100644 index c3def0fd41..0000000000 --- a/vendor/github.com/spf13/pflag/flag_test.go +++ /dev/null @@ -1,1085 +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 pflag - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net" - "os" - "reflect" - "sort" - "strconv" - "strings" - "testing" - "time" -) - -var ( - testBool = Bool("test_bool", false, "bool value") - testInt = Int("test_int", 0, "int value") - testInt64 = Int64("test_int64", 0, "int64 value") - testUint = Uint("test_uint", 0, "uint value") - testUint64 = Uint64("test_uint64", 0, "uint64 value") - testString = String("test_string", "0", "string value") - testFloat = Float64("test_float64", 0, "float64 value") - testDuration = Duration("test_duration", 0, "time.Duration value") - testOptionalInt = Int("test_optional_int", 0, "optional int value") - normalizeFlagNameInvocations = 0 -) - -func boolString(s string) string { - if s == "0" { - return "false" - } - return "true" -} - -func TestEverything(t *testing.T) { - m := make(map[string]*Flag) - desired := "0" - visitor := func(f *Flag) { - if len(f.Name) > 5 && f.Name[0:5] == "test_" { - m[f.Name] = f - ok := false - switch { - case f.Value.String() == desired: - ok = true - case f.Name == "test_bool" && f.Value.String() == boolString(desired): - ok = true - case f.Name == "test_duration" && f.Value.String() == desired+"s": - ok = true - } - if !ok { - t.Error("Visit: bad value", f.Value.String(), "for", f.Name) - } - } - } - VisitAll(visitor) - if len(m) != 9 { - t.Error("VisitAll misses some flags") - for k, v := range m { - t.Log(k, *v) - } - } - m = make(map[string]*Flag) - Visit(visitor) - if len(m) != 0 { - t.Errorf("Visit sees unset flags") - for k, v := range m { - t.Log(k, *v) - } - } - // Now set all flags - Set("test_bool", "true") - Set("test_int", "1") - Set("test_int64", "1") - Set("test_uint", "1") - Set("test_uint64", "1") - Set("test_string", "1") - Set("test_float64", "1") - Set("test_duration", "1s") - Set("test_optional_int", "1") - desired = "1" - Visit(visitor) - if len(m) != 9 { - t.Error("Visit fails after set") - for k, v := range m { - t.Log(k, *v) - } - } - // Now test they're visited in sort order. - var flagNames []string - Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) }) - if !sort.StringsAreSorted(flagNames) { - t.Errorf("flag names not sorted: %v", flagNames) - } -} - -func TestUsage(t *testing.T) { - called := false - ResetForTesting(func() { called = true }) - if GetCommandLine().Parse([]string{"--x"}) == nil { - t.Error("parse did not fail for unknown flag") - } - if !called { - t.Error("did not call Usage for unknown flag") - } -} - -func TestAddFlagSet(t *testing.T) { - oldSet := NewFlagSet("old", ContinueOnError) - newSet := NewFlagSet("new", ContinueOnError) - - oldSet.String("flag1", "flag1", "flag1") - oldSet.String("flag2", "flag2", "flag2") - - newSet.String("flag2", "flag2", "flag2") - newSet.String("flag3", "flag3", "flag3") - - oldSet.AddFlagSet(newSet) - - if len(oldSet.formal) != 3 { - t.Errorf("Unexpected result adding a FlagSet to a FlagSet %v", oldSet) - } -} - -func TestAnnotation(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - - if err := f.SetAnnotation("missing-flag", "key", nil); err == nil { - t.Errorf("Expected error setting annotation on non-existent flag") - } - - f.StringP("stringa", "a", "", "string value") - if err := f.SetAnnotation("stringa", "key", nil); err != nil { - t.Errorf("Unexpected error setting new nil annotation: %v", err) - } - if annotation := f.Lookup("stringa").Annotations["key"]; annotation != nil { - t.Errorf("Unexpected annotation: %v", annotation) - } - - f.StringP("stringb", "b", "", "string2 value") - if err := f.SetAnnotation("stringb", "key", []string{"value1"}); err != nil { - t.Errorf("Unexpected error setting new annotation: %v", err) - } - if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value1"}) { - t.Errorf("Unexpected annotation: %v", annotation) - } - - if err := f.SetAnnotation("stringb", "key", []string{"value2"}); err != nil { - t.Errorf("Unexpected error updating annotation: %v", err) - } - if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value2"}) { - t.Errorf("Unexpected annotation: %v", annotation) - } -} - -func testParse(f *FlagSet, t *testing.T) { - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - boolFlag := f.Bool("bool", false, "bool value") - bool2Flag := f.Bool("bool2", false, "bool2 value") - bool3Flag := f.Bool("bool3", false, "bool3 value") - intFlag := f.Int("int", 0, "int value") - int8Flag := f.Int8("int8", 0, "int value") - int32Flag := f.Int32("int32", 0, "int value") - int64Flag := f.Int64("int64", 0, "int64 value") - uintFlag := f.Uint("uint", 0, "uint value") - uint8Flag := f.Uint8("uint8", 0, "uint value") - uint16Flag := f.Uint16("uint16", 0, "uint value") - uint32Flag := f.Uint32("uint32", 0, "uint value") - uint64Flag := f.Uint64("uint64", 0, "uint64 value") - stringFlag := f.String("string", "0", "string value") - float32Flag := f.Float32("float32", 0, "float32 value") - float64Flag := f.Float64("float64", 0, "float64 value") - ipFlag := f.IP("ip", net.ParseIP("127.0.0.1"), "ip value") - maskFlag := f.IPMask("mask", ParseIPv4Mask("0.0.0.0"), "mask value") - durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value") - optionalIntNoValueFlag := f.Int("optional-int-no-value", 0, "int value") - f.Lookup("optional-int-no-value").NoOptDefVal = "9" - optionalIntWithValueFlag := f.Int("optional-int-with-value", 0, "int value") - f.Lookup("optional-int-no-value").NoOptDefVal = "9" - extra := "one-extra-argument" - args := []string{ - "--bool", - "--bool2=true", - "--bool3=false", - "--int=22", - "--int8=-8", - "--int32=-32", - "--int64=0x23", - "--uint", "24", - "--uint8=8", - "--uint16=16", - "--uint32=32", - "--uint64=25", - "--string=hello", - "--float32=-172e12", - "--float64=2718e28", - "--ip=10.11.12.13", - "--mask=255.255.255.0", - "--duration=2m", - "--optional-int-no-value", - "--optional-int-with-value=42", - extra, - } - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolFlag != true { - t.Error("bool flag should be true, is ", *boolFlag) - } - if v, err := f.GetBool("bool"); err != nil || v != *boolFlag { - t.Error("GetBool does not work.") - } - if *bool2Flag != true { - t.Error("bool2 flag should be true, is ", *bool2Flag) - } - if *bool3Flag != false { - t.Error("bool3 flag should be false, is ", *bool2Flag) - } - if *intFlag != 22 { - t.Error("int flag should be 22, is ", *intFlag) - } - if v, err := f.GetInt("int"); err != nil || v != *intFlag { - t.Error("GetInt does not work.") - } - if *int8Flag != -8 { - t.Error("int8 flag should be 0x23, is ", *int8Flag) - } - if v, err := f.GetInt8("int8"); err != nil || v != *int8Flag { - t.Error("GetInt8 does not work.") - } - if *int32Flag != -32 { - t.Error("int32 flag should be 0x23, is ", *int32Flag) - } - if v, err := f.GetInt32("int32"); err != nil || v != *int32Flag { - t.Error("GetInt32 does not work.") - } - if *int64Flag != 0x23 { - t.Error("int64 flag should be 0x23, is ", *int64Flag) - } - if v, err := f.GetInt64("int64"); err != nil || v != *int64Flag { - t.Error("GetInt64 does not work.") - } - if *uintFlag != 24 { - t.Error("uint flag should be 24, is ", *uintFlag) - } - if v, err := f.GetUint("uint"); err != nil || v != *uintFlag { - t.Error("GetUint does not work.") - } - if *uint8Flag != 8 { - t.Error("uint8 flag should be 8, is ", *uint8Flag) - } - if v, err := f.GetUint8("uint8"); err != nil || v != *uint8Flag { - t.Error("GetUint8 does not work.") - } - if *uint16Flag != 16 { - t.Error("uint16 flag should be 16, is ", *uint16Flag) - } - if v, err := f.GetUint16("uint16"); err != nil || v != *uint16Flag { - t.Error("GetUint16 does not work.") - } - if *uint32Flag != 32 { - t.Error("uint32 flag should be 32, is ", *uint32Flag) - } - if v, err := f.GetUint32("uint32"); err != nil || v != *uint32Flag { - t.Error("GetUint32 does not work.") - } - if *uint64Flag != 25 { - t.Error("uint64 flag should be 25, is ", *uint64Flag) - } - if v, err := f.GetUint64("uint64"); err != nil || v != *uint64Flag { - t.Error("GetUint64 does not work.") - } - if *stringFlag != "hello" { - t.Error("string flag should be `hello`, is ", *stringFlag) - } - if v, err := f.GetString("string"); err != nil || v != *stringFlag { - t.Error("GetString does not work.") - } - if *float32Flag != -172e12 { - t.Error("float32 flag should be -172e12, is ", *float32Flag) - } - if v, err := f.GetFloat32("float32"); err != nil || v != *float32Flag { - t.Errorf("GetFloat32 returned %v but float32Flag was %v", v, *float32Flag) - } - if *float64Flag != 2718e28 { - t.Error("float64 flag should be 2718e28, is ", *float64Flag) - } - if v, err := f.GetFloat64("float64"); err != nil || v != *float64Flag { - t.Errorf("GetFloat64 returned %v but float64Flag was %v", v, *float64Flag) - } - if !(*ipFlag).Equal(net.ParseIP("10.11.12.13")) { - t.Error("ip flag should be 10.11.12.13, is ", *ipFlag) - } - if v, err := f.GetIP("ip"); err != nil || !v.Equal(*ipFlag) { - t.Errorf("GetIP returned %v but ipFlag was %v", v, *ipFlag) - } - if (*maskFlag).String() != ParseIPv4Mask("255.255.255.0").String() { - t.Error("mask flag should be 255.255.255.0, is ", (*maskFlag).String()) - } - if v, err := f.GetIPv4Mask("mask"); err != nil || v.String() != (*maskFlag).String() { - t.Errorf("GetIP returned %v maskFlag was %v error was %v", v, *maskFlag, err) - } - if *durationFlag != 2*time.Minute { - t.Error("duration flag should be 2m, is ", *durationFlag) - } - if v, err := f.GetDuration("duration"); err != nil || v != *durationFlag { - t.Error("GetDuration does not work.") - } - if _, err := f.GetInt("duration"); err == nil { - t.Error("GetInt parsed a time.Duration?!?!") - } - if *optionalIntNoValueFlag != 9 { - t.Error("optional int flag should be the default value, is ", *optionalIntNoValueFlag) - } - if *optionalIntWithValueFlag != 42 { - t.Error("optional int flag should be 42, is ", *optionalIntWithValueFlag) - } - if len(f.Args()) != 1 { - t.Error("expected one argument, got", len(f.Args())) - } else if f.Args()[0] != extra { - t.Errorf("expected argument %q got %q", extra, f.Args()[0]) - } -} - -func testParseAll(f *FlagSet, t *testing.T) { - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - f.BoolP("boola", "a", false, "bool value") - f.BoolP("boolb", "b", false, "bool2 value") - f.BoolP("boolc", "c", false, "bool3 value") - f.BoolP("boold", "d", false, "bool4 value") - f.StringP("stringa", "s", "0", "string value") - f.StringP("stringz", "z", "0", "string value") - f.StringP("stringx", "x", "0", "string value") - f.StringP("stringy", "y", "0", "string value") - f.Lookup("stringx").NoOptDefVal = "1" - args := []string{ - "-ab", - "-cs=xx", - "--stringz=something", - "-d=true", - "-x", - "-y", - "ee", - } - want := []string{ - "boola", "true", - "boolb", "true", - "boolc", "true", - "stringa", "xx", - "stringz", "something", - "boold", "true", - "stringx", "1", - "stringy", "ee", - } - got := []string{} - store := func(flag *Flag, value string) error { - got = append(got, flag.Name) - if len(value) > 0 { - got = append(got, value) - } - return nil - } - if err := f.ParseAll(args, store); err != nil { - t.Errorf("expected no error, got %s", err) - } - if !f.Parsed() { - t.Errorf("f.Parse() = false after Parse") - } - if !reflect.DeepEqual(got, want) { - t.Errorf("f.ParseAll() fail to restore the args") - t.Errorf("Got: %v", got) - t.Errorf("Want: %v", want) - } -} - -func TestShorthand(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - boolaFlag := f.BoolP("boola", "a", false, "bool value") - boolbFlag := f.BoolP("boolb", "b", false, "bool2 value") - boolcFlag := f.BoolP("boolc", "c", false, "bool3 value") - booldFlag := f.BoolP("boold", "d", false, "bool4 value") - stringaFlag := f.StringP("stringa", "s", "0", "string value") - stringzFlag := f.StringP("stringz", "z", "0", "string value") - extra := "interspersed-argument" - notaflag := "--i-look-like-a-flag" - args := []string{ - "-ab", - extra, - "-cs", - "hello", - "-z=something", - "-d=true", - "--", - notaflag, - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolaFlag != true { - t.Error("boola flag should be true, is ", *boolaFlag) - } - if *boolbFlag != true { - t.Error("boolb flag should be true, is ", *boolbFlag) - } - if *boolcFlag != true { - t.Error("boolc flag should be true, is ", *boolcFlag) - } - if *booldFlag != true { - t.Error("boold flag should be true, is ", *booldFlag) - } - if *stringaFlag != "hello" { - t.Error("stringa flag should be `hello`, is ", *stringaFlag) - } - if *stringzFlag != "something" { - t.Error("stringz flag should be `something`, is ", *stringzFlag) - } - if len(f.Args()) != 2 { - t.Error("expected one argument, got", len(f.Args())) - } else if f.Args()[0] != extra { - t.Errorf("expected argument %q got %q", extra, f.Args()[0]) - } else if f.Args()[1] != notaflag { - t.Errorf("expected argument %q got %q", notaflag, f.Args()[1]) - } - if f.ArgsLenAtDash() != 1 { - t.Errorf("expected argsLenAtDash %d got %d", f.ArgsLenAtDash(), 1) - } -} - -func TestShorthandLookup(t *testing.T) { - f := NewFlagSet("shorthand", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - f.BoolP("boola", "a", false, "bool value") - f.BoolP("boolb", "b", false, "bool2 value") - args := []string{ - "-ab", - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Error("expected no error, got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - flag := f.ShorthandLookup("a") - if flag == nil { - t.Errorf("f.ShorthandLookup(\"a\") returned nil") - } - if flag.Name != "boola" { - t.Errorf("f.ShorthandLookup(\"a\") found %q instead of \"boola\"", flag.Name) - } - flag = f.ShorthandLookup("") - if flag != nil { - t.Errorf("f.ShorthandLookup(\"\") did not return nil") - } - defer func() { - recover() - }() - flag = f.ShorthandLookup("ab") - // should NEVER get here. lookup should panic. defer'd func should recover it. - t.Errorf("f.ShorthandLookup(\"ab\") did not panic") -} - -func TestParse(t *testing.T) { - ResetForTesting(func() { t.Error("bad parse") }) - testParse(GetCommandLine(), t) -} - -func TestParseAll(t *testing.T) { - ResetForTesting(func() { t.Error("bad parse") }) - testParseAll(GetCommandLine(), t) -} - -func TestFlagSetParse(t *testing.T) { - testParse(NewFlagSet("test", ContinueOnError), t) -} - -func TestChangedHelper(t *testing.T) { - f := NewFlagSet("changedtest", ContinueOnError) - f.Bool("changed", false, "changed bool") - f.Bool("settrue", true, "true to true") - f.Bool("setfalse", false, "false to false") - f.Bool("unchanged", false, "unchanged bool") - - args := []string{"--changed", "--settrue", "--setfalse=false"} - if err := f.Parse(args); err != nil { - t.Error("f.Parse() = false after Parse") - } - if !f.Changed("changed") { - t.Errorf("--changed wasn't changed!") - } - if !f.Changed("settrue") { - t.Errorf("--settrue wasn't changed!") - } - if !f.Changed("setfalse") { - t.Errorf("--setfalse wasn't changed!") - } - if f.Changed("unchanged") { - t.Errorf("--unchanged was changed!") - } - if f.Changed("invalid") { - t.Errorf("--invalid was changed!") - } - if f.ArgsLenAtDash() != -1 { - t.Errorf("Expected argsLenAtDash: %d but got %d", -1, f.ArgsLenAtDash()) - } -} - -func replaceSeparators(name string, from []string, to string) string { - result := name - for _, sep := range from { - result = strings.Replace(result, sep, to, -1) - } - // Type convert to indicate normalization has been done. - return result -} - -func wordSepNormalizeFunc(f *FlagSet, name string) NormalizedName { - seps := []string{"-", "_"} - name = replaceSeparators(name, seps, ".") - normalizeFlagNameInvocations++ - - return NormalizedName(name) -} - -func testWordSepNormalizedNames(args []string, t *testing.T) { - f := NewFlagSet("normalized", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - withDashFlag := f.Bool("with-dash-flag", false, "bool value") - // Set this after some flags have been added and before others. - f.SetNormalizeFunc(wordSepNormalizeFunc) - withUnderFlag := f.Bool("with_under_flag", false, "bool value") - withBothFlag := f.Bool("with-both_flag", false, "bool value") - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *withDashFlag != true { - t.Error("withDashFlag flag should be true, is ", *withDashFlag) - } - if *withUnderFlag != true { - t.Error("withUnderFlag flag should be true, is ", *withUnderFlag) - } - if *withBothFlag != true { - t.Error("withBothFlag flag should be true, is ", *withBothFlag) - } -} - -func TestWordSepNormalizedNames(t *testing.T) { - args := []string{ - "--with-dash-flag", - "--with-under-flag", - "--with-both-flag", - } - testWordSepNormalizedNames(args, t) - - args = []string{ - "--with_dash_flag", - "--with_under_flag", - "--with_both_flag", - } - testWordSepNormalizedNames(args, t) - - args = []string{ - "--with-dash_flag", - "--with-under_flag", - "--with-both_flag", - } - testWordSepNormalizedNames(args, t) -} - -func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName { - seps := []string{"-", "_"} - - oldName := replaceSeparators("old-valid_flag", seps, ".") - newName := replaceSeparators("valid-flag", seps, ".") - - name = replaceSeparators(name, seps, ".") - switch name { - case oldName: - name = newName - break - } - - return NormalizedName(name) -} - -func TestCustomNormalizedNames(t *testing.T) { - f := NewFlagSet("normalized", ContinueOnError) - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - - validFlag := f.Bool("valid-flag", false, "bool value") - f.SetNormalizeFunc(aliasAndWordSepFlagNames) - someOtherFlag := f.Bool("some-other-flag", false, "bool value") - - args := []string{"--old_valid_flag", "--some-other_flag"} - if err := f.Parse(args); err != nil { - t.Fatal(err) - } - - if *validFlag != true { - t.Errorf("validFlag is %v even though we set the alias --old_valid_falg", *validFlag) - } - if *someOtherFlag != true { - t.Error("someOtherFlag should be true, is ", *someOtherFlag) - } -} - -// Every flag we add, the name (displayed also in usage) should normalized -func TestNormalizationFuncShouldChangeFlagName(t *testing.T) { - // Test normalization after addition - f := NewFlagSet("normalized", ContinueOnError) - - f.Bool("valid_flag", false, "bool value") - if f.Lookup("valid_flag").Name != "valid_flag" { - t.Error("The new flag should have the name 'valid_flag' instead of ", f.Lookup("valid_flag").Name) - } - - f.SetNormalizeFunc(wordSepNormalizeFunc) - if f.Lookup("valid_flag").Name != "valid.flag" { - t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name) - } - - // Test normalization before addition - f = NewFlagSet("normalized", ContinueOnError) - f.SetNormalizeFunc(wordSepNormalizeFunc) - - f.Bool("valid_flag", false, "bool value") - if f.Lookup("valid_flag").Name != "valid.flag" { - t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name) - } -} - -// Declare a user-defined flag type. -type flagVar []string - -func (f *flagVar) String() string { - return fmt.Sprint([]string(*f)) -} - -func (f *flagVar) Set(value string) error { - *f = append(*f, value) - return nil -} - -func (f *flagVar) Type() string { - return "flagVar" -} - -func TestUserDefined(t *testing.T) { - var flags FlagSet - flags.Init("test", ContinueOnError) - var v flagVar - flags.VarP(&v, "v", "v", "usage") - if err := flags.Parse([]string{"--v=1", "-v2", "-v", "3"}); err != nil { - t.Error(err) - } - if len(v) != 3 { - t.Fatal("expected 3 args; got ", len(v)) - } - expect := "[1 2 3]" - if v.String() != expect { - t.Errorf("expected value %q got %q", expect, v.String()) - } -} - -func TestSetOutput(t *testing.T) { - var flags FlagSet - var buf bytes.Buffer - flags.SetOutput(&buf) - flags.Init("test", ContinueOnError) - flags.Parse([]string{"--unknown"}) - if out := buf.String(); !strings.Contains(out, "--unknown") { - t.Logf("expected output mentioning unknown; got %q", out) - } -} - -// This tests that one can reset the flags. This still works but not well, and is -// superseded by FlagSet. -func TestChangingArgs(t *testing.T) { - ResetForTesting(func() { t.Fatal("bad parse") }) - oldArgs := os.Args - defer func() { os.Args = oldArgs }() - os.Args = []string{"cmd", "--before", "subcmd"} - before := Bool("before", false, "") - if err := GetCommandLine().Parse(os.Args[1:]); err != nil { - t.Fatal(err) - } - cmd := Arg(0) - os.Args = []string{"subcmd", "--after", "args"} - after := Bool("after", false, "") - Parse() - args := Args() - - if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" { - t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args) - } -} - -// Test that -help invokes the usage message and returns ErrHelp. -func TestHelp(t *testing.T) { - var helpCalled = false - fs := NewFlagSet("help test", ContinueOnError) - fs.Usage = func() { helpCalled = true } - var flag bool - fs.BoolVar(&flag, "flag", false, "regular flag") - // Regular flag invocation should work - err := fs.Parse([]string{"--flag=true"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - if !flag { - t.Error("flag was not set by --flag") - } - if helpCalled { - t.Error("help called for regular flag") - helpCalled = false // reset for next test - } - // Help flag should work as expected. - err = fs.Parse([]string{"--help"}) - if err == nil { - t.Fatal("error expected") - } - if err != ErrHelp { - t.Fatal("expected ErrHelp; got ", err) - } - if !helpCalled { - t.Fatal("help was not called") - } - // If we define a help flag, that should override. - var help bool - fs.BoolVar(&help, "help", false, "help flag") - helpCalled = false - err = fs.Parse([]string{"--help"}) - if err != nil { - t.Fatal("expected no error for defined --help; got ", err) - } - if helpCalled { - t.Fatal("help was called; should not have been for defined help flag") - } -} - -func TestNoInterspersed(t *testing.T) { - f := NewFlagSet("test", ContinueOnError) - f.SetInterspersed(false) - f.Bool("true", true, "always true") - f.Bool("false", false, "always false") - err := f.Parse([]string{"--true", "break", "--false"}) - if err != nil { - t.Fatal("expected no error; got ", err) - } - args := f.Args() - if len(args) != 2 || args[0] != "break" || args[1] != "--false" { - t.Fatal("expected interspersed options/non-options to fail") - } -} - -func TestTermination(t *testing.T) { - f := NewFlagSet("termination", ContinueOnError) - boolFlag := f.BoolP("bool", "l", false, "bool value") - if f.Parsed() { - t.Error("f.Parse() = true before Parse") - } - arg1 := "ls" - arg2 := "-l" - args := []string{ - "--", - arg1, - arg2, - } - f.SetOutput(ioutil.Discard) - if err := f.Parse(args); err != nil { - t.Fatal("expected no error; got ", err) - } - if !f.Parsed() { - t.Error("f.Parse() = false after Parse") - } - if *boolFlag { - t.Error("expected boolFlag=false, got true") - } - if len(f.Args()) != 2 { - t.Errorf("expected 2 arguments, got %d: %v", len(f.Args()), f.Args()) - } - if f.Args()[0] != arg1 { - t.Errorf("expected argument %q got %q", arg1, f.Args()[0]) - } - if f.Args()[1] != arg2 { - t.Errorf("expected argument %q got %q", arg2, f.Args()[1]) - } - if f.ArgsLenAtDash() != 0 { - t.Errorf("expected argsLenAtDash %d got %d", 0, f.ArgsLenAtDash()) - } -} - -func TestDeprecatedFlagInDocs(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("badflag", true, "always true") - f.MarkDeprecated("badflag", "use --good-flag instead") - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "badflag") { - t.Errorf("found deprecated flag in usage!") - } -} - -func TestDeprecatedFlagShorthandInDocs(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - name := "noshorthandflag" - f.BoolP(name, "n", true, "always true") - f.MarkShorthandDeprecated("noshorthandflag", fmt.Sprintf("use --%s instead", name)) - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "-n,") { - t.Errorf("found deprecated flag shorthand in usage!") - } -} - -func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error) { - oldStderr := os.Stderr - r, w, _ := os.Pipe() - os.Stderr = w - - err := f.Parse(args) - - outC := make(chan string) - // copy the output in a separate goroutine so printing can't block indefinitely - go func() { - var buf bytes.Buffer - io.Copy(&buf, r) - outC <- buf.String() - }() - - w.Close() - os.Stderr = oldStderr - out := <-outC - - return out, err -} - -func TestDeprecatedFlagUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("badflag", true, "always true") - usageMsg := "use --good-flag instead" - f.MarkDeprecated("badflag", usageMsg) - - args := []string{"--badflag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -func TestDeprecatedFlagShorthandUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - name := "noshorthandflag" - f.BoolP(name, "n", true, "always true") - usageMsg := fmt.Sprintf("use --%s instead", name) - f.MarkShorthandDeprecated(name, usageMsg) - - args := []string{"-n"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -func TestDeprecatedFlagUsageNormalized(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("bad-double_flag", true, "always true") - f.SetNormalizeFunc(wordSepNormalizeFunc) - usageMsg := "use --good-flag instead" - f.MarkDeprecated("bad_double-flag", usageMsg) - - args := []string{"--bad_double_flag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if !strings.Contains(out, usageMsg) { - t.Errorf("usageMsg not printed when using a deprecated flag!") - } -} - -// Name normalization function should be called only once on flag addition -func TestMultipleNormalizeFlagNameInvocations(t *testing.T) { - normalizeFlagNameInvocations = 0 - - f := NewFlagSet("normalized", ContinueOnError) - f.SetNormalizeFunc(wordSepNormalizeFunc) - f.Bool("with_under_flag", false, "bool value") - - if normalizeFlagNameInvocations != 1 { - t.Fatal("Expected normalizeFlagNameInvocations to be 1; got ", normalizeFlagNameInvocations) - } -} - -// -func TestHiddenFlagInUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("secretFlag", true, "shhh") - f.MarkHidden("secretFlag") - - out := new(bytes.Buffer) - f.SetOutput(out) - f.PrintDefaults() - - if strings.Contains(out.String(), "secretFlag") { - t.Errorf("found hidden flag in usage!") - } -} - -// -func TestHiddenFlagUsage(t *testing.T) { - f := NewFlagSet("bob", ContinueOnError) - f.Bool("secretFlag", true, "shhh") - f.MarkHidden("secretFlag") - - args := []string{"--secretFlag"} - out, err := parseReturnStderr(t, f, args) - if err != nil { - t.Fatal("expected no error; got ", err) - } - - if strings.Contains(out, "shhh") { - t.Errorf("usage message printed when using a hidden flag!") - } -} - -const defaultOutput = ` --A for bootstrapping, allow 'any' type - --Alongflagname disable bounds checking - -C, --CCC a boolean defaulting to true (default true) - --D path set relative path for local imports - -E, --EEE num[=1234] a num with NoOptDefVal (default 4321) - --F number a non-zero number (default 2.7) - --G float a float that defaults to zero - --IP ip IP address with no default - --IPMask ipMask Netmask address with no default - --IPNet ipNet IP network with no default - --Ints intSlice int slice with zero default - --N int a non-zero int (default 27) - --ND1 string[="bar"] a string with NoOptDefVal (default "foo") - --ND2 num[=4321] a num with NoOptDefVal (default 1234) - --StringArray stringArray string array with zero default - --StringSlice stringSlice string slice with zero default - --Z int an int that defaults to zero - --custom custom custom Value implementation - --customP custom a VarP with default (default 10) - --maxT timeout set timeout for dial -` - -// Custom value that satisfies the Value interface. -type customValue int - -func (cv *customValue) String() string { return fmt.Sprintf("%v", *cv) } - -func (cv *customValue) Set(s string) error { - v, err := strconv.ParseInt(s, 0, 64) - *cv = customValue(v) - return err -} - -func (cv *customValue) Type() string { return "custom" } - -func TestPrintDefaults(t *testing.T) { - fs := NewFlagSet("print defaults test", ContinueOnError) - var buf bytes.Buffer - fs.SetOutput(&buf) - fs.Bool("A", false, "for bootstrapping, allow 'any' type") - fs.Bool("Alongflagname", false, "disable bounds checking") - fs.BoolP("CCC", "C", true, "a boolean defaulting to true") - fs.String("D", "", "set relative `path` for local imports") - fs.Float64("F", 2.7, "a non-zero `number`") - fs.Float64("G", 0, "a float that defaults to zero") - fs.Int("N", 27, "a non-zero int") - fs.IntSlice("Ints", []int{}, "int slice with zero default") - fs.IP("IP", nil, "IP address with no default") - fs.IPMask("IPMask", nil, "Netmask address with no default") - fs.IPNet("IPNet", net.IPNet{}, "IP network with no default") - fs.Int("Z", 0, "an int that defaults to zero") - fs.Duration("maxT", 0, "set `timeout` for dial") - fs.String("ND1", "foo", "a string with NoOptDefVal") - fs.Lookup("ND1").NoOptDefVal = "bar" - fs.Int("ND2", 1234, "a `num` with NoOptDefVal") - fs.Lookup("ND2").NoOptDefVal = "4321" - fs.IntP("EEE", "E", 4321, "a `num` with NoOptDefVal") - fs.ShorthandLookup("E").NoOptDefVal = "1234" - fs.StringSlice("StringSlice", []string{}, "string slice with zero default") - fs.StringArray("StringArray", []string{}, "string array with zero default") - - var cv customValue - fs.Var(&cv, "custom", "custom Value implementation") - - cv2 := customValue(10) - fs.VarP(&cv2, "customP", "", "a VarP with default") - - fs.PrintDefaults() - got := buf.String() - if got != defaultOutput { - fmt.Println("\n" + got) - fmt.Println("\n" + defaultOutput) - t.Errorf("got %q want %q\n", got, defaultOutput) - } -} - -func TestVisitAllFlagOrder(t *testing.T) { - fs := NewFlagSet("TestVisitAllFlagOrder", ContinueOnError) - fs.SortFlags = false - // https://github.com/spf13/pflag/issues/120 - fs.SetNormalizeFunc(func(f *FlagSet, name string) NormalizedName { - return NormalizedName(name) - }) - - names := []string{"C", "B", "A", "D"} - for _, name := range names { - fs.Bool(name, false, "") - } - - i := 0 - fs.VisitAll(func(f *Flag) { - if names[i] != f.Name { - t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) - } - i++ - }) -} - -func TestVisitFlagOrder(t *testing.T) { - fs := NewFlagSet("TestVisitFlagOrder", ContinueOnError) - fs.SortFlags = false - names := []string{"C", "B", "A", "D"} - for _, name := range names { - fs.Bool(name, false, "") - fs.Set(name, "true") - } - - i := 0 - fs.Visit(func(f *Flag) { - if names[i] != f.Name { - t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) - } - i++ - }) -} diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go index c4f47ebe59..d3dd72b7fe 100644 --- a/vendor/github.com/spf13/pflag/golangflag.go +++ b/vendor/github.com/spf13/pflag/golangflag.go @@ -98,4 +98,8 @@ func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) { newSet.VisitAll(func(goflag *goflag.Flag) { f.AddGoFlag(goflag) }) + if f.addedGoFlagSets == nil { + f.addedGoFlagSets = make([]*goflag.FlagSet, 0) + } + f.addedGoFlagSets = append(f.addedGoFlagSets, newSet) } diff --git a/vendor/github.com/spf13/pflag/golangflag_test.go b/vendor/github.com/spf13/pflag/golangflag_test.go deleted file mode 100644 index 77e2d7d80a..0000000000 --- a/vendor/github.com/spf13/pflag/golangflag_test.go +++ /dev/null @@ -1,39 +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 pflag - -import ( - goflag "flag" - "testing" -) - -func TestGoflags(t *testing.T) { - goflag.String("stringFlag", "stringFlag", "stringFlag") - goflag.Bool("boolFlag", false, "boolFlag") - - f := NewFlagSet("test", ContinueOnError) - - f.AddGoFlagSet(goflag.CommandLine) - err := f.Parse([]string{"--stringFlag=bob", "--boolFlag"}) - if err != nil { - t.Fatal("expected no error; get", err) - } - - getString, err := f.GetString("stringFlag") - if err != nil { - t.Fatal("expected no error; get", err) - } - if getString != "bob" { - t.Fatalf("expected getString=bob but got getString=%s", getString) - } - - getBool, err := f.GetBool("boolFlag") - if err != nil { - t.Fatal("expected no error; get", err) - } - if getBool != true { - t.Fatalf("expected getBool=true but got getBool=%v", getBool) - } -} diff --git a/vendor/github.com/spf13/pflag/int16.go b/vendor/github.com/spf13/pflag/int16.go new file mode 100644 index 0000000000..f1a01d05e6 --- /dev/null +++ b/vendor/github.com/spf13/pflag/int16.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- int16 Value +type int16Value int16 + +func newInt16Value(val int16, p *int16) *int16Value { + *p = val + return (*int16Value)(p) +} + +func (i *int16Value) Set(s string) error { + v, err := strconv.ParseInt(s, 0, 16) + *i = int16Value(v) + return err +} + +func (i *int16Value) Type() string { + return "int16" +} + +func (i *int16Value) String() string { return strconv.FormatInt(int64(*i), 10) } + +func int16Conv(sval string) (interface{}, error) { + v, err := strconv.ParseInt(sval, 0, 16) + if err != nil { + return 0, err + } + return int16(v), nil +} + +// GetInt16 returns the int16 value of a flag with the given name +func (f *FlagSet) GetInt16(name string) (int16, error) { + val, err := f.getFlagType(name, "int16", int16Conv) + if err != nil { + return 0, err + } + return val.(int16), nil +} + +// Int16Var defines an int16 flag with specified name, default value, and usage string. +// The argument p points to an int16 variable in which to store the value of the flag. +func (f *FlagSet) Int16Var(p *int16, name string, value int16, usage string) { + f.VarP(newInt16Value(value, p), name, "", usage) +} + +// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int16VarP(p *int16, name, shorthand string, value int16, usage string) { + f.VarP(newInt16Value(value, p), name, shorthand, usage) +} + +// Int16Var defines an int16 flag with specified name, default value, and usage string. +// The argument p points to an int16 variable in which to store the value of the flag. +func Int16Var(p *int16, name string, value int16, usage string) { + CommandLine.VarP(newInt16Value(value, p), name, "", usage) +} + +// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. +func Int16VarP(p *int16, name, shorthand string, value int16, usage string) { + CommandLine.VarP(newInt16Value(value, p), name, shorthand, usage) +} + +// Int16 defines an int16 flag with specified name, default value, and usage string. +// The return value is the address of an int16 variable that stores the value of the flag. +func (f *FlagSet) Int16(name string, value int16, usage string) *int16 { + p := new(int16) + f.Int16VarP(p, name, "", value, usage) + return p +} + +// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int16P(name, shorthand string, value int16, usage string) *int16 { + p := new(int16) + f.Int16VarP(p, name, shorthand, value, usage) + return p +} + +// Int16 defines an int16 flag with specified name, default value, and usage string. +// The return value is the address of an int16 variable that stores the value of the flag. +func Int16(name string, value int16, usage string) *int16 { + return CommandLine.Int16P(name, "", value, usage) +} + +// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. +func Int16P(name, shorthand string, value int16, usage string) *int16 { + return CommandLine.Int16P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/int_slice_test.go b/vendor/github.com/spf13/pflag/int_slice_test.go deleted file mode 100644 index 745aecb950..0000000000 --- a/vendor/github.com/spf13/pflag/int_slice_test.go +++ /dev/null @@ -1,165 +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 pflag - -import ( - "fmt" - "strconv" - "strings" - "testing" -) - -func setUpISFlagSet(isp *[]int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IntSliceVar(isp, "is", []int{}, "Command separated list!") - return f -} - -func setUpISFlagSetWithDefault(isp *[]int) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IntSliceVar(isp, "is", []int{0, 1}, "Command separated list!") - return f -} - -func TestEmptyIS(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if len(getIS) != 0 { - t.Fatalf("got is %v with len=%d but expected length=0", getIS, len(getIS)) - } -} - -func TestIS(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - - vals := []string{"1", "2", "4", "3"} - arg := fmt.Sprintf("--is=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %s but got: %d", i, vals[i], v) - } - } - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatalf("got error: %v", err) - } - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %s but got: %d from GetIntSlice", i, vals[i], v) - } - } -} - -func TestISDefault(t *testing.T) { - var is []int - f := setUpISFlagSetWithDefault(&is) - - vals := []string{"0", "1"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) - } - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) - } - } -} - -func TestISWithDefault(t *testing.T) { - var is []int - f := setUpISFlagSetWithDefault(&is) - - vals := []string{"1", "2"} - arg := fmt.Sprintf("--is=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v) - } - } - - getIS, err := f.GetIntSlice("is") - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - for i, v := range getIS { - d, err := strconv.Atoi(vals[i]) - if err != nil { - t.Fatalf("got error: %v", err) - } - if d != v { - t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v) - } - } -} - -func TestISCalledTwice(t *testing.T) { - var is []int - f := setUpISFlagSet(&is) - - in := []string{"1,2", "3"} - expected := []int{1, 2, 3} - argfmt := "--is=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range is { - if expected[i] != v { - t.Fatalf("expected is[%d] to be %d but got: %d", i, expected[i], v) - } - } -} diff --git a/vendor/github.com/spf13/pflag/ip_slice_test.go b/vendor/github.com/spf13/pflag/ip_slice_test.go deleted file mode 100644 index b0c681c5b2..0000000000 --- a/vendor/github.com/spf13/pflag/ip_slice_test.go +++ /dev/null @@ -1,222 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "strings" - "testing" -) - -func setUpIPSFlagSet(ipsp *[]net.IP) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IPSliceVar(ipsp, "ips", []net.IP{}, "Command separated list!") - return f -} - -func setUpIPSFlagSetWithDefault(ipsp *[]net.IP) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IPSliceVar(ipsp, "ips", - []net.IP{ - net.ParseIP("192.168.1.1"), - net.ParseIP("0:0:0:0:0:0:0:1"), - }, - "Command separated list!") - return f -} - -func TestEmptyIP(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSet(&ips) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getIPS, err := f.GetIPSlice("ips") - if err != nil { - t.Fatal("got an error from GetIPSlice():", err) - } - if len(getIPS) != 0 { - t.Fatalf("got ips %v with len=%d but expected length=0", getIPS, len(getIPS)) - } -} - -func TestIPS(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSet(&ips) - - vals := []string{"192.168.1.1", "10.0.0.1", "0:0:0:0:0:0:0:2"} - arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s from GetIPSlice", i, vals[i], v) - } - } -} - -func TestIPSDefault(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSetWithDefault(&ips) - - vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"} - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getIPS, err := f.GetIPSlice("ips") - if err != nil { - t.Fatal("got an error from GetIPSlice") - } - for i, v := range getIPS { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } -} - -func TestIPSWithDefault(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSetWithDefault(&ips) - - vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"} - arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getIPS, err := f.GetIPSlice("ips") - if err != nil { - t.Fatal("got an error from GetIPSlice") - } - for i, v := range getIPS { - if ip := net.ParseIP(vals[i]); ip == nil { - t.Fatalf("invalid string being converted to IP address: %s", vals[i]) - } else if !ip.Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v) - } - } -} - -func TestIPSCalledTwice(t *testing.T) { - var ips []net.IP - f := setUpIPSFlagSet(&ips) - - in := []string{"192.168.1.2,0:0:0:0:0:0:0:1", "10.0.0.1"} - expected := []net.IP{net.ParseIP("192.168.1.2"), net.ParseIP("0:0:0:0:0:0:0:1"), net.ParseIP("10.0.0.1")} - argfmt := "ips=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ips { - if !expected[i].Equal(v) { - t.Fatalf("expected ips[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestIPSBadQuoting(t *testing.T) { - - tests := []struct { - Want []net.IP - FlagArg []string - }{ - { - Want: []net.IP{ - net.ParseIP("a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568"), - net.ParseIP("203.107.49.208"), - net.ParseIP("14.57.204.90"), - }, - FlagArg: []string{ - "a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568", - "203.107.49.208", - "14.57.204.90", - }, - }, - { - Want: []net.IP{ - net.ParseIP("204.228.73.195"), - net.ParseIP("86.141.15.94"), - }, - FlagArg: []string{ - "204.228.73.195", - "86.141.15.94", - }, - }, - { - Want: []net.IP{ - net.ParseIP("c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f"), - net.ParseIP("4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472"), - }, - FlagArg: []string{ - "c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f", - "4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472", - }, - }, - { - Want: []net.IP{ - net.ParseIP("5170:f971:cfac:7be3:512a:af37:952c:bc33"), - net.ParseIP("93.21.145.140"), - net.ParseIP("2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca"), - }, - FlagArg: []string{ - " 5170:f971:cfac:7be3:512a:af37:952c:bc33 , 93.21.145.140 ", - "2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca", - }, - }, - { - Want: []net.IP{ - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"), - }, - FlagArg: []string{ - `"2e5e:66b2:6441:848:5b74:76ea:574c:3a7b, 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b,2e5e:66b2:6441:848:5b74:76ea:574c:3a7b "`, - " 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"}, - }, - } - - for i, test := range tests { - - var ips []net.IP - f := setUpIPSFlagSet(&ips) - - if err := f.Parse([]string{fmt.Sprintf("--ips=%s", strings.Join(test.FlagArg, ","))}); err != nil { - t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%s", - err, test.FlagArg, test.Want[i]) - } - - for j, b := range ips { - if !b.Equal(test.Want[j]) { - t.Fatalf("bad value parsed for test %d on net.IP %d:\nwant:\t%s\ngot:\t%s", i, j, test.Want[j], b) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/ip_test.go b/vendor/github.com/spf13/pflag/ip_test.go deleted file mode 100644 index 1fec50e425..0000000000 --- a/vendor/github.com/spf13/pflag/ip_test.go +++ /dev/null @@ -1,63 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "os" - "testing" -) - -func setUpIP(ip *net.IP) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.IPVar(ip, "address", net.ParseIP("0.0.0.0"), "IP Address") - return f -} - -func TestIP(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - {"0.0.0.0", true, "0.0.0.0"}, - {" 0.0.0.0 ", true, "0.0.0.0"}, - {"1.2.3.4", true, "1.2.3.4"}, - {"127.0.0.1", true, "127.0.0.1"}, - {"255.255.255.255", true, "255.255.255.255"}, - {"", false, ""}, - {"0", false, ""}, - {"localhost", false, ""}, - {"0.0.0", false, ""}, - {"0.0.0.", false, ""}, - {"0.0.0.0.", false, ""}, - {"0.0.0.256", false, ""}, - {"0 . 0 . 0 . 0", false, ""}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var addr net.IP - f := setUpIP(&addr) - - tc := &testCases[i] - - arg := fmt.Sprintf("--address=%s", tc.input) - err := f.Parse([]string{arg}) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure") - continue - } else if tc.success { - ip, err := f.GetIP("address") - if err != nil { - t.Errorf("Got error trying to fetch the IP flag: %v", err) - } - if ip.String() != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, ip.String()) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/ipnet_test.go b/vendor/github.com/spf13/pflag/ipnet_test.go deleted file mode 100644 index 335b6fa156..0000000000 --- a/vendor/github.com/spf13/pflag/ipnet_test.go +++ /dev/null @@ -1,70 +0,0 @@ -package pflag - -import ( - "fmt" - "net" - "os" - "testing" -) - -func setUpIPNet(ip *net.IPNet) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - _, def, _ := net.ParseCIDR("0.0.0.0/0") - f.IPNetVar(ip, "address", *def, "IP Address") - return f -} - -func TestIPNet(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - }{ - {"0.0.0.0/0", true, "0.0.0.0/0"}, - {" 0.0.0.0/0 ", true, "0.0.0.0/0"}, - {"1.2.3.4/8", true, "1.0.0.0/8"}, - {"127.0.0.1/16", true, "127.0.0.0/16"}, - {"255.255.255.255/19", true, "255.255.224.0/19"}, - {"255.255.255.255/32", true, "255.255.255.255/32"}, - {"", false, ""}, - {"/0", false, ""}, - {"0", false, ""}, - {"0/0", false, ""}, - {"localhost/0", false, ""}, - {"0.0.0/4", false, ""}, - {"0.0.0./8", false, ""}, - {"0.0.0.0./12", false, ""}, - {"0.0.0.256/16", false, ""}, - {"0.0.0.0 /20", false, ""}, - {"0.0.0.0/ 24", false, ""}, - {"0 . 0 . 0 . 0 / 28", false, ""}, - {"0.0.0.0/33", false, ""}, - } - - devnull, _ := os.Open(os.DevNull) - os.Stderr = devnull - for i := range testCases { - var addr net.IPNet - f := setUpIPNet(&addr) - - tc := &testCases[i] - - arg := fmt.Sprintf("--address=%s", tc.input) - err := f.Parse([]string{arg}) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure") - continue - } else if tc.success { - ip, err := f.GetIPNet("address") - if err != nil { - t.Errorf("Got error trying to fetch the IP flag: %v", err) - } - if ip.String() != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, ip.String()) - } - } - } -} diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go index 276b7ed49e..fa7bc60187 100644 --- a/vendor/github.com/spf13/pflag/string_array.go +++ b/vendor/github.com/spf13/pflag/string_array.go @@ -52,7 +52,7 @@ func (f *FlagSet) GetStringArray(name string) ([]string, error) { // StringArrayVar defines a string flag with specified name, default value, and usage string. // The argument p points to a []string variable in which to store the values of the multiple flags. -// The value of each argument will not try to be separated by comma +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) { f.VarP(newStringArrayValue(value, p), name, "", usage) } @@ -64,7 +64,7 @@ func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []s // StringArrayVar defines a string flag with specified name, default value, and usage string. // The argument p points to a []string variable in which to store the value of the flag. -// The value of each argument will not try to be separated by comma +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. func StringArrayVar(p *[]string, name string, value []string, usage string) { CommandLine.VarP(newStringArrayValue(value, p), name, "", usage) } @@ -76,7 +76,7 @@ func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage // StringArray defines a string flag with specified name, default value, and usage string. // The return value is the address of a []string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string { p := []string{} f.StringArrayVarP(&p, name, "", value, usage) @@ -92,7 +92,7 @@ func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage str // StringArray defines a string flag with specified name, default value, and usage string. // The return value is the address of a []string variable that stores the value of the flag. -// The value of each argument will not try to be separated by comma +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. func StringArray(name string, value []string, usage string) *[]string { return CommandLine.StringArrayP(name, "", value, usage) } diff --git a/vendor/github.com/spf13/pflag/string_array_test.go b/vendor/github.com/spf13/pflag/string_array_test.go deleted file mode 100644 index 1ceac8c6c6..0000000000 --- a/vendor/github.com/spf13/pflag/string_array_test.go +++ /dev/null @@ -1,233 +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 pflag - -import ( - "fmt" - "testing" -) - -func setUpSAFlagSet(sap *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringArrayVar(sap, "sa", []string{}, "Command separated list!") - return f -} - -func setUpSAFlagSetWithDefault(sap *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringArrayVar(sap, "sa", []string{"default", "values"}, "Command separated list!") - return f -} - -func TestEmptySA(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - if len(getSA) != 0 { - t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA)) - } -} - -func TestEmptySAValue(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - err := f.Parse([]string{"--sa="}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - if len(getSA) != 0 { - t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA)) - } -} - -func TestSADefault(t *testing.T) { - var sa []string - f := setUpSAFlagSetWithDefault(&sa) - - vals := []string{"default", "values"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range sa { - if vals[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - for i, v := range getSA { - if vals[i] != v { - t.Fatalf("expected sa[%d] to be %s from GetStringArray but got: %s", i, vals[i], v) - } - } -} - -func TestSAWithDefault(t *testing.T) { - var sa []string - f := setUpSAFlagSetWithDefault(&sa) - - val := "one" - arg := fmt.Sprintf("--sa=%s", val) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(sa) != 1 { - t.Fatalf("expected number of values to be %d but %d", 1, len(sa)) - } - - if sa[0] != val { - t.Fatalf("expected value to be %s but got: %s", sa[0], val) - } - - getSA, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("got an error from GetStringArray():", err) - } - - if len(getSA) != 1 { - t.Fatalf("expected number of values to be %d but %d", 1, len(getSA)) - } - - if getSA[0] != val { - t.Fatalf("expected value to be %s but got: %s", getSA[0], val) - } -} - -func TestSACalledTwice(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - - in := []string{"one", "two"} - expected := []string{"one", "two"} - argfmt := "--sa=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(sa) { - t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range sa { - if expected[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSAWithSpecialChar(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - - in := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"} - expected := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"} - argfmt := "--sa=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - arg3 := fmt.Sprintf(argfmt, in[2]) - arg4 := fmt.Sprintf(argfmt, in[3]) - err := f.Parse([]string{arg1, arg2, arg3, arg4}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(sa) { - t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range sa { - if expected[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSAWithSquareBrackets(t *testing.T) { - var sa []string - f := setUpSAFlagSet(&sa) - - in := []string{"][]-[", "[a-z]", "[a-z]+"} - expected := []string{"][]-[", "[a-z]", "[a-z]+"} - argfmt := "--sa=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - arg3 := fmt.Sprintf(argfmt, in[2]) - err := f.Parse([]string{arg1, arg2, arg3}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(sa) { - t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa)) - } - for i, v := range sa { - if expected[i] != v { - t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringArray("sa") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v) - } - } -} diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go index 05eee75438..0cd3ccc083 100644 --- a/vendor/github.com/spf13/pflag/string_slice.go +++ b/vendor/github.com/spf13/pflag/string_slice.go @@ -82,6 +82,11 @@ func (f *FlagSet) GetStringSlice(name string) ([]string, error) { // StringSliceVar defines a string flag with specified name, default value, and usage string. // The argument p points to a []string variable in which to store the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" -ss="v3" +// will result in +// []string{"v1", "v2", "v3"} func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) { f.VarP(newStringSliceValue(value, p), name, "", usage) } @@ -93,6 +98,11 @@ func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []s // StringSliceVar defines a string flag with specified name, default value, and usage string. // The argument p points to a []string variable in which to store the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" -ss="v3" +// will result in +// []string{"v1", "v2", "v3"} func StringSliceVar(p *[]string, name string, value []string, usage string) { CommandLine.VarP(newStringSliceValue(value, p), name, "", usage) } @@ -104,6 +114,11 @@ func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage // StringSlice defines a string flag with specified name, default value, and usage string. // The return value is the address of a []string variable that stores the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" -ss="v3" +// will result in +// []string{"v1", "v2", "v3"} func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string { p := []string{} f.StringSliceVarP(&p, name, "", value, usage) @@ -119,6 +134,11 @@ func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage str // StringSlice defines a string flag with specified name, default value, and usage string. // The return value is the address of a []string variable that stores the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" -ss="v3" +// will result in +// []string{"v1", "v2", "v3"} func StringSlice(name string, value []string, usage string) *[]string { return CommandLine.StringSliceP(name, "", value, usage) } diff --git a/vendor/github.com/spf13/pflag/string_slice_test.go b/vendor/github.com/spf13/pflag/string_slice_test.go deleted file mode 100644 index c41f3bd660..0000000000 --- a/vendor/github.com/spf13/pflag/string_slice_test.go +++ /dev/null @@ -1,253 +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 pflag - -import ( - "fmt" - "strings" - "testing" -) - -func setUpSSFlagSet(ssp *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringSliceVar(ssp, "ss", []string{}, "Command separated list!") - return f -} - -func setUpSSFlagSetWithDefault(ssp *[]string) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.StringSliceVar(ssp, "ss", []string{"default", "values"}, "Command separated list!") - return f -} - -func TestEmptySS(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - if len(getSS) != 0 { - t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS)) - } -} - -func TestEmptySSValue(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - err := f.Parse([]string{"--ss="}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - if len(getSS) != 0 { - t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS)) - } -} - -func TestSS(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - vals := []string{"one", "two", "4", "3"} - arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSDefault(t *testing.T) { - var ss []string - f := setUpSSFlagSetWithDefault(&ss) - - vals := []string{"default", "values"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSWithDefault(t *testing.T) { - var ss []string - f := setUpSSFlagSetWithDefault(&ss) - - vals := []string{"one", "two", "4", "3"} - arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range ss { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) - } - } - - getSS, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("got an error from GetStringSlice():", err) - } - for i, v := range getSS { - if vals[i] != v { - t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) - } - } -} - -func TestSSCalledTwice(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{"one,two", "three"} - expected := []string{"one", "two", "three"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(ss) { - t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSSWithComma(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{`"one,two"`, `"three"`, `"four,five",six`} - expected := []string{"one,two", "three", "four,five", "six"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - arg3 := fmt.Sprintf(argfmt, in[2]) - err := f.Parse([]string{arg1, arg2, arg3}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(ss) { - t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} - -func TestSSWithSquareBrackets(t *testing.T) { - var ss []string - f := setUpSSFlagSet(&ss) - - in := []string{`"[a-z]"`, `"[a-z]+"`} - expected := []string{"[a-z]", "[a-z]+"} - argfmt := "--ss=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(ss) { - t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss)) - } - for i, v := range ss { - if expected[i] != v { - t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v) - } - } - - values, err := f.GetStringSlice("ss") - if err != nil { - t.Fatal("expected no error; got", err) - } - - if len(expected) != len(values) { - t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values)) - } - for i, v := range values { - if expected[i] != v { - t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v) - } - } -} diff --git a/vendor/github.com/spf13/pflag/uint_slice_test.go b/vendor/github.com/spf13/pflag/uint_slice_test.go deleted file mode 100644 index db1a19dc2d..0000000000 --- a/vendor/github.com/spf13/pflag/uint_slice_test.go +++ /dev/null @@ -1,161 +0,0 @@ -package pflag - -import ( - "fmt" - "strconv" - "strings" - "testing" -) - -func setUpUISFlagSet(uisp *[]uint) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.UintSliceVar(uisp, "uis", []uint{}, "Command separated list!") - return f -} - -func setUpUISFlagSetWithDefault(uisp *[]uint) *FlagSet { - f := NewFlagSet("test", ContinueOnError) - f.UintSliceVar(uisp, "uis", []uint{0, 1}, "Command separated list!") - return f -} - -func TestEmptyUIS(t *testing.T) { - var uis []uint - f := setUpUISFlagSet(&uis) - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatal("got an error from GetUintSlice():", err) - } - if len(getUIS) != 0 { - t.Fatalf("got is %v with len=%d but expected length=0", getUIS, len(getUIS)) - } -} - -func TestUIS(t *testing.T) { - var uis []uint - f := setUpUISFlagSet(&uis) - - vals := []string{"1", "2", "4", "3"} - arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %s but got %d", i, vals[i], v) - } - } - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatalf("got error: %v", err) - } - for i, v := range getUIS { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %s but got: %d from GetUintSlice", i, vals[i], v) - } - } -} - -func TestUISDefault(t *testing.T) { - var uis []uint - f := setUpUISFlagSetWithDefault(&uis) - - vals := []string{"0", "1"} - - err := f.Parse([]string{}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expect uis[%d] to be %d but got: %d", i, u, v) - } - } - - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatal("got an error from GetUintSlice():", err) - } - for i, v := range getUIS { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatal("got an error from GetIntSlice():", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) - } - } -} - -func TestUISWithDefault(t *testing.T) { - var uis []uint - f := setUpUISFlagSetWithDefault(&uis) - - vals := []string{"1", "2"} - arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ",")) - err := f.Parse([]string{arg}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) - } - } - - getUIS, err := f.GetUintSlice("uis") - if err != nil { - t.Fatal("got an error from GetUintSlice():", err) - } - for i, v := range getUIS { - u, err := strconv.ParseUint(vals[i], 10, 0) - if err != nil { - t.Fatalf("got error: %v", err) - } - if uint(u) != v { - t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v) - } - } -} - -func TestUISCalledTwice(t *testing.T) { - var uis []uint - f := setUpUISFlagSet(&uis) - - in := []string{"1,2", "3"} - expected := []int{1, 2, 3} - argfmt := "--uis=%s" - arg1 := fmt.Sprintf(argfmt, in[0]) - arg2 := fmt.Sprintf(argfmt, in[1]) - err := f.Parse([]string{arg1, arg2}) - if err != nil { - t.Fatal("expected no error; got", err) - } - for i, v := range uis { - if uint(expected[i]) != v { - t.Fatalf("expected uis[%d] to be %d but got: %d", i, expected[i], v) - } - } -} diff --git a/vendor/github.com/zakjan/cert-chain-resolver/certUtil/chain_test.go b/vendor/github.com/zakjan/cert-chain-resolver/certUtil/chain_test.go deleted file mode 100644 index 592aaac703..0000000000 --- a/vendor/github.com/zakjan/cert-chain-resolver/certUtil/chain_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package certUtil - -import ( - "crypto/x509" - "testing" - "os" - "io/ioutil" - "github.com/stretchr/testify/assert" -) - -func TestFetchCertificateChain(t *testing.T) { - file, err := os.Open("../tests/comodo.der.crt") - if err != nil { - t.Error(err) - } - - data, err := ioutil.ReadAll(file) - if err != nil { - t.Error(err) - } - - cert, err := x509.ParseCertificate(data) - if err != nil { - t.Error(err) - } - - certs, err := FetchCertificateChain(cert) - if err != nil { - t.Error(err) - } - - assert.Equal(t, 3, len(certs)) -} diff --git a/vendor/github.com/zakjan/cert-chain-resolver/certUtil/io_test.go b/vendor/github.com/zakjan/cert-chain-resolver/certUtil/io_test.go deleted file mode 100644 index c897f9ba08..0000000000 --- a/vendor/github.com/zakjan/cert-chain-resolver/certUtil/io_test.go +++ /dev/null @@ -1,11 +0,0 @@ -package certUtil - -import ( - "github.com/stretchr/testify/assert" - "testing" -) - -func TestIsPEM(t *testing.T) { - assert.True(t, IsPEM([]byte("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"))) - assert.False(t, IsPEM([]byte("xxx"))) -} diff --git a/vendor/golang.org/x/crypto/CONTRIBUTING.md b/vendor/golang.org/x/crypto/CONTRIBUTING.md index 88dff59bc7..d0485e887a 100644 --- a/vendor/golang.org/x/crypto/CONTRIBUTING.md +++ b/vendor/golang.org/x/crypto/CONTRIBUTING.md @@ -4,16 +4,15 @@ Go is an open source project. It is the work of hundreds of contributors. We appreciate your help! - ## Filing issues When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: -1. What version of Go are you using (`go version`)? -2. What operating system and processor architecture are you using? -3. What did you do? -4. What did you expect to see? -5. What did you see instead? +1. What version of Go are you using (`go version`)? +2. What operating system and processor architecture are you using? +3. What did you do? +4. What did you expect to see? +5. What did you see instead? General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. The gophers there will answer or ask you to file an issue if you've tripped over a bug. @@ -23,9 +22,5 @@ The gophers there will answer or ask you to file an issue if you've tripped over Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) before sending patches. -**We do not accept GitHub pull requests** -(we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). - Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file. - diff --git a/vendor/golang.org/x/crypto/ed25519/ed25519.go b/vendor/golang.org/x/crypto/ed25519/ed25519.go index 4f26b49b6a..a57771a1ed 100644 --- a/vendor/golang.org/x/crypto/ed25519/ed25519.go +++ b/vendor/golang.org/x/crypto/ed25519/ed25519.go @@ -171,9 +171,16 @@ func Verify(publicKey PublicKey, message, sig []byte) bool { edwards25519.ScReduce(&hReduced, &digest) var R edwards25519.ProjectiveGroupElement - var b [32]byte - copy(b[:], sig[32:]) - edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &b) + var s [32]byte + copy(s[:], sig[32:]) + + // https://tools.ietf.org/html/rfc8032#section-5.1.7 requires that s be in + // the range [0, order) in order to prevent signature malleability. + if !edwards25519.ScMinimal(&s) { + return false + } + + edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &s) var checkR [32]byte R.ToBytes(&checkR) diff --git a/vendor/golang.org/x/crypto/ed25519/ed25519_test.go b/vendor/golang.org/x/crypto/ed25519/ed25519_test.go deleted file mode 100644 index e272f8a557..0000000000 --- a/vendor/golang.org/x/crypto/ed25519/ed25519_test.go +++ /dev/null @@ -1,183 +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 ed25519 - -import ( - "bufio" - "bytes" - "compress/gzip" - "crypto" - "crypto/rand" - "encoding/hex" - "os" - "strings" - "testing" - - "golang.org/x/crypto/ed25519/internal/edwards25519" -) - -type zeroReader struct{} - -func (zeroReader) Read(buf []byte) (int, error) { - for i := range buf { - buf[i] = 0 - } - return len(buf), nil -} - -func TestUnmarshalMarshal(t *testing.T) { - pub, _, _ := GenerateKey(rand.Reader) - - var A edwards25519.ExtendedGroupElement - var pubBytes [32]byte - copy(pubBytes[:], pub) - if !A.FromBytes(&pubBytes) { - t.Fatalf("ExtendedGroupElement.FromBytes failed") - } - - var pub2 [32]byte - A.ToBytes(&pub2) - - if pubBytes != pub2 { - t.Errorf("FromBytes(%v)->ToBytes does not round-trip, got %x\n", pubBytes, pub2) - } -} - -func TestSignVerify(t *testing.T) { - var zero zeroReader - public, private, _ := GenerateKey(zero) - - message := []byte("test message") - sig := Sign(private, message) - if !Verify(public, message, sig) { - t.Errorf("valid signature rejected") - } - - wrongMessage := []byte("wrong message") - if Verify(public, wrongMessage, sig) { - t.Errorf("signature of different message accepted") - } -} - -func TestCryptoSigner(t *testing.T) { - var zero zeroReader - public, private, _ := GenerateKey(zero) - - signer := crypto.Signer(private) - - publicInterface := signer.Public() - public2, ok := publicInterface.(PublicKey) - if !ok { - t.Fatalf("expected PublicKey from Public() but got %T", publicInterface) - } - - if !bytes.Equal(public, public2) { - t.Errorf("public keys do not match: original:%x vs Public():%x", public, public2) - } - - message := []byte("message") - var noHash crypto.Hash - signature, err := signer.Sign(zero, message, noHash) - if err != nil { - t.Fatalf("error from Sign(): %s", err) - } - - if !Verify(public, message, signature) { - t.Errorf("Verify failed on signature from Sign()") - } -} - -func TestGolden(t *testing.T) { - // sign.input.gz is a selection of test cases from - // https://ed25519.cr.yp.to/python/sign.input - testDataZ, err := os.Open("testdata/sign.input.gz") - if err != nil { - t.Fatal(err) - } - defer testDataZ.Close() - testData, err := gzip.NewReader(testDataZ) - if err != nil { - t.Fatal(err) - } - defer testData.Close() - - scanner := bufio.NewScanner(testData) - lineNo := 0 - - for scanner.Scan() { - lineNo++ - - line := scanner.Text() - parts := strings.Split(line, ":") - if len(parts) != 5 { - t.Fatalf("bad number of parts on line %d", lineNo) - } - - privBytes, _ := hex.DecodeString(parts[0]) - pubKey, _ := hex.DecodeString(parts[1]) - msg, _ := hex.DecodeString(parts[2]) - sig, _ := hex.DecodeString(parts[3]) - // The signatures in the test vectors also include the message - // at the end, but we just want R and S. - sig = sig[:SignatureSize] - - if l := len(pubKey); l != PublicKeySize { - t.Fatalf("bad public key length on line %d: got %d bytes", lineNo, l) - } - - var priv [PrivateKeySize]byte - copy(priv[:], privBytes) - copy(priv[32:], pubKey) - - sig2 := Sign(priv[:], msg) - if !bytes.Equal(sig, sig2[:]) { - t.Errorf("different signature result on line %d: %x vs %x", lineNo, sig, sig2) - } - - if !Verify(pubKey, msg, sig2) { - t.Errorf("signature failed to verify on line %d", lineNo) - } - } - - if err := scanner.Err(); err != nil { - t.Fatalf("error reading test data: %s", err) - } -} - -func BenchmarkKeyGeneration(b *testing.B) { - var zero zeroReader - for i := 0; i < b.N; i++ { - if _, _, err := GenerateKey(zero); err != nil { - b.Fatal(err) - } - } -} - -func BenchmarkSigning(b *testing.B) { - var zero zeroReader - _, priv, err := GenerateKey(zero) - if err != nil { - b.Fatal(err) - } - message := []byte("Hello, world!") - b.ResetTimer() - for i := 0; i < b.N; i++ { - Sign(priv, message) - } -} - -func BenchmarkVerification(b *testing.B) { - var zero zeroReader - pub, priv, err := GenerateKey(zero) - if err != nil { - b.Fatal(err) - } - message := []byte("Hello, world!") - signature := Sign(priv, message) - b.ResetTimer() - for i := 0; i < b.N; i++ { - Verify(pub, message, signature) - } -} diff --git a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go index 5f8b994787..fd03c252af 100644 --- a/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go +++ b/vendor/golang.org/x/crypto/ed25519/internal/edwards25519/edwards25519.go @@ -4,6 +4,8 @@ package edwards25519 +import "encoding/binary" + // This code is a port of the public domain, “ref10” implementation of ed25519 // from SUPERCOP. @@ -1769,3 +1771,23 @@ func ScReduce(out *[32]byte, s *[64]byte) { out[30] = byte(s11 >> 9) out[31] = byte(s11 >> 17) } + +// order is the order of Curve25519 in little-endian form. +var order = [4]uint64{0x5812631a5cf5d3ed, 0x14def9dea2f79cd6, 0, 0x1000000000000000} + +// ScMinimal returns true if the given scalar is less than the order of the +// curve. +func ScMinimal(scalar *[32]byte) bool { + for i := 3; ; i-- { + v := binary.LittleEndian.Uint64(scalar[i*8:]) + if v > order[i] { + return false + } else if v < order[i] { + break + } else if i == 0 { + return false + } + } + + return true +} diff --git a/vendor/golang.org/x/crypto/ssh/benchmark_test.go b/vendor/golang.org/x/crypto/ssh/benchmark_test.go deleted file mode 100644 index d9f7eb9b60..0000000000 --- a/vendor/golang.org/x/crypto/ssh/benchmark_test.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "errors" - "io" - "net" - "testing" -) - -type server struct { - *ServerConn - chans <-chan NewChannel -} - -func newServer(c net.Conn, conf *ServerConfig) (*server, error) { - sconn, chans, reqs, err := NewServerConn(c, conf) - if err != nil { - return nil, err - } - go DiscardRequests(reqs) - return &server{sconn, chans}, nil -} - -func (s *server) Accept() (NewChannel, error) { - n, ok := <-s.chans - if !ok { - return nil, io.EOF - } - return n, nil -} - -func sshPipe() (Conn, *server, error) { - c1, c2, err := netPipe() - if err != nil { - return nil, nil, err - } - - clientConf := ClientConfig{ - User: "user", - } - serverConf := ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["ecdsa"]) - done := make(chan *server, 1) - go func() { - server, err := newServer(c2, &serverConf) - if err != nil { - done <- nil - } - done <- server - }() - - client, _, reqs, err := NewClientConn(c1, "", &clientConf) - if err != nil { - return nil, nil, err - } - - server := <-done - if server == nil { - return nil, nil, errors.New("server handshake failed.") - } - go DiscardRequests(reqs) - - return client, server, nil -} - -func BenchmarkEndToEnd(b *testing.B) { - b.StopTimer() - - client, server, err := sshPipe() - if err != nil { - b.Fatalf("sshPipe: %v", err) - } - - defer client.Close() - defer server.Close() - - size := (1 << 20) - input := make([]byte, size) - output := make([]byte, size) - b.SetBytes(int64(size)) - done := make(chan int, 1) - - go func() { - newCh, err := server.Accept() - if err != nil { - b.Fatalf("Client: %v", err) - } - ch, incoming, err := newCh.Accept() - go DiscardRequests(incoming) - for i := 0; i < b.N; i++ { - if _, err := io.ReadFull(ch, output); err != nil { - b.Fatalf("ReadFull: %v", err) - } - } - ch.Close() - done <- 1 - }() - - ch, in, err := client.OpenChannel("speed", nil) - if err != nil { - b.Fatalf("OpenChannel: %v", err) - } - go DiscardRequests(in) - - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - if _, err := ch.Write(input); err != nil { - b.Fatalf("WriteFull: %v", err) - } - } - ch.Close() - b.StopTimer() - - <-done -} diff --git a/vendor/golang.org/x/crypto/ssh/buffer_test.go b/vendor/golang.org/x/crypto/ssh/buffer_test.go deleted file mode 100644 index d5781cb3da..0000000000 --- a/vendor/golang.org/x/crypto/ssh/buffer_test.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "io" - "testing" -) - -var alphabet = []byte("abcdefghijklmnopqrstuvwxyz") - -func TestBufferReadwrite(t *testing.T) { - b := newBuffer() - b.write(alphabet[:10]) - r, _ := b.Read(make([]byte, 10)) - if r != 10 { - t.Fatalf("Expected written == read == 10, written: 10, read %d", r) - } - - b = newBuffer() - b.write(alphabet[:5]) - r, _ = b.Read(make([]byte, 10)) - if r != 5 { - t.Fatalf("Expected written == read == 5, written: 5, read %d", r) - } - - b = newBuffer() - b.write(alphabet[:10]) - r, _ = b.Read(make([]byte, 5)) - if r != 5 { - t.Fatalf("Expected written == 10, read == 5, written: 10, read %d", r) - } - - b = newBuffer() - b.write(alphabet[:5]) - b.write(alphabet[5:15]) - r, _ = b.Read(make([]byte, 10)) - r2, _ := b.Read(make([]byte, 10)) - if r != 10 || r2 != 5 || 15 != r+r2 { - t.Fatal("Expected written == read == 15") - } -} - -func TestBufferClose(t *testing.T) { - b := newBuffer() - b.write(alphabet[:10]) - b.eof() - _, err := b.Read(make([]byte, 5)) - if err != nil { - t.Fatal("expected read of 5 to not return EOF") - } - b = newBuffer() - b.write(alphabet[:10]) - b.eof() - r, err := b.Read(make([]byte, 5)) - r2, err2 := b.Read(make([]byte, 10)) - if r != 5 || r2 != 5 || err != nil || err2 != nil { - t.Fatal("expected reads of 5 and 5") - } - - b = newBuffer() - b.write(alphabet[:10]) - b.eof() - r, err = b.Read(make([]byte, 5)) - r2, err2 = b.Read(make([]byte, 10)) - r3, err3 := b.Read(make([]byte, 10)) - if r != 5 || r2 != 5 || r3 != 0 || err != nil || err2 != nil || err3 != io.EOF { - t.Fatal("expected reads of 5 and 5 and 0, with EOF") - } - - b = newBuffer() - b.write(make([]byte, 5)) - b.write(make([]byte, 10)) - b.eof() - r, err = b.Read(make([]byte, 9)) - r2, err2 = b.Read(make([]byte, 3)) - r3, err3 = b.Read(make([]byte, 3)) - r4, err4 := b.Read(make([]byte, 10)) - if err != nil || err2 != nil || err3 != nil || err4 != io.EOF { - t.Fatalf("Expected EOF on forth read only, err=%v, err2=%v, err3=%v, err4=%v", err, err2, err3, err4) - } - if r != 9 || r2 != 3 || r3 != 3 || r4 != 0 { - t.Fatal("Expected written == read == 15", r, r2, r3, r4) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/certs.go b/vendor/golang.org/x/crypto/ssh/certs.go index b1f0220781..42106f3f2c 100644 --- a/vendor/golang.org/x/crypto/ssh/certs.go +++ b/vendor/golang.org/x/crypto/ssh/certs.go @@ -44,7 +44,9 @@ type Signature struct { const CertTimeInfinity = 1<<64 - 1 // An Certificate represents an OpenSSH certificate as defined in -// [PROTOCOL.certkeys]?rev=1.8. +// [PROTOCOL.certkeys]?rev=1.8. The Certificate type implements the +// PublicKey interface, so it can be unmarshaled using +// ParsePublicKey. type Certificate struct { Nonce []byte Key PublicKey @@ -340,10 +342,10 @@ func (c *CertChecker) Authenticate(conn ConnMetadata, pubKey PublicKey) (*Permis // the signature of the certificate. func (c *CertChecker) CheckCert(principal string, cert *Certificate) error { if c.IsRevoked != nil && c.IsRevoked(cert) { - return fmt.Errorf("ssh: certicate serial %d revoked", cert.Serial) + return fmt.Errorf("ssh: certificate serial %d revoked", cert.Serial) } - for opt, _ := range cert.CriticalOptions { + for opt := range cert.CriticalOptions { // sourceAddressCriticalOption will be enforced by // serverAuthenticate if opt == sourceAddressCriticalOption { diff --git a/vendor/golang.org/x/crypto/ssh/certs_test.go b/vendor/golang.org/x/crypto/ssh/certs_test.go deleted file mode 100644 index 0200531f4c..0000000000 --- a/vendor/golang.org/x/crypto/ssh/certs_test.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "bytes" - "crypto/rand" - "reflect" - "testing" - "time" -) - -// Cert generated by ssh-keygen 6.0p1 Debian-4. -// % ssh-keygen -s ca-key -I test user-key -const exampleSSHCert = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgb1srW/W3ZDjYAO45xLYAwzHBDLsJ4Ux6ICFIkTjb1LEAAAADAQABAAAAYQCkoR51poH0wE8w72cqSB8Sszx+vAhzcMdCO0wqHTj7UNENHWEXGrU0E0UQekD7U+yhkhtoyjbPOVIP7hNa6aRk/ezdh/iUnCIt4Jt1v3Z1h1P+hA4QuYFMHNB+rmjPwAcAAAAAAAAAAAAAAAEAAAAEdGVzdAAAAAAAAAAAAAAAAP//////////AAAAAAAAAIIAAAAVcGVybWl0LVgxMS1mb3J3YXJkaW5nAAAAAAAAABdwZXJtaXQtYWdlbnQtZm9yd2FyZGluZwAAAAAAAAAWcGVybWl0LXBvcnQtZm9yd2FyZGluZwAAAAAAAAAKcGVybWl0LXB0eQAAAAAAAAAOcGVybWl0LXVzZXItcmMAAAAAAAAAAAAAAHcAAAAHc3NoLXJzYQAAAAMBAAEAAABhANFS2kaktpSGc+CcmEKPyw9mJC4nZKxHKTgLVZeaGbFZOvJTNzBspQHdy7Q1uKSfktxpgjZnksiu/tFF9ngyY2KFoc+U88ya95IZUycBGCUbBQ8+bhDtw/icdDGQD5WnUwAAAG8AAAAHc3NoLXJzYQAAAGC8Y9Z2LQKhIhxf52773XaWrXdxP0t3GBVo4A10vUWiYoAGepr6rQIoGGXFxT4B9Gp+nEBJjOwKDXPrAevow0T9ca8gZN+0ykbhSrXLE5Ao48rqr3zP4O1/9P7e6gp0gw8=` - -func TestParseCert(t *testing.T) { - authKeyBytes := []byte(exampleSSHCert) - - key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes) - if err != nil { - t.Fatalf("ParseAuthorizedKey: %v", err) - } - if len(rest) > 0 { - t.Errorf("rest: got %q, want empty", rest) - } - - if _, ok := key.(*Certificate); !ok { - t.Fatalf("got %v (%T), want *Certificate", key, key) - } - - marshaled := MarshalAuthorizedKey(key) - // Before comparison, remove the trailing newline that - // MarshalAuthorizedKey adds. - marshaled = marshaled[:len(marshaled)-1] - if !bytes.Equal(authKeyBytes, marshaled) { - t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes) - } -} - -// Cert generated by ssh-keygen OpenSSH_6.8p1 OS X 10.10.3 -// % ssh-keygen -s ca -I testcert -O source-address=192.168.1.0/24 -O force-command=/bin/sleep user.pub -// user.pub key: ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMN -// Critical Options: -// force-command /bin/sleep -// source-address 192.168.1.0/24 -// Extensions: -// permit-X11-forwarding -// permit-agent-forwarding -// permit-port-forwarding -// permit-pty -// permit-user-rc -const exampleSSHCertWithOptions = `ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgDyysCJY0XrO1n03EeRRoITnTPdjENFmWDs9X58PP3VUAAAADAQABAAABAQDACh1rt2DXfV3hk6fszSQcQ/rueMId0kVD9U7nl8cfEnFxqOCrNT92g4laQIGl2mn8lsGZfTLg8ksHq3gkvgO3oo/0wHy4v32JeBOHTsN5AL4gfHNEhWeWb50ev47hnTsRIt9P4dxogeUo/hTu7j9+s9lLpEQXCvq6xocXQt0j8MV9qZBBXFLXVT3cWIkSqOdwt/5ZBg+1GSrc7WfCXVWgTk4a20uPMuJPxU4RQwZW6X3+O8Pqo8C3cW0OzZRFP6gUYUKUsTI5WntlS+LAxgw1mZNsozFGdbiOPRnEryE3SRldh9vjDR3tin1fGpA5P7+CEB/bqaXtG3V+F2OkqaMNAAAAAAAAAAAAAAABAAAACHRlc3RjZXJ0AAAAAAAAAAAAAAAA//////////8AAABLAAAADWZvcmNlLWNvbW1hbmQAAAAOAAAACi9iaW4vc2xlZXAAAAAOc291cmNlLWFkZHJlc3MAAAASAAAADjE5Mi4xNjguMS4wLzI0AAAAggAAABVwZXJtaXQtWDExLWZvcndhcmRpbmcAAAAAAAAAF3Blcm1pdC1hZ2VudC1mb3J3YXJkaW5nAAAAAAAAABZwZXJtaXQtcG9ydC1mb3J3YXJkaW5nAAAAAAAAAApwZXJtaXQtcHR5AAAAAAAAAA5wZXJtaXQtdXNlci1yYwAAAAAAAAAAAAABFwAAAAdzc2gtcnNhAAAAAwEAAQAAAQEAwU+c5ui5A8+J/CFpjW8wCa52bEODA808WWQDCSuTG/eMXNf59v9Y8Pk0F1E9dGCosSNyVcB/hacUrc6He+i97+HJCyKavBsE6GDxrjRyxYqAlfcOXi/IVmaUGiO8OQ39d4GHrjToInKvExSUeleQyH4Y4/e27T/pILAqPFL3fyrvMLT5qU9QyIt6zIpa7GBP5+urouNavMprV3zsfIqNBbWypinOQAw823a5wN+zwXnhZrgQiHZ/USG09Y6k98y1dTVz8YHlQVR4D3lpTAsKDKJ5hCH9WU4fdf+lU8OyNGaJ/vz0XNqxcToe1l4numLTnaoSuH89pHryjqurB7lJKwAAAQ8AAAAHc3NoLXJzYQAAAQCaHvUIoPL1zWUHIXLvu96/HU1s/i4CAW2IIEuGgxCUCiFj6vyTyYtgxQxcmbfZf6eaITlS6XJZa7Qq4iaFZh75C1DXTX8labXhRSD4E2t//AIP9MC1rtQC5xo6FmbQ+BoKcDskr+mNACcbRSxs3IL3bwCfWDnIw2WbVox9ZdcthJKk4UoCW4ix4QwdHw7zlddlz++fGEEVhmTbll1SUkycGApPFBsAYRTMupUJcYPIeReBI/m8XfkoMk99bV8ZJQTAd7OekHY2/48Ff53jLmyDjP7kNw1F8OaPtkFs6dGJXta4krmaekPy87j+35In5hFj7yoOqvSbmYUkeX70/GGQ` - -func TestParseCertWithOptions(t *testing.T) { - opts := map[string]string{ - "source-address": "192.168.1.0/24", - "force-command": "/bin/sleep", - } - exts := map[string]string{ - "permit-X11-forwarding": "", - "permit-agent-forwarding": "", - "permit-port-forwarding": "", - "permit-pty": "", - "permit-user-rc": "", - } - authKeyBytes := []byte(exampleSSHCertWithOptions) - - key, _, _, rest, err := ParseAuthorizedKey(authKeyBytes) - if err != nil { - t.Fatalf("ParseAuthorizedKey: %v", err) - } - if len(rest) > 0 { - t.Errorf("rest: got %q, want empty", rest) - } - cert, ok := key.(*Certificate) - if !ok { - t.Fatalf("got %v (%T), want *Certificate", key, key) - } - if !reflect.DeepEqual(cert.CriticalOptions, opts) { - t.Errorf("unexpected critical options - got %v, want %v", cert.CriticalOptions, opts) - } - if !reflect.DeepEqual(cert.Extensions, exts) { - t.Errorf("unexpected Extensions - got %v, want %v", cert.Extensions, exts) - } - marshaled := MarshalAuthorizedKey(key) - // Before comparison, remove the trailing newline that - // MarshalAuthorizedKey adds. - marshaled = marshaled[:len(marshaled)-1] - if !bytes.Equal(authKeyBytes, marshaled) { - t.Errorf("marshaled certificate does not match original: got %q, want %q", marshaled, authKeyBytes) - } -} - -func TestValidateCert(t *testing.T) { - key, _, _, _, err := ParseAuthorizedKey([]byte(exampleSSHCert)) - if err != nil { - t.Fatalf("ParseAuthorizedKey: %v", err) - } - validCert, ok := key.(*Certificate) - if !ok { - t.Fatalf("got %v (%T), want *Certificate", key, key) - } - checker := CertChecker{} - checker.IsUserAuthority = func(k PublicKey) bool { - return bytes.Equal(k.Marshal(), validCert.SignatureKey.Marshal()) - } - - if err := checker.CheckCert("user", validCert); err != nil { - t.Errorf("Unable to validate certificate: %v", err) - } - invalidCert := &Certificate{ - Key: testPublicKeys["rsa"], - SignatureKey: testPublicKeys["ecdsa"], - ValidBefore: CertTimeInfinity, - Signature: &Signature{}, - } - if err := checker.CheckCert("user", invalidCert); err == nil { - t.Error("Invalid cert signature passed validation") - } -} - -func TestValidateCertTime(t *testing.T) { - cert := Certificate{ - ValidPrincipals: []string{"user"}, - Key: testPublicKeys["rsa"], - ValidAfter: 50, - ValidBefore: 100, - } - - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - - for ts, ok := range map[int64]bool{ - 25: false, - 50: true, - 99: true, - 100: false, - 125: false, - } { - checker := CertChecker{ - Clock: func() time.Time { return time.Unix(ts, 0) }, - } - checker.IsUserAuthority = func(k PublicKey) bool { - return bytes.Equal(k.Marshal(), - testPublicKeys["ecdsa"].Marshal()) - } - - if v := checker.CheckCert("user", &cert); (v == nil) != ok { - t.Errorf("Authenticate(%d): %v", ts, v) - } - } -} - -// TODO(hanwen): tests for -// -// host keys: -// * fallbacks - -func TestHostKeyCert(t *testing.T) { - cert := &Certificate{ - ValidPrincipals: []string{"hostname", "hostname.domain", "otherhost"}, - Key: testPublicKeys["rsa"], - ValidBefore: CertTimeInfinity, - CertType: HostCert, - } - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - - checker := &CertChecker{ - IsHostAuthority: func(p PublicKey, addr string) bool { - return addr == "hostname:22" && bytes.Equal(testPublicKeys["ecdsa"].Marshal(), p.Marshal()) - }, - } - - certSigner, err := NewCertSigner(cert, testSigners["rsa"]) - if err != nil { - t.Errorf("NewCertSigner: %v", err) - } - - for _, test := range []struct { - addr string - succeed bool - }{ - {addr: "hostname:22", succeed: true}, - {addr: "otherhost:22", succeed: false}, // The certificate is valid for 'otherhost' as hostname, but we only recognize the authority of the signer for the address 'hostname:22' - {addr: "lasthost:22", succeed: false}, - } { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - errc := make(chan error) - - go func() { - conf := ServerConfig{ - NoClientAuth: true, - } - conf.AddHostKey(certSigner) - _, _, _, err := NewServerConn(c1, &conf) - errc <- err - }() - - config := &ClientConfig{ - User: "user", - HostKeyCallback: checker.CheckHostKey, - } - _, _, _, err = NewClientConn(c2, test.addr, config) - - if (err == nil) != test.succeed { - t.Fatalf("NewClientConn(%q): %v", test.addr, err) - } - - err = <-errc - if (err == nil) != test.succeed { - t.Fatalf("NewServerConn(%q): %v", test.addr, err) - } - } -} diff --git a/vendor/golang.org/x/crypto/ssh/channel.go b/vendor/golang.org/x/crypto/ssh/channel.go index 195530ea0d..c0834c00df 100644 --- a/vendor/golang.org/x/crypto/ssh/channel.go +++ b/vendor/golang.org/x/crypto/ssh/channel.go @@ -205,32 +205,32 @@ type channel struct { // writePacket sends a packet. If the packet is a channel close, it updates // sentClose. This method takes the lock c.writeMu. -func (c *channel) writePacket(packet []byte) error { - c.writeMu.Lock() - if c.sentClose { - c.writeMu.Unlock() +func (ch *channel) writePacket(packet []byte) error { + ch.writeMu.Lock() + if ch.sentClose { + ch.writeMu.Unlock() return io.EOF } - c.sentClose = (packet[0] == msgChannelClose) - err := c.mux.conn.writePacket(packet) - c.writeMu.Unlock() + ch.sentClose = (packet[0] == msgChannelClose) + err := ch.mux.conn.writePacket(packet) + ch.writeMu.Unlock() return err } -func (c *channel) sendMessage(msg interface{}) error { +func (ch *channel) sendMessage(msg interface{}) error { if debugMux { - log.Printf("send(%d): %#v", c.mux.chanList.offset, msg) + log.Printf("send(%d): %#v", ch.mux.chanList.offset, msg) } p := Marshal(msg) - binary.BigEndian.PutUint32(p[1:], c.remoteId) - return c.writePacket(p) + binary.BigEndian.PutUint32(p[1:], ch.remoteId) + return ch.writePacket(p) } // WriteExtended writes data to a specific extended stream. These streams are // used, for example, for stderr. -func (c *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err error) { - if c.sentEOF { +func (ch *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err error) { + if ch.sentEOF { return 0, io.EOF } // 1 byte message type, 4 bytes remoteId, 4 bytes data length @@ -241,16 +241,16 @@ func (c *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err er opCode = msgChannelExtendedData } - c.writeMu.Lock() - packet := c.packetPool[extendedCode] + ch.writeMu.Lock() + packet := ch.packetPool[extendedCode] // We don't remove the buffer from packetPool, so // WriteExtended calls from different goroutines will be // flagged as errors by the race detector. - c.writeMu.Unlock() + ch.writeMu.Unlock() for len(data) > 0 { - space := min(c.maxRemotePayload, len(data)) - if space, err = c.remoteWin.reserve(space); err != nil { + space := min(ch.maxRemotePayload, len(data)) + if space, err = ch.remoteWin.reserve(space); err != nil { return n, err } if want := headerLength + space; uint32(cap(packet)) < want { @@ -262,13 +262,13 @@ func (c *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err er todo := data[:space] packet[0] = opCode - binary.BigEndian.PutUint32(packet[1:], c.remoteId) + binary.BigEndian.PutUint32(packet[1:], ch.remoteId) if extendedCode > 0 { binary.BigEndian.PutUint32(packet[5:], uint32(extendedCode)) } binary.BigEndian.PutUint32(packet[headerLength-4:], uint32(len(todo))) copy(packet[headerLength:], todo) - if err = c.writePacket(packet); err != nil { + if err = ch.writePacket(packet); err != nil { return n, err } @@ -276,14 +276,14 @@ func (c *channel) WriteExtended(data []byte, extendedCode uint32) (n int, err er data = data[len(todo):] } - c.writeMu.Lock() - c.packetPool[extendedCode] = packet - c.writeMu.Unlock() + ch.writeMu.Lock() + ch.packetPool[extendedCode] = packet + ch.writeMu.Unlock() return n, err } -func (c *channel) handleData(packet []byte) error { +func (ch *channel) handleData(packet []byte) error { headerLen := 9 isExtendedData := packet[0] == msgChannelExtendedData if isExtendedData { @@ -303,7 +303,7 @@ func (c *channel) handleData(packet []byte) error { if length == 0 { return nil } - if length > c.maxIncomingPayload { + if length > ch.maxIncomingPayload { // TODO(hanwen): should send Disconnect? return errors.New("ssh: incoming packet exceeds maximum payload size") } @@ -313,21 +313,21 @@ func (c *channel) handleData(packet []byte) error { return errors.New("ssh: wrong packet length") } - c.windowMu.Lock() - if c.myWindow < length { - c.windowMu.Unlock() + ch.windowMu.Lock() + if ch.myWindow < length { + ch.windowMu.Unlock() // TODO(hanwen): should send Disconnect with reason? return errors.New("ssh: remote side wrote too much") } - c.myWindow -= length - c.windowMu.Unlock() + ch.myWindow -= length + ch.windowMu.Unlock() if extended == 1 { - c.extPending.write(data) + ch.extPending.write(data) } else if extended > 0 { // discard other extended data. } else { - c.pending.write(data) + ch.pending.write(data) } return nil } @@ -384,31 +384,31 @@ func (c *channel) close() { // responseMessageReceived is called when a success or failure message is // received on a channel to check that such a message is reasonable for the // given channel. -func (c *channel) responseMessageReceived() error { - if c.direction == channelInbound { +func (ch *channel) responseMessageReceived() error { + if ch.direction == channelInbound { return errors.New("ssh: channel response message received on inbound channel") } - if c.decided { + if ch.decided { return errors.New("ssh: duplicate response received for channel") } - c.decided = true + ch.decided = true return nil } -func (c *channel) handlePacket(packet []byte) error { +func (ch *channel) handlePacket(packet []byte) error { switch packet[0] { case msgChannelData, msgChannelExtendedData: - return c.handleData(packet) + return ch.handleData(packet) case msgChannelClose: - c.sendMessage(channelCloseMsg{PeersId: c.remoteId}) - c.mux.chanList.remove(c.localId) - c.close() + ch.sendMessage(channelCloseMsg{PeersID: ch.remoteId}) + ch.mux.chanList.remove(ch.localId) + ch.close() return nil case msgChannelEOF: // RFC 4254 is mute on how EOF affects dataExt messages but // it is logical to signal EOF at the same time. - c.extPending.eof() - c.pending.eof() + ch.extPending.eof() + ch.pending.eof() return nil } @@ -419,24 +419,24 @@ func (c *channel) handlePacket(packet []byte) error { switch msg := decoded.(type) { case *channelOpenFailureMsg: - if err := c.responseMessageReceived(); err != nil { + if err := ch.responseMessageReceived(); err != nil { return err } - c.mux.chanList.remove(msg.PeersId) - c.msg <- msg + ch.mux.chanList.remove(msg.PeersID) + ch.msg <- msg case *channelOpenConfirmMsg: - if err := c.responseMessageReceived(); err != nil { + if err := ch.responseMessageReceived(); err != nil { return err } if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 { return fmt.Errorf("ssh: invalid MaxPacketSize %d from peer", msg.MaxPacketSize) } - c.remoteId = msg.MyId - c.maxRemotePayload = msg.MaxPacketSize - c.remoteWin.add(msg.MyWindow) - c.msg <- msg + ch.remoteId = msg.MyID + ch.maxRemotePayload = msg.MaxPacketSize + ch.remoteWin.add(msg.MyWindow) + ch.msg <- msg case *windowAdjustMsg: - if !c.remoteWin.add(msg.AdditionalBytes) { + if !ch.remoteWin.add(msg.AdditionalBytes) { return fmt.Errorf("ssh: invalid window update for %d bytes", msg.AdditionalBytes) } case *channelRequestMsg: @@ -444,12 +444,12 @@ func (c *channel) handlePacket(packet []byte) error { Type: msg.Request, WantReply: msg.WantReply, Payload: msg.RequestSpecificData, - ch: c, + ch: ch, } - c.incomingRequests <- &req + ch.incomingRequests <- &req default: - c.msg <- msg + ch.msg <- msg } return nil } @@ -488,23 +488,23 @@ func (e *extChannel) Read(data []byte) (n int, err error) { return e.ch.ReadExtended(data, e.code) } -func (c *channel) Accept() (Channel, <-chan *Request, error) { - if c.decided { +func (ch *channel) Accept() (Channel, <-chan *Request, error) { + if ch.decided { return nil, nil, errDecidedAlready } - c.maxIncomingPayload = channelMaxPacket + ch.maxIncomingPayload = channelMaxPacket confirm := channelOpenConfirmMsg{ - PeersId: c.remoteId, - MyId: c.localId, - MyWindow: c.myWindow, - MaxPacketSize: c.maxIncomingPayload, + PeersID: ch.remoteId, + MyID: ch.localId, + MyWindow: ch.myWindow, + MaxPacketSize: ch.maxIncomingPayload, } - c.decided = true - if err := c.sendMessage(confirm); err != nil { + ch.decided = true + if err := ch.sendMessage(confirm); err != nil { return nil, nil, err } - return c, c.incomingRequests, nil + return ch, ch.incomingRequests, nil } func (ch *channel) Reject(reason RejectionReason, message string) error { @@ -512,7 +512,7 @@ func (ch *channel) Reject(reason RejectionReason, message string) error { return errDecidedAlready } reject := channelOpenFailureMsg{ - PeersId: ch.remoteId, + PeersID: ch.remoteId, Reason: reason, Message: message, Language: "en", @@ -541,7 +541,7 @@ func (ch *channel) CloseWrite() error { } ch.sentEOF = true return ch.sendMessage(channelEOFMsg{ - PeersId: ch.remoteId}) + PeersID: ch.remoteId}) } func (ch *channel) Close() error { @@ -550,7 +550,7 @@ func (ch *channel) Close() error { } return ch.sendMessage(channelCloseMsg{ - PeersId: ch.remoteId}) + PeersID: ch.remoteId}) } // Extended returns an io.ReadWriter that sends and receives data on the given, @@ -577,7 +577,7 @@ func (ch *channel) SendRequest(name string, wantReply bool, payload []byte) (boo } msg := channelRequestMsg{ - PeersId: ch.remoteId, + PeersID: ch.remoteId, Request: name, WantReply: wantReply, RequestSpecificData: payload, @@ -614,11 +614,11 @@ func (ch *channel) ackRequest(ok bool) error { var msg interface{} if !ok { msg = channelRequestFailureMsg{ - PeersId: ch.remoteId, + PeersID: ch.remoteId, } } else { msg = channelRequestSuccessMsg{ - PeersId: ch.remoteId, + PeersID: ch.remoteId, } } return ch.sendMessage(msg) diff --git a/vendor/golang.org/x/crypto/ssh/cipher.go b/vendor/golang.org/x/crypto/ssh/cipher.go index aed2b1f017..67b0126105 100644 --- a/vendor/golang.org/x/crypto/ssh/cipher.go +++ b/vendor/golang.org/x/crypto/ssh/cipher.go @@ -16,6 +16,10 @@ import ( "hash" "io" "io/ioutil" + "math/bits" + + "golang.org/x/crypto/internal/chacha20" + "golang.org/x/crypto/poly1305" ) const ( @@ -53,78 +57,78 @@ func newRC4(key, iv []byte) (cipher.Stream, error) { return rc4.NewCipher(key) } -type streamCipherMode struct { - keySize int - ivSize int - skip int - createFunc func(key, iv []byte) (cipher.Stream, error) +type cipherMode struct { + keySize int + ivSize int + create func(key, iv []byte, macKey []byte, algs directionAlgorithms) (packetCipher, error) } -func (c *streamCipherMode) createStream(key, iv []byte) (cipher.Stream, error) { - if len(key) < c.keySize { - panic("ssh: key length too small for cipher") - } - if len(iv) < c.ivSize { - panic("ssh: iv too small for cipher") - } - - stream, err := c.createFunc(key[:c.keySize], iv[:c.ivSize]) - if err != nil { - return nil, err - } +func streamCipherMode(skip int, createFunc func(key, iv []byte) (cipher.Stream, error)) func(key, iv []byte, macKey []byte, algs directionAlgorithms) (packetCipher, error) { + return func(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { + stream, err := createFunc(key, iv) + if err != nil { + return nil, err + } - var streamDump []byte - if c.skip > 0 { - streamDump = make([]byte, 512) - } + var streamDump []byte + if skip > 0 { + streamDump = make([]byte, 512) + } - for remainingToDump := c.skip; remainingToDump > 0; { - dumpThisTime := remainingToDump - if dumpThisTime > len(streamDump) { - dumpThisTime = len(streamDump) + for remainingToDump := skip; remainingToDump > 0; { + dumpThisTime := remainingToDump + if dumpThisTime > len(streamDump) { + dumpThisTime = len(streamDump) + } + stream.XORKeyStream(streamDump[:dumpThisTime], streamDump[:dumpThisTime]) + remainingToDump -= dumpThisTime } - stream.XORKeyStream(streamDump[:dumpThisTime], streamDump[:dumpThisTime]) - remainingToDump -= dumpThisTime - } - return stream, nil + mac := macModes[algs.MAC].new(macKey) + return &streamPacketCipher{ + mac: mac, + etm: macModes[algs.MAC].etm, + macResult: make([]byte, mac.Size()), + cipher: stream, + }, nil + } } // cipherModes documents properties of supported ciphers. Ciphers not included // are not supported and will not be negotiated, even if explicitly requested in // ClientConfig.Crypto.Ciphers. -var cipherModes = map[string]*streamCipherMode{ +var cipherModes = map[string]*cipherMode{ // Ciphers from RFC4344, which introduced many CTR-based ciphers. Algorithms // are defined in the order specified in the RFC. - "aes128-ctr": {16, aes.BlockSize, 0, newAESCTR}, - "aes192-ctr": {24, aes.BlockSize, 0, newAESCTR}, - "aes256-ctr": {32, aes.BlockSize, 0, newAESCTR}, + "aes128-ctr": {16, aes.BlockSize, streamCipherMode(0, newAESCTR)}, + "aes192-ctr": {24, aes.BlockSize, streamCipherMode(0, newAESCTR)}, + "aes256-ctr": {32, aes.BlockSize, streamCipherMode(0, newAESCTR)}, // Ciphers from RFC4345, which introduces security-improved arcfour ciphers. // They are defined in the order specified in the RFC. - "arcfour128": {16, 0, 1536, newRC4}, - "arcfour256": {32, 0, 1536, newRC4}, + "arcfour128": {16, 0, streamCipherMode(1536, newRC4)}, + "arcfour256": {32, 0, streamCipherMode(1536, newRC4)}, // Cipher defined in RFC 4253, which describes SSH Transport Layer Protocol. // Note that this cipher is not safe, as stated in RFC 4253: "Arcfour (and // RC4) has problems with weak keys, and should be used with caution." // RFC4345 introduces improved versions of Arcfour. - "arcfour": {16, 0, 0, newRC4}, + "arcfour": {16, 0, streamCipherMode(0, newRC4)}, - // AES-GCM is not a stream cipher, so it is constructed with a - // special case. If we add any more non-stream ciphers, we - // should invest a cleaner way to do this. - gcmCipherID: {16, 12, 0, nil}, + // AEAD ciphers + gcmCipherID: {16, 12, newGCMCipher}, + chacha20Poly1305ID: {64, 0, newChaCha20Cipher}, // CBC mode is insecure and so is not included in the default config. // (See http://www.isg.rhul.ac.uk/~kp/SandPfinal.pdf). If absolutely // needed, it's possible to specify a custom Config to enable it. // You should expect that an active attacker can recover plaintext if // you do. - aes128cbcID: {16, aes.BlockSize, 0, nil}, + aes128cbcID: {16, aes.BlockSize, newAESCBCCipher}, - // 3des-cbc is insecure and is disabled by default. - tripledescbcID: {24, des.BlockSize, 0, nil}, + // 3des-cbc is insecure and is not included in the default + // config. + tripledescbcID: {24, des.BlockSize, newTripleDESCBCCipher}, } // prefixLen is the length of the packet prefix that contains the packet length @@ -304,7 +308,7 @@ type gcmCipher struct { buf []byte } -func newGCMCipher(iv, key []byte) (packetCipher, error) { +func newGCMCipher(key, iv, unusedMacKey []byte, unusedAlgs directionAlgorithms) (packetCipher, error) { c, err := aes.NewCipher(key) if err != nil { return nil, err @@ -372,7 +376,7 @@ func (c *gcmCipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { } length := binary.BigEndian.Uint32(c.prefix[:]) if length > maxPacket { - return nil, errors.New("ssh: max packet length exceeded.") + return nil, errors.New("ssh: max packet length exceeded") } if cap(c.buf) < int(length+gcmTagSize) { @@ -422,7 +426,7 @@ type cbcCipher struct { oracleCamouflage uint32 } -func newCBCCipher(c cipher.Block, iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { +func newCBCCipher(c cipher.Block, key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { cbc := &cbcCipher{ mac: macModes[algs.MAC].new(macKey), decrypter: cipher.NewCBCDecrypter(c, iv), @@ -436,13 +440,13 @@ func newCBCCipher(c cipher.Block, iv, key, macKey []byte, algs directionAlgorith return cbc, nil } -func newAESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { +func newAESCBCCipher(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { c, err := aes.NewCipher(key) if err != nil { return nil, err } - cbc, err := newCBCCipher(c, iv, key, macKey, algs) + cbc, err := newCBCCipher(c, key, iv, macKey, algs) if err != nil { return nil, err } @@ -450,13 +454,13 @@ func newAESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCi return cbc, nil } -func newTripleDESCBCCipher(iv, key, macKey []byte, algs directionAlgorithms) (packetCipher, error) { +func newTripleDESCBCCipher(key, iv, macKey []byte, algs directionAlgorithms) (packetCipher, error) { c, err := des.NewTripleDESCipher(key) if err != nil { return nil, err } - cbc, err := newCBCCipher(c, iv, key, macKey, algs) + cbc, err := newCBCCipher(c, key, iv, macKey, algs) if err != nil { return nil, err } @@ -548,11 +552,11 @@ func (c *cbcCipher) readPacketLeaky(seqNum uint32, r io.Reader) ([]byte, error) c.packetData = c.packetData[:entirePacketSize] } - if n, err := io.ReadFull(r, c.packetData[firstBlockLength:]); err != nil { + n, err := io.ReadFull(r, c.packetData[firstBlockLength:]) + if err != nil { return nil, err - } else { - c.oracleCamouflage -= uint32(n) } + c.oracleCamouflage -= uint32(n) remainingCrypted := c.packetData[firstBlockLength:macStart] c.decrypter.CryptBlocks(remainingCrypted, remainingCrypted) @@ -627,3 +631,140 @@ func (c *cbcCipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, pack return nil } + +const chacha20Poly1305ID = "chacha20-poly1305@openssh.com" + +// chacha20Poly1305Cipher implements the chacha20-poly1305@openssh.com +// AEAD, which is described here: +// +// https://tools.ietf.org/html/draft-josefsson-ssh-chacha20-poly1305-openssh-00 +// +// the methods here also implement padding, which RFC4253 Section 6 +// also requires of stream ciphers. +type chacha20Poly1305Cipher struct { + lengthKey [8]uint32 + contentKey [8]uint32 + buf []byte +} + +func newChaCha20Cipher(key, unusedIV, unusedMACKey []byte, unusedAlgs directionAlgorithms) (packetCipher, error) { + if len(key) != 64 { + panic(len(key)) + } + + c := &chacha20Poly1305Cipher{ + buf: make([]byte, 256), + } + + for i := range c.contentKey { + c.contentKey[i] = binary.LittleEndian.Uint32(key[i*4 : (i+1)*4]) + } + for i := range c.lengthKey { + c.lengthKey[i] = binary.LittleEndian.Uint32(key[(i+8)*4 : (i+9)*4]) + } + return c, nil +} + +func (c *chacha20Poly1305Cipher) readPacket(seqNum uint32, r io.Reader) ([]byte, error) { + nonce := [3]uint32{0, 0, bits.ReverseBytes32(seqNum)} + s := chacha20.New(c.contentKey, nonce) + var polyKey [32]byte + s.XORKeyStream(polyKey[:], polyKey[:]) + s.Advance() // skip next 32 bytes + + encryptedLength := c.buf[:4] + if _, err := io.ReadFull(r, encryptedLength); err != nil { + return nil, err + } + + var lenBytes [4]byte + chacha20.New(c.lengthKey, nonce).XORKeyStream(lenBytes[:], encryptedLength) + + length := binary.BigEndian.Uint32(lenBytes[:]) + if length > maxPacket { + return nil, errors.New("ssh: invalid packet length, packet too large") + } + + contentEnd := 4 + length + packetEnd := contentEnd + poly1305.TagSize + if uint32(cap(c.buf)) < packetEnd { + c.buf = make([]byte, packetEnd) + copy(c.buf[:], encryptedLength) + } else { + c.buf = c.buf[:packetEnd] + } + + if _, err := io.ReadFull(r, c.buf[4:packetEnd]); err != nil { + return nil, err + } + + var mac [poly1305.TagSize]byte + copy(mac[:], c.buf[contentEnd:packetEnd]) + if !poly1305.Verify(&mac, c.buf[:contentEnd], &polyKey) { + return nil, errors.New("ssh: MAC failure") + } + + plain := c.buf[4:contentEnd] + s.XORKeyStream(plain, plain) + + padding := plain[0] + if padding < 4 { + // padding is a byte, so it automatically satisfies + // the maximum size, which is 255. + return nil, fmt.Errorf("ssh: illegal padding %d", padding) + } + + if int(padding)+1 >= len(plain) { + return nil, fmt.Errorf("ssh: padding %d too large", padding) + } + + plain = plain[1 : len(plain)-int(padding)] + + return plain, nil +} + +func (c *chacha20Poly1305Cipher) writePacket(seqNum uint32, w io.Writer, rand io.Reader, payload []byte) error { + nonce := [3]uint32{0, 0, bits.ReverseBytes32(seqNum)} + s := chacha20.New(c.contentKey, nonce) + var polyKey [32]byte + s.XORKeyStream(polyKey[:], polyKey[:]) + s.Advance() // skip next 32 bytes + + // There is no blocksize, so fall back to multiple of 8 byte + // padding, as described in RFC 4253, Sec 6. + const packetSizeMultiple = 8 + + padding := packetSizeMultiple - (1+len(payload))%packetSizeMultiple + if padding < 4 { + padding += packetSizeMultiple + } + + // size (4 bytes), padding (1), payload, padding, tag. + totalLength := 4 + 1 + len(payload) + padding + poly1305.TagSize + if cap(c.buf) < totalLength { + c.buf = make([]byte, totalLength) + } else { + c.buf = c.buf[:totalLength] + } + + binary.BigEndian.PutUint32(c.buf, uint32(1+len(payload)+padding)) + chacha20.New(c.lengthKey, nonce).XORKeyStream(c.buf, c.buf[:4]) + c.buf[4] = byte(padding) + copy(c.buf[5:], payload) + packetEnd := 5 + len(payload) + padding + if _, err := io.ReadFull(rand, c.buf[5+len(payload):packetEnd]); err != nil { + return err + } + + s.XORKeyStream(c.buf[4:], c.buf[4:packetEnd]) + + var mac [poly1305.TagSize]byte + poly1305.Sum(&mac, c.buf[:packetEnd], &polyKey) + + copy(c.buf[packetEnd:], mac[:]) + + if _, err := w.Write(c.buf); err != nil { + return err + } + return nil +} diff --git a/vendor/golang.org/x/crypto/ssh/cipher_test.go b/vendor/golang.org/x/crypto/ssh/cipher_test.go deleted file mode 100644 index 5cfa17a62d..0000000000 --- a/vendor/golang.org/x/crypto/ssh/cipher_test.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "crypto" - "crypto/aes" - "crypto/rand" - "testing" -) - -func TestDefaultCiphersExist(t *testing.T) { - for _, cipherAlgo := range supportedCiphers { - if _, ok := cipherModes[cipherAlgo]; !ok { - t.Errorf("default cipher %q is unknown", cipherAlgo) - } - } -} - -func TestPacketCiphers(t *testing.T) { - // Still test aes128cbc cipher although it's commented out. - cipherModes[aes128cbcID] = &streamCipherMode{16, aes.BlockSize, 0, nil} - defer delete(cipherModes, aes128cbcID) - - for cipher := range cipherModes { - for mac := range macModes { - kr := &kexResult{Hash: crypto.SHA1} - algs := directionAlgorithms{ - Cipher: cipher, - MAC: mac, - Compression: "none", - } - client, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Errorf("newPacketCipher(client, %q, %q): %v", cipher, mac, err) - continue - } - server, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Errorf("newPacketCipher(client, %q, %q): %v", cipher, mac, err) - continue - } - - want := "bla bla" - input := []byte(want) - buf := &bytes.Buffer{} - if err := client.writePacket(0, buf, rand.Reader, input); err != nil { - t.Errorf("writePacket(%q, %q): %v", cipher, mac, err) - continue - } - - packet, err := server.readPacket(0, buf) - if err != nil { - t.Errorf("readPacket(%q, %q): %v", cipher, mac, err) - continue - } - - if string(packet) != want { - t.Errorf("roundtrip(%q, %q): got %q, want %q", cipher, mac, packet, want) - } - } - } -} - -func TestCBCOracleCounterMeasure(t *testing.T) { - cipherModes[aes128cbcID] = &streamCipherMode{16, aes.BlockSize, 0, nil} - defer delete(cipherModes, aes128cbcID) - - kr := &kexResult{Hash: crypto.SHA1} - algs := directionAlgorithms{ - Cipher: aes128cbcID, - MAC: "hmac-sha1", - Compression: "none", - } - client, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Fatalf("newPacketCipher(client): %v", err) - } - - want := "bla bla" - input := []byte(want) - buf := &bytes.Buffer{} - if err := client.writePacket(0, buf, rand.Reader, input); err != nil { - t.Errorf("writePacket: %v", err) - } - - packetSize := buf.Len() - buf.Write(make([]byte, 2*maxPacket)) - - // We corrupt each byte, but this usually will only test the - // 'packet too large' or 'MAC failure' cases. - lastRead := -1 - for i := 0; i < packetSize; i++ { - server, err := newPacketCipher(clientKeys, algs, kr) - if err != nil { - t.Fatalf("newPacketCipher(client): %v", err) - } - - fresh := &bytes.Buffer{} - fresh.Write(buf.Bytes()) - fresh.Bytes()[i] ^= 0x01 - - before := fresh.Len() - _, err = server.readPacket(0, fresh) - if err == nil { - t.Errorf("corrupt byte %d: readPacket succeeded ", i) - continue - } - if _, ok := err.(cbcError); !ok { - t.Errorf("corrupt byte %d: got %v (%T), want cbcError", i, err, err) - continue - } - - after := fresh.Len() - bytesRead := before - after - if bytesRead < maxPacket { - t.Errorf("corrupt byte %d: read %d bytes, want more than %d", i, bytesRead, maxPacket) - continue - } - - if i > 0 && bytesRead != lastRead { - t.Errorf("corrupt byte %d: read %d bytes, want %d bytes read", i, bytesRead, lastRead) - } - lastRead = bytesRead - } -} diff --git a/vendor/golang.org/x/crypto/ssh/client.go b/vendor/golang.org/x/crypto/ssh/client.go index a7e3263bca..ae6ca775ee 100644 --- a/vendor/golang.org/x/crypto/ssh/client.go +++ b/vendor/golang.org/x/crypto/ssh/client.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "net" + "os" "sync" "time" ) @@ -18,6 +19,8 @@ import ( type Client struct { Conn + handleForwardsOnce sync.Once // guards calling (*Client).handleForwards + forwards forwardList // forwarded tcpip connections from the remote side mu sync.Mutex channelHandlers map[string]chan NewChannel @@ -59,8 +62,6 @@ func NewClient(c Conn, chans <-chan NewChannel, reqs <-chan *Request) *Client { conn.Wait() conn.forwards.closeAll() }() - go conn.forwards.handleChannels(conn.HandleChannelOpen("forwarded-tcpip")) - go conn.forwards.handleChannels(conn.HandleChannelOpen("forwarded-streamlocal@openssh.com")) return conn } @@ -187,6 +188,10 @@ func Dial(network, addr string, config *ClientConfig) (*Client, error) { // net.Conn underlying the the SSH connection. type HostKeyCallback func(hostname string, remote net.Addr, key PublicKey) error +// BannerCallback is the function type used for treat the banner sent by +// the server. A BannerCallback receives the message sent by the remote server. +type BannerCallback func(message string) error + // A ClientConfig structure is used to configure a Client. It must not be // modified after having been passed to an SSH function. type ClientConfig struct { @@ -209,6 +214,12 @@ type ClientConfig struct { // FixedHostKey can be used for simplistic host key checks. HostKeyCallback HostKeyCallback + // BannerCallback is called during the SSH dance to display a custom + // server's message. The client configuration can supply this callback to + // handle it as wished. The function BannerDisplayStderr can be used for + // simplistic display on Stderr. + BannerCallback BannerCallback + // ClientVersion contains the version identification string that will // be used for the connection. If empty, a reasonable default is used. ClientVersion string @@ -255,3 +266,13 @@ func FixedHostKey(key PublicKey) HostKeyCallback { hk := &fixedHostKey{key} return hk.check } + +// BannerDisplayStderr returns a function that can be used for +// ClientConfig.BannerCallback to display banners on os.Stderr. +func BannerDisplayStderr() BannerCallback { + return func(banner string) error { + _, err := os.Stderr.WriteString(banner) + + return err + } +} diff --git a/vendor/golang.org/x/crypto/ssh/client_auth.go b/vendor/golang.org/x/crypto/ssh/client_auth.go index 3acd8d4988..5f44b77403 100644 --- a/vendor/golang.org/x/crypto/ssh/client_auth.go +++ b/vendor/golang.org/x/crypto/ssh/client_auth.go @@ -11,6 +11,14 @@ import ( "io" ) +type authResult int + +const ( + authFailure authResult = iota + authPartialSuccess + authSuccess +) + // clientAuthenticate authenticates with the remote server. See RFC 4252. func (c *connection) clientAuthenticate(config *ClientConfig) error { // initiate user auth session @@ -37,11 +45,12 @@ func (c *connection) clientAuthenticate(config *ClientConfig) error { if err != nil { return err } - if ok { + if ok == authSuccess { // success return nil + } else if ok == authFailure { + tried[auth.method()] = true } - tried[auth.method()] = true if methods == nil { methods = lastMethods } @@ -82,7 +91,7 @@ type AuthMethod interface { // If authentication is not successful, a []string of alternative // method names is returned. If the slice is nil, it will be ignored // and the previous set of possible methods will be reused. - auth(session []byte, user string, p packetConn, rand io.Reader) (bool, []string, error) + auth(session []byte, user string, p packetConn, rand io.Reader) (authResult, []string, error) // method returns the RFC 4252 method name. method() string @@ -91,13 +100,13 @@ type AuthMethod interface { // "none" authentication, RFC 4252 section 5.2. type noneAuth int -func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { +func (n *noneAuth) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { if err := c.writePacket(Marshal(&userAuthRequestMsg{ User: user, Service: serviceSSH, Method: "none", })); err != nil { - return false, nil, err + return authFailure, nil, err } return handleAuthResponse(c) @@ -111,7 +120,7 @@ func (n *noneAuth) method() string { // a function call, e.g. by prompting the user. type passwordCallback func() (password string, err error) -func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { +func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { type passwordAuthMsg struct { User string `sshtype:"50"` Service string @@ -125,7 +134,7 @@ func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand // The program may only find out that the user doesn't have a password // when prompting. if err != nil { - return false, nil, err + return authFailure, nil, err } if err := c.writePacket(Marshal(&passwordAuthMsg{ @@ -135,7 +144,7 @@ func (cb passwordCallback) auth(session []byte, user string, c packetConn, rand Reply: false, Password: pw, })); err != nil { - return false, nil, err + return authFailure, nil, err } return handleAuthResponse(c) @@ -178,7 +187,7 @@ func (cb publicKeyCallback) method() string { return "publickey" } -func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { +func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { // Authentication is performed by sending an enquiry to test if a key is // acceptable to the remote. If the key is acceptable, the client will // attempt to authenticate with the valid key. If not the client will repeat @@ -186,13 +195,13 @@ func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand signers, err := cb() if err != nil { - return false, nil, err + return authFailure, nil, err } var methods []string for _, signer := range signers { ok, err := validateKey(signer.PublicKey(), user, c) if err != nil { - return false, nil, err + return authFailure, nil, err } if !ok { continue @@ -206,7 +215,7 @@ func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand Method: cb.method(), }, []byte(pub.Type()), pubKey)) if err != nil { - return false, nil, err + return authFailure, nil, err } // manually wrap the serialized signature in a string @@ -224,24 +233,24 @@ func (cb publicKeyCallback) auth(session []byte, user string, c packetConn, rand } p := Marshal(&msg) if err := c.writePacket(p); err != nil { - return false, nil, err + return authFailure, nil, err } - var success bool + var success authResult success, methods, err = handleAuthResponse(c) if err != nil { - return false, nil, err + return authFailure, nil, err } // If authentication succeeds or the list of available methods does not // contain the "publickey" method, do not attempt to authenticate with any // other keys. According to RFC 4252 Section 7, the latter can occur when // additional authentication methods are required. - if success || !containsMethod(methods, cb.method()) { + if success == authSuccess || !containsMethod(methods, cb.method()) { return success, methods, err } } - return false, methods, nil + return authFailure, methods, nil } func containsMethod(methods []string, method string) bool { @@ -283,7 +292,9 @@ func confirmKeyAck(key PublicKey, c packetConn) (bool, error) { } switch packet[0] { case msgUserAuthBanner: - // TODO(gpaul): add callback to present the banner to the user + if err := handleBannerResponse(c, packet); err != nil { + return false, err + } case msgUserAuthPubKeyOk: var msg userAuthPubKeyOkMsg if err := Unmarshal(packet, &msg); err != nil { @@ -316,30 +327,53 @@ func PublicKeysCallback(getSigners func() (signers []Signer, err error)) AuthMet // handleAuthResponse returns whether the preceding authentication request succeeded // along with a list of remaining authentication methods to try next and // an error if an unexpected response was received. -func handleAuthResponse(c packetConn) (bool, []string, error) { +func handleAuthResponse(c packetConn) (authResult, []string, error) { for { packet, err := c.readPacket() if err != nil { - return false, nil, err + return authFailure, nil, err } switch packet[0] { case msgUserAuthBanner: - // TODO: add callback to present the banner to the user + if err := handleBannerResponse(c, packet); err != nil { + return authFailure, nil, err + } case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { - return false, nil, err + return authFailure, nil, err + } + if msg.PartialSuccess { + return authPartialSuccess, msg.Methods, nil } - return false, msg.Methods, nil + return authFailure, msg.Methods, nil case msgUserAuthSuccess: - return true, nil, nil + return authSuccess, nil, nil default: - return false, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0]) + return authFailure, nil, unexpectedMessageError(msgUserAuthSuccess, packet[0]) } } } +func handleBannerResponse(c packetConn, packet []byte) error { + var msg userAuthBannerMsg + if err := Unmarshal(packet, &msg); err != nil { + return err + } + + transport, ok := c.(*handshakeTransport) + if !ok { + return nil + } + + if transport.bannerCallback != nil { + return transport.bannerCallback(msg.Message) + } + + return nil +} + // KeyboardInteractiveChallenge should print questions, optionally // disabling echoing (e.g. for passwords), and return all the answers. // Challenge may be called multiple times in a single session. After @@ -359,7 +393,7 @@ func (cb KeyboardInteractiveChallenge) method() string { return "keyboard-interactive" } -func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (bool, []string, error) { +func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packetConn, rand io.Reader) (authResult, []string, error) { type initiateMsg struct { User string `sshtype:"50"` Service string @@ -373,37 +407,42 @@ func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packe Service: serviceSSH, Method: "keyboard-interactive", })); err != nil { - return false, nil, err + return authFailure, nil, err } for { packet, err := c.readPacket() if err != nil { - return false, nil, err + return authFailure, nil, err } // like handleAuthResponse, but with less options. switch packet[0] { case msgUserAuthBanner: - // TODO: Print banners during userauth. + if err := handleBannerResponse(c, packet); err != nil { + return authFailure, nil, err + } continue case msgUserAuthInfoRequest: // OK case msgUserAuthFailure: var msg userAuthFailureMsg if err := Unmarshal(packet, &msg); err != nil { - return false, nil, err + return authFailure, nil, err + } + if msg.PartialSuccess { + return authPartialSuccess, msg.Methods, nil } - return false, msg.Methods, nil + return authFailure, msg.Methods, nil case msgUserAuthSuccess: - return true, nil, nil + return authSuccess, nil, nil default: - return false, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0]) + return authFailure, nil, unexpectedMessageError(msgUserAuthInfoRequest, packet[0]) } var msg userAuthInfoRequestMsg if err := Unmarshal(packet, &msg); err != nil { - return false, nil, err + return authFailure, nil, err } // Manually unpack the prompt/echo pairs. @@ -413,7 +452,7 @@ func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packe for i := 0; i < int(msg.NumPrompts); i++ { prompt, r, ok := parseString(rest) if !ok || len(r) == 0 { - return false, nil, errors.New("ssh: prompt format error") + return authFailure, nil, errors.New("ssh: prompt format error") } prompts = append(prompts, string(prompt)) echos = append(echos, r[0] != 0) @@ -421,16 +460,16 @@ func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packe } if len(rest) != 0 { - return false, nil, errors.New("ssh: extra data following keyboard-interactive pairs") + return authFailure, nil, errors.New("ssh: extra data following keyboard-interactive pairs") } answers, err := cb(msg.User, msg.Instruction, prompts, echos) if err != nil { - return false, nil, err + return authFailure, nil, err } if len(answers) != len(prompts) { - return false, nil, errors.New("ssh: not enough answers from keyboard-interactive callback") + return authFailure, nil, errors.New("ssh: not enough answers from keyboard-interactive callback") } responseLength := 1 + 4 for _, a := range answers { @@ -446,7 +485,7 @@ func (cb KeyboardInteractiveChallenge) auth(session []byte, user string, c packe } if err := c.writePacket(serialized); err != nil { - return false, nil, err + return authFailure, nil, err } } } @@ -456,10 +495,10 @@ type retryableAuthMethod struct { maxTries int } -func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok bool, methods []string, err error) { +func (r *retryableAuthMethod) auth(session []byte, user string, c packetConn, rand io.Reader) (ok authResult, methods []string, err error) { for i := 0; r.maxTries <= 0 || i < r.maxTries; i++ { ok, methods, err = r.authMethod.auth(session, user, c, rand) - if ok || err != nil { // either success or error terminate + if ok != authFailure || err != nil { // either success, partial success or error terminate return ok, methods, err } } diff --git a/vendor/golang.org/x/crypto/ssh/client_auth_test.go b/vendor/golang.org/x/crypto/ssh/client_auth_test.go deleted file mode 100644 index 145b57a2bb..0000000000 --- a/vendor/golang.org/x/crypto/ssh/client_auth_test.go +++ /dev/null @@ -1,628 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "crypto/rand" - "errors" - "fmt" - "os" - "strings" - "testing" -) - -type keyboardInteractive map[string]string - -func (cr keyboardInteractive) Challenge(user string, instruction string, questions []string, echos []bool) ([]string, error) { - var answers []string - for _, q := range questions { - answers = append(answers, cr[q]) - } - return answers, nil -} - -// reused internally by tests -var clientPassword = "tiger" - -// tryAuth runs a handshake with a given config against an SSH server -// with config serverConfig -func tryAuth(t *testing.T, config *ClientConfig) error { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - certChecker := CertChecker{ - IsUserAuthority: func(k PublicKey) bool { - return bytes.Equal(k.Marshal(), testPublicKeys["ecdsa"].Marshal()) - }, - UserKeyFallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) { - if conn.User() == "testuser" && bytes.Equal(key.Marshal(), testPublicKeys["rsa"].Marshal()) { - return nil, nil - } - - return nil, fmt.Errorf("pubkey for %q not acceptable", conn.User()) - }, - IsRevoked: func(c *Certificate) bool { - return c.Serial == 666 - }, - } - - serverConfig := &ServerConfig{ - PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) { - if conn.User() == "testuser" && string(pass) == clientPassword { - return nil, nil - } - return nil, errors.New("password auth failed") - }, - PublicKeyCallback: certChecker.Authenticate, - KeyboardInteractiveCallback: func(conn ConnMetadata, challenge KeyboardInteractiveChallenge) (*Permissions, error) { - ans, err := challenge("user", - "instruction", - []string{"question1", "question2"}, - []bool{true, true}) - if err != nil { - return nil, err - } - ok := conn.User() == "testuser" && ans[0] == "answer1" && ans[1] == "answer2" - if ok { - challenge("user", "motd", nil, nil) - return nil, nil - } - return nil, errors.New("keyboard-interactive failed") - }, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - go newServer(c1, serverConfig) - _, _, _, err = NewClientConn(c2, "", config) - return err -} - -func TestClientAuthPublicKey(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodPassword(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - Password(clientPassword), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodFallback(t *testing.T) { - var passwordCalled bool - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - PasswordCallback( - func() (string, error) { - passwordCalled = true - return "WRONG", nil - }), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } - - if passwordCalled { - t.Errorf("password auth tried before public-key auth.") - } -} - -func TestAuthMethodWrongPassword(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - Password("wrong"), - PublicKeys(testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodKeyboardInteractive(t *testing.T) { - answers := keyboardInteractive(map[string]string{ - "question1": "answer1", - "question2": "answer2", - }) - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - KeyboardInteractive(answers.Challenge), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -func TestAuthMethodWrongKeyboardInteractive(t *testing.T) { - answers := keyboardInteractive(map[string]string{ - "question1": "answer1", - "question2": "WRONG", - }) - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - KeyboardInteractive(answers.Challenge), - }, - } - - if err := tryAuth(t, config); err == nil { - t.Fatalf("wrong answers should not have authenticated with KeyboardInteractive") - } -} - -// the mock server will only authenticate ssh-rsa keys -func TestAuthMethodInvalidPublicKey(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["dsa"]), - }, - } - - if err := tryAuth(t, config); err == nil { - t.Fatalf("dsa private key should not have authenticated with rsa public key") - } -} - -// the client should authenticate with the second key -func TestAuthMethodRSAandDSA(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["dsa"], testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, config); err != nil { - t.Fatalf("client could not authenticate with rsa key: %v", err) - } -} - -func TestClientHMAC(t *testing.T) { - for _, mac := range supportedMACs { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - Config: Config{ - MACs: []string{mac}, - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, config); err != nil { - t.Fatalf("client could not authenticate with mac algo %s: %v", mac, err) - } - } -} - -// issue 4285. -func TestClientUnsupportedCipher(t *testing.T) { - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(), - }, - Config: Config{ - Ciphers: []string{"aes128-cbc"}, // not currently supported - }, - } - if err := tryAuth(t, config); err == nil { - t.Errorf("expected no ciphers in common") - } -} - -func TestClientUnsupportedKex(t *testing.T) { - if os.Getenv("GO_BUILDER_NAME") != "" { - t.Skip("skipping known-flaky test on the Go build dashboard; see golang.org/issue/15198") - } - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(), - }, - Config: Config{ - KeyExchanges: []string{"diffie-hellman-group-exchange-sha256"}, // not currently supported - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, config); err == nil || !strings.Contains(err.Error(), "common algorithm") { - t.Errorf("got %v, expected 'common algorithm'", err) - } -} - -func TestClientLoginCert(t *testing.T) { - cert := &Certificate{ - Key: testPublicKeys["rsa"], - ValidBefore: CertTimeInfinity, - CertType: UserCert, - } - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - certSigner, err := NewCertSigner(cert, testSigners["rsa"]) - if err != nil { - t.Fatalf("NewCertSigner: %v", err) - } - - clientConfig := &ClientConfig{ - User: "user", - HostKeyCallback: InsecureIgnoreHostKey(), - } - clientConfig.Auth = append(clientConfig.Auth, PublicKeys(certSigner)) - - // should succeed - if err := tryAuth(t, clientConfig); err != nil { - t.Errorf("cert login failed: %v", err) - } - - // corrupted signature - cert.Signature.Blob[0]++ - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with corrupted sig") - } - - // revoked - cert.Serial = 666 - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("revoked cert login succeeded") - } - cert.Serial = 1 - - // sign with wrong key - cert.SignCert(rand.Reader, testSigners["dsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with non-authoritative key") - } - - // host cert - cert.CertType = HostCert - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with wrong type") - } - cert.CertType = UserCert - - // principal specified - cert.ValidPrincipals = []string{"user"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err != nil { - t.Errorf("cert login failed: %v", err) - } - - // wrong principal specified - cert.ValidPrincipals = []string{"fred"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with wrong principal") - } - cert.ValidPrincipals = nil - - // added critical option - cert.CriticalOptions = map[string]string{"root-access": "yes"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login passed with unrecognized critical option") - } - - // allowed source address - cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42/24,::42/120"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err != nil { - t.Errorf("cert login with source-address failed: %v", err) - } - - // disallowed source address - cert.CriticalOptions = map[string]string{"source-address": "127.0.0.42,::42"} - cert.SignCert(rand.Reader, testSigners["ecdsa"]) - if err := tryAuth(t, clientConfig); err == nil { - t.Errorf("cert login with source-address succeeded") - } -} - -func testPermissionsPassing(withPermissions bool, t *testing.T) { - serverConfig := &ServerConfig{ - PublicKeyCallback: func(conn ConnMetadata, key PublicKey) (*Permissions, error) { - if conn.User() == "nopermissions" { - return nil, nil - } - return &Permissions{}, nil - }, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - clientConfig := &ClientConfig{ - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if withPermissions { - clientConfig.User = "permissions" - } else { - clientConfig.User = "nopermissions" - } - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewClientConn(c2, "", clientConfig) - serverConn, err := newServer(c1, serverConfig) - if err != nil { - t.Fatal(err) - } - if p := serverConn.Permissions; (p != nil) != withPermissions { - t.Fatalf("withPermissions is %t, but Permissions object is %#v", withPermissions, p) - } -} - -func TestPermissionsPassing(t *testing.T) { - testPermissionsPassing(true, t) -} - -func TestNoPermissionsPassing(t *testing.T) { - testPermissionsPassing(false, t) -} - -func TestRetryableAuth(t *testing.T) { - n := 0 - passwords := []string{"WRONG1", "WRONG2"} - - config := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - RetryableAuthMethod(PasswordCallback(func() (string, error) { - p := passwords[n] - n++ - return p, nil - }), 2), - PublicKeys(testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } - if n != 2 { - t.Fatalf("Did not try all passwords") - } -} - -func ExampleRetryableAuthMethod(t *testing.T) { - user := "testuser" - NumberOfPrompts := 3 - - // Normally this would be a callback that prompts the user to answer the - // provided questions - Cb := func(user, instruction string, questions []string, echos []bool) (answers []string, err error) { - return []string{"answer1", "answer2"}, nil - } - - config := &ClientConfig{ - HostKeyCallback: InsecureIgnoreHostKey(), - User: user, - Auth: []AuthMethod{ - RetryableAuthMethod(KeyboardInteractiveChallenge(Cb), NumberOfPrompts), - }, - } - - if err := tryAuth(t, config); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } -} - -// Test if username is received on server side when NoClientAuth is used -func TestClientAuthNone(t *testing.T) { - user := "testuser" - serverConfig := &ServerConfig{ - NoClientAuth: true, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - clientConfig := &ClientConfig{ - User: user, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewClientConn(c2, "", clientConfig) - serverConn, err := newServer(c1, serverConfig) - if err != nil { - t.Fatalf("newServer: %v", err) - } - if serverConn.User() != user { - t.Fatalf("server: got %q, want %q", serverConn.User(), user) - } -} - -// Test if authentication attempts are limited on server when MaxAuthTries is set -func TestClientAuthMaxAuthTries(t *testing.T) { - user := "testuser" - - serverConfig := &ServerConfig{ - MaxAuthTries: 2, - PasswordCallback: func(conn ConnMetadata, pass []byte) (*Permissions, error) { - if conn.User() == "testuser" && string(pass) == "right" { - return nil, nil - } - return nil, errors.New("password auth failed") - }, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - expectedErr := fmt.Errorf("ssh: handshake failed: %v", &disconnectMsg{ - Reason: 2, - Message: "too many authentication failures", - }) - - for tries := 2; tries < 4; tries++ { - n := tries - clientConfig := &ClientConfig{ - User: user, - Auth: []AuthMethod{ - RetryableAuthMethod(PasswordCallback(func() (string, error) { - n-- - if n == 0 { - return "right", nil - } - return "wrong", nil - }), tries), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go newServer(c1, serverConfig) - _, _, _, err = NewClientConn(c2, "", clientConfig) - if tries > 2 { - if err == nil { - t.Fatalf("client: got no error, want %s", expectedErr) - } else if err.Error() != expectedErr.Error() { - t.Fatalf("client: got %s, want %s", err, expectedErr) - } - } else { - if err != nil { - t.Fatalf("client: got %s, want no error", err) - } - } - } -} - -// Test if authentication attempts are correctly limited on server -// when more public keys are provided then MaxAuthTries -func TestClientAuthMaxAuthTriesPublicKey(t *testing.T) { - signers := []Signer{} - for i := 0; i < 6; i++ { - signers = append(signers, testSigners["dsa"]) - } - - validConfig := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(append([]Signer{testSigners["rsa"]}, signers...)...), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, validConfig); err != nil { - t.Fatalf("unable to dial remote side: %s", err) - } - - expectedErr := fmt.Errorf("ssh: handshake failed: %v", &disconnectMsg{ - Reason: 2, - Message: "too many authentication failures", - }) - invalidConfig := &ClientConfig{ - User: "testuser", - Auth: []AuthMethod{ - PublicKeys(append(signers, testSigners["rsa"])...), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - if err := tryAuth(t, invalidConfig); err == nil { - t.Fatalf("client: got no error, want %s", expectedErr) - } else if err.Error() != expectedErr.Error() { - t.Fatalf("client: got %s, want %s", err, expectedErr) - } -} - -// Test whether authentication errors are being properly logged if all -// authentication methods have been exhausted -func TestClientAuthErrorList(t *testing.T) { - publicKeyErr := errors.New("This is an error from PublicKeyCallback") - - clientConfig := &ClientConfig{ - Auth: []AuthMethod{ - PublicKeys(testSigners["rsa"]), - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - serverConfig := &ServerConfig{ - PublicKeyCallback: func(_ ConnMetadata, _ PublicKey) (*Permissions, error) { - return nil, publicKeyErr - }, - } - serverConfig.AddHostKey(testSigners["rsa"]) - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewClientConn(c2, "", clientConfig) - _, err = newServer(c1, serverConfig) - if err == nil { - t.Fatal("newServer: got nil, expected errors") - } - - authErrs, ok := err.(*ServerAuthError) - if !ok { - t.Fatalf("errors: got %T, want *ssh.ServerAuthError", err) - } - for i, e := range authErrs.Errors { - switch i { - case 0: - if e.Error() != "no auth passed yet" { - t.Fatalf("errors: got %v, want no auth passed yet", e.Error()) - } - case 1: - if e != publicKeyErr { - t.Fatalf("errors: got %v, want %v", e, publicKeyErr) - } - default: - t.Fatalf("errors: got %v, expected 2 errors", authErrs.Errors) - } - } -} diff --git a/vendor/golang.org/x/crypto/ssh/client_test.go b/vendor/golang.org/x/crypto/ssh/client_test.go deleted file mode 100644 index ccf56074d7..0000000000 --- a/vendor/golang.org/x/crypto/ssh/client_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2014 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 ssh - -import ( - "net" - "strings" - "testing" -) - -func testClientVersion(t *testing.T, config *ClientConfig, expected string) { - clientConn, serverConn := net.Pipe() - defer clientConn.Close() - receivedVersion := make(chan string, 1) - config.HostKeyCallback = InsecureIgnoreHostKey() - go func() { - version, err := readVersion(serverConn) - if err != nil { - receivedVersion <- "" - } else { - receivedVersion <- string(version) - } - serverConn.Close() - }() - NewClientConn(clientConn, "", config) - actual := <-receivedVersion - if actual != expected { - t.Fatalf("got %s; want %s", actual, expected) - } -} - -func TestCustomClientVersion(t *testing.T) { - version := "Test-Client-Version-0.0" - testClientVersion(t, &ClientConfig{ClientVersion: version}, version) -} - -func TestDefaultClientVersion(t *testing.T) { - testClientVersion(t, &ClientConfig{}, packageVersion) -} - -func TestHostKeyCheck(t *testing.T) { - for _, tt := range []struct { - name string - wantError string - key PublicKey - }{ - {"no callback", "must specify HostKeyCallback", nil}, - {"correct key", "", testSigners["rsa"].PublicKey()}, - {"mismatch", "mismatch", testSigners["ecdsa"].PublicKey()}, - } { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - serverConf := &ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["rsa"]) - - go NewServerConn(c1, serverConf) - clientConf := ClientConfig{ - User: "user", - } - if tt.key != nil { - clientConf.HostKeyCallback = FixedHostKey(tt.key) - } - - _, _, _, err = NewClientConn(c2, "", &clientConf) - if err != nil { - if tt.wantError == "" || !strings.Contains(err.Error(), tt.wantError) { - t.Errorf("%s: got error %q, missing %q", tt.name, err.Error(), tt.wantError) - } - } else if tt.wantError != "" { - t.Errorf("%s: succeeded, but want error string %q", tt.name, tt.wantError) - } - } -} diff --git a/vendor/golang.org/x/crypto/ssh/common.go b/vendor/golang.org/x/crypto/ssh/common.go index dc39e4d231..04f3620b3d 100644 --- a/vendor/golang.org/x/crypto/ssh/common.go +++ b/vendor/golang.org/x/crypto/ssh/common.go @@ -24,11 +24,21 @@ const ( serviceSSH = "ssh-connection" ) -// supportedCiphers specifies the supported ciphers in preference order. +// supportedCiphers lists ciphers we support but might not recommend. var supportedCiphers = []string{ "aes128-ctr", "aes192-ctr", "aes256-ctr", "aes128-gcm@openssh.com", - "arcfour256", "arcfour128", + chacha20Poly1305ID, + "arcfour256", "arcfour128", "arcfour", + aes128cbcID, + tripledescbcID, +} + +// preferredCiphers specifies the default preference for ciphers. +var preferredCiphers = []string{ + "aes128-gcm@openssh.com", + chacha20Poly1305ID, + "aes128-ctr", "aes192-ctr", "aes256-ctr", } // supportedKexAlgos specifies the supported key-exchange algorithms in @@ -211,7 +221,7 @@ func (c *Config) SetDefaults() { c.Rand = rand.Reader } if c.Ciphers == nil { - c.Ciphers = supportedCiphers + c.Ciphers = preferredCiphers } var ciphers []string for _, c := range c.Ciphers { @@ -242,7 +252,7 @@ func (c *Config) SetDefaults() { // buildDataSignedForAuth returns the data that is signed in order to prove // possession of a private key. See RFC 4252, section 7. -func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte { +func buildDataSignedForAuth(sessionID []byte, req userAuthRequestMsg, algo, pubKey []byte) []byte { data := struct { Session []byte Type byte @@ -253,7 +263,7 @@ func buildDataSignedForAuth(sessionId []byte, req userAuthRequestMsg, algo, pubK Algo []byte PubKey []byte }{ - sessionId, + sessionID, msgUserAuthRequest, req.User, req.Service, diff --git a/vendor/golang.org/x/crypto/ssh/example_test.go b/vendor/golang.org/x/crypto/ssh/example_test.go deleted file mode 100644 index b910c7bf60..0000000000 --- a/vendor/golang.org/x/crypto/ssh/example_test.go +++ /dev/null @@ -1,320 +0,0 @@ -// Copyright 2011 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 ssh_test - -import ( - "bufio" - "bytes" - "fmt" - "io/ioutil" - "log" - "net" - "net/http" - "os" - "path/filepath" - "strings" - - "golang.org/x/crypto/ssh" - "golang.org/x/crypto/ssh/terminal" -) - -func ExampleNewServerConn() { - // Public key authentication is done by comparing - // the public key of a received connection - // with the entries in the authorized_keys file. - authorizedKeysBytes, err := ioutil.ReadFile("authorized_keys") - if err != nil { - log.Fatalf("Failed to load authorized_keys, err: %v", err) - } - - authorizedKeysMap := map[string]bool{} - for len(authorizedKeysBytes) > 0 { - pubKey, _, _, rest, err := ssh.ParseAuthorizedKey(authorizedKeysBytes) - if err != nil { - log.Fatal(err) - } - - authorizedKeysMap[string(pubKey.Marshal())] = true - authorizedKeysBytes = rest - } - - // An SSH server is represented by a ServerConfig, which holds - // certificate details and handles authentication of ServerConns. - config := &ssh.ServerConfig{ - // Remove to disable password auth. - PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) { - // Should use constant-time compare (or better, salt+hash) in - // a production setting. - if c.User() == "testuser" && string(pass) == "tiger" { - return nil, nil - } - return nil, fmt.Errorf("password rejected for %q", c.User()) - }, - - // Remove to disable public key auth. - PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) { - if authorizedKeysMap[string(pubKey.Marshal())] { - return &ssh.Permissions{ - // Record the public key used for authentication. - Extensions: map[string]string{ - "pubkey-fp": ssh.FingerprintSHA256(pubKey), - }, - }, nil - } - return nil, fmt.Errorf("unknown public key for %q", c.User()) - }, - } - - privateBytes, err := ioutil.ReadFile("id_rsa") - if err != nil { - log.Fatal("Failed to load private key: ", err) - } - - private, err := ssh.ParsePrivateKey(privateBytes) - if err != nil { - log.Fatal("Failed to parse private key: ", err) - } - - config.AddHostKey(private) - - // Once a ServerConfig has been configured, connections can be - // accepted. - listener, err := net.Listen("tcp", "0.0.0.0:2022") - if err != nil { - log.Fatal("failed to listen for connection: ", err) - } - nConn, err := listener.Accept() - if err != nil { - log.Fatal("failed to accept incoming connection: ", err) - } - - // Before use, a handshake must be performed on the incoming - // net.Conn. - conn, chans, reqs, err := ssh.NewServerConn(nConn, config) - if err != nil { - log.Fatal("failed to handshake: ", err) - } - log.Printf("logged in with key %s", conn.Permissions.Extensions["pubkey-fp"]) - - // The incoming Request channel must be serviced. - go ssh.DiscardRequests(reqs) - - // Service the incoming Channel channel. - for newChannel := range chans { - // Channels have a type, depending on the application level - // protocol intended. In the case of a shell, the type is - // "session" and ServerShell may be used to present a simple - // terminal interface. - if newChannel.ChannelType() != "session" { - newChannel.Reject(ssh.UnknownChannelType, "unknown channel type") - continue - } - channel, requests, err := newChannel.Accept() - if err != nil { - log.Fatalf("Could not accept channel: %v", err) - } - - // Sessions have out-of-band requests such as "shell", - // "pty-req" and "env". Here we handle only the - // "shell" request. - go func(in <-chan *ssh.Request) { - for req := range in { - req.Reply(req.Type == "shell", nil) - } - }(requests) - - term := terminal.NewTerminal(channel, "> ") - - go func() { - defer channel.Close() - for { - line, err := term.ReadLine() - if err != nil { - break - } - fmt.Println(line) - } - }() - } -} - -func ExampleHostKeyCheck() { - // Every client must provide a host key check. Here is a - // simple-minded parse of OpenSSH's known_hosts file - host := "hostname" - file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")) - if err != nil { - log.Fatal(err) - } - defer file.Close() - - scanner := bufio.NewScanner(file) - var hostKey ssh.PublicKey - for scanner.Scan() { - fields := strings.Split(scanner.Text(), " ") - if len(fields) != 3 { - continue - } - if strings.Contains(fields[0], host) { - var err error - hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes()) - if err != nil { - log.Fatalf("error parsing %q: %v", fields[2], err) - } - break - } - } - - if hostKey == nil { - log.Fatalf("no hostkey for %s", host) - } - - config := ssh.ClientConfig{ - User: os.Getenv("USER"), - HostKeyCallback: ssh.FixedHostKey(hostKey), - } - - _, err = ssh.Dial("tcp", host+":22", &config) - log.Println(err) -} - -func ExampleDial() { - var hostKey ssh.PublicKey - // An SSH client is represented with a ClientConn. - // - // To authenticate with the remote server you must pass at least one - // implementation of AuthMethod via the Auth field in ClientConfig, - // and provide a HostKeyCallback. - config := &ssh.ClientConfig{ - User: "username", - Auth: []ssh.AuthMethod{ - ssh.Password("yourpassword"), - }, - HostKeyCallback: ssh.FixedHostKey(hostKey), - } - client, err := ssh.Dial("tcp", "yourserver.com:22", config) - if err != nil { - log.Fatal("Failed to dial: ", err) - } - - // Each ClientConn can support multiple interactive sessions, - // represented by a Session. - session, err := client.NewSession() - if err != nil { - log.Fatal("Failed to create session: ", err) - } - defer session.Close() - - // Once a Session is created, you can execute a single command on - // the remote side using the Run method. - var b bytes.Buffer - session.Stdout = &b - if err := session.Run("/usr/bin/whoami"); err != nil { - log.Fatal("Failed to run: " + err.Error()) - } - fmt.Println(b.String()) -} - -func ExamplePublicKeys() { - var hostKey ssh.PublicKey - // A public key may be used to authenticate against the remote - // server by using an unencrypted PEM-encoded private key file. - // - // If you have an encrypted private key, the crypto/x509 package - // can be used to decrypt it. - key, err := ioutil.ReadFile("/home/user/.ssh/id_rsa") - if err != nil { - log.Fatalf("unable to read private key: %v", err) - } - - // Create the Signer for this private key. - signer, err := ssh.ParsePrivateKey(key) - if err != nil { - log.Fatalf("unable to parse private key: %v", err) - } - - config := &ssh.ClientConfig{ - User: "user", - Auth: []ssh.AuthMethod{ - // Use the PublicKeys method for remote authentication. - ssh.PublicKeys(signer), - }, - HostKeyCallback: ssh.FixedHostKey(hostKey), - } - - // Connect to the remote server and perform the SSH handshake. - client, err := ssh.Dial("tcp", "host.com:22", config) - if err != nil { - log.Fatalf("unable to connect: %v", err) - } - defer client.Close() -} - -func ExampleClient_Listen() { - var hostKey ssh.PublicKey - config := &ssh.ClientConfig{ - User: "username", - Auth: []ssh.AuthMethod{ - ssh.Password("password"), - }, - HostKeyCallback: ssh.FixedHostKey(hostKey), - } - // Dial your ssh server. - conn, err := ssh.Dial("tcp", "localhost:22", config) - if err != nil { - log.Fatal("unable to connect: ", err) - } - defer conn.Close() - - // Request the remote side to open port 8080 on all interfaces. - l, err := conn.Listen("tcp", "0.0.0.0:8080") - if err != nil { - log.Fatal("unable to register tcp forward: ", err) - } - defer l.Close() - - // Serve HTTP with your SSH server acting as a reverse proxy. - http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) { - fmt.Fprintf(resp, "Hello world!\n") - })) -} - -func ExampleSession_RequestPty() { - var hostKey ssh.PublicKey - // Create client config - config := &ssh.ClientConfig{ - User: "username", - Auth: []ssh.AuthMethod{ - ssh.Password("password"), - }, - HostKeyCallback: ssh.FixedHostKey(hostKey), - } - // Connect to ssh server - conn, err := ssh.Dial("tcp", "localhost:22", config) - if err != nil { - log.Fatal("unable to connect: ", err) - } - defer conn.Close() - // Create a session - session, err := conn.NewSession() - if err != nil { - log.Fatal("unable to create session: ", err) - } - defer session.Close() - // Set up terminal modes - modes := ssh.TerminalModes{ - ssh.ECHO: 0, // disable echoing - ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud - ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud - } - // Request pseudo terminal - if err := session.RequestPty("xterm", 40, 80, modes); err != nil { - log.Fatal("request for pseudo terminal failed: ", err) - } - // Start remote shell - if err := session.Shell(); err != nil { - log.Fatal("failed to start shell: ", err) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/handshake.go b/vendor/golang.org/x/crypto/ssh/handshake.go index 932ce8393e..4f7912ecd6 100644 --- a/vendor/golang.org/x/crypto/ssh/handshake.go +++ b/vendor/golang.org/x/crypto/ssh/handshake.go @@ -78,6 +78,11 @@ type handshakeTransport struct { dialAddress string remoteAddr net.Addr + // bannerCallback is non-empty if we are the client and it has been set in + // ClientConfig. In that case it is called during the user authentication + // dance to handle a custom server's message. + bannerCallback BannerCallback + // Algorithms agreed in the last key exchange. algorithms *algorithms @@ -120,6 +125,7 @@ func newClientTransport(conn keyingTransport, clientVersion, serverVersion []byt t.dialAddress = dialAddr t.remoteAddr = addr t.hostKeyCallback = config.HostKeyCallback + t.bannerCallback = config.BannerCallback if config.HostKeyAlgorithms != nil { t.hostKeyAlgorithms = config.HostKeyAlgorithms } else { diff --git a/vendor/golang.org/x/crypto/ssh/handshake_test.go b/vendor/golang.org/x/crypto/ssh/handshake_test.go deleted file mode 100644 index 91d4935689..0000000000 --- a/vendor/golang.org/x/crypto/ssh/handshake_test.go +++ /dev/null @@ -1,559 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "bytes" - "crypto/rand" - "errors" - "fmt" - "io" - "net" - "reflect" - "runtime" - "strings" - "sync" - "testing" -) - -type testChecker struct { - calls []string -} - -func (t *testChecker) Check(dialAddr string, addr net.Addr, key PublicKey) error { - if dialAddr == "bad" { - return fmt.Errorf("dialAddr is bad") - } - - if tcpAddr, ok := addr.(*net.TCPAddr); !ok || tcpAddr == nil { - return fmt.Errorf("testChecker: got %T want *net.TCPAddr", addr) - } - - t.calls = append(t.calls, fmt.Sprintf("%s %v %s %x", dialAddr, addr, key.Type(), key.Marshal())) - - return nil -} - -// netPipe is analogous to net.Pipe, but it uses a real net.Conn, and -// therefore is buffered (net.Pipe deadlocks if both sides start with -// a write.) -func netPipe() (net.Conn, net.Conn, error) { - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - listener, err = net.Listen("tcp", "[::1]:0") - if err != nil { - return nil, nil, err - } - } - defer listener.Close() - c1, err := net.Dial("tcp", listener.Addr().String()) - if err != nil { - return nil, nil, err - } - - c2, err := listener.Accept() - if err != nil { - c1.Close() - return nil, nil, err - } - - return c1, c2, nil -} - -// noiseTransport inserts ignore messages to check that the read loop -// and the key exchange filters out these messages. -type noiseTransport struct { - keyingTransport -} - -func (t *noiseTransport) writePacket(p []byte) error { - ignore := []byte{msgIgnore} - if err := t.keyingTransport.writePacket(ignore); err != nil { - return err - } - debug := []byte{msgDebug, 1, 2, 3} - if err := t.keyingTransport.writePacket(debug); err != nil { - return err - } - - return t.keyingTransport.writePacket(p) -} - -func addNoiseTransport(t keyingTransport) keyingTransport { - return &noiseTransport{t} -} - -// handshakePair creates two handshakeTransports connected with each -// other. If the noise argument is true, both transports will try to -// confuse the other side by sending ignore and debug messages. -func handshakePair(clientConf *ClientConfig, addr string, noise bool) (client *handshakeTransport, server *handshakeTransport, err error) { - a, b, err := netPipe() - if err != nil { - return nil, nil, err - } - - var trC, trS keyingTransport - - trC = newTransport(a, rand.Reader, true) - trS = newTransport(b, rand.Reader, false) - if noise { - trC = addNoiseTransport(trC) - trS = addNoiseTransport(trS) - } - clientConf.SetDefaults() - - v := []byte("version") - client = newClientTransport(trC, v, v, clientConf, addr, a.RemoteAddr()) - - serverConf := &ServerConfig{} - serverConf.AddHostKey(testSigners["ecdsa"]) - serverConf.AddHostKey(testSigners["rsa"]) - serverConf.SetDefaults() - server = newServerTransport(trS, v, v, serverConf) - - if err := server.waitSession(); err != nil { - return nil, nil, fmt.Errorf("server.waitSession: %v", err) - } - if err := client.waitSession(); err != nil { - return nil, nil, fmt.Errorf("client.waitSession: %v", err) - } - - return client, server, nil -} - -func TestHandshakeBasic(t *testing.T) { - if runtime.GOOS == "plan9" { - t.Skip("see golang.org/issue/7237") - } - - checker := &syncChecker{ - waitCall: make(chan int, 10), - called: make(chan int, 10), - } - - checker.waitCall <- 1 - trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr", false) - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - - defer trC.Close() - defer trS.Close() - - // Let first kex complete normally. - <-checker.called - - clientDone := make(chan int, 0) - gotHalf := make(chan int, 0) - const N = 20 - - go func() { - defer close(clientDone) - // Client writes a bunch of stuff, and does a key - // change in the middle. This should not confuse the - // handshake in progress. We do this twice, so we test - // that the packet buffer is reset correctly. - for i := 0; i < N; i++ { - p := []byte{msgRequestSuccess, byte(i)} - if err := trC.writePacket(p); err != nil { - t.Fatalf("sendPacket: %v", err) - } - if (i % 10) == 5 { - <-gotHalf - // halfway through, we request a key change. - trC.requestKeyExchange() - - // Wait until we can be sure the key - // change has really started before we - // write more. - <-checker.called - } - if (i % 10) == 7 { - // write some packets until the kex - // completes, to test buffering of - // packets. - checker.waitCall <- 1 - } - } - }() - - // Server checks that client messages come in cleanly - i := 0 - err = nil - for ; i < N; i++ { - var p []byte - p, err = trS.readPacket() - if err != nil { - break - } - if (i % 10) == 5 { - gotHalf <- 1 - } - - want := []byte{msgRequestSuccess, byte(i)} - if bytes.Compare(p, want) != 0 { - t.Errorf("message %d: got %v, want %v", i, p, want) - } - } - <-clientDone - if err != nil && err != io.EOF { - t.Fatalf("server error: %v", err) - } - if i != N { - t.Errorf("received %d messages, want 10.", i) - } - - close(checker.called) - if _, ok := <-checker.called; ok { - // If all went well, we registered exactly 2 key changes: one - // that establishes the session, and one that we requested - // additionally. - t.Fatalf("got another host key checks after 2 handshakes") - } -} - -func TestForceFirstKex(t *testing.T) { - // like handshakePair, but must access the keyingTransport. - checker := &testChecker{} - clientConf := &ClientConfig{HostKeyCallback: checker.Check} - a, b, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - - var trC, trS keyingTransport - - trC = newTransport(a, rand.Reader, true) - - // This is the disallowed packet: - trC.writePacket(Marshal(&serviceRequestMsg{serviceUserAuth})) - - // Rest of the setup. - trS = newTransport(b, rand.Reader, false) - clientConf.SetDefaults() - - v := []byte("version") - client := newClientTransport(trC, v, v, clientConf, "addr", a.RemoteAddr()) - - serverConf := &ServerConfig{} - serverConf.AddHostKey(testSigners["ecdsa"]) - serverConf.AddHostKey(testSigners["rsa"]) - serverConf.SetDefaults() - server := newServerTransport(trS, v, v, serverConf) - - defer client.Close() - defer server.Close() - - // We setup the initial key exchange, but the remote side - // tries to send serviceRequestMsg in cleartext, which is - // disallowed. - - if err := server.waitSession(); err == nil { - t.Errorf("server first kex init should reject unexpected packet") - } -} - -func TestHandshakeAutoRekeyWrite(t *testing.T) { - checker := &syncChecker{ - called: make(chan int, 10), - waitCall: nil, - } - clientConf := &ClientConfig{HostKeyCallback: checker.Check} - clientConf.RekeyThreshold = 500 - trC, trS, err := handshakePair(clientConf, "addr", false) - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - defer trC.Close() - defer trS.Close() - - input := make([]byte, 251) - input[0] = msgRequestSuccess - - done := make(chan int, 1) - const numPacket = 5 - go func() { - defer close(done) - j := 0 - for ; j < numPacket; j++ { - if p, err := trS.readPacket(); err != nil { - break - } else if !bytes.Equal(input, p) { - t.Errorf("got packet type %d, want %d", p[0], input[0]) - } - } - - if j != numPacket { - t.Errorf("got %d, want 5 messages", j) - } - }() - - <-checker.called - - for i := 0; i < numPacket; i++ { - p := make([]byte, len(input)) - copy(p, input) - if err := trC.writePacket(p); err != nil { - t.Errorf("writePacket: %v", err) - } - if i == 2 { - // Make sure the kex is in progress. - <-checker.called - } - - } - <-done -} - -type syncChecker struct { - waitCall chan int - called chan int -} - -func (c *syncChecker) Check(dialAddr string, addr net.Addr, key PublicKey) error { - c.called <- 1 - if c.waitCall != nil { - <-c.waitCall - } - return nil -} - -func TestHandshakeAutoRekeyRead(t *testing.T) { - sync := &syncChecker{ - called: make(chan int, 2), - waitCall: nil, - } - clientConf := &ClientConfig{ - HostKeyCallback: sync.Check, - } - clientConf.RekeyThreshold = 500 - - trC, trS, err := handshakePair(clientConf, "addr", false) - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - defer trC.Close() - defer trS.Close() - - packet := make([]byte, 501) - packet[0] = msgRequestSuccess - if err := trS.writePacket(packet); err != nil { - t.Fatalf("writePacket: %v", err) - } - - // While we read out the packet, a key change will be - // initiated. - done := make(chan int, 1) - go func() { - defer close(done) - if _, err := trC.readPacket(); err != nil { - t.Fatalf("readPacket(client): %v", err) - } - - }() - - <-done - <-sync.called -} - -// errorKeyingTransport generates errors after a given number of -// read/write operations. -type errorKeyingTransport struct { - packetConn - readLeft, writeLeft int -} - -func (n *errorKeyingTransport) prepareKeyChange(*algorithms, *kexResult) error { - return nil -} - -func (n *errorKeyingTransport) getSessionID() []byte { - return nil -} - -func (n *errorKeyingTransport) writePacket(packet []byte) error { - if n.writeLeft == 0 { - n.Close() - return errors.New("barf") - } - - n.writeLeft-- - return n.packetConn.writePacket(packet) -} - -func (n *errorKeyingTransport) readPacket() ([]byte, error) { - if n.readLeft == 0 { - n.Close() - return nil, errors.New("barf") - } - - n.readLeft-- - return n.packetConn.readPacket() -} - -func TestHandshakeErrorHandlingRead(t *testing.T) { - for i := 0; i < 20; i++ { - testHandshakeErrorHandlingN(t, i, -1, false) - } -} - -func TestHandshakeErrorHandlingWrite(t *testing.T) { - for i := 0; i < 20; i++ { - testHandshakeErrorHandlingN(t, -1, i, false) - } -} - -func TestHandshakeErrorHandlingReadCoupled(t *testing.T) { - for i := 0; i < 20; i++ { - testHandshakeErrorHandlingN(t, i, -1, true) - } -} - -func TestHandshakeErrorHandlingWriteCoupled(t *testing.T) { - for i := 0; i < 20; i++ { - testHandshakeErrorHandlingN(t, -1, i, true) - } -} - -// testHandshakeErrorHandlingN runs handshakes, injecting errors. If -// handshakeTransport deadlocks, the go runtime will detect it and -// panic. -func testHandshakeErrorHandlingN(t *testing.T, readLimit, writeLimit int, coupled bool) { - msg := Marshal(&serviceRequestMsg{strings.Repeat("x", int(minRekeyThreshold)/4)}) - - a, b := memPipe() - defer a.Close() - defer b.Close() - - key := testSigners["ecdsa"] - serverConf := Config{RekeyThreshold: minRekeyThreshold} - serverConf.SetDefaults() - serverConn := newHandshakeTransport(&errorKeyingTransport{a, readLimit, writeLimit}, &serverConf, []byte{'a'}, []byte{'b'}) - serverConn.hostKeys = []Signer{key} - go serverConn.readLoop() - go serverConn.kexLoop() - - clientConf := Config{RekeyThreshold: 10 * minRekeyThreshold} - clientConf.SetDefaults() - clientConn := newHandshakeTransport(&errorKeyingTransport{b, -1, -1}, &clientConf, []byte{'a'}, []byte{'b'}) - clientConn.hostKeyAlgorithms = []string{key.PublicKey().Type()} - clientConn.hostKeyCallback = InsecureIgnoreHostKey() - go clientConn.readLoop() - go clientConn.kexLoop() - - var wg sync.WaitGroup - - for _, hs := range []packetConn{serverConn, clientConn} { - if !coupled { - wg.Add(2) - go func(c packetConn) { - for i := 0; ; i++ { - str := fmt.Sprintf("%08x", i) + strings.Repeat("x", int(minRekeyThreshold)/4-8) - err := c.writePacket(Marshal(&serviceRequestMsg{str})) - if err != nil { - break - } - } - wg.Done() - c.Close() - }(hs) - go func(c packetConn) { - for { - _, err := c.readPacket() - if err != nil { - break - } - } - wg.Done() - }(hs) - } else { - wg.Add(1) - go func(c packetConn) { - for { - _, err := c.readPacket() - if err != nil { - break - } - if err := c.writePacket(msg); err != nil { - break - } - - } - wg.Done() - }(hs) - } - } - wg.Wait() -} - -func TestDisconnect(t *testing.T) { - if runtime.GOOS == "plan9" { - t.Skip("see golang.org/issue/7237") - } - checker := &testChecker{} - trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr", false) - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - - defer trC.Close() - defer trS.Close() - - trC.writePacket([]byte{msgRequestSuccess, 0, 0}) - errMsg := &disconnectMsg{ - Reason: 42, - Message: "such is life", - } - trC.writePacket(Marshal(errMsg)) - trC.writePacket([]byte{msgRequestSuccess, 0, 0}) - - packet, err := trS.readPacket() - if err != nil { - t.Fatalf("readPacket 1: %v", err) - } - if packet[0] != msgRequestSuccess { - t.Errorf("got packet %v, want packet type %d", packet, msgRequestSuccess) - } - - _, err = trS.readPacket() - if err == nil { - t.Errorf("readPacket 2 succeeded") - } else if !reflect.DeepEqual(err, errMsg) { - t.Errorf("got error %#v, want %#v", err, errMsg) - } - - _, err = trS.readPacket() - if err == nil { - t.Errorf("readPacket 3 succeeded") - } -} - -func TestHandshakeRekeyDefault(t *testing.T) { - clientConf := &ClientConfig{ - Config: Config{ - Ciphers: []string{"aes128-ctr"}, - }, - HostKeyCallback: InsecureIgnoreHostKey(), - } - trC, trS, err := handshakePair(clientConf, "addr", false) - if err != nil { - t.Fatalf("handshakePair: %v", err) - } - defer trC.Close() - defer trS.Close() - - trC.writePacket([]byte{msgRequestSuccess, 0, 0}) - trC.Close() - - rgb := (1024 + trC.readBytesLeft) >> 30 - wgb := (1024 + trC.writeBytesLeft) >> 30 - - if rgb != 64 { - t.Errorf("got rekey after %dG read, want 64G", rgb) - } - if wgb != 64 { - t.Errorf("got rekey after %dG write, want 64G", wgb) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/kex.go b/vendor/golang.org/x/crypto/ssh/kex.go index f91c2770ed..f34bcc0133 100644 --- a/vendor/golang.org/x/crypto/ssh/kex.go +++ b/vendor/golang.org/x/crypto/ssh/kex.go @@ -119,7 +119,7 @@ func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handsha return nil, err } - kInt, err := group.diffieHellman(kexDHReply.Y, x) + ki, err := group.diffieHellman(kexDHReply.Y, x) if err != nil { return nil, err } @@ -129,8 +129,8 @@ func (group *dhGroup) Client(c packetConn, randSource io.Reader, magics *handsha writeString(h, kexDHReply.HostKey) writeInt(h, X) writeInt(h, kexDHReply.Y) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) + K := make([]byte, intLength(ki)) + marshalInt(K, ki) h.Write(K) return &kexResult{ @@ -164,7 +164,7 @@ func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handsha } Y := new(big.Int).Exp(group.g, y, group.p) - kInt, err := group.diffieHellman(kexDHInit.X, y) + ki, err := group.diffieHellman(kexDHInit.X, y) if err != nil { return nil, err } @@ -177,8 +177,8 @@ func (group *dhGroup) Server(c packetConn, randSource io.Reader, magics *handsha writeInt(h, kexDHInit.X) writeInt(h, Y) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) + K := make([]byte, intLength(ki)) + marshalInt(K, ki) h.Write(K) H := h.Sum(nil) @@ -462,9 +462,9 @@ func (kex *curve25519sha256) Client(c packetConn, rand io.Reader, magics *handsh writeString(h, kp.pub[:]) writeString(h, reply.EphemeralPubKey) - kInt := new(big.Int).SetBytes(secret[:]) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) + ki := new(big.Int).SetBytes(secret[:]) + K := make([]byte, intLength(ki)) + marshalInt(K, ki) h.Write(K) return &kexResult{ @@ -510,9 +510,9 @@ func (kex *curve25519sha256) Server(c packetConn, rand io.Reader, magics *handsh writeString(h, kexInit.ClientPubKey) writeString(h, kp.pub[:]) - kInt := new(big.Int).SetBytes(secret[:]) - K := make([]byte, intLength(kInt)) - marshalInt(K, kInt) + ki := new(big.Int).SetBytes(secret[:]) + K := make([]byte, intLength(ki)) + marshalInt(K, ki) h.Write(K) H := h.Sum(nil) diff --git a/vendor/golang.org/x/crypto/ssh/kex_test.go b/vendor/golang.org/x/crypto/ssh/kex_test.go deleted file mode 100644 index 12ca0acd31..0000000000 --- a/vendor/golang.org/x/crypto/ssh/kex_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2013 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 ssh - -// Key exchange tests. - -import ( - "crypto/rand" - "reflect" - "testing" -) - -func TestKexes(t *testing.T) { - type kexResultErr struct { - result *kexResult - err error - } - - for name, kex := range kexAlgoMap { - a, b := memPipe() - - s := make(chan kexResultErr, 1) - c := make(chan kexResultErr, 1) - var magics handshakeMagics - go func() { - r, e := kex.Client(a, rand.Reader, &magics) - a.Close() - c <- kexResultErr{r, e} - }() - go func() { - r, e := kex.Server(b, rand.Reader, &magics, testSigners["ecdsa"]) - b.Close() - s <- kexResultErr{r, e} - }() - - clientRes := <-c - serverRes := <-s - if clientRes.err != nil { - t.Errorf("client: %v", clientRes.err) - } - if serverRes.err != nil { - t.Errorf("server: %v", serverRes.err) - } - if !reflect.DeepEqual(clientRes.result, serverRes.result) { - t.Errorf("kex %q: mismatch %#v, %#v", name, clientRes.result, serverRes.result) - } - } -} diff --git a/vendor/golang.org/x/crypto/ssh/keys.go b/vendor/golang.org/x/crypto/ssh/keys.go index b682c1741b..73697deda6 100644 --- a/vendor/golang.org/x/crypto/ssh/keys.go +++ b/vendor/golang.org/x/crypto/ssh/keys.go @@ -276,7 +276,8 @@ type PublicKey interface { Type() string // Marshal returns the serialized key data in SSH wire format, - // with the name prefix. + // with the name prefix. To unmarshal the returned data, use + // the ParsePublicKey function. Marshal() []byte // Verify that sig is a signature on the given data using this @@ -363,7 +364,7 @@ func (r *rsaPublicKey) CryptoPublicKey() crypto.PublicKey { type dsaPublicKey dsa.PublicKey -func (r *dsaPublicKey) Type() string { +func (k *dsaPublicKey) Type() string { return "ssh-dss" } @@ -481,12 +482,12 @@ func (k *dsaPrivateKey) Sign(rand io.Reader, data []byte) (*Signature, error) { type ecdsaPublicKey ecdsa.PublicKey -func (key *ecdsaPublicKey) Type() string { - return "ecdsa-sha2-" + key.nistID() +func (k *ecdsaPublicKey) Type() string { + return "ecdsa-sha2-" + k.nistID() } -func (key *ecdsaPublicKey) nistID() string { - switch key.Params().BitSize { +func (k *ecdsaPublicKey) nistID() string { + switch k.Params().BitSize { case 256: return "nistp256" case 384: @@ -499,7 +500,7 @@ func (key *ecdsaPublicKey) nistID() string { type ed25519PublicKey ed25519.PublicKey -func (key ed25519PublicKey) Type() string { +func (k ed25519PublicKey) Type() string { return KeyAlgoED25519 } @@ -518,23 +519,23 @@ func parseED25519(in []byte) (out PublicKey, rest []byte, err error) { return (ed25519PublicKey)(key), w.Rest, nil } -func (key ed25519PublicKey) Marshal() []byte { +func (k ed25519PublicKey) Marshal() []byte { w := struct { Name string KeyBytes []byte }{ KeyAlgoED25519, - []byte(key), + []byte(k), } return Marshal(&w) } -func (key ed25519PublicKey) Verify(b []byte, sig *Signature) error { - if sig.Format != key.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type()) +func (k ed25519PublicKey) Verify(b []byte, sig *Signature) error { + if sig.Format != k.Type() { + return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) } - edKey := (ed25519.PublicKey)(key) + edKey := (ed25519.PublicKey)(k) if ok := ed25519.Verify(edKey, b, sig.Blob); !ok { return errors.New("ssh: signature did not verify") } @@ -595,9 +596,9 @@ func parseECDSA(in []byte) (out PublicKey, rest []byte, err error) { return (*ecdsaPublicKey)(key), w.Rest, nil } -func (key *ecdsaPublicKey) Marshal() []byte { +func (k *ecdsaPublicKey) Marshal() []byte { // See RFC 5656, section 3.1. - keyBytes := elliptic.Marshal(key.Curve, key.X, key.Y) + keyBytes := elliptic.Marshal(k.Curve, k.X, k.Y) // ECDSA publickey struct layout should match the struct used by // parseECDSACert in the x/crypto/ssh/agent package. w := struct { @@ -605,20 +606,20 @@ func (key *ecdsaPublicKey) Marshal() []byte { ID string Key []byte }{ - key.Type(), - key.nistID(), + k.Type(), + k.nistID(), keyBytes, } return Marshal(&w) } -func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error { - if sig.Format != key.Type() { - return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, key.Type()) +func (k *ecdsaPublicKey) Verify(data []byte, sig *Signature) error { + if sig.Format != k.Type() { + return fmt.Errorf("ssh: signature type %s for key type %s", sig.Format, k.Type()) } - h := ecHash(key.Curve).New() + h := ecHash(k.Curve).New() h.Write(data) digest := h.Sum(nil) @@ -635,7 +636,7 @@ func (key *ecdsaPublicKey) Verify(data []byte, sig *Signature) error { return err } - if ecdsa.Verify((*ecdsa.PublicKey)(key), digest, ecSig.R, ecSig.S) { + if ecdsa.Verify((*ecdsa.PublicKey)(k), digest, ecSig.R, ecSig.S) { return nil } return errors.New("ssh: signature did not verify") @@ -758,7 +759,7 @@ func NewPublicKey(key interface{}) (PublicKey, error) { return (*rsaPublicKey)(key), nil case *ecdsa.PublicKey: if !supportedEllipticCurve(key.Curve) { - return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported.") + return nil, errors.New("ssh: only P-256, P-384 and P-521 EC keys are supported") } return (*ecdsaPublicKey)(key), nil case *dsa.PublicKey: diff --git a/vendor/golang.org/x/crypto/ssh/keys_test.go b/vendor/golang.org/x/crypto/ssh/keys_test.go deleted file mode 100644 index 20ab954e2a..0000000000 --- a/vendor/golang.org/x/crypto/ssh/keys_test.go +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright 2014 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 ssh - -import ( - "bytes" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "fmt" - "reflect" - "strings" - "testing" - - "golang.org/x/crypto/ed25519" - "golang.org/x/crypto/ssh/testdata" -) - -func rawKey(pub PublicKey) interface{} { - switch k := pub.(type) { - case *rsaPublicKey: - return (*rsa.PublicKey)(k) - case *dsaPublicKey: - return (*dsa.PublicKey)(k) - case *ecdsaPublicKey: - return (*ecdsa.PublicKey)(k) - case ed25519PublicKey: - return (ed25519.PublicKey)(k) - case *Certificate: - return k - } - panic("unknown key type") -} - -func TestKeyMarshalParse(t *testing.T) { - for _, priv := range testSigners { - pub := priv.PublicKey() - roundtrip, err := ParsePublicKey(pub.Marshal()) - if err != nil { - t.Errorf("ParsePublicKey(%T): %v", pub, err) - } - - k1 := rawKey(pub) - k2 := rawKey(roundtrip) - - if !reflect.DeepEqual(k1, k2) { - t.Errorf("got %#v in roundtrip, want %#v", k2, k1) - } - } -} - -func TestUnsupportedCurves(t *testing.T) { - raw, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader) - if err != nil { - t.Fatalf("GenerateKey: %v", err) - } - - if _, err = NewSignerFromKey(raw); err == nil || !strings.Contains(err.Error(), "only P-256") { - t.Fatalf("NewPrivateKey should not succeed with P-224, got: %v", err) - } - - if _, err = NewPublicKey(&raw.PublicKey); err == nil || !strings.Contains(err.Error(), "only P-256") { - t.Fatalf("NewPublicKey should not succeed with P-224, got: %v", err) - } -} - -func TestNewPublicKey(t *testing.T) { - for _, k := range testSigners { - raw := rawKey(k.PublicKey()) - // Skip certificates, as NewPublicKey does not support them. - if _, ok := raw.(*Certificate); ok { - continue - } - pub, err := NewPublicKey(raw) - if err != nil { - t.Errorf("NewPublicKey(%#v): %v", raw, err) - } - if !reflect.DeepEqual(k.PublicKey(), pub) { - t.Errorf("NewPublicKey(%#v) = %#v, want %#v", raw, pub, k.PublicKey()) - } - } -} - -func TestKeySignVerify(t *testing.T) { - for _, priv := range testSigners { - pub := priv.PublicKey() - - data := []byte("sign me") - sig, err := priv.Sign(rand.Reader, data) - if err != nil { - t.Fatalf("Sign(%T): %v", priv, err) - } - - if err := pub.Verify(data, sig); err != nil { - t.Errorf("publicKey.Verify(%T): %v", priv, err) - } - sig.Blob[5]++ - if err := pub.Verify(data, sig); err == nil { - t.Errorf("publicKey.Verify on broken sig did not fail") - } - } -} - -func TestParseRSAPrivateKey(t *testing.T) { - key := testPrivateKeys["rsa"] - - rsa, ok := key.(*rsa.PrivateKey) - if !ok { - t.Fatalf("got %T, want *rsa.PrivateKey", rsa) - } - - if err := rsa.Validate(); err != nil { - t.Errorf("Validate: %v", err) - } -} - -func TestParseECPrivateKey(t *testing.T) { - key := testPrivateKeys["ecdsa"] - - ecKey, ok := key.(*ecdsa.PrivateKey) - if !ok { - t.Fatalf("got %T, want *ecdsa.PrivateKey", ecKey) - } - - if !validateECPublicKey(ecKey.Curve, ecKey.X, ecKey.Y) { - t.Fatalf("public key does not validate.") - } -} - -// See Issue https://github.com/golang/go/issues/6650. -func TestParseEncryptedPrivateKeysFails(t *testing.T) { - const wantSubstring = "encrypted" - for i, tt := range testdata.PEMEncryptedKeys { - _, err := ParsePrivateKey(tt.PEMBytes) - if err == nil { - t.Errorf("#%d key %s: ParsePrivateKey successfully parsed, expected an error", i, tt.Name) - continue - } - - if !strings.Contains(err.Error(), wantSubstring) { - t.Errorf("#%d key %s: got error %q, want substring %q", i, tt.Name, err, wantSubstring) - } - } -} - -// Parse encrypted private keys with passphrase -func TestParseEncryptedPrivateKeysWithPassphrase(t *testing.T) { - data := []byte("sign me") - for _, tt := range testdata.PEMEncryptedKeys { - s, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte(tt.EncryptionKey)) - if err != nil { - t.Fatalf("ParsePrivateKeyWithPassphrase returned error: %s", err) - continue - } - sig, err := s.Sign(rand.Reader, data) - if err != nil { - t.Fatalf("dsa.Sign: %v", err) - } - if err := s.PublicKey().Verify(data, sig); err != nil { - t.Errorf("Verify failed: %v", err) - } - } - - tt := testdata.PEMEncryptedKeys[0] - _, err := ParsePrivateKeyWithPassphrase(tt.PEMBytes, []byte("incorrect")) - if err != x509.IncorrectPasswordError { - t.Fatalf("got %v want IncorrectPasswordError", err) - } -} - -func TestParseDSA(t *testing.T) { - // We actually exercise the ParsePrivateKey codepath here, as opposed to - // using the ParseRawPrivateKey+NewSignerFromKey path that testdata_test.go - // uses. - s, err := ParsePrivateKey(testdata.PEMBytes["dsa"]) - if err != nil { - t.Fatalf("ParsePrivateKey returned error: %s", err) - } - - data := []byte("sign me") - sig, err := s.Sign(rand.Reader, data) - if err != nil { - t.Fatalf("dsa.Sign: %v", err) - } - - if err := s.PublicKey().Verify(data, sig); err != nil { - t.Errorf("Verify failed: %v", err) - } -} - -// Tests for authorized_keys parsing. - -// getTestKey returns a public key, and its base64 encoding. -func getTestKey() (PublicKey, string) { - k := testPublicKeys["rsa"] - - b := &bytes.Buffer{} - e := base64.NewEncoder(base64.StdEncoding, b) - e.Write(k.Marshal()) - e.Close() - - return k, b.String() -} - -func TestMarshalParsePublicKey(t *testing.T) { - pub, pubSerialized := getTestKey() - line := fmt.Sprintf("%s %s user@host", pub.Type(), pubSerialized) - - authKeys := MarshalAuthorizedKey(pub) - actualFields := strings.Fields(string(authKeys)) - if len(actualFields) == 0 { - t.Fatalf("failed authKeys: %v", authKeys) - } - - // drop the comment - expectedFields := strings.Fields(line)[0:2] - - if !reflect.DeepEqual(actualFields, expectedFields) { - t.Errorf("got %v, expected %v", actualFields, expectedFields) - } - - actPub, _, _, _, err := ParseAuthorizedKey([]byte(line)) - if err != nil { - t.Fatalf("cannot parse %v: %v", line, err) - } - if !reflect.DeepEqual(actPub, pub) { - t.Errorf("got %v, expected %v", actPub, pub) - } -} - -type authResult struct { - pubKey PublicKey - options []string - comments string - rest string - ok bool -} - -func testAuthorizedKeys(t *testing.T, authKeys []byte, expected []authResult) { - rest := authKeys - var values []authResult - for len(rest) > 0 { - var r authResult - var err error - r.pubKey, r.comments, r.options, rest, err = ParseAuthorizedKey(rest) - r.ok = (err == nil) - t.Log(err) - r.rest = string(rest) - values = append(values, r) - } - - if !reflect.DeepEqual(values, expected) { - t.Errorf("got %#v, expected %#v", values, expected) - } -} - -func TestAuthorizedKeyBasic(t *testing.T) { - pub, pubSerialized := getTestKey() - line := "ssh-rsa " + pubSerialized + " user@host" - testAuthorizedKeys(t, []byte(line), - []authResult{ - {pub, nil, "user@host", "", true}, - }) -} - -func TestAuth(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithOptions := []string{ - `# comments to ignore before any keys...`, - ``, - `env="HOME=/home/root",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`, - `# comments to ignore, along with a blank line`, - ``, - `env="HOME=/home/root2" ssh-rsa ` + pubSerialized + ` user2@host2`, - ``, - `# more comments, plus a invalid entry`, - `ssh-rsa data-that-will-not-parse user@host3`, - } - for _, eol := range []string{"\n", "\r\n"} { - authOptions := strings.Join(authWithOptions, eol) - rest2 := strings.Join(authWithOptions[3:], eol) - rest3 := strings.Join(authWithOptions[6:], eol) - testAuthorizedKeys(t, []byte(authOptions), []authResult{ - {pub, []string{`env="HOME=/home/root"`, "no-port-forwarding"}, "user@host", rest2, true}, - {pub, []string{`env="HOME=/home/root2"`}, "user2@host2", rest3, true}, - {nil, nil, "", "", false}, - }) - } -} - -func TestAuthWithQuotedSpaceInEnv(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithQuotedSpaceInEnv := []byte(`env="HOME=/home/root dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`) - testAuthorizedKeys(t, []byte(authWithQuotedSpaceInEnv), []authResult{ - {pub, []string{`env="HOME=/home/root dir"`, "no-port-forwarding"}, "user@host", "", true}, - }) -} - -func TestAuthWithQuotedCommaInEnv(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithQuotedCommaInEnv := []byte(`env="HOME=/home/root,dir",no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host`) - testAuthorizedKeys(t, []byte(authWithQuotedCommaInEnv), []authResult{ - {pub, []string{`env="HOME=/home/root,dir"`, "no-port-forwarding"}, "user@host", "", true}, - }) -} - -func TestAuthWithQuotedQuoteInEnv(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithQuotedQuoteInEnv := []byte(`env="HOME=/home/\"root dir",no-port-forwarding` + "\t" + `ssh-rsa` + "\t" + pubSerialized + ` user@host`) - authWithDoubleQuotedQuote := []byte(`no-port-forwarding,env="HOME=/home/ \"root dir\"" ssh-rsa ` + pubSerialized + "\t" + `user@host`) - testAuthorizedKeys(t, []byte(authWithQuotedQuoteInEnv), []authResult{ - {pub, []string{`env="HOME=/home/\"root dir"`, "no-port-forwarding"}, "user@host", "", true}, - }) - - testAuthorizedKeys(t, []byte(authWithDoubleQuotedQuote), []authResult{ - {pub, []string{"no-port-forwarding", `env="HOME=/home/ \"root dir\""`}, "user@host", "", true}, - }) -} - -func TestAuthWithInvalidSpace(t *testing.T) { - _, pubSerialized := getTestKey() - authWithInvalidSpace := []byte(`env="HOME=/home/root dir", no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host -#more to follow but still no valid keys`) - testAuthorizedKeys(t, []byte(authWithInvalidSpace), []authResult{ - {nil, nil, "", "", false}, - }) -} - -func TestAuthWithMissingQuote(t *testing.T) { - pub, pubSerialized := getTestKey() - authWithMissingQuote := []byte(`env="HOME=/home/root,no-port-forwarding ssh-rsa ` + pubSerialized + ` user@host -env="HOME=/home/root",shared-control ssh-rsa ` + pubSerialized + ` user@host`) - - testAuthorizedKeys(t, []byte(authWithMissingQuote), []authResult{ - {pub, []string{`env="HOME=/home/root"`, `shared-control`}, "user@host", "", true}, - }) -} - -func TestInvalidEntry(t *testing.T) { - authInvalid := []byte(`ssh-rsa`) - _, _, _, _, err := ParseAuthorizedKey(authInvalid) - if err == nil { - t.Errorf("got valid entry for %q", authInvalid) - } -} - -var knownHostsParseTests = []struct { - input string - err string - - marker string - comment string - hosts []string - rest string -}{ - { - "", - "EOF", - - "", "", nil, "", - }, - { - "# Just a comment", - "EOF", - - "", "", nil, "", - }, - { - " \t ", - "EOF", - - "", "", nil, "", - }, - { - "localhost ssh-rsa {RSAPUB}", - "", - - "", "", []string{"localhost"}, "", - }, - { - "localhost\tssh-rsa {RSAPUB}", - "", - - "", "", []string{"localhost"}, "", - }, - { - "localhost\tssh-rsa {RSAPUB}\tcomment comment", - "", - - "", "comment comment", []string{"localhost"}, "", - }, - { - "localhost\tssh-rsa {RSAPUB}\tcomment comment\n", - "", - - "", "comment comment", []string{"localhost"}, "", - }, - { - "localhost\tssh-rsa {RSAPUB}\tcomment comment\r\n", - "", - - "", "comment comment", []string{"localhost"}, "", - }, - { - "localhost\tssh-rsa {RSAPUB}\tcomment comment\r\nnext line", - "", - - "", "comment comment", []string{"localhost"}, "next line", - }, - { - "localhost,[host2:123]\tssh-rsa {RSAPUB}\tcomment comment", - "", - - "", "comment comment", []string{"localhost", "[host2:123]"}, "", - }, - { - "@marker \tlocalhost,[host2:123]\tssh-rsa {RSAPUB}", - "", - - "marker", "", []string{"localhost", "[host2:123]"}, "", - }, - { - "@marker \tlocalhost,[host2:123]\tssh-rsa aabbccdd", - "short read", - - "", "", nil, "", - }, -} - -func TestKnownHostsParsing(t *testing.T) { - rsaPub, rsaPubSerialized := getTestKey() - - for i, test := range knownHostsParseTests { - var expectedKey PublicKey - const rsaKeyToken = "{RSAPUB}" - - input := test.input - if strings.Contains(input, rsaKeyToken) { - expectedKey = rsaPub - input = strings.Replace(test.input, rsaKeyToken, rsaPubSerialized, -1) - } - - marker, hosts, pubKey, comment, rest, err := ParseKnownHosts([]byte(input)) - if err != nil { - if len(test.err) == 0 { - t.Errorf("#%d: unexpectedly failed with %q", i, err) - } else if !strings.Contains(err.Error(), test.err) { - t.Errorf("#%d: expected error containing %q, but got %q", i, test.err, err) - } - continue - } else if len(test.err) != 0 { - t.Errorf("#%d: succeeded but expected error including %q", i, test.err) - continue - } - - if !reflect.DeepEqual(expectedKey, pubKey) { - t.Errorf("#%d: expected key %#v, but got %#v", i, expectedKey, pubKey) - } - - if marker != test.marker { - t.Errorf("#%d: expected marker %q, but got %q", i, test.marker, marker) - } - - if comment != test.comment { - t.Errorf("#%d: expected comment %q, but got %q", i, test.comment, comment) - } - - if !reflect.DeepEqual(test.hosts, hosts) { - t.Errorf("#%d: expected hosts %#v, but got %#v", i, test.hosts, hosts) - } - - if rest := string(rest); rest != test.rest { - t.Errorf("#%d: expected remaining input to be %q, but got %q", i, test.rest, rest) - } - } -} - -func TestFingerprintLegacyMD5(t *testing.T) { - pub, _ := getTestKey() - fingerprint := FingerprintLegacyMD5(pub) - want := "fb:61:6d:1a:e3:f0:95:45:3c:a0:79:be:4a:93:63:66" // ssh-keygen -lf -E md5 rsa - if fingerprint != want { - t.Errorf("got fingerprint %q want %q", fingerprint, want) - } -} - -func TestFingerprintSHA256(t *testing.T) { - pub, _ := getTestKey() - fingerprint := FingerprintSHA256(pub) - want := "SHA256:Anr3LjZK8YVpjrxu79myrW9Hrb/wpcMNpVvTq/RcBm8" // ssh-keygen -lf rsa - if fingerprint != want { - t.Errorf("got fingerprint %q want %q", fingerprint, want) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/mempipe_test.go b/vendor/golang.org/x/crypto/ssh/mempipe_test.go deleted file mode 100644 index 8697cd6140..0000000000 --- a/vendor/golang.org/x/crypto/ssh/mempipe_test.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "io" - "sync" - "testing" -) - -// An in-memory packetConn. It is safe to call Close and writePacket -// from different goroutines. -type memTransport struct { - eof bool - pending [][]byte - write *memTransport - sync.Mutex - *sync.Cond -} - -func (t *memTransport) readPacket() ([]byte, error) { - t.Lock() - defer t.Unlock() - for { - if len(t.pending) > 0 { - r := t.pending[0] - t.pending = t.pending[1:] - return r, nil - } - if t.eof { - return nil, io.EOF - } - t.Cond.Wait() - } -} - -func (t *memTransport) closeSelf() error { - t.Lock() - defer t.Unlock() - if t.eof { - return io.EOF - } - t.eof = true - t.Cond.Broadcast() - return nil -} - -func (t *memTransport) Close() error { - err := t.write.closeSelf() - t.closeSelf() - return err -} - -func (t *memTransport) writePacket(p []byte) error { - t.write.Lock() - defer t.write.Unlock() - if t.write.eof { - return io.EOF - } - c := make([]byte, len(p)) - copy(c, p) - t.write.pending = append(t.write.pending, c) - t.write.Cond.Signal() - return nil -} - -func memPipe() (a, b packetConn) { - t1 := memTransport{} - t2 := memTransport{} - t1.write = &t2 - t2.write = &t1 - t1.Cond = sync.NewCond(&t1.Mutex) - t2.Cond = sync.NewCond(&t2.Mutex) - return &t1, &t2 -} - -func TestMemPipe(t *testing.T) { - a, b := memPipe() - if err := a.writePacket([]byte{42}); err != nil { - t.Fatalf("writePacket: %v", err) - } - if err := a.Close(); err != nil { - t.Fatal("Close: ", err) - } - p, err := b.readPacket() - if err != nil { - t.Fatal("readPacket: ", err) - } - if len(p) != 1 || p[0] != 42 { - t.Fatalf("got %v, want {42}", p) - } - p, err = b.readPacket() - if err != io.EOF { - t.Fatalf("got %v, %v, want EOF", p, err) - } -} - -func TestDoubleClose(t *testing.T) { - a, _ := memPipe() - err := a.Close() - if err != nil { - t.Errorf("Close: %v", err) - } - err = a.Close() - if err != io.EOF { - t.Errorf("expect EOF on double close.") - } -} diff --git a/vendor/golang.org/x/crypto/ssh/messages.go b/vendor/golang.org/x/crypto/ssh/messages.go index e6ecd3afa5..08d2811730 100644 --- a/vendor/golang.org/x/crypto/ssh/messages.go +++ b/vendor/golang.org/x/crypto/ssh/messages.go @@ -23,10 +23,6 @@ const ( msgUnimplemented = 3 msgDebug = 4 msgNewKeys = 21 - - // Standard authentication messages - msgUserAuthSuccess = 52 - msgUserAuthBanner = 53 ) // SSH messages: @@ -137,6 +133,18 @@ type userAuthFailureMsg struct { PartialSuccess bool } +// See RFC 4252, section 5.1 +const msgUserAuthSuccess = 52 + +// See RFC 4252, section 5.4 +const msgUserAuthBanner = 53 + +type userAuthBannerMsg struct { + Message string `sshtype:"53"` + // unused, but required to allow message parsing + Language string +} + // See RFC 4256, section 3.2 const msgUserAuthInfoRequest = 60 const msgUserAuthInfoResponse = 61 @@ -154,7 +162,7 @@ const msgChannelOpen = 90 type channelOpenMsg struct { ChanType string `sshtype:"90"` - PeersId uint32 + PeersID uint32 PeersWindow uint32 MaxPacketSize uint32 TypeSpecificData []byte `ssh:"rest"` @@ -165,7 +173,7 @@ const msgChannelData = 94 // Used for debug print outs of packets. type channelDataMsg struct { - PeersId uint32 `sshtype:"94"` + PeersID uint32 `sshtype:"94"` Length uint32 Rest []byte `ssh:"rest"` } @@ -174,8 +182,8 @@ type channelDataMsg struct { const msgChannelOpenConfirm = 91 type channelOpenConfirmMsg struct { - PeersId uint32 `sshtype:"91"` - MyId uint32 + PeersID uint32 `sshtype:"91"` + MyID uint32 MyWindow uint32 MaxPacketSize uint32 TypeSpecificData []byte `ssh:"rest"` @@ -185,7 +193,7 @@ type channelOpenConfirmMsg struct { const msgChannelOpenFailure = 92 type channelOpenFailureMsg struct { - PeersId uint32 `sshtype:"92"` + PeersID uint32 `sshtype:"92"` Reason RejectionReason Message string Language string @@ -194,7 +202,7 @@ type channelOpenFailureMsg struct { const msgChannelRequest = 98 type channelRequestMsg struct { - PeersId uint32 `sshtype:"98"` + PeersID uint32 `sshtype:"98"` Request string WantReply bool RequestSpecificData []byte `ssh:"rest"` @@ -204,28 +212,28 @@ type channelRequestMsg struct { const msgChannelSuccess = 99 type channelRequestSuccessMsg struct { - PeersId uint32 `sshtype:"99"` + PeersID uint32 `sshtype:"99"` } // See RFC 4254, section 5.4. const msgChannelFailure = 100 type channelRequestFailureMsg struct { - PeersId uint32 `sshtype:"100"` + PeersID uint32 `sshtype:"100"` } // See RFC 4254, section 5.3 const msgChannelClose = 97 type channelCloseMsg struct { - PeersId uint32 `sshtype:"97"` + PeersID uint32 `sshtype:"97"` } // See RFC 4254, section 5.3 const msgChannelEOF = 96 type channelEOFMsg struct { - PeersId uint32 `sshtype:"96"` + PeersID uint32 `sshtype:"96"` } // See RFC 4254, section 4 @@ -255,7 +263,7 @@ type globalRequestFailureMsg struct { const msgChannelWindowAdjust = 93 type windowAdjustMsg struct { - PeersId uint32 `sshtype:"93"` + PeersID uint32 `sshtype:"93"` AdditionalBytes uint32 } diff --git a/vendor/golang.org/x/crypto/ssh/messages_test.go b/vendor/golang.org/x/crypto/ssh/messages_test.go deleted file mode 100644 index e79076412a..0000000000 --- a/vendor/golang.org/x/crypto/ssh/messages_test.go +++ /dev/null @@ -1,288 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "math/big" - "math/rand" - "reflect" - "testing" - "testing/quick" -) - -var intLengthTests = []struct { - val, length int -}{ - {0, 4 + 0}, - {1, 4 + 1}, - {127, 4 + 1}, - {128, 4 + 2}, - {-1, 4 + 1}, -} - -func TestIntLength(t *testing.T) { - for _, test := range intLengthTests { - v := new(big.Int).SetInt64(int64(test.val)) - length := intLength(v) - if length != test.length { - t.Errorf("For %d, got length %d but expected %d", test.val, length, test.length) - } - } -} - -type msgAllTypes struct { - Bool bool `sshtype:"21"` - Array [16]byte - Uint64 uint64 - Uint32 uint32 - Uint8 uint8 - String string - Strings []string - Bytes []byte - Int *big.Int - Rest []byte `ssh:"rest"` -} - -func (t *msgAllTypes) Generate(rand *rand.Rand, size int) reflect.Value { - m := &msgAllTypes{} - m.Bool = rand.Intn(2) == 1 - randomBytes(m.Array[:], rand) - m.Uint64 = uint64(rand.Int63n(1<<63 - 1)) - m.Uint32 = uint32(rand.Intn((1 << 31) - 1)) - m.Uint8 = uint8(rand.Intn(1 << 8)) - m.String = string(m.Array[:]) - m.Strings = randomNameList(rand) - m.Bytes = m.Array[:] - m.Int = randomInt(rand) - m.Rest = m.Array[:] - return reflect.ValueOf(m) -} - -func TestMarshalUnmarshal(t *testing.T) { - rand := rand.New(rand.NewSource(0)) - iface := &msgAllTypes{} - ty := reflect.ValueOf(iface).Type() - - n := 100 - if testing.Short() { - n = 5 - } - for j := 0; j < n; j++ { - v, ok := quick.Value(ty, rand) - if !ok { - t.Errorf("failed to create value") - break - } - - m1 := v.Elem().Interface() - m2 := iface - - marshaled := Marshal(m1) - if err := Unmarshal(marshaled, m2); err != nil { - t.Errorf("Unmarshal %#v: %s", m1, err) - break - } - - if !reflect.DeepEqual(v.Interface(), m2) { - t.Errorf("got: %#v\nwant:%#v\n%x", m2, m1, marshaled) - break - } - } -} - -func TestUnmarshalEmptyPacket(t *testing.T) { - var b []byte - var m channelRequestSuccessMsg - if err := Unmarshal(b, &m); err == nil { - t.Fatalf("unmarshal of empty slice succeeded") - } -} - -func TestUnmarshalUnexpectedPacket(t *testing.T) { - type S struct { - I uint32 `sshtype:"43"` - S string - B bool - } - - s := S{11, "hello", true} - packet := Marshal(s) - packet[0] = 42 - roundtrip := S{} - err := Unmarshal(packet, &roundtrip) - if err == nil { - t.Fatal("expected error, not nil") - } -} - -func TestMarshalPtr(t *testing.T) { - s := struct { - S string - }{"hello"} - - m1 := Marshal(s) - m2 := Marshal(&s) - if !bytes.Equal(m1, m2) { - t.Errorf("got %q, want %q for marshaled pointer", m2, m1) - } -} - -func TestBareMarshalUnmarshal(t *testing.T) { - type S struct { - I uint32 - S string - B bool - } - - s := S{42, "hello", true} - packet := Marshal(s) - roundtrip := S{} - Unmarshal(packet, &roundtrip) - - if !reflect.DeepEqual(s, roundtrip) { - t.Errorf("got %#v, want %#v", roundtrip, s) - } -} - -func TestBareMarshal(t *testing.T) { - type S2 struct { - I uint32 - } - s := S2{42} - packet := Marshal(s) - i, rest, ok := parseUint32(packet) - if len(rest) > 0 || !ok { - t.Errorf("parseInt(%q): parse error", packet) - } - if i != s.I { - t.Errorf("got %d, want %d", i, s.I) - } -} - -func TestUnmarshalShortKexInitPacket(t *testing.T) { - // This used to panic. - // Issue 11348 - packet := []byte{0x14, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0xff, 0xff, 0xff, 0xff} - kim := &kexInitMsg{} - if err := Unmarshal(packet, kim); err == nil { - t.Error("truncated packet unmarshaled without error") - } -} - -func TestMarshalMultiTag(t *testing.T) { - var res struct { - A uint32 `sshtype:"1|2"` - } - - good1 := struct { - A uint32 `sshtype:"1"` - }{ - 1, - } - good2 := struct { - A uint32 `sshtype:"2"` - }{ - 1, - } - - if e := Unmarshal(Marshal(good1), &res); e != nil { - t.Errorf("error unmarshaling multipart tag: %v", e) - } - - if e := Unmarshal(Marshal(good2), &res); e != nil { - t.Errorf("error unmarshaling multipart tag: %v", e) - } - - bad1 := struct { - A uint32 `sshtype:"3"` - }{ - 1, - } - if e := Unmarshal(Marshal(bad1), &res); e == nil { - t.Errorf("bad struct unmarshaled without error") - } -} - -func randomBytes(out []byte, rand *rand.Rand) { - for i := 0; i < len(out); i++ { - out[i] = byte(rand.Int31()) - } -} - -func randomNameList(rand *rand.Rand) []string { - ret := make([]string, rand.Int31()&15) - for i := range ret { - s := make([]byte, 1+(rand.Int31()&15)) - for j := range s { - s[j] = 'a' + uint8(rand.Int31()&15) - } - ret[i] = string(s) - } - return ret -} - -func randomInt(rand *rand.Rand) *big.Int { - return new(big.Int).SetInt64(int64(int32(rand.Uint32()))) -} - -func (*kexInitMsg) Generate(rand *rand.Rand, size int) reflect.Value { - ki := &kexInitMsg{} - randomBytes(ki.Cookie[:], rand) - ki.KexAlgos = randomNameList(rand) - ki.ServerHostKeyAlgos = randomNameList(rand) - ki.CiphersClientServer = randomNameList(rand) - ki.CiphersServerClient = randomNameList(rand) - ki.MACsClientServer = randomNameList(rand) - ki.MACsServerClient = randomNameList(rand) - ki.CompressionClientServer = randomNameList(rand) - ki.CompressionServerClient = randomNameList(rand) - ki.LanguagesClientServer = randomNameList(rand) - ki.LanguagesServerClient = randomNameList(rand) - if rand.Int31()&1 == 1 { - ki.FirstKexFollows = true - } - return reflect.ValueOf(ki) -} - -func (*kexDHInitMsg) Generate(rand *rand.Rand, size int) reflect.Value { - dhi := &kexDHInitMsg{} - dhi.X = randomInt(rand) - return reflect.ValueOf(dhi) -} - -var ( - _kexInitMsg = new(kexInitMsg).Generate(rand.New(rand.NewSource(0)), 10).Elem().Interface() - _kexDHInitMsg = new(kexDHInitMsg).Generate(rand.New(rand.NewSource(0)), 10).Elem().Interface() - - _kexInit = Marshal(_kexInitMsg) - _kexDHInit = Marshal(_kexDHInitMsg) -) - -func BenchmarkMarshalKexInitMsg(b *testing.B) { - for i := 0; i < b.N; i++ { - Marshal(_kexInitMsg) - } -} - -func BenchmarkUnmarshalKexInitMsg(b *testing.B) { - m := new(kexInitMsg) - for i := 0; i < b.N; i++ { - Unmarshal(_kexInit, m) - } -} - -func BenchmarkMarshalKexDHInitMsg(b *testing.B) { - for i := 0; i < b.N; i++ { - Marshal(_kexDHInitMsg) - } -} - -func BenchmarkUnmarshalKexDHInitMsg(b *testing.B) { - m := new(kexDHInitMsg) - for i := 0; i < b.N; i++ { - Unmarshal(_kexDHInit, m) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/mux.go b/vendor/golang.org/x/crypto/ssh/mux.go index 27a527c106..f19016270e 100644 --- a/vendor/golang.org/x/crypto/ssh/mux.go +++ b/vendor/golang.org/x/crypto/ssh/mux.go @@ -278,7 +278,7 @@ func (m *mux) handleChannelOpen(packet []byte) error { if msg.MaxPacketSize < minPacketLength || msg.MaxPacketSize > 1<<31 { failMsg := channelOpenFailureMsg{ - PeersId: msg.PeersId, + PeersID: msg.PeersID, Reason: ConnectionFailed, Message: "invalid request", Language: "en_US.UTF-8", @@ -287,7 +287,7 @@ func (m *mux) handleChannelOpen(packet []byte) error { } c := m.newChannel(msg.ChanType, channelInbound, msg.TypeSpecificData) - c.remoteId = msg.PeersId + c.remoteId = msg.PeersID c.maxRemotePayload = msg.MaxPacketSize c.remoteWin.add(msg.PeersWindow) m.incomingChannels <- c @@ -313,7 +313,7 @@ func (m *mux) openChannel(chanType string, extra []byte) (*channel, error) { PeersWindow: ch.myWindow, MaxPacketSize: ch.maxIncomingPayload, TypeSpecificData: extra, - PeersId: ch.localId, + PeersID: ch.localId, } if err := m.sendMessage(open); err != nil { return nil, err diff --git a/vendor/golang.org/x/crypto/ssh/mux_test.go b/vendor/golang.org/x/crypto/ssh/mux_test.go deleted file mode 100644 index 25d2181d62..0000000000 --- a/vendor/golang.org/x/crypto/ssh/mux_test.go +++ /dev/null @@ -1,505 +0,0 @@ -// Copyright 2013 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 ssh - -import ( - "io" - "io/ioutil" - "sync" - "testing" -) - -func muxPair() (*mux, *mux) { - a, b := memPipe() - - s := newMux(a) - c := newMux(b) - - return s, c -} - -// Returns both ends of a channel, and the mux for the the 2nd -// channel. -func channelPair(t *testing.T) (*channel, *channel, *mux) { - c, s := muxPair() - - res := make(chan *channel, 1) - go func() { - newCh, ok := <-s.incomingChannels - if !ok { - t.Fatalf("No incoming channel") - } - if newCh.ChannelType() != "chan" { - t.Fatalf("got type %q want chan", newCh.ChannelType()) - } - ch, _, err := newCh.Accept() - if err != nil { - t.Fatalf("Accept %v", err) - } - res <- ch.(*channel) - }() - - ch, err := c.openChannel("chan", nil) - if err != nil { - t.Fatalf("OpenChannel: %v", err) - } - - return <-res, ch, c -} - -// Test that stderr and stdout can be addressed from different -// goroutines. This is intended for use with the race detector. -func TestMuxChannelExtendedThreadSafety(t *testing.T) { - writer, reader, mux := channelPair(t) - defer writer.Close() - defer reader.Close() - defer mux.Close() - - var wr, rd sync.WaitGroup - magic := "hello world" - - wr.Add(2) - go func() { - io.WriteString(writer, magic) - wr.Done() - }() - go func() { - io.WriteString(writer.Stderr(), magic) - wr.Done() - }() - - rd.Add(2) - go func() { - c, err := ioutil.ReadAll(reader) - if string(c) != magic { - t.Fatalf("stdout read got %q, want %q (error %s)", c, magic, err) - } - rd.Done() - }() - go func() { - c, err := ioutil.ReadAll(reader.Stderr()) - if string(c) != magic { - t.Fatalf("stderr read got %q, want %q (error %s)", c, magic, err) - } - rd.Done() - }() - - wr.Wait() - writer.CloseWrite() - rd.Wait() -} - -func TestMuxReadWrite(t *testing.T) { - s, c, mux := channelPair(t) - defer s.Close() - defer c.Close() - defer mux.Close() - - magic := "hello world" - magicExt := "hello stderr" - go func() { - _, err := s.Write([]byte(magic)) - if err != nil { - t.Fatalf("Write: %v", err) - } - _, err = s.Extended(1).Write([]byte(magicExt)) - if err != nil { - t.Fatalf("Write: %v", err) - } - err = s.Close() - if err != nil { - t.Fatalf("Close: %v", err) - } - }() - - var buf [1024]byte - n, err := c.Read(buf[:]) - if err != nil { - t.Fatalf("server Read: %v", err) - } - got := string(buf[:n]) - if got != magic { - t.Fatalf("server: got %q want %q", got, magic) - } - - n, err = c.Extended(1).Read(buf[:]) - if err != nil { - t.Fatalf("server Read: %v", err) - } - - got = string(buf[:n]) - if got != magicExt { - t.Fatalf("server: got %q want %q", got, magic) - } -} - -func TestMuxChannelOverflow(t *testing.T) { - reader, writer, mux := channelPair(t) - defer reader.Close() - defer writer.Close() - defer mux.Close() - - wDone := make(chan int, 1) - go func() { - if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { - t.Errorf("could not fill window: %v", err) - } - writer.Write(make([]byte, 1)) - wDone <- 1 - }() - writer.remoteWin.waitWriterBlocked() - - // Send 1 byte. - packet := make([]byte, 1+4+4+1) - packet[0] = msgChannelData - marshalUint32(packet[1:], writer.remoteId) - marshalUint32(packet[5:], uint32(1)) - packet[9] = 42 - - if err := writer.mux.conn.writePacket(packet); err != nil { - t.Errorf("could not send packet") - } - if _, err := reader.SendRequest("hello", true, nil); err == nil { - t.Errorf("SendRequest succeeded.") - } - <-wDone -} - -func TestMuxChannelCloseWriteUnblock(t *testing.T) { - reader, writer, mux := channelPair(t) - defer reader.Close() - defer writer.Close() - defer mux.Close() - - wDone := make(chan int, 1) - go func() { - if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { - t.Errorf("could not fill window: %v", err) - } - if _, err := writer.Write(make([]byte, 1)); err != io.EOF { - t.Errorf("got %v, want EOF for unblock write", err) - } - wDone <- 1 - }() - - writer.remoteWin.waitWriterBlocked() - reader.Close() - <-wDone -} - -func TestMuxConnectionCloseWriteUnblock(t *testing.T) { - reader, writer, mux := channelPair(t) - defer reader.Close() - defer writer.Close() - defer mux.Close() - - wDone := make(chan int, 1) - go func() { - if _, err := writer.Write(make([]byte, channelWindowSize)); err != nil { - t.Errorf("could not fill window: %v", err) - } - if _, err := writer.Write(make([]byte, 1)); err != io.EOF { - t.Errorf("got %v, want EOF for unblock write", err) - } - wDone <- 1 - }() - - writer.remoteWin.waitWriterBlocked() - mux.Close() - <-wDone -} - -func TestMuxReject(t *testing.T) { - client, server := muxPair() - defer server.Close() - defer client.Close() - - go func() { - ch, ok := <-server.incomingChannels - if !ok { - t.Fatalf("Accept") - } - if ch.ChannelType() != "ch" || string(ch.ExtraData()) != "extra" { - t.Fatalf("unexpected channel: %q, %q", ch.ChannelType(), ch.ExtraData()) - } - ch.Reject(RejectionReason(42), "message") - }() - - ch, err := client.openChannel("ch", []byte("extra")) - if ch != nil { - t.Fatal("openChannel not rejected") - } - - ocf, ok := err.(*OpenChannelError) - if !ok { - t.Errorf("got %#v want *OpenChannelError", err) - } else if ocf.Reason != 42 || ocf.Message != "message" { - t.Errorf("got %#v, want {Reason: 42, Message: %q}", ocf, "message") - } - - want := "ssh: rejected: unknown reason 42 (message)" - if err.Error() != want { - t.Errorf("got %q, want %q", err.Error(), want) - } -} - -func TestMuxChannelRequest(t *testing.T) { - client, server, mux := channelPair(t) - defer server.Close() - defer client.Close() - defer mux.Close() - - var received int - var wg sync.WaitGroup - wg.Add(1) - go func() { - for r := range server.incomingRequests { - received++ - r.Reply(r.Type == "yes", nil) - } - wg.Done() - }() - _, err := client.SendRequest("yes", false, nil) - if err != nil { - t.Fatalf("SendRequest: %v", err) - } - ok, err := client.SendRequest("yes", true, nil) - if err != nil { - t.Fatalf("SendRequest: %v", err) - } - - if !ok { - t.Errorf("SendRequest(yes): %v", ok) - - } - - ok, err = client.SendRequest("no", true, nil) - if err != nil { - t.Fatalf("SendRequest: %v", err) - } - if ok { - t.Errorf("SendRequest(no): %v", ok) - - } - - client.Close() - wg.Wait() - - if received != 3 { - t.Errorf("got %d requests, want %d", received, 3) - } -} - -func TestMuxGlobalRequest(t *testing.T) { - clientMux, serverMux := muxPair() - defer serverMux.Close() - defer clientMux.Close() - - var seen bool - go func() { - for r := range serverMux.incomingRequests { - seen = seen || r.Type == "peek" - if r.WantReply { - err := r.Reply(r.Type == "yes", - append([]byte(r.Type), r.Payload...)) - if err != nil { - t.Errorf("AckRequest: %v", err) - } - } - } - }() - - _, _, err := clientMux.SendRequest("peek", false, nil) - if err != nil { - t.Errorf("SendRequest: %v", err) - } - - ok, data, err := clientMux.SendRequest("yes", true, []byte("a")) - if !ok || string(data) != "yesa" || err != nil { - t.Errorf("SendRequest(\"yes\", true, \"a\"): %v %v %v", - ok, data, err) - } - if ok, data, err := clientMux.SendRequest("yes", true, []byte("a")); !ok || string(data) != "yesa" || err != nil { - t.Errorf("SendRequest(\"yes\", true, \"a\"): %v %v %v", - ok, data, err) - } - - if ok, data, err := clientMux.SendRequest("no", true, []byte("a")); ok || string(data) != "noa" || err != nil { - t.Errorf("SendRequest(\"no\", true, \"a\"): %v %v %v", - ok, data, err) - } - - if !seen { - t.Errorf("never saw 'peek' request") - } -} - -func TestMuxGlobalRequestUnblock(t *testing.T) { - clientMux, serverMux := muxPair() - defer serverMux.Close() - defer clientMux.Close() - - result := make(chan error, 1) - go func() { - _, _, err := clientMux.SendRequest("hello", true, nil) - result <- err - }() - - <-serverMux.incomingRequests - serverMux.conn.Close() - err := <-result - - if err != io.EOF { - t.Errorf("want EOF, got %v", io.EOF) - } -} - -func TestMuxChannelRequestUnblock(t *testing.T) { - a, b, connB := channelPair(t) - defer a.Close() - defer b.Close() - defer connB.Close() - - result := make(chan error, 1) - go func() { - _, err := a.SendRequest("hello", true, nil) - result <- err - }() - - <-b.incomingRequests - connB.conn.Close() - err := <-result - - if err != io.EOF { - t.Errorf("want EOF, got %v", err) - } -} - -func TestMuxCloseChannel(t *testing.T) { - r, w, mux := channelPair(t) - defer mux.Close() - defer r.Close() - defer w.Close() - - result := make(chan error, 1) - go func() { - var b [1024]byte - _, err := r.Read(b[:]) - result <- err - }() - if err := w.Close(); err != nil { - t.Errorf("w.Close: %v", err) - } - - if _, err := w.Write([]byte("hello")); err != io.EOF { - t.Errorf("got err %v, want io.EOF after Close", err) - } - - if err := <-result; err != io.EOF { - t.Errorf("got %v (%T), want io.EOF", err, err) - } -} - -func TestMuxCloseWriteChannel(t *testing.T) { - r, w, mux := channelPair(t) - defer mux.Close() - - result := make(chan error, 1) - go func() { - var b [1024]byte - _, err := r.Read(b[:]) - result <- err - }() - if err := w.CloseWrite(); err != nil { - t.Errorf("w.CloseWrite: %v", err) - } - - if _, err := w.Write([]byte("hello")); err != io.EOF { - t.Errorf("got err %v, want io.EOF after CloseWrite", err) - } - - if err := <-result; err != io.EOF { - t.Errorf("got %v (%T), want io.EOF", err, err) - } -} - -func TestMuxInvalidRecord(t *testing.T) { - a, b := muxPair() - defer a.Close() - defer b.Close() - - packet := make([]byte, 1+4+4+1) - packet[0] = msgChannelData - marshalUint32(packet[1:], 29348723 /* invalid channel id */) - marshalUint32(packet[5:], 1) - packet[9] = 42 - - a.conn.writePacket(packet) - go a.SendRequest("hello", false, nil) - // 'a' wrote an invalid packet, so 'b' has exited. - req, ok := <-b.incomingRequests - if ok { - t.Errorf("got request %#v after receiving invalid packet", req) - } -} - -func TestZeroWindowAdjust(t *testing.T) { - a, b, mux := channelPair(t) - defer a.Close() - defer b.Close() - defer mux.Close() - - go func() { - io.WriteString(a, "hello") - // bogus adjust. - a.sendMessage(windowAdjustMsg{}) - io.WriteString(a, "world") - a.Close() - }() - - want := "helloworld" - c, _ := ioutil.ReadAll(b) - if string(c) != want { - t.Errorf("got %q want %q", c, want) - } -} - -func TestMuxMaxPacketSize(t *testing.T) { - a, b, mux := channelPair(t) - defer a.Close() - defer b.Close() - defer mux.Close() - - large := make([]byte, a.maxRemotePayload+1) - packet := make([]byte, 1+4+4+1+len(large)) - packet[0] = msgChannelData - marshalUint32(packet[1:], a.remoteId) - marshalUint32(packet[5:], uint32(len(large))) - packet[9] = 42 - - if err := a.mux.conn.writePacket(packet); err != nil { - t.Errorf("could not send packet") - } - - go a.SendRequest("hello", false, nil) - - _, ok := <-b.incomingRequests - if ok { - t.Errorf("connection still alive after receiving large packet.") - } -} - -// Don't ship code with debug=true. -func TestDebug(t *testing.T) { - if debugMux { - t.Error("mux debug switched on") - } - if debugHandshake { - t.Error("handshake debug switched on") - } - if debugTransport { - t.Error("transport debug switched on") - } -} diff --git a/vendor/golang.org/x/crypto/ssh/server.go b/vendor/golang.org/x/crypto/ssh/server.go index 8a78b7ca0f..d0f4825319 100644 --- a/vendor/golang.org/x/crypto/ssh/server.go +++ b/vendor/golang.org/x/crypto/ssh/server.go @@ -95,6 +95,10 @@ type ServerConfig struct { // Note that RFC 4253 section 4.2 requires that this string start with // "SSH-2.0-". ServerVersion string + + // BannerCallback, if present, is called and the return string is sent to + // the client after key exchange completed but before authentication. + BannerCallback func(conn ConnMetadata) string } // AddHostKey adds a private key as a host key. If an existing host @@ -162,6 +166,9 @@ type ServerConn struct { // unsuccessful, it closes the connection and returns an error. The // Request and NewChannel channels must be serviced, or the connection // will hang. +// +// The returned error may be of type *ServerAuthError for +// authentication errors. func NewServerConn(c net.Conn, config *ServerConfig) (*ServerConn, <-chan NewChannel, <-chan *Request, error) { fullConf := *config fullConf.SetDefaults() @@ -252,7 +259,7 @@ func (s *connection) serverHandshake(config *ServerConfig) (*Permissions, error) func isAcceptableAlgo(algo string) bool { switch algo { case KeyAlgoRSA, KeyAlgoDSA, KeyAlgoECDSA256, KeyAlgoECDSA384, KeyAlgoECDSA521, KeyAlgoED25519, - CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01: + CertAlgoRSAv01, CertAlgoDSAv01, CertAlgoECDSA256v01, CertAlgoECDSA384v01, CertAlgoECDSA521v01, CertAlgoED25519v01: return true } return false @@ -288,12 +295,13 @@ func checkSourceAddress(addr net.Addr, sourceAddrs string) error { return fmt.Errorf("ssh: remote address %v is not allowed because of source-address restriction", addr) } -// ServerAuthError implements the error interface. It appends any authentication -// errors that may occur, and is returned if all of the authentication methods -// provided by the user failed to authenticate. +// ServerAuthError represents server authentication errors and is +// sometimes returned by NewServerConn. It appends any authentication +// errors that may occur, and is returned if all of the authentication +// methods provided by the user failed to authenticate. type ServerAuthError struct { // Errors contains authentication errors returned by the authentication - // callback methods. + // callback methods. The first entry is typically ErrNoAuth. Errors []error } @@ -305,6 +313,13 @@ func (l ServerAuthError) Error() string { return "[" + strings.Join(errs, ", ") + "]" } +// ErrNoAuth is the error value returned if no +// authentication method has been passed yet. This happens as a normal +// part of the authentication loop, since the client first tries +// 'none' authentication to discover available methods. +// It is returned in ServerAuthError.Errors from NewServerConn. +var ErrNoAuth = errors.New("ssh: no auth passed yet") + func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, error) { sessionID := s.transport.getSessionID() var cache pubKeyCache @@ -312,6 +327,7 @@ func (s *connection) serverAuthenticate(config *ServerConfig) (*Permissions, err authFailures := 0 var authErrs []error + var displayedBanner bool userAuthLoop: for { @@ -343,8 +359,22 @@ userAuthLoop: } s.user = userAuthReq.User + + if !displayedBanner && config.BannerCallback != nil { + displayedBanner = true + msg := config.BannerCallback(s) + if msg != "" { + bannerMsg := &userAuthBannerMsg{ + Message: msg, + } + if err := s.transport.writePacket(Marshal(bannerMsg)); err != nil { + return nil, err + } + } + } + perms = nil - authErr := errors.New("no auth passed yet") + authErr := ErrNoAuth switch userAuthReq.Method { case "none": diff --git a/vendor/golang.org/x/crypto/ssh/session.go b/vendor/golang.org/x/crypto/ssh/session.go index cc06e03f5c..d3321f6b78 100644 --- a/vendor/golang.org/x/crypto/ssh/session.go +++ b/vendor/golang.org/x/crypto/ssh/session.go @@ -406,7 +406,7 @@ func (s *Session) Wait() error { s.stdinPipeWriter.Close() } var copyError error - for _ = range s.copyFuncs { + for range s.copyFuncs { if err := <-s.errors; err != nil && copyError == nil { copyError = err } diff --git a/vendor/golang.org/x/crypto/ssh/session_test.go b/vendor/golang.org/x/crypto/ssh/session_test.go deleted file mode 100644 index 7dce6dd699..0000000000 --- a/vendor/golang.org/x/crypto/ssh/session_test.go +++ /dev/null @@ -1,774 +0,0 @@ -// Copyright 2011 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 ssh - -// Session tests. - -import ( - "bytes" - crypto_rand "crypto/rand" - "errors" - "io" - "io/ioutil" - "math/rand" - "net" - "testing" - - "golang.org/x/crypto/ssh/terminal" -) - -type serverType func(Channel, <-chan *Request, *testing.T) - -// dial constructs a new test server and returns a *ClientConn. -func dial(handler serverType, t *testing.T) *Client { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - - go func() { - defer c1.Close() - conf := ServerConfig{ - NoClientAuth: true, - } - conf.AddHostKey(testSigners["rsa"]) - - _, chans, reqs, err := NewServerConn(c1, &conf) - if err != nil { - t.Fatalf("Unable to handshake: %v", err) - } - go DiscardRequests(reqs) - - for newCh := range chans { - if newCh.ChannelType() != "session" { - newCh.Reject(UnknownChannelType, "unknown channel type") - continue - } - - ch, inReqs, err := newCh.Accept() - if err != nil { - t.Errorf("Accept: %v", err) - continue - } - go func() { - handler(ch, inReqs, t) - }() - } - }() - - config := &ClientConfig{ - User: "testuser", - HostKeyCallback: InsecureIgnoreHostKey(), - } - - conn, chans, reqs, err := NewClientConn(c2, "", config) - if err != nil { - t.Fatalf("unable to dial remote side: %v", err) - } - - return NewClient(conn, chans, reqs) -} - -// Test a simple string is returned to session.Stdout. -func TestSessionShell(t *testing.T) { - conn := dial(shellHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - stdout := new(bytes.Buffer) - session.Stdout = stdout - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %s", err) - } - if err := session.Wait(); err != nil { - t.Fatalf("Remote command did not exit cleanly: %v", err) - } - actual := stdout.String() - if actual != "golang" { - t.Fatalf("Remote shell did not return expected string: expected=golang, actual=%s", actual) - } -} - -// TODO(dfc) add support for Std{in,err}Pipe when the Server supports it. - -// Test a simple string is returned via StdoutPipe. -func TestSessionStdoutPipe(t *testing.T) { - conn := dial(shellHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - stdout, err := session.StdoutPipe() - if err != nil { - t.Fatalf("Unable to request StdoutPipe(): %v", err) - } - var buf bytes.Buffer - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - done := make(chan bool, 1) - go func() { - if _, err := io.Copy(&buf, stdout); err != nil { - t.Errorf("Copy of stdout failed: %v", err) - } - done <- true - }() - if err := session.Wait(); err != nil { - t.Fatalf("Remote command did not exit cleanly: %v", err) - } - <-done - actual := buf.String() - if actual != "golang" { - t.Fatalf("Remote shell did not return expected string: expected=golang, actual=%s", actual) - } -} - -// Test that a simple string is returned via the Output helper, -// and that stderr is discarded. -func TestSessionOutput(t *testing.T) { - conn := dial(fixedOutputHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - - buf, err := session.Output("") // cmd is ignored by fixedOutputHandler - if err != nil { - t.Error("Remote command did not exit cleanly:", err) - } - w := "this-is-stdout." - g := string(buf) - if g != w { - t.Error("Remote command did not return expected string:") - t.Logf("want %q", w) - t.Logf("got %q", g) - } -} - -// Test that both stdout and stderr are returned -// via the CombinedOutput helper. -func TestSessionCombinedOutput(t *testing.T) { - conn := dial(fixedOutputHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - - buf, err := session.CombinedOutput("") // cmd is ignored by fixedOutputHandler - if err != nil { - t.Error("Remote command did not exit cleanly:", err) - } - const stdout = "this-is-stdout." - const stderr = "this-is-stderr." - g := string(buf) - if g != stdout+stderr && g != stderr+stdout { - t.Error("Remote command did not return expected string:") - t.Logf("want %q, or %q", stdout+stderr, stderr+stdout) - t.Logf("got %q", g) - } -} - -// Test non-0 exit status is returned correctly. -func TestExitStatusNonZero(t *testing.T) { - conn := dial(exitStatusNonZeroHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.ExitStatus() != 15 { - t.Fatalf("expected command to exit with 15 but got %v", e.ExitStatus()) - } -} - -// Test 0 exit status is returned correctly. -func TestExitStatusZero(t *testing.T) { - conn := dial(exitStatusZeroHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err != nil { - t.Fatalf("expected nil but got %v", err) - } -} - -// Test exit signal and status are both returned correctly. -func TestExitSignalAndStatus(t *testing.T) { - conn := dial(exitSignalAndStatusHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.Signal() != "TERM" || e.ExitStatus() != 15 { - t.Fatalf("expected command to exit with signal TERM and status 15 but got signal %s and status %v", e.Signal(), e.ExitStatus()) - } -} - -// Test exit signal and status are both returned correctly. -func TestKnownExitSignalOnly(t *testing.T) { - conn := dial(exitSignalHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.Signal() != "TERM" || e.ExitStatus() != 143 { - t.Fatalf("expected command to exit with signal TERM and status 143 but got signal %s and status %v", e.Signal(), e.ExitStatus()) - } -} - -// Test exit signal and status are both returned correctly. -func TestUnknownExitSignal(t *testing.T) { - conn := dial(exitSignalUnknownHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - e, ok := err.(*ExitError) - if !ok { - t.Fatalf("expected *ExitError but got %T", err) - } - if e.Signal() != "SYS" || e.ExitStatus() != 128 { - t.Fatalf("expected command to exit with signal SYS and status 128 but got signal %s and status %v", e.Signal(), e.ExitStatus()) - } -} - -func TestExitWithoutStatusOrSignal(t *testing.T) { - conn := dial(exitWithoutSignalOrStatus, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatalf("Unable to request new session: %v", err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err == nil { - t.Fatalf("expected command to fail but it didn't") - } - if _, ok := err.(*ExitMissingError); !ok { - t.Fatalf("got %T want *ExitMissingError", err) - } -} - -// windowTestBytes is the number of bytes that we'll send to the SSH server. -const windowTestBytes = 16000 * 200 - -// TestServerWindow writes random data to the server. The server is expected to echo -// the same data back, which is compared against the original. -func TestServerWindow(t *testing.T) { - origBuf := bytes.NewBuffer(make([]byte, 0, windowTestBytes)) - io.CopyN(origBuf, crypto_rand.Reader, windowTestBytes) - origBytes := origBuf.Bytes() - - conn := dial(echoHandler, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatal(err) - } - defer session.Close() - result := make(chan []byte) - - go func() { - defer close(result) - echoedBuf := bytes.NewBuffer(make([]byte, 0, windowTestBytes)) - serverStdout, err := session.StdoutPipe() - if err != nil { - t.Errorf("StdoutPipe failed: %v", err) - return - } - n, err := copyNRandomly("stdout", echoedBuf, serverStdout, windowTestBytes) - if err != nil && err != io.EOF { - t.Errorf("Read only %d bytes from server, expected %d: %v", n, windowTestBytes, err) - } - result <- echoedBuf.Bytes() - }() - - serverStdin, err := session.StdinPipe() - if err != nil { - t.Fatalf("StdinPipe failed: %v", err) - } - written, err := copyNRandomly("stdin", serverStdin, origBuf, windowTestBytes) - if err != nil { - t.Fatalf("failed to copy origBuf to serverStdin: %v", err) - } - if written != windowTestBytes { - t.Fatalf("Wrote only %d of %d bytes to server", written, windowTestBytes) - } - - echoedBytes := <-result - - if !bytes.Equal(origBytes, echoedBytes) { - t.Fatalf("Echoed buffer differed from original, orig %d, echoed %d", len(origBytes), len(echoedBytes)) - } -} - -// Verify the client can handle a keepalive packet from the server. -func TestClientHandlesKeepalives(t *testing.T) { - conn := dial(channelKeepaliveSender, t) - defer conn.Close() - session, err := conn.NewSession() - if err != nil { - t.Fatal(err) - } - defer session.Close() - if err := session.Shell(); err != nil { - t.Fatalf("Unable to execute command: %v", err) - } - err = session.Wait() - if err != nil { - t.Fatalf("expected nil but got: %v", err) - } -} - -type exitStatusMsg struct { - Status uint32 -} - -type exitSignalMsg struct { - Signal string - CoreDumped bool - Errmsg string - Lang string -} - -func handleTerminalRequests(in <-chan *Request) { - for req := range in { - ok := false - switch req.Type { - case "shell": - ok = true - if len(req.Payload) > 0 { - // We don't accept any commands, only the default shell. - ok = false - } - case "env": - ok = true - } - req.Reply(ok, nil) - } -} - -func newServerShell(ch Channel, in <-chan *Request, prompt string) *terminal.Terminal { - term := terminal.NewTerminal(ch, prompt) - go handleTerminalRequests(in) - return term -} - -func exitStatusZeroHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - // this string is returned to stdout - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendStatus(0, ch, t) -} - -func exitStatusNonZeroHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendStatus(15, ch, t) -} - -func exitSignalAndStatusHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendStatus(15, ch, t) - sendSignal("TERM", ch, t) -} - -func exitSignalHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendSignal("TERM", ch, t) -} - -func exitSignalUnknownHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - sendSignal("SYS", ch, t) -} - -func exitWithoutSignalOrStatus(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) -} - -func shellHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - // this string is returned to stdout - shell := newServerShell(ch, in, "golang") - readLine(shell, t) - sendStatus(0, ch, t) -} - -// Ignores the command, writes fixed strings to stderr and stdout. -// Strings are "this-is-stdout." and "this-is-stderr.". -func fixedOutputHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - _, err := ch.Read(nil) - - req, ok := <-in - if !ok { - t.Fatalf("error: expected channel request, got: %#v", err) - return - } - - // ignore request, always send some text - req.Reply(true, nil) - - _, err = io.WriteString(ch, "this-is-stdout.") - if err != nil { - t.Fatalf("error writing on server: %v", err) - } - _, err = io.WriteString(ch.Stderr(), "this-is-stderr.") - if err != nil { - t.Fatalf("error writing on server: %v", err) - } - sendStatus(0, ch, t) -} - -func readLine(shell *terminal.Terminal, t *testing.T) { - if _, err := shell.ReadLine(); err != nil && err != io.EOF { - t.Errorf("unable to read line: %v", err) - } -} - -func sendStatus(status uint32, ch Channel, t *testing.T) { - msg := exitStatusMsg{ - Status: status, - } - if _, err := ch.SendRequest("exit-status", false, Marshal(&msg)); err != nil { - t.Errorf("unable to send status: %v", err) - } -} - -func sendSignal(signal string, ch Channel, t *testing.T) { - sig := exitSignalMsg{ - Signal: signal, - CoreDumped: false, - Errmsg: "Process terminated", - Lang: "en-GB-oed", - } - if _, err := ch.SendRequest("exit-signal", false, Marshal(&sig)); err != nil { - t.Errorf("unable to send signal: %v", err) - } -} - -func discardHandler(ch Channel, t *testing.T) { - defer ch.Close() - io.Copy(ioutil.Discard, ch) -} - -func echoHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - if n, err := copyNRandomly("echohandler", ch, ch, windowTestBytes); err != nil { - t.Errorf("short write, wrote %d, expected %d: %v ", n, windowTestBytes, err) - } -} - -// copyNRandomly copies n bytes from src to dst. It uses a variable, and random, -// buffer size to exercise more code paths. -func copyNRandomly(title string, dst io.Writer, src io.Reader, n int) (int, error) { - var ( - buf = make([]byte, 32*1024) - written int - remaining = n - ) - for remaining > 0 { - l := rand.Intn(1 << 15) - if remaining < l { - l = remaining - } - nr, er := src.Read(buf[:l]) - nw, ew := dst.Write(buf[:nr]) - remaining -= nw - written += nw - if ew != nil { - return written, ew - } - if nr != nw { - return written, io.ErrShortWrite - } - if er != nil && er != io.EOF { - return written, er - } - } - return written, nil -} - -func channelKeepaliveSender(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - shell := newServerShell(ch, in, "> ") - readLine(shell, t) - if _, err := ch.SendRequest("keepalive@openssh.com", true, nil); err != nil { - t.Errorf("unable to send channel keepalive request: %v", err) - } - sendStatus(0, ch, t) -} - -func TestClientWriteEOF(t *testing.T) { - conn := dial(simpleEchoHandler, t) - defer conn.Close() - - session, err := conn.NewSession() - if err != nil { - t.Fatal(err) - } - defer session.Close() - stdin, err := session.StdinPipe() - if err != nil { - t.Fatalf("StdinPipe failed: %v", err) - } - stdout, err := session.StdoutPipe() - if err != nil { - t.Fatalf("StdoutPipe failed: %v", err) - } - - data := []byte(`0000`) - _, err = stdin.Write(data) - if err != nil { - t.Fatalf("Write failed: %v", err) - } - stdin.Close() - - res, err := ioutil.ReadAll(stdout) - if err != nil { - t.Fatalf("Read failed: %v", err) - } - - if !bytes.Equal(data, res) { - t.Fatalf("Read differed from write, wrote: %v, read: %v", data, res) - } -} - -func simpleEchoHandler(ch Channel, in <-chan *Request, t *testing.T) { - defer ch.Close() - data, err := ioutil.ReadAll(ch) - if err != nil { - t.Errorf("handler read error: %v", err) - } - _, err = ch.Write(data) - if err != nil { - t.Errorf("handler write error: %v", err) - } -} - -func TestSessionID(t *testing.T) { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - serverID := make(chan []byte, 1) - clientID := make(chan []byte, 1) - - serverConf := &ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["ecdsa"]) - clientConf := &ClientConfig{ - HostKeyCallback: InsecureIgnoreHostKey(), - User: "user", - } - - go func() { - conn, chans, reqs, err := NewServerConn(c1, serverConf) - if err != nil { - t.Fatalf("server handshake: %v", err) - } - serverID <- conn.SessionID() - go DiscardRequests(reqs) - for ch := range chans { - ch.Reject(Prohibited, "") - } - }() - - go func() { - conn, chans, reqs, err := NewClientConn(c2, "", clientConf) - if err != nil { - t.Fatalf("client handshake: %v", err) - } - clientID <- conn.SessionID() - go DiscardRequests(reqs) - for ch := range chans { - ch.Reject(Prohibited, "") - } - }() - - s := <-serverID - c := <-clientID - if bytes.Compare(s, c) != 0 { - t.Errorf("server session ID (%x) != client session ID (%x)", s, c) - } else if len(s) == 0 { - t.Errorf("client and server SessionID were empty.") - } -} - -type noReadConn struct { - readSeen bool - net.Conn -} - -func (c *noReadConn) Close() error { - return nil -} - -func (c *noReadConn) Read(b []byte) (int, error) { - c.readSeen = true - return 0, errors.New("noReadConn error") -} - -func TestInvalidServerConfiguration(t *testing.T) { - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - serveConn := noReadConn{Conn: c1} - serverConf := &ServerConfig{} - - NewServerConn(&serveConn, serverConf) - if serveConn.readSeen { - t.Fatalf("NewServerConn attempted to Read() from Conn while configuration is missing host key") - } - - serverConf.AddHostKey(testSigners["ecdsa"]) - - NewServerConn(&serveConn, serverConf) - if serveConn.readSeen { - t.Fatalf("NewServerConn attempted to Read() from Conn while configuration is missing authentication method") - } -} - -func TestHostKeyAlgorithms(t *testing.T) { - serverConf := &ServerConfig{ - NoClientAuth: true, - } - serverConf.AddHostKey(testSigners["rsa"]) - serverConf.AddHostKey(testSigners["ecdsa"]) - - connect := func(clientConf *ClientConfig, want string) { - var alg string - clientConf.HostKeyCallback = func(h string, a net.Addr, key PublicKey) error { - alg = key.Type() - return nil - } - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewServerConn(c1, serverConf) - _, _, _, err = NewClientConn(c2, "", clientConf) - if err != nil { - t.Fatalf("NewClientConn: %v", err) - } - if alg != want { - t.Errorf("selected key algorithm %s, want %s", alg, want) - } - } - - // By default, we get the preferred algorithm, which is ECDSA 256. - - clientConf := &ClientConfig{ - HostKeyCallback: InsecureIgnoreHostKey(), - } - connect(clientConf, KeyAlgoECDSA256) - - // Client asks for RSA explicitly. - clientConf.HostKeyAlgorithms = []string{KeyAlgoRSA} - connect(clientConf, KeyAlgoRSA) - - c1, c2, err := netPipe() - if err != nil { - t.Fatalf("netPipe: %v", err) - } - defer c1.Close() - defer c2.Close() - - go NewServerConn(c1, serverConf) - clientConf.HostKeyAlgorithms = []string{"nonexistent-hostkey-algo"} - _, _, _, err = NewClientConn(c2, "", clientConf) - if err == nil { - t.Fatal("succeeded connecting with unknown hostkey algorithm") - } -} diff --git a/vendor/golang.org/x/crypto/ssh/streamlocal.go b/vendor/golang.org/x/crypto/ssh/streamlocal.go index a2dccc64c7..b171b330bc 100644 --- a/vendor/golang.org/x/crypto/ssh/streamlocal.go +++ b/vendor/golang.org/x/crypto/ssh/streamlocal.go @@ -32,6 +32,7 @@ type streamLocalChannelForwardMsg struct { // ListenUnix is similar to ListenTCP but uses a Unix domain socket. func (c *Client) ListenUnix(socketPath string) (net.Listener, error) { + c.handleForwardsOnce.Do(c.handleForwards) m := streamLocalChannelForwardMsg{ socketPath, } diff --git a/vendor/golang.org/x/crypto/ssh/tcpip.go b/vendor/golang.org/x/crypto/ssh/tcpip.go index acf17175df..80d35f5ec1 100644 --- a/vendor/golang.org/x/crypto/ssh/tcpip.go +++ b/vendor/golang.org/x/crypto/ssh/tcpip.go @@ -90,10 +90,19 @@ type channelForwardMsg struct { rport uint32 } +// handleForwards starts goroutines handling forwarded connections. +// It's called on first use by (*Client).ListenTCP to not launch +// goroutines until needed. +func (c *Client) handleForwards() { + go c.forwards.handleChannels(c.HandleChannelOpen("forwarded-tcpip")) + go c.forwards.handleChannels(c.HandleChannelOpen("forwarded-streamlocal@openssh.com")) +} + // ListenTCP requests the remote peer open a listening socket // on laddr. Incoming connections will be available by calling // Accept on the returned net.Listener. func (c *Client) ListenTCP(laddr *net.TCPAddr) (net.Listener, error) { + c.handleForwardsOnce.Do(c.handleForwards) if laddr.Port == 0 && isBrokenOpenSSHVersion(string(c.ServerVersion())) { return c.autoPortListenWorkaround(laddr) } diff --git a/vendor/golang.org/x/crypto/ssh/tcpip_test.go b/vendor/golang.org/x/crypto/ssh/tcpip_test.go deleted file mode 100644 index f1265cb496..0000000000 --- a/vendor/golang.org/x/crypto/ssh/tcpip_test.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2014 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 ssh - -import ( - "testing" -) - -func TestAutoPortListenBroken(t *testing.T) { - broken := "SSH-2.0-OpenSSH_5.9hh11" - works := "SSH-2.0-OpenSSH_6.1" - if !isBrokenOpenSSHVersion(broken) { - t.Errorf("version %q not marked as broken", broken) - } - if isBrokenOpenSSHVersion(works) { - t.Errorf("version %q marked as broken", works) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/terminal/terminal.go b/vendor/golang.org/x/crypto/ssh/terminal/terminal.go index 18379a935b..9a887598ff 100644 --- a/vendor/golang.org/x/crypto/ssh/terminal/terminal.go +++ b/vendor/golang.org/x/crypto/ssh/terminal/terminal.go @@ -617,7 +617,7 @@ func writeWithCRLF(w io.Writer, buf []byte) (n int, err error) { if _, err = w.Write(crlf); err != nil { return n, err } - n += 1 + n++ buf = buf[1:] } } diff --git a/vendor/golang.org/x/crypto/ssh/terminal/terminal_test.go b/vendor/golang.org/x/crypto/ssh/terminal/terminal_test.go deleted file mode 100644 index 901c72ab35..0000000000 --- a/vendor/golang.org/x/crypto/ssh/terminal/terminal_test.go +++ /dev/null @@ -1,350 +0,0 @@ -// Copyright 2011 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 terminal - -import ( - "bytes" - "io" - "os" - "testing" -) - -type MockTerminal struct { - toSend []byte - bytesPerRead int - received []byte -} - -func (c *MockTerminal) Read(data []byte) (n int, err error) { - n = len(data) - if n == 0 { - return - } - if n > len(c.toSend) { - n = len(c.toSend) - } - if n == 0 { - return 0, io.EOF - } - if c.bytesPerRead > 0 && n > c.bytesPerRead { - n = c.bytesPerRead - } - copy(data, c.toSend[:n]) - c.toSend = c.toSend[n:] - return -} - -func (c *MockTerminal) Write(data []byte) (n int, err error) { - c.received = append(c.received, data...) - return len(data), nil -} - -func TestClose(t *testing.T) { - c := &MockTerminal{} - ss := NewTerminal(c, "> ") - line, err := ss.ReadLine() - if line != "" { - t.Errorf("Expected empty line but got: %s", line) - } - if err != io.EOF { - t.Errorf("Error should have been EOF but got: %s", err) - } -} - -var keyPressTests = []struct { - in string - line string - err error - throwAwayLines int -}{ - { - err: io.EOF, - }, - { - in: "\r", - line: "", - }, - { - in: "foo\r", - line: "foo", - }, - { - in: "a\x1b[Cb\r", // right - line: "ab", - }, - { - in: "a\x1b[Db\r", // left - line: "ba", - }, - { - in: "a\177b\r", // backspace - line: "b", - }, - { - in: "\x1b[A\r", // up - }, - { - in: "\x1b[B\r", // down - }, - { - in: "line\x1b[A\x1b[B\r", // up then down - line: "line", - }, - { - in: "line1\rline2\x1b[A\r", // recall previous line. - line: "line1", - throwAwayLines: 1, - }, - { - // recall two previous lines and append. - in: "line1\rline2\rline3\x1b[A\x1b[Axxx\r", - line: "line1xxx", - throwAwayLines: 2, - }, - { - // Ctrl-A to move to beginning of line followed by ^K to kill - // line. - in: "a b \001\013\r", - line: "", - }, - { - // Ctrl-A to move to beginning of line, Ctrl-E to move to end, - // finally ^K to kill nothing. - in: "a b \001\005\013\r", - line: "a b ", - }, - { - in: "\027\r", - line: "", - }, - { - in: "a\027\r", - line: "", - }, - { - in: "a \027\r", - line: "", - }, - { - in: "a b\027\r", - line: "a ", - }, - { - in: "a b \027\r", - line: "a ", - }, - { - in: "one two thr\x1b[D\027\r", - line: "one two r", - }, - { - in: "\013\r", - line: "", - }, - { - in: "a\013\r", - line: "a", - }, - { - in: "ab\x1b[D\013\r", - line: "a", - }, - { - in: "Ξεσκεπάζω\r", - line: "Ξεσκεπάζω", - }, - { - in: "£\r\x1b[A\177\r", // non-ASCII char, enter, up, backspace. - line: "", - throwAwayLines: 1, - }, - { - in: "£\r££\x1b[A\x1b[B\177\r", // non-ASCII char, enter, 2x non-ASCII, up, down, backspace, enter. - line: "£", - throwAwayLines: 1, - }, - { - // Ctrl-D at the end of the line should be ignored. - in: "a\004\r", - line: "a", - }, - { - // a, b, left, Ctrl-D should erase the b. - in: "ab\x1b[D\004\r", - line: "a", - }, - { - // a, b, c, d, left, left, ^U should erase to the beginning of - // the line. - in: "abcd\x1b[D\x1b[D\025\r", - line: "cd", - }, - { - // Bracketed paste mode: control sequences should be returned - // verbatim in paste mode. - in: "abc\x1b[200~de\177f\x1b[201~\177\r", - line: "abcde\177", - }, - { - // Enter in bracketed paste mode should still work. - in: "abc\x1b[200~d\refg\x1b[201~h\r", - line: "efgh", - throwAwayLines: 1, - }, - { - // Lines consisting entirely of pasted data should be indicated as such. - in: "\x1b[200~a\r", - line: "a", - err: ErrPasteIndicator, - }, -} - -func TestKeyPresses(t *testing.T) { - for i, test := range keyPressTests { - for j := 1; j < len(test.in); j++ { - c := &MockTerminal{ - toSend: []byte(test.in), - bytesPerRead: j, - } - ss := NewTerminal(c, "> ") - for k := 0; k < test.throwAwayLines; k++ { - _, err := ss.ReadLine() - if err != nil { - t.Errorf("Throwaway line %d from test %d resulted in error: %s", k, i, err) - } - } - line, err := ss.ReadLine() - if line != test.line { - t.Errorf("Line resulting from test %d (%d bytes per read) was '%s', expected '%s'", i, j, line, test.line) - break - } - if err != test.err { - t.Errorf("Error resulting from test %d (%d bytes per read) was '%v', expected '%v'", i, j, err, test.err) - break - } - } - } -} - -func TestPasswordNotSaved(t *testing.T) { - c := &MockTerminal{ - toSend: []byte("password\r\x1b[A\r"), - bytesPerRead: 1, - } - ss := NewTerminal(c, "> ") - pw, _ := ss.ReadPassword("> ") - if pw != "password" { - t.Fatalf("failed to read password, got %s", pw) - } - line, _ := ss.ReadLine() - if len(line) > 0 { - t.Fatalf("password was saved in history") - } -} - -var setSizeTests = []struct { - width, height int -}{ - {40, 13}, - {80, 24}, - {132, 43}, -} - -func TestTerminalSetSize(t *testing.T) { - for _, setSize := range setSizeTests { - c := &MockTerminal{ - toSend: []byte("password\r\x1b[A\r"), - bytesPerRead: 1, - } - ss := NewTerminal(c, "> ") - ss.SetSize(setSize.width, setSize.height) - pw, _ := ss.ReadPassword("Password: ") - if pw != "password" { - t.Fatalf("failed to read password, got %s", pw) - } - if string(c.received) != "Password: \r\n" { - t.Errorf("failed to set the temporary prompt expected %q, got %q", "Password: ", c.received) - } - } -} - -func TestReadPasswordLineEnd(t *testing.T) { - var tests = []struct { - input string - want string - }{ - {"\n", ""}, - {"\r\n", ""}, - {"test\r\n", "test"}, - {"testtesttesttes\n", "testtesttesttes"}, - {"testtesttesttes\r\n", "testtesttesttes"}, - {"testtesttesttesttest\n", "testtesttesttesttest"}, - {"testtesttesttesttest\r\n", "testtesttesttesttest"}, - } - for _, test := range tests { - buf := new(bytes.Buffer) - if _, err := buf.WriteString(test.input); err != nil { - t.Fatal(err) - } - - have, err := readPasswordLine(buf) - if err != nil { - t.Errorf("readPasswordLine(%q) failed: %v", test.input, err) - continue - } - if string(have) != test.want { - t.Errorf("readPasswordLine(%q) returns %q, but %q is expected", test.input, string(have), test.want) - continue - } - - if _, err = buf.WriteString(test.input); err != nil { - t.Fatal(err) - } - have, err = readPasswordLine(buf) - if err != nil { - t.Errorf("readPasswordLine(%q) failed: %v", test.input, err) - continue - } - if string(have) != test.want { - t.Errorf("readPasswordLine(%q) returns %q, but %q is expected", test.input, string(have), test.want) - continue - } - } -} - -func TestMakeRawState(t *testing.T) { - fd := int(os.Stdout.Fd()) - if !IsTerminal(fd) { - t.Skip("stdout is not a terminal; skipping test") - } - - st, err := GetState(fd) - if err != nil { - t.Fatalf("failed to get terminal state from GetState: %s", err) - } - defer Restore(fd, st) - raw, err := MakeRaw(fd) - if err != nil { - t.Fatalf("failed to get terminal state from MakeRaw: %s", err) - } - - if *st != *raw { - t.Errorf("states do not match; was %v, expected %v", raw, st) - } -} - -func TestOutputNewlines(t *testing.T) { - // \n should be changed to \r\n in terminal output. - buf := new(bytes.Buffer) - term := NewTerminal(buf, ">") - - term.Write([]byte("1\n2\n")) - output := string(buf.Bytes()) - const expected = "1\r\n2\r\n" - - if output != expected { - t.Errorf("incorrect output: was %q, expected %q", output, expected) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/terminal/util.go b/vendor/golang.org/x/crypto/ssh/terminal/util.go index 02dad484e5..731c89a284 100644 --- a/vendor/golang.org/x/crypto/ssh/terminal/util.go +++ b/vendor/golang.org/x/crypto/ssh/terminal/util.go @@ -108,9 +108,7 @@ func ReadPassword(fd int) ([]byte, error) { return nil, err } - defer func() { - unix.IoctlSetTermios(fd, ioctlWriteTermios, termios) - }() + defer unix.IoctlSetTermios(fd, ioctlWriteTermios, termios) return readPasswordLine(passwordReader(fd)) } diff --git a/vendor/golang.org/x/crypto/ssh/terminal/util_solaris.go b/vendor/golang.org/x/crypto/ssh/terminal/util_solaris.go index a2e1b57dc1..9e41b9f43f 100644 --- a/vendor/golang.org/x/crypto/ssh/terminal/util_solaris.go +++ b/vendor/golang.org/x/crypto/ssh/terminal/util_solaris.go @@ -14,7 +14,7 @@ import ( // State contains the state of a terminal. type State struct { - state *unix.Termios + termios unix.Termios } // IsTerminal returns true if the given file descriptor is a terminal. @@ -75,47 +75,43 @@ func ReadPassword(fd int) ([]byte, error) { // restored. // see http://cr.illumos.org/~webrev/andy_js/1060/ func MakeRaw(fd int) (*State, error) { - oldTermiosPtr, err := unix.IoctlGetTermios(fd, unix.TCGETS) + termios, err := unix.IoctlGetTermios(fd, unix.TCGETS) if err != nil { return nil, err } - oldTermios := *oldTermiosPtr - - newTermios := oldTermios - newTermios.Iflag &^= syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON - newTermios.Oflag &^= syscall.OPOST - newTermios.Lflag &^= syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN - newTermios.Cflag &^= syscall.CSIZE | syscall.PARENB - newTermios.Cflag |= syscall.CS8 - newTermios.Cc[unix.VMIN] = 1 - newTermios.Cc[unix.VTIME] = 0 - - if err := unix.IoctlSetTermios(fd, unix.TCSETS, &newTermios); err != nil { + + oldState := State{termios: *termios} + + termios.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON + termios.Oflag &^= unix.OPOST + termios.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN + termios.Cflag &^= unix.CSIZE | unix.PARENB + termios.Cflag |= unix.CS8 + termios.Cc[unix.VMIN] = 1 + termios.Cc[unix.VTIME] = 0 + + if err := unix.IoctlSetTermios(fd, unix.TCSETS, termios); err != nil { return nil, err } - return &State{ - state: oldTermiosPtr, - }, nil + return &oldState, nil } // Restore restores the terminal connected to the given file descriptor to a // previous state. func Restore(fd int, oldState *State) error { - return unix.IoctlSetTermios(fd, unix.TCSETS, oldState.state) + return unix.IoctlSetTermios(fd, unix.TCSETS, &oldState.termios) } // GetState returns the current state of a terminal which may be useful to // restore the terminal after a signal. func GetState(fd int) (*State, error) { - oldTermiosPtr, err := unix.IoctlGetTermios(fd, unix.TCGETS) + termios, err := unix.IoctlGetTermios(fd, unix.TCGETS) if err != nil { return nil, err } - return &State{ - state: oldTermiosPtr, - }, nil + return &State{termios: *termios}, nil } // GetSize returns the dimensions of the given terminal. diff --git a/vendor/golang.org/x/crypto/ssh/terminal/util_windows.go b/vendor/golang.org/x/crypto/ssh/terminal/util_windows.go index 60979ccd00..8618955df7 100644 --- a/vendor/golang.org/x/crypto/ssh/terminal/util_windows.go +++ b/vendor/golang.org/x/crypto/ssh/terminal/util_windows.go @@ -17,6 +17,8 @@ package terminal import ( + "os" + "golang.org/x/sys/windows" ) @@ -71,13 +73,6 @@ func GetSize(fd int) (width, height int, err error) { return int(info.Size.X), int(info.Size.Y), nil } -// passwordReader is an io.Reader that reads from a specific Windows HANDLE. -type passwordReader int - -func (r passwordReader) Read(buf []byte) (int, error) { - return windows.Read(windows.Handle(r), buf) -} - // ReadPassword reads a line of input from a terminal without local echo. This // is commonly used for inputting passwords and other sensitive data. The slice // returned does not include the \n. @@ -94,9 +89,15 @@ func ReadPassword(fd int) ([]byte, error) { return nil, err } - defer func() { - windows.SetConsoleMode(windows.Handle(fd), old) - }() + defer windows.SetConsoleMode(windows.Handle(fd), old) + + var h windows.Handle + p, _ := windows.GetCurrentProcess() + if err := windows.DuplicateHandle(p, windows.Handle(fd), p, &h, 0, false, windows.DUPLICATE_SAME_ACCESS); err != nil { + return nil, err + } - return readPasswordLine(passwordReader(fd)) + f := os.NewFile(uintptr(h), "stdin") + defer f.Close() + return readPasswordLine(f) } diff --git a/vendor/golang.org/x/crypto/ssh/testdata_test.go b/vendor/golang.org/x/crypto/ssh/testdata_test.go deleted file mode 100644 index 2da8c79dc6..0000000000 --- a/vendor/golang.org/x/crypto/ssh/testdata_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2014 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. - -// IMPLEMENTATION NOTE: To avoid a package loop, this file is in three places: -// ssh/, ssh/agent, and ssh/test/. It should be kept in sync across all three -// instances. - -package ssh - -import ( - "crypto/rand" - "fmt" - - "golang.org/x/crypto/ssh/testdata" -) - -var ( - testPrivateKeys map[string]interface{} - testSigners map[string]Signer - testPublicKeys map[string]PublicKey -) - -func init() { - var err error - - n := len(testdata.PEMBytes) - testPrivateKeys = make(map[string]interface{}, n) - testSigners = make(map[string]Signer, n) - testPublicKeys = make(map[string]PublicKey, n) - for t, k := range testdata.PEMBytes { - testPrivateKeys[t], err = ParseRawPrivateKey(k) - if err != nil { - panic(fmt.Sprintf("Unable to parse test key %s: %v", t, err)) - } - testSigners[t], err = NewSignerFromKey(testPrivateKeys[t]) - if err != nil { - panic(fmt.Sprintf("Unable to create signer for test key %s: %v", t, err)) - } - testPublicKeys[t] = testSigners[t].PublicKey() - } - - // Create a cert and sign it for use in tests. - testCert := &Certificate{ - Nonce: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil - ValidPrincipals: []string{"gopher1", "gopher2"}, // increases test coverage - ValidAfter: 0, // unix epoch - ValidBefore: CertTimeInfinity, // The end of currently representable time. - Reserved: []byte{}, // To pass reflect.DeepEqual after marshal & parse, this must be non-nil - Key: testPublicKeys["ecdsa"], - SignatureKey: testPublicKeys["rsa"], - Permissions: Permissions{ - CriticalOptions: map[string]string{}, - Extensions: map[string]string{}, - }, - } - testCert.SignCert(rand.Reader, testSigners["rsa"]) - testPrivateKeys["cert"] = testPrivateKeys["ecdsa"] - testSigners["cert"], err = NewCertSigner(testCert, testSigners["ecdsa"]) - if err != nil { - panic(fmt.Sprintf("Unable to create certificate signer: %v", err)) - } -} diff --git a/vendor/golang.org/x/crypto/ssh/transport.go b/vendor/golang.org/x/crypto/ssh/transport.go index ab2b88765a..f6fae1db46 100644 --- a/vendor/golang.org/x/crypto/ssh/transport.go +++ b/vendor/golang.org/x/crypto/ssh/transport.go @@ -6,6 +6,7 @@ package ssh import ( "bufio" + "bytes" "errors" "io" "log" @@ -76,17 +77,17 @@ type connectionState struct { // both directions are triggered by reading and writing a msgNewKey packet // respectively. func (t *transport) prepareKeyChange(algs *algorithms, kexResult *kexResult) error { - if ciph, err := newPacketCipher(t.reader.dir, algs.r, kexResult); err != nil { + ciph, err := newPacketCipher(t.reader.dir, algs.r, kexResult) + if err != nil { return err - } else { - t.reader.pendingKeyChange <- ciph } + t.reader.pendingKeyChange <- ciph - if ciph, err := newPacketCipher(t.writer.dir, algs.w, kexResult); err != nil { + ciph, err = newPacketCipher(t.writer.dir, algs.w, kexResult) + if err != nil { return err - } else { - t.writer.pendingKeyChange <- ciph } + t.writer.pendingKeyChange <- ciph return nil } @@ -139,7 +140,7 @@ func (s *connectionState) readPacket(r *bufio.Reader) ([]byte, error) { case cipher := <-s.pendingKeyChange: s.packetCipher = cipher default: - return nil, errors.New("ssh: got bogus newkeys message.") + return nil, errors.New("ssh: got bogus newkeys message") } case msgDisconnect: @@ -232,52 +233,22 @@ var ( clientKeys = direction{[]byte{'A'}, []byte{'C'}, []byte{'E'}} ) -// generateKeys generates key material for IV, MAC and encryption. -func generateKeys(d direction, algs directionAlgorithms, kex *kexResult) (iv, key, macKey []byte) { +// setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as +// described in RFC 4253, section 6.4. direction should either be serverKeys +// (to setup server->client keys) or clientKeys (for client->server keys). +func newPacketCipher(d direction, algs directionAlgorithms, kex *kexResult) (packetCipher, error) { cipherMode := cipherModes[algs.Cipher] macMode := macModes[algs.MAC] - iv = make([]byte, cipherMode.ivSize) - key = make([]byte, cipherMode.keySize) - macKey = make([]byte, macMode.keySize) + iv := make([]byte, cipherMode.ivSize) + key := make([]byte, cipherMode.keySize) + macKey := make([]byte, macMode.keySize) generateKeyMaterial(iv, d.ivTag, kex) generateKeyMaterial(key, d.keyTag, kex) generateKeyMaterial(macKey, d.macKeyTag, kex) - return -} - -// setupKeys sets the cipher and MAC keys from kex.K, kex.H and sessionId, as -// described in RFC 4253, section 6.4. direction should either be serverKeys -// (to setup server->client keys) or clientKeys (for client->server keys). -func newPacketCipher(d direction, algs directionAlgorithms, kex *kexResult) (packetCipher, error) { - iv, key, macKey := generateKeys(d, algs, kex) - - if algs.Cipher == gcmCipherID { - return newGCMCipher(iv, key) - } - - if algs.Cipher == aes128cbcID { - return newAESCBCCipher(iv, key, macKey, algs) - } - - if algs.Cipher == tripledescbcID { - return newTripleDESCBCCipher(iv, key, macKey, algs) - } - c := &streamPacketCipher{ - mac: macModes[algs.MAC].new(macKey), - etm: macModes[algs.MAC].etm, - } - c.macResult = make([]byte, c.mac.Size()) - - var err error - c.cipher, err = cipherModes[algs.Cipher].createStream(key, iv) - if err != nil { - return nil, err - } - - return c, nil + return cipherModes[algs.Cipher].create(key, iv, macKey, algs) } // generateKeyMaterial fills out with key material generated from tag, K, H @@ -342,7 +313,7 @@ func readVersion(r io.Reader) ([]byte, error) { var ok bool var buf [1]byte - for len(versionString) < maxVersionStringBytes { + for length := 0; length < maxVersionStringBytes; length++ { _, err := io.ReadFull(r, buf[:]) if err != nil { return nil, err @@ -350,6 +321,13 @@ func readVersion(r io.Reader) ([]byte, error) { // The RFC says that the version should be terminated with \r\n // but several SSH servers actually only send a \n. if buf[0] == '\n' { + if !bytes.HasPrefix(versionString, []byte("SSH-")) { + // RFC 4253 says we need to ignore all version string lines + // except the one containing the SSH version (provided that + // all the lines do not exceed 255 bytes in total). + versionString = versionString[:0] + continue + } ok = true break } diff --git a/vendor/golang.org/x/crypto/ssh/transport_test.go b/vendor/golang.org/x/crypto/ssh/transport_test.go deleted file mode 100644 index 92d83abf93..0000000000 --- a/vendor/golang.org/x/crypto/ssh/transport_test.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2011 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 ssh - -import ( - "bytes" - "crypto/rand" - "encoding/binary" - "strings" - "testing" -) - -func TestReadVersion(t *testing.T) { - longversion := strings.Repeat("SSH-2.0-bla", 50)[:253] - cases := map[string]string{ - "SSH-2.0-bla\r\n": "SSH-2.0-bla", - "SSH-2.0-bla\n": "SSH-2.0-bla", - longversion + "\r\n": longversion, - } - - for in, want := range cases { - result, err := readVersion(bytes.NewBufferString(in)) - if err != nil { - t.Errorf("readVersion(%q): %s", in, err) - } - got := string(result) - if got != want { - t.Errorf("got %q, want %q", got, want) - } - } -} - -func TestReadVersionError(t *testing.T) { - longversion := strings.Repeat("SSH-2.0-bla", 50)[:253] - cases := []string{ - longversion + "too-long\r\n", - } - for _, in := range cases { - if _, err := readVersion(bytes.NewBufferString(in)); err == nil { - t.Errorf("readVersion(%q) should have failed", in) - } - } -} - -func TestExchangeVersionsBasic(t *testing.T) { - v := "SSH-2.0-bla" - buf := bytes.NewBufferString(v + "\r\n") - them, err := exchangeVersions(buf, []byte("xyz")) - if err != nil { - t.Errorf("exchangeVersions: %v", err) - } - - if want := "SSH-2.0-bla"; string(them) != want { - t.Errorf("got %q want %q for our version", them, want) - } -} - -func TestExchangeVersions(t *testing.T) { - cases := []string{ - "not\x000allowed", - "not allowed\n", - } - for _, c := range cases { - buf := bytes.NewBufferString("SSH-2.0-bla\r\n") - if _, err := exchangeVersions(buf, []byte(c)); err == nil { - t.Errorf("exchangeVersions(%q): should have failed", c) - } - } -} - -type closerBuffer struct { - bytes.Buffer -} - -func (b *closerBuffer) Close() error { - return nil -} - -func TestTransportMaxPacketWrite(t *testing.T) { - buf := &closerBuffer{} - tr := newTransport(buf, rand.Reader, true) - huge := make([]byte, maxPacket+1) - err := tr.writePacket(huge) - if err == nil { - t.Errorf("transport accepted write for a huge packet.") - } -} - -func TestTransportMaxPacketReader(t *testing.T) { - var header [5]byte - huge := make([]byte, maxPacket+128) - binary.BigEndian.PutUint32(header[0:], uint32(len(huge))) - // padding. - header[4] = 0 - - buf := &closerBuffer{} - buf.Write(header[:]) - buf.Write(huge) - - tr := newTransport(buf, rand.Reader, true) - _, err := tr.readPacket() - if err == nil { - t.Errorf("transport succeeded reading huge packet.") - } else if !strings.Contains(err.Error(), "large") { - t.Errorf("got %q, should mention %q", err.Error(), "large") - } -} diff --git a/vendor/golang.org/x/net/CONTRIBUTING.md b/vendor/golang.org/x/net/CONTRIBUTING.md index 88dff59bc7..d0485e887a 100644 --- a/vendor/golang.org/x/net/CONTRIBUTING.md +++ b/vendor/golang.org/x/net/CONTRIBUTING.md @@ -4,16 +4,15 @@ Go is an open source project. It is the work of hundreds of contributors. We appreciate your help! - ## Filing issues When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: -1. What version of Go are you using (`go version`)? -2. What operating system and processor architecture are you using? -3. What did you do? -4. What did you expect to see? -5. What did you see instead? +1. What version of Go are you using (`go version`)? +2. What operating system and processor architecture are you using? +3. What did you do? +4. What did you expect to see? +5. What did you see instead? General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. The gophers there will answer or ask you to file an issue if you've tripped over a bug. @@ -23,9 +22,5 @@ The gophers there will answer or ask you to file an issue if you've tripped over Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) before sending patches. -**We do not accept GitHub pull requests** -(we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). - Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file. - diff --git a/vendor/golang.org/x/net/context/context_test.go b/vendor/golang.org/x/net/context/context_test.go deleted file mode 100644 index 62844131bd..0000000000 --- a/vendor/golang.org/x/net/context/context_test.go +++ /dev/null @@ -1,583 +0,0 @@ -// Copyright 2014 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 !go1.7 - -package context - -import ( - "fmt" - "math/rand" - "runtime" - "strings" - "sync" - "testing" - "time" -) - -// otherContext is a Context that's not one of the types defined in context.go. -// This lets us test code paths that differ based on the underlying type of the -// Context. -type otherContext struct { - Context -} - -func TestBackground(t *testing.T) { - c := Background() - if c == nil { - t.Fatalf("Background returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.Background"; got != want { - t.Errorf("Background().String() = %q want %q", got, want) - } -} - -func TestTODO(t *testing.T) { - c := TODO() - if c == nil { - t.Fatalf("TODO returned nil") - } - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - if got, want := fmt.Sprint(c), "context.TODO"; got != want { - t.Errorf("TODO().String() = %q want %q", got, want) - } -} - -func TestWithCancel(t *testing.T) { - c1, cancel := WithCancel(Background()) - - if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want { - t.Errorf("c1.String() = %q want %q", got, want) - } - - o := otherContext{c1} - c2, _ := WithCancel(o) - contexts := []Context{c1, o, c2} - - for i, c := range contexts { - if d := c.Done(); d == nil { - t.Errorf("c[%d].Done() == %v want non-nil", i, d) - } - if e := c.Err(); e != nil { - t.Errorf("c[%d].Err() == %v want nil", i, e) - } - - select { - case x := <-c.Done(): - t.Errorf("<-c.Done() == %v want nothing (it should block)", x) - default: - } - } - - cancel() - time.Sleep(100 * time.Millisecond) // let cancelation propagate - - for i, c := range contexts { - select { - case <-c.Done(): - default: - t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i) - } - if e := c.Err(); e != Canceled { - t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled) - } - } -} - -func TestParentFinishesChild(t *testing.T) { - // Context tree: - // parent -> cancelChild - // parent -> valueChild -> timerChild - parent, cancel := WithCancel(Background()) - cancelChild, stop := WithCancel(parent) - defer stop() - valueChild := WithValue(parent, "key", "value") - timerChild, stop := WithTimeout(valueChild, 10000*time.Hour) - defer stop() - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-cancelChild.Done(): - t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x) - case x := <-timerChild.Done(): - t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x) - case x := <-valueChild.Done(): - t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x) - default: - } - - // The parent's children should contain the two cancelable children. - pc := parent.(*cancelCtx) - cc := cancelChild.(*cancelCtx) - tc := timerChild.(*timerCtx) - pc.mu.Lock() - if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] { - t.Errorf("bad linkage: pc.children = %v, want %v and %v", - pc.children, cc, tc) - } - pc.mu.Unlock() - - if p, ok := parentCancelCtx(cc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc) - } - if p, ok := parentCancelCtx(tc.Context); !ok || p != pc { - t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc) - } - - cancel() - - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children) - } - pc.mu.Unlock() - - // parent and children should all be finished. - check := func(ctx Context, name string) { - select { - case <-ctx.Done(): - default: - t.Errorf("<-%s.Done() blocked, but shouldn't have", name) - } - if e := ctx.Err(); e != Canceled { - t.Errorf("%s.Err() == %v want %v", name, e, Canceled) - } - } - check(parent, "parent") - check(cancelChild, "cancelChild") - check(valueChild, "valueChild") - check(timerChild, "timerChild") - - // WithCancel should return a canceled context on a canceled parent. - precanceledChild := WithValue(parent, "key", "value") - select { - case <-precanceledChild.Done(): - default: - t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have") - } - if e := precanceledChild.Err(); e != Canceled { - t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled) - } -} - -func TestChildFinishesFirst(t *testing.T) { - cancelable, stop := WithCancel(Background()) - defer stop() - for _, parent := range []Context{Background(), cancelable} { - child, cancel := WithCancel(parent) - - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - case x := <-child.Done(): - t.Errorf("<-child.Done() == %v want nothing (it should block)", x) - default: - } - - cc := child.(*cancelCtx) - pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background() - if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) { - t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok) - } - - if pcok { - pc.mu.Lock() - if len(pc.children) != 1 || !pc.children[cc] { - t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc) - } - pc.mu.Unlock() - } - - cancel() - - if pcok { - pc.mu.Lock() - if len(pc.children) != 0 { - t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children) - } - pc.mu.Unlock() - } - - // child should be finished. - select { - case <-child.Done(): - default: - t.Errorf("<-child.Done() blocked, but shouldn't have") - } - if e := child.Err(); e != Canceled { - t.Errorf("child.Err() == %v want %v", e, Canceled) - } - - // parent should not be finished. - select { - case x := <-parent.Done(): - t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) - default: - } - if e := parent.Err(); e != nil { - t.Errorf("parent.Err() == %v want nil", e) - } - } -} - -func testDeadline(c Context, wait time.Duration, t *testing.T) { - select { - case <-time.After(wait): - t.Fatalf("context should have timed out") - case <-c.Done(): - } - if e := c.Err(); e != DeadlineExceeded { - t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded) - } -} - -func TestDeadline(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithDeadline(Background(), time.Now().Add(1*timeUnit)) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 2*timeUnit, t) - - c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit)) - o := otherContext{c} - testDeadline(o, 2*timeUnit, t) - - c, _ = WithDeadline(Background(), time.Now().Add(1*timeUnit)) - o = otherContext{c} - c, _ = WithDeadline(o, time.Now().Add(3*timeUnit)) - testDeadline(c, 2*timeUnit, t) -} - -func TestTimeout(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithTimeout(Background(), 1*timeUnit) - if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { - t.Errorf("c.String() = %q want prefix %q", got, prefix) - } - testDeadline(c, 2*timeUnit, t) - - c, _ = WithTimeout(Background(), 1*timeUnit) - o := otherContext{c} - testDeadline(o, 2*timeUnit, t) - - c, _ = WithTimeout(Background(), 1*timeUnit) - o = otherContext{c} - c, _ = WithTimeout(o, 3*timeUnit) - testDeadline(c, 2*timeUnit, t) -} - -func TestCanceledTimeout(t *testing.T) { - t.Parallel() - const timeUnit = 500 * time.Millisecond - c, _ := WithTimeout(Background(), 2*timeUnit) - o := otherContext{c} - c, cancel := WithTimeout(o, 4*timeUnit) - cancel() - time.Sleep(1 * timeUnit) // let cancelation propagate - select { - case <-c.Done(): - default: - t.Errorf("<-c.Done() blocked, but shouldn't have") - } - if e := c.Err(); e != Canceled { - t.Errorf("c.Err() == %v want %v", e, Canceled) - } -} - -type key1 int -type key2 int - -var k1 = key1(1) -var k2 = key2(1) // same int as k1, different type -var k3 = key2(3) // same type as k2, different int - -func TestValues(t *testing.T) { - check := func(c Context, nm, v1, v2, v3 string) { - if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 { - t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0) - } - if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 { - t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0) - } - if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 { - t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0) - } - } - - c0 := Background() - check(c0, "c0", "", "", "") - - c1 := WithValue(Background(), k1, "c1k1") - check(c1, "c1", "c1k1", "", "") - - if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want { - t.Errorf("c.String() = %q want %q", got, want) - } - - c2 := WithValue(c1, k2, "c2k2") - check(c2, "c2", "c1k1", "c2k2", "") - - c3 := WithValue(c2, k3, "c3k3") - check(c3, "c2", "c1k1", "c2k2", "c3k3") - - c4 := WithValue(c3, k1, nil) - check(c4, "c4", "", "c2k2", "c3k3") - - o0 := otherContext{Background()} - check(o0, "o0", "", "", "") - - o1 := otherContext{WithValue(Background(), k1, "c1k1")} - check(o1, "o1", "c1k1", "", "") - - o2 := WithValue(o1, k2, "o2k2") - check(o2, "o2", "c1k1", "o2k2", "") - - o3 := otherContext{c4} - check(o3, "o3", "", "c2k2", "c3k3") - - o4 := WithValue(o3, k3, nil) - check(o4, "o4", "", "c2k2", "") -} - -func TestAllocs(t *testing.T) { - bg := Background() - for _, test := range []struct { - desc string - f func() - limit float64 - gccgoLimit float64 - }{ - { - desc: "Background()", - f: func() { Background() }, - limit: 0, - gccgoLimit: 0, - }, - { - desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1), - f: func() { - c := WithValue(bg, k1, nil) - c.Value(k1) - }, - limit: 3, - gccgoLimit: 3, - }, - { - desc: "WithTimeout(bg, 15*time.Millisecond)", - f: func() { - c, _ := WithTimeout(bg, 15*time.Millisecond) - <-c.Done() - }, - limit: 8, - gccgoLimit: 16, - }, - { - desc: "WithCancel(bg)", - f: func() { - c, cancel := WithCancel(bg) - cancel() - <-c.Done() - }, - limit: 5, - gccgoLimit: 8, - }, - { - desc: "WithTimeout(bg, 100*time.Millisecond)", - f: func() { - c, cancel := WithTimeout(bg, 100*time.Millisecond) - cancel() - <-c.Done() - }, - limit: 8, - gccgoLimit: 25, - }, - } { - limit := test.limit - if runtime.Compiler == "gccgo" { - // gccgo does not yet do escape analysis. - // TODO(iant): Remove this when gccgo does do escape analysis. - limit = test.gccgoLimit - } - if n := testing.AllocsPerRun(100, test.f); n > limit { - t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit)) - } - } -} - -func TestSimultaneousCancels(t *testing.T) { - root, cancel := WithCancel(Background()) - m := map[Context]CancelFunc{root: cancel} - q := []Context{root} - // Create a tree of contexts. - for len(q) != 0 && len(m) < 100 { - parent := q[0] - q = q[1:] - for i := 0; i < 4; i++ { - ctx, cancel := WithCancel(parent) - m[ctx] = cancel - q = append(q, ctx) - } - } - // Start all the cancels in a random order. - var wg sync.WaitGroup - wg.Add(len(m)) - for _, cancel := range m { - go func(cancel CancelFunc) { - cancel() - wg.Done() - }(cancel) - } - // Wait on all the contexts in a random order. - for ctx := range m { - select { - case <-ctx.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n]) - } - } - // Wait for all the cancel functions to return. - done := make(chan struct{}) - go func() { - wg.Wait() - close(done) - }() - select { - case <-done: - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n]) - } -} - -func TestInterlockedCancels(t *testing.T) { - parent, cancelParent := WithCancel(Background()) - child, cancelChild := WithCancel(parent) - go func() { - parent.Done() - cancelChild() - }() - cancelParent() - select { - case <-child.Done(): - case <-time.After(1 * time.Second): - buf := make([]byte, 10<<10) - n := runtime.Stack(buf, true) - t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n]) - } -} - -func TestLayersCancel(t *testing.T) { - testLayers(t, time.Now().UnixNano(), false) -} - -func TestLayersTimeout(t *testing.T) { - testLayers(t, time.Now().UnixNano(), true) -} - -func testLayers(t *testing.T, seed int64, testTimeout bool) { - rand.Seed(seed) - errorf := func(format string, a ...interface{}) { - t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...) - } - const ( - timeout = 200 * time.Millisecond - minLayers = 30 - ) - type value int - var ( - vals []*value - cancels []CancelFunc - numTimers int - ctx = Background() - ) - for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ { - switch rand.Intn(3) { - case 0: - v := new(value) - ctx = WithValue(ctx, v, v) - vals = append(vals, v) - case 1: - var cancel CancelFunc - ctx, cancel = WithCancel(ctx) - cancels = append(cancels, cancel) - case 2: - var cancel CancelFunc - ctx, cancel = WithTimeout(ctx, timeout) - cancels = append(cancels, cancel) - numTimers++ - } - } - checkValues := func(when string) { - for _, key := range vals { - if val := ctx.Value(key).(*value); key != val { - errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key) - } - } - } - select { - case <-ctx.Done(): - errorf("ctx should not be canceled yet") - default: - } - if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) { - t.Errorf("ctx.String() = %q want prefix %q", s, prefix) - } - t.Log(ctx) - checkValues("before cancel") - if testTimeout { - select { - case <-ctx.Done(): - case <-time.After(timeout + 100*time.Millisecond): - errorf("ctx should have timed out") - } - checkValues("after timeout") - } else { - cancel := cancels[rand.Intn(len(cancels))] - cancel() - select { - case <-ctx.Done(): - default: - errorf("ctx should be canceled") - } - checkValues("after cancel") - } -} - -func TestCancelRemoves(t *testing.T) { - checkChildren := func(when string, ctx Context, want int) { - if got := len(ctx.(*cancelCtx).children); got != want { - t.Errorf("%s: context has %d children, want %d", when, got, want) - } - } - - ctx, _ := WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel := WithCancel(ctx) - checkChildren("with WithCancel child ", ctx, 1) - cancel() - checkChildren("after cancelling WithCancel child", ctx, 0) - - ctx, _ = WithCancel(Background()) - checkChildren("after creation", ctx, 0) - _, cancel = WithTimeout(ctx, 60*time.Minute) - checkChildren("with WithTimeout child ", ctx, 1) - cancel() - checkChildren("after cancelling WithTimeout child", ctx, 0) -} diff --git a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_17_test.go b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_17_test.go deleted file mode 100644 index 72411b1b67..0000000000 --- a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_17_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2015 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 !plan9,go1.7 - -package ctxhttp - -import ( - "io" - "net/http" - "net/http/httptest" - "testing" - - "context" -) - -func TestGo17Context(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "ok") - })) - defer ts.Close() - ctx := context.Background() - resp, err := Get(ctx, http.DefaultClient, ts.URL) - if resp == nil || err != nil { - t.Fatalf("error received from client: %v %v", err, resp) - } - resp.Body.Close() -} diff --git a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17_test.go b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17_test.go deleted file mode 100644 index 9159cf0225..0000000000 --- a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2015 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 !plan9,!go1.7 - -package ctxhttp - -import ( - "net" - "net/http" - "net/http/httptest" - "sync" - "testing" - "time" - - "golang.org/x/net/context" -) - -// golang.org/issue/14065 -func TestClosesResponseBodyOnCancel(t *testing.T) { - defer func() { testHookContextDoneBeforeHeaders = nop }() - defer func() { testHookDoReturned = nop }() - defer func() { testHookDidBodyClose = nop }() - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) - defer ts.Close() - - ctx, cancel := context.WithCancel(context.Background()) - - // closed when Do enters select case <-ctx.Done() - enteredDonePath := make(chan struct{}) - - testHookContextDoneBeforeHeaders = func() { - close(enteredDonePath) - } - - testHookDoReturned = func() { - // We now have the result (the Flush'd headers) at least, - // so we can cancel the request. - cancel() - - // But block the client.Do goroutine from sending - // until Do enters into the <-ctx.Done() path, since - // otherwise if both channels are readable, select - // picks a random one. - <-enteredDonePath - } - - sawBodyClose := make(chan struct{}) - testHookDidBodyClose = func() { close(sawBodyClose) } - - tr := &http.Transport{} - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - req, _ := http.NewRequest("GET", ts.URL, nil) - _, doErr := Do(ctx, c, req) - - select { - case <-sawBodyClose: - case <-time.After(5 * time.Second): - t.Fatal("timeout waiting for body to close") - } - - if doErr != ctx.Err() { - t.Errorf("Do error = %v; want %v", doErr, ctx.Err()) - } -} - -type noteCloseConn struct { - net.Conn - onceClose sync.Once - closefn func() -} - -func (c *noteCloseConn) Close() error { - c.onceClose.Do(c.closefn) - return c.Conn.Close() -} diff --git a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_test.go b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_test.go deleted file mode 100644 index 1e4155180c..0000000000 --- a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_test.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright 2015 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 !plan9 - -package ctxhttp - -import ( - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" - "time" - - "golang.org/x/net/context" -) - -const ( - requestDuration = 100 * time.Millisecond - requestBody = "ok" -) - -func okHandler(w http.ResponseWriter, r *http.Request) { - time.Sleep(requestDuration) - io.WriteString(w, requestBody) -} - -func TestNoTimeout(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(okHandler)) - defer ts.Close() - - ctx := context.Background() - res, err := Get(ctx, nil, ts.URL) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if string(slurp) != requestBody { - t.Errorf("body = %q; want %q", slurp, requestBody) - } -} - -func TestCancelBeforeHeaders(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - - blockServer := make(chan struct{}) - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - cancel() - <-blockServer - io.WriteString(w, requestBody) - })) - defer ts.Close() - defer close(blockServer) - - res, err := Get(ctx, nil, ts.URL) - if err == nil { - res.Body.Close() - t.Fatal("Get returned unexpected nil error") - } - if err != context.Canceled { - t.Errorf("err = %v; want %v", err, context.Canceled) - } -} - -func TestCancelAfterHangingRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - w.(http.Flusher).Flush() - <-w.(http.CloseNotifier).CloseNotify() - })) - defer ts.Close() - - ctx, cancel := context.WithCancel(context.Background()) - resp, err := Get(ctx, nil, ts.URL) - if err != nil { - t.Fatalf("unexpected error in Get: %v", err) - } - - // Cancel befer reading the body. - // Reading Request.Body should fail, since the request was - // canceled before anything was written. - cancel() - - done := make(chan struct{}) - - go func() { - b, err := ioutil.ReadAll(resp.Body) - if len(b) != 0 || err == nil { - t.Errorf(`Read got (%q, %v); want ("", error)`, b, err) - } - close(done) - }() - - select { - case <-time.After(1 * time.Second): - t.Errorf("Test timed out") - case <-done: - } -} diff --git a/vendor/golang.org/x/net/context/withtimeout_test.go b/vendor/golang.org/x/net/context/withtimeout_test.go deleted file mode 100644 index e6f56691d1..0000000000 --- a/vendor/golang.org/x/net/context/withtimeout_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2014 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 context_test - -import ( - "fmt" - "time" - - "golang.org/x/net/context" -) - -// This example passes a context with a timeout to tell a blocking function that -// it should abandon its work after the timeout elapses. -func ExampleWithTimeout() { - // Pass a context with a timeout to tell a blocking function that it - // should abandon its work after the timeout elapses. - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - defer cancel() - - select { - case <-time.After(1 * time.Second): - fmt.Println("overslept") - case <-ctx.Done(): - fmt.Println(ctx.Err()) // prints "context deadline exceeded" - } - - // Output: - // context deadline exceeded -} diff --git a/vendor/golang.org/x/net/html/atom/atom_test.go b/vendor/golang.org/x/net/html/atom/atom_test.go deleted file mode 100644 index 6e33704dd5..0000000000 --- a/vendor/golang.org/x/net/html/atom/atom_test.go +++ /dev/null @@ -1,109 +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 atom - -import ( - "sort" - "testing" -) - -func TestKnown(t *testing.T) { - for _, s := range testAtomList { - if atom := Lookup([]byte(s)); atom.String() != s { - t.Errorf("Lookup(%q) = %#x (%q)", s, uint32(atom), atom.String()) - } - } -} - -func TestHits(t *testing.T) { - for _, a := range table { - if a == 0 { - continue - } - got := Lookup([]byte(a.String())) - if got != a { - t.Errorf("Lookup(%q) = %#x, want %#x", a.String(), uint32(got), uint32(a)) - } - } -} - -func TestMisses(t *testing.T) { - testCases := []string{ - "", - "\x00", - "\xff", - "A", - "DIV", - "Div", - "dIV", - "aa", - "a\x00", - "ab", - "abb", - "abbr0", - "abbr ", - " abbr", - " a", - "acceptcharset", - "acceptCharset", - "accept_charset", - "h0", - "h1h2", - "h7", - "onClick", - "λ", - // The following string has the same hash (0xa1d7fab7) as "onmouseover". - "\x00\x00\x00\x00\x00\x50\x18\xae\x38\xd0\xb7", - } - for _, tc := range testCases { - got := Lookup([]byte(tc)) - if got != 0 { - t.Errorf("Lookup(%q): got %d, want 0", tc, got) - } - } -} - -func TestForeignObject(t *testing.T) { - const ( - afo = Foreignobject - afO = ForeignObject - sfo = "foreignobject" - sfO = "foreignObject" - ) - if got := Lookup([]byte(sfo)); got != afo { - t.Errorf("Lookup(%q): got %#v, want %#v", sfo, got, afo) - } - if got := Lookup([]byte(sfO)); got != afO { - t.Errorf("Lookup(%q): got %#v, want %#v", sfO, got, afO) - } - if got := afo.String(); got != sfo { - t.Errorf("Atom(%#v).String(): got %q, want %q", afo, got, sfo) - } - if got := afO.String(); got != sfO { - t.Errorf("Atom(%#v).String(): got %q, want %q", afO, got, sfO) - } -} - -func BenchmarkLookup(b *testing.B) { - sortedTable := make([]string, 0, len(table)) - for _, a := range table { - if a != 0 { - sortedTable = append(sortedTable, a.String()) - } - } - sort.Strings(sortedTable) - - x := make([][]byte, 1000) - for i := range x { - x[i] = []byte(sortedTable[i%len(sortedTable)]) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - for _, s := range x { - Lookup(s) - } - } -} diff --git a/vendor/golang.org/x/net/html/atom/gen.go b/vendor/golang.org/x/net/html/atom/gen.go index cc5dc5dbce..5d052781bc 100644 --- a/vendor/golang.org/x/net/html/atom/gen.go +++ b/vendor/golang.org/x/net/html/atom/gen.go @@ -306,7 +306,7 @@ func (t *table) push(i uint32, depth int) bool { // The lists of element names and attribute keys were taken from // https://html.spec.whatwg.org/multipage/indices.html#index -// as of the "HTML Living Standard - Last Updated 18 September 2017" version. +// as of the "HTML Living Standard - Last Updated 16 April 2018" version. // "command", "keygen" and "menuitem" have been removed from the spec, // but are kept here for backwards compatibility. @@ -665,6 +665,7 @@ var eventHandlers = []string{ // extra are ad-hoc values not covered by any of the lists above. var extra = []string{ + "acronym", "align", "annotation", "annotation-xml", @@ -700,6 +701,8 @@ var extra = []string{ "plaintext", "prompt", "public", + "rb", + "rtc", "spacer", "strike", "svg", diff --git a/vendor/golang.org/x/net/html/atom/table.go b/vendor/golang.org/x/net/html/atom/table.go index f74018ecea..2a938864cb 100644 --- a/vendor/golang.org/x/net/html/atom/table.go +++ b/vendor/golang.org/x/net/html/atom/table.go @@ -10,366 +10,369 @@ const ( Accept Atom = 0x1a06 AcceptCharset Atom = 0x1a0e Accesskey Atom = 0x2c09 - Action Atom = 0x25a06 - Address Atom = 0x6ed07 - Align Atom = 0x6d405 - Allowfullscreen Atom = 0x1f00f - Allowpaymentrequest Atom = 0x6913 - Allowusermedia Atom = 0x850e - Alt Atom = 0xb003 - Annotation Atom = 0x1b90a - AnnotationXml Atom = 0x1b90e - Applet Atom = 0x30106 - Area Atom = 0x34a04 - Article Atom = 0x3f007 - As Atom = 0xb902 - Aside Atom = 0xc105 - Async Atom = 0xb905 - Audio Atom = 0xcf05 - Autocomplete Atom = 0x2600c - Autofocus Atom = 0xeb09 - Autoplay Atom = 0x10608 + Acronym Atom = 0xaa07 + Action Atom = 0x27206 + Address Atom = 0x6f307 + Align Atom = 0xb105 + Allowfullscreen Atom = 0x2080f + Allowpaymentrequest Atom = 0xc113 + Allowusermedia Atom = 0xdd0e + Alt Atom = 0xf303 + Annotation Atom = 0x1c90a + AnnotationXml Atom = 0x1c90e + Applet Atom = 0x31906 + Area Atom = 0x35604 + Article Atom = 0x3fc07 + As Atom = 0x3c02 + Aside Atom = 0x10705 + Async Atom = 0xff05 + Audio Atom = 0x11505 + Autocomplete Atom = 0x2780c + Autofocus Atom = 0x12109 + Autoplay Atom = 0x13c08 B Atom = 0x101 - Base Atom = 0x11504 - Basefont Atom = 0x11508 - Bdi Atom = 0x16103 - Bdo Atom = 0x13403 - Bgsound Atom = 0x14707 - Big Atom = 0x15903 - Blink Atom = 0x15c05 - Blockquote Atom = 0x1680a + Base Atom = 0x3b04 + Basefont Atom = 0x3b08 + Bdi Atom = 0xba03 + Bdo Atom = 0x14b03 + Bgsound Atom = 0x15e07 + Big Atom = 0x17003 + Blink Atom = 0x17305 + Blockquote Atom = 0x1870a Body Atom = 0x2804 Br Atom = 0x202 - Button Atom = 0x17206 - Canvas Atom = 0xbd06 - Caption Atom = 0x21907 - Center Atom = 0x20806 - Challenge Atom = 0x28309 + Button Atom = 0x19106 + Canvas Atom = 0x10306 + Caption Atom = 0x23107 + Center Atom = 0x22006 + Challenge Atom = 0x29b09 Charset Atom = 0x2107 - Checked Atom = 0x46d07 - Cite Atom = 0x55804 - Class Atom = 0x5b905 - Code Atom = 0x19004 - Col Atom = 0x19703 - Colgroup Atom = 0x19708 - Color Atom = 0x1af05 - Cols Atom = 0x1b404 - Colspan Atom = 0x1b407 - Command Atom = 0x1c707 - Content Atom = 0x57f07 - Contenteditable Atom = 0x57f0f - Contextmenu Atom = 0x3740b - Controls Atom = 0x1ce08 - Coords Atom = 0x1da06 - Crossorigin Atom = 0x1e30b - Data Atom = 0x49904 - Datalist Atom = 0x49908 - Datetime Atom = 0x2a008 - Dd Atom = 0x2bf02 - Default Atom = 0xc407 - Defer Atom = 0x19205 - Del Atom = 0x44603 - Desc Atom = 0x55504 - Details Atom = 0x4607 - Dfn Atom = 0x5f03 - Dialog Atom = 0x16206 - Dir Atom = 0xa303 - Dirname Atom = 0xa307 - Disabled Atom = 0x14d08 - Div Atom = 0x15403 - Dl Atom = 0x5e202 - Download Atom = 0x45708 - Draggable Atom = 0x18309 - Dropzone Atom = 0x3f908 - Dt Atom = 0x64702 - Em Atom = 0x4202 - Embed Atom = 0x4205 - Enctype Atom = 0x27507 - Face Atom = 0x20604 - Fieldset Atom = 0x20e08 - Figcaption Atom = 0x2160a - Figure Atom = 0x23006 - Font Atom = 0x11904 - Footer Atom = 0xb306 - For Atom = 0x23c03 - ForeignObject Atom = 0x23c0d - Foreignobject Atom = 0x2490d - Form Atom = 0x25604 - Formaction Atom = 0x2560a - Formenctype Atom = 0x2710b - Formmethod Atom = 0x28c0a - Formnovalidate Atom = 0x2960e - Formtarget Atom = 0x2a80a - Frame Atom = 0x5705 - Frameset Atom = 0x5708 - H1 Atom = 0x14502 - H2 Atom = 0x2c602 - H3 Atom = 0x2f502 - H4 Atom = 0x33902 - H5 Atom = 0x34302 - H6 Atom = 0x64902 - Head Atom = 0x32504 - Header Atom = 0x32506 - Headers Atom = 0x32507 - Height Atom = 0x12c06 - Hgroup Atom = 0x2b206 - Hidden Atom = 0x2bd06 - High Atom = 0x2c304 - Hr Atom = 0x14002 - Href Atom = 0x2c804 - Hreflang Atom = 0x2c808 - Html Atom = 0x13004 - HttpEquiv Atom = 0x2d00a + Checked Atom = 0x47907 + Cite Atom = 0x19c04 + Class Atom = 0x56405 + Code Atom = 0x5c504 + Col Atom = 0x1ab03 + Colgroup Atom = 0x1ab08 + Color Atom = 0x1bf05 + Cols Atom = 0x1c404 + Colspan Atom = 0x1c407 + Command Atom = 0x1d707 + Content Atom = 0x58b07 + Contenteditable Atom = 0x58b0f + Contextmenu Atom = 0x3800b + Controls Atom = 0x1de08 + Coords Atom = 0x1ea06 + Crossorigin Atom = 0x1fb0b + Data Atom = 0x4a504 + Datalist Atom = 0x4a508 + Datetime Atom = 0x2b808 + Dd Atom = 0x2d702 + Default Atom = 0x10a07 + Defer Atom = 0x5c705 + Del Atom = 0x45203 + Desc Atom = 0x56104 + Details Atom = 0x7207 + Dfn Atom = 0x8703 + Dialog Atom = 0xbb06 + Dir Atom = 0x9303 + Dirname Atom = 0x9307 + Disabled Atom = 0x16408 + Div Atom = 0x16b03 + Dl Atom = 0x5e602 + Download Atom = 0x46308 + Draggable Atom = 0x17a09 + Dropzone Atom = 0x40508 + Dt Atom = 0x64b02 + Em Atom = 0x6e02 + Embed Atom = 0x6e05 + Enctype Atom = 0x28d07 + Face Atom = 0x21e04 + Fieldset Atom = 0x22608 + Figcaption Atom = 0x22e0a + Figure Atom = 0x24806 + Font Atom = 0x3f04 + Footer Atom = 0xf606 + For Atom = 0x25403 + ForeignObject Atom = 0x2540d + Foreignobject Atom = 0x2610d + Form Atom = 0x26e04 + Formaction Atom = 0x26e0a + Formenctype Atom = 0x2890b + Formmethod Atom = 0x2a40a + Formnovalidate Atom = 0x2ae0e + Formtarget Atom = 0x2c00a + Frame Atom = 0x8b05 + Frameset Atom = 0x8b08 + H1 Atom = 0x15c02 + H2 Atom = 0x2de02 + H3 Atom = 0x30d02 + H4 Atom = 0x34502 + H5 Atom = 0x34f02 + H6 Atom = 0x64d02 + Head Atom = 0x33104 + Header Atom = 0x33106 + Headers Atom = 0x33107 + Height Atom = 0x5206 + Hgroup Atom = 0x2ca06 + Hidden Atom = 0x2d506 + High Atom = 0x2db04 + Hr Atom = 0x15702 + Href Atom = 0x2e004 + Hreflang Atom = 0x2e008 + Html Atom = 0x5604 + HttpEquiv Atom = 0x2e80a I Atom = 0x601 - Icon Atom = 0x57e04 - Id Atom = 0xc302 - Iframe Atom = 0x2e406 - Image Atom = 0x2ea05 - Img Atom = 0x2ef03 - Input Atom = 0x43f05 - Inputmode Atom = 0x43f09 - Ins Atom = 0x1ec03 - Integrity Atom = 0x22709 - Is Atom = 0x14e02 - Isindex Atom = 0x2f707 - Ismap Atom = 0x2fe05 - Itemid Atom = 0x37f06 - Itemprop Atom = 0x55908 - Itemref Atom = 0x3c107 - Itemscope Atom = 0x66d09 - Itemtype Atom = 0x30708 - Kbd Atom = 0x16003 + Icon Atom = 0x58a04 + Id Atom = 0x10902 + Iframe Atom = 0x2fc06 + Image Atom = 0x30205 + Img Atom = 0x30703 + Input Atom = 0x44b05 + Inputmode Atom = 0x44b09 + Ins Atom = 0x20403 + Integrity Atom = 0x23f09 + Is Atom = 0x16502 + Isindex Atom = 0x30f07 + Ismap Atom = 0x31605 + Itemid Atom = 0x38b06 + Itemprop Atom = 0x19d08 + Itemref Atom = 0x3cd07 + Itemscope Atom = 0x67109 + Itemtype Atom = 0x31f08 + Kbd Atom = 0xb903 Keygen Atom = 0x3206 - Keytype Atom = 0x7e07 - Kind Atom = 0x18004 - Label Atom = 0xda05 - Lang Atom = 0x2cc04 - Legend Atom = 0x18a06 - Li Atom = 0x11102 - Link Atom = 0x15d04 - List Atom = 0x49d04 - Listing Atom = 0x49d07 - Loop Atom = 0xde04 - Low Atom = 0x6b03 + Keytype Atom = 0xd607 + Kind Atom = 0x17704 + Label Atom = 0x5905 + Lang Atom = 0x2e404 + Legend Atom = 0x18106 + Li Atom = 0xb202 + Link Atom = 0x17404 + List Atom = 0x4a904 + Listing Atom = 0x4a907 + Loop Atom = 0x5d04 + Low Atom = 0xc303 Main Atom = 0x1004 - Malignmark Atom = 0x6d30a - Manifest Atom = 0x30f08 - Map Atom = 0x30003 - Mark Atom = 0x6d904 - Marquee Atom = 0x31b07 - Math Atom = 0x32204 - Max Atom = 0x33103 - Maxlength Atom = 0x33109 - Media Atom = 0x8e05 - Mediagroup Atom = 0x8e0a - Menu Atom = 0x37b04 - Menuitem Atom = 0x37b08 - Meta Atom = 0x4ac04 - Meter Atom = 0xa805 - Method Atom = 0x29006 - Mglyph Atom = 0x2f006 - Mi Atom = 0x33b02 - Min Atom = 0x33b03 - Minlength Atom = 0x33b09 - Mn Atom = 0x29902 - Mo Atom = 0x6302 - Ms Atom = 0x67002 - Mtext Atom = 0x34505 - Multiple Atom = 0x35308 - Muted Atom = 0x35b05 - Name Atom = 0xa604 + Malignmark Atom = 0xb00a + Manifest Atom = 0x6d708 + Map Atom = 0x31803 + Mark Atom = 0xb604 + Marquee Atom = 0x32707 + Math Atom = 0x32e04 + Max Atom = 0x33d03 + Maxlength Atom = 0x33d09 + Media Atom = 0xe605 + Mediagroup Atom = 0xe60a + Menu Atom = 0x38704 + Menuitem Atom = 0x38708 + Meta Atom = 0x4b804 + Meter Atom = 0x9805 + Method Atom = 0x2a806 + Mglyph Atom = 0x30806 + Mi Atom = 0x34702 + Min Atom = 0x34703 + Minlength Atom = 0x34709 + Mn Atom = 0x2b102 + Mo Atom = 0xa402 + Ms Atom = 0x67402 + Mtext Atom = 0x35105 + Multiple Atom = 0x35f08 + Muted Atom = 0x36705 + Name Atom = 0x9604 Nav Atom = 0x1303 Nobr Atom = 0x3704 - Noembed Atom = 0x4007 - Noframes Atom = 0x5508 - Nomodule Atom = 0x6108 - Nonce Atom = 0x56205 - Noscript Atom = 0x1fe08 - Novalidate Atom = 0x29a0a - Object Atom = 0x25006 - Ol Atom = 0x10102 - Onabort Atom = 0x17607 - Onafterprint Atom = 0x21e0c - Onautocomplete Atom = 0x25e0e - Onautocompleteerror Atom = 0x25e13 - Onauxclick Atom = 0x61b0a - Onbeforeprint Atom = 0x69a0d - Onbeforeunload Atom = 0x6e10e - Onblur Atom = 0x5c206 - Oncancel Atom = 0xd308 - Oncanplay Atom = 0x13609 - Oncanplaythrough Atom = 0x13610 - Onchange Atom = 0x40f08 - Onclick Atom = 0x2dd07 - Onclose Atom = 0x36007 - Oncontextmenu Atom = 0x3720d - Oncopy Atom = 0x38506 - Oncuechange Atom = 0x38b0b - Oncut Atom = 0x39605 - Ondblclick Atom = 0x39b0a - Ondrag Atom = 0x3a506 - Ondragend Atom = 0x3a509 - Ondragenter Atom = 0x3ae0b - Ondragexit Atom = 0x3b90a - Ondragleave Atom = 0x3d30b - Ondragover Atom = 0x3de0a - Ondragstart Atom = 0x3e80b - Ondrop Atom = 0x3f706 - Ondurationchange Atom = 0x40710 - Onemptied Atom = 0x3fe09 - Onended Atom = 0x41707 - Onerror Atom = 0x41e07 - Onfocus Atom = 0x42507 - Onhashchange Atom = 0x4310c - Oninput Atom = 0x43d07 - Oninvalid Atom = 0x44909 - Onkeydown Atom = 0x45209 - Onkeypress Atom = 0x45f0a - Onkeyup Atom = 0x47407 - Onlanguagechange Atom = 0x48110 - Onload Atom = 0x49106 - Onloadeddata Atom = 0x4910c - Onloadedmetadata Atom = 0x4a410 - Onloadend Atom = 0x4ba09 - Onloadstart Atom = 0x4c30b - Onmessage Atom = 0x4ce09 - Onmessageerror Atom = 0x4ce0e - Onmousedown Atom = 0x4dc0b - Onmouseenter Atom = 0x4e70c - Onmouseleave Atom = 0x4f30c - Onmousemove Atom = 0x4ff0b - Onmouseout Atom = 0x50a0a - Onmouseover Atom = 0x5170b - Onmouseup Atom = 0x52209 - Onmousewheel Atom = 0x5300c - Onoffline Atom = 0x53c09 - Ononline Atom = 0x54508 - Onpagehide Atom = 0x54d0a - Onpageshow Atom = 0x5670a - Onpaste Atom = 0x57307 - Onpause Atom = 0x58e07 - Onplay Atom = 0x59806 - Onplaying Atom = 0x59809 - Onpopstate Atom = 0x5a10a - Onprogress Atom = 0x5ab0a - Onratechange Atom = 0x5c80c - Onrejectionhandled Atom = 0x5d412 - Onreset Atom = 0x5e607 - Onresize Atom = 0x5ed08 - Onscroll Atom = 0x5fc08 - Onsecuritypolicyviolation Atom = 0x60419 - Onseeked Atom = 0x62508 - Onseeking Atom = 0x62d09 - Onselect Atom = 0x63608 - Onshow Atom = 0x64006 - Onsort Atom = 0x64b06 - Onstalled Atom = 0x65509 - Onstorage Atom = 0x65e09 - Onsubmit Atom = 0x66708 - Onsuspend Atom = 0x67709 - Ontimeupdate Atom = 0x11a0c - Ontoggle Atom = 0x68008 - Onunhandledrejection Atom = 0x68814 - Onunload Atom = 0x6a708 - Onvolumechange Atom = 0x6af0e - Onwaiting Atom = 0x6bd09 - Onwheel Atom = 0x6c607 - Open Atom = 0x55f04 - Optgroup Atom = 0xe008 - Optimum Atom = 0x6cd07 - Option Atom = 0x6dd06 - Output Atom = 0x51106 + Noembed Atom = 0x6c07 + Noframes Atom = 0x8908 + Nomodule Atom = 0xa208 + Nonce Atom = 0x1a605 + Noscript Atom = 0x21608 + Novalidate Atom = 0x2b20a + Object Atom = 0x26806 + Ol Atom = 0x13702 + Onabort Atom = 0x19507 + Onafterprint Atom = 0x2360c + Onautocomplete Atom = 0x2760e + Onautocompleteerror Atom = 0x27613 + Onauxclick Atom = 0x61f0a + Onbeforeprint Atom = 0x69e0d + Onbeforeunload Atom = 0x6e70e + Onblur Atom = 0x56d06 + Oncancel Atom = 0x11908 + Oncanplay Atom = 0x14d09 + Oncanplaythrough Atom = 0x14d10 + Onchange Atom = 0x41b08 + Onclick Atom = 0x2f507 + Onclose Atom = 0x36c07 + Oncontextmenu Atom = 0x37e0d + Oncopy Atom = 0x39106 + Oncuechange Atom = 0x3970b + Oncut Atom = 0x3a205 + Ondblclick Atom = 0x3a70a + Ondrag Atom = 0x3b106 + Ondragend Atom = 0x3b109 + Ondragenter Atom = 0x3ba0b + Ondragexit Atom = 0x3c50a + Ondragleave Atom = 0x3df0b + Ondragover Atom = 0x3ea0a + Ondragstart Atom = 0x3f40b + Ondrop Atom = 0x40306 + Ondurationchange Atom = 0x41310 + Onemptied Atom = 0x40a09 + Onended Atom = 0x42307 + Onerror Atom = 0x42a07 + Onfocus Atom = 0x43107 + Onhashchange Atom = 0x43d0c + Oninput Atom = 0x44907 + Oninvalid Atom = 0x45509 + Onkeydown Atom = 0x45e09 + Onkeypress Atom = 0x46b0a + Onkeyup Atom = 0x48007 + Onlanguagechange Atom = 0x48d10 + Onload Atom = 0x49d06 + Onloadeddata Atom = 0x49d0c + Onloadedmetadata Atom = 0x4b010 + Onloadend Atom = 0x4c609 + Onloadstart Atom = 0x4cf0b + Onmessage Atom = 0x4da09 + Onmessageerror Atom = 0x4da0e + Onmousedown Atom = 0x4e80b + Onmouseenter Atom = 0x4f30c + Onmouseleave Atom = 0x4ff0c + Onmousemove Atom = 0x50b0b + Onmouseout Atom = 0x5160a + Onmouseover Atom = 0x5230b + Onmouseup Atom = 0x52e09 + Onmousewheel Atom = 0x53c0c + Onoffline Atom = 0x54809 + Ononline Atom = 0x55108 + Onpagehide Atom = 0x5590a + Onpageshow Atom = 0x5730a + Onpaste Atom = 0x57f07 + Onpause Atom = 0x59a07 + Onplay Atom = 0x5a406 + Onplaying Atom = 0x5a409 + Onpopstate Atom = 0x5ad0a + Onprogress Atom = 0x5b70a + Onratechange Atom = 0x5cc0c + Onrejectionhandled Atom = 0x5d812 + Onreset Atom = 0x5ea07 + Onresize Atom = 0x5f108 + Onscroll Atom = 0x60008 + Onsecuritypolicyviolation Atom = 0x60819 + Onseeked Atom = 0x62908 + Onseeking Atom = 0x63109 + Onselect Atom = 0x63a08 + Onshow Atom = 0x64406 + Onsort Atom = 0x64f06 + Onstalled Atom = 0x65909 + Onstorage Atom = 0x66209 + Onsubmit Atom = 0x66b08 + Onsuspend Atom = 0x67b09 + Ontimeupdate Atom = 0x400c + Ontoggle Atom = 0x68408 + Onunhandledrejection Atom = 0x68c14 + Onunload Atom = 0x6ab08 + Onvolumechange Atom = 0x6b30e + Onwaiting Atom = 0x6c109 + Onwheel Atom = 0x6ca07 + Open Atom = 0x1a304 + Optgroup Atom = 0x5f08 + Optimum Atom = 0x6d107 + Option Atom = 0x6e306 + Output Atom = 0x51d06 P Atom = 0xc01 Param Atom = 0xc05 - Pattern Atom = 0x4f07 - Picture Atom = 0x9707 - Ping Atom = 0xe704 - Placeholder Atom = 0xfb0b - Plaintext Atom = 0x19e09 - Playsinline Atom = 0x10a0b - Poster Atom = 0x2b706 - Pre Atom = 0x46403 - Preload Atom = 0x47a07 - Progress Atom = 0x5ad08 - Prompt Atom = 0x52a06 - Public Atom = 0x57a06 - Q Atom = 0x7701 + Pattern Atom = 0x6607 + Picture Atom = 0x7b07 + Ping Atom = 0xef04 + Placeholder Atom = 0x1310b + Plaintext Atom = 0x1b209 + Playsinline Atom = 0x1400b + Poster Atom = 0x2cf06 + Pre Atom = 0x47003 + Preload Atom = 0x48607 + Progress Atom = 0x5b908 + Prompt Atom = 0x53606 + Public Atom = 0x58606 + Q Atom = 0xcf01 Radiogroup Atom = 0x30a - Readonly Atom = 0x34b08 - Referrerpolicy Atom = 0x3c50e - Rel Atom = 0x47b03 - Required Atom = 0x23408 - Reversed Atom = 0x9c08 - Rows Atom = 0x3a04 - Rowspan Atom = 0x3a07 - Rp Atom = 0x22402 - Rt Atom = 0x17b02 - Ruby Atom = 0xac04 + Rb Atom = 0x3a02 + Readonly Atom = 0x35708 + Referrerpolicy Atom = 0x3d10e + Rel Atom = 0x48703 + Required Atom = 0x24c08 + Reversed Atom = 0x8008 + Rows Atom = 0x9c04 + Rowspan Atom = 0x9c07 + Rp Atom = 0x23c02 + Rt Atom = 0x19a02 + Rtc Atom = 0x19a03 + Ruby Atom = 0xfb04 S Atom = 0x2501 - Samp Atom = 0x4c04 - Sandbox Atom = 0xf307 - Scope Atom = 0x67105 - Scoped Atom = 0x67106 - Script Atom = 0x20006 - Seamless Atom = 0x36508 - Section Atom = 0x5bd07 - Select Atom = 0x63806 - Selected Atom = 0x63808 - Shape Atom = 0x1d505 - Size Atom = 0x5f104 - Sizes Atom = 0x5f105 - Slot Atom = 0x1df04 - Small Atom = 0x1ee05 - Sortable Atom = 0x64d08 - Sorted Atom = 0x32b06 - Source Atom = 0x36c06 - Spacer Atom = 0x42b06 - Span Atom = 0x3d04 - Spellcheck Atom = 0x4680a - Src Atom = 0x5b403 - Srcdoc Atom = 0x5b406 - Srclang Atom = 0x5f507 - Srcset Atom = 0x6f306 - Start Atom = 0x3ee05 - Step Atom = 0x57704 - Strike Atom = 0x7a06 - Strong Atom = 0x31506 - Style Atom = 0x6f905 - Sub Atom = 0x66903 - Summary Atom = 0x6fe07 - Sup Atom = 0x70503 - Svg Atom = 0x70803 - System Atom = 0x70b06 - Tabindex Atom = 0x4b208 - Table Atom = 0x58905 - Target Atom = 0x2ac06 + Samp Atom = 0x7804 + Sandbox Atom = 0x12907 + Scope Atom = 0x67505 + Scoped Atom = 0x67506 + Script Atom = 0x21806 + Seamless Atom = 0x37108 + Section Atom = 0x56807 + Select Atom = 0x63c06 + Selected Atom = 0x63c08 + Shape Atom = 0x1e505 + Size Atom = 0x5f504 + Sizes Atom = 0x5f505 + Slot Atom = 0x1ef04 + Small Atom = 0x20605 + Sortable Atom = 0x65108 + Sorted Atom = 0x33706 + Source Atom = 0x37806 + Spacer Atom = 0x43706 + Span Atom = 0x9f04 + Spellcheck Atom = 0x4740a + Src Atom = 0x5c003 + Srcdoc Atom = 0x5c006 + Srclang Atom = 0x5f907 + Srcset Atom = 0x6f906 + Start Atom = 0x3fa05 + Step Atom = 0x58304 + Strike Atom = 0xd206 + Strong Atom = 0x6dd06 + Style Atom = 0x6ff05 + Sub Atom = 0x66d03 + Summary Atom = 0x70407 + Sup Atom = 0x70b03 + Svg Atom = 0x70e03 + System Atom = 0x71106 + Tabindex Atom = 0x4be08 + Table Atom = 0x59505 + Target Atom = 0x2c406 Tbody Atom = 0x2705 - Td Atom = 0x5e02 - Template Atom = 0x70e08 - Textarea Atom = 0x34608 - Tfoot Atom = 0xb205 - Th Atom = 0x13f02 - Thead Atom = 0x32405 - Time Atom = 0x11c04 - Title Atom = 0xca05 - Tr Atom = 0x7402 - Track Atom = 0x17c05 - Translate Atom = 0x1a609 - Tt Atom = 0x5102 - Type Atom = 0x8104 - Typemustmatch Atom = 0x2780d + Td Atom = 0x9202 + Template Atom = 0x71408 + Textarea Atom = 0x35208 + Tfoot Atom = 0xf505 + Th Atom = 0x15602 + Thead Atom = 0x33005 + Time Atom = 0x4204 + Title Atom = 0x11005 + Tr Atom = 0xcc02 + Track Atom = 0x1ba05 + Translate Atom = 0x1f209 + Tt Atom = 0x6802 + Type Atom = 0xd904 + Typemustmatch Atom = 0x2900d U Atom = 0xb01 - Ul Atom = 0x6602 - Updateviacache Atom = 0x1200e - Usemap Atom = 0x59206 + Ul Atom = 0xa702 + Updateviacache Atom = 0x460e + Usemap Atom = 0x59e06 Value Atom = 0x1505 - Var Atom = 0x15603 - Video Atom = 0x2d905 - Wbr Atom = 0x57003 - Width Atom = 0x64505 - Workertype Atom = 0x7160a - Wrap Atom = 0x72004 - Xmp Atom = 0xf903 + Var Atom = 0x16d03 + Video Atom = 0x2f105 + Wbr Atom = 0x57c03 + Width Atom = 0x64905 + Workertype Atom = 0x71c0a + Wrap Atom = 0x72604 + Xmp Atom = 0x12f03 ) const hash0 = 0x81cdf10e @@ -377,401 +380,404 @@ const hash0 = 0x81cdf10e const maxAtomLen = 25 var table = [1 << 9]Atom{ - 0x1: 0x8e0a, // mediagroup - 0x2: 0x2cc04, // lang + 0x1: 0xe60a, // mediagroup + 0x2: 0x2e404, // lang 0x4: 0x2c09, // accesskey - 0x5: 0x5708, // frameset - 0x7: 0x63608, // onselect - 0x8: 0x70b06, // system - 0xa: 0x64505, // width - 0xc: 0x2710b, // formenctype - 0xd: 0x10102, // ol - 0xe: 0x38b0b, // oncuechange - 0x10: 0x13403, // bdo - 0x11: 0xcf05, // audio - 0x12: 0x18309, // draggable - 0x14: 0x2d905, // video - 0x15: 0x29902, // mn - 0x16: 0x37b04, // menu - 0x17: 0x2b706, // poster - 0x19: 0xb306, // footer - 0x1a: 0x29006, // method - 0x1b: 0x2a008, // datetime - 0x1c: 0x17607, // onabort - 0x1d: 0x1200e, // updateviacache - 0x1e: 0xb905, // async - 0x1f: 0x49106, // onload - 0x21: 0xd308, // oncancel - 0x22: 0x62508, // onseeked - 0x23: 0x2ea05, // image - 0x24: 0x5d412, // onrejectionhandled - 0x26: 0x15d04, // link - 0x27: 0x51106, // output - 0x28: 0x32504, // head - 0x29: 0x4f30c, // onmouseleave - 0x2a: 0x57307, // onpaste - 0x2b: 0x59809, // onplaying - 0x2c: 0x1b407, // colspan - 0x2f: 0x1af05, // color - 0x30: 0x5f104, // size - 0x31: 0x2d00a, // http-equiv + 0x5: 0x8b08, // frameset + 0x7: 0x63a08, // onselect + 0x8: 0x71106, // system + 0xa: 0x64905, // width + 0xc: 0x2890b, // formenctype + 0xd: 0x13702, // ol + 0xe: 0x3970b, // oncuechange + 0x10: 0x14b03, // bdo + 0x11: 0x11505, // audio + 0x12: 0x17a09, // draggable + 0x14: 0x2f105, // video + 0x15: 0x2b102, // mn + 0x16: 0x38704, // menu + 0x17: 0x2cf06, // poster + 0x19: 0xf606, // footer + 0x1a: 0x2a806, // method + 0x1b: 0x2b808, // datetime + 0x1c: 0x19507, // onabort + 0x1d: 0x460e, // updateviacache + 0x1e: 0xff05, // async + 0x1f: 0x49d06, // onload + 0x21: 0x11908, // oncancel + 0x22: 0x62908, // onseeked + 0x23: 0x30205, // image + 0x24: 0x5d812, // onrejectionhandled + 0x26: 0x17404, // link + 0x27: 0x51d06, // output + 0x28: 0x33104, // head + 0x29: 0x4ff0c, // onmouseleave + 0x2a: 0x57f07, // onpaste + 0x2b: 0x5a409, // onplaying + 0x2c: 0x1c407, // colspan + 0x2f: 0x1bf05, // color + 0x30: 0x5f504, // size + 0x31: 0x2e80a, // http-equiv 0x33: 0x601, // i - 0x34: 0x54d0a, // onpagehide - 0x35: 0x68814, // onunhandledrejection - 0x37: 0x41e07, // onerror - 0x3a: 0x11508, // basefont + 0x34: 0x5590a, // onpagehide + 0x35: 0x68c14, // onunhandledrejection + 0x37: 0x42a07, // onerror + 0x3a: 0x3b08, // basefont 0x3f: 0x1303, // nav - 0x40: 0x18004, // kind - 0x41: 0x34b08, // readonly - 0x42: 0x2f006, // mglyph - 0x44: 0x11102, // li - 0x46: 0x2bd06, // hidden - 0x47: 0x70803, // svg - 0x48: 0x57704, // step - 0x49: 0x22709, // integrity - 0x4a: 0x57a06, // public - 0x4c: 0x19703, // col - 0x4d: 0x1680a, // blockquote - 0x4e: 0x34302, // h5 - 0x50: 0x5ad08, // progress - 0x51: 0x5f105, // sizes - 0x52: 0x33902, // h4 - 0x56: 0x32405, // thead - 0x57: 0x7e07, // keytype - 0x58: 0x5ab0a, // onprogress - 0x59: 0x43f09, // inputmode - 0x5a: 0x3a509, // ondragend - 0x5d: 0x39605, // oncut - 0x5e: 0x42b06, // spacer - 0x5f: 0x19708, // colgroup - 0x62: 0x14e02, // is - 0x65: 0xb902, // as - 0x66: 0x53c09, // onoffline - 0x67: 0x32b06, // sorted - 0x69: 0x48110, // onlanguagechange - 0x6c: 0x4310c, // onhashchange - 0x6d: 0xa604, // name - 0x6e: 0xb205, // tfoot - 0x6f: 0x55504, // desc - 0x70: 0x33103, // max - 0x72: 0x1da06, // coords - 0x73: 0x2f502, // h3 - 0x74: 0x6e10e, // onbeforeunload - 0x75: 0x3a04, // rows - 0x76: 0x63806, // select - 0x77: 0xa805, // meter - 0x78: 0x37f06, // itemid - 0x79: 0x5300c, // onmousewheel - 0x7a: 0x5b406, // srcdoc - 0x7d: 0x17c05, // track - 0x7f: 0x30708, // itemtype - 0x82: 0x6302, // mo - 0x83: 0x40f08, // onchange - 0x84: 0x32507, // headers - 0x85: 0x5c80c, // onratechange - 0x86: 0x60419, // onsecuritypolicyviolation - 0x88: 0x49908, // datalist - 0x89: 0x4dc0b, // onmousedown - 0x8a: 0x1df04, // slot - 0x8b: 0x4a410, // onloadedmetadata + 0x40: 0x17704, // kind + 0x41: 0x35708, // readonly + 0x42: 0x30806, // mglyph + 0x44: 0xb202, // li + 0x46: 0x2d506, // hidden + 0x47: 0x70e03, // svg + 0x48: 0x58304, // step + 0x49: 0x23f09, // integrity + 0x4a: 0x58606, // public + 0x4c: 0x1ab03, // col + 0x4d: 0x1870a, // blockquote + 0x4e: 0x34f02, // h5 + 0x50: 0x5b908, // progress + 0x51: 0x5f505, // sizes + 0x52: 0x34502, // h4 + 0x56: 0x33005, // thead + 0x57: 0xd607, // keytype + 0x58: 0x5b70a, // onprogress + 0x59: 0x44b09, // inputmode + 0x5a: 0x3b109, // ondragend + 0x5d: 0x3a205, // oncut + 0x5e: 0x43706, // spacer + 0x5f: 0x1ab08, // colgroup + 0x62: 0x16502, // is + 0x65: 0x3c02, // as + 0x66: 0x54809, // onoffline + 0x67: 0x33706, // sorted + 0x69: 0x48d10, // onlanguagechange + 0x6c: 0x43d0c, // onhashchange + 0x6d: 0x9604, // name + 0x6e: 0xf505, // tfoot + 0x6f: 0x56104, // desc + 0x70: 0x33d03, // max + 0x72: 0x1ea06, // coords + 0x73: 0x30d02, // h3 + 0x74: 0x6e70e, // onbeforeunload + 0x75: 0x9c04, // rows + 0x76: 0x63c06, // select + 0x77: 0x9805, // meter + 0x78: 0x38b06, // itemid + 0x79: 0x53c0c, // onmousewheel + 0x7a: 0x5c006, // srcdoc + 0x7d: 0x1ba05, // track + 0x7f: 0x31f08, // itemtype + 0x82: 0xa402, // mo + 0x83: 0x41b08, // onchange + 0x84: 0x33107, // headers + 0x85: 0x5cc0c, // onratechange + 0x86: 0x60819, // onsecuritypolicyviolation + 0x88: 0x4a508, // datalist + 0x89: 0x4e80b, // onmousedown + 0x8a: 0x1ef04, // slot + 0x8b: 0x4b010, // onloadedmetadata 0x8c: 0x1a06, // accept - 0x8d: 0x25006, // object - 0x91: 0x6af0e, // onvolumechange + 0x8d: 0x26806, // object + 0x91: 0x6b30e, // onvolumechange 0x92: 0x2107, // charset - 0x93: 0x25e13, // onautocompleteerror - 0x94: 0x6913, // allowpaymentrequest + 0x93: 0x27613, // onautocompleteerror + 0x94: 0xc113, // allowpaymentrequest 0x95: 0x2804, // body - 0x96: 0xc407, // default - 0x97: 0x63808, // selected - 0x98: 0x20604, // face - 0x99: 0x1d505, // shape - 0x9b: 0x68008, // ontoggle - 0x9e: 0x64702, // dt - 0x9f: 0x6d904, // mark + 0x96: 0x10a07, // default + 0x97: 0x63c08, // selected + 0x98: 0x21e04, // face + 0x99: 0x1e505, // shape + 0x9b: 0x68408, // ontoggle + 0x9e: 0x64b02, // dt + 0x9f: 0xb604, // mark 0xa1: 0xb01, // u - 0xa4: 0x6a708, // onunload - 0xa5: 0xde04, // loop - 0xa6: 0x14d08, // disabled - 0xaa: 0x41707, // onended - 0xab: 0x6d30a, // malignmark - 0xad: 0x67709, // onsuspend - 0xae: 0x34505, // mtext - 0xaf: 0x64b06, // onsort - 0xb0: 0x55908, // itemprop - 0xb3: 0x66d09, // itemscope - 0xb4: 0x15c05, // blink - 0xb6: 0x3a506, // ondrag - 0xb7: 0x6602, // ul - 0xb8: 0x25604, // form - 0xb9: 0xf307, // sandbox - 0xba: 0x5705, // frame + 0xa4: 0x6ab08, // onunload + 0xa5: 0x5d04, // loop + 0xa6: 0x16408, // disabled + 0xaa: 0x42307, // onended + 0xab: 0xb00a, // malignmark + 0xad: 0x67b09, // onsuspend + 0xae: 0x35105, // mtext + 0xaf: 0x64f06, // onsort + 0xb0: 0x19d08, // itemprop + 0xb3: 0x67109, // itemscope + 0xb4: 0x17305, // blink + 0xb6: 0x3b106, // ondrag + 0xb7: 0xa702, // ul + 0xb8: 0x26e04, // form + 0xb9: 0x12907, // sandbox + 0xba: 0x8b05, // frame 0xbb: 0x1505, // value - 0xbc: 0x65e09, // onstorage - 0xc0: 0x17b02, // rt + 0xbc: 0x66209, // onstorage + 0xbf: 0xaa07, // acronym + 0xc0: 0x19a02, // rt 0xc2: 0x202, // br - 0xc3: 0x20e08, // fieldset - 0xc4: 0x2780d, // typemustmatch - 0xc5: 0x6108, // nomodule - 0xc6: 0x4007, // noembed - 0xc7: 0x69a0d, // onbeforeprint - 0xc8: 0x17206, // button - 0xc9: 0x2dd07, // onclick - 0xca: 0x6fe07, // summary - 0xcd: 0xac04, // ruby - 0xce: 0x5b905, // class - 0xcf: 0x3e80b, // ondragstart - 0xd0: 0x21907, // caption - 0xd4: 0x850e, // allowusermedia - 0xd5: 0x4c30b, // onloadstart - 0xd9: 0x15403, // div - 0xda: 0x49d04, // list - 0xdb: 0x32204, // math - 0xdc: 0x43f05, // input - 0xdf: 0x3de0a, // ondragover - 0xe0: 0x2c602, // h2 - 0xe2: 0x19e09, // plaintext - 0xe4: 0x4e70c, // onmouseenter - 0xe7: 0x46d07, // checked - 0xe8: 0x46403, // pre - 0xea: 0x35308, // multiple - 0xeb: 0x16103, // bdi - 0xec: 0x33109, // maxlength - 0xed: 0x7701, // q - 0xee: 0x61b0a, // onauxclick - 0xf0: 0x57003, // wbr - 0xf2: 0x11504, // base - 0xf3: 0x6dd06, // option - 0xf5: 0x40710, // ondurationchange - 0xf7: 0x5508, // noframes - 0xf9: 0x3f908, // dropzone - 0xfb: 0x67105, // scope - 0xfc: 0x9c08, // reversed - 0xfd: 0x3ae0b, // ondragenter - 0xfe: 0x3ee05, // start - 0xff: 0xf903, // xmp - 0x100: 0x5f507, // srclang - 0x101: 0x2ef03, // img + 0xc3: 0x22608, // fieldset + 0xc4: 0x2900d, // typemustmatch + 0xc5: 0xa208, // nomodule + 0xc6: 0x6c07, // noembed + 0xc7: 0x69e0d, // onbeforeprint + 0xc8: 0x19106, // button + 0xc9: 0x2f507, // onclick + 0xca: 0x70407, // summary + 0xcd: 0xfb04, // ruby + 0xce: 0x56405, // class + 0xcf: 0x3f40b, // ondragstart + 0xd0: 0x23107, // caption + 0xd4: 0xdd0e, // allowusermedia + 0xd5: 0x4cf0b, // onloadstart + 0xd9: 0x16b03, // div + 0xda: 0x4a904, // list + 0xdb: 0x32e04, // math + 0xdc: 0x44b05, // input + 0xdf: 0x3ea0a, // ondragover + 0xe0: 0x2de02, // h2 + 0xe2: 0x1b209, // plaintext + 0xe4: 0x4f30c, // onmouseenter + 0xe7: 0x47907, // checked + 0xe8: 0x47003, // pre + 0xea: 0x35f08, // multiple + 0xeb: 0xba03, // bdi + 0xec: 0x33d09, // maxlength + 0xed: 0xcf01, // q + 0xee: 0x61f0a, // onauxclick + 0xf0: 0x57c03, // wbr + 0xf2: 0x3b04, // base + 0xf3: 0x6e306, // option + 0xf5: 0x41310, // ondurationchange + 0xf7: 0x8908, // noframes + 0xf9: 0x40508, // dropzone + 0xfb: 0x67505, // scope + 0xfc: 0x8008, // reversed + 0xfd: 0x3ba0b, // ondragenter + 0xfe: 0x3fa05, // start + 0xff: 0x12f03, // xmp + 0x100: 0x5f907, // srclang + 0x101: 0x30703, // img 0x104: 0x101, // b - 0x105: 0x23c03, // for - 0x106: 0xc105, // aside - 0x107: 0x43d07, // oninput - 0x108: 0x34a04, // area - 0x109: 0x28c0a, // formmethod - 0x10a: 0x72004, // wrap - 0x10c: 0x22402, // rp - 0x10d: 0x45f0a, // onkeypress - 0x10e: 0x5102, // tt - 0x110: 0x33b02, // mi - 0x111: 0x35b05, // muted - 0x112: 0xb003, // alt - 0x113: 0x19004, // code - 0x114: 0x4202, // em - 0x115: 0x3b90a, // ondragexit - 0x117: 0x3d04, // span - 0x119: 0x30f08, // manifest - 0x11a: 0x37b08, // menuitem - 0x11b: 0x57f07, // content - 0x11d: 0x6bd09, // onwaiting - 0x11f: 0x4ba09, // onloadend - 0x121: 0x3720d, // oncontextmenu - 0x123: 0x5c206, // onblur - 0x124: 0x3f007, // article - 0x125: 0xa303, // dir - 0x126: 0xe704, // ping - 0x127: 0x23408, // required - 0x128: 0x44909, // oninvalid - 0x129: 0x6d405, // align - 0x12b: 0x57e04, // icon - 0x12c: 0x64902, // h6 - 0x12d: 0x1b404, // cols - 0x12e: 0x2160a, // figcaption - 0x12f: 0x45209, // onkeydown - 0x130: 0x66708, // onsubmit - 0x131: 0x13609, // oncanplay - 0x132: 0x70503, // sup + 0x105: 0x25403, // for + 0x106: 0x10705, // aside + 0x107: 0x44907, // oninput + 0x108: 0x35604, // area + 0x109: 0x2a40a, // formmethod + 0x10a: 0x72604, // wrap + 0x10c: 0x23c02, // rp + 0x10d: 0x46b0a, // onkeypress + 0x10e: 0x6802, // tt + 0x110: 0x34702, // mi + 0x111: 0x36705, // muted + 0x112: 0xf303, // alt + 0x113: 0x5c504, // code + 0x114: 0x6e02, // em + 0x115: 0x3c50a, // ondragexit + 0x117: 0x9f04, // span + 0x119: 0x6d708, // manifest + 0x11a: 0x38708, // menuitem + 0x11b: 0x58b07, // content + 0x11d: 0x6c109, // onwaiting + 0x11f: 0x4c609, // onloadend + 0x121: 0x37e0d, // oncontextmenu + 0x123: 0x56d06, // onblur + 0x124: 0x3fc07, // article + 0x125: 0x9303, // dir + 0x126: 0xef04, // ping + 0x127: 0x24c08, // required + 0x128: 0x45509, // oninvalid + 0x129: 0xb105, // align + 0x12b: 0x58a04, // icon + 0x12c: 0x64d02, // h6 + 0x12d: 0x1c404, // cols + 0x12e: 0x22e0a, // figcaption + 0x12f: 0x45e09, // onkeydown + 0x130: 0x66b08, // onsubmit + 0x131: 0x14d09, // oncanplay + 0x132: 0x70b03, // sup 0x133: 0xc01, // p - 0x135: 0x3fe09, // onemptied - 0x136: 0x38506, // oncopy - 0x137: 0x55804, // cite - 0x138: 0x39b0a, // ondblclick - 0x13a: 0x4ff0b, // onmousemove - 0x13c: 0x66903, // sub - 0x13d: 0x47b03, // rel - 0x13e: 0xe008, // optgroup - 0x142: 0x3a07, // rowspan - 0x143: 0x36c06, // source - 0x144: 0x1fe08, // noscript - 0x145: 0x55f04, // open - 0x146: 0x1ec03, // ins - 0x147: 0x23c0d, // foreignObject - 0x148: 0x5a10a, // onpopstate - 0x14a: 0x27507, // enctype - 0x14b: 0x25e0e, // onautocomplete - 0x14c: 0x34608, // textarea - 0x14e: 0x2600c, // autocomplete - 0x14f: 0x14002, // hr - 0x150: 0x1ce08, // controls - 0x151: 0xc302, // id - 0x153: 0x21e0c, // onafterprint - 0x155: 0x2490d, // foreignobject - 0x156: 0x31b07, // marquee - 0x157: 0x58e07, // onpause - 0x158: 0x5e202, // dl - 0x159: 0x12c06, // height - 0x15a: 0x33b03, // min - 0x15b: 0xa307, // dirname - 0x15c: 0x1a609, // translate - 0x15d: 0x13004, // html - 0x15e: 0x33b09, // minlength - 0x15f: 0x47a07, // preload - 0x160: 0x70e08, // template - 0x161: 0x3d30b, // ondragleave - 0x164: 0x5b403, // src - 0x165: 0x31506, // strong - 0x167: 0x4c04, // samp - 0x168: 0x6ed07, // address - 0x169: 0x54508, // ononline - 0x16b: 0xfb0b, // placeholder - 0x16c: 0x2ac06, // target - 0x16d: 0x1ee05, // small - 0x16e: 0x6c607, // onwheel - 0x16f: 0x1b90a, // annotation - 0x170: 0x4680a, // spellcheck - 0x171: 0x4607, // details - 0x172: 0xbd06, // canvas - 0x173: 0xeb09, // autofocus + 0x135: 0x40a09, // onemptied + 0x136: 0x39106, // oncopy + 0x137: 0x19c04, // cite + 0x138: 0x3a70a, // ondblclick + 0x13a: 0x50b0b, // onmousemove + 0x13c: 0x66d03, // sub + 0x13d: 0x48703, // rel + 0x13e: 0x5f08, // optgroup + 0x142: 0x9c07, // rowspan + 0x143: 0x37806, // source + 0x144: 0x21608, // noscript + 0x145: 0x1a304, // open + 0x146: 0x20403, // ins + 0x147: 0x2540d, // foreignObject + 0x148: 0x5ad0a, // onpopstate + 0x14a: 0x28d07, // enctype + 0x14b: 0x2760e, // onautocomplete + 0x14c: 0x35208, // textarea + 0x14e: 0x2780c, // autocomplete + 0x14f: 0x15702, // hr + 0x150: 0x1de08, // controls + 0x151: 0x10902, // id + 0x153: 0x2360c, // onafterprint + 0x155: 0x2610d, // foreignobject + 0x156: 0x32707, // marquee + 0x157: 0x59a07, // onpause + 0x158: 0x5e602, // dl + 0x159: 0x5206, // height + 0x15a: 0x34703, // min + 0x15b: 0x9307, // dirname + 0x15c: 0x1f209, // translate + 0x15d: 0x5604, // html + 0x15e: 0x34709, // minlength + 0x15f: 0x48607, // preload + 0x160: 0x71408, // template + 0x161: 0x3df0b, // ondragleave + 0x162: 0x3a02, // rb + 0x164: 0x5c003, // src + 0x165: 0x6dd06, // strong + 0x167: 0x7804, // samp + 0x168: 0x6f307, // address + 0x169: 0x55108, // ononline + 0x16b: 0x1310b, // placeholder + 0x16c: 0x2c406, // target + 0x16d: 0x20605, // small + 0x16e: 0x6ca07, // onwheel + 0x16f: 0x1c90a, // annotation + 0x170: 0x4740a, // spellcheck + 0x171: 0x7207, // details + 0x172: 0x10306, // canvas + 0x173: 0x12109, // autofocus 0x174: 0xc05, // param - 0x176: 0x45708, // download - 0x177: 0x44603, // del - 0x178: 0x36007, // onclose - 0x179: 0x16003, // kbd - 0x17a: 0x30106, // applet - 0x17b: 0x2c804, // href - 0x17c: 0x5ed08, // onresize - 0x17e: 0x4910c, // onloadeddata - 0x180: 0x7402, // tr - 0x181: 0x2a80a, // formtarget - 0x182: 0xca05, // title - 0x183: 0x6f905, // style - 0x184: 0x7a06, // strike - 0x185: 0x59206, // usemap - 0x186: 0x2e406, // iframe + 0x176: 0x46308, // download + 0x177: 0x45203, // del + 0x178: 0x36c07, // onclose + 0x179: 0xb903, // kbd + 0x17a: 0x31906, // applet + 0x17b: 0x2e004, // href + 0x17c: 0x5f108, // onresize + 0x17e: 0x49d0c, // onloadeddata + 0x180: 0xcc02, // tr + 0x181: 0x2c00a, // formtarget + 0x182: 0x11005, // title + 0x183: 0x6ff05, // style + 0x184: 0xd206, // strike + 0x185: 0x59e06, // usemap + 0x186: 0x2fc06, // iframe 0x187: 0x1004, // main - 0x189: 0x9707, // picture - 0x18c: 0x2fe05, // ismap - 0x18e: 0x49904, // data - 0x18f: 0xda05, // label - 0x191: 0x3c50e, // referrerpolicy - 0x192: 0x13f02, // th - 0x194: 0x52a06, // prompt - 0x195: 0x5bd07, // section - 0x197: 0x6cd07, // optimum - 0x198: 0x2c304, // high - 0x199: 0x14502, // h1 - 0x19a: 0x65509, // onstalled - 0x19b: 0x15603, // var - 0x19c: 0x11c04, // time - 0x19e: 0x67002, // ms - 0x19f: 0x32506, // header - 0x1a0: 0x4ce09, // onmessage - 0x1a1: 0x56205, // nonce - 0x1a2: 0x2560a, // formaction - 0x1a3: 0x20806, // center + 0x189: 0x7b07, // picture + 0x18c: 0x31605, // ismap + 0x18e: 0x4a504, // data + 0x18f: 0x5905, // label + 0x191: 0x3d10e, // referrerpolicy + 0x192: 0x15602, // th + 0x194: 0x53606, // prompt + 0x195: 0x56807, // section + 0x197: 0x6d107, // optimum + 0x198: 0x2db04, // high + 0x199: 0x15c02, // h1 + 0x19a: 0x65909, // onstalled + 0x19b: 0x16d03, // var + 0x19c: 0x4204, // time + 0x19e: 0x67402, // ms + 0x19f: 0x33106, // header + 0x1a0: 0x4da09, // onmessage + 0x1a1: 0x1a605, // nonce + 0x1a2: 0x26e0a, // formaction + 0x1a3: 0x22006, // center 0x1a4: 0x3704, // nobr - 0x1a5: 0x58905, // table - 0x1a6: 0x49d07, // listing - 0x1a7: 0x18a06, // legend - 0x1a9: 0x28309, // challenge - 0x1aa: 0x23006, // figure - 0x1ab: 0x8e05, // media - 0x1ae: 0x8104, // type - 0x1af: 0x11904, // font - 0x1b0: 0x4ce0e, // onmessageerror - 0x1b1: 0x36508, // seamless - 0x1b2: 0x5f03, // dfn - 0x1b3: 0x19205, // defer - 0x1b4: 0x6b03, // low - 0x1b5: 0x62d09, // onseeking - 0x1b6: 0x5170b, // onmouseover - 0x1b7: 0x29a0a, // novalidate - 0x1b8: 0x7160a, // workertype - 0x1ba: 0x3c107, // itemref + 0x1a5: 0x59505, // table + 0x1a6: 0x4a907, // listing + 0x1a7: 0x18106, // legend + 0x1a9: 0x29b09, // challenge + 0x1aa: 0x24806, // figure + 0x1ab: 0xe605, // media + 0x1ae: 0xd904, // type + 0x1af: 0x3f04, // font + 0x1b0: 0x4da0e, // onmessageerror + 0x1b1: 0x37108, // seamless + 0x1b2: 0x8703, // dfn + 0x1b3: 0x5c705, // defer + 0x1b4: 0xc303, // low + 0x1b5: 0x19a03, // rtc + 0x1b6: 0x5230b, // onmouseover + 0x1b7: 0x2b20a, // novalidate + 0x1b8: 0x71c0a, // workertype + 0x1ba: 0x3cd07, // itemref 0x1bd: 0x1, // a - 0x1be: 0x30003, // map - 0x1bf: 0x11a0c, // ontimeupdate - 0x1c0: 0x14707, // bgsound + 0x1be: 0x31803, // map + 0x1bf: 0x400c, // ontimeupdate + 0x1c0: 0x15e07, // bgsound 0x1c1: 0x3206, // keygen 0x1c2: 0x2705, // tbody - 0x1c5: 0x64006, // onshow + 0x1c5: 0x64406, // onshow 0x1c7: 0x2501, // s - 0x1c8: 0x4f07, // pattern - 0x1cc: 0x13610, // oncanplaythrough - 0x1ce: 0x2bf02, // dd - 0x1cf: 0x6f306, // srcset - 0x1d0: 0x15903, // big - 0x1d2: 0x64d08, // sortable - 0x1d3: 0x47407, // onkeyup - 0x1d5: 0x59806, // onplay - 0x1d7: 0x4ac04, // meta - 0x1d8: 0x3f706, // ondrop - 0x1da: 0x5fc08, // onscroll - 0x1db: 0x1e30b, // crossorigin - 0x1dc: 0x5670a, // onpageshow + 0x1c8: 0x6607, // pattern + 0x1cc: 0x14d10, // oncanplaythrough + 0x1ce: 0x2d702, // dd + 0x1cf: 0x6f906, // srcset + 0x1d0: 0x17003, // big + 0x1d2: 0x65108, // sortable + 0x1d3: 0x48007, // onkeyup + 0x1d5: 0x5a406, // onplay + 0x1d7: 0x4b804, // meta + 0x1d8: 0x40306, // ondrop + 0x1da: 0x60008, // onscroll + 0x1db: 0x1fb0b, // crossorigin + 0x1dc: 0x5730a, // onpageshow 0x1dd: 0x4, // abbr - 0x1de: 0x5e02, // td - 0x1df: 0x57f0f, // contenteditable - 0x1e0: 0x25a06, // action - 0x1e1: 0x10a0b, // playsinline - 0x1e2: 0x42507, // onfocus - 0x1e3: 0x2c808, // hreflang - 0x1e5: 0x50a0a, // onmouseout - 0x1e6: 0x5e607, // onreset - 0x1e7: 0x10608, // autoplay - 0x1ea: 0x67106, // scoped + 0x1de: 0x9202, // td + 0x1df: 0x58b0f, // contenteditable + 0x1e0: 0x27206, // action + 0x1e1: 0x1400b, // playsinline + 0x1e2: 0x43107, // onfocus + 0x1e3: 0x2e008, // hreflang + 0x1e5: 0x5160a, // onmouseout + 0x1e6: 0x5ea07, // onreset + 0x1e7: 0x13c08, // autoplay + 0x1e8: 0x63109, // onseeking + 0x1ea: 0x67506, // scoped 0x1ec: 0x30a, // radiogroup - 0x1ee: 0x3740b, // contextmenu - 0x1ef: 0x52209, // onmouseup - 0x1f1: 0x2b206, // hgroup - 0x1f2: 0x1f00f, // allowfullscreen - 0x1f3: 0x4b208, // tabindex - 0x1f6: 0x2f707, // isindex + 0x1ee: 0x3800b, // contextmenu + 0x1ef: 0x52e09, // onmouseup + 0x1f1: 0x2ca06, // hgroup + 0x1f2: 0x2080f, // allowfullscreen + 0x1f3: 0x4be08, // tabindex + 0x1f6: 0x30f07, // isindex 0x1f7: 0x1a0e, // accept-charset - 0x1f8: 0x2960e, // formnovalidate - 0x1fb: 0x1b90e, // annotation-xml - 0x1fc: 0x4205, // embed - 0x1fd: 0x20006, // script - 0x1fe: 0x16206, // dialog - 0x1ff: 0x1c707, // command + 0x1f8: 0x2ae0e, // formnovalidate + 0x1fb: 0x1c90e, // annotation-xml + 0x1fc: 0x6e05, // embed + 0x1fd: 0x21806, // script + 0x1fe: 0xbb06, // dialog + 0x1ff: 0x1d707, // command } -const atomText = "abbradiogrouparamainavalueaccept-charsetbodyaccesskeygenobro" + - "wspanoembedetailsampatternoframesetdfnomoduleallowpaymentreq" + - "uestrikeytypeallowusermediagroupictureversedirnameterubyaltf" + - "ooterasyncanvasidefaultitleaudioncancelabelooptgroupingautof" + - "ocusandboxmplaceholderautoplaysinlinebasefontimeupdateviacac" + - "heightmlbdoncanplaythrough1bgsoundisabledivarbigblinkbdialog" + - "blockquotebuttonabortrackindraggablegendcodefercolgrouplaint" + - "extranslatecolorcolspannotation-xmlcommandcontrolshapecoords" + - "lotcrossoriginsmallowfullscreenoscriptfacenterfieldsetfigcap" + - "tionafterprintegrityfigurequiredforeignObjectforeignobjectfo" + - "rmactionautocompleteerrorformenctypemustmatchallengeformmeth" + - "odformnovalidatetimeformtargethgrouposterhiddenhigh2hreflang" + - "http-equivideonclickiframeimageimglyph3isindexismappletitemt" + - "ypemanifestrongmarqueematheadersortedmaxlength4minlength5mte" + - "xtareadonlymultiplemutedoncloseamlessourceoncontextmenuitemi" + - "doncopyoncuechangeoncutondblclickondragendondragenterondrage" + - "xitemreferrerpolicyondragleaveondragoverondragstarticleondro" + - "pzonemptiedondurationchangeonendedonerroronfocuspaceronhashc" + - "hangeoninputmodeloninvalidonkeydownloadonkeypresspellchecked" + - "onkeyupreloadonlanguagechangeonloadeddatalistingonloadedmeta" + - "databindexonloadendonloadstartonmessageerroronmousedownonmou" + - "seenteronmouseleaveonmousemoveonmouseoutputonmouseoveronmous" + - "eupromptonmousewheelonofflineononlineonpagehidescitempropeno" + - "nceonpageshowbronpastepublicontenteditableonpausemaponplayin" + - "gonpopstateonprogressrcdoclassectionbluronratechangeonreject" + - "ionhandledonresetonresizesrclangonscrollonsecuritypolicyviol" + - "ationauxclickonseekedonseekingonselectedonshowidth6onsortabl" + - "eonstalledonstorageonsubmitemscopedonsuspendontoggleonunhand" + - "ledrejectionbeforeprintonunloadonvolumechangeonwaitingonwhee" + - "loptimumalignmarkoptionbeforeunloaddressrcsetstylesummarysup" + - "svgsystemplateworkertypewrap" +const atomText = "abbradiogrouparamainavalueaccept-charsetbodyaccesskeygenobrb" + + "asefontimeupdateviacacheightmlabelooptgroupatternoembedetail" + + "sampictureversedfnoframesetdirnameterowspanomoduleacronymali" + + "gnmarkbdialogallowpaymentrequestrikeytypeallowusermediagroup" + + "ingaltfooterubyasyncanvasidefaultitleaudioncancelautofocusan" + + "dboxmplaceholderautoplaysinlinebdoncanplaythrough1bgsoundisa" + + "bledivarbigblinkindraggablegendblockquotebuttonabortcitempro" + + "penoncecolgrouplaintextrackcolorcolspannotation-xmlcommandco" + + "ntrolshapecoordslotranslatecrossoriginsmallowfullscreenoscri" + + "ptfacenterfieldsetfigcaptionafterprintegrityfigurequiredfore" + + "ignObjectforeignobjectformactionautocompleteerrorformenctype" + + "mustmatchallengeformmethodformnovalidatetimeformtargethgroup" + + "osterhiddenhigh2hreflanghttp-equivideonclickiframeimageimgly" + + "ph3isindexismappletitemtypemarqueematheadersortedmaxlength4m" + + "inlength5mtextareadonlymultiplemutedoncloseamlessourceoncont" + + "extmenuitemidoncopyoncuechangeoncutondblclickondragendondrag" + + "enterondragexitemreferrerpolicyondragleaveondragoverondragst" + + "articleondropzonemptiedondurationchangeonendedonerroronfocus" + + "paceronhashchangeoninputmodeloninvalidonkeydownloadonkeypres" + + "spellcheckedonkeyupreloadonlanguagechangeonloadeddatalisting" + + "onloadedmetadatabindexonloadendonloadstartonmessageerroronmo" + + "usedownonmouseenteronmouseleaveonmousemoveonmouseoutputonmou" + + "seoveronmouseupromptonmousewheelonofflineononlineonpagehides" + + "classectionbluronpageshowbronpastepublicontenteditableonpaus" + + "emaponplayingonpopstateonprogressrcdocodeferonratechangeonre" + + "jectionhandledonresetonresizesrclangonscrollonsecuritypolicy" + + "violationauxclickonseekedonseekingonselectedonshowidth6onsor" + + "tableonstalledonstorageonsubmitemscopedonsuspendontoggleonun" + + "handledrejectionbeforeprintonunloadonvolumechangeonwaitingon" + + "wheeloptimumanifestrongoptionbeforeunloaddressrcsetstylesumm" + + "arysupsvgsystemplateworkertypewrap" diff --git a/vendor/golang.org/x/net/html/atom/table_test.go b/vendor/golang.org/x/net/html/atom/table_test.go deleted file mode 100644 index 16891054fc..0000000000 --- a/vendor/golang.org/x/net/html/atom/table_test.go +++ /dev/null @@ -1,373 +0,0 @@ -// Code generated by go generate gen.go; DO NOT EDIT. - -//go:generate go run gen.go -test - -package atom - -var testAtomList = []string{ - "a", - "abbr", - "accept", - "accept-charset", - "accesskey", - "action", - "address", - "align", - "allowfullscreen", - "allowpaymentrequest", - "allowusermedia", - "alt", - "annotation", - "annotation-xml", - "applet", - "area", - "article", - "as", - "aside", - "async", - "audio", - "autocomplete", - "autofocus", - "autoplay", - "b", - "base", - "basefont", - "bdi", - "bdo", - "bgsound", - "big", - "blink", - "blockquote", - "body", - "br", - "button", - "canvas", - "caption", - "center", - "challenge", - "charset", - "checked", - "cite", - "class", - "code", - "col", - "colgroup", - "color", - "cols", - "colspan", - "command", - "content", - "contenteditable", - "contextmenu", - "controls", - "coords", - "crossorigin", - "data", - "datalist", - "datetime", - "dd", - "default", - "defer", - "del", - "desc", - "details", - "dfn", - "dialog", - "dir", - "dirname", - "disabled", - "div", - "dl", - "download", - "draggable", - "dropzone", - "dt", - "em", - "embed", - "enctype", - "face", - "fieldset", - "figcaption", - "figure", - "font", - "footer", - "for", - "foreignObject", - "foreignobject", - "form", - "formaction", - "formenctype", - "formmethod", - "formnovalidate", - "formtarget", - "frame", - "frameset", - "h1", - "h2", - "h3", - "h4", - "h5", - "h6", - "head", - "header", - "headers", - "height", - "hgroup", - "hidden", - "high", - "hr", - "href", - "hreflang", - "html", - "http-equiv", - "i", - "icon", - "id", - "iframe", - "image", - "img", - "input", - "inputmode", - "ins", - "integrity", - "is", - "isindex", - "ismap", - "itemid", - "itemprop", - "itemref", - "itemscope", - "itemtype", - "kbd", - "keygen", - "keytype", - "kind", - "label", - "lang", - "legend", - "li", - "link", - "list", - "listing", - "loop", - "low", - "main", - "malignmark", - "manifest", - "map", - "mark", - "marquee", - "math", - "max", - "maxlength", - "media", - "mediagroup", - "menu", - "menuitem", - "meta", - "meter", - "method", - "mglyph", - "mi", - "min", - "minlength", - "mn", - "mo", - "ms", - "mtext", - "multiple", - "muted", - "name", - "nav", - "nobr", - "noembed", - "noframes", - "nomodule", - "nonce", - "noscript", - "novalidate", - "object", - "ol", - "onabort", - "onafterprint", - "onautocomplete", - "onautocompleteerror", - "onauxclick", - "onbeforeprint", - "onbeforeunload", - "onblur", - "oncancel", - "oncanplay", - "oncanplaythrough", - "onchange", - "onclick", - "onclose", - "oncontextmenu", - "oncopy", - "oncuechange", - "oncut", - "ondblclick", - "ondrag", - "ondragend", - "ondragenter", - "ondragexit", - "ondragleave", - "ondragover", - "ondragstart", - "ondrop", - "ondurationchange", - "onemptied", - "onended", - "onerror", - "onfocus", - "onhashchange", - "oninput", - "oninvalid", - "onkeydown", - "onkeypress", - "onkeyup", - "onlanguagechange", - "onload", - "onloadeddata", - "onloadedmetadata", - "onloadend", - "onloadstart", - "onmessage", - "onmessageerror", - "onmousedown", - "onmouseenter", - "onmouseleave", - "onmousemove", - "onmouseout", - "onmouseover", - "onmouseup", - "onmousewheel", - "onoffline", - "ononline", - "onpagehide", - "onpageshow", - "onpaste", - "onpause", - "onplay", - "onplaying", - "onpopstate", - "onprogress", - "onratechange", - "onrejectionhandled", - "onreset", - "onresize", - "onscroll", - "onsecuritypolicyviolation", - "onseeked", - "onseeking", - "onselect", - "onshow", - "onsort", - "onstalled", - "onstorage", - "onsubmit", - "onsuspend", - "ontimeupdate", - "ontoggle", - "onunhandledrejection", - "onunload", - "onvolumechange", - "onwaiting", - "onwheel", - "open", - "optgroup", - "optimum", - "option", - "output", - "p", - "param", - "pattern", - "picture", - "ping", - "placeholder", - "plaintext", - "playsinline", - "poster", - "pre", - "preload", - "progress", - "prompt", - "public", - "q", - "radiogroup", - "readonly", - "referrerpolicy", - "rel", - "required", - "reversed", - "rows", - "rowspan", - "rp", - "rt", - "ruby", - "s", - "samp", - "sandbox", - "scope", - "scoped", - "script", - "seamless", - "section", - "select", - "selected", - "shape", - "size", - "sizes", - "slot", - "small", - "sortable", - "sorted", - "source", - "spacer", - "span", - "spellcheck", - "src", - "srcdoc", - "srclang", - "srcset", - "start", - "step", - "strike", - "strong", - "style", - "sub", - "summary", - "sup", - "svg", - "system", - "tabindex", - "table", - "target", - "tbody", - "td", - "template", - "textarea", - "tfoot", - "th", - "thead", - "time", - "title", - "tr", - "track", - "translate", - "tt", - "type", - "typemustmatch", - "u", - "ul", - "updateviacache", - "usemap", - "value", - "var", - "video", - "wbr", - "width", - "workertype", - "wrap", - "xmp", -} diff --git a/vendor/golang.org/x/net/html/charset/charset_test.go b/vendor/golang.org/x/net/html/charset/charset_test.go deleted file mode 100644 index e4e7d86bf9..0000000000 --- a/vendor/golang.org/x/net/html/charset/charset_test.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2013 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 charset - -import ( - "bytes" - "encoding/xml" - "io/ioutil" - "runtime" - "strings" - "testing" - - "golang.org/x/text/transform" -) - -func transformString(t transform.Transformer, s string) (string, error) { - r := transform.NewReader(strings.NewReader(s), t) - b, err := ioutil.ReadAll(r) - return string(b), err -} - -type testCase struct { - utf8, other, otherEncoding string -} - -// testCases for encoding and decoding. -var testCases = []testCase{ - {"Résumé", "Résumé", "utf8"}, - {"Résumé", "R\xe9sum\xe9", "latin1"}, - {"これは漢字です。", "S0\x8c0o0\"oW[g0Y0\x020", "UTF-16LE"}, - {"これは漢字です。", "0S0\x8c0oo\"[W0g0Y0\x02", "UTF-16BE"}, - {"Hello, world", "Hello, world", "ASCII"}, - {"Gdańsk", "Gda\xf1sk", "ISO-8859-2"}, - {"Ââ Čč Đđ Ŋŋ Õõ Šš Žž Åå Ää", "\xc2\xe2 \xc8\xe8 \xa9\xb9 \xaf\xbf \xd5\xf5 \xaa\xba \xac\xbc \xc5\xe5 \xc4\xe4", "ISO-8859-10"}, - {"สำหรับ", "\xca\xd3\xcb\xc3\u047a", "ISO-8859-11"}, - {"latviešu", "latvie\xf0u", "ISO-8859-13"}, - {"Seònaid", "Se\xf2naid", "ISO-8859-14"}, - {"€1 is cheap", "\xa41 is cheap", "ISO-8859-15"}, - {"românește", "rom\xe2ne\xbate", "ISO-8859-16"}, - {"nutraĵo", "nutra\xbco", "ISO-8859-3"}, - {"Kalâdlit", "Kal\xe2dlit", "ISO-8859-4"}, - {"русский", "\xe0\xe3\xe1\xe1\xda\xd8\xd9", "ISO-8859-5"}, - {"ελληνικά", "\xe5\xeb\xeb\xe7\xed\xe9\xea\xdc", "ISO-8859-7"}, - {"Kağan", "Ka\xf0an", "ISO-8859-9"}, - {"Résumé", "R\x8esum\x8e", "macintosh"}, - {"Gdańsk", "Gda\xf1sk", "windows-1250"}, - {"русский", "\xf0\xf3\xf1\xf1\xea\xe8\xe9", "windows-1251"}, - {"Résumé", "R\xe9sum\xe9", "windows-1252"}, - {"ελληνικά", "\xe5\xeb\xeb\xe7\xed\xe9\xea\xdc", "windows-1253"}, - {"Kağan", "Ka\xf0an", "windows-1254"}, - {"עִבְרִית", "\xf2\xc4\xe1\xc0\xf8\xc4\xe9\xfa", "windows-1255"}, - {"العربية", "\xc7\xe1\xda\xd1\xc8\xed\xc9", "windows-1256"}, - {"latviešu", "latvie\xf0u", "windows-1257"}, - {"Việt", "Vi\xea\xf2t", "windows-1258"}, - {"สำหรับ", "\xca\xd3\xcb\xc3\u047a", "windows-874"}, - {"русский", "\xd2\xd5\xd3\xd3\xcb\xc9\xca", "KOI8-R"}, - {"українська", "\xd5\xcb\xd2\xc1\xa7\xce\xd3\xd8\xcb\xc1", "KOI8-U"}, - {"Hello 常用國字標準字體表", "Hello \xb1`\xa5\u03b0\xea\xa6r\xbc\u0437\u01e6r\xc5\xe9\xaa\xed", "big5"}, - {"Hello 常用國字標準字體表", "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed", "gbk"}, - {"Hello 常用國字標準字體表", "Hello \xb3\xa3\xd3\xc3\x87\xf8\xd7\xd6\x98\xcb\x9c\xca\xd7\xd6\xf3\x77\xb1\xed", "gb18030"}, - {"עִבְרִית", "\x81\x30\xfb\x30\x81\x30\xf6\x34\x81\x30\xf9\x33\x81\x30\xf6\x30\x81\x30\xfb\x36\x81\x30\xf6\x34\x81\x30\xfa\x31\x81\x30\xfb\x38", "gb18030"}, - {"㧯", "\x82\x31\x89\x38", "gb18030"}, - {"これは漢字です。", "\x82\xb1\x82\xea\x82\xcd\x8a\xbf\x8e\x9a\x82\xc5\x82\xb7\x81B", "SJIS"}, - {"Hello, 世界!", "Hello, \x90\xa2\x8aE!", "SJIS"}, - {"イウエオカ", "\xb2\xb3\xb4\xb5\xb6", "SJIS"}, - {"これは漢字です。", "\xa4\xb3\xa4\xec\xa4\u03f4\xc1\xbb\xfa\xa4\u01e4\xb9\xa1\xa3", "EUC-JP"}, - {"Hello, 世界!", "Hello, \x1b$B@$3&\x1b(B!", "ISO-2022-JP"}, - {"다음과 같은 조건을 따라야 합니다: 저작자표시", "\xb4\xd9\xc0\xbd\xb0\xfa \xb0\xb0\xc0\xba \xc1\xb6\xb0\xc7\xc0\xbb \xb5\xfb\xb6\xf3\xbe\xdf \xc7մϴ\xd9: \xc0\xfa\xc0\xdb\xc0\xdaǥ\xbd\xc3", "EUC-KR"}, -} - -func TestDecode(t *testing.T) { - testCases := append(testCases, []testCase{ - // Replace multi-byte maximum subpart of ill-formed subsequence with - // single replacement character (WhatWG requirement). - {"Rés\ufffdumé", "Rés\xe1\x80umé", "utf8"}, - }...) - for _, tc := range testCases { - e, _ := Lookup(tc.otherEncoding) - if e == nil { - t.Errorf("%s: not found", tc.otherEncoding) - continue - } - s, err := transformString(e.NewDecoder(), tc.other) - if err != nil { - t.Errorf("%s: decode %q: %v", tc.otherEncoding, tc.other, err) - continue - } - if s != tc.utf8 { - t.Errorf("%s: got %q, want %q", tc.otherEncoding, s, tc.utf8) - } - } -} - -func TestEncode(t *testing.T) { - testCases := append(testCases, []testCase{ - // Use Go-style replacement. - {"Rés\xe1\x80umé", "Rés\ufffd\ufffdumé", "utf8"}, - // U+0144 LATIN SMALL LETTER N WITH ACUTE not supported by encoding. - {"Gdańsk", "Gdańsk", "ISO-8859-11"}, - {"\ufffd", "�", "ISO-8859-11"}, - {"a\xe1\x80b", "a��b", "ISO-8859-11"}, - }...) - for _, tc := range testCases { - e, _ := Lookup(tc.otherEncoding) - if e == nil { - t.Errorf("%s: not found", tc.otherEncoding) - continue - } - s, err := transformString(e.NewEncoder(), tc.utf8) - if err != nil { - t.Errorf("%s: encode %q: %s", tc.otherEncoding, tc.utf8, err) - continue - } - if s != tc.other { - t.Errorf("%s: got %q, want %q", tc.otherEncoding, s, tc.other) - } - } -} - -var sniffTestCases = []struct { - filename, declared, want string -}{ - {"HTTP-charset.html", "text/html; charset=iso-8859-15", "iso-8859-15"}, - {"UTF-16LE-BOM.html", "", "utf-16le"}, - {"UTF-16BE-BOM.html", "", "utf-16be"}, - {"meta-content-attribute.html", "text/html", "iso-8859-15"}, - {"meta-charset-attribute.html", "text/html", "iso-8859-15"}, - {"No-encoding-declaration.html", "text/html", "utf-8"}, - {"HTTP-vs-UTF-8-BOM.html", "text/html; charset=iso-8859-15", "utf-8"}, - {"HTTP-vs-meta-content.html", "text/html; charset=iso-8859-15", "iso-8859-15"}, - {"HTTP-vs-meta-charset.html", "text/html; charset=iso-8859-15", "iso-8859-15"}, - {"UTF-8-BOM-vs-meta-content.html", "text/html", "utf-8"}, - {"UTF-8-BOM-vs-meta-charset.html", "text/html", "utf-8"}, -} - -func TestSniff(t *testing.T) { - switch runtime.GOOS { - case "nacl": // platforms that don't permit direct file system access - t.Skipf("not supported on %q", runtime.GOOS) - } - - for _, tc := range sniffTestCases { - content, err := ioutil.ReadFile("testdata/" + tc.filename) - if err != nil { - t.Errorf("%s: error reading file: %v", tc.filename, err) - continue - } - - _, name, _ := DetermineEncoding(content, tc.declared) - if name != tc.want { - t.Errorf("%s: got %q, want %q", tc.filename, name, tc.want) - continue - } - } -} - -func TestReader(t *testing.T) { - switch runtime.GOOS { - case "nacl": // platforms that don't permit direct file system access - t.Skipf("not supported on %q", runtime.GOOS) - } - - for _, tc := range sniffTestCases { - content, err := ioutil.ReadFile("testdata/" + tc.filename) - if err != nil { - t.Errorf("%s: error reading file: %v", tc.filename, err) - continue - } - - r, err := NewReader(bytes.NewReader(content), tc.declared) - if err != nil { - t.Errorf("%s: error creating reader: %v", tc.filename, err) - continue - } - - got, err := ioutil.ReadAll(r) - if err != nil { - t.Errorf("%s: error reading from charset.NewReader: %v", tc.filename, err) - continue - } - - e, _ := Lookup(tc.want) - want, err := ioutil.ReadAll(transform.NewReader(bytes.NewReader(content), e.NewDecoder())) - if err != nil { - t.Errorf("%s: error decoding with hard-coded charset name: %v", tc.filename, err) - continue - } - - if !bytes.Equal(got, want) { - t.Errorf("%s: got %q, want %q", tc.filename, got, want) - continue - } - } -} - -var metaTestCases = []struct { - meta, want string -}{ - {"", ""}, - {"text/html", ""}, - {"text/html; charset utf-8", ""}, - {"text/html; charset=latin-2", "latin-2"}, - {"text/html; charset; charset = utf-8", "utf-8"}, - {`charset="big5"`, "big5"}, - {"charset='shift_jis'", "shift_jis"}, -} - -func TestFromMeta(t *testing.T) { - for _, tc := range metaTestCases { - got := fromMetaElement(tc.meta) - if got != tc.want { - t.Errorf("%q: got %q, want %q", tc.meta, got, tc.want) - } - } -} - -func TestXML(t *testing.T) { - const s = "r\xe9sum\xe9" - - d := xml.NewDecoder(strings.NewReader(s)) - d.CharsetReader = NewReaderLabel - - var a struct { - Word string - } - err := d.Decode(&a) - if err != nil { - t.Fatalf("Decode: %v", err) - } - - want := "résumé" - if a.Word != want { - t.Errorf("got %q, want %q", a.Word, want) - } -} diff --git a/vendor/golang.org/x/net/html/const.go b/vendor/golang.org/x/net/html/const.go index b37e621247..5eb7c5a8ff 100644 --- a/vendor/golang.org/x/net/html/const.go +++ b/vendor/golang.org/x/net/html/const.go @@ -4,7 +4,7 @@ package html -// Section 12.2.3.2 of the HTML5 specification says "The following elements +// Section 12.2.4.2 of the HTML5 specification says "The following elements // have varying levels of special parsing rules". // https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements var isSpecialElementMap = map[string]bool{ diff --git a/vendor/golang.org/x/net/html/doc.go b/vendor/golang.org/x/net/html/doc.go index 94f496874a..822ed42a04 100644 --- a/vendor/golang.org/x/net/html/doc.go +++ b/vendor/golang.org/x/net/html/doc.go @@ -49,18 +49,18 @@ call to Next. For example, to extract an HTML page's anchor text: for { tt := z.Next() switch tt { - case ErrorToken: + case html.ErrorToken: return z.Err() - case TextToken: + case html.TextToken: if depth > 0 { // emitBytes should copy the []byte it receives, // if it doesn't process it immediately. emitBytes(z.Text()) } - case StartTagToken, EndTagToken: + case html.StartTagToken, html.EndTagToken: tn, _ := z.TagName() if len(tn) == 1 && tn[0] == 'a' { - if tt == StartTagToken { + if tt == html.StartTagToken { depth++ } else { depth-- diff --git a/vendor/golang.org/x/net/html/entity.go b/vendor/golang.org/x/net/html/entity.go index a50c04c60e..b628880a01 100644 --- a/vendor/golang.org/x/net/html/entity.go +++ b/vendor/golang.org/x/net/html/entity.go @@ -75,2083 +75,2083 @@ var entity = map[string]rune{ "Copf;": '\U00002102', "Coproduct;": '\U00002210', "CounterClockwiseContourIntegral;": '\U00002233', - "Cross;": '\U00002A2F', - "Cscr;": '\U0001D49E', - "Cup;": '\U000022D3', - "CupCap;": '\U0000224D', - "DD;": '\U00002145', - "DDotrahd;": '\U00002911', - "DJcy;": '\U00000402', - "DScy;": '\U00000405', - "DZcy;": '\U0000040F', - "Dagger;": '\U00002021', - "Darr;": '\U000021A1', - "Dashv;": '\U00002AE4', - "Dcaron;": '\U0000010E', - "Dcy;": '\U00000414', - "Del;": '\U00002207', - "Delta;": '\U00000394', - "Dfr;": '\U0001D507', - "DiacriticalAcute;": '\U000000B4', - "DiacriticalDot;": '\U000002D9', - "DiacriticalDoubleAcute;": '\U000002DD', - "DiacriticalGrave;": '\U00000060', - "DiacriticalTilde;": '\U000002DC', - "Diamond;": '\U000022C4', - "DifferentialD;": '\U00002146', - "Dopf;": '\U0001D53B', - "Dot;": '\U000000A8', - "DotDot;": '\U000020DC', - "DotEqual;": '\U00002250', - "DoubleContourIntegral;": '\U0000222F', - "DoubleDot;": '\U000000A8', - "DoubleDownArrow;": '\U000021D3', - "DoubleLeftArrow;": '\U000021D0', - "DoubleLeftRightArrow;": '\U000021D4', - "DoubleLeftTee;": '\U00002AE4', - "DoubleLongLeftArrow;": '\U000027F8', - "DoubleLongLeftRightArrow;": '\U000027FA', - "DoubleLongRightArrow;": '\U000027F9', - "DoubleRightArrow;": '\U000021D2', - "DoubleRightTee;": '\U000022A8', - "DoubleUpArrow;": '\U000021D1', - "DoubleUpDownArrow;": '\U000021D5', - "DoubleVerticalBar;": '\U00002225', - "DownArrow;": '\U00002193', - "DownArrowBar;": '\U00002913', - "DownArrowUpArrow;": '\U000021F5', - "DownBreve;": '\U00000311', - "DownLeftRightVector;": '\U00002950', - "DownLeftTeeVector;": '\U0000295E', - "DownLeftVector;": '\U000021BD', - "DownLeftVectorBar;": '\U00002956', - "DownRightTeeVector;": '\U0000295F', - "DownRightVector;": '\U000021C1', - "DownRightVectorBar;": '\U00002957', - "DownTee;": '\U000022A4', - "DownTeeArrow;": '\U000021A7', - "Downarrow;": '\U000021D3', - "Dscr;": '\U0001D49F', - "Dstrok;": '\U00000110', - "ENG;": '\U0000014A', - "ETH;": '\U000000D0', - "Eacute;": '\U000000C9', - "Ecaron;": '\U0000011A', - "Ecirc;": '\U000000CA', - "Ecy;": '\U0000042D', - "Edot;": '\U00000116', - "Efr;": '\U0001D508', - "Egrave;": '\U000000C8', - "Element;": '\U00002208', - "Emacr;": '\U00000112', - "EmptySmallSquare;": '\U000025FB', - "EmptyVerySmallSquare;": '\U000025AB', - "Eogon;": '\U00000118', - "Eopf;": '\U0001D53C', - "Epsilon;": '\U00000395', - "Equal;": '\U00002A75', - "EqualTilde;": '\U00002242', - "Equilibrium;": '\U000021CC', - "Escr;": '\U00002130', - "Esim;": '\U00002A73', - "Eta;": '\U00000397', - "Euml;": '\U000000CB', - "Exists;": '\U00002203', - "ExponentialE;": '\U00002147', - "Fcy;": '\U00000424', - "Ffr;": '\U0001D509', - "FilledSmallSquare;": '\U000025FC', - "FilledVerySmallSquare;": '\U000025AA', - "Fopf;": '\U0001D53D', - "ForAll;": '\U00002200', - "Fouriertrf;": '\U00002131', - "Fscr;": '\U00002131', - "GJcy;": '\U00000403', - "GT;": '\U0000003E', - "Gamma;": '\U00000393', - "Gammad;": '\U000003DC', - "Gbreve;": '\U0000011E', - "Gcedil;": '\U00000122', - "Gcirc;": '\U0000011C', - "Gcy;": '\U00000413', - "Gdot;": '\U00000120', - "Gfr;": '\U0001D50A', - "Gg;": '\U000022D9', - "Gopf;": '\U0001D53E', - "GreaterEqual;": '\U00002265', - "GreaterEqualLess;": '\U000022DB', - "GreaterFullEqual;": '\U00002267', - "GreaterGreater;": '\U00002AA2', - "GreaterLess;": '\U00002277', - "GreaterSlantEqual;": '\U00002A7E', - "GreaterTilde;": '\U00002273', - "Gscr;": '\U0001D4A2', - "Gt;": '\U0000226B', - "HARDcy;": '\U0000042A', - "Hacek;": '\U000002C7', - "Hat;": '\U0000005E', - "Hcirc;": '\U00000124', - "Hfr;": '\U0000210C', - "HilbertSpace;": '\U0000210B', - "Hopf;": '\U0000210D', - "HorizontalLine;": '\U00002500', - "Hscr;": '\U0000210B', - "Hstrok;": '\U00000126', - "HumpDownHump;": '\U0000224E', - "HumpEqual;": '\U0000224F', - "IEcy;": '\U00000415', - "IJlig;": '\U00000132', - "IOcy;": '\U00000401', - "Iacute;": '\U000000CD', - "Icirc;": '\U000000CE', - "Icy;": '\U00000418', - "Idot;": '\U00000130', - "Ifr;": '\U00002111', - "Igrave;": '\U000000CC', - "Im;": '\U00002111', - "Imacr;": '\U0000012A', - "ImaginaryI;": '\U00002148', - "Implies;": '\U000021D2', - "Int;": '\U0000222C', - "Integral;": '\U0000222B', - "Intersection;": '\U000022C2', - "InvisibleComma;": '\U00002063', - "InvisibleTimes;": '\U00002062', - "Iogon;": '\U0000012E', - "Iopf;": '\U0001D540', - "Iota;": '\U00000399', - "Iscr;": '\U00002110', - "Itilde;": '\U00000128', - "Iukcy;": '\U00000406', - "Iuml;": '\U000000CF', - "Jcirc;": '\U00000134', - "Jcy;": '\U00000419', - "Jfr;": '\U0001D50D', - "Jopf;": '\U0001D541', - "Jscr;": '\U0001D4A5', - "Jsercy;": '\U00000408', - "Jukcy;": '\U00000404', - "KHcy;": '\U00000425', - "KJcy;": '\U0000040C', - "Kappa;": '\U0000039A', - "Kcedil;": '\U00000136', - "Kcy;": '\U0000041A', - "Kfr;": '\U0001D50E', - "Kopf;": '\U0001D542', - "Kscr;": '\U0001D4A6', - "LJcy;": '\U00000409', - "LT;": '\U0000003C', - "Lacute;": '\U00000139', - "Lambda;": '\U0000039B', - "Lang;": '\U000027EA', - "Laplacetrf;": '\U00002112', - "Larr;": '\U0000219E', - "Lcaron;": '\U0000013D', - "Lcedil;": '\U0000013B', - "Lcy;": '\U0000041B', - "LeftAngleBracket;": '\U000027E8', - "LeftArrow;": '\U00002190', - "LeftArrowBar;": '\U000021E4', - "LeftArrowRightArrow;": '\U000021C6', - "LeftCeiling;": '\U00002308', - "LeftDoubleBracket;": '\U000027E6', - "LeftDownTeeVector;": '\U00002961', - "LeftDownVector;": '\U000021C3', - "LeftDownVectorBar;": '\U00002959', - "LeftFloor;": '\U0000230A', - "LeftRightArrow;": '\U00002194', - "LeftRightVector;": '\U0000294E', - "LeftTee;": '\U000022A3', - "LeftTeeArrow;": '\U000021A4', - "LeftTeeVector;": '\U0000295A', - "LeftTriangle;": '\U000022B2', - "LeftTriangleBar;": '\U000029CF', - "LeftTriangleEqual;": '\U000022B4', - "LeftUpDownVector;": '\U00002951', - "LeftUpTeeVector;": '\U00002960', - "LeftUpVector;": '\U000021BF', - "LeftUpVectorBar;": '\U00002958', - "LeftVector;": '\U000021BC', - "LeftVectorBar;": '\U00002952', - "Leftarrow;": '\U000021D0', - "Leftrightarrow;": '\U000021D4', - "LessEqualGreater;": '\U000022DA', - "LessFullEqual;": '\U00002266', - "LessGreater;": '\U00002276', - "LessLess;": '\U00002AA1', - "LessSlantEqual;": '\U00002A7D', - "LessTilde;": '\U00002272', - "Lfr;": '\U0001D50F', - "Ll;": '\U000022D8', - "Lleftarrow;": '\U000021DA', - "Lmidot;": '\U0000013F', - "LongLeftArrow;": '\U000027F5', - "LongLeftRightArrow;": '\U000027F7', - "LongRightArrow;": '\U000027F6', - "Longleftarrow;": '\U000027F8', - "Longleftrightarrow;": '\U000027FA', - "Longrightarrow;": '\U000027F9', - "Lopf;": '\U0001D543', - "LowerLeftArrow;": '\U00002199', - "LowerRightArrow;": '\U00002198', - "Lscr;": '\U00002112', - "Lsh;": '\U000021B0', - "Lstrok;": '\U00000141', - "Lt;": '\U0000226A', - "Map;": '\U00002905', - "Mcy;": '\U0000041C', - "MediumSpace;": '\U0000205F', - "Mellintrf;": '\U00002133', - "Mfr;": '\U0001D510', - "MinusPlus;": '\U00002213', - "Mopf;": '\U0001D544', - "Mscr;": '\U00002133', - "Mu;": '\U0000039C', - "NJcy;": '\U0000040A', - "Nacute;": '\U00000143', - "Ncaron;": '\U00000147', - "Ncedil;": '\U00000145', - "Ncy;": '\U0000041D', - "NegativeMediumSpace;": '\U0000200B', - "NegativeThickSpace;": '\U0000200B', - "NegativeThinSpace;": '\U0000200B', - "NegativeVeryThinSpace;": '\U0000200B', - "NestedGreaterGreater;": '\U0000226B', - "NestedLessLess;": '\U0000226A', - "NewLine;": '\U0000000A', - "Nfr;": '\U0001D511', - "NoBreak;": '\U00002060', - "NonBreakingSpace;": '\U000000A0', - "Nopf;": '\U00002115', - "Not;": '\U00002AEC', - "NotCongruent;": '\U00002262', - "NotCupCap;": '\U0000226D', - "NotDoubleVerticalBar;": '\U00002226', - "NotElement;": '\U00002209', - "NotEqual;": '\U00002260', - "NotExists;": '\U00002204', - "NotGreater;": '\U0000226F', - "NotGreaterEqual;": '\U00002271', - "NotGreaterLess;": '\U00002279', - "NotGreaterTilde;": '\U00002275', - "NotLeftTriangle;": '\U000022EA', - "NotLeftTriangleEqual;": '\U000022EC', - "NotLess;": '\U0000226E', - "NotLessEqual;": '\U00002270', - "NotLessGreater;": '\U00002278', - "NotLessTilde;": '\U00002274', - "NotPrecedes;": '\U00002280', - "NotPrecedesSlantEqual;": '\U000022E0', - "NotReverseElement;": '\U0000220C', - "NotRightTriangle;": '\U000022EB', - "NotRightTriangleEqual;": '\U000022ED', - "NotSquareSubsetEqual;": '\U000022E2', - "NotSquareSupersetEqual;": '\U000022E3', - "NotSubsetEqual;": '\U00002288', - "NotSucceeds;": '\U00002281', - "NotSucceedsSlantEqual;": '\U000022E1', - "NotSupersetEqual;": '\U00002289', - "NotTilde;": '\U00002241', - "NotTildeEqual;": '\U00002244', - "NotTildeFullEqual;": '\U00002247', - "NotTildeTilde;": '\U00002249', - "NotVerticalBar;": '\U00002224', - "Nscr;": '\U0001D4A9', - "Ntilde;": '\U000000D1', - "Nu;": '\U0000039D', - "OElig;": '\U00000152', - "Oacute;": '\U000000D3', - "Ocirc;": '\U000000D4', - "Ocy;": '\U0000041E', - "Odblac;": '\U00000150', - "Ofr;": '\U0001D512', - "Ograve;": '\U000000D2', - "Omacr;": '\U0000014C', - "Omega;": '\U000003A9', - "Omicron;": '\U0000039F', - "Oopf;": '\U0001D546', - "OpenCurlyDoubleQuote;": '\U0000201C', - "OpenCurlyQuote;": '\U00002018', - "Or;": '\U00002A54', - "Oscr;": '\U0001D4AA', - "Oslash;": '\U000000D8', - "Otilde;": '\U000000D5', - "Otimes;": '\U00002A37', - "Ouml;": '\U000000D6', - "OverBar;": '\U0000203E', - "OverBrace;": '\U000023DE', - "OverBracket;": '\U000023B4', - "OverParenthesis;": '\U000023DC', - "PartialD;": '\U00002202', - "Pcy;": '\U0000041F', - "Pfr;": '\U0001D513', - "Phi;": '\U000003A6', - "Pi;": '\U000003A0', - "PlusMinus;": '\U000000B1', - "Poincareplane;": '\U0000210C', - "Popf;": '\U00002119', - "Pr;": '\U00002ABB', - "Precedes;": '\U0000227A', - "PrecedesEqual;": '\U00002AAF', - "PrecedesSlantEqual;": '\U0000227C', - "PrecedesTilde;": '\U0000227E', - "Prime;": '\U00002033', - "Product;": '\U0000220F', - "Proportion;": '\U00002237', - "Proportional;": '\U0000221D', - "Pscr;": '\U0001D4AB', - "Psi;": '\U000003A8', - "QUOT;": '\U00000022', - "Qfr;": '\U0001D514', - "Qopf;": '\U0000211A', - "Qscr;": '\U0001D4AC', - "RBarr;": '\U00002910', - "REG;": '\U000000AE', - "Racute;": '\U00000154', - "Rang;": '\U000027EB', - "Rarr;": '\U000021A0', - "Rarrtl;": '\U00002916', - "Rcaron;": '\U00000158', - "Rcedil;": '\U00000156', - "Rcy;": '\U00000420', - "Re;": '\U0000211C', - "ReverseElement;": '\U0000220B', - "ReverseEquilibrium;": '\U000021CB', - "ReverseUpEquilibrium;": '\U0000296F', - "Rfr;": '\U0000211C', - "Rho;": '\U000003A1', - "RightAngleBracket;": '\U000027E9', - "RightArrow;": '\U00002192', - "RightArrowBar;": '\U000021E5', - "RightArrowLeftArrow;": '\U000021C4', - "RightCeiling;": '\U00002309', - "RightDoubleBracket;": '\U000027E7', - "RightDownTeeVector;": '\U0000295D', - "RightDownVector;": '\U000021C2', - "RightDownVectorBar;": '\U00002955', - "RightFloor;": '\U0000230B', - "RightTee;": '\U000022A2', - "RightTeeArrow;": '\U000021A6', - "RightTeeVector;": '\U0000295B', - "RightTriangle;": '\U000022B3', - "RightTriangleBar;": '\U000029D0', - "RightTriangleEqual;": '\U000022B5', - "RightUpDownVector;": '\U0000294F', - "RightUpTeeVector;": '\U0000295C', - "RightUpVector;": '\U000021BE', - "RightUpVectorBar;": '\U00002954', - "RightVector;": '\U000021C0', - "RightVectorBar;": '\U00002953', - "Rightarrow;": '\U000021D2', - "Ropf;": '\U0000211D', - "RoundImplies;": '\U00002970', - "Rrightarrow;": '\U000021DB', - "Rscr;": '\U0000211B', - "Rsh;": '\U000021B1', - "RuleDelayed;": '\U000029F4', - "SHCHcy;": '\U00000429', - "SHcy;": '\U00000428', - "SOFTcy;": '\U0000042C', - "Sacute;": '\U0000015A', - "Sc;": '\U00002ABC', - "Scaron;": '\U00000160', - "Scedil;": '\U0000015E', - "Scirc;": '\U0000015C', - "Scy;": '\U00000421', - "Sfr;": '\U0001D516', - "ShortDownArrow;": '\U00002193', - "ShortLeftArrow;": '\U00002190', - "ShortRightArrow;": '\U00002192', - "ShortUpArrow;": '\U00002191', - "Sigma;": '\U000003A3', - "SmallCircle;": '\U00002218', - "Sopf;": '\U0001D54A', - "Sqrt;": '\U0000221A', - "Square;": '\U000025A1', - "SquareIntersection;": '\U00002293', - "SquareSubset;": '\U0000228F', - "SquareSubsetEqual;": '\U00002291', - "SquareSuperset;": '\U00002290', - "SquareSupersetEqual;": '\U00002292', - "SquareUnion;": '\U00002294', - "Sscr;": '\U0001D4AE', - "Star;": '\U000022C6', - "Sub;": '\U000022D0', - "Subset;": '\U000022D0', - "SubsetEqual;": '\U00002286', - "Succeeds;": '\U0000227B', - "SucceedsEqual;": '\U00002AB0', - "SucceedsSlantEqual;": '\U0000227D', - "SucceedsTilde;": '\U0000227F', - "SuchThat;": '\U0000220B', - "Sum;": '\U00002211', - "Sup;": '\U000022D1', - "Superset;": '\U00002283', - "SupersetEqual;": '\U00002287', - "Supset;": '\U000022D1', - "THORN;": '\U000000DE', - "TRADE;": '\U00002122', - "TSHcy;": '\U0000040B', - "TScy;": '\U00000426', - "Tab;": '\U00000009', - "Tau;": '\U000003A4', - "Tcaron;": '\U00000164', - "Tcedil;": '\U00000162', - "Tcy;": '\U00000422', - "Tfr;": '\U0001D517', - "Therefore;": '\U00002234', - "Theta;": '\U00000398', - "ThinSpace;": '\U00002009', - "Tilde;": '\U0000223C', - "TildeEqual;": '\U00002243', - "TildeFullEqual;": '\U00002245', - "TildeTilde;": '\U00002248', - "Topf;": '\U0001D54B', - "TripleDot;": '\U000020DB', - "Tscr;": '\U0001D4AF', - "Tstrok;": '\U00000166', - "Uacute;": '\U000000DA', - "Uarr;": '\U0000219F', - "Uarrocir;": '\U00002949', - "Ubrcy;": '\U0000040E', - "Ubreve;": '\U0000016C', - "Ucirc;": '\U000000DB', - "Ucy;": '\U00000423', - "Udblac;": '\U00000170', - "Ufr;": '\U0001D518', - "Ugrave;": '\U000000D9', - "Umacr;": '\U0000016A', - "UnderBar;": '\U0000005F', - "UnderBrace;": '\U000023DF', - "UnderBracket;": '\U000023B5', - "UnderParenthesis;": '\U000023DD', - "Union;": '\U000022C3', - "UnionPlus;": '\U0000228E', - "Uogon;": '\U00000172', - "Uopf;": '\U0001D54C', - "UpArrow;": '\U00002191', - "UpArrowBar;": '\U00002912', - "UpArrowDownArrow;": '\U000021C5', - "UpDownArrow;": '\U00002195', - "UpEquilibrium;": '\U0000296E', - "UpTee;": '\U000022A5', - "UpTeeArrow;": '\U000021A5', - "Uparrow;": '\U000021D1', - "Updownarrow;": '\U000021D5', - "UpperLeftArrow;": '\U00002196', - "UpperRightArrow;": '\U00002197', - "Upsi;": '\U000003D2', - "Upsilon;": '\U000003A5', - "Uring;": '\U0000016E', - "Uscr;": '\U0001D4B0', - "Utilde;": '\U00000168', - "Uuml;": '\U000000DC', - "VDash;": '\U000022AB', - "Vbar;": '\U00002AEB', - "Vcy;": '\U00000412', - "Vdash;": '\U000022A9', - "Vdashl;": '\U00002AE6', - "Vee;": '\U000022C1', - "Verbar;": '\U00002016', - "Vert;": '\U00002016', - "VerticalBar;": '\U00002223', - "VerticalLine;": '\U0000007C', - "VerticalSeparator;": '\U00002758', - "VerticalTilde;": '\U00002240', - "VeryThinSpace;": '\U0000200A', - "Vfr;": '\U0001D519', - "Vopf;": '\U0001D54D', - "Vscr;": '\U0001D4B1', - "Vvdash;": '\U000022AA', - "Wcirc;": '\U00000174', - "Wedge;": '\U000022C0', - "Wfr;": '\U0001D51A', - "Wopf;": '\U0001D54E', - "Wscr;": '\U0001D4B2', - "Xfr;": '\U0001D51B', - "Xi;": '\U0000039E', - "Xopf;": '\U0001D54F', - "Xscr;": '\U0001D4B3', - "YAcy;": '\U0000042F', - "YIcy;": '\U00000407', - "YUcy;": '\U0000042E', - "Yacute;": '\U000000DD', - "Ycirc;": '\U00000176', - "Ycy;": '\U0000042B', - "Yfr;": '\U0001D51C', - "Yopf;": '\U0001D550', - "Yscr;": '\U0001D4B4', - "Yuml;": '\U00000178', - "ZHcy;": '\U00000416', - "Zacute;": '\U00000179', - "Zcaron;": '\U0000017D', - "Zcy;": '\U00000417', - "Zdot;": '\U0000017B', - "ZeroWidthSpace;": '\U0000200B', - "Zeta;": '\U00000396', - "Zfr;": '\U00002128', - "Zopf;": '\U00002124', - "Zscr;": '\U0001D4B5', - "aacute;": '\U000000E1', - "abreve;": '\U00000103', - "ac;": '\U0000223E', - "acd;": '\U0000223F', - "acirc;": '\U000000E2', - "acute;": '\U000000B4', - "acy;": '\U00000430', - "aelig;": '\U000000E6', - "af;": '\U00002061', - "afr;": '\U0001D51E', - "agrave;": '\U000000E0', - "alefsym;": '\U00002135', - "aleph;": '\U00002135', - "alpha;": '\U000003B1', - "amacr;": '\U00000101', - "amalg;": '\U00002A3F', - "amp;": '\U00000026', - "and;": '\U00002227', - "andand;": '\U00002A55', - "andd;": '\U00002A5C', - "andslope;": '\U00002A58', - "andv;": '\U00002A5A', - "ang;": '\U00002220', - "ange;": '\U000029A4', - "angle;": '\U00002220', - "angmsd;": '\U00002221', - "angmsdaa;": '\U000029A8', - "angmsdab;": '\U000029A9', - "angmsdac;": '\U000029AA', - "angmsdad;": '\U000029AB', - "angmsdae;": '\U000029AC', - "angmsdaf;": '\U000029AD', - "angmsdag;": '\U000029AE', - "angmsdah;": '\U000029AF', - "angrt;": '\U0000221F', - "angrtvb;": '\U000022BE', - "angrtvbd;": '\U0000299D', - "angsph;": '\U00002222', - "angst;": '\U000000C5', - "angzarr;": '\U0000237C', - "aogon;": '\U00000105', - "aopf;": '\U0001D552', - "ap;": '\U00002248', - "apE;": '\U00002A70', - "apacir;": '\U00002A6F', - "ape;": '\U0000224A', - "apid;": '\U0000224B', - "apos;": '\U00000027', - "approx;": '\U00002248', - "approxeq;": '\U0000224A', - "aring;": '\U000000E5', - "ascr;": '\U0001D4B6', - "ast;": '\U0000002A', - "asymp;": '\U00002248', - "asympeq;": '\U0000224D', - "atilde;": '\U000000E3', - "auml;": '\U000000E4', - "awconint;": '\U00002233', - "awint;": '\U00002A11', - "bNot;": '\U00002AED', - "backcong;": '\U0000224C', - "backepsilon;": '\U000003F6', - "backprime;": '\U00002035', - "backsim;": '\U0000223D', - "backsimeq;": '\U000022CD', - "barvee;": '\U000022BD', - "barwed;": '\U00002305', - "barwedge;": '\U00002305', - "bbrk;": '\U000023B5', - "bbrktbrk;": '\U000023B6', - "bcong;": '\U0000224C', - "bcy;": '\U00000431', - "bdquo;": '\U0000201E', - "becaus;": '\U00002235', - "because;": '\U00002235', - "bemptyv;": '\U000029B0', - "bepsi;": '\U000003F6', - "bernou;": '\U0000212C', - "beta;": '\U000003B2', - "beth;": '\U00002136', - "between;": '\U0000226C', - "bfr;": '\U0001D51F', - "bigcap;": '\U000022C2', - "bigcirc;": '\U000025EF', - "bigcup;": '\U000022C3', - "bigodot;": '\U00002A00', - "bigoplus;": '\U00002A01', - "bigotimes;": '\U00002A02', - "bigsqcup;": '\U00002A06', - "bigstar;": '\U00002605', - "bigtriangledown;": '\U000025BD', - "bigtriangleup;": '\U000025B3', - "biguplus;": '\U00002A04', - "bigvee;": '\U000022C1', - "bigwedge;": '\U000022C0', - "bkarow;": '\U0000290D', - "blacklozenge;": '\U000029EB', - "blacksquare;": '\U000025AA', - "blacktriangle;": '\U000025B4', - "blacktriangledown;": '\U000025BE', - "blacktriangleleft;": '\U000025C2', - "blacktriangleright;": '\U000025B8', - "blank;": '\U00002423', - "blk12;": '\U00002592', - "blk14;": '\U00002591', - "blk34;": '\U00002593', - "block;": '\U00002588', - "bnot;": '\U00002310', - "bopf;": '\U0001D553', - "bot;": '\U000022A5', - "bottom;": '\U000022A5', - "bowtie;": '\U000022C8', - "boxDL;": '\U00002557', - "boxDR;": '\U00002554', - "boxDl;": '\U00002556', - "boxDr;": '\U00002553', - "boxH;": '\U00002550', - "boxHD;": '\U00002566', - "boxHU;": '\U00002569', - "boxHd;": '\U00002564', - "boxHu;": '\U00002567', - "boxUL;": '\U0000255D', - "boxUR;": '\U0000255A', - "boxUl;": '\U0000255C', - "boxUr;": '\U00002559', - "boxV;": '\U00002551', - "boxVH;": '\U0000256C', - "boxVL;": '\U00002563', - "boxVR;": '\U00002560', - "boxVh;": '\U0000256B', - "boxVl;": '\U00002562', - "boxVr;": '\U0000255F', - "boxbox;": '\U000029C9', - "boxdL;": '\U00002555', - "boxdR;": '\U00002552', - "boxdl;": '\U00002510', - "boxdr;": '\U0000250C', - "boxh;": '\U00002500', - "boxhD;": '\U00002565', - "boxhU;": '\U00002568', - "boxhd;": '\U0000252C', - "boxhu;": '\U00002534', - "boxminus;": '\U0000229F', - "boxplus;": '\U0000229E', - "boxtimes;": '\U000022A0', - "boxuL;": '\U0000255B', - "boxuR;": '\U00002558', - "boxul;": '\U00002518', - "boxur;": '\U00002514', - "boxv;": '\U00002502', - "boxvH;": '\U0000256A', - "boxvL;": '\U00002561', - "boxvR;": '\U0000255E', - "boxvh;": '\U0000253C', - "boxvl;": '\U00002524', - "boxvr;": '\U0000251C', - "bprime;": '\U00002035', - "breve;": '\U000002D8', - "brvbar;": '\U000000A6', - "bscr;": '\U0001D4B7', - "bsemi;": '\U0000204F', - "bsim;": '\U0000223D', - "bsime;": '\U000022CD', - "bsol;": '\U0000005C', - "bsolb;": '\U000029C5', - "bsolhsub;": '\U000027C8', - "bull;": '\U00002022', - "bullet;": '\U00002022', - "bump;": '\U0000224E', - "bumpE;": '\U00002AAE', - "bumpe;": '\U0000224F', - "bumpeq;": '\U0000224F', - "cacute;": '\U00000107', - "cap;": '\U00002229', - "capand;": '\U00002A44', - "capbrcup;": '\U00002A49', - "capcap;": '\U00002A4B', - "capcup;": '\U00002A47', - "capdot;": '\U00002A40', - "caret;": '\U00002041', - "caron;": '\U000002C7', - "ccaps;": '\U00002A4D', - "ccaron;": '\U0000010D', - "ccedil;": '\U000000E7', - "ccirc;": '\U00000109', - "ccups;": '\U00002A4C', - "ccupssm;": '\U00002A50', - "cdot;": '\U0000010B', - "cedil;": '\U000000B8', - "cemptyv;": '\U000029B2', - "cent;": '\U000000A2', - "centerdot;": '\U000000B7', - "cfr;": '\U0001D520', - "chcy;": '\U00000447', - "check;": '\U00002713', - "checkmark;": '\U00002713', - "chi;": '\U000003C7', - "cir;": '\U000025CB', - "cirE;": '\U000029C3', - "circ;": '\U000002C6', - "circeq;": '\U00002257', - "circlearrowleft;": '\U000021BA', - "circlearrowright;": '\U000021BB', - "circledR;": '\U000000AE', - "circledS;": '\U000024C8', - "circledast;": '\U0000229B', - "circledcirc;": '\U0000229A', - "circleddash;": '\U0000229D', - "cire;": '\U00002257', - "cirfnint;": '\U00002A10', - "cirmid;": '\U00002AEF', - "cirscir;": '\U000029C2', - "clubs;": '\U00002663', - "clubsuit;": '\U00002663', - "colon;": '\U0000003A', - "colone;": '\U00002254', - "coloneq;": '\U00002254', - "comma;": '\U0000002C', - "commat;": '\U00000040', - "comp;": '\U00002201', - "compfn;": '\U00002218', - "complement;": '\U00002201', - "complexes;": '\U00002102', - "cong;": '\U00002245', - "congdot;": '\U00002A6D', - "conint;": '\U0000222E', - "copf;": '\U0001D554', - "coprod;": '\U00002210', - "copy;": '\U000000A9', - "copysr;": '\U00002117', - "crarr;": '\U000021B5', - "cross;": '\U00002717', - "cscr;": '\U0001D4B8', - "csub;": '\U00002ACF', - "csube;": '\U00002AD1', - "csup;": '\U00002AD0', - "csupe;": '\U00002AD2', - "ctdot;": '\U000022EF', - "cudarrl;": '\U00002938', - "cudarrr;": '\U00002935', - "cuepr;": '\U000022DE', - "cuesc;": '\U000022DF', - "cularr;": '\U000021B6', - "cularrp;": '\U0000293D', - "cup;": '\U0000222A', - "cupbrcap;": '\U00002A48', - "cupcap;": '\U00002A46', - "cupcup;": '\U00002A4A', - "cupdot;": '\U0000228D', - "cupor;": '\U00002A45', - "curarr;": '\U000021B7', - "curarrm;": '\U0000293C', - "curlyeqprec;": '\U000022DE', - "curlyeqsucc;": '\U000022DF', - "curlyvee;": '\U000022CE', - "curlywedge;": '\U000022CF', - "curren;": '\U000000A4', - "curvearrowleft;": '\U000021B6', - "curvearrowright;": '\U000021B7', - "cuvee;": '\U000022CE', - "cuwed;": '\U000022CF', - "cwconint;": '\U00002232', - "cwint;": '\U00002231', - "cylcty;": '\U0000232D', - "dArr;": '\U000021D3', - "dHar;": '\U00002965', - "dagger;": '\U00002020', - "daleth;": '\U00002138', - "darr;": '\U00002193', - "dash;": '\U00002010', - "dashv;": '\U000022A3', - "dbkarow;": '\U0000290F', - "dblac;": '\U000002DD', - "dcaron;": '\U0000010F', - "dcy;": '\U00000434', - "dd;": '\U00002146', - "ddagger;": '\U00002021', - "ddarr;": '\U000021CA', - "ddotseq;": '\U00002A77', - "deg;": '\U000000B0', - "delta;": '\U000003B4', - "demptyv;": '\U000029B1', - "dfisht;": '\U0000297F', - "dfr;": '\U0001D521', - "dharl;": '\U000021C3', - "dharr;": '\U000021C2', - "diam;": '\U000022C4', - "diamond;": '\U000022C4', - "diamondsuit;": '\U00002666', - "diams;": '\U00002666', - "die;": '\U000000A8', - "digamma;": '\U000003DD', - "disin;": '\U000022F2', - "div;": '\U000000F7', - "divide;": '\U000000F7', - "divideontimes;": '\U000022C7', - "divonx;": '\U000022C7', - "djcy;": '\U00000452', - "dlcorn;": '\U0000231E', - "dlcrop;": '\U0000230D', - "dollar;": '\U00000024', - "dopf;": '\U0001D555', - "dot;": '\U000002D9', - "doteq;": '\U00002250', - "doteqdot;": '\U00002251', - "dotminus;": '\U00002238', - "dotplus;": '\U00002214', - "dotsquare;": '\U000022A1', - "doublebarwedge;": '\U00002306', - "downarrow;": '\U00002193', - "downdownarrows;": '\U000021CA', - "downharpoonleft;": '\U000021C3', - "downharpoonright;": '\U000021C2', - "drbkarow;": '\U00002910', - "drcorn;": '\U0000231F', - "drcrop;": '\U0000230C', - "dscr;": '\U0001D4B9', - "dscy;": '\U00000455', - "dsol;": '\U000029F6', - "dstrok;": '\U00000111', - "dtdot;": '\U000022F1', - "dtri;": '\U000025BF', - "dtrif;": '\U000025BE', - "duarr;": '\U000021F5', - "duhar;": '\U0000296F', - "dwangle;": '\U000029A6', - "dzcy;": '\U0000045F', - "dzigrarr;": '\U000027FF', - "eDDot;": '\U00002A77', - "eDot;": '\U00002251', - "eacute;": '\U000000E9', - "easter;": '\U00002A6E', - "ecaron;": '\U0000011B', - "ecir;": '\U00002256', - "ecirc;": '\U000000EA', - "ecolon;": '\U00002255', - "ecy;": '\U0000044D', - "edot;": '\U00000117', - "ee;": '\U00002147', - "efDot;": '\U00002252', - "efr;": '\U0001D522', - "eg;": '\U00002A9A', - "egrave;": '\U000000E8', - "egs;": '\U00002A96', - "egsdot;": '\U00002A98', - "el;": '\U00002A99', - "elinters;": '\U000023E7', - "ell;": '\U00002113', - "els;": '\U00002A95', - "elsdot;": '\U00002A97', - "emacr;": '\U00000113', - "empty;": '\U00002205', - "emptyset;": '\U00002205', - "emptyv;": '\U00002205', - "emsp;": '\U00002003', - "emsp13;": '\U00002004', - "emsp14;": '\U00002005', - "eng;": '\U0000014B', - "ensp;": '\U00002002', - "eogon;": '\U00000119', - "eopf;": '\U0001D556', - "epar;": '\U000022D5', - "eparsl;": '\U000029E3', - "eplus;": '\U00002A71', - "epsi;": '\U000003B5', - "epsilon;": '\U000003B5', - "epsiv;": '\U000003F5', - "eqcirc;": '\U00002256', - "eqcolon;": '\U00002255', - "eqsim;": '\U00002242', - "eqslantgtr;": '\U00002A96', - "eqslantless;": '\U00002A95', - "equals;": '\U0000003D', - "equest;": '\U0000225F', - "equiv;": '\U00002261', - "equivDD;": '\U00002A78', - "eqvparsl;": '\U000029E5', - "erDot;": '\U00002253', - "erarr;": '\U00002971', - "escr;": '\U0000212F', - "esdot;": '\U00002250', - "esim;": '\U00002242', - "eta;": '\U000003B7', - "eth;": '\U000000F0', - "euml;": '\U000000EB', - "euro;": '\U000020AC', - "excl;": '\U00000021', - "exist;": '\U00002203', - "expectation;": '\U00002130', - "exponentiale;": '\U00002147', - "fallingdotseq;": '\U00002252', - "fcy;": '\U00000444', - "female;": '\U00002640', - "ffilig;": '\U0000FB03', - "fflig;": '\U0000FB00', - "ffllig;": '\U0000FB04', - "ffr;": '\U0001D523', - "filig;": '\U0000FB01', - "flat;": '\U0000266D', - "fllig;": '\U0000FB02', - "fltns;": '\U000025B1', - "fnof;": '\U00000192', - "fopf;": '\U0001D557', - "forall;": '\U00002200', - "fork;": '\U000022D4', - "forkv;": '\U00002AD9', - "fpartint;": '\U00002A0D', - "frac12;": '\U000000BD', - "frac13;": '\U00002153', - "frac14;": '\U000000BC', - "frac15;": '\U00002155', - "frac16;": '\U00002159', - "frac18;": '\U0000215B', - "frac23;": '\U00002154', - "frac25;": '\U00002156', - "frac34;": '\U000000BE', - "frac35;": '\U00002157', - "frac38;": '\U0000215C', - "frac45;": '\U00002158', - "frac56;": '\U0000215A', - "frac58;": '\U0000215D', - "frac78;": '\U0000215E', - "frasl;": '\U00002044', - "frown;": '\U00002322', - "fscr;": '\U0001D4BB', - "gE;": '\U00002267', - "gEl;": '\U00002A8C', - "gacute;": '\U000001F5', - "gamma;": '\U000003B3', - "gammad;": '\U000003DD', - "gap;": '\U00002A86', - "gbreve;": '\U0000011F', - "gcirc;": '\U0000011D', - "gcy;": '\U00000433', - "gdot;": '\U00000121', - "ge;": '\U00002265', - "gel;": '\U000022DB', - "geq;": '\U00002265', - "geqq;": '\U00002267', - "geqslant;": '\U00002A7E', - "ges;": '\U00002A7E', - "gescc;": '\U00002AA9', - "gesdot;": '\U00002A80', - "gesdoto;": '\U00002A82', - "gesdotol;": '\U00002A84', - "gesles;": '\U00002A94', - "gfr;": '\U0001D524', - "gg;": '\U0000226B', - "ggg;": '\U000022D9', - "gimel;": '\U00002137', - "gjcy;": '\U00000453', - "gl;": '\U00002277', - "glE;": '\U00002A92', - "gla;": '\U00002AA5', - "glj;": '\U00002AA4', - "gnE;": '\U00002269', - "gnap;": '\U00002A8A', - "gnapprox;": '\U00002A8A', - "gne;": '\U00002A88', - "gneq;": '\U00002A88', - "gneqq;": '\U00002269', - "gnsim;": '\U000022E7', - "gopf;": '\U0001D558', - "grave;": '\U00000060', - "gscr;": '\U0000210A', - "gsim;": '\U00002273', - "gsime;": '\U00002A8E', - "gsiml;": '\U00002A90', - "gt;": '\U0000003E', - "gtcc;": '\U00002AA7', - "gtcir;": '\U00002A7A', - "gtdot;": '\U000022D7', - "gtlPar;": '\U00002995', - "gtquest;": '\U00002A7C', - "gtrapprox;": '\U00002A86', - "gtrarr;": '\U00002978', - "gtrdot;": '\U000022D7', - "gtreqless;": '\U000022DB', - "gtreqqless;": '\U00002A8C', - "gtrless;": '\U00002277', - "gtrsim;": '\U00002273', - "hArr;": '\U000021D4', - "hairsp;": '\U0000200A', - "half;": '\U000000BD', - "hamilt;": '\U0000210B', - "hardcy;": '\U0000044A', - "harr;": '\U00002194', - "harrcir;": '\U00002948', - "harrw;": '\U000021AD', - "hbar;": '\U0000210F', - "hcirc;": '\U00000125', - "hearts;": '\U00002665', - "heartsuit;": '\U00002665', - "hellip;": '\U00002026', - "hercon;": '\U000022B9', - "hfr;": '\U0001D525', - "hksearow;": '\U00002925', - "hkswarow;": '\U00002926', - "hoarr;": '\U000021FF', - "homtht;": '\U0000223B', - "hookleftarrow;": '\U000021A9', - "hookrightarrow;": '\U000021AA', - "hopf;": '\U0001D559', - "horbar;": '\U00002015', - "hscr;": '\U0001D4BD', - "hslash;": '\U0000210F', - "hstrok;": '\U00000127', - "hybull;": '\U00002043', - "hyphen;": '\U00002010', - "iacute;": '\U000000ED', - "ic;": '\U00002063', - "icirc;": '\U000000EE', - "icy;": '\U00000438', - "iecy;": '\U00000435', - "iexcl;": '\U000000A1', - "iff;": '\U000021D4', - "ifr;": '\U0001D526', - "igrave;": '\U000000EC', - "ii;": '\U00002148', - "iiiint;": '\U00002A0C', - "iiint;": '\U0000222D', - "iinfin;": '\U000029DC', - "iiota;": '\U00002129', - "ijlig;": '\U00000133', - "imacr;": '\U0000012B', - "image;": '\U00002111', - "imagline;": '\U00002110', - "imagpart;": '\U00002111', - "imath;": '\U00000131', - "imof;": '\U000022B7', - "imped;": '\U000001B5', - "in;": '\U00002208', - "incare;": '\U00002105', - "infin;": '\U0000221E', - "infintie;": '\U000029DD', - "inodot;": '\U00000131', - "int;": '\U0000222B', - "intcal;": '\U000022BA', - "integers;": '\U00002124', - "intercal;": '\U000022BA', - "intlarhk;": '\U00002A17', - "intprod;": '\U00002A3C', - "iocy;": '\U00000451', - "iogon;": '\U0000012F', - "iopf;": '\U0001D55A', - "iota;": '\U000003B9', - "iprod;": '\U00002A3C', - "iquest;": '\U000000BF', - "iscr;": '\U0001D4BE', - "isin;": '\U00002208', - "isinE;": '\U000022F9', - "isindot;": '\U000022F5', - "isins;": '\U000022F4', - "isinsv;": '\U000022F3', - "isinv;": '\U00002208', - "it;": '\U00002062', - "itilde;": '\U00000129', - "iukcy;": '\U00000456', - "iuml;": '\U000000EF', - "jcirc;": '\U00000135', - "jcy;": '\U00000439', - "jfr;": '\U0001D527', - "jmath;": '\U00000237', - "jopf;": '\U0001D55B', - "jscr;": '\U0001D4BF', - "jsercy;": '\U00000458', - "jukcy;": '\U00000454', - "kappa;": '\U000003BA', - "kappav;": '\U000003F0', - "kcedil;": '\U00000137', - "kcy;": '\U0000043A', - "kfr;": '\U0001D528', - "kgreen;": '\U00000138', - "khcy;": '\U00000445', - "kjcy;": '\U0000045C', - "kopf;": '\U0001D55C', - "kscr;": '\U0001D4C0', - "lAarr;": '\U000021DA', - "lArr;": '\U000021D0', - "lAtail;": '\U0000291B', - "lBarr;": '\U0000290E', - "lE;": '\U00002266', - "lEg;": '\U00002A8B', - "lHar;": '\U00002962', - "lacute;": '\U0000013A', - "laemptyv;": '\U000029B4', - "lagran;": '\U00002112', - "lambda;": '\U000003BB', - "lang;": '\U000027E8', - "langd;": '\U00002991', - "langle;": '\U000027E8', - "lap;": '\U00002A85', - "laquo;": '\U000000AB', - "larr;": '\U00002190', - "larrb;": '\U000021E4', - "larrbfs;": '\U0000291F', - "larrfs;": '\U0000291D', - "larrhk;": '\U000021A9', - "larrlp;": '\U000021AB', - "larrpl;": '\U00002939', - "larrsim;": '\U00002973', - "larrtl;": '\U000021A2', - "lat;": '\U00002AAB', - "latail;": '\U00002919', - "late;": '\U00002AAD', - "lbarr;": '\U0000290C', - "lbbrk;": '\U00002772', - "lbrace;": '\U0000007B', - "lbrack;": '\U0000005B', - "lbrke;": '\U0000298B', - "lbrksld;": '\U0000298F', - "lbrkslu;": '\U0000298D', - "lcaron;": '\U0000013E', - "lcedil;": '\U0000013C', - "lceil;": '\U00002308', - "lcub;": '\U0000007B', - "lcy;": '\U0000043B', - "ldca;": '\U00002936', - "ldquo;": '\U0000201C', - "ldquor;": '\U0000201E', - "ldrdhar;": '\U00002967', - "ldrushar;": '\U0000294B', - "ldsh;": '\U000021B2', - "le;": '\U00002264', - "leftarrow;": '\U00002190', - "leftarrowtail;": '\U000021A2', - "leftharpoondown;": '\U000021BD', - "leftharpoonup;": '\U000021BC', - "leftleftarrows;": '\U000021C7', - "leftrightarrow;": '\U00002194', - "leftrightarrows;": '\U000021C6', - "leftrightharpoons;": '\U000021CB', - "leftrightsquigarrow;": '\U000021AD', - "leftthreetimes;": '\U000022CB', - "leg;": '\U000022DA', - "leq;": '\U00002264', - "leqq;": '\U00002266', - "leqslant;": '\U00002A7D', - "les;": '\U00002A7D', - "lescc;": '\U00002AA8', - "lesdot;": '\U00002A7F', - "lesdoto;": '\U00002A81', - "lesdotor;": '\U00002A83', - "lesges;": '\U00002A93', - "lessapprox;": '\U00002A85', - "lessdot;": '\U000022D6', - "lesseqgtr;": '\U000022DA', - "lesseqqgtr;": '\U00002A8B', - "lessgtr;": '\U00002276', - "lesssim;": '\U00002272', - "lfisht;": '\U0000297C', - "lfloor;": '\U0000230A', - "lfr;": '\U0001D529', - "lg;": '\U00002276', - "lgE;": '\U00002A91', - "lhard;": '\U000021BD', - "lharu;": '\U000021BC', - "lharul;": '\U0000296A', - "lhblk;": '\U00002584', - "ljcy;": '\U00000459', - "ll;": '\U0000226A', - "llarr;": '\U000021C7', - "llcorner;": '\U0000231E', - "llhard;": '\U0000296B', - "lltri;": '\U000025FA', - "lmidot;": '\U00000140', - "lmoust;": '\U000023B0', - "lmoustache;": '\U000023B0', - "lnE;": '\U00002268', - "lnap;": '\U00002A89', - "lnapprox;": '\U00002A89', - "lne;": '\U00002A87', - "lneq;": '\U00002A87', - "lneqq;": '\U00002268', - "lnsim;": '\U000022E6', - "loang;": '\U000027EC', - "loarr;": '\U000021FD', - "lobrk;": '\U000027E6', - "longleftarrow;": '\U000027F5', - "longleftrightarrow;": '\U000027F7', - "longmapsto;": '\U000027FC', - "longrightarrow;": '\U000027F6', - "looparrowleft;": '\U000021AB', - "looparrowright;": '\U000021AC', - "lopar;": '\U00002985', - "lopf;": '\U0001D55D', - "loplus;": '\U00002A2D', - "lotimes;": '\U00002A34', - "lowast;": '\U00002217', - "lowbar;": '\U0000005F', - "loz;": '\U000025CA', - "lozenge;": '\U000025CA', - "lozf;": '\U000029EB', - "lpar;": '\U00000028', - "lparlt;": '\U00002993', - "lrarr;": '\U000021C6', - "lrcorner;": '\U0000231F', - "lrhar;": '\U000021CB', - "lrhard;": '\U0000296D', - "lrm;": '\U0000200E', - "lrtri;": '\U000022BF', - "lsaquo;": '\U00002039', - "lscr;": '\U0001D4C1', - "lsh;": '\U000021B0', - "lsim;": '\U00002272', - "lsime;": '\U00002A8D', - "lsimg;": '\U00002A8F', - "lsqb;": '\U0000005B', - "lsquo;": '\U00002018', - "lsquor;": '\U0000201A', - "lstrok;": '\U00000142', - "lt;": '\U0000003C', - "ltcc;": '\U00002AA6', - "ltcir;": '\U00002A79', - "ltdot;": '\U000022D6', - "lthree;": '\U000022CB', - "ltimes;": '\U000022C9', - "ltlarr;": '\U00002976', - "ltquest;": '\U00002A7B', - "ltrPar;": '\U00002996', - "ltri;": '\U000025C3', - "ltrie;": '\U000022B4', - "ltrif;": '\U000025C2', - "lurdshar;": '\U0000294A', - "luruhar;": '\U00002966', - "mDDot;": '\U0000223A', - "macr;": '\U000000AF', - "male;": '\U00002642', - "malt;": '\U00002720', - "maltese;": '\U00002720', - "map;": '\U000021A6', - "mapsto;": '\U000021A6', - "mapstodown;": '\U000021A7', - "mapstoleft;": '\U000021A4', - "mapstoup;": '\U000021A5', - "marker;": '\U000025AE', - "mcomma;": '\U00002A29', - "mcy;": '\U0000043C', - "mdash;": '\U00002014', - "measuredangle;": '\U00002221', - "mfr;": '\U0001D52A', - "mho;": '\U00002127', - "micro;": '\U000000B5', - "mid;": '\U00002223', - "midast;": '\U0000002A', - "midcir;": '\U00002AF0', - "middot;": '\U000000B7', - "minus;": '\U00002212', - "minusb;": '\U0000229F', - "minusd;": '\U00002238', - "minusdu;": '\U00002A2A', - "mlcp;": '\U00002ADB', - "mldr;": '\U00002026', - "mnplus;": '\U00002213', - "models;": '\U000022A7', - "mopf;": '\U0001D55E', - "mp;": '\U00002213', - "mscr;": '\U0001D4C2', - "mstpos;": '\U0000223E', - "mu;": '\U000003BC', - "multimap;": '\U000022B8', - "mumap;": '\U000022B8', - "nLeftarrow;": '\U000021CD', - "nLeftrightarrow;": '\U000021CE', - "nRightarrow;": '\U000021CF', - "nVDash;": '\U000022AF', - "nVdash;": '\U000022AE', - "nabla;": '\U00002207', - "nacute;": '\U00000144', - "nap;": '\U00002249', - "napos;": '\U00000149', - "napprox;": '\U00002249', - "natur;": '\U0000266E', - "natural;": '\U0000266E', - "naturals;": '\U00002115', - "nbsp;": '\U000000A0', - "ncap;": '\U00002A43', - "ncaron;": '\U00000148', - "ncedil;": '\U00000146', - "ncong;": '\U00002247', - "ncup;": '\U00002A42', - "ncy;": '\U0000043D', - "ndash;": '\U00002013', - "ne;": '\U00002260', - "neArr;": '\U000021D7', - "nearhk;": '\U00002924', - "nearr;": '\U00002197', - "nearrow;": '\U00002197', - "nequiv;": '\U00002262', - "nesear;": '\U00002928', - "nexist;": '\U00002204', - "nexists;": '\U00002204', - "nfr;": '\U0001D52B', - "nge;": '\U00002271', - "ngeq;": '\U00002271', - "ngsim;": '\U00002275', - "ngt;": '\U0000226F', - "ngtr;": '\U0000226F', - "nhArr;": '\U000021CE', - "nharr;": '\U000021AE', - "nhpar;": '\U00002AF2', - "ni;": '\U0000220B', - "nis;": '\U000022FC', - "nisd;": '\U000022FA', - "niv;": '\U0000220B', - "njcy;": '\U0000045A', - "nlArr;": '\U000021CD', - "nlarr;": '\U0000219A', - "nldr;": '\U00002025', - "nle;": '\U00002270', - "nleftarrow;": '\U0000219A', - "nleftrightarrow;": '\U000021AE', - "nleq;": '\U00002270', - "nless;": '\U0000226E', - "nlsim;": '\U00002274', - "nlt;": '\U0000226E', - "nltri;": '\U000022EA', - "nltrie;": '\U000022EC', - "nmid;": '\U00002224', - "nopf;": '\U0001D55F', - "not;": '\U000000AC', - "notin;": '\U00002209', - "notinva;": '\U00002209', - "notinvb;": '\U000022F7', - "notinvc;": '\U000022F6', - "notni;": '\U0000220C', - "notniva;": '\U0000220C', - "notnivb;": '\U000022FE', - "notnivc;": '\U000022FD', - "npar;": '\U00002226', - "nparallel;": '\U00002226', - "npolint;": '\U00002A14', - "npr;": '\U00002280', - "nprcue;": '\U000022E0', - "nprec;": '\U00002280', - "nrArr;": '\U000021CF', - "nrarr;": '\U0000219B', - "nrightarrow;": '\U0000219B', - "nrtri;": '\U000022EB', - "nrtrie;": '\U000022ED', - "nsc;": '\U00002281', - "nsccue;": '\U000022E1', - "nscr;": '\U0001D4C3', - "nshortmid;": '\U00002224', - "nshortparallel;": '\U00002226', - "nsim;": '\U00002241', - "nsime;": '\U00002244', - "nsimeq;": '\U00002244', - "nsmid;": '\U00002224', - "nspar;": '\U00002226', - "nsqsube;": '\U000022E2', - "nsqsupe;": '\U000022E3', - "nsub;": '\U00002284', - "nsube;": '\U00002288', - "nsubseteq;": '\U00002288', - "nsucc;": '\U00002281', - "nsup;": '\U00002285', - "nsupe;": '\U00002289', - "nsupseteq;": '\U00002289', - "ntgl;": '\U00002279', - "ntilde;": '\U000000F1', - "ntlg;": '\U00002278', - "ntriangleleft;": '\U000022EA', - "ntrianglelefteq;": '\U000022EC', - "ntriangleright;": '\U000022EB', - "ntrianglerighteq;": '\U000022ED', - "nu;": '\U000003BD', - "num;": '\U00000023', - "numero;": '\U00002116', - "numsp;": '\U00002007', - "nvDash;": '\U000022AD', - "nvHarr;": '\U00002904', - "nvdash;": '\U000022AC', - "nvinfin;": '\U000029DE', - "nvlArr;": '\U00002902', - "nvrArr;": '\U00002903', - "nwArr;": '\U000021D6', - "nwarhk;": '\U00002923', - "nwarr;": '\U00002196', - "nwarrow;": '\U00002196', - "nwnear;": '\U00002927', - "oS;": '\U000024C8', - "oacute;": '\U000000F3', - "oast;": '\U0000229B', - "ocir;": '\U0000229A', - "ocirc;": '\U000000F4', - "ocy;": '\U0000043E', - "odash;": '\U0000229D', - "odblac;": '\U00000151', - "odiv;": '\U00002A38', - "odot;": '\U00002299', - "odsold;": '\U000029BC', - "oelig;": '\U00000153', - "ofcir;": '\U000029BF', - "ofr;": '\U0001D52C', - "ogon;": '\U000002DB', - "ograve;": '\U000000F2', - "ogt;": '\U000029C1', - "ohbar;": '\U000029B5', - "ohm;": '\U000003A9', - "oint;": '\U0000222E', - "olarr;": '\U000021BA', - "olcir;": '\U000029BE', - "olcross;": '\U000029BB', - "oline;": '\U0000203E', - "olt;": '\U000029C0', - "omacr;": '\U0000014D', - "omega;": '\U000003C9', - "omicron;": '\U000003BF', - "omid;": '\U000029B6', - "ominus;": '\U00002296', - "oopf;": '\U0001D560', - "opar;": '\U000029B7', - "operp;": '\U000029B9', - "oplus;": '\U00002295', - "or;": '\U00002228', - "orarr;": '\U000021BB', - "ord;": '\U00002A5D', - "order;": '\U00002134', - "orderof;": '\U00002134', - "ordf;": '\U000000AA', - "ordm;": '\U000000BA', - "origof;": '\U000022B6', - "oror;": '\U00002A56', - "orslope;": '\U00002A57', - "orv;": '\U00002A5B', - "oscr;": '\U00002134', - "oslash;": '\U000000F8', - "osol;": '\U00002298', - "otilde;": '\U000000F5', - "otimes;": '\U00002297', - "otimesas;": '\U00002A36', - "ouml;": '\U000000F6', - "ovbar;": '\U0000233D', - "par;": '\U00002225', - "para;": '\U000000B6', - "parallel;": '\U00002225', - "parsim;": '\U00002AF3', - "parsl;": '\U00002AFD', - "part;": '\U00002202', - "pcy;": '\U0000043F', - "percnt;": '\U00000025', - "period;": '\U0000002E', - "permil;": '\U00002030', - "perp;": '\U000022A5', - "pertenk;": '\U00002031', - "pfr;": '\U0001D52D', - "phi;": '\U000003C6', - "phiv;": '\U000003D5', - "phmmat;": '\U00002133', - "phone;": '\U0000260E', - "pi;": '\U000003C0', - "pitchfork;": '\U000022D4', - "piv;": '\U000003D6', - "planck;": '\U0000210F', - "planckh;": '\U0000210E', - "plankv;": '\U0000210F', - "plus;": '\U0000002B', - "plusacir;": '\U00002A23', - "plusb;": '\U0000229E', - "pluscir;": '\U00002A22', - "plusdo;": '\U00002214', - "plusdu;": '\U00002A25', - "pluse;": '\U00002A72', - "plusmn;": '\U000000B1', - "plussim;": '\U00002A26', - "plustwo;": '\U00002A27', - "pm;": '\U000000B1', - "pointint;": '\U00002A15', - "popf;": '\U0001D561', - "pound;": '\U000000A3', - "pr;": '\U0000227A', - "prE;": '\U00002AB3', - "prap;": '\U00002AB7', - "prcue;": '\U0000227C', - "pre;": '\U00002AAF', - "prec;": '\U0000227A', - "precapprox;": '\U00002AB7', - "preccurlyeq;": '\U0000227C', - "preceq;": '\U00002AAF', - "precnapprox;": '\U00002AB9', - "precneqq;": '\U00002AB5', - "precnsim;": '\U000022E8', - "precsim;": '\U0000227E', - "prime;": '\U00002032', - "primes;": '\U00002119', - "prnE;": '\U00002AB5', - "prnap;": '\U00002AB9', - "prnsim;": '\U000022E8', - "prod;": '\U0000220F', - "profalar;": '\U0000232E', - "profline;": '\U00002312', - "profsurf;": '\U00002313', - "prop;": '\U0000221D', - "propto;": '\U0000221D', - "prsim;": '\U0000227E', - "prurel;": '\U000022B0', - "pscr;": '\U0001D4C5', - "psi;": '\U000003C8', - "puncsp;": '\U00002008', - "qfr;": '\U0001D52E', - "qint;": '\U00002A0C', - "qopf;": '\U0001D562', - "qprime;": '\U00002057', - "qscr;": '\U0001D4C6', - "quaternions;": '\U0000210D', - "quatint;": '\U00002A16', - "quest;": '\U0000003F', - "questeq;": '\U0000225F', - "quot;": '\U00000022', - "rAarr;": '\U000021DB', - "rArr;": '\U000021D2', - "rAtail;": '\U0000291C', - "rBarr;": '\U0000290F', - "rHar;": '\U00002964', - "racute;": '\U00000155', - "radic;": '\U0000221A', - "raemptyv;": '\U000029B3', - "rang;": '\U000027E9', - "rangd;": '\U00002992', - "range;": '\U000029A5', - "rangle;": '\U000027E9', - "raquo;": '\U000000BB', - "rarr;": '\U00002192', - "rarrap;": '\U00002975', - "rarrb;": '\U000021E5', - "rarrbfs;": '\U00002920', - "rarrc;": '\U00002933', - "rarrfs;": '\U0000291E', - "rarrhk;": '\U000021AA', - "rarrlp;": '\U000021AC', - "rarrpl;": '\U00002945', - "rarrsim;": '\U00002974', - "rarrtl;": '\U000021A3', - "rarrw;": '\U0000219D', - "ratail;": '\U0000291A', - "ratio;": '\U00002236', - "rationals;": '\U0000211A', - "rbarr;": '\U0000290D', - "rbbrk;": '\U00002773', - "rbrace;": '\U0000007D', - "rbrack;": '\U0000005D', - "rbrke;": '\U0000298C', - "rbrksld;": '\U0000298E', - "rbrkslu;": '\U00002990', - "rcaron;": '\U00000159', - "rcedil;": '\U00000157', - "rceil;": '\U00002309', - "rcub;": '\U0000007D', - "rcy;": '\U00000440', - "rdca;": '\U00002937', - "rdldhar;": '\U00002969', - "rdquo;": '\U0000201D', - "rdquor;": '\U0000201D', - "rdsh;": '\U000021B3', - "real;": '\U0000211C', - "realine;": '\U0000211B', - "realpart;": '\U0000211C', - "reals;": '\U0000211D', - "rect;": '\U000025AD', - "reg;": '\U000000AE', - "rfisht;": '\U0000297D', - "rfloor;": '\U0000230B', - "rfr;": '\U0001D52F', - "rhard;": '\U000021C1', - "rharu;": '\U000021C0', - "rharul;": '\U0000296C', - "rho;": '\U000003C1', - "rhov;": '\U000003F1', - "rightarrow;": '\U00002192', - "rightarrowtail;": '\U000021A3', - "rightharpoondown;": '\U000021C1', - "rightharpoonup;": '\U000021C0', - "rightleftarrows;": '\U000021C4', - "rightleftharpoons;": '\U000021CC', - "rightrightarrows;": '\U000021C9', - "rightsquigarrow;": '\U0000219D', - "rightthreetimes;": '\U000022CC', - "ring;": '\U000002DA', - "risingdotseq;": '\U00002253', - "rlarr;": '\U000021C4', - "rlhar;": '\U000021CC', - "rlm;": '\U0000200F', - "rmoust;": '\U000023B1', - "rmoustache;": '\U000023B1', - "rnmid;": '\U00002AEE', - "roang;": '\U000027ED', - "roarr;": '\U000021FE', - "robrk;": '\U000027E7', - "ropar;": '\U00002986', - "ropf;": '\U0001D563', - "roplus;": '\U00002A2E', - "rotimes;": '\U00002A35', - "rpar;": '\U00000029', - "rpargt;": '\U00002994', - "rppolint;": '\U00002A12', - "rrarr;": '\U000021C9', - "rsaquo;": '\U0000203A', - "rscr;": '\U0001D4C7', - "rsh;": '\U000021B1', - "rsqb;": '\U0000005D', - "rsquo;": '\U00002019', - "rsquor;": '\U00002019', - "rthree;": '\U000022CC', - "rtimes;": '\U000022CA', - "rtri;": '\U000025B9', - "rtrie;": '\U000022B5', - "rtrif;": '\U000025B8', - "rtriltri;": '\U000029CE', - "ruluhar;": '\U00002968', - "rx;": '\U0000211E', - "sacute;": '\U0000015B', - "sbquo;": '\U0000201A', - "sc;": '\U0000227B', - "scE;": '\U00002AB4', - "scap;": '\U00002AB8', - "scaron;": '\U00000161', - "sccue;": '\U0000227D', - "sce;": '\U00002AB0', - "scedil;": '\U0000015F', - "scirc;": '\U0000015D', - "scnE;": '\U00002AB6', - "scnap;": '\U00002ABA', - "scnsim;": '\U000022E9', - "scpolint;": '\U00002A13', - "scsim;": '\U0000227F', - "scy;": '\U00000441', - "sdot;": '\U000022C5', - "sdotb;": '\U000022A1', - "sdote;": '\U00002A66', - "seArr;": '\U000021D8', - "searhk;": '\U00002925', - "searr;": '\U00002198', - "searrow;": '\U00002198', - "sect;": '\U000000A7', - "semi;": '\U0000003B', - "seswar;": '\U00002929', - "setminus;": '\U00002216', - "setmn;": '\U00002216', - "sext;": '\U00002736', - "sfr;": '\U0001D530', - "sfrown;": '\U00002322', - "sharp;": '\U0000266F', - "shchcy;": '\U00000449', - "shcy;": '\U00000448', - "shortmid;": '\U00002223', - "shortparallel;": '\U00002225', - "shy;": '\U000000AD', - "sigma;": '\U000003C3', - "sigmaf;": '\U000003C2', - "sigmav;": '\U000003C2', - "sim;": '\U0000223C', - "simdot;": '\U00002A6A', - "sime;": '\U00002243', - "simeq;": '\U00002243', - "simg;": '\U00002A9E', - "simgE;": '\U00002AA0', - "siml;": '\U00002A9D', - "simlE;": '\U00002A9F', - "simne;": '\U00002246', - "simplus;": '\U00002A24', - "simrarr;": '\U00002972', - "slarr;": '\U00002190', - "smallsetminus;": '\U00002216', - "smashp;": '\U00002A33', - "smeparsl;": '\U000029E4', - "smid;": '\U00002223', - "smile;": '\U00002323', - "smt;": '\U00002AAA', - "smte;": '\U00002AAC', - "softcy;": '\U0000044C', - "sol;": '\U0000002F', - "solb;": '\U000029C4', - "solbar;": '\U0000233F', - "sopf;": '\U0001D564', - "spades;": '\U00002660', - "spadesuit;": '\U00002660', - "spar;": '\U00002225', - "sqcap;": '\U00002293', - "sqcup;": '\U00002294', - "sqsub;": '\U0000228F', - "sqsube;": '\U00002291', - "sqsubset;": '\U0000228F', - "sqsubseteq;": '\U00002291', - "sqsup;": '\U00002290', - "sqsupe;": '\U00002292', - "sqsupset;": '\U00002290', - "sqsupseteq;": '\U00002292', - "squ;": '\U000025A1', - "square;": '\U000025A1', - "squarf;": '\U000025AA', - "squf;": '\U000025AA', - "srarr;": '\U00002192', - "sscr;": '\U0001D4C8', - "ssetmn;": '\U00002216', - "ssmile;": '\U00002323', - "sstarf;": '\U000022C6', - "star;": '\U00002606', - "starf;": '\U00002605', - "straightepsilon;": '\U000003F5', - "straightphi;": '\U000003D5', - "strns;": '\U000000AF', - "sub;": '\U00002282', - "subE;": '\U00002AC5', - "subdot;": '\U00002ABD', - "sube;": '\U00002286', - "subedot;": '\U00002AC3', - "submult;": '\U00002AC1', - "subnE;": '\U00002ACB', - "subne;": '\U0000228A', - "subplus;": '\U00002ABF', - "subrarr;": '\U00002979', - "subset;": '\U00002282', - "subseteq;": '\U00002286', - "subseteqq;": '\U00002AC5', - "subsetneq;": '\U0000228A', - "subsetneqq;": '\U00002ACB', - "subsim;": '\U00002AC7', - "subsub;": '\U00002AD5', - "subsup;": '\U00002AD3', - "succ;": '\U0000227B', - "succapprox;": '\U00002AB8', - "succcurlyeq;": '\U0000227D', - "succeq;": '\U00002AB0', - "succnapprox;": '\U00002ABA', - "succneqq;": '\U00002AB6', - "succnsim;": '\U000022E9', - "succsim;": '\U0000227F', - "sum;": '\U00002211', - "sung;": '\U0000266A', - "sup;": '\U00002283', - "sup1;": '\U000000B9', - "sup2;": '\U000000B2', - "sup3;": '\U000000B3', - "supE;": '\U00002AC6', - "supdot;": '\U00002ABE', - "supdsub;": '\U00002AD8', - "supe;": '\U00002287', - "supedot;": '\U00002AC4', - "suphsol;": '\U000027C9', - "suphsub;": '\U00002AD7', - "suplarr;": '\U0000297B', - "supmult;": '\U00002AC2', - "supnE;": '\U00002ACC', - "supne;": '\U0000228B', - "supplus;": '\U00002AC0', - "supset;": '\U00002283', - "supseteq;": '\U00002287', - "supseteqq;": '\U00002AC6', - "supsetneq;": '\U0000228B', - "supsetneqq;": '\U00002ACC', - "supsim;": '\U00002AC8', - "supsub;": '\U00002AD4', - "supsup;": '\U00002AD6', - "swArr;": '\U000021D9', - "swarhk;": '\U00002926', - "swarr;": '\U00002199', - "swarrow;": '\U00002199', - "swnwar;": '\U0000292A', - "szlig;": '\U000000DF', - "target;": '\U00002316', - "tau;": '\U000003C4', - "tbrk;": '\U000023B4', - "tcaron;": '\U00000165', - "tcedil;": '\U00000163', - "tcy;": '\U00000442', - "tdot;": '\U000020DB', - "telrec;": '\U00002315', - "tfr;": '\U0001D531', - "there4;": '\U00002234', - "therefore;": '\U00002234', - "theta;": '\U000003B8', - "thetasym;": '\U000003D1', - "thetav;": '\U000003D1', - "thickapprox;": '\U00002248', - "thicksim;": '\U0000223C', - "thinsp;": '\U00002009', - "thkap;": '\U00002248', - "thksim;": '\U0000223C', - "thorn;": '\U000000FE', - "tilde;": '\U000002DC', - "times;": '\U000000D7', - "timesb;": '\U000022A0', - "timesbar;": '\U00002A31', - "timesd;": '\U00002A30', - "tint;": '\U0000222D', - "toea;": '\U00002928', - "top;": '\U000022A4', - "topbot;": '\U00002336', - "topcir;": '\U00002AF1', - "topf;": '\U0001D565', - "topfork;": '\U00002ADA', - "tosa;": '\U00002929', - "tprime;": '\U00002034', - "trade;": '\U00002122', - "triangle;": '\U000025B5', - "triangledown;": '\U000025BF', - "triangleleft;": '\U000025C3', - "trianglelefteq;": '\U000022B4', - "triangleq;": '\U0000225C', - "triangleright;": '\U000025B9', - "trianglerighteq;": '\U000022B5', - "tridot;": '\U000025EC', - "trie;": '\U0000225C', - "triminus;": '\U00002A3A', - "triplus;": '\U00002A39', - "trisb;": '\U000029CD', - "tritime;": '\U00002A3B', - "trpezium;": '\U000023E2', - "tscr;": '\U0001D4C9', - "tscy;": '\U00000446', - "tshcy;": '\U0000045B', - "tstrok;": '\U00000167', - "twixt;": '\U0000226C', - "twoheadleftarrow;": '\U0000219E', - "twoheadrightarrow;": '\U000021A0', - "uArr;": '\U000021D1', - "uHar;": '\U00002963', - "uacute;": '\U000000FA', - "uarr;": '\U00002191', - "ubrcy;": '\U0000045E', - "ubreve;": '\U0000016D', - "ucirc;": '\U000000FB', - "ucy;": '\U00000443', - "udarr;": '\U000021C5', - "udblac;": '\U00000171', - "udhar;": '\U0000296E', - "ufisht;": '\U0000297E', - "ufr;": '\U0001D532', - "ugrave;": '\U000000F9', - "uharl;": '\U000021BF', - "uharr;": '\U000021BE', - "uhblk;": '\U00002580', - "ulcorn;": '\U0000231C', - "ulcorner;": '\U0000231C', - "ulcrop;": '\U0000230F', - "ultri;": '\U000025F8', - "umacr;": '\U0000016B', - "uml;": '\U000000A8', - "uogon;": '\U00000173', - "uopf;": '\U0001D566', - "uparrow;": '\U00002191', - "updownarrow;": '\U00002195', - "upharpoonleft;": '\U000021BF', - "upharpoonright;": '\U000021BE', - "uplus;": '\U0000228E', - "upsi;": '\U000003C5', - "upsih;": '\U000003D2', - "upsilon;": '\U000003C5', - "upuparrows;": '\U000021C8', - "urcorn;": '\U0000231D', - "urcorner;": '\U0000231D', - "urcrop;": '\U0000230E', - "uring;": '\U0000016F', - "urtri;": '\U000025F9', - "uscr;": '\U0001D4CA', - "utdot;": '\U000022F0', - "utilde;": '\U00000169', - "utri;": '\U000025B5', - "utrif;": '\U000025B4', - "uuarr;": '\U000021C8', - "uuml;": '\U000000FC', - "uwangle;": '\U000029A7', - "vArr;": '\U000021D5', - "vBar;": '\U00002AE8', - "vBarv;": '\U00002AE9', - "vDash;": '\U000022A8', - "vangrt;": '\U0000299C', - "varepsilon;": '\U000003F5', - "varkappa;": '\U000003F0', - "varnothing;": '\U00002205', - "varphi;": '\U000003D5', - "varpi;": '\U000003D6', - "varpropto;": '\U0000221D', - "varr;": '\U00002195', - "varrho;": '\U000003F1', - "varsigma;": '\U000003C2', - "vartheta;": '\U000003D1', - "vartriangleleft;": '\U000022B2', - "vartriangleright;": '\U000022B3', - "vcy;": '\U00000432', - "vdash;": '\U000022A2', - "vee;": '\U00002228', - "veebar;": '\U000022BB', - "veeeq;": '\U0000225A', - "vellip;": '\U000022EE', - "verbar;": '\U0000007C', - "vert;": '\U0000007C', - "vfr;": '\U0001D533', - "vltri;": '\U000022B2', - "vopf;": '\U0001D567', - "vprop;": '\U0000221D', - "vrtri;": '\U000022B3', - "vscr;": '\U0001D4CB', - "vzigzag;": '\U0000299A', - "wcirc;": '\U00000175', - "wedbar;": '\U00002A5F', - "wedge;": '\U00002227', - "wedgeq;": '\U00002259', - "weierp;": '\U00002118', - "wfr;": '\U0001D534', - "wopf;": '\U0001D568', - "wp;": '\U00002118', - "wr;": '\U00002240', - "wreath;": '\U00002240', - "wscr;": '\U0001D4CC', - "xcap;": '\U000022C2', - "xcirc;": '\U000025EF', - "xcup;": '\U000022C3', - "xdtri;": '\U000025BD', - "xfr;": '\U0001D535', - "xhArr;": '\U000027FA', - "xharr;": '\U000027F7', - "xi;": '\U000003BE', - "xlArr;": '\U000027F8', - "xlarr;": '\U000027F5', - "xmap;": '\U000027FC', - "xnis;": '\U000022FB', - "xodot;": '\U00002A00', - "xopf;": '\U0001D569', - "xoplus;": '\U00002A01', - "xotime;": '\U00002A02', - "xrArr;": '\U000027F9', - "xrarr;": '\U000027F6', - "xscr;": '\U0001D4CD', - "xsqcup;": '\U00002A06', - "xuplus;": '\U00002A04', - "xutri;": '\U000025B3', - "xvee;": '\U000022C1', - "xwedge;": '\U000022C0', - "yacute;": '\U000000FD', - "yacy;": '\U0000044F', - "ycirc;": '\U00000177', - "ycy;": '\U0000044B', - "yen;": '\U000000A5', - "yfr;": '\U0001D536', - "yicy;": '\U00000457', - "yopf;": '\U0001D56A', - "yscr;": '\U0001D4CE', - "yucy;": '\U0000044E', - "yuml;": '\U000000FF', - "zacute;": '\U0000017A', - "zcaron;": '\U0000017E', - "zcy;": '\U00000437', - "zdot;": '\U0000017C', - "zeetrf;": '\U00002128', - "zeta;": '\U000003B6', - "zfr;": '\U0001D537', - "zhcy;": '\U00000436', - "zigrarr;": '\U000021DD', - "zopf;": '\U0001D56B', - "zscr;": '\U0001D4CF', - "zwj;": '\U0000200D', - "zwnj;": '\U0000200C', - "AElig": '\U000000C6', - "AMP": '\U00000026', - "Aacute": '\U000000C1', - "Acirc": '\U000000C2', - "Agrave": '\U000000C0', - "Aring": '\U000000C5', - "Atilde": '\U000000C3', - "Auml": '\U000000C4', - "COPY": '\U000000A9', - "Ccedil": '\U000000C7', - "ETH": '\U000000D0', - "Eacute": '\U000000C9', - "Ecirc": '\U000000CA', - "Egrave": '\U000000C8', - "Euml": '\U000000CB', - "GT": '\U0000003E', - "Iacute": '\U000000CD', - "Icirc": '\U000000CE', - "Igrave": '\U000000CC', - "Iuml": '\U000000CF', - "LT": '\U0000003C', - "Ntilde": '\U000000D1', - "Oacute": '\U000000D3', - "Ocirc": '\U000000D4', - "Ograve": '\U000000D2', - "Oslash": '\U000000D8', - "Otilde": '\U000000D5', - "Ouml": '\U000000D6', - "QUOT": '\U00000022', - "REG": '\U000000AE', - "THORN": '\U000000DE', - "Uacute": '\U000000DA', - "Ucirc": '\U000000DB', - "Ugrave": '\U000000D9', - "Uuml": '\U000000DC', - "Yacute": '\U000000DD', - "aacute": '\U000000E1', - "acirc": '\U000000E2', - "acute": '\U000000B4', - "aelig": '\U000000E6', - "agrave": '\U000000E0', - "amp": '\U00000026', - "aring": '\U000000E5', - "atilde": '\U000000E3', - "auml": '\U000000E4', - "brvbar": '\U000000A6', - "ccedil": '\U000000E7', - "cedil": '\U000000B8', - "cent": '\U000000A2', - "copy": '\U000000A9', - "curren": '\U000000A4', - "deg": '\U000000B0', - "divide": '\U000000F7', - "eacute": '\U000000E9', - "ecirc": '\U000000EA', - "egrave": '\U000000E8', - "eth": '\U000000F0', - "euml": '\U000000EB', - "frac12": '\U000000BD', - "frac14": '\U000000BC', - "frac34": '\U000000BE', - "gt": '\U0000003E', - "iacute": '\U000000ED', - "icirc": '\U000000EE', - "iexcl": '\U000000A1', - "igrave": '\U000000EC', - "iquest": '\U000000BF', - "iuml": '\U000000EF', - "laquo": '\U000000AB', - "lt": '\U0000003C', - "macr": '\U000000AF', - "micro": '\U000000B5', - "middot": '\U000000B7', - "nbsp": '\U000000A0', - "not": '\U000000AC', - "ntilde": '\U000000F1', - "oacute": '\U000000F3', - "ocirc": '\U000000F4', - "ograve": '\U000000F2', - "ordf": '\U000000AA', - "ordm": '\U000000BA', - "oslash": '\U000000F8', - "otilde": '\U000000F5', - "ouml": '\U000000F6', - "para": '\U000000B6', - "plusmn": '\U000000B1', - "pound": '\U000000A3', - "quot": '\U00000022', - "raquo": '\U000000BB', - "reg": '\U000000AE', - "sect": '\U000000A7', - "shy": '\U000000AD', - "sup1": '\U000000B9', - "sup2": '\U000000B2', - "sup3": '\U000000B3', - "szlig": '\U000000DF', - "thorn": '\U000000FE', - "times": '\U000000D7', - "uacute": '\U000000FA', - "ucirc": '\U000000FB', - "ugrave": '\U000000F9', - "uml": '\U000000A8', - "uuml": '\U000000FC', - "yacute": '\U000000FD', - "yen": '\U000000A5', - "yuml": '\U000000FF', + "Cross;": '\U00002A2F', + "Cscr;": '\U0001D49E', + "Cup;": '\U000022D3', + "CupCap;": '\U0000224D', + "DD;": '\U00002145', + "DDotrahd;": '\U00002911', + "DJcy;": '\U00000402', + "DScy;": '\U00000405', + "DZcy;": '\U0000040F', + "Dagger;": '\U00002021', + "Darr;": '\U000021A1', + "Dashv;": '\U00002AE4', + "Dcaron;": '\U0000010E', + "Dcy;": '\U00000414', + "Del;": '\U00002207', + "Delta;": '\U00000394', + "Dfr;": '\U0001D507', + "DiacriticalAcute;": '\U000000B4', + "DiacriticalDot;": '\U000002D9', + "DiacriticalDoubleAcute;": '\U000002DD', + "DiacriticalGrave;": '\U00000060', + "DiacriticalTilde;": '\U000002DC', + "Diamond;": '\U000022C4', + "DifferentialD;": '\U00002146', + "Dopf;": '\U0001D53B', + "Dot;": '\U000000A8', + "DotDot;": '\U000020DC', + "DotEqual;": '\U00002250', + "DoubleContourIntegral;": '\U0000222F', + "DoubleDot;": '\U000000A8', + "DoubleDownArrow;": '\U000021D3', + "DoubleLeftArrow;": '\U000021D0', + "DoubleLeftRightArrow;": '\U000021D4', + "DoubleLeftTee;": '\U00002AE4', + "DoubleLongLeftArrow;": '\U000027F8', + "DoubleLongLeftRightArrow;": '\U000027FA', + "DoubleLongRightArrow;": '\U000027F9', + "DoubleRightArrow;": '\U000021D2', + "DoubleRightTee;": '\U000022A8', + "DoubleUpArrow;": '\U000021D1', + "DoubleUpDownArrow;": '\U000021D5', + "DoubleVerticalBar;": '\U00002225', + "DownArrow;": '\U00002193', + "DownArrowBar;": '\U00002913', + "DownArrowUpArrow;": '\U000021F5', + "DownBreve;": '\U00000311', + "DownLeftRightVector;": '\U00002950', + "DownLeftTeeVector;": '\U0000295E', + "DownLeftVector;": '\U000021BD', + "DownLeftVectorBar;": '\U00002956', + "DownRightTeeVector;": '\U0000295F', + "DownRightVector;": '\U000021C1', + "DownRightVectorBar;": '\U00002957', + "DownTee;": '\U000022A4', + "DownTeeArrow;": '\U000021A7', + "Downarrow;": '\U000021D3', + "Dscr;": '\U0001D49F', + "Dstrok;": '\U00000110', + "ENG;": '\U0000014A', + "ETH;": '\U000000D0', + "Eacute;": '\U000000C9', + "Ecaron;": '\U0000011A', + "Ecirc;": '\U000000CA', + "Ecy;": '\U0000042D', + "Edot;": '\U00000116', + "Efr;": '\U0001D508', + "Egrave;": '\U000000C8', + "Element;": '\U00002208', + "Emacr;": '\U00000112', + "EmptySmallSquare;": '\U000025FB', + "EmptyVerySmallSquare;": '\U000025AB', + "Eogon;": '\U00000118', + "Eopf;": '\U0001D53C', + "Epsilon;": '\U00000395', + "Equal;": '\U00002A75', + "EqualTilde;": '\U00002242', + "Equilibrium;": '\U000021CC', + "Escr;": '\U00002130', + "Esim;": '\U00002A73', + "Eta;": '\U00000397', + "Euml;": '\U000000CB', + "Exists;": '\U00002203', + "ExponentialE;": '\U00002147', + "Fcy;": '\U00000424', + "Ffr;": '\U0001D509', + "FilledSmallSquare;": '\U000025FC', + "FilledVerySmallSquare;": '\U000025AA', + "Fopf;": '\U0001D53D', + "ForAll;": '\U00002200', + "Fouriertrf;": '\U00002131', + "Fscr;": '\U00002131', + "GJcy;": '\U00000403', + "GT;": '\U0000003E', + "Gamma;": '\U00000393', + "Gammad;": '\U000003DC', + "Gbreve;": '\U0000011E', + "Gcedil;": '\U00000122', + "Gcirc;": '\U0000011C', + "Gcy;": '\U00000413', + "Gdot;": '\U00000120', + "Gfr;": '\U0001D50A', + "Gg;": '\U000022D9', + "Gopf;": '\U0001D53E', + "GreaterEqual;": '\U00002265', + "GreaterEqualLess;": '\U000022DB', + "GreaterFullEqual;": '\U00002267', + "GreaterGreater;": '\U00002AA2', + "GreaterLess;": '\U00002277', + "GreaterSlantEqual;": '\U00002A7E', + "GreaterTilde;": '\U00002273', + "Gscr;": '\U0001D4A2', + "Gt;": '\U0000226B', + "HARDcy;": '\U0000042A', + "Hacek;": '\U000002C7', + "Hat;": '\U0000005E', + "Hcirc;": '\U00000124', + "Hfr;": '\U0000210C', + "HilbertSpace;": '\U0000210B', + "Hopf;": '\U0000210D', + "HorizontalLine;": '\U00002500', + "Hscr;": '\U0000210B', + "Hstrok;": '\U00000126', + "HumpDownHump;": '\U0000224E', + "HumpEqual;": '\U0000224F', + "IEcy;": '\U00000415', + "IJlig;": '\U00000132', + "IOcy;": '\U00000401', + "Iacute;": '\U000000CD', + "Icirc;": '\U000000CE', + "Icy;": '\U00000418', + "Idot;": '\U00000130', + "Ifr;": '\U00002111', + "Igrave;": '\U000000CC', + "Im;": '\U00002111', + "Imacr;": '\U0000012A', + "ImaginaryI;": '\U00002148', + "Implies;": '\U000021D2', + "Int;": '\U0000222C', + "Integral;": '\U0000222B', + "Intersection;": '\U000022C2', + "InvisibleComma;": '\U00002063', + "InvisibleTimes;": '\U00002062', + "Iogon;": '\U0000012E', + "Iopf;": '\U0001D540', + "Iota;": '\U00000399', + "Iscr;": '\U00002110', + "Itilde;": '\U00000128', + "Iukcy;": '\U00000406', + "Iuml;": '\U000000CF', + "Jcirc;": '\U00000134', + "Jcy;": '\U00000419', + "Jfr;": '\U0001D50D', + "Jopf;": '\U0001D541', + "Jscr;": '\U0001D4A5', + "Jsercy;": '\U00000408', + "Jukcy;": '\U00000404', + "KHcy;": '\U00000425', + "KJcy;": '\U0000040C', + "Kappa;": '\U0000039A', + "Kcedil;": '\U00000136', + "Kcy;": '\U0000041A', + "Kfr;": '\U0001D50E', + "Kopf;": '\U0001D542', + "Kscr;": '\U0001D4A6', + "LJcy;": '\U00000409', + "LT;": '\U0000003C', + "Lacute;": '\U00000139', + "Lambda;": '\U0000039B', + "Lang;": '\U000027EA', + "Laplacetrf;": '\U00002112', + "Larr;": '\U0000219E', + "Lcaron;": '\U0000013D', + "Lcedil;": '\U0000013B', + "Lcy;": '\U0000041B', + "LeftAngleBracket;": '\U000027E8', + "LeftArrow;": '\U00002190', + "LeftArrowBar;": '\U000021E4', + "LeftArrowRightArrow;": '\U000021C6', + "LeftCeiling;": '\U00002308', + "LeftDoubleBracket;": '\U000027E6', + "LeftDownTeeVector;": '\U00002961', + "LeftDownVector;": '\U000021C3', + "LeftDownVectorBar;": '\U00002959', + "LeftFloor;": '\U0000230A', + "LeftRightArrow;": '\U00002194', + "LeftRightVector;": '\U0000294E', + "LeftTee;": '\U000022A3', + "LeftTeeArrow;": '\U000021A4', + "LeftTeeVector;": '\U0000295A', + "LeftTriangle;": '\U000022B2', + "LeftTriangleBar;": '\U000029CF', + "LeftTriangleEqual;": '\U000022B4', + "LeftUpDownVector;": '\U00002951', + "LeftUpTeeVector;": '\U00002960', + "LeftUpVector;": '\U000021BF', + "LeftUpVectorBar;": '\U00002958', + "LeftVector;": '\U000021BC', + "LeftVectorBar;": '\U00002952', + "Leftarrow;": '\U000021D0', + "Leftrightarrow;": '\U000021D4', + "LessEqualGreater;": '\U000022DA', + "LessFullEqual;": '\U00002266', + "LessGreater;": '\U00002276', + "LessLess;": '\U00002AA1', + "LessSlantEqual;": '\U00002A7D', + "LessTilde;": '\U00002272', + "Lfr;": '\U0001D50F', + "Ll;": '\U000022D8', + "Lleftarrow;": '\U000021DA', + "Lmidot;": '\U0000013F', + "LongLeftArrow;": '\U000027F5', + "LongLeftRightArrow;": '\U000027F7', + "LongRightArrow;": '\U000027F6', + "Longleftarrow;": '\U000027F8', + "Longleftrightarrow;": '\U000027FA', + "Longrightarrow;": '\U000027F9', + "Lopf;": '\U0001D543', + "LowerLeftArrow;": '\U00002199', + "LowerRightArrow;": '\U00002198', + "Lscr;": '\U00002112', + "Lsh;": '\U000021B0', + "Lstrok;": '\U00000141', + "Lt;": '\U0000226A', + "Map;": '\U00002905', + "Mcy;": '\U0000041C', + "MediumSpace;": '\U0000205F', + "Mellintrf;": '\U00002133', + "Mfr;": '\U0001D510', + "MinusPlus;": '\U00002213', + "Mopf;": '\U0001D544', + "Mscr;": '\U00002133', + "Mu;": '\U0000039C', + "NJcy;": '\U0000040A', + "Nacute;": '\U00000143', + "Ncaron;": '\U00000147', + "Ncedil;": '\U00000145', + "Ncy;": '\U0000041D', + "NegativeMediumSpace;": '\U0000200B', + "NegativeThickSpace;": '\U0000200B', + "NegativeThinSpace;": '\U0000200B', + "NegativeVeryThinSpace;": '\U0000200B', + "NestedGreaterGreater;": '\U0000226B', + "NestedLessLess;": '\U0000226A', + "NewLine;": '\U0000000A', + "Nfr;": '\U0001D511', + "NoBreak;": '\U00002060', + "NonBreakingSpace;": '\U000000A0', + "Nopf;": '\U00002115', + "Not;": '\U00002AEC', + "NotCongruent;": '\U00002262', + "NotCupCap;": '\U0000226D', + "NotDoubleVerticalBar;": '\U00002226', + "NotElement;": '\U00002209', + "NotEqual;": '\U00002260', + "NotExists;": '\U00002204', + "NotGreater;": '\U0000226F', + "NotGreaterEqual;": '\U00002271', + "NotGreaterLess;": '\U00002279', + "NotGreaterTilde;": '\U00002275', + "NotLeftTriangle;": '\U000022EA', + "NotLeftTriangleEqual;": '\U000022EC', + "NotLess;": '\U0000226E', + "NotLessEqual;": '\U00002270', + "NotLessGreater;": '\U00002278', + "NotLessTilde;": '\U00002274', + "NotPrecedes;": '\U00002280', + "NotPrecedesSlantEqual;": '\U000022E0', + "NotReverseElement;": '\U0000220C', + "NotRightTriangle;": '\U000022EB', + "NotRightTriangleEqual;": '\U000022ED', + "NotSquareSubsetEqual;": '\U000022E2', + "NotSquareSupersetEqual;": '\U000022E3', + "NotSubsetEqual;": '\U00002288', + "NotSucceeds;": '\U00002281', + "NotSucceedsSlantEqual;": '\U000022E1', + "NotSupersetEqual;": '\U00002289', + "NotTilde;": '\U00002241', + "NotTildeEqual;": '\U00002244', + "NotTildeFullEqual;": '\U00002247', + "NotTildeTilde;": '\U00002249', + "NotVerticalBar;": '\U00002224', + "Nscr;": '\U0001D4A9', + "Ntilde;": '\U000000D1', + "Nu;": '\U0000039D', + "OElig;": '\U00000152', + "Oacute;": '\U000000D3', + "Ocirc;": '\U000000D4', + "Ocy;": '\U0000041E', + "Odblac;": '\U00000150', + "Ofr;": '\U0001D512', + "Ograve;": '\U000000D2', + "Omacr;": '\U0000014C', + "Omega;": '\U000003A9', + "Omicron;": '\U0000039F', + "Oopf;": '\U0001D546', + "OpenCurlyDoubleQuote;": '\U0000201C', + "OpenCurlyQuote;": '\U00002018', + "Or;": '\U00002A54', + "Oscr;": '\U0001D4AA', + "Oslash;": '\U000000D8', + "Otilde;": '\U000000D5', + "Otimes;": '\U00002A37', + "Ouml;": '\U000000D6', + "OverBar;": '\U0000203E', + "OverBrace;": '\U000023DE', + "OverBracket;": '\U000023B4', + "OverParenthesis;": '\U000023DC', + "PartialD;": '\U00002202', + "Pcy;": '\U0000041F', + "Pfr;": '\U0001D513', + "Phi;": '\U000003A6', + "Pi;": '\U000003A0', + "PlusMinus;": '\U000000B1', + "Poincareplane;": '\U0000210C', + "Popf;": '\U00002119', + "Pr;": '\U00002ABB', + "Precedes;": '\U0000227A', + "PrecedesEqual;": '\U00002AAF', + "PrecedesSlantEqual;": '\U0000227C', + "PrecedesTilde;": '\U0000227E', + "Prime;": '\U00002033', + "Product;": '\U0000220F', + "Proportion;": '\U00002237', + "Proportional;": '\U0000221D', + "Pscr;": '\U0001D4AB', + "Psi;": '\U000003A8', + "QUOT;": '\U00000022', + "Qfr;": '\U0001D514', + "Qopf;": '\U0000211A', + "Qscr;": '\U0001D4AC', + "RBarr;": '\U00002910', + "REG;": '\U000000AE', + "Racute;": '\U00000154', + "Rang;": '\U000027EB', + "Rarr;": '\U000021A0', + "Rarrtl;": '\U00002916', + "Rcaron;": '\U00000158', + "Rcedil;": '\U00000156', + "Rcy;": '\U00000420', + "Re;": '\U0000211C', + "ReverseElement;": '\U0000220B', + "ReverseEquilibrium;": '\U000021CB', + "ReverseUpEquilibrium;": '\U0000296F', + "Rfr;": '\U0000211C', + "Rho;": '\U000003A1', + "RightAngleBracket;": '\U000027E9', + "RightArrow;": '\U00002192', + "RightArrowBar;": '\U000021E5', + "RightArrowLeftArrow;": '\U000021C4', + "RightCeiling;": '\U00002309', + "RightDoubleBracket;": '\U000027E7', + "RightDownTeeVector;": '\U0000295D', + "RightDownVector;": '\U000021C2', + "RightDownVectorBar;": '\U00002955', + "RightFloor;": '\U0000230B', + "RightTee;": '\U000022A2', + "RightTeeArrow;": '\U000021A6', + "RightTeeVector;": '\U0000295B', + "RightTriangle;": '\U000022B3', + "RightTriangleBar;": '\U000029D0', + "RightTriangleEqual;": '\U000022B5', + "RightUpDownVector;": '\U0000294F', + "RightUpTeeVector;": '\U0000295C', + "RightUpVector;": '\U000021BE', + "RightUpVectorBar;": '\U00002954', + "RightVector;": '\U000021C0', + "RightVectorBar;": '\U00002953', + "Rightarrow;": '\U000021D2', + "Ropf;": '\U0000211D', + "RoundImplies;": '\U00002970', + "Rrightarrow;": '\U000021DB', + "Rscr;": '\U0000211B', + "Rsh;": '\U000021B1', + "RuleDelayed;": '\U000029F4', + "SHCHcy;": '\U00000429', + "SHcy;": '\U00000428', + "SOFTcy;": '\U0000042C', + "Sacute;": '\U0000015A', + "Sc;": '\U00002ABC', + "Scaron;": '\U00000160', + "Scedil;": '\U0000015E', + "Scirc;": '\U0000015C', + "Scy;": '\U00000421', + "Sfr;": '\U0001D516', + "ShortDownArrow;": '\U00002193', + "ShortLeftArrow;": '\U00002190', + "ShortRightArrow;": '\U00002192', + "ShortUpArrow;": '\U00002191', + "Sigma;": '\U000003A3', + "SmallCircle;": '\U00002218', + "Sopf;": '\U0001D54A', + "Sqrt;": '\U0000221A', + "Square;": '\U000025A1', + "SquareIntersection;": '\U00002293', + "SquareSubset;": '\U0000228F', + "SquareSubsetEqual;": '\U00002291', + "SquareSuperset;": '\U00002290', + "SquareSupersetEqual;": '\U00002292', + "SquareUnion;": '\U00002294', + "Sscr;": '\U0001D4AE', + "Star;": '\U000022C6', + "Sub;": '\U000022D0', + "Subset;": '\U000022D0', + "SubsetEqual;": '\U00002286', + "Succeeds;": '\U0000227B', + "SucceedsEqual;": '\U00002AB0', + "SucceedsSlantEqual;": '\U0000227D', + "SucceedsTilde;": '\U0000227F', + "SuchThat;": '\U0000220B', + "Sum;": '\U00002211', + "Sup;": '\U000022D1', + "Superset;": '\U00002283', + "SupersetEqual;": '\U00002287', + "Supset;": '\U000022D1', + "THORN;": '\U000000DE', + "TRADE;": '\U00002122', + "TSHcy;": '\U0000040B', + "TScy;": '\U00000426', + "Tab;": '\U00000009', + "Tau;": '\U000003A4', + "Tcaron;": '\U00000164', + "Tcedil;": '\U00000162', + "Tcy;": '\U00000422', + "Tfr;": '\U0001D517', + "Therefore;": '\U00002234', + "Theta;": '\U00000398', + "ThinSpace;": '\U00002009', + "Tilde;": '\U0000223C', + "TildeEqual;": '\U00002243', + "TildeFullEqual;": '\U00002245', + "TildeTilde;": '\U00002248', + "Topf;": '\U0001D54B', + "TripleDot;": '\U000020DB', + "Tscr;": '\U0001D4AF', + "Tstrok;": '\U00000166', + "Uacute;": '\U000000DA', + "Uarr;": '\U0000219F', + "Uarrocir;": '\U00002949', + "Ubrcy;": '\U0000040E', + "Ubreve;": '\U0000016C', + "Ucirc;": '\U000000DB', + "Ucy;": '\U00000423', + "Udblac;": '\U00000170', + "Ufr;": '\U0001D518', + "Ugrave;": '\U000000D9', + "Umacr;": '\U0000016A', + "UnderBar;": '\U0000005F', + "UnderBrace;": '\U000023DF', + "UnderBracket;": '\U000023B5', + "UnderParenthesis;": '\U000023DD', + "Union;": '\U000022C3', + "UnionPlus;": '\U0000228E', + "Uogon;": '\U00000172', + "Uopf;": '\U0001D54C', + "UpArrow;": '\U00002191', + "UpArrowBar;": '\U00002912', + "UpArrowDownArrow;": '\U000021C5', + "UpDownArrow;": '\U00002195', + "UpEquilibrium;": '\U0000296E', + "UpTee;": '\U000022A5', + "UpTeeArrow;": '\U000021A5', + "Uparrow;": '\U000021D1', + "Updownarrow;": '\U000021D5', + "UpperLeftArrow;": '\U00002196', + "UpperRightArrow;": '\U00002197', + "Upsi;": '\U000003D2', + "Upsilon;": '\U000003A5', + "Uring;": '\U0000016E', + "Uscr;": '\U0001D4B0', + "Utilde;": '\U00000168', + "Uuml;": '\U000000DC', + "VDash;": '\U000022AB', + "Vbar;": '\U00002AEB', + "Vcy;": '\U00000412', + "Vdash;": '\U000022A9', + "Vdashl;": '\U00002AE6', + "Vee;": '\U000022C1', + "Verbar;": '\U00002016', + "Vert;": '\U00002016', + "VerticalBar;": '\U00002223', + "VerticalLine;": '\U0000007C', + "VerticalSeparator;": '\U00002758', + "VerticalTilde;": '\U00002240', + "VeryThinSpace;": '\U0000200A', + "Vfr;": '\U0001D519', + "Vopf;": '\U0001D54D', + "Vscr;": '\U0001D4B1', + "Vvdash;": '\U000022AA', + "Wcirc;": '\U00000174', + "Wedge;": '\U000022C0', + "Wfr;": '\U0001D51A', + "Wopf;": '\U0001D54E', + "Wscr;": '\U0001D4B2', + "Xfr;": '\U0001D51B', + "Xi;": '\U0000039E', + "Xopf;": '\U0001D54F', + "Xscr;": '\U0001D4B3', + "YAcy;": '\U0000042F', + "YIcy;": '\U00000407', + "YUcy;": '\U0000042E', + "Yacute;": '\U000000DD', + "Ycirc;": '\U00000176', + "Ycy;": '\U0000042B', + "Yfr;": '\U0001D51C', + "Yopf;": '\U0001D550', + "Yscr;": '\U0001D4B4', + "Yuml;": '\U00000178', + "ZHcy;": '\U00000416', + "Zacute;": '\U00000179', + "Zcaron;": '\U0000017D', + "Zcy;": '\U00000417', + "Zdot;": '\U0000017B', + "ZeroWidthSpace;": '\U0000200B', + "Zeta;": '\U00000396', + "Zfr;": '\U00002128', + "Zopf;": '\U00002124', + "Zscr;": '\U0001D4B5', + "aacute;": '\U000000E1', + "abreve;": '\U00000103', + "ac;": '\U0000223E', + "acd;": '\U0000223F', + "acirc;": '\U000000E2', + "acute;": '\U000000B4', + "acy;": '\U00000430', + "aelig;": '\U000000E6', + "af;": '\U00002061', + "afr;": '\U0001D51E', + "agrave;": '\U000000E0', + "alefsym;": '\U00002135', + "aleph;": '\U00002135', + "alpha;": '\U000003B1', + "amacr;": '\U00000101', + "amalg;": '\U00002A3F', + "amp;": '\U00000026', + "and;": '\U00002227', + "andand;": '\U00002A55', + "andd;": '\U00002A5C', + "andslope;": '\U00002A58', + "andv;": '\U00002A5A', + "ang;": '\U00002220', + "ange;": '\U000029A4', + "angle;": '\U00002220', + "angmsd;": '\U00002221', + "angmsdaa;": '\U000029A8', + "angmsdab;": '\U000029A9', + "angmsdac;": '\U000029AA', + "angmsdad;": '\U000029AB', + "angmsdae;": '\U000029AC', + "angmsdaf;": '\U000029AD', + "angmsdag;": '\U000029AE', + "angmsdah;": '\U000029AF', + "angrt;": '\U0000221F', + "angrtvb;": '\U000022BE', + "angrtvbd;": '\U0000299D', + "angsph;": '\U00002222', + "angst;": '\U000000C5', + "angzarr;": '\U0000237C', + "aogon;": '\U00000105', + "aopf;": '\U0001D552', + "ap;": '\U00002248', + "apE;": '\U00002A70', + "apacir;": '\U00002A6F', + "ape;": '\U0000224A', + "apid;": '\U0000224B', + "apos;": '\U00000027', + "approx;": '\U00002248', + "approxeq;": '\U0000224A', + "aring;": '\U000000E5', + "ascr;": '\U0001D4B6', + "ast;": '\U0000002A', + "asymp;": '\U00002248', + "asympeq;": '\U0000224D', + "atilde;": '\U000000E3', + "auml;": '\U000000E4', + "awconint;": '\U00002233', + "awint;": '\U00002A11', + "bNot;": '\U00002AED', + "backcong;": '\U0000224C', + "backepsilon;": '\U000003F6', + "backprime;": '\U00002035', + "backsim;": '\U0000223D', + "backsimeq;": '\U000022CD', + "barvee;": '\U000022BD', + "barwed;": '\U00002305', + "barwedge;": '\U00002305', + "bbrk;": '\U000023B5', + "bbrktbrk;": '\U000023B6', + "bcong;": '\U0000224C', + "bcy;": '\U00000431', + "bdquo;": '\U0000201E', + "becaus;": '\U00002235', + "because;": '\U00002235', + "bemptyv;": '\U000029B0', + "bepsi;": '\U000003F6', + "bernou;": '\U0000212C', + "beta;": '\U000003B2', + "beth;": '\U00002136', + "between;": '\U0000226C', + "bfr;": '\U0001D51F', + "bigcap;": '\U000022C2', + "bigcirc;": '\U000025EF', + "bigcup;": '\U000022C3', + "bigodot;": '\U00002A00', + "bigoplus;": '\U00002A01', + "bigotimes;": '\U00002A02', + "bigsqcup;": '\U00002A06', + "bigstar;": '\U00002605', + "bigtriangledown;": '\U000025BD', + "bigtriangleup;": '\U000025B3', + "biguplus;": '\U00002A04', + "bigvee;": '\U000022C1', + "bigwedge;": '\U000022C0', + "bkarow;": '\U0000290D', + "blacklozenge;": '\U000029EB', + "blacksquare;": '\U000025AA', + "blacktriangle;": '\U000025B4', + "blacktriangledown;": '\U000025BE', + "blacktriangleleft;": '\U000025C2', + "blacktriangleright;": '\U000025B8', + "blank;": '\U00002423', + "blk12;": '\U00002592', + "blk14;": '\U00002591', + "blk34;": '\U00002593', + "block;": '\U00002588', + "bnot;": '\U00002310', + "bopf;": '\U0001D553', + "bot;": '\U000022A5', + "bottom;": '\U000022A5', + "bowtie;": '\U000022C8', + "boxDL;": '\U00002557', + "boxDR;": '\U00002554', + "boxDl;": '\U00002556', + "boxDr;": '\U00002553', + "boxH;": '\U00002550', + "boxHD;": '\U00002566', + "boxHU;": '\U00002569', + "boxHd;": '\U00002564', + "boxHu;": '\U00002567', + "boxUL;": '\U0000255D', + "boxUR;": '\U0000255A', + "boxUl;": '\U0000255C', + "boxUr;": '\U00002559', + "boxV;": '\U00002551', + "boxVH;": '\U0000256C', + "boxVL;": '\U00002563', + "boxVR;": '\U00002560', + "boxVh;": '\U0000256B', + "boxVl;": '\U00002562', + "boxVr;": '\U0000255F', + "boxbox;": '\U000029C9', + "boxdL;": '\U00002555', + "boxdR;": '\U00002552', + "boxdl;": '\U00002510', + "boxdr;": '\U0000250C', + "boxh;": '\U00002500', + "boxhD;": '\U00002565', + "boxhU;": '\U00002568', + "boxhd;": '\U0000252C', + "boxhu;": '\U00002534', + "boxminus;": '\U0000229F', + "boxplus;": '\U0000229E', + "boxtimes;": '\U000022A0', + "boxuL;": '\U0000255B', + "boxuR;": '\U00002558', + "boxul;": '\U00002518', + "boxur;": '\U00002514', + "boxv;": '\U00002502', + "boxvH;": '\U0000256A', + "boxvL;": '\U00002561', + "boxvR;": '\U0000255E', + "boxvh;": '\U0000253C', + "boxvl;": '\U00002524', + "boxvr;": '\U0000251C', + "bprime;": '\U00002035', + "breve;": '\U000002D8', + "brvbar;": '\U000000A6', + "bscr;": '\U0001D4B7', + "bsemi;": '\U0000204F', + "bsim;": '\U0000223D', + "bsime;": '\U000022CD', + "bsol;": '\U0000005C', + "bsolb;": '\U000029C5', + "bsolhsub;": '\U000027C8', + "bull;": '\U00002022', + "bullet;": '\U00002022', + "bump;": '\U0000224E', + "bumpE;": '\U00002AAE', + "bumpe;": '\U0000224F', + "bumpeq;": '\U0000224F', + "cacute;": '\U00000107', + "cap;": '\U00002229', + "capand;": '\U00002A44', + "capbrcup;": '\U00002A49', + "capcap;": '\U00002A4B', + "capcup;": '\U00002A47', + "capdot;": '\U00002A40', + "caret;": '\U00002041', + "caron;": '\U000002C7', + "ccaps;": '\U00002A4D', + "ccaron;": '\U0000010D', + "ccedil;": '\U000000E7', + "ccirc;": '\U00000109', + "ccups;": '\U00002A4C', + "ccupssm;": '\U00002A50', + "cdot;": '\U0000010B', + "cedil;": '\U000000B8', + "cemptyv;": '\U000029B2', + "cent;": '\U000000A2', + "centerdot;": '\U000000B7', + "cfr;": '\U0001D520', + "chcy;": '\U00000447', + "check;": '\U00002713', + "checkmark;": '\U00002713', + "chi;": '\U000003C7', + "cir;": '\U000025CB', + "cirE;": '\U000029C3', + "circ;": '\U000002C6', + "circeq;": '\U00002257', + "circlearrowleft;": '\U000021BA', + "circlearrowright;": '\U000021BB', + "circledR;": '\U000000AE', + "circledS;": '\U000024C8', + "circledast;": '\U0000229B', + "circledcirc;": '\U0000229A', + "circleddash;": '\U0000229D', + "cire;": '\U00002257', + "cirfnint;": '\U00002A10', + "cirmid;": '\U00002AEF', + "cirscir;": '\U000029C2', + "clubs;": '\U00002663', + "clubsuit;": '\U00002663', + "colon;": '\U0000003A', + "colone;": '\U00002254', + "coloneq;": '\U00002254', + "comma;": '\U0000002C', + "commat;": '\U00000040', + "comp;": '\U00002201', + "compfn;": '\U00002218', + "complement;": '\U00002201', + "complexes;": '\U00002102', + "cong;": '\U00002245', + "congdot;": '\U00002A6D', + "conint;": '\U0000222E', + "copf;": '\U0001D554', + "coprod;": '\U00002210', + "copy;": '\U000000A9', + "copysr;": '\U00002117', + "crarr;": '\U000021B5', + "cross;": '\U00002717', + "cscr;": '\U0001D4B8', + "csub;": '\U00002ACF', + "csube;": '\U00002AD1', + "csup;": '\U00002AD0', + "csupe;": '\U00002AD2', + "ctdot;": '\U000022EF', + "cudarrl;": '\U00002938', + "cudarrr;": '\U00002935', + "cuepr;": '\U000022DE', + "cuesc;": '\U000022DF', + "cularr;": '\U000021B6', + "cularrp;": '\U0000293D', + "cup;": '\U0000222A', + "cupbrcap;": '\U00002A48', + "cupcap;": '\U00002A46', + "cupcup;": '\U00002A4A', + "cupdot;": '\U0000228D', + "cupor;": '\U00002A45', + "curarr;": '\U000021B7', + "curarrm;": '\U0000293C', + "curlyeqprec;": '\U000022DE', + "curlyeqsucc;": '\U000022DF', + "curlyvee;": '\U000022CE', + "curlywedge;": '\U000022CF', + "curren;": '\U000000A4', + "curvearrowleft;": '\U000021B6', + "curvearrowright;": '\U000021B7', + "cuvee;": '\U000022CE', + "cuwed;": '\U000022CF', + "cwconint;": '\U00002232', + "cwint;": '\U00002231', + "cylcty;": '\U0000232D', + "dArr;": '\U000021D3', + "dHar;": '\U00002965', + "dagger;": '\U00002020', + "daleth;": '\U00002138', + "darr;": '\U00002193', + "dash;": '\U00002010', + "dashv;": '\U000022A3', + "dbkarow;": '\U0000290F', + "dblac;": '\U000002DD', + "dcaron;": '\U0000010F', + "dcy;": '\U00000434', + "dd;": '\U00002146', + "ddagger;": '\U00002021', + "ddarr;": '\U000021CA', + "ddotseq;": '\U00002A77', + "deg;": '\U000000B0', + "delta;": '\U000003B4', + "demptyv;": '\U000029B1', + "dfisht;": '\U0000297F', + "dfr;": '\U0001D521', + "dharl;": '\U000021C3', + "dharr;": '\U000021C2', + "diam;": '\U000022C4', + "diamond;": '\U000022C4', + "diamondsuit;": '\U00002666', + "diams;": '\U00002666', + "die;": '\U000000A8', + "digamma;": '\U000003DD', + "disin;": '\U000022F2', + "div;": '\U000000F7', + "divide;": '\U000000F7', + "divideontimes;": '\U000022C7', + "divonx;": '\U000022C7', + "djcy;": '\U00000452', + "dlcorn;": '\U0000231E', + "dlcrop;": '\U0000230D', + "dollar;": '\U00000024', + "dopf;": '\U0001D555', + "dot;": '\U000002D9', + "doteq;": '\U00002250', + "doteqdot;": '\U00002251', + "dotminus;": '\U00002238', + "dotplus;": '\U00002214', + "dotsquare;": '\U000022A1', + "doublebarwedge;": '\U00002306', + "downarrow;": '\U00002193', + "downdownarrows;": '\U000021CA', + "downharpoonleft;": '\U000021C3', + "downharpoonright;": '\U000021C2', + "drbkarow;": '\U00002910', + "drcorn;": '\U0000231F', + "drcrop;": '\U0000230C', + "dscr;": '\U0001D4B9', + "dscy;": '\U00000455', + "dsol;": '\U000029F6', + "dstrok;": '\U00000111', + "dtdot;": '\U000022F1', + "dtri;": '\U000025BF', + "dtrif;": '\U000025BE', + "duarr;": '\U000021F5', + "duhar;": '\U0000296F', + "dwangle;": '\U000029A6', + "dzcy;": '\U0000045F', + "dzigrarr;": '\U000027FF', + "eDDot;": '\U00002A77', + "eDot;": '\U00002251', + "eacute;": '\U000000E9', + "easter;": '\U00002A6E', + "ecaron;": '\U0000011B', + "ecir;": '\U00002256', + "ecirc;": '\U000000EA', + "ecolon;": '\U00002255', + "ecy;": '\U0000044D', + "edot;": '\U00000117', + "ee;": '\U00002147', + "efDot;": '\U00002252', + "efr;": '\U0001D522', + "eg;": '\U00002A9A', + "egrave;": '\U000000E8', + "egs;": '\U00002A96', + "egsdot;": '\U00002A98', + "el;": '\U00002A99', + "elinters;": '\U000023E7', + "ell;": '\U00002113', + "els;": '\U00002A95', + "elsdot;": '\U00002A97', + "emacr;": '\U00000113', + "empty;": '\U00002205', + "emptyset;": '\U00002205', + "emptyv;": '\U00002205', + "emsp;": '\U00002003', + "emsp13;": '\U00002004', + "emsp14;": '\U00002005', + "eng;": '\U0000014B', + "ensp;": '\U00002002', + "eogon;": '\U00000119', + "eopf;": '\U0001D556', + "epar;": '\U000022D5', + "eparsl;": '\U000029E3', + "eplus;": '\U00002A71', + "epsi;": '\U000003B5', + "epsilon;": '\U000003B5', + "epsiv;": '\U000003F5', + "eqcirc;": '\U00002256', + "eqcolon;": '\U00002255', + "eqsim;": '\U00002242', + "eqslantgtr;": '\U00002A96', + "eqslantless;": '\U00002A95', + "equals;": '\U0000003D', + "equest;": '\U0000225F', + "equiv;": '\U00002261', + "equivDD;": '\U00002A78', + "eqvparsl;": '\U000029E5', + "erDot;": '\U00002253', + "erarr;": '\U00002971', + "escr;": '\U0000212F', + "esdot;": '\U00002250', + "esim;": '\U00002242', + "eta;": '\U000003B7', + "eth;": '\U000000F0', + "euml;": '\U000000EB', + "euro;": '\U000020AC', + "excl;": '\U00000021', + "exist;": '\U00002203', + "expectation;": '\U00002130', + "exponentiale;": '\U00002147', + "fallingdotseq;": '\U00002252', + "fcy;": '\U00000444', + "female;": '\U00002640', + "ffilig;": '\U0000FB03', + "fflig;": '\U0000FB00', + "ffllig;": '\U0000FB04', + "ffr;": '\U0001D523', + "filig;": '\U0000FB01', + "flat;": '\U0000266D', + "fllig;": '\U0000FB02', + "fltns;": '\U000025B1', + "fnof;": '\U00000192', + "fopf;": '\U0001D557', + "forall;": '\U00002200', + "fork;": '\U000022D4', + "forkv;": '\U00002AD9', + "fpartint;": '\U00002A0D', + "frac12;": '\U000000BD', + "frac13;": '\U00002153', + "frac14;": '\U000000BC', + "frac15;": '\U00002155', + "frac16;": '\U00002159', + "frac18;": '\U0000215B', + "frac23;": '\U00002154', + "frac25;": '\U00002156', + "frac34;": '\U000000BE', + "frac35;": '\U00002157', + "frac38;": '\U0000215C', + "frac45;": '\U00002158', + "frac56;": '\U0000215A', + "frac58;": '\U0000215D', + "frac78;": '\U0000215E', + "frasl;": '\U00002044', + "frown;": '\U00002322', + "fscr;": '\U0001D4BB', + "gE;": '\U00002267', + "gEl;": '\U00002A8C', + "gacute;": '\U000001F5', + "gamma;": '\U000003B3', + "gammad;": '\U000003DD', + "gap;": '\U00002A86', + "gbreve;": '\U0000011F', + "gcirc;": '\U0000011D', + "gcy;": '\U00000433', + "gdot;": '\U00000121', + "ge;": '\U00002265', + "gel;": '\U000022DB', + "geq;": '\U00002265', + "geqq;": '\U00002267', + "geqslant;": '\U00002A7E', + "ges;": '\U00002A7E', + "gescc;": '\U00002AA9', + "gesdot;": '\U00002A80', + "gesdoto;": '\U00002A82', + "gesdotol;": '\U00002A84', + "gesles;": '\U00002A94', + "gfr;": '\U0001D524', + "gg;": '\U0000226B', + "ggg;": '\U000022D9', + "gimel;": '\U00002137', + "gjcy;": '\U00000453', + "gl;": '\U00002277', + "glE;": '\U00002A92', + "gla;": '\U00002AA5', + "glj;": '\U00002AA4', + "gnE;": '\U00002269', + "gnap;": '\U00002A8A', + "gnapprox;": '\U00002A8A', + "gne;": '\U00002A88', + "gneq;": '\U00002A88', + "gneqq;": '\U00002269', + "gnsim;": '\U000022E7', + "gopf;": '\U0001D558', + "grave;": '\U00000060', + "gscr;": '\U0000210A', + "gsim;": '\U00002273', + "gsime;": '\U00002A8E', + "gsiml;": '\U00002A90', + "gt;": '\U0000003E', + "gtcc;": '\U00002AA7', + "gtcir;": '\U00002A7A', + "gtdot;": '\U000022D7', + "gtlPar;": '\U00002995', + "gtquest;": '\U00002A7C', + "gtrapprox;": '\U00002A86', + "gtrarr;": '\U00002978', + "gtrdot;": '\U000022D7', + "gtreqless;": '\U000022DB', + "gtreqqless;": '\U00002A8C', + "gtrless;": '\U00002277', + "gtrsim;": '\U00002273', + "hArr;": '\U000021D4', + "hairsp;": '\U0000200A', + "half;": '\U000000BD', + "hamilt;": '\U0000210B', + "hardcy;": '\U0000044A', + "harr;": '\U00002194', + "harrcir;": '\U00002948', + "harrw;": '\U000021AD', + "hbar;": '\U0000210F', + "hcirc;": '\U00000125', + "hearts;": '\U00002665', + "heartsuit;": '\U00002665', + "hellip;": '\U00002026', + "hercon;": '\U000022B9', + "hfr;": '\U0001D525', + "hksearow;": '\U00002925', + "hkswarow;": '\U00002926', + "hoarr;": '\U000021FF', + "homtht;": '\U0000223B', + "hookleftarrow;": '\U000021A9', + "hookrightarrow;": '\U000021AA', + "hopf;": '\U0001D559', + "horbar;": '\U00002015', + "hscr;": '\U0001D4BD', + "hslash;": '\U0000210F', + "hstrok;": '\U00000127', + "hybull;": '\U00002043', + "hyphen;": '\U00002010', + "iacute;": '\U000000ED', + "ic;": '\U00002063', + "icirc;": '\U000000EE', + "icy;": '\U00000438', + "iecy;": '\U00000435', + "iexcl;": '\U000000A1', + "iff;": '\U000021D4', + "ifr;": '\U0001D526', + "igrave;": '\U000000EC', + "ii;": '\U00002148', + "iiiint;": '\U00002A0C', + "iiint;": '\U0000222D', + "iinfin;": '\U000029DC', + "iiota;": '\U00002129', + "ijlig;": '\U00000133', + "imacr;": '\U0000012B', + "image;": '\U00002111', + "imagline;": '\U00002110', + "imagpart;": '\U00002111', + "imath;": '\U00000131', + "imof;": '\U000022B7', + "imped;": '\U000001B5', + "in;": '\U00002208', + "incare;": '\U00002105', + "infin;": '\U0000221E', + "infintie;": '\U000029DD', + "inodot;": '\U00000131', + "int;": '\U0000222B', + "intcal;": '\U000022BA', + "integers;": '\U00002124', + "intercal;": '\U000022BA', + "intlarhk;": '\U00002A17', + "intprod;": '\U00002A3C', + "iocy;": '\U00000451', + "iogon;": '\U0000012F', + "iopf;": '\U0001D55A', + "iota;": '\U000003B9', + "iprod;": '\U00002A3C', + "iquest;": '\U000000BF', + "iscr;": '\U0001D4BE', + "isin;": '\U00002208', + "isinE;": '\U000022F9', + "isindot;": '\U000022F5', + "isins;": '\U000022F4', + "isinsv;": '\U000022F3', + "isinv;": '\U00002208', + "it;": '\U00002062', + "itilde;": '\U00000129', + "iukcy;": '\U00000456', + "iuml;": '\U000000EF', + "jcirc;": '\U00000135', + "jcy;": '\U00000439', + "jfr;": '\U0001D527', + "jmath;": '\U00000237', + "jopf;": '\U0001D55B', + "jscr;": '\U0001D4BF', + "jsercy;": '\U00000458', + "jukcy;": '\U00000454', + "kappa;": '\U000003BA', + "kappav;": '\U000003F0', + "kcedil;": '\U00000137', + "kcy;": '\U0000043A', + "kfr;": '\U0001D528', + "kgreen;": '\U00000138', + "khcy;": '\U00000445', + "kjcy;": '\U0000045C', + "kopf;": '\U0001D55C', + "kscr;": '\U0001D4C0', + "lAarr;": '\U000021DA', + "lArr;": '\U000021D0', + "lAtail;": '\U0000291B', + "lBarr;": '\U0000290E', + "lE;": '\U00002266', + "lEg;": '\U00002A8B', + "lHar;": '\U00002962', + "lacute;": '\U0000013A', + "laemptyv;": '\U000029B4', + "lagran;": '\U00002112', + "lambda;": '\U000003BB', + "lang;": '\U000027E8', + "langd;": '\U00002991', + "langle;": '\U000027E8', + "lap;": '\U00002A85', + "laquo;": '\U000000AB', + "larr;": '\U00002190', + "larrb;": '\U000021E4', + "larrbfs;": '\U0000291F', + "larrfs;": '\U0000291D', + "larrhk;": '\U000021A9', + "larrlp;": '\U000021AB', + "larrpl;": '\U00002939', + "larrsim;": '\U00002973', + "larrtl;": '\U000021A2', + "lat;": '\U00002AAB', + "latail;": '\U00002919', + "late;": '\U00002AAD', + "lbarr;": '\U0000290C', + "lbbrk;": '\U00002772', + "lbrace;": '\U0000007B', + "lbrack;": '\U0000005B', + "lbrke;": '\U0000298B', + "lbrksld;": '\U0000298F', + "lbrkslu;": '\U0000298D', + "lcaron;": '\U0000013E', + "lcedil;": '\U0000013C', + "lceil;": '\U00002308', + "lcub;": '\U0000007B', + "lcy;": '\U0000043B', + "ldca;": '\U00002936', + "ldquo;": '\U0000201C', + "ldquor;": '\U0000201E', + "ldrdhar;": '\U00002967', + "ldrushar;": '\U0000294B', + "ldsh;": '\U000021B2', + "le;": '\U00002264', + "leftarrow;": '\U00002190', + "leftarrowtail;": '\U000021A2', + "leftharpoondown;": '\U000021BD', + "leftharpoonup;": '\U000021BC', + "leftleftarrows;": '\U000021C7', + "leftrightarrow;": '\U00002194', + "leftrightarrows;": '\U000021C6', + "leftrightharpoons;": '\U000021CB', + "leftrightsquigarrow;": '\U000021AD', + "leftthreetimes;": '\U000022CB', + "leg;": '\U000022DA', + "leq;": '\U00002264', + "leqq;": '\U00002266', + "leqslant;": '\U00002A7D', + "les;": '\U00002A7D', + "lescc;": '\U00002AA8', + "lesdot;": '\U00002A7F', + "lesdoto;": '\U00002A81', + "lesdotor;": '\U00002A83', + "lesges;": '\U00002A93', + "lessapprox;": '\U00002A85', + "lessdot;": '\U000022D6', + "lesseqgtr;": '\U000022DA', + "lesseqqgtr;": '\U00002A8B', + "lessgtr;": '\U00002276', + "lesssim;": '\U00002272', + "lfisht;": '\U0000297C', + "lfloor;": '\U0000230A', + "lfr;": '\U0001D529', + "lg;": '\U00002276', + "lgE;": '\U00002A91', + "lhard;": '\U000021BD', + "lharu;": '\U000021BC', + "lharul;": '\U0000296A', + "lhblk;": '\U00002584', + "ljcy;": '\U00000459', + "ll;": '\U0000226A', + "llarr;": '\U000021C7', + "llcorner;": '\U0000231E', + "llhard;": '\U0000296B', + "lltri;": '\U000025FA', + "lmidot;": '\U00000140', + "lmoust;": '\U000023B0', + "lmoustache;": '\U000023B0', + "lnE;": '\U00002268', + "lnap;": '\U00002A89', + "lnapprox;": '\U00002A89', + "lne;": '\U00002A87', + "lneq;": '\U00002A87', + "lneqq;": '\U00002268', + "lnsim;": '\U000022E6', + "loang;": '\U000027EC', + "loarr;": '\U000021FD', + "lobrk;": '\U000027E6', + "longleftarrow;": '\U000027F5', + "longleftrightarrow;": '\U000027F7', + "longmapsto;": '\U000027FC', + "longrightarrow;": '\U000027F6', + "looparrowleft;": '\U000021AB', + "looparrowright;": '\U000021AC', + "lopar;": '\U00002985', + "lopf;": '\U0001D55D', + "loplus;": '\U00002A2D', + "lotimes;": '\U00002A34', + "lowast;": '\U00002217', + "lowbar;": '\U0000005F', + "loz;": '\U000025CA', + "lozenge;": '\U000025CA', + "lozf;": '\U000029EB', + "lpar;": '\U00000028', + "lparlt;": '\U00002993', + "lrarr;": '\U000021C6', + "lrcorner;": '\U0000231F', + "lrhar;": '\U000021CB', + "lrhard;": '\U0000296D', + "lrm;": '\U0000200E', + "lrtri;": '\U000022BF', + "lsaquo;": '\U00002039', + "lscr;": '\U0001D4C1', + "lsh;": '\U000021B0', + "lsim;": '\U00002272', + "lsime;": '\U00002A8D', + "lsimg;": '\U00002A8F', + "lsqb;": '\U0000005B', + "lsquo;": '\U00002018', + "lsquor;": '\U0000201A', + "lstrok;": '\U00000142', + "lt;": '\U0000003C', + "ltcc;": '\U00002AA6', + "ltcir;": '\U00002A79', + "ltdot;": '\U000022D6', + "lthree;": '\U000022CB', + "ltimes;": '\U000022C9', + "ltlarr;": '\U00002976', + "ltquest;": '\U00002A7B', + "ltrPar;": '\U00002996', + "ltri;": '\U000025C3', + "ltrie;": '\U000022B4', + "ltrif;": '\U000025C2', + "lurdshar;": '\U0000294A', + "luruhar;": '\U00002966', + "mDDot;": '\U0000223A', + "macr;": '\U000000AF', + "male;": '\U00002642', + "malt;": '\U00002720', + "maltese;": '\U00002720', + "map;": '\U000021A6', + "mapsto;": '\U000021A6', + "mapstodown;": '\U000021A7', + "mapstoleft;": '\U000021A4', + "mapstoup;": '\U000021A5', + "marker;": '\U000025AE', + "mcomma;": '\U00002A29', + "mcy;": '\U0000043C', + "mdash;": '\U00002014', + "measuredangle;": '\U00002221', + "mfr;": '\U0001D52A', + "mho;": '\U00002127', + "micro;": '\U000000B5', + "mid;": '\U00002223', + "midast;": '\U0000002A', + "midcir;": '\U00002AF0', + "middot;": '\U000000B7', + "minus;": '\U00002212', + "minusb;": '\U0000229F', + "minusd;": '\U00002238', + "minusdu;": '\U00002A2A', + "mlcp;": '\U00002ADB', + "mldr;": '\U00002026', + "mnplus;": '\U00002213', + "models;": '\U000022A7', + "mopf;": '\U0001D55E', + "mp;": '\U00002213', + "mscr;": '\U0001D4C2', + "mstpos;": '\U0000223E', + "mu;": '\U000003BC', + "multimap;": '\U000022B8', + "mumap;": '\U000022B8', + "nLeftarrow;": '\U000021CD', + "nLeftrightarrow;": '\U000021CE', + "nRightarrow;": '\U000021CF', + "nVDash;": '\U000022AF', + "nVdash;": '\U000022AE', + "nabla;": '\U00002207', + "nacute;": '\U00000144', + "nap;": '\U00002249', + "napos;": '\U00000149', + "napprox;": '\U00002249', + "natur;": '\U0000266E', + "natural;": '\U0000266E', + "naturals;": '\U00002115', + "nbsp;": '\U000000A0', + "ncap;": '\U00002A43', + "ncaron;": '\U00000148', + "ncedil;": '\U00000146', + "ncong;": '\U00002247', + "ncup;": '\U00002A42', + "ncy;": '\U0000043D', + "ndash;": '\U00002013', + "ne;": '\U00002260', + "neArr;": '\U000021D7', + "nearhk;": '\U00002924', + "nearr;": '\U00002197', + "nearrow;": '\U00002197', + "nequiv;": '\U00002262', + "nesear;": '\U00002928', + "nexist;": '\U00002204', + "nexists;": '\U00002204', + "nfr;": '\U0001D52B', + "nge;": '\U00002271', + "ngeq;": '\U00002271', + "ngsim;": '\U00002275', + "ngt;": '\U0000226F', + "ngtr;": '\U0000226F', + "nhArr;": '\U000021CE', + "nharr;": '\U000021AE', + "nhpar;": '\U00002AF2', + "ni;": '\U0000220B', + "nis;": '\U000022FC', + "nisd;": '\U000022FA', + "niv;": '\U0000220B', + "njcy;": '\U0000045A', + "nlArr;": '\U000021CD', + "nlarr;": '\U0000219A', + "nldr;": '\U00002025', + "nle;": '\U00002270', + "nleftarrow;": '\U0000219A', + "nleftrightarrow;": '\U000021AE', + "nleq;": '\U00002270', + "nless;": '\U0000226E', + "nlsim;": '\U00002274', + "nlt;": '\U0000226E', + "nltri;": '\U000022EA', + "nltrie;": '\U000022EC', + "nmid;": '\U00002224', + "nopf;": '\U0001D55F', + "not;": '\U000000AC', + "notin;": '\U00002209', + "notinva;": '\U00002209', + "notinvb;": '\U000022F7', + "notinvc;": '\U000022F6', + "notni;": '\U0000220C', + "notniva;": '\U0000220C', + "notnivb;": '\U000022FE', + "notnivc;": '\U000022FD', + "npar;": '\U00002226', + "nparallel;": '\U00002226', + "npolint;": '\U00002A14', + "npr;": '\U00002280', + "nprcue;": '\U000022E0', + "nprec;": '\U00002280', + "nrArr;": '\U000021CF', + "nrarr;": '\U0000219B', + "nrightarrow;": '\U0000219B', + "nrtri;": '\U000022EB', + "nrtrie;": '\U000022ED', + "nsc;": '\U00002281', + "nsccue;": '\U000022E1', + "nscr;": '\U0001D4C3', + "nshortmid;": '\U00002224', + "nshortparallel;": '\U00002226', + "nsim;": '\U00002241', + "nsime;": '\U00002244', + "nsimeq;": '\U00002244', + "nsmid;": '\U00002224', + "nspar;": '\U00002226', + "nsqsube;": '\U000022E2', + "nsqsupe;": '\U000022E3', + "nsub;": '\U00002284', + "nsube;": '\U00002288', + "nsubseteq;": '\U00002288', + "nsucc;": '\U00002281', + "nsup;": '\U00002285', + "nsupe;": '\U00002289', + "nsupseteq;": '\U00002289', + "ntgl;": '\U00002279', + "ntilde;": '\U000000F1', + "ntlg;": '\U00002278', + "ntriangleleft;": '\U000022EA', + "ntrianglelefteq;": '\U000022EC', + "ntriangleright;": '\U000022EB', + "ntrianglerighteq;": '\U000022ED', + "nu;": '\U000003BD', + "num;": '\U00000023', + "numero;": '\U00002116', + "numsp;": '\U00002007', + "nvDash;": '\U000022AD', + "nvHarr;": '\U00002904', + "nvdash;": '\U000022AC', + "nvinfin;": '\U000029DE', + "nvlArr;": '\U00002902', + "nvrArr;": '\U00002903', + "nwArr;": '\U000021D6', + "nwarhk;": '\U00002923', + "nwarr;": '\U00002196', + "nwarrow;": '\U00002196', + "nwnear;": '\U00002927', + "oS;": '\U000024C8', + "oacute;": '\U000000F3', + "oast;": '\U0000229B', + "ocir;": '\U0000229A', + "ocirc;": '\U000000F4', + "ocy;": '\U0000043E', + "odash;": '\U0000229D', + "odblac;": '\U00000151', + "odiv;": '\U00002A38', + "odot;": '\U00002299', + "odsold;": '\U000029BC', + "oelig;": '\U00000153', + "ofcir;": '\U000029BF', + "ofr;": '\U0001D52C', + "ogon;": '\U000002DB', + "ograve;": '\U000000F2', + "ogt;": '\U000029C1', + "ohbar;": '\U000029B5', + "ohm;": '\U000003A9', + "oint;": '\U0000222E', + "olarr;": '\U000021BA', + "olcir;": '\U000029BE', + "olcross;": '\U000029BB', + "oline;": '\U0000203E', + "olt;": '\U000029C0', + "omacr;": '\U0000014D', + "omega;": '\U000003C9', + "omicron;": '\U000003BF', + "omid;": '\U000029B6', + "ominus;": '\U00002296', + "oopf;": '\U0001D560', + "opar;": '\U000029B7', + "operp;": '\U000029B9', + "oplus;": '\U00002295', + "or;": '\U00002228', + "orarr;": '\U000021BB', + "ord;": '\U00002A5D', + "order;": '\U00002134', + "orderof;": '\U00002134', + "ordf;": '\U000000AA', + "ordm;": '\U000000BA', + "origof;": '\U000022B6', + "oror;": '\U00002A56', + "orslope;": '\U00002A57', + "orv;": '\U00002A5B', + "oscr;": '\U00002134', + "oslash;": '\U000000F8', + "osol;": '\U00002298', + "otilde;": '\U000000F5', + "otimes;": '\U00002297', + "otimesas;": '\U00002A36', + "ouml;": '\U000000F6', + "ovbar;": '\U0000233D', + "par;": '\U00002225', + "para;": '\U000000B6', + "parallel;": '\U00002225', + "parsim;": '\U00002AF3', + "parsl;": '\U00002AFD', + "part;": '\U00002202', + "pcy;": '\U0000043F', + "percnt;": '\U00000025', + "period;": '\U0000002E', + "permil;": '\U00002030', + "perp;": '\U000022A5', + "pertenk;": '\U00002031', + "pfr;": '\U0001D52D', + "phi;": '\U000003C6', + "phiv;": '\U000003D5', + "phmmat;": '\U00002133', + "phone;": '\U0000260E', + "pi;": '\U000003C0', + "pitchfork;": '\U000022D4', + "piv;": '\U000003D6', + "planck;": '\U0000210F', + "planckh;": '\U0000210E', + "plankv;": '\U0000210F', + "plus;": '\U0000002B', + "plusacir;": '\U00002A23', + "plusb;": '\U0000229E', + "pluscir;": '\U00002A22', + "plusdo;": '\U00002214', + "plusdu;": '\U00002A25', + "pluse;": '\U00002A72', + "plusmn;": '\U000000B1', + "plussim;": '\U00002A26', + "plustwo;": '\U00002A27', + "pm;": '\U000000B1', + "pointint;": '\U00002A15', + "popf;": '\U0001D561', + "pound;": '\U000000A3', + "pr;": '\U0000227A', + "prE;": '\U00002AB3', + "prap;": '\U00002AB7', + "prcue;": '\U0000227C', + "pre;": '\U00002AAF', + "prec;": '\U0000227A', + "precapprox;": '\U00002AB7', + "preccurlyeq;": '\U0000227C', + "preceq;": '\U00002AAF', + "precnapprox;": '\U00002AB9', + "precneqq;": '\U00002AB5', + "precnsim;": '\U000022E8', + "precsim;": '\U0000227E', + "prime;": '\U00002032', + "primes;": '\U00002119', + "prnE;": '\U00002AB5', + "prnap;": '\U00002AB9', + "prnsim;": '\U000022E8', + "prod;": '\U0000220F', + "profalar;": '\U0000232E', + "profline;": '\U00002312', + "profsurf;": '\U00002313', + "prop;": '\U0000221D', + "propto;": '\U0000221D', + "prsim;": '\U0000227E', + "prurel;": '\U000022B0', + "pscr;": '\U0001D4C5', + "psi;": '\U000003C8', + "puncsp;": '\U00002008', + "qfr;": '\U0001D52E', + "qint;": '\U00002A0C', + "qopf;": '\U0001D562', + "qprime;": '\U00002057', + "qscr;": '\U0001D4C6', + "quaternions;": '\U0000210D', + "quatint;": '\U00002A16', + "quest;": '\U0000003F', + "questeq;": '\U0000225F', + "quot;": '\U00000022', + "rAarr;": '\U000021DB', + "rArr;": '\U000021D2', + "rAtail;": '\U0000291C', + "rBarr;": '\U0000290F', + "rHar;": '\U00002964', + "racute;": '\U00000155', + "radic;": '\U0000221A', + "raemptyv;": '\U000029B3', + "rang;": '\U000027E9', + "rangd;": '\U00002992', + "range;": '\U000029A5', + "rangle;": '\U000027E9', + "raquo;": '\U000000BB', + "rarr;": '\U00002192', + "rarrap;": '\U00002975', + "rarrb;": '\U000021E5', + "rarrbfs;": '\U00002920', + "rarrc;": '\U00002933', + "rarrfs;": '\U0000291E', + "rarrhk;": '\U000021AA', + "rarrlp;": '\U000021AC', + "rarrpl;": '\U00002945', + "rarrsim;": '\U00002974', + "rarrtl;": '\U000021A3', + "rarrw;": '\U0000219D', + "ratail;": '\U0000291A', + "ratio;": '\U00002236', + "rationals;": '\U0000211A', + "rbarr;": '\U0000290D', + "rbbrk;": '\U00002773', + "rbrace;": '\U0000007D', + "rbrack;": '\U0000005D', + "rbrke;": '\U0000298C', + "rbrksld;": '\U0000298E', + "rbrkslu;": '\U00002990', + "rcaron;": '\U00000159', + "rcedil;": '\U00000157', + "rceil;": '\U00002309', + "rcub;": '\U0000007D', + "rcy;": '\U00000440', + "rdca;": '\U00002937', + "rdldhar;": '\U00002969', + "rdquo;": '\U0000201D', + "rdquor;": '\U0000201D', + "rdsh;": '\U000021B3', + "real;": '\U0000211C', + "realine;": '\U0000211B', + "realpart;": '\U0000211C', + "reals;": '\U0000211D', + "rect;": '\U000025AD', + "reg;": '\U000000AE', + "rfisht;": '\U0000297D', + "rfloor;": '\U0000230B', + "rfr;": '\U0001D52F', + "rhard;": '\U000021C1', + "rharu;": '\U000021C0', + "rharul;": '\U0000296C', + "rho;": '\U000003C1', + "rhov;": '\U000003F1', + "rightarrow;": '\U00002192', + "rightarrowtail;": '\U000021A3', + "rightharpoondown;": '\U000021C1', + "rightharpoonup;": '\U000021C0', + "rightleftarrows;": '\U000021C4', + "rightleftharpoons;": '\U000021CC', + "rightrightarrows;": '\U000021C9', + "rightsquigarrow;": '\U0000219D', + "rightthreetimes;": '\U000022CC', + "ring;": '\U000002DA', + "risingdotseq;": '\U00002253', + "rlarr;": '\U000021C4', + "rlhar;": '\U000021CC', + "rlm;": '\U0000200F', + "rmoust;": '\U000023B1', + "rmoustache;": '\U000023B1', + "rnmid;": '\U00002AEE', + "roang;": '\U000027ED', + "roarr;": '\U000021FE', + "robrk;": '\U000027E7', + "ropar;": '\U00002986', + "ropf;": '\U0001D563', + "roplus;": '\U00002A2E', + "rotimes;": '\U00002A35', + "rpar;": '\U00000029', + "rpargt;": '\U00002994', + "rppolint;": '\U00002A12', + "rrarr;": '\U000021C9', + "rsaquo;": '\U0000203A', + "rscr;": '\U0001D4C7', + "rsh;": '\U000021B1', + "rsqb;": '\U0000005D', + "rsquo;": '\U00002019', + "rsquor;": '\U00002019', + "rthree;": '\U000022CC', + "rtimes;": '\U000022CA', + "rtri;": '\U000025B9', + "rtrie;": '\U000022B5', + "rtrif;": '\U000025B8', + "rtriltri;": '\U000029CE', + "ruluhar;": '\U00002968', + "rx;": '\U0000211E', + "sacute;": '\U0000015B', + "sbquo;": '\U0000201A', + "sc;": '\U0000227B', + "scE;": '\U00002AB4', + "scap;": '\U00002AB8', + "scaron;": '\U00000161', + "sccue;": '\U0000227D', + "sce;": '\U00002AB0', + "scedil;": '\U0000015F', + "scirc;": '\U0000015D', + "scnE;": '\U00002AB6', + "scnap;": '\U00002ABA', + "scnsim;": '\U000022E9', + "scpolint;": '\U00002A13', + "scsim;": '\U0000227F', + "scy;": '\U00000441', + "sdot;": '\U000022C5', + "sdotb;": '\U000022A1', + "sdote;": '\U00002A66', + "seArr;": '\U000021D8', + "searhk;": '\U00002925', + "searr;": '\U00002198', + "searrow;": '\U00002198', + "sect;": '\U000000A7', + "semi;": '\U0000003B', + "seswar;": '\U00002929', + "setminus;": '\U00002216', + "setmn;": '\U00002216', + "sext;": '\U00002736', + "sfr;": '\U0001D530', + "sfrown;": '\U00002322', + "sharp;": '\U0000266F', + "shchcy;": '\U00000449', + "shcy;": '\U00000448', + "shortmid;": '\U00002223', + "shortparallel;": '\U00002225', + "shy;": '\U000000AD', + "sigma;": '\U000003C3', + "sigmaf;": '\U000003C2', + "sigmav;": '\U000003C2', + "sim;": '\U0000223C', + "simdot;": '\U00002A6A', + "sime;": '\U00002243', + "simeq;": '\U00002243', + "simg;": '\U00002A9E', + "simgE;": '\U00002AA0', + "siml;": '\U00002A9D', + "simlE;": '\U00002A9F', + "simne;": '\U00002246', + "simplus;": '\U00002A24', + "simrarr;": '\U00002972', + "slarr;": '\U00002190', + "smallsetminus;": '\U00002216', + "smashp;": '\U00002A33', + "smeparsl;": '\U000029E4', + "smid;": '\U00002223', + "smile;": '\U00002323', + "smt;": '\U00002AAA', + "smte;": '\U00002AAC', + "softcy;": '\U0000044C', + "sol;": '\U0000002F', + "solb;": '\U000029C4', + "solbar;": '\U0000233F', + "sopf;": '\U0001D564', + "spades;": '\U00002660', + "spadesuit;": '\U00002660', + "spar;": '\U00002225', + "sqcap;": '\U00002293', + "sqcup;": '\U00002294', + "sqsub;": '\U0000228F', + "sqsube;": '\U00002291', + "sqsubset;": '\U0000228F', + "sqsubseteq;": '\U00002291', + "sqsup;": '\U00002290', + "sqsupe;": '\U00002292', + "sqsupset;": '\U00002290', + "sqsupseteq;": '\U00002292', + "squ;": '\U000025A1', + "square;": '\U000025A1', + "squarf;": '\U000025AA', + "squf;": '\U000025AA', + "srarr;": '\U00002192', + "sscr;": '\U0001D4C8', + "ssetmn;": '\U00002216', + "ssmile;": '\U00002323', + "sstarf;": '\U000022C6', + "star;": '\U00002606', + "starf;": '\U00002605', + "straightepsilon;": '\U000003F5', + "straightphi;": '\U000003D5', + "strns;": '\U000000AF', + "sub;": '\U00002282', + "subE;": '\U00002AC5', + "subdot;": '\U00002ABD', + "sube;": '\U00002286', + "subedot;": '\U00002AC3', + "submult;": '\U00002AC1', + "subnE;": '\U00002ACB', + "subne;": '\U0000228A', + "subplus;": '\U00002ABF', + "subrarr;": '\U00002979', + "subset;": '\U00002282', + "subseteq;": '\U00002286', + "subseteqq;": '\U00002AC5', + "subsetneq;": '\U0000228A', + "subsetneqq;": '\U00002ACB', + "subsim;": '\U00002AC7', + "subsub;": '\U00002AD5', + "subsup;": '\U00002AD3', + "succ;": '\U0000227B', + "succapprox;": '\U00002AB8', + "succcurlyeq;": '\U0000227D', + "succeq;": '\U00002AB0', + "succnapprox;": '\U00002ABA', + "succneqq;": '\U00002AB6', + "succnsim;": '\U000022E9', + "succsim;": '\U0000227F', + "sum;": '\U00002211', + "sung;": '\U0000266A', + "sup;": '\U00002283', + "sup1;": '\U000000B9', + "sup2;": '\U000000B2', + "sup3;": '\U000000B3', + "supE;": '\U00002AC6', + "supdot;": '\U00002ABE', + "supdsub;": '\U00002AD8', + "supe;": '\U00002287', + "supedot;": '\U00002AC4', + "suphsol;": '\U000027C9', + "suphsub;": '\U00002AD7', + "suplarr;": '\U0000297B', + "supmult;": '\U00002AC2', + "supnE;": '\U00002ACC', + "supne;": '\U0000228B', + "supplus;": '\U00002AC0', + "supset;": '\U00002283', + "supseteq;": '\U00002287', + "supseteqq;": '\U00002AC6', + "supsetneq;": '\U0000228B', + "supsetneqq;": '\U00002ACC', + "supsim;": '\U00002AC8', + "supsub;": '\U00002AD4', + "supsup;": '\U00002AD6', + "swArr;": '\U000021D9', + "swarhk;": '\U00002926', + "swarr;": '\U00002199', + "swarrow;": '\U00002199', + "swnwar;": '\U0000292A', + "szlig;": '\U000000DF', + "target;": '\U00002316', + "tau;": '\U000003C4', + "tbrk;": '\U000023B4', + "tcaron;": '\U00000165', + "tcedil;": '\U00000163', + "tcy;": '\U00000442', + "tdot;": '\U000020DB', + "telrec;": '\U00002315', + "tfr;": '\U0001D531', + "there4;": '\U00002234', + "therefore;": '\U00002234', + "theta;": '\U000003B8', + "thetasym;": '\U000003D1', + "thetav;": '\U000003D1', + "thickapprox;": '\U00002248', + "thicksim;": '\U0000223C', + "thinsp;": '\U00002009', + "thkap;": '\U00002248', + "thksim;": '\U0000223C', + "thorn;": '\U000000FE', + "tilde;": '\U000002DC', + "times;": '\U000000D7', + "timesb;": '\U000022A0', + "timesbar;": '\U00002A31', + "timesd;": '\U00002A30', + "tint;": '\U0000222D', + "toea;": '\U00002928', + "top;": '\U000022A4', + "topbot;": '\U00002336', + "topcir;": '\U00002AF1', + "topf;": '\U0001D565', + "topfork;": '\U00002ADA', + "tosa;": '\U00002929', + "tprime;": '\U00002034', + "trade;": '\U00002122', + "triangle;": '\U000025B5', + "triangledown;": '\U000025BF', + "triangleleft;": '\U000025C3', + "trianglelefteq;": '\U000022B4', + "triangleq;": '\U0000225C', + "triangleright;": '\U000025B9', + "trianglerighteq;": '\U000022B5', + "tridot;": '\U000025EC', + "trie;": '\U0000225C', + "triminus;": '\U00002A3A', + "triplus;": '\U00002A39', + "trisb;": '\U000029CD', + "tritime;": '\U00002A3B', + "trpezium;": '\U000023E2', + "tscr;": '\U0001D4C9', + "tscy;": '\U00000446', + "tshcy;": '\U0000045B', + "tstrok;": '\U00000167', + "twixt;": '\U0000226C', + "twoheadleftarrow;": '\U0000219E', + "twoheadrightarrow;": '\U000021A0', + "uArr;": '\U000021D1', + "uHar;": '\U00002963', + "uacute;": '\U000000FA', + "uarr;": '\U00002191', + "ubrcy;": '\U0000045E', + "ubreve;": '\U0000016D', + "ucirc;": '\U000000FB', + "ucy;": '\U00000443', + "udarr;": '\U000021C5', + "udblac;": '\U00000171', + "udhar;": '\U0000296E', + "ufisht;": '\U0000297E', + "ufr;": '\U0001D532', + "ugrave;": '\U000000F9', + "uharl;": '\U000021BF', + "uharr;": '\U000021BE', + "uhblk;": '\U00002580', + "ulcorn;": '\U0000231C', + "ulcorner;": '\U0000231C', + "ulcrop;": '\U0000230F', + "ultri;": '\U000025F8', + "umacr;": '\U0000016B', + "uml;": '\U000000A8', + "uogon;": '\U00000173', + "uopf;": '\U0001D566', + "uparrow;": '\U00002191', + "updownarrow;": '\U00002195', + "upharpoonleft;": '\U000021BF', + "upharpoonright;": '\U000021BE', + "uplus;": '\U0000228E', + "upsi;": '\U000003C5', + "upsih;": '\U000003D2', + "upsilon;": '\U000003C5', + "upuparrows;": '\U000021C8', + "urcorn;": '\U0000231D', + "urcorner;": '\U0000231D', + "urcrop;": '\U0000230E', + "uring;": '\U0000016F', + "urtri;": '\U000025F9', + "uscr;": '\U0001D4CA', + "utdot;": '\U000022F0', + "utilde;": '\U00000169', + "utri;": '\U000025B5', + "utrif;": '\U000025B4', + "uuarr;": '\U000021C8', + "uuml;": '\U000000FC', + "uwangle;": '\U000029A7', + "vArr;": '\U000021D5', + "vBar;": '\U00002AE8', + "vBarv;": '\U00002AE9', + "vDash;": '\U000022A8', + "vangrt;": '\U0000299C', + "varepsilon;": '\U000003F5', + "varkappa;": '\U000003F0', + "varnothing;": '\U00002205', + "varphi;": '\U000003D5', + "varpi;": '\U000003D6', + "varpropto;": '\U0000221D', + "varr;": '\U00002195', + "varrho;": '\U000003F1', + "varsigma;": '\U000003C2', + "vartheta;": '\U000003D1', + "vartriangleleft;": '\U000022B2', + "vartriangleright;": '\U000022B3', + "vcy;": '\U00000432', + "vdash;": '\U000022A2', + "vee;": '\U00002228', + "veebar;": '\U000022BB', + "veeeq;": '\U0000225A', + "vellip;": '\U000022EE', + "verbar;": '\U0000007C', + "vert;": '\U0000007C', + "vfr;": '\U0001D533', + "vltri;": '\U000022B2', + "vopf;": '\U0001D567', + "vprop;": '\U0000221D', + "vrtri;": '\U000022B3', + "vscr;": '\U0001D4CB', + "vzigzag;": '\U0000299A', + "wcirc;": '\U00000175', + "wedbar;": '\U00002A5F', + "wedge;": '\U00002227', + "wedgeq;": '\U00002259', + "weierp;": '\U00002118', + "wfr;": '\U0001D534', + "wopf;": '\U0001D568', + "wp;": '\U00002118', + "wr;": '\U00002240', + "wreath;": '\U00002240', + "wscr;": '\U0001D4CC', + "xcap;": '\U000022C2', + "xcirc;": '\U000025EF', + "xcup;": '\U000022C3', + "xdtri;": '\U000025BD', + "xfr;": '\U0001D535', + "xhArr;": '\U000027FA', + "xharr;": '\U000027F7', + "xi;": '\U000003BE', + "xlArr;": '\U000027F8', + "xlarr;": '\U000027F5', + "xmap;": '\U000027FC', + "xnis;": '\U000022FB', + "xodot;": '\U00002A00', + "xopf;": '\U0001D569', + "xoplus;": '\U00002A01', + "xotime;": '\U00002A02', + "xrArr;": '\U000027F9', + "xrarr;": '\U000027F6', + "xscr;": '\U0001D4CD', + "xsqcup;": '\U00002A06', + "xuplus;": '\U00002A04', + "xutri;": '\U000025B3', + "xvee;": '\U000022C1', + "xwedge;": '\U000022C0', + "yacute;": '\U000000FD', + "yacy;": '\U0000044F', + "ycirc;": '\U00000177', + "ycy;": '\U0000044B', + "yen;": '\U000000A5', + "yfr;": '\U0001D536', + "yicy;": '\U00000457', + "yopf;": '\U0001D56A', + "yscr;": '\U0001D4CE', + "yucy;": '\U0000044E', + "yuml;": '\U000000FF', + "zacute;": '\U0000017A', + "zcaron;": '\U0000017E', + "zcy;": '\U00000437', + "zdot;": '\U0000017C', + "zeetrf;": '\U00002128', + "zeta;": '\U000003B6', + "zfr;": '\U0001D537', + "zhcy;": '\U00000436', + "zigrarr;": '\U000021DD', + "zopf;": '\U0001D56B', + "zscr;": '\U0001D4CF', + "zwj;": '\U0000200D', + "zwnj;": '\U0000200C', + "AElig": '\U000000C6', + "AMP": '\U00000026', + "Aacute": '\U000000C1', + "Acirc": '\U000000C2', + "Agrave": '\U000000C0', + "Aring": '\U000000C5', + "Atilde": '\U000000C3', + "Auml": '\U000000C4', + "COPY": '\U000000A9', + "Ccedil": '\U000000C7', + "ETH": '\U000000D0', + "Eacute": '\U000000C9', + "Ecirc": '\U000000CA', + "Egrave": '\U000000C8', + "Euml": '\U000000CB', + "GT": '\U0000003E', + "Iacute": '\U000000CD', + "Icirc": '\U000000CE', + "Igrave": '\U000000CC', + "Iuml": '\U000000CF', + "LT": '\U0000003C', + "Ntilde": '\U000000D1', + "Oacute": '\U000000D3', + "Ocirc": '\U000000D4', + "Ograve": '\U000000D2', + "Oslash": '\U000000D8', + "Otilde": '\U000000D5', + "Ouml": '\U000000D6', + "QUOT": '\U00000022', + "REG": '\U000000AE', + "THORN": '\U000000DE', + "Uacute": '\U000000DA', + "Ucirc": '\U000000DB', + "Ugrave": '\U000000D9', + "Uuml": '\U000000DC', + "Yacute": '\U000000DD', + "aacute": '\U000000E1', + "acirc": '\U000000E2', + "acute": '\U000000B4', + "aelig": '\U000000E6', + "agrave": '\U000000E0', + "amp": '\U00000026', + "aring": '\U000000E5', + "atilde": '\U000000E3', + "auml": '\U000000E4', + "brvbar": '\U000000A6', + "ccedil": '\U000000E7', + "cedil": '\U000000B8', + "cent": '\U000000A2', + "copy": '\U000000A9', + "curren": '\U000000A4', + "deg": '\U000000B0', + "divide": '\U000000F7', + "eacute": '\U000000E9', + "ecirc": '\U000000EA', + "egrave": '\U000000E8', + "eth": '\U000000F0', + "euml": '\U000000EB', + "frac12": '\U000000BD', + "frac14": '\U000000BC', + "frac34": '\U000000BE', + "gt": '\U0000003E', + "iacute": '\U000000ED', + "icirc": '\U000000EE', + "iexcl": '\U000000A1', + "igrave": '\U000000EC', + "iquest": '\U000000BF', + "iuml": '\U000000EF', + "laquo": '\U000000AB', + "lt": '\U0000003C', + "macr": '\U000000AF', + "micro": '\U000000B5', + "middot": '\U000000B7', + "nbsp": '\U000000A0', + "not": '\U000000AC', + "ntilde": '\U000000F1', + "oacute": '\U000000F3', + "ocirc": '\U000000F4', + "ograve": '\U000000F2', + "ordf": '\U000000AA', + "ordm": '\U000000BA', + "oslash": '\U000000F8', + "otilde": '\U000000F5', + "ouml": '\U000000F6', + "para": '\U000000B6', + "plusmn": '\U000000B1', + "pound": '\U000000A3', + "quot": '\U00000022', + "raquo": '\U000000BB', + "reg": '\U000000AE', + "sect": '\U000000A7', + "shy": '\U000000AD', + "sup1": '\U000000B9', + "sup2": '\U000000B2', + "sup3": '\U000000B3', + "szlig": '\U000000DF', + "thorn": '\U000000FE', + "times": '\U000000D7', + "uacute": '\U000000FA', + "ucirc": '\U000000FB', + "ugrave": '\U000000F9', + "uml": '\U000000A8', + "uuml": '\U000000FC', + "yacute": '\U000000FD', + "yen": '\U000000A5', + "yuml": '\U000000FF', } // HTML entities that are two unicode codepoints. diff --git a/vendor/golang.org/x/net/html/entity_test.go b/vendor/golang.org/x/net/html/entity_test.go deleted file mode 100644 index b53f866fa2..0000000000 --- a/vendor/golang.org/x/net/html/entity_test.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2010 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 html - -import ( - "testing" - "unicode/utf8" -) - -func TestEntityLength(t *testing.T) { - // We verify that the length of UTF-8 encoding of each value is <= 1 + len(key). - // The +1 comes from the leading "&". This property implies that the length of - // unescaped text is <= the length of escaped text. - for k, v := range entity { - if 1+len(k) < utf8.RuneLen(v) { - t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v)) - } - if len(k) > longestEntityWithoutSemicolon && k[len(k)-1] != ';' { - t.Errorf("entity name %s is %d characters, but longestEntityWithoutSemicolon=%d", k, len(k), longestEntityWithoutSemicolon) - } - } - for k, v := range entity2 { - if 1+len(k) < utf8.RuneLen(v[0])+utf8.RuneLen(v[1]) { - t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v[0]) + string(v[1])) - } - } -} diff --git a/vendor/golang.org/x/net/html/escape_test.go b/vendor/golang.org/x/net/html/escape_test.go deleted file mode 100644 index b405d4b4a7..0000000000 --- a/vendor/golang.org/x/net/html/escape_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2013 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 html - -import "testing" - -type unescapeTest struct { - // A short description of the test case. - desc string - // The HTML text. - html string - // The unescaped text. - unescaped string -} - -var unescapeTests = []unescapeTest{ - // Handle no entities. - { - "copy", - "A\ttext\nstring", - "A\ttext\nstring", - }, - // Handle simple named entities. - { - "simple", - "& > <", - "& > <", - }, - // Handle hitting the end of the string. - { - "stringEnd", - "& &", - "& &", - }, - // Handle entities with two codepoints. - { - "multiCodepoint", - "text ⋛︀ blah", - "text \u22db\ufe00 blah", - }, - // Handle decimal numeric entities. - { - "decimalEntity", - "Delta = Δ ", - "Delta = Δ ", - }, - // Handle hexadecimal numeric entities. - { - "hexadecimalEntity", - "Lambda = λ = λ ", - "Lambda = λ = λ ", - }, - // Handle numeric early termination. - { - "numericEnds", - "&# &#x €43 © = ©f = ©", - "&# &#x €43 © = ©f = ©", - }, - // Handle numeric ISO-8859-1 entity replacements. - { - "numericReplacements", - "Footnote‡", - "Footnote‡", - }, -} - -func TestUnescape(t *testing.T) { - for _, tt := range unescapeTests { - unescaped := UnescapeString(tt.html) - if unescaped != tt.unescaped { - t.Errorf("TestUnescape %s: want %q, got %q", tt.desc, tt.unescaped, unescaped) - } - } -} - -func TestUnescapeEscape(t *testing.T) { - ss := []string{ - ``, - `abc def`, - `a & b`, - `a&b`, - `a & b`, - `"`, - `"`, - `"<&>"`, - `"<&>"`, - `3&5==1 && 0<1, "0<1", a+acute=á`, - `The special characters are: <, >, &, ' and "`, - } - for _, s := range ss { - if got := UnescapeString(EscapeString(s)); got != s { - t.Errorf("got %q want %q", got, s) - } - } -} diff --git a/vendor/golang.org/x/net/html/example_test.go b/vendor/golang.org/x/net/html/example_test.go deleted file mode 100644 index 0b06ed7730..0000000000 --- a/vendor/golang.org/x/net/html/example_test.go +++ /dev/null @@ -1,40 +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. - -// This example demonstrates parsing HTML data and walking the resulting tree. -package html_test - -import ( - "fmt" - "log" - "strings" - - "golang.org/x/net/html" -) - -func ExampleParse() { - s := `

Links:

` - doc, err := html.Parse(strings.NewReader(s)) - if err != nil { - log.Fatal(err) - } - var f func(*html.Node) - f = func(n *html.Node) { - if n.Type == html.ElementNode && n.Data == "a" { - for _, a := range n.Attr { - if a.Key == "href" { - fmt.Println(a.Val) - break - } - } - } - for c := n.FirstChild; c != nil; c = c.NextSibling { - f(c) - } - } - f(doc) - // Output: - // foo - // /bar/baz -} diff --git a/vendor/golang.org/x/net/html/foreign.go b/vendor/golang.org/x/net/html/foreign.go index d3b3844099..01477a9639 100644 --- a/vendor/golang.org/x/net/html/foreign.go +++ b/vendor/golang.org/x/net/html/foreign.go @@ -67,7 +67,7 @@ func mathMLTextIntegrationPoint(n *Node) bool { return false } -// Section 12.2.5.5. +// Section 12.2.6.5. var breakout = map[string]bool{ "b": true, "big": true, @@ -115,7 +115,7 @@ var breakout = map[string]bool{ "var": true, } -// Section 12.2.5.5. +// Section 12.2.6.5. var svgTagNameAdjustments = map[string]string{ "altglyph": "altGlyph", "altglyphdef": "altGlyphDef", @@ -155,7 +155,7 @@ var svgTagNameAdjustments = map[string]string{ "textpath": "textPath", } -// Section 12.2.5.1 +// Section 12.2.6.1 var mathMLAttributeAdjustments = map[string]string{ "definitionurl": "definitionURL", } diff --git a/vendor/golang.org/x/net/html/node.go b/vendor/golang.org/x/net/html/node.go index 26b657aec8..2c1cade607 100644 --- a/vendor/golang.org/x/net/html/node.go +++ b/vendor/golang.org/x/net/html/node.go @@ -21,9 +21,10 @@ const ( scopeMarkerNode ) -// Section 12.2.3.3 says "scope markers are inserted when entering applet -// elements, buttons, object elements, marquees, table cells, and table -// captions, and are used to prevent formatting from 'leaking'". +// Section 12.2.4.3 says "The markers are inserted when entering applet, +// object, marquee, template, td, th, and caption elements, and are used +// to prevent formatting from "leaking" into applet, object, marquee, +// template, td, th, and caption elements". var scopeMarker = Node{Type: scopeMarkerNode} // A Node consists of a NodeType and some Data (tag name for element nodes, @@ -173,6 +174,16 @@ func (s *nodeStack) index(n *Node) int { return -1 } +// contains returns whether a is within s. +func (s *nodeStack) contains(a atom.Atom) bool { + for _, n := range *s { + if n.DataAtom == a { + return true + } + } + return false +} + // insert inserts a node at the given index. func (s *nodeStack) insert(i int, n *Node) { (*s) = append(*s, nil) @@ -191,3 +202,19 @@ func (s *nodeStack) remove(n *Node) { (*s)[j] = nil *s = (*s)[:j] } + +type insertionModeStack []insertionMode + +func (s *insertionModeStack) pop() (im insertionMode) { + i := len(*s) + im = (*s)[i-1] + *s = (*s)[:i-1] + return im +} + +func (s *insertionModeStack) top() insertionMode { + if i := len(*s); i > 0 { + return (*s)[i-1] + } + return nil +} diff --git a/vendor/golang.org/x/net/html/node_test.go b/vendor/golang.org/x/net/html/node_test.go deleted file mode 100644 index 471102f3a2..0000000000 --- a/vendor/golang.org/x/net/html/node_test.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2010 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 html - -import ( - "fmt" -) - -// checkTreeConsistency checks that a node and its descendants are all -// consistent in their parent/child/sibling relationships. -func checkTreeConsistency(n *Node) error { - return checkTreeConsistency1(n, 0) -} - -func checkTreeConsistency1(n *Node, depth int) error { - if depth == 1e4 { - return fmt.Errorf("html: tree looks like it contains a cycle") - } - if err := checkNodeConsistency(n); err != nil { - return err - } - for c := n.FirstChild; c != nil; c = c.NextSibling { - if err := checkTreeConsistency1(c, depth+1); err != nil { - return err - } - } - return nil -} - -// checkNodeConsistency checks that a node's parent/child/sibling relationships -// are consistent. -func checkNodeConsistency(n *Node) error { - if n == nil { - return nil - } - - nParent := 0 - for p := n.Parent; p != nil; p = p.Parent { - nParent++ - if nParent == 1e4 { - return fmt.Errorf("html: parent list looks like an infinite loop") - } - } - - nForward := 0 - for c := n.FirstChild; c != nil; c = c.NextSibling { - nForward++ - if nForward == 1e6 { - return fmt.Errorf("html: forward list of children looks like an infinite loop") - } - if c.Parent != n { - return fmt.Errorf("html: inconsistent child/parent relationship") - } - } - - nBackward := 0 - for c := n.LastChild; c != nil; c = c.PrevSibling { - nBackward++ - if nBackward == 1e6 { - return fmt.Errorf("html: backward list of children looks like an infinite loop") - } - if c.Parent != n { - return fmt.Errorf("html: inconsistent child/parent relationship") - } - } - - if n.Parent != nil { - if n.Parent == n { - return fmt.Errorf("html: inconsistent parent relationship") - } - if n.Parent == n.FirstChild { - return fmt.Errorf("html: inconsistent parent/first relationship") - } - if n.Parent == n.LastChild { - return fmt.Errorf("html: inconsistent parent/last relationship") - } - if n.Parent == n.PrevSibling { - return fmt.Errorf("html: inconsistent parent/prev relationship") - } - if n.Parent == n.NextSibling { - return fmt.Errorf("html: inconsistent parent/next relationship") - } - - parentHasNAsAChild := false - for c := n.Parent.FirstChild; c != nil; c = c.NextSibling { - if c == n { - parentHasNAsAChild = true - break - } - } - if !parentHasNAsAChild { - return fmt.Errorf("html: inconsistent parent/child relationship") - } - } - - if n.PrevSibling != nil && n.PrevSibling.NextSibling != n { - return fmt.Errorf("html: inconsistent prev/next relationship") - } - if n.NextSibling != nil && n.NextSibling.PrevSibling != n { - return fmt.Errorf("html: inconsistent next/prev relationship") - } - - if (n.FirstChild == nil) != (n.LastChild == nil) { - return fmt.Errorf("html: inconsistent first/last relationship") - } - if n.FirstChild != nil && n.FirstChild == n.LastChild { - // We have a sole child. - if n.FirstChild.PrevSibling != nil || n.FirstChild.NextSibling != nil { - return fmt.Errorf("html: inconsistent sole child's sibling relationship") - } - } - - seen := map[*Node]bool{} - - var last *Node - for c := n.FirstChild; c != nil; c = c.NextSibling { - if seen[c] { - return fmt.Errorf("html: inconsistent repeated child") - } - seen[c] = true - last = c - } - if last != n.LastChild { - return fmt.Errorf("html: inconsistent last relationship") - } - - var first *Node - for c := n.LastChild; c != nil; c = c.PrevSibling { - if !seen[c] { - return fmt.Errorf("html: inconsistent missing child") - } - delete(seen, c) - first = c - } - if first != n.FirstChild { - return fmt.Errorf("html: inconsistent first relationship") - } - - if len(seen) != 0 { - return fmt.Errorf("html: inconsistent forwards/backwards child list") - } - - return nil -} diff --git a/vendor/golang.org/x/net/html/parse.go b/vendor/golang.org/x/net/html/parse.go index be4b2bf5aa..d23e05e064 100644 --- a/vendor/golang.org/x/net/html/parse.go +++ b/vendor/golang.org/x/net/html/parse.go @@ -25,20 +25,22 @@ type parser struct { hasSelfClosingToken bool // doc is the document root element. doc *Node - // The stack of open elements (section 12.2.3.2) and active formatting - // elements (section 12.2.3.3). + // The stack of open elements (section 12.2.4.2) and active formatting + // elements (section 12.2.4.3). oe, afe nodeStack - // Element pointers (section 12.2.3.4). + // Element pointers (section 12.2.4.4). head, form *Node - // Other parsing state flags (section 12.2.3.5). + // Other parsing state flags (section 12.2.4.5). scripting, framesetOK bool + // The stack of template insertion modes + templateStack insertionModeStack // im is the current insertion mode. im insertionMode // originalIM is the insertion mode to go back to after completing a text // or inTableText insertion mode. originalIM insertionMode // fosterParenting is whether new elements should be inserted according to - // the foster parenting rules (section 12.2.5.3). + // the foster parenting rules (section 12.2.6.1). fosterParenting bool // quirks is whether the parser is operating in "quirks mode." quirks bool @@ -56,7 +58,7 @@ func (p *parser) top() *Node { return p.doc } -// Stop tags for use in popUntil. These come from section 12.2.3.2. +// Stop tags for use in popUntil. These come from section 12.2.4.2. var ( defaultScopeStopTags = map[string][]a.Atom{ "": {a.Applet, a.Caption, a.Html, a.Table, a.Td, a.Th, a.Marquee, a.Object, a.Template}, @@ -79,7 +81,7 @@ const ( // popUntil pops the stack of open elements at the highest element whose tag // is in matchTags, provided there is no higher element in the scope's stop -// tags (as defined in section 12.2.3.2). It returns whether or not there was +// tags (as defined in section 12.2.4.2). It returns whether or not there was // such an element. If there was not, popUntil leaves the stack unchanged. // // For example, the set of stop tags for table scope is: "html", "table". If @@ -126,7 +128,7 @@ func (p *parser) indexOfElementInScope(s scope, matchTags ...a.Atom) int { return -1 } case tableScope: - if tagAtom == a.Html || tagAtom == a.Table { + if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template { return -1 } case selectScope: @@ -162,17 +164,17 @@ func (p *parser) clearStackToContext(s scope) { tagAtom := p.oe[i].DataAtom switch s { case tableScope: - if tagAtom == a.Html || tagAtom == a.Table { + if tagAtom == a.Html || tagAtom == a.Table || tagAtom == a.Template { p.oe = p.oe[:i+1] return } case tableRowScope: - if tagAtom == a.Html || tagAtom == a.Tr { + if tagAtom == a.Html || tagAtom == a.Tr || tagAtom == a.Template { p.oe = p.oe[:i+1] return } case tableBodyScope: - if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead { + if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead || tagAtom == a.Template { p.oe = p.oe[:i+1] return } @@ -183,7 +185,7 @@ func (p *parser) clearStackToContext(s scope) { } // generateImpliedEndTags pops nodes off the stack of open elements as long as -// the top node has a tag name of dd, dt, li, option, optgroup, p, rp, or rt. +// the top node has a tag name of dd, dt, li, optgroup, option, p, rb, rp, rt or rtc. // If exceptions are specified, nodes with that name will not be popped off. func (p *parser) generateImpliedEndTags(exceptions ...string) { var i int @@ -192,7 +194,7 @@ loop: n := p.oe[i] if n.Type == ElementNode { switch n.DataAtom { - case a.Dd, a.Dt, a.Li, a.Option, a.Optgroup, a.P, a.Rp, a.Rt: + case a.Dd, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, a.Rp, a.Rt, a.Rtc: for _, except := range exceptions { if n.Data == except { break loop @@ -207,6 +209,27 @@ loop: p.oe = p.oe[:i+1] } +// generateAllImpliedEndTags pops nodes off the stack of open elements as long as +// the top node has a tag name of caption, colgroup, dd, div, dt, li, optgroup, option, p, rb, +// rp, rt, rtc, span, tbody, td, tfoot, th, thead or tr. +func (p *parser) generateAllImpliedEndTags() { + var i int + for i = len(p.oe) - 1; i >= 0; i-- { + n := p.oe[i] + if n.Type == ElementNode { + switch n.DataAtom { + // TODO: remove this divergence from the HTML5 spec + case a.Caption, a.Colgroup, a.Dd, a.Div, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, + a.Rp, a.Rt, a.Rtc, a.Span, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr: + continue + } + } + break + } + + p.oe = p.oe[:i+1] +} + // addChild adds a child node n to the top element, and pushes n onto the stack // of open elements if it is an element node. func (p *parser) addChild(n *Node) { @@ -234,9 +257,9 @@ func (p *parser) shouldFosterParent() bool { } // fosterParent adds a child node according to the foster parenting rules. -// Section 12.2.5.3, "foster parenting". +// Section 12.2.6.1, "foster parenting". func (p *parser) fosterParent(n *Node) { - var table, parent, prev *Node + var table, parent, prev, template *Node var i int for i = len(p.oe) - 1; i >= 0; i-- { if p.oe[i].DataAtom == a.Table { @@ -245,6 +268,19 @@ func (p *parser) fosterParent(n *Node) { } } + var j int + for j = len(p.oe) - 1; j >= 0; j-- { + if p.oe[j].DataAtom == a.Template { + template = p.oe[j] + break + } + } + + if template != nil && (table == nil || j < i) { + template.AppendChild(n) + return + } + if table == nil { // The foster parent is the html element. parent = p.oe[0] @@ -304,7 +340,7 @@ func (p *parser) addElement() { }) } -// Section 12.2.3.3. +// Section 12.2.4.3. func (p *parser) addFormattingElement() { tagAtom, attr := p.tok.DataAtom, p.tok.Attr p.addElement() @@ -351,7 +387,7 @@ findIdenticalElements: p.afe = append(p.afe, p.top()) } -// Section 12.2.3.3. +// Section 12.2.4.3. func (p *parser) clearActiveFormattingElements() { for { n := p.afe.pop() @@ -361,7 +397,7 @@ func (p *parser) clearActiveFormattingElements() { } } -// Section 12.2.3.3. +// Section 12.2.4.3. func (p *parser) reconstructActiveFormattingElements() { n := p.afe.top() if n == nil { @@ -390,12 +426,12 @@ func (p *parser) reconstructActiveFormattingElements() { } } -// Section 12.2.4. +// Section 12.2.5. func (p *parser) acknowledgeSelfClosingTag() { p.hasSelfClosingToken = false } -// An insertion mode (section 12.2.3.1) is the state transition function from +// An insertion mode (section 12.2.4.1) is the state transition function from // a particular state in the HTML5 parser's state machine. It updates the // parser's fields depending on parser.tok (where ErrorToken means EOF). // It returns whether the token was consumed. @@ -403,7 +439,7 @@ type insertionMode func(*parser) bool // setOriginalIM sets the insertion mode to return to after completing a text or // inTableText insertion mode. -// Section 12.2.3.1, "using the rules for". +// Section 12.2.4.1, "using the rules for". func (p *parser) setOriginalIM() { if p.originalIM != nil { panic("html: bad parser state: originalIM was set twice") @@ -411,18 +447,38 @@ func (p *parser) setOriginalIM() { p.originalIM = p.im } -// Section 12.2.3.1, "reset the insertion mode". +// Section 12.2.4.1, "reset the insertion mode". func (p *parser) resetInsertionMode() { for i := len(p.oe) - 1; i >= 0; i-- { n := p.oe[i] - if i == 0 && p.context != nil { + last := i == 0 + if last && p.context != nil { n = p.context } switch n.DataAtom { case a.Select: + if !last { + for ancestor, first := n, p.oe[0]; ancestor != first; { + if ancestor == first { + break + } + ancestor = p.oe[p.oe.index(ancestor)-1] + switch ancestor.DataAtom { + case a.Template: + p.im = inSelectIM + return + case a.Table: + p.im = inSelectInTableIM + return + } + } + } p.im = inSelectIM case a.Td, a.Th: + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 p.im = inCellIM case a.Tr: p.im = inRowIM @@ -434,25 +490,37 @@ func (p *parser) resetInsertionMode() { p.im = inColumnGroupIM case a.Table: p.im = inTableIM + case a.Template: + p.im = p.templateStack.top() case a.Head: - p.im = inBodyIM + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 + p.im = inHeadIM case a.Body: p.im = inBodyIM case a.Frameset: p.im = inFramesetIM case a.Html: - p.im = beforeHeadIM + if p.head == nil { + p.im = beforeHeadIM + } else { + p.im = afterHeadIM + } default: + if last { + p.im = inBodyIM + return + } continue } return } - p.im = inBodyIM } const whitespace = " \t\r\n\f" -// Section 12.2.5.4.1. +// Section 12.2.6.4.1. func initialIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -479,7 +547,7 @@ func initialIM(p *parser) bool { return false } -// Section 12.2.5.4.2. +// Section 12.2.6.4.2. func beforeHTMLIM(p *parser) bool { switch p.tok.Type { case DoctypeToken: @@ -517,7 +585,7 @@ func beforeHTMLIM(p *parser) bool { return false } -// Section 12.2.5.4.3. +// Section 12.2.6.4.3. func beforeHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -560,7 +628,7 @@ func beforeHeadIM(p *parser) bool { return false } -// Section 12.2.5.4.4. +// Section 12.2.6.4.4. func inHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -590,19 +658,36 @@ func inHeadIM(p *parser) bool { case a.Head: // Ignore the token. return true + case a.Template: + p.addElement() + p.afe = append(p.afe, &scopeMarker) + p.framesetOK = false + p.im = inTemplateIM + p.templateStack = append(p.templateStack, inTemplateIM) + return true } case EndTagToken: switch p.tok.DataAtom { case a.Head: - n := p.oe.pop() - if n.DataAtom != a.Head { - panic("html: bad parser state: element not found, in the in-head insertion mode") - } + p.oe.pop() p.im = afterHeadIM return true case a.Body, a.Html, a.Br: p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) return false + case a.Template: + if !p.oe.contains(a.Template) { + return true + } + p.generateAllImpliedEndTags() + if n := p.oe.top(); n.DataAtom != a.Template { + return true + } + p.popUntil(defaultScope, a.Template) + p.clearActiveFormattingElements() + p.templateStack.pop() + p.resetInsertionMode() + return true default: // Ignore the token. return true @@ -622,7 +707,7 @@ func inHeadIM(p *parser) bool { return false } -// Section 12.2.5.4.6. +// Section 12.2.6.4.6. func afterHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -648,7 +733,7 @@ func afterHeadIM(p *parser) bool { p.addElement() p.im = inFramesetIM return true - case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Title: + case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title: p.oe = append(p.oe, p.head) defer p.oe.remove(p.head) return inHeadIM(p) @@ -660,6 +745,8 @@ func afterHeadIM(p *parser) bool { switch p.tok.DataAtom { case a.Body, a.Html, a.Br: // Drop down to creating an implied tag. + case a.Template: + return inHeadIM(p) default: // Ignore the token. return true @@ -697,7 +784,7 @@ func copyAttributes(dst *Node, src Token) { } } -// Section 12.2.5.4.7. +// Section 12.2.6.4.7. func inBodyIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -727,10 +814,16 @@ func inBodyIM(p *parser) bool { case StartTagToken: switch p.tok.DataAtom { case a.Html: + if p.oe.contains(a.Template) { + return true + } copyAttributes(p.oe[0], p.tok) - case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Title: + case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title: return inHeadIM(p) case a.Body: + if p.oe.contains(a.Template) { + return true + } if len(p.oe) >= 2 { body := p.oe[1] if body.Type == ElementNode && body.DataAtom == a.Body { @@ -767,7 +860,7 @@ func inBodyIM(p *parser) bool { // The newline, if any, will be dealt with by the TextToken case. p.framesetOK = false case a.Form: - if p.form == nil { + if p.oe.contains(a.Template) || p.form == nil { p.popUntil(buttonScope, a.P) p.addElement() p.form = p.top() @@ -952,11 +1045,16 @@ func inBodyIM(p *parser) bool { } p.reconstructActiveFormattingElements() p.addElement() - case a.Rp, a.Rt: + case a.Rb, a.Rtc: if p.elementInScope(defaultScope, a.Ruby) { p.generateImpliedEndTags() } p.addElement() + case a.Rp, a.Rt: + if p.elementInScope(defaultScope, a.Ruby) { + p.generateImpliedEndTags("rtc") + } + p.addElement() case a.Math, a.Svg: p.reconstructActiveFormattingElements() if p.tok.DataAtom == a.Math { @@ -972,7 +1070,13 @@ func inBodyIM(p *parser) bool { p.acknowledgeSelfClosingTag() } return true - case a.Caption, a.Col, a.Colgroup, a.Frame, a.Head, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr: + case a.Frame: + // TODO: remove this divergence from the HTML5 spec. + if p.oe.contains(a.Template) { + p.addElement() + return true + } + case a.Caption, a.Col, a.Colgroup, a.Head, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr: // Ignore the token. default: p.reconstructActiveFormattingElements() @@ -993,15 +1097,28 @@ func inBodyIM(p *parser) bool { case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Menu, a.Nav, a.Ol, a.Pre, a.Section, a.Summary, a.Ul: p.popUntil(defaultScope, p.tok.DataAtom) case a.Form: - node := p.form - p.form = nil - i := p.indexOfElementInScope(defaultScope, a.Form) - if node == nil || i == -1 || p.oe[i] != node { - // Ignore the token. - return true + if p.oe.contains(a.Template) { + if !p.oe.contains(a.Form) { + // Ignore the token. + return true + } + p.generateImpliedEndTags() + if p.tok.DataAtom == a.Form { + // Ignore the token. + return true + } + p.popUntil(defaultScope, a.Form) + } else { + node := p.form + p.form = nil + i := p.indexOfElementInScope(defaultScope, a.Form) + if node == nil || i == -1 || p.oe[i] != node { + // Ignore the token. + return true + } + p.generateImpliedEndTags() + p.oe.remove(node) } - p.generateImpliedEndTags() - p.oe.remove(node) case a.P: if !p.elementInScope(buttonScope, a.P) { p.parseImpliedToken(StartTagToken, a.P, a.P.String()) @@ -1022,6 +1139,8 @@ func inBodyIM(p *parser) bool { case a.Br: p.tok.Type = StartTagToken return false + case a.Template: + return inHeadIM(p) default: p.inBodyEndTagOther(p.tok.DataAtom) } @@ -1030,6 +1149,21 @@ func inBodyIM(p *parser) bool { Type: CommentNode, Data: p.tok.Data, }) + case ErrorToken: + // TODO: remove this divergence from the HTML5 spec. + if len(p.templateStack) > 0 { + p.im = inTemplateIM + return false + } else { + for _, e := range p.oe { + switch e.DataAtom { + case a.Dd, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, a.Rp, a.Rt, a.Rtc, a.Tbody, a.Td, a.Tfoot, a.Th, + a.Thead, a.Tr, a.Body, a.Html: + default: + return true + } + } + } } return true @@ -1135,6 +1269,12 @@ func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) { switch commonAncestor.DataAtom { case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: p.fosterParent(lastNode) + case a.Template: + // TODO: remove namespace checking + if commonAncestor.Namespace == "html" { + commonAncestor = commonAncestor.LastChild + } + fallthrough default: commonAncestor.AppendChild(lastNode) } @@ -1160,7 +1300,7 @@ func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) { } // inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM. -// "Any other end tag" handling from 12.2.5.5 The rules for parsing tokens in foreign content +// "Any other end tag" handling from 12.2.6.5 The rules for parsing tokens in foreign content // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign func (p *parser) inBodyEndTagOther(tagAtom a.Atom) { for i := len(p.oe) - 1; i >= 0; i-- { @@ -1174,7 +1314,7 @@ func (p *parser) inBodyEndTagOther(tagAtom a.Atom) { } } -// Section 12.2.5.4.8. +// Section 12.2.6.4.8. func textIM(p *parser) bool { switch p.tok.Type { case ErrorToken: @@ -1203,7 +1343,7 @@ func textIM(p *parser) bool { return p.tok.Type == EndTagToken } -// Section 12.2.5.4.9. +// Section 12.2.6.4.9. func inTableIM(p *parser) bool { switch p.tok.Type { case ErrorToken: @@ -1249,7 +1389,7 @@ func inTableIM(p *parser) bool { } // Ignore the token. return true - case a.Style, a.Script: + case a.Style, a.Script, a.Template: return inHeadIM(p) case a.Input: for _, t := range p.tok.Attr { @@ -1261,7 +1401,7 @@ func inTableIM(p *parser) bool { } // Otherwise drop down to the default action. case a.Form: - if p.form != nil { + if p.oe.contains(a.Template) || p.form != nil { // Ignore the token. return true } @@ -1291,6 +1431,8 @@ func inTableIM(p *parser) bool { case a.Body, a.Caption, a.Col, a.Colgroup, a.Html, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr: // Ignore the token. return true + case a.Template: + return inHeadIM(p) } case CommentToken: p.addChild(&Node{ @@ -1309,7 +1451,7 @@ func inTableIM(p *parser) bool { return inBodyIM(p) } -// Section 12.2.5.4.11. +// Section 12.2.6.4.11. func inCaptionIM(p *parser) bool { switch p.tok.Type { case StartTagToken: @@ -1355,7 +1497,7 @@ func inCaptionIM(p *parser) bool { return inBodyIM(p) } -// Section 12.2.5.4.12. +// Section 12.2.6.4.12. func inColumnGroupIM(p *parser) bool { switch p.tok.Type { case TextToken: @@ -1386,11 +1528,13 @@ func inColumnGroupIM(p *parser) bool { p.oe.pop() p.acknowledgeSelfClosingTag() return true + case a.Template: + return inHeadIM(p) } case EndTagToken: switch p.tok.DataAtom { case a.Colgroup: - if p.oe.top().DataAtom != a.Html { + if p.oe.top().DataAtom == a.Colgroup { p.oe.pop() p.im = inTableIM } @@ -1398,17 +1542,19 @@ func inColumnGroupIM(p *parser) bool { case a.Col: // Ignore the token. return true + case a.Template: + return inHeadIM(p) } } - if p.oe.top().DataAtom != a.Html { - p.oe.pop() - p.im = inTableIM - return false + if p.oe.top().DataAtom != a.Colgroup { + return true } - return true + p.oe.pop() + p.im = inTableIM + return false } -// Section 12.2.5.4.13. +// Section 12.2.6.4.13. func inTableBodyIM(p *parser) bool { switch p.tok.Type { case StartTagToken: @@ -1460,7 +1606,7 @@ func inTableBodyIM(p *parser) bool { return inTableIM(p) } -// Section 12.2.5.4.14. +// Section 12.2.6.4.14. func inRowIM(p *parser) bool { switch p.tok.Type { case StartTagToken: @@ -1511,7 +1657,7 @@ func inRowIM(p *parser) bool { return inTableIM(p) } -// Section 12.2.5.4.15. +// Section 12.2.6.4.15. func inCellIM(p *parser) bool { switch p.tok.Type { case StartTagToken: @@ -1560,7 +1706,7 @@ func inCellIM(p *parser) bool { return inBodyIM(p) } -// Section 12.2.5.4.16. +// Section 12.2.6.4.16. func inSelectIM(p *parser) bool { switch p.tok.Type { case ErrorToken: @@ -1597,7 +1743,7 @@ func inSelectIM(p *parser) bool { p.tokenizer.NextIsNotRawText() // Ignore the token. return true - case a.Script: + case a.Script, a.Template: return inHeadIM(p) } case EndTagToken: @@ -1618,6 +1764,8 @@ func inSelectIM(p *parser) bool { if p.popUntil(selectScope, a.Select) { p.resetInsertionMode() } + case a.Template: + return inHeadIM(p) } case CommentToken: p.addChild(&Node{ @@ -1632,7 +1780,7 @@ func inSelectIM(p *parser) bool { return true } -// Section 12.2.5.4.17. +// Section 12.2.6.4.17. func inSelectInTableIM(p *parser) bool { switch p.tok.Type { case StartTagToken, EndTagToken: @@ -1650,7 +1798,62 @@ func inSelectInTableIM(p *parser) bool { return inSelectIM(p) } -// Section 12.2.5.4.18. +// Section 12.2.6.4.18. +func inTemplateIM(p *parser) bool { + switch p.tok.Type { + case TextToken, CommentToken, DoctypeToken: + return inBodyIM(p) + case StartTagToken: + switch p.tok.DataAtom { + case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Template, a.Title: + return inHeadIM(p) + case a.Caption, a.Colgroup, a.Tbody, a.Tfoot, a.Thead: + p.templateStack.pop() + p.templateStack = append(p.templateStack, inTableIM) + p.im = inTableIM + return false + case a.Col: + p.templateStack.pop() + p.templateStack = append(p.templateStack, inColumnGroupIM) + p.im = inColumnGroupIM + return false + case a.Tr: + p.templateStack.pop() + p.templateStack = append(p.templateStack, inTableBodyIM) + p.im = inTableBodyIM + return false + case a.Td, a.Th: + p.templateStack.pop() + p.templateStack = append(p.templateStack, inRowIM) + p.im = inRowIM + return false + default: + p.templateStack.pop() + p.templateStack = append(p.templateStack, inBodyIM) + p.im = inBodyIM + return false + } + case EndTagToken: + switch p.tok.DataAtom { + case a.Template: + return inHeadIM(p) + default: + // Ignore the token. + return true + } + } + if !p.oe.contains(a.Template) { + // Ignore the token. + return true + } + p.popUntil(defaultScope, a.Template) + p.clearActiveFormattingElements() + p.templateStack.pop() + p.resetInsertionMode() + return false +} + +// Section 12.2.6.4.19. func afterBodyIM(p *parser) bool { switch p.tok.Type { case ErrorToken: @@ -1688,7 +1891,7 @@ func afterBodyIM(p *parser) bool { return false } -// Section 12.2.5.4.19. +// Section 12.2.6.4.20. func inFramesetIM(p *parser) bool { switch p.tok.Type { case CommentToken: @@ -1720,6 +1923,11 @@ func inFramesetIM(p *parser) bool { p.acknowledgeSelfClosingTag() case a.Noframes: return inHeadIM(p) + case a.Template: + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 + return inTemplateIM(p) } case EndTagToken: switch p.tok.DataAtom { @@ -1738,7 +1946,7 @@ func inFramesetIM(p *parser) bool { return true } -// Section 12.2.5.4.20. +// Section 12.2.6.4.21. func afterFramesetIM(p *parser) bool { switch p.tok.Type { case CommentToken: @@ -1777,7 +1985,7 @@ func afterFramesetIM(p *parser) bool { return true } -// Section 12.2.5.4.21. +// Section 12.2.6.4.22. func afterAfterBodyIM(p *parser) bool { switch p.tok.Type { case ErrorToken: @@ -1806,7 +2014,7 @@ func afterAfterBodyIM(p *parser) bool { return false } -// Section 12.2.5.4.22. +// Section 12.2.6.4.23. func afterAfterFramesetIM(p *parser) bool { switch p.tok.Type { case CommentToken: @@ -1844,7 +2052,7 @@ func afterAfterFramesetIM(p *parser) bool { const whitespaceOrNUL = whitespace + "\x00" -// Section 12.2.5.5. +// Section 12.2.6.5 func parseForeignContent(p *parser) bool { switch p.tok.Type { case TextToken: @@ -1924,7 +2132,7 @@ func parseForeignContent(p *parser) bool { return true } -// Section 12.2.5. +// Section 12.2.6. func (p *parser) inForeignContent() bool { if len(p.oe) == 0 { return false @@ -2064,6 +2272,9 @@ func ParseFragment(r io.Reader, context *Node) ([]*Node, error) { } p.doc.AppendChild(root) p.oe = nodeStack{root} + if context != nil && context.DataAtom == a.Template { + p.templateStack = append(p.templateStack, inTemplateIM) + } p.resetInsertionMode() for n := context; n != nil; n = n.Parent { diff --git a/vendor/golang.org/x/net/html/parse_test.go b/vendor/golang.org/x/net/html/parse_test.go deleted file mode 100644 index 7e47d11be8..0000000000 --- a/vendor/golang.org/x/net/html/parse_test.go +++ /dev/null @@ -1,388 +0,0 @@ -// Copyright 2010 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 html - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "runtime" - "sort" - "strings" - "testing" - - "golang.org/x/net/html/atom" -) - -// readParseTest reads a single test case from r. -func readParseTest(r *bufio.Reader) (text, want, context string, err error) { - line, err := r.ReadSlice('\n') - if err != nil { - return "", "", "", err - } - var b []byte - - // Read the HTML. - if string(line) != "#data\n" { - return "", "", "", fmt.Errorf(`got %q want "#data\n"`, line) - } - for { - line, err = r.ReadSlice('\n') - if err != nil { - return "", "", "", err - } - if line[0] == '#' { - break - } - b = append(b, line...) - } - text = strings.TrimSuffix(string(b), "\n") - b = b[:0] - - // Skip the error list. - if string(line) != "#errors\n" { - return "", "", "", fmt.Errorf(`got %q want "#errors\n"`, line) - } - for { - line, err = r.ReadSlice('\n') - if err != nil { - return "", "", "", err - } - if line[0] == '#' { - break - } - } - - if string(line) == "#document-fragment\n" { - line, err = r.ReadSlice('\n') - if err != nil { - return "", "", "", err - } - context = strings.TrimSpace(string(line)) - line, err = r.ReadSlice('\n') - if err != nil { - return "", "", "", err - } - } - - // Read the dump of what the parse tree should be. - if string(line) != "#document\n" { - return "", "", "", fmt.Errorf(`got %q want "#document\n"`, line) - } - inQuote := false - for { - line, err = r.ReadSlice('\n') - if err != nil && err != io.EOF { - return "", "", "", err - } - trimmed := bytes.Trim(line, "| \n") - if len(trimmed) > 0 { - if line[0] == '|' && trimmed[0] == '"' { - inQuote = true - } - if trimmed[len(trimmed)-1] == '"' && !(line[0] == '|' && len(trimmed) == 1) { - inQuote = false - } - } - if len(line) == 0 || len(line) == 1 && line[0] == '\n' && !inQuote { - break - } - b = append(b, line...) - } - return text, string(b), context, nil -} - -func dumpIndent(w io.Writer, level int) { - io.WriteString(w, "| ") - for i := 0; i < level; i++ { - io.WriteString(w, " ") - } -} - -type sortedAttributes []Attribute - -func (a sortedAttributes) Len() int { - return len(a) -} - -func (a sortedAttributes) Less(i, j int) bool { - if a[i].Namespace != a[j].Namespace { - return a[i].Namespace < a[j].Namespace - } - return a[i].Key < a[j].Key -} - -func (a sortedAttributes) Swap(i, j int) { - a[i], a[j] = a[j], a[i] -} - -func dumpLevel(w io.Writer, n *Node, level int) error { - dumpIndent(w, level) - switch n.Type { - case ErrorNode: - return errors.New("unexpected ErrorNode") - case DocumentNode: - return errors.New("unexpected DocumentNode") - case ElementNode: - if n.Namespace != "" { - fmt.Fprintf(w, "<%s %s>", n.Namespace, n.Data) - } else { - fmt.Fprintf(w, "<%s>", n.Data) - } - attr := sortedAttributes(n.Attr) - sort.Sort(attr) - for _, a := range attr { - io.WriteString(w, "\n") - dumpIndent(w, level+1) - if a.Namespace != "" { - fmt.Fprintf(w, `%s %s="%s"`, a.Namespace, a.Key, a.Val) - } else { - fmt.Fprintf(w, `%s="%s"`, a.Key, a.Val) - } - } - case TextNode: - fmt.Fprintf(w, `"%s"`, n.Data) - case CommentNode: - fmt.Fprintf(w, "", n.Data) - case DoctypeNode: - fmt.Fprintf(w, "") - case scopeMarkerNode: - return errors.New("unexpected scopeMarkerNode") - default: - return errors.New("unknown node type") - } - io.WriteString(w, "\n") - for c := n.FirstChild; c != nil; c = c.NextSibling { - if err := dumpLevel(w, c, level+1); err != nil { - return err - } - } - return nil -} - -func dump(n *Node) (string, error) { - if n == nil || n.FirstChild == nil { - return "", nil - } - var b bytes.Buffer - for c := n.FirstChild; c != nil; c = c.NextSibling { - if err := dumpLevel(&b, c, 0); err != nil { - return "", err - } - } - return b.String(), nil -} - -const testDataDir = "testdata/webkit/" - -func TestParser(t *testing.T) { - testFiles, err := filepath.Glob(testDataDir + "*.dat") - if err != nil { - t.Fatal(err) - } - for _, tf := range testFiles { - f, err := os.Open(tf) - if err != nil { - t.Fatal(err) - } - defer f.Close() - r := bufio.NewReader(f) - - for i := 0; ; i++ { - text, want, context, err := readParseTest(r) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - - err = testParseCase(text, want, context) - - if err != nil { - t.Errorf("%s test #%d %q, %s", tf, i, text, err) - } - } - } -} - -// testParseCase tests one test case from the test files. If the test does not -// pass, it returns an error that explains the failure. -// text is the HTML to be parsed, want is a dump of the correct parse tree, -// and context is the name of the context node, if any. -func testParseCase(text, want, context string) (err error) { - defer func() { - if x := recover(); x != nil { - switch e := x.(type) { - case error: - err = e - default: - err = fmt.Errorf("%v", e) - } - } - }() - - var doc *Node - if context == "" { - doc, err = Parse(strings.NewReader(text)) - if err != nil { - return err - } - } else { - contextNode := &Node{ - Type: ElementNode, - DataAtom: atom.Lookup([]byte(context)), - Data: context, - } - nodes, err := ParseFragment(strings.NewReader(text), contextNode) - if err != nil { - return err - } - doc = &Node{ - Type: DocumentNode, - } - for _, n := range nodes { - doc.AppendChild(n) - } - } - - if err := checkTreeConsistency(doc); err != nil { - return err - } - - got, err := dump(doc) - if err != nil { - return err - } - // Compare the parsed tree to the #document section. - if got != want { - return fmt.Errorf("got vs want:\n----\n%s----\n%s----", got, want) - } - - if renderTestBlacklist[text] || context != "" { - return nil - } - - // Check that rendering and re-parsing results in an identical tree. - pr, pw := io.Pipe() - go func() { - pw.CloseWithError(Render(pw, doc)) - }() - doc1, err := Parse(pr) - if err != nil { - return err - } - got1, err := dump(doc1) - if err != nil { - return err - } - if got != got1 { - return fmt.Errorf("got vs got1:\n----\n%s----\n%s----", got, got1) - } - - return nil -} - -// Some test input result in parse trees are not 'well-formed' despite -// following the HTML5 recovery algorithms. Rendering and re-parsing such a -// tree will not result in an exact clone of that tree. We blacklist such -// inputs from the render test. -var renderTestBlacklist = map[string]bool{ - // The second will be reparented to the first
NameOptionTypeDescriptionDefault
gostring Message bool if true, a `GoString` method is generated. This returns a string representing valid go code to reproduce the current state of the struct. false
onlyone (deprecated) Message bool if true, all fields must be nullable and only one of the fields may be set, like a union. Two methods are generated: `GetValue() interface{}` and `SetValue(v interface{}) (set bool)`. These provide easier interaction with a union. false
onlyone Message bool if true, all fields must be nullable and only one of the fields may be set, like a union. Two methods are generated: `GetValue() interface{}` and `SetValue(v interface{}) (set bool)`. These provide easier interaction with a union. false
equal Message bool if true, an Equal method is generated false
compare Message bool if true, a Compare method is generated. This is very useful for quickly implementing sort on a list of protobuf structs false
verbose_equal Message bool if true, a verbose equal method is generated for the message. This returns an error which describes the exact element which is not equal to the exact element in the other struct. false
's parent. This - // results in an whose parent is an , which is not 'well-formed'. - `
XCY`: true, - // The same thing with a

: - `

`: true, - // More cases of being reparented: - `aba
brx
aoe`: true, - `

`: true, - `
`: true, - // A similar reparenting situation involving : - `123`: true, - // A element is reparented, putting it before a table. - // A <plaintext> element can't have anything after it in HTML. - `<table><plaintext><td>`: true, - `<!doctype html><table><plaintext></plaintext>`: true, - `<!doctype html><table><tbody><plaintext></plaintext>`: true, - `<!doctype html><table><tbody><tr><plaintext></plaintext>`: true, - // A form inside a table inside a form doesn't work either. - `<!doctype html><form><table></form><form></table></form>`: true, - // A script that ends at EOF may escape its own closing tag when rendered. - `<!doctype html><script><!--<script `: true, - `<!doctype html><script><!--<script <`: true, - `<!doctype html><script><!--<script <a`: true, - `<!doctype html><script><!--<script </`: true, - `<!doctype html><script><!--<script </s`: true, - `<!doctype html><script><!--<script </script`: true, - `<!doctype html><script><!--<script </scripta`: true, - `<!doctype html><script><!--<script -`: true, - `<!doctype html><script><!--<script -a`: true, - `<!doctype html><script><!--<script -<`: true, - `<!doctype html><script><!--<script --`: true, - `<!doctype html><script><!--<script --a`: true, - `<!doctype html><script><!--<script --<`: true, - `<script><!--<script `: true, - `<script><!--<script <a`: true, - `<script><!--<script </script`: true, - `<script><!--<script </scripta`: true, - `<script><!--<script -`: true, - `<script><!--<script -a`: true, - `<script><!--<script --`: true, - `<script><!--<script --a`: true, - `<script><!--<script <`: true, - `<script><!--<script </`: true, - `<script><!--<script </s`: true, - // Reconstructing the active formatting elements results in a <plaintext> - // element that contains an <a> element. - `<!doctype html><p><a><plaintext>b`: true, -} - -func TestNodeConsistency(t *testing.T) { - // inconsistentNode is a Node whose DataAtom and Data do not agree. - inconsistentNode := &Node{ - Type: ElementNode, - DataAtom: atom.Frameset, - Data: "table", - } - _, err := ParseFragment(strings.NewReader("<p>hello</p>"), inconsistentNode) - if err == nil { - t.Errorf("got nil error, want non-nil") - } -} - -func BenchmarkParser(b *testing.B) { - buf, err := ioutil.ReadFile("testdata/go1.html") - if err != nil { - b.Fatalf("could not read testdata/go1.html: %v", err) - } - b.SetBytes(int64(len(buf))) - runtime.GC() - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - Parse(bytes.NewBuffer(buf)) - } -} diff --git a/vendor/golang.org/x/net/html/render_test.go b/vendor/golang.org/x/net/html/render_test.go deleted file mode 100644 index 11da54b313..0000000000 --- a/vendor/golang.org/x/net/html/render_test.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2010 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 html - -import ( - "bytes" - "testing" -) - -func TestRenderer(t *testing.T) { - nodes := [...]*Node{ - 0: { - Type: ElementNode, - Data: "html", - }, - 1: { - Type: ElementNode, - Data: "head", - }, - 2: { - Type: ElementNode, - Data: "body", - }, - 3: { - Type: TextNode, - Data: "0<1", - }, - 4: { - Type: ElementNode, - Data: "p", - Attr: []Attribute{ - { - Key: "id", - Val: "A", - }, - { - Key: "foo", - Val: `abc"def`, - }, - }, - }, - 5: { - Type: TextNode, - Data: "2", - }, - 6: { - Type: ElementNode, - Data: "b", - Attr: []Attribute{ - { - Key: "empty", - Val: "", - }, - }, - }, - 7: { - Type: TextNode, - Data: "3", - }, - 8: { - Type: ElementNode, - Data: "i", - Attr: []Attribute{ - { - Key: "backslash", - Val: `\`, - }, - }, - }, - 9: { - Type: TextNode, - Data: "&4", - }, - 10: { - Type: TextNode, - Data: "5", - }, - 11: { - Type: ElementNode, - Data: "blockquote", - }, - 12: { - Type: ElementNode, - Data: "br", - }, - 13: { - Type: TextNode, - Data: "6", - }, - } - - // Build a tree out of those nodes, based on a textual representation. - // Only the ".\t"s are significant. The trailing HTML-like text is - // just commentary. The "0:" prefixes are for easy cross-reference with - // the nodes array. - treeAsText := [...]string{ - 0: `<html>`, - 1: `. <head>`, - 2: `. <body>`, - 3: `. . "0&lt;1"`, - 4: `. . <p id="A" foo="abc&#34;def">`, - 5: `. . . "2"`, - 6: `. . . <b empty="">`, - 7: `. . . . "3"`, - 8: `. . . <i backslash="\">`, - 9: `. . . . "&amp;4"`, - 10: `. . "5"`, - 11: `. . <blockquote>`, - 12: `. . <br>`, - 13: `. . "6"`, - } - if len(nodes) != len(treeAsText) { - t.Fatal("len(nodes) != len(treeAsText)") - } - var stack [8]*Node - for i, line := range treeAsText { - level := 0 - for line[0] == '.' { - // Strip a leading ".\t". - line = line[2:] - level++ - } - n := nodes[i] - if level == 0 { - if stack[0] != nil { - t.Fatal("multiple root nodes") - } - stack[0] = n - } else { - stack[level-1].AppendChild(n) - stack[level] = n - for i := level + 1; i < len(stack); i++ { - stack[i] = nil - } - } - // At each stage of tree construction, we check all nodes for consistency. - for j, m := range nodes { - if err := checkNodeConsistency(m); err != nil { - t.Fatalf("i=%d, j=%d: %v", i, j, err) - } - } - } - - want := `<html><head></head><body>0&lt;1<p id="A" foo="abc&#34;def">` + - `2<b empty="">3</b><i backslash="\">&amp;4</i></p>` + - `5<blockquote></blockquote><br/>6</body></html>` - b := new(bytes.Buffer) - if err := Render(b, nodes[0]); err != nil { - t.Fatal(err) - } - if got := b.String(); got != want { - t.Errorf("got vs want:\n%s\n%s\n", got, want) - } -} diff --git a/vendor/golang.org/x/net/html/token.go b/vendor/golang.org/x/net/html/token.go index 893e272a9e..e3c01d7c90 100644 --- a/vendor/golang.org/x/net/html/token.go +++ b/vendor/golang.org/x/net/html/token.go @@ -1161,8 +1161,8 @@ func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool) { return nil, nil, false } -// Token returns the next Token. The result's Data and Attr values remain valid -// after subsequent Next calls. +// Token returns the current Token. The result's Data and Attr values remain +// valid after subsequent Next calls. func (z *Tokenizer) Token() Token { t := Token{Type: z.tt} switch z.tt { diff --git a/vendor/golang.org/x/net/html/token_test.go b/vendor/golang.org/x/net/html/token_test.go deleted file mode 100644 index 20221c3284..0000000000 --- a/vendor/golang.org/x/net/html/token_test.go +++ /dev/null @@ -1,748 +0,0 @@ -// Copyright 2010 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 html - -import ( - "bytes" - "io" - "io/ioutil" - "reflect" - "runtime" - "strings" - "testing" -) - -type tokenTest struct { - // A short description of the test case. - desc string - // The HTML to parse. - html string - // The string representations of the expected tokens, joined by '$'. - golden string -} - -var tokenTests = []tokenTest{ - { - "empty", - "", - "", - }, - // A single text node. The tokenizer should not break text nodes on whitespace, - // nor should it normalize whitespace within a text node. - { - "text", - "foo bar", - "foo bar", - }, - // An entity. - { - "entity", - "one &lt; two", - "one &lt; two", - }, - // A start, self-closing and end tag. The tokenizer does not care if the start - // and end tokens don't match; that is the job of the parser. - { - "tags", - "<a>b<c/>d</e>", - "<a>$b$<c/>$d$</e>", - }, - // Angle brackets that aren't a tag. - { - "not a tag #0", - "<", - "&lt;", - }, - { - "not a tag #1", - "</", - "&lt;/", - }, - { - "not a tag #2", - "</>", - "<!---->", - }, - { - "not a tag #3", - "a</>b", - "a$<!---->$b", - }, - { - "not a tag #4", - "</ >", - "<!-- -->", - }, - { - "not a tag #5", - "</.", - "<!--.-->", - }, - { - "not a tag #6", - "</.>", - "<!--.-->", - }, - { - "not a tag #7", - "a < b", - "a &lt; b", - }, - { - "not a tag #8", - "<.>", - "&lt;.&gt;", - }, - { - "not a tag #9", - "a<<<b>>>c", - "a&lt;&lt;$<b>$&gt;&gt;c", - }, - { - "not a tag #10", - "if x<0 and y < 0 then x*y>0", - "if x&lt;0 and y &lt; 0 then x*y&gt;0", - }, - { - "not a tag #11", - "<<p>", - "&lt;$<p>", - }, - // EOF in a tag name. - { - "tag name eof #0", - "<a", - "", - }, - { - "tag name eof #1", - "<a ", - "", - }, - { - "tag name eof #2", - "a<b", - "a", - }, - { - "tag name eof #3", - "<a><b", - "<a>", - }, - { - "tag name eof #4", - `<a x`, - ``, - }, - // Some malformed tags that are missing a '>'. - { - "malformed tag #0", - `<p</p>`, - `<p< p="">`, - }, - { - "malformed tag #1", - `<p </p>`, - `<p <="" p="">`, - }, - { - "malformed tag #2", - `<p id`, - ``, - }, - { - "malformed tag #3", - `<p id=`, - ``, - }, - { - "malformed tag #4", - `<p id=>`, - `<p id="">`, - }, - { - "malformed tag #5", - `<p id=0`, - ``, - }, - { - "malformed tag #6", - `<p id=0</p>`, - `<p id="0&lt;/p">`, - }, - { - "malformed tag #7", - `<p id="0</p>`, - ``, - }, - { - "malformed tag #8", - `<p id="0"</p>`, - `<p id="0" <="" p="">`, - }, - { - "malformed tag #9", - `<p></p id`, - `<p>`, - }, - // Raw text and RCDATA. - { - "basic raw text", - "<script><a></b></script>", - "<script>$&lt;a&gt;&lt;/b&gt;$</script>", - }, - { - "unfinished script end tag", - "<SCRIPT>a</SCR", - "<script>$a&lt;/SCR", - }, - { - "broken script end tag", - "<SCRIPT>a</SCR ipt>", - "<script>$a&lt;/SCR ipt&gt;", - }, - { - "EOF in script end tag", - "<SCRIPT>a</SCRipt", - "<script>$a&lt;/SCRipt", - }, - { - "scriptx end tag", - "<SCRIPT>a</SCRiptx", - "<script>$a&lt;/SCRiptx", - }, - { - "' ' completes script end tag", - "<SCRIPT>a</SCRipt ", - "<script>$a", - }, - { - "'>' completes script end tag", - "<SCRIPT>a</SCRipt>", - "<script>$a$</script>", - }, - { - "self-closing script end tag", - "<SCRIPT>a</SCRipt/>", - "<script>$a$</script>", - }, - { - "nested script tag", - "<SCRIPT>a</SCRipt<script>", - "<script>$a&lt;/SCRipt&lt;script&gt;", - }, - { - "script end tag after unfinished", - "<SCRIPT>a</SCRipt</script>", - "<script>$a&lt;/SCRipt$</script>", - }, - { - "script/style mismatched tags", - "<script>a</style>", - "<script>$a&lt;/style&gt;", - }, - { - "style element with entity", - "<style>&apos;", - "<style>$&amp;apos;", - }, - { - "textarea with tag", - "<textarea><div></textarea>", - "<textarea>$&lt;div&gt;$</textarea>", - }, - { - "title with tag and entity", - "<title><b>K&amp;R C</b></title>", - "<title>$&lt;b&gt;K&amp;R C&lt;/b&gt;$</title>", - }, - // DOCTYPE tests. - { - "Proper DOCTYPE", - "<!DOCTYPE html>", - "<!DOCTYPE html>", - }, - { - "DOCTYPE with no space", - "<!doctypehtml>", - "<!DOCTYPE html>", - }, - { - "DOCTYPE with two spaces", - "<!doctype html>", - "<!DOCTYPE html>", - }, - { - "looks like DOCTYPE but isn't", - "<!DOCUMENT html>", - "<!--DOCUMENT html-->", - }, - { - "DOCTYPE at EOF", - "<!DOCtype", - "<!DOCTYPE >", - }, - // XML processing instructions. - { - "XML processing instruction", - "<?xml?>", - "<!--?xml?-->", - }, - // Comments. - { - "comment0", - "abc<b><!-- skipme --></b>def", - "abc$<b>$<!-- skipme -->$</b>$def", - }, - { - "comment1", - "a<!-->z", - "a$<!---->$z", - }, - { - "comment2", - "a<!--->z", - "a$<!---->$z", - }, - { - "comment3", - "a<!--x>-->z", - "a$<!--x>-->$z", - }, - { - "comment4", - "a<!--x->-->z", - "a$<!--x->-->$z", - }, - { - "comment5", - "a<!>z", - "a$<!---->$z", - }, - { - "comment6", - "a<!->z", - "a$<!----->$z", - }, - { - "comment7", - "a<!---<>z", - "a$<!---<>z-->", - }, - { - "comment8", - "a<!--z", - "a$<!--z-->", - }, - { - "comment9", - "a<!--z-", - "a$<!--z-->", - }, - { - "comment10", - "a<!--z--", - "a$<!--z-->", - }, - { - "comment11", - "a<!--z---", - "a$<!--z--->", - }, - { - "comment12", - "a<!--z----", - "a$<!--z---->", - }, - { - "comment13", - "a<!--x--!>z", - "a$<!--x-->$z", - }, - // An attribute with a backslash. - { - "backslash", - `<p id="a\"b">`, - `<p id="a\" b"="">`, - }, - // Entities, tag name and attribute key lower-casing, and whitespace - // normalization within a tag. - { - "tricky", - "<p \t\n iD=\"a&quot;B\" foo=\"bar\"><EM>te&lt;&amp;;xt</em></p>", - `<p id="a&#34;B" foo="bar">$<em>$te&lt;&amp;;xt$</em>$</p>`, - }, - // A nonexistent entity. Tokenizing and converting back to a string should - // escape the "&" to become "&amp;". - { - "noSuchEntity", - `<a b="c&noSuchEntity;d">&lt;&alsoDoesntExist;&`, - `<a b="c&amp;noSuchEntity;d">$&lt;&amp;alsoDoesntExist;&amp;`, - }, - { - "entity without semicolon", - `&notit;&notin;<a b="q=z&amp=5&notice=hello&not;=world">`, - `¬it;∉$<a b="q=z&amp;amp=5&amp;notice=hello¬=world">`, - }, - { - "entity with digits", - "&frac12;", - "½", - }, - // Attribute tests: - // http://dev.w3.org/html5/pf-summary/Overview.html#attributes - { - "Empty attribute", - `<input disabled FOO>`, - `<input disabled="" foo="">`, - }, - { - "Empty attribute, whitespace", - `<input disabled FOO >`, - `<input disabled="" foo="">`, - }, - { - "Unquoted attribute value", - `<input value=yes FOO=BAR>`, - `<input value="yes" foo="BAR">`, - }, - { - "Unquoted attribute value, spaces", - `<input value = yes FOO = BAR>`, - `<input value="yes" foo="BAR">`, - }, - { - "Unquoted attribute value, trailing space", - `<input value=yes FOO=BAR >`, - `<input value="yes" foo="BAR">`, - }, - { - "Single-quoted attribute value", - `<input value='yes' FOO='BAR'>`, - `<input value="yes" foo="BAR">`, - }, - { - "Single-quoted attribute value, trailing space", - `<input value='yes' FOO='BAR' >`, - `<input value="yes" foo="BAR">`, - }, - { - "Double-quoted attribute value", - `<input value="I'm an attribute" FOO="BAR">`, - `<input value="I&#39;m an attribute" foo="BAR">`, - }, - { - "Attribute name characters", - `<meta http-equiv="content-type">`, - `<meta http-equiv="content-type">`, - }, - { - "Mixed attributes", - `a<P V="0 1" w='2' X=3 y>z`, - `a$<p v="0 1" w="2" x="3" y="">$z`, - }, - { - "Attributes with a solitary single quote", - `<p id=can't><p id=won't>`, - `<p id="can&#39;t">$<p id="won&#39;t">`, - }, -} - -func TestTokenizer(t *testing.T) { -loop: - for _, tt := range tokenTests { - z := NewTokenizer(strings.NewReader(tt.html)) - if tt.golden != "" { - for i, s := range strings.Split(tt.golden, "$") { - if z.Next() == ErrorToken { - t.Errorf("%s token %d: want %q got error %v", tt.desc, i, s, z.Err()) - continue loop - } - actual := z.Token().String() - if s != actual { - t.Errorf("%s token %d: want %q got %q", tt.desc, i, s, actual) - continue loop - } - } - } - z.Next() - if z.Err() != io.EOF { - t.Errorf("%s: want EOF got %q", tt.desc, z.Err()) - } - } -} - -func TestMaxBuffer(t *testing.T) { - // Exceeding the maximum buffer size generates ErrBufferExceeded. - z := NewTokenizer(strings.NewReader("<" + strings.Repeat("t", 10))) - z.SetMaxBuf(5) - tt := z.Next() - if got, want := tt, ErrorToken; got != want { - t.Fatalf("token type: got: %v want: %v", got, want) - } - if got, want := z.Err(), ErrBufferExceeded; got != want { - t.Errorf("error type: got: %v want: %v", got, want) - } - if got, want := string(z.Raw()), "<tttt"; got != want { - t.Fatalf("buffered before overflow: got: %q want: %q", got, want) - } -} - -func TestMaxBufferReconstruction(t *testing.T) { - // Exceeding the maximum buffer size at any point while tokenizing permits - // reconstructing the original input. -tests: - for _, test := range tokenTests { - for maxBuf := 1; ; maxBuf++ { - r := strings.NewReader(test.html) - z := NewTokenizer(r) - z.SetMaxBuf(maxBuf) - var tokenized bytes.Buffer - for { - tt := z.Next() - tokenized.Write(z.Raw()) - if tt == ErrorToken { - if err := z.Err(); err != io.EOF && err != ErrBufferExceeded { - t.Errorf("%s: unexpected error: %v", test.desc, err) - } - break - } - } - // Anything tokenized along with untokenized input or data left in the reader. - assembled, err := ioutil.ReadAll(io.MultiReader(&tokenized, bytes.NewReader(z.Buffered()), r)) - if err != nil { - t.Errorf("%s: ReadAll: %v", test.desc, err) - continue tests - } - if got, want := string(assembled), test.html; got != want { - t.Errorf("%s: reassembled html:\n got: %q\nwant: %q", test.desc, got, want) - continue tests - } - // EOF indicates that we completed tokenization and hence found the max - // maxBuf that generates ErrBufferExceeded, so continue to the next test. - if z.Err() == io.EOF { - break - } - } // buffer sizes - } // tests -} - -func TestPassthrough(t *testing.T) { - // Accumulating the raw output for each parse event should reconstruct the - // original input. - for _, test := range tokenTests { - z := NewTokenizer(strings.NewReader(test.html)) - var parsed bytes.Buffer - for { - tt := z.Next() - parsed.Write(z.Raw()) - if tt == ErrorToken { - break - } - } - if got, want := parsed.String(), test.html; got != want { - t.Errorf("%s: parsed output:\n got: %q\nwant: %q", test.desc, got, want) - } - } -} - -func TestBufAPI(t *testing.T) { - s := "0<a>1</a>2<b>3<a>4<a>5</a>6</b>7</a>8<a/>9" - z := NewTokenizer(bytes.NewBufferString(s)) - var result bytes.Buffer - depth := 0 -loop: - for { - tt := z.Next() - switch tt { - case ErrorToken: - if z.Err() != io.EOF { - t.Error(z.Err()) - } - break loop - case TextToken: - if depth > 0 { - result.Write(z.Text()) - } - case StartTagToken, EndTagToken: - tn, _ := z.TagName() - if len(tn) == 1 && tn[0] == 'a' { - if tt == StartTagToken { - depth++ - } else { - depth-- - } - } - } - } - u := "14567" - v := string(result.Bytes()) - if u != v { - t.Errorf("TestBufAPI: want %q got %q", u, v) - } -} - -func TestConvertNewlines(t *testing.T) { - testCases := map[string]string{ - "Mac\rDOS\r\nUnix\n": "Mac\nDOS\nUnix\n", - "Unix\nMac\rDOS\r\n": "Unix\nMac\nDOS\n", - "DOS\r\nDOS\r\nDOS\r\n": "DOS\nDOS\nDOS\n", - "": "", - "\n": "\n", - "\n\r": "\n\n", - "\r": "\n", - "\r\n": "\n", - "\r\n\n": "\n\n", - "\r\n\r": "\n\n", - "\r\n\r\n": "\n\n", - "\r\r": "\n\n", - "\r\r\n": "\n\n", - "\r\r\n\n": "\n\n\n", - "\r\r\r\n": "\n\n\n", - "\r \n": "\n \n", - "xyz": "xyz", - } - for in, want := range testCases { - if got := string(convertNewlines([]byte(in))); got != want { - t.Errorf("input %q: got %q, want %q", in, got, want) - } - } -} - -func TestReaderEdgeCases(t *testing.T) { - const s = "<p>An io.Reader can return (0, nil) or (n, io.EOF).</p>" - testCases := []io.Reader{ - &zeroOneByteReader{s: s}, - &eofStringsReader{s: s}, - &stuckReader{}, - } - for i, tc := range testCases { - got := []TokenType{} - z := NewTokenizer(tc) - for { - tt := z.Next() - if tt == ErrorToken { - break - } - got = append(got, tt) - } - if err := z.Err(); err != nil && err != io.EOF { - if err != io.ErrNoProgress { - t.Errorf("i=%d: %v", i, err) - } - continue - } - want := []TokenType{ - StartTagToken, - TextToken, - EndTagToken, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("i=%d: got %v, want %v", i, got, want) - continue - } - } -} - -// zeroOneByteReader is like a strings.Reader that alternates between -// returning 0 bytes and 1 byte at a time. -type zeroOneByteReader struct { - s string - n int -} - -func (r *zeroOneByteReader) Read(p []byte) (int, error) { - if len(p) == 0 { - return 0, nil - } - if len(r.s) == 0 { - return 0, io.EOF - } - r.n++ - if r.n%2 != 0 { - return 0, nil - } - p[0], r.s = r.s[0], r.s[1:] - return 1, nil -} - -// eofStringsReader is like a strings.Reader but can return an (n, err) where -// n > 0 && err != nil. -type eofStringsReader struct { - s string -} - -func (r *eofStringsReader) Read(p []byte) (int, error) { - n := copy(p, r.s) - r.s = r.s[n:] - if r.s != "" { - return n, nil - } - return n, io.EOF -} - -// stuckReader is an io.Reader that always returns no data and no error. -type stuckReader struct{} - -func (*stuckReader) Read(p []byte) (int, error) { - return 0, nil -} - -const ( - rawLevel = iota - lowLevel - highLevel -) - -func benchmarkTokenizer(b *testing.B, level int) { - buf, err := ioutil.ReadFile("testdata/go1.html") - if err != nil { - b.Fatalf("could not read testdata/go1.html: %v", err) - } - b.SetBytes(int64(len(buf))) - runtime.GC() - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - z := NewTokenizer(bytes.NewBuffer(buf)) - for { - tt := z.Next() - if tt == ErrorToken { - if err := z.Err(); err != nil && err != io.EOF { - b.Fatalf("tokenizer error: %v", err) - } - break - } - switch level { - case rawLevel: - // Calling z.Raw just returns the raw bytes of the token. It does - // not unescape &lt; to <, or lower-case tag names and attribute keys. - z.Raw() - case lowLevel: - // Caling z.Text, z.TagName and z.TagAttr returns []byte values - // whose contents may change on the next call to z.Next. - switch tt { - case TextToken, CommentToken, DoctypeToken: - z.Text() - case StartTagToken, SelfClosingTagToken: - _, more := z.TagName() - for more { - _, _, more = z.TagAttr() - } - case EndTagToken: - z.TagName() - } - case highLevel: - // Calling z.Token converts []byte values to strings whose validity - // extend beyond the next call to z.Next. - z.Token() - } - } - } -} - -func BenchmarkRawLevelTokenizer(b *testing.B) { benchmarkTokenizer(b, rawLevel) } -func BenchmarkLowLevelTokenizer(b *testing.B) { benchmarkTokenizer(b, lowLevel) } -func BenchmarkHighLevelTokenizer(b *testing.B) { benchmarkTokenizer(b, highLevel) } diff --git a/vendor/golang.org/x/net/http/httpguts/guts.go b/vendor/golang.org/x/net/http/httpguts/guts.go new file mode 100644 index 0000000000..8255fd49b4 --- /dev/null +++ b/vendor/golang.org/x/net/http/httpguts/guts.go @@ -0,0 +1,65 @@ +// Copyright 2018 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 httpguts provides functions implementing various details +// of the HTTP specification. +// +// This package is shared by the standard library (which vendors it) +// and x/net/http2. It comes with no API stability promise. +package httpguts + +import ( + "net/textproto" + "strings" +) + +// SniffedContentType reports whether ct is a Content-Type that is known +// to cause client-side content sniffing. +// +// This provides just a partial implementation of mime.ParseMediaType +// with the assumption that the Content-Type is not attacker controlled. +func SniffedContentType(ct string) bool { + if i := strings.Index(ct, ";"); i != -1 { + ct = ct[:i] + } + ct = strings.ToLower(strings.TrimSpace(ct)) + return ct == "text/plain" || ct == "application/octet-stream" || + ct == "application/unknown" || ct == "unknown/unknown" || ct == "*/*" || + !strings.Contains(ct, "/") +} + +// ValidTrailerHeader reports whether name is a valid header field name to appear +// in trailers. +// See RFC 7230, Section 4.1.2 +func ValidTrailerHeader(name string) bool { + name = textproto.CanonicalMIMEHeaderKey(name) + if strings.HasPrefix(name, "If-") || badTrailer[name] { + return false + } + return true +} + +var badTrailer = map[string]bool{ + "Authorization": true, + "Cache-Control": true, + "Connection": true, + "Content-Encoding": true, + "Content-Length": true, + "Content-Range": true, + "Content-Type": true, + "Expect": true, + "Host": true, + "Keep-Alive": true, + "Max-Forwards": true, + "Pragma": true, + "Proxy-Authenticate": true, + "Proxy-Authorization": true, + "Proxy-Connection": true, + "Range": true, + "Realm": true, + "Te": true, + "Trailer": true, + "Transfer-Encoding": true, + "Www-Authenticate": true, +} diff --git a/vendor/golang.org/x/net/lex/httplex/httplex.go b/vendor/golang.org/x/net/http/httpguts/httplex.go similarity index 97% rename from vendor/golang.org/x/net/lex/httplex/httplex.go rename to vendor/golang.org/x/net/http/httpguts/httplex.go index 20f2b8940b..e7de24ee64 100644 --- a/vendor/golang.org/x/net/lex/httplex/httplex.go +++ b/vendor/golang.org/x/net/http/httpguts/httplex.go @@ -2,12 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package httplex contains rules around lexical matters of various -// HTTP-related specifications. -// -// This package is shared by the standard library (which vendors it) -// and x/net/http2. It comes with no API stability promise. -package httplex +package httpguts import ( "net" diff --git a/vendor/golang.org/x/net/http2/ciphers.go b/vendor/golang.org/x/net/http2/ciphers.go index 698860b777..c9a0cf3b42 100644 --- a/vendor/golang.org/x/net/http2/ciphers.go +++ b/vendor/golang.org/x/net/http2/ciphers.go @@ -5,7 +5,7 @@ package http2 // A list of the possible cipher suite ids. Taken from -// http://www.iana.org/assignments/tls-parameters/tls-parameters.txt +// https://www.iana.org/assignments/tls-parameters/tls-parameters.txt const ( cipher_TLS_NULL_WITH_NULL_NULL uint16 = 0x0000 diff --git a/vendor/golang.org/x/net/http2/ciphers_test.go b/vendor/golang.org/x/net/http2/ciphers_test.go deleted file mode 100644 index 764bbc8c8c..0000000000 --- a/vendor/golang.org/x/net/http2/ciphers_test.go +++ /dev/null @@ -1,309 +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 http2 - -import "testing" - -func TestIsBadCipherBad(t *testing.T) { - for _, c := range badCiphers { - if !isBadCipher(c) { - t.Errorf("Wrong result for isBadCipher(%d), want true", c) - } - } -} - -// verify we don't give false positives on ciphers not on blacklist -func TestIsBadCipherGood(t *testing.T) { - goodCiphers := map[uint16]string{ - cipher_TLS_DHE_RSA_WITH_AES_256_CCM: "cipher_TLS_DHE_RSA_WITH_AES_256_CCM", - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM: "cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM", - cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256: "cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256", - } - for c, name := range goodCiphers { - if isBadCipher(c) { - t.Errorf("Wrong result for isBadCipher(%d) %s, want false", c, name) - } - } -} - -// copied from https://http2.github.io/http2-spec/#BadCipherSuites, -var badCiphers = []uint16{ - cipher_TLS_NULL_WITH_NULL_NULL, - cipher_TLS_RSA_WITH_NULL_MD5, - cipher_TLS_RSA_WITH_NULL_SHA, - cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5, - cipher_TLS_RSA_WITH_RC4_128_MD5, - cipher_TLS_RSA_WITH_RC4_128_SHA, - cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5, - cipher_TLS_RSA_WITH_IDEA_CBC_SHA, - cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_RSA_WITH_DES_CBC_SHA, - cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DH_DSS_WITH_DES_CBC_SHA, - cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DH_RSA_WITH_DES_CBC_SHA, - cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5, - cipher_TLS_DH_anon_WITH_RC4_128_MD5, - cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA, - cipher_TLS_DH_anon_WITH_DES_CBC_SHA, - cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_KRB5_WITH_DES_CBC_SHA, - cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_KRB5_WITH_RC4_128_SHA, - cipher_TLS_KRB5_WITH_IDEA_CBC_SHA, - cipher_TLS_KRB5_WITH_DES_CBC_MD5, - cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5, - cipher_TLS_KRB5_WITH_RC4_128_MD5, - cipher_TLS_KRB5_WITH_IDEA_CBC_MD5, - cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA, - cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA, - cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA, - cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5, - cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5, - cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5, - cipher_TLS_PSK_WITH_NULL_SHA, - cipher_TLS_DHE_PSK_WITH_NULL_SHA, - cipher_TLS_RSA_PSK_WITH_NULL_SHA, - cipher_TLS_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA, - cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA, - cipher_TLS_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA, - cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_WITH_NULL_SHA256, - cipher_TLS_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_RSA_WITH_AES_256_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, - cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256, - cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA, - cipher_TLS_PSK_WITH_RC4_128_SHA, - cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_DHE_PSK_WITH_RC4_128_SHA, - cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_PSK_WITH_RC4_128_SHA, - cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_WITH_SEED_CBC_SHA, - cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA, - cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA, - cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA, - cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA, - cipher_TLS_DH_anon_WITH_SEED_CBC_SHA, - cipher_TLS_RSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_RSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256, - cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384, - cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256, - cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384, - cipher_TLS_PSK_WITH_AES_128_GCM_SHA256, - cipher_TLS_PSK_WITH_AES_256_GCM_SHA384, - cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, - cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, - cipher_TLS_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_PSK_WITH_NULL_SHA256, - cipher_TLS_PSK_WITH_NULL_SHA384, - cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_DHE_PSK_WITH_NULL_SHA256, - cipher_TLS_DHE_PSK_WITH_NULL_SHA384, - cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_RSA_PSK_WITH_NULL_SHA256, - cipher_TLS_RSA_PSK_WITH_NULL_SHA384, - cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256, - cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV, - cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA, - cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA, - cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDH_RSA_WITH_NULL_SHA, - cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA, - cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_RSA_WITH_NULL_SHA, - cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA, - cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDH_anon_WITH_NULL_SHA, - cipher_TLS_ECDH_anon_WITH_RC4_128_SHA, - cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA, - cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA, - cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA, - cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA, - cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA, - cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, - cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, - cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA, - cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA, - cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, - cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, - cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, - cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384, - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA, - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256, - cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384, - cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256, - cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384, - cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256, - cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384, - cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384, - cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256, - cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384, - cipher_TLS_RSA_WITH_AES_128_CCM, - cipher_TLS_RSA_WITH_AES_256_CCM, - cipher_TLS_RSA_WITH_AES_128_CCM_8, - cipher_TLS_RSA_WITH_AES_256_CCM_8, - cipher_TLS_PSK_WITH_AES_128_CCM, - cipher_TLS_PSK_WITH_AES_256_CCM, - cipher_TLS_PSK_WITH_AES_128_CCM_8, - cipher_TLS_PSK_WITH_AES_256_CCM_8, -} diff --git a/vendor/golang.org/x/net/http2/configure_transport.go b/vendor/golang.org/x/net/http2/configure_transport.go index b65fc6d423..088d6e2bdb 100644 --- a/vendor/golang.org/x/net/http2/configure_transport.go +++ b/vendor/golang.org/x/net/http2/configure_transport.go @@ -73,7 +73,7 @@ type noDialH2RoundTripper struct{ t *Transport } func (rt noDialH2RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { res, err := rt.t.RoundTrip(req) - if err == ErrNoCachedConn { + if isNoCachedConnError(err) { return nil, http.ErrSkipAltProtocol } return res, err diff --git a/vendor/golang.org/x/net/http2/databuffer_test.go b/vendor/golang.org/x/net/http2/databuffer_test.go deleted file mode 100644 index 028e12e52e..0000000000 --- a/vendor/golang.org/x/net/http2/databuffer_test.go +++ /dev/null @@ -1,157 +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. - -// +build go1.7 - -package http2 - -import ( - "bytes" - "fmt" - "reflect" - "testing" -) - -func fmtDataChunk(chunk []byte) string { - out := "" - var last byte - var count int - for _, c := range chunk { - if c != last { - if count > 0 { - out += fmt.Sprintf(" x %d ", count) - count = 0 - } - out += string([]byte{c}) - last = c - } - count++ - } - if count > 0 { - out += fmt.Sprintf(" x %d", count) - } - return out -} - -func fmtDataChunks(chunks [][]byte) string { - var out string - for _, chunk := range chunks { - out += fmt.Sprintf("{%q}", fmtDataChunk(chunk)) - } - return out -} - -func testDataBuffer(t *testing.T, wantBytes []byte, setup func(t *testing.T) *dataBuffer) { - // Run setup, then read the remaining bytes from the dataBuffer and check - // that they match wantBytes. We use different read sizes to check corner - // cases in Read. - for _, readSize := range []int{1, 2, 1 * 1024, 32 * 1024} { - t.Run(fmt.Sprintf("ReadSize=%d", readSize), func(t *testing.T) { - b := setup(t) - buf := make([]byte, readSize) - var gotRead bytes.Buffer - for { - n, err := b.Read(buf) - gotRead.Write(buf[:n]) - if err == errReadEmpty { - break - } - if err != nil { - t.Fatalf("error after %v bytes: %v", gotRead.Len(), err) - } - } - if got, want := gotRead.Bytes(), wantBytes; !bytes.Equal(got, want) { - t.Errorf("FinalRead=%q, want %q", fmtDataChunk(got), fmtDataChunk(want)) - } - }) - } -} - -func TestDataBufferAllocation(t *testing.T) { - writes := [][]byte{ - bytes.Repeat([]byte("a"), 1*1024-1), - []byte("a"), - bytes.Repeat([]byte("b"), 4*1024-1), - []byte("b"), - bytes.Repeat([]byte("c"), 8*1024-1), - []byte("c"), - bytes.Repeat([]byte("d"), 16*1024-1), - []byte("d"), - bytes.Repeat([]byte("e"), 32*1024), - } - var wantRead bytes.Buffer - for _, p := range writes { - wantRead.Write(p) - } - - testDataBuffer(t, wantRead.Bytes(), func(t *testing.T) *dataBuffer { - b := &dataBuffer{} - for _, p := range writes { - if n, err := b.Write(p); n != len(p) || err != nil { - t.Fatalf("Write(%q x %d)=%v,%v want %v,nil", p[:1], len(p), n, err, len(p)) - } - } - want := [][]byte{ - bytes.Repeat([]byte("a"), 1*1024), - bytes.Repeat([]byte("b"), 4*1024), - bytes.Repeat([]byte("c"), 8*1024), - bytes.Repeat([]byte("d"), 16*1024), - bytes.Repeat([]byte("e"), 16*1024), - bytes.Repeat([]byte("e"), 16*1024), - } - if !reflect.DeepEqual(b.chunks, want) { - t.Errorf("dataBuffer.chunks\ngot: %s\nwant: %s", fmtDataChunks(b.chunks), fmtDataChunks(want)) - } - return b - }) -} - -func TestDataBufferAllocationWithExpected(t *testing.T) { - writes := [][]byte{ - bytes.Repeat([]byte("a"), 1*1024), // allocates 16KB - bytes.Repeat([]byte("b"), 14*1024), - bytes.Repeat([]byte("c"), 15*1024), // allocates 16KB more - bytes.Repeat([]byte("d"), 2*1024), - bytes.Repeat([]byte("e"), 1*1024), // overflows 32KB expectation, allocates just 1KB - } - var wantRead bytes.Buffer - for _, p := range writes { - wantRead.Write(p) - } - - testDataBuffer(t, wantRead.Bytes(), func(t *testing.T) *dataBuffer { - b := &dataBuffer{expected: 32 * 1024} - for _, p := range writes { - if n, err := b.Write(p); n != len(p) || err != nil { - t.Fatalf("Write(%q x %d)=%v,%v want %v,nil", p[:1], len(p), n, err, len(p)) - } - } - want := [][]byte{ - append(bytes.Repeat([]byte("a"), 1*1024), append(bytes.Repeat([]byte("b"), 14*1024), bytes.Repeat([]byte("c"), 1*1024)...)...), - append(bytes.Repeat([]byte("c"), 14*1024), bytes.Repeat([]byte("d"), 2*1024)...), - bytes.Repeat([]byte("e"), 1*1024), - } - if !reflect.DeepEqual(b.chunks, want) { - t.Errorf("dataBuffer.chunks\ngot: %s\nwant: %s", fmtDataChunks(b.chunks), fmtDataChunks(want)) - } - return b - }) -} - -func TestDataBufferWriteAfterPartialRead(t *testing.T) { - testDataBuffer(t, []byte("cdxyz"), func(t *testing.T) *dataBuffer { - b := &dataBuffer{} - if n, err := b.Write([]byte("abcd")); n != 4 || err != nil { - t.Fatalf("Write(\"abcd\")=%v,%v want 4,nil", n, err) - } - p := make([]byte, 2) - if n, err := b.Read(p); n != 2 || err != nil || !bytes.Equal(p, []byte("ab")) { - t.Fatalf("Read()=%q,%v,%v want \"ab\",2,nil", p, n, err) - } - if n, err := b.Write([]byte("xyz")); n != 3 || err != nil { - t.Fatalf("Write(\"xyz\")=%v,%v want 3,nil", n, err) - } - return b - }) -} diff --git a/vendor/golang.org/x/net/http2/errors_test.go b/vendor/golang.org/x/net/http2/errors_test.go deleted file mode 100644 index da5c58c31d..0000000000 --- a/vendor/golang.org/x/net/http2/errors_test.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2014 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 http2 - -import "testing" - -func TestErrCodeString(t *testing.T) { - tests := []struct { - err ErrCode - want string - }{ - {ErrCodeProtocol, "PROTOCOL_ERROR"}, - {0xd, "HTTP_1_1_REQUIRED"}, - {0xf, "unknown error code 0xf"}, - } - for i, tt := range tests { - got := tt.err.String() - if got != tt.want { - t.Errorf("%d. Error = %q; want %q", i, got, tt.want) - } - } -} diff --git a/vendor/golang.org/x/net/http2/flow_test.go b/vendor/golang.org/x/net/http2/flow_test.go deleted file mode 100644 index 859adf5d14..0000000000 --- a/vendor/golang.org/x/net/http2/flow_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2014 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 http2 - -import "testing" - -func TestFlow(t *testing.T) { - var st flow - var conn flow - st.add(3) - conn.add(2) - - if got, want := st.available(), int32(3); got != want { - t.Errorf("available = %d; want %d", got, want) - } - st.setConnFlow(&conn) - if got, want := st.available(), int32(2); got != want { - t.Errorf("after parent setup, available = %d; want %d", got, want) - } - - st.take(2) - if got, want := conn.available(), int32(0); got != want { - t.Errorf("after taking 2, conn = %d; want %d", got, want) - } - if got, want := st.available(), int32(0); got != want { - t.Errorf("after taking 2, stream = %d; want %d", got, want) - } -} - -func TestFlowAdd(t *testing.T) { - var f flow - if !f.add(1) { - t.Fatal("failed to add 1") - } - if !f.add(-1) { - t.Fatal("failed to add -1") - } - if got, want := f.available(), int32(0); got != want { - t.Fatalf("size = %d; want %d", got, want) - } - if !f.add(1<<31 - 1) { - t.Fatal("failed to add 2^31-1") - } - if got, want := f.available(), int32(1<<31-1); got != want { - t.Fatalf("size = %d; want %d", got, want) - } - if f.add(1) { - t.Fatal("adding 1 to max shouldn't be allowed") - } - -} diff --git a/vendor/golang.org/x/net/http2/frame.go b/vendor/golang.org/x/net/http2/frame.go index 3b14890728..e32500779a 100644 --- a/vendor/golang.org/x/net/http2/frame.go +++ b/vendor/golang.org/x/net/http2/frame.go @@ -14,8 +14,8 @@ import ( "strings" "sync" + "golang.org/x/net/http/httpguts" "golang.org/x/net/http2/hpack" - "golang.org/x/net/lex/httplex" ) const frameHeaderLen = 9 @@ -1462,7 +1462,7 @@ func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) { if VerboseLogs && fr.logReads { fr.debugReadLoggerf("http2: decoded hpack field %+v", hf) } - if !httplex.ValidHeaderFieldValue(hf.Value) { + if !httpguts.ValidHeaderFieldValue(hf.Value) { invalid = headerFieldValueError(hf.Value) } isPseudo := strings.HasPrefix(hf.Name, ":") diff --git a/vendor/golang.org/x/net/http2/frame_test.go b/vendor/golang.org/x/net/http2/frame_test.go deleted file mode 100644 index 37266bc58f..0000000000 --- a/vendor/golang.org/x/net/http2/frame_test.go +++ /dev/null @@ -1,1191 +0,0 @@ -// Copyright 2014 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 http2 - -import ( - "bytes" - "fmt" - "io" - "reflect" - "strings" - "testing" - "unsafe" - - "golang.org/x/net/http2/hpack" -) - -func testFramer() (*Framer, *bytes.Buffer) { - buf := new(bytes.Buffer) - return NewFramer(buf, buf), buf -} - -func TestFrameSizes(t *testing.T) { - // Catch people rearranging the FrameHeader fields. - if got, want := int(unsafe.Sizeof(FrameHeader{})), 12; got != want { - t.Errorf("FrameHeader size = %d; want %d", got, want) - } -} - -func TestFrameTypeString(t *testing.T) { - tests := []struct { - ft FrameType - want string - }{ - {FrameData, "DATA"}, - {FramePing, "PING"}, - {FrameGoAway, "GOAWAY"}, - {0xf, "UNKNOWN_FRAME_TYPE_15"}, - } - - for i, tt := range tests { - got := tt.ft.String() - if got != tt.want { - t.Errorf("%d. String(FrameType %d) = %q; want %q", i, int(tt.ft), got, tt.want) - } - } -} - -func TestWriteRST(t *testing.T) { - fr, buf := testFramer() - var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 - var errCode uint32 = 7<<24 + 6<<16 + 5<<8 + 4 - fr.WriteRSTStream(streamID, ErrCode(errCode)) - const wantEnc = "\x00\x00\x04\x03\x00\x01\x02\x03\x04\x07\x06\x05\x04" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - want := &RSTStreamFrame{ - FrameHeader: FrameHeader{ - valid: true, - Type: 0x3, - Flags: 0x0, - Length: 0x4, - StreamID: 0x1020304, - }, - ErrCode: 0x7060504, - } - if !reflect.DeepEqual(f, want) { - t.Errorf("parsed back %#v; want %#v", f, want) - } -} - -func TestWriteData(t *testing.T) { - fr, buf := testFramer() - var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 - data := []byte("ABC") - fr.WriteData(streamID, true, data) - const wantEnc = "\x00\x00\x03\x00\x01\x01\x02\x03\x04ABC" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - df, ok := f.(*DataFrame) - if !ok { - t.Fatalf("got %T; want *DataFrame", f) - } - if !bytes.Equal(df.Data(), data) { - t.Errorf("got %q; want %q", df.Data(), data) - } - if f.Header().Flags&1 == 0 { - t.Errorf("didn't see END_STREAM flag") - } -} - -func TestWriteDataPadded(t *testing.T) { - tests := [...]struct { - streamID uint32 - endStream bool - data []byte - pad []byte - wantHeader FrameHeader - }{ - // Unpadded: - 0: { - streamID: 1, - endStream: true, - data: []byte("foo"), - pad: nil, - wantHeader: FrameHeader{ - Type: FrameData, - Flags: FlagDataEndStream, - Length: 3, - StreamID: 1, - }, - }, - - // Padded bit set, but no padding: - 1: { - streamID: 1, - endStream: true, - data: []byte("foo"), - pad: []byte{}, - wantHeader: FrameHeader{ - Type: FrameData, - Flags: FlagDataEndStream | FlagDataPadded, - Length: 4, - StreamID: 1, - }, - }, - - // Padded bit set, with padding: - 2: { - streamID: 1, - endStream: false, - data: []byte("foo"), - pad: []byte{0, 0, 0}, - wantHeader: FrameHeader{ - Type: FrameData, - Flags: FlagDataPadded, - Length: 7, - StreamID: 1, - }, - }, - } - for i, tt := range tests { - fr, _ := testFramer() - fr.WriteDataPadded(tt.streamID, tt.endStream, tt.data, tt.pad) - f, err := fr.ReadFrame() - if err != nil { - t.Errorf("%d. ReadFrame: %v", i, err) - continue - } - got := f.Header() - tt.wantHeader.valid = true - if got != tt.wantHeader { - t.Errorf("%d. read %+v; want %+v", i, got, tt.wantHeader) - continue - } - df := f.(*DataFrame) - if !bytes.Equal(df.Data(), tt.data) { - t.Errorf("%d. got %q; want %q", i, df.Data(), tt.data) - } - } -} - -func TestWriteHeaders(t *testing.T) { - tests := []struct { - name string - p HeadersFrameParam - wantEnc string - wantFrame *HeadersFrame - }{ - { - "basic", - HeadersFrameParam{ - StreamID: 42, - BlockFragment: []byte("abc"), - Priority: PriorityParam{}, - }, - "\x00\x00\x03\x01\x00\x00\x00\x00*abc", - &HeadersFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: 42, - Type: FrameHeaders, - Length: uint32(len("abc")), - }, - Priority: PriorityParam{}, - headerFragBuf: []byte("abc"), - }, - }, - { - "basic + end flags", - HeadersFrameParam{ - StreamID: 42, - BlockFragment: []byte("abc"), - EndStream: true, - EndHeaders: true, - Priority: PriorityParam{}, - }, - "\x00\x00\x03\x01\x05\x00\x00\x00*abc", - &HeadersFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: 42, - Type: FrameHeaders, - Flags: FlagHeadersEndStream | FlagHeadersEndHeaders, - Length: uint32(len("abc")), - }, - Priority: PriorityParam{}, - headerFragBuf: []byte("abc"), - }, - }, - { - "with padding", - HeadersFrameParam{ - StreamID: 42, - BlockFragment: []byte("abc"), - EndStream: true, - EndHeaders: true, - PadLength: 5, - Priority: PriorityParam{}, - }, - "\x00\x00\t\x01\r\x00\x00\x00*\x05abc\x00\x00\x00\x00\x00", - &HeadersFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: 42, - Type: FrameHeaders, - Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded, - Length: uint32(1 + len("abc") + 5), // pad length + contents + padding - }, - Priority: PriorityParam{}, - headerFragBuf: []byte("abc"), - }, - }, - { - "with priority", - HeadersFrameParam{ - StreamID: 42, - BlockFragment: []byte("abc"), - EndStream: true, - EndHeaders: true, - PadLength: 2, - Priority: PriorityParam{ - StreamDep: 15, - Exclusive: true, - Weight: 127, - }, - }, - "\x00\x00\v\x01-\x00\x00\x00*\x02\x80\x00\x00\x0f\u007fabc\x00\x00", - &HeadersFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: 42, - Type: FrameHeaders, - Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded | FlagHeadersPriority, - Length: uint32(1 + 5 + len("abc") + 2), // pad length + priority + contents + padding - }, - Priority: PriorityParam{ - StreamDep: 15, - Exclusive: true, - Weight: 127, - }, - headerFragBuf: []byte("abc"), - }, - }, - { - "with priority stream dep zero", // golang.org/issue/15444 - HeadersFrameParam{ - StreamID: 42, - BlockFragment: []byte("abc"), - EndStream: true, - EndHeaders: true, - PadLength: 2, - Priority: PriorityParam{ - StreamDep: 0, - Exclusive: true, - Weight: 127, - }, - }, - "\x00\x00\v\x01-\x00\x00\x00*\x02\x80\x00\x00\x00\u007fabc\x00\x00", - &HeadersFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: 42, - Type: FrameHeaders, - Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded | FlagHeadersPriority, - Length: uint32(1 + 5 + len("abc") + 2), // pad length + priority + contents + padding - }, - Priority: PriorityParam{ - StreamDep: 0, - Exclusive: true, - Weight: 127, - }, - headerFragBuf: []byte("abc"), - }, - }, - } - for _, tt := range tests { - fr, buf := testFramer() - if err := fr.WriteHeaders(tt.p); err != nil { - t.Errorf("test %q: %v", tt.name, err) - continue - } - if buf.String() != tt.wantEnc { - t.Errorf("test %q: encoded %q; want %q", tt.name, buf.Bytes(), tt.wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) - continue - } - if !reflect.DeepEqual(f, tt.wantFrame) { - t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) - } - } -} - -func TestWriteInvalidStreamDep(t *testing.T) { - fr, _ := testFramer() - err := fr.WriteHeaders(HeadersFrameParam{ - StreamID: 42, - Priority: PriorityParam{ - StreamDep: 1 << 31, - }, - }) - if err != errDepStreamID { - t.Errorf("header error = %v; want %q", err, errDepStreamID) - } - - err = fr.WritePriority(2, PriorityParam{StreamDep: 1 << 31}) - if err != errDepStreamID { - t.Errorf("priority error = %v; want %q", err, errDepStreamID) - } -} - -func TestWriteContinuation(t *testing.T) { - const streamID = 42 - tests := []struct { - name string - end bool - frag []byte - - wantFrame *ContinuationFrame - }{ - { - "not end", - false, - []byte("abc"), - &ContinuationFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: streamID, - Type: FrameContinuation, - Length: uint32(len("abc")), - }, - headerFragBuf: []byte("abc"), - }, - }, - { - "end", - true, - []byte("def"), - &ContinuationFrame{ - FrameHeader: FrameHeader{ - valid: true, - StreamID: streamID, - Type: FrameContinuation, - Flags: FlagContinuationEndHeaders, - Length: uint32(len("def")), - }, - headerFragBuf: []byte("def"), - }, - }, - } - for _, tt := range tests { - fr, _ := testFramer() - if err := fr.WriteContinuation(streamID, tt.end, tt.frag); err != nil { - t.Errorf("test %q: %v", tt.name, err) - continue - } - fr.AllowIllegalReads = true - f, err := fr.ReadFrame() - if err != nil { - t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) - continue - } - if !reflect.DeepEqual(f, tt.wantFrame) { - t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) - } - } -} - -func TestWritePriority(t *testing.T) { - const streamID = 42 - tests := []struct { - name string - priority PriorityParam - wantFrame *PriorityFrame - }{ - { - "not exclusive", - PriorityParam{ - StreamDep: 2, - Exclusive: false, - Weight: 127, - }, - &PriorityFrame{ - FrameHeader{ - valid: true, - StreamID: streamID, - Type: FramePriority, - Length: 5, - }, - PriorityParam{ - StreamDep: 2, - Exclusive: false, - Weight: 127, - }, - }, - }, - - { - "exclusive", - PriorityParam{ - StreamDep: 3, - Exclusive: true, - Weight: 77, - }, - &PriorityFrame{ - FrameHeader{ - valid: true, - StreamID: streamID, - Type: FramePriority, - Length: 5, - }, - PriorityParam{ - StreamDep: 3, - Exclusive: true, - Weight: 77, - }, - }, - }, - } - for _, tt := range tests { - fr, _ := testFramer() - if err := fr.WritePriority(streamID, tt.priority); err != nil { - t.Errorf("test %q: %v", tt.name, err) - continue - } - f, err := fr.ReadFrame() - if err != nil { - t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) - continue - } - if !reflect.DeepEqual(f, tt.wantFrame) { - t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) - } - } -} - -func TestWriteSettings(t *testing.T) { - fr, buf := testFramer() - settings := []Setting{{1, 2}, {3, 4}} - fr.WriteSettings(settings...) - const wantEnc = "\x00\x00\f\x04\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00\x00\x04" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - sf, ok := f.(*SettingsFrame) - if !ok { - t.Fatalf("Got a %T; want a SettingsFrame", f) - } - var got []Setting - sf.ForeachSetting(func(s Setting) error { - got = append(got, s) - valBack, ok := sf.Value(s.ID) - if !ok || valBack != s.Val { - t.Errorf("Value(%d) = %v, %v; want %v, true", s.ID, valBack, ok, s.Val) - } - return nil - }) - if !reflect.DeepEqual(settings, got) { - t.Errorf("Read settings %+v != written settings %+v", got, settings) - } -} - -func TestWriteSettingsAck(t *testing.T) { - fr, buf := testFramer() - fr.WriteSettingsAck() - const wantEnc = "\x00\x00\x00\x04\x01\x00\x00\x00\x00" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } -} - -func TestWriteWindowUpdate(t *testing.T) { - fr, buf := testFramer() - const streamID = 1<<24 + 2<<16 + 3<<8 + 4 - const incr = 7<<24 + 6<<16 + 5<<8 + 4 - if err := fr.WriteWindowUpdate(streamID, incr); err != nil { - t.Fatal(err) - } - const wantEnc = "\x00\x00\x04\x08\x00\x01\x02\x03\x04\x07\x06\x05\x04" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - want := &WindowUpdateFrame{ - FrameHeader: FrameHeader{ - valid: true, - Type: 0x8, - Flags: 0x0, - Length: 0x4, - StreamID: 0x1020304, - }, - Increment: 0x7060504, - } - if !reflect.DeepEqual(f, want) { - t.Errorf("parsed back %#v; want %#v", f, want) - } -} - -func TestWritePing(t *testing.T) { testWritePing(t, false) } -func TestWritePingAck(t *testing.T) { testWritePing(t, true) } - -func testWritePing(t *testing.T, ack bool) { - fr, buf := testFramer() - if err := fr.WritePing(ack, [8]byte{1, 2, 3, 4, 5, 6, 7, 8}); err != nil { - t.Fatal(err) - } - var wantFlags Flags - if ack { - wantFlags = FlagPingAck - } - var wantEnc = "\x00\x00\x08\x06" + string(wantFlags) + "\x00\x00\x00\x00" + "\x01\x02\x03\x04\x05\x06\x07\x08" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - want := &PingFrame{ - FrameHeader: FrameHeader{ - valid: true, - Type: 0x6, - Flags: wantFlags, - Length: 0x8, - StreamID: 0, - }, - Data: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}, - } - if !reflect.DeepEqual(f, want) { - t.Errorf("parsed back %#v; want %#v", f, want) - } -} - -func TestReadFrameHeader(t *testing.T) { - tests := []struct { - in string - want FrameHeader - }{ - {in: "\x00\x00\x00" + "\x00" + "\x00" + "\x00\x00\x00\x00", want: FrameHeader{}}, - {in: "\x01\x02\x03" + "\x04" + "\x05" + "\x06\x07\x08\x09", want: FrameHeader{ - Length: 66051, Type: 4, Flags: 5, StreamID: 101124105, - }}, - // Ignore high bit: - {in: "\xff\xff\xff" + "\xff" + "\xff" + "\xff\xff\xff\xff", want: FrameHeader{ - Length: 16777215, Type: 255, Flags: 255, StreamID: 2147483647}}, - {in: "\xff\xff\xff" + "\xff" + "\xff" + "\x7f\xff\xff\xff", want: FrameHeader{ - Length: 16777215, Type: 255, Flags: 255, StreamID: 2147483647}}, - } - for i, tt := range tests { - got, err := readFrameHeader(make([]byte, 9), strings.NewReader(tt.in)) - if err != nil { - t.Errorf("%d. readFrameHeader(%q) = %v", i, tt.in, err) - continue - } - tt.want.valid = true - if got != tt.want { - t.Errorf("%d. readFrameHeader(%q) = %+v; want %+v", i, tt.in, got, tt.want) - } - } -} - -func TestReadWriteFrameHeader(t *testing.T) { - tests := []struct { - len uint32 - typ FrameType - flags Flags - streamID uint32 - }{ - {len: 0, typ: 255, flags: 1, streamID: 0}, - {len: 0, typ: 255, flags: 1, streamID: 1}, - {len: 0, typ: 255, flags: 1, streamID: 255}, - {len: 0, typ: 255, flags: 1, streamID: 256}, - {len: 0, typ: 255, flags: 1, streamID: 65535}, - {len: 0, typ: 255, flags: 1, streamID: 65536}, - - {len: 0, typ: 1, flags: 255, streamID: 1}, - {len: 255, typ: 1, flags: 255, streamID: 1}, - {len: 256, typ: 1, flags: 255, streamID: 1}, - {len: 65535, typ: 1, flags: 255, streamID: 1}, - {len: 65536, typ: 1, flags: 255, streamID: 1}, - {len: 16777215, typ: 1, flags: 255, streamID: 1}, - } - for _, tt := range tests { - fr, buf := testFramer() - fr.startWrite(tt.typ, tt.flags, tt.streamID) - fr.writeBytes(make([]byte, tt.len)) - fr.endWrite() - fh, err := ReadFrameHeader(buf) - if err != nil { - t.Errorf("ReadFrameHeader(%+v) = %v", tt, err) - continue - } - if fh.Type != tt.typ || fh.Flags != tt.flags || fh.Length != tt.len || fh.StreamID != tt.streamID { - t.Errorf("ReadFrameHeader(%+v) = %+v; mismatch", tt, fh) - } - } - -} - -func TestWriteTooLargeFrame(t *testing.T) { - fr, _ := testFramer() - fr.startWrite(0, 1, 1) - fr.writeBytes(make([]byte, 1<<24)) - err := fr.endWrite() - if err != ErrFrameTooLarge { - t.Errorf("endWrite = %v; want errFrameTooLarge", err) - } -} - -func TestWriteGoAway(t *testing.T) { - const debug = "foo" - fr, buf := testFramer() - if err := fr.WriteGoAway(0x01020304, 0x05060708, []byte(debug)); err != nil { - t.Fatal(err) - } - const wantEnc = "\x00\x00\v\a\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08" + debug - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - want := &GoAwayFrame{ - FrameHeader: FrameHeader{ - valid: true, - Type: 0x7, - Flags: 0, - Length: uint32(4 + 4 + len(debug)), - StreamID: 0, - }, - LastStreamID: 0x01020304, - ErrCode: 0x05060708, - debugData: []byte(debug), - } - if !reflect.DeepEqual(f, want) { - t.Fatalf("parsed back:\n%#v\nwant:\n%#v", f, want) - } - if got := string(f.(*GoAwayFrame).DebugData()); got != debug { - t.Errorf("debug data = %q; want %q", got, debug) - } -} - -func TestWritePushPromise(t *testing.T) { - pp := PushPromiseParam{ - StreamID: 42, - PromiseID: 42, - BlockFragment: []byte("abc"), - } - fr, buf := testFramer() - if err := fr.WritePushPromise(pp); err != nil { - t.Fatal(err) - } - const wantEnc = "\x00\x00\x07\x05\x00\x00\x00\x00*\x00\x00\x00*abc" - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - _, ok := f.(*PushPromiseFrame) - if !ok { - t.Fatalf("got %T; want *PushPromiseFrame", f) - } - want := &PushPromiseFrame{ - FrameHeader: FrameHeader{ - valid: true, - Type: 0x5, - Flags: 0x0, - Length: 0x7, - StreamID: 42, - }, - PromiseID: 42, - headerFragBuf: []byte("abc"), - } - if !reflect.DeepEqual(f, want) { - t.Fatalf("parsed back:\n%#v\nwant:\n%#v", f, want) - } -} - -// test checkFrameOrder and that HEADERS and CONTINUATION frames can't be intermingled. -func TestReadFrameOrder(t *testing.T) { - head := func(f *Framer, id uint32, end bool) { - f.WriteHeaders(HeadersFrameParam{ - StreamID: id, - BlockFragment: []byte("foo"), // unused, but non-empty - EndHeaders: end, - }) - } - cont := func(f *Framer, id uint32, end bool) { - f.WriteContinuation(id, end, []byte("foo")) - } - - tests := [...]struct { - name string - w func(*Framer) - atLeast int - wantErr string - }{ - 0: { - w: func(f *Framer) { - head(f, 1, true) - }, - }, - 1: { - w: func(f *Framer) { - head(f, 1, true) - head(f, 2, true) - }, - }, - 2: { - wantErr: "got HEADERS for stream 2; expected CONTINUATION following HEADERS for stream 1", - w: func(f *Framer) { - head(f, 1, false) - head(f, 2, true) - }, - }, - 3: { - wantErr: "got DATA for stream 1; expected CONTINUATION following HEADERS for stream 1", - w: func(f *Framer) { - head(f, 1, false) - }, - }, - 4: { - w: func(f *Framer) { - head(f, 1, false) - cont(f, 1, true) - head(f, 2, true) - }, - }, - 5: { - wantErr: "got CONTINUATION for stream 2; expected stream 1", - w: func(f *Framer) { - head(f, 1, false) - cont(f, 2, true) - head(f, 2, true) - }, - }, - 6: { - wantErr: "unexpected CONTINUATION for stream 1", - w: func(f *Framer) { - cont(f, 1, true) - }, - }, - 7: { - wantErr: "unexpected CONTINUATION for stream 1", - w: func(f *Framer) { - cont(f, 1, false) - }, - }, - 8: { - wantErr: "HEADERS frame with stream ID 0", - w: func(f *Framer) { - head(f, 0, true) - }, - }, - 9: { - wantErr: "CONTINUATION frame with stream ID 0", - w: func(f *Framer) { - cont(f, 0, true) - }, - }, - 10: { - wantErr: "unexpected CONTINUATION for stream 1", - atLeast: 5, - w: func(f *Framer) { - head(f, 1, false) - cont(f, 1, false) - cont(f, 1, false) - cont(f, 1, false) - cont(f, 1, true) - cont(f, 1, false) - }, - }, - } - for i, tt := range tests { - buf := new(bytes.Buffer) - f := NewFramer(buf, buf) - f.AllowIllegalWrites = true - tt.w(f) - f.WriteData(1, true, nil) // to test transition away from last step - - var err error - n := 0 - var log bytes.Buffer - for { - var got Frame - got, err = f.ReadFrame() - fmt.Fprintf(&log, " read %v, %v\n", got, err) - if err != nil { - break - } - n++ - } - if err == io.EOF { - err = nil - } - ok := tt.wantErr == "" - if ok && err != nil { - t.Errorf("%d. after %d good frames, ReadFrame = %v; want success\n%s", i, n, err, log.Bytes()) - continue - } - if !ok && err != ConnectionError(ErrCodeProtocol) { - t.Errorf("%d. after %d good frames, ReadFrame = %v; want ConnectionError(ErrCodeProtocol)\n%s", i, n, err, log.Bytes()) - continue - } - if !((f.errDetail == nil && tt.wantErr == "") || (fmt.Sprint(f.errDetail) == tt.wantErr)) { - t.Errorf("%d. framer eror = %q; want %q\n%s", i, f.errDetail, tt.wantErr, log.Bytes()) - } - if n < tt.atLeast { - t.Errorf("%d. framer only read %d frames; want at least %d\n%s", i, n, tt.atLeast, log.Bytes()) - } - } -} - -func TestMetaFrameHeader(t *testing.T) { - write := func(f *Framer, frags ...[]byte) { - for i, frag := range frags { - end := (i == len(frags)-1) - if i == 0 { - f.WriteHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: frag, - EndHeaders: end, - }) - } else { - f.WriteContinuation(1, end, frag) - } - } - } - - want := func(flags Flags, length uint32, pairs ...string) *MetaHeadersFrame { - mh := &MetaHeadersFrame{ - HeadersFrame: &HeadersFrame{ - FrameHeader: FrameHeader{ - Type: FrameHeaders, - Flags: flags, - Length: length, - StreamID: 1, - }, - }, - Fields: []hpack.HeaderField(nil), - } - for len(pairs) > 0 { - mh.Fields = append(mh.Fields, hpack.HeaderField{ - Name: pairs[0], - Value: pairs[1], - }) - pairs = pairs[2:] - } - return mh - } - truncated := func(mh *MetaHeadersFrame) *MetaHeadersFrame { - mh.Truncated = true - return mh - } - - const noFlags Flags = 0 - - oneKBString := strings.Repeat("a", 1<<10) - - tests := [...]struct { - name string - w func(*Framer) - want interface{} // *MetaHeaderFrame or error - wantErrReason string - maxHeaderListSize uint32 - }{ - 0: { - name: "single_headers", - w: func(f *Framer) { - var he hpackEncoder - all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/") - write(f, all) - }, - want: want(FlagHeadersEndHeaders, 2, ":method", "GET", ":path", "/"), - }, - 1: { - name: "with_continuation", - w: func(f *Framer) { - var he hpackEncoder - all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", "bar") - write(f, all[:1], all[1:]) - }, - want: want(noFlags, 1, ":method", "GET", ":path", "/", "foo", "bar"), - }, - 2: { - name: "with_two_continuation", - w: func(f *Framer) { - var he hpackEncoder - all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", "bar") - write(f, all[:2], all[2:4], all[4:]) - }, - want: want(noFlags, 2, ":method", "GET", ":path", "/", "foo", "bar"), - }, - 3: { - name: "big_string_okay", - w: func(f *Framer) { - var he hpackEncoder - all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", oneKBString) - write(f, all[:2], all[2:]) - }, - want: want(noFlags, 2, ":method", "GET", ":path", "/", "foo", oneKBString), - }, - 4: { - name: "big_string_error", - w: func(f *Framer) { - var he hpackEncoder - all := he.encodeHeaderRaw(t, ":method", "GET", ":path", "/", "foo", oneKBString) - write(f, all[:2], all[2:]) - }, - maxHeaderListSize: (1 << 10) / 2, - want: ConnectionError(ErrCodeCompression), - }, - 5: { - name: "max_header_list_truncated", - w: func(f *Framer) { - var he hpackEncoder - var pairs = []string{":method", "GET", ":path", "/"} - for i := 0; i < 100; i++ { - pairs = append(pairs, "foo", "bar") - } - all := he.encodeHeaderRaw(t, pairs...) - write(f, all[:2], all[2:]) - }, - maxHeaderListSize: (1 << 10) / 2, - want: truncated(want(noFlags, 2, - ":method", "GET", - ":path", "/", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", - "foo", "bar", // 11 - )), - }, - 6: { - name: "pseudo_order", - w: func(f *Framer) { - write(f, encodeHeaderRaw(t, - ":method", "GET", - "foo", "bar", - ":path", "/", // bogus - )) - }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "pseudo header field after regular", - }, - 7: { - name: "pseudo_unknown", - w: func(f *Framer) { - write(f, encodeHeaderRaw(t, - ":unknown", "foo", // bogus - "foo", "bar", - )) - }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "invalid pseudo-header \":unknown\"", - }, - 8: { - name: "pseudo_mix_request_response", - w: func(f *Framer) { - write(f, encodeHeaderRaw(t, - ":method", "GET", - ":status", "100", - )) - }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "mix of request and response pseudo headers", - }, - 9: { - name: "pseudo_dup", - w: func(f *Framer) { - write(f, encodeHeaderRaw(t, - ":method", "GET", - ":method", "POST", - )) - }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "duplicate pseudo-header \":method\"", - }, - 10: { - name: "trailer_okay_no_pseudo", - w: func(f *Framer) { write(f, encodeHeaderRaw(t, "foo", "bar")) }, - want: want(FlagHeadersEndHeaders, 8, "foo", "bar"), - }, - 11: { - name: "invalid_field_name", - w: func(f *Framer) { write(f, encodeHeaderRaw(t, "CapitalBad", "x")) }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "invalid header field name \"CapitalBad\"", - }, - 12: { - name: "invalid_field_value", - w: func(f *Framer) { write(f, encodeHeaderRaw(t, "key", "bad_null\x00")) }, - want: streamError(1, ErrCodeProtocol), - wantErrReason: "invalid header field value \"bad_null\\x00\"", - }, - } - for i, tt := range tests { - buf := new(bytes.Buffer) - f := NewFramer(buf, buf) - f.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil) - f.MaxHeaderListSize = tt.maxHeaderListSize - tt.w(f) - - name := tt.name - if name == "" { - name = fmt.Sprintf("test index %d", i) - } - - var got interface{} - var err error - got, err = f.ReadFrame() - if err != nil { - got = err - - // Ignore the StreamError.Cause field, if it matches the wantErrReason. - // The test table above predates the Cause field. - if se, ok := err.(StreamError); ok && se.Cause != nil && se.Cause.Error() == tt.wantErrReason { - se.Cause = nil - got = se - } - } - if !reflect.DeepEqual(got, tt.want) { - if mhg, ok := got.(*MetaHeadersFrame); ok { - if mhw, ok := tt.want.(*MetaHeadersFrame); ok { - hg := mhg.HeadersFrame - hw := mhw.HeadersFrame - if hg != nil && hw != nil && !reflect.DeepEqual(*hg, *hw) { - t.Errorf("%s: headers differ:\n got: %+v\nwant: %+v\n", name, *hg, *hw) - } - } - } - str := func(v interface{}) string { - if _, ok := v.(error); ok { - return fmt.Sprintf("error %v", v) - } else { - return fmt.Sprintf("value %#v", v) - } - } - t.Errorf("%s:\n got: %v\nwant: %s", name, str(got), str(tt.want)) - } - if tt.wantErrReason != "" && tt.wantErrReason != fmt.Sprint(f.errDetail) { - t.Errorf("%s: got error reason %q; want %q", name, f.errDetail, tt.wantErrReason) - } - } -} - -func TestSetReuseFrames(t *testing.T) { - fr, buf := testFramer() - fr.SetReuseFrames() - - // Check that DataFrames are reused. Note that - // SetReuseFrames only currently implements reuse of DataFrames. - firstDf := readAndVerifyDataFrame("ABC", 3, fr, buf, t) - - for i := 0; i < 10; i++ { - df := readAndVerifyDataFrame("XYZ", 3, fr, buf, t) - if df != firstDf { - t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) - } - } - - for i := 0; i < 10; i++ { - df := readAndVerifyDataFrame("", 0, fr, buf, t) - if df != firstDf { - t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) - } - } - - for i := 0; i < 10; i++ { - df := readAndVerifyDataFrame("HHH", 3, fr, buf, t) - if df != firstDf { - t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) - } - } -} - -func TestSetReuseFramesMoreThanOnce(t *testing.T) { - fr, buf := testFramer() - fr.SetReuseFrames() - - firstDf := readAndVerifyDataFrame("ABC", 3, fr, buf, t) - fr.SetReuseFrames() - - for i := 0; i < 10; i++ { - df := readAndVerifyDataFrame("XYZ", 3, fr, buf, t) - // SetReuseFrames should be idempotent - fr.SetReuseFrames() - if df != firstDf { - t.Errorf("Expected Framer to return references to the same DataFrame. Have %v and %v", &df, &firstDf) - } - } -} - -func TestNoSetReuseFrames(t *testing.T) { - fr, buf := testFramer() - const numNewDataFrames = 10 - dfSoFar := make([]interface{}, numNewDataFrames) - - // Check that DataFrames are not reused if SetReuseFrames wasn't called. - // SetReuseFrames only currently implements reuse of DataFrames. - for i := 0; i < numNewDataFrames; i++ { - df := readAndVerifyDataFrame("XYZ", 3, fr, buf, t) - for _, item := range dfSoFar { - if df == item { - t.Errorf("Expected Framer to return new DataFrames since SetNoReuseFrames not set.") - } - } - dfSoFar[i] = df - } -} - -func readAndVerifyDataFrame(data string, length byte, fr *Framer, buf *bytes.Buffer, t *testing.T) *DataFrame { - var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 - fr.WriteData(streamID, true, []byte(data)) - wantEnc := "\x00\x00" + string(length) + "\x00\x01\x01\x02\x03\x04" + data - if buf.String() != wantEnc { - t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) - } - f, err := fr.ReadFrame() - if err != nil { - t.Fatal(err) - } - df, ok := f.(*DataFrame) - if !ok { - t.Fatalf("got %T; want *DataFrame", f) - } - if !bytes.Equal(df.Data(), []byte(data)) { - t.Errorf("got %q; want %q", df.Data(), []byte(data)) - } - if f.Header().Flags&1 == 0 { - t.Errorf("didn't see END_STREAM flag") - } - return df -} - -func encodeHeaderRaw(t *testing.T, pairs ...string) []byte { - var he hpackEncoder - return he.encodeHeaderRaw(t, pairs...) -} diff --git a/vendor/golang.org/x/net/http2/go18_test.go b/vendor/golang.org/x/net/http2/go18_test.go deleted file mode 100644 index 30e3b038bf..0000000000 --- a/vendor/golang.org/x/net/http2/go18_test.go +++ /dev/null @@ -1,79 +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. - -// +build go1.8 - -package http2 - -import ( - "crypto/tls" - "net/http" - "testing" - "time" -) - -// Tests that http2.Server.IdleTimeout is initialized from -// http.Server.{Idle,Read}Timeout. http.Server.IdleTimeout was -// added in Go 1.8. -func TestConfigureServerIdleTimeout_Go18(t *testing.T) { - const timeout = 5 * time.Second - const notThisOne = 1 * time.Second - - // With a zero http2.Server, verify that it copies IdleTimeout: - { - s1 := &http.Server{ - IdleTimeout: timeout, - ReadTimeout: notThisOne, - } - s2 := &Server{} - if err := ConfigureServer(s1, s2); err != nil { - t.Fatal(err) - } - if s2.IdleTimeout != timeout { - t.Errorf("s2.IdleTimeout = %v; want %v", s2.IdleTimeout, timeout) - } - } - - // And that it falls back to ReadTimeout: - { - s1 := &http.Server{ - ReadTimeout: timeout, - } - s2 := &Server{} - if err := ConfigureServer(s1, s2); err != nil { - t.Fatal(err) - } - if s2.IdleTimeout != timeout { - t.Errorf("s2.IdleTimeout = %v; want %v", s2.IdleTimeout, timeout) - } - } - - // Verify that s1's IdleTimeout doesn't overwrite an existing setting: - { - s1 := &http.Server{ - IdleTimeout: notThisOne, - } - s2 := &Server{ - IdleTimeout: timeout, - } - if err := ConfigureServer(s1, s2); err != nil { - t.Fatal(err) - } - if s2.IdleTimeout != timeout { - t.Errorf("s2.IdleTimeout = %v; want %v", s2.IdleTimeout, timeout) - } - } -} - -func TestCertClone(t *testing.T) { - c := &tls.Config{ - GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { - panic("shouldn't be called") - }, - } - c2 := cloneTLSConfig(c) - if c2.GetClientCertificate == nil { - t.Error("GetClientCertificate is nil") - } -} diff --git a/vendor/golang.org/x/net/http2/go19_test.go b/vendor/golang.org/x/net/http2/go19_test.go deleted file mode 100644 index 1675d248f0..0000000000 --- a/vendor/golang.org/x/net/http2/go19_test.go +++ /dev/null @@ -1,60 +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. - -// +build go1.9 - -package http2 - -import ( - "context" - "net/http" - "reflect" - "testing" - "time" -) - -func TestServerGracefulShutdown(t *testing.T) { - var st *serverTester - handlerDone := make(chan struct{}) - st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - defer close(handlerDone) - go st.ts.Config.Shutdown(context.Background()) - - ga := st.wantGoAway() - if ga.ErrCode != ErrCodeNo { - t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode) - } - if ga.LastStreamID != 1 { - t.Errorf("GOAWAY LastStreamID = %v; want 1", ga.LastStreamID) - } - - w.Header().Set("x-foo", "bar") - }) - defer st.Close() - - st.greet() - st.bodylessReq1() - - select { - case <-handlerDone: - case <-time.After(5 * time.Second): - t.Fatalf("server did not shutdown?") - } - hf := st.wantHeaders() - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"x-foo", "bar"}, - {"content-type", "text/plain; charset=utf-8"}, - {"content-length", "0"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - - n, err := st.cc.Read([]byte{0}) - if n != 0 || err == nil { - t.Errorf("Read = %v, %v; want 0, non-nil", n, err) - } -} diff --git a/vendor/golang.org/x/net/http2/gotrack_test.go b/vendor/golang.org/x/net/http2/gotrack_test.go deleted file mode 100644 index 06db61231d..0000000000 --- a/vendor/golang.org/x/net/http2/gotrack_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2014 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 http2 - -import ( - "fmt" - "strings" - "testing" -) - -func TestGoroutineLock(t *testing.T) { - oldDebug := DebugGoroutines - DebugGoroutines = true - defer func() { DebugGoroutines = oldDebug }() - - g := newGoroutineLock() - g.check() - - sawPanic := make(chan interface{}) - go func() { - defer func() { sawPanic <- recover() }() - g.check() // should panic - }() - e := <-sawPanic - if e == nil { - t.Fatal("did not see panic from check in other goroutine") - } - if !strings.Contains(fmt.Sprint(e), "wrong goroutine") { - t.Errorf("expected on see panic about running on the wrong goroutine; got %v", e) - } -} diff --git a/vendor/golang.org/x/net/http2/hpack/encode.go b/vendor/golang.org/x/net/http2/hpack/encode.go index 54726c2a3c..1565cf2702 100644 --- a/vendor/golang.org/x/net/http2/hpack/encode.go +++ b/vendor/golang.org/x/net/http2/hpack/encode.go @@ -206,7 +206,7 @@ func appendVarInt(dst []byte, n byte, i uint64) []byte { } // appendHpackString appends s, as encoded in "String Literal" -// representation, to dst and returns the the extended buffer. +// representation, to dst and returns the extended buffer. // // s will be encoded in Huffman codes only when it produces strictly // shorter byte string. diff --git a/vendor/golang.org/x/net/http2/hpack/encode_test.go b/vendor/golang.org/x/net/http2/hpack/encode_test.go deleted file mode 100644 index 05f12db9cd..0000000000 --- a/vendor/golang.org/x/net/http2/hpack/encode_test.go +++ /dev/null @@ -1,386 +0,0 @@ -// Copyright 2014 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 hpack - -import ( - "bytes" - "encoding/hex" - "fmt" - "math/rand" - "reflect" - "strings" - "testing" -) - -func TestEncoderTableSizeUpdate(t *testing.T) { - tests := []struct { - size1, size2 uint32 - wantHex string - }{ - // Should emit 2 table size updates (2048 and 4096) - {2048, 4096, "3fe10f 3fe11f 82"}, - - // Should emit 1 table size update (2048) - {16384, 2048, "3fe10f 82"}, - } - for _, tt := range tests { - var buf bytes.Buffer - e := NewEncoder(&buf) - e.SetMaxDynamicTableSize(tt.size1) - e.SetMaxDynamicTableSize(tt.size2) - if err := e.WriteField(pair(":method", "GET")); err != nil { - t.Fatal(err) - } - want := removeSpace(tt.wantHex) - if got := hex.EncodeToString(buf.Bytes()); got != want { - t.Errorf("e.SetDynamicTableSize %v, %v = %q; want %q", tt.size1, tt.size2, got, want) - } - } -} - -func TestEncoderWriteField(t *testing.T) { - var buf bytes.Buffer - e := NewEncoder(&buf) - var got []HeaderField - d := NewDecoder(4<<10, func(f HeaderField) { - got = append(got, f) - }) - - tests := []struct { - hdrs []HeaderField - }{ - {[]HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - }}, - {[]HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - pair("cache-control", "no-cache"), - }}, - {[]HeaderField{ - pair(":method", "GET"), - pair(":scheme", "https"), - pair(":path", "/index.html"), - pair(":authority", "www.example.com"), - pair("custom-key", "custom-value"), - }}, - } - for i, tt := range tests { - buf.Reset() - got = got[:0] - for _, hf := range tt.hdrs { - if err := e.WriteField(hf); err != nil { - t.Fatal(err) - } - } - _, err := d.Write(buf.Bytes()) - if err != nil { - t.Errorf("%d. Decoder Write = %v", i, err) - } - if !reflect.DeepEqual(got, tt.hdrs) { - t.Errorf("%d. Decoded %+v; want %+v", i, got, tt.hdrs) - } - } -} - -func TestEncoderSearchTable(t *testing.T) { - e := NewEncoder(nil) - - e.dynTab.add(pair("foo", "bar")) - e.dynTab.add(pair("blake", "miz")) - e.dynTab.add(pair(":method", "GET")) - - tests := []struct { - hf HeaderField - wantI uint64 - wantMatch bool - }{ - // Name and Value match - {pair("foo", "bar"), uint64(staticTable.len()) + 3, true}, - {pair("blake", "miz"), uint64(staticTable.len()) + 2, true}, - {pair(":method", "GET"), 2, true}, - - // Only name match because Sensitive == true. This is allowed to match - // any ":method" entry. The current implementation uses the last entry - // added in newStaticTable. - {HeaderField{":method", "GET", true}, 3, false}, - - // Only Name matches - {pair("foo", "..."), uint64(staticTable.len()) + 3, false}, - {pair("blake", "..."), uint64(staticTable.len()) + 2, false}, - // As before, this is allowed to match any ":method" entry. - {pair(":method", "..."), 3, false}, - - // None match - {pair("foo-", "bar"), 0, false}, - } - for _, tt := range tests { - if gotI, gotMatch := e.searchTable(tt.hf); gotI != tt.wantI || gotMatch != tt.wantMatch { - t.Errorf("d.search(%+v) = %v, %v; want %v, %v", tt.hf, gotI, gotMatch, tt.wantI, tt.wantMatch) - } - } -} - -func TestAppendVarInt(t *testing.T) { - tests := []struct { - n byte - i uint64 - want []byte - }{ - // Fits in a byte: - {1, 0, []byte{0}}, - {2, 2, []byte{2}}, - {3, 6, []byte{6}}, - {4, 14, []byte{14}}, - {5, 30, []byte{30}}, - {6, 62, []byte{62}}, - {7, 126, []byte{126}}, - {8, 254, []byte{254}}, - - // Multiple bytes: - {5, 1337, []byte{31, 154, 10}}, - } - for _, tt := range tests { - got := appendVarInt(nil, tt.n, tt.i) - if !bytes.Equal(got, tt.want) { - t.Errorf("appendVarInt(nil, %v, %v) = %v; want %v", tt.n, tt.i, got, tt.want) - } - } -} - -func TestAppendHpackString(t *testing.T) { - tests := []struct { - s, wantHex string - }{ - // Huffman encoded - {"www.example.com", "8c f1e3 c2e5 f23a 6ba0 ab90 f4ff"}, - - // Not Huffman encoded - {"a", "01 61"}, - - // zero length - {"", "00"}, - } - for _, tt := range tests { - want := removeSpace(tt.wantHex) - buf := appendHpackString(nil, tt.s) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("appendHpackString(nil, %q) = %q; want %q", tt.s, got, want) - } - } -} - -func TestAppendIndexed(t *testing.T) { - tests := []struct { - i uint64 - wantHex string - }{ - // 1 byte - {1, "81"}, - {126, "fe"}, - - // 2 bytes - {127, "ff00"}, - {128, "ff01"}, - } - for _, tt := range tests { - want := removeSpace(tt.wantHex) - buf := appendIndexed(nil, tt.i) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("appendIndex(nil, %v) = %q; want %q", tt.i, got, want) - } - } -} - -func TestAppendNewName(t *testing.T) { - tests := []struct { - f HeaderField - indexing bool - wantHex string - }{ - // Incremental indexing - {HeaderField{"custom-key", "custom-value", false}, true, "40 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, - - // Without indexing - {HeaderField{"custom-key", "custom-value", false}, false, "00 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, - - // Never indexed - {HeaderField{"custom-key", "custom-value", true}, true, "10 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, - {HeaderField{"custom-key", "custom-value", true}, false, "10 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, - } - for _, tt := range tests { - want := removeSpace(tt.wantHex) - buf := appendNewName(nil, tt.f, tt.indexing) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("appendNewName(nil, %+v, %v) = %q; want %q", tt.f, tt.indexing, got, want) - } - } -} - -func TestAppendIndexedName(t *testing.T) { - tests := []struct { - f HeaderField - i uint64 - indexing bool - wantHex string - }{ - // Incremental indexing - {HeaderField{":status", "302", false}, 8, true, "48 82 6402"}, - - // Without indexing - {HeaderField{":status", "302", false}, 8, false, "08 82 6402"}, - - // Never indexed - {HeaderField{":status", "302", true}, 8, true, "18 82 6402"}, - {HeaderField{":status", "302", true}, 8, false, "18 82 6402"}, - } - for _, tt := range tests { - want := removeSpace(tt.wantHex) - buf := appendIndexedName(nil, tt.f, tt.i, tt.indexing) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("appendIndexedName(nil, %+v, %v) = %q; want %q", tt.f, tt.indexing, got, want) - } - } -} - -func TestAppendTableSize(t *testing.T) { - tests := []struct { - i uint32 - wantHex string - }{ - // Fits into 1 byte - {30, "3e"}, - - // Extra byte - {31, "3f00"}, - {32, "3f01"}, - } - for _, tt := range tests { - want := removeSpace(tt.wantHex) - buf := appendTableSize(nil, tt.i) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("appendTableSize(nil, %v) = %q; want %q", tt.i, got, want) - } - } -} - -func TestEncoderSetMaxDynamicTableSize(t *testing.T) { - var buf bytes.Buffer - e := NewEncoder(&buf) - tests := []struct { - v uint32 - wantUpdate bool - wantMinSize uint32 - wantMaxSize uint32 - }{ - // Set new table size to 2048 - {2048, true, 2048, 2048}, - - // Set new table size to 16384, but still limited to - // 4096 - {16384, true, 2048, 4096}, - } - for _, tt := range tests { - e.SetMaxDynamicTableSize(tt.v) - if got := e.tableSizeUpdate; tt.wantUpdate != got { - t.Errorf("e.tableSizeUpdate = %v; want %v", got, tt.wantUpdate) - } - if got := e.minSize; tt.wantMinSize != got { - t.Errorf("e.minSize = %v; want %v", got, tt.wantMinSize) - } - if got := e.dynTab.maxSize; tt.wantMaxSize != got { - t.Errorf("e.maxSize = %v; want %v", got, tt.wantMaxSize) - } - } -} - -func TestEncoderSetMaxDynamicTableSizeLimit(t *testing.T) { - e := NewEncoder(nil) - // 4095 < initialHeaderTableSize means maxSize is truncated to - // 4095. - e.SetMaxDynamicTableSizeLimit(4095) - if got, want := e.dynTab.maxSize, uint32(4095); got != want { - t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) - } - if got, want := e.maxSizeLimit, uint32(4095); got != want { - t.Errorf("e.maxSizeLimit = %v; want %v", got, want) - } - if got, want := e.tableSizeUpdate, true; got != want { - t.Errorf("e.tableSizeUpdate = %v; want %v", got, want) - } - // maxSize will be truncated to maxSizeLimit - e.SetMaxDynamicTableSize(16384) - if got, want := e.dynTab.maxSize, uint32(4095); got != want { - t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) - } - // 8192 > current maxSizeLimit, so maxSize does not change. - e.SetMaxDynamicTableSizeLimit(8192) - if got, want := e.dynTab.maxSize, uint32(4095); got != want { - t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) - } - if got, want := e.maxSizeLimit, uint32(8192); got != want { - t.Errorf("e.maxSizeLimit = %v; want %v", got, want) - } -} - -func removeSpace(s string) string { - return strings.Replace(s, " ", "", -1) -} - -func BenchmarkEncoderSearchTable(b *testing.B) { - e := NewEncoder(nil) - - // A sample of possible header fields. - // This is not based on any actual data from HTTP/2 traces. - var possible []HeaderField - for _, f := range staticTable.ents { - if f.Value == "" { - possible = append(possible, f) - continue - } - // Generate 5 random values, except for cookie and set-cookie, - // which we know can have many values in practice. - num := 5 - if f.Name == "cookie" || f.Name == "set-cookie" { - num = 25 - } - for i := 0; i < num; i++ { - f.Value = fmt.Sprintf("%s-%d", f.Name, i) - possible = append(possible, f) - } - } - for k := 0; k < 10; k++ { - f := HeaderField{ - Name: fmt.Sprintf("x-header-%d", k), - Sensitive: rand.Int()%2 == 0, - } - for i := 0; i < 5; i++ { - f.Value = fmt.Sprintf("%s-%d", f.Name, i) - possible = append(possible, f) - } - } - - // Add a random sample to the dynamic table. This very loosely simulates - // a history of 100 requests with 20 header fields per request. - for r := 0; r < 100*20; r++ { - f := possible[rand.Int31n(int32(len(possible)))] - // Skip if this is in the staticTable verbatim. - if _, has := staticTable.search(f); !has { - e.dynTab.add(f) - } - } - - b.ResetTimer() - for n := 0; n < b.N; n++ { - for _, f := range possible { - e.searchTable(f) - } - } -} diff --git a/vendor/golang.org/x/net/http2/hpack/hpack.go b/vendor/golang.org/x/net/http2/hpack/hpack.go index 176644acda..166788ceec 100644 --- a/vendor/golang.org/x/net/http2/hpack/hpack.go +++ b/vendor/golang.org/x/net/http2/hpack/hpack.go @@ -389,6 +389,12 @@ func (d *Decoder) callEmit(hf HeaderField) error { // (same invariants and behavior as parseHeaderFieldRepr) func (d *Decoder) parseDynamicTableSizeUpdate() error { + // RFC 7541, sec 4.2: This dynamic table size update MUST occur at the + // beginning of the first header block following the change to the dynamic table size. + if d.dynTab.size > 0 { + return DecodingError{errors.New("dynamic table size update MUST occur at the beginning of a header block")} + } + buf := d.buf size, buf, err := readVarInt(5, buf) if err != nil { diff --git a/vendor/golang.org/x/net/http2/hpack/hpack_test.go b/vendor/golang.org/x/net/http2/hpack/hpack_test.go deleted file mode 100644 index bc7f476782..0000000000 --- a/vendor/golang.org/x/net/http2/hpack/hpack_test.go +++ /dev/null @@ -1,722 +0,0 @@ -// Copyright 2014 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 hpack - -import ( - "bytes" - "encoding/hex" - "fmt" - "math/rand" - "reflect" - "strings" - "testing" - "time" -) - -func (d *Decoder) mustAt(idx int) HeaderField { - if hf, ok := d.at(uint64(idx)); !ok { - panic(fmt.Sprintf("bogus index %d", idx)) - } else { - return hf - } -} - -func TestDynamicTableAt(t *testing.T) { - d := NewDecoder(4096, nil) - at := d.mustAt - if got, want := at(2), (pair(":method", "GET")); got != want { - t.Errorf("at(2) = %v; want %v", got, want) - } - d.dynTab.add(pair("foo", "bar")) - d.dynTab.add(pair("blake", "miz")) - if got, want := at(staticTable.len()+1), (pair("blake", "miz")); got != want { - t.Errorf("at(dyn 1) = %v; want %v", got, want) - } - if got, want := at(staticTable.len()+2), (pair("foo", "bar")); got != want { - t.Errorf("at(dyn 2) = %v; want %v", got, want) - } - if got, want := at(3), (pair(":method", "POST")); got != want { - t.Errorf("at(3) = %v; want %v", got, want) - } -} - -func TestDynamicTableSizeEvict(t *testing.T) { - d := NewDecoder(4096, nil) - if want := uint32(0); d.dynTab.size != want { - t.Fatalf("size = %d; want %d", d.dynTab.size, want) - } - add := d.dynTab.add - add(pair("blake", "eats pizza")) - if want := uint32(15 + 32); d.dynTab.size != want { - t.Fatalf("after pizza, size = %d; want %d", d.dynTab.size, want) - } - add(pair("foo", "bar")) - if want := uint32(15 + 32 + 6 + 32); d.dynTab.size != want { - t.Fatalf("after foo bar, size = %d; want %d", d.dynTab.size, want) - } - d.dynTab.setMaxSize(15 + 32 + 1 /* slop */) - if want := uint32(6 + 32); d.dynTab.size != want { - t.Fatalf("after setMaxSize, size = %d; want %d", d.dynTab.size, want) - } - if got, want := d.mustAt(staticTable.len()+1), (pair("foo", "bar")); got != want { - t.Errorf("at(dyn 1) = %v; want %v", got, want) - } - add(pair("long", strings.Repeat("x", 500))) - if want := uint32(0); d.dynTab.size != want { - t.Fatalf("after big one, size = %d; want %d", d.dynTab.size, want) - } -} - -func TestDecoderDecode(t *testing.T) { - tests := []struct { - name string - in []byte - want []HeaderField - wantDynTab []HeaderField // newest entry first - }{ - // C.2.1 Literal Header Field with Indexing - // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.1 - {"C.2.1", dehex("400a 6375 7374 6f6d 2d6b 6579 0d63 7573 746f 6d2d 6865 6164 6572"), - []HeaderField{pair("custom-key", "custom-header")}, - []HeaderField{pair("custom-key", "custom-header")}, - }, - - // C.2.2 Literal Header Field without Indexing - // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.2 - {"C.2.2", dehex("040c 2f73 616d 706c 652f 7061 7468"), - []HeaderField{pair(":path", "/sample/path")}, - []HeaderField{}}, - - // C.2.3 Literal Header Field never Indexed - // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.3 - {"C.2.3", dehex("1008 7061 7373 776f 7264 0673 6563 7265 74"), - []HeaderField{{"password", "secret", true}}, - []HeaderField{}}, - - // C.2.4 Indexed Header Field - // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.4 - {"C.2.4", []byte("\x82"), - []HeaderField{pair(":method", "GET")}, - []HeaderField{}}, - } - for _, tt := range tests { - d := NewDecoder(4096, nil) - hf, err := d.DecodeFull(tt.in) - if err != nil { - t.Errorf("%s: %v", tt.name, err) - continue - } - if !reflect.DeepEqual(hf, tt.want) { - t.Errorf("%s: Got %v; want %v", tt.name, hf, tt.want) - } - gotDynTab := d.dynTab.reverseCopy() - if !reflect.DeepEqual(gotDynTab, tt.wantDynTab) { - t.Errorf("%s: dynamic table after = %v; want %v", tt.name, gotDynTab, tt.wantDynTab) - } - } -} - -func (dt *dynamicTable) reverseCopy() (hf []HeaderField) { - hf = make([]HeaderField, len(dt.table.ents)) - for i := range hf { - hf[i] = dt.table.ents[len(dt.table.ents)-1-i] - } - return -} - -type encAndWant struct { - enc []byte - want []HeaderField - wantDynTab []HeaderField - wantDynSize uint32 -} - -// C.3 Request Examples without Huffman Coding -// http://http2.github.io/http2-spec/compression.html#rfc.section.C.3 -func TestDecodeC3_NoHuffman(t *testing.T) { - testDecodeSeries(t, 4096, []encAndWant{ - {dehex("8286 8441 0f77 7777 2e65 7861 6d70 6c65 2e63 6f6d"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - }, - []HeaderField{ - pair(":authority", "www.example.com"), - }, - 57, - }, - {dehex("8286 84be 5808 6e6f 2d63 6163 6865"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - pair("cache-control", "no-cache"), - }, - []HeaderField{ - pair("cache-control", "no-cache"), - pair(":authority", "www.example.com"), - }, - 110, - }, - {dehex("8287 85bf 400a 6375 7374 6f6d 2d6b 6579 0c63 7573 746f 6d2d 7661 6c75 65"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "https"), - pair(":path", "/index.html"), - pair(":authority", "www.example.com"), - pair("custom-key", "custom-value"), - }, - []HeaderField{ - pair("custom-key", "custom-value"), - pair("cache-control", "no-cache"), - pair(":authority", "www.example.com"), - }, - 164, - }, - }) -} - -// C.4 Request Examples with Huffman Coding -// http://http2.github.io/http2-spec/compression.html#rfc.section.C.4 -func TestDecodeC4_Huffman(t *testing.T) { - testDecodeSeries(t, 4096, []encAndWant{ - {dehex("8286 8441 8cf1 e3c2 e5f2 3a6b a0ab 90f4 ff"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - }, - []HeaderField{ - pair(":authority", "www.example.com"), - }, - 57, - }, - {dehex("8286 84be 5886 a8eb 1064 9cbf"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "http"), - pair(":path", "/"), - pair(":authority", "www.example.com"), - pair("cache-control", "no-cache"), - }, - []HeaderField{ - pair("cache-control", "no-cache"), - pair(":authority", "www.example.com"), - }, - 110, - }, - {dehex("8287 85bf 4088 25a8 49e9 5ba9 7d7f 8925 a849 e95b b8e8 b4bf"), - []HeaderField{ - pair(":method", "GET"), - pair(":scheme", "https"), - pair(":path", "/index.html"), - pair(":authority", "www.example.com"), - pair("custom-key", "custom-value"), - }, - []HeaderField{ - pair("custom-key", "custom-value"), - pair("cache-control", "no-cache"), - pair(":authority", "www.example.com"), - }, - 164, - }, - }) -} - -// http://http2.github.io/http2-spec/compression.html#rfc.section.C.5 -// "This section shows several consecutive header lists, corresponding -// to HTTP responses, on the same connection. The HTTP/2 setting -// parameter SETTINGS_HEADER_TABLE_SIZE is set to the value of 256 -// octets, causing some evictions to occur." -func TestDecodeC5_ResponsesNoHuff(t *testing.T) { - testDecodeSeries(t, 256, []encAndWant{ - {dehex(` -4803 3330 3258 0770 7269 7661 7465 611d -4d6f 6e2c 2032 3120 4f63 7420 3230 3133 -2032 303a 3133 3a32 3120 474d 546e 1768 -7474 7073 3a2f 2f77 7777 2e65 7861 6d70 -6c65 2e63 6f6d -`), - []HeaderField{ - pair(":status", "302"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("location", "https://www.example.com"), - }, - []HeaderField{ - pair("location", "https://www.example.com"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("cache-control", "private"), - pair(":status", "302"), - }, - 222, - }, - {dehex("4803 3330 37c1 c0bf"), - []HeaderField{ - pair(":status", "307"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("location", "https://www.example.com"), - }, - []HeaderField{ - pair(":status", "307"), - pair("location", "https://www.example.com"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("cache-control", "private"), - }, - 222, - }, - {dehex(` -88c1 611d 4d6f 6e2c 2032 3120 4f63 7420 -3230 3133 2032 303a 3133 3a32 3220 474d -54c0 5a04 677a 6970 7738 666f 6f3d 4153 -444a 4b48 514b 425a 584f 5157 454f 5049 -5541 5851 5745 4f49 553b 206d 6178 2d61 -6765 3d33 3630 303b 2076 6572 7369 6f6e -3d31 -`), - []HeaderField{ - pair(":status", "200"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), - pair("location", "https://www.example.com"), - pair("content-encoding", "gzip"), - pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), - }, - []HeaderField{ - pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), - pair("content-encoding", "gzip"), - pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), - }, - 215, - }, - }) -} - -// http://http2.github.io/http2-spec/compression.html#rfc.section.C.6 -// "This section shows the same examples as the previous section, but -// using Huffman encoding for the literal values. The HTTP/2 setting -// parameter SETTINGS_HEADER_TABLE_SIZE is set to the value of 256 -// octets, causing some evictions to occur. The eviction mechanism -// uses the length of the decoded literal values, so the same -// evictions occurs as in the previous section." -func TestDecodeC6_ResponsesHuffman(t *testing.T) { - testDecodeSeries(t, 256, []encAndWant{ - {dehex(` -4882 6402 5885 aec3 771a 4b61 96d0 7abe -9410 54d4 44a8 2005 9504 0b81 66e0 82a6 -2d1b ff6e 919d 29ad 1718 63c7 8f0b 97c8 -e9ae 82ae 43d3 -`), - []HeaderField{ - pair(":status", "302"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("location", "https://www.example.com"), - }, - []HeaderField{ - pair("location", "https://www.example.com"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("cache-control", "private"), - pair(":status", "302"), - }, - 222, - }, - {dehex("4883 640e ffc1 c0bf"), - []HeaderField{ - pair(":status", "307"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("location", "https://www.example.com"), - }, - []HeaderField{ - pair(":status", "307"), - pair("location", "https://www.example.com"), - pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - pair("cache-control", "private"), - }, - 222, - }, - {dehex(` -88c1 6196 d07a be94 1054 d444 a820 0595 -040b 8166 e084 a62d 1bff c05a 839b d9ab -77ad 94e7 821d d7f2 e6c7 b335 dfdf cd5b -3960 d5af 2708 7f36 72c1 ab27 0fb5 291f -9587 3160 65c0 03ed 4ee5 b106 3d50 07 -`), - []HeaderField{ - pair(":status", "200"), - pair("cache-control", "private"), - pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), - pair("location", "https://www.example.com"), - pair("content-encoding", "gzip"), - pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), - }, - []HeaderField{ - pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), - pair("content-encoding", "gzip"), - pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), - }, - 215, - }, - }) -} - -func testDecodeSeries(t *testing.T, size uint32, steps []encAndWant) { - d := NewDecoder(size, nil) - for i, step := range steps { - hf, err := d.DecodeFull(step.enc) - if err != nil { - t.Fatalf("Error at step index %d: %v", i, err) - } - if !reflect.DeepEqual(hf, step.want) { - t.Fatalf("At step index %d: Got headers %v; want %v", i, hf, step.want) - } - gotDynTab := d.dynTab.reverseCopy() - if !reflect.DeepEqual(gotDynTab, step.wantDynTab) { - t.Errorf("After step index %d, dynamic table = %v; want %v", i, gotDynTab, step.wantDynTab) - } - if d.dynTab.size != step.wantDynSize { - t.Errorf("After step index %d, dynamic table size = %v; want %v", i, d.dynTab.size, step.wantDynSize) - } - } -} - -func TestHuffmanDecodeExcessPadding(t *testing.T) { - tests := [][]byte{ - {0xff}, // Padding Exceeds 7 bits - {0x1f, 0xff}, // {"a", 1 byte excess padding} - {0x1f, 0xff, 0xff}, // {"a", 2 byte excess padding} - {0x1f, 0xff, 0xff, 0xff}, // {"a", 3 byte excess padding} - {0xff, 0x9f, 0xff, 0xff, 0xff}, // {"a", 29 bit excess padding} - {'R', 0xbc, '0', 0xff, 0xff, 0xff, 0xff}, // Padding ends on partial symbol. - } - for i, in := range tests { - var buf bytes.Buffer - if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman { - t.Errorf("test-%d: decode(%q) = %v; want ErrInvalidHuffman", i, in, err) - } - } -} - -func TestHuffmanDecodeEOS(t *testing.T) { - in := []byte{0xff, 0xff, 0xff, 0xff, 0xfc} // {EOS, "?"} - var buf bytes.Buffer - if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman { - t.Errorf("error = %v; want ErrInvalidHuffman", err) - } -} - -func TestHuffmanDecodeMaxLengthOnTrailingByte(t *testing.T) { - in := []byte{0x00, 0x01} // {"0", "0", "0"} - var buf bytes.Buffer - if err := huffmanDecode(&buf, 2, in); err != ErrStringLength { - t.Errorf("error = %v; want ErrStringLength", err) - } -} - -func TestHuffmanDecodeCorruptPadding(t *testing.T) { - in := []byte{0x00} - var buf bytes.Buffer - if _, err := HuffmanDecode(&buf, in); err != ErrInvalidHuffman { - t.Errorf("error = %v; want ErrInvalidHuffman", err) - } -} - -func TestHuffmanDecode(t *testing.T) { - tests := []struct { - inHex, want string - }{ - {"f1e3 c2e5 f23a 6ba0 ab90 f4ff", "www.example.com"}, - {"a8eb 1064 9cbf", "no-cache"}, - {"25a8 49e9 5ba9 7d7f", "custom-key"}, - {"25a8 49e9 5bb8 e8b4 bf", "custom-value"}, - {"6402", "302"}, - {"aec3 771a 4b", "private"}, - {"d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff", "Mon, 21 Oct 2013 20:13:21 GMT"}, - {"9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3", "https://www.example.com"}, - {"9bd9 ab", "gzip"}, - {"94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07", - "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}, - } - for i, tt := range tests { - var buf bytes.Buffer - in, err := hex.DecodeString(strings.Replace(tt.inHex, " ", "", -1)) - if err != nil { - t.Errorf("%d. hex input error: %v", i, err) - continue - } - if _, err := HuffmanDecode(&buf, in); err != nil { - t.Errorf("%d. decode error: %v", i, err) - continue - } - if got := buf.String(); tt.want != got { - t.Errorf("%d. decode = %q; want %q", i, got, tt.want) - } - } -} - -func TestAppendHuffmanString(t *testing.T) { - tests := []struct { - in, want string - }{ - {"www.example.com", "f1e3 c2e5 f23a 6ba0 ab90 f4ff"}, - {"no-cache", "a8eb 1064 9cbf"}, - {"custom-key", "25a8 49e9 5ba9 7d7f"}, - {"custom-value", "25a8 49e9 5bb8 e8b4 bf"}, - {"302", "6402"}, - {"private", "aec3 771a 4b"}, - {"Mon, 21 Oct 2013 20:13:21 GMT", "d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff"}, - {"https://www.example.com", "9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3"}, - {"gzip", "9bd9 ab"}, - {"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", - "94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07"}, - } - for i, tt := range tests { - buf := []byte{} - want := strings.Replace(tt.want, " ", "", -1) - buf = AppendHuffmanString(buf, tt.in) - if got := hex.EncodeToString(buf); want != got { - t.Errorf("%d. encode = %q; want %q", i, got, want) - } - } -} - -func TestHuffmanMaxStrLen(t *testing.T) { - const msg = "Some string" - huff := AppendHuffmanString(nil, msg) - - testGood := func(max int) { - var out bytes.Buffer - if err := huffmanDecode(&out, max, huff); err != nil { - t.Errorf("For maxLen=%d, unexpected error: %v", max, err) - } - if out.String() != msg { - t.Errorf("For maxLen=%d, out = %q; want %q", max, out.String(), msg) - } - } - testGood(0) - testGood(len(msg)) - testGood(len(msg) + 1) - - var out bytes.Buffer - if err := huffmanDecode(&out, len(msg)-1, huff); err != ErrStringLength { - t.Errorf("err = %v; want ErrStringLength", err) - } -} - -func TestHuffmanRoundtripStress(t *testing.T) { - const Len = 50 // of uncompressed string - input := make([]byte, Len) - var output bytes.Buffer - var huff []byte - - n := 5000 - if testing.Short() { - n = 100 - } - seed := time.Now().UnixNano() - t.Logf("Seed = %v", seed) - src := rand.New(rand.NewSource(seed)) - var encSize int64 - for i := 0; i < n; i++ { - for l := range input { - input[l] = byte(src.Intn(256)) - } - huff = AppendHuffmanString(huff[:0], string(input)) - encSize += int64(len(huff)) - output.Reset() - if err := huffmanDecode(&output, 0, huff); err != nil { - t.Errorf("Failed to decode %q -> %q -> error %v", input, huff, err) - continue - } - if !bytes.Equal(output.Bytes(), input) { - t.Errorf("Roundtrip failure on %q -> %q -> %q", input, huff, output.Bytes()) - } - } - t.Logf("Compressed size of original: %0.02f%% (%v -> %v)", 100*(float64(encSize)/(Len*float64(n))), Len*n, encSize) -} - -func TestHuffmanDecodeFuzz(t *testing.T) { - const Len = 50 // of compressed - var buf, zbuf bytes.Buffer - - n := 5000 - if testing.Short() { - n = 100 - } - seed := time.Now().UnixNano() - t.Logf("Seed = %v", seed) - src := rand.New(rand.NewSource(seed)) - numFail := 0 - for i := 0; i < n; i++ { - zbuf.Reset() - if i == 0 { - // Start with at least one invalid one. - zbuf.WriteString("00\x91\xff\xff\xff\xff\xc8") - } else { - for l := 0; l < Len; l++ { - zbuf.WriteByte(byte(src.Intn(256))) - } - } - - buf.Reset() - if err := huffmanDecode(&buf, 0, zbuf.Bytes()); err != nil { - if err == ErrInvalidHuffman { - numFail++ - continue - } - t.Errorf("Failed to decode %q: %v", zbuf.Bytes(), err) - continue - } - } - t.Logf("%0.02f%% are invalid (%d / %d)", 100*float64(numFail)/float64(n), numFail, n) - if numFail < 1 { - t.Error("expected at least one invalid huffman encoding (test starts with one)") - } -} - -func TestReadVarInt(t *testing.T) { - type res struct { - i uint64 - consumed int - err error - } - tests := []struct { - n byte - p []byte - want res - }{ - // Fits in a byte: - {1, []byte{0}, res{0, 1, nil}}, - {2, []byte{2}, res{2, 1, nil}}, - {3, []byte{6}, res{6, 1, nil}}, - {4, []byte{14}, res{14, 1, nil}}, - {5, []byte{30}, res{30, 1, nil}}, - {6, []byte{62}, res{62, 1, nil}}, - {7, []byte{126}, res{126, 1, nil}}, - {8, []byte{254}, res{254, 1, nil}}, - - // Doesn't fit in a byte: - {1, []byte{1}, res{0, 0, errNeedMore}}, - {2, []byte{3}, res{0, 0, errNeedMore}}, - {3, []byte{7}, res{0, 0, errNeedMore}}, - {4, []byte{15}, res{0, 0, errNeedMore}}, - {5, []byte{31}, res{0, 0, errNeedMore}}, - {6, []byte{63}, res{0, 0, errNeedMore}}, - {7, []byte{127}, res{0, 0, errNeedMore}}, - {8, []byte{255}, res{0, 0, errNeedMore}}, - - // Ignoring top bits: - {5, []byte{255, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 111 - {5, []byte{159, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 100 - {5, []byte{191, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 101 - - // Extra byte: - {5, []byte{191, 154, 10, 2}, res{1337, 3, nil}}, // extra byte - - // Short a byte: - {5, []byte{191, 154}, res{0, 0, errNeedMore}}, - - // integer overflow: - {1, []byte{255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, res{0, 0, errVarintOverflow}}, - } - for _, tt := range tests { - i, remain, err := readVarInt(tt.n, tt.p) - consumed := len(tt.p) - len(remain) - got := res{i, consumed, err} - if got != tt.want { - t.Errorf("readVarInt(%d, %v ~ %x) = %+v; want %+v", tt.n, tt.p, tt.p, got, tt.want) - } - } -} - -// Fuzz crash, originally reported at https://github.com/bradfitz/http2/issues/56 -func TestHuffmanFuzzCrash(t *testing.T) { - got, err := HuffmanDecodeToString([]byte("00\x91\xff\xff\xff\xff\xc8")) - if got != "" { - t.Errorf("Got %q; want empty string", got) - } - if err != ErrInvalidHuffman { - t.Errorf("Err = %v; want ErrInvalidHuffman", err) - } -} - -func pair(name, value string) HeaderField { - return HeaderField{Name: name, Value: value} -} - -func dehex(s string) []byte { - s = strings.Replace(s, " ", "", -1) - s = strings.Replace(s, "\n", "", -1) - b, err := hex.DecodeString(s) - if err != nil { - panic(err) - } - return b -} - -func TestEmitEnabled(t *testing.T) { - var buf bytes.Buffer - enc := NewEncoder(&buf) - enc.WriteField(HeaderField{Name: "foo", Value: "bar"}) - enc.WriteField(HeaderField{Name: "foo", Value: "bar"}) - - numCallback := 0 - var dec *Decoder - dec = NewDecoder(8<<20, func(HeaderField) { - numCallback++ - dec.SetEmitEnabled(false) - }) - if !dec.EmitEnabled() { - t.Errorf("initial emit enabled = false; want true") - } - if _, err := dec.Write(buf.Bytes()); err != nil { - t.Error(err) - } - if numCallback != 1 { - t.Errorf("num callbacks = %d; want 1", numCallback) - } - if dec.EmitEnabled() { - t.Errorf("emit enabled = true; want false") - } -} - -func TestSaveBufLimit(t *testing.T) { - const maxStr = 1 << 10 - var got []HeaderField - dec := NewDecoder(initialHeaderTableSize, func(hf HeaderField) { - got = append(got, hf) - }) - dec.SetMaxStringLength(maxStr) - var frag []byte - frag = append(frag[:0], encodeTypeByte(false, false)) - frag = appendVarInt(frag, 7, 3) - frag = append(frag, "foo"...) - frag = appendVarInt(frag, 7, 3) - frag = append(frag, "bar"...) - - if _, err := dec.Write(frag); err != nil { - t.Fatal(err) - } - - want := []HeaderField{{Name: "foo", Value: "bar"}} - if !reflect.DeepEqual(got, want) { - t.Errorf("After small writes, got %v; want %v", got, want) - } - - frag = append(frag[:0], encodeTypeByte(false, false)) - frag = appendVarInt(frag, 7, maxStr*3) - frag = append(frag, make([]byte, maxStr*3)...) - - _, err := dec.Write(frag) - if err != ErrStringLength { - t.Fatalf("Write error = %v; want ErrStringLength", err) - } -} diff --git a/vendor/golang.org/x/net/http2/hpack/tables_test.go b/vendor/golang.org/x/net/http2/hpack/tables_test.go deleted file mode 100644 index d963f36354..0000000000 --- a/vendor/golang.org/x/net/http2/hpack/tables_test.go +++ /dev/null @@ -1,214 +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 hpack - -import ( - "bufio" - "regexp" - "strconv" - "strings" - "testing" -) - -func TestHeaderFieldTable(t *testing.T) { - table := &headerFieldTable{} - table.init() - table.addEntry(pair("key1", "value1-1")) - table.addEntry(pair("key2", "value2-1")) - table.addEntry(pair("key1", "value1-2")) - table.addEntry(pair("key3", "value3-1")) - table.addEntry(pair("key4", "value4-1")) - table.addEntry(pair("key2", "value2-2")) - - // Tests will be run twice: once before evicting anything, and - // again after evicting the three oldest entries. - tests := []struct { - f HeaderField - beforeWantStaticI uint64 - beforeWantMatch bool - afterWantStaticI uint64 - afterWantMatch bool - }{ - {HeaderField{"key1", "value1-1", false}, 1, true, 0, false}, - {HeaderField{"key1", "value1-2", false}, 3, true, 0, false}, - {HeaderField{"key1", "value1-3", false}, 3, false, 0, false}, - {HeaderField{"key2", "value2-1", false}, 2, true, 3, false}, - {HeaderField{"key2", "value2-2", false}, 6, true, 3, true}, - {HeaderField{"key2", "value2-3", false}, 6, false, 3, false}, - {HeaderField{"key4", "value4-1", false}, 5, true, 2, true}, - // Name match only, because sensitive. - {HeaderField{"key4", "value4-1", true}, 5, false, 2, false}, - // Key not found. - {HeaderField{"key5", "value5-x", false}, 0, false, 0, false}, - } - - staticToDynamic := func(i uint64) uint64 { - if i == 0 { - return 0 - } - return uint64(table.len()) - i + 1 // dynamic is the reversed table - } - - searchStatic := func(f HeaderField) (uint64, bool) { - old := staticTable - staticTable = table - defer func() { staticTable = old }() - return staticTable.search(f) - } - - searchDynamic := func(f HeaderField) (uint64, bool) { - return table.search(f) - } - - for _, test := range tests { - gotI, gotMatch := searchStatic(test.f) - if wantI, wantMatch := test.beforeWantStaticI, test.beforeWantMatch; gotI != wantI || gotMatch != wantMatch { - t.Errorf("before evictions: searchStatic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) - } - gotI, gotMatch = searchDynamic(test.f) - wantDynamicI := staticToDynamic(test.beforeWantStaticI) - if wantI, wantMatch := wantDynamicI, test.beforeWantMatch; gotI != wantI || gotMatch != wantMatch { - t.Errorf("before evictions: searchDynamic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) - } - } - - table.evictOldest(3) - - for _, test := range tests { - gotI, gotMatch := searchStatic(test.f) - if wantI, wantMatch := test.afterWantStaticI, test.afterWantMatch; gotI != wantI || gotMatch != wantMatch { - t.Errorf("after evictions: searchStatic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) - } - gotI, gotMatch = searchDynamic(test.f) - wantDynamicI := staticToDynamic(test.afterWantStaticI) - if wantI, wantMatch := wantDynamicI, test.afterWantMatch; gotI != wantI || gotMatch != wantMatch { - t.Errorf("after evictions: searchDynamic(%+v)=%v,%v want %v,%v", test.f, gotI, gotMatch, wantI, wantMatch) - } - } -} - -func TestHeaderFieldTable_LookupMapEviction(t *testing.T) { - table := &headerFieldTable{} - table.init() - table.addEntry(pair("key1", "value1-1")) - table.addEntry(pair("key2", "value2-1")) - table.addEntry(pair("key1", "value1-2")) - table.addEntry(pair("key3", "value3-1")) - table.addEntry(pair("key4", "value4-1")) - table.addEntry(pair("key2", "value2-2")) - - // evict all pairs - table.evictOldest(table.len()) - - if l := table.len(); l > 0 { - t.Errorf("table.len() = %d, want 0", l) - } - - if l := len(table.byName); l > 0 { - t.Errorf("len(table.byName) = %d, want 0", l) - } - - if l := len(table.byNameValue); l > 0 { - t.Errorf("len(table.byNameValue) = %d, want 0", l) - } -} - -func TestStaticTable(t *testing.T) { - fromSpec := ` - +-------+-----------------------------+---------------+ - | 1 | :authority | | - | 2 | :method | GET | - | 3 | :method | POST | - | 4 | :path | / | - | 5 | :path | /index.html | - | 6 | :scheme | http | - | 7 | :scheme | https | - | 8 | :status | 200 | - | 9 | :status | 204 | - | 10 | :status | 206 | - | 11 | :status | 304 | - | 12 | :status | 400 | - | 13 | :status | 404 | - | 14 | :status | 500 | - | 15 | accept-charset | | - | 16 | accept-encoding | gzip, deflate | - | 17 | accept-language | | - | 18 | accept-ranges | | - | 19 | accept | | - | 20 | access-control-allow-origin | | - | 21 | age | | - | 22 | allow | | - | 23 | authorization | | - | 24 | cache-control | | - | 25 | content-disposition | | - | 26 | content-encoding | | - | 27 | content-language | | - | 28 | content-length | | - | 29 | content-location | | - | 30 | content-range | | - | 31 | content-type | | - | 32 | cookie | | - | 33 | date | | - | 34 | etag | | - | 35 | expect | | - | 36 | expires | | - | 37 | from | | - | 38 | host | | - | 39 | if-match | | - | 40 | if-modified-since | | - | 41 | if-none-match | | - | 42 | if-range | | - | 43 | if-unmodified-since | | - | 44 | last-modified | | - | 45 | link | | - | 46 | location | | - | 47 | max-forwards | | - | 48 | proxy-authenticate | | - | 49 | proxy-authorization | | - | 50 | range | | - | 51 | referer | | - | 52 | refresh | | - | 53 | retry-after | | - | 54 | server | | - | 55 | set-cookie | | - | 56 | strict-transport-security | | - | 57 | transfer-encoding | | - | 58 | user-agent | | - | 59 | vary | | - | 60 | via | | - | 61 | www-authenticate | | - +-------+-----------------------------+---------------+ -` - bs := bufio.NewScanner(strings.NewReader(fromSpec)) - re := regexp.MustCompile(`\| (\d+)\s+\| (\S+)\s*\| (\S(.*\S)?)?\s+\|`) - for bs.Scan() { - l := bs.Text() - if !strings.Contains(l, "|") { - continue - } - m := re.FindStringSubmatch(l) - if m == nil { - continue - } - i, err := strconv.Atoi(m[1]) - if err != nil { - t.Errorf("Bogus integer on line %q", l) - continue - } - if i < 1 || i > staticTable.len() { - t.Errorf("Bogus index %d on line %q", i, l) - continue - } - if got, want := staticTable.ents[i-1].Name, m[2]; got != want { - t.Errorf("header index %d name = %q; want %q", i, got, want) - } - if got, want := staticTable.ents[i-1].Value, m[3]; got != want { - t.Errorf("header index %d value = %q; want %q", i, got, want) - } - } - if err := bs.Err(); err != nil { - t.Error(err) - } -} diff --git a/vendor/golang.org/x/net/http2/http2.go b/vendor/golang.org/x/net/http2/http2.go index d565f40e0c..c82428254a 100644 --- a/vendor/golang.org/x/net/http2/http2.go +++ b/vendor/golang.org/x/net/http2/http2.go @@ -29,7 +29,7 @@ import ( "strings" "sync" - "golang.org/x/net/lex/httplex" + "golang.org/x/net/http/httpguts" ) var ( @@ -179,7 +179,7 @@ var ( ) // validWireHeaderFieldName reports whether v is a valid header field -// name (key). See httplex.ValidHeaderName for the base rules. +// name (key). See httpguts.ValidHeaderName for the base rules. // // Further, http2 says: // "Just as in HTTP/1.x, header field names are strings of ASCII @@ -191,7 +191,7 @@ func validWireHeaderFieldName(v string) bool { return false } for _, r := range v { - if !httplex.IsTokenRune(r) { + if !httpguts.IsTokenRune(r) { return false } if 'A' <= r && r <= 'Z' { @@ -312,7 +312,7 @@ func mustUint31(v int32) uint32 { } // bodyAllowedForStatus reports whether a given response status code -// permits a body. See RFC 2616, section 4.4. +// permits a body. See RFC 7230, section 3.3. func bodyAllowedForStatus(status int) bool { switch { case status >= 100 && status <= 199: diff --git a/vendor/golang.org/x/net/http2/http2_test.go b/vendor/golang.org/x/net/http2/http2_test.go deleted file mode 100644 index 5248776470..0000000000 --- a/vendor/golang.org/x/net/http2/http2_test.go +++ /dev/null @@ -1,199 +0,0 @@ -// Copyright 2014 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 http2 - -import ( - "bytes" - "errors" - "flag" - "fmt" - "net/http" - "os/exec" - "strconv" - "strings" - "testing" - - "golang.org/x/net/http2/hpack" -) - -var knownFailing = flag.Bool("known_failing", false, "Run known-failing tests.") - -func condSkipFailingTest(t *testing.T) { - if !*knownFailing { - t.Skip("Skipping known-failing test without --known_failing") - } -} - -func init() { - inTests = true - DebugGoroutines = true - flag.BoolVar(&VerboseLogs, "verboseh2", VerboseLogs, "Verbose HTTP/2 debug logging") -} - -func TestSettingString(t *testing.T) { - tests := []struct { - s Setting - want string - }{ - {Setting{SettingMaxFrameSize, 123}, "[MAX_FRAME_SIZE = 123]"}, - {Setting{1<<16 - 1, 123}, "[UNKNOWN_SETTING_65535 = 123]"}, - } - for i, tt := range tests { - got := fmt.Sprint(tt.s) - if got != tt.want { - t.Errorf("%d. for %#v, string = %q; want %q", i, tt.s, got, tt.want) - } - } -} - -type twriter struct { - t testing.TB - st *serverTester // optional -} - -func (w twriter) Write(p []byte) (n int, err error) { - if w.st != nil { - ps := string(p) - for _, phrase := range w.st.logFilter { - if strings.Contains(ps, phrase) { - return len(p), nil // no logging - } - } - } - w.t.Logf("%s", p) - return len(p), nil -} - -// like encodeHeader, but don't add implicit pseudo headers. -func encodeHeaderNoImplicit(t *testing.T, headers ...string) []byte { - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - for len(headers) > 0 { - k, v := headers[0], headers[1] - headers = headers[2:] - if err := enc.WriteField(hpack.HeaderField{Name: k, Value: v}); err != nil { - t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) - } - } - return buf.Bytes() -} - -// Verify that curl has http2. -func requireCurl(t *testing.T) { - out, err := dockerLogs(curl(t, "--version")) - if err != nil { - t.Skipf("failed to determine curl features; skipping test") - } - if !strings.Contains(string(out), "HTTP2") { - t.Skip("curl doesn't support HTTP2; skipping test") - } -} - -func curl(t *testing.T, args ...string) (container string) { - out, err := exec.Command("docker", append([]string{"run", "-d", "--net=host", "gohttp2/curl"}, args...)...).Output() - if err != nil { - t.Skipf("Failed to run curl in docker: %v, %s", err, out) - } - return strings.TrimSpace(string(out)) -} - -// Verify that h2load exists. -func requireH2load(t *testing.T) { - out, err := dockerLogs(h2load(t, "--version")) - if err != nil { - t.Skipf("failed to probe h2load; skipping test: %s", out) - } - if !strings.Contains(string(out), "h2load nghttp2/") { - t.Skipf("h2load not present; skipping test. (Output=%q)", out) - } -} - -func h2load(t *testing.T, args ...string) (container string) { - out, err := exec.Command("docker", append([]string{"run", "-d", "--net=host", "--entrypoint=/usr/local/bin/h2load", "gohttp2/curl"}, args...)...).Output() - if err != nil { - t.Skipf("Failed to run h2load in docker: %v, %s", err, out) - } - return strings.TrimSpace(string(out)) -} - -type puppetCommand struct { - fn func(w http.ResponseWriter, r *http.Request) - done chan<- bool -} - -type handlerPuppet struct { - ch chan puppetCommand -} - -func newHandlerPuppet() *handlerPuppet { - return &handlerPuppet{ - ch: make(chan puppetCommand), - } -} - -func (p *handlerPuppet) act(w http.ResponseWriter, r *http.Request) { - for cmd := range p.ch { - cmd.fn(w, r) - cmd.done <- true - } -} - -func (p *handlerPuppet) done() { close(p.ch) } -func (p *handlerPuppet) do(fn func(http.ResponseWriter, *http.Request)) { - done := make(chan bool) - p.ch <- puppetCommand{fn, done} - <-done -} -func dockerLogs(container string) ([]byte, error) { - out, err := exec.Command("docker", "wait", container).CombinedOutput() - if err != nil { - return out, err - } - exitStatus, err := strconv.Atoi(strings.TrimSpace(string(out))) - if err != nil { - return out, errors.New("unexpected exit status from docker wait") - } - out, err = exec.Command("docker", "logs", container).CombinedOutput() - exec.Command("docker", "rm", container).Run() - if err == nil && exitStatus != 0 { - err = fmt.Errorf("exit status %d: %s", exitStatus, out) - } - return out, err -} - -func kill(container string) { - exec.Command("docker", "kill", container).Run() - exec.Command("docker", "rm", container).Run() -} - -func cleanDate(res *http.Response) { - if d := res.Header["Date"]; len(d) == 1 { - d[0] = "XXX" - } -} - -func TestSorterPoolAllocs(t *testing.T) { - ss := []string{"a", "b", "c"} - h := http.Header{ - "a": nil, - "b": nil, - "c": nil, - } - sorter := new(sorter) - - if allocs := testing.AllocsPerRun(100, func() { - sorter.SortStrings(ss) - }); allocs >= 1 { - t.Logf("SortStrings allocs = %v; want <1", allocs) - } - - if allocs := testing.AllocsPerRun(5, func() { - if len(sorter.Keys(h)) != 3 { - t.Fatal("wrong result") - } - }); allocs > 0 { - t.Logf("Keys allocs = %v; want <1", allocs) - } -} diff --git a/vendor/golang.org/x/net/http2/pipe_test.go b/vendor/golang.org/x/net/http2/pipe_test.go deleted file mode 100644 index 1bf351ff6b..0000000000 --- a/vendor/golang.org/x/net/http2/pipe_test.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2014 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 http2 - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "testing" -) - -func TestPipeClose(t *testing.T) { - var p pipe - p.b = new(bytes.Buffer) - a := errors.New("a") - b := errors.New("b") - p.CloseWithError(a) - p.CloseWithError(b) - _, err := p.Read(make([]byte, 1)) - if err != a { - t.Errorf("err = %v want %v", err, a) - } -} - -func TestPipeDoneChan(t *testing.T) { - var p pipe - done := p.Done() - select { - case <-done: - t.Fatal("done too soon") - default: - } - p.CloseWithError(io.EOF) - select { - case <-done: - default: - t.Fatal("should be done") - } -} - -func TestPipeDoneChan_ErrFirst(t *testing.T) { - var p pipe - p.CloseWithError(io.EOF) - done := p.Done() - select { - case <-done: - default: - t.Fatal("should be done") - } -} - -func TestPipeDoneChan_Break(t *testing.T) { - var p pipe - done := p.Done() - select { - case <-done: - t.Fatal("done too soon") - default: - } - p.BreakWithError(io.EOF) - select { - case <-done: - default: - t.Fatal("should be done") - } -} - -func TestPipeDoneChan_Break_ErrFirst(t *testing.T) { - var p pipe - p.BreakWithError(io.EOF) - done := p.Done() - select { - case <-done: - default: - t.Fatal("should be done") - } -} - -func TestPipeCloseWithError(t *testing.T) { - p := &pipe{b: new(bytes.Buffer)} - const body = "foo" - io.WriteString(p, body) - a := errors.New("test error") - p.CloseWithError(a) - all, err := ioutil.ReadAll(p) - if string(all) != body { - t.Errorf("read bytes = %q; want %q", all, body) - } - if err != a { - t.Logf("read error = %v, %v", err, a) - } - // Read and Write should fail. - if n, err := p.Write([]byte("abc")); err != errClosedPipeWrite || n != 0 { - t.Errorf("Write(abc) after close\ngot %v, %v\nwant 0, %v", n, err, errClosedPipeWrite) - } - if n, err := p.Read(make([]byte, 1)); err == nil || n != 0 { - t.Errorf("Read() after close\ngot %v, nil\nwant 0, %v", n, errClosedPipeWrite) - } -} - -func TestPipeBreakWithError(t *testing.T) { - p := &pipe{b: new(bytes.Buffer)} - io.WriteString(p, "foo") - a := errors.New("test err") - p.BreakWithError(a) - all, err := ioutil.ReadAll(p) - if string(all) != "" { - t.Errorf("read bytes = %q; want empty string", all) - } - if err != a { - t.Logf("read error = %v, %v", err, a) - } - if p.b != nil { - t.Errorf("buffer should be nil after BreakWithError") - } - // Write should succeed silently. - if n, err := p.Write([]byte("abc")); err != nil || n != 3 { - t.Errorf("Write(abc) after break\ngot %v, %v\nwant 0, nil", n, err) - } - if p.b != nil { - t.Errorf("buffer should be nil after Write") - } - // Read should fail. - if n, err := p.Read(make([]byte, 1)); err == nil || n != 0 { - t.Errorf("Read() after close\ngot %v, nil\nwant 0, not nil", n) - } -} diff --git a/vendor/golang.org/x/net/http2/server.go b/vendor/golang.org/x/net/http2/server.go index 3e705a01c6..acf3b24186 100644 --- a/vendor/golang.org/x/net/http2/server.go +++ b/vendor/golang.org/x/net/http2/server.go @@ -46,6 +46,7 @@ import ( "sync" "time" + "golang.org/x/net/http/httpguts" "golang.org/x/net/http2/hpack" ) @@ -406,7 +407,7 @@ func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) { // addresses during development. // // TODO: optionally enforce? Or enforce at the time we receive - // a new request, and verify the the ServerName matches the :authority? + // a new request, and verify the ServerName matches the :authority? // But that precludes proxy situations, perhaps. // // So for now, do nothing here again. @@ -652,7 +653,7 @@ func (sc *serverConn) condlogf(err error, format string, args ...interface{}) { if err == nil { return } - if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) { + if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) || err == errPrefaceTimeout { // Boring, expected errors. sc.vlogf(format, args...) } else { @@ -897,8 +898,11 @@ func (sc *serverConn) sendServeMsg(msg interface{}) { } } -// readPreface reads the ClientPreface greeting from the peer -// or returns an error on timeout or an invalid greeting. +var errPrefaceTimeout = errors.New("timeout waiting for client preface") + +// readPreface reads the ClientPreface greeting from the peer or +// returns errPrefaceTimeout on timeout, or an error if the greeting +// is invalid. func (sc *serverConn) readPreface() error { errc := make(chan error, 1) go func() { @@ -916,7 +920,7 @@ func (sc *serverConn) readPreface() error { defer timer.Stop() select { case <-timer.C: - return errors.New("timeout waiting for client preface") + return errPrefaceTimeout case err := <-errc: if err == nil { if VerboseLogs { @@ -1604,7 +1608,10 @@ func (sc *serverConn) processData(f *DataFrame) error { // Sender sending more than they'd declared? if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes { st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes)) - return streamError(id, ErrCodeStreamClosed) + // RFC 7540, sec 8.1.2.6: A request or response is also malformed if the + // value of a content-length header field does not equal the sum of the + // DATA frame payload lengths that form the body. + return streamError(id, ErrCodeProtocol) } if f.Length > 0 { // Check whether the client has flow control quota. @@ -1814,7 +1821,7 @@ func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error { if st.trailer != nil { for _, hf := range f.RegularFields() { key := sc.canonicalHeader(hf.Name) - if !ValidTrailerHeader(key) { + if !httpguts.ValidTrailerHeader(key) { // TODO: send more details to the peer somehow. But http2 has // no way to send debug data at a stream level. Discuss with // HTTP folk. @@ -2281,8 +2288,8 @@ func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != // written in the trailers at the end of the response. func (rws *responseWriterState) declareTrailer(k string) { k = http.CanonicalHeaderKey(k) - if !ValidTrailerHeader(k) { - // Forbidden by RFC 2616 14.40. + if !httpguts.ValidTrailerHeader(k) { + // Forbidden by RFC 7230, section 4.1.2. rws.conn.logf("ignoring invalid trailer %q", k) return } @@ -2305,6 +2312,7 @@ func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) { isHeadResp := rws.req.Method == "HEAD" if !rws.sentHeader { rws.sentHeader = true + var ctype, clen string if clen = rws.snapHeader.Get("Content-Length"); clen != "" { rws.snapHeader.Del("Content-Length") @@ -2318,10 +2326,33 @@ func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) { if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) { clen = strconv.Itoa(len(p)) } + _, hasContentType := rws.snapHeader["Content-Type"] - if !hasContentType && bodyAllowedForStatus(rws.status) { - ctype = http.DetectContentType(p) + if !hasContentType && bodyAllowedForStatus(rws.status) && len(p) > 0 { + if cto := rws.snapHeader.Get("X-Content-Type-Options"); strings.EqualFold("nosniff", cto) { + // nosniff is an explicit directive not to guess a content-type. + // Content-sniffing is no less susceptible to polyglot attacks via + // hosted content when done on the server. + ctype = "application/octet-stream" + rws.conn.logf("http2: WriteHeader called with X-Content-Type-Options:nosniff but no Content-Type") + } else { + ctype = http.DetectContentType(p) + } + } + + var noSniff bool + if bodyAllowedForStatus(rws.status) && (rws.sentContentLen > 0 || len(p) > 0) { + // If the content type triggers client-side sniffing on old browsers, + // attach a X-Content-Type-Options header if not present (or explicitly nil). + if _, ok := rws.snapHeader["X-Content-Type-Options"]; !ok { + if hasContentType { + noSniff = httpguts.SniffedContentType(rws.snapHeader.Get("Content-Type")) + } else if ctype != "" { + noSniff = httpguts.SniffedContentType(ctype) + } + } } + var date string if _, ok := rws.snapHeader["Date"]; !ok { // TODO(bradfitz): be faster here, like net/http? measure. @@ -2340,6 +2371,7 @@ func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) { endStream: endStream, contentType: ctype, contentLength: clen, + noSniff: noSniff, date: date, }) if err != nil { @@ -2403,7 +2435,7 @@ const TrailerPrefix = "Trailer:" // after the header has already been flushed. Because the Go // ResponseWriter interface has no way to set Trailers (only the // Header), and because we didn't want to expand the ResponseWriter -// interface, and because nobody used trailers, and because RFC 2616 +// interface, and because nobody used trailers, and because RFC 7230 // says you SHOULD (but not must) predeclare any trailers in the // header, the official ResponseWriter rules said trailers in Go must // be predeclared, and then we reuse the same ResponseWriter.Header() @@ -2487,6 +2519,24 @@ func (w *responseWriter) Header() http.Header { return rws.handlerHeader } +// checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode. +func checkWriteHeaderCode(code int) { + // Issue 22880: require valid WriteHeader status codes. + // For now we only enforce that it's three digits. + // In the future we might block things over 599 (600 and above aren't defined + // at http://httpwg.org/specs/rfc7231.html#status.codes) + // and we might block under 200 (once we have more mature 1xx support). + // But for now any three digits. + // + // We used to send "HTTP/1.1 000 0" on the wire in responses but there's + // no equivalent bogus thing we can realistically send in HTTP/2, + // so we'll consistently panic instead and help people find their bugs + // early. (We can't return an error from WriteHeader even if we wanted to.) + if code < 100 || code > 999 { + panic(fmt.Sprintf("invalid WriteHeader code %v", code)) + } +} + func (w *responseWriter) WriteHeader(code int) { rws := w.rws if rws == nil { @@ -2497,6 +2547,7 @@ func (w *responseWriter) WriteHeader(code int) { func (rws *responseWriterState) writeHeader(code int) { if !rws.wroteHeader { + checkWriteHeaderCode(code) rws.wroteHeader = true rws.status = code if len(rws.handlerHeader) > 0 { @@ -2768,7 +2819,7 @@ func (sc *serverConn) startPush(msg *startPushRequest) { } // foreachHeaderElement splits v according to the "#rule" construction -// in RFC 2616 section 2.1 and calls fn for each non-empty element. +// in RFC 7230 section 7 and calls fn for each non-empty element. func foreachHeaderElement(v string, fn func(string)) { v = textproto.TrimString(v) if v == "" { @@ -2816,41 +2867,6 @@ func new400Handler(err error) http.HandlerFunc { } } -// ValidTrailerHeader reports whether name is a valid header field name to appear -// in trailers. -// See: http://tools.ietf.org/html/rfc7230#section-4.1.2 -func ValidTrailerHeader(name string) bool { - name = http.CanonicalHeaderKey(name) - if strings.HasPrefix(name, "If-") || badTrailer[name] { - return false - } - return true -} - -var badTrailer = map[string]bool{ - "Authorization": true, - "Cache-Control": true, - "Connection": true, - "Content-Encoding": true, - "Content-Length": true, - "Content-Range": true, - "Content-Type": true, - "Expect": true, - "Host": true, - "Keep-Alive": true, - "Max-Forwards": true, - "Pragma": true, - "Proxy-Authenticate": true, - "Proxy-Authorization": true, - "Proxy-Connection": true, - "Range": true, - "Realm": true, - "Te": true, - "Trailer": true, - "Transfer-Encoding": true, - "Www-Authenticate": true, -} - // h1ServerKeepAlivesDisabled reports whether hs has its keep-alives // disabled. See comments on h1ServerShutdownChan above for why // the code is written this way. diff --git a/vendor/golang.org/x/net/http2/server_push_test.go b/vendor/golang.org/x/net/http2/server_push_test.go deleted file mode 100644 index 918fd30dc4..0000000000 --- a/vendor/golang.org/x/net/http2/server_push_test.go +++ /dev/null @@ -1,521 +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. - -// +build go1.8 - -package http2 - -import ( - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "sync" - "testing" - "time" -) - -func TestServer_Push_Success(t *testing.T) { - const ( - mainBody = "<html>index page</html>" - pushedBody = "<html>pushed page</html>" - userAgent = "testagent" - cookie = "testcookie" - ) - - var stURL string - checkPromisedReq := func(r *http.Request, wantMethod string, wantH http.Header) error { - if got, want := r.Method, wantMethod; got != want { - return fmt.Errorf("promised Req.Method=%q, want %q", got, want) - } - if got, want := r.Header, wantH; !reflect.DeepEqual(got, want) { - return fmt.Errorf("promised Req.Header=%q, want %q", got, want) - } - if got, want := "https://"+r.Host, stURL; got != want { - return fmt.Errorf("promised Req.Host=%q, want %q", got, want) - } - if r.Body == nil { - return fmt.Errorf("nil Body") - } - if buf, err := ioutil.ReadAll(r.Body); err != nil || len(buf) != 0 { - return fmt.Errorf("ReadAll(Body)=%q,%v, want '',nil", buf, err) - } - return nil - } - - errc := make(chan error, 3) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - switch r.URL.RequestURI() { - case "/": - // Push "/pushed?get" as a GET request, using an absolute URL. - opt := &http.PushOptions{ - Header: http.Header{ - "User-Agent": {userAgent}, - }, - } - if err := w.(http.Pusher).Push(stURL+"/pushed?get", opt); err != nil { - errc <- fmt.Errorf("error pushing /pushed?get: %v", err) - return - } - // Push "/pushed?head" as a HEAD request, using a path. - opt = &http.PushOptions{ - Method: "HEAD", - Header: http.Header{ - "User-Agent": {userAgent}, - "Cookie": {cookie}, - }, - } - if err := w.(http.Pusher).Push("/pushed?head", opt); err != nil { - errc <- fmt.Errorf("error pushing /pushed?head: %v", err) - return - } - w.Header().Set("Content-Type", "text/html") - w.Header().Set("Content-Length", strconv.Itoa(len(mainBody))) - w.WriteHeader(200) - io.WriteString(w, mainBody) - errc <- nil - - case "/pushed?get": - wantH := http.Header{} - wantH.Set("User-Agent", userAgent) - if err := checkPromisedReq(r, "GET", wantH); err != nil { - errc <- fmt.Errorf("/pushed?get: %v", err) - return - } - w.Header().Set("Content-Type", "text/html") - w.Header().Set("Content-Length", strconv.Itoa(len(pushedBody))) - w.WriteHeader(200) - io.WriteString(w, pushedBody) - errc <- nil - - case "/pushed?head": - wantH := http.Header{} - wantH.Set("User-Agent", userAgent) - wantH.Set("Cookie", cookie) - if err := checkPromisedReq(r, "HEAD", wantH); err != nil { - errc <- fmt.Errorf("/pushed?head: %v", err) - return - } - w.WriteHeader(204) - errc <- nil - - default: - errc <- fmt.Errorf("unknown RequestURL %q", r.URL.RequestURI()) - } - }) - stURL = st.ts.URL - - // Send one request, which should push two responses. - st.greet() - getSlash(st) - for k := 0; k < 3; k++ { - select { - case <-time.After(2 * time.Second): - t.Errorf("timeout waiting for handler %d to finish", k) - case err := <-errc: - if err != nil { - t.Fatal(err) - } - } - } - - checkPushPromise := func(f Frame, promiseID uint32, wantH [][2]string) error { - pp, ok := f.(*PushPromiseFrame) - if !ok { - return fmt.Errorf("got a %T; want *PushPromiseFrame", f) - } - if !pp.HeadersEnded() { - return fmt.Errorf("want END_HEADERS flag in PushPromiseFrame") - } - if got, want := pp.PromiseID, promiseID; got != want { - return fmt.Errorf("got PromiseID %v; want %v", got, want) - } - gotH := st.decodeHeader(pp.HeaderBlockFragment()) - if !reflect.DeepEqual(gotH, wantH) { - return fmt.Errorf("got promised headers %v; want %v", gotH, wantH) - } - return nil - } - checkHeaders := func(f Frame, wantH [][2]string) error { - hf, ok := f.(*HeadersFrame) - if !ok { - return fmt.Errorf("got a %T; want *HeadersFrame", f) - } - gotH := st.decodeHeader(hf.HeaderBlockFragment()) - if !reflect.DeepEqual(gotH, wantH) { - return fmt.Errorf("got response headers %v; want %v", gotH, wantH) - } - return nil - } - checkData := func(f Frame, wantData string) error { - df, ok := f.(*DataFrame) - if !ok { - return fmt.Errorf("got a %T; want *DataFrame", f) - } - if gotData := string(df.Data()); gotData != wantData { - return fmt.Errorf("got response data %q; want %q", gotData, wantData) - } - return nil - } - - // Stream 1 has 2 PUSH_PROMISE + HEADERS + DATA - // Stream 2 has HEADERS + DATA - // Stream 4 has HEADERS - expected := map[uint32][]func(Frame) error{ - 1: { - func(f Frame) error { - return checkPushPromise(f, 2, [][2]string{ - {":method", "GET"}, - {":scheme", "https"}, - {":authority", st.ts.Listener.Addr().String()}, - {":path", "/pushed?get"}, - {"user-agent", userAgent}, - }) - }, - func(f Frame) error { - return checkPushPromise(f, 4, [][2]string{ - {":method", "HEAD"}, - {":scheme", "https"}, - {":authority", st.ts.Listener.Addr().String()}, - {":path", "/pushed?head"}, - {"cookie", cookie}, - {"user-agent", userAgent}, - }) - }, - func(f Frame) error { - return checkHeaders(f, [][2]string{ - {":status", "200"}, - {"content-type", "text/html"}, - {"content-length", strconv.Itoa(len(mainBody))}, - }) - }, - func(f Frame) error { - return checkData(f, mainBody) - }, - }, - 2: { - func(f Frame) error { - return checkHeaders(f, [][2]string{ - {":status", "200"}, - {"content-type", "text/html"}, - {"content-length", strconv.Itoa(len(pushedBody))}, - }) - }, - func(f Frame) error { - return checkData(f, pushedBody) - }, - }, - 4: { - func(f Frame) error { - return checkHeaders(f, [][2]string{ - {":status", "204"}, - }) - }, - }, - } - - consumed := map[uint32]int{} - for k := 0; len(expected) > 0; k++ { - f, err := st.readFrame() - if err != nil { - for id, left := range expected { - t.Errorf("stream %d: missing %d frames", id, len(left)) - } - t.Fatalf("readFrame %d: %v", k, err) - } - id := f.Header().StreamID - label := fmt.Sprintf("stream %d, frame %d", id, consumed[id]) - if len(expected[id]) == 0 { - t.Fatalf("%s: unexpected frame %#+v", label, f) - } - check := expected[id][0] - expected[id] = expected[id][1:] - if len(expected[id]) == 0 { - delete(expected, id) - } - if err := check(f); err != nil { - t.Fatalf("%s: %v", label, err) - } - consumed[id]++ - } -} - -func TestServer_Push_SuccessNoRace(t *testing.T) { - // Regression test for issue #18326. Ensure the request handler can mutate - // pushed request headers without racing with the PUSH_PROMISE write. - errc := make(chan error, 2) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - switch r.URL.RequestURI() { - case "/": - opt := &http.PushOptions{ - Header: http.Header{"User-Agent": {"testagent"}}, - } - if err := w.(http.Pusher).Push("/pushed", opt); err != nil { - errc <- fmt.Errorf("error pushing: %v", err) - return - } - w.WriteHeader(200) - errc <- nil - - case "/pushed": - // Update request header, ensure there is no race. - r.Header.Set("User-Agent", "newagent") - r.Header.Set("Cookie", "cookie") - w.WriteHeader(200) - errc <- nil - - default: - errc <- fmt.Errorf("unknown RequestURL %q", r.URL.RequestURI()) - } - }) - - // Send one request, which should push one response. - st.greet() - getSlash(st) - for k := 0; k < 2; k++ { - select { - case <-time.After(2 * time.Second): - t.Errorf("timeout waiting for handler %d to finish", k) - case err := <-errc: - if err != nil { - t.Fatal(err) - } - } - } -} - -func TestServer_Push_RejectRecursivePush(t *testing.T) { - // Expect two requests, but might get three if there's a bug and the second push succeeds. - errc := make(chan error, 3) - handler := func(w http.ResponseWriter, r *http.Request) error { - baseURL := "https://" + r.Host - switch r.URL.Path { - case "/": - if err := w.(http.Pusher).Push(baseURL+"/push1", nil); err != nil { - return fmt.Errorf("first Push()=%v, want nil", err) - } - return nil - - case "/push1": - if got, want := w.(http.Pusher).Push(baseURL+"/push2", nil), ErrRecursivePush; got != want { - return fmt.Errorf("Push()=%v, want %v", got, want) - } - return nil - - default: - return fmt.Errorf("unexpected path: %q", r.URL.Path) - } - } - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - errc <- handler(w, r) - }) - defer st.Close() - st.greet() - getSlash(st) - if err := <-errc; err != nil { - t.Errorf("First request failed: %v", err) - } - if err := <-errc; err != nil { - t.Errorf("Second request failed: %v", err) - } -} - -func testServer_Push_RejectSingleRequest(t *testing.T, doPush func(http.Pusher, *http.Request) error, settings ...Setting) { - // Expect one request, but might get two if there's a bug and the push succeeds. - errc := make(chan error, 2) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - errc <- doPush(w.(http.Pusher), r) - }) - defer st.Close() - st.greet() - if err := st.fr.WriteSettings(settings...); err != nil { - st.t.Fatalf("WriteSettings: %v", err) - } - st.wantSettingsAck() - getSlash(st) - if err := <-errc; err != nil { - t.Error(err) - } - // Should not get a PUSH_PROMISE frame. - hf := st.wantHeaders() - if !hf.StreamEnded() { - t.Error("stream should end after headers") - } -} - -func TestServer_Push_RejectIfDisabled(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if got, want := p.Push("https://"+r.Host+"/pushed", nil), http.ErrNotSupported; got != want { - return fmt.Errorf("Push()=%v, want %v", got, want) - } - return nil - }, - Setting{SettingEnablePush, 0}) -} - -func TestServer_Push_RejectWhenNoConcurrentStreams(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if got, want := p.Push("https://"+r.Host+"/pushed", nil), ErrPushLimitReached; got != want { - return fmt.Errorf("Push()=%v, want %v", got, want) - } - return nil - }, - Setting{SettingMaxConcurrentStreams, 0}) -} - -func TestServer_Push_RejectWrongScheme(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if err := p.Push("http://"+r.Host+"/pushed", nil); err == nil { - return errors.New("Push() should have failed (push target URL is http)") - } - return nil - }) -} - -func TestServer_Push_RejectMissingHost(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if err := p.Push("https:pushed", nil); err == nil { - return errors.New("Push() should have failed (push target URL missing host)") - } - return nil - }) -} - -func TestServer_Push_RejectRelativePath(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if err := p.Push("../test", nil); err == nil { - return errors.New("Push() should have failed (push target is a relative path)") - } - return nil - }) -} - -func TestServer_Push_RejectForbiddenMethod(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - if err := p.Push("https://"+r.Host+"/pushed", &http.PushOptions{Method: "POST"}); err == nil { - return errors.New("Push() should have failed (cannot promise a POST)") - } - return nil - }) -} - -func TestServer_Push_RejectForbiddenHeader(t *testing.T) { - testServer_Push_RejectSingleRequest(t, - func(p http.Pusher, r *http.Request) error { - header := http.Header{ - "Content-Length": {"10"}, - "Content-Encoding": {"gzip"}, - "Trailer": {"Foo"}, - "Te": {"trailers"}, - "Host": {"test.com"}, - ":authority": {"test.com"}, - } - if err := p.Push("https://"+r.Host+"/pushed", &http.PushOptions{Header: header}); err == nil { - return errors.New("Push() should have failed (forbidden headers)") - } - return nil - }) -} - -func TestServer_Push_StateTransitions(t *testing.T) { - const body = "foo" - - gotPromise := make(chan bool) - finishedPush := make(chan bool) - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - switch r.URL.RequestURI() { - case "/": - if err := w.(http.Pusher).Push("/pushed", nil); err != nil { - t.Errorf("Push error: %v", err) - } - // Don't finish this request until the push finishes so we don't - // nondeterministically interleave output frames with the push. - <-finishedPush - case "/pushed": - <-gotPromise - } - w.Header().Set("Content-Type", "text/html") - w.Header().Set("Content-Length", strconv.Itoa(len(body))) - w.WriteHeader(200) - io.WriteString(w, body) - }) - defer st.Close() - - st.greet() - if st.stream(2) != nil { - t.Fatal("stream 2 should be empty") - } - if got, want := st.streamState(2), stateIdle; got != want { - t.Fatalf("streamState(2)=%v, want %v", got, want) - } - getSlash(st) - // After the PUSH_PROMISE is sent, the stream should be stateHalfClosedRemote. - st.wantPushPromise() - if got, want := st.streamState(2), stateHalfClosedRemote; got != want { - t.Fatalf("streamState(2)=%v, want %v", got, want) - } - // We stall the HTTP handler for "/pushed" until the above check. If we don't - // stall the handler, then the handler might write HEADERS and DATA and finish - // the stream before we check st.streamState(2) -- should that happen, we'll - // see stateClosed and fail the above check. - close(gotPromise) - st.wantHeaders() - if df := st.wantData(); !df.StreamEnded() { - t.Fatal("expected END_STREAM flag on DATA") - } - if got, want := st.streamState(2), stateClosed; got != want { - t.Fatalf("streamState(2)=%v, want %v", got, want) - } - close(finishedPush) -} - -func TestServer_Push_RejectAfterGoAway(t *testing.T) { - var readyOnce sync.Once - ready := make(chan struct{}) - errc := make(chan error, 2) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - select { - case <-ready: - case <-time.After(5 * time.Second): - errc <- fmt.Errorf("timeout waiting for GOAWAY to be processed") - } - if got, want := w.(http.Pusher).Push("https://"+r.Host+"/pushed", nil), http.ErrNotSupported; got != want { - errc <- fmt.Errorf("Push()=%v, want %v", got, want) - } - errc <- nil - }) - defer st.Close() - st.greet() - getSlash(st) - - // Send GOAWAY and wait for it to be processed. - st.fr.WriteGoAway(1, ErrCodeNo, nil) - go func() { - for { - select { - case <-ready: - return - default: - } - st.sc.serveMsgCh <- func(loopNum int) { - if !st.sc.pushEnabled { - readyOnce.Do(func() { close(ready) }) - } - } - } - }() - if err := <-errc; err != nil { - t.Error(err) - } -} diff --git a/vendor/golang.org/x/net/http2/server_test.go b/vendor/golang.org/x/net/http2/server_test.go deleted file mode 100644 index 91db6a2c56..0000000000 --- a/vendor/golang.org/x/net/http2/server_test.go +++ /dev/null @@ -1,3728 +0,0 @@ -// Copyright 2014 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 http2 - -import ( - "bytes" - "crypto/tls" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "log" - "net" - "net/http" - "net/http/httptest" - "os" - "os/exec" - "reflect" - "runtime" - "strconv" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "golang.org/x/net/http2/hpack" -) - -var stderrVerbose = flag.Bool("stderr_verbose", false, "Mirror verbosity to stderr, unbuffered") - -func stderrv() io.Writer { - if *stderrVerbose { - return os.Stderr - } - - return ioutil.Discard -} - -type serverTester struct { - cc net.Conn // client conn - t testing.TB - ts *httptest.Server - fr *Framer - serverLogBuf bytes.Buffer // logger for httptest.Server - logFilter []string // substrings to filter out - scMu sync.Mutex // guards sc - sc *serverConn - hpackDec *hpack.Decoder - decodedHeaders [][2]string - - // If http2debug!=2, then we capture Frame debug logs that will be written - // to t.Log after a test fails. The read and write logs use separate locks - // and buffers so we don't accidentally introduce synchronization between - // the read and write goroutines, which may hide data races. - frameReadLogMu sync.Mutex - frameReadLogBuf bytes.Buffer - frameWriteLogMu sync.Mutex - frameWriteLogBuf bytes.Buffer - - // writing headers: - headerBuf bytes.Buffer - hpackEnc *hpack.Encoder -} - -func init() { - testHookOnPanicMu = new(sync.Mutex) - goAwayTimeout = 25 * time.Millisecond -} - -func resetHooks() { - testHookOnPanicMu.Lock() - testHookOnPanic = nil - testHookOnPanicMu.Unlock() -} - -type serverTesterOpt string - -var optOnlyServer = serverTesterOpt("only_server") -var optQuiet = serverTesterOpt("quiet_logging") -var optFramerReuseFrames = serverTesterOpt("frame_reuse_frames") - -func newServerTester(t testing.TB, handler http.HandlerFunc, opts ...interface{}) *serverTester { - resetHooks() - - ts := httptest.NewUnstartedServer(handler) - - tlsConfig := &tls.Config{ - InsecureSkipVerify: true, - NextProtos: []string{NextProtoTLS}, - } - - var onlyServer, quiet, framerReuseFrames bool - h2server := new(Server) - for _, opt := range opts { - switch v := opt.(type) { - case func(*tls.Config): - v(tlsConfig) - case func(*httptest.Server): - v(ts) - case func(*Server): - v(h2server) - case serverTesterOpt: - switch v { - case optOnlyServer: - onlyServer = true - case optQuiet: - quiet = true - case optFramerReuseFrames: - framerReuseFrames = true - } - case func(net.Conn, http.ConnState): - ts.Config.ConnState = v - default: - t.Fatalf("unknown newServerTester option type %T", v) - } - } - - ConfigureServer(ts.Config, h2server) - - st := &serverTester{ - t: t, - ts: ts, - } - st.hpackEnc = hpack.NewEncoder(&st.headerBuf) - st.hpackDec = hpack.NewDecoder(initialHeaderTableSize, st.onHeaderField) - - ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config - if quiet { - ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0) - } else { - ts.Config.ErrorLog = log.New(io.MultiWriter(stderrv(), twriter{t: t, st: st}, &st.serverLogBuf), "", log.LstdFlags) - } - ts.StartTLS() - - if VerboseLogs { - t.Logf("Running test server at: %s", ts.URL) - } - testHookGetServerConn = func(v *serverConn) { - st.scMu.Lock() - defer st.scMu.Unlock() - st.sc = v - } - log.SetOutput(io.MultiWriter(stderrv(), twriter{t: t, st: st})) - if !onlyServer { - cc, err := tls.Dial("tcp", ts.Listener.Addr().String(), tlsConfig) - if err != nil { - t.Fatal(err) - } - st.cc = cc - st.fr = NewFramer(cc, cc) - if framerReuseFrames { - st.fr.SetReuseFrames() - } - if !logFrameReads && !logFrameWrites { - st.fr.debugReadLoggerf = func(m string, v ...interface{}) { - m = time.Now().Format("2006-01-02 15:04:05.999999999 ") + strings.TrimPrefix(m, "http2: ") + "\n" - st.frameReadLogMu.Lock() - fmt.Fprintf(&st.frameReadLogBuf, m, v...) - st.frameReadLogMu.Unlock() - } - st.fr.debugWriteLoggerf = func(m string, v ...interface{}) { - m = time.Now().Format("2006-01-02 15:04:05.999999999 ") + strings.TrimPrefix(m, "http2: ") + "\n" - st.frameWriteLogMu.Lock() - fmt.Fprintf(&st.frameWriteLogBuf, m, v...) - st.frameWriteLogMu.Unlock() - } - st.fr.logReads = true - st.fr.logWrites = true - } - } - return st -} - -func (st *serverTester) closeConn() { - st.scMu.Lock() - defer st.scMu.Unlock() - st.sc.conn.Close() -} - -func (st *serverTester) addLogFilter(phrase string) { - st.logFilter = append(st.logFilter, phrase) -} - -func (st *serverTester) stream(id uint32) *stream { - ch := make(chan *stream, 1) - st.sc.serveMsgCh <- func(int) { - ch <- st.sc.streams[id] - } - return <-ch -} - -func (st *serverTester) streamState(id uint32) streamState { - ch := make(chan streamState, 1) - st.sc.serveMsgCh <- func(int) { - state, _ := st.sc.state(id) - ch <- state - } - return <-ch -} - -// loopNum reports how many times this conn's select loop has gone around. -func (st *serverTester) loopNum() int { - lastc := make(chan int, 1) - st.sc.serveMsgCh <- func(loopNum int) { - lastc <- loopNum - } - return <-lastc -} - -// awaitIdle heuristically awaits for the server conn's select loop to be idle. -// The heuristic is that the server connection's serve loop must schedule -// 50 times in a row without any channel sends or receives occurring. -func (st *serverTester) awaitIdle() { - remain := 50 - last := st.loopNum() - for remain > 0 { - n := st.loopNum() - if n == last+1 { - remain-- - } else { - remain = 50 - } - last = n - } -} - -func (st *serverTester) Close() { - if st.t.Failed() { - st.frameReadLogMu.Lock() - if st.frameReadLogBuf.Len() > 0 { - st.t.Logf("Framer read log:\n%s", st.frameReadLogBuf.String()) - } - st.frameReadLogMu.Unlock() - - st.frameWriteLogMu.Lock() - if st.frameWriteLogBuf.Len() > 0 { - st.t.Logf("Framer write log:\n%s", st.frameWriteLogBuf.String()) - } - st.frameWriteLogMu.Unlock() - - // If we failed already (and are likely in a Fatal, - // unwindowing), force close the connection, so the - // httptest.Server doesn't wait forever for the conn - // to close. - if st.cc != nil { - st.cc.Close() - } - } - st.ts.Close() - if st.cc != nil { - st.cc.Close() - } - log.SetOutput(os.Stderr) -} - -// greet initiates the client's HTTP/2 connection into a state where -// frames may be sent. -func (st *serverTester) greet() { - st.greetAndCheckSettings(func(Setting) error { return nil }) -} - -func (st *serverTester) greetAndCheckSettings(checkSetting func(s Setting) error) { - st.writePreface() - st.writeInitialSettings() - st.wantSettings().ForeachSetting(checkSetting) - st.writeSettingsAck() - - // The initial WINDOW_UPDATE and SETTINGS ACK can come in any order. - var gotSettingsAck bool - var gotWindowUpdate bool - - for i := 0; i < 2; i++ { - f, err := st.readFrame() - if err != nil { - st.t.Fatal(err) - } - switch f := f.(type) { - case *SettingsFrame: - if !f.Header().Flags.Has(FlagSettingsAck) { - st.t.Fatal("Settings Frame didn't have ACK set") - } - gotSettingsAck = true - - case *WindowUpdateFrame: - if f.FrameHeader.StreamID != 0 { - st.t.Fatalf("WindowUpdate StreamID = %d; want 0", f.FrameHeader.StreamID) - } - incr := uint32((&Server{}).initialConnRecvWindowSize() - initialWindowSize) - if f.Increment != incr { - st.t.Fatalf("WindowUpdate increment = %d; want %d", f.Increment, incr) - } - gotWindowUpdate = true - - default: - st.t.Fatalf("Wanting a settings ACK or window update, received a %T", f) - } - } - - if !gotSettingsAck { - st.t.Fatalf("Didn't get a settings ACK") - } - if !gotWindowUpdate { - st.t.Fatalf("Didn't get a window update") - } -} - -func (st *serverTester) writePreface() { - n, err := st.cc.Write(clientPreface) - if err != nil { - st.t.Fatalf("Error writing client preface: %v", err) - } - if n != len(clientPreface) { - st.t.Fatalf("Writing client preface, wrote %d bytes; want %d", n, len(clientPreface)) - } -} - -func (st *serverTester) writeInitialSettings() { - if err := st.fr.WriteSettings(); err != nil { - st.t.Fatalf("Error writing initial SETTINGS frame from client to server: %v", err) - } -} - -func (st *serverTester) writeSettingsAck() { - if err := st.fr.WriteSettingsAck(); err != nil { - st.t.Fatalf("Error writing ACK of server's SETTINGS: %v", err) - } -} - -func (st *serverTester) writeHeaders(p HeadersFrameParam) { - if err := st.fr.WriteHeaders(p); err != nil { - st.t.Fatalf("Error writing HEADERS: %v", err) - } -} - -func (st *serverTester) writePriority(id uint32, p PriorityParam) { - if err := st.fr.WritePriority(id, p); err != nil { - st.t.Fatalf("Error writing PRIORITY: %v", err) - } -} - -func (st *serverTester) encodeHeaderField(k, v string) { - err := st.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v}) - if err != nil { - st.t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) - } -} - -// encodeHeaderRaw is the magic-free version of encodeHeader. -// It takes 0 or more (k, v) pairs and encodes them. -func (st *serverTester) encodeHeaderRaw(headers ...string) []byte { - if len(headers)%2 == 1 { - panic("odd number of kv args") - } - st.headerBuf.Reset() - for len(headers) > 0 { - k, v := headers[0], headers[1] - st.encodeHeaderField(k, v) - headers = headers[2:] - } - return st.headerBuf.Bytes() -} - -// encodeHeader encodes headers and returns their HPACK bytes. headers -// must contain an even number of key/value pairs. There may be -// multiple pairs for keys (e.g. "cookie"). The :method, :path, and -// :scheme headers default to GET, / and https. The :authority header -// defaults to st.ts.Listener.Addr(). -func (st *serverTester) encodeHeader(headers ...string) []byte { - if len(headers)%2 == 1 { - panic("odd number of kv args") - } - - st.headerBuf.Reset() - defaultAuthority := st.ts.Listener.Addr().String() - - if len(headers) == 0 { - // Fast path, mostly for benchmarks, so test code doesn't pollute - // profiles when we're looking to improve server allocations. - st.encodeHeaderField(":method", "GET") - st.encodeHeaderField(":scheme", "https") - st.encodeHeaderField(":authority", defaultAuthority) - st.encodeHeaderField(":path", "/") - return st.headerBuf.Bytes() - } - - if len(headers) == 2 && headers[0] == ":method" { - // Another fast path for benchmarks. - st.encodeHeaderField(":method", headers[1]) - st.encodeHeaderField(":scheme", "https") - st.encodeHeaderField(":authority", defaultAuthority) - st.encodeHeaderField(":path", "/") - return st.headerBuf.Bytes() - } - - pseudoCount := map[string]int{} - keys := []string{":method", ":scheme", ":authority", ":path"} - vals := map[string][]string{ - ":method": {"GET"}, - ":scheme": {"https"}, - ":authority": {defaultAuthority}, - ":path": {"/"}, - } - for len(headers) > 0 { - k, v := headers[0], headers[1] - headers = headers[2:] - if _, ok := vals[k]; !ok { - keys = append(keys, k) - } - if strings.HasPrefix(k, ":") { - pseudoCount[k]++ - if pseudoCount[k] == 1 { - vals[k] = []string{v} - } else { - // Allows testing of invalid headers w/ dup pseudo fields. - vals[k] = append(vals[k], v) - } - } else { - vals[k] = append(vals[k], v) - } - } - for _, k := range keys { - for _, v := range vals[k] { - st.encodeHeaderField(k, v) - } - } - return st.headerBuf.Bytes() -} - -// bodylessReq1 writes a HEADERS frames with StreamID 1 and EndStream and EndHeaders set. -func (st *serverTester) bodylessReq1(headers ...string) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(headers...), - EndStream: true, - EndHeaders: true, - }) -} - -func (st *serverTester) writeData(streamID uint32, endStream bool, data []byte) { - if err := st.fr.WriteData(streamID, endStream, data); err != nil { - st.t.Fatalf("Error writing DATA: %v", err) - } -} - -func (st *serverTester) writeDataPadded(streamID uint32, endStream bool, data, pad []byte) { - if err := st.fr.WriteDataPadded(streamID, endStream, data, pad); err != nil { - st.t.Fatalf("Error writing DATA: %v", err) - } -} - -func readFrameTimeout(fr *Framer, wait time.Duration) (Frame, error) { - ch := make(chan interface{}, 1) - go func() { - fr, err := fr.ReadFrame() - if err != nil { - ch <- err - } else { - ch <- fr - } - }() - t := time.NewTimer(wait) - select { - case v := <-ch: - t.Stop() - if fr, ok := v.(Frame); ok { - return fr, nil - } - return nil, v.(error) - case <-t.C: - return nil, errors.New("timeout waiting for frame") - } -} - -func (st *serverTester) readFrame() (Frame, error) { - return readFrameTimeout(st.fr, 2*time.Second) -} - -func (st *serverTester) wantHeaders() *HeadersFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a HEADERS frame: %v", err) - } - hf, ok := f.(*HeadersFrame) - if !ok { - st.t.Fatalf("got a %T; want *HeadersFrame", f) - } - return hf -} - -func (st *serverTester) wantContinuation() *ContinuationFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a CONTINUATION frame: %v", err) - } - cf, ok := f.(*ContinuationFrame) - if !ok { - st.t.Fatalf("got a %T; want *ContinuationFrame", f) - } - return cf -} - -func (st *serverTester) wantData() *DataFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a DATA frame: %v", err) - } - df, ok := f.(*DataFrame) - if !ok { - st.t.Fatalf("got a %T; want *DataFrame", f) - } - return df -} - -func (st *serverTester) wantSettings() *SettingsFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a SETTINGS frame: %v", err) - } - sf, ok := f.(*SettingsFrame) - if !ok { - st.t.Fatalf("got a %T; want *SettingsFrame", f) - } - return sf -} - -func (st *serverTester) wantPing() *PingFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a PING frame: %v", err) - } - pf, ok := f.(*PingFrame) - if !ok { - st.t.Fatalf("got a %T; want *PingFrame", f) - } - return pf -} - -func (st *serverTester) wantGoAway() *GoAwayFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a GOAWAY frame: %v", err) - } - gf, ok := f.(*GoAwayFrame) - if !ok { - st.t.Fatalf("got a %T; want *GoAwayFrame", f) - } - return gf -} - -func (st *serverTester) wantRSTStream(streamID uint32, errCode ErrCode) { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting an RSTStream frame: %v", err) - } - rs, ok := f.(*RSTStreamFrame) - if !ok { - st.t.Fatalf("got a %T; want *RSTStreamFrame", f) - } - if rs.FrameHeader.StreamID != streamID { - st.t.Fatalf("RSTStream StreamID = %d; want %d", rs.FrameHeader.StreamID, streamID) - } - if rs.ErrCode != errCode { - st.t.Fatalf("RSTStream ErrCode = %d (%s); want %d (%s)", rs.ErrCode, rs.ErrCode, errCode, errCode) - } -} - -func (st *serverTester) wantWindowUpdate(streamID, incr uint32) { - f, err := st.readFrame() - if err != nil { - st.t.Fatalf("Error while expecting a WINDOW_UPDATE frame: %v", err) - } - wu, ok := f.(*WindowUpdateFrame) - if !ok { - st.t.Fatalf("got a %T; want *WindowUpdateFrame", f) - } - if wu.FrameHeader.StreamID != streamID { - st.t.Fatalf("WindowUpdate StreamID = %d; want %d", wu.FrameHeader.StreamID, streamID) - } - if wu.Increment != incr { - st.t.Fatalf("WindowUpdate increment = %d; want %d", wu.Increment, incr) - } -} - -func (st *serverTester) wantSettingsAck() { - f, err := st.readFrame() - if err != nil { - st.t.Fatal(err) - } - sf, ok := f.(*SettingsFrame) - if !ok { - st.t.Fatalf("Wanting a settings ACK, received a %T", f) - } - if !sf.Header().Flags.Has(FlagSettingsAck) { - st.t.Fatal("Settings Frame didn't have ACK set") - } -} - -func (st *serverTester) wantPushPromise() *PushPromiseFrame { - f, err := st.readFrame() - if err != nil { - st.t.Fatal(err) - } - ppf, ok := f.(*PushPromiseFrame) - if !ok { - st.t.Fatalf("Wanted PushPromise, received %T", ppf) - } - return ppf -} - -func TestServer(t *testing.T) { - gotReq := make(chan bool, 1) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Foo", "Bar") - gotReq <- true - }) - defer st.Close() - - covers("3.5", ` - The server connection preface consists of a potentially empty - SETTINGS frame ([SETTINGS]) that MUST be the first frame the - server sends in the HTTP/2 connection. - `) - - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(), - EndStream: true, // no DATA frames - EndHeaders: true, - }) - - select { - case <-gotReq: - case <-time.After(2 * time.Second): - t.Error("timeout waiting for request") - } -} - -func TestServer_Request_Get(t *testing.T) { - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader("foo-bar", "some-value"), - EndStream: true, // no DATA frames - EndHeaders: true, - }) - }, func(r *http.Request) { - if r.Method != "GET" { - t.Errorf("Method = %q; want GET", r.Method) - } - if r.URL.Path != "/" { - t.Errorf("URL.Path = %q; want /", r.URL.Path) - } - if r.ContentLength != 0 { - t.Errorf("ContentLength = %v; want 0", r.ContentLength) - } - if r.Close { - t.Error("Close = true; want false") - } - if !strings.Contains(r.RemoteAddr, ":") { - t.Errorf("RemoteAddr = %q; want something with a colon", r.RemoteAddr) - } - if r.Proto != "HTTP/2.0" || r.ProtoMajor != 2 || r.ProtoMinor != 0 { - t.Errorf("Proto = %q Major=%v,Minor=%v; want HTTP/2.0", r.Proto, r.ProtoMajor, r.ProtoMinor) - } - wantHeader := http.Header{ - "Foo-Bar": []string{"some-value"}, - } - if !reflect.DeepEqual(r.Header, wantHeader) { - t.Errorf("Header = %#v; want %#v", r.Header, wantHeader) - } - if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 { - t.Errorf("Read = %d, %v; want 0, EOF", n, err) - } - }) -} - -func TestServer_Request_Get_PathSlashes(t *testing.T) { - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":path", "/%2f/"), - EndStream: true, // no DATA frames - EndHeaders: true, - }) - }, func(r *http.Request) { - if r.RequestURI != "/%2f/" { - t.Errorf("RequestURI = %q; want /%%2f/", r.RequestURI) - } - if r.URL.Path != "///" { - t.Errorf("URL.Path = %q; want ///", r.URL.Path) - } - }) -} - -// TODO: add a test with EndStream=true on the HEADERS but setting a -// Content-Length anyway. Should we just omit it and force it to -// zero? - -func TestServer_Request_Post_NoContentLength_EndStream(t *testing.T) { - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: true, - EndHeaders: true, - }) - }, func(r *http.Request) { - if r.Method != "POST" { - t.Errorf("Method = %q; want POST", r.Method) - } - if r.ContentLength != 0 { - t.Errorf("ContentLength = %v; want 0", r.ContentLength) - } - if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 { - t.Errorf("Read = %d, %v; want 0, EOF", n, err) - } - }) -} - -func TestServer_Request_Post_Body_ImmediateEOF(t *testing.T) { - testBodyContents(t, -1, "", func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, nil) // just kidding. empty body. - }) -} - -func TestServer_Request_Post_Body_OneData(t *testing.T) { - const content = "Some content" - testBodyContents(t, -1, content, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, []byte(content)) - }) -} - -func TestServer_Request_Post_Body_TwoData(t *testing.T) { - const content = "Some content" - testBodyContents(t, -1, content, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, false, []byte(content[:5])) - st.writeData(1, true, []byte(content[5:])) - }) -} - -func TestServer_Request_Post_Body_ContentLength_Correct(t *testing.T) { - const content = "Some content" - testBodyContents(t, int64(len(content)), content, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader( - ":method", "POST", - "content-length", strconv.Itoa(len(content)), - ), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, []byte(content)) - }) -} - -func TestServer_Request_Post_Body_ContentLength_TooLarge(t *testing.T) { - testBodyContentsFail(t, 3, "request declared a Content-Length of 3 but only wrote 2 bytes", - func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader( - ":method", "POST", - "content-length", "3", - ), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, []byte("12")) - }) -} - -func TestServer_Request_Post_Body_ContentLength_TooSmall(t *testing.T) { - testBodyContentsFail(t, 4, "sender tried to send more than declared Content-Length of 4 bytes", - func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader( - ":method", "POST", - "content-length", "4", - ), - EndStream: false, // to say DATA frames are coming - EndHeaders: true, - }) - st.writeData(1, true, []byte("12345")) - }) -} - -func testBodyContents(t *testing.T, wantContentLength int64, wantBody string, write func(st *serverTester)) { - testServerRequest(t, write, func(r *http.Request) { - if r.Method != "POST" { - t.Errorf("Method = %q; want POST", r.Method) - } - if r.ContentLength != wantContentLength { - t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength) - } - all, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Fatal(err) - } - if string(all) != wantBody { - t.Errorf("Read = %q; want %q", all, wantBody) - } - if err := r.Body.Close(); err != nil { - t.Fatalf("Close: %v", err) - } - }) -} - -func testBodyContentsFail(t *testing.T, wantContentLength int64, wantReadError string, write func(st *serverTester)) { - testServerRequest(t, write, func(r *http.Request) { - if r.Method != "POST" { - t.Errorf("Method = %q; want POST", r.Method) - } - if r.ContentLength != wantContentLength { - t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength) - } - all, err := ioutil.ReadAll(r.Body) - if err == nil { - t.Fatalf("expected an error (%q) reading from the body. Successfully read %q instead.", - wantReadError, all) - } - if !strings.Contains(err.Error(), wantReadError) { - t.Fatalf("Body.Read = %v; want substring %q", err, wantReadError) - } - if err := r.Body.Close(); err != nil { - t.Fatalf("Close: %v", err) - } - }) -} - -// Using a Host header, instead of :authority -func TestServer_Request_Get_Host(t *testing.T) { - const host = "example.com" - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":authority", "", "host", host), - EndStream: true, - EndHeaders: true, - }) - }, func(r *http.Request) { - if r.Host != host { - t.Errorf("Host = %q; want %q", r.Host, host) - } - }) -} - -// Using an :authority pseudo-header, instead of Host -func TestServer_Request_Get_Authority(t *testing.T) { - const host = "example.com" - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":authority", host), - EndStream: true, - EndHeaders: true, - }) - }, func(r *http.Request) { - if r.Host != host { - t.Errorf("Host = %q; want %q", r.Host, host) - } - }) -} - -func TestServer_Request_WithContinuation(t *testing.T) { - wantHeader := http.Header{ - "Foo-One": []string{"value-one"}, - "Foo-Two": []string{"value-two"}, - "Foo-Three": []string{"value-three"}, - } - testServerRequest(t, func(st *serverTester) { - fullHeaders := st.encodeHeader( - "foo-one", "value-one", - "foo-two", "value-two", - "foo-three", "value-three", - ) - remain := fullHeaders - chunks := 0 - for len(remain) > 0 { - const maxChunkSize = 5 - chunk := remain - if len(chunk) > maxChunkSize { - chunk = chunk[:maxChunkSize] - } - remain = remain[len(chunk):] - - if chunks == 0 { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: chunk, - EndStream: true, // no DATA frames - EndHeaders: false, // we'll have continuation frames - }) - } else { - err := st.fr.WriteContinuation(1, len(remain) == 0, chunk) - if err != nil { - t.Fatal(err) - } - } - chunks++ - } - if chunks < 2 { - t.Fatal("too few chunks") - } - }, func(r *http.Request) { - if !reflect.DeepEqual(r.Header, wantHeader) { - t.Errorf("Header = %#v; want %#v", r.Header, wantHeader) - } - }) -} - -// Concatenated cookie headers. ("8.1.2.5 Compressing the Cookie Header Field") -func TestServer_Request_CookieConcat(t *testing.T) { - const host = "example.com" - testServerRequest(t, func(st *serverTester) { - st.bodylessReq1( - ":authority", host, - "cookie", "a=b", - "cookie", "c=d", - "cookie", "e=f", - ) - }, func(r *http.Request) { - const want = "a=b; c=d; e=f" - if got := r.Header.Get("Cookie"); got != want { - t.Errorf("Cookie = %q; want %q", got, want) - } - }) -} - -func TestServer_Request_Reject_CapitalHeader(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("UPPER", "v") }) -} - -func TestServer_Request_Reject_HeaderFieldNameColon(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("has:colon", "v") }) -} - -func TestServer_Request_Reject_HeaderFieldNameNULL(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("has\x00null", "v") }) -} - -func TestServer_Request_Reject_HeaderFieldNameEmpty(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("", "v") }) -} - -func TestServer_Request_Reject_HeaderFieldValueNewline(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\nnewline") }) -} - -func TestServer_Request_Reject_HeaderFieldValueCR(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\rcarriage") }) -} - -func TestServer_Request_Reject_HeaderFieldValueDEL(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("foo", "has\x7fdel") }) -} - -func TestServer_Request_Reject_Pseudo_Missing_method(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":method", "") }) -} - -func TestServer_Request_Reject_Pseudo_ExactlyOne(t *testing.T) { - // 8.1.2.3 Request Pseudo-Header Fields - // "All HTTP/2 requests MUST include exactly one valid value" ... - testRejectRequest(t, func(st *serverTester) { - st.addLogFilter("duplicate pseudo-header") - st.bodylessReq1(":method", "GET", ":method", "POST") - }) -} - -func TestServer_Request_Reject_Pseudo_AfterRegular(t *testing.T) { - // 8.1.2.3 Request Pseudo-Header Fields - // "All pseudo-header fields MUST appear in the header block - // before regular header fields. Any request or response that - // contains a pseudo-header field that appears in a header - // block after a regular header field MUST be treated as - // malformed (Section 8.1.2.6)." - testRejectRequest(t, func(st *serverTester) { - st.addLogFilter("pseudo-header after regular header") - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":method", Value: "GET"}) - enc.WriteField(hpack.HeaderField{Name: "regular", Value: "foobar"}) - enc.WriteField(hpack.HeaderField{Name: ":path", Value: "/"}) - enc.WriteField(hpack.HeaderField{Name: ":scheme", Value: "https"}) - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: buf.Bytes(), - EndStream: true, - EndHeaders: true, - }) - }) -} - -func TestServer_Request_Reject_Pseudo_Missing_path(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":path", "") }) -} - -func TestServer_Request_Reject_Pseudo_Missing_scheme(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "") }) -} - -func TestServer_Request_Reject_Pseudo_scheme_invalid(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "bogus") }) -} - -func TestServer_Request_Reject_Pseudo_Unknown(t *testing.T) { - testRejectRequest(t, func(st *serverTester) { - st.addLogFilter(`invalid pseudo-header ":unknown_thing"`) - st.bodylessReq1(":unknown_thing", "") - }) -} - -func testRejectRequest(t *testing.T, send func(*serverTester)) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - t.Error("server request made it to handler; should've been rejected") - }) - defer st.Close() - - st.greet() - send(st) - st.wantRSTStream(1, ErrCodeProtocol) -} - -func testRejectRequestWithProtocolError(t *testing.T, send func(*serverTester)) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - t.Error("server request made it to handler; should've been rejected") - }, optQuiet) - defer st.Close() - - st.greet() - send(st) - gf := st.wantGoAway() - if gf.ErrCode != ErrCodeProtocol { - t.Errorf("err code = %v; want %v", gf.ErrCode, ErrCodeProtocol) - } -} - -// Section 5.1, on idle connections: "Receiving any frame other than -// HEADERS or PRIORITY on a stream in this state MUST be treated as a -// connection error (Section 5.4.1) of type PROTOCOL_ERROR." -func TestRejectFrameOnIdle_WindowUpdate(t *testing.T) { - testRejectRequestWithProtocolError(t, func(st *serverTester) { - st.fr.WriteWindowUpdate(123, 456) - }) -} -func TestRejectFrameOnIdle_Data(t *testing.T) { - testRejectRequestWithProtocolError(t, func(st *serverTester) { - st.fr.WriteData(123, true, nil) - }) -} -func TestRejectFrameOnIdle_RSTStream(t *testing.T) { - testRejectRequestWithProtocolError(t, func(st *serverTester) { - st.fr.WriteRSTStream(123, ErrCodeCancel) - }) -} - -func TestServer_Request_Connect(t *testing.T) { - testServerRequest(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeaderRaw( - ":method", "CONNECT", - ":authority", "example.com:123", - ), - EndStream: true, - EndHeaders: true, - }) - }, func(r *http.Request) { - if g, w := r.Method, "CONNECT"; g != w { - t.Errorf("Method = %q; want %q", g, w) - } - if g, w := r.RequestURI, "example.com:123"; g != w { - t.Errorf("RequestURI = %q; want %q", g, w) - } - if g, w := r.URL.Host, "example.com:123"; g != w { - t.Errorf("URL.Host = %q; want %q", g, w) - } - }) -} - -func TestServer_Request_Connect_InvalidPath(t *testing.T) { - testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeaderRaw( - ":method", "CONNECT", - ":authority", "example.com:123", - ":path", "/bogus", - ), - EndStream: true, - EndHeaders: true, - }) - }) -} - -func TestServer_Request_Connect_InvalidScheme(t *testing.T) { - testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeaderRaw( - ":method", "CONNECT", - ":authority", "example.com:123", - ":scheme", "https", - ), - EndStream: true, - EndHeaders: true, - }) - }) -} - -func TestServer_Ping(t *testing.T) { - st := newServerTester(t, nil) - defer st.Close() - st.greet() - - // Server should ignore this one, since it has ACK set. - ackPingData := [8]byte{1, 2, 4, 8, 16, 32, 64, 128} - if err := st.fr.WritePing(true, ackPingData); err != nil { - t.Fatal(err) - } - - // But the server should reply to this one, since ACK is false. - pingData := [8]byte{1, 2, 3, 4, 5, 6, 7, 8} - if err := st.fr.WritePing(false, pingData); err != nil { - t.Fatal(err) - } - - pf := st.wantPing() - if !pf.Flags.Has(FlagPingAck) { - t.Error("response ping doesn't have ACK set") - } - if pf.Data != pingData { - t.Errorf("response ping has data %q; want %q", pf.Data, pingData) - } -} - -func TestServer_RejectsLargeFrames(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("see golang.org/issue/13434") - } - - st := newServerTester(t, nil) - defer st.Close() - st.greet() - - // Write too large of a frame (too large by one byte) - // We ignore the return value because it's expected that the server - // will only read the first 9 bytes (the headre) and then disconnect. - st.fr.WriteRawFrame(0xff, 0, 0, make([]byte, defaultMaxReadFrameSize+1)) - - gf := st.wantGoAway() - if gf.ErrCode != ErrCodeFrameSize { - t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFrameSize) - } - if st.serverLogBuf.Len() != 0 { - // Previously we spun here for a bit until the GOAWAY disconnect - // timer fired, logging while we fired. - t.Errorf("unexpected server output: %.500s\n", st.serverLogBuf.Bytes()) - } -} - -func TestServer_Handler_Sends_WindowUpdate(t *testing.T) { - puppet := newHandlerPuppet() - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - puppet.act(w, r) - }) - defer st.Close() - defer puppet.done() - - st.greet() - - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // data coming - EndHeaders: true, - }) - st.writeData(1, false, []byte("abcdef")) - puppet.do(readBodyHandler(t, "abc")) - st.wantWindowUpdate(0, 3) - st.wantWindowUpdate(1, 3) - - puppet.do(readBodyHandler(t, "def")) - st.wantWindowUpdate(0, 3) - st.wantWindowUpdate(1, 3) - - st.writeData(1, true, []byte("ghijkl")) // END_STREAM here - puppet.do(readBodyHandler(t, "ghi")) - puppet.do(readBodyHandler(t, "jkl")) - st.wantWindowUpdate(0, 3) - st.wantWindowUpdate(0, 3) // no more stream-level, since END_STREAM -} - -// the version of the TestServer_Handler_Sends_WindowUpdate with padding. -// See golang.org/issue/16556 -func TestServer_Handler_Sends_WindowUpdate_Padding(t *testing.T) { - puppet := newHandlerPuppet() - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - puppet.act(w, r) - }) - defer st.Close() - defer puppet.done() - - st.greet() - - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, - EndHeaders: true, - }) - st.writeDataPadded(1, false, []byte("abcdef"), []byte{0, 0, 0, 0}) - - // Expect to immediately get our 5 bytes of padding back for - // both the connection and stream (4 bytes of padding + 1 byte of length) - st.wantWindowUpdate(0, 5) - st.wantWindowUpdate(1, 5) - - puppet.do(readBodyHandler(t, "abc")) - st.wantWindowUpdate(0, 3) - st.wantWindowUpdate(1, 3) - - puppet.do(readBodyHandler(t, "def")) - st.wantWindowUpdate(0, 3) - st.wantWindowUpdate(1, 3) -} - -func TestServer_Send_GoAway_After_Bogus_WindowUpdate(t *testing.T) { - st := newServerTester(t, nil) - defer st.Close() - st.greet() - if err := st.fr.WriteWindowUpdate(0, 1<<31-1); err != nil { - t.Fatal(err) - } - gf := st.wantGoAway() - if gf.ErrCode != ErrCodeFlowControl { - t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFlowControl) - } - if gf.LastStreamID != 0 { - t.Errorf("GOAWAY last stream ID = %v; want %v", gf.LastStreamID, 0) - } -} - -func TestServer_Send_RstStream_After_Bogus_WindowUpdate(t *testing.T) { - inHandler := make(chan bool) - blockHandler := make(chan bool) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - inHandler <- true - <-blockHandler - }) - defer st.Close() - defer close(blockHandler) - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // keep it open - EndHeaders: true, - }) - <-inHandler - // Send a bogus window update: - if err := st.fr.WriteWindowUpdate(1, 1<<31-1); err != nil { - t.Fatal(err) - } - st.wantRSTStream(1, ErrCodeFlowControl) -} - -// testServerPostUnblock sends a hanging POST with unsent data to handler, -// then runs fn once in the handler, and verifies that the error returned from -// handler is acceptable. It fails if takes over 5 seconds for handler to exit. -func testServerPostUnblock(t *testing.T, - handler func(http.ResponseWriter, *http.Request) error, - fn func(*serverTester), - checkErr func(error), - otherHeaders ...string) { - inHandler := make(chan bool) - errc := make(chan error, 1) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - inHandler <- true - errc <- handler(w, r) - }) - defer st.Close() - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(append([]string{":method", "POST"}, otherHeaders...)...), - EndStream: false, // keep it open - EndHeaders: true, - }) - <-inHandler - fn(st) - select { - case err := <-errc: - if checkErr != nil { - checkErr(err) - } - case <-time.After(5 * time.Second): - t.Fatal("timeout waiting for Handler to return") - } -} - -func TestServer_RSTStream_Unblocks_Read(t *testing.T) { - testServerPostUnblock(t, - func(w http.ResponseWriter, r *http.Request) (err error) { - _, err = r.Body.Read(make([]byte, 1)) - return - }, - func(st *serverTester) { - if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { - t.Fatal(err) - } - }, - func(err error) { - want := StreamError{StreamID: 0x1, Code: 0x8} - if !reflect.DeepEqual(err, want) { - t.Errorf("Read error = %v; want %v", err, want) - } - }, - ) -} - -func TestServer_RSTStream_Unblocks_Header_Write(t *testing.T) { - // Run this test a bunch, because it doesn't always - // deadlock. But with a bunch, it did. - n := 50 - if testing.Short() { - n = 5 - } - for i := 0; i < n; i++ { - testServer_RSTStream_Unblocks_Header_Write(t) - } -} - -func testServer_RSTStream_Unblocks_Header_Write(t *testing.T) { - inHandler := make(chan bool, 1) - unblockHandler := make(chan bool, 1) - headerWritten := make(chan bool, 1) - wroteRST := make(chan bool, 1) - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - inHandler <- true - <-wroteRST - w.Header().Set("foo", "bar") - w.WriteHeader(200) - w.(http.Flusher).Flush() - headerWritten <- true - <-unblockHandler - }) - defer st.Close() - - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // keep it open - EndHeaders: true, - }) - <-inHandler - if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { - t.Fatal(err) - } - wroteRST <- true - st.awaitIdle() - select { - case <-headerWritten: - case <-time.After(2 * time.Second): - t.Error("timeout waiting for header write") - } - unblockHandler <- true -} - -func TestServer_DeadConn_Unblocks_Read(t *testing.T) { - testServerPostUnblock(t, - func(w http.ResponseWriter, r *http.Request) (err error) { - _, err = r.Body.Read(make([]byte, 1)) - return - }, - func(st *serverTester) { st.cc.Close() }, - func(err error) { - if err == nil { - t.Error("unexpected nil error from Request.Body.Read") - } - }, - ) -} - -var blockUntilClosed = func(w http.ResponseWriter, r *http.Request) error { - <-w.(http.CloseNotifier).CloseNotify() - return nil -} - -func TestServer_CloseNotify_After_RSTStream(t *testing.T) { - testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { - if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { - t.Fatal(err) - } - }, nil) -} - -func TestServer_CloseNotify_After_ConnClose(t *testing.T) { - testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { st.cc.Close() }, nil) -} - -// that CloseNotify unblocks after a stream error due to the client's -// problem that's unrelated to them explicitly canceling it (which is -// TestServer_CloseNotify_After_RSTStream above) -func TestServer_CloseNotify_After_StreamError(t *testing.T) { - testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { - // data longer than declared Content-Length => stream error - st.writeData(1, true, []byte("1234")) - }, nil, "content-length", "3") -} - -func TestServer_StateTransitions(t *testing.T) { - var st *serverTester - inHandler := make(chan bool) - writeData := make(chan bool) - leaveHandler := make(chan bool) - st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - inHandler <- true - if st.stream(1) == nil { - t.Errorf("nil stream 1 in handler") - } - if got, want := st.streamState(1), stateOpen; got != want { - t.Errorf("in handler, state is %v; want %v", got, want) - } - writeData <- true - if n, err := r.Body.Read(make([]byte, 1)); n != 0 || err != io.EOF { - t.Errorf("body read = %d, %v; want 0, EOF", n, err) - } - if got, want := st.streamState(1), stateHalfClosedRemote; got != want { - t.Errorf("in handler, state is %v; want %v", got, want) - } - - <-leaveHandler - }) - st.greet() - if st.stream(1) != nil { - t.Fatal("stream 1 should be empty") - } - if got := st.streamState(1); got != stateIdle { - t.Fatalf("stream 1 should be idle; got %v", got) - } - - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, // keep it open - EndHeaders: true, - }) - <-inHandler - <-writeData - st.writeData(1, true, nil) - - leaveHandler <- true - hf := st.wantHeaders() - if !hf.StreamEnded() { - t.Fatal("expected END_STREAM flag") - } - - if got, want := st.streamState(1), stateClosed; got != want { - t.Errorf("at end, state is %v; want %v", got, want) - } - if st.stream(1) != nil { - t.Fatal("at end, stream 1 should be gone") - } -} - -// test HEADERS w/o EndHeaders + another HEADERS (should get rejected) -func TestServer_Rejects_HeadersNoEnd_Then_Headers(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: false, - }) - st.writeHeaders(HeadersFrameParam{ // Not a continuation. - StreamID: 3, // different stream. - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - }) -} - -// test HEADERS w/o EndHeaders + PING (should get rejected) -func TestServer_Rejects_HeadersNoEnd_Then_Ping(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: false, - }) - if err := st.fr.WritePing(false, [8]byte{}); err != nil { - t.Fatal(err) - } - }) -} - -// test HEADERS w/ EndHeaders + a continuation HEADERS (should get rejected) -func TestServer_Rejects_HeadersEnd_Then_Continuation(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - st.wantHeaders() - if err := st.fr.WriteContinuation(1, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil { - t.Fatal(err) - } - }) -} - -// test HEADERS w/o EndHeaders + a continuation HEADERS on wrong stream ID -func TestServer_Rejects_HeadersNoEnd_Then_ContinuationWrongStream(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: false, - }) - if err := st.fr.WriteContinuation(3, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil { - t.Fatal(err) - } - }) -} - -// No HEADERS on stream 0. -func TestServer_Rejects_Headers0(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.fr.AllowIllegalWrites = true - st.writeHeaders(HeadersFrameParam{ - StreamID: 0, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - }) -} - -// No CONTINUATION on stream 0. -func TestServer_Rejects_Continuation0(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.fr.AllowIllegalWrites = true - if err := st.fr.WriteContinuation(0, true, st.encodeHeader()); err != nil { - t.Fatal(err) - } - }) -} - -// No PRIORITY on stream 0. -func TestServer_Rejects_Priority0(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - st.fr.AllowIllegalWrites = true - st.writePriority(0, PriorityParam{StreamDep: 1}) - }) -} - -// No HEADERS frame with a self-dependence. -func TestServer_Rejects_HeadersSelfDependence(t *testing.T) { - testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { - st.fr.AllowIllegalWrites = true - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - Priority: PriorityParam{StreamDep: 1}, - }) - }) -} - -// No PRIORTY frame with a self-dependence. -func TestServer_Rejects_PrioritySelfDependence(t *testing.T) { - testServerRejectsStream(t, ErrCodeProtocol, func(st *serverTester) { - st.fr.AllowIllegalWrites = true - st.writePriority(1, PriorityParam{StreamDep: 1}) - }) -} - -func TestServer_Rejects_PushPromise(t *testing.T) { - testServerRejectsConn(t, func(st *serverTester) { - pp := PushPromiseParam{ - StreamID: 1, - PromiseID: 3, - } - if err := st.fr.WritePushPromise(pp); err != nil { - t.Fatal(err) - } - }) -} - -// testServerRejectsConn tests that the server hangs up with a GOAWAY -// frame and a server close after the client does something -// deserving a CONNECTION_ERROR. -func testServerRejectsConn(t *testing.T, writeReq func(*serverTester)) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}) - st.addLogFilter("connection error: PROTOCOL_ERROR") - defer st.Close() - st.greet() - writeReq(st) - - st.wantGoAway() - errc := make(chan error, 1) - go func() { - fr, err := st.fr.ReadFrame() - if err == nil { - err = fmt.Errorf("got frame of type %T", fr) - } - errc <- err - }() - select { - case err := <-errc: - if err != io.EOF { - t.Errorf("ReadFrame = %v; want io.EOF", err) - } - case <-time.After(2 * time.Second): - t.Error("timeout waiting for disconnect") - } -} - -// testServerRejectsStream tests that the server sends a RST_STREAM with the provided -// error code after a client sends a bogus request. -func testServerRejectsStream(t *testing.T, code ErrCode, writeReq func(*serverTester)) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}) - defer st.Close() - st.greet() - writeReq(st) - st.wantRSTStream(1, code) -} - -// testServerRequest sets up an idle HTTP/2 connection and lets you -// write a single request with writeReq, and then verify that the -// *http.Request is built correctly in checkReq. -func testServerRequest(t *testing.T, writeReq func(*serverTester), checkReq func(*http.Request)) { - gotReq := make(chan bool, 1) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - if r.Body == nil { - t.Fatal("nil Body") - } - checkReq(r) - gotReq <- true - }) - defer st.Close() - - st.greet() - writeReq(st) - - select { - case <-gotReq: - case <-time.After(2 * time.Second): - t.Error("timeout waiting for request") - } -} - -func getSlash(st *serverTester) { st.bodylessReq1() } - -func TestServer_Response_NoData(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - // Nothing. - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if !hf.StreamEnded() { - t.Fatal("want END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - }) -} - -func TestServer_Response_NoData_Header_FooBar(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("Foo-Bar", "some-value") - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if !hf.StreamEnded() { - t.Fatal("want END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"foo-bar", "some-value"}, - {"content-type", "text/plain; charset=utf-8"}, - {"content-length", "0"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - }) -} - -func TestServer_Response_Data_Sniff_DoesntOverride(t *testing.T) { - const msg = "<html>this is HTML." - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("Content-Type", "foo/bar") - io.WriteString(w, msg) - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("don't want END_STREAM, expecting data") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "foo/bar"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - df := st.wantData() - if !df.StreamEnded() { - t.Error("expected DATA to have END_STREAM flag") - } - if got := string(df.Data()); got != msg { - t.Errorf("got DATA %q; want %q", got, msg) - } - }) -} - -func TestServer_Response_TransferEncoding_chunked(t *testing.T) { - const msg = "hi" - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("Transfer-Encoding", "chunked") // should be stripped - io.WriteString(w, msg) - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "text/plain; charset=utf-8"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - }) -} - -// Header accessed only after the initial write. -func TestServer_Response_Data_IgnoreHeaderAfterWrite_After(t *testing.T) { - const msg = "<html>this is HTML." - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - io.WriteString(w, msg) - w.Header().Set("foo", "should be ignored") - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "text/html; charset=utf-8"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - }) -} - -// Header accessed before the initial write and later mutated. -func TestServer_Response_Data_IgnoreHeaderAfterWrite_Overwrite(t *testing.T) { - const msg = "<html>this is HTML." - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("foo", "proper value") - io.WriteString(w, msg) - w.Header().Set("foo", "should be ignored") - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"foo", "proper value"}, - {"content-type", "text/html; charset=utf-8"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - }) -} - -func TestServer_Response_Data_SniffLenType(t *testing.T) { - const msg = "<html>this is HTML." - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - io.WriteString(w, msg) - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("don't want END_STREAM, expecting data") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "text/html; charset=utf-8"}, - {"content-length", strconv.Itoa(len(msg))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - df := st.wantData() - if !df.StreamEnded() { - t.Error("expected DATA to have END_STREAM flag") - } - if got := string(df.Data()); got != msg { - t.Errorf("got DATA %q; want %q", got, msg) - } - }) -} - -func TestServer_Response_Header_Flush_MidWrite(t *testing.T) { - const msg = "<html>this is HTML" - const msg2 = ", and this is the next chunk" - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - io.WriteString(w, msg) - w.(http.Flusher).Flush() - io.WriteString(w, msg2) - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "text/html; charset=utf-8"}, // sniffed - // and no content-length - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - { - df := st.wantData() - if df.StreamEnded() { - t.Error("unexpected END_STREAM flag") - } - if got := string(df.Data()); got != msg { - t.Errorf("got DATA %q; want %q", got, msg) - } - } - { - df := st.wantData() - if !df.StreamEnded() { - t.Error("wanted END_STREAM flag on last data chunk") - } - if got := string(df.Data()); got != msg2 { - t.Errorf("got DATA %q; want %q", got, msg2) - } - } - }) -} - -func TestServer_Response_LargeWrite(t *testing.T) { - const size = 1 << 20 - const maxFrameSize = 16 << 10 - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - n, err := w.Write(bytes.Repeat([]byte("a"), size)) - if err != nil { - return fmt.Errorf("Write error: %v", err) - } - if n != size { - return fmt.Errorf("wrong size %d from Write", n) - } - return nil - }, func(st *serverTester) { - if err := st.fr.WriteSettings( - Setting{SettingInitialWindowSize, 0}, - Setting{SettingMaxFrameSize, maxFrameSize}, - ); err != nil { - t.Fatal(err) - } - st.wantSettingsAck() - - getSlash(st) // make the single request - - // Give the handler quota to write: - if err := st.fr.WriteWindowUpdate(1, size); err != nil { - t.Fatal(err) - } - // Give the handler quota to write to connection-level - // window as well - if err := st.fr.WriteWindowUpdate(0, size); err != nil { - t.Fatal(err) - } - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"content-type", "text/plain; charset=utf-8"}, // sniffed - // and no content-length - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - var bytes, frames int - for { - df := st.wantData() - bytes += len(df.Data()) - frames++ - for _, b := range df.Data() { - if b != 'a' { - t.Fatal("non-'a' byte seen in DATA") - } - } - if df.StreamEnded() { - break - } - } - if bytes != size { - t.Errorf("Got %d bytes; want %d", bytes, size) - } - if want := int(size / maxFrameSize); frames < want || frames > want*2 { - t.Errorf("Got %d frames; want %d", frames, size) - } - }) -} - -// Test that the handler can't write more than the client allows -func TestServer_Response_LargeWrite_FlowControlled(t *testing.T) { - // Make these reads. Before each read, the client adds exactly enough - // flow-control to satisfy the read. Numbers chosen arbitrarily. - reads := []int{123, 1, 13, 127} - size := 0 - for _, n := range reads { - size += n - } - - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.(http.Flusher).Flush() - n, err := w.Write(bytes.Repeat([]byte("a"), size)) - if err != nil { - return fmt.Errorf("Write error: %v", err) - } - if n != size { - return fmt.Errorf("wrong size %d from Write", n) - } - return nil - }, func(st *serverTester) { - // Set the window size to something explicit for this test. - // It's also how much initial data we expect. - if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, uint32(reads[0])}); err != nil { - t.Fatal(err) - } - st.wantSettingsAck() - - getSlash(st) // make the single request - - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - - df := st.wantData() - if got := len(df.Data()); got != reads[0] { - t.Fatalf("Initial window size = %d but got DATA with %d bytes", reads[0], got) - } - - for _, quota := range reads[1:] { - if err := st.fr.WriteWindowUpdate(1, uint32(quota)); err != nil { - t.Fatal(err) - } - df := st.wantData() - if int(quota) != len(df.Data()) { - t.Fatalf("read %d bytes after giving %d quota", len(df.Data()), quota) - } - } - }) -} - -// Test that the handler blocked in a Write is unblocked if the server sends a RST_STREAM. -func TestServer_Response_RST_Unblocks_LargeWrite(t *testing.T) { - const size = 1 << 20 - const maxFrameSize = 16 << 10 - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.(http.Flusher).Flush() - errc := make(chan error, 1) - go func() { - _, err := w.Write(bytes.Repeat([]byte("a"), size)) - errc <- err - }() - select { - case err := <-errc: - if err == nil { - return errors.New("unexpected nil error from Write in handler") - } - return nil - case <-time.After(2 * time.Second): - return errors.New("timeout waiting for Write in handler") - } - }, func(st *serverTester) { - if err := st.fr.WriteSettings( - Setting{SettingInitialWindowSize, 0}, - Setting{SettingMaxFrameSize, maxFrameSize}, - ); err != nil { - t.Fatal(err) - } - st.wantSettingsAck() - - getSlash(st) // make the single request - - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - - if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { - t.Fatal(err) - } - }) -} - -func TestServer_Response_Empty_Data_Not_FlowControlled(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.(http.Flusher).Flush() - // Nothing; send empty DATA - return nil - }, func(st *serverTester) { - // Handler gets no data quota: - if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, 0}); err != nil { - t.Fatal(err) - } - st.wantSettingsAck() - - getSlash(st) // make the single request - - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - - df := st.wantData() - if got := len(df.Data()); got != 0 { - t.Fatalf("unexpected %d DATA bytes; want 0", got) - } - if !df.StreamEnded() { - t.Fatal("DATA didn't have END_STREAM") - } - }) -} - -func TestServer_Response_Automatic100Continue(t *testing.T) { - const msg = "foo" - const reply = "bar" - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - if v := r.Header.Get("Expect"); v != "" { - t.Errorf("Expect header = %q; want empty", v) - } - buf := make([]byte, len(msg)) - // This read should trigger the 100-continue being sent. - if n, err := io.ReadFull(r.Body, buf); err != nil || n != len(msg) || string(buf) != msg { - return fmt.Errorf("ReadFull = %q, %v; want %q, nil", buf[:n], err, msg) - } - _, err := io.WriteString(w, reply) - return err - }, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "POST", "expect", "100-continue"), - EndStream: false, - EndHeaders: true, - }) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "100"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Fatalf("Got headers %v; want %v", goth, wanth) - } - - // Okay, they sent status 100, so we can send our - // gigantic and/or sensitive "foo" payload now. - st.writeData(1, true, []byte(msg)) - - st.wantWindowUpdate(0, uint32(len(msg))) - - hf = st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("expected data to follow") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - goth = st.decodeHeader(hf.HeaderBlockFragment()) - wanth = [][2]string{ - {":status", "200"}, - {"content-type", "text/plain; charset=utf-8"}, - {"content-length", strconv.Itoa(len(reply))}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } - - df := st.wantData() - if string(df.Data()) != reply { - t.Errorf("Client read %q; want %q", df.Data(), reply) - } - if !df.StreamEnded() { - t.Errorf("expect data stream end") - } - }) -} - -func TestServer_HandlerWriteErrorOnDisconnect(t *testing.T) { - errc := make(chan error, 1) - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - p := []byte("some data.\n") - for { - _, err := w.Write(p) - if err != nil { - errc <- err - return nil - } - } - }, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: false, - EndHeaders: true, - }) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("unexpected END_STREAM flag") - } - if !hf.HeadersEnded() { - t.Fatal("want END_HEADERS flag") - } - // Close the connection and wait for the handler to (hopefully) notice. - st.cc.Close() - select { - case <-errc: - case <-time.After(5 * time.Second): - t.Error("timeout") - } - }) -} - -func TestServer_Rejects_Too_Many_Streams(t *testing.T) { - const testPath = "/some/path" - - inHandler := make(chan uint32) - leaveHandler := make(chan bool) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - id := w.(*responseWriter).rws.stream.id - inHandler <- id - if id == 1+(defaultMaxStreams+1)*2 && r.URL.Path != testPath { - t.Errorf("decoded final path as %q; want %q", r.URL.Path, testPath) - } - <-leaveHandler - }) - defer st.Close() - st.greet() - nextStreamID := uint32(1) - streamID := func() uint32 { - defer func() { nextStreamID += 2 }() - return nextStreamID - } - sendReq := func(id uint32, headers ...string) { - st.writeHeaders(HeadersFrameParam{ - StreamID: id, - BlockFragment: st.encodeHeader(headers...), - EndStream: true, - EndHeaders: true, - }) - } - for i := 0; i < defaultMaxStreams; i++ { - sendReq(streamID()) - <-inHandler - } - defer func() { - for i := 0; i < defaultMaxStreams; i++ { - leaveHandler <- true - } - }() - - // And this one should cross the limit: - // (It's also sent as a CONTINUATION, to verify we still track the decoder context, - // even if we're rejecting it) - rejectID := streamID() - headerBlock := st.encodeHeader(":path", testPath) - frag1, frag2 := headerBlock[:3], headerBlock[3:] - st.writeHeaders(HeadersFrameParam{ - StreamID: rejectID, - BlockFragment: frag1, - EndStream: true, - EndHeaders: false, // CONTINUATION coming - }) - if err := st.fr.WriteContinuation(rejectID, true, frag2); err != nil { - t.Fatal(err) - } - st.wantRSTStream(rejectID, ErrCodeProtocol) - - // But let a handler finish: - leaveHandler <- true - st.wantHeaders() - - // And now another stream should be able to start: - goodID := streamID() - sendReq(goodID, ":path", testPath) - select { - case got := <-inHandler: - if got != goodID { - t.Errorf("Got stream %d; want %d", got, goodID) - } - case <-time.After(3 * time.Second): - t.Error("timeout waiting for handler") - } -} - -// So many response headers that the server needs to use CONTINUATION frames: -func TestServer_Response_ManyHeaders_With_Continuation(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - h := w.Header() - for i := 0; i < 5000; i++ { - h.Set(fmt.Sprintf("x-header-%d", i), fmt.Sprintf("x-value-%d", i)) - } - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.HeadersEnded() { - t.Fatal("got unwanted END_HEADERS flag") - } - n := 0 - for { - n++ - cf := st.wantContinuation() - if cf.HeadersEnded() { - break - } - } - if n < 5 { - t.Errorf("Only got %d CONTINUATION frames; expected 5+ (currently 6)", n) - } - }) -} - -// This previously crashed (reported by Mathieu Lonjaret as observed -// while using Camlistore) because we got a DATA frame from the client -// after the handler exited and our logic at the time was wrong, -// keeping a stream in the map in stateClosed, which tickled an -// invariant check later when we tried to remove that stream (via -// defer sc.closeAllStreamsOnConnClose) when the serverConn serve loop -// ended. -func TestServer_NoCrash_HandlerClose_Then_ClientClose(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - // nothing - return nil - }, func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: false, // DATA is coming - EndHeaders: true, - }) - hf := st.wantHeaders() - if !hf.HeadersEnded() || !hf.StreamEnded() { - t.Fatalf("want END_HEADERS+END_STREAM, got %v", hf) - } - - // Sent when the a Handler closes while a client has - // indicated it's still sending DATA: - st.wantRSTStream(1, ErrCodeNo) - - // Now the handler has ended, so it's ended its - // stream, but the client hasn't closed its side - // (stateClosedLocal). So send more data and verify - // it doesn't crash with an internal invariant panic, like - // it did before. - st.writeData(1, true, []byte("foo")) - - // Get our flow control bytes back, since the handler didn't get them. - st.wantWindowUpdate(0, uint32(len("foo"))) - - // Sent after a peer sends data anyway (admittedly the - // previous RST_STREAM might've still been in-flight), - // but they'll get the more friendly 'cancel' code - // first. - st.wantRSTStream(1, ErrCodeStreamClosed) - - // Set up a bunch of machinery to record the panic we saw - // previously. - var ( - panMu sync.Mutex - panicVal interface{} - ) - - testHookOnPanicMu.Lock() - testHookOnPanic = func(sc *serverConn, pv interface{}) bool { - panMu.Lock() - panicVal = pv - panMu.Unlock() - return true - } - testHookOnPanicMu.Unlock() - - // Now force the serve loop to end, via closing the connection. - st.cc.Close() - select { - case <-st.sc.doneServing: - // Loop has exited. - panMu.Lock() - got := panicVal - panMu.Unlock() - if got != nil { - t.Errorf("Got panic: %v", got) - } - case <-time.After(5 * time.Second): - t.Error("timeout") - } - }) -} - -func TestServer_Rejects_TLS10(t *testing.T) { testRejectTLS(t, tls.VersionTLS10) } -func TestServer_Rejects_TLS11(t *testing.T) { testRejectTLS(t, tls.VersionTLS11) } - -func testRejectTLS(t *testing.T, max uint16) { - st := newServerTester(t, nil, func(c *tls.Config) { - c.MaxVersion = max - }) - defer st.Close() - gf := st.wantGoAway() - if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want { - t.Errorf("Got error code %v; want %v", got, want) - } -} - -func TestServer_Rejects_TLSBadCipher(t *testing.T) { - st := newServerTester(t, nil, func(c *tls.Config) { - // Only list bad ones: - c.CipherSuites = []uint16{ - tls.TLS_RSA_WITH_RC4_128_SHA, - tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, - tls.TLS_RSA_WITH_AES_128_CBC_SHA, - tls.TLS_RSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, - tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - cipher_TLS_RSA_WITH_AES_128_CBC_SHA256, - } - }) - defer st.Close() - gf := st.wantGoAway() - if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want { - t.Errorf("Got error code %v; want %v", got, want) - } -} - -func TestServer_Advertises_Common_Cipher(t *testing.T) { - const requiredSuite = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 - st := newServerTester(t, nil, func(c *tls.Config) { - // Have the client only support the one required by the spec. - c.CipherSuites = []uint16{requiredSuite} - }, func(ts *httptest.Server) { - var srv *http.Server = ts.Config - // Have the server configured with no specific cipher suites. - // This tests that Go's defaults include the required one. - srv.TLSConfig = nil - }) - defer st.Close() - st.greet() -} - -func (st *serverTester) onHeaderField(f hpack.HeaderField) { - if f.Name == "date" { - return - } - st.decodedHeaders = append(st.decodedHeaders, [2]string{f.Name, f.Value}) -} - -func (st *serverTester) decodeHeader(headerBlock []byte) (pairs [][2]string) { - st.decodedHeaders = nil - if _, err := st.hpackDec.Write(headerBlock); err != nil { - st.t.Fatalf("hpack decoding error: %v", err) - } - if err := st.hpackDec.Close(); err != nil { - st.t.Fatalf("hpack decoding error: %v", err) - } - return st.decodedHeaders -} - -// testServerResponse sets up an idle HTTP/2 connection. The client function should -// write a single request that must be handled by the handler. This waits up to 5s -// for client to return, then up to an additional 2s for the handler to return. -func testServerResponse(t testing.TB, - handler func(http.ResponseWriter, *http.Request) error, - client func(*serverTester), -) { - errc := make(chan error, 1) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - if r.Body == nil { - t.Fatal("nil Body") - } - errc <- handler(w, r) - }) - defer st.Close() - - donec := make(chan bool) - go func() { - defer close(donec) - st.greet() - client(st) - }() - - select { - case <-donec: - case <-time.After(5 * time.Second): - t.Fatal("timeout in client") - } - - select { - case err := <-errc: - if err != nil { - t.Fatalf("Error in handler: %v", err) - } - case <-time.After(2 * time.Second): - t.Fatal("timeout in handler") - } -} - -// readBodyHandler returns an http Handler func that reads len(want) -// bytes from r.Body and fails t if the contents read were not -// the value of want. -func readBodyHandler(t *testing.T, want string) func(w http.ResponseWriter, r *http.Request) { - return func(w http.ResponseWriter, r *http.Request) { - buf := make([]byte, len(want)) - _, err := io.ReadFull(r.Body, buf) - if err != nil { - t.Error(err) - return - } - if string(buf) != want { - t.Errorf("read %q; want %q", buf, want) - } - } -} - -// TestServerWithCurl currently fails, hence the LenientCipherSuites test. See: -// https://github.com/tatsuhiro-t/nghttp2/issues/140 & -// http://sourceforge.net/p/curl/bugs/1472/ -func TestServerWithCurl(t *testing.T) { testServerWithCurl(t, false) } -func TestServerWithCurl_LenientCipherSuites(t *testing.T) { testServerWithCurl(t, true) } - -func testServerWithCurl(t *testing.T, permitProhibitedCipherSuites bool) { - if runtime.GOOS != "linux" { - t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway") - } - if testing.Short() { - t.Skip("skipping curl test in short mode") - } - requireCurl(t) - var gotConn int32 - testHookOnConn = func() { atomic.StoreInt32(&gotConn, 1) } - - const msg = "Hello from curl!\n" - ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Foo", "Bar") - w.Header().Set("Client-Proto", r.Proto) - io.WriteString(w, msg) - })) - ConfigureServer(ts.Config, &Server{ - PermitProhibitedCipherSuites: permitProhibitedCipherSuites, - }) - ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config - ts.StartTLS() - defer ts.Close() - - t.Logf("Running test server for curl to hit at: %s", ts.URL) - container := curl(t, "--silent", "--http2", "--insecure", "-v", ts.URL) - defer kill(container) - resc := make(chan interface{}, 1) - go func() { - res, err := dockerLogs(container) - if err != nil { - resc <- err - } else { - resc <- res - } - }() - select { - case res := <-resc: - if err, ok := res.(error); ok { - t.Fatal(err) - } - body := string(res.([]byte)) - // Search for both "key: value" and "key:value", since curl changed their format - // Our Dockerfile contains the latest version (no space), but just in case people - // didn't rebuild, check both. - if !strings.Contains(body, "foo: Bar") && !strings.Contains(body, "foo:Bar") { - t.Errorf("didn't see foo: Bar header") - t.Logf("Got: %s", body) - } - if !strings.Contains(body, "client-proto: HTTP/2") && !strings.Contains(body, "client-proto:HTTP/2") { - t.Errorf("didn't see client-proto: HTTP/2 header") - t.Logf("Got: %s", res) - } - if !strings.Contains(string(res.([]byte)), msg) { - t.Errorf("didn't see %q content", msg) - t.Logf("Got: %s", res) - } - case <-time.After(3 * time.Second): - t.Errorf("timeout waiting for curl") - } - - if atomic.LoadInt32(&gotConn) == 0 { - t.Error("never saw an http2 connection") - } -} - -var doh2load = flag.Bool("h2load", false, "Run h2load test") - -func TestServerWithH2Load(t *testing.T) { - if !*doh2load { - t.Skip("Skipping without --h2load flag.") - } - if runtime.GOOS != "linux" { - t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway") - } - requireH2load(t) - - msg := strings.Repeat("Hello, h2load!\n", 5000) - ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, msg) - w.(http.Flusher).Flush() - io.WriteString(w, msg) - })) - ts.StartTLS() - defer ts.Close() - - cmd := exec.Command("docker", "run", "--net=host", "--entrypoint=/usr/local/bin/h2load", "gohttp2/curl", - "-n100000", "-c100", "-m100", ts.URL) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - t.Fatal(err) - } -} - -// Issue 12843 -func TestServerDoS_MaxHeaderListSize(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}) - defer st.Close() - - // shake hands - frameSize := defaultMaxReadFrameSize - var advHeaderListSize *uint32 - st.greetAndCheckSettings(func(s Setting) error { - switch s.ID { - case SettingMaxFrameSize: - if s.Val < minMaxFrameSize { - frameSize = minMaxFrameSize - } else if s.Val > maxFrameSize { - frameSize = maxFrameSize - } else { - frameSize = int(s.Val) - } - case SettingMaxHeaderListSize: - advHeaderListSize = &s.Val - } - return nil - }) - - if advHeaderListSize == nil { - t.Errorf("server didn't advertise a max header list size") - } else if *advHeaderListSize == 0 { - t.Errorf("server advertised a max header list size of 0") - } - - st.encodeHeaderField(":method", "GET") - st.encodeHeaderField(":path", "/") - st.encodeHeaderField(":scheme", "https") - cookie := strings.Repeat("*", 4058) - st.encodeHeaderField("cookie", cookie) - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.headerBuf.Bytes(), - EndStream: true, - EndHeaders: false, - }) - - // Capture the short encoding of a duplicate ~4K cookie, now - // that we've already sent it once. - st.headerBuf.Reset() - st.encodeHeaderField("cookie", cookie) - - // Now send 1MB of it. - const size = 1 << 20 - b := bytes.Repeat(st.headerBuf.Bytes(), size/st.headerBuf.Len()) - for len(b) > 0 { - chunk := b - if len(chunk) > frameSize { - chunk = chunk[:frameSize] - } - b = b[len(chunk):] - st.fr.WriteContinuation(1, len(b) == 0, chunk) - } - - h := st.wantHeaders() - if !h.HeadersEnded() { - t.Fatalf("Got HEADERS without END_HEADERS set: %v", h) - } - headers := st.decodeHeader(h.HeaderBlockFragment()) - want := [][2]string{ - {":status", "431"}, - {"content-type", "text/html; charset=utf-8"}, - {"content-length", "63"}, - } - if !reflect.DeepEqual(headers, want) { - t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) - } -} - -func TestCompressionErrorOnWrite(t *testing.T) { - const maxStrLen = 8 << 10 - var serverConfig *http.Server - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // No response body. - }, func(ts *httptest.Server) { - serverConfig = ts.Config - serverConfig.MaxHeaderBytes = maxStrLen - }) - st.addLogFilter("connection error: COMPRESSION_ERROR") - defer st.Close() - st.greet() - - maxAllowed := st.sc.framer.maxHeaderStringLen() - - // Crank this up, now that we have a conn connected with the - // hpack.Decoder's max string length set has been initialized - // from the earlier low ~8K value. We want this higher so don't - // hit the max header list size. We only want to test hitting - // the max string size. - serverConfig.MaxHeaderBytes = 1 << 20 - - // First a request with a header that's exactly the max allowed size - // for the hpack compression. It's still too long for the header list - // size, so we'll get the 431 error, but that keeps the compression - // context still valid. - hbf := st.encodeHeader("foo", strings.Repeat("a", maxAllowed)) - - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: hbf, - EndStream: true, - EndHeaders: true, - }) - h := st.wantHeaders() - if !h.HeadersEnded() { - t.Fatalf("Got HEADERS without END_HEADERS set: %v", h) - } - headers := st.decodeHeader(h.HeaderBlockFragment()) - want := [][2]string{ - {":status", "431"}, - {"content-type", "text/html; charset=utf-8"}, - {"content-length", "63"}, - } - if !reflect.DeepEqual(headers, want) { - t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) - } - df := st.wantData() - if !strings.Contains(string(df.Data()), "HTTP Error 431") { - t.Errorf("Unexpected data body: %q", df.Data()) - } - if !df.StreamEnded() { - t.Fatalf("expect data stream end") - } - - // And now send one that's just one byte too big. - hbf = st.encodeHeader("bar", strings.Repeat("b", maxAllowed+1)) - st.writeHeaders(HeadersFrameParam{ - StreamID: 3, - BlockFragment: hbf, - EndStream: true, - EndHeaders: true, - }) - ga := st.wantGoAway() - if ga.ErrCode != ErrCodeCompression { - t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode) - } -} - -func TestCompressionErrorOnClose(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // No response body. - }) - st.addLogFilter("connection error: COMPRESSION_ERROR") - defer st.Close() - st.greet() - - hbf := st.encodeHeader("foo", "bar") - hbf = hbf[:len(hbf)-1] // truncate one byte from the end, so hpack.Decoder.Close fails. - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: hbf, - EndStream: true, - EndHeaders: true, - }) - ga := st.wantGoAway() - if ga.ErrCode != ErrCodeCompression { - t.Errorf("GOAWAY err = %v; want ErrCodeCompression", ga.ErrCode) - } -} - -// test that a server handler can read trailers from a client -func TestServerReadsTrailers(t *testing.T) { - const testBody = "some test body" - writeReq := func(st *serverTester) { - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader("trailer", "Foo, Bar", "trailer", "Baz"), - EndStream: false, - EndHeaders: true, - }) - st.writeData(1, false, []byte(testBody)) - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeaderRaw( - "foo", "foov", - "bar", "barv", - "baz", "bazv", - "surprise", "wasn't declared; shouldn't show up", - ), - EndStream: true, - EndHeaders: true, - }) - } - checkReq := func(r *http.Request) { - wantTrailer := http.Header{ - "Foo": nil, - "Bar": nil, - "Baz": nil, - } - if !reflect.DeepEqual(r.Trailer, wantTrailer) { - t.Errorf("initial Trailer = %v; want %v", r.Trailer, wantTrailer) - } - slurp, err := ioutil.ReadAll(r.Body) - if string(slurp) != testBody { - t.Errorf("read body %q; want %q", slurp, testBody) - } - if err != nil { - t.Fatalf("Body slurp: %v", err) - } - wantTrailerAfter := http.Header{ - "Foo": {"foov"}, - "Bar": {"barv"}, - "Baz": {"bazv"}, - } - if !reflect.DeepEqual(r.Trailer, wantTrailerAfter) { - t.Errorf("final Trailer = %v; want %v", r.Trailer, wantTrailerAfter) - } - } - testServerRequest(t, writeReq, checkReq) -} - -// test that a server handler can send trailers -func TestServerWritesTrailers_WithFlush(t *testing.T) { testServerWritesTrailers(t, true) } -func TestServerWritesTrailers_WithoutFlush(t *testing.T) { testServerWritesTrailers(t, false) } - -func testServerWritesTrailers(t *testing.T, withFlush bool) { - // See https://httpwg.github.io/specs/rfc7540.html#rfc.section.8.1.3 - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Set("Trailer", "Server-Trailer-A, Server-Trailer-B") - w.Header().Add("Trailer", "Server-Trailer-C") - w.Header().Add("Trailer", "Transfer-Encoding, Content-Length, Trailer") // filtered - - // Regular headers: - w.Header().Set("Foo", "Bar") - w.Header().Set("Content-Length", "5") // len("Hello") - - io.WriteString(w, "Hello") - if withFlush { - w.(http.Flusher).Flush() - } - w.Header().Set("Server-Trailer-A", "valuea") - w.Header().Set("Server-Trailer-C", "valuec") // skipping B - // After a flush, random keys like Server-Surprise shouldn't show up: - w.Header().Set("Server-Surpise", "surprise! this isn't predeclared!") - // But we do permit promoting keys to trailers after a - // flush if they start with the magic - // otherwise-invalid "Trailer:" prefix: - w.Header().Set("Trailer:Post-Header-Trailer", "hi1") - w.Header().Set("Trailer:post-header-trailer2", "hi2") - w.Header().Set("Trailer:Range", "invalid") - w.Header().Set("Trailer:Foo\x01Bogus", "invalid") - w.Header().Set("Transfer-Encoding", "should not be included; Forbidden by RFC 2616 14.40") - w.Header().Set("Content-Length", "should not be included; Forbidden by RFC 2616 14.40") - w.Header().Set("Trailer", "should not be included; Forbidden by RFC 2616 14.40") - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if hf.StreamEnded() { - t.Fatal("response HEADERS had END_STREAM") - } - if !hf.HeadersEnded() { - t.Fatal("response HEADERS didn't have END_HEADERS") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"foo", "Bar"}, - {"trailer", "Server-Trailer-A, Server-Trailer-B"}, - {"trailer", "Server-Trailer-C"}, - {"trailer", "Transfer-Encoding, Content-Length, Trailer"}, - {"content-type", "text/plain; charset=utf-8"}, - {"content-length", "5"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth) - } - df := st.wantData() - if string(df.Data()) != "Hello" { - t.Fatalf("Client read %q; want Hello", df.Data()) - } - if df.StreamEnded() { - t.Fatalf("data frame had STREAM_ENDED") - } - tf := st.wantHeaders() // for the trailers - if !tf.StreamEnded() { - t.Fatalf("trailers HEADERS lacked END_STREAM") - } - if !tf.HeadersEnded() { - t.Fatalf("trailers HEADERS lacked END_HEADERS") - } - wanth = [][2]string{ - {"post-header-trailer", "hi1"}, - {"post-header-trailer2", "hi2"}, - {"server-trailer-a", "valuea"}, - {"server-trailer-c", "valuec"}, - } - goth = st.decodeHeader(tf.HeaderBlockFragment()) - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth) - } - }) -} - -// validate transmitted header field names & values -// golang.org/issue/14048 -func TestServerDoesntWriteInvalidHeaders(t *testing.T) { - testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { - w.Header().Add("OK1", "x") - w.Header().Add("Bad:Colon", "x") // colon (non-token byte) in key - w.Header().Add("Bad1\x00", "x") // null in key - w.Header().Add("Bad2", "x\x00y") // null in value - return nil - }, func(st *serverTester) { - getSlash(st) - hf := st.wantHeaders() - if !hf.StreamEnded() { - t.Error("response HEADERS lacked END_STREAM") - } - if !hf.HeadersEnded() { - t.Fatal("response HEADERS didn't have END_HEADERS") - } - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "200"}, - {"ok1", "x"}, - {"content-type", "text/plain; charset=utf-8"}, - {"content-length", "0"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Header mismatch.\n got: %v\nwant: %v", goth, wanth) - } - }) -} - -func BenchmarkServerGets(b *testing.B) { - defer disableGoroutineTracking()() - b.ReportAllocs() - - const msg = "Hello, world" - st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, msg) - }) - defer st.Close() - st.greet() - - // Give the server quota to reply. (plus it has the the 64KB) - if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { - b.Fatal(err) - } - - for i := 0; i < b.N; i++ { - id := 1 + uint32(i)*2 - st.writeHeaders(HeadersFrameParam{ - StreamID: id, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - st.wantHeaders() - df := st.wantData() - if !df.StreamEnded() { - b.Fatalf("DATA didn't have END_STREAM; got %v", df) - } - } -} - -func BenchmarkServerPosts(b *testing.B) { - defer disableGoroutineTracking()() - b.ReportAllocs() - - const msg = "Hello, world" - st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { - // Consume the (empty) body from th peer before replying, otherwise - // the server will sometimes (depending on scheduling) send the peer a - // a RST_STREAM with the CANCEL error code. - if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil { - b.Errorf("Copy error; got %v, %v; want 0, nil", n, err) - } - io.WriteString(w, msg) - }) - defer st.Close() - st.greet() - - // Give the server quota to reply. (plus it has the the 64KB) - if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { - b.Fatal(err) - } - - for i := 0; i < b.N; i++ { - id := 1 + uint32(i)*2 - st.writeHeaders(HeadersFrameParam{ - StreamID: id, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, - EndHeaders: true, - }) - st.writeData(id, true, nil) - st.wantHeaders() - df := st.wantData() - if !df.StreamEnded() { - b.Fatalf("DATA didn't have END_STREAM; got %v", df) - } - } -} - -// Send a stream of messages from server to client in separate data frames. -// Brings up performance issues seen in long streams. -// Created to show problem in go issue #18502 -func BenchmarkServerToClientStreamDefaultOptions(b *testing.B) { - benchmarkServerToClientStream(b) -} - -// Justification for Change-Id: Iad93420ef6c3918f54249d867098f1dadfa324d8 -// Expect to see memory/alloc reduction by opting in to Frame reuse with the Framer. -func BenchmarkServerToClientStreamReuseFrames(b *testing.B) { - benchmarkServerToClientStream(b, optFramerReuseFrames) -} - -func benchmarkServerToClientStream(b *testing.B, newServerOpts ...interface{}) { - defer disableGoroutineTracking()() - b.ReportAllocs() - const msgLen = 1 - // default window size - const windowSize = 1<<16 - 1 - - // next message to send from the server and for the client to expect - nextMsg := func(i int) []byte { - msg := make([]byte, msgLen) - msg[0] = byte(i) - if len(msg) != msgLen { - panic("invalid test setup msg length") - } - return msg - } - - st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { - // Consume the (empty) body from th peer before replying, otherwise - // the server will sometimes (depending on scheduling) send the peer a - // a RST_STREAM with the CANCEL error code. - if n, err := io.Copy(ioutil.Discard, r.Body); n != 0 || err != nil { - b.Errorf("Copy error; got %v, %v; want 0, nil", n, err) - } - for i := 0; i < b.N; i += 1 { - w.Write(nextMsg(i)) - w.(http.Flusher).Flush() - } - }, newServerOpts...) - defer st.Close() - st.greet() - - const id = uint32(1) - - st.writeHeaders(HeadersFrameParam{ - StreamID: id, - BlockFragment: st.encodeHeader(":method", "POST"), - EndStream: false, - EndHeaders: true, - }) - - st.writeData(id, true, nil) - st.wantHeaders() - - var pendingWindowUpdate = uint32(0) - - for i := 0; i < b.N; i += 1 { - expected := nextMsg(i) - df := st.wantData() - if bytes.Compare(expected, df.data) != 0 { - b.Fatalf("Bad message received; want %v; got %v", expected, df.data) - } - // try to send infrequent but large window updates so they don't overwhelm the test - pendingWindowUpdate += uint32(len(df.data)) - if pendingWindowUpdate >= windowSize/2 { - if err := st.fr.WriteWindowUpdate(0, pendingWindowUpdate); err != nil { - b.Fatal(err) - } - if err := st.fr.WriteWindowUpdate(id, pendingWindowUpdate); err != nil { - b.Fatal(err) - } - pendingWindowUpdate = 0 - } - } - df := st.wantData() - if !df.StreamEnded() { - b.Fatalf("DATA didn't have END_STREAM; got %v", df) - } -} - -// go-fuzz bug, originally reported at https://github.com/bradfitz/http2/issues/53 -// Verify we don't hang. -func TestIssue53(t *testing.T) { - const data = "PRI * HTTP/2.0\r\n\r\nSM" + - "\r\n\r\n\x00\x00\x00\x01\ainfinfin\ad" - s := &http.Server{ - ErrorLog: log.New(io.MultiWriter(stderrv(), twriter{t: t}), "", log.LstdFlags), - Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - w.Write([]byte("hello")) - }), - } - s2 := &Server{ - MaxReadFrameSize: 1 << 16, - PermitProhibitedCipherSuites: true, - } - c := &issue53Conn{[]byte(data), false, false} - s2.ServeConn(c, &ServeConnOpts{BaseConfig: s}) - if !c.closed { - t.Fatal("connection is not closed") - } -} - -type issue53Conn struct { - data []byte - closed bool - written bool -} - -func (c *issue53Conn) Read(b []byte) (n int, err error) { - if len(c.data) == 0 { - return 0, io.EOF - } - n = copy(b, c.data) - c.data = c.data[n:] - return -} - -func (c *issue53Conn) Write(b []byte) (n int, err error) { - c.written = true - return len(b), nil -} - -func (c *issue53Conn) Close() error { - c.closed = true - return nil -} - -func (c *issue53Conn) LocalAddr() net.Addr { - return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706} -} -func (c *issue53Conn) RemoteAddr() net.Addr { - return &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 49706} -} -func (c *issue53Conn) SetDeadline(t time.Time) error { return nil } -func (c *issue53Conn) SetReadDeadline(t time.Time) error { return nil } -func (c *issue53Conn) SetWriteDeadline(t time.Time) error { return nil } - -// golang.org/issue/12895 -func TestConfigureServer(t *testing.T) { - tests := []struct { - name string - tlsConfig *tls.Config - wantErr string - }{ - { - name: "empty server", - }, - { - name: "just the required cipher suite", - tlsConfig: &tls.Config{ - CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, - }, - }, - { - name: "just the alternative required cipher suite", - tlsConfig: &tls.Config{ - CipherSuites: []uint16{tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256}, - }, - }, - { - name: "missing required cipher suite", - tlsConfig: &tls.Config{ - CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384}, - }, - wantErr: "is missing an HTTP/2-required AES_128_GCM_SHA256 cipher.", - }, - { - name: "required after bad", - tlsConfig: &tls.Config{ - CipherSuites: []uint16{tls.TLS_RSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256}, - }, - wantErr: "contains an HTTP/2-approved cipher suite (0xc02f), but it comes after", - }, - { - name: "bad after required", - tlsConfig: &tls.Config{ - CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_RSA_WITH_RC4_128_SHA}, - }, - }, - } - for _, tt := range tests { - srv := &http.Server{TLSConfig: tt.tlsConfig} - err := ConfigureServer(srv, nil) - if (err != nil) != (tt.wantErr != "") { - if tt.wantErr != "" { - t.Errorf("%s: success, but want error", tt.name) - } else { - t.Errorf("%s: unexpected error: %v", tt.name, err) - } - } - if err != nil && tt.wantErr != "" && !strings.Contains(err.Error(), tt.wantErr) { - t.Errorf("%s: err = %v; want substring %q", tt.name, err, tt.wantErr) - } - if err == nil && !srv.TLSConfig.PreferServerCipherSuites { - t.Errorf("%s: PreferServerCipherSuite is false; want true", tt.name) - } - } -} - -func TestServerRejectHeadWithBody(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // No response body. - }) - defer st.Close() - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "HEAD"), - EndStream: false, // what we're testing, a bogus HEAD request with body - EndHeaders: true, - }) - st.wantRSTStream(1, ErrCodeProtocol) -} - -func TestServerNoAutoContentLengthOnHead(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // No response body. (or smaller than one frame) - }) - defer st.Close() - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, // clients send odd numbers - BlockFragment: st.encodeHeader(":method", "HEAD"), - EndStream: true, - EndHeaders: true, - }) - h := st.wantHeaders() - headers := st.decodeHeader(h.HeaderBlockFragment()) - want := [][2]string{ - {":status", "200"}, - {"content-type", "text/plain; charset=utf-8"}, - } - if !reflect.DeepEqual(headers, want) { - t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) - } -} - -// golang.org/issue/13495 -func TestServerNoDuplicateContentType(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.Header()["Content-Type"] = []string{""} - fmt.Fprintf(w, "<html><head></head><body>hi</body></html>") - }) - defer st.Close() - st.greet() - st.writeHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: st.encodeHeader(), - EndStream: true, - EndHeaders: true, - }) - h := st.wantHeaders() - headers := st.decodeHeader(h.HeaderBlockFragment()) - want := [][2]string{ - {":status", "200"}, - {"content-type", ""}, - {"content-length", "41"}, - } - if !reflect.DeepEqual(headers, want) { - t.Errorf("Headers mismatch.\n got: %q\nwant: %q\n", headers, want) - } -} - -func disableGoroutineTracking() (restore func()) { - old := DebugGoroutines - DebugGoroutines = false - return func() { DebugGoroutines = old } -} - -func BenchmarkServer_GetRequest(b *testing.B) { - defer disableGoroutineTracking()() - b.ReportAllocs() - const msg = "Hello, world." - st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { - n, err := io.Copy(ioutil.Discard, r.Body) - if err != nil || n > 0 { - b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err) - } - io.WriteString(w, msg) - }) - defer st.Close() - - st.greet() - // Give the server quota to reply. (plus it has the the 64KB) - if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { - b.Fatal(err) - } - hbf := st.encodeHeader(":method", "GET") - for i := 0; i < b.N; i++ { - streamID := uint32(1 + 2*i) - st.writeHeaders(HeadersFrameParam{ - StreamID: streamID, - BlockFragment: hbf, - EndStream: true, - EndHeaders: true, - }) - st.wantHeaders() - st.wantData() - } -} - -func BenchmarkServer_PostRequest(b *testing.B) { - defer disableGoroutineTracking()() - b.ReportAllocs() - const msg = "Hello, world." - st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { - n, err := io.Copy(ioutil.Discard, r.Body) - if err != nil || n > 0 { - b.Errorf("Read %d bytes, error %v; want 0 bytes.", n, err) - } - io.WriteString(w, msg) - }) - defer st.Close() - st.greet() - // Give the server quota to reply. (plus it has the the 64KB) - if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { - b.Fatal(err) - } - hbf := st.encodeHeader(":method", "POST") - for i := 0; i < b.N; i++ { - streamID := uint32(1 + 2*i) - st.writeHeaders(HeadersFrameParam{ - StreamID: streamID, - BlockFragment: hbf, - EndStream: false, - EndHeaders: true, - }) - st.writeData(streamID, true, nil) - st.wantHeaders() - st.wantData() - } -} - -type connStateConn struct { - net.Conn - cs tls.ConnectionState -} - -func (c connStateConn) ConnectionState() tls.ConnectionState { return c.cs } - -// golang.org/issue/12737 -- handle any net.Conn, not just -// *tls.Conn. -func TestServerHandleCustomConn(t *testing.T) { - var s Server - c1, c2 := net.Pipe() - clientDone := make(chan struct{}) - handlerDone := make(chan struct{}) - var req *http.Request - go func() { - defer close(clientDone) - defer c2.Close() - fr := NewFramer(c2, c2) - io.WriteString(c2, ClientPreface) - fr.WriteSettings() - fr.WriteSettingsAck() - f, err := fr.ReadFrame() - if err != nil { - t.Error(err) - return - } - if sf, ok := f.(*SettingsFrame); !ok || sf.IsAck() { - t.Errorf("Got %v; want non-ACK SettingsFrame", summarizeFrame(f)) - return - } - f, err = fr.ReadFrame() - if err != nil { - t.Error(err) - return - } - if sf, ok := f.(*SettingsFrame); !ok || !sf.IsAck() { - t.Errorf("Got %v; want ACK SettingsFrame", summarizeFrame(f)) - return - } - var henc hpackEncoder - fr.WriteHeaders(HeadersFrameParam{ - StreamID: 1, - BlockFragment: henc.encodeHeaderRaw(t, ":method", "GET", ":path", "/", ":scheme", "https", ":authority", "foo.com"), - EndStream: true, - EndHeaders: true, - }) - go io.Copy(ioutil.Discard, c2) - <-handlerDone - }() - const testString = "my custom ConnectionState" - fakeConnState := tls.ConnectionState{ - ServerName: testString, - Version: tls.VersionTLS12, - CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - } - go s.ServeConn(connStateConn{c1, fakeConnState}, &ServeConnOpts{ - BaseConfig: &http.Server{ - Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer close(handlerDone) - req = r - }), - }}) - select { - case <-clientDone: - case <-time.After(5 * time.Second): - t.Fatal("timeout waiting for handler") - } - if req.TLS == nil { - t.Fatalf("Request.TLS is nil. Got: %#v", req) - } - if req.TLS.ServerName != testString { - t.Fatalf("Request.TLS = %+v; want ServerName of %q", req.TLS, testString) - } -} - -// golang.org/issue/14214 -func TestServer_Rejects_ConnHeaders(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - t.Error("should not get to Handler") - }) - defer st.Close() - st.greet() - st.bodylessReq1("connection", "foo") - hf := st.wantHeaders() - goth := st.decodeHeader(hf.HeaderBlockFragment()) - wanth := [][2]string{ - {":status", "400"}, - {"content-type", "text/plain; charset=utf-8"}, - {"x-content-type-options", "nosniff"}, - {"content-length", "51"}, - } - if !reflect.DeepEqual(goth, wanth) { - t.Errorf("Got headers %v; want %v", goth, wanth) - } -} - -type hpackEncoder struct { - enc *hpack.Encoder - buf bytes.Buffer -} - -func (he *hpackEncoder) encodeHeaderRaw(t *testing.T, headers ...string) []byte { - if len(headers)%2 == 1 { - panic("odd number of kv args") - } - he.buf.Reset() - if he.enc == nil { - he.enc = hpack.NewEncoder(&he.buf) - } - for len(headers) > 0 { - k, v := headers[0], headers[1] - err := he.enc.WriteField(hpack.HeaderField{Name: k, Value: v}) - if err != nil { - t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) - } - headers = headers[2:] - } - return he.buf.Bytes() -} - -func TestCheckValidHTTP2Request(t *testing.T) { - tests := []struct { - h http.Header - want error - }{ - { - h: http.Header{"Te": {"trailers"}}, - want: nil, - }, - { - h: http.Header{"Te": {"trailers", "bogus"}}, - want: errors.New(`request header "TE" may only be "trailers" in HTTP/2`), - }, - { - h: http.Header{"Foo": {""}}, - want: nil, - }, - { - h: http.Header{"Connection": {""}}, - want: errors.New(`request header "Connection" is not valid in HTTP/2`), - }, - { - h: http.Header{"Proxy-Connection": {""}}, - want: errors.New(`request header "Proxy-Connection" is not valid in HTTP/2`), - }, - { - h: http.Header{"Keep-Alive": {""}}, - want: errors.New(`request header "Keep-Alive" is not valid in HTTP/2`), - }, - { - h: http.Header{"Upgrade": {""}}, - want: errors.New(`request header "Upgrade" is not valid in HTTP/2`), - }, - } - for i, tt := range tests { - got := checkValidHTTP2RequestHeaders(tt.h) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("%d. checkValidHTTP2Request = %v; want %v", i, got, tt.want) - } - } -} - -// golang.org/issue/14030 -func TestExpect100ContinueAfterHandlerWrites(t *testing.T) { - const msg = "Hello" - const msg2 = "World" - - doRead := make(chan bool, 1) - defer close(doRead) // fallback cleanup - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, msg) - w.(http.Flusher).Flush() - - // Do a read, which might force a 100-continue status to be sent. - <-doRead - r.Body.Read(make([]byte, 10)) - - io.WriteString(w, msg2) - - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - req, _ := http.NewRequest("POST", st.ts.URL, io.LimitReader(neverEnding('A'), 2<<20)) - req.Header.Set("Expect", "100-continue") - - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - - buf := make([]byte, len(msg)) - if _, err := io.ReadFull(res.Body, buf); err != nil { - t.Fatal(err) - } - if string(buf) != msg { - t.Fatalf("msg = %q; want %q", buf, msg) - } - - doRead <- true - - if _, err := io.ReadFull(res.Body, buf); err != nil { - t.Fatal(err) - } - if string(buf) != msg2 { - t.Fatalf("second msg = %q; want %q", buf, msg2) - } -} - -type funcReader func([]byte) (n int, err error) - -func (f funcReader) Read(p []byte) (n int, err error) { return f(p) } - -// golang.org/issue/16481 -- return flow control when streams close with unread data. -// (The Server version of the bug. See also TestUnreadFlowControlReturned_Transport) -func TestUnreadFlowControlReturned_Server(t *testing.T) { - unblock := make(chan bool, 1) - defer close(unblock) - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // Don't read the 16KB request body. Wait until the client's - // done sending it and then return. This should cause the Server - // to then return those 16KB of flow control to the client. - <-unblock - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - // This previously hung on the 4th iteration. - for i := 0; i < 6; i++ { - body := io.MultiReader( - io.LimitReader(neverEnding('A'), 16<<10), - funcReader(func([]byte) (n int, err error) { - unblock <- true - return 0, io.EOF - }), - ) - req, _ := http.NewRequest("POST", st.ts.URL, body) - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - res.Body.Close() - } - -} - -func TestServerIdleTimeout(t *testing.T) { - if testing.Short() { - t.Skip("skipping in short mode") - } - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - }, func(h2s *Server) { - h2s.IdleTimeout = 500 * time.Millisecond - }) - defer st.Close() - - st.greet() - ga := st.wantGoAway() - if ga.ErrCode != ErrCodeNo { - t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode) - } -} - -func TestServerIdleTimeout_AfterRequest(t *testing.T) { - if testing.Short() { - t.Skip("skipping in short mode") - } - const timeout = 250 * time.Millisecond - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - time.Sleep(timeout * 2) - }, func(h2s *Server) { - h2s.IdleTimeout = timeout - }) - defer st.Close() - - st.greet() - - // Send a request which takes twice the timeout. Verifies the - // idle timeout doesn't fire while we're in a request: - st.bodylessReq1() - st.wantHeaders() - - // But the idle timeout should be rearmed after the request - // is done: - ga := st.wantGoAway() - if ga.ErrCode != ErrCodeNo { - t.Errorf("GOAWAY error = %v; want ErrCodeNo", ga.ErrCode) - } -} - -// grpc-go closes the Request.Body currently with a Read. -// Verify that it doesn't race. -// See https://github.com/grpc/grpc-go/pull/938 -func TestRequestBodyReadCloseRace(t *testing.T) { - for i := 0; i < 100; i++ { - body := &requestBody{ - pipe: &pipe{ - b: new(bytes.Buffer), - }, - } - body.pipe.CloseWithError(io.EOF) - - done := make(chan bool, 1) - buf := make([]byte, 10) - go func() { - time.Sleep(1 * time.Millisecond) - body.Close() - done <- true - }() - body.Read(buf) - <-done - } -} - -func TestIssue20704Race(t *testing.T) { - if testing.Short() && os.Getenv("GO_BUILDER_NAME") == "" { - t.Skip("skipping in short mode") - } - const ( - itemSize = 1 << 10 - itemCount = 100 - ) - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - for i := 0; i < itemCount; i++ { - _, err := w.Write(make([]byte, itemSize)) - if err != nil { - return - } - } - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - cl := &http.Client{Transport: tr} - - for i := 0; i < 1000; i++ { - resp, err := cl.Get(st.ts.URL) - if err != nil { - t.Fatal(err) - } - // Force a RST stream to the server by closing without - // reading the body: - resp.Body.Close() - } -} diff --git a/vendor/golang.org/x/net/http2/transport.go b/vendor/golang.org/x/net/http2/transport.go index 4392a09f83..d23a226251 100644 --- a/vendor/golang.org/x/net/http2/transport.go +++ b/vendor/golang.org/x/net/http2/transport.go @@ -27,9 +27,9 @@ import ( "sync" "time" + "golang.org/x/net/http/httpguts" "golang.org/x/net/http2/hpack" "golang.org/x/net/idna" - "golang.org/x/net/lex/httplex" ) const ( @@ -306,7 +306,26 @@ func (sew stickyErrWriter) Write(p []byte) (n int, err error) { return } -var ErrNoCachedConn = errors.New("http2: no cached connection was available") +// noCachedConnError is the concrete type of ErrNoCachedConn, which +// needs to be detected by net/http regardless of whether it's its +// bundled version (in h2_bundle.go with a rewritten type name) or +// from a user's x/net/http2. As such, as it has a unique method name +// (IsHTTP2NoCachedConnError) that net/http sniffs for via func +// isNoCachedConnError. +type noCachedConnError struct{} + +func (noCachedConnError) IsHTTP2NoCachedConnError() {} +func (noCachedConnError) Error() string { return "http2: no cached connection was available" } + +// isNoCachedConnError reports whether err is of type noCachedConnError +// or its equivalent renamed type in net/http2's h2_bundle.go. Both types +// may coexist in the same running program. +func isNoCachedConnError(err error) bool { + _, ok := err.(interface{ IsHTTP2NoCachedConnError() }) + return ok +} + +var ErrNoCachedConn error = noCachedConnError{} // RoundTripOpt are options for the Transport.RoundTripOpt method. type RoundTripOpt struct { @@ -548,6 +567,10 @@ func (t *Transport) newClientConn(c net.Conn, singleUse bool) (*ClientConn, erro // henc in response to SETTINGS frames? cc.henc = hpack.NewEncoder(&cc.hbuf) + if t.AllowHTTP { + cc.nextStreamID = 3 + } + if cs, ok := c.(connectionStater); ok { state := cs.ConnectionState() cc.tlsState = &state @@ -811,7 +834,7 @@ func (cc *ClientConn) roundTrip(req *http.Request) (res *http.Response, gotErrAf cc.wmu.Lock() endStream := !hasBody && !hasTrailers - werr := cc.writeHeaders(cs.ID, endStream, hdrs) + werr := cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs) cc.wmu.Unlock() traceWroteHeaders(cs.trace) cc.mu.Unlock() @@ -932,6 +955,9 @@ func (cc *ClientConn) awaitOpenSlotForRequest(req *http.Request) error { for { cc.lastActive = time.Now() if cc.closed || !cc.canTakeNewRequestLocked() { + if waitingForConn != nil { + close(waitingForConn) + } return errClientConnUnusable } if int64(len(cc.streams))+1 <= int64(cc.maxConcurrentStreams) { @@ -964,13 +990,12 @@ func (cc *ClientConn) awaitOpenSlotForRequest(req *http.Request) error { } // requires cc.wmu be held -func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, hdrs []byte) error { +func (cc *ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error { first := true // first frame written (HEADERS is first, then CONTINUATION) - frameSize := int(cc.maxFrameSize) for len(hdrs) > 0 && cc.werr == nil { chunk := hdrs - if len(chunk) > frameSize { - chunk = chunk[:frameSize] + if len(chunk) > maxFrameSize { + chunk = chunk[:maxFrameSize] } hdrs = hdrs[len(chunk):] endHeaders := len(hdrs) == 0 @@ -1087,13 +1112,17 @@ func (cs *clientStream) writeRequestBody(body io.Reader, bodyCloser io.Closer) ( } } + cc.mu.Lock() + maxFrameSize := int(cc.maxFrameSize) + cc.mu.Unlock() + cc.wmu.Lock() defer cc.wmu.Unlock() // Two ways to send END_STREAM: either with trailers, or // with an empty DATA frame. if len(trls) > 0 { - err = cc.writeHeaders(cs.ID, true, trls) + err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls) } else { err = cc.fr.WriteData(cs.ID, true, nil) } @@ -1152,7 +1181,7 @@ func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trail if host == "" { host = req.URL.Host } - host, err := httplex.PunycodeHostPort(host) + host, err := httpguts.PunycodeHostPort(host) if err != nil { return nil, err } @@ -1177,11 +1206,11 @@ func (cc *ClientConn) encodeHeaders(req *http.Request, addGzipHeader bool, trail // potentially pollute our hpack state. (We want to be able to // continue to reuse the hpack encoder for future requests) for k, vv := range req.Header { - if !httplex.ValidHeaderFieldName(k) { + if !httpguts.ValidHeaderFieldName(k) { return nil, fmt.Errorf("invalid HTTP header name %q", k) } for _, v := range vv { - if !httplex.ValidHeaderFieldValue(v) { + if !httpguts.ValidHeaderFieldValue(v) { return nil, fmt.Errorf("invalid HTTP header value %q for header %q", v, k) } } @@ -1373,17 +1402,12 @@ func (cc *ClientConn) streamByID(id uint32, andRemove bool) *clientStream { // clientConnReadLoop is the state owned by the clientConn's frame-reading readLoop. type clientConnReadLoop struct { cc *ClientConn - activeRes map[uint32]*clientStream // keyed by streamID closeWhenIdle bool } // readLoop runs in its own goroutine and reads and dispatches frames. func (cc *ClientConn) readLoop() { - rl := &clientConnReadLoop{ - cc: cc, - activeRes: make(map[uint32]*clientStream), - } - + rl := &clientConnReadLoop{cc: cc} defer rl.cleanup() cc.readerErr = rl.run() if ce, ok := cc.readerErr.(ConnectionError); ok { @@ -1438,10 +1462,8 @@ func (rl *clientConnReadLoop) cleanup() { } else if err == io.EOF { err = io.ErrUnexpectedEOF } - for _, cs := range rl.activeRes { - cs.bufPipe.CloseWithError(err) - } for _, cs := range cc.streams { + cs.bufPipe.CloseWithError(err) // no-op if already closed select { case cs.resc <- resAndError{err: err}: default: @@ -1519,7 +1541,7 @@ func (rl *clientConnReadLoop) run() error { } return err } - if rl.closeWhenIdle && gotReply && maybeIdle && len(rl.activeRes) == 0 { + if rl.closeWhenIdle && gotReply && maybeIdle { cc.closeIfIdle() } } @@ -1527,6 +1549,13 @@ func (rl *clientConnReadLoop) run() error { func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error { cc := rl.cc + cs := cc.streamByID(f.StreamID, false) + if cs == nil { + // We'd get here if we canceled a request while the + // server had its response still in flight. So if this + // was just something we canceled, ignore it. + return nil + } if f.StreamEnded() { // Issue 20521: If the stream has ended, streamByID() causes // clientStream.done to be closed, which causes the request's bodyWriter @@ -1535,14 +1564,15 @@ func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error { // Deferring stream closure allows the header processing to occur first. // clientConn.RoundTrip may still receive the bodyWriter error first, but // the fix for issue 16102 prioritises any response. - defer cc.streamByID(f.StreamID, true) - } - cs := cc.streamByID(f.StreamID, false) - if cs == nil { - // We'd get here if we canceled a request while the - // server had its response still in flight. So if this - // was just something we canceled, ignore it. - return nil + // + // Issue 22413: If there is no request body, we should close the + // stream before writing to cs.resc so that the stream is closed + // immediately once RoundTrip returns. + if cs.req.Body != nil { + defer cc.forgetStreamID(f.StreamID) + } else { + cc.forgetStreamID(f.StreamID) + } } if !cs.firstByte { if cs.trace != nil { @@ -1567,6 +1597,7 @@ func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error { } // Any other error type is a stream error. cs.cc.writeStreamReset(f.StreamID, ErrCodeProtocol, err) + cc.forgetStreamID(cs.ID) cs.resc <- resAndError{err: err} return nil // return nil from process* funcs to keep conn alive } @@ -1574,9 +1605,6 @@ func (rl *clientConnReadLoop) processHeaders(f *MetaHeadersFrame) error { // (nil, nil) special case. See handleResponse docs. return nil } - if res.Body != noBody { - rl.activeRes[cs.ID] = cs - } cs.resTrailer = &res.Trailer cs.resc <- resAndError{res: res} return nil @@ -1596,11 +1624,11 @@ func (rl *clientConnReadLoop) handleResponse(cs *clientStream, f *MetaHeadersFra status := f.PseudoValue("status") if status == "" { - return nil, errors.New("missing status pseudo header") + return nil, errors.New("malformed response from server: missing status pseudo header") } statusCode, err := strconv.Atoi(status) if err != nil { - return nil, errors.New("malformed non-numeric status pseudo header") + return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header") } if statusCode == 100 { @@ -1915,7 +1943,6 @@ func (rl *clientConnReadLoop) endStreamError(cs *clientStream, err error) { rl.closeWhenIdle = true } cs.bufPipe.closeWithErrorAndCode(err, code) - delete(rl.activeRes, cs.ID) select { case cs.resc <- resAndError{err: err}: @@ -2042,7 +2069,6 @@ func (rl *clientConnReadLoop) processResetStream(f *RSTStreamFrame) error { cs.bufPipe.CloseWithError(err) cs.cc.cond.Broadcast() // wake up checkResetOrDone via clientStream.awaitFlowControl } - delete(rl.activeRes, cs.ID) return nil } @@ -2225,7 +2251,7 @@ func (t *Transport) getBodyWriterState(cs *clientStream, body io.Reader) (s body } s.delay = t.expectContinueTimeout() if s.delay == 0 || - !httplex.HeaderValuesContainsToken( + !httpguts.HeaderValuesContainsToken( cs.req.Header["Expect"], "100-continue") { return @@ -2280,5 +2306,5 @@ func (s bodyWriterState) scheduleBodyWrite() { // isConnectionCloseRequest reports whether req should use its own // connection for a single request and then close the connection. func isConnectionCloseRequest(req *http.Request) bool { - return req.Close || httplex.HeaderValuesContainsToken(req.Header["Connection"], "close") + return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close") } diff --git a/vendor/golang.org/x/net/http2/transport_test.go b/vendor/golang.org/x/net/http2/transport_test.go deleted file mode 100644 index 30d7b5de0f..0000000000 --- a/vendor/golang.org/x/net/http2/transport_test.go +++ /dev/null @@ -1,3796 +0,0 @@ -// Copyright 2015 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 http2 - -import ( - "bufio" - "bytes" - "crypto/tls" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "math/rand" - "net" - "net/http" - "net/http/httptest" - "net/url" - "os" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "golang.org/x/net/http2/hpack" -) - -var ( - extNet = flag.Bool("extnet", false, "do external network tests") - transportHost = flag.String("transporthost", "http2.golang.org", "hostname to use for TestTransport") - insecure = flag.Bool("insecure", false, "insecure TLS dials") // TODO: dead code. remove? -) - -var tlsConfigInsecure = &tls.Config{InsecureSkipVerify: true} - -type testContext struct{} - -func (testContext) Done() <-chan struct{} { return make(chan struct{}) } -func (testContext) Err() error { panic("should not be called") } -func (testContext) Deadline() (deadline time.Time, ok bool) { return time.Time{}, false } -func (testContext) Value(key interface{}) interface{} { return nil } - -func TestTransportExternal(t *testing.T) { - if !*extNet { - t.Skip("skipping external network test") - } - req, _ := http.NewRequest("GET", "https://"+*transportHost+"/", nil) - rt := &Transport{TLSClientConfig: tlsConfigInsecure} - res, err := rt.RoundTrip(req) - if err != nil { - t.Fatalf("%v", err) - } - res.Write(os.Stdout) -} - -type fakeTLSConn struct { - net.Conn -} - -func (c *fakeTLSConn) ConnectionState() tls.ConnectionState { - return tls.ConnectionState{ - Version: tls.VersionTLS12, - CipherSuite: cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - } -} - -func startH2cServer(t *testing.T) net.Listener { - h2Server := &Server{} - l := newLocalListener(t) - go func() { - conn, err := l.Accept() - if err != nil { - t.Error(err) - return - } - h2Server.ServeConn(&fakeTLSConn{conn}, &ServeConnOpts{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hello, %v, http: %v", r.URL.Path, r.TLS == nil) - })}) - }() - return l -} - -func TestTransportH2c(t *testing.T) { - l := startH2cServer(t) - defer l.Close() - req, err := http.NewRequest("GET", "http://"+l.Addr().String()+"/foobar", nil) - if err != nil { - t.Fatal(err) - } - tr := &Transport{ - AllowHTTP: true, - DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { - return net.Dial(network, addr) - }, - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - if res.ProtoMajor != 2 { - t.Fatal("proto not h2c") - } - body, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if got, want := string(body), "Hello, /foobar, http: true"; got != want { - t.Fatalf("response got %v, want %v", got, want) - } -} - -func TestTransport(t *testing.T) { - const body = "sup" - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, body) - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal(err) - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - - t.Logf("Got res: %+v", res) - if g, w := res.StatusCode, 200; g != w { - t.Errorf("StatusCode = %v; want %v", g, w) - } - if g, w := res.Status, "200 OK"; g != w { - t.Errorf("Status = %q; want %q", g, w) - } - wantHeader := http.Header{ - "Content-Length": []string{"3"}, - "Content-Type": []string{"text/plain; charset=utf-8"}, - "Date": []string{"XXX"}, // see cleanDate - } - cleanDate(res) - if !reflect.DeepEqual(res.Header, wantHeader) { - t.Errorf("res Header = %v; want %v", res.Header, wantHeader) - } - if res.Request != req { - t.Errorf("Response.Request = %p; want %p", res.Request, req) - } - if res.TLS == nil { - t.Error("Response.TLS = nil; want non-nil") - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Errorf("Body read: %v", err) - } else if string(slurp) != body { - t.Errorf("Body = %q; want %q", slurp, body) - } -} - -func onSameConn(t *testing.T, modReq func(*http.Request)) bool { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, r.RemoteAddr) - }, optOnlyServer, func(c net.Conn, st http.ConnState) { - t.Logf("conn %v is now state %v", c.RemoteAddr(), st) - }) - defer st.Close() - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - get := func() string { - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal(err) - } - modReq(req) - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatalf("Body read: %v", err) - } - addr := strings.TrimSpace(string(slurp)) - if addr == "" { - t.Fatalf("didn't get an addr in response") - } - return addr - } - first := get() - second := get() - return first == second -} - -func TestTransportReusesConns(t *testing.T) { - if !onSameConn(t, func(*http.Request) {}) { - t.Errorf("first and second responses were on different connections") - } -} - -func TestTransportReusesConn_RequestClose(t *testing.T) { - if onSameConn(t, func(r *http.Request) { r.Close = true }) { - t.Errorf("first and second responses were not on different connections") - } -} - -func TestTransportReusesConn_ConnClose(t *testing.T) { - if onSameConn(t, func(r *http.Request) { r.Header.Set("Connection", "close") }) { - t.Errorf("first and second responses were not on different connections") - } -} - -// Tests that the Transport only keeps one pending dial open per destination address. -// https://golang.org/issue/13397 -func TestTransportGroupsPendingDials(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, r.RemoteAddr) - }, optOnlyServer) - defer st.Close() - tr := &Transport{ - TLSClientConfig: tlsConfigInsecure, - } - defer tr.CloseIdleConnections() - var ( - mu sync.Mutex - dials = map[string]int{} - ) - var wg sync.WaitGroup - for i := 0; i < 10; i++ { - wg.Add(1) - go func() { - defer wg.Done() - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Error(err) - return - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Error(err) - return - } - defer res.Body.Close() - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Errorf("Body read: %v", err) - } - addr := strings.TrimSpace(string(slurp)) - if addr == "" { - t.Errorf("didn't get an addr in response") - } - mu.Lock() - dials[addr]++ - mu.Unlock() - }() - } - wg.Wait() - if len(dials) != 1 { - t.Errorf("saw %d dials; want 1: %v", len(dials), dials) - } - tr.CloseIdleConnections() - if err := retry(50, 10*time.Millisecond, func() error { - cp, ok := tr.connPool().(*clientConnPool) - if !ok { - return fmt.Errorf("Conn pool is %T; want *clientConnPool", tr.connPool()) - } - cp.mu.Lock() - defer cp.mu.Unlock() - if len(cp.dialing) != 0 { - return fmt.Errorf("dialing map = %v; want empty", cp.dialing) - } - if len(cp.conns) != 0 { - return fmt.Errorf("conns = %v; want empty", cp.conns) - } - if len(cp.keys) != 0 { - return fmt.Errorf("keys = %v; want empty", cp.keys) - } - return nil - }); err != nil { - t.Errorf("State of pool after CloseIdleConnections: %v", err) - } -} - -func retry(tries int, delay time.Duration, fn func() error) error { - var err error - for i := 0; i < tries; i++ { - err = fn() - if err == nil { - return nil - } - time.Sleep(delay) - } - return err -} - -func TestTransportAbortClosesPipes(t *testing.T) { - shutdown := make(chan struct{}) - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - w.(http.Flusher).Flush() - <-shutdown - }, - optOnlyServer, - ) - defer st.Close() - defer close(shutdown) // we must shutdown before st.Close() to avoid hanging - - done := make(chan struct{}) - requestMade := make(chan struct{}) - go func() { - defer close(done) - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal(err) - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - close(requestMade) - _, err = ioutil.ReadAll(res.Body) - if err == nil { - t.Error("expected error from res.Body.Read") - } - }() - - <-requestMade - // Now force the serve loop to end, via closing the connection. - st.closeConn() - // deadlock? that's a bug. - select { - case <-done: - case <-time.After(3 * time.Second): - t.Fatal("timeout") - } -} - -// TODO: merge this with TestTransportBody to make TestTransportRequest? This -// could be a table-driven test with extra goodies. -func TestTransportPath(t *testing.T) { - gotc := make(chan *url.URL, 1) - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - gotc <- r.URL - }, - optOnlyServer, - ) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - const ( - path = "/testpath" - query = "q=1" - ) - surl := st.ts.URL + path + "?" + query - req, err := http.NewRequest("POST", surl, nil) - if err != nil { - t.Fatal(err) - } - c := &http.Client{Transport: tr} - res, err := c.Do(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - got := <-gotc - if got.Path != path { - t.Errorf("Read Path = %q; want %q", got.Path, path) - } - if got.RawQuery != query { - t.Errorf("Read RawQuery = %q; want %q", got.RawQuery, query) - } -} - -func randString(n int) string { - rnd := rand.New(rand.NewSource(int64(n))) - b := make([]byte, n) - for i := range b { - b[i] = byte(rnd.Intn(256)) - } - return string(b) -} - -type panicReader struct{} - -func (panicReader) Read([]byte) (int, error) { panic("unexpected Read") } -func (panicReader) Close() error { panic("unexpected Close") } - -func TestActualContentLength(t *testing.T) { - tests := []struct { - req *http.Request - want int64 - }{ - // Verify we don't read from Body: - 0: { - req: &http.Request{Body: panicReader{}}, - want: -1, - }, - // nil Body means 0, regardless of ContentLength: - 1: { - req: &http.Request{Body: nil, ContentLength: 5}, - want: 0, - }, - // ContentLength is used if set. - 2: { - req: &http.Request{Body: panicReader{}, ContentLength: 5}, - want: 5, - }, - // http.NoBody means 0, not -1. - 3: { - req: &http.Request{Body: go18httpNoBody()}, - want: 0, - }, - } - for i, tt := range tests { - got := actualContentLength(tt.req) - if got != tt.want { - t.Errorf("test[%d]: got %d; want %d", i, got, tt.want) - } - } -} - -func TestTransportBody(t *testing.T) { - bodyTests := []struct { - body string - noContentLen bool - }{ - {body: "some message"}, - {body: "some message", noContentLen: true}, - {body: strings.Repeat("a", 1<<20), noContentLen: true}, - {body: strings.Repeat("a", 1<<20)}, - {body: randString(16<<10 - 1)}, - {body: randString(16 << 10)}, - {body: randString(16<<10 + 1)}, - {body: randString(512<<10 - 1)}, - {body: randString(512 << 10)}, - {body: randString(512<<10 + 1)}, - {body: randString(1<<20 - 1)}, - {body: randString(1 << 20)}, - {body: randString(1<<20 + 2)}, - } - - type reqInfo struct { - req *http.Request - slurp []byte - err error - } - gotc := make(chan reqInfo, 1) - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - slurp, err := ioutil.ReadAll(r.Body) - if err != nil { - gotc <- reqInfo{err: err} - } else { - gotc <- reqInfo{req: r, slurp: slurp} - } - }, - optOnlyServer, - ) - defer st.Close() - - for i, tt := range bodyTests { - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - var body io.Reader = strings.NewReader(tt.body) - if tt.noContentLen { - body = struct{ io.Reader }{body} // just a Reader, hiding concrete type and other methods - } - req, err := http.NewRequest("POST", st.ts.URL, body) - if err != nil { - t.Fatalf("#%d: %v", i, err) - } - c := &http.Client{Transport: tr} - res, err := c.Do(req) - if err != nil { - t.Fatalf("#%d: %v", i, err) - } - defer res.Body.Close() - ri := <-gotc - if ri.err != nil { - t.Errorf("#%d: read error: %v", i, ri.err) - continue - } - if got := string(ri.slurp); got != tt.body { - t.Errorf("#%d: Read body mismatch.\n got: %q (len %d)\nwant: %q (len %d)", i, shortString(got), len(got), shortString(tt.body), len(tt.body)) - } - wantLen := int64(len(tt.body)) - if tt.noContentLen && tt.body != "" { - wantLen = -1 - } - if ri.req.ContentLength != wantLen { - t.Errorf("#%d. handler got ContentLength = %v; want %v", i, ri.req.ContentLength, wantLen) - } - } -} - -func shortString(v string) string { - const maxLen = 100 - if len(v) <= maxLen { - return v - } - return fmt.Sprintf("%v[...%d bytes omitted...]%v", v[:maxLen/2], len(v)-maxLen, v[len(v)-maxLen/2:]) -} - -func TestTransportDialTLS(t *testing.T) { - var mu sync.Mutex // guards following - var gotReq, didDial bool - - ts := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - mu.Lock() - gotReq = true - mu.Unlock() - }, - optOnlyServer, - ) - defer ts.Close() - tr := &Transport{ - DialTLS: func(netw, addr string, cfg *tls.Config) (net.Conn, error) { - mu.Lock() - didDial = true - mu.Unlock() - cfg.InsecureSkipVerify = true - c, err := tls.Dial(netw, addr, cfg) - if err != nil { - return nil, err - } - return c, c.Handshake() - }, - } - defer tr.CloseIdleConnections() - client := &http.Client{Transport: tr} - res, err := client.Get(ts.ts.URL) - if err != nil { - t.Fatal(err) - } - res.Body.Close() - mu.Lock() - if !gotReq { - t.Error("didn't get request") - } - if !didDial { - t.Error("didn't use dial hook") - } -} - -func TestConfigureTransport(t *testing.T) { - t1 := &http.Transport{} - err := ConfigureTransport(t1) - if err == errTransportVersion { - t.Skip(err) - } - if err != nil { - t.Fatal(err) - } - if got := fmt.Sprintf("%#v", t1); !strings.Contains(got, `"h2"`) { - // Laziness, to avoid buildtags. - t.Errorf("stringification of HTTP/1 transport didn't contain \"h2\": %v", got) - } - wantNextProtos := []string{"h2", "http/1.1"} - if t1.TLSClientConfig == nil { - t.Errorf("nil t1.TLSClientConfig") - } else if !reflect.DeepEqual(t1.TLSClientConfig.NextProtos, wantNextProtos) { - t.Errorf("TLSClientConfig.NextProtos = %q; want %q", t1.TLSClientConfig.NextProtos, wantNextProtos) - } - if err := ConfigureTransport(t1); err == nil { - t.Error("unexpected success on second call to ConfigureTransport") - } - - // And does it work? - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, r.Proto) - }, optOnlyServer) - defer st.Close() - - t1.TLSClientConfig.InsecureSkipVerify = true - c := &http.Client{Transport: t1} - res, err := c.Get(st.ts.URL) - if err != nil { - t.Fatal(err) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if got, want := string(slurp), "HTTP/2.0"; got != want { - t.Errorf("body = %q; want %q", got, want) - } -} - -type capitalizeReader struct { - r io.Reader -} - -func (cr capitalizeReader) Read(p []byte) (n int, err error) { - n, err = cr.r.Read(p) - for i, b := range p[:n] { - if b >= 'a' && b <= 'z' { - p[i] = b - ('a' - 'A') - } - } - return -} - -type flushWriter struct { - w io.Writer -} - -func (fw flushWriter) Write(p []byte) (n int, err error) { - n, err = fw.w.Write(p) - if f, ok := fw.w.(http.Flusher); ok { - f.Flush() - } - return -} - -type clientTester struct { - t *testing.T - tr *Transport - sc, cc net.Conn // server and client conn - fr *Framer // server's framer - client func() error - server func() error -} - -func newClientTester(t *testing.T) *clientTester { - var dialOnce struct { - sync.Mutex - dialed bool - } - ct := &clientTester{ - t: t, - } - ct.tr = &Transport{ - TLSClientConfig: tlsConfigInsecure, - DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { - dialOnce.Lock() - defer dialOnce.Unlock() - if dialOnce.dialed { - return nil, errors.New("only one dial allowed in test mode") - } - dialOnce.dialed = true - return ct.cc, nil - }, - } - - ln := newLocalListener(t) - cc, err := net.Dial("tcp", ln.Addr().String()) - if err != nil { - t.Fatal(err) - - } - sc, err := ln.Accept() - if err != nil { - t.Fatal(err) - } - ln.Close() - ct.cc = cc - ct.sc = sc - ct.fr = NewFramer(sc, sc) - return ct -} - -func newLocalListener(t *testing.T) net.Listener { - ln, err := net.Listen("tcp4", "127.0.0.1:0") - if err == nil { - return ln - } - ln, err = net.Listen("tcp6", "[::1]:0") - if err != nil { - t.Fatal(err) - } - return ln -} - -func (ct *clientTester) greet(settings ...Setting) { - buf := make([]byte, len(ClientPreface)) - _, err := io.ReadFull(ct.sc, buf) - if err != nil { - ct.t.Fatalf("reading client preface: %v", err) - } - f, err := ct.fr.ReadFrame() - if err != nil { - ct.t.Fatalf("Reading client settings frame: %v", err) - } - if sf, ok := f.(*SettingsFrame); !ok { - ct.t.Fatalf("Wanted client settings frame; got %v", f) - _ = sf // stash it away? - } - if err := ct.fr.WriteSettings(settings...); err != nil { - ct.t.Fatal(err) - } - if err := ct.fr.WriteSettingsAck(); err != nil { - ct.t.Fatal(err) - } -} - -func (ct *clientTester) readNonSettingsFrame() (Frame, error) { - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return nil, err - } - if _, ok := f.(*SettingsFrame); ok { - continue - } - return f, nil - } -} - -func (ct *clientTester) cleanup() { - ct.tr.CloseIdleConnections() -} - -func (ct *clientTester) run() { - errc := make(chan error, 2) - ct.start("client", errc, ct.client) - ct.start("server", errc, ct.server) - defer ct.cleanup() - for i := 0; i < 2; i++ { - if err := <-errc; err != nil { - ct.t.Error(err) - return - } - } -} - -func (ct *clientTester) start(which string, errc chan<- error, fn func() error) { - go func() { - finished := false - var err error - defer func() { - if !finished { - err = fmt.Errorf("%s goroutine didn't finish.", which) - } else if err != nil { - err = fmt.Errorf("%s: %v", which, err) - } - errc <- err - }() - err = fn() - finished = true - }() -} - -func (ct *clientTester) readFrame() (Frame, error) { - return readFrameTimeout(ct.fr, 2*time.Second) -} - -func (ct *clientTester) firstHeaders() (*HeadersFrame, error) { - for { - f, err := ct.readFrame() - if err != nil { - return nil, fmt.Errorf("ReadFrame while waiting for Headers: %v", err) - } - switch f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - continue - } - hf, ok := f.(*HeadersFrame) - if !ok { - return nil, fmt.Errorf("Got %T; want HeadersFrame", f) - } - return hf, nil - } -} - -type countingReader struct { - n *int64 -} - -func (r countingReader) Read(p []byte) (n int, err error) { - for i := range p { - p[i] = byte(i) - } - atomic.AddInt64(r.n, int64(len(p))) - return len(p), err -} - -func TestTransportReqBodyAfterResponse_200(t *testing.T) { testTransportReqBodyAfterResponse(t, 200) } -func TestTransportReqBodyAfterResponse_403(t *testing.T) { testTransportReqBodyAfterResponse(t, 403) } - -func testTransportReqBodyAfterResponse(t *testing.T, status int) { - const bodySize = 10 << 20 - clientDone := make(chan struct{}) - ct := newClientTester(t) - ct.client = func() error { - defer ct.cc.(*net.TCPConn).CloseWrite() - defer close(clientDone) - - var n int64 // atomic - req, err := http.NewRequest("PUT", "https://dummy.tld/", io.LimitReader(countingReader{&n}, bodySize)) - if err != nil { - return err - } - res, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - defer res.Body.Close() - if res.StatusCode != status { - return fmt.Errorf("status code = %v; want %v", res.StatusCode, status) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("Slurp: %v", err) - } - if len(slurp) > 0 { - return fmt.Errorf("unexpected body: %q", slurp) - } - if status == 200 { - if got := atomic.LoadInt64(&n); got != bodySize { - return fmt.Errorf("For 200 response, Transport wrote %d bytes; want %d", got, bodySize) - } - } else { - if got := atomic.LoadInt64(&n); got == 0 || got >= bodySize { - return fmt.Errorf("For %d response, Transport wrote %d bytes; want (0,%d) exclusive", status, got, bodySize) - } - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - var dataRecv int64 - var closed bool - for { - f, err := ct.fr.ReadFrame() - if err != nil { - select { - case <-clientDone: - // If the client's done, it - // will have reported any - // errors on its side. - return nil - default: - return err - } - } - //println(fmt.Sprintf("server got frame: %v", f)) - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *HeadersFrame: - if !f.HeadersEnded() { - return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) - } - if f.StreamEnded() { - return fmt.Errorf("headers contains END_STREAM unexpectedly: %v", f) - } - case *DataFrame: - dataLen := len(f.Data()) - if dataLen > 0 { - if dataRecv == 0 { - enc.WriteField(hpack.HeaderField{Name: ":status", Value: strconv.Itoa(status)}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - } - if err := ct.fr.WriteWindowUpdate(0, uint32(dataLen)); err != nil { - return err - } - if err := ct.fr.WriteWindowUpdate(f.StreamID, uint32(dataLen)); err != nil { - return err - } - } - dataRecv += int64(dataLen) - - if !closed && ((status != 200 && dataRecv > 0) || - (status == 200 && dataRecv == bodySize)) { - closed = true - if err := ct.fr.WriteData(f.StreamID, true, nil); err != nil { - return err - } - } - default: - return fmt.Errorf("Unexpected client frame %v", f) - } - } - } - ct.run() -} - -// See golang.org/issue/13444 -func TestTransportFullDuplex(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(200) // redundant but for clarity - w.(http.Flusher).Flush() - io.Copy(flushWriter{w}, capitalizeReader{r.Body}) - fmt.Fprintf(w, "bye.\n") - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - - pr, pw := io.Pipe() - req, err := http.NewRequest("PUT", st.ts.URL, ioutil.NopCloser(pr)) - if err != nil { - t.Fatal(err) - } - req.ContentLength = -1 - res, err := c.Do(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - if res.StatusCode != 200 { - t.Fatalf("StatusCode = %v; want %v", res.StatusCode, 200) - } - bs := bufio.NewScanner(res.Body) - want := func(v string) { - if !bs.Scan() { - t.Fatalf("wanted to read %q but Scan() = false, err = %v", v, bs.Err()) - } - } - write := func(v string) { - _, err := io.WriteString(pw, v) - if err != nil { - t.Fatalf("pipe write: %v", err) - } - } - write("foo\n") - want("FOO") - write("bar\n") - want("BAR") - pw.Close() - want("bye.") - if err := bs.Err(); err != nil { - t.Fatal(err) - } -} - -func TestTransportConnectRequest(t *testing.T) { - gotc := make(chan *http.Request, 1) - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - gotc <- r - }, optOnlyServer) - defer st.Close() - - u, err := url.Parse(st.ts.URL) - if err != nil { - t.Fatal(err) - } - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - - tests := []struct { - req *http.Request - want string - }{ - { - req: &http.Request{ - Method: "CONNECT", - Header: http.Header{}, - URL: u, - }, - want: u.Host, - }, - { - req: &http.Request{ - Method: "CONNECT", - Header: http.Header{}, - URL: u, - Host: "example.com:123", - }, - want: "example.com:123", - }, - } - - for i, tt := range tests { - res, err := c.Do(tt.req) - if err != nil { - t.Errorf("%d. RoundTrip = %v", i, err) - continue - } - res.Body.Close() - req := <-gotc - if req.Method != "CONNECT" { - t.Errorf("method = %q; want CONNECT", req.Method) - } - if req.Host != tt.want { - t.Errorf("Host = %q; want %q", req.Host, tt.want) - } - if req.URL.Host != tt.want { - t.Errorf("URL.Host = %q; want %q", req.URL.Host, tt.want) - } - } -} - -type headerType int - -const ( - noHeader headerType = iota // omitted - oneHeader - splitHeader // broken into continuation on purpose -) - -const ( - f0 = noHeader - f1 = oneHeader - f2 = splitHeader - d0 = false - d1 = true -) - -// Test all 36 combinations of response frame orders: -// (3 ways of 100-continue) * (2 ways of headers) * (2 ways of data) * (3 ways of trailers):func TestTransportResponsePattern_00f0(t *testing.T) { testTransportResponsePattern(h0, h1, false, h0) } -// Generated by http://play.golang.org/p/SScqYKJYXd -func TestTransportResPattern_c0h1d0t0(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f0) } -func TestTransportResPattern_c0h1d0t1(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f1) } -func TestTransportResPattern_c0h1d0t2(t *testing.T) { testTransportResPattern(t, f0, f1, d0, f2) } -func TestTransportResPattern_c0h1d1t0(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f0) } -func TestTransportResPattern_c0h1d1t1(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f1) } -func TestTransportResPattern_c0h1d1t2(t *testing.T) { testTransportResPattern(t, f0, f1, d1, f2) } -func TestTransportResPattern_c0h2d0t0(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f0) } -func TestTransportResPattern_c0h2d0t1(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f1) } -func TestTransportResPattern_c0h2d0t2(t *testing.T) { testTransportResPattern(t, f0, f2, d0, f2) } -func TestTransportResPattern_c0h2d1t0(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f0) } -func TestTransportResPattern_c0h2d1t1(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f1) } -func TestTransportResPattern_c0h2d1t2(t *testing.T) { testTransportResPattern(t, f0, f2, d1, f2) } -func TestTransportResPattern_c1h1d0t0(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f0) } -func TestTransportResPattern_c1h1d0t1(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f1) } -func TestTransportResPattern_c1h1d0t2(t *testing.T) { testTransportResPattern(t, f1, f1, d0, f2) } -func TestTransportResPattern_c1h1d1t0(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f0) } -func TestTransportResPattern_c1h1d1t1(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f1) } -func TestTransportResPattern_c1h1d1t2(t *testing.T) { testTransportResPattern(t, f1, f1, d1, f2) } -func TestTransportResPattern_c1h2d0t0(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f0) } -func TestTransportResPattern_c1h2d0t1(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f1) } -func TestTransportResPattern_c1h2d0t2(t *testing.T) { testTransportResPattern(t, f1, f2, d0, f2) } -func TestTransportResPattern_c1h2d1t0(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f0) } -func TestTransportResPattern_c1h2d1t1(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f1) } -func TestTransportResPattern_c1h2d1t2(t *testing.T) { testTransportResPattern(t, f1, f2, d1, f2) } -func TestTransportResPattern_c2h1d0t0(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f0) } -func TestTransportResPattern_c2h1d0t1(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f1) } -func TestTransportResPattern_c2h1d0t2(t *testing.T) { testTransportResPattern(t, f2, f1, d0, f2) } -func TestTransportResPattern_c2h1d1t0(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f0) } -func TestTransportResPattern_c2h1d1t1(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f1) } -func TestTransportResPattern_c2h1d1t2(t *testing.T) { testTransportResPattern(t, f2, f1, d1, f2) } -func TestTransportResPattern_c2h2d0t0(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f0) } -func TestTransportResPattern_c2h2d0t1(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f1) } -func TestTransportResPattern_c2h2d0t2(t *testing.T) { testTransportResPattern(t, f2, f2, d0, f2) } -func TestTransportResPattern_c2h2d1t0(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f0) } -func TestTransportResPattern_c2h2d1t1(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f1) } -func TestTransportResPattern_c2h2d1t2(t *testing.T) { testTransportResPattern(t, f2, f2, d1, f2) } - -func testTransportResPattern(t *testing.T, expect100Continue, resHeader headerType, withData bool, trailers headerType) { - const reqBody = "some request body" - const resBody = "some response body" - - if resHeader == noHeader { - // TODO: test 100-continue followed by immediate - // server stream reset, without headers in the middle? - panic("invalid combination") - } - - ct := newClientTester(t) - ct.client = func() error { - req, _ := http.NewRequest("POST", "https://dummy.tld/", strings.NewReader(reqBody)) - if expect100Continue != noHeader { - req.Header.Set("Expect", "100-continue") - } - res, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - defer res.Body.Close() - if res.StatusCode != 200 { - return fmt.Errorf("status code = %v; want 200", res.StatusCode) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("Slurp: %v", err) - } - wantBody := resBody - if !withData { - wantBody = "" - } - if string(slurp) != wantBody { - return fmt.Errorf("body = %q; want %q", slurp, wantBody) - } - if trailers == noHeader { - if len(res.Trailer) > 0 { - t.Errorf("Trailer = %v; want none", res.Trailer) - } - } else { - want := http.Header{"Some-Trailer": {"some-value"}} - if !reflect.DeepEqual(res.Trailer, want) { - t.Errorf("Trailer = %v; want %v", res.Trailer, want) - } - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return err - } - endStream := false - send := func(mode headerType) { - hbf := buf.Bytes() - switch mode { - case oneHeader: - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.Header().StreamID, - EndHeaders: true, - EndStream: endStream, - BlockFragment: hbf, - }) - case splitHeader: - if len(hbf) < 2 { - panic("too small") - } - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.Header().StreamID, - EndHeaders: false, - EndStream: endStream, - BlockFragment: hbf[:1], - }) - ct.fr.WriteContinuation(f.Header().StreamID, true, hbf[1:]) - default: - panic("bogus mode") - } - } - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *DataFrame: - if !f.StreamEnded() { - // No need to send flow control tokens. The test request body is tiny. - continue - } - // Response headers (1+ frames; 1 or 2 in this test, but never 0) - { - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "x-foo", Value: "blah"}) - enc.WriteField(hpack.HeaderField{Name: "x-bar", Value: "more"}) - if trailers != noHeader { - enc.WriteField(hpack.HeaderField{Name: "trailer", Value: "some-trailer"}) - } - endStream = withData == false && trailers == noHeader - send(resHeader) - } - if withData { - endStream = trailers == noHeader - ct.fr.WriteData(f.StreamID, endStream, []byte(resBody)) - } - if trailers != noHeader { - endStream = true - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: "some-trailer", Value: "some-value"}) - send(trailers) - } - if endStream { - return nil - } - case *HeadersFrame: - if expect100Continue != noHeader { - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "100"}) - send(expect100Continue) - } - } - } - } - ct.run() -} - -func TestTransportReceiveUndeclaredTrailer(t *testing.T) { - ct := newClientTester(t) - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - defer res.Body.Close() - if res.StatusCode != 200 { - return fmt.Errorf("status code = %v; want 200", res.StatusCode) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("res.Body ReadAll error = %q, %v; want %v", slurp, err, nil) - } - if len(slurp) > 0 { - return fmt.Errorf("body = %q; want nothing", slurp) - } - if _, ok := res.Trailer["Some-Trailer"]; !ok { - return fmt.Errorf("expected Some-Trailer") - } - return nil - } - ct.server = func() error { - ct.greet() - - var n int - var hf *HeadersFrame - for hf == nil && n < 10 { - f, err := ct.fr.ReadFrame() - if err != nil { - return err - } - hf, _ = f.(*HeadersFrame) - n++ - } - - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - - // send headers without Trailer header - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - - // send trailers - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: "some-trailer", Value: "I'm an undeclared Trailer!"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - return nil - } - ct.run() -} - -func TestTransportInvalidTrailer_Pseudo1(t *testing.T) { - testTransportInvalidTrailer_Pseudo(t, oneHeader) -} -func TestTransportInvalidTrailer_Pseudo2(t *testing.T) { - testTransportInvalidTrailer_Pseudo(t, splitHeader) -} -func testTransportInvalidTrailer_Pseudo(t *testing.T, trailers headerType) { - testInvalidTrailer(t, trailers, pseudoHeaderError(":colon"), func(enc *hpack.Encoder) { - enc.WriteField(hpack.HeaderField{Name: ":colon", Value: "foo"}) - enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"}) - }) -} - -func TestTransportInvalidTrailer_Capital1(t *testing.T) { - testTransportInvalidTrailer_Capital(t, oneHeader) -} -func TestTransportInvalidTrailer_Capital2(t *testing.T) { - testTransportInvalidTrailer_Capital(t, splitHeader) -} -func testTransportInvalidTrailer_Capital(t *testing.T, trailers headerType) { - testInvalidTrailer(t, trailers, headerFieldNameError("Capital"), func(enc *hpack.Encoder) { - enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"}) - enc.WriteField(hpack.HeaderField{Name: "Capital", Value: "bad"}) - }) -} -func TestTransportInvalidTrailer_EmptyFieldName(t *testing.T) { - testInvalidTrailer(t, oneHeader, headerFieldNameError(""), func(enc *hpack.Encoder) { - enc.WriteField(hpack.HeaderField{Name: "", Value: "bad"}) - }) -} -func TestTransportInvalidTrailer_BinaryFieldValue(t *testing.T) { - testInvalidTrailer(t, oneHeader, headerFieldValueError("has\nnewline"), func(enc *hpack.Encoder) { - enc.WriteField(hpack.HeaderField{Name: "x", Value: "has\nnewline"}) - }) -} - -func testInvalidTrailer(t *testing.T, trailers headerType, wantErr error, writeTrailer func(*hpack.Encoder)) { - ct := newClientTester(t) - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - defer res.Body.Close() - if res.StatusCode != 200 { - return fmt.Errorf("status code = %v; want 200", res.StatusCode) - } - slurp, err := ioutil.ReadAll(res.Body) - se, ok := err.(StreamError) - if !ok || se.Cause != wantErr { - return fmt.Errorf("res.Body ReadAll error = %q, %#v; want StreamError with cause %T, %#v", slurp, err, wantErr, wantErr) - } - if len(slurp) > 0 { - return fmt.Errorf("body = %q; want nothing", slurp) - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return err - } - switch f := f.(type) { - case *HeadersFrame: - var endStream bool - send := func(mode headerType) { - hbf := buf.Bytes() - switch mode { - case oneHeader: - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: endStream, - BlockFragment: hbf, - }) - case splitHeader: - if len(hbf) < 2 { - panic("too small") - } - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: false, - EndStream: endStream, - BlockFragment: hbf[:1], - }) - ct.fr.WriteContinuation(f.StreamID, true, hbf[1:]) - default: - panic("bogus mode") - } - } - // Response headers (1+ frames; 1 or 2 in this test, but never 0) - { - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "trailer", Value: "declared"}) - endStream = false - send(oneHeader) - } - // Trailers: - { - endStream = true - buf.Reset() - writeTrailer(enc) - send(trailers) - } - return nil - } - } - } - ct.run() -} - -// headerListSize returns the HTTP2 header list size of h. -// http://httpwg.org/specs/rfc7540.html#SETTINGS_MAX_HEADER_LIST_SIZE -// http://httpwg.org/specs/rfc7540.html#MaxHeaderBlock -func headerListSize(h http.Header) (size uint32) { - for k, vv := range h { - for _, v := range vv { - hf := hpack.HeaderField{Name: k, Value: v} - size += hf.Size() - } - } - return size -} - -// padHeaders adds data to an http.Header until headerListSize(h) == -// limit. Due to the way header list sizes are calculated, padHeaders -// cannot add fewer than len("Pad-Headers") + 32 bytes to h, and will -// call t.Fatal if asked to do so. PadHeaders first reserves enough -// space for an empty "Pad-Headers" key, then adds as many copies of -// filler as possible. Any remaining bytes necessary to push the -// header list size up to limit are added to h["Pad-Headers"]. -func padHeaders(t *testing.T, h http.Header, limit uint64, filler string) { - if limit > 0xffffffff { - t.Fatalf("padHeaders: refusing to pad to more than 2^32-1 bytes. limit = %v", limit) - } - hf := hpack.HeaderField{Name: "Pad-Headers", Value: ""} - minPadding := uint64(hf.Size()) - size := uint64(headerListSize(h)) - - minlimit := size + minPadding - if limit < minlimit { - t.Fatalf("padHeaders: limit %v < %v", limit, minlimit) - } - - // Use a fixed-width format for name so that fieldSize - // remains constant. - nameFmt := "Pad-Headers-%06d" - hf = hpack.HeaderField{Name: fmt.Sprintf(nameFmt, 1), Value: filler} - fieldSize := uint64(hf.Size()) - - // Add as many complete filler values as possible, leaving - // room for at least one empty "Pad-Headers" key. - limit = limit - minPadding - for i := 0; size+fieldSize < limit; i++ { - name := fmt.Sprintf(nameFmt, i) - h.Add(name, filler) - size += fieldSize - } - - // Add enough bytes to reach limit. - remain := limit - size - lastValue := strings.Repeat("*", int(remain)) - h.Add("Pad-Headers", lastValue) -} - -func TestPadHeaders(t *testing.T) { - check := func(h http.Header, limit uint32, fillerLen int) { - if h == nil { - h = make(http.Header) - } - filler := strings.Repeat("f", fillerLen) - padHeaders(t, h, uint64(limit), filler) - gotSize := headerListSize(h) - if gotSize != limit { - t.Errorf("Got size = %v; want %v", gotSize, limit) - } - } - // Try all possible combinations for small fillerLen and limit. - hf := hpack.HeaderField{Name: "Pad-Headers", Value: ""} - minLimit := hf.Size() - for limit := minLimit; limit <= 128; limit++ { - for fillerLen := 0; uint32(fillerLen) <= limit; fillerLen++ { - check(nil, limit, fillerLen) - } - } - - // Try a few tests with larger limits, plus cumulative - // tests. Since these tests are cumulative, tests[i+1].limit - // must be >= tests[i].limit + minLimit. See the comment on - // padHeaders for more info on why the limit arg has this - // restriction. - tests := []struct { - fillerLen int - limit uint32 - }{ - { - fillerLen: 64, - limit: 1024, - }, - { - fillerLen: 1024, - limit: 1286, - }, - { - fillerLen: 256, - limit: 2048, - }, - { - fillerLen: 1024, - limit: 10 * 1024, - }, - { - fillerLen: 1023, - limit: 11 * 1024, - }, - } - h := make(http.Header) - for _, tc := range tests { - check(nil, tc.limit, tc.fillerLen) - check(h, tc.limit, tc.fillerLen) - } -} - -func TestTransportChecksRequestHeaderListSize(t *testing.T) { - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - // Consume body & force client to send - // trailers before writing response. - // ioutil.ReadAll returns non-nil err for - // requests that attempt to send greater than - // maxHeaderListSize bytes of trailers, since - // those requests generate a stream reset. - ioutil.ReadAll(r.Body) - r.Body.Close() - }, - func(ts *httptest.Server) { - ts.Config.MaxHeaderBytes = 16 << 10 - }, - optOnlyServer, - optQuiet, - ) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - checkRoundTrip := func(req *http.Request, wantErr error, desc string) { - res, err := tr.RoundTrip(req) - if err != wantErr { - if res != nil { - res.Body.Close() - } - t.Errorf("%v: RoundTrip err = %v; want %v", desc, err, wantErr) - return - } - if err == nil { - if res == nil { - t.Errorf("%v: response nil; want non-nil.", desc) - return - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - t.Errorf("%v: response status = %v; want %v", desc, res.StatusCode, http.StatusOK) - } - return - } - if res != nil { - t.Errorf("%v: RoundTrip err = %v but response non-nil", desc, err) - } - } - headerListSizeForRequest := func(req *http.Request) (size uint64) { - contentLen := actualContentLength(req) - trailers, err := commaSeparatedTrailers(req) - if err != nil { - t.Fatalf("headerListSizeForRequest: %v", err) - } - cc := &ClientConn{peerMaxHeaderListSize: 0xffffffffffffffff} - cc.henc = hpack.NewEncoder(&cc.hbuf) - cc.mu.Lock() - hdrs, err := cc.encodeHeaders(req, true, trailers, contentLen) - cc.mu.Unlock() - if err != nil { - t.Fatalf("headerListSizeForRequest: %v", err) - } - hpackDec := hpack.NewDecoder(initialHeaderTableSize, func(hf hpack.HeaderField) { - size += uint64(hf.Size()) - }) - if len(hdrs) > 0 { - if _, err := hpackDec.Write(hdrs); err != nil { - t.Fatalf("headerListSizeForRequest: %v", err) - } - } - return size - } - // Create a new Request for each test, rather than reusing the - // same Request, to avoid a race when modifying req.Headers. - // See https://github.com/golang/go/issues/21316 - newRequest := func() *http.Request { - // Body must be non-nil to enable writing trailers. - body := strings.NewReader("hello") - req, err := http.NewRequest("POST", st.ts.URL, body) - if err != nil { - t.Fatalf("newRequest: NewRequest: %v", err) - } - return req - } - - // Make an arbitrary request to ensure we get the server's - // settings frame and initialize peerMaxHeaderListSize. - req := newRequest() - checkRoundTrip(req, nil, "Initial request") - - // Get the ClientConn associated with the request and validate - // peerMaxHeaderListSize. - addr := authorityAddr(req.URL.Scheme, req.URL.Host) - cc, err := tr.connPool().GetClientConn(req, addr) - if err != nil { - t.Fatalf("GetClientConn: %v", err) - } - cc.mu.Lock() - peerSize := cc.peerMaxHeaderListSize - cc.mu.Unlock() - st.scMu.Lock() - wantSize := uint64(st.sc.maxHeaderListSize()) - st.scMu.Unlock() - if peerSize != wantSize { - t.Errorf("peerMaxHeaderListSize = %v; want %v", peerSize, wantSize) - } - - // Sanity check peerSize. (*serverConn) maxHeaderListSize adds - // 320 bytes of padding. - wantHeaderBytes := uint64(st.ts.Config.MaxHeaderBytes) + 320 - if peerSize != wantHeaderBytes { - t.Errorf("peerMaxHeaderListSize = %v; want %v.", peerSize, wantHeaderBytes) - } - - // Pad headers & trailers, but stay under peerSize. - req = newRequest() - req.Header = make(http.Header) - req.Trailer = make(http.Header) - filler := strings.Repeat("*", 1024) - padHeaders(t, req.Trailer, peerSize, filler) - // cc.encodeHeaders adds some default headers to the request, - // so we need to leave room for those. - defaultBytes := headerListSizeForRequest(req) - padHeaders(t, req.Header, peerSize-defaultBytes, filler) - checkRoundTrip(req, nil, "Headers & Trailers under limit") - - // Add enough header bytes to push us over peerSize. - req = newRequest() - req.Header = make(http.Header) - padHeaders(t, req.Header, peerSize, filler) - checkRoundTrip(req, errRequestHeaderListSize, "Headers over limit") - - // Push trailers over the limit. - req = newRequest() - req.Trailer = make(http.Header) - padHeaders(t, req.Trailer, peerSize+1, filler) - checkRoundTrip(req, errRequestHeaderListSize, "Trailers over limit") - - // Send headers with a single large value. - req = newRequest() - filler = strings.Repeat("*", int(peerSize)) - req.Header = make(http.Header) - req.Header.Set("Big", filler) - checkRoundTrip(req, errRequestHeaderListSize, "Single large header") - - // Send trailers with a single large value. - req = newRequest() - req.Trailer = make(http.Header) - req.Trailer.Set("Big", filler) - checkRoundTrip(req, errRequestHeaderListSize, "Single large trailer") -} - -func TestTransportChecksResponseHeaderListSize(t *testing.T) { - ct := newClientTester(t) - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != errResponseHeaderListSize { - if res != nil { - res.Body.Close() - } - size := int64(0) - for k, vv := range res.Header { - for _, v := range vv { - size += int64(len(k)) + int64(len(v)) + 32 - } - } - return fmt.Errorf("RoundTrip Error = %v (and %d bytes of response headers); want errResponseHeaderListSize", err, size) - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return err - } - switch f := f.(type) { - case *HeadersFrame: - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - large := strings.Repeat("a", 1<<10) - for i := 0; i < 5042; i++ { - enc.WriteField(hpack.HeaderField{Name: large, Value: large}) - } - if size, want := buf.Len(), 6329; size != want { - // Note: this number might change if - // our hpack implementation - // changes. That's fine. This is - // just a sanity check that our - // response can fit in a single - // header block fragment frame. - return fmt.Errorf("encoding over 10MB of duplicate keypairs took %d bytes; expected %d", size, want) - } - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - return nil - } - } - } - ct.run() -} - -// Test that the the Transport returns a typed error from Response.Body.Read calls -// when the server sends an error. (here we use a panic, since that should generate -// a stream error, but others like cancel should be similar) -func TestTransportBodyReadErrorType(t *testing.T) { - doPanic := make(chan bool, 1) - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - w.(http.Flusher).Flush() // force headers out - <-doPanic - panic("boom") - }, - optOnlyServer, - optQuiet, - ) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - - res, err := c.Get(st.ts.URL) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() - doPanic <- true - buf := make([]byte, 100) - n, err := res.Body.Read(buf) - want := StreamError{StreamID: 0x1, Code: 0x2} - if !reflect.DeepEqual(want, err) { - t.Errorf("Read = %v, %#v; want error %#v", n, err, want) - } -} - -// golang.org/issue/13924 -// This used to fail after many iterations, especially with -race: -// go test -v -run=TestTransportDoubleCloseOnWriteError -count=500 -race -func TestTransportDoubleCloseOnWriteError(t *testing.T) { - var ( - mu sync.Mutex - conn net.Conn // to close if set - ) - - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - mu.Lock() - defer mu.Unlock() - if conn != nil { - conn.Close() - } - }, - optOnlyServer, - ) - defer st.Close() - - tr := &Transport{ - TLSClientConfig: tlsConfigInsecure, - DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { - tc, err := tls.Dial(network, addr, cfg) - if err != nil { - return nil, err - } - mu.Lock() - defer mu.Unlock() - conn = tc - return tc, nil - }, - } - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - c.Get(st.ts.URL) -} - -// Test that the http1 Transport.DisableKeepAlives option is respected -// and connections are closed as soon as idle. -// See golang.org/issue/14008 -func TestTransportDisableKeepAlives(t *testing.T) { - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "hi") - }, - optOnlyServer, - ) - defer st.Close() - - connClosed := make(chan struct{}) // closed on tls.Conn.Close - tr := &Transport{ - t1: &http.Transport{ - DisableKeepAlives: true, - }, - TLSClientConfig: tlsConfigInsecure, - DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { - tc, err := tls.Dial(network, addr, cfg) - if err != nil { - return nil, err - } - return &noteCloseConn{Conn: tc, closefn: func() { close(connClosed) }}, nil - }, - } - c := &http.Client{Transport: tr} - res, err := c.Get(st.ts.URL) - if err != nil { - t.Fatal(err) - } - if _, err := ioutil.ReadAll(res.Body); err != nil { - t.Fatal(err) - } - defer res.Body.Close() - - select { - case <-connClosed: - case <-time.After(1 * time.Second): - t.Errorf("timeout") - } - -} - -// Test concurrent requests with Transport.DisableKeepAlives. We can share connections, -// but when things are totally idle, it still needs to close. -func TestTransportDisableKeepAlives_Concurrency(t *testing.T) { - const D = 25 * time.Millisecond - st := newServerTester(t, - func(w http.ResponseWriter, r *http.Request) { - time.Sleep(D) - io.WriteString(w, "hi") - }, - optOnlyServer, - ) - defer st.Close() - - var dials int32 - var conns sync.WaitGroup - tr := &Transport{ - t1: &http.Transport{ - DisableKeepAlives: true, - }, - TLSClientConfig: tlsConfigInsecure, - DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) { - tc, err := tls.Dial(network, addr, cfg) - if err != nil { - return nil, err - } - atomic.AddInt32(&dials, 1) - conns.Add(1) - return &noteCloseConn{Conn: tc, closefn: func() { conns.Done() }}, nil - }, - } - c := &http.Client{Transport: tr} - var reqs sync.WaitGroup - const N = 20 - for i := 0; i < N; i++ { - reqs.Add(1) - if i == N-1 { - // For the final request, try to make all the - // others close. This isn't verified in the - // count, other than the Log statement, since - // it's so timing dependent. This test is - // really to make sure we don't interrupt a - // valid request. - time.Sleep(D * 2) - } - go func() { - defer reqs.Done() - res, err := c.Get(st.ts.URL) - if err != nil { - t.Error(err) - return - } - if _, err := ioutil.ReadAll(res.Body); err != nil { - t.Error(err) - return - } - res.Body.Close() - }() - } - reqs.Wait() - conns.Wait() - t.Logf("did %d dials, %d requests", atomic.LoadInt32(&dials), N) -} - -type noteCloseConn struct { - net.Conn - onceClose sync.Once - closefn func() -} - -func (c *noteCloseConn) Close() error { - c.onceClose.Do(c.closefn) - return c.Conn.Close() -} - -func isTimeout(err error) bool { - switch err := err.(type) { - case nil: - return false - case *url.Error: - return isTimeout(err.Err) - case net.Error: - return err.Timeout() - } - return false -} - -// Test that the http1 Transport.ResponseHeaderTimeout option and cancel is sent. -func TestTransportResponseHeaderTimeout_NoBody(t *testing.T) { - testTransportResponseHeaderTimeout(t, false) -} -func TestTransportResponseHeaderTimeout_Body(t *testing.T) { - testTransportResponseHeaderTimeout(t, true) -} - -func testTransportResponseHeaderTimeout(t *testing.T, body bool) { - ct := newClientTester(t) - ct.tr.t1 = &http.Transport{ - ResponseHeaderTimeout: 5 * time.Millisecond, - } - ct.client = func() error { - c := &http.Client{Transport: ct.tr} - var err error - var n int64 - const bodySize = 4 << 20 - if body { - _, err = c.Post("https://dummy.tld/", "text/foo", io.LimitReader(countingReader{&n}, bodySize)) - } else { - _, err = c.Get("https://dummy.tld/") - } - if !isTimeout(err) { - t.Errorf("client expected timeout error; got %#v", err) - } - if body && n != bodySize { - t.Errorf("only read %d bytes of body; want %d", n, bodySize) - } - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err != nil { - t.Logf("ReadFrame: %v", err) - return nil - } - switch f := f.(type) { - case *DataFrame: - dataLen := len(f.Data()) - if dataLen > 0 { - if err := ct.fr.WriteWindowUpdate(0, uint32(dataLen)); err != nil { - return err - } - if err := ct.fr.WriteWindowUpdate(f.StreamID, uint32(dataLen)); err != nil { - return err - } - } - case *RSTStreamFrame: - if f.StreamID == 1 && f.ErrCode == ErrCodeCancel { - return nil - } - } - } - } - ct.run() -} - -func TestTransportDisableCompression(t *testing.T) { - const body = "sup" - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - want := http.Header{ - "User-Agent": []string{"Go-http-client/2.0"}, - } - if !reflect.DeepEqual(r.Header, want) { - t.Errorf("request headers = %v; want %v", r.Header, want) - } - }, optOnlyServer) - defer st.Close() - - tr := &Transport{ - TLSClientConfig: tlsConfigInsecure, - t1: &http.Transport{ - DisableCompression: true, - }, - } - defer tr.CloseIdleConnections() - - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal(err) - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - defer res.Body.Close() -} - -// RFC 7540 section 8.1.2.2 -func TestTransportRejectsConnHeaders(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - var got []string - for k := range r.Header { - got = append(got, k) - } - sort.Strings(got) - w.Header().Set("Got-Header", strings.Join(got, ",")) - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - tests := []struct { - key string - value []string - want string - }{ - { - key: "Upgrade", - value: []string{"anything"}, - want: "ERROR: http2: invalid Upgrade request header: [\"anything\"]", - }, - { - key: "Connection", - value: []string{"foo"}, - want: "ERROR: http2: invalid Connection request header: [\"foo\"]", - }, - { - key: "Connection", - value: []string{"close"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Connection", - value: []string{"close", "something-else"}, - want: "ERROR: http2: invalid Connection request header: [\"close\" \"something-else\"]", - }, - { - key: "Connection", - value: []string{"keep-alive"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Proxy-Connection", // just deleted and ignored - value: []string{"keep-alive"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Transfer-Encoding", - value: []string{""}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Transfer-Encoding", - value: []string{"foo"}, - want: "ERROR: http2: invalid Transfer-Encoding request header: [\"foo\"]", - }, - { - key: "Transfer-Encoding", - value: []string{"chunked"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Transfer-Encoding", - value: []string{"chunked", "other"}, - want: "ERROR: http2: invalid Transfer-Encoding request header: [\"chunked\" \"other\"]", - }, - { - key: "Content-Length", - value: []string{"123"}, - want: "Accept-Encoding,User-Agent", - }, - { - key: "Keep-Alive", - value: []string{"doop"}, - want: "Accept-Encoding,User-Agent", - }, - } - - for _, tt := range tests { - req, _ := http.NewRequest("GET", st.ts.URL, nil) - req.Header[tt.key] = tt.value - res, err := tr.RoundTrip(req) - var got string - if err != nil { - got = fmt.Sprintf("ERROR: %v", err) - } else { - got = res.Header.Get("Got-Header") - res.Body.Close() - } - if got != tt.want { - t.Errorf("For key %q, value %q, got = %q; want %q", tt.key, tt.value, got, tt.want) - } - } -} - -// golang.org/issue/14048 -func TestTransportFailsOnInvalidHeaders(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - var got []string - for k := range r.Header { - got = append(got, k) - } - sort.Strings(got) - w.Header().Set("Got-Header", strings.Join(got, ",")) - }, optOnlyServer) - defer st.Close() - - tests := [...]struct { - h http.Header - wantErr string - }{ - 0: { - h: http.Header{"with space": {"foo"}}, - wantErr: `invalid HTTP header name "with space"`, - }, - 1: { - h: http.Header{"name": {"Брэд"}}, - wantErr: "", // okay - }, - 2: { - h: http.Header{"имя": {"Brad"}}, - wantErr: `invalid HTTP header name "имя"`, - }, - 3: { - h: http.Header{"foo": {"foo\x01bar"}}, - wantErr: `invalid HTTP header value "foo\x01bar" for header "foo"`, - }, - } - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - for i, tt := range tests { - req, _ := http.NewRequest("GET", st.ts.URL, nil) - req.Header = tt.h - res, err := tr.RoundTrip(req) - var bad bool - if tt.wantErr == "" { - if err != nil { - bad = true - t.Errorf("case %d: error = %v; want no error", i, err) - } - } else { - if !strings.Contains(fmt.Sprint(err), tt.wantErr) { - bad = true - t.Errorf("case %d: error = %v; want error %q", i, err, tt.wantErr) - } - } - if err == nil { - if bad { - t.Logf("case %d: server got headers %q", i, res.Header.Get("Got-Header")) - } - res.Body.Close() - } - } -} - -// Tests that gzipReader doesn't crash on a second Read call following -// the first Read call's gzip.NewReader returning an error. -func TestGzipReader_DoubleReadCrash(t *testing.T) { - gz := &gzipReader{ - body: ioutil.NopCloser(strings.NewReader("0123456789")), - } - var buf [1]byte - n, err1 := gz.Read(buf[:]) - if n != 0 || !strings.Contains(fmt.Sprint(err1), "invalid header") { - t.Fatalf("Read = %v, %v; want 0, invalid header", n, err1) - } - n, err2 := gz.Read(buf[:]) - if n != 0 || err2 != err1 { - t.Fatalf("second Read = %v, %v; want 0, %v", n, err2, err1) - } -} - -func TestTransportNewTLSConfig(t *testing.T) { - tests := [...]struct { - conf *tls.Config - host string - want *tls.Config - }{ - // Normal case. - 0: { - conf: nil, - host: "foo.com", - want: &tls.Config{ - ServerName: "foo.com", - NextProtos: []string{NextProtoTLS}, - }, - }, - - // User-provided name (bar.com) takes precedence: - 1: { - conf: &tls.Config{ - ServerName: "bar.com", - }, - host: "foo.com", - want: &tls.Config{ - ServerName: "bar.com", - NextProtos: []string{NextProtoTLS}, - }, - }, - - // NextProto is prepended: - 2: { - conf: &tls.Config{ - NextProtos: []string{"foo", "bar"}, - }, - host: "example.com", - want: &tls.Config{ - ServerName: "example.com", - NextProtos: []string{NextProtoTLS, "foo", "bar"}, - }, - }, - - // NextProto is not duplicated: - 3: { - conf: &tls.Config{ - NextProtos: []string{"foo", "bar", NextProtoTLS}, - }, - host: "example.com", - want: &tls.Config{ - ServerName: "example.com", - NextProtos: []string{"foo", "bar", NextProtoTLS}, - }, - }, - } - for i, tt := range tests { - // Ignore the session ticket keys part, which ends up populating - // unexported fields in the Config: - if tt.conf != nil { - tt.conf.SessionTicketsDisabled = true - } - - tr := &Transport{TLSClientConfig: tt.conf} - got := tr.newTLSConfig(tt.host) - - got.SessionTicketsDisabled = false - - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("%d. got %#v; want %#v", i, got, tt.want) - } - } -} - -// The Google GFE responds to HEAD requests with a HEADERS frame -// without END_STREAM, followed by a 0-length DATA frame with -// END_STREAM. Make sure we don't get confused by that. (We did.) -func TestTransportReadHeadResponse(t *testing.T) { - ct := newClientTester(t) - clientDone := make(chan struct{}) - ct.client = func() error { - defer close(clientDone) - req, _ := http.NewRequest("HEAD", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return err - } - if res.ContentLength != 123 { - return fmt.Errorf("Content-Length = %d; want 123", res.ContentLength) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("ReadAll: %v", err) - } - if len(slurp) > 0 { - return fmt.Errorf("Unexpected non-empty ReadAll body: %q", slurp) - } - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err != nil { - t.Logf("ReadFrame: %v", err) - return nil - } - hf, ok := f.(*HeadersFrame) - if !ok { - continue - } - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "123"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, // as the GFE does - BlockFragment: buf.Bytes(), - }) - ct.fr.WriteData(hf.StreamID, true, nil) - - <-clientDone - return nil - } - } - ct.run() -} - -func TestTransportReadHeadResponseWithBody(t *testing.T) { - response := "redirecting to /elsewhere" - ct := newClientTester(t) - clientDone := make(chan struct{}) - ct.client = func() error { - defer close(clientDone) - req, _ := http.NewRequest("HEAD", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return err - } - if res.ContentLength != int64(len(response)) { - return fmt.Errorf("Content-Length = %d; want %d", res.ContentLength, len(response)) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("ReadAll: %v", err) - } - if len(slurp) > 0 { - return fmt.Errorf("Unexpected non-empty ReadAll body: %q", slurp) - } - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err != nil { - t.Logf("ReadFrame: %v", err) - return nil - } - hf, ok := f.(*HeadersFrame) - if !ok { - continue - } - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "content-length", Value: strconv.Itoa(len(response))}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - ct.fr.WriteData(hf.StreamID, true, []byte(response)) - - <-clientDone - return nil - } - } - ct.run() -} - -type neverEnding byte - -func (b neverEnding) Read(p []byte) (int, error) { - for i := range p { - p[i] = byte(b) - } - return len(p), nil -} - -// golang.org/issue/15425: test that a handler closing the request -// body doesn't terminate the stream to the peer. (It just stops -// readability from the handler's side, and eventually the client -// runs out of flow control tokens) -func TestTransportHandlerBodyClose(t *testing.T) { - const bodySize = 10 << 20 - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - r.Body.Close() - io.Copy(w, io.LimitReader(neverEnding('A'), bodySize)) - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - g0 := runtime.NumGoroutine() - - const numReq = 10 - for i := 0; i < numReq; i++ { - req, err := http.NewRequest("POST", st.ts.URL, struct{ io.Reader }{io.LimitReader(neverEnding('A'), bodySize)}) - if err != nil { - t.Fatal(err) - } - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - n, err := io.Copy(ioutil.Discard, res.Body) - res.Body.Close() - if n != bodySize || err != nil { - t.Fatalf("req#%d: Copy = %d, %v; want %d, nil", i, n, err, bodySize) - } - } - tr.CloseIdleConnections() - - gd := runtime.NumGoroutine() - g0 - if gd > numReq/2 { - t.Errorf("appeared to leak goroutines") - } - -} - -// https://golang.org/issue/15930 -func TestTransportFlowControl(t *testing.T) { - const bufLen = 64 << 10 - var total int64 = 100 << 20 // 100MB - if testing.Short() { - total = 10 << 20 - } - - var wrote int64 // updated atomically - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - b := make([]byte, bufLen) - for wrote < total { - n, err := w.Write(b) - atomic.AddInt64(&wrote, int64(n)) - if err != nil { - t.Errorf("ResponseWriter.Write error: %v", err) - break - } - w.(http.Flusher).Flush() - } - }, optOnlyServer) - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - t.Fatal("NewRequest error:", err) - } - resp, err := tr.RoundTrip(req) - if err != nil { - t.Fatal("RoundTrip error:", err) - } - defer resp.Body.Close() - - var read int64 - b := make([]byte, bufLen) - for { - n, err := resp.Body.Read(b) - if err == io.EOF { - break - } - if err != nil { - t.Fatal("Read error:", err) - } - read += int64(n) - - const max = transportDefaultStreamFlow - if w := atomic.LoadInt64(&wrote); -max > read-w || read-w > max { - t.Fatalf("Too much data inflight: server wrote %v bytes but client only received %v", w, read) - } - - // Let the server get ahead of the client. - time.Sleep(1 * time.Millisecond) - } -} - -// golang.org/issue/14627 -- if the server sends a GOAWAY frame, make -// the Transport remember it and return it back to users (via -// RoundTrip or request body reads) if needed (e.g. if the server -// proceeds to close the TCP connection before the client gets its -// response) -func TestTransportUsesGoAwayDebugError_RoundTrip(t *testing.T) { - testTransportUsesGoAwayDebugError(t, false) -} - -func TestTransportUsesGoAwayDebugError_Body(t *testing.T) { - testTransportUsesGoAwayDebugError(t, true) -} - -func testTransportUsesGoAwayDebugError(t *testing.T, failMidBody bool) { - ct := newClientTester(t) - clientDone := make(chan struct{}) - - const goAwayErrCode = ErrCodeHTTP11Required // arbitrary - const goAwayDebugData = "some debug data" - - ct.client = func() error { - defer close(clientDone) - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if failMidBody { - if err != nil { - return fmt.Errorf("unexpected client RoundTrip error: %v", err) - } - _, err = io.Copy(ioutil.Discard, res.Body) - res.Body.Close() - } - want := GoAwayError{ - LastStreamID: 5, - ErrCode: goAwayErrCode, - DebugData: goAwayDebugData, - } - if !reflect.DeepEqual(err, want) { - t.Errorf("RoundTrip error = %T: %#v, want %T (%#v)", err, err, want, want) - } - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err != nil { - t.Logf("ReadFrame: %v", err) - return nil - } - hf, ok := f.(*HeadersFrame) - if !ok { - continue - } - if failMidBody { - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "123"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - } - // Write two GOAWAY frames, to test that the Transport takes - // the interesting parts of both. - ct.fr.WriteGoAway(5, ErrCodeNo, []byte(goAwayDebugData)) - ct.fr.WriteGoAway(5, goAwayErrCode, nil) - ct.sc.(*net.TCPConn).CloseWrite() - <-clientDone - return nil - } - } - ct.run() -} - -func testTransportReturnsUnusedFlowControl(t *testing.T, oneDataFrame bool) { - ct := newClientTester(t) - - clientClosed := make(chan struct{}) - serverWroteFirstByte := make(chan struct{}) - - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return err - } - <-serverWroteFirstByte - - if n, err := res.Body.Read(make([]byte, 1)); err != nil || n != 1 { - return fmt.Errorf("body read = %v, %v; want 1, nil", n, err) - } - res.Body.Close() // leaving 4999 bytes unread - close(clientClosed) - - return nil - } - ct.server = func() error { - ct.greet() - - var hf *HeadersFrame - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) - } - switch f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - continue - } - var ok bool - hf, ok = f.(*HeadersFrame) - if !ok { - return fmt.Errorf("Got %T; want HeadersFrame", f) - } - break - } - - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "5000"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - - // Two cases: - // - Send one DATA frame with 5000 bytes. - // - Send two DATA frames with 1 and 4999 bytes each. - // - // In both cases, the client should consume one byte of data, - // refund that byte, then refund the following 4999 bytes. - // - // In the second case, the server waits for the client connection to - // close before seconding the second DATA frame. This tests the case - // where the client receives a DATA frame after it has reset the stream. - if oneDataFrame { - ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 5000)) - close(serverWroteFirstByte) - <-clientClosed - } else { - ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 1)) - close(serverWroteFirstByte) - <-clientClosed - ct.fr.WriteData(hf.StreamID, false /* don't end stream */, make([]byte, 4999)) - } - - waitingFor := "RSTStreamFrame" - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for %s: %v", waitingFor, err) - } - if _, ok := f.(*SettingsFrame); ok { - continue - } - switch waitingFor { - case "RSTStreamFrame": - if rf, ok := f.(*RSTStreamFrame); !ok || rf.ErrCode != ErrCodeCancel { - return fmt.Errorf("Expected a RSTStreamFrame with code cancel; got %v", summarizeFrame(f)) - } - waitingFor = "WindowUpdateFrame" - case "WindowUpdateFrame": - if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != 4999 { - return fmt.Errorf("Expected WindowUpdateFrame for 4999 bytes; got %v", summarizeFrame(f)) - } - return nil - } - } - } - ct.run() -} - -// See golang.org/issue/16481 -func TestTransportReturnsUnusedFlowControlSingleWrite(t *testing.T) { - testTransportReturnsUnusedFlowControl(t, true) -} - -// See golang.org/issue/20469 -func TestTransportReturnsUnusedFlowControlMultipleWrites(t *testing.T) { - testTransportReturnsUnusedFlowControl(t, false) -} - -// Issue 16612: adjust flow control on open streams when transport -// receives SETTINGS with INITIAL_WINDOW_SIZE from server. -func TestTransportAdjustsFlowControl(t *testing.T) { - ct := newClientTester(t) - clientDone := make(chan struct{}) - - const bodySize = 1 << 20 - - ct.client = func() error { - defer ct.cc.(*net.TCPConn).CloseWrite() - defer close(clientDone) - - req, _ := http.NewRequest("POST", "https://dummy.tld/", struct{ io.Reader }{io.LimitReader(neverEnding('A'), bodySize)}) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return err - } - res.Body.Close() - return nil - } - ct.server = func() error { - _, err := io.ReadFull(ct.sc, make([]byte, len(ClientPreface))) - if err != nil { - return fmt.Errorf("reading client preface: %v", err) - } - - var gotBytes int64 - var sentSettings bool - for { - f, err := ct.fr.ReadFrame() - if err != nil { - select { - case <-clientDone: - return nil - default: - return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) - } - } - switch f := f.(type) { - case *DataFrame: - gotBytes += int64(len(f.Data())) - // After we've got half the client's - // initial flow control window's worth - // of request body data, give it just - // enough flow control to finish. - if gotBytes >= initialWindowSize/2 && !sentSettings { - sentSettings = true - - ct.fr.WriteSettings(Setting{ID: SettingInitialWindowSize, Val: bodySize}) - ct.fr.WriteWindowUpdate(0, bodySize) - ct.fr.WriteSettingsAck() - } - - if f.StreamEnded() { - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - } - } - } - } - ct.run() -} - -// See golang.org/issue/16556 -func TestTransportReturnsDataPaddingFlowControl(t *testing.T) { - ct := newClientTester(t) - - unblockClient := make(chan bool, 1) - - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err != nil { - return err - } - defer res.Body.Close() - <-unblockClient - return nil - } - ct.server = func() error { - ct.greet() - - var hf *HeadersFrame - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) - } - switch f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - continue - } - var ok bool - hf, ok = f.(*HeadersFrame) - if !ok { - return fmt.Errorf("Got %T; want HeadersFrame", f) - } - break - } - - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "content-length", Value: "5000"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - pad := make([]byte, 5) - ct.fr.WriteDataPadded(hf.StreamID, false, make([]byte, 5000), pad) // without ending stream - - f, err := ct.readNonSettingsFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for first WindowUpdateFrame: %v", err) - } - wantBack := uint32(len(pad)) + 1 // one byte for the length of the padding - if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != wantBack || wuf.StreamID != 0 { - return fmt.Errorf("Expected conn WindowUpdateFrame for %d bytes; got %v", wantBack, summarizeFrame(f)) - } - - f, err = ct.readNonSettingsFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for second WindowUpdateFrame: %v", err) - } - if wuf, ok := f.(*WindowUpdateFrame); !ok || wuf.Increment != wantBack || wuf.StreamID == 0 { - return fmt.Errorf("Expected stream WindowUpdateFrame for %d bytes; got %v", wantBack, summarizeFrame(f)) - } - unblockClient <- true - return nil - } - ct.run() -} - -// golang.org/issue/16572 -- RoundTrip shouldn't hang when it gets a -// StreamError as a result of the response HEADERS -func TestTransportReturnsErrorOnBadResponseHeaders(t *testing.T) { - ct := newClientTester(t) - - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := ct.tr.RoundTrip(req) - if err == nil { - res.Body.Close() - return errors.New("unexpected successful GET") - } - want := StreamError{1, ErrCodeProtocol, headerFieldNameError(" content-type")} - if !reflect.DeepEqual(want, err) { - t.Errorf("RoundTrip error = %#v; want %#v", err, want) - } - return nil - } - ct.server = func() error { - ct.greet() - - hf, err := ct.firstHeaders() - if err != nil { - return err - } - - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: " content-type", Value: "bogus"}) // bogus spaces - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - - for { - fr, err := ct.readFrame() - if err != nil { - return fmt.Errorf("error waiting for RST_STREAM from client: %v", err) - } - if _, ok := fr.(*SettingsFrame); ok { - continue - } - if rst, ok := fr.(*RSTStreamFrame); !ok || rst.StreamID != 1 || rst.ErrCode != ErrCodeProtocol { - t.Errorf("Frame = %v; want RST_STREAM for stream 1 with ErrCodeProtocol", summarizeFrame(fr)) - } - break - } - - return nil - } - ct.run() -} - -// byteAndEOFReader returns is in an io.Reader which reads one byte -// (the underlying byte) and io.EOF at once in its Read call. -type byteAndEOFReader byte - -func (b byteAndEOFReader) Read(p []byte) (n int, err error) { - if len(p) == 0 { - panic("unexpected useless call") - } - p[0] = byte(b) - return 1, io.EOF -} - -// Issue 16788: the Transport had a regression where it started -// sending a spurious DATA frame with a duplicate END_STREAM bit after -// the request body writer goroutine had already read an EOF from the -// Request.Body and included the END_STREAM on a data-carrying DATA -// frame. -// -// Notably, to trigger this, the requests need to use a Request.Body -// which returns (non-0, io.EOF) and also needs to set the ContentLength -// explicitly. -func TestTransportBodyDoubleEndStream(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - // Nothing. - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - for i := 0; i < 2; i++ { - req, _ := http.NewRequest("POST", st.ts.URL, byteAndEOFReader('a')) - req.ContentLength = 1 - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatalf("failure on req %d: %v", i+1, err) - } - defer res.Body.Close() - } -} - -// golang.org/issue/16847, golang.org/issue/19103 -func TestTransportRequestPathPseudo(t *testing.T) { - type result struct { - path string - err string - } - tests := []struct { - req *http.Request - want result - }{ - 0: { - req: &http.Request{ - Method: "GET", - URL: &url.URL{ - Host: "foo.com", - Path: "/foo", - }, - }, - want: result{path: "/foo"}, - }, - // In Go 1.7, we accepted paths of "//foo". - // In Go 1.8, we rejected it (issue 16847). - // In Go 1.9, we accepted it again (issue 19103). - 1: { - req: &http.Request{ - Method: "GET", - URL: &url.URL{ - Host: "foo.com", - Path: "//foo", - }, - }, - want: result{path: "//foo"}, - }, - - // Opaque with //$Matching_Hostname/path - 2: { - req: &http.Request{ - Method: "GET", - URL: &url.URL{ - Scheme: "https", - Opaque: "//foo.com/path", - Host: "foo.com", - Path: "/ignored", - }, - }, - want: result{path: "/path"}, - }, - - // Opaque with some other Request.Host instead: - 3: { - req: &http.Request{ - Method: "GET", - Host: "bar.com", - URL: &url.URL{ - Scheme: "https", - Opaque: "//bar.com/path", - Host: "foo.com", - Path: "/ignored", - }, - }, - want: result{path: "/path"}, - }, - - // Opaque without the leading "//": - 4: { - req: &http.Request{ - Method: "GET", - URL: &url.URL{ - Opaque: "/path", - Host: "foo.com", - Path: "/ignored", - }, - }, - want: result{path: "/path"}, - }, - - // Opaque we can't handle: - 5: { - req: &http.Request{ - Method: "GET", - URL: &url.URL{ - Scheme: "https", - Opaque: "//unknown_host/path", - Host: "foo.com", - Path: "/ignored", - }, - }, - want: result{err: `invalid request :path "https://unknown_host/path" from URL.Opaque = "//unknown_host/path"`}, - }, - - // A CONNECT request: - 6: { - req: &http.Request{ - Method: "CONNECT", - URL: &url.URL{ - Host: "foo.com", - }, - }, - want: result{}, - }, - } - for i, tt := range tests { - cc := &ClientConn{peerMaxHeaderListSize: 0xffffffffffffffff} - cc.henc = hpack.NewEncoder(&cc.hbuf) - cc.mu.Lock() - hdrs, err := cc.encodeHeaders(tt.req, false, "", -1) - cc.mu.Unlock() - var got result - hpackDec := hpack.NewDecoder(initialHeaderTableSize, func(f hpack.HeaderField) { - if f.Name == ":path" { - got.path = f.Value - } - }) - if err != nil { - got.err = err.Error() - } else if len(hdrs) > 0 { - if _, err := hpackDec.Write(hdrs); err != nil { - t.Errorf("%d. bogus hpack: %v", i, err) - continue - } - } - if got != tt.want { - t.Errorf("%d. got %+v; want %+v", i, got, tt.want) - } - - } - -} - -// golang.org/issue/17071 -- don't sniff the first byte of the request body -// before we've determined that the ClientConn is usable. -func TestRoundTripDoesntConsumeRequestBodyEarly(t *testing.T) { - const body = "foo" - req, _ := http.NewRequest("POST", "http://foo.com/", ioutil.NopCloser(strings.NewReader(body))) - cc := &ClientConn{ - closed: true, - } - _, err := cc.RoundTrip(req) - if err != errClientConnUnusable { - t.Fatalf("RoundTrip = %v; want errClientConnUnusable", err) - } - slurp, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Errorf("ReadAll = %v", err) - } - if string(slurp) != body { - t.Errorf("Body = %q; want %q", slurp, body) - } -} - -func TestClientConnPing(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}, optOnlyServer) - defer st.Close() - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - cc, err := tr.dialClientConn(st.ts.Listener.Addr().String(), false) - if err != nil { - t.Fatal(err) - } - if err = cc.Ping(testContext{}); err != nil { - t.Fatal(err) - } -} - -// Issue 16974: if the server sent a DATA frame after the user -// canceled the Transport's Request, the Transport previously wrote to a -// closed pipe, got an error, and ended up closing the whole TCP -// connection. -func TestTransportCancelDataResponseRace(t *testing.T) { - cancel := make(chan struct{}) - clientGotError := make(chan bool, 1) - - const msg = "Hello." - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - if strings.Contains(r.URL.Path, "/hello") { - time.Sleep(50 * time.Millisecond) - io.WriteString(w, msg) - return - } - for i := 0; i < 50; i++ { - io.WriteString(w, "Some data.") - w.(http.Flusher).Flush() - if i == 2 { - close(cancel) - <-clientGotError - } - time.Sleep(10 * time.Millisecond) - } - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - c := &http.Client{Transport: tr} - req, _ := http.NewRequest("GET", st.ts.URL, nil) - req.Cancel = cancel - res, err := c.Do(req) - if err != nil { - t.Fatal(err) - } - if _, err = io.Copy(ioutil.Discard, res.Body); err == nil { - t.Fatal("unexpected success") - } - clientGotError <- true - - res, err = c.Get(st.ts.URL + "/hello") - if err != nil { - t.Fatal(err) - } - slurp, err := ioutil.ReadAll(res.Body) - if err != nil { - t.Fatal(err) - } - if string(slurp) != msg { - t.Errorf("Got = %q; want %q", slurp, msg) - } -} - -// Issue 21316: It should be safe to reuse an http.Request after the -// request has completed. -func TestTransportNoRaceOnRequestObjectAfterRequestComplete(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(200) - io.WriteString(w, "body") - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - req, _ := http.NewRequest("GET", st.ts.URL, nil) - resp, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - if _, err = io.Copy(ioutil.Discard, resp.Body); err != nil { - t.Fatalf("error reading response body: %v", err) - } - if err := resp.Body.Close(); err != nil { - t.Fatalf("error closing response body: %v", err) - } - - // This access of req.Header should not race with code in the transport. - req.Header = http.Header{} -} - -func TestTransportRetryAfterGOAWAY(t *testing.T) { - var dialer struct { - sync.Mutex - count int - } - ct1 := make(chan *clientTester) - ct2 := make(chan *clientTester) - - ln := newLocalListener(t) - defer ln.Close() - - tr := &Transport{ - TLSClientConfig: tlsConfigInsecure, - } - tr.DialTLS = func(network, addr string, cfg *tls.Config) (net.Conn, error) { - dialer.Lock() - defer dialer.Unlock() - dialer.count++ - if dialer.count == 3 { - return nil, errors.New("unexpected number of dials") - } - cc, err := net.Dial("tcp", ln.Addr().String()) - if err != nil { - return nil, fmt.Errorf("dial error: %v", err) - } - sc, err := ln.Accept() - if err != nil { - return nil, fmt.Errorf("accept error: %v", err) - } - ct := &clientTester{ - t: t, - tr: tr, - cc: cc, - sc: sc, - fr: NewFramer(sc, sc), - } - switch dialer.count { - case 1: - ct1 <- ct - case 2: - ct2 <- ct - } - return cc, nil - } - - errs := make(chan error, 3) - done := make(chan struct{}) - defer close(done) - - // Client. - go func() { - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - res, err := tr.RoundTrip(req) - if res != nil { - res.Body.Close() - if got := res.Header.Get("Foo"); got != "bar" { - err = fmt.Errorf("foo header = %q; want bar", got) - } - } - if err != nil { - err = fmt.Errorf("RoundTrip: %v", err) - } - errs <- err - }() - - connToClose := make(chan io.Closer, 2) - - // Server for the first request. - go func() { - var ct *clientTester - select { - case ct = <-ct1: - case <-done: - return - } - - connToClose <- ct.cc - ct.greet() - hf, err := ct.firstHeaders() - if err != nil { - errs <- fmt.Errorf("server1 failed reading HEADERS: %v", err) - return - } - t.Logf("server1 got %v", hf) - if err := ct.fr.WriteGoAway(0 /*max id*/, ErrCodeNo, nil); err != nil { - errs <- fmt.Errorf("server1 failed writing GOAWAY: %v", err) - return - } - errs <- nil - }() - - // Server for the second request. - go func() { - var ct *clientTester - select { - case ct = <-ct2: - case <-done: - return - } - - connToClose <- ct.cc - ct.greet() - hf, err := ct.firstHeaders() - if err != nil { - errs <- fmt.Errorf("server2 failed reading HEADERS: %v", err) - return - } - t.Logf("server2 got %v", hf) - - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - enc.WriteField(hpack.HeaderField{Name: "foo", Value: "bar"}) - err = ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: hf.StreamID, - EndHeaders: true, - EndStream: false, - BlockFragment: buf.Bytes(), - }) - if err != nil { - errs <- fmt.Errorf("server2 failed writing response HEADERS: %v", err) - } else { - errs <- nil - } - }() - - for k := 0; k < 3; k++ { - select { - case err := <-errs: - if err != nil { - t.Error(err) - } - case <-time.After(1 * time.Second): - t.Errorf("timed out") - } - } - - for { - select { - case c := <-connToClose: - c.Close() - default: - return - } - } -} - -func TestTransportRetryAfterRefusedStream(t *testing.T) { - clientDone := make(chan struct{}) - ct := newClientTester(t) - ct.client = func() error { - defer ct.cc.(*net.TCPConn).CloseWrite() - defer close(clientDone) - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - resp, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip: %v", err) - } - resp.Body.Close() - if resp.StatusCode != 204 { - return fmt.Errorf("Status = %v; want 204", resp.StatusCode) - } - return nil - } - ct.server = func() error { - ct.greet() - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - nreq := 0 - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - select { - case <-clientDone: - // If the client's done, it - // will have reported any - // errors on its side. - return nil - default: - return err - } - } - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *HeadersFrame: - if !f.HeadersEnded() { - return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) - } - nreq++ - if nreq == 1 { - ct.fr.WriteRSTStream(f.StreamID, ErrCodeRefusedStream) - } else { - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "204"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - } - default: - return fmt.Errorf("Unexpected client frame %v", f) - } - } - } - ct.run() -} - -func TestTransportRetryHasLimit(t *testing.T) { - // Skip in short mode because the total expected delay is 1s+2s+4s+8s+16s=29s. - if testing.Short() { - t.Skip("skipping long test in short mode") - } - clientDone := make(chan struct{}) - ct := newClientTester(t) - ct.client = func() error { - defer ct.cc.(*net.TCPConn).CloseWrite() - defer close(clientDone) - req, _ := http.NewRequest("GET", "https://dummy.tld/", nil) - resp, err := ct.tr.RoundTrip(req) - if err == nil { - return fmt.Errorf("RoundTrip expected error, got response: %+v", resp) - } - t.Logf("expected error, got: %v", err) - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err != nil { - select { - case <-clientDone: - // If the client's done, it - // will have reported any - // errors on its side. - return nil - default: - return err - } - } - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *HeadersFrame: - if !f.HeadersEnded() { - return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) - } - ct.fr.WriteRSTStream(f.StreamID, ErrCodeRefusedStream) - default: - return fmt.Errorf("Unexpected client frame %v", f) - } - } - } - ct.run() -} - -func TestTransportResponseDataBeforeHeaders(t *testing.T) { - ct := newClientTester(t) - ct.client = func() error { - defer ct.cc.(*net.TCPConn).CloseWrite() - req := httptest.NewRequest("GET", "https://dummy.tld/", nil) - // First request is normal to ensure the check is per stream and not per connection. - _, err := ct.tr.RoundTrip(req) - if err != nil { - return fmt.Errorf("RoundTrip expected no error, got: %v", err) - } - // Second request returns a DATA frame with no HEADERS. - resp, err := ct.tr.RoundTrip(req) - if err == nil { - return fmt.Errorf("RoundTrip expected error, got response: %+v", resp) - } - if err, ok := err.(StreamError); !ok || err.Code != ErrCodeProtocol { - return fmt.Errorf("expected stream PROTOCOL_ERROR, got: %v", err) - } - return nil - } - ct.server = func() error { - ct.greet() - for { - f, err := ct.fr.ReadFrame() - if err == io.EOF { - return nil - } else if err != nil { - return err - } - switch f := f.(type) { - case *WindowUpdateFrame, *SettingsFrame: - case *HeadersFrame: - switch f.StreamID { - case 1: - // Send a valid response to first request. - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "200"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: f.StreamID, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - case 3: - ct.fr.WriteData(f.StreamID, true, []byte("payload")) - } - default: - return fmt.Errorf("Unexpected client frame %v", f) - } - } - } - ct.run() -} -func TestTransportRequestsStallAtServerLimit(t *testing.T) { - const maxConcurrent = 2 - - greet := make(chan struct{}) // server sends initial SETTINGS frame - gotRequest := make(chan struct{}) // server received a request - clientDone := make(chan struct{}) - - // Collect errors from goroutines. - var wg sync.WaitGroup - errs := make(chan error, 100) - defer func() { - wg.Wait() - close(errs) - for err := range errs { - t.Error(err) - } - }() - - // We will send maxConcurrent+2 requests. This checker goroutine waits for the - // following stages: - // 1. The first maxConcurrent requests are received by the server. - // 2. The client will cancel the next request - // 3. The server is unblocked so it can service the first maxConcurrent requests - // 4. The client will send the final request - wg.Add(1) - unblockClient := make(chan struct{}) - clientRequestCancelled := make(chan struct{}) - unblockServer := make(chan struct{}) - go func() { - defer wg.Done() - // Stage 1. - for k := 0; k < maxConcurrent; k++ { - <-gotRequest - } - // Stage 2. - close(unblockClient) - <-clientRequestCancelled - // Stage 3: give some time for the final RoundTrip call to be scheduled and - // verify that the final request is not sent. - time.Sleep(50 * time.Millisecond) - select { - case <-gotRequest: - errs <- errors.New("last request did not stall") - close(unblockServer) - return - default: - } - close(unblockServer) - // Stage 4. - <-gotRequest - }() - - ct := newClientTester(t) - ct.client = func() error { - var wg sync.WaitGroup - defer func() { - wg.Wait() - close(clientDone) - ct.cc.(*net.TCPConn).CloseWrite() - }() - for k := 0; k < maxConcurrent+2; k++ { - wg.Add(1) - go func(k int) { - defer wg.Done() - // Don't send the second request until after receiving SETTINGS from the server - // to avoid a race where we use the default SettingMaxConcurrentStreams, which - // is much larger than maxConcurrent. We have to send the first request before - // waiting because the first request triggers the dial and greet. - if k > 0 { - <-greet - } - // Block until maxConcurrent requests are sent before sending any more. - if k >= maxConcurrent { - <-unblockClient - } - req, _ := http.NewRequest("GET", fmt.Sprintf("https://dummy.tld/%d", k), nil) - if k == maxConcurrent { - // This request will be canceled. - cancel := make(chan struct{}) - req.Cancel = cancel - close(cancel) - _, err := ct.tr.RoundTrip(req) - close(clientRequestCancelled) - if err == nil { - errs <- fmt.Errorf("RoundTrip(%d) should have failed due to cancel", k) - return - } - } else { - resp, err := ct.tr.RoundTrip(req) - if err != nil { - errs <- fmt.Errorf("RoundTrip(%d): %v", k, err) - return - } - ioutil.ReadAll(resp.Body) - resp.Body.Close() - if resp.StatusCode != 204 { - errs <- fmt.Errorf("Status = %v; want 204", resp.StatusCode) - return - } - } - }(k) - } - return nil - } - - ct.server = func() error { - var wg sync.WaitGroup - defer wg.Wait() - - ct.greet(Setting{SettingMaxConcurrentStreams, maxConcurrent}) - - // Server write loop. - var buf bytes.Buffer - enc := hpack.NewEncoder(&buf) - writeResp := make(chan uint32, maxConcurrent+1) - - wg.Add(1) - go func() { - defer wg.Done() - <-unblockServer - for id := range writeResp { - buf.Reset() - enc.WriteField(hpack.HeaderField{Name: ":status", Value: "204"}) - ct.fr.WriteHeaders(HeadersFrameParam{ - StreamID: id, - EndHeaders: true, - EndStream: true, - BlockFragment: buf.Bytes(), - }) - } - }() - - // Server read loop. - var nreq int - for { - f, err := ct.fr.ReadFrame() - if err != nil { - select { - case <-clientDone: - // If the client's done, it will have reported any errors on its side. - return nil - default: - return err - } - } - switch f := f.(type) { - case *WindowUpdateFrame: - case *SettingsFrame: - // Wait for the client SETTINGS ack until ending the greet. - close(greet) - case *HeadersFrame: - if !f.HeadersEnded() { - return fmt.Errorf("headers should have END_HEADERS be ended: %v", f) - } - gotRequest <- struct{}{} - nreq++ - writeResp <- f.StreamID - if nreq == maxConcurrent+1 { - close(writeResp) - } - default: - return fmt.Errorf("Unexpected client frame %v", f) - } - } - } - - ct.run() -} - -func TestAuthorityAddr(t *testing.T) { - tests := []struct { - scheme, authority string - want string - }{ - {"http", "foo.com", "foo.com:80"}, - {"https", "foo.com", "foo.com:443"}, - {"https", "foo.com:1234", "foo.com:1234"}, - {"https", "1.2.3.4:1234", "1.2.3.4:1234"}, - {"https", "1.2.3.4", "1.2.3.4:443"}, - {"https", "[::1]:1234", "[::1]:1234"}, - {"https", "[::1]", "[::1]:443"}, - } - for _, tt := range tests { - got := authorityAddr(tt.scheme, tt.authority) - if got != tt.want { - t.Errorf("authorityAddr(%q, %q) = %q; want %q", tt.scheme, tt.authority, got, tt.want) - } - } -} - -// Issue 20448: stop allocating for DATA frames' payload after -// Response.Body.Close is called. -func TestTransportAllocationsAfterResponseBodyClose(t *testing.T) { - megabyteZero := make([]byte, 1<<20) - - writeErr := make(chan error, 1) - - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.(http.Flusher).Flush() - var sum int64 - for i := 0; i < 100; i++ { - n, err := w.Write(megabyteZero) - sum += int64(n) - if err != nil { - writeErr <- err - return - } - } - t.Logf("wrote all %d bytes", sum) - writeErr <- nil - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - c := &http.Client{Transport: tr} - res, err := c.Get(st.ts.URL) - if err != nil { - t.Fatal(err) - } - var buf [1]byte - if _, err := res.Body.Read(buf[:]); err != nil { - t.Error(err) - } - if err := res.Body.Close(); err != nil { - t.Error(err) - } - - trb, ok := res.Body.(transportResponseBody) - if !ok { - t.Fatalf("res.Body = %T; want transportResponseBody", res.Body) - } - if trb.cs.bufPipe.b != nil { - t.Errorf("response body pipe is still open") - } - - gotErr := <-writeErr - if gotErr == nil { - t.Errorf("Handler unexpectedly managed to write its entire response without getting an error") - } else if gotErr != errStreamClosed { - t.Errorf("Handler Write err = %v; want errStreamClosed", gotErr) - } -} - -// Issue 18891: make sure Request.Body == NoBody means no DATA frame -// is ever sent, even if empty. -func TestTransportNoBodyMeansNoDATA(t *testing.T) { - ct := newClientTester(t) - - unblockClient := make(chan bool) - - ct.client = func() error { - req, _ := http.NewRequest("GET", "https://dummy.tld/", go18httpNoBody()) - ct.tr.RoundTrip(req) - <-unblockClient - return nil - } - ct.server = func() error { - defer close(unblockClient) - defer ct.cc.(*net.TCPConn).Close() - ct.greet() - - for { - f, err := ct.fr.ReadFrame() - if err != nil { - return fmt.Errorf("ReadFrame while waiting for Headers: %v", err) - } - switch f := f.(type) { - default: - return fmt.Errorf("Got %T; want HeadersFrame", f) - case *WindowUpdateFrame, *SettingsFrame: - continue - case *HeadersFrame: - if !f.StreamEnded() { - return fmt.Errorf("got headers frame without END_STREAM") - } - return nil - } - } - } - ct.run() -} - -func benchSimpleRoundTrip(b *testing.B, nHeaders int) { - defer disableGoroutineTracking()() - b.ReportAllocs() - st := newServerTester(b, - func(w http.ResponseWriter, r *http.Request) { - }, - optOnlyServer, - optQuiet, - ) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - req, err := http.NewRequest("GET", st.ts.URL, nil) - if err != nil { - b.Fatal(err) - } - - for i := 0; i < nHeaders; i++ { - name := fmt.Sprint("A-", i) - req.Header.Set(name, "*") - } - - b.ResetTimer() - - for i := 0; i < b.N; i++ { - res, err := tr.RoundTrip(req) - if err != nil { - if res != nil { - res.Body.Close() - } - b.Fatalf("RoundTrip err = %v; want nil", err) - } - res.Body.Close() - if res.StatusCode != http.StatusOK { - b.Fatalf("Response code = %v; want %v", res.StatusCode, http.StatusOK) - } - } -} - -type infiniteReader struct{} - -func (r infiniteReader) Read(b []byte) (int, error) { - return len(b), nil -} - -// Issue 20521: it is not an error to receive a response and end stream -// from the server without the body being consumed. -func TestTransportResponseAndResetWithoutConsumingBodyRace(t *testing.T) { - st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusOK) - }, optOnlyServer) - defer st.Close() - - tr := &Transport{TLSClientConfig: tlsConfigInsecure} - defer tr.CloseIdleConnections() - - // The request body needs to be big enough to trigger flow control. - req, _ := http.NewRequest("PUT", st.ts.URL, infiniteReader{}) - res, err := tr.RoundTrip(req) - if err != nil { - t.Fatal(err) - } - if res.StatusCode != http.StatusOK { - t.Fatalf("Response code = %v; want %v", res.StatusCode, http.StatusOK) - } -} - -func BenchmarkClientRequestHeaders(b *testing.B) { - b.Run(" 0 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 0) }) - b.Run(" 10 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 10) }) - b.Run(" 100 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 100) }) - b.Run("1000 Headers", func(b *testing.B) { benchSimpleRoundTrip(b, 1000) }) -} diff --git a/vendor/golang.org/x/net/http2/write.go b/vendor/golang.org/x/net/http2/write.go index 54ab4a88e7..a5120412e6 100644 --- a/vendor/golang.org/x/net/http2/write.go +++ b/vendor/golang.org/x/net/http2/write.go @@ -11,8 +11,8 @@ import ( "net/http" "net/url" + "golang.org/x/net/http/httpguts" "golang.org/x/net/http2/hpack" - "golang.org/x/net/lex/httplex" ) // writeFramer is implemented by any type that is used to write frames. @@ -186,6 +186,7 @@ type writeResHeaders struct { date string contentType string contentLength string + noSniff bool } func encKV(enc *hpack.Encoder, k, v string) { @@ -222,6 +223,9 @@ func (w *writeResHeaders) writeFrame(ctx writeContext) error { if w.contentLength != "" { encKV(enc, "content-length", w.contentLength) } + if w.noSniff { + encKV(enc, "x-content-type-options", "nosniff") + } if w.date != "" { encKV(enc, "date", w.date) } @@ -350,7 +354,7 @@ func encodeHeaders(enc *hpack.Encoder, h http.Header, keys []string) { } isTE := k == "transfer-encoding" for _, v := range vv { - if !httplex.ValidHeaderFieldValue(v) { + if !httpguts.ValidHeaderFieldValue(v) { // TODO: return an error? golang.org/issue/14048 // For now just omit it. continue diff --git a/vendor/golang.org/x/net/http2/writesched_priority_test.go b/vendor/golang.org/x/net/http2/writesched_priority_test.go deleted file mode 100644 index f2b535a2c6..0000000000 --- a/vendor/golang.org/x/net/http2/writesched_priority_test.go +++ /dev/null @@ -1,541 +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 http2 - -import ( - "bytes" - "fmt" - "sort" - "testing" -) - -func defaultPriorityWriteScheduler() *priorityWriteScheduler { - return NewPriorityWriteScheduler(nil).(*priorityWriteScheduler) -} - -func checkPriorityWellFormed(ws *priorityWriteScheduler) error { - for id, n := range ws.nodes { - if id != n.id { - return fmt.Errorf("bad ws.nodes: ws.nodes[%d] = %d", id, n.id) - } - if n.parent == nil { - if n.next != nil || n.prev != nil { - return fmt.Errorf("bad node %d: nil parent but prev/next not nil", id) - } - continue - } - found := false - for k := n.parent.kids; k != nil; k = k.next { - if k.id == id { - found = true - break - } - } - if !found { - return fmt.Errorf("bad node %d: not found in parent %d kids list", id, n.parent.id) - } - } - return nil -} - -func fmtTree(ws *priorityWriteScheduler, fmtNode func(*priorityNode) string) string { - var ids []int - for _, n := range ws.nodes { - ids = append(ids, int(n.id)) - } - sort.Ints(ids) - - var buf bytes.Buffer - for _, id := range ids { - if buf.Len() != 0 { - buf.WriteString(" ") - } - if id == 0 { - buf.WriteString(fmtNode(&ws.root)) - } else { - buf.WriteString(fmtNode(ws.nodes[uint32(id)])) - } - } - return buf.String() -} - -func fmtNodeParentSkipRoot(n *priorityNode) string { - switch { - case n.id == 0: - return "" - case n.parent == nil: - return fmt.Sprintf("%d{parent:nil}", n.id) - default: - return fmt.Sprintf("%d{parent:%d}", n.id, n.parent.id) - } -} - -func fmtNodeWeightParentSkipRoot(n *priorityNode) string { - switch { - case n.id == 0: - return "" - case n.parent == nil: - return fmt.Sprintf("%d{weight:%d,parent:nil}", n.id, n.weight) - default: - return fmt.Sprintf("%d{weight:%d,parent:%d}", n.id, n.weight, n.parent.id) - } -} - -func TestPriorityTwoStreams(t *testing.T) { - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{}) - - want := "1{weight:15,parent:0} 2{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After open\ngot %q\nwant %q", got, want) - } - - // Move 1's parent to 2. - ws.AdjustStream(1, PriorityParam{ - StreamDep: 2, - Weight: 32, - Exclusive: false, - }) - want = "1{weight:32,parent:2} 2{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityAdjustExclusiveZero(t *testing.T) { - // 1, 2, and 3 are all children of the 0 stream. - // Exclusive reprioritization to any of the streams should bring - // the rest of the streams under the reprioritized stream. - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{}) - ws.OpenStream(3, OpenStreamOptions{}) - - want := "1{weight:15,parent:0} 2{weight:15,parent:0} 3{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After open\ngot %q\nwant %q", got, want) - } - - ws.AdjustStream(2, PriorityParam{ - StreamDep: 0, - Weight: 20, - Exclusive: true, - }) - want = "1{weight:15,parent:2} 2{weight:20,parent:0} 3{weight:15,parent:2}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityAdjustOwnParent(t *testing.T) { - // Assigning a node as its own parent should have no effect. - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{}) - ws.AdjustStream(2, PriorityParam{ - StreamDep: 2, - Weight: 20, - Exclusive: true, - }) - want := "1{weight:15,parent:0} 2{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityClosedStreams(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{MaxClosedNodesInTree: 2}).(*priorityWriteScheduler) - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 2}) - ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) - - // Close the first three streams. We lose 1, but keep 2 and 3. - ws.CloseStream(1) - ws.CloseStream(2) - ws.CloseStream(3) - - want := "2{weight:15,parent:0} 3{weight:15,parent:2} 4{weight:15,parent:3}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After close\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } - - // Adding a stream as an exclusive child of 1 gives it default - // priorities, since 1 is gone. - ws.OpenStream(5, OpenStreamOptions{}) - ws.AdjustStream(5, PriorityParam{StreamDep: 1, Weight: 15, Exclusive: true}) - - // Adding a stream as an exclusive child of 2 should work, since 2 is not gone. - ws.OpenStream(6, OpenStreamOptions{}) - ws.AdjustStream(6, PriorityParam{StreamDep: 2, Weight: 15, Exclusive: true}) - - want = "2{weight:15,parent:0} 3{weight:15,parent:6} 4{weight:15,parent:3} 5{weight:15,parent:0} 6{weight:15,parent:2}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After add streams\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityClosedStreamsDisabled(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{}).(*priorityWriteScheduler) - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 2}) - - // Close the first two streams. We keep only 3. - ws.CloseStream(1) - ws.CloseStream(2) - - want := "3{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After close\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityIdleStreams(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{MaxIdleNodesInTree: 2}).(*priorityWriteScheduler) - ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 15}) // idle - ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 15}) // idle - ws.AdjustStream(3, PriorityParam{StreamDep: 2, Weight: 20}) // idle - ws.OpenStream(4, OpenStreamOptions{}) - ws.OpenStream(5, OpenStreamOptions{}) - ws.OpenStream(6, OpenStreamOptions{}) - ws.AdjustStream(4, PriorityParam{StreamDep: 1, Weight: 15}) - ws.AdjustStream(5, PriorityParam{StreamDep: 2, Weight: 15}) - ws.AdjustStream(6, PriorityParam{StreamDep: 3, Weight: 15}) - - want := "2{weight:15,parent:0} 3{weight:20,parent:2} 4{weight:15,parent:0} 5{weight:15,parent:2} 6{weight:15,parent:3}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After open\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPriorityIdleStreamsDisabled(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{}).(*priorityWriteScheduler) - ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 15}) // idle - ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 15}) // idle - ws.AdjustStream(3, PriorityParam{StreamDep: 2, Weight: 20}) // idle - ws.OpenStream(4, OpenStreamOptions{}) - - want := "4{weight:15,parent:0}" - if got := fmtTree(ws, fmtNodeWeightParentSkipRoot); got != want { - t.Errorf("After open\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPrioritySection531NonExclusive(t *testing.T) { - // Example from RFC 7540 Section 5.3.1. - // A,B,C,D = 1,2,3,4 - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(4, OpenStreamOptions{}) - ws.AdjustStream(4, PriorityParam{ - StreamDep: 1, - Weight: 15, - Exclusive: false, - }) - want := "1{parent:0} 2{parent:1} 3{parent:1} 4{parent:1}" - if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPrioritySection531Exclusive(t *testing.T) { - // Example from RFC 7540 Section 5.3.1. - // A,B,C,D = 1,2,3,4 - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(4, OpenStreamOptions{}) - ws.AdjustStream(4, PriorityParam{ - StreamDep: 1, - Weight: 15, - Exclusive: true, - }) - want := "1{parent:0} 2{parent:4} 3{parent:4} 4{parent:1}" - if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func makeSection533Tree() *priorityWriteScheduler { - // Initial tree from RFC 7540 Section 5.3.3. - // A,B,C,D,E,F = 1,2,3,4,5,6 - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(5, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(6, OpenStreamOptions{PusherID: 4}) - return ws -} - -func TestPrioritySection533NonExclusive(t *testing.T) { - // Example from RFC 7540 Section 5.3.3. - // A,B,C,D,E,F = 1,2,3,4,5,6 - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(5, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(6, OpenStreamOptions{PusherID: 4}) - ws.AdjustStream(1, PriorityParam{ - StreamDep: 4, - Weight: 15, - Exclusive: false, - }) - want := "1{parent:4} 2{parent:1} 3{parent:1} 4{parent:0} 5{parent:3} 6{parent:4}" - if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func TestPrioritySection533Exclusive(t *testing.T) { - // Example from RFC 7540 Section 5.3.3. - // A,B,C,D,E,F = 1,2,3,4,5,6 - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(5, OpenStreamOptions{PusherID: 3}) - ws.OpenStream(6, OpenStreamOptions{PusherID: 4}) - ws.AdjustStream(1, PriorityParam{ - StreamDep: 4, - Weight: 15, - Exclusive: true, - }) - want := "1{parent:4} 2{parent:1} 3{parent:1} 4{parent:0} 5{parent:3} 6{parent:1}" - if got := fmtTree(ws, fmtNodeParentSkipRoot); got != want { - t.Errorf("After adjust\ngot %q\nwant %q", got, want) - } - if err := checkPriorityWellFormed(ws); err != nil { - t.Error(err) - } -} - -func checkPopAll(ws WriteScheduler, order []uint32) error { - for k, id := range order { - wr, ok := ws.Pop() - if !ok { - return fmt.Errorf("Pop[%d]: got ok=false, want %d (order=%v)", k, id, order) - } - if got := wr.StreamID(); got != id { - return fmt.Errorf("Pop[%d]: got %v, want %d (order=%v)", k, got, id, order) - } - } - wr, ok := ws.Pop() - if ok { - return fmt.Errorf("Pop[%d]: got %v, want ok=false (order=%v)", len(order), wr.StreamID(), order) - } - return nil -} - -func TestPriorityPopFrom533Tree(t *testing.T) { - ws := makeSection533Tree() - - ws.Push(makeWriteHeadersRequest(3 /*C*/)) - ws.Push(makeWriteNonStreamRequest()) - ws.Push(makeWriteHeadersRequest(5 /*E*/)) - ws.Push(makeWriteHeadersRequest(1 /*A*/)) - t.Log("tree:", fmtTree(ws, fmtNodeParentSkipRoot)) - - if err := checkPopAll(ws, []uint32{0 /*NonStream*/, 1, 3, 5}); err != nil { - t.Error(err) - } -} - -func TestPriorityPopFromLinearTree(t *testing.T) { - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - ws.OpenStream(3, OpenStreamOptions{PusherID: 2}) - ws.OpenStream(4, OpenStreamOptions{PusherID: 3}) - - ws.Push(makeWriteHeadersRequest(3)) - ws.Push(makeWriteHeadersRequest(4)) - ws.Push(makeWriteHeadersRequest(1)) - ws.Push(makeWriteHeadersRequest(2)) - ws.Push(makeWriteNonStreamRequest()) - ws.Push(makeWriteNonStreamRequest()) - t.Log("tree:", fmtTree(ws, fmtNodeParentSkipRoot)) - - if err := checkPopAll(ws, []uint32{0, 0 /*NonStreams*/, 1, 2, 3, 4}); err != nil { - t.Error(err) - } -} - -func TestPriorityFlowControl(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ThrottleOutOfOrderWrites: false}) - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - - sc := &serverConn{maxFrameSize: 16} - st1 := &stream{id: 1, sc: sc} - st2 := &stream{id: 2, sc: sc} - - ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 16), false}, st1, nil}) - ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 16), false}, st2, nil}) - ws.AdjustStream(2, PriorityParam{StreamDep: 1}) - - // No flow-control bytes available. - if wr, ok := ws.Pop(); ok { - t.Fatalf("Pop(limited by flow control)=%v,true, want false", wr) - } - - // Add enough flow-control bytes to write st2 in two Pop calls. - // Should write data from st2 even though it's lower priority than st1. - for i := 1; i <= 2; i++ { - st2.flow.add(8) - wr, ok := ws.Pop() - if !ok { - t.Fatalf("Pop(%d)=false, want true", i) - } - if got, want := wr.DataSize(), 8; got != want { - t.Fatalf("Pop(%d)=%d bytes, want %d bytes", i, got, want) - } - } -} - -func TestPriorityThrottleOutOfOrderWrites(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ThrottleOutOfOrderWrites: true}) - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{PusherID: 1}) - - sc := &serverConn{maxFrameSize: 4096} - st1 := &stream{id: 1, sc: sc} - st2 := &stream{id: 2, sc: sc} - st1.flow.add(4096) - st2.flow.add(4096) - ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 4096), false}, st2, nil}) - ws.AdjustStream(2, PriorityParam{StreamDep: 1}) - - // We have enough flow-control bytes to write st2 in a single Pop call. - // However, due to out-of-order write throttling, the first call should - // only write 1KB. - wr, ok := ws.Pop() - if !ok { - t.Fatalf("Pop(st2.first)=false, want true") - } - if got, want := wr.StreamID(), uint32(2); got != want { - t.Fatalf("Pop(st2.first)=stream %d, want stream %d", got, want) - } - if got, want := wr.DataSize(), 1024; got != want { - t.Fatalf("Pop(st2.first)=%d bytes, want %d bytes", got, want) - } - - // Now add data on st1. This should take precedence. - ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 4096), false}, st1, nil}) - wr, ok = ws.Pop() - if !ok { - t.Fatalf("Pop(st1)=false, want true") - } - if got, want := wr.StreamID(), uint32(1); got != want { - t.Fatalf("Pop(st1)=stream %d, want stream %d", got, want) - } - if got, want := wr.DataSize(), 4096; got != want { - t.Fatalf("Pop(st1)=%d bytes, want %d bytes", got, want) - } - - // Should go back to writing 1KB from st2. - wr, ok = ws.Pop() - if !ok { - t.Fatalf("Pop(st2.last)=false, want true") - } - if got, want := wr.StreamID(), uint32(2); got != want { - t.Fatalf("Pop(st2.last)=stream %d, want stream %d", got, want) - } - if got, want := wr.DataSize(), 1024; got != want { - t.Fatalf("Pop(st2.last)=%d bytes, want %d bytes", got, want) - } -} - -func TestPriorityWeights(t *testing.T) { - ws := defaultPriorityWriteScheduler() - ws.OpenStream(1, OpenStreamOptions{}) - ws.OpenStream(2, OpenStreamOptions{}) - - sc := &serverConn{maxFrameSize: 8} - st1 := &stream{id: 1, sc: sc} - st2 := &stream{id: 2, sc: sc} - st1.flow.add(40) - st2.flow.add(40) - - ws.Push(FrameWriteRequest{&writeData{1, make([]byte, 40), false}, st1, nil}) - ws.Push(FrameWriteRequest{&writeData{2, make([]byte, 40), false}, st2, nil}) - ws.AdjustStream(1, PriorityParam{StreamDep: 0, Weight: 34}) - ws.AdjustStream(2, PriorityParam{StreamDep: 0, Weight: 9}) - - // st1 gets 3.5x the bandwidth of st2 (3.5 = (34+1)/(9+1)). - // The maximum frame size is 8 bytes. The write sequence should be: - // st1, total bytes so far is (st1=8, st=0) - // st2, total bytes so far is (st1=8, st=8) - // st1, total bytes so far is (st1=16, st=8) - // st1, total bytes so far is (st1=24, st=8) // 3x bandwidth - // st1, total bytes so far is (st1=32, st=8) // 4x bandwidth - // st2, total bytes so far is (st1=32, st=16) // 2x bandwidth - // st1, total bytes so far is (st1=40, st=16) - // st2, total bytes so far is (st1=40, st=24) - // st2, total bytes so far is (st1=40, st=32) - // st2, total bytes so far is (st1=40, st=40) - if err := checkPopAll(ws, []uint32{1, 2, 1, 1, 1, 2, 1, 2, 2, 2}); err != nil { - t.Error(err) - } -} - -func TestPriorityRstStreamOnNonOpenStreams(t *testing.T) { - ws := NewPriorityWriteScheduler(&PriorityWriteSchedulerConfig{ - MaxClosedNodesInTree: 0, - MaxIdleNodesInTree: 0, - }) - ws.OpenStream(1, OpenStreamOptions{}) - ws.CloseStream(1) - ws.Push(FrameWriteRequest{write: streamError(1, ErrCodeProtocol)}) - ws.Push(FrameWriteRequest{write: streamError(2, ErrCodeProtocol)}) - - if err := checkPopAll(ws, []uint32{1, 2}); err != nil { - t.Error(err) - } -} diff --git a/vendor/golang.org/x/net/http2/writesched_random_test.go b/vendor/golang.org/x/net/http2/writesched_random_test.go deleted file mode 100644 index 3bf4aa36ab..0000000000 --- a/vendor/golang.org/x/net/http2/writesched_random_test.go +++ /dev/null @@ -1,44 +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 http2 - -import "testing" - -func TestRandomScheduler(t *testing.T) { - ws := NewRandomWriteScheduler() - ws.Push(makeWriteHeadersRequest(3)) - ws.Push(makeWriteHeadersRequest(4)) - ws.Push(makeWriteHeadersRequest(1)) - ws.Push(makeWriteHeadersRequest(2)) - ws.Push(makeWriteNonStreamRequest()) - ws.Push(makeWriteNonStreamRequest()) - - // Pop all frames. Should get the non-stream requests first, - // followed by the stream requests in any order. - var order []FrameWriteRequest - for { - wr, ok := ws.Pop() - if !ok { - break - } - order = append(order, wr) - } - t.Logf("got frames: %v", order) - if len(order) != 6 { - t.Fatalf("got %d frames, expected 6", len(order)) - } - if order[0].StreamID() != 0 || order[1].StreamID() != 0 { - t.Fatal("expected non-stream frames first", order[0], order[1]) - } - got := make(map[uint32]bool) - for _, wr := range order[2:] { - got[wr.StreamID()] = true - } - for id := uint32(1); id <= 4; id++ { - if !got[id] { - t.Errorf("frame not found for stream %d", id) - } - } -} diff --git a/vendor/golang.org/x/net/http2/writesched_test.go b/vendor/golang.org/x/net/http2/writesched_test.go deleted file mode 100644 index 0807056bc9..0000000000 --- a/vendor/golang.org/x/net/http2/writesched_test.go +++ /dev/null @@ -1,125 +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 http2 - -import ( - "fmt" - "math" - "reflect" - "testing" -) - -func makeWriteNonStreamRequest() FrameWriteRequest { - return FrameWriteRequest{writeSettingsAck{}, nil, nil} -} - -func makeWriteHeadersRequest(streamID uint32) FrameWriteRequest { - st := &stream{id: streamID} - return FrameWriteRequest{&writeResHeaders{streamID: streamID, httpResCode: 200}, st, nil} -} - -func checkConsume(wr FrameWriteRequest, nbytes int32, want []FrameWriteRequest) error { - consumed, rest, n := wr.Consume(nbytes) - var wantConsumed, wantRest FrameWriteRequest - switch len(want) { - case 0: - case 1: - wantConsumed = want[0] - case 2: - wantConsumed = want[0] - wantRest = want[1] - } - if !reflect.DeepEqual(consumed, wantConsumed) || !reflect.DeepEqual(rest, wantRest) || n != len(want) { - return fmt.Errorf("got %v, %v, %v\nwant %v, %v, %v", consumed, rest, n, wantConsumed, wantRest, len(want)) - } - return nil -} - -func TestFrameWriteRequestNonData(t *testing.T) { - wr := makeWriteNonStreamRequest() - if got, want := wr.DataSize(), 0; got != want { - t.Errorf("DataSize: got %v, want %v", got, want) - } - - // Non-DATA frames are always consumed whole. - if err := checkConsume(wr, 0, []FrameWriteRequest{wr}); err != nil { - t.Errorf("Consume:\n%v", err) - } -} - -func TestFrameWriteRequestData(t *testing.T) { - st := &stream{ - id: 1, - sc: &serverConn{maxFrameSize: 16}, - } - const size = 32 - wr := FrameWriteRequest{&writeData{st.id, make([]byte, size), true}, st, make(chan error)} - if got, want := wr.DataSize(), size; got != want { - t.Errorf("DataSize: got %v, want %v", got, want) - } - - // No flow-control bytes available: cannot consume anything. - if err := checkConsume(wr, math.MaxInt32, []FrameWriteRequest{}); err != nil { - t.Errorf("Consume(limited by flow control):\n%v", err) - } - - // Add enough flow-control bytes to consume the entire frame, - // but we're now restricted by st.sc.maxFrameSize. - st.flow.add(size) - want := []FrameWriteRequest{ - { - write: &writeData{st.id, make([]byte, st.sc.maxFrameSize), false}, - stream: st, - done: nil, - }, - { - write: &writeData{st.id, make([]byte, size-st.sc.maxFrameSize), true}, - stream: st, - done: wr.done, - }, - } - if err := checkConsume(wr, math.MaxInt32, want); err != nil { - t.Errorf("Consume(limited by maxFrameSize):\n%v", err) - } - rest := want[1] - - // Consume 8 bytes from the remaining frame. - want = []FrameWriteRequest{ - { - write: &writeData{st.id, make([]byte, 8), false}, - stream: st, - done: nil, - }, - { - write: &writeData{st.id, make([]byte, size-st.sc.maxFrameSize-8), true}, - stream: st, - done: wr.done, - }, - } - if err := checkConsume(rest, 8, want); err != nil { - t.Errorf("Consume(8):\n%v", err) - } - rest = want[1] - - // Consume all remaining bytes. - want = []FrameWriteRequest{ - { - write: &writeData{st.id, make([]byte, size-st.sc.maxFrameSize-8), true}, - stream: st, - done: wr.done, - }, - } - if err := checkConsume(rest, math.MaxInt32, want); err != nil { - t.Errorf("Consume(remainder):\n%v", err) - } -} - -func TestFrameWriteRequest_StreamID(t *testing.T) { - const streamID = 123 - wr := FrameWriteRequest{write: streamError(streamID, ErrCodeNo)} - if got := wr.StreamID(); got != streamID { - t.Errorf("FrameWriteRequest(StreamError) = %v; want %v", got, streamID) - } -} diff --git a/vendor/golang.org/x/net/http2/z_spec_test.go b/vendor/golang.org/x/net/http2/z_spec_test.go deleted file mode 100644 index 610b2cdbc2..0000000000 --- a/vendor/golang.org/x/net/http2/z_spec_test.go +++ /dev/null @@ -1,356 +0,0 @@ -// Copyright 2014 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 http2 - -import ( - "bytes" - "encoding/xml" - "flag" - "fmt" - "io" - "os" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "sync" - "testing" -) - -var coverSpec = flag.Bool("coverspec", false, "Run spec coverage tests") - -// The global map of sentence coverage for the http2 spec. -var defaultSpecCoverage specCoverage - -var loadSpecOnce sync.Once - -func loadSpec() { - if f, err := os.Open("testdata/draft-ietf-httpbis-http2.xml"); err != nil { - panic(err) - } else { - defaultSpecCoverage = readSpecCov(f) - f.Close() - } -} - -// covers marks all sentences for section sec in defaultSpecCoverage. Sentences not -// "covered" will be included in report outputted by TestSpecCoverage. -func covers(sec, sentences string) { - loadSpecOnce.Do(loadSpec) - defaultSpecCoverage.cover(sec, sentences) -} - -type specPart struct { - section string - sentence string -} - -func (ss specPart) Less(oo specPart) bool { - atoi := func(s string) int { - n, err := strconv.Atoi(s) - if err != nil { - panic(err) - } - return n - } - a := strings.Split(ss.section, ".") - b := strings.Split(oo.section, ".") - for len(a) > 0 { - if len(b) == 0 { - return false - } - x, y := atoi(a[0]), atoi(b[0]) - if x == y { - a, b = a[1:], b[1:] - continue - } - return x < y - } - if len(b) > 0 { - return true - } - return false -} - -type bySpecSection []specPart - -func (a bySpecSection) Len() int { return len(a) } -func (a bySpecSection) Less(i, j int) bool { return a[i].Less(a[j]) } -func (a bySpecSection) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -type specCoverage struct { - coverage map[specPart]bool - d *xml.Decoder -} - -func joinSection(sec []int) string { - s := fmt.Sprintf("%d", sec[0]) - for _, n := range sec[1:] { - s = fmt.Sprintf("%s.%d", s, n) - } - return s -} - -func (sc specCoverage) readSection(sec []int) { - var ( - buf = new(bytes.Buffer) - sub = 0 - ) - for { - tk, err := sc.d.Token() - if err != nil { - if err == io.EOF { - return - } - panic(err) - } - switch v := tk.(type) { - case xml.StartElement: - if skipElement(v) { - if err := sc.d.Skip(); err != nil { - panic(err) - } - if v.Name.Local == "section" { - sub++ - } - break - } - switch v.Name.Local { - case "section": - sub++ - sc.readSection(append(sec, sub)) - case "xref": - buf.Write(sc.readXRef(v)) - } - case xml.CharData: - if len(sec) == 0 { - break - } - buf.Write(v) - case xml.EndElement: - if v.Name.Local == "section" { - sc.addSentences(joinSection(sec), buf.String()) - return - } - } - } -} - -func (sc specCoverage) readXRef(se xml.StartElement) []byte { - var b []byte - for { - tk, err := sc.d.Token() - if err != nil { - panic(err) - } - switch v := tk.(type) { - case xml.CharData: - if b != nil { - panic("unexpected CharData") - } - b = []byte(string(v)) - case xml.EndElement: - if v.Name.Local != "xref" { - panic("expected </xref>") - } - if b != nil { - return b - } - sig := attrSig(se) - switch sig { - case "target": - return []byte(fmt.Sprintf("[%s]", attrValue(se, "target"))) - case "fmt-of,rel,target", "fmt-,,rel,target": - return []byte(fmt.Sprintf("[%s, %s]", attrValue(se, "target"), attrValue(se, "rel"))) - case "fmt-of,sec,target", "fmt-,,sec,target": - return []byte(fmt.Sprintf("[section %s of %s]", attrValue(se, "sec"), attrValue(se, "target"))) - case "fmt-of,rel,sec,target": - return []byte(fmt.Sprintf("[section %s of %s, %s]", attrValue(se, "sec"), attrValue(se, "target"), attrValue(se, "rel"))) - default: - panic(fmt.Sprintf("unknown attribute signature %q in %#v", sig, fmt.Sprintf("%#v", se))) - } - default: - panic(fmt.Sprintf("unexpected tag %q", v)) - } - } -} - -var skipAnchor = map[string]bool{ - "intro": true, - "Overview": true, -} - -var skipTitle = map[string]bool{ - "Acknowledgements": true, - "Change Log": true, - "Document Organization": true, - "Conventions and Terminology": true, -} - -func skipElement(s xml.StartElement) bool { - switch s.Name.Local { - case "artwork": - return true - case "section": - for _, attr := range s.Attr { - switch attr.Name.Local { - case "anchor": - if skipAnchor[attr.Value] || strings.HasPrefix(attr.Value, "changes.since.") { - return true - } - case "title": - if skipTitle[attr.Value] { - return true - } - } - } - } - return false -} - -func readSpecCov(r io.Reader) specCoverage { - sc := specCoverage{ - coverage: map[specPart]bool{}, - d: xml.NewDecoder(r)} - sc.readSection(nil) - return sc -} - -func (sc specCoverage) addSentences(sec string, sentence string) { - for _, s := range parseSentences(sentence) { - sc.coverage[specPart{sec, s}] = false - } -} - -func (sc specCoverage) cover(sec string, sentence string) { - for _, s := range parseSentences(sentence) { - p := specPart{sec, s} - if _, ok := sc.coverage[p]; !ok { - panic(fmt.Sprintf("Not found in spec: %q, %q", sec, s)) - } - sc.coverage[specPart{sec, s}] = true - } - -} - -var whitespaceRx = regexp.MustCompile(`\s+`) - -func parseSentences(sens string) []string { - sens = strings.TrimSpace(sens) - if sens == "" { - return nil - } - ss := strings.Split(whitespaceRx.ReplaceAllString(sens, " "), ". ") - for i, s := range ss { - s = strings.TrimSpace(s) - if !strings.HasSuffix(s, ".") { - s += "." - } - ss[i] = s - } - return ss -} - -func TestSpecParseSentences(t *testing.T) { - tests := []struct { - ss string - want []string - }{ - {"Sentence 1. Sentence 2.", - []string{ - "Sentence 1.", - "Sentence 2.", - }}, - {"Sentence 1. \nSentence 2.\tSentence 3.", - []string{ - "Sentence 1.", - "Sentence 2.", - "Sentence 3.", - }}, - } - - for i, tt := range tests { - got := parseSentences(tt.ss) - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("%d: got = %q, want %q", i, got, tt.want) - } - } -} - -func TestSpecCoverage(t *testing.T) { - if !*coverSpec { - t.Skip() - } - - loadSpecOnce.Do(loadSpec) - - var ( - list []specPart - cv = defaultSpecCoverage.coverage - total = len(cv) - complete = 0 - ) - - for sp, touched := range defaultSpecCoverage.coverage { - if touched { - complete++ - } else { - list = append(list, sp) - } - } - sort.Stable(bySpecSection(list)) - - if testing.Short() && len(list) > 5 { - list = list[:5] - } - - for _, p := range list { - t.Errorf("\tSECTION %s: %s", p.section, p.sentence) - } - - t.Logf("%d/%d (%d%%) sentences covered", complete, total, (complete/total)*100) -} - -func attrSig(se xml.StartElement) string { - var names []string - for _, attr := range se.Attr { - if attr.Name.Local == "fmt" { - names = append(names, "fmt-"+attr.Value) - } else { - names = append(names, attr.Name.Local) - } - } - sort.Strings(names) - return strings.Join(names, ",") -} - -func attrValue(se xml.StartElement, attr string) string { - for _, a := range se.Attr { - if a.Name.Local == attr { - return a.Value - } - } - panic("unknown attribute " + attr) -} - -func TestSpecPartLess(t *testing.T) { - tests := []struct { - sec1, sec2 string - want bool - }{ - {"6.2.1", "6.2", false}, - {"6.2", "6.2.1", true}, - {"6.10", "6.10.1", true}, - {"6.10", "6.1.1", false}, // 10, not 1 - {"6.1", "6.1", false}, // equal, so not less - } - for _, tt := range tests { - got := (specPart{tt.sec1, "foo"}).Less(specPart{tt.sec2, "foo"}) - if got != tt.want { - t.Errorf("Less(%q, %q) = %v; want %v", tt.sec1, tt.sec2, got, tt.want) - } - } -} diff --git a/vendor/golang.org/x/net/idna/example_test.go b/vendor/golang.org/x/net/idna/example_test.go deleted file mode 100644 index 948f6eb208..0000000000 --- a/vendor/golang.org/x/net/idna/example_test.go +++ /dev/null @@ -1,70 +0,0 @@ -// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. - -// 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 idna_test - -import ( - "fmt" - - "golang.org/x/net/idna" -) - -func ExampleProfile() { - // Raw Punycode has no restrictions and does no mappings. - fmt.Println(idna.ToASCII("")) - fmt.Println(idna.ToASCII("*.faß.com")) - fmt.Println(idna.Punycode.ToASCII("*.faß.com")) - - // Rewrite IDN for lookup. This (currently) uses transitional mappings to - // find a balance between IDNA2003 and IDNA2008 compatibility. - fmt.Println(idna.Lookup.ToASCII("")) - fmt.Println(idna.Lookup.ToASCII("www.faß.com")) - - // Convert an IDN to ASCII for registration purposes. This changes the - // encoding, but reports an error if the input was illformed. - fmt.Println(idna.Registration.ToASCII("")) - fmt.Println(idna.Registration.ToASCII("www.faß.com")) - - // Output: - // <nil> - // *.xn--fa-hia.com <nil> - // *.xn--fa-hia.com <nil> - // <nil> - // www.fass.com <nil> - // idna: invalid label "" - // www.xn--fa-hia.com <nil> -} - -func ExampleNew() { - var p *idna.Profile - - // Raw Punycode has no restrictions and does no mappings. - p = idna.New() - fmt.Println(p.ToASCII("*.faß.com")) - - // Do mappings. Note that star is not allowed in a DNS lookup. - p = idna.New( - idna.MapForLookup(), - idna.Transitional(true)) // Map ß -> ss - fmt.Println(p.ToASCII("*.faß.com")) - - // Lookup for registration. Also does not allow '*'. - p = idna.New(idna.ValidateForRegistration()) - fmt.Println(p.ToUnicode("*.faß.com")) - - // Set up a profile maps for lookup, but allows wild cards. - p = idna.New( - idna.MapForLookup(), - idna.Transitional(true), // Map ß -> ss - idna.StrictDomainName(false)) // Set more permissive ASCII rules. - fmt.Println(p.ToASCII("*.faß.com")) - - // Output: - // *.xn--fa-hia.com <nil> - // *.fass.com idna: disallowed rune U+002A - // *.faß.com idna: disallowed rune U+002A - // *.fass.com <nil> -} diff --git a/vendor/golang.org/x/net/idna/idna_test.go b/vendor/golang.org/x/net/idna/idna_test.go deleted file mode 100644 index 0b067cac97..0000000000 --- a/vendor/golang.org/x/net/idna/idna_test.go +++ /dev/null @@ -1,108 +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 idna - -import ( - "testing" -) - -var idnaTestCases = [...]struct { - ascii, unicode string -}{ - // Labels. - {"books", "books"}, - {"xn--bcher-kva", "bücher"}, - - // Domains. - {"foo--xn--bar.org", "foo--xn--bar.org"}, - {"golang.org", "golang.org"}, - {"example.xn--p1ai", "example.рф"}, - {"xn--czrw28b.tw", "商業.tw"}, - {"www.xn--mller-kva.de", "www.müller.de"}, -} - -func TestIDNA(t *testing.T) { - for _, tc := range idnaTestCases { - if a, err := ToASCII(tc.unicode); err != nil { - t.Errorf("ToASCII(%q): %v", tc.unicode, err) - } else if a != tc.ascii { - t.Errorf("ToASCII(%q): got %q, want %q", tc.unicode, a, tc.ascii) - } - - if u, err := ToUnicode(tc.ascii); err != nil { - t.Errorf("ToUnicode(%q): %v", tc.ascii, err) - } else if u != tc.unicode { - t.Errorf("ToUnicode(%q): got %q, want %q", tc.ascii, u, tc.unicode) - } - } -} - -func TestIDNASeparators(t *testing.T) { - type subCase struct { - unicode string - wantASCII string - wantErr bool - } - - testCases := []struct { - name string - profile *Profile - subCases []subCase - }{ - { - name: "Punycode", profile: Punycode, - subCases: []subCase{ - {"example\u3002jp", "xn--examplejp-ck3h", false}, - {"東京\uFF0Ejp", "xn--jp-l92cn98g071o", false}, - {"大阪\uFF61jp", "xn--jp-ku9cz72u463f", false}, - }, - }, - { - name: "Lookup", profile: Lookup, - subCases: []subCase{ - {"example\u3002jp", "example.jp", false}, - {"東京\uFF0Ejp", "xn--1lqs71d.jp", false}, - {"大阪\uFF61jp", "xn--pssu33l.jp", false}, - }, - }, - { - name: "Display", profile: Display, - subCases: []subCase{ - {"example\u3002jp", "example.jp", false}, - {"東京\uFF0Ejp", "xn--1lqs71d.jp", false}, - {"大阪\uFF61jp", "xn--pssu33l.jp", false}, - }, - }, - { - name: "Registration", profile: Registration, - subCases: []subCase{ - {"example\u3002jp", "", true}, - {"東京\uFF0Ejp", "", true}, - {"大阪\uFF61jp", "", true}, - }, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - for _, c := range tc.subCases { - gotA, err := tc.profile.ToASCII(c.unicode) - if c.wantErr { - if err == nil { - t.Errorf("ToASCII(%q): got no error, but an error expected", c.unicode) - } - } else { - if err != nil { - t.Errorf("ToASCII(%q): got err=%v, but no error expected", c.unicode, err) - } else if gotA != c.wantASCII { - t.Errorf("ToASCII(%q): got %q, want %q", c.unicode, gotA, c.wantASCII) - } - } - } - }) - } -} - -// TODO(nigeltao): test errors, once we've specified when ToASCII and ToUnicode -// return errors. diff --git a/vendor/golang.org/x/net/idna/punycode_test.go b/vendor/golang.org/x/net/idna/punycode_test.go deleted file mode 100644 index bfec81decd..0000000000 --- a/vendor/golang.org/x/net/idna/punycode_test.go +++ /dev/null @@ -1,198 +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 idna - -import ( - "strings" - "testing" -) - -var punycodeTestCases = [...]struct { - s, encoded string -}{ - {"", ""}, - {"-", "--"}, - {"-a", "-a-"}, - {"-a-", "-a--"}, - {"a", "a-"}, - {"a-", "a--"}, - {"a-b", "a-b-"}, - {"books", "books-"}, - {"bücher", "bcher-kva"}, - {"Hello世界", "Hello-ck1hg65u"}, - {"ü", "tda"}, - {"üý", "tdac"}, - - // The test cases below come from RFC 3492 section 7.1 with Errata 3026. - { - // (A) Arabic (Egyptian). - "\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" + - "\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F", - "egbpdaj6bu4bxfgehfvwxn", - }, - { - // (B) Chinese (simplified). - "\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587", - "ihqwcrb4cv8a8dqg056pqjye", - }, - { - // (C) Chinese (traditional). - "\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587", - "ihqwctvzc91f659drss3x8bo0yb", - }, - { - // (D) Czech. - "\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074" + - "\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D" + - "\u0065\u0073\u006B\u0079", - "Proprostnemluvesky-uyb24dma41a", - }, - { - // (E) Hebrew. - "\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8" + - "\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2" + - "\u05D1\u05E8\u05D9\u05EA", - "4dbcagdahymbxekheh6e0a7fei0b", - }, - { - // (F) Hindi (Devanagari). - "\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D" + - "\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939" + - "\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947" + - "\u0939\u0948\u0902", - "i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd", - }, - { - // (G) Japanese (kanji and hiragana). - "\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092" + - "\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B", - "n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa", - }, - { - // (H) Korean (Hangul syllables). - "\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774" + - "\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74" + - "\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C", - "989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j" + - "psd879ccm6fea98c", - }, - { - // (I) Russian (Cyrillic). - "\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E" + - "\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440" + - "\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A" + - "\u0438", - "b1abfaaepdrnnbgefbadotcwatmq2g4l", - }, - { - // (J) Spanish. - "\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070" + - "\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070" + - "\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061" + - "\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070" + - "\u0061\u00F1\u006F\u006C", - "PorqunopuedensimplementehablarenEspaol-fmd56a", - }, - { - // (K) Vietnamese. - "\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B" + - "\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068" + - "\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067" + - "\u0056\u0069\u1EC7\u0074", - "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g", - }, - { - // (L) 3<nen>B<gumi><kinpachi><sensei>. - "\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F", - "3B-ww4c5e180e575a65lsy2b", - }, - { - // (M) <amuro><namie>-with-SUPER-MONKEYS. - "\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074" + - "\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D" + - "\u004F\u004E\u004B\u0045\u0059\u0053", - "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n", - }, - { - // (N) Hello-Another-Way-<sorezore><no><basho>. - "\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F" + - "\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D" + - "\u305D\u308C\u305E\u308C\u306E\u5834\u6240", - "Hello-Another-Way--fc4qua05auwb3674vfr0b", - }, - { - // (O) <hitotsu><yane><no><shita>2. - "\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032", - "2-u9tlzr9756bt3uc0v", - }, - { - // (P) Maji<de>Koi<suru>5<byou><mae> - "\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059" + - "\u308B\u0035\u79D2\u524D", - "MajiKoi5-783gue6qz075azm5e", - }, - { - // (Q) <pafii>de<runba> - "\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", - "de-jg4avhby1noc0d", - }, - { - // (R) <sono><supiido><de> - "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067", - "d9juau41awczczp", - }, - { - // (S) -> $1.00 <- - "\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020" + - "\u003C\u002D", - "-> $1.00 <--", - }, -} - -func TestPunycode(t *testing.T) { - for _, tc := range punycodeTestCases { - if got, err := decode(tc.encoded); err != nil { - t.Errorf("decode(%q): %v", tc.encoded, err) - } else if got != tc.s { - t.Errorf("decode(%q): got %q, want %q", tc.encoded, got, tc.s) - } - - if got, err := encode("", tc.s); err != nil { - t.Errorf(`encode("", %q): %v`, tc.s, err) - } else if got != tc.encoded { - t.Errorf(`encode("", %q): got %q, want %q`, tc.s, got, tc.encoded) - } - } -} - -var punycodeErrorTestCases = [...]string{ - "decode -", // A sole '-' is invalid. - "decode foo\x00bar", // '\x00' is not in [0-9A-Za-z]. - "decode foo#bar", // '#' is not in [0-9A-Za-z]. - "decode foo\u00A3bar", // '\u00A3' is not in [0-9A-Za-z]. - "decode 9", // "9a" decodes to codepoint \u00A3; "9" is truncated. - "decode 99999a", // "99999a" decodes to codepoint \U0048A3C1, which is > \U0010FFFF. - "decode 9999999999a", // "9999999999a" overflows the int32 calculation. - - "encode " + strings.Repeat("x", 65536) + "\uff00", // int32 overflow. -} - -func TestPunycodeErrors(t *testing.T) { - for _, tc := range punycodeErrorTestCases { - var err error - switch { - case strings.HasPrefix(tc, "decode "): - _, err = decode(tc[7:]) - case strings.HasPrefix(tc, "encode "): - _, err = encode("", tc[7:]) - } - if err == nil { - if len(tc) > 256 { - tc = tc[:100] + "..." + tc[len(tc)-100:] - } - t.Errorf("no error for %s", tc) - } - } -} diff --git a/vendor/golang.org/x/net/internal/timeseries/timeseries_test.go b/vendor/golang.org/x/net/internal/timeseries/timeseries_test.go deleted file mode 100644 index 66325a912a..0000000000 --- a/vendor/golang.org/x/net/internal/timeseries/timeseries_test.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2015 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 timeseries - -import ( - "math" - "testing" - "time" -) - -func isNear(x *Float, y float64, tolerance float64) bool { - return math.Abs(x.Value()-y) < tolerance -} - -func isApproximate(x *Float, y float64) bool { - return isNear(x, y, 1e-2) -} - -func checkApproximate(t *testing.T, o Observable, y float64) { - x := o.(*Float) - if !isApproximate(x, y) { - t.Errorf("Wanted %g, got %g", y, x.Value()) - } -} - -func checkNear(t *testing.T, o Observable, y, tolerance float64) { - x := o.(*Float) - if !isNear(x, y, tolerance) { - t.Errorf("Wanted %g +- %g, got %g", y, tolerance, x.Value()) - } -} - -var baseTime = time.Date(2013, 1, 1, 0, 0, 0, 0, time.UTC) - -func tu(s int64) time.Time { - return baseTime.Add(time.Duration(s) * time.Second) -} - -func tu2(s int64, ns int64) time.Time { - return baseTime.Add(time.Duration(s)*time.Second + time.Duration(ns)*time.Nanosecond) -} - -func TestBasicTimeSeries(t *testing.T) { - ts := NewTimeSeries(NewFloat) - fo := new(Float) - *fo = Float(10) - ts.AddWithTime(fo, tu(1)) - ts.AddWithTime(fo, tu(1)) - ts.AddWithTime(fo, tu(1)) - ts.AddWithTime(fo, tu(1)) - checkApproximate(t, ts.Range(tu(0), tu(1)), 40) - checkApproximate(t, ts.Total(), 40) - ts.AddWithTime(fo, tu(3)) - ts.AddWithTime(fo, tu(3)) - ts.AddWithTime(fo, tu(3)) - checkApproximate(t, ts.Range(tu(0), tu(2)), 40) - checkApproximate(t, ts.Range(tu(2), tu(4)), 30) - checkApproximate(t, ts.Total(), 70) - ts.AddWithTime(fo, tu(1)) - ts.AddWithTime(fo, tu(1)) - checkApproximate(t, ts.Range(tu(0), tu(2)), 60) - checkApproximate(t, ts.Range(tu(2), tu(4)), 30) - checkApproximate(t, ts.Total(), 90) - *fo = Float(100) - ts.AddWithTime(fo, tu(100)) - checkApproximate(t, ts.Range(tu(99), tu(100)), 100) - checkApproximate(t, ts.Range(tu(0), tu(4)), 36) - checkApproximate(t, ts.Total(), 190) - *fo = Float(10) - ts.AddWithTime(fo, tu(1)) - ts.AddWithTime(fo, tu(1)) - checkApproximate(t, ts.Range(tu(0), tu(4)), 44) - checkApproximate(t, ts.Range(tu(37), tu2(100, 100e6)), 100) - checkApproximate(t, ts.Range(tu(50), tu2(100, 100e6)), 100) - checkApproximate(t, ts.Range(tu(99), tu2(100, 100e6)), 100) - checkApproximate(t, ts.Total(), 210) - - for i, l := range ts.ComputeRange(tu(36), tu(100), 64) { - if i == 63 { - checkApproximate(t, l, 100) - } else { - checkApproximate(t, l, 0) - } - } - - checkApproximate(t, ts.Range(tu(0), tu(100)), 210) - checkApproximate(t, ts.Range(tu(10), tu(100)), 100) - - for i, l := range ts.ComputeRange(tu(0), tu(100), 100) { - if i < 10 { - checkApproximate(t, l, 11) - } else if i >= 90 { - checkApproximate(t, l, 10) - } else { - checkApproximate(t, l, 0) - } - } -} - -func TestFloat(t *testing.T) { - f := Float(1) - if g, w := f.String(), "1"; g != w { - t.Errorf("Float(1).String = %q; want %q", g, w) - } - f2 := Float(2) - var o Observable = &f2 - f.Add(o) - if g, w := f.Value(), 3.0; g != w { - t.Errorf("Float post-add = %v; want %v", g, w) - } - f.Multiply(2) - if g, w := f.Value(), 6.0; g != w { - t.Errorf("Float post-multiply = %v; want %v", g, w) - } - f.Clear() - if g, w := f.Value(), 0.0; g != w { - t.Errorf("Float post-clear = %v; want %v", g, w) - } - f.CopyFrom(&f2) - if g, w := f.Value(), 2.0; g != w { - t.Errorf("Float post-CopyFrom = %v; want %v", g, w) - } -} - -type mockClock struct { - time time.Time -} - -func (m *mockClock) Time() time.Time { return m.time } -func (m *mockClock) Set(t time.Time) { m.time = t } - -const buckets = 6 - -var testResolutions = []time.Duration{ - 10 * time.Second, // level holds one minute of observations - 100 * time.Second, // level holds ten minutes of observations - 10 * time.Minute, // level holds one hour of observations -} - -// TestTimeSeries uses a small number of buckets to force a higher -// error rate on approximations from the timeseries. -type TestTimeSeries struct { - timeSeries -} - -func TestExpectedErrorRate(t *testing.T) { - ts := new(TestTimeSeries) - fake := new(mockClock) - fake.Set(time.Now()) - ts.timeSeries.init(testResolutions, NewFloat, buckets, fake) - for i := 1; i <= 61*61; i++ { - fake.Set(fake.Time().Add(1 * time.Second)) - ob := Float(1) - ts.AddWithTime(&ob, fake.Time()) - - // The results should be accurate within one missing bucket (1/6) of the observations recorded. - checkNear(t, ts.Latest(0, buckets), min(float64(i), 60), 10) - checkNear(t, ts.Latest(1, buckets), min(float64(i), 600), 100) - checkNear(t, ts.Latest(2, buckets), min(float64(i), 3600), 600) - } -} - -func min(a, b float64) float64 { - if a < b { - return a - } - return b -} diff --git a/vendor/golang.org/x/net/lex/httplex/httplex_test.go b/vendor/golang.org/x/net/lex/httplex/httplex_test.go deleted file mode 100644 index f47adc939f..0000000000 --- a/vendor/golang.org/x/net/lex/httplex/httplex_test.go +++ /dev/null @@ -1,119 +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 httplex - -import ( - "testing" -) - -func isChar(c rune) bool { return c <= 127 } - -func isCtl(c rune) bool { return c <= 31 || c == 127 } - -func isSeparator(c rune) bool { - switch c { - case '(', ')', '<', '>', '@', ',', ';', ':', '\\', '"', '/', '[', ']', '?', '=', '{', '}', ' ', '\t': - return true - } - return false -} - -func TestIsToken(t *testing.T) { - for i := 0; i <= 130; i++ { - r := rune(i) - expected := isChar(r) && !isCtl(r) && !isSeparator(r) - if IsTokenRune(r) != expected { - t.Errorf("isToken(0x%x) = %v", r, !expected) - } - } -} - -func TestHeaderValuesContainsToken(t *testing.T) { - tests := []struct { - vals []string - token string - want bool - }{ - { - vals: []string{"foo"}, - token: "foo", - want: true, - }, - { - vals: []string{"bar", "foo"}, - token: "foo", - want: true, - }, - { - vals: []string{"foo"}, - token: "FOO", - want: true, - }, - { - vals: []string{"foo"}, - token: "bar", - want: false, - }, - { - vals: []string{" foo "}, - token: "FOO", - want: true, - }, - { - vals: []string{"foo,bar"}, - token: "FOO", - want: true, - }, - { - vals: []string{"bar,foo,bar"}, - token: "FOO", - want: true, - }, - { - vals: []string{"bar , foo"}, - token: "FOO", - want: true, - }, - { - vals: []string{"foo ,bar "}, - token: "FOO", - want: true, - }, - { - vals: []string{"bar, foo ,bar"}, - token: "FOO", - want: true, - }, - { - vals: []string{"bar , foo"}, - token: "FOO", - want: true, - }, - } - for _, tt := range tests { - got := HeaderValuesContainsToken(tt.vals, tt.token) - if got != tt.want { - t.Errorf("headerValuesContainsToken(%q, %q) = %v; want %v", tt.vals, tt.token, got, tt.want) - } - } -} - -func TestPunycodeHostPort(t *testing.T) { - tests := []struct { - in, want string - }{ - {"www.google.com", "www.google.com"}, - {"гофер.рф", "xn--c1ae0ajs.xn--p1ai"}, - {"bücher.de", "xn--bcher-kva.de"}, - {"bücher.de:8080", "xn--bcher-kva.de:8080"}, - {"[1::6]:8080", "[1::6]:8080"}, - } - for _, tt := range tests { - got, err := PunycodeHostPort(tt.in) - if tt.want != got || err != nil { - t.Errorf("PunycodeHostPort(%q) = %q, %v, want %q, nil", tt.in, got, err, tt.want) - } - } -} diff --git a/vendor/golang.org/x/net/publicsuffix/list_test.go b/vendor/golang.org/x/net/publicsuffix/list_test.go deleted file mode 100644 index 42d79cc43e..0000000000 --- a/vendor/golang.org/x/net/publicsuffix/list_test.go +++ /dev/null @@ -1,416 +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 publicsuffix - -import ( - "sort" - "strings" - "testing" -) - -func TestNodeLabel(t *testing.T) { - for i, want := range nodeLabels { - got := nodeLabel(uint32(i)) - if got != want { - t.Errorf("%d: got %q, want %q", i, got, want) - } - } -} - -func TestFind(t *testing.T) { - testCases := []string{ - "", - "a", - "a0", - "aaaa", - "ao", - "ap", - "ar", - "aro", - "arp", - "arpa", - "arpaa", - "arpb", - "az", - "b", - "b0", - "ba", - "z", - "zu", - "zv", - "zw", - "zx", - "zy", - "zz", - "zzzz", - } - for _, tc := range testCases { - got := find(tc, 0, numTLD) - want := notFound - for i := uint32(0); i < numTLD; i++ { - if tc == nodeLabel(i) { - want = i - break - } - } - if got != want { - t.Errorf("%q: got %d, want %d", tc, got, want) - } - } -} - -func TestICANN(t *testing.T) { - testCases := map[string]bool{ - "foo.org": true, - "foo.co.uk": true, - "foo.dyndns.org": false, - "foo.go.dyndns.org": false, - "foo.blogspot.co.uk": false, - "foo.intranet": false, - } - for domain, want := range testCases { - _, got := PublicSuffix(domain) - if got != want { - t.Errorf("%q: got %v, want %v", domain, got, want) - } - } -} - -var publicSuffixTestCases = []struct { - domain, want string -}{ - // Empty string. - {"", ""}, - - // The .ao rules are: - // ao - // ed.ao - // gv.ao - // og.ao - // co.ao - // pb.ao - // it.ao - {"ao", "ao"}, - {"www.ao", "ao"}, - {"pb.ao", "pb.ao"}, - {"www.pb.ao", "pb.ao"}, - {"www.xxx.yyy.zzz.pb.ao", "pb.ao"}, - - // The .ar rules are: - // ar - // com.ar - // edu.ar - // gob.ar - // gov.ar - // int.ar - // mil.ar - // net.ar - // org.ar - // tur.ar - // blogspot.com.ar - {"ar", "ar"}, - {"www.ar", "ar"}, - {"nic.ar", "ar"}, - {"www.nic.ar", "ar"}, - {"com.ar", "com.ar"}, - {"www.com.ar", "com.ar"}, - {"blogspot.com.ar", "blogspot.com.ar"}, - {"www.blogspot.com.ar", "blogspot.com.ar"}, - {"www.xxx.yyy.zzz.blogspot.com.ar", "blogspot.com.ar"}, - {"logspot.com.ar", "com.ar"}, - {"zlogspot.com.ar", "com.ar"}, - {"zblogspot.com.ar", "com.ar"}, - - // The .arpa rules are: - // arpa - // e164.arpa - // in-addr.arpa - // ip6.arpa - // iris.arpa - // uri.arpa - // urn.arpa - {"arpa", "arpa"}, - {"www.arpa", "arpa"}, - {"urn.arpa", "urn.arpa"}, - {"www.urn.arpa", "urn.arpa"}, - {"www.xxx.yyy.zzz.urn.arpa", "urn.arpa"}, - - // The relevant {kobe,kyoto}.jp rules are: - // jp - // *.kobe.jp - // !city.kobe.jp - // kyoto.jp - // ide.kyoto.jp - {"jp", "jp"}, - {"kobe.jp", "jp"}, - {"c.kobe.jp", "c.kobe.jp"}, - {"b.c.kobe.jp", "c.kobe.jp"}, - {"a.b.c.kobe.jp", "c.kobe.jp"}, - {"city.kobe.jp", "kobe.jp"}, - {"www.city.kobe.jp", "kobe.jp"}, - {"kyoto.jp", "kyoto.jp"}, - {"test.kyoto.jp", "kyoto.jp"}, - {"ide.kyoto.jp", "ide.kyoto.jp"}, - {"b.ide.kyoto.jp", "ide.kyoto.jp"}, - {"a.b.ide.kyoto.jp", "ide.kyoto.jp"}, - - // The .tw rules are: - // tw - // edu.tw - // gov.tw - // mil.tw - // com.tw - // net.tw - // org.tw - // idv.tw - // game.tw - // ebiz.tw - // club.tw - // 網路.tw (xn--zf0ao64a.tw) - // 組織.tw (xn--uc0atv.tw) - // 商業.tw (xn--czrw28b.tw) - // blogspot.tw - {"tw", "tw"}, - {"aaa.tw", "tw"}, - {"www.aaa.tw", "tw"}, - {"xn--czrw28b.aaa.tw", "tw"}, - {"edu.tw", "edu.tw"}, - {"www.edu.tw", "edu.tw"}, - {"xn--czrw28b.edu.tw", "edu.tw"}, - {"xn--czrw28b.tw", "xn--czrw28b.tw"}, - {"www.xn--czrw28b.tw", "xn--czrw28b.tw"}, - {"xn--uc0atv.xn--czrw28b.tw", "xn--czrw28b.tw"}, - {"xn--kpry57d.tw", "tw"}, - - // The .uk rules are: - // uk - // ac.uk - // co.uk - // gov.uk - // ltd.uk - // me.uk - // net.uk - // nhs.uk - // org.uk - // plc.uk - // police.uk - // *.sch.uk - // blogspot.co.uk - {"uk", "uk"}, - {"aaa.uk", "uk"}, - {"www.aaa.uk", "uk"}, - {"mod.uk", "uk"}, - {"www.mod.uk", "uk"}, - {"sch.uk", "uk"}, - {"mod.sch.uk", "mod.sch.uk"}, - {"www.sch.uk", "www.sch.uk"}, - {"blogspot.co.uk", "blogspot.co.uk"}, - {"blogspot.nic.uk", "uk"}, - {"blogspot.sch.uk", "blogspot.sch.uk"}, - - // The .рф rules are - // рф (xn--p1ai) - {"xn--p1ai", "xn--p1ai"}, - {"aaa.xn--p1ai", "xn--p1ai"}, - {"www.xxx.yyy.xn--p1ai", "xn--p1ai"}, - - // The .bd rules are: - // *.bd - {"bd", "bd"}, - {"www.bd", "www.bd"}, - {"zzz.bd", "zzz.bd"}, - {"www.zzz.bd", "zzz.bd"}, - {"www.xxx.yyy.zzz.bd", "zzz.bd"}, - - // There are no .nosuchtld rules. - {"nosuchtld", "nosuchtld"}, - {"foo.nosuchtld", "nosuchtld"}, - {"bar.foo.nosuchtld", "nosuchtld"}, -} - -func BenchmarkPublicSuffix(b *testing.B) { - for i := 0; i < b.N; i++ { - for _, tc := range publicSuffixTestCases { - List.PublicSuffix(tc.domain) - } - } -} - -func TestPublicSuffix(t *testing.T) { - for _, tc := range publicSuffixTestCases { - got := List.PublicSuffix(tc.domain) - if got != tc.want { - t.Errorf("%q: got %q, want %q", tc.domain, got, tc.want) - } - } -} - -func TestSlowPublicSuffix(t *testing.T) { - for _, tc := range publicSuffixTestCases { - got := slowPublicSuffix(tc.domain) - if got != tc.want { - t.Errorf("%q: got %q, want %q", tc.domain, got, tc.want) - } - } -} - -// slowPublicSuffix implements the canonical (but O(number of rules)) public -// suffix algorithm described at http://publicsuffix.org/list/. -// -// 1. Match domain against all rules and take note of the matching ones. -// 2. If no rules match, the prevailing rule is "*". -// 3. If more than one rule matches, the prevailing rule is the one which is an exception rule. -// 4. If there is no matching exception rule, the prevailing rule is the one with the most labels. -// 5. If the prevailing rule is a exception rule, modify it by removing the leftmost label. -// 6. The public suffix is the set of labels from the domain which directly match the labels of the prevailing rule (joined by dots). -// 7. The registered or registrable domain is the public suffix plus one additional label. -// -// This function returns the public suffix, not the registrable domain, and so -// it stops after step 6. -func slowPublicSuffix(domain string) string { - match := func(rulePart, domainPart string) bool { - switch rulePart[0] { - case '*': - return true - case '!': - return rulePart[1:] == domainPart - } - return rulePart == domainPart - } - - domainParts := strings.Split(domain, ".") - var matchingRules [][]string - -loop: - for _, rule := range rules { - ruleParts := strings.Split(rule, ".") - if len(domainParts) < len(ruleParts) { - continue - } - for i := range ruleParts { - rulePart := ruleParts[len(ruleParts)-1-i] - domainPart := domainParts[len(domainParts)-1-i] - if !match(rulePart, domainPart) { - continue loop - } - } - matchingRules = append(matchingRules, ruleParts) - } - if len(matchingRules) == 0 { - matchingRules = append(matchingRules, []string{"*"}) - } else { - sort.Sort(byPriority(matchingRules)) - } - prevailing := matchingRules[0] - if prevailing[0][0] == '!' { - prevailing = prevailing[1:] - } - if prevailing[0][0] == '*' { - replaced := domainParts[len(domainParts)-len(prevailing)] - prevailing = append([]string{replaced}, prevailing[1:]...) - } - return strings.Join(prevailing, ".") -} - -type byPriority [][]string - -func (b byPriority) Len() int { return len(b) } -func (b byPriority) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b byPriority) Less(i, j int) bool { - if b[i][0][0] == '!' { - return true - } - if b[j][0][0] == '!' { - return false - } - return len(b[i]) > len(b[j]) -} - -// eTLDPlusOneTestCases come from -// https://github.com/publicsuffix/list/blob/master/tests/test_psl.txt -var eTLDPlusOneTestCases = []struct { - domain, want string -}{ - // Empty input. - {"", ""}, - // Unlisted TLD. - {"example", ""}, - {"example.example", "example.example"}, - {"b.example.example", "example.example"}, - {"a.b.example.example", "example.example"}, - // TLD with only 1 rule. - {"biz", ""}, - {"domain.biz", "domain.biz"}, - {"b.domain.biz", "domain.biz"}, - {"a.b.domain.biz", "domain.biz"}, - // TLD with some 2-level rules. - {"com", ""}, - {"example.com", "example.com"}, - {"b.example.com", "example.com"}, - {"a.b.example.com", "example.com"}, - {"uk.com", ""}, - {"example.uk.com", "example.uk.com"}, - {"b.example.uk.com", "example.uk.com"}, - {"a.b.example.uk.com", "example.uk.com"}, - {"test.ac", "test.ac"}, - // TLD with only 1 (wildcard) rule. - {"mm", ""}, - {"c.mm", ""}, - {"b.c.mm", "b.c.mm"}, - {"a.b.c.mm", "b.c.mm"}, - // More complex TLD. - {"jp", ""}, - {"test.jp", "test.jp"}, - {"www.test.jp", "test.jp"}, - {"ac.jp", ""}, - {"test.ac.jp", "test.ac.jp"}, - {"www.test.ac.jp", "test.ac.jp"}, - {"kyoto.jp", ""}, - {"test.kyoto.jp", "test.kyoto.jp"}, - {"ide.kyoto.jp", ""}, - {"b.ide.kyoto.jp", "b.ide.kyoto.jp"}, - {"a.b.ide.kyoto.jp", "b.ide.kyoto.jp"}, - {"c.kobe.jp", ""}, - {"b.c.kobe.jp", "b.c.kobe.jp"}, - {"a.b.c.kobe.jp", "b.c.kobe.jp"}, - {"city.kobe.jp", "city.kobe.jp"}, - {"www.city.kobe.jp", "city.kobe.jp"}, - // TLD with a wildcard rule and exceptions. - {"ck", ""}, - {"test.ck", ""}, - {"b.test.ck", "b.test.ck"}, - {"a.b.test.ck", "b.test.ck"}, - {"www.ck", "www.ck"}, - {"www.www.ck", "www.ck"}, - // US K12. - {"us", ""}, - {"test.us", "test.us"}, - {"www.test.us", "test.us"}, - {"ak.us", ""}, - {"test.ak.us", "test.ak.us"}, - {"www.test.ak.us", "test.ak.us"}, - {"k12.ak.us", ""}, - {"test.k12.ak.us", "test.k12.ak.us"}, - {"www.test.k12.ak.us", "test.k12.ak.us"}, - // Punycoded IDN labels - {"xn--85x722f.com.cn", "xn--85x722f.com.cn"}, - {"xn--85x722f.xn--55qx5d.cn", "xn--85x722f.xn--55qx5d.cn"}, - {"www.xn--85x722f.xn--55qx5d.cn", "xn--85x722f.xn--55qx5d.cn"}, - {"shishi.xn--55qx5d.cn", "shishi.xn--55qx5d.cn"}, - {"xn--55qx5d.cn", ""}, - {"xn--85x722f.xn--fiqs8s", "xn--85x722f.xn--fiqs8s"}, - {"www.xn--85x722f.xn--fiqs8s", "xn--85x722f.xn--fiqs8s"}, - {"shishi.xn--fiqs8s", "shishi.xn--fiqs8s"}, - {"xn--fiqs8s", ""}, -} - -func TestEffectiveTLDPlusOne(t *testing.T) { - for _, tc := range eTLDPlusOneTestCases { - got, _ := EffectiveTLDPlusOne(tc.domain) - if got != tc.want { - t.Errorf("%q: got %q, want %q", tc.domain, got, tc.want) - } - } -} diff --git a/vendor/golang.org/x/net/publicsuffix/table.go b/vendor/golang.org/x/net/publicsuffix/table.go index 549511c884..a870b36cd4 100644 --- a/vendor/golang.org/x/net/publicsuffix/table.go +++ b/vendor/golang.org/x/net/publicsuffix/table.go @@ -2,7 +2,7 @@ package publicsuffix -const version = "publicsuffix.org's public_suffix_list.dat, git revision 38b238d6324042f2c2e6270459d1f4ccfe789fba (2017-08-28T20:09:01Z)" +const version = "publicsuffix.org's public_suffix_list.dat, git revision 0f3b07d9aab6d6c9fe74990af98316468d40f488 (2018-01-25T09:22:16Z)" const ( nodesBitsChildren = 10 @@ -23,459 +23,464 @@ const ( ) // numTLD is the number of top level domains. -const numTLD = 1557 +const numTLD = 1551 // Text is the combined text of all labels. -const text = "bifukagawalterbihorologyukuhashimoichinosekigaharaxastronomy-gat" + - "ewaybomloans3-ca-central-1bikedagestangeorgeorgiabilbaogakihokum" + - "akogengerdalces3-website-us-west-1billustrationikinuyamashinashi" + - "kitchenikkoebenhavnikolaevents3-website-us-west-2bioddabirdartce" + - "nterprisesakikugawarszawashingtondclkariyameldalindesnesakurainv" + - "estmentsakyotanabellunord-odalivornomutashinainzais-a-candidateb" + - "irkenesoddtangenovaraumalopolskanlandrayddnsfreebox-oslocus-3bir" + - "thplacebitballooningladefinimakanegasakindlegokasells-for-lessal" + - "angenikonantankarlsoyurihonjoyentattoolsztynsettlersalondonetska" + - "rmoyusuharabjarkoyusuisserveexchangebjerkreimbalsfjordgcahcesuol" + - "ocalhostrodawaraugustowadaegubalsanagochihayaakasakawaharanzanne" + - "frankfurtarumizusawabkhaziamallamagazineat-url-o-g-i-naturalhist" + - "orymuseumcentereviewskrakowebredirectmeteorappaleobihirosakikami" + - "jimabogadocscbgdyniabruzzoologicalvinklein-addrammenuernberggfar" + - "merseinebinagisochildrensgardenaturalsciencesnaturelles3-ap-nort" + - "heast-2ixboxenapponazure-mobileastcoastaldefenceatonsberg12000em" + - "mafanconagawakayamadridvagsoyericssonyoursidealerimo-i-ranaamesj" + - "evuemielno-ip6bjugninohekinannestadraydnsaltdalombardiamondsalva" + - "dordalibabalatinord-frontierblockbustermezjavald-aostaplesalzbur" + - "glassassinationalheritagematsubarakawagoebloombergbauerninomiyak" + - "onojosoyrorosamegawabloxcmsamnangerbluedancebmoattachmentsamsclu" + - "bindalombardynamisches-dnsamsungleezebmsandvikcoromantovalle-d-a" + - "ostathellebmwedeployuufcfanirasakis-a-catererbnpparibaselburgliw" + - "icebnrwegroweibolzanorddalomzaporizhzheguris-a-celticsfanishiaza" + - "is-a-chefarmsteadrivelandrobaknoluoktachikawalbrzycharternidrudu" + - "nsanfranciscofreakunedre-eikerbonnishigoppdalorenskoglobalashovh" + - "achinohedmarkarpaczeladzlglobodoes-itvedestrandupontariobookingl" + - "ogoweirboomladbrokesangobootsanjournalismailillesandefjordurbana" + - "mexnetlifyis-a-conservativefsnillfjordurhamburgloppenzaogashimad" + - "achicagoboatsannanishiharaboschaefflerdalotenkawabostikaruizawab" + - "ostonakijinsekikogentingmbhartiffanyuzawabotanicalgardenishiizun" + - "azukis-a-cpadualstackspace-to-rentalstomakomaibarabotanicgardeni" + - "shikatakayamatta-varjjataxihuanishikatsuragit-repostfoldnavybota" + - "nybouncemerckmsdnipropetrovskjervoyagebounty-fullensakerryproper" + - "tiesannohelplfinancialotteboutiquebecngminakamichiharabozentsuji" + - "iebplacedekagaminordkappgafanpachigasakievennodesashibetsukumiya" + - "mazonawsaarlandyndns-at-workinggroupalmspringsakerbrandywinevall" + - "eybrasiliabresciabrindisibenikebristoloseyouripirangapartmentsan" + - "okarumaifarsundyndns-blogdnsantabarbarabritishcolumbialowiezachp" + - "omorskienishikawazukamitsuebroadcastlefrakkestadyndns-freeboxost" + - "rowwlkpmgmodenakatombetsumitakagiizebroadwaybroke-itgorybrokerbr" + - "onnoysundyndns-homednsantacruzsantafedjeffersonishimerabrotherme" + - "saverdeatnurembergmxfinitybrowsersafetymarketsanukis-a-cubicle-s" + - "lavellinotteroybrumunddalottokonamegatakasugais-a-democratjeldsu" + - "ndyndns-ipamperedchefashionishinomiyashironobrunelasticbeanstalk" + - "asaokaminoyamaxunusualpersonishinoomotegobrusselsaotomeloyalistj" + - "ordalshalsenishinoshimattelefonicarbonia-iglesias-carboniaiglesi" + - "ascarboniabruxellesapodlasiellaktyubinskiptveterinairealtorlandy" + - "ndns-mailouvrehabmerbryanskleppanamabrynewjerseybuskerudinewport" + - "lligatjmaxxxjaworznowtv-infoodnetworkshoppingrimstadyndns-office" + - "-on-the-webcambulancebuzenishiokoppegardyndns-picsapporobuzzpana" + - "sonicateringebugattipschlesischesardegnamsskoganeis-a-designerim" + - "arumorimachidabwfastlylbaltimore-og-romsdalillyokozehimejibigawa" + - "ukraanghkeymachinewhampshirebungoonord-aurdalpha-myqnapcloudacce" + - "sscambridgestonemurorangeiseiyoichippubetsubetsugaruhrhcloudns3-" + - "eu-central-1bzhitomirumalselvendrellowiczest-le-patronishitosash" + - "imizunaminamiashigaracompute-1computerhistoryofscience-fictionco" + - "msecuritytacticsaseboknowsitallvivano-frankivskasuyanagawacondos" + - "hichinohealth-carereformitakeharaconferenceconstructionconsulado" + - "esntexistanbullensvanguardyndns-workisboringrueconsultanthropolo" + - "gyconsultingvollcontactoyonocontemporaryarteducationalchikugodoh" + - "aruovatoyookannamifunecontractorskenconventureshinodearthdfcbank" + - "aszubycookingchannelsdvrdnsdojoetsuwanouchikujogaszczytnordreisa" + - "-geekatowicecoolkuszkolahppiacenzaganquannakadomarineustarhubsas" + - "katchewancooperaunitemp-dnsassaris-a-gurulsandoycopenhagencyclop" + - "edichernihivanovodkagoshimalvikashibatakashimaseratis-a-financia" + - "ladvisor-aurdalucaniacorsicagliaridagawashtenawdev-myqnapcloudap" + - "plebtimnetzwhoswhokksundyndns1corvettenrightathomeftparliamentoy" + - "osatoyakokonoecosenzakopanerairguardiann-arboretumbriacosidnsfor" + - "-better-thanawatchesatxn--12c1fe0bradescorporationcostumedio-cam" + - "pidano-mediocampidanomediocouchpotatofriesaudacouncilcouponsauhe" + - "radynnsavannahgacoursesaves-the-whalessandria-trani-barletta-and" + - "riatranibarlettaandriacqhachiojiyahoooshikamaishimodatecranbrook" + - "uwanalyticsavonaplesaxocreditcardynulvikatsushikabeeldengeluidyn" + - "v6creditunioncremonashgabadaddjambylcrewiiheyakagecricketrzyncri" + - "meast-kazakhstanangercrotonexus-2crownprovidercrsvparmacruisesbs" + - "chokoladencryptonomichigangwoncuisinellair-traffic-controlleycul" + - "turalcentertainmentoyotaris-a-hard-workercuneocupcakecxn--12cfi8" + - "ixb8lcyberlevagangaviikanonjis-a-huntercymrussiacyonabarunzencyo" + - "utheworkpccwildlifedorainfracloudcontrolledogawarabikomaezakirun" + - "orfolkebibleikangerfidonnakaniikawatanagurafieldfiguerestauranto" + - "yotsukaidownloadfilateliafilegearfilminamiechizenfinalfinancefin" + - "eartscientistockholmestrandfinlandfinnoyfirebaseapparscjohnsonfi" + - "renzefirestonefirmdaleirvikatsuyamasfjordenfishingolffanscotland" + - "fitjarfitnessettlementoyourafjalerflesbergulenflickragerotikakeg" + - "awaflightscrapper-siteflirflogintogurafloraflorencefloridavvesii" + - "dazaifudaigojomedizinhistorischescrappingunmarburguovdageaidnusl" + - "ivinghistoryfloripaderbornfloristanohatakahamangyshlakasamatsudo" + - "ntexisteingeekaufenflorogerserveftpartis-a-landscaperflowerserve" + - "game-serversicherungushikamifuranortonflynnhostingxn--1ck2e1bamb" + - "leclercasadelamonedatingjerstadotsuruokakudamatsuemrflynnhubanan" + - "arepublicaseihichisobetsuitainairforcechirealmetlifeinsuranceu-1" + - "fndfor-ourfor-someethnologyfor-theaterforexrothachirogatakahatak" + - "aishimogosenforgotdnservehalflifestyleforli-cesena-forlicesenafo" + - "rlikescandynamic-dnservehttpartnerservehumourforsaleitungsenfors" + - "andasuolodingenfortmissoulancashireggio-calabriafortworthadanose" + - "gawaforuminamifuranofosneserveirchernovtsykkylvenetogakushimotog" + - "anewyorkshirecipesaro-urbino-pesarourbinopesaromasvuotnaharimamu" + - "rogawassamukawataricohdatsunanjoburgriwataraidyndns-remotewdyndn" + - "s-serverdaluccapitalonewspaperfotaruis-a-lawyerfoxfordebianfredr" + - "ikstadtvserveminecraftoystre-slidrettozawafreeddnsgeekgalaxyfree" + - "masonryfreesitexascolipicenogiftservemp3freetlservep2partservepi" + - "cservequakefreiburgfreightcminamiiselectozsdeloittevadsoccertifi" + - "cationfresenius-4fribourgfriuli-v-giuliafriuli-ve-giuliafriuli-v" + - "egiuliafriuli-venezia-giuliafriuli-veneziagiuliafriuli-vgiuliafr" + - "iuliv-giuliafriulive-giuliafriulivegiuliafriulivenezia-giuliafri" + - "uliveneziagiuliafriulivgiuliafrlfroganservesarcasmatartanddesign" + - "frognfrolandfrom-akrehamnfrom-alfrom-arfrom-azfrom-capebretonami" + - "astalowa-wolayangroupartyfrom-coguchikuzenfrom-ctrani-andria-bar" + - "letta-trani-andriafrom-dchirurgiens-dentistes-en-francefrom-dedy" + - "n-ip24from-flanderservicesettsurgeonshalloffamemergencyachtsevas" + - "topolefrom-gausdalfrom-higashiagatsumagoizumizakirkenesevenassis" + - "icilyfrom-iafrom-idfrom-ilfrom-incheonfrom-ksewilliamhillfrom-ky" + - "owariasahikawafrom-lancasterfrom-maniwakuratextileksvikautokeino" + - "from-mdfrom-megurokunohealthcareersharis-a-liberalfrom-microsoft" + - "bankazofrom-mnfrom-modellingfrom-msharpasadenamsosnowiechiryukyu" + - "ragifuchungbukharafrom-mtnfrom-nchitachinakagawatchandclockashih" + - "arafrom-ndfrom-nefrom-nhktraniandriabarlettatraniandriafrom-njcb" + - "nlfrom-nminamiizukamishihoronobeauxartsandcraftshawaiijimarugame" + - "-hostrolekamikitayamatsuris-a-libertarianfrom-nvalled-aostatoilf" + - "rom-nyfrom-ohkurafrom-oketohmannorth-kazakhstanfrom-orfrom-padov" + - "aksdalfrom-pratohnoshooguyfrom-rivnefrom-schoenbrunnfrom-sdfrom-" + - "tnfrom-txn--1ctwolominamatakkokamiokamiminershellaspeziafrom-uta" + - "zuerichardlillehammerfeste-ipassagenshimojis-a-linux-useranishia" + - "ritabashijonawatefrom-val-daostavalleyfrom-vtranoyfrom-wafrom-wi" + - "elunnerfrom-wvalledaostavangerfrom-wyfrosinonefrostalbanshimokaw" + - "afroyahikobeardubaiduckdnshimokitayamafstavernfujiiderafujikawag" + - "uchikonefujiminohtawaramotoineppubolognakanotoddenfujinomiyadafu" + - "jiokayamansionshimonitayanagithubusercontentransportransurlfujis" + - "atoshonairtelecitychyattorneyagawakuyabukidsmynasushiobaragusart" + - "shimonosekikawafujisawafujishiroishidakabiratoridefenseljordfuji" + - "tsurugashimaritimekeepingfujixeroxn--1lqs03nfujiyoshidafukayabea" + - "tshimosuwalkis-a-llamarylandfukuchiyamadafukudominichitosetogits" + - "uldalucernefukuis-a-musicianfukumitsubishigakirovogradoyfukuokaz" + - "akiryuohadselfipassenger-associationfukuroishikarikaturindalfuku" + - "sakisarazurewebsiteshikagamiishibukawafukuyamagatakaharufunabash" + - "iriuchinadafunagatakahashimamakishiwadafunahashikamiamakusatsuma" + - "sendaisennangonohejis-a-nascarfanfundaciofuoiskujukuriyamanxn--1" + - "lqs71dfuosskoczowinbarcelonagasakikonaikawachinaganoharamcoacham" + - "pionshiphoptobishimaizurugbydgoszczecinemakeupowiathletajimabari" + - "akembuchikumagayagawakkanaibetsubamericanfamilydscloudcontrolapp" + - "spotagerfurnitureggio-emilia-romagnakasatsunairtrafficplexus-1fu" + - "rubiraquarellebesbyenglandfurudonostiaarpaviancarrierfurukawais-" + - "a-nurservebbshimotsukefusodegaurafussagamiharafutabayamaguchinom" + - "igawafutboldlygoingnowhere-for-moregontrailroadfuttsurugimperiaf" + - "uturecmshimotsumafuturehostingfuturemailingfvgfylkesbiblackfrida" + - "yfyresdalhangglidinghangoutsystemscloudfunctionshinichinanhannan" + - "mokuizumodernhannotaireshinjournalisteinkjerusalembroideryhanyuz" + - "enhapmirhareidsbergenharstadharvestcelebrationhasamarcheapgfoggi" + - "ahasaminami-alpssells-itrapaniimimatakatoris-a-playerhashbanghas" + - "udahasura-appharmacienshinjukumanohasvikazunohatogayaitakamoriok" + - "aluganskolevangerhatoyamazakitahiroshimarnardalhatsukaichikaisei" + - "s-a-republicancerresearchaeologicaliforniahattfjelldalhayashimam" + - "otobungotakadapliernewmexicodyn-vpnplusterhazuminobusellsyourhom" + - "egoodshinkamigotoyohashimotoshimahboehringerikehelsinkitakamiizu" + - "misanofidelityhembygdsforbundhemneshinshinotsurgeryhemsedalhepfo" + - "rgeherokussldheroyhgtvallee-aosteroyhigashichichibunkyonanaoshim" + - "ageandsoundandvisionhigashihiroshimanehigashiizumozakitakatakana" + - "beautysfjordhigashikagawahigashikagurasoedahigashikawakitaaikita" + - "kyushuaiahigashikurumeiwamarriottravelchannelhigashimatsushimars" + - "hallstatebankddielddanuorrikuzentakataiwanairlinebraskaunjargals" + - "aceohigashimatsuyamakitaakitadaitoigawahigashimurayamamotorcycle" + - "shinshirohigashinarusembokukitamidoris-a-rockstarachowicehigashi" + - "nehigashiomihachimanchesterhigashiosakasayamanakakogawahigashish" + - "irakawamatakanezawahigashisumiyoshikawaminamiaikitamotosumy-rout" + - "erhigashitsunotogawahigashiurausukitanakagusukumoduminamiminowah" + - "igashiyamatokoriyamanashifteditchyouripharmacyshintokushimahigas" + - "hiyodogawahigashiyoshinogaris-a-socialistmein-vigorgehiraizumisa" + - "tohobby-sitehirakatashinagawahiranais-a-soxfanhirarahiratsukagaw" + - "ahirayaizuwakamatsubushikusakadogawahistorichouseshintomikasahar" + - "ahitachiomiyagildeskaliszhitachiotagooglecodespotravelersinsuran" + - "cehitraeumtgeradellogliastradinghjartdalhjelmelandholeckobierzyc" + - "eholidayhomeiphdhomelinkfhappouhomelinuxn--1qqw23ahomeofficehome" + - "securitymaceratakaokamakurazakitashiobarahomesecuritypchloehomes" + - "enseminehomeunixn--2m4a15ehondahoneywellbeingzonehongopocznorthw" + - "esternmutualhonjyoitakarazukameokameyamatotakadahornindalhorseou" + - "lminamiogunicomcastresistancehortendofinternet-dnshinyoshitomiok" + - "amogawahospitalhoteleshiojirishirifujiedahotmailhoyangerhoylande" + - "troitskydivinghumanitieshioyanaizuhurdalhurumajis-a-studentalhyl" + - "lestadhyogoris-a-teacherkassymantechnologyhyugawarahyundaiwafune" + - "hzchocolatemasekashiwarajewishartgalleryjfkharkovalleeaosteigenj" + - "gorajlcube-serverrankoshigayakumoldelmenhorstagejlljmphilipsynol" + - "ogy-diskstationjnjcphilatelyjoyokaichibahccavuotnagareyamalborkd" + - "alwaysdatabaseballangenoamishirasatochigiessensiositelemarkherso" + - "njpmorganjpnjprshiraokananporovigotpantheonsitejuniperjurkoshuna" + - "ntokigawakosugekotohiradomainshiratakahagitlaborkotourakouhokuta" + - "makis-an-artistcgrouphiladelphiaareadmyblogsitekounosupplieshish" + - "ikuis-an-engineeringkouyamashikokuchuokouzushimasoykozagawakozak" + - "is-an-entertainerkozowindmillkpnkppspdnshisognekrasnodarkredston" + - "ekristiansandcatshisuifuelblagdenesnaaseralingenkainanaejrietisa" + - "latinabenonichoshibuyachiyodavvenjargaulardalutskasukabedzin-the" + - "-bandaioiraseeklogest-mon-blogueurovisionisshingugekristiansundk" + - "rodsheradkrokstadelvaldaostarnbergkryminamisanrikubetsupportrent" + - "ino-alto-adigekumatorinokumejimasudakumenanyokkaichiropractichoy" + - "odobashichikashukujitawarakunisakis-bykunitachiarailwaykunitomig" + - "usukumamotoyamassa-carrara-massacarraramassabusinessebyklegalloc" + - "alhistoryggeelvinckhmelnytskyivanylvenicekunneppulawykunstsammlu" + - "ngkunstunddesignkuokgrouphoenixn--30rr7ykureggioemiliaromagnakay" + - "amatsumaebashikshacknetrentino-altoadigekurgankurobelaudiblebork" + - "angerkurogimilanokuroisoftwarendalenugkuromatsunais-certifieduca" + - "torahimeshimamateramochizukirakurotakikawasakis-foundationkushir" + - "ogawakustanais-gonekusupplykutchanelkutnokuzumakis-into-animelbo" + - "urnekvafjordkvalsundkvamlidlugolekafjordkvanangenkvinesdalkvinnh" + - "eradkviteseidskogkvitsoykwpspiegelkzmisugitokorozawamitourismola" + - "ngevagrarchaeologyeongbuknx-serveronakatsugawamitoyoakemiuramiya" + - "zumiyotamanomjondalenmlbfanmonstermonticellolmontrealestatefarme" + - "quipmentrentino-s-tirollagrigentomologyeonggiehtavuoatnagaivuotn" + - "agaokakyotambabia-goracleaningatlantabusebastopologyeongnamegawa" + - "keisenbahnmonza-brianzaporizhzhiamonza-e-della-brianzapposhitara" + - "mamonzabrianzaptokuyamatsusakahoginankokubunjis-leetnedalmonzaeb" + - "rianzaramonzaedellabrianzamoonscalezajskolobrzegersundmoparachut" + - "ingmordoviajessheiminamitanemoriyamatsushigemoriyoshimilitarymor" + - "monmouthagakhanamigawamoroyamatsuuramortgagemoscowindowshizukuis" + - "himofusaintlouis-a-bruinsfanmoseushistorymosjoenmoskeneshizuokan" + - "azawamosshoujis-lostre-toteneis-an-accountantshirahamatonbetsurn" + - "adalmosvikomaganemoteginowaniihamatamakawajimaoris-not-certified" + - "unetbankhakassiamoviemovistargardmtpchristiansburgrondarmtranbym" + - "uenstermuginozawaonsenmuikamisunagawamukochikushinonsenergymulho" + - "uservebeermunakatanemuncieszynmuosattemuphonefosshowamurmanskoma" + - "kiyosunndalmurotorcraftrentino-stirolmusashimurayamatsuzakis-sav" + - "edmusashinoharamuseetrentino-sud-tirolmuseumverenigingmusicargod" + - "addynaliascoli-picenogataijis-slickharkivgucciprianiigataishinom" + - "akinderoymutsuzawamy-vigorlicemy-wanggouvicenzamyactivedirectory" + - "myasustor-elvdalmycdn77-securecifedexhibitionmyddnskingmydissent" + - "rentino-sudtirolmydrobofagemydshowtimemorialmyeffectrentino-sued" + - "-tirolmyfirewallonieruchomoscienceandindustrynmyfritzmyftpaccess" + - "hriramsterdamnserverbaniamyfusionmyhome-serversaillesienarashino" + - "mykolaivaolbia-tempio-olbiatempioolbialystokkepnoduminamiuonumat" + - "sumotofukemymailermymediapchristmasakimobetsuliguriamyokohamamat" + - "sudamypephotographysiomypetsigdalmyphotoshibajddarchitecturealty" + - "dalipaymypsxn--32vp30hagebostadmysecuritycamerakermyshopblocksil" + - "komatsushimashikizunokunimihoboleslawiechonanbuilderschmidtre-ga" + - "uldalukowhalingroks-thisayamanobeokalmykiamytis-a-bloggermytulea" + - "piagetmyipictetrentino-suedtirolmyvnchromedicaltanissettairamywi" + - "reitrentinoa-adigepinkomforbarclays3-us-east-2pioneerpippupictur" + - "esimple-urlpiszpittsburghofauskedsmokorsetagayasells-for-usgarde" + - "npiwatepixolinopizzapkommunalforbundplanetariuminamiyamashirokaw" + - "anabelembetsukubanklabudhabikinokawabarthaebaruminamimakis-a-pai" + - "nteractivegarsheis-a-patsfanplantationplantslingplatformshangril" + - "anslupskommuneplaystationplazaplchryslerplumbingopmnpodzonepohlp" + - "oivronpokerpokrovskomonopolitiendapolkowicepoltavalle-aostarostw" + - "odzislawinnersnoasaitamatsukuris-uberleetrdpomorzeszowiosokaneya" + - "mazoepordenonepornporsangerporsanguidell-ogliastraderporsgrunnan" + - "poznanpraxis-a-bookkeeperugiaprdpreservationpresidioprgmrprimelh" + - "uscultureisenprincipeprivatizehealthinsuranceprochowiceproductio" + - "nsokndalprofbsbxn--12co0c3b4evalleaostaticschuleprogressivegasia" + - "promombetsurfbx-oschwarzgwangjuifminamidaitomangotsukisofukushim" + - "aparocherkasyno-dschweizpropertyprotectionprotonetrentinoaadigep" + - "rudentialpruszkowitdkomorotsukamisatokamachintaifun-dnsaliasdabu" + - "rprzeworskogptplusdecorativeartsolarssonpvtrentinoalto-adigepwch" + - "ungnamdalseidfjordyndns-weberlincolniyodogawapzqldqponqslgbtrent" + - "inoaltoadigequicksytesolognequipelementsolundbeckomvuxn--2scrj9c" + - "hoseiroumuenchenissandnessjoenissayokoshibahikariwanumatakazakis" + - "-a-greenissedaluroyqvchurchaseljeepsongdalenviknagatorodoystufft" + - "oread-booksnesomnaritakurashikis-very-badajozorastuttgartrentino" + - "sudtirolsusakis-very-evillagesusonosuzakaniepcesuzukanmakiwakuni" + - "gamidsundsuzukis-very-goodhandsonsvalbardunloppacificirclegnicaf" + - "ederationsveiosvelvikongsvingersvizzerasvn-reposooswedenswidnica" + - "rtierswiebodzindianapolis-a-anarchistoireggiocalabriaswiftcovers" + - "winoujscienceandhistoryswisshikis-very-nicesynology-dsopotrentin" + - "os-tirolturystykanoyaltakasakiwientuscanytushuissier-justicetuva" + - "lle-daostatic-accessorreisahayakawakamiichikawamisatotaltuxfamil" + - "ytwmailvbargainstitutelevisionaustdalimanowarudaustevollavangena" + - "turbruksgymnaturhistorisches3-eu-west-1venneslaskerrylogisticsor" + - "tlandvestfoldvestnesoruminanovestre-slidreamhostersouthcarolinaz" + - "awavestre-totennishiawakuravestvagoyvevelstadvibo-valentiavibova" + - "lentiavideovillaskimitsubatamicable-modemoneyvinnicartoonartdeco" + - "ffeedbackplaneapplinzis-very-sweetpeppervinnytsiavipsinaappilots" + - "irdalvirginiavirtualvirtueeldomeindianmarketingvirtuelvisakataki" + - "nouevistaprinternationalfirearmsouthwestfalenviterboltrevisohugh" + - "esor-odalvivoldavixn--3bst00mincommbankmpspbarclaycards3-sa-east" + - "-1vlaanderenvladikavkazimierz-dolnyvladimirvlogoipimientaketomis" + - "atolgavolkswagentsowavologdanskonskowolawavolvolkenkundenvolyngd" + - "alvossevangenvotevotingvotoyonakagyokutourspjelkavikongsbergwloc" + - "lawekonsulatrobeepilepsydneywmflabspreadbettingworldworse-thanda" + - "wowithgoogleapisa-hockeynutsiracusakakinokiawpdevcloudwritesthis" + - "blogsytewroclawithyoutubeneventoeidsvollwtcircustomerwtfbxoscien" + - "cecentersciencehistorywuozuwwwiwatsukiyonowruzhgorodeowzmiuwajim" + - "axn--42c2d9axn--45br5cylxn--45brj9citadeliveryxn--45q11citicatho" + - "licheltenham-radio-opencraftrainingripescaravantaaxn--4gbriminin" + - "gxn--4it168dxn--4it797kooris-an-actorxn--4pvxs4allxn--54b7fta0cc" + - "ivilaviationxn--55qw42gxn--55qx5dxn--5js045dxn--5rtp49civilisati" + - "onxn--5rtq34kopervikhmelnitskiyamashikexn--5su34j936bgsgxn--5tzm" + - "5gxn--6btw5axn--6frz82gxn--6orx2rxn--6qq986b3xlxn--7t0a264civili" + - "zationxn--80adxhkspydebergxn--80ao21axn--80aqecdr1axn--80asehdba" + - "rreauctionaval-d-aosta-valleyolasiteu-2xn--80aswgxn--80audnedaln" + - "xn--8ltr62koryokamikawanehonbetsurutaharaxn--8pvr4uxn--8y0a063ax" + - "n--90a3academy-firewall-gatewayxn--90aeroportalaheadjudaicaaarbo" + - "rteaches-yogasawaracingroks-theatreexn--90aishobaraomoriguchihar" + - "ahkkeravjuedischesapeakebayernrtritonxn--90azhytomyrxn--9dbhblg6" + - "dietcimdbarrel-of-knowledgemologicallimitediscountysvardolls3-us" + - "-gov-west-1xn--9dbq2axn--9et52uxn--9krt00axn--andy-iraxn--aropor" + - "t-byandexn--3ds443gxn--asky-iraxn--aurskog-hland-jnbarrell-of-kn" + - "owledgeologyombondiscoveryomitanobninskarasjohkaminokawanishiaiz" + - "ubangeu-3utilitiesquare7xn--avery-yuasakegawaxn--b-5gaxn--b4w605" + - "ferdxn--bck1b9a5dre4civilwarmanagementjxn--0trq7p7nnxn--bdddj-mr" + - "abdxn--bearalvhki-y4axn--berlevg-jxaxn--bhcavuotna-s4axn--bhccav" + - "uotna-k7axn--bidr-5nachikatsuuraxn--bievt-0qa2xn--bjarky-fyaotsu" + - "rreyxn--bjddar-ptamayufuettertdasnetzxn--blt-elabourxn--bmlo-gra" + - "ingerxn--bod-2naroyxn--brnny-wuaccident-investigation-aptiblease" + - "ating-organicbcn-north-1xn--brnnysund-m8accident-prevention-webh" + - "openairbusantiquest-a-la-maisondre-landebudapest-a-la-masionionj" + - "ukudoyamagentositelekommunikationthewifiat-band-campaniaxn--brum" + - "-voagatroandinosaurepbodynathomebuiltrentinosued-tirolxn--btsfjo" + - "rd-9zaxn--c1avgxn--c2br7gxn--c3s14minnesotaketakatsukis-into-car" + - "shiranukanagawaxn--cck2b3barsyonlinewhollandishakotanavigationav" + - "oibmdisrechtranakaiwamizawaweddingjesdalimoliserniaustinnatuurwe" + - "tenschappenaumburgjerdrumckinseyokosukanzakiyokawaragrocerybnika" + - "hokutobamaintenancebetsuikicks-assedic66xn--cg4bkis-with-theband" + - "ovre-eikerxn--ciqpnxn--clchc0ea0b2g2a9gcdn77-sslattumintelligenc" + - "exn--comunicaes-v6a2oxn--correios-e-telecomunicaes-ghc29axn--czr" + - "694bashkiriaustraliaisondriodejaneirochesterxn--czrs0trogstadxn-" + - "-czru2dxn--czrw28basilicataniaustrheimatunduhrennesoyokotebinore" + - "-og-uvdalaziobiraskvolloabathsbcasacamdvrcampobassociatestingjem" + - "nes3-ap-southeast-1xn--d1acj3basketballyngenavuotnaklodzkodairau" + - "thordalandroiddnss3-eu-west-2xn--d1alfaromeoxn--d1atromsaitomobe" + - "llevuelosangelesjaguarmeniaxn--d5qv7z876claimsardiniaxn--davvenj" + - "rga-y4axn--djrs72d6uyxn--djty4kosaigawaxn--dnna-grajewolterskluw" + - "erxn--drbak-wuaxn--dyry-iraxn--e1a4clanbibaidarq-axn--eckvdtc9dx" + - "n--efvn9srlxn--efvy88haibarakisosakitagawaxn--ehqz56nxn--elqq16h" + - "air-surveillancexn--estv75gxn--eveni-0qa01gaxn--f6qx53axn--fct42" + - "9kosakaerodromegallupinbarefootballfinanzgoraurskog-holandroverh" + - "alla-speziaetnagahamaroygardenebakkeshibechambagriculturennebude" + - "jjudygarlandd-dnshome-webservercellikes-piedmontblancomeeres3-ap" + - "-south-1kappchizippodhaleangaviikadenadexetereport3l3p0rtargets-" + - "itargivestbytomaritimobaravennagasuke12hpalace164lima-cityeatsel" + - "inogradultarnobrzegyptianativeamericanantiques3-ap-northeast-133" + - "7xn--fhbeiarnxn--finny-yuaxn--fiq228c5hsrtrentinostirolxn--fiq64" + - "batodayonagoyautomotivecoalvdalaskanittedallasalleasinglesurance" + - "rtmgretagajoboji234xn--fiqs8srvaporcloudxn--fiqz9storagexn--fjor" + - "d-lraxn--fjq720axn--fl-ziaxn--flor-jraxn--flw351exn--fpcrj9c3dxn" + - "--frde-grandrapidstordalxn--frna-woaraisaijotromsojampagefrontap" + - "piemontexn--frya-hraxn--fzc2c9e2cldmailuxembourgrongaxn--fzys8d6" + - "9uvgmailxn--g2xx48clickasumigaurawa-mazowszextraspacekitagatajir" + - "issagaeroclubmedecincinnationwidealstahaugesunderseaportsinfolld" + - "alabamagasakishimabarackmazerbaijan-mayendoftheinternetflixilove" + - "collegefantasyleaguernseyxn--gckr3f0fedorapeopleirfjordynvpncher" + - "nivtsiciliaxn--gecrj9clinichernigovernmentjometacentruminamiawaj" + - "ikis-a-doctorayxn--ggaviika-8ya47hakatanoshiroomuraxn--gildeskl-" + - "g0axn--givuotna-8yasakaiminatoyonezawaxn--gjvik-wuaxn--gk3at1exn" + - "--gls-elacaixaxn--gmq050isleofmandalxn--gmqw5axn--h-2failxn--h1a" + - "eghakodatexn--h2breg3evenestorepaircraftrentinosud-tirolxn--h2br" + - "j9c8cliniquenoharaxn--h3cuzk1digitalxn--hbmer-xqaxn--hcesuolo-7y" + - "a35batsfjordivtasvuodnakamagayahababyglandivttasvuotnakamurataji" + - "mibuildingjovikarasjokarasuyamarylhurstjohnayorovnoceanographics" + - "3-us-west-1xn--hery-iraxn--hgebostad-g3axn--hmmrfeasta-s4acctrus" + - "teexn--hnefoss-q1axn--hobl-iraxn--holtlen-hxaxn--hpmir-xqaxn--hx" + - "t814exn--hyanger-q1axn--hylandet-54axn--i1b6b1a6a2exn--imr513nxn" + - "--indery-fyasugivingxn--io0a7issmarterthanyouxn--j1aefedoraproje" + - "ctoyotomiyazakis-a-knightpointtokaizukamikoaniikappugliaxn--j1am" + - "hakonexn--j6w193gxn--jlq61u9w7bauhausposts-and-telecommunication" + - "sncfdiyonaguniversityoriikarateu-4xn--jlster-byasuokanraxn--jrpe" + - "land-54axn--jvr189misakis-into-cartoonshiraois-a-techietis-a-the" + - "rapistoiaxn--k7yn95exn--karmy-yuaxn--kbrq7oxn--kcrx77d1x4axn--kf" + - "jord-iuaxn--klbu-woaxn--klt787dxn--kltp7dxn--kltx9axn--klty5xn--" + - "3e0b707exn--koluokta-7ya57hakubaghdadxn--kprw13dxn--kpry57dxn--k" + - "pu716fermodalenxn--kput3iwchofunatoriginsurecreationishiwakis-a-" + - "geekashiwazakiyosatokashikiyosemitexn--krager-gyatomitamamuraxn-" + +const text = "0emmafann-arboretumbriamallamaceiobihirosakikamijimatsuzaki234li" + + "ma-cityeatselinogradult3l3p0rtargets-itargivestbytomaritimekeepi" + + "ng120009guacuiababia-goracleaningroks-theatreeastcoastaldefencea" + + "tonsbergjemnes3-ap-northeast-1337bilbaogashimadachicagoboats3-we" + + "bsite-us-east-1billustrationikonanporovnopocznoppdalindesnes3-we" + + "bsite-us-west-1biobirdartcenterprisesakimobetsuitainairforcechir" + + "ealminamiechizeninohekinannestadiybirkenesoddtangenovaranzanpach" + + "igasakievennodesaarlandnpanasonicateringebuilderschmidtre-gaulda" + + "livornobirthplacebitballooningladefinimakanegasakinkobayashikaoi" + + "rminamifuranobjarkoybjerkreimbananarepublicasadelamonedatingjesd" + + "alimitediscountysvardolls3-eu-west-3utilitiesquare7bjugninomiyak" + + "onojorpelandrangedalombardiamonds3-website-us-west-2blancomedica" + + "ltanissettaipeiheijinuyamashinatsukigatakasagotpantheonsitebloom" + + "bergbauernuorochesterbloxcms5ybluedancebmoattachmentsakyotanabel" + + "lunord-aurdalvdalcesalangenirasakinvestmentsalondonetskarmoybmsa" + + "ltdalombardynamisches-dnsaludray-dnsupdaternopilawawebspacebmwed" + + "dinglassassinationalheritagebnpparibaselburgleezebnrwedeployboml" + + "oansalvadordalibabalsanagochihayaakasakawaharaholtalenvironmenta" + + "lconservationishiazainzais-a-candidatebondrayddnsfreebox-osascol" + + "i-picenordre-landraydnsalzburgliwicebonnishigobookinglobalashovh" + + "achinohedmarkarpaczeladzparaglidingloboavistaprintelligencebooml" + + "adbrokesamegawabootsamnangerboschaefflerdalwaysdatabaseballangen" + + "oamishirasatochigiessensiositelekommunikationishiharabostikaruiz" + + "awabostonakijinsekikogentinglogowegroweibolognagasukebotanicalga" + + "rdenishiizunazukis-a-catererbotanicgardenishikatakayamatsushigeb" + + "otanybouncemerckmsdnipropetrovskjervoyagebounty-fullensakerrypro" + + "pertiesampagespeedmobilizeroboutiquebecatholicaxiascolipicenodum" + + "inamiiselectjomemorialomzaporizhzheguris-a-celticsfanishikatsura" + + "git-repostfoldnavybozentsujiiebplacedekagaminord-odalondrinaples" + + "amsclubindalorenskogloppenzaolbia-tempio-olbiatempioolbialystokk" + + "embuchikumagayagawakuyabukihokumakogenglandrivelandrobaknoluokta" + + "chikawakkanaibetsubamericanfamilydscloudcontrolappspotagerbrandy" + + "winevalleybrasiliabrindisibenikebristoloseyouripirangapartmentsa" + + "msungmbhartiffanybritishcolumbialowiezachpomorskienishikawazukam" + + "itsuebroadcastlefrakkestadrudunsandvikcoromantovalle-d-aostathel" + + "lebroadwaybroke-itjxjavald-aostaplesanfranciscofreakunemurorange" + + "iseiyoichippubetsubetsugarugbyengerdalaskanittedallasalleasingle" + + "surancertmgretagajobojis-a-chefarmsteadupontariodejaneirodoybrok" + + "erbronnoysundurbanamexnetlifyis-a-conservativefsnillfjordurhambu" + + "rgminakamichiharabrothermesaverdeatnurembergmodellingmxn--0trq7p" + + "7nnishimerabrowsersafetymarketsangobrumunddalotenkawabrunelastic" + + "beanstalkarumaifarsundyndns-at-workinggrouparisor-fronishinomiya" + + "shironobrusselsanjotkmaxxn--11b4c3dyndns-blogdnsannanishinoomote" + + "gobruxellesannohelplfinancialottebryanskleppgafanquannefrankfurt" + + "ksatxn--12c1fe0bradescorporationishinoshimatsuurabrynewjerseybus" + + "kerudinewportlligatmparliamentoyosatoyonakagyokutoyokawabuzenish" + + "iokoppegardyndns-freeboxoslodingenishitosashimizunaminamibosognd" + + "alottokorozawabuzzweirbwfashionishiwakis-a-cpadualstackspace-to-" + + "rentalstomakomaibarabzhitomirumalatvuopmicrolightingrimstadyndns" + + "-homednsanokasaokaminokawanishiaizubangecommunitysnesardegnaroyc" + + "omobaracomparemarkerryhotelsardiniacompute-1computerhistoryofsci" + + "ence-fictioncomsecuritytacticsarlutskashiwazakiyosemitecondoshic" + + "hinohealth-carereformitakeharaconferenceconstructionconsuladohar" + + "uovatrani-andria-barletta-trani-andriaconsultanthropologyconsult" + + "ingvolluxembourgruecontactraniandriabarlettatraniandriacontagema" + + "tsubaracontemporaryarteducationalchikugojomedio-campidano-medioc" + + "ampidanomediocontractorskenconventureshinodearthdfcbankasukabedz" + + "in-the-bandaioiraseeklogest-mon-blogueurovisionionjukudoyamainte" + + "nancebetsuikidsmynasushiobarackmazerbaijan-mayenebakkeshibechamb" + + "agriculturennebudapest-a-la-masionthewifiat-band-campaniacooking" + + "channelsdvrdnsdojoetsuwanouchikujogaszczytnordlandyndns-weberlin" + + "colncoolkuszkolahppiacenzagancooperativano-frankivskodjeffersonc" + + "openhagencyclopedichernivtsiciliacorsicagliaribeiraokinawashiros" + + "atochiokinoshimaizuruhrcorvettemasekasumigaurawa-mazowszextraspa" + + "cekitagatajirissagamiharacosenzakopanerairguardiannakadomarinebr" + + "askaunjargalsaceocosidnsfor-better-thanawatchesarpsborguitarsaru" + + "futsunomiyawakasaikaitakoelncostumedizinhistorischesasayamacouch" + + "potatofriesasebofagecounciluxurycouponsaskatchewancoursesassaris" + + "-a-doctoraycq-acranbrookuwanalyticsaudacreditcardyndns-wikiracre" + + "ditunioncremonashgabadaddjaguarqhachiojiyahoooshikamaishimodatec" + + "rewhoswhokksundyndns-workisboringujoinvillewismillercricketrzync" + + "rimeast-kazakhstanangercrotonexus-3crownprovidercrsvparsauherady" + + "ndns1cruisesavannahgacryptonomichigangwoncuisinellair-traffic-co" + + "ntrolleyculturalcentertainmentranoycuneocupcakecuritibaghdadynns" + + "aves-the-whalessandria-trani-barletta-andriatranibarlettaandriac" + + "xn--12cfi8ixb8luzerncyberlevagangaviikanonjis-a-financialadvisor" + + "-aurdalvivanovodkamisatokashikiwakunigamiharufcfancymrussiacyona" + + "barulsandoycyoutheworkpccwiiheyakagefgushikamifuranorth-kazakhst" + + "anfhvalerfidonnakanotoddenfieldynvpnchernovtsykkylvenetogakushim" + + "otoganewyorkshirecipesaro-urbino-pesarourbinopesaromasvuotnakaiw" + + "amizawassamukawataricohdatsunanjoburgriwataraidyndns-iparmattele" + + "fonicapitalonewspaperfigueresinstagingxn--1ctwolominamatakkokami" + + "noyamaxunusualpersonfilateliafilegearfilminamimakis-a-geekaszuby" + + "finalfinancefineartscholarshipschoolfinlandyroyrvikingulenfinnoy" + + "firebaseappartis-a-greenfirenzefirestonefirmdaleirvikatowicefish" + + "ingolffanschulefitjarfitnessettlementransurlfjalerflesbergflickr" + + "agerotikakamigaharaflightschwarzgwangjuniperflirflogintohmalvika" + + "tsushikabeeldengeluidfloraflorencefloridavvesiidazaifudaigokasel" + + "jordfloripaderbornfloristanohatakahamamurogawaflorogerschweizflo" + + "wersciencecentersciencehistoryflynnhosting-clusterflynnhubarclay" + + "s3-sa-east-1fndfor-ourfor-someeresistancefor-theaterforexrothach" + + "irogatakamoriokalmykiaforgotdnscientistockholmestrandforli-cesen" + + "a-forlicesenaforlikescandynamic-dnscjohnsonforsaleitungsenforsan" + + "dasuoloftrapaniizafortalfortmissoulancashireggio-calabriafortwor" + + "thadanorthwesternmutualforuminamiminowafosnescotlandfotaruis-a-g" + + "urufoxfordebianfozorafredrikstadtvscrapper-sitefreeddnsgeekgalax" + + "yfreemasonryfreesitevadsochildrensgardenfreetlscrappingfreiburgf" + + "reightravelchannelfreseniuscountryestateofdelawarezzoologyfribou" + + "rgfriuli-v-giuliafriuli-ve-giuliafriuli-vegiuliafriuli-venezia-g" + + "iuliafriuli-veneziagiuliafriuli-vgiuliafriuliv-giuliafriulive-gi" + + "uliafriulivegiuliafriulivenezia-giuliafriuliveneziagiuliafriuliv" + + "giuliafrlfroganscrysechirurgiens-dentistes-en-francefrognfroland" + + "from-akrehamnfrom-alfrom-arfrom-azfrom-canonoichinomiyakefrom-co" + + "dynaliasdaburfrom-ctravelersinsurancefrom-dchiryukyuragifuchungb" + + "ukharafrom-dedyn-ip24from-flanderservegame-serversicherungfrom-g" + + "ausdalfrom-higashiagatsumagoianiafrom-iafrom-idfrom-ilfrom-inche" + + "onfrom-kservehalflifestylefrom-kyowariasahikawafrom-lancasterfro" + + "m-mangonohejis-a-hard-workerfrom-mdfrom-meethnologyfrom-mifunefr" + + "om-mnfrom-modalenfrom-mservehttpartnerservehumourfrom-mtnfrom-nc" + + "hitachinakagawatchandclockashibatakashimarumorimachidafrom-ndfro" + + "m-nefrom-nh-servebbserveirchitosetogitsuliguriafrom-njaworznotog" + + "awafrom-nminamiogunicomcastresindeviceserveminecraftrdfrom-nv-in" + + "foodnetworkshoppingfrom-nyfrom-ohtawaramotoineppuboliviajessheim" + + "periafrom-oketohnoshooguyfrom-orfrom-padovaksdalfrom-pratohobby-" + + "sitexashorokanaiefrom-rivnefrom-schoenbrunnfrom-sdfrom-tnfrom-tx" + + "n--1lqs03nfrom-utazuerichardlillehammerfeste-ipartservemp3from-v" + + "al-daostavalleyfrom-vtrentino-a-adigefrom-wafrom-wielunnerfrom-w" + + "valled-aostatoilfrom-wyfrosinonefrostalowa-wolawafroyahikobeardu" + + "baiduckdnservep2partyfstavernfujiiderafujikawaguchikonefujiminok" + + "amoenairtelecitychyattorneyagawakeisenbahnfujinomiyadafujiokayam" + + "angyshlakasamatsudontexistmein-vigorgefujisatoshonairtrafficplex" + + "us-1fujisawafujishiroishidakabiratoridefensells-for-lesservepics" + + "ervequakefujitsurugashimaringatlantakaharufujixeroxn--1lqs71dfuj" + + "iyoshidafukayabeatservesarcasmatartanddesignfukuchiyamadafukudom" + + "inichocolatelevisionissedalouvreisenisshingugefukuis-a-hunterfuk" + + "umitsubishigakirovogradoyfukuokazakiryuohadselfipasadenaritakura" + + "shikis-a-knightpointtokamachintaifun-dnsaliasiafukuroishikarikat" + + "urindalfukusakisarazurewebsiteshikagamiishibukawafukuyamagatakah" + + "ashimamakishiwadafunabashiriuchinadafunagatakahatakaishimogosenf" + + "unahashikamiamakusatsumasendaisennangoodyearfundaciofuoiskujukur" + + "iyamaniwakuratextileksvikatsuyamarylandfuosskoczowildlifedorainf" + + "racloudcontrolledogawarabikomaezakirunore-og-uvdalfurnitureggio-" + + "emilia-romagnakatombetsumitakagiizefurubirafurudonostiaarpassage" + + "nservicesettsurgeonshalloffameloyalistjordalshalsenfurukawais-a-" + + "landscaperfusodegaurafussaikisofukushimannorfolkebiblelveruminam" + + "isanrikubetsupportrentino-aadigefutabayamaguchinomigawafutboldly" + + "goingnowhere-for-morenakatsugawafuttsurugiminamitanefuturecmseva" + + "stopolefuturehostingfuturemailingfvgfylkesbiblackfridayfyresdalh" + + "angoutsystemscloudfunctionsevenassisicilyhannanmokuizumodenakaya" + + "mapassenger-associationhannosegawahanyuzenhapmirhareidsbergenhar" + + "stadharvestcelebrationhasamarburghasaminami-alpssells-itrentino-" + + "altoadigehashbanghasudahasura-appatriahasvikazohatogayaitakanabe" + + "autysfjordhatoyamazakitakamiizumisanofidelityhatsukaichikaiseis-" + + "a-linux-useranishiaritabashijonawatehattfjelldalhayashimamotobun" + + "gotakadapliernewmexicoalhazuminobusellsyourhomegoodsewilliamhill" + + "hbodoes-itvedestrandhelsinkitakatakanezawahembygdsforbundhemnesh" + + "aris-a-llamarriottrentino-s-tirollagrigentomologyeonggiehtavuoat" + + "nagaivuotnagaokakyotambabydgoszczecinemaceratabusebastopologyeon" + + "gnamegawakayamadridhemsedalhepforgeherokussldheroyhgtvalledaosta" + + "vangerhigashichichibunkyonanaoshimageandsoundandvisionhigashihir" + + "oshimanehigashiizumozakitakyushuaiahigashikagawahigashikagurasoe" + + "dahigashikawakitaaikitamihamadahigashikurumeguromskoghigashimats" + + "ushimarcheapaviancargodaddyn-vpnplus-2higashimatsuyamakitaakitad" + + "aitoigawahigashimurayamamotorcyclesharpfizerhigashinarusembokuki" + + "tamotosumy-routerhigashinehigashiomihachimanaustdalhigashiosakas" + + "ayamanakakogawahigashishirakawamatakaokaluganskydivinghigashisum" + + "iyoshikawaminamiaikitanakagusukumodernhigashitsunoshiroomurahiga" + + "shiurausukitashiobarahigashiyamatokoriyamanashifteditchyouripgfo" + + "ggiahigashiyodogawahigashiyoshinogaris-a-musicianhiraizumisatoka" + + "izukamakurazakitaurayasudahirakatashinagawahiranais-a-nascarfanh" + + "irarahiratsukagawahirayaizuwakamatsubushikusakadogawahistorichou" + + "seshawaiijimaritimoduminamiyamashirokawanabelembetsukubankazunow" + + "tvallee-aosteroyhitachiomiyagildeskaliszhitachiotagoperauniteroi" + + "zumizakisosakitagawahitraeumtgeradellogliastradinghjartdalhjelme" + + "landholeckobierzyceholidayhomeipharmacienshellaspeziahomelinkddi" + + "elddanuorrikuzentakataiwanairlinedre-eikerhomelinuxn--1qqw23ahom" + + "eofficehomesecuritymacaparecidahomesecuritypchofunatoriginsurecr" + + "eationiyodogawahomesenseminehomeunixn--2m4a15ehondahoneywellbein" + + "gzonehongotembaixadahonjyoitakarazukameokameyamatotakadahorninda" + + "lhorseoullensvanguardhortendofinternet-dnshimojis-a-nurservebeer" + + "hospitalhoteleshimokawahotmailhoyangerhoylandetroitskypehumaniti" + + "eshimokitayamahurdalhurumajis-a-painteractivegarsheis-a-patsfanh" + + "yllestadhyogoris-a-personaltrainerhyugawarahyundaiwafunejewelryj" + + "ewishartgalleryjfkharkovanylvenicejgorajlcube-serverrankoshigaya" + + "kumoldelmenhorstalbanshinichinanjlljmphilatelyjnjcphiladelphiaar" + + "eadmyblogsitejoyentrentino-sued-tiroljoyokaichibalatinoipifonymi" + + "nanojpmorganjpnjprshinjournalismailillesandefjordjurkoshunantank" + + "hmelnitskiyamarylhurstjohnkosugekotohiradomainshinjukumanokotour" + + "akouhokutamakis-a-techietis-a-photographerokuappharmacyshimonita" + + "yanagithubusercontentrentino-stirolkounosupplieshinkamigotoyohas" + + "himotottoris-a-therapistoiakouyamashikekouzushimashikis-an-accou" + + "ntantshimonosekikawakozagawakozakis-an-actorkozowinbarrel-of-kno" + + "wledgeologyonagoyaustrheimatunduhrennesoyolasitebizenakasatsunai" + + "rportland-4-salernoboribetsucks3-eu-central-1kpnkppspdnshinshino" + + "tsurgerykrasnodarkredstonekristiansandcatshinshirokristiansundkr" + + "odsheradkrokstadelvaldaostarnbergkrymincommbankhmelnytskyivaokum" + + "atorinokumejimasoykumenantokonamegatakatoris-an-actresshimosuwal" + + "kis-a-playerkunisakis-an-anarchistoricalsocietykunitachiarailway" + + "kunitomigusukumamotoyamashikokuchuokunneppugliakunstsammlungkuns" + + "tunddesignkuokgrouphoenixn--30rr7ykurehabmerkurgankurobelaudible" + + "borkangerkurogiminamiashigarakuroisoftwarendalenugkuromatsunais-" + + "an-artisteinkjerusalembroiderykurotakikawasakis-an-engineeringku" + + "shirogawakustanais-an-entertainerkusupplykutchanelkutnokuzumakis" + + "-bykvafjordkvalsundkvamfamberkeleykvanangenkvinesdalkvinnheradkv" + + "iteseidskogkvitsoykwpspiegelkzmitoyoakemiuramiyazumiyotamanomjon" + + "dalenmlbfanmonstermontrealestatefarmequipmentrentinoa-adigemonza" + + "-brianzaporizhzhiamonza-e-della-brianzapposhintomikasaharamonzab" + + "rianzaptokyotangotsukitahatakamatsukawamonzaebrianzaramonzaedell" + + "abrianzamoonscalemoparachutingmordoviamoriyamatsumotofukemoriyos" + + "himinamiawajikis-into-animeiwamarshallstatebankfhappoumormonmout" + + "hagakhanamigawamoroyamatsunomortgagemoscowindmillmoseushistorymo" + + "sjoenmoskeneshinyoshitomiokamogawamosshiojirishirifujiedamosvikn" + + "x-serveronamsskoganeis-a-rockstarachowicemoteginowaniihamatamaka" + + "wajimansionshioyanaizumoviemovimientolgamovistargardmtpchoyodoba" + + "shichikashukujitawaramtranbymuenstermuginozawaonsenmuikamisunaga" + + "wamukodairamulhouserveblogspotrentinoaadigemunakatanemuncienciam" + + "uosattemuphonefosshirahamatonbetsurnadalmurmanskolobrzegersundmu" + + "rotorcraftrentinoalto-adigemusashimurayamatsusakahoginankokubunj" + + "is-into-carshimotsukemusashinoharamuseetrentinoaltoadigemuseumve" + + "renigingmusicarbonia-iglesias-carboniaiglesiascarboniamutsuzawam" + + "y-vigorlicemy-wanggouvicenzamyactivedirectorymyasustor-elvdalmyc" + + "dn77-securecifedexhibitionmyddnskingmydissentrentinos-tirolmydro" + + "boehringerikemydshirakofuefukihaborokunohealthcareershiranukanag" + + "awamyeffectrentinostirolmyfirewallonieruchomoscienceandindustryn" + + "myfritzmyftpaccesshiraois-into-cartoonshimotsumamyhome-serversai" + + "lleshiraokananiimihoboleslawiechristiansburgrondarmykolaivaporcl" + + "oudmymailermymediapchristmasakinderoymyokohamamatsudamypephotogr" + + "aphysiomypetshiratakahagitlabormyphotoshibalestrandabergamoareke" + + "ymachinewhampshirebungoonombresciamypsxn--32vp30hagebostadmysecu" + + "ritycamerakermyshopblockshishikuis-into-gamessinazawamytis-a-boo" + + "kkeeperugiamytuleapiagetmyipictetrentinosud-tirolmyvnchromedicin" + + "akamagayachtsantabarbaramywireitrentinosudtirolpinkomaganepionee" + + "rpippulawypiszpittsburghofauskedsmokorsetagayasells-for-unzenpiw" + + "atepixolinopizzapkomakiyosunndalplanetariuminnesotaketakatsukis-" + + "certifieducatorahimeshimamateramobilyplantationplantshitaramapla" + + "tformshangrilanshizukuishimofusaitamatsukuris-lostre-toteneis-a-" + + "republicancerresearchaeologicaliforniaplaystationplazaplchungnam" + + "dalseidfjordyndns-mailucaniaplumbingoplurinacionalpmnpodzonepohl" + + "poivronpokerpokrovskomatsushimasfjordenpoliticarrierpolitiendapo" + + "lkowicepoltavalle-aostarostwodzislawindowshizuokanazawapomorzesz" + + "owinnershoujis-not-certifiedunetbankhakassiapordenonepornporsang" + + "erporsanguidell-ogliastraderporsgrunnanyokoshibahikariwanumatake" + + "tomisatoshimapoznanpraxis-a-bruinsfanprdpreservationpresidioprgm" + + "rprimeldalprincipeprivatizehealthinsuranceprochowiceproductionsh" + + "owaprofesionalprogressivegaskvolloabathsbchurchaseljeepsongdalen" + + "viknaharimalopolskanlandyndns-office-on-the-webcampinashikiminoh" + + "kurapromombetsurfbsbxn--12co0c3b4evalleaostaticsavonarusawaprope" + + "rtyprotectionprotonetrentinosued-tirolprudentialpruszkowioshowti" + + "memergencyahabahcavuotnagarahkkeravjuegoshikikonaikawachinaganoh" + + "aramcoachampionshiphoptobishimagentositecnologiaprzeworskogptplu" + + "sgardenpupictureshisognepvhaibarakitahiroshimaoris-a-lawyerpvtre" + + "ntinosuedtirolpwciprianiigataishinomakindlegnicafederationpzqldq" + + "ponqslgbtrentoyonezawaquicksyteshriramlidlugolekafjordquipelemen" + + "tsienarutomobellevuelosangelesjabbottrevisohughesigdalqvcirclego" + + "doesntexisteingeekashiharasrtroandinosaurepaircraftrogstadsrvare" + + "servecounterstrikestoragestordalstoregontrailroadstorfjordstorjd" + + "evcloudfrontdoorstpetersburgstreamsterdamnserverbaniastudiostudy" + + "ndns-at-homedepotenzamamidsundstuff-4-salestufftoread-booksnesir" + + "dalstuttgartromsakakinokiasusakis-savedsusonosuzakaniepcesuzukan" + + "makiwiensuzukis-slickharkivalleeaosteigensvalbardunloppacificirc" + + "ustomersveiosvelvikomvuxn--2scrj9choshibuyachiyodavvenjargaulard" + + "alowiczest-le-patronsvizzerasvn-reposjcbnlswedenswidnicartoonart" + + "decologiaswiebodzindianapolis-a-bloggerswiftcoverswinoujsciencea" + + "ndhistoryswisshikis-uberleetrentino-sud-tirolsynology-dslingtush" + + "uissier-justicetuvalle-daostatic-accessnoasaitotaltuxfamilytwmai" + + "lvenneslaskerrylogisticsokaneyamazoevestfoldvestnesokndalvestre-" + + "slidrepbodynathomebuiltrusteevestre-totennishiawakuravestvagoyve" + + "velstadvibo-valentiavibovalentiavideovillasnesoddenmarkhangelskj" + + "akdnepropetrovskiervaapsteiermarkongsvingervinnicasacamdvrcampin" + + "agrandebugattipschlesischesolarssonvinnytsiavipsinaappiemontevir" + + "giniavirtualvirtueeldomeindianmarketingvirtuelvisakegawaviterbok" + + "nowsitallvivoldavixn--3bst00misakis-foundationvlaanderenvladikav" + + "kazimierz-dolnyvladimirvlogoipilotshisuifuelblagdenesnaaseraling" + + "enkainanaejrietisalatinabenonichryslervolkswagentsolognevologdan" + + "skoninjambylvolvolkenkundenvolyngdalvossevangenvotevotingvotoyon" + + "owiwatsukiyonoticiaskimitsubatamibudejjuedischesapeakebayernrtrv" + + "arggatromsojamisonwloclawekonsulatrobeepilepsydneywmflabsolundbe" + + "ckommuneworldworse-thandawowitdkonskowolayangrouphilipsynology-d" + + "iskstationwpdevcloudwritesthisblogsytewroclawithgoogleapisa-hock" + + "eynutsiracusakatakinouewtcmisasaguris-gonewtfbx-ostrowwlkpmgunma" + + "nxn--1ck2e1barclaycards3-fips-us-gov-west-1wuozuwwwithyoutubenev" + + "entoeidsvollwzmiuwajimaxn--42c2d9axn--45br5cylxn--45brj9citadeli" + + "veryxn--45q11citichernigovernmentoyotaris-a-cubicle-slavellinota" + + "irestaurantoyotomiyazakis-a-democratoyotsukaidoxn--4gbriminingxn" + + "--4it168dxn--4it797kooris-a-soxfanxn--4pvxs4allxn--54b7fta0ccivi" + + "laviationxn--55qw42gxn--55qx5dxn--5js045dxn--5rtp49civilisationx" + + "n--5rtq34kopervikhersonxn--5su34j936bgsgxn--5tzm5gxn--6btw5axn--" + + "6frz82gxn--6orx2rxn--6qq986b3xlxn--7t0a264civilizationxn--80adxh" + + "ksolutionsilkomforbargainstitutelemarkarateu-1xn--80ao21axn--80a" + + "qecdr1axn--80asehdbarsyonlinewhollandiscoveryonaguniversityoriik" + + "aratsuginamikatagamilitaryoshiokaracoldwarmiastageu-2xn--80aswgx" + + "n--80audnedalnxn--8ltr62koryokamikawanehonbetsurutaharaxn--8pvr4" + + "uxn--8y0a063axn--90a3academiamicaaarborteaches-yogasawaracingxn-" + + "-90aeroportalaheadjudaicable-modemocraciaxn--90aishobarakawagoex" + + "n--90azhytomyrxn--9dbhblg6dietcimdbashkiriauthordalandeportenrig" + + "htathomeftpalmaseratibigawastronomy-gatewayokosukanzakiyosatokig" + + "awagrocerybnikahokutobamagazineat-url-o-g-i-natuurwetenschappena" + + "umburgjerdrumeteorappalermomahachijolstereportarumizusawaetnagah" + + "amaroygardendoftheinternetflixilovecollegefantasyleaguernseybolt" + + "arnobrzegyptianaturhistorisches3-ap-northeast-2ixboxenapponazure" + + "-mobile12hpaleobirabogadocscbgdyniabruzzoologicalvinklein-addram" + + "menuernberggfarmerseine164xn--9dbq2axn--9et52uxn--9krt00axn--and" + + "y-iraxn--aroport-byandexn--3ds443gxn--asky-iraxn--aurskog-hland-" + + "jnbasilicataniautomotiveconomiasakuchinotsuchiurakawalmartataran" + + "toyakokonoehimejibmdgcahcesuolocalhostrodawaraumalborkdalaziocea" + + "nographics3-eu-west-1xn--avery-yuasakuhokkaidoomdnsiskinkyotobet" + + "sumidatlanticivilwarmanagementoyouraxn--b-5gaxn--b4w605ferdxn--b" + + "ck1b9a5dre4claimsantacruzsantafedjejuifminamiizukamishihoronobea" + + "uxartsandcraftsantamariakexn--bdddj-mrabdxn--bearalvhki-y4axn--b" + + "erlevg-jxaxn--bhcavuotna-s4axn--bhccavuotna-k7axn--bidr-5nachika" + + "tsuuraxn--bievt-0qa2xn--bjarky-fyaotsurreyxn--bjddar-ptamayufuet" + + "tertdasnetzxn--blt-elabourxn--bmlo-graingerxn--bod-2natalxn--brn" + + "ny-wuacademy-firewall-gatewayxn--brnnysund-m8accident-investigat" + + "ion-aptibleaseating-organicbcn-north-1xn--brum-voagatrysiljanxn-" + + "-btsfjord-9zaxn--c1avgxn--c2br7gxn--c3s14misawaxn--cck2b3basketb" + + "allyngenhktatsunoddautoscanadaejeonbukarasjohkamikoaniikappueblo" + + "ckbustermezgoraugustowadaegubambleclerc66xn--cg4bkis-very-badajo" + + "zxn--ciqpnxn--clchc0ea0b2g2a9gcdn77-sslattumisconfusedxn--comuni" + + "caes-v6a2oxn--correios-e-telecomunicaes-ghc29axn--czr694batodayu" + + "kindustriaveroykeniwaizumiotsukumiyamazonawsadodgemologicallilly" + + "ombolzanord-frontiereviewskrakowebhostingjerstadotsuruokakegawau" + + "kraanghkepnogifts3-ap-southeast-2xn--czrs0tulanxesslupskommunalf" + + "orbundxn--czru2dxn--czrw28batsfjordishakotanhlfanhs3-us-gov-west" + + "-1xn--d1acj3bauhausposts-and-telecommunicationsncfdisrechtranaka" + + "muratajimidoriopretogoldpoint2thisamitsukeu-3xn--d1alfaromeoxn--" + + "d1atuneslzxn--d5qv7z876clanbibaidarmeniaxn--davvenjrga-y4axn--dj" + + "rs72d6uyxn--djty4kosaigawaxn--dnna-grajewolterskluwerxn--drbak-w" + + "uaxn--dyry-iraxn--e1a4cldmailuccapetownnews-stagingrongaxn--eckv" + + "dtc9dxn--efvn9somaxn--efvy88hair-surveillancexn--ehqz56nxn--elqq" + + "16hakatanortonxn--estv75gxn--eveni-0qa01gaxn--f6qx53axn--fct429k" + + "osakaerodromegallupinbarreauctionflfanfshostrowiecaseihichisobet" + + "suldalimoliserniaustraliaisondriobranconagawalesundemoneyokozebi" + + "nordreisa-geekaragandamusementashkentatamotors3-ap-southeast-1pa" + + "sswordd-dnshome-webservercellikes-piedmonticellocus-4xn--fhbeiar" + + "nxn--finny-yuaxn--fiq228c5hsomnarviikamitondabayashiogamagorizia" + + "xn--fiq64bbcasertairavennagatorockartuzyukuhashimoichinosekigaha" + + "ravocatanzarowebredirectmetacentrumetlifeinsurancempresashibetsu" + + "kuiitatebayashiibajddarchitecturealtydalipayomitanoceanographiqu" + + "emrevistanbulminamidaitomandalimanowarudaurskog-holandroverhalla" + + "-speziajudygarlanddnss3-ap-south-1kappchizippodhaleangaviikadena" + + "amesjevuemielno-ip6xn--fiqs8sooxn--fiqz9sopotritonxn--fjord-lrax" + + "n--fjq720axn--fl-ziaxn--flor-jraxn--flw351exn--fpcrj9c3dxn--frde" + + "-grandrapidsor-odalxn--frna-woaraisaijosoyrorosor-varangerxn--fr" + + "ya-hraxn--fzc2c9e2clickashiwaraxn--fzys8d69uvgmailxn--g2xx48clin" + + "ichernihivguccieszynissandnessjoenissayokkaichiropracticheltenha" + + "m-radio-opencraftrainingripescaravantaaxn--gckr3f0fbxosaxoxn--ge" + + "crj9cliniquenoharaxn--ggaviika-8ya47hakodatexn--gildeskl-g0axn--" + + "givuotna-8yasakaiminatoyookannamilanotteroyxn--gjvik-wuaxn--gk3a" + + "t1exn--gls-elacaixaxn--gmq050is-very-evillagexn--gmqw5axn--h-2fa" + + "ilxn--h1aeghakonexn--h2breg3evenesorfoldxn--h2brj9c8clintonoshoe" + + "santoandreamhostersanukis-a-designerimarnardalucernexn--h3cuzk1d" + + "igitalxn--hbmer-xqaxn--hcesuolo-7ya35bbtattoolsztynsettlers3-us-" + + "west-1xn--hery-iraxn--hgebostad-g3axn--hmmrfeasta-s4accident-pre" + + "vention-webhopenairbusantiquest-a-la-maisondre-landroidvagsoyeri" + + "cssonyoursidealerimo-i-ranadexeterxn--hnefoss-q1axn--hobl-iraxn-" + + "-holtlen-hxaxn--hpmir-xqaxn--hxt814exn--hyanger-q1axn--hylandet-" + + "54axn--i1b6b1a6a2exn--imr513nxn--indery-fyasugivingxn--io0a7is-v" + + "ery-goodhandsonxn--j1aefedorapeopleikangerxn--j1amhakubahccavuot" + + "nagareyamakeupowiathletajimabaridagawalbrzycharternidxn--j6w193g" + + "xn--jlq61u9w7bbvacationswatch-and-clockerhcloudns3-us-west-2xn--" + + "jlster-byasuokanraxn--jrpeland-54axn--jvr189mishimasudaxn--k7yn9" + + "5exn--karmy-yuaxn--kbrq7oxn--kcrx77d1x4axn--kfjord-iuaxn--klbu-w" + + "oaxn--klt787dxn--kltp7dxn--kltx9axn--klty5xn--3e0b707exn--koluok" + + "ta-7ya57hakuis-a-liberalxn--kprw13dxn--kpry57dxn--kpu716fedorapr" + + "ojectransportexn--kput3is-very-nicexn--krager-gyatomitamamuraxn-" + "-kranghke-b0axn--krdsherad-m8axn--krehamn-dxaxn--krjohka-hwab49j" + - "elenia-goraxn--ksnes-uuaxn--kvfjord-nxaxn--kvitsy-fyatsukanumazu" + - "ryxn--kvnangen-k0axn--l-1fairwindstorfjordxn--l1accentureklambor" + - "ghiniizaxn--laheadju-7yatsushiroxn--langevg-jxaxn--lcvr32dxn--ld" + - "ingen-q1axn--leagaviika-52bbcasertaipeiheijiitatebayashiibahcavu" + - "otnagaraholtalenvironmentalconservationflfanfshostrowiecasinordl" + - "andnpalermomahachijorpelandrangedalindashorokanaieverbankaratsug" + - "inamikatagamiharuconnectashkentatamotors3-us-west-2xn--lesund-hu" + - "axn--lgbbat1ad8jeonnamerikawauexn--lgrd-poaclintonoshoesarluxury" + - "xn--lhppi-xqaxn--linds-pramericanartrvareserveblogspotrentinosue" + - "dtirolxn--lns-qlapyatigorskypexn--loabt-0qaxn--lrdal-sraxn--lren" + - "skog-54axn--lt-liaclothingdustkakamigaharaxn--lten-granexn--lury" + - "-iraxn--m3ch0j3axn--mely-iraxn--merker-kuaxn--mgb2ddestorjdevclo" + - "udfrontdoorxn--mgb9awbferraraxn--mgba3a3ejtrysiljanxn--mgba3a4f1" + - "6axn--mgba3a4franamizuholdingsmilelverumisasaguris-into-gamessin" + - "atsukigatakasagotembaixadaxn--mgba7c0bbn0axn--mgbaakc7dvferrarit" + - "togoldpoint2thisamitsukexn--mgbaam7a8hakuis-a-personaltrainerxn-" + - "-mgbab2bdxn--mgbai9a5eva00bbtatarantottoriiyamanouchikuhokuryuga" + - "sakitaurayasudautoscanadaejeonbukaragandasnesoddenmarkhangelskja" + - "kdnepropetrovskiervaapsteiermark12xn--mgbai9azgqp6jetztrentino-a" + - "-adigexn--mgbayh7gpagespeedmobilizeroxn--mgbb9fbpobanazawaxn--mg" + - "bbh1a71exn--mgbc0a9azcgxn--mgbca7dzdoxn--mgberp4a5d4a87gxn--mgbe" + - "rp4a5d4arxn--mgbgu82axn--mgbi4ecexposedxn--mgbpl2fhskodjejuegosh" + - "ikiminokamoenairportland-4-salernoboribetsuckstpetersburgxn--mgb" + - "qly7c0a67fbcnsarpsborgrossetouchijiwadegreexn--mgbqly7cvafranzis" + - "kanerdpolicexn--mgbt3dhdxn--mgbtf8flatangerxn--mgbtx2bbvacations" + - "watch-and-clockerxn--mgbx4cd0abbottulanxessor-varangerxn--mix082" + - "ferreroticanonoichinomiyakexn--mix891fetsundyroyrvikinguitarscho" + - "larshipschoolxn--mjndalen-64axn--mk0axindustriesteamfamberkeleyx" + - "n--mk1bu44cntkmaxxn--11b4c3dyndns-wikinkobayashikaoirminamibosog" + - "ndaluzernxn--mkru45ixn--mlatvuopmi-s4axn--mli-tlaquilanciaxn--ml" + - "selv-iuaxn--moreke-juaxn--mori-qsakuhokkaidoomdnsiskinkyotobetsu" + - "midatlanticolognextdirectmparaglidingroundhandlingroznyxn--mosje" + - "n-eyawaraxn--mot-tlarvikoseis-an-actresshirakofuefukihaboromskog" + - "xn--mre-og-romsdal-qqbentleyoshiokaracoldwarmiamihamadaveroykeni" + - "waizumiotsukuibestadds3-external-1xn--msy-ula0hakusandiegoodyear" + - "xn--mtta-vrjjat-k7afamilycompanycolonialwilliamsburgrparisor-fro" + - "nxn--muost-0qaxn--mxtq1misawaxn--ngbc5azdxn--ngbe9e0axn--ngbrxn-" + - "-3hcrj9cistrondheimmobilienxn--nit225kosherbrookegawaxn--nmesjev" + - "uemie-tcbalestrandabergamoarekexn--nnx388axn--nodessakuragawaxn-" + - "-nqv7fs00emaxn--nry-yla5gxn--ntso0iqx3axn--ntsq17gxn--nttery-bya" + - "eservecounterstrikexn--nvuotna-hwaxn--nyqy26axn--o1achattanoogan" + - "ordre-landxn--o3cw4haldenxn--o3cyx2axn--od0algxn--od0aq3beppubli" + - "shproxyzgorzeleccollectionhlfanhs3-website-ap-northeast-1xn--ogb" + - "pf8flekkefjordxn--oppegrd-ixaxn--ostery-fyawatahamaxn--osyro-wua" + - "xn--p1acfgujolsterxn--p1aixn--pbt977coloradoplateaudioxn--pgbs0d" + - "hlxn--porsgu-sta26fhvalerxn--pssu33lxn--pssy2uxn--q9jyb4columbus" + - "heyxn--qcka1pmcdonaldstreamuneuesolutionsomaxn--qqqt11misconfuse" + - "dxn--qxamusementunesorfoldxn--rady-iraxn--rdal-poaxn--rde-ulavag" + - "iskexn--rdy-0nabarixn--rennesy-v1axn--rhkkervju-01aflakstadaokag" + - "akibichuoxn--rholt-mragowoodsideltaitogliattirestudioxn--rhqv96g" + - "xn--rht27zxn--rht3dxn--rht61exn--risa-5narusawaxn--risr-iraxn--r" + - "land-uuaxn--rlingen-mxaxn--rmskog-byaxn--rny31halsaikitahatakama" + - "tsukawaxn--rovu88bernuorockartuzyukinfinitintuitateshinanomachim" + - "kentateyamavocatanzarowebspacebizenakanojohanamakinoharassnasaba" + - "erobatickets3-ap-southeast-2xn--rros-granvindafjordxn--rskog-uua" + - "xn--rst-0narutokyotangovtunkoninjamisonxn--rsta-francaiseharaxn-" + - "-rvc1e0am3exn--ryken-vuaxn--ryrvik-byaxn--s-1faithruheredumbrell" + - "ajollamericanexpressexyxn--s9brj9communitysnesarufutsunomiyawaka" + - "saikaitakoelnxn--sandnessjen-ogbizxn--sandy-yuaxn--seral-lraxn--" + - "ses554gxn--sgne-gratangenxn--skierv-utazaskoyabearalvahkijobserv" + - "erisignieznoipifonymishimatsunoxn--skjervy-v1axn--skjk-soaxn--sk" + - "nit-yqaxn--sknland-fxaxn--slat-5narviikamitondabayashiogamagoriz" + - "iaxn--slt-elabbvieeexn--smla-hraxn--smna-gratis-a-bulls-fanxn--s" + - "nase-nraxn--sndre-land-0cbremangerxn--snes-poaxn--snsa-roaxn--sr" + - "-aurdal-l8axn--sr-fron-q1axn--sr-odal-q1axn--sr-varanger-ggbeski" + - "dyn-o-saurlandes3-website-ap-southeast-1xn--srfold-byaxn--srreis" + - "a-q1axn--srum-grazxn--stfold-9xaxn--stjrdal-s1axn--stjrdalshalse" + - "n-sqbestbuyshouses3-website-ap-southeast-2xn--stre-toten-zcbstud" + - "yndns-at-homedepotenzamamicrolightingxn--t60b56axn--tckweatherch" + - "annelxn--tiq49xqyjevnakershuscountryestateofdelawarezzoologyxn--" + - "tjme-hraxn--tn0agrinet-freakstuff-4-salexn--tnsberg-q1axn--tor13" + - "1oxn--trany-yuaxn--trgstad-r1axn--trna-woaxn--troms-zuaxn--tysvr" + - "-vraxn--uc0atvarggatrentoyokawaxn--uc0ay4axn--uist22hammarfeasta" + - "fricapetownnews-stagingxn--uisz3gxn--unjrga-rtaobaokinawashirosa" + - "tochiokinoshimalatvuopmiasakuchinotsuchiurakawalesundxn--unup4yx" + - "n--uuwu58axn--vads-jraxn--vard-jraxn--vegrshei-c0axn--vermgensbe" + - "rater-ctbetainaboxfusejnynysadodgeometre-experts-comptables3-web" + - "site-eu-west-1xn--vermgensberatung-pwbieigersundray-dnsupdaterno" + - "pilawavoues3-fips-us-gov-west-1xn--vestvgy-ixa6oxn--vg-yiabcgxn-" + - "-vgan-qoaxn--vgsy-qoa0jewelryxn--vgu402comobilyxn--vhquvaroyxn--" + - "vler-qoaxn--vre-eiker-k8axn--vrggt-xqadxn--vry-yla5gxn--vuq861bi" + - "elawalmartatsunoceanographiquevje-og-hornnes3-website-sa-east-1x" + - "n--w4r85el8fhu5dnraxn--w4rs40lxn--wcvs22dxn--wgbh1comparemarkerr" + - "yhotelsasayamaxn--wgbl6axn--xhq521biellaakesvuemieleccexn--xkc2a" + - "l3hye2axn--xkc2dl3a5ee0hamurakamigoris-a-photographerokuappfizer" + - "xn--y9a3aquariumissilewismillerxn--yer-znarvikoshimizumakis-an-a" + - "narchistoricalsocietyxn--yfro4i67oxn--ygarden-p1axn--ygbi2ammxn-" + - "-3oq18vl8pn36axn--ystre-slidre-ujbieszczadygeyachimataikikuchiku" + - "seikarugamvikareliancexn--zbx025dxn--zf0ao64axn--zf0avxn--3pxu8k" + - "onyveloftrentino-aadigexn--zfr164bievatmallorcadaques3-website-u" + - "s-east-1xperiaxz" + "dfastlylbarcelonagasakikuchikuseikarugamvikarasjokarasuyamarugam" + + "e-hostrolekamiminers3-external-1xn--ksnes-uuaxn--kvfjord-nxaxn--" + + "kvitsy-fyatsukanumazuryxn--kvnangen-k0axn--l-1fairwindsorocabals" + + "fjordxn--l1accentureklamborghinikis-very-sweetpepperxn--laheadju" + + "-7yatsushiroxn--langevg-jxaxn--lcvr32dxn--ldingen-q1axn--leagavi" + + "ika-52bentleyurihonjournalistgoryusuharavoues3-eu-west-2xn--lesu" + + "nd-huaxn--lgbbat1ad8jelenia-goraxn--lgrd-poacctunkongsbergxn--lh" + + "ppi-xqaxn--linds-pramericanarturystykanoyaltakasakiyokawaraxn--l" + + "ns-qlapyatigorskoseis-a-studentalxn--loabt-0qaxn--lrdal-sraxn--l" + + "renskog-54axn--lt-liaclothingdustkagoshimalselvendrellukowhaling" + + "rossetouchijiwadegreexn--lten-granexn--lury-iraxn--m3ch0j3axn--m" + + "ely-iraxn--merker-kuaxn--mgb2ddesorreisahayakawakamiichikawamisa" + + "toursimple-urlxn--mgb9awbfeiraquarellebesbyglandynulvikasuyanaga" + + "waxn--mgba3a3ejtuscanyxn--mgba3a4f16axn--mgba3a4franamizuholding" + + "smilevangerxn--mgba7c0bbn0axn--mgbaakc7dvfermochizukirkenesbscho" + + "koladenxn--mgbaam7a8hakusandiegooglecodespotrentino-alto-adigexn" + + "--mgbab2bdxn--mgbai9a5eva00beppublishproxyzjampagefrontappalmspr" + + "ingsakerxn--mgbai9azgqp6jeonnamerikawauexn--mgbayh7gpalacexn--mg" + + "bb9fbpobanazawaxn--mgbbh1a71exn--mgbc0a9azcgxn--mgbca7dzdoxn--mg" + + "berp4a5d4a87gxn--mgberp4a5d4arxn--mgbgu82axn--mgbi4ecexposedxn--" + + "mgbpl2fhskoleirfjordxn--mgbqly7c0a67fbcngroundhandlingroznyxn--m" + + "gbqly7cvafranziskanerdpolicexn--mgbt3dhdxn--mgbtf8flatangerxn--m" + + "gbtx2beskidyn-o-saurlandes3-website-ap-northeast-1xn--mgbx4cd0ab" + + "bvieeexn--mix082ferraraxn--mix891ferrarittoguraxn--mjndalen-64ax" + + "n--mk0axindigenaklodzkochikushinonsenergyxn--mk1bu44cnsaobernard" + + "ownloadyndns-picsaogoncartierxn--mkru45is-with-thebandovre-eiker" + + "xn--mlatvuopmi-s4axn--mli-tlaquilanciaxn--mlselv-iuaxn--moreke-j" + + "uaxn--mori-qsakuragawaxn--mosjen-eyawaraxn--mot-tlarvikosherbroo" + + "kegawaxn--mre-og-romsdal-qqbestbuyshouses3-website-ap-southeast-" + + "1xn--msy-ula0haldenxn--mtta-vrjjat-k7afamilycompanycntoystre-sli" + + "drettozawaxn--muost-0qaxn--mxtq1missilezajsklabudhabikinokawabar" + + "thaebaruminamiuonumassa-carrara-massacarraramassabusinessebykleg" + + "allocalhistoryggeelvinckaufenxn--ngbc5azdxn--ngbe9e0axn--ngbrxn-" + + "-3hcrj9cistrondheimmobilienxn--nit225koshimizumakizunokunimimata" + + "kasugais-a-teacherkassymantechnologyxn--nmesjevuemie-tcbaltimore" + + "-og-romsdalpha-myqnapcloudaccesscambridgestoneuesortlandxn--nnx3" + + "88axn--nodessakuraisleofmanchesterxn--nqv7fs00emaxn--nry-yla5gxn" + + "--ntso0iqx3axn--ntsq17gxn--nttery-byaeserveexchangexn--nvuotna-h" + + "waxn--nyqy26axn--o1achattanooganordkappimientakazakis-leetnedalx" + + "n--o3cw4halsaintlouis-a-anarchistoireggiocalabriaxn--o3cyx2axn--" + + "od0algxn--od0aq3betainaboxfusejnynysagaeroclubmedecincinnationwi" + + "dealstahaugesunderseaportsinfolldalabamagasakishimabaraogakibich" + + "uomutashinaindustriesteambulanceu-4xn--ogbpf8flekkefjordxn--oppe" + + "grd-ixaxn--ostery-fyawatahamaxn--osyro-wuaxn--p1acferreroticampo" + + "bassociatestinguovdageaidnuslivinghistoryxn--p1aissmarterthanyou" + + "xn--pbt977coguchikuzenxn--pgbs0dhlxn--porsgu-sta26fetsundynv6xn-" + + "-pssu33lxn--pssy2uxn--q9jyb4collectionxn--qcka1pmckinseyxn--qqqt" + + "11misugitokuyamatsumaebashikshacknetrentino-suedtirolxn--qxamune" + + "ustarhubsoruminternationalfirearmshintokushimaxn--rady-iraxn--rd" + + "al-poaxn--rde-ulavagiskexn--rdy-0nabariwchonanbuildingroks-thisa" + + "yamanobeokakudamatsuexn--rennesy-v1axn--rhkkervju-01aflakstadaok" + + "agakicks-assedicolognextdirectozsdeloittemp-dnsaotomelhusdecorat" + + "iveartsapodlasiellaktyubinskiptveterinairealtorlandyndns-remotew" + + "dyndns-serverdaluroyxn--rholt-mragowoodsideltaitogliattiresouthc" + + "arolinarvikomonoxn--rhqv96gxn--rht27zxn--rht3dxn--rht61exn--risa" + + "-5nativeamericanantiquesouthwestfalenxn--risr-iraxn--rland-uuaxn" + + "--rlingen-mxaxn--rmskog-byaxn--rny31hammarfeastafricapebretonami" + + "crosoftbankautokeinowruzhgorodeoxn--rovu88bhzcasinorddalindaskoy" + + "abearalvahkijobserverisignieznogataijinfinitintuitaxihuanikkoebe" + + "nhavnikolaevents3-website-ap-southeast-2xn--rros-granvindafjordx" + + "n--rskog-uuaxn--rst-0naturalhistorymuseumcenterxn--rsta-francais" + + "eharaxn--rvc1e0am3exn--ryken-vuaxn--ryrvik-byaxn--s-1faithruhere" + + "dumbrellajollamericanexpressexyxn--s9brj9colonialwilliamsburgrpa" + + "rocherkasyno-dsapporoxn--sandnessjen-ogbizxn--sandy-yuaxn--seral" + + "-lraxn--ses554gxn--sgne-gratangenxn--skierv-utazassnasabaerobati" + + "cketsowaxn--skjervy-v1axn--skjk-soaxn--sknit-yqaxn--sknland-fxax" + + "n--slat-5naturalsciencesnaturellespjelkavikomorotsukamiokamikita" + + "yamatsuris-a-socialistcgrouphdxn--slt-elabcgxn--smla-hraxn--smna" + + "-gratis-a-bulls-fanxn--snase-nraxn--sndre-land-0cbremangerxn--sn" + + "es-poaxn--snsa-roaxn--sr-aurdal-l8axn--sr-fron-q1axn--sr-odal-q1" + + "axn--sr-varanger-ggbieigersundivtasvuodnakaniikawatanaguraxauste" + + "vollavangenaval-d-aosta-valleyokotebinagisoccertificationavigati" + + "onavoibestadds3-ca-central-1xn--srfold-byaxn--srreisa-q1axn--sru" + + "m-grazxn--stfold-9xaxn--stjrdal-s1axn--stjrdalshalsen-sqbielawal" + + "terxn--stre-toten-zcbspreadbettingxn--t60b56axn--tckweatherchann" + + "elxn--tiq49xqyjetztrentino-sudtirolxn--tjme-hraxn--tn0agrinet-fr" + + "eakspydebergxn--tnsberg-q1axn--tor131oxn--trany-yuaxn--trgstad-r" + + "1axn--trna-woaxn--troms-zuaxn--tysvr-vraxn--uc0atvaroyxn--uc0ay4" + + "axn--uist22hamurakamigoris-a-libertarianxn--uisz3gxn--unjrga-rta" + + "obaomoriguchiharagusartsrlxn--unup4yxn--uuwu58axn--vads-jraxn--v" + + "ard-jraxn--vegrshei-c0axn--vermgensberater-ctbiellaakesvuemielec" + + "ceverbankareliancevje-og-hornnes3-website-eu-west-1xn--vermgensb" + + "eratung-pwbieszczadygeyachimataikikugawarszawashingtondclkariyam" + + "elbournexn--vestvgy-ixa6oxn--vg-yiabkhaziaxn--vgan-qoaxn--vgsy-q" + + "oa0jevnakershuscultureggioemiliaromagnamsosnowiechoseiroumuenche" + + "nxn--vgu402coloradoplateaudioxn--vhquvbarrell-of-knowledgeometre" + + "-experts-comptables3-us-east-2xn--vler-qoaxn--vre-eiker-k8axn--v" + + "rggt-xqadxn--vry-yla5gxn--vuq861bievatmallorcadaques3-website-sa" + + "-east-1xn--w4r85el8fhu5dnraxn--w4rs40lxn--wcvs22dxn--wgbh1columb" + + "usheyxn--wgbl6axn--xhq521bifukagawashtenawdev-myqnapcloudapplebt" + + "imnetzlgjovikarlsoyusuisserveftpanamatta-varjjatjeldsundivttasvu" + + "otnakanojohanamakinoharaxn--xkc2al3hye2axn--xkc2dl3a5ee0hangglid" + + "ingxn--y9a3aquariumitourismolangevagrarchaeologyeongbukmpspbaref" + + "ootballfinanzgorzeleccoffeedbackplaneapplinziiyamanouchikuhokury" + + "ugasakitchenayorovigovtateshinanomachimkentateyamaustinnavuotnar" + + "ashinobninsk12xn--yer-znaturbruksgymnxn--yfro4i67oxn--ygarden-p1" + + "axn--ygbi2ammxn--3oq18vl8pn36axn--ystre-slidre-ujbihorologyuucon" + + "nectjmaxxxfinityuzawaxn--zbx025dxn--zf0ao64axn--zf0avxn--3pxu8ko" + + "nyvelolxn--zfr164bikedagestangeorgeorgiaxperiaxz" // nodes is the list of nodes. Each node is represented as a uint32, which // encodes the node's children, wildcard bit and node type (as an index into @@ -495,8413 +500,8517 @@ const text = "bifukagawalterbihorologyukuhashimoichinosekigaharaxastronomy-gat" // [15 bits] text index // [ 6 bits] text length var nodes = [...]uint32{ - 0x31fe83, - 0x28e944, - 0x2ed8c6, - 0x380743, - 0x380746, - 0x3a5306, - 0x3b5e43, - 0x30a7c4, - 0x20d0c7, - 0x2ed508, - 0x1a07102, - 0x31f1c7, - 0x368c09, - 0x2d68ca, - 0x2d68cb, - 0x238503, - 0x2dec46, - 0x23d6c5, - 0x1e07542, - 0x21cf84, - 0x266d03, - 0x346145, - 0x22035c2, - 0x20a643, - 0x271f944, - 0x342285, - 0x2a10042, - 0x38a48e, - 0x255083, - 0x3affc6, - 0x2e00142, - 0x2d4207, - 0x240d86, - 0x3204f02, - 0x22ee43, - 0x256204, - 0x32d106, - 0x25b788, - 0x2811c6, - 0x378fc4, - 0x3600242, - 0x33b8c9, - 0x212107, - 0x2e6046, - 0x341809, - 0x2a0048, - 0x33a904, - 0x2a0f46, - 0x21f886, - 0x3a02d42, - 0x3a014f, - 0x28c84e, - 0x21bfc4, - 0x382c85, - 0x30a6c5, - 0x2e2109, - 0x249089, - 0x33b1c7, - 0x23f8c6, - 0x20ae43, - 0x3e01d42, - 0x2e3203, - 0x225d0a, - 0x20cac3, - 0x242f85, - 0x28e142, - 0x28e149, - 0x4200bc2, - 0x209204, - 0x28ad46, - 0x2e5c05, - 0x361644, - 0x4a1a344, - 0x203ec3, - 0x218d04, - 0x4e00702, - 0x2f8e84, - 0x52f5f04, - 0x339bca, - 0x5600f82, - 0x28bc47, - 0x281548, - 0x6206502, - 0x31d0c7, - 0x2c6d44, - 0x2c6d47, - 0x393c45, - 0x35e887, - 0x33af86, - 0x271dc4, - 0x378385, - 0x28ea47, - 0x72001c2, - 0x224143, - 0x200c42, - 0x200c43, - 0x760b5c2, - 0x20f4c5, - 0x7a01d02, - 0x357844, - 0x27e405, - 0x21bf07, - 0x25aece, - 0x2bf044, - 0x23df04, - 0x211c43, - 0x28a4c9, - 0x30eacb, - 0x2ea6c8, - 0x3415c8, - 0x306208, - 0x2b7288, - 0x33a74a, - 0x35e787, - 0x321606, - 0x7e8f282, - 0x36a683, - 0x377683, - 0x37fd44, - 0x3b5e83, - 0x32c343, - 0x1727e02, - 0x8203302, - 0x283f45, - 0x29e006, - 0x2da184, - 0x388547, - 0x2fa686, - 0x389384, - 0x3aa107, - 0x223d43, - 0x86cd5c2, - 0x8a0d342, - 0x8e1e642, - 0x21e646, - 0x9200002, - 0x2501c5, - 0x329343, - 0x201684, - 0x2efb04, - 0x2efb05, - 0x203c43, - 0x979c783, - 0x9a092c2, - 0x291d85, - 0x291d8b, - 0x343c06, - 0x21270b, - 0x226544, - 0x213a49, - 0x2148c4, - 0x9e14b02, - 0x215943, - 0x216283, - 0x1616b42, - 0x275fc3, - 0x216b4a, - 0xa201102, - 0x21d205, - 0x29a88a, - 0x2e0544, - 0x201103, + 0x31a803, + 0x284d84, + 0x382f06, + 0x2f37c3, + 0x2f37c6, + 0x37af86, + 0x3a7a03, + 0x31b604, + 0x322487, + 0x382b48, + 0x1a00742, + 0x32e147, + 0x3672c9, + 0x2b4eca, + 0x2b4ecb, + 0x232183, + 0x2ab9c6, + 0x238485, + 0x1e01482, + 0x203b44, + 0x260543, + 0x201485, + 0x2215842, + 0x332603, + 0x271b0c4, + 0x31fe05, + 0x2a00102, + 0x38194e, + 0x256483, + 0x39cbc6, + 0x2e03d02, + 0x2c8047, + 0x23e146, + 0x3205c42, + 0x257dc3, + 0x257dc4, + 0x357406, + 0x205d08, + 0x277146, + 0x302004, + 0x3600602, + 0x33acc9, + 0x211307, + 0x347986, + 0x3c1109, + 0x2c78c8, + 0x331004, + 0x241286, + 0x230106, + 0x3a00582, + 0x3a234f, + 0x21f4ce, + 0x226484, + 0x2c1545, + 0x31a705, + 0x2f6809, + 0x244689, + 0x357c07, + 0x22bbc6, + 0x206dc3, + 0x3e03942, + 0x21d6c3, + 0x220d4a, + 0x21fbc3, + 0x3bde45, + 0x2f2542, + 0x370749, + 0x4200282, + 0x216c84, + 0x2ef006, + 0x2bb6c5, + 0x2d7c04, + 0x4a14344, + 0x205583, + 0x2374c4, + 0x4e02b82, + 0x267184, + 0x527eac4, + 0x39004a, + 0x5600cc2, + 0x35c447, + 0x2774c8, + 0x6207ec2, + 0x340687, + 0x2bde44, + 0x2bde47, + 0x3b9605, + 0x339407, + 0x31ca86, 0x325384, - 0x21ae03, - 0x21ae04, - 0x21ae07, - 0x21b605, - 0x21d685, - 0x21dc46, - 0x21dfc6, - 0x21ea43, - 0x222688, - 0x206c03, - 0xa60c702, - 0x245848, - 0x23614b, - 0x228908, - 0x228e06, - 0x229dc7, - 0x22da48, - 0xb6024c2, - 0xba430c2, - 0x32da08, - 0x233347, - 0x2e7b45, - 0x2e7b48, - 0x2c3b08, - 0x2be483, - 0x232e04, - 0x37fd82, - 0xbe34382, - 0xc23e102, - 0xca37302, - 0x237303, - 0xce01382, - 0x30a783, - 0x300f44, - 0x20a043, - 0x322844, - 0x20d7cb, - 0x2322c3, - 0x2e6a46, - 0x245f44, - 0x2982ce, - 0x381245, - 0x3b00c8, - 0x263347, - 0x26334a, - 0x22e803, - 0x317a07, - 0x30ec85, - 0x23a384, - 0x272706, - 0x272707, - 0x330f44, - 0x301f87, - 0x25a184, - 0x25b204, - 0x25b206, - 0x25f704, - 0x36bdc6, - 0x216983, - 0x233108, - 0x316ec8, - 0x23dec3, - 0x275f83, - 0x3a6604, - 0x3aae83, - 0xd235f42, - 0xd6df482, - 0x207143, - 0x203f86, - 0x2a1043, - 0x285184, - 0xda165c2, - 0x2165c3, - 0x35f083, - 0x21fe02, - 0xde008c2, - 0x2c9786, - 0x23e347, - 0x2fd645, - 0x38fd04, - 0x294d45, - 0x2f8a47, - 0x2add85, - 0x2e4689, - 0x2e9906, - 0x2ef808, - 0x2fd546, - 0xe20e982, - 0x2ddb08, - 0x300d06, - 0x219205, - 0x316887, - 0x316dc4, - 0x316dc5, - 0x281384, - 0x345d88, - 0xe6127c2, - 0xea04882, - 0x33ca06, - 0x2cf588, + 0x3314c5, + 0x298307, + 0x720fc02, + 0x335a43, + 0x21ab82, + 0x3aae43, + 0x7612442, + 0x27f485, + 0x7a023c2, + 0x293584, + 0x276005, + 0x2263c7, + 0x20974e, + 0x2391c4, + 0x238cc4, + 0x20b583, + 0x364209, + 0x30e2cb, + 0x259e48, + 0x3c0ec8, + 0x316488, + 0x215cc8, + 0x330e4a, + 0x339307, + 0x309d86, + 0x7e6e442, + 0x345243, + 0x355943, + 0x35d344, + 0x3a7a43, + 0x32f6c3, + 0x172a782, + 0x8203102, + 0x27b385, + 0x28df86, + 0x2a9f04, + 0x369187, + 0x23ce86, + 0x3806c4, + 0x3806c7, + 0x205a83, + 0x86c31c2, + 0x8b14902, + 0x8e21182, + 0x221186, + 0x9200882, + 0x286c45, + 0x32bcc3, + 0x3c6444, + 0x2e3804, + 0x2e3805, + 0x2053c3, + 0x96b6c03, + 0x9a09342, + 0x289b05, + 0x289b0b, + 0x20bd06, + 0x331f4b, + 0x22aa44, + 0x20cec9, + 0x20d784, + 0x9e0d9c2, + 0x20ef03, + 0x20fec3, + 0x1610702, + 0x2fb9c3, + 0x21070a, + 0xa200302, + 0x203dc5, + 0x2d400a, + 0x243384, + 0x210f03, + 0x212984, + 0x213b83, + 0x213b84, + 0x213b87, + 0x2153c5, + 0x215705, + 0x216d46, + 0x2170c6, + 0x217d43, + 0x21a708, + 0x212d43, + 0xa6004c2, + 0x22c3c8, + 0x3878cb, + 0x223088, + 0x225f06, + 0x227447, + 0x22a1c8, + 0xb604002, + 0xbaf21c2, + 0x23b388, + 0x3031c7, + 0x207a45, + 0x207a48, + 0x383c48, + 0x2fa9c3, + 0x22f384, + 0x35d382, + 0xbe2f582, + 0xc201bc2, + 0xca30502, + 0x230503, + 0xce03cc2, + 0x31b5c3, + 0x2f1b84, + 0x20bf83, + 0x335e04, + 0x322b8b, + 0x237c03, + 0x2db106, + 0x237c04, + 0x2e21ce, + 0x2669c5, + 0x33d7c8, + 0x251107, + 0x25110a, + 0x2342c3, + 0x34f747, + 0x30e485, + 0x2342c4, + 0x2d4b86, + 0x2d4b87, + 0x2d0204, + 0x37d587, + 0x209a84, + 0x340c44, + 0x340c46, + 0x25d944, + 0x39db46, + 0x207803, + 0x207808, + 0x21a988, + 0x238c83, + 0x2fb983, + 0x3a8c04, + 0x3ae4c3, + 0xd24d5c2, + 0xd6d2fc2, + 0x2083c3, + 0x205646, + 0x241383, + 0x354bc4, + 0xda4b182, + 0x24cb83, + 0x339c03, + 0x218882, + 0xde03c02, + 0x2c0b06, + 0x23c007, + 0x2eab45, + 0x38a504, + 0x2981c5, + 0x27e687, + 0x2d84c9, + 0x2dcd46, + 0x307788, + 0x2eaa46, + 0xe2010c2, + 0x2f1408, + 0x2f3e06, + 0x223a85, + 0x30fe07, + 0x310344, + 0x310345, + 0x2010c4, + 0x2010c8, + 0xe619382, + 0xea02642, + 0x3292c6, + 0x202648, 0x34d485, - 0x351546, - 0x356108, - 0x371488, - 0xee35dc5, - 0xf214f44, - 0x34e247, - 0xf614602, - 0xfa22902, - 0x10e0f882, - 0x28ae45, - 0x2aaa45, - 0x30af86, - 0x350007, - 0x386287, - 0x11638543, - 0x2b0307, - 0x30e7c8, - 0x3a0849, - 0x38a647, - 0x3b9c87, - 0x238788, - 0x238f86, - 0x239e86, - 0x23aacc, - 0x23c08a, - 0x23c407, - 0x23d58b, - 0x23e187, - 0x23e18e, - 0x19a3f304, - 0x240244, - 0x242547, - 0x3ac747, - 0x246d46, - 0x246d47, - 0x247407, - 0x19e29682, - 0x2495c6, - 0x2495ca, - 0x24a08b, - 0x24ac87, - 0x24b845, - 0x24bb83, - 0x24bdc6, - 0x24bdc7, - 0x20d283, - 0x1a206e02, - 0x24c78a, - 0x1a769d02, - 0x1aa4f282, - 0x1ae4dd42, - 0x1b240e82, - 0x24e9c5, - 0x24ef44, - 0x1ba1a442, - 0x2f8f05, - 0x24a683, - 0x2149c5, - 0x2b7184, - 0x205ec4, - 0x25a486, - 0x262586, - 0x291f83, - 0x204844, - 0x3894c3, - 0x1c204c82, - 0x210ac4, - 0x210ac6, - 0x34e7c5, - 0x37e946, - 0x316988, - 0x273544, - 0x266ac8, - 0x398785, - 0x22bc88, - 0x2b2dc6, - 0x26d907, - 0x233d84, - 0x233d86, - 0x242bc3, - 0x393fc3, - 0x211d08, - 0x322004, - 0x356747, - 0x20c7c6, - 0x2dedc9, - 0x322a88, - 0x325448, - 0x331ac4, - 0x35f103, - 0x229942, - 0x1d2234c2, - 0x1d61a202, - 0x36c083, - 0x1da08e02, - 0x20d204, - 0x3521c6, - 0x3b3745, - 0x24fa83, - 0x23cf44, - 0x2b95c7, - 0x25a783, - 0x251208, - 0x218405, - 0x264143, - 0x27e385, - 0x27e4c4, - 0x300a06, - 0x218f84, - 0x21ab86, - 0x21be46, - 0x210584, - 0x23e543, - 0x1de1a582, - 0x23dd05, - 0x20b9c3, - 0x1e20c882, - 0x23aa83, - 0x2231c5, - 0x23cac3, - 0x23cac9, - 0x1e606b82, - 0x1ee07842, - 0x2918c5, - 0x2211c6, - 0x2d9d46, - 0x2bb248, - 0x2bb24b, - 0x203fcb, - 0x220bc5, - 0x2fd845, - 0x2cdfc9, - 0x1600302, - 0x210748, - 0x213d44, - 0x1f601842, + 0x34df06, + 0x350108, + 0x36d548, + 0xee1f8c5, + 0xf21d0c4, + 0x38ca87, + 0xf60d642, + 0xfaefa02, + 0x10e02c42, + 0x2ef105, + 0x373905, + 0x3c1546, + 0x3208c7, + 0x3973c7, + 0x1160be03, + 0x26f507, + 0x2b99c8, + 0x231a09, + 0x381b07, + 0x2321c7, + 0x232b08, + 0x233306, + 0x233dc6, + 0x234a0c, + 0x235e4a, + 0x2364c7, + 0x23834b, + 0x23be47, + 0x23be4e, + 0x1a23d104, + 0x23d744, + 0x23e847, + 0x2616c7, + 0x243806, + 0x243807, + 0x243c87, + 0x1a630a42, + 0x2449c6, + 0x2449ca, + 0x244f4b, + 0x246d07, + 0x2478c5, + 0x247c03, + 0x248146, + 0x248147, + 0x322643, + 0x1aa022c2, + 0x248a4a, + 0x1af68802, + 0x1b24d602, + 0x1b64afc2, + 0x1ba3e242, + 0x24cc85, + 0x24d2c4, + 0x1c204ac2, + 0x267205, + 0x245543, + 0x20d885, + 0x215bc4, + 0x20f984, + 0x209d86, + 0x2505c6, + 0x289d03, + 0x3b6d84, + 0x3ac2c3, + 0x1ca02e02, + 0x3582c4, + 0x3582c6, + 0x38d005, + 0x36e3c6, + 0x30ff08, + 0x227b84, + 0x397848, + 0x399a45, + 0x311708, + 0x36c6c6, + 0x265847, + 0x27b984, + 0x27b986, + 0x26f803, + 0x3917c3, + 0x20b648, + 0x31c684, + 0x354fc7, + 0x2d2906, + 0x2d2909, + 0x20a1c8, + 0x317908, + 0x338884, + 0x2067c3, + 0x23dd42, + 0x1da4c3c2, + 0x1de14202, + 0x207583, + 0x1e20a502, + 0x3225c4, + 0x2440c6, + 0x335b45, + 0x283403, + 0x234ec4, + 0x2b1a07, + 0x336bc3, + 0x37cfc8, + 0x21ea85, + 0x25f7c3, + 0x275f85, + 0x2760c4, + 0x2f9c06, + 0x222704, + 0x225986, + 0x226306, + 0x357d84, + 0x23c203, + 0x1e614582, + 0x238ac5, + 0x2011c3, + 0x1ea05ec2, + 0x2319c3, + 0x21c8c5, + 0x237583, + 0x237589, + 0x1ee01f02, + 0x1f608ac2, + 0x289645, + 0x219286, + 0x37c8c6, + 0x2bfcc8, + 0x2bfccb, + 0x20568b, + 0x21c145, + 0x2ead45, + 0x2c3909, + 0x1603142, + 0x357f48, + 0x23e504, + 0x1fe01b02, + 0x20aac3, + 0x20661886, + 0x224fc8, + 0x20a003c2, + 0x307348, + 0x20e0a6c2, + 0x23994a, + 0x212c8d03, + 0x39f286, + 0x3b5048, + 0x389ac8, + 0x3ba046, + 0x377d47, + 0x3a2547, + 0x23fe0a, + 0x243404, + 0x352f84, + 0x366b89, + 0x21ba1d45, + 0x21f6c6, + 0x200143, + 0x255184, + 0x21e25784, + 0x323307, + 0x22f607, + 0x364044, + 0x2d3345, + 0x3c1608, + 0x37b847, + 0x38fc87, + 0x22208882, + 0x23b9c4, + 0x28e948, + 0x24e244, + 0x252944, + 0x253005, + 0x253147, + 0x22b509, + 0x254004, + 0x2547c9, + 0x254a08, + 0x254f04, + 0x254f07, + 0x226553c3, + 0x255547, + 0x1626d02, + 0x16ad402, + 0x255e86, + 0x2564c7, + 0x256b04, + 0x258487, + 0x258f47, + 0x259783, + 0x329982, + 0x205dc2, + 0x270003, + 0x270004, + 0x27000b, + 0x3c0fc8, + 0x25f184, + 0x25ad05, + 0x25cac7, + 0x25e5c5, + 0x30590a, + 0x25f0c3, + 0x22a12c42, + 0x212c44, + 0x261489, + 0x265183, + 0x265247, + 0x2f61c9, + 0x336308, + 0x25d1c3, + 0x27a247, + 0x27aa89, + 0x26be83, + 0x281b04, + 0x283c89, + 0x287dc6, + 0x2266c3, + 0x2039c2, + 0x241243, + 0x2ad207, + 0x383fc5, + 0x340346, + 0x268984, + 0x2dba05, + 0x220d03, + 0x217f86, + 0x20d0c2, + 0x3a3984, + 0x22e2ab02, + 0x22ab03, + 0x23201802, + 0x252843, + 0x217544, + 0x217547, + 0x3c6746, + 0x255e42, + 0x23629942, + 0x384384, + 0x23a30b82, + 0x23e01a42, + 0x337304, + 0x337305, + 0x201a45, + 0x35ab46, + 0x24208742, + 0x208745, + 0x2100c5, + 0x210ac3, + 0x213d06, + 0x214885, + 0x221102, + 0x34db45, + 0x221104, + 0x227ac3, + 0x227d03, + 0x2460ad82, + 0x298507, + 0x33a504, + 0x33a509, + 0x255084, + 0x281903, + 0x35b109, + 0x281908, + 0x24b0cc04, + 0x30cc06, + 0x2a2c83, + 0x20cb03, + 0x30e843, + 0x24eefe82, + 0x375502, + 0x25201402, + 0x32d8c8, + 0x327088, + 0x3a8046, + 0x2544c5, + 0x34f5c5, + 0x31e0c7, + 0x229985, + 0x25cd82, + 0x25694cc2, + 0x1602202, + 0x240a88, + 0x34e285, + 0x27ca84, + 0x2e7205, + 0x241d87, + 0x25efc4, + 0x248942, + 0x25a2dac2, + 0x33e704, + 0x226ec7, + 0x289fc7, + 0x3393c4, + 0x291003, + 0x238bc4, + 0x238bc8, + 0x234106, + 0x2d4a0a, + 0x22b3c4, + 0x291508, + 0x288204, + 0x227546, + 0x294c84, + 0x2ef406, + 0x33a7c9, + 0x26d007, + 0x34e1c3, + 0x25eebfc2, + 0x331203, + 0x207c82, + 0x2625c982, + 0x30cf06, + 0x371e48, + 0x2a44c7, + 0x2f7209, + 0x290ac9, + 0x2a61c5, + 0x2a73c9, + 0x2a7b85, + 0x2a7cc9, + 0x2a9045, + 0x2aa008, + 0x266598c4, + 0x26a598c7, + 0x232583, + 0x2aa207, + 0x232586, + 0x2aa5c7, + 0x2a0f45, + 0x2ca8c3, + 0x26e35c02, + 0x2ea984, + 0x27230bc2, + 0x276552c2, + 0x2f3ac6, + 0x277445, + 0x2acac7, 0x326403, - 0x1fecdd46, - 0x348e08, - 0x20208b42, - 0x2bdec8, - 0x2060c182, - 0x2bf7ca, - 0x20a3fd03, - 0x203606, - 0x36cc48, - 0x209708, - 0x3b3a46, - 0x37c807, - 0x3a0347, - 0x34daca, - 0x2e05c4, - 0x354d44, - 0x368649, - 0x2139fb45, - 0x28ca46, - 0x210083, - 0x253d44, - 0x2160df44, - 0x20df47, - 0x22c507, - 0x234404, - 0x2df805, - 0x30b048, - 0x375e07, - 0x381007, - 0x21a07602, - 0x32e984, - 0x29b188, - 0x2504c4, - 0x251844, - 0x251c45, - 0x251d87, - 0x222349, - 0x252a04, - 0x253149, - 0x253388, - 0x253ac4, - 0x253ac7, - 0x21e54003, - 0x254187, - 0x1609c42, - 0x16b4a42, - 0x254b86, - 0x2550c7, - 0x255584, - 0x257687, - 0x258d47, - 0x259983, - 0x2f6802, - 0x207d82, - 0x231683, - 0x231684, - 0x23168b, - 0x3416c8, - 0x263c84, - 0x25c985, - 0x25eb47, - 0x260105, - 0x2c8c0a, - 0x263bc3, - 0x22206b02, - 0x206b04, - 0x267189, - 0x26a743, - 0x26a807, - 0x373089, - 0x212508, - 0x2db543, - 0x282f07, - 0x283649, - 0x23d483, - 0x289844, - 0x28d209, - 0x290146, - 0x21c203, - 0x200182, - 0x264d83, - 0x2b4847, - 0x2c3e85, - 0x3413c6, - 0x259004, - 0x374e05, - 0x225cc3, - 0x20e646, - 0x213c42, - 0x3a1784, - 0x2260d382, - 0x226603, - 0x22a01802, - 0x251743, - 0x21e444, - 0x21e447, - 0x201986, - 0x20df02, - 0x22e0dec2, - 0x2c4244, - 0x23235182, - 0x23601b82, - 0x265704, - 0x265705, - 0x345105, - 0x35c386, - 0x23a074c2, - 0x2074c5, - 0x213005, - 0x2157c3, - 0x219d06, - 0x21a645, - 0x21e5c2, - 0x34d0c5, - 0x21e5c4, - 0x228203, + 0x32f644, + 0x2130c3, + 0x23b0c3, + 0x27a07d02, + 0x28206202, + 0x37b084, + 0x329943, + 0x24b905, + 0x28603882, + 0x28e00c42, + 0x2e0586, + 0x31c7c4, + 0x385444, + 0x38544a, + 0x29601342, + 0x38e2ca, + 0x39e948, + 0x29a6ff84, + 0x201fc3, + 0x208c43, + 0x3165c9, + 0x267709, + 0x2a6e06, + 0x29e14bc3, + 0x214bc5, + 0x39434d, + 0x39eb06, + 0x20e84b, + 0x2a200802, + 0x220b88, + 0x2ca1a802, + 0x2ce00942, + 0x2c9a85, + 0x2d205842, + 0x21b147, + 0x2b0747, + 0x214a43, + 0x348148, + 0x2d601102, + 0x29f384, + 0x291203, + 0x325545, + 0x395983, + 0x245646, + 0x223504, + 0x2fb943, + 0x2aec03, + 0x2da03202, + 0x2eacc4, + 0x3af385, + 0x2ace07, + 0x277e03, + 0x2ad9c3, + 0x2ae803, + 0x16ae8c2, + 0x2ae8c3, + 0x2aeb83, + 0x2de0b0c2, + 0x39e304, + 0x2507c6, 0x22a443, - 0x23e11442, - 0x2dcf47, - 0x376084, - 0x376089, - 0x253c44, - 0x2357c3, - 0x300589, - 0x389e08, - 0x242aa8c4, - 0x2aa8c6, - 0x219983, - 0x25d3c3, - 0x323043, - 0x246eebc2, - 0x379b82, - 0x24a17202, - 0x32af48, - 0x358e08, - 0x3a5a46, - 0x2fd0c5, - 0x317885, - 0x333d07, - 0x2247c5, - 0x210642, - 0x24e04742, - 0x160a442, - 0x2447c8, - 0x2dda45, - 0x2bfbc4, - 0x2f2845, - 0x381d87, - 0x240944, - 0x24c682, - 0x25200582, - 0x33ffc4, - 0x21ca07, - 0x292507, - 0x35e844, - 0x29a843, - 0x23de04, - 0x23de08, - 0x23a1c6, - 0x27258a, - 0x222204, - 0x29abc8, - 0x290584, - 0x229ec6, - 0x29c484, - 0x28b146, - 0x376349, - 0x274847, - 0x241243, - 0x256351c2, - 0x2755c3, - 0x214d02, - 0x25a52e42, - 0x313486, - 0x374588, - 0x2ac047, - 0x3ab249, - 0x299f49, - 0x2acf05, - 0x2adec9, - 0x2ae685, - 0x2ae7c9, - 0x2afe45, - 0x2b11c8, - 0x25e0a104, - 0x26259ac7, - 0x2b13c3, - 0x2b13c7, - 0x3ba046, - 0x2b1a47, - 0x2a9b05, - 0x2a2cc3, - 0x26636d02, - 0x339704, - 0x26a42a42, - 0x266603, - 0x26e206c2, - 0x30df06, - 0x2814c5, - 0x2b3cc7, - 0x332043, - 0x32c2c4, - 0x217003, - 0x342c43, - 0x27205e82, - 0x27a0c442, - 0x3a5404, - 0x2f67c3, - 0x24e545, - 0x27e01c82, - 0x286007c2, - 0x2c8286, - 0x322144, - 0x38c444, - 0x38c44a, - 0x28e00942, - 0x38298a, - 0x39b8c8, - 0x29231604, - 0x2046c3, - 0x20d8c3, - 0x306349, - 0x25bd09, - 0x364986, - 0x29655783, - 0x335d45, - 0x30d2cd, - 0x39ba86, - 0x204f4b, - 0x29a02b02, - 0x225b48, - 0x2be22782, - 0x2c203e02, - 0x2b1685, - 0x2c604182, - 0x266847, - 0x21b987, - 0x20bf43, - 0x23b188, - 0x2ca02542, - 0x3780c4, - 0x21a8c3, - 0x348505, - 0x364603, - 0x33c406, - 0x212a84, - 0x275f43, - 0x2b6443, - 0x2ce09942, - 0x2fd7c4, - 0x379c85, - 0x3b6587, - 0x280003, - 0x2b5103, - 0x2b5c03, - 0x1631182, - 0x2b5cc3, - 0x2b63c3, - 0x2d2086c2, - 0x3a2e44, - 0x262786, - 0x34ba83, - 0x2086c3, - 0x2d6b8042, - 0x2b8048, - 0x2b8304, - 0x37ce46, - 0x2b8bc7, - 0x258346, - 0x2a0304, - 0x3b201702, - 0x3b9f0b, - 0x307c0e, - 0x221d4f, - 0x2ac5c3, - 0x3ba64d42, - 0x160b542, - 0x3be00a82, - 0x2e89c3, - 0x2e4903, - 0x2de046, - 0x207986, - 0x203007, - 0x304704, - 0x3c221302, - 0x3c618742, - 0x3a1205, - 0x2e7007, - 0x38c946, - 0x3ca28142, - 0x228144, - 0x2bc743, - 0x3ce09a02, - 0x3d366443, - 0x2bce04, - 0x2c5409, - 0x16cb602, - 0x3d605242, - 0x385d85, - 0x3dacb882, - 0x3de03582, - 0x3541c7, - 0x21b2c9, - 0x368e8b, - 0x3a0105, - 0x2714c9, - 0x384d06, - 0x343c47, - 0x3e206844, - 0x341d89, - 0x380907, - 0x348ac7, - 0x2122c3, - 0x2122c6, - 0x312247, - 0x263a43, - 0x263a46, - 0x3ea01cc2, - 0x3ee022c2, - 0x22bf03, - 0x32bec5, - 0x25a007, - 0x227906, - 0x2c3e05, - 0x207a84, - 0x28ddc5, - 0x2fae04, - 0x3f204bc2, - 0x337447, - 0x2ca604, - 0x24f3c4, - 0x25bc0d, - 0x25d749, - 0x3ab748, - 0x25e044, - 0x234a85, - 0x322907, - 0x3329c4, - 0x2fa747, - 0x204bc5, - 0x3f6ac504, - 0x2b5e05, - 0x269404, - 0x256fc6, - 0x34fe05, - 0x3fa048c2, - 0x2011c4, - 0x2011c5, - 0x3802c6, - 0x206d85, - 0x3c0144, - 0x2cda83, - 0x208d46, - 0x222545, - 0x22b605, - 0x34ff04, - 0x222283, - 0x22228c, - 0x3fe90a82, - 0x40206702, - 0x40600282, - 0x211a83, - 0x211a84, - 0x40a02942, - 0x2fba48, - 0x341485, - 0x34c984, - 0x36ee86, - 0x40e0d842, - 0x41234502, - 0x41601fc2, - 0x2a6a85, - 0x210446, - 0x226144, - 0x32d646, - 0x28ba06, - 0x215c83, - 0x41b2770a, - 0x2f6b05, - 0x2f6fc3, - 0x22a9c6, - 0x30c989, - 0x22a9c7, - 0x29f648, - 0x29ff09, - 0x241b08, - 0x22e546, - 0x209b03, - 0x41e0c202, - 0x395343, - 0x395349, - 0x333608, - 0x42253442, - 0x42604a82, - 0x229443, - 0x2e4505, + 0x2af343, + 0x2e2b0102, + 0x2b0108, + 0x2b03c4, + 0x2ee8c6, + 0x256947, + 0x3845c6, + 0x2a4f04, + 0x3be01ec2, + 0x23244b, + 0x2ff28e, + 0x219e0f, + 0x2c7b83, + 0x3c65fe82, + 0x1647302, + 0x3ca00a82, + 0x25b4c3, + 0x205983, + 0x2d8746, + 0x2f1946, + 0x3c2147, + 0x2f9084, + 0x3ce193c2, + 0x3d21edc2, + 0x2425c5, + 0x2e44c7, + 0x37fd86, + 0x3d64d542, + 0x30de04, + 0x2b7b43, + 0x3da09602, + 0x3df63443, + 0x2b8444, + 0x2bd289, + 0x16c2482, + 0x3e20dd82, + 0x327e05, + 0x3e6c2702, + 0x3ea00682, + 0x352307, + 0x214fc9, + 0x36754b, + 0x3a2305, + 0x26ad09, + 0x37e806, + 0x20bd47, + 0x3ee074c4, + 0x348c89, + 0x337b07, + 0x224c87, + 0x230803, + 0x2afc46, + 0x30a7c7, + 0x20fbc3, + 0x2f0d46, + 0x3f6038c2, + 0x3fa0e402, + 0x3bec83, + 0x32f245, + 0x332807, + 0x222386, + 0x383f45, + 0x2f3f04, + 0x278f45, + 0x2f2144, + 0x3fe00f82, + 0x341587, + 0x2f2984, + 0x26a444, + 0x34694d, + 0x26a449, + 0x230b08, 0x25c404, - 0x2c9ec9, - 0x26eb44, - 0x2e0908, - 0x2050c3, - 0x20dc44, - 0x2acd03, - 0x221208, - 0x25bb47, - 0x42e281c2, - 0x270d02, - 0x388b05, - 0x272dc9, - 0x28cac3, - 0x284bc4, - 0x335d04, - 0x227543, - 0x28580a, - 0x43382842, - 0x43601182, - 0x2cd543, - 0x384f83, - 0x160dc02, - 0x20ffc3, - 0x43a14702, - 0x43e00802, - 0x4420f644, - 0x20f646, - 0x3b6a46, - 0x248c44, - 0x37d243, - 0x200803, - 0x2f60c3, - 0x24a406, - 0x30aa05, - 0x2cd6c7, - 0x343b09, - 0x2d2d85, - 0x2d3f46, - 0x2d4908, - 0x2d4b06, - 0x260ec4, - 0x2a1d8b, - 0x2d8403, - 0x2d8405, - 0x2d8548, - 0x22c2c2, - 0x3544c2, - 0x4464ea42, - 0x44a14642, - 0x221343, - 0x44e745c2, - 0x2745c3, - 0x2d8844, - 0x2d8e03, - 0x45605902, - 0x45a0c0c6, - 0x2af186, - 0x45edcac2, - 0x462162c2, - 0x4662a482, - 0x46a00e82, - 0x46e176c2, - 0x47202ec2, - 0x205383, - 0x344905, - 0x348206, - 0x4761bf84, - 0x34e5ca, - 0x20bd46, - 0x220e04, - 0x28a483, - 0x4820ea42, - 0x204d42, - 0x23d503, - 0x48608e83, - 0x2d8047, - 0x34fd07, - 0x49e31787, - 0x23fcc7, - 0x2309c3, - 0x33188a, - 0x263544, - 0x3863c4, - 0x3863ca, - 0x24b685, - 0x4a2190c2, - 0x254b43, - 0x4a601942, - 0x21b543, - 0x275583, - 0x4ae02b82, - 0x2b0284, - 0x2256c4, - 0x208105, - 0x39e745, - 0x2fc3c6, - 0x2fc746, - 0x4b206802, - 0x4b600982, - 0x3139c5, - 0x2aee92, - 0x259806, - 0x231483, - 0x315a06, - 0x231485, - 0x1616b82, - 0x53a17102, - 0x35fd43, - 0x217103, - 0x35d703, - 0x53e02c82, - 0x38a783, - 0x54205b82, - 0x20cc43, - 0x3a2e88, - 0x231e83, - 0x231e86, - 0x3b0c87, - 0x26c286, - 0x26c28b, - 0x220d47, - 0x339504, - 0x54a00e42, - 0x341305, - 0x54e08e43, - 0x2aec83, - 0x32de85, - 0x331783, - 0x55331786, - 0x2108ca, - 0x2488c3, - 0x240c44, - 0x2cf4c6, - 0x2364c6, - 0x55601a03, - 0x32c187, - 0x364887, - 0x2a3885, - 0x251046, - 0x222583, - 0x57619f43, - 0x57a0cb42, - 0x34bd44, - 0x22c24c, - 0x232f09, - 0x2445c7, - 0x38ad45, - 0x252c84, - 0x25e6c8, - 0x265d45, - 0x57e6c505, - 0x27b709, - 0x2e6103, - 0x24f204, - 0x5821cc82, - 0x221543, - 0x5869bf42, - 0x3bbe86, - 0x16235c2, - 0x58a35b42, - 0x2a6988, - 0x2ac343, - 0x2b5d47, - 0x2daa05, - 0x2e5205, - 0x2e520b, - 0x2e58c6, - 0x2e5406, - 0x2e9006, - 0x232b84, - 0x2e9246, - 0x58eeae88, - 0x246003, - 0x231a43, - 0x231a44, - 0x2ea484, - 0x2eab87, - 0x2ec3c5, - 0x592ec502, - 0x59607082, - 0x207085, - 0x295bc4, - 0x2ef38b, - 0x2efa08, - 0x2998c4, - 0x228182, - 0x59e99842, - 0x350e83, - 0x2efec4, - 0x2f0185, - 0x2f0607, - 0x2f2384, - 0x220c04, - 0x5a204102, - 0x36f5c9, - 0x2f3185, - 0x3a03c5, - 0x2f3e45, - 0x5a621483, - 0x2f4dc4, - 0x2f4dcb, - 0x2f5204, - 0x2f5c0b, - 0x2f6005, - 0x221e8a, - 0x2f7608, - 0x2f780a, - 0x2f7fc3, - 0x2f7fca, - 0x5aa33502, - 0x5ae2fa42, - 0x236903, - 0x5b2f9f02, - 0x2f9f03, - 0x5b71c482, - 0x5bb29ac2, - 0x2fac84, - 0x2227c6, - 0x32d385, - 0x2fd4c3, - 0x320446, - 0x317345, - 0x262a84, - 0x5be06b42, - 0x2ba844, - 0x2cdc4a, - 0x22fd07, - 0x2e5e86, - 0x2612c7, - 0x20c743, - 0x2bce48, - 0x39fd8b, - 0x230305, - 0x2f41c5, - 0x2f41c6, - 0x2ea004, - 0x3bf388, - 0x20e543, - 0x21f784, - 0x21f787, - 0x355746, - 0x344b06, - 0x29810a, - 0x250d44, - 0x250d4a, - 0x5c20c386, - 0x20c387, - 0x25ca07, - 0x27b0c4, - 0x27b0c9, - 0x262445, - 0x2439cb, - 0x2eef43, - 0x21ad43, - 0x5c625b03, - 0x23a584, - 0x5ca00482, - 0x2f70c6, - 0x5cea2a45, - 0x315c45, - 0x258586, - 0x352b04, - 0x5d2044c2, - 0x24bbc4, - 0x5d60b282, - 0x28b5c5, - 0x236c84, - 0x22cb43, - 0x5de17142, - 0x217143, - 0x273e86, - 0x5e204242, - 0x2241c8, - 0x22a844, - 0x22a846, - 0x204dc6, - 0x25ec04, - 0x208cc5, - 0x214e48, - 0x215647, - 0x2159c7, - 0x2159cf, - 0x29b086, - 0x22f483, + 0x335ec5, + 0x20a047, + 0x341144, + 0x23cf47, + 0x204cc5, + 0x402a4e44, + 0x30bcc5, + 0x263e44, + 0x390706, + 0x3206c5, + 0x406291c2, + 0x210fc4, + 0x210fc5, + 0x35d8c6, + 0x343b85, + 0x25d144, + 0x3c6103, + 0x20eb46, + 0x22b705, + 0x22f045, + 0x3207c4, + 0x22b443, + 0x22b44c, + 0x40aacf02, + 0x40e0a5c2, + 0x41201542, + 0x20f003, + 0x20f004, + 0x41604482, + 0x30ae88, + 0x340405, + 0x236184, + 0x243686, + 0x41a0e302, + 0x41e1de42, + 0x422000c2, + 0x2b2cc5, + 0x294346, + 0x229304, + 0x357946, + 0x35c206, + 0x222a83, + 0x4272850a, + 0x26b085, + 0x28b003, + 0x228606, + 0x304789, + 0x228607, + 0x292288, + 0x2c7789, + 0x31d348, + 0x250e46, + 0x209703, + 0x42a6f582, + 0x392c08, + 0x42e54ac2, + 0x43201e42, + 0x20be83, + 0x2d8345, + 0x26ba04, + 0x3b6fc9, + 0x2ee004, + 0x21b388, + 0x20dc03, + 0x323004, + 0x2a5fc3, + 0x2192c8, + 0x346887, + 0x43a25242, + 0x290ec2, + 0x31a685, + 0x39cf89, + 0x21f743, + 0x27bfc4, + 0x394304, + 0x20a0c3, + 0x27d04a, + 0x43f7c0c2, + 0x44210f82, + 0x2c3143, + 0x37ea83, + 0x1600082, + 0x200083, + 0x44603282, + 0x44a05a02, + 0x44e1a484, + 0x322046, + 0x2e07c6, + 0x245e44, + 0x277043, + 0x345c03, + 0x2ec1c3, + 0x2452c6, + 0x341d05, + 0x2c32c7, + 0x2c6445, + 0x2c7d86, + 0x2c8708, + 0x2c8906, + 0x24efc4, + 0x29960b, + 0x2cb583, + 0x2cb585, + 0x2cba08, + 0x21a202, + 0x352602, + 0x4524cd02, + 0x4560d682, + 0x219403, + 0x45a6cd82, + 0x26cd83, + 0x2cbd04, + 0x2cc543, + 0x462168c2, + 0x466d0e06, + 0x25e446, + 0x46ad0f42, + 0x46e0ff02, + 0x47227d42, + 0x4763a3c2, + 0x47a1b5c2, + 0x47e047c2, + 0x20dec3, + 0x358645, + 0x2b6306, + 0x48226444, + 0x38ce0a, + 0x3a0546, + 0x21c384, + 0x277943, + 0x48e02f02, + 0x2032c2, + 0x26fb43, + 0x4920ec83, + 0x2e6747, + 0x3205c7, + 0x4aa70107, + 0x393f87, + 0x22cd03, + 0x3176ca, + 0x251304, + 0x397504, + 0x39750a, + 0x247705, + 0x4ae1f682, + 0x258443, + 0x4b202002, + 0x228803, + 0x3311c3, + 0x4ba02742, + 0x26f484, + 0x220704, + 0x2046c5, + 0x3080c5, + 0x34e4c6, + 0x34e846, + 0x4be53982, + 0x4c201382, + 0x2f8545, + 0x25e152, + 0x33f206, + 0x25e8c3, + 0x39d486, + 0x2a1f45, + 0x1604842, + 0x54610c82, + 0x35e3c3, + 0x210c83, + 0x27e483, + 0x54a0c502, + 0x381c43, + 0x54e06e02, + 0x200843, + 0x39e348, + 0x285603, + 0x2a6046, + 0x23ecc7, + 0x30b986, + 0x30b98b, + 0x21c2c7, + 0x2ea784, + 0x55601c82, + 0x340285, + 0x55a09cc3, + 0x292c83, + 0x239b45, + 0x3175c3, + 0x55f175c6, + 0x3580ca, + 0x245ac3, + 0x23e004, + 0x202586, + 0x223e86, + 0x56241d03, + 0x32f507, + 0x2a6d07, + 0x29ae85, + 0x311986, + 0x22b743, + 0x58e13f43, + 0x59206f02, + 0x21a244, + 0x207609, + 0x240887, + 0x229a85, + 0x247d04, + 0x26c7c8, + 0x273b85, + 0x59676405, + 0x284e49, + 0x347a43, + 0x24d584, + 0x59a0b182, + 0x219603, + 0x59e94742, + 0x299986, + 0x162bac2, + 0x5a2a47c2, + 0x2b2bc8, + 0x3a76c3, + 0x30bc07, + 0x2ce245, + 0x2b2785, + 0x2d8e4b, + 0x2d9846, + 0x2d9046, + 0x2dc486, + 0x279f04, + 0x2dc6c6, + 0x5a6f0248, + 0x237cc3, + 0x201f83, + 0x201f84, + 0x2ddbc4, + 0x2dde87, + 0x2df2c5, + 0x5aadf402, + 0x5ae08302, + 0x208305, + 0x2bb184, + 0x2e298b, + 0x2e3708, + 0x298804, + 0x230982, + 0x5b64e882, + 0x24e883, + 0x2e3f04, + 0x2e41c5, + 0x2e4d07, + 0x2e6d44, + 0x21c184, + 0x5ba057c2, + 0x36b449, + 0x2e84c5, + 0x3a25c5, + 0x2e9045, + 0x5be19543, + 0x2e9d04, + 0x2e9d0b, + 0x2ea0c4, + 0x2ea38b, + 0x2ec105, + 0x219f4a, + 0x2ecec8, + 0x2ed0ca, + 0x2ed983, + 0x2ed98a, + 0x5c21fc42, + 0x5c648602, + 0x209943, + 0x5caf1382, + 0x2f1383, + 0x5cf6c182, + 0x5d32c442, + 0x2f1fc4, + 0x21a846, + 0x357685, + 0x2f3d83, + 0x31adc6, + 0x34f085, + 0x250ac4, + 0x5d600382, + 0x2aefc4, + 0x2c358a, + 0x398a07, + 0x3477c6, + 0x24f3c7, + 0x244a03, + 0x2b8488, + 0x3a1f8b, + 0x2bd905, + 0x27c785, + 0x27c786, + 0x2dd704, + 0x3b5288, + 0x21d343, + 0x230004, + 0x230007, + 0x2f4a06, + 0x31fa06, + 0x2e200a, + 0x254844, + 0x31104a, + 0x5db364c6, + 0x3364c7, + 0x25ad87, + 0x273544, + 0x273549, + 0x250485, + 0x31cf4b, + 0x2e1283, + 0x225b43, + 0x5de20b43, + 0x2344c4, + 0x5e200982, + 0x3a3006, + 0x5e6ca645, + 0x39d6c5, + 0x258c46, + 0x29cd44, + 0x5ea07bc2, + 0x247c44, + 0x5ee16f02, + 0x224645, + 0x23f4c4, + 0x228d83, + 0x5f610cc2, + 0x210cc3, + 0x267b86, + 0x5fa00a02, + 0x2073c8, + 0x228484, + 0x228486, + 0x37f306, + 0x25cb84, + 0x20eac5, + 0x21cfc8, + 0x220f87, + 0x2227c7, + 0x2227cf, + 0x28e846, + 0x309bc3, + 0x398184, + 0x233744, + 0x2101c3, + 0x227684, + 0x34fd84, + 0x5fe030c2, + 0x289a43, + 0x372e83, + 0x60207c02, + 0x25c503, + 0x322683, + 0x21578a, + 0x207c07, + 0x2534cc, + 0x253786, + 0x255246, + 0x256647, + 0x60632f47, + 0x25c889, + 0x22c504, + 0x25eb04, + 0x60a09f82, + 0x60e01282, + 0x2e23c6, + 0x32f304, + 0x2d3146, + 0x2333c8, + 0x239444, + 0x21b186, + 0x37c885, + 0x285048, + 0x205883, + 0x28a685, + 0x290cc3, + 0x3a26c3, + 0x3a26c4, + 0x212c03, + 0x6125fd82, + 0x61603a42, + 0x2e1149, + 0x299885, + 0x2a1084, + 0x2a4a45, + 0x212384, + 0x393607, + 0x353f05, + 0x2702c4, + 0x2702c8, + 0x2e61c6, + 0x2e9f84, + 0x2ede88, + 0x2f27c7, + 0x61a04042, + 0x316244, + 0x210284, + 0x224e87, + 0x61e04044, + 0x2c9002, + 0x6220ed42, + 0x221b83, + 0x2d37c4, + 0x29bb43, + 0x2aacc5, + 0x6262e642, + 0x2fddc5, + 0x23a382, + 0x390c85, + 0x372005, + 0x62a04e02, + 0x339b84, + 0x62e06a42, + 0x3aba46, + 0x3a7346, + 0x39d0c8, + 0x2be888, + 0x2f3a44, + 0x303685, + 0x316049, + 0x2eadc4, + 0x358084, + 0x2b6983, + 0x6320fd85, + 0x2c2547, + 0x21fc84, + 0x3ae54d, + 0x2f4682, + 0x3b35c3, + 0x2f4683, + 0x63601b42, + 0x396e45, + 0x223747, + 0x2b9604, + 0x394047, + 0x2c7989, + 0x2c36c9, + 0x275247, + 0x202bc3, + 0x3a7508, + 0x25b949, + 0x2f5487, + 0x2f5805, + 0x2f6706, + 0x2f6d46, + 0x2f6ec5, + 0x26a545, + 0x63a00d42, + 0x2b7685, + 0x2b3a08, + 0x2c08c6, + 0x63e872c7, + 0x2ec344, + 0x2b8047, + 0x2f9206, + 0x6420a402, + 0x35d5c6, + 0x2fc9ca, + 0x2fd245, + 0x646da942, + 0x64a4eb02, + 0x30ab06, + 0x386548, + 0x64e8a187, + 0x6523c902, + 0x215c43, + 0x20c246, + 0x229144, + 0x3b2f86, + 0x201746, + 0x34290a, + 0x325e45, + 0x3559c6, + 0x39ec43, + 0x39ec44, + 0x202c02, + 0x31c743, + 0x6560f042, + 0x30b743, + 0x38e544, + 0x2b2484, + 0x38668a, + 0x214c43, + 0x277208, + 0x250f0a, + 0x23f747, + 0x300986, + 0x260484, + 0x21c242, + 0x2a3702, + 0x65a02982, + 0x238b83, + 0x25ab47, + 0x202987, + 0x284d04, + 0x3a4f87, + 0x2e4e06, + 0x221287, + 0x303304, + 0x399d85, + 0x292705, + 0x65e1b2c2, + 0x3c50c6, + 0x223443, + 0x22a4c2, + 0x22a4c6, + 0x66222342, + 0x6660e982, + 0x3bb945, + 0x66a27882, + 0x66e01c42, + 0x334e85, + 0x2c51c5, + 0x355a85, + 0x289043, + 0x244185, + 0x2d9907, + 0x2feb45, + 0x370005, + 0x33d8c4, + 0x310806, + 0x381d44, + 0x67202a82, + 0x67ee7585, + 0x2a3ac7, + 0x34f408, + 0x261146, + 0x26114d, + 0x2674c9, + 0x2674d2, + 0x300585, + 0x309f43, + 0x6820c202, + 0x30ee44, + 0x39eb83, + 0x33b0c5, + 0x2fdf05, + 0x68630882, + 0x25f803, + 0x68a51b02, + 0x692d6142, + 0x69602242, + 0x2a1d45, + 0x394183, + 0x3c4f08, + 0x69a0ad42, + 0x69e0c842, + 0x26f446, + 0x317c4a, + 0x20e043, + 0x25d0c3, + 0x337d03, + 0x6aa04182, + 0x78e0c542, + 0x79600d82, + 0x206d02, + 0x35d3c9, + 0x2c18c4, + 0x2a9348, + 0x79af3dc2, + 0x79e01ac2, + 0x2ea5c5, + 0x238788, + 0x39e488, + 0x268b8c, + 0x23f683, + 0x7a263802, + 0x7a611d82, + 0x270d46, + 0x301805, + 0x2787c3, + 0x253c06, + 0x301946, + 0x29bc83, + 0x303b03, + 0x303f46, + 0x304b84, + 0x239a46, + 0x214a05, + 0x214a0a, + 0x24c1c4, + 0x305244, + 0x305b8a, + 0x7aa04982, + 0x24c345, + 0x30798a, + 0x308305, + 0x308bc4, + 0x308cc6, + 0x308e44, + 0x2198c6, + 0x7ae308c2, + 0x2f3446, + 0x341ac5, + 0x325cc7, + 0x3adf46, + 0x256844, + 0x2d2387, + 0x328446, + 0x241a05, + 0x241a07, + 0x3aed07, + 0x3aed0e, + 0x2ebb06, + 0x23ce05, + 0x203f87, + 0x20ff43, + 0x20ff47, + 0x217945, 0x22f484, - 0x36edc4, - 0x213103, - 0x22a004, - 0x2494c4, - 0x5e60fd02, - 0x291cc3, - 0x24bf43, - 0x5ea0d2c2, - 0x22f043, - 0x20d2c3, - 0x21d70a, - 0x2e7d07, - 0x381f0c, - 0x3821c6, - 0x2f5a86, - 0x2f6447, - 0x5ee0e947, - 0x252d49, - 0x245984, - 0x253e04, - 0x5f221382, - 0x5f600a02, - 0x2984c6, - 0x32bf84, - 0x2df606, - 0x239048, - 0x2bf2c4, - 0x266886, - 0x2d9d05, - 0x26e488, - 0x2041c3, - 0x26fd85, - 0x270b03, - 0x3a04c3, - 0x3a04c4, - 0x206ac3, - 0x5fa0e602, - 0x5fe00742, - 0x2eee09, - 0x273885, - 0x276bc4, - 0x27ab05, - 0x217e84, - 0x2c62c7, - 0x36ecc5, - 0x231944, - 0x231948, - 0x2d6206, - 0x2dac04, - 0x2e0788, - 0x2e1fc7, - 0x60202502, - 0x2e6f44, - 0x2131c4, - 0x348cc7, - 0x60602504, - 0x210f82, - 0x60a06742, - 0x227103, - 0x2dfc84, - 0x2b2143, - 0x370645, - 0x60e06d42, - 0x2eeac5, - 0x21b9c2, - 0x35c7c5, - 0x374745, - 0x61204d02, - 0x35f004, - 0x61606182, - 0x266d86, - 0x2a7806, - 0x272f08, - 0x2c7588, - 0x30de84, - 0x2f97c5, - 0x395809, - 0x2fd8c4, - 0x210884, - 0x208483, - 0x61a1f545, - 0x2cb6c7, - 0x28d004, - 0x31288d, - 0x332182, - 0x33f203, - 0x3479c3, - 0x61e00d02, - 0x397dc5, - 0x212cc7, - 0x23fd84, - 0x23fd87, - 0x2a0109, - 0x2cdd89, - 0x277e07, - 0x20f803, - 0x2ba348, - 0x2522c9, - 0x349c47, - 0x355685, - 0x395546, - 0x398bc6, - 0x3aaf05, - 0x25d845, - 0x62209142, - 0x37da45, - 0x2bad08, - 0x2c9546, - 0x626c0d47, - 0x2f6244, - 0x29bb07, - 0x300246, - 0x62a3b442, - 0x37ffc6, - 0x302d4a, - 0x3035c5, - 0x62ee6282, - 0x63260a02, - 0x312586, - 0x2b36c8, - 0x636926c7, - 0x63a04502, - 0x226783, - 0x36a846, - 0x22cf04, - 0x3b0b46, - 0x344e06, - 0x36d78a, - 0x377705, - 0x208806, - 0x2205c3, - 0x2205c4, - 0x203082, - 0x314a43, - 0x63e11ac2, - 0x2f8483, - 0x382c04, - 0x2b3804, - 0x2b380a, - 0x22e603, - 0x281288, - 0x22e60a, - 0x2b4247, - 0x309306, - 0x266c44, - 0x220cc2, - 0x228cc2, - 0x64207002, - 0x23ddc3, - 0x25c7c7, - 0x320707, - 0x28e8c4, - 0x39d147, - 0x2f0706, - 0x21e747, - 0x233484, - 0x398ac5, - 0x2ce485, - 0x6462be42, - 0x231146, - 0x327943, - 0x371742, - 0x383306, - 0x64a08bc2, - 0x64e05082, - 0x3c0985, - 0x6522a202, - 0x65604782, - 0x348085, - 0x39e345, - 0x2088c5, - 0x26f003, - 0x352285, - 0x2e5987, - 0x305cc5, - 0x311985, - 0x3b01c4, - 0x24d486, - 0x264544, - 0x65a00d42, - 0x666f2bc5, - 0x2ab647, - 0x3176c8, - 0x29f806, - 0x29f80d, - 0x2aac09, - 0x2aac12, - 0x359f05, - 0x36f8c3, - 0x66a08882, - 0x314544, - 0x39bb03, - 0x3963c5, - 0x304a45, - 0x66e1a902, - 0x264183, - 0x67231802, - 0x67a43242, - 0x67e1f342, - 0x2ed385, - 0x23fec3, - 0x36d408, - 0x68204382, - 0x686000c2, - 0x2b0246, - 0x35f2ca, - 0x205503, - 0x209f43, - 0x2ef103, - 0x69202642, - 0x77602cc2, - 0x77e0d582, - 0x206442, - 0x37fdc9, - 0x2caa44, - 0x23b488, - 0x782fd502, - 0x78603642, - 0x2f5e45, - 0x23d9c8, - 0x3a2fc8, - 0x25920c, - 0x22fac3, - 0x78a68dc2, - 0x78e0c402, - 0x2d3206, - 0x30a185, - 0x2a7b83, - 0x381c46, - 0x30a2c6, - 0x20d883, - 0x30bc43, - 0x30c146, - 0x30cd84, - 0x29d386, - 0x2d85c5, - 0x30d10a, - 0x2397c4, - 0x30e244, - 0x30f08a, - 0x79203442, - 0x2413c5, - 0x31018a, - 0x310a85, - 0x311344, - 0x311446, - 0x3115c4, - 0x221806, - 0x79611042, - 0x33c0c6, - 0x3b1b45, - 0x3b80c7, - 0x200206, - 0x2de844, - 0x2de847, - 0x327646, - 0x245345, - 0x245347, - 0x3abdc7, - 0x3abdce, - 0x232206, - 0x2fa605, - 0x202447, - 0x216303, - 0x3326c7, - 0x2172c5, - 0x21b0c4, - 0x2343c2, - 0x2432c7, - 0x304784, - 0x383884, - 0x270b8b, - 0x224e03, - 0x2d4c47, - 0x224e04, - 0x2f11c7, - 0x299543, - 0x33dd4d, - 0x398608, - 0x224604, - 0x231845, - 0x312bc5, - 0x313003, - 0x79a0c4c2, - 0x314a03, - 0x314d43, - 0x20f204, - 0x283745, - 0x22a4c7, - 0x220646, - 0x382943, - 0x38344b, - 0x259c8b, - 0x2ac9cb, - 0x2fbd4b, - 0x2c578a, - 0x30e48b, - 0x32420b, - 0x362f0c, - 0x38bf4b, - 0x3bdf51, - 0x3bfd8a, - 0x31604b, - 0x31630c, - 0x31660b, - 0x316b8a, - 0x317c8a, - 0x318c8e, - 0x31930b, - 0x3195ca, - 0x31a9d1, - 0x31ae0a, - 0x31b30b, - 0x31b84e, - 0x31c18c, - 0x31c68b, - 0x31c94e, - 0x31cccc, - 0x31d9ca, - 0x31eccc, - 0x79f1efca, - 0x31f7c8, - 0x320909, - 0x3232ca, - 0x32354a, - 0x3237cb, - 0x326d8e, - 0x327111, - 0x330189, - 0x3303ca, - 0x3313cb, - 0x334a0a, - 0x3354d6, - 0x336e4b, - 0x337b0a, - 0x337f4a, - 0x33a4cb, - 0x33b749, - 0x33e6c9, - 0x33ec8d, - 0x33f2cb, - 0x34040b, - 0x340dcb, - 0x347049, - 0x34768e, - 0x347dca, - 0x3494ca, - 0x349a0a, - 0x34a14b, - 0x34a98b, - 0x34ac4d, - 0x34c50d, - 0x34cd50, - 0x34d20b, - 0x35064c, - 0x3512cb, - 0x353ccb, - 0x35528e, - 0x355e0b, - 0x355e0d, - 0x35ae8b, - 0x35b90f, - 0x35bccb, - 0x35c50a, - 0x35cb49, - 0x35de09, - 0x35e18b, - 0x35e44e, - 0x36020b, - 0x361acf, - 0x36394b, - 0x363c0b, - 0x363ecb, - 0x3643ca, - 0x368a89, - 0x36e04f, - 0x372a8c, - 0x3732cc, - 0x37374e, - 0x373ccf, - 0x37408e, - 0x375690, - 0x375a8f, - 0x37660e, - 0x376f4c, - 0x377252, - 0x379891, - 0x37a18e, - 0x37a94e, - 0x37ae8e, - 0x37b20f, - 0x37b5ce, - 0x37b953, - 0x37be11, - 0x37c24c, - 0x37c54e, - 0x37c9cc, - 0x37de53, - 0x37ead0, - 0x37f30c, - 0x37f60c, - 0x37facb, - 0x38044e, - 0x380d8b, - 0x3816cb, - 0x382fcc, - 0x38b38a, - 0x38b74c, - 0x38ba4c, - 0x38bd49, - 0x38d7cb, - 0x38da88, - 0x38df49, - 0x38df4f, - 0x38f88b, - 0x7a39028a, - 0x391e4c, - 0x393009, - 0x393488, - 0x39368b, - 0x393d8b, - 0x39490a, - 0x394b8b, - 0x3950cc, - 0x396048, - 0x398d4b, - 0x39b1cb, - 0x39ef4e, - 0x3a05cb, - 0x3a1f0b, - 0x3ab94b, - 0x3abc09, - 0x3ac14d, - 0x3b1d4a, - 0x3b2c97, - 0x3b4398, - 0x3b6bc9, - 0x3b7d0b, - 0x3b8fd4, - 0x3b94cb, - 0x3b9a4a, - 0x3ba38a, - 0x3ba60b, - 0x3badd0, - 0x3bb1d1, - 0x3bc00a, - 0x3bd54d, - 0x3bdc4d, - 0x3c05cb, - 0x3c1206, - 0x231243, - 0x7a791143, - 0x26ed86, - 0x248805, - 0x22d287, - 0x3240c6, - 0x1608742, - 0x2c1fc9, - 0x320244, - 0x2e4d48, - 0x210943, - 0x314487, - 0x239202, - 0x2b3d03, - 0x7aa04542, - 0x2d0d06, - 0x2d2104, - 0x37a844, - 0x3443c3, - 0x3443c5, - 0x7b2cb8c2, - 0x7b6aeb44, - 0x27b007, - 0x7ba43282, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x200e03, - 0x207102, - 0x16fb88, - 0x20f882, - 0x323043, - 0x28cac3, - 0x208e83, - 0xe03, - 0x201a03, - 0x215443, - 0x32b7d6, - 0x32ca13, - 0x39cfc9, - 0x34e148, - 0x341189, - 0x310306, - 0x340010, - 0x24c9d3, - 0x355808, - 0x2a0a87, - 0x37d347, - 0x28db0a, - 0x232309, - 0x3961c9, - 0x28664b, - 0x33af86, - 0x20728a, - 0x228e06, - 0x31fe43, - 0x2dce85, - 0x233108, - 0x266e4d, - 0x28af0c, - 0x218c87, - 0x318fcd, - 0x214f44, - 0x23a84a, - 0x23bbca, - 0x23c08a, - 0x24ccc7, - 0x246b87, - 0x24a904, - 0x233d86, - 0x209d44, - 0x2c7ec8, - 0x26eb89, - 0x2bb246, - 0x2bb248, - 0x24d18d, - 0x2cdfc9, - 0x209708, - 0x3a0347, - 0x300fca, - 0x2550c6, - 0x2664c7, - 0x2bd584, - 0x292347, - 0x35180a, - 0x38690e, - 0x2247c5, - 0x29224b, - 0x32f709, - 0x25bd09, - 0x21b7c7, - 0x2936ca, - 0x348c07, - 0x307d49, - 0x20b808, - 0x33420b, - 0x2e4505, - 0x3ab60a, - 0x2734c9, - 0x331d0a, - 0x2d2e0b, - 0x38668b, - 0x2863d5, - 0x30be85, - 0x3a03c5, - 0x2f4dca, - 0x364a8a, - 0x32f487, - 0x2252c3, - 0x298448, - 0x2db34a, - 0x22a846, - 0x252109, - 0x26e488, - 0x2dac04, - 0x2b2149, - 0x2c7588, - 0x2b2d07, - 0x2f2bc6, - 0x2ab647, - 0x376d87, - 0x24a205, - 0x22460c, - 0x231845, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x20f882, - 0x238543, - 0x208e83, - 0x200e03, - 0x201a03, - 0x238543, - 0x208e83, - 0xe03, - 0x231e83, - 0x201a03, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0xe03, - 0x201a03, - 0x16fb88, - 0x20f882, - 0x201742, - 0x23c2c2, - 0x202542, - 0x200542, - 0x2e6dc2, - 0x4638543, - 0x23cac3, - 0x21b583, - 0x323043, - 0x255783, - 0x28cac3, - 0x2dcd86, - 0x208e83, - 0x201a03, - 0x20bdc3, - 0x16fb88, - 0x345b44, - 0x20da07, - 0x2112c3, - 0x2b1684, - 0x208543, - 0x21b843, - 0x323043, - 0x36dc7, - 0x145944, - 0xf183, - 0x145c05, - 0x207102, - 0x19c783, - 0x5a0f882, - 0x1490fc9, - 0x9144d, - 0x9178d, - 0x23c2c2, - 0x31604, - 0x145c49, - 0x200442, - 0x5f4ed48, - 0xf4544, - 0x16fb88, - 0x1409702, - 0x1510cc6, - 0x239283, - 0x2bcc43, - 0x6638543, - 0x23a844, - 0x6a3cac3, - 0x6f23043, - 0x205e82, - 0x231604, - 0x208e83, - 0x301dc3, - 0x2014c2, - 0x201a03, - 0x222dc2, - 0x2fabc3, - 0x204242, - 0x205983, - 0x26e543, - 0x200202, - 0x16fb88, - 0x239283, - 0x301dc3, - 0x2014c2, - 0x2fabc3, - 0x204242, - 0x205983, - 0x26e543, - 0x200202, - 0x2fabc3, - 0x204242, - 0x205983, - 0x26e543, - 0x200202, - 0x238543, - 0x39c783, - 0x238543, - 0x23cac3, - 0x323043, - 0x231604, - 0x255783, - 0x28cac3, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x20cb02, - 0x221483, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x39c783, - 0x20f882, - 0x238543, - 0x23cac3, - 0x323043, - 0x231604, - 0x208e83, - 0x201a03, - 0x355685, - 0x21a902, - 0x207102, - 0x16fb88, - 0x1480cc8, - 0x323043, - 0x20fec1, - 0x201641, - 0x203c01, - 0x201301, - 0x267401, - 0x2ae601, - 0x211341, - 0x28a0c1, - 0x24dfc1, - 0x2fbf81, - 0x200141, + 0x22f5c2, + 0x246087, + 0x2f9104, + 0x244dc4, + 0x290d4b, + 0x220003, + 0x2e58c7, + 0x220004, + 0x2e6047, + 0x2903c3, + 0x33ca0d, + 0x3998c8, + 0x2297c4, + 0x2701c5, + 0x30b205, + 0x30b643, + 0x7b228382, + 0x30d5c3, + 0x30da83, + 0x321c04, + 0x27ab85, + 0x3c5247, + 0x39ecc6, + 0x37c1c3, + 0x22a60b, + 0x30e04b, + 0x2a5c8b, + 0x2fa5cb, + 0x2bd60a, + 0x30548b, + 0x3245cb, + 0x360a8c, + 0x384f4b, + 0x3c4351, + 0x3c5d4a, + 0x30f5cb, + 0x30f88c, + 0x30fb8b, + 0x31010a, + 0x311bca, + 0x312bce, + 0x31324b, + 0x31350a, + 0x3145d1, + 0x314a0a, + 0x314f0b, + 0x31544e, + 0x315d8c, + 0x316b8b, + 0x316e4e, + 0x3171cc, + 0x318d4a, + 0x31a04c, + 0x7b71a34a, + 0x31af48, + 0x31ba49, + 0x32368a, + 0x32390a, + 0x323b8b, + 0x328b4e, + 0x328ed1, + 0x330349, + 0x33058a, + 0x330bcb, + 0x332a4a, + 0x333296, + 0x334b8b, + 0x33784a, + 0x33818a, + 0x33908b, + 0x33ab49, + 0x33d389, + 0x33de0d, + 0x33e48b, + 0x33f38b, + 0x33fd4b, + 0x343d49, + 0x34438e, + 0x34500a, + 0x34a4ca, + 0x34a7ca, + 0x34afcb, + 0x34b80b, + 0x34bacd, + 0x34d18d, + 0x34d7d0, + 0x34dc8b, + 0x34f9cc, + 0x34fe8b, + 0x351e0b, + 0x35344e, + 0x353a0b, + 0x353a0d, + 0x35964b, + 0x35a0cf, + 0x35a48b, + 0x35acca, + 0x35b3c9, + 0x35ba89, + 0x35cd4b, + 0x35d00e, + 0x35e88b, + 0x35f64f, + 0x36160b, + 0x3618cb, + 0x361b8b, + 0x36238a, + 0x367149, + 0x36a18f, + 0x36f54c, + 0x37038c, + 0x37108e, + 0x37158f, + 0x37194e, + 0x3722d0, + 0x3726cf, + 0x3731ce, + 0x373f8c, + 0x374292, + 0x375211, + 0x375a0e, + 0x375e8e, + 0x3763ce, + 0x37674f, + 0x376b0e, + 0x376e93, + 0x377351, + 0x37778c, + 0x377a8e, + 0x377f0c, + 0x378513, + 0x378ed0, + 0x37970c, + 0x379a0c, + 0x379ecb, + 0x37ac8e, + 0x37b18b, + 0x37b5cb, + 0x37ca4c, + 0x3825ca, + 0x38474c, + 0x384a4c, + 0x384d49, + 0x387e0b, + 0x3880c8, + 0x388889, + 0x38888f, + 0x38a08b, + 0x7bb8afca, + 0x38e8cc, + 0x38fa89, + 0x390a48, + 0x39100b, + 0x39158b, + 0x39220a, + 0x39248b, + 0x39298c, + 0x393d48, + 0x39a40b, + 0x39d80b, + 0x3a114e, + 0x3a27cb, + 0x3a410b, + 0x3ae88b, + 0x3aeb49, + 0x3af08d, + 0x3b368a, + 0x3b45d7, + 0x3b5cd8, + 0x3b9749, + 0x3bb58b, + 0x3bc1d4, + 0x3bc6cb, + 0x3bcc4a, + 0x3bd14a, + 0x3bd3cb, + 0x3bf610, + 0x3bfa11, + 0x3c00ca, + 0x3c394d, + 0x3c404d, + 0x3c61cb, + 0x3c6a06, + 0x3c51c3, + 0x7bf74a03, + 0x2dd1c6, + 0x245a05, + 0x252087, + 0x324486, + 0x1601182, + 0x2cbe89, + 0x31abc4, + 0x2d8988, + 0x220a83, + 0x30ed87, + 0x201c02, + 0x2acb03, + 0x7c200dc2, + 0x2c4946, + 0x2c5c84, + 0x21a604, + 0x349a43, + 0x349a45, + 0x7cac2742, + 0x7cea8044, + 0x273487, + 0x7d22f442, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x20ae43, + 0x200742, + 0xcd588, + 0x202c42, + 0x30e843, + 0x21f743, + 0x20ec83, + 0xae43, + 0x241d03, + 0x207c03, + 0x32eb56, + 0x356d13, + 0x3a4e09, + 0x38c988, + 0x340109, + 0x307b06, + 0x33e750, + 0x248c93, + 0x2f4ac8, + 0x2a5687, + 0x2b6f87, + 0x278c8a, + 0x38e5c9, + 0x342549, + 0x28b30b, + 0x31ca86, + 0x20850a, + 0x225f06, + 0x31a7c3, + 0x298445, + 0x207808, + 0x3abb0d, + 0x2ef1cc, + 0x35cac7, + 0x312f0d, + 0x21d0c4, + 0x23478a, + 0x23598a, + 0x235e4a, + 0x21fa07, + 0x243507, + 0x245fc4, + 0x27b986, + 0x3264c4, + 0x2e01c8, + 0x2ee049, + 0x2bfcc6, + 0x2bfcc8, + 0x24944d, + 0x2c3909, + 0x389ac8, + 0x3a2547, + 0x2f1c0a, + 0x2564c6, + 0x260fc7, + 0x306a04, + 0x214707, + 0x3105ca, + 0x378a0e, + 0x229985, + 0x3bfe0b, + 0x300389, + 0x267709, + 0x2b0587, + 0x3694ca, + 0x224dc7, + 0x2ff3c9, + 0x31e5c8, + 0x239e8b, + 0x2d8345, + 0x2309ca, + 0x227b09, + 0x3abe0a, + 0x2c64cb, + 0x21460b, + 0x28b095, + 0x306745, + 0x3a25c5, + 0x2e9d0a, + 0x2a6f0a, + 0x300107, + 0x2388c3, + 0x2e2348, + 0x2cf00a, + 0x228486, + 0x25b789, + 0x285048, + 0x2e9f84, + 0x29bb49, + 0x2be888, + 0x36c607, + 0x2e7586, + 0x2a3ac7, + 0x2ac6c7, + 0x2450c5, + 0x2297cc, + 0x2701c5, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x202c42, + 0x20be03, + 0x20ec83, + 0x20ae43, + 0x241d03, + 0x20be03, + 0x20ec83, + 0xae43, + 0x285603, + 0x241d03, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0xae43, + 0x241d03, + 0xcd588, + 0x202c42, + 0x209d42, + 0x236082, + 0x201102, + 0x2013c2, + 0x2db482, + 0x460be03, + 0x237583, + 0x203d43, + 0x30e843, + 0x214bc3, + 0x21f743, + 0x2d1206, + 0x20ec83, + 0x241d03, + 0x238843, + 0xcd588, + 0x323584, + 0x322dc7, + 0x34a403, + 0x2402c4, + 0x21b903, + 0x283cc3, + 0x30e843, + 0x15da87, + 0x1221c4, + 0x121b83, + 0xf45, + 0x200742, + 0xb6c03, + 0x5a02c42, + 0x1488d09, + 0x891cd, + 0x8950d, + 0x236082, + 0x6ff84, + 0xf89, + 0x200342, + 0x5f8d588, + 0xe9484, + 0xcd588, + 0x1426502, + 0x1508546, + 0x233603, + 0x2b8283, + 0x660be03, + 0x234784, + 0x6a37583, + 0x6f0e843, + 0x207d02, + 0x26ff84, + 0x20ec83, + 0x2fbbc3, + 0x2056c2, + 0x241d03, + 0x21c4c2, + 0x2f1f03, + 0x200a02, + 0x29d2c3, + 0x26f883, + 0x20fc42, + 0xcd588, + 0x233603, + 0x2fbbc3, + 0x2056c2, + 0x2f1f03, + 0x200a02, + 0x29d2c3, + 0x26f883, + 0x20fc42, + 0x2f1f03, + 0x200a02, + 0x29d2c3, + 0x26f883, + 0x20fc42, + 0x20be03, + 0x2b6c03, + 0x20be03, + 0x237583, + 0x30e843, + 0x26ff84, + 0x214bc3, + 0x21f743, + 0x226444, + 0x20ec83, + 0x241d03, + 0x204bc2, + 0x219543, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x2b6c03, + 0x202c42, + 0x20be03, + 0x237583, + 0x30e843, + 0x26ff84, + 0x20ec83, + 0x241d03, + 0x2f5805, + 0x230882, + 0x200742, + 0xcd588, + 0x1455908, + 0x1367ca, + 0x30e843, 0x200001, - 0x131645, - 0x16fb88, - 0x2008c1, - 0x201781, + 0x202081, + 0x200ec1, + 0x200f01, + 0x200f41, + 0x20d701, + 0x312181, + 0x203801, + 0x24b241, + 0x2021c1, + 0x200101, 0x200301, - 0x200081, - 0x200181, - 0x200401, + 0x117485, + 0xcd588, + 0x200781, + 0x2014c1, 0x200041, - 0x2086c1, - 0x200101, - 0x200281, - 0x200801, - 0x200981, - 0x200441, - 0x204101, - 0x2227c1, + 0x200141, + 0x201401, + 0x200901, + 0x200541, + 0x200c01, + 0x200a81, + 0x200641, + 0x200081, + 0x2001c1, 0x200341, - 0x200741, + 0x201681, + 0x20ab41, 0x2002c1, - 0x2000c1, - 0x203441, - 0x200201, - 0x200c81, - 0x2005c1, - 0x204541, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x20f882, - 0x238543, - 0x23cac3, - 0x200442, - 0x201a03, - 0x36dc7, - 0x8cbc7, - 0x24386, - 0x44f4a, - 0x906c8, - 0x5c288, - 0x5c6c7, - 0xffc6, - 0xe1d45, - 0x11205, - 0x86286, - 0x12cf06, - 0x286644, - 0x31cf87, - 0x16fb88, - 0x2de944, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x238543, - 0x23cac3, - 0x21b583, - 0x323043, - 0x255783, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x21a902, - 0x2ba8c3, - 0x242043, - 0x2cc103, - 0x202d42, - 0x33eb43, - 0x203ec3, - 0x20fc03, - 0x200001, - 0x2ed0c5, - 0x203c43, - 0x226544, - 0x332083, - 0x322103, - 0x222903, - 0x383283, - 0xaa38543, - 0x240244, - 0x24ac83, - 0x207583, - 0x2228c3, - 0x23aa83, - 0x23cac3, - 0x23c803, - 0x202103, - 0x2aab03, - 0x322083, - 0x2bdec3, - 0x20df43, - 0x255684, - 0x257307, - 0x2f6802, - 0x25c003, - 0x263783, - 0x27e983, - 0x20fe03, - 0x20dec3, - 0xaf23043, - 0x209ac3, - 0x204c03, - 0x231603, - 0x34bc85, - 0x209c83, - 0x304d43, - 0xb207a83, - 0x374803, - 0x213643, - 0x229443, - 0x28cac3, - 0x22c2c2, - 0x20c0c3, - 0x208e83, - 0x1600e03, - 0x22b1c3, - 0x2014c3, - 0x21a743, - 0x201a03, - 0x36ea03, - 0x223583, - 0x221483, - 0x233503, - 0x30bcc3, - 0x2fad83, - 0x317345, - 0x20c843, - 0x2df706, - 0x2fadc3, - 0x349703, - 0x2205c4, - 0x20c9c3, - 0x386603, - 0x2f1a03, - 0x20bdc3, - 0x21a902, - 0x22fac3, - 0x30e403, - 0x30fac4, - 0x383884, - 0x21a5c3, - 0x16fb88, - 0x207102, - 0x200242, - 0x202d42, - 0x20cac2, - 0x201d02, - 0x201442, - 0x23de42, - 0x201842, - 0x207b02, - 0x201fc2, - 0x2281c2, - 0x214642, - 0x2745c2, - 0x20cb42, - 0x2e6dc2, - 0x21cc82, - 0x225b82, - 0x204102, - 0x2204c2, - 0x205842, - 0x200482, - 0x221dc2, - 0x2044c2, - 0x20d2c2, - 0x200a02, - 0x21f542, - 0x204782, - 0x7102, - 0x242, - 0x2d42, - 0xcac2, - 0x1d02, - 0x1442, - 0x3de42, - 0x1842, - 0x7b02, - 0x1fc2, - 0x281c2, - 0x14642, - 0x745c2, - 0xcb42, - 0xe6dc2, - 0x1cc82, - 0x25b82, - 0x4102, - 0x204c2, - 0x5842, - 0x482, - 0x21dc2, - 0x44c2, - 0xd2c2, - 0xa02, - 0x1f542, - 0x4782, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x2442, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x20f882, - 0x201a03, - 0xc638543, - 0x323043, - 0x28cac3, - 0x1a3443, - 0x219302, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x1a3443, - 0x201a03, - 0x4542, - 0x201c02, - 0x1442b45, - 0x232282, - 0x16fb88, - 0xf882, - 0x209d82, - 0x209b02, - 0x20ddc2, - 0x2190c2, - 0x206802, - 0x11205, - 0x201282, - 0x2014c2, - 0x202c82, - 0x200dc2, - 0x21cc82, - 0x3951c2, - 0x206742, - 0x260a42, - 0x36dc7, - 0x1501cd, - 0xe1dc9, - 0x5900b, - 0xe5848, - 0x56809, - 0x106046, - 0x323043, - 0x16fb88, - 0x145944, - 0xf183, - 0x145c05, - 0x16fb88, - 0x5d3c6, - 0x145c49, - 0x126447, - 0x207102, - 0x286644, - 0x20f882, - 0x238543, - 0x201742, - 0x23cac3, - 0x207b02, - 0x2de944, - 0x255783, - 0x253442, - 0x208e83, - 0x200442, - 0x201a03, - 0x3a03c6, - 0x323d8f, - 0x7156c3, - 0x16fb88, - 0x20f882, - 0x21b583, - 0x323043, - 0x28cac3, - 0xe03, - 0x152e1cb, - 0xe2648, - 0x14b7aca, - 0x14f5907, - 0x8dbcb, - 0x149785, - 0x36dc7, - 0x20f882, - 0x238543, - 0x323043, - 0x208e83, - 0x207102, - 0x200b42, - 0x2092c2, - 0xfe38543, - 0x248582, - 0x23cac3, - 0x209c42, - 0x20d382, - 0x323043, - 0x210642, - 0x259c42, - 0x2aeb02, - 0x2006c2, - 0x295e02, - 0x203102, + 0x200a01, + 0x200401, + 0x200441, + 0x201ac1, + 0x203f81, + 0x20d601, + 0x201181, + 0x200dc1, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x202c42, + 0x20be03, + 0x237583, + 0x200342, + 0x241d03, + 0x15da87, + 0x1f847, + 0x29546, + 0x4160a, + 0x88348, + 0x5a588, + 0x5aa47, + 0x86, + 0xd61c5, + 0x14a345, + 0x7dac6, + 0x157206, + 0x28b304, + 0x340547, + 0xcd588, + 0x2d2484, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x31a548, + 0x31e084, + 0x2374c4, + 0x22aa44, + 0x270c47, + 0x2cde07, + 0x20be03, + 0x23d74b, + 0x31b7ca, + 0x31cd47, + 0x2fc048, + 0x3255c8, + 0x237583, + 0x346c47, + 0x203d43, + 0x37c208, + 0x335049, + 0x26ff84, + 0x214bc3, + 0x2dce48, + 0x21f743, + 0x2cb6ca, + 0x2d1206, + 0x3a0547, + 0x20ec83, + 0x2da606, + 0x309308, + 0x241d03, + 0x28d806, + 0x2e394d, + 0x2e49c8, + 0x2ea0cb, + 0x331e86, + 0x348087, + 0x20f605, + 0x2ef98a, + 0x22bfc5, + 0x36210a, + 0x230882, + 0x203f83, + 0x244dc4, + 0x2021c6, + 0x3a7a03, + 0x2af043, + 0x24be43, + 0x23b003, + 0x349183, + 0x200582, + 0x2d7285, + 0x2a6589, + 0x245743, + 0x205583, + 0x202fc3, + 0x200301, + 0x2a1a85, + 0x39da83, + 0x2053c3, + 0x22aa44, + 0x326443, + 0x214948, + 0x2ec443, + 0x302e8d, + 0x2ebbc8, + 0x21ab46, + 0x31c783, + 0x378983, + 0x381cc3, + 0xaa0be03, + 0x236dc8, + 0x23d744, + 0x246d03, + 0x2022c6, + 0x249bc8, + 0x202e03, + 0x2ef9c3, + 0x2319c3, + 0x237583, + 0x21d8c3, + 0x21e903, + 0x21a303, + 0x31c703, + 0x2b25c3, + 0x225783, + 0x370645, + 0x256c04, + 0x258107, + 0x329982, + 0x25a303, + 0x25d486, + 0x25ed03, + 0x25f3c3, + 0x276543, + 0x202043, + 0x323283, + 0x269687, + 0xaf0e843, + 0x2363c3, + 0x2096c3, + 0x204d03, + 0x26ff83, + 0x2f3783, + 0x374ac5, + 0x363fc3, + 0x246889, + 0x20b0c3, + 0x2fe203, + 0xb2527c3, + 0x286d03, + 0x21cd08, + 0x2a64c6, + 0x200706, + 0x29aa46, + 0x27a5c7, + 0x200c83, + 0x20be83, + 0x21f743, + 0x288446, + 0x21a202, + 0x29ea43, + 0x32dd05, + 0x20ec83, + 0x2a2e47, + 0x160ae43, + 0x24e483, + 0x21fa83, + 0x225e03, + 0x241d03, + 0x212e46, + 0x31d286, + 0x36aa43, + 0x22ba83, + 0x219543, + 0x253743, + 0x303b83, + 0x2f0603, + 0x2f20c3, + 0x34f085, + 0x24f3c3, + 0x2d3246, + 0x23eb08, + 0x225b43, + 0x341789, + 0x33a308, + 0x2110c8, + 0x21a185, + 0x32a38a, + 0x35400a, + 0x37cd8b, + 0x37d408, + 0x2fb903, + 0x2f2103, + 0x33b1c3, + 0x366d88, + 0x2f4e83, + 0x39ec44, + 0x261983, + 0x202983, + 0x22d483, + 0x26fcc3, + 0x238843, + 0x230882, + 0x22d0c3, + 0x23f683, + 0x305403, + 0x3065c4, + 0x244dc4, + 0x3be143, + 0xcd588, + 0x200742, + 0x200602, + 0x200582, + 0x203402, + 0x2023c2, 0x200782, - 0x2351c2, - 0x2335c2, - 0x252e42, - 0x2b5102, - 0x2d2942, - 0x327982, - 0x2111c2, - 0x28cac3, - 0x200802, - 0x208e83, - 0x24d382, - 0x289e82, - 0x201a03, - 0x2485c2, - 0x20d2c2, - 0x221382, + 0x238c02, + 0x201b02, + 0x202542, + 0x2000c2, + 0x225242, + 0x20d682, + 0x26cd82, + 0x206f02, + 0x2db482, + 0x20b182, + 0x201f82, + 0x2057c2, + 0x2f5f42, + 0x208102, + 0x200982, + 0x219e82, + 0x207bc2, + 0x207c02, + 0x201282, + 0x20fd82, + 0x201c42, + 0x742, + 0x602, + 0x582, + 0x3402, + 0x23c2, + 0x782, + 0x38c02, + 0x1b02, + 0x2542, + 0xc2, + 0x25242, + 0xd682, + 0x6cd82, + 0x6f02, + 0xdb482, + 0xb182, + 0x1f82, + 0x57c2, + 0xf5f42, + 0x8102, + 0x982, + 0x19e82, + 0x7bc2, + 0x7c02, + 0x1282, + 0xfd82, + 0x1c42, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x3f82, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x202c42, + 0x241d03, + 0xc60be03, + 0x30e843, + 0x21f743, + 0xaff03, + 0x223b82, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0xaff03, + 0x241d03, + 0xdc2, + 0x142f49, + 0x202382, + 0x15bda05, + 0x2eaa02, + 0xcd588, + 0x2c42, + 0x23bfc2, + 0x200482, + 0x244482, + 0x21f682, + 0x253982, + 0x14a345, + 0x203082, + 0x2056c2, + 0x20c502, + 0x203042, + 0x20b182, + 0x392a82, + 0x20ed42, + 0x24eb42, + 0x15da87, + 0x120a8d, + 0xd6249, + 0x6898b, + 0xd97c8, + 0x60b89, + 0xfeec6, + 0x30e843, + 0xcd588, + 0x1221c4, + 0x121b83, + 0xf45, + 0xcd588, + 0x5b646, + 0xf89, + 0xab07, 0x200742, - 0x204d02, - 0x2e6282, - 0x22be42, - 0x231802, - 0x2312c2, - 0x3195ca, - 0x35c50a, - 0x39090a, - 0x3c1382, - 0x208a82, - 0x212a42, - 0x10223fc9, - 0x1072c38a, - 0x1438547, - 0x10a02482, - 0x1416dc3, - 0x12c2, - 0x12c38a, - 0x252044, - 0x11238543, - 0x23cac3, - 0x253384, - 0x323043, - 0x231604, - 0x255783, - 0x28cac3, - 0x208e83, - 0xe3bc5, - 0x200e03, - 0x201a03, - 0x20c843, - 0x202443, - 0x16fb88, - 0x140ff44, - 0x1441c5, - 0x12620a, - 0x11ec42, - 0x1affc6, - 0x35ad1, - 0x11a23fc9, - 0x144248, - 0x10b388, - 0x8cf47, - 0xbc2, - 0x13164b, - 0x1b320a, - 0x71ca, - 0x26547, - 0x16fb88, - 0x114008, - 0x14507, - 0x17c2198b, - 0x23087, - 0xc702, - 0x5b907, - 0x1920a, - 0x8cc4f, - 0x4f70f, - 0x22902, - 0xf882, - 0xaaa48, - 0xe228a, - 0x6a08, - 0x64b88, - 0xdfbc8, - 0x4c82, - 0x42bcf, - 0xa670b, - 0xf8d08, - 0x3e607, - 0x185b8a, - 0x3af8b, - 0x57f89, - 0x185a87, - 0x6908, - 0x1089cc, - 0x81a87, - 0x1a800a, - 0xdd088, - 0x1aafce, - 0x2438e, - 0x2638b, - 0x27bcb, - 0x2920b, - 0x2c049, - 0x2ff8b, - 0x31ccd, - 0x329cb, - 0x62b4d, - 0x62ecd, - 0xfa44a, - 0x1836cb, - 0x3b64b, - 0x47085, - 0x1802cc10, - 0x12d40f, - 0x12db4f, - 0x37a4d, - 0xbf490, - 0xc182, - 0x18623a08, - 0x8ca48, - 0x18af52c5, - 0x52a0b, - 0x11f3d0, - 0x5ad08, - 0x6b0a, - 0x27d89, - 0x6b307, - 0x6b647, - 0x6b807, - 0x6bb87, - 0x6ca87, - 0x6d487, - 0x6ddc7, - 0x6e187, - 0x6f187, - 0x6f487, - 0x70147, - 0x70307, - 0x704c7, + 0x28b304, + 0x202c42, + 0x20be03, + 0x209d42, + 0x237583, + 0x202542, + 0x2d2484, + 0x214bc3, + 0x254ac2, + 0x20ec83, + 0x200342, + 0x241d03, + 0x3a25c6, + 0x32414f, + 0x70ec03, + 0xcd588, + 0x202c42, + 0x203d43, + 0x30e843, + 0x21f743, + 0xae43, + 0x14ef74b, + 0x141650a, + 0x14eca47, + 0x78d4b, + 0xd7e45, + 0x15da87, + 0x202c42, + 0x20be03, + 0x30e843, + 0x20ec83, + 0x200742, + 0x211a42, + 0x209342, + 0xfe0be03, + 0x2442c2, + 0x237583, + 0x226d02, + 0x22ab02, + 0x30e843, + 0x25cd82, + 0x251942, + 0x2a8002, + 0x211742, + 0x28d302, + 0x2029c2, + 0x200902, + 0x2ebfc2, + 0x278142, + 0x25c982, + 0x2ad9c2, + 0x2fcdc2, + 0x223482, + 0x23d082, + 0x21f743, + 0x205a02, + 0x20ec83, + 0x211e82, + 0x2c9fc2, + 0x241d03, + 0x2457c2, + 0x207c02, + 0x209f82, + 0x203a42, + 0x204e02, + 0x2da942, + 0x21b2c2, + 0x251b02, + 0x2234c2, + 0x31350a, + 0x35acca, + 0x38bf0a, + 0x3c6b82, + 0x20f2c2, + 0x374a82, + 0x103358c9, + 0x1072f70a, + 0x14328c7, + 0x10a03fc2, + 0x1410983, + 0x3342, + 0x12f70a, + 0x253404, + 0x1120be03, + 0x237583, + 0x254a04, + 0x30e843, + 0x26ff84, + 0x214bc3, + 0x21f743, + 0x20ec83, + 0x1aec5, + 0x20ae43, + 0x241d03, + 0x24f3c3, + 0x203f83, + 0xcd588, + 0x1400004, + 0x149845, + 0x142f49, + 0xa8ca, + 0x119fc2, + 0x19cbc6, + 0x187251, + 0x11b358c9, + 0x1498c8, + 0x1c1948, + 0x1fbc7, + 0x282, + 0x11748b, + 0x18c40a, + 0x844a, + 0x2aa47, + 0xcd588, + 0x10c788, + 0xd547, + 0x18419a4b, + 0x1c787, + 0x4c2, + 0x5e87, + 0x23a8a, + 0x1f8cf, + 0x8308f, + 0xefa02, + 0x2c42, + 0x173908, + 0xf698a, + 0x12b48, + 0x5fcc8, + 0xd3708, + 0x2e02, + 0x1bda8f, + 0x9dc8b, + 0x7e948, + 0x3c2c7, + 0x127c0a, + 0xf400b, + 0x78449, + 0x127b07, + 0x12a48, + 0x1541cc, + 0x3a347, + 0x17a28a, + 0x67008, + 0xf6f8e, + 0x2954e, + 0x2a88b, + 0x2e28b, + 0x30e8b, + 0x50b89, + 0xe32cb, + 0xeb5cd, + 0x17d18b, + 0x198c8d, + 0x19900d, + 0x3cc4a, + 0x44c0b, + 0x4638b, + 0x49ec5, + 0x18828e50, + 0x15770f, + 0x3b4cf, + 0xfb1cd, + 0x39610, + 0xa6c2, + 0x18e071c8, + 0x1f6c8, + 0x192ec405, + 0x5400b, + 0x12e350, + 0x59c88, + 0x12c4a, + 0x2e449, + 0x66007, + 0x66347, + 0x66507, + 0x66887, + 0x67347, + 0x67947, + 0x68187, + 0x68547, + 0x68e87, + 0x69187, + 0x69847, + 0x69a07, + 0x69bc7, + 0x69d87, + 0x6a087, + 0x6a687, + 0x6af47, + 0x6b707, + 0x6bcc7, + 0x6bf87, + 0x6c147, + 0x6c447, + 0x6cc47, + 0x6ce47, + 0x6dd87, + 0x6df47, + 0x6e107, + 0x6ebc7, + 0x6f0c7, + 0x6fd87, 0x70687, - 0x70987, - 0x70e47, - 0x71707, - 0x72007, + 0x71147, + 0x71647, + 0x71807, + 0x71c07, + 0x72447, + 0x726c7, + 0x72ac7, 0x72c87, - 0x731c7, - 0x73387, - 0x73707, - 0x74487, - 0x74687, - 0x750c7, - 0x75287, - 0x75447, - 0x75dc7, - 0x76087, - 0x77a47, - 0x78187, - 0x78447, - 0x78bc7, - 0x78d87, - 0x79187, - 0x79687, - 0x79907, - 0x79d07, - 0x79ec7, - 0x7a087, - 0x7ae07, - 0x7c447, - 0x7c987, - 0x7cc87, - 0x7ce47, - 0x7d1c7, - 0x7d787, - 0x13c42, - 0x64c8a, - 0xe90c7, - 0x287c5, - 0x806d1, - 0x157c6, - 0x11318a, - 0xaa8ca, - 0x5d3c6, - 0xb880b, - 0x17202, - 0x3a1d1, - 0x1bbc89, - 0x9c0c9, - 0x351c2, - 0xa808a, - 0xac7c9, - 0xacf0f, - 0xada4e, - 0xae208, - 0x206c2, - 0xb649, - 0x1025ce, - 0xe8b4c, - 0xf328f, - 0x1a5b4e, - 0x1684c, - 0x18009, - 0x1c291, - 0x1f108, - 0x2ac92, - 0x2bb4d, - 0x33c4d, - 0x15208b, - 0x41cd5, - 0x164ec9, - 0xfcf8a, - 0x40809, - 0x4d650, - 0x4e70b, - 0x5898f, - 0x6390b, - 0x7298c, - 0x77650, - 0x8430a, - 0x853cd, - 0x894ce, - 0x8ef4a, - 0xede0c, - 0x176a54, - 0x1bb911, - 0x95a8b, - 0x97fcf, - 0xa290d, - 0xa76ce, - 0xb2bcc, - 0xb330c, - 0x160b0b, - 0x160e0e, - 0xd6750, - 0x11868b, - 0x1876cd, - 0x1bce4f, - 0xba0cc, - 0xbb0ce, - 0xbc011, - 0xc7c4c, - 0xc9307, - 0xc9c0d, - 0x130d4c, - 0x1605d0, - 0x174c0d, - 0xd1b47, - 0xd7c10, - 0xdd6c8, - 0xf178b, - 0x134c4f, - 0x3ef48, - 0x11338d, - 0x15c750, - 0x172e49, - 0x18e086c6, - 0xb8243, - 0xbc445, - 0x9a02, - 0x143889, - 0x5e04a, - 0x10fb06, - 0x2594a, - 0x1900c949, - 0x1c003, - 0xdebd1, - 0xdf009, - 0xe0407, - 0x35c4b, - 0xe67d0, - 0xe6c8c, - 0xe8e48, - 0xe9805, - 0xb988, - 0x1ad4ca, - 0x1c0c7, - 0x16bac7, - 0x982, - 0x12bcca, - 0x12e7c9, - 0x79545, - 0x402ca, - 0x9260f, - 0x4b8cb, - 0x14bd4c, - 0x17a492, - 0x94e45, - 0xec1c8, - 0x17618a, - 0x196f3d05, - 0x190ecc, - 0x129ac3, - 0x1951c2, - 0xfb30a, - 0x14fb70c, - 0x14f508, - 0x62d08, - 0x36d47, - 0xb282, - 0x4242, - 0x47590, + 0x72e47, + 0x73287, + 0x73e87, + 0x743c7, + 0x74947, + 0x74b07, + 0x74e87, + 0x75407, + 0xd0c2, + 0x5fdca, + 0xdc547, + 0x84785, + 0xb3111, + 0x10ac6, + 0x10cc0a, + 0x17378a, + 0x5b646, + 0xcb0b, + 0x1402, + 0x34111, + 0xb29c9, + 0x948c9, + 0xebfc2, + 0x71e8a, + 0xa5a89, + 0xa61cf, + 0xa67ce, + 0xa7708, + 0x552c2, + 0x549, + 0x18b4ce, + 0xfc6cc, + 0xdbe0f, + 0x1a814e, + 0x1840c, + 0x25589, + 0x26751, + 0x2f988, + 0x1109d2, + 0x1115cd, + 0x1545cd, + 0x43f8b, + 0x4bad5, + 0x52c49, + 0x5438a, + 0x5ee89, + 0x6b310, + 0x7cc8b, + 0x85ecf, + 0xf0c0b, + 0x16130c, + 0x1b2610, + 0x9208a, + 0x9e90d, + 0x9fc4e, + 0xa9bca, + 0xab6cc, + 0xac394, + 0xb2651, + 0xbb04b, + 0xe1ecf, + 0xca50d, + 0x1a720e, + 0x16c4cc, + 0x18618c, + 0xb234b, + 0xb428e, + 0xb4d50, + 0xb584b, + 0xbaa8d, + 0xbb4cf, + 0xbef4c, + 0xbfb4e, + 0xc0411, + 0xdff4c, + 0x10d8c7, + 0xc738d, + 0xd000c, + 0xd65d0, + 0xdb80d, + 0x18acc7, + 0xe6310, + 0xf9348, + 0xfd44b, + 0x17d9cf, + 0x142188, + 0x10ce0d, + 0x190c10, + 0xf5f89, + 0x196af346, + 0xb0303, + 0xb5b05, + 0x9602, + 0x143709, + 0x5c40a, + 0x106606, + 0x2098a, + 0x1991f309, + 0x264c3, + 0xd2711, + 0xd2b49, + 0xd3ec7, + 0x1873cb, + 0xdae90, + 0xdb34c, + 0xdc2c8, + 0xdcc45, + 0x11e748, + 0x1afe8a, + 0x26587, + 0x140947, + 0x1382, + 0x12f04a, + 0x3b809, + 0x71505, + 0xa2cca, + 0x8a0cf, + 0x4794b, + 0x174b8c, + 0x1a252, + 0x9df05, + 0xdf0c8, + 0x13a60a, + 0x19ee8f05, + 0x17478c, + 0x12c443, + 0x192a82, + 0xf258a, + 0x14f2d8c, + 0x3a6c8, + 0x198e48, + 0x15da07, + 0x16f02, 0xa02, - 0x3904f, - 0x86286, - 0x7c0e, - 0xebbcb, - 0x8f148, - 0xda049, - 0x18f052, - 0x95cd, - 0x586c8, - 0x58ec9, - 0x5d50d, - 0x5e4c9, - 0x5e88b, - 0x60648, - 0x65808, - 0x65b88, - 0x65e49, - 0x6604a, - 0x6a98c, - 0xeb04a, - 0x10bd07, - 0x1f54d, - 0xfde8b, - 0x12004c, - 0x404c8, - 0x4f049, - 0x1b01d0, - 0xc2, - 0x2d3cd, - 0x2642, - 0x2cc2, - 0x10bc4a, - 0x11308a, - 0x11438b, - 0x3b80c, - 0x113b0a, - 0x113d8e, - 0xf2cd, - 0x11d708, - 0x4542, - 0x11f46c0e, - 0x1260ee4e, - 0x12f43f8a, - 0x1373a14e, - 0x13f9d38e, - 0x1460138c, - 0x1438547, - 0x1438549, - 0x1416dc3, - 0x14e3700c, - 0x15707789, - 0x15f3b509, - 0x12c2, - 0x146b51, - 0xed91, - 0x143ecd, - 0x13a091, - 0x19d2d1, - 0x12cf, - 0x36f4f, - 0x1076cc, - 0x13b44c, - 0x18954d, - 0x1b5295, - 0x10ed8c, - 0xea88c, - 0x122ed0, - 0x158fcc, - 0x16d9cc, - 0x191819, - 0x1a83d9, - 0x1aa459, - 0x1b3e94, - 0x1b8ad4, - 0x1c0d14, - 0x2394, - 0x3754, - 0x1670ee49, - 0x16dc0fc9, - 0x176ea949, - 0x1221f309, - 0x12c2, - 0x12a1f309, - 0x12c2, - 0x238a, - 0x12c2, - 0x1321f309, - 0x12c2, - 0x238a, - 0x12c2, - 0x13a1f309, - 0x12c2, - 0x1421f309, - 0x12c2, - 0x14a1f309, - 0x12c2, - 0x238a, - 0x12c2, - 0x1521f309, - 0x12c2, - 0x238a, - 0x12c2, - 0x15a1f309, - 0x12c2, - 0x1621f309, - 0x12c2, - 0x238a, - 0x12c2, - 0x16a1f309, - 0x12c2, - 0x1721f309, - 0x12c2, - 0x17a1f309, - 0x12c2, - 0x238a, - 0x12c2, - 0x35ac5, - 0x1b3204, - 0x146c0e, - 0xee4e, - 0x143f8a, - 0x13a14e, - 0x19d38e, - 0x138c, - 0x3700c, - 0x107789, - 0x13b509, - 0x10ee49, - 0x1c0fc9, - 0xea949, - 0x122f8d, - 0x2649, - 0x3a09, - 0x5bf04, - 0x11d8c4, - 0x126144, - 0x15f784, - 0x8de84, - 0x4b744, - 0x6e44, - 0x67344, - 0x8cf44, - 0x157e2c3, - 0xc182, - 0xf2c3, - 0x4c82, - 0x207102, - 0x20f882, - 0x201742, - 0x207602, - 0x207b02, - 0x200442, - 0x204242, - 0x238543, - 0x23cac3, - 0x323043, - 0x231603, - 0x208e83, - 0x201a03, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x208e83, - 0x201a03, - 0x160c3, - 0x323043, - 0x31604, - 0x207102, - 0x39c783, - 0x1b638543, - 0x2bf347, - 0x323043, - 0x211a83, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x243d0a, - 0x3a03c5, - 0x221483, - 0x205082, - 0x16fb88, - 0x16fb88, - 0xf882, - 0x127482, - 0x1bf51b0b, - 0x5ba45, - 0x35dc5, - 0x114b46, - 0x145944, - 0xf183, - 0x145c05, - 0x131645, - 0x16fb88, - 0x23087, - 0x38543, - 0x1c644d87, - 0x1432c6, - 0x1c93b345, - 0x143387, - 0x1b4d0a, - 0x1b4bc8, - 0x11887, - 0x6df88, - 0x99707, - 0x152cf, - 0x435c7, - 0x150d86, - 0x11f3d0, - 0x12a58f, - 0x20a89, - 0x10fb84, - 0x1cd4344e, - 0xb098c, - 0x5810a, - 0xa7987, - 0x3520a, - 0xbb49, - 0xb514c, - 0x4304a, - 0x5ec8a, - 0x145c49, - 0x10fb06, - 0xa7a4a, - 0xe8a, - 0xa4e49, - 0xde488, - 0xde786, - 0xe284d, - 0xbc8c5, - 0x126447, - 0x1019c9, - 0xf72c7, - 0xb5ed4, - 0x103acb, - 0xf8b4a, - 0xab10d, - 0xd3c3, - 0xd3c3, - 0x24386, - 0xd3c3, - 0x19c783, - 0x16fb88, - 0xf882, - 0x53384, - 0x5f843, - 0x155685, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x203ec3, - 0x238543, - 0x23cac3, - 0x21b583, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x29c283, - 0x202443, - 0x203ec3, - 0x286644, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x206683, - 0x238543, - 0x23cac3, - 0x207603, - 0x21b583, - 0x323043, - 0x231604, - 0x3797c3, - 0x229443, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x221483, - 0x36a883, - 0x1ea38543, - 0x23cac3, - 0x250ac3, - 0x323043, - 0x212143, - 0x229443, - 0x201a03, - 0x204103, - 0x35f584, - 0x16fb88, - 0x1f238543, - 0x23cac3, - 0x2ae2c3, - 0x323043, - 0x28cac3, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x20e943, - 0x16fb88, - 0x1fa38543, - 0x23cac3, - 0x21b583, - 0x200e03, - 0x201a03, - 0x16fb88, - 0x1438547, - 0x39c783, - 0x238543, - 0x23cac3, - 0x323043, - 0x231604, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x131645, - 0x36dc7, - 0xb610b, - 0xdf404, - 0xbc8c5, - 0x1480cc8, - 0xae90d, - 0x20e6c505, - 0x7bd44, - 0x10c3, - 0x172d45, - 0x33b145, - 0x16fb88, - 0xd3c2, - 0x2bc3, - 0xf9306, - 0x31f948, - 0x3347c7, - 0x286644, - 0x39c286, - 0x3b5146, - 0x16fb88, - 0x2ddac3, - 0x342a49, - 0x26d615, - 0x6d61f, - 0x238543, - 0x3b3a52, - 0xf6306, - 0x114dc5, - 0x6b0a, - 0x27d89, - 0x3b380f, - 0x2de944, - 0x3490c5, - 0x304b10, - 0x34e347, - 0x200e03, - 0x293408, - 0x12ce46, - 0x29630a, - 0x230f04, - 0x2f3743, - 0x3a03c6, - 0x205082, - 0x22facb, - 0xe03, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x2f9a03, - 0x20f882, - 0x6ed43, - 0x208e83, - 0x201a03, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x201a03, - 0x238543, - 0x23cac3, - 0x323043, - 0x211a83, - 0x228243, - 0x201a03, - 0x20f882, - 0x238543, - 0x23cac3, - 0x208e83, - 0xe03, - 0x201a03, - 0x207102, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x35dc5, - 0x286644, - 0x238543, - 0x23cac3, - 0x20f644, - 0x208e83, - 0x201a03, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x1a3443, - 0x201a03, - 0x238543, - 0x23cac3, - 0x21b583, - 0x204c03, - 0x28cac3, - 0x208e83, - 0xe03, - 0x201a03, - 0x20f882, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x210543, - 0x707c3, - 0x11a83, - 0x208e83, - 0x201a03, - 0x3195ca, - 0x335289, - 0x35438b, - 0x35490a, - 0x35c50a, - 0x369bcb, - 0x38274a, - 0x38b38a, - 0x39090a, - 0x390b8b, - 0x3ad209, - 0x3af10a, - 0x3af7cb, - 0x3b978b, - 0x3bfb4a, - 0x238543, - 0x23cac3, - 0x21b583, - 0x28cac3, - 0x208e83, - 0xe03, - 0x201a03, - 0x35dcb, - 0x651c8, - 0x1174c9, - 0x16fb88, - 0x238543, - 0x26b304, - 0x20b342, - 0x21bf84, - 0x346145, - 0x203ec3, - 0x286644, - 0x238543, - 0x240244, - 0x23cac3, - 0x253384, - 0x2de944, - 0x231604, - 0x229443, - 0x208e83, - 0x201a03, - 0x22d585, - 0x206683, - 0x221483, - 0x20ec43, - 0x231944, - 0x20fe84, - 0x2cc105, - 0x16fb88, - 0x30dc84, - 0x36bdc6, - 0x281384, - 0x20f882, - 0x381107, - 0x254d87, - 0x251844, - 0x260105, - 0x374e05, - 0x2b13c5, - 0x231604, - 0x2cf6c8, - 0x23eb46, - 0x3bffc8, - 0x257cc5, - 0x2e4505, - 0x263544, - 0x201a03, - 0x2f4544, - 0x368dc6, - 0x3a04c3, - 0x231944, - 0x280bc5, - 0x2e4ac4, - 0x34da44, - 0x205082, - 0x2669c6, - 0x3a2906, - 0x30a185, - 0x207102, - 0x39c783, - 0x2760f882, - 0x223b84, - 0x207b02, - 0x28cac3, - 0x200e82, - 0x208e83, - 0x200442, - 0x215443, - 0x202443, - 0x16fb88, - 0x16fb88, - 0x323043, - 0x207102, - 0x2820f882, - 0x323043, - 0x270443, - 0x3797c3, - 0x32e5c4, - 0x208e83, - 0x201a03, - 0x16fb88, - 0x207102, - 0x28a0f882, - 0x238543, - 0x208e83, - 0xe03, - 0x201a03, - 0x482, + 0x49fd0, + 0x653c7, + 0x1282, + 0x333cf, + 0x7dac6, + 0x79a8e, + 0xdeb8b, + 0x6e308, + 0xa9dc9, + 0xf5012, + 0x18998d, + 0x1be608, + 0x68849, + 0x6a20d, + 0x6c5c9, + 0x6c98b, + 0x6e4c8, + 0x73c88, + 0x76248, + 0x79dc9, + 0x79fca, + 0x7b48c, + 0x17010a, + 0x103bc7, + 0x2fdcd, + 0xf7a8b, + 0x11a9cc, + 0x1979c8, + 0x4d3c9, + 0x13d8d0, + 0xc842, + 0x521cd, + 0x4182, + 0xc542, + 0x103b0a, + 0x10cb0a, + 0x10ec8b, + 0x4654c, + 0x10c28a, + 0x10c50e, + 0x121ccd, + 0xb6a08, + 0xdc2, + 0x11e0340e, + 0x1272184e, + 0x12f4960a, + 0x13742c0e, + 0x13f374ce, + 0x147ac40c, + 0x14328c7, + 0x14328c9, + 0x1410983, + 0x14eb784c, + 0x15727309, + 0x15f69bc9, + 0x1660a6c9, + 0x3342, + 0x3351, + 0x121791, + 0x14954d, + 0x142b51, + 0x137411, + 0x1ac34f, + 0xb778f, + 0x12724c, + 0x169b0c, + 0xa60c, + 0x1654cd, + 0x10e595, + 0x5a00c, + 0x1ba48c, + 0x138c90, + 0x155e8c, + 0x15dc0c, + 0x17a659, + 0x180a19, + 0x19f3d9, + 0x1b57d4, + 0x1bbcd4, + 0x3ed4, + 0x4ed4, + 0xb814, + 0x16e5a0c9, + 0x17404189, + 0x17fba549, + 0x1222fb89, + 0x3342, + 0x12a2fb89, + 0x3342, + 0x3eca, + 0x3342, + 0x1322fb89, + 0x3342, + 0x3eca, + 0x3342, + 0x13a2fb89, + 0x3342, + 0x1422fb89, + 0x3342, + 0x14a2fb89, + 0x3342, + 0x3eca, + 0x3342, + 0x1522fb89, + 0x3342, + 0x3eca, + 0x3342, + 0x15a2fb89, + 0x3342, + 0x1622fb89, + 0x3342, + 0x3eca, + 0x3342, + 0x16a2fb89, + 0x3342, + 0x3eca, + 0x3342, + 0x1722fb89, + 0x3342, + 0x17a2fb89, + 0x3342, + 0x1822fb89, + 0x3342, + 0x3eca, + 0x3342, + 0x187245, + 0x18c404, + 0x340e, + 0x12184e, + 0x14960a, + 0x142c0e, + 0x1374ce, + 0x1ac40c, + 0xb784c, + 0x127309, + 0x169bc9, + 0xa6c9, + 0x5a0c9, + 0x4189, + 0x1ba549, + 0x10e78d, + 0x5189, + 0xbac9, + 0x116a84, + 0x118c44, + 0x13aa44, + 0x18e7c4, + 0x79004, + 0x98884, + 0x477c4, + 0x143c44, + 0x1fbc4, + 0x157cd03, + 0xa6c2, + 0x121cc3, + 0x2e02, + 0x200742, + 0x202c42, + 0x209d42, 0x208882, - 0x21a902, - 0x211a83, - 0x2ef783, - 0x207102, - 0x131645, - 0x16fb88, - 0x36dc7, - 0x20f882, - 0x23cac3, - 0x253384, - 0x2020c3, - 0x323043, - 0x204c03, - 0x28cac3, - 0x208e83, - 0x21eb43, - 0x201a03, - 0x2252c3, - 0x122213, - 0x124cd4, - 0x36dc7, - 0x139986, - 0x5e24b, - 0x24386, - 0x5c0c7, - 0x120589, - 0xe838a, - 0x9058d, - 0x14fecc, - 0x3954a, - 0x11205, - 0x1b4d48, - 0x86286, - 0x31586, - 0x12cf06, - 0x20c182, - 0x10b14c, - 0x1b33c7, - 0x2a691, - 0x238543, - 0x6df05, - 0x7588, - 0x18ec4, - 0x29cbe1c6, - 0x806c6, - 0xb9a06, - 0x960ca, - 0xb4003, - 0x2a24c984, - 0xe8345, - 0x18e43, - 0x2a63dc47, - 0xe3bc5, - 0xb88cc, - 0xf7a88, - 0xbd248, - 0xa6589, - 0x14dc08, - 0x1425886, - 0x2ab71549, - 0x14978a, - 0x16308, - 0x114b48, - 0x8cf44, - 0xb5ac5, - 0x2ae42bc3, - 0x2b332106, - 0x2b6f4dc4, - 0x2bb39d87, - 0x114b44, - 0x114b44, - 0x114b44, - 0x114b44, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x207102, - 0x20f882, - 0x323043, - 0x205e82, - 0x208e83, - 0x201a03, - 0x215443, - 0x373ccf, - 0x37408e, - 0x16fb88, - 0x238543, - 0x4db87, - 0x23cac3, - 0x323043, - 0x255783, - 0x208e83, - 0x201a03, - 0x20d4c3, - 0x20d4c7, - 0x200142, - 0x2ce609, - 0x200242, - 0x24788b, - 0x2c110a, - 0x2c67c9, - 0x201242, - 0x2100c6, - 0x26cd95, - 0x2479d5, - 0x275793, - 0x247f53, - 0x201d42, - 0x212c45, - 0x31d44c, - 0x27c6cb, - 0x29c705, - 0x20cac2, - 0x28e142, - 0x384c06, - 0x200bc2, - 0x3acc46, - 0x2dd20d, - 0x26540c, - 0x22cc84, - 0x200f82, - 0x203402, - 0x22b048, - 0x201d02, - 0x20a746, - 0x28bf04, - 0x26cf55, - 0x275913, - 0x216d03, - 0x33844a, - 0x205407, - 0x3145c9, - 0x38d4c7, - 0x20d342, - 0x200002, - 0x3ba886, - 0x212702, - 0x16fb88, - 0x216b42, - 0x201102, - 0x27f847, - 0x217387, - 0x222d85, - 0x20c702, - 0x225287, - 0x225448, - 0x2024c2, - 0x2430c2, - 0x237302, - 0x201382, - 0x242688, - 0x20a043, - 0x25fa08, - 0x2e9b0d, - 0x2322c3, - 0x32ec08, - 0x245f4f, - 0x24630e, - 0x339a4a, - 0x22e811, - 0x22ec90, - 0x2c34cd, - 0x2c380c, - 0x36a707, - 0x3385c7, - 0x39c349, - 0x20d302, - 0x201442, - 0x25db0c, - 0x25de0b, - 0x2008c2, - 0x360cc6, + 0x202542, + 0x200342, + 0x200a02, + 0x20be03, + 0x237583, + 0x30e843, + 0x26ff83, + 0x20ec83, + 0x241d03, + 0xcd588, + 0x20be03, + 0x237583, + 0x20ec83, + 0x241d03, + 0x1a9c3, + 0x30e843, + 0x6ff84, + 0x200742, + 0x2b6c03, + 0x1be0be03, + 0x2394c7, + 0x30e843, + 0x20f003, + 0x226444, + 0x20ec83, + 0x241d03, + 0x22d50a, + 0x3a25c5, + 0x219543, 0x20e982, - 0x204882, - 0x222902, - 0x20f882, - 0x3b69c4, - 0x244387, - 0x229682, - 0x24a347, - 0x24b547, - 0x20d282, - 0x20c8c2, - 0x24da45, - 0x21a442, - 0x2f290e, - 0x2ab3cd, - 0x23cac3, - 0x28d58e, - 0x2c5c0d, - 0x25ac43, - 0x201482, - 0x2891c4, - 0x216582, - 0x20fac2, - 0x364145, - 0x373587, - 0x393202, - 0x207602, - 0x252f87, - 0x255ac8, - 0x2f6802, - 0x294ec6, - 0x25d98c, - 0x25dccb, - 0x206b02, - 0x26764f, - 0x267a10, - 0x267e0f, - 0x2681d5, - 0x268714, - 0x268c0e, - 0x268f8e, - 0x26930f, - 0x2696ce, - 0x269a54, - 0x269f53, - 0x26a40d, - 0x27d949, - 0x291ac3, - 0x201802, - 0x2b7505, - 0x206346, - 0x207b02, - 0x3a4ec7, - 0x323043, - 0x217202, - 0x37e548, - 0x22ea51, - 0x22ee90, - 0x2007c2, - 0x290e07, - 0x204182, - 0x332b07, - 0x209a02, - 0x342089, - 0x384bc7, - 0x27ac08, - 0x2be006, - 0x2ef683, - 0x339205, - 0x2022c2, - 0x207a82, - 0x3bac85, - 0x391345, - 0x204bc2, - 0x231043, - 0x2e4b47, - 0x205747, - 0x200502, - 0x25f1c4, - 0x211b83, - 0x211b89, - 0x215148, - 0x200282, - 0x202942, - 0x242387, - 0x263285, - 0x2ad208, - 0x215c87, - 0x21a243, - 0x294c86, - 0x2c334d, - 0x2c36cc, - 0x2c8346, - 0x209b02, + 0xcd588, + 0xcd588, + 0x2c42, + 0x129242, + 0x1c74660b, + 0x5fc5, + 0x1f8c5, + 0xf9fc6, + 0x1221c4, + 0x121b83, + 0xf45, + 0x117485, + 0xcd588, + 0x1c787, + 0xbe03, + 0x1ce41447, + 0x143146, + 0x1d149445, + 0x143207, + 0xf84a, + 0xf708, + 0x13407, + 0x68348, + 0x98647, + 0xf28f, + 0x47f87, + 0x4e786, + 0x12e350, + 0x12cf0f, + 0x1c009, + 0x106684, + 0x1d5432ce, + 0xa978c, + 0xf420a, + 0x785c7, + 0xd9f8a, + 0x11e909, + 0xada0c, + 0x1bdf0a, + 0x5cc0a, + 0xf89, + 0x106606, + 0x7868a, + 0x11d84a, + 0x9a209, + 0xd1fc8, + 0xd22c6, + 0xd6c0d, + 0xb7cc5, + 0xab07, + 0xfb709, + 0x1a3207, + 0x10bd94, + 0xfdb4b, + 0x7e78a, + 0xa358d, + 0xf283, + 0xf283, + 0x29546, + 0xf283, + 0xb6c03, + 0xcd588, + 0x2c42, + 0x54a04, + 0x5da83, + 0xf5805, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x205583, + 0x20be03, + 0x237583, + 0x203d43, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x294a83, + 0x203f83, + 0x205583, + 0x28b304, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x235cc3, + 0x20be03, + 0x237583, + 0x208883, + 0x203d43, + 0x30e843, + 0x26ff84, + 0x3c32c3, + 0x20be83, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x219543, + 0x20c283, + 0x1f20be03, + 0x237583, + 0x24e683, + 0x30e843, + 0x211343, + 0x20be83, + 0x241d03, + 0x2057c3, + 0x317f04, + 0xcd588, + 0x1fa0be03, + 0x237583, + 0x2a77c3, + 0x30e843, + 0x21f743, + 0x226444, + 0x20ec83, + 0x241d03, + 0x232f43, + 0xcd588, + 0x2020be03, + 0x237583, + 0x203d43, + 0x20ae43, + 0x241d03, + 0xcd588, + 0x14328c7, + 0x2b6c03, + 0x20be03, + 0x237583, + 0x30e843, + 0x26ff84, + 0x226444, + 0x20ec83, + 0x241d03, + 0x142f49, + 0x117485, + 0x15da87, + 0x10bfcb, + 0xd2f44, + 0xb7cc5, + 0x1455908, + 0xa7e0d, + 0x21676405, + 0x8f204, + 0x10ec3, + 0xf5e85, + 0x31cc45, + 0xcd588, + 0xf282, + 0x3a283, + 0xefec6, + 0x31b0c8, + 0x397247, + 0x28b304, + 0x346046, + 0x3699c6, + 0xcd588, + 0x312ec3, + 0x23aec9, + 0x265555, + 0x6555f, + 0x20be03, + 0x3ba052, + 0x10db06, + 0x14fc85, + 0x12c4a, + 0x2e449, + 0x3b9e0f, + 0x2d2484, + 0x225285, + 0x2fdfd0, + 0x38cb87, + 0x20ae43, + 0x310f08, + 0x157146, + 0x2a47ca, + 0x22d244, + 0x2e8943, + 0x3a25c6, + 0x20e982, + 0x3987cb, + 0xae43, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x2f0ec3, + 0x202c42, + 0xee203, + 0x20ec83, + 0x241d03, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x241d03, + 0x20be03, + 0x237583, + 0x30e843, + 0x20f003, + 0x227b03, + 0x241d03, + 0x202c42, + 0x20be03, + 0x237583, + 0x20ec83, + 0xae43, + 0x241d03, + 0x200742, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x1f8c5, + 0x28b304, + 0x20be03, + 0x237583, + 0x21a484, + 0x20ec83, + 0x241d03, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0xaff03, + 0x241d03, + 0x20be03, + 0x237583, + 0x203d43, + 0x204d03, + 0x21f743, + 0x20ec83, + 0xae43, + 0x241d03, + 0x202c42, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x357d43, + 0x3cf83, + 0xf003, + 0x20ec83, + 0x241d03, + 0x31350a, + 0x333049, + 0x3524cb, + 0x352b4a, + 0x35acca, + 0x3686cb, + 0x37bfca, + 0x3825ca, + 0x38bf0a, + 0x38c18b, + 0x3afbc9, + 0x3b1a0a, + 0x3b1d8b, + 0x3bc98b, + 0x3c5b0a, + 0x20be03, + 0x237583, + 0x203d43, + 0x21f743, + 0x20ec83, + 0xae43, + 0x241d03, + 0x18754b, + 0x60308, + 0x14f209, + 0xcd588, + 0x20be03, + 0x266004, + 0x206302, + 0x226444, + 0x201485, + 0x205583, + 0x28b304, + 0x20be03, + 0x23d744, + 0x237583, + 0x254a04, + 0x2d2484, + 0x26ff84, + 0x20be83, + 0x20ec83, + 0x241d03, + 0x252385, + 0x235cc3, + 0x219543, + 0x2b5d83, + 0x2702c4, + 0x2020c4, + 0x3c0885, + 0xcd588, + 0x320f04, + 0x39db46, + 0x2010c4, + 0x202c42, + 0x38fd87, + 0x256087, + 0x252944, + 0x25e5c5, + 0x2dba05, + 0x232585, + 0x26ff84, + 0x27a688, + 0x23c806, + 0x3c5f88, + 0x278185, + 0x2d8345, + 0x251304, + 0x241d03, + 0x2e9484, + 0x367486, + 0x3a26c3, + 0x2702c4, + 0x362205, + 0x26e984, + 0x23fd84, + 0x20e982, + 0x397746, + 0x3a4b06, + 0x301805, + 0x200742, + 0x2b6c03, + 0x27e02c42, + 0x207344, + 0x202542, + 0x21f743, + 0x23a3c2, + 0x20ec83, + 0x200342, + 0x207c03, + 0x203f83, + 0xcd588, + 0xcd588, + 0x30e843, + 0x200742, + 0x28a02c42, + 0x30e843, + 0x2574c3, + 0x3c32c3, + 0x2168c4, + 0x20ec83, + 0x241d03, + 0xcd588, + 0x200742, + 0x29202c42, + 0x20be03, + 0x20ec83, + 0xae43, + 0x241d03, + 0x982, 0x20c202, - 0x204a82, - 0x245dcf, - 0x2461ce, - 0x374e87, - 0x20b302, - 0x2c72c5, - 0x2c72c6, - 0x214702, - 0x200802, - 0x228246, - 0x2b57c3, - 0x332a46, - 0x2d0285, - 0x2d028d, - 0x2d0855, - 0x2d108c, - 0x2d1e4d, - 0x2d2212, - 0x214642, - 0x2745c2, + 0x230882, + 0x20f003, + 0x2e2d83, + 0x200742, + 0x117485, + 0xcd588, + 0x15da87, + 0x202c42, + 0x237583, + 0x254a04, + 0x206c03, + 0x30e843, + 0x204d03, + 0x21f743, + 0x20ec83, + 0x207783, + 0x241d03, + 0x2388c3, + 0xb5cd3, + 0x1b9994, + 0x15da87, + 0x102dc6, + 0x5c60b, + 0x29546, + 0x5a3c7, + 0x2809, + 0x195d4a, + 0x8820d, + 0x12078c, + 0x104fca, + 0x14a345, + 0xf888, + 0x7dac6, + 0x6ff06, + 0x157206, + 0x20a6c2, + 0x1c170c, + 0x18c5c7, + 0x282d1, + 0x20be03, + 0x682c5, + 0x8808, + 0x22644, + 0x2a507646, + 0xb3106, + 0xd95c6, + 0x8d5ca, + 0x19dac3, + 0x2aa48c44, + 0x27c5, + 0x15cc83, + 0x2ae38a07, + 0x1aec5, + 0xcbcc, + 0xed348, + 0x6f6cb, + 0x2b25168c, + 0x140d6c3, + 0xb8888, + 0x9db09, + 0x3ff48, + 0x14208c6, + 0x2b76d609, + 0xd7e4a, + 0x10d08, + 0xf9fc8, + 0x1fbc4, + 0x118b45, + 0x6f807, + 0x2ba6f803, + 0x2bf39c86, + 0x2c2e9d04, + 0x2c790207, + 0xf9fc4, + 0xf9fc4, + 0xf9fc4, + 0xf9fc4, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x200742, + 0x202c42, + 0x30e843, + 0x207d02, + 0x20ec83, + 0x241d03, + 0x207c03, + 0x37158f, + 0x37194e, + 0xcd588, + 0x20be03, + 0x49a07, + 0x237583, + 0x30e843, + 0x214bc3, + 0x20ec83, + 0x241d03, + 0x220443, + 0x322887, + 0x203d02, + 0x292889, + 0x200602, + 0x24a2cb, + 0x2cf44a, + 0x28d009, + 0x200182, + 0x3418c6, + 0x235295, + 0x24a415, + 0x236793, + 0x24a993, + 0x203942, + 0x222dc5, + 0x3ab48c, + 0x27410b, + 0x2a2205, + 0x203402, + 0x2f2542, + 0x37e706, + 0x200282, + 0x261bc6, + 0x212ecd, + 0x21ac4c, + 0x228ec4, + 0x200cc2, + 0x2149c2, + 0x310d88, + 0x2023c2, + 0x211446, + 0x35c704, + 0x235455, + 0x236913, + 0x2108c3, + 0x32508a, + 0x20df47, + 0x30eec9, + 0x2d9d07, + 0x314902, + 0x200882, + 0x3b4b46, + 0x2099c2, + 0xcd588, + 0x210702, + 0x200302, + 0x217a07, + 0x336087, + 0x21c485, + 0x2004c2, + 0x2da6c7, + 0x220488, + 0x204002, + 0x2f21c2, + 0x230502, + 0x203cc2, + 0x23e988, + 0x20bf83, + 0x25dc48, + 0x20bf8d, + 0x237c03, + 0x23bc48, + 0x237c0f, + 0x237fce, + 0x38feca, + 0x2d1311, + 0x2d1790, + 0x38360d, + 0x38394c, + 0x3452c7, + 0x325207, + 0x346109, + 0x228fc2, + 0x200782, + 0x25becc, + 0x25c1cb, + 0x203c02, + 0x2b2506, + 0x2010c2, + 0x202642, + 0x2efa02, + 0x202c42, + 0x231fc4, + 0x240647, + 0x230a42, + 0x245207, + 0x2475c7, + 0x21bc02, + 0x21b282, + 0x2498c5, + 0x204ac2, + 0x2e72ce, + 0x2a384d, + 0x237583, + 0x28400e, + 0x3b868d, + 0x348003, 0x202ec2, - 0x249386, - 0x302486, - 0x200982, - 0x2063c6, - 0x202c82, - 0x39b505, - 0x200542, - 0x2ab4c9, - 0x2e324c, - 0x2e358b, - 0x200442, - 0x257708, - 0x2052c2, - 0x20cb42, - 0x278ec6, - 0x21f285, - 0x36c107, - 0x24bc85, - 0x28ea05, - 0x235d82, - 0x219a42, - 0x21cc82, - 0x2f3587, - 0x2613cd, - 0x26174c, - 0x317947, - 0x2235c2, - 0x225b82, - 0x23f688, - 0x343a08, - 0x34c008, - 0x313344, - 0x361087, - 0x2efc43, - 0x299842, - 0x206682, - 0x2f2149, - 0x3ab3c7, - 0x204102, - 0x2792c5, - 0x22fa42, - 0x236902, - 0x35dc83, - 0x35dc86, - 0x2f9a02, - 0x2fab42, - 0x200c02, - 0x281e06, - 0x345607, - 0x221282, - 0x206b42, - 0x25f84f, - 0x28d3cd, - 0x3029ce, - 0x2c5a8c, - 0x201a42, - 0x204142, - 0x2bde45, - 0x317e46, - 0x209002, + 0x2817c4, + 0x238c42, + 0x202e82, + 0x372a45, + 0x37b407, + 0x24d902, + 0x208882, + 0x254607, + 0x257688, + 0x329982, + 0x29df86, + 0x25bd4c, + 0x25c08b, + 0x212c42, + 0x26208f, + 0x262450, + 0x26284f, + 0x262c15, + 0x263154, + 0x26364e, + 0x2639ce, + 0x263d4f, + 0x26410e, + 0x264494, + 0x264993, + 0x264e4d, + 0x2755c9, + 0x289843, + 0x201802, + 0x215f45, + 0x206c06, + 0x202542, + 0x344e47, + 0x30e843, + 0x201402, + 0x36dfc8, + 0x2d1551, + 0x2d1990, + 0x200c42, + 0x270f87, 0x205842, + 0x341287, + 0x209602, + 0x348f89, + 0x37e6c7, + 0x2a4b48, + 0x307486, + 0x2e2c83, + 0x326e05, + 0x20e402, + 0x202682, + 0x3b4f45, + 0x3c1485, + 0x200f82, + 0x214d03, + 0x26ea07, + 0x208007, + 0x2085c2, + 0x22e684, + 0x20b4c3, + 0x20b4c9, + 0x20f108, + 0x201542, + 0x204482, + 0x2e3547, + 0x33d705, + 0x293988, + 0x222a87, + 0x201cc3, + 0x298106, + 0x38348d, + 0x38380c, + 0x2e0646, 0x200482, - 0x215c04, - 0x2e9984, - 0x2b8706, - 0x204242, - 0x37d6c7, - 0x233803, - 0x233808, - 0x33cb48, - 0x240687, - 0x249286, - 0x202502, - 0x242603, - 0x351107, - 0x26ffc6, - 0x2e2d05, - 0x3136c8, - 0x206182, - 0x337547, - 0x21f542, - 0x332182, - 0x207f02, - 0x2e95c9, - 0x23b442, - 0x2018c2, - 0x248383, - 0x377787, - 0x2002c2, - 0x2e33cc, - 0x2e36cb, - 0x2c83c6, - 0x218d85, - 0x22a202, - 0x204782, - 0x2c1486, - 0x237e83, - 0x378407, - 0x243cc2, - 0x200d42, - 0x26cc15, - 0x247b95, - 0x275653, - 0x2480d3, - 0x2955c7, - 0x2c0ec8, - 0x379d90, - 0x3c020f, - 0x2c0ed3, - 0x2c6592, - 0x2ce1d0, - 0x2db58f, - 0x2dc512, - 0x2dffd1, - 0x2e0cd3, - 0x2e9392, - 0x2ea0cf, - 0x2f7c4e, - 0x2f9a92, - 0x2faed1, - 0x303e4f, - 0x347a4e, - 0x3559d1, - 0x2fee10, - 0x32f912, - 0x36fd51, - 0x3af4c6, - 0x30dd47, - 0x382ac7, - 0x203702, - 0x286d05, - 0x304887, - 0x21a902, - 0x218f42, - 0x230d85, - 0x226c43, - 0x244c06, - 0x26158d, - 0x2618cc, - 0x206442, - 0x31d2cb, - 0x27c58a, - 0x212b0a, - 0x2c04c9, - 0x2f0c0b, - 0x215dcd, - 0x304f8c, - 0x2f574a, - 0x277bcc, - 0x27d34b, - 0x29c54c, - 0x2b4c0b, - 0x2e31c3, - 0x36f946, - 0x3061c2, - 0x2fd502, - 0x256d03, - 0x203642, - 0x203643, - 0x260b86, - 0x268387, - 0x2c48c6, - 0x2e2448, - 0x343708, - 0x2cc7c6, - 0x20c402, - 0x309b4d, - 0x309e8c, - 0x2dea07, - 0x30db47, - 0x2302c2, - 0x221682, - 0x260982, - 0x255e82, - 0x20f882, - 0x208e83, - 0x201a03, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x215443, - 0x207102, - 0x207542, - 0x2da97d45, - 0x2de97685, - 0x2e320c86, - 0x16fb88, - 0x2e6b68c5, - 0x20f882, + 0x26f582, + 0x201e42, + 0x237a8f, + 0x237e8e, + 0x2dba87, + 0x200b82, + 0x3517c5, + 0x3517c6, + 0x203282, + 0x205a02, + 0x28ad86, + 0x292ac3, + 0x3411c6, + 0x2c3ec5, + 0x2c3ecd, + 0x2c4495, + 0x2c4e8c, + 0x2c59cd, + 0x2c5d92, + 0x20d682, + 0x26cd82, + 0x2047c2, + 0x21ce86, + 0x2fc586, + 0x201382, + 0x206c86, + 0x20c502, + 0x20d245, + 0x2013c2, + 0x2a3949, + 0x21d70c, + 0x21da4b, + 0x200342, + 0x258508, + 0x20cb42, + 0x206f02, + 0x271946, + 0x22fb05, + 0x31f507, + 0x250d85, + 0x2982c5, + 0x249a82, + 0x204c02, + 0x20b182, + 0x2dc107, + 0x24f4cd, + 0x24f84c, + 0x34f687, + 0x22bac2, + 0x201f82, + 0x23d488, + 0x343888, + 0x303d48, + 0x30cdc4, + 0x2b4507, + 0x2e3c83, + 0x24e882, + 0x204882, + 0x2e6b09, + 0x2f7387, + 0x2057c2, + 0x271d45, + 0x248602, + 0x209942, + 0x2bca43, + 0x2bca46, + 0x2f0602, + 0x2f1e82, + 0x201442, + 0x3b33c6, + 0x3454c7, + 0x205e42, + 0x200382, + 0x25da8f, + 0x283e4d, + 0x38b8ce, + 0x3b850c, + 0x2017c2, + 0x200502, + 0x3072c5, + 0x311d86, + 0x209002, + 0x208102, + 0x200982, + 0x222a04, + 0x2dcdc4, + 0x3c23c6, + 0x200a02, + 0x2b7307, + 0x231d03, + 0x231d08, + 0x2326c8, + 0x243e07, + 0x2ecbc6, + 0x204042, + 0x23e683, + 0x23e687, + 0x28a8c6, + 0x2f3045, + 0x30d148, + 0x206a42, + 0x341687, + 0x20fd82, + 0x2f4682, + 0x20c142, + 0x2f1149, + 0x20a402, 0x201742, - 0x2ea34cc5, - 0x2ee852c5, - 0x2f285e07, - 0x2f6f6e09, - 0x2fa74084, - 0x207b02, - 0x217202, - 0x2fe56a05, - 0x302977c9, - 0x30785908, - 0x30ab3185, - 0x30f3f5c7, - 0x31227248, - 0x316ec085, - 0x31a00106, - 0x31e41489, - 0x323311c8, - 0x326c8988, - 0x32a9ef0a, - 0x32e7e204, - 0x332d99c5, - 0x336c30c8, - 0x33b85d85, - 0x21a602, - 0x33e11103, - 0x342aa246, - 0x3475d1c8, - 0x34a8ab86, - 0x34e8a688, - 0x35348206, - 0x356e2dc4, - 0x204d42, - 0x35addc87, - 0x35eaf444, - 0x36280087, - 0x367b0c87, - 0x200442, - 0x36aa3885, - 0x36e8f904, - 0x372f1447, - 0x37632c47, - 0x37a89006, - 0x37e38385, - 0x3829d7c7, - 0x386d5dc8, - 0x38ab7887, - 0x38ea6c89, - 0x3939e345, - 0x397778c7, - 0x39a974c6, - 0x39e102c8, - 0x3279cd, - 0x27a209, - 0x28384b, - 0x289ecb, - 0x2ae3cb, - 0x2e62cb, - 0x31804b, - 0x31830b, - 0x318949, - 0x31984b, - 0x319b0b, - 0x31a08b, - 0x31b08a, - 0x31b5ca, - 0x31bbcc, - 0x31e00b, - 0x31ea4a, - 0x33064a, - 0x33c6ce, - 0x33d1ce, - 0x33d54a, - 0x33efca, + 0x24adc3, + 0x325ec7, + 0x2040c2, + 0x21d88c, + 0x21db8b, + 0x2e06c6, + 0x35cbc5, + 0x227882, + 0x201c42, + 0x2ba046, + 0x22e983, + 0x331547, + 0x20cb82, + 0x202a82, + 0x235115, + 0x24a5d5, + 0x236653, + 0x24ab13, + 0x25d207, + 0x274548, + 0x274550, + 0x28744f, + 0x373ad3, + 0x28cdd2, + 0x292450, + 0x2b350f, + 0x2fd6d2, + 0x3af491, + 0x2af493, + 0x3938d2, + 0x2c3b0f, + 0x2cd74e, + 0x2cf252, + 0x2d09d1, + 0x2d3b0f, + 0x2d528e, + 0x2dc811, + 0x2dd7d0, + 0x2ed512, + 0x2f0f51, + 0x2f2206, + 0x2f3907, + 0x38e407, + 0x200d02, + 0x27efc5, + 0x3713c7, + 0x230882, + 0x20f6c2, + 0x22d0c5, + 0x200443, + 0x200446, + 0x24f68d, + 0x24f9cc, + 0x206d02, + 0x3ab30b, + 0x273fca, + 0x22358a, + 0x2b9489, + 0x2e530b, + 0x222bcd, + 0x2fe44c, + 0x2ec88a, + 0x27500c, + 0x294d4b, + 0x2a204c, + 0x2f968b, + 0x2b9e83, + 0x2f4f06, + 0x3b9942, + 0x2f3dc2, + 0x20e343, + 0x201ac2, + 0x207203, + 0x24ec86, + 0x262dc7, + 0x2ad706, + 0x2f6b48, + 0x343588, + 0x2ca146, + 0x211d82, + 0x3011cd, + 0x30150c, + 0x2d2547, + 0x304e07, + 0x23c242, + 0x219742, + 0x23e602, + 0x257a42, + 0x202c42, + 0x20ec83, + 0x241d03, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x226444, + 0x20ec83, + 0x241d03, + 0x207c03, + 0x200742, + 0x201482, + 0x2e68ecc5, + 0x2ea8e4c5, + 0x2efb3086, + 0xcd588, + 0x2f2afb05, + 0x202c42, + 0x209d42, + 0x2f726285, + 0x2fa7cb85, + 0x2fe7d647, + 0x302867c9, + 0x30667d84, + 0x202542, + 0x201402, + 0x30b0dec5, + 0x30e95f49, + 0x31327988, + 0x316ac205, + 0x31af0707, + 0x31e21cc8, + 0x322def85, + 0x3266d246, + 0x32b6d849, + 0x32ed4ec8, + 0x332bf988, + 0x3369658a, + 0x33a75e04, + 0x33f7c545, + 0x342bc308, + 0x34727e05, + 0x217f42, + 0x34a061c3, + 0x34ea2606, + 0x35311408, + 0x356eee46, + 0x35b643c8, + 0x35eb6306, + 0x363c2f44, + 0x2032c2, + 0x366f1587, + 0x36aa8644, + 0x36e77e87, + 0x3723ecc7, + 0x200342, + 0x3769ae85, + 0x37a403c4, + 0x37ee1787, + 0x383a3387, + 0x38681606, + 0x38a7d205, + 0x38e96047, + 0x392e5a48, + 0x396162c7, + 0x39b94949, + 0x39ec51c5, + 0x3a2b4107, + 0x3a68e306, + 0x3aa941c8, + 0x227d8d, + 0x251989, + 0x272fcb, + 0x27ac8b, + 0x2a78cb, + 0x2da98b, + 0x311f8b, + 0x31224b, + 0x312889, + 0x31378b, + 0x313a4b, + 0x313fcb, + 0x314c8a, + 0x3151ca, + 0x3157cc, + 0x31938b, + 0x319dca, + 0x33080a, + 0x33b28e, + 0x33be8e, + 0x33c20a, + 0x33e14a, + 0x33eb4b, + 0x33ee0b, 0x33fa8b, - 0x33fd4b, - 0x340b0b, - 0x36124b, - 0x36184a, - 0x36250b, - 0x3627ca, - 0x362a4a, - 0x362cca, - 0x38424b, - 0x38c6cb, - 0x38e64e, - 0x38e9cb, - 0x39464b, - 0x395b0b, - 0x39900a, - 0x399289, - 0x3994ca, - 0x39a94a, - 0x3addcb, - 0x3afa8b, - 0x3b05ca, - 0x3b1fcb, - 0x3b674b, - 0x3bf58b, - 0x3a287a88, - 0x3a68fd09, - 0x3aaa6409, - 0x3aee4d48, - 0x34b945, - 0x202d43, - 0x21b744, - 0x345805, - 0x273dc6, - 0x274805, - 0x28f584, - 0x3a4dc8, - 0x312ec5, - 0x299a84, - 0x211587, - 0x2a550a, - 0x3813ca, - 0x308f07, - 0x202c47, - 0x303647, - 0x271907, - 0x2ff9c5, - 0x204906, - 0x22b9c7, - 0x2c8684, - 0x2db006, - 0x2daf06, - 0x208185, - 0x331c04, - 0x388bc6, - 0x2a4707, - 0x232646, - 0x2bfa07, - 0x232dc3, - 0x26c7c6, - 0x23cf85, - 0x285f07, - 0x27100a, - 0x284e04, - 0x220808, - 0x2a2009, - 0x2d0e47, - 0x31e8c6, - 0x257988, - 0x28b2c9, - 0x314784, - 0x376004, - 0x35d785, - 0x22b6c8, - 0x2ccc07, - 0x29a3c9, - 0x3af5c8, - 0x353706, - 0x24d486, - 0x29fd88, - 0x365bc6, - 0x297685, - 0x2890c6, - 0x280ec8, - 0x256286, - 0x25cb8b, - 0x2ac646, - 0x2a224d, - 0x208605, - 0x2af306, - 0x218a05, - 0x35d949, - 0x27a787, - 0x36d148, - 0x2969c6, - 0x2a1509, - 0x341046, - 0x270f85, - 0x2a7f06, - 0x2d3586, - 0x2d3b09, - 0x333f06, - 0x3529c7, - 0x248c85, - 0x201d83, - 0x25cd05, - 0x2a2507, - 0x338d06, - 0x208509, - 0x320c86, - 0x289306, - 0x219fc9, - 0x288ac9, - 0x2a8747, - 0x20cd08, - 0x280509, - 0x286988, - 0x38b5c6, - 0x2de245, - 0x23fa4a, - 0x289386, - 0x2bf1c6, - 0x2d7605, - 0x272408, - 0x2220c7, - 0x239fca, - 0x253b46, - 0x27a645, - 0x20a506, - 0x236b47, - 0x31e787, - 0x24fc45, - 0x271145, - 0x2e79c6, - 0x2fbfc6, - 0x2be306, - 0x2bb884, - 0x287e09, - 0x290bc6, - 0x2d430a, - 0x222b88, - 0x3059c8, - 0x3813ca, - 0x205b45, - 0x2a4645, - 0x3575c8, - 0x2b0fc8, - 0x2b43c7, - 0x295946, - 0x329608, - 0x30a447, - 0x287088, - 0x2bbec6, - 0x289b88, - 0x29cd06, - 0x257e47, - 0x2a27c6, - 0x388bc6, - 0x383d4a, - 0x345506, - 0x2de249, - 0x36b086, - 0x2b6c0a, - 0x2e2dc9, - 0x2fe406, - 0x2bccc4, - 0x2b75cd, - 0x28ff87, - 0x32df46, - 0x2c8845, - 0x3410c5, - 0x204dc6, - 0x2d4fc9, - 0x3879c7, - 0x2826c6, - 0x2bd406, - 0x28f609, - 0x33f784, - 0x3a1184, - 0x39c0c8, - 0x260f46, - 0x279388, - 0x30fec8, - 0x378187, - 0x3beb49, - 0x2be507, - 0x2b678a, - 0x2fc88f, - 0x25100a, - 0x2bdc45, - 0x281105, - 0x220085, - 0x28be47, - 0x236703, - 0x20cf08, - 0x201e46, - 0x201f49, - 0x2e4806, - 0x3a3607, - 0x2a12c9, - 0x36d048, - 0x2d76c7, - 0x315603, - 0x34b9c5, - 0x236685, - 0x2bb6cb, - 0x385e44, - 0x30ad44, - 0x27f006, - 0x315e87, - 0x392a4a, - 0x251a87, - 0x36a947, - 0x2852c5, - 0x2016c5, - 0x253689, - 0x388bc6, - 0x25190d, - 0x334145, - 0x2a10c3, - 0x200dc3, - 0x39cf05, - 0x3534c5, - 0x257988, - 0x283007, - 0x3a0f06, - 0x2a6086, - 0x232545, - 0x23cd87, - 0x377c87, - 0x23ea07, - 0x2d9a4a, - 0x26c888, - 0x2bb884, - 0x256007, - 0x284707, - 0x352846, - 0x26f5c7, - 0x2ece48, - 0x2e8548, - 0x276346, - 0x374f88, - 0x2d1704, - 0x22b9c6, - 0x239b86, - 0x333b86, - 0x2d0006, - 0x233ac4, - 0x2719c6, - 0x2c7146, - 0x29f406, - 0x2381c6, - 0x213ec6, - 0x223f06, - 0x3a0e08, - 0x3bcc88, - 0x2da288, - 0x274a08, - 0x357546, - 0x217e05, - 0x2dd4c6, - 0x2b3205, - 0x397f07, - 0x27df05, - 0x21ae83, - 0x2058c5, - 0x34cc44, - 0x214005, - 0x22dc83, - 0x33d807, - 0x374a48, - 0x2bfac6, - 0x2b0c4d, - 0x2810c6, - 0x29e985, - 0x227603, - 0x2c2a89, - 0x33f906, - 0x29dd86, - 0x2a8004, - 0x250f87, - 0x334546, - 0x387c85, - 0x20b2c3, - 0x209484, - 0x2848c6, - 0x204a04, - 0x239c88, - 0x2005c9, - 0x325f49, - 0x2a7e0a, - 0x2a918d, - 0x20abc7, - 0x2bf046, - 0x205ec4, - 0x2f6e09, - 0x28e688, - 0x28fb86, - 0x245246, - 0x26f5c7, - 0x2b9786, - 0x22c986, - 0x36aac6, - 0x3b0d0a, - 0x227248, - 0x364dc5, - 0x26fa09, - 0x28758a, - 0x2f1e88, - 0x2a40c8, - 0x29dd08, - 0x2ad74c, - 0x318585, - 0x2a6308, - 0x2e7546, - 0x36d2c6, - 0x3a34c7, - 0x251985, - 0x289245, - 0x325e09, - 0x219847, - 0x201f05, - 0x22d887, - 0x200dc3, - 0x2cd145, - 0x214308, - 0x25d087, - 0x2a3f89, - 0x2dac05, - 0x395a04, - 0x2a8e48, - 0x2dddc7, - 0x2d7888, - 0x2508c8, - 0x2d6645, - 0x281906, - 0x2a6186, - 0x277449, - 0x2b26c7, - 0x2b3ac6, - 0x2236c7, - 0x20e743, - 0x274084, - 0x2d1805, - 0x23cec4, - 0x393244, - 0x288547, - 0x25b347, - 0x234284, - 0x2a3dd0, - 0x234e47, - 0x2016c5, - 0x37178c, - 0x250684, - 0x2a9e48, - 0x257d49, - 0x36e646, - 0x34dd48, - 0x223384, - 0x37d0c8, - 0x23a5c6, - 0x238048, - 0x2a4cc6, - 0x2cc8cb, - 0x201d85, - 0x2d1688, - 0x200a04, - 0x200a0a, - 0x2a3f89, - 0x357f06, - 0x220148, - 0x263805, - 0x2b9044, - 0x2a9d46, - 0x23e8c8, - 0x287a88, - 0x329e86, - 0x358b04, - 0x23f9c6, - 0x2be587, - 0x27ff87, - 0x26f5cf, - 0x204187, - 0x2fe4c7, - 0x23d2c5, - 0x35fcc5, - 0x2a8409, - 0x2ed806, - 0x286045, - 0x288dc7, - 0x2c6188, - 0x29f505, - 0x2a27c6, - 0x2229c8, - 0x28ab8a, - 0x39c888, - 0x292f47, - 0x2fccc6, - 0x26f9c6, - 0x20ca43, - 0x2052c3, - 0x287749, - 0x280389, - 0x2a6b86, - 0x2dac05, - 0x304588, - 0x220148, - 0x365d48, - 0x36ab4b, - 0x2b0e87, - 0x315849, - 0x26f848, - 0x356284, - 0x3886c8, - 0x295089, - 0x2b3dc5, - 0x28bd47, - 0x274105, - 0x287988, - 0x297bcb, - 0x29d510, - 0x2aec45, - 0x21e20c, - 0x3a10c5, - 0x285343, - 0x296706, - 0x2c5a04, - 0x28fa06, - 0x2a4707, - 0x222a44, - 0x24c3c8, - 0x20cdcd, - 0x330a05, - 0x20ac04, - 0x241b84, - 0x27bd89, - 0x292bc8, - 0x320b07, - 0x23a648, - 0x287ec8, - 0x2829c5, - 0x28c647, - 0x282947, - 0x342807, - 0x271149, - 0x223c49, - 0x36c986, - 0x2c3a06, - 0x26f806, - 0x33e9c5, - 0x3b4944, - 0x200006, - 0x200386, - 0x282a08, - 0x23680b, - 0x284cc7, - 0x205ec4, - 0x334486, - 0x2ed187, - 0x388f45, - 0x210bc5, - 0x21b484, - 0x223bc6, - 0x200088, - 0x2f6e09, - 0x259706, - 0x28df88, - 0x387d46, - 0x355088, - 0x2d6c8c, - 0x282886, - 0x29e64d, - 0x29eacb, - 0x352a85, - 0x377dc7, - 0x334006, - 0x31e648, - 0x36ca09, - 0x276608, - 0x2016c5, - 0x2076c7, - 0x286a88, - 0x332489, - 0x2a0986, - 0x25960a, - 0x31e3c8, - 0x27644b, - 0x2d964c, - 0x37d1c8, - 0x283e46, - 0x28c048, - 0x28a807, - 0x2e4909, - 0x2976cd, - 0x2a26c6, - 0x365308, - 0x3bcb49, - 0x2c4a48, - 0x289c88, - 0x2c798c, - 0x2c8e87, - 0x2c96c7, - 0x270f85, - 0x31a807, - 0x2c6048, - 0x2a9dc6, - 0x26020c, - 0x2f60c8, - 0x2d5708, - 0x262246, - 0x236407, - 0x36cb84, - 0x274a08, - 0x28d88c, - 0x22834c, - 0x2bdcc5, - 0x2b85c7, - 0x358a86, - 0x236386, - 0x35db08, - 0x202b84, - 0x23264b, - 0x37d80b, - 0x2fccc6, - 0x20cc47, - 0x339305, - 0x278585, - 0x232786, - 0x2637c5, - 0x385e05, - 0x2e40c7, - 0x27f609, - 0x2fc184, - 0x2feac5, - 0x2ead45, - 0x2b5448, - 0x235685, - 0x2c0b89, - 0x2b16c7, - 0x2b16cb, - 0x261ac6, - 0x3a0b49, - 0x331b48, - 0x272885, - 0x342908, - 0x223c88, - 0x249b07, - 0x383b47, - 0x2885c9, - 0x237f87, - 0x27de09, - 0x29b88c, - 0x2a6b88, - 0x331009, - 0x360987, - 0x287f89, - 0x25b487, - 0x2d9748, - 0x3bed05, - 0x22b946, - 0x2c8888, - 0x30cf08, - 0x287449, - 0x385e47, - 0x278645, - 0x21f949, - 0x345306, - 0x2440c4, - 0x2440c6, - 0x35d048, - 0x254547, - 0x236a08, - 0x375049, - 0x3b1a07, - 0x2a56c6, - 0x377e84, - 0x205949, - 0x28c4c8, - 0x262107, - 0x2b56c6, - 0x236746, - 0x2bf144, - 0x241986, - 0x202003, - 0x34f109, - 0x201d46, - 0x3752c5, - 0x2a6086, - 0x2d79c5, - 0x286f08, - 0x37cf07, - 0x261e06, - 0x234d06, - 0x3059c8, - 0x2a8587, - 0x2a2705, - 0x2a3bc8, - 0x3bb748, - 0x31e3c8, - 0x3a0f85, - 0x22b9c6, - 0x325d09, - 0x2772c4, - 0x351d8b, - 0x22c68b, - 0x364cc9, - 0x200dc3, - 0x25efc5, - 0x21d306, - 0x3ba188, - 0x2fc804, - 0x2bfac6, - 0x2d9b89, - 0x2bc9c5, - 0x2e4006, - 0x2dddc6, - 0x220144, - 0x2af4ca, - 0x375208, - 0x30cf06, - 0x2cf245, - 0x3b8247, - 0x23d187, - 0x281904, - 0x22c8c7, - 0x2b6784, - 0x333b06, - 0x20cf43, - 0x271145, - 0x334f05, - 0x3beec8, - 0x2561c5, - 0x2825c9, - 0x274847, - 0x27484b, - 0x2aa04c, - 0x2aa64a, - 0x33f5c7, - 0x202e83, - 0x202e88, - 0x3a1145, - 0x29f585, - 0x2140c4, - 0x2d9646, - 0x257d46, - 0x2419c7, - 0x34d58b, - 0x233ac4, - 0x2e7644, - 0x2cbd04, - 0x2d3706, - 0x222a44, - 0x22b7c8, - 0x34b885, - 0x24fac5, - 0x365c87, - 0x377ec9, - 0x3534c5, - 0x38dcca, - 0x248b89, - 0x2911ca, - 0x3b0e49, - 0x310444, - 0x2bd4c5, - 0x2b9888, - 0x2f150b, - 0x35d785, - 0x33be86, - 0x236304, - 0x282b06, - 0x3b1889, - 0x2ed287, - 0x320e48, - 0x2a9506, - 0x2be507, - 0x287a88, - 0x3870c6, - 0x39b804, - 0x3743c7, - 0x376945, - 0x389b87, - 0x200104, - 0x333f86, - 0x2d5f48, - 0x29ec88, - 0x2e7007, - 0x27f988, - 0x29cdc5, - 0x213e44, - 0x3812c8, - 0x27fa84, - 0x220005, - 0x2ffbc4, - 0x30a547, - 0x290c87, - 0x2880c8, - 0x2d7a06, - 0x256145, - 0x2823c8, - 0x39ca88, - 0x2a7d49, - 0x22c986, - 0x23a048, - 0x20088a, - 0x388fc8, - 0x2ec085, - 0x349286, - 0x248a48, - 0x20778a, - 0x226047, - 0x28ee45, - 0x29ad48, - 0x2c2404, - 0x272486, - 0x2c9a48, - 0x213ec6, - 0x20b308, - 0x296e87, - 0x211486, - 0x2bccc4, - 0x364707, - 0x2b8e84, - 0x3b1847, - 0x2a064d, - 0x288805, - 0x2d4dcb, - 0x2285c6, - 0x257808, - 0x24c384, - 0x357746, - 0x2848c6, - 0x28c387, - 0x29e30d, - 0x24e587, - 0x2b93c8, - 0x278705, - 0x276e08, - 0x2ccb86, - 0x29ce48, - 0x22ab46, - 0x25a707, - 0x39ae89, - 0x36ebc7, - 0x28fe48, - 0x27af45, - 0x222e08, - 0x219405, - 0x3ab545, - 0x3b10c5, - 0x23ef43, - 0x289144, - 0x26fa05, - 0x241489, - 0x3043c6, - 0x2ecf48, - 0x383905, - 0x2bb507, - 0x2ad54a, - 0x2e3f49, - 0x2d348a, - 0x2da308, - 0x22d6cc, - 0x288e4d, - 0x301bc3, - 0x20b208, - 0x209445, - 0x28a946, - 0x36cec6, - 0x2ebb05, - 0x2237c9, - 0x20e1c5, - 0x2823c8, - 0x25fe06, - 0x35e006, - 0x2a8d09, - 0x39ed87, - 0x297e86, - 0x2ad4c8, - 0x333a88, - 0x2e4f47, - 0x2381ce, - 0x2ccdc5, - 0x332385, - 0x213dc8, - 0x20a247, - 0x200842, - 0x2c7504, - 0x28f90a, - 0x2621c8, - 0x389206, - 0x2a1408, - 0x2a6186, - 0x3337c8, - 0x2b3ac8, - 0x3ab504, - 0x2bba45, - 0x681384, - 0x681384, - 0x681384, - 0x201e03, - 0x2365c6, - 0x282886, - 0x2a508c, - 0x200943, - 0x223286, - 0x20cf04, - 0x33f888, - 0x2d99c5, - 0x28fa06, - 0x2c31c8, - 0x2db2c6, - 0x261d86, - 0x357d08, - 0x2d1887, - 0x237d49, - 0x2fa8ca, - 0x20a944, - 0x27df05, - 0x29a385, - 0x2f6c06, - 0x20ac06, - 0x2a5ac6, - 0x2ff206, - 0x237e84, - 0x237e8b, - 0x23c584, - 0x2a5245, - 0x2b2ac5, - 0x378246, - 0x2090c8, - 0x288d07, - 0x320c04, - 0x232fc3, - 0x2c1f05, - 0x311847, - 0x288c0b, - 0x3bedc7, - 0x2c30c8, - 0x2e7287, - 0x23d406, - 0x27a4c8, - 0x2b004b, - 0x345746, - 0x21d449, - 0x2b01c5, - 0x315603, - 0x2e4006, - 0x296d88, - 0x21f083, - 0x271e03, - 0x287a86, - 0x2a6186, - 0x36958a, - 0x283e85, - 0x28470b, - 0x2a5fcb, - 0x210a83, - 0x20b943, - 0x2b6704, - 0x2af6c7, - 0x296e04, - 0x277344, - 0x2e73c4, - 0x223e88, - 0x2cf188, - 0x205249, - 0x39e3c8, - 0x28b487, - 0x2381c6, - 0x2ecb8f, - 0x2ccf06, - 0x2d9944, - 0x2cefca, - 0x311747, - 0x208206, - 0x297509, - 0x2051c5, - 0x3bf005, - 0x205306, - 0x222f43, - 0x2c2449, - 0x2273c6, - 0x202d09, - 0x392a46, - 0x271145, - 0x2be0c5, - 0x204183, - 0x2af808, - 0x213887, - 0x201e44, - 0x33f708, - 0x2ffe04, - 0x2f0486, - 0x296706, - 0x248fc6, - 0x2d1549, - 0x29f505, - 0x388bc6, - 0x2666c9, - 0x2cb906, - 0x223f06, - 0x397346, - 0x21ce85, - 0x2ffbc6, - 0x25a704, - 0x3bed05, - 0x2c8884, - 0x2b9f86, - 0x334104, - 0x2136c3, - 0x28e745, - 0x23dac8, - 0x262987, - 0x2c1ac9, - 0x28ed48, - 0x29fb51, - 0x2dde4a, - 0x2fcc07, - 0x25a986, - 0x20cf04, - 0x2c8988, - 0x233fc8, - 0x29fd0a, - 0x2c094d, - 0x2a7f06, - 0x357e06, - 0x3647c6, - 0x24fac7, - 0x2b9485, - 0x210187, - 0x20cdc5, - 0x2b1804, - 0x2ae086, - 0x241807, - 0x2c214d, - 0x248987, - 0x3a4cc8, - 0x2826c9, - 0x349186, - 0x2a0905, - 0x22dcc4, - 0x35d146, - 0x281806, - 0x262346, - 0x2a1c88, - 0x21cd43, - 0x20aa83, - 0x338e45, - 0x207b06, - 0x2b3a85, - 0x2a9708, - 0x2a48ca, - 0x3a2dc4, - 0x33f888, - 0x29dd08, - 0x378087, - 0x3839c9, - 0x2c2dc8, - 0x2a6d07, - 0x2957c6, - 0x213eca, - 0x35d1c8, - 0x2f8589, - 0x292c88, - 0x229b89, - 0x2e8747, - 0x33bdc5, - 0x36ad46, - 0x2a9c48, - 0x287c08, - 0x29de88, - 0x2fcdc8, - 0x2a5245, - 0x218944, - 0x213588, - 0x24b384, - 0x3b0c44, - 0x271145, - 0x299ac7, - 0x377c89, - 0x28c187, - 0x2008c5, - 0x27f206, - 0x363686, - 0x200b84, - 0x2a9046, - 0x255f84, - 0x276d06, - 0x377a46, - 0x21eec6, - 0x2016c5, - 0x2a95c7, - 0x202e83, - 0x21dd89, - 0x3057c8, - 0x2f6d04, - 0x2f6d0d, - 0x29ed88, - 0x2d7248, - 0x2f8506, - 0x39af89, - 0x2e3f49, - 0x3b1585, - 0x2a49ca, - 0x2edbca, - 0x2a5ccc, - 0x2a5e46, - 0x27fe06, - 0x2cd086, - 0x2c84c9, - 0x28ab86, - 0x2101c6, - 0x20e286, - 0x274a08, - 0x27f986, - 0x2d92cb, - 0x299c45, - 0x24fac5, - 0x280085, - 0x39be46, - 0x213e83, - 0x248f46, - 0x248907, - 0x2c8845, - 0x24d545, - 0x3410c5, - 0x313846, - 0x204dc4, - 0x385806, - 0x284049, - 0x39bccc, - 0x2b1548, - 0x23e844, - 0x2ff8c6, - 0x2286c6, - 0x296d88, - 0x220148, - 0x39bbc9, - 0x3b8247, - 0x260c89, - 0x255806, - 0x237404, - 0x214944, - 0x20a584, - 0x287a88, - 0x377aca, - 0x353446, - 0x35fb87, - 0x37e787, - 0x3a0c45, - 0x29a344, - 0x295046, - 0x2b94c6, - 0x202bc3, - 0x305607, - 0x2507c8, - 0x3b16ca, - 0x2d4708, - 0x28a688, - 0x334145, - 0x352b85, - 0x284dc5, - 0x3a1006, - 0x2393c6, - 0x25b285, - 0x34f349, - 0x29a14c, - 0x284e87, - 0x29fd88, - 0x24ee05, - 0x681384, - 0x240ac4, - 0x25d1c4, - 0x217946, - 0x2a728e, - 0x3bf087, - 0x24fcc5, - 0x27724c, - 0x2ffcc7, - 0x241787, - 0x274e89, - 0x2208c9, - 0x28ee45, - 0x3057c8, - 0x325d09, - 0x31e285, - 0x2c8788, - 0x227546, - 0x381546, - 0x2e2dc4, - 0x25ff08, - 0x248743, - 0x235e44, - 0x2c1f85, - 0x204dc7, - 0x21b4c5, - 0x200749, - 0x27e64d, - 0x2935c6, - 0x229b04, - 0x2958c8, - 0x27f44a, - 0x21da87, - 0x243905, - 0x235e83, - 0x2a618e, - 0x2af90c, - 0x2f1f87, - 0x2a7447, - 0x200143, - 0x28abc5, - 0x25d1c5, - 0x2a17c8, - 0x29db49, - 0x23e746, - 0x296e04, - 0x2fcb46, - 0x3650cb, - 0x2e3ccc, - 0x376447, - 0x2d9585, - 0x3bb648, - 0x2e4d05, - 0x2cefc7, - 0x2ddc87, - 0x248745, - 0x213e83, - 0x3b36c4, - 0x21b705, - 0x2fc085, - 0x2fc086, - 0x2821c8, - 0x241807, - 0x36d1c6, - 0x25b686, - 0x3b1006, - 0x2f88c9, - 0x28c747, - 0x262606, - 0x2e3e46, - 0x27e106, - 0x2af405, - 0x21e8c6, - 0x390e05, - 0x235708, - 0x2990cb, - 0x294b86, - 0x37e7c4, - 0x2c8109, - 0x274844, - 0x2274c8, - 0x2441c7, - 0x289b84, - 0x2c2688, - 0x2c94c4, - 0x2af444, - 0x39ac45, - 0x330a46, - 0x223dc7, - 0x20b3c3, - 0x2a5785, - 0x32a504, - 0x3323c6, - 0x3b1608, - 0x39c785, + 0x35edcb, + 0x35f3ca, + 0x36008b, + 0x36034a, + 0x3605ca, + 0x36084a, + 0x37d74b, + 0x3856cb, + 0x388f8e, + 0x38930b, + 0x391f4b, + 0x392e0b, + 0x39a6ca, + 0x39a949, + 0x39ab8a, + 0x39c6ca, + 0x3b06cb, + 0x3b204b, + 0x3b2a0a, + 0x3b390b, + 0x3b904b, + 0x3c554b, + 0x3ae7fd48, + 0x3b287989, + 0x3b69d989, + 0x3bad8988, + 0x34c805, + 0x200583, + 0x22a3c4, + 0x217c05, + 0x267ac6, + 0x26cfc5, + 0x286284, + 0x344d48, + 0x30b505, + 0x290604, + 0x2064c7, + 0x29cf0a, + 0x266b4a, + 0x2dbb87, + 0x20c4c7, + 0x2fd2c7, + 0x282187, + 0x2f8c45, + 0x3b6e46, + 0x386007, + 0x244e44, + 0x2df546, + 0x2df446, + 0x204745, + 0x3389c4, + 0x2975c6, + 0x29bfc7, + 0x22df06, + 0x27c8c7, + 0x250803, + 0x3912c6, + 0x234f05, + 0x27d747, + 0x26a84a, + 0x26e7c4, + 0x21bd88, + 0x2b8a49, + 0x2e0d07, + 0x319c46, + 0x258788, + 0x2ef589, + 0x30f084, + 0x33a484, + 0x29ef05, + 0x2ba648, + 0x2c2807, + 0x2b3e49, + 0x22dc08, + 0x2f2306, + 0x310806, + 0x297f88, + 0x362bc6, + 0x28e4c5, + 0x2816c6, + 0x278988, + 0x237986, + 0x25af0b, + 0x2c7c06, + 0x299b0d, + 0x369405, + 0x2a8506, + 0x21f085, + 0x331b49, + 0x3a6cc7, + 0x318308, + 0x2a1e46, 0x298d89, - 0x21fb45, - 0x223288, - 0x22cfc7, - 0x398048, - 0x2c1907, - 0x2fe589, - 0x271846, - 0x360486, - 0x20e284, - 0x295705, - 0x3093cc, - 0x280087, - 0x280fc7, - 0x37e648, - 0x2935c6, - 0x2794c4, - 0x34bc04, - 0x288449, - 0x2cd186, - 0x253707, - 0x2cff84, - 0x24ab06, - 0x35f245, - 0x2d7547, - 0x2d9246, - 0x2594c9, - 0x2eda07, - 0x26f5c7, - 0x2a8b86, - 0x24aa45, - 0x285988, + 0x33ffc6, + 0x26a7c5, + 0x24c486, + 0x288b86, + 0x2c6e49, + 0x31e2c6, + 0x29cc07, + 0x245e85, + 0x203983, + 0x25b085, + 0x299dc7, + 0x3ab746, + 0x369309, + 0x3b3086, + 0x26b146, + 0x213fc9, + 0x2810c9, + 0x29fac7, + 0x200908, + 0x2b2f49, + 0x27ec48, + 0x330a46, + 0x2d1d85, + 0x240c8a, + 0x26b1c6, + 0x239346, + 0x2cac05, + 0x2d4888, + 0x22b287, + 0x233f0a, + 0x254f86, + 0x251dc5, + 0x3324c6, + 0x224507, + 0x319b07, + 0x2835c5, + 0x26a985, + 0x395a06, + 0x3b8c06, + 0x2fa846, + 0x2bc7c4, + 0x280449, + 0x288806, + 0x2c814a, 0x227248, - 0x2f6a46, - 0x39c7c5, - 0x344806, - 0x202c03, - 0x2a1649, - 0x2a584e, - 0x2c1608, - 0x2fff08, - 0x2f684b, - 0x298fc6, - 0x20a884, - 0x261d84, - 0x2a594a, - 0x21e107, - 0x2626c5, - 0x21d449, - 0x2c7205, - 0x3b0c87, - 0x250584, - 0x27b907, - 0x30fdc8, - 0x2d0f06, - 0x365489, - 0x2c2eca, - 0x21e086, - 0x29e8c6, - 0x2b2a45, - 0x38ef85, - 0x325647, - 0x24ec48, - 0x35f188, - 0x3ab506, - 0x2be145, - 0x20a98e, - 0x2bb884, - 0x2a1745, - 0x27eb89, - 0x2ed608, - 0x292e86, - 0x2a36cc, - 0x2a44d0, - 0x2a6ecf, - 0x2a8308, - 0x33f5c7, - 0x2016c5, - 0x26fa05, - 0x389089, - 0x29af49, - 0x23fac6, - 0x35d807, - 0x2b8545, - 0x2b43c9, - 0x3528c6, - 0x28a9cd, - 0x288789, - 0x277344, - 0x2c1388, - 0x213649, - 0x353606, - 0x27f305, - 0x360486, - 0x320d09, - 0x281688, - 0x217e05, - 0x200984, - 0x2a388b, - 0x3534c5, - 0x2a39c6, - 0x289186, - 0x26e646, - 0x27c18b, - 0x298e89, - 0x25b5c5, - 0x397e07, - 0x2dddc6, - 0x34dec6, - 0x25cf48, - 0x330b49, - 0x3a4a8c, - 0x311648, - 0x23c586, - 0x329e83, - 0x28bf46, - 0x27bfc5, - 0x284a48, - 0x2bdb46, - 0x2d7788, - 0x251b05, - 0x283245, - 0x27a8c8, - 0x333947, - 0x36ce07, - 0x2419c7, - 0x34dd48, - 0x39ad08, - 0x31a706, - 0x2b9dc7, - 0x273f47, - 0x27be8a, - 0x20d703, - 0x39be46, - 0x23e985, - 0x28f904, - 0x2826c9, - 0x2fe504, - 0x262a04, - 0x2a4d44, - 0x2a744b, - 0x2137c7, - 0x20abc5, - 0x29cac8, - 0x27f206, - 0x27f208, - 0x283dc6, - 0x293345, - 0x293e85, - 0x295f46, - 0x296b48, - 0x297448, - 0x282886, - 0x29c90f, - 0x2a1110, - 0x208605, - 0x202e83, - 0x2374c5, - 0x315788, - 0x29ae49, - 0x31e3c8, - 0x2f8748, - 0x2bec08, - 0x213887, - 0x27eec9, - 0x2d7988, - 0x2730c4, - 0x2a4bc8, - 0x2b5509, - 0x2babc7, - 0x2a2644, - 0x28c248, - 0x2a938a, - 0x3085c6, - 0x2a7f06, - 0x22c849, - 0x2a4707, - 0x2d4588, - 0x2fdbc8, - 0x2cfe08, - 0x3690c5, - 0x38ff05, - 0x24fac5, - 0x25d185, - 0x38cb87, - 0x213e85, - 0x2c8845, - 0x20ae06, - 0x31e307, - 0x2f1447, - 0x2a9686, - 0x2da845, - 0x2a39c6, - 0x202f45, - 0x2b83c8, - 0x2f1e04, - 0x2cb986, - 0x348084, - 0x2b9048, - 0x2cba8a, - 0x28300c, - 0x34d785, - 0x24fb86, - 0x3a4c46, - 0x234b86, - 0x23c604, - 0x35f505, - 0x283c07, - 0x2a4789, - 0x2d3c07, - 0x681384, - 0x681384, - 0x320a85, - 0x38d584, - 0x2a308a, - 0x27f086, - 0x27a704, - 0x208185, - 0x3875c5, - 0x2b93c4, - 0x288dc7, - 0x21fac7, - 0x2d3708, - 0x342348, - 0x217e09, - 0x2a5308, - 0x2a324b, - 0x251044, - 0x375f45, - 0x2860c5, - 0x241949, - 0x330b49, - 0x2c8008, - 0x243f48, - 0x2df044, - 0x228705, - 0x202d43, - 0x2f6bc5, - 0x388c46, - 0x29d98c, - 0x2189c6, - 0x37cfc6, - 0x293105, - 0x3138c8, - 0x2c1786, - 0x25ab06, - 0x2a7f06, - 0x22e2cc, - 0x262504, - 0x3b114a, - 0x293048, - 0x29d7c7, - 0x32a406, - 0x23e807, - 0x2f2ec5, - 0x2b56c6, - 0x35c286, - 0x367cc7, - 0x262a44, - 0x30a645, - 0x27eb84, - 0x2b1887, - 0x27edc8, - 0x27fc8a, - 0x286907, - 0x375387, - 0x33f547, - 0x2e4e49, - 0x29d98a, - 0x2373c3, - 0x262945, - 0x20b343, - 0x2e7409, - 0x254ec8, - 0x23d2c7, - 0x31e4c9, - 0x227346, - 0x2042c8, - 0x33d785, - 0x39cb8a, - 0x2dbc89, - 0x276209, - 0x3a34c7, - 0x2340c9, - 0x21edc8, - 0x367e86, - 0x24fd48, - 0x21ce87, - 0x237f87, - 0x248b87, - 0x2d5dc8, - 0x2ff746, - 0x2a9145, - 0x283c07, - 0x29e3c8, - 0x348004, - 0x2d41c4, - 0x297d87, - 0x2b3e47, - 0x325b8a, - 0x367e06, - 0x35854a, - 0x2c7447, - 0x2bb647, - 0x358004, - 0x27dec4, - 0x2d7446, - 0x281b84, - 0x281b8c, - 0x203185, - 0x21ff89, - 0x265684, - 0x2b9485, - 0x27f3c8, - 0x22d245, - 0x204dc6, - 0x225f44, - 0x28f30a, - 0x2b25c6, - 0x2a424a, - 0x2b7887, - 0x236b45, - 0x222f45, - 0x3a0c8a, - 0x296cc5, - 0x2a7e06, - 0x24b384, - 0x2b6886, - 0x325705, - 0x2bdc06, - 0x2e700c, - 0x2d388a, - 0x2957c4, - 0x2381c6, - 0x2a4707, - 0x2d91c4, - 0x274a08, - 0x39e246, - 0x20a809, - 0x2baec9, - 0x2a6c89, - 0x351f46, - 0x21cf86, - 0x24fe87, - 0x34f288, - 0x21cd89, - 0x2137c7, - 0x29cc46, - 0x2be587, - 0x364685, - 0x2bb884, - 0x24fa47, - 0x274105, - 0x28f845, - 0x36c347, - 0x248608, - 0x3bb5c6, - 0x29f24d, - 0x2a19cf, - 0x2a5fcd, - 0x200904, - 0x23dbc6, - 0x2dc1c8, - 0x20e245, - 0x27c048, - 0x2499ca, - 0x277344, - 0x365646, - 0x33ae07, - 0x233ac7, - 0x2d1949, - 0x24fd05, - 0x2b93c4, - 0x2bb98a, - 0x2c2989, - 0x2341c7, - 0x272306, - 0x353606, - 0x228646, - 0x374486, - 0x2db94f, - 0x2dc089, - 0x27f986, - 0x233ec6, - 0x320289, - 0x2b9ec7, - 0x229403, - 0x22e446, - 0x2052c3, - 0x2eb9c8, - 0x2be3c7, - 0x2a8509, - 0x296588, - 0x36cf48, - 0x385f86, - 0x218909, - 0x398845, - 0x2b9f84, - 0x29a687, - 0x2c8545, - 0x200904, - 0x20ac88, - 0x202044, - 0x2b9c07, - 0x3749c6, - 0x2e7a85, - 0x292c88, - 0x3534cb, - 0x3778c7, - 0x3a0f06, - 0x2ccf84, - 0x348186, - 0x271145, - 0x274105, - 0x285709, - 0x2889c9, - 0x237fc4, - 0x238005, - 0x238205, - 0x39ca06, - 0x3058c8, - 0x2c6b86, - 0x25060b, - 0x36e4ca, - 0x2b8f85, - 0x293f06, - 0x3a2ac5, - 0x2e9dc5, - 0x2ad387, - 0x39c0c8, - 0x260c84, - 0x26be86, + 0x36fd08, + 0x266b4a, + 0x212505, + 0x29bf05, + 0x2dd048, + 0x2c9688, + 0x233907, + 0x2ba946, + 0x32bf88, + 0x309507, + 0x27f348, + 0x2b5706, + 0x281e48, + 0x295586, + 0x278307, + 0x33a206, + 0x2975c6, + 0x22ecca, + 0x232046, + 0x2d1d89, + 0x2ee586, + 0x35c00a, + 0x3c2f49, + 0x27dd86, + 0x2b8304, + 0x21600d, + 0x287c07, + 0x239c06, + 0x2bf845, + 0x340045, + 0x37f306, + 0x2e15c9, + 0x2d4407, + 0x279406, + 0x306886, + 0x286309, + 0x2a3204, + 0x242544, + 0x3c2a88, + 0x24f046, + 0x271348, + 0x2e8008, + 0x29f447, + 0x3b6589, + 0x2faa47, + 0x2af9ca, + 0x2e79cf, + 0x31194a, + 0x3070c5, + 0x278bc5, + 0x218b05, + 0x35c647, + 0x2240c3, + 0x200b08, + 0x21e646, + 0x21e749, + 0x2d8646, + 0x2c8547, + 0x298b49, + 0x318208, + 0x2cacc7, + 0x30eb43, + 0x34c885, + 0x224045, + 0x2bc60b, + 0x327ec4, + 0x2d6884, + 0x276bc6, + 0x30f407, + 0x38f4ca, + 0x206247, + 0x20c347, + 0x27cb85, + 0x3c6485, + 0x282609, + 0x2975c6, + 0x2060cd, + 0x31e505, + 0x2b18c3, + 0x20b003, + 0x3a4d45, + 0x351305, + 0x258788, + 0x27a347, + 0x2422c6, + 0x29d606, + 0x22de05, + 0x237847, + 0x3c1d47, + 0x23c6c7, + 0x37c5ca, + 0x391388, + 0x2bc7c4, + 0x257bc7, + 0x27bb07, + 0x33f086, + 0x2692c7, + 0x2a1808, + 0x395f08, + 0x329b06, + 0x20c708, + 0x2cfbc4, + 0x386006, + 0x370d86, + 0x36bd46, + 0x277806, + 0x29b244, + 0x282246, + 0x2be246, + 0x297986, + 0x2060c6, + 0x20aec6, + 0x2a1646, + 0x2421c8, + 0x385a88, + 0x2cdac8, + 0x26d1c8, + 0x2dcfc6, + 0x212305, + 0x39e746, + 0x2ac285, + 0x396f87, + 0x22dcc5, + 0x213c03, + 0x38e045, + 0x33dd04, + 0x20b005, + 0x247643, + 0x33c4c7, + 0x30d708, + 0x27c986, + 0x2c930d, + 0x278b86, + 0x296f45, + 0x222083, + 0x2bbcc9, + 0x2a3386, + 0x291706, + 0x271e04, + 0x3118c7, + 0x23a1c6, + 0x2d46c5, + 0x21af83, + 0x3be4c4, + 0x27bcc6, + 0x3b6f44, + 0x370e88, + 0x3459c9, + 0x2317c9, + 0x29ed0a, + 0x2a05cd, + 0x2118c7, + 0x2391c6, + 0x20f984, + 0x2867c9, + 0x284ac8, + 0x287806, + 0x241906, + 0x2692c7, + 0x2d9346, + 0x22a046, + 0x347086, + 0x23ed4a, + 0x221cc8, + 0x22f885, + 0x2a2fc9, + 0x27f84a, + 0x2ff648, + 0x29b6c8, + 0x291688, + 0x29d24c, + 0x3124c5, + 0x29d888, + 0x385d86, + 0x24c9c6, + 0x35eb07, + 0x206145, + 0x281845, + 0x231689, + 0x2139c7, + 0x21e705, + 0x22aec7, + 0x20b003, + 0x2c2d45, + 0x2151c8, + 0x280d47, + 0x29b589, + 0x2e9f85, + 0x33e384, + 0x2a0288, + 0x2f16c7, + 0x2cae88, + 0x3aac88, + 0x2e1dc5, + 0x21e546, + 0x29d706, + 0x3a7009, + 0x2cb3c7, + 0x2ac8c6, + 0x206e87, + 0x239fc3, + 0x267d84, + 0x2cfcc5, + 0x2f3f84, + 0x246804, + 0x27ffc7, + 0x340d87, + 0x26dc84, + 0x29b3d0, + 0x31d507, + 0x3c6485, + 0x2561cc, + 0x224a04, + 0x2c4c88, + 0x278209, + 0x375886, + 0x240088, + 0x21ca84, + 0x276ec8, + 0x234506, + 0x22eb48, + 0x29a086, + 0x28854b, + 0x38ddc5, + 0x2cfb48, + 0x2173c4, + 0x345e0a, + 0x29b589, + 0x33a106, + 0x218bc8, + 0x25ed85, + 0x31dec4, + 0x2c4b86, + 0x23c588, + 0x27fd48, + 0x32c806, + 0x3c2344, + 0x240c06, + 0x2faac7, + 0x277d87, + 0x2692cf, + 0x205847, + 0x27de47, + 0x351685, + 0x35e345, + 0x29f789, + 0x382e46, + 0x27d885, + 0x2813c7, + 0x3934c8, + 0x2c7645, + 0x33a206, + 0x227088, + 0x2eee4a, + 0x3bf088, + 0x28ab07, + 0x2e7e06, + 0x2a2f86, + 0x202583, + 0x20de03, + 0x27fa09, + 0x2b2dc9, + 0x2c4a86, + 0x2e9f85, + 0x36bac8, + 0x218bc8, + 0x362d48, + 0x34710b, + 0x2c9547, + 0x309149, + 0x269548, + 0x350284, + 0x318648, + 0x28c889, + 0x2acbc5, + 0x35c547, + 0x267e05, + 0x27fc48, + 0x28eb4b, + 0x295d90, + 0x2a8145, + 0x21730c, + 0x242485, + 0x27cc03, + 0x2b1d06, + 0x2bd884, + 0x2404c6, + 0x29bfc7, + 0x227104, + 0x248688, + 0x2009cd, + 0x2dfc05, + 0x211904, + 0x28f244, + 0x28f249, + 0x2ae548, + 0x31bc47, + 0x234588, + 0x280508, + 0x279705, + 0x21f2c7, + 0x279687, + 0x23ac87, + 0x26a989, + 0x346dc9, + 0x272146, + 0x383b46, + 0x269506, + 0x33b6c5, + 0x3aa4c4, + 0x3bd646, + 0x3c4c46, + 0x279748, + 0x2241cb, + 0x26e687, + 0x20f984, + 0x23a106, + 0x2a1b47, + 0x335405, + 0x3583c5, + 0x223884, + 0x346d46, + 0x3bd6c8, + 0x2867c9, + 0x2091c6, + 0x2848c8, + 0x2d4786, + 0x350908, + 0x2ce58c, + 0x2795c6, + 0x296c0d, + 0x29708b, + 0x29ccc5, + 0x3c1e87, + 0x31e3c6, + 0x3199c8, + 0x2721c9, + 0x329dc8, + 0x3c6485, + 0x208947, + 0x27ed48, + 0x24ff89, + 0x2a5586, + 0x24da8a, + 0x319748, + 0x329c0b, + 0x2ccd8c, + 0x276fc8, + 0x27b286, + 0x21dfc8, + 0x2eeac7, + 0x205989, + 0x2f084d, 0x2974c6, - 0x21ef87, - 0x3155c4, - 0x2848c6, - 0x2427c5, - 0x2427c9, - 0x21b584, - 0x29a4c9, - 0x282886, - 0x2c8f48, - 0x238205, - 0x37e885, - 0x2bdc06, - 0x3a4989, - 0x2208c9, - 0x37d046, - 0x2ed708, - 0x277348, - 0x3a2a84, - 0x2bbcc4, - 0x2bbcc8, - 0x32e048, - 0x260d89, - 0x388bc6, - 0x2a7f06, - 0x3294cd, - 0x2bfac6, - 0x2d6b49, - 0x2dd5c5, - 0x205306, - 0x2102c8, - 0x326885, - 0x273f84, - 0x271145, - 0x2882c8, - 0x2a2e49, - 0x27ec44, - 0x333f86, - 0x22d10a, - 0x2f1e88, - 0x325d09, - 0x261f0a, - 0x31e446, - 0x2a1b88, - 0x2ced85, - 0x2c5ec8, - 0x2c1a05, - 0x227209, - 0x37ac49, - 0x203282, - 0x2b01c5, - 0x2782c6, - 0x2827c7, - 0x34e085, - 0x30ce06, - 0x326948, - 0x2935c6, - 0x2b9749, - 0x2810c6, - 0x25cdc8, - 0x2b0805, - 0x264906, - 0x25a808, - 0x287a88, - 0x2e8648, - 0x353788, - 0x21e8c4, - 0x281943, - 0x2b9984, - 0x286b06, - 0x3646c4, - 0x2ffe47, - 0x25aa09, - 0x2cbd05, - 0x2fdbc6, - 0x22e446, - 0x28200b, - 0x2b8ec6, - 0x2cf8c6, - 0x2d13c8, - 0x24d486, - 0x236943, - 0x2164c3, - 0x2bb884, - 0x239f45, - 0x387b87, - 0x27edc8, - 0x27edcf, - 0x283b0b, - 0x3056c8, - 0x334006, - 0x3059ce, - 0x251143, - 0x387b04, - 0x2b8e45, - 0x2b9246, - 0x29514b, - 0x299b86, - 0x222a49, - 0x2e7a85, - 0x3999c8, - 0x216688, - 0x22078c, - 0x2a7486, - 0x2f6c06, - 0x2dac05, - 0x28fc08, - 0x25a805, - 0x356288, - 0x2a3a4a, - 0x2a6409, - 0x681384, - 0x3b60f882, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x39c783, - 0x238543, - 0x23cac3, - 0x323043, - 0x231604, - 0x208e83, - 0x201a03, - 0x213083, - 0x286644, - 0x238543, - 0x240244, - 0x23cac3, - 0x2de944, - 0x323043, - 0x34e347, - 0x28cac3, - 0x200e03, - 0x293408, - 0x201a03, - 0x29630b, - 0x2f3743, - 0x3a03c6, - 0x205082, - 0x22facb, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x238543, - 0x23cac3, - 0x323043, - 0x201a03, - 0x220b83, - 0x201503, - 0x207102, - 0x16fb88, - 0x32d1c5, - 0x274188, - 0x2f9f88, - 0x20f882, - 0x20a605, - 0x3785c7, - 0x201842, - 0x24c5c7, - 0x207b02, - 0x2f6607, - 0x2cc409, - 0x2ce948, - 0x2cfc89, - 0x24b2c2, - 0x2707c7, - 0x37cdc4, - 0x378687, - 0x36e3c7, - 0x264d42, - 0x28cac3, - 0x214642, - 0x204d42, - 0x200442, - 0x21cc82, - 0x206b42, - 0x20d2c2, - 0x2aff05, - 0x240a05, - 0xf882, - 0x3cac3, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x1a3443, - 0x201a03, - 0x170c3, - 0x8c1, - 0x238543, - 0x23cac3, - 0x323043, - 0x231604, - 0x255783, - 0x208e83, - 0x1a3443, - 0x201a03, - 0x221f43, - 0x3e4f5906, - 0x42bc3, - 0x873c5, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x20f882, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x84c2, - 0x16fb88, - 0xe03, - 0x1a3443, - 0x4ec04, - 0xe5105, - 0x207102, - 0x39cdc4, - 0x238543, - 0x23cac3, - 0x323043, - 0x38acc3, - 0x2b13c5, - 0x255783, - 0x211a83, - 0x208e83, - 0x21b543, - 0x201a03, - 0x215443, - 0x20e383, - 0x202443, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x20f882, - 0x201a03, - 0x16fb88, - 0x323043, - 0x1a3443, - 0x16fb88, - 0x1a3443, - 0x2bcc43, - 0x238543, - 0x23a844, - 0x23cac3, - 0x323043, - 0x205e82, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x238543, - 0x23cac3, - 0x323043, - 0x205e82, - 0x229443, - 0x208e83, - 0x201a03, - 0x2ef783, - 0x215443, - 0x207102, - 0x20f882, - 0x323043, - 0x208e83, - 0x201a03, - 0x3a03c5, - 0xa4f06, - 0x286644, - 0x205082, - 0x16fb88, - 0x207102, - 0x25088, - 0x134943, - 0x20f882, - 0x42899306, - 0x6a04, - 0xb610b, - 0x44e86, - 0x8cbc7, - 0x23cac3, - 0x51648, - 0x323043, - 0x8b205, - 0x1493c4, - 0x227583, - 0x556c7, - 0xe06c4, - 0x208e83, - 0x1a3284, - 0x1a3443, - 0x201a03, - 0x2f4544, - 0xb5ec8, - 0x12cf06, - 0x16308, - 0x1252c5, - 0x9fc9, - 0x20f882, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x200e03, - 0x201a03, - 0x2f3743, - 0x205082, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x231603, - 0x21bf84, - 0x208e83, - 0xe03, - 0x201a03, - 0x238543, - 0x23cac3, - 0x2de944, - 0x323043, - 0x208e83, - 0x201a03, - 0x3a03c6, - 0x23cac3, - 0x323043, - 0x18a783, - 0x201a03, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x8cbc7, - 0x16fb88, - 0x323043, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x45238543, - 0x23cac3, - 0x208e83, - 0x201a03, - 0x16fb88, - 0x207102, - 0x20f882, - 0x238543, - 0x323043, - 0x208e83, - 0x200442, - 0x201a03, - 0x31f1c7, - 0x342b8b, - 0x22fc83, - 0x244708, - 0x34f007, - 0x348746, - 0x382d45, - 0x232309, - 0x28c848, - 0x346789, - 0x346790, - 0x36f64b, - 0x2e2109, - 0x205dc3, - 0x20af09, - 0x23bd86, - 0x23bd8c, - 0x32d288, - 0x3bc208, - 0x244a49, - 0x29854e, - 0x2cc1cb, - 0x2e5c0c, - 0x203ec3, - 0x26ad0c, - 0x203ec9, - 0x30ae47, - 0x23ca0c, - 0x2b478a, - 0x252044, - 0x2768cd, - 0x26abc8, - 0x21308d, - 0x26fec6, - 0x28664b, - 0x200cc9, - 0x2cf787, - 0x332c86, - 0x3372c9, - 0x34834a, - 0x319108, - 0x2f3204, - 0x2fe987, - 0x363787, - 0x2d0184, - 0x38d204, - 0x2345c9, - 0x28a4c9, - 0x2b7288, - 0x216d05, - 0x339645, - 0x213c86, - 0x276789, - 0x249c4d, - 0x33bf88, - 0x213b87, - 0x382dc8, - 0x2fa686, - 0x39b444, - 0x2501c5, + 0x31dd48, + 0x385949, + 0x2bc8c8, + 0x281f48, + 0x2bec8c, + 0x2bff87, + 0x2c0a47, + 0x26a7c5, + 0x2b4807, + 0x393388, + 0x2c4c06, + 0x20904c, + 0x2ec1c8, + 0x2c8c48, + 0x250286, + 0x223dc7, + 0x272344, + 0x26d1c8, + 0x2b6d0c, + 0x28430c, + 0x307145, + 0x2047c7, + 0x3c22c6, + 0x223d46, + 0x331d08, + 0x367784, + 0x22df0b, + 0x2b744b, + 0x2e7e06, + 0x200847, + 0x322385, + 0x271285, + 0x22e046, + 0x25ed45, + 0x327e85, + 0x2c6c87, + 0x270a09, + 0x3b8dc4, + 0x25f405, + 0x2de045, + 0x2add08, + 0x2da405, + 0x287109, + 0x2c9ac7, + 0x2c9acb, + 0x24fbc6, + 0x241f09, + 0x338908, + 0x291f85, + 0x23ad88, + 0x346e08, + 0x2570c7, + 0x208e47, + 0x280049, + 0x22ea87, + 0x2aa389, + 0x2b7dcc, + 0x394848, + 0x2d4d09, + 0x2d6447, + 0x2805c9, + 0x340ec7, + 0x2cce88, + 0x3b6745, + 0x385f86, + 0x2bf888, + 0x30d3c8, + 0x27f709, + 0x327ec7, + 0x256d85, + 0x2301c9, 0x201c46, - 0x202884, - 0x203dc7, - 0x206f4a, - 0x219784, - 0x21dfc6, - 0x21ea49, - 0x21ea4f, - 0x21fc8d, - 0x220f06, - 0x224c90, - 0x225086, - 0x2257c7, - 0x2269c7, - 0x2269cf, - 0x2276c9, - 0x22cb06, - 0x22da47, - 0x22da48, - 0x22f289, - 0x358088, - 0x2eb507, - 0x212843, - 0x394f46, - 0x3c0b48, - 0x29880a, - 0x236089, - 0x205d83, - 0x3784c6, - 0x26bcca, - 0x28eb87, - 0x30ac8a, - 0x25a18e, - 0x227806, - 0x2b03c7, - 0x217bc6, - 0x203f86, - 0x38fd0b, - 0x31708a, - 0x32138d, - 0x21d047, - 0x20e408, - 0x20e409, - 0x20e40f, - 0x2c1c4c, - 0x2b4089, - 0x2d890e, - 0x34e44a, - 0x28b906, - 0x314a86, - 0x319d8c, - 0x31be8c, - 0x327508, - 0x36eac7, - 0x274d85, - 0x3485c4, - 0x20f88e, - 0x299684, - 0x388947, - 0x39140a, - 0x38a814, - 0x39390f, - 0x226b88, - 0x394e08, - 0x35eccd, - 0x35ecce, - 0x3a0849, - 0x238788, - 0x23878f, - 0x23c70c, - 0x23c70f, - 0x23d907, - 0x240c0a, - 0x2459cb, - 0x243788, - 0x245c87, - 0x3ac74d, - 0x322b46, - 0x276a86, - 0x248dc9, - 0x364b08, - 0x24cf48, - 0x24cf4e, - 0x2f4087, - 0x24e145, - 0x24e9c5, - 0x204b44, - 0x348a06, - 0x2b7188, - 0x20db03, - 0x2f948e, - 0x3acb08, - 0x2b588b, - 0x378bc7, - 0x3ab345, - 0x233d86, - 0x2b1f87, - 0x32f2c8, - 0x325449, - 0x322dc5, - 0x28e788, - 0x21c946, - 0x3afeca, - 0x20f789, - 0x23cac9, - 0x23cacb, - 0x346448, - 0x2d0049, - 0x216dc6, - 0x23768a, - 0x293c0a, - 0x240e0c, - 0x28e4c7, - 0x2ce74a, - 0x36b38b, - 0x36b399, - 0x312408, - 0x3a0445, - 0x2cdd46, - 0x25c489, - 0x3449c6, - 0x2df8ca, - 0x28ca46, - 0x20df44, - 0x2cdecd, - 0x20df47, - 0x218209, - 0x250ac5, - 0x250c08, - 0x251409, - 0x251844, - 0x251f47, - 0x251f48, - 0x2526c7, - 0x26e2c8, - 0x255cc7, - 0x25b845, - 0x25f3cc, - 0x25fc09, - 0x2c8c0a, - 0x39ec09, - 0x20b009, - 0x37ee4c, - 0x264f0b, - 0x2662c8, - 0x267448, - 0x26a804, - 0x289848, - 0x28d209, - 0x2b4847, - 0x20e646, - 0x200f47, - 0x2c4289, - 0x32264b, - 0x325147, - 0x201a87, - 0x2b79c7, - 0x213004, - 0x213005, - 0x2a7c05, - 0x34b1cb, - 0x3a9384, - 0x350448, - 0x26e94a, - 0x21ca07, - 0x300687, - 0x294712, - 0x276c06, - 0x23a1c6, - 0x33888e, - 0x27ab46, - 0x29abc8, - 0x29b38f, - 0x213448, - 0x302848, - 0x3bd10a, - 0x3bd111, - 0x2a990e, - 0x25654a, - 0x25654c, - 0x20bf07, - 0x238990, - 0x200408, - 0x2a9b05, - 0x2b238a, - 0x2028cc, - 0x29cf8d, - 0x302346, - 0x302347, - 0x30234c, - 0x30c80c, - 0x335d4c, - 0x2edfcb, - 0x28e0c4, - 0x22c9c4, - 0x354609, - 0x39e807, - 0x229989, - 0x293a49, - 0x3b6587, - 0x2b4606, - 0x2b4609, - 0x2b4a03, - 0x21b7ca, - 0x31fd07, - 0x34304b, - 0x32120a, - 0x2f6744, - 0x35f646, - 0x286b89, - 0x281a04, - 0x20324a, - 0x3a1205, - 0x2c4d45, - 0x2c4d4d, - 0x2c508e, - 0x2b9ac5, - 0x32ab86, - 0x39ffc7, - 0x25f64a, - 0x3a8286, - 0x2eefc4, - 0x2f9847, - 0x3bc50b, - 0x2fa747, - 0x30b444, - 0x256fc6, - 0x256fcd, - 0x2c3f4c, - 0x208d46, - 0x33c18a, - 0x230206, - 0x22ddc8, - 0x285107, - 0x34c98a, - 0x3840c6, - 0x210443, - 0x210446, - 0x3c09c8, - 0x2a344a, - 0x2801c7, - 0x2801c8, - 0x289e04, - 0x256ac7, - 0x283288, - 0x345388, - 0x284508, - 0x35874a, - 0x2e4505, - 0x2e9a07, - 0x256393, - 0x343d86, - 0x2e0908, - 0x229f89, - 0x24c488, - 0x38600b, - 0x2d3d48, - 0x2bc644, - 0x27a9c6, - 0x317ec6, - 0x330889, - 0x3bc3c7, - 0x25f4c8, - 0x2931c6, - 0x36c244, - 0x30aa05, - 0x2d4008, - 0x2cd88a, + 0x28e304, + 0x326006, + 0x311288, + 0x328747, + 0x2243c8, + 0x20c7c9, + 0x325b87, + 0x29d0c6, + 0x3c1f44, + 0x38e0c9, + 0x21f148, + 0x250147, + 0x2adf86, + 0x224106, + 0x2392c4, + 0x26d846, + 0x20af83, + 0x38d949, + 0x38dd86, + 0x20ca45, + 0x29d606, + 0x2c7205, + 0x27f1c8, + 0x2ee987, + 0x2eb146, + 0x3262c6, + 0x36fd08, + 0x29f907, + 0x297505, + 0x29b1c8, + 0x3b2448, + 0x319748, + 0x242345, + 0x386006, + 0x231589, + 0x3a6e84, + 0x2c708b, + 0x229d4b, + 0x22f789, + 0x20b003, + 0x25cf45, + 0x22abc6, + 0x242cc8, + 0x34e904, + 0x27c986, + 0x37c709, + 0x2f0405, + 0x2c6bc6, + 0x2f16c6, + 0x20c984, + 0x2a86ca, + 0x20c988, + 0x30d3c6, + 0x2934c5, + 0x331287, + 0x351547, + 0x21e544, + 0x229f87, + 0x22dc84, + 0x22dc86, + 0x200b43, + 0x26a985, + 0x37dc85, + 0x364648, + 0x257d85, + 0x279309, + 0x26d007, + 0x26d00b, + 0x2a240c, + 0x2a2a0a, + 0x2f0707, + 0x205c83, + 0x2ebcc8, + 0x242505, + 0x2c76c5, + 0x34c944, + 0x2ccd86, + 0x278206, + 0x26d887, + 0x23f8cb, + 0x29b244, + 0x2d7404, + 0x2c2784, + 0x2c6986, + 0x227104, + 0x2ba748, + 0x34c745, + 0x258a45, + 0x362c87, + 0x3c1f89, + 0x351305, + 0x37f30a, + 0x245d89, + 0x2d698a, + 0x23ee89, + 0x3a5104, + 0x306945, + 0x2d9448, + 0x2e184b, + 0x29ef05, + 0x2f3206, + 0x247684, + 0x279846, + 0x325a09, + 0x2a1c47, + 0x3b3248, + 0x2a0946, + 0x2faa47, + 0x27fd48, + 0x37f886, + 0x334f84, + 0x371c87, + 0x361205, + 0x373507, + 0x21c984, + 0x31e346, + 0x2e5bc8, + 0x297248, + 0x2e44c7, + 0x24e388, + 0x295645, + 0x20ae44, + 0x266a48, + 0x24e484, + 0x208e45, + 0x2f8e44, + 0x309607, + 0x2888c7, + 0x280708, + 0x2cb006, + 0x257d05, + 0x279108, + 0x3bf288, + 0x29ec49, + 0x22a046, + 0x233f88, + 0x345c8a, + 0x335488, + 0x2def85, + 0x225446, + 0x245c48, + 0x208a0a, + 0x229207, + 0x285dc5, + 0x28e508, + 0x2cc2c4, + 0x2d4906, + 0x2c0dc8, + 0x20aec6, + 0x31fc48, + 0x25b247, + 0x2063c6, + 0x2b8304, + 0x2a6b87, + 0x2b0d44, + 0x3259c7, + 0x2a524d, + 0x22f805, + 0x2e13cb, + 0x284586, + 0x258608, + 0x248644, + 0x2ee246, + 0x27bcc6, + 0x21e307, + 0x2968cd, + 0x24b947, + 0x2b1808, + 0x286985, + 0x364e48, + 0x2c2786, + 0x2956c8, + 0x354486, + 0x336b47, + 0x2c5689, + 0x353e07, + 0x287ac8, + 0x2733c5, + 0x21c508, + 0x223c85, + 0x2f7505, + 0x23f105, + 0x24c4c3, + 0x277884, + 0x28e705, + 0x36d849, + 0x36b906, + 0x2a1908, + 0x208c05, + 0x2b46c7, + 0x29f14a, + 0x2c6b09, + 0x288a8a, 0x2cdb48, - 0x2d4b06, - 0x2a1d8a, - 0x2fc208, - 0x2d8fc8, - 0x2d9ec8, - 0x2da506, - 0x2dc3c6, - 0x20c0cc, - 0x2dc990, - 0x285505, - 0x213248, - 0x30d410, - 0x213250, - 0x34660e, - 0x20bd4e, - 0x20bd54, - 0x20e78f, - 0x20eb46, - 0x3072d1, - 0x332e13, - 0x333288, - 0x31d245, - 0x2a0bc8, - 0x395705, - 0x23540c, - 0x2309c9, - 0x2994c9, - 0x230e47, - 0x263549, - 0x261047, - 0x2ffa46, - 0x24ffc7, - 0x20ef05, - 0x217103, - 0x20dcc9, - 0x22a249, - 0x38a783, - 0x3b35c4, - 0x358c8d, - 0x3b83cf, - 0x36c285, - 0x331786, - 0x21ac47, - 0x32d007, - 0x290806, - 0x29080b, - 0x2aa805, - 0x263c06, - 0x300b87, - 0x257449, - 0x345a06, - 0x20cb45, - 0x2248cb, - 0x230786, - 0x38ad45, - 0x273988, - 0x2a6988, - 0x2ba50c, - 0x2ba510, - 0x2b64c9, - 0x2c5607, - 0x2e520b, - 0x30be86, - 0x2eb3ca, - 0x2ec90b, - 0x2ee70a, - 0x2ee986, - 0x2ef645, - 0x31fa46, - 0x37d408, - 0x230f0a, - 0x35e95c, - 0x2f380c, - 0x2f3b08, - 0x3a03c5, - 0x35cec7, - 0x25b0c6, - 0x27f7c5, - 0x2227c6, - 0x2909c8, - 0x2c2c07, - 0x298448, - 0x2b04ca, - 0x33764c, - 0x3378c9, - 0x39b5c7, - 0x215c04, - 0x24ea86, - 0x2d518a, - 0x293b45, - 0x211ecc, - 0x212e48, - 0x389c88, - 0x21904c, - 0x2266cc, - 0x229549, - 0x229787, - 0x23ff4c, - 0x2454c4, - 0x24718a, - 0x23354c, - 0x279a4b, - 0x24bfcb, - 0x3821c6, - 0x2f7447, - 0x20e947, - 0x238bcf, - 0x303191, - 0x2e16d2, - 0x314ecd, - 0x314ece, - 0x31520e, - 0x20e948, - 0x20e952, - 0x253e08, - 0x34ec47, - 0x25430a, - 0x208b08, - 0x27ab05, - 0x38c9ca, - 0x2255c7, - 0x2e6f44, - 0x227103, - 0x297185, - 0x3bd387, - 0x2fb547, - 0x29d18e, - 0x308c8d, - 0x30d7c9, - 0x21f545, - 0x31c443, - 0x326446, - 0x264085, - 0x27dc48, - 0x2c0649, - 0x2a0105, - 0x3ac94f, - 0x2b6207, - 0x382bc5, - 0x37958a, - 0x358946, - 0x2522c9, - 0x37db4c, - 0x2fec09, - 0x2094c6, - 0x26e74c, - 0x329f86, - 0x3017c8, - 0x301c86, - 0x312586, - 0x2082c4, - 0x266643, - 0x2b380a, - 0x32e411, - 0x30650a, - 0x265345, - 0x271ac7, - 0x25c7c7, - 0x283384, - 0x28338b, - 0x2cfb08, - 0x2c1486, - 0x37e6c5, - 0x3b01c4, - 0x280ac9, - 0x320804, - 0x24cd87, - 0x359f05, - 0x359f07, - 0x338ac5, - 0x2affc3, - 0x34eb08, - 0x35f2ca, - 0x20b3c3, - 0x32d20a, - 0x281ec6, - 0x3ac6cf, - 0x2f4009, - 0x2f9410, - 0x2ebe48, - 0x2d5809, - 0x29f087, - 0x256f4f, - 0x31e884, - 0x2de9c4, - 0x224f06, - 0x317b06, - 0x2e2aca, - 0x381c46, - 0x2ff587, - 0x30c148, - 0x30c347, - 0x30cbc7, - 0x30f08a, - 0x310b4b, - 0x3b1b45, - 0x2e1308, - 0x204443, - 0x2045cc, - 0x38000f, - 0x274b8d, - 0x2aefc7, - 0x30d909, - 0x2e8207, - 0x24f2c8, - 0x38aa0c, - 0x2bc548, - 0x231848, - 0x321d0e, - 0x336054, - 0x336564, - 0x354e4a, - 0x37018b, - 0x261104, - 0x261109, - 0x3656c8, - 0x24ef85, - 0x20d60a, - 0x3acd47, - 0x31f944, - 0x39c783, - 0x238543, - 0x240244, - 0x23cac3, - 0x323043, - 0x231604, - 0x255783, - 0x28cac3, - 0x20c0c6, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x221483, - 0x207102, - 0x39c783, - 0x20f882, - 0x238543, - 0x240244, - 0x23cac3, - 0x323043, - 0x255783, - 0x20c0c6, - 0x208e83, - 0x201a03, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x21b583, - 0x208e83, - 0x1a3443, - 0x201a03, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x207102, - 0x242043, - 0x20f882, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x201382, - 0x235f42, - 0x20f882, - 0x238543, - 0x206902, - 0x200942, - 0x231604, - 0x20f644, - 0x22a482, - 0x21bf84, - 0x200442, - 0x201a03, - 0x221483, - 0x3821c6, - 0x21a902, - 0x202642, - 0x20c4c2, - 0x47a13443, - 0x47e0bf03, - 0x5d306, - 0x5d306, - 0x286644, - 0x200e03, - 0x14b700a, - 0x12ea0c, - 0xf4cc, - 0x871cd, - 0x131645, - 0x26547, - 0x1b1c6, - 0x21088, - 0x23087, - 0x28b08, - 0x1aa20a, - 0x1397c7, - 0x48adf485, - 0x1359c9, - 0x3e34b, - 0x35dcb, - 0x42e48, - 0x172f4a, - 0x9288e, - 0x144c28b, - 0x6a04, - 0x63d46, - 0x7588, - 0xf8d08, - 0x3e607, - 0x1a787, - 0x57f89, - 0x81a87, - 0xdd088, - 0x12f5c9, - 0x49804, - 0x49f45, - 0x12bfce, - 0xb084d, - 0x8ca48, - 0x48e34406, - 0x49834408, - 0x7b548, - 0x11f3d0, - 0x5998c, - 0x6b9c7, - 0x6c647, - 0x71387, - 0x77fc7, - 0x13c42, - 0x144ec7, - 0x11724c, - 0x43b87, - 0xac206, - 0xac7c9, - 0xae208, - 0x206c2, - 0x942, - 0xbee8b, - 0x1a3307, - 0x18009, - 0x164ec9, - 0x3ef48, - 0xb8042, - 0x134649, - 0xcc60a, - 0xd2689, - 0xdfdc9, - 0xe0b08, - 0xe1b87, - 0xe4489, - 0xe61c5, - 0xe67d0, - 0x191646, - 0x11205, - 0x31e8d, - 0x235c6, - 0xefd07, - 0xf4558, - 0x14f508, - 0xc74a, - 0xb282, - 0x5524d, - 0xa02, - 0x86286, - 0x95408, - 0x8f148, - 0x16fa49, - 0x586c8, - 0x6420e, - 0x126447, - 0x1051cd, - 0xfb445, - 0x144c48, - 0x19fc08, - 0x106046, - 0xc2, - 0x12cf06, - 0x4542, - 0x341, - 0x65a07, - 0xf6fc3, - 0x492f4dc4, - 0x4969c243, - 0x141, - 0x19d06, - 0x141, - 0x1, - 0x19d06, - 0xf6fc3, - 0x1402285, - 0x252044, - 0x238543, - 0x253384, - 0x231604, - 0x208e83, - 0x229e45, - 0x221f43, + 0x22ad0c, + 0x28144d, + 0x34a703, + 0x31fb48, + 0x3be485, + 0x2eec06, + 0x318086, + 0x2deac5, + 0x206f89, + 0x3ab885, + 0x279108, + 0x25e046, + 0x3532c6, + 0x2a0149, + 0x3a0f87, + 0x28ee06, + 0x29f0c8, + 0x36bc48, + 0x2d8b87, + 0x2be3ce, + 0x2c29c5, + 0x24fe85, + 0x20adc8, + 0x3269c7, + 0x208f82, + 0x2be804, + 0x2403ca, + 0x250208, + 0x346f46, + 0x298c88, + 0x29d706, + 0x31da88, + 0x2ac8c8, + 0x2f74c4, + 0x2b4a85, + 0x6010c4, + 0x6010c4, + 0x6010c4, + 0x200a43, + 0x223f86, + 0x2795c6, + 0x29c98c, + 0x201343, + 0x21c986, + 0x200b04, + 0x2a3308, + 0x37c545, + 0x2404c6, + 0x2bc408, + 0x2cef86, + 0x2eb0c6, + 0x339f08, + 0x2cfd47, + 0x22e849, + 0x2a714a, + 0x211644, + 0x22dcc5, + 0x2b3e05, + 0x2c5406, + 0x211906, + 0x29c706, + 0x2f8686, + 0x22e984, + 0x22e98b, + 0x22d744, + 0x242085, + 0x2ab5c5, + 0x29f506, + 0x369808, + 0x281307, + 0x38dd04, + 0x2076c3, + 0x2cbdc5, + 0x22dac7, + 0x28120b, + 0x364547, + 0x2bc308, + 0x2b4bc7, + 0x26be06, + 0x251c48, + 0x26f24b, + 0x217b46, + 0x216b09, + 0x26f3c5, + 0x30eb43, + 0x2c6bc6, + 0x25b148, 0x20c843, - 0x355685, - 0x202443, - 0x4aa38543, - 0x23cac3, - 0x323043, - 0x200041, - 0x28cac3, - 0x20f644, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x215443, - 0x16fb88, - 0x207102, - 0x39c783, - 0x20f882, - 0x238543, - 0x23cac3, - 0x21b583, - 0x200942, - 0x231604, - 0x255783, - 0x28cac3, - 0x208e83, - 0x200e03, - 0x201a03, - 0x202443, - 0x16fb88, - 0x37fd82, - 0x18c1c7, - 0xf882, - 0x10a985, - 0x1480cc8, - 0x10c50e, - 0x4ba0ab02, - 0x31fec8, - 0x2bdd86, - 0x2ca186, - 0x2bd707, - 0x4be00b42, - 0x4c3ac548, - 0x21870a, - 0x26b448, - 0x200242, - 0x31fb49, - 0x3b1b87, - 0x21ec06, - 0x34e849, - 0x2e9b44, - 0x348646, - 0x2ca584, - 0x27f584, - 0x25f009, - 0x32d906, - 0x240ac5, - 0x297a85, - 0x3b9d87, - 0x2c76c7, - 0x2979c4, - 0x2bd946, - 0x307b85, - 0x30a3c5, - 0x3a2a05, - 0x339407, - 0x378a05, - 0x31ddc9, - 0x234fc5, - 0x32f404, - 0x3a81c7, - 0x341b0e, - 0x306bc9, - 0x338749, - 0x388d86, - 0x24a608, - 0x36ae4b, - 0x2b698c, - 0x33ea46, - 0x2e5ac7, - 0x212245, - 0x38d20a, - 0x2b7389, - 0x209b49, - 0x259f06, - 0x300945, - 0x2edac5, - 0x3570c9, - 0x3a2b8b, - 0x27e286, - 0x3471c6, - 0x20de04, - 0x2943c6, - 0x24e1c8, - 0x3c0846, - 0x215006, - 0x205fc8, - 0x2092c7, - 0x209909, - 0x211385, - 0x16fb88, - 0x21a704, - 0x2394c4, - 0x201105, - 0x3a6649, - 0x228f87, - 0x228f8b, - 0x22b3ca, - 0x230905, - 0x4c612842, - 0x342f07, - 0x4ca30c08, - 0x3578c7, - 0x2c3d45, - 0x209dca, - 0xf882, - 0x2be6cb, - 0x255e0a, - 0x22a146, - 0x216383, - 0x2a038d, - 0x3572cc, - 0x357a4d, - 0x250545, - 0x334fc5, - 0x20db47, - 0x36c689, - 0x218606, - 0x381ac5, - 0x2d2b88, - 0x2942c3, - 0x2fa288, - 0x2942c8, - 0x2cb287, - 0x314808, - 0x3b49c9, - 0x374847, - 0x342707, - 0x202108, - 0x2d1c84, - 0x2d1c87, - 0x26fdc8, - 0x355546, - 0x3b874f, - 0x226207, - 0x2eb686, - 0x2298c5, - 0x22a8c3, - 0x381947, - 0x37cc43, - 0x252886, - 0x254006, - 0x254706, - 0x298b85, - 0x26e2c3, - 0x397cc8, - 0x37f889, - 0x3920cb, - 0x254888, - 0x255985, - 0x2584c5, - 0x4cef6802, - 0x250089, - 0x34eec7, - 0x263c85, - 0x25ef07, - 0x260506, - 0x374345, - 0x263ecb, - 0x2662c4, - 0x26b005, - 0x26b147, - 0x27db86, - 0x27e045, - 0x289a47, - 0x28a187, - 0x2d5104, - 0x291b8a, - 0x292048, - 0x2cee09, - 0x2a0f05, - 0x3bf1c6, - 0x24e38a, - 0x2be906, - 0x26f2c7, - 0x2ceacd, - 0x2aa349, - 0x396fc5, - 0x339f07, - 0x333448, - 0x25a5c8, - 0x332847, - 0x358246, - 0x21cb87, - 0x253c43, - 0x34b1c4, - 0x371cc5, - 0x39d947, - 0x3a2409, - 0x231b08, - 0x34cbc5, - 0x23bac4, - 0x254a45, - 0x256c4d, - 0x2006c2, - 0x230386, - 0x2861c6, - 0x2e654a, - 0x3904c6, - 0x39ab85, - 0x342445, - 0x342447, - 0x3afd0c, - 0x27b3ca, - 0x294086, - 0x28ad05, - 0x294206, - 0x294547, - 0x296886, - 0x298a8c, + 0x22dbc3, + 0x27fd46, + 0x29d706, + 0x36808a, + 0x27b2c5, + 0x27bb0b, + 0x29d54b, + 0x247b03, + 0x220043, + 0x2af944, + 0x2a88c7, + 0x25b1c4, + 0x240084, + 0x385c04, + 0x335788, + 0x293408, + 0x20dd89, + 0x2c5248, + 0x23f387, + 0x2060c6, + 0x2a154f, + 0x2c2b06, + 0x2cd084, + 0x29324a, + 0x22d9c7, + 0x2b0e46, + 0x28e349, + 0x20dd05, + 0x364785, + 0x20de46, + 0x21c643, + 0x2cc309, + 0x221e46, + 0x20c589, + 0x38f4c6, + 0x26a985, + 0x307545, + 0x205843, + 0x2a8a08, + 0x31be07, + 0x21e644, + 0x2a3188, + 0x24c744, + 0x39a286, + 0x2b1d06, + 0x2445c6, + 0x2cfa09, + 0x2c7645, + 0x2975c6, + 0x21afc9, + 0x393086, + 0x2a1646, + 0x395846, + 0x203a45, + 0x2f8e46, + 0x336b44, + 0x3b6745, + 0x2bf884, + 0x2b2206, + 0x31e4c4, + 0x200d03, + 0x284b85, + 0x238888, + 0x2509c7, 0x34e989, - 0x4d21a187, - 0x29b745, - 0x29b746, - 0x29bcc8, - 0x246f85, - 0x2ab085, - 0x2ab808, - 0x2aba0a, - 0x4d6335c2, - 0x4da14d02, - 0x2e76c5, - 0x2eb603, - 0x243408, - 0x252403, - 0x2abc84, - 0x25240b, - 0x36b208, - 0x2daa48, - 0x4df3b049, - 0x2afc09, - 0x2b0746, - 0x2b1c08, - 0x2b1e09, - 0x2b2886, - 0x2b2a05, - 0x3944c6, - 0x2b2f49, - 0x389347, - 0x2647c6, - 0x2de087, - 0x218487, - 0x2dd9c4, - 0x4e34f809, - 0x2d32c8, - 0x3ac448, - 0x3932c7, - 0x2cd346, - 0x36c489, - 0x2ca847, - 0x32598a, - 0x358388, - 0x208387, - 0x208f86, - 0x271d8a, - 0x26fbc8, - 0x2ed485, - 0x230685, - 0x2ef1c7, - 0x311cc9, - 0x30150b, - 0x31a308, - 0x235049, - 0x254c87, - 0x2bd04c, - 0x2bfccc, - 0x2bffca, - 0x2c024c, - 0x2ca108, - 0x2ca308, - 0x2ca504, - 0x2caa09, - 0x2cac49, - 0x2cae8a, - 0x2cb109, - 0x2cb447, - 0x3ba98c, - 0x23f586, - 0x2cbf88, - 0x2be9c6, - 0x387486, - 0x396ec7, - 0x306dc8, - 0x3445cb, - 0x28e307, - 0x250289, - 0x350b89, - 0x253507, - 0x2771c4, - 0x271c07, - 0x2fda46, - 0x21d8c6, - 0x33c345, - 0x297248, - 0x2993c4, - 0x2993c6, - 0x27b28b, - 0x21bac9, - 0x36c886, - 0x204bc9, - 0x339586, - 0x25f1c8, - 0x211b83, - 0x300ac5, - 0x219b09, - 0x21da05, - 0x2fba44, - 0x27d046, - 0x2fd385, - 0x299906, - 0x310ec7, - 0x33a986, - 0x3b134b, - 0x237587, - 0x241646, - 0x354786, - 0x3b9e46, - 0x297989, - 0x25384a, - 0x2bbb85, - 0x2202cd, - 0x2abb06, - 0x204a86, - 0x2f3f06, - 0x22dd45, - 0x2e6ac7, - 0x300087, - 0x2e7dce, - 0x28cac3, - 0x2cd309, - 0x210c89, - 0x38d607, - 0x364207, - 0x2a5bc5, - 0x2b57c5, - 0x4e63470f, - 0x2d5a47, - 0x2d5c08, - 0x2d6144, - 0x2d7106, - 0x4ea4ea42, - 0x2da786, - 0x20c0c6, - 0x210e4e, - 0x2fa0ca, - 0x273b06, - 0x23398a, - 0x211689, - 0x32b385, - 0x3a4808, - 0x3bca06, - 0x306748, - 0x33aac8, - 0x2194cb, - 0x2bd805, - 0x378a88, - 0x20610c, - 0x2c3c07, - 0x254246, - 0x2fd1c8, - 0x3488c8, - 0x4ee06802, - 0x23588b, - 0x2123c9, - 0x205549, - 0x2174c7, - 0x223408, - 0x4f36bec8, - 0x38ffcb, - 0x23edc9, - 0x338f0d, - 0x27fa88, - 0x22b1c8, - 0x4f6014c2, - 0x203cc4, - 0x4fa19302, - 0x2fe206, - 0x4fe004c2, - 0x261b8a, - 0x2199c6, - 0x232808, - 0x2c6f48, - 0x2b6f06, - 0x22fe46, - 0x2f9186, - 0x2b5a45, - 0x2443c4, - 0x50206d04, - 0x214106, - 0x29c747, - 0x50620c47, - 0x2d644b, - 0x341ec9, - 0x33500a, - 0x2106c4, - 0x342588, - 0x26458d, - 0x2f2489, - 0x2f26c8, - 0x2f2d49, - 0x2f4544, - 0x245884, - 0x285cc5, - 0x320fcb, - 0x36b186, - 0x34b905, - 0x2279c9, - 0x2bda08, - 0x210dc4, - 0x38d389, - 0x2064c5, - 0x2c7708, - 0x342dc7, - 0x338b48, - 0x286d86, - 0x233207, - 0x29a989, - 0x224a49, - 0x38adc5, - 0x34dfc5, - 0x50a08402, - 0x32f1c4, - 0x2fdd45, - 0x2ce506, - 0x33bd05, - 0x387e47, - 0x214205, - 0x27dbc4, - 0x388e46, - 0x381b47, - 0x23d046, - 0x2c41c5, - 0x207f48, - 0x2bdf85, - 0x211a07, - 0x214689, - 0x21bc0a, - 0x2fc487, - 0x2fc48c, - 0x240a86, - 0x37e349, - 0x246a45, - 0x246ec8, - 0x207c03, - 0x216d85, - 0x2fd705, - 0x282d47, - 0x50e06ac2, - 0x22f647, - 0x2e56c6, - 0x373b46, - 0x30bfc6, - 0x348806, - 0x206748, - 0x2a0d05, - 0x2eb747, - 0x2eb74d, - 0x227103, - 0x227105, - 0x379347, - 0x22f988, - 0x378f05, - 0x2216c8, - 0x37ccc6, - 0x335b87, - 0x2cbec5, - 0x2bd886, - 0x39ce45, - 0x21c70a, - 0x2f1346, - 0x383f47, - 0x2bca85, - 0x2f5047, - 0x2f97c4, - 0x2fb9c6, - 0x2fe345, - 0x32d70b, - 0x2fd8c9, - 0x24214a, - 0x38ae48, - 0x30e048, - 0x380a8c, - 0x3964c7, - 0x3054c8, - 0x307f48, - 0x3084c5, - 0x311a8a, - 0x31c449, - 0x51200d02, - 0x201886, - 0x216044, - 0x216049, - 0x27d549, - 0x27e9c7, - 0x2b4e07, - 0x2938c9, - 0x22df48, - 0x22df4f, - 0x2e3a06, - 0x2df14b, - 0x34b445, - 0x34b447, - 0x368849, - 0x21aa46, - 0x38d307, - 0x2e1a45, - 0x23ae84, - 0x284fc6, - 0x2262c4, - 0x2db107, - 0x2d6f08, - 0x51700848, - 0x301245, - 0x301387, - 0x260a09, - 0x205304, - 0x24b348, - 0x51ab7cc8, - 0x283384, - 0x23c208, - 0x332d44, - 0x22be49, - 0x351a45, - 0x51e05082, - 0x2e3a45, - 0x310045, - 0x20fc48, - 0x23d747, - 0x52200d42, - 0x3322c5, - 0x2d8e46, - 0x27cb06, - 0x32f188, - 0x337d48, - 0x33bcc6, - 0x34bb06, - 0x38c289, - 0x373a86, - 0x21a90b, - 0x2e5f85, - 0x208a46, - 0x29e108, - 0x3a0a06, - 0x322c46, - 0x221b8a, - 0x23b30a, - 0x2498c5, - 0x2a0dc7, - 0x313646, - 0x52606442, - 0x379487, - 0x266cc5, + 0x285cc8, + 0x297d51, + 0x2f174a, + 0x2e7d47, + 0x396246, + 0x200b04, + 0x2bf988, + 0x26d9c8, + 0x297f0a, + 0x286ecd, + 0x24c486, + 0x33a006, + 0x2a6c46, + 0x283447, + 0x2b18c5, + 0x341987, + 0x2009c5, + 0x2c9c04, + 0x2a7586, + 0x26d6c7, + 0x2cc00d, + 0x245b87, + 0x344c48, + 0x279409, + 0x225346, + 0x2a5505, + 0x2fa084, + 0x311386, + 0x21e446, + 0x250386, + 0x299508, + 0x21d683, + 0x208d83, + 0x341f45, + 0x257e46, + 0x2ac885, + 0x2a0b48, + 0x29c18a, + 0x39e284, + 0x2a3308, + 0x291688, + 0x29f347, + 0x208cc9, + 0x2bc008, + 0x286847, + 0x385e86, + 0x20aeca, + 0x311408, + 0x3a6b09, + 0x2ae608, + 0x228089, + 0x396107, + 0x2fea85, + 0x347306, + 0x2c4a88, + 0x27a888, + 0x28de08, + 0x38ab08, + 0x242085, + 0x203bc4, + 0x236ec8, + 0x209784, + 0x23ec84, + 0x26a985, + 0x290647, + 0x3c1d49, + 0x21e107, + 0x214045, + 0x276dc6, + 0x35bc86, + 0x211a84, + 0x2a0486, + 0x257b44, + 0x2a11c6, + 0x3c1b06, + 0x2181c6, + 0x3c6485, + 0x2a0a07, + 0x205c83, + 0x216e89, + 0x36fb08, + 0x2866c4, + 0x2866cd, + 0x297348, + 0x2ddc88, + 0x3a6a86, + 0x2c5789, + 0x2c6b09, + 0x325705, + 0x29c28a, + 0x252a0a, + 0x25e6cc, + 0x25e846, + 0x277c06, + 0x2c2c86, + 0x372b09, + 0x2eee46, + 0x29f946, + 0x3ab946, + 0x26d1c8, + 0x24e386, + 0x2cca0b, + 0x2907c5, + 0x258a45, + 0x277e85, + 0x3c2806, + 0x20ae83, + 0x244546, + 0x245b07, + 0x2bf845, + 0x3108c5, + 0x340045, + 0x2f83c6, + 0x3257c4, + 0x327886, + 0x2bad89, + 0x3c268c, + 0x2c9948, + 0x23c504, + 0x2f8b46, + 0x284686, + 0x25b148, + 0x218bc8, + 0x3c2589, + 0x331287, + 0x24ed89, + 0x37ba46, + 0x230604, + 0x20d804, + 0x280344, + 0x27fd48, + 0x3c1b8a, + 0x351286, + 0x35e207, + 0x36e207, + 0x242005, + 0x2b3dc4, + 0x28c846, + 0x2b1906, + 0x23a283, + 0x36f947, + 0x3aab88, + 0x32584a, + 0x22ca48, + 0x3643c8, + 0x31e505, + 0x29cdc5, + 0x26e785, + 0x2423c6, + 0x243286, + 0x340cc5, + 0x38db89, + 0x2b3bcc, + 0x26e847, + 0x297f88, + 0x2dee05, + 0x6010c4, + 0x24d184, + 0x280e84, + 0x21b846, + 0x29e4ce, + 0x364807, + 0x283645, + 0x3a6e0c, + 0x2f8f47, + 0x26d647, + 0x2f4449, + 0x21be49, + 0x285dc5, + 0x36fb08, + 0x231589, + 0x319605, + 0x2bf788, + 0x221fc6, + 0x266cc6, + 0x3c2f44, + 0x28b688, + 0x225503, + 0x3875c4, + 0x2cbe45, + 0x388307, + 0x228785, + 0x345b49, + 0x2ab04d, + 0x2b0486, + 0x207704, + 0x2ba8c8, + 0x27084a, + 0x228b87, + 0x31ce85, + 0x23b3c3, + 0x29d70e, + 0x2a8b0c, + 0x2ff747, + 0x29e687, + 0x217b83, + 0x2eee85, + 0x280e85, + 0x299048, + 0x2963c9, + 0x23c406, + 0x25b1c4, + 0x2e7c86, + 0x23390b, + 0x38320c, + 0x33a8c7, + 0x2cccc5, + 0x3b2348, + 0x2d8945, + 0x293247, + 0x2f1587, + 0x245945, + 0x20ae83, + 0x335ac4, + 0x22a385, + 0x3b8cc5, + 0x3b8cc6, + 0x2b5308, + 0x26d6c7, + 0x318386, + 0x205c06, + 0x23f046, + 0x27e509, + 0x21f3c7, + 0x250646, + 0x383386, + 0x275d06, + 0x2a8605, + 0x3c53c6, + 0x3746c5, + 0x2da488, + 0x28ff4b, + 0x28c586, + 0x36e244, + 0x2e0409, + 0x26d004, + 0x221f48, + 0x326107, + 0x281e44, + 0x2bb308, + 0x2c0844, + 0x2a8644, + 0x286605, + 0x2dfc46, + 0x3356c7, + 0x27f283, + 0x29d185, + 0x32ce84, + 0x24fec6, + 0x325788, + 0x2b6c05, + 0x28fc09, + 0x2303c5, + 0x21c988, + 0x2312c7, + 0x38de88, + 0x2ba487, + 0x27df09, + 0x2820c6, + 0x305706, + 0x2b3084, + 0x2d7345, + 0x300a4c, + 0x277e87, + 0x278a87, + 0x36e0c8, + 0x2b0486, + 0x271484, + 0x30a244, + 0x27fec9, + 0x2c2d86, + 0x282687, + 0x277784, + 0x24d786, + 0x317bc5, + 0x2cab47, + 0x2cc986, + 0x24d949, + 0x383047, + 0x2692c7, + 0x29ffc6, + 0x24d6c5, + 0x27d1c8, + 0x221cc8, + 0x348546, + 0x2b6c45, + 0x349e86, + 0x206543, + 0x298ec9, + 0x29c48e, + 0x2ba1c8, + 0x24c848, + 0x34834b, + 0x28fe46, + 0x211584, + 0x281044, + 0x29c58a, + 0x217207, + 0x250705, + 0x216b09, + 0x2be305, + 0x23ecc7, 0x24e304, - 0x24e305, - 0x2105c6, - 0x278fc7, - 0x215dc5, - 0x23b484, - 0x2c4788, - 0x322d05, - 0x3af347, - 0x3b6dc5, + 0x2a9a47, + 0x2e7f08, + 0x2e0dc6, + 0x24c589, + 0x2bc10a, + 0x217186, + 0x296e86, + 0x2ab545, + 0x3898c5, + 0x347ac7, + 0x24cf08, + 0x317b08, + 0x2f74c6, + 0x3075c5, + 0x21168e, + 0x2bc7c4, + 0x298fc5, + 0x276749, + 0x382c48, + 0x28aa46, + 0x29accc, + 0x29bd90, + 0x29e10f, + 0x29f688, + 0x2f0707, + 0x3c6485, + 0x28e705, + 0x335549, + 0x28e709, + 0x240d06, + 0x29ef87, + 0x2d7245, + 0x34d589, + 0x33f106, + 0x2eec8d, + 0x280209, + 0x240084, + 0x2b9f48, + 0x236f89, + 0x351446, + 0x2ebec5, + 0x305706, + 0x3b3109, + 0x277608, + 0x212305, + 0x28b684, + 0x29ae8b, + 0x351305, + 0x242d46, + 0x281786, + 0x285206, + 0x28f64b, + 0x28fd09, + 0x205b45, + 0x396e87, + 0x2f16c6, + 0x240206, + 0x280c08, + 0x2dfd49, + 0x344a0c, + 0x22d8c8, + 0x308ec6, + 0x32c803, + 0x32a506, + 0x27ddc5, + 0x27be48, + 0x306fc6, + 0x2cad88, + 0x2062c5, + 0x27a585, + 0x365288, + 0x31dc07, + 0x317fc7, + 0x26d887, + 0x240088, + 0x2c5508, + 0x2b1206, + 0x2b2047, + 0x267c47, + 0x28f34a, + 0x256c83, + 0x3c2806, + 0x23c645, + 0x2403c4, + 0x279409, + 0x27de84, + 0x250a44, + 0x29a104, + 0x29e68b, + 0x31bd47, + 0x2118c5, + 0x295348, + 0x276dc6, + 0x276dc8, + 0x27b206, + 0x28b5c5, + 0x28b885, + 0x28d446, + 0x28dbc8, + 0x28e288, + 0x2795c6, + 0x29518f, + 0x298990, + 0x369405, + 0x205c83, + 0x2306c5, + 0x309088, + 0x28e609, + 0x319748, + 0x24c408, + 0x238d88, + 0x31be07, + 0x276a89, + 0x2caf88, + 0x28dac4, + 0x299f88, + 0x2addc9, + 0x2b38c7, + 0x299f04, + 0x21e1c8, + 0x2a07ca, + 0x2aff86, + 0x24c486, + 0x229f09, + 0x29bfc7, + 0x2c83c8, + 0x345608, + 0x294048, + 0x25d345, + 0x38a705, + 0x258a45, + 0x280e45, + 0x37ffc7, + 0x20ae85, + 0x2bf845, + 0x206d86, + 0x319687, + 0x2e1787, + 0x2a0ac6, + 0x2ce085, + 0x242d46, + 0x24c685, + 0x2d70c8, + 0x2ff5c4, + 0x393106, + 0x334e84, + 0x31dec8, + 0x22f10a, + 0x27a34c, + 0x23fac5, + 0x283506, + 0x344bc6, + 0x341e06, + 0x308f44, + 0x317e85, + 0x27b047, + 0x29c049, + 0x2c6f47, + 0x6010c4, + 0x6010c4, + 0x31bbc5, + 0x2cb984, + 0x29a68a, + 0x276c46, + 0x251e84, + 0x204745, + 0x36c3c5, + 0x2b1804, + 0x2813c7, + 0x230347, + 0x2c6988, + 0x31fec8, + 0x212309, + 0x26eec8, + 0x29a84b, + 0x2b7fc4, + 0x37b985, + 0x27d905, + 0x26d809, + 0x2dfd49, + 0x2e0308, + 0x22d748, + 0x29f504, + 0x2846c5, + 0x200583, + 0x2c53c5, + 0x297646, + 0x29620c, + 0x21f046, + 0x2ebdc6, + 0x28acc5, + 0x2f8448, + 0x35ec46, + 0x3963c6, + 0x24c486, + 0x22c7cc, + 0x250544, + 0x23f18a, + 0x28ac08, + 0x296047, + 0x32cd86, + 0x23c4c7, + 0x2e7885, + 0x2adf86, + 0x35aa46, + 0x366207, + 0x250a84, + 0x309705, + 0x276744, + 0x2c9c87, + 0x276988, + 0x277a8a, + 0x27ebc7, + 0x2a8207, + 0x2f0687, + 0x2d8a89, + 0x29620a, + 0x22e943, + 0x250985, + 0x218203, + 0x385c49, + 0x336dc8, + 0x351687, + 0x319849, + 0x221dc6, + 0x3b6808, + 0x33c445, + 0x3bf38a, + 0x200c89, + 0x3299c9, + 0x35eb07, + 0x26dac9, + 0x2180c8, + 0x3663c6, + 0x2836c8, + 0x203a47, + 0x22ea87, + 0x245d87, + 0x2e5a48, + 0x2f89c6, + 0x2a0585, + 0x27b047, + 0x296988, + 0x334e04, + 0x2c8004, + 0x28ed07, + 0x2acc47, + 0x23140a, + 0x366346, + 0x364c4a, + 0x2be747, + 0x2bc587, + 0x3097c4, + 0x2aa444, + 0x2caa46, + 0x23a444, + 0x23a44c, + 0x39ee05, + 0x218a09, + 0x337284, + 0x2b18c5, + 0x2707c8, + 0x239dc5, + 0x37f306, + 0x2311c4, + 0x2d02ca, + 0x2cb2c6, + 0x29180a, + 0x2162c7, + 0x224505, 0x21c645, - 0x258f84, - 0x2ee209, - 0x3079c8, - 0x263146, - 0x2b5386, - 0x345186, - 0x52b08148, - 0x308347, - 0x30874d, - 0x3090cc, - 0x3096c9, - 0x309909, - 0x52f67742, - 0x3b6343, - 0x215ac3, - 0x2fdb05, - 0x39da4a, - 0x32f046, - 0x30e2c5, - 0x311084, - 0x31108b, - 0x323a8c, - 0x3244cc, - 0x3247d5, - 0x32660d, - 0x327d0f, - 0x3280d2, - 0x32854f, - 0x328912, - 0x328d93, - 0x32924d, - 0x32980d, - 0x329b8e, - 0x32a10e, - 0x32a94c, - 0x32ad0c, - 0x32b14b, - 0x32b4ce, - 0x32c612, - 0x32ee0c, - 0x32fd90, - 0x33cd52, - 0x33d9cc, - 0x33e08d, - 0x33e3cc, - 0x3406d1, - 0x34734d, - 0x349e0d, - 0x34a40a, - 0x34a68c, - 0x34af8c, - 0x34b60c, - 0x34c20c, - 0x3523d3, - 0x352cd0, - 0x3530d0, - 0x35398d, - 0x353f8c, - 0x354b89, - 0x35690d, - 0x356c53, - 0x3595d1, - 0x359a13, - 0x35a0cf, - 0x35a48c, - 0x35a78f, - 0x35ab4d, - 0x35b14f, - 0x35b510, - 0x35bf8e, - 0x35f88e, - 0x35fe10, - 0x36150d, - 0x361e8e, - 0x36220c, - 0x363213, - 0x3658ce, - 0x365f50, - 0x366351, - 0x36678f, - 0x366b53, - 0x3672cd, - 0x36760f, - 0x3679ce, - 0x368090, - 0x368489, - 0x369210, - 0x36980f, - 0x369e8f, - 0x36a252, - 0x36dcce, - 0x36e7cd, - 0x36f00d, - 0x36f34d, - 0x37078d, - 0x370acd, - 0x370e10, - 0x37120b, - 0x371a8c, - 0x371e0c, - 0x37240c, - 0x37270e, - 0x382350, - 0x384512, - 0x38498b, - 0x384e8e, - 0x38520e, - 0x386dce, - 0x38724b, - 0x53388016, - 0x38988d, - 0x38a014, - 0x38b04d, - 0x38cd55, - 0x38e30d, - 0x38ec8f, - 0x38f4cf, - 0x39238f, - 0x39274e, - 0x392ccd, - 0x394091, - 0x39668c, - 0x39698c, - 0x396c8b, - 0x39710c, - 0x3974cf, - 0x397892, - 0x39824d, - 0x39974c, - 0x399bcc, - 0x399ecd, - 0x39a20f, - 0x39a5ce, - 0x39d70c, - 0x39dccd, - 0x39e00b, - 0x39e9cc, - 0x39f2cd, - 0x39f60e, - 0x39f989, - 0x3a1353, - 0x3a188d, - 0x3a1bcd, - 0x3a21cc, - 0x3a264e, - 0x3a37cf, - 0x3a3b8c, - 0x3a3e8d, - 0x3a41cf, - 0x3a458c, - 0x3a508c, - 0x3a550c, - 0x3a580c, - 0x3a5ecd, - 0x3a6212, - 0x3a688c, - 0x3a6b8c, - 0x3a6e91, - 0x3a72cf, - 0x3a768f, - 0x3a7a53, - 0x3a8a0e, - 0x3a8d8f, - 0x3a914c, - 0x537a948e, - 0x3a980f, - 0x3a9bd6, - 0x3aaa92, - 0x3acf0c, - 0x3ada0f, - 0x3ae08d, - 0x3ae3cf, - 0x3ae78c, - 0x3aea8d, - 0x3aedcd, - 0x3b084e, - 0x3b228c, - 0x3b258c, - 0x3b2890, - 0x3b57d1, - 0x3b5c0b, - 0x3b5f4c, - 0x3b624e, + 0x24204a, + 0x28dd45, + 0x29ed06, + 0x209784, + 0x2afac6, + 0x347b85, + 0x307086, + 0x2e44cc, + 0x218d4a, + 0x252b04, + 0x2060c6, + 0x29bfc7, + 0x2cc904, + 0x26d1c8, + 0x2f3106, + 0x211509, + 0x2db609, + 0x394949, + 0x2c7246, + 0x203b46, + 0x283807, + 0x38dac8, + 0x203949, + 0x31bd47, + 0x2954c6, + 0x2faac7, + 0x2a6b05, + 0x2bc7c4, + 0x2833c7, + 0x267e05, + 0x286545, + 0x31f747, + 0x245808, + 0x3b22c6, + 0x2977cd, + 0x29924f, + 0x29d54d, + 0x214084, + 0x238986, + 0x2d0688, + 0x3ab905, + 0x28f508, + 0x256f8a, + 0x240084, + 0x233b46, + 0x2cd107, + 0x2ca387, + 0x2cfe09, + 0x283685, + 0x2b1804, + 0x2b49ca, + 0x2bbbc9, + 0x26dbc7, + 0x297a86, + 0x351446, + 0x284606, + 0x371d46, + 0x2cf6cf, + 0x2d0549, + 0x24e386, + 0x354846, + 0x31ac09, + 0x2b2147, + 0x20be43, + 0x22c946, + 0x20de03, + 0x2de988, + 0x2fa907, + 0x29f889, + 0x2b1b88, + 0x318108, + 0x328006, + 0x21ef89, + 0x399b05, + 0x2b2204, + 0x2e8187, + 0x372b85, + 0x214084, + 0x211988, + 0x2174c4, + 0x2b1e87, + 0x30d686, + 0x395ac5, + 0x2ae608, + 0x35130b, + 0x2b4107, + 0x2422c6, + 0x2c2b84, + 0x2b6286, + 0x26a985, + 0x267e05, + 0x27cf49, + 0x280fc9, + 0x22eac4, + 0x22eb05, + 0x206105, + 0x3bf206, + 0x36fc08, + 0x2bdc86, + 0x3aa9cb, + 0x37570a, + 0x2ba585, + 0x28b906, + 0x39df85, + 0x345405, + 0x29b847, + 0x3c2a88, + 0x24ed84, + 0x39ce86, + 0x28e306, + 0x218287, + 0x30eb04, + 0x27bcc6, + 0x35c745, + 0x35c749, + 0x203d44, + 0x2b3f49, + 0x2795c6, + 0x2c0048, + 0x206105, + 0x36e305, + 0x307086, + 0x344909, + 0x21be49, + 0x2ebe46, + 0x382d48, + 0x2ab188, + 0x39df44, + 0x2b5504, + 0x2b5508, + 0x239d08, + 0x24ee89, + 0x2975c6, + 0x24c486, + 0x32be4d, + 0x27c986, + 0x2ce449, + 0x39e845, + 0x20de46, + 0x2941c8, + 0x3277c5, + 0x267c84, + 0x26a985, + 0x280908, + 0x29a449, + 0x276804, + 0x31e346, + 0x251f0a, + 0x2ff648, + 0x231589, + 0x25890a, + 0x3197c6, + 0x299408, + 0x293005, + 0x28ae88, + 0x2e7905, + 0x221c89, + 0x376189, + 0x23c442, + 0x26f3c5, + 0x2ebf86, + 0x279507, + 0x38c8c5, + 0x30d2c6, + 0x304c08, + 0x2b0486, + 0x2d9309, + 0x278b86, + 0x280a88, + 0x2a9605, + 0x382106, + 0x336c48, + 0x27fd48, + 0x396008, + 0x2f2388, + 0x3c53c4, + 0x21e583, + 0x2d9544, + 0x27edc6, + 0x2a6b44, + 0x24c787, + 0x3962c9, + 0x3c0485, + 0x345606, + 0x22c946, + 0x2b514b, + 0x2b0d86, + 0x293b06, + 0x393208, + 0x310806, + 0x224303, + 0x3c4e83, + 0x2bc7c4, + 0x233e85, + 0x2d45c7, + 0x276988, + 0x27698f, + 0x27af4b, + 0x36fa08, + 0x31e3c6, + 0x36fd0e, + 0x242483, + 0x2d4544, + 0x2b0d05, + 0x2b1686, + 0x28c94b, + 0x290706, + 0x227109, + 0x395ac5, + 0x2eccc8, + 0x20e688, + 0x21bd0c, + 0x29e6c6, + 0x2c5406, + 0x2e9f85, + 0x287888, + 0x27a345, + 0x350288, + 0x29b04a, + 0x29d989, + 0x6010c4, + 0x200742, + 0x3c202c42, + 0x202542, + 0x26ff84, + 0x201e42, + 0x21a484, + 0x2032c2, + 0x200342, + 0x207c02, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x2b6c03, + 0x20be03, + 0x237583, + 0x30e843, + 0x26ff84, + 0x20ec83, + 0x241d03, + 0x210143, + 0x28b304, + 0x20be03, + 0x23d744, + 0x237583, + 0x2d2484, + 0x30e843, + 0x38cb87, + 0x21f743, + 0x20ae43, + 0x310f08, + 0x241d03, + 0x2a47cb, + 0x2e8943, + 0x3a25c6, + 0x20e982, + 0x3987cb, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x20be03, + 0x237583, + 0x30e843, + 0x241d03, + 0x2098c3, + 0x204543, + 0x200742, + 0xcd588, + 0x3574c5, + 0x267e88, + 0x2e2e08, + 0x202c42, + 0x3325c5, + 0x331707, + 0x201b02, + 0x248887, + 0x202542, + 0x256807, + 0x3c0b89, + 0x292bc8, + 0x293ec9, + 0x247342, + 0x269ec7, + 0x329844, + 0x3317c7, + 0x375607, + 0x25fe82, + 0x21f743, + 0x20d682, + 0x2032c2, + 0x200342, + 0x20b182, + 0x200382, + 0x207c02, + 0x2a9105, + 0x24d0c5, + 0x2c42, + 0x37583, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0xaff03, + 0x241d03, + 0x10c43, + 0x781, + 0x20be03, + 0x237583, + 0x30e843, + 0x26ff84, + 0x214bc3, + 0x20ec83, + 0xaff03, + 0x241d03, + 0x21a003, + 0x3f0eca46, + 0x6f803, + 0x7f685, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x202c42, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x9482, + 0xcd588, + 0xae43, + 0xaff03, + 0x4cec4, + 0xd8d45, + 0x200742, + 0x3a4c04, + 0x20be03, + 0x237583, + 0x30e843, + 0x3a2f03, + 0x232585, + 0x214bc3, + 0x20f003, + 0x20ec83, + 0x228803, + 0x241d03, + 0x207c03, + 0x2605c3, + 0x203f83, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x202c42, + 0x241d03, + 0xcd588, + 0x30e843, + 0xaff03, + 0xcd588, + 0xaff03, + 0x2b8283, + 0x20be03, + 0x234784, + 0x237583, + 0x30e843, + 0x207d02, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x20be03, + 0x237583, + 0x30e843, + 0x207d02, + 0x20be83, + 0x20ec83, + 0x241d03, + 0x2e2d83, + 0x207c03, + 0x200742, + 0x202c42, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x3a25c5, + 0x9a2c6, + 0x28b304, + 0x20e982, + 0xcd588, + 0x200742, + 0x20288, + 0x132983, + 0x202c42, + 0x43490186, + 0x12b44, + 0x10bfcb, + 0x41546, + 0x1f847, + 0x237583, + 0x52748, + 0x30e843, + 0xef4c5, + 0xe84, + 0x222003, + 0x56c47, + 0xd4344, + 0x20ec83, + 0xafd44, + 0xaff03, + 0x241d03, + 0x2e9484, + 0xfdb48, + 0x157206, + 0x10d08, + 0x135fc5, + 0x126749, + 0x202c42, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ae43, + 0x241d03, + 0x2e8943, + 0x20e982, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x26ff83, + 0x226444, + 0x20ec83, + 0xae43, + 0x241d03, + 0x20be03, + 0x237583, + 0x2d2484, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x3a25c6, + 0x237583, + 0x30e843, + 0x181c43, + 0x241d03, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x1f847, + 0xcd588, + 0x30e843, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x45e0be03, + 0x237583, + 0x20ec83, + 0x241d03, + 0xcd588, + 0x200742, + 0x202c42, + 0x20be03, + 0x30e843, + 0x20ec83, + 0x200342, + 0x241d03, + 0x32e147, + 0x23b00b, + 0x205d03, + 0x2409c8, + 0x38d847, + 0x224906, + 0x2c1605, + 0x38e5c9, + 0x21f4c8, + 0x36b4c9, + 0x39b210, + 0x36b4cb, + 0x2f6809, + 0x207503, + 0x22bcc9, + 0x235b46, + 0x235b4c, + 0x357588, + 0x3c02c8, + 0x200289, + 0x2e244e, + 0x3c094b, + 0x34754c, + 0x205583, + 0x27b80c, + 0x205589, + 0x2fbf47, + 0x2374cc, + 0x2ad14a, + 0x253404, + 0x32a08d, + 0x27b6c8, + 0x21014d, + 0x28a7c6, + 0x28b30b, + 0x31d689, + 0x27a747, + 0x3c2c46, + 0x341409, + 0x32538a, + 0x313048, + 0x2e8544, + 0x332e87, + 0x249d47, + 0x277984, + 0x2d9a44, + 0x386dc9, + 0x364209, + 0x215cc8, + 0x2108c5, + 0x2ea8c5, + 0x20d106, + 0x329f49, + 0x25720d, + 0x2f3308, + 0x20d007, + 0x2c1688, + 0x23ce86, + 0x37ce44, + 0x286c45, + 0x203846, + 0x2043c4, + 0x205487, + 0x2081ca, + 0x213904, + 0x2170c6, + 0x217d49, + 0x217d4f, + 0x21870d, + 0x218fc6, + 0x21fe90, + 0x220286, + 0x220807, + 0x221447, + 0x22144f, + 0x222149, + 0x228d46, + 0x22a1c7, + 0x22a1c8, + 0x22b089, + 0x395b88, + 0x2de4c7, + 0x22cf43, + 0x3bcfc6, + 0x3bbb08, + 0x2e270a, + 0x387809, + 0x212743, + 0x331606, + 0x39ccca, + 0x2e4b47, + 0x2fbd8a, + 0x209a8e, + 0x222286, + 0x26f5c7, + 0x21bac6, + 0x205646, + 0x38a50b, + 0x34edca, + 0x309b0d, + 0x203c07, + 0x260648, + 0x260649, + 0x26064f, + 0x34eb0c, + 0x27c0c9, + 0x2d778e, + 0x38cc8a, + 0x293886, + 0x2f9f06, + 0x313ccc, + 0x315a8c, + 0x328308, + 0x353d07, + 0x26d545, + 0x290504, + 0x202c4e, + 0x266f84, + 0x3188c7, + 0x39270a, + 0x3a2a54, + 0x3b92cf, + 0x221608, + 0x3bce88, + 0x33984d, + 0x33984e, + 0x231a09, + 0x232b08, + 0x232b0f, + 0x2371cc, + 0x2371cf, + 0x2386c7, + 0x23dfca, + 0x22c54b, + 0x23f5c8, + 0x242707, + 0x2616cd, + 0x20a286, + 0x32a246, + 0x2443c9, + 0x2a6f88, + 0x249208, + 0x24920e, + 0x23b107, + 0x24b505, + 0x24cc85, + 0x204c44, + 0x224bc6, + 0x215bc8, + 0x322ec3, + 0x397e4e, + 0x261a88, + 0x2ae14b, + 0x301c07, + 0x2f7305, + 0x27b986, + 0x2aab07, + 0x2f4848, + 0x317909, + 0x20a505, + 0x284bc8, + 0x226e06, + 0x39caca, + 0x202b49, + 0x237589, + 0x23758b, + 0x3211c8, + 0x277849, + 0x210986, + 0x36db0a, + 0x2bf50a, + 0x23e1cc, + 0x21e907, + 0x2929ca, + 0x211d0b, + 0x211d19, + 0x30a988, + 0x3a2645, + 0x261886, + 0x26ba89, + 0x358706, + 0x2d340a, + 0x21f6c6, + 0x225784, + 0x2c380d, + 0x323307, + 0x225789, + 0x24e685, + 0x251548, + 0x252509, + 0x252944, + 0x253307, + 0x253308, + 0x253907, + 0x268688, + 0x257887, + 0x205dc5, + 0x25d60c, + 0x25de49, + 0x30590a, + 0x3a0e09, + 0x22bdc9, + 0x37924c, + 0x26004b, + 0x260dc8, + 0x261e88, + 0x265244, + 0x281b08, + 0x283c89, + 0x2ad207, + 0x217f86, + 0x31d907, + 0x3843c9, + 0x335c0b, + 0x2b6107, + 0x3c6847, + 0x216407, + 0x2100c4, + 0x2100c5, + 0x278845, + 0x34c04b, + 0x3ad084, + 0x320d08, + 0x28550a, + 0x226ec7, + 0x35b207, + 0x28c112, + 0x2a10c6, + 0x234106, + 0x2b658e, + 0x2a4a86, + 0x291508, + 0x291a8f, + 0x210508, + 0x38b748, + 0x2bb78a, + 0x2bb791, + 0x2a0d4e, + 0x242a0a, + 0x242a0c, + 0x232d07, + 0x232d10, + 0x3c4cc8, + 0x2a0f45, + 0x2aae0a, + 0x20440c, + 0x29580d, + 0x2fc446, + 0x2fc447, + 0x2fc44c, + 0x30460c, + 0x214bcc, + 0x2ab88b, + 0x3706c4, + 0x211dc4, + 0x388489, + 0x30a2c7, + 0x23dd89, + 0x2bf349, + 0x2ace07, + 0x2acfc6, + 0x2acfc9, + 0x2ad3c3, + 0x2b058a, + 0x31b487, + 0x3491cb, + 0x30998a, + 0x3298c4, + 0x316946, + 0x27ee49, + 0x23a2c4, + 0x39eeca, + 0x2425c5, + 0x2bcbc5, + 0x2bcbcd, + 0x2bcf0e, + 0x2d9685, + 0x32d506, + 0x3a21c7, + 0x25d88a, + 0x37a506, + 0x2e1304, + 0x303707, + 0x246a4b, + 0x23cf47, + 0x3c1a04, + 0x390706, + 0x39070d, + 0x38408c, + 0x20eb46, + 0x2f350a, + 0x27c686, + 0x285788, + 0x354b47, + 0x23618a, + 0x24b386, + 0x203b03, + 0x294346, + 0x3bb988, + 0x38860a, + 0x2cb107, + 0x2cb108, + 0x30df84, + 0x28c687, + 0x201cc8, + 0x2a12c8, + 0x2827c8, + 0x2b130a, + 0x2d8345, + 0x20be87, + 0x242853, + 0x25a706, + 0x21b388, + 0x227609, + 0x248748, + 0x32808b, + 0x318488, + 0x246b84, + 0x365386, + 0x311e06, + 0x2dfa89, + 0x382807, + 0x25d708, + 0x29c806, + 0x31f644, + 0x341d05, + 0x2c7e48, + 0x34398a, + 0x2c3488, + 0x2c8906, + 0x29960a, + 0x3b8e48, + 0x2cc708, + 0x2cd2c8, + 0x2cdd46, + 0x2d0886, + 0x3a08cc, + 0x2d0e10, + 0x29ea45, + 0x210308, + 0x394490, + 0x210310, + 0x39b08e, + 0x3a054e, + 0x3a0554, + 0x3a624f, + 0x3a6606, + 0x321391, + 0x31eb13, + 0x31ef88, + 0x3ab285, + 0x240f08, + 0x387b05, + 0x2da18c, + 0x22cd09, + 0x290349, + 0x22d187, + 0x251309, + 0x24f147, + 0x2f8cc6, + 0x286a47, + 0x2034c5, + 0x210c83, + 0x323089, + 0x2278c9, + 0x381c43, + 0x38c7c4, + 0x326f0d, + 0x347c8f, + 0x31f685, + 0x3175c6, + 0x225a47, + 0x357307, + 0x2f5886, + 0x2f588b, + 0x2a2bc5, + 0x25f106, + 0x2f9d87, + 0x258249, + 0x375d06, + 0x322285, + 0x374e4b, + 0x3be7c6, + 0x229a85, + 0x27dc08, + 0x2b2bc8, + 0x2aec8c, + 0x2aec90, + 0x2ae949, + 0x2bd487, + 0x2d8e4b, + 0x306746, + 0x2de38a, + 0x2df80b, + 0x2e094a, + 0x2e0bc6, + 0x2e2c45, + 0x31b1c6, + 0x2b7048, + 0x22d24a, + 0x3394dc, + 0x2e8a0c, + 0x2e8d08, + 0x3a25c5, + 0x361f87, + 0x209946, + 0x270bc5, + 0x21a846, + 0x2f5a48, + 0x2bbe47, + 0x2e2348, + 0x25a7ca, + 0x225b4c, + 0x20d309, + 0x345787, + 0x222a04, + 0x24cd46, + 0x38b2ca, + 0x2bf445, + 0x2110cc, + 0x213588, + 0x373608, + 0x2238cc, + 0x2dd30c, + 0x329409, + 0x329647, + 0x24398c, + 0x22c044, + 0x2482ca, + 0x3033cc, + 0x27280b, + 0x372f0b, + 0x253786, + 0x258d87, + 0x232f47, + 0x232f4f, + 0x2fce11, + 0x2d5b52, + 0x2590cd, + 0x2590ce, + 0x25940e, + 0x3a6408, + 0x3a6412, + 0x25eb08, + 0x38d487, + 0x2556ca, + 0x355cc8, + 0x2a4a45, + 0x37fe0a, + 0x220607, + 0x316244, + 0x221b83, + 0x378205, + 0x2bba07, + 0x307c47, + 0x295a0e, + 0x399e8d, + 0x39b5c9, + 0x20fd85, + 0x3b00c3, + 0x20ab06, + 0x25f705, + 0x2ae388, + 0x2b9609, + 0x2618c5, + 0x2618cf, + 0x2e2a87, + 0x38e505, + 0x3025ca, + 0x2b1506, + 0x25b949, + 0x2f640c, + 0x2f80c9, + 0x3be506, + 0x28530c, + 0x32c906, + 0x2fb508, + 0x2fba86, + 0x30ab06, + 0x2b0f04, + 0x30d603, + 0x38668a, + 0x216711, + 0x27c28a, + 0x272085, + 0x282347, + 0x25ab47, + 0x201dc4, + 0x201dcb, + 0x293d48, + 0x2ba046, + 0x36e145, + 0x33d8c4, + 0x362109, + 0x202a84, + 0x249047, + 0x300585, + 0x300587, + 0x2b67c5, + 0x3482c3, + 0x38d348, + 0x317c4a, + 0x27f283, + 0x35750a, + 0x3b3486, + 0x26164f, + 0x3b8349, + 0x397dd0, + 0x2effc8, + 0x2c8d49, + 0x296707, + 0x39068f, + 0x319c04, + 0x2d2504, + 0x220106, + 0x34f846, + 0x2d6e8a, + 0x253c06, + 0x352987, + 0x303f48, + 0x304147, + 0x3049c7, + 0x305b8a, + 0x3083cb, + 0x341ac5, + 0x2d5788, + 0x256703, + 0x3b6b0c, + 0x35d60f, + 0x26d34d, + 0x25e287, + 0x39b709, + 0x36de47, + 0x282c48, + 0x3a2c4c, + 0x2c8a48, + 0x2701c8, + 0x31c38e, + 0x333d94, + 0x3342a4, + 0x35308a, + 0x36becb, + 0x24f204, + 0x24f209, + 0x233bc8, + 0x24d305, + 0x3229ca, + 0x261cc7, + 0x31b0c4, + 0x2b6c03, + 0x20be03, + 0x23d744, + 0x237583, + 0x30e843, + 0x26ff84, + 0x214bc3, + 0x21f743, + 0x2d0e06, + 0x226444, + 0x20ec83, + 0x241d03, + 0x219543, + 0x200742, + 0x2b6c03, + 0x202c42, + 0x20be03, + 0x23d744, + 0x237583, + 0x30e843, + 0x214bc3, + 0x2d0e06, + 0x20ec83, + 0x241d03, + 0xcd588, + 0x20be03, + 0x237583, + 0x203d43, + 0x20ec83, + 0xaff03, + 0x241d03, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x226444, + 0x20ec83, + 0x241d03, + 0x200742, + 0x24be43, + 0x202c42, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x203cc2, + 0x24d5c2, + 0x202c42, + 0x20be03, + 0x20b2c2, + 0x201342, + 0x26ff84, + 0x21a484, + 0x227d42, + 0x226444, + 0x200342, + 0x241d03, + 0x219543, + 0x253786, + 0x230882, + 0x204182, + 0x228382, + 0x48610503, + 0x48a32d03, + 0x5b586, + 0x5b586, + 0x28b304, + 0x20ae43, + 0x15a4a, + 0x3ba4c, + 0x121ecc, + 0x7f48d, + 0x117485, + 0x2aa47, + 0x14ec6, + 0x19148, + 0x1c787, + 0x23288, + 0x1807ca, + 0x102c07, + 0x496d2fc5, + 0x133789, + 0x3c00b, + 0x18754b, + 0x1bdd08, + 0xf608a, + 0x8a34e, + 0x144854b, + 0x12b44, + 0x5f246, + 0x8808, + 0x7e948, + 0x3c2c7, + 0x910c7, + 0x78449, + 0x3a347, + 0x67008, + 0x100249, + 0x170bc4, + 0x191e05, + 0x12f34e, + 0xa964d, + 0x1f6c8, + 0x49b64046, + 0x4a564048, + 0x739c8, + 0x12e350, + 0x5978c, + 0x666c7, + 0x66e47, + 0x6abc7, + 0x704c7, + 0xd0c2, + 0x1807, + 0x14ef8c, + 0x11d107, + 0xa4686, + 0xa5a89, + 0xa7708, + 0x552c2, + 0x1342, + 0x3900b, + 0xafdc7, + 0x25589, + 0x52c49, + 0x142188, + 0xb0102, + 0x1970c9, + 0xc9f8a, + 0xc6209, + 0xd3909, + 0xd50c8, + 0xd6007, + 0xd82c9, + 0xda885, + 0xdae90, + 0x138ac6, + 0x14a345, + 0xeb78d, + 0x2bac6, + 0xe3d47, + 0xe9498, + 0x3a6c8, + 0x14640a, + 0x16f02, + 0x5f88d, + 0x1282, + 0x7dac6, + 0x8cc08, + 0x6e308, + 0xcd449, + 0x1be608, + 0x6f98e, + 0xab07, + 0xfe68d, + 0xf26c5, + 0x1588, + 0x1a1e08, + 0xfeec6, + 0xc842, + 0x157206, + 0xdc2, + 0x2c1, + 0x60a07, + 0x8b003, + 0x49ee9d04, + 0x4a294a43, + 0x101, + 0x13d06, + 0x101, + 0x301, + 0x13d06, + 0x8b003, + 0x140e3c5, + 0x253404, + 0x20be03, + 0x254a04, + 0x26ff84, + 0x20ec83, + 0x2274c5, + 0x21a003, + 0x24f3c3, + 0x2f5805, + 0x203f83, + 0x4b60be03, + 0x237583, + 0x30e843, + 0x200541, + 0x21f743, + 0x21a484, + 0x226444, + 0x20ec83, + 0x241d03, + 0x207c03, + 0xcd588, + 0x200742, + 0x2b6c03, + 0x202c42, + 0x20be03, + 0x237583, + 0x203d43, + 0x201342, + 0x26ff84, + 0x214bc3, + 0x21f743, + 0x20ec83, + 0x20ae43, + 0x241d03, + 0x203f83, + 0xcd588, + 0x35d382, + 0x1851c7, + 0x2c42, + 0x141c85, + 0x598cf, + 0x1455908, + 0x10430e, + 0x4c607402, + 0x31a848, + 0x307206, + 0x2c1146, + 0x306b87, + 0x4ca11a42, + 0x4cfb81c8, + 0x21ed8a, + 0x266148, + 0x200602, + 0x31b2c9, + 0x341b07, + 0x217f06, + 0x38d089, + 0x20bfc4, + 0x20e2c6, + 0x2f2904, + 0x270984, + 0x25cf89, + 0x3030c6, + 0x24d185, + 0x2faf45, + 0x2322c7, + 0x2be9c7, + 0x354984, + 0x306dc6, + 0x2ff205, + 0x309485, + 0x39dec5, + 0x2ea687, + 0x301a45, + 0x319149, + 0x336f85, + 0x2f4984, + 0x37a447, + 0x348a0e, + 0x3aaec9, + 0x2b6449, + 0x335246, + 0x2454c8, + 0x2ee34b, + 0x35bd8c, + 0x33b746, + 0x347407, + 0x2afbc5, + 0x2d9a4a, + 0x215dc9, + 0x366f09, + 0x332706, + 0x2f9b45, + 0x383105, + 0x338689, + 0x39e04b, + 0x275e86, + 0x343ec6, + 0x203104, + 0x28bdc6, + 0x24b588, + 0x3bb806, + 0x21d186, + 0x206888, + 0x209347, + 0x209509, + 0x20acc5, + 0xcd588, + 0x291044, + 0x304f44, + 0x210f05, + 0x3a8c49, + 0x226087, + 0x22608b, + 0x2288ca, + 0x22cc45, + 0x4d207a42, + 0x309847, + 0x4d62cf48, + 0x370a47, + 0x383e85, + 0x32654a, + 0x2c42, + 0x2fac0b, + 0x2579ca, + 0x2277c6, + 0x210d83, + 0x2a4f8d, + 0x3aa74c, + 0x3bedcd, + 0x24e2c5, + 0x37dd45, + 0x322f07, + 0x20b2c9, + 0x21ec86, + 0x253a85, + 0x2ced88, + 0x28bcc3, + 0x2e3108, + 0x28bcc8, + 0x2c2107, + 0x30f108, + 0x3aa549, + 0x286d47, + 0x23ab87, + 0x224788, + 0x38ae04, + 0x38ae07, + 0x28a6c8, + 0x353706, + 0x3b544f, + 0x2293c7, + 0x2de646, + 0x329785, + 0x228503, + 0x391c87, + 0x378183, + 0x253e86, + 0x2553c6, + 0x255b06, + 0x28fa05, + 0x268683, + 0x396d48, + 0x379c89, + 0x38eb4b, + 0x255c88, + 0x257545, + 0x258b85, + 0x4db29982, + 0x286b09, + 0x38d707, + 0x25f185, + 0x25ce87, + 0x25e9c6, + 0x371c05, + 0x25f54b, + 0x260dc4, + 0x265d05, + 0x265e47, + 0x275806, + 0x275c45, + 0x281d07, + 0x2829c7, + 0x2e1704, + 0x28990a, + 0x289dc8, + 0x293089, + 0x241245, + 0x364946, + 0x24b74a, + 0x2fae46, + 0x268fc7, + 0x292d4d, + 0x2a2709, + 0x3954c5, + 0x2031c7, + 0x31f148, + 0x336a08, + 0x209ec7, + 0x3be1c6, + 0x21d4c7, + 0x255083, + 0x303044, + 0x36e785, + 0x39fc47, + 0x3a4609, + 0x230cc8, + 0x33dc85, + 0x2363c4, + 0x253d45, + 0x39038d, + 0x211742, + 0x2bd986, + 0x27da06, + 0x2dac0a, + 0x381346, + 0x38b205, + 0x31ffc5, + 0x31ffc7, + 0x39c90c, + 0x27384a, + 0x28ba86, + 0x2c4d85, + 0x28bc06, + 0x28bf47, + 0x28d986, + 0x28f90c, + 0x38d1c9, + 0x4de14187, + 0x291e45, + 0x291e46, + 0x2944c8, + 0x247e85, + 0x2a3505, + 0x2a3c88, + 0x2a3e8a, + 0x4e278142, + 0x4e607c82, + 0x2d7485, + 0x2a6b43, + 0x2461c8, + 0x211b83, + 0x2a4104, + 0x25ba8b, + 0x211b88, + 0x2ce288, + 0x4eb1cb49, + 0x2a8e09, + 0x2a9546, + 0x2aa788, + 0x2aa989, + 0x2ab386, + 0x2ab505, + 0x24e0c6, + 0x2abfc9, + 0x3ac147, + 0x381fc6, + 0x2d8787, + 0x21eb07, + 0x34e204, + 0x4ee3a9c9, + 0x270e08, + 0x3b80c8, + 0x31f887, + 0x2c2f46, + 0x20b0c9, + 0x2f2bc7, + 0x33194a, + 0x364a88, + 0x3be307, + 0x20ed86, + 0x39d28a, + 0x372cc8, + 0x382ac5, + 0x22b9c5, + 0x30b047, + 0x36ac49, + 0x30280b, + 0x314248, + 0x337009, + 0x255f87, + 0x2b868c, + 0x2b8c8c, + 0x2b8f8a, + 0x2b920c, + 0x2c10c8, + 0x2c12c8, + 0x2c14c4, + 0x2c1889, + 0x2c1ac9, + 0x2c1d0a, + 0x2c1f89, + 0x2c22c7, + 0x3b4c4c, + 0x23d386, + 0x3c0708, + 0x2faf06, + 0x37fc46, + 0x3953c7, + 0x3ab0c8, + 0x349c4b, + 0x370907, + 0x35b849, + 0x3782c9, + 0x254b87, + 0x2f2b44, + 0x282487, + 0x2eaf46, + 0x215946, + 0x2f36c5, + 0x3720c8, + 0x290244, + 0x290246, + 0x27370b, + 0x2b0889, + 0x39ddc6, + 0x204cc9, + 0x2ea806, + 0x22e688, + 0x20b4c3, + 0x2f9cc5, + 0x21d2c9, + 0x228b05, + 0x30ae84, + 0x274d06, + 0x3993c5, + 0x259b06, + 0x308747, + 0x331086, + 0x23078b, + 0x36da07, + 0x256e46, + 0x348606, + 0x232386, + 0x354949, + 0x2e474a, + 0x2ba345, + 0x3be8cd, + 0x2a3f86, + 0x2e9106, + 0x397cc6, + 0x285705, + 0x2db187, + 0x2f75c7, + 0x207cce, + 0x21f743, + 0x2c2f09, + 0x358489, + 0x2d9e47, + 0x26c287, + 0x2a1445, + 0x2ae085, + 0x4f386f0f, + 0x2c8f87, + 0x2c9148, + 0x2c9884, + 0x2c9e46, + 0x4f64cd02, + 0x2cdfc6, + 0x2d0e06, + 0x349f8e, + 0x2e2f4a, + 0x3b8946, + 0x2ca24a, + 0x2065c9, + 0x231e85, + 0x344788, + 0x39a146, + 0x29aac8, + 0x3c2dc8, + 0x2a57cb, + 0x306c85, + 0x301ac8, + 0x2069cc, + 0x383d47, + 0x255606, + 0x27c4c8, + 0x224a88, + 0x4fa53982, + 0x20e08b, + 0x3361c9, + 0x21cb09, + 0x39dc47, + 0x38a7c8, + 0x4fe3ca88, + 0x21318b, + 0x342009, + 0x28394d, + 0x24e488, + 0x3518c8, + 0x502056c2, + 0x331404, + 0x50623b82, + 0x2f7e06, + 0x50a0a542, + 0x24fc8a, + 0x204b86, + 0x22e0c8, + 0x2be048, + 0x326cc6, + 0x398b46, + 0x2efd46, + 0x2ae305, + 0x240684, + 0x50e2e604, + 0x34c986, + 0x2a2247, + 0x5121c1c7, + 0x2e1bcb, + 0x348dc9, + 0x37dd8a, + 0x357ec4, + 0x320108, + 0x381d8d, + 0x2e6e49, + 0x2e7088, + 0x2e7709, + 0x2e9484, + 0x22c404, + 0x27d505, + 0x2ee68b, + 0x211b06, + 0x34c7c5, + 0x222449, + 0x306e88, + 0x29fb44, + 0x2d9bc9, + 0x326b05, + 0x2bea08, + 0x23b247, + 0x2b6848, + 0x27f046, + 0x207907, + 0x2d4109, + 0x374fc9, + 0x229b05, + 0x240305, + 0x51607482, + 0x2f4744, + 0x225dc5, + 0x292786, + 0x2f8305, + 0x297b87, + 0x34ca85, + 0x275844, + 0x335306, + 0x253b07, + 0x234fc6, + 0x384305, + 0x20e4c8, + 0x307405, + 0x20ef87, + 0x2154c9, + 0x2b09ca, + 0x34e587, + 0x34e58c, + 0x24d146, + 0x241b89, + 0x244885, + 0x247dc8, + 0x201283, + 0x210945, + 0x2eac05, + 0x257f47, + 0x51a12c02, + 0x398347, + 0x2f3c06, + 0x32fdc6, + 0x2f7f46, + 0x2249c6, + 0x2eb408, + 0x241045, + 0x2de707, + 0x2de70d, + 0x221b83, + 0x221b85, + 0x302387, + 0x398688, + 0x301f45, + 0x219788, + 0x23dc86, + 0x333947, + 0x3c0645, + 0x306d06, + 0x3a4c85, + 0x226bca, + 0x2fe986, + 0x22eec7, + 0x2f04c5, + 0x2ffc87, + 0x303684, + 0x30ae06, + 0x3446c5, + 0x357a0b, + 0x2eadc9, + 0x24bf4a, + 0x229b88, + 0x34c2c8, + 0x34cb8c, + 0x353847, + 0x36f808, + 0x387c08, + 0x394205, + 0x3a684a, + 0x3b00c9, + 0x51e01b42, + 0x3c6646, + 0x222e44, + 0x222e49, + 0x294f49, + 0x276587, + 0x2f9887, + 0x2bf1c9, + 0x285908, + 0x28590f, + 0x21dec6, + 0x2d2c8b, + 0x2f5645, + 0x2f5647, + 0x2f5c49, + 0x25bbc6, + 0x2d9b47, + 0x2d5ec5, + 0x234dc4, + 0x341006, + 0x226244, + 0x2df647, + 0x2ce808, + 0x522f9a48, + 0x2fa1c5, + 0x2fa307, + 0x24eb09, + 0x20de44, + 0x2473c8, + 0x52716788, + 0x201dc4, + 0x235fc8, + 0x3c2d04, + 0x3bebc9, + 0x21b2c5, + 0x52a0e982, + 0x21df05, + 0x2cb8c5, + 0x203008, + 0x238507, + 0x52e02a82, + 0x339e45, + 0x2cc586, + 0x249746, + 0x2f4708, + 0x2f4c88, + 0x2f82c6, + 0x30a146, + 0x385289, + 0x32fd06, + 0x29124b, + 0x3478c5, + 0x355c06, + 0x28e088, + 0x231bc6, + 0x20a386, + 0x219c4a, + 0x2a91ca, + 0x370c85, + 0x241107, + 0x30d0c6, + 0x53206d02, + 0x3024c7, + 0x260505, + 0x24b6c4, + 0x24b6c5, + 0x357dc6, + 0x271a47, + 0x220105, + 0x295004, + 0x2ad5c8, + 0x20a445, + 0x309fc7, + 0x3b1c45, + 0x226b05, + 0x268904, + 0x2abac9, + 0x2ff048, + 0x399286, + 0x2adc46, + 0x201ac6, + 0x536ff908, + 0x2ffb07, + 0x2ffe4d, + 0x30074c, + 0x300d49, + 0x300f89, + 0x53b65c82, + 0x3b7e83, + 0x2228c3, + 0x2eb005, + 0x39fd4a, + 0x32fbc6, + 0x3052c5, + 0x308904, + 0x30890b, + 0x323e4c, + 0x32488c, + 0x324b95, + 0x32754d, + 0x32a68f, + 0x32aa52, + 0x32aecf, + 0x32b292, + 0x32b713, + 0x32bbcd, + 0x32c18d, + 0x32c50e, + 0x32ca8e, + 0x32d2cc, + 0x32d68c, + 0x32dacb, + 0x32de4e, + 0x32e752, + 0x32f98c, + 0x32ff50, + 0x33ba12, + 0x33c68c, + 0x33cd4d, + 0x33d08c, + 0x33f651, + 0x34404d, + 0x34ac8d, + 0x34b28a, + 0x34b50c, + 0x34be0c, + 0x34c4cc, + 0x34ce8c, + 0x350493, + 0x350b10, + 0x350f10, + 0x351acd, + 0x3520cc, + 0x352dc9, + 0x35518d, + 0x3554d3, + 0x356491, + 0x3568d3, + 0x35888f, + 0x358c4c, + 0x358f4f, + 0x35930d, + 0x35990f, + 0x359cd0, + 0x35a74e, + 0x35df0e, + 0x35e490, + 0x35f08d, + 0x35fa0e, + 0x35fd8c, + 0x360d93, + 0x3628ce, + 0x362f50, + 0x363351, + 0x36378f, + 0x363b53, + 0x36580d, + 0x365b4f, + 0x365f0e, + 0x3665d0, + 0x3669c9, + 0x367d10, + 0x36830f, + 0x36898f, + 0x368d52, + 0x369e0e, + 0x36a80d, + 0x36ae8d, + 0x36b1cd, + 0x36c84d, + 0x36cb8d, + 0x36ced0, + 0x36d2cb, + 0x36e54c, + 0x36e8cc, + 0x36eecc, + 0x36f1ce, + 0x37bbd0, + 0x37e012, + 0x37e48b, + 0x37e98e, + 0x37ed0e, + 0x37f58e, + 0x37fa0b, + 0x53f80196, + 0x38104d, + 0x3814d4, + 0x38228d, + 0x386915, + 0x388c4d, + 0x3895cf, + 0x389ccf, + 0x38ee0f, + 0x38f1ce, + 0x38f74d, + 0x391891, + 0x394b8c, + 0x394e8c, + 0x39518b, + 0x39560c, + 0x39654f, + 0x396912, + 0x39950d, + 0x39ae0c, + 0x39b94c, + 0x39bc4d, + 0x39bf8f, + 0x39c34e, + 0x39fa0c, + 0x39ffcd, + 0x3a030b, + 0x3a0bcc, + 0x3a14cd, + 0x3a180e, + 0x3a1b89, + 0x3a3553, + 0x3a3a8d, + 0x3a3dcd, + 0x3a43cc, + 0x3a484e, + 0x3a520f, + 0x3a55cc, + 0x3a58cd, + 0x3a5c0f, + 0x3a5fcc, + 0x3a778c, + 0x3a7b0c, + 0x3a7e0c, + 0x3a84cd, + 0x3a8812, + 0x3a8e8c, + 0x3a918c, + 0x3a9491, + 0x3a98cf, + 0x3a9c8f, + 0x3aa053, + 0x3ac70e, + 0x3aca8f, + 0x3ace4c, + 0x543ad18e, + 0x3ad50f, + 0x3ad8d6, + 0x3ae0d2, + 0x3af8cc, + 0x3b030f, + 0x3b098d, + 0x3b0ccf, + 0x3b108c, + 0x3b138d, + 0x3b16cd, + 0x3b2c8e, + 0x3b3bcc, + 0x3b3ecc, + 0x3b41d0, 0x3b7211, - 0x3b764e, - 0x3b79cd, - 0x3bc7cb, - 0x3bd88f, - 0x3be394, - 0x210642, - 0x210642, - 0x204d43, - 0x210642, - 0x204d43, - 0x210642, + 0x3b764b, + 0x3b7a8c, + 0x3b7d8e, + 0x3baa91, + 0x3baece, + 0x3bb24d, + 0x3c338b, + 0x3c3c8f, + 0x3c4794, + 0x25cd82, + 0x25cd82, + 0x2032c3, + 0x25cd82, + 0x2032c3, + 0x25cd82, 0x2009c2, - 0x394505, - 0x3b6f0c, - 0x210642, - 0x210642, + 0x24e105, + 0x3ba78c, + 0x25cd82, + 0x25cd82, 0x2009c2, - 0x210642, - 0x29c345, - 0x21bc05, - 0x210642, - 0x210642, - 0x201102, - 0x29c345, - 0x326b49, - 0x3592cc, - 0x210642, - 0x210642, - 0x210642, - 0x210642, - 0x394505, - 0x210642, - 0x210642, - 0x210642, - 0x210642, - 0x201102, - 0x326b49, - 0x210642, - 0x210642, - 0x210642, - 0x21bc05, - 0x210642, - 0x21bc05, - 0x3592cc, - 0x3b6f0c, - 0x39c783, - 0x238543, - 0x23cac3, - 0x323043, - 0x231604, - 0x208e83, - 0x201a03, - 0xe008, - 0x64344, - 0xe03, - 0xc63c8, - 0x207102, - 0x5460f882, - 0x24ac83, - 0x23f044, - 0x2020c3, - 0x39e544, - 0x23a1c6, - 0x216f83, - 0x304704, - 0x2d7b05, - 0x28cac3, - 0x208e83, - 0x1a3443, - 0x201a03, - 0x243d0a, - 0x3821c6, - 0x38558c, - 0x16fb88, - 0x20f882, - 0x238543, - 0x23cac3, - 0x323043, - 0x229443, - 0x20c0c6, - 0x208e83, - 0x201a03, - 0x221483, - 0xac408, - 0x131645, - 0x35f09, - 0x35c2, - 0x55b95645, - 0x26547, - 0xba9c8, - 0x14b0e, - 0x90212, - 0x10a78b, - 0x1398c6, - 0x55edf485, - 0x562df48c, - 0x148f87, - 0x36dc7, - 0x15000a, - 0x46690, - 0x13b345, - 0xb610b, - 0xf8d08, - 0x3e607, - 0x3af8b, - 0x57f89, - 0x185a87, - 0x81a87, - 0x7e4c7, - 0x3e546, - 0xdd088, - 0x56824386, - 0xb084d, - 0x14f9d0, - 0x56c0c182, - 0x8ca48, - 0x4f450, - 0x15090c, - 0x5735cd4d, - 0x64a88, - 0x721c7, - 0x76f09, - 0x5d3c6, - 0x9bec8, - 0x351c2, - 0xa808a, - 0x293c7, - 0x43b87, - 0xac7c9, - 0xae208, - 0x8b205, - 0xd538e, - 0x5c4e, - 0x17a8f, - 0x18009, - 0x164ec9, - 0x15d38b, - 0x7ba8f, - 0xee40c, - 0xa88cb, - 0xc8b48, - 0xd6347, - 0xdbe88, - 0xfe78b, - 0xff34c, - 0x10038c, - 0x1037cc, - 0x10b54d, - 0x3ef48, - 0xd2942, - 0x134649, - 0x195d8b, - 0xcd546, - 0x11f30b, - 0xe118a, - 0xe1d45, - 0xe67d0, - 0xe9f06, - 0x16b986, - 0x11205, - 0x10fc48, - 0xefd07, - 0xeffc7, - 0x8d047, - 0xfe04a, - 0xba84a, - 0x86286, - 0x99d0d, - 0x8f148, - 0x586c8, - 0x58ec9, - 0xbc8c5, - 0x1ad70c, - 0x10b74b, - 0x19e604, - 0x105e09, - 0x106046, - 0x16546, - 0x2642, - 0x12cf06, - 0xc68b, - 0x112707, - 0x4542, - 0xd1305, - 0x2e604, - 0x8c1, - 0x52d03, - 0x56764886, - 0x9c243, - 0x7b02, - 0x293c4, - 0x242, - 0x86644, - 0xf82, - 0x6502, - 0x3302, - 0xd342, - 0x1382, - 0xdf482, - 0x8c2, - 0x22902, - 0x40e82, - 0x1a442, - 0x4c82, - 0x234c2, - 0x3cac3, - 0x6b82, - 0x1842, - 0x7602, - 0x6b02, - 0x17202, - 0x36d02, - 0x206c2, - 0xc442, - 0x1c82, - 0x942, - 0x55783, + 0x25cd82, + 0x294b45, + 0x2b09c5, + 0x25cd82, + 0x25cd82, + 0x200302, + 0x294b45, + 0x328909, + 0x35618c, + 0x25cd82, + 0x25cd82, + 0x25cd82, + 0x25cd82, + 0x24e105, + 0x25cd82, + 0x25cd82, + 0x25cd82, + 0x25cd82, + 0x200302, + 0x328909, + 0x25cd82, + 0x25cd82, + 0x25cd82, + 0x2b09c5, + 0x25cd82, + 0x2b09c5, + 0x35618c, + 0x3ba78c, + 0x2b6c03, + 0x20be03, + 0x237583, + 0x30e843, + 0x26ff84, + 0x20ec83, + 0x241d03, + 0x1233c8, + 0x6fac4, + 0xae43, + 0x193708, + 0x200742, + 0x55202c42, + 0x246d03, + 0x252d84, + 0x206c03, + 0x3c24c4, + 0x234106, + 0x2137c3, + 0x2f9084, + 0x2f0b05, + 0x21f743, + 0x20ec83, + 0xaff03, + 0x241d03, + 0x22d50a, + 0x253786, + 0x37f08c, + 0xcd588, + 0x202c42, + 0x20be03, + 0x237583, + 0x30e843, + 0x20be83, + 0x2d0e06, + 0x20ec83, + 0x241d03, + 0x219543, + 0xa4d48, + 0x117485, + 0x187689, + 0x15842, + 0x56793ec5, + 0x2aa47, + 0xaf148, + 0xd9ce, + 0x87e92, + 0x11b5cb, + 0x102d06, + 0x56ad2fc5, + 0x56ed2fcc, + 0x25147, + 0x15da87, + 0x1208ca, + 0x42ed0, + 0x149445, + 0x10bfcb, + 0x7e948, + 0x3c2c7, + 0xf400b, + 0x78449, + 0x127b07, + 0x3a347, + 0x760c7, + 0x3c206, + 0x67008, + 0x57429546, + 0xa964d, + 0x120290, + 0x5780a6c2, + 0x1f6c8, + 0x82dd0, + 0x15b5cc, + 0x57f61e0d, + 0x5fbc8, + 0x6b8c7, + 0x164f49, + 0x5b646, + 0x946c8, + 0xebfc2, + 0x71e8a, + 0x31047, + 0x11d107, + 0xa5a89, + 0xa7708, + 0xef4c5, + 0xe85ce, + 0x1260e, + 0x1b98f, + 0x25589, + 0x52c49, + 0x7e10b, + 0x8ef4f, + 0xabccc, + 0x1125cb, + 0x105848, + 0xe1ac7, + 0xf87c8, + 0x132c8b, + 0x15274c, + 0x15af0c, + 0x1625cc, + 0x16784d, + 0x142188, + 0xfcdc2, + 0x1970c9, + 0x133acb, + 0xc3146, + 0x12e28b, + 0xd560a, + 0xd61c5, + 0xdae90, + 0xdd606, + 0x140806, + 0x14a345, + 0x18a988, + 0xe3d47, + 0xe4007, + 0x1fcc7, + 0xf7c4a, + 0xaefca, + 0x7dac6, + 0x9088d, + 0x6e308, + 0x1be608, + 0x68849, + 0xb7cc5, + 0xf778c, + 0x167a4b, + 0x16ab84, + 0xfec89, + 0xfeec6, + 0x4cb06, 0x4182, + 0x157206, + 0x14634b, + 0x10ac87, + 0xdc2, + 0xc5105, + 0x16704, + 0x781, + 0x7bc3, + 0x572a6d06, + 0x94a43, 0x2542, - 0xb8042, - 0x9a02, - 0x282, - 0x2942, - 0xd842, - 0xc202, - 0x4a82, - 0x182842, - 0x745c2, - 0xe82, - 0x8e83, - 0x1942, - 0x6802, + 0x31044, + 0x602, + 0x8b304, + 0xcc2, + 0x7ec2, + 0x3102, + 0x114902, + 0x3cc2, + 0xd2fc2, + 0x3c02, + 0xefa02, + 0x3e242, + 0x4ac2, + 0x2e02, + 0x4c3c2, + 0x37583, + 0x1f02, + 0x1b02, + 0x8882, + 0x12c42, + 0x1402, + 0x35c02, + 0x552c2, + 0x6202, + 0x3882, + 0x1342, + 0x14bc3, + 0x5842, + 0x1102, + 0xb0102, + 0x9602, + 0x1542, + 0x4482, + 0xe302, + 0x6f582, + 0x1e42, + 0x17c0c2, + 0x6cd82, + 0x3a3c2, + 0xec83, + 0x2002, + 0x53982, + 0x1382, + 0x6e02, + 0x29a85, + 0x8302, + 0x48602, + 0x44303, 0x982, - 0x5b82, - 0x18ad45, - 0x7082, - 0x2fa42, - 0x13ebc3, - 0x482, - 0xb282, - 0xa02, - 0x2502, - 0x6742, - 0xd42, - 0xc2, - 0x2642, - 0x35dc5, - 0x17f087, - 0x20d0c3, - 0x207102, - 0x238543, - 0x23cac3, - 0x21b583, - 0x2046c3, - 0x229443, - 0x208e83, - 0x200e03, - 0x201a03, - 0x29c283, - 0x10c3, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x21b583, - 0x28cac3, - 0x208e83, - 0x200e03, - 0x1a3443, - 0x201a03, - 0x238543, - 0x23cac3, - 0x201a03, - 0x238543, - 0x23cac3, - 0x323043, - 0x200041, - 0x28cac3, - 0x208e83, - 0x21b543, - 0x201a03, - 0x146f44, - 0x39c783, - 0x238543, - 0x23cac3, - 0x26eac3, - 0x21b583, - 0x207b03, - 0x289303, - 0x219983, - 0x241503, - 0x323043, - 0x231604, - 0x208e83, - 0x201a03, - 0x202443, - 0x333cc4, - 0x251183, - 0x3ec3, - 0x3c0943, - 0x20a3c8, - 0x271dc4, - 0x2cf30a, - 0x2bed86, - 0x112384, - 0x3a7ec7, - 0x226cca, - 0x2e38c9, - 0x3b7f87, - 0x3be84a, - 0x39c783, - 0x2e774b, - 0x28b689, - 0x345285, - 0x2da5c7, - 0xf882, - 0x238543, - 0x21a447, - 0x2379c5, - 0x2ca689, - 0x23cac3, - 0x2bd606, - 0x2c9883, - 0xe5743, - 0x110646, - 0xd386, - 0x16f07, - 0x21af86, - 0x222985, - 0x3a3147, - 0x2de5c7, - 0x59b23043, - 0x33dc07, - 0x374703, - 0x3b5045, - 0x231604, - 0x231308, - 0x366fcc, - 0x2b4fc5, - 0x2aa4c6, - 0x21a307, - 0x39b687, - 0x23dfc7, - 0x23f108, - 0x30f50f, - 0x2e3b05, - 0x24ad87, - 0x33acc7, - 0x2abdca, - 0x2d29c9, - 0x39e6c5, - 0x31078a, - 0xc546, - 0x2c9905, - 0x3703c4, - 0x2c6e86, - 0x300e07, - 0x2d2847, - 0x306908, - 0x217645, - 0x2378c6, - 0x214f85, - 0x2e8105, - 0x21ba04, - 0x2b6e07, - 0x20658a, - 0x34d908, - 0x367f06, - 0x29443, - 0x2e4505, - 0x26bf86, - 0x3babc6, - 0x211106, - 0x28cac3, - 0x3984c7, - 0x33ac45, - 0x208e83, - 0x2e144d, - 0x200e03, - 0x306a08, - 0x3b3644, - 0x310945, - 0x2abcc6, - 0x23f386, - 0x208947, - 0x2aed47, - 0x26f045, - 0x201a03, - 0x20a147, - 0x277089, - 0x36bbc9, - 0x227f4a, - 0x235d82, - 0x3b5004, - 0x2eb2c4, - 0x344487, - 0x22f508, - 0x2f0889, - 0x226fc9, - 0x2f1ac7, - 0x28bb46, - 0xf3006, - 0x2f4544, - 0x2f4b4a, - 0x2f8248, - 0x2f9049, - 0x2c4bc6, - 0x2b9545, - 0x34d7c8, - 0x2cdc4a, - 0x20ec43, - 0x333e46, - 0x2f1bc7, - 0x225f45, - 0x3b3505, - 0x3a04c3, - 0x231944, - 0x230645, - 0x28a287, - 0x307b05, - 0x2ef086, - 0x103d45, - 0x273bc3, - 0x273bc9, - 0x26c04c, - 0x2a2b4c, - 0x2d8648, - 0x284187, - 0x301e08, - 0x30214a, - 0x302fcb, - 0x28b7c8, - 0x23ec48, - 0x23f486, - 0x345045, - 0x34624a, - 0x228cc5, - 0x205082, - 0x2cbd87, - 0x29f806, - 0x368d45, - 0x304209, - 0x281405, - 0x3716c5, - 0x218ac9, - 0x388a46, - 0x204448, - 0x332643, - 0x217186, - 0x27cf86, - 0x311f05, - 0x311f09, - 0x2f0fc9, - 0x27a3c7, - 0x114204, - 0x314207, - 0x226ec9, - 0x23f805, - 0x444c8, - 0x39c485, - 0x341a05, - 0x3911c9, - 0x20cac2, - 0x2628c4, - 0x200882, - 0x204182, - 0x30e985, - 0x312108, - 0x2bc805, - 0x2cb603, - 0x2cb605, - 0x2da983, - 0x2162c2, - 0x383c84, - 0x2fc183, - 0x20cb42, - 0x341504, - 0x2ec043, - 0x206682, - 0x28cfc3, - 0x295384, - 0x2eae03, - 0x2f6584, - 0x204242, - 0x221383, - 0x219c43, - 0x206182, - 0x332182, - 0x2f0e09, - 0x204382, - 0x290d84, - 0x201f82, - 0x34d644, - 0x28bb04, - 0x2c0d84, - 0x202642, - 0x23e882, - 0x229703, - 0x302d83, - 0x24a9c4, - 0x28a404, - 0x2f1d44, - 0x2f8404, - 0x315743, - 0x224183, - 0x20c4c4, - 0x315584, - 0x315d86, - 0x232ec2, - 0x20f882, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x207102, - 0x39c783, - 0x238543, - 0x23cac3, - 0x201843, - 0x323043, - 0x231604, - 0x2f10c4, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x221483, - 0x2f5204, - 0x31fe83, - 0x2c37c3, - 0x359e44, - 0x39c286, - 0x211c43, - 0x36dc7, - 0x21f243, - 0x202103, - 0x2b8d83, - 0x263a43, - 0x229443, - 0x3321c5, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x216403, - 0x239043, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x255783, - 0x208e83, - 0x2464c4, - 0x1a3443, - 0x201a03, - 0x25b0c4, - 0x2c6c85, - 0x36dc7, - 0x20f882, - 0x201742, - 0x207b02, - 0x204d42, - 0xe03, + 0x16f02, + 0x1282, + 0x4042, + 0xed42, + 0x2a82, + 0xc842, + 0x4182, + 0x1f8c5, + 0x582009c2, + 0x587696c3, + 0x1fbc3, + 0x58a009c2, + 0x1fbc3, + 0x179487, + 0x215383, + 0x200742, + 0x20be03, + 0x237583, + 0x203d43, + 0x201fc3, + 0x20be83, + 0x20ec83, + 0x20ae43, + 0x241d03, + 0x294a83, + 0x10ec3, + 0xcd588, + 0x20be03, + 0x237583, + 0x203d43, + 0x21f743, + 0x20ec83, + 0x20ae43, + 0xaff03, + 0x241d03, + 0x20be03, + 0x237583, + 0x241d03, + 0x20be03, + 0x237583, + 0x30e843, + 0x200541, + 0x21f743, + 0x20ec83, + 0x228803, + 0x241d03, + 0x3744, + 0x2b6c03, + 0x20be03, + 0x237583, + 0x21f6c3, + 0x203d43, + 0x257e43, + 0x26b143, + 0x2a2c83, + 0x280e83, + 0x30e843, + 0x26ff84, + 0x20ec83, + 0x241d03, + 0x203f83, + 0x31e084, + 0x250b03, + 0x5583, + 0x22d443, + 0x332388, + 0x325384, + 0x2023ca, + 0x238f06, + 0x10a904, + 0x37a147, + 0x22174a, + 0x21dd89, + 0x3ade07, + 0x3b628a, + 0x2b6c03, + 0x2d750b, + 0x293609, + 0x201bc5, + 0x34e347, + 0x2c42, + 0x20be03, + 0x214447, + 0x2fb145, + 0x2f2a09, + 0x237583, + 0x306a86, + 0x2c0c03, + 0xeae83, + 0x107f06, + 0x122746, + 0x13747, + 0x2176c6, + 0x227045, + 0x39e607, + 0x2d2107, + 0x5b30e843, + 0x33c8c7, + 0x371fc3, + 0x20fb85, + 0x26ff84, + 0x26ed48, + 0x36a50c, + 0x2ad885, + 0x2a2886, + 0x214307, + 0x345847, + 0x252e47, + 0x254d08, + 0x30600f, + 0x3371c5, + 0x246e07, + 0x37c407, + 0x2a424a, + 0x2cebc9, + 0x308045, + 0x30b7ca, + 0x136686, + 0x2c0c85, + 0x36c104, + 0x2bdf86, + 0x2f1a47, + 0x382947, + 0x348748, + 0x21b545, + 0x2fb046, + 0x21d105, + 0x36dd45, + 0x289684, + 0x326bc7, + 0x2eb24a, + 0x23fc48, + 0x366446, + 0xbe83, + 0x2d8345, + 0x318a86, + 0x3b4e86, + 0x34a246, + 0x21f743, + 0x399787, + 0x37c385, + 0x20ec83, + 0x2d58cd, + 0x20ae43, + 0x348848, + 0x38c844, + 0x275b05, + 0x2a4146, + 0x23d186, + 0x355b07, + 0x204a07, + 0x289085, + 0x241d03, + 0x3268c7, + 0x3650c9, + 0x340a49, + 0x30dc0a, + 0x249a82, + 0x20fb44, + 0x2de284, + 0x349b07, + 0x398208, + 0x2e4f89, + 0x221a49, + 0x2e5dc7, + 0x35c346, + 0xe8346, + 0x2e9484, + 0x2e9a8a, + 0x2edc08, + 0x2efc09, + 0x2de106, + 0x2b1985, + 0x23fb08, + 0x2c358a, + 0x2b5d83, + 0x31e206, + 0x2e5ec7, + 0x2311c5, + 0x38c705, + 0x3a26c3, + 0x2702c4, + 0x22b985, + 0x282ac7, + 0x2ff185, + 0x337c86, + 0x14aa05, + 0x2a3203, + 0x3b8a09, + 0x2758cc, + 0x2ca74c, + 0x2cbb08, + 0x2baec7, + 0x2fbc08, + 0x2fc24a, + 0x2fcc4b, + 0x293748, + 0x23c908, + 0x23d286, + 0x201985, + 0x320fca, + 0x369705, + 0x20e982, + 0x3c0507, + 0x261146, + 0x367405, + 0x36b749, + 0x277385, + 0x36d785, + 0x35c909, + 0x3189c6, + 0x3b6988, + 0x20fc43, + 0x217806, + 0x274c46, + 0x30a485, + 0x30a489, + 0x2e56c9, + 0x251b47, + 0x10c984, + 0x30c987, + 0x221949, + 0x23d605, + 0x40788, + 0x346245, + 0x332285, + 0x3c1309, + 0x203402, + 0x250904, + 0x203c82, + 0x205842, + 0x3c0d85, + 0x30a688, + 0x2b7c05, + 0x2c2483, + 0x2c2485, + 0x2ce1c3, + 0x20ff02, + 0x208f84, + 0x2c7d03, + 0x206f02, + 0x340484, + 0x2def43, + 0x204882, + 0x21fc43, + 0x28cb84, + 0x2f01c3, + 0x256784, + 0x200a02, + 0x219443, + 0x21d403, + 0x206a42, + 0x2f4682, + 0x2e5509, + 0x20ad42, + 0x2889c4, 0x200442, - 0x238543, - 0x240244, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x21bf84, - 0x208e83, - 0xe03, - 0x201a03, - 0x215443, - 0x286644, - 0x16fb88, - 0x238543, - 0x200e03, - 0x10c3, - 0x13e8c4, - 0x252044, - 0x16fb88, - 0x238543, - 0x253384, - 0x231604, - 0x200e03, - 0x2014c2, - 0x201a03, - 0x20c843, - 0x31944, - 0x355685, - 0x205082, - 0x3156c3, - 0x145c49, - 0xdfb46, - 0x19c588, - 0x207102, - 0x16fb88, - 0x20f882, - 0x23cac3, - 0x323043, - 0x200942, - 0xe03, - 0x201a03, - 0x207102, - 0x1bea07, - 0x1370c9, - 0x3dc3, - 0x16fb88, - 0xd303, - 0x5db4c807, - 0x38543, - 0x1788, - 0x23cac3, - 0x323043, - 0x186c46, - 0x255783, - 0xe8888, - 0xc9148, - 0x3fbc6, - 0x28cac3, - 0xd30c8, - 0x187ec3, - 0xe8a85, - 0x3ccc7, - 0x8e83, - 0x63c3, - 0x1a03, - 0xcb02, - 0x17044a, - 0x10ea43, - 0x313e44, - 0x10f30b, - 0x10f8c8, - 0x95e02, - 0x207102, - 0x20f882, - 0x238543, - 0x23cac3, - 0x2de944, - 0x323043, - 0x255783, - 0x28cac3, - 0x208e83, - 0x238543, - 0x23cac3, - 0x323043, - 0x229443, - 0x208e83, - 0x201a03, - 0x236903, - 0x215443, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x10c3, - 0x238543, - 0x23cac3, - 0x323043, - 0x231604, - 0x229443, - 0x208e83, - 0x201a03, - 0x21a902, - 0x200141, - 0x207102, - 0x200001, - 0x327e02, - 0x16fb88, - 0x224c85, - 0x2008c1, - 0x38543, - 0x201781, + 0x23f984, + 0x35c304, + 0x287304, + 0x204182, + 0x23c542, + 0x3295c3, + 0x23b943, + 0x24d644, + 0x2b5c04, + 0x2eddc4, + 0x30b6c4, + 0x309043, + 0x335a83, + 0x336604, + 0x30eac4, + 0x30f306, + 0x2145c2, + 0x202c42, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x200742, + 0x2b6c03, + 0x20be03, + 0x237583, + 0x201b03, + 0x30e843, + 0x26ff84, + 0x2e57c4, + 0x226444, + 0x20ec83, + 0x241d03, + 0x219543, + 0x2ea0c4, + 0x31a803, + 0x2a6503, + 0x36aac4, + 0x346046, + 0x20b583, + 0x15da87, + 0x22fac3, + 0x21e903, + 0x2b0c43, + 0x20fbc3, + 0x20be83, + 0x339d45, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x210e03, + 0x2333c3, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x214bc3, + 0x20ec83, + 0x238184, + 0xaff03, + 0x241d03, + 0x209944, + 0x2bdd85, + 0x15da87, + 0x202c42, + 0x209d42, + 0x202542, + 0x2032c2, + 0xae43, + 0x200342, + 0x20be03, + 0x23d744, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x226444, + 0x20ec83, + 0xae43, + 0x241d03, + 0x207c03, + 0x28b304, + 0xcd588, + 0x20be03, + 0x20ae43, + 0x10ec3, + 0x13b5c4, + 0x253404, + 0xcd588, + 0x20be03, + 0x254a04, + 0x26ff84, + 0x20ae43, + 0x2056c2, + 0x241d03, + 0x24f3c3, + 0x702c4, + 0x2f5805, + 0x20e982, + 0x30ec03, + 0xf89, + 0xd3686, + 0xfcc8, + 0x200742, + 0xcd588, + 0x202c42, + 0x237583, + 0x30e843, + 0x201342, + 0xae43, + 0x241d03, + 0x200742, + 0x1b6447, + 0x11c889, + 0x5483, + 0xcd588, + 0x1226c3, + 0x5f33d587, + 0xbe03, + 0x1c6548, + 0x237583, + 0x30e843, + 0x178d46, + 0x214bc3, + 0x5b388, + 0xc0248, + 0x40e06, + 0x21f743, + 0xc6788, + 0x97c03, + 0xdbd45, + 0x37787, + 0xec83, + 0x6c83, + 0x41d03, + 0x4bc2, + 0x16c18a, + 0x1c0e43, + 0x30c5c4, + 0x105e0b, + 0x1063c8, + 0x8d302, + 0x200742, + 0x202c42, + 0x20be03, + 0x237583, + 0x2d2484, + 0x30e843, + 0x214bc3, + 0x21f743, + 0x20ec83, + 0x20be03, + 0x237583, + 0x30e843, + 0x20be83, + 0x20ec83, + 0x241d03, + 0x209943, + 0x207c03, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x10ec3, + 0x20be03, + 0x237583, + 0x30e843, + 0x26ff84, + 0x20be83, + 0x20ec83, + 0x241d03, + 0x230882, + 0x200101, + 0x200742, 0x200301, - 0x200081, - 0x2ac602, - 0x37cc44, - 0x394483, - 0x200181, - 0x200401, + 0x32a782, + 0xcd588, + 0x21fe85, + 0x200781, + 0xbe03, + 0x2014c1, 0x200041, - 0x200101, - 0x2ea547, - 0x2ec54f, - 0x2fbc06, - 0x200281, - 0x33e906, - 0x200801, - 0x200981, - 0x306f8e, - 0x200441, - 0x201a03, - 0x204101, - 0x258885, - 0x20cb02, - 0x3a03c5, + 0x200141, + 0x24e082, + 0x378184, + 0x24e083, + 0x201401, + 0x200901, + 0x200541, + 0x200a81, + 0x316307, + 0x337dcf, + 0x2fa486, + 0x200641, + 0x33b606, + 0x200081, + 0x2001c1, + 0x3c35ce, 0x200341, - 0x200741, + 0x241d03, + 0x201681, + 0x254285, + 0x204bc2, + 0x3a25c5, 0x2002c1, - 0x205082, - 0x2000c1, - 0x200201, - 0x200c81, - 0x2005c1, - 0x204541, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x221f43, - 0x238543, - 0x323043, - 0x95d48, - 0x28cac3, - 0x208e83, - 0x31483, - 0x201a03, - 0x14eec08, - 0x16308, - 0x16fb88, - 0xe03, - 0x8e444, - 0x4ec04, - 0x14eec0a, - 0x16fb88, - 0x1a3443, - 0x238543, - 0x23cac3, - 0x323043, - 0x208e83, - 0x201a03, - 0x203ec3, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x2de944, - 0x201a03, - 0x22d585, - 0x35f2c4, - 0x238543, - 0x208e83, - 0x201a03, - 0x1f40a, - 0xf1844, - 0x118b06, - 0x20f882, - 0x238543, - 0x23adc9, - 0x23cac3, - 0x375449, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x2f4348, - 0x22dc07, - 0x355685, - 0xb4c8, - 0x1bea07, - 0x2f78a, - 0x178ccb, - 0x13c507, - 0x4a4c8, - 0x14f64a, - 0x19dc8, - 0x1370c9, - 0x30507, - 0x742c7, - 0x19bf08, - 0x1788, - 0x4b04f, - 0x1c045, - 0x1a87, - 0x186c46, - 0x41287, - 0x4a786, - 0xe8888, - 0x96fc6, - 0x188847, - 0x178809, - 0x1bf307, - 0xd81c9, - 0xbcbc9, - 0xc6a06, - 0xc9148, - 0xc7845, - 0x57b0a, - 0xd30c8, - 0x187ec3, - 0xdad48, - 0x3ccc7, - 0x131f45, - 0x787d0, - 0x63c3, - 0x1a3443, - 0x125807, - 0x1cc85, - 0xf02c8, - 0xe385, - 0x10ea43, - 0x16d5c8, - 0x12906, - 0x198909, - 0xb2007, - 0x145f0b, - 0x180884, - 0x104f04, - 0x10f30b, - 0x10f8c8, - 0x110547, - 0x131645, - 0x238543, - 0x23cac3, - 0x21b583, - 0x201a03, + 0x200a01, + 0x200401, + 0x20e982, + 0x200441, + 0x203f81, + 0x20d601, + 0x201181, + 0x200dc1, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x21a003, + 0x20be03, + 0x30e843, + 0x8d248, + 0x21f743, + 0x20ec83, + 0x5e8c3, + 0x241d03, + 0x14e0f48, + 0x10d08, + 0xcd588, + 0xae43, + 0x24704, + 0x4cec4, + 0x14e0f4a, + 0xcd588, + 0xaff03, + 0x20be03, + 0x237583, + 0x30e843, + 0x20ec83, + 0x241d03, + 0x205583, + 0xcd588, + 0x20be03, + 0x237583, + 0x2d2484, + 0x241d03, + 0x252385, + 0x317c44, + 0x20be03, + 0x20ec83, + 0x241d03, + 0x2fc8a, + 0xfd504, + 0x112a46, + 0x202c42, + 0x20be03, + 0x234d09, + 0x237583, + 0x2a82c9, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x2e9288, + 0x397b87, + 0x2f5805, + 0x1b7888, + 0x1b6447, + 0x19848a, + 0x101d0b, + 0x13b847, + 0x45388, + 0x3a80a, + 0x13dc8, + 0x11c889, + 0x2b847, + 0x67fc7, + 0x1c28c8, + 0x1c6548, + 0x470cf, + 0x26505, + 0x1c6847, + 0x178d46, + 0x4c207, + 0x108186, + 0x5b388, + 0x9b986, + 0x1187c7, + 0x142349, + 0x1b5207, + 0xe68c9, + 0xb8209, + 0xbdb06, + 0xc0248, + 0xbeb45, + 0x77fca, + 0xc6788, + 0x97c03, + 0xcea08, + 0x37787, + 0x1ac045, + 0x4dc90, + 0x6c83, + 0xaff03, + 0x1c3147, + 0x1d5c5, + 0xe4308, + 0x605c5, + 0x1c0e43, + 0x142748, + 0x132146, + 0x199bc9, + 0xaab87, + 0x124b, + 0x137a84, + 0xfe3c4, + 0x105e0b, + 0x1063c8, + 0x107e07, + 0x117485, + 0x20be03, + 0x237583, + 0x203d43, + 0x241d03, + 0x244a03, + 0x30e843, + 0xaff03, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x7e24b, + 0x200742, + 0x202c42, + 0x241d03, + 0xcd588, + 0x200742, + 0x202c42, + 0x202542, + 0x201342, + 0x200b82, + 0x20ec83, + 0x200342, + 0x200742, + 0x2b6c03, + 0x202c42, + 0x20be03, + 0x237583, + 0x202542, + 0x30e843, + 0x214bc3, + 0x21f743, + 0x226444, + 0x20ec83, + 0x207783, + 0x241d03, + 0x30c5c4, + 0x203f83, + 0x30e843, + 0x202c42, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x20ae43, + 0x241d03, + 0x3afd87, + 0x20be03, + 0x279947, + 0x2e6686, + 0x216543, + 0x208883, + 0x30e843, + 0x204d03, + 0x26ff84, + 0x38b344, + 0x2b9906, 0x20c743, - 0x323043, - 0x1a3443, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x15d4cb, - 0x207102, - 0x20f882, - 0x201a03, - 0x16fb88, - 0x207102, - 0x20f882, - 0x207b02, - 0x200942, - 0x20b302, - 0x208e83, - 0x200442, - 0x207102, - 0x39c783, - 0x20f882, - 0x238543, - 0x23cac3, - 0x207b02, - 0x323043, - 0x255783, - 0x28cac3, - 0x21bf84, - 0x208e83, - 0x21eb43, - 0x201a03, - 0x313e44, - 0x202443, - 0x323043, - 0x20f882, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x200e03, - 0x201a03, - 0x3ad3c7, - 0x238543, - 0x282c07, - 0x2d7f86, - 0x20e583, - 0x207603, - 0x323043, - 0x204c03, - 0x231604, - 0x2d5204, - 0x30e706, - 0x20bd43, - 0x208e83, - 0x201a03, - 0x22d585, - 0x321704, - 0x350503, - 0x39b4c3, - 0x2cbd87, - 0x342d45, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x99807, - 0x203402, - 0x28f283, - 0x205403, - 0x39c783, - 0x65e38543, - 0x206902, - 0x23cac3, - 0x2020c3, - 0x323043, - 0x231604, - 0x3797c3, - 0x2e3b03, - 0x28cac3, - 0x21bf84, - 0x6620ea42, - 0x208e83, - 0x201a03, - 0x206683, - 0x22e603, - 0x21a902, - 0x202443, - 0x16fb88, - 0x323043, - 0x10c3, - 0x31f944, - 0x39c783, - 0x20f882, - 0x238543, - 0x240244, - 0x23cac3, - 0x323043, - 0x231604, - 0x255783, - 0x3a2e44, - 0x20f644, - 0x20c0c6, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x221483, - 0x29f806, - 0x4504b, - 0x24386, - 0x3204a, - 0x112d0a, - 0x16fb88, - 0x214f44, - 0x67638543, - 0x39c744, - 0x23cac3, - 0x259004, - 0x323043, - 0x210543, - 0x28cac3, - 0x208e83, - 0x1a3443, - 0x201a03, - 0xbac3, - 0x3381cb, - 0x3af10a, - 0x3bf84c, - 0xe4288, - 0x207102, - 0x20f882, - 0x207b02, - 0x2b13c5, - 0x231604, - 0x204a82, - 0x28cac3, - 0x20f644, - 0x204d42, - 0x200442, - 0x20d2c2, - 0x21a902, - 0x19c783, - 0x35f42, - 0x2b3509, - 0x2f7148, - 0x351689, - 0x2410c9, - 0x350f0a, - 0x26080a, - 0x2127c2, - 0x222902, - 0xf882, - 0x238543, - 0x229682, - 0x24af46, - 0x369d02, - 0x206a42, - 0x37904e, - 0x2213ce, - 0x284b47, - 0x208e07, - 0x2ec8c2, - 0x23cac3, - 0x323043, - 0x200042, - 0x200942, - 0x31603, - 0x23980f, - 0x20b542, - 0x2dd887, - 0x2b4a87, - 0x2b7e87, - 0x31a4cc, - 0x2c448c, - 0x223984, - 0x285b0a, - 0x221302, - 0x209a02, - 0x2c0884, - 0x21f502, - 0x2ca102, - 0x2c46c4, - 0x21a602, - 0x200282, - 0x11a83, - 0x297047, - 0x2beb05, - 0x20d842, - 0x239784, - 0x382842, - 0x2e3008, - 0x208e83, - 0x203488, - 0x203cc2, - 0x223b45, - 0x38dbc6, - 0x201a03, - 0x207082, - 0x2f0ac7, - 0xcb02, - 0x2797c5, - 0x358b85, - 0x209642, - 0x20fd02, - 0x2cf9ca, - 0x26eeca, - 0x21b9c2, - 0x2a4dc4, - 0x2002c2, - 0x3b4ec8, - 0x20d582, - 0x315b08, - 0x30ab47, - 0x30ba09, - 0x203442, - 0x310e45, - 0x3044c5, - 0x21770b, - 0x2d054c, - 0x237348, - 0x321b08, - 0x232ec2, - 0x208a02, - 0x207102, - 0x16fb88, - 0x20f882, - 0x238543, - 0x207b02, - 0x204d42, - 0xe03, - 0x200442, - 0x201a03, - 0x20d2c2, - 0x207102, - 0x68a0f882, - 0x68f23043, - 0x211a83, - 0x204a82, - 0x208e83, - 0x391783, - 0x201a03, - 0x2ef783, - 0x37f186, - 0x1615443, - 0x16fb88, - 0x11205, - 0xae90d, - 0xacc8a, - 0x6e487, - 0x69601e02, - 0x69a00242, - 0x69e00bc2, - 0x6a200702, - 0x6a60b5c2, - 0x6aa01382, - 0x36dc7, - 0x6ae0f882, - 0x6b20c8c2, - 0x6b604842, - 0x6ba04c82, - 0x2213c3, - 0x18ec4, - 0x2298c3, - 0x6be1d882, - 0x6c200182, - 0x53c47, - 0x6c60a442, - 0x6ca00782, - 0x6ce01bc2, - 0x6d205e82, - 0x6d601c82, - 0x6da00942, - 0xc2845, - 0x23ef43, - 0x281a04, - 0x6de1f502, - 0x6e205242, - 0x6e603582, - 0x17d50b, - 0x6ea01fc2, - 0x6f253442, - 0x6f604a82, - 0x6fa0b302, - 0x6fe14702, - 0x70200802, - 0x70614642, - 0x70a745c2, - 0x70e0ea42, - 0x71204802, - 0x71604d42, - 0x71a03382, - 0x71e08682, - 0x7224d382, - 0x1a3284, - 0x35efc3, - 0x72604f82, - 0x72a10902, - 0x72e11542, - 0x73201f02, - 0x73600442, - 0x73a0cb42, - 0x15d647, - 0x73e04102, - 0x74204142, - 0x7460d2c2, - 0x74a21382, - 0x1ad70c, - 0x74e2a202, - 0x75245542, - 0x75605942, - 0x75a06442, - 0x75e0c402, - 0x76260982, - 0x76600202, - 0x76a16fc2, - 0x76e7d302, - 0x772610c2, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x12143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x6ef797c3, - 0x212143, - 0x332244, - 0x2f7046, - 0x2f9a03, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x244949, - 0x235f42, - 0x26c783, - 0x2bcec3, - 0x20fbc5, - 0x2020c3, - 0x3797c3, - 0x212143, + 0x20ec83, + 0x241d03, + 0x252385, + 0x309e84, + 0x320dc3, + 0x20d203, + 0x3c0507, + 0x23b1c5, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x98747, + 0x2149c2, + 0x26e443, + 0x20df43, + 0x2b6c03, + 0x6760be03, + 0x20b2c2, + 0x237583, + 0x206c03, + 0x30e843, + 0x26ff84, + 0x3c32c3, + 0x3371c3, + 0x21f743, + 0x226444, + 0x67a02f02, + 0x20ec83, + 0x241d03, + 0x235cc3, + 0x214c43, + 0x230882, + 0x203f83, + 0xcd588, + 0x30e843, + 0x10ec3, + 0x31b0c4, + 0x2b6c03, + 0x202c42, + 0x20be03, + 0x23d744, + 0x237583, + 0x30e843, + 0x26ff84, + 0x214bc3, + 0x39e304, + 0x21a484, + 0x2d0e06, + 0x226444, + 0x20ec83, + 0x241d03, + 0x219543, + 0x261146, + 0x4170b, + 0x29546, + 0xeb94a, + 0x10b34a, + 0xcd588, + 0x21d0c4, + 0x68e0be03, + 0x2b6bc4, + 0x237583, + 0x268984, + 0x30e843, + 0x357d43, + 0x21f743, + 0x20ec83, + 0xaff03, + 0x241d03, + 0x55a43, + 0x33840b, + 0x3b1a0a, + 0x3c580c, + 0xd80c8, + 0x200742, + 0x202c42, + 0x202542, + 0x232585, + 0x26ff84, + 0x201e42, + 0x21f743, + 0x21a484, + 0x2032c2, + 0x200342, + 0x207c02, + 0x230882, + 0xb6c03, + 0x4d5c2, + 0x386389, + 0x3a3088, + 0x310449, + 0x34e049, + 0x23e48a, + 0x24e90a, + 0x219382, + 0x2efa02, + 0x2c42, + 0x20be03, + 0x230a42, + 0x246fc6, + 0x368802, + 0x207582, + 0x30208e, + 0x21948e, + 0x27bf47, + 0x20ec07, + 0x2e89c2, + 0x237583, + 0x30e843, + 0x209182, + 0x201342, + 0x6ff83, + 0x23d94f, + 0x247302, + 0x2f9507, + 0x2ad447, + 0x314407, + 0x2b0fcc, + 0x2b9b8c, + 0x207144, + 0x27d34a, + 0x2193c2, + 0x209602, + 0x2b9844, + 0x2028c2, + 0x2c10c2, + 0x2b9dc4, + 0x217f42, + 0x201542, + 0xf003, + 0x29ba07, + 0x233805, + 0x20e302, + 0x24c184, + 0x37c0c2, + 0x2d7c88, + 0x20ec83, + 0x39f108, + 0x206a82, + 0x207305, + 0x388206, + 0x241d03, + 0x208302, + 0x2e51c7, + 0x4bc2, + 0x272585, + 0x204905, + 0x212182, + 0x2030c2, + 0x293c0a, + 0x288f0a, + 0x23a382, + 0x29a184, + 0x2040c2, + 0x20fa08, + 0x200d82, + 0x39d588, + 0x302ac7, + 0x3038c9, + 0x204982, + 0x3086c5, + 0x36ba05, + 0x21b60b, + 0x2c418c, + 0x230548, + 0x31c188, + 0x2145c2, + 0x355bc2, + 0x200742, + 0xcd588, + 0x202c42, + 0x20be03, + 0x202542, + 0x2032c2, + 0xae43, + 0x200342, + 0x241d03, + 0x207c02, + 0x200742, + 0x6a202c42, + 0x6a70e843, + 0x20f003, + 0x201e42, + 0x20ec83, + 0x338c03, + 0x241d03, + 0x2e2d83, + 0x379586, + 0x1607c03, + 0xcd588, + 0x6e247, + 0x14a345, + 0xa7e0d, + 0xa5f4a, + 0x85047, + 0x6ae00a42, + 0x6b200602, + 0x6b600282, + 0x6ba02b82, + 0x6be12442, + 0x6c203cc2, + 0x15da87, + 0x6c602c42, + 0x6ca1b282, + 0x6ce1f9c2, + 0x6d202e02, + 0x219483, + 0x22644, + 0x282dc3, + 0x6d615902, + 0x6da039c2, + 0x55087, + 0x6de02202, + 0x6e200902, + 0x6e600542, + 0x6ea07d02, + 0x6ee03882, + 0x6f201342, + 0xc0f85, + 0x24c4c3, + 0x23a2c4, + 0x6f6028c2, + 0x6fa0dd82, + 0x6fe00682, + 0xb714b, + 0x702000c2, + 0x70a54ac2, + 0x70e01e42, + 0x71200b82, + 0x71603282, + 0x71a05a02, + 0x71e0d682, + 0x7226cd82, + 0x72602f02, + 0x72a04d42, + 0x72e032c2, + 0x7323e0c2, + 0x7362a402, + 0x73a11e82, + 0xafd44, + 0x339b43, + 0x73e0e882, + 0x742190c2, + 0x74606482, + 0x74a02882, + 0x74e00342, + 0x75206f02, + 0x7e3c7, + 0x756057c2, + 0x75a00502, + 0x75e07c02, + 0x76209f82, + 0xf778c, + 0x76627882, + 0x76a2c0c2, + 0x76e0a902, + 0x77206d02, + 0x77611d82, + 0x77a3e602, + 0x77e0fc42, + 0x78213802, + 0x78674fc2, + 0x78a4f1c2, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x11343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x707c32c3, + 0x211343, + 0x339dc4, + 0x3a2f86, + 0x2f0ec3, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x200189, + 0x24d5c2, + 0x391283, + 0x2b8503, + 0x202f85, + 0x206c03, + 0x3c32c3, + 0x211343, + 0x29ea43, + 0x233d43, + 0x3bd849, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x24d5c2, + 0x24d5c2, + 0x3c32c3, + 0x211343, + 0x7920be03, + 0x237583, + 0x332683, + 0x21f743, + 0x20ec83, + 0xae43, + 0x241d03, + 0xcd588, + 0x202c42, + 0x20be03, + 0x20ec83, + 0x241d03, + 0x20be03, + 0x237583, + 0x30e843, + 0x21f743, + 0x20ec83, + 0xae43, + 0x241d03, + 0x253404, + 0x202c42, + 0x20be03, + 0x322183, + 0x237583, + 0x254a04, + 0x203d43, + 0x30e843, + 0x26ff84, + 0x214bc3, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x24f3c3, + 0x2f5805, + 0x233d43, + 0x203f83, + 0xae43, + 0x202c42, + 0x20be03, + 0x3c32c3, + 0x20ec83, + 0x241d03, + 0x200742, + 0x2b6c03, + 0xcd588, + 0x20be03, + 0x237583, + 0x30e843, + 0x234106, + 0x26ff84, + 0x214bc3, + 0x226444, + 0x20ec83, + 0x241d03, + 0x219543, + 0x20be03, + 0x237583, + 0x20ec83, + 0x241d03, + 0x144be47, + 0x20be03, + 0x29546, + 0x237583, + 0x30e843, + 0xd91c6, + 0x20ec83, + 0x241d03, + 0x318fc8, + 0x31bfc9, + 0x330349, + 0x33af08, + 0x38a348, + 0x38a349, + 0x22c10d, + 0x24b00f, + 0x2ec510, + 0x354d0d, + 0x36ebcc, + 0x38bc4b, + 0xaf148, + 0xc7bc5, + 0x200742, + 0x23b005, + 0x20bfc3, + 0x7c602c42, + 0x237583, + 0x30e843, + 0x2d7ac7, + 0x20fbc3, + 0x21f743, + 0x20ec83, + 0x228803, 0x20c0c3, - 0x248d43, - 0x242989, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x3797c3, - 0x212143, - 0x235f42, - 0x235f42, - 0x3797c3, - 0x212143, - 0x77a38543, - 0x23cac3, - 0x20a6c3, - 0x28cac3, - 0x208e83, - 0xe03, - 0x201a03, - 0x16fb88, - 0x20f882, - 0x238543, - 0x208e83, - 0x201a03, - 0x238543, - 0x23cac3, - 0x323043, - 0x28cac3, - 0x208e83, - 0xe03, - 0x201a03, - 0x252044, - 0x20f882, - 0x238543, - 0x345903, - 0x23cac3, - 0x253384, - 0x21b583, - 0x323043, - 0x231604, - 0x255783, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x20c843, - 0x355685, - 0x248d43, - 0x202443, - 0xe03, - 0x20f882, - 0x238543, - 0x3797c3, - 0x208e83, - 0x201a03, - 0x207102, - 0x39c783, - 0x16fb88, - 0x238543, - 0x23cac3, - 0x323043, - 0x23a1c6, - 0x231604, - 0x255783, - 0x21bf84, - 0x208e83, - 0x201a03, - 0x221483, - 0x238543, - 0x23cac3, - 0x208e83, - 0x201a03, - 0x1442047, - 0x238543, - 0x24386, - 0x23cac3, - 0x323043, - 0xe5586, - 0x208e83, - 0x201a03, - 0x31dc48, - 0x321949, - 0x330189, - 0x33bb08, - 0x38fb48, - 0x38fb49, - 0x24558d, - 0x24dd8f, - 0x2f53d0, - 0x35648d, - 0x37210c, - 0x39064b, - 0xba9c8, - 0xac605, - 0x207102, - 0x342b85, - 0x200243, - 0x7ae0f882, - 0x23cac3, - 0x323043, - 0x2d8c47, - 0x263a43, - 0x28cac3, - 0x208e83, - 0x21b543, - 0x217e03, - 0x200e03, - 0x201a03, - 0x3821c6, - 0x205082, - 0x202443, - 0x16fb88, - 0x207102, - 0x39c783, - 0x20f882, - 0x238543, - 0x23cac3, - 0x323043, - 0x231604, - 0x28cac3, - 0x208e83, - 0x201a03, - 0x215443, - 0x106904, - 0x15217c6, - 0x207102, - 0x20f882, - 0x323043, - 0x28cac3, - 0x201a03, + 0x20ae43, + 0x241d03, + 0x253786, + 0x20e982, + 0x203f83, + 0xcd588, + 0x200742, + 0x2b6c03, + 0x202c42, + 0x20be03, + 0x237583, + 0x30e843, + 0x26ff84, + 0x21f743, + 0x20ec83, + 0x241d03, + 0x207c03, + 0xf84, + 0x154ab06, + 0x200742, + 0x202c42, + 0x30e843, + 0x21f743, + 0x241d03, } // children is the list of nodes' children, the parent's wildcard bit and the @@ -8921,499 +9030,505 @@ var children = [...]uint32{ 0x40000000, 0x50000000, 0x60000000, - 0x186c615, - 0x187061b, - 0x189461c, - 0x19f0625, - 0x1a0467c, - 0x1a18681, - 0x1a2c686, - 0x1a4c68b, - 0x1a50693, - 0x1a68694, - 0x1a9069a, - 0x1a946a4, - 0x1aac6a5, - 0x1ab06ab, - 0x1ab46ac, - 0x1af06ad, - 0x1af46bc, - 0x21afc6bd, - 0x1b446bf, - 0x1b486d1, - 0x1b686d2, - 0x1b7c6da, - 0x1b806df, - 0x1bb06e0, - 0x1bcc6ec, - 0x1bf46f3, - 0x1c006fd, - 0x1c04700, - 0x1c9c701, + 0x185460f, + 0x1858615, + 0x187c616, + 0x19d861f, + 0x19ec676, + 0x1a0067b, + 0x1a14680, + 0x1a34685, + 0x1a3868d, + 0x1a5068e, + 0x1a78694, + 0x1a7c69e, + 0x1a9469f, + 0x1a986a5, + 0x1a9c6a6, + 0x1ad86a7, + 0x1adc6b6, + 0x21ae46b7, + 0x1b2c6b9, + 0x1b306cb, + 0x1b506cc, + 0x1b646d4, + 0x1b686d9, + 0x1b986da, + 0x1bb46e6, + 0x1bdc6ed, + 0x1bec6f7, + 0x1bf06fb, + 0x1c886fc, + 0x1c9c722, 0x1cb0727, - 0x1cc472c, - 0x1cf4731, - 0x1d0473d, - 0x1d18741, - 0x1d3c746, - 0x1e7474f, - 0x1e7879d, - 0x1ee479e, - 0x1f507b9, - 0x1f687d4, - 0x1f7c7da, - 0x1f847df, - 0x1f987e1, - 0x1f9c7e6, - 0x1fb87e7, - 0x20047ee, - 0x2020801, - 0x2024808, - 0x2028809, - 0x204480a, - 0x2080811, - 0x62084820, - 0x209c821, - 0x20b4827, - 0x20b882d, - 0x20c882e, - 0x2178832, - 0x217c85e, - 0x2218c85f, - 0x22190863, - 0x22194864, - 0x21cc865, - 0x21d0873, - 0x2658874, - 0x226f8996, - 0x226fc9be, - 0x227009bf, - 0x2270c9c0, - 0x227109c3, - 0x2271c9c4, - 0x227209c7, - 0x227249c8, - 0x227289c9, - 0x2272c9ca, - 0x227309cb, - 0x2273c9cc, - 0x227409cf, - 0x2274c9d0, - 0x227509d3, - 0x227549d4, - 0x227589d5, - 0x227649d6, - 0x227689d9, - 0x2276c9da, - 0x227709db, - 0x27749dc, - 0x227789dd, - 0x227849de, - 0x227889e1, - 0x27909e2, - 0x27cc9e4, - 0x227ec9f3, - 0x227f09fb, - 0x227f49fc, - 0x27f89fd, - 0x227fc9fe, - 0x28009ff, - 0x281ca00, - 0x2834a07, - 0x2838a0d, - 0x2848a0e, - 0x2854a12, - 0x2888a15, - 0x288ca22, - 0x28a0a23, - 0x228a8a28, - 0x2968a2a, - 0x2296ca5a, - 0x2974a5b, - 0x2978a5d, - 0x2990a5e, - 0x29a4a64, - 0x29cca69, - 0x29eca73, - 0x2a1ca7b, - 0x2a44a87, - 0x2a48a91, - 0x2a6ca92, - 0x2a70a9b, - 0x2a84a9c, - 0x2a88aa1, - 0x2a8caa2, - 0x2aacaa3, - 0x2ac8aab, - 0x2accab2, - 0x22ad0ab3, - 0x2ad4ab4, - 0x2ad8ab5, - 0x2ae8ab6, - 0x2aecaba, - 0x2b64abb, - 0x2b68ad9, - 0x2b84ada, - 0x2b94ae1, - 0x2ba8ae5, - 0x2bc0aea, - 0x2bd8af0, - 0x2bf0af6, - 0x2bf4afc, - 0x2c0cafd, - 0x2c28b03, - 0x2c48b0a, - 0x2c60b12, - 0x2cc0b18, - 0x2cdcb30, - 0x2ce4b37, - 0x2ce8b39, + 0x1ce072c, + 0x1cf0738, + 0x1d0473c, + 0x1da8741, + 0x1fa076a, + 0x1fa47e8, + 0x20107e9, + 0x207c804, + 0x209481f, + 0x20a8825, + 0x20b082a, + 0x20c482c, + 0x20c8831, + 0x20e4832, + 0x2134839, + 0x215084d, + 0x2154854, + 0x2158855, + 0x2174856, + 0x21b085d, + 0x621b486c, + 0x21cc86d, + 0x21e0873, + 0x21e4878, + 0x21f4879, + 0x22a487d, + 0x22a88a9, + 0x222b88aa, + 0x222bc8ae, + 0x222c08af, + 0x22f88b0, + 0x22fc8be, + 0x278c8bf, + 0x228349e3, + 0x22838a0d, + 0x2283ca0e, + 0x22848a0f, + 0x2284ca12, + 0x22858a13, + 0x2285ca16, + 0x22860a17, + 0x22864a18, + 0x22868a19, + 0x2286ca1a, + 0x22878a1b, + 0x2287ca1e, + 0x22888a1f, + 0x2288ca22, + 0x22890a23, + 0x22894a24, + 0x228a0a25, + 0x228a4a28, + 0x228b0a29, + 0x228b4a2c, + 0x228b8a2d, + 0x228bca2e, + 0x28c0a2f, + 0x228c4a30, + 0x228d0a31, + 0x228d4a34, + 0x28dca35, + 0x291ca37, + 0x2293ca47, + 0x22940a4f, + 0x22944a50, + 0x2948a51, + 0x2294ca52, + 0x2950a53, + 0x296ca54, + 0x2984a5b, + 0x2988a61, + 0x2998a62, + 0x29a4a66, + 0x29d8a69, + 0x29dca76, + 0x29f0a77, + 0x229f8a7c, + 0x2ab8a7e, + 0x22abcaae, + 0x2ac4aaf, + 0x2ac8ab1, + 0x2ae0ab2, + 0x2af4ab8, + 0x2b1cabd, + 0x2b3cac7, + 0x2b6cacf, + 0x2b94adb, + 0x2b98ae5, + 0x2bbcae6, + 0x2bc0aef, + 0x2bd4af0, + 0x2bd8af5, + 0x2bdcaf6, + 0x2bfcaf7, + 0x2c1caff, + 0x2c20b07, + 0x22c24b08, + 0x2c28b09, + 0x2c2cb0a, + 0x2c3cb0b, + 0x2c40b0f, + 0x2cb8b10, + 0x2cbcb2e, + 0x2cd8b2f, + 0x2ce8b36, 0x2cfcb3a, - 0x2d40b3f, - 0x2dc0b50, - 0x2decb70, - 0x2df0b7b, - 0x2df8b7c, - 0x2e18b7e, - 0x2e1cb86, - 0x2e40b87, - 0x2e48b90, - 0x2e84b92, - 0x2ec8ba1, - 0x2eccbb2, - 0x2f34bb3, - 0x2f38bcd, - 0x22f3cbce, - 0x22f40bcf, - 0x22f50bd0, - 0x22f54bd4, - 0x22f58bd5, - 0x22f5cbd6, - 0x22f60bd7, - 0x2f78bd8, - 0x2f9cbde, - 0x2fbcbe7, - 0x3580bef, - 0x358cd60, - 0x35acd63, - 0x3768d6b, - 0x3838dda, - 0x38a8e0e, - 0x3900e2a, - 0x39e8e40, - 0x3a40e7a, - 0x3a7ce90, - 0x3b78e9f, - 0x3c44ede, - 0x3cdcf11, - 0x3d6cf37, - 0x3dd0f5b, - 0x4008f74, - 0x40c1002, - 0x418d030, - 0x41d9063, - 0x4261076, - 0x429d098, - 0x42ed0a7, - 0x43650bb, - 0x643690d9, - 0x6436d0da, - 0x643710db, - 0x43ed0dc, - 0x44490fb, - 0x44c5112, - 0x453d131, - 0x45bd14f, - 0x462916f, - 0x475518a, - 0x47ad1d5, - 0x647b11eb, - 0x48491ec, - 0x48d1212, - 0x491d234, - 0x4985247, - 0x4a2d261, - 0x4af528b, - 0x4b5d2bd, - 0x4c712d7, - 0x64c7531c, - 0x64c7931d, - 0x4cd531e, - 0x4d31335, - 0x4dc134c, - 0x4e3d370, - 0x4e8138f, - 0x4f653a0, - 0x4f993d9, - 0x4ff93e6, - 0x506d3fe, - 0x50f541b, - 0x513543d, - 0x51a544d, - 0x651a9469, - 0x651ad46a, - 0x251b146b, - 0x51c946c, - 0x51e5472, - 0x5229479, - 0x523948a, - 0x525148e, - 0x52c9494, - 0x52d14b2, - 0x52e54b4, - 0x53014b9, - 0x532d4c0, - 0x53314cb, - 0x53394cc, - 0x534d4ce, + 0x2d14b3f, + 0x2d2cb45, + 0x2d44b4b, + 0x2d48b51, + 0x2d60b52, + 0x2d7cb58, + 0x2d9cb5f, + 0x2db4b67, + 0x2e14b6d, + 0x2e30b85, + 0x2e38b8c, + 0x2e3cb8e, + 0x2e50b8f, + 0x2e94b94, + 0x2f14ba5, + 0x2f40bc5, + 0x2f44bd0, + 0x2f4cbd1, + 0x2f6cbd3, + 0x2f70bdb, + 0x2f94bdc, + 0x2f9cbe5, + 0x2fd8be7, + 0x301cbf6, + 0x3020c07, + 0x3094c08, + 0x3098c25, + 0x2309cc26, + 0x230a0c27, + 0x230a4c28, + 0x230b4c29, + 0x230b8c2d, + 0x230bcc2e, + 0x230c0c2f, + 0x230c4c30, + 0x30dcc31, + 0x3100c37, + 0x3120c40, + 0x36e4c48, + 0x36f0db9, + 0x3710dbc, + 0x38ccdc4, + 0x399ce33, + 0x3a0ce67, + 0x3a64e83, + 0x3b4ce99, + 0x3ba4ed3, + 0x3be0ee9, + 0x3cdcef8, + 0x3da8f37, + 0x3e40f6a, + 0x3ed0f90, + 0x3f34fb4, + 0x416cfcd, + 0x422505b, + 0x42f1089, + 0x433d0bc, + 0x43c50cf, + 0x44010f1, + 0x4451100, + 0x44c9114, + 0x644cd132, + 0x644d1133, + 0x644d5134, + 0x4551135, + 0x45ad154, + 0x462916b, + 0x46a118a, + 0x47211a8, + 0x478d1c8, + 0x48b91e3, + 0x491122e, + 0x64915244, + 0x49ad245, + 0x4a3526b, + 0x4a8128d, + 0x4ae92a0, + 0x4b912ba, + 0x4c592e4, + 0x4cc1316, + 0x4dd5330, + 0x64dd9375, + 0x64ddd376, + 0x4e39377, + 0x4e9538e, + 0x4f253a5, + 0x4fa13c9, + 0x4fe53e8, + 0x50c93f9, + 0x50fd432, + 0x515d43f, + 0x51d1457, + 0x5259474, + 0x5299496, + 0x53094a6, + 0x6530d4c2, + 0x53314c3, + 0x53354cc, + 0x534d4cd, 0x53694d3, - 0x53754da, - 0x537d4dd, - 0x53b94df, - 0x53cd4ee, - 0x53d54f3, - 0x53e14f5, - 0x53e94f8, - 0x540d4fa, - 0x5431503, - 0x544950c, - 0x544d512, + 0x53ad4da, + 0x53bd4eb, + 0x53d54ef, + 0x544d4f5, 0x5455513, - 0x5459515, - 0x54c1516, - 0x54c5530, - 0x54e9531, - 0x550d53a, - 0x5529543, - 0x553954a, - 0x554d54e, - 0x5551553, + 0x5469515, + 0x548551a, + 0x54b1521, + 0x54b552c, + 0x54bd52d, + 0x54d152f, + 0x54ed534, + 0x54f953b, + 0x550153e, + 0x553d540, + 0x555154f, 0x5559554, - 0x556d556, - 0x557d55b, - 0x558155f, - 0x559d560, - 0x5e2d567, - 0x5e6578b, - 0x5e91799, - 0x5ead7a4, - 0x5ecd7ab, - 0x5eed7b3, - 0x5f317bb, - 0x5f397cc, - 0x25f3d7ce, - 0x25f417cf, - 0x5f497d0, - 0x60c17d2, + 0x5565556, + 0x556d559, + 0x559155b, + 0x55b5564, + 0x55cd56d, + 0x55d1573, + 0x55d9574, + 0x55dd576, + 0x5645577, + 0x5649591, + 0x566d592, + 0x569159b, + 0x56ad5a4, + 0x56bd5ab, + 0x56d15af, + 0x56d55b4, + 0x56dd5b5, + 0x56f15b7, + 0x57015bc, + 0x57055c0, + 0x57215c1, + 0x5fb15c8, + 0x5fe97ec, + 0x60157fa, + 0x6031805, + 0x605180c, + 0x6071814, + 0x60b581c, + 0x60bd82d, + 0x260c182f, 0x260c5830, - 0x260d5831, - 0x260dd835, - 0x260e9837, - 0x60ed83a, - 0x60f183b, - 0x611983c, - 0x6141846, - 0x6145850, - 0x617d851, - 0x619985f, - 0x6cf1866, - 0x6cf5b3c, - 0x6cf9b3d, - 0x26cfdb3e, - 0x6d01b3f, - 0x26d05b40, - 0x6d09b41, - 0x26d15b42, - 0x6d19b45, - 0x6d1db46, - 0x26d21b47, - 0x6d25b48, - 0x26d2db49, - 0x6d31b4b, - 0x6d35b4c, - 0x26d45b4d, - 0x6d49b51, - 0x6d4db52, - 0x6d51b53, - 0x6d55b54, - 0x26d59b55, - 0x6d5db56, - 0x6d61b57, - 0x6d65b58, - 0x6d69b59, - 0x26d71b5a, - 0x6d75b5c, - 0x6d79b5d, - 0x6d7db5e, - 0x26d81b5f, - 0x6d85b60, - 0x26d8db61, - 0x26d91b63, - 0x6dadb64, - 0x6dbdb6b, - 0x6e01b6f, - 0x6e05b80, - 0x6e29b81, - 0x6e2db8a, - 0x6e31b8b, - 0x6fbdb8c, - 0x26fc1bef, - 0x26fc9bf0, - 0x26fcdbf2, - 0x26fd1bf3, - 0x6fd9bf4, - 0x70b5bf6, - 0x270b9c2d, - 0x70bdc2e, - 0x70e9c2f, - 0x70edc3a, - 0x7111c3b, - 0x711dc44, - 0x713dc47, - 0x7141c4f, - 0x7179c50, - 0x7411c5e, - 0x74cdd04, - 0x74e1d33, - 0x7515d38, - 0x7545d45, - 0x7561d51, - 0x7589d58, - 0x75a9d62, - 0x75c5d6a, - 0x75edd71, - 0x75fdd7b, - 0x7601d7f, - 0x7605d80, - 0x7639d81, - 0x7645d8e, - 0x7665d91, - 0x76ddd99, - 0x276e1db7, - 0x7705db8, - 0x7725dc1, - 0x7739dc9, - 0x774ddce, - 0x7751dd3, - 0x7771dd4, - 0x7815ddc, - 0x7831e05, - 0x7855e0c, - 0x785de15, - 0x7869e17, - 0x7871e1a, - 0x7885e1c, - 0x78a5e21, - 0x78b1e29, - 0x78bde2c, - 0x78ede2f, - 0x79c1e3b, - 0x79c5e70, - 0x79d9e71, - 0x79e1e76, - 0x79f9e78, - 0x79fde7e, - 0x7a09e7f, - 0x7a0de82, - 0x7a29e83, - 0x7a65e8a, - 0x7a69e99, - 0x7a89e9a, - 0x7ad9ea2, - 0x7af5eb6, - 0x7b49ebd, - 0x7b4ded2, - 0x7b51ed3, - 0x7b55ed4, - 0x7b99ed5, - 0x7ba9ee6, - 0x7be9eea, - 0x7bedefa, - 0x7c1defb, - 0x7d65f07, - 0x7d8df59, - 0x7db9f63, - 0x7dc5f6e, - 0x7dcdf71, - 0x7eddf73, - 0x7ee9fb7, - 0x7ef5fba, - 0x7f01fbd, - 0x7f0dfc0, - 0x7f19fc3, - 0x7f25fc6, - 0x7f31fc9, - 0x7f3dfcc, - 0x7f49fcf, - 0x7f55fd2, - 0x7f61fd5, - 0x7f6dfd8, - 0x7f79fdb, - 0x7f81fde, - 0x7f8dfe0, - 0x7f99fe3, - 0x7fa5fe6, - 0x7fb1fe9, - 0x7fbdfec, - 0x7fc9fef, - 0x7fd5ff2, - 0x7fe1ff5, - 0x7fedff8, - 0x7ff9ffb, - 0x8005ffe, - 0x8032001, - 0x803e00c, - 0x804a00f, - 0x8056012, - 0x8062015, - 0x806e018, - 0x807601b, - 0x808201d, - 0x808e020, - 0x809a023, - 0x80a6026, - 0x80b2029, - 0x80be02c, - 0x80ca02f, - 0x80d6032, - 0x80e2035, - 0x80ee038, - 0x80fa03b, - 0x810603e, - 0x8112041, - 0x811a044, - 0x8126046, - 0x8132049, - 0x813e04c, - 0x814a04f, - 0x8156052, - 0x8162055, - 0x816e058, - 0x817a05b, - 0x817e05e, - 0x818a05f, - 0x81a6062, - 0x81aa069, - 0x81ba06a, - 0x81d606e, - 0x821a075, - 0x821e086, - 0x8232087, - 0x826608c, - 0x8276099, - 0x829609d, - 0x82ae0a5, - 0x82c60ab, - 0x82ce0b1, - 0x283120b3, - 0x83160c4, - 0x83420c5, - 0x834a0d0, - 0x835e0d2, + 0x60cd831, + 0x6245833, + 0x26249891, + 0x26259892, + 0x26261896, + 0x2626d898, + 0x627189b, + 0x627589c, + 0x629d89d, + 0x62c58a7, + 0x62c98b1, + 0x63018b2, + 0x63218c0, + 0x6e798c8, + 0x6e7db9e, + 0x6e81b9f, + 0x26e85ba0, + 0x6e89ba1, + 0x26e8dba2, + 0x6e91ba3, + 0x26e9dba4, + 0x6ea1ba7, + 0x6ea5ba8, + 0x26ea9ba9, + 0x6eadbaa, + 0x26eb5bab, + 0x6eb9bad, + 0x6ebdbae, + 0x26ecdbaf, + 0x6ed1bb3, + 0x6ed5bb4, + 0x6ed9bb5, + 0x6eddbb6, + 0x26ee1bb7, + 0x6ee5bb8, + 0x6ee9bb9, + 0x6eedbba, + 0x6ef1bbb, + 0x26ef9bbc, + 0x6efdbbe, + 0x6f01bbf, + 0x6f05bc0, + 0x26f09bc1, + 0x6f0dbc2, + 0x26f15bc3, + 0x26f19bc5, + 0x6f35bc6, + 0x6f45bcd, + 0x6f89bd1, + 0x6f8dbe2, + 0x6fb1be3, + 0x6fb5bec, + 0x6fb9bed, + 0x7145bee, + 0x27149c51, + 0x27151c52, + 0x27155c54, + 0x27159c55, + 0x7161c56, + 0x723dc58, + 0x27249c8f, + 0x2724dc92, + 0x27251c93, + 0x27255c94, + 0x7259c95, + 0x7285c96, + 0x7289ca1, + 0x72adca2, + 0x72b9cab, + 0x72d9cae, + 0x72ddcb6, + 0x7315cb7, + 0x75adcc5, + 0x7669d6b, + 0x767dd9a, + 0x76b1d9f, + 0x76e1dac, + 0x76fddb8, + 0x7725dbf, + 0x7745dc9, + 0x7761dd1, + 0x7789dd8, + 0x7799de2, + 0x779dde6, + 0x77a1de7, + 0x77d5de8, + 0x77e1df5, + 0x7801df8, + 0x7879e00, + 0x2787de1e, + 0x78a1e1f, + 0x78c1e28, + 0x78d5e30, + 0x78e9e35, + 0x78ede3a, + 0x790de3b, + 0x79b1e43, + 0x79cde6c, + 0x79f1e73, + 0x79f9e7c, + 0x7a05e7e, + 0x7a0de81, + 0x7a21e83, + 0x7a41e88, + 0x7a4de90, + 0x7a59e93, + 0x7a89e96, + 0x7b5dea2, + 0x7b61ed7, + 0x7b75ed8, + 0x7b7dedd, + 0x7b95edf, + 0x7b99ee5, + 0x7ba5ee6, + 0x7ba9ee9, + 0x7bc5eea, + 0x7c01ef1, + 0x7c05f00, + 0x7c25f01, + 0x7c75f09, + 0x7c91f1d, + 0x7ce5f24, + 0x7ce9f39, + 0x7cedf3a, + 0x7cf1f3b, + 0x7d35f3c, + 0x7d45f4d, + 0x7d85f51, + 0x7d89f61, + 0x7db9f62, + 0x7f01f6e, + 0x7f29fc0, + 0x7f55fca, + 0x7f65fd5, + 0x7f6dfd9, + 0x807dfdb, + 0x808a01f, + 0x8096022, + 0x80a2025, + 0x80ae028, + 0x80ba02b, + 0x80c602e, + 0x80d2031, + 0x80de034, + 0x80ea037, + 0x80f603a, + 0x810203d, + 0x810e040, + 0x811a043, + 0x8122046, + 0x812e048, + 0x813a04b, + 0x814604e, + 0x8152051, + 0x815e054, + 0x816a057, + 0x817605a, + 0x818205d, + 0x818e060, + 0x819a063, + 0x81a6066, + 0x81d2069, + 0x81de074, + 0x81ea077, + 0x81f607a, + 0x820207d, + 0x820e080, + 0x8216083, + 0x8222085, + 0x822e088, + 0x823a08b, + 0x824608e, + 0x8252091, + 0x825e094, + 0x826a097, + 0x827609a, + 0x828209d, + 0x828e0a0, + 0x829a0a3, + 0x82a60a6, + 0x82b20a9, + 0x82ba0ac, + 0x82c60ae, + 0x82d20b1, + 0x82de0b4, + 0x82ea0b7, + 0x82f60ba, + 0x83020bd, + 0x830e0c0, + 0x831a0c3, + 0x831e0c6, + 0x832a0c7, + 0x83460ca, + 0x834a0d1, + 0x835a0d2, + 0x83760d6, + 0x83ba0dd, + 0x83be0ee, + 0x83d20ef, + 0x84060f4, + 0x8416101, + 0x8436105, + 0x844e10d, + 0x8466113, + 0x846e119, + 0x284b211b, + 0x84b612c, + 0x84e212d, + 0x84ea138, + 0x84fe13a, } -// max children 494 (capacity 1023) -// max text offset 28750 (capacity 32767) +// max children 500 (capacity 1023) +// max text offset 29102 (capacity 32767) // max text length 36 (capacity 63) -// max hi 8407 (capacity 16383) -// max lo 8402 (capacity 16383) +// max hi 8511 (capacity 16383) +// max lo 8506 (capacity 16383) diff --git a/vendor/golang.org/x/net/publicsuffix/table_test.go b/vendor/golang.org/x/net/publicsuffix/table_test.go deleted file mode 100644 index 62610185be..0000000000 --- a/vendor/golang.org/x/net/publicsuffix/table_test.go +++ /dev/null @@ -1,16756 +0,0 @@ -// generated by go run gen.go; DO NOT EDIT - -package publicsuffix - -var rules = [...]string{ - "ac", - "com.ac", - "edu.ac", - "gov.ac", - "net.ac", - "mil.ac", - "org.ac", - "ad", - "nom.ad", - "ae", - "co.ae", - "net.ae", - "org.ae", - "sch.ae", - "ac.ae", - "gov.ae", - "mil.ae", - "aero", - "accident-investigation.aero", - "accident-prevention.aero", - "aerobatic.aero", - "aeroclub.aero", - "aerodrome.aero", - "agents.aero", - "aircraft.aero", - "airline.aero", - "airport.aero", - "air-surveillance.aero", - "airtraffic.aero", - "air-traffic-control.aero", - "ambulance.aero", - "amusement.aero", - "association.aero", - "author.aero", - "ballooning.aero", - "broker.aero", - "caa.aero", - "cargo.aero", - "catering.aero", - "certification.aero", - "championship.aero", - "charter.aero", - "civilaviation.aero", - "club.aero", - "conference.aero", - "consultant.aero", - "consulting.aero", - "control.aero", - "council.aero", - "crew.aero", - "design.aero", - "dgca.aero", - "educator.aero", - "emergency.aero", - "engine.aero", - "engineer.aero", - "entertainment.aero", - "equipment.aero", - "exchange.aero", - "express.aero", - "federation.aero", - "flight.aero", - "freight.aero", - "fuel.aero", - "gliding.aero", - "government.aero", - "groundhandling.aero", - "group.aero", - "hanggliding.aero", - "homebuilt.aero", - "insurance.aero", - "journal.aero", - "journalist.aero", - "leasing.aero", - "logistics.aero", - "magazine.aero", - "maintenance.aero", - "media.aero", - "microlight.aero", - "modelling.aero", - "navigation.aero", - "parachuting.aero", - "paragliding.aero", - "passenger-association.aero", - "pilot.aero", - "press.aero", - "production.aero", - "recreation.aero", - "repbody.aero", - "res.aero", - "research.aero", - "rotorcraft.aero", - "safety.aero", - "scientist.aero", - "services.aero", - "show.aero", - "skydiving.aero", - "software.aero", - "student.aero", - "trader.aero", - "trading.aero", - "trainer.aero", - "union.aero", - "workinggroup.aero", - "works.aero", - "af", - "gov.af", - "com.af", - "org.af", - "net.af", - "edu.af", - "ag", - "com.ag", - "org.ag", - "net.ag", - "co.ag", - "nom.ag", - "ai", - "off.ai", - "com.ai", - "net.ai", - "org.ai", - "al", - "com.al", - "edu.al", - "gov.al", - "mil.al", - "net.al", - "org.al", - "am", - "ao", - "ed.ao", - "gv.ao", - "og.ao", - "co.ao", - "pb.ao", - "it.ao", - "aq", - "ar", - "com.ar", - "edu.ar", - "gob.ar", - "gov.ar", - "int.ar", - "mil.ar", - "musica.ar", - "net.ar", - "org.ar", - "tur.ar", - "arpa", - "e164.arpa", - "in-addr.arpa", - "ip6.arpa", - "iris.arpa", - "uri.arpa", - "urn.arpa", - "as", - "gov.as", - "asia", - "at", - "ac.at", - "co.at", - "gv.at", - "or.at", - "au", - "com.au", - "net.au", - "org.au", - "edu.au", - "gov.au", - "asn.au", - "id.au", - "info.au", - "conf.au", - "oz.au", - "act.au", - "nsw.au", - "nt.au", - "qld.au", - "sa.au", - "tas.au", - "vic.au", - "wa.au", - "act.edu.au", - "nsw.edu.au", - "nt.edu.au", - "qld.edu.au", - "sa.edu.au", - "tas.edu.au", - "vic.edu.au", - "wa.edu.au", - "qld.gov.au", - "sa.gov.au", - "tas.gov.au", - "vic.gov.au", - "wa.gov.au", - "aw", - "com.aw", - "ax", - "az", - "com.az", - "net.az", - "int.az", - "gov.az", - "org.az", - "edu.az", - "info.az", - "pp.az", - "mil.az", - "name.az", - "pro.az", - "biz.az", - "ba", - "com.ba", - "edu.ba", - "gov.ba", - "mil.ba", - "net.ba", - "org.ba", - "bb", - "biz.bb", - "co.bb", - "com.bb", - "edu.bb", - "gov.bb", - "info.bb", - "net.bb", - "org.bb", - "store.bb", - "tv.bb", - "*.bd", - "be", - "ac.be", - "bf", - "gov.bf", - "bg", - "a.bg", - "b.bg", - "c.bg", - "d.bg", - "e.bg", - "f.bg", - "g.bg", - "h.bg", - "i.bg", - "j.bg", - "k.bg", - "l.bg", - "m.bg", - "n.bg", - "o.bg", - "p.bg", - "q.bg", - "r.bg", - "s.bg", - "t.bg", - "u.bg", - "v.bg", - "w.bg", - "x.bg", - "y.bg", - "z.bg", - "0.bg", - "1.bg", - "2.bg", - "3.bg", - "4.bg", - "5.bg", - "6.bg", - "7.bg", - "8.bg", - "9.bg", - "bh", - "com.bh", - "edu.bh", - "net.bh", - "org.bh", - "gov.bh", - "bi", - "co.bi", - "com.bi", - "edu.bi", - "or.bi", - "org.bi", - "biz", - "bj", - "asso.bj", - "barreau.bj", - "gouv.bj", - "bm", - "com.bm", - "edu.bm", - "gov.bm", - "net.bm", - "org.bm", - "*.bn", - "bo", - "com.bo", - "edu.bo", - "gov.bo", - "gob.bo", - "int.bo", - "org.bo", - "net.bo", - "mil.bo", - "tv.bo", - "br", - "adm.br", - "adv.br", - "agr.br", - "am.br", - "arq.br", - "art.br", - "ato.br", - "b.br", - "belem.br", - "bio.br", - "blog.br", - "bmd.br", - "cim.br", - "cng.br", - "cnt.br", - "com.br", - "coop.br", - "cri.br", - "def.br", - "ecn.br", - "eco.br", - "edu.br", - "emp.br", - "eng.br", - "esp.br", - "etc.br", - "eti.br", - "far.br", - "flog.br", - "floripa.br", - "fm.br", - "fnd.br", - "fot.br", - "fst.br", - "g12.br", - "ggf.br", - "gov.br", - "ac.gov.br", - "al.gov.br", - "am.gov.br", - "ap.gov.br", - "ba.gov.br", - "ce.gov.br", - "df.gov.br", - "es.gov.br", - "go.gov.br", - "ma.gov.br", - "mg.gov.br", - "ms.gov.br", - "mt.gov.br", - "pa.gov.br", - "pb.gov.br", - "pe.gov.br", - "pi.gov.br", - "pr.gov.br", - "rj.gov.br", - "rn.gov.br", - "ro.gov.br", - "rr.gov.br", - "rs.gov.br", - "sc.gov.br", - "se.gov.br", - "sp.gov.br", - "to.gov.br", - "imb.br", - "ind.br", - "inf.br", - "jampa.br", - "jor.br", - "jus.br", - "leg.br", - "lel.br", - "mat.br", - "med.br", - "mil.br", - "mp.br", - "mus.br", - "net.br", - "*.nom.br", - "not.br", - "ntr.br", - "odo.br", - "org.br", - "poa.br", - "ppg.br", - "pro.br", - "psc.br", - "psi.br", - "qsl.br", - "radio.br", - "rec.br", - "recife.br", - "slg.br", - "srv.br", - "taxi.br", - "teo.br", - "tmp.br", - "trd.br", - "tur.br", - "tv.br", - "vet.br", - "vix.br", - "vlog.br", - "wiki.br", - "zlg.br", - "bs", - "com.bs", - "net.bs", - "org.bs", - "edu.bs", - "gov.bs", - "bt", - "com.bt", - "edu.bt", - "gov.bt", - "net.bt", - "org.bt", - "bv", - "bw", - "co.bw", - "org.bw", - "by", - "gov.by", - "mil.by", - "com.by", - "of.by", - "bz", - "com.bz", - "net.bz", - "org.bz", - "edu.bz", - "gov.bz", - "ca", - "ab.ca", - "bc.ca", - "mb.ca", - "nb.ca", - "nf.ca", - "nl.ca", - "ns.ca", - "nt.ca", - "nu.ca", - "on.ca", - "pe.ca", - "qc.ca", - "sk.ca", - "yk.ca", - "gc.ca", - "cat", - "cc", - "cd", - "gov.cd", - "cf", - "cg", - "ch", - "ci", - "org.ci", - "or.ci", - "com.ci", - "co.ci", - "edu.ci", - "ed.ci", - "ac.ci", - "net.ci", - "go.ci", - "asso.ci", - "xn--aroport-bya.ci", - "int.ci", - "presse.ci", - "md.ci", - "gouv.ci", - "*.ck", - "!www.ck", - "cl", - "gov.cl", - "gob.cl", - "co.cl", - "mil.cl", - "cm", - "co.cm", - "com.cm", - "gov.cm", - "net.cm", - "cn", - "ac.cn", - "com.cn", - "edu.cn", - "gov.cn", - "net.cn", - "org.cn", - "mil.cn", - "xn--55qx5d.cn", - "xn--io0a7i.cn", - "xn--od0alg.cn", - "ah.cn", - "bj.cn", - "cq.cn", - "fj.cn", - "gd.cn", - "gs.cn", - "gz.cn", - "gx.cn", - "ha.cn", - "hb.cn", - "he.cn", - "hi.cn", - "hl.cn", - "hn.cn", - "jl.cn", - "js.cn", - "jx.cn", - "ln.cn", - "nm.cn", - "nx.cn", - "qh.cn", - "sc.cn", - "sd.cn", - "sh.cn", - "sn.cn", - "sx.cn", - "tj.cn", - "xj.cn", - "xz.cn", - "yn.cn", - "zj.cn", - "hk.cn", - "mo.cn", - "tw.cn", - "co", - "arts.co", - "com.co", - "edu.co", - "firm.co", - "gov.co", - "info.co", - "int.co", - "mil.co", - "net.co", - "nom.co", - "org.co", - "rec.co", - "web.co", - "com", - "coop", - "cr", - "ac.cr", - "co.cr", - "ed.cr", - "fi.cr", - "go.cr", - "or.cr", - "sa.cr", - "cu", - "com.cu", - "edu.cu", - "org.cu", - "net.cu", - "gov.cu", - "inf.cu", - "cv", - "cw", - "com.cw", - "edu.cw", - "net.cw", - "org.cw", - "cx", - "gov.cx", - "cy", - "ac.cy", - "biz.cy", - "com.cy", - "ekloges.cy", - "gov.cy", - "ltd.cy", - "name.cy", - "net.cy", - "org.cy", - "parliament.cy", - "press.cy", - "pro.cy", - "tm.cy", - "cz", - "de", - "dj", - "dk", - "dm", - "com.dm", - "net.dm", - "org.dm", - "edu.dm", - "gov.dm", - "do", - "art.do", - "com.do", - "edu.do", - "gob.do", - "gov.do", - "mil.do", - "net.do", - "org.do", - "sld.do", - "web.do", - "dz", - "com.dz", - "org.dz", - "net.dz", - "gov.dz", - "edu.dz", - "asso.dz", - "pol.dz", - "art.dz", - "ec", - "com.ec", - "info.ec", - "net.ec", - "fin.ec", - "k12.ec", - "med.ec", - "pro.ec", - "org.ec", - "edu.ec", - "gov.ec", - "gob.ec", - "mil.ec", - "edu", - "ee", - "edu.ee", - "gov.ee", - "riik.ee", - "lib.ee", - "med.ee", - "com.ee", - "pri.ee", - "aip.ee", - "org.ee", - "fie.ee", - "eg", - "com.eg", - "edu.eg", - "eun.eg", - "gov.eg", - "mil.eg", - "name.eg", - "net.eg", - "org.eg", - "sci.eg", - "*.er", - "es", - "com.es", - "nom.es", - "org.es", - "gob.es", - "edu.es", - "et", - "com.et", - "gov.et", - "org.et", - "edu.et", - "biz.et", - "name.et", - "info.et", - "net.et", - "eu", - "fi", - "aland.fi", - "*.fj", - "*.fk", - "fm", - "fo", - "fr", - "com.fr", - "asso.fr", - "nom.fr", - "prd.fr", - "presse.fr", - "tm.fr", - "aeroport.fr", - "assedic.fr", - "avocat.fr", - "avoues.fr", - "cci.fr", - "chambagri.fr", - "chirurgiens-dentistes.fr", - "experts-comptables.fr", - "geometre-expert.fr", - "gouv.fr", - "greta.fr", - "huissier-justice.fr", - "medecin.fr", - "notaires.fr", - "pharmacien.fr", - "port.fr", - "veterinaire.fr", - "ga", - "gb", - "gd", - "ge", - "com.ge", - "edu.ge", - "gov.ge", - "org.ge", - "mil.ge", - "net.ge", - "pvt.ge", - "gf", - "gg", - "co.gg", - "net.gg", - "org.gg", - "gh", - "com.gh", - "edu.gh", - "gov.gh", - "org.gh", - "mil.gh", - "gi", - "com.gi", - "ltd.gi", - "gov.gi", - "mod.gi", - "edu.gi", - "org.gi", - "gl", - "co.gl", - "com.gl", - "edu.gl", - "net.gl", - "org.gl", - "gm", - "gn", - "ac.gn", - "com.gn", - "edu.gn", - "gov.gn", - "org.gn", - "net.gn", - "gov", - "gp", - "com.gp", - "net.gp", - "mobi.gp", - "edu.gp", - "org.gp", - "asso.gp", - "gq", - "gr", - "com.gr", - "edu.gr", - "net.gr", - "org.gr", - "gov.gr", - "gs", - "gt", - "com.gt", - "edu.gt", - "gob.gt", - "ind.gt", - "mil.gt", - "net.gt", - "org.gt", - "*.gu", - "gw", - "gy", - "co.gy", - "com.gy", - "edu.gy", - "gov.gy", - "net.gy", - "org.gy", - "hk", - "com.hk", - "edu.hk", - "gov.hk", - "idv.hk", - "net.hk", - "org.hk", - "xn--55qx5d.hk", - "xn--wcvs22d.hk", - "xn--lcvr32d.hk", - "xn--mxtq1m.hk", - "xn--gmqw5a.hk", - "xn--ciqpn.hk", - "xn--gmq050i.hk", - "xn--zf0avx.hk", - "xn--io0a7i.hk", - "xn--mk0axi.hk", - "xn--od0alg.hk", - "xn--od0aq3b.hk", - "xn--tn0ag.hk", - "xn--uc0atv.hk", - "xn--uc0ay4a.hk", - "hm", - "hn", - "com.hn", - "edu.hn", - "org.hn", - "net.hn", - "mil.hn", - "gob.hn", - "hr", - "iz.hr", - "from.hr", - "name.hr", - "com.hr", - "ht", - "com.ht", - "shop.ht", - "firm.ht", - "info.ht", - "adult.ht", - "net.ht", - "pro.ht", - "org.ht", - "med.ht", - "art.ht", - "coop.ht", - "pol.ht", - "asso.ht", - "edu.ht", - "rel.ht", - "gouv.ht", - "perso.ht", - "hu", - "co.hu", - "info.hu", - "org.hu", - "priv.hu", - "sport.hu", - "tm.hu", - "2000.hu", - "agrar.hu", - "bolt.hu", - "casino.hu", - "city.hu", - "erotica.hu", - "erotika.hu", - "film.hu", - "forum.hu", - "games.hu", - "hotel.hu", - "ingatlan.hu", - "jogasz.hu", - "konyvelo.hu", - "lakas.hu", - "media.hu", - "news.hu", - "reklam.hu", - "sex.hu", - "shop.hu", - "suli.hu", - "szex.hu", - "tozsde.hu", - "utazas.hu", - "video.hu", - "id", - "ac.id", - "biz.id", - "co.id", - "desa.id", - "go.id", - "mil.id", - "my.id", - "net.id", - "or.id", - "sch.id", - "web.id", - "ie", - "gov.ie", - "il", - "ac.il", - "co.il", - "gov.il", - "idf.il", - "k12.il", - "muni.il", - "net.il", - "org.il", - "im", - "ac.im", - "co.im", - "com.im", - "ltd.co.im", - "net.im", - "org.im", - "plc.co.im", - "tt.im", - "tv.im", - "in", - "co.in", - "firm.in", - "net.in", - "org.in", - "gen.in", - "ind.in", - "nic.in", - "ac.in", - "edu.in", - "res.in", - "gov.in", - "mil.in", - "info", - "int", - "eu.int", - "io", - "com.io", - "iq", - "gov.iq", - "edu.iq", - "mil.iq", - "com.iq", - "org.iq", - "net.iq", - "ir", - "ac.ir", - "co.ir", - "gov.ir", - "id.ir", - "net.ir", - "org.ir", - "sch.ir", - "xn--mgba3a4f16a.ir", - "xn--mgba3a4fra.ir", - "is", - "net.is", - "com.is", - "edu.is", - "gov.is", - "org.is", - "int.is", - "it", - "gov.it", - "edu.it", - "abr.it", - "abruzzo.it", - "aosta-valley.it", - "aostavalley.it", - "bas.it", - "basilicata.it", - "cal.it", - "calabria.it", - "cam.it", - "campania.it", - "emilia-romagna.it", - "emiliaromagna.it", - "emr.it", - "friuli-v-giulia.it", - "friuli-ve-giulia.it", - "friuli-vegiulia.it", - "friuli-venezia-giulia.it", - "friuli-veneziagiulia.it", - "friuli-vgiulia.it", - "friuliv-giulia.it", - "friulive-giulia.it", - "friulivegiulia.it", - "friulivenezia-giulia.it", - "friuliveneziagiulia.it", - "friulivgiulia.it", - "fvg.it", - "laz.it", - "lazio.it", - "lig.it", - "liguria.it", - "lom.it", - "lombardia.it", - "lombardy.it", - "lucania.it", - "mar.it", - "marche.it", - "mol.it", - "molise.it", - "piedmont.it", - "piemonte.it", - "pmn.it", - "pug.it", - "puglia.it", - "sar.it", - "sardegna.it", - "sardinia.it", - "sic.it", - "sicilia.it", - "sicily.it", - "taa.it", - "tos.it", - "toscana.it", - "trentino-a-adige.it", - "trentino-aadige.it", - "trentino-alto-adige.it", - "trentino-altoadige.it", - "trentino-s-tirol.it", - "trentino-stirol.it", - "trentino-sud-tirol.it", - "trentino-sudtirol.it", - "trentino-sued-tirol.it", - "trentino-suedtirol.it", - "trentinoa-adige.it", - "trentinoaadige.it", - "trentinoalto-adige.it", - "trentinoaltoadige.it", - "trentinos-tirol.it", - "trentinostirol.it", - "trentinosud-tirol.it", - "trentinosudtirol.it", - "trentinosued-tirol.it", - "trentinosuedtirol.it", - "tuscany.it", - "umb.it", - "umbria.it", - "val-d-aosta.it", - "val-daosta.it", - "vald-aosta.it", - "valdaosta.it", - "valle-aosta.it", - "valle-d-aosta.it", - "valle-daosta.it", - "valleaosta.it", - "valled-aosta.it", - "valledaosta.it", - "vallee-aoste.it", - "valleeaoste.it", - "vao.it", - "vda.it", - "ven.it", - "veneto.it", - "ag.it", - "agrigento.it", - "al.it", - "alessandria.it", - "alto-adige.it", - "altoadige.it", - "an.it", - "ancona.it", - "andria-barletta-trani.it", - "andria-trani-barletta.it", - "andriabarlettatrani.it", - "andriatranibarletta.it", - "ao.it", - "aosta.it", - "aoste.it", - "ap.it", - "aq.it", - "aquila.it", - "ar.it", - "arezzo.it", - "ascoli-piceno.it", - "ascolipiceno.it", - "asti.it", - "at.it", - "av.it", - "avellino.it", - "ba.it", - "balsan.it", - "bari.it", - "barletta-trani-andria.it", - "barlettatraniandria.it", - "belluno.it", - "benevento.it", - "bergamo.it", - "bg.it", - "bi.it", - "biella.it", - "bl.it", - "bn.it", - "bo.it", - "bologna.it", - "bolzano.it", - "bozen.it", - "br.it", - "brescia.it", - "brindisi.it", - "bs.it", - "bt.it", - "bz.it", - "ca.it", - "cagliari.it", - "caltanissetta.it", - "campidano-medio.it", - "campidanomedio.it", - "campobasso.it", - "carbonia-iglesias.it", - "carboniaiglesias.it", - "carrara-massa.it", - "carraramassa.it", - "caserta.it", - "catania.it", - "catanzaro.it", - "cb.it", - "ce.it", - "cesena-forli.it", - "cesenaforli.it", - "ch.it", - "chieti.it", - "ci.it", - "cl.it", - "cn.it", - "co.it", - "como.it", - "cosenza.it", - "cr.it", - "cremona.it", - "crotone.it", - "cs.it", - "ct.it", - "cuneo.it", - "cz.it", - "dell-ogliastra.it", - "dellogliastra.it", - "en.it", - "enna.it", - "fc.it", - "fe.it", - "fermo.it", - "ferrara.it", - "fg.it", - "fi.it", - "firenze.it", - "florence.it", - "fm.it", - "foggia.it", - "forli-cesena.it", - "forlicesena.it", - "fr.it", - "frosinone.it", - "ge.it", - "genoa.it", - "genova.it", - "go.it", - "gorizia.it", - "gr.it", - "grosseto.it", - "iglesias-carbonia.it", - "iglesiascarbonia.it", - "im.it", - "imperia.it", - "is.it", - "isernia.it", - "kr.it", - "la-spezia.it", - "laquila.it", - "laspezia.it", - "latina.it", - "lc.it", - "le.it", - "lecce.it", - "lecco.it", - "li.it", - "livorno.it", - "lo.it", - "lodi.it", - "lt.it", - "lu.it", - "lucca.it", - "macerata.it", - "mantova.it", - "massa-carrara.it", - "massacarrara.it", - "matera.it", - "mb.it", - "mc.it", - "me.it", - "medio-campidano.it", - "mediocampidano.it", - "messina.it", - "mi.it", - "milan.it", - "milano.it", - "mn.it", - "mo.it", - "modena.it", - "monza-brianza.it", - "monza-e-della-brianza.it", - "monza.it", - "monzabrianza.it", - "monzaebrianza.it", - "monzaedellabrianza.it", - "ms.it", - "mt.it", - "na.it", - "naples.it", - "napoli.it", - "no.it", - "novara.it", - "nu.it", - "nuoro.it", - "og.it", - "ogliastra.it", - "olbia-tempio.it", - "olbiatempio.it", - "or.it", - "oristano.it", - "ot.it", - "pa.it", - "padova.it", - "padua.it", - "palermo.it", - "parma.it", - "pavia.it", - "pc.it", - "pd.it", - "pe.it", - "perugia.it", - "pesaro-urbino.it", - "pesarourbino.it", - "pescara.it", - "pg.it", - "pi.it", - "piacenza.it", - "pisa.it", - "pistoia.it", - "pn.it", - "po.it", - "pordenone.it", - "potenza.it", - "pr.it", - "prato.it", - "pt.it", - "pu.it", - "pv.it", - "pz.it", - "ra.it", - "ragusa.it", - "ravenna.it", - "rc.it", - "re.it", - "reggio-calabria.it", - "reggio-emilia.it", - "reggiocalabria.it", - "reggioemilia.it", - "rg.it", - "ri.it", - "rieti.it", - "rimini.it", - "rm.it", - "rn.it", - "ro.it", - "roma.it", - "rome.it", - "rovigo.it", - "sa.it", - "salerno.it", - "sassari.it", - "savona.it", - "si.it", - "siena.it", - "siracusa.it", - "so.it", - "sondrio.it", - "sp.it", - "sr.it", - "ss.it", - "suedtirol.it", - "sv.it", - "ta.it", - "taranto.it", - "te.it", - "tempio-olbia.it", - "tempioolbia.it", - "teramo.it", - "terni.it", - "tn.it", - "to.it", - "torino.it", - "tp.it", - "tr.it", - "trani-andria-barletta.it", - "trani-barletta-andria.it", - "traniandriabarletta.it", - "tranibarlettaandria.it", - "trapani.it", - "trentino.it", - "trento.it", - "treviso.it", - "trieste.it", - "ts.it", - "turin.it", - "tv.it", - "ud.it", - "udine.it", - "urbino-pesaro.it", - "urbinopesaro.it", - "va.it", - "varese.it", - "vb.it", - "vc.it", - "ve.it", - "venezia.it", - "venice.it", - "verbania.it", - "vercelli.it", - "verona.it", - "vi.it", - "vibo-valentia.it", - "vibovalentia.it", - "vicenza.it", - "viterbo.it", - "vr.it", - "vs.it", - "vt.it", - "vv.it", - "je", - "co.je", - "net.je", - "org.je", - "*.jm", - "jo", - "com.jo", - "org.jo", - "net.jo", - "edu.jo", - "sch.jo", - "gov.jo", - "mil.jo", - "name.jo", - "jobs", - "jp", - "ac.jp", - "ad.jp", - "co.jp", - "ed.jp", - "go.jp", - "gr.jp", - "lg.jp", - "ne.jp", - "or.jp", - "aichi.jp", - "akita.jp", - "aomori.jp", - "chiba.jp", - "ehime.jp", - "fukui.jp", - "fukuoka.jp", - "fukushima.jp", - "gifu.jp", - "gunma.jp", - "hiroshima.jp", - "hokkaido.jp", - "hyogo.jp", - "ibaraki.jp", - "ishikawa.jp", - "iwate.jp", - "kagawa.jp", - "kagoshima.jp", - "kanagawa.jp", - "kochi.jp", - "kumamoto.jp", - "kyoto.jp", - "mie.jp", - "miyagi.jp", - "miyazaki.jp", - "nagano.jp", - "nagasaki.jp", - "nara.jp", - "niigata.jp", - "oita.jp", - "okayama.jp", - "okinawa.jp", - "osaka.jp", - "saga.jp", - "saitama.jp", - "shiga.jp", - "shimane.jp", - "shizuoka.jp", - "tochigi.jp", - "tokushima.jp", - "tokyo.jp", - "tottori.jp", - "toyama.jp", - "wakayama.jp", - "yamagata.jp", - "yamaguchi.jp", - "yamanashi.jp", - "xn--4pvxs.jp", - "xn--vgu402c.jp", - "xn--c3s14m.jp", - "xn--f6qx53a.jp", - "xn--8pvr4u.jp", - "xn--uist22h.jp", - "xn--djrs72d6uy.jp", - "xn--mkru45i.jp", - "xn--0trq7p7nn.jp", - "xn--8ltr62k.jp", - "xn--2m4a15e.jp", - "xn--efvn9s.jp", - "xn--32vp30h.jp", - "xn--4it797k.jp", - "xn--1lqs71d.jp", - "xn--5rtp49c.jp", - "xn--5js045d.jp", - "xn--ehqz56n.jp", - "xn--1lqs03n.jp", - "xn--qqqt11m.jp", - "xn--kbrq7o.jp", - "xn--pssu33l.jp", - "xn--ntsq17g.jp", - "xn--uisz3g.jp", - "xn--6btw5a.jp", - "xn--1ctwo.jp", - "xn--6orx2r.jp", - "xn--rht61e.jp", - "xn--rht27z.jp", - "xn--djty4k.jp", - "xn--nit225k.jp", - "xn--rht3d.jp", - "xn--klty5x.jp", - "xn--kltx9a.jp", - "xn--kltp7d.jp", - "xn--uuwu58a.jp", - "xn--zbx025d.jp", - "xn--ntso0iqx3a.jp", - "xn--elqq16h.jp", - "xn--4it168d.jp", - "xn--klt787d.jp", - "xn--rny31h.jp", - "xn--7t0a264c.jp", - "xn--5rtq34k.jp", - "xn--k7yn95e.jp", - "xn--tor131o.jp", - "xn--d5qv7z876c.jp", - "*.kawasaki.jp", - "*.kitakyushu.jp", - "*.kobe.jp", - "*.nagoya.jp", - "*.sapporo.jp", - "*.sendai.jp", - "*.yokohama.jp", - "!city.kawasaki.jp", - "!city.kitakyushu.jp", - "!city.kobe.jp", - "!city.nagoya.jp", - "!city.sapporo.jp", - "!city.sendai.jp", - "!city.yokohama.jp", - "aisai.aichi.jp", - "ama.aichi.jp", - "anjo.aichi.jp", - "asuke.aichi.jp", - "chiryu.aichi.jp", - "chita.aichi.jp", - "fuso.aichi.jp", - "gamagori.aichi.jp", - "handa.aichi.jp", - "hazu.aichi.jp", - "hekinan.aichi.jp", - "higashiura.aichi.jp", - "ichinomiya.aichi.jp", - "inazawa.aichi.jp", - "inuyama.aichi.jp", - "isshiki.aichi.jp", - "iwakura.aichi.jp", - "kanie.aichi.jp", - "kariya.aichi.jp", - "kasugai.aichi.jp", - "kira.aichi.jp", - "kiyosu.aichi.jp", - "komaki.aichi.jp", - "konan.aichi.jp", - "kota.aichi.jp", - "mihama.aichi.jp", - "miyoshi.aichi.jp", - "nishio.aichi.jp", - "nisshin.aichi.jp", - "obu.aichi.jp", - "oguchi.aichi.jp", - "oharu.aichi.jp", - "okazaki.aichi.jp", - "owariasahi.aichi.jp", - "seto.aichi.jp", - "shikatsu.aichi.jp", - "shinshiro.aichi.jp", - "shitara.aichi.jp", - "tahara.aichi.jp", - "takahama.aichi.jp", - "tobishima.aichi.jp", - "toei.aichi.jp", - "togo.aichi.jp", - "tokai.aichi.jp", - "tokoname.aichi.jp", - "toyoake.aichi.jp", - "toyohashi.aichi.jp", - "toyokawa.aichi.jp", - "toyone.aichi.jp", - "toyota.aichi.jp", - "tsushima.aichi.jp", - "yatomi.aichi.jp", - "akita.akita.jp", - "daisen.akita.jp", - "fujisato.akita.jp", - "gojome.akita.jp", - "hachirogata.akita.jp", - "happou.akita.jp", - "higashinaruse.akita.jp", - "honjo.akita.jp", - "honjyo.akita.jp", - "ikawa.akita.jp", - "kamikoani.akita.jp", - "kamioka.akita.jp", - "katagami.akita.jp", - "kazuno.akita.jp", - "kitaakita.akita.jp", - "kosaka.akita.jp", - "kyowa.akita.jp", - "misato.akita.jp", - "mitane.akita.jp", - "moriyoshi.akita.jp", - "nikaho.akita.jp", - "noshiro.akita.jp", - "odate.akita.jp", - "oga.akita.jp", - "ogata.akita.jp", - "semboku.akita.jp", - "yokote.akita.jp", - "yurihonjo.akita.jp", - "aomori.aomori.jp", - "gonohe.aomori.jp", - "hachinohe.aomori.jp", - "hashikami.aomori.jp", - "hiranai.aomori.jp", - "hirosaki.aomori.jp", - "itayanagi.aomori.jp", - "kuroishi.aomori.jp", - "misawa.aomori.jp", - "mutsu.aomori.jp", - "nakadomari.aomori.jp", - "noheji.aomori.jp", - "oirase.aomori.jp", - "owani.aomori.jp", - "rokunohe.aomori.jp", - "sannohe.aomori.jp", - "shichinohe.aomori.jp", - "shingo.aomori.jp", - "takko.aomori.jp", - "towada.aomori.jp", - "tsugaru.aomori.jp", - "tsuruta.aomori.jp", - "abiko.chiba.jp", - "asahi.chiba.jp", - "chonan.chiba.jp", - "chosei.chiba.jp", - "choshi.chiba.jp", - "chuo.chiba.jp", - "funabashi.chiba.jp", - "futtsu.chiba.jp", - "hanamigawa.chiba.jp", - "ichihara.chiba.jp", - "ichikawa.chiba.jp", - "ichinomiya.chiba.jp", - "inzai.chiba.jp", - "isumi.chiba.jp", - "kamagaya.chiba.jp", - "kamogawa.chiba.jp", - "kashiwa.chiba.jp", - "katori.chiba.jp", - "katsuura.chiba.jp", - "kimitsu.chiba.jp", - "kisarazu.chiba.jp", - "kozaki.chiba.jp", - "kujukuri.chiba.jp", - "kyonan.chiba.jp", - "matsudo.chiba.jp", - "midori.chiba.jp", - "mihama.chiba.jp", - "minamiboso.chiba.jp", - "mobara.chiba.jp", - "mutsuzawa.chiba.jp", - "nagara.chiba.jp", - "nagareyama.chiba.jp", - "narashino.chiba.jp", - "narita.chiba.jp", - "noda.chiba.jp", - "oamishirasato.chiba.jp", - "omigawa.chiba.jp", - "onjuku.chiba.jp", - "otaki.chiba.jp", - "sakae.chiba.jp", - "sakura.chiba.jp", - "shimofusa.chiba.jp", - "shirako.chiba.jp", - "shiroi.chiba.jp", - "shisui.chiba.jp", - "sodegaura.chiba.jp", - "sosa.chiba.jp", - "tako.chiba.jp", - "tateyama.chiba.jp", - "togane.chiba.jp", - "tohnosho.chiba.jp", - "tomisato.chiba.jp", - "urayasu.chiba.jp", - "yachimata.chiba.jp", - "yachiyo.chiba.jp", - "yokaichiba.chiba.jp", - "yokoshibahikari.chiba.jp", - "yotsukaido.chiba.jp", - "ainan.ehime.jp", - "honai.ehime.jp", - "ikata.ehime.jp", - "imabari.ehime.jp", - "iyo.ehime.jp", - "kamijima.ehime.jp", - "kihoku.ehime.jp", - "kumakogen.ehime.jp", - "masaki.ehime.jp", - "matsuno.ehime.jp", - "matsuyama.ehime.jp", - "namikata.ehime.jp", - "niihama.ehime.jp", - "ozu.ehime.jp", - "saijo.ehime.jp", - "seiyo.ehime.jp", - "shikokuchuo.ehime.jp", - "tobe.ehime.jp", - "toon.ehime.jp", - "uchiko.ehime.jp", - "uwajima.ehime.jp", - "yawatahama.ehime.jp", - "echizen.fukui.jp", - "eiheiji.fukui.jp", - "fukui.fukui.jp", - "ikeda.fukui.jp", - "katsuyama.fukui.jp", - "mihama.fukui.jp", - "minamiechizen.fukui.jp", - "obama.fukui.jp", - "ohi.fukui.jp", - "ono.fukui.jp", - "sabae.fukui.jp", - "sakai.fukui.jp", - "takahama.fukui.jp", - "tsuruga.fukui.jp", - "wakasa.fukui.jp", - "ashiya.fukuoka.jp", - "buzen.fukuoka.jp", - "chikugo.fukuoka.jp", - "chikuho.fukuoka.jp", - "chikujo.fukuoka.jp", - "chikushino.fukuoka.jp", - "chikuzen.fukuoka.jp", - "chuo.fukuoka.jp", - "dazaifu.fukuoka.jp", - "fukuchi.fukuoka.jp", - "hakata.fukuoka.jp", - "higashi.fukuoka.jp", - "hirokawa.fukuoka.jp", - "hisayama.fukuoka.jp", - "iizuka.fukuoka.jp", - "inatsuki.fukuoka.jp", - "kaho.fukuoka.jp", - "kasuga.fukuoka.jp", - "kasuya.fukuoka.jp", - "kawara.fukuoka.jp", - "keisen.fukuoka.jp", - "koga.fukuoka.jp", - "kurate.fukuoka.jp", - "kurogi.fukuoka.jp", - "kurume.fukuoka.jp", - "minami.fukuoka.jp", - "miyako.fukuoka.jp", - "miyama.fukuoka.jp", - "miyawaka.fukuoka.jp", - "mizumaki.fukuoka.jp", - "munakata.fukuoka.jp", - "nakagawa.fukuoka.jp", - "nakama.fukuoka.jp", - "nishi.fukuoka.jp", - "nogata.fukuoka.jp", - "ogori.fukuoka.jp", - "okagaki.fukuoka.jp", - "okawa.fukuoka.jp", - "oki.fukuoka.jp", - "omuta.fukuoka.jp", - "onga.fukuoka.jp", - "onojo.fukuoka.jp", - "oto.fukuoka.jp", - "saigawa.fukuoka.jp", - "sasaguri.fukuoka.jp", - "shingu.fukuoka.jp", - "shinyoshitomi.fukuoka.jp", - "shonai.fukuoka.jp", - "soeda.fukuoka.jp", - "sue.fukuoka.jp", - "tachiarai.fukuoka.jp", - "tagawa.fukuoka.jp", - "takata.fukuoka.jp", - "toho.fukuoka.jp", - "toyotsu.fukuoka.jp", - "tsuiki.fukuoka.jp", - "ukiha.fukuoka.jp", - "umi.fukuoka.jp", - "usui.fukuoka.jp", - "yamada.fukuoka.jp", - "yame.fukuoka.jp", - "yanagawa.fukuoka.jp", - "yukuhashi.fukuoka.jp", - "aizubange.fukushima.jp", - "aizumisato.fukushima.jp", - "aizuwakamatsu.fukushima.jp", - "asakawa.fukushima.jp", - "bandai.fukushima.jp", - "date.fukushima.jp", - "fukushima.fukushima.jp", - "furudono.fukushima.jp", - "futaba.fukushima.jp", - "hanawa.fukushima.jp", - "higashi.fukushima.jp", - "hirata.fukushima.jp", - "hirono.fukushima.jp", - "iitate.fukushima.jp", - "inawashiro.fukushima.jp", - "ishikawa.fukushima.jp", - "iwaki.fukushima.jp", - "izumizaki.fukushima.jp", - "kagamiishi.fukushima.jp", - "kaneyama.fukushima.jp", - "kawamata.fukushima.jp", - "kitakata.fukushima.jp", - "kitashiobara.fukushima.jp", - "koori.fukushima.jp", - "koriyama.fukushima.jp", - "kunimi.fukushima.jp", - "miharu.fukushima.jp", - "mishima.fukushima.jp", - "namie.fukushima.jp", - "nango.fukushima.jp", - "nishiaizu.fukushima.jp", - "nishigo.fukushima.jp", - "okuma.fukushima.jp", - "omotego.fukushima.jp", - "ono.fukushima.jp", - "otama.fukushima.jp", - "samegawa.fukushima.jp", - "shimogo.fukushima.jp", - "shirakawa.fukushima.jp", - "showa.fukushima.jp", - "soma.fukushima.jp", - "sukagawa.fukushima.jp", - "taishin.fukushima.jp", - "tamakawa.fukushima.jp", - "tanagura.fukushima.jp", - "tenei.fukushima.jp", - "yabuki.fukushima.jp", - "yamato.fukushima.jp", - "yamatsuri.fukushima.jp", - "yanaizu.fukushima.jp", - "yugawa.fukushima.jp", - "anpachi.gifu.jp", - "ena.gifu.jp", - "gifu.gifu.jp", - "ginan.gifu.jp", - "godo.gifu.jp", - "gujo.gifu.jp", - "hashima.gifu.jp", - "hichiso.gifu.jp", - "hida.gifu.jp", - "higashishirakawa.gifu.jp", - "ibigawa.gifu.jp", - "ikeda.gifu.jp", - "kakamigahara.gifu.jp", - "kani.gifu.jp", - "kasahara.gifu.jp", - "kasamatsu.gifu.jp", - "kawaue.gifu.jp", - "kitagata.gifu.jp", - "mino.gifu.jp", - "minokamo.gifu.jp", - "mitake.gifu.jp", - "mizunami.gifu.jp", - "motosu.gifu.jp", - "nakatsugawa.gifu.jp", - "ogaki.gifu.jp", - "sakahogi.gifu.jp", - "seki.gifu.jp", - "sekigahara.gifu.jp", - "shirakawa.gifu.jp", - "tajimi.gifu.jp", - "takayama.gifu.jp", - "tarui.gifu.jp", - "toki.gifu.jp", - "tomika.gifu.jp", - "wanouchi.gifu.jp", - "yamagata.gifu.jp", - "yaotsu.gifu.jp", - "yoro.gifu.jp", - "annaka.gunma.jp", - "chiyoda.gunma.jp", - "fujioka.gunma.jp", - "higashiagatsuma.gunma.jp", - "isesaki.gunma.jp", - "itakura.gunma.jp", - "kanna.gunma.jp", - "kanra.gunma.jp", - "katashina.gunma.jp", - "kawaba.gunma.jp", - "kiryu.gunma.jp", - "kusatsu.gunma.jp", - "maebashi.gunma.jp", - "meiwa.gunma.jp", - "midori.gunma.jp", - "minakami.gunma.jp", - "naganohara.gunma.jp", - "nakanojo.gunma.jp", - "nanmoku.gunma.jp", - "numata.gunma.jp", - "oizumi.gunma.jp", - "ora.gunma.jp", - "ota.gunma.jp", - "shibukawa.gunma.jp", - "shimonita.gunma.jp", - "shinto.gunma.jp", - "showa.gunma.jp", - "takasaki.gunma.jp", - "takayama.gunma.jp", - "tamamura.gunma.jp", - "tatebayashi.gunma.jp", - "tomioka.gunma.jp", - "tsukiyono.gunma.jp", - "tsumagoi.gunma.jp", - "ueno.gunma.jp", - "yoshioka.gunma.jp", - "asaminami.hiroshima.jp", - "daiwa.hiroshima.jp", - "etajima.hiroshima.jp", - "fuchu.hiroshima.jp", - "fukuyama.hiroshima.jp", - "hatsukaichi.hiroshima.jp", - "higashihiroshima.hiroshima.jp", - "hongo.hiroshima.jp", - "jinsekikogen.hiroshima.jp", - "kaita.hiroshima.jp", - "kui.hiroshima.jp", - "kumano.hiroshima.jp", - "kure.hiroshima.jp", - "mihara.hiroshima.jp", - "miyoshi.hiroshima.jp", - "naka.hiroshima.jp", - "onomichi.hiroshima.jp", - "osakikamijima.hiroshima.jp", - "otake.hiroshima.jp", - "saka.hiroshima.jp", - "sera.hiroshima.jp", - "seranishi.hiroshima.jp", - "shinichi.hiroshima.jp", - "shobara.hiroshima.jp", - "takehara.hiroshima.jp", - "abashiri.hokkaido.jp", - "abira.hokkaido.jp", - "aibetsu.hokkaido.jp", - "akabira.hokkaido.jp", - "akkeshi.hokkaido.jp", - "asahikawa.hokkaido.jp", - "ashibetsu.hokkaido.jp", - "ashoro.hokkaido.jp", - "assabu.hokkaido.jp", - "atsuma.hokkaido.jp", - "bibai.hokkaido.jp", - "biei.hokkaido.jp", - "bifuka.hokkaido.jp", - "bihoro.hokkaido.jp", - "biratori.hokkaido.jp", - "chippubetsu.hokkaido.jp", - "chitose.hokkaido.jp", - "date.hokkaido.jp", - "ebetsu.hokkaido.jp", - "embetsu.hokkaido.jp", - "eniwa.hokkaido.jp", - "erimo.hokkaido.jp", - "esan.hokkaido.jp", - "esashi.hokkaido.jp", - "fukagawa.hokkaido.jp", - "fukushima.hokkaido.jp", - "furano.hokkaido.jp", - "furubira.hokkaido.jp", - "haboro.hokkaido.jp", - "hakodate.hokkaido.jp", - "hamatonbetsu.hokkaido.jp", - "hidaka.hokkaido.jp", - "higashikagura.hokkaido.jp", - "higashikawa.hokkaido.jp", - "hiroo.hokkaido.jp", - "hokuryu.hokkaido.jp", - "hokuto.hokkaido.jp", - "honbetsu.hokkaido.jp", - "horokanai.hokkaido.jp", - "horonobe.hokkaido.jp", - "ikeda.hokkaido.jp", - "imakane.hokkaido.jp", - "ishikari.hokkaido.jp", - "iwamizawa.hokkaido.jp", - "iwanai.hokkaido.jp", - "kamifurano.hokkaido.jp", - "kamikawa.hokkaido.jp", - "kamishihoro.hokkaido.jp", - "kamisunagawa.hokkaido.jp", - "kamoenai.hokkaido.jp", - "kayabe.hokkaido.jp", - "kembuchi.hokkaido.jp", - "kikonai.hokkaido.jp", - "kimobetsu.hokkaido.jp", - "kitahiroshima.hokkaido.jp", - "kitami.hokkaido.jp", - "kiyosato.hokkaido.jp", - "koshimizu.hokkaido.jp", - "kunneppu.hokkaido.jp", - "kuriyama.hokkaido.jp", - "kuromatsunai.hokkaido.jp", - "kushiro.hokkaido.jp", - "kutchan.hokkaido.jp", - "kyowa.hokkaido.jp", - "mashike.hokkaido.jp", - "matsumae.hokkaido.jp", - "mikasa.hokkaido.jp", - "minamifurano.hokkaido.jp", - "mombetsu.hokkaido.jp", - "moseushi.hokkaido.jp", - "mukawa.hokkaido.jp", - "muroran.hokkaido.jp", - "naie.hokkaido.jp", - "nakagawa.hokkaido.jp", - "nakasatsunai.hokkaido.jp", - "nakatombetsu.hokkaido.jp", - "nanae.hokkaido.jp", - "nanporo.hokkaido.jp", - "nayoro.hokkaido.jp", - "nemuro.hokkaido.jp", - "niikappu.hokkaido.jp", - "niki.hokkaido.jp", - "nishiokoppe.hokkaido.jp", - "noboribetsu.hokkaido.jp", - "numata.hokkaido.jp", - "obihiro.hokkaido.jp", - "obira.hokkaido.jp", - "oketo.hokkaido.jp", - "okoppe.hokkaido.jp", - "otaru.hokkaido.jp", - "otobe.hokkaido.jp", - "otofuke.hokkaido.jp", - "otoineppu.hokkaido.jp", - "oumu.hokkaido.jp", - "ozora.hokkaido.jp", - "pippu.hokkaido.jp", - "rankoshi.hokkaido.jp", - "rebun.hokkaido.jp", - "rikubetsu.hokkaido.jp", - "rishiri.hokkaido.jp", - "rishirifuji.hokkaido.jp", - "saroma.hokkaido.jp", - "sarufutsu.hokkaido.jp", - "shakotan.hokkaido.jp", - "shari.hokkaido.jp", - "shibecha.hokkaido.jp", - "shibetsu.hokkaido.jp", - "shikabe.hokkaido.jp", - "shikaoi.hokkaido.jp", - "shimamaki.hokkaido.jp", - "shimizu.hokkaido.jp", - "shimokawa.hokkaido.jp", - "shinshinotsu.hokkaido.jp", - "shintoku.hokkaido.jp", - "shiranuka.hokkaido.jp", - "shiraoi.hokkaido.jp", - "shiriuchi.hokkaido.jp", - "sobetsu.hokkaido.jp", - "sunagawa.hokkaido.jp", - "taiki.hokkaido.jp", - "takasu.hokkaido.jp", - "takikawa.hokkaido.jp", - "takinoue.hokkaido.jp", - "teshikaga.hokkaido.jp", - "tobetsu.hokkaido.jp", - "tohma.hokkaido.jp", - "tomakomai.hokkaido.jp", - "tomari.hokkaido.jp", - "toya.hokkaido.jp", - "toyako.hokkaido.jp", - "toyotomi.hokkaido.jp", - "toyoura.hokkaido.jp", - "tsubetsu.hokkaido.jp", - "tsukigata.hokkaido.jp", - "urakawa.hokkaido.jp", - "urausu.hokkaido.jp", - "uryu.hokkaido.jp", - "utashinai.hokkaido.jp", - "wakkanai.hokkaido.jp", - "wassamu.hokkaido.jp", - "yakumo.hokkaido.jp", - "yoichi.hokkaido.jp", - "aioi.hyogo.jp", - "akashi.hyogo.jp", - "ako.hyogo.jp", - "amagasaki.hyogo.jp", - "aogaki.hyogo.jp", - "asago.hyogo.jp", - "ashiya.hyogo.jp", - "awaji.hyogo.jp", - "fukusaki.hyogo.jp", - "goshiki.hyogo.jp", - "harima.hyogo.jp", - "himeji.hyogo.jp", - "ichikawa.hyogo.jp", - "inagawa.hyogo.jp", - "itami.hyogo.jp", - "kakogawa.hyogo.jp", - "kamigori.hyogo.jp", - "kamikawa.hyogo.jp", - "kasai.hyogo.jp", - "kasuga.hyogo.jp", - "kawanishi.hyogo.jp", - "miki.hyogo.jp", - "minamiawaji.hyogo.jp", - "nishinomiya.hyogo.jp", - "nishiwaki.hyogo.jp", - "ono.hyogo.jp", - "sanda.hyogo.jp", - "sannan.hyogo.jp", - "sasayama.hyogo.jp", - "sayo.hyogo.jp", - "shingu.hyogo.jp", - "shinonsen.hyogo.jp", - "shiso.hyogo.jp", - "sumoto.hyogo.jp", - "taishi.hyogo.jp", - "taka.hyogo.jp", - "takarazuka.hyogo.jp", - "takasago.hyogo.jp", - "takino.hyogo.jp", - "tamba.hyogo.jp", - "tatsuno.hyogo.jp", - "toyooka.hyogo.jp", - "yabu.hyogo.jp", - "yashiro.hyogo.jp", - "yoka.hyogo.jp", - "yokawa.hyogo.jp", - "ami.ibaraki.jp", - "asahi.ibaraki.jp", - "bando.ibaraki.jp", - "chikusei.ibaraki.jp", - "daigo.ibaraki.jp", - "fujishiro.ibaraki.jp", - "hitachi.ibaraki.jp", - "hitachinaka.ibaraki.jp", - "hitachiomiya.ibaraki.jp", - "hitachiota.ibaraki.jp", - "ibaraki.ibaraki.jp", - "ina.ibaraki.jp", - "inashiki.ibaraki.jp", - "itako.ibaraki.jp", - "iwama.ibaraki.jp", - "joso.ibaraki.jp", - "kamisu.ibaraki.jp", - "kasama.ibaraki.jp", - "kashima.ibaraki.jp", - "kasumigaura.ibaraki.jp", - "koga.ibaraki.jp", - "miho.ibaraki.jp", - "mito.ibaraki.jp", - "moriya.ibaraki.jp", - "naka.ibaraki.jp", - "namegata.ibaraki.jp", - "oarai.ibaraki.jp", - "ogawa.ibaraki.jp", - "omitama.ibaraki.jp", - "ryugasaki.ibaraki.jp", - "sakai.ibaraki.jp", - "sakuragawa.ibaraki.jp", - "shimodate.ibaraki.jp", - "shimotsuma.ibaraki.jp", - "shirosato.ibaraki.jp", - "sowa.ibaraki.jp", - "suifu.ibaraki.jp", - "takahagi.ibaraki.jp", - "tamatsukuri.ibaraki.jp", - "tokai.ibaraki.jp", - "tomobe.ibaraki.jp", - "tone.ibaraki.jp", - "toride.ibaraki.jp", - "tsuchiura.ibaraki.jp", - "tsukuba.ibaraki.jp", - "uchihara.ibaraki.jp", - "ushiku.ibaraki.jp", - "yachiyo.ibaraki.jp", - "yamagata.ibaraki.jp", - "yawara.ibaraki.jp", - "yuki.ibaraki.jp", - "anamizu.ishikawa.jp", - "hakui.ishikawa.jp", - "hakusan.ishikawa.jp", - "kaga.ishikawa.jp", - "kahoku.ishikawa.jp", - "kanazawa.ishikawa.jp", - "kawakita.ishikawa.jp", - "komatsu.ishikawa.jp", - "nakanoto.ishikawa.jp", - "nanao.ishikawa.jp", - "nomi.ishikawa.jp", - "nonoichi.ishikawa.jp", - "noto.ishikawa.jp", - "shika.ishikawa.jp", - "suzu.ishikawa.jp", - "tsubata.ishikawa.jp", - "tsurugi.ishikawa.jp", - "uchinada.ishikawa.jp", - "wajima.ishikawa.jp", - "fudai.iwate.jp", - "fujisawa.iwate.jp", - "hanamaki.iwate.jp", - "hiraizumi.iwate.jp", - "hirono.iwate.jp", - "ichinohe.iwate.jp", - "ichinoseki.iwate.jp", - "iwaizumi.iwate.jp", - "iwate.iwate.jp", - "joboji.iwate.jp", - "kamaishi.iwate.jp", - "kanegasaki.iwate.jp", - "karumai.iwate.jp", - "kawai.iwate.jp", - "kitakami.iwate.jp", - "kuji.iwate.jp", - "kunohe.iwate.jp", - "kuzumaki.iwate.jp", - "miyako.iwate.jp", - "mizusawa.iwate.jp", - "morioka.iwate.jp", - "ninohe.iwate.jp", - "noda.iwate.jp", - "ofunato.iwate.jp", - "oshu.iwate.jp", - "otsuchi.iwate.jp", - "rikuzentakata.iwate.jp", - "shiwa.iwate.jp", - "shizukuishi.iwate.jp", - "sumita.iwate.jp", - "tanohata.iwate.jp", - "tono.iwate.jp", - "yahaba.iwate.jp", - "yamada.iwate.jp", - "ayagawa.kagawa.jp", - "higashikagawa.kagawa.jp", - "kanonji.kagawa.jp", - "kotohira.kagawa.jp", - "manno.kagawa.jp", - "marugame.kagawa.jp", - "mitoyo.kagawa.jp", - "naoshima.kagawa.jp", - "sanuki.kagawa.jp", - "tadotsu.kagawa.jp", - "takamatsu.kagawa.jp", - "tonosho.kagawa.jp", - "uchinomi.kagawa.jp", - "utazu.kagawa.jp", - "zentsuji.kagawa.jp", - "akune.kagoshima.jp", - "amami.kagoshima.jp", - "hioki.kagoshima.jp", - "isa.kagoshima.jp", - "isen.kagoshima.jp", - "izumi.kagoshima.jp", - "kagoshima.kagoshima.jp", - "kanoya.kagoshima.jp", - "kawanabe.kagoshima.jp", - "kinko.kagoshima.jp", - "kouyama.kagoshima.jp", - "makurazaki.kagoshima.jp", - "matsumoto.kagoshima.jp", - "minamitane.kagoshima.jp", - "nakatane.kagoshima.jp", - "nishinoomote.kagoshima.jp", - "satsumasendai.kagoshima.jp", - "soo.kagoshima.jp", - "tarumizu.kagoshima.jp", - "yusui.kagoshima.jp", - "aikawa.kanagawa.jp", - "atsugi.kanagawa.jp", - "ayase.kanagawa.jp", - "chigasaki.kanagawa.jp", - "ebina.kanagawa.jp", - "fujisawa.kanagawa.jp", - "hadano.kanagawa.jp", - "hakone.kanagawa.jp", - "hiratsuka.kanagawa.jp", - "isehara.kanagawa.jp", - "kaisei.kanagawa.jp", - "kamakura.kanagawa.jp", - "kiyokawa.kanagawa.jp", - "matsuda.kanagawa.jp", - "minamiashigara.kanagawa.jp", - "miura.kanagawa.jp", - "nakai.kanagawa.jp", - "ninomiya.kanagawa.jp", - "odawara.kanagawa.jp", - "oi.kanagawa.jp", - "oiso.kanagawa.jp", - "sagamihara.kanagawa.jp", - "samukawa.kanagawa.jp", - "tsukui.kanagawa.jp", - "yamakita.kanagawa.jp", - "yamato.kanagawa.jp", - "yokosuka.kanagawa.jp", - "yugawara.kanagawa.jp", - "zama.kanagawa.jp", - "zushi.kanagawa.jp", - "aki.kochi.jp", - "geisei.kochi.jp", - "hidaka.kochi.jp", - "higashitsuno.kochi.jp", - "ino.kochi.jp", - "kagami.kochi.jp", - "kami.kochi.jp", - "kitagawa.kochi.jp", - "kochi.kochi.jp", - "mihara.kochi.jp", - "motoyama.kochi.jp", - "muroto.kochi.jp", - "nahari.kochi.jp", - "nakamura.kochi.jp", - "nankoku.kochi.jp", - "nishitosa.kochi.jp", - "niyodogawa.kochi.jp", - "ochi.kochi.jp", - "okawa.kochi.jp", - "otoyo.kochi.jp", - "otsuki.kochi.jp", - "sakawa.kochi.jp", - "sukumo.kochi.jp", - "susaki.kochi.jp", - "tosa.kochi.jp", - "tosashimizu.kochi.jp", - "toyo.kochi.jp", - "tsuno.kochi.jp", - "umaji.kochi.jp", - "yasuda.kochi.jp", - "yusuhara.kochi.jp", - "amakusa.kumamoto.jp", - "arao.kumamoto.jp", - "aso.kumamoto.jp", - "choyo.kumamoto.jp", - "gyokuto.kumamoto.jp", - "kamiamakusa.kumamoto.jp", - "kikuchi.kumamoto.jp", - "kumamoto.kumamoto.jp", - "mashiki.kumamoto.jp", - "mifune.kumamoto.jp", - "minamata.kumamoto.jp", - "minamioguni.kumamoto.jp", - "nagasu.kumamoto.jp", - "nishihara.kumamoto.jp", - "oguni.kumamoto.jp", - "ozu.kumamoto.jp", - "sumoto.kumamoto.jp", - "takamori.kumamoto.jp", - "uki.kumamoto.jp", - "uto.kumamoto.jp", - "yamaga.kumamoto.jp", - "yamato.kumamoto.jp", - "yatsushiro.kumamoto.jp", - "ayabe.kyoto.jp", - "fukuchiyama.kyoto.jp", - "higashiyama.kyoto.jp", - "ide.kyoto.jp", - "ine.kyoto.jp", - "joyo.kyoto.jp", - "kameoka.kyoto.jp", - "kamo.kyoto.jp", - "kita.kyoto.jp", - "kizu.kyoto.jp", - "kumiyama.kyoto.jp", - "kyotamba.kyoto.jp", - "kyotanabe.kyoto.jp", - "kyotango.kyoto.jp", - "maizuru.kyoto.jp", - "minami.kyoto.jp", - "minamiyamashiro.kyoto.jp", - "miyazu.kyoto.jp", - "muko.kyoto.jp", - "nagaokakyo.kyoto.jp", - "nakagyo.kyoto.jp", - "nantan.kyoto.jp", - "oyamazaki.kyoto.jp", - "sakyo.kyoto.jp", - "seika.kyoto.jp", - "tanabe.kyoto.jp", - "uji.kyoto.jp", - "ujitawara.kyoto.jp", - "wazuka.kyoto.jp", - "yamashina.kyoto.jp", - "yawata.kyoto.jp", - "asahi.mie.jp", - "inabe.mie.jp", - "ise.mie.jp", - "kameyama.mie.jp", - "kawagoe.mie.jp", - "kiho.mie.jp", - "kisosaki.mie.jp", - "kiwa.mie.jp", - "komono.mie.jp", - "kumano.mie.jp", - "kuwana.mie.jp", - "matsusaka.mie.jp", - "meiwa.mie.jp", - "mihama.mie.jp", - "minamiise.mie.jp", - "misugi.mie.jp", - "miyama.mie.jp", - "nabari.mie.jp", - "shima.mie.jp", - "suzuka.mie.jp", - "tado.mie.jp", - "taiki.mie.jp", - "taki.mie.jp", - "tamaki.mie.jp", - "toba.mie.jp", - "tsu.mie.jp", - "udono.mie.jp", - "ureshino.mie.jp", - "watarai.mie.jp", - "yokkaichi.mie.jp", - "furukawa.miyagi.jp", - "higashimatsushima.miyagi.jp", - "ishinomaki.miyagi.jp", - "iwanuma.miyagi.jp", - "kakuda.miyagi.jp", - "kami.miyagi.jp", - "kawasaki.miyagi.jp", - "marumori.miyagi.jp", - "matsushima.miyagi.jp", - "minamisanriku.miyagi.jp", - "misato.miyagi.jp", - "murata.miyagi.jp", - "natori.miyagi.jp", - "ogawara.miyagi.jp", - "ohira.miyagi.jp", - "onagawa.miyagi.jp", - "osaki.miyagi.jp", - "rifu.miyagi.jp", - "semine.miyagi.jp", - "shibata.miyagi.jp", - "shichikashuku.miyagi.jp", - "shikama.miyagi.jp", - "shiogama.miyagi.jp", - "shiroishi.miyagi.jp", - "tagajo.miyagi.jp", - "taiwa.miyagi.jp", - "tome.miyagi.jp", - "tomiya.miyagi.jp", - "wakuya.miyagi.jp", - "watari.miyagi.jp", - "yamamoto.miyagi.jp", - "zao.miyagi.jp", - "aya.miyazaki.jp", - "ebino.miyazaki.jp", - "gokase.miyazaki.jp", - "hyuga.miyazaki.jp", - "kadogawa.miyazaki.jp", - "kawaminami.miyazaki.jp", - "kijo.miyazaki.jp", - "kitagawa.miyazaki.jp", - "kitakata.miyazaki.jp", - "kitaura.miyazaki.jp", - "kobayashi.miyazaki.jp", - "kunitomi.miyazaki.jp", - "kushima.miyazaki.jp", - "mimata.miyazaki.jp", - "miyakonojo.miyazaki.jp", - "miyazaki.miyazaki.jp", - "morotsuka.miyazaki.jp", - "nichinan.miyazaki.jp", - "nishimera.miyazaki.jp", - "nobeoka.miyazaki.jp", - "saito.miyazaki.jp", - "shiiba.miyazaki.jp", - "shintomi.miyazaki.jp", - "takaharu.miyazaki.jp", - "takanabe.miyazaki.jp", - "takazaki.miyazaki.jp", - "tsuno.miyazaki.jp", - "achi.nagano.jp", - "agematsu.nagano.jp", - "anan.nagano.jp", - "aoki.nagano.jp", - "asahi.nagano.jp", - "azumino.nagano.jp", - "chikuhoku.nagano.jp", - "chikuma.nagano.jp", - "chino.nagano.jp", - "fujimi.nagano.jp", - "hakuba.nagano.jp", - "hara.nagano.jp", - "hiraya.nagano.jp", - "iida.nagano.jp", - "iijima.nagano.jp", - "iiyama.nagano.jp", - "iizuna.nagano.jp", - "ikeda.nagano.jp", - "ikusaka.nagano.jp", - "ina.nagano.jp", - "karuizawa.nagano.jp", - "kawakami.nagano.jp", - "kiso.nagano.jp", - "kisofukushima.nagano.jp", - "kitaaiki.nagano.jp", - "komagane.nagano.jp", - "komoro.nagano.jp", - "matsukawa.nagano.jp", - "matsumoto.nagano.jp", - "miasa.nagano.jp", - "minamiaiki.nagano.jp", - "minamimaki.nagano.jp", - "minamiminowa.nagano.jp", - "minowa.nagano.jp", - "miyada.nagano.jp", - "miyota.nagano.jp", - "mochizuki.nagano.jp", - "nagano.nagano.jp", - "nagawa.nagano.jp", - "nagiso.nagano.jp", - "nakagawa.nagano.jp", - "nakano.nagano.jp", - "nozawaonsen.nagano.jp", - "obuse.nagano.jp", - "ogawa.nagano.jp", - "okaya.nagano.jp", - "omachi.nagano.jp", - "omi.nagano.jp", - "ookuwa.nagano.jp", - "ooshika.nagano.jp", - "otaki.nagano.jp", - "otari.nagano.jp", - "sakae.nagano.jp", - "sakaki.nagano.jp", - "saku.nagano.jp", - "sakuho.nagano.jp", - "shimosuwa.nagano.jp", - "shinanomachi.nagano.jp", - "shiojiri.nagano.jp", - "suwa.nagano.jp", - "suzaka.nagano.jp", - "takagi.nagano.jp", - "takamori.nagano.jp", - "takayama.nagano.jp", - "tateshina.nagano.jp", - "tatsuno.nagano.jp", - "togakushi.nagano.jp", - "togura.nagano.jp", - "tomi.nagano.jp", - "ueda.nagano.jp", - "wada.nagano.jp", - "yamagata.nagano.jp", - "yamanouchi.nagano.jp", - "yasaka.nagano.jp", - "yasuoka.nagano.jp", - "chijiwa.nagasaki.jp", - "futsu.nagasaki.jp", - "goto.nagasaki.jp", - "hasami.nagasaki.jp", - "hirado.nagasaki.jp", - "iki.nagasaki.jp", - "isahaya.nagasaki.jp", - "kawatana.nagasaki.jp", - "kuchinotsu.nagasaki.jp", - "matsuura.nagasaki.jp", - "nagasaki.nagasaki.jp", - "obama.nagasaki.jp", - "omura.nagasaki.jp", - "oseto.nagasaki.jp", - "saikai.nagasaki.jp", - "sasebo.nagasaki.jp", - "seihi.nagasaki.jp", - "shimabara.nagasaki.jp", - "shinkamigoto.nagasaki.jp", - "togitsu.nagasaki.jp", - "tsushima.nagasaki.jp", - "unzen.nagasaki.jp", - "ando.nara.jp", - "gose.nara.jp", - "heguri.nara.jp", - "higashiyoshino.nara.jp", - "ikaruga.nara.jp", - "ikoma.nara.jp", - "kamikitayama.nara.jp", - "kanmaki.nara.jp", - "kashiba.nara.jp", - "kashihara.nara.jp", - "katsuragi.nara.jp", - "kawai.nara.jp", - "kawakami.nara.jp", - "kawanishi.nara.jp", - "koryo.nara.jp", - "kurotaki.nara.jp", - "mitsue.nara.jp", - "miyake.nara.jp", - "nara.nara.jp", - "nosegawa.nara.jp", - "oji.nara.jp", - "ouda.nara.jp", - "oyodo.nara.jp", - "sakurai.nara.jp", - "sango.nara.jp", - "shimoichi.nara.jp", - "shimokitayama.nara.jp", - "shinjo.nara.jp", - "soni.nara.jp", - "takatori.nara.jp", - "tawaramoto.nara.jp", - "tenkawa.nara.jp", - "tenri.nara.jp", - "uda.nara.jp", - "yamatokoriyama.nara.jp", - "yamatotakada.nara.jp", - "yamazoe.nara.jp", - "yoshino.nara.jp", - "aga.niigata.jp", - "agano.niigata.jp", - "gosen.niigata.jp", - "itoigawa.niigata.jp", - "izumozaki.niigata.jp", - "joetsu.niigata.jp", - "kamo.niigata.jp", - "kariwa.niigata.jp", - "kashiwazaki.niigata.jp", - "minamiuonuma.niigata.jp", - "mitsuke.niigata.jp", - "muika.niigata.jp", - "murakami.niigata.jp", - "myoko.niigata.jp", - "nagaoka.niigata.jp", - "niigata.niigata.jp", - "ojiya.niigata.jp", - "omi.niigata.jp", - "sado.niigata.jp", - "sanjo.niigata.jp", - "seiro.niigata.jp", - "seirou.niigata.jp", - "sekikawa.niigata.jp", - "shibata.niigata.jp", - "tagami.niigata.jp", - "tainai.niigata.jp", - "tochio.niigata.jp", - "tokamachi.niigata.jp", - "tsubame.niigata.jp", - "tsunan.niigata.jp", - "uonuma.niigata.jp", - "yahiko.niigata.jp", - "yoita.niigata.jp", - "yuzawa.niigata.jp", - "beppu.oita.jp", - "bungoono.oita.jp", - "bungotakada.oita.jp", - "hasama.oita.jp", - "hiji.oita.jp", - "himeshima.oita.jp", - "hita.oita.jp", - "kamitsue.oita.jp", - "kokonoe.oita.jp", - "kuju.oita.jp", - "kunisaki.oita.jp", - "kusu.oita.jp", - "oita.oita.jp", - "saiki.oita.jp", - "taketa.oita.jp", - "tsukumi.oita.jp", - "usa.oita.jp", - "usuki.oita.jp", - "yufu.oita.jp", - "akaiwa.okayama.jp", - "asakuchi.okayama.jp", - "bizen.okayama.jp", - "hayashima.okayama.jp", - "ibara.okayama.jp", - "kagamino.okayama.jp", - "kasaoka.okayama.jp", - "kibichuo.okayama.jp", - "kumenan.okayama.jp", - "kurashiki.okayama.jp", - "maniwa.okayama.jp", - "misaki.okayama.jp", - "nagi.okayama.jp", - "niimi.okayama.jp", - "nishiawakura.okayama.jp", - "okayama.okayama.jp", - "satosho.okayama.jp", - "setouchi.okayama.jp", - "shinjo.okayama.jp", - "shoo.okayama.jp", - "soja.okayama.jp", - "takahashi.okayama.jp", - "tamano.okayama.jp", - "tsuyama.okayama.jp", - "wake.okayama.jp", - "yakage.okayama.jp", - "aguni.okinawa.jp", - "ginowan.okinawa.jp", - "ginoza.okinawa.jp", - "gushikami.okinawa.jp", - "haebaru.okinawa.jp", - "higashi.okinawa.jp", - "hirara.okinawa.jp", - "iheya.okinawa.jp", - "ishigaki.okinawa.jp", - "ishikawa.okinawa.jp", - "itoman.okinawa.jp", - "izena.okinawa.jp", - "kadena.okinawa.jp", - "kin.okinawa.jp", - "kitadaito.okinawa.jp", - "kitanakagusuku.okinawa.jp", - "kumejima.okinawa.jp", - "kunigami.okinawa.jp", - "minamidaito.okinawa.jp", - "motobu.okinawa.jp", - "nago.okinawa.jp", - "naha.okinawa.jp", - "nakagusuku.okinawa.jp", - "nakijin.okinawa.jp", - "nanjo.okinawa.jp", - "nishihara.okinawa.jp", - "ogimi.okinawa.jp", - "okinawa.okinawa.jp", - "onna.okinawa.jp", - "shimoji.okinawa.jp", - "taketomi.okinawa.jp", - "tarama.okinawa.jp", - "tokashiki.okinawa.jp", - "tomigusuku.okinawa.jp", - "tonaki.okinawa.jp", - "urasoe.okinawa.jp", - "uruma.okinawa.jp", - "yaese.okinawa.jp", - "yomitan.okinawa.jp", - "yonabaru.okinawa.jp", - "yonaguni.okinawa.jp", - "zamami.okinawa.jp", - "abeno.osaka.jp", - "chihayaakasaka.osaka.jp", - "chuo.osaka.jp", - "daito.osaka.jp", - "fujiidera.osaka.jp", - "habikino.osaka.jp", - "hannan.osaka.jp", - "higashiosaka.osaka.jp", - "higashisumiyoshi.osaka.jp", - "higashiyodogawa.osaka.jp", - "hirakata.osaka.jp", - "ibaraki.osaka.jp", - "ikeda.osaka.jp", - "izumi.osaka.jp", - "izumiotsu.osaka.jp", - "izumisano.osaka.jp", - "kadoma.osaka.jp", - "kaizuka.osaka.jp", - "kanan.osaka.jp", - "kashiwara.osaka.jp", - "katano.osaka.jp", - "kawachinagano.osaka.jp", - "kishiwada.osaka.jp", - "kita.osaka.jp", - "kumatori.osaka.jp", - "matsubara.osaka.jp", - "minato.osaka.jp", - "minoh.osaka.jp", - "misaki.osaka.jp", - "moriguchi.osaka.jp", - "neyagawa.osaka.jp", - "nishi.osaka.jp", - "nose.osaka.jp", - "osakasayama.osaka.jp", - "sakai.osaka.jp", - "sayama.osaka.jp", - "sennan.osaka.jp", - "settsu.osaka.jp", - "shijonawate.osaka.jp", - "shimamoto.osaka.jp", - "suita.osaka.jp", - "tadaoka.osaka.jp", - "taishi.osaka.jp", - "tajiri.osaka.jp", - "takaishi.osaka.jp", - "takatsuki.osaka.jp", - "tondabayashi.osaka.jp", - "toyonaka.osaka.jp", - "toyono.osaka.jp", - "yao.osaka.jp", - "ariake.saga.jp", - "arita.saga.jp", - "fukudomi.saga.jp", - "genkai.saga.jp", - "hamatama.saga.jp", - "hizen.saga.jp", - "imari.saga.jp", - "kamimine.saga.jp", - "kanzaki.saga.jp", - "karatsu.saga.jp", - "kashima.saga.jp", - "kitagata.saga.jp", - "kitahata.saga.jp", - "kiyama.saga.jp", - "kouhoku.saga.jp", - "kyuragi.saga.jp", - "nishiarita.saga.jp", - "ogi.saga.jp", - "omachi.saga.jp", - "ouchi.saga.jp", - "saga.saga.jp", - "shiroishi.saga.jp", - "taku.saga.jp", - "tara.saga.jp", - "tosu.saga.jp", - "yoshinogari.saga.jp", - "arakawa.saitama.jp", - "asaka.saitama.jp", - "chichibu.saitama.jp", - "fujimi.saitama.jp", - "fujimino.saitama.jp", - "fukaya.saitama.jp", - "hanno.saitama.jp", - "hanyu.saitama.jp", - "hasuda.saitama.jp", - "hatogaya.saitama.jp", - "hatoyama.saitama.jp", - "hidaka.saitama.jp", - "higashichichibu.saitama.jp", - "higashimatsuyama.saitama.jp", - "honjo.saitama.jp", - "ina.saitama.jp", - "iruma.saitama.jp", - "iwatsuki.saitama.jp", - "kamiizumi.saitama.jp", - "kamikawa.saitama.jp", - "kamisato.saitama.jp", - "kasukabe.saitama.jp", - "kawagoe.saitama.jp", - "kawaguchi.saitama.jp", - "kawajima.saitama.jp", - "kazo.saitama.jp", - "kitamoto.saitama.jp", - "koshigaya.saitama.jp", - "kounosu.saitama.jp", - "kuki.saitama.jp", - "kumagaya.saitama.jp", - "matsubushi.saitama.jp", - "minano.saitama.jp", - "misato.saitama.jp", - "miyashiro.saitama.jp", - "miyoshi.saitama.jp", - "moroyama.saitama.jp", - "nagatoro.saitama.jp", - "namegawa.saitama.jp", - "niiza.saitama.jp", - "ogano.saitama.jp", - "ogawa.saitama.jp", - "ogose.saitama.jp", - "okegawa.saitama.jp", - "omiya.saitama.jp", - "otaki.saitama.jp", - "ranzan.saitama.jp", - "ryokami.saitama.jp", - "saitama.saitama.jp", - "sakado.saitama.jp", - "satte.saitama.jp", - "sayama.saitama.jp", - "shiki.saitama.jp", - "shiraoka.saitama.jp", - "soka.saitama.jp", - "sugito.saitama.jp", - "toda.saitama.jp", - "tokigawa.saitama.jp", - "tokorozawa.saitama.jp", - "tsurugashima.saitama.jp", - "urawa.saitama.jp", - "warabi.saitama.jp", - "yashio.saitama.jp", - "yokoze.saitama.jp", - "yono.saitama.jp", - "yorii.saitama.jp", - "yoshida.saitama.jp", - "yoshikawa.saitama.jp", - "yoshimi.saitama.jp", - "aisho.shiga.jp", - "gamo.shiga.jp", - "higashiomi.shiga.jp", - "hikone.shiga.jp", - "koka.shiga.jp", - "konan.shiga.jp", - "kosei.shiga.jp", - "koto.shiga.jp", - "kusatsu.shiga.jp", - "maibara.shiga.jp", - "moriyama.shiga.jp", - "nagahama.shiga.jp", - "nishiazai.shiga.jp", - "notogawa.shiga.jp", - "omihachiman.shiga.jp", - "otsu.shiga.jp", - "ritto.shiga.jp", - "ryuoh.shiga.jp", - "takashima.shiga.jp", - "takatsuki.shiga.jp", - "torahime.shiga.jp", - "toyosato.shiga.jp", - "yasu.shiga.jp", - "akagi.shimane.jp", - "ama.shimane.jp", - "gotsu.shimane.jp", - "hamada.shimane.jp", - "higashiizumo.shimane.jp", - "hikawa.shimane.jp", - "hikimi.shimane.jp", - "izumo.shimane.jp", - "kakinoki.shimane.jp", - "masuda.shimane.jp", - "matsue.shimane.jp", - "misato.shimane.jp", - "nishinoshima.shimane.jp", - "ohda.shimane.jp", - "okinoshima.shimane.jp", - "okuizumo.shimane.jp", - "shimane.shimane.jp", - "tamayu.shimane.jp", - "tsuwano.shimane.jp", - "unnan.shimane.jp", - "yakumo.shimane.jp", - "yasugi.shimane.jp", - "yatsuka.shimane.jp", - "arai.shizuoka.jp", - "atami.shizuoka.jp", - "fuji.shizuoka.jp", - "fujieda.shizuoka.jp", - "fujikawa.shizuoka.jp", - "fujinomiya.shizuoka.jp", - "fukuroi.shizuoka.jp", - "gotemba.shizuoka.jp", - "haibara.shizuoka.jp", - "hamamatsu.shizuoka.jp", - "higashiizu.shizuoka.jp", - "ito.shizuoka.jp", - "iwata.shizuoka.jp", - "izu.shizuoka.jp", - "izunokuni.shizuoka.jp", - "kakegawa.shizuoka.jp", - "kannami.shizuoka.jp", - "kawanehon.shizuoka.jp", - "kawazu.shizuoka.jp", - "kikugawa.shizuoka.jp", - "kosai.shizuoka.jp", - "makinohara.shizuoka.jp", - "matsuzaki.shizuoka.jp", - "minamiizu.shizuoka.jp", - "mishima.shizuoka.jp", - "morimachi.shizuoka.jp", - "nishiizu.shizuoka.jp", - "numazu.shizuoka.jp", - "omaezaki.shizuoka.jp", - "shimada.shizuoka.jp", - "shimizu.shizuoka.jp", - "shimoda.shizuoka.jp", - "shizuoka.shizuoka.jp", - "susono.shizuoka.jp", - "yaizu.shizuoka.jp", - "yoshida.shizuoka.jp", - "ashikaga.tochigi.jp", - "bato.tochigi.jp", - "haga.tochigi.jp", - "ichikai.tochigi.jp", - "iwafune.tochigi.jp", - "kaminokawa.tochigi.jp", - "kanuma.tochigi.jp", - "karasuyama.tochigi.jp", - "kuroiso.tochigi.jp", - "mashiko.tochigi.jp", - "mibu.tochigi.jp", - "moka.tochigi.jp", - "motegi.tochigi.jp", - "nasu.tochigi.jp", - "nasushiobara.tochigi.jp", - "nikko.tochigi.jp", - "nishikata.tochigi.jp", - "nogi.tochigi.jp", - "ohira.tochigi.jp", - "ohtawara.tochigi.jp", - "oyama.tochigi.jp", - "sakura.tochigi.jp", - "sano.tochigi.jp", - "shimotsuke.tochigi.jp", - "shioya.tochigi.jp", - "takanezawa.tochigi.jp", - "tochigi.tochigi.jp", - "tsuga.tochigi.jp", - "ujiie.tochigi.jp", - "utsunomiya.tochigi.jp", - "yaita.tochigi.jp", - "aizumi.tokushima.jp", - "anan.tokushima.jp", - "ichiba.tokushima.jp", - "itano.tokushima.jp", - "kainan.tokushima.jp", - "komatsushima.tokushima.jp", - "matsushige.tokushima.jp", - "mima.tokushima.jp", - "minami.tokushima.jp", - "miyoshi.tokushima.jp", - "mugi.tokushima.jp", - "nakagawa.tokushima.jp", - "naruto.tokushima.jp", - "sanagochi.tokushima.jp", - "shishikui.tokushima.jp", - "tokushima.tokushima.jp", - "wajiki.tokushima.jp", - "adachi.tokyo.jp", - "akiruno.tokyo.jp", - "akishima.tokyo.jp", - "aogashima.tokyo.jp", - "arakawa.tokyo.jp", - "bunkyo.tokyo.jp", - "chiyoda.tokyo.jp", - "chofu.tokyo.jp", - "chuo.tokyo.jp", - "edogawa.tokyo.jp", - "fuchu.tokyo.jp", - "fussa.tokyo.jp", - "hachijo.tokyo.jp", - "hachioji.tokyo.jp", - "hamura.tokyo.jp", - "higashikurume.tokyo.jp", - "higashimurayama.tokyo.jp", - "higashiyamato.tokyo.jp", - "hino.tokyo.jp", - "hinode.tokyo.jp", - "hinohara.tokyo.jp", - "inagi.tokyo.jp", - "itabashi.tokyo.jp", - "katsushika.tokyo.jp", - "kita.tokyo.jp", - "kiyose.tokyo.jp", - "kodaira.tokyo.jp", - "koganei.tokyo.jp", - "kokubunji.tokyo.jp", - "komae.tokyo.jp", - "koto.tokyo.jp", - "kouzushima.tokyo.jp", - "kunitachi.tokyo.jp", - "machida.tokyo.jp", - "meguro.tokyo.jp", - "minato.tokyo.jp", - "mitaka.tokyo.jp", - "mizuho.tokyo.jp", - "musashimurayama.tokyo.jp", - "musashino.tokyo.jp", - "nakano.tokyo.jp", - "nerima.tokyo.jp", - "ogasawara.tokyo.jp", - "okutama.tokyo.jp", - "ome.tokyo.jp", - "oshima.tokyo.jp", - "ota.tokyo.jp", - "setagaya.tokyo.jp", - "shibuya.tokyo.jp", - "shinagawa.tokyo.jp", - "shinjuku.tokyo.jp", - "suginami.tokyo.jp", - "sumida.tokyo.jp", - "tachikawa.tokyo.jp", - "taito.tokyo.jp", - "tama.tokyo.jp", - "toshima.tokyo.jp", - "chizu.tottori.jp", - "hino.tottori.jp", - "kawahara.tottori.jp", - "koge.tottori.jp", - "kotoura.tottori.jp", - "misasa.tottori.jp", - "nanbu.tottori.jp", - "nichinan.tottori.jp", - "sakaiminato.tottori.jp", - "tottori.tottori.jp", - "wakasa.tottori.jp", - "yazu.tottori.jp", - "yonago.tottori.jp", - "asahi.toyama.jp", - "fuchu.toyama.jp", - "fukumitsu.toyama.jp", - "funahashi.toyama.jp", - "himi.toyama.jp", - "imizu.toyama.jp", - "inami.toyama.jp", - "johana.toyama.jp", - "kamiichi.toyama.jp", - "kurobe.toyama.jp", - "nakaniikawa.toyama.jp", - "namerikawa.toyama.jp", - "nanto.toyama.jp", - "nyuzen.toyama.jp", - "oyabe.toyama.jp", - "taira.toyama.jp", - "takaoka.toyama.jp", - "tateyama.toyama.jp", - "toga.toyama.jp", - "tonami.toyama.jp", - "toyama.toyama.jp", - "unazuki.toyama.jp", - "uozu.toyama.jp", - "yamada.toyama.jp", - "arida.wakayama.jp", - "aridagawa.wakayama.jp", - "gobo.wakayama.jp", - "hashimoto.wakayama.jp", - "hidaka.wakayama.jp", - "hirogawa.wakayama.jp", - "inami.wakayama.jp", - "iwade.wakayama.jp", - "kainan.wakayama.jp", - "kamitonda.wakayama.jp", - "katsuragi.wakayama.jp", - "kimino.wakayama.jp", - "kinokawa.wakayama.jp", - "kitayama.wakayama.jp", - "koya.wakayama.jp", - "koza.wakayama.jp", - "kozagawa.wakayama.jp", - "kudoyama.wakayama.jp", - "kushimoto.wakayama.jp", - "mihama.wakayama.jp", - "misato.wakayama.jp", - "nachikatsuura.wakayama.jp", - "shingu.wakayama.jp", - "shirahama.wakayama.jp", - "taiji.wakayama.jp", - "tanabe.wakayama.jp", - "wakayama.wakayama.jp", - "yuasa.wakayama.jp", - "yura.wakayama.jp", - "asahi.yamagata.jp", - "funagata.yamagata.jp", - "higashine.yamagata.jp", - "iide.yamagata.jp", - "kahoku.yamagata.jp", - "kaminoyama.yamagata.jp", - "kaneyama.yamagata.jp", - "kawanishi.yamagata.jp", - "mamurogawa.yamagata.jp", - "mikawa.yamagata.jp", - "murayama.yamagata.jp", - "nagai.yamagata.jp", - "nakayama.yamagata.jp", - "nanyo.yamagata.jp", - "nishikawa.yamagata.jp", - "obanazawa.yamagata.jp", - "oe.yamagata.jp", - "oguni.yamagata.jp", - "ohkura.yamagata.jp", - "oishida.yamagata.jp", - "sagae.yamagata.jp", - "sakata.yamagata.jp", - "sakegawa.yamagata.jp", - "shinjo.yamagata.jp", - "shirataka.yamagata.jp", - "shonai.yamagata.jp", - "takahata.yamagata.jp", - "tendo.yamagata.jp", - "tozawa.yamagata.jp", - "tsuruoka.yamagata.jp", - "yamagata.yamagata.jp", - "yamanobe.yamagata.jp", - "yonezawa.yamagata.jp", - "yuza.yamagata.jp", - "abu.yamaguchi.jp", - "hagi.yamaguchi.jp", - "hikari.yamaguchi.jp", - "hofu.yamaguchi.jp", - "iwakuni.yamaguchi.jp", - "kudamatsu.yamaguchi.jp", - "mitou.yamaguchi.jp", - "nagato.yamaguchi.jp", - "oshima.yamaguchi.jp", - "shimonoseki.yamaguchi.jp", - "shunan.yamaguchi.jp", - "tabuse.yamaguchi.jp", - "tokuyama.yamaguchi.jp", - "toyota.yamaguchi.jp", - "ube.yamaguchi.jp", - "yuu.yamaguchi.jp", - "chuo.yamanashi.jp", - "doshi.yamanashi.jp", - "fuefuki.yamanashi.jp", - "fujikawa.yamanashi.jp", - "fujikawaguchiko.yamanashi.jp", - "fujiyoshida.yamanashi.jp", - "hayakawa.yamanashi.jp", - "hokuto.yamanashi.jp", - "ichikawamisato.yamanashi.jp", - "kai.yamanashi.jp", - "kofu.yamanashi.jp", - "koshu.yamanashi.jp", - "kosuge.yamanashi.jp", - "minami-alps.yamanashi.jp", - "minobu.yamanashi.jp", - "nakamichi.yamanashi.jp", - "nanbu.yamanashi.jp", - "narusawa.yamanashi.jp", - "nirasaki.yamanashi.jp", - "nishikatsura.yamanashi.jp", - "oshino.yamanashi.jp", - "otsuki.yamanashi.jp", - "showa.yamanashi.jp", - "tabayama.yamanashi.jp", - "tsuru.yamanashi.jp", - "uenohara.yamanashi.jp", - "yamanakako.yamanashi.jp", - "yamanashi.yamanashi.jp", - "*.ke", - "kg", - "org.kg", - "net.kg", - "com.kg", - "edu.kg", - "gov.kg", - "mil.kg", - "*.kh", - "ki", - "edu.ki", - "biz.ki", - "net.ki", - "org.ki", - "gov.ki", - "info.ki", - "com.ki", - "km", - "org.km", - "nom.km", - "gov.km", - "prd.km", - "tm.km", - "edu.km", - "mil.km", - "ass.km", - "com.km", - "coop.km", - "asso.km", - "presse.km", - "medecin.km", - "notaires.km", - "pharmaciens.km", - "veterinaire.km", - "gouv.km", - "kn", - "net.kn", - "org.kn", - "edu.kn", - "gov.kn", - "kp", - "com.kp", - "edu.kp", - "gov.kp", - "org.kp", - "rep.kp", - "tra.kp", - "kr", - "ac.kr", - "co.kr", - "es.kr", - "go.kr", - "hs.kr", - "kg.kr", - "mil.kr", - "ms.kr", - "ne.kr", - "or.kr", - "pe.kr", - "re.kr", - "sc.kr", - "busan.kr", - "chungbuk.kr", - "chungnam.kr", - "daegu.kr", - "daejeon.kr", - "gangwon.kr", - "gwangju.kr", - "gyeongbuk.kr", - "gyeonggi.kr", - "gyeongnam.kr", - "incheon.kr", - "jeju.kr", - "jeonbuk.kr", - "jeonnam.kr", - "seoul.kr", - "ulsan.kr", - "*.kw", - "ky", - "edu.ky", - "gov.ky", - "com.ky", - "org.ky", - "net.ky", - "kz", - "org.kz", - "edu.kz", - "net.kz", - "gov.kz", - "mil.kz", - "com.kz", - "la", - "int.la", - "net.la", - "info.la", - "edu.la", - "gov.la", - "per.la", - "com.la", - "org.la", - "lb", - "com.lb", - "edu.lb", - "gov.lb", - "net.lb", - "org.lb", - "lc", - "com.lc", - "net.lc", - "co.lc", - "org.lc", - "edu.lc", - "gov.lc", - "li", - "lk", - "gov.lk", - "sch.lk", - "net.lk", - "int.lk", - "com.lk", - "org.lk", - "edu.lk", - "ngo.lk", - "soc.lk", - "web.lk", - "ltd.lk", - "assn.lk", - "grp.lk", - "hotel.lk", - "ac.lk", - "lr", - "com.lr", - "edu.lr", - "gov.lr", - "org.lr", - "net.lr", - "ls", - "co.ls", - "org.ls", - "lt", - "gov.lt", - "lu", - "lv", - "com.lv", - "edu.lv", - "gov.lv", - "org.lv", - "mil.lv", - "id.lv", - "net.lv", - "asn.lv", - "conf.lv", - "ly", - "com.ly", - "net.ly", - "gov.ly", - "plc.ly", - "edu.ly", - "sch.ly", - "med.ly", - "org.ly", - "id.ly", - "ma", - "co.ma", - "net.ma", - "gov.ma", - "org.ma", - "ac.ma", - "press.ma", - "mc", - "tm.mc", - "asso.mc", - "md", - "me", - "co.me", - "net.me", - "org.me", - "edu.me", - "ac.me", - "gov.me", - "its.me", - "priv.me", - "mg", - "org.mg", - "nom.mg", - "gov.mg", - "prd.mg", - "tm.mg", - "edu.mg", - "mil.mg", - "com.mg", - "co.mg", - "mh", - "mil", - "mk", - "com.mk", - "org.mk", - "net.mk", - "edu.mk", - "gov.mk", - "inf.mk", - "name.mk", - "ml", - "com.ml", - "edu.ml", - "gouv.ml", - "gov.ml", - "net.ml", - "org.ml", - "presse.ml", - "*.mm", - "mn", - "gov.mn", - "edu.mn", - "org.mn", - "mo", - "com.mo", - "net.mo", - "org.mo", - "edu.mo", - "gov.mo", - "mobi", - "mp", - "mq", - "mr", - "gov.mr", - "ms", - "com.ms", - "edu.ms", - "gov.ms", - "net.ms", - "org.ms", - "mt", - "com.mt", - "edu.mt", - "net.mt", - "org.mt", - "mu", - "com.mu", - "net.mu", - "org.mu", - "gov.mu", - "ac.mu", - "co.mu", - "or.mu", - "museum", - "academy.museum", - "agriculture.museum", - "air.museum", - "airguard.museum", - "alabama.museum", - "alaska.museum", - "amber.museum", - "ambulance.museum", - "american.museum", - "americana.museum", - "americanantiques.museum", - "americanart.museum", - "amsterdam.museum", - "and.museum", - "annefrank.museum", - "anthro.museum", - "anthropology.museum", - "antiques.museum", - "aquarium.museum", - "arboretum.museum", - "archaeological.museum", - "archaeology.museum", - "architecture.museum", - "art.museum", - "artanddesign.museum", - "artcenter.museum", - "artdeco.museum", - "arteducation.museum", - "artgallery.museum", - "arts.museum", - "artsandcrafts.museum", - "asmatart.museum", - "assassination.museum", - "assisi.museum", - "association.museum", - "astronomy.museum", - "atlanta.museum", - "austin.museum", - "australia.museum", - "automotive.museum", - "aviation.museum", - "axis.museum", - "badajoz.museum", - "baghdad.museum", - "bahn.museum", - "bale.museum", - "baltimore.museum", - "barcelona.museum", - "baseball.museum", - "basel.museum", - "baths.museum", - "bauern.museum", - "beauxarts.museum", - "beeldengeluid.museum", - "bellevue.museum", - "bergbau.museum", - "berkeley.museum", - "berlin.museum", - "bern.museum", - "bible.museum", - "bilbao.museum", - "bill.museum", - "birdart.museum", - "birthplace.museum", - "bonn.museum", - "boston.museum", - "botanical.museum", - "botanicalgarden.museum", - "botanicgarden.museum", - "botany.museum", - "brandywinevalley.museum", - "brasil.museum", - "bristol.museum", - "british.museum", - "britishcolumbia.museum", - "broadcast.museum", - "brunel.museum", - "brussel.museum", - "brussels.museum", - "bruxelles.museum", - "building.museum", - "burghof.museum", - "bus.museum", - "bushey.museum", - "cadaques.museum", - "california.museum", - "cambridge.museum", - "can.museum", - "canada.museum", - "capebreton.museum", - "carrier.museum", - "cartoonart.museum", - "casadelamoneda.museum", - "castle.museum", - "castres.museum", - "celtic.museum", - "center.museum", - "chattanooga.museum", - "cheltenham.museum", - "chesapeakebay.museum", - "chicago.museum", - "children.museum", - "childrens.museum", - "childrensgarden.museum", - "chiropractic.museum", - "chocolate.museum", - "christiansburg.museum", - "cincinnati.museum", - "cinema.museum", - "circus.museum", - "civilisation.museum", - "civilization.museum", - "civilwar.museum", - "clinton.museum", - "clock.museum", - "coal.museum", - "coastaldefence.museum", - "cody.museum", - "coldwar.museum", - "collection.museum", - "colonialwilliamsburg.museum", - "coloradoplateau.museum", - "columbia.museum", - "columbus.museum", - "communication.museum", - "communications.museum", - "community.museum", - "computer.museum", - "computerhistory.museum", - "xn--comunicaes-v6a2o.museum", - "contemporary.museum", - "contemporaryart.museum", - "convent.museum", - "copenhagen.museum", - "corporation.museum", - "xn--correios-e-telecomunicaes-ghc29a.museum", - "corvette.museum", - "costume.museum", - "countryestate.museum", - "county.museum", - "crafts.museum", - "cranbrook.museum", - "creation.museum", - "cultural.museum", - "culturalcenter.museum", - "culture.museum", - "cyber.museum", - "cymru.museum", - "dali.museum", - "dallas.museum", - "database.museum", - "ddr.museum", - "decorativearts.museum", - "delaware.museum", - "delmenhorst.museum", - "denmark.museum", - "depot.museum", - "design.museum", - "detroit.museum", - "dinosaur.museum", - "discovery.museum", - "dolls.museum", - "donostia.museum", - "durham.museum", - "eastafrica.museum", - "eastcoast.museum", - "education.museum", - "educational.museum", - "egyptian.museum", - "eisenbahn.museum", - "elburg.museum", - "elvendrell.museum", - "embroidery.museum", - "encyclopedic.museum", - "england.museum", - "entomology.museum", - "environment.museum", - "environmentalconservation.museum", - "epilepsy.museum", - "essex.museum", - "estate.museum", - "ethnology.museum", - "exeter.museum", - "exhibition.museum", - "family.museum", - "farm.museum", - "farmequipment.museum", - "farmers.museum", - "farmstead.museum", - "field.museum", - "figueres.museum", - "filatelia.museum", - "film.museum", - "fineart.museum", - "finearts.museum", - "finland.museum", - "flanders.museum", - "florida.museum", - "force.museum", - "fortmissoula.museum", - "fortworth.museum", - "foundation.museum", - "francaise.museum", - "frankfurt.museum", - "franziskaner.museum", - "freemasonry.museum", - "freiburg.museum", - "fribourg.museum", - "frog.museum", - "fundacio.museum", - "furniture.museum", - "gallery.museum", - "garden.museum", - "gateway.museum", - "geelvinck.museum", - "gemological.museum", - "geology.museum", - "georgia.museum", - "giessen.museum", - "glas.museum", - "glass.museum", - "gorge.museum", - "grandrapids.museum", - "graz.museum", - "guernsey.museum", - "halloffame.museum", - "hamburg.museum", - "handson.museum", - "harvestcelebration.museum", - "hawaii.museum", - "health.museum", - "heimatunduhren.museum", - "hellas.museum", - "helsinki.museum", - "hembygdsforbund.museum", - "heritage.museum", - "histoire.museum", - "historical.museum", - "historicalsociety.museum", - "historichouses.museum", - "historisch.museum", - "historisches.museum", - "history.museum", - "historyofscience.museum", - "horology.museum", - "house.museum", - "humanities.museum", - "illustration.museum", - "imageandsound.museum", - "indian.museum", - "indiana.museum", - "indianapolis.museum", - "indianmarket.museum", - "intelligence.museum", - "interactive.museum", - "iraq.museum", - "iron.museum", - "isleofman.museum", - "jamison.museum", - "jefferson.museum", - "jerusalem.museum", - "jewelry.museum", - "jewish.museum", - "jewishart.museum", - "jfk.museum", - "journalism.museum", - "judaica.museum", - "judygarland.museum", - "juedisches.museum", - "juif.museum", - "karate.museum", - "karikatur.museum", - "kids.museum", - "koebenhavn.museum", - "koeln.museum", - "kunst.museum", - "kunstsammlung.museum", - "kunstunddesign.museum", - "labor.museum", - "labour.museum", - "lajolla.museum", - "lancashire.museum", - "landes.museum", - "lans.museum", - "xn--lns-qla.museum", - "larsson.museum", - "lewismiller.museum", - "lincoln.museum", - "linz.museum", - "living.museum", - "livinghistory.museum", - "localhistory.museum", - "london.museum", - "losangeles.museum", - "louvre.museum", - "loyalist.museum", - "lucerne.museum", - "luxembourg.museum", - "luzern.museum", - "mad.museum", - "madrid.museum", - "mallorca.museum", - "manchester.museum", - "mansion.museum", - "mansions.museum", - "manx.museum", - "marburg.museum", - "maritime.museum", - "maritimo.museum", - "maryland.museum", - "marylhurst.museum", - "media.museum", - "medical.museum", - "medizinhistorisches.museum", - "meeres.museum", - "memorial.museum", - "mesaverde.museum", - "michigan.museum", - "midatlantic.museum", - "military.museum", - "mill.museum", - "miners.museum", - "mining.museum", - "minnesota.museum", - "missile.museum", - "missoula.museum", - "modern.museum", - "moma.museum", - "money.museum", - "monmouth.museum", - "monticello.museum", - "montreal.museum", - "moscow.museum", - "motorcycle.museum", - "muenchen.museum", - "muenster.museum", - "mulhouse.museum", - "muncie.museum", - "museet.museum", - "museumcenter.museum", - "museumvereniging.museum", - "music.museum", - "national.museum", - "nationalfirearms.museum", - "nationalheritage.museum", - "nativeamerican.museum", - "naturalhistory.museum", - "naturalhistorymuseum.museum", - "naturalsciences.museum", - "nature.museum", - "naturhistorisches.museum", - "natuurwetenschappen.museum", - "naumburg.museum", - "naval.museum", - "nebraska.museum", - "neues.museum", - "newhampshire.museum", - "newjersey.museum", - "newmexico.museum", - "newport.museum", - "newspaper.museum", - "newyork.museum", - "niepce.museum", - "norfolk.museum", - "north.museum", - "nrw.museum", - "nuernberg.museum", - "nuremberg.museum", - "nyc.museum", - "nyny.museum", - "oceanographic.museum", - "oceanographique.museum", - "omaha.museum", - "online.museum", - "ontario.museum", - "openair.museum", - "oregon.museum", - "oregontrail.museum", - "otago.museum", - "oxford.museum", - "pacific.museum", - "paderborn.museum", - "palace.museum", - "paleo.museum", - "palmsprings.museum", - "panama.museum", - "paris.museum", - "pasadena.museum", - "pharmacy.museum", - "philadelphia.museum", - "philadelphiaarea.museum", - "philately.museum", - "phoenix.museum", - "photography.museum", - "pilots.museum", - "pittsburgh.museum", - "planetarium.museum", - "plantation.museum", - "plants.museum", - "plaza.museum", - "portal.museum", - "portland.museum", - "portlligat.museum", - "posts-and-telecommunications.museum", - "preservation.museum", - "presidio.museum", - "press.museum", - "project.museum", - "public.museum", - "pubol.museum", - "quebec.museum", - "railroad.museum", - "railway.museum", - "research.museum", - "resistance.museum", - "riodejaneiro.museum", - "rochester.museum", - "rockart.museum", - "roma.museum", - "russia.museum", - "saintlouis.museum", - "salem.museum", - "salvadordali.museum", - "salzburg.museum", - "sandiego.museum", - "sanfrancisco.museum", - "santabarbara.museum", - "santacruz.museum", - "santafe.museum", - "saskatchewan.museum", - "satx.museum", - "savannahga.museum", - "schlesisches.museum", - "schoenbrunn.museum", - "schokoladen.museum", - "school.museum", - "schweiz.museum", - "science.museum", - "scienceandhistory.museum", - "scienceandindustry.museum", - "sciencecenter.museum", - "sciencecenters.museum", - "science-fiction.museum", - "sciencehistory.museum", - "sciences.museum", - "sciencesnaturelles.museum", - "scotland.museum", - "seaport.museum", - "settlement.museum", - "settlers.museum", - "shell.museum", - "sherbrooke.museum", - "sibenik.museum", - "silk.museum", - "ski.museum", - "skole.museum", - "society.museum", - "sologne.museum", - "soundandvision.museum", - "southcarolina.museum", - "southwest.museum", - "space.museum", - "spy.museum", - "square.museum", - "stadt.museum", - "stalbans.museum", - "starnberg.museum", - "state.museum", - "stateofdelaware.museum", - "station.museum", - "steam.museum", - "steiermark.museum", - "stjohn.museum", - "stockholm.museum", - "stpetersburg.museum", - "stuttgart.museum", - "suisse.museum", - "surgeonshall.museum", - "surrey.museum", - "svizzera.museum", - "sweden.museum", - "sydney.museum", - "tank.museum", - "tcm.museum", - "technology.museum", - "telekommunikation.museum", - "television.museum", - "texas.museum", - "textile.museum", - "theater.museum", - "time.museum", - "timekeeping.museum", - "topology.museum", - "torino.museum", - "touch.museum", - "town.museum", - "transport.museum", - "tree.museum", - "trolley.museum", - "trust.museum", - "trustee.museum", - "uhren.museum", - "ulm.museum", - "undersea.museum", - "university.museum", - "usa.museum", - "usantiques.museum", - "usarts.museum", - "uscountryestate.museum", - "usculture.museum", - "usdecorativearts.museum", - "usgarden.museum", - "ushistory.museum", - "ushuaia.museum", - "uslivinghistory.museum", - "utah.museum", - "uvic.museum", - "valley.museum", - "vantaa.museum", - "versailles.museum", - "viking.museum", - "village.museum", - "virginia.museum", - "virtual.museum", - "virtuel.museum", - "vlaanderen.museum", - "volkenkunde.museum", - "wales.museum", - "wallonie.museum", - "war.museum", - "washingtondc.museum", - "watchandclock.museum", - "watch-and-clock.museum", - "western.museum", - "westfalen.museum", - "whaling.museum", - "wildlife.museum", - "williamsburg.museum", - "windmill.museum", - "workshop.museum", - "york.museum", - "yorkshire.museum", - "yosemite.museum", - "youth.museum", - "zoological.museum", - "zoology.museum", - "xn--9dbhblg6di.museum", - "xn--h1aegh.museum", - "mv", - "aero.mv", - "biz.mv", - "com.mv", - "coop.mv", - "edu.mv", - "gov.mv", - "info.mv", - "int.mv", - "mil.mv", - "museum.mv", - "name.mv", - "net.mv", - "org.mv", - "pro.mv", - "mw", - "ac.mw", - "biz.mw", - "co.mw", - "com.mw", - "coop.mw", - "edu.mw", - "gov.mw", - "int.mw", - "museum.mw", - "net.mw", - "org.mw", - "mx", - "com.mx", - "org.mx", - "gob.mx", - "edu.mx", - "net.mx", - "my", - "com.my", - "net.my", - "org.my", - "gov.my", - "edu.my", - "mil.my", - "name.my", - "mz", - "ac.mz", - "adv.mz", - "co.mz", - "edu.mz", - "gov.mz", - "mil.mz", - "net.mz", - "org.mz", - "na", - "info.na", - "pro.na", - "name.na", - "school.na", - "or.na", - "dr.na", - "us.na", - "mx.na", - "ca.na", - "in.na", - "cc.na", - "tv.na", - "ws.na", - "mobi.na", - "co.na", - "com.na", - "org.na", - "name", - "nc", - "asso.nc", - "nom.nc", - "ne", - "net", - "nf", - "com.nf", - "net.nf", - "per.nf", - "rec.nf", - "web.nf", - "arts.nf", - "firm.nf", - "info.nf", - "other.nf", - "store.nf", - "ng", - "com.ng", - "edu.ng", - "gov.ng", - "i.ng", - "mil.ng", - "mobi.ng", - "name.ng", - "net.ng", - "org.ng", - "sch.ng", - "ni", - "ac.ni", - "biz.ni", - "co.ni", - "com.ni", - "edu.ni", - "gob.ni", - "in.ni", - "info.ni", - "int.ni", - "mil.ni", - "net.ni", - "nom.ni", - "org.ni", - "web.ni", - "nl", - "bv.nl", - "no", - "fhs.no", - "vgs.no", - "fylkesbibl.no", - "folkebibl.no", - "museum.no", - "idrett.no", - "priv.no", - "mil.no", - "stat.no", - "dep.no", - "kommune.no", - "herad.no", - "aa.no", - "ah.no", - "bu.no", - "fm.no", - "hl.no", - "hm.no", - "jan-mayen.no", - "mr.no", - "nl.no", - "nt.no", - "of.no", - "ol.no", - "oslo.no", - "rl.no", - "sf.no", - "st.no", - "svalbard.no", - "tm.no", - "tr.no", - "va.no", - "vf.no", - "gs.aa.no", - "gs.ah.no", - "gs.bu.no", - "gs.fm.no", - "gs.hl.no", - "gs.hm.no", - "gs.jan-mayen.no", - "gs.mr.no", - "gs.nl.no", - "gs.nt.no", - "gs.of.no", - "gs.ol.no", - "gs.oslo.no", - "gs.rl.no", - "gs.sf.no", - "gs.st.no", - "gs.svalbard.no", - "gs.tm.no", - "gs.tr.no", - "gs.va.no", - "gs.vf.no", - "akrehamn.no", - "xn--krehamn-dxa.no", - "algard.no", - "xn--lgrd-poac.no", - "arna.no", - "brumunddal.no", - "bryne.no", - "bronnoysund.no", - "xn--brnnysund-m8ac.no", - "drobak.no", - "xn--drbak-wua.no", - "egersund.no", - "fetsund.no", - "floro.no", - "xn--flor-jra.no", - "fredrikstad.no", - "hokksund.no", - "honefoss.no", - "xn--hnefoss-q1a.no", - "jessheim.no", - "jorpeland.no", - "xn--jrpeland-54a.no", - "kirkenes.no", - "kopervik.no", - "krokstadelva.no", - "langevag.no", - "xn--langevg-jxa.no", - "leirvik.no", - "mjondalen.no", - "xn--mjndalen-64a.no", - "mo-i-rana.no", - "mosjoen.no", - "xn--mosjen-eya.no", - "nesoddtangen.no", - "orkanger.no", - "osoyro.no", - "xn--osyro-wua.no", - "raholt.no", - "xn--rholt-mra.no", - "sandnessjoen.no", - "xn--sandnessjen-ogb.no", - "skedsmokorset.no", - "slattum.no", - "spjelkavik.no", - "stathelle.no", - "stavern.no", - "stjordalshalsen.no", - "xn--stjrdalshalsen-sqb.no", - "tananger.no", - "tranby.no", - "vossevangen.no", - "afjord.no", - "xn--fjord-lra.no", - "agdenes.no", - "al.no", - "xn--l-1fa.no", - "alesund.no", - "xn--lesund-hua.no", - "alstahaug.no", - "alta.no", - "xn--lt-liac.no", - "alaheadju.no", - "xn--laheadju-7ya.no", - "alvdal.no", - "amli.no", - "xn--mli-tla.no", - "amot.no", - "xn--mot-tla.no", - "andebu.no", - "andoy.no", - "xn--andy-ira.no", - "andasuolo.no", - "ardal.no", - "xn--rdal-poa.no", - "aremark.no", - "arendal.no", - "xn--s-1fa.no", - "aseral.no", - "xn--seral-lra.no", - "asker.no", - "askim.no", - "askvoll.no", - "askoy.no", - "xn--asky-ira.no", - "asnes.no", - "xn--snes-poa.no", - "audnedaln.no", - "aukra.no", - "aure.no", - "aurland.no", - "aurskog-holand.no", - "xn--aurskog-hland-jnb.no", - "austevoll.no", - "austrheim.no", - "averoy.no", - "xn--avery-yua.no", - "balestrand.no", - "ballangen.no", - "balat.no", - "xn--blt-elab.no", - "balsfjord.no", - "bahccavuotna.no", - "xn--bhccavuotna-k7a.no", - "bamble.no", - "bardu.no", - "beardu.no", - "beiarn.no", - "bajddar.no", - "xn--bjddar-pta.no", - "baidar.no", - "xn--bidr-5nac.no", - "berg.no", - "bergen.no", - "berlevag.no", - "xn--berlevg-jxa.no", - "bearalvahki.no", - "xn--bearalvhki-y4a.no", - "bindal.no", - "birkenes.no", - "bjarkoy.no", - "xn--bjarky-fya.no", - "bjerkreim.no", - "bjugn.no", - "bodo.no", - "xn--bod-2na.no", - "badaddja.no", - "xn--bdddj-mrabd.no", - "budejju.no", - "bokn.no", - "bremanger.no", - "bronnoy.no", - "xn--brnny-wuac.no", - "bygland.no", - "bykle.no", - "barum.no", - "xn--brum-voa.no", - "bo.telemark.no", - "xn--b-5ga.telemark.no", - "bo.nordland.no", - "xn--b-5ga.nordland.no", - "bievat.no", - "xn--bievt-0qa.no", - "bomlo.no", - "xn--bmlo-gra.no", - "batsfjord.no", - "xn--btsfjord-9za.no", - "bahcavuotna.no", - "xn--bhcavuotna-s4a.no", - "dovre.no", - "drammen.no", - "drangedal.no", - "dyroy.no", - "xn--dyry-ira.no", - "donna.no", - "xn--dnna-gra.no", - "eid.no", - "eidfjord.no", - "eidsberg.no", - "eidskog.no", - "eidsvoll.no", - "eigersund.no", - "elverum.no", - "enebakk.no", - "engerdal.no", - "etne.no", - "etnedal.no", - "evenes.no", - "evenassi.no", - "xn--eveni-0qa01ga.no", - "evje-og-hornnes.no", - "farsund.no", - "fauske.no", - "fuossko.no", - "fuoisku.no", - "fedje.no", - "fet.no", - "finnoy.no", - "xn--finny-yua.no", - "fitjar.no", - "fjaler.no", - "fjell.no", - "flakstad.no", - "flatanger.no", - "flekkefjord.no", - "flesberg.no", - "flora.no", - "fla.no", - "xn--fl-zia.no", - "folldal.no", - "forsand.no", - "fosnes.no", - "frei.no", - "frogn.no", - "froland.no", - "frosta.no", - "frana.no", - "xn--frna-woa.no", - "froya.no", - "xn--frya-hra.no", - "fusa.no", - "fyresdal.no", - "forde.no", - "xn--frde-gra.no", - "gamvik.no", - "gangaviika.no", - "xn--ggaviika-8ya47h.no", - "gaular.no", - "gausdal.no", - "gildeskal.no", - "xn--gildeskl-g0a.no", - "giske.no", - "gjemnes.no", - "gjerdrum.no", - "gjerstad.no", - "gjesdal.no", - "gjovik.no", - "xn--gjvik-wua.no", - "gloppen.no", - "gol.no", - "gran.no", - "grane.no", - "granvin.no", - "gratangen.no", - "grimstad.no", - "grong.no", - "kraanghke.no", - "xn--kranghke-b0a.no", - "grue.no", - "gulen.no", - "hadsel.no", - "halden.no", - "halsa.no", - "hamar.no", - "hamaroy.no", - "habmer.no", - "xn--hbmer-xqa.no", - "hapmir.no", - "xn--hpmir-xqa.no", - "hammerfest.no", - "hammarfeasta.no", - "xn--hmmrfeasta-s4ac.no", - "haram.no", - "hareid.no", - "harstad.no", - "hasvik.no", - "aknoluokta.no", - "xn--koluokta-7ya57h.no", - "hattfjelldal.no", - "aarborte.no", - "haugesund.no", - "hemne.no", - "hemnes.no", - "hemsedal.no", - "heroy.more-og-romsdal.no", - "xn--hery-ira.xn--mre-og-romsdal-qqb.no", - "heroy.nordland.no", - "xn--hery-ira.nordland.no", - "hitra.no", - "hjartdal.no", - "hjelmeland.no", - "hobol.no", - "xn--hobl-ira.no", - "hof.no", - "hol.no", - "hole.no", - "holmestrand.no", - "holtalen.no", - "xn--holtlen-hxa.no", - "hornindal.no", - "horten.no", - "hurdal.no", - "hurum.no", - "hvaler.no", - "hyllestad.no", - "hagebostad.no", - "xn--hgebostad-g3a.no", - "hoyanger.no", - "xn--hyanger-q1a.no", - "hoylandet.no", - "xn--hylandet-54a.no", - "ha.no", - "xn--h-2fa.no", - "ibestad.no", - "inderoy.no", - "xn--indery-fya.no", - "iveland.no", - "jevnaker.no", - "jondal.no", - "jolster.no", - "xn--jlster-bya.no", - "karasjok.no", - "karasjohka.no", - "xn--krjohka-hwab49j.no", - "karlsoy.no", - "galsa.no", - "xn--gls-elac.no", - "karmoy.no", - "xn--karmy-yua.no", - "kautokeino.no", - "guovdageaidnu.no", - "klepp.no", - "klabu.no", - "xn--klbu-woa.no", - "kongsberg.no", - "kongsvinger.no", - "kragero.no", - "xn--krager-gya.no", - "kristiansand.no", - "kristiansund.no", - "krodsherad.no", - "xn--krdsherad-m8a.no", - "kvalsund.no", - "rahkkeravju.no", - "xn--rhkkervju-01af.no", - "kvam.no", - "kvinesdal.no", - "kvinnherad.no", - "kviteseid.no", - "kvitsoy.no", - "xn--kvitsy-fya.no", - "kvafjord.no", - "xn--kvfjord-nxa.no", - "giehtavuoatna.no", - "kvanangen.no", - "xn--kvnangen-k0a.no", - "navuotna.no", - "xn--nvuotna-hwa.no", - "kafjord.no", - "xn--kfjord-iua.no", - "gaivuotna.no", - "xn--givuotna-8ya.no", - "larvik.no", - "lavangen.no", - "lavagis.no", - "loabat.no", - "xn--loabt-0qa.no", - "lebesby.no", - "davvesiida.no", - "leikanger.no", - "leirfjord.no", - "leka.no", - "leksvik.no", - "lenvik.no", - "leangaviika.no", - "xn--leagaviika-52b.no", - "lesja.no", - "levanger.no", - "lier.no", - "lierne.no", - "lillehammer.no", - "lillesand.no", - "lindesnes.no", - "lindas.no", - "xn--linds-pra.no", - "lom.no", - "loppa.no", - "lahppi.no", - "xn--lhppi-xqa.no", - "lund.no", - "lunner.no", - "luroy.no", - "xn--lury-ira.no", - "luster.no", - "lyngdal.no", - "lyngen.no", - "ivgu.no", - "lardal.no", - "lerdal.no", - "xn--lrdal-sra.no", - "lodingen.no", - "xn--ldingen-q1a.no", - "lorenskog.no", - "xn--lrenskog-54a.no", - "loten.no", - "xn--lten-gra.no", - "malvik.no", - "masoy.no", - "xn--msy-ula0h.no", - "muosat.no", - "xn--muost-0qa.no", - "mandal.no", - "marker.no", - "marnardal.no", - "masfjorden.no", - "meland.no", - "meldal.no", - "melhus.no", - "meloy.no", - "xn--mely-ira.no", - "meraker.no", - "xn--merker-kua.no", - "moareke.no", - "xn--moreke-jua.no", - "midsund.no", - "midtre-gauldal.no", - "modalen.no", - "modum.no", - "molde.no", - "moskenes.no", - "moss.no", - "mosvik.no", - "malselv.no", - "xn--mlselv-iua.no", - "malatvuopmi.no", - "xn--mlatvuopmi-s4a.no", - "namdalseid.no", - "aejrie.no", - "namsos.no", - "namsskogan.no", - "naamesjevuemie.no", - "xn--nmesjevuemie-tcba.no", - "laakesvuemie.no", - "nannestad.no", - "narvik.no", - "narviika.no", - "naustdal.no", - "nedre-eiker.no", - "nes.akershus.no", - "nes.buskerud.no", - "nesna.no", - "nesodden.no", - "nesseby.no", - "unjarga.no", - "xn--unjrga-rta.no", - "nesset.no", - "nissedal.no", - "nittedal.no", - "nord-aurdal.no", - "nord-fron.no", - "nord-odal.no", - "norddal.no", - "nordkapp.no", - "davvenjarga.no", - "xn--davvenjrga-y4a.no", - "nordre-land.no", - "nordreisa.no", - "raisa.no", - "xn--risa-5na.no", - "nore-og-uvdal.no", - "notodden.no", - "naroy.no", - "xn--nry-yla5g.no", - "notteroy.no", - "xn--nttery-byae.no", - "odda.no", - "oksnes.no", - "xn--ksnes-uua.no", - "oppdal.no", - "oppegard.no", - "xn--oppegrd-ixa.no", - "orkdal.no", - "orland.no", - "xn--rland-uua.no", - "orskog.no", - "xn--rskog-uua.no", - "orsta.no", - "xn--rsta-fra.no", - "os.hedmark.no", - "os.hordaland.no", - "osen.no", - "osteroy.no", - "xn--ostery-fya.no", - "ostre-toten.no", - "xn--stre-toten-zcb.no", - "overhalla.no", - "ovre-eiker.no", - "xn--vre-eiker-k8a.no", - "oyer.no", - "xn--yer-zna.no", - "oygarden.no", - "xn--ygarden-p1a.no", - "oystre-slidre.no", - "xn--ystre-slidre-ujb.no", - "porsanger.no", - "porsangu.no", - "xn--porsgu-sta26f.no", - "porsgrunn.no", - "radoy.no", - "xn--rady-ira.no", - "rakkestad.no", - "rana.no", - "ruovat.no", - "randaberg.no", - "rauma.no", - "rendalen.no", - "rennebu.no", - "rennesoy.no", - "xn--rennesy-v1a.no", - "rindal.no", - "ringebu.no", - "ringerike.no", - "ringsaker.no", - "rissa.no", - "risor.no", - "xn--risr-ira.no", - "roan.no", - "rollag.no", - "rygge.no", - "ralingen.no", - "xn--rlingen-mxa.no", - "rodoy.no", - "xn--rdy-0nab.no", - "romskog.no", - "xn--rmskog-bya.no", - "roros.no", - "xn--rros-gra.no", - "rost.no", - "xn--rst-0na.no", - "royken.no", - "xn--ryken-vua.no", - "royrvik.no", - "xn--ryrvik-bya.no", - "rade.no", - "xn--rde-ula.no", - "salangen.no", - "siellak.no", - "saltdal.no", - "salat.no", - "xn--slt-elab.no", - "xn--slat-5na.no", - "samnanger.no", - "sande.more-og-romsdal.no", - "sande.xn--mre-og-romsdal-qqb.no", - "sande.vestfold.no", - "sandefjord.no", - "sandnes.no", - "sandoy.no", - "xn--sandy-yua.no", - "sarpsborg.no", - "sauda.no", - "sauherad.no", - "sel.no", - "selbu.no", - "selje.no", - "seljord.no", - "sigdal.no", - "siljan.no", - "sirdal.no", - "skaun.no", - "skedsmo.no", - "ski.no", - "skien.no", - "skiptvet.no", - "skjervoy.no", - "xn--skjervy-v1a.no", - "skierva.no", - "xn--skierv-uta.no", - "skjak.no", - "xn--skjk-soa.no", - "skodje.no", - "skanland.no", - "xn--sknland-fxa.no", - "skanit.no", - "xn--sknit-yqa.no", - "smola.no", - "xn--smla-hra.no", - "snillfjord.no", - "snasa.no", - "xn--snsa-roa.no", - "snoasa.no", - "snaase.no", - "xn--snase-nra.no", - "sogndal.no", - "sokndal.no", - "sola.no", - "solund.no", - "songdalen.no", - "sortland.no", - "spydeberg.no", - "stange.no", - "stavanger.no", - "steigen.no", - "steinkjer.no", - "stjordal.no", - "xn--stjrdal-s1a.no", - "stokke.no", - "stor-elvdal.no", - "stord.no", - "stordal.no", - "storfjord.no", - "omasvuotna.no", - "strand.no", - "stranda.no", - "stryn.no", - "sula.no", - "suldal.no", - "sund.no", - "sunndal.no", - "surnadal.no", - "sveio.no", - "svelvik.no", - "sykkylven.no", - "sogne.no", - "xn--sgne-gra.no", - "somna.no", - "xn--smna-gra.no", - "sondre-land.no", - "xn--sndre-land-0cb.no", - "sor-aurdal.no", - "xn--sr-aurdal-l8a.no", - "sor-fron.no", - "xn--sr-fron-q1a.no", - "sor-odal.no", - "xn--sr-odal-q1a.no", - "sor-varanger.no", - "xn--sr-varanger-ggb.no", - "matta-varjjat.no", - "xn--mtta-vrjjat-k7af.no", - "sorfold.no", - "xn--srfold-bya.no", - "sorreisa.no", - "xn--srreisa-q1a.no", - "sorum.no", - "xn--srum-gra.no", - "tana.no", - "deatnu.no", - "time.no", - "tingvoll.no", - "tinn.no", - "tjeldsund.no", - "dielddanuorri.no", - "tjome.no", - "xn--tjme-hra.no", - "tokke.no", - "tolga.no", - "torsken.no", - "tranoy.no", - "xn--trany-yua.no", - "tromso.no", - "xn--troms-zua.no", - "tromsa.no", - "romsa.no", - "trondheim.no", - "troandin.no", - "trysil.no", - "trana.no", - "xn--trna-woa.no", - "trogstad.no", - "xn--trgstad-r1a.no", - "tvedestrand.no", - "tydal.no", - "tynset.no", - "tysfjord.no", - "divtasvuodna.no", - "divttasvuotna.no", - "tysnes.no", - "tysvar.no", - "xn--tysvr-vra.no", - "tonsberg.no", - "xn--tnsberg-q1a.no", - "ullensaker.no", - "ullensvang.no", - "ulvik.no", - "utsira.no", - "vadso.no", - "xn--vads-jra.no", - "cahcesuolo.no", - "xn--hcesuolo-7ya35b.no", - "vaksdal.no", - "valle.no", - "vang.no", - "vanylven.no", - "vardo.no", - "xn--vard-jra.no", - "varggat.no", - "xn--vrggt-xqad.no", - "vefsn.no", - "vaapste.no", - "vega.no", - "vegarshei.no", - "xn--vegrshei-c0a.no", - "vennesla.no", - "verdal.no", - "verran.no", - "vestby.no", - "vestnes.no", - "vestre-slidre.no", - "vestre-toten.no", - "vestvagoy.no", - "xn--vestvgy-ixa6o.no", - "vevelstad.no", - "vik.no", - "vikna.no", - "vindafjord.no", - "volda.no", - "voss.no", - "varoy.no", - "xn--vry-yla5g.no", - "vagan.no", - "xn--vgan-qoa.no", - "voagat.no", - "vagsoy.no", - "xn--vgsy-qoa0j.no", - "vaga.no", - "xn--vg-yiab.no", - "valer.ostfold.no", - "xn--vler-qoa.xn--stfold-9xa.no", - "valer.hedmark.no", - "xn--vler-qoa.hedmark.no", - "*.np", - "nr", - "biz.nr", - "info.nr", - "gov.nr", - "edu.nr", - "org.nr", - "net.nr", - "com.nr", - "nu", - "nz", - "ac.nz", - "co.nz", - "cri.nz", - "geek.nz", - "gen.nz", - "govt.nz", - "health.nz", - "iwi.nz", - "kiwi.nz", - "maori.nz", - "mil.nz", - "xn--mori-qsa.nz", - "net.nz", - "org.nz", - "parliament.nz", - "school.nz", - "om", - "co.om", - "com.om", - "edu.om", - "gov.om", - "med.om", - "museum.om", - "net.om", - "org.om", - "pro.om", - "onion", - "org", - "pa", - "ac.pa", - "gob.pa", - "com.pa", - "org.pa", - "sld.pa", - "edu.pa", - "net.pa", - "ing.pa", - "abo.pa", - "med.pa", - "nom.pa", - "pe", - "edu.pe", - "gob.pe", - "nom.pe", - "mil.pe", - "org.pe", - "com.pe", - "net.pe", - "pf", - "com.pf", - "org.pf", - "edu.pf", - "*.pg", - "ph", - "com.ph", - "net.ph", - "org.ph", - "gov.ph", - "edu.ph", - "ngo.ph", - "mil.ph", - "i.ph", - "pk", - "com.pk", - "net.pk", - "edu.pk", - "org.pk", - "fam.pk", - "biz.pk", - "web.pk", - "gov.pk", - "gob.pk", - "gok.pk", - "gon.pk", - "gop.pk", - "gos.pk", - "info.pk", - "pl", - "com.pl", - "net.pl", - "org.pl", - "aid.pl", - "agro.pl", - "atm.pl", - "auto.pl", - "biz.pl", - "edu.pl", - "gmina.pl", - "gsm.pl", - "info.pl", - "mail.pl", - "miasta.pl", - "media.pl", - "mil.pl", - "nieruchomosci.pl", - "nom.pl", - "pc.pl", - "powiat.pl", - "priv.pl", - "realestate.pl", - "rel.pl", - "sex.pl", - "shop.pl", - "sklep.pl", - "sos.pl", - "szkola.pl", - "targi.pl", - "tm.pl", - "tourism.pl", - "travel.pl", - "turystyka.pl", - "gov.pl", - "ap.gov.pl", - "ic.gov.pl", - "is.gov.pl", - "us.gov.pl", - "kmpsp.gov.pl", - "kppsp.gov.pl", - "kwpsp.gov.pl", - "psp.gov.pl", - "wskr.gov.pl", - "kwp.gov.pl", - "mw.gov.pl", - "ug.gov.pl", - "um.gov.pl", - "umig.gov.pl", - "ugim.gov.pl", - "upow.gov.pl", - "uw.gov.pl", - "starostwo.gov.pl", - "pa.gov.pl", - "po.gov.pl", - "psse.gov.pl", - "pup.gov.pl", - "rzgw.gov.pl", - "sa.gov.pl", - "so.gov.pl", - "sr.gov.pl", - "wsa.gov.pl", - "sko.gov.pl", - "uzs.gov.pl", - "wiih.gov.pl", - "winb.gov.pl", - "pinb.gov.pl", - "wios.gov.pl", - "witd.gov.pl", - "wzmiuw.gov.pl", - "piw.gov.pl", - "wiw.gov.pl", - "griw.gov.pl", - "wif.gov.pl", - "oum.gov.pl", - "sdn.gov.pl", - "zp.gov.pl", - "uppo.gov.pl", - "mup.gov.pl", - "wuoz.gov.pl", - "konsulat.gov.pl", - "oirm.gov.pl", - "augustow.pl", - "babia-gora.pl", - "bedzin.pl", - "beskidy.pl", - "bialowieza.pl", - "bialystok.pl", - "bielawa.pl", - "bieszczady.pl", - "boleslawiec.pl", - "bydgoszcz.pl", - "bytom.pl", - "cieszyn.pl", - "czeladz.pl", - "czest.pl", - "dlugoleka.pl", - "elblag.pl", - "elk.pl", - "glogow.pl", - "gniezno.pl", - "gorlice.pl", - "grajewo.pl", - "ilawa.pl", - "jaworzno.pl", - "jelenia-gora.pl", - "jgora.pl", - "kalisz.pl", - "kazimierz-dolny.pl", - "karpacz.pl", - "kartuzy.pl", - "kaszuby.pl", - "katowice.pl", - "kepno.pl", - "ketrzyn.pl", - "klodzko.pl", - "kobierzyce.pl", - "kolobrzeg.pl", - "konin.pl", - "konskowola.pl", - "kutno.pl", - "lapy.pl", - "lebork.pl", - "legnica.pl", - "lezajsk.pl", - "limanowa.pl", - "lomza.pl", - "lowicz.pl", - "lubin.pl", - "lukow.pl", - "malbork.pl", - "malopolska.pl", - "mazowsze.pl", - "mazury.pl", - "mielec.pl", - "mielno.pl", - "mragowo.pl", - "naklo.pl", - "nowaruda.pl", - "nysa.pl", - "olawa.pl", - "olecko.pl", - "olkusz.pl", - "olsztyn.pl", - "opoczno.pl", - "opole.pl", - "ostroda.pl", - "ostroleka.pl", - "ostrowiec.pl", - "ostrowwlkp.pl", - "pila.pl", - "pisz.pl", - "podhale.pl", - "podlasie.pl", - "polkowice.pl", - "pomorze.pl", - "pomorskie.pl", - "prochowice.pl", - "pruszkow.pl", - "przeworsk.pl", - "pulawy.pl", - "radom.pl", - "rawa-maz.pl", - "rybnik.pl", - "rzeszow.pl", - "sanok.pl", - "sejny.pl", - "slask.pl", - "slupsk.pl", - "sosnowiec.pl", - "stalowa-wola.pl", - "skoczow.pl", - "starachowice.pl", - "stargard.pl", - "suwalki.pl", - "swidnica.pl", - "swiebodzin.pl", - "swinoujscie.pl", - "szczecin.pl", - "szczytno.pl", - "tarnobrzeg.pl", - "tgory.pl", - "turek.pl", - "tychy.pl", - "ustka.pl", - "walbrzych.pl", - "warmia.pl", - "warszawa.pl", - "waw.pl", - "wegrow.pl", - "wielun.pl", - "wlocl.pl", - "wloclawek.pl", - "wodzislaw.pl", - "wolomin.pl", - "wroclaw.pl", - "zachpomor.pl", - "zagan.pl", - "zarow.pl", - "zgora.pl", - "zgorzelec.pl", - "pm", - "pn", - "gov.pn", - "co.pn", - "org.pn", - "edu.pn", - "net.pn", - "post", - "pr", - "com.pr", - "net.pr", - "org.pr", - "gov.pr", - "edu.pr", - "isla.pr", - "pro.pr", - "biz.pr", - "info.pr", - "name.pr", - "est.pr", - "prof.pr", - "ac.pr", - "pro", - "aaa.pro", - "aca.pro", - "acct.pro", - "avocat.pro", - "bar.pro", - "cpa.pro", - "eng.pro", - "jur.pro", - "law.pro", - "med.pro", - "recht.pro", - "ps", - "edu.ps", - "gov.ps", - "sec.ps", - "plo.ps", - "com.ps", - "org.ps", - "net.ps", - "pt", - "net.pt", - "gov.pt", - "org.pt", - "edu.pt", - "int.pt", - "publ.pt", - "com.pt", - "nome.pt", - "pw", - "co.pw", - "ne.pw", - "or.pw", - "ed.pw", - "go.pw", - "belau.pw", - "py", - "com.py", - "coop.py", - "edu.py", - "gov.py", - "mil.py", - "net.py", - "org.py", - "qa", - "com.qa", - "edu.qa", - "gov.qa", - "mil.qa", - "name.qa", - "net.qa", - "org.qa", - "sch.qa", - "re", - "asso.re", - "com.re", - "nom.re", - "ro", - "arts.ro", - "com.ro", - "firm.ro", - "info.ro", - "nom.ro", - "nt.ro", - "org.ro", - "rec.ro", - "store.ro", - "tm.ro", - "www.ro", - "rs", - "ac.rs", - "co.rs", - "edu.rs", - "gov.rs", - "in.rs", - "org.rs", - "ru", - "ac.ru", - "edu.ru", - "gov.ru", - "int.ru", - "mil.ru", - "test.ru", - "rw", - "gov.rw", - "net.rw", - "edu.rw", - "ac.rw", - "com.rw", - "co.rw", - "int.rw", - "mil.rw", - "gouv.rw", - "sa", - "com.sa", - "net.sa", - "org.sa", - "gov.sa", - "med.sa", - "pub.sa", - "edu.sa", - "sch.sa", - "sb", - "com.sb", - "edu.sb", - "gov.sb", - "net.sb", - "org.sb", - "sc", - "com.sc", - "gov.sc", - "net.sc", - "org.sc", - "edu.sc", - "sd", - "com.sd", - "net.sd", - "org.sd", - "edu.sd", - "med.sd", - "tv.sd", - "gov.sd", - "info.sd", - "se", - "a.se", - "ac.se", - "b.se", - "bd.se", - "brand.se", - "c.se", - "d.se", - "e.se", - "f.se", - "fh.se", - "fhsk.se", - "fhv.se", - "g.se", - "h.se", - "i.se", - "k.se", - "komforb.se", - "kommunalforbund.se", - "komvux.se", - "l.se", - "lanbib.se", - "m.se", - "n.se", - "naturbruksgymn.se", - "o.se", - "org.se", - "p.se", - "parti.se", - "pp.se", - "press.se", - "r.se", - "s.se", - "t.se", - "tm.se", - "u.se", - "w.se", - "x.se", - "y.se", - "z.se", - "sg", - "com.sg", - "net.sg", - "org.sg", - "gov.sg", - "edu.sg", - "per.sg", - "sh", - "com.sh", - "net.sh", - "gov.sh", - "org.sh", - "mil.sh", - "si", - "sj", - "sk", - "sl", - "com.sl", - "net.sl", - "edu.sl", - "gov.sl", - "org.sl", - "sm", - "sn", - "art.sn", - "com.sn", - "edu.sn", - "gouv.sn", - "org.sn", - "perso.sn", - "univ.sn", - "so", - "com.so", - "net.so", - "org.so", - "sr", - "st", - "co.st", - "com.st", - "consulado.st", - "edu.st", - "embaixada.st", - "gov.st", - "mil.st", - "net.st", - "org.st", - "principe.st", - "saotome.st", - "store.st", - "su", - "sv", - "com.sv", - "edu.sv", - "gob.sv", - "org.sv", - "red.sv", - "sx", - "gov.sx", - "sy", - "edu.sy", - "gov.sy", - "net.sy", - "mil.sy", - "com.sy", - "org.sy", - "sz", - "co.sz", - "ac.sz", - "org.sz", - "tc", - "td", - "tel", - "tf", - "tg", - "th", - "ac.th", - "co.th", - "go.th", - "in.th", - "mi.th", - "net.th", - "or.th", - "tj", - "ac.tj", - "biz.tj", - "co.tj", - "com.tj", - "edu.tj", - "go.tj", - "gov.tj", - "int.tj", - "mil.tj", - "name.tj", - "net.tj", - "nic.tj", - "org.tj", - "test.tj", - "web.tj", - "tk", - "tl", - "gov.tl", - "tm", - "com.tm", - "co.tm", - "org.tm", - "net.tm", - "nom.tm", - "gov.tm", - "mil.tm", - "edu.tm", - "tn", - "com.tn", - "ens.tn", - "fin.tn", - "gov.tn", - "ind.tn", - "intl.tn", - "nat.tn", - "net.tn", - "org.tn", - "info.tn", - "perso.tn", - "tourism.tn", - "edunet.tn", - "rnrt.tn", - "rns.tn", - "rnu.tn", - "mincom.tn", - "agrinet.tn", - "defense.tn", - "turen.tn", - "to", - "com.to", - "gov.to", - "net.to", - "org.to", - "edu.to", - "mil.to", - "tr", - "com.tr", - "info.tr", - "biz.tr", - "net.tr", - "org.tr", - "web.tr", - "gen.tr", - "tv.tr", - "av.tr", - "dr.tr", - "bbs.tr", - "name.tr", - "tel.tr", - "gov.tr", - "bel.tr", - "pol.tr", - "mil.tr", - "k12.tr", - "edu.tr", - "kep.tr", - "nc.tr", - "gov.nc.tr", - "travel", - "tt", - "co.tt", - "com.tt", - "org.tt", - "net.tt", - "biz.tt", - "info.tt", - "pro.tt", - "int.tt", - "coop.tt", - "jobs.tt", - "mobi.tt", - "travel.tt", - "museum.tt", - "aero.tt", - "name.tt", - "gov.tt", - "edu.tt", - "tv", - "tw", - "edu.tw", - "gov.tw", - "mil.tw", - "com.tw", - "net.tw", - "org.tw", - "idv.tw", - "game.tw", - "ebiz.tw", - "club.tw", - "xn--zf0ao64a.tw", - "xn--uc0atv.tw", - "xn--czrw28b.tw", - "tz", - "ac.tz", - "co.tz", - "go.tz", - "hotel.tz", - "info.tz", - "me.tz", - "mil.tz", - "mobi.tz", - "ne.tz", - "or.tz", - "sc.tz", - "tv.tz", - "ua", - "com.ua", - "edu.ua", - "gov.ua", - "in.ua", - "net.ua", - "org.ua", - "cherkassy.ua", - "cherkasy.ua", - "chernigov.ua", - "chernihiv.ua", - "chernivtsi.ua", - "chernovtsy.ua", - "ck.ua", - "cn.ua", - "cr.ua", - "crimea.ua", - "cv.ua", - "dn.ua", - "dnepropetrovsk.ua", - "dnipropetrovsk.ua", - "dominic.ua", - "donetsk.ua", - "dp.ua", - "if.ua", - "ivano-frankivsk.ua", - "kh.ua", - "kharkiv.ua", - "kharkov.ua", - "kherson.ua", - "khmelnitskiy.ua", - "khmelnytskyi.ua", - "kiev.ua", - "kirovograd.ua", - "km.ua", - "kr.ua", - "krym.ua", - "ks.ua", - "kv.ua", - "kyiv.ua", - "lg.ua", - "lt.ua", - "lugansk.ua", - "lutsk.ua", - "lv.ua", - "lviv.ua", - "mk.ua", - "mykolaiv.ua", - "nikolaev.ua", - "od.ua", - "odesa.ua", - "odessa.ua", - "pl.ua", - "poltava.ua", - "rivne.ua", - "rovno.ua", - "rv.ua", - "sb.ua", - "sebastopol.ua", - "sevastopol.ua", - "sm.ua", - "sumy.ua", - "te.ua", - "ternopil.ua", - "uz.ua", - "uzhgorod.ua", - "vinnica.ua", - "vinnytsia.ua", - "vn.ua", - "volyn.ua", - "yalta.ua", - "zaporizhzhe.ua", - "zaporizhzhia.ua", - "zhitomir.ua", - "zhytomyr.ua", - "zp.ua", - "zt.ua", - "ug", - "co.ug", - "or.ug", - "ac.ug", - "sc.ug", - "go.ug", - "ne.ug", - "com.ug", - "org.ug", - "uk", - "ac.uk", - "co.uk", - "gov.uk", - "ltd.uk", - "me.uk", - "net.uk", - "nhs.uk", - "org.uk", - "plc.uk", - "police.uk", - "*.sch.uk", - "us", - "dni.us", - "fed.us", - "isa.us", - "kids.us", - "nsn.us", - "ak.us", - "al.us", - "ar.us", - "as.us", - "az.us", - "ca.us", - "co.us", - "ct.us", - "dc.us", - "de.us", - "fl.us", - "ga.us", - "gu.us", - "hi.us", - "ia.us", - "id.us", - "il.us", - "in.us", - "ks.us", - "ky.us", - "la.us", - "ma.us", - "md.us", - "me.us", - "mi.us", - "mn.us", - "mo.us", - "ms.us", - "mt.us", - "nc.us", - "nd.us", - "ne.us", - "nh.us", - "nj.us", - "nm.us", - "nv.us", - "ny.us", - "oh.us", - "ok.us", - "or.us", - "pa.us", - "pr.us", - "ri.us", - "sc.us", - "sd.us", - "tn.us", - "tx.us", - "ut.us", - "vi.us", - "vt.us", - "va.us", - "wa.us", - "wi.us", - "wv.us", - "wy.us", - "k12.ak.us", - "k12.al.us", - "k12.ar.us", - "k12.as.us", - "k12.az.us", - "k12.ca.us", - "k12.co.us", - "k12.ct.us", - "k12.dc.us", - "k12.de.us", - "k12.fl.us", - "k12.ga.us", - "k12.gu.us", - "k12.ia.us", - "k12.id.us", - "k12.il.us", - "k12.in.us", - "k12.ks.us", - "k12.ky.us", - "k12.la.us", - "k12.ma.us", - "k12.md.us", - "k12.me.us", - "k12.mi.us", - "k12.mn.us", - "k12.mo.us", - "k12.ms.us", - "k12.mt.us", - "k12.nc.us", - "k12.ne.us", - "k12.nh.us", - "k12.nj.us", - "k12.nm.us", - "k12.nv.us", - "k12.ny.us", - "k12.oh.us", - "k12.ok.us", - "k12.or.us", - "k12.pa.us", - "k12.pr.us", - "k12.ri.us", - "k12.sc.us", - "k12.tn.us", - "k12.tx.us", - "k12.ut.us", - "k12.vi.us", - "k12.vt.us", - "k12.va.us", - "k12.wa.us", - "k12.wi.us", - "k12.wy.us", - "cc.ak.us", - "cc.al.us", - "cc.ar.us", - "cc.as.us", - "cc.az.us", - "cc.ca.us", - "cc.co.us", - "cc.ct.us", - "cc.dc.us", - "cc.de.us", - "cc.fl.us", - "cc.ga.us", - "cc.gu.us", - "cc.hi.us", - "cc.ia.us", - "cc.id.us", - "cc.il.us", - "cc.in.us", - "cc.ks.us", - "cc.ky.us", - "cc.la.us", - "cc.ma.us", - "cc.md.us", - "cc.me.us", - "cc.mi.us", - "cc.mn.us", - "cc.mo.us", - "cc.ms.us", - "cc.mt.us", - "cc.nc.us", - "cc.nd.us", - "cc.ne.us", - "cc.nh.us", - "cc.nj.us", - "cc.nm.us", - "cc.nv.us", - "cc.ny.us", - "cc.oh.us", - "cc.ok.us", - "cc.or.us", - "cc.pa.us", - "cc.pr.us", - "cc.ri.us", - "cc.sc.us", - "cc.sd.us", - "cc.tn.us", - "cc.tx.us", - "cc.ut.us", - "cc.vi.us", - "cc.vt.us", - "cc.va.us", - "cc.wa.us", - "cc.wi.us", - "cc.wv.us", - "cc.wy.us", - "lib.ak.us", - "lib.al.us", - "lib.ar.us", - "lib.as.us", - "lib.az.us", - "lib.ca.us", - "lib.co.us", - "lib.ct.us", - "lib.dc.us", - "lib.fl.us", - "lib.ga.us", - "lib.gu.us", - "lib.hi.us", - "lib.ia.us", - "lib.id.us", - "lib.il.us", - "lib.in.us", - "lib.ks.us", - "lib.ky.us", - "lib.la.us", - "lib.ma.us", - "lib.md.us", - "lib.me.us", - "lib.mi.us", - "lib.mn.us", - "lib.mo.us", - "lib.ms.us", - "lib.mt.us", - "lib.nc.us", - "lib.nd.us", - "lib.ne.us", - "lib.nh.us", - "lib.nj.us", - "lib.nm.us", - "lib.nv.us", - "lib.ny.us", - "lib.oh.us", - "lib.ok.us", - "lib.or.us", - "lib.pa.us", - "lib.pr.us", - "lib.ri.us", - "lib.sc.us", - "lib.sd.us", - "lib.tn.us", - "lib.tx.us", - "lib.ut.us", - "lib.vi.us", - "lib.vt.us", - "lib.va.us", - "lib.wa.us", - "lib.wi.us", - "lib.wy.us", - "pvt.k12.ma.us", - "chtr.k12.ma.us", - "paroch.k12.ma.us", - "ann-arbor.mi.us", - "cog.mi.us", - "dst.mi.us", - "eaton.mi.us", - "gen.mi.us", - "mus.mi.us", - "tec.mi.us", - "washtenaw.mi.us", - "uy", - "com.uy", - "edu.uy", - "gub.uy", - "mil.uy", - "net.uy", - "org.uy", - "uz", - "co.uz", - "com.uz", - "net.uz", - "org.uz", - "va", - "vc", - "com.vc", - "net.vc", - "org.vc", - "gov.vc", - "mil.vc", - "edu.vc", - "ve", - "arts.ve", - "co.ve", - "com.ve", - "e12.ve", - "edu.ve", - "firm.ve", - "gob.ve", - "gov.ve", - "info.ve", - "int.ve", - "mil.ve", - "net.ve", - "org.ve", - "rec.ve", - "store.ve", - "tec.ve", - "web.ve", - "vg", - "vi", - "co.vi", - "com.vi", - "k12.vi", - "net.vi", - "org.vi", - "vn", - "com.vn", - "net.vn", - "org.vn", - "edu.vn", - "gov.vn", - "int.vn", - "ac.vn", - "biz.vn", - "info.vn", - "name.vn", - "pro.vn", - "health.vn", - "vu", - "com.vu", - "edu.vu", - "net.vu", - "org.vu", - "wf", - "ws", - "com.ws", - "net.ws", - "org.ws", - "gov.ws", - "edu.ws", - "yt", - "xn--mgbaam7a8h", - "xn--y9a3aq", - "xn--54b7fta0cc", - "xn--90ae", - "xn--90ais", - "xn--fiqs8s", - "xn--fiqz9s", - "xn--lgbbat1ad8j", - "xn--wgbh1c", - "xn--e1a4c", - "xn--node", - "xn--qxam", - "xn--j6w193g", - "xn--2scrj9c", - "xn--3hcrj9c", - "xn--45br5cyl", - "xn--h2breg3eve", - "xn--h2brj9c8c", - "xn--mgbgu82a", - "xn--rvc1e0am3e", - "xn--h2brj9c", - "xn--mgbbh1a71e", - "xn--fpcrj9c3d", - "xn--gecrj9c", - "xn--s9brj9c", - "xn--45brj9c", - "xn--xkc2dl3a5ee0h", - "xn--mgba3a4f16a", - "xn--mgba3a4fra", - "xn--mgbtx2b", - "xn--mgbayh7gpa", - "xn--3e0b707e", - "xn--80ao21a", - "xn--fzc2c9e2c", - "xn--xkc2al3hye2a", - "xn--mgbc0a9azcg", - "xn--d1alf", - "xn--l1acc", - "xn--mix891f", - "xn--mix082f", - "xn--mgbx4cd0ab", - "xn--mgb9awbf", - "xn--mgbai9azgqp6j", - "xn--mgbai9a5eva00b", - "xn--ygbi2ammx", - "xn--90a3ac", - "xn--o1ac.xn--90a3ac", - "xn--c1avg.xn--90a3ac", - "xn--90azh.xn--90a3ac", - "xn--d1at.xn--90a3ac", - "xn--o1ach.xn--90a3ac", - "xn--80au.xn--90a3ac", - "xn--p1ai", - "xn--wgbl6a", - "xn--mgberp4a5d4ar", - "xn--mgberp4a5d4a87g", - "xn--mgbqly7c0a67fbc", - "xn--mgbqly7cvafr", - "xn--mgbpl2fh", - "xn--yfro4i67o", - "xn--clchc0ea0b2g2a9gcd", - "xn--ogbpf8fl", - "xn--mgbtf8fl", - "xn--o3cw4h", - "xn--12c1fe0br.xn--o3cw4h", - "xn--12co0c3b4eva.xn--o3cw4h", - "xn--h3cuzk1di.xn--o3cw4h", - "xn--o3cyx2a.xn--o3cw4h", - "xn--m3ch0j3a.xn--o3cw4h", - "xn--12cfi8ixb8l.xn--o3cw4h", - "xn--pgbs0dh", - "xn--kpry57d", - "xn--kprw13d", - "xn--nnx388a", - "xn--j1amh", - "xn--mgb2ddes", - "xxx", - "*.ye", - "ac.za", - "agric.za", - "alt.za", - "co.za", - "edu.za", - "gov.za", - "grondar.za", - "law.za", - "mil.za", - "net.za", - "ngo.za", - "nis.za", - "nom.za", - "org.za", - "school.za", - "tm.za", - "web.za", - "zm", - "ac.zm", - "biz.zm", - "co.zm", - "com.zm", - "edu.zm", - "gov.zm", - "info.zm", - "mil.zm", - "net.zm", - "org.zm", - "sch.zm", - "zw", - "ac.zw", - "co.zw", - "gov.zw", - "mil.zw", - "org.zw", - "aaa", - "aarp", - "abarth", - "abb", - "abbott", - "abbvie", - "abc", - "able", - "abogado", - "abudhabi", - "academy", - "accenture", - "accountant", - "accountants", - "aco", - "active", - "actor", - "adac", - "ads", - "adult", - "aeg", - "aetna", - "afamilycompany", - "afl", - "africa", - "agakhan", - "agency", - "aig", - "aigo", - "airbus", - "airforce", - "airtel", - "akdn", - "alfaromeo", - "alibaba", - "alipay", - "allfinanz", - "allstate", - "ally", - "alsace", - "alstom", - "americanexpress", - "americanfamily", - "amex", - "amfam", - "amica", - "amsterdam", - "analytics", - "android", - "anquan", - "anz", - "aol", - "apartments", - "app", - "apple", - "aquarelle", - "arab", - "aramco", - "archi", - "army", - "art", - "arte", - "asda", - "associates", - "athleta", - "attorney", - "auction", - "audi", - "audible", - "audio", - "auspost", - "author", - "auto", - "autos", - "avianca", - "aws", - "axa", - "azure", - "baby", - "baidu", - "banamex", - "bananarepublic", - "band", - "bank", - "bar", - "barcelona", - "barclaycard", - "barclays", - "barefoot", - "bargains", - "baseball", - "basketball", - "bauhaus", - "bayern", - "bbc", - "bbt", - "bbva", - "bcg", - "bcn", - "beats", - "beauty", - "beer", - "bentley", - "berlin", - "best", - "bestbuy", - "bet", - "bharti", - "bible", - "bid", - "bike", - "bing", - "bingo", - "bio", - "black", - "blackfriday", - "blanco", - "blockbuster", - "blog", - "bloomberg", - "blue", - "bms", - "bmw", - "bnl", - "bnpparibas", - "boats", - "boehringer", - "bofa", - "bom", - "bond", - "boo", - "book", - "booking", - "boots", - "bosch", - "bostik", - "boston", - "bot", - "boutique", - "box", - "bradesco", - "bridgestone", - "broadway", - "broker", - "brother", - "brussels", - "budapest", - "bugatti", - "build", - "builders", - "business", - "buy", - "buzz", - "bzh", - "cab", - "cafe", - "cal", - "call", - "calvinklein", - "cam", - "camera", - "camp", - "cancerresearch", - "canon", - "capetown", - "capital", - "capitalone", - "car", - "caravan", - "cards", - "care", - "career", - "careers", - "cars", - "cartier", - "casa", - "case", - "caseih", - "cash", - "casino", - "catering", - "catholic", - "cba", - "cbn", - "cbre", - "cbs", - "ceb", - "center", - "ceo", - "cern", - "cfa", - "cfd", - "chanel", - "channel", - "chase", - "chat", - "cheap", - "chintai", - "chloe", - "christmas", - "chrome", - "chrysler", - "church", - "cipriani", - "circle", - "cisco", - "citadel", - "citi", - "citic", - "city", - "cityeats", - "claims", - "cleaning", - "click", - "clinic", - "clinique", - "clothing", - "cloud", - "club", - "clubmed", - "coach", - "codes", - "coffee", - "college", - "cologne", - "comcast", - "commbank", - "community", - "company", - "compare", - "computer", - "comsec", - "condos", - "construction", - "consulting", - "contact", - "contractors", - "cooking", - "cookingchannel", - "cool", - "corsica", - "country", - "coupon", - "coupons", - "courses", - "credit", - "creditcard", - "creditunion", - "cricket", - "crown", - "crs", - "cruise", - "cruises", - "csc", - "cuisinella", - "cymru", - "cyou", - "dabur", - "dad", - "dance", - "data", - "date", - "dating", - "datsun", - "day", - "dclk", - "dds", - "deal", - "dealer", - "deals", - "degree", - "delivery", - "dell", - "deloitte", - "delta", - "democrat", - "dental", - "dentist", - "desi", - "design", - "dev", - "dhl", - "diamonds", - "diet", - "digital", - "direct", - "directory", - "discount", - "discover", - "dish", - "diy", - "dnp", - "docs", - "doctor", - "dodge", - "dog", - "doha", - "domains", - "dot", - "download", - "drive", - "dtv", - "dubai", - "duck", - "dunlop", - "duns", - "dupont", - "durban", - "dvag", - "dvr", - "earth", - "eat", - "eco", - "edeka", - "education", - "email", - "emerck", - "energy", - "engineer", - "engineering", - "enterprises", - "epost", - "epson", - "equipment", - "ericsson", - "erni", - "esq", - "estate", - "esurance", - "etisalat", - "eurovision", - "eus", - "events", - "everbank", - "exchange", - "expert", - "exposed", - "express", - "extraspace", - "fage", - "fail", - "fairwinds", - "faith", - "family", - "fan", - "fans", - "farm", - "farmers", - "fashion", - "fast", - "fedex", - "feedback", - "ferrari", - "ferrero", - "fiat", - "fidelity", - "fido", - "film", - "final", - "finance", - "financial", - "fire", - "firestone", - "firmdale", - "fish", - "fishing", - "fit", - "fitness", - "flickr", - "flights", - "flir", - "florist", - "flowers", - "fly", - "foo", - "food", - "foodnetwork", - "football", - "ford", - "forex", - "forsale", - "forum", - "foundation", - "fox", - "free", - "fresenius", - "frl", - "frogans", - "frontdoor", - "frontier", - "ftr", - "fujitsu", - "fujixerox", - "fun", - "fund", - "furniture", - "futbol", - "fyi", - "gal", - "gallery", - "gallo", - "gallup", - "game", - "games", - "gap", - "garden", - "gbiz", - "gdn", - "gea", - "gent", - "genting", - "george", - "ggee", - "gift", - "gifts", - "gives", - "giving", - "glade", - "glass", - "gle", - "global", - "globo", - "gmail", - "gmbh", - "gmo", - "gmx", - "godaddy", - "gold", - "goldpoint", - "golf", - "goo", - "goodhands", - "goodyear", - "goog", - "google", - "gop", - "got", - "grainger", - "graphics", - "gratis", - "green", - "gripe", - "grocery", - "group", - "guardian", - "gucci", - "guge", - "guide", - "guitars", - "guru", - "hair", - "hamburg", - "hangout", - "haus", - "hbo", - "hdfc", - "hdfcbank", - "health", - "healthcare", - "help", - "helsinki", - "here", - "hermes", - "hgtv", - "hiphop", - "hisamitsu", - "hitachi", - "hiv", - "hkt", - "hockey", - "holdings", - "holiday", - "homedepot", - "homegoods", - "homes", - "homesense", - "honda", - "honeywell", - "horse", - "hospital", - "host", - "hosting", - "hot", - "hoteles", - "hotels", - "hotmail", - "house", - "how", - "hsbc", - "htc", - "hughes", - "hyatt", - "hyundai", - "ibm", - "icbc", - "ice", - "icu", - "ieee", - "ifm", - "ikano", - "imamat", - "imdb", - "immo", - "immobilien", - "industries", - "infiniti", - "ing", - "ink", - "institute", - "insurance", - "insure", - "intel", - "international", - "intuit", - "investments", - "ipiranga", - "irish", - "iselect", - "ismaili", - "ist", - "istanbul", - "itau", - "itv", - "iveco", - "iwc", - "jaguar", - "java", - "jcb", - "jcp", - "jeep", - "jetzt", - "jewelry", - "jio", - "jlc", - "jll", - "jmp", - "jnj", - "joburg", - "jot", - "joy", - "jpmorgan", - "jprs", - "juegos", - "juniper", - "kaufen", - "kddi", - "kerryhotels", - "kerrylogistics", - "kerryproperties", - "kfh", - "kia", - "kim", - "kinder", - "kindle", - "kitchen", - "kiwi", - "koeln", - "komatsu", - "kosher", - "kpmg", - "kpn", - "krd", - "kred", - "kuokgroup", - "kyoto", - "lacaixa", - "ladbrokes", - "lamborghini", - "lamer", - "lancaster", - "lancia", - "lancome", - "land", - "landrover", - "lanxess", - "lasalle", - "lat", - "latino", - "latrobe", - "law", - "lawyer", - "lds", - "lease", - "leclerc", - "lefrak", - "legal", - "lego", - "lexus", - "lgbt", - "liaison", - "lidl", - "life", - "lifeinsurance", - "lifestyle", - "lighting", - "like", - "lilly", - "limited", - "limo", - "lincoln", - "linde", - "link", - "lipsy", - "live", - "living", - "lixil", - "loan", - "loans", - "locker", - "locus", - "loft", - "lol", - "london", - "lotte", - "lotto", - "love", - "lpl", - "lplfinancial", - "ltd", - "ltda", - "lundbeck", - "lupin", - "luxe", - "luxury", - "macys", - "madrid", - "maif", - "maison", - "makeup", - "man", - "management", - "mango", - "map", - "market", - "marketing", - "markets", - "marriott", - "marshalls", - "maserati", - "mattel", - "mba", - "mcd", - "mcdonalds", - "mckinsey", - "med", - "media", - "meet", - "melbourne", - "meme", - "memorial", - "men", - "menu", - "meo", - "merckmsd", - "metlife", - "miami", - "microsoft", - "mini", - "mint", - "mit", - "mitsubishi", - "mlb", - "mls", - "mma", - "mobile", - "mobily", - "moda", - "moe", - "moi", - "mom", - "monash", - "money", - "monster", - "montblanc", - "mopar", - "mormon", - "mortgage", - "moscow", - "moto", - "motorcycles", - "mov", - "movie", - "movistar", - "msd", - "mtn", - "mtpc", - "mtr", - "mutual", - "nab", - "nadex", - "nagoya", - "nationwide", - "natura", - "navy", - "nba", - "nec", - "netbank", - "netflix", - "network", - "neustar", - "new", - "newholland", - "news", - "next", - "nextdirect", - "nexus", - "nfl", - "ngo", - "nhk", - "nico", - "nike", - "nikon", - "ninja", - "nissan", - "nissay", - "nokia", - "northwesternmutual", - "norton", - "now", - "nowruz", - "nowtv", - "nra", - "nrw", - "ntt", - "nyc", - "obi", - "observer", - "off", - "office", - "okinawa", - "olayan", - "olayangroup", - "oldnavy", - "ollo", - "omega", - "one", - "ong", - "onl", - "online", - "onyourside", - "ooo", - "open", - "oracle", - "orange", - "organic", - "origins", - "osaka", - "otsuka", - "ott", - "ovh", - "page", - "pamperedchef", - "panasonic", - "panerai", - "paris", - "pars", - "partners", - "parts", - "party", - "passagens", - "pay", - "pccw", - "pet", - "pfizer", - "pharmacy", - "phd", - "philips", - "phone", - "photo", - "photography", - "photos", - "physio", - "piaget", - "pics", - "pictet", - "pictures", - "pid", - "pin", - "ping", - "pink", - "pioneer", - "pizza", - "place", - "play", - "playstation", - "plumbing", - "plus", - "pnc", - "pohl", - "poker", - "politie", - "porn", - "pramerica", - "praxi", - "press", - "prime", - "prod", - "productions", - "prof", - "progressive", - "promo", - "properties", - "property", - "protection", - "pru", - "prudential", - "pub", - "pwc", - "qpon", - "quebec", - "quest", - "qvc", - "racing", - "radio", - "raid", - "read", - "realestate", - "realtor", - "realty", - "recipes", - "red", - "redstone", - "redumbrella", - "rehab", - "reise", - "reisen", - "reit", - "reliance", - "ren", - "rent", - "rentals", - "repair", - "report", - "republican", - "rest", - "restaurant", - "review", - "reviews", - "rexroth", - "rich", - "richardli", - "ricoh", - "rightathome", - "ril", - "rio", - "rip", - "rmit", - "rocher", - "rocks", - "rodeo", - "rogers", - "room", - "rsvp", - "rugby", - "ruhr", - "run", - "rwe", - "ryukyu", - "saarland", - "safe", - "safety", - "sakura", - "sale", - "salon", - "samsclub", - "samsung", - "sandvik", - "sandvikcoromant", - "sanofi", - "sap", - "sapo", - "sarl", - "sas", - "save", - "saxo", - "sbi", - "sbs", - "sca", - "scb", - "schaeffler", - "schmidt", - "scholarships", - "school", - "schule", - "schwarz", - "science", - "scjohnson", - "scor", - "scot", - "search", - "seat", - "secure", - "security", - "seek", - "select", - "sener", - "services", - "ses", - "seven", - "sew", - "sex", - "sexy", - "sfr", - "shangrila", - "sharp", - "shaw", - "shell", - "shia", - "shiksha", - "shoes", - "shop", - "shopping", - "shouji", - "show", - "showtime", - "shriram", - "silk", - "sina", - "singles", - "site", - "ski", - "skin", - "sky", - "skype", - "sling", - "smart", - "smile", - "sncf", - "soccer", - "social", - "softbank", - "software", - "sohu", - "solar", - "solutions", - "song", - "sony", - "soy", - "space", - "spiegel", - "spot", - "spreadbetting", - "srl", - "srt", - "stada", - "staples", - "star", - "starhub", - "statebank", - "statefarm", - "statoil", - "stc", - "stcgroup", - "stockholm", - "storage", - "store", - "stream", - "studio", - "study", - "style", - "sucks", - "supplies", - "supply", - "support", - "surf", - "surgery", - "suzuki", - "swatch", - "swiftcover", - "swiss", - "sydney", - "symantec", - "systems", - "tab", - "taipei", - "talk", - "taobao", - "target", - "tatamotors", - "tatar", - "tattoo", - "tax", - "taxi", - "tci", - "tdk", - "team", - "tech", - "technology", - "telecity", - "telefonica", - "temasek", - "tennis", - "teva", - "thd", - "theater", - "theatre", - "tiaa", - "tickets", - "tienda", - "tiffany", - "tips", - "tires", - "tirol", - "tjmaxx", - "tjx", - "tkmaxx", - "tmall", - "today", - "tokyo", - "tools", - "top", - "toray", - "toshiba", - "total", - "tours", - "town", - "toyota", - "toys", - "trade", - "trading", - "training", - "travelchannel", - "travelers", - "travelersinsurance", - "trust", - "trv", - "tube", - "tui", - "tunes", - "tushu", - "tvs", - "ubank", - "ubs", - "uconnect", - "unicom", - "university", - "uno", - "uol", - "ups", - "vacations", - "vana", - "vanguard", - "vegas", - "ventures", - "verisign", - "versicherung", - "vet", - "viajes", - "video", - "vig", - "viking", - "villas", - "vin", - "vip", - "virgin", - "visa", - "vision", - "vista", - "vistaprint", - "viva", - "vivo", - "vlaanderen", - "vodka", - "volkswagen", - "volvo", - "vote", - "voting", - "voto", - "voyage", - "vuelos", - "wales", - "walmart", - "walter", - "wang", - "wanggou", - "warman", - "watch", - "watches", - "weather", - "weatherchannel", - "webcam", - "weber", - "website", - "wed", - "wedding", - "weibo", - "weir", - "whoswho", - "wien", - "wiki", - "williamhill", - "win", - "windows", - "wine", - "winners", - "wme", - "wolterskluwer", - "woodside", - "work", - "works", - "world", - "wow", - "wtc", - "wtf", - "xbox", - "xerox", - "xfinity", - "xihuan", - "xin", - "xn--11b4c3d", - "xn--1ck2e1b", - "xn--1qqw23a", - "xn--30rr7y", - "xn--3bst00m", - "xn--3ds443g", - "xn--3oq18vl8pn36a", - "xn--3pxu8k", - "xn--42c2d9a", - "xn--45q11c", - "xn--4gbrim", - "xn--55qw42g", - "xn--55qx5d", - "xn--5su34j936bgsg", - "xn--5tzm5g", - "xn--6frz82g", - "xn--6qq986b3xl", - "xn--80adxhks", - "xn--80aqecdr1a", - "xn--80asehdb", - "xn--80aswg", - "xn--8y0a063a", - "xn--9dbq2a", - "xn--9et52u", - "xn--9krt00a", - "xn--b4w605ferd", - "xn--bck1b9a5dre4c", - "xn--c1avg", - "xn--c2br7g", - "xn--cck2b3b", - "xn--cg4bki", - "xn--czr694b", - "xn--czrs0t", - "xn--czru2d", - "xn--d1acj3b", - "xn--eckvdtc9d", - "xn--efvy88h", - "xn--estv75g", - "xn--fct429k", - "xn--fhbei", - "xn--fiq228c5hs", - "xn--fiq64b", - "xn--fjq720a", - "xn--flw351e", - "xn--fzys8d69uvgm", - "xn--g2xx48c", - "xn--gckr3f0f", - "xn--gk3at1e", - "xn--hxt814e", - "xn--i1b6b1a6a2e", - "xn--imr513n", - "xn--io0a7i", - "xn--j1aef", - "xn--jlq61u9w7b", - "xn--jvr189m", - "xn--kcrx77d1x4a", - "xn--kpu716f", - "xn--kput3i", - "xn--mgba3a3ejt", - "xn--mgba7c0bbn0a", - "xn--mgbaakc7dvf", - "xn--mgbab2bd", - "xn--mgbb9fbpob", - "xn--mgbca7dzdo", - "xn--mgbi4ecexp", - "xn--mgbt3dhd", - "xn--mk1bu44c", - "xn--mxtq1m", - "xn--ngbc5azd", - "xn--ngbe9e0a", - "xn--ngbrx", - "xn--nqv7f", - "xn--nqv7fs00ema", - "xn--nyqy26a", - "xn--p1acf", - "xn--pbt977c", - "xn--pssy2u", - "xn--q9jyb4c", - "xn--qcka1pmc", - "xn--rhqv96g", - "xn--rovu88b", - "xn--ses554g", - "xn--t60b56a", - "xn--tckwe", - "xn--tiq49xqyj", - "xn--unup4y", - "xn--vermgensberater-ctb", - "xn--vermgensberatung-pwb", - "xn--vhquv", - "xn--vuq861b", - "xn--w4r85el8fhu5dnra", - "xn--w4rs40l", - "xn--xhq521b", - "xn--zfr164b", - "xperia", - "xyz", - "yachts", - "yahoo", - "yamaxun", - "yandex", - "yodobashi", - "yoga", - "yokohama", - "you", - "youtube", - "yun", - "zappos", - "zara", - "zero", - "zip", - "zippo", - "zone", - "zuerich", - "cc.ua", - "inf.ua", - "ltd.ua", - "beep.pl", - "*.compute.estate", - "*.alces.network", - "*.alwaysdata.net", - "cloudfront.net", - "*.compute.amazonaws.com", - "*.compute-1.amazonaws.com", - "*.compute.amazonaws.com.cn", - "us-east-1.amazonaws.com", - "cn-north-1.eb.amazonaws.com.cn", - "elasticbeanstalk.com", - "ap-northeast-1.elasticbeanstalk.com", - "ap-northeast-2.elasticbeanstalk.com", - "ap-south-1.elasticbeanstalk.com", - "ap-southeast-1.elasticbeanstalk.com", - "ap-southeast-2.elasticbeanstalk.com", - "ca-central-1.elasticbeanstalk.com", - "eu-central-1.elasticbeanstalk.com", - "eu-west-1.elasticbeanstalk.com", - "eu-west-2.elasticbeanstalk.com", - "sa-east-1.elasticbeanstalk.com", - "us-east-1.elasticbeanstalk.com", - "us-east-2.elasticbeanstalk.com", - "us-gov-west-1.elasticbeanstalk.com", - "us-west-1.elasticbeanstalk.com", - "us-west-2.elasticbeanstalk.com", - "*.elb.amazonaws.com", - "*.elb.amazonaws.com.cn", - "s3.amazonaws.com", - "s3-ap-northeast-1.amazonaws.com", - "s3-ap-northeast-2.amazonaws.com", - "s3-ap-south-1.amazonaws.com", - "s3-ap-southeast-1.amazonaws.com", - "s3-ap-southeast-2.amazonaws.com", - "s3-ca-central-1.amazonaws.com", - "s3-eu-central-1.amazonaws.com", - "s3-eu-west-1.amazonaws.com", - "s3-eu-west-2.amazonaws.com", - "s3-external-1.amazonaws.com", - "s3-fips-us-gov-west-1.amazonaws.com", - "s3-sa-east-1.amazonaws.com", - "s3-us-gov-west-1.amazonaws.com", - "s3-us-east-2.amazonaws.com", - "s3-us-west-1.amazonaws.com", - "s3-us-west-2.amazonaws.com", - "s3.ap-northeast-2.amazonaws.com", - "s3.ap-south-1.amazonaws.com", - "s3.cn-north-1.amazonaws.com.cn", - "s3.ca-central-1.amazonaws.com", - "s3.eu-central-1.amazonaws.com", - "s3.eu-west-2.amazonaws.com", - "s3.us-east-2.amazonaws.com", - "s3.dualstack.ap-northeast-1.amazonaws.com", - "s3.dualstack.ap-northeast-2.amazonaws.com", - "s3.dualstack.ap-south-1.amazonaws.com", - "s3.dualstack.ap-southeast-1.amazonaws.com", - "s3.dualstack.ap-southeast-2.amazonaws.com", - "s3.dualstack.ca-central-1.amazonaws.com", - "s3.dualstack.eu-central-1.amazonaws.com", - "s3.dualstack.eu-west-1.amazonaws.com", - "s3.dualstack.eu-west-2.amazonaws.com", - "s3.dualstack.sa-east-1.amazonaws.com", - "s3.dualstack.us-east-1.amazonaws.com", - "s3.dualstack.us-east-2.amazonaws.com", - "s3-website-us-east-1.amazonaws.com", - "s3-website-us-west-1.amazonaws.com", - "s3-website-us-west-2.amazonaws.com", - "s3-website-ap-northeast-1.amazonaws.com", - "s3-website-ap-southeast-1.amazonaws.com", - "s3-website-ap-southeast-2.amazonaws.com", - "s3-website-eu-west-1.amazonaws.com", - "s3-website-sa-east-1.amazonaws.com", - "s3-website.ap-northeast-2.amazonaws.com", - "s3-website.ap-south-1.amazonaws.com", - "s3-website.ca-central-1.amazonaws.com", - "s3-website.eu-central-1.amazonaws.com", - "s3-website.eu-west-2.amazonaws.com", - "s3-website.us-east-2.amazonaws.com", - "t3l3p0rt.net", - "tele.amune.org", - "on-aptible.com", - "user.party.eus", - "pimienta.org", - "poivron.org", - "potager.org", - "sweetpepper.org", - "myasustor.com", - "myfritz.net", - "*.awdev.ca", - "*.advisor.ws", - "backplaneapp.io", - "betainabox.com", - "bnr.la", - "boomla.net", - "boxfuse.io", - "square7.ch", - "bplaced.com", - "bplaced.de", - "square7.de", - "bplaced.net", - "square7.net", - "browsersafetymark.io", - "mycd.eu", - "ae.org", - "ar.com", - "br.com", - "cn.com", - "com.de", - "com.se", - "de.com", - "eu.com", - "gb.com", - "gb.net", - "hu.com", - "hu.net", - "jp.net", - "jpn.com", - "kr.com", - "mex.com", - "no.com", - "qc.com", - "ru.com", - "sa.com", - "se.com", - "se.net", - "uk.com", - "uk.net", - "us.com", - "uy.com", - "za.bz", - "za.com", - "africa.com", - "gr.com", - "in.net", - "us.org", - "co.com", - "c.la", - "certmgr.org", - "xenapponazure.com", - "virtueeldomein.nl", - "c66.me", - "jdevcloud.com", - "wpdevcloud.com", - "cloudaccess.host", - "freesite.host", - "cloudaccess.net", - "cloudcontrolled.com", - "cloudcontrolapp.com", - "co.ca", - "co.cz", - "c.cdn77.org", - "cdn77-ssl.net", - "r.cdn77.net", - "rsc.cdn77.org", - "ssl.origin.cdn77-secure.org", - "cloudns.asia", - "cloudns.biz", - "cloudns.club", - "cloudns.cc", - "cloudns.eu", - "cloudns.in", - "cloudns.info", - "cloudns.org", - "cloudns.pro", - "cloudns.pw", - "cloudns.us", - "co.nl", - "co.no", - "dyn.cosidns.de", - "dynamisches-dns.de", - "dnsupdater.de", - "internet-dns.de", - "l-o-g-i-n.de", - "dynamic-dns.info", - "feste-ip.net", - "knx-server.net", - "static-access.net", - "realm.cz", - "*.cryptonomic.net", - "cupcake.is", - "cyon.link", - "cyon.site", - "daplie.me", - "localhost.daplie.me", - "biz.dk", - "co.dk", - "firm.dk", - "reg.dk", - "store.dk", - "debian.net", - "dedyn.io", - "dnshome.de", - "drayddns.com", - "dreamhosters.com", - "mydrobo.com", - "drud.io", - "drud.us", - "duckdns.org", - "dy.fi", - "tunk.org", - "dyndns-at-home.com", - "dyndns-at-work.com", - "dyndns-blog.com", - "dyndns-free.com", - "dyndns-home.com", - "dyndns-ip.com", - "dyndns-mail.com", - "dyndns-office.com", - "dyndns-pics.com", - "dyndns-remote.com", - "dyndns-server.com", - "dyndns-web.com", - "dyndns-wiki.com", - "dyndns-work.com", - "dyndns.biz", - "dyndns.info", - "dyndns.org", - "dyndns.tv", - "at-band-camp.net", - "ath.cx", - "barrel-of-knowledge.info", - "barrell-of-knowledge.info", - "better-than.tv", - "blogdns.com", - "blogdns.net", - "blogdns.org", - "blogsite.org", - "boldlygoingnowhere.org", - "broke-it.net", - "buyshouses.net", - "cechire.com", - "dnsalias.com", - "dnsalias.net", - "dnsalias.org", - "dnsdojo.com", - "dnsdojo.net", - "dnsdojo.org", - "does-it.net", - "doesntexist.com", - "doesntexist.org", - "dontexist.com", - "dontexist.net", - "dontexist.org", - "doomdns.com", - "doomdns.org", - "dvrdns.org", - "dyn-o-saur.com", - "dynalias.com", - "dynalias.net", - "dynalias.org", - "dynathome.net", - "dyndns.ws", - "endofinternet.net", - "endofinternet.org", - "endoftheinternet.org", - "est-a-la-maison.com", - "est-a-la-masion.com", - "est-le-patron.com", - "est-mon-blogueur.com", - "for-better.biz", - "for-more.biz", - "for-our.info", - "for-some.biz", - "for-the.biz", - "forgot.her.name", - "forgot.his.name", - "from-ak.com", - "from-al.com", - "from-ar.com", - "from-az.net", - "from-ca.com", - "from-co.net", - "from-ct.com", - "from-dc.com", - "from-de.com", - "from-fl.com", - "from-ga.com", - "from-hi.com", - "from-ia.com", - "from-id.com", - "from-il.com", - "from-in.com", - "from-ks.com", - "from-ky.com", - "from-la.net", - "from-ma.com", - "from-md.com", - "from-me.org", - "from-mi.com", - "from-mn.com", - "from-mo.com", - "from-ms.com", - "from-mt.com", - "from-nc.com", - "from-nd.com", - "from-ne.com", - "from-nh.com", - "from-nj.com", - "from-nm.com", - "from-nv.com", - "from-ny.net", - "from-oh.com", - "from-ok.com", - "from-or.com", - "from-pa.com", - "from-pr.com", - "from-ri.com", - "from-sc.com", - "from-sd.com", - "from-tn.com", - "from-tx.com", - "from-ut.com", - "from-va.com", - "from-vt.com", - "from-wa.com", - "from-wi.com", - "from-wv.com", - "from-wy.com", - "ftpaccess.cc", - "fuettertdasnetz.de", - "game-host.org", - "game-server.cc", - "getmyip.com", - "gets-it.net", - "go.dyndns.org", - "gotdns.com", - "gotdns.org", - "groks-the.info", - "groks-this.info", - "ham-radio-op.net", - "here-for-more.info", - "hobby-site.com", - "hobby-site.org", - "home.dyndns.org", - "homedns.org", - "homeftp.net", - "homeftp.org", - "homeip.net", - "homelinux.com", - "homelinux.net", - "homelinux.org", - "homeunix.com", - "homeunix.net", - "homeunix.org", - "iamallama.com", - "in-the-band.net", - "is-a-anarchist.com", - "is-a-blogger.com", - "is-a-bookkeeper.com", - "is-a-bruinsfan.org", - "is-a-bulls-fan.com", - "is-a-candidate.org", - "is-a-caterer.com", - "is-a-celticsfan.org", - "is-a-chef.com", - "is-a-chef.net", - "is-a-chef.org", - "is-a-conservative.com", - "is-a-cpa.com", - "is-a-cubicle-slave.com", - "is-a-democrat.com", - "is-a-designer.com", - "is-a-doctor.com", - "is-a-financialadvisor.com", - "is-a-geek.com", - "is-a-geek.net", - "is-a-geek.org", - "is-a-green.com", - "is-a-guru.com", - "is-a-hard-worker.com", - "is-a-hunter.com", - "is-a-knight.org", - "is-a-landscaper.com", - "is-a-lawyer.com", - "is-a-liberal.com", - "is-a-libertarian.com", - "is-a-linux-user.org", - "is-a-llama.com", - "is-a-musician.com", - "is-a-nascarfan.com", - "is-a-nurse.com", - "is-a-painter.com", - "is-a-patsfan.org", - "is-a-personaltrainer.com", - "is-a-photographer.com", - "is-a-player.com", - "is-a-republican.com", - "is-a-rockstar.com", - "is-a-socialist.com", - "is-a-soxfan.org", - "is-a-student.com", - "is-a-teacher.com", - "is-a-techie.com", - "is-a-therapist.com", - "is-an-accountant.com", - "is-an-actor.com", - "is-an-actress.com", - "is-an-anarchist.com", - "is-an-artist.com", - "is-an-engineer.com", - "is-an-entertainer.com", - "is-by.us", - "is-certified.com", - "is-found.org", - "is-gone.com", - "is-into-anime.com", - "is-into-cars.com", - "is-into-cartoons.com", - "is-into-games.com", - "is-leet.com", - "is-lost.org", - "is-not-certified.com", - "is-saved.org", - "is-slick.com", - "is-uberleet.com", - "is-very-bad.org", - "is-very-evil.org", - "is-very-good.org", - "is-very-nice.org", - "is-very-sweet.org", - "is-with-theband.com", - "isa-geek.com", - "isa-geek.net", - "isa-geek.org", - "isa-hockeynut.com", - "issmarterthanyou.com", - "isteingeek.de", - "istmein.de", - "kicks-ass.net", - "kicks-ass.org", - "knowsitall.info", - "land-4-sale.us", - "lebtimnetz.de", - "leitungsen.de", - "likes-pie.com", - "likescandy.com", - "merseine.nu", - "mine.nu", - "misconfused.org", - "mypets.ws", - "myphotos.cc", - "neat-url.com", - "office-on-the.net", - "on-the-web.tv", - "podzone.net", - "podzone.org", - "readmyblog.org", - "saves-the-whales.com", - "scrapper-site.net", - "scrapping.cc", - "selfip.biz", - "selfip.com", - "selfip.info", - "selfip.net", - "selfip.org", - "sells-for-less.com", - "sells-for-u.com", - "sells-it.net", - "sellsyourhome.org", - "servebbs.com", - "servebbs.net", - "servebbs.org", - "serveftp.net", - "serveftp.org", - "servegame.org", - "shacknet.nu", - "simple-url.com", - "space-to-rent.com", - "stuff-4-sale.org", - "stuff-4-sale.us", - "teaches-yoga.com", - "thruhere.net", - "traeumtgerade.de", - "webhop.biz", - "webhop.info", - "webhop.net", - "webhop.org", - "worse-than.tv", - "writesthisblog.com", - "ddnss.de", - "dyn.ddnss.de", - "dyndns.ddnss.de", - "dyndns1.de", - "dyn-ip24.de", - "home-webserver.de", - "dyn.home-webserver.de", - "myhome-server.de", - "ddnss.org", - "definima.net", - "definima.io", - "ddnsfree.com", - "ddnsgeek.com", - "giize.com", - "gleeze.com", - "kozow.com", - "loseyourip.com", - "ooguy.com", - "theworkpc.com", - "casacam.net", - "dynu.net", - "accesscam.org", - "camdvr.org", - "freeddns.org", - "mywire.org", - "webredirect.org", - "myddns.rocks", - "blogsite.xyz", - "dynv6.net", - "e4.cz", - "mytuleap.com", - "enonic.io", - "customer.enonic.io", - "eu.org", - "al.eu.org", - "asso.eu.org", - "at.eu.org", - "au.eu.org", - "be.eu.org", - "bg.eu.org", - "ca.eu.org", - "cd.eu.org", - "ch.eu.org", - "cn.eu.org", - "cy.eu.org", - "cz.eu.org", - "de.eu.org", - "dk.eu.org", - "edu.eu.org", - "ee.eu.org", - "es.eu.org", - "fi.eu.org", - "fr.eu.org", - "gr.eu.org", - "hr.eu.org", - "hu.eu.org", - "ie.eu.org", - "il.eu.org", - "in.eu.org", - "int.eu.org", - "is.eu.org", - "it.eu.org", - "jp.eu.org", - "kr.eu.org", - "lt.eu.org", - "lu.eu.org", - "lv.eu.org", - "mc.eu.org", - "me.eu.org", - "mk.eu.org", - "mt.eu.org", - "my.eu.org", - "net.eu.org", - "ng.eu.org", - "nl.eu.org", - "no.eu.org", - "nz.eu.org", - "paris.eu.org", - "pl.eu.org", - "pt.eu.org", - "q-a.eu.org", - "ro.eu.org", - "ru.eu.org", - "se.eu.org", - "si.eu.org", - "sk.eu.org", - "tr.eu.org", - "uk.eu.org", - "us.eu.org", - "eu-1.evennode.com", - "eu-2.evennode.com", - "eu-3.evennode.com", - "eu-4.evennode.com", - "us-1.evennode.com", - "us-2.evennode.com", - "us-3.evennode.com", - "us-4.evennode.com", - "twmail.cc", - "twmail.net", - "twmail.org", - "mymailer.com.tw", - "url.tw", - "apps.fbsbx.com", - "ru.net", - "adygeya.ru", - "bashkiria.ru", - "bir.ru", - "cbg.ru", - "com.ru", - "dagestan.ru", - "grozny.ru", - "kalmykia.ru", - "kustanai.ru", - "marine.ru", - "mordovia.ru", - "msk.ru", - "mytis.ru", - "nalchik.ru", - "nov.ru", - "pyatigorsk.ru", - "spb.ru", - "vladikavkaz.ru", - "vladimir.ru", - "abkhazia.su", - "adygeya.su", - "aktyubinsk.su", - "arkhangelsk.su", - "armenia.su", - "ashgabad.su", - "azerbaijan.su", - "balashov.su", - "bashkiria.su", - "bryansk.su", - "bukhara.su", - "chimkent.su", - "dagestan.su", - "east-kazakhstan.su", - "exnet.su", - "georgia.su", - "grozny.su", - "ivanovo.su", - "jambyl.su", - "kalmykia.su", - "kaluga.su", - "karacol.su", - "karaganda.su", - "karelia.su", - "khakassia.su", - "krasnodar.su", - "kurgan.su", - "kustanai.su", - "lenug.su", - "mangyshlak.su", - "mordovia.su", - "msk.su", - "murmansk.su", - "nalchik.su", - "navoi.su", - "north-kazakhstan.su", - "nov.su", - "obninsk.su", - "penza.su", - "pokrovsk.su", - "sochi.su", - "spb.su", - "tashkent.su", - "termez.su", - "togliatti.su", - "troitsk.su", - "tselinograd.su", - "tula.su", - "tuva.su", - "vladikavkaz.su", - "vladimir.su", - "vologda.su", - "channelsdvr.net", - "fastlylb.net", - "map.fastlylb.net", - "freetls.fastly.net", - "map.fastly.net", - "a.prod.fastly.net", - "global.prod.fastly.net", - "a.ssl.fastly.net", - "b.ssl.fastly.net", - "global.ssl.fastly.net", - "fhapp.xyz", - "fedorainfracloud.org", - "fedorapeople.org", - "cloud.fedoraproject.org", - "filegear.me", - "firebaseapp.com", - "flynnhub.com", - "flynnhosting.net", - "freebox-os.com", - "freeboxos.com", - "fbx-os.fr", - "fbxos.fr", - "freebox-os.fr", - "freeboxos.fr", - "myfusion.cloud", - "*.futurecms.at", - "futurehosting.at", - "futuremailing.at", - "*.ex.ortsinfo.at", - "*.kunden.ortsinfo.at", - "*.statics.cloud", - "service.gov.uk", - "github.io", - "githubusercontent.com", - "gitlab.io", - "homeoffice.gov.uk", - "ro.im", - "shop.ro", - "goip.de", - "*.0emm.com", - "appspot.com", - "blogspot.ae", - "blogspot.al", - "blogspot.am", - "blogspot.ba", - "blogspot.be", - "blogspot.bg", - "blogspot.bj", - "blogspot.ca", - "blogspot.cf", - "blogspot.ch", - "blogspot.cl", - "blogspot.co.at", - "blogspot.co.id", - "blogspot.co.il", - "blogspot.co.ke", - "blogspot.co.nz", - "blogspot.co.uk", - "blogspot.co.za", - "blogspot.com", - "blogspot.com.ar", - "blogspot.com.au", - "blogspot.com.br", - "blogspot.com.by", - "blogspot.com.co", - "blogspot.com.cy", - "blogspot.com.ee", - "blogspot.com.eg", - "blogspot.com.es", - "blogspot.com.mt", - "blogspot.com.ng", - "blogspot.com.tr", - "blogspot.com.uy", - "blogspot.cv", - "blogspot.cz", - "blogspot.de", - "blogspot.dk", - "blogspot.fi", - "blogspot.fr", - "blogspot.gr", - "blogspot.hk", - "blogspot.hr", - "blogspot.hu", - "blogspot.ie", - "blogspot.in", - "blogspot.is", - "blogspot.it", - "blogspot.jp", - "blogspot.kr", - "blogspot.li", - "blogspot.lt", - "blogspot.lu", - "blogspot.md", - "blogspot.mk", - "blogspot.mr", - "blogspot.mx", - "blogspot.my", - "blogspot.nl", - "blogspot.no", - "blogspot.pe", - "blogspot.pt", - "blogspot.qa", - "blogspot.re", - "blogspot.ro", - "blogspot.rs", - "blogspot.ru", - "blogspot.se", - "blogspot.sg", - "blogspot.si", - "blogspot.sk", - "blogspot.sn", - "blogspot.td", - "blogspot.tw", - "blogspot.ug", - "blogspot.vn", - "cloudfunctions.net", - "cloud.goog", - "codespot.com", - "googleapis.com", - "googlecode.com", - "pagespeedmobilizer.com", - "publishproxy.com", - "withgoogle.com", - "withyoutube.com", - "hashbang.sh", - "hasura-app.io", - "hepforge.org", - "herokuapp.com", - "herokussl.com", - "moonscale.net", - "iki.fi", - "biz.at", - "info.at", - "info.cx", - "ac.leg.br", - "al.leg.br", - "am.leg.br", - "ap.leg.br", - "ba.leg.br", - "ce.leg.br", - "df.leg.br", - "es.leg.br", - "go.leg.br", - "ma.leg.br", - "mg.leg.br", - "ms.leg.br", - "mt.leg.br", - "pa.leg.br", - "pb.leg.br", - "pe.leg.br", - "pi.leg.br", - "pr.leg.br", - "rj.leg.br", - "rn.leg.br", - "ro.leg.br", - "rr.leg.br", - "rs.leg.br", - "sc.leg.br", - "se.leg.br", - "sp.leg.br", - "to.leg.br", - "pixolino.com", - "ipifony.net", - "*.triton.zone", - "*.cns.joyent.com", - "js.org", - "keymachine.de", - "knightpoint.systems", - "co.krd", - "edu.krd", - "git-repos.de", - "lcube-server.de", - "svn-repos.de", - "we.bs", - "barsy.bg", - "barsyonline.com", - "barsy.de", - "barsy.eu", - "barsy.in", - "barsy.net", - "barsy.online", - "barsy.support", - "*.magentosite.cloud", - "hb.cldmail.ru", - "cloud.metacentrum.cz", - "custom.metacentrum.cz", - "meteorapp.com", - "eu.meteorapp.com", - "co.pl", - "azurewebsites.net", - "azure-mobile.net", - "cloudapp.net", - "bmoattachments.org", - "net.ru", - "org.ru", - "pp.ru", - "bitballoon.com", - "netlify.com", - "4u.com", - "ngrok.io", - "nfshost.com", - "nsupdate.info", - "nerdpol.ovh", - "blogsyte.com", - "brasilia.me", - "cable-modem.org", - "ciscofreak.com", - "collegefan.org", - "couchpotatofries.org", - "damnserver.com", - "ddns.me", - "ditchyourip.com", - "dnsfor.me", - "dnsiskinky.com", - "dvrcam.info", - "dynns.com", - "eating-organic.net", - "fantasyleague.cc", - "geekgalaxy.com", - "golffan.us", - "health-carereform.com", - "homesecuritymac.com", - "homesecuritypc.com", - "hopto.me", - "ilovecollege.info", - "loginto.me", - "mlbfan.org", - "mmafan.biz", - "myactivedirectory.com", - "mydissent.net", - "myeffect.net", - "mymediapc.net", - "mypsx.net", - "mysecuritycamera.com", - "mysecuritycamera.net", - "mysecuritycamera.org", - "net-freaks.com", - "nflfan.org", - "nhlfan.net", - "no-ip.ca", - "no-ip.co.uk", - "no-ip.net", - "noip.us", - "onthewifi.com", - "pgafan.net", - "point2this.com", - "pointto.us", - "privatizehealthinsurance.net", - "quicksytes.com", - "read-books.org", - "securitytactics.com", - "serveexchange.com", - "servehumour.com", - "servep2p.com", - "servesarcasm.com", - "stufftoread.com", - "ufcfan.org", - "unusualperson.com", - "workisboring.com", - "3utilities.com", - "bounceme.net", - "ddns.net", - "ddnsking.com", - "gotdns.ch", - "hopto.org", - "myftp.biz", - "myftp.org", - "myvnc.com", - "no-ip.biz", - "no-ip.info", - "no-ip.org", - "noip.me", - "redirectme.net", - "servebeer.com", - "serveblog.net", - "servecounterstrike.com", - "serveftp.com", - "servegame.com", - "servehalflife.com", - "servehttp.com", - "serveirc.com", - "serveminecraft.net", - "servemp3.com", - "servepics.com", - "servequake.com", - "sytes.net", - "webhop.me", - "zapto.org", - "stage.nodeart.io", - "nodum.co", - "nodum.io", - "nyc.mn", - "nom.ae", - "nom.ai", - "nom.al", - "nym.by", - "nym.bz", - "nom.cl", - "nom.gd", - "nom.gl", - "nym.gr", - "nom.gt", - "nom.hn", - "nom.im", - "nym.kz", - "nym.la", - "nom.li", - "nym.li", - "nym.lt", - "nym.lu", - "nym.me", - "nom.mk", - "nym.mx", - "nom.nu", - "nym.nz", - "nym.pe", - "nym.pt", - "nom.pw", - "nom.qa", - "nom.rs", - "nom.si", - "nym.sk", - "nym.su", - "nym.sx", - "nym.tw", - "nom.ug", - "nom.uy", - "nom.vc", - "nom.vg", - "cya.gg", - "nid.io", - "opencraft.hosting", - "operaunite.com", - "outsystemscloud.com", - "ownprovider.com", - "oy.lc", - "pgfog.com", - "pagefrontapp.com", - "art.pl", - "gliwice.pl", - "krakow.pl", - "poznan.pl", - "wroc.pl", - "zakopane.pl", - "pantheonsite.io", - "gotpantheon.com", - "mypep.link", - "on-web.fr", - "*.platform.sh", - "*.platformsh.site", - "xen.prgmr.com", - "priv.at", - "protonet.io", - "chirurgiens-dentistes-en-france.fr", - "byen.site", - "qa2.com", - "dev-myqnapcloud.com", - "alpha-myqnapcloud.com", - "myqnapcloud.com", - "*.quipelements.com", - "vapor.cloud", - "vaporcloud.io", - "rackmaze.com", - "rackmaze.net", - "rhcloud.com", - "hzc.io", - "wellbeingzone.eu", - "ptplus.fit", - "wellbeingzone.co.uk", - "sandcats.io", - "logoip.de", - "logoip.com", - "firewall-gateway.com", - "firewall-gateway.de", - "my-gateway.de", - "my-router.de", - "spdns.de", - "spdns.eu", - "firewall-gateway.net", - "my-firewall.org", - "myfirewall.org", - "spdns.org", - "*.sensiosite.cloud", - "biz.ua", - "co.ua", - "pp.ua", - "shiftedit.io", - "myshopblocks.com", - "1kapp.com", - "appchizi.com", - "applinzi.com", - "sinaapp.com", - "vipsinaapp.com", - "bounty-full.com", - "alpha.bounty-full.com", - "beta.bounty-full.com", - "static.land", - "dev.static.land", - "sites.static.land", - "apps.lair.io", - "*.stolos.io", - "spacekit.io", - "stackspace.space", - "storj.farm", - "temp-dns.com", - "diskstation.me", - "dscloud.biz", - "dscloud.me", - "dscloud.mobi", - "dsmynas.com", - "dsmynas.net", - "dsmynas.org", - "familyds.com", - "familyds.net", - "familyds.org", - "i234.me", - "myds.me", - "synology.me", - "vpnplus.to", - "taifun-dns.de", - "gda.pl", - "gdansk.pl", - "gdynia.pl", - "med.pl", - "sopot.pl", - "cust.dev.thingdust.io", - "cust.disrec.thingdust.io", - "cust.prod.thingdust.io", - "cust.testing.thingdust.io", - "bloxcms.com", - "townnews-staging.com", - "12hp.at", - "2ix.at", - "4lima.at", - "lima-city.at", - "12hp.ch", - "2ix.ch", - "4lima.ch", - "lima-city.ch", - "trafficplex.cloud", - "de.cool", - "12hp.de", - "2ix.de", - "4lima.de", - "lima-city.de", - "1337.pictures", - "clan.rip", - "lima-city.rocks", - "webspace.rocks", - "lima.zone", - "*.transurl.be", - "*.transurl.eu", - "*.transurl.nl", - "tuxfamily.org", - "dd-dns.de", - "diskstation.eu", - "diskstation.org", - "dray-dns.de", - "draydns.de", - "dyn-vpn.de", - "dynvpn.de", - "mein-vigor.de", - "my-vigor.de", - "my-wan.de", - "syno-ds.de", - "synology-diskstation.de", - "synology-ds.de", - "uber.space", - "hk.com", - "hk.org", - "ltd.hk", - "inc.hk", - "lib.de.us", - "router.management", - "v-info.info", - "wedeploy.io", - "wedeploy.me", - "wedeploy.sh", - "remotewd.com", - "wmflabs.org", - "cistron.nl", - "demon.nl", - "xs4all.space", - "yolasite.com", - "ybo.faith", - "yombo.me", - "homelink.one", - "ybo.party", - "ybo.review", - "ybo.science", - "ybo.trade", - "za.net", - "za.org", - "now.sh", -} - -var nodeLabels = [...]string{ - "aaa", - "aarp", - "abarth", - "abb", - "abbott", - "abbvie", - "abc", - "able", - "abogado", - "abudhabi", - "ac", - "academy", - "accenture", - "accountant", - "accountants", - "aco", - "active", - "actor", - "ad", - "adac", - "ads", - "adult", - "ae", - "aeg", - "aero", - "aetna", - "af", - "afamilycompany", - "afl", - "africa", - "ag", - "agakhan", - "agency", - "ai", - "aig", - "aigo", - "airbus", - "airforce", - "airtel", - "akdn", - "al", - "alfaromeo", - "alibaba", - "alipay", - "allfinanz", - "allstate", - "ally", - "alsace", - "alstom", - "am", - "americanexpress", - "americanfamily", - "amex", - "amfam", - "amica", - "amsterdam", - "analytics", - "android", - "anquan", - "anz", - "ao", - "aol", - "apartments", - "app", - "apple", - "aq", - "aquarelle", - "ar", - "arab", - "aramco", - "archi", - "army", - "arpa", - "art", - "arte", - "as", - "asda", - "asia", - "associates", - "at", - "athleta", - "attorney", - "au", - "auction", - "audi", - "audible", - "audio", - "auspost", - "author", - "auto", - "autos", - "avianca", - "aw", - "aws", - "ax", - "axa", - "az", - "azure", - "ba", - "baby", - "baidu", - "banamex", - "bananarepublic", - "band", - "bank", - "bar", - "barcelona", - "barclaycard", - "barclays", - "barefoot", - "bargains", - "baseball", - "basketball", - "bauhaus", - "bayern", - "bb", - "bbc", - "bbt", - "bbva", - "bcg", - "bcn", - "bd", - "be", - "beats", - "beauty", - "beer", - "bentley", - "berlin", - "best", - "bestbuy", - "bet", - "bf", - "bg", - "bh", - "bharti", - "bi", - "bible", - "bid", - "bike", - "bing", - "bingo", - "bio", - "biz", - "bj", - "black", - "blackfriday", - "blanco", - "blockbuster", - "blog", - "bloomberg", - "blue", - "bm", - "bms", - "bmw", - "bn", - "bnl", - "bnpparibas", - "bo", - "boats", - "boehringer", - "bofa", - "bom", - "bond", - "boo", - "book", - "booking", - "boots", - "bosch", - "bostik", - "boston", - "bot", - "boutique", - "box", - "br", - "bradesco", - "bridgestone", - "broadway", - "broker", - "brother", - "brussels", - "bs", - "bt", - "budapest", - "bugatti", - "build", - "builders", - "business", - "buy", - "buzz", - "bv", - "bw", - "by", - "bz", - "bzh", - "ca", - "cab", - "cafe", - "cal", - "call", - "calvinklein", - "cam", - "camera", - "camp", - "cancerresearch", - "canon", - "capetown", - "capital", - "capitalone", - "car", - "caravan", - "cards", - "care", - "career", - "careers", - "cars", - "cartier", - "casa", - "case", - "caseih", - "cash", - "casino", - "cat", - "catering", - "catholic", - "cba", - "cbn", - "cbre", - "cbs", - "cc", - "cd", - "ceb", - "center", - "ceo", - "cern", - "cf", - "cfa", - "cfd", - "cg", - "ch", - "chanel", - "channel", - "chase", - "chat", - "cheap", - "chintai", - "chloe", - "christmas", - "chrome", - "chrysler", - "church", - "ci", - "cipriani", - "circle", - "cisco", - "citadel", - "citi", - "citic", - "city", - "cityeats", - "ck", - "cl", - "claims", - "cleaning", - "click", - "clinic", - "clinique", - "clothing", - "cloud", - "club", - "clubmed", - "cm", - "cn", - "co", - "coach", - "codes", - "coffee", - "college", - "cologne", - "com", - "comcast", - "commbank", - "community", - "company", - "compare", - "computer", - "comsec", - "condos", - "construction", - "consulting", - "contact", - "contractors", - "cooking", - "cookingchannel", - "cool", - "coop", - "corsica", - "country", - "coupon", - "coupons", - "courses", - "cr", - "credit", - "creditcard", - "creditunion", - "cricket", - "crown", - "crs", - "cruise", - "cruises", - "csc", - "cu", - "cuisinella", - "cv", - "cw", - "cx", - "cy", - "cymru", - "cyou", - "cz", - "dabur", - "dad", - "dance", - "data", - "date", - "dating", - "datsun", - "day", - "dclk", - "dds", - "de", - "deal", - "dealer", - "deals", - "degree", - "delivery", - "dell", - "deloitte", - "delta", - "democrat", - "dental", - "dentist", - "desi", - "design", - "dev", - "dhl", - "diamonds", - "diet", - "digital", - "direct", - "directory", - "discount", - "discover", - "dish", - "diy", - "dj", - "dk", - "dm", - "dnp", - "do", - "docs", - "doctor", - "dodge", - "dog", - "doha", - "domains", - "dot", - "download", - "drive", - "dtv", - "dubai", - "duck", - "dunlop", - "duns", - "dupont", - "durban", - "dvag", - "dvr", - "dz", - "earth", - "eat", - "ec", - "eco", - "edeka", - "edu", - "education", - "ee", - "eg", - "email", - "emerck", - "energy", - "engineer", - "engineering", - "enterprises", - "epost", - "epson", - "equipment", - "er", - "ericsson", - "erni", - "es", - "esq", - "estate", - "esurance", - "et", - "etisalat", - "eu", - "eurovision", - "eus", - "events", - "everbank", - "exchange", - "expert", - "exposed", - "express", - "extraspace", - "fage", - "fail", - "fairwinds", - "faith", - "family", - "fan", - "fans", - "farm", - "farmers", - "fashion", - "fast", - "fedex", - "feedback", - "ferrari", - "ferrero", - "fi", - "fiat", - "fidelity", - "fido", - "film", - "final", - "finance", - "financial", - "fire", - "firestone", - "firmdale", - "fish", - "fishing", - "fit", - "fitness", - "fj", - "fk", - "flickr", - "flights", - "flir", - "florist", - "flowers", - "fly", - "fm", - "fo", - "foo", - "food", - "foodnetwork", - "football", - "ford", - "forex", - "forsale", - "forum", - "foundation", - "fox", - "fr", - "free", - "fresenius", - "frl", - "frogans", - "frontdoor", - "frontier", - "ftr", - "fujitsu", - "fujixerox", - "fun", - "fund", - "furniture", - "futbol", - "fyi", - "ga", - "gal", - "gallery", - "gallo", - "gallup", - "game", - "games", - "gap", - "garden", - "gb", - "gbiz", - "gd", - "gdn", - "ge", - "gea", - "gent", - "genting", - "george", - "gf", - "gg", - "ggee", - "gh", - "gi", - "gift", - "gifts", - "gives", - "giving", - "gl", - "glade", - "glass", - "gle", - "global", - "globo", - "gm", - "gmail", - "gmbh", - "gmo", - "gmx", - "gn", - "godaddy", - "gold", - "goldpoint", - "golf", - "goo", - "goodhands", - "goodyear", - "goog", - "google", - "gop", - "got", - "gov", - "gp", - "gq", - "gr", - "grainger", - "graphics", - "gratis", - "green", - "gripe", - "grocery", - "group", - "gs", - "gt", - "gu", - "guardian", - "gucci", - "guge", - "guide", - "guitars", - "guru", - "gw", - "gy", - "hair", - "hamburg", - "hangout", - "haus", - "hbo", - "hdfc", - "hdfcbank", - "health", - "healthcare", - "help", - "helsinki", - "here", - "hermes", - "hgtv", - "hiphop", - "hisamitsu", - "hitachi", - "hiv", - "hk", - "hkt", - "hm", - "hn", - "hockey", - "holdings", - "holiday", - "homedepot", - "homegoods", - "homes", - "homesense", - "honda", - "honeywell", - "horse", - "hospital", - "host", - "hosting", - "hot", - "hoteles", - "hotels", - "hotmail", - "house", - "how", - "hr", - "hsbc", - "ht", - "htc", - "hu", - "hughes", - "hyatt", - "hyundai", - "ibm", - "icbc", - "ice", - "icu", - "id", - "ie", - "ieee", - "ifm", - "ikano", - "il", - "im", - "imamat", - "imdb", - "immo", - "immobilien", - "in", - "industries", - "infiniti", - "info", - "ing", - "ink", - "institute", - "insurance", - "insure", - "int", - "intel", - "international", - "intuit", - "investments", - "io", - "ipiranga", - "iq", - "ir", - "irish", - "is", - "iselect", - "ismaili", - "ist", - "istanbul", - "it", - "itau", - "itv", - "iveco", - "iwc", - "jaguar", - "java", - "jcb", - "jcp", - "je", - "jeep", - "jetzt", - "jewelry", - "jio", - "jlc", - "jll", - "jm", - "jmp", - "jnj", - "jo", - "jobs", - "joburg", - "jot", - "joy", - "jp", - "jpmorgan", - "jprs", - "juegos", - "juniper", - "kaufen", - "kddi", - "ke", - "kerryhotels", - "kerrylogistics", - "kerryproperties", - "kfh", - "kg", - "kh", - "ki", - "kia", - "kim", - "kinder", - "kindle", - "kitchen", - "kiwi", - "km", - "kn", - "koeln", - "komatsu", - "kosher", - "kp", - "kpmg", - "kpn", - "kr", - "krd", - "kred", - "kuokgroup", - "kw", - "ky", - "kyoto", - "kz", - "la", - "lacaixa", - "ladbrokes", - "lamborghini", - "lamer", - "lancaster", - "lancia", - "lancome", - "land", - "landrover", - "lanxess", - "lasalle", - "lat", - "latino", - "latrobe", - "law", - "lawyer", - "lb", - "lc", - "lds", - "lease", - "leclerc", - "lefrak", - "legal", - "lego", - "lexus", - "lgbt", - "li", - "liaison", - "lidl", - "life", - "lifeinsurance", - "lifestyle", - "lighting", - "like", - "lilly", - "limited", - "limo", - "lincoln", - "linde", - "link", - "lipsy", - "live", - "living", - "lixil", - "lk", - "loan", - "loans", - "locker", - "locus", - "loft", - "lol", - "london", - "lotte", - "lotto", - "love", - "lpl", - "lplfinancial", - "lr", - "ls", - "lt", - "ltd", - "ltda", - "lu", - "lundbeck", - "lupin", - "luxe", - "luxury", - "lv", - "ly", - "ma", - "macys", - "madrid", - "maif", - "maison", - "makeup", - "man", - "management", - "mango", - "map", - "market", - "marketing", - "markets", - "marriott", - "marshalls", - "maserati", - "mattel", - "mba", - "mc", - "mcd", - "mcdonalds", - "mckinsey", - "md", - "me", - "med", - "media", - "meet", - "melbourne", - "meme", - "memorial", - "men", - "menu", - "meo", - "merckmsd", - "metlife", - "mg", - "mh", - "miami", - "microsoft", - "mil", - "mini", - "mint", - "mit", - "mitsubishi", - "mk", - "ml", - "mlb", - "mls", - "mm", - "mma", - "mn", - "mo", - "mobi", - "mobile", - "mobily", - "moda", - "moe", - "moi", - "mom", - "monash", - "money", - "monster", - "montblanc", - "mopar", - "mormon", - "mortgage", - "moscow", - "moto", - "motorcycles", - "mov", - "movie", - "movistar", - "mp", - "mq", - "mr", - "ms", - "msd", - "mt", - "mtn", - "mtpc", - "mtr", - "mu", - "museum", - "mutual", - "mv", - "mw", - "mx", - "my", - "mz", - "na", - "nab", - "nadex", - "nagoya", - "name", - "nationwide", - "natura", - "navy", - "nba", - "nc", - "ne", - "nec", - "net", - "netbank", - "netflix", - "network", - "neustar", - "new", - "newholland", - "news", - "next", - "nextdirect", - "nexus", - "nf", - "nfl", - "ng", - "ngo", - "nhk", - "ni", - "nico", - "nike", - "nikon", - "ninja", - "nissan", - "nissay", - "nl", - "no", - "nokia", - "northwesternmutual", - "norton", - "now", - "nowruz", - "nowtv", - "np", - "nr", - "nra", - "nrw", - "ntt", - "nu", - "nyc", - "nz", - "obi", - "observer", - "off", - "office", - "okinawa", - "olayan", - "olayangroup", - "oldnavy", - "ollo", - "om", - "omega", - "one", - "ong", - "onion", - "onl", - "online", - "onyourside", - "ooo", - "open", - "oracle", - "orange", - "org", - "organic", - "origins", - "osaka", - "otsuka", - "ott", - "ovh", - "pa", - "page", - "pamperedchef", - "panasonic", - "panerai", - "paris", - "pars", - "partners", - "parts", - "party", - "passagens", - "pay", - "pccw", - "pe", - "pet", - "pf", - "pfizer", - "pg", - "ph", - "pharmacy", - "phd", - "philips", - "phone", - "photo", - "photography", - "photos", - "physio", - "piaget", - "pics", - "pictet", - "pictures", - "pid", - "pin", - "ping", - "pink", - "pioneer", - "pizza", - "pk", - "pl", - "place", - "play", - "playstation", - "plumbing", - "plus", - "pm", - "pn", - "pnc", - "pohl", - "poker", - "politie", - "porn", - "post", - "pr", - "pramerica", - "praxi", - "press", - "prime", - "pro", - "prod", - "productions", - "prof", - "progressive", - "promo", - "properties", - "property", - "protection", - "pru", - "prudential", - "ps", - "pt", - "pub", - "pw", - "pwc", - "py", - "qa", - "qpon", - "quebec", - "quest", - "qvc", - "racing", - "radio", - "raid", - "re", - "read", - "realestate", - "realtor", - "realty", - "recipes", - "red", - "redstone", - "redumbrella", - "rehab", - "reise", - "reisen", - "reit", - "reliance", - "ren", - "rent", - "rentals", - "repair", - "report", - "republican", - "rest", - "restaurant", - "review", - "reviews", - "rexroth", - "rich", - "richardli", - "ricoh", - "rightathome", - "ril", - "rio", - "rip", - "rmit", - "ro", - "rocher", - "rocks", - "rodeo", - "rogers", - "room", - "rs", - "rsvp", - "ru", - "rugby", - "ruhr", - "run", - "rw", - "rwe", - "ryukyu", - "sa", - "saarland", - "safe", - "safety", - "sakura", - "sale", - "salon", - "samsclub", - "samsung", - "sandvik", - "sandvikcoromant", - "sanofi", - "sap", - "sapo", - "sarl", - "sas", - "save", - "saxo", - "sb", - "sbi", - "sbs", - "sc", - "sca", - "scb", - "schaeffler", - "schmidt", - "scholarships", - "school", - "schule", - "schwarz", - "science", - "scjohnson", - "scor", - "scot", - "sd", - "se", - "search", - "seat", - "secure", - "security", - "seek", - "select", - "sener", - "services", - "ses", - "seven", - "sew", - "sex", - "sexy", - "sfr", - "sg", - "sh", - "shangrila", - "sharp", - "shaw", - "shell", - "shia", - "shiksha", - "shoes", - "shop", - "shopping", - "shouji", - "show", - "showtime", - "shriram", - "si", - "silk", - "sina", - "singles", - "site", - "sj", - "sk", - "ski", - "skin", - "sky", - "skype", - "sl", - "sling", - "sm", - "smart", - "smile", - "sn", - "sncf", - "so", - "soccer", - "social", - "softbank", - "software", - "sohu", - "solar", - "solutions", - "song", - "sony", - "soy", - "space", - "spiegel", - "spot", - "spreadbetting", - "sr", - "srl", - "srt", - "st", - "stada", - "staples", - "star", - "starhub", - "statebank", - "statefarm", - "statoil", - "stc", - "stcgroup", - "stockholm", - "storage", - "store", - "stream", - "studio", - "study", - "style", - "su", - "sucks", - "supplies", - "supply", - "support", - "surf", - "surgery", - "suzuki", - "sv", - "swatch", - "swiftcover", - "swiss", - "sx", - "sy", - "sydney", - "symantec", - "systems", - "sz", - "tab", - "taipei", - "talk", - "taobao", - "target", - "tatamotors", - "tatar", - "tattoo", - "tax", - "taxi", - "tc", - "tci", - "td", - "tdk", - "team", - "tech", - "technology", - "tel", - "telecity", - "telefonica", - "temasek", - "tennis", - "teva", - "tf", - "tg", - "th", - "thd", - "theater", - "theatre", - "tiaa", - "tickets", - "tienda", - "tiffany", - "tips", - "tires", - "tirol", - "tj", - "tjmaxx", - "tjx", - "tk", - "tkmaxx", - "tl", - "tm", - "tmall", - "tn", - "to", - "today", - "tokyo", - "tools", - "top", - "toray", - "toshiba", - "total", - "tours", - "town", - "toyota", - "toys", - "tr", - "trade", - "trading", - "training", - "travel", - "travelchannel", - "travelers", - "travelersinsurance", - "trust", - "trv", - "tt", - "tube", - "tui", - "tunes", - "tushu", - "tv", - "tvs", - "tw", - "tz", - "ua", - "ubank", - "ubs", - "uconnect", - "ug", - "uk", - "unicom", - "university", - "uno", - "uol", - "ups", - "us", - "uy", - "uz", - "va", - "vacations", - "vana", - "vanguard", - "vc", - "ve", - "vegas", - "ventures", - "verisign", - "versicherung", - "vet", - "vg", - "vi", - "viajes", - "video", - "vig", - "viking", - "villas", - "vin", - "vip", - "virgin", - "visa", - "vision", - "vista", - "vistaprint", - "viva", - "vivo", - "vlaanderen", - "vn", - "vodka", - "volkswagen", - "volvo", - "vote", - "voting", - "voto", - "voyage", - "vu", - "vuelos", - "wales", - "walmart", - "walter", - "wang", - "wanggou", - "warman", - "watch", - "watches", - "weather", - "weatherchannel", - "webcam", - "weber", - "website", - "wed", - "wedding", - "weibo", - "weir", - "wf", - "whoswho", - "wien", - "wiki", - "williamhill", - "win", - "windows", - "wine", - "winners", - "wme", - "wolterskluwer", - "woodside", - "work", - "works", - "world", - "wow", - "ws", - "wtc", - "wtf", - "xbox", - "xerox", - "xfinity", - "xihuan", - "xin", - "xn--11b4c3d", - "xn--1ck2e1b", - "xn--1qqw23a", - "xn--2scrj9c", - "xn--30rr7y", - "xn--3bst00m", - "xn--3ds443g", - "xn--3e0b707e", - "xn--3hcrj9c", - "xn--3oq18vl8pn36a", - "xn--3pxu8k", - "xn--42c2d9a", - "xn--45br5cyl", - "xn--45brj9c", - "xn--45q11c", - "xn--4gbrim", - "xn--54b7fta0cc", - "xn--55qw42g", - "xn--55qx5d", - "xn--5su34j936bgsg", - "xn--5tzm5g", - "xn--6frz82g", - "xn--6qq986b3xl", - "xn--80adxhks", - "xn--80ao21a", - "xn--80aqecdr1a", - "xn--80asehdb", - "xn--80aswg", - "xn--8y0a063a", - "xn--90a3ac", - "xn--90ae", - "xn--90ais", - "xn--9dbq2a", - "xn--9et52u", - "xn--9krt00a", - "xn--b4w605ferd", - "xn--bck1b9a5dre4c", - "xn--c1avg", - "xn--c2br7g", - "xn--cck2b3b", - "xn--cg4bki", - "xn--clchc0ea0b2g2a9gcd", - "xn--czr694b", - "xn--czrs0t", - "xn--czru2d", - "xn--d1acj3b", - "xn--d1alf", - "xn--e1a4c", - "xn--eckvdtc9d", - "xn--efvy88h", - "xn--estv75g", - "xn--fct429k", - "xn--fhbei", - "xn--fiq228c5hs", - "xn--fiq64b", - "xn--fiqs8s", - "xn--fiqz9s", - "xn--fjq720a", - "xn--flw351e", - "xn--fpcrj9c3d", - "xn--fzc2c9e2c", - "xn--fzys8d69uvgm", - "xn--g2xx48c", - "xn--gckr3f0f", - "xn--gecrj9c", - "xn--gk3at1e", - "xn--h2breg3eve", - "xn--h2brj9c", - "xn--h2brj9c8c", - "xn--hxt814e", - "xn--i1b6b1a6a2e", - "xn--imr513n", - "xn--io0a7i", - "xn--j1aef", - "xn--j1amh", - "xn--j6w193g", - "xn--jlq61u9w7b", - "xn--jvr189m", - "xn--kcrx77d1x4a", - "xn--kprw13d", - "xn--kpry57d", - "xn--kpu716f", - "xn--kput3i", - "xn--l1acc", - "xn--lgbbat1ad8j", - "xn--mgb2ddes", - "xn--mgb9awbf", - "xn--mgba3a3ejt", - "xn--mgba3a4f16a", - "xn--mgba3a4fra", - "xn--mgba7c0bbn0a", - "xn--mgbaakc7dvf", - "xn--mgbaam7a8h", - "xn--mgbab2bd", - "xn--mgbai9a5eva00b", - "xn--mgbai9azgqp6j", - "xn--mgbayh7gpa", - "xn--mgbb9fbpob", - "xn--mgbbh1a71e", - "xn--mgbc0a9azcg", - "xn--mgbca7dzdo", - "xn--mgberp4a5d4a87g", - "xn--mgberp4a5d4ar", - "xn--mgbgu82a", - "xn--mgbi4ecexp", - "xn--mgbpl2fh", - "xn--mgbqly7c0a67fbc", - "xn--mgbqly7cvafr", - "xn--mgbt3dhd", - "xn--mgbtf8fl", - "xn--mgbtx2b", - "xn--mgbx4cd0ab", - "xn--mix082f", - "xn--mix891f", - "xn--mk1bu44c", - "xn--mxtq1m", - "xn--ngbc5azd", - "xn--ngbe9e0a", - "xn--ngbrx", - "xn--nnx388a", - "xn--node", - "xn--nqv7f", - "xn--nqv7fs00ema", - "xn--nyqy26a", - "xn--o3cw4h", - "xn--ogbpf8fl", - "xn--p1acf", - "xn--p1ai", - "xn--pbt977c", - "xn--pgbs0dh", - "xn--pssy2u", - "xn--q9jyb4c", - "xn--qcka1pmc", - "xn--qxam", - "xn--rhqv96g", - "xn--rovu88b", - "xn--rvc1e0am3e", - "xn--s9brj9c", - "xn--ses554g", - "xn--t60b56a", - "xn--tckwe", - "xn--tiq49xqyj", - "xn--unup4y", - "xn--vermgensberater-ctb", - "xn--vermgensberatung-pwb", - "xn--vhquv", - "xn--vuq861b", - "xn--w4r85el8fhu5dnra", - "xn--w4rs40l", - "xn--wgbh1c", - "xn--wgbl6a", - "xn--xhq521b", - "xn--xkc2al3hye2a", - "xn--xkc2dl3a5ee0h", - "xn--y9a3aq", - "xn--yfro4i67o", - "xn--ygbi2ammx", - "xn--zfr164b", - "xperia", - "xxx", - "xyz", - "yachts", - "yahoo", - "yamaxun", - "yandex", - "ye", - "yodobashi", - "yoga", - "yokohama", - "you", - "youtube", - "yt", - "yun", - "za", - "zappos", - "zara", - "zero", - "zip", - "zippo", - "zm", - "zone", - "zuerich", - "zw", - "com", - "edu", - "gov", - "mil", - "net", - "org", - "nom", - "ac", - "blogspot", - "co", - "gov", - "mil", - "net", - "nom", - "org", - "sch", - "accident-investigation", - "accident-prevention", - "aerobatic", - "aeroclub", - "aerodrome", - "agents", - "air-surveillance", - "air-traffic-control", - "aircraft", - "airline", - "airport", - "airtraffic", - "ambulance", - "amusement", - "association", - "author", - "ballooning", - "broker", - "caa", - "cargo", - "catering", - "certification", - "championship", - "charter", - "civilaviation", - "club", - "conference", - "consultant", - "consulting", - "control", - "council", - "crew", - "design", - "dgca", - "educator", - "emergency", - "engine", - "engineer", - "entertainment", - "equipment", - "exchange", - "express", - "federation", - "flight", - "freight", - "fuel", - "gliding", - "government", - "groundhandling", - "group", - "hanggliding", - "homebuilt", - "insurance", - "journal", - "journalist", - "leasing", - "logistics", - "magazine", - "maintenance", - "media", - "microlight", - "modelling", - "navigation", - "parachuting", - "paragliding", - "passenger-association", - "pilot", - "press", - "production", - "recreation", - "repbody", - "res", - "research", - "rotorcraft", - "safety", - "scientist", - "services", - "show", - "skydiving", - "software", - "student", - "trader", - "trading", - "trainer", - "union", - "workinggroup", - "works", - "com", - "edu", - "gov", - "net", - "org", - "co", - "com", - "net", - "nom", - "org", - "com", - "net", - "nom", - "off", - "org", - "blogspot", - "com", - "edu", - "gov", - "mil", - "net", - "nom", - "org", - "blogspot", - "co", - "ed", - "gv", - "it", - "og", - "pb", - "com", - "edu", - "gob", - "gov", - "int", - "mil", - "musica", - "net", - "org", - "tur", - "blogspot", - "e164", - "in-addr", - "ip6", - "iris", - "uri", - "urn", - "gov", - "cloudns", - "12hp", - "2ix", - "4lima", - "ac", - "biz", - "co", - "futurecms", - "futurehosting", - "futuremailing", - "gv", - "info", - "lima-city", - "or", - "ortsinfo", - "priv", - "blogspot", - "ex", - "kunden", - "act", - "asn", - "com", - "conf", - "edu", - "gov", - "id", - "info", - "net", - "nsw", - "nt", - "org", - "oz", - "qld", - "sa", - "tas", - "vic", - "wa", - "blogspot", - "act", - "nsw", - "nt", - "qld", - "sa", - "tas", - "vic", - "wa", - "qld", - "sa", - "tas", - "vic", - "wa", - "com", - "biz", - "com", - "edu", - "gov", - "info", - "int", - "mil", - "name", - "net", - "org", - "pp", - "pro", - "blogspot", - "com", - "edu", - "gov", - "mil", - "net", - "org", - "biz", - "co", - "com", - "edu", - "gov", - "info", - "net", - "org", - "store", - "tv", - "ac", - "blogspot", - "transurl", - "gov", - "0", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "9", - "a", - "b", - "barsy", - "blogspot", - "c", - "d", - "e", - "f", - "g", - "h", - "i", - "j", - "k", - "l", - "m", - "n", - "o", - "p", - "q", - "r", - "s", - "t", - "u", - "v", - "w", - "x", - "y", - "z", - "com", - "edu", - "gov", - "net", - "org", - "co", - "com", - "edu", - "or", - "org", - "cloudns", - "dscloud", - "dyndns", - "for-better", - "for-more", - "for-some", - "for-the", - "mmafan", - "myftp", - "no-ip", - "selfip", - "webhop", - "asso", - "barreau", - "blogspot", - "gouv", - "com", - "edu", - "gov", - "net", - "org", - "com", - "edu", - "gob", - "gov", - "int", - "mil", - "net", - "org", - "tv", - "adm", - "adv", - "agr", - "am", - "arq", - "art", - "ato", - "b", - "belem", - "bio", - "blog", - "bmd", - "cim", - "cng", - "cnt", - "com", - "coop", - "cri", - "def", - "ecn", - "eco", - "edu", - "emp", - "eng", - "esp", - "etc", - "eti", - "far", - "flog", - "floripa", - "fm", - "fnd", - "fot", - "fst", - "g12", - "ggf", - "gov", - "imb", - "ind", - "inf", - "jampa", - "jor", - "jus", - "leg", - "lel", - "mat", - "med", - "mil", - "mp", - "mus", - "net", - "nom", - "not", - "ntr", - "odo", - "org", - "poa", - "ppg", - "pro", - "psc", - "psi", - "qsl", - "radio", - "rec", - "recife", - "slg", - "srv", - "taxi", - "teo", - "tmp", - "trd", - "tur", - "tv", - "vet", - "vix", - "vlog", - "wiki", - "zlg", - "blogspot", - "ac", - "al", - "am", - "ap", - "ba", - "ce", - "df", - "es", - "go", - "ma", - "mg", - "ms", - "mt", - "pa", - "pb", - "pe", - "pi", - "pr", - "rj", - "rn", - "ro", - "rr", - "rs", - "sc", - "se", - "sp", - "to", - "ac", - "al", - "am", - "ap", - "ba", - "ce", - "df", - "es", - "go", - "ma", - "mg", - "ms", - "mt", - "pa", - "pb", - "pe", - "pi", - "pr", - "rj", - "rn", - "ro", - "rr", - "rs", - "sc", - "se", - "sp", - "to", - "com", - "edu", - "gov", - "net", - "org", - "we", - "com", - "edu", - "gov", - "net", - "org", - "co", - "org", - "com", - "gov", - "mil", - "nym", - "of", - "blogspot", - "com", - "edu", - "gov", - "net", - "nym", - "org", - "za", - "ab", - "awdev", - "bc", - "blogspot", - "co", - "gc", - "mb", - "nb", - "nf", - "nl", - "no-ip", - "ns", - "nt", - "nu", - "on", - "pe", - "qc", - "sk", - "yk", - "cloudns", - "fantasyleague", - "ftpaccess", - "game-server", - "myphotos", - "scrapping", - "twmail", - "gov", - "blogspot", - "12hp", - "2ix", - "4lima", - "blogspot", - "gotdns", - "lima-city", - "square7", - "ac", - "asso", - "co", - "com", - "ed", - "edu", - "go", - "gouv", - "int", - "md", - "net", - "or", - "org", - "presse", - "xn--aroport-bya", - "www", - "blogspot", - "co", - "gob", - "gov", - "mil", - "nom", - "magentosite", - "myfusion", - "sensiosite", - "statics", - "trafficplex", - "vapor", - "cloudns", - "co", - "com", - "gov", - "net", - "ac", - "ah", - "bj", - "com", - "cq", - "edu", - "fj", - "gd", - "gov", - "gs", - "gx", - "gz", - "ha", - "hb", - "he", - "hi", - "hk", - "hl", - "hn", - "jl", - "js", - "jx", - "ln", - "mil", - "mo", - "net", - "nm", - "nx", - "org", - "qh", - "sc", - "sd", - "sh", - "sn", - "sx", - "tj", - "tw", - "xj", - "xn--55qx5d", - "xn--io0a7i", - "xn--od0alg", - "xz", - "yn", - "zj", - "amazonaws", - "cn-north-1", - "compute", - "eb", - "elb", - "s3", - "cn-north-1", - "arts", - "com", - "edu", - "firm", - "gov", - "info", - "int", - "mil", - "net", - "nodum", - "nom", - "org", - "rec", - "web", - "blogspot", - "0emm", - "1kapp", - "3utilities", - "4u", - "africa", - "alpha-myqnapcloud", - "amazonaws", - "appchizi", - "applinzi", - "appspot", - "ar", - "barsyonline", - "betainabox", - "bitballoon", - "blogdns", - "blogspot", - "blogsyte", - "bloxcms", - "bounty-full", - "bplaced", - "br", - "cechire", - "ciscofreak", - "cloudcontrolapp", - "cloudcontrolled", - "cn", - "co", - "codespot", - "damnserver", - "ddnsfree", - "ddnsgeek", - "ddnsking", - "de", - "dev-myqnapcloud", - "ditchyourip", - "dnsalias", - "dnsdojo", - "dnsiskinky", - "doesntexist", - "dontexist", - "doomdns", - "drayddns", - "dreamhosters", - "dsmynas", - "dyn-o-saur", - "dynalias", - "dyndns-at-home", - "dyndns-at-work", - "dyndns-blog", - "dyndns-free", - "dyndns-home", - "dyndns-ip", - "dyndns-mail", - "dyndns-office", - "dyndns-pics", - "dyndns-remote", - "dyndns-server", - "dyndns-web", - "dyndns-wiki", - "dyndns-work", - "dynns", - "elasticbeanstalk", - "est-a-la-maison", - "est-a-la-masion", - "est-le-patron", - "est-mon-blogueur", - "eu", - "evennode", - "familyds", - "fbsbx", - "firebaseapp", - "firewall-gateway", - "flynnhub", - "freebox-os", - "freeboxos", - "from-ak", - "from-al", - "from-ar", - "from-ca", - "from-ct", - "from-dc", - "from-de", - "from-fl", - "from-ga", - "from-hi", - "from-ia", - "from-id", - "from-il", - "from-in", - "from-ks", - "from-ky", - "from-ma", - "from-md", - "from-mi", - "from-mn", - "from-mo", - "from-ms", - "from-mt", - "from-nc", - "from-nd", - "from-ne", - "from-nh", - "from-nj", - "from-nm", - "from-nv", - "from-oh", - "from-ok", - "from-or", - "from-pa", - "from-pr", - "from-ri", - "from-sc", - "from-sd", - "from-tn", - "from-tx", - "from-ut", - "from-va", - "from-vt", - "from-wa", - "from-wi", - "from-wv", - "from-wy", - "gb", - "geekgalaxy", - "getmyip", - "giize", - "githubusercontent", - "gleeze", - "googleapis", - "googlecode", - "gotdns", - "gotpantheon", - "gr", - "health-carereform", - "herokuapp", - "herokussl", - "hk", - "hobby-site", - "homelinux", - "homesecuritymac", - "homesecuritypc", - "homeunix", - "hu", - "iamallama", - "is-a-anarchist", - "is-a-blogger", - "is-a-bookkeeper", - "is-a-bulls-fan", - "is-a-caterer", - "is-a-chef", - "is-a-conservative", - "is-a-cpa", - "is-a-cubicle-slave", - "is-a-democrat", - "is-a-designer", - "is-a-doctor", - "is-a-financialadvisor", - "is-a-geek", - "is-a-green", - "is-a-guru", - "is-a-hard-worker", - "is-a-hunter", - "is-a-landscaper", - "is-a-lawyer", - "is-a-liberal", - "is-a-libertarian", - "is-a-llama", - "is-a-musician", - "is-a-nascarfan", - "is-a-nurse", - "is-a-painter", - "is-a-personaltrainer", - "is-a-photographer", - "is-a-player", - "is-a-republican", - "is-a-rockstar", - "is-a-socialist", - "is-a-student", - "is-a-teacher", - "is-a-techie", - "is-a-therapist", - "is-an-accountant", - "is-an-actor", - "is-an-actress", - "is-an-anarchist", - "is-an-artist", - "is-an-engineer", - "is-an-entertainer", - "is-certified", - "is-gone", - "is-into-anime", - "is-into-cars", - "is-into-cartoons", - "is-into-games", - "is-leet", - "is-not-certified", - "is-slick", - "is-uberleet", - "is-with-theband", - "isa-geek", - "isa-hockeynut", - "issmarterthanyou", - "jdevcloud", - "joyent", - "jpn", - "kozow", - "kr", - "likes-pie", - "likescandy", - "logoip", - "loseyourip", - "meteorapp", - "mex", - "myactivedirectory", - "myasustor", - "mydrobo", - "myqnapcloud", - "mysecuritycamera", - "myshopblocks", - "mytuleap", - "myvnc", - "neat-url", - "net-freaks", - "netlify", - "nfshost", - "no", - "on-aptible", - "onthewifi", - "ooguy", - "operaunite", - "outsystemscloud", - "ownprovider", - "pagefrontapp", - "pagespeedmobilizer", - "pgfog", - "pixolino", - "point2this", - "prgmr", - "publishproxy", - "qa2", - "qc", - "quicksytes", - "quipelements", - "rackmaze", - "remotewd", - "rhcloud", - "ru", - "sa", - "saves-the-whales", - "se", - "securitytactics", - "selfip", - "sells-for-less", - "sells-for-u", - "servebbs", - "servebeer", - "servecounterstrike", - "serveexchange", - "serveftp", - "servegame", - "servehalflife", - "servehttp", - "servehumour", - "serveirc", - "servemp3", - "servep2p", - "servepics", - "servequake", - "servesarcasm", - "simple-url", - "sinaapp", - "space-to-rent", - "stufftoread", - "teaches-yoga", - "temp-dns", - "theworkpc", - "townnews-staging", - "uk", - "unusualperson", - "us", - "uy", - "vipsinaapp", - "withgoogle", - "withyoutube", - "workisboring", - "wpdevcloud", - "writesthisblog", - "xenapponazure", - "yolasite", - "za", - "ap-northeast-1", - "ap-northeast-2", - "ap-south-1", - "ap-southeast-1", - "ap-southeast-2", - "ca-central-1", - "compute", - "compute-1", - "elb", - "eu-central-1", - "eu-west-1", - "eu-west-2", - "s3", - "s3-ap-northeast-1", - "s3-ap-northeast-2", - "s3-ap-south-1", - "s3-ap-southeast-1", - "s3-ap-southeast-2", - "s3-ca-central-1", - "s3-eu-central-1", - "s3-eu-west-1", - "s3-eu-west-2", - "s3-external-1", - "s3-fips-us-gov-west-1", - "s3-sa-east-1", - "s3-us-east-2", - "s3-us-gov-west-1", - "s3-us-west-1", - "s3-us-west-2", - "s3-website-ap-northeast-1", - "s3-website-ap-southeast-1", - "s3-website-ap-southeast-2", - "s3-website-eu-west-1", - "s3-website-sa-east-1", - "s3-website-us-east-1", - "s3-website-us-west-1", - "s3-website-us-west-2", - "sa-east-1", - "us-east-1", - "us-east-2", - "dualstack", - "s3", - "dualstack", - "s3", - "s3-website", - "s3", - "dualstack", - "s3", - "s3-website", - "s3", - "dualstack", - "s3", - "dualstack", - "s3", - "dualstack", - "s3", - "s3-website", - "s3", - "dualstack", - "s3", - "s3-website", - "s3", - "dualstack", - "s3", - "dualstack", - "s3", - "s3-website", - "s3", - "dualstack", - "s3", - "dualstack", - "s3", - "dualstack", - "s3", - "s3-website", - "s3", - "alpha", - "beta", - "ap-northeast-1", - "ap-northeast-2", - "ap-south-1", - "ap-southeast-1", - "ap-southeast-2", - "ca-central-1", - "eu-central-1", - "eu-west-1", - "eu-west-2", - "sa-east-1", - "us-east-1", - "us-east-2", - "us-gov-west-1", - "us-west-1", - "us-west-2", - "eu-1", - "eu-2", - "eu-3", - "eu-4", - "us-1", - "us-2", - "us-3", - "us-4", - "apps", - "cns", - "eu", - "xen", - "de", - "ac", - "co", - "ed", - "fi", - "go", - "or", - "sa", - "com", - "edu", - "gov", - "inf", - "net", - "org", - "blogspot", - "com", - "edu", - "net", - "org", - "ath", - "gov", - "info", - "ac", - "biz", - "com", - "ekloges", - "gov", - "ltd", - "name", - "net", - "org", - "parliament", - "press", - "pro", - "tm", - "blogspot", - "blogspot", - "co", - "e4", - "metacentrum", - "realm", - "cloud", - "custom", - "12hp", - "2ix", - "4lima", - "barsy", - "blogspot", - "bplaced", - "com", - "cosidns", - "dd-dns", - "ddnss", - "dnshome", - "dnsupdater", - "dray-dns", - "draydns", - "dyn-ip24", - "dyn-vpn", - "dynamisches-dns", - "dyndns1", - "dynvpn", - "firewall-gateway", - "fuettertdasnetz", - "git-repos", - "goip", - "home-webserver", - "internet-dns", - "isteingeek", - "istmein", - "keymachine", - "l-o-g-i-n", - "lcube-server", - "lebtimnetz", - "leitungsen", - "lima-city", - "logoip", - "mein-vigor", - "my-gateway", - "my-router", - "my-vigor", - "my-wan", - "myhome-server", - "spdns", - "square7", - "svn-repos", - "syno-ds", - "synology-diskstation", - "synology-ds", - "taifun-dns", - "traeumtgerade", - "dyn", - "dyn", - "dyndns", - "dyn", - "biz", - "blogspot", - "co", - "firm", - "reg", - "store", - "com", - "edu", - "gov", - "net", - "org", - "art", - "com", - "edu", - "gob", - "gov", - "mil", - "net", - "org", - "sld", - "web", - "art", - "asso", - "com", - "edu", - "gov", - "net", - "org", - "pol", - "com", - "edu", - "fin", - "gob", - "gov", - "info", - "k12", - "med", - "mil", - "net", - "org", - "pro", - "aip", - "com", - "edu", - "fie", - "gov", - "lib", - "med", - "org", - "pri", - "riik", - "blogspot", - "com", - "edu", - "eun", - "gov", - "mil", - "name", - "net", - "org", - "sci", - "blogspot", - "com", - "edu", - "gob", - "nom", - "org", - "blogspot", - "compute", - "biz", - "com", - "edu", - "gov", - "info", - "name", - "net", - "org", - "barsy", - "cloudns", - "diskstation", - "mycd", - "spdns", - "transurl", - "wellbeingzone", - "party", - "user", - "ybo", - "storj", - "aland", - "blogspot", - "dy", - "iki", - "ptplus", - "aeroport", - "assedic", - "asso", - "avocat", - "avoues", - "blogspot", - "cci", - "chambagri", - "chirurgiens-dentistes", - "chirurgiens-dentistes-en-france", - "com", - "experts-comptables", - "fbx-os", - "fbxos", - "freebox-os", - "freeboxos", - "geometre-expert", - "gouv", - "greta", - "huissier-justice", - "medecin", - "nom", - "notaires", - "on-web", - "pharmacien", - "port", - "prd", - "presse", - "tm", - "veterinaire", - "nom", - "com", - "edu", - "gov", - "mil", - "net", - "org", - "pvt", - "co", - "cya", - "net", - "org", - "com", - "edu", - "gov", - "mil", - "org", - "com", - "edu", - "gov", - "ltd", - "mod", - "org", - "co", - "com", - "edu", - "net", - "nom", - "org", - "ac", - "com", - "edu", - "gov", - "net", - "org", - "cloud", - "asso", - "com", - "edu", - "mobi", - "net", - "org", - "blogspot", - "com", - "edu", - "gov", - "net", - "nym", - "org", - "com", - "edu", - "gob", - "ind", - "mil", - "net", - "nom", - "org", - "co", - "com", - "edu", - "gov", - "net", - "org", - "blogspot", - "com", - "edu", - "gov", - "idv", - "inc", - "ltd", - "net", - "org", - "xn--55qx5d", - "xn--ciqpn", - "xn--gmq050i", - "xn--gmqw5a", - "xn--io0a7i", - "xn--lcvr32d", - "xn--mk0axi", - "xn--mxtq1m", - "xn--od0alg", - "xn--od0aq3b", - "xn--tn0ag", - "xn--uc0atv", - "xn--uc0ay4a", - "xn--wcvs22d", - "xn--zf0avx", - "com", - "edu", - "gob", - "mil", - "net", - "nom", - "org", - "cloudaccess", - "freesite", - "opencraft", - "blogspot", - "com", - "from", - "iz", - "name", - "adult", - "art", - "asso", - "com", - "coop", - "edu", - "firm", - "gouv", - "info", - "med", - "net", - "org", - "perso", - "pol", - "pro", - "rel", - "shop", - "2000", - "agrar", - "blogspot", - "bolt", - "casino", - "city", - "co", - "erotica", - "erotika", - "film", - "forum", - "games", - "hotel", - "info", - "ingatlan", - "jogasz", - "konyvelo", - "lakas", - "media", - "news", - "org", - "priv", - "reklam", - "sex", - "shop", - "sport", - "suli", - "szex", - "tm", - "tozsde", - "utazas", - "video", - "ac", - "biz", - "co", - "desa", - "go", - "mil", - "my", - "net", - "or", - "sch", - "web", - "blogspot", - "blogspot", - "gov", - "ac", - "co", - "gov", - "idf", - "k12", - "muni", - "net", - "org", - "blogspot", - "ac", - "co", - "com", - "net", - "nom", - "org", - "ro", - "tt", - "tv", - "ltd", - "plc", - "ac", - "barsy", - "blogspot", - "cloudns", - "co", - "edu", - "firm", - "gen", - "gov", - "ind", - "mil", - "net", - "nic", - "org", - "res", - "barrel-of-knowledge", - "barrell-of-knowledge", - "cloudns", - "dvrcam", - "dynamic-dns", - "dyndns", - "for-our", - "groks-the", - "groks-this", - "here-for-more", - "ilovecollege", - "knowsitall", - "no-ip", - "nsupdate", - "selfip", - "v-info", - "webhop", - "eu", - "backplaneapp", - "boxfuse", - "browsersafetymark", - "com", - "dedyn", - "definima", - "drud", - "enonic", - "github", - "gitlab", - "hasura-app", - "hzc", - "lair", - "ngrok", - "nid", - "nodeart", - "nodum", - "pantheonsite", - "protonet", - "sandcats", - "shiftedit", - "spacekit", - "stolos", - "thingdust", - "vaporcloud", - "wedeploy", - "customer", - "apps", - "stage", - "dev", - "disrec", - "prod", - "testing", - "cust", - "cust", - "cust", - "cust", - "com", - "edu", - "gov", - "mil", - "net", - "org", - "ac", - "co", - "gov", - "id", - "net", - "org", - "sch", - "xn--mgba3a4f16a", - "xn--mgba3a4fra", - "blogspot", - "com", - "cupcake", - "edu", - "gov", - "int", - "net", - "org", - "abr", - "abruzzo", - "ag", - "agrigento", - "al", - "alessandria", - "alto-adige", - "altoadige", - "an", - "ancona", - "andria-barletta-trani", - "andria-trani-barletta", - "andriabarlettatrani", - "andriatranibarletta", - "ao", - "aosta", - "aosta-valley", - "aostavalley", - "aoste", - "ap", - "aq", - "aquila", - "ar", - "arezzo", - "ascoli-piceno", - "ascolipiceno", - "asti", - "at", - "av", - "avellino", - "ba", - "balsan", - "bari", - "barletta-trani-andria", - "barlettatraniandria", - "bas", - "basilicata", - "belluno", - "benevento", - "bergamo", - "bg", - "bi", - "biella", - "bl", - "blogspot", - "bn", - "bo", - "bologna", - "bolzano", - "bozen", - "br", - "brescia", - "brindisi", - "bs", - "bt", - "bz", - "ca", - "cagliari", - "cal", - "calabria", - "caltanissetta", - "cam", - "campania", - "campidano-medio", - "campidanomedio", - "campobasso", - "carbonia-iglesias", - "carboniaiglesias", - "carrara-massa", - "carraramassa", - "caserta", - "catania", - "catanzaro", - "cb", - "ce", - "cesena-forli", - "cesenaforli", - "ch", - "chieti", - "ci", - "cl", - "cn", - "co", - "como", - "cosenza", - "cr", - "cremona", - "crotone", - "cs", - "ct", - "cuneo", - "cz", - "dell-ogliastra", - "dellogliastra", - "edu", - "emilia-romagna", - "emiliaromagna", - "emr", - "en", - "enna", - "fc", - "fe", - "fermo", - "ferrara", - "fg", - "fi", - "firenze", - "florence", - "fm", - "foggia", - "forli-cesena", - "forlicesena", - "fr", - "friuli-v-giulia", - "friuli-ve-giulia", - "friuli-vegiulia", - "friuli-venezia-giulia", - "friuli-veneziagiulia", - "friuli-vgiulia", - "friuliv-giulia", - "friulive-giulia", - "friulivegiulia", - "friulivenezia-giulia", - "friuliveneziagiulia", - "friulivgiulia", - "frosinone", - "fvg", - "ge", - "genoa", - "genova", - "go", - "gorizia", - "gov", - "gr", - "grosseto", - "iglesias-carbonia", - "iglesiascarbonia", - "im", - "imperia", - "is", - "isernia", - "kr", - "la-spezia", - "laquila", - "laspezia", - "latina", - "laz", - "lazio", - "lc", - "le", - "lecce", - "lecco", - "li", - "lig", - "liguria", - "livorno", - "lo", - "lodi", - "lom", - "lombardia", - "lombardy", - "lt", - "lu", - "lucania", - "lucca", - "macerata", - "mantova", - "mar", - "marche", - "massa-carrara", - "massacarrara", - "matera", - "mb", - "mc", - "me", - "medio-campidano", - "mediocampidano", - "messina", - "mi", - "milan", - "milano", - "mn", - "mo", - "modena", - "mol", - "molise", - "monza", - "monza-brianza", - "monza-e-della-brianza", - "monzabrianza", - "monzaebrianza", - "monzaedellabrianza", - "ms", - "mt", - "na", - "naples", - "napoli", - "no", - "novara", - "nu", - "nuoro", - "og", - "ogliastra", - "olbia-tempio", - "olbiatempio", - "or", - "oristano", - "ot", - "pa", - "padova", - "padua", - "palermo", - "parma", - "pavia", - "pc", - "pd", - "pe", - "perugia", - "pesaro-urbino", - "pesarourbino", - "pescara", - "pg", - "pi", - "piacenza", - "piedmont", - "piemonte", - "pisa", - "pistoia", - "pmn", - "pn", - "po", - "pordenone", - "potenza", - "pr", - "prato", - "pt", - "pu", - "pug", - "puglia", - "pv", - "pz", - "ra", - "ragusa", - "ravenna", - "rc", - "re", - "reggio-calabria", - "reggio-emilia", - "reggiocalabria", - "reggioemilia", - "rg", - "ri", - "rieti", - "rimini", - "rm", - "rn", - "ro", - "roma", - "rome", - "rovigo", - "sa", - "salerno", - "sar", - "sardegna", - "sardinia", - "sassari", - "savona", - "si", - "sic", - "sicilia", - "sicily", - "siena", - "siracusa", - "so", - "sondrio", - "sp", - "sr", - "ss", - "suedtirol", - "sv", - "ta", - "taa", - "taranto", - "te", - "tempio-olbia", - "tempioolbia", - "teramo", - "terni", - "tn", - "to", - "torino", - "tos", - "toscana", - "tp", - "tr", - "trani-andria-barletta", - "trani-barletta-andria", - "traniandriabarletta", - "tranibarlettaandria", - "trapani", - "trentino", - "trentino-a-adige", - "trentino-aadige", - "trentino-alto-adige", - "trentino-altoadige", - "trentino-s-tirol", - "trentino-stirol", - "trentino-sud-tirol", - "trentino-sudtirol", - "trentino-sued-tirol", - "trentino-suedtirol", - "trentinoa-adige", - "trentinoaadige", - "trentinoalto-adige", - "trentinoaltoadige", - "trentinos-tirol", - "trentinostirol", - "trentinosud-tirol", - "trentinosudtirol", - "trentinosued-tirol", - "trentinosuedtirol", - "trento", - "treviso", - "trieste", - "ts", - "turin", - "tuscany", - "tv", - "ud", - "udine", - "umb", - "umbria", - "urbino-pesaro", - "urbinopesaro", - "va", - "val-d-aosta", - "val-daosta", - "vald-aosta", - "valdaosta", - "valle-aosta", - "valle-d-aosta", - "valle-daosta", - "valleaosta", - "valled-aosta", - "valledaosta", - "vallee-aoste", - "valleeaoste", - "vao", - "varese", - "vb", - "vc", - "vda", - "ve", - "ven", - "veneto", - "venezia", - "venice", - "verbania", - "vercelli", - "verona", - "vi", - "vibo-valentia", - "vibovalentia", - "vicenza", - "viterbo", - "vr", - "vs", - "vt", - "vv", - "co", - "net", - "org", - "com", - "edu", - "gov", - "mil", - "name", - "net", - "org", - "sch", - "ac", - "ad", - "aichi", - "akita", - "aomori", - "blogspot", - "chiba", - "co", - "ed", - "ehime", - "fukui", - "fukuoka", - "fukushima", - "gifu", - "go", - "gr", - "gunma", - "hiroshima", - "hokkaido", - "hyogo", - "ibaraki", - "ishikawa", - "iwate", - "kagawa", - "kagoshima", - "kanagawa", - "kawasaki", - "kitakyushu", - "kobe", - "kochi", - "kumamoto", - "kyoto", - "lg", - "mie", - "miyagi", - "miyazaki", - "nagano", - "nagasaki", - "nagoya", - "nara", - "ne", - "niigata", - "oita", - "okayama", - "okinawa", - "or", - "osaka", - "saga", - "saitama", - "sapporo", - "sendai", - "shiga", - "shimane", - "shizuoka", - "tochigi", - "tokushima", - "tokyo", - "tottori", - "toyama", - "wakayama", - "xn--0trq7p7nn", - "xn--1ctwo", - "xn--1lqs03n", - "xn--1lqs71d", - "xn--2m4a15e", - "xn--32vp30h", - "xn--4it168d", - "xn--4it797k", - "xn--4pvxs", - "xn--5js045d", - "xn--5rtp49c", - "xn--5rtq34k", - "xn--6btw5a", - "xn--6orx2r", - "xn--7t0a264c", - "xn--8ltr62k", - "xn--8pvr4u", - "xn--c3s14m", - "xn--d5qv7z876c", - "xn--djrs72d6uy", - "xn--djty4k", - "xn--efvn9s", - "xn--ehqz56n", - "xn--elqq16h", - "xn--f6qx53a", - "xn--k7yn95e", - "xn--kbrq7o", - "xn--klt787d", - "xn--kltp7d", - "xn--kltx9a", - "xn--klty5x", - "xn--mkru45i", - "xn--nit225k", - "xn--ntso0iqx3a", - "xn--ntsq17g", - "xn--pssu33l", - "xn--qqqt11m", - "xn--rht27z", - "xn--rht3d", - "xn--rht61e", - "xn--rny31h", - "xn--tor131o", - "xn--uist22h", - "xn--uisz3g", - "xn--uuwu58a", - "xn--vgu402c", - "xn--zbx025d", - "yamagata", - "yamaguchi", - "yamanashi", - "yokohama", - "aisai", - "ama", - "anjo", - "asuke", - "chiryu", - "chita", - "fuso", - "gamagori", - "handa", - "hazu", - "hekinan", - "higashiura", - "ichinomiya", - "inazawa", - "inuyama", - "isshiki", - "iwakura", - "kanie", - "kariya", - "kasugai", - "kira", - "kiyosu", - "komaki", - "konan", - "kota", - "mihama", - "miyoshi", - "nishio", - "nisshin", - "obu", - "oguchi", - "oharu", - "okazaki", - "owariasahi", - "seto", - "shikatsu", - "shinshiro", - "shitara", - "tahara", - "takahama", - "tobishima", - "toei", - "togo", - "tokai", - "tokoname", - "toyoake", - "toyohashi", - "toyokawa", - "toyone", - "toyota", - "tsushima", - "yatomi", - "akita", - "daisen", - "fujisato", - "gojome", - "hachirogata", - "happou", - "higashinaruse", - "honjo", - "honjyo", - "ikawa", - "kamikoani", - "kamioka", - "katagami", - "kazuno", - "kitaakita", - "kosaka", - "kyowa", - "misato", - "mitane", - "moriyoshi", - "nikaho", - "noshiro", - "odate", - "oga", - "ogata", - "semboku", - "yokote", - "yurihonjo", - "aomori", - "gonohe", - "hachinohe", - "hashikami", - "hiranai", - "hirosaki", - "itayanagi", - "kuroishi", - "misawa", - "mutsu", - "nakadomari", - "noheji", - "oirase", - "owani", - "rokunohe", - "sannohe", - "shichinohe", - "shingo", - "takko", - "towada", - "tsugaru", - "tsuruta", - "abiko", - "asahi", - "chonan", - "chosei", - "choshi", - "chuo", - "funabashi", - "futtsu", - "hanamigawa", - "ichihara", - "ichikawa", - "ichinomiya", - "inzai", - "isumi", - "kamagaya", - "kamogawa", - "kashiwa", - "katori", - "katsuura", - "kimitsu", - "kisarazu", - "kozaki", - "kujukuri", - "kyonan", - "matsudo", - "midori", - "mihama", - "minamiboso", - "mobara", - "mutsuzawa", - "nagara", - "nagareyama", - "narashino", - "narita", - "noda", - "oamishirasato", - "omigawa", - "onjuku", - "otaki", - "sakae", - "sakura", - "shimofusa", - "shirako", - "shiroi", - "shisui", - "sodegaura", - "sosa", - "tako", - "tateyama", - "togane", - "tohnosho", - "tomisato", - "urayasu", - "yachimata", - "yachiyo", - "yokaichiba", - "yokoshibahikari", - "yotsukaido", - "ainan", - "honai", - "ikata", - "imabari", - "iyo", - "kamijima", - "kihoku", - "kumakogen", - "masaki", - "matsuno", - "matsuyama", - "namikata", - "niihama", - "ozu", - "saijo", - "seiyo", - "shikokuchuo", - "tobe", - "toon", - "uchiko", - "uwajima", - "yawatahama", - "echizen", - "eiheiji", - "fukui", - "ikeda", - "katsuyama", - "mihama", - "minamiechizen", - "obama", - "ohi", - "ono", - "sabae", - "sakai", - "takahama", - "tsuruga", - "wakasa", - "ashiya", - "buzen", - "chikugo", - "chikuho", - "chikujo", - "chikushino", - "chikuzen", - "chuo", - "dazaifu", - "fukuchi", - "hakata", - "higashi", - "hirokawa", - "hisayama", - "iizuka", - "inatsuki", - "kaho", - "kasuga", - "kasuya", - "kawara", - "keisen", - "koga", - "kurate", - "kurogi", - "kurume", - "minami", - "miyako", - "miyama", - "miyawaka", - "mizumaki", - "munakata", - "nakagawa", - "nakama", - "nishi", - "nogata", - "ogori", - "okagaki", - "okawa", - "oki", - "omuta", - "onga", - "onojo", - "oto", - "saigawa", - "sasaguri", - "shingu", - "shinyoshitomi", - "shonai", - "soeda", - "sue", - "tachiarai", - "tagawa", - "takata", - "toho", - "toyotsu", - "tsuiki", - "ukiha", - "umi", - "usui", - "yamada", - "yame", - "yanagawa", - "yukuhashi", - "aizubange", - "aizumisato", - "aizuwakamatsu", - "asakawa", - "bandai", - "date", - "fukushima", - "furudono", - "futaba", - "hanawa", - "higashi", - "hirata", - "hirono", - "iitate", - "inawashiro", - "ishikawa", - "iwaki", - "izumizaki", - "kagamiishi", - "kaneyama", - "kawamata", - "kitakata", - "kitashiobara", - "koori", - "koriyama", - "kunimi", - "miharu", - "mishima", - "namie", - "nango", - "nishiaizu", - "nishigo", - "okuma", - "omotego", - "ono", - "otama", - "samegawa", - "shimogo", - "shirakawa", - "showa", - "soma", - "sukagawa", - "taishin", - "tamakawa", - "tanagura", - "tenei", - "yabuki", - "yamato", - "yamatsuri", - "yanaizu", - "yugawa", - "anpachi", - "ena", - "gifu", - "ginan", - "godo", - "gujo", - "hashima", - "hichiso", - "hida", - "higashishirakawa", - "ibigawa", - "ikeda", - "kakamigahara", - "kani", - "kasahara", - "kasamatsu", - "kawaue", - "kitagata", - "mino", - "minokamo", - "mitake", - "mizunami", - "motosu", - "nakatsugawa", - "ogaki", - "sakahogi", - "seki", - "sekigahara", - "shirakawa", - "tajimi", - "takayama", - "tarui", - "toki", - "tomika", - "wanouchi", - "yamagata", - "yaotsu", - "yoro", - "annaka", - "chiyoda", - "fujioka", - "higashiagatsuma", - "isesaki", - "itakura", - "kanna", - "kanra", - "katashina", - "kawaba", - "kiryu", - "kusatsu", - "maebashi", - "meiwa", - "midori", - "minakami", - "naganohara", - "nakanojo", - "nanmoku", - "numata", - "oizumi", - "ora", - "ota", - "shibukawa", - "shimonita", - "shinto", - "showa", - "takasaki", - "takayama", - "tamamura", - "tatebayashi", - "tomioka", - "tsukiyono", - "tsumagoi", - "ueno", - "yoshioka", - "asaminami", - "daiwa", - "etajima", - "fuchu", - "fukuyama", - "hatsukaichi", - "higashihiroshima", - "hongo", - "jinsekikogen", - "kaita", - "kui", - "kumano", - "kure", - "mihara", - "miyoshi", - "naka", - "onomichi", - "osakikamijima", - "otake", - "saka", - "sera", - "seranishi", - "shinichi", - "shobara", - "takehara", - "abashiri", - "abira", - "aibetsu", - "akabira", - "akkeshi", - "asahikawa", - "ashibetsu", - "ashoro", - "assabu", - "atsuma", - "bibai", - "biei", - "bifuka", - "bihoro", - "biratori", - "chippubetsu", - "chitose", - "date", - "ebetsu", - "embetsu", - "eniwa", - "erimo", - "esan", - "esashi", - "fukagawa", - "fukushima", - "furano", - "furubira", - "haboro", - "hakodate", - "hamatonbetsu", - "hidaka", - "higashikagura", - "higashikawa", - "hiroo", - "hokuryu", - "hokuto", - "honbetsu", - "horokanai", - "horonobe", - "ikeda", - "imakane", - "ishikari", - "iwamizawa", - "iwanai", - "kamifurano", - "kamikawa", - "kamishihoro", - "kamisunagawa", - "kamoenai", - "kayabe", - "kembuchi", - "kikonai", - "kimobetsu", - "kitahiroshima", - "kitami", - "kiyosato", - "koshimizu", - "kunneppu", - "kuriyama", - "kuromatsunai", - "kushiro", - "kutchan", - "kyowa", - "mashike", - "matsumae", - "mikasa", - "minamifurano", - "mombetsu", - "moseushi", - "mukawa", - "muroran", - "naie", - "nakagawa", - "nakasatsunai", - "nakatombetsu", - "nanae", - "nanporo", - "nayoro", - "nemuro", - "niikappu", - "niki", - "nishiokoppe", - "noboribetsu", - "numata", - "obihiro", - "obira", - "oketo", - "okoppe", - "otaru", - "otobe", - "otofuke", - "otoineppu", - "oumu", - "ozora", - "pippu", - "rankoshi", - "rebun", - "rikubetsu", - "rishiri", - "rishirifuji", - "saroma", - "sarufutsu", - "shakotan", - "shari", - "shibecha", - "shibetsu", - "shikabe", - "shikaoi", - "shimamaki", - "shimizu", - "shimokawa", - "shinshinotsu", - "shintoku", - "shiranuka", - "shiraoi", - "shiriuchi", - "sobetsu", - "sunagawa", - "taiki", - "takasu", - "takikawa", - "takinoue", - "teshikaga", - "tobetsu", - "tohma", - "tomakomai", - "tomari", - "toya", - "toyako", - "toyotomi", - "toyoura", - "tsubetsu", - "tsukigata", - "urakawa", - "urausu", - "uryu", - "utashinai", - "wakkanai", - "wassamu", - "yakumo", - "yoichi", - "aioi", - "akashi", - "ako", - "amagasaki", - "aogaki", - "asago", - "ashiya", - "awaji", - "fukusaki", - "goshiki", - "harima", - "himeji", - "ichikawa", - "inagawa", - "itami", - "kakogawa", - "kamigori", - "kamikawa", - "kasai", - "kasuga", - "kawanishi", - "miki", - "minamiawaji", - "nishinomiya", - "nishiwaki", - "ono", - "sanda", - "sannan", - "sasayama", - "sayo", - "shingu", - "shinonsen", - "shiso", - "sumoto", - "taishi", - "taka", - "takarazuka", - "takasago", - "takino", - "tamba", - "tatsuno", - "toyooka", - "yabu", - "yashiro", - "yoka", - "yokawa", - "ami", - "asahi", - "bando", - "chikusei", - "daigo", - "fujishiro", - "hitachi", - "hitachinaka", - "hitachiomiya", - "hitachiota", - "ibaraki", - "ina", - "inashiki", - "itako", - "iwama", - "joso", - "kamisu", - "kasama", - "kashima", - "kasumigaura", - "koga", - "miho", - "mito", - "moriya", - "naka", - "namegata", - "oarai", - "ogawa", - "omitama", - "ryugasaki", - "sakai", - "sakuragawa", - "shimodate", - "shimotsuma", - "shirosato", - "sowa", - "suifu", - "takahagi", - "tamatsukuri", - "tokai", - "tomobe", - "tone", - "toride", - "tsuchiura", - "tsukuba", - "uchihara", - "ushiku", - "yachiyo", - "yamagata", - "yawara", - "yuki", - "anamizu", - "hakui", - "hakusan", - "kaga", - "kahoku", - "kanazawa", - "kawakita", - "komatsu", - "nakanoto", - "nanao", - "nomi", - "nonoichi", - "noto", - "shika", - "suzu", - "tsubata", - "tsurugi", - "uchinada", - "wajima", - "fudai", - "fujisawa", - "hanamaki", - "hiraizumi", - "hirono", - "ichinohe", - "ichinoseki", - "iwaizumi", - "iwate", - "joboji", - "kamaishi", - "kanegasaki", - "karumai", - "kawai", - "kitakami", - "kuji", - "kunohe", - "kuzumaki", - "miyako", - "mizusawa", - "morioka", - "ninohe", - "noda", - "ofunato", - "oshu", - "otsuchi", - "rikuzentakata", - "shiwa", - "shizukuishi", - "sumita", - "tanohata", - "tono", - "yahaba", - "yamada", - "ayagawa", - "higashikagawa", - "kanonji", - "kotohira", - "manno", - "marugame", - "mitoyo", - "naoshima", - "sanuki", - "tadotsu", - "takamatsu", - "tonosho", - "uchinomi", - "utazu", - "zentsuji", - "akune", - "amami", - "hioki", - "isa", - "isen", - "izumi", - "kagoshima", - "kanoya", - "kawanabe", - "kinko", - "kouyama", - "makurazaki", - "matsumoto", - "minamitane", - "nakatane", - "nishinoomote", - "satsumasendai", - "soo", - "tarumizu", - "yusui", - "aikawa", - "atsugi", - "ayase", - "chigasaki", - "ebina", - "fujisawa", - "hadano", - "hakone", - "hiratsuka", - "isehara", - "kaisei", - "kamakura", - "kiyokawa", - "matsuda", - "minamiashigara", - "miura", - "nakai", - "ninomiya", - "odawara", - "oi", - "oiso", - "sagamihara", - "samukawa", - "tsukui", - "yamakita", - "yamato", - "yokosuka", - "yugawara", - "zama", - "zushi", - "city", - "city", - "city", - "aki", - "geisei", - "hidaka", - "higashitsuno", - "ino", - "kagami", - "kami", - "kitagawa", - "kochi", - "mihara", - "motoyama", - "muroto", - "nahari", - "nakamura", - "nankoku", - "nishitosa", - "niyodogawa", - "ochi", - "okawa", - "otoyo", - "otsuki", - "sakawa", - "sukumo", - "susaki", - "tosa", - "tosashimizu", - "toyo", - "tsuno", - "umaji", - "yasuda", - "yusuhara", - "amakusa", - "arao", - "aso", - "choyo", - "gyokuto", - "kamiamakusa", - "kikuchi", - "kumamoto", - "mashiki", - "mifune", - "minamata", - "minamioguni", - "nagasu", - "nishihara", - "oguni", - "ozu", - "sumoto", - "takamori", - "uki", - "uto", - "yamaga", - "yamato", - "yatsushiro", - "ayabe", - "fukuchiyama", - "higashiyama", - "ide", - "ine", - "joyo", - "kameoka", - "kamo", - "kita", - "kizu", - "kumiyama", - "kyotamba", - "kyotanabe", - "kyotango", - "maizuru", - "minami", - "minamiyamashiro", - "miyazu", - "muko", - "nagaokakyo", - "nakagyo", - "nantan", - "oyamazaki", - "sakyo", - "seika", - "tanabe", - "uji", - "ujitawara", - "wazuka", - "yamashina", - "yawata", - "asahi", - "inabe", - "ise", - "kameyama", - "kawagoe", - "kiho", - "kisosaki", - "kiwa", - "komono", - "kumano", - "kuwana", - "matsusaka", - "meiwa", - "mihama", - "minamiise", - "misugi", - "miyama", - "nabari", - "shima", - "suzuka", - "tado", - "taiki", - "taki", - "tamaki", - "toba", - "tsu", - "udono", - "ureshino", - "watarai", - "yokkaichi", - "furukawa", - "higashimatsushima", - "ishinomaki", - "iwanuma", - "kakuda", - "kami", - "kawasaki", - "marumori", - "matsushima", - "minamisanriku", - "misato", - "murata", - "natori", - "ogawara", - "ohira", - "onagawa", - "osaki", - "rifu", - "semine", - "shibata", - "shichikashuku", - "shikama", - "shiogama", - "shiroishi", - "tagajo", - "taiwa", - "tome", - "tomiya", - "wakuya", - "watari", - "yamamoto", - "zao", - "aya", - "ebino", - "gokase", - "hyuga", - "kadogawa", - "kawaminami", - "kijo", - "kitagawa", - "kitakata", - "kitaura", - "kobayashi", - "kunitomi", - "kushima", - "mimata", - "miyakonojo", - "miyazaki", - "morotsuka", - "nichinan", - "nishimera", - "nobeoka", - "saito", - "shiiba", - "shintomi", - "takaharu", - "takanabe", - "takazaki", - "tsuno", - "achi", - "agematsu", - "anan", - "aoki", - "asahi", - "azumino", - "chikuhoku", - "chikuma", - "chino", - "fujimi", - "hakuba", - "hara", - "hiraya", - "iida", - "iijima", - "iiyama", - "iizuna", - "ikeda", - "ikusaka", - "ina", - "karuizawa", - "kawakami", - "kiso", - "kisofukushima", - "kitaaiki", - "komagane", - "komoro", - "matsukawa", - "matsumoto", - "miasa", - "minamiaiki", - "minamimaki", - "minamiminowa", - "minowa", - "miyada", - "miyota", - "mochizuki", - "nagano", - "nagawa", - "nagiso", - "nakagawa", - "nakano", - "nozawaonsen", - "obuse", - "ogawa", - "okaya", - "omachi", - "omi", - "ookuwa", - "ooshika", - "otaki", - "otari", - "sakae", - "sakaki", - "saku", - "sakuho", - "shimosuwa", - "shinanomachi", - "shiojiri", - "suwa", - "suzaka", - "takagi", - "takamori", - "takayama", - "tateshina", - "tatsuno", - "togakushi", - "togura", - "tomi", - "ueda", - "wada", - "yamagata", - "yamanouchi", - "yasaka", - "yasuoka", - "chijiwa", - "futsu", - "goto", - "hasami", - "hirado", - "iki", - "isahaya", - "kawatana", - "kuchinotsu", - "matsuura", - "nagasaki", - "obama", - "omura", - "oseto", - "saikai", - "sasebo", - "seihi", - "shimabara", - "shinkamigoto", - "togitsu", - "tsushima", - "unzen", - "city", - "ando", - "gose", - "heguri", - "higashiyoshino", - "ikaruga", - "ikoma", - "kamikitayama", - "kanmaki", - "kashiba", - "kashihara", - "katsuragi", - "kawai", - "kawakami", - "kawanishi", - "koryo", - "kurotaki", - "mitsue", - "miyake", - "nara", - "nosegawa", - "oji", - "ouda", - "oyodo", - "sakurai", - "sango", - "shimoichi", - "shimokitayama", - "shinjo", - "soni", - "takatori", - "tawaramoto", - "tenkawa", - "tenri", - "uda", - "yamatokoriyama", - "yamatotakada", - "yamazoe", - "yoshino", - "aga", - "agano", - "gosen", - "itoigawa", - "izumozaki", - "joetsu", - "kamo", - "kariwa", - "kashiwazaki", - "minamiuonuma", - "mitsuke", - "muika", - "murakami", - "myoko", - "nagaoka", - "niigata", - "ojiya", - "omi", - "sado", - "sanjo", - "seiro", - "seirou", - "sekikawa", - "shibata", - "tagami", - "tainai", - "tochio", - "tokamachi", - "tsubame", - "tsunan", - "uonuma", - "yahiko", - "yoita", - "yuzawa", - "beppu", - "bungoono", - "bungotakada", - "hasama", - "hiji", - "himeshima", - "hita", - "kamitsue", - "kokonoe", - "kuju", - "kunisaki", - "kusu", - "oita", - "saiki", - "taketa", - "tsukumi", - "usa", - "usuki", - "yufu", - "akaiwa", - "asakuchi", - "bizen", - "hayashima", - "ibara", - "kagamino", - "kasaoka", - "kibichuo", - "kumenan", - "kurashiki", - "maniwa", - "misaki", - "nagi", - "niimi", - "nishiawakura", - "okayama", - "satosho", - "setouchi", - "shinjo", - "shoo", - "soja", - "takahashi", - "tamano", - "tsuyama", - "wake", - "yakage", - "aguni", - "ginowan", - "ginoza", - "gushikami", - "haebaru", - "higashi", - "hirara", - "iheya", - "ishigaki", - "ishikawa", - "itoman", - "izena", - "kadena", - "kin", - "kitadaito", - "kitanakagusuku", - "kumejima", - "kunigami", - "minamidaito", - "motobu", - "nago", - "naha", - "nakagusuku", - "nakijin", - "nanjo", - "nishihara", - "ogimi", - "okinawa", - "onna", - "shimoji", - "taketomi", - "tarama", - "tokashiki", - "tomigusuku", - "tonaki", - "urasoe", - "uruma", - "yaese", - "yomitan", - "yonabaru", - "yonaguni", - "zamami", - "abeno", - "chihayaakasaka", - "chuo", - "daito", - "fujiidera", - "habikino", - "hannan", - "higashiosaka", - "higashisumiyoshi", - "higashiyodogawa", - "hirakata", - "ibaraki", - "ikeda", - "izumi", - "izumiotsu", - "izumisano", - "kadoma", - "kaizuka", - "kanan", - "kashiwara", - "katano", - "kawachinagano", - "kishiwada", - "kita", - "kumatori", - "matsubara", - "minato", - "minoh", - "misaki", - "moriguchi", - "neyagawa", - "nishi", - "nose", - "osakasayama", - "sakai", - "sayama", - "sennan", - "settsu", - "shijonawate", - "shimamoto", - "suita", - "tadaoka", - "taishi", - "tajiri", - "takaishi", - "takatsuki", - "tondabayashi", - "toyonaka", - "toyono", - "yao", - "ariake", - "arita", - "fukudomi", - "genkai", - "hamatama", - "hizen", - "imari", - "kamimine", - "kanzaki", - "karatsu", - "kashima", - "kitagata", - "kitahata", - "kiyama", - "kouhoku", - "kyuragi", - "nishiarita", - "ogi", - "omachi", - "ouchi", - "saga", - "shiroishi", - "taku", - "tara", - "tosu", - "yoshinogari", - "arakawa", - "asaka", - "chichibu", - "fujimi", - "fujimino", - "fukaya", - "hanno", - "hanyu", - "hasuda", - "hatogaya", - "hatoyama", - "hidaka", - "higashichichibu", - "higashimatsuyama", - "honjo", - "ina", - "iruma", - "iwatsuki", - "kamiizumi", - "kamikawa", - "kamisato", - "kasukabe", - "kawagoe", - "kawaguchi", - "kawajima", - "kazo", - "kitamoto", - "koshigaya", - "kounosu", - "kuki", - "kumagaya", - "matsubushi", - "minano", - "misato", - "miyashiro", - "miyoshi", - "moroyama", - "nagatoro", - "namegawa", - "niiza", - "ogano", - "ogawa", - "ogose", - "okegawa", - "omiya", - "otaki", - "ranzan", - "ryokami", - "saitama", - "sakado", - "satte", - "sayama", - "shiki", - "shiraoka", - "soka", - "sugito", - "toda", - "tokigawa", - "tokorozawa", - "tsurugashima", - "urawa", - "warabi", - "yashio", - "yokoze", - "yono", - "yorii", - "yoshida", - "yoshikawa", - "yoshimi", - "city", - "city", - "aisho", - "gamo", - "higashiomi", - "hikone", - "koka", - "konan", - "kosei", - "koto", - "kusatsu", - "maibara", - "moriyama", - "nagahama", - "nishiazai", - "notogawa", - "omihachiman", - "otsu", - "ritto", - "ryuoh", - "takashima", - "takatsuki", - "torahime", - "toyosato", - "yasu", - "akagi", - "ama", - "gotsu", - "hamada", - "higashiizumo", - "hikawa", - "hikimi", - "izumo", - "kakinoki", - "masuda", - "matsue", - "misato", - "nishinoshima", - "ohda", - "okinoshima", - "okuizumo", - "shimane", - "tamayu", - "tsuwano", - "unnan", - "yakumo", - "yasugi", - "yatsuka", - "arai", - "atami", - "fuji", - "fujieda", - "fujikawa", - "fujinomiya", - "fukuroi", - "gotemba", - "haibara", - "hamamatsu", - "higashiizu", - "ito", - "iwata", - "izu", - "izunokuni", - "kakegawa", - "kannami", - "kawanehon", - "kawazu", - "kikugawa", - "kosai", - "makinohara", - "matsuzaki", - "minamiizu", - "mishima", - "morimachi", - "nishiizu", - "numazu", - "omaezaki", - "shimada", - "shimizu", - "shimoda", - "shizuoka", - "susono", - "yaizu", - "yoshida", - "ashikaga", - "bato", - "haga", - "ichikai", - "iwafune", - "kaminokawa", - "kanuma", - "karasuyama", - "kuroiso", - "mashiko", - "mibu", - "moka", - "motegi", - "nasu", - "nasushiobara", - "nikko", - "nishikata", - "nogi", - "ohira", - "ohtawara", - "oyama", - "sakura", - "sano", - "shimotsuke", - "shioya", - "takanezawa", - "tochigi", - "tsuga", - "ujiie", - "utsunomiya", - "yaita", - "aizumi", - "anan", - "ichiba", - "itano", - "kainan", - "komatsushima", - "matsushige", - "mima", - "minami", - "miyoshi", - "mugi", - "nakagawa", - "naruto", - "sanagochi", - "shishikui", - "tokushima", - "wajiki", - "adachi", - "akiruno", - "akishima", - "aogashima", - "arakawa", - "bunkyo", - "chiyoda", - "chofu", - "chuo", - "edogawa", - "fuchu", - "fussa", - "hachijo", - "hachioji", - "hamura", - "higashikurume", - "higashimurayama", - "higashiyamato", - "hino", - "hinode", - "hinohara", - "inagi", - "itabashi", - "katsushika", - "kita", - "kiyose", - "kodaira", - "koganei", - "kokubunji", - "komae", - "koto", - "kouzushima", - "kunitachi", - "machida", - "meguro", - "minato", - "mitaka", - "mizuho", - "musashimurayama", - "musashino", - "nakano", - "nerima", - "ogasawara", - "okutama", - "ome", - "oshima", - "ota", - "setagaya", - "shibuya", - "shinagawa", - "shinjuku", - "suginami", - "sumida", - "tachikawa", - "taito", - "tama", - "toshima", - "chizu", - "hino", - "kawahara", - "koge", - "kotoura", - "misasa", - "nanbu", - "nichinan", - "sakaiminato", - "tottori", - "wakasa", - "yazu", - "yonago", - "asahi", - "fuchu", - "fukumitsu", - "funahashi", - "himi", - "imizu", - "inami", - "johana", - "kamiichi", - "kurobe", - "nakaniikawa", - "namerikawa", - "nanto", - "nyuzen", - "oyabe", - "taira", - "takaoka", - "tateyama", - "toga", - "tonami", - "toyama", - "unazuki", - "uozu", - "yamada", - "arida", - "aridagawa", - "gobo", - "hashimoto", - "hidaka", - "hirogawa", - "inami", - "iwade", - "kainan", - "kamitonda", - "katsuragi", - "kimino", - "kinokawa", - "kitayama", - "koya", - "koza", - "kozagawa", - "kudoyama", - "kushimoto", - "mihama", - "misato", - "nachikatsuura", - "shingu", - "shirahama", - "taiji", - "tanabe", - "wakayama", - "yuasa", - "yura", - "asahi", - "funagata", - "higashine", - "iide", - "kahoku", - "kaminoyama", - "kaneyama", - "kawanishi", - "mamurogawa", - "mikawa", - "murayama", - "nagai", - "nakayama", - "nanyo", - "nishikawa", - "obanazawa", - "oe", - "oguni", - "ohkura", - "oishida", - "sagae", - "sakata", - "sakegawa", - "shinjo", - "shirataka", - "shonai", - "takahata", - "tendo", - "tozawa", - "tsuruoka", - "yamagata", - "yamanobe", - "yonezawa", - "yuza", - "abu", - "hagi", - "hikari", - "hofu", - "iwakuni", - "kudamatsu", - "mitou", - "nagato", - "oshima", - "shimonoseki", - "shunan", - "tabuse", - "tokuyama", - "toyota", - "ube", - "yuu", - "chuo", - "doshi", - "fuefuki", - "fujikawa", - "fujikawaguchiko", - "fujiyoshida", - "hayakawa", - "hokuto", - "ichikawamisato", - "kai", - "kofu", - "koshu", - "kosuge", - "minami-alps", - "minobu", - "nakamichi", - "nanbu", - "narusawa", - "nirasaki", - "nishikatsura", - "oshino", - "otsuki", - "showa", - "tabayama", - "tsuru", - "uenohara", - "yamanakako", - "yamanashi", - "city", - "co", - "blogspot", - "com", - "edu", - "gov", - "mil", - "net", - "org", - "biz", - "com", - "edu", - "gov", - "info", - "net", - "org", - "ass", - "asso", - "com", - "coop", - "edu", - "gouv", - "gov", - "medecin", - "mil", - "nom", - "notaires", - "org", - "pharmaciens", - "prd", - "presse", - "tm", - "veterinaire", - "edu", - "gov", - "net", - "org", - "com", - "edu", - "gov", - "org", - "rep", - "tra", - "ac", - "blogspot", - "busan", - "chungbuk", - "chungnam", - "co", - "daegu", - "daejeon", - "es", - "gangwon", - "go", - "gwangju", - "gyeongbuk", - "gyeonggi", - "gyeongnam", - "hs", - "incheon", - "jeju", - "jeonbuk", - "jeonnam", - "kg", - "mil", - "ms", - "ne", - "or", - "pe", - "re", - "sc", - "seoul", - "ulsan", - "co", - "edu", - "com", - "edu", - "gov", - "net", - "org", - "com", - "edu", - "gov", - "mil", - "net", - "nym", - "org", - "bnr", - "c", - "com", - "edu", - "gov", - "info", - "int", - "net", - "nym", - "org", - "per", - "static", - "dev", - "sites", - "com", - "edu", - "gov", - "net", - "org", - "co", - "com", - "edu", - "gov", - "net", - "org", - "oy", - "blogspot", - "nom", - "nym", - "cyon", - "mypep", - "ac", - "assn", - "com", - "edu", - "gov", - "grp", - "hotel", - "int", - "ltd", - "net", - "ngo", - "org", - "sch", - "soc", - "web", - "com", - "edu", - "gov", - "net", - "org", - "co", - "org", - "blogspot", - "gov", - "nym", - "blogspot", - "nym", - "asn", - "com", - "conf", - "edu", - "gov", - "id", - "mil", - "net", - "org", - "com", - "edu", - "gov", - "id", - "med", - "net", - "org", - "plc", - "sch", - "ac", - "co", - "gov", - "net", - "org", - "press", - "router", - "asso", - "tm", - "blogspot", - "ac", - "brasilia", - "c66", - "co", - "daplie", - "ddns", - "diskstation", - "dnsfor", - "dscloud", - "edu", - "filegear", - "gov", - "hopto", - "i234", - "its", - "loginto", - "myds", - "net", - "noip", - "nym", - "org", - "priv", - "synology", - "webhop", - "wedeploy", - "yombo", - "localhost", - "co", - "com", - "edu", - "gov", - "mil", - "nom", - "org", - "prd", - "tm", - "blogspot", - "com", - "edu", - "gov", - "inf", - "name", - "net", - "nom", - "org", - "com", - "edu", - "gouv", - "gov", - "net", - "org", - "presse", - "edu", - "gov", - "nyc", - "org", - "com", - "edu", - "gov", - "net", - "org", - "dscloud", - "blogspot", - "gov", - "com", - "edu", - "gov", - "net", - "org", - "com", - "edu", - "net", - "org", - "blogspot", - "ac", - "co", - "com", - "gov", - "net", - "or", - "org", - "academy", - "agriculture", - "air", - "airguard", - "alabama", - "alaska", - "amber", - "ambulance", - "american", - "americana", - "americanantiques", - "americanart", - "amsterdam", - "and", - "annefrank", - "anthro", - "anthropology", - "antiques", - "aquarium", - "arboretum", - "archaeological", - "archaeology", - "architecture", - "art", - "artanddesign", - "artcenter", - "artdeco", - "arteducation", - "artgallery", - "arts", - "artsandcrafts", - "asmatart", - "assassination", - "assisi", - "association", - "astronomy", - "atlanta", - "austin", - "australia", - "automotive", - "aviation", - "axis", - "badajoz", - "baghdad", - "bahn", - "bale", - "baltimore", - "barcelona", - "baseball", - "basel", - "baths", - "bauern", - "beauxarts", - "beeldengeluid", - "bellevue", - "bergbau", - "berkeley", - "berlin", - "bern", - "bible", - "bilbao", - "bill", - "birdart", - "birthplace", - "bonn", - "boston", - "botanical", - "botanicalgarden", - "botanicgarden", - "botany", - "brandywinevalley", - "brasil", - "bristol", - "british", - "britishcolumbia", - "broadcast", - "brunel", - "brussel", - "brussels", - "bruxelles", - "building", - "burghof", - "bus", - "bushey", - "cadaques", - "california", - "cambridge", - "can", - "canada", - "capebreton", - "carrier", - "cartoonart", - "casadelamoneda", - "castle", - "castres", - "celtic", - "center", - "chattanooga", - "cheltenham", - "chesapeakebay", - "chicago", - "children", - "childrens", - "childrensgarden", - "chiropractic", - "chocolate", - "christiansburg", - "cincinnati", - "cinema", - "circus", - "civilisation", - "civilization", - "civilwar", - "clinton", - "clock", - "coal", - "coastaldefence", - "cody", - "coldwar", - "collection", - "colonialwilliamsburg", - "coloradoplateau", - "columbia", - "columbus", - "communication", - "communications", - "community", - "computer", - "computerhistory", - "contemporary", - "contemporaryart", - "convent", - "copenhagen", - "corporation", - "corvette", - "costume", - "countryestate", - "county", - "crafts", - "cranbrook", - "creation", - "cultural", - "culturalcenter", - "culture", - "cyber", - "cymru", - "dali", - "dallas", - "database", - "ddr", - "decorativearts", - "delaware", - "delmenhorst", - "denmark", - "depot", - "design", - "detroit", - "dinosaur", - "discovery", - "dolls", - "donostia", - "durham", - "eastafrica", - "eastcoast", - "education", - "educational", - "egyptian", - "eisenbahn", - "elburg", - "elvendrell", - "embroidery", - "encyclopedic", - "england", - "entomology", - "environment", - "environmentalconservation", - "epilepsy", - "essex", - "estate", - "ethnology", - "exeter", - "exhibition", - "family", - "farm", - "farmequipment", - "farmers", - "farmstead", - "field", - "figueres", - "filatelia", - "film", - "fineart", - "finearts", - "finland", - "flanders", - "florida", - "force", - "fortmissoula", - "fortworth", - "foundation", - "francaise", - "frankfurt", - "franziskaner", - "freemasonry", - "freiburg", - "fribourg", - "frog", - "fundacio", - "furniture", - "gallery", - "garden", - "gateway", - "geelvinck", - "gemological", - "geology", - "georgia", - "giessen", - "glas", - "glass", - "gorge", - "grandrapids", - "graz", - "guernsey", - "halloffame", - "hamburg", - "handson", - "harvestcelebration", - "hawaii", - "health", - "heimatunduhren", - "hellas", - "helsinki", - "hembygdsforbund", - "heritage", - "histoire", - "historical", - "historicalsociety", - "historichouses", - "historisch", - "historisches", - "history", - "historyofscience", - "horology", - "house", - "humanities", - "illustration", - "imageandsound", - "indian", - "indiana", - "indianapolis", - "indianmarket", - "intelligence", - "interactive", - "iraq", - "iron", - "isleofman", - "jamison", - "jefferson", - "jerusalem", - "jewelry", - "jewish", - "jewishart", - "jfk", - "journalism", - "judaica", - "judygarland", - "juedisches", - "juif", - "karate", - "karikatur", - "kids", - "koebenhavn", - "koeln", - "kunst", - "kunstsammlung", - "kunstunddesign", - "labor", - "labour", - "lajolla", - "lancashire", - "landes", - "lans", - "larsson", - "lewismiller", - "lincoln", - "linz", - "living", - "livinghistory", - "localhistory", - "london", - "losangeles", - "louvre", - "loyalist", - "lucerne", - "luxembourg", - "luzern", - "mad", - "madrid", - "mallorca", - "manchester", - "mansion", - "mansions", - "manx", - "marburg", - "maritime", - "maritimo", - "maryland", - "marylhurst", - "media", - "medical", - "medizinhistorisches", - "meeres", - "memorial", - "mesaverde", - "michigan", - "midatlantic", - "military", - "mill", - "miners", - "mining", - "minnesota", - "missile", - "missoula", - "modern", - "moma", - "money", - "monmouth", - "monticello", - "montreal", - "moscow", - "motorcycle", - "muenchen", - "muenster", - "mulhouse", - "muncie", - "museet", - "museumcenter", - "museumvereniging", - "music", - "national", - "nationalfirearms", - "nationalheritage", - "nativeamerican", - "naturalhistory", - "naturalhistorymuseum", - "naturalsciences", - "nature", - "naturhistorisches", - "natuurwetenschappen", - "naumburg", - "naval", - "nebraska", - "neues", - "newhampshire", - "newjersey", - "newmexico", - "newport", - "newspaper", - "newyork", - "niepce", - "norfolk", - "north", - "nrw", - "nuernberg", - "nuremberg", - "nyc", - "nyny", - "oceanographic", - "oceanographique", - "omaha", - "online", - "ontario", - "openair", - "oregon", - "oregontrail", - "otago", - "oxford", - "pacific", - "paderborn", - "palace", - "paleo", - "palmsprings", - "panama", - "paris", - "pasadena", - "pharmacy", - "philadelphia", - "philadelphiaarea", - "philately", - "phoenix", - "photography", - "pilots", - "pittsburgh", - "planetarium", - "plantation", - "plants", - "plaza", - "portal", - "portland", - "portlligat", - "posts-and-telecommunications", - "preservation", - "presidio", - "press", - "project", - "public", - "pubol", - "quebec", - "railroad", - "railway", - "research", - "resistance", - "riodejaneiro", - "rochester", - "rockart", - "roma", - "russia", - "saintlouis", - "salem", - "salvadordali", - "salzburg", - "sandiego", - "sanfrancisco", - "santabarbara", - "santacruz", - "santafe", - "saskatchewan", - "satx", - "savannahga", - "schlesisches", - "schoenbrunn", - "schokoladen", - "school", - "schweiz", - "science", - "science-fiction", - "scienceandhistory", - "scienceandindustry", - "sciencecenter", - "sciencecenters", - "sciencehistory", - "sciences", - "sciencesnaturelles", - "scotland", - "seaport", - "settlement", - "settlers", - "shell", - "sherbrooke", - "sibenik", - "silk", - "ski", - "skole", - "society", - "sologne", - "soundandvision", - "southcarolina", - "southwest", - "space", - "spy", - "square", - "stadt", - "stalbans", - "starnberg", - "state", - "stateofdelaware", - "station", - "steam", - "steiermark", - "stjohn", - "stockholm", - "stpetersburg", - "stuttgart", - "suisse", - "surgeonshall", - "surrey", - "svizzera", - "sweden", - "sydney", - "tank", - "tcm", - "technology", - "telekommunikation", - "television", - "texas", - "textile", - "theater", - "time", - "timekeeping", - "topology", - "torino", - "touch", - "town", - "transport", - "tree", - "trolley", - "trust", - "trustee", - "uhren", - "ulm", - "undersea", - "university", - "usa", - "usantiques", - "usarts", - "uscountryestate", - "usculture", - "usdecorativearts", - "usgarden", - "ushistory", - "ushuaia", - "uslivinghistory", - "utah", - "uvic", - "valley", - "vantaa", - "versailles", - "viking", - "village", - "virginia", - "virtual", - "virtuel", - "vlaanderen", - "volkenkunde", - "wales", - "wallonie", - "war", - "washingtondc", - "watch-and-clock", - "watchandclock", - "western", - "westfalen", - "whaling", - "wildlife", - "williamsburg", - "windmill", - "workshop", - "xn--9dbhblg6di", - "xn--comunicaes-v6a2o", - "xn--correios-e-telecomunicaes-ghc29a", - "xn--h1aegh", - "xn--lns-qla", - "york", - "yorkshire", - "yosemite", - "youth", - "zoological", - "zoology", - "aero", - "biz", - "com", - "coop", - "edu", - "gov", - "info", - "int", - "mil", - "museum", - "name", - "net", - "org", - "pro", - "ac", - "biz", - "co", - "com", - "coop", - "edu", - "gov", - "int", - "museum", - "net", - "org", - "blogspot", - "com", - "edu", - "gob", - "net", - "nym", - "org", - "blogspot", - "com", - "edu", - "gov", - "mil", - "name", - "net", - "org", - "ac", - "adv", - "co", - "edu", - "gov", - "mil", - "net", - "org", - "ca", - "cc", - "co", - "com", - "dr", - "in", - "info", - "mobi", - "mx", - "name", - "or", - "org", - "pro", - "school", - "tv", - "us", - "ws", - "her", - "his", - "forgot", - "forgot", - "asso", - "nom", - "alwaysdata", - "at-band-camp", - "azure-mobile", - "azurewebsites", - "barsy", - "blogdns", - "boomla", - "bounceme", - "bplaced", - "broke-it", - "buyshouses", - "casacam", - "cdn77", - "cdn77-ssl", - "channelsdvr", - "cloudaccess", - "cloudapp", - "cloudfront", - "cloudfunctions", - "cryptonomic", - "ddns", - "debian", - "definima", - "dnsalias", - "dnsdojo", - "does-it", - "dontexist", - "dsmynas", - "dynalias", - "dynathome", - "dynu", - "dynv6", - "eating-organic", - "endofinternet", - "familyds", - "fastly", - "fastlylb", - "feste-ip", - "firewall-gateway", - "flynnhosting", - "from-az", - "from-co", - "from-la", - "from-ny", - "gb", - "gets-it", - "ham-radio-op", - "homeftp", - "homeip", - "homelinux", - "homeunix", - "hu", - "in", - "in-the-band", - "ipifony", - "is-a-chef", - "is-a-geek", - "isa-geek", - "jp", - "kicks-ass", - "knx-server", - "moonscale", - "mydissent", - "myeffect", - "myfritz", - "mymediapc", - "mypsx", - "mysecuritycamera", - "nhlfan", - "no-ip", - "office-on-the", - "pgafan", - "podzone", - "privatizehealthinsurance", - "rackmaze", - "redirectme", - "ru", - "scrapper-site", - "se", - "selfip", - "sells-it", - "servebbs", - "serveblog", - "serveftp", - "serveminecraft", - "square7", - "static-access", - "sytes", - "t3l3p0rt", - "thruhere", - "twmail", - "uk", - "webhop", - "za", - "r", - "freetls", - "map", - "prod", - "ssl", - "a", - "global", - "a", - "b", - "global", - "map", - "alces", - "arts", - "com", - "firm", - "info", - "net", - "other", - "per", - "rec", - "store", - "web", - "com", - "edu", - "gov", - "i", - "mil", - "mobi", - "name", - "net", - "org", - "sch", - "blogspot", - "ac", - "biz", - "co", - "com", - "edu", - "gob", - "in", - "info", - "int", - "mil", - "net", - "nom", - "org", - "web", - "blogspot", - "bv", - "cistron", - "co", - "demon", - "transurl", - "virtueeldomein", - "aa", - "aarborte", - "aejrie", - "afjord", - "agdenes", - "ah", - "akershus", - "aknoluokta", - "akrehamn", - "al", - "alaheadju", - "alesund", - "algard", - "alstahaug", - "alta", - "alvdal", - "amli", - "amot", - "andasuolo", - "andebu", - "andoy", - "ardal", - "aremark", - "arendal", - "arna", - "aseral", - "asker", - "askim", - "askoy", - "askvoll", - "asnes", - "audnedaln", - "aukra", - "aure", - "aurland", - "aurskog-holand", - "austevoll", - "austrheim", - "averoy", - "badaddja", - "bahcavuotna", - "bahccavuotna", - "baidar", - "bajddar", - "balat", - "balestrand", - "ballangen", - "balsfjord", - "bamble", - "bardu", - "barum", - "batsfjord", - "bearalvahki", - "beardu", - "beiarn", - "berg", - "bergen", - "berlevag", - "bievat", - "bindal", - "birkenes", - "bjarkoy", - "bjerkreim", - "bjugn", - "blogspot", - "bodo", - "bokn", - "bomlo", - "bremanger", - "bronnoy", - "bronnoysund", - "brumunddal", - "bryne", - "bu", - "budejju", - "buskerud", - "bygland", - "bykle", - "cahcesuolo", - "co", - "davvenjarga", - "davvesiida", - "deatnu", - "dep", - "dielddanuorri", - "divtasvuodna", - "divttasvuotna", - "donna", - "dovre", - "drammen", - "drangedal", - "drobak", - "dyroy", - "egersund", - "eid", - "eidfjord", - "eidsberg", - "eidskog", - "eidsvoll", - "eigersund", - "elverum", - "enebakk", - "engerdal", - "etne", - "etnedal", - "evenassi", - "evenes", - "evje-og-hornnes", - "farsund", - "fauske", - "fedje", - "fet", - "fetsund", - "fhs", - "finnoy", - "fitjar", - "fjaler", - "fjell", - "fla", - "flakstad", - "flatanger", - "flekkefjord", - "flesberg", - "flora", - "floro", - "fm", - "folkebibl", - "folldal", - "forde", - "forsand", - "fosnes", - "frana", - "fredrikstad", - "frei", - "frogn", - "froland", - "frosta", - "froya", - "fuoisku", - "fuossko", - "fusa", - "fylkesbibl", - "fyresdal", - "gaivuotna", - "galsa", - "gamvik", - "gangaviika", - "gaular", - "gausdal", - "giehtavuoatna", - "gildeskal", - "giske", - "gjemnes", - "gjerdrum", - "gjerstad", - "gjesdal", - "gjovik", - "gloppen", - "gol", - "gran", - "grane", - "granvin", - "gratangen", - "grimstad", - "grong", - "grue", - "gulen", - "guovdageaidnu", - "ha", - "habmer", - "hadsel", - "hagebostad", - "halden", - "halsa", - "hamar", - "hamaroy", - "hammarfeasta", - "hammerfest", - "hapmir", - "haram", - "hareid", - "harstad", - "hasvik", - "hattfjelldal", - "haugesund", - "hedmark", - "hemne", - "hemnes", - "hemsedal", - "herad", - "hitra", - "hjartdal", - "hjelmeland", - "hl", - "hm", - "hobol", - "hof", - "hokksund", - "hol", - "hole", - "holmestrand", - "holtalen", - "honefoss", - "hordaland", - "hornindal", - "horten", - "hoyanger", - "hoylandet", - "hurdal", - "hurum", - "hvaler", - "hyllestad", - "ibestad", - "idrett", - "inderoy", - "iveland", - "ivgu", - "jan-mayen", - "jessheim", - "jevnaker", - "jolster", - "jondal", - "jorpeland", - "kafjord", - "karasjohka", - "karasjok", - "karlsoy", - "karmoy", - "kautokeino", - "kirkenes", - "klabu", - "klepp", - "kommune", - "kongsberg", - "kongsvinger", - "kopervik", - "kraanghke", - "kragero", - "kristiansand", - "kristiansund", - "krodsherad", - "krokstadelva", - "kvafjord", - "kvalsund", - "kvam", - "kvanangen", - "kvinesdal", - "kvinnherad", - "kviteseid", - "kvitsoy", - "laakesvuemie", - "lahppi", - "langevag", - "lardal", - "larvik", - "lavagis", - "lavangen", - "leangaviika", - "lebesby", - "leikanger", - "leirfjord", - "leirvik", - "leka", - "leksvik", - "lenvik", - "lerdal", - "lesja", - "levanger", - "lier", - "lierne", - "lillehammer", - "lillesand", - "lindas", - "lindesnes", - "loabat", - "lodingen", - "lom", - "loppa", - "lorenskog", - "loten", - "lund", - "lunner", - "luroy", - "luster", - "lyngdal", - "lyngen", - "malatvuopmi", - "malselv", - "malvik", - "mandal", - "marker", - "marnardal", - "masfjorden", - "masoy", - "matta-varjjat", - "meland", - "meldal", - "melhus", - "meloy", - "meraker", - "midsund", - "midtre-gauldal", - "mil", - "mjondalen", - "mo-i-rana", - "moareke", - "modalen", - "modum", - "molde", - "more-og-romsdal", - "mosjoen", - "moskenes", - "moss", - "mosvik", - "mr", - "muosat", - "museum", - "naamesjevuemie", - "namdalseid", - "namsos", - "namsskogan", - "nannestad", - "naroy", - "narviika", - "narvik", - "naustdal", - "navuotna", - "nedre-eiker", - "nesna", - "nesodden", - "nesoddtangen", - "nesseby", - "nesset", - "nissedal", - "nittedal", - "nl", - "nord-aurdal", - "nord-fron", - "nord-odal", - "norddal", - "nordkapp", - "nordland", - "nordre-land", - "nordreisa", - "nore-og-uvdal", - "notodden", - "notteroy", - "nt", - "odda", - "of", - "oksnes", - "ol", - "omasvuotna", - "oppdal", - "oppegard", - "orkanger", - "orkdal", - "orland", - "orskog", - "orsta", - "osen", - "oslo", - "osoyro", - "osteroy", - "ostfold", - "ostre-toten", - "overhalla", - "ovre-eiker", - "oyer", - "oygarden", - "oystre-slidre", - "porsanger", - "porsangu", - "porsgrunn", - "priv", - "rade", - "radoy", - "rahkkeravju", - "raholt", - "raisa", - "rakkestad", - "ralingen", - "rana", - "randaberg", - "rauma", - "rendalen", - "rennebu", - "rennesoy", - "rindal", - "ringebu", - "ringerike", - "ringsaker", - "risor", - "rissa", - "rl", - "roan", - "rodoy", - "rollag", - "romsa", - "romskog", - "roros", - "rost", - "royken", - "royrvik", - "ruovat", - "rygge", - "salangen", - "salat", - "saltdal", - "samnanger", - "sandefjord", - "sandnes", - "sandnessjoen", - "sandoy", - "sarpsborg", - "sauda", - "sauherad", - "sel", - "selbu", - "selje", - "seljord", - "sf", - "siellak", - "sigdal", - "siljan", - "sirdal", - "skanit", - "skanland", - "skaun", - "skedsmo", - "skedsmokorset", - "ski", - "skien", - "skierva", - "skiptvet", - "skjak", - "skjervoy", - "skodje", - "slattum", - "smola", - "snaase", - "snasa", - "snillfjord", - "snoasa", - "sogndal", - "sogne", - "sokndal", - "sola", - "solund", - "somna", - "sondre-land", - "songdalen", - "sor-aurdal", - "sor-fron", - "sor-odal", - "sor-varanger", - "sorfold", - "sorreisa", - "sortland", - "sorum", - "spjelkavik", - "spydeberg", - "st", - "stange", - "stat", - "stathelle", - "stavanger", - "stavern", - "steigen", - "steinkjer", - "stjordal", - "stjordalshalsen", - "stokke", - "stor-elvdal", - "stord", - "stordal", - "storfjord", - "strand", - "stranda", - "stryn", - "sula", - "suldal", - "sund", - "sunndal", - "surnadal", - "svalbard", - "sveio", - "svelvik", - "sykkylven", - "tana", - "tananger", - "telemark", - "time", - "tingvoll", - "tinn", - "tjeldsund", - "tjome", - "tm", - "tokke", - "tolga", - "tonsberg", - "torsken", - "tr", - "trana", - "tranby", - "tranoy", - "troandin", - "trogstad", - "tromsa", - "tromso", - "trondheim", - "trysil", - "tvedestrand", - "tydal", - "tynset", - "tysfjord", - "tysnes", - "tysvar", - "ullensaker", - "ullensvang", - "ulvik", - "unjarga", - "utsira", - "va", - "vaapste", - "vadso", - "vaga", - "vagan", - "vagsoy", - "vaksdal", - "valle", - "vang", - "vanylven", - "vardo", - "varggat", - "varoy", - "vefsn", - "vega", - "vegarshei", - "vennesla", - "verdal", - "verran", - "vestby", - "vestfold", - "vestnes", - "vestre-slidre", - "vestre-toten", - "vestvagoy", - "vevelstad", - "vf", - "vgs", - "vik", - "vikna", - "vindafjord", - "voagat", - "volda", - "voss", - "vossevangen", - "xn--andy-ira", - "xn--asky-ira", - "xn--aurskog-hland-jnb", - "xn--avery-yua", - "xn--bdddj-mrabd", - "xn--bearalvhki-y4a", - "xn--berlevg-jxa", - "xn--bhcavuotna-s4a", - "xn--bhccavuotna-k7a", - "xn--bidr-5nac", - "xn--bievt-0qa", - "xn--bjarky-fya", - "xn--bjddar-pta", - "xn--blt-elab", - "xn--bmlo-gra", - "xn--bod-2na", - "xn--brnny-wuac", - "xn--brnnysund-m8ac", - "xn--brum-voa", - "xn--btsfjord-9za", - "xn--davvenjrga-y4a", - "xn--dnna-gra", - "xn--drbak-wua", - "xn--dyry-ira", - "xn--eveni-0qa01ga", - "xn--finny-yua", - "xn--fjord-lra", - "xn--fl-zia", - "xn--flor-jra", - "xn--frde-gra", - "xn--frna-woa", - "xn--frya-hra", - "xn--ggaviika-8ya47h", - "xn--gildeskl-g0a", - "xn--givuotna-8ya", - "xn--gjvik-wua", - "xn--gls-elac", - "xn--h-2fa", - "xn--hbmer-xqa", - "xn--hcesuolo-7ya35b", - "xn--hgebostad-g3a", - "xn--hmmrfeasta-s4ac", - "xn--hnefoss-q1a", - "xn--hobl-ira", - "xn--holtlen-hxa", - "xn--hpmir-xqa", - "xn--hyanger-q1a", - "xn--hylandet-54a", - "xn--indery-fya", - "xn--jlster-bya", - "xn--jrpeland-54a", - "xn--karmy-yua", - "xn--kfjord-iua", - "xn--klbu-woa", - "xn--koluokta-7ya57h", - "xn--krager-gya", - "xn--kranghke-b0a", - "xn--krdsherad-m8a", - "xn--krehamn-dxa", - "xn--krjohka-hwab49j", - "xn--ksnes-uua", - "xn--kvfjord-nxa", - "xn--kvitsy-fya", - "xn--kvnangen-k0a", - "xn--l-1fa", - "xn--laheadju-7ya", - "xn--langevg-jxa", - "xn--ldingen-q1a", - "xn--leagaviika-52b", - "xn--lesund-hua", - "xn--lgrd-poac", - "xn--lhppi-xqa", - "xn--linds-pra", - "xn--loabt-0qa", - "xn--lrdal-sra", - "xn--lrenskog-54a", - "xn--lt-liac", - "xn--lten-gra", - "xn--lury-ira", - "xn--mely-ira", - "xn--merker-kua", - "xn--mjndalen-64a", - "xn--mlatvuopmi-s4a", - "xn--mli-tla", - "xn--mlselv-iua", - "xn--moreke-jua", - "xn--mosjen-eya", - "xn--mot-tla", - "xn--mre-og-romsdal-qqb", - "xn--msy-ula0h", - "xn--mtta-vrjjat-k7af", - "xn--muost-0qa", - "xn--nmesjevuemie-tcba", - "xn--nry-yla5g", - "xn--nttery-byae", - "xn--nvuotna-hwa", - "xn--oppegrd-ixa", - "xn--ostery-fya", - "xn--osyro-wua", - "xn--porsgu-sta26f", - "xn--rady-ira", - "xn--rdal-poa", - "xn--rde-ula", - "xn--rdy-0nab", - "xn--rennesy-v1a", - "xn--rhkkervju-01af", - "xn--rholt-mra", - "xn--risa-5na", - "xn--risr-ira", - "xn--rland-uua", - "xn--rlingen-mxa", - "xn--rmskog-bya", - "xn--rros-gra", - "xn--rskog-uua", - "xn--rst-0na", - "xn--rsta-fra", - "xn--ryken-vua", - "xn--ryrvik-bya", - "xn--s-1fa", - "xn--sandnessjen-ogb", - "xn--sandy-yua", - "xn--seral-lra", - "xn--sgne-gra", - "xn--skierv-uta", - "xn--skjervy-v1a", - "xn--skjk-soa", - "xn--sknit-yqa", - "xn--sknland-fxa", - "xn--slat-5na", - "xn--slt-elab", - "xn--smla-hra", - "xn--smna-gra", - "xn--snase-nra", - "xn--sndre-land-0cb", - "xn--snes-poa", - "xn--snsa-roa", - "xn--sr-aurdal-l8a", - "xn--sr-fron-q1a", - "xn--sr-odal-q1a", - "xn--sr-varanger-ggb", - "xn--srfold-bya", - "xn--srreisa-q1a", - "xn--srum-gra", - "xn--stfold-9xa", - "xn--stjrdal-s1a", - "xn--stjrdalshalsen-sqb", - "xn--stre-toten-zcb", - "xn--tjme-hra", - "xn--tnsberg-q1a", - "xn--trany-yua", - "xn--trgstad-r1a", - "xn--trna-woa", - "xn--troms-zua", - "xn--tysvr-vra", - "xn--unjrga-rta", - "xn--vads-jra", - "xn--vard-jra", - "xn--vegrshei-c0a", - "xn--vestvgy-ixa6o", - "xn--vg-yiab", - "xn--vgan-qoa", - "xn--vgsy-qoa0j", - "xn--vre-eiker-k8a", - "xn--vrggt-xqad", - "xn--vry-yla5g", - "xn--yer-zna", - "xn--ygarden-p1a", - "xn--ystre-slidre-ujb", - "gs", - "gs", - "nes", - "gs", - "nes", - "gs", - "os", - "valer", - "xn--vler-qoa", - "gs", - "gs", - "os", - "gs", - "heroy", - "sande", - "gs", - "gs", - "bo", - "heroy", - "xn--b-5ga", - "xn--hery-ira", - "gs", - "gs", - "gs", - "gs", - "valer", - "gs", - "gs", - "gs", - "gs", - "bo", - "xn--b-5ga", - "gs", - "gs", - "gs", - "sande", - "gs", - "sande", - "xn--hery-ira", - "xn--vler-qoa", - "biz", - "com", - "edu", - "gov", - "info", - "net", - "org", - "merseine", - "mine", - "nom", - "shacknet", - "ac", - "co", - "cri", - "geek", - "gen", - "govt", - "health", - "iwi", - "kiwi", - "maori", - "mil", - "net", - "nym", - "org", - "parliament", - "school", - "xn--mori-qsa", - "blogspot", - "co", - "com", - "edu", - "gov", - "med", - "museum", - "net", - "org", - "pro", - "homelink", - "barsy", - "accesscam", - "ae", - "amune", - "blogdns", - "blogsite", - "bmoattachments", - "boldlygoingnowhere", - "cable-modem", - "camdvr", - "cdn77", - "cdn77-secure", - "certmgr", - "cloudns", - "collegefan", - "couchpotatofries", - "ddnss", - "diskstation", - "dnsalias", - "dnsdojo", - "doesntexist", - "dontexist", - "doomdns", - "dsmynas", - "duckdns", - "dvrdns", - "dynalias", - "dyndns", - "endofinternet", - "endoftheinternet", - "eu", - "familyds", - "fedorainfracloud", - "fedorapeople", - "fedoraproject", - "freeddns", - "from-me", - "game-host", - "gotdns", - "hepforge", - "hk", - "hobby-site", - "homedns", - "homeftp", - "homelinux", - "homeunix", - "hopto", - "is-a-bruinsfan", - "is-a-candidate", - "is-a-celticsfan", - "is-a-chef", - "is-a-geek", - "is-a-knight", - "is-a-linux-user", - "is-a-patsfan", - "is-a-soxfan", - "is-found", - "is-lost", - "is-saved", - "is-very-bad", - "is-very-evil", - "is-very-good", - "is-very-nice", - "is-very-sweet", - "isa-geek", - "js", - "kicks-ass", - "misconfused", - "mlbfan", - "my-firewall", - "myfirewall", - "myftp", - "mysecuritycamera", - "mywire", - "nflfan", - "no-ip", - "pimienta", - "podzone", - "poivron", - "potager", - "read-books", - "readmyblog", - "selfip", - "sellsyourhome", - "servebbs", - "serveftp", - "servegame", - "spdns", - "stuff-4-sale", - "sweetpepper", - "tunk", - "tuxfamily", - "twmail", - "ufcfan", - "us", - "webhop", - "webredirect", - "wmflabs", - "za", - "zapto", - "tele", - "c", - "rsc", - "origin", - "ssl", - "go", - "home", - "al", - "asso", - "at", - "au", - "be", - "bg", - "ca", - "cd", - "ch", - "cn", - "cy", - "cz", - "de", - "dk", - "edu", - "ee", - "es", - "fi", - "fr", - "gr", - "hr", - "hu", - "ie", - "il", - "in", - "int", - "is", - "it", - "jp", - "kr", - "lt", - "lu", - "lv", - "mc", - "me", - "mk", - "mt", - "my", - "net", - "ng", - "nl", - "no", - "nz", - "paris", - "pl", - "pt", - "q-a", - "ro", - "ru", - "se", - "si", - "sk", - "tr", - "uk", - "us", - "cloud", - "nerdpol", - "abo", - "ac", - "com", - "edu", - "gob", - "ing", - "med", - "net", - "nom", - "org", - "sld", - "ybo", - "blogspot", - "com", - "edu", - "gob", - "mil", - "net", - "nom", - "nym", - "org", - "com", - "edu", - "org", - "com", - "edu", - "gov", - "i", - "mil", - "net", - "ngo", - "org", - "1337", - "biz", - "com", - "edu", - "fam", - "gob", - "gok", - "gon", - "gop", - "gos", - "gov", - "info", - "net", - "org", - "web", - "agro", - "aid", - "art", - "atm", - "augustow", - "auto", - "babia-gora", - "bedzin", - "beep", - "beskidy", - "bialowieza", - "bialystok", - "bielawa", - "bieszczady", - "biz", - "boleslawiec", - "bydgoszcz", - "bytom", - "cieszyn", - "co", - "com", - "czeladz", - "czest", - "dlugoleka", - "edu", - "elblag", - "elk", - "gda", - "gdansk", - "gdynia", - "gliwice", - "glogow", - "gmina", - "gniezno", - "gorlice", - "gov", - "grajewo", - "gsm", - "ilawa", - "info", - "jaworzno", - "jelenia-gora", - "jgora", - "kalisz", - "karpacz", - "kartuzy", - "kaszuby", - "katowice", - "kazimierz-dolny", - "kepno", - "ketrzyn", - "klodzko", - "kobierzyce", - "kolobrzeg", - "konin", - "konskowola", - "krakow", - "kutno", - "lapy", - "lebork", - "legnica", - "lezajsk", - "limanowa", - "lomza", - "lowicz", - "lubin", - "lukow", - "mail", - "malbork", - "malopolska", - "mazowsze", - "mazury", - "med", - "media", - "miasta", - "mielec", - "mielno", - "mil", - "mragowo", - "naklo", - "net", - "nieruchomosci", - "nom", - "nowaruda", - "nysa", - "olawa", - "olecko", - "olkusz", - "olsztyn", - "opoczno", - "opole", - "org", - "ostroda", - "ostroleka", - "ostrowiec", - "ostrowwlkp", - "pc", - "pila", - "pisz", - "podhale", - "podlasie", - "polkowice", - "pomorskie", - "pomorze", - "powiat", - "poznan", - "priv", - "prochowice", - "pruszkow", - "przeworsk", - "pulawy", - "radom", - "rawa-maz", - "realestate", - "rel", - "rybnik", - "rzeszow", - "sanok", - "sejny", - "sex", - "shop", - "sklep", - "skoczow", - "slask", - "slupsk", - "sopot", - "sos", - "sosnowiec", - "stalowa-wola", - "starachowice", - "stargard", - "suwalki", - "swidnica", - "swiebodzin", - "swinoujscie", - "szczecin", - "szczytno", - "szkola", - "targi", - "tarnobrzeg", - "tgory", - "tm", - "tourism", - "travel", - "turek", - "turystyka", - "tychy", - "ustka", - "walbrzych", - "warmia", - "warszawa", - "waw", - "wegrow", - "wielun", - "wlocl", - "wloclawek", - "wodzislaw", - "wolomin", - "wroc", - "wroclaw", - "zachpomor", - "zagan", - "zakopane", - "zarow", - "zgora", - "zgorzelec", - "ap", - "griw", - "ic", - "is", - "kmpsp", - "konsulat", - "kppsp", - "kwp", - "kwpsp", - "mup", - "mw", - "oirm", - "oum", - "pa", - "pinb", - "piw", - "po", - "psp", - "psse", - "pup", - "rzgw", - "sa", - "sdn", - "sko", - "so", - "sr", - "starostwo", - "ug", - "ugim", - "um", - "umig", - "upow", - "uppo", - "us", - "uw", - "uzs", - "wif", - "wiih", - "winb", - "wios", - "witd", - "wiw", - "wsa", - "wskr", - "wuoz", - "wzmiuw", - "zp", - "co", - "edu", - "gov", - "net", - "org", - "ac", - "biz", - "com", - "edu", - "est", - "gov", - "info", - "isla", - "name", - "net", - "org", - "pro", - "prof", - "aaa", - "aca", - "acct", - "avocat", - "bar", - "cloudns", - "cpa", - "eng", - "jur", - "law", - "med", - "recht", - "com", - "edu", - "gov", - "net", - "org", - "plo", - "sec", - "blogspot", - "com", - "edu", - "gov", - "int", - "net", - "nome", - "nym", - "org", - "publ", - "belau", - "cloudns", - "co", - "ed", - "go", - "ne", - "nom", - "or", - "com", - "coop", - "edu", - "gov", - "mil", - "net", - "org", - "blogspot", - "com", - "edu", - "gov", - "mil", - "name", - "net", - "nom", - "org", - "sch", - "asso", - "blogspot", - "com", - "nom", - "ybo", - "clan", - "arts", - "blogspot", - "com", - "firm", - "info", - "nom", - "nt", - "org", - "rec", - "shop", - "store", - "tm", - "www", - "lima-city", - "myddns", - "webspace", - "ac", - "blogspot", - "co", - "edu", - "gov", - "in", - "nom", - "org", - "ac", - "adygeya", - "bashkiria", - "bir", - "blogspot", - "cbg", - "cldmail", - "com", - "dagestan", - "edu", - "gov", - "grozny", - "int", - "kalmykia", - "kustanai", - "marine", - "mil", - "mordovia", - "msk", - "mytis", - "nalchik", - "net", - "nov", - "org", - "pp", - "pyatigorsk", - "spb", - "test", - "vladikavkaz", - "vladimir", - "hb", - "ac", - "co", - "com", - "edu", - "gouv", - "gov", - "int", - "mil", - "net", - "com", - "edu", - "gov", - "med", - "net", - "org", - "pub", - "sch", - "com", - "edu", - "gov", - "net", - "org", - "com", - "edu", - "gov", - "net", - "org", - "ybo", - "com", - "edu", - "gov", - "info", - "med", - "net", - "org", - "tv", - "a", - "ac", - "b", - "bd", - "blogspot", - "brand", - "c", - "com", - "d", - "e", - "f", - "fh", - "fhsk", - "fhv", - "g", - "h", - "i", - "k", - "komforb", - "kommunalforbund", - "komvux", - "l", - "lanbib", - "m", - "n", - "naturbruksgymn", - "o", - "org", - "p", - "parti", - "pp", - "press", - "r", - "s", - "t", - "tm", - "u", - "w", - "x", - "y", - "z", - "blogspot", - "com", - "edu", - "gov", - "net", - "org", - "per", - "com", - "gov", - "hashbang", - "mil", - "net", - "now", - "org", - "platform", - "wedeploy", - "blogspot", - "nom", - "byen", - "cyon", - "platformsh", - "blogspot", - "nym", - "com", - "edu", - "gov", - "net", - "org", - "art", - "blogspot", - "com", - "edu", - "gouv", - "org", - "perso", - "univ", - "com", - "net", - "org", - "stackspace", - "uber", - "xs4all", - "co", - "com", - "consulado", - "edu", - "embaixada", - "gov", - "mil", - "net", - "org", - "principe", - "saotome", - "store", - "abkhazia", - "adygeya", - "aktyubinsk", - "arkhangelsk", - "armenia", - "ashgabad", - "azerbaijan", - "balashov", - "bashkiria", - "bryansk", - "bukhara", - "chimkent", - "dagestan", - "east-kazakhstan", - "exnet", - "georgia", - "grozny", - "ivanovo", - "jambyl", - "kalmykia", - "kaluga", - "karacol", - "karaganda", - "karelia", - "khakassia", - "krasnodar", - "kurgan", - "kustanai", - "lenug", - "mangyshlak", - "mordovia", - "msk", - "murmansk", - "nalchik", - "navoi", - "north-kazakhstan", - "nov", - "nym", - "obninsk", - "penza", - "pokrovsk", - "sochi", - "spb", - "tashkent", - "termez", - "togliatti", - "troitsk", - "tselinograd", - "tula", - "tuva", - "vladikavkaz", - "vladimir", - "vologda", - "barsy", - "com", - "edu", - "gob", - "org", - "red", - "gov", - "nym", - "com", - "edu", - "gov", - "mil", - "net", - "org", - "knightpoint", - "ac", - "co", - "org", - "blogspot", - "ac", - "co", - "go", - "in", - "mi", - "net", - "or", - "ac", - "biz", - "co", - "com", - "edu", - "go", - "gov", - "int", - "mil", - "name", - "net", - "nic", - "org", - "test", - "web", - "gov", - "co", - "com", - "edu", - "gov", - "mil", - "net", - "nom", - "org", - "agrinet", - "com", - "defense", - "edunet", - "ens", - "fin", - "gov", - "ind", - "info", - "intl", - "mincom", - "nat", - "net", - "org", - "perso", - "rnrt", - "rns", - "rnu", - "tourism", - "turen", - "com", - "edu", - "gov", - "mil", - "net", - "org", - "vpnplus", - "av", - "bbs", - "bel", - "biz", - "com", - "dr", - "edu", - "gen", - "gov", - "info", - "k12", - "kep", - "mil", - "name", - "nc", - "net", - "org", - "pol", - "tel", - "tv", - "web", - "blogspot", - "gov", - "ybo", - "aero", - "biz", - "co", - "com", - "coop", - "edu", - "gov", - "info", - "int", - "jobs", - "mobi", - "museum", - "name", - "net", - "org", - "pro", - "travel", - "better-than", - "dyndns", - "on-the-web", - "worse-than", - "blogspot", - "club", - "com", - "ebiz", - "edu", - "game", - "gov", - "idv", - "mil", - "net", - "nym", - "org", - "url", - "xn--czrw28b", - "xn--uc0atv", - "xn--zf0ao64a", - "mymailer", - "ac", - "co", - "go", - "hotel", - "info", - "me", - "mil", - "mobi", - "ne", - "or", - "sc", - "tv", - "biz", - "cc", - "cherkassy", - "cherkasy", - "chernigov", - "chernihiv", - "chernivtsi", - "chernovtsy", - "ck", - "cn", - "co", - "com", - "cr", - "crimea", - "cv", - "dn", - "dnepropetrovsk", - "dnipropetrovsk", - "dominic", - "donetsk", - "dp", - "edu", - "gov", - "if", - "in", - "inf", - "ivano-frankivsk", - "kh", - "kharkiv", - "kharkov", - "kherson", - "khmelnitskiy", - "khmelnytskyi", - "kiev", - "kirovograd", - "km", - "kr", - "krym", - "ks", - "kv", - "kyiv", - "lg", - "lt", - "ltd", - "lugansk", - "lutsk", - "lv", - "lviv", - "mk", - "mykolaiv", - "net", - "nikolaev", - "od", - "odesa", - "odessa", - "org", - "pl", - "poltava", - "pp", - "rivne", - "rovno", - "rv", - "sb", - "sebastopol", - "sevastopol", - "sm", - "sumy", - "te", - "ternopil", - "uz", - "uzhgorod", - "vinnica", - "vinnytsia", - "vn", - "volyn", - "yalta", - "zaporizhzhe", - "zaporizhzhia", - "zhitomir", - "zhytomyr", - "zp", - "zt", - "ac", - "blogspot", - "co", - "com", - "go", - "ne", - "nom", - "or", - "org", - "sc", - "ac", - "co", - "gov", - "ltd", - "me", - "net", - "nhs", - "org", - "plc", - "police", - "sch", - "blogspot", - "no-ip", - "wellbeingzone", - "homeoffice", - "service", - "ak", - "al", - "ar", - "as", - "az", - "ca", - "cloudns", - "co", - "ct", - "dc", - "de", - "dni", - "drud", - "fed", - "fl", - "ga", - "golffan", - "gu", - "hi", - "ia", - "id", - "il", - "in", - "is-by", - "isa", - "kids", - "ks", - "ky", - "la", - "land-4-sale", - "ma", - "md", - "me", - "mi", - "mn", - "mo", - "ms", - "mt", - "nc", - "nd", - "ne", - "nh", - "nj", - "nm", - "noip", - "nsn", - "nv", - "ny", - "oh", - "ok", - "or", - "pa", - "pointto", - "pr", - "ri", - "sc", - "sd", - "stuff-4-sale", - "tn", - "tx", - "ut", - "va", - "vi", - "vt", - "wa", - "wi", - "wv", - "wy", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "chtr", - "paroch", - "pvt", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "ann-arbor", - "cc", - "cog", - "dst", - "eaton", - "gen", - "k12", - "lib", - "mus", - "tec", - "washtenaw", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "k12", - "lib", - "cc", - "cc", - "k12", - "lib", - "com", - "edu", - "gub", - "mil", - "net", - "nom", - "org", - "blogspot", - "co", - "com", - "net", - "org", - "com", - "edu", - "gov", - "mil", - "net", - "nom", - "org", - "arts", - "co", - "com", - "e12", - "edu", - "firm", - "gob", - "gov", - "info", - "int", - "mil", - "net", - "org", - "rec", - "store", - "tec", - "web", - "nom", - "co", - "com", - "k12", - "net", - "org", - "ac", - "biz", - "blogspot", - "com", - "edu", - "gov", - "health", - "info", - "int", - "name", - "net", - "org", - "pro", - "com", - "edu", - "net", - "org", - "advisor", - "com", - "dyndns", - "edu", - "gov", - "mypets", - "net", - "org", - "xn--80au", - "xn--90azh", - "xn--c1avg", - "xn--d1at", - "xn--o1ac", - "xn--o1ach", - "xn--12c1fe0br", - "xn--12cfi8ixb8l", - "xn--12co0c3b4eva", - "xn--h3cuzk1di", - "xn--m3ch0j3a", - "xn--o3cyx2a", - "blogsite", - "fhapp", - "ac", - "agric", - "alt", - "co", - "edu", - "gov", - "grondar", - "law", - "mil", - "net", - "ngo", - "nis", - "nom", - "org", - "school", - "tm", - "web", - "blogspot", - "ac", - "biz", - "co", - "com", - "edu", - "gov", - "info", - "mil", - "net", - "org", - "sch", - "lima", - "triton", - "ac", - "co", - "gov", - "mil", - "org", -} diff --git a/vendor/golang.org/x/net/trace/histogram_test.go b/vendor/golang.org/x/net/trace/histogram_test.go deleted file mode 100644 index d384b9332d..0000000000 --- a/vendor/golang.org/x/net/trace/histogram_test.go +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright 2015 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 trace - -import ( - "math" - "testing" -) - -type sumTest struct { - value int64 - sum int64 - sumOfSquares float64 - total int64 -} - -var sumTests = []sumTest{ - {100, 100, 10000, 1}, - {50, 150, 12500, 2}, - {50, 200, 15000, 3}, - {50, 250, 17500, 4}, -} - -type bucketingTest struct { - in int64 - log int - bucket int -} - -var bucketingTests = []bucketingTest{ - {0, 0, 0}, - {1, 1, 0}, - {2, 2, 1}, - {3, 2, 1}, - {4, 3, 2}, - {1000, 10, 9}, - {1023, 10, 9}, - {1024, 11, 10}, - {1000000, 20, 19}, -} - -type multiplyTest struct { - in int64 - ratio float64 - expectedSum int64 - expectedTotal int64 - expectedSumOfSquares float64 -} - -var multiplyTests = []multiplyTest{ - {15, 2.5, 37, 2, 562.5}, - {128, 4.6, 758, 13, 77953.9}, -} - -type percentileTest struct { - fraction float64 - expected int64 -} - -var percentileTests = []percentileTest{ - {0.25, 48}, - {0.5, 96}, - {0.6, 109}, - {0.75, 128}, - {0.90, 205}, - {0.95, 230}, - {0.99, 256}, -} - -func TestSum(t *testing.T) { - var h histogram - - for _, test := range sumTests { - h.addMeasurement(test.value) - sum := h.sum - if sum != test.sum { - t.Errorf("h.Sum = %v WANT: %v", sum, test.sum) - } - - sumOfSquares := h.sumOfSquares - if sumOfSquares != test.sumOfSquares { - t.Errorf("h.SumOfSquares = %v WANT: %v", sumOfSquares, test.sumOfSquares) - } - - total := h.total() - if total != test.total { - t.Errorf("h.Total = %v WANT: %v", total, test.total) - } - } -} - -func TestMultiply(t *testing.T) { - var h histogram - for i, test := range multiplyTests { - h.addMeasurement(test.in) - h.Multiply(test.ratio) - if h.sum != test.expectedSum { - t.Errorf("#%v: h.sum = %v WANT: %v", i, h.sum, test.expectedSum) - } - if h.total() != test.expectedTotal { - t.Errorf("#%v: h.total = %v WANT: %v", i, h.total(), test.expectedTotal) - } - if h.sumOfSquares != test.expectedSumOfSquares { - t.Errorf("#%v: h.SumOfSquares = %v WANT: %v", i, test.expectedSumOfSquares, h.sumOfSquares) - } - } -} - -func TestBucketingFunctions(t *testing.T) { - for _, test := range bucketingTests { - log := log2(test.in) - if log != test.log { - t.Errorf("log2 = %v WANT: %v", log, test.log) - } - - bucket := getBucket(test.in) - if bucket != test.bucket { - t.Errorf("getBucket = %v WANT: %v", bucket, test.bucket) - } - } -} - -func TestAverage(t *testing.T) { - a := new(histogram) - average := a.average() - if average != 0 { - t.Errorf("Average of empty histogram was %v WANT: 0", average) - } - - a.addMeasurement(1) - a.addMeasurement(1) - a.addMeasurement(3) - const expected = float64(5) / float64(3) - average = a.average() - - if !isApproximate(average, expected) { - t.Errorf("Average = %g WANT: %v", average, expected) - } -} - -func TestStandardDeviation(t *testing.T) { - a := new(histogram) - add(a, 10, 1<<4) - add(a, 10, 1<<5) - add(a, 10, 1<<6) - stdDev := a.standardDeviation() - const expected = 19.95 - - if !isApproximate(stdDev, expected) { - t.Errorf("StandardDeviation = %v WANT: %v", stdDev, expected) - } - - // No values - a = new(histogram) - stdDev = a.standardDeviation() - - if !isApproximate(stdDev, 0) { - t.Errorf("StandardDeviation = %v WANT: 0", stdDev) - } - - add(a, 1, 1<<4) - if !isApproximate(stdDev, 0) { - t.Errorf("StandardDeviation = %v WANT: 0", stdDev) - } - - add(a, 10, 1<<4) - if !isApproximate(stdDev, 0) { - t.Errorf("StandardDeviation = %v WANT: 0", stdDev) - } -} - -func TestPercentileBoundary(t *testing.T) { - a := new(histogram) - add(a, 5, 1<<4) - add(a, 10, 1<<6) - add(a, 5, 1<<7) - - for _, test := range percentileTests { - percentile := a.percentileBoundary(test.fraction) - if percentile != test.expected { - t.Errorf("h.PercentileBoundary (fraction=%v) = %v WANT: %v", test.fraction, percentile, test.expected) - } - } -} - -func TestCopyFrom(t *testing.T) { - a := histogram{5, 25, []int64{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, 33, 34, 35, 36, 37, 38}, 4, -1} - b := histogram{6, 36, []int64{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, 33, 34, 35, 36, 37, 38, 39}, 5, -1} - - a.CopyFrom(&b) - - if a.String() != b.String() { - t.Errorf("a.String = %s WANT: %s", a.String(), b.String()) - } -} - -func TestClear(t *testing.T) { - a := histogram{5, 25, []int64{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, 33, 34, 35, 36, 37, 38}, 4, -1} - - a.Clear() - - expected := "0, 0.000000, 0, 0, []" - if a.String() != expected { - t.Errorf("a.String = %s WANT %s", a.String(), expected) - } -} - -func TestNew(t *testing.T) { - a := histogram{5, 25, []int64{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, 33, 34, 35, 36, 37, 38}, 4, -1} - b := a.New() - - expected := "0, 0.000000, 0, 0, []" - if b.(*histogram).String() != expected { - t.Errorf("b.(*histogram).String = %s WANT: %s", b.(*histogram).String(), expected) - } -} - -func TestAdd(t *testing.T) { - // The tests here depend on the associativity of addMeasurement and Add. - // Add empty observation - a := histogram{5, 25, []int64{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, 33, 34, 35, 36, 37, 38}, 4, -1} - b := a.New() - - expected := a.String() - a.Add(b) - if a.String() != expected { - t.Errorf("a.String = %s WANT: %s", a.String(), expected) - } - - // Add same bucketed value, no new buckets - c := new(histogram) - d := new(histogram) - e := new(histogram) - c.addMeasurement(12) - d.addMeasurement(11) - e.addMeasurement(12) - e.addMeasurement(11) - c.Add(d) - if c.String() != e.String() { - t.Errorf("c.String = %s WANT: %s", c.String(), e.String()) - } - - // Add bucketed values - f := new(histogram) - g := new(histogram) - h := new(histogram) - f.addMeasurement(4) - f.addMeasurement(12) - f.addMeasurement(100) - g.addMeasurement(18) - g.addMeasurement(36) - g.addMeasurement(255) - h.addMeasurement(4) - h.addMeasurement(12) - h.addMeasurement(100) - h.addMeasurement(18) - h.addMeasurement(36) - h.addMeasurement(255) - f.Add(g) - if f.String() != h.String() { - t.Errorf("f.String = %q WANT: %q", f.String(), h.String()) - } - - // add buckets to no buckets - i := new(histogram) - j := new(histogram) - k := new(histogram) - j.addMeasurement(18) - j.addMeasurement(36) - j.addMeasurement(255) - k.addMeasurement(18) - k.addMeasurement(36) - k.addMeasurement(255) - i.Add(j) - if i.String() != k.String() { - t.Errorf("i.String = %q WANT: %q", i.String(), k.String()) - } - - // add buckets to single value (no overlap) - l := new(histogram) - m := new(histogram) - n := new(histogram) - l.addMeasurement(0) - m.addMeasurement(18) - m.addMeasurement(36) - m.addMeasurement(255) - n.addMeasurement(0) - n.addMeasurement(18) - n.addMeasurement(36) - n.addMeasurement(255) - l.Add(m) - if l.String() != n.String() { - t.Errorf("l.String = %q WANT: %q", l.String(), n.String()) - } - - // mixed order - o := new(histogram) - p := new(histogram) - o.addMeasurement(0) - o.addMeasurement(2) - o.addMeasurement(0) - p.addMeasurement(0) - p.addMeasurement(0) - p.addMeasurement(2) - if o.String() != p.String() { - t.Errorf("o.String = %q WANT: %q", o.String(), p.String()) - } -} - -func add(h *histogram, times int, val int64) { - for i := 0; i < times; i++ { - h.addMeasurement(val) - } -} - -func isApproximate(x, y float64) bool { - return math.Abs(x-y) < 1e-2 -} diff --git a/vendor/golang.org/x/net/trace/trace.go b/vendor/golang.org/x/net/trace/trace.go index bb72a527e8..a46ee0eaa3 100644 --- a/vendor/golang.org/x/net/trace/trace.go +++ b/vendor/golang.org/x/net/trace/trace.go @@ -368,7 +368,11 @@ func New(family, title string) Trace { } func (tr *trace) Finish() { - tr.Elapsed = time.Now().Sub(tr.Start) + elapsed := time.Now().Sub(tr.Start) + tr.mu.Lock() + tr.Elapsed = elapsed + tr.mu.Unlock() + if DebugUseAfterFinish { buf := make([]byte, 4<<10) // 4 KB should be enough n := runtime.Stack(buf, false) @@ -381,14 +385,17 @@ func (tr *trace) Finish() { m.Remove(tr) f := getFamily(tr.Family, true) + tr.mu.RLock() // protects tr fields in Cond.match calls for _, b := range f.Buckets { if b.Cond.match(tr) { b.Add(tr) } } + tr.mu.RUnlock() + // Add a sample of elapsed time as microseconds to the family's timeseries h := new(histogram) - h.addMeasurement(tr.Elapsed.Nanoseconds() / 1e3) + h.addMeasurement(elapsed.Nanoseconds() / 1e3) f.LatencyMu.Lock() f.Latency.Add(h) f.LatencyMu.Unlock() @@ -684,25 +691,20 @@ type trace struct { // Title is the title of this trace. Title string - // Timing information. - Start time.Time - Elapsed time.Duration // zero while active - - // Trace information if non-zero. - traceID uint64 - spanID uint64 - - // Whether this trace resulted in an error. - IsError bool + // Start time of the this trace. + Start time.Time - // Append-only sequence of events (modulo discards). mu sync.RWMutex - events []event + events []event // Append-only sequence of events (modulo discards). maxEvents int + recycler func(interface{}) + IsError bool // Whether this trace resulted in an error. + Elapsed time.Duration // Elapsed time for this trace, zero while active. + traceID uint64 // Trace information if non-zero. + spanID uint64 - refs int32 // how many buckets this is in - recycler func(interface{}) - disc discarded // scratch space to avoid allocation + refs int32 // how many buckets this is in + disc discarded // scratch space to avoid allocation finishStack []byte // where finish was called, if DebugUseAfterFinish is set @@ -714,14 +716,18 @@ func (tr *trace) reset() { tr.Family = "" tr.Title = "" tr.Start = time.Time{} + + tr.mu.Lock() tr.Elapsed = 0 tr.traceID = 0 tr.spanID = 0 tr.IsError = false tr.maxEvents = 0 tr.events = nil - tr.refs = 0 tr.recycler = nil + tr.mu.Unlock() + + tr.refs = 0 tr.disc = 0 tr.finishStack = nil for i := range tr.eventsBuf { @@ -801,21 +807,31 @@ func (tr *trace) LazyPrintf(format string, a ...interface{}) { tr.addEvent(&lazySprintf{format, a}, false, false) } -func (tr *trace) SetError() { tr.IsError = true } +func (tr *trace) SetError() { + tr.mu.Lock() + tr.IsError = true + tr.mu.Unlock() +} func (tr *trace) SetRecycler(f func(interface{})) { + tr.mu.Lock() tr.recycler = f + tr.mu.Unlock() } func (tr *trace) SetTraceInfo(traceID, spanID uint64) { + tr.mu.Lock() tr.traceID, tr.spanID = traceID, spanID + tr.mu.Unlock() } func (tr *trace) SetMaxEvents(m int) { + tr.mu.Lock() // Always keep at least three events: first, discarded count, last. if len(tr.events) == 0 && m > 3 { tr.maxEvents = m } + tr.mu.Unlock() } func (tr *trace) ref() { @@ -824,6 +840,7 @@ func (tr *trace) ref() { func (tr *trace) unref() { if atomic.AddInt32(&tr.refs, -1) == 0 { + tr.mu.RLock() if tr.recycler != nil { // freeTrace clears tr, so we hold tr.recycler and tr.events here. go func(f func(interface{}), es []event) { @@ -834,6 +851,7 @@ func (tr *trace) unref() { } }(tr.recycler, tr.events) } + tr.mu.RUnlock() freeTrace(tr) } @@ -844,7 +862,10 @@ func (tr *trace) When() string { } func (tr *trace) ElapsedTime() string { + tr.mu.RLock() t := tr.Elapsed + tr.mu.RUnlock() + if t == 0 { // Active trace. t = time.Since(tr.Start) diff --git a/vendor/golang.org/x/net/trace/trace_test.go b/vendor/golang.org/x/net/trace/trace_test.go deleted file mode 100644 index bfd9dfe947..0000000000 --- a/vendor/golang.org/x/net/trace/trace_test.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2015 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 trace - -import ( - "net/http" - "reflect" - "testing" -) - -type s struct{} - -func (s) String() string { return "lazy string" } - -// TestReset checks whether all the fields are zeroed after reset. -func TestReset(t *testing.T) { - tr := New("foo", "bar") - tr.LazyLog(s{}, false) - tr.LazyPrintf("%d", 1) - tr.SetRecycler(func(_ interface{}) {}) - tr.SetTraceInfo(3, 4) - tr.SetMaxEvents(100) - tr.SetError() - tr.Finish() - - tr.(*trace).reset() - - if !reflect.DeepEqual(tr, new(trace)) { - t.Errorf("reset didn't clear all fields: %+v", tr) - } -} - -// TestResetLog checks whether all the fields are zeroed after reset. -func TestResetLog(t *testing.T) { - el := NewEventLog("foo", "bar") - el.Printf("message") - el.Errorf("error") - el.Finish() - - el.(*eventLog).reset() - - if !reflect.DeepEqual(el, new(eventLog)) { - t.Errorf("reset didn't clear all fields: %+v", el) - } -} - -func TestAuthRequest(t *testing.T) { - testCases := []struct { - host string - want bool - }{ - {host: "192.168.23.1", want: false}, - {host: "192.168.23.1:8080", want: false}, - {host: "malformed remote addr", want: false}, - {host: "localhost", want: true}, - {host: "localhost:8080", want: true}, - {host: "127.0.0.1", want: true}, - {host: "127.0.0.1:8080", want: true}, - {host: "::1", want: true}, - {host: "[::1]:8080", want: true}, - } - for _, tt := range testCases { - req := &http.Request{RemoteAddr: tt.host} - any, sensitive := AuthRequest(req) - if any != tt.want || sensitive != tt.want { - t.Errorf("AuthRequest(%q) = %t, %t; want %t, %t", tt.host, any, sensitive, tt.want, tt.want) - } - } -} - -// TestParseTemplate checks that all templates used by this package are valid -// as they are parsed on first usage -func TestParseTemplate(t *testing.T) { - if tmpl := distTmpl(); tmpl == nil { - t.Error("invalid template returned from distTmpl()") - } - if tmpl := pageTmpl(); tmpl == nil { - t.Error("invalid template returned from pageTmpl()") - } - if tmpl := eventsTmpl(); tmpl == nil { - t.Error("invalid template returned from eventsTmpl()") - } -} - -func benchmarkTrace(b *testing.B, maxEvents, numEvents int) { - numSpans := (b.N + numEvents + 1) / numEvents - - for i := 0; i < numSpans; i++ { - tr := New("test", "test") - tr.SetMaxEvents(maxEvents) - for j := 0; j < numEvents; j++ { - tr.LazyPrintf("%d", j) - } - tr.Finish() - } -} - -func BenchmarkTrace_Default_2(b *testing.B) { - benchmarkTrace(b, 0, 2) -} - -func BenchmarkTrace_Default_10(b *testing.B) { - benchmarkTrace(b, 0, 10) -} - -func BenchmarkTrace_Default_100(b *testing.B) { - benchmarkTrace(b, 0, 100) -} - -func BenchmarkTrace_Default_1000(b *testing.B) { - benchmarkTrace(b, 0, 1000) -} - -func BenchmarkTrace_Default_10000(b *testing.B) { - benchmarkTrace(b, 0, 10000) -} - -func BenchmarkTrace_10_2(b *testing.B) { - benchmarkTrace(b, 10, 2) -} - -func BenchmarkTrace_10_10(b *testing.B) { - benchmarkTrace(b, 10, 10) -} - -func BenchmarkTrace_10_100(b *testing.B) { - benchmarkTrace(b, 10, 100) -} - -func BenchmarkTrace_10_1000(b *testing.B) { - benchmarkTrace(b, 10, 1000) -} - -func BenchmarkTrace_10_10000(b *testing.B) { - benchmarkTrace(b, 10, 10000) -} - -func BenchmarkTrace_100_2(b *testing.B) { - benchmarkTrace(b, 100, 2) -} - -func BenchmarkTrace_100_10(b *testing.B) { - benchmarkTrace(b, 100, 10) -} - -func BenchmarkTrace_100_100(b *testing.B) { - benchmarkTrace(b, 100, 100) -} - -func BenchmarkTrace_100_1000(b *testing.B) { - benchmarkTrace(b, 100, 1000) -} - -func BenchmarkTrace_100_10000(b *testing.B) { - benchmarkTrace(b, 100, 10000) -} - -func BenchmarkTrace_1000_2(b *testing.B) { - benchmarkTrace(b, 1000, 2) -} - -func BenchmarkTrace_1000_10(b *testing.B) { - benchmarkTrace(b, 1000, 10) -} - -func BenchmarkTrace_1000_100(b *testing.B) { - benchmarkTrace(b, 1000, 100) -} - -func BenchmarkTrace_1000_1000(b *testing.B) { - benchmarkTrace(b, 1000, 1000) -} - -func BenchmarkTrace_1000_10000(b *testing.B) { - benchmarkTrace(b, 1000, 10000) -} diff --git a/vendor/golang.org/x/oauth2/CONTRIBUTING.md b/vendor/golang.org/x/oauth2/CONTRIBUTING.md index 46aa2b12dd..dfbed62cf5 100644 --- a/vendor/golang.org/x/oauth2/CONTRIBUTING.md +++ b/vendor/golang.org/x/oauth2/CONTRIBUTING.md @@ -4,16 +4,15 @@ Go is an open source project. It is the work of hundreds of contributors. We appreciate your help! - ## Filing issues When [filing an issue](https://github.com/golang/oauth2/issues), make sure to answer these five questions: -1. What version of Go are you using (`go version`)? -2. What operating system and processor architecture are you using? -3. What did you do? -4. What did you expect to see? -5. What did you see instead? +1. What version of Go are you using (`go version`)? +2. What operating system and processor architecture are you using? +3. What did you do? +4. What did you expect to see? +5. What did you see instead? General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. The gophers there will answer or ask you to file an issue if you've tripped over a bug. @@ -23,9 +22,5 @@ The gophers there will answer or ask you to file an issue if you've tripped over Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) before sending patches. -**We do not accept GitHub pull requests** -(we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). - Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file. - diff --git a/vendor/golang.org/x/oauth2/client_appengine.go b/vendor/golang.org/x/oauth2/client_appengine.go deleted file mode 100644 index 8962c49d1d..0000000000 --- a/vendor/golang.org/x/oauth2/client_appengine.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2014 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 appengine - -// App Engine hooks. - -package oauth2 - -import ( - "net/http" - - "golang.org/x/net/context" - "golang.org/x/oauth2/internal" - "google.golang.org/appengine/urlfetch" -) - -func init() { - internal.RegisterContextClientFunc(contextClientAppEngine) -} - -func contextClientAppEngine(ctx context.Context) (*http.Client, error) { - return urlfetch.Client(ctx), nil -} diff --git a/vendor/golang.org/x/oauth2/example_test.go b/vendor/golang.org/x/oauth2/example_test.go deleted file mode 100644 index fc2f793b26..0000000000 --- a/vendor/golang.org/x/oauth2/example_test.go +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright 2014 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 oauth2_test - -import ( - "context" - "fmt" - "log" - "net/http" - "time" - - "golang.org/x/oauth2" -) - -func ExampleConfig() { - ctx := context.Background() - conf := &oauth2.Config{ - ClientID: "YOUR_CLIENT_ID", - ClientSecret: "YOUR_CLIENT_SECRET", - Scopes: []string{"SCOPE1", "SCOPE2"}, - Endpoint: oauth2.Endpoint{ - AuthURL: "https://provider.com/o/oauth2/auth", - TokenURL: "https://provider.com/o/oauth2/token", - }, - } - - // Redirect user to consent page to ask for permission - // for the scopes specified above. - url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline) - fmt.Printf("Visit the URL for the auth dialog: %v", url) - - // Use the authorization code that is pushed to the redirect - // URL. Exchange will do the handshake to retrieve the - // initial access token. The HTTP Client returned by - // conf.Client will refresh the token as necessary. - var code string - if _, err := fmt.Scan(&code); err != nil { - log.Fatal(err) - } - tok, err := conf.Exchange(ctx, code) - if err != nil { - log.Fatal(err) - } - - client := conf.Client(ctx, tok) - client.Get("...") -} - -func ExampleConfig_customHTTP() { - ctx := context.Background() - - conf := &oauth2.Config{ - ClientID: "YOUR_CLIENT_ID", - ClientSecret: "YOUR_CLIENT_SECRET", - Scopes: []string{"SCOPE1", "SCOPE2"}, - Endpoint: oauth2.Endpoint{ - TokenURL: "https://provider.com/o/oauth2/token", - AuthURL: "https://provider.com/o/oauth2/auth", - }, - } - - // Redirect user to consent page to ask for permission - // for the scopes specified above. - url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline) - fmt.Printf("Visit the URL for the auth dialog: %v", url) - - // Use the authorization code that is pushed to the redirect - // URL. Exchange will do the handshake to retrieve the - // initial access token. The HTTP Client returned by - // conf.Client will refresh the token as necessary. - var code string - if _, err := fmt.Scan(&code); err != nil { - log.Fatal(err) - } - - // Use the custom HTTP client when requesting a token. - httpClient := &http.Client{Timeout: 2 * time.Second} - ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) - - tok, err := conf.Exchange(ctx, code) - if err != nil { - log.Fatal(err) - } - - client := conf.Client(ctx, tok) - _ = client -} diff --git a/vendor/golang.org/x/oauth2/google/default.go b/vendor/golang.org/x/oauth2/google/default.go index b4b62745c4..a31607437d 100644 --- a/vendor/golang.org/x/oauth2/google/default.go +++ b/vendor/golang.org/x/oauth2/google/default.go @@ -18,20 +18,6 @@ import ( "golang.org/x/oauth2" ) -// DefaultCredentials holds "Application Default Credentials". -// For more details, see: -// https://developers.google.com/accounts/docs/application-default-credentials -type DefaultCredentials struct { - ProjectID string // may be empty - TokenSource oauth2.TokenSource - - // JSON contains the raw bytes from a JSON credentials file. - // This field may be nil if authentication is provided by the - // environment and not with a credentials file, e.g. when code is - // running on Google Cloud Platform. - JSON []byte -} - // DefaultClient returns an HTTP Client that uses the // DefaultTokenSource to obtain authentication credentials. func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) { @@ -53,25 +39,12 @@ func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSourc return creds.TokenSource, nil } -// FindDefaultCredentials searches for "Application Default Credentials". -// -// It looks for credentials in the following places, -// preferring the first location found: -// -// 1. A JSON file whose path is specified by the -// GOOGLE_APPLICATION_CREDENTIALS environment variable. -// 2. A JSON file in a location known to the gcloud command-line tool. -// On Windows, this is %APPDATA%/gcloud/application_default_credentials.json. -// On other systems, $HOME/.config/gcloud/application_default_credentials.json. -// 3. On Google App Engine it uses the appengine.AccessToken function. -// 4. On Google Compute Engine and Google App Engine Managed VMs, it fetches -// credentials from the metadata server. -// (In this final case any provided scopes are ignored.) -func FindDefaultCredentials(ctx context.Context, scope ...string) (*DefaultCredentials, error) { +// Common implementation for FindDefaultCredentials. +func findDefaultCredentials(ctx context.Context, scopes []string) (*DefaultCredentials, error) { // First, try the environment variable. const envVar = "GOOGLE_APPLICATION_CREDENTIALS" if filename := os.Getenv(envVar); filename != "" { - creds, err := readCredentialsFile(ctx, filename, scope) + creds, err := readCredentialsFile(ctx, filename, scopes) if err != nil { return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err) } @@ -80,7 +53,7 @@ func FindDefaultCredentials(ctx context.Context, scope ...string) (*DefaultCrede // Second, try a well-known file. filename := wellKnownFile() - if creds, err := readCredentialsFile(ctx, filename, scope); err == nil { + if creds, err := readCredentialsFile(ctx, filename, scopes); err == nil { return creds, nil } else if !os.IsNotExist(err) { return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err) @@ -90,7 +63,7 @@ func FindDefaultCredentials(ctx context.Context, scope ...string) (*DefaultCrede if appengineTokenFunc != nil && !appengineFlex { return &DefaultCredentials{ ProjectID: appengineAppIDFunc(ctx), - TokenSource: AppEngineTokenSource(ctx, scope...), + TokenSource: AppEngineTokenSource(ctx, scopes...), }, nil } @@ -108,6 +81,23 @@ func FindDefaultCredentials(ctx context.Context, scope ...string) (*DefaultCrede return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url) } +// Common implementation for CredentialsFromJSON. +func credentialsFromJSON(ctx context.Context, jsonData []byte, scopes []string) (*DefaultCredentials, error) { + var f credentialsFile + if err := json.Unmarshal(jsonData, &f); err != nil { + return nil, err + } + ts, err := f.tokenSource(ctx, append([]string(nil), scopes...)) + if err != nil { + return nil, err + } + return &DefaultCredentials{ + ProjectID: f.ProjectID, + TokenSource: ts, + JSON: jsonData, + }, nil +} + func wellKnownFile() string { const f = "application_default_credentials.json" if runtime.GOOS == "windows" { @@ -121,17 +111,5 @@ func readCredentialsFile(ctx context.Context, filename string, scopes []string) if err != nil { return nil, err } - var f credentialsFile - if err := json.Unmarshal(b, &f); err != nil { - return nil, err - } - ts, err := f.tokenSource(ctx, append([]string(nil), scopes...)) - if err != nil { - return nil, err - } - return &DefaultCredentials{ - ProjectID: f.ProjectID, - TokenSource: ts, - JSON: b, - }, nil + return CredentialsFromJSON(ctx, b, scopes...) } diff --git a/vendor/golang.org/x/oauth2/google/doc_go19.go b/vendor/golang.org/x/oauth2/google/doc_go19.go new file mode 100644 index 0000000000..2a86325fe3 --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/doc_go19.go @@ -0,0 +1,42 @@ +// Copyright 2018 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 go1.9 + +// Package google provides support for making OAuth2 authorized and authenticated +// HTTP requests to Google APIs. It supports the Web server flow, client-side +// credentials, service accounts, Google Compute Engine service accounts, and Google +// App Engine service accounts. +// +// A brief overview of the package follows. For more information, please read +// https://developers.google.com/accounts/docs/OAuth2 +// and +// https://developers.google.com/accounts/docs/application-default-credentials. +// +// OAuth2 Configs +// +// Two functions in this package return golang.org/x/oauth2.Config values from Google credential +// data. Google supports two JSON formats for OAuth2 credentials: one is handled by ConfigFromJSON, +// the other by JWTConfigFromJSON. The returned Config can be used to obtain a TokenSource or +// create an http.Client. +// +// +// Credentials +// +// The Credentials type represents Google credentials, including Application Default +// Credentials. +// +// Use FindDefaultCredentials to obtain Application Default Credentials. +// FindDefaultCredentials looks in some well-known places for a credentials file, and +// will call AppEngineTokenSource or ComputeTokenSource as needed. +// +// DefaultClient and DefaultTokenSource are convenience methods. They first call FindDefaultCredentials, +// then use the credentials to construct an http.Client or an oauth2.TokenSource. +// +// Use CredentialsFromJSON to obtain credentials from either of the two JSON formats +// described in OAuth2 Configs, above. The TokenSource in the returned value is the +// same as the one obtained from the oauth2.Config returned from ConfigFromJSON or +// JWTConfigFromJSON, but the Credentials may contain additional information +// that is useful is some circumstances. +package google // import "golang.org/x/oauth2/google" diff --git a/vendor/golang.org/x/oauth2/google/doc_not_go19.go b/vendor/golang.org/x/oauth2/google/doc_not_go19.go new file mode 100644 index 0000000000..5c3c6e1481 --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/doc_not_go19.go @@ -0,0 +1,43 @@ +// Copyright 2018 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 !go1.9 + +// Package google provides support for making OAuth2 authorized and authenticated +// HTTP requests to Google APIs. It supports the Web server flow, client-side +// credentials, service accounts, Google Compute Engine service accounts, and Google +// App Engine service accounts. +// +// A brief overview of the package follows. For more information, please read +// https://developers.google.com/accounts/docs/OAuth2 +// and +// https://developers.google.com/accounts/docs/application-default-credentials. +// +// OAuth2 Configs +// +// Two functions in this package return golang.org/x/oauth2.Config values from Google credential +// data. Google supports two JSON formats for OAuth2 credentials: one is handled by ConfigFromJSON, +// the other by JWTConfigFromJSON. The returned Config can be used to obtain a TokenSource or +// create an http.Client. +// +// +// Credentials +// +// The DefaultCredentials type represents Google Application Default Credentials, as +// well as other forms of credential. +// +// Use FindDefaultCredentials to obtain Application Default Credentials. +// FindDefaultCredentials looks in some well-known places for a credentials file, and +// will call AppEngineTokenSource or ComputeTokenSource as needed. +// +// DefaultClient and DefaultTokenSource are convenience methods. They first call FindDefaultCredentials, +// then use the credentials to construct an http.Client or an oauth2.TokenSource. +// +// Use CredentialsFromJSON to obtain credentials from either of the two JSON +// formats described in OAuth2 Configs, above. (The DefaultCredentials returned may +// not be "Application Default Credentials".) The TokenSource in the returned value +// is the same as the one obtained from the oauth2.Config returned from +// ConfigFromJSON or JWTConfigFromJSON, but the DefaultCredentials may contain +// additional information that is useful is some circumstances. +package google // import "golang.org/x/oauth2/google" diff --git a/vendor/golang.org/x/oauth2/google/example_test.go b/vendor/golang.org/x/oauth2/google/example_test.go deleted file mode 100644 index 92bc3b40c7..0000000000 --- a/vendor/golang.org/x/oauth2/google/example_test.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2014 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 appenginevm appengine - -package google_test - -import ( - "fmt" - "io/ioutil" - "log" - "net/http" - - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - "golang.org/x/oauth2/jwt" - "google.golang.org/appengine" - "google.golang.org/appengine/urlfetch" -) - -func ExampleDefaultClient() { - client, err := google.DefaultClient(oauth2.NoContext, - "https://www.googleapis.com/auth/devstorage.full_control") - if err != nil { - log.Fatal(err) - } - client.Get("...") -} - -func Example_webServer() { - // Your credentials should be obtained from the Google - // Developer Console (https://console.developers.google.com). - conf := &oauth2.Config{ - ClientID: "YOUR_CLIENT_ID", - ClientSecret: "YOUR_CLIENT_SECRET", - RedirectURL: "YOUR_REDIRECT_URL", - Scopes: []string{ - "https://www.googleapis.com/auth/bigquery", - "https://www.googleapis.com/auth/blogger", - }, - Endpoint: google.Endpoint, - } - // Redirect user to Google's consent page to ask for permission - // for the scopes specified above. - url := conf.AuthCodeURL("state") - fmt.Printf("Visit the URL for the auth dialog: %v", url) - - // Handle the exchange code to initiate a transport. - tok, err := conf.Exchange(oauth2.NoContext, "authorization-code") - if err != nil { - log.Fatal(err) - } - client := conf.Client(oauth2.NoContext, tok) - client.Get("...") -} - -func ExampleJWTConfigFromJSON() { - // Your credentials should be obtained from the Google - // Developer Console (https://console.developers.google.com). - // Navigate to your project, then see the "Credentials" page - // under "APIs & Auth". - // To create a service account client, click "Create new Client ID", - // select "Service Account", and click "Create Client ID". A JSON - // key file will then be downloaded to your computer. - data, err := ioutil.ReadFile("/path/to/your-project-key.json") - if err != nil { - log.Fatal(err) - } - conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/bigquery") - if err != nil { - log.Fatal(err) - } - // Initiate an http.Client. The following GET request will be - // authorized and authenticated on the behalf of - // your service account. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} - -func ExampleSDKConfig() { - // The credentials will be obtained from the first account that - // has been authorized with `gcloud auth login`. - conf, err := google.NewSDKConfig("") - if err != nil { - log.Fatal(err) - } - // Initiate an http.Client. The following GET request will be - // authorized and authenticated on the behalf of the SDK user. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} - -func Example_serviceAccount() { - // Your credentials should be obtained from the Google - // Developer Console (https://console.developers.google.com). - conf := &jwt.Config{ - Email: "xxx@developer.gserviceaccount.com", - // The contents of your RSA private key or your PEM file - // that contains a private key. - // If you have a p12 file instead, you - // can use `openssl` to export the private key into a pem file. - // - // $ openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes - // - // The field only supports PEM containers with no passphrase. - // The openssl command will convert p12 keys to passphrase-less PEM containers. - PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."), - Scopes: []string{ - "https://www.googleapis.com/auth/bigquery", - "https://www.googleapis.com/auth/blogger", - }, - TokenURL: google.JWTTokenURL, - // If you would like to impersonate a user, you can - // create a transport with a subject. The following GET - // request will be made on the behalf of user@example.com. - // Optional. - Subject: "user@example.com", - } - // Initiate an http.Client, the following GET request will be - // authorized and authenticated on the behalf of user@example.com. - client := conf.Client(oauth2.NoContext) - client.Get("...") -} - -func ExampleAppEngineTokenSource() { - var req *http.Request // from the ServeHTTP handler - ctx := appengine.NewContext(req) - client := &http.Client{ - Transport: &oauth2.Transport{ - Source: google.AppEngineTokenSource(ctx, "https://www.googleapis.com/auth/bigquery"), - Base: &urlfetch.Transport{ - Context: ctx, - }, - }, - } - client.Get("...") -} - -func ExampleComputeTokenSource() { - client := &http.Client{ - Transport: &oauth2.Transport{ - // Fetch from Google Compute Engine's metadata server to retrieve - // an access token for the provided account. - // If no account is specified, "default" is used. - Source: google.ComputeTokenSource(""), - }, - } - client.Get("...") -} diff --git a/vendor/golang.org/x/oauth2/google/go19.go b/vendor/golang.org/x/oauth2/google/go19.go new file mode 100644 index 0000000000..4d0318b1e1 --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/go19.go @@ -0,0 +1,57 @@ +// Copyright 2018 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 go1.9 + +package google + +import ( + "golang.org/x/net/context" + "golang.org/x/oauth2" +) + +// Credentials holds Google credentials, including "Application Default Credentials". +// For more details, see: +// https://developers.google.com/accounts/docs/application-default-credentials +type Credentials struct { + ProjectID string // may be empty + TokenSource oauth2.TokenSource + + // JSON contains the raw bytes from a JSON credentials file. + // This field may be nil if authentication is provided by the + // environment and not with a credentials file, e.g. when code is + // running on Google Cloud Platform. + JSON []byte +} + +// DefaultCredentials is the old name of Credentials. +// +// Deprecated: use Credentials instead. +type DefaultCredentials = Credentials + +// FindDefaultCredentials searches for "Application Default Credentials". +// +// It looks for credentials in the following places, +// preferring the first location found: +// +// 1. A JSON file whose path is specified by the +// GOOGLE_APPLICATION_CREDENTIALS environment variable. +// 2. A JSON file in a location known to the gcloud command-line tool. +// On Windows, this is %APPDATA%/gcloud/application_default_credentials.json. +// On other systems, $HOME/.config/gcloud/application_default_credentials.json. +// 3. On Google App Engine it uses the appengine.AccessToken function. +// 4. On Google Compute Engine and Google App Engine Managed VMs, it fetches +// credentials from the metadata server. +// (In this final case any provided scopes are ignored.) +func FindDefaultCredentials(ctx context.Context, scopes ...string) (*Credentials, error) { + return findDefaultCredentials(ctx, scopes) +} + +// CredentialsFromJSON obtains Google credentials from a JSON value. The JSON can +// represent either a Google Developers Console client_credentials.json file (as in +// ConfigFromJSON) or a Google Developers service account key file (as in +// JWTConfigFromJSON). +func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*Credentials, error) { + return credentialsFromJSON(ctx, jsonData, scopes) +} diff --git a/vendor/golang.org/x/oauth2/google/google.go b/vendor/golang.org/x/oauth2/google/google.go index 66a8b0e181..f7481fbcc6 100644 --- a/vendor/golang.org/x/oauth2/google/google.go +++ b/vendor/golang.org/x/oauth2/google/google.go @@ -2,17 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Package google provides support for making OAuth2 authorized and -// authenticated HTTP requests to Google APIs. -// It supports the Web server flow, client-side credentials, service accounts, -// Google Compute Engine service accounts, and Google App Engine service -// accounts. -// -// For more information, please read -// https://developers.google.com/accounts/docs/OAuth2 -// and -// https://developers.google.com/accounts/docs/application-default-credentials. -package google // import "golang.org/x/oauth2/google" +package google import ( "encoding/json" diff --git a/vendor/golang.org/x/oauth2/google/google_test.go b/vendor/golang.org/x/oauth2/google/google_test.go deleted file mode 100644 index 287c699e7b..0000000000 --- a/vendor/golang.org/x/oauth2/google/google_test.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2015 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 google - -import ( - "strings" - "testing" -) - -var webJSONKey = []byte(` -{ - "web": { - "auth_uri": "https://google.com/o/oauth2/auth", - "client_secret": "3Oknc4jS_wA2r9i", - "token_uri": "https://google.com/o/oauth2/token", - "client_email": "222-nprqovg5k43uum874cs9osjt2koe97g8@developer.gserviceaccount.com", - "redirect_uris": ["https://www.example.com/oauth2callback"], - "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/222-nprqovg5k43uum874cs9osjt2koe97g8@developer.gserviceaccount.com", - "client_id": "222-nprqovg5k43uum874cs9osjt2koe97g8.apps.googleusercontent.com", - "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", - "javascript_origins": ["https://www.example.com"] - } -}`) - -var installedJSONKey = []byte(`{ - "installed": { - "client_id": "222-installed.apps.googleusercontent.com", - "redirect_uris": ["https://www.example.com/oauth2callback"] - } -}`) - -var jwtJSONKey = []byte(`{ - "private_key_id": "268f54e43a1af97cfc71731688434f45aca15c8b", - "private_key": "super secret key", - "client_email": "gopher@developer.gserviceaccount.com", - "client_id": "gopher.apps.googleusercontent.com", - "token_uri": "https://accounts.google.com/o/gophers/token", - "type": "service_account" -}`) - -var jwtJSONKeyNoTokenURL = []byte(`{ - "private_key_id": "268f54e43a1af97cfc71731688434f45aca15c8b", - "private_key": "super secret key", - "client_email": "gopher@developer.gserviceaccount.com", - "client_id": "gopher.apps.googleusercontent.com", - "type": "service_account" -}`) - -func TestConfigFromJSON(t *testing.T) { - conf, err := ConfigFromJSON(webJSONKey, "scope1", "scope2") - if err != nil { - t.Error(err) - } - if got, want := conf.ClientID, "222-nprqovg5k43uum874cs9osjt2koe97g8.apps.googleusercontent.com"; got != want { - t.Errorf("ClientID = %q; want %q", got, want) - } - if got, want := conf.ClientSecret, "3Oknc4jS_wA2r9i"; got != want { - t.Errorf("ClientSecret = %q; want %q", got, want) - } - if got, want := conf.RedirectURL, "https://www.example.com/oauth2callback"; got != want { - t.Errorf("RedictURL = %q; want %q", got, want) - } - if got, want := strings.Join(conf.Scopes, ","), "scope1,scope2"; got != want { - t.Errorf("Scopes = %q; want %q", got, want) - } - if got, want := conf.Endpoint.AuthURL, "https://google.com/o/oauth2/auth"; got != want { - t.Errorf("AuthURL = %q; want %q", got, want) - } - if got, want := conf.Endpoint.TokenURL, "https://google.com/o/oauth2/token"; got != want { - t.Errorf("TokenURL = %q; want %q", got, want) - } -} - -func TestConfigFromJSON_Installed(t *testing.T) { - conf, err := ConfigFromJSON(installedJSONKey) - if err != nil { - t.Error(err) - } - if got, want := conf.ClientID, "222-installed.apps.googleusercontent.com"; got != want { - t.Errorf("ClientID = %q; want %q", got, want) - } -} - -func TestJWTConfigFromJSON(t *testing.T) { - conf, err := JWTConfigFromJSON(jwtJSONKey, "scope1", "scope2") - if err != nil { - t.Fatal(err) - } - if got, want := conf.Email, "gopher@developer.gserviceaccount.com"; got != want { - t.Errorf("Email = %q, want %q", got, want) - } - if got, want := string(conf.PrivateKey), "super secret key"; got != want { - t.Errorf("PrivateKey = %q, want %q", got, want) - } - if got, want := conf.PrivateKeyID, "268f54e43a1af97cfc71731688434f45aca15c8b"; got != want { - t.Errorf("PrivateKeyID = %q, want %q", got, want) - } - if got, want := strings.Join(conf.Scopes, ","), "scope1,scope2"; got != want { - t.Errorf("Scopes = %q; want %q", got, want) - } - if got, want := conf.TokenURL, "https://accounts.google.com/o/gophers/token"; got != want { - t.Errorf("TokenURL = %q; want %q", got, want) - } -} - -func TestJWTConfigFromJSONNoTokenURL(t *testing.T) { - conf, err := JWTConfigFromJSON(jwtJSONKeyNoTokenURL, "scope1", "scope2") - if err != nil { - t.Fatal(err) - } - if got, want := conf.TokenURL, "https://accounts.google.com/o/oauth2/token"; got != want { - t.Errorf("TokenURL = %q; want %q", got, want) - } -} diff --git a/vendor/golang.org/x/oauth2/google/jwt_test.go b/vendor/golang.org/x/oauth2/google/jwt_test.go deleted file mode 100644 index f844436fc8..0000000000 --- a/vendor/golang.org/x/oauth2/google/jwt_test.go +++ /dev/null @@ -1,91 +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 google - -import ( - "bytes" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/base64" - "encoding/json" - "encoding/pem" - "strings" - "testing" - "time" - - "golang.org/x/oauth2/jws" -) - -func TestJWTAccessTokenSourceFromJSON(t *testing.T) { - // Generate a key we can use in the test data. - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Fatal(err) - } - - // Encode the key and substitute into our example JSON. - enc := pem.EncodeToMemory(&pem.Block{ - Type: "PRIVATE KEY", - Bytes: x509.MarshalPKCS1PrivateKey(privateKey), - }) - enc, err = json.Marshal(string(enc)) - if err != nil { - t.Fatalf("json.Marshal: %v", err) - } - jsonKey := bytes.Replace(jwtJSONKey, []byte(`"super secret key"`), enc, 1) - - ts, err := JWTAccessTokenSourceFromJSON(jsonKey, "audience") - if err != nil { - t.Fatalf("JWTAccessTokenSourceFromJSON: %v\nJSON: %s", err, string(jsonKey)) - } - - tok, err := ts.Token() - if err != nil { - t.Fatalf("Token: %v", err) - } - - if got, want := tok.TokenType, "Bearer"; got != want { - t.Errorf("TokenType = %q, want %q", got, want) - } - if got := tok.Expiry; tok.Expiry.Before(time.Now()) { - t.Errorf("Expiry = %v, should not be expired", got) - } - - err = jws.Verify(tok.AccessToken, &privateKey.PublicKey) - if err != nil { - t.Errorf("jws.Verify on AccessToken: %v", err) - } - - claim, err := jws.Decode(tok.AccessToken) - if err != nil { - t.Fatalf("jws.Decode on AccessToken: %v", err) - } - - if got, want := claim.Iss, "gopher@developer.gserviceaccount.com"; got != want { - t.Errorf("Iss = %q, want %q", got, want) - } - if got, want := claim.Sub, "gopher@developer.gserviceaccount.com"; got != want { - t.Errorf("Sub = %q, want %q", got, want) - } - if got, want := claim.Aud, "audience"; got != want { - t.Errorf("Aud = %q, want %q", got, want) - } - - // Finally, check the header private key. - parts := strings.Split(tok.AccessToken, ".") - hdrJSON, err := base64.RawURLEncoding.DecodeString(parts[0]) - if err != nil { - t.Fatalf("base64 DecodeString: %v\nString: %q", err, parts[0]) - } - var hdr jws.Header - if err := json.Unmarshal([]byte(hdrJSON), &hdr); err != nil { - t.Fatalf("json.Unmarshal: %v (%q)", err, hdrJSON) - } - - if got, want := hdr.KeyID, "268f54e43a1af97cfc71731688434f45aca15c8b"; got != want { - t.Errorf("Header KeyID = %q, want %q", got, want) - } -} diff --git a/vendor/golang.org/x/oauth2/google/not_go19.go b/vendor/golang.org/x/oauth2/google/not_go19.go new file mode 100644 index 0000000000..544e40624e --- /dev/null +++ b/vendor/golang.org/x/oauth2/google/not_go19.go @@ -0,0 +1,54 @@ +// Copyright 2018 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 !go1.9 + +package google + +import ( + "golang.org/x/net/context" + "golang.org/x/oauth2" +) + +// DefaultCredentials holds Google credentials, including "Application Default Credentials". +// For more details, see: +// https://developers.google.com/accounts/docs/application-default-credentials +type DefaultCredentials struct { + ProjectID string // may be empty + TokenSource oauth2.TokenSource + + // JSON contains the raw bytes from a JSON credentials file. + // This field may be nil if authentication is provided by the + // environment and not with a credentials file, e.g. when code is + // running on Google Cloud Platform. + JSON []byte +} + +// FindDefaultCredentials searches for "Application Default Credentials". +// +// It looks for credentials in the following places, +// preferring the first location found: +// +// 1. A JSON file whose path is specified by the +// GOOGLE_APPLICATION_CREDENTIALS environment variable. +// 2. A JSON file in a location known to the gcloud command-line tool. +// On Windows, this is %APPDATA%/gcloud/application_default_credentials.json. +// On other systems, $HOME/.config/gcloud/application_default_credentials.json. +// 3. On Google App Engine it uses the appengine.AccessToken function. +// 4. On Google Compute Engine and Google App Engine Managed VMs, it fetches +// credentials from the metadata server. +// (In this final case any provided scopes are ignored.) +func FindDefaultCredentials(ctx context.Context, scopes ...string) (*DefaultCredentials, error) { + return findDefaultCredentials(ctx, scopes) +} + +// CredentialsFromJSON obtains Google credentials from a JSON value. The JSON can +// represent either a Google Developers Console client_credentials.json file (as in +// ConfigFromJSON) or a Google Developers service account key file (as in +// JWTConfigFromJSON). +// +// Note: despite the name, the returned credentials may not be Application Default Credentials. +func CredentialsFromJSON(ctx context.Context, jsonData []byte, scopes ...string) (*DefaultCredentials, error) { + return credentialsFromJSON(ctx, jsonData, scopes) +} diff --git a/vendor/golang.org/x/oauth2/google/sdk.go b/vendor/golang.org/x/oauth2/google/sdk.go index bdc18084b1..b9660caddf 100644 --- a/vendor/golang.org/x/oauth2/google/sdk.go +++ b/vendor/golang.org/x/oauth2/google/sdk.go @@ -5,9 +5,11 @@ package google import ( + "bufio" "encoding/json" "errors" "fmt" + "io" "net/http" "os" "os/user" @@ -18,7 +20,6 @@ import ( "golang.org/x/net/context" "golang.org/x/oauth2" - "golang.org/x/oauth2/internal" ) type sdkCredentials struct { @@ -76,7 +77,7 @@ func NewSDKConfig(account string) (*SDKConfig, error) { return nil, fmt.Errorf("oauth2/google: failed to load SDK properties: %v", err) } defer f.Close() - ini, err := internal.ParseINI(f) + ini, err := parseINI(f) if err != nil { return nil, fmt.Errorf("oauth2/google: failed to parse SDK properties %q: %v", propertiesPath, err) } @@ -146,6 +147,34 @@ func (c *SDKConfig) Scopes() []string { return c.conf.Scopes } +func parseINI(ini io.Reader) (map[string]map[string]string, error) { + result := map[string]map[string]string{ + "": {}, // root section + } + scanner := bufio.NewScanner(ini) + currentSection := "" + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if strings.HasPrefix(line, ";") { + // comment. + continue + } + if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + currentSection = strings.TrimSpace(line[1 : len(line)-1]) + result[currentSection] = map[string]string{} + continue + } + parts := strings.SplitN(line, "=", 2) + if len(parts) == 2 && parts[0] != "" { + result[currentSection][strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) + } + } + if err := scanner.Err(); err != nil { + return nil, fmt.Errorf("error scanning ini: %v", err) + } + return result, nil +} + // sdkConfigPath tries to guess where the gcloud config is located. // It can be overridden during tests. var sdkConfigPath = func() (string, error) { diff --git a/vendor/golang.org/x/oauth2/google/sdk_test.go b/vendor/golang.org/x/oauth2/google/sdk_test.go deleted file mode 100644 index 4489bb9430..0000000000 --- a/vendor/golang.org/x/oauth2/google/sdk_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2015 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 google - -import "testing" - -func TestSDKConfig(t *testing.T) { - sdkConfigPath = func() (string, error) { - return "testdata/gcloud", nil - } - - tests := []struct { - account string - accessToken string - err bool - }{ - {"", "bar_access_token", false}, - {"foo@example.com", "foo_access_token", false}, - {"bar@example.com", "bar_access_token", false}, - {"baz@serviceaccount.example.com", "", true}, - } - for _, tt := range tests { - c, err := NewSDKConfig(tt.account) - if got, want := err != nil, tt.err; got != want { - if !tt.err { - t.Errorf("got %v, want nil", err) - } else { - t.Errorf("got nil, want error") - } - continue - } - if err != nil { - continue - } - tok := c.initialToken - if tok == nil { - t.Errorf("got nil, want %q", tt.accessToken) - continue - } - if tok.AccessToken != tt.accessToken { - t.Errorf("got %q, want %q", tok.AccessToken, tt.accessToken) - } - } -} diff --git a/vendor/golang.org/x/oauth2/internal/client_appengine.go b/vendor/golang.org/x/oauth2/internal/client_appengine.go new file mode 100644 index 0000000000..7434871880 --- /dev/null +++ b/vendor/golang.org/x/oauth2/internal/client_appengine.go @@ -0,0 +1,13 @@ +// Copyright 2018 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 appengine + +package internal + +import "google.golang.org/appengine/urlfetch" + +func init() { + appengineClientHook = urlfetch.Client +} diff --git a/vendor/golang.org/x/oauth2/internal/oauth2.go b/vendor/golang.org/x/oauth2/internal/oauth2.go index 6978192a99..fc63fcab3f 100644 --- a/vendor/golang.org/x/oauth2/internal/oauth2.go +++ b/vendor/golang.org/x/oauth2/internal/oauth2.go @@ -5,14 +5,11 @@ package internal import ( - "bufio" "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "fmt" - "io" - "strings" ) // ParseKey converts the binary contents of a private key file @@ -38,38 +35,3 @@ func ParseKey(key []byte) (*rsa.PrivateKey, error) { } return parsed, nil } - -func ParseINI(ini io.Reader) (map[string]map[string]string, error) { - result := map[string]map[string]string{ - "": {}, // root section - } - scanner := bufio.NewScanner(ini) - currentSection := "" - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - if strings.HasPrefix(line, ";") { - // comment. - continue - } - if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { - currentSection = strings.TrimSpace(line[1 : len(line)-1]) - result[currentSection] = map[string]string{} - continue - } - parts := strings.SplitN(line, "=", 2) - if len(parts) == 2 && parts[0] != "" { - result[currentSection][strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) - } - } - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("error scanning ini: %v", err) - } - return result, nil -} - -func CondVal(v string) []string { - if v == "" { - return nil - } - return []string{v} -} diff --git a/vendor/golang.org/x/oauth2/internal/oauth2_test.go b/vendor/golang.org/x/oauth2/internal/oauth2_test.go deleted file mode 100644 index 07d51c433e..0000000000 --- a/vendor/golang.org/x/oauth2/internal/oauth2_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2014 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 internal - -import ( - "reflect" - "strings" - "testing" -) - -func TestParseINI(t *testing.T) { - tests := []struct { - ini string - want map[string]map[string]string - }{ - { - `root = toor -[foo] -bar = hop -ini = nin -`, - map[string]map[string]string{ - "": {"root": "toor"}, - "foo": {"bar": "hop", "ini": "nin"}, - }, - }, - { - `[empty] -[section] -empty= -`, - map[string]map[string]string{ - "": {}, - "empty": {}, - "section": {"empty": ""}, - }, - }, - { - `ignore -[invalid -=stuff -;comment=true -`, - map[string]map[string]string{ - "": {}, - }, - }, - } - for _, tt := range tests { - result, err := ParseINI(strings.NewReader(tt.ini)) - if err != nil { - t.Errorf("ParseINI(%q) error %v, want: no error", tt.ini, err) - continue - } - if !reflect.DeepEqual(result, tt.want) { - t.Errorf("ParseINI(%q) = %#v, want: %#v", tt.ini, result, tt.want) - } - } -} diff --git a/vendor/golang.org/x/oauth2/internal/token.go b/vendor/golang.org/x/oauth2/internal/token.go index 0460957215..30fb315d13 100644 --- a/vendor/golang.org/x/oauth2/internal/token.go +++ b/vendor/golang.org/x/oauth2/internal/token.go @@ -6,6 +6,7 @@ package internal import ( "encoding/json" + "errors" "fmt" "io" "io/ioutil" @@ -102,10 +103,11 @@ var brokenAuthHeaderProviders = []string{ "https://api.twitch.tv/", "https://app.box.com/", "https://connect.stripe.com/", - "https://graph.facebook.com", // see https://github.com/golang/oauth2/issues/214 + "https://login.mailchimp.com/", "https://login.microsoftonline.com/", "https://login.salesforce.com/", "https://login.windows.net", + "https://login.live.com/", "https://oauth.sandbox.trainingpeaks.com/", "https://oauth.trainingpeaks.com/", "https://oauth.vk.com/", @@ -122,10 +124,15 @@ var brokenAuthHeaderProviders = []string{ "https://api.patreon.com/", "https://sandbox.codeswholesale.com/oauth/token", "https://api.sipgate.com/v1/authorization/oauth", + "https://api.medium.com/v1/tokens", + "https://log.finalsurge.com/oauth/token", + "https://multisport.todaysplan.com.au/rest/oauth/access_token", + "https://whats.todaysplan.com.au/rest/oauth/access_token", } // brokenAuthHeaderDomains lists broken providers that issue dynamic endpoints. var brokenAuthHeaderDomains = []string{ + ".auth0.com", ".force.com", ".myshopify.com", ".okta.com", @@ -168,10 +175,6 @@ func providerAuthHeaderWorks(tokenURL string) bool { } func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values) (*Token, error) { - hc, err := ContextClient(ctx) - if err != nil { - return nil, err - } bustedAuth := !providerAuthHeaderWorks(tokenURL) if bustedAuth { if clientID != "" { @@ -189,7 +192,7 @@ func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, if !bustedAuth { req.SetBasicAuth(url.QueryEscape(clientID), url.QueryEscape(clientSecret)) } - r, err := ctxhttp.Do(ctx, hc, req) + r, err := ctxhttp.Do(ctx, ContextClient(ctx), req) if err != nil { return nil, err } @@ -199,7 +202,10 @@ func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) } if code := r.StatusCode; code < 200 || code > 299 { - return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", r.Status, body) + return nil, &RetrieveError{ + Response: r, + Body: body, + } } var token *Token @@ -246,5 +252,17 @@ func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, if token.RefreshToken == "" { token.RefreshToken = v.Get("refresh_token") } + if token.AccessToken == "" { + return token, errors.New("oauth2: server response missing access_token") + } return token, nil } + +type RetrieveError struct { + Response *http.Response + Body []byte +} + +func (r *RetrieveError) Error() string { + return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body) +} diff --git a/vendor/golang.org/x/oauth2/internal/token_test.go b/vendor/golang.org/x/oauth2/internal/token_test.go deleted file mode 100644 index df5eb26471..0000000000 --- a/vendor/golang.org/x/oauth2/internal/token_test.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2014 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 internal - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "testing" - - "golang.org/x/net/context" -) - -func TestRegisterBrokenAuthHeaderProvider(t *testing.T) { - RegisterBrokenAuthHeaderProvider("https://aaa.com/") - tokenURL := "https://aaa.com/token" - if providerAuthHeaderWorks(tokenURL) { - t.Errorf("got %q as unbroken; want broken", tokenURL) - } -} - -func TestRetrieveTokenBustedNoSecret(t *testing.T) { - const clientID = "client-id" - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.FormValue("client_id"), clientID; got != want { - t.Errorf("client_id = %q; want %q", got, want) - } - if got, want := r.FormValue("client_secret"), ""; got != want { - t.Errorf("client_secret = %q; want empty", got) - } - })) - defer ts.Close() - - RegisterBrokenAuthHeaderProvider(ts.URL) - _, err := RetrieveToken(context.Background(), clientID, "", ts.URL, url.Values{}) - if err != nil { - t.Errorf("RetrieveToken = %v; want no error", err) - } -} - -func Test_providerAuthHeaderWorks(t *testing.T) { - for _, p := range brokenAuthHeaderProviders { - if providerAuthHeaderWorks(p) { - t.Errorf("got %q as unbroken; want broken", p) - } - p := fmt.Sprintf("%ssomesuffix", p) - if providerAuthHeaderWorks(p) { - t.Errorf("got %q as unbroken; want broken", p) - } - } - p := "https://api.not-in-the-list-example.com/" - if !providerAuthHeaderWorks(p) { - t.Errorf("got %q as unbroken; want broken", p) - } -} - -func TestProviderAuthHeaderWorksDomain(t *testing.T) { - tests := []struct { - tokenURL string - wantWorks bool - }{ - {"https://dev-12345.okta.com/token-url", false}, - {"https://dev-12345.oktapreview.com/token-url", false}, - {"https://dev-12345.okta.org/token-url", true}, - {"https://foo.bar.force.com/token-url", false}, - {"https://foo.force.com/token-url", false}, - {"https://force.com/token-url", true}, - } - - for _, test := range tests { - got := providerAuthHeaderWorks(test.tokenURL) - if got != test.wantWorks { - t.Errorf("providerAuthHeaderWorks(%q) = %v; want %v", test.tokenURL, got, test.wantWorks) - } - } -} - -func TestRetrieveTokenWithContexts(t *testing.T) { - const clientID = "client-id" - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) - defer ts.Close() - - _, err := RetrieveToken(context.Background(), clientID, "", ts.URL, url.Values{}) - if err != nil { - t.Errorf("RetrieveToken (with background context) = %v; want no error", err) - } - - ctx, cancelfunc := context.WithCancel(context.Background()) - - cancellingts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - cancelfunc() - })) - defer cancellingts.Close() - - _, err = RetrieveToken(ctx, clientID, "", cancellingts.URL, url.Values{}) - if err == nil { - t.Errorf("RetrieveToken (with cancelled context) = nil; want error") - } -} diff --git a/vendor/golang.org/x/oauth2/internal/transport.go b/vendor/golang.org/x/oauth2/internal/transport.go index 783bd98c8b..d16f9ae1fe 100644 --- a/vendor/golang.org/x/oauth2/internal/transport.go +++ b/vendor/golang.org/x/oauth2/internal/transport.go @@ -19,50 +19,16 @@ var HTTPClient ContextKey // because nobody else can create a ContextKey, being unexported. type ContextKey struct{} -// ContextClientFunc is a func which tries to return an *http.Client -// given a Context value. If it returns an error, the search stops -// with that error. If it returns (nil, nil), the search continues -// down the list of registered funcs. -type ContextClientFunc func(context.Context) (*http.Client, error) +var appengineClientHook func(context.Context) *http.Client -var contextClientFuncs []ContextClientFunc - -func RegisterContextClientFunc(fn ContextClientFunc) { - contextClientFuncs = append(contextClientFuncs, fn) -} - -func ContextClient(ctx context.Context) (*http.Client, error) { +func ContextClient(ctx context.Context) *http.Client { if ctx != nil { if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok { - return hc, nil + return hc } } - for _, fn := range contextClientFuncs { - c, err := fn(ctx) - if err != nil { - return nil, err - } - if c != nil { - return c, nil - } + if appengineClientHook != nil { + return appengineClientHook(ctx) } - return http.DefaultClient, nil -} - -func ContextTransport(ctx context.Context) http.RoundTripper { - hc, err := ContextClient(ctx) - // This is a rare error case (somebody using nil on App Engine). - if err != nil { - return ErrorTransport{err} - } - return hc.Transport -} - -// ErrorTransport returns the specified error on RoundTrip. -// This RoundTripper should be used in rare error cases where -// error handling can be postponed to response handling time. -type ErrorTransport struct{ Err error } - -func (t ErrorTransport) RoundTrip(*http.Request) (*http.Response, error) { - return nil, t.Err + return http.DefaultClient } diff --git a/vendor/golang.org/x/oauth2/internal/transport_test.go b/vendor/golang.org/x/oauth2/internal/transport_test.go deleted file mode 100644 index 8772ec5c45..0000000000 --- a/vendor/golang.org/x/oauth2/internal/transport_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015 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 internal - -import ( - "net/http" - "testing" - - "golang.org/x/net/context" -) - -func TestContextClient(t *testing.T) { - rc := &http.Client{} - RegisterContextClientFunc(func(context.Context) (*http.Client, error) { - return rc, nil - }) - - c := &http.Client{} - ctx := context.WithValue(context.Background(), HTTPClient, c) - - hc, err := ContextClient(ctx) - if err != nil { - t.Fatalf("want valid client; got err = %v", err) - } - if hc != c { - t.Fatalf("want context client = %p; got = %p", c, hc) - } - - hc, err = ContextClient(context.TODO()) - if err != nil { - t.Fatalf("want valid client; got err = %v", err) - } - if hc != rc { - t.Fatalf("want registered client = %p; got = %p", c, hc) - } -} diff --git a/vendor/golang.org/x/oauth2/jws/jws_test.go b/vendor/golang.org/x/oauth2/jws/jws_test.go deleted file mode 100644 index 39a136a29f..0000000000 --- a/vendor/golang.org/x/oauth2/jws/jws_test.go +++ /dev/null @@ -1,46 +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 jws - -import ( - "crypto/rand" - "crypto/rsa" - "testing" -) - -func TestSignAndVerify(t *testing.T) { - header := &Header{ - Algorithm: "RS256", - Typ: "JWT", - } - payload := &ClaimSet{ - Iss: "http://google.com/", - Aud: "", - Exp: 3610, - Iat: 10, - } - - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Fatal(err) - } - - token, err := Encode(header, payload, privateKey) - if err != nil { - t.Fatal(err) - } - - err = Verify(token, &privateKey.PublicKey) - if err != nil { - t.Fatal(err) - } -} - -func TestVerifyFailsOnMalformedClaim(t *testing.T) { - err := Verify("abc.def", nil) - if err == nil { - t.Error("got no errors; want improperly formed JWT not to be verified") - } -} diff --git a/vendor/golang.org/x/oauth2/jwt/example_test.go b/vendor/golang.org/x/oauth2/jwt/example_test.go deleted file mode 100644 index 58503d80d3..0000000000 --- a/vendor/golang.org/x/oauth2/jwt/example_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2014 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 jwt_test - -import ( - "context" - - "golang.org/x/oauth2/jwt" -) - -func ExampleJWTConfig() { - ctx := context.Background() - conf := &jwt.Config{ - Email: "xxx@developer.com", - // The contents of your RSA private key or your PEM file - // that contains a private key. - // If you have a p12 file instead, you - // can use `openssl` to export the private key into a pem file. - // - // $ openssl pkcs12 -in key.p12 -out key.pem -nodes - // - // It only supports PEM containers with no passphrase. - PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."), - Subject: "user@example.com", - TokenURL: "https://provider.com/o/oauth2/token", - } - // Initiate an http.Client, the following GET request will be - // authorized and authenticated on the behalf of user@example.com. - client := conf.Client(ctx) - client.Get("...") -} diff --git a/vendor/golang.org/x/oauth2/jwt/jwt.go b/vendor/golang.org/x/oauth2/jwt/jwt.go index e016db4217..e08f315959 100644 --- a/vendor/golang.org/x/oauth2/jwt/jwt.go +++ b/vendor/golang.org/x/oauth2/jwt/jwt.go @@ -124,7 +124,10 @@ func (js jwtSource) Token() (*oauth2.Token, error) { return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) } if c := resp.StatusCode; c < 200 || c > 299 { - return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", resp.Status, body) + return nil, &oauth2.RetrieveError{ + Response: resp, + Body: body, + } } // tokenRes is the JSON response body. var tokenRes struct { diff --git a/vendor/golang.org/x/oauth2/jwt/jwt_test.go b/vendor/golang.org/x/oauth2/jwt/jwt_test.go deleted file mode 100644 index 9f82c71c1e..0000000000 --- a/vendor/golang.org/x/oauth2/jwt/jwt_test.go +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright 2014 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 jwt - -import ( - "context" - "encoding/base64" - "encoding/json" - "net/http" - "net/http/httptest" - "strings" - "testing" - - "golang.org/x/oauth2/jws" -) - -var dummyPrivateKey = []byte(`-----BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEAx4fm7dngEmOULNmAs1IGZ9Apfzh+BkaQ1dzkmbUgpcoghucE -DZRnAGd2aPyB6skGMXUytWQvNYav0WTR00wFtX1ohWTfv68HGXJ8QXCpyoSKSSFY -fuP9X36wBSkSX9J5DVgiuzD5VBdzUISSmapjKm+DcbRALjz6OUIPEWi1Tjl6p5RK -1w41qdbmt7E5/kGhKLDuT7+M83g4VWhgIvaAXtnhklDAggilPPa8ZJ1IFe31lNlr -k4DRk38nc6sEutdf3RL7QoH7FBusI7uXV03DC6dwN1kP4GE7bjJhcRb/7jYt7CQ9 -/E9Exz3c0yAp0yrTg0Fwh+qxfH9dKwN52S7SBwIDAQABAoIBAQCaCs26K07WY5Jt -3a2Cw3y2gPrIgTCqX6hJs7O5ByEhXZ8nBwsWANBUe4vrGaajQHdLj5OKfsIDrOvn -2NI1MqflqeAbu/kR32q3tq8/Rl+PPiwUsW3E6Pcf1orGMSNCXxeducF2iySySzh3 -nSIhCG5uwJDWI7a4+9KiieFgK1pt/Iv30q1SQS8IEntTfXYwANQrfKUVMmVF9aIK -6/WZE2yd5+q3wVVIJ6jsmTzoDCX6QQkkJICIYwCkglmVy5AeTckOVwcXL0jqw5Kf -5/soZJQwLEyBoQq7Kbpa26QHq+CJONetPP8Ssy8MJJXBT+u/bSseMb3Zsr5cr43e -DJOhwsThAoGBAPY6rPKl2NT/K7XfRCGm1sbWjUQyDShscwuWJ5+kD0yudnT/ZEJ1 -M3+KS/iOOAoHDdEDi9crRvMl0UfNa8MAcDKHflzxg2jg/QI+fTBjPP5GOX0lkZ9g -z6VePoVoQw2gpPFVNPPTxKfk27tEzbaffvOLGBEih0Kb7HTINkW8rIlzAoGBAM9y -1yr+jvfS1cGFtNU+Gotoihw2eMKtIqR03Yn3n0PK1nVCDKqwdUqCypz4+ml6cxRK -J8+Pfdh7D+ZJd4LEG6Y4QRDLuv5OA700tUoSHxMSNn3q9As4+T3MUyYxWKvTeu3U -f2NWP9ePU0lV8ttk7YlpVRaPQmc1qwooBA/z/8AdAoGAW9x0HWqmRICWTBnpjyxx -QGlW9rQ9mHEtUotIaRSJ6K/F3cxSGUEkX1a3FRnp6kPLcckC6NlqdNgNBd6rb2rA -cPl/uSkZP42Als+9YMoFPU/xrrDPbUhu72EDrj3Bllnyb168jKLa4VBOccUvggxr -Dm08I1hgYgdN5huzs7y6GeUCgYEAj+AZJSOJ6o1aXS6rfV3mMRve9bQ9yt8jcKXw -5HhOCEmMtaSKfnOF1Ziih34Sxsb7O2428DiX0mV/YHtBnPsAJidL0SdLWIapBzeg -KHArByIRkwE6IvJvwpGMdaex1PIGhx5i/3VZL9qiq/ElT05PhIb+UXgoWMabCp84 -OgxDK20CgYAeaFo8BdQ7FmVX2+EEejF+8xSge6WVLtkaon8bqcn6P0O8lLypoOhd -mJAYH8WU+UAy9pecUnDZj14LAGNVmYcse8HFX71MoshnvCTFEPVo4rZxIAGwMpeJ -5jgQ3slYLpqrGlcbLgUXBUgzEO684Wk/UV9DFPlHALVqCfXQ9dpJPg== ------END RSA PRIVATE KEY-----`) - -func TestJWTFetch_JSONResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{ - "access_token": "90d64460d14870c08c81352a05dedd3465940a7c", - "scope": "user", - "token_type": "bearer", - "expires_in": 3600 - }`)) - })) - defer ts.Close() - - conf := &Config{ - Email: "aaa@xxx.com", - PrivateKey: dummyPrivateKey, - TokenURL: ts.URL, - } - tok, err := conf.TokenSource(context.Background()).Token() - if err != nil { - t.Fatal(err) - } - if !tok.Valid() { - t.Errorf("got invalid token: %v", tok) - } - if got, want := tok.AccessToken, "90d64460d14870c08c81352a05dedd3465940a7c"; got != want { - t.Errorf("access token = %q; want %q", got, want) - } - if got, want := tok.TokenType, "bearer"; got != want { - t.Errorf("token type = %q; want %q", got, want) - } - if got := tok.Expiry.IsZero(); got { - t.Errorf("token expiry = %v, want none", got) - } - scope := tok.Extra("scope") - if got, want := scope, "user"; got != want { - t.Errorf("scope = %q; want %q", got, want) - } -} - -func TestJWTFetch_BadResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - - conf := &Config{ - Email: "aaa@xxx.com", - PrivateKey: dummyPrivateKey, - TokenURL: ts.URL, - } - tok, err := conf.TokenSource(context.Background()).Token() - if err != nil { - t.Fatal(err) - } - if tok == nil { - t.Fatalf("got nil token; want token") - } - if tok.Valid() { - t.Errorf("got invalid token: %v", tok) - } - if got, want := tok.AccessToken, ""; got != want { - t.Errorf("access token = %q; want %q", got, want) - } - if got, want := tok.TokenType, "bearer"; got != want { - t.Errorf("token type = %q; want %q", got, want) - } - scope := tok.Extra("scope") - if got, want := scope, "user"; got != want { - t.Errorf("token scope = %q; want %q", got, want) - } -} - -func TestJWTFetch_BadResponseType(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := &Config{ - Email: "aaa@xxx.com", - PrivateKey: dummyPrivateKey, - TokenURL: ts.URL, - } - tok, err := conf.TokenSource(context.Background()).Token() - if err == nil { - t.Error("got a token; expected error") - if got, want := tok.AccessToken, ""; got != want { - t.Errorf("access token = %q; want %q", got, want) - } - } -} - -func TestJWTFetch_Assertion(t *testing.T) { - var assertion string - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - r.ParseForm() - assertion = r.Form.Get("assertion") - - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{ - "access_token": "90d64460d14870c08c81352a05dedd3465940a7c", - "scope": "user", - "token_type": "bearer", - "expires_in": 3600 - }`)) - })) - defer ts.Close() - - conf := &Config{ - Email: "aaa@xxx.com", - PrivateKey: dummyPrivateKey, - PrivateKeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", - TokenURL: ts.URL, - } - - _, err := conf.TokenSource(context.Background()).Token() - if err != nil { - t.Fatalf("Failed to fetch token: %v", err) - } - - parts := strings.Split(assertion, ".") - if len(parts) != 3 { - t.Fatalf("assertion = %q; want 3 parts", assertion) - } - gotjson, err := base64.RawURLEncoding.DecodeString(parts[0]) - if err != nil { - t.Fatalf("invalid token header; err = %v", err) - } - - got := jws.Header{} - if err := json.Unmarshal(gotjson, &got); err != nil { - t.Errorf("failed to unmarshal json token header = %q; err = %v", gotjson, err) - } - - want := jws.Header{ - Algorithm: "RS256", - Typ: "JWT", - KeyID: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", - } - if got != want { - t.Errorf("access token header = %q; want %q", got, want) - } -} diff --git a/vendor/golang.org/x/oauth2/oauth2.go b/vendor/golang.org/x/oauth2/oauth2.go index 4bafe873d0..a047a5f98b 100644 --- a/vendor/golang.org/x/oauth2/oauth2.go +++ b/vendor/golang.org/x/oauth2/oauth2.go @@ -117,7 +117,7 @@ func SetAuthURLParam(key, value string) AuthCodeOption { // that asks for permissions for the required scopes explicitly. // // State is a token to protect the user from CSRF attacks. You must -// always provide a non-zero string and validate that it matches the +// always provide a non-empty string and validate that it matches the // the state query parameter on your redirect callback. // See http://tools.ietf.org/html/rfc6749#section-10.12 for more info. // @@ -129,9 +129,16 @@ func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string { v := url.Values{ "response_type": {"code"}, "client_id": {c.ClientID}, - "redirect_uri": internal.CondVal(c.RedirectURL), - "scope": internal.CondVal(strings.Join(c.Scopes, " ")), - "state": internal.CondVal(state), + } + if c.RedirectURL != "" { + v.Set("redirect_uri", c.RedirectURL) + } + if len(c.Scopes) > 0 { + v.Set("scope", strings.Join(c.Scopes, " ")) + } + if state != "" { + // TODO(light): Docs say never to omit state; don't allow empty. + v.Set("state", state) } for _, opt := range opts { opt.setValue(v) @@ -157,12 +164,15 @@ func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string { // The HTTP client to use is derived from the context. // If nil, http.DefaultClient is used. func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) { - return retrieveToken(ctx, c, url.Values{ + v := url.Values{ "grant_type": {"password"}, "username": {username}, "password": {password}, - "scope": internal.CondVal(strings.Join(c.Scopes, " ")), - }) + } + if len(c.Scopes) > 0 { + v.Set("scope", strings.Join(c.Scopes, " ")) + } + return retrieveToken(ctx, c, v) } // Exchange converts an authorization code into a token. @@ -176,11 +186,14 @@ func (c *Config) PasswordCredentialsToken(ctx context.Context, username, passwor // The code will be in the *http.Request.FormValue("code"). Before // calling Exchange, be sure to validate FormValue("state"). func (c *Config) Exchange(ctx context.Context, code string) (*Token, error) { - return retrieveToken(ctx, c, url.Values{ - "grant_type": {"authorization_code"}, - "code": {code}, - "redirect_uri": internal.CondVal(c.RedirectURL), - }) + v := url.Values{ + "grant_type": {"authorization_code"}, + "code": {code}, + } + if c.RedirectURL != "" { + v.Set("redirect_uri", c.RedirectURL) + } + return retrieveToken(ctx, c, v) } // Client returns an HTTP client using the provided token. @@ -300,15 +313,11 @@ var HTTPClient internal.ContextKey // packages. func NewClient(ctx context.Context, src TokenSource) *http.Client { if src == nil { - c, err := internal.ContextClient(ctx) - if err != nil { - return &http.Client{Transport: internal.ErrorTransport{Err: err}} - } - return c + return internal.ContextClient(ctx) } return &http.Client{ Transport: &Transport{ - Base: internal.ContextTransport(ctx), + Base: internal.ContextClient(ctx).Transport, Source: ReuseTokenSource(nil, src), }, } diff --git a/vendor/golang.org/x/oauth2/oauth2_test.go b/vendor/golang.org/x/oauth2/oauth2_test.go deleted file mode 100644 index 09293ede19..0000000000 --- a/vendor/golang.org/x/oauth2/oauth2_test.go +++ /dev/null @@ -1,490 +0,0 @@ -// Copyright 2014 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 oauth2 - -import ( - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "testing" - "time" - - "golang.org/x/net/context" -) - -type mockTransport struct { - rt func(req *http.Request) (resp *http.Response, err error) -} - -func (t *mockTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { - return t.rt(req) -} - -func newConf(url string) *Config { - return &Config{ - ClientID: "CLIENT_ID", - ClientSecret: "CLIENT_SECRET", - RedirectURL: "REDIRECT_URL", - Scopes: []string{"scope1", "scope2"}, - Endpoint: Endpoint{ - AuthURL: url + "/auth", - TokenURL: url + "/token", - }, - } -} - -func TestAuthCodeURL(t *testing.T) { - conf := newConf("server") - url := conf.AuthCodeURL("foo", AccessTypeOffline, ApprovalForce) - const want = "server/auth?access_type=offline&approval_prompt=force&client_id=CLIENT_ID&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=foo" - if got := url; got != want { - t.Errorf("got auth code URL = %q; want %q", got, want) - } -} - -func TestAuthCodeURL_CustomParam(t *testing.T) { - conf := newConf("server") - param := SetAuthURLParam("foo", "bar") - url := conf.AuthCodeURL("baz", param) - const want = "server/auth?client_id=CLIENT_ID&foo=bar&redirect_uri=REDIRECT_URL&response_type=code&scope=scope1+scope2&state=baz" - if got := url; got != want { - t.Errorf("got auth code = %q; want %q", got, want) - } -} - -func TestAuthCodeURL_Optional(t *testing.T) { - conf := &Config{ - ClientID: "CLIENT_ID", - Endpoint: Endpoint{ - AuthURL: "/auth-url", - TokenURL: "/token-url", - }, - } - url := conf.AuthCodeURL("") - const want = "/auth-url?client_id=CLIENT_ID&response_type=code" - if got := url; got != want { - t.Fatalf("got auth code = %q; want %q", got, want) - } -} - -func TestURLUnsafeClientConfig(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), "Basic Q0xJRU5UX0lEJTNGJTNGOkNMSUVOVF9TRUNSRVQlM0YlM0Y="; got != want { - t.Errorf("Authorization header = %q; want %q", got, want) - } - - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - conf.ClientID = "CLIENT_ID??" - conf.ClientSecret = "CLIENT_SECRET??" - _, err := conf.Exchange(context.Background(), "exchange-code") - if err != nil { - t.Error(err) - } -} - -func TestExchangeRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() != "/token" { - t.Errorf("Unexpected exchange request URL, %v is found.", r.URL) - } - headerAuth := r.Header.Get("Authorization") - if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - if string(body) != "code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL" { - t.Errorf("Unexpected exchange payload, %v is found.", string(body)) - } - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(context.Background(), "exchange-code") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } - if tok.TokenType != "bearer" { - t.Errorf("Unexpected token type, %#v.", tok.TokenType) - } - scope := tok.Extra("scope") - if scope != "user" { - t.Errorf("Unexpected value for scope: %v", scope) - } -} - -func TestExchangeRequest_JSONResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() != "/token" { - t.Errorf("Unexpected exchange request URL, %v is found.", r.URL) - } - headerAuth := r.Header.Get("Authorization") - if headerAuth != "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - if string(body) != "code=exchange-code&grant_type=authorization_code&redirect_uri=REDIRECT_URL" { - t.Errorf("Unexpected exchange payload, %v is found.", string(body)) - } - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token": "90d64460d14870c08c81352a05dedd3465940a7c", "scope": "user", "token_type": "bearer", "expires_in": 86400}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(context.Background(), "exchange-code") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - if tok.AccessToken != "90d64460d14870c08c81352a05dedd3465940a7c" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } - if tok.TokenType != "bearer" { - t.Errorf("Unexpected token type, %#v.", tok.TokenType) - } - scope := tok.Extra("scope") - if scope != "user" { - t.Errorf("Unexpected value for scope: %v", scope) - } - expiresIn := tok.Extra("expires_in") - if expiresIn != float64(86400) { - t.Errorf("Unexpected non-numeric value for expires_in: %v", expiresIn) - } -} - -func TestExtraValueRetrieval(t *testing.T) { - values := url.Values{} - kvmap := map[string]string{ - "scope": "user", "token_type": "bearer", "expires_in": "86400.92", - "server_time": "1443571905.5606415", "referer_ip": "10.0.0.1", - "etag": "\"afZYj912P4alikMz_P11982\"", "request_id": "86400", - "untrimmed": " untrimmed ", - } - for key, value := range kvmap { - values.Set(key, value) - } - - tok := Token{raw: values} - scope := tok.Extra("scope") - if got, want := scope, "user"; got != want { - t.Errorf("got scope = %q; want %q", got, want) - } - serverTime := tok.Extra("server_time") - if got, want := serverTime, 1443571905.5606415; got != want { - t.Errorf("got server_time value = %v; want %v", got, want) - } - refererIP := tok.Extra("referer_ip") - if got, want := refererIP, "10.0.0.1"; got != want { - t.Errorf("got referer_ip value = %v, want %v", got, want) - } - expiresIn := tok.Extra("expires_in") - if got, want := expiresIn, 86400.92; got != want { - t.Errorf("got expires_in value = %v, want %v", got, want) - } - requestID := tok.Extra("request_id") - if got, want := requestID, int64(86400); got != want { - t.Errorf("got request_id value = %v, want %v", got, want) - } - untrimmed := tok.Extra("untrimmed") - if got, want := untrimmed, " untrimmed "; got != want { - t.Errorf("got untrimmed = %q; want %q", got, want) - } -} - -const day = 24 * time.Hour - -func TestExchangeRequest_JSONResponse_Expiry(t *testing.T) { - seconds := int32(day.Seconds()) - for _, c := range []struct { - expires string - want bool - }{ - {fmt.Sprintf(`"expires_in": %d`, seconds), true}, - {fmt.Sprintf(`"expires_in": "%d"`, seconds), true}, // PayPal case - {fmt.Sprintf(`"expires": %d`, seconds), true}, // Facebook case - {`"expires": false`, false}, // wrong type - {`"expires": {}`, false}, // wrong type - {`"expires": "zzz"`, false}, // wrong value - } { - testExchangeRequest_JSONResponse_expiry(t, c.expires, c.want) - } -} - -func testExchangeRequest_JSONResponse_expiry(t *testing.T, exp string, want bool) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(fmt.Sprintf(`{"access_token": "90d", "scope": "user", "token_type": "bearer", %s}`, exp))) - })) - defer ts.Close() - conf := newConf(ts.URL) - t1 := time.Now().Add(day) - tok, err := conf.Exchange(context.Background(), "exchange-code") - t2 := time.Now().Add(day) - - if got := (err == nil); got != want { - if want { - t.Errorf("unexpected error: got %v", err) - } else { - t.Errorf("unexpected success") - } - } - if !want { - return - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - expiry := tok.Expiry - if expiry.Before(t1) || expiry.After(t2) { - t.Errorf("Unexpected value for Expiry: %v (shold be between %v and %v)", expiry, t1, t2) - } -} - -func TestExchangeRequest_BadResponse(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.Exchange(context.Background(), "code") - if err != nil { - t.Fatal(err) - } - if tok.AccessToken != "" { - t.Errorf("Unexpected access token, %#v.", tok.AccessToken) - } -} - -func TestExchangeRequest_BadResponseType(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":123, "scope": "user", "token_type": "bearer"}`)) - })) - defer ts.Close() - conf := newConf(ts.URL) - _, err := conf.Exchange(context.Background(), "exchange-code") - if err == nil { - t.Error("expected error from invalid access_token type") - } -} - -func TestExchangeRequest_NonBasicAuth(t *testing.T) { - tr := &mockTransport{ - rt: func(r *http.Request) (w *http.Response, err error) { - headerAuth := r.Header.Get("Authorization") - if headerAuth != "" { - t.Errorf("Unexpected authorization header, %v is found.", headerAuth) - } - return nil, errors.New("no response") - }, - } - c := &http.Client{Transport: tr} - conf := &Config{ - ClientID: "CLIENT_ID", - Endpoint: Endpoint{ - AuthURL: "https://accounts.google.com/auth", - TokenURL: "https://accounts.google.com/token", - }, - } - - ctx := context.WithValue(context.Background(), HTTPClient, c) - conf.Exchange(ctx, "code") -} - -func TestPasswordCredentialsTokenRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer r.Body.Close() - expected := "/token" - if r.URL.String() != expected { - t.Errorf("URL = %q; want %q", r.URL, expected) - } - headerAuth := r.Header.Get("Authorization") - expected = "Basic Q0xJRU5UX0lEOkNMSUVOVF9TRUNSRVQ=" - if headerAuth != expected { - t.Errorf("Authorization header = %q; want %q", headerAuth, expected) - } - headerContentType := r.Header.Get("Content-Type") - expected = "application/x-www-form-urlencoded" - if headerContentType != expected { - t.Errorf("Content-Type header = %q; want %q", headerContentType, expected) - } - body, err := ioutil.ReadAll(r.Body) - if err != nil { - t.Errorf("Failed reading request body: %s.", err) - } - expected = "grant_type=password&password=password1&scope=scope1+scope2&username=user1" - if string(body) != expected { - t.Errorf("res.Body = %q; want %q", string(body), expected) - } - w.Header().Set("Content-Type", "application/x-www-form-urlencoded") - w.Write([]byte("access_token=90d64460d14870c08c81352a05dedd3465940a7c&scope=user&token_type=bearer")) - })) - defer ts.Close() - conf := newConf(ts.URL) - tok, err := conf.PasswordCredentialsToken(context.Background(), "user1", "password1") - if err != nil { - t.Error(err) - } - if !tok.Valid() { - t.Fatalf("Token invalid. Got: %#v", tok) - } - expected := "90d64460d14870c08c81352a05dedd3465940a7c" - if tok.AccessToken != expected { - t.Errorf("AccessToken = %q; want %q", tok.AccessToken, expected) - } - expected = "bearer" - if tok.TokenType != expected { - t.Errorf("TokenType = %q; want %q", tok.TokenType, expected) - } -} - -func TestTokenRefreshRequest(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/somethingelse" { - return - } - if r.URL.String() != "/token" { - t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "grant_type=refresh_token&refresh_token=REFRESH_TOKEN" { - t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) - } - })) - defer ts.Close() - conf := newConf(ts.URL) - c := conf.Client(context.Background(), &Token{RefreshToken: "REFRESH_TOKEN"}) - c.Get(ts.URL + "/somethingelse") -} - -func TestFetchWithNoRefreshToken(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.String() == "/somethingelse" { - return - } - if r.URL.String() != "/token" { - t.Errorf("Unexpected token refresh request URL, %v is found.", r.URL) - } - headerContentType := r.Header.Get("Content-Type") - if headerContentType != "application/x-www-form-urlencoded" { - t.Errorf("Unexpected Content-Type header, %v is found.", headerContentType) - } - body, _ := ioutil.ReadAll(r.Body) - if string(body) != "client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN" { - t.Errorf("Unexpected refresh token payload, %v is found.", string(body)) - } - })) - defer ts.Close() - conf := newConf(ts.URL) - c := conf.Client(context.Background(), nil) - _, err := c.Get(ts.URL + "/somethingelse") - if err == nil { - t.Errorf("Fetch should return an error if no refresh token is set") - } -} - -func TestRefreshToken_RefreshTokenReplacement(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":"ACCESS_TOKEN", "scope": "user", "token_type": "bearer", "refresh_token": "NEW_REFRESH_TOKEN"}`)) - return - })) - defer ts.Close() - conf := newConf(ts.URL) - tkr := &tokenRefresher{ - conf: conf, - ctx: context.Background(), - refreshToken: "OLD_REFRESH_TOKEN", - } - tk, err := tkr.Token() - if err != nil { - t.Errorf("got err = %v; want none", err) - return - } - if tk.RefreshToken != tkr.refreshToken { - t.Errorf("tokenRefresher.refresh_token = %q; want %q", tkr.refreshToken, tk.RefreshToken) - } -} - -func TestRefreshToken_RefreshTokenPreservation(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token":"ACCESS_TOKEN", "scope": "user", "token_type": "bearer"}`)) - return - })) - defer ts.Close() - conf := newConf(ts.URL) - const oldRefreshToken = "OLD_REFRESH_TOKEN" - tkr := &tokenRefresher{ - conf: conf, - ctx: context.Background(), - refreshToken: oldRefreshToken, - } - _, err := tkr.Token() - if err != nil { - t.Fatalf("got err = %v; want none", err) - } - if tkr.refreshToken != oldRefreshToken { - t.Errorf("tokenRefresher.refreshToken = %q; want %q", tkr.refreshToken, oldRefreshToken) - } -} - -func TestConfigClientWithToken(t *testing.T) { - tok := &Token{ - AccessToken: "abc123", - } - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), fmt.Sprintf("Bearer %s", tok.AccessToken); got != want { - t.Errorf("Authorization header = %q; want %q", got, want) - } - return - })) - defer ts.Close() - conf := newConf(ts.URL) - - c := conf.Client(context.Background(), tok) - req, err := http.NewRequest("GET", ts.URL, nil) - if err != nil { - t.Error(err) - } - _, err = c.Do(req) - if err != nil { - t.Error(err) - } -} diff --git a/vendor/golang.org/x/oauth2/token.go b/vendor/golang.org/x/oauth2/token.go index bdac1de849..34db8cdc8a 100644 --- a/vendor/golang.org/x/oauth2/token.go +++ b/vendor/golang.org/x/oauth2/token.go @@ -5,6 +5,7 @@ package oauth2 import ( + "fmt" "net/http" "net/url" "strconv" @@ -123,7 +124,7 @@ func (t *Token) expired() bool { if t.Expiry.IsZero() { return false } - return t.Expiry.Add(-expiryDelta).Before(time.Now()) + return t.Expiry.Round(0).Add(-expiryDelta).Before(time.Now()) } // Valid reports whether t is non-nil, has an AccessToken, and is not expired. @@ -152,7 +153,23 @@ func tokenFromInternal(t *internal.Token) *Token { func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) { tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v) if err != nil { + if rErr, ok := err.(*internal.RetrieveError); ok { + return nil, (*RetrieveError)(rErr) + } return nil, err } return tokenFromInternal(tk), nil } + +// RetrieveError is the error returned when the token endpoint returns a +// non-2XX HTTP status code. +type RetrieveError struct { + Response *http.Response + // Body is the body that was consumed by reading Response.Body. + // It may be truncated. + Body []byte +} + +func (r *RetrieveError) Error() string { + return fmt.Sprintf("oauth2: cannot fetch token: %v\nResponse: %s", r.Response.Status, r.Body) +} diff --git a/vendor/golang.org/x/oauth2/token_test.go b/vendor/golang.org/x/oauth2/token_test.go deleted file mode 100644 index 80db83c29c..0000000000 --- a/vendor/golang.org/x/oauth2/token_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2014 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 oauth2 - -import ( - "testing" - "time" -) - -func TestTokenExtra(t *testing.T) { - type testCase struct { - key string - val interface{} - want interface{} - } - const key = "extra-key" - cases := []testCase{ - {key: key, val: "abc", want: "abc"}, - {key: key, val: 123, want: 123}, - {key: key, val: "", want: ""}, - {key: "other-key", val: "def", want: nil}, - } - for _, tc := range cases { - extra := make(map[string]interface{}) - extra[tc.key] = tc.val - tok := &Token{raw: extra} - if got, want := tok.Extra(key), tc.want; got != want { - t.Errorf("Extra(%q) = %q; want %q", key, got, want) - } - } -} - -func TestTokenExpiry(t *testing.T) { - now := time.Now() - cases := []struct { - name string - tok *Token - want bool - }{ - {name: "12 seconds", tok: &Token{Expiry: now.Add(12 * time.Second)}, want: false}, - {name: "10 seconds", tok: &Token{Expiry: now.Add(expiryDelta)}, want: true}, - {name: "-1 hour", tok: &Token{Expiry: now.Add(-1 * time.Hour)}, want: true}, - } - for _, tc := range cases { - if got, want := tc.tok.expired(), tc.want; got != want { - t.Errorf("expired (%q) = %v; want %v", tc.name, got, want) - } - } -} - -func TestTokenTypeMethod(t *testing.T) { - cases := []struct { - name string - tok *Token - want string - }{ - {name: "bearer-mixed_case", tok: &Token{TokenType: "beAREr"}, want: "Bearer"}, - {name: "default-bearer", tok: &Token{}, want: "Bearer"}, - {name: "basic", tok: &Token{TokenType: "basic"}, want: "Basic"}, - {name: "basic-capitalized", tok: &Token{TokenType: "Basic"}, want: "Basic"}, - {name: "mac", tok: &Token{TokenType: "mac"}, want: "MAC"}, - {name: "mac-caps", tok: &Token{TokenType: "MAC"}, want: "MAC"}, - {name: "mac-mixed_case", tok: &Token{TokenType: "mAc"}, want: "MAC"}, - } - for _, tc := range cases { - if got, want := tc.tok.Type(), tc.want; got != want { - t.Errorf("TokenType(%q) = %v; want %v", tc.name, got, want) - } - } -} diff --git a/vendor/golang.org/x/oauth2/transport_test.go b/vendor/golang.org/x/oauth2/transport_test.go deleted file mode 100644 index d6e8087d6e..0000000000 --- a/vendor/golang.org/x/oauth2/transport_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package oauth2 - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" -) - -type tokenSource struct{ token *Token } - -func (t *tokenSource) Token() (*Token, error) { - return t.token, nil -} - -func TestTransportNilTokenSource(t *testing.T) { - tr := &Transport{} - server := newMockServer(func(w http.ResponseWriter, r *http.Request) {}) - defer server.Close() - client := &http.Client{Transport: tr} - resp, err := client.Get(server.URL) - if err == nil { - t.Errorf("got no errors, want an error with nil token source") - } - if resp != nil { - t.Errorf("Response = %v; want nil", resp) - } -} - -func TestTransportTokenSource(t *testing.T) { - ts := &tokenSource{ - token: &Token{ - AccessToken: "abc", - }, - } - tr := &Transport{ - Source: ts, - } - server := newMockServer(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), "Bearer abc"; got != want { - t.Errorf("Authorization header = %q; want %q", got, want) - } - }) - defer server.Close() - client := &http.Client{Transport: tr} - res, err := client.Get(server.URL) - if err != nil { - t.Fatal(err) - } - res.Body.Close() -} - -// Test for case-sensitive token types, per https://github.com/golang/oauth2/issues/113 -func TestTransportTokenSourceTypes(t *testing.T) { - const val = "abc" - tests := []struct { - key string - val string - want string - }{ - {key: "bearer", val: val, want: "Bearer abc"}, - {key: "mac", val: val, want: "MAC abc"}, - {key: "basic", val: val, want: "Basic abc"}, - } - for _, tc := range tests { - ts := &tokenSource{ - token: &Token{ - AccessToken: tc.val, - TokenType: tc.key, - }, - } - tr := &Transport{ - Source: ts, - } - server := newMockServer(func(w http.ResponseWriter, r *http.Request) { - if got, want := r.Header.Get("Authorization"), tc.want; got != want { - t.Errorf("Authorization header (%q) = %q; want %q", val, got, want) - } - }) - defer server.Close() - client := &http.Client{Transport: tr} - res, err := client.Get(server.URL) - if err != nil { - t.Fatal(err) - } - res.Body.Close() - } -} - -func TestTokenValidNoAccessToken(t *testing.T) { - token := &Token{} - if token.Valid() { - t.Errorf("got valid with no access token; want invalid") - } -} - -func TestExpiredWithExpiry(t *testing.T) { - token := &Token{ - Expiry: time.Now().Add(-5 * time.Hour), - } - if token.Valid() { - t.Errorf("got valid with expired token; want invalid") - } -} - -func newMockServer(handler func(w http.ResponseWriter, r *http.Request)) *httptest.Server { - return httptest.NewServer(http.HandlerFunc(handler)) -} diff --git a/vendor/golang.org/x/sys/CONTRIBUTING.md b/vendor/golang.org/x/sys/CONTRIBUTING.md index 88dff59bc7..d0485e887a 100644 --- a/vendor/golang.org/x/sys/CONTRIBUTING.md +++ b/vendor/golang.org/x/sys/CONTRIBUTING.md @@ -4,16 +4,15 @@ Go is an open source project. It is the work of hundreds of contributors. We appreciate your help! - ## Filing issues When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: -1. What version of Go are you using (`go version`)? -2. What operating system and processor architecture are you using? -3. What did you do? -4. What did you expect to see? -5. What did you see instead? +1. What version of Go are you using (`go version`)? +2. What operating system and processor architecture are you using? +3. What did you do? +4. What did you expect to see? +5. What did you see instead? General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. The gophers there will answer or ask you to file an issue if you've tripped over a bug. @@ -23,9 +22,5 @@ The gophers there will answer or ask you to file an issue if you've tripped over Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) before sending patches. -**We do not accept GitHub pull requests** -(we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). - Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file. - diff --git a/vendor/golang.org/x/sys/unix/.gitignore b/vendor/golang.org/x/sys/unix/.gitignore index e482715909..e3e0fc6f89 100644 --- a/vendor/golang.org/x/sys/unix/.gitignore +++ b/vendor/golang.org/x/sys/unix/.gitignore @@ -1 +1,2 @@ _obj/ +unix.test diff --git a/vendor/golang.org/x/sys/unix/affinity_linux.go b/vendor/golang.org/x/sys/unix/affinity_linux.go new file mode 100644 index 0000000000..72afe3338c --- /dev/null +++ b/vendor/golang.org/x/sys/unix/affinity_linux.go @@ -0,0 +1,124 @@ +// Copyright 2018 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. + +// CPU affinity functions + +package unix + +import ( + "unsafe" +) + +const cpuSetSize = _CPU_SETSIZE / _NCPUBITS + +// CPUSet represents a CPU affinity mask. +type CPUSet [cpuSetSize]cpuMask + +func schedAffinity(trap uintptr, pid int, set *CPUSet) error { + _, _, e := RawSyscall(trap, uintptr(pid), uintptr(unsafe.Sizeof(*set)), uintptr(unsafe.Pointer(set))) + if e != 0 { + return errnoErr(e) + } + return nil +} + +// SchedGetaffinity gets the CPU affinity mask of the thread specified by pid. +// If pid is 0 the calling thread is used. +func SchedGetaffinity(pid int, set *CPUSet) error { + return schedAffinity(SYS_SCHED_GETAFFINITY, pid, set) +} + +// SchedSetaffinity sets the CPU affinity mask of the thread specified by pid. +// If pid is 0 the calling thread is used. +func SchedSetaffinity(pid int, set *CPUSet) error { + return schedAffinity(SYS_SCHED_SETAFFINITY, pid, set) +} + +// Zero clears the set s, so that it contains no CPUs. +func (s *CPUSet) Zero() { + for i := range s { + s[i] = 0 + } +} + +func cpuBitsIndex(cpu int) int { + return cpu / _NCPUBITS +} + +func cpuBitsMask(cpu int) cpuMask { + return cpuMask(1 << (uint(cpu) % _NCPUBITS)) +} + +// Set adds cpu to the set s. +func (s *CPUSet) Set(cpu int) { + i := cpuBitsIndex(cpu) + if i < len(s) { + s[i] |= cpuBitsMask(cpu) + } +} + +// Clear removes cpu from the set s. +func (s *CPUSet) Clear(cpu int) { + i := cpuBitsIndex(cpu) + if i < len(s) { + s[i] &^= cpuBitsMask(cpu) + } +} + +// IsSet reports whether cpu is in the set s. +func (s *CPUSet) IsSet(cpu int) bool { + i := cpuBitsIndex(cpu) + if i < len(s) { + return s[i]&cpuBitsMask(cpu) != 0 + } + return false +} + +// Count returns the number of CPUs in the set s. +func (s *CPUSet) Count() int { + c := 0 + for _, b := range s { + c += onesCount64(uint64(b)) + } + return c +} + +// onesCount64 is a copy of Go 1.9's math/bits.OnesCount64. +// Once this package can require Go 1.9, we can delete this +// and update the caller to use bits.OnesCount64. +func onesCount64(x uint64) int { + const m0 = 0x5555555555555555 // 01010101 ... + const m1 = 0x3333333333333333 // 00110011 ... + const m2 = 0x0f0f0f0f0f0f0f0f // 00001111 ... + const m3 = 0x00ff00ff00ff00ff // etc. + const m4 = 0x0000ffff0000ffff + + // Implementation: Parallel summing of adjacent bits. + // See "Hacker's Delight", Chap. 5: Counting Bits. + // The following pattern shows the general approach: + // + // x = x>>1&(m0&m) + x&(m0&m) + // x = x>>2&(m1&m) + x&(m1&m) + // x = x>>4&(m2&m) + x&(m2&m) + // x = x>>8&(m3&m) + x&(m3&m) + // x = x>>16&(m4&m) + x&(m4&m) + // x = x>>32&(m5&m) + x&(m5&m) + // return int(x) + // + // Masking (& operations) can be left away when there's no + // danger that a field's sum will carry over into the next + // field: Since the result cannot be > 64, 8 bits is enough + // and we can ignore the masks for the shifts by 8 and up. + // Per "Hacker's Delight", the first line can be simplified + // more, but it saves at best one instruction, so we leave + // it alone for clarity. + const m = 1<<64 - 1 + x = x>>1&(m0&m) + x&(m0&m) + x = x>>2&(m1&m) + x&(m1&m) + x = (x>>4 + x) & (m2 & m) + x += x >> 8 + x += x >> 16 + x += x >> 32 + return int(x) & (1<<7 - 1) +} diff --git a/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s b/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s index d5ed6726cc..603dd5728c 100644 --- a/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s +++ b/vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s @@ -13,17 +13,17 @@ // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. -TEXT ·Syscall(SB),NOSPLIT,$0-64 +TEXT ·Syscall(SB),NOSPLIT,$0-56 JMP syscall·Syscall(SB) -TEXT ·Syscall6(SB),NOSPLIT,$0-88 +TEXT ·Syscall6(SB),NOSPLIT,$0-80 JMP syscall·Syscall6(SB) -TEXT ·Syscall9(SB),NOSPLIT,$0-112 +TEXT ·Syscall9(SB),NOSPLIT,$0-104 JMP syscall·Syscall9(SB) -TEXT ·RawSyscall(SB),NOSPLIT,$0-64 +TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) -TEXT ·RawSyscall6(SB),NOSPLIT,$0-88 +TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) diff --git a/vendor/golang.org/x/sys/unix/asm_linux_386.s b/vendor/golang.org/x/sys/unix/asm_linux_386.s index 4db2909323..448bebbb59 100644 --- a/vendor/golang.org/x/sys/unix/asm_linux_386.s +++ b/vendor/golang.org/x/sys/unix/asm_linux_386.s @@ -10,21 +10,51 @@ // System calls for 386, Linux // +// See ../runtime/sys_linux_386.s for the reason why we always use int 0x80 +// instead of the glibc-specific "CALL 0x10(GS)". +#define INVOKE_SYSCALL INT $0x80 + // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. -TEXT ·Syscall(SB),NOSPLIT,$0-28 +TEXT ·Syscall(SB),NOSPLIT,$0-28 JMP syscall·Syscall(SB) -TEXT ·Syscall6(SB),NOSPLIT,$0-40 +TEXT ·Syscall6(SB),NOSPLIT,$0-40 JMP syscall·Syscall6(SB) +TEXT ·SyscallNoError(SB),NOSPLIT,$0-24 + CALL runtime·entersyscall(SB) + MOVL trap+0(FP), AX // syscall entry + MOVL a1+4(FP), BX + MOVL a2+8(FP), CX + MOVL a3+12(FP), DX + MOVL $0, SI + MOVL $0, DI + INVOKE_SYSCALL + MOVL AX, r1+16(FP) + MOVL DX, r2+20(FP) + CALL runtime·exitsyscall(SB) + RET + TEXT ·RawSyscall(SB),NOSPLIT,$0-28 JMP syscall·RawSyscall(SB) -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 +TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 JMP syscall·RawSyscall6(SB) +TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-24 + MOVL trap+0(FP), AX // syscall entry + MOVL a1+4(FP), BX + MOVL a2+8(FP), CX + MOVL a3+12(FP), DX + MOVL $0, SI + MOVL $0, DI + INVOKE_SYSCALL + MOVL AX, r1+16(FP) + MOVL DX, r2+20(FP) + RET + TEXT ·socketcall(SB),NOSPLIT,$0-36 JMP syscall·socketcall(SB) diff --git a/vendor/golang.org/x/sys/unix/asm_linux_amd64.s b/vendor/golang.org/x/sys/unix/asm_linux_amd64.s index 44e25c62f9..c6468a9588 100644 --- a/vendor/golang.org/x/sys/unix/asm_linux_amd64.s +++ b/vendor/golang.org/x/sys/unix/asm_linux_amd64.s @@ -13,17 +13,45 @@ // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. -TEXT ·Syscall(SB),NOSPLIT,$0-56 +TEXT ·Syscall(SB),NOSPLIT,$0-56 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 JMP syscall·Syscall6(SB) +TEXT ·SyscallNoError(SB),NOSPLIT,$0-48 + CALL runtime·entersyscall(SB) + MOVQ a1+8(FP), DI + MOVQ a2+16(FP), SI + MOVQ a3+24(FP), DX + MOVQ $0, R10 + MOVQ $0, R8 + MOVQ $0, R9 + MOVQ trap+0(FP), AX // syscall entry + SYSCALL + MOVQ AX, r1+32(FP) + MOVQ DX, r2+40(FP) + CALL runtime·exitsyscall(SB) + RET + TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) +TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48 + MOVQ a1+8(FP), DI + MOVQ a2+16(FP), SI + MOVQ a3+24(FP), DX + MOVQ $0, R10 + MOVQ $0, R8 + MOVQ $0, R9 + MOVQ trap+0(FP), AX // syscall entry + SYSCALL + MOVQ AX, r1+32(FP) + MOVQ DX, r2+40(FP) + RET + TEXT ·gettimeofday(SB),NOSPLIT,$0-16 JMP syscall·gettimeofday(SB) diff --git a/vendor/golang.org/x/sys/unix/asm_linux_arm.s b/vendor/golang.org/x/sys/unix/asm_linux_arm.s index cf0b574658..cf0f3575c1 100644 --- a/vendor/golang.org/x/sys/unix/asm_linux_arm.s +++ b/vendor/golang.org/x/sys/unix/asm_linux_arm.s @@ -13,17 +13,44 @@ // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. -TEXT ·Syscall(SB),NOSPLIT,$0-28 +TEXT ·Syscall(SB),NOSPLIT,$0-28 B syscall·Syscall(SB) -TEXT ·Syscall6(SB),NOSPLIT,$0-40 +TEXT ·Syscall6(SB),NOSPLIT,$0-40 B syscall·Syscall6(SB) +TEXT ·SyscallNoError(SB),NOSPLIT,$0-24 + BL runtime·entersyscall(SB) + MOVW trap+0(FP), R7 + MOVW a1+4(FP), R0 + MOVW a2+8(FP), R1 + MOVW a3+12(FP), R2 + MOVW $0, R3 + MOVW $0, R4 + MOVW $0, R5 + SWI $0 + MOVW R0, r1+16(FP) + MOVW $0, R0 + MOVW R0, r2+20(FP) + BL runtime·exitsyscall(SB) + RET + TEXT ·RawSyscall(SB),NOSPLIT,$0-28 B syscall·RawSyscall(SB) -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 +TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 B syscall·RawSyscall6(SB) -TEXT ·seek(SB),NOSPLIT,$0-32 +TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-24 + MOVW trap+0(FP), R7 // syscall entry + MOVW a1+4(FP), R0 + MOVW a2+8(FP), R1 + MOVW a3+12(FP), R2 + SWI $0 + MOVW R0, r1+16(FP) + MOVW $0, R0 + MOVW R0, r2+20(FP) + RET + +TEXT ·seek(SB),NOSPLIT,$0-28 B syscall·seek(SB) diff --git a/vendor/golang.org/x/sys/unix/asm_linux_arm64.s b/vendor/golang.org/x/sys/unix/asm_linux_arm64.s index 4be9bfedea..afe6fdf6b1 100644 --- a/vendor/golang.org/x/sys/unix/asm_linux_arm64.s +++ b/vendor/golang.org/x/sys/unix/asm_linux_arm64.s @@ -11,14 +11,42 @@ // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. -TEXT ·Syscall(SB),NOSPLIT,$0-56 +TEXT ·Syscall(SB),NOSPLIT,$0-56 B syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 B syscall·Syscall6(SB) +TEXT ·SyscallNoError(SB),NOSPLIT,$0-48 + BL runtime·entersyscall(SB) + MOVD a1+8(FP), R0 + MOVD a2+16(FP), R1 + MOVD a3+24(FP), R2 + MOVD $0, R3 + MOVD $0, R4 + MOVD $0, R5 + MOVD trap+0(FP), R8 // syscall entry + SVC + MOVD R0, r1+32(FP) // r1 + MOVD R1, r2+40(FP) // r2 + BL runtime·exitsyscall(SB) + RET + TEXT ·RawSyscall(SB),NOSPLIT,$0-56 B syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 B syscall·RawSyscall6(SB) + +TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48 + MOVD a1+8(FP), R0 + MOVD a2+16(FP), R1 + MOVD a3+24(FP), R2 + MOVD $0, R3 + MOVD $0, R4 + MOVD $0, R5 + MOVD trap+0(FP), R8 // syscall entry + SVC + MOVD R0, r1+32(FP) + MOVD R1, r2+40(FP) + RET diff --git a/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s b/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s index 724e580c4e..ab9d63831a 100644 --- a/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s +++ b/vendor/golang.org/x/sys/unix/asm_linux_mips64x.s @@ -15,14 +15,42 @@ // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. -TEXT ·Syscall(SB),NOSPLIT,$0-56 +TEXT ·Syscall(SB),NOSPLIT,$0-56 JMP syscall·Syscall(SB) -TEXT ·Syscall6(SB),NOSPLIT,$0-80 +TEXT ·Syscall6(SB),NOSPLIT,$0-80 JMP syscall·Syscall6(SB) -TEXT ·RawSyscall(SB),NOSPLIT,$0-56 +TEXT ·SyscallNoError(SB),NOSPLIT,$0-48 + JAL runtime·entersyscall(SB) + MOVV a1+8(FP), R4 + MOVV a2+16(FP), R5 + MOVV a3+24(FP), R6 + MOVV R0, R7 + MOVV R0, R8 + MOVV R0, R9 + MOVV trap+0(FP), R2 // syscall entry + SYSCALL + MOVV R2, r1+32(FP) + MOVV R3, r2+40(FP) + JAL runtime·exitsyscall(SB) + RET + +TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) -TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 +TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) + +TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48 + MOVV a1+8(FP), R4 + MOVV a2+16(FP), R5 + MOVV a3+24(FP), R6 + MOVV R0, R7 + MOVV R0, R8 + MOVV R0, R9 + MOVV trap+0(FP), R2 // syscall entry + SYSCALL + MOVV R2, r1+32(FP) + MOVV R3, r2+40(FP) + RET diff --git a/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s b/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s index 2ea425755e..99e5399045 100644 --- a/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s +++ b/vendor/golang.org/x/sys/unix/asm_linux_mipsx.s @@ -15,17 +15,40 @@ // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. -TEXT ·Syscall(SB),NOSPLIT,$0-28 +TEXT ·Syscall(SB),NOSPLIT,$0-28 JMP syscall·Syscall(SB) -TEXT ·Syscall6(SB),NOSPLIT,$0-40 +TEXT ·Syscall6(SB),NOSPLIT,$0-40 JMP syscall·Syscall6(SB) -TEXT ·Syscall9(SB),NOSPLIT,$0-52 +TEXT ·Syscall9(SB),NOSPLIT,$0-52 JMP syscall·Syscall9(SB) -TEXT ·RawSyscall(SB),NOSPLIT,$0-28 +TEXT ·SyscallNoError(SB),NOSPLIT,$0-24 + JAL runtime·entersyscall(SB) + MOVW a1+4(FP), R4 + MOVW a2+8(FP), R5 + MOVW a3+12(FP), R6 + MOVW R0, R7 + MOVW trap+0(FP), R2 // syscall entry + SYSCALL + MOVW R2, r1+16(FP) // r1 + MOVW R3, r2+20(FP) // r2 + JAL runtime·exitsyscall(SB) + RET + +TEXT ·RawSyscall(SB),NOSPLIT,$0-28 JMP syscall·RawSyscall(SB) -TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 +TEXT ·RawSyscall6(SB),NOSPLIT,$0-40 JMP syscall·RawSyscall6(SB) + +TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-24 + MOVW a1+4(FP), R4 + MOVW a2+8(FP), R5 + MOVW a3+12(FP), R6 + MOVW trap+0(FP), R2 // syscall entry + SYSCALL + MOVW R2, r1+16(FP) + MOVW R3, r2+20(FP) + RET diff --git a/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s b/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s index 8d231feb4b..649e58714d 100644 --- a/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s +++ b/vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s @@ -15,14 +15,42 @@ // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. -TEXT ·Syscall(SB),NOSPLIT,$0-56 +TEXT ·Syscall(SB),NOSPLIT,$0-56 BR syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 BR syscall·Syscall6(SB) +TEXT ·SyscallNoError(SB),NOSPLIT,$0-48 + BL runtime·entersyscall(SB) + MOVD a1+8(FP), R3 + MOVD a2+16(FP), R4 + MOVD a3+24(FP), R5 + MOVD R0, R6 + MOVD R0, R7 + MOVD R0, R8 + MOVD trap+0(FP), R9 // syscall entry + SYSCALL R9 + MOVD R3, r1+32(FP) + MOVD R4, r2+40(FP) + BL runtime·exitsyscall(SB) + RET + TEXT ·RawSyscall(SB),NOSPLIT,$0-56 BR syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 BR syscall·RawSyscall6(SB) + +TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48 + MOVD a1+8(FP), R3 + MOVD a2+16(FP), R4 + MOVD a3+24(FP), R5 + MOVD R0, R6 + MOVD R0, R7 + MOVD R0, R8 + MOVD trap+0(FP), R9 // syscall entry + SYSCALL R9 + MOVD R3, r1+32(FP) + MOVD R4, r2+40(FP) + RET diff --git a/vendor/golang.org/x/sys/unix/asm_linux_s390x.s b/vendor/golang.org/x/sys/unix/asm_linux_s390x.s index 11889859fb..a5a863c6bd 100644 --- a/vendor/golang.org/x/sys/unix/asm_linux_s390x.s +++ b/vendor/golang.org/x/sys/unix/asm_linux_s390x.s @@ -21,8 +21,36 @@ TEXT ·Syscall(SB),NOSPLIT,$0-56 TEXT ·Syscall6(SB),NOSPLIT,$0-80 BR syscall·Syscall6(SB) +TEXT ·SyscallNoError(SB),NOSPLIT,$0-48 + BL runtime·entersyscall(SB) + MOVD a1+8(FP), R2 + MOVD a2+16(FP), R3 + MOVD a3+24(FP), R4 + MOVD $0, R5 + MOVD $0, R6 + MOVD $0, R7 + MOVD trap+0(FP), R1 // syscall entry + SYSCALL + MOVD R2, r1+32(FP) + MOVD R3, r2+40(FP) + BL runtime·exitsyscall(SB) + RET + TEXT ·RawSyscall(SB),NOSPLIT,$0-56 BR syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 BR syscall·RawSyscall6(SB) + +TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48 + MOVD a1+8(FP), R2 + MOVD a2+16(FP), R3 + MOVD a3+24(FP), R4 + MOVD $0, R5 + MOVD $0, R6 + MOVD $0, R7 + MOVD trap+0(FP), R1 // syscall entry + SYSCALL + MOVD R2, r1+32(FP) + MOVD R3, r2+40(FP) + RET diff --git a/vendor/golang.org/x/sys/unix/cap_freebsd.go b/vendor/golang.org/x/sys/unix/cap_freebsd.go index 83b6bceab4..df52048773 100644 --- a/vendor/golang.org/x/sys/unix/cap_freebsd.go +++ b/vendor/golang.org/x/sys/unix/cap_freebsd.go @@ -7,7 +7,7 @@ package unix import ( - errorspkg "errors" + "errors" "fmt" ) @@ -60,26 +60,26 @@ func CapRightsSet(rights *CapRights, setrights []uint64) error { n := caparsize(rights) if n < capArSizeMin || n > capArSizeMax { - return errorspkg.New("bad rights size") + return errors.New("bad rights size") } for _, right := range setrights { if caprver(right) != CAP_RIGHTS_VERSION_00 { - return errorspkg.New("bad right version") + return errors.New("bad right version") } i, err := rightToIndex(right) if err != nil { return err } if i >= n { - return errorspkg.New("index overflow") + return errors.New("index overflow") } if capidxbit(rights.Rights[i]) != capidxbit(right) { - return errorspkg.New("index mismatch") + return errors.New("index mismatch") } rights.Rights[i] |= right if capidxbit(rights.Rights[i]) != capidxbit(right) { - return errorspkg.New("index mismatch (after assign)") + return errors.New("index mismatch (after assign)") } } @@ -95,26 +95,26 @@ func CapRightsClear(rights *CapRights, clearrights []uint64) error { n := caparsize(rights) if n < capArSizeMin || n > capArSizeMax { - return errorspkg.New("bad rights size") + return errors.New("bad rights size") } for _, right := range clearrights { if caprver(right) != CAP_RIGHTS_VERSION_00 { - return errorspkg.New("bad right version") + return errors.New("bad right version") } i, err := rightToIndex(right) if err != nil { return err } if i >= n { - return errorspkg.New("index overflow") + return errors.New("index overflow") } if capidxbit(rights.Rights[i]) != capidxbit(right) { - return errorspkg.New("index mismatch") + return errors.New("index mismatch") } rights.Rights[i] &= ^(right & 0x01FFFFFFFFFFFFFF) if capidxbit(rights.Rights[i]) != capidxbit(right) { - return errorspkg.New("index mismatch (after assign)") + return errors.New("index mismatch (after assign)") } } @@ -130,22 +130,22 @@ func CapRightsIsSet(rights *CapRights, setrights []uint64) (bool, error) { n := caparsize(rights) if n < capArSizeMin || n > capArSizeMax { - return false, errorspkg.New("bad rights size") + return false, errors.New("bad rights size") } for _, right := range setrights { if caprver(right) != CAP_RIGHTS_VERSION_00 { - return false, errorspkg.New("bad right version") + return false, errors.New("bad right version") } i, err := rightToIndex(right) if err != nil { return false, err } if i >= n { - return false, errorspkg.New("index overflow") + return false, errors.New("index overflow") } if capidxbit(rights.Rights[i]) != capidxbit(right) { - return false, errorspkg.New("index mismatch") + return false, errors.New("index mismatch") } if (rights.Rights[i] & right) != right { return false, nil diff --git a/vendor/golang.org/x/sys/unix/creds_test.go b/vendor/golang.org/x/sys/unix/creds_test.go deleted file mode 100644 index 4557ea4262..0000000000 --- a/vendor/golang.org/x/sys/unix/creds_test.go +++ /dev/null @@ -1,136 +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 - -package unix_test - -import ( - "bytes" - "net" - "os" - "syscall" - "testing" - - "golang.org/x/sys/unix" -) - -// TestSCMCredentials tests the sending and receiving of credentials -// (PID, UID, GID) in an ancillary message between two UNIX -// sockets. The SO_PASSCRED socket option is enabled on the sending -// socket for this to work. -func TestSCMCredentials(t *testing.T) { - socketTypeTests := []struct { - socketType int - dataLen int - }{ - { - unix.SOCK_STREAM, - 1, - }, { - unix.SOCK_DGRAM, - 0, - }, - } - - for _, tt := range socketTypeTests { - fds, err := unix.Socketpair(unix.AF_LOCAL, tt.socketType, 0) - if err != nil { - t.Fatalf("Socketpair: %v", err) - } - defer unix.Close(fds[0]) - defer unix.Close(fds[1]) - - err = unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_PASSCRED, 1) - if err != nil { - t.Fatalf("SetsockoptInt: %v", err) - } - - srvFile := os.NewFile(uintptr(fds[0]), "server") - defer srvFile.Close() - srv, err := net.FileConn(srvFile) - if err != nil { - t.Errorf("FileConn: %v", err) - return - } - defer srv.Close() - - cliFile := os.NewFile(uintptr(fds[1]), "client") - defer cliFile.Close() - cli, err := net.FileConn(cliFile) - if err != nil { - t.Errorf("FileConn: %v", err) - return - } - defer cli.Close() - - var ucred unix.Ucred - if os.Getuid() != 0 { - ucred.Pid = int32(os.Getpid()) - ucred.Uid = 0 - ucred.Gid = 0 - oob := unix.UnixCredentials(&ucred) - _, _, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) - if op, ok := err.(*net.OpError); ok { - err = op.Err - } - if sys, ok := err.(*os.SyscallError); ok { - err = sys.Err - } - if err != syscall.EPERM { - t.Fatalf("WriteMsgUnix failed with %v, want EPERM", err) - } - } - - ucred.Pid = int32(os.Getpid()) - ucred.Uid = uint32(os.Getuid()) - ucred.Gid = uint32(os.Getgid()) - oob := unix.UnixCredentials(&ucred) - - // On SOCK_STREAM, this is internally going to send a dummy byte - n, oobn, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) - if err != nil { - t.Fatalf("WriteMsgUnix: %v", err) - } - if n != 0 { - t.Fatalf("WriteMsgUnix n = %d, want 0", n) - } - if oobn != len(oob) { - t.Fatalf("WriteMsgUnix oobn = %d, want %d", oobn, len(oob)) - } - - oob2 := make([]byte, 10*len(oob)) - n, oobn2, flags, _, err := srv.(*net.UnixConn).ReadMsgUnix(nil, oob2) - if err != nil { - t.Fatalf("ReadMsgUnix: %v", err) - } - if flags != 0 { - t.Fatalf("ReadMsgUnix flags = 0x%x, want 0", flags) - } - if n != tt.dataLen { - t.Fatalf("ReadMsgUnix n = %d, want %d", n, tt.dataLen) - } - if oobn2 != oobn { - // without SO_PASSCRED set on the socket, ReadMsgUnix will - // return zero oob bytes - t.Fatalf("ReadMsgUnix oobn = %d, want %d", oobn2, oobn) - } - oob2 = oob2[:oobn2] - if !bytes.Equal(oob, oob2) { - t.Fatal("ReadMsgUnix oob bytes don't match") - } - - scm, err := unix.ParseSocketControlMessage(oob2) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - newUcred, err := unix.ParseUnixCredentials(&scm[0]) - if err != nil { - t.Fatalf("ParseUnixCredentials: %v", err) - } - if *newUcred != ucred { - t.Fatalf("ParseUnixCredentials = %+v, want %+v", newUcred, ucred) - } - } -} diff --git a/vendor/golang.org/x/sys/unix/dev_darwin_test.go b/vendor/golang.org/x/sys/unix/dev_darwin_test.go deleted file mode 100644 index 48d0448603..0000000000 --- a/vendor/golang.org/x/sys/unix/dev_darwin_test.go +++ /dev/null @@ -1,49 +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 unix_test - -import ( - "fmt" - "testing" - - "golang.org/x/sys/unix" -) - -func TestDevices(t *testing.T) { - testCases := []struct { - path string - major uint32 - minor uint32 - }{ - // Most of the device major/minor numbers on Darwin are - // dynamically generated by devfs. These are some well-known - // static numbers. - {"/dev/ttyp0", 4, 0}, - {"/dev/ttys0", 4, 48}, - {"/dev/ptyp0", 5, 0}, - {"/dev/ptyr0", 5, 32}, - } - for _, tc := range testCases { - t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { - var stat unix.Stat_t - err := unix.Stat(tc.path, &stat) - if err != nil { - t.Errorf("failed to stat device: %v", err) - return - } - - dev := uint64(stat.Rdev) - if unix.Major(dev) != tc.major { - t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) - } - if unix.Minor(dev) != tc.minor { - t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) - } - if unix.Mkdev(tc.major, tc.minor) != dev { - t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) - } - }) - } -} diff --git a/vendor/golang.org/x/sys/unix/dev_dragonfly_test.go b/vendor/golang.org/x/sys/unix/dev_dragonfly_test.go deleted file mode 100644 index 2caba08a8d..0000000000 --- a/vendor/golang.org/x/sys/unix/dev_dragonfly_test.go +++ /dev/null @@ -1,48 +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 unix_test - -import ( - "fmt" - "testing" - - "golang.org/x/sys/unix" -) - -func TestDevices(t *testing.T) { - testCases := []struct { - path string - major uint32 - minor uint32 - }{ - // Minor is a cookie instead of an index on DragonFlyBSD - {"/dev/null", 10, 0x00000002}, - {"/dev/random", 10, 0x00000003}, - {"/dev/urandom", 10, 0x00000004}, - {"/dev/zero", 10, 0x0000000c}, - {"/dev/bpf", 15, 0xffff00ff}, - } - for _, tc := range testCases { - t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { - var stat unix.Stat_t - err := unix.Stat(tc.path, &stat) - if err != nil { - t.Errorf("failed to stat device: %v", err) - return - } - - dev := uint64(stat.Rdev) - if unix.Major(dev) != tc.major { - t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) - } - if unix.Minor(dev) != tc.minor { - t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) - } - if unix.Mkdev(tc.major, tc.minor) != dev { - t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) - } - }) - } -} diff --git a/vendor/golang.org/x/sys/unix/dev_linux_test.go b/vendor/golang.org/x/sys/unix/dev_linux_test.go deleted file mode 100644 index 6e001f37ae..0000000000 --- a/vendor/golang.org/x/sys/unix/dev_linux_test.go +++ /dev/null @@ -1,51 +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 unix_test - -import ( - "fmt" - "testing" - - "golang.org/x/sys/unix" -) - -func TestDevices(t *testing.T) { - testCases := []struct { - path string - major uint32 - minor uint32 - }{ - // well known major/minor numbers according to - // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/admin-guide/devices.txt - {"/dev/null", 1, 3}, - {"/dev/zero", 1, 5}, - {"/dev/random", 1, 8}, - {"/dev/full", 1, 7}, - {"/dev/urandom", 1, 9}, - {"/dev/tty", 5, 0}, - } - for _, tc := range testCases { - t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { - var stat unix.Stat_t - err := unix.Stat(tc.path, &stat) - if err != nil { - t.Errorf("failed to stat device: %v", err) - return - } - - dev := uint64(stat.Rdev) - if unix.Major(dev) != tc.major { - t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) - } - if unix.Minor(dev) != tc.minor { - t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) - } - if unix.Mkdev(tc.major, tc.minor) != dev { - t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) - } - }) - - } -} diff --git a/vendor/golang.org/x/sys/unix/dev_netbsd_test.go b/vendor/golang.org/x/sys/unix/dev_netbsd_test.go deleted file mode 100644 index c39a80a48e..0000000000 --- a/vendor/golang.org/x/sys/unix/dev_netbsd_test.go +++ /dev/null @@ -1,50 +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 unix_test - -import ( - "fmt" - "testing" - - "golang.org/x/sys/unix" -) - -func TestDevices(t *testing.T) { - testCases := []struct { - path string - major uint32 - minor uint32 - }{ - // well known major/minor numbers according to /dev/MAKEDEV on - // NetBSD 7.0 - {"/dev/null", 2, 2}, - {"/dev/zero", 2, 12}, - {"/dev/ttyp0", 5, 0}, - {"/dev/ttyp1", 5, 1}, - {"/dev/random", 46, 0}, - {"/dev/urandom", 46, 1}, - } - for _, tc := range testCases { - t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { - var stat unix.Stat_t - err := unix.Stat(tc.path, &stat) - if err != nil { - t.Errorf("failed to stat device: %v", err) - return - } - - dev := uint64(stat.Rdev) - if unix.Major(dev) != tc.major { - t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) - } - if unix.Minor(dev) != tc.minor { - t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) - } - if unix.Mkdev(tc.major, tc.minor) != dev { - t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) - } - }) - } -} diff --git a/vendor/golang.org/x/sys/unix/dev_openbsd_test.go b/vendor/golang.org/x/sys/unix/dev_openbsd_test.go deleted file mode 100644 index 5635d271f4..0000000000 --- a/vendor/golang.org/x/sys/unix/dev_openbsd_test.go +++ /dev/null @@ -1,52 +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 unix_test - -import ( - "fmt" - "testing" - - "golang.org/x/sys/unix" -) - -func TestDevices(t *testing.T) { - testCases := []struct { - path string - major uint32 - minor uint32 - }{ - // well known major/minor numbers according to /dev/MAKEDEV on - // OpenBSD 6.0 - {"/dev/null", 2, 2}, - {"/dev/zero", 2, 12}, - {"/dev/ttyp0", 5, 0}, - {"/dev/ttyp1", 5, 1}, - {"/dev/random", 45, 0}, - {"/dev/srandom", 45, 1}, - {"/dev/urandom", 45, 2}, - {"/dev/arandom", 45, 3}, - } - for _, tc := range testCases { - t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { - var stat unix.Stat_t - err := unix.Stat(tc.path, &stat) - if err != nil { - t.Errorf("failed to stat device: %v", err) - return - } - - dev := uint64(stat.Rdev) - if unix.Major(dev) != tc.major { - t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) - } - if unix.Minor(dev) != tc.minor { - t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) - } - if unix.Mkdev(tc.major, tc.minor) != dev { - t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) - } - }) - } -} diff --git a/vendor/golang.org/x/sys/unix/dev_solaris_test.go b/vendor/golang.org/x/sys/unix/dev_solaris_test.go deleted file mode 100644 index db58c0d05e..0000000000 --- a/vendor/golang.org/x/sys/unix/dev_solaris_test.go +++ /dev/null @@ -1,49 +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 unix_test - -import ( - "fmt" - "testing" - - "golang.org/x/sys/unix" -) - -func TestDevices(t *testing.T) { - testCases := []struct { - path string - major uint32 - minor uint32 - }{ - // Well-known major/minor numbers on OpenSolaris according to - // /etc/name_to_major - {"/dev/zero", 134, 12}, - {"/dev/null", 134, 2}, - {"/dev/ptyp0", 172, 0}, - {"/dev/ttyp0", 175, 0}, - {"/dev/ttyp1", 175, 1}, - } - for _, tc := range testCases { - t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) { - var stat unix.Stat_t - err := unix.Stat(tc.path, &stat) - if err != nil { - t.Errorf("failed to stat device: %v", err) - return - } - - dev := uint64(stat.Rdev) - if unix.Major(dev) != tc.major { - t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major) - } - if unix.Minor(dev) != tc.minor { - t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor) - } - if unix.Mkdev(tc.major, tc.minor) != dev { - t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev) - } - }) - } -} diff --git a/vendor/golang.org/x/sys/unix/dirent.go b/vendor/golang.org/x/sys/unix/dirent.go index bd475812b7..95fd353171 100644 --- a/vendor/golang.org/x/sys/unix/dirent.go +++ b/vendor/golang.org/x/sys/unix/dirent.go @@ -6,97 +6,12 @@ package unix -import "unsafe" - -// readInt returns the size-bytes unsigned integer in native byte order at offset off. -func readInt(b []byte, off, size uintptr) (u uint64, ok bool) { - if len(b) < int(off+size) { - return 0, false - } - if isBigEndian { - return readIntBE(b[off:], size), true - } - return readIntLE(b[off:], size), true -} - -func readIntBE(b []byte, size uintptr) uint64 { - switch size { - case 1: - return uint64(b[0]) - case 2: - _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 - return uint64(b[1]) | uint64(b[0])<<8 - case 4: - _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 - return uint64(b[3]) | uint64(b[2])<<8 | uint64(b[1])<<16 | uint64(b[0])<<24 - case 8: - _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 - return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | - uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 - default: - panic("syscall: readInt with unsupported size") - } -} - -func readIntLE(b []byte, size uintptr) uint64 { - switch size { - case 1: - return uint64(b[0]) - case 2: - _ = b[1] // bounds check hint to compiler; see golang.org/issue/14808 - return uint64(b[0]) | uint64(b[1])<<8 - case 4: - _ = b[3] // bounds check hint to compiler; see golang.org/issue/14808 - return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 - case 8: - _ = b[7] // bounds check hint to compiler; see golang.org/issue/14808 - 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 - default: - panic("syscall: readInt with unsupported size") - } -} +import "syscall" // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number of // bytes consumed from buf, the number of entries added // to names, and the new names slice. func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string) { - origlen := len(buf) - count = 0 - for max != 0 && len(buf) > 0 { - reclen, ok := direntReclen(buf) - if !ok || reclen > uint64(len(buf)) { - return origlen, count, names - } - rec := buf[:reclen] - buf = buf[reclen:] - ino, ok := direntIno(rec) - if !ok { - break - } - if ino == 0 { // File absent in directory. - continue - } - const namoff = uint64(unsafe.Offsetof(Dirent{}.Name)) - namlen, ok := direntNamlen(rec) - if !ok || namoff+namlen > uint64(len(rec)) { - break - } - name := rec[namoff : namoff+namlen] - for i, c := range name { - if c == 0 { - name = name[:i] - break - } - } - // Check for useless names before allocating a string. - if string(name) == "." || string(name) == ".." { - continue - } - max-- - count++ - names = append(names, string(name)) - } - return origlen - len(buf), count, names + return syscall.ParseDirent(buf, max, names) } diff --git a/vendor/golang.org/x/sys/unix/env_unix.go b/vendor/golang.org/x/sys/unix/env_unix.go index 2e06b33f2e..706b3cd1dd 100644 --- a/vendor/golang.org/x/sys/unix/env_unix.go +++ b/vendor/golang.org/x/sys/unix/env_unix.go @@ -25,3 +25,7 @@ func Clearenv() { func Environ() []string { return syscall.Environ() } + +func Unsetenv(key string) error { + return syscall.Unsetenv(key) +} diff --git a/vendor/golang.org/x/sys/unix/env_unset.go b/vendor/golang.org/x/sys/unix/env_unset.go deleted file mode 100644 index c44fdc4afa..0000000000 --- a/vendor/golang.org/x/sys/unix/env_unset.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2014 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 go1.4 - -package unix - -import "syscall" - -func Unsetenv(key string) error { - // This was added in Go 1.4. - return syscall.Unsetenv(key) -} diff --git a/vendor/golang.org/x/sys/unix/export_test.go b/vendor/golang.org/x/sys/unix/export_test.go deleted file mode 100644 index e8024690df..0000000000 --- a/vendor/golang.org/x/sys/unix/export_test.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2015 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 dragonfly freebsd linux netbsd openbsd solaris - -package unix - -var Itoa = itoa diff --git a/vendor/golang.org/x/sys/unix/flock.go b/vendor/golang.org/x/sys/unix/fcntl.go similarity index 74% rename from vendor/golang.org/x/sys/unix/flock.go rename to vendor/golang.org/x/sys/unix/fcntl.go index 2994ce75f2..0c58c7e1e5 100644 --- a/vendor/golang.org/x/sys/unix/flock.go +++ b/vendor/golang.org/x/sys/unix/fcntl.go @@ -12,6 +12,12 @@ import "unsafe" // systems by flock_linux_32bit.go to be SYS_FCNTL64. var fcntl64Syscall uintptr = SYS_FCNTL +// FcntlInt performs a fcntl syscall on fd with the provided command and argument. +func FcntlInt(fd uintptr, cmd, arg int) (int, error) { + valptr, _, err := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(arg)) + return int(valptr), err +} + // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { _, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(unsafe.Pointer(lk))) diff --git a/vendor/golang.org/x/sys/unix/flock_linux_32bit.go b/vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go similarity index 100% rename from vendor/golang.org/x/sys/unix/flock_linux_32bit.go rename to vendor/golang.org/x/sys/unix/fcntl_linux_32bit.go diff --git a/vendor/golang.org/x/sys/unix/gccgo.go b/vendor/golang.org/x/sys/unix/gccgo.go index 40bed3fa80..50062e3c74 100644 --- a/vendor/golang.org/x/sys/unix/gccgo.go +++ b/vendor/golang.org/x/sys/unix/gccgo.go @@ -11,9 +11,19 @@ import "syscall" // We can't use the gc-syntax .s files for gccgo. On the plus side // much of the functionality can be written directly in Go. +//extern gccgoRealSyscallNoError +func realSyscallNoError(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r uintptr) + //extern gccgoRealSyscall func realSyscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r, errno uintptr) +func SyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) { + syscall.Entersyscall() + r := realSyscallNoError(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) + syscall.Exitsyscall() + return r, 0 +} + func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { syscall.Entersyscall() r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) @@ -35,6 +45,11 @@ func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, return r, 0, syscall.Errno(errno) } +func RawSyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) { + r := realSyscallNoError(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) + return r, 0 +} + func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) { r, errno := realSyscall(trap, a1, a2, a3, 0, 0, 0, 0, 0, 0) return r, 0, syscall.Errno(errno) diff --git a/vendor/golang.org/x/sys/unix/gccgo_c.c b/vendor/golang.org/x/sys/unix/gccgo_c.c index 99a774f2be..24e96b1198 100644 --- a/vendor/golang.org/x/sys/unix/gccgo_c.c +++ b/vendor/golang.org/x/sys/unix/gccgo_c.c @@ -31,6 +31,12 @@ gccgoRealSyscall(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintp return r; } +uintptr_t +gccgoRealSyscallNoError(uintptr_t trap, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7, uintptr_t a8, uintptr_t a9) +{ + return syscall(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9); +} + // Define the use function in C so that it is not inlined. extern void use(void *) __asm__ (GOSYM_PREFIX GOPKGPATH ".use") __attribute__((noinline)); diff --git a/vendor/golang.org/x/sys/unix/mkall.sh b/vendor/golang.org/x/sys/unix/mkall.sh index 00b7ce7ac1..1715122bd4 100755 --- a/vendor/golang.org/x/sys/unix/mkall.sh +++ b/vendor/golang.org/x/sys/unix/mkall.sh @@ -80,12 +80,6 @@ darwin_arm64) mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; -dragonfly_386) - mkerrors="$mkerrors -m32" - mksyscall="./mksyscall.pl -l32 -dragonfly" - mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" - mktypes="GOARCH=$GOARCH go tool cgo -godefs" - ;; dragonfly_amd64) mkerrors="$mkerrors -m64" mksyscall="./mksyscall.pl -dragonfly" diff --git a/vendor/golang.org/x/sys/unix/mkerrors.sh b/vendor/golang.org/x/sys/unix/mkerrors.sh index 2db9e0adce..ddc50a018a 100755 --- a/vendor/golang.org/x/sys/unix/mkerrors.sh +++ b/vendor/golang.org/x/sys/unix/mkerrors.sh @@ -48,7 +48,9 @@ includes_Darwin=' #include <sys/sysctl.h> #include <sys/mman.h> #include <sys/mount.h> +#include <sys/utsname.h> #include <sys/wait.h> +#include <sys/xattr.h> #include <net/bpf.h> #include <net/if.h> #include <net/if_types.h> @@ -170,6 +172,8 @@ struct ltchars { #include <linux/filter.h> #include <linux/fs.h> #include <linux/keyctl.h> +#include <linux/magic.h> +#include <linux/netfilter/nfnetlink.h> #include <linux/netlink.h> #include <linux/perf_event.h> #include <linux/random.h> @@ -186,7 +190,9 @@ struct ltchars { #include <linux/vm_sockets.h> #include <linux/taskstats.h> #include <linux/genetlink.h> +#include <linux/stat.h> #include <linux/watchdog.h> +#include <linux/hdreg.h> #include <net/route.h> #include <asm/termbits.h> @@ -362,6 +368,7 @@ ccflags="$@" $2 ~ /^IGN/ || $2 ~ /^IX(ON|ANY|OFF)$/ || $2 ~ /^IN(LCR|PCK)$/ || + $2 !~ "X86_CR3_PCID_NOFLUSH" && $2 ~ /(^FLU?SH)|(FLU?SH$)/ || $2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ || $2 == "BRKINT" || @@ -380,13 +387,16 @@ ccflags="$@" $2 ~ /^TC[IO](ON|OFF)$/ || $2 ~ /^IN_/ || $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || - $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ || + $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|T?PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ || + $2 ~ /^TP_STATUS_/ || $2 ~ /^FALLOC_/ || $2 == "ICMPV6_FILTER" || $2 == "SOMAXCONN" || $2 == "NAME_MAX" || $2 == "IFNAMSIZ" || - $2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ || + $2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ || + $2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ || + $2 ~ /^HW_MACHINE$/ || $2 ~ /^SYSCTL_VERS/ || $2 ~ /^(MS|MNT|UMOUNT)_/ || $2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ || @@ -420,15 +430,21 @@ ccflags="$@" $2 ~ /^PERF_EVENT_IOC_/ || $2 ~ /^SECCOMP_MODE_/ || $2 ~ /^SPLICE_/ || + $2 !~ /^AUDIT_RECORD_MAGIC/ && + $2 ~ /^[A-Z0-9_]+_MAGIC2?$/ || $2 ~ /^(VM|VMADDR)_/ || $2 ~ /^IOCTL_VM_SOCKETS_/ || $2 ~ /^(TASKSTATS|TS)_/ || + $2 ~ /^CGROUPSTATS_/ || $2 ~ /^GENL_/ || + $2 ~ /^STATX_/ || $2 ~ /^UTIME_/ || - $2 ~ /^XATTR_(CREATE|REPLACE)/ || + $2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ || $2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ || $2 ~ /^FSOPT_/ || $2 ~ /^WDIOC_/ || + $2 ~ /^NFN/ || + $2 ~ /^(HDIO|WIN|SMART)_/ || $2 !~ "WMESGLEN" && $2 ~ /^W[A-Z0-9]+$/ || $2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf("\t%s = C.%s\n", $2, $2)} @@ -498,21 +514,26 @@ echo ')' enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below -int errors[] = { +struct tuple { + int num; + const char *name; +}; + +struct tuple errors[] = { " for i in $errors do - echo -E ' '$i, + echo -E ' {'$i', "'$i'" },' done echo -E " }; -int signals[] = { +struct tuple signals[] = { " for i in $signals do - echo -E ' '$i, + echo -E ' {'$i', "'$i'" },' done # Use -E because on some systems bash builtin interprets \n itself. @@ -520,9 +541,9 @@ int signals[] = { }; static int -intcmp(const void *a, const void *b) +tuplecmp(const void *a, const void *b) { - return *(int*)a - *(int*)b; + return ((struct tuple *)a)->num - ((struct tuple *)b)->num; } int @@ -532,26 +553,34 @@ main(void) char buf[1024], *p; printf("\n\n// Error table\n"); - printf("var errors = [...]string {\n"); - qsort(errors, nelem(errors), sizeof errors[0], intcmp); + printf("var errorList = [...]struct {\n"); + printf("\tnum syscall.Errno\n"); + printf("\tname string\n"); + printf("\tdesc string\n"); + printf("} {\n"); + qsort(errors, nelem(errors), sizeof errors[0], tuplecmp); for(i=0; i<nelem(errors); i++) { - e = errors[i]; - if(i > 0 && errors[i-1] == e) + e = errors[i].num; + if(i > 0 && errors[i-1].num == e) continue; strcpy(buf, strerror(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; - printf("\t%d: \"%s\",\n", e, buf); + printf("\t{ %d, \"%s\", \"%s\" },\n", e, errors[i].name, buf); } printf("}\n\n"); printf("\n\n// Signal table\n"); - printf("var signals = [...]string {\n"); - qsort(signals, nelem(signals), sizeof signals[0], intcmp); + printf("var signalList = [...]struct {\n"); + printf("\tnum syscall.Signal\n"); + printf("\tname string\n"); + printf("\tdesc string\n"); + printf("} {\n"); + qsort(signals, nelem(signals), sizeof signals[0], tuplecmp); for(i=0; i<nelem(signals); i++) { - e = signals[i]; - if(i > 0 && signals[i-1] == e) + e = signals[i].num; + if(i > 0 && signals[i-1].num == e) continue; strcpy(buf, strsignal(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. @@ -561,7 +590,7 @@ main(void) p = strrchr(buf, ":"[0]); if(p) *p = '\0'; - printf("\t%d: \"%s\",\n", e, buf); + printf("\t{ %d, \"%s\", \"%s\" },\n", e, signals[i].name, buf); } printf("}\n\n"); diff --git a/vendor/golang.org/x/sys/unix/mkpost.go b/vendor/golang.org/x/sys/unix/mkpost.go index dbdfd0a3f1..7e5c22c473 100644 --- a/vendor/golang.org/x/sys/unix/mkpost.go +++ b/vendor/golang.org/x/sys/unix/mkpost.go @@ -42,6 +42,10 @@ func main() { log.Fatal(err) } + // Intentionally export __val fields in Fsid and Sigset_t + valRegex := regexp.MustCompile(`type (Fsid|Sigset_t) struct {(\s+)X__val(\s+\S+\s+)}`) + b = valRegex.ReplaceAll(b, []byte("type $1 struct {${2}Val$3}")) + // If we have empty Ptrace structs, we should delete them. Only s390x emits // nonempty Ptrace structs. ptraceRexexp := regexp.MustCompile(`type Ptrace((Psw|Fpregs|Per) struct {\s*})`) @@ -61,16 +65,17 @@ func main() { convertUtsnameRegex := regexp.MustCompile(`((Sys|Node|Domain)name|Release|Version|Machine)(\s+)\[(\d+)\]u?int8`) b = convertUtsnameRegex.ReplaceAll(b, []byte("$1$3[$4]byte")) - // We refuse to export private fields on s390x - if goarch == "s390x" && goos == "linux" { - // Remove cgo padding fields - removeFieldsRegex := regexp.MustCompile(`Pad_cgo_\d+`) - b = removeFieldsRegex.ReplaceAll(b, []byte("_")) + // Remove spare fields (e.g. in Statx_t) + spareFieldsRegex := regexp.MustCompile(`X__spare\S*`) + b = spareFieldsRegex.ReplaceAll(b, []byte("_")) - // Remove padding, hidden, or unused fields - removeFieldsRegex = regexp.MustCompile(`X_\S+`) - b = removeFieldsRegex.ReplaceAll(b, []byte("_")) - } + // Remove cgo padding fields + removePaddingFieldsRegex := regexp.MustCompile(`Pad_cgo_\d+`) + b = removePaddingFieldsRegex.ReplaceAll(b, []byte("_")) + + // Remove padding, hidden, or unused fields + removeFieldsRegex = regexp.MustCompile(`\b(X_\S+|Padding)`) + b = removeFieldsRegex.ReplaceAll(b, []byte("_")) // Remove the first line of warning from cgo b = b[bytes.IndexByte(b, '\n')+1:] diff --git a/vendor/golang.org/x/sys/unix/mksyscall.pl b/vendor/golang.org/x/sys/unix/mksyscall.pl index fb929b4ce1..1f6b926f8c 100755 --- a/vendor/golang.org/x/sys/unix/mksyscall.pl +++ b/vendor/golang.org/x/sys/unix/mksyscall.pl @@ -210,7 +210,15 @@ ($) # Determine which form to use; pad args with zeros. my $asm = "Syscall"; if ($nonblock) { - $asm = "RawSyscall"; + if ($errvar eq "" && $ENV{'GOOS'} eq "linux") { + $asm = "RawSyscallNoError"; + } else { + $asm = "RawSyscall"; + } + } else { + if ($errvar eq "" && $ENV{'GOOS'} eq "linux") { + $asm = "SyscallNoError"; + } } if(@args <= 3) { while(@args < 3) { @@ -284,7 +292,12 @@ ($) if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { $text .= "\t$call\n"; } else { - $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; + if ($errvar eq "" && $ENV{'GOOS'} eq "linux") { + # raw syscall without error on Linux, see golang.org/issue/22924 + $text .= "\t$ret[0], $ret[1] := $call\n"; + } else { + $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; + } } $text .= $body; diff --git a/vendor/golang.org/x/sys/unix/mmap_unix_test.go b/vendor/golang.org/x/sys/unix/mmap_unix_test.go deleted file mode 100644 index 3258ca3284..0000000000 --- a/vendor/golang.org/x/sys/unix/mmap_unix_test.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2014 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 dragonfly freebsd linux netbsd openbsd solaris - -package unix_test - -import ( - "testing" - - "golang.org/x/sys/unix" -) - -func TestMmap(t *testing.T) { - b, err := unix.Mmap(-1, 0, unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE) - if err != nil { - t.Fatalf("Mmap: %v", err) - } - if err := unix.Mprotect(b, unix.PROT_READ|unix.PROT_WRITE); err != nil { - t.Fatalf("Mprotect: %v", err) - } - - b[0] = 42 - - if err := unix.Msync(b, unix.MS_SYNC); err != nil { - t.Fatalf("Msync: %v", err) - } - if err := unix.Madvise(b, unix.MADV_DONTNEED); err != nil { - t.Fatalf("Madvise: %v", err) - } - if err := unix.Munmap(b); err != nil { - t.Fatalf("Munmap: %v", err) - } -} diff --git a/vendor/golang.org/x/sys/unix/openbsd_pledge.go b/vendor/golang.org/x/sys/unix/openbsd_pledge.go index db4f72ea9c..9b1e86a12b 100644 --- a/vendor/golang.org/x/sys/unix/openbsd_pledge.go +++ b/vendor/golang.org/x/sys/unix/openbsd_pledge.go @@ -13,7 +13,7 @@ import ( ) const ( - SYS_PLEDGE = 108 + _SYS_PLEDGE = 108 ) // Pledge implements the pledge syscall. For more information see pledge(2). @@ -30,7 +30,7 @@ func Pledge(promises string, paths []string) error { } pathsUnsafe = unsafe.Pointer(&pathsPtr[0]) } - _, _, e := syscall.Syscall(SYS_PLEDGE, uintptr(promisesUnsafe), uintptr(pathsUnsafe), 0) + _, _, e := syscall.Syscall(_SYS_PLEDGE, uintptr(promisesUnsafe), uintptr(pathsUnsafe), 0) if e != 0 { return e } diff --git a/vendor/golang.org/x/sys/unix/openbsd_test.go b/vendor/golang.org/x/sys/unix/openbsd_test.go deleted file mode 100644 index 734d765857..0000000000 --- a/vendor/golang.org/x/sys/unix/openbsd_test.go +++ /dev/null @@ -1,113 +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. - -// +build openbsd - -// This, on the face of it, bizarre testing mechanism is necessary because -// the only reliable way to gauge whether or not a pledge(2) call has succeeded -// is that the program has been killed as a result of breaking its pledge. - -package unix_test - -import ( - "flag" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "testing" - - "golang.org/x/sys/unix" -) - -type testProc struct { - fn func() // should always exit instead of returning - cleanup func() error // for instance, delete coredumps from testing pledge - success bool // whether zero-exit means success or failure -} - -var ( - testProcs = map[string]testProc{} - procName = "" -) - -const ( - optName = "sys-unix-internal-procname" -) - -func init() { - flag.StringVar(&procName, optName, "", "internal use only") -} - -// testCmd generates a proper command that, when executed, runs the test -// corresponding to the given key. -func testCmd(procName string) (*exec.Cmd, error) { - exe, err := filepath.Abs(os.Args[0]) - if err != nil { - return nil, err - } - cmd := exec.Command(exe, "-"+optName+"="+procName) - cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr - return cmd, nil -} - -// ExitsCorrectly is a comprehensive, one-line-of-use wrapper for testing -// a testProc with a key. -func ExitsCorrectly(procName string, t *testing.T) { - s := testProcs[procName] - c, err := testCmd(procName) - defer func() { - if s.cleanup() != nil { - t.Fatalf("Failed to run cleanup for %s", procName) - } - }() - if err != nil { - t.Fatalf("Failed to construct command for %s", procName) - } - if (c.Run() == nil) != s.success { - result := "succeed" - if !s.success { - result = "fail" - } - t.Fatalf("Process did not %s when it was supposed to", result) - } -} - -func TestMain(m *testing.M) { - flag.Parse() - if procName != "" { - testProcs[procName].fn() - } - os.Exit(m.Run()) -} - -// For example, add a test for pledge. -func init() { - testProcs["pledge"] = testProc{ - func() { - fmt.Println(unix.Pledge("", nil)) - os.Exit(0) - }, - func() error { - files, err := ioutil.ReadDir(".") - if err != nil { - return err - } - for _, file := range files { - if filepath.Ext(file.Name()) == ".core" { - if err := os.Remove(file.Name()); err != nil { - return err - } - } - } - return nil - }, - false, - } -} - -func TestPledge(t *testing.T) { - ExitsCorrectly("pledge", t) -} diff --git a/vendor/golang.org/x/sys/unix/syscall.go b/vendor/golang.org/x/sys/unix/syscall.go index 857d2a42d4..ef35fce804 100644 --- a/vendor/golang.org/x/sys/unix/syscall.go +++ b/vendor/golang.org/x/sys/unix/syscall.go @@ -11,24 +11,27 @@ // system, set $GOOS and $GOARCH to the desired system. For example, if // you want to view documentation for freebsd/arm on linux/amd64, set $GOOS // to freebsd and $GOARCH to arm. +// // The primary use of this package is inside other packages that provide a more // portable interface to the system, such as "os", "time" and "net". Use // those packages rather than this one if you can. +// // For details of the functions and data types in this package consult // the manuals for the appropriate operating system. +// // These calls return err == nil to indicate success; otherwise // err represents an operating system error describing the failure and // holds a value of type syscall.Errno. package unix // import "golang.org/x/sys/unix" +import "strings" + // ByteSliceFromString returns a NUL-terminated slice of bytes // containing the text of s. If s contains a NUL byte at any // location, it returns (nil, EINVAL). func ByteSliceFromString(s string) ([]byte, error) { - for i := 0; i < len(s); i++ { - if s[i] == 0 { - return nil, EINVAL - } + if strings.IndexByte(s, 0) != -1 { + return nil, EINVAL } a := make([]byte, len(s)+1) copy(a, s) diff --git a/vendor/golang.org/x/sys/unix/syscall_bsd.go b/vendor/golang.org/x/sys/unix/syscall_bsd.go index 47b0598401..53fb851823 100644 --- a/vendor/golang.org/x/sys/unix/syscall_bsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_bsd.go @@ -311,45 +311,16 @@ func Getsockname(fd int) (sa Sockaddr, err error) { //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) -func GetsockoptByte(fd, level, opt int) (value byte, err error) { - var n byte - vallen := _Socklen(1) - err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) - return n, err -} - -func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) { - vallen := _Socklen(4) - err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) - return value, err -} - -func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) { - var value IPMreq - vallen := _Socklen(SizeofIPMreq) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) { - var value IPv6Mreq - vallen := _Socklen(SizeofIPv6Mreq) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) { - var value IPv6MTUInfo - vallen := _Socklen(SizeofIPv6MTUInfo) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) { - var value ICMPv6Filter - vallen := _Socklen(SizeofICMPv6Filter) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err +// GetsockoptString returns the string value of the socket option opt for the +// socket associated with fd at the given socket level. +func GetsockoptString(fd, level, opt int) (string, error) { + buf := make([]byte, 256) + vallen := _Socklen(len(buf)) + err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen) + if err != nil { + return "", err + } + return string(buf[:vallen-1]), nil } //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_bsd_test.go b/vendor/golang.org/x/sys/unix/syscall_bsd_test.go deleted file mode 100644 index d8085a0729..0000000000 --- a/vendor/golang.org/x/sys/unix/syscall_bsd_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2014 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 dragonfly freebsd openbsd - -package unix_test - -import ( - "os/exec" - "runtime" - "testing" - - "golang.org/x/sys/unix" -) - -const MNT_WAIT = 1 -const MNT_NOWAIT = 2 - -func TestGetfsstat(t *testing.T) { - const flags = MNT_NOWAIT // see golang.org/issue/16937 - n, err := unix.Getfsstat(nil, flags) - if err != nil { - t.Fatal(err) - } - - data := make([]unix.Statfs_t, n) - n2, err := unix.Getfsstat(data, flags) - if err != nil { - t.Fatal(err) - } - if n != n2 { - t.Errorf("Getfsstat(nil) = %d, but subsequent Getfsstat(slice) = %d", n, n2) - } - for i, stat := range data { - if stat == (unix.Statfs_t{}) { - t.Errorf("index %v is an empty Statfs_t struct", i) - } - } - if t.Failed() { - for i, stat := range data[:n2] { - t.Logf("data[%v] = %+v", i, stat) - } - mount, err := exec.Command("mount").CombinedOutput() - if err != nil { - t.Logf("mount: %v\n%s", err, mount) - } else { - t.Logf("mount: %s", mount) - } - } -} - -func TestSysctlRaw(t *testing.T) { - if runtime.GOOS == "openbsd" { - t.Skip("kern.proc.pid does not exist on OpenBSD") - } - - _, err := unix.SysctlRaw("kern.proc.pid", unix.Getpid()) - if err != nil { - t.Fatal(err) - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin.go b/vendor/golang.org/x/sys/unix/syscall_darwin.go index 9a6783e9b9..79e94767de 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin.go @@ -13,7 +13,7 @@ package unix import ( - errorspkg "errors" + "errors" "syscall" "unsafe" ) @@ -36,6 +36,7 @@ func Getwd() (string, error) { return "", ENOTSUP } +// SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. type SockaddrDatalink struct { Len uint8 Family uint8 @@ -76,18 +77,6 @@ func nametomib(name string) (mib []_C_int, err error) { return buf[0 : n/siz], nil } -func direntIno(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) -} - -func direntReclen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) -} - -func direntNamlen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) -} - //sys ptrace(request int, pid int, addr uintptr, data uintptr) (err error) func PtraceAttach(pid int) (err error) { return ptrace(PT_ATTACH, pid, 0, 0) } func PtraceDetach(pid int) (err error) { return ptrace(PT_DETACH, pid, 0, 0) } @@ -109,7 +98,7 @@ type attrList struct { func getAttrList(path string, attrList attrList, attrBuf []byte, options uint) (attrs [][]byte, err error) { if len(attrBuf) < 4 { - return nil, errorspkg.New("attrBuf too small") + return nil, errors.New("attrBuf too small") } attrList.bitmapCount = attrBitMapCount @@ -145,12 +134,12 @@ func getAttrList(path string, attrList attrList, attrBuf []byte, options uint) ( for i := uint32(0); int(i) < len(dat); { header := dat[i:] if len(header) < 8 { - return attrs, errorspkg.New("truncated attribute header") + return attrs, errors.New("truncated attribute header") } datOff := *(*int32)(unsafe.Pointer(&header[0])) attrLen := *(*uint32)(unsafe.Pointer(&header[4])) if datOff < 0 || uint32(datOff)+attrLen > uint32(len(dat)) { - return attrs, errorspkg.New("truncated results; attrBuf too small") + return attrs, errors.New("truncated results; attrBuf too small") } end := uint32(datOff) + attrLen attrs = append(attrs, dat[datOff:end]) @@ -187,6 +176,88 @@ func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { return } +func xattrPointer(dest []byte) *byte { + // It's only when dest is set to NULL that the OS X implementations of + // getxattr() and listxattr() return the current sizes of the named attributes. + // An empty byte array is not sufficient. To maintain the same behaviour as the + // linux implementation, we wrap around the system calls and pass in NULL when + // dest is empty. + var destp *byte + if len(dest) > 0 { + destp = &dest[0] + } + return destp +} + +//sys getxattr(path string, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) + +func Getxattr(path string, attr string, dest []byte) (sz int, err error) { + return getxattr(path, attr, xattrPointer(dest), len(dest), 0, 0) +} + +func Lgetxattr(link string, attr string, dest []byte) (sz int, err error) { + return getxattr(link, attr, xattrPointer(dest), len(dest), 0, XATTR_NOFOLLOW) +} + +//sys setxattr(path string, attr string, data *byte, size int, position uint32, options int) (err error) + +func Setxattr(path string, attr string, data []byte, flags int) (err error) { + // The parameters for the OS X implementation vary slightly compared to the + // linux system call, specifically the position parameter: + // + // linux: + // int setxattr( + // const char *path, + // const char *name, + // const void *value, + // size_t size, + // int flags + // ); + // + // darwin: + // int setxattr( + // const char *path, + // const char *name, + // void *value, + // size_t size, + // u_int32_t position, + // int options + // ); + // + // position specifies the offset within the extended attribute. In the + // current implementation, only the resource fork extended attribute makes + // use of this argument. For all others, position is reserved. We simply + // default to setting it to zero. + return setxattr(path, attr, xattrPointer(data), len(data), 0, flags) +} + +func Lsetxattr(link string, attr string, data []byte, flags int) (err error) { + return setxattr(link, attr, xattrPointer(data), len(data), 0, flags|XATTR_NOFOLLOW) +} + +//sys removexattr(path string, attr string, options int) (err error) + +func Removexattr(path string, attr string) (err error) { + // We wrap around and explicitly zero out the options provided to the OS X + // implementation of removexattr, we do so for interoperability with the + // linux variant. + return removexattr(path, attr, 0) +} + +func Lremovexattr(link string, attr string) (err error) { + return removexattr(link, attr, XATTR_NOFOLLOW) +} + +//sys listxattr(path string, dest *byte, size int, options int) (sz int, err error) + +func Listxattr(path string, dest []byte) (sz int, err error) { + return listxattr(path, xattrPointer(dest), len(dest), 0) +} + +func Llistxattr(link string, dest []byte) (sz int, err error) { + return listxattr(link, xattrPointer(dest), len(dest), XATTR_NOFOLLOW) +} + func setattrlistTimes(path string, times []Timespec, flags int) error { _p0, err := BytePtrFromString(path) if err != nil { @@ -270,6 +341,52 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { return &value, err } +func Uname(uname *Utsname) error { + mib := []_C_int{CTL_KERN, KERN_OSTYPE} + n := unsafe.Sizeof(uname.Sysname) + if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_HOSTNAME} + n = unsafe.Sizeof(uname.Nodename) + if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_OSRELEASE} + n = unsafe.Sizeof(uname.Release) + if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_VERSION} + n = unsafe.Sizeof(uname.Version) + if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil { + return err + } + + // The version might have newlines or tabs in it, convert them to + // spaces. + for i, b := range uname.Version { + if b == '\n' || b == '\t' { + if i == len(uname.Version)-1 { + uname.Version[i] = 0 + } else { + uname.Version[i] = ' ' + } + } + } + + mib = []_C_int{CTL_HW, HW_MACHINE} + n = unsafe.Sizeof(uname.Machine) + if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil { + return err + } + + return nil +} + /* * Exposed directly */ @@ -295,6 +412,7 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 +//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 //sys Fstatfs(fd int, stat *Statfs_t) (err error) = SYS_FSTATFS64 //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) @@ -411,13 +529,9 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { // Watchevent // Waitevent // Modwatch -// Getxattr // Fgetxattr -// Setxattr // Fsetxattr -// Removexattr // Fremovexattr -// Listxattr // Flistxattr // Fsctl // Initgroups diff --git a/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go b/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go index 47ab664859..faae207a47 100644 --- a/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go +++ b/vendor/golang.org/x/sys/unix/syscall_darwin_arm.go @@ -60,3 +60,7 @@ func sendfile(outfd int, infd int, offset *int64, count int) (written int, err e } func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) // sic + +// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions +// of darwin/arm the syscall is called sysctl instead of __sysctl. +const SYS___SYSCTL = SYS_SYSCTL diff --git a/vendor/golang.org/x/sys/unix/syscall_dragonfly.go b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go index 49c65ea61b..b5072de285 100644 --- a/vendor/golang.org/x/sys/unix/syscall_dragonfly.go +++ b/vendor/golang.org/x/sys/unix/syscall_dragonfly.go @@ -14,6 +14,7 @@ package unix import "unsafe" +// SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. type SockaddrDatalink struct { Len uint8 Family uint8 @@ -56,22 +57,6 @@ func nametomib(name string) (mib []_C_int, err error) { return buf[0 : n/siz], nil } -func direntIno(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) -} - -func direntReclen(buf []byte) (uint64, bool) { - namlen, ok := direntNamlen(buf) - if !ok { - return 0, false - } - return (16 + namlen + 1 + 7) &^ 7, true -} - -func direntNamlen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) -} - //sysnb pipe() (r int, w int, err error) func Pipe(p []int) (err error) { @@ -110,6 +95,23 @@ func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) { return } +const ImplementsGetwd = true + +//sys Getcwd(buf []byte) (n int, err error) = SYS___GETCWD + +func Getwd() (string, error) { + var buf [PathMax]byte + _, err := Getcwd(buf[0:]) + if err != nil { + return "", err + } + n := clen(buf[:]) + if n < 1 { + return "", EINVAL + } + return string(buf[:n]), nil +} + func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { var _p0 unsafe.Pointer var bufsize uintptr @@ -169,6 +171,69 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { return &value, err } +func sysctlUname(mib []_C_int, old *byte, oldlen *uintptr) error { + err := sysctl(mib, old, oldlen, nil, 0) + if err != nil { + // Utsname members on Dragonfly are only 32 bytes and + // the syscall returns ENOMEM in case the actual value + // is longer. + if err == ENOMEM { + err = nil + } + } + return err +} + +func Uname(uname *Utsname) error { + mib := []_C_int{CTL_KERN, KERN_OSTYPE} + n := unsafe.Sizeof(uname.Sysname) + if err := sysctlUname(mib, &uname.Sysname[0], &n); err != nil { + return err + } + uname.Sysname[unsafe.Sizeof(uname.Sysname)-1] = 0 + + mib = []_C_int{CTL_KERN, KERN_HOSTNAME} + n = unsafe.Sizeof(uname.Nodename) + if err := sysctlUname(mib, &uname.Nodename[0], &n); err != nil { + return err + } + uname.Nodename[unsafe.Sizeof(uname.Nodename)-1] = 0 + + mib = []_C_int{CTL_KERN, KERN_OSRELEASE} + n = unsafe.Sizeof(uname.Release) + if err := sysctlUname(mib, &uname.Release[0], &n); err != nil { + return err + } + uname.Release[unsafe.Sizeof(uname.Release)-1] = 0 + + mib = []_C_int{CTL_KERN, KERN_VERSION} + n = unsafe.Sizeof(uname.Version) + if err := sysctlUname(mib, &uname.Version[0], &n); err != nil { + return err + } + + // The version might have newlines or tabs in it, convert them to + // spaces. + for i, b := range uname.Version { + if b == '\n' || b == '\t' { + if i == len(uname.Version)-1 { + uname.Version[i] = 0 + } else { + uname.Version[i] = ' ' + } + } + } + + mib = []_C_int{CTL_HW, HW_MACHINE} + n = unsafe.Sizeof(uname.Machine) + if err := sysctlUname(mib, &uname.Machine[0], &n); err != nil { + return err + } + uname.Machine[unsafe.Sizeof(uname.Machine)-1] = 0 + + return nil +} + /* * Exposed directly */ @@ -186,10 +251,12 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { //sys Fchdir(fd int) (err error) //sys Fchflags(fd int, flags int) (err error) //sys Fchmod(fd int, mode uint32) (err error) +//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) //sys Fstatfs(fd int, stat *Statfs_t) (err error) //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd.go b/vendor/golang.org/x/sys/unix/syscall_freebsd.go index a82ce127e6..ba9df4ac12 100644 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_freebsd.go @@ -12,8 +12,12 @@ package unix -import "unsafe" +import ( + "strings" + "unsafe" +) +// SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. type SockaddrDatalink struct { Len uint8 Family uint8 @@ -54,18 +58,6 @@ func nametomib(name string) (mib []_C_int, err error) { return buf[0 : n/siz], nil } -func direntIno(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) -} - -func direntReclen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) -} - -func direntNamlen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) -} - //sysnb pipe() (r int, w int, err error) func Pipe(p []int) (err error) { @@ -105,6 +97,23 @@ func Accept4(fd, flags int) (nfd int, sa Sockaddr, err error) { return } +const ImplementsGetwd = true + +//sys Getcwd(buf []byte) (n int, err error) = SYS___GETCWD + +func Getwd() (string, error) { + var buf [PathMax]byte + _, err := Getcwd(buf[0:]) + if err != nil { + return "", err + } + n := clen(buf[:]) + if n < 1 { + return "", EINVAL + } + return string(buf[:n]), nil +} + func Getfsstat(buf []Statfs_t, flags int) (n int, err error) { var _p0 unsafe.Pointer var bufsize uintptr @@ -128,14 +137,7 @@ func setattrlistTimes(path string, times []Timespec, flags int) error { // Derive extattr namespace and attribute name func xattrnamespace(fullattr string) (ns int, attr string, err error) { - s := -1 - for idx, val := range fullattr { - if val == '.' { - s = idx - break - } - } - + s := strings.IndexByte(fullattr, '.') if s == -1 { return -1, "", ENOATTR } @@ -276,7 +278,6 @@ func Listxattr(file string, dest []byte) (sz int, err error) { // FreeBSD won't allow you to list xattrs from multiple namespaces s := 0 - var e error for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { stmp, e := ExtattrListFile(file, nsid, uintptr(d), destsiz) @@ -288,7 +289,6 @@ func Listxattr(file string, dest []byte) (sz int, err error) { * we don't have read permissions on, so don't ignore those errors */ if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER { - e = nil continue } else if e != nil { return s, e @@ -302,7 +302,7 @@ func Listxattr(file string, dest []byte) (sz int, err error) { d = initxattrdest(dest, s) } - return s, e + return s, nil } func Flistxattr(fd int, dest []byte) (sz int, err error) { @@ -310,11 +310,9 @@ func Flistxattr(fd int, dest []byte) (sz int, err error) { destsiz := len(dest) s := 0 - var e error for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { stmp, e := ExtattrListFd(fd, nsid, uintptr(d), destsiz) if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER { - e = nil continue } else if e != nil { return s, e @@ -328,7 +326,7 @@ func Flistxattr(fd int, dest []byte) (sz int, err error) { d = initxattrdest(dest, s) } - return s, e + return s, nil } func Llistxattr(link string, dest []byte) (sz int, err error) { @@ -336,11 +334,9 @@ func Llistxattr(link string, dest []byte) (sz int, err error) { destsiz := len(dest) s := 0 - var e error for _, nsid := range [...]int{EXTATTR_NAMESPACE_USER, EXTATTR_NAMESPACE_SYSTEM} { stmp, e := ExtattrListLink(link, nsid, uintptr(d), destsiz) if e != nil && e == EPERM && nsid != EXTATTR_NAMESPACE_USER { - e = nil continue } else if e != nil { return s, e @@ -354,7 +350,7 @@ func Llistxattr(link string, dest []byte) (sz int, err error) { d = initxattrdest(dest, s) } - return s, e + return s, nil } //sys ioctl(fd int, req uint, arg uintptr) (err error) @@ -396,6 +392,52 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { return &value, err } +func Uname(uname *Utsname) error { + mib := []_C_int{CTL_KERN, KERN_OSTYPE} + n := unsafe.Sizeof(uname.Sysname) + if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_HOSTNAME} + n = unsafe.Sizeof(uname.Nodename) + if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_OSRELEASE} + n = unsafe.Sizeof(uname.Release) + if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_VERSION} + n = unsafe.Sizeof(uname.Version) + if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil { + return err + } + + // The version might have newlines or tabs in it, convert them to + // spaces. + for i, b := range uname.Version { + if b == '\n' || b == '\t' { + if i == len(uname.Version)-1 { + uname.Version[i] = 0 + } else { + uname.Version[i] = ' ' + } + } + } + + mib = []_C_int{CTL_HW, HW_MACHINE} + n = unsafe.Sizeof(uname.Machine) + if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil { + return err + } + + return nil +} + /* * Exposed directly */ @@ -436,9 +478,11 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) //sys Fstatfs(fd int, stat *Statfs_t) (err error) //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) +//sys Getdents(fd int, buf []byte) (n int, err error) //sys Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) //sys Getdtablesize() (size int) //sysnb Getegid() (egid int) diff --git a/vendor/golang.org/x/sys/unix/syscall_freebsd_test.go b/vendor/golang.org/x/sys/unix/syscall_freebsd_test.go deleted file mode 100644 index 654439e02b..0000000000 --- a/vendor/golang.org/x/sys/unix/syscall_freebsd_test.go +++ /dev/null @@ -1,297 +0,0 @@ -// Copyright 2014 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 freebsd - -package unix_test - -import ( - "flag" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path" - "path/filepath" - "runtime" - "testing" - - "golang.org/x/sys/unix" -) - -func TestSysctlUint64(t *testing.T) { - _, err := unix.SysctlUint64("vm.swap_total") - if err != nil { - t.Fatal(err) - } -} - -// FIXME: Infrastructure for launching tests in subprocesses stolen from openbsd_test.go - refactor? -// testCmd generates a proper command that, when executed, runs the test -// corresponding to the given key. - -type testProc struct { - fn func() // should always exit instead of returning - arg func(t *testing.T) string // generate argument for test - cleanup func(arg string) error // for instance, delete coredumps from testing pledge - success bool // whether zero-exit means success or failure -} - -var ( - testProcs = map[string]testProc{} - procName = "" - procArg = "" -) - -const ( - optName = "sys-unix-internal-procname" - optArg = "sys-unix-internal-arg" -) - -func init() { - flag.StringVar(&procName, optName, "", "internal use only") - flag.StringVar(&procArg, optArg, "", "internal use only") - -} - -func testCmd(procName string, procArg string) (*exec.Cmd, error) { - exe, err := filepath.Abs(os.Args[0]) - if err != nil { - return nil, err - } - cmd := exec.Command(exe, "-"+optName+"="+procName, "-"+optArg+"="+procArg) - cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr - return cmd, nil -} - -// ExitsCorrectly is a comprehensive, one-line-of-use wrapper for testing -// a testProc with a key. -func ExitsCorrectly(t *testing.T, procName string) { - s := testProcs[procName] - arg := "-" - if s.arg != nil { - arg = s.arg(t) - } - c, err := testCmd(procName, arg) - defer func(arg string) { - if err := s.cleanup(arg); err != nil { - t.Fatalf("Failed to run cleanup for %s %s %#v", procName, err, err) - } - }(arg) - if err != nil { - t.Fatalf("Failed to construct command for %s", procName) - } - if (c.Run() == nil) != s.success { - result := "succeed" - if !s.success { - result = "fail" - } - t.Fatalf("Process did not %s when it was supposed to", result) - } -} - -func TestMain(m *testing.M) { - flag.Parse() - if procName != "" { - t := testProcs[procName] - t.fn() - os.Stderr.WriteString("test function did not exit\n") - if t.success { - os.Exit(1) - } else { - os.Exit(0) - } - } - os.Exit(m.Run()) -} - -// end of infrastructure - -const testfile = "gocapmodetest" -const testfile2 = testfile + "2" - -func CapEnterTest() { - _, err := os.OpenFile(path.Join(procArg, testfile), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) - if err != nil { - panic(fmt.Sprintf("OpenFile: %s", err)) - } - - err = unix.CapEnter() - if err != nil { - panic(fmt.Sprintf("CapEnter: %s", err)) - } - - _, err = os.OpenFile(path.Join(procArg, testfile2), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) - if err == nil { - panic("OpenFile works!") - } - if err.(*os.PathError).Err != unix.ECAPMODE { - panic(fmt.Sprintf("OpenFile failed wrong: %s %#v", err, err)) - } - os.Exit(0) -} - -func makeTempDir(t *testing.T) string { - d, err := ioutil.TempDir("", "go_openat_test") - if err != nil { - t.Fatalf("TempDir failed: %s", err) - } - return d -} - -func removeTempDir(arg string) error { - err := os.RemoveAll(arg) - if err != nil && err.(*os.PathError).Err == unix.ENOENT { - return nil - } - return err -} - -func init() { - testProcs["cap_enter"] = testProc{ - CapEnterTest, - makeTempDir, - removeTempDir, - true, - } -} - -func TestCapEnter(t *testing.T) { - if runtime.GOARCH != "amd64" { - t.Skipf("skipping test on %s", runtime.GOARCH) - } - ExitsCorrectly(t, "cap_enter") -} - -func OpenatTest() { - f, err := os.Open(procArg) - if err != nil { - panic(err) - } - - err = unix.CapEnter() - if err != nil { - panic(fmt.Sprintf("CapEnter: %s", err)) - } - - fxx, err := unix.Openat(int(f.Fd()), "xx", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) - if err != nil { - panic(err) - } - unix.Close(fxx) - - // The right to open BASE/xx is not ambient - _, err = os.OpenFile(procArg+"/xx", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) - if err == nil { - panic("OpenFile succeeded") - } - if err.(*os.PathError).Err != unix.ECAPMODE { - panic(fmt.Sprintf("OpenFile failed wrong: %s %#v", err, err)) - } - - // Can't make a new directory either - err = os.Mkdir(procArg+"2", 0777) - if err == nil { - panic("MKdir succeeded") - } - if err.(*os.PathError).Err != unix.ECAPMODE { - panic(fmt.Sprintf("Mkdir failed wrong: %s %#v", err, err)) - } - - // Remove all caps except read and lookup. - r, err := unix.CapRightsInit([]uint64{unix.CAP_READ, unix.CAP_LOOKUP}) - if err != nil { - panic(fmt.Sprintf("CapRightsInit failed: %s %#v", err, err)) - } - err = unix.CapRightsLimit(f.Fd(), r) - if err != nil { - panic(fmt.Sprintf("CapRightsLimit failed: %s %#v", err, err)) - } - - // Check we can get the rights back again - r, err = unix.CapRightsGet(f.Fd()) - if err != nil { - panic(fmt.Sprintf("CapRightsGet failed: %s %#v", err, err)) - } - b, err := unix.CapRightsIsSet(r, []uint64{unix.CAP_READ, unix.CAP_LOOKUP}) - if err != nil { - panic(fmt.Sprintf("CapRightsIsSet failed: %s %#v", err, err)) - } - if !b { - panic(fmt.Sprintf("Unexpected rights")) - } - b, err = unix.CapRightsIsSet(r, []uint64{unix.CAP_READ, unix.CAP_LOOKUP, unix.CAP_WRITE}) - if err != nil { - panic(fmt.Sprintf("CapRightsIsSet failed: %s %#v", err, err)) - } - if b { - panic(fmt.Sprintf("Unexpected rights (2)")) - } - - // Can no longer create a file - _, err = unix.Openat(int(f.Fd()), "xx2", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) - if err == nil { - panic("Openat succeeded") - } - if err != unix.ENOTCAPABLE { - panic(fmt.Sprintf("OpenFileAt failed wrong: %s %#v", err, err)) - } - - // But can read an existing one - _, err = unix.Openat(int(f.Fd()), "xx", os.O_RDONLY, 0666) - if err != nil { - panic(fmt.Sprintf("Openat failed: %s %#v", err, err)) - } - - os.Exit(0) -} - -func init() { - testProcs["openat"] = testProc{ - OpenatTest, - makeTempDir, - removeTempDir, - true, - } -} - -func TestOpenat(t *testing.T) { - if runtime.GOARCH != "amd64" { - t.Skipf("skipping test on %s", runtime.GOARCH) - } - ExitsCorrectly(t, "openat") -} - -func TestCapRightsSetAndClear(t *testing.T) { - r, err := unix.CapRightsInit([]uint64{unix.CAP_READ, unix.CAP_WRITE, unix.CAP_PDWAIT}) - if err != nil { - t.Fatalf("CapRightsInit failed: %s", err) - } - - err = unix.CapRightsSet(r, []uint64{unix.CAP_EVENT, unix.CAP_LISTEN}) - if err != nil { - t.Fatalf("CapRightsSet failed: %s", err) - } - - b, err := unix.CapRightsIsSet(r, []uint64{unix.CAP_READ, unix.CAP_WRITE, unix.CAP_PDWAIT, unix.CAP_EVENT, unix.CAP_LISTEN}) - if err != nil { - t.Fatalf("CapRightsIsSet failed: %s", err) - } - if !b { - t.Fatalf("Wrong rights set") - } - - err = unix.CapRightsClear(r, []uint64{unix.CAP_READ, unix.CAP_PDWAIT}) - if err != nil { - t.Fatalf("CapRightsClear failed: %s", err) - } - - b, err = unix.CapRightsIsSet(r, []uint64{unix.CAP_WRITE, unix.CAP_EVENT, unix.CAP_LISTEN}) - if err != nil { - t.Fatalf("CapRightsIsSet failed: %s", err) - } - if !b { - t.Fatalf("Wrong rights set") - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_linux.go b/vendor/golang.org/x/sys/unix/syscall_linux.go index 9098661a3c..04f38c53ee 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux.go @@ -413,6 +413,7 @@ func (sa *SockaddrUnix) sockaddr() (unsafe.Pointer, _Socklen, error) { return unsafe.Pointer(&sa.raw), sl, nil } +// SockaddrLinklayer implements the Sockaddr interface for AF_PACKET type sockets. type SockaddrLinklayer struct { Protocol uint16 Ifindex int @@ -439,6 +440,7 @@ func (sa *SockaddrLinklayer) sockaddr() (unsafe.Pointer, _Socklen, error) { return unsafe.Pointer(&sa.raw), SizeofSockaddrLinklayer, nil } +// SockaddrNetlink implements the Sockaddr interface for AF_NETLINK type sockets. type SockaddrNetlink struct { Family uint16 Pad uint16 @@ -455,6 +457,8 @@ func (sa *SockaddrNetlink) sockaddr() (unsafe.Pointer, _Socklen, error) { return unsafe.Pointer(&sa.raw), SizeofSockaddrNetlink, nil } +// SockaddrHCI implements the Sockaddr interface for AF_BLUETOOTH type sockets +// using the HCI protocol. type SockaddrHCI struct { Dev uint16 Channel uint16 @@ -468,6 +472,31 @@ func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) { return unsafe.Pointer(&sa.raw), SizeofSockaddrHCI, nil } +// SockaddrL2 implements the Sockaddr interface for AF_BLUETOOTH type sockets +// using the L2CAP protocol. +type SockaddrL2 struct { + PSM uint16 + CID uint16 + Addr [6]uint8 + AddrType uint8 + raw RawSockaddrL2 +} + +func (sa *SockaddrL2) sockaddr() (unsafe.Pointer, _Socklen, error) { + sa.raw.Family = AF_BLUETOOTH + psm := (*[2]byte)(unsafe.Pointer(&sa.raw.Psm)) + psm[0] = byte(sa.PSM) + psm[1] = byte(sa.PSM >> 8) + for i := 0; i < len(sa.Addr); i++ { + sa.raw.Bdaddr[i] = sa.Addr[len(sa.Addr)-1-i] + } + cid := (*[2]byte)(unsafe.Pointer(&sa.raw.Cid)) + cid[0] = byte(sa.CID) + cid[1] = byte(sa.CID >> 8) + sa.raw.Bdaddr_type = sa.AddrType + return unsafe.Pointer(&sa.raw), SizeofSockaddrL2, nil +} + // SockaddrCAN implements the Sockaddr interface for AF_CAN type sockets. // The RxID and TxID fields are used for transport protocol addressing in // (CAN_TP16, CAN_TP20, CAN_MCNET, and CAN_ISOTP), they can be left with @@ -753,19 +782,6 @@ func Getsockname(fd int) (sa Sockaddr, err error) { return anyToSockaddr(&rsa) } -func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) { - vallen := _Socklen(4) - err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) - return value, err -} - -func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) { - var value IPMreq - vallen := _Socklen(SizeofIPMreq) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) { var value IPMreqn vallen := _Socklen(SizeofIPMreqn) @@ -773,27 +789,6 @@ func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error) { return &value, err } -func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) { - var value IPv6Mreq - vallen := _Socklen(SizeofIPv6Mreq) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) { - var value IPv6MTUInfo - vallen := _Socklen(SizeofIPv6MTUInfo) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - -func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) { - var value ICMPv6Filter - vallen := _Socklen(SizeofICMPv6Filter) - err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) - return &value, err -} - func GetsockoptUcred(fd, level, opt int) (*Ucred, error) { var value Ucred vallen := _Socklen(SizeofUcred) @@ -808,6 +803,24 @@ func GetsockoptTCPInfo(fd, level, opt int) (*TCPInfo, error) { return &value, err } +// GetsockoptString returns the string value of the socket option opt for the +// socket associated with fd at the given socket level. +func GetsockoptString(fd, level, opt int) (string, error) { + buf := make([]byte, 256) + vallen := _Socklen(len(buf)) + err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen) + if err != nil { + if err == ERANGE { + buf = make([]byte, vallen) + err = getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen) + } + if err != nil { + return "", err + } + } + return string(buf[:vallen-1]), nil +} + func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) } @@ -931,15 +944,17 @@ func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from } var dummy byte if len(oob) > 0 { - var sockType int - sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE) - if err != nil { - return - } - // receive at least one normal byte - if sockType != SOCK_DGRAM && len(p) == 0 { - iov.Base = &dummy - iov.SetLen(1) + if len(p) == 0 { + var sockType int + sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE) + if err != nil { + return + } + // receive at least one normal byte + if sockType != SOCK_DGRAM { + iov.Base = &dummy + iov.SetLen(1) + } } msg.Control = &oob[0] msg.SetControllen(len(oob)) @@ -983,15 +998,17 @@ func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error) } var dummy byte if len(oob) > 0 { - var sockType int - sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE) - if err != nil { - return 0, err - } - // send at least one normal byte - if sockType != SOCK_DGRAM && len(p) == 0 { - iov.Base = &dummy - iov.SetLen(1) + if len(p) == 0 { + var sockType int + sockType, err = GetsockoptInt(fd, SOL_SOCKET, SO_TYPE) + if err != nil { + return 0, err + } + // send at least one normal byte + if sockType != SOCK_DGRAM { + iov.Base = &dummy + iov.SetLen(1) + } } msg.Control = &oob[0] msg.SetControllen(len(oob)) @@ -1172,22 +1189,6 @@ func ReadDirent(fd int, buf []byte) (n int, err error) { return Getdents(fd, buf) } -func direntIno(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) -} - -func direntReclen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) -} - -func direntNamlen(buf []byte) (uint64, bool) { - reclen, ok := direntReclen(buf) - if !ok { - return 0, false - } - return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true -} - //sys mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) func Mount(source string, target string, fstype string, flags uintptr, data string) (err error) { @@ -1263,6 +1264,7 @@ func Getpgrp() (pid int) { //sys Mkdirat(dirfd int, path string, mode uint32) (err error) //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error) +//sys PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT //sysnb prlimit(pid int, resource int, newlimit *Rlimit, old *Rlimit) (err error) = SYS_PRLIMIT64 //sys Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) @@ -1293,6 +1295,7 @@ func Setgid(uid int) (err error) { //sys Setpriority(which int, who int, prio int) (err error) //sys Setxattr(path string, attr string, data []byte, flags int) (err error) +//sys Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) //sys Sync() //sys Syncfs(fd int) (err error) //sysnb Sysinfo(info *Sysinfo_t) (err error) @@ -1410,7 +1413,6 @@ func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) { // Msgget // Msgrcv // Msgsnd -// Newfstatat // Nfsservctl // Personality // Pselect6 @@ -1431,11 +1433,9 @@ func Vmsplice(fd int, iovs []Iovec, flags int) (int, error) { // RtSigtimedwait // SchedGetPriorityMax // SchedGetPriorityMin -// SchedGetaffinity // SchedGetparam // SchedGetscheduler // SchedRrGetInterval -// SchedSetaffinity // SchedSetparam // SchedYield // Security diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_386.go b/vendor/golang.org/x/sys/unix/syscall_linux_386.go index 4774fa363e..bb8e4fbd86 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_386.go @@ -54,6 +54,7 @@ func Pipe2(p []int, flags int) (err error) { //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64_64 //sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 +//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 //sysnb Getegid() (egid int) = SYS_GETEGID32 //sysnb Geteuid() (euid int) = SYS_GETEUID32 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go index 3707f6b7c9..d121106323 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_amd64.go @@ -11,6 +11,7 @@ package unix //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_NEWFSTATAT //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) @@ -28,7 +29,15 @@ package unix //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK -//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) + +func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { + var ts *Timespec + if timeout != nil { + ts = &Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} + } + return Pselect(nfd, r, w, e, ts, nil) +} + //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) @@ -39,7 +48,12 @@ package unix //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) -//sys Stat(path string, stat *Stat_t) (err error) + +func Stat(path string, stat *Stat_t) (err error) { + // Use fstatat, because Android's seccomp policy blocks stat. + return Fstatat(AT_FDCWD, path, stat, 0) +} + //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go index 226be100f5..c59f8588f1 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm.go @@ -77,6 +77,7 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { //sys Dup2(oldfd int, newfd int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) = SYS_FCHOWN32 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 +//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 //sysnb Getegid() (egid int) = SYS_GETEGID32 //sysnb Geteuid() (euid int) = SYS_GETEUID32 //sysnb Getgid() (gid int) = SYS_GETGID32 diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go index 9a8e6e4117..a1e8a609b2 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_arm64.go @@ -7,6 +7,7 @@ package unix //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT +//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) @@ -23,8 +24,11 @@ package unix //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - ts := Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} - return Pselect(nfd, r, w, e, &ts, nil) + var ts *Timespec + if timeout != nil { + ts = &Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} + } + return Pselect(nfd, r, w, e, ts, nil) } //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_gc.go b/vendor/golang.org/x/sys/unix/syscall_linux_gc.go new file mode 100644 index 0000000000..c26e6ec231 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/syscall_linux_gc.go @@ -0,0 +1,14 @@ +// Copyright 2018 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,!gccgo + +package unix + +// SyscallNoError may be used instead of Syscall for syscalls that don't fail. +func SyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) + +// RawSyscallNoError may be used instead of RawSyscall for syscalls that don't +// fail. +func RawSyscallNoError(trap, a1, a2, a3 uintptr) (r1, r2 uintptr) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_gccgo.go b/vendor/golang.org/x/sys/unix/syscall_linux_gccgo.go new file mode 100644 index 0000000000..df9c123718 --- /dev/null +++ b/vendor/golang.org/x/sys/unix/syscall_linux_gccgo.go @@ -0,0 +1,21 @@ +// Copyright 2018 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 +// +build gccgo +// +build 386 arm + +package unix + +import ( + "syscall" + "unsafe" +) + +func seek(fd int, offset int64, whence int) (newoffset int64, err syscall.Errno) { + offsetLow := uint32(offset & 0xffffffff) + offsetHigh := uint32((offset >> 32) & 0xffffffff) + _, _, err = Syscall6(SYS__LLSEEK, uintptr(fd), uintptr(offsetHigh), uintptr(offsetLow), uintptr(unsafe.Pointer(&newoffset)), uintptr(whence), 0) + return newoffset, err +} diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go index cdda11a9fa..090ed404ab 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mips64x.go @@ -9,7 +9,9 @@ package unix //sys Dup2(oldfd int, newfd int) (err error) //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) +//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) +//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_NEWFSTATAT //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) @@ -25,8 +27,11 @@ package unix //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - ts := Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} - return Pselect(nfd, r, w, e, &ts, nil) + var ts *Timespec + if timeout != nil { + ts = &Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} + } + return Pselect(nfd, r, w, e, ts, nil) } //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go index a114ba8cb3..9e16cc9d14 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_mipsx.go @@ -15,6 +15,7 @@ import ( func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) //sys Dup2(oldfd int, newfd int) (err error) +//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Ftruncate(fd int, length int64) (err error) = SYS_FTRUNCATE64 //sysnb Getegid() (egid int) @@ -35,7 +36,7 @@ func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) -//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) +//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) = SYS_TRUNCATE64 @@ -65,6 +66,7 @@ func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, //sys Lstat(path string, stat *Stat_t) (err error) = SYS_LSTAT64 //sys Fstat(fd int, stat *Stat_t) (err error) = SYS_FSTAT64 +//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 //sys Stat(path string, stat *Stat_t) (err error) = SYS_STAT64 //sys Utime(path string, buf *Utimbuf) (err error) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go index 7cae936c45..6fb8733d67 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go @@ -9,8 +9,10 @@ package unix //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //sys Dup2(oldfd int, newfd int) (err error) +//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_NEWFSTATAT //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go index e96a40cb21..c0d86e722b 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_s390x.go @@ -15,6 +15,7 @@ import ( //sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_NEWFSTATAT //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go index 012a3285ef..78c1e0df1d 100644 --- a/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/syscall_linux_sparc64.go @@ -7,9 +7,11 @@ package unix //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) +//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_FADVISE64 //sys Dup2(oldfd int, newfd int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) = SYS_FSTATAT64 //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) diff --git a/vendor/golang.org/x/sys/unix/syscall_linux_test.go b/vendor/golang.org/x/sys/unix/syscall_linux_test.go deleted file mode 100644 index 84c69d268b..0000000000 --- a/vendor/golang.org/x/sys/unix/syscall_linux_test.go +++ /dev/null @@ -1,230 +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. - -// +build linux - -package unix_test - -import ( - "io/ioutil" - "os" - "testing" - "time" - - "golang.org/x/sys/unix" -) - -func TestFchmodat(t *testing.T) { - defer chtmpdir(t)() - - touch(t, "file1") - os.Symlink("file1", "symlink1") - - err := unix.Fchmodat(unix.AT_FDCWD, "symlink1", 0444, 0) - if err != nil { - t.Fatalf("Fchmodat: unexpected error: %v", err) - } - - fi, err := os.Stat("file1") - if err != nil { - t.Fatal(err) - } - - if fi.Mode() != 0444 { - t.Errorf("Fchmodat: failed to change mode: expected %v, got %v", 0444, fi.Mode()) - } - - err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", 0444, unix.AT_SYMLINK_NOFOLLOW) - if err != unix.EOPNOTSUPP { - t.Fatalf("Fchmodat: unexpected error: %v, expected EOPNOTSUPP", err) - } -} - -func TestIoctlGetInt(t *testing.T) { - f, err := os.Open("/dev/random") - if err != nil { - t.Fatalf("failed to open device: %v", err) - } - defer f.Close() - - v, err := unix.IoctlGetInt(int(f.Fd()), unix.RNDGETENTCNT) - if err != nil { - t.Fatalf("failed to perform ioctl: %v", err) - } - - t.Logf("%d bits of entropy available", v) -} - -func TestPpoll(t *testing.T) { - f, cleanup := mktmpfifo(t) - defer cleanup() - - const timeout = 100 * time.Millisecond - - ok := make(chan bool, 1) - go func() { - select { - case <-time.After(10 * timeout): - t.Errorf("Ppoll: failed to timeout after %d", 10*timeout) - case <-ok: - } - }() - - fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}} - timeoutTs := unix.NsecToTimespec(int64(timeout)) - n, err := unix.Ppoll(fds, &timeoutTs, nil) - ok <- true - if err != nil { - t.Errorf("Ppoll: unexpected error: %v", err) - return - } - if n != 0 { - t.Errorf("Ppoll: wrong number of events: got %v, expected %v", n, 0) - return - } -} - -func TestTime(t *testing.T) { - var ut unix.Time_t - ut2, err := unix.Time(&ut) - if err != nil { - t.Fatalf("Time: %v", err) - } - if ut != ut2 { - t.Errorf("Time: return value %v should be equal to argument %v", ut2, ut) - } - - var now time.Time - - for i := 0; i < 10; i++ { - ut, err = unix.Time(nil) - if err != nil { - t.Fatalf("Time: %v", err) - } - - now = time.Now() - - if int64(ut) == now.Unix() { - return - } - } - - t.Errorf("Time: return value %v should be nearly equal to time.Now().Unix() %v", ut, now.Unix()) -} - -func TestUtime(t *testing.T) { - defer chtmpdir(t)() - - touch(t, "file1") - - buf := &unix.Utimbuf{ - Modtime: 12345, - } - - err := unix.Utime("file1", buf) - if err != nil { - t.Fatalf("Utime: %v", err) - } - - fi, err := os.Stat("file1") - if err != nil { - t.Fatal(err) - } - - if fi.ModTime().Unix() != 12345 { - t.Errorf("Utime: failed to change modtime: expected %v, got %v", 12345, fi.ModTime().Unix()) - } -} - -func TestUtimesNanoAt(t *testing.T) { - defer chtmpdir(t)() - - symlink := "symlink1" - os.Remove(symlink) - err := os.Symlink("nonexisting", symlink) - if err != nil { - t.Fatal(err) - } - - ts := []unix.Timespec{ - {Sec: 1111, Nsec: 2222}, - {Sec: 3333, Nsec: 4444}, - } - err = unix.UtimesNanoAt(unix.AT_FDCWD, symlink, ts, unix.AT_SYMLINK_NOFOLLOW) - if err != nil { - t.Fatalf("UtimesNanoAt: %v", err) - } - - var st unix.Stat_t - err = unix.Lstat(symlink, &st) - if err != nil { - t.Fatalf("Lstat: %v", err) - } - if st.Atim != ts[0] { - t.Errorf("UtimesNanoAt: wrong atime: %v", st.Atim) - } - if st.Mtim != ts[1] { - t.Errorf("UtimesNanoAt: wrong mtime: %v", st.Mtim) - } -} - -func TestGetrlimit(t *testing.T) { - var rlim unix.Rlimit - err := unix.Getrlimit(unix.RLIMIT_AS, &rlim) - if err != nil { - t.Fatalf("Getrlimit: %v", err) - } -} - -func TestSelect(t *testing.T) { - _, err := unix.Select(0, nil, nil, nil, &unix.Timeval{Sec: 0, Usec: 0}) - if err != nil { - t.Fatalf("Select: %v", err) - } -} - -func TestUname(t *testing.T) { - var utsname unix.Utsname - err := unix.Uname(&utsname) - if err != nil { - t.Fatalf("Uname: %v", err) - } - - // conversion from []byte to string, golang.org/issue/20753 - t.Logf("OS: %s/%s %s", string(utsname.Sysname[:]), string(utsname.Machine[:]), string(utsname.Release[:])) -} - -// utilities taken from os/os_test.go - -func touch(t *testing.T, name string) { - f, err := os.Create(name) - if err != nil { - t.Fatal(err) - } - if err := f.Close(); err != nil { - t.Fatal(err) - } -} - -// chtmpdir changes the working directory to a new temporary directory and -// provides a cleanup function. Used when PWD is read-only. -func chtmpdir(t *testing.T) func() { - oldwd, err := os.Getwd() - if err != nil { - t.Fatalf("chtmpdir: %v", err) - } - d, err := ioutil.TempDir("", "test") - if err != nil { - t.Fatalf("chtmpdir: %v", err) - } - if err := os.Chdir(d); err != nil { - t.Fatalf("chtmpdir: %v", err) - } - return func() { - if err := os.Chdir(oldwd); err != nil { - t.Fatalf("chtmpdir: %v", err) - } - os.RemoveAll(d) - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_netbsd.go b/vendor/golang.org/x/sys/unix/syscall_netbsd.go index 9146809527..e1a3baa237 100644 --- a/vendor/golang.org/x/sys/unix/syscall_netbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_netbsd.go @@ -17,6 +17,7 @@ import ( "unsafe" ) +// SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. type SockaddrDatalink struct { Len uint8 Family uint8 @@ -92,18 +93,6 @@ func nametomib(name string) (mib []_C_int, err error) { return mib, nil } -func direntIno(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) -} - -func direntReclen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) -} - -func direntNamlen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) -} - //sysnb pipe() (fd1 int, fd2 int, err error) func Pipe(p []int) (err error) { if len(p) != 2 { @@ -118,6 +107,23 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { return getdents(fd, buf) } +const ImplementsGetwd = true + +//sys Getcwd(buf []byte) (n int, err error) = SYS___GETCWD + +func Getwd() (string, error) { + var buf [PathMax]byte + _, err := Getcwd(buf[0:]) + if err != nil { + return "", err + } + n := clen(buf[:]) + if n < 1 { + return "", EINVAL + } + return string(buf[:n]), nil +} + // TODO func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { return -1, ENOSYS @@ -167,6 +173,52 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { return &value, err } +func Uname(uname *Utsname) error { + mib := []_C_int{CTL_KERN, KERN_OSTYPE} + n := unsafe.Sizeof(uname.Sysname) + if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_HOSTNAME} + n = unsafe.Sizeof(uname.Nodename) + if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_OSRELEASE} + n = unsafe.Sizeof(uname.Release) + if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_VERSION} + n = unsafe.Sizeof(uname.Version) + if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil { + return err + } + + // The version might have newlines or tabs in it, convert them to + // spaces. + for i, b := range uname.Version { + if b == '\n' || b == '\t' { + if i == len(uname.Version)-1 { + uname.Version[i] = 0 + } else { + uname.Version[i] = ' ' + } + } + } + + mib = []_C_int{CTL_HW, HW_MACHINE} + n = unsafe.Sizeof(uname.Machine) + if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil { + return err + } + + return nil +} + /* * Exposed directly */ @@ -181,13 +233,16 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { //sys Dup(fd int) (nfd int, err error) //sys Dup2(from int, to int) (err error) //sys Exit(code int) +//sys Fadvise(fd int, offset int64, length int64, advice int) (err error) = SYS_POSIX_FADVISE //sys Fchdir(fd int) (err error) //sys Fchflags(fd int, flags int) (err error) //sys Fchmod(fd int, mode uint32) (err error) +//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) @@ -268,7 +323,6 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { // __msync13 // __ntp_gettime30 // __posix_chown -// __posix_fadvise50 // __posix_fchown // __posix_lchown // __posix_rename diff --git a/vendor/golang.org/x/sys/unix/syscall_no_getwd.go b/vendor/golang.org/x/sys/unix/syscall_no_getwd.go deleted file mode 100644 index 530792ea93..0000000000 --- a/vendor/golang.org/x/sys/unix/syscall_no_getwd.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2013 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 dragonfly freebsd netbsd openbsd - -package unix - -const ImplementsGetwd = false - -func Getwd() (string, error) { return "", ENOTSUP } diff --git a/vendor/golang.org/x/sys/unix/syscall_openbsd.go b/vendor/golang.org/x/sys/unix/syscall_openbsd.go index 0bda73c384..614fcf0494 100644 --- a/vendor/golang.org/x/sys/unix/syscall_openbsd.go +++ b/vendor/golang.org/x/sys/unix/syscall_openbsd.go @@ -13,10 +13,12 @@ package unix import ( + "sort" "syscall" "unsafe" ) +// SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. type SockaddrDatalink struct { Len uint8 Family uint8 @@ -32,38 +34,15 @@ type SockaddrDatalink struct { func Syscall9(trap, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno) func nametomib(name string) (mib []_C_int, err error) { - // Perform lookup via a binary search - left := 0 - right := len(sysctlMib) - 1 - for { - idx := left + (right-left)/2 - switch { - case name == sysctlMib[idx].ctlname: - return sysctlMib[idx].ctloid, nil - case name > sysctlMib[idx].ctlname: - left = idx + 1 - default: - right = idx - 1 - } - if left > right { - break - } + i := sort.Search(len(sysctlMib), func(i int) bool { + return sysctlMib[i].ctlname >= name + }) + if i < len(sysctlMib) && sysctlMib[i].ctlname == name { + return sysctlMib[i].ctloid, nil } return nil, EINVAL } -func direntIno(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Fileno), unsafe.Sizeof(Dirent{}.Fileno)) -} - -func direntReclen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) -} - -func direntNamlen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen)) -} - //sysnb pipe(p *[2]_C_int) (err error) func Pipe(p []int) (err error) { if len(p) != 2 { @@ -81,6 +60,23 @@ func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { return getdents(fd, buf) } +const ImplementsGetwd = true + +//sys Getcwd(buf []byte) (n int, err error) = SYS___GETCWD + +func Getwd() (string, error) { + var buf [PathMax]byte + _, err := Getcwd(buf[0:]) + if err != nil { + return "", err + } + n := clen(buf[:]) + if n < 1 { + return "", EINVAL + } + return string(buf[:n]), nil +} + // TODO func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { return -1, ENOSYS @@ -145,6 +141,52 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { return &value, err } +func Uname(uname *Utsname) error { + mib := []_C_int{CTL_KERN, KERN_OSTYPE} + n := unsafe.Sizeof(uname.Sysname) + if err := sysctl(mib, &uname.Sysname[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_HOSTNAME} + n = unsafe.Sizeof(uname.Nodename) + if err := sysctl(mib, &uname.Nodename[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_OSRELEASE} + n = unsafe.Sizeof(uname.Release) + if err := sysctl(mib, &uname.Release[0], &n, nil, 0); err != nil { + return err + } + + mib = []_C_int{CTL_KERN, KERN_VERSION} + n = unsafe.Sizeof(uname.Version) + if err := sysctl(mib, &uname.Version[0], &n, nil, 0); err != nil { + return err + } + + // The version might have newlines or tabs in it, convert them to + // spaces. + for i, b := range uname.Version { + if b == '\n' || b == '\t' { + if i == len(uname.Version)-1 { + uname.Version[i] = 0 + } else { + uname.Version[i] = ' ' + } + } + } + + mib = []_C_int{CTL_HW, HW_MACHINE} + n = unsafe.Sizeof(uname.Machine) + if err := sysctl(mib, &uname.Machine[0], &n, nil, 0); err != nil { + return err + } + + return nil +} + /* * Exposed directly */ @@ -162,10 +204,12 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { //sys Fchdir(fd int) (err error) //sys Fchflags(fd int, flags int) (err error) //sys Fchmod(fd int, mode uint32) (err error) +//sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) //sys Fchown(fd int, uid int, gid int) (err error) //sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) //sys Fstatfs(fd int, stat *Statfs_t) (err error) //sys Fsync(fd int) (err error) //sys Ftruncate(fd int, length int64) (err error) @@ -178,6 +222,7 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { //sysnb Getppid() (ppid int) //sys Getpriority(which int, who int) (prio int, err error) //sysnb Getrlimit(which int, lim *Rlimit) (err error) +//sysnb Getrtable() (rtable int, err error) //sysnb Getrusage(who int, rusage *Rusage) (err error) //sysnb Getsid(pid int) (sid int, err error) //sysnb Gettimeofday(tv *Timeval) (err error) @@ -215,6 +260,7 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(which int, lim *Rlimit) (err error) +//sysnb Setrtable(rtable int) (err error) //sysnb Setsid() (pid int, err error) //sysnb Settimeofday(tp *Timeval) (err error) //sysnb Setuid(uid int) (err error) @@ -263,7 +309,6 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { // getlogin // getresgid // getresuid -// getrtable // getthrid // ktrace // lfs_bmapv @@ -299,7 +344,6 @@ func IoctlGetTermios(fd int, req uint) (*Termios, error) { // semop // setgroups // setitimer -// setrtable // setsockopt // shmat // shmctl diff --git a/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go index 649e67fccc..9a35334cba 100644 --- a/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go @@ -31,3 +31,7 @@ func (msghdr *Msghdr) SetControllen(length int) { func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } + +// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions +// of openbsd/amd64 the syscall is called sysctl instead of __sysctl. +const SYS___SYSCTL = SYS_SYSCTL diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris.go b/vendor/golang.org/x/sys/unix/syscall_solaris.go index 3ab9e07c8c..b7629529b3 100644 --- a/vendor/golang.org/x/sys/unix/syscall_solaris.go +++ b/vendor/golang.org/x/sys/unix/syscall_solaris.go @@ -23,6 +23,7 @@ type syscallFunc uintptr func rawSysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) func sysvicall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) +// SockaddrDatalink implements the Sockaddr interface for AF_LINK type sockets. type SockaddrDatalink struct { Family uint16 Index uint16 @@ -34,31 +35,6 @@ type SockaddrDatalink struct { raw RawSockaddrDatalink } -func clen(n []byte) int { - for i := 0; i < len(n); i++ { - if n[i] == 0 { - return i - } - } - return len(n) -} - -func direntIno(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) -} - -func direntReclen(buf []byte) (uint64, bool) { - return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) -} - -func direntNamlen(buf []byte) (uint64, bool) { - reclen, ok := direntReclen(buf) - if !ok { - return 0, false - } - return reclen - uint64(unsafe.Offsetof(Dirent{}.Name)), true -} - //sysnb pipe(p *[2]_C_int) (n int, err error) func Pipe(p []int) (err error) { @@ -139,6 +115,18 @@ func Getsockname(fd int) (sa Sockaddr, err error) { return anyToSockaddr(&rsa) } +// GetsockoptString returns the string value of the socket option opt for the +// socket associated with fd at the given socket level. +func GetsockoptString(fd, level, opt int) (string, error) { + buf := make([]byte, 256) + vallen := _Socklen(len(buf)) + err := getsockopt(fd, level, opt, unsafe.Pointer(&buf[0]), &vallen) + if err != nil { + return "", err + } + return string(buf[:vallen-1]), nil +} + const ImplementsGetwd = true //sys Getcwd(buf []byte) (n int, err error) @@ -324,6 +312,12 @@ func UtimesNanoAt(dirfd int, path string, ts []Timespec, flags int) error { //sys fcntl(fd int, cmd int, arg int) (val int, err error) +// FcntlInt performs a fcntl syscall on fd with the provided command and argument. +func FcntlInt(fd uintptr, cmd, arg int) (int, error) { + valptr, _, err := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0) + return int(valptr), err +} + // FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(unsafe.Pointer(lk)), 0, 0, 0) @@ -607,9 +601,10 @@ func Poll(fds []PollFd, timeout int) (n int, err error) { //sys Fchown(fd int, uid int, gid int) (err error) //sys Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) //sys Fdatasync(fd int) (err error) -//sys Flock(fd int, how int) (err error) +//sys Flock(fd int, how int) (err error) //sys Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_t) (err error) +//sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) //sys Fstatvfs(fd int, vfsstat *Statvfs_t) (err error) //sys Getdents(fd int, buf []byte, basep *uintptr) (n int, err error) //sysnb Getgid() (gid int) @@ -655,6 +650,7 @@ func Poll(fds []PollFd, timeout int) (n int, err error) { //sys Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) //sys Rmdir(path string) (err error) //sys Seek(fd int, offset int64, whence int) (newoffset int64, err error) = lseek +//sys Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) //sysnb Setegid(egid int) (err error) //sysnb Seteuid(euid int) (err error) //sysnb Setgid(gid int) (err error) @@ -686,6 +682,7 @@ func Poll(fds []PollFd, timeout int) (n int, err error) { //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_connect //sys mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) //sys munmap(addr uintptr, length uintptr) (err error) +//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) = libsendfile.sendfile //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.__xnet_sendto //sys socket(domain int, typ int, proto int) (fd int, err error) = libsocket.__xnet_socket //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) = libsocket.__xnet_socketpair diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go b/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go index 9d4e7a678f..91c32ddf02 100644 --- a/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go +++ b/vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go @@ -21,8 +21,3 @@ func (iov *Iovec) SetLen(length int) { func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint32(length) } - -func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { - // TODO(aram): implement this, see issue 5847. - panic("unimplemented") -} diff --git a/vendor/golang.org/x/sys/unix/syscall_solaris_test.go b/vendor/golang.org/x/sys/unix/syscall_solaris_test.go deleted file mode 100644 index d3e7d2b2e5..0000000000 --- a/vendor/golang.org/x/sys/unix/syscall_solaris_test.go +++ /dev/null @@ -1,34 +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. - -// +build solaris - -package unix_test - -import ( - "os/exec" - "testing" - - "golang.org/x/sys/unix" -) - -func TestStatvfs(t *testing.T) { - if err := unix.Statvfs("", nil); err == nil { - t.Fatal(`Statvfs("") expected failure`) - } - - statvfs := unix.Statvfs_t{} - if err := unix.Statvfs("/", &statvfs); err != nil { - t.Errorf(`Statvfs("/") failed: %v`, err) - } - - if t.Failed() { - mount, err := exec.Command("mount").CombinedOutput() - if err != nil { - t.Logf("mount: %v\n%s", err, mount) - } else { - t.Logf("mount: %s", mount) - } - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_test.go b/vendor/golang.org/x/sys/unix/syscall_test.go deleted file mode 100644 index 95eac92aca..0000000000 --- a/vendor/golang.org/x/sys/unix/syscall_test.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2013 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 dragonfly freebsd linux netbsd openbsd solaris - -package unix_test - -import ( - "fmt" - "testing" - - "golang.org/x/sys/unix" -) - -func testSetGetenv(t *testing.T, key, value string) { - err := unix.Setenv(key, value) - if err != nil { - t.Fatalf("Setenv failed to set %q: %v", value, err) - } - newvalue, found := unix.Getenv(key) - if !found { - t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) - } - if newvalue != value { - t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) - } -} - -func TestEnv(t *testing.T) { - testSetGetenv(t, "TESTENV", "AVALUE") - // make sure TESTENV gets set to "", not deleted - testSetGetenv(t, "TESTENV", "") -} - -func TestItoa(t *testing.T) { - // Make most negative integer: 0x8000... - i := 1 - for i<<1 != 0 { - i <<= 1 - } - if i >= 0 { - t.Fatal("bad math") - } - s := unix.Itoa(i) - f := fmt.Sprint(i) - if s != f { - t.Fatalf("itoa(%d) = %s, want %s", i, s, f) - } -} diff --git a/vendor/golang.org/x/sys/unix/syscall_unix.go b/vendor/golang.org/x/sys/unix/syscall_unix.go index 3ed8a91f5c..b835bad0fe 100644 --- a/vendor/golang.org/x/sys/unix/syscall_unix.go +++ b/vendor/golang.org/x/sys/unix/syscall_unix.go @@ -7,7 +7,9 @@ package unix import ( + "bytes" "runtime" + "sort" "sync" "syscall" "unsafe" @@ -50,6 +52,37 @@ func errnoErr(e syscall.Errno) error { return e } +// ErrnoName returns the error name for error number e. +func ErrnoName(e syscall.Errno) string { + i := sort.Search(len(errorList), func(i int) bool { + return errorList[i].num >= e + }) + if i < len(errorList) && errorList[i].num == e { + return errorList[i].name + } + return "" +} + +// SignalName returns the signal name for signal number s. +func SignalName(s syscall.Signal) string { + i := sort.Search(len(signalList), func(i int) bool { + return signalList[i].num >= s + }) + if i < len(signalList) && signalList[i].num == s { + return signalList[i].name + } + return "" +} + +// clen returns the index of the first NULL byte in n or len(n) if n contains no NULL byte. +func clen(n []byte) int { + i := bytes.IndexByte(n, 0) + if i == -1 { + i = len(n) + } + return i +} + // Mmap manager, for use by operating system-specific implementations. type mmapper struct { @@ -138,16 +171,19 @@ func Write(fd int, p []byte) (n int, err error) { // creation of IPv6 sockets to return EAFNOSUPPORT. var SocketDisableIPv6 bool +// Sockaddr represents a socket address. type Sockaddr interface { sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs } +// SockaddrInet4 implements the Sockaddr interface for AF_INET type sockets. type SockaddrInet4 struct { Port int Addr [4]byte raw RawSockaddrInet4 } +// SockaddrInet6 implements the Sockaddr interface for AF_INET6 type sockets. type SockaddrInet6 struct { Port int ZoneId uint32 @@ -155,6 +191,7 @@ type SockaddrInet6 struct { raw RawSockaddrInet6 } +// SockaddrUnix implements the Sockaddr interface for AF_UNIX type sockets. type SockaddrUnix struct { Name string raw RawSockaddrUnix @@ -185,6 +222,13 @@ func Getpeername(fd int) (sa Sockaddr, err error) { return anyToSockaddr(&rsa) } +func GetsockoptByte(fd, level, opt int) (value byte, err error) { + var n byte + vallen := _Socklen(1) + err = getsockopt(fd, level, opt, unsafe.Pointer(&n), &vallen) + return n, err +} + func GetsockoptInt(fd, level, opt int) (value int, err error) { var n int32 vallen := _Socklen(4) @@ -192,6 +236,54 @@ func GetsockoptInt(fd, level, opt int) (value int, err error) { return int(n), err } +func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error) { + vallen := _Socklen(4) + err = getsockopt(fd, level, opt, unsafe.Pointer(&value[0]), &vallen) + return value, err +} + +func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error) { + var value IPMreq + vallen := _Socklen(SizeofIPMreq) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err +} + +func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error) { + var value IPv6Mreq + vallen := _Socklen(SizeofIPv6Mreq) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err +} + +func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error) { + var value IPv6MTUInfo + vallen := _Socklen(SizeofIPv6MTUInfo) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err +} + +func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error) { + var value ICMPv6Filter + vallen := _Socklen(SizeofICMPv6Filter) + err := getsockopt(fd, level, opt, unsafe.Pointer(&value), &vallen) + return &value, err +} + +func GetsockoptLinger(fd, level, opt int) (*Linger, error) { + var linger Linger + vallen := _Socklen(SizeofLinger) + err := getsockopt(fd, level, opt, unsafe.Pointer(&linger), &vallen) + return &linger, err +} + +func GetsockoptTimeval(fd, level, opt int) (*Timeval, error) { + var tv Timeval + vallen := _Socklen(unsafe.Sizeof(tv)) + err := getsockopt(fd, level, opt, unsafe.Pointer(&tv), &vallen) + return &tv, err +} + func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error) { var rsa RawSockaddrAny var len _Socklen = SizeofSockaddrAny @@ -291,3 +383,12 @@ func SetNonblock(fd int, nonblocking bool) (err error) { _, err = fcntl(fd, F_SETFL, flag) return err } + +// Exec calls execve(2), which replaces the calling executable in the process +// tree. argv0 should be the full path to an executable ("/bin/ls") and the +// executable name should also be the first argument in argv (["ls", "-l"]). +// envv are the environment variables that should be passed to the new +// process (["USER=go", "PWD=/tmp"]). +func Exec(argv0 string, argv []string, envv []string) error { + return syscall.Exec(argv0, argv, envv) +} diff --git a/vendor/golang.org/x/sys/unix/syscall_unix_test.go b/vendor/golang.org/x/sys/unix/syscall_unix_test.go deleted file mode 100644 index d0a09ce88a..0000000000 --- a/vendor/golang.org/x/sys/unix/syscall_unix_test.go +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright 2013 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 dragonfly freebsd linux netbsd openbsd solaris - -package unix_test - -import ( - "flag" - "fmt" - "io/ioutil" - "net" - "os" - "os/exec" - "path/filepath" - "runtime" - "testing" - "time" - - "golang.org/x/sys/unix" -) - -// Tests that below functions, structures and constants are consistent -// on all Unix-like systems. -func _() { - // program scheduling priority functions and constants - var ( - _ func(int, int, int) error = unix.Setpriority - _ func(int, int) (int, error) = unix.Getpriority - ) - const ( - _ int = unix.PRIO_USER - _ int = unix.PRIO_PROCESS - _ int = unix.PRIO_PGRP - ) - - // termios constants - const ( - _ int = unix.TCIFLUSH - _ int = unix.TCIOFLUSH - _ int = unix.TCOFLUSH - ) - - // fcntl file locking structure and constants - var ( - _ = unix.Flock_t{ - Type: int16(0), - Whence: int16(0), - Start: int64(0), - Len: int64(0), - Pid: int32(0), - } - ) - const ( - _ = unix.F_GETLK - _ = unix.F_SETLK - _ = unix.F_SETLKW - ) -} - -// TestFcntlFlock tests whether the file locking structure matches -// the calling convention of each kernel. -func TestFcntlFlock(t *testing.T) { - name := filepath.Join(os.TempDir(), "TestFcntlFlock") - fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0) - if err != nil { - t.Fatalf("Open failed: %v", err) - } - defer unix.Unlink(name) - defer unix.Close(fd) - flock := unix.Flock_t{ - Type: unix.F_RDLCK, - Start: 0, Len: 0, Whence: 1, - } - if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil { - t.Fatalf("FcntlFlock failed: %v", err) - } -} - -// TestPassFD tests passing a file descriptor over a Unix socket. -// -// This test involved both a parent and child process. The parent -// process is invoked as a normal test, with "go test", which then -// runs the child process by running the current test binary with args -// "-test.run=^TestPassFD$" and an environment variable used to signal -// that the test should become the child process instead. -func TestPassFD(t *testing.T) { - if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { - passFDChild() - return - } - - tempDir, err := ioutil.TempDir("", "TestPassFD") - if err != nil { - t.Fatal(err) - } - defer os.RemoveAll(tempDir) - - fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) - if err != nil { - t.Fatalf("Socketpair: %v", err) - } - defer unix.Close(fds[0]) - defer unix.Close(fds[1]) - writeFile := os.NewFile(uintptr(fds[0]), "child-writes") - readFile := os.NewFile(uintptr(fds[1]), "parent-reads") - defer writeFile.Close() - defer readFile.Close() - - cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir) - cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} - if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" { - cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp) - } - cmd.ExtraFiles = []*os.File{writeFile} - - out, err := cmd.CombinedOutput() - if len(out) > 0 || err != nil { - t.Fatalf("child process: %q, %v", out, err) - } - - c, err := net.FileConn(readFile) - if err != nil { - t.Fatalf("FileConn: %v", err) - } - defer c.Close() - - uc, ok := c.(*net.UnixConn) - if !ok { - t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c) - } - - buf := make([]byte, 32) // expect 1 byte - oob := make([]byte, 32) // expect 24 bytes - closeUnix := time.AfterFunc(5*time.Second, func() { - t.Logf("timeout reading from unix socket") - uc.Close() - }) - _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob) - if err != nil { - t.Fatalf("ReadMsgUnix: %v", err) - } - closeUnix.Stop() - - scms, err := unix.ParseSocketControlMessage(oob[:oobn]) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - if len(scms) != 1 { - t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms) - } - scm := scms[0] - gotFds, err := unix.ParseUnixRights(&scm) - if err != nil { - t.Fatalf("unix.ParseUnixRights: %v", err) - } - if len(gotFds) != 1 { - t.Fatalf("wanted 1 fd; got %#v", gotFds) - } - - f := os.NewFile(uintptr(gotFds[0]), "fd-from-child") - defer f.Close() - - got, err := ioutil.ReadAll(f) - want := "Hello from child process!\n" - if string(got) != want { - t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want) - } -} - -// passFDChild is the child process used by TestPassFD. -func passFDChild() { - defer os.Exit(0) - - // Look for our fd. It should be fd 3, but we work around an fd leak - // bug here (http://golang.org/issue/2603) to let it be elsewhere. - var uc *net.UnixConn - for fd := uintptr(3); fd <= 10; fd++ { - f := os.NewFile(fd, "unix-conn") - var ok bool - netc, _ := net.FileConn(f) - uc, ok = netc.(*net.UnixConn) - if ok { - break - } - } - if uc == nil { - fmt.Println("failed to find unix fd") - return - } - - // Make a file f to send to our parent process on uc. - // We make it in tempDir, which our parent will clean up. - flag.Parse() - tempDir := flag.Arg(0) - f, err := ioutil.TempFile(tempDir, "") - if err != nil { - fmt.Printf("TempFile: %v", err) - return - } - - f.Write([]byte("Hello from child process!\n")) - f.Seek(0, 0) - - rights := unix.UnixRights(int(f.Fd())) - dummyByte := []byte("x") - n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil) - if err != nil { - fmt.Printf("WriteMsgUnix: %v", err) - return - } - if n != 1 || oobn != len(rights) { - fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights)) - return - } -} - -// TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage, -// and ParseUnixRights are able to successfully round-trip lists of file descriptors. -func TestUnixRightsRoundtrip(t *testing.T) { - testCases := [...][][]int{ - {{42}}, - {{1, 2}}, - {{3, 4, 5}}, - {{}}, - {{1, 2}, {3, 4, 5}, {}, {7}}, - } - for _, testCase := range testCases { - b := []byte{} - var n int - for _, fds := range testCase { - // Last assignment to n wins - n = len(b) + unix.CmsgLen(4*len(fds)) - b = append(b, unix.UnixRights(fds...)...) - } - // Truncate b - b = b[:n] - - scms, err := unix.ParseSocketControlMessage(b) - if err != nil { - t.Fatalf("ParseSocketControlMessage: %v", err) - } - if len(scms) != len(testCase) { - t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms) - } - for i, scm := range scms { - gotFds, err := unix.ParseUnixRights(&scm) - if err != nil { - t.Fatalf("ParseUnixRights: %v", err) - } - wantFds := testCase[i] - if len(gotFds) != len(wantFds) { - t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds) - } - for j, fd := range gotFds { - if fd != wantFds[j] { - t.Fatalf("expected fd %v, got %v", wantFds[j], fd) - } - } - } - } -} - -func TestRlimit(t *testing.T) { - var rlimit, zero unix.Rlimit - err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit) - if err != nil { - t.Fatalf("Getrlimit: save failed: %v", err) - } - if zero == rlimit { - t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit) - } - set := rlimit - set.Cur = set.Max - 1 - err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set) - if err != nil { - t.Fatalf("Setrlimit: set failed: %#v %v", set, err) - } - var get unix.Rlimit - err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get) - if err != nil { - t.Fatalf("Getrlimit: get failed: %v", err) - } - set = rlimit - set.Cur = set.Max - 1 - if set != get { - // Seems like Darwin requires some privilege to - // increase the soft limit of rlimit sandbox, though - // Setrlimit never reports an error. - switch runtime.GOOS { - case "darwin": - default: - t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get) - } - } - err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit) - if err != nil { - t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err) - } -} - -func TestSeekFailure(t *testing.T) { - _, err := unix.Seek(-1, 0, 0) - if err == nil { - t.Fatalf("Seek(-1, 0, 0) did not fail") - } - str := err.Error() // used to crash on Linux - t.Logf("Seek: %v", str) - if str == "" { - t.Fatalf("Seek(-1, 0, 0) return error with empty message") - } -} - -func TestDup(t *testing.T) { - file, err := ioutil.TempFile("", "TestDup") - if err != nil { - t.Fatalf("Tempfile failed: %v", err) - } - defer os.Remove(file.Name()) - defer file.Close() - f := int(file.Fd()) - - newFd, err := unix.Dup(f) - if err != nil { - t.Fatalf("Dup: %v", err) - } - - err = unix.Dup2(newFd, newFd+1) - if err != nil { - t.Fatalf("Dup2: %v", err) - } - - b1 := []byte("Test123") - b2 := make([]byte, 7) - _, err = unix.Write(newFd+1, b1) - if err != nil { - t.Fatalf("Write to dup2 fd failed: %v", err) - } - _, err = unix.Seek(f, 0, 0) - if err != nil { - t.Fatalf("Seek failed: %v", err) - } - _, err = unix.Read(f, b2) - if err != nil { - t.Fatalf("Read back failed: %v", err) - } - if string(b1) != string(b2) { - t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2)) - } -} - -func TestPoll(t *testing.T) { - f, cleanup := mktmpfifo(t) - defer cleanup() - - const timeout = 100 - - ok := make(chan bool, 1) - go func() { - select { - case <-time.After(10 * timeout * time.Millisecond): - t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout) - case <-ok: - } - }() - - fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}} - n, err := unix.Poll(fds, timeout) - ok <- true - if err != nil { - t.Errorf("Poll: unexpected error: %v", err) - return - } - if n != 0 { - t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0) - return - } -} - -// mktmpfifo creates a temporary FIFO and provides a cleanup function. -func mktmpfifo(t *testing.T) (*os.File, func()) { - err := unix.Mkfifo("fifo", 0666) - if err != nil { - t.Fatalf("mktmpfifo: failed to create FIFO: %v", err) - } - - f, err := os.OpenFile("fifo", os.O_RDWR, 0666) - if err != nil { - os.Remove("fifo") - t.Fatalf("mktmpfifo: failed to open FIFO: %v", err) - } - - return f, func() { - f.Close() - os.Remove("fifo") - } -} diff --git a/vendor/golang.org/x/sys/unix/timestruct.go b/vendor/golang.org/x/sys/unix/timestruct.go index 139fbbebbb..47b9011ee9 100644 --- a/vendor/golang.org/x/sys/unix/timestruct.go +++ b/vendor/golang.org/x/sys/unix/timestruct.go @@ -6,6 +6,8 @@ package unix +import "time" + // TimespecToNsec converts a Timespec value into a number of // nanoseconds since the Unix epoch. func TimespecToNsec(ts Timespec) int64 { return int64(ts.Sec)*1e9 + int64(ts.Nsec) } @@ -22,6 +24,24 @@ func NsecToTimespec(nsec int64) Timespec { return setTimespec(sec, nsec) } +// TimeToTimespec converts t into a Timespec. +// On some 32-bit systems the range of valid Timespec values are smaller +// than that of time.Time values. So if t is out of the valid range of +// Timespec, it returns a zero Timespec and ERANGE. +func TimeToTimespec(t time.Time) (Timespec, error) { + sec := t.Unix() + nsec := int64(t.Nanosecond()) + ts := setTimespec(sec, nsec) + + // Currently all targets have either int32 or int64 for Timespec.Sec. + // If there were a new target with floating point type for it, we have + // to consider the rounding error. + if int64(ts.Sec) != sec { + return Timespec{}, ERANGE + } + return ts, nil +} + // TimevalToNsec converts a Timeval value into a number of nanoseconds // since the Unix epoch. func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } diff --git a/vendor/golang.org/x/sys/unix/types_darwin.go b/vendor/golang.org/x/sys/unix/types_darwin.go index 3a938ace68..46b9908e03 100644 --- a/vendor/golang.org/x/sys/unix/types_darwin.go +++ b/vendor/golang.org/x/sys/unix/types_darwin.go @@ -39,6 +39,7 @@ package unix #include <sys/types.h> #include <sys/uio.h> #include <sys/un.h> +#include <sys/utsname.h> #include <sys/wait.h> #include <net/bpf.h> #include <net/if.h> @@ -270,3 +271,7 @@ const ( POLLWRBAND = C.POLLWRBAND POLLWRNORM = C.POLLWRNORM ) + +// uname + +type Utsname C.struct_utsname diff --git a/vendor/golang.org/x/sys/unix/types_dragonfly.go b/vendor/golang.org/x/sys/unix/types_dragonfly.go index 46d7da96d1..0c63304839 100644 --- a/vendor/golang.org/x/sys/unix/types_dragonfly.go +++ b/vendor/golang.org/x/sys/unix/types_dragonfly.go @@ -35,6 +35,7 @@ package unix #include <sys/time.h> #include <sys/types.h> #include <sys/un.h> +#include <sys/utsname.h> #include <sys/wait.h> #include <net/bpf.h> #include <net/if.h> @@ -126,6 +127,12 @@ type Dirent C.struct_dirent type Fsid C.struct_fsid +// File system limits + +const ( + PathMax = C.PATH_MAX +) + // Sockets type RawSockaddrInet4 C.struct_sockaddr_in @@ -267,3 +274,7 @@ const ( POLLWRBAND = C.POLLWRBAND POLLWRNORM = C.POLLWRNORM ) + +// Uname + +type Utsname C.struct_utsname diff --git a/vendor/golang.org/x/sys/unix/types_freebsd.go b/vendor/golang.org/x/sys/unix/types_freebsd.go index 7340004ef0..4eb02cd4da 100644 --- a/vendor/golang.org/x/sys/unix/types_freebsd.go +++ b/vendor/golang.org/x/sys/unix/types_freebsd.go @@ -36,6 +36,7 @@ package unix #include <sys/time.h> #include <sys/types.h> #include <sys/un.h> +#include <sys/utsname.h> #include <sys/wait.h> #include <net/bpf.h> #include <net/if.h> @@ -215,6 +216,12 @@ type Dirent C.struct_dirent type Fsid C.struct_fsid +// File system limits + +const ( + PathMax = C.PATH_MAX +) + // Advice to Fadvise const ( @@ -389,3 +396,7 @@ const ( // Capabilities type CapRights C.struct_cap_rights + +// Uname + +type Utsname C.struct_utsname diff --git a/vendor/golang.org/x/sys/unix/types_netbsd.go b/vendor/golang.org/x/sys/unix/types_netbsd.go index 7ff50bc848..1494aafcbb 100644 --- a/vendor/golang.org/x/sys/unix/types_netbsd.go +++ b/vendor/golang.org/x/sys/unix/types_netbsd.go @@ -37,6 +37,7 @@ package unix #include <sys/time.h> #include <sys/uio.h> #include <sys/un.h> +#include <sys/utsname.h> #include <sys/wait.h> #include <net/bpf.h> #include <net/if.h> @@ -111,6 +112,23 @@ type Dirent C.struct_dirent type Fsid C.fsid_t +// File system limits + +const ( + PathMax = C.PATH_MAX +) + +// Advice to Fadvise + +const ( + FADV_NORMAL = C.POSIX_FADV_NORMAL + FADV_RANDOM = C.POSIX_FADV_RANDOM + FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL + FADV_WILLNEED = C.POSIX_FADV_WILLNEED + FADV_DONTNEED = C.POSIX_FADV_DONTNEED + FADV_NOREUSE = C.POSIX_FADV_NOREUSE +) + // Sockets type RawSockaddrInet4 C.struct_sockaddr_in @@ -257,3 +275,7 @@ const ( // Sysctl type Sysctlnode C.struct_sysctlnode + +// Uname + +type Utsname C.struct_utsname diff --git a/vendor/golang.org/x/sys/unix/types_openbsd.go b/vendor/golang.org/x/sys/unix/types_openbsd.go index 837b514dc6..649e55998f 100644 --- a/vendor/golang.org/x/sys/unix/types_openbsd.go +++ b/vendor/golang.org/x/sys/unix/types_openbsd.go @@ -36,6 +36,7 @@ package unix #include <sys/time.h> #include <sys/uio.h> #include <sys/un.h> +#include <sys/utsname.h> #include <sys/wait.h> #include <net/bpf.h> #include <net/if.h> @@ -127,6 +128,12 @@ type Dirent C.struct_dirent type Fsid C.fsid_t +// File system limits + +const ( + PathMax = C.PATH_MAX +) + // Sockets type RawSockaddrInet4 C.struct_sockaddr_in @@ -269,3 +276,7 @@ const ( POLLWRBAND = C.POLLWRBAND POLLWRNORM = C.POLLWRNORM ) + +// Uname + +type Utsname C.struct_utsname diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_386.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_386.go index c90ebcf7a2..3b39d7408a 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_darwin_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_386.go @@ -249,6 +249,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 @@ -532,6 +534,7 @@ const ( F_VOLPOSMODE = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -878,6 +881,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -1466,6 +1473,12 @@ const ( WORDSIZE = 0x20 WSTOPPED = 0x8 WUNTRACED = 0x2 + XATTR_CREATE = 0x2 + XATTR_NODEFAULT = 0x10 + XATTR_NOFOLLOW = 0x1 + XATTR_NOSECURITY = 0x8 + XATTR_REPLACE = 0x4 + XATTR_SHOWCOMPRESSION = 0x20 ) // Errors @@ -1617,146 +1630,154 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "resource busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "device power is off", - 83: "device error", - 84: "value too large to be stored in data type", - 85: "bad executable (or shared library)", - 86: "bad CPU type in executable", - 87: "shared library version mismatch", - 88: "malformed Mach-o file", - 89: "operation canceled", - 90: "identifier removed", - 91: "no message of desired type", - 92: "illegal byte sequence", - 93: "attribute not found", - 94: "bad message", - 95: "EMULTIHOP (Reserved)", - 96: "no message available on STREAM", - 97: "ENOLINK (Reserved)", - 98: "no STREAM resources", - 99: "not a STREAM", - 100: "protocol error", - 101: "STREAM ioctl timeout", - 102: "operation not supported on socket", - 103: "policy not found", - 104: "state not recoverable", - 105: "previous owner died", - 106: "interface output queue is full", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "ENOTSUP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EPWROFF", "device power is off"}, + {83, "EDEVERR", "device error"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "EBADEXEC", "bad executable (or shared library)"}, + {86, "EBADARCH", "bad CPU type in executable"}, + {87, "ESHLIBVERS", "shared library version mismatch"}, + {88, "EBADMACHO", "malformed Mach-o file"}, + {89, "ECANCELED", "operation canceled"}, + {90, "EIDRM", "identifier removed"}, + {91, "ENOMSG", "no message of desired type"}, + {92, "EILSEQ", "illegal byte sequence"}, + {93, "ENOATTR", "attribute not found"}, + {94, "EBADMSG", "bad message"}, + {95, "EMULTIHOP", "EMULTIHOP (Reserved)"}, + {96, "ENODATA", "no message available on STREAM"}, + {97, "ENOLINK", "ENOLINK (Reserved)"}, + {98, "ENOSR", "no STREAM resources"}, + {99, "ENOSTR", "not a STREAM"}, + {100, "EPROTO", "protocol error"}, + {101, "ETIME", "STREAM ioctl timeout"}, + {102, "EOPNOTSUPP", "operation not supported on socket"}, + {103, "ENOPOLICY", "policy not found"}, + {104, "ENOTRECOVERABLE", "state not recoverable"}, + {105, "EOWNERDEAD", "previous owner died"}, + {106, "EQFULL", "interface output queue is full"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGABRT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go index 8991948649..8fe5547775 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go @@ -249,6 +249,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 @@ -532,6 +534,7 @@ const ( F_VOLPOSMODE = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -878,6 +881,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -1466,6 +1473,12 @@ const ( WORDSIZE = 0x40 WSTOPPED = 0x8 WUNTRACED = 0x2 + XATTR_CREATE = 0x2 + XATTR_NODEFAULT = 0x10 + XATTR_NOFOLLOW = 0x1 + XATTR_NOSECURITY = 0x8 + XATTR_REPLACE = 0x4 + XATTR_SHOWCOMPRESSION = 0x20 ) // Errors @@ -1617,146 +1630,154 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "resource busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "device power is off", - 83: "device error", - 84: "value too large to be stored in data type", - 85: "bad executable (or shared library)", - 86: "bad CPU type in executable", - 87: "shared library version mismatch", - 88: "malformed Mach-o file", - 89: "operation canceled", - 90: "identifier removed", - 91: "no message of desired type", - 92: "illegal byte sequence", - 93: "attribute not found", - 94: "bad message", - 95: "EMULTIHOP (Reserved)", - 96: "no message available on STREAM", - 97: "ENOLINK (Reserved)", - 98: "no STREAM resources", - 99: "not a STREAM", - 100: "protocol error", - 101: "STREAM ioctl timeout", - 102: "operation not supported on socket", - 103: "policy not found", - 104: "state not recoverable", - 105: "previous owner died", - 106: "interface output queue is full", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "ENOTSUP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EPWROFF", "device power is off"}, + {83, "EDEVERR", "device error"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "EBADEXEC", "bad executable (or shared library)"}, + {86, "EBADARCH", "bad CPU type in executable"}, + {87, "ESHLIBVERS", "shared library version mismatch"}, + {88, "EBADMACHO", "malformed Mach-o file"}, + {89, "ECANCELED", "operation canceled"}, + {90, "EIDRM", "identifier removed"}, + {91, "ENOMSG", "no message of desired type"}, + {92, "EILSEQ", "illegal byte sequence"}, + {93, "ENOATTR", "attribute not found"}, + {94, "EBADMSG", "bad message"}, + {95, "EMULTIHOP", "EMULTIHOP (Reserved)"}, + {96, "ENODATA", "no message available on STREAM"}, + {97, "ENOLINK", "ENOLINK (Reserved)"}, + {98, "ENOSR", "no STREAM resources"}, + {99, "ENOSTR", "not a STREAM"}, + {100, "EPROTO", "protocol error"}, + {101, "ETIME", "STREAM ioctl timeout"}, + {102, "EOPNOTSUPP", "operation not supported on socket"}, + {103, "ENOPOLICY", "policy not found"}, + {104, "ENOTRECOVERABLE", "state not recoverable"}, + {105, "EOWNERDEAD", "previous owner died"}, + {106, "EQFULL", "interface output queue is full"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGABRT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go index c41a6b8790..7a977770d0 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go @@ -249,6 +249,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 @@ -532,6 +534,7 @@ const ( F_VOLPOSMODE = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -878,6 +881,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -1466,6 +1473,12 @@ const ( WORDSIZE = 0x40 WSTOPPED = 0x8 WUNTRACED = 0x2 + XATTR_CREATE = 0x2 + XATTR_NODEFAULT = 0x10 + XATTR_NOFOLLOW = 0x1 + XATTR_NOSECURITY = 0x8 + XATTR_REPLACE = 0x4 + XATTR_SHOWCOMPRESSION = 0x20 ) // Errors @@ -1617,146 +1630,154 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "resource busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "device power is off", - 83: "device error", - 84: "value too large to be stored in data type", - 85: "bad executable (or shared library)", - 86: "bad CPU type in executable", - 87: "shared library version mismatch", - 88: "malformed Mach-o file", - 89: "operation canceled", - 90: "identifier removed", - 91: "no message of desired type", - 92: "illegal byte sequence", - 93: "attribute not found", - 94: "bad message", - 95: "EMULTIHOP (Reserved)", - 96: "no message available on STREAM", - 97: "ENOLINK (Reserved)", - 98: "no STREAM resources", - 99: "not a STREAM", - 100: "protocol error", - 101: "STREAM ioctl timeout", - 102: "operation not supported on socket", - 103: "policy not found", - 104: "state not recoverable", - 105: "previous owner died", - 106: "interface output queue is full", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "ENOTSUP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EPWROFF", "device power is off"}, + {83, "EDEVERR", "device error"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "EBADEXEC", "bad executable (or shared library)"}, + {86, "EBADARCH", "bad CPU type in executable"}, + {87, "ESHLIBVERS", "shared library version mismatch"}, + {88, "EBADMACHO", "malformed Mach-o file"}, + {89, "ECANCELED", "operation canceled"}, + {90, "EIDRM", "identifier removed"}, + {91, "ENOMSG", "no message of desired type"}, + {92, "EILSEQ", "illegal byte sequence"}, + {93, "ENOATTR", "attribute not found"}, + {94, "EBADMSG", "bad message"}, + {95, "EMULTIHOP", "EMULTIHOP (Reserved)"}, + {96, "ENODATA", "no message available on STREAM"}, + {97, "ENOLINK", "ENOLINK (Reserved)"}, + {98, "ENOSR", "no STREAM resources"}, + {99, "ENOSTR", "not a STREAM"}, + {100, "EPROTO", "protocol error"}, + {101, "ETIME", "STREAM ioctl timeout"}, + {102, "EOPNOTSUPP", "operation not supported on socket"}, + {103, "ENOPOLICY", "policy not found"}, + {104, "ENOTRECOVERABLE", "state not recoverable"}, + {105, "EOWNERDEAD", "previous owner died"}, + {106, "EQFULL", "interface output queue is full"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGABRT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go index 73f8c8784c..6d56d8a059 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go @@ -249,6 +249,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 @@ -532,6 +534,7 @@ const ( F_VOLPOSMODE = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -878,6 +881,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -1466,6 +1473,12 @@ const ( WORDSIZE = 0x40 WSTOPPED = 0x8 WUNTRACED = 0x2 + XATTR_CREATE = 0x2 + XATTR_NODEFAULT = 0x10 + XATTR_NOFOLLOW = 0x1 + XATTR_NOSECURITY = 0x8 + XATTR_REPLACE = 0x4 + XATTR_SHOWCOMPRESSION = 0x20 ) // Errors @@ -1617,146 +1630,154 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "resource busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "device power is off", - 83: "device error", - 84: "value too large to be stored in data type", - 85: "bad executable (or shared library)", - 86: "bad CPU type in executable", - 87: "shared library version mismatch", - 88: "malformed Mach-o file", - 89: "operation canceled", - 90: "identifier removed", - 91: "no message of desired type", - 92: "illegal byte sequence", - 93: "attribute not found", - 94: "bad message", - 95: "EMULTIHOP (Reserved)", - 96: "no message available on STREAM", - 97: "ENOLINK (Reserved)", - 98: "no STREAM resources", - 99: "not a STREAM", - 100: "protocol error", - 101: "STREAM ioctl timeout", - 102: "operation not supported on socket", - 103: "policy not found", - 104: "state not recoverable", - 105: "previous owner died", - 106: "interface output queue is full", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "ENOTSUP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EPWROFF", "device power is off"}, + {83, "EDEVERR", "device error"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "EBADEXEC", "bad executable (or shared library)"}, + {86, "EBADARCH", "bad CPU type in executable"}, + {87, "ESHLIBVERS", "shared library version mismatch"}, + {88, "EBADMACHO", "malformed Mach-o file"}, + {89, "ECANCELED", "operation canceled"}, + {90, "EIDRM", "identifier removed"}, + {91, "ENOMSG", "no message of desired type"}, + {92, "EILSEQ", "illegal byte sequence"}, + {93, "ENOATTR", "attribute not found"}, + {94, "EBADMSG", "bad message"}, + {95, "EMULTIHOP", "EMULTIHOP (Reserved)"}, + {96, "ENODATA", "no message available on STREAM"}, + {97, "ENOLINK", "ENOLINK (Reserved)"}, + {98, "ENOSR", "no STREAM resources"}, + {99, "ENOSTR", "not a STREAM"}, + {100, "EPROTO", "protocol error"}, + {101, "ETIME", "STREAM ioctl timeout"}, + {102, "EOPNOTSUPP", "operation not supported on socket"}, + {103, "ENOPOLICY", "policy not found"}, + {104, "ENOTRECOVERABLE", "state not recoverable"}, + {105, "EOWNERDEAD", "previous owner died"}, + {106, "EQFULL", "interface output queue is full"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGABRT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go index 8f40598bb3..46a082b6d5 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go @@ -168,6 +168,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_A429 = 0xb8 @@ -353,6 +355,7 @@ const ( F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -835,6 +838,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -973,7 +980,10 @@ const ( RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 + RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 + RLIMIT_NPROC = 0x7 + RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 @@ -1427,142 +1437,150 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "operation canceled", - 86: "illegal byte sequence", - 87: "attribute not found", - 88: "programming error", - 89: "bad message", - 90: "multihop attempted", - 91: "link has been severed", - 92: "protocol error", - 93: "no medium found", - 94: "unknown error: 94", - 95: "unknown error: 95", - 96: "unknown error: 96", - 97: "unknown error: 97", - 98: "unknown error: 98", - 99: "unknown error: 99", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EWOULDBLOCK", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "EOPNOTSUPP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EIDRM", "identifier removed"}, + {83, "ENOMSG", "no message of desired type"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "ECANCELED", "operation canceled"}, + {86, "EILSEQ", "illegal byte sequence"}, + {87, "ENOATTR", "attribute not found"}, + {88, "EDOOFUS", "programming error"}, + {89, "EBADMSG", "bad message"}, + {90, "EMULTIHOP", "multihop attempted"}, + {91, "ENOLINK", "link has been severed"}, + {92, "EPROTO", "protocol error"}, + {93, "ENOMEDIUM", "no medium found"}, + {94, "EUNUSED94", "unknown error: 94"}, + {95, "EUNUSED95", "unknown error: 95"}, + {96, "EUNUSED96", "unknown error: 96"}, + {97, "EUNUSED97", "unknown error: 97"}, + {98, "EUNUSED98", "unknown error: 98"}, + {99, "ELAST", "unknown error: 99"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "thread Scheduler", - 33: "checkPoint", - 34: "checkPointExit", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGIOT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, + {32, "SIGTHR", "thread Scheduler"}, + {33, "SIGCKPT", "checkPoint"}, + {34, "SIGCKPTEXIT", "checkPointExit"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go index adf5eef0f8..2947dc0382 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go @@ -351,6 +351,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 DLT_A429 = 0xb8 @@ -608,6 +610,7 @@ const ( F_UNLCKSYS = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -944,6 +947,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -1612,138 +1619,146 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "operation canceled", - 86: "illegal byte sequence", - 87: "attribute not found", - 88: "programming error", - 89: "bad message", - 90: "multihop attempted", - 91: "link has been severed", - 92: "protocol error", - 93: "capabilities insufficient", - 94: "not permitted in capability mode", - 95: "state not recoverable", - 96: "previous owner died", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "EOPNOTSUPP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EIDRM", "identifier removed"}, + {83, "ENOMSG", "no message of desired type"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "ECANCELED", "operation canceled"}, + {86, "EILSEQ", "illegal byte sequence"}, + {87, "ENOATTR", "attribute not found"}, + {88, "EDOOFUS", "programming error"}, + {89, "EBADMSG", "bad message"}, + {90, "EMULTIHOP", "multihop attempted"}, + {91, "ENOLINK", "link has been severed"}, + {92, "EPROTO", "protocol error"}, + {93, "ENOTCAPABLE", "capabilities insufficient"}, + {94, "ECAPMODE", "not permitted in capability mode"}, + {95, "ENOTRECOVERABLE", "state not recoverable"}, + {96, "EOWNERDEAD", "previous owner died"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "unknown signal", - 33: "unknown signal", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGIOT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, + {32, "SIGTHR", "unknown signal"}, + {33, "SIGLIBRT", "unknown signal"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go index 360caff4f9..c600d012d0 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go @@ -351,6 +351,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 DLT_A429 = 0xb8 @@ -608,6 +610,7 @@ const ( F_UNLCKSYS = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -944,6 +947,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -1613,138 +1620,146 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "operation canceled", - 86: "illegal byte sequence", - 87: "attribute not found", - 88: "programming error", - 89: "bad message", - 90: "multihop attempted", - 91: "link has been severed", - 92: "protocol error", - 93: "capabilities insufficient", - 94: "not permitted in capability mode", - 95: "state not recoverable", - 96: "previous owner died", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "EOPNOTSUPP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EIDRM", "identifier removed"}, + {83, "ENOMSG", "no message of desired type"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "ECANCELED", "operation canceled"}, + {86, "EILSEQ", "illegal byte sequence"}, + {87, "ENOATTR", "attribute not found"}, + {88, "EDOOFUS", "programming error"}, + {89, "EBADMSG", "bad message"}, + {90, "EMULTIHOP", "multihop attempted"}, + {91, "ENOLINK", "link has been severed"}, + {92, "EPROTO", "protocol error"}, + {93, "ENOTCAPABLE", "capabilities insufficient"}, + {94, "ECAPMODE", "not permitted in capability mode"}, + {95, "ENOTRECOVERABLE", "state not recoverable"}, + {96, "EOWNERDEAD", "previous owner died"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "unknown signal", - 33: "unknown signal", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGIOT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, + {32, "SIGTHR", "unknown signal"}, + {33, "SIGLIBRT", "unknown signal"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go index 87deda950e..e8240d2397 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go @@ -351,6 +351,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0x18 CTL_NET = 0x4 DLT_A429 = 0xb8 @@ -615,6 +617,7 @@ const ( F_UNLCKSYS = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -951,6 +954,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -1621,138 +1628,146 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "operation timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "operation canceled", - 86: "illegal byte sequence", - 87: "attribute not found", - 88: "programming error", - 89: "bad message", - 90: "multihop attempted", - 91: "link has been severed", - 92: "protocol error", - 93: "capabilities insufficient", - 94: "not permitted in capability mode", - 95: "state not recoverable", - 96: "previous owner died", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "EOPNOTSUPP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EIDRM", "identifier removed"}, + {83, "ENOMSG", "no message of desired type"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "ECANCELED", "operation canceled"}, + {86, "EILSEQ", "illegal byte sequence"}, + {87, "ENOATTR", "attribute not found"}, + {88, "EDOOFUS", "programming error"}, + {89, "EBADMSG", "bad message"}, + {90, "EMULTIHOP", "multihop attempted"}, + {91, "ENOLINK", "link has been severed"}, + {92, "EPROTO", "protocol error"}, + {93, "ENOTCAPABLE", "capabilities insufficient"}, + {94, "ECAPMODE", "not permitted in capability mode"}, + {95, "ENOTRECOVERABLE", "state not recoverable"}, + {96, "EOWNERDEAD", "previous owner died"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "suspended (signal)", - 18: "suspended", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "unknown signal", - 33: "unknown signal", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGIOT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, + {32, "SIGTHR", "unknown signal"}, + {33, "SIGLIBRT", "unknown signal"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go index 8947248f68..ee17d4bd4a 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_386.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x1007 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x80041270 BLKBSZSET = 0x40041271 BLKFLSBUF = 0x1261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -390,6 +414,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -398,6 +424,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -408,11 +435,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -440,9 +469,14 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -456,6 +490,7 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FP_XSTATE_MAGIC2 = 0x46505845 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 @@ -476,6 +511,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -488,6 +525,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -495,6 +535,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -506,6 +550,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -527,6 +573,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 @@ -561,6 +650,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -775,12 +866,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -845,6 +938,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -853,6 +947,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_32BIT = 0x40 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 @@ -875,9 +970,15 @@ const ( MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -899,6 +1000,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -936,7 +1038,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -971,6 +1075,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 @@ -998,10 +1133,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1009,7 +1147,9 @@ const ( ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 @@ -1096,14 +1236,17 @@ const ( PERF_EVENT_IOC_ID = 0x80042407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409 PERF_EVENT_IOC_PERIOD = 0x40082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc004240a PERF_EVENT_IOC_REFRESH = 0x2402 PERF_EVENT_IOC_RESET = 0x2403 PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40042406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1196,6 +1339,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1204,6 +1352,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -1247,6 +1396,7 @@ const ( PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETFPXREGS = 0x13 @@ -1262,6 +1412,11 @@ const ( PTRACE_SYSEMU = 0x1f PTRACE_SYSEMU_SINGLESTEP = 0x20 PTRACE_TRACEME = 0x0 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1282,6 +1437,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1292,7 +1448,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1446,6 +1602,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1530,6 +1688,23 @@ const ( SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 @@ -1566,6 +1741,7 @@ const ( SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e @@ -1634,10 +1810,35 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1709,6 +1910,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1729,6 +1932,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 @@ -1816,7 +2020,27 @@ const ( TIOCSTI = 0x5412 TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x100 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x400854d5 TUNDETACHFILTER = 0x400854d6 @@ -1828,6 +2052,7 @@ const ( TUNGETVNETHDRSZ = 0x800454d7 TUNGETVNETLE = 0x800454dd TUNSETDEBUG = 0x400454c9 + TUNSETFILTEREBPF = 0x800454e1 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da @@ -1838,13 +2063,17 @@ const ( TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 + TUNSETSTEERINGEBPF = 0x800454e0 TUNSETTXFILTER = 0x400454d1 TUNSETVNETBE = 0x400454de TUNSETVNETHDRSZ = 0x400454d8 TUNSETVNETLE = 0x400454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb @@ -1886,16 +2115,99 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 WORDSIZE = 0x20 WSTOPPED = 0x2 WUNTRACED = 0x2 + X86_FXSR_MAGIC = 0x0 XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0x1800 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2075,171 +2387,179 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "memory page has hardware error", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "EDEADLK", "resource deadlock avoided"}, + {36, "ENAMETOOLONG", "file name too long"}, + {37, "ENOLCK", "no locks available"}, + {38, "ENOSYS", "function not implemented"}, + {39, "ENOTEMPTY", "directory not empty"}, + {40, "ELOOP", "too many levels of symbolic links"}, + {42, "ENOMSG", "no message of desired type"}, + {43, "EIDRM", "identifier removed"}, + {44, "ECHRNG", "channel number out of range"}, + {45, "EL2NSYNC", "level 2 not synchronized"}, + {46, "EL3HLT", "level 3 halted"}, + {47, "EL3RST", "level 3 reset"}, + {48, "ELNRNG", "link number out of range"}, + {49, "EUNATCH", "protocol driver not attached"}, + {50, "ENOCSI", "no CSI structure available"}, + {51, "EL2HLT", "level 2 halted"}, + {52, "EBADE", "invalid exchange"}, + {53, "EBADR", "invalid request descriptor"}, + {54, "EXFULL", "exchange full"}, + {55, "ENOANO", "no anode"}, + {56, "EBADRQC", "invalid request code"}, + {57, "EBADSLT", "invalid slot"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {72, "EMULTIHOP", "multihop attempted"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EBADMSG", "bad message"}, + {75, "EOVERFLOW", "value too large for defined data type"}, + {76, "ENOTUNIQ", "name not unique on network"}, + {77, "EBADFD", "file descriptor in bad state"}, + {78, "EREMCHG", "remote address changed"}, + {79, "ELIBACC", "can not access a needed shared library"}, + {80, "ELIBBAD", "accessing a corrupted shared library"}, + {81, "ELIBSCN", ".lib section in a.out corrupted"}, + {82, "ELIBMAX", "attempting to link in too many shared libraries"}, + {83, "ELIBEXEC", "cannot exec a shared library directly"}, + {84, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {85, "ERESTART", "interrupted system call should be restarted"}, + {86, "ESTRPIPE", "streams pipe error"}, + {87, "EUSERS", "too many users"}, + {88, "ENOTSOCK", "socket operation on non-socket"}, + {89, "EDESTADDRREQ", "destination address required"}, + {90, "EMSGSIZE", "message too long"}, + {91, "EPROTOTYPE", "protocol wrong type for socket"}, + {92, "ENOPROTOOPT", "protocol not available"}, + {93, "EPROTONOSUPPORT", "protocol not supported"}, + {94, "ESOCKTNOSUPPORT", "socket type not supported"}, + {95, "ENOTSUP", "operation not supported"}, + {96, "EPFNOSUPPORT", "protocol family not supported"}, + {97, "EAFNOSUPPORT", "address family not supported by protocol"}, + {98, "EADDRINUSE", "address already in use"}, + {99, "EADDRNOTAVAIL", "cannot assign requested address"}, + {100, "ENETDOWN", "network is down"}, + {101, "ENETUNREACH", "network is unreachable"}, + {102, "ENETRESET", "network dropped connection on reset"}, + {103, "ECONNABORTED", "software caused connection abort"}, + {104, "ECONNRESET", "connection reset by peer"}, + {105, "ENOBUFS", "no buffer space available"}, + {106, "EISCONN", "transport endpoint is already connected"}, + {107, "ENOTCONN", "transport endpoint is not connected"}, + {108, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {109, "ETOOMANYREFS", "too many references: cannot splice"}, + {110, "ETIMEDOUT", "connection timed out"}, + {111, "ECONNREFUSED", "connection refused"}, + {112, "EHOSTDOWN", "host is down"}, + {113, "EHOSTUNREACH", "no route to host"}, + {114, "EALREADY", "operation already in progress"}, + {115, "EINPROGRESS", "operation now in progress"}, + {116, "ESTALE", "stale file handle"}, + {117, "EUCLEAN", "structure needs cleaning"}, + {118, "ENOTNAM", "not a XENIX named type file"}, + {119, "ENAVAIL", "no XENIX semaphores available"}, + {120, "EISNAM", "is a named type file"}, + {121, "EREMOTEIO", "remote I/O error"}, + {122, "EDQUOT", "disk quota exceeded"}, + {123, "ENOMEDIUM", "no medium found"}, + {124, "EMEDIUMTYPE", "wrong medium type"}, + {125, "ECANCELED", "operation canceled"}, + {126, "ENOKEY", "required key not available"}, + {127, "EKEYEXPIRED", "key has expired"}, + {128, "EKEYREVOKED", "key has been revoked"}, + {129, "EKEYREJECTED", "key was rejected by service"}, + {130, "EOWNERDEAD", "owner died"}, + {131, "ENOTRECOVERABLE", "state not recoverable"}, + {132, "ERFKILL", "operation not possible due to RF-kill"}, + {133, "EHWPOISON", "memory page has hardware error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGBUS", "bus error"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGUSR1", "user defined signal 1"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGUSR2", "user defined signal 2"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGSTKFLT", "stack fault"}, + {17, "SIGCHLD", "child exited"}, + {18, "SIGCONT", "continued"}, + {19, "SIGSTOP", "stopped (signal)"}, + {20, "SIGTSTP", "stopped"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGURG", "urgent I/O condition"}, + {24, "SIGXCPU", "CPU time limit exceeded"}, + {25, "SIGXFSZ", "file size limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window changed"}, + {29, "SIGIO", "I/O possible"}, + {30, "SIGPWR", "power failure"}, + {31, "SIGSYS", "bad system call"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go index 4083cb2a86..64ab9f40ad 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x1007 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 BLKFLSBUF = 0x1261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -390,6 +414,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -398,6 +424,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -408,11 +435,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -440,9 +469,14 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -456,6 +490,7 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FP_XSTATE_MAGIC2 = 0x46505845 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 @@ -476,6 +511,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -488,6 +525,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -495,6 +535,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -506,6 +550,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -527,6 +573,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 @@ -561,6 +650,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -775,12 +866,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -845,6 +938,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -853,6 +947,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_32BIT = 0x40 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 @@ -875,9 +970,15 @@ const ( MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -899,6 +1000,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -936,7 +1038,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -971,6 +1075,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 @@ -998,10 +1133,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1009,7 +1147,9 @@ const ( ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 @@ -1096,14 +1236,17 @@ const ( PERF_EVENT_IOC_ID = 0x80082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409 PERF_EVENT_IOC_PERIOD = 0x40082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc008240a PERF_EVENT_IOC_REFRESH = 0x2402 PERF_EVENT_IOC_RESET = 0x2403 PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40082406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1196,6 +1339,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1204,6 +1352,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ARCH_PRCTL = 0x1e PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 @@ -1248,6 +1397,7 @@ const ( PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETFPXREGS = 0x13 @@ -1263,6 +1413,11 @@ const ( PTRACE_SYSEMU = 0x1f PTRACE_SYSEMU_SINGLESTEP = 0x20 PTRACE_TRACEME = 0x0 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1283,6 +1438,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1293,7 +1449,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1447,6 +1603,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1531,6 +1689,23 @@ const ( SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 @@ -1567,6 +1742,7 @@ const ( SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e @@ -1635,10 +1811,35 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1710,6 +1911,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1730,6 +1933,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 @@ -1817,7 +2021,27 @@ const ( TIOCSTI = 0x5412 TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x100 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 @@ -1829,6 +2053,7 @@ const ( TUNGETVNETHDRSZ = 0x800454d7 TUNGETVNETLE = 0x800454dd TUNSETDEBUG = 0x400454c9 + TUNSETFILTEREBPF = 0x800454e1 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da @@ -1839,13 +2064,17 @@ const ( TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 + TUNSETSTEERINGEBPF = 0x800454e0 TUNSETTXFILTER = 0x400454d1 TUNSETVNETBE = 0x400454de TUNSETVNETHDRSZ = 0x400454d8 TUNSETVNETLE = 0x400454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb @@ -1887,6 +2116,86 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 @@ -1896,7 +2205,9 @@ const ( XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0x1800 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2076,171 +2387,179 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "memory page has hardware error", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "EDEADLK", "resource deadlock avoided"}, + {36, "ENAMETOOLONG", "file name too long"}, + {37, "ENOLCK", "no locks available"}, + {38, "ENOSYS", "function not implemented"}, + {39, "ENOTEMPTY", "directory not empty"}, + {40, "ELOOP", "too many levels of symbolic links"}, + {42, "ENOMSG", "no message of desired type"}, + {43, "EIDRM", "identifier removed"}, + {44, "ECHRNG", "channel number out of range"}, + {45, "EL2NSYNC", "level 2 not synchronized"}, + {46, "EL3HLT", "level 3 halted"}, + {47, "EL3RST", "level 3 reset"}, + {48, "ELNRNG", "link number out of range"}, + {49, "EUNATCH", "protocol driver not attached"}, + {50, "ENOCSI", "no CSI structure available"}, + {51, "EL2HLT", "level 2 halted"}, + {52, "EBADE", "invalid exchange"}, + {53, "EBADR", "invalid request descriptor"}, + {54, "EXFULL", "exchange full"}, + {55, "ENOANO", "no anode"}, + {56, "EBADRQC", "invalid request code"}, + {57, "EBADSLT", "invalid slot"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {72, "EMULTIHOP", "multihop attempted"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EBADMSG", "bad message"}, + {75, "EOVERFLOW", "value too large for defined data type"}, + {76, "ENOTUNIQ", "name not unique on network"}, + {77, "EBADFD", "file descriptor in bad state"}, + {78, "EREMCHG", "remote address changed"}, + {79, "ELIBACC", "can not access a needed shared library"}, + {80, "ELIBBAD", "accessing a corrupted shared library"}, + {81, "ELIBSCN", ".lib section in a.out corrupted"}, + {82, "ELIBMAX", "attempting to link in too many shared libraries"}, + {83, "ELIBEXEC", "cannot exec a shared library directly"}, + {84, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {85, "ERESTART", "interrupted system call should be restarted"}, + {86, "ESTRPIPE", "streams pipe error"}, + {87, "EUSERS", "too many users"}, + {88, "ENOTSOCK", "socket operation on non-socket"}, + {89, "EDESTADDRREQ", "destination address required"}, + {90, "EMSGSIZE", "message too long"}, + {91, "EPROTOTYPE", "protocol wrong type for socket"}, + {92, "ENOPROTOOPT", "protocol not available"}, + {93, "EPROTONOSUPPORT", "protocol not supported"}, + {94, "ESOCKTNOSUPPORT", "socket type not supported"}, + {95, "ENOTSUP", "operation not supported"}, + {96, "EPFNOSUPPORT", "protocol family not supported"}, + {97, "EAFNOSUPPORT", "address family not supported by protocol"}, + {98, "EADDRINUSE", "address already in use"}, + {99, "EADDRNOTAVAIL", "cannot assign requested address"}, + {100, "ENETDOWN", "network is down"}, + {101, "ENETUNREACH", "network is unreachable"}, + {102, "ENETRESET", "network dropped connection on reset"}, + {103, "ECONNABORTED", "software caused connection abort"}, + {104, "ECONNRESET", "connection reset by peer"}, + {105, "ENOBUFS", "no buffer space available"}, + {106, "EISCONN", "transport endpoint is already connected"}, + {107, "ENOTCONN", "transport endpoint is not connected"}, + {108, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {109, "ETOOMANYREFS", "too many references: cannot splice"}, + {110, "ETIMEDOUT", "connection timed out"}, + {111, "ECONNREFUSED", "connection refused"}, + {112, "EHOSTDOWN", "host is down"}, + {113, "EHOSTUNREACH", "no route to host"}, + {114, "EALREADY", "operation already in progress"}, + {115, "EINPROGRESS", "operation now in progress"}, + {116, "ESTALE", "stale file handle"}, + {117, "EUCLEAN", "structure needs cleaning"}, + {118, "ENOTNAM", "not a XENIX named type file"}, + {119, "ENAVAIL", "no XENIX semaphores available"}, + {120, "EISNAM", "is a named type file"}, + {121, "EREMOTEIO", "remote I/O error"}, + {122, "EDQUOT", "disk quota exceeded"}, + {123, "ENOMEDIUM", "no medium found"}, + {124, "EMEDIUMTYPE", "wrong medium type"}, + {125, "ECANCELED", "operation canceled"}, + {126, "ENOKEY", "required key not available"}, + {127, "EKEYEXPIRED", "key has expired"}, + {128, "EKEYREVOKED", "key has been revoked"}, + {129, "EKEYREJECTED", "key was rejected by service"}, + {130, "EOWNERDEAD", "owner died"}, + {131, "ENOTRECOVERABLE", "state not recoverable"}, + {132, "ERFKILL", "operation not possible due to RF-kill"}, + {133, "EHWPOISON", "memory page has hardware error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGBUS", "bus error"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGUSR1", "user defined signal 1"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGUSR2", "user defined signal 2"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGSTKFLT", "stack fault"}, + {17, "SIGCHLD", "child exited"}, + {18, "SIGCONT", "continued"}, + {19, "SIGSTOP", "stopped (signal)"}, + {20, "SIGTSTP", "stopped"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGURG", "urgent I/O condition"}, + {24, "SIGXCPU", "CPU time limit exceeded"}, + {25, "SIGXFSZ", "file size limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window changed"}, + {29, "SIGIO", "I/O possible"}, + {30, "SIGPWR", "power failure"}, + {31, "SIGSYS", "bad system call"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go index 27d38352bd..6ae0ac6f86 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x1007 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x80041270 BLKBSZSET = 0x40041271 BLKFLSBUF = 0x1261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -390,6 +414,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -398,6 +424,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -408,11 +435,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -440,9 +469,14 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -476,6 +510,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -488,6 +524,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -495,6 +534,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -506,6 +549,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -527,6 +572,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 @@ -561,6 +649,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -775,12 +865,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -845,6 +937,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -853,6 +946,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 @@ -874,9 +968,15 @@ const ( MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -898,6 +998,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -935,7 +1036,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -970,6 +1073,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 @@ -997,10 +1131,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1008,7 +1145,9 @@ const ( ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 @@ -1095,14 +1234,17 @@ const ( PERF_EVENT_IOC_ID = 0x80042407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409 PERF_EVENT_IOC_PERIOD = 0x40082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc004240a PERF_EVENT_IOC_REFRESH = 0x2402 PERF_EVENT_IOC_RESET = 0x2403 PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40042406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1195,6 +1337,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1203,6 +1350,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -1216,6 +1364,9 @@ const ( PTRACE_EVENT_VFORK_DONE = 0x5 PTRACE_GETCRUNCHREGS = 0x19 PTRACE_GETEVENTMSG = 0x4201 + PTRACE_GETFDPIC = 0x1f + PTRACE_GETFDPIC_EXEC = 0x0 + PTRACE_GETFDPIC_INTERP = 0x1 PTRACE_GETFPREGS = 0xe PTRACE_GETHBPREGS = 0x1d PTRACE_GETREGS = 0xc @@ -1249,6 +1400,7 @@ const ( PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETCRUNCHREGS = 0x1a PTRACE_SETFPREGS = 0xf @@ -1267,6 +1419,11 @@ const ( PT_DATA_ADDR = 0x10004 PT_TEXT_ADDR = 0x10000 PT_TEXT_END_ADDR = 0x10008 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1287,6 +1444,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1297,7 +1455,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1451,6 +1609,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1535,6 +1695,23 @@ const ( SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 @@ -1571,6 +1748,7 @@ const ( SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e @@ -1639,10 +1817,35 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1714,6 +1917,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1734,6 +1939,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 @@ -1821,7 +2027,27 @@ const ( TIOCSTI = 0x5412 TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x100 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x400854d5 TUNDETACHFILTER = 0x400854d6 @@ -1833,6 +2059,7 @@ const ( TUNGETVNETHDRSZ = 0x800454d7 TUNGETVNETLE = 0x800454dd TUNSETDEBUG = 0x400454c9 + TUNSETFILTEREBPF = 0x800454e1 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da @@ -1843,13 +2070,17 @@ const ( TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 + TUNSETSTEERINGEBPF = 0x800454e0 TUNSETTXFILTER = 0x400454d1 TUNSETVNETBE = 0x400454de TUNSETVNETHDRSZ = 0x400454d8 TUNSETVNETLE = 0x400454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb @@ -1891,6 +2122,86 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 @@ -1900,7 +2211,9 @@ const ( XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0x1800 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2080,171 +2393,179 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "memory page has hardware error", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "EDEADLK", "resource deadlock avoided"}, + {36, "ENAMETOOLONG", "file name too long"}, + {37, "ENOLCK", "no locks available"}, + {38, "ENOSYS", "function not implemented"}, + {39, "ENOTEMPTY", "directory not empty"}, + {40, "ELOOP", "too many levels of symbolic links"}, + {42, "ENOMSG", "no message of desired type"}, + {43, "EIDRM", "identifier removed"}, + {44, "ECHRNG", "channel number out of range"}, + {45, "EL2NSYNC", "level 2 not synchronized"}, + {46, "EL3HLT", "level 3 halted"}, + {47, "EL3RST", "level 3 reset"}, + {48, "ELNRNG", "link number out of range"}, + {49, "EUNATCH", "protocol driver not attached"}, + {50, "ENOCSI", "no CSI structure available"}, + {51, "EL2HLT", "level 2 halted"}, + {52, "EBADE", "invalid exchange"}, + {53, "EBADR", "invalid request descriptor"}, + {54, "EXFULL", "exchange full"}, + {55, "ENOANO", "no anode"}, + {56, "EBADRQC", "invalid request code"}, + {57, "EBADSLT", "invalid slot"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {72, "EMULTIHOP", "multihop attempted"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EBADMSG", "bad message"}, + {75, "EOVERFLOW", "value too large for defined data type"}, + {76, "ENOTUNIQ", "name not unique on network"}, + {77, "EBADFD", "file descriptor in bad state"}, + {78, "EREMCHG", "remote address changed"}, + {79, "ELIBACC", "can not access a needed shared library"}, + {80, "ELIBBAD", "accessing a corrupted shared library"}, + {81, "ELIBSCN", ".lib section in a.out corrupted"}, + {82, "ELIBMAX", "attempting to link in too many shared libraries"}, + {83, "ELIBEXEC", "cannot exec a shared library directly"}, + {84, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {85, "ERESTART", "interrupted system call should be restarted"}, + {86, "ESTRPIPE", "streams pipe error"}, + {87, "EUSERS", "too many users"}, + {88, "ENOTSOCK", "socket operation on non-socket"}, + {89, "EDESTADDRREQ", "destination address required"}, + {90, "EMSGSIZE", "message too long"}, + {91, "EPROTOTYPE", "protocol wrong type for socket"}, + {92, "ENOPROTOOPT", "protocol not available"}, + {93, "EPROTONOSUPPORT", "protocol not supported"}, + {94, "ESOCKTNOSUPPORT", "socket type not supported"}, + {95, "ENOTSUP", "operation not supported"}, + {96, "EPFNOSUPPORT", "protocol family not supported"}, + {97, "EAFNOSUPPORT", "address family not supported by protocol"}, + {98, "EADDRINUSE", "address already in use"}, + {99, "EADDRNOTAVAIL", "cannot assign requested address"}, + {100, "ENETDOWN", "network is down"}, + {101, "ENETUNREACH", "network is unreachable"}, + {102, "ENETRESET", "network dropped connection on reset"}, + {103, "ECONNABORTED", "software caused connection abort"}, + {104, "ECONNRESET", "connection reset by peer"}, + {105, "ENOBUFS", "no buffer space available"}, + {106, "EISCONN", "transport endpoint is already connected"}, + {107, "ENOTCONN", "transport endpoint is not connected"}, + {108, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {109, "ETOOMANYREFS", "too many references: cannot splice"}, + {110, "ETIMEDOUT", "connection timed out"}, + {111, "ECONNREFUSED", "connection refused"}, + {112, "EHOSTDOWN", "host is down"}, + {113, "EHOSTUNREACH", "no route to host"}, + {114, "EALREADY", "operation already in progress"}, + {115, "EINPROGRESS", "operation now in progress"}, + {116, "ESTALE", "stale file handle"}, + {117, "EUCLEAN", "structure needs cleaning"}, + {118, "ENOTNAM", "not a XENIX named type file"}, + {119, "ENAVAIL", "no XENIX semaphores available"}, + {120, "EISNAM", "is a named type file"}, + {121, "EREMOTEIO", "remote I/O error"}, + {122, "EDQUOT", "disk quota exceeded"}, + {123, "ENOMEDIUM", "no medium found"}, + {124, "EMEDIUMTYPE", "wrong medium type"}, + {125, "ECANCELED", "operation canceled"}, + {126, "ENOKEY", "required key not available"}, + {127, "EKEYEXPIRED", "key has expired"}, + {128, "EKEYREVOKED", "key has been revoked"}, + {129, "EKEYREJECTED", "key was rejected by service"}, + {130, "EOWNERDEAD", "owner died"}, + {131, "ENOTRECOVERABLE", "state not recoverable"}, + {132, "ERFKILL", "operation not possible due to RF-kill"}, + {133, "EHWPOISON", "memory page has hardware error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGBUS", "bus error"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGUSR1", "user defined signal 1"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGUSR2", "user defined signal 2"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGSTKFLT", "stack fault"}, + {17, "SIGCHLD", "child exited"}, + {18, "SIGCONT", "continued"}, + {19, "SIGSTOP", "stopped (signal)"}, + {20, "SIGTSTP", "stopped"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGURG", "urgent I/O condition"}, + {24, "SIGXCPU", "CPU time limit exceeded"}, + {25, "SIGXFSZ", "file size limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window changed"}, + {29, "SIGIO", "I/O possible"}, + {30, "SIGPWR", "power failure"}, + {31, "SIGSYS", "bad system call"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go index 69ad31470d..f58450bf3d 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x1007 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 BLKFLSBUF = 0x1261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -391,6 +415,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -399,6 +425,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -409,11 +436,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -441,10 +470,15 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 EXTRA_MAGIC = 0x45585401 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -458,6 +492,7 @@ const ( FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 + FPSIMD_MAGIC = 0x46508001 FS_ENCRYPTION_MODE_AES_128_CBC = 0x5 FS_ENCRYPTION_MODE_AES_128_CTS = 0x6 FS_ENCRYPTION_MODE_AES_256_CBC = 0x3 @@ -478,6 +513,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -490,6 +527,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -497,6 +537,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -508,6 +552,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -529,6 +575,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 @@ -563,6 +652,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -777,12 +868,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -847,6 +940,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -855,6 +949,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 @@ -876,9 +971,15 @@ const ( MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -900,6 +1001,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -937,7 +1039,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -972,6 +1076,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 @@ -999,10 +1134,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1010,7 +1148,9 @@ const ( ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 @@ -1097,14 +1237,17 @@ const ( PERF_EVENT_IOC_ID = 0x80082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409 PERF_EVENT_IOC_PERIOD = 0x40082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc008240a PERF_EVENT_IOC_REFRESH = 0x2402 PERF_EVENT_IOC_RESET = 0x2403 PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40082406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1197,6 +1340,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1205,6 +1353,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -1244,6 +1393,7 @@ const ( PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd @@ -1253,6 +1403,11 @@ const ( PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1273,6 +1428,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1283,7 +1439,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1437,6 +1593,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1521,6 +1679,23 @@ const ( SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 @@ -1557,6 +1732,7 @@ const ( SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e @@ -1625,10 +1801,36 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SVE_MAGIC = 0x53564501 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1700,6 +1902,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1720,6 +1924,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 @@ -1807,7 +2012,27 @@ const ( TIOCSTI = 0x5412 TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x100 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 @@ -1819,6 +2044,7 @@ const ( TUNGETVNETHDRSZ = 0x800454d7 TUNGETVNETLE = 0x800454dd TUNSETDEBUG = 0x400454c9 + TUNSETFILTEREBPF = 0x800454e1 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da @@ -1829,13 +2055,17 @@ const ( TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 + TUNSETSTEERINGEBPF = 0x800454e0 TUNSETTXFILTER = 0x400454d1 TUNSETVNETBE = 0x400454de TUNSETVNETHDRSZ = 0x400454d8 TUNSETVNETLE = 0x400454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb @@ -1877,6 +2107,86 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 @@ -1886,7 +2196,9 @@ const ( XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0x1800 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2066,171 +2378,179 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "memory page has hardware error", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "EDEADLK", "resource deadlock avoided"}, + {36, "ENAMETOOLONG", "file name too long"}, + {37, "ENOLCK", "no locks available"}, + {38, "ENOSYS", "function not implemented"}, + {39, "ENOTEMPTY", "directory not empty"}, + {40, "ELOOP", "too many levels of symbolic links"}, + {42, "ENOMSG", "no message of desired type"}, + {43, "EIDRM", "identifier removed"}, + {44, "ECHRNG", "channel number out of range"}, + {45, "EL2NSYNC", "level 2 not synchronized"}, + {46, "EL3HLT", "level 3 halted"}, + {47, "EL3RST", "level 3 reset"}, + {48, "ELNRNG", "link number out of range"}, + {49, "EUNATCH", "protocol driver not attached"}, + {50, "ENOCSI", "no CSI structure available"}, + {51, "EL2HLT", "level 2 halted"}, + {52, "EBADE", "invalid exchange"}, + {53, "EBADR", "invalid request descriptor"}, + {54, "EXFULL", "exchange full"}, + {55, "ENOANO", "no anode"}, + {56, "EBADRQC", "invalid request code"}, + {57, "EBADSLT", "invalid slot"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {72, "EMULTIHOP", "multihop attempted"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EBADMSG", "bad message"}, + {75, "EOVERFLOW", "value too large for defined data type"}, + {76, "ENOTUNIQ", "name not unique on network"}, + {77, "EBADFD", "file descriptor in bad state"}, + {78, "EREMCHG", "remote address changed"}, + {79, "ELIBACC", "can not access a needed shared library"}, + {80, "ELIBBAD", "accessing a corrupted shared library"}, + {81, "ELIBSCN", ".lib section in a.out corrupted"}, + {82, "ELIBMAX", "attempting to link in too many shared libraries"}, + {83, "ELIBEXEC", "cannot exec a shared library directly"}, + {84, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {85, "ERESTART", "interrupted system call should be restarted"}, + {86, "ESTRPIPE", "streams pipe error"}, + {87, "EUSERS", "too many users"}, + {88, "ENOTSOCK", "socket operation on non-socket"}, + {89, "EDESTADDRREQ", "destination address required"}, + {90, "EMSGSIZE", "message too long"}, + {91, "EPROTOTYPE", "protocol wrong type for socket"}, + {92, "ENOPROTOOPT", "protocol not available"}, + {93, "EPROTONOSUPPORT", "protocol not supported"}, + {94, "ESOCKTNOSUPPORT", "socket type not supported"}, + {95, "ENOTSUP", "operation not supported"}, + {96, "EPFNOSUPPORT", "protocol family not supported"}, + {97, "EAFNOSUPPORT", "address family not supported by protocol"}, + {98, "EADDRINUSE", "address already in use"}, + {99, "EADDRNOTAVAIL", "cannot assign requested address"}, + {100, "ENETDOWN", "network is down"}, + {101, "ENETUNREACH", "network is unreachable"}, + {102, "ENETRESET", "network dropped connection on reset"}, + {103, "ECONNABORTED", "software caused connection abort"}, + {104, "ECONNRESET", "connection reset by peer"}, + {105, "ENOBUFS", "no buffer space available"}, + {106, "EISCONN", "transport endpoint is already connected"}, + {107, "ENOTCONN", "transport endpoint is not connected"}, + {108, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {109, "ETOOMANYREFS", "too many references: cannot splice"}, + {110, "ETIMEDOUT", "connection timed out"}, + {111, "ECONNREFUSED", "connection refused"}, + {112, "EHOSTDOWN", "host is down"}, + {113, "EHOSTUNREACH", "no route to host"}, + {114, "EALREADY", "operation already in progress"}, + {115, "EINPROGRESS", "operation now in progress"}, + {116, "ESTALE", "stale file handle"}, + {117, "EUCLEAN", "structure needs cleaning"}, + {118, "ENOTNAM", "not a XENIX named type file"}, + {119, "ENAVAIL", "no XENIX semaphores available"}, + {120, "EISNAM", "is a named type file"}, + {121, "EREMOTEIO", "remote I/O error"}, + {122, "EDQUOT", "disk quota exceeded"}, + {123, "ENOMEDIUM", "no medium found"}, + {124, "EMEDIUMTYPE", "wrong medium type"}, + {125, "ECANCELED", "operation canceled"}, + {126, "ENOKEY", "required key not available"}, + {127, "EKEYEXPIRED", "key has expired"}, + {128, "EKEYREVOKED", "key has been revoked"}, + {129, "EKEYREJECTED", "key was rejected by service"}, + {130, "EOWNERDEAD", "owner died"}, + {131, "ENOTRECOVERABLE", "state not recoverable"}, + {132, "ERFKILL", "operation not possible due to RF-kill"}, + {133, "EHWPOISON", "memory page has hardware error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGBUS", "bus error"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGUSR1", "user defined signal 1"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGUSR2", "user defined signal 2"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGSTKFLT", "stack fault"}, + {17, "SIGCHLD", "child exited"}, + {18, "SIGCONT", "continued"}, + {19, "SIGSTOP", "stopped (signal)"}, + {20, "SIGTSTP", "stopped"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGURG", "urgent I/O condition"}, + {24, "SIGXCPU", "CPU time limit exceeded"}, + {25, "SIGXFSZ", "file size limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window changed"}, + {29, "SIGIO", "I/O possible"}, + {30, "SIGPWR", "power failure"}, + {31, "SIGSYS", "bad system call"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go index d131a4cc51..465ff2f0f3 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x1007 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x40041270 BLKBSZSET = 0x80041271 BLKFLSBUF = 0x20001261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -390,6 +414,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -398,6 +424,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -408,11 +435,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -440,9 +469,14 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -476,6 +510,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -488,6 +524,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -495,6 +534,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -506,6 +549,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -527,6 +572,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 @@ -561,6 +649,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -775,12 +865,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -845,6 +937,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -853,6 +946,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_ANON = 0x800 MAP_ANONYMOUS = 0x800 MAP_DENYWRITE = 0x2000 @@ -875,9 +969,15 @@ const ( MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -899,6 +999,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -936,7 +1037,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -971,6 +1074,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 @@ -998,10 +1132,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1009,7 +1146,9 @@ const ( ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x1000 @@ -1096,14 +1235,17 @@ const ( PERF_EVENT_IOC_ID = 0x40042407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc004240a PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80042406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1196,6 +1338,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1204,6 +1351,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -1252,6 +1400,7 @@ const ( PTRACE_POKETEXT_3264 = 0xc2 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETOPTIONS = 0x4200 @@ -1264,6 +1413,11 @@ const ( PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x6 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1284,6 +1438,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1294,7 +1449,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1448,6 +1603,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1532,6 +1689,23 @@ const ( SIOCSPGRP = 0x80047308 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x1 @@ -1568,6 +1742,7 @@ const ( SOL_SOCKET = 0xffff SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1009 @@ -1637,10 +1812,35 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1711,6 +1911,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1731,6 +1933,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x5410 @@ -1820,7 +2023,27 @@ const ( TIOCSTI = 0x5472 TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x8000 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x800854d5 TUNDETACHFILTER = 0x800854d6 @@ -1832,6 +2055,7 @@ const ( TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 + TUNSETFILTEREBPF = 0x400454e1 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da @@ -1842,13 +2066,17 @@ const ( TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 + TUNSETSTEERINGEBPF = 0x400454e0 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0xd VEOF = 0x10 VEOL = 0x11 @@ -1891,6 +2119,86 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 @@ -1900,7 +2208,9 @@ const ( XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0x1800 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2082,174 +2392,182 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "no message of desired type", - 36: "identifier removed", - 37: "channel number out of range", - 38: "level 2 not synchronized", - 39: "level 3 halted", - 40: "level 3 reset", - 41: "link number out of range", - 42: "protocol driver not attached", - 43: "no CSI structure available", - 44: "level 2 halted", - 45: "resource deadlock avoided", - 46: "no locks available", - 50: "invalid exchange", - 51: "invalid request descriptor", - 52: "exchange full", - 53: "no anode", - 54: "invalid request code", - 55: "invalid slot", - 56: "file locking deadlock error", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 73: "RFS specific error", - 74: "multihop attempted", - 77: "bad message", - 78: "file name too long", - 79: "value too large for defined data type", - 80: "name not unique on network", - 81: "file descriptor in bad state", - 82: "remote address changed", - 83: "can not access a needed shared library", - 84: "accessing a corrupted shared library", - 85: ".lib section in a.out corrupted", - 86: "attempting to link in too many shared libraries", - 87: "cannot exec a shared library directly", - 88: "invalid or incomplete multibyte or wide character", - 89: "function not implemented", - 90: "too many levels of symbolic links", - 91: "interrupted system call should be restarted", - 92: "streams pipe error", - 93: "directory not empty", - 94: "too many users", - 95: "socket operation on non-socket", - 96: "destination address required", - 97: "message too long", - 98: "protocol wrong type for socket", - 99: "protocol not available", - 120: "protocol not supported", - 121: "socket type not supported", - 122: "operation not supported", - 123: "protocol family not supported", - 124: "address family not supported by protocol", - 125: "address already in use", - 126: "cannot assign requested address", - 127: "network is down", - 128: "network is unreachable", - 129: "network dropped connection on reset", - 130: "software caused connection abort", - 131: "connection reset by peer", - 132: "no buffer space available", - 133: "transport endpoint is already connected", - 134: "transport endpoint is not connected", - 135: "structure needs cleaning", - 137: "not a XENIX named type file", - 138: "no XENIX semaphores available", - 139: "is a named type file", - 140: "remote I/O error", - 141: "unknown error 141", - 142: "unknown error 142", - 143: "cannot send after transport endpoint shutdown", - 144: "too many references: cannot splice", - 145: "connection timed out", - 146: "connection refused", - 147: "host is down", - 148: "no route to host", - 149: "operation already in progress", - 150: "operation now in progress", - 151: "stale file handle", - 158: "operation canceled", - 159: "no medium found", - 160: "wrong medium type", - 161: "required key not available", - 162: "key has expired", - 163: "key has been revoked", - 164: "key was rejected by service", - 165: "owner died", - 166: "state not recoverable", - 167: "operation not possible due to RF-kill", - 168: "memory page has hardware error", - 1133: "disk quota exceeded", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "ENOMSG", "no message of desired type"}, + {36, "EIDRM", "identifier removed"}, + {37, "ECHRNG", "channel number out of range"}, + {38, "EL2NSYNC", "level 2 not synchronized"}, + {39, "EL3HLT", "level 3 halted"}, + {40, "EL3RST", "level 3 reset"}, + {41, "ELNRNG", "link number out of range"}, + {42, "EUNATCH", "protocol driver not attached"}, + {43, "ENOCSI", "no CSI structure available"}, + {44, "EL2HLT", "level 2 halted"}, + {45, "EDEADLK", "resource deadlock avoided"}, + {46, "ENOLCK", "no locks available"}, + {50, "EBADE", "invalid exchange"}, + {51, "EBADR", "invalid request descriptor"}, + {52, "EXFULL", "exchange full"}, + {53, "ENOANO", "no anode"}, + {54, "EBADRQC", "invalid request code"}, + {55, "EBADSLT", "invalid slot"}, + {56, "EDEADLOCK", "file locking deadlock error"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EMULTIHOP", "multihop attempted"}, + {77, "EBADMSG", "bad message"}, + {78, "ENAMETOOLONG", "file name too long"}, + {79, "EOVERFLOW", "value too large for defined data type"}, + {80, "ENOTUNIQ", "name not unique on network"}, + {81, "EBADFD", "file descriptor in bad state"}, + {82, "EREMCHG", "remote address changed"}, + {83, "ELIBACC", "can not access a needed shared library"}, + {84, "ELIBBAD", "accessing a corrupted shared library"}, + {85, "ELIBSCN", ".lib section in a.out corrupted"}, + {86, "ELIBMAX", "attempting to link in too many shared libraries"}, + {87, "ELIBEXEC", "cannot exec a shared library directly"}, + {88, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {89, "ENOSYS", "function not implemented"}, + {90, "ELOOP", "too many levels of symbolic links"}, + {91, "ERESTART", "interrupted system call should be restarted"}, + {92, "ESTRPIPE", "streams pipe error"}, + {93, "ENOTEMPTY", "directory not empty"}, + {94, "EUSERS", "too many users"}, + {95, "ENOTSOCK", "socket operation on non-socket"}, + {96, "EDESTADDRREQ", "destination address required"}, + {97, "EMSGSIZE", "message too long"}, + {98, "EPROTOTYPE", "protocol wrong type for socket"}, + {99, "ENOPROTOOPT", "protocol not available"}, + {120, "EPROTONOSUPPORT", "protocol not supported"}, + {121, "ESOCKTNOSUPPORT", "socket type not supported"}, + {122, "ENOTSUP", "operation not supported"}, + {123, "EPFNOSUPPORT", "protocol family not supported"}, + {124, "EAFNOSUPPORT", "address family not supported by protocol"}, + {125, "EADDRINUSE", "address already in use"}, + {126, "EADDRNOTAVAIL", "cannot assign requested address"}, + {127, "ENETDOWN", "network is down"}, + {128, "ENETUNREACH", "network is unreachable"}, + {129, "ENETRESET", "network dropped connection on reset"}, + {130, "ECONNABORTED", "software caused connection abort"}, + {131, "ECONNRESET", "connection reset by peer"}, + {132, "ENOBUFS", "no buffer space available"}, + {133, "EISCONN", "transport endpoint is already connected"}, + {134, "ENOTCONN", "transport endpoint is not connected"}, + {135, "EUCLEAN", "structure needs cleaning"}, + {137, "ENOTNAM", "not a XENIX named type file"}, + {138, "ENAVAIL", "no XENIX semaphores available"}, + {139, "EISNAM", "is a named type file"}, + {140, "EREMOTEIO", "remote I/O error"}, + {141, "EINIT", "unknown error 141"}, + {142, "EREMDEV", "unknown error 142"}, + {143, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {144, "ETOOMANYREFS", "too many references: cannot splice"}, + {145, "ETIMEDOUT", "connection timed out"}, + {146, "ECONNREFUSED", "connection refused"}, + {147, "EHOSTDOWN", "host is down"}, + {148, "EHOSTUNREACH", "no route to host"}, + {149, "EALREADY", "operation already in progress"}, + {150, "EINPROGRESS", "operation now in progress"}, + {151, "ESTALE", "stale file handle"}, + {158, "ECANCELED", "operation canceled"}, + {159, "ENOMEDIUM", "no medium found"}, + {160, "EMEDIUMTYPE", "wrong medium type"}, + {161, "ENOKEY", "required key not available"}, + {162, "EKEYEXPIRED", "key has expired"}, + {163, "EKEYREVOKED", "key has been revoked"}, + {164, "EKEYREJECTED", "key was rejected by service"}, + {165, "EOWNERDEAD", "owner died"}, + {166, "ENOTRECOVERABLE", "state not recoverable"}, + {167, "ERFKILL", "operation not possible due to RF-kill"}, + {168, "EHWPOISON", "memory page has hardware error"}, + {1133, "EDQUOT", "disk quota exceeded"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "user defined signal 1", - 17: "user defined signal 2", - 18: "child exited", - 19: "power failure", - 20: "window changed", - 21: "urgent I/O condition", - 22: "I/O possible", - 23: "stopped (signal)", - 24: "stopped", - 25: "continued", - 26: "stopped (tty input)", - 27: "stopped (tty output)", - 28: "virtual timer expired", - 29: "profiling timer expired", - 30: "CPU time limit exceeded", - 31: "file size limit exceeded", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGUSR1", "user defined signal 1"}, + {17, "SIGUSR2", "user defined signal 2"}, + {18, "SIGCHLD", "child exited"}, + {19, "SIGPWR", "power failure"}, + {20, "SIGWINCH", "window changed"}, + {21, "SIGURG", "urgent I/O condition"}, + {22, "SIGIO", "I/O possible"}, + {23, "SIGSTOP", "stopped (signal)"}, + {24, "SIGTSTP", "stopped"}, + {25, "SIGCONT", "continued"}, + {26, "SIGTTIN", "stopped (tty input)"}, + {27, "SIGTTOU", "stopped (tty output)"}, + {28, "SIGVTALRM", "virtual timer expired"}, + {29, "SIGPROF", "profiling timer expired"}, + {30, "SIGXCPU", "CPU time limit exceeded"}, + {31, "SIGXFSZ", "file size limit exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go index 62dd20352b..37e851aabe 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x1007 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 BLKFLSBUF = 0x20001261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -390,6 +414,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -398,6 +424,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -408,11 +435,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -440,9 +469,14 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -476,6 +510,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -488,6 +524,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -495,6 +534,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -506,6 +549,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -527,6 +572,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 @@ -561,6 +649,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -775,12 +865,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -845,6 +937,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -853,6 +946,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_ANON = 0x800 MAP_ANONYMOUS = 0x800 MAP_DENYWRITE = 0x2000 @@ -875,9 +969,15 @@ const ( MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -899,6 +999,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -936,7 +1037,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -971,6 +1074,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 @@ -998,10 +1132,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1009,7 +1146,9 @@ const ( ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x1000 @@ -1096,14 +1235,17 @@ const ( PERF_EVENT_IOC_ID = 0x40082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc008240a PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80082406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1196,6 +1338,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1204,6 +1351,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -1252,6 +1400,7 @@ const ( PTRACE_POKETEXT_3264 = 0xc2 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETOPTIONS = 0x4200 @@ -1264,6 +1413,11 @@ const ( PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x6 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1284,6 +1438,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1294,7 +1449,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1448,6 +1603,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1532,6 +1689,23 @@ const ( SIOCSPGRP = 0x80047308 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x1 @@ -1568,6 +1742,7 @@ const ( SOL_SOCKET = 0xffff SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1009 @@ -1637,10 +1812,35 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1711,6 +1911,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1731,6 +1933,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x5410 @@ -1820,7 +2023,27 @@ const ( TIOCSTI = 0x5472 TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x8000 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 @@ -1832,6 +2055,7 @@ const ( TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 + TUNSETFILTEREBPF = 0x400454e1 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da @@ -1842,13 +2066,17 @@ const ( TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 + TUNSETSTEERINGEBPF = 0x400454e0 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0xd VEOF = 0x10 VEOL = 0x11 @@ -1891,6 +2119,86 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 @@ -1900,7 +2208,9 @@ const ( XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0x1800 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2082,174 +2392,182 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "no message of desired type", - 36: "identifier removed", - 37: "channel number out of range", - 38: "level 2 not synchronized", - 39: "level 3 halted", - 40: "level 3 reset", - 41: "link number out of range", - 42: "protocol driver not attached", - 43: "no CSI structure available", - 44: "level 2 halted", - 45: "resource deadlock avoided", - 46: "no locks available", - 50: "invalid exchange", - 51: "invalid request descriptor", - 52: "exchange full", - 53: "no anode", - 54: "invalid request code", - 55: "invalid slot", - 56: "file locking deadlock error", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 73: "RFS specific error", - 74: "multihop attempted", - 77: "bad message", - 78: "file name too long", - 79: "value too large for defined data type", - 80: "name not unique on network", - 81: "file descriptor in bad state", - 82: "remote address changed", - 83: "can not access a needed shared library", - 84: "accessing a corrupted shared library", - 85: ".lib section in a.out corrupted", - 86: "attempting to link in too many shared libraries", - 87: "cannot exec a shared library directly", - 88: "invalid or incomplete multibyte or wide character", - 89: "function not implemented", - 90: "too many levels of symbolic links", - 91: "interrupted system call should be restarted", - 92: "streams pipe error", - 93: "directory not empty", - 94: "too many users", - 95: "socket operation on non-socket", - 96: "destination address required", - 97: "message too long", - 98: "protocol wrong type for socket", - 99: "protocol not available", - 120: "protocol not supported", - 121: "socket type not supported", - 122: "operation not supported", - 123: "protocol family not supported", - 124: "address family not supported by protocol", - 125: "address already in use", - 126: "cannot assign requested address", - 127: "network is down", - 128: "network is unreachable", - 129: "network dropped connection on reset", - 130: "software caused connection abort", - 131: "connection reset by peer", - 132: "no buffer space available", - 133: "transport endpoint is already connected", - 134: "transport endpoint is not connected", - 135: "structure needs cleaning", - 137: "not a XENIX named type file", - 138: "no XENIX semaphores available", - 139: "is a named type file", - 140: "remote I/O error", - 141: "unknown error 141", - 142: "unknown error 142", - 143: "cannot send after transport endpoint shutdown", - 144: "too many references: cannot splice", - 145: "connection timed out", - 146: "connection refused", - 147: "host is down", - 148: "no route to host", - 149: "operation already in progress", - 150: "operation now in progress", - 151: "stale file handle", - 158: "operation canceled", - 159: "no medium found", - 160: "wrong medium type", - 161: "required key not available", - 162: "key has expired", - 163: "key has been revoked", - 164: "key was rejected by service", - 165: "owner died", - 166: "state not recoverable", - 167: "operation not possible due to RF-kill", - 168: "memory page has hardware error", - 1133: "disk quota exceeded", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "ENOMSG", "no message of desired type"}, + {36, "EIDRM", "identifier removed"}, + {37, "ECHRNG", "channel number out of range"}, + {38, "EL2NSYNC", "level 2 not synchronized"}, + {39, "EL3HLT", "level 3 halted"}, + {40, "EL3RST", "level 3 reset"}, + {41, "ELNRNG", "link number out of range"}, + {42, "EUNATCH", "protocol driver not attached"}, + {43, "ENOCSI", "no CSI structure available"}, + {44, "EL2HLT", "level 2 halted"}, + {45, "EDEADLK", "resource deadlock avoided"}, + {46, "ENOLCK", "no locks available"}, + {50, "EBADE", "invalid exchange"}, + {51, "EBADR", "invalid request descriptor"}, + {52, "EXFULL", "exchange full"}, + {53, "ENOANO", "no anode"}, + {54, "EBADRQC", "invalid request code"}, + {55, "EBADSLT", "invalid slot"}, + {56, "EDEADLOCK", "file locking deadlock error"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EMULTIHOP", "multihop attempted"}, + {77, "EBADMSG", "bad message"}, + {78, "ENAMETOOLONG", "file name too long"}, + {79, "EOVERFLOW", "value too large for defined data type"}, + {80, "ENOTUNIQ", "name not unique on network"}, + {81, "EBADFD", "file descriptor in bad state"}, + {82, "EREMCHG", "remote address changed"}, + {83, "ELIBACC", "can not access a needed shared library"}, + {84, "ELIBBAD", "accessing a corrupted shared library"}, + {85, "ELIBSCN", ".lib section in a.out corrupted"}, + {86, "ELIBMAX", "attempting to link in too many shared libraries"}, + {87, "ELIBEXEC", "cannot exec a shared library directly"}, + {88, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {89, "ENOSYS", "function not implemented"}, + {90, "ELOOP", "too many levels of symbolic links"}, + {91, "ERESTART", "interrupted system call should be restarted"}, + {92, "ESTRPIPE", "streams pipe error"}, + {93, "ENOTEMPTY", "directory not empty"}, + {94, "EUSERS", "too many users"}, + {95, "ENOTSOCK", "socket operation on non-socket"}, + {96, "EDESTADDRREQ", "destination address required"}, + {97, "EMSGSIZE", "message too long"}, + {98, "EPROTOTYPE", "protocol wrong type for socket"}, + {99, "ENOPROTOOPT", "protocol not available"}, + {120, "EPROTONOSUPPORT", "protocol not supported"}, + {121, "ESOCKTNOSUPPORT", "socket type not supported"}, + {122, "ENOTSUP", "operation not supported"}, + {123, "EPFNOSUPPORT", "protocol family not supported"}, + {124, "EAFNOSUPPORT", "address family not supported by protocol"}, + {125, "EADDRINUSE", "address already in use"}, + {126, "EADDRNOTAVAIL", "cannot assign requested address"}, + {127, "ENETDOWN", "network is down"}, + {128, "ENETUNREACH", "network is unreachable"}, + {129, "ENETRESET", "network dropped connection on reset"}, + {130, "ECONNABORTED", "software caused connection abort"}, + {131, "ECONNRESET", "connection reset by peer"}, + {132, "ENOBUFS", "no buffer space available"}, + {133, "EISCONN", "transport endpoint is already connected"}, + {134, "ENOTCONN", "transport endpoint is not connected"}, + {135, "EUCLEAN", "structure needs cleaning"}, + {137, "ENOTNAM", "not a XENIX named type file"}, + {138, "ENAVAIL", "no XENIX semaphores available"}, + {139, "EISNAM", "is a named type file"}, + {140, "EREMOTEIO", "remote I/O error"}, + {141, "EINIT", "unknown error 141"}, + {142, "EREMDEV", "unknown error 142"}, + {143, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {144, "ETOOMANYREFS", "too many references: cannot splice"}, + {145, "ETIMEDOUT", "connection timed out"}, + {146, "ECONNREFUSED", "connection refused"}, + {147, "EHOSTDOWN", "host is down"}, + {148, "EHOSTUNREACH", "no route to host"}, + {149, "EALREADY", "operation already in progress"}, + {150, "EINPROGRESS", "operation now in progress"}, + {151, "ESTALE", "stale file handle"}, + {158, "ECANCELED", "operation canceled"}, + {159, "ENOMEDIUM", "no medium found"}, + {160, "EMEDIUMTYPE", "wrong medium type"}, + {161, "ENOKEY", "required key not available"}, + {162, "EKEYEXPIRED", "key has expired"}, + {163, "EKEYREVOKED", "key has been revoked"}, + {164, "EKEYREJECTED", "key was rejected by service"}, + {165, "EOWNERDEAD", "owner died"}, + {166, "ENOTRECOVERABLE", "state not recoverable"}, + {167, "ERFKILL", "operation not possible due to RF-kill"}, + {168, "EHWPOISON", "memory page has hardware error"}, + {1133, "EDQUOT", "disk quota exceeded"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "user defined signal 1", - 17: "user defined signal 2", - 18: "child exited", - 19: "power failure", - 20: "window changed", - 21: "urgent I/O condition", - 22: "I/O possible", - 23: "stopped (signal)", - 24: "stopped", - 25: "continued", - 26: "stopped (tty input)", - 27: "stopped (tty output)", - 28: "virtual timer expired", - 29: "profiling timer expired", - 30: "CPU time limit exceeded", - 31: "file size limit exceeded", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGUSR1", "user defined signal 1"}, + {17, "SIGUSR2", "user defined signal 2"}, + {18, "SIGCHLD", "child exited"}, + {19, "SIGPWR", "power failure"}, + {20, "SIGWINCH", "window changed"}, + {21, "SIGURG", "urgent I/O condition"}, + {22, "SIGIO", "I/O possible"}, + {23, "SIGSTOP", "stopped (signal)"}, + {24, "SIGTSTP", "stopped"}, + {25, "SIGCONT", "continued"}, + {26, "SIGTTIN", "stopped (tty input)"}, + {27, "SIGTTOU", "stopped (tty output)"}, + {28, "SIGVTALRM", "virtual timer expired"}, + {29, "SIGPROF", "profiling timer expired"}, + {30, "SIGXCPU", "CPU time limit exceeded"}, + {31, "SIGXFSZ", "file size limit exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go index dc8e56e30c..1131d3ca16 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mips64le.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x1007 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 BLKFLSBUF = 0x20001261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -390,6 +414,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -398,6 +424,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -408,11 +435,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -440,9 +469,14 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -476,6 +510,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -488,6 +524,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -495,6 +534,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -506,6 +549,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -527,6 +572,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 @@ -561,6 +649,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -775,12 +865,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -845,6 +937,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -853,6 +946,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_ANON = 0x800 MAP_ANONYMOUS = 0x800 MAP_DENYWRITE = 0x2000 @@ -875,9 +969,15 @@ const ( MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -899,6 +999,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -936,7 +1037,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -971,6 +1074,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 @@ -998,10 +1132,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1009,7 +1146,9 @@ const ( ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x1000 @@ -1096,14 +1235,17 @@ const ( PERF_EVENT_IOC_ID = 0x40082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc008240a PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80082406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1196,6 +1338,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1204,6 +1351,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -1252,6 +1400,7 @@ const ( PTRACE_POKETEXT_3264 = 0xc2 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETOPTIONS = 0x4200 @@ -1264,6 +1413,11 @@ const ( PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x6 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1284,6 +1438,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1294,7 +1449,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1448,6 +1603,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1532,6 +1689,23 @@ const ( SIOCSPGRP = 0x80047308 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x1 @@ -1568,6 +1742,7 @@ const ( SOL_SOCKET = 0xffff SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1009 @@ -1637,10 +1812,35 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1711,6 +1911,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1731,6 +1933,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x5410 @@ -1820,7 +2023,27 @@ const ( TIOCSTI = 0x5472 TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x8000 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 @@ -1832,6 +2055,7 @@ const ( TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 + TUNSETFILTEREBPF = 0x400454e1 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da @@ -1842,13 +2066,17 @@ const ( TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 + TUNSETSTEERINGEBPF = 0x400454e0 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0xd VEOF = 0x10 VEOL = 0x11 @@ -1891,6 +2119,86 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 @@ -1900,7 +2208,9 @@ const ( XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0x1800 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2082,174 +2392,182 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "no message of desired type", - 36: "identifier removed", - 37: "channel number out of range", - 38: "level 2 not synchronized", - 39: "level 3 halted", - 40: "level 3 reset", - 41: "link number out of range", - 42: "protocol driver not attached", - 43: "no CSI structure available", - 44: "level 2 halted", - 45: "resource deadlock avoided", - 46: "no locks available", - 50: "invalid exchange", - 51: "invalid request descriptor", - 52: "exchange full", - 53: "no anode", - 54: "invalid request code", - 55: "invalid slot", - 56: "file locking deadlock error", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 73: "RFS specific error", - 74: "multihop attempted", - 77: "bad message", - 78: "file name too long", - 79: "value too large for defined data type", - 80: "name not unique on network", - 81: "file descriptor in bad state", - 82: "remote address changed", - 83: "can not access a needed shared library", - 84: "accessing a corrupted shared library", - 85: ".lib section in a.out corrupted", - 86: "attempting to link in too many shared libraries", - 87: "cannot exec a shared library directly", - 88: "invalid or incomplete multibyte or wide character", - 89: "function not implemented", - 90: "too many levels of symbolic links", - 91: "interrupted system call should be restarted", - 92: "streams pipe error", - 93: "directory not empty", - 94: "too many users", - 95: "socket operation on non-socket", - 96: "destination address required", - 97: "message too long", - 98: "protocol wrong type for socket", - 99: "protocol not available", - 120: "protocol not supported", - 121: "socket type not supported", - 122: "operation not supported", - 123: "protocol family not supported", - 124: "address family not supported by protocol", - 125: "address already in use", - 126: "cannot assign requested address", - 127: "network is down", - 128: "network is unreachable", - 129: "network dropped connection on reset", - 130: "software caused connection abort", - 131: "connection reset by peer", - 132: "no buffer space available", - 133: "transport endpoint is already connected", - 134: "transport endpoint is not connected", - 135: "structure needs cleaning", - 137: "not a XENIX named type file", - 138: "no XENIX semaphores available", - 139: "is a named type file", - 140: "remote I/O error", - 141: "unknown error 141", - 142: "unknown error 142", - 143: "cannot send after transport endpoint shutdown", - 144: "too many references: cannot splice", - 145: "connection timed out", - 146: "connection refused", - 147: "host is down", - 148: "no route to host", - 149: "operation already in progress", - 150: "operation now in progress", - 151: "stale file handle", - 158: "operation canceled", - 159: "no medium found", - 160: "wrong medium type", - 161: "required key not available", - 162: "key has expired", - 163: "key has been revoked", - 164: "key was rejected by service", - 165: "owner died", - 166: "state not recoverable", - 167: "operation not possible due to RF-kill", - 168: "memory page has hardware error", - 1133: "disk quota exceeded", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "ENOMSG", "no message of desired type"}, + {36, "EIDRM", "identifier removed"}, + {37, "ECHRNG", "channel number out of range"}, + {38, "EL2NSYNC", "level 2 not synchronized"}, + {39, "EL3HLT", "level 3 halted"}, + {40, "EL3RST", "level 3 reset"}, + {41, "ELNRNG", "link number out of range"}, + {42, "EUNATCH", "protocol driver not attached"}, + {43, "ENOCSI", "no CSI structure available"}, + {44, "EL2HLT", "level 2 halted"}, + {45, "EDEADLK", "resource deadlock avoided"}, + {46, "ENOLCK", "no locks available"}, + {50, "EBADE", "invalid exchange"}, + {51, "EBADR", "invalid request descriptor"}, + {52, "EXFULL", "exchange full"}, + {53, "ENOANO", "no anode"}, + {54, "EBADRQC", "invalid request code"}, + {55, "EBADSLT", "invalid slot"}, + {56, "EDEADLOCK", "file locking deadlock error"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EMULTIHOP", "multihop attempted"}, + {77, "EBADMSG", "bad message"}, + {78, "ENAMETOOLONG", "file name too long"}, + {79, "EOVERFLOW", "value too large for defined data type"}, + {80, "ENOTUNIQ", "name not unique on network"}, + {81, "EBADFD", "file descriptor in bad state"}, + {82, "EREMCHG", "remote address changed"}, + {83, "ELIBACC", "can not access a needed shared library"}, + {84, "ELIBBAD", "accessing a corrupted shared library"}, + {85, "ELIBSCN", ".lib section in a.out corrupted"}, + {86, "ELIBMAX", "attempting to link in too many shared libraries"}, + {87, "ELIBEXEC", "cannot exec a shared library directly"}, + {88, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {89, "ENOSYS", "function not implemented"}, + {90, "ELOOP", "too many levels of symbolic links"}, + {91, "ERESTART", "interrupted system call should be restarted"}, + {92, "ESTRPIPE", "streams pipe error"}, + {93, "ENOTEMPTY", "directory not empty"}, + {94, "EUSERS", "too many users"}, + {95, "ENOTSOCK", "socket operation on non-socket"}, + {96, "EDESTADDRREQ", "destination address required"}, + {97, "EMSGSIZE", "message too long"}, + {98, "EPROTOTYPE", "protocol wrong type for socket"}, + {99, "ENOPROTOOPT", "protocol not available"}, + {120, "EPROTONOSUPPORT", "protocol not supported"}, + {121, "ESOCKTNOSUPPORT", "socket type not supported"}, + {122, "ENOTSUP", "operation not supported"}, + {123, "EPFNOSUPPORT", "protocol family not supported"}, + {124, "EAFNOSUPPORT", "address family not supported by protocol"}, + {125, "EADDRINUSE", "address already in use"}, + {126, "EADDRNOTAVAIL", "cannot assign requested address"}, + {127, "ENETDOWN", "network is down"}, + {128, "ENETUNREACH", "network is unreachable"}, + {129, "ENETRESET", "network dropped connection on reset"}, + {130, "ECONNABORTED", "software caused connection abort"}, + {131, "ECONNRESET", "connection reset by peer"}, + {132, "ENOBUFS", "no buffer space available"}, + {133, "EISCONN", "transport endpoint is already connected"}, + {134, "ENOTCONN", "transport endpoint is not connected"}, + {135, "EUCLEAN", "structure needs cleaning"}, + {137, "ENOTNAM", "not a XENIX named type file"}, + {138, "ENAVAIL", "no XENIX semaphores available"}, + {139, "EISNAM", "is a named type file"}, + {140, "EREMOTEIO", "remote I/O error"}, + {141, "EINIT", "unknown error 141"}, + {142, "EREMDEV", "unknown error 142"}, + {143, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {144, "ETOOMANYREFS", "too many references: cannot splice"}, + {145, "ETIMEDOUT", "connection timed out"}, + {146, "ECONNREFUSED", "connection refused"}, + {147, "EHOSTDOWN", "host is down"}, + {148, "EHOSTUNREACH", "no route to host"}, + {149, "EALREADY", "operation already in progress"}, + {150, "EINPROGRESS", "operation now in progress"}, + {151, "ESTALE", "stale file handle"}, + {158, "ECANCELED", "operation canceled"}, + {159, "ENOMEDIUM", "no medium found"}, + {160, "EMEDIUMTYPE", "wrong medium type"}, + {161, "ENOKEY", "required key not available"}, + {162, "EKEYEXPIRED", "key has expired"}, + {163, "EKEYREVOKED", "key has been revoked"}, + {164, "EKEYREJECTED", "key was rejected by service"}, + {165, "EOWNERDEAD", "owner died"}, + {166, "ENOTRECOVERABLE", "state not recoverable"}, + {167, "ERFKILL", "operation not possible due to RF-kill"}, + {168, "EHWPOISON", "memory page has hardware error"}, + {1133, "EDQUOT", "disk quota exceeded"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "user defined signal 1", - 17: "user defined signal 2", - 18: "child exited", - 19: "power failure", - 20: "window changed", - 21: "urgent I/O condition", - 22: "I/O possible", - 23: "stopped (signal)", - 24: "stopped", - 25: "continued", - 26: "stopped (tty input)", - 27: "stopped (tty output)", - 28: "virtual timer expired", - 29: "profiling timer expired", - 30: "CPU time limit exceeded", - 31: "file size limit exceeded", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGUSR1", "user defined signal 1"}, + {17, "SIGUSR2", "user defined signal 2"}, + {18, "SIGCHLD", "child exited"}, + {19, "SIGPWR", "power failure"}, + {20, "SIGWINCH", "window changed"}, + {21, "SIGURG", "urgent I/O condition"}, + {22, "SIGIO", "I/O possible"}, + {23, "SIGSTOP", "stopped (signal)"}, + {24, "SIGTSTP", "stopped"}, + {25, "SIGCONT", "continued"}, + {26, "SIGTTIN", "stopped (tty input)"}, + {27, "SIGTTOU", "stopped (tty output)"}, + {28, "SIGVTALRM", "virtual timer expired"}, + {29, "SIGPROF", "profiling timer expired"}, + {30, "SIGXCPU", "CPU time limit exceeded"}, + {31, "SIGXFSZ", "file size limit exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go index 906766254c..d04a43b2bc 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_mipsle.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x1007 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x40041270 BLKBSZSET = 0x80041271 BLKFLSBUF = 0x20001261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x80 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -390,6 +414,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -398,6 +424,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -408,11 +435,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -440,9 +469,14 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -476,6 +510,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -488,6 +524,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -495,6 +534,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -506,6 +549,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -527,6 +572,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 @@ -561,6 +649,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -775,12 +865,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -845,6 +937,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -853,6 +946,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_ANON = 0x800 MAP_ANONYMOUS = 0x800 MAP_DENYWRITE = 0x2000 @@ -875,9 +969,15 @@ const ( MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -899,6 +999,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -936,7 +1037,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -971,6 +1074,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 @@ -998,10 +1132,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1009,7 +1146,9 @@ const ( ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x1000 @@ -1096,14 +1235,17 @@ const ( PERF_EVENT_IOC_ID = 0x40042407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc004240a PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80042406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1196,6 +1338,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1204,6 +1351,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -1252,6 +1400,7 @@ const ( PTRACE_POKETEXT_3264 = 0xc2 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETFPREGS = 0xf PTRACE_SETOPTIONS = 0x4200 @@ -1264,6 +1413,11 @@ const ( PTRACE_SINGLESTEP = 0x9 PTRACE_SYSCALL = 0x18 PTRACE_TRACEME = 0x0 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x6 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1284,6 +1438,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1294,7 +1449,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1448,6 +1603,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1532,6 +1689,23 @@ const ( SIOCSPGRP = 0x80047308 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x1 @@ -1568,6 +1742,7 @@ const ( SOL_SOCKET = 0xffff SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1009 @@ -1637,10 +1812,35 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1711,6 +1911,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1731,6 +1933,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x5410 @@ -1820,7 +2023,27 @@ const ( TIOCSTI = 0x5472 TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x8000 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x800854d5 TUNDETACHFILTER = 0x800854d6 @@ -1832,6 +2055,7 @@ const ( TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 + TUNSETFILTEREBPF = 0x400454e1 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da @@ -1842,13 +2066,17 @@ const ( TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 + TUNSETSTEERINGEBPF = 0x400454e0 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0xd VEOF = 0x10 VEOL = 0x11 @@ -1891,6 +2119,86 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 @@ -1900,7 +2208,9 @@ const ( XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0x1800 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2082,174 +2392,182 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "no message of desired type", - 36: "identifier removed", - 37: "channel number out of range", - 38: "level 2 not synchronized", - 39: "level 3 halted", - 40: "level 3 reset", - 41: "link number out of range", - 42: "protocol driver not attached", - 43: "no CSI structure available", - 44: "level 2 halted", - 45: "resource deadlock avoided", - 46: "no locks available", - 50: "invalid exchange", - 51: "invalid request descriptor", - 52: "exchange full", - 53: "no anode", - 54: "invalid request code", - 55: "invalid slot", - 56: "file locking deadlock error", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 73: "RFS specific error", - 74: "multihop attempted", - 77: "bad message", - 78: "file name too long", - 79: "value too large for defined data type", - 80: "name not unique on network", - 81: "file descriptor in bad state", - 82: "remote address changed", - 83: "can not access a needed shared library", - 84: "accessing a corrupted shared library", - 85: ".lib section in a.out corrupted", - 86: "attempting to link in too many shared libraries", - 87: "cannot exec a shared library directly", - 88: "invalid or incomplete multibyte or wide character", - 89: "function not implemented", - 90: "too many levels of symbolic links", - 91: "interrupted system call should be restarted", - 92: "streams pipe error", - 93: "directory not empty", - 94: "too many users", - 95: "socket operation on non-socket", - 96: "destination address required", - 97: "message too long", - 98: "protocol wrong type for socket", - 99: "protocol not available", - 120: "protocol not supported", - 121: "socket type not supported", - 122: "operation not supported", - 123: "protocol family not supported", - 124: "address family not supported by protocol", - 125: "address already in use", - 126: "cannot assign requested address", - 127: "network is down", - 128: "network is unreachable", - 129: "network dropped connection on reset", - 130: "software caused connection abort", - 131: "connection reset by peer", - 132: "no buffer space available", - 133: "transport endpoint is already connected", - 134: "transport endpoint is not connected", - 135: "structure needs cleaning", - 137: "not a XENIX named type file", - 138: "no XENIX semaphores available", - 139: "is a named type file", - 140: "remote I/O error", - 141: "unknown error 141", - 142: "unknown error 142", - 143: "cannot send after transport endpoint shutdown", - 144: "too many references: cannot splice", - 145: "connection timed out", - 146: "connection refused", - 147: "host is down", - 148: "no route to host", - 149: "operation already in progress", - 150: "operation now in progress", - 151: "stale file handle", - 158: "operation canceled", - 159: "no medium found", - 160: "wrong medium type", - 161: "required key not available", - 162: "key has expired", - 163: "key has been revoked", - 164: "key was rejected by service", - 165: "owner died", - 166: "state not recoverable", - 167: "operation not possible due to RF-kill", - 168: "memory page has hardware error", - 1133: "disk quota exceeded", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "ENOMSG", "no message of desired type"}, + {36, "EIDRM", "identifier removed"}, + {37, "ECHRNG", "channel number out of range"}, + {38, "EL2NSYNC", "level 2 not synchronized"}, + {39, "EL3HLT", "level 3 halted"}, + {40, "EL3RST", "level 3 reset"}, + {41, "ELNRNG", "link number out of range"}, + {42, "EUNATCH", "protocol driver not attached"}, + {43, "ENOCSI", "no CSI structure available"}, + {44, "EL2HLT", "level 2 halted"}, + {45, "EDEADLK", "resource deadlock avoided"}, + {46, "ENOLCK", "no locks available"}, + {50, "EBADE", "invalid exchange"}, + {51, "EBADR", "invalid request descriptor"}, + {52, "EXFULL", "exchange full"}, + {53, "ENOANO", "no anode"}, + {54, "EBADRQC", "invalid request code"}, + {55, "EBADSLT", "invalid slot"}, + {56, "EDEADLOCK", "file locking deadlock error"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EMULTIHOP", "multihop attempted"}, + {77, "EBADMSG", "bad message"}, + {78, "ENAMETOOLONG", "file name too long"}, + {79, "EOVERFLOW", "value too large for defined data type"}, + {80, "ENOTUNIQ", "name not unique on network"}, + {81, "EBADFD", "file descriptor in bad state"}, + {82, "EREMCHG", "remote address changed"}, + {83, "ELIBACC", "can not access a needed shared library"}, + {84, "ELIBBAD", "accessing a corrupted shared library"}, + {85, "ELIBSCN", ".lib section in a.out corrupted"}, + {86, "ELIBMAX", "attempting to link in too many shared libraries"}, + {87, "ELIBEXEC", "cannot exec a shared library directly"}, + {88, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {89, "ENOSYS", "function not implemented"}, + {90, "ELOOP", "too many levels of symbolic links"}, + {91, "ERESTART", "interrupted system call should be restarted"}, + {92, "ESTRPIPE", "streams pipe error"}, + {93, "ENOTEMPTY", "directory not empty"}, + {94, "EUSERS", "too many users"}, + {95, "ENOTSOCK", "socket operation on non-socket"}, + {96, "EDESTADDRREQ", "destination address required"}, + {97, "EMSGSIZE", "message too long"}, + {98, "EPROTOTYPE", "protocol wrong type for socket"}, + {99, "ENOPROTOOPT", "protocol not available"}, + {120, "EPROTONOSUPPORT", "protocol not supported"}, + {121, "ESOCKTNOSUPPORT", "socket type not supported"}, + {122, "ENOTSUP", "operation not supported"}, + {123, "EPFNOSUPPORT", "protocol family not supported"}, + {124, "EAFNOSUPPORT", "address family not supported by protocol"}, + {125, "EADDRINUSE", "address already in use"}, + {126, "EADDRNOTAVAIL", "cannot assign requested address"}, + {127, "ENETDOWN", "network is down"}, + {128, "ENETUNREACH", "network is unreachable"}, + {129, "ENETRESET", "network dropped connection on reset"}, + {130, "ECONNABORTED", "software caused connection abort"}, + {131, "ECONNRESET", "connection reset by peer"}, + {132, "ENOBUFS", "no buffer space available"}, + {133, "EISCONN", "transport endpoint is already connected"}, + {134, "ENOTCONN", "transport endpoint is not connected"}, + {135, "EUCLEAN", "structure needs cleaning"}, + {137, "ENOTNAM", "not a XENIX named type file"}, + {138, "ENAVAIL", "no XENIX semaphores available"}, + {139, "EISNAM", "is a named type file"}, + {140, "EREMOTEIO", "remote I/O error"}, + {141, "EINIT", "unknown error 141"}, + {142, "EREMDEV", "unknown error 142"}, + {143, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {144, "ETOOMANYREFS", "too many references: cannot splice"}, + {145, "ETIMEDOUT", "connection timed out"}, + {146, "ECONNREFUSED", "connection refused"}, + {147, "EHOSTDOWN", "host is down"}, + {148, "EHOSTUNREACH", "no route to host"}, + {149, "EALREADY", "operation already in progress"}, + {150, "EINPROGRESS", "operation now in progress"}, + {151, "ESTALE", "stale file handle"}, + {158, "ECANCELED", "operation canceled"}, + {159, "ENOMEDIUM", "no medium found"}, + {160, "EMEDIUMTYPE", "wrong medium type"}, + {161, "ENOKEY", "required key not available"}, + {162, "EKEYEXPIRED", "key has expired"}, + {163, "EKEYREVOKED", "key has been revoked"}, + {164, "EKEYREJECTED", "key was rejected by service"}, + {165, "EOWNERDEAD", "owner died"}, + {166, "ENOTRECOVERABLE", "state not recoverable"}, + {167, "ERFKILL", "operation not possible due to RF-kill"}, + {168, "EHWPOISON", "memory page has hardware error"}, + {1133, "EDQUOT", "disk quota exceeded"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "user defined signal 1", - 17: "user defined signal 2", - 18: "child exited", - 19: "power failure", - 20: "window changed", - 21: "urgent I/O condition", - 22: "I/O possible", - 23: "stopped (signal)", - 24: "stopped", - 25: "continued", - 26: "stopped (tty input)", - 27: "stopped (tty output)", - 28: "virtual timer expired", - 29: "profiling timer expired", - 30: "CPU time limit exceeded", - 31: "file size limit exceeded", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGUSR1", "user defined signal 1"}, + {17, "SIGUSR2", "user defined signal 2"}, + {18, "SIGCHLD", "child exited"}, + {19, "SIGPWR", "power failure"}, + {20, "SIGWINCH", "window changed"}, + {21, "SIGURG", "urgent I/O condition"}, + {22, "SIGIO", "I/O possible"}, + {23, "SIGSTOP", "stopped (signal)"}, + {24, "SIGTSTP", "stopped"}, + {25, "SIGCONT", "continued"}, + {26, "SIGTTIN", "stopped (tty input)"}, + {27, "SIGTTOU", "stopped (tty output)"}, + {28, "SIGVTALRM", "virtual timer expired"}, + {29, "SIGPROF", "profiling timer expired"}, + {30, "SIGXCPU", "CPU time limit exceeded"}, + {31, "SIGXFSZ", "file size limit exceeded"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go index f6ca82c715..710410efdd 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x17 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x16 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 BLKFLSBUF = 0x20001261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x8000 BSDLY = 0x8000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0xff CBAUDEX = 0x0 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0xff0000 CLOCAL = 0x8000 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x1000 CR2 = 0x2000 CR3 = 0x3000 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x3000 CREAD = 0x800 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -390,6 +414,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -398,6 +424,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -408,11 +435,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -440,9 +469,14 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000000 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -476,6 +510,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -488,6 +524,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -495,6 +534,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -506,6 +549,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -527,6 +572,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x4000 IBSHIFT = 0x10 ICANON = 0x100 @@ -561,6 +649,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -775,12 +865,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x80 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x1000 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -845,6 +937,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -853,6 +946,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 @@ -874,9 +968,15 @@ const ( MCL_CURRENT = 0x2000 MCL_FUTURE = 0x4000 MCL_ONFAULT = 0x8000 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -898,6 +998,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -935,7 +1036,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -970,6 +1073,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NL2 = 0x200 @@ -999,10 +1133,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80000000 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1010,7 +1147,9 @@ const ( ONLCR = 0x2 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 @@ -1097,14 +1236,17 @@ const ( PERF_EVENT_IOC_ID = 0x40082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc008240a PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80082406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1198,6 +1340,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1206,6 +1353,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -1251,6 +1399,7 @@ const ( PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETEVRREGS = 0x15 PTRACE_SETFPREGS = 0xf @@ -1320,6 +1469,11 @@ const ( PT_VSR0 = 0x96 PT_VSR31 = 0xd4 PT_XER = 0x25 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1340,6 +1494,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1350,7 +1505,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1504,6 +1659,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1588,6 +1745,23 @@ const ( SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 @@ -1624,6 +1798,7 @@ const ( SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e @@ -1692,10 +1867,35 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1765,6 +1965,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1785,6 +1987,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 @@ -1878,7 +2081,27 @@ const ( TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x400000 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 @@ -1890,6 +2113,7 @@ const ( TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 + TUNSETFILTEREBPF = 0x400454e1 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da @@ -1900,13 +2124,17 @@ const ( TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 + TUNSETSTEERINGEBPF = 0x400454e0 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0x10 VEOF = 0x4 VEOL = 0x6 @@ -1948,6 +2176,86 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 @@ -1957,7 +2265,9 @@ const ( XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4000 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0xc00 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2137,172 +2447,180 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 58: "file locking deadlock error", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "memory page has hardware error", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "EDEADLK", "resource deadlock avoided"}, + {36, "ENAMETOOLONG", "file name too long"}, + {37, "ENOLCK", "no locks available"}, + {38, "ENOSYS", "function not implemented"}, + {39, "ENOTEMPTY", "directory not empty"}, + {40, "ELOOP", "too many levels of symbolic links"}, + {42, "ENOMSG", "no message of desired type"}, + {43, "EIDRM", "identifier removed"}, + {44, "ECHRNG", "channel number out of range"}, + {45, "EL2NSYNC", "level 2 not synchronized"}, + {46, "EL3HLT", "level 3 halted"}, + {47, "EL3RST", "level 3 reset"}, + {48, "ELNRNG", "link number out of range"}, + {49, "EUNATCH", "protocol driver not attached"}, + {50, "ENOCSI", "no CSI structure available"}, + {51, "EL2HLT", "level 2 halted"}, + {52, "EBADE", "invalid exchange"}, + {53, "EBADR", "invalid request descriptor"}, + {54, "EXFULL", "exchange full"}, + {55, "ENOANO", "no anode"}, + {56, "EBADRQC", "invalid request code"}, + {57, "EBADSLT", "invalid slot"}, + {58, "EDEADLOCK", "file locking deadlock error"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {72, "EMULTIHOP", "multihop attempted"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EBADMSG", "bad message"}, + {75, "EOVERFLOW", "value too large for defined data type"}, + {76, "ENOTUNIQ", "name not unique on network"}, + {77, "EBADFD", "file descriptor in bad state"}, + {78, "EREMCHG", "remote address changed"}, + {79, "ELIBACC", "can not access a needed shared library"}, + {80, "ELIBBAD", "accessing a corrupted shared library"}, + {81, "ELIBSCN", ".lib section in a.out corrupted"}, + {82, "ELIBMAX", "attempting to link in too many shared libraries"}, + {83, "ELIBEXEC", "cannot exec a shared library directly"}, + {84, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {85, "ERESTART", "interrupted system call should be restarted"}, + {86, "ESTRPIPE", "streams pipe error"}, + {87, "EUSERS", "too many users"}, + {88, "ENOTSOCK", "socket operation on non-socket"}, + {89, "EDESTADDRREQ", "destination address required"}, + {90, "EMSGSIZE", "message too long"}, + {91, "EPROTOTYPE", "protocol wrong type for socket"}, + {92, "ENOPROTOOPT", "protocol not available"}, + {93, "EPROTONOSUPPORT", "protocol not supported"}, + {94, "ESOCKTNOSUPPORT", "socket type not supported"}, + {95, "ENOTSUP", "operation not supported"}, + {96, "EPFNOSUPPORT", "protocol family not supported"}, + {97, "EAFNOSUPPORT", "address family not supported by protocol"}, + {98, "EADDRINUSE", "address already in use"}, + {99, "EADDRNOTAVAIL", "cannot assign requested address"}, + {100, "ENETDOWN", "network is down"}, + {101, "ENETUNREACH", "network is unreachable"}, + {102, "ENETRESET", "network dropped connection on reset"}, + {103, "ECONNABORTED", "software caused connection abort"}, + {104, "ECONNRESET", "connection reset by peer"}, + {105, "ENOBUFS", "no buffer space available"}, + {106, "EISCONN", "transport endpoint is already connected"}, + {107, "ENOTCONN", "transport endpoint is not connected"}, + {108, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {109, "ETOOMANYREFS", "too many references: cannot splice"}, + {110, "ETIMEDOUT", "connection timed out"}, + {111, "ECONNREFUSED", "connection refused"}, + {112, "EHOSTDOWN", "host is down"}, + {113, "EHOSTUNREACH", "no route to host"}, + {114, "EALREADY", "operation already in progress"}, + {115, "EINPROGRESS", "operation now in progress"}, + {116, "ESTALE", "stale file handle"}, + {117, "EUCLEAN", "structure needs cleaning"}, + {118, "ENOTNAM", "not a XENIX named type file"}, + {119, "ENAVAIL", "no XENIX semaphores available"}, + {120, "EISNAM", "is a named type file"}, + {121, "EREMOTEIO", "remote I/O error"}, + {122, "EDQUOT", "disk quota exceeded"}, + {123, "ENOMEDIUM", "no medium found"}, + {124, "EMEDIUMTYPE", "wrong medium type"}, + {125, "ECANCELED", "operation canceled"}, + {126, "ENOKEY", "required key not available"}, + {127, "EKEYEXPIRED", "key has expired"}, + {128, "EKEYREVOKED", "key has been revoked"}, + {129, "EKEYREJECTED", "key was rejected by service"}, + {130, "EOWNERDEAD", "owner died"}, + {131, "ENOTRECOVERABLE", "state not recoverable"}, + {132, "ERFKILL", "operation not possible due to RF-kill"}, + {133, "EHWPOISON", "memory page has hardware error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGBUS", "bus error"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGUSR1", "user defined signal 1"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGUSR2", "user defined signal 2"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGSTKFLT", "stack fault"}, + {17, "SIGCHLD", "child exited"}, + {18, "SIGCONT", "continued"}, + {19, "SIGSTOP", "stopped (signal)"}, + {20, "SIGTSTP", "stopped"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGURG", "urgent I/O condition"}, + {24, "SIGXCPU", "CPU time limit exceeded"}, + {25, "SIGXFSZ", "file size limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window changed"}, + {29, "SIGIO", "I/O possible"}, + {30, "SIGPWR", "power failure"}, + {31, "SIGSYS", "bad system call"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go index ddd256254f..c1c1c01bcf 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x17 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x16 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x40081270 BLKBSZSET = 0x80081271 BLKFLSBUF = 0x20001261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x8000 BSDLY = 0x8000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0xff CBAUDEX = 0x0 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0xff0000 CLOCAL = 0x8000 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x1000 CR2 = 0x2000 CR3 = 0x3000 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x3000 CREAD = 0x800 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -390,6 +414,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -398,6 +424,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -408,11 +435,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -440,9 +469,14 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000000 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -476,6 +510,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -488,6 +524,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -495,6 +534,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -506,6 +549,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -527,6 +572,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x4000 IBSHIFT = 0x10 ICANON = 0x100 @@ -561,6 +649,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -775,12 +865,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x80 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x1000 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -845,6 +937,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -853,6 +946,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 @@ -874,9 +968,15 @@ const ( MCL_CURRENT = 0x2000 MCL_FUTURE = 0x4000 MCL_ONFAULT = 0x8000 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -898,6 +998,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -935,7 +1036,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -970,6 +1073,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NL2 = 0x200 @@ -999,10 +1133,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80000000 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1010,7 +1147,9 @@ const ( ONLCR = 0x2 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 @@ -1097,14 +1236,17 @@ const ( PERF_EVENT_IOC_ID = 0x40082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x80042409 PERF_EVENT_IOC_PERIOD = 0x80082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc008240a PERF_EVENT_IOC_REFRESH = 0x20002402 PERF_EVENT_IOC_RESET = 0x20002403 PERF_EVENT_IOC_SET_BPF = 0x80042408 PERF_EVENT_IOC_SET_FILTER = 0x80082406 PERF_EVENT_IOC_SET_OUTPUT = 0x20002405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1198,6 +1340,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1206,6 +1353,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -1251,6 +1399,7 @@ const ( PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETEVRREGS = 0x15 PTRACE_SETFPREGS = 0xf @@ -1320,6 +1469,11 @@ const ( PT_VSR0 = 0x96 PT_VSR31 = 0xd4 PT_XER = 0x25 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1340,6 +1494,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1350,7 +1505,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1504,6 +1659,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1588,6 +1745,23 @@ const ( SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 @@ -1624,6 +1798,7 @@ const ( SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e @@ -1692,10 +1867,35 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1765,6 +1965,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1785,6 +1987,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 @@ -1878,7 +2081,27 @@ const ( TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x400000 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 @@ -1890,6 +2113,7 @@ const ( TUNGETVNETHDRSZ = 0x400454d7 TUNGETVNETLE = 0x400454dd TUNSETDEBUG = 0x800454c9 + TUNSETFILTEREBPF = 0x400454e1 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da @@ -1900,13 +2124,17 @@ const ( TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 + TUNSETSTEERINGEBPF = 0x400454e0 TUNSETTXFILTER = 0x800454d1 TUNSETVNETBE = 0x800454de TUNSETVNETHDRSZ = 0x800454d8 TUNSETVNETLE = 0x800454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0x10 VEOF = 0x4 VEOL = 0x6 @@ -1948,6 +2176,86 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 @@ -1957,7 +2265,9 @@ const ( XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4000 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0xc00 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2137,172 +2447,180 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 58: "file locking deadlock error", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "memory page has hardware error", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "EDEADLK", "resource deadlock avoided"}, + {36, "ENAMETOOLONG", "file name too long"}, + {37, "ENOLCK", "no locks available"}, + {38, "ENOSYS", "function not implemented"}, + {39, "ENOTEMPTY", "directory not empty"}, + {40, "ELOOP", "too many levels of symbolic links"}, + {42, "ENOMSG", "no message of desired type"}, + {43, "EIDRM", "identifier removed"}, + {44, "ECHRNG", "channel number out of range"}, + {45, "EL2NSYNC", "level 2 not synchronized"}, + {46, "EL3HLT", "level 3 halted"}, + {47, "EL3RST", "level 3 reset"}, + {48, "ELNRNG", "link number out of range"}, + {49, "EUNATCH", "protocol driver not attached"}, + {50, "ENOCSI", "no CSI structure available"}, + {51, "EL2HLT", "level 2 halted"}, + {52, "EBADE", "invalid exchange"}, + {53, "EBADR", "invalid request descriptor"}, + {54, "EXFULL", "exchange full"}, + {55, "ENOANO", "no anode"}, + {56, "EBADRQC", "invalid request code"}, + {57, "EBADSLT", "invalid slot"}, + {58, "EDEADLOCK", "file locking deadlock error"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {72, "EMULTIHOP", "multihop attempted"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EBADMSG", "bad message"}, + {75, "EOVERFLOW", "value too large for defined data type"}, + {76, "ENOTUNIQ", "name not unique on network"}, + {77, "EBADFD", "file descriptor in bad state"}, + {78, "EREMCHG", "remote address changed"}, + {79, "ELIBACC", "can not access a needed shared library"}, + {80, "ELIBBAD", "accessing a corrupted shared library"}, + {81, "ELIBSCN", ".lib section in a.out corrupted"}, + {82, "ELIBMAX", "attempting to link in too many shared libraries"}, + {83, "ELIBEXEC", "cannot exec a shared library directly"}, + {84, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {85, "ERESTART", "interrupted system call should be restarted"}, + {86, "ESTRPIPE", "streams pipe error"}, + {87, "EUSERS", "too many users"}, + {88, "ENOTSOCK", "socket operation on non-socket"}, + {89, "EDESTADDRREQ", "destination address required"}, + {90, "EMSGSIZE", "message too long"}, + {91, "EPROTOTYPE", "protocol wrong type for socket"}, + {92, "ENOPROTOOPT", "protocol not available"}, + {93, "EPROTONOSUPPORT", "protocol not supported"}, + {94, "ESOCKTNOSUPPORT", "socket type not supported"}, + {95, "ENOTSUP", "operation not supported"}, + {96, "EPFNOSUPPORT", "protocol family not supported"}, + {97, "EAFNOSUPPORT", "address family not supported by protocol"}, + {98, "EADDRINUSE", "address already in use"}, + {99, "EADDRNOTAVAIL", "cannot assign requested address"}, + {100, "ENETDOWN", "network is down"}, + {101, "ENETUNREACH", "network is unreachable"}, + {102, "ENETRESET", "network dropped connection on reset"}, + {103, "ECONNABORTED", "software caused connection abort"}, + {104, "ECONNRESET", "connection reset by peer"}, + {105, "ENOBUFS", "no buffer space available"}, + {106, "EISCONN", "transport endpoint is already connected"}, + {107, "ENOTCONN", "transport endpoint is not connected"}, + {108, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {109, "ETOOMANYREFS", "too many references: cannot splice"}, + {110, "ETIMEDOUT", "connection timed out"}, + {111, "ECONNREFUSED", "connection refused"}, + {112, "EHOSTDOWN", "host is down"}, + {113, "EHOSTUNREACH", "no route to host"}, + {114, "EALREADY", "operation already in progress"}, + {115, "EINPROGRESS", "operation now in progress"}, + {116, "ESTALE", "stale file handle"}, + {117, "EUCLEAN", "structure needs cleaning"}, + {118, "ENOTNAM", "not a XENIX named type file"}, + {119, "ENAVAIL", "no XENIX semaphores available"}, + {120, "EISNAM", "is a named type file"}, + {121, "EREMOTEIO", "remote I/O error"}, + {122, "EDQUOT", "disk quota exceeded"}, + {123, "ENOMEDIUM", "no medium found"}, + {124, "EMEDIUMTYPE", "wrong medium type"}, + {125, "ECANCELED", "operation canceled"}, + {126, "ENOKEY", "required key not available"}, + {127, "EKEYEXPIRED", "key has expired"}, + {128, "EKEYREVOKED", "key has been revoked"}, + {129, "EKEYREJECTED", "key was rejected by service"}, + {130, "EOWNERDEAD", "owner died"}, + {131, "ENOTRECOVERABLE", "state not recoverable"}, + {132, "ERFKILL", "operation not possible due to RF-kill"}, + {133, "EHWPOISON", "memory page has hardware error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGBUS", "bus error"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGUSR1", "user defined signal 1"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGUSR2", "user defined signal 2"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGSTKFLT", "stack fault"}, + {17, "SIGCHLD", "child exited"}, + {18, "SIGCONT", "continued"}, + {19, "SIGSTOP", "stopped (signal)"}, + {20, "SIGTSTP", "stopped"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGURG", "urgent I/O condition"}, + {24, "SIGXCPU", "CPU time limit exceeded"}, + {25, "SIGXFSZ", "file size limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window changed"}, + {29, "SIGIO", "I/O possible"}, + {30, "SIGPWR", "power failure"}, + {31, "SIGSYS", "bad system call"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go index fc304a68f6..c7583e15eb 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zerrors_linux_s390x.go @@ -11,6 +11,11 @@ package unix import "syscall" const ( + AAFS_MAGIC = 0x5a3c69f0 + ADFS_SUPER_MAGIC = 0xadf5 + AFFS_SUPER_MAGIC = 0xadff + AFS_FS_MAGIC = 0x6b414653 + AFS_SUPER_MAGIC = 0x5346414f AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 @@ -66,6 +71,7 @@ const ( ALG_SET_IV = 0x2 ALG_SET_KEY = 0x1 ALG_SET_OP = 0x3 + ANON_INODE_FS_MAGIC = 0x9041934 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 @@ -121,6 +127,7 @@ const ( ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 + ARPHRD_RAWIP = 0x207 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 @@ -132,6 +139,7 @@ const ( ARPHRD_VOID = 0xffff ARPHRD_VSOCKMON = 0x33a ARPHRD_X25 = 0x10f + AUTOFS_SUPER_MAGIC = 0x187 B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 @@ -163,6 +171,9 @@ const ( B75 = 0x2 B921600 = 0x1007 B9600 = 0xd + BALLOON_KVM_MAGIC = 0x13661366 + BDEVFS_MAGIC = 0x62646576 + BINFMTFS_MAGIC = 0x42494e4d BLKBSZGET = 0x80081270 BLKBSZSET = 0x40081271 BLKFLSBUF = 0x1261 @@ -187,6 +198,7 @@ const ( BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 + BPF_FS_MAGIC = 0xcafe4a11 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 @@ -228,6 +240,8 @@ const ( BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 + BTRFS_SUPER_MAGIC = 0x9123683e + BTRFS_TEST_MAGIC = 0x73727279 CAN_BCM = 0x2 CAN_EFF_FLAG = 0x80000000 CAN_EFF_ID_BITS = 0x1d @@ -251,6 +265,8 @@ const ( CBAUD = 0x100f CBAUDEX = 0x1000 CFLUSH = 0xf + CGROUP2_SUPER_MAGIC = 0x63677270 + CGROUP_SUPER_MAGIC = 0x27e0eb CIBAUD = 0x100f0000 CLOCAL = 0x800 CLOCK_BOOTTIME = 0x7 @@ -293,10 +309,12 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 + CODA_SUPER_MAGIC = 0x73757245 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 + CRAMFS_MAGIC = 0x28cd3d45 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 @@ -311,6 +329,9 @@ const ( CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a + DAXFS_MAGIC = 0x64646178 + DEBUGFS_MAGIC = 0x64626720 + DEVPTS_SUPER_MAGIC = 0x1cd1 DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -327,9 +348,12 @@ const ( ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 + ECRYPTFS_SUPER_MAGIC = 0xf15f EFD_CLOEXEC = 0x80000 EFD_NONBLOCK = 0x800 EFD_SEMAPHORE = 0x1 + EFIVARFS_MAGIC = 0xde5e81e4 + EFS_SUPER_MAGIC = 0x414a53 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 @@ -390,6 +414,8 @@ const ( ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada + ETH_P_ERSPAN = 0x88be + ETH_P_ERSPAN2 = 0x22eb ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 @@ -398,6 +424,7 @@ const ( ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 + ETH_P_IFE = 0xed3e ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 @@ -408,11 +435,13 @@ const ( ETH_P_LOOP = 0x60 ETH_P_LOOPBACK = 0x9000 ETH_P_MACSEC = 0x88e5 + ETH_P_MAP = 0xf9 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_MVRP = 0x88f5 ETH_P_NCSI = 0x88f8 + ETH_P_NSH = 0x894f ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 @@ -440,9 +469,14 @@ const ( ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 + EXABYTE_ENABLE_NEST = 0xf0 + EXT2_SUPER_MAGIC = 0xef53 + EXT3_SUPER_MAGIC = 0xef53 + EXT4_SUPER_MAGIC = 0xef53 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 + F2FS_SUPER_MAGIC = 0xf2f52010 FALLOC_FL_COLLAPSE_RANGE = 0x8 FALLOC_FL_INSERT_RANGE = 0x20 FALLOC_FL_KEEP_SIZE = 0x1 @@ -476,6 +510,8 @@ const ( FS_POLICY_FLAGS_PAD_8 = 0x1 FS_POLICY_FLAGS_PAD_MASK = 0x3 FS_POLICY_FLAGS_VALID = 0x3 + FUTEXFS_SUPER_MAGIC = 0xbad1dea + F_ADD_SEALS = 0x409 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x406 F_EXLCK = 0x4 @@ -488,6 +524,9 @@ const ( F_GETOWN_EX = 0x10 F_GETPIPE_SZ = 0x408 F_GETSIG = 0xb + F_GET_FILE_RW_HINT = 0x40d + F_GET_RW_HINT = 0x40b + F_GET_SEALS = 0x40a F_LOCK = 0x1 F_NOTIFY = 0x402 F_OFD_GETLK = 0x24 @@ -495,6 +534,10 @@ const ( F_OFD_SETLKW = 0x26 F_OK = 0x0 F_RDLCK = 0x0 + F_SEAL_GROW = 0x4 + F_SEAL_SEAL = 0x1 + F_SEAL_SHRINK = 0x2 + F_SEAL_WRITE = 0x8 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLEASE = 0x400 @@ -506,6 +549,8 @@ const ( F_SETOWN_EX = 0xf F_SETPIPE_SZ = 0x407 F_SETSIG = 0xa + F_SET_FILE_RW_HINT = 0x40e + F_SET_RW_HINT = 0x40c F_SHLCK = 0x8 F_TEST = 0x3 F_TLOCK = 0x2 @@ -527,6 +572,49 @@ const ( GENL_UNS_ADMIN_PERM = 0x10 GRND_NONBLOCK = 0x1 GRND_RANDOM = 0x2 + HDIO_DRIVE_CMD = 0x31f + HDIO_DRIVE_CMD_AEB = 0x31e + HDIO_DRIVE_CMD_HDR_SIZE = 0x4 + HDIO_DRIVE_HOB_HDR_SIZE = 0x8 + HDIO_DRIVE_RESET = 0x31c + HDIO_DRIVE_TASK = 0x31e + HDIO_DRIVE_TASKFILE = 0x31d + HDIO_DRIVE_TASK_HDR_SIZE = 0x8 + HDIO_GETGEO = 0x301 + HDIO_GET_32BIT = 0x309 + HDIO_GET_ACOUSTIC = 0x30f + HDIO_GET_ADDRESS = 0x310 + HDIO_GET_BUSSTATE = 0x31a + HDIO_GET_DMA = 0x30b + HDIO_GET_IDENTITY = 0x30d + HDIO_GET_KEEPSETTINGS = 0x308 + HDIO_GET_MULTCOUNT = 0x304 + HDIO_GET_NICE = 0x30c + HDIO_GET_NOWERR = 0x30a + HDIO_GET_QDMA = 0x305 + HDIO_GET_UNMASKINTR = 0x302 + HDIO_GET_WCACHE = 0x30e + HDIO_OBSOLETE_IDENTITY = 0x307 + HDIO_SCAN_HWIF = 0x328 + HDIO_SET_32BIT = 0x324 + HDIO_SET_ACOUSTIC = 0x32c + HDIO_SET_ADDRESS = 0x32f + HDIO_SET_BUSSTATE = 0x32d + HDIO_SET_DMA = 0x326 + HDIO_SET_KEEPSETTINGS = 0x323 + HDIO_SET_MULTCOUNT = 0x321 + HDIO_SET_NICE = 0x329 + HDIO_SET_NOWERR = 0x325 + HDIO_SET_PIO_MODE = 0x327 + HDIO_SET_QDMA = 0x32e + HDIO_SET_UNMASKINTR = 0x322 + HDIO_SET_WCACHE = 0x32b + HDIO_SET_XFER = 0x306 + HDIO_TRISTATE_HWIF = 0x31b + HDIO_UNREGISTER_HWIF = 0x32a + HOSTFS_SUPER_MAGIC = 0xc0ffee + HPFS_SUPER_MAGIC = 0xf995e849 + HUGETLBFS_MAGIC = 0x958458f6 HUPCL = 0x400 IBSHIFT = 0x10 ICANON = 0x2 @@ -561,6 +649,8 @@ const ( IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_MULTI_QUEUE = 0x100 + IFF_NAPI = 0x10 + IFF_NAPI_FRAGS = 0x20 IFF_NOARP = 0x80 IFF_NOFILTER = 0x1000 IFF_NOTRAILERS = 0x20 @@ -775,12 +865,14 @@ const ( IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x1 + ISOFS_SUPER_MAGIC = 0x9660 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 + JFFS2_SUPER_MAGIC = 0x72b6 KEYCTL_ASSUME_AUTHORITY = 0x10 KEYCTL_CHOWN = 0x4 KEYCTL_CLEAR = 0x7 @@ -845,6 +937,7 @@ const ( MADV_FREE = 0x8 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 + MADV_KEEPONFORK = 0x13 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 @@ -853,6 +946,7 @@ const ( MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 + MADV_WIPEONFORK = 0x12 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 @@ -874,9 +968,15 @@ const ( MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MCL_ONFAULT = 0x4 + MINIX2_SUPER_MAGIC = 0x2468 + MINIX2_SUPER_MAGIC2 = 0x2478 + MINIX3_SUPER_MAGIC = 0x4d5a + MINIX_SUPER_MAGIC = 0x137f + MINIX_SUPER_MAGIC2 = 0x138f MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 + MSDOS_SUPER_MAGIC = 0x4d44 MSG_BATCH = 0x40000 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 @@ -898,6 +998,7 @@ const ( MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 + MSG_ZEROCOPY = 0x4000000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 @@ -935,7 +1036,9 @@ const ( MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 MS_VERBOSE = 0x8000 + MTD_INODE_FS_MAGIC = 0x11307854 NAME_MAX = 0xff + NCP_SUPER_MAGIC = 0x564c NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 @@ -970,6 +1073,37 @@ const ( NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 + NFNETLINK_V0 = 0x0 + NFNLGRP_ACCT_QUOTA = 0x8 + NFNLGRP_CONNTRACK_DESTROY = 0x3 + NFNLGRP_CONNTRACK_EXP_DESTROY = 0x6 + NFNLGRP_CONNTRACK_EXP_NEW = 0x4 + NFNLGRP_CONNTRACK_EXP_UPDATE = 0x5 + NFNLGRP_CONNTRACK_NEW = 0x1 + NFNLGRP_CONNTRACK_UPDATE = 0x2 + NFNLGRP_MAX = 0x9 + NFNLGRP_NFTABLES = 0x7 + NFNLGRP_NFTRACE = 0x9 + NFNLGRP_NONE = 0x0 + NFNL_BATCH_MAX = 0x1 + NFNL_MSG_BATCH_BEGIN = 0x10 + NFNL_MSG_BATCH_END = 0x11 + NFNL_NFA_NEST = 0x8000 + NFNL_SUBSYS_ACCT = 0x7 + NFNL_SUBSYS_COUNT = 0xc + NFNL_SUBSYS_CTHELPER = 0x9 + NFNL_SUBSYS_CTNETLINK = 0x1 + NFNL_SUBSYS_CTNETLINK_EXP = 0x2 + NFNL_SUBSYS_CTNETLINK_TIMEOUT = 0x8 + NFNL_SUBSYS_IPSET = 0x6 + NFNL_SUBSYS_NFTABLES = 0xa + NFNL_SUBSYS_NFT_COMPAT = 0xb + NFNL_SUBSYS_NONE = 0x0 + NFNL_SUBSYS_OSF = 0x5 + NFNL_SUBSYS_QUEUE = 0x3 + NFNL_SUBSYS_ULOG = 0x4 + NFS_SUPER_MAGIC = 0x6969 + NILFS_SUPER_MAGIC = 0x3434 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 @@ -997,10 +1131,13 @@ const ( NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 + NLM_F_NONREC = 0x100 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 + NSFS_MAGIC = 0x6e736673 + OCFS2_SUPER_MAGIC = 0x7461636f OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 @@ -1008,7 +1145,9 @@ const ( ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 + OPENPROM_SUPER_MAGIC = 0x9fa1 OPOST = 0x1 + OVERLAYFS_SUPER_MAGIC = 0x794c7630 O_ACCMODE = 0x3 O_APPEND = 0x400 O_ASYNC = 0x2000 @@ -1095,14 +1234,17 @@ const ( PERF_EVENT_IOC_ID = 0x80082407 PERF_EVENT_IOC_PAUSE_OUTPUT = 0x40042409 PERF_EVENT_IOC_PERIOD = 0x40082404 + PERF_EVENT_IOC_QUERY_BPF = 0xc008240a PERF_EVENT_IOC_REFRESH = 0x2402 PERF_EVENT_IOC_RESET = 0x2403 PERF_EVENT_IOC_SET_BPF = 0x40042408 PERF_EVENT_IOC_SET_FILTER = 0x40082406 PERF_EVENT_IOC_SET_OUTPUT = 0x2405 + PIPEFS_MAGIC = 0x50495045 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 + PROC_SUPER_MAGIC = 0x9fa0 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 @@ -1195,6 +1337,11 @@ const ( PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 + PR_SVE_GET_VL = 0x33 + PR_SVE_SET_VL = 0x32 + PR_SVE_SET_VL_ONEXEC = 0x40000 + PR_SVE_VL_INHERIT = 0x20000 + PR_SVE_VL_LEN_MASK = 0xffff PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 @@ -1203,6 +1350,7 @@ const ( PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 + PSTOREFS_MAGIC = 0x6165676c PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 @@ -1255,6 +1403,7 @@ const ( PTRACE_POKE_SYSTEM_CALL = 0x5008 PTRACE_PROT = 0x15 PTRACE_SECCOMP_GET_FILTER = 0x420c + PTRACE_SECCOMP_GET_METADATA = 0x420d PTRACE_SEIZE = 0x4206 PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd @@ -1324,6 +1473,11 @@ const ( PT_ORIGGPR2 = 0xd0 PT_PSWADDR = 0x8 PT_PSWMASK = 0x0 + QNX4_SUPER_MAGIC = 0x2f + QNX6_SUPER_MAGIC = 0x68191122 + RAMFS_MAGIC = 0x858458f6 + RDTGROUP_SUPER_MAGIC = 0x7655821 + REISERFS_SUPER_MAGIC = 0x52654973 RLIMIT_AS = 0x9 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 @@ -1344,6 +1498,7 @@ const ( RTAX_ADVMSS = 0x8 RTAX_CC_ALGO = 0x10 RTAX_CWND = 0x7 + RTAX_FASTOPEN_NO_COOKIE = 0x11 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 @@ -1354,7 +1509,7 @@ const ( RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 - RTAX_MAX = 0x10 + RTAX_MAX = 0x11 RTAX_MTU = 0x2 RTAX_QUICKACK = 0xf RTAX_REORDERING = 0x9 @@ -1508,6 +1663,8 @@ const ( SECCOMP_MODE_DISABLED = 0x0 SECCOMP_MODE_FILTER = 0x2 SECCOMP_MODE_STRICT = 0x1 + SECURITYFS_MAGIC = 0x73636673 + SELINUX_MAGIC = 0xf97cff8c SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 @@ -1592,6 +1749,23 @@ const ( SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SIOCWANDEV = 0x894a + SMACK_MAGIC = 0x43415d53 + SMART_AUTOSAVE = 0xd2 + SMART_AUTO_OFFLINE = 0xdb + SMART_DISABLE = 0xd9 + SMART_ENABLE = 0xd8 + SMART_HCYL_PASS = 0xc2 + SMART_IMMEDIATE_OFFLINE = 0xd4 + SMART_LCYL_PASS = 0x4f + SMART_READ_LOG_SECTOR = 0xd5 + SMART_READ_THRESHOLDS = 0xd1 + SMART_READ_VALUES = 0xd0 + SMART_SAVE = 0xd3 + SMART_STATUS = 0xda + SMART_WRITE_LOG_SECTOR = 0xd6 + SMART_WRITE_THRESHOLDS = 0xd7 + SMB_SUPER_MAGIC = 0x517b + SOCKFS_MAGIC = 0x534f434b SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 @@ -1628,6 +1802,7 @@ const ( SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_TIPC = 0x10f + SOL_TLS = 0x11a SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e @@ -1696,10 +1871,35 @@ const ( SO_VM_SOCKETS_PEER_HOST_VM_ID = 0x3 SO_VM_SOCKETS_TRUSTED = 0x5 SO_WIFI_STATUS = 0x29 + SO_ZEROCOPY = 0x3c SPLICE_F_GIFT = 0x8 SPLICE_F_MORE = 0x4 SPLICE_F_MOVE = 0x1 SPLICE_F_NONBLOCK = 0x2 + SQUASHFS_MAGIC = 0x73717368 + STACK_END_MAGIC = 0x57ac6e9d + STATX_ALL = 0xfff + STATX_ATIME = 0x20 + STATX_ATTR_APPEND = 0x20 + STATX_ATTR_AUTOMOUNT = 0x1000 + STATX_ATTR_COMPRESSED = 0x4 + STATX_ATTR_ENCRYPTED = 0x800 + STATX_ATTR_IMMUTABLE = 0x10 + STATX_ATTR_NODUMP = 0x40 + STATX_BASIC_STATS = 0x7ff + STATX_BLOCKS = 0x400 + STATX_BTIME = 0x800 + STATX_CTIME = 0x80 + STATX_GID = 0x10 + STATX_INO = 0x100 + STATX_MODE = 0x2 + STATX_MTIME = 0x40 + STATX_NLINK = 0x4 + STATX_SIZE = 0x200 + STATX_TYPE = 0x1 + STATX_UID = 0x8 + STATX__RESERVED = 0x80000000 + SYSFS_MAGIC = 0x62656572 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 @@ -1771,6 +1971,8 @@ const ( TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe + TCP_MD5SIG_EXT = 0x20 + TCP_MD5SIG_FLAG_PREFIX = 0x1 TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_MSS_DEFAULT = 0x218 @@ -1791,6 +1993,7 @@ const ( TCP_THIN_DUPACK = 0x11 TCP_THIN_LINEAR_TIMEOUTS = 0x10 TCP_TIMESTAMP = 0x18 + TCP_ULP = 0x1f TCP_USER_TIMEOUT = 0x12 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 0x2 @@ -1878,7 +2081,27 @@ const ( TIOCSTI = 0x5412 TIOCSWINSZ = 0x5414 TIOCVHANGUP = 0x5437 + TMPFS_MAGIC = 0x1021994 TOSTOP = 0x100 + TPACKET_ALIGNMENT = 0x10 + TPACKET_HDRLEN = 0x34 + TP_STATUS_AVAILABLE = 0x0 + TP_STATUS_BLK_TMO = 0x20 + TP_STATUS_COPY = 0x2 + TP_STATUS_CSUMNOTREADY = 0x8 + TP_STATUS_CSUM_VALID = 0x80 + TP_STATUS_KERNEL = 0x0 + TP_STATUS_LOSING = 0x4 + TP_STATUS_SENDING = 0x2 + TP_STATUS_SEND_REQUEST = 0x1 + TP_STATUS_TS_RAW_HARDWARE = -0x80000000 + TP_STATUS_TS_SOFTWARE = 0x20000000 + TP_STATUS_TS_SYS_HARDWARE = 0x40000000 + TP_STATUS_USER = 0x1 + TP_STATUS_VLAN_TPID_VALID = 0x40 + TP_STATUS_VLAN_VALID = 0x10 + TP_STATUS_WRONG_FORMAT = 0x4 + TRACEFS_MAGIC = 0x74726163 TS_COMM_LEN = 0x20 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 @@ -1890,6 +2113,7 @@ const ( TUNGETVNETHDRSZ = 0x800454d7 TUNGETVNETLE = 0x800454dd TUNSETDEBUG = 0x400454c9 + TUNSETFILTEREBPF = 0x800454e1 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da @@ -1900,13 +2124,17 @@ const ( TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 + TUNSETSTEERINGEBPF = 0x800454e0 TUNSETTXFILTER = 0x400454d1 TUNSETVNETBE = 0x400454de TUNSETVNETHDRSZ = 0x400454d8 TUNSETVNETLE = 0x400454dc + UDF_SUPER_MAGIC = 0x15013346 UMOUNT_NOFOLLOW = 0x8 + USBDEVICE_SUPER_MAGIC = 0x9fa2 UTIME_NOW = 0x3fffffff UTIME_OMIT = 0x3ffffffe + V9FS_MAGIC = 0x1021997 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb @@ -1948,6 +2176,86 @@ const ( WDIOC_SETPRETIMEOUT = 0xc0045708 WDIOC_SETTIMEOUT = 0xc0045706 WEXITED = 0x4 + WIN_ACKMEDIACHANGE = 0xdb + WIN_CHECKPOWERMODE1 = 0xe5 + WIN_CHECKPOWERMODE2 = 0x98 + WIN_DEVICE_RESET = 0x8 + WIN_DIAGNOSE = 0x90 + WIN_DOORLOCK = 0xde + WIN_DOORUNLOCK = 0xdf + WIN_DOWNLOAD_MICROCODE = 0x92 + WIN_FLUSH_CACHE = 0xe7 + WIN_FLUSH_CACHE_EXT = 0xea + WIN_FORMAT = 0x50 + WIN_GETMEDIASTATUS = 0xda + WIN_IDENTIFY = 0xec + WIN_IDENTIFY_DMA = 0xee + WIN_IDLEIMMEDIATE = 0xe1 + WIN_INIT = 0x60 + WIN_MEDIAEJECT = 0xed + WIN_MULTREAD = 0xc4 + WIN_MULTREAD_EXT = 0x29 + WIN_MULTWRITE = 0xc5 + WIN_MULTWRITE_EXT = 0x39 + WIN_NOP = 0x0 + WIN_PACKETCMD = 0xa0 + WIN_PIDENTIFY = 0xa1 + WIN_POSTBOOT = 0xdc + WIN_PREBOOT = 0xdd + WIN_QUEUED_SERVICE = 0xa2 + WIN_READ = 0x20 + WIN_READDMA = 0xc8 + WIN_READDMA_EXT = 0x25 + WIN_READDMA_ONCE = 0xc9 + WIN_READDMA_QUEUED = 0xc7 + WIN_READDMA_QUEUED_EXT = 0x26 + WIN_READ_BUFFER = 0xe4 + WIN_READ_EXT = 0x24 + WIN_READ_LONG = 0x22 + WIN_READ_LONG_ONCE = 0x23 + WIN_READ_NATIVE_MAX = 0xf8 + WIN_READ_NATIVE_MAX_EXT = 0x27 + WIN_READ_ONCE = 0x21 + WIN_RECAL = 0x10 + WIN_RESTORE = 0x10 + WIN_SECURITY_DISABLE = 0xf6 + WIN_SECURITY_ERASE_PREPARE = 0xf3 + WIN_SECURITY_ERASE_UNIT = 0xf4 + WIN_SECURITY_FREEZE_LOCK = 0xf5 + WIN_SECURITY_SET_PASS = 0xf1 + WIN_SECURITY_UNLOCK = 0xf2 + WIN_SEEK = 0x70 + WIN_SETFEATURES = 0xef + WIN_SETIDLE1 = 0xe3 + WIN_SETIDLE2 = 0x97 + WIN_SETMULT = 0xc6 + WIN_SET_MAX = 0xf9 + WIN_SET_MAX_EXT = 0x37 + WIN_SLEEPNOW1 = 0xe6 + WIN_SLEEPNOW2 = 0x99 + WIN_SMART = 0xb0 + WIN_SPECIFY = 0x91 + WIN_SRST = 0x8 + WIN_STANDBY = 0xe2 + WIN_STANDBY2 = 0x96 + WIN_STANDBYNOW1 = 0xe0 + WIN_STANDBYNOW2 = 0x94 + WIN_VERIFY = 0x40 + WIN_VERIFY_EXT = 0x42 + WIN_VERIFY_ONCE = 0x41 + WIN_WRITE = 0x30 + WIN_WRITEDMA = 0xca + WIN_WRITEDMA_EXT = 0x35 + WIN_WRITEDMA_ONCE = 0xcb + WIN_WRITEDMA_QUEUED = 0xcc + WIN_WRITEDMA_QUEUED_EXT = 0x36 + WIN_WRITE_BUFFER = 0xe8 + WIN_WRITE_EXT = 0x34 + WIN_WRITE_LONG = 0x32 + WIN_WRITE_LONG_ONCE = 0x33 + WIN_WRITE_ONCE = 0x31 + WIN_WRITE_SAME = 0xe9 + WIN_WRITE_VERIFY = 0x3c WNOHANG = 0x1 WNOTHREAD = 0x20000000 WNOWAIT = 0x1000000 @@ -1957,7 +2265,9 @@ const ( XATTR_CREATE = 0x1 XATTR_REPLACE = 0x2 XCASE = 0x4 + XENFS_SUPER_MAGIC = 0xabba1974 XTABS = 0x1800 + ZSMALLOC_MAGIC = 0x58295829 ) // Errors @@ -2137,171 +2447,179 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "no such device or address", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device or resource busy", - 17: "file exists", - 18: "invalid cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "numerical result out of range", - 35: "resource deadlock avoided", - 36: "file name too long", - 37: "no locks available", - 38: "function not implemented", - 39: "directory not empty", - 40: "too many levels of symbolic links", - 42: "no message of desired type", - 43: "identifier removed", - 44: "channel number out of range", - 45: "level 2 not synchronized", - 46: "level 3 halted", - 47: "level 3 reset", - 48: "link number out of range", - 49: "protocol driver not attached", - 50: "no CSI structure available", - 51: "level 2 halted", - 52: "invalid exchange", - 53: "invalid request descriptor", - 54: "exchange full", - 55: "no anode", - 56: "invalid request code", - 57: "invalid slot", - 59: "bad font file format", - 60: "device not a stream", - 61: "no data available", - 62: "timer expired", - 63: "out of streams resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "multihop attempted", - 73: "RFS specific error", - 74: "bad message", - 75: "value too large for defined data type", - 76: "name not unique on network", - 77: "file descriptor in bad state", - 78: "remote address changed", - 79: "can not access a needed shared library", - 80: "accessing a corrupted shared library", - 81: ".lib section in a.out corrupted", - 82: "attempting to link in too many shared libraries", - 83: "cannot exec a shared library directly", - 84: "invalid or incomplete multibyte or wide character", - 85: "interrupted system call should be restarted", - 86: "streams pipe error", - 87: "too many users", - 88: "socket operation on non-socket", - 89: "destination address required", - 90: "message too long", - 91: "protocol wrong type for socket", - 92: "protocol not available", - 93: "protocol not supported", - 94: "socket type not supported", - 95: "operation not supported", - 96: "protocol family not supported", - 97: "address family not supported by protocol", - 98: "address already in use", - 99: "cannot assign requested address", - 100: "network is down", - 101: "network is unreachable", - 102: "network dropped connection on reset", - 103: "software caused connection abort", - 104: "connection reset by peer", - 105: "no buffer space available", - 106: "transport endpoint is already connected", - 107: "transport endpoint is not connected", - 108: "cannot send after transport endpoint shutdown", - 109: "too many references: cannot splice", - 110: "connection timed out", - 111: "connection refused", - 112: "host is down", - 113: "no route to host", - 114: "operation already in progress", - 115: "operation now in progress", - 116: "stale file handle", - 117: "structure needs cleaning", - 118: "not a XENIX named type file", - 119: "no XENIX semaphores available", - 120: "is a named type file", - 121: "remote I/O error", - 122: "disk quota exceeded", - 123: "no medium found", - 124: "wrong medium type", - 125: "operation canceled", - 126: "required key not available", - 127: "key has expired", - 128: "key has been revoked", - 129: "key was rejected by service", - 130: "owner died", - 131: "state not recoverable", - 132: "operation not possible due to RF-kill", - 133: "memory page has hardware error", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device or resource busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "invalid cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "numerical result out of range"}, + {35, "EDEADLK", "resource deadlock avoided"}, + {36, "ENAMETOOLONG", "file name too long"}, + {37, "ENOLCK", "no locks available"}, + {38, "ENOSYS", "function not implemented"}, + {39, "ENOTEMPTY", "directory not empty"}, + {40, "ELOOP", "too many levels of symbolic links"}, + {42, "ENOMSG", "no message of desired type"}, + {43, "EIDRM", "identifier removed"}, + {44, "ECHRNG", "channel number out of range"}, + {45, "EL2NSYNC", "level 2 not synchronized"}, + {46, "EL3HLT", "level 3 halted"}, + {47, "EL3RST", "level 3 reset"}, + {48, "ELNRNG", "link number out of range"}, + {49, "EUNATCH", "protocol driver not attached"}, + {50, "ENOCSI", "no CSI structure available"}, + {51, "EL2HLT", "level 2 halted"}, + {52, "EBADE", "invalid exchange"}, + {53, "EBADR", "invalid request descriptor"}, + {54, "EXFULL", "exchange full"}, + {55, "ENOANO", "no anode"}, + {56, "EBADRQC", "invalid request code"}, + {57, "EBADSLT", "invalid slot"}, + {59, "EBFONT", "bad font file format"}, + {60, "ENOSTR", "device not a stream"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of streams resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {72, "EMULTIHOP", "multihop attempted"}, + {73, "EDOTDOT", "RFS specific error"}, + {74, "EBADMSG", "bad message"}, + {75, "EOVERFLOW", "value too large for defined data type"}, + {76, "ENOTUNIQ", "name not unique on network"}, + {77, "EBADFD", "file descriptor in bad state"}, + {78, "EREMCHG", "remote address changed"}, + {79, "ELIBACC", "can not access a needed shared library"}, + {80, "ELIBBAD", "accessing a corrupted shared library"}, + {81, "ELIBSCN", ".lib section in a.out corrupted"}, + {82, "ELIBMAX", "attempting to link in too many shared libraries"}, + {83, "ELIBEXEC", "cannot exec a shared library directly"}, + {84, "EILSEQ", "invalid or incomplete multibyte or wide character"}, + {85, "ERESTART", "interrupted system call should be restarted"}, + {86, "ESTRPIPE", "streams pipe error"}, + {87, "EUSERS", "too many users"}, + {88, "ENOTSOCK", "socket operation on non-socket"}, + {89, "EDESTADDRREQ", "destination address required"}, + {90, "EMSGSIZE", "message too long"}, + {91, "EPROTOTYPE", "protocol wrong type for socket"}, + {92, "ENOPROTOOPT", "protocol not available"}, + {93, "EPROTONOSUPPORT", "protocol not supported"}, + {94, "ESOCKTNOSUPPORT", "socket type not supported"}, + {95, "ENOTSUP", "operation not supported"}, + {96, "EPFNOSUPPORT", "protocol family not supported"}, + {97, "EAFNOSUPPORT", "address family not supported by protocol"}, + {98, "EADDRINUSE", "address already in use"}, + {99, "EADDRNOTAVAIL", "cannot assign requested address"}, + {100, "ENETDOWN", "network is down"}, + {101, "ENETUNREACH", "network is unreachable"}, + {102, "ENETRESET", "network dropped connection on reset"}, + {103, "ECONNABORTED", "software caused connection abort"}, + {104, "ECONNRESET", "connection reset by peer"}, + {105, "ENOBUFS", "no buffer space available"}, + {106, "EISCONN", "transport endpoint is already connected"}, + {107, "ENOTCONN", "transport endpoint is not connected"}, + {108, "ESHUTDOWN", "cannot send after transport endpoint shutdown"}, + {109, "ETOOMANYREFS", "too many references: cannot splice"}, + {110, "ETIMEDOUT", "connection timed out"}, + {111, "ECONNREFUSED", "connection refused"}, + {112, "EHOSTDOWN", "host is down"}, + {113, "EHOSTUNREACH", "no route to host"}, + {114, "EALREADY", "operation already in progress"}, + {115, "EINPROGRESS", "operation now in progress"}, + {116, "ESTALE", "stale file handle"}, + {117, "EUCLEAN", "structure needs cleaning"}, + {118, "ENOTNAM", "not a XENIX named type file"}, + {119, "ENAVAIL", "no XENIX semaphores available"}, + {120, "EISNAM", "is a named type file"}, + {121, "EREMOTEIO", "remote I/O error"}, + {122, "EDQUOT", "disk quota exceeded"}, + {123, "ENOMEDIUM", "no medium found"}, + {124, "EMEDIUMTYPE", "wrong medium type"}, + {125, "ECANCELED", "operation canceled"}, + {126, "ENOKEY", "required key not available"}, + {127, "EKEYEXPIRED", "key has expired"}, + {128, "EKEYREVOKED", "key has been revoked"}, + {129, "EKEYREJECTED", "key was rejected by service"}, + {130, "EOWNERDEAD", "owner died"}, + {131, "ENOTRECOVERABLE", "state not recoverable"}, + {132, "ERFKILL", "operation not possible due to RF-kill"}, + {133, "EHWPOISON", "memory page has hardware error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/breakpoint trap", - 6: "aborted", - 7: "bus error", - 8: "floating point exception", - 9: "killed", - 10: "user defined signal 1", - 11: "segmentation fault", - 12: "user defined signal 2", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "stack fault", - 17: "child exited", - 18: "continued", - 19: "stopped (signal)", - 20: "stopped", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "urgent I/O condition", - 24: "CPU time limit exceeded", - 25: "file size limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window changed", - 29: "I/O possible", - 30: "power failure", - 31: "bad system call", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/breakpoint trap"}, + {6, "SIGABRT", "aborted"}, + {7, "SIGBUS", "bus error"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGUSR1", "user defined signal 1"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGUSR2", "user defined signal 2"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGSTKFLT", "stack fault"}, + {17, "SIGCHLD", "child exited"}, + {18, "SIGCONT", "continued"}, + {19, "SIGSTOP", "stopped (signal)"}, + {20, "SIGTSTP", "stopped"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGURG", "urgent I/O condition"}, + {24, "SIGXCPU", "CPU time limit exceeded"}, + {25, "SIGXFSZ", "file size limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window changed"}, + {29, "SIGIO", "I/O possible"}, + {30, "SIGPWR", "power failure"}, + {31, "SIGSYS", "bad system call"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go b/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go index b4338d5f26..cd93ce0d85 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go @@ -1,5 +1,5 @@ // mkerrors.sh -m32 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT +// Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,netbsd @@ -159,6 +159,7 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CREAD = 0x800 + CRTSCTS = 0x10000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 @@ -169,6 +170,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 CTL_QUERY = -0x2 @@ -581,6 +584,7 @@ const ( F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -970,6 +974,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -1576,137 +1584,145 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large or too small", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol option not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "connection timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "illegal byte sequence", - 86: "not supported", - 87: "operation Canceled", - 88: "bad or Corrupt message", - 89: "no message available", - 90: "no STREAM resources", - 91: "not a STREAM", - 92: "STREAM ioctl timeout", - 93: "attribute not found", - 94: "multihop attempted", - 95: "link has been severed", - 96: "protocol error", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large or too small"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol option not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "EOPNOTSUPP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "connection timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EIDRM", "identifier removed"}, + {83, "ENOMSG", "no message of desired type"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "EILSEQ", "illegal byte sequence"}, + {86, "ENOTSUP", "not supported"}, + {87, "ECANCELED", "operation Canceled"}, + {88, "EBADMSG", "bad or Corrupt message"}, + {89, "ENODATA", "no message available"}, + {90, "ENOSR", "no STREAM resources"}, + {91, "ENOSTR", "not a STREAM"}, + {92, "ETIME", "STREAM ioctl timeout"}, + {93, "ENOATTR", "attribute not found"}, + {94, "EMULTIHOP", "multihop attempted"}, + {95, "ENOLINK", "link has been severed"}, + {96, "ELAST", "protocol error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "stopped (signal)", - 18: "stopped", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "power fail/restart", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGIOT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "stopped (signal)"}, + {18, "SIGTSTP", "stopped"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, + {32, "SIGPWR", "power fail/restart"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go index 4994437b63..071701c411 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go @@ -1,5 +1,5 @@ // mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT +// Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,netbsd @@ -159,6 +159,7 @@ const ( CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CREAD = 0x800 + CRTSCTS = 0x10000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 @@ -169,6 +170,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 CTL_QUERY = -0x2 @@ -571,6 +574,7 @@ const ( F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -960,6 +964,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -1566,137 +1574,145 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large or too small", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol option not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "connection timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "illegal byte sequence", - 86: "not supported", - 87: "operation Canceled", - 88: "bad or Corrupt message", - 89: "no message available", - 90: "no STREAM resources", - 91: "not a STREAM", - 92: "STREAM ioctl timeout", - 93: "attribute not found", - 94: "multihop attempted", - 95: "link has been severed", - 96: "protocol error", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large or too small"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol option not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "EOPNOTSUPP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "connection timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EIDRM", "identifier removed"}, + {83, "ENOMSG", "no message of desired type"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "EILSEQ", "illegal byte sequence"}, + {86, "ENOTSUP", "not supported"}, + {87, "ECANCELED", "operation Canceled"}, + {88, "EBADMSG", "bad or Corrupt message"}, + {89, "ENODATA", "no message available"}, + {90, "ENOSR", "no STREAM resources"}, + {91, "ENOSTR", "not a STREAM"}, + {92, "ETIME", "STREAM ioctl timeout"}, + {93, "ENOATTR", "attribute not found"}, + {94, "EMULTIHOP", "multihop attempted"}, + {95, "ENOLINK", "link has been severed"}, + {96, "ELAST", "protocol error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "stopped (signal)", - 18: "stopped", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "power fail/restart", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGIOT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "stopped (signal)"}, + {18, "SIGTSTP", "stopped"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, + {32, "SIGPWR", "power fail/restart"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go index 206c75f094..5fe56ae8c7 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go @@ -1,5 +1,5 @@ // mkerrors.sh -marm -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT +// Code generated by the command above; see README.md. DO NOT EDIT. // +build arm,netbsd @@ -151,6 +151,7 @@ const ( CFLUSH = 0xf CLOCAL = 0x8000 CREAD = 0x800 + CRTSCTS = 0x10000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 @@ -161,6 +162,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 CTL_QUERY = -0x2 @@ -563,6 +566,7 @@ const ( F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -952,6 +956,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 @@ -1555,137 +1563,145 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large or too small", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol option not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "connection timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "identifier removed", - 83: "no message of desired type", - 84: "value too large to be stored in data type", - 85: "illegal byte sequence", - 86: "not supported", - 87: "operation Canceled", - 88: "bad or Corrupt message", - 89: "no message available", - 90: "no STREAM resources", - 91: "not a STREAM", - 92: "STREAM ioctl timeout", - 93: "attribute not found", - 94: "multihop attempted", - 95: "link has been severed", - 96: "protocol error", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large or too small"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol option not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "EOPNOTSUPP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "connection timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disc quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC prog. not avail"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EIDRM", "identifier removed"}, + {83, "ENOMSG", "no message of desired type"}, + {84, "EOVERFLOW", "value too large to be stored in data type"}, + {85, "EILSEQ", "illegal byte sequence"}, + {86, "ENOTSUP", "not supported"}, + {87, "ECANCELED", "operation Canceled"}, + {88, "EBADMSG", "bad or Corrupt message"}, + {89, "ENODATA", "no message available"}, + {90, "ENOSR", "no STREAM resources"}, + {91, "ENOSTR", "not a STREAM"}, + {92, "ETIME", "STREAM ioctl timeout"}, + {93, "ENOATTR", "attribute not found"}, + {94, "EMULTIHOP", "multihop attempted"}, + {95, "ENOLINK", "link has been severed"}, + {96, "ELAST", "protocol error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "stopped (signal)", - 18: "stopped", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "power fail/restart", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGIOT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "stopped (signal)"}, + {18, "SIGTSTP", "stopped"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, + {32, "SIGPWR", "power fail/restart"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go b/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go index 3322e998d3..0a1c3e7e8c 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go @@ -1,5 +1,5 @@ // mkerrors.sh -m32 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT +// Code generated by the command above; see README.md. DO NOT EDIT. // +build 386,openbsd @@ -147,6 +147,7 @@ const ( CFLUSH = 0xf CLOCAL = 0x8000 CREAD = 0x800 + CRTSCTS = 0x10000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 @@ -157,6 +158,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DIOCOSFPFLUSH = 0x2000444e @@ -442,6 +445,7 @@ const ( F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -860,6 +864,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LCNT_OVERLOAD_FLUSH = 0x6 LOCK_EX = 0x2 LOCK_NB = 0x4 @@ -1453,132 +1461,140 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "connection timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "IPsec processing failure", - 83: "attribute not found", - 84: "illegal byte sequence", - 85: "no medium found", - 86: "wrong medium type", - 87: "value too large to be stored in data type", - 88: "operation canceled", - 89: "identifier removed", - 90: "no message of desired type", - 91: "not supported", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EWOULDBLOCK", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "EOPNOTSUPP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disk quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC program not available"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EIPSEC", "IPsec processing failure"}, + {83, "ENOATTR", "attribute not found"}, + {84, "EILSEQ", "illegal byte sequence"}, + {85, "ENOMEDIUM", "no medium found"}, + {86, "EMEDIUMTYPE", "wrong medium type"}, + {87, "EOVERFLOW", "value too large to be stored in data type"}, + {88, "ECANCELED", "operation canceled"}, + {89, "EIDRM", "identifier removed"}, + {90, "ENOMSG", "no message of desired type"}, + {91, "ELAST", "not supported"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "stopped (signal)", - 18: "stopped", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "thread AST", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGABRT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, + {32, "SIGTHR", "thread AST"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go index 1758ecca93..acfc664691 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go @@ -1,5 +1,5 @@ // mkerrors.sh -m64 -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT +// Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,openbsd @@ -45,6 +45,7 @@ const ( AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 + ALTWERASE = 0x200 ARPHRD_ETHER = 0x1 ARPHRD_FRELAY = 0xf ARPHRD_IEEE1394 = 0x18 @@ -146,7 +147,14 @@ const ( BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 + CLOCK_BOOTTIME = 0x6 + CLOCK_MONOTONIC = 0x3 + CLOCK_PROCESS_CPUTIME_ID = 0x2 + CLOCK_REALTIME = 0x0 + CLOCK_THREAD_CPUTIME_ID = 0x4 + CLOCK_UPTIME = 0x5 CREAD = 0x800 + CRTSCTS = 0x10000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 @@ -157,6 +165,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DIOCOSFPFLUSH = 0x2000444e @@ -175,6 +185,7 @@ const ( DLT_LOOP = 0xc DLT_MPLS = 0xdb DLT_NULL = 0x0 + DLT_OPENFLOW = 0x10b DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 @@ -185,6 +196,23 @@ const ( DLT_RAW = 0xe DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf + DLT_USBPCAP = 0xf9 + DLT_USER0 = 0x93 + DLT_USER1 = 0x94 + DLT_USER10 = 0x9d + DLT_USER11 = 0x9e + DLT_USER12 = 0x9f + DLT_USER13 = 0xa0 + DLT_USER14 = 0xa1 + DLT_USER15 = 0xa2 + DLT_USER2 = 0x95 + DLT_USER3 = 0x96 + DLT_USER4 = 0x97 + DLT_USER5 = 0x98 + DLT_USER6 = 0x99 + DLT_USER7 = 0x9a + DLT_USER8 = 0x9b + DLT_USER9 = 0x9c DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 @@ -398,27 +426,38 @@ const ( ETHER_CRC_POLY_LE = 0xedb88320 ETHER_HDR_LEN = 0xe ETHER_MAX_DIX_LEN = 0x600 + ETHER_MAX_HARDMTU_LEN = 0xff9b ETHER_MAX_LEN = 0x5ee ETHER_MIN_LEN = 0x40 ETHER_TYPE_LEN = 0x2 ETHER_VLAN_ENCAP_LEN = 0x4 EVFILT_AIO = -0x3 + EVFILT_DEVICE = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 - EVFILT_SYSCOUNT = 0x7 + EVFILT_SYSCOUNT = 0x8 EVFILT_TIMER = -0x7 EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 + EVL_ENCAPLEN = 0x4 + EVL_PRIO_BITS = 0xd + EVL_PRIO_MAX = 0x7 + EVL_VLID_MASK = 0xfff + EVL_VLID_MAX = 0xffe + EVL_VLID_MIN = 0x1 + EVL_VLID_NULL = 0x0 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 + EV_DISPATCH = 0x80 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 + EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 @@ -432,7 +471,7 @@ const ( F_GETFL = 0x3 F_GETLK = 0x7 F_GETOWN = 0x5 - F_OK = 0x0 + F_ISATTY = 0xb F_RDLCK = 0x1 F_SETFD = 0x2 F_SETFL = 0x4 @@ -442,13 +481,13 @@ const ( F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFAN_ARRIVAL = 0x0 IFAN_DEPARTURE = 0x1 - IFA_ROUTE = 0x1 IFF_ALLMULTI = 0x200 IFF_BROADCAST = 0x2 IFF_CANTCHANGE = 0x8e52 @@ -459,12 +498,12 @@ const ( IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 - IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 + IFF_STATICARP = 0x20 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 @@ -593,6 +632,7 @@ const ( IFT_LINEGROUP = 0xd2 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 + IFT_MBIM = 0xfa IFT_MEDIAMAILOVERIP = 0x8b IFT_MFSIGLINK = 0xa7 IFT_MIOX25 = 0x26 @@ -717,8 +757,6 @@ const ( IPPROTO_AH = 0x33 IPPROTO_CARP = 0x70 IPPROTO_DIVERT = 0x102 - IPPROTO_DIVERT_INIT = 0x2 - IPPROTO_DIVERT_RESP = 0x1 IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 @@ -775,6 +813,7 @@ const ( IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXPACKET = 0xffff + IPV6_MINHOPCOUNT = 0x41 IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 @@ -814,12 +853,12 @@ const ( IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 - IP_DIVERTFL = 0x1022 IP_DROP_MEMBERSHIP = 0xd IP_ESP_NETWORK_LEVEL = 0x16 IP_ESP_TRANS_LEVEL = 0x15 IP_HDRINCL = 0x2 IP_IPCOMP_LEVEL = 0x1d + IP_IPDEFTTL = 0x25 IP_IPSECFLOWINFO = 0x24 IP_IPSEC_LOCAL_AUTH = 0x1b IP_IPSEC_LOCAL_CRED = 0x19 @@ -853,13 +892,19 @@ const ( IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RTABLE = 0x1021 + IP_SENDSRCADDR = 0x7 IP_TOS = 0x3 IP_TTL = 0x4 ISIG = 0x80 ISTRIP = 0x20 + IUCLC = 0x1000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LCNT_OVERLOAD_FLUSH = 0x6 LOCK_EX = 0x2 LOCK_NB = 0x4 @@ -873,25 +918,28 @@ const ( MADV_SPACEAVAIL = 0x5 MADV_WILLNEED = 0x3 MAP_ANON = 0x1000 - MAP_COPY = 0x4 + MAP_ANONYMOUS = 0x1000 + MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 - MAP_FLAGMASK = 0x1ff7 - MAP_HASSEMAPHORE = 0x200 - MAP_INHERIT = 0x80 + MAP_FLAGMASK = 0x7ff7 + MAP_HASSEMAPHORE = 0x0 + MAP_INHERIT = 0x0 MAP_INHERIT_COPY = 0x1 - MAP_INHERIT_DONATE_COPY = 0x3 MAP_INHERIT_NONE = 0x2 MAP_INHERIT_SHARE = 0x0 - MAP_NOEXTEND = 0x100 - MAP_NORESERVE = 0x40 + MAP_INHERIT_ZERO = 0x3 + MAP_NOEXTEND = 0x0 + MAP_NORESERVE = 0x0 MAP_PRIVATE = 0x2 - MAP_RENAME = 0x20 + MAP_RENAME = 0x0 MAP_SHARED = 0x1 - MAP_TRYFIXED = 0x400 + MAP_STACK = 0x4000 + MAP_TRYFIXED = 0x0 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_BCAST = 0x100 + MSG_CMSG_CLOEXEC = 0x800 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 @@ -909,11 +957,14 @@ const ( NET_RT_DUMP = 0x1 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 - NET_RT_MAXID = 0x6 + NET_RT_IFNAMES = 0x6 + NET_RT_MAXID = 0x7 NET_RT_STATS = 0x4 NET_RT_TABLE = 0x5 NOFLSH = 0x80000000 + NOKERNINFO = 0x2000000 NOTE_ATTRIB = 0x8 + NOTE_CHANGE = 0x1 NOTE_CHILD = 0x4 NOTE_DELETE = 0x1 NOTE_EOF = 0x2 @@ -932,11 +983,13 @@ const ( NOTE_TRUNCATE = 0x80 NOTE_WRITE = 0x2 OCRNL = 0x10 + OLCUC = 0x20 ONLCR = 0x2 ONLRET = 0x80 ONOCR = 0x40 ONOEOT = 0x8 OPOST = 0x1 + OXTABS = 0x4 O_ACCMODE = 0x3 O_APPEND = 0x8 O_ASYNC = 0x40 @@ -974,23 +1027,32 @@ const ( RLIMIT_CPU = 0x0 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 + RLIMIT_MEMLOCK = 0x6 RLIMIT_NOFILE = 0x8 + RLIMIT_NPROC = 0x7 + RLIMIT_RSS = 0x5 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 + RTAX_BFD = 0xb RTAX_BRD = 0x7 + RTAX_DNS = 0xc RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_LABEL = 0xa - RTAX_MAX = 0xb + RTAX_MAX = 0xf RTAX_NETMASK = 0x2 + RTAX_SEARCH = 0xe RTAX_SRC = 0x8 RTAX_SRCMASK = 0x9 + RTAX_STATIC = 0xd RTA_AUTHOR = 0x40 + RTA_BFD = 0x800 RTA_BRD = 0x80 + RTA_DNS = 0x1000 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 @@ -998,34 +1060,39 @@ const ( RTA_IFP = 0x10 RTA_LABEL = 0x400 RTA_NETMASK = 0x4 + RTA_SEARCH = 0x4000 RTA_SRC = 0x100 RTA_SRCMASK = 0x200 + RTA_STATIC = 0x2000 RTF_ANNOUNCE = 0x4000 + RTF_BFD = 0x1000000 RTF_BLACKHOLE = 0x1000 + RTF_BROADCAST = 0x400000 + RTF_CACHED = 0x20000 RTF_CLONED = 0x10000 RTF_CLONING = 0x100 + RTF_CONNECTED = 0x800000 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 - RTF_FMASK = 0x10f808 + RTF_FMASK = 0x110fc08 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_LLINFO = 0x400 - RTF_MASK = 0x80 + RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MPATH = 0x40000 RTF_MPLS = 0x100000 + RTF_MULTICAST = 0x200 RTF_PERMANENT_ARP = 0x2000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x2000 RTF_REJECT = 0x8 - RTF_SOURCE = 0x20000 RTF_STATIC = 0x800 - RTF_TUNNEL = 0x100000 RTF_UP = 0x1 RTF_USETRAILERS = 0x8000 - RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 + RTM_BFD = 0x12 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 @@ -1033,11 +1100,13 @@ const ( RTM_GET = 0x4 RTM_IFANNOUNCE = 0xf RTM_IFINFO = 0xe + RTM_INVALIDATE = 0x11 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MAXSIZE = 0x800 RTM_MISS = 0x7 RTM_NEWADDR = 0xc + RTM_PROPOSAL = 0x13 RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 @@ -1050,6 +1119,8 @@ const ( RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 + RT_TABLEID_BITS = 0x8 + RT_TABLEID_MASK = 0xff RT_TABLEID_MAX = 0xff RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 @@ -1062,55 +1133,55 @@ const ( SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80286987 - SIOCALIFADDR = 0x8218691c SIOCATMARK = 0x40047307 - SIOCBRDGADD = 0x8058693c - SIOCBRDGADDS = 0x80586941 - SIOCBRDGARL = 0x806e694d + SIOCBRDGADD = 0x8060693c + SIOCBRDGADDL = 0x80606949 + SIOCBRDGADDS = 0x80606941 + SIOCBRDGARL = 0x808c694d SIOCBRDGDADDR = 0x81286947 - SIOCBRDGDEL = 0x8058693d - SIOCBRDGDELS = 0x80586942 - SIOCBRDGFLUSH = 0x80586948 - SIOCBRDGFRL = 0x806e694e - SIOCBRDGGCACHE = 0xc0146941 - SIOCBRDGGFD = 0xc0146952 - SIOCBRDGGHT = 0xc0146951 - SIOCBRDGGIFFLGS = 0xc058693e - SIOCBRDGGMA = 0xc0146953 + SIOCBRDGDEL = 0x8060693d + SIOCBRDGDELS = 0x80606942 + SIOCBRDGFLUSH = 0x80606948 + SIOCBRDGFRL = 0x808c694e + SIOCBRDGGCACHE = 0xc0186941 + SIOCBRDGGFD = 0xc0186952 + SIOCBRDGGHT = 0xc0186951 + SIOCBRDGGIFFLGS = 0xc060693e + SIOCBRDGGMA = 0xc0186953 SIOCBRDGGPARAM = 0xc0406958 - SIOCBRDGGPRI = 0xc0146950 + SIOCBRDGGPRI = 0xc0186950 SIOCBRDGGRL = 0xc030694f - SIOCBRDGGSIFS = 0xc058693c - SIOCBRDGGTO = 0xc0146946 - SIOCBRDGIFS = 0xc0586942 + SIOCBRDGGTO = 0xc0186946 + SIOCBRDGIFS = 0xc0606942 SIOCBRDGRTS = 0xc0206943 SIOCBRDGSADDR = 0xc1286944 - SIOCBRDGSCACHE = 0x80146940 - SIOCBRDGSFD = 0x80146952 - SIOCBRDGSHT = 0x80146951 - SIOCBRDGSIFCOST = 0x80586955 - SIOCBRDGSIFFLGS = 0x8058693f - SIOCBRDGSIFPRIO = 0x80586954 - SIOCBRDGSMA = 0x80146953 - SIOCBRDGSPRI = 0x80146950 - SIOCBRDGSPROTO = 0x8014695a - SIOCBRDGSTO = 0x80146945 - SIOCBRDGSTXHC = 0x80146959 + SIOCBRDGSCACHE = 0x80186940 + SIOCBRDGSFD = 0x80186952 + SIOCBRDGSHT = 0x80186951 + SIOCBRDGSIFCOST = 0x80606955 + SIOCBRDGSIFFLGS = 0x8060693f + SIOCBRDGSIFPRIO = 0x80606954 + SIOCBRDGSIFPROT = 0x8060694a + SIOCBRDGSMA = 0x80186953 + SIOCBRDGSPRI = 0x80186950 + SIOCBRDGSPROTO = 0x8018695a + SIOCBRDGSTO = 0x80186945 + SIOCBRDGSTXHC = 0x80186959 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80286989 + SIOCDIFPARENT = 0x802069b4 SIOCDIFPHYADDR = 0x80206949 - SIOCDLIFADDR = 0x8218691e + SIOCDVNETID = 0x802069af SIOCGETKALIVE = 0xc01869a4 SIOCGETLABEL = 0x8020699a + SIOCGETMPWCFG = 0xc02069ae SIOCGETPFLOW = 0xc02069fe SIOCGETPFSYNC = 0xc02069f8 SIOCGETSGCNT = 0xc0207534 SIOCGETVIFCNT = 0xc0287533 SIOCGETVLAN = 0xc0206990 - SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 - SIOCGIFASYNCMAP = 0xc020697c SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCONF = 0xc0106924 SIOCGIFDATA = 0xc020691b @@ -1122,37 +1193,41 @@ const ( SIOCGIFGMEMB = 0xc028698a SIOCGIFGROUP = 0xc0286988 SIOCGIFHARDMTU = 0xc02069a5 - SIOCGIFMEDIA = 0xc0306936 + SIOCGIFLLPRIO = 0xc02069b6 + SIOCGIFMEDIA = 0xc0406938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc020697e SIOCGIFNETMASK = 0xc0206925 - SIOCGIFPDSTADDR = 0xc0206948 + SIOCGIFPAIR = 0xc02069b1 + SIOCGIFPARENT = 0xc02069b3 SIOCGIFPRIORITY = 0xc020699c - SIOCGIFPSRCADDR = 0xc0206947 SIOCGIFRDOMAIN = 0xc02069a0 SIOCGIFRTLABEL = 0xc0206983 - SIOCGIFTIMESLOT = 0xc0206986 + SIOCGIFRXR = 0x802069aa SIOCGIFXFLAGS = 0xc020699e - SIOCGLIFADDR = 0xc218691d SIOCGLIFPHYADDR = 0xc218694b + SIOCGLIFPHYDF = 0xc02069c2 SIOCGLIFPHYRTABLE = 0xc02069a2 SIOCGLIFPHYTTL = 0xc02069a9 - SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGSPPPPARAMS = 0xc0206994 + SIOCGUMBINFO = 0xc02069be + SIOCGUMBPARAM = 0xc02069c0 SIOCGVH = 0xc02069f6 + SIOCGVNETFLOWID = 0xc02069c4 SIOCGVNETID = 0xc02069a7 + SIOCIFAFATTACH = 0x801169ab + SIOCIFAFDETACH = 0x801169ac SIOCIFCREATE = 0x8020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106978 SIOCSETKALIVE = 0x801869a3 SIOCSETLABEL = 0x80206999 + SIOCSETMPWCFG = 0x802069ad SIOCSETPFLOW = 0x802069fd SIOCSETPFSYNC = 0x802069f7 SIOCSETVLAN = 0x8020698f - SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c - SIOCSIFASYNCMAP = 0x8020697d SIOCSIFBRDADDR = 0x80206913 SIOCSIFDESCR = 0x80206980 SIOCSIFDSTADDR = 0x8020690e @@ -1160,25 +1235,36 @@ const ( SIOCSIFGATTR = 0x8028698c SIOCSIFGENERIC = 0x80206939 SIOCSIFLLADDR = 0x8020691f - SIOCSIFMEDIA = 0xc0206935 + SIOCSIFLLPRIO = 0x802069b5 + SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x8020697f SIOCSIFNETMASK = 0x80206916 - SIOCSIFPHYADDR = 0x80406946 + SIOCSIFPAIR = 0x802069b0 + SIOCSIFPARENT = 0x802069b2 SIOCSIFPRIORITY = 0x8020699b SIOCSIFRDOMAIN = 0x8020699f SIOCSIFRTLABEL = 0x80206982 - SIOCSIFTIMESLOT = 0x80206985 SIOCSIFXFLAGS = 0x8020699d SIOCSLIFPHYADDR = 0x8218694a + SIOCSLIFPHYDF = 0x802069c1 SIOCSLIFPHYRTABLE = 0x802069a1 SIOCSLIFPHYTTL = 0x802069a8 - SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SIOCSSPPPPARAMS = 0x80206993 + SIOCSUMBPARAM = 0x802069bf SIOCSVH = 0xc02069f5 + SIOCSVNETFLOWID = 0x802069c3 SIOCSVNETID = 0x802069a6 + SIOCSWGDPID = 0xc018695b + SIOCSWGMAXFLOW = 0xc0186960 + SIOCSWGMAXGROUP = 0xc018695d + SIOCSWSDPID = 0x8018695c + SIOCSWSPORTNO = 0xc060695f + SOCK_CLOEXEC = 0x8000 SOCK_DGRAM = 0x2 + SOCK_DNS = 0x1000 + SOCK_NONBLOCK = 0x4000 SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 @@ -1209,9 +1295,14 @@ const ( SO_TIMESTAMP = 0x800 SO_TYPE = 0x1008 SO_USELOOPBACK = 0x40 + SO_ZEROIZE = 0x2000 TCIFLUSH = 0x1 + TCIOFF = 0x3 TCIOFLUSH = 0x3 + TCION = 0x4 TCOFLUSH = 0x2 + TCOOFF = 0x1 + TCOON = 0x2 TCP_MAXBURST = 0x4 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff @@ -1221,11 +1312,12 @@ const ( TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOPUSH = 0x10 - TCP_NSTATES = 0xb TCP_SACK_ENABLE = 0x8 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 + TIOCCHKVERAUTH = 0x2000741e + TIOCCLRVERAUTH = 0x2000741d TIOCCONS = 0x80047462 TIOCDRAIN = 0x2000745e TIOCEXCL = 0x2000740d @@ -1280,16 +1372,19 @@ const ( TIOCSETAF = 0x802c7416 TIOCSETAW = 0x802c7415 TIOCSETD = 0x8004741b + TIOCSETVERAUTH = 0x8004741c TIOCSFLAGS = 0x8004745c TIOCSIG = 0x8004745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e - TIOCSTAT = 0x80047465 + TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSTSTAMP = 0x8008745a TIOCSWINSZ = 0x80087467 TIOCUCNTL = 0x80047466 + TIOCUCNTL_CBRK = 0x7a + TIOCUCNTL_SBRK = 0x7b TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb @@ -1301,6 +1396,18 @@ const ( VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 + VM_ANONMIN = 0x7 + VM_LOADAVG = 0x2 + VM_MAXID = 0xc + VM_MAXSLP = 0xa + VM_METER = 0x1 + VM_NKMEMPAGES = 0x6 + VM_PSSTRINGS = 0x3 + VM_SWAPENCRYPT = 0x5 + VM_USPACE = 0xb + VM_UVMEXP = 0x4 + VM_VNODEMIN = 0x9 + VM_VTEXTMIN = 0x8 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc @@ -1313,8 +1420,8 @@ const ( WCONTINUED = 0x8 WCOREFLAG = 0x80 WNOHANG = 0x1 - WSTOPPED = 0x7f WUNTRACED = 0x2 + XCASE = 0x1000000 ) // Errors @@ -1328,6 +1435,7 @@ const ( EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADF = syscall.Errno(0x9) + EBADMSG = syscall.Errno(0x5c) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x58) @@ -1354,7 +1462,7 @@ const ( EIPSEC = syscall.Errno(0x52) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) - ELAST = syscall.Errno(0x5b) + ELAST = syscall.Errno(0x5f) ELOOP = syscall.Errno(0x3e) EMEDIUMTYPE = syscall.Errno(0x56) EMFILE = syscall.Errno(0x18) @@ -1382,12 +1490,14 @@ const ( ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) + ENOTRECOVERABLE = syscall.Errno(0x5d) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x5b) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x2d) EOVERFLOW = syscall.Errno(0x57) + EOWNERDEAD = syscall.Errno(0x5e) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) @@ -1395,6 +1505,7 @@ const ( EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) + EPROTO = syscall.Errno(0x5f) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) ERANGE = syscall.Errno(0x22) @@ -1452,132 +1563,144 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "connection timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "IPsec processing failure", - 83: "attribute not found", - 84: "illegal byte sequence", - 85: "no medium found", - 86: "wrong medium type", - 87: "value too large to be stored in data type", - 88: "operation canceled", - 89: "identifier removed", - 90: "no message of desired type", - 91: "not supported", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EAGAIN", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "EOPNOTSUPP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disk quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC program not available"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EIPSEC", "IPsec processing failure"}, + {83, "ENOATTR", "attribute not found"}, + {84, "EILSEQ", "illegal byte sequence"}, + {85, "ENOMEDIUM", "no medium found"}, + {86, "EMEDIUMTYPE", "wrong medium type"}, + {87, "EOVERFLOW", "value too large to be stored in data type"}, + {88, "ECANCELED", "operation canceled"}, + {89, "EIDRM", "identifier removed"}, + {90, "ENOMSG", "no message of desired type"}, + {91, "ENOTSUP", "not supported"}, + {92, "EBADMSG", "bad message"}, + {93, "ENOTRECOVERABLE", "state not recoverable"}, + {94, "EOWNERDEAD", "previous owner died"}, + {95, "ELAST", "protocol error"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "stopped (signal)", - 18: "stopped", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "thread AST", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGABRT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, + {32, "SIGTHR", "thread AST"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go b/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go index 3ed0b2602f..93e37c4b28 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zerrors_openbsd_arm.go @@ -1,5 +1,5 @@ // mkerrors.sh -// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT +// Code generated by the command above; see README.md. DO NOT EDIT. // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go @@ -147,6 +147,7 @@ const ( CFLUSH = 0xf CLOCAL = 0x8000 CREAD = 0x800 + CRTSCTS = 0x10000 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 @@ -157,6 +158,8 @@ const ( CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a + CTL_HW = 0x6 + CTL_KERN = 0x1 CTL_MAXNAME = 0xc CTL_NET = 0x4 DIOCOSFPFLUSH = 0x2000444e @@ -441,6 +444,7 @@ const ( F_UNLCK = 0x2 F_WRLCK = 0x3 HUPCL = 0x4000 + HW_MACHINE = 0x1 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 @@ -859,6 +863,10 @@ const ( IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 + KERN_HOSTNAME = 0xa + KERN_OSRELEASE = 0x2 + KERN_OSTYPE = 0x1 + KERN_VERSION = 0x4 LCNT_OVERLOAD_FLUSH = 0x6 LOCK_EX = 0x2 LOCK_NB = 0x4 @@ -1455,132 +1463,140 @@ const ( ) // Error table -var errors = [...]string{ - 1: "operation not permitted", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "input/output error", - 6: "device not configured", - 7: "argument list too long", - 8: "exec format error", - 9: "bad file descriptor", - 10: "no child processes", - 11: "resource deadlock avoided", - 12: "cannot allocate memory", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "operation not supported by device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "too many open files in system", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "numerical argument out of domain", - 34: "result too large", - 35: "resource temporarily unavailable", - 36: "operation now in progress", - 37: "operation already in progress", - 38: "socket operation on non-socket", - 39: "destination address required", - 40: "message too long", - 41: "protocol wrong type for socket", - 42: "protocol not available", - 43: "protocol not supported", - 44: "socket type not supported", - 45: "operation not supported", - 46: "protocol family not supported", - 47: "address family not supported by protocol family", - 48: "address already in use", - 49: "can't assign requested address", - 50: "network is down", - 51: "network is unreachable", - 52: "network dropped connection on reset", - 53: "software caused connection abort", - 54: "connection reset by peer", - 55: "no buffer space available", - 56: "socket is already connected", - 57: "socket is not connected", - 58: "can't send after socket shutdown", - 59: "too many references: can't splice", - 60: "connection timed out", - 61: "connection refused", - 62: "too many levels of symbolic links", - 63: "file name too long", - 64: "host is down", - 65: "no route to host", - 66: "directory not empty", - 67: "too many processes", - 68: "too many users", - 69: "disc quota exceeded", - 70: "stale NFS file handle", - 71: "too many levels of remote in path", - 72: "RPC struct is bad", - 73: "RPC version wrong", - 74: "RPC prog. not avail", - 75: "program version wrong", - 76: "bad procedure for program", - 77: "no locks available", - 78: "function not implemented", - 79: "inappropriate file type or format", - 80: "authentication error", - 81: "need authenticator", - 82: "IPsec processing failure", - 83: "attribute not found", - 84: "illegal byte sequence", - 85: "no medium found", - 86: "wrong medium type", - 87: "value too large to be stored in data type", - 88: "operation canceled", - 89: "identifier removed", - 90: "no message of desired type", - 91: "not supported", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "operation not permitted"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "input/output error"}, + {6, "ENXIO", "device not configured"}, + {7, "E2BIG", "argument list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file descriptor"}, + {10, "ECHILD", "no child processes"}, + {11, "EDEADLK", "resource deadlock avoided"}, + {12, "ENOMEM", "cannot allocate memory"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "operation not supported by device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "too many open files in system"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "numerical argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "EWOULDBLOCK", "resource temporarily unavailable"}, + {36, "EINPROGRESS", "operation now in progress"}, + {37, "EALREADY", "operation already in progress"}, + {38, "ENOTSOCK", "socket operation on non-socket"}, + {39, "EDESTADDRREQ", "destination address required"}, + {40, "EMSGSIZE", "message too long"}, + {41, "EPROTOTYPE", "protocol wrong type for socket"}, + {42, "ENOPROTOOPT", "protocol not available"}, + {43, "EPROTONOSUPPORT", "protocol not supported"}, + {44, "ESOCKTNOSUPPORT", "socket type not supported"}, + {45, "EOPNOTSUPP", "operation not supported"}, + {46, "EPFNOSUPPORT", "protocol family not supported"}, + {47, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {48, "EADDRINUSE", "address already in use"}, + {49, "EADDRNOTAVAIL", "can't assign requested address"}, + {50, "ENETDOWN", "network is down"}, + {51, "ENETUNREACH", "network is unreachable"}, + {52, "ENETRESET", "network dropped connection on reset"}, + {53, "ECONNABORTED", "software caused connection abort"}, + {54, "ECONNRESET", "connection reset by peer"}, + {55, "ENOBUFS", "no buffer space available"}, + {56, "EISCONN", "socket is already connected"}, + {57, "ENOTCONN", "socket is not connected"}, + {58, "ESHUTDOWN", "can't send after socket shutdown"}, + {59, "ETOOMANYREFS", "too many references: can't splice"}, + {60, "ETIMEDOUT", "operation timed out"}, + {61, "ECONNREFUSED", "connection refused"}, + {62, "ELOOP", "too many levels of symbolic links"}, + {63, "ENAMETOOLONG", "file name too long"}, + {64, "EHOSTDOWN", "host is down"}, + {65, "EHOSTUNREACH", "no route to host"}, + {66, "ENOTEMPTY", "directory not empty"}, + {67, "EPROCLIM", "too many processes"}, + {68, "EUSERS", "too many users"}, + {69, "EDQUOT", "disk quota exceeded"}, + {70, "ESTALE", "stale NFS file handle"}, + {71, "EREMOTE", "too many levels of remote in path"}, + {72, "EBADRPC", "RPC struct is bad"}, + {73, "ERPCMISMATCH", "RPC version wrong"}, + {74, "EPROGUNAVAIL", "RPC program not available"}, + {75, "EPROGMISMATCH", "program version wrong"}, + {76, "EPROCUNAVAIL", "bad procedure for program"}, + {77, "ENOLCK", "no locks available"}, + {78, "ENOSYS", "function not implemented"}, + {79, "EFTYPE", "inappropriate file type or format"}, + {80, "EAUTH", "authentication error"}, + {81, "ENEEDAUTH", "need authenticator"}, + {82, "EIPSEC", "IPsec processing failure"}, + {83, "ENOATTR", "attribute not found"}, + {84, "EILSEQ", "illegal byte sequence"}, + {85, "ENOMEDIUM", "no medium found"}, + {86, "EMEDIUMTYPE", "wrong medium type"}, + {87, "EOVERFLOW", "value too large to be stored in data type"}, + {88, "ECANCELED", "operation canceled"}, + {89, "EIDRM", "identifier removed"}, + {90, "ENOMSG", "no message of desired type"}, + {91, "ELAST", "not supported"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal instruction", - 5: "trace/BPT trap", - 6: "abort trap", - 7: "EMT trap", - 8: "floating point exception", - 9: "killed", - 10: "bus error", - 11: "segmentation fault", - 12: "bad system call", - 13: "broken pipe", - 14: "alarm clock", - 15: "terminated", - 16: "urgent I/O condition", - 17: "stopped (signal)", - 18: "stopped", - 19: "continued", - 20: "child exited", - 21: "stopped (tty input)", - 22: "stopped (tty output)", - 23: "I/O possible", - 24: "cputime limit exceeded", - 25: "filesize limit exceeded", - 26: "virtual timer expired", - 27: "profiling timer expired", - 28: "window size changes", - 29: "information request", - 30: "user defined signal 1", - 31: "user defined signal 2", - 32: "thread AST", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal instruction"}, + {5, "SIGTRAP", "trace/BPT trap"}, + {6, "SIGABRT", "abort trap"}, + {7, "SIGEMT", "EMT trap"}, + {8, "SIGFPE", "floating point exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus error"}, + {11, "SIGSEGV", "segmentation fault"}, + {12, "SIGSYS", "bad system call"}, + {13, "SIGPIPE", "broken pipe"}, + {14, "SIGALRM", "alarm clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGURG", "urgent I/O condition"}, + {17, "SIGSTOP", "suspended (signal)"}, + {18, "SIGTSTP", "suspended"}, + {19, "SIGCONT", "continued"}, + {20, "SIGCHLD", "child exited"}, + {21, "SIGTTIN", "stopped (tty input)"}, + {22, "SIGTTOU", "stopped (tty output)"}, + {23, "SIGIO", "I/O possible"}, + {24, "SIGXCPU", "cputime limit exceeded"}, + {25, "SIGXFSZ", "filesize limit exceeded"}, + {26, "SIGVTALRM", "virtual timer expired"}, + {27, "SIGPROF", "profiling timer expired"}, + {28, "SIGWINCH", "window size changes"}, + {29, "SIGINFO", "information request"}, + {30, "SIGUSR1", "user defined signal 1"}, + {31, "SIGUSR2", "user defined signal 2"}, + {32, "SIGTHR", "thread AST"}, } diff --git a/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go b/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go index 09eedb0093..be42830cf3 100644 --- a/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go +++ b/vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go @@ -1319,171 +1319,179 @@ const ( ) // Error table -var errors = [...]string{ - 1: "not owner", - 2: "no such file or directory", - 3: "no such process", - 4: "interrupted system call", - 5: "I/O error", - 6: "no such device or address", - 7: "arg list too long", - 8: "exec format error", - 9: "bad file number", - 10: "no child processes", - 11: "resource temporarily unavailable", - 12: "not enough space", - 13: "permission denied", - 14: "bad address", - 15: "block device required", - 16: "device busy", - 17: "file exists", - 18: "cross-device link", - 19: "no such device", - 20: "not a directory", - 21: "is a directory", - 22: "invalid argument", - 23: "file table overflow", - 24: "too many open files", - 25: "inappropriate ioctl for device", - 26: "text file busy", - 27: "file too large", - 28: "no space left on device", - 29: "illegal seek", - 30: "read-only file system", - 31: "too many links", - 32: "broken pipe", - 33: "argument out of domain", - 34: "result too large", - 35: "no message of desired type", - 36: "identifier removed", - 37: "channel number out of range", - 38: "level 2 not synchronized", - 39: "level 3 halted", - 40: "level 3 reset", - 41: "link number out of range", - 42: "protocol driver not attached", - 43: "no CSI structure available", - 44: "level 2 halted", - 45: "deadlock situation detected/avoided", - 46: "no record locks available", - 47: "operation canceled", - 48: "operation not supported", - 49: "disc quota exceeded", - 50: "bad exchange descriptor", - 51: "bad request descriptor", - 52: "message tables full", - 53: "anode table overflow", - 54: "bad request code", - 55: "invalid slot", - 56: "file locking deadlock", - 57: "bad font file format", - 58: "owner of the lock died", - 59: "lock is not recoverable", - 60: "not a stream device", - 61: "no data available", - 62: "timer expired", - 63: "out of stream resources", - 64: "machine is not on the network", - 65: "package not installed", - 66: "object is remote", - 67: "link has been severed", - 68: "advertise error", - 69: "srmount error", - 70: "communication error on send", - 71: "protocol error", - 72: "locked lock was unmapped ", - 73: "facility is not active", - 74: "multihop attempted", - 77: "not a data message", - 78: "file name too long", - 79: "value too large for defined data type", - 80: "name not unique on network", - 81: "file descriptor in bad state", - 82: "remote address changed", - 83: "can not access a needed shared library", - 84: "accessing a corrupted shared library", - 85: ".lib section in a.out corrupted", - 86: "attempting to link in more shared libraries than system limit", - 87: "can not exec a shared library directly", - 88: "illegal byte sequence", - 89: "operation not applicable", - 90: "number of symbolic links encountered during path name traversal exceeds MAXSYMLINKS", - 91: "error 91", - 92: "error 92", - 93: "directory not empty", - 94: "too many users", - 95: "socket operation on non-socket", - 96: "destination address required", - 97: "message too long", - 98: "protocol wrong type for socket", - 99: "option not supported by protocol", - 120: "protocol not supported", - 121: "socket type not supported", - 122: "operation not supported on transport endpoint", - 123: "protocol family not supported", - 124: "address family not supported by protocol family", - 125: "address already in use", - 126: "cannot assign requested address", - 127: "network is down", - 128: "network is unreachable", - 129: "network dropped connection because of reset", - 130: "software caused connection abort", - 131: "connection reset by peer", - 132: "no buffer space available", - 133: "transport endpoint is already connected", - 134: "transport endpoint is not connected", - 143: "cannot send after socket shutdown", - 144: "too many references: cannot splice", - 145: "connection timed out", - 146: "connection refused", - 147: "host is down", - 148: "no route to host", - 149: "operation already in progress", - 150: "operation now in progress", - 151: "stale NFS file handle", +var errorList = [...]struct { + num syscall.Errno + name string + desc string +}{ + {1, "EPERM", "not owner"}, + {2, "ENOENT", "no such file or directory"}, + {3, "ESRCH", "no such process"}, + {4, "EINTR", "interrupted system call"}, + {5, "EIO", "I/O error"}, + {6, "ENXIO", "no such device or address"}, + {7, "E2BIG", "arg list too long"}, + {8, "ENOEXEC", "exec format error"}, + {9, "EBADF", "bad file number"}, + {10, "ECHILD", "no child processes"}, + {11, "EAGAIN", "resource temporarily unavailable"}, + {12, "ENOMEM", "not enough space"}, + {13, "EACCES", "permission denied"}, + {14, "EFAULT", "bad address"}, + {15, "ENOTBLK", "block device required"}, + {16, "EBUSY", "device busy"}, + {17, "EEXIST", "file exists"}, + {18, "EXDEV", "cross-device link"}, + {19, "ENODEV", "no such device"}, + {20, "ENOTDIR", "not a directory"}, + {21, "EISDIR", "is a directory"}, + {22, "EINVAL", "invalid argument"}, + {23, "ENFILE", "file table overflow"}, + {24, "EMFILE", "too many open files"}, + {25, "ENOTTY", "inappropriate ioctl for device"}, + {26, "ETXTBSY", "text file busy"}, + {27, "EFBIG", "file too large"}, + {28, "ENOSPC", "no space left on device"}, + {29, "ESPIPE", "illegal seek"}, + {30, "EROFS", "read-only file system"}, + {31, "EMLINK", "too many links"}, + {32, "EPIPE", "broken pipe"}, + {33, "EDOM", "argument out of domain"}, + {34, "ERANGE", "result too large"}, + {35, "ENOMSG", "no message of desired type"}, + {36, "EIDRM", "identifier removed"}, + {37, "ECHRNG", "channel number out of range"}, + {38, "EL2NSYNC", "level 2 not synchronized"}, + {39, "EL3HLT", "level 3 halted"}, + {40, "EL3RST", "level 3 reset"}, + {41, "ELNRNG", "link number out of range"}, + {42, "EUNATCH", "protocol driver not attached"}, + {43, "ENOCSI", "no CSI structure available"}, + {44, "EL2HLT", "level 2 halted"}, + {45, "EDEADLK", "deadlock situation detected/avoided"}, + {46, "ENOLCK", "no record locks available"}, + {47, "ECANCELED", "operation canceled"}, + {48, "ENOTSUP", "operation not supported"}, + {49, "EDQUOT", "disc quota exceeded"}, + {50, "EBADE", "bad exchange descriptor"}, + {51, "EBADR", "bad request descriptor"}, + {52, "EXFULL", "message tables full"}, + {53, "ENOANO", "anode table overflow"}, + {54, "EBADRQC", "bad request code"}, + {55, "EBADSLT", "invalid slot"}, + {56, "EDEADLOCK", "file locking deadlock"}, + {57, "EBFONT", "bad font file format"}, + {58, "EOWNERDEAD", "owner of the lock died"}, + {59, "ENOTRECOVERABLE", "lock is not recoverable"}, + {60, "ENOSTR", "not a stream device"}, + {61, "ENODATA", "no data available"}, + {62, "ETIME", "timer expired"}, + {63, "ENOSR", "out of stream resources"}, + {64, "ENONET", "machine is not on the network"}, + {65, "ENOPKG", "package not installed"}, + {66, "EREMOTE", "object is remote"}, + {67, "ENOLINK", "link has been severed"}, + {68, "EADV", "advertise error"}, + {69, "ESRMNT", "srmount error"}, + {70, "ECOMM", "communication error on send"}, + {71, "EPROTO", "protocol error"}, + {72, "ELOCKUNMAPPED", "locked lock was unmapped "}, + {73, "ENOTACTIVE", "facility is not active"}, + {74, "EMULTIHOP", "multihop attempted"}, + {77, "EBADMSG", "not a data message"}, + {78, "ENAMETOOLONG", "file name too long"}, + {79, "EOVERFLOW", "value too large for defined data type"}, + {80, "ENOTUNIQ", "name not unique on network"}, + {81, "EBADFD", "file descriptor in bad state"}, + {82, "EREMCHG", "remote address changed"}, + {83, "ELIBACC", "can not access a needed shared library"}, + {84, "ELIBBAD", "accessing a corrupted shared library"}, + {85, "ELIBSCN", ".lib section in a.out corrupted"}, + {86, "ELIBMAX", "attempting to link in more shared libraries than system limit"}, + {87, "ELIBEXEC", "can not exec a shared library directly"}, + {88, "EILSEQ", "illegal byte sequence"}, + {89, "ENOSYS", "operation not applicable"}, + {90, "ELOOP", "number of symbolic links encountered during path name traversal exceeds MAXSYMLINKS"}, + {91, "ERESTART", "error 91"}, + {92, "ESTRPIPE", "error 92"}, + {93, "ENOTEMPTY", "directory not empty"}, + {94, "EUSERS", "too many users"}, + {95, "ENOTSOCK", "socket operation on non-socket"}, + {96, "EDESTADDRREQ", "destination address required"}, + {97, "EMSGSIZE", "message too long"}, + {98, "EPROTOTYPE", "protocol wrong type for socket"}, + {99, "ENOPROTOOPT", "option not supported by protocol"}, + {120, "EPROTONOSUPPORT", "protocol not supported"}, + {121, "ESOCKTNOSUPPORT", "socket type not supported"}, + {122, "EOPNOTSUPP", "operation not supported on transport endpoint"}, + {123, "EPFNOSUPPORT", "protocol family not supported"}, + {124, "EAFNOSUPPORT", "address family not supported by protocol family"}, + {125, "EADDRINUSE", "address already in use"}, + {126, "EADDRNOTAVAIL", "cannot assign requested address"}, + {127, "ENETDOWN", "network is down"}, + {128, "ENETUNREACH", "network is unreachable"}, + {129, "ENETRESET", "network dropped connection because of reset"}, + {130, "ECONNABORTED", "software caused connection abort"}, + {131, "ECONNRESET", "connection reset by peer"}, + {132, "ENOBUFS", "no buffer space available"}, + {133, "EISCONN", "transport endpoint is already connected"}, + {134, "ENOTCONN", "transport endpoint is not connected"}, + {143, "ESHUTDOWN", "cannot send after socket shutdown"}, + {144, "ETOOMANYREFS", "too many references: cannot splice"}, + {145, "ETIMEDOUT", "connection timed out"}, + {146, "ECONNREFUSED", "connection refused"}, + {147, "EHOSTDOWN", "host is down"}, + {148, "EHOSTUNREACH", "no route to host"}, + {149, "EALREADY", "operation already in progress"}, + {150, "EINPROGRESS", "operation now in progress"}, + {151, "ESTALE", "stale NFS file handle"}, } // Signal table -var signals = [...]string{ - 1: "hangup", - 2: "interrupt", - 3: "quit", - 4: "illegal Instruction", - 5: "trace/Breakpoint Trap", - 6: "abort", - 7: "emulation Trap", - 8: "arithmetic Exception", - 9: "killed", - 10: "bus Error", - 11: "segmentation Fault", - 12: "bad System Call", - 13: "broken Pipe", - 14: "alarm Clock", - 15: "terminated", - 16: "user Signal 1", - 17: "user Signal 2", - 18: "child Status Changed", - 19: "power-Fail/Restart", - 20: "window Size Change", - 21: "urgent Socket Condition", - 22: "pollable Event", - 23: "stopped (signal)", - 24: "stopped (user)", - 25: "continued", - 26: "stopped (tty input)", - 27: "stopped (tty output)", - 28: "virtual Timer Expired", - 29: "profiling Timer Expired", - 30: "cpu Limit Exceeded", - 31: "file Size Limit Exceeded", - 32: "no runnable lwp", - 33: "inter-lwp signal", - 34: "checkpoint Freeze", - 35: "checkpoint Thaw", - 36: "thread Cancellation", - 37: "resource Lost", - 38: "resource Control Exceeded", - 39: "reserved for JVM 1", - 40: "reserved for JVM 2", - 41: "information Request", +var signalList = [...]struct { + num syscall.Signal + name string + desc string +}{ + {1, "SIGHUP", "hangup"}, + {2, "SIGINT", "interrupt"}, + {3, "SIGQUIT", "quit"}, + {4, "SIGILL", "illegal Instruction"}, + {5, "SIGTRAP", "trace/Breakpoint Trap"}, + {6, "SIGABRT", "abort"}, + {7, "SIGEMT", "emulation Trap"}, + {8, "SIGFPE", "arithmetic Exception"}, + {9, "SIGKILL", "killed"}, + {10, "SIGBUS", "bus Error"}, + {11, "SIGSEGV", "segmentation Fault"}, + {12, "SIGSYS", "bad System Call"}, + {13, "SIGPIPE", "broken Pipe"}, + {14, "SIGALRM", "alarm Clock"}, + {15, "SIGTERM", "terminated"}, + {16, "SIGUSR1", "user Signal 1"}, + {17, "SIGUSR2", "user Signal 2"}, + {18, "SIGCHLD", "child Status Changed"}, + {19, "SIGPWR", "power-Fail/Restart"}, + {20, "SIGWINCH", "window Size Change"}, + {21, "SIGURG", "urgent Socket Condition"}, + {22, "SIGIO", "pollable Event"}, + {23, "SIGSTOP", "stopped (signal)"}, + {24, "SIGTSTP", "stopped (user)"}, + {25, "SIGCONT", "continued"}, + {26, "SIGTTIN", "stopped (tty input)"}, + {27, "SIGTTOU", "stopped (tty output)"}, + {28, "SIGVTALRM", "virtual Timer Expired"}, + {29, "SIGPROF", "profiling Timer Expired"}, + {30, "SIGXCPU", "cpu Limit Exceeded"}, + {31, "SIGXFSZ", "file Size Limit Exceeded"}, + {32, "SIGWAITING", "no runnable lwp"}, + {33, "SIGLWP", "inter-lwp signal"}, + {34, "SIGFREEZE", "checkpoint Freeze"}, + {35, "SIGTHAW", "checkpoint Thaw"}, + {36, "SIGCANCEL", "thread Cancellation"}, + {37, "SIGLOST", "resource Lost"}, + {38, "SIGXRES", "resource Control Exceeded"}, + {39, "SIGJVM1", "reserved for JVM 1"}, + {40, "SIGJVM2", "reserved for JVM 2"}, + {41, "SIGINFO", "information Request"}, } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go index 763ae4fbb9..ac02d4d841 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go @@ -399,6 +399,83 @@ func pipe() (r int, w int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getxattr(path string, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(position), uintptr(options)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func setxattr(path string, attr string, data *byte, size int, position uint32, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(data)), uintptr(size), uintptr(position), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func removexattr(path string, attr string, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func listxattr(path string, dest *byte, size int, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(options), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func kill(pid int, signum int, posix int) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { @@ -693,6 +770,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go index d6808e072d..1dd3cfa0e1 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go @@ -399,6 +399,83 @@ func pipe() (r int, w int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getxattr(path string, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(position), uintptr(options)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func setxattr(path string, attr string, data *byte, size int, position uint32, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(data)), uintptr(size), uintptr(position), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func removexattr(path string, attr string, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func listxattr(path string, dest *byte, size int, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(options), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func kill(pid int, signum int, posix int) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { @@ -693,6 +770,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go index 6ae95e6b9a..cab46e74ba 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go @@ -1,4 +1,4 @@ -// mksyscall.pl -tags darwin,arm syscall_bsd.go syscall_darwin.go syscall_darwin_arm.go +// mksyscall.pl -l32 -tags darwin,arm syscall_bsd.go syscall_darwin.go syscall_darwin_arm.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build darwin,arm @@ -399,6 +399,83 @@ func pipe() (r int, w int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getxattr(path string, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(position), uintptr(options)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func setxattr(path string, attr string, data *byte, size int, position uint32, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(data)), uintptr(size), uintptr(position), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func removexattr(path string, attr string, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func listxattr(path string, dest *byte, size int, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(options), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func kill(pid int, signum int, posix int) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { @@ -693,6 +770,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go index ca6a7ea8b7..13478dd0bc 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go @@ -399,6 +399,83 @@ func pipe() (r int, w int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func getxattr(path string, attr string, dest *byte, size int, position uint32, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(position), uintptr(options)) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func setxattr(path string, attr string, data *byte, size int, position uint32, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(data)), uintptr(size), uintptr(position), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func removexattr(path string, attr string, options int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + var _p1 *byte + _p1, err = BytePtrFromString(attr) + if err != nil { + return + } + _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + +func listxattr(path string, dest *byte, size int, options int) (sz int, err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := Syscall6(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(dest)), uintptr(size), uintptr(options), 0, 0) + sz = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func kill(pid int, signum int, posix int) (err error) { _, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix)) if e1 != 0 { @@ -693,6 +770,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go index 2ed340fd18..91f36e9ec3 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go @@ -423,6 +423,23 @@ func extpwrite(fd int, p []byte, flags int, offset int64) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -601,6 +618,21 @@ func Fchmod(fd int, mode uint32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -642,6 +674,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go index 8bcecfb9b6..a86434a7ba 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go @@ -389,6 +389,23 @@ func pipe() (r int, w int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -907,6 +924,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { @@ -937,6 +969,23 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go index 61c0cf99bb..040e2f760c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go @@ -389,6 +389,23 @@ func pipe() (r int, w int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -907,6 +924,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { @@ -937,6 +969,23 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go index ffd01073c1..cddc5e86b1 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go @@ -389,6 +389,23 @@ func pipe() (r int, w int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -907,6 +924,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { @@ -937,6 +969,23 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getdents(fd int, buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS_GETDENTS, uintptr(fd), uintptr(_p0), uintptr(len(buf))) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go index 85a2907e5d..433becfd02 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_386.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1569,6 +1595,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Ftruncate(fd int, length int64) (err error) { _, _, e1 := Syscall(SYS_FTRUNCATE64, uintptr(fd), uintptr(length), uintptr(length>>32)) if e1 != 0 { @@ -1580,7 +1621,7 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID32, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID32, 0, 0, 0) egid = int(r0) return } @@ -1588,7 +1629,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID32, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID32, 0, 0, 0) euid = int(r0) return } @@ -1596,7 +1637,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID32, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID32, 0, 0, 0) gid = int(r0) return } @@ -1604,7 +1645,7 @@ func Getgid() (gid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID32, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID32, 0, 0, 0) uid = int(r0) return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go index 8e2be97d36..33c02b2695 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1566,6 +1592,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { @@ -1587,7 +1628,7 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } @@ -1595,7 +1636,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } @@ -1603,7 +1644,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) gid = int(r0) return } @@ -1621,7 +1662,7 @@ func Getrlimit(resource int, rlim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) uid = int(r0) return } @@ -1754,17 +1795,6 @@ func Seek(fd int, offset int64, whence int) (off int64, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { - r0, _, e1 := Syscall6(SYS_SELECT, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) - n = int(r0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { r0, _, e1 := Syscall6(SYS_SENDFILE, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) written = int(r0) @@ -1867,21 +1897,6 @@ func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n i // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Stat(path string, stat *Stat_t) (err error) { - var _p0 *byte - _p0, err = BytePtrFromString(path) - if err != nil { - return - } - _, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) - if e1 != 0 { - err = errnoErr(e1) - } - return -} - -// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT - func Statfs(path string, buf *Statfs_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go index 5ff0637fde..f91b56c217 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1728,8 +1754,23 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID32, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID32, 0, 0, 0) egid = int(r0) return } @@ -1737,7 +1778,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID32, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID32, 0, 0, 0) euid = int(r0) return } @@ -1745,7 +1786,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID32, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID32, 0, 0, 0) gid = int(r0) return } @@ -1753,7 +1794,7 @@ func Getgid() (gid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID32, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID32, 0, 0, 0) uid = int(r0) return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go index 40760110f3..52d7595250 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1526,6 +1552,16 @@ func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -1582,7 +1618,7 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } @@ -1590,7 +1626,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } @@ -1598,7 +1634,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) gid = int(r0) return } @@ -1616,7 +1652,7 @@ func Getrlimit(resource int, rlim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) uid = int(r0) return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go index 984e561733..970a5c132d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1519,6 +1545,16 @@ func Dup2(oldfd int, newfd int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall9(SYS_FADVISE64, uintptr(fd), 0, uintptr(offset>>32), uintptr(offset), uintptr(length>>32), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -1540,7 +1576,7 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } @@ -1548,7 +1584,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } @@ -1556,7 +1592,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) gid = int(r0) return } @@ -1564,7 +1600,7 @@ func Getgid() (gid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) uid = int(r0) return } @@ -1722,9 +1758,9 @@ func Shutdown(fd int, how int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { - r0, r1, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) - n = int64(int64(r0)<<32 | int64(r1)) +func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int(r0) if e1 != 0 { err = errnoErr(e1) } @@ -2014,6 +2050,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go index f98194e245..b989d0f282 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1536,6 +1562,16 @@ func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -1546,6 +1582,21 @@ func Fchown(fd int, uid int, gid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { @@ -1567,7 +1618,7 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } @@ -1575,7 +1626,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } @@ -1583,7 +1634,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) gid = int(r0) return } @@ -1601,7 +1652,7 @@ func Getrlimit(resource int, rlim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) uid = int(r0) return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go index f30267019b..1f8d14cacc 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mips64le.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1536,6 +1562,16 @@ func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -1546,6 +1582,21 @@ func Fchown(fd int, uid int, gid int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { @@ -1567,7 +1618,7 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } @@ -1575,7 +1626,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } @@ -1583,7 +1634,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) gid = int(r0) return } @@ -1601,7 +1652,7 @@ func Getrlimit(resource int, rlim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) uid = int(r0) return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go index f18c5e4a76..a9c7e520e4 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1519,6 +1545,16 @@ func Dup2(oldfd int, newfd int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall9(SYS_FADVISE64, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), uintptr(length), uintptr(length>>32), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -1540,7 +1576,7 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } @@ -1548,7 +1584,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } @@ -1556,7 +1592,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) gid = int(r0) return } @@ -1564,7 +1600,7 @@ func Getgid() (gid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) uid = int(r0) return } @@ -1722,9 +1758,9 @@ func Shutdown(fd int, how int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT -func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) { - r0, r1, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) - n = int64(int64(r1)<<32 | int64(r0)) +func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int, err error) { + r0, _, e1 := Syscall6(SYS_SPLICE, uintptr(rfd), uintptr(unsafe.Pointer(roff)), uintptr(wfd), uintptr(unsafe.Pointer(woff)), uintptr(len), uintptr(flags)) + n = int(r0) if e1 != 0 { err = errnoErr(e1) } @@ -2014,6 +2050,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT64, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Stat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go index bc268243cf..3bb9a20992 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1536,6 +1562,16 @@ func Dup2(oldfd int, newfd int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -1556,6 +1592,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { @@ -1577,7 +1628,7 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } @@ -1585,7 +1636,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } @@ -1593,7 +1644,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) gid = int(r0) return } @@ -1611,7 +1662,7 @@ func Getrlimit(resource int, rlim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) uid = int(r0) return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go index 8d874cbcdc..56116623d6 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1536,6 +1562,16 @@ func Dup2(oldfd int, newfd int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -1556,6 +1592,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { @@ -1577,7 +1628,7 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } @@ -1585,7 +1636,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } @@ -1593,7 +1644,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) gid = int(r0) return } @@ -1611,7 +1662,7 @@ func Getrlimit(resource int, rlim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) uid = int(r0) return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go index 169321273d..9696a0199d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_s390x.go @@ -538,7 +538,7 @@ func Eventfd(initval uint, flags int) (fd int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Exit(code int) { - Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) + SyscallNoError(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } @@ -674,7 +674,7 @@ func Getpgid(pid int) (pgid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { - r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPID, 0, 0, 0) pid = int(r0) return } @@ -682,7 +682,7 @@ func Getpid() (pid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { - r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } @@ -739,7 +739,7 @@ func Getsid(pid int) (sid int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { - r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETTID, 0, 0, 0) tid = int(r0) return } @@ -995,6 +995,17 @@ func Nanosleep(time *Timespec, leftover *Timespec) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func PerfEventOpen(attr *PerfEventAttr, pid int, cpu int, groupFd int, flags int) (fd int, err error) { + r0, _, e1 := Syscall6(SYS_PERF_EVENT_OPEN, uintptr(unsafe.Pointer(attr)), uintptr(pid), uintptr(cpu), uintptr(groupFd), uintptr(flags), 0) + fd = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) @@ -1238,8 +1249,23 @@ func Setxattr(path string, attr string, data []byte, flags int) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Statx(dirfd int, path string, flags int, mask int, stat *Statx_t) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_STATX, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mask), uintptr(unsafe.Pointer(stat)), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Sync() { - Syscall(SYS_SYNC, 0, 0, 0) + SyscallNoError(SYS_SYNC, 0, 0, 0) return } @@ -1298,7 +1324,7 @@ func Times(tms *Tms) (ticks uintptr, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { - r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) + r0, _ := RawSyscallNoError(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } @@ -1566,6 +1592,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(dirfd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_NEWFSTATAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, buf *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(buf)), 0) if e1 != 0 { @@ -1587,7 +1628,7 @@ func Ftruncate(fd int, length int64) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getegid() (egid int) { - r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEGID, 0, 0, 0) egid = int(r0) return } @@ -1595,7 +1636,7 @@ func Getegid() (egid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Geteuid() (euid int) { - r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETEUID, 0, 0, 0) euid = int(r0) return } @@ -1603,7 +1644,7 @@ func Geteuid() (euid int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getgid() (gid int) { - r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETGID, 0, 0, 0) gid = int(r0) return } @@ -1621,7 +1662,7 @@ func Getrlimit(resource int, rlim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getuid() (uid int) { - r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0) + r0, _ := RawSyscallNoError(SYS_GETUID, 0, 0, 0) uid = int(r0) return } diff --git a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go index 2dd98434ea..c01b3b6bab 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_linux_sparc64.go @@ -1222,6 +1222,16 @@ func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_FADVISE64, uintptr(fd), uintptr(offset), uintptr(length), uintptr(advice), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go index 04a1ace9d0..fb4b962782 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go @@ -406,6 +406,23 @@ func getdents(fd int, buf []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -554,6 +571,16 @@ func Exit(code int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall9(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), 0, uintptr(length), uintptr(length>>32), uintptr(advice), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { @@ -584,6 +611,21 @@ func Fchmod(fd int, mode uint32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -625,6 +667,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go index 079824a71a..beac82ef86 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go @@ -406,6 +406,23 @@ func getdents(fd int, buf []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -554,6 +571,16 @@ func Exit(code int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall6(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), 0, uintptr(length), uintptr(advice)) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { @@ -584,6 +611,21 @@ func Fchmod(fd int, mode uint32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -625,6 +667,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go index 05f8b496a8..7bd5f60b00 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go @@ -406,6 +406,23 @@ func getdents(fd int, buf []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -554,6 +571,16 @@ func Exit(code int) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fadvise(fd int, offset int64, length int64, advice int) (err error) { + _, _, e1 := Syscall9(SYS_POSIX_FADVISE, uintptr(fd), 0, uintptr(offset), uintptr(offset>>32), 0, uintptr(length), uintptr(length>>32), uintptr(advice), 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { @@ -584,6 +611,21 @@ func Fchmod(fd int, mode uint32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -625,6 +667,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go index 3b55544df7..49b3b5e8a4 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go @@ -404,6 +404,23 @@ func getdents(fd int, buf []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -582,6 +599,21 @@ func Fchmod(fd int, mode uint32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -623,6 +655,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { @@ -733,6 +780,17 @@ func Getrlimit(which int, lim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getrtable() (rtable int, err error) { + r0, _, e1 := RawSyscall(SYS_GETRTABLE, 0, 0, 0) + rtable = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { @@ -1207,6 +1265,16 @@ func Setrlimit(which int, lim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Setrtable(rtable int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRTABLE, uintptr(rtable), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go index cdaf4ef4c1..c4c7d8540c 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go @@ -404,6 +404,23 @@ func getdents(fd int, buf []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -582,6 +599,21 @@ func Fchmod(fd int, mode uint32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -623,6 +655,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { @@ -733,6 +780,17 @@ func Getrlimit(which int, lim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getrtable() (rtable int, err error) { + r0, _, e1 := RawSyscall(SYS_GETRTABLE, 0, 0, 0) + rtable = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { @@ -1207,6 +1265,16 @@ func Setrlimit(which int, lim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Setrtable(rtable int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRTABLE, uintptr(rtable), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go index 6c4dc8a9fb..210285b0ba 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_openbsd_arm.go @@ -404,6 +404,23 @@ func getdents(fd int, buf []byte) (n int, err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getcwd(buf []byte) (n int, err error) { + var _p0 unsafe.Pointer + if len(buf) > 0 { + _p0 = unsafe.Pointer(&buf[0]) + } else { + _p0 = unsafe.Pointer(&_zero) + } + r0, _, e1 := Syscall(SYS___GETCWD, uintptr(_p0), uintptr(len(buf)), 0) + n = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func ioctl(fd int, req uint, arg uintptr) (err error) { _, _, e1 := Syscall(SYS_IOCTL, uintptr(fd), uintptr(req), uintptr(arg)) if e1 != 0 { @@ -582,6 +599,21 @@ func Fchmod(fd int, mode uint32) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fchown(fd int, uid int, gid int) (err error) { _, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid)) if e1 != 0 { @@ -623,6 +655,21 @@ func Fstat(fd int, stat *Stat_t) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := Syscall6(SYS_FSTATAT, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Fstatfs(fd int, stat *Statfs_t) (err error) { _, _, e1 := Syscall(SYS_FSTATFS, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0) if e1 != 0 { @@ -733,6 +780,17 @@ func Getrlimit(which int, lim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Getrtable() (rtable int, err error) { + r0, _, e1 := RawSyscall(SYS_GETRTABLE, 0, 0, 0) + rtable = int(r0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { @@ -1207,6 +1265,16 @@ func Setrlimit(which int, lim *Rlimit) (err error) { // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT +func Setrtable(rtable int) (err error) { + _, _, e1 := RawSyscall(SYS_SETRTABLE, uintptr(rtable), 0, 0) + if e1 != 0 { + err = errnoErr(e1) + } + return +} + +// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT + func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) diff --git a/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go b/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go index 1d45276498..397896300d 100644 --- a/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go @@ -50,6 +50,7 @@ import ( //go:cgo_import_dynamic libc_flock flock "libc.so" //go:cgo_import_dynamic libc_fpathconf fpathconf "libc.so" //go:cgo_import_dynamic libc_fstat fstat "libc.so" +//go:cgo_import_dynamic libc_fstatat fstatat "libc.so" //go:cgo_import_dynamic libc_fstatvfs fstatvfs "libc.so" //go:cgo_import_dynamic libc_getdents getdents "libc.so" //go:cgo_import_dynamic libc_getgid getgid "libc.so" @@ -95,6 +96,7 @@ import ( //go:cgo_import_dynamic libc_renameat renameat "libc.so" //go:cgo_import_dynamic libc_rmdir rmdir "libc.so" //go:cgo_import_dynamic libc_lseek lseek "libc.so" +//go:cgo_import_dynamic libc_select select "libc.so" //go:cgo_import_dynamic libc_setegid setegid "libc.so" //go:cgo_import_dynamic libc_seteuid seteuid "libc.so" //go:cgo_import_dynamic libc_setgid setgid "libc.so" @@ -126,6 +128,7 @@ import ( //go:cgo_import_dynamic libc___xnet_connect __xnet_connect "libsocket.so" //go:cgo_import_dynamic libc_mmap mmap "libc.so" //go:cgo_import_dynamic libc_munmap munmap "libc.so" +//go:cgo_import_dynamic libc_sendfile sendfile "libsendfile.so" //go:cgo_import_dynamic libc___xnet_sendto __xnet_sendto "libsocket.so" //go:cgo_import_dynamic libc___xnet_socket __xnet_socket "libsocket.so" //go:cgo_import_dynamic libc___xnet_socketpair __xnet_socketpair "libsocket.so" @@ -175,6 +178,7 @@ import ( //go:linkname procFlock libc_flock //go:linkname procFpathconf libc_fpathconf //go:linkname procFstat libc_fstat +//go:linkname procFstatat libc_fstatat //go:linkname procFstatvfs libc_fstatvfs //go:linkname procGetdents libc_getdents //go:linkname procGetgid libc_getgid @@ -220,6 +224,7 @@ import ( //go:linkname procRenameat libc_renameat //go:linkname procRmdir libc_rmdir //go:linkname proclseek libc_lseek +//go:linkname procSelect libc_select //go:linkname procSetegid libc_setegid //go:linkname procSeteuid libc_seteuid //go:linkname procSetgid libc_setgid @@ -251,6 +256,7 @@ import ( //go:linkname proc__xnet_connect libc___xnet_connect //go:linkname procmmap libc_mmap //go:linkname procmunmap libc_munmap +//go:linkname procsendfile libc_sendfile //go:linkname proc__xnet_sendto libc___xnet_sendto //go:linkname proc__xnet_socket libc___xnet_socket //go:linkname proc__xnet_socketpair libc___xnet_socketpair @@ -301,6 +307,7 @@ var ( procFlock, procFpathconf, procFstat, + procFstatat, procFstatvfs, procGetdents, procGetgid, @@ -346,6 +353,7 @@ var ( procRenameat, procRmdir, proclseek, + procSelect, procSetegid, procSeteuid, procSetgid, @@ -377,6 +385,7 @@ var ( proc__xnet_connect, procmmap, procmunmap, + procsendfile, proc__xnet_sendto, proc__xnet_socket, proc__xnet_socketpair, @@ -769,6 +778,19 @@ func Fstat(fd int, stat *Stat_t) (err error) { return } +func Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) { + var _p0 *byte + _p0, err = BytePtrFromString(path) + if err != nil { + return + } + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstatat)), 4, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), uintptr(flags), 0, 0) + if e1 != 0 { + err = e1 + } + return +} + func Fstatvfs(fd int, vfsstat *Statvfs_t) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procFstatvfs)), 2, uintptr(fd), uintptr(unsafe.Pointer(vfsstat)), 0, 0, 0, 0) if e1 != 0 { @@ -1264,6 +1286,14 @@ func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { return } +func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) { + _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procSelect)), 5, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0) + if e1 != 0 { + err = e1 + } + return +} + func Setegid(egid int) (err error) { _, _, e1 := rawSysvicall6(uintptr(unsafe.Pointer(&procSetegid)), 1, uintptr(egid), 0, 0, 0, 0, 0) if e1 != 0 { @@ -1562,6 +1592,15 @@ func munmap(addr uintptr, length uintptr) (err error) { return } +func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) { + r0, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procsendfile)), 4, uintptr(outfd), uintptr(infd), uintptr(unsafe.Pointer(offset)), uintptr(count), 0, 0) + written = int(r0) + if e1 != 0 { + err = e1 + } + return +} + func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 *byte if len(buf) > 0 { diff --git a/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go index 83bb935b91..207b27938b 100644 --- a/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsysctl_openbsd_amd64.go @@ -1,6 +1,8 @@ // mksysctl_openbsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT +// +build amd64,openbsd + package unix type mibentry struct { @@ -14,6 +16,7 @@ var sysctlMib = []mibentry{ {"ddb.max_line", []_C_int{9, 3}}, {"ddb.max_width", []_C_int{9, 2}}, {"ddb.panic", []_C_int{9, 5}}, + {"ddb.profile", []_C_int{9, 9}}, {"ddb.radix", []_C_int{9, 1}}, {"ddb.tab_stop_width", []_C_int{9, 4}}, {"ddb.trigger", []_C_int{9, 8}}, @@ -29,6 +32,7 @@ var sysctlMib = []mibentry{ {"hw.ncpu", []_C_int{6, 3}}, {"hw.ncpufound", []_C_int{6, 21}}, {"hw.pagesize", []_C_int{6, 7}}, + {"hw.perfpolicy", []_C_int{6, 23}}, {"hw.physmem", []_C_int{6, 19}}, {"hw.product", []_C_int{6, 15}}, {"hw.serialno", []_C_int{6, 17}}, @@ -37,7 +41,7 @@ var sysctlMib = []mibentry{ {"hw.uuid", []_C_int{6, 18}}, {"hw.vendor", []_C_int{6, 14}}, {"hw.version", []_C_int{6, 16}}, - {"kern.arandom", []_C_int{1, 37}}, + {"kern.allowkmem", []_C_int{1, 52}}, {"kern.argmax", []_C_int{1, 8}}, {"kern.boottime", []_C_int{1, 21}}, {"kern.bufcachepercent", []_C_int{1, 72}}, @@ -46,12 +50,13 @@ var sysctlMib = []mibentry{ {"kern.consdev", []_C_int{1, 75}}, {"kern.cp_time", []_C_int{1, 40}}, {"kern.cp_time2", []_C_int{1, 71}}, - {"kern.cryptodevallowsoft", []_C_int{1, 53}}, + {"kern.dnsjackport", []_C_int{1, 13}}, {"kern.domainname", []_C_int{1, 22}}, {"kern.file", []_C_int{1, 73}}, {"kern.forkstat", []_C_int{1, 42}}, {"kern.fscale", []_C_int{1, 46}}, {"kern.fsync", []_C_int{1, 33}}, + {"kern.global_ptrace", []_C_int{1, 81}}, {"kern.hostid", []_C_int{1, 11}}, {"kern.hostname", []_C_int{1, 10}}, {"kern.intrcnt.nintrcnt", []_C_int{1, 63, 1}}, @@ -84,7 +89,6 @@ var sysctlMib = []mibentry{ {"kern.pool_debug", []_C_int{1, 77}}, {"kern.posix1version", []_C_int{1, 17}}, {"kern.proc", []_C_int{1, 66}}, - {"kern.random", []_C_int{1, 31}}, {"kern.rawpartition", []_C_int{1, 24}}, {"kern.saved_ids", []_C_int{1, 20}}, {"kern.securelevel", []_C_int{1, 9}}, @@ -102,21 +106,16 @@ var sysctlMib = []mibentry{ {"kern.timecounter.hardware", []_C_int{1, 69, 3}}, {"kern.timecounter.tick", []_C_int{1, 69, 1}}, {"kern.timecounter.timestepwarnings", []_C_int{1, 69, 2}}, - {"kern.tty.maxptys", []_C_int{1, 44, 6}}, - {"kern.tty.nptys", []_C_int{1, 44, 7}}, {"kern.tty.tk_cancc", []_C_int{1, 44, 4}}, {"kern.tty.tk_nin", []_C_int{1, 44, 1}}, {"kern.tty.tk_nout", []_C_int{1, 44, 2}}, {"kern.tty.tk_rawcc", []_C_int{1, 44, 3}}, {"kern.tty.ttyinfo", []_C_int{1, 44, 5}}, {"kern.ttycount", []_C_int{1, 57}}, - {"kern.userasymcrypto", []_C_int{1, 60}}, - {"kern.usercrypto", []_C_int{1, 52}}, - {"kern.usermount", []_C_int{1, 30}}, {"kern.version", []_C_int{1, 4}}, - {"kern.vnode", []_C_int{1, 13}}, {"kern.watchdog.auto", []_C_int{1, 64, 2}}, {"kern.watchdog.period", []_C_int{1, 64, 1}}, + {"kern.wxabort", []_C_int{1, 74}}, {"net.bpf.bufsize", []_C_int{4, 31, 1}}, {"net.bpf.maxbufsize", []_C_int{4, 31, 2}}, {"net.inet.ah.enable", []_C_int{4, 2, 51, 1}}, @@ -144,7 +143,9 @@ var sysctlMib = []mibentry{ {"net.inet.icmp.stats", []_C_int{4, 2, 1, 7}}, {"net.inet.icmp.tstamprepl", []_C_int{4, 2, 1, 6}}, {"net.inet.igmp.stats", []_C_int{4, 2, 2, 1}}, + {"net.inet.ip.arpdown", []_C_int{4, 2, 0, 40}}, {"net.inet.ip.arpqueued", []_C_int{4, 2, 0, 36}}, + {"net.inet.ip.arptimeout", []_C_int{4, 2, 0, 39}}, {"net.inet.ip.encdebug", []_C_int{4, 2, 0, 12}}, {"net.inet.ip.forwarding", []_C_int{4, 2, 0, 1}}, {"net.inet.ip.ifq.congestion", []_C_int{4, 2, 0, 30, 4}}, @@ -153,8 +154,10 @@ var sysctlMib = []mibentry{ {"net.inet.ip.ifq.maxlen", []_C_int{4, 2, 0, 30, 2}}, {"net.inet.ip.maxqueue", []_C_int{4, 2, 0, 11}}, {"net.inet.ip.mforwarding", []_C_int{4, 2, 0, 31}}, + {"net.inet.ip.mrtmfc", []_C_int{4, 2, 0, 37}}, {"net.inet.ip.mrtproto", []_C_int{4, 2, 0, 34}}, {"net.inet.ip.mrtstats", []_C_int{4, 2, 0, 35}}, + {"net.inet.ip.mrtvif", []_C_int{4, 2, 0, 38}}, {"net.inet.ip.mtu", []_C_int{4, 2, 0, 4}}, {"net.inet.ip.mtudisc", []_C_int{4, 2, 0, 27}}, {"net.inet.ip.mtudisctimeout", []_C_int{4, 2, 0, 28}}, @@ -173,7 +176,6 @@ var sysctlMib = []mibentry{ {"net.inet.ipip.stats", []_C_int{4, 2, 4, 2}}, {"net.inet.mobileip.allow", []_C_int{4, 2, 55, 1}}, {"net.inet.pfsync.stats", []_C_int{4, 2, 240, 1}}, - {"net.inet.pim.stats", []_C_int{4, 2, 103, 1}}, {"net.inet.tcp.ackonpush", []_C_int{4, 2, 6, 13}}, {"net.inet.tcp.always_keepalive", []_C_int{4, 2, 6, 22}}, {"net.inet.tcp.baddynamic", []_C_int{4, 2, 6, 6}}, @@ -187,6 +189,7 @@ var sysctlMib = []mibentry{ {"net.inet.tcp.reasslimit", []_C_int{4, 2, 6, 18}}, {"net.inet.tcp.rfc1323", []_C_int{4, 2, 6, 1}}, {"net.inet.tcp.rfc3390", []_C_int{4, 2, 6, 17}}, + {"net.inet.tcp.rootonly", []_C_int{4, 2, 6, 24}}, {"net.inet.tcp.rstppslimit", []_C_int{4, 2, 6, 12}}, {"net.inet.tcp.sack", []_C_int{4, 2, 6, 10}}, {"net.inet.tcp.sackholelimit", []_C_int{4, 2, 6, 20}}, @@ -194,9 +197,12 @@ var sysctlMib = []mibentry{ {"net.inet.tcp.stats", []_C_int{4, 2, 6, 21}}, {"net.inet.tcp.synbucketlimit", []_C_int{4, 2, 6, 16}}, {"net.inet.tcp.syncachelimit", []_C_int{4, 2, 6, 15}}, + {"net.inet.tcp.synhashsize", []_C_int{4, 2, 6, 25}}, + {"net.inet.tcp.synuselimit", []_C_int{4, 2, 6, 23}}, {"net.inet.udp.baddynamic", []_C_int{4, 2, 17, 2}}, {"net.inet.udp.checksum", []_C_int{4, 2, 17, 1}}, {"net.inet.udp.recvspace", []_C_int{4, 2, 17, 3}}, + {"net.inet.udp.rootonly", []_C_int{4, 2, 17, 6}}, {"net.inet.udp.sendspace", []_C_int{4, 2, 17, 4}}, {"net.inet.udp.stats", []_C_int{4, 2, 17, 5}}, {"net.inet6.divert.recvspace", []_C_int{4, 24, 86, 1}}, @@ -209,13 +215,8 @@ var sysctlMib = []mibentry{ {"net.inet6.icmp6.nd6_delay", []_C_int{4, 24, 30, 8}}, {"net.inet6.icmp6.nd6_maxnudhint", []_C_int{4, 24, 30, 15}}, {"net.inet6.icmp6.nd6_mmaxtries", []_C_int{4, 24, 30, 10}}, - {"net.inet6.icmp6.nd6_prune", []_C_int{4, 24, 30, 6}}, {"net.inet6.icmp6.nd6_umaxtries", []_C_int{4, 24, 30, 9}}, - {"net.inet6.icmp6.nd6_useloopback", []_C_int{4, 24, 30, 11}}, - {"net.inet6.icmp6.nodeinfo", []_C_int{4, 24, 30, 13}}, - {"net.inet6.icmp6.rediraccept", []_C_int{4, 24, 30, 2}}, {"net.inet6.icmp6.redirtimeout", []_C_int{4, 24, 30, 3}}, - {"net.inet6.ip6.accept_rtadv", []_C_int{4, 24, 17, 12}}, {"net.inet6.ip6.auto_flowlabel", []_C_int{4, 24, 17, 17}}, {"net.inet6.ip6.dad_count", []_C_int{4, 24, 17, 16}}, {"net.inet6.ip6.dad_pending", []_C_int{4, 24, 17, 49}}, @@ -228,20 +229,19 @@ var sysctlMib = []mibentry{ {"net.inet6.ip6.maxdynroutes", []_C_int{4, 24, 17, 48}}, {"net.inet6.ip6.maxfragpackets", []_C_int{4, 24, 17, 9}}, {"net.inet6.ip6.maxfrags", []_C_int{4, 24, 17, 41}}, - {"net.inet6.ip6.maxifdefrouters", []_C_int{4, 24, 17, 47}}, - {"net.inet6.ip6.maxifprefixes", []_C_int{4, 24, 17, 46}}, {"net.inet6.ip6.mforwarding", []_C_int{4, 24, 17, 42}}, + {"net.inet6.ip6.mrtmfc", []_C_int{4, 24, 17, 53}}, + {"net.inet6.ip6.mrtmif", []_C_int{4, 24, 17, 52}}, {"net.inet6.ip6.mrtproto", []_C_int{4, 24, 17, 8}}, {"net.inet6.ip6.mtudisctimeout", []_C_int{4, 24, 17, 50}}, {"net.inet6.ip6.multicast_mtudisc", []_C_int{4, 24, 17, 44}}, {"net.inet6.ip6.multipath", []_C_int{4, 24, 17, 43}}, {"net.inet6.ip6.neighborgcthresh", []_C_int{4, 24, 17, 45}}, {"net.inet6.ip6.redirect", []_C_int{4, 24, 17, 2}}, - {"net.inet6.ip6.rr_prune", []_C_int{4, 24, 17, 22}}, + {"net.inet6.ip6.soiikey", []_C_int{4, 24, 17, 54}}, {"net.inet6.ip6.sourcecheck", []_C_int{4, 24, 17, 10}}, {"net.inet6.ip6.sourcecheck_logint", []_C_int{4, 24, 17, 11}}, {"net.inet6.ip6.use_deprecated", []_C_int{4, 24, 17, 21}}, - {"net.inet6.ip6.v6only", []_C_int{4, 24, 17, 24}}, {"net.key.sadb_dump", []_C_int{4, 30, 1}}, {"net.key.spd_dump", []_C_int{4, 30, 2}}, {"net.mpls.ifq.congestion", []_C_int{4, 33, 3, 4}}, @@ -254,17 +254,4 @@ var sysctlMib = []mibentry{ {"net.mpls.ttl", []_C_int{4, 33, 2}}, {"net.pflow.stats", []_C_int{4, 34, 1}}, {"net.pipex.enable", []_C_int{4, 35, 1}}, - {"vm.anonmin", []_C_int{2, 7}}, - {"vm.loadavg", []_C_int{2, 2}}, - {"vm.maxslp", []_C_int{2, 10}}, - {"vm.nkmempages", []_C_int{2, 6}}, - {"vm.psstrings", []_C_int{2, 3}}, - {"vm.swapencrypt.enable", []_C_int{2, 5, 0}}, - {"vm.swapencrypt.keyscreated", []_C_int{2, 5, 1}}, - {"vm.swapencrypt.keysdeleted", []_C_int{2, 5, 2}}, - {"vm.uspace", []_C_int{2, 11}}, - {"vm.uvmexp", []_C_int{2, 4}}, - {"vm.vmmeter", []_C_int{2, 1}}, - {"vm.vnodemin", []_C_int{2, 9}}, - {"vm.vtextmin", []_C_int{2, 8}}, } diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go index dfe5dab67e..384d49bfa5 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go @@ -367,4 +367,7 @@ const ( SYS_PWRITEV2 = 381 SYS_KEXEC_FILE_LOAD = 382 SYS_STATX = 383 + SYS_PKEY_ALLOC = 384 + SYS_PKEY_FREE = 385 + SYS_PKEY_MPROTECT = 386 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go index eca97f738b..9623248a5e 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go @@ -367,4 +367,7 @@ const ( SYS_PWRITEV2 = 381 SYS_KEXEC_FILE_LOAD = 382 SYS_STATX = 383 + SYS_PKEY_ALLOC = 384 + SYS_PKEY_FREE = 385 + SYS_PKEY_MPROTECT = 386 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go index 8ea18e6c25..ed92409d97 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_linux_s390x.go @@ -109,6 +109,7 @@ const ( SYS_PERSONALITY = 136 SYS_AFS_SYSCALL = 137 SYS_GETDENTS = 141 + SYS_SELECT = 142 SYS_FLOCK = 143 SYS_MSYNC = 144 SYS_READV = 145 @@ -151,6 +152,26 @@ const ( SYS_GETPMSG = 188 SYS_PUTPMSG = 189 SYS_VFORK = 190 + SYS_GETRLIMIT = 191 + SYS_LCHOWN = 198 + SYS_GETUID = 199 + SYS_GETGID = 200 + SYS_GETEUID = 201 + SYS_GETEGID = 202 + SYS_SETREUID = 203 + SYS_SETREGID = 204 + SYS_GETGROUPS = 205 + SYS_SETGROUPS = 206 + SYS_FCHOWN = 207 + SYS_SETRESUID = 208 + SYS_GETRESUID = 209 + SYS_SETRESGID = 210 + SYS_GETRESGID = 211 + SYS_CHOWN = 212 + SYS_SETUID = 213 + SYS_SETGID = 214 + SYS_SETFSUID = 215 + SYS_SETFSGID = 216 SYS_PIVOT_ROOT = 217 SYS_MINCORE = 218 SYS_MADVISE = 219 @@ -222,6 +243,7 @@ const ( SYS_MKNODAT = 290 SYS_FCHOWNAT = 291 SYS_FUTIMESAT = 292 + SYS_NEWFSTATAT = 293 SYS_UNLINKAT = 294 SYS_RENAMEAT = 295 SYS_LINKAT = 296 @@ -308,26 +330,5 @@ const ( SYS_PWRITEV2 = 377 SYS_S390_GUARDED_STORAGE = 378 SYS_STATX = 379 - SYS_SELECT = 142 - SYS_GETRLIMIT = 191 - SYS_LCHOWN = 198 - SYS_GETUID = 199 - SYS_GETGID = 200 - SYS_GETEUID = 201 - SYS_GETEGID = 202 - SYS_SETREUID = 203 - SYS_SETREGID = 204 - SYS_GETGROUPS = 205 - SYS_SETGROUPS = 206 - SYS_FCHOWN = 207 - SYS_SETRESUID = 208 - SYS_GETRESUID = 209 - SYS_SETRESGID = 210 - SYS_GETRESGID = 211 - SYS_CHOWN = 212 - SYS_SETUID = 213 - SYS_SETGID = 214 - SYS_SETFSUID = 215 - SYS_SETFSGID = 216 - SYS_NEWFSTATAT = 293 + SYS_S390_STHYI = 380 ) diff --git a/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go index bd28146ddd..10edff07d5 100644 --- a/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go @@ -1,5 +1,5 @@ // mksysnum_openbsd.pl -// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT +// Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,openbsd @@ -12,6 +12,7 @@ const ( SYS_WRITE = 4 // { ssize_t sys_write(int fd, const void *buf, \ SYS_OPEN = 5 // { int sys_open(const char *path, \ SYS_CLOSE = 6 // { int sys_close(int fd); } + SYS_GETENTROPY = 7 // { int sys_getentropy(void *buf, size_t nbyte); } SYS___TFORK = 8 // { int sys___tfork(const struct __tfork *param, \ SYS_LINK = 9 // { int sys_link(const char *path, const char *link); } SYS_UNLINK = 10 // { int sys_unlink(const char *path); } @@ -37,11 +38,10 @@ const ( SYS_ACCEPT = 30 // { int sys_accept(int s, struct sockaddr *name, \ SYS_GETPEERNAME = 31 // { int sys_getpeername(int fdes, struct sockaddr *asa, \ SYS_GETSOCKNAME = 32 // { int sys_getsockname(int fdes, struct sockaddr *asa, \ - SYS_ACCESS = 33 // { int sys_access(const char *path, int flags); } + SYS_ACCESS = 33 // { int sys_access(const char *path, int amode); } SYS_CHFLAGS = 34 // { int sys_chflags(const char *path, u_int flags); } SYS_FCHFLAGS = 35 // { int sys_fchflags(int fd, u_int flags); } SYS_SYNC = 36 // { void sys_sync(void); } - SYS_KILL = 37 // { int sys_kill(int pid, int signum); } SYS_STAT = 38 // { int sys_stat(const char *path, struct stat *ub); } SYS_GETPPID = 39 // { pid_t sys_getppid(void); } SYS_LSTAT = 40 // { int sys_lstat(const char *path, struct stat *ub); } @@ -53,7 +53,6 @@ const ( SYS_SIGACTION = 46 // { int sys_sigaction(int signum, \ SYS_GETGID = 47 // { gid_t sys_getgid(void); } SYS_SIGPROCMASK = 48 // { int sys_sigprocmask(int how, sigset_t mask); } - SYS_GETLOGIN = 49 // { int sys_getlogin(char *namebuf, u_int namelen); } SYS_SETLOGIN = 50 // { int sys_setlogin(const char *namebuf); } SYS_ACCT = 51 // { int sys_acct(const char *path); } SYS_SIGPENDING = 52 // { int sys_sigpending(void); } @@ -62,7 +61,7 @@ const ( SYS_REBOOT = 55 // { int sys_reboot(int opt); } SYS_REVOKE = 56 // { int sys_revoke(const char *path); } SYS_SYMLINK = 57 // { int sys_symlink(const char *path, \ - SYS_READLINK = 58 // { int sys_readlink(const char *path, char *buf, \ + SYS_READLINK = 58 // { ssize_t sys_readlink(const char *path, \ SYS_EXECVE = 59 // { int sys_execve(const char *path, \ SYS_UMASK = 60 // { mode_t sys_umask(mode_t newmask); } SYS_CHROOT = 61 // { int sys_chroot(const char *path); } @@ -86,15 +85,18 @@ const ( SYS_GETGROUPS = 79 // { int sys_getgroups(int gidsetsize, \ SYS_SETGROUPS = 80 // { int sys_setgroups(int gidsetsize, \ SYS_GETPGRP = 81 // { int sys_getpgrp(void); } - SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, int pgid); } + SYS_SETPGID = 82 // { int sys_setpgid(pid_t pid, pid_t pgid); } + SYS_FUTEX = 83 // { int sys_futex(uint32_t *f, int op, int val, \ SYS_UTIMENSAT = 84 // { int sys_utimensat(int fd, const char *path, \ SYS_FUTIMENS = 85 // { int sys_futimens(int fd, \ + SYS_KBIND = 86 // { int sys_kbind(const struct __kbind *param, \ SYS_CLOCK_GETTIME = 87 // { int sys_clock_gettime(clockid_t clock_id, \ SYS_CLOCK_SETTIME = 88 // { int sys_clock_settime(clockid_t clock_id, \ SYS_CLOCK_GETRES = 89 // { int sys_clock_getres(clockid_t clock_id, \ SYS_DUP2 = 90 // { int sys_dup2(int from, int to); } SYS_NANOSLEEP = 91 // { int sys_nanosleep(const struct timespec *rqtp, \ SYS_FCNTL = 92 // { int sys_fcntl(int fd, int cmd, ... void *arg); } + SYS_ACCEPT4 = 93 // { int sys_accept4(int s, struct sockaddr *name, \ SYS___THRSLEEP = 94 // { int sys___thrsleep(const volatile void *ident, \ SYS_FSYNC = 95 // { int sys_fsync(int fd); } SYS_SETPRIORITY = 96 // { int sys_setpriority(int which, id_t who, int prio); } @@ -102,16 +104,23 @@ const ( SYS_CONNECT = 98 // { int sys_connect(int s, const struct sockaddr *name, \ SYS_GETDENTS = 99 // { int sys_getdents(int fd, void *buf, size_t buflen); } SYS_GETPRIORITY = 100 // { int sys_getpriority(int which, id_t who); } + SYS_PIPE2 = 101 // { int sys_pipe2(int *fdp, int flags); } + SYS_DUP3 = 102 // { int sys_dup3(int from, int to, int flags); } SYS_SIGRETURN = 103 // { int sys_sigreturn(struct sigcontext *sigcntxp); } SYS_BIND = 104 // { int sys_bind(int s, const struct sockaddr *name, \ SYS_SETSOCKOPT = 105 // { int sys_setsockopt(int s, int level, int name, \ SYS_LISTEN = 106 // { int sys_listen(int s, int backlog); } + SYS_CHFLAGSAT = 107 // { int sys_chflagsat(int fd, const char *path, \ + SYS_PLEDGE = 108 // { int sys_pledge(const char *promises, \ SYS_PPOLL = 109 // { int sys_ppoll(struct pollfd *fds, \ SYS_PSELECT = 110 // { int sys_pselect(int nd, fd_set *in, fd_set *ou, \ SYS_SIGSUSPEND = 111 // { int sys_sigsuspend(int mask); } + SYS_SENDSYSLOG = 112 // { int sys_sendsyslog(const char *buf, size_t nbyte, \ SYS_GETSOCKOPT = 118 // { int sys_getsockopt(int s, int level, int name, \ + SYS_THRKILL = 119 // { int sys_thrkill(pid_t tid, int signum, void *tcb); } SYS_READV = 120 // { ssize_t sys_readv(int fd, \ SYS_WRITEV = 121 // { ssize_t sys_writev(int fd, \ + SYS_KILL = 122 // { int sys_kill(int pid, int signum); } SYS_FCHOWN = 123 // { int sys_fchown(int fd, uid_t uid, gid_t gid); } SYS_FCHMOD = 124 // { int sys_fchmod(int fd, mode_t mode); } SYS_SETREUID = 126 // { int sys_setreuid(uid_t ruid, uid_t euid); } @@ -125,6 +134,7 @@ const ( SYS_MKDIR = 136 // { int sys_mkdir(const char *path, mode_t mode); } SYS_RMDIR = 137 // { int sys_rmdir(const char *path); } SYS_ADJTIME = 140 // { int sys_adjtime(const struct timeval *delta, \ + SYS_GETLOGIN_R = 141 // { int sys_getlogin_r(char *namebuf, u_int namelen); } SYS_SETSID = 147 // { int sys_setsid(void); } SYS_QUOTACTL = 148 // { int sys_quotactl(const char *path, int cmd, \ SYS_NFSSVC = 155 // { int sys_nfssvc(int flag, void *argp); } @@ -144,7 +154,7 @@ const ( SYS_LSEEK = 199 // { off_t sys_lseek(int fd, int pad, off_t offset, \ SYS_TRUNCATE = 200 // { int sys_truncate(const char *path, int pad, \ SYS_FTRUNCATE = 201 // { int sys_ftruncate(int fd, int pad, off_t length); } - SYS___SYSCTL = 202 // { int sys___sysctl(const int *name, u_int namelen, \ + SYS_SYSCTL = 202 // { int sys_sysctl(const int *name, u_int namelen, \ SYS_MLOCK = 203 // { int sys_mlock(const void *addr, size_t len); } SYS_MUNLOCK = 204 // { int sys_munlock(const void *addr, size_t len); } SYS_GETPGID = 207 // { pid_t sys_getpgid(pid_t pid); } diff --git a/vendor/golang.org/x/sys/unix/zsysnum_solaris_amd64.go b/vendor/golang.org/x/sys/unix/zsysnum_solaris_amd64.go deleted file mode 100644 index c708659859..0000000000 --- a/vendor/golang.org/x/sys/unix/zsysnum_solaris_amd64.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2014 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 amd64,solaris - -package unix - -// TODO(aram): remove these before Go 1.3. -const ( - SYS_EXECVE = 59 - SYS_FCNTL = 62 -) diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_386.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_386.go index 4667c7b277..327af5fba1 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_darwin_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_386.go @@ -136,13 +136,13 @@ type Fsid struct { } type Dirent struct { - Ino uint64 - Seekoff uint64 - Reclen uint16 - Namlen uint16 - Type uint8 - Name [1024]int8 - Pad_cgo_0 [3]byte + Ino uint64 + Seekoff uint64 + Reclen uint16 + Namlen uint16 + Type uint8 + Name [1024]int8 + _ [3]byte } type RawSockaddrInet4 struct { @@ -295,14 +295,14 @@ const ( ) type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Data IfData } type IfData struct { @@ -338,51 +338,51 @@ type IfData struct { } type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Metric int32 } type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte } type IfmaMsghdr2 struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Refcount int32 + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Refcount int32 } type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics + Msglen uint16 + Version uint8 + Type uint8 + Index uint16 + _ [2]byte + Flags int32 + Addrs int32 + Pid int32 + Seq int32 + Errno int32 + Use int32 + Inits uint32 + Rmx RtMetrics } type RtMetrics struct { @@ -430,11 +430,11 @@ type BpfInsn struct { } type BpfHdr struct { - Tstamp Timeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte + Tstamp Timeval + Caplen uint32 + Datalen uint32 + Hdrlen uint16 + _ [2]byte } type Termios struct { @@ -479,3 +479,11 @@ const ( POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go index 3f33b18fc7..116e6e0757 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go @@ -26,9 +26,9 @@ type Timespec struct { } type Timeval struct { - Sec int64 - Usec int32 - Pad_cgo_0 [4]byte + Sec int64 + Usec int32 + _ [4]byte } type Timeval32 struct { @@ -70,7 +70,7 @@ type Stat_t struct { Uid uint32 Gid uint32 Rdev int32 - Pad_cgo_0 [4]byte + _ [4]byte Atimespec Timespec Mtimespec Timespec Ctimespec Timespec @@ -120,9 +120,9 @@ type Fstore_t struct { } type Radvisory_t struct { - Offset int64 - Count int32 - Pad_cgo_0 [4]byte + Offset int64 + Count int32 + _ [4]byte } type Fbootstraptransfer_t struct { @@ -132,9 +132,9 @@ type Fbootstraptransfer_t struct { } type Log2phys_t struct { - Flags uint32 - Pad_cgo_0 [8]byte - Pad_cgo_1 [8]byte + Flags uint32 + _ [8]byte + _ [8]byte } type Fsid struct { @@ -142,13 +142,13 @@ type Fsid struct { } type Dirent struct { - Ino uint64 - Seekoff uint64 - Reclen uint16 - Namlen uint16 - Type uint8 - Name [1024]int8 - Pad_cgo_0 [3]byte + Ino uint64 + Seekoff uint64 + Reclen uint16 + Namlen uint16 + Type uint8 + Name [1024]int8 + _ [3]byte } type RawSockaddrInet4 struct { @@ -221,10 +221,10 @@ type IPv6Mreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen int32 - Pad_cgo_1 [4]byte + _ [4]byte Control *byte Controllen uint32 Flags int32 @@ -303,14 +303,14 @@ const ( ) type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Data IfData } type IfData struct { @@ -346,51 +346,51 @@ type IfData struct { } type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Metric int32 } type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte } type IfmaMsghdr2 struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Refcount int32 + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Refcount int32 } type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics + Msglen uint16 + Version uint8 + Type uint8 + Index uint16 + _ [2]byte + Flags int32 + Addrs int32 + Pid int32 + Seq int32 + Errno int32 + Use int32 + Inits uint32 + Rmx RtMetrics } type RtMetrics struct { @@ -426,9 +426,9 @@ type BpfStat struct { } type BpfProgram struct { - Len uint32 - Pad_cgo_0 [4]byte - Insns *BpfInsn + Len uint32 + _ [4]byte + Insns *BpfInsn } type BpfInsn struct { @@ -439,22 +439,22 @@ type BpfInsn struct { } type BpfHdr struct { - Tstamp Timeval32 - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte + Tstamp Timeval32 + Caplen uint32 + Datalen uint32 + Hdrlen uint16 + _ [2]byte } type Termios struct { - Iflag uint64 - Oflag uint64 - Cflag uint64 - Lflag uint64 - Cc [20]uint8 - Pad_cgo_0 [4]byte - Ispeed uint64 - Ospeed uint64 + Iflag uint64 + Oflag uint64 + Cflag uint64 + Lflag uint64 + Cc [20]uint8 + _ [4]byte + Ispeed uint64 + Ospeed uint64 } type Winsize struct { @@ -489,3 +489,11 @@ const ( POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go index 463a28ba6f..2750ad7607 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go @@ -137,13 +137,13 @@ type Fsid struct { } type Dirent struct { - Ino uint64 - Seekoff uint64 - Reclen uint16 - Namlen uint16 - Type uint8 - Name [1024]int8 - Pad_cgo_0 [3]byte + Ino uint64 + Seekoff uint64 + Reclen uint16 + Namlen uint16 + Type uint8 + Name [1024]int8 + _ [3]byte } type RawSockaddrInet4 struct { @@ -296,14 +296,14 @@ const ( ) type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Data IfData } type IfData struct { @@ -339,51 +339,51 @@ type IfData struct { } type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Metric int32 } type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte } type IfmaMsghdr2 struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Refcount int32 + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Refcount int32 } type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics + Msglen uint16 + Version uint8 + Type uint8 + Index uint16 + _ [2]byte + Flags int32 + Addrs int32 + Pid int32 + Seq int32 + Errno int32 + Use int32 + Inits uint32 + Rmx RtMetrics } type RtMetrics struct { @@ -431,11 +431,11 @@ type BpfInsn struct { } type BpfHdr struct { - Tstamp Timeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte + Tstamp Timeval + Caplen uint32 + Datalen uint32 + Hdrlen uint16 + _ [2]byte } type Termios struct { @@ -480,3 +480,11 @@ const ( POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go index 1ec20a0025..8cead0996c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go @@ -26,9 +26,9 @@ type Timespec struct { } type Timeval struct { - Sec int64 - Usec int32 - Pad_cgo_0 [4]byte + Sec int64 + Usec int32 + _ [4]byte } type Timeval32 struct { @@ -70,7 +70,7 @@ type Stat_t struct { Uid uint32 Gid uint32 Rdev int32 - Pad_cgo_0 [4]byte + _ [4]byte Atimespec Timespec Mtimespec Timespec Ctimespec Timespec @@ -120,9 +120,9 @@ type Fstore_t struct { } type Radvisory_t struct { - Offset int64 - Count int32 - Pad_cgo_0 [4]byte + Offset int64 + Count int32 + _ [4]byte } type Fbootstraptransfer_t struct { @@ -132,9 +132,9 @@ type Fbootstraptransfer_t struct { } type Log2phys_t struct { - Flags uint32 - Pad_cgo_0 [8]byte - Pad_cgo_1 [8]byte + Flags uint32 + _ [8]byte + _ [8]byte } type Fsid struct { @@ -142,13 +142,13 @@ type Fsid struct { } type Dirent struct { - Ino uint64 - Seekoff uint64 - Reclen uint16 - Namlen uint16 - Type uint8 - Name [1024]int8 - Pad_cgo_0 [3]byte + Ino uint64 + Seekoff uint64 + Reclen uint16 + Namlen uint16 + Type uint8 + Name [1024]int8 + _ [3]byte } type RawSockaddrInet4 struct { @@ -221,10 +221,10 @@ type IPv6Mreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen int32 - Pad_cgo_1 [4]byte + _ [4]byte Control *byte Controllen uint32 Flags int32 @@ -303,14 +303,14 @@ const ( ) type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Data IfData } type IfData struct { @@ -346,51 +346,51 @@ type IfData struct { } type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Metric int32 } type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte } type IfmaMsghdr2 struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Refcount int32 + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Refcount int32 } type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics + Msglen uint16 + Version uint8 + Type uint8 + Index uint16 + _ [2]byte + Flags int32 + Addrs int32 + Pid int32 + Seq int32 + Errno int32 + Use int32 + Inits uint32 + Rmx RtMetrics } type RtMetrics struct { @@ -426,9 +426,9 @@ type BpfStat struct { } type BpfProgram struct { - Len uint32 - Pad_cgo_0 [4]byte - Insns *BpfInsn + Len uint32 + _ [4]byte + Insns *BpfInsn } type BpfInsn struct { @@ -439,22 +439,22 @@ type BpfInsn struct { } type BpfHdr struct { - Tstamp Timeval32 - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte + Tstamp Timeval32 + Caplen uint32 + Datalen uint32 + Hdrlen uint16 + _ [2]byte } type Termios struct { - Iflag uint64 - Oflag uint64 - Cflag uint64 - Lflag uint64 - Cc [20]uint8 - Pad_cgo_0 [4]byte - Ispeed uint64 - Ospeed uint64 + Iflag uint64 + Oflag uint64 + Cflag uint64 + Lflag uint64 + Cc [20]uint8 + _ [4]byte + Ispeed uint64 + Ospeed uint64 } type Winsize struct { @@ -489,3 +489,11 @@ const ( POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go index 1ca0e3ee04..315a553bd5 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go @@ -108,7 +108,7 @@ type Statfs_t struct { Owner uint32 Type int32 Flags int32 - Pad_cgo_0 [4]byte + _ [4]byte Syncwrites int64 Asyncwrites int64 Fstypename [16]int8 @@ -118,7 +118,7 @@ type Statfs_t struct { Spares1 int16 Mntfromname [80]int8 Spares2 int16 - Pad_cgo_1 [4]byte + _ [4]byte Spare [2]int64 } @@ -143,6 +143,10 @@ type Fsid struct { Val [2]int32 } +const ( + PathMax = 0x400 +) + type RawSockaddrInet4 struct { Len uint8 Family uint8 @@ -215,10 +219,10 @@ type IPv6Mreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen int32 - Pad_cgo_1 [4]byte + _ [4]byte Control *byte Controllen uint32 Flags int32 @@ -290,14 +294,14 @@ const ( ) type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Data IfData } type IfData struct { @@ -307,7 +311,7 @@ type IfData struct { Hdrlen uint8 Recvquota uint8 Xmitquota uint8 - Pad_cgo_0 [2]byte + _ [2]byte Mtu uint64 Metric uint64 Link_state uint64 @@ -329,24 +333,24 @@ type IfData struct { } type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Metric int32 } type IfmaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte } type IfAnnounceMsghdr struct { @@ -359,19 +363,19 @@ type IfAnnounceMsghdr struct { } type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint64 - Rmx RtMetrics + Msglen uint16 + Version uint8 + Type uint8 + Index uint16 + _ [2]byte + Flags int32 + Addrs int32 + Pid int32 + Seq int32 + Errno int32 + Use int32 + Inits uint64 + Rmx RtMetrics } type RtMetrics struct { @@ -387,7 +391,7 @@ type RtMetrics struct { Hopcount uint64 Mssopt uint16 Pad uint16 - Pad_cgo_0 [4]byte + _ [4]byte Msl uint64 Iwmaxsegs uint64 Iwcapsegs uint64 @@ -412,9 +416,9 @@ type BpfStat struct { } type BpfProgram struct { - Len uint32 - Pad_cgo_0 [4]byte - Insns *BpfInsn + Len uint32 + _ [4]byte + Insns *BpfInsn } type BpfInsn struct { @@ -425,11 +429,11 @@ type BpfInsn struct { } type BpfHdr struct { - Tstamp Timeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [6]byte + Tstamp Timeval + Caplen uint32 + Datalen uint32 + Hdrlen uint16 + _ [6]byte } type Termios struct { @@ -472,3 +476,11 @@ const ( POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) + +type Utsname struct { + Sysname [32]byte + Nodename [32]byte + Release [32]byte + Version [32]byte + Machine [32]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go index 18f7816009..878a21ad6d 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go @@ -140,6 +140,10 @@ type Fsid struct { Val [2]int32 } +const ( + PathMax = 0x400 +) + const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 @@ -539,3 +543,11 @@ const ( type CapRights struct { Rights [2]uint64 } + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go index dd0db2a5ea..8408af1250 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go @@ -140,6 +140,10 @@ type Fsid struct { Val [2]int32 } +const ( + PathMax = 0x400 +) + const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 @@ -542,3 +546,11 @@ const ( type CapRights struct { Rights [2]uint64 } + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go index 473d3dcf08..4b2d9a4839 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go @@ -142,6 +142,10 @@ type Fsid struct { Val [2]int32 } +const ( + PathMax = 0x400 +) + const ( FADV_NORMAL = 0x0 FADV_RANDOM = 0x1 @@ -542,3 +546,11 @@ const ( type CapRights struct { Rights [2]uint64 } + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go index c6de94269d..4047462081 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_386.go @@ -52,7 +52,7 @@ type Timex struct { Errcnt int32 Stbcnt int32 Tai int32 - Pad_cgo_0 [44]byte + _ [44]byte } type Time_t int32 @@ -96,52 +96,67 @@ type Rlimit struct { type _Gid_t uint32 type Stat_t struct { - Dev uint64 - X__pad1 uint16 - Pad_cgo_0 [2]byte - X__st_ino uint32 - Mode uint32 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev uint64 - X__pad2 uint16 - Pad_cgo_1 [2]byte - Size int64 - Blksize int32 - Blocks int64 - Atim Timespec - Mtim Timespec - Ctim Timespec - Ino uint64 -} - -type Statfs_t struct { - Type int32 - Bsize int32 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int32 - Frsize int32 - Flags int32 - Spare [4]int32 + Dev uint64 + _ uint16 + _ [2]byte + _ uint32 + Mode uint32 + Nlink uint32 + Uid uint32 + Gid uint32 + Rdev uint64 + _ uint16 + _ [2]byte + Size int64 + Blksize int32 + Blocks int64 + Atim Timespec + Mtim Timespec + Ctim Timespec + Ino uint64 +} + +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]int8 - Pad_cgo_0 [1]byte + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]int8 + _ [1]byte } type Fsid struct { - X__val [2]int32 + Val [2]int32 } type Flock_t struct { @@ -224,11 +239,20 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { - Family uint16 - Pad_cgo_0 [2]byte - Ifindex int32 - Addr [8]byte + Family uint16 + _ [2]byte + Ifindex int32 + Addr [8]byte } type RawSockaddrALG struct { @@ -341,7 +365,7 @@ type TCPInfo struct { Probes uint8 Backoff uint8 Options uint8 - Pad_cgo_0 [2]byte + _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 @@ -376,6 +400,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -396,97 +421,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -517,12 +568,12 @@ type RtAttr struct { } type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 + Family uint8 + _ uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 } type IfAddrmsg struct { @@ -565,9 +616,9 @@ type SockFilter struct { } type SockFprog struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *SockFilter + Len uint16 + _ [2]byte + Filter *SockFilter } type InotifyEvent struct { @@ -617,7 +668,7 @@ type Sysinfo_t struct { Totalhigh uint32 Freehigh uint32 Unit uint32 - X_f [8]int8 + _ [8]int8 } type Utsname struct { @@ -643,8 +694,15 @@ type EpollEvent struct { } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -666,7 +724,7 @@ const ( ) type Sigset_t struct { - X__val [32]uint32 + Val [32]uint32 } const RNDGETENTCNT = 0x80045200 @@ -693,11 +751,11 @@ type Winsize struct { type Taskstats struct { Version uint16 - Pad_cgo_0 [2]byte + _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - Pad_cgo_1 [6]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 @@ -709,13 +767,13 @@ type Taskstats struct { Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 - Pad_cgo_2 [4]byte + _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 - Pad_cgo_3 [4]byte + _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 @@ -759,6 +817,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -791,3 +867,949 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint32 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x20 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x1 + CBitFieldMaskBit1 = 0x2 + CBitFieldMaskBit2 = 0x4 + CBitFieldMaskBit3 = 0x8 + CBitFieldMaskBit4 = 0x10 + CBitFieldMaskBit5 = 0x20 + CBitFieldMaskBit6 = 0x40 + CBitFieldMaskBit7 = 0x80 + CBitFieldMaskBit8 = 0x100 + CBitFieldMaskBit9 = 0x200 + CBitFieldMaskBit10 = 0x400 + CBitFieldMaskBit11 = 0x800 + CBitFieldMaskBit12 = 0x1000 + CBitFieldMaskBit13 = 0x2000 + CBitFieldMaskBit14 = 0x4000 + CBitFieldMaskBit15 = 0x8000 + CBitFieldMaskBit16 = 0x10000 + CBitFieldMaskBit17 = 0x20000 + CBitFieldMaskBit18 = 0x40000 + CBitFieldMaskBit19 = 0x80000 + CBitFieldMaskBit20 = 0x100000 + CBitFieldMaskBit21 = 0x200000 + CBitFieldMaskBit22 = 0x400000 + CBitFieldMaskBit23 = 0x800000 + CBitFieldMaskBit24 = 0x1000000 + CBitFieldMaskBit25 = 0x2000000 + CBitFieldMaskBit26 = 0x4000000 + CBitFieldMaskBit27 = 0x8000000 + CBitFieldMaskBit28 = 0x10000000 + CBitFieldMaskBit29 = 0x20000000 + CBitFieldMaskBit30 = 0x40000000 + CBitFieldMaskBit31 = 0x80000000 + CBitFieldMaskBit32 = 0x100000000 + CBitFieldMaskBit33 = 0x200000000 + CBitFieldMaskBit34 = 0x400000000 + CBitFieldMaskBit35 = 0x800000000 + CBitFieldMaskBit36 = 0x1000000000 + CBitFieldMaskBit37 = 0x2000000000 + CBitFieldMaskBit38 = 0x4000000000 + CBitFieldMaskBit39 = 0x8000000000 + CBitFieldMaskBit40 = 0x10000000000 + CBitFieldMaskBit41 = 0x20000000000 + CBitFieldMaskBit42 = 0x40000000000 + CBitFieldMaskBit43 = 0x80000000000 + CBitFieldMaskBit44 = 0x100000000000 + CBitFieldMaskBit45 = 0x200000000000 + CBitFieldMaskBit46 = 0x400000000000 + CBitFieldMaskBit47 = 0x800000000000 + CBitFieldMaskBit48 = 0x1000000000000 + CBitFieldMaskBit49 = 0x2000000000000 + CBitFieldMaskBit50 = 0x4000000000000 + CBitFieldMaskBit51 = 0x8000000000000 + CBitFieldMaskBit52 = 0x10000000000000 + CBitFieldMaskBit53 = 0x20000000000000 + CBitFieldMaskBit54 = 0x40000000000000 + CBitFieldMaskBit55 = 0x80000000000000 + CBitFieldMaskBit56 = 0x100000000000000 + CBitFieldMaskBit57 = 0x200000000000000 + CBitFieldMaskBit58 = 0x400000000000000 + CBitFieldMaskBit59 = 0x800000000000000 + CBitFieldMaskBit60 = 0x1000000000000000 + CBitFieldMaskBit61 = 0x2000000000000000 + CBitFieldMaskBit62 = 0x4000000000000000 + CBitFieldMaskBit63 = 0x8000000000000000 +) + +type SockaddrStorage struct { + Family uint16 + _ [122]int8 + _ uint32 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + Start uint32 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type int32 + Bsize int32 + Blocks uint64 + Bfree uint64 + Bavail uint64 + Files uint64 + Ffree uint64 + Fsid Fsid + Namelen int32 + Frsize int32 + Flags int32 + Spare [4]int32 +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x18 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go index 4ea42dfc2e..2ab0cb9e79 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go @@ -33,13 +33,13 @@ type Timeval struct { type Timex struct { Modes uint32 - Pad_cgo_0 [4]byte + _ [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 - Pad_cgo_1 [4]byte + _ [4]byte Constant int64 Precision int64 Tolerance int64 @@ -48,14 +48,14 @@ type Timex struct { Ppsfreq int64 Jitter int64 Shift int32 - Pad_cgo_2 [4]byte + _ [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 - Pad_cgo_3 [44]byte + _ [44]byte } type Time_t int64 @@ -105,7 +105,7 @@ type Stat_t struct { Mode uint32 Uid uint32 Gid uint32 - X__pad0 int32 + _ int32 Rdev uint64 Size int64 Blksize int64 @@ -116,42 +116,57 @@ type Stat_t struct { _ [3]int64 } -type Statfs_t struct { - Type int64 - Bsize int64 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int64 - Frsize int64 - Flags int64 - Spare [4]int64 +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]int8 - Pad_cgo_0 [5]byte + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]int8 + _ [5]byte } type Fsid struct { - X__val [2]int32 + Val [2]int32 } type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte + Type int16 + Whence int16 + _ [4]byte + Start int64 + Len int64 + Pid int32 + _ [4]byte } type FscryptPolicy struct { @@ -226,11 +241,20 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { - Family uint16 - Pad_cgo_0 [2]byte - Ifindex int32 - Addr [8]byte + Family uint16 + _ [2]byte + Ifindex int32 + Addr [8]byte } type RawSockaddrALG struct { @@ -297,13 +321,13 @@ type PacketMreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 - Pad_cgo_1 [4]byte + _ [4]byte } type Cmsghdr struct { @@ -345,7 +369,7 @@ type TCPInfo struct { Probes uint8 Backoff uint8 Options uint8 - Pad_cgo_0 [2]byte + _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 @@ -380,6 +404,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -400,97 +425,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -521,12 +572,12 @@ type RtAttr struct { } type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 + Family uint8 + _ uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 } type IfAddrmsg struct { @@ -569,9 +620,9 @@ type SockFilter struct { } type SockFprog struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *SockFilter + Len uint16 + _ [6]byte + Filter *SockFilter } type InotifyEvent struct { @@ -628,12 +679,12 @@ type Sysinfo_t struct { Freeswap uint64 Procs uint16 Pad uint16 - Pad_cgo_0 [4]byte + _ [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 - X_f [0]int8 - Pad_cgo_1 [4]byte + _ [0]int8 + _ [4]byte } type Utsname struct { @@ -646,12 +697,12 @@ type Utsname struct { } type Ustat_t struct { - Tfree int32 - Pad_cgo_0 [4]byte - Tinode uint64 - Fname [6]int8 - Fpack [6]int8 - Pad_cgo_1 [4]byte + Tfree int32 + _ [4]byte + Tinode uint64 + Fname [6]int8 + Fpack [6]int8 + _ [4]byte } type EpollEvent struct { @@ -661,8 +712,15 @@ type EpollEvent struct { } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -684,7 +742,7 @@ const ( ) type Sigset_t struct { - X__val [16]uint64 + Val [16]uint64 } const RNDGETENTCNT = 0x80045200 @@ -711,11 +769,11 @@ type Winsize struct { type Taskstats struct { Version uint16 - Pad_cgo_0 [2]byte + _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - Pad_cgo_1 [6]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 @@ -727,13 +785,13 @@ type Taskstats struct { Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 - Pad_cgo_2 [4]byte + _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 - Pad_cgo_3 [4]byte + _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 @@ -777,6 +835,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -809,3 +885,951 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint64 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x40 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x1 + CBitFieldMaskBit1 = 0x2 + CBitFieldMaskBit2 = 0x4 + CBitFieldMaskBit3 = 0x8 + CBitFieldMaskBit4 = 0x10 + CBitFieldMaskBit5 = 0x20 + CBitFieldMaskBit6 = 0x40 + CBitFieldMaskBit7 = 0x80 + CBitFieldMaskBit8 = 0x100 + CBitFieldMaskBit9 = 0x200 + CBitFieldMaskBit10 = 0x400 + CBitFieldMaskBit11 = 0x800 + CBitFieldMaskBit12 = 0x1000 + CBitFieldMaskBit13 = 0x2000 + CBitFieldMaskBit14 = 0x4000 + CBitFieldMaskBit15 = 0x8000 + CBitFieldMaskBit16 = 0x10000 + CBitFieldMaskBit17 = 0x20000 + CBitFieldMaskBit18 = 0x40000 + CBitFieldMaskBit19 = 0x80000 + CBitFieldMaskBit20 = 0x100000 + CBitFieldMaskBit21 = 0x200000 + CBitFieldMaskBit22 = 0x400000 + CBitFieldMaskBit23 = 0x800000 + CBitFieldMaskBit24 = 0x1000000 + CBitFieldMaskBit25 = 0x2000000 + CBitFieldMaskBit26 = 0x4000000 + CBitFieldMaskBit27 = 0x8000000 + CBitFieldMaskBit28 = 0x10000000 + CBitFieldMaskBit29 = 0x20000000 + CBitFieldMaskBit30 = 0x40000000 + CBitFieldMaskBit31 = 0x80000000 + CBitFieldMaskBit32 = 0x100000000 + CBitFieldMaskBit33 = 0x200000000 + CBitFieldMaskBit34 = 0x400000000 + CBitFieldMaskBit35 = 0x800000000 + CBitFieldMaskBit36 = 0x1000000000 + CBitFieldMaskBit37 = 0x2000000000 + CBitFieldMaskBit38 = 0x4000000000 + CBitFieldMaskBit39 = 0x8000000000 + CBitFieldMaskBit40 = 0x10000000000 + CBitFieldMaskBit41 = 0x20000000000 + CBitFieldMaskBit42 = 0x40000000000 + CBitFieldMaskBit43 = 0x80000000000 + CBitFieldMaskBit44 = 0x100000000000 + CBitFieldMaskBit45 = 0x200000000000 + CBitFieldMaskBit46 = 0x400000000000 + CBitFieldMaskBit47 = 0x800000000000 + CBitFieldMaskBit48 = 0x1000000000000 + CBitFieldMaskBit49 = 0x2000000000000 + CBitFieldMaskBit50 = 0x4000000000000 + CBitFieldMaskBit51 = 0x8000000000000 + CBitFieldMaskBit52 = 0x10000000000000 + CBitFieldMaskBit53 = 0x20000000000000 + CBitFieldMaskBit54 = 0x40000000000000 + CBitFieldMaskBit55 = 0x80000000000000 + CBitFieldMaskBit56 = 0x100000000000000 + CBitFieldMaskBit57 = 0x200000000000000 + CBitFieldMaskBit58 = 0x400000000000000 + CBitFieldMaskBit59 = 0x800000000000000 + CBitFieldMaskBit60 = 0x1000000000000000 + CBitFieldMaskBit61 = 0x2000000000000000 + CBitFieldMaskBit62 = 0x4000000000000000 + CBitFieldMaskBit63 = 0x8000000000000000 +) + +type SockaddrStorage struct { + Family uint16 + _ [118]int8 + _ uint64 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + _ [4]byte + Start uint64 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type int64 + Bsize int64 + Blocks uint64 + Bfree uint64 + Bavail uint64 + Files uint64 + Ffree uint64 + Fsid Fsid + Namelen int64 + Frsize int64 + Flags int64 + Spare [4]int64 +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint64 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 + _ [4]byte +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x20 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go index f86d683882..18d577b912 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm.go @@ -52,7 +52,7 @@ type Timex struct { Errcnt int32 Stbcnt int32 Tai int32 - Pad_cgo_0 [44]byte + _ [44]byte } type Time_t int32 @@ -96,64 +96,78 @@ type Rlimit struct { type _Gid_t uint32 type Stat_t struct { - Dev uint64 - X__pad1 uint16 - Pad_cgo_0 [2]byte - X__st_ino uint32 - Mode uint32 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev uint64 - X__pad2 uint16 - Pad_cgo_1 [6]byte - Size int64 - Blksize int32 - Pad_cgo_2 [4]byte - Blocks int64 - Atim Timespec - Mtim Timespec - Ctim Timespec - Ino uint64 -} - -type Statfs_t struct { - Type int32 - Bsize int32 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int32 - Frsize int32 - Flags int32 - Spare [4]int32 - Pad_cgo_0 [4]byte + Dev uint64 + _ uint16 + _ [2]byte + _ uint32 + Mode uint32 + Nlink uint32 + Uid uint32 + Gid uint32 + Rdev uint64 + _ uint16 + _ [6]byte + Size int64 + Blksize int32 + _ [4]byte + Blocks int64 + Atim Timespec + Mtim Timespec + Ctim Timespec + Ino uint64 +} + +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]uint8 - Pad_cgo_0 [5]byte + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]uint8 + _ [5]byte } type Fsid struct { - X__val [2]int32 + Val [2]int32 } type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte + Type int16 + Whence int16 + _ [4]byte + Start int64 + Len int64 + Pid int32 + _ [4]byte } type FscryptPolicy struct { @@ -228,11 +242,20 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { - Family uint16 - Pad_cgo_0 [2]byte - Ifindex int32 - Addr [8]byte + Family uint16 + _ [2]byte + Ifindex int32 + Addr [8]byte } type RawSockaddrALG struct { @@ -345,7 +368,7 @@ type TCPInfo struct { Probes uint8 Backoff uint8 Options uint8 - Pad_cgo_0 [2]byte + _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 @@ -380,6 +403,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -400,97 +424,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -521,12 +571,12 @@ type RtAttr struct { } type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 + Family uint8 + _ uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 } type IfAddrmsg struct { @@ -569,9 +619,9 @@ type SockFilter struct { } type SockFprog struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *SockFilter + Len uint16 + _ [2]byte + Filter *SockFilter } type InotifyEvent struct { @@ -605,7 +655,7 @@ type Sysinfo_t struct { Totalhigh uint32 Freehigh uint32 Unit uint32 - X_f [8]uint8 + _ [8]uint8 } type Utsname struct { @@ -632,8 +682,15 @@ type EpollEvent struct { } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -655,7 +712,7 @@ const ( ) type Sigset_t struct { - X__val [32]uint32 + Val [32]uint32 } const RNDGETENTCNT = 0x80045200 @@ -682,11 +739,11 @@ type Winsize struct { type Taskstats struct { Version uint16 - Pad_cgo_0 [2]byte + _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - Pad_cgo_1 [6]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 @@ -698,13 +755,13 @@ type Taskstats struct { Ac_comm [32]uint8 Ac_sched uint8 Ac_pad [3]uint8 - Pad_cgo_2 [4]byte + _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 - Pad_cgo_3 [4]byte + _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 @@ -748,6 +805,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -780,3 +855,950 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint32 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x20 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x1 + CBitFieldMaskBit1 = 0x2 + CBitFieldMaskBit2 = 0x4 + CBitFieldMaskBit3 = 0x8 + CBitFieldMaskBit4 = 0x10 + CBitFieldMaskBit5 = 0x20 + CBitFieldMaskBit6 = 0x40 + CBitFieldMaskBit7 = 0x80 + CBitFieldMaskBit8 = 0x100 + CBitFieldMaskBit9 = 0x200 + CBitFieldMaskBit10 = 0x400 + CBitFieldMaskBit11 = 0x800 + CBitFieldMaskBit12 = 0x1000 + CBitFieldMaskBit13 = 0x2000 + CBitFieldMaskBit14 = 0x4000 + CBitFieldMaskBit15 = 0x8000 + CBitFieldMaskBit16 = 0x10000 + CBitFieldMaskBit17 = 0x20000 + CBitFieldMaskBit18 = 0x40000 + CBitFieldMaskBit19 = 0x80000 + CBitFieldMaskBit20 = 0x100000 + CBitFieldMaskBit21 = 0x200000 + CBitFieldMaskBit22 = 0x400000 + CBitFieldMaskBit23 = 0x800000 + CBitFieldMaskBit24 = 0x1000000 + CBitFieldMaskBit25 = 0x2000000 + CBitFieldMaskBit26 = 0x4000000 + CBitFieldMaskBit27 = 0x8000000 + CBitFieldMaskBit28 = 0x10000000 + CBitFieldMaskBit29 = 0x20000000 + CBitFieldMaskBit30 = 0x40000000 + CBitFieldMaskBit31 = 0x80000000 + CBitFieldMaskBit32 = 0x100000000 + CBitFieldMaskBit33 = 0x200000000 + CBitFieldMaskBit34 = 0x400000000 + CBitFieldMaskBit35 = 0x800000000 + CBitFieldMaskBit36 = 0x1000000000 + CBitFieldMaskBit37 = 0x2000000000 + CBitFieldMaskBit38 = 0x4000000000 + CBitFieldMaskBit39 = 0x8000000000 + CBitFieldMaskBit40 = 0x10000000000 + CBitFieldMaskBit41 = 0x20000000000 + CBitFieldMaskBit42 = 0x40000000000 + CBitFieldMaskBit43 = 0x80000000000 + CBitFieldMaskBit44 = 0x100000000000 + CBitFieldMaskBit45 = 0x200000000000 + CBitFieldMaskBit46 = 0x400000000000 + CBitFieldMaskBit47 = 0x800000000000 + CBitFieldMaskBit48 = 0x1000000000000 + CBitFieldMaskBit49 = 0x2000000000000 + CBitFieldMaskBit50 = 0x4000000000000 + CBitFieldMaskBit51 = 0x8000000000000 + CBitFieldMaskBit52 = 0x10000000000000 + CBitFieldMaskBit53 = 0x20000000000000 + CBitFieldMaskBit54 = 0x40000000000000 + CBitFieldMaskBit55 = 0x80000000000000 + CBitFieldMaskBit56 = 0x100000000000000 + CBitFieldMaskBit57 = 0x200000000000000 + CBitFieldMaskBit58 = 0x400000000000000 + CBitFieldMaskBit59 = 0x800000000000000 + CBitFieldMaskBit60 = 0x1000000000000000 + CBitFieldMaskBit61 = 0x2000000000000000 + CBitFieldMaskBit62 = 0x4000000000000000 + CBitFieldMaskBit63 = 0x8000000000000000 +) + +type SockaddrStorage struct { + Family uint16 + _ [122]uint8 + _ uint32 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + Start uint32 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type int32 + Bsize int32 + Blocks uint64 + Bfree uint64 + Bavail uint64 + Files uint64 + Ffree uint64 + Fsid Fsid + Namelen int32 + Frsize int32 + Flags int32 + Spare [4]int32 + _ [4]byte +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x18 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go index 45c10b7429..6ea80563f1 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go @@ -33,13 +33,13 @@ type Timeval struct { type Timex struct { Modes uint32 - Pad_cgo_0 [4]byte + _ [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 - Pad_cgo_1 [4]byte + _ [4]byte Constant int64 Precision int64 Tolerance int64 @@ -48,14 +48,14 @@ type Timex struct { Ppsfreq int64 Jitter int64 Shift int32 - Pad_cgo_2 [4]byte + _ [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 - Pad_cgo_3 [44]byte + _ [44]byte } type Time_t int64 @@ -106,10 +106,10 @@ type Stat_t struct { Uid uint32 Gid uint32 Rdev uint64 - X__pad1 uint64 + _ uint64 Size int64 Blksize int32 - X__pad2 int32 + _ int32 Blocks int64 Atim Timespec Mtim Timespec @@ -117,42 +117,57 @@ type Stat_t struct { _ [2]int32 } -type Statfs_t struct { - Type int64 - Bsize int64 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int64 - Frsize int64 - Flags int64 - Spare [4]int64 +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]int8 - Pad_cgo_0 [5]byte + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]int8 + _ [5]byte } type Fsid struct { - X__val [2]int32 + Val [2]int32 } type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte + Type int16 + Whence int16 + _ [4]byte + Start int64 + Len int64 + Pid int32 + _ [4]byte } type FscryptPolicy struct { @@ -227,11 +242,20 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { - Family uint16 - Pad_cgo_0 [2]byte - Ifindex int32 - Addr [8]byte + Family uint16 + _ [2]byte + Ifindex int32 + Addr [8]byte } type RawSockaddrALG struct { @@ -298,13 +322,13 @@ type PacketMreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 - Pad_cgo_1 [4]byte + _ [4]byte } type Cmsghdr struct { @@ -346,7 +370,7 @@ type TCPInfo struct { Probes uint8 Backoff uint8 Options uint8 - Pad_cgo_0 [2]byte + _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 @@ -381,6 +405,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -401,97 +426,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -522,12 +573,12 @@ type RtAttr struct { } type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 + Family uint8 + _ uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 } type IfAddrmsg struct { @@ -570,9 +621,9 @@ type SockFilter struct { } type SockFprog struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *SockFilter + Len uint16 + _ [6]byte + Filter *SockFilter } type InotifyEvent struct { @@ -606,12 +657,12 @@ type Sysinfo_t struct { Freeswap uint64 Procs uint16 Pad uint16 - Pad_cgo_0 [4]byte + _ [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 - X_f [0]int8 - Pad_cgo_1 [4]byte + _ [0]int8 + _ [4]byte } type Utsname struct { @@ -624,12 +675,12 @@ type Utsname struct { } type Ustat_t struct { - Tfree int32 - Pad_cgo_0 [4]byte - Tinode uint64 - Fname [6]int8 - Fpack [6]int8 - Pad_cgo_1 [4]byte + Tfree int32 + _ [4]byte + Tinode uint64 + Fname [6]int8 + Fpack [6]int8 + _ [4]byte } type EpollEvent struct { @@ -640,8 +691,15 @@ type EpollEvent struct { } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -663,7 +721,7 @@ const ( ) type Sigset_t struct { - X__val [16]uint64 + Val [16]uint64 } const RNDGETENTCNT = 0x80045200 @@ -690,11 +748,11 @@ type Winsize struct { type Taskstats struct { Version uint16 - Pad_cgo_0 [2]byte + _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - Pad_cgo_1 [6]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 @@ -706,13 +764,13 @@ type Taskstats struct { Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 - Pad_cgo_2 [4]byte + _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 - Pad_cgo_3 [4]byte + _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 @@ -756,6 +814,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -788,3 +864,951 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint64 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x40 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x1 + CBitFieldMaskBit1 = 0x2 + CBitFieldMaskBit2 = 0x4 + CBitFieldMaskBit3 = 0x8 + CBitFieldMaskBit4 = 0x10 + CBitFieldMaskBit5 = 0x20 + CBitFieldMaskBit6 = 0x40 + CBitFieldMaskBit7 = 0x80 + CBitFieldMaskBit8 = 0x100 + CBitFieldMaskBit9 = 0x200 + CBitFieldMaskBit10 = 0x400 + CBitFieldMaskBit11 = 0x800 + CBitFieldMaskBit12 = 0x1000 + CBitFieldMaskBit13 = 0x2000 + CBitFieldMaskBit14 = 0x4000 + CBitFieldMaskBit15 = 0x8000 + CBitFieldMaskBit16 = 0x10000 + CBitFieldMaskBit17 = 0x20000 + CBitFieldMaskBit18 = 0x40000 + CBitFieldMaskBit19 = 0x80000 + CBitFieldMaskBit20 = 0x100000 + CBitFieldMaskBit21 = 0x200000 + CBitFieldMaskBit22 = 0x400000 + CBitFieldMaskBit23 = 0x800000 + CBitFieldMaskBit24 = 0x1000000 + CBitFieldMaskBit25 = 0x2000000 + CBitFieldMaskBit26 = 0x4000000 + CBitFieldMaskBit27 = 0x8000000 + CBitFieldMaskBit28 = 0x10000000 + CBitFieldMaskBit29 = 0x20000000 + CBitFieldMaskBit30 = 0x40000000 + CBitFieldMaskBit31 = 0x80000000 + CBitFieldMaskBit32 = 0x100000000 + CBitFieldMaskBit33 = 0x200000000 + CBitFieldMaskBit34 = 0x400000000 + CBitFieldMaskBit35 = 0x800000000 + CBitFieldMaskBit36 = 0x1000000000 + CBitFieldMaskBit37 = 0x2000000000 + CBitFieldMaskBit38 = 0x4000000000 + CBitFieldMaskBit39 = 0x8000000000 + CBitFieldMaskBit40 = 0x10000000000 + CBitFieldMaskBit41 = 0x20000000000 + CBitFieldMaskBit42 = 0x40000000000 + CBitFieldMaskBit43 = 0x80000000000 + CBitFieldMaskBit44 = 0x100000000000 + CBitFieldMaskBit45 = 0x200000000000 + CBitFieldMaskBit46 = 0x400000000000 + CBitFieldMaskBit47 = 0x800000000000 + CBitFieldMaskBit48 = 0x1000000000000 + CBitFieldMaskBit49 = 0x2000000000000 + CBitFieldMaskBit50 = 0x4000000000000 + CBitFieldMaskBit51 = 0x8000000000000 + CBitFieldMaskBit52 = 0x10000000000000 + CBitFieldMaskBit53 = 0x20000000000000 + CBitFieldMaskBit54 = 0x40000000000000 + CBitFieldMaskBit55 = 0x80000000000000 + CBitFieldMaskBit56 = 0x100000000000000 + CBitFieldMaskBit57 = 0x200000000000000 + CBitFieldMaskBit58 = 0x400000000000000 + CBitFieldMaskBit59 = 0x800000000000000 + CBitFieldMaskBit60 = 0x1000000000000000 + CBitFieldMaskBit61 = 0x2000000000000000 + CBitFieldMaskBit62 = 0x4000000000000000 + CBitFieldMaskBit63 = 0x8000000000000000 +) + +type SockaddrStorage struct { + Family uint16 + _ [118]int8 + _ uint64 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + _ [4]byte + Start uint64 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type int64 + Bsize int64 + Blocks uint64 + Bfree uint64 + Bavail uint64 + Files uint64 + Ffree uint64 + Fsid Fsid + Namelen int64 + Frsize int64 + Flags int64 + Spare [4]int64 +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint64 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 + _ [4]byte +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x20 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go index 4cc0a1c91f..e0a3932232 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips.go @@ -52,7 +52,7 @@ type Timex struct { Errcnt int32 Stbcnt int32 Tai int32 - Pad_cgo_0 [44]byte + _ [44]byte } type Time_t int32 @@ -115,44 +115,57 @@ type Stat_t struct { Pad5 [14]int32 } -type Statfs_t struct { - Type int32 - Bsize int32 - Frsize int32 - Pad_cgo_0 [4]byte - Blocks uint64 - Bfree uint64 - Files uint64 - Ffree uint64 - Bavail uint64 - Fsid Fsid - Namelen int32 - Flags int32 - Spare [5]int32 - Pad_cgo_1 [4]byte +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]int8 - Pad_cgo_0 [5]byte + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]int8 + _ [5]byte } type Fsid struct { - X__val [2]int32 + Val [2]int32 } type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte + Type int16 + Whence int16 + _ [4]byte + Start int64 + Len int64 + Pid int32 + _ [4]byte } type FscryptPolicy struct { @@ -227,11 +240,20 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { - Family uint16 - Pad_cgo_0 [2]byte - Ifindex int32 - Addr [8]byte + Family uint16 + _ [2]byte + Ifindex int32 + Addr [8]byte } type RawSockaddrALG struct { @@ -344,7 +366,7 @@ type TCPInfo struct { Probes uint8 Backoff uint8 Options uint8 - Pad_cgo_0 [2]byte + _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 @@ -379,6 +401,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -399,97 +422,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -520,12 +569,12 @@ type RtAttr struct { } type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 + Family uint8 + _ uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 } type IfAddrmsg struct { @@ -568,9 +617,9 @@ type SockFilter struct { } type SockFprog struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *SockFilter + Len uint16 + _ [2]byte + Filter *SockFilter } type InotifyEvent struct { @@ -610,7 +659,7 @@ type Sysinfo_t struct { Totalhigh uint32 Freehigh uint32 Unit uint32 - X_f [8]int8 + _ [8]int8 } type Utsname struct { @@ -637,8 +686,15 @@ type EpollEvent struct { } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -660,7 +716,7 @@ const ( ) type Sigset_t struct { - X__val [32]uint32 + Val [32]uint32 } const RNDGETENTCNT = 0x40045200 @@ -687,11 +743,11 @@ type Winsize struct { type Taskstats struct { Version uint16 - Pad_cgo_0 [2]byte + _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - Pad_cgo_1 [6]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 @@ -703,13 +759,13 @@ type Taskstats struct { Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 - Pad_cgo_2 [4]byte + _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 - Pad_cgo_3 [4]byte + _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 @@ -753,6 +809,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -785,3 +859,951 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint32 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x20 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x8000000000000000 + CBitFieldMaskBit1 = 0x4000000000000000 + CBitFieldMaskBit2 = 0x2000000000000000 + CBitFieldMaskBit3 = 0x1000000000000000 + CBitFieldMaskBit4 = 0x800000000000000 + CBitFieldMaskBit5 = 0x400000000000000 + CBitFieldMaskBit6 = 0x200000000000000 + CBitFieldMaskBit7 = 0x100000000000000 + CBitFieldMaskBit8 = 0x80000000000000 + CBitFieldMaskBit9 = 0x40000000000000 + CBitFieldMaskBit10 = 0x20000000000000 + CBitFieldMaskBit11 = 0x10000000000000 + CBitFieldMaskBit12 = 0x8000000000000 + CBitFieldMaskBit13 = 0x4000000000000 + CBitFieldMaskBit14 = 0x2000000000000 + CBitFieldMaskBit15 = 0x1000000000000 + CBitFieldMaskBit16 = 0x800000000000 + CBitFieldMaskBit17 = 0x400000000000 + CBitFieldMaskBit18 = 0x200000000000 + CBitFieldMaskBit19 = 0x100000000000 + CBitFieldMaskBit20 = 0x80000000000 + CBitFieldMaskBit21 = 0x40000000000 + CBitFieldMaskBit22 = 0x20000000000 + CBitFieldMaskBit23 = 0x10000000000 + CBitFieldMaskBit24 = 0x8000000000 + CBitFieldMaskBit25 = 0x4000000000 + CBitFieldMaskBit26 = 0x2000000000 + CBitFieldMaskBit27 = 0x1000000000 + CBitFieldMaskBit28 = 0x800000000 + CBitFieldMaskBit29 = 0x400000000 + CBitFieldMaskBit30 = 0x200000000 + CBitFieldMaskBit31 = 0x100000000 + CBitFieldMaskBit32 = 0x80000000 + CBitFieldMaskBit33 = 0x40000000 + CBitFieldMaskBit34 = 0x20000000 + CBitFieldMaskBit35 = 0x10000000 + CBitFieldMaskBit36 = 0x8000000 + CBitFieldMaskBit37 = 0x4000000 + CBitFieldMaskBit38 = 0x2000000 + CBitFieldMaskBit39 = 0x1000000 + CBitFieldMaskBit40 = 0x800000 + CBitFieldMaskBit41 = 0x400000 + CBitFieldMaskBit42 = 0x200000 + CBitFieldMaskBit43 = 0x100000 + CBitFieldMaskBit44 = 0x80000 + CBitFieldMaskBit45 = 0x40000 + CBitFieldMaskBit46 = 0x20000 + CBitFieldMaskBit47 = 0x10000 + CBitFieldMaskBit48 = 0x8000 + CBitFieldMaskBit49 = 0x4000 + CBitFieldMaskBit50 = 0x2000 + CBitFieldMaskBit51 = 0x1000 + CBitFieldMaskBit52 = 0x800 + CBitFieldMaskBit53 = 0x400 + CBitFieldMaskBit54 = 0x200 + CBitFieldMaskBit55 = 0x100 + CBitFieldMaskBit56 = 0x80 + CBitFieldMaskBit57 = 0x40 + CBitFieldMaskBit58 = 0x20 + CBitFieldMaskBit59 = 0x10 + CBitFieldMaskBit60 = 0x8 + CBitFieldMaskBit61 = 0x4 + CBitFieldMaskBit62 = 0x2 + CBitFieldMaskBit63 = 0x1 +) + +type SockaddrStorage struct { + Family uint16 + _ [122]int8 + _ uint32 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + Start uint32 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type int32 + Bsize int32 + Frsize int32 + _ [4]byte + Blocks uint64 + Bfree uint64 + Files uint64 + Ffree uint64 + Bavail uint64 + Fsid Fsid + Namelen int32 + Flags int32 + Spare [5]int32 + _ [4]byte +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x18 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go index d9df08789f..838135e24b 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64.go @@ -33,13 +33,13 @@ type Timeval struct { type Timex struct { Modes uint32 - Pad_cgo_0 [4]byte + _ [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 - Pad_cgo_1 [4]byte + _ [4]byte Constant int64 Precision int64 Tolerance int64 @@ -48,14 +48,14 @@ type Timex struct { Ppsfreq int64 Jitter int64 Shift int32 - Pad_cgo_2 [4]byte + _ [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 - Pad_cgo_3 [44]byte + _ [44]byte } type Time_t int64 @@ -117,42 +117,57 @@ type Stat_t struct { Blocks int64 } -type Statfs_t struct { - Type int64 - Bsize int64 - Frsize int64 - Blocks uint64 - Bfree uint64 - Files uint64 - Ffree uint64 - Bavail uint64 - Fsid Fsid - Namelen int64 - Flags int64 - Spare [5]int64 +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]int8 - Pad_cgo_0 [5]byte + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]int8 + _ [5]byte } type Fsid struct { - X__val [2]int32 + Val [2]int32 } type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte + Type int16 + Whence int16 + _ [4]byte + Start int64 + Len int64 + Pid int32 + _ [4]byte } type FscryptPolicy struct { @@ -227,11 +242,20 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { - Family uint16 - Pad_cgo_0 [2]byte - Ifindex int32 - Addr [8]byte + Family uint16 + _ [2]byte + Ifindex int32 + Addr [8]byte } type RawSockaddrALG struct { @@ -298,13 +322,13 @@ type PacketMreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 - Pad_cgo_1 [4]byte + _ [4]byte } type Cmsghdr struct { @@ -346,7 +370,7 @@ type TCPInfo struct { Probes uint8 Backoff uint8 Options uint8 - Pad_cgo_0 [2]byte + _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 @@ -381,6 +405,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -401,97 +426,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -522,12 +573,12 @@ type RtAttr struct { } type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 + Family uint8 + _ uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 } type IfAddrmsg struct { @@ -570,9 +621,9 @@ type SockFilter struct { } type SockFprog struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *SockFilter + Len uint16 + _ [6]byte + Filter *SockFilter } type InotifyEvent struct { @@ -609,12 +660,12 @@ type Sysinfo_t struct { Freeswap uint64 Procs uint16 Pad uint16 - Pad_cgo_0 [4]byte + _ [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 - X_f [0]int8 - Pad_cgo_1 [4]byte + _ [0]int8 + _ [4]byte } type Utsname struct { @@ -627,12 +678,12 @@ type Utsname struct { } type Ustat_t struct { - Tfree int32 - Pad_cgo_0 [4]byte - Tinode uint64 - Fname [6]int8 - Fpack [6]int8 - Pad_cgo_1 [4]byte + Tfree int32 + _ [4]byte + Tinode uint64 + Fname [6]int8 + Fpack [6]int8 + _ [4]byte } type EpollEvent struct { @@ -642,8 +693,15 @@ type EpollEvent struct { } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -665,7 +723,7 @@ const ( ) type Sigset_t struct { - X__val [16]uint64 + Val [16]uint64 } const RNDGETENTCNT = 0x40045200 @@ -692,11 +750,11 @@ type Winsize struct { type Taskstats struct { Version uint16 - Pad_cgo_0 [2]byte + _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - Pad_cgo_1 [6]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 @@ -708,13 +766,13 @@ type Taskstats struct { Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 - Pad_cgo_2 [4]byte + _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 - Pad_cgo_3 [4]byte + _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 @@ -758,6 +816,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -790,3 +866,951 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint64 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x40 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x8000000000000000 + CBitFieldMaskBit1 = 0x4000000000000000 + CBitFieldMaskBit2 = 0x2000000000000000 + CBitFieldMaskBit3 = 0x1000000000000000 + CBitFieldMaskBit4 = 0x800000000000000 + CBitFieldMaskBit5 = 0x400000000000000 + CBitFieldMaskBit6 = 0x200000000000000 + CBitFieldMaskBit7 = 0x100000000000000 + CBitFieldMaskBit8 = 0x80000000000000 + CBitFieldMaskBit9 = 0x40000000000000 + CBitFieldMaskBit10 = 0x20000000000000 + CBitFieldMaskBit11 = 0x10000000000000 + CBitFieldMaskBit12 = 0x8000000000000 + CBitFieldMaskBit13 = 0x4000000000000 + CBitFieldMaskBit14 = 0x2000000000000 + CBitFieldMaskBit15 = 0x1000000000000 + CBitFieldMaskBit16 = 0x800000000000 + CBitFieldMaskBit17 = 0x400000000000 + CBitFieldMaskBit18 = 0x200000000000 + CBitFieldMaskBit19 = 0x100000000000 + CBitFieldMaskBit20 = 0x80000000000 + CBitFieldMaskBit21 = 0x40000000000 + CBitFieldMaskBit22 = 0x20000000000 + CBitFieldMaskBit23 = 0x10000000000 + CBitFieldMaskBit24 = 0x8000000000 + CBitFieldMaskBit25 = 0x4000000000 + CBitFieldMaskBit26 = 0x2000000000 + CBitFieldMaskBit27 = 0x1000000000 + CBitFieldMaskBit28 = 0x800000000 + CBitFieldMaskBit29 = 0x400000000 + CBitFieldMaskBit30 = 0x200000000 + CBitFieldMaskBit31 = 0x100000000 + CBitFieldMaskBit32 = 0x80000000 + CBitFieldMaskBit33 = 0x40000000 + CBitFieldMaskBit34 = 0x20000000 + CBitFieldMaskBit35 = 0x10000000 + CBitFieldMaskBit36 = 0x8000000 + CBitFieldMaskBit37 = 0x4000000 + CBitFieldMaskBit38 = 0x2000000 + CBitFieldMaskBit39 = 0x1000000 + CBitFieldMaskBit40 = 0x800000 + CBitFieldMaskBit41 = 0x400000 + CBitFieldMaskBit42 = 0x200000 + CBitFieldMaskBit43 = 0x100000 + CBitFieldMaskBit44 = 0x80000 + CBitFieldMaskBit45 = 0x40000 + CBitFieldMaskBit46 = 0x20000 + CBitFieldMaskBit47 = 0x10000 + CBitFieldMaskBit48 = 0x8000 + CBitFieldMaskBit49 = 0x4000 + CBitFieldMaskBit50 = 0x2000 + CBitFieldMaskBit51 = 0x1000 + CBitFieldMaskBit52 = 0x800 + CBitFieldMaskBit53 = 0x400 + CBitFieldMaskBit54 = 0x200 + CBitFieldMaskBit55 = 0x100 + CBitFieldMaskBit56 = 0x80 + CBitFieldMaskBit57 = 0x40 + CBitFieldMaskBit58 = 0x20 + CBitFieldMaskBit59 = 0x10 + CBitFieldMaskBit60 = 0x8 + CBitFieldMaskBit61 = 0x4 + CBitFieldMaskBit62 = 0x2 + CBitFieldMaskBit63 = 0x1 +) + +type SockaddrStorage struct { + Family uint16 + _ [118]int8 + _ uint64 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + _ [4]byte + Start uint64 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type int64 + Bsize int64 + Frsize int64 + Blocks uint64 + Bfree uint64 + Files uint64 + Ffree uint64 + Bavail uint64 + Fsid Fsid + Namelen int64 + Flags int64 + Spare [5]int64 +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint64 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 + _ [4]byte +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x20 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go index 15e6b4b4b1..a9d0131f2e 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mips64le.go @@ -33,13 +33,13 @@ type Timeval struct { type Timex struct { Modes uint32 - Pad_cgo_0 [4]byte + _ [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 - Pad_cgo_1 [4]byte + _ [4]byte Constant int64 Precision int64 Tolerance int64 @@ -48,14 +48,14 @@ type Timex struct { Ppsfreq int64 Jitter int64 Shift int32 - Pad_cgo_2 [4]byte + _ [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 - Pad_cgo_3 [44]byte + _ [44]byte } type Time_t int64 @@ -117,42 +117,57 @@ type Stat_t struct { Blocks int64 } -type Statfs_t struct { - Type int64 - Bsize int64 - Frsize int64 - Blocks uint64 - Bfree uint64 - Files uint64 - Ffree uint64 - Bavail uint64 - Fsid Fsid - Namelen int64 - Flags int64 - Spare [5]int64 +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]int8 - Pad_cgo_0 [5]byte + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]int8 + _ [5]byte } type Fsid struct { - X__val [2]int32 + Val [2]int32 } type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte + Type int16 + Whence int16 + _ [4]byte + Start int64 + Len int64 + Pid int32 + _ [4]byte } type FscryptPolicy struct { @@ -227,11 +242,20 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { - Family uint16 - Pad_cgo_0 [2]byte - Ifindex int32 - Addr [8]byte + Family uint16 + _ [2]byte + Ifindex int32 + Addr [8]byte } type RawSockaddrALG struct { @@ -298,13 +322,13 @@ type PacketMreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 - Pad_cgo_1 [4]byte + _ [4]byte } type Cmsghdr struct { @@ -346,7 +370,7 @@ type TCPInfo struct { Probes uint8 Backoff uint8 Options uint8 - Pad_cgo_0 [2]byte + _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 @@ -381,6 +405,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -401,97 +426,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -522,12 +573,12 @@ type RtAttr struct { } type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 + Family uint8 + _ uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 } type IfAddrmsg struct { @@ -570,9 +621,9 @@ type SockFilter struct { } type SockFprog struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *SockFilter + Len uint16 + _ [6]byte + Filter *SockFilter } type InotifyEvent struct { @@ -609,12 +660,12 @@ type Sysinfo_t struct { Freeswap uint64 Procs uint16 Pad uint16 - Pad_cgo_0 [4]byte + _ [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 - X_f [0]int8 - Pad_cgo_1 [4]byte + _ [0]int8 + _ [4]byte } type Utsname struct { @@ -627,12 +678,12 @@ type Utsname struct { } type Ustat_t struct { - Tfree int32 - Pad_cgo_0 [4]byte - Tinode uint64 - Fname [6]int8 - Fpack [6]int8 - Pad_cgo_1 [4]byte + Tfree int32 + _ [4]byte + Tinode uint64 + Fname [6]int8 + Fpack [6]int8 + _ [4]byte } type EpollEvent struct { @@ -642,8 +693,15 @@ type EpollEvent struct { } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -665,7 +723,7 @@ const ( ) type Sigset_t struct { - X__val [16]uint64 + Val [16]uint64 } const RNDGETENTCNT = 0x40045200 @@ -692,11 +750,11 @@ type Winsize struct { type Taskstats struct { Version uint16 - Pad_cgo_0 [2]byte + _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - Pad_cgo_1 [6]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 @@ -708,13 +766,13 @@ type Taskstats struct { Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 - Pad_cgo_2 [4]byte + _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 - Pad_cgo_3 [4]byte + _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 @@ -758,6 +816,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -790,3 +866,951 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint64 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x40 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x1 + CBitFieldMaskBit1 = 0x2 + CBitFieldMaskBit2 = 0x4 + CBitFieldMaskBit3 = 0x8 + CBitFieldMaskBit4 = 0x10 + CBitFieldMaskBit5 = 0x20 + CBitFieldMaskBit6 = 0x40 + CBitFieldMaskBit7 = 0x80 + CBitFieldMaskBit8 = 0x100 + CBitFieldMaskBit9 = 0x200 + CBitFieldMaskBit10 = 0x400 + CBitFieldMaskBit11 = 0x800 + CBitFieldMaskBit12 = 0x1000 + CBitFieldMaskBit13 = 0x2000 + CBitFieldMaskBit14 = 0x4000 + CBitFieldMaskBit15 = 0x8000 + CBitFieldMaskBit16 = 0x10000 + CBitFieldMaskBit17 = 0x20000 + CBitFieldMaskBit18 = 0x40000 + CBitFieldMaskBit19 = 0x80000 + CBitFieldMaskBit20 = 0x100000 + CBitFieldMaskBit21 = 0x200000 + CBitFieldMaskBit22 = 0x400000 + CBitFieldMaskBit23 = 0x800000 + CBitFieldMaskBit24 = 0x1000000 + CBitFieldMaskBit25 = 0x2000000 + CBitFieldMaskBit26 = 0x4000000 + CBitFieldMaskBit27 = 0x8000000 + CBitFieldMaskBit28 = 0x10000000 + CBitFieldMaskBit29 = 0x20000000 + CBitFieldMaskBit30 = 0x40000000 + CBitFieldMaskBit31 = 0x80000000 + CBitFieldMaskBit32 = 0x100000000 + CBitFieldMaskBit33 = 0x200000000 + CBitFieldMaskBit34 = 0x400000000 + CBitFieldMaskBit35 = 0x800000000 + CBitFieldMaskBit36 = 0x1000000000 + CBitFieldMaskBit37 = 0x2000000000 + CBitFieldMaskBit38 = 0x4000000000 + CBitFieldMaskBit39 = 0x8000000000 + CBitFieldMaskBit40 = 0x10000000000 + CBitFieldMaskBit41 = 0x20000000000 + CBitFieldMaskBit42 = 0x40000000000 + CBitFieldMaskBit43 = 0x80000000000 + CBitFieldMaskBit44 = 0x100000000000 + CBitFieldMaskBit45 = 0x200000000000 + CBitFieldMaskBit46 = 0x400000000000 + CBitFieldMaskBit47 = 0x800000000000 + CBitFieldMaskBit48 = 0x1000000000000 + CBitFieldMaskBit49 = 0x2000000000000 + CBitFieldMaskBit50 = 0x4000000000000 + CBitFieldMaskBit51 = 0x8000000000000 + CBitFieldMaskBit52 = 0x10000000000000 + CBitFieldMaskBit53 = 0x20000000000000 + CBitFieldMaskBit54 = 0x40000000000000 + CBitFieldMaskBit55 = 0x80000000000000 + CBitFieldMaskBit56 = 0x100000000000000 + CBitFieldMaskBit57 = 0x200000000000000 + CBitFieldMaskBit58 = 0x400000000000000 + CBitFieldMaskBit59 = 0x800000000000000 + CBitFieldMaskBit60 = 0x1000000000000000 + CBitFieldMaskBit61 = 0x2000000000000000 + CBitFieldMaskBit62 = 0x4000000000000000 + CBitFieldMaskBit63 = 0x8000000000000000 +) + +type SockaddrStorage struct { + Family uint16 + _ [118]int8 + _ uint64 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + _ [4]byte + Start uint64 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type int64 + Bsize int64 + Frsize int64 + Blocks uint64 + Bfree uint64 + Files uint64 + Ffree uint64 + Bavail uint64 + Fsid Fsid + Namelen int64 + Flags int64 + Spare [5]int64 +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint64 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 + _ [4]byte +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x20 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go index b6c2d32dd8..4f6f145556 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go @@ -52,7 +52,7 @@ type Timex struct { Errcnt int32 Stbcnt int32 Tai int32 - Pad_cgo_0 [44]byte + _ [44]byte } type Time_t int32 @@ -115,44 +115,57 @@ type Stat_t struct { Pad5 [14]int32 } -type Statfs_t struct { - Type int32 - Bsize int32 - Frsize int32 - Pad_cgo_0 [4]byte - Blocks uint64 - Bfree uint64 - Files uint64 - Ffree uint64 - Bavail uint64 - Fsid Fsid - Namelen int32 - Flags int32 - Spare [5]int32 - Pad_cgo_1 [4]byte +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]int8 - Pad_cgo_0 [5]byte + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]int8 + _ [5]byte } type Fsid struct { - X__val [2]int32 + Val [2]int32 } type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte + Type int16 + Whence int16 + _ [4]byte + Start int64 + Len int64 + Pid int32 + _ [4]byte } type FscryptPolicy struct { @@ -227,11 +240,20 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { - Family uint16 - Pad_cgo_0 [2]byte - Ifindex int32 - Addr [8]byte + Family uint16 + _ [2]byte + Ifindex int32 + Addr [8]byte } type RawSockaddrALG struct { @@ -344,7 +366,7 @@ type TCPInfo struct { Probes uint8 Backoff uint8 Options uint8 - Pad_cgo_0 [2]byte + _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 @@ -379,6 +401,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -399,97 +422,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -520,12 +569,12 @@ type RtAttr struct { } type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 + Family uint8 + _ uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 } type IfAddrmsg struct { @@ -568,9 +617,9 @@ type SockFilter struct { } type SockFprog struct { - Len uint16 - Pad_cgo_0 [2]byte - Filter *SockFilter + Len uint16 + _ [2]byte + Filter *SockFilter } type InotifyEvent struct { @@ -610,7 +659,7 @@ type Sysinfo_t struct { Totalhigh uint32 Freehigh uint32 Unit uint32 - X_f [8]int8 + _ [8]int8 } type Utsname struct { @@ -637,8 +686,15 @@ type EpollEvent struct { } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -660,7 +716,7 @@ const ( ) type Sigset_t struct { - X__val [32]uint32 + Val [32]uint32 } const RNDGETENTCNT = 0x40045200 @@ -687,11 +743,11 @@ type Winsize struct { type Taskstats struct { Version uint16 - Pad_cgo_0 [2]byte + _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - Pad_cgo_1 [6]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 @@ -703,13 +759,13 @@ type Taskstats struct { Ac_comm [32]int8 Ac_sched uint8 Ac_pad [3]uint8 - Pad_cgo_2 [4]byte + _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 - Pad_cgo_3 [4]byte + _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 @@ -753,6 +809,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -785,3 +859,951 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint32 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x20 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x1 + CBitFieldMaskBit1 = 0x2 + CBitFieldMaskBit2 = 0x4 + CBitFieldMaskBit3 = 0x8 + CBitFieldMaskBit4 = 0x10 + CBitFieldMaskBit5 = 0x20 + CBitFieldMaskBit6 = 0x40 + CBitFieldMaskBit7 = 0x80 + CBitFieldMaskBit8 = 0x100 + CBitFieldMaskBit9 = 0x200 + CBitFieldMaskBit10 = 0x400 + CBitFieldMaskBit11 = 0x800 + CBitFieldMaskBit12 = 0x1000 + CBitFieldMaskBit13 = 0x2000 + CBitFieldMaskBit14 = 0x4000 + CBitFieldMaskBit15 = 0x8000 + CBitFieldMaskBit16 = 0x10000 + CBitFieldMaskBit17 = 0x20000 + CBitFieldMaskBit18 = 0x40000 + CBitFieldMaskBit19 = 0x80000 + CBitFieldMaskBit20 = 0x100000 + CBitFieldMaskBit21 = 0x200000 + CBitFieldMaskBit22 = 0x400000 + CBitFieldMaskBit23 = 0x800000 + CBitFieldMaskBit24 = 0x1000000 + CBitFieldMaskBit25 = 0x2000000 + CBitFieldMaskBit26 = 0x4000000 + CBitFieldMaskBit27 = 0x8000000 + CBitFieldMaskBit28 = 0x10000000 + CBitFieldMaskBit29 = 0x20000000 + CBitFieldMaskBit30 = 0x40000000 + CBitFieldMaskBit31 = 0x80000000 + CBitFieldMaskBit32 = 0x100000000 + CBitFieldMaskBit33 = 0x200000000 + CBitFieldMaskBit34 = 0x400000000 + CBitFieldMaskBit35 = 0x800000000 + CBitFieldMaskBit36 = 0x1000000000 + CBitFieldMaskBit37 = 0x2000000000 + CBitFieldMaskBit38 = 0x4000000000 + CBitFieldMaskBit39 = 0x8000000000 + CBitFieldMaskBit40 = 0x10000000000 + CBitFieldMaskBit41 = 0x20000000000 + CBitFieldMaskBit42 = 0x40000000000 + CBitFieldMaskBit43 = 0x80000000000 + CBitFieldMaskBit44 = 0x100000000000 + CBitFieldMaskBit45 = 0x200000000000 + CBitFieldMaskBit46 = 0x400000000000 + CBitFieldMaskBit47 = 0x800000000000 + CBitFieldMaskBit48 = 0x1000000000000 + CBitFieldMaskBit49 = 0x2000000000000 + CBitFieldMaskBit50 = 0x4000000000000 + CBitFieldMaskBit51 = 0x8000000000000 + CBitFieldMaskBit52 = 0x10000000000000 + CBitFieldMaskBit53 = 0x20000000000000 + CBitFieldMaskBit54 = 0x40000000000000 + CBitFieldMaskBit55 = 0x80000000000000 + CBitFieldMaskBit56 = 0x100000000000000 + CBitFieldMaskBit57 = 0x200000000000000 + CBitFieldMaskBit58 = 0x400000000000000 + CBitFieldMaskBit59 = 0x800000000000000 + CBitFieldMaskBit60 = 0x1000000000000000 + CBitFieldMaskBit61 = 0x2000000000000000 + CBitFieldMaskBit62 = 0x4000000000000000 + CBitFieldMaskBit63 = 0x8000000000000000 +) + +type SockaddrStorage struct { + Family uint16 + _ [122]int8 + _ uint32 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + Start uint32 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type int32 + Bsize int32 + Frsize int32 + _ [4]byte + Blocks uint64 + Bfree uint64 + Files uint64 + Ffree uint64 + Bavail uint64 + Fsid Fsid + Namelen int32 + Flags int32 + Spare [5]int32 + _ [4]byte +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x18 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go index 3803e1062b..9ddd47015e 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go @@ -33,13 +33,13 @@ type Timeval struct { type Timex struct { Modes uint32 - Pad_cgo_0 [4]byte + _ [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 - Pad_cgo_1 [4]byte + _ [4]byte Constant int64 Precision int64 Tolerance int64 @@ -48,14 +48,14 @@ type Timex struct { Ppsfreq int64 Jitter int64 Shift int32 - Pad_cgo_2 [4]byte + _ [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 - Pad_cgo_3 [44]byte + _ [44]byte } type Time_t int64 @@ -105,7 +105,7 @@ type Stat_t struct { Mode uint32 Uid uint32 Gid uint32 - X__pad2 int32 + _ int32 Rdev uint64 Size int64 Blksize int64 @@ -118,42 +118,57 @@ type Stat_t struct { _ uint64 } -type Statfs_t struct { - Type int64 - Bsize int64 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int64 - Frsize int64 - Flags int64 - Spare [4]int64 +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]uint8 - Pad_cgo_0 [5]byte + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]uint8 + _ [5]byte } type Fsid struct { - X__val [2]int32 + Val [2]int32 } type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte + Type int16 + Whence int16 + _ [4]byte + Start int64 + Len int64 + Pid int32 + _ [4]byte } type FscryptPolicy struct { @@ -228,11 +243,20 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { - Family uint16 - Pad_cgo_0 [2]byte - Ifindex int32 - Addr [8]byte + Family uint16 + _ [2]byte + Ifindex int32 + Addr [8]byte } type RawSockaddrALG struct { @@ -299,13 +323,13 @@ type PacketMreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 - Pad_cgo_1 [4]byte + _ [4]byte } type Cmsghdr struct { @@ -347,7 +371,7 @@ type TCPInfo struct { Probes uint8 Backoff uint8 Options uint8 - Pad_cgo_0 [2]byte + _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 @@ -382,6 +406,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -402,97 +427,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -523,12 +574,12 @@ type RtAttr struct { } type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 + Family uint8 + _ uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 } type IfAddrmsg struct { @@ -571,9 +622,9 @@ type SockFilter struct { } type SockFprog struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *SockFilter + Len uint16 + _ [6]byte + Filter *SockFilter } type InotifyEvent struct { @@ -616,12 +667,12 @@ type Sysinfo_t struct { Freeswap uint64 Procs uint16 Pad uint16 - Pad_cgo_0 [4]byte + _ [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 - X_f [0]uint8 - Pad_cgo_1 [4]byte + _ [0]uint8 + _ [4]byte } type Utsname struct { @@ -634,24 +685,31 @@ type Utsname struct { } type Ustat_t struct { - Tfree int32 - Pad_cgo_0 [4]byte - Tinode uint64 - Fname [6]uint8 - Fpack [6]uint8 - Pad_cgo_1 [4]byte + Tfree int32 + _ [4]byte + Tinode uint64 + Fname [6]uint8 + Fpack [6]uint8 + _ [4]byte } type EpollEvent struct { - Events uint32 - X_padFd int32 - Fd int32 - Pad int32 + Events uint32 + _ int32 + Fd int32 + Pad int32 } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -673,7 +731,7 @@ const ( ) type Sigset_t struct { - X__val [16]uint64 + Val [16]uint64 } const RNDGETENTCNT = 0x40045200 @@ -700,11 +758,11 @@ type Winsize struct { type Taskstats struct { Version uint16 - Pad_cgo_0 [2]byte + _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - Pad_cgo_1 [6]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 @@ -716,13 +774,13 @@ type Taskstats struct { Ac_comm [32]uint8 Ac_sched uint8 Ac_pad [3]uint8 - Pad_cgo_2 [4]byte + _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 - Pad_cgo_3 [4]byte + _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 @@ -766,6 +824,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -798,3 +874,951 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint64 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x40 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x8000000000000000 + CBitFieldMaskBit1 = 0x4000000000000000 + CBitFieldMaskBit2 = 0x2000000000000000 + CBitFieldMaskBit3 = 0x1000000000000000 + CBitFieldMaskBit4 = 0x800000000000000 + CBitFieldMaskBit5 = 0x400000000000000 + CBitFieldMaskBit6 = 0x200000000000000 + CBitFieldMaskBit7 = 0x100000000000000 + CBitFieldMaskBit8 = 0x80000000000000 + CBitFieldMaskBit9 = 0x40000000000000 + CBitFieldMaskBit10 = 0x20000000000000 + CBitFieldMaskBit11 = 0x10000000000000 + CBitFieldMaskBit12 = 0x8000000000000 + CBitFieldMaskBit13 = 0x4000000000000 + CBitFieldMaskBit14 = 0x2000000000000 + CBitFieldMaskBit15 = 0x1000000000000 + CBitFieldMaskBit16 = 0x800000000000 + CBitFieldMaskBit17 = 0x400000000000 + CBitFieldMaskBit18 = 0x200000000000 + CBitFieldMaskBit19 = 0x100000000000 + CBitFieldMaskBit20 = 0x80000000000 + CBitFieldMaskBit21 = 0x40000000000 + CBitFieldMaskBit22 = 0x20000000000 + CBitFieldMaskBit23 = 0x10000000000 + CBitFieldMaskBit24 = 0x8000000000 + CBitFieldMaskBit25 = 0x4000000000 + CBitFieldMaskBit26 = 0x2000000000 + CBitFieldMaskBit27 = 0x1000000000 + CBitFieldMaskBit28 = 0x800000000 + CBitFieldMaskBit29 = 0x400000000 + CBitFieldMaskBit30 = 0x200000000 + CBitFieldMaskBit31 = 0x100000000 + CBitFieldMaskBit32 = 0x80000000 + CBitFieldMaskBit33 = 0x40000000 + CBitFieldMaskBit34 = 0x20000000 + CBitFieldMaskBit35 = 0x10000000 + CBitFieldMaskBit36 = 0x8000000 + CBitFieldMaskBit37 = 0x4000000 + CBitFieldMaskBit38 = 0x2000000 + CBitFieldMaskBit39 = 0x1000000 + CBitFieldMaskBit40 = 0x800000 + CBitFieldMaskBit41 = 0x400000 + CBitFieldMaskBit42 = 0x200000 + CBitFieldMaskBit43 = 0x100000 + CBitFieldMaskBit44 = 0x80000 + CBitFieldMaskBit45 = 0x40000 + CBitFieldMaskBit46 = 0x20000 + CBitFieldMaskBit47 = 0x10000 + CBitFieldMaskBit48 = 0x8000 + CBitFieldMaskBit49 = 0x4000 + CBitFieldMaskBit50 = 0x2000 + CBitFieldMaskBit51 = 0x1000 + CBitFieldMaskBit52 = 0x800 + CBitFieldMaskBit53 = 0x400 + CBitFieldMaskBit54 = 0x200 + CBitFieldMaskBit55 = 0x100 + CBitFieldMaskBit56 = 0x80 + CBitFieldMaskBit57 = 0x40 + CBitFieldMaskBit58 = 0x20 + CBitFieldMaskBit59 = 0x10 + CBitFieldMaskBit60 = 0x8 + CBitFieldMaskBit61 = 0x4 + CBitFieldMaskBit62 = 0x2 + CBitFieldMaskBit63 = 0x1 +) + +type SockaddrStorage struct { + Family uint16 + _ [118]uint8 + _ uint64 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + _ [4]byte + Start uint64 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type int64 + Bsize int64 + Blocks uint64 + Bfree uint64 + Bavail uint64 + Files uint64 + Ffree uint64 + Fsid Fsid + Namelen int64 + Frsize int64 + Flags int64 + Spare [4]int64 +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint64 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 + _ [4]byte +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x20 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go index 7ef31fe213..3a5cc696ec 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go @@ -33,13 +33,13 @@ type Timeval struct { type Timex struct { Modes uint32 - Pad_cgo_0 [4]byte + _ [4]byte Offset int64 Freq int64 Maxerror int64 Esterror int64 Status int32 - Pad_cgo_1 [4]byte + _ [4]byte Constant int64 Precision int64 Tolerance int64 @@ -48,14 +48,14 @@ type Timex struct { Ppsfreq int64 Jitter int64 Shift int32 - Pad_cgo_2 [4]byte + _ [4]byte Stabil int64 Jitcnt int64 Calcnt int64 Errcnt int64 Stbcnt int64 Tai int32 - Pad_cgo_3 [44]byte + _ [44]byte } type Time_t int64 @@ -105,7 +105,7 @@ type Stat_t struct { Mode uint32 Uid uint32 Gid uint32 - X__pad2 int32 + _ int32 Rdev uint64 Size int64 Blksize int64 @@ -118,42 +118,57 @@ type Stat_t struct { _ uint64 } -type Statfs_t struct { - Type int64 - Bsize int64 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen int64 - Frsize int64 - Flags int64 - Spare [4]int64 +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Type uint8 - Name [256]uint8 - Pad_cgo_0 [5]byte + Ino uint64 + Off int64 + Reclen uint16 + Type uint8 + Name [256]uint8 + _ [5]byte } type Fsid struct { - X__val [2]int32 + Val [2]int32 } type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Pid int32 - Pad_cgo_1 [4]byte + Type int16 + Whence int16 + _ [4]byte + Start int64 + Len int64 + Pid int32 + _ [4]byte } type FscryptPolicy struct { @@ -228,11 +243,20 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { - Family uint16 - Pad_cgo_0 [2]byte - Ifindex int32 - Addr [8]byte + Family uint16 + _ [2]byte + Ifindex int32 + Addr [8]byte } type RawSockaddrALG struct { @@ -299,13 +323,13 @@ type PacketMreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen uint64 Control *byte Controllen uint64 Flags int32 - Pad_cgo_1 [4]byte + _ [4]byte } type Cmsghdr struct { @@ -347,7 +371,7 @@ type TCPInfo struct { Probes uint8 Backoff uint8 Options uint8 - Pad_cgo_0 [2]byte + _ [2]byte Rto uint32 Ato uint32 Snd_mss uint32 @@ -382,6 +406,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -402,97 +427,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -523,12 +574,12 @@ type RtAttr struct { } type IfInfomsg struct { - Family uint8 - X__ifi_pad uint8 - Type uint16 - Index int32 - Flags uint32 - Change uint32 + Family uint8 + _ uint8 + Type uint16 + Index int32 + Flags uint32 + Change uint32 } type IfAddrmsg struct { @@ -571,9 +622,9 @@ type SockFilter struct { } type SockFprog struct { - Len uint16 - Pad_cgo_0 [6]byte - Filter *SockFilter + Len uint16 + _ [6]byte + Filter *SockFilter } type InotifyEvent struct { @@ -616,12 +667,12 @@ type Sysinfo_t struct { Freeswap uint64 Procs uint16 Pad uint16 - Pad_cgo_0 [4]byte + _ [4]byte Totalhigh uint64 Freehigh uint64 Unit uint32 - X_f [0]uint8 - Pad_cgo_1 [4]byte + _ [0]uint8 + _ [4]byte } type Utsname struct { @@ -634,24 +685,31 @@ type Utsname struct { } type Ustat_t struct { - Tfree int32 - Pad_cgo_0 [4]byte - Tinode uint64 - Fname [6]uint8 - Fpack [6]uint8 - Pad_cgo_1 [4]byte + Tfree int32 + _ [4]byte + Tinode uint64 + Fname [6]uint8 + Fpack [6]uint8 + _ [4]byte } type EpollEvent struct { - Events uint32 - X_padFd int32 - Fd int32 - Pad int32 + Events uint32 + _ int32 + Fd int32 + Pad int32 } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -673,7 +731,7 @@ const ( ) type Sigset_t struct { - X__val [16]uint64 + Val [16]uint64 } const RNDGETENTCNT = 0x40045200 @@ -700,11 +758,11 @@ type Winsize struct { type Taskstats struct { Version uint16 - Pad_cgo_0 [2]byte + _ [2]byte Ac_exitcode uint32 Ac_flag uint8 Ac_nice uint8 - Pad_cgo_1 [6]byte + _ [6]byte Cpu_count uint64 Cpu_delay_total uint64 Blkio_count uint64 @@ -716,13 +774,13 @@ type Taskstats struct { Ac_comm [32]uint8 Ac_sched uint8 Ac_pad [3]uint8 - Pad_cgo_2 [4]byte + _ [4]byte Ac_uid uint32 Ac_gid uint32 Ac_pid uint32 Ac_ppid uint32 Ac_btime uint32 - Pad_cgo_3 [4]byte + _ [4]byte Ac_etime uint64 Ac_utime uint64 Ac_stime uint64 @@ -766,6 +824,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -798,3 +874,951 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint64 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x40 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x1 + CBitFieldMaskBit1 = 0x2 + CBitFieldMaskBit2 = 0x4 + CBitFieldMaskBit3 = 0x8 + CBitFieldMaskBit4 = 0x10 + CBitFieldMaskBit5 = 0x20 + CBitFieldMaskBit6 = 0x40 + CBitFieldMaskBit7 = 0x80 + CBitFieldMaskBit8 = 0x100 + CBitFieldMaskBit9 = 0x200 + CBitFieldMaskBit10 = 0x400 + CBitFieldMaskBit11 = 0x800 + CBitFieldMaskBit12 = 0x1000 + CBitFieldMaskBit13 = 0x2000 + CBitFieldMaskBit14 = 0x4000 + CBitFieldMaskBit15 = 0x8000 + CBitFieldMaskBit16 = 0x10000 + CBitFieldMaskBit17 = 0x20000 + CBitFieldMaskBit18 = 0x40000 + CBitFieldMaskBit19 = 0x80000 + CBitFieldMaskBit20 = 0x100000 + CBitFieldMaskBit21 = 0x200000 + CBitFieldMaskBit22 = 0x400000 + CBitFieldMaskBit23 = 0x800000 + CBitFieldMaskBit24 = 0x1000000 + CBitFieldMaskBit25 = 0x2000000 + CBitFieldMaskBit26 = 0x4000000 + CBitFieldMaskBit27 = 0x8000000 + CBitFieldMaskBit28 = 0x10000000 + CBitFieldMaskBit29 = 0x20000000 + CBitFieldMaskBit30 = 0x40000000 + CBitFieldMaskBit31 = 0x80000000 + CBitFieldMaskBit32 = 0x100000000 + CBitFieldMaskBit33 = 0x200000000 + CBitFieldMaskBit34 = 0x400000000 + CBitFieldMaskBit35 = 0x800000000 + CBitFieldMaskBit36 = 0x1000000000 + CBitFieldMaskBit37 = 0x2000000000 + CBitFieldMaskBit38 = 0x4000000000 + CBitFieldMaskBit39 = 0x8000000000 + CBitFieldMaskBit40 = 0x10000000000 + CBitFieldMaskBit41 = 0x20000000000 + CBitFieldMaskBit42 = 0x40000000000 + CBitFieldMaskBit43 = 0x80000000000 + CBitFieldMaskBit44 = 0x100000000000 + CBitFieldMaskBit45 = 0x200000000000 + CBitFieldMaskBit46 = 0x400000000000 + CBitFieldMaskBit47 = 0x800000000000 + CBitFieldMaskBit48 = 0x1000000000000 + CBitFieldMaskBit49 = 0x2000000000000 + CBitFieldMaskBit50 = 0x4000000000000 + CBitFieldMaskBit51 = 0x8000000000000 + CBitFieldMaskBit52 = 0x10000000000000 + CBitFieldMaskBit53 = 0x20000000000000 + CBitFieldMaskBit54 = 0x40000000000000 + CBitFieldMaskBit55 = 0x80000000000000 + CBitFieldMaskBit56 = 0x100000000000000 + CBitFieldMaskBit57 = 0x200000000000000 + CBitFieldMaskBit58 = 0x400000000000000 + CBitFieldMaskBit59 = 0x800000000000000 + CBitFieldMaskBit60 = 0x1000000000000000 + CBitFieldMaskBit61 = 0x2000000000000000 + CBitFieldMaskBit62 = 0x4000000000000000 + CBitFieldMaskBit63 = 0x8000000000000000 +) + +type SockaddrStorage struct { + Family uint16 + _ [118]uint8 + _ uint64 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + _ [4]byte + Start uint64 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type int64 + Bsize int64 + Blocks uint64 + Bfree uint64 + Bavail uint64 + Files uint64 + Ffree uint64 + Fsid Fsid + Namelen int64 + Frsize int64 + Flags int64 + Spare [4]int64 +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint64 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 + _ [4]byte +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x20 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go index cb194f4717..032a71bbfe 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_s390x.go @@ -116,20 +116,34 @@ type Stat_t struct { _ [3]int64 } -type Statfs_t struct { - Type uint32 - Bsize uint32 - Blocks uint64 - Bfree uint64 - Bavail uint64 - Files uint64 - Ffree uint64 - Fsid Fsid - Namelen uint32 - Frsize uint32 - Flags uint32 - Spare [4]uint32 - _ [4]byte +type StatxTimestamp struct { + Sec int64 + Nsec uint32 + _ int32 +} + +type Statx_t struct { + Mask uint32 + Blksize uint32 + Attributes uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Mode uint16 + _ [1]uint16 + Ino uint64 + Size uint64 + Blocks uint64 + Attributes_mask uint64 + Atime StatxTimestamp + Btime StatxTimestamp + Ctime StatxTimestamp + Mtime StatxTimestamp + Rdev_major uint32 + Rdev_minor uint32 + Dev_major uint32 + Dev_minor uint32 + _ [14]uint64 } type Dirent struct { @@ -142,7 +156,7 @@ type Dirent struct { } type Fsid struct { - _ [2]int32 + Val [2]int32 } type Flock_t struct { @@ -227,6 +241,15 @@ type RawSockaddrHCI struct { Channel uint16 } +type RawSockaddrL2 struct { + Family uint16 + Psm uint16 + Bdaddr [6]uint8 + Cid uint16 + Bdaddr_type uint8 + _ [1]byte +} + type RawSockaddrCAN struct { Family uint16 _ [2]byte @@ -381,6 +404,7 @@ const ( SizeofSockaddrLinklayer = 0x14 SizeofSockaddrNetlink = 0xc SizeofSockaddrHCI = 0x6 + SizeofSockaddrL2 = 0xe SizeofSockaddrCAN = 0x10 SizeofSockaddrALG = 0x58 SizeofSockaddrVM = 0x10 @@ -401,97 +425,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2c - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x31 + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { @@ -667,8 +717,15 @@ type EpollEvent struct { } const ( - AT_FDCWD = -0x64 - AT_REMOVEDIR = 0x200 + AT_EMPTY_PATH = 0x1000 + AT_FDCWD = -0x64 + AT_NO_AUTOMOUNT = 0x800 + AT_REMOVEDIR = 0x200 + + AT_STATX_SYNC_AS_STAT = 0x0 + AT_STATX_FORCE_SYNC = 0x2000 + AT_STATX_DONT_SYNC = 0x4000 + AT_SYMLINK_FOLLOW = 0x400 AT_SYMLINK_NOFOLLOW = 0x100 ) @@ -690,7 +747,7 @@ const ( ) type Sigset_t struct { - _ [16]uint64 + Val [16]uint64 } const RNDGETENTCNT = 0x80045200 @@ -783,6 +840,24 @@ const ( TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4 ) +type CGroupStats struct { + Sleeping uint64 + Running uint64 + Stopped uint64 + Uninterruptible uint64 + Io_wait uint64 +} + +const ( + CGROUPSTATS_CMD_UNSPEC = 0x3 + CGROUPSTATS_CMD_GET = 0x4 + CGROUPSTATS_CMD_NEW = 0x5 + CGROUPSTATS_TYPE_UNSPEC = 0x0 + CGROUPSTATS_TYPE_CGROUP_STATS = 0x1 + CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0 + CGROUPSTATS_CMD_ATTR_FD = 0x1 +) + type Genlmsghdr struct { Cmd uint8 Version uint8 @@ -815,3 +890,952 @@ const ( CTRL_ATTR_MCAST_GRP_NAME = 0x1 CTRL_ATTR_MCAST_GRP_ID = 0x2 ) + +type cpuMask uint64 + +const ( + _CPU_SETSIZE = 0x400 + _NCPUBITS = 0x40 +) + +const ( + BDADDR_BREDR = 0x0 + BDADDR_LE_PUBLIC = 0x1 + BDADDR_LE_RANDOM = 0x2 +) + +type PerfEventAttr struct { + Type uint32 + Size uint32 + Config uint64 + Sample uint64 + Sample_type uint64 + Read_format uint64 + Bits uint64 + Wakeup uint32 + Bp_type uint32 + Ext1 uint64 + Ext2 uint64 + Branch_sample_type uint64 + Sample_regs_user uint64 + Sample_stack_user uint32 + Clockid int32 + Sample_regs_intr uint64 + Aux_watermark uint32 + _ uint32 +} + +type PerfEventMmapPage struct { + Version uint32 + Compat_version uint32 + Lock uint32 + Index uint32 + Offset int64 + Time_enabled uint64 + Time_running uint64 + Capabilities uint64 + Pmc_width uint16 + Time_shift uint16 + Time_mult uint32 + Time_offset uint64 + Time_zero uint64 + Size uint32 + _ [948]uint8 + Data_head uint64 + Data_tail uint64 + Data_offset uint64 + Data_size uint64 + Aux_head uint64 + Aux_tail uint64 + Aux_offset uint64 + Aux_size uint64 +} + +const ( + PerfBitDisabled uint64 = CBitFieldMaskBit0 + PerfBitInherit = CBitFieldMaskBit1 + PerfBitPinned = CBitFieldMaskBit2 + PerfBitExclusive = CBitFieldMaskBit3 + PerfBitExcludeUser = CBitFieldMaskBit4 + PerfBitExcludeKernel = CBitFieldMaskBit5 + PerfBitExcludeHv = CBitFieldMaskBit6 + PerfBitExcludeIdle = CBitFieldMaskBit7 + PerfBitMmap = CBitFieldMaskBit8 + PerfBitComm = CBitFieldMaskBit9 + PerfBitFreq = CBitFieldMaskBit10 + PerfBitInheritStat = CBitFieldMaskBit11 + PerfBitEnableOnExec = CBitFieldMaskBit12 + PerfBitTask = CBitFieldMaskBit13 + PerfBitWatermark = CBitFieldMaskBit14 + PerfBitPreciseIPBit1 = CBitFieldMaskBit15 + PerfBitPreciseIPBit2 = CBitFieldMaskBit16 + PerfBitMmapData = CBitFieldMaskBit17 + PerfBitSampleIDAll = CBitFieldMaskBit18 + PerfBitExcludeHost = CBitFieldMaskBit19 + PerfBitExcludeGuest = CBitFieldMaskBit20 + PerfBitExcludeCallchainKernel = CBitFieldMaskBit21 + PerfBitExcludeCallchainUser = CBitFieldMaskBit22 + PerfBitMmap2 = CBitFieldMaskBit23 + PerfBitCommExec = CBitFieldMaskBit24 + PerfBitUseClockID = CBitFieldMaskBit25 + PerfBitContextSwitch = CBitFieldMaskBit26 +) + +const ( + PERF_TYPE_HARDWARE = 0x0 + PERF_TYPE_SOFTWARE = 0x1 + PERF_TYPE_TRACEPOINT = 0x2 + PERF_TYPE_HW_CACHE = 0x3 + PERF_TYPE_RAW = 0x4 + PERF_TYPE_BREAKPOINT = 0x5 + + PERF_COUNT_HW_CPU_CYCLES = 0x0 + PERF_COUNT_HW_INSTRUCTIONS = 0x1 + PERF_COUNT_HW_CACHE_REFERENCES = 0x2 + PERF_COUNT_HW_CACHE_MISSES = 0x3 + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4 + PERF_COUNT_HW_BRANCH_MISSES = 0x5 + PERF_COUNT_HW_BUS_CYCLES = 0x6 + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7 + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8 + PERF_COUNT_HW_REF_CPU_CYCLES = 0x9 + + PERF_COUNT_HW_CACHE_L1D = 0x0 + PERF_COUNT_HW_CACHE_L1I = 0x1 + PERF_COUNT_HW_CACHE_LL = 0x2 + PERF_COUNT_HW_CACHE_DTLB = 0x3 + PERF_COUNT_HW_CACHE_ITLB = 0x4 + PERF_COUNT_HW_CACHE_BPU = 0x5 + PERF_COUNT_HW_CACHE_NODE = 0x6 + + PERF_COUNT_HW_CACHE_OP_READ = 0x0 + PERF_COUNT_HW_CACHE_OP_WRITE = 0x1 + PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2 + + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0 + PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1 + + PERF_COUNT_SW_CPU_CLOCK = 0x0 + PERF_COUNT_SW_TASK_CLOCK = 0x1 + PERF_COUNT_SW_PAGE_FAULTS = 0x2 + PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3 + PERF_COUNT_SW_CPU_MIGRATIONS = 0x4 + PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5 + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6 + PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7 + PERF_COUNT_SW_EMULATION_FAULTS = 0x8 + PERF_COUNT_SW_DUMMY = 0x9 + + PERF_SAMPLE_IP = 0x1 + PERF_SAMPLE_TID = 0x2 + PERF_SAMPLE_TIME = 0x4 + PERF_SAMPLE_ADDR = 0x8 + PERF_SAMPLE_READ = 0x10 + PERF_SAMPLE_CALLCHAIN = 0x20 + PERF_SAMPLE_ID = 0x40 + PERF_SAMPLE_CPU = 0x80 + PERF_SAMPLE_PERIOD = 0x100 + PERF_SAMPLE_STREAM_ID = 0x200 + PERF_SAMPLE_RAW = 0x400 + PERF_SAMPLE_BRANCH_STACK = 0x800 + + PERF_SAMPLE_BRANCH_USER = 0x1 + PERF_SAMPLE_BRANCH_KERNEL = 0x2 + PERF_SAMPLE_BRANCH_HV = 0x4 + PERF_SAMPLE_BRANCH_ANY = 0x8 + PERF_SAMPLE_BRANCH_ANY_CALL = 0x10 + PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20 + PERF_SAMPLE_BRANCH_IND_CALL = 0x40 + + PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1 + PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2 + PERF_FORMAT_ID = 0x4 + PERF_FORMAT_GROUP = 0x8 + + PERF_RECORD_MMAP = 0x1 + PERF_RECORD_LOST = 0x2 + PERF_RECORD_COMM = 0x3 + PERF_RECORD_EXIT = 0x4 + PERF_RECORD_THROTTLE = 0x5 + PERF_RECORD_UNTHROTTLE = 0x6 + PERF_RECORD_FORK = 0x7 + PERF_RECORD_READ = 0x8 + PERF_RECORD_SAMPLE = 0x9 + + PERF_CONTEXT_HV = -0x20 + PERF_CONTEXT_KERNEL = -0x80 + PERF_CONTEXT_USER = -0x200 + + PERF_CONTEXT_GUEST = -0x800 + PERF_CONTEXT_GUEST_KERNEL = -0x880 + PERF_CONTEXT_GUEST_USER = -0xa00 + + PERF_FLAG_FD_NO_GROUP = 0x1 + PERF_FLAG_FD_OUTPUT = 0x2 + PERF_FLAG_PID_CGROUP = 0x4 +) + +const ( + CBitFieldMaskBit0 = 0x8000000000000000 + CBitFieldMaskBit1 = 0x4000000000000000 + CBitFieldMaskBit2 = 0x2000000000000000 + CBitFieldMaskBit3 = 0x1000000000000000 + CBitFieldMaskBit4 = 0x800000000000000 + CBitFieldMaskBit5 = 0x400000000000000 + CBitFieldMaskBit6 = 0x200000000000000 + CBitFieldMaskBit7 = 0x100000000000000 + CBitFieldMaskBit8 = 0x80000000000000 + CBitFieldMaskBit9 = 0x40000000000000 + CBitFieldMaskBit10 = 0x20000000000000 + CBitFieldMaskBit11 = 0x10000000000000 + CBitFieldMaskBit12 = 0x8000000000000 + CBitFieldMaskBit13 = 0x4000000000000 + CBitFieldMaskBit14 = 0x2000000000000 + CBitFieldMaskBit15 = 0x1000000000000 + CBitFieldMaskBit16 = 0x800000000000 + CBitFieldMaskBit17 = 0x400000000000 + CBitFieldMaskBit18 = 0x200000000000 + CBitFieldMaskBit19 = 0x100000000000 + CBitFieldMaskBit20 = 0x80000000000 + CBitFieldMaskBit21 = 0x40000000000 + CBitFieldMaskBit22 = 0x20000000000 + CBitFieldMaskBit23 = 0x10000000000 + CBitFieldMaskBit24 = 0x8000000000 + CBitFieldMaskBit25 = 0x4000000000 + CBitFieldMaskBit26 = 0x2000000000 + CBitFieldMaskBit27 = 0x1000000000 + CBitFieldMaskBit28 = 0x800000000 + CBitFieldMaskBit29 = 0x400000000 + CBitFieldMaskBit30 = 0x200000000 + CBitFieldMaskBit31 = 0x100000000 + CBitFieldMaskBit32 = 0x80000000 + CBitFieldMaskBit33 = 0x40000000 + CBitFieldMaskBit34 = 0x20000000 + CBitFieldMaskBit35 = 0x10000000 + CBitFieldMaskBit36 = 0x8000000 + CBitFieldMaskBit37 = 0x4000000 + CBitFieldMaskBit38 = 0x2000000 + CBitFieldMaskBit39 = 0x1000000 + CBitFieldMaskBit40 = 0x800000 + CBitFieldMaskBit41 = 0x400000 + CBitFieldMaskBit42 = 0x200000 + CBitFieldMaskBit43 = 0x100000 + CBitFieldMaskBit44 = 0x80000 + CBitFieldMaskBit45 = 0x40000 + CBitFieldMaskBit46 = 0x20000 + CBitFieldMaskBit47 = 0x10000 + CBitFieldMaskBit48 = 0x8000 + CBitFieldMaskBit49 = 0x4000 + CBitFieldMaskBit50 = 0x2000 + CBitFieldMaskBit51 = 0x1000 + CBitFieldMaskBit52 = 0x800 + CBitFieldMaskBit53 = 0x400 + CBitFieldMaskBit54 = 0x200 + CBitFieldMaskBit55 = 0x100 + CBitFieldMaskBit56 = 0x80 + CBitFieldMaskBit57 = 0x40 + CBitFieldMaskBit58 = 0x20 + CBitFieldMaskBit59 = 0x10 + CBitFieldMaskBit60 = 0x8 + CBitFieldMaskBit61 = 0x4 + CBitFieldMaskBit62 = 0x2 + CBitFieldMaskBit63 = 0x1 +) + +type SockaddrStorage struct { + Family uint16 + _ [118]int8 + _ uint64 +} + +type TCPMD5Sig struct { + Addr SockaddrStorage + Flags uint8 + Prefixlen uint8 + Keylen uint16 + _ uint32 + Key [80]uint8 +} + +type HDDriveCmdHdr struct { + Command uint8 + Number uint8 + Feature uint8 + Count uint8 +} + +type HDGeometry struct { + Heads uint8 + Sectors uint8 + Cylinders uint16 + _ [4]byte + Start uint64 +} + +type HDDriveID struct { + Config uint16 + Cyls uint16 + Reserved2 uint16 + Heads uint16 + Track_bytes uint16 + Sector_bytes uint16 + Sectors uint16 + Vendor0 uint16 + Vendor1 uint16 + Vendor2 uint16 + Serial_no [20]uint8 + Buf_type uint16 + Buf_size uint16 + Ecc_bytes uint16 + Fw_rev [8]uint8 + Model [40]uint8 + Max_multsect uint8 + Vendor3 uint8 + Dword_io uint16 + Vendor4 uint8 + Capability uint8 + Reserved50 uint16 + Vendor5 uint8 + TPIO uint8 + Vendor6 uint8 + TDMA uint8 + Field_valid uint16 + Cur_cyls uint16 + Cur_heads uint16 + Cur_sectors uint16 + Cur_capacity0 uint16 + Cur_capacity1 uint16 + Multsect uint8 + Multsect_valid uint8 + Lba_capacity uint32 + Dma_1word uint16 + Dma_mword uint16 + Eide_pio_modes uint16 + Eide_dma_min uint16 + Eide_dma_time uint16 + Eide_pio uint16 + Eide_pio_iordy uint16 + Words69_70 [2]uint16 + Words71_74 [4]uint16 + Queue_depth uint16 + Words76_79 [4]uint16 + Major_rev_num uint16 + Minor_rev_num uint16 + Command_set_1 uint16 + Command_set_2 uint16 + Cfsse uint16 + Cfs_enable_1 uint16 + Cfs_enable_2 uint16 + Csf_default uint16 + Dma_ultra uint16 + Trseuc uint16 + TrsEuc uint16 + CurAPMvalues uint16 + Mprc uint16 + Hw_config uint16 + Acoustic uint16 + Msrqs uint16 + Sxfert uint16 + Sal uint16 + Spg uint32 + Lba_capacity_2 uint64 + Words104_125 [22]uint16 + Last_lun uint16 + Word127 uint16 + Dlf uint16 + Csfo uint16 + Words130_155 [26]uint16 + Word156 uint16 + Words157_159 [3]uint16 + Cfa_power uint16 + Words161_175 [15]uint16 + Words176_205 [30]uint16 + Words206_254 [49]uint16 + Integrity_word uint16 +} + +type Statfs_t struct { + Type uint32 + Bsize uint32 + Blocks uint64 + Bfree uint64 + Bavail uint64 + Files uint64 + Ffree uint64 + Fsid Fsid + Namelen uint32 + Frsize uint32 + Flags uint32 + Spare [4]uint32 + _ [4]byte +} + +const ( + ST_MANDLOCK = 0x40 + ST_NOATIME = 0x400 + ST_NODEV = 0x4 + ST_NODIRATIME = 0x800 + ST_NOEXEC = 0x8 + ST_NOSUID = 0x2 + ST_RDONLY = 0x1 + ST_RELATIME = 0x1000 + ST_SYNCHRONOUS = 0x10 +) + +type TpacketHdr struct { + Status uint64 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Usec uint32 + _ [4]byte +} + +type Tpacket2Hdr struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Sec uint32 + Nsec uint32 + Vlan_tci uint16 + Vlan_tpid uint16 + _ [4]uint8 +} + +type Tpacket3Hdr struct { + Next_offset uint32 + Sec uint32 + Nsec uint32 + Snaplen uint32 + Len uint32 + Status uint32 + Mac uint16 + Net uint16 + Hv1 TpacketHdrVariant1 + _ [8]uint8 +} + +type TpacketHdrVariant1 struct { + Rxhash uint32 + Vlan_tci uint32 + Vlan_tpid uint16 + _ uint16 +} + +type TpacketBlockDesc struct { + Version uint32 + To_priv uint32 + Hdr [40]byte +} + +type TpacketReq struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 +} + +type TpacketReq3 struct { + Block_size uint32 + Block_nr uint32 + Frame_size uint32 + Frame_nr uint32 + Retire_blk_tov uint32 + Sizeof_priv uint32 + Feature_req_word uint32 +} + +type TpacketStats struct { + Packets uint32 + Drops uint32 +} + +type TpacketStatsV3 struct { + Packets uint32 + Drops uint32 + Freeze_q_cnt uint32 +} + +type TpacketAuxdata struct { + Status uint32 + Len uint32 + Snaplen uint32 + Mac uint16 + Net uint16 + Vlan_tci uint16 + Vlan_tpid uint16 +} + +const ( + TPACKET_V1 = 0x0 + TPACKET_V2 = 0x1 + TPACKET_V3 = 0x2 +) + +const ( + SizeofTpacketHdr = 0x20 + SizeofTpacket2Hdr = 0x20 + SizeofTpacket3Hdr = 0x30 +) + +const ( + NF_INET_PRE_ROUTING = 0x0 + NF_INET_LOCAL_IN = 0x1 + NF_INET_FORWARD = 0x2 + NF_INET_LOCAL_OUT = 0x3 + NF_INET_POST_ROUTING = 0x4 + NF_INET_NUMHOOKS = 0x5 +) + +const ( + NF_NETDEV_INGRESS = 0x0 + NF_NETDEV_NUMHOOKS = 0x1 +) + +const ( + NFPROTO_UNSPEC = 0x0 + NFPROTO_INET = 0x1 + NFPROTO_IPV4 = 0x2 + NFPROTO_ARP = 0x3 + NFPROTO_NETDEV = 0x5 + NFPROTO_BRIDGE = 0x7 + NFPROTO_IPV6 = 0xa + NFPROTO_DECNET = 0xc + NFPROTO_NUMPROTO = 0xd +) + +type Nfgenmsg struct { + Nfgen_family uint8 + Version uint8 + Res_id uint16 +} + +const ( + NFNL_BATCH_UNSPEC = 0x0 + NFNL_BATCH_GENID = 0x1 +) + +const ( + NFT_REG_VERDICT = 0x0 + NFT_REG_1 = 0x1 + NFT_REG_2 = 0x2 + NFT_REG_3 = 0x3 + NFT_REG_4 = 0x4 + NFT_REG32_00 = 0x8 + NFT_REG32_01 = 0x9 + NFT_REG32_02 = 0xa + NFT_REG32_03 = 0xb + NFT_REG32_04 = 0xc + NFT_REG32_05 = 0xd + NFT_REG32_06 = 0xe + NFT_REG32_07 = 0xf + NFT_REG32_08 = 0x10 + NFT_REG32_09 = 0x11 + NFT_REG32_10 = 0x12 + NFT_REG32_11 = 0x13 + NFT_REG32_12 = 0x14 + NFT_REG32_13 = 0x15 + NFT_REG32_14 = 0x16 + NFT_REG32_15 = 0x17 + NFT_CONTINUE = -0x1 + NFT_BREAK = -0x2 + NFT_JUMP = -0x3 + NFT_GOTO = -0x4 + NFT_RETURN = -0x5 + NFT_MSG_NEWTABLE = 0x0 + NFT_MSG_GETTABLE = 0x1 + NFT_MSG_DELTABLE = 0x2 + NFT_MSG_NEWCHAIN = 0x3 + NFT_MSG_GETCHAIN = 0x4 + NFT_MSG_DELCHAIN = 0x5 + NFT_MSG_NEWRULE = 0x6 + NFT_MSG_GETRULE = 0x7 + NFT_MSG_DELRULE = 0x8 + NFT_MSG_NEWSET = 0x9 + NFT_MSG_GETSET = 0xa + NFT_MSG_DELSET = 0xb + NFT_MSG_NEWSETELEM = 0xc + NFT_MSG_GETSETELEM = 0xd + NFT_MSG_DELSETELEM = 0xe + NFT_MSG_NEWGEN = 0xf + NFT_MSG_GETGEN = 0x10 + NFT_MSG_TRACE = 0x11 + NFT_MSG_NEWOBJ = 0x12 + NFT_MSG_GETOBJ = 0x13 + NFT_MSG_DELOBJ = 0x14 + NFT_MSG_GETOBJ_RESET = 0x15 + NFT_MSG_MAX = 0x19 + NFTA_LIST_UNPEC = 0x0 + NFTA_LIST_ELEM = 0x1 + NFTA_HOOK_UNSPEC = 0x0 + NFTA_HOOK_HOOKNUM = 0x1 + NFTA_HOOK_PRIORITY = 0x2 + NFTA_HOOK_DEV = 0x3 + NFT_TABLE_F_DORMANT = 0x1 + NFTA_TABLE_UNSPEC = 0x0 + NFTA_TABLE_NAME = 0x1 + NFTA_TABLE_FLAGS = 0x2 + NFTA_TABLE_USE = 0x3 + NFTA_CHAIN_UNSPEC = 0x0 + NFTA_CHAIN_TABLE = 0x1 + NFTA_CHAIN_HANDLE = 0x2 + NFTA_CHAIN_NAME = 0x3 + NFTA_CHAIN_HOOK = 0x4 + NFTA_CHAIN_POLICY = 0x5 + NFTA_CHAIN_USE = 0x6 + NFTA_CHAIN_TYPE = 0x7 + NFTA_CHAIN_COUNTERS = 0x8 + NFTA_CHAIN_PAD = 0x9 + NFTA_RULE_UNSPEC = 0x0 + NFTA_RULE_TABLE = 0x1 + NFTA_RULE_CHAIN = 0x2 + NFTA_RULE_HANDLE = 0x3 + NFTA_RULE_EXPRESSIONS = 0x4 + NFTA_RULE_COMPAT = 0x5 + NFTA_RULE_POSITION = 0x6 + NFTA_RULE_USERDATA = 0x7 + NFTA_RULE_PAD = 0x8 + NFTA_RULE_ID = 0x9 + NFT_RULE_COMPAT_F_INV = 0x2 + NFT_RULE_COMPAT_F_MASK = 0x2 + NFTA_RULE_COMPAT_UNSPEC = 0x0 + NFTA_RULE_COMPAT_PROTO = 0x1 + NFTA_RULE_COMPAT_FLAGS = 0x2 + NFT_SET_ANONYMOUS = 0x1 + NFT_SET_CONSTANT = 0x2 + NFT_SET_INTERVAL = 0x4 + NFT_SET_MAP = 0x8 + NFT_SET_TIMEOUT = 0x10 + NFT_SET_EVAL = 0x20 + NFT_SET_OBJECT = 0x40 + NFT_SET_POL_PERFORMANCE = 0x0 + NFT_SET_POL_MEMORY = 0x1 + NFTA_SET_DESC_UNSPEC = 0x0 + NFTA_SET_DESC_SIZE = 0x1 + NFTA_SET_UNSPEC = 0x0 + NFTA_SET_TABLE = 0x1 + NFTA_SET_NAME = 0x2 + NFTA_SET_FLAGS = 0x3 + NFTA_SET_KEY_TYPE = 0x4 + NFTA_SET_KEY_LEN = 0x5 + NFTA_SET_DATA_TYPE = 0x6 + NFTA_SET_DATA_LEN = 0x7 + NFTA_SET_POLICY = 0x8 + NFTA_SET_DESC = 0x9 + NFTA_SET_ID = 0xa + NFTA_SET_TIMEOUT = 0xb + NFTA_SET_GC_INTERVAL = 0xc + NFTA_SET_USERDATA = 0xd + NFTA_SET_PAD = 0xe + NFTA_SET_OBJ_TYPE = 0xf + NFT_SET_ELEM_INTERVAL_END = 0x1 + NFTA_SET_ELEM_UNSPEC = 0x0 + NFTA_SET_ELEM_KEY = 0x1 + NFTA_SET_ELEM_DATA = 0x2 + NFTA_SET_ELEM_FLAGS = 0x3 + NFTA_SET_ELEM_TIMEOUT = 0x4 + NFTA_SET_ELEM_EXPIRATION = 0x5 + NFTA_SET_ELEM_USERDATA = 0x6 + NFTA_SET_ELEM_EXPR = 0x7 + NFTA_SET_ELEM_PAD = 0x8 + NFTA_SET_ELEM_OBJREF = 0x9 + NFTA_SET_ELEM_LIST_UNSPEC = 0x0 + NFTA_SET_ELEM_LIST_TABLE = 0x1 + NFTA_SET_ELEM_LIST_SET = 0x2 + NFTA_SET_ELEM_LIST_ELEMENTS = 0x3 + NFTA_SET_ELEM_LIST_SET_ID = 0x4 + NFT_DATA_VALUE = 0x0 + NFT_DATA_VERDICT = 0xffffff00 + NFTA_DATA_UNSPEC = 0x0 + NFTA_DATA_VALUE = 0x1 + NFTA_DATA_VERDICT = 0x2 + NFTA_VERDICT_UNSPEC = 0x0 + NFTA_VERDICT_CODE = 0x1 + NFTA_VERDICT_CHAIN = 0x2 + NFTA_EXPR_UNSPEC = 0x0 + NFTA_EXPR_NAME = 0x1 + NFTA_EXPR_DATA = 0x2 + NFTA_IMMEDIATE_UNSPEC = 0x0 + NFTA_IMMEDIATE_DREG = 0x1 + NFTA_IMMEDIATE_DATA = 0x2 + NFTA_BITWISE_UNSPEC = 0x0 + NFTA_BITWISE_SREG = 0x1 + NFTA_BITWISE_DREG = 0x2 + NFTA_BITWISE_LEN = 0x3 + NFTA_BITWISE_MASK = 0x4 + NFTA_BITWISE_XOR = 0x5 + NFT_BYTEORDER_NTOH = 0x0 + NFT_BYTEORDER_HTON = 0x1 + NFTA_BYTEORDER_UNSPEC = 0x0 + NFTA_BYTEORDER_SREG = 0x1 + NFTA_BYTEORDER_DREG = 0x2 + NFTA_BYTEORDER_OP = 0x3 + NFTA_BYTEORDER_LEN = 0x4 + NFTA_BYTEORDER_SIZE = 0x5 + NFT_CMP_EQ = 0x0 + NFT_CMP_NEQ = 0x1 + NFT_CMP_LT = 0x2 + NFT_CMP_LTE = 0x3 + NFT_CMP_GT = 0x4 + NFT_CMP_GTE = 0x5 + NFTA_CMP_UNSPEC = 0x0 + NFTA_CMP_SREG = 0x1 + NFTA_CMP_OP = 0x2 + NFTA_CMP_DATA = 0x3 + NFT_RANGE_EQ = 0x0 + NFT_RANGE_NEQ = 0x1 + NFTA_RANGE_UNSPEC = 0x0 + NFTA_RANGE_SREG = 0x1 + NFTA_RANGE_OP = 0x2 + NFTA_RANGE_FROM_DATA = 0x3 + NFTA_RANGE_TO_DATA = 0x4 + NFT_LOOKUP_F_INV = 0x1 + NFTA_LOOKUP_UNSPEC = 0x0 + NFTA_LOOKUP_SET = 0x1 + NFTA_LOOKUP_SREG = 0x2 + NFTA_LOOKUP_DREG = 0x3 + NFTA_LOOKUP_SET_ID = 0x4 + NFTA_LOOKUP_FLAGS = 0x5 + NFT_DYNSET_OP_ADD = 0x0 + NFT_DYNSET_OP_UPDATE = 0x1 + NFT_DYNSET_F_INV = 0x1 + NFTA_DYNSET_UNSPEC = 0x0 + NFTA_DYNSET_SET_NAME = 0x1 + NFTA_DYNSET_SET_ID = 0x2 + NFTA_DYNSET_OP = 0x3 + NFTA_DYNSET_SREG_KEY = 0x4 + NFTA_DYNSET_SREG_DATA = 0x5 + NFTA_DYNSET_TIMEOUT = 0x6 + NFTA_DYNSET_EXPR = 0x7 + NFTA_DYNSET_PAD = 0x8 + NFTA_DYNSET_FLAGS = 0x9 + NFT_PAYLOAD_LL_HEADER = 0x0 + NFT_PAYLOAD_NETWORK_HEADER = 0x1 + NFT_PAYLOAD_TRANSPORT_HEADER = 0x2 + NFT_PAYLOAD_CSUM_NONE = 0x0 + NFT_PAYLOAD_CSUM_INET = 0x1 + NFT_PAYLOAD_L4CSUM_PSEUDOHDR = 0x1 + NFTA_PAYLOAD_UNSPEC = 0x0 + NFTA_PAYLOAD_DREG = 0x1 + NFTA_PAYLOAD_BASE = 0x2 + NFTA_PAYLOAD_OFFSET = 0x3 + NFTA_PAYLOAD_LEN = 0x4 + NFTA_PAYLOAD_SREG = 0x5 + NFTA_PAYLOAD_CSUM_TYPE = 0x6 + NFTA_PAYLOAD_CSUM_OFFSET = 0x7 + NFTA_PAYLOAD_CSUM_FLAGS = 0x8 + NFT_EXTHDR_F_PRESENT = 0x1 + NFT_EXTHDR_OP_IPV6 = 0x0 + NFT_EXTHDR_OP_TCPOPT = 0x1 + NFTA_EXTHDR_UNSPEC = 0x0 + NFTA_EXTHDR_DREG = 0x1 + NFTA_EXTHDR_TYPE = 0x2 + NFTA_EXTHDR_OFFSET = 0x3 + NFTA_EXTHDR_LEN = 0x4 + NFTA_EXTHDR_FLAGS = 0x5 + NFTA_EXTHDR_OP = 0x6 + NFTA_EXTHDR_SREG = 0x7 + NFT_META_LEN = 0x0 + NFT_META_PROTOCOL = 0x1 + NFT_META_PRIORITY = 0x2 + NFT_META_MARK = 0x3 + NFT_META_IIF = 0x4 + NFT_META_OIF = 0x5 + NFT_META_IIFNAME = 0x6 + NFT_META_OIFNAME = 0x7 + NFT_META_IIFTYPE = 0x8 + NFT_META_OIFTYPE = 0x9 + NFT_META_SKUID = 0xa + NFT_META_SKGID = 0xb + NFT_META_NFTRACE = 0xc + NFT_META_RTCLASSID = 0xd + NFT_META_SECMARK = 0xe + NFT_META_NFPROTO = 0xf + NFT_META_L4PROTO = 0x10 + NFT_META_BRI_IIFNAME = 0x11 + NFT_META_BRI_OIFNAME = 0x12 + NFT_META_PKTTYPE = 0x13 + NFT_META_CPU = 0x14 + NFT_META_IIFGROUP = 0x15 + NFT_META_OIFGROUP = 0x16 + NFT_META_CGROUP = 0x17 + NFT_META_PRANDOM = 0x18 + NFT_RT_CLASSID = 0x0 + NFT_RT_NEXTHOP4 = 0x1 + NFT_RT_NEXTHOP6 = 0x2 + NFT_RT_TCPMSS = 0x3 + NFT_HASH_JENKINS = 0x0 + NFT_HASH_SYM = 0x1 + NFTA_HASH_UNSPEC = 0x0 + NFTA_HASH_SREG = 0x1 + NFTA_HASH_DREG = 0x2 + NFTA_HASH_LEN = 0x3 + NFTA_HASH_MODULUS = 0x4 + NFTA_HASH_SEED = 0x5 + NFTA_HASH_OFFSET = 0x6 + NFTA_HASH_TYPE = 0x7 + NFTA_META_UNSPEC = 0x0 + NFTA_META_DREG = 0x1 + NFTA_META_KEY = 0x2 + NFTA_META_SREG = 0x3 + NFTA_RT_UNSPEC = 0x0 + NFTA_RT_DREG = 0x1 + NFTA_RT_KEY = 0x2 + NFT_CT_STATE = 0x0 + NFT_CT_DIRECTION = 0x1 + NFT_CT_STATUS = 0x2 + NFT_CT_MARK = 0x3 + NFT_CT_SECMARK = 0x4 + NFT_CT_EXPIRATION = 0x5 + NFT_CT_HELPER = 0x6 + NFT_CT_L3PROTOCOL = 0x7 + NFT_CT_SRC = 0x8 + NFT_CT_DST = 0x9 + NFT_CT_PROTOCOL = 0xa + NFT_CT_PROTO_SRC = 0xb + NFT_CT_PROTO_DST = 0xc + NFT_CT_LABELS = 0xd + NFT_CT_PKTS = 0xe + NFT_CT_BYTES = 0xf + NFT_CT_AVGPKT = 0x10 + NFT_CT_ZONE = 0x11 + NFT_CT_EVENTMASK = 0x12 + NFTA_CT_UNSPEC = 0x0 + NFTA_CT_DREG = 0x1 + NFTA_CT_KEY = 0x2 + NFTA_CT_DIRECTION = 0x3 + NFTA_CT_SREG = 0x4 + NFT_LIMIT_PKTS = 0x0 + NFT_LIMIT_PKT_BYTES = 0x1 + NFT_LIMIT_F_INV = 0x1 + NFTA_LIMIT_UNSPEC = 0x0 + NFTA_LIMIT_RATE = 0x1 + NFTA_LIMIT_UNIT = 0x2 + NFTA_LIMIT_BURST = 0x3 + NFTA_LIMIT_TYPE = 0x4 + NFTA_LIMIT_FLAGS = 0x5 + NFTA_LIMIT_PAD = 0x6 + NFTA_COUNTER_UNSPEC = 0x0 + NFTA_COUNTER_BYTES = 0x1 + NFTA_COUNTER_PACKETS = 0x2 + NFTA_COUNTER_PAD = 0x3 + NFTA_LOG_UNSPEC = 0x0 + NFTA_LOG_GROUP = 0x1 + NFTA_LOG_PREFIX = 0x2 + NFTA_LOG_SNAPLEN = 0x3 + NFTA_LOG_QTHRESHOLD = 0x4 + NFTA_LOG_LEVEL = 0x5 + NFTA_LOG_FLAGS = 0x6 + NFTA_QUEUE_UNSPEC = 0x0 + NFTA_QUEUE_NUM = 0x1 + NFTA_QUEUE_TOTAL = 0x2 + NFTA_QUEUE_FLAGS = 0x3 + NFTA_QUEUE_SREG_QNUM = 0x4 + NFT_QUOTA_F_INV = 0x1 + NFT_QUOTA_F_DEPLETED = 0x2 + NFTA_QUOTA_UNSPEC = 0x0 + NFTA_QUOTA_BYTES = 0x1 + NFTA_QUOTA_FLAGS = 0x2 + NFTA_QUOTA_PAD = 0x3 + NFTA_QUOTA_CONSUMED = 0x4 + NFT_REJECT_ICMP_UNREACH = 0x0 + NFT_REJECT_TCP_RST = 0x1 + NFT_REJECT_ICMPX_UNREACH = 0x2 + NFT_REJECT_ICMPX_NO_ROUTE = 0x0 + NFT_REJECT_ICMPX_PORT_UNREACH = 0x1 + NFT_REJECT_ICMPX_HOST_UNREACH = 0x2 + NFT_REJECT_ICMPX_ADMIN_PROHIBITED = 0x3 + NFTA_REJECT_UNSPEC = 0x0 + NFTA_REJECT_TYPE = 0x1 + NFTA_REJECT_ICMP_CODE = 0x2 + NFT_NAT_SNAT = 0x0 + NFT_NAT_DNAT = 0x1 + NFTA_NAT_UNSPEC = 0x0 + NFTA_NAT_TYPE = 0x1 + NFTA_NAT_FAMILY = 0x2 + NFTA_NAT_REG_ADDR_MIN = 0x3 + NFTA_NAT_REG_ADDR_MAX = 0x4 + NFTA_NAT_REG_PROTO_MIN = 0x5 + NFTA_NAT_REG_PROTO_MAX = 0x6 + NFTA_NAT_FLAGS = 0x7 + NFTA_MASQ_UNSPEC = 0x0 + NFTA_MASQ_FLAGS = 0x1 + NFTA_MASQ_REG_PROTO_MIN = 0x2 + NFTA_MASQ_REG_PROTO_MAX = 0x3 + NFTA_REDIR_UNSPEC = 0x0 + NFTA_REDIR_REG_PROTO_MIN = 0x1 + NFTA_REDIR_REG_PROTO_MAX = 0x2 + NFTA_REDIR_FLAGS = 0x3 + NFTA_DUP_UNSPEC = 0x0 + NFTA_DUP_SREG_ADDR = 0x1 + NFTA_DUP_SREG_DEV = 0x2 + NFTA_FWD_UNSPEC = 0x0 + NFTA_FWD_SREG_DEV = 0x1 + NFTA_OBJREF_UNSPEC = 0x0 + NFTA_OBJREF_IMM_TYPE = 0x1 + NFTA_OBJREF_IMM_NAME = 0x2 + NFTA_OBJREF_SET_SREG = 0x3 + NFTA_OBJREF_SET_NAME = 0x4 + NFTA_OBJREF_SET_ID = 0x5 + NFTA_GEN_UNSPEC = 0x0 + NFTA_GEN_ID = 0x1 + NFTA_GEN_PROC_PID = 0x2 + NFTA_GEN_PROC_NAME = 0x3 + NFTA_FIB_UNSPEC = 0x0 + NFTA_FIB_DREG = 0x1 + NFTA_FIB_RESULT = 0x2 + NFTA_FIB_FLAGS = 0x3 + NFT_FIB_RESULT_UNSPEC = 0x0 + NFT_FIB_RESULT_OIF = 0x1 + NFT_FIB_RESULT_OIFNAME = 0x2 + NFT_FIB_RESULT_ADDRTYPE = 0x3 + NFTA_FIB_F_SADDR = 0x1 + NFTA_FIB_F_DADDR = 0x2 + NFTA_FIB_F_MARK = 0x4 + NFTA_FIB_F_IIF = 0x8 + NFTA_FIB_F_OIF = 0x10 + NFTA_FIB_F_PRESENT = 0x20 + NFTA_CT_HELPER_UNSPEC = 0x0 + NFTA_CT_HELPER_NAME = 0x1 + NFTA_CT_HELPER_L3PROTO = 0x2 + NFTA_CT_HELPER_L4PROTO = 0x3 + NFTA_OBJ_UNSPEC = 0x0 + NFTA_OBJ_TABLE = 0x1 + NFTA_OBJ_NAME = 0x2 + NFTA_OBJ_TYPE = 0x3 + NFTA_OBJ_DATA = 0x4 + NFTA_OBJ_USE = 0x5 + NFTA_TRACE_UNSPEC = 0x0 + NFTA_TRACE_TABLE = 0x1 + NFTA_TRACE_CHAIN = 0x2 + NFTA_TRACE_RULE_HANDLE = 0x3 + NFTA_TRACE_TYPE = 0x4 + NFTA_TRACE_VERDICT = 0x5 + NFTA_TRACE_ID = 0x6 + NFTA_TRACE_LL_HEADER = 0x7 + NFTA_TRACE_NETWORK_HEADER = 0x8 + NFTA_TRACE_TRANSPORT_HEADER = 0x9 + NFTA_TRACE_IIF = 0xa + NFTA_TRACE_IIFTYPE = 0xb + NFTA_TRACE_OIF = 0xc + NFTA_TRACE_OIFTYPE = 0xd + NFTA_TRACE_MARK = 0xe + NFTA_TRACE_NFPROTO = 0xf + NFTA_TRACE_POLICY = 0x10 + NFTA_TRACE_PAD = 0x11 + NFT_TRACETYPE_UNSPEC = 0x0 + NFT_TRACETYPE_POLICY = 0x1 + NFT_TRACETYPE_RETURN = 0x2 + NFT_TRACETYPE_RULE = 0x3 + NFTA_NG_UNSPEC = 0x0 + NFTA_NG_DREG = 0x1 + NFTA_NG_MODULUS = 0x2 + NFTA_NG_TYPE = 0x3 + NFTA_NG_OFFSET = 0x4 + NFT_NG_INCREMENTAL = 0x0 + NFT_NG_RANDOM = 0x1 +) diff --git a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go index 9dbbb1ce52..8e7384b89c 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_linux_sparc64.go @@ -376,97 +376,123 @@ const ( ) const ( - IFA_UNSPEC = 0x0 - IFA_ADDRESS = 0x1 - IFA_LOCAL = 0x2 - IFA_LABEL = 0x3 - IFA_BROADCAST = 0x4 - IFA_ANYCAST = 0x5 - IFA_CACHEINFO = 0x6 - IFA_MULTICAST = 0x7 - IFLA_UNSPEC = 0x0 - IFLA_ADDRESS = 0x1 - IFLA_BROADCAST = 0x2 - IFLA_IFNAME = 0x3 - IFLA_MTU = 0x4 - IFLA_LINK = 0x5 - IFLA_QDISC = 0x6 - IFLA_STATS = 0x7 - IFLA_COST = 0x8 - IFLA_PRIORITY = 0x9 - IFLA_MASTER = 0xa - IFLA_WIRELESS = 0xb - IFLA_PROTINFO = 0xc - IFLA_TXQLEN = 0xd - IFLA_MAP = 0xe - IFLA_WEIGHT = 0xf - IFLA_OPERSTATE = 0x10 - IFLA_LINKMODE = 0x11 - IFLA_LINKINFO = 0x12 - IFLA_NET_NS_PID = 0x13 - IFLA_IFALIAS = 0x14 - IFLA_MAX = 0x2a - RT_SCOPE_UNIVERSE = 0x0 - RT_SCOPE_SITE = 0xc8 - RT_SCOPE_LINK = 0xfd - RT_SCOPE_HOST = 0xfe - RT_SCOPE_NOWHERE = 0xff - RT_TABLE_UNSPEC = 0x0 - RT_TABLE_COMPAT = 0xfc - RT_TABLE_DEFAULT = 0xfd - RT_TABLE_MAIN = 0xfe - RT_TABLE_LOCAL = 0xff - RT_TABLE_MAX = 0xffffffff - RTA_UNSPEC = 0x0 - RTA_DST = 0x1 - RTA_SRC = 0x2 - RTA_IIF = 0x3 - RTA_OIF = 0x4 - RTA_GATEWAY = 0x5 - RTA_PRIORITY = 0x6 - RTA_PREFSRC = 0x7 - RTA_METRICS = 0x8 - RTA_MULTIPATH = 0x9 - RTA_FLOW = 0xb - RTA_CACHEINFO = 0xc - RTA_TABLE = 0xf - RTN_UNSPEC = 0x0 - RTN_UNICAST = 0x1 - RTN_LOCAL = 0x2 - RTN_BROADCAST = 0x3 - RTN_ANYCAST = 0x4 - RTN_MULTICAST = 0x5 - RTN_BLACKHOLE = 0x6 - RTN_UNREACHABLE = 0x7 - RTN_PROHIBIT = 0x8 - RTN_THROW = 0x9 - RTN_NAT = 0xa - RTN_XRESOLVE = 0xb - RTNLGRP_NONE = 0x0 - RTNLGRP_LINK = 0x1 - RTNLGRP_NOTIFY = 0x2 - RTNLGRP_NEIGH = 0x3 - RTNLGRP_TC = 0x4 - RTNLGRP_IPV4_IFADDR = 0x5 - RTNLGRP_IPV4_MROUTE = 0x6 - RTNLGRP_IPV4_ROUTE = 0x7 - RTNLGRP_IPV4_RULE = 0x8 - RTNLGRP_IPV6_IFADDR = 0x9 - RTNLGRP_IPV6_MROUTE = 0xa - RTNLGRP_IPV6_ROUTE = 0xb - RTNLGRP_IPV6_IFINFO = 0xc - RTNLGRP_IPV6_PREFIX = 0x12 - RTNLGRP_IPV6_RULE = 0x13 - RTNLGRP_ND_USEROPT = 0x14 - SizeofNlMsghdr = 0x10 - SizeofNlMsgerr = 0x14 - SizeofRtGenmsg = 0x1 - SizeofNlAttr = 0x4 - SizeofRtAttr = 0x4 - SizeofIfInfomsg = 0x10 - SizeofIfAddrmsg = 0x8 - SizeofRtMsg = 0xc - SizeofRtNexthop = 0x8 + IFA_UNSPEC = 0x0 + IFA_ADDRESS = 0x1 + IFA_LOCAL = 0x2 + IFA_LABEL = 0x3 + IFA_BROADCAST = 0x4 + IFA_ANYCAST = 0x5 + IFA_CACHEINFO = 0x6 + IFA_MULTICAST = 0x7 + IFLA_UNSPEC = 0x0 + IFLA_ADDRESS = 0x1 + IFLA_BROADCAST = 0x2 + IFLA_IFNAME = 0x3 + IFLA_MTU = 0x4 + IFLA_LINK = 0x5 + IFLA_QDISC = 0x6 + IFLA_STATS = 0x7 + IFLA_COST = 0x8 + IFLA_PRIORITY = 0x9 + IFLA_MASTER = 0xa + IFLA_WIRELESS = 0xb + IFLA_PROTINFO = 0xc + IFLA_TXQLEN = 0xd + IFLA_MAP = 0xe + IFLA_WEIGHT = 0xf + IFLA_OPERSTATE = 0x10 + IFLA_LINKMODE = 0x11 + IFLA_LINKINFO = 0x12 + IFLA_NET_NS_PID = 0x13 + IFLA_IFALIAS = 0x14 + IFLA_NUM_VF = 0x15 + IFLA_VFINFO_LIST = 0x16 + IFLA_STATS64 = 0x17 + IFLA_VF_PORTS = 0x18 + IFLA_PORT_SELF = 0x19 + IFLA_AF_SPEC = 0x1a + IFLA_GROUP = 0x1b + IFLA_NET_NS_FD = 0x1c + IFLA_EXT_MASK = 0x1d + IFLA_PROMISCUITY = 0x1e + IFLA_NUM_TX_QUEUES = 0x1f + IFLA_NUM_RX_QUEUES = 0x20 + IFLA_CARRIER = 0x21 + IFLA_PHYS_PORT_ID = 0x22 + IFLA_CARRIER_CHANGES = 0x23 + IFLA_PHYS_SWITCH_ID = 0x24 + IFLA_LINK_NETNSID = 0x25 + IFLA_PHYS_PORT_NAME = 0x26 + IFLA_PROTO_DOWN = 0x27 + IFLA_GSO_MAX_SEGS = 0x28 + IFLA_GSO_MAX_SIZE = 0x29 + IFLA_PAD = 0x2a + IFLA_XDP = 0x2b + IFLA_EVENT = 0x2c + IFLA_NEW_NETNSID = 0x2d + IFLA_IF_NETNSID = 0x2e + IFLA_MAX = 0x2e + RT_SCOPE_UNIVERSE = 0x0 + RT_SCOPE_SITE = 0xc8 + RT_SCOPE_LINK = 0xfd + RT_SCOPE_HOST = 0xfe + RT_SCOPE_NOWHERE = 0xff + RT_TABLE_UNSPEC = 0x0 + RT_TABLE_COMPAT = 0xfc + RT_TABLE_DEFAULT = 0xfd + RT_TABLE_MAIN = 0xfe + RT_TABLE_LOCAL = 0xff + RT_TABLE_MAX = 0xffffffff + RTA_UNSPEC = 0x0 + RTA_DST = 0x1 + RTA_SRC = 0x2 + RTA_IIF = 0x3 + RTA_OIF = 0x4 + RTA_GATEWAY = 0x5 + RTA_PRIORITY = 0x6 + RTA_PREFSRC = 0x7 + RTA_METRICS = 0x8 + RTA_MULTIPATH = 0x9 + RTA_FLOW = 0xb + RTA_CACHEINFO = 0xc + RTA_TABLE = 0xf + RTN_UNSPEC = 0x0 + RTN_UNICAST = 0x1 + RTN_LOCAL = 0x2 + RTN_BROADCAST = 0x3 + RTN_ANYCAST = 0x4 + RTN_MULTICAST = 0x5 + RTN_BLACKHOLE = 0x6 + RTN_UNREACHABLE = 0x7 + RTN_PROHIBIT = 0x8 + RTN_THROW = 0x9 + RTN_NAT = 0xa + RTN_XRESOLVE = 0xb + RTNLGRP_NONE = 0x0 + RTNLGRP_LINK = 0x1 + RTNLGRP_NOTIFY = 0x2 + RTNLGRP_NEIGH = 0x3 + RTNLGRP_TC = 0x4 + RTNLGRP_IPV4_IFADDR = 0x5 + RTNLGRP_IPV4_MROUTE = 0x6 + RTNLGRP_IPV4_ROUTE = 0x7 + RTNLGRP_IPV4_RULE = 0x8 + RTNLGRP_IPV6_IFADDR = 0x9 + RTNLGRP_IPV6_MROUTE = 0xa + RTNLGRP_IPV6_ROUTE = 0xb + RTNLGRP_IPV6_IFINFO = 0xc + RTNLGRP_IPV6_PREFIX = 0x12 + RTNLGRP_IPV6_RULE = 0x13 + RTNLGRP_ND_USEROPT = 0x14 + SizeofNlMsghdr = 0x10 + SizeofNlMsgerr = 0x14 + SizeofRtGenmsg = 0x1 + SizeofNlAttr = 0x4 + SizeofRtAttr = 0x4 + SizeofIfInfomsg = 0x10 + SizeofIfAddrmsg = 0x8 + SizeofRtMsg = 0xc + SizeofRtNexthop = 0x8 ) type NlMsghdr struct { diff --git a/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go b/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go index e16c05a8a0..4b86fb2b33 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go @@ -99,6 +99,19 @@ type Fsid struct { X__fsid_val [2]int32 } +const ( + PathMax = 0x400 +) + +const ( + FADV_NORMAL = 0x0 + FADV_RANDOM = 0x1 + FADV_SEQUENTIAL = 0x2 + FADV_WILLNEED = 0x3 + FADV_DONTNEED = 0x4 + FADV_NOREUSE = 0x5 +) + type RawSockaddrInet4 struct { Len uint8 Family uint8 @@ -425,3 +438,11 @@ type Sysctlnode struct { X_sysctl_parent [8]byte X_sysctl_desc [8]byte } + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go index 9c3743561f..9048a509d0 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go @@ -103,6 +103,19 @@ type Fsid struct { X__fsid_val [2]int32 } +const ( + PathMax = 0x400 +) + +const ( + FADV_NORMAL = 0x0 + FADV_RANDOM = 0x1 + FADV_SEQUENTIAL = 0x2 + FADV_WILLNEED = 0x3 + FADV_DONTNEED = 0x4 + FADV_NOREUSE = 0x5 +) + type RawSockaddrInet4 struct { Len uint8 Family uint8 @@ -432,3 +445,11 @@ type Sysctlnode struct { X_sysctl_parent [8]byte X_sysctl_desc [8]byte } + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go b/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go index 1329423184..00525e7b02 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go @@ -104,6 +104,19 @@ type Fsid struct { X__fsid_val [2]int32 } +const ( + PathMax = 0x400 +) + +const ( + FADV_NORMAL = 0x0 + FADV_RANDOM = 0x1 + FADV_SEQUENTIAL = 0x2 + FADV_WILLNEED = 0x3 + FADV_DONTNEED = 0x4 + FADV_NOREUSE = 0x5 +) + type RawSockaddrInet4 struct { Len uint8 Family uint8 @@ -430,3 +443,11 @@ type Sysctlnode struct { X_sysctl_parent [8]byte X_sysctl_desc [8]byte } + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go b/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go index 2cf08bf495..d5a2d75da3 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go +++ b/vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go @@ -140,6 +140,10 @@ type Fsid struct { Val [2]int32 } +const ( + PathMax = 0x400 +) + type RawSockaddrInet4 struct { Len uint8 Family uint8 @@ -470,3 +474,11 @@ const ( POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go index 7cfc61f661..5a9c818485 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go @@ -74,30 +74,30 @@ const ( ) type Stat_t struct { - Mode uint32 - Dev int32 - Ino uint64 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev int32 - Atim Timespec - Mtim Timespec - Ctim Timespec - Size int64 - Blocks int64 - Blksize uint32 - Flags uint32 - Gen uint32 - Pad_cgo_0 [4]byte - X__st_birthtim Timespec + Mode uint32 + Dev int32 + Ino uint64 + Nlink uint32 + Uid uint32 + Gid uint32 + Rdev int32 + Atim Timespec + Mtim Timespec + Ctim Timespec + Size int64 + Blocks int64 + Blksize int32 + Flags uint32 + Gen uint32 + _ [4]byte + _ Timespec } type Statfs_t struct { F_flags uint32 F_bsize uint32 F_iosize uint32 - Pad_cgo_0 [4]byte + _ [4]byte F_blocks uint64 F_bfree uint64 F_bavail int64 @@ -116,7 +116,7 @@ type Statfs_t struct { F_mntonname [90]int8 F_mntfromname [90]int8 F_mntfromspec [90]int8 - Pad_cgo_1 [2]byte + _ [2]byte Mount_info [160]byte } @@ -129,19 +129,23 @@ type Flock_t struct { } type Dirent struct { - Fileno uint64 - Off int64 - Reclen uint16 - Type uint8 - Namlen uint8 - X__d_padding [4]uint8 - Name [256]int8 + Fileno uint64 + Off int64 + Reclen uint16 + Type uint8 + Namlen uint8 + _ [4]uint8 + Name [256]int8 } type Fsid struct { Val [2]int32 } +const ( + PathMax = 0x400 +) + type RawSockaddrInet4 struct { Len uint8 Family uint8 @@ -212,10 +216,10 @@ type IPv6Mreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen uint32 - Pad_cgo_1 [4]byte + _ [4]byte Control *byte Controllen uint32 Flags int32 @@ -277,8 +281,8 @@ type FdSet struct { } const ( - SizeofIfMsghdr = 0xf8 - SizeofIfData = 0xe0 + SizeofIfMsghdr = 0xa8 + SizeofIfData = 0x90 SizeofIfaMsghdr = 0x18 SizeofIfAnnounceMsghdr = 0x1a SizeofRtMsghdr = 0x60 @@ -307,7 +311,7 @@ type IfData struct { Link_state uint8 Mtu uint32 Metric uint32 - Pad uint32 + Rdomain uint32 Baudrate uint64 Ipackets uint64 Ierrors uint64 @@ -319,12 +323,11 @@ type IfData struct { Imcasts uint64 Omcasts uint64 Iqdrops uint64 + Oqdrops uint64 Noproto uint64 Capabilities uint32 - Pad_cgo_0 [4]byte + _ [4]byte Lastchange Timeval - Mclpool [7]Mclpool - Pad_cgo_1 [4]byte } type IfaMsghdr struct { @@ -385,13 +388,7 @@ type RtMetrics struct { Pad uint32 } -type Mclpool struct { - Grown int32 - Alive uint16 - Hwm uint16 - Cwm uint16 - Lwm uint16 -} +type Mclpool struct{} const ( SizeofBpfVersion = 0x4 @@ -412,9 +409,9 @@ type BpfStat struct { } type BpfProgram struct { - Len uint32 - Pad_cgo_0 [4]byte - Insns *BpfInsn + Len uint32 + _ [4]byte + Insns *BpfInsn } type BpfInsn struct { @@ -425,11 +422,11 @@ type BpfInsn struct { } type BpfHdr struct { - Tstamp BpfTimeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte + Tstamp BpfTimeval + Caplen uint32 + Datalen uint32 + Hdrlen uint16 + _ [2]byte } type BpfTimeval struct { @@ -477,3 +474,11 @@ const ( POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go b/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go index 842c59c5c1..e35b13b6fc 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go +++ b/vendor/golang.org/x/sys/unix/ztypes_openbsd_arm.go @@ -140,6 +140,10 @@ type Fsid struct { Val [2]int32 } +const ( + PathMax = 0x400 +) + type RawSockaddrInet4 struct { Len uint8 Family uint8 @@ -463,3 +467,11 @@ const ( POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) + +type Utsname struct { + Sysname [256]byte + Nodename [256]byte + Release [256]byte + Version [256]byte + Machine [256]byte +} diff --git a/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go b/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go index d445452486..2248598d03 100644 --- a/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go +++ b/vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go @@ -93,40 +93,40 @@ const ( ) type Stat_t struct { - Dev uint64 - Ino uint64 - Mode uint32 - Nlink uint32 - Uid uint32 - Gid uint32 - Rdev uint64 - Size int64 - Atim Timespec - Mtim Timespec - Ctim Timespec - Blksize int32 - Pad_cgo_0 [4]byte - Blocks int64 - Fstype [16]int8 + Dev uint64 + Ino uint64 + Mode uint32 + Nlink uint32 + Uid uint32 + Gid uint32 + Rdev uint64 + Size int64 + Atim Timespec + Mtim Timespec + Ctim Timespec + Blksize int32 + _ [4]byte + Blocks int64 + Fstype [16]int8 } type Flock_t struct { - Type int16 - Whence int16 - Pad_cgo_0 [4]byte - Start int64 - Len int64 - Sysid int32 - Pid int32 - Pad [4]int64 + Type int16 + Whence int16 + _ [4]byte + Start int64 + Len int64 + Sysid int32 + Pid int32 + Pad [4]int64 } type Dirent struct { - Ino uint64 - Off int64 - Reclen uint16 - Name [1]int8 - Pad_cgo_0 [5]byte + Ino uint64 + Off int64 + Reclen uint16 + Name [1]int8 + _ [5]byte } type _Fsblkcnt_t uint64 @@ -213,13 +213,13 @@ type IPv6Mreq struct { type Msghdr struct { Name *byte Namelen uint32 - Pad_cgo_0 [4]byte + _ [4]byte Iov *Iovec Iovlen int32 - Pad_cgo_1 [4]byte + _ [4]byte Accrights *int8 Accrightslen int32 - Pad_cgo_2 [4]byte + _ [4]byte } type Cmsghdr struct { @@ -271,11 +271,11 @@ type Utsname struct { } type Ustat_t struct { - Tfree int64 - Tinode uint64 - Fname [6]int8 - Fpack [6]int8 - Pad_cgo_0 [4]byte + Tfree int64 + Tinode uint64 + Fname [6]int8 + Fpack [6]int8 + _ [4]byte } const ( @@ -295,21 +295,21 @@ const ( ) type IfMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Data IfData + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Data IfData } type IfData struct { Type uint8 Addrlen uint8 Hdrlen uint8 - Pad_cgo_0 [1]byte + _ [1]byte Mtu uint32 Metric uint32 Baudrate uint32 @@ -328,30 +328,30 @@ type IfData struct { } type IfaMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Addrs int32 - Flags int32 - Index uint16 - Pad_cgo_0 [2]byte - Metric int32 + Msglen uint16 + Version uint8 + Type uint8 + Addrs int32 + Flags int32 + Index uint16 + _ [2]byte + Metric int32 } type RtMsghdr struct { - Msglen uint16 - Version uint8 - Type uint8 - Index uint16 - Pad_cgo_0 [2]byte - Flags int32 - Addrs int32 - Pid int32 - Seq int32 - Errno int32 - Use int32 - Inits uint32 - Rmx RtMetrics + Msglen uint16 + Version uint8 + Type uint8 + Index uint16 + _ [2]byte + Flags int32 + Addrs int32 + Pid int32 + Seq int32 + Errno int32 + Use int32 + Inits uint32 + Rmx RtMetrics } type RtMetrics struct { @@ -388,9 +388,9 @@ type BpfStat struct { } type BpfProgram struct { - Len uint32 - Pad_cgo_0 [4]byte - Insns *BpfInsn + Len uint32 + _ [4]byte + Insns *BpfInsn } type BpfInsn struct { @@ -406,30 +406,30 @@ type BpfTimeval struct { } type BpfHdr struct { - Tstamp BpfTimeval - Caplen uint32 - Datalen uint32 - Hdrlen uint16 - Pad_cgo_0 [2]byte + Tstamp BpfTimeval + Caplen uint32 + Datalen uint32 + Hdrlen uint16 + _ [2]byte } type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [19]uint8 - Pad_cgo_0 [1]byte + Iflag uint32 + Oflag uint32 + Cflag uint32 + Lflag uint32 + Cc [19]uint8 + _ [1]byte } type Termio struct { - Iflag uint16 - Oflag uint16 - Cflag uint16 - Lflag uint16 - Line int8 - Cc [8]uint8 - Pad_cgo_0 [1]byte + Iflag uint16 + Oflag uint16 + Cflag uint16 + Lflag uint16 + Line int8 + Cc [8]uint8 + _ [1]byte } type Winsize struct { diff --git a/vendor/golang.org/x/sys/windows/asm_windows_386.s b/vendor/golang.org/x/sys/windows/asm_windows_386.s index 1c20dd2f89..21d994d318 100644 --- a/vendor/golang.org/x/sys/windows/asm_windows_386.s +++ b/vendor/golang.org/x/sys/windows/asm_windows_386.s @@ -6,8 +6,8 @@ // System calls for 386, Windows are implemented in runtime/syscall_windows.goc // -TEXT ·getprocaddress(SB), 7, $0-8 +TEXT ·getprocaddress(SB), 7, $0-16 JMP syscall·getprocaddress(SB) -TEXT ·loadlibrary(SB), 7, $0-4 +TEXT ·loadlibrary(SB), 7, $0-12 JMP syscall·loadlibrary(SB) diff --git a/vendor/golang.org/x/sys/windows/asm_windows_amd64.s b/vendor/golang.org/x/sys/windows/asm_windows_amd64.s index 4d025ab556..5bfdf79741 100644 --- a/vendor/golang.org/x/sys/windows/asm_windows_amd64.s +++ b/vendor/golang.org/x/sys/windows/asm_windows_amd64.s @@ -9,5 +9,5 @@ TEXT ·getprocaddress(SB), 7, $0-32 JMP syscall·getprocaddress(SB) -TEXT ·loadlibrary(SB), 7, $0-8 +TEXT ·loadlibrary(SB), 7, $0-24 JMP syscall·loadlibrary(SB) diff --git a/vendor/golang.org/x/sys/windows/env_unset.go b/vendor/golang.org/x/sys/windows/env_unset.go deleted file mode 100644 index b712c6604a..0000000000 --- a/vendor/golang.org/x/sys/windows/env_unset.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2014 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 windows -// +build go1.4 - -package windows - -import "syscall" - -func Unsetenv(key string) error { - // This was added in Go 1.4. - return syscall.Unsetenv(key) -} diff --git a/vendor/golang.org/x/sys/windows/env_windows.go b/vendor/golang.org/x/sys/windows/env_windows.go index e8292386c0..bdc71e241e 100644 --- a/vendor/golang.org/x/sys/windows/env_windows.go +++ b/vendor/golang.org/x/sys/windows/env_windows.go @@ -23,3 +23,7 @@ func Clearenv() { func Environ() []string { return syscall.Environ() } + +func Unsetenv(key string) error { + return syscall.Unsetenv(key) +} diff --git a/vendor/golang.org/x/sys/windows/security_windows.go b/vendor/golang.org/x/sys/windows/security_windows.go index d8e7ff2ec5..f1ec5dc4ee 100644 --- a/vendor/golang.org/x/sys/windows/security_windows.go +++ b/vendor/golang.org/x/sys/windows/security_windows.go @@ -132,6 +132,36 @@ const ( SECURITY_NT_NON_UNIQUE_RID = 0x15 ) +// Predefined domain-relative RIDs for local groups. +// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa379649(v=vs.85).aspx +const ( + DOMAIN_ALIAS_RID_ADMINS = 0x220 + DOMAIN_ALIAS_RID_USERS = 0x221 + DOMAIN_ALIAS_RID_GUESTS = 0x222 + DOMAIN_ALIAS_RID_POWER_USERS = 0x223 + DOMAIN_ALIAS_RID_ACCOUNT_OPS = 0x224 + DOMAIN_ALIAS_RID_SYSTEM_OPS = 0x225 + DOMAIN_ALIAS_RID_PRINT_OPS = 0x226 + DOMAIN_ALIAS_RID_BACKUP_OPS = 0x227 + DOMAIN_ALIAS_RID_REPLICATOR = 0x228 + DOMAIN_ALIAS_RID_RAS_SERVERS = 0x229 + DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = 0x22a + DOMAIN_ALIAS_RID_REMOTE_DESKTOP_USERS = 0x22b + DOMAIN_ALIAS_RID_NETWORK_CONFIGURATION_OPS = 0x22c + DOMAIN_ALIAS_RID_INCOMING_FOREST_TRUST_BUILDERS = 0x22d + DOMAIN_ALIAS_RID_MONITORING_USERS = 0X22e + DOMAIN_ALIAS_RID_LOGGING_USERS = 0x22f + DOMAIN_ALIAS_RID_AUTHORIZATIONACCESS = 0x230 + DOMAIN_ALIAS_RID_TS_LICENSE_SERVERS = 0x231 + DOMAIN_ALIAS_RID_DCOM_USERS = 0x232 + DOMAIN_ALIAS_RID_IUSERS = 0x238 + DOMAIN_ALIAS_RID_CRYPTO_OPERATORS = 0x239 + DOMAIN_ALIAS_RID_CACHEABLE_PRINCIPALS_GROUP = 0x23b + DOMAIN_ALIAS_RID_NON_CACHEABLE_PRINCIPALS_GROUP = 0x23c + DOMAIN_ALIAS_RID_EVENT_LOG_READERS_GROUP = 0x23d + DOMAIN_ALIAS_RID_CERTSVC_DCOM_ACCESS_GROUP = 0x23e +) + //sys LookupAccountSid(systemName *uint16, sid *SID, name *uint16, nameLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountSidW //sys LookupAccountName(systemName *uint16, accountName *uint16, sid *SID, sidLen *uint32, refdDomainName *uint16, refdDomainNameLen *uint32, use *uint32) (err error) = advapi32.LookupAccountNameW //sys ConvertSidToStringSid(sid *SID, stringSid **uint16) (err error) = advapi32.ConvertSidToStringSidW @@ -335,6 +365,8 @@ type Tokengroups struct { Groups [1]SIDAndAttributes } +// Authorization Functions +//sys checkTokenMembership(tokenHandle Token, sidToCheck *SID, isMember *int32) (err error) = advapi32.CheckTokenMembership //sys OpenProcessToken(h Handle, access uint32, token *Token) (err error) = advapi32.OpenProcessToken //sys GetTokenInformation(t Token, infoClass uint32, info *byte, infoLen uint32, returnedLen *uint32) (err error) = advapi32.GetTokenInformation //sys GetUserProfileDirectory(t Token, dir *uint16, dirLen *uint32) (err error) = userenv.GetUserProfileDirectoryW @@ -433,3 +465,12 @@ func (t Token) GetUserProfileDirectory() (string, error) { } } } + +// IsMember reports whether the access token t is a member of the provided SID. +func (t Token) IsMember(sid *SID) (bool, error) { + var b int32 + if e := checkTokenMembership(t, sid, &b); e != nil { + return false, e + } + return b != 0, nil +} diff --git a/vendor/golang.org/x/sys/windows/service.go b/vendor/golang.org/x/sys/windows/service.go index a500dd7dfc..24aa90bbbe 100644 --- a/vendor/golang.org/x/sys/windows/service.go +++ b/vendor/golang.org/x/sys/windows/service.go @@ -162,3 +162,4 @@ type ENUM_SERVICE_STATUS_PROCESS struct { //sys ChangeServiceConfig2(service Handle, infoLevel uint32, info *byte) (err error) = advapi32.ChangeServiceConfig2W //sys QueryServiceConfig2(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceConfig2W //sys EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serviceState uint32, services *byte, bufSize uint32, bytesNeeded *uint32, servicesReturned *uint32, resumeHandle *uint32, groupName *uint16) (err error) = advapi32.EnumServicesStatusExW +//sys QueryServiceStatusEx(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) = advapi32.QueryServiceStatusEx diff --git a/vendor/golang.org/x/sys/windows/syscall.go b/vendor/golang.org/x/sys/windows/syscall.go index b07bc2305d..af828a91bc 100644 --- a/vendor/golang.org/x/sys/windows/syscall.go +++ b/vendor/golang.org/x/sys/windows/syscall.go @@ -11,11 +11,14 @@ // system, set $GOOS and $GOARCH to the desired system. For example, if // you want to view documentation for freebsd/arm on linux/amd64, set $GOOS // to freebsd and $GOARCH to arm. +// // The primary use of this package is inside other packages that provide a more // portable interface to the system, such as "os", "time" and "net". Use // those packages rather than this one if you can. +// // For details of the functions and data types in this package consult // the manuals for the appropriate operating system. +// // These calls return err == nil to indicate success; otherwise // err represents an operating system error describing the failure and // holds a value of type syscall.Errno. diff --git a/vendor/golang.org/x/sys/windows/syscall_test.go b/vendor/golang.org/x/sys/windows/syscall_test.go deleted file mode 100644 index d7009e44a5..0000000000 --- a/vendor/golang.org/x/sys/windows/syscall_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2013 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 windows - -package windows_test - -import ( - "syscall" - "testing" - - "golang.org/x/sys/windows" -) - -func testSetGetenv(t *testing.T, key, value string) { - err := windows.Setenv(key, value) - if err != nil { - t.Fatalf("Setenv failed to set %q: %v", value, err) - } - newvalue, found := windows.Getenv(key) - if !found { - t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) - } - if newvalue != value { - t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) - } -} - -func TestEnv(t *testing.T) { - testSetGetenv(t, "TESTENV", "AVALUE") - // make sure TESTENV gets set to "", not deleted - testSetGetenv(t, "TESTENV", "") -} - -func TestGetProcAddressByOrdinal(t *testing.T) { - // Attempt calling shlwapi.dll:IsOS, resolving it by ordinal, as - // suggested in - // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773795.aspx - h, err := windows.LoadLibrary("shlwapi.dll") - if err != nil { - t.Fatalf("Failed to load shlwapi.dll: %s", err) - } - procIsOS, err := windows.GetProcAddressByOrdinal(h, 437) - if err != nil { - t.Fatalf("Could not find shlwapi.dll:IsOS by ordinal: %s", err) - } - const OS_NT = 1 - r, _, _ := syscall.Syscall(procIsOS, 1, OS_NT, 0, 0) - if r == 0 { - t.Error("shlwapi.dll:IsOS(OS_NT) returned 0, expected non-zero value") - } -} diff --git a/vendor/golang.org/x/sys/windows/syscall_windows.go b/vendor/golang.org/x/sys/windows/syscall_windows.go index f48fec60d4..1e9f4bb4a3 100644 --- a/vendor/golang.org/x/sys/windows/syscall_windows.go +++ b/vendor/golang.org/x/sys/windows/syscall_windows.go @@ -16,7 +16,46 @@ import ( type Handle uintptr -const InvalidHandle = ^Handle(0) +const ( + InvalidHandle = ^Handle(0) + + // Flags for DefineDosDevice. + DDD_EXACT_MATCH_ON_REMOVE = 0x00000004 + DDD_NO_BROADCAST_SYSTEM = 0x00000008 + DDD_RAW_TARGET_PATH = 0x00000001 + DDD_REMOVE_DEFINITION = 0x00000002 + + // Return values for GetDriveType. + DRIVE_UNKNOWN = 0 + DRIVE_NO_ROOT_DIR = 1 + DRIVE_REMOVABLE = 2 + DRIVE_FIXED = 3 + DRIVE_REMOTE = 4 + DRIVE_CDROM = 5 + DRIVE_RAMDISK = 6 + + // File system flags from GetVolumeInformation and GetVolumeInformationByHandle. + FILE_CASE_SENSITIVE_SEARCH = 0x00000001 + FILE_CASE_PRESERVED_NAMES = 0x00000002 + FILE_FILE_COMPRESSION = 0x00000010 + FILE_DAX_VOLUME = 0x20000000 + FILE_NAMED_STREAMS = 0x00040000 + FILE_PERSISTENT_ACLS = 0x00000008 + FILE_READ_ONLY_VOLUME = 0x00080000 + FILE_SEQUENTIAL_WRITE_ONCE = 0x00100000 + FILE_SUPPORTS_ENCRYPTION = 0x00020000 + FILE_SUPPORTS_EXTENDED_ATTRIBUTES = 0x00800000 + FILE_SUPPORTS_HARD_LINKS = 0x00400000 + FILE_SUPPORTS_OBJECT_IDS = 0x00010000 + FILE_SUPPORTS_OPEN_BY_FILE_ID = 0x01000000 + FILE_SUPPORTS_REPARSE_POINTS = 0x00000080 + FILE_SUPPORTS_SPARSE_FILES = 0x00000040 + FILE_SUPPORTS_TRANSACTIONS = 0x00200000 + FILE_SUPPORTS_USN_JOURNAL = 0x02000000 + FILE_UNICODE_ON_DISK = 0x00000004 + FILE_VOLUME_IS_COMPRESSED = 0x00008000 + FILE_VOLUME_QUOTAS = 0x00000020 +) // StringToUTF16 is deprecated. Use UTF16FromString instead. // If s contains a NUL byte this function panics instead of @@ -200,6 +239,27 @@ func NewCallbackCDecl(fn interface{}) uintptr { //sys ResetEvent(event Handle) (err error) = kernel32.ResetEvent //sys PulseEvent(event Handle) (err error) = kernel32.PulseEvent +// Volume Management Functions +//sys DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) = DefineDosDeviceW +//sys DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) = DeleteVolumeMountPointW +//sys FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeW +//sys FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error) [failretval==InvalidHandle] = FindFirstVolumeMountPointW +//sys FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) = FindNextVolumeW +//sys FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) = FindNextVolumeMountPointW +//sys FindVolumeClose(findVolume Handle) (err error) +//sys FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error) +//sys GetDriveType(rootPathName *uint16) (driveType uint32) = GetDriveTypeW +//sys GetLogicalDrives() (drivesBitMask uint32, err error) [failretval==0] +//sys GetLogicalDriveStrings(bufferLength uint32, buffer *uint16) (n uint32, err error) [failretval==0] = GetLogicalDriveStringsW +//sys GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationW +//sys GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) = GetVolumeInformationByHandleW +//sys GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) = GetVolumeNameForVolumeMountPointW +//sys GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error) = GetVolumePathNameW +//sys GetVolumePathNamesForVolumeName(volumeName *uint16, volumePathNames *uint16, bufferLength uint32, returnLength *uint32) (err error) = GetVolumePathNamesForVolumeNameW +//sys QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) [failretval==0] = QueryDosDeviceW +//sys SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) = SetVolumeLabelW +//sys SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error) = SetVolumeMountPointW + // syscall interface implementation for other packages // GetProcAddressByOrdinal retrieves the address of the exported diff --git a/vendor/golang.org/x/sys/windows/syscall_windows_test.go b/vendor/golang.org/x/sys/windows/syscall_windows_test.go deleted file mode 100644 index 9c7133cc41..0000000000 --- a/vendor/golang.org/x/sys/windows/syscall_windows_test.go +++ /dev/null @@ -1,107 +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 windows_test - -import ( - "io/ioutil" - "os" - "path/filepath" - "syscall" - "testing" - "unsafe" - - "golang.org/x/sys/windows" -) - -func TestWin32finddata(t *testing.T) { - dir, err := ioutil.TempDir("", "go-build") - if err != nil { - t.Fatalf("failed to create temp directory: %v", err) - } - defer os.RemoveAll(dir) - - path := filepath.Join(dir, "long_name.and_extension") - f, err := os.Create(path) - if err != nil { - t.Fatalf("failed to create %v: %v", path, err) - } - f.Close() - - type X struct { - fd windows.Win32finddata - got byte - pad [10]byte // to protect ourselves - - } - var want byte = 2 // it is unlikely to have this character in the filename - x := X{got: want} - - pathp, _ := windows.UTF16PtrFromString(path) - h, err := windows.FindFirstFile(pathp, &(x.fd)) - if err != nil { - t.Fatalf("FindFirstFile failed: %v", err) - } - err = windows.FindClose(h) - if err != nil { - t.Fatalf("FindClose failed: %v", err) - } - - if x.got != want { - t.Fatalf("memory corruption: want=%d got=%d", want, x.got) - } -} - -func TestFormatMessage(t *testing.T) { - dll := windows.MustLoadDLL("pdh.dll") - - pdhOpenQuery := func(datasrc *uint16, userdata uint32, query *windows.Handle) (errno uintptr) { - r0, _, _ := syscall.Syscall(dll.MustFindProc("PdhOpenQueryW").Addr(), 3, uintptr(unsafe.Pointer(datasrc)), uintptr(userdata), uintptr(unsafe.Pointer(query))) - return r0 - } - - pdhCloseQuery := func(query windows.Handle) (errno uintptr) { - r0, _, _ := syscall.Syscall(dll.MustFindProc("PdhCloseQuery").Addr(), 1, uintptr(query), 0, 0) - return r0 - } - - var q windows.Handle - name, err := windows.UTF16PtrFromString("no_such_source") - if err != nil { - t.Fatal(err) - } - errno := pdhOpenQuery(name, 0, &q) - if errno == 0 { - pdhCloseQuery(q) - t.Fatal("PdhOpenQuery succeeded, but expected to fail.") - } - - const flags uint32 = syscall.FORMAT_MESSAGE_FROM_HMODULE | syscall.FORMAT_MESSAGE_ARGUMENT_ARRAY | syscall.FORMAT_MESSAGE_IGNORE_INSERTS - buf := make([]uint16, 300) - _, err = windows.FormatMessage(flags, uintptr(dll.Handle), uint32(errno), 0, buf, nil) - if err != nil { - t.Fatalf("FormatMessage for handle=%x and errno=%x failed: %v", dll.Handle, errno, err) - } -} - -func abort(funcname string, err error) { - panic(funcname + " failed: " + err.Error()) -} - -func ExampleLoadLibrary() { - h, err := windows.LoadLibrary("kernel32.dll") - if err != nil { - abort("LoadLibrary", err) - } - defer windows.FreeLibrary(h) - proc, err := windows.GetProcAddress(h, "GetVersion") - if err != nil { - abort("GetProcAddress", err) - } - r, _, _ := syscall.Syscall(uintptr(proc), 0, 0, 0, 0) - major := byte(r) - minor := uint8(r >> 8) - build := uint16(r >> 16) - print("windows version ", major, ".", minor, " (Build ", build, ")\n") -} diff --git a/vendor/golang.org/x/sys/windows/types_windows.go b/vendor/golang.org/x/sys/windows/types_windows.go index 78b714c0da..52c2037b68 100644 --- a/vendor/golang.org/x/sys/windows/types_windows.go +++ b/vendor/golang.org/x/sys/windows/types_windows.go @@ -159,9 +159,6 @@ const ( WAIT_OBJECT_0 = 0x00000000 WAIT_FAILED = 0xFFFFFFFF - CREATE_NEW_PROCESS_GROUP = 0x00000200 - CREATE_UNICODE_ENVIRONMENT = 0x00000400 - PROCESS_TERMINATE = 1 PROCESS_QUERY_INFORMATION = 0x00000400 SYNCHRONIZE = 0x00100000 @@ -178,6 +175,26 @@ const ( APPLICATION_ERROR = 1 << 29 ) +const ( + // Process creation flags. + CREATE_BREAKAWAY_FROM_JOB = 0x01000000 + CREATE_DEFAULT_ERROR_MODE = 0x04000000 + CREATE_NEW_CONSOLE = 0x00000010 + CREATE_NEW_PROCESS_GROUP = 0x00000200 + CREATE_NO_WINDOW = 0x08000000 + CREATE_PROTECTED_PROCESS = 0x00040000 + CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000 + CREATE_SEPARATE_WOW_VDM = 0x00000800 + CREATE_SHARED_WOW_VDM = 0x00001000 + CREATE_SUSPENDED = 0x00000004 + CREATE_UNICODE_ENVIRONMENT = 0x00000400 + DEBUG_ONLY_THIS_PROCESS = 0x00000002 + DEBUG_PROCESS = 0x00000001 + DETACHED_PROCESS = 0x00000008 + EXTENDED_STARTUPINFO_PRESENT = 0x00080000 + INHERIT_PARENT_AFFINITY = 0x00010000 +) + const ( // flags for CreateToolhelp32Snapshot TH32CS_SNAPHEAPLIST = 0x01 diff --git a/vendor/golang.org/x/sys/windows/zsyscall_windows.go b/vendor/golang.org/x/sys/windows/zsyscall_windows.go index 2f893d2efc..318c61634e 100644 --- a/vendor/golang.org/x/sys/windows/zsyscall_windows.go +++ b/vendor/golang.org/x/sys/windows/zsyscall_windows.go @@ -65,6 +65,7 @@ var ( procChangeServiceConfig2W = modadvapi32.NewProc("ChangeServiceConfig2W") procQueryServiceConfig2W = modadvapi32.NewProc("QueryServiceConfig2W") procEnumServicesStatusExW = modadvapi32.NewProc("EnumServicesStatusExW") + procQueryServiceStatusEx = modadvapi32.NewProc("QueryServiceStatusEx") procGetLastError = modkernel32.NewProc("GetLastError") procLoadLibraryW = modkernel32.NewProc("LoadLibraryW") procLoadLibraryExW = modkernel32.NewProc("LoadLibraryExW") @@ -178,6 +179,25 @@ var ( procSetEvent = modkernel32.NewProc("SetEvent") procResetEvent = modkernel32.NewProc("ResetEvent") procPulseEvent = modkernel32.NewProc("PulseEvent") + procDefineDosDeviceW = modkernel32.NewProc("DefineDosDeviceW") + procDeleteVolumeMountPointW = modkernel32.NewProc("DeleteVolumeMountPointW") + procFindFirstVolumeW = modkernel32.NewProc("FindFirstVolumeW") + procFindFirstVolumeMountPointW = modkernel32.NewProc("FindFirstVolumeMountPointW") + procFindNextVolumeW = modkernel32.NewProc("FindNextVolumeW") + procFindNextVolumeMountPointW = modkernel32.NewProc("FindNextVolumeMountPointW") + procFindVolumeClose = modkernel32.NewProc("FindVolumeClose") + procFindVolumeMountPointClose = modkernel32.NewProc("FindVolumeMountPointClose") + procGetDriveTypeW = modkernel32.NewProc("GetDriveTypeW") + procGetLogicalDrives = modkernel32.NewProc("GetLogicalDrives") + procGetLogicalDriveStringsW = modkernel32.NewProc("GetLogicalDriveStringsW") + procGetVolumeInformationW = modkernel32.NewProc("GetVolumeInformationW") + procGetVolumeInformationByHandleW = modkernel32.NewProc("GetVolumeInformationByHandleW") + procGetVolumeNameForVolumeMountPointW = modkernel32.NewProc("GetVolumeNameForVolumeMountPointW") + procGetVolumePathNameW = modkernel32.NewProc("GetVolumePathNameW") + procGetVolumePathNamesForVolumeNameW = modkernel32.NewProc("GetVolumePathNamesForVolumeNameW") + procQueryDosDeviceW = modkernel32.NewProc("QueryDosDeviceW") + procSetVolumeLabelW = modkernel32.NewProc("SetVolumeLabelW") + procSetVolumeMountPointW = modkernel32.NewProc("SetVolumeMountPointW") procWSAStartup = modws2_32.NewProc("WSAStartup") procWSACleanup = modws2_32.NewProc("WSACleanup") procWSAIoctl = modws2_32.NewProc("WSAIoctl") @@ -227,6 +247,7 @@ var ( procAllocateAndInitializeSid = modadvapi32.NewProc("AllocateAndInitializeSid") procFreeSid = modadvapi32.NewProc("FreeSid") procEqualSid = modadvapi32.NewProc("EqualSid") + procCheckTokenMembership = modadvapi32.NewProc("CheckTokenMembership") procOpenProcessToken = modadvapi32.NewProc("OpenProcessToken") procGetTokenInformation = modadvapi32.NewProc("GetTokenInformation") procGetUserProfileDirectoryW = moduserenv.NewProc("GetUserProfileDirectoryW") @@ -452,6 +473,18 @@ func EnumServicesStatusEx(mgr Handle, infoLevel uint32, serviceType uint32, serv return } +func QueryServiceStatusEx(service Handle, infoLevel uint32, buff *byte, buffSize uint32, bytesNeeded *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procQueryServiceStatusEx.Addr(), 5, uintptr(service), uintptr(infoLevel), uintptr(unsafe.Pointer(buff)), uintptr(buffSize), uintptr(unsafe.Pointer(bytesNeeded)), 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + func GetLastError() (lasterr error) { r0, _, _ := syscall.Syscall(procGetLastError.Addr(), 0, 0, 0, 0) if r0 != 0 { @@ -1843,6 +1876,233 @@ func PulseEvent(event Handle) (err error) { return } +func DefineDosDevice(flags uint32, deviceName *uint16, targetPath *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procDefineDosDeviceW.Addr(), 3, uintptr(flags), uintptr(unsafe.Pointer(deviceName)), uintptr(unsafe.Pointer(targetPath))) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func DeleteVolumeMountPoint(volumeMountPoint *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procDeleteVolumeMountPointW.Addr(), 1, uintptr(unsafe.Pointer(volumeMountPoint)), 0, 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func FindFirstVolume(volumeName *uint16, bufferLength uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procFindFirstVolumeW.Addr(), 2, uintptr(unsafe.Pointer(volumeName)), uintptr(bufferLength), 0) + handle = Handle(r0) + if handle == InvalidHandle { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func FindFirstVolumeMountPoint(rootPathName *uint16, volumeMountPoint *uint16, bufferLength uint32) (handle Handle, err error) { + r0, _, e1 := syscall.Syscall(procFindFirstVolumeMountPointW.Addr(), 3, uintptr(unsafe.Pointer(rootPathName)), uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(bufferLength)) + handle = Handle(r0) + if handle == InvalidHandle { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func FindNextVolume(findVolume Handle, volumeName *uint16, bufferLength uint32) (err error) { + r1, _, e1 := syscall.Syscall(procFindNextVolumeW.Addr(), 3, uintptr(findVolume), uintptr(unsafe.Pointer(volumeName)), uintptr(bufferLength)) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func FindNextVolumeMountPoint(findVolumeMountPoint Handle, volumeMountPoint *uint16, bufferLength uint32) (err error) { + r1, _, e1 := syscall.Syscall(procFindNextVolumeMountPointW.Addr(), 3, uintptr(findVolumeMountPoint), uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(bufferLength)) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func FindVolumeClose(findVolume Handle) (err error) { + r1, _, e1 := syscall.Syscall(procFindVolumeClose.Addr(), 1, uintptr(findVolume), 0, 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func FindVolumeMountPointClose(findVolumeMountPoint Handle) (err error) { + r1, _, e1 := syscall.Syscall(procFindVolumeMountPointClose.Addr(), 1, uintptr(findVolumeMountPoint), 0, 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func GetDriveType(rootPathName *uint16) (driveType uint32) { + r0, _, _ := syscall.Syscall(procGetDriveTypeW.Addr(), 1, uintptr(unsafe.Pointer(rootPathName)), 0, 0) + driveType = uint32(r0) + return +} + +func GetLogicalDrives() (drivesBitMask uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetLogicalDrives.Addr(), 0, 0, 0, 0) + drivesBitMask = uint32(r0) + if drivesBitMask == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func GetLogicalDriveStrings(bufferLength uint32, buffer *uint16) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procGetLogicalDriveStringsW.Addr(), 2, uintptr(bufferLength), uintptr(unsafe.Pointer(buffer)), 0) + n = uint32(r0) + if n == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func GetVolumeInformation(rootPathName *uint16, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procGetVolumeInformationW.Addr(), 8, uintptr(unsafe.Pointer(rootPathName)), uintptr(unsafe.Pointer(volumeNameBuffer)), uintptr(volumeNameSize), uintptr(unsafe.Pointer(volumeNameSerialNumber)), uintptr(unsafe.Pointer(maximumComponentLength)), uintptr(unsafe.Pointer(fileSystemFlags)), uintptr(unsafe.Pointer(fileSystemNameBuffer)), uintptr(fileSystemNameSize), 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func GetVolumeInformationByHandle(file Handle, volumeNameBuffer *uint16, volumeNameSize uint32, volumeNameSerialNumber *uint32, maximumComponentLength *uint32, fileSystemFlags *uint32, fileSystemNameBuffer *uint16, fileSystemNameSize uint32) (err error) { + r1, _, e1 := syscall.Syscall9(procGetVolumeInformationByHandleW.Addr(), 8, uintptr(file), uintptr(unsafe.Pointer(volumeNameBuffer)), uintptr(volumeNameSize), uintptr(unsafe.Pointer(volumeNameSerialNumber)), uintptr(unsafe.Pointer(maximumComponentLength)), uintptr(unsafe.Pointer(fileSystemFlags)), uintptr(unsafe.Pointer(fileSystemNameBuffer)), uintptr(fileSystemNameSize), 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func GetVolumeNameForVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16, bufferlength uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetVolumeNameForVolumeMountPointW.Addr(), 3, uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(unsafe.Pointer(volumeName)), uintptr(bufferlength)) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func GetVolumePathName(fileName *uint16, volumePathName *uint16, bufferLength uint32) (err error) { + r1, _, e1 := syscall.Syscall(procGetVolumePathNameW.Addr(), 3, uintptr(unsafe.Pointer(fileName)), uintptr(unsafe.Pointer(volumePathName)), uintptr(bufferLength)) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func GetVolumePathNamesForVolumeName(volumeName *uint16, volumePathNames *uint16, bufferLength uint32, returnLength *uint32) (err error) { + r1, _, e1 := syscall.Syscall6(procGetVolumePathNamesForVolumeNameW.Addr(), 4, uintptr(unsafe.Pointer(volumeName)), uintptr(unsafe.Pointer(volumePathNames)), uintptr(bufferLength), uintptr(unsafe.Pointer(returnLength)), 0, 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func QueryDosDevice(deviceName *uint16, targetPath *uint16, max uint32) (n uint32, err error) { + r0, _, e1 := syscall.Syscall(procQueryDosDeviceW.Addr(), 3, uintptr(unsafe.Pointer(deviceName)), uintptr(unsafe.Pointer(targetPath)), uintptr(max)) + n = uint32(r0) + if n == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func SetVolumeLabel(rootPathName *uint16, volumeName *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procSetVolumeLabelW.Addr(), 2, uintptr(unsafe.Pointer(rootPathName)), uintptr(unsafe.Pointer(volumeName)), 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + +func SetVolumeMountPoint(volumeMountPoint *uint16, volumeName *uint16) (err error) { + r1, _, e1 := syscall.Syscall(procSetVolumeMountPointW.Addr(), 2, uintptr(unsafe.Pointer(volumeMountPoint)), uintptr(unsafe.Pointer(volumeName)), 0) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + func WSAStartup(verreq uint32, data *WSAData) (sockerr error) { r0, _, _ := syscall.Syscall(procWSAStartup.Addr(), 2, uintptr(verreq), uintptr(unsafe.Pointer(data)), 0) if r0 != 0 { @@ -2391,6 +2651,18 @@ func EqualSid(sid1 *SID, sid2 *SID) (isEqual bool) { return } +func checkTokenMembership(tokenHandle Token, sidToCheck *SID, isMember *int32) (err error) { + r1, _, e1 := syscall.Syscall(procCheckTokenMembership.Addr(), 3, uintptr(tokenHandle), uintptr(unsafe.Pointer(sidToCheck)), uintptr(unsafe.Pointer(isMember))) + if r1 == 0 { + if e1 != 0 { + err = errnoErr(e1) + } else { + err = syscall.EINVAL + } + } + return +} + func OpenProcessToken(h Handle, access uint32, token *Token) (err error) { r1, _, e1 := syscall.Syscall(procOpenProcessToken.Addr(), 3, uintptr(h), uintptr(access), uintptr(unsafe.Pointer(token))) if r1 == 0 { diff --git a/vendor/golang.org/x/text/README.md b/vendor/golang.org/x/text/README.md index 75e29bcd74..b3f365eed4 100644 --- a/vendor/golang.org/x/text/README.md +++ b/vendor/golang.org/x/text/README.md @@ -9,16 +9,18 @@ This repo uses Semantic versioning (http://semver.org/), so and 1. PATCH version when you make backwards-compatible bug fixes. -A Unicode major and minor version bump is mapped to a major version bump in -x/text. -A path version bump in Unicode is mapped to a minor version bump in x/text. -Note that, consistent with the definitions in semver, until version 1.0.0 of -x/text is reached, the minor version is considered a major version. -So going from 0.1.0 to 0.2.0 is considered to be a major version bump. +Until version 1.0.0 of x/text is reached, the minor version is considered a +major version. So going from 0.1.0 to 0.2.0 is considered to be a major version +bump. A major new CLDR version is mapped to a minor version increase in x/text. Any other new CLDR version is mapped to a patch version increase in x/text. +It is important that the Unicode version used in `x/text` matches the one used +by your Go compiler. The `x/text` repository supports multiple versions of +Unicode and will match the version of Unicode to that of the Go compiler. At the +moment this is supported for Go compilers from version 1.7. + ## Download/Install The easiest way to install is to run `go get -u golang.org/x/text`. You can diff --git a/vendor/golang.org/x/text/collate/build/builder_test.go b/vendor/golang.org/x/text/collate/build/builder_test.go deleted file mode 100644 index ff0aba3aee..0000000000 --- a/vendor/golang.org/x/text/collate/build/builder_test.go +++ /dev/null @@ -1,290 +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 build - -import "testing" - -// cjk returns an implicit collation element for a CJK rune. -func cjk(r rune) []rawCE { - // A CJK character C is represented in the DUCET as - // [.AAAA.0020.0002.C][.BBBB.0000.0000.C] - // Where AAAA is the most significant 15 bits plus a base value. - // Any base value will work for the test, so we pick the common value of FB40. - const base = 0xFB40 - return []rawCE{ - {w: []int{base + int(r>>15), defaultSecondary, defaultTertiary, int(r)}}, - {w: []int{int(r&0x7FFF) | 0x8000, 0, 0, int(r)}}, - } -} - -func pCE(p int) []rawCE { - return mkCE([]int{p, defaultSecondary, defaultTertiary, 0}, 0) -} - -func pqCE(p, q int) []rawCE { - return mkCE([]int{p, defaultSecondary, defaultTertiary, q}, 0) -} - -func ptCE(p, t int) []rawCE { - return mkCE([]int{p, defaultSecondary, t, 0}, 0) -} - -func ptcCE(p, t int, ccc uint8) []rawCE { - return mkCE([]int{p, defaultSecondary, t, 0}, ccc) -} - -func sCE(s int) []rawCE { - return mkCE([]int{0, s, defaultTertiary, 0}, 0) -} - -func stCE(s, t int) []rawCE { - return mkCE([]int{0, s, t, 0}, 0) -} - -func scCE(s int, ccc uint8) []rawCE { - return mkCE([]int{0, s, defaultTertiary, 0}, ccc) -} - -func mkCE(w []int, ccc uint8) []rawCE { - return []rawCE{rawCE{w, ccc}} -} - -// ducetElem is used to define test data that is used to generate a table. -type ducetElem struct { - str string - ces []rawCE -} - -func newBuilder(t *testing.T, ducet []ducetElem) *Builder { - b := NewBuilder() - for _, e := range ducet { - ces := [][]int{} - for _, ce := range e.ces { - ces = append(ces, ce.w) - } - if err := b.Add([]rune(e.str), ces, nil); err != nil { - t.Errorf(err.Error()) - } - } - b.t = &table{} - b.root.sort() - return b -} - -type convertTest struct { - in, out []rawCE - err bool -} - -var convLargeTests = []convertTest{ - {pCE(0xFB39), pCE(0xFB39), false}, - {cjk(0x2F9B2), pqCE(0x3F9B2, 0x2F9B2), false}, - {pCE(0xFB40), pCE(0), true}, - {append(pCE(0xFB40), pCE(0)[0]), pCE(0), true}, - {pCE(0xFFFE), pCE(illegalOffset), false}, - {pCE(0xFFFF), pCE(illegalOffset + 1), false}, -} - -func TestConvertLarge(t *testing.T) { - for i, tt := range convLargeTests { - e := new(entry) - for _, ce := range tt.in { - e.elems = append(e.elems, makeRawCE(ce.w, ce.ccc)) - } - elems, err := convertLargeWeights(e.elems) - if tt.err { - if err == nil { - t.Errorf("%d: expected error; none found", i) - } - continue - } else if err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - } - if !equalCEArrays(elems, tt.out) { - t.Errorf("%d: conversion was %x; want %x", i, elems, tt.out) - } - } -} - -// Collation element table for simplify tests. -var simplifyTest = []ducetElem{ - {"\u0300", sCE(30)}, // grave - {"\u030C", sCE(40)}, // caron - {"A", ptCE(100, 8)}, - {"D", ptCE(104, 8)}, - {"E", ptCE(105, 8)}, - {"I", ptCE(110, 8)}, - {"z", ptCE(130, 8)}, - {"\u05F2", append(ptCE(200, 4), ptCE(200, 4)[0])}, - {"\u05B7", sCE(80)}, - {"\u00C0", append(ptCE(100, 8), sCE(30)...)}, // A with grave, can be removed - {"\u00C8", append(ptCE(105, 8), sCE(30)...)}, // E with grave - {"\uFB1F", append(ptCE(200, 4), ptCE(200, 4)[0], sCE(80)[0])}, // eliminated by NFD - {"\u00C8\u0302", ptCE(106, 8)}, // block previous from simplifying - {"\u01C5", append(ptCE(104, 9), ptCE(130, 4)[0], stCE(40, maxTertiary)[0])}, // eliminated by NFKD - // no removal: tertiary value of third element is not maxTertiary - {"\u2162", append(ptCE(110, 9), ptCE(110, 4)[0], ptCE(110, 8)[0])}, -} - -var genColTests = []ducetElem{ - {"\uFA70", pqCE(0x1FA70, 0xFA70)}, - {"A\u0300", append(ptCE(100, 8), sCE(30)...)}, - {"A\u0300\uFA70", append(ptCE(100, 8), sCE(30)[0], pqCE(0x1FA70, 0xFA70)[0])}, - {"A\u0300A\u0300", append(ptCE(100, 8), sCE(30)[0], ptCE(100, 8)[0], sCE(30)[0])}, -} - -func TestGenColElems(t *testing.T) { - b := newBuilder(t, simplifyTest[:5]) - - for i, tt := range genColTests { - res := b.root.genColElems(tt.str) - if !equalCEArrays(tt.ces, res) { - t.Errorf("%d: result %X; want %X", i, res, tt.ces) - } - } -} - -type strArray []string - -func (sa strArray) contains(s string) bool { - for _, e := range sa { - if e == s { - return true - } - } - return false -} - -var simplifyRemoved = strArray{"\u00C0", "\uFB1F"} -var simplifyMarked = strArray{"\u01C5"} - -func TestSimplify(t *testing.T) { - b := newBuilder(t, simplifyTest) - o := &b.root - simplify(o) - - for i, tt := range simplifyTest { - if simplifyRemoved.contains(tt.str) { - continue - } - e := o.find(tt.str) - if e.str != tt.str || !equalCEArrays(e.elems, tt.ces) { - t.Errorf("%d: found element %s -> %X; want %s -> %X", i, e.str, e.elems, tt.str, tt.ces) - break - } - } - var i, k int - for e := o.front(); e != nil; e, _ = e.nextIndexed() { - gold := simplifyMarked.contains(e.str) - if gold { - k++ - } - if gold != e.decompose { - t.Errorf("%d: %s has decompose %v; want %v", i, e.str, e.decompose, gold) - } - i++ - } - if k != len(simplifyMarked) { - t.Errorf(" an entry that should be marked as decompose was deleted") - } -} - -var expandTest = []ducetElem{ - {"\u0300", append(scCE(29, 230), scCE(30, 230)...)}, - {"\u00C0", append(ptCE(100, 8), scCE(30, 230)...)}, - {"\u00C8", append(ptCE(105, 8), scCE(30, 230)...)}, - {"\u00C9", append(ptCE(105, 8), scCE(30, 230)...)}, // identical expansion - {"\u05F2", append(ptCE(200, 4), ptCE(200, 4)[0], ptCE(200, 4)[0])}, - {"\u01FF", append(ptCE(200, 4), ptcCE(201, 4, 0)[0], scCE(30, 230)[0])}, -} - -func TestExpand(t *testing.T) { - const ( - totalExpansions = 5 - totalElements = 2 + 2 + 2 + 3 + 3 + totalExpansions - ) - b := newBuilder(t, expandTest) - o := &b.root - b.processExpansions(o) - - e := o.front() - for _, tt := range expandTest { - exp := b.t.ExpandElem[e.expansionIndex:] - if int(exp[0]) != len(tt.ces) { - t.Errorf("%U: len(expansion)==%d; want %d", []rune(tt.str)[0], exp[0], len(tt.ces)) - } - exp = exp[1:] - for j, w := range tt.ces { - if ce, _ := makeCE(w); exp[j] != ce { - t.Errorf("%U: element %d is %X; want %X", []rune(tt.str)[0], j, exp[j], ce) - } - } - e, _ = e.nextIndexed() - } - // Verify uniquing. - if len(b.t.ExpandElem) != totalElements { - t.Errorf("len(expandElem)==%d; want %d", len(b.t.ExpandElem), totalElements) - } -} - -var contractTest = []ducetElem{ - {"abc", pCE(102)}, - {"abd", pCE(103)}, - {"a", pCE(100)}, - {"ab", pCE(101)}, - {"ac", pCE(104)}, - {"bcd", pCE(202)}, - {"b", pCE(200)}, - {"bc", pCE(201)}, - {"bd", pCE(203)}, - // shares suffixes with a* - {"Ab", pCE(301)}, - {"A", pCE(300)}, - {"Ac", pCE(304)}, - {"Abc", pCE(302)}, - {"Abd", pCE(303)}, - // starter to be ignored - {"z", pCE(1000)}, -} - -func TestContract(t *testing.T) { - const ( - totalElements = 5 + 5 + 4 - ) - b := newBuilder(t, contractTest) - o := &b.root - b.processContractions(o) - - indexMap := make(map[int]bool) - handleMap := make(map[rune]*entry) - for e := o.front(); e != nil; e, _ = e.nextIndexed() { - if e.contractionHandle.n > 0 { - handleMap[e.runes[0]] = e - indexMap[e.contractionHandle.index] = true - } - } - // Verify uniquing. - if len(indexMap) != 2 { - t.Errorf("number of tries is %d; want %d", len(indexMap), 2) - } - for _, tt := range contractTest { - e, ok := handleMap[[]rune(tt.str)[0]] - if !ok { - continue - } - str := tt.str[1:] - offset, n := lookup(&b.t.ContractTries, e.contractionHandle, []byte(str)) - if len(str) != n { - t.Errorf("%s: bytes consumed==%d; want %d", tt.str, n, len(str)) - } - ce := b.t.ContractElem[offset+e.contractionIndex] - if want, _ := makeCE(tt.ces[0]); want != ce { - t.Errorf("%s: element %X; want %X", tt.str, ce, want) - } - } - if len(b.t.ContractElem) != totalElements { - t.Errorf("len(expandElem)==%d; want %d", len(b.t.ContractElem), totalElements) - } -} diff --git a/vendor/golang.org/x/text/collate/build/colelem_test.go b/vendor/golang.org/x/text/collate/build/colelem_test.go deleted file mode 100644 index d0c8d07d8a..0000000000 --- a/vendor/golang.org/x/text/collate/build/colelem_test.go +++ /dev/null @@ -1,215 +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 build - -import ( - "testing" - - "golang.org/x/text/internal/colltab" -) - -type ceTest struct { - f func(in []int) (uint32, error) - arg []int - val uint32 -} - -func normalCE(in []int) (ce uint32, err error) { - return makeCE(rawCE{w: in[:3], ccc: uint8(in[3])}) -} - -func expandCE(in []int) (ce uint32, err error) { - return makeExpandIndex(in[0]) -} - -func contractCE(in []int) (ce uint32, err error) { - return makeContractIndex(ctHandle{in[0], in[1]}, in[2]) -} - -func decompCE(in []int) (ce uint32, err error) { - return makeDecompose(in[0], in[1]) -} - -var ceTests = []ceTest{ - {normalCE, []int{0, 0, 0, 0}, 0xA0000000}, - {normalCE, []int{0, 0x28, 3, 0}, 0xA0002803}, - {normalCE, []int{0, 0x28, 3, 0xFF}, 0xAFF02803}, - {normalCE, []int{100, defaultSecondary, 3, 0}, 0x0000C883}, - // non-ignorable primary with non-default secondary - {normalCE, []int{100, 0x28, defaultTertiary, 0}, 0x4000C828}, - {normalCE, []int{100, defaultSecondary + 8, 3, 0}, 0x0000C983}, - {normalCE, []int{100, 0, 3, 0}, 0xFFFF}, // non-ignorable primary with non-supported secondary - {normalCE, []int{100, 1, 3, 0}, 0xFFFF}, - {normalCE, []int{1 << maxPrimaryBits, defaultSecondary, 0, 0}, 0xFFFF}, - {normalCE, []int{0, 1 << maxSecondaryBits, 0, 0}, 0xFFFF}, - {normalCE, []int{100, defaultSecondary, 1 << maxTertiaryBits, 0}, 0xFFFF}, - {normalCE, []int{0x123, defaultSecondary, 8, 0xFF}, 0x88FF0123}, - {normalCE, []int{0x123, defaultSecondary + 1, 8, 0xFF}, 0xFFFF}, - - {contractCE, []int{0, 0, 0}, 0xC0000000}, - {contractCE, []int{1, 1, 1}, 0xC0010011}, - {contractCE, []int{1, (1 << maxNBits) - 1, 1}, 0xC001001F}, - {contractCE, []int{(1 << maxTrieIndexBits) - 1, 1, 1}, 0xC001FFF1}, - {contractCE, []int{1, 1, (1 << maxContractOffsetBits) - 1}, 0xDFFF0011}, - {contractCE, []int{1, (1 << maxNBits), 1}, 0xFFFF}, - {contractCE, []int{(1 << maxTrieIndexBits), 1, 1}, 0xFFFF}, - {contractCE, []int{1, (1 << maxContractOffsetBits), 1}, 0xFFFF}, - - {expandCE, []int{0}, 0xE0000000}, - {expandCE, []int{5}, 0xE0000005}, - {expandCE, []int{(1 << maxExpandIndexBits) - 1}, 0xE000FFFF}, - {expandCE, []int{1 << maxExpandIndexBits}, 0xFFFF}, - - {decompCE, []int{0, 0}, 0xF0000000}, - {decompCE, []int{1, 1}, 0xF0000101}, - {decompCE, []int{0x1F, 0x1F}, 0xF0001F1F}, - {decompCE, []int{256, 0x1F}, 0xFFFF}, - {decompCE, []int{0x1F, 256}, 0xFFFF}, -} - -func TestColElem(t *testing.T) { - for i, tt := range ceTests { - in := make([]int, len(tt.arg)) - copy(in, tt.arg) - ce, err := tt.f(in) - if tt.val == 0xFFFF { - if err == nil { - t.Errorf("%d: expected error for args %x", i, tt.arg) - } - continue - } - if err != nil { - t.Errorf("%d: unexpected error: %v", i, err.Error()) - } - if ce != tt.val { - t.Errorf("%d: colElem=%X; want %X", i, ce, tt.val) - } - } -} - -func mkRawCES(in [][]int) []rawCE { - out := []rawCE{} - for _, w := range in { - out = append(out, rawCE{w: w}) - } - return out -} - -type weightsTest struct { - a, b [][]int - level colltab.Level - result int -} - -var nextWeightTests = []weightsTest{ - { - a: [][]int{{100, 20, 5, 0}}, - b: [][]int{{101, defaultSecondary, defaultTertiary, 0}}, - level: colltab.Primary, - }, - { - a: [][]int{{100, 20, 5, 0}}, - b: [][]int{{100, 21, defaultTertiary, 0}}, - level: colltab.Secondary, - }, - { - a: [][]int{{100, 20, 5, 0}}, - b: [][]int{{100, 20, 6, 0}}, - level: colltab.Tertiary, - }, - { - a: [][]int{{100, 20, 5, 0}}, - b: [][]int{{100, 20, 5, 0}}, - level: colltab.Identity, - }, -} - -var extra = [][]int{{200, 32, 8, 0}, {0, 32, 8, 0}, {0, 0, 8, 0}, {0, 0, 0, 0}} - -func TestNextWeight(t *testing.T) { - for i, tt := range nextWeightTests { - test := func(l colltab.Level, tt weightsTest, a, gold [][]int) { - res := nextWeight(tt.level, mkRawCES(a)) - if !equalCEArrays(mkRawCES(gold), res) { - t.Errorf("%d:%d: expected weights %d; found %d", i, l, gold, res) - } - } - test(-1, tt, tt.a, tt.b) - for l := colltab.Primary; l <= colltab.Tertiary; l++ { - if tt.level <= l { - test(l, tt, append(tt.a, extra[l]), tt.b) - } else { - test(l, tt, append(tt.a, extra[l]), append(tt.b, extra[l])) - } - } - } -} - -var compareTests = []weightsTest{ - { - [][]int{{100, 20, 5, 0}}, - [][]int{{100, 20, 5, 0}}, - colltab.Identity, - 0, - }, - { - [][]int{{100, 20, 5, 0}, extra[0]}, - [][]int{{100, 20, 5, 1}}, - colltab.Primary, - 1, - }, - { - [][]int{{100, 20, 5, 0}}, - [][]int{{101, 20, 5, 0}}, - colltab.Primary, - -1, - }, - { - [][]int{{101, 20, 5, 0}}, - [][]int{{100, 20, 5, 0}}, - colltab.Primary, - 1, - }, - { - [][]int{{100, 0, 0, 0}, {0, 20, 5, 0}}, - [][]int{{0, 20, 5, 0}, {100, 0, 0, 0}}, - colltab.Identity, - 0, - }, - { - [][]int{{100, 20, 5, 0}}, - [][]int{{100, 21, 5, 0}}, - colltab.Secondary, - -1, - }, - { - [][]int{{100, 20, 5, 0}}, - [][]int{{100, 20, 2, 0}}, - colltab.Tertiary, - 1, - }, - { - [][]int{{100, 20, 5, 1}}, - [][]int{{100, 20, 5, 2}}, - colltab.Quaternary, - -1, - }, -} - -func TestCompareWeights(t *testing.T) { - for i, tt := range compareTests { - test := func(tt weightsTest, a, b [][]int) { - res, level := compareWeights(mkRawCES(a), mkRawCES(b)) - if res != tt.result { - t.Errorf("%d: expected comparison result %d; found %d", i, tt.result, res) - } - if level != tt.level { - t.Errorf("%d: expected level %d; found %d", i, tt.level, level) - } - } - test(tt, tt.a, tt.b) - test(tt, append(tt.a, extra[0]), append(tt.b, extra[0])) - } -} diff --git a/vendor/golang.org/x/text/collate/build/contract_test.go b/vendor/golang.org/x/text/collate/build/contract_test.go deleted file mode 100644 index 2e0eaecd51..0000000000 --- a/vendor/golang.org/x/text/collate/build/contract_test.go +++ /dev/null @@ -1,266 +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 build - -import ( - "bytes" - "sort" - "testing" - - "golang.org/x/text/internal/colltab" -) - -var largetosmall = []stridx{ - {"a", 5}, - {"ab", 4}, - {"abc", 3}, - {"abcd", 2}, - {"abcde", 1}, - {"abcdef", 0}, -} - -var offsetSortTests = [][]stridx{ - { - {"bcde", 1}, - {"bc", 5}, - {"ab", 4}, - {"bcd", 3}, - {"abcd", 0}, - {"abc", 2}, - }, - largetosmall, -} - -func TestOffsetSort(t *testing.T) { - for i, st := range offsetSortTests { - sort.Sort(offsetSort(st)) - for j, si := range st { - if j != si.index { - t.Errorf("%d: failed: %v", i, st) - } - } - } - for i, tt := range genStateTests { - // ensure input is well-formed - sort.Sort(offsetSort(tt.in)) - for j, si := range tt.in { - if si.index != j+1 { - t.Errorf("%dth sort failed: %v", i, tt.in) - } - } - } -} - -var genidxtest1 = []stridx{ - {"bcde", 3}, - {"bc", 6}, - {"ab", 2}, - {"bcd", 5}, - {"abcd", 0}, - {"abc", 1}, - {"bcdf", 4}, -} - -var genidxSortTests = [][]stridx{ - genidxtest1, - largetosmall, -} - -func TestGenIdxSort(t *testing.T) { - for i, st := range genidxSortTests { - sort.Sort(genidxSort(st)) - for j, si := range st { - if j != si.index { - t.Errorf("%dth sort failed %v", i, st) - break - } - } - } -} - -var entrySortTests = []colltab.ContractTrieSet{ - { - {10, 0, 1, 3}, - {99, 0, 1, 0}, - {20, 50, 0, 2}, - {30, 0, 1, 1}, - }, -} - -func TestEntrySort(t *testing.T) { - for i, et := range entrySortTests { - sort.Sort(entrySort(et)) - for j, fe := range et { - if j != int(fe.I) { - t.Errorf("%dth sort failed %v", i, et) - break - } - } - } -} - -type GenStateTest struct { - in []stridx - firstBlockLen int - out colltab.ContractTrieSet -} - -var genStateTests = []GenStateTest{ - {[]stridx{ - {"abc", 1}, - }, - 1, - colltab.ContractTrieSet{ - {'a', 0, 1, noIndex}, - {'b', 0, 1, noIndex}, - {'c', 'c', final, 1}, - }, - }, - {[]stridx{ - {"abc", 1}, - {"abd", 2}, - {"abe", 3}, - }, - 1, - colltab.ContractTrieSet{ - {'a', 0, 1, noIndex}, - {'b', 0, 1, noIndex}, - {'c', 'e', final, 1}, - }, - }, - {[]stridx{ - {"abc", 1}, - {"ab", 2}, - {"a", 3}, - }, - 1, - colltab.ContractTrieSet{ - {'a', 0, 1, 3}, - {'b', 0, 1, 2}, - {'c', 'c', final, 1}, - }, - }, - {[]stridx{ - {"abc", 1}, - {"abd", 2}, - {"ab", 3}, - {"ac", 4}, - {"a", 5}, - {"b", 6}, - }, - 2, - colltab.ContractTrieSet{ - {'b', 'b', final, 6}, - {'a', 0, 2, 5}, - {'c', 'c', final, 4}, - {'b', 0, 1, 3}, - {'c', 'd', final, 1}, - }, - }, - {[]stridx{ - {"bcde", 2}, - {"bc", 7}, - {"ab", 6}, - {"bcd", 5}, - {"abcd", 1}, - {"abc", 4}, - {"bcdf", 3}, - }, - 2, - colltab.ContractTrieSet{ - {'b', 3, 1, noIndex}, - {'a', 0, 1, noIndex}, - {'b', 0, 1, 6}, - {'c', 0, 1, 4}, - {'d', 'd', final, 1}, - {'c', 0, 1, 7}, - {'d', 0, 1, 5}, - {'e', 'f', final, 2}, - }, - }, -} - -func TestGenStates(t *testing.T) { - for i, tt := range genStateTests { - si := []stridx{} - for _, e := range tt.in { - si = append(si, e) - } - // ensure input is well-formed - sort.Sort(genidxSort(si)) - ct := colltab.ContractTrieSet{} - n, _ := genStates(&ct, si) - if nn := tt.firstBlockLen; nn != n { - t.Errorf("%d: block len %v; want %v", i, n, nn) - } - if lv, lw := len(ct), len(tt.out); lv != lw { - t.Errorf("%d: len %v; want %v", i, lv, lw) - continue - } - for j, fe := range tt.out { - const msg = "%d:%d: value %s=%v; want %v" - if fe.L != ct[j].L { - t.Errorf(msg, i, j, "l", ct[j].L, fe.L) - } - if fe.H != ct[j].H { - t.Errorf(msg, i, j, "h", ct[j].H, fe.H) - } - if fe.N != ct[j].N { - t.Errorf(msg, i, j, "n", ct[j].N, fe.N) - } - if fe.I != ct[j].I { - t.Errorf(msg, i, j, "i", ct[j].I, fe.I) - } - } - } -} - -func TestLookupContraction(t *testing.T) { - for i, tt := range genStateTests { - input := []string{} - for _, e := range tt.in { - input = append(input, e.str) - } - cts := colltab.ContractTrieSet{} - h, _ := appendTrie(&cts, input) - for j, si := range tt.in { - str := si.str - for _, s := range []string{str, str + "X"} { - msg := "%d:%d: %s(%s) %v; want %v" - idx, sn := lookup(&cts, h, []byte(s)) - if idx != si.index { - t.Errorf(msg, i, j, "index", s, idx, si.index) - } - if sn != len(str) { - t.Errorf(msg, i, j, "sn", s, sn, len(str)) - } - } - } - } -} - -func TestPrintContractionTrieSet(t *testing.T) { - testdata := colltab.ContractTrieSet(genStateTests[4].out) - buf := &bytes.Buffer{} - print(&testdata, buf, "test") - if contractTrieOutput != buf.String() { - t.Errorf("output differs; found\n%s", buf.String()) - println(string(buf.Bytes())) - } -} - -const contractTrieOutput = `// testCTEntries: 8 entries, 32 bytes -var testCTEntries = [8]struct{L,H,N,I uint8}{ - {0x62, 0x3, 1, 255}, - {0x61, 0x0, 1, 255}, - {0x62, 0x0, 1, 6}, - {0x63, 0x0, 1, 4}, - {0x64, 0x64, 0, 1}, - {0x63, 0x0, 1, 7}, - {0x64, 0x0, 1, 5}, - {0x65, 0x66, 0, 2}, -} -var testContractTrieSet = colltab.ContractTrieSet( testCTEntries[:] ) -` diff --git a/vendor/golang.org/x/text/collate/build/order_test.go b/vendor/golang.org/x/text/collate/build/order_test.go deleted file mode 100644 index 0e174bfbd4..0000000000 --- a/vendor/golang.org/x/text/collate/build/order_test.go +++ /dev/null @@ -1,229 +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 build - -import ( - "strconv" - "testing" - - "golang.org/x/text/internal/colltab" -) - -type entryTest struct { - f func(in []int) (uint32, error) - arg []int - val uint32 -} - -// makeList returns a list of entries of length n+2, with n normal -// entries plus a leading and trailing anchor. -func makeList(n int) []*entry { - es := make([]*entry, n+2) - weights := []rawCE{{w: []int{100, 20, 5, 0}}} - for i := range es { - runes := []rune{rune(i)} - es[i] = &entry{ - runes: runes, - elems: weights, - } - weights = nextWeight(colltab.Primary, weights) - } - for i := 1; i < len(es); i++ { - es[i-1].next = es[i] - es[i].prev = es[i-1] - _, es[i-1].level = compareWeights(es[i-1].elems, es[i].elems) - } - es[0].exclude = true - es[0].logical = firstAnchor - es[len(es)-1].exclude = true - es[len(es)-1].logical = lastAnchor - return es -} - -func TestNextIndexed(t *testing.T) { - const n = 5 - es := makeList(n) - for i := int64(0); i < 1<<n; i++ { - mask := strconv.FormatInt(i+(1<<n), 2) - for i, c := range mask { - es[i].exclude = c == '1' - } - e := es[0] - for i, c := range mask { - if c == '0' { - e, _ = e.nextIndexed() - if e != es[i] { - t.Errorf("%d: expected entry %d; found %d", i, es[i].elems, e.elems) - } - } - } - if e, _ = e.nextIndexed(); e != nil { - t.Errorf("%d: expected nil entry; found %d", i, e.elems) - } - } -} - -func TestRemove(t *testing.T) { - const n = 5 - for i := int64(0); i < 1<<n; i++ { - es := makeList(n) - mask := strconv.FormatInt(i+(1<<n), 2) - for i, c := range mask { - if c == '0' { - es[i].remove() - } - } - e := es[0] - for i, c := range mask { - if c == '1' { - if e != es[i] { - t.Errorf("%d: expected entry %d; found %d", i, es[i].elems, e.elems) - } - e, _ = e.nextIndexed() - } - } - if e != nil { - t.Errorf("%d: expected nil entry; found %d", i, e.elems) - } - } -} - -// nextPerm generates the next permutation of the array. The starting -// permutation is assumed to be a list of integers sorted in increasing order. -// It returns false if there are no more permuations left. -func nextPerm(a []int) bool { - i := len(a) - 2 - for ; i >= 0; i-- { - if a[i] < a[i+1] { - break - } - } - if i < 0 { - return false - } - for j := len(a) - 1; j >= i; j-- { - if a[j] > a[i] { - a[i], a[j] = a[j], a[i] - break - } - } - for j := i + 1; j < (len(a)+i+1)/2; j++ { - a[j], a[len(a)+i-j] = a[len(a)+i-j], a[j] - } - return true -} - -func TestInsertAfter(t *testing.T) { - const n = 5 - orig := makeList(n) - perm := make([]int, n) - for i := range perm { - perm[i] = i + 1 - } - for ok := true; ok; ok = nextPerm(perm) { - es := makeList(n) - last := es[0] - for _, i := range perm { - last.insertAfter(es[i]) - last = es[i] - } - for _, e := range es { - e.elems = es[0].elems - } - e := es[0] - for _, i := range perm { - e, _ = e.nextIndexed() - if e.runes[0] != orig[i].runes[0] { - t.Errorf("%d:%d: expected entry %X; found %X", perm, i, orig[i].runes, e.runes) - break - } - } - } -} - -func TestInsertBefore(t *testing.T) { - const n = 5 - orig := makeList(n) - perm := make([]int, n) - for i := range perm { - perm[i] = i + 1 - } - for ok := true; ok; ok = nextPerm(perm) { - es := makeList(n) - last := es[len(es)-1] - for _, i := range perm { - last.insertBefore(es[i]) - last = es[i] - } - for _, e := range es { - e.elems = es[0].elems - } - e := es[0] - for i := n - 1; i >= 0; i-- { - e, _ = e.nextIndexed() - if e.runes[0] != rune(perm[i]) { - t.Errorf("%d:%d: expected entry %X; found %X", perm, i, orig[i].runes, e.runes) - break - } - } - } -} - -type entryLessTest struct { - a, b *entry - res bool -} - -var ( - w1 = []rawCE{{w: []int{100, 20, 5, 5}}} - w2 = []rawCE{{w: []int{101, 20, 5, 5}}} -) - -var entryLessTests = []entryLessTest{ - {&entry{str: "a", elems: w1}, - &entry{str: "a", elems: w1}, - false, - }, - {&entry{str: "a", elems: w1}, - &entry{str: "a", elems: w2}, - true, - }, - {&entry{str: "a", elems: w1}, - &entry{str: "b", elems: w1}, - true, - }, - {&entry{str: "a", elems: w2}, - &entry{str: "a", elems: w1}, - false, - }, - {&entry{str: "c", elems: w1}, - &entry{str: "b", elems: w1}, - false, - }, - {&entry{str: "a", elems: w1, logical: firstAnchor}, - &entry{str: "a", elems: w1}, - true, - }, - {&entry{str: "a", elems: w1}, - &entry{str: "b", elems: w1, logical: firstAnchor}, - false, - }, - {&entry{str: "b", elems: w1}, - &entry{str: "a", elems: w1, logical: lastAnchor}, - true, - }, - {&entry{str: "a", elems: w1, logical: lastAnchor}, - &entry{str: "c", elems: w1}, - false, - }, -} - -func TestEntryLess(t *testing.T) { - for i, tt := range entryLessTests { - if res := entryLess(tt.a, tt.b); res != tt.res { - t.Errorf("%d: was %v; want %v", i, res, tt.res) - } - } -} diff --git a/vendor/golang.org/x/text/collate/build/trie_test.go b/vendor/golang.org/x/text/collate/build/trie_test.go deleted file mode 100644 index 4d4f6e4d14..0000000000 --- a/vendor/golang.org/x/text/collate/build/trie_test.go +++ /dev/null @@ -1,107 +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 build - -import ( - "bytes" - "fmt" - "testing" -) - -// We take the smallest, largest and an arbitrary value for each -// of the UTF-8 sequence lengths. -var testRunes = []rune{ - 0x01, 0x0C, 0x7F, // 1-byte sequences - 0x80, 0x100, 0x7FF, // 2-byte sequences - 0x800, 0x999, 0xFFFF, // 3-byte sequences - 0x10000, 0x10101, 0x10FFFF, // 4-byte sequences - 0x200, 0x201, 0x202, 0x210, 0x215, // five entries in one sparse block -} - -func makeTestTrie(t *testing.T) trie { - n := newNode() - for i, r := range testRunes { - n.insert(r, uint32(i)) - } - idx := newTrieBuilder() - idx.addTrie(n) - tr, err := idx.generate() - if err != nil { - t.Errorf(err.Error()) - } - return *tr -} - -func TestGenerateTrie(t *testing.T) { - testdata := makeTestTrie(t) - buf := &bytes.Buffer{} - testdata.printArrays(buf, "test") - fmt.Fprintf(buf, "var testTrie = ") - testdata.printStruct(buf, &trieHandle{19, 0}, "test") - if output != buf.String() { - t.Error("output differs") - } -} - -var output = `// testValues: 832 entries, 3328 bytes -// Block 2 is the null block. -var testValues = [832]uint32 { - // Block 0x0, offset 0x0 - 0x000c:0x00000001, - // Block 0x1, offset 0x40 - 0x007f:0x00000002, - // Block 0x2, offset 0x80 - // Block 0x3, offset 0xc0 - 0x00c0:0x00000003, - // Block 0x4, offset 0x100 - 0x0100:0x00000004, - // Block 0x5, offset 0x140 - 0x0140:0x0000000c, 0x0141:0x0000000d, 0x0142:0x0000000e, - 0x0150:0x0000000f, - 0x0155:0x00000010, - // Block 0x6, offset 0x180 - 0x01bf:0x00000005, - // Block 0x7, offset 0x1c0 - 0x01c0:0x00000006, - // Block 0x8, offset 0x200 - 0x0219:0x00000007, - // Block 0x9, offset 0x240 - 0x027f:0x00000008, - // Block 0xa, offset 0x280 - 0x0280:0x00000009, - // Block 0xb, offset 0x2c0 - 0x02c1:0x0000000a, - // Block 0xc, offset 0x300 - 0x033f:0x0000000b, -} - -// testLookup: 640 entries, 1280 bytes -// Block 0 is the null block. -var testLookup = [640]uint16 { - // Block 0x0, offset 0x0 - // Block 0x1, offset 0x40 - // Block 0x2, offset 0x80 - // Block 0x3, offset 0xc0 - 0x0e0:0x05, 0x0e6:0x06, - // Block 0x4, offset 0x100 - 0x13f:0x07, - // Block 0x5, offset 0x140 - 0x140:0x08, 0x144:0x09, - // Block 0x6, offset 0x180 - 0x190:0x03, - // Block 0x7, offset 0x1c0 - 0x1ff:0x0a, - // Block 0x8, offset 0x200 - 0x20f:0x05, - // Block 0x9, offset 0x240 - 0x242:0x01, 0x244:0x02, - 0x248:0x03, - 0x25f:0x04, - 0x260:0x01, - 0x26f:0x02, - 0x270:0x04, 0x274:0x06, -} - -var testTrie = trie{ testLookup[1216:], testValues[0:], testLookup[:], testValues[:]}` diff --git a/vendor/golang.org/x/text/collate/collate_test.go b/vendor/golang.org/x/text/collate/collate_test.go deleted file mode 100644 index 0e78b96fae..0000000000 --- a/vendor/golang.org/x/text/collate/collate_test.go +++ /dev/null @@ -1,482 +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 collate - -import ( - "bytes" - "testing" - - "golang.org/x/text/internal/colltab" - "golang.org/x/text/language" -) - -type weightsTest struct { - opt opts - in, out ColElems -} - -type opts struct { - lev int - alt alternateHandling - top int - - backwards bool - caseLevel bool -} - -// ignore returns an initialized boolean array based on the given Level. -// A negative value means using the default setting of quaternary. -func ignore(level colltab.Level) (ignore [colltab.NumLevels]bool) { - if level < 0 { - level = colltab.Quaternary - } - for i := range ignore { - ignore[i] = level < colltab.Level(i) - } - return ignore -} - -func makeCE(w []int) colltab.Elem { - ce, err := colltab.MakeElem(w[0], w[1], w[2], uint8(w[3])) - if err != nil { - panic(err) - } - return ce -} - -func (o opts) collator() *Collator { - c := &Collator{ - options: options{ - ignore: ignore(colltab.Level(o.lev - 1)), - alternate: o.alt, - backwards: o.backwards, - caseLevel: o.caseLevel, - variableTop: uint32(o.top), - }, - } - return c -} - -const ( - maxQ = 0x1FFFFF -) - -func wpq(p, q int) Weights { - return W(p, defaults.Secondary, defaults.Tertiary, q) -} - -func wsq(s, q int) Weights { - return W(0, s, defaults.Tertiary, q) -} - -func wq(q int) Weights { - return W(0, 0, 0, q) -} - -var zero = W(0, 0, 0, 0) - -var processTests = []weightsTest{ - // Shifted - { // simple sequence of non-variables - opt: opts{alt: altShifted, top: 100}, - in: ColElems{W(200), W(300), W(400)}, - out: ColElems{wpq(200, maxQ), wpq(300, maxQ), wpq(400, maxQ)}, - }, - { // first is a variable - opt: opts{alt: altShifted, top: 250}, - in: ColElems{W(200), W(300), W(400)}, - out: ColElems{wq(200), wpq(300, maxQ), wpq(400, maxQ)}, - }, - { // all but first are variable - opt: opts{alt: altShifted, top: 999}, - in: ColElems{W(1000), W(200), W(300), W(400)}, - out: ColElems{wpq(1000, maxQ), wq(200), wq(300), wq(400)}, - }, - { // first is a modifier - opt: opts{alt: altShifted, top: 999}, - in: ColElems{W(0, 10), W(1000)}, - out: ColElems{wsq(10, maxQ), wpq(1000, maxQ)}, - }, - { // primary ignorables - opt: opts{alt: altShifted, top: 250}, - in: ColElems{W(200), W(0, 10), W(300), W(0, 15), W(400)}, - out: ColElems{wq(200), zero, wpq(300, maxQ), wsq(15, maxQ), wpq(400, maxQ)}, - }, - { // secondary ignorables - opt: opts{alt: altShifted, top: 250}, - in: ColElems{W(200), W(0, 0, 10), W(300), W(0, 0, 15), W(400)}, - out: ColElems{wq(200), zero, wpq(300, maxQ), W(0, 0, 15, maxQ), wpq(400, maxQ)}, - }, - { // tertiary ignorables, no change - opt: opts{alt: altShifted, top: 250}, - in: ColElems{W(200), zero, W(300), zero, W(400)}, - out: ColElems{wq(200), zero, wpq(300, maxQ), zero, wpq(400, maxQ)}, - }, - - // ShiftTrimmed (same as Shifted) - { // simple sequence of non-variables - opt: opts{alt: altShiftTrimmed, top: 100}, - in: ColElems{W(200), W(300), W(400)}, - out: ColElems{wpq(200, maxQ), wpq(300, maxQ), wpq(400, maxQ)}, - }, - { // first is a variable - opt: opts{alt: altShiftTrimmed, top: 250}, - in: ColElems{W(200), W(300), W(400)}, - out: ColElems{wq(200), wpq(300, maxQ), wpq(400, maxQ)}, - }, - { // all but first are variable - opt: opts{alt: altShiftTrimmed, top: 999}, - in: ColElems{W(1000), W(200), W(300), W(400)}, - out: ColElems{wpq(1000, maxQ), wq(200), wq(300), wq(400)}, - }, - { // first is a modifier - opt: opts{alt: altShiftTrimmed, top: 999}, - in: ColElems{W(0, 10), W(1000)}, - out: ColElems{wsq(10, maxQ), wpq(1000, maxQ)}, - }, - { // primary ignorables - opt: opts{alt: altShiftTrimmed, top: 250}, - in: ColElems{W(200), W(0, 10), W(300), W(0, 15), W(400)}, - out: ColElems{wq(200), zero, wpq(300, maxQ), wsq(15, maxQ), wpq(400, maxQ)}, - }, - { // secondary ignorables - opt: opts{alt: altShiftTrimmed, top: 250}, - in: ColElems{W(200), W(0, 0, 10), W(300), W(0, 0, 15), W(400)}, - out: ColElems{wq(200), zero, wpq(300, maxQ), W(0, 0, 15, maxQ), wpq(400, maxQ)}, - }, - { // tertiary ignorables, no change - opt: opts{alt: altShiftTrimmed, top: 250}, - in: ColElems{W(200), zero, W(300), zero, W(400)}, - out: ColElems{wq(200), zero, wpq(300, maxQ), zero, wpq(400, maxQ)}, - }, - - // Blanked - { // simple sequence of non-variables - opt: opts{alt: altBlanked, top: 100}, - in: ColElems{W(200), W(300), W(400)}, - out: ColElems{W(200), W(300), W(400)}, - }, - { // first is a variable - opt: opts{alt: altBlanked, top: 250}, - in: ColElems{W(200), W(300), W(400)}, - out: ColElems{zero, W(300), W(400)}, - }, - { // all but first are variable - opt: opts{alt: altBlanked, top: 999}, - in: ColElems{W(1000), W(200), W(300), W(400)}, - out: ColElems{W(1000), zero, zero, zero}, - }, - { // first is a modifier - opt: opts{alt: altBlanked, top: 999}, - in: ColElems{W(0, 10), W(1000)}, - out: ColElems{W(0, 10), W(1000)}, - }, - { // primary ignorables - opt: opts{alt: altBlanked, top: 250}, - in: ColElems{W(200), W(0, 10), W(300), W(0, 15), W(400)}, - out: ColElems{zero, zero, W(300), W(0, 15), W(400)}, - }, - { // secondary ignorables - opt: opts{alt: altBlanked, top: 250}, - in: ColElems{W(200), W(0, 0, 10), W(300), W(0, 0, 15), W(400)}, - out: ColElems{zero, zero, W(300), W(0, 0, 15), W(400)}, - }, - { // tertiary ignorables, no change - opt: opts{alt: altBlanked, top: 250}, - in: ColElems{W(200), zero, W(300), zero, W(400)}, - out: ColElems{zero, zero, W(300), zero, W(400)}, - }, - - // Non-ignorable: input is always equal to output. - { // all but first are variable - opt: opts{alt: altNonIgnorable, top: 999}, - in: ColElems{W(1000), W(200), W(300), W(400)}, - out: ColElems{W(1000), W(200), W(300), W(400)}, - }, - { // primary ignorables - opt: opts{alt: altNonIgnorable, top: 250}, - in: ColElems{W(200), W(0, 10), W(300), W(0, 15), W(400)}, - out: ColElems{W(200), W(0, 10), W(300), W(0, 15), W(400)}, - }, - { // secondary ignorables - opt: opts{alt: altNonIgnorable, top: 250}, - in: ColElems{W(200), W(0, 0, 10), W(300), W(0, 0, 15), W(400)}, - out: ColElems{W(200), W(0, 0, 10), W(300), W(0, 0, 15), W(400)}, - }, - { // tertiary ignorables, no change - opt: opts{alt: altNonIgnorable, top: 250}, - in: ColElems{W(200), zero, W(300), zero, W(400)}, - out: ColElems{W(200), zero, W(300), zero, W(400)}, - }, -} - -func TestProcessWeights(t *testing.T) { - for i, tt := range processTests { - in := convertFromWeights(tt.in) - out := convertFromWeights(tt.out) - processWeights(tt.opt.alt, uint32(tt.opt.top), in) - for j, w := range in { - if w != out[j] { - t.Errorf("%d: Weights %d was %v; want %v", i, j, w, out[j]) - } - } - } -} - -type keyFromElemTest struct { - opt opts - in ColElems - out []byte -} - -var defS = byte(defaults.Secondary) -var defT = byte(defaults.Tertiary) - -const sep = 0 // separator byte - -var keyFromElemTests = []keyFromElemTest{ - { // simple primary and secondary weights. - opts{alt: altShifted}, - ColElems{W(0x200), W(0x7FFF), W(0, 0x30), W(0x100)}, - []byte{0x2, 0, 0x7F, 0xFF, 0x1, 0x00, // primary - sep, sep, 0, defS, 0, defS, 0, 0x30, 0, defS, // secondary - sep, sep, defT, defT, defT, defT, // tertiary - sep, 0xFF, 0xFF, 0xFF, 0xFF, // quaternary - }, - }, - { // same as first, but with zero element that need to be removed - opts{alt: altShifted}, - ColElems{W(0x200), zero, W(0x7FFF), W(0, 0x30), zero, W(0x100)}, - []byte{0x2, 0, 0x7F, 0xFF, 0x1, 0x00, // primary - sep, sep, 0, defS, 0, defS, 0, 0x30, 0, defS, // secondary - sep, sep, defT, defT, defT, defT, // tertiary - sep, 0xFF, 0xFF, 0xFF, 0xFF, // quaternary - }, - }, - { // same as first, with large primary values - opts{alt: altShifted}, - ColElems{W(0x200), W(0x8000), W(0, 0x30), W(0x12345)}, - []byte{0x2, 0, 0x80, 0x80, 0x00, 0x81, 0x23, 0x45, // primary - sep, sep, 0, defS, 0, defS, 0, 0x30, 0, defS, // secondary - sep, sep, defT, defT, defT, defT, // tertiary - sep, 0xFF, 0xFF, 0xFF, 0xFF, // quaternary - }, - }, - { // same as first, but with the secondary level backwards - opts{alt: altShifted, backwards: true}, - ColElems{W(0x200), W(0x7FFF), W(0, 0x30), W(0x100)}, - []byte{0x2, 0, 0x7F, 0xFF, 0x1, 0x00, // primary - sep, sep, 0, defS, 0, 0x30, 0, defS, 0, defS, // secondary - sep, sep, defT, defT, defT, defT, // tertiary - sep, 0xFF, 0xFF, 0xFF, 0xFF, // quaternary - }, - }, - { // same as first, ignoring quaternary level - opts{alt: altShifted, lev: 3}, - ColElems{W(0x200), zero, W(0x7FFF), W(0, 0x30), zero, W(0x100)}, - []byte{0x2, 0, 0x7F, 0xFF, 0x1, 0x00, // primary - sep, sep, 0, defS, 0, defS, 0, 0x30, 0, defS, // secondary - sep, sep, defT, defT, defT, defT, // tertiary - }, - }, - { // same as first, ignoring tertiary level - opts{alt: altShifted, lev: 2}, - ColElems{W(0x200), zero, W(0x7FFF), W(0, 0x30), zero, W(0x100)}, - []byte{0x2, 0, 0x7F, 0xFF, 0x1, 0x00, // primary - sep, sep, 0, defS, 0, defS, 0, 0x30, 0, defS, // secondary - }, - }, - { // same as first, ignoring secondary level - opts{alt: altShifted, lev: 1}, - ColElems{W(0x200), zero, W(0x7FFF), W(0, 0x30), zero, W(0x100)}, - []byte{0x2, 0, 0x7F, 0xFF, 0x1, 0x00}, - }, - { // simple primary and secondary weights. - opts{alt: altShiftTrimmed, top: 0x250}, - ColElems{W(0x300), W(0x200), W(0x7FFF), W(0, 0x30), W(0x800)}, - []byte{0x3, 0, 0x7F, 0xFF, 0x8, 0x00, // primary - sep, sep, 0, defS, 0, defS, 0, 0x30, 0, defS, // secondary - sep, sep, defT, defT, defT, defT, // tertiary - sep, 0xFF, 0x2, 0, // quaternary - }, - }, - { // as first, primary with case level enabled - opts{alt: altShifted, lev: 1, caseLevel: true}, - ColElems{W(0x200), W(0x7FFF), W(0, 0x30), W(0x100)}, - []byte{0x2, 0, 0x7F, 0xFF, 0x1, 0x00, // primary - sep, sep, // secondary - sep, sep, defT, defT, defT, defT, // tertiary - }, - }, -} - -func TestKeyFromElems(t *testing.T) { - buf := Buffer{} - for i, tt := range keyFromElemTests { - buf.Reset() - in := convertFromWeights(tt.in) - processWeights(tt.opt.alt, uint32(tt.opt.top), in) - tt.opt.collator().keyFromElems(&buf, in) - res := buf.key - if len(res) != len(tt.out) { - t.Errorf("%d: len(ws) was %d; want %d (%X should be %X)", i, len(res), len(tt.out), res, tt.out) - } - n := len(res) - if len(tt.out) < n { - n = len(tt.out) - } - for j, c := range res[:n] { - if c != tt.out[j] { - t.Errorf("%d: byte %d was %X; want %X", i, j, c, tt.out[j]) - } - } - } -} - -func TestGetColElems(t *testing.T) { - for i, tt := range appendNextTests { - c, err := makeTable(tt.in) - if err != nil { - // error is reported in TestAppendNext - continue - } - // Create one large test per table - str := make([]byte, 0, 4000) - out := ColElems{} - for len(str) < 3000 { - for _, chk := range tt.chk { - str = append(str, chk.in[:chk.n]...) - out = append(out, chk.out...) - } - } - for j, chk := range append(tt.chk, check{string(str), len(str), out}) { - out := convertFromWeights(chk.out) - ce := c.getColElems([]byte(chk.in)[:chk.n]) - if len(ce) != len(out) { - t.Errorf("%d:%d: len(ws) was %d; want %d", i, j, len(ce), len(out)) - continue - } - cnt := 0 - for k, w := range ce { - w, _ = colltab.MakeElem(w.Primary(), w.Secondary(), int(w.Tertiary()), 0) - if w != out[k] { - t.Errorf("%d:%d: Weights %d was %X; want %X", i, j, k, w, out[k]) - cnt++ - } - if cnt > 10 { - break - } - } - } - } -} - -type keyTest struct { - in string - out []byte -} - -var keyTests = []keyTest{ - {"abc", - []byte{0, 100, 0, 200, 1, 44, 0, 0, 0, 32, 0, 32, 0, 32, 0, 0, 2, 2, 2, 0, 255, 255, 255}, - }, - {"a\u0301", - []byte{0, 102, 0, 0, 0, 32, 0, 0, 2, 0, 255}, - }, - {"aaaaa", - []byte{0, 100, 0, 100, 0, 100, 0, 100, 0, 100, 0, 0, - 0, 32, 0, 32, 0, 32, 0, 32, 0, 32, 0, 0, - 2, 2, 2, 2, 2, 0, - 255, 255, 255, 255, 255, - }, - }, - // Issue 16391: incomplete rune at end of UTF-8 sequence. - {"\xc2", []byte{133, 255, 253, 0, 0, 0, 32, 0, 0, 2, 0, 255}}, - {"\xc2a", []byte{133, 255, 253, 0, 100, 0, 0, 0, 32, 0, 32, 0, 0, 2, 2, 0, 255, 255}}, -} - -func TestKey(t *testing.T) { - c, _ := makeTable(appendNextTests[4].in) - c.alternate = altShifted - c.ignore = ignore(colltab.Quaternary) - buf := Buffer{} - keys1 := [][]byte{} - keys2 := [][]byte{} - for _, tt := range keyTests { - keys1 = append(keys1, c.Key(&buf, []byte(tt.in))) - keys2 = append(keys2, c.KeyFromString(&buf, tt.in)) - } - // Separate generation from testing to ensure buffers are not overwritten. - for i, tt := range keyTests { - if !bytes.Equal(keys1[i], tt.out) { - t.Errorf("%d: Key(%q) = %d; want %d", i, tt.in, keys1[i], tt.out) - } - if !bytes.Equal(keys2[i], tt.out) { - t.Errorf("%d: KeyFromString(%q) = %d; want %d", i, tt.in, keys2[i], tt.out) - } - } -} - -type compareTest struct { - a, b string - res int // comparison result -} - -var compareTests = []compareTest{ - {"a\u0301", "a", 1}, - {"a\u0301b", "ab", 1}, - {"a", "a\u0301", -1}, - {"ab", "a\u0301b", -1}, - {"bc", "a\u0301c", 1}, - {"ab", "aB", -1}, - {"a\u0301", "a\u0301", 0}, - {"a", "a", 0}, - // Only clip prefixes of whole runes. - {"\u302E", "\u302F", 1}, - // Don't clip prefixes when last rune of prefix may be part of contraction. - {"a\u035E", "a\u0301\u035F", -1}, - {"a\u0301\u035Fb", "a\u0301\u035F", -1}, -} - -func TestCompare(t *testing.T) { - c, _ := makeTable(appendNextTests[4].in) - for i, tt := range compareTests { - if res := c.Compare([]byte(tt.a), []byte(tt.b)); res != tt.res { - t.Errorf("%d: Compare(%q, %q) == %d; want %d", i, tt.a, tt.b, res, tt.res) - } - if res := c.CompareString(tt.a, tt.b); res != tt.res { - t.Errorf("%d: CompareString(%q, %q) == %d; want %d", i, tt.a, tt.b, res, tt.res) - } - } -} - -func TestNumeric(t *testing.T) { - c := New(language.English, Loose, Numeric) - - for i, tt := range []struct { - a, b string - want int - }{ - {"1", "2", -1}, - {"2", "12", -1}, - {"2", "12", -1}, // Fullwidth is sorted as usual. - {"₂", "₁₂", 1}, // Subscript is not sorted as numbers. - {"②", "①②", 1}, // Circled is not sorted as numbers. - { // Imperial Aramaic, is not sorted as number. - "\U00010859", - "\U00010858\U00010859", - 1, - }, - {"12", "2", 1}, - {"A-1", "A-2", -1}, - {"A-2", "A-12", -1}, - {"A-12", "A-2", 1}, - {"A-0001", "A-1", 0}, - } { - if got := c.CompareString(tt.a, tt.b); got != tt.want { - t.Errorf("%d: CompareString(%s, %s) = %d; want %d", i, tt.a, tt.b, got, tt.want) - } - } -} diff --git a/vendor/golang.org/x/text/collate/export_test.go b/vendor/golang.org/x/text/collate/export_test.go deleted file mode 100644 index 69bfeaf1ac..0000000000 --- a/vendor/golang.org/x/text/collate/export_test.go +++ /dev/null @@ -1,51 +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 collate - -// Export for testing. -// TODO: no longer necessary. Remove at some point. - -import ( - "fmt" - - "golang.org/x/text/internal/colltab" -) - -const ( - defaultSecondary = 0x20 - defaultTertiary = 0x2 -) - -type Weights struct { - Primary, Secondary, Tertiary, Quaternary int -} - -func W(ce ...int) Weights { - w := Weights{ce[0], defaultSecondary, defaultTertiary, 0} - if len(ce) > 1 { - w.Secondary = ce[1] - } - if len(ce) > 2 { - w.Tertiary = ce[2] - } - if len(ce) > 3 { - w.Quaternary = ce[3] - } - return w -} -func (w Weights) String() string { - return fmt.Sprintf("[%X.%X.%X.%X]", w.Primary, w.Secondary, w.Tertiary, w.Quaternary) -} - -func convertFromWeights(ws []Weights) []colltab.Elem { - out := make([]colltab.Elem, len(ws)) - for i, w := range ws { - out[i], _ = colltab.MakeElem(w.Primary, w.Secondary, w.Tertiary, 0) - if out[i] == colltab.Ignore && w.Quaternary > 0 { - out[i] = colltab.MakeQuaternary(w.Quaternary) - } - } - return out -} diff --git a/vendor/golang.org/x/text/collate/option_test.go b/vendor/golang.org/x/text/collate/option_test.go deleted file mode 100644 index 0f6ba9bc81..0000000000 --- a/vendor/golang.org/x/text/collate/option_test.go +++ /dev/null @@ -1,209 +0,0 @@ -// Copyright 2014 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 collate - -import ( - "reflect" - "strings" - "testing" - - "golang.org/x/text/internal/colltab" - "golang.org/x/text/language" -) - -var ( - defaultIgnore = ignore(colltab.Tertiary) - defaultTable = getTable(locales[0]) -) - -func TestOptions(t *testing.T) { - for i, tt := range []struct { - in []Option - out options - }{ - 0: { - out: options{ - ignore: defaultIgnore, - }, - }, - 1: { - in: []Option{IgnoreDiacritics}, - out: options{ - ignore: [colltab.NumLevels]bool{false, true, false, true, true}, - }, - }, - 2: { - in: []Option{IgnoreCase, IgnoreDiacritics}, - out: options{ - ignore: ignore(colltab.Primary), - }, - }, - 3: { - in: []Option{ignoreDiacritics, IgnoreWidth}, - out: options{ - ignore: ignore(colltab.Primary), - caseLevel: true, - }, - }, - 4: { - in: []Option{IgnoreWidth, ignoreDiacritics}, - out: options{ - ignore: ignore(colltab.Primary), - caseLevel: true, - }, - }, - 5: { - in: []Option{IgnoreCase, IgnoreWidth}, - out: options{ - ignore: ignore(colltab.Secondary), - }, - }, - 6: { - in: []Option{IgnoreCase, IgnoreWidth, Loose}, - out: options{ - ignore: ignore(colltab.Primary), - }, - }, - 7: { - in: []Option{Force, IgnoreCase, IgnoreWidth, Loose}, - out: options{ - ignore: [colltab.NumLevels]bool{false, true, true, true, false}, - }, - }, - 8: { - in: []Option{IgnoreDiacritics, IgnoreCase}, - out: options{ - ignore: ignore(colltab.Primary), - }, - }, - 9: { - in: []Option{Numeric}, - out: options{ - ignore: defaultIgnore, - numeric: true, - }, - }, - 10: { - in: []Option{OptionsFromTag(language.MustParse("und-u-ks-level1"))}, - out: options{ - ignore: ignore(colltab.Primary), - }, - }, - 11: { - in: []Option{OptionsFromTag(language.MustParse("und-u-ks-level4"))}, - out: options{ - ignore: ignore(colltab.Quaternary), - }, - }, - 12: { - in: []Option{OptionsFromTag(language.MustParse("und-u-ks-identic"))}, - out: options{}, - }, - 13: { - in: []Option{ - OptionsFromTag(language.MustParse("und-u-kn-true-kb-true-kc-true")), - }, - out: options{ - ignore: defaultIgnore, - caseLevel: true, - backwards: true, - numeric: true, - }, - }, - 14: { - in: []Option{ - OptionsFromTag(language.MustParse("und-u-kn-true-kb-true-kc-true")), - OptionsFromTag(language.MustParse("und-u-kn-false-kb-false-kc-false")), - }, - out: options{ - ignore: defaultIgnore, - }, - }, - 15: { - in: []Option{ - OptionsFromTag(language.MustParse("und-u-kn-true-kb-true-kc-true")), - OptionsFromTag(language.MustParse("und-u-kn-foo-kb-foo-kc-foo")), - }, - out: options{ - ignore: defaultIgnore, - caseLevel: true, - backwards: true, - numeric: true, - }, - }, - 16: { // Normal options take precedence over tag options. - in: []Option{ - Numeric, IgnoreCase, - OptionsFromTag(language.MustParse("und-u-kn-false-kc-true")), - }, - out: options{ - ignore: ignore(colltab.Secondary), - caseLevel: false, - numeric: true, - }, - }, - 17: { - in: []Option{ - OptionsFromTag(language.MustParse("und-u-ka-shifted")), - }, - out: options{ - ignore: defaultIgnore, - alternate: altShifted, - }, - }, - 18: { - in: []Option{ - OptionsFromTag(language.MustParse("und-u-ka-blanked")), - }, - out: options{ - ignore: defaultIgnore, - alternate: altBlanked, - }, - }, - 19: { - in: []Option{ - OptionsFromTag(language.MustParse("und-u-ka-posix")), - }, - out: options{ - ignore: defaultIgnore, - alternate: altShiftTrimmed, - }, - }, - } { - c := newCollator(defaultTable) - c.t = nil - c.variableTop = 0 - c.f = 0 - - c.setOptions(tt.in) - if !reflect.DeepEqual(c.options, tt.out) { - t.Errorf("%d: got %v; want %v", i, c.options, tt.out) - } - } -} - -func TestAlternateSortTypes(t *testing.T) { - testCases := []struct { - lang string - in []string - want []string - }{{ - lang: "zh,cmn,zh-Hant-u-co-pinyin,zh-HK-u-co-pinyin,zh-pinyin", - in: []string{"爸爸", "妈妈", "儿子", "女儿"}, - want: []string{"爸爸", "儿子", "妈妈", "女儿"}, - }, { - lang: "zh-Hant,zh-u-co-stroke,zh-Hant-u-co-stroke", - in: []string{"爸爸", "妈妈", "儿子", "女儿"}, - want: []string{"儿子", "女儿", "妈妈", "爸爸"}, - }} - for _, tc := range testCases { - for _, tag := range strings.Split(tc.lang, ",") { - got := append([]string{}, tc.in...) - New(language.MustParse(tag)).SortStrings(got) - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("New(%s).SortStrings(%v) = %v; want %v", tag, tc.in, got, tc.want) - } - } - } -} diff --git a/vendor/golang.org/x/text/collate/reg_test.go b/vendor/golang.org/x/text/collate/reg_test.go deleted file mode 100644 index 1ac5fedc8a..0000000000 --- a/vendor/golang.org/x/text/collate/reg_test.go +++ /dev/null @@ -1,230 +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 collate - -import ( - "archive/zip" - "bufio" - "bytes" - "flag" - "io" - "io/ioutil" - "log" - "path" - "regexp" - "strconv" - "strings" - "testing" - "unicode/utf8" - - "golang.org/x/text/collate/build" - "golang.org/x/text/internal/gen" - "golang.org/x/text/language" -) - -var long = flag.Bool("long", false, - "run time-consuming tests, such as tests that fetch data online") - -// This regression test runs tests for the test files in CollationTest.zip -// (taken from http://www.unicode.org/Public/UCA/<gen.UnicodeVersion()>/). -// -// The test files have the following form: -// # header -// 0009 0021; # ('\u0009') <CHARACTER TABULATION> [| | | 0201 025E] -// 0009 003F; # ('\u0009') <CHARACTER TABULATION> [| | | 0201 0263] -// 000A 0021; # ('\u000A') <LINE FEED (LF)> [| | | 0202 025E] -// 000A 003F; # ('\u000A') <LINE FEED (LF)> [| | | 0202 0263] -// -// The part before the semicolon is the hex representation of a sequence -// of runes. After the hash mark is a comment. The strings -// represented by rune sequence are in the file in sorted order, as -// defined by the DUCET. - -type Test struct { - name string - str [][]byte - comment []string -} - -var versionRe = regexp.MustCompile(`# UCA Version: (.*)\n?$`) -var testRe = regexp.MustCompile(`^([\dA-F ]+);.*# (.*)\n?$`) - -func TestCollation(t *testing.T) { - if !gen.IsLocal() && !*long { - t.Skip("skipping test to prevent downloading; to run use -long or use -local to specify a local source") - } - t.Skip("must first update to new file format to support test") - for _, test := range loadTestData() { - doTest(t, test) - } -} - -func Error(e error) { - if e != nil { - log.Fatal(e) - } -} - -// parseUCA parses a Default Unicode Collation Element Table of the format -// specified in http://www.unicode.org/reports/tr10/#File_Format. -// It returns the variable top. -func parseUCA(builder *build.Builder) { - r := gen.OpenUnicodeFile("UCA", "", "allkeys.txt") - defer r.Close() - input := bufio.NewReader(r) - colelem := regexp.MustCompile(`\[([.*])([0-9A-F.]+)\]`) - for i := 1; true; i++ { - l, prefix, err := input.ReadLine() - if err == io.EOF { - break - } - Error(err) - line := string(l) - if prefix { - log.Fatalf("%d: buffer overflow", i) - } - if len(line) == 0 || line[0] == '#' { - continue - } - if line[0] == '@' { - if strings.HasPrefix(line[1:], "version ") { - if v := strings.Split(line[1:], " ")[1]; v != gen.UnicodeVersion() { - log.Fatalf("incompatible version %s; want %s", v, gen.UnicodeVersion()) - } - } - } else { - // parse entries - part := strings.Split(line, " ; ") - if len(part) != 2 { - log.Fatalf("%d: production rule without ';': %v", i, line) - } - lhs := []rune{} - for _, v := range strings.Split(part[0], " ") { - if v != "" { - lhs = append(lhs, rune(convHex(i, v))) - } - } - vars := []int{} - rhs := [][]int{} - for i, m := range colelem.FindAllStringSubmatch(part[1], -1) { - if m[1] == "*" { - vars = append(vars, i) - } - elem := []int{} - for _, h := range strings.Split(m[2], ".") { - elem = append(elem, convHex(i, h)) - } - rhs = append(rhs, elem) - } - builder.Add(lhs, rhs, vars) - } - } -} - -func convHex(line int, s string) int { - r, e := strconv.ParseInt(s, 16, 32) - if e != nil { - log.Fatalf("%d: %v", line, e) - } - return int(r) -} - -func loadTestData() []Test { - f := gen.OpenUnicodeFile("UCA", "", "CollationTest.zip") - buffer, err := ioutil.ReadAll(f) - f.Close() - Error(err) - archive, err := zip.NewReader(bytes.NewReader(buffer), int64(len(buffer))) - Error(err) - tests := []Test{} - for _, f := range archive.File { - // Skip the short versions, which are simply duplicates of the long versions. - if strings.Contains(f.Name, "SHORT") || f.FileInfo().IsDir() { - continue - } - ff, err := f.Open() - Error(err) - defer ff.Close() - scanner := bufio.NewScanner(ff) - test := Test{name: path.Base(f.Name)} - for scanner.Scan() { - line := scanner.Text() - if len(line) <= 1 || line[0] == '#' { - if m := versionRe.FindStringSubmatch(line); m != nil { - if m[1] != gen.UnicodeVersion() { - log.Printf("warning:%s: version is %s; want %s", f.Name, m[1], gen.UnicodeVersion()) - } - } - continue - } - m := testRe.FindStringSubmatch(line) - if m == nil || len(m) < 3 { - log.Fatalf(`Failed to parse: "%s" result: %#v`, line, m) - } - str := []byte{} - // In the regression test data (unpaired) surrogates are assigned a weight - // corresponding to their code point value. However, utf8.DecodeRune, - // which is used to compute the implicit weight, assigns FFFD to surrogates. - // We therefore skip tests with surrogates. This skips about 35 entries - // per test. - valid := true - for _, split := range strings.Split(m[1], " ") { - r, err := strconv.ParseUint(split, 16, 64) - Error(err) - valid = valid && utf8.ValidRune(rune(r)) - str = append(str, string(rune(r))...) - } - if valid { - test.str = append(test.str, str) - test.comment = append(test.comment, m[2]) - } - } - if scanner.Err() != nil { - log.Fatal(scanner.Err()) - } - tests = append(tests, test) - } - return tests -} - -var errorCount int - -func runes(b []byte) []rune { - return []rune(string(b)) -} - -var shifted = language.MustParse("und-u-ka-shifted-ks-level4") - -func doTest(t *testing.T, tc Test) { - bld := build.NewBuilder() - parseUCA(bld) - w, err := bld.Build() - Error(err) - var tag language.Tag - if !strings.Contains(tc.name, "NON_IGNOR") { - tag = shifted - } - c := NewFromTable(w, OptionsFromTag(tag)) - b := &Buffer{} - prev := tc.str[0] - for i := 1; i < len(tc.str); i++ { - b.Reset() - s := tc.str[i] - ka := c.Key(b, prev) - kb := c.Key(b, s) - if r := bytes.Compare(ka, kb); r == 1 { - t.Errorf("%s:%d: Key(%.4X) < Key(%.4X) (%X < %X) == %d; want -1 or 0", tc.name, i, []rune(string(prev)), []rune(string(s)), ka, kb, r) - prev = s - continue - } - if r := c.Compare(prev, s); r == 1 { - t.Errorf("%s:%d: Compare(%.4X, %.4X) == %d; want -1 or 0", tc.name, i, runes(prev), runes(s), r) - } - if r := c.Compare(s, prev); r == -1 { - t.Errorf("%s:%d: Compare(%.4X, %.4X) == %d; want 1 or 0", tc.name, i, runes(s), runes(prev), r) - } - prev = s - } -} diff --git a/vendor/golang.org/x/text/collate/sort_test.go b/vendor/golang.org/x/text/collate/sort_test.go deleted file mode 100644 index d9e7f31cc9..0000000000 --- a/vendor/golang.org/x/text/collate/sort_test.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2013 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 collate_test - -import ( - "fmt" - "testing" - - "golang.org/x/text/collate" - "golang.org/x/text/language" -) - -func ExampleCollator_Strings() { - c := collate.New(language.Und) - strings := []string{ - "ad", - "ab", - "äb", - "ac", - } - c.SortStrings(strings) - fmt.Println(strings) - // Output: [ab äb ac ad] -} - -type sorter []string - -func (s sorter) Len() int { - return len(s) -} - -func (s sorter) Swap(i, j int) { - s[j], s[i] = s[i], s[j] -} - -func (s sorter) Bytes(i int) []byte { - return []byte(s[i]) -} - -func TestSort(t *testing.T) { - c := collate.New(language.English) - strings := []string{ - "bcd", - "abc", - "ddd", - } - c.Sort(sorter(strings)) - res := fmt.Sprint(strings) - want := "[abc bcd ddd]" - if res != want { - t.Errorf("found %s; want %s", res, want) - } -} diff --git a/vendor/golang.org/x/text/collate/table_test.go b/vendor/golang.org/x/text/collate/table_test.go deleted file mode 100644 index 3a6b12fd62..0000000000 --- a/vendor/golang.org/x/text/collate/table_test.go +++ /dev/null @@ -1,291 +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 collate - -import ( - "testing" - - "golang.org/x/text/collate/build" - "golang.org/x/text/internal/colltab" - "golang.org/x/text/unicode/norm" -) - -type ColElems []Weights - -type input struct { - str string - ces [][]int -} - -type check struct { - in string - n int - out ColElems -} - -type tableTest struct { - in []input - chk []check -} - -func w(ce ...int) Weights { - return W(ce...) -} - -var defaults = w(0) - -func pt(p, t int) []int { - return []int{p, defaults.Secondary, t} -} - -func makeTable(in []input) (*Collator, error) { - b := build.NewBuilder() - for _, r := range in { - if e := b.Add([]rune(r.str), r.ces, nil); e != nil { - panic(e) - } - } - t, err := b.Build() - if err != nil { - return nil, err - } - return NewFromTable(t), nil -} - -// modSeq holds a seqeunce of modifiers in increasing order of CCC long enough -// to cause a segment overflow if not handled correctly. The last rune in this -// list has a CCC of 214. -var modSeq = []rune{ - 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7, 0x05B8, 0x05B9, 0x05BB, - 0x05BC, 0x05BD, 0x05BF, 0x05C1, 0x05C2, 0xFB1E, 0x064B, 0x064C, 0x064D, 0x064E, - 0x064F, 0x0650, 0x0651, 0x0652, 0x0670, 0x0711, 0x0C55, 0x0C56, 0x0E38, 0x0E48, - 0x0EB8, 0x0EC8, 0x0F71, 0x0F72, 0x0F74, 0x0321, 0x1DCE, -} - -var mods []input -var modW = func() ColElems { - ws := ColElems{} - for _, r := range modSeq { - rune := norm.NFC.PropertiesString(string(r)) - ws = append(ws, w(0, int(rune.CCC()))) - mods = append(mods, input{string(r), [][]int{{0, int(rune.CCC())}}}) - } - return ws -}() - -var appendNextTests = []tableTest{ - { // test getWeights - []input{ - {"a", [][]int{{100}}}, - {"b", [][]int{{105}}}, - {"c", [][]int{{110}}}, - {"ß", [][]int{{120}}}, - }, - []check{ - {"a", 1, ColElems{w(100)}}, - {"b", 1, ColElems{w(105)}}, - {"c", 1, ColElems{w(110)}}, - {"d", 1, ColElems{w(0x50064)}}, - {"ab", 1, ColElems{w(100)}}, - {"bc", 1, ColElems{w(105)}}, - {"dd", 1, ColElems{w(0x50064)}}, - {"ß", 2, ColElems{w(120)}}, - }, - }, - { // test expansion - []input{ - {"u", [][]int{{100}}}, - {"U", [][]int{{100}, {0, 25}}}, - {"w", [][]int{{100}, {100}}}, - {"W", [][]int{{100}, {0, 25}, {100}, {0, 25}}}, - }, - []check{ - {"u", 1, ColElems{w(100)}}, - {"U", 1, ColElems{w(100), w(0, 25)}}, - {"w", 1, ColElems{w(100), w(100)}}, - {"W", 1, ColElems{w(100), w(0, 25), w(100), w(0, 25)}}, - }, - }, - { // test decompose - []input{ - {"D", [][]int{pt(104, 8)}}, - {"z", [][]int{pt(130, 8)}}, - {"\u030C", [][]int{{0, 40}}}, // Caron - {"\u01C5", [][]int{pt(104, 9), pt(130, 4), {0, 40, 0x1F}}}, // Dž = D+z+caron - }, - []check{ - {"\u01C5", 2, ColElems{w(pt(104, 9)...), w(pt(130, 4)...), w(0, 40, 0x1F)}}, - }, - }, - { // test basic contraction - []input{ - {"a", [][]int{{100}}}, - {"ab", [][]int{{101}}}, - {"aab", [][]int{{101}, {101}}}, - {"abc", [][]int{{102}}}, - {"b", [][]int{{200}}}, - {"c", [][]int{{300}}}, - {"d", [][]int{{400}}}, - }, - []check{ - {"a", 1, ColElems{w(100)}}, - {"aa", 1, ColElems{w(100)}}, - {"aac", 1, ColElems{w(100)}}, - {"d", 1, ColElems{w(400)}}, - {"ab", 2, ColElems{w(101)}}, - {"abb", 2, ColElems{w(101)}}, - {"aab", 3, ColElems{w(101), w(101)}}, - {"aaba", 3, ColElems{w(101), w(101)}}, - {"abc", 3, ColElems{w(102)}}, - {"abcd", 3, ColElems{w(102)}}, - }, - }, - { // test discontinuous contraction - append(mods, []input{ - // modifiers; secondary weight equals ccc - {"\u0316", [][]int{{0, 220}}}, - {"\u0317", [][]int{{0, 220}, {0, 220}}}, - {"\u302D", [][]int{{0, 222}}}, - {"\u302E", [][]int{{0, 225}}}, // used as starter - {"\u302F", [][]int{{0, 224}}}, // used as starter - {"\u18A9", [][]int{{0, 228}}}, - {"\u0300", [][]int{{0, 230}}}, - {"\u0301", [][]int{{0, 230}}}, - {"\u0315", [][]int{{0, 232}}}, - {"\u031A", [][]int{{0, 232}}}, - {"\u035C", [][]int{{0, 233}}}, - {"\u035F", [][]int{{0, 233}}}, - {"\u035D", [][]int{{0, 234}}}, - {"\u035E", [][]int{{0, 234}}}, - {"\u0345", [][]int{{0, 240}}}, - - // starters - {"a", [][]int{{100}}}, - {"b", [][]int{{200}}}, - {"c", [][]int{{300}}}, - {"\u03B1", [][]int{{900}}}, - {"\x01", [][]int{{0, 0, 0, 0}}}, - - // contractions - {"a\u0300", [][]int{{101}}}, - {"a\u0301", [][]int{{102}}}, - {"a\u035E", [][]int{{110}}}, - {"a\u035Eb\u035E", [][]int{{115}}}, - {"ac\u035Eaca\u035E", [][]int{{116}}}, - {"a\u035Db\u035D", [][]int{{117}}}, - {"a\u0301\u035Db", [][]int{{120}}}, - {"a\u0301\u035F", [][]int{{121}}}, - {"a\u0301\u035Fb", [][]int{{119}}}, - {"\u03B1\u0345", [][]int{{901}, {902}}}, - {"\u302E\u302F", [][]int{{0, 131}, {0, 131}}}, - {"\u302F\u18A9", [][]int{{0, 130}}}, - }...), - []check{ - {"a\x01\u0300", 1, ColElems{w(100)}}, - {"ab", 1, ColElems{w(100)}}, // closing segment - {"a\u0316\u0300b", 5, ColElems{w(101), w(0, 220)}}, // closing segment - {"a\u0316\u0300", 5, ColElems{w(101), w(0, 220)}}, // no closing segment - {"a\u0316\u0300\u035Cb", 5, ColElems{w(101), w(0, 220)}}, // completes before segment end - {"a\u0316\u0300\u035C", 5, ColElems{w(101), w(0, 220)}}, // completes before segment end - - {"a\u0316\u0301b", 5, ColElems{w(102), w(0, 220)}}, // closing segment - {"a\u0316\u0301", 5, ColElems{w(102), w(0, 220)}}, // no closing segment - {"a\u0316\u0301\u035Cb", 5, ColElems{w(102), w(0, 220)}}, // completes before segment end - {"a\u0316\u0301\u035C", 5, ColElems{w(102), w(0, 220)}}, // completes before segment end - - // match blocked by modifier with same ccc - {"a\u0301\u0315\u031A\u035Fb", 3, ColElems{w(102)}}, - - // multiple gaps - {"a\u0301\u035Db", 6, ColElems{w(120)}}, - {"a\u0301\u035F", 5, ColElems{w(121)}}, - {"a\u0301\u035Fb", 6, ColElems{w(119)}}, - {"a\u0316\u0301\u035F", 7, ColElems{w(121), w(0, 220)}}, - {"a\u0301\u0315\u035Fb", 7, ColElems{w(121), w(0, 232)}}, - {"a\u0316\u0301\u0315\u035Db", 5, ColElems{w(102), w(0, 220)}}, - {"a\u0316\u0301\u0315\u035F", 9, ColElems{w(121), w(0, 220), w(0, 232)}}, - {"a\u0316\u0301\u0315\u035Fb", 9, ColElems{w(121), w(0, 220), w(0, 232)}}, - {"a\u0316\u0301\u0315\u035F\u035D", 9, ColElems{w(121), w(0, 220), w(0, 232)}}, - {"a\u0316\u0301\u0315\u035F\u035Db", 9, ColElems{w(121), w(0, 220), w(0, 232)}}, - - // handling of segment overflow - { // just fits within segment - "a" + string(modSeq[:30]) + "\u0301", - 3 + len(string(modSeq[:30])), - append(ColElems{w(102)}, modW[:30]...), - }, - {"a" + string(modSeq[:31]) + "\u0301", 1, ColElems{w(100)}}, // overflow - {"a" + string(modSeq) + "\u0301", 1, ColElems{w(100)}}, - { // just fits within segment with two interstitial runes - "a" + string(modSeq[:28]) + "\u0301\u0315\u035F", - 7 + len(string(modSeq[:28])), - append(append(ColElems{w(121)}, modW[:28]...), w(0, 232)), - }, - { // second half does not fit within segment - "a" + string(modSeq[:29]) + "\u0301\u0315\u035F", - 3 + len(string(modSeq[:29])), - append(ColElems{w(102)}, modW[:29]...), - }, - - // discontinuity can only occur in last normalization segment - {"a\u035Eb\u035E", 6, ColElems{w(115)}}, - {"a\u0316\u035Eb\u035E", 5, ColElems{w(110), w(0, 220)}}, - {"a\u035Db\u035D", 6, ColElems{w(117)}}, - {"a\u0316\u035Db\u035D", 1, ColElems{w(100)}}, - {"a\u035Eb\u0316\u035E", 8, ColElems{w(115), w(0, 220)}}, - {"a\u035Db\u0316\u035D", 8, ColElems{w(117), w(0, 220)}}, - {"ac\u035Eaca\u035E", 9, ColElems{w(116)}}, - {"a\u0316c\u035Eaca\u035E", 1, ColElems{w(100)}}, - {"ac\u035Eac\u0316a\u035E", 1, ColElems{w(100)}}, - - // expanding contraction - {"\u03B1\u0345", 4, ColElems{w(901), w(902)}}, - - // Theoretical possibilities - // contraction within a gap - {"a\u302F\u18A9\u0301", 9, ColElems{w(102), w(0, 130)}}, - // expansion within a gap - {"a\u0317\u0301", 5, ColElems{w(102), w(0, 220), w(0, 220)}}, - // repeating CCC blocks last modifier - {"a\u302E\u302F\u0301", 1, ColElems{w(100)}}, - // The trailing combining characters (with lower CCC) should block the first one. - // TODO: make the following pass. - // {"a\u035E\u0316\u0316", 1, ColElems{w(100)}}, - {"a\u035F\u035Eb", 5, ColElems{w(110), w(0, 233)}}, - // Last combiner should match after normalization. - // TODO: make the following pass. - // {"a\u035D\u0301", 3, ColElems{w(102), w(0, 234)}}, - // The first combiner is blocking the second one as they have the same CCC. - {"a\u035D\u035Eb", 1, ColElems{w(100)}}, - }, - }, -} - -func TestAppendNext(t *testing.T) { - for i, tt := range appendNextTests { - c, err := makeTable(tt.in) - if err != nil { - t.Errorf("%d: error creating table: %v", i, err) - continue - } - for j, chk := range tt.chk { - ws, n := c.t.AppendNext(nil, []byte(chk.in)) - if n != chk.n { - t.Errorf("%d:%d: bytes consumed was %d; want %d", i, j, n, chk.n) - } - out := convertFromWeights(chk.out) - if len(ws) != len(out) { - t.Errorf("%d:%d: len(ws) was %d; want %d (%X vs %X)\n%X", i, j, len(ws), len(out), ws, out, chk.in) - continue - } - for k, w := range ws { - w, _ = colltab.MakeElem(w.Primary(), w.Secondary(), int(w.Tertiary()), 0) - if w != out[k] { - t.Errorf("%d:%d: Weights %d was %X; want %X", i, j, k, w, out[k]) - } - } - } - } -} diff --git a/vendor/golang.org/x/text/encoding/charmap/charmap_test.go b/vendor/golang.org/x/text/encoding/charmap/charmap_test.go deleted file mode 100644 index 03dd76ebd2..0000000000 --- a/vendor/golang.org/x/text/encoding/charmap/charmap_test.go +++ /dev/null @@ -1,258 +0,0 @@ -// Copyright 2015 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 charmap - -import ( - "testing" - - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/internal" - "golang.org/x/text/encoding/internal/enctest" - "golang.org/x/text/transform" -) - -func dec(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Decode", e.NewDecoder(), nil -} - -func encASCIISuperset(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Encode", e.NewEncoder(), internal.ErrASCIIReplacement -} - -func encEBCDIC(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Encode", e.NewEncoder(), internal.RepertoireError(0x3f) -} - -func TestNonRepertoire(t *testing.T) { - testCases := []struct { - init func(e encoding.Encoding) (string, transform.Transformer, error) - e encoding.Encoding - src, want string - }{ - {dec, Windows1252, "\x81", "\ufffd"}, - - {encEBCDIC, CodePage037, "갂", ""}, - - {encEBCDIC, CodePage1047, "갂", ""}, - {encEBCDIC, CodePage1047, "a¤갂", "\x81\x9F"}, - - {encEBCDIC, CodePage1140, "갂", ""}, - {encEBCDIC, CodePage1140, "a€갂", "\x81\x9F"}, - - {encASCIISuperset, Windows1252, "갂", ""}, - {encASCIISuperset, Windows1252, "a갂", "a"}, - {encASCIISuperset, Windows1252, "\u00E9갂", "\xE9"}, - } - for _, tc := range testCases { - dir, tr, wantErr := tc.init(tc.e) - - dst, _, err := transform.String(tr, tc.src) - if err != wantErr { - t.Errorf("%s %v(%q): got %v; want %v", dir, tc.e, tc.src, err, wantErr) - } - if got := string(dst); got != tc.want { - t.Errorf("%s %v(%q):\ngot %q\nwant %q", dir, tc.e, tc.src, got, tc.want) - } - } -} - -func TestBasics(t *testing.T) { - testCases := []struct { - e encoding.Encoding - encoded string - utf8 string - }{{ - e: CodePage037, - encoded: "\xc8\x51\xba\x93\xcf", - utf8: "Hé[lõ", - }, { - e: CodePage437, - encoded: "H\x82ll\x93 \x9d\xa7\xf4\x9c\xbe", - utf8: "Héllô ¥º⌠£╛", - }, { - e: CodePage866, - encoded: "H\xf3\xd3o \x98\xfd\x9f\xdd\xa1", - utf8: "Hє╙o Ш¤Я▌б", - }, { - e: CodePage1047, - encoded: "\xc8\x54\x93\x93\x9f", - utf8: "Hèll¤", - }, { - e: CodePage1140, - encoded: "\xc8\x9f\x93\x93\xcf", - utf8: "H€llõ", - }, { - e: ISO8859_2, - encoded: "Hel\xe5\xf5", - utf8: "Helĺő", - }, { - e: ISO8859_3, - encoded: "He\xbd\xd4", - utf8: "He½Ô", - }, { - e: ISO8859_4, - encoded: "Hel\xb6\xf8", - utf8: "Helļø", - }, { - e: ISO8859_5, - encoded: "H\xd7\xc6o", - utf8: "HзЦo", - }, { - e: ISO8859_6, - encoded: "Hel\xc2\xc9", - utf8: "Helآة", - }, { - e: ISO8859_7, - encoded: "H\xeel\xebo", - utf8: "Hξlλo", - }, { - e: ISO8859_8, - encoded: "Hel\xf5\xed", - utf8: "Helץם", - }, { - e: ISO8859_9, - encoded: "\xdeayet", - utf8: "Şayet", - }, { - e: ISO8859_10, - encoded: "H\xea\xbfo", - utf8: "Hęŋo", - }, { - e: ISO8859_13, - encoded: "H\xe6l\xf9o", - utf8: "Hęlło", - }, { - e: ISO8859_14, - encoded: "He\xfe\xd0o", - utf8: "HeŷŴo", - }, { - e: ISO8859_15, - encoded: "H\xa4ll\xd8", - utf8: "H€llØ", - }, { - e: ISO8859_16, - encoded: "H\xe6ll\xbd", - utf8: "Hællœ", - }, { - e: KOI8R, - encoded: "He\x93\xad\x9c", - utf8: "He⌠╜°", - }, { - e: KOI8U, - encoded: "He\x93\xad\x9c", - utf8: "He⌠ґ°", - }, { - e: Macintosh, - encoded: "He\xdf\xd7", - utf8: "Hefl◊", - }, { - e: MacintoshCyrillic, - encoded: "He\xbe\x94", - utf8: "HeЊФ", - }, { - e: Windows874, - encoded: "He\xb7\xf0", - utf8: "Heท๐", - }, { - e: Windows1250, - encoded: "He\xe5\xe5o", - utf8: "Heĺĺo", - }, { - e: Windows1251, - encoded: "H\xball\xfe", - utf8: "Hєllю", - }, { - e: Windows1252, - encoded: "H\xe9ll\xf4 \xa5\xbA\xae\xa3\xd0", - utf8: "Héllô ¥º®£Ð", - }, { - e: Windows1253, - encoded: "H\xe5ll\xd6", - utf8: "HεllΦ", - }, { - e: Windows1254, - encoded: "\xd0ello", - utf8: "Ğello", - }, { - e: Windows1255, - encoded: "He\xd4o", - utf8: "Heװo", - }, { - e: Windows1256, - encoded: "H\xdbllo", - utf8: "Hغllo", - }, { - e: Windows1257, - encoded: "He\xeflo", - utf8: "Heļlo", - }, { - e: Windows1258, - encoded: "Hell\xf5", - utf8: "Hellơ", - }, { - e: XUserDefined, - encoded: "\x00\x40\x7f\x80\xab\xff", - utf8: "\u0000\u0040\u007f\uf780\uf7ab\uf7ff", - }} - - for _, tc := range testCases { - enctest.TestEncoding(t, tc.e, tc.encoded, tc.utf8, "", "") - } -} - -var windows1255TestCases = []struct { - b byte - ok bool - r rune -}{ - {'\x00', true, '\u0000'}, - {'\x1a', true, '\u001a'}, - {'\x61', true, '\u0061'}, - {'\x7f', true, '\u007f'}, - {'\x80', true, '\u20ac'}, - {'\x95', true, '\u2022'}, - {'\xa0', true, '\u00a0'}, - {'\xc0', true, '\u05b0'}, - {'\xfc', true, '\ufffd'}, - {'\xfd', true, '\u200e'}, - {'\xfe', true, '\u200f'}, - {'\xff', true, '\ufffd'}, - {encoding.ASCIISub, false, '\u0400'}, - {encoding.ASCIISub, false, '\u2603'}, - {encoding.ASCIISub, false, '\U0001f4a9'}, -} - -func TestDecodeByte(t *testing.T) { - for _, tc := range windows1255TestCases { - if !tc.ok { - continue - } - - got := Windows1255.DecodeByte(tc.b) - want := tc.r - if got != want { - t.Errorf("DecodeByte(%#02x): got %#08x, want %#08x", tc.b, got, want) - } - } -} - -func TestEncodeRune(t *testing.T) { - for _, tc := range windows1255TestCases { - // There can be multiple tc.b values that map to tc.r = '\ufffd'. - if tc.r == '\ufffd' { - continue - } - - gotB, gotOK := Windows1255.EncodeRune(tc.r) - wantB, wantOK := tc.b, tc.ok - if gotB != wantB || gotOK != wantOK { - t.Errorf("EncodeRune(%#08x): got (%#02x, %t), want (%#02x, %t)", tc.r, gotB, gotOK, wantB, wantOK) - } - } -} - -func TestFiles(t *testing.T) { enctest.TestFile(t, Windows1252) } - -func BenchmarkEncoding(b *testing.B) { enctest.Benchmark(b, Windows1252) } diff --git a/vendor/golang.org/x/text/encoding/encoding_test.go b/vendor/golang.org/x/text/encoding/encoding_test.go deleted file mode 100644 index 1738147622..0000000000 --- a/vendor/golang.org/x/text/encoding/encoding_test.go +++ /dev/null @@ -1,290 +0,0 @@ -// Copyright 2013 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 encoding_test - -import ( - "io/ioutil" - "strings" - "testing" - - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/charmap" - "golang.org/x/text/transform" -) - -func TestEncodeInvalidUTF8(t *testing.T) { - inputs := []string{ - "hello.", - "wo\ufffdld.", - "ABC\xff\x80\x80", // Invalid UTF-8. - "\x80\x80\x80\x80\x80", - "\x80\x80D\x80\x80", // Valid rune at "D". - "E\xed\xa0\x80\xed\xbf\xbfF", // Two invalid UTF-8 runes (surrogates). - "G", - "H\xe2\x82", // U+20AC in UTF-8 is "\xe2\x82\xac", which we split over two - "\xacI\xe2\x82", // input lines. It maps to 0x80 in the Windows-1252 encoding. - } - // Each invalid source byte becomes '\x1a'. - want := strings.Replace("hello.wo?ld.ABC??????????D??E??????FGH\x80I??", "?", "\x1a", -1) - - transformer := encoding.ReplaceUnsupported(charmap.Windows1252.NewEncoder()) - gotBuf := make([]byte, 0, 1024) - src := make([]byte, 0, 1024) - for i, input := range inputs { - dst := make([]byte, 1024) - src = append(src, input...) - atEOF := i == len(inputs)-1 - nDst, nSrc, err := transformer.Transform(dst, src, atEOF) - gotBuf = append(gotBuf, dst[:nDst]...) - src = src[nSrc:] - if err != nil && err != transform.ErrShortSrc { - t.Fatalf("i=%d: %v", i, err) - } - if atEOF && err != nil { - t.Fatalf("i=%d: atEOF: %v", i, err) - } - } - if got := string(gotBuf); got != want { - t.Fatalf("\ngot %+q\nwant %+q", got, want) - } -} - -func TestReplacement(t *testing.T) { - for _, direction := range []string{"Decode", "Encode"} { - enc, want := (transform.Transformer)(nil), "" - if direction == "Decode" { - enc = encoding.Replacement.NewDecoder() - want = "\ufffd" - } else { - enc = encoding.Replacement.NewEncoder() - want = "AB\x00CD\ufffdYZ" - } - sr := strings.NewReader("AB\x00CD\x80YZ") - g, err := ioutil.ReadAll(transform.NewReader(sr, enc)) - if err != nil { - t.Errorf("%s: ReadAll: %v", direction, err) - continue - } - if got := string(g); got != want { - t.Errorf("%s:\ngot %q\nwant %q", direction, got, want) - continue - } - } -} - -func TestUTF8Validator(t *testing.T) { - testCases := []struct { - desc string - dstSize int - src string - atEOF bool - want string - wantErr error - }{ - { - "empty input", - 100, - "", - false, - "", - nil, - }, - { - "valid 1-byte 1-rune input", - 100, - "a", - false, - "a", - nil, - }, - { - "valid 3-byte 1-rune input", - 100, - "\u1234", - false, - "\u1234", - nil, - }, - { - "valid 5-byte 3-rune input", - 100, - "a\u0100\u0101", - false, - "a\u0100\u0101", - nil, - }, - { - "perfectly sized dst (non-ASCII)", - 5, - "a\u0100\u0101", - false, - "a\u0100\u0101", - nil, - }, - { - "short dst (non-ASCII)", - 4, - "a\u0100\u0101", - false, - "a\u0100", - transform.ErrShortDst, - }, - { - "perfectly sized dst (ASCII)", - 5, - "abcde", - false, - "abcde", - nil, - }, - { - "short dst (ASCII)", - 4, - "abcde", - false, - "abcd", - transform.ErrShortDst, - }, - { - "partial input (!EOF)", - 100, - "a\u0100\xf1", - false, - "a\u0100", - transform.ErrShortSrc, - }, - { - "invalid input (EOF)", - 100, - "a\u0100\xf1", - true, - "a\u0100", - encoding.ErrInvalidUTF8, - }, - { - "invalid input (!EOF)", - 100, - "a\u0100\x80", - false, - "a\u0100", - encoding.ErrInvalidUTF8, - }, - { - "invalid input (above U+10FFFF)", - 100, - "a\u0100\xf7\xbf\xbf\xbf", - false, - "a\u0100", - encoding.ErrInvalidUTF8, - }, - { - "invalid input (surrogate half)", - 100, - "a\u0100\xed\xa0\x80", - false, - "a\u0100", - encoding.ErrInvalidUTF8, - }, - } - for _, tc := range testCases { - dst := make([]byte, tc.dstSize) - nDst, nSrc, err := encoding.UTF8Validator.Transform(dst, []byte(tc.src), tc.atEOF) - if nDst < 0 || len(dst) < nDst { - t.Errorf("%s: nDst=%d out of range", tc.desc, nDst) - continue - } - got := string(dst[:nDst]) - if got != tc.want || nSrc != len(tc.want) || err != tc.wantErr { - t.Errorf("%s:\ngot %+q, %d, %v\nwant %+q, %d, %v", - tc.desc, got, nSrc, err, tc.want, len(tc.want), tc.wantErr) - continue - } - } -} - -func TestErrorHandler(t *testing.T) { - testCases := []struct { - desc string - handler func(*encoding.Encoder) *encoding.Encoder - sizeDst int - src, want string - nSrc int - err error - }{ - { - desc: "one rune replacement", - handler: encoding.ReplaceUnsupported, - sizeDst: 100, - src: "\uAC00", - want: "\x1a", - nSrc: 3, - }, - { - desc: "mid-stream rune replacement", - handler: encoding.ReplaceUnsupported, - sizeDst: 100, - src: "a\uAC00bcd\u00e9", - want: "a\x1abcd\xe9", - nSrc: 9, - }, - { - desc: "at end rune replacement", - handler: encoding.ReplaceUnsupported, - sizeDst: 10, - src: "\u00e9\uAC00", - want: "\xe9\x1a", - nSrc: 5, - }, - { - desc: "short buffer replacement", - handler: encoding.ReplaceUnsupported, - sizeDst: 1, - src: "\u00e9\uAC00", - want: "\xe9", - nSrc: 2, - err: transform.ErrShortDst, - }, - { - desc: "one rune html escape", - handler: encoding.HTMLEscapeUnsupported, - sizeDst: 100, - src: "\uAC00", - want: "&#44032;", - nSrc: 3, - }, - { - desc: "mid-stream html escape", - handler: encoding.HTMLEscapeUnsupported, - sizeDst: 100, - src: "\u00e9\uAC00dcba", - want: "\xe9&#44032;dcba", - nSrc: 9, - }, - { - desc: "short buffer html escape", - handler: encoding.HTMLEscapeUnsupported, - sizeDst: 9, - src: "ab\uAC01", - want: "ab", - nSrc: 2, - err: transform.ErrShortDst, - }, - } - for i, tc := range testCases { - tr := tc.handler(charmap.Windows1250.NewEncoder()) - b := make([]byte, tc.sizeDst) - nDst, nSrc, err := tr.Transform(b, []byte(tc.src), true) - if err != tc.err { - t.Errorf("%d:%s: error was %v; want %v", i, tc.desc, err, tc.err) - } - if got := string(b[:nDst]); got != tc.want { - t.Errorf("%d:%s: result was %q: want %q", i, tc.desc, got, tc.want) - } - if nSrc != tc.nSrc { - t.Errorf("%d:%s: nSrc was %d; want %d", i, tc.desc, nSrc, tc.nSrc) - } - - } -} diff --git a/vendor/golang.org/x/text/encoding/example_test.go b/vendor/golang.org/x/text/encoding/example_test.go deleted file mode 100644 index 4f923530f0..0000000000 --- a/vendor/golang.org/x/text/encoding/example_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2013 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 encoding_test - -import ( - "fmt" - "io" - "os" - "strings" - - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/charmap" - "golang.org/x/text/encoding/unicode" - "golang.org/x/text/transform" -) - -func ExampleDecodeWindows1252() { - sr := strings.NewReader("Gar\xe7on !") - tr := charmap.Windows1252.NewDecoder().Reader(sr) - io.Copy(os.Stdout, tr) - // Output: Garçon ! -} - -func ExampleUTF8Validator() { - for i := 0; i < 2; i++ { - var transformer transform.Transformer - transformer = unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM).NewEncoder() - if i == 1 { - transformer = transform.Chain(encoding.UTF8Validator, transformer) - } - dst := make([]byte, 256) - src := []byte("abc\xffxyz") // src is invalid UTF-8. - nDst, nSrc, err := transformer.Transform(dst, src, true) - fmt.Printf("i=%d: produced %q, consumed %q, error %v\n", - i, dst[:nDst], src[:nSrc], err) - } - // Output: - // i=0: produced "\x00a\x00b\x00c\xff\xfd\x00x\x00y\x00z", consumed "abc\xffxyz", error <nil> - // i=1: produced "\x00a\x00b\x00c", consumed "abc", error encoding: invalid UTF-8 -} diff --git a/vendor/golang.org/x/text/encoding/htmlindex/htmlindex_test.go b/vendor/golang.org/x/text/encoding/htmlindex/htmlindex_test.go deleted file mode 100644 index 3fdab0f49d..0000000000 --- a/vendor/golang.org/x/text/encoding/htmlindex/htmlindex_test.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2015 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 htmlindex - -import ( - "testing" - - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/charmap" - "golang.org/x/text/encoding/internal/identifier" - "golang.org/x/text/encoding/unicode" - "golang.org/x/text/language" -) - -func TestGet(t *testing.T) { - for i, tc := range []struct { - name string - canonical string - err error - }{ - {"utf-8", "utf-8", nil}, - {" utf-8 ", "utf-8", nil}, - {" l5 ", "windows-1254", nil}, - {"latin5 ", "windows-1254", nil}, - {"latin 5", "", errInvalidName}, - {"latin-5", "", errInvalidName}, - } { - enc, err := Get(tc.name) - if err != tc.err { - t.Errorf("%d: error was %v; want %v", i, err, tc.err) - } - if err != nil { - continue - } - if got, err := Name(enc); got != tc.canonical { - t.Errorf("%d: Name(Get(%q)) = %q; want %q (%v)", i, tc.name, got, tc.canonical, err) - } - } -} - -func TestTables(t *testing.T) { - for name, index := range nameMap { - got, err := Get(name) - if err != nil { - t.Errorf("%s:err: expected non-nil error", name) - } - if want := encodings[index]; got != want { - t.Errorf("%s:encoding: got %v; want %v", name, got, want) - } - mib, _ := got.(identifier.Interface).ID() - if mibMap[mib] != index { - t.Errorf("%s:mibMab: got %d; want %d", name, mibMap[mib], index) - } - } -} - -func TestName(t *testing.T) { - for i, tc := range []struct { - desc string - enc encoding.Encoding - name string - err error - }{{ - "defined encoding", - charmap.ISO8859_2, - "iso-8859-2", - nil, - }, { - "defined Unicode encoding", - unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM), - "utf-16be", - nil, - }, { - "undefined Unicode encoding in HTML standard", - unicode.UTF16(unicode.BigEndian, unicode.UseBOM), - "", - errUnsupported, - }, { - "undefined other encoding in HTML standard", - charmap.CodePage437, - "", - errUnsupported, - }, { - "unknown encoding", - encoding.Nop, - "", - errUnknown, - }} { - name, err := Name(tc.enc) - if name != tc.name || err != tc.err { - t.Errorf("%d:%s: got %q, %v; want %q, %v", i, tc.desc, name, err, tc.name, tc.err) - } - } -} - -func TestLanguageDefault(t *testing.T) { - for _, tc := range []struct{ tag, want string }{ - {"und", "windows-1252"}, // The default value. - {"ar", "windows-1256"}, - {"ba", "windows-1251"}, - {"be", "windows-1251"}, - {"bg", "windows-1251"}, - {"cs", "windows-1250"}, - {"el", "iso-8859-7"}, - {"et", "windows-1257"}, - {"fa", "windows-1256"}, - {"he", "windows-1255"}, - {"hr", "windows-1250"}, - {"hu", "iso-8859-2"}, - {"ja", "shift_jis"}, - {"kk", "windows-1251"}, - {"ko", "euc-kr"}, - {"ku", "windows-1254"}, - {"ky", "windows-1251"}, - {"lt", "windows-1257"}, - {"lv", "windows-1257"}, - {"mk", "windows-1251"}, - {"pl", "iso-8859-2"}, - {"ru", "windows-1251"}, - {"sah", "windows-1251"}, - {"sk", "windows-1250"}, - {"sl", "iso-8859-2"}, - {"sr", "windows-1251"}, - {"tg", "windows-1251"}, - {"th", "windows-874"}, - {"tr", "windows-1254"}, - {"tt", "windows-1251"}, - {"uk", "windows-1251"}, - {"vi", "windows-1258"}, - {"zh-hans", "gb18030"}, - {"zh-hant", "big5"}, - // Variants and close approximates of the above. - {"ar_EG", "windows-1256"}, - {"bs", "windows-1250"}, // Bosnian Latin maps to Croatian. - // Use default fallback in case of miss. - {"nl", "windows-1252"}, - } { - if got := LanguageDefault(language.MustParse(tc.tag)); got != tc.want { - t.Errorf("LanguageDefault(%s) = %s; want %s", tc.tag, got, tc.want) - } - } -} diff --git a/vendor/golang.org/x/text/encoding/japanese/all_test.go b/vendor/golang.org/x/text/encoding/japanese/all_test.go deleted file mode 100644 index 9cffe10dc1..0000000000 --- a/vendor/golang.org/x/text/encoding/japanese/all_test.go +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright 2015 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 japanese - -import ( - "fmt" - "strings" - "testing" - - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/internal" - "golang.org/x/text/encoding/internal/enctest" - "golang.org/x/text/transform" -) - -func dec(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Decode", e.NewDecoder(), nil -} -func enc(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Encode", e.NewEncoder(), internal.ErrASCIIReplacement -} - -func TestNonRepertoire(t *testing.T) { - // Pick n to cause the destination buffer in transform.String to overflow. - const n = 100 - long := strings.Repeat(".", n) - testCases := []struct { - init func(e encoding.Encoding) (string, transform.Transformer, error) - e encoding.Encoding - src, want string - }{ - {enc, EUCJP, "갂", ""}, - {enc, EUCJP, "a갂", "a"}, - {enc, EUCJP, "丌갂", "\x8f\xb0\xa4"}, - - {enc, ISO2022JP, "갂", ""}, - {enc, ISO2022JP, "a갂", "a"}, - {enc, ISO2022JP, "朗갂", "\x1b$BzF\x1b(B"}, // switch back to ASCII mode at end - - {enc, ShiftJIS, "갂", ""}, - {enc, ShiftJIS, "a갂", "a"}, - {enc, ShiftJIS, "\u2190갂", "\x81\xa9"}, - - // Continue correctly after errors - {dec, EUCJP, "\x8e\xa0", "\ufffd\ufffd"}, - {dec, EUCJP, "\x8e\xe0", "\ufffd"}, - {dec, EUCJP, "\x8e\xff", "\ufffd\ufffd"}, - {dec, EUCJP, "\x8ea", "\ufffda"}, - {dec, EUCJP, "\x8f\xa0", "\ufffd\ufffd"}, - {dec, EUCJP, "\x8f\xa1\xa0", "\ufffd\ufffd"}, - {dec, EUCJP, "\x8f\xa1a", "\ufffda"}, - {dec, EUCJP, "\x8f\xa1a", "\ufffda"}, - {dec, EUCJP, "\x8f\xa1a", "\ufffda"}, - {dec, EUCJP, "\x8f\xa2\xa2", "\ufffd"}, - {dec, EUCJP, "\xfe", "\ufffd"}, - {dec, EUCJP, "\xfe\xfc", "\ufffd"}, - {dec, EUCJP, "\xfe\xff", "\ufffd\ufffd"}, - // Correct handling of end of source - {dec, EUCJP, strings.Repeat("\x8e", n), strings.Repeat("\ufffd", n)}, - {dec, EUCJP, strings.Repeat("\x8f", n), strings.Repeat("\ufffd", n)}, - {dec, EUCJP, strings.Repeat("\x8f\xa0", n), strings.Repeat("\ufffd", 2*n)}, - {dec, EUCJP, "a" + strings.Repeat("\x8f\xa1", n), "a" + strings.Repeat("\ufffd", n)}, - {dec, EUCJP, "a" + strings.Repeat("\x8f\xa1\xff", n), "a" + strings.Repeat("\ufffd", 2*n)}, - - // Continue correctly after errors - {dec, ShiftJIS, "\x80", "\u0080"}, // It's what the spec says. - {dec, ShiftJIS, "\x81", "\ufffd"}, - {dec, ShiftJIS, "\x81\x7f", "\ufffd\u007f"}, - {dec, ShiftJIS, "\xe0", "\ufffd"}, - {dec, ShiftJIS, "\xe0\x39", "\ufffd\u0039"}, - {dec, ShiftJIS, "\xe0\x9f", "燹"}, - {dec, ShiftJIS, "\xe0\xfd", "\ufffd"}, - {dec, ShiftJIS, "\xef\xfc", "\ufffd"}, - {dec, ShiftJIS, "\xfc\xfc", "\ufffd"}, - {dec, ShiftJIS, "\xfc\xfd", "\ufffd"}, - {dec, ShiftJIS, "\xfdaa", "\ufffdaa"}, - - {dec, ShiftJIS, strings.Repeat("\x81\x81", n), strings.Repeat("=", n)}, - {dec, ShiftJIS, strings.Repeat("\xe0\xfd", n), strings.Repeat("\ufffd", n)}, - {dec, ShiftJIS, "a" + strings.Repeat("\xe0\xfd", n), "a" + strings.Repeat("\ufffd", n)}, - - {dec, ISO2022JP, "\x1b$", "\ufffd$"}, - {dec, ISO2022JP, "\x1b(", "\ufffd("}, - {dec, ISO2022JP, "\x1b@", "\ufffd@"}, - {dec, ISO2022JP, "\x1bZ", "\ufffdZ"}, - // incomplete escapes - {dec, ISO2022JP, "\x1b$", "\ufffd$"}, - {dec, ISO2022JP, "\x1b$J.", "\ufffd$J."}, // illegal - {dec, ISO2022JP, "\x1b$B.", "\ufffd"}, // JIS208 - {dec, ISO2022JP, "\x1b$(", "\ufffd$("}, // JIS212 - {dec, ISO2022JP, "\x1b$(..", "\ufffd$(.."}, // JIS212 - {dec, ISO2022JP, "\x1b$(" + long, "\ufffd$(" + long}, // JIS212 - {dec, ISO2022JP, "\x1b$(D.", "\ufffd"}, // JIS212 - {dec, ISO2022JP, "\x1b$(D..", "\ufffd"}, // JIS212 - {dec, ISO2022JP, "\x1b$(D...", "\ufffd\ufffd"}, // JIS212 - {dec, ISO2022JP, "\x1b(B.", "."}, // ascii - {dec, ISO2022JP, "\x1b(B..", ".."}, // ascii - {dec, ISO2022JP, "\x1b(J.", "."}, // roman - {dec, ISO2022JP, "\x1b(J..", ".."}, // roman - {dec, ISO2022JP, "\x1b(I\x20", "\ufffd"}, // katakana - {dec, ISO2022JP, "\x1b(I\x20\x20", "\ufffd\ufffd"}, // katakana - // recover to same state - {dec, ISO2022JP, "\x1b(B\x1b.", "\ufffd."}, - {dec, ISO2022JP, "\x1b(I\x1b.", "\ufffdョ"}, - {dec, ISO2022JP, "\x1b(I\x1b$.", "\ufffd、ョ"}, - {dec, ISO2022JP, "\x1b(I\x1b(.", "\ufffdィョ"}, - {dec, ISO2022JP, "\x1b$B\x7e\x7e", "\ufffd"}, - {dec, ISO2022JP, "\x1b$@\x0a.", "\x0a."}, - {dec, ISO2022JP, "\x1b$B\x0a.", "\x0a."}, - {dec, ISO2022JP, "\x1b$(D\x0a.", "\x0a."}, - {dec, ISO2022JP, "\x1b$(D\x7e\x7e", "\ufffd"}, - {dec, ISO2022JP, "\x80", "\ufffd"}, - - // TODO: according to https://encoding.spec.whatwg.org/#iso-2022-jp, - // these should all be correct. - // {dec, ISO2022JP, "\x1b(B\x0E", "\ufffd"}, - // {dec, ISO2022JP, "\x1b(B\x0F", "\ufffd"}, - {dec, ISO2022JP, "\x1b(B\x5C", "\u005C"}, - {dec, ISO2022JP, "\x1b(B\x7E", "\u007E"}, - // {dec, ISO2022JP, "\x1b(J\x0E", "\ufffd"}, - // {dec, ISO2022JP, "\x1b(J\x0F", "\ufffd"}, - // {dec, ISO2022JP, "\x1b(J\x5C", "\u00A5"}, - // {dec, ISO2022JP, "\x1b(J\x7E", "\u203E"}, - } - for _, tc := range testCases { - dir, tr, wantErr := tc.init(tc.e) - t.Run(fmt.Sprintf("%s/%v/%q", dir, tc.e, tc.src), func(t *testing.T) { - dst := make([]byte, 100000) - src := []byte(tc.src) - for i := 0; i <= len(tc.src); i++ { - nDst, nSrc, err := tr.Transform(dst, src[:i], false) - if err != nil && err != transform.ErrShortSrc && err != wantErr { - t.Fatalf("error on first call to Transform: %v", err) - } - n, _, err := tr.Transform(dst[nDst:], src[nSrc:], true) - nDst += n - if err != wantErr { - t.Fatalf("(%q|%q): got %v; want %v", tc.src[:i], tc.src[i:], err, wantErr) - } - if got := string(dst[:nDst]); got != tc.want { - t.Errorf("(%q|%q):\ngot %q\nwant %q", tc.src[:i], tc.src[i:], got, tc.want) - } - } - }) - } -} - -func TestCorrect(t *testing.T) { - testCases := []struct { - init func(e encoding.Encoding) (string, transform.Transformer, error) - e encoding.Encoding - src, want string - }{ - {dec, ShiftJIS, "\x9f\xfc", "滌"}, - {dec, ShiftJIS, "\xfb\xfc", "髙"}, - {dec, ShiftJIS, "\xfa\xb1", "﨑"}, - {enc, ShiftJIS, "滌", "\x9f\xfc"}, - {enc, ShiftJIS, "﨑", "\xed\x95"}, - } - for _, tc := range testCases { - dir, tr, _ := tc.init(tc.e) - - dst, _, err := transform.String(tr, tc.src) - if err != nil { - t.Errorf("%s %v(%q): got %v; want %v", dir, tc.e, tc.src, err, nil) - } - if got := string(dst); got != tc.want { - t.Errorf("%s %v(%q):\ngot %q\nwant %q", dir, tc.e, tc.src, got, tc.want) - } - } -} - -func TestBasics(t *testing.T) { - // The encoded forms can be verified by the iconv program: - // $ echo 月日は百代 | iconv -f UTF-8 -t SHIFT-JIS | xxd - testCases := []struct { - e encoding.Encoding - encPrefix string - encSuffix string - encoded string - utf8 string - }{{ - // "A。カ゚ 0208: etc 0212: etc" is a nonsense string that contains ASCII, half-width - // kana, JIS X 0208 (including two near the kink in the Shift JIS second byte - // encoding) and JIS X 0212 encodable codepoints. - // - // "月日は百代の過客にして、行かふ年も又旅人也。" is from the 17th century poem - // "Oku no Hosomichi" and contains both hiragana and kanji. - e: EUCJP, - encoded: "A\x8e\xa1\x8e\xb6\x8e\xdf " + - "0208: \xa1\xa1\xa1\xa2\xa1\xdf\xa1\xe0\xa1\xfd\xa1\xfe\xa2\xa1\xa2\xa2\xf4\xa6 " + - "0212: \x8f\xa2\xaf\x8f\xed\xe3", - utf8: "A。カ゚ " + - "0208: \u3000\u3001\u00d7\u00f7\u25ce\u25c7\u25c6\u25a1\u7199 " + - "0212: \u02d8\u9fa5", - }, { - e: EUCJP, - encoded: "\xb7\xee\xc6\xfc\xa4\xcf\xc9\xb4\xc2\xe5\xa4\xce\xb2\xe1\xb5\xd2" + - "\xa4\xcb\xa4\xb7\xa4\xc6\xa1\xa2\xb9\xd4\xa4\xab\xa4\xd5\xc7\xaf" + - "\xa4\xe2\xcb\xf4\xce\xb9\xbf\xcd\xcc\xe9\xa1\xa3", - utf8: "月日は百代の過客にして、行かふ年も又旅人也。", - }, { - e: ISO2022JP, - encSuffix: "\x1b\x28\x42", - encoded: "\x1b\x28\x49\x21\x36\x5f\x1b\x28\x42 " + - "0208: \x1b\x24\x42\x21\x21\x21\x22\x21\x5f\x21\x60\x21\x7d\x21\x7e\x22\x21\x22\x22\x74\x26", - utf8: "。カ゚ " + - "0208: \u3000\u3001\u00d7\u00f7\u25ce\u25c7\u25c6\u25a1\u7199", - }, { - e: ISO2022JP, - encPrefix: "\x1b\x24\x42", - encSuffix: "\x1b\x28\x42", - encoded: "\x37\x6e\x46\x7c\x24\x4f\x49\x34\x42\x65\x24\x4e\x32\x61\x35\x52" + - "\x24\x4b\x24\x37\x24\x46\x21\x22\x39\x54\x24\x2b\x24\x55\x47\x2f" + - "\x24\x62\x4b\x74\x4e\x39\x3f\x4d\x4c\x69\x21\x23", - utf8: "月日は百代の過客にして、行かふ年も又旅人也。", - }, { - e: ShiftJIS, - encoded: "A\xa1\xb6\xdf " + - "0208: \x81\x40\x81\x41\x81\x7e\x81\x80\x81\x9d\x81\x9e\x81\x9f\x81\xa0\xea\xa4", - utf8: "A。カ゚ " + - "0208: \u3000\u3001\u00d7\u00f7\u25ce\u25c7\u25c6\u25a1\u7199", - }, { - e: ShiftJIS, - encoded: "\x8c\x8e\x93\xfa\x82\xcd\x95\x53\x91\xe3\x82\xcc\x89\xdf\x8b\x71" + - "\x82\xc9\x82\xb5\x82\xc4\x81\x41\x8d\x73\x82\xa9\x82\xd3\x94\x4e" + - "\x82\xe0\x96\x94\x97\xb7\x90\x6c\x96\xe7\x81\x42", - utf8: "月日は百代の過客にして、行かふ年も又旅人也。", - }} - - for _, tc := range testCases { - enctest.TestEncoding(t, tc.e, tc.encoded, tc.utf8, tc.encPrefix, tc.encSuffix) - } -} - -func TestFiles(t *testing.T) { - enctest.TestFile(t, EUCJP) - enctest.TestFile(t, ISO2022JP) - enctest.TestFile(t, ShiftJIS) -} - -func BenchmarkEncoding(b *testing.B) { - enctest.Benchmark(b, EUCJP) - enctest.Benchmark(b, ISO2022JP) - enctest.Benchmark(b, ShiftJIS) -} diff --git a/vendor/golang.org/x/text/encoding/korean/all_test.go b/vendor/golang.org/x/text/encoding/korean/all_test.go deleted file mode 100644 index 8225ce62a8..0000000000 --- a/vendor/golang.org/x/text/encoding/korean/all_test.go +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright 2015 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 korean - -import ( - "strings" - "testing" - - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/internal" - "golang.org/x/text/encoding/internal/enctest" - "golang.org/x/text/transform" -) - -func dec(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Decode", e.NewDecoder(), nil -} -func enc(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Encode", e.NewEncoder(), internal.ErrASCIIReplacement -} - -func TestNonRepertoire(t *testing.T) { - // Pick n large enough to cause an overflow in the destination buffer of - // transform.String. - const n = 10000 - testCases := []struct { - init func(e encoding.Encoding) (string, transform.Transformer, error) - e encoding.Encoding - src, want string - }{ - {dec, EUCKR, "\xfe\xfe", "\ufffd"}, - // {dec, EUCKR, "א", "\ufffd"}, // TODO: why is this different? - - {enc, EUCKR, "א", ""}, - {enc, EUCKR, "aא", "a"}, - {enc, EUCKR, "\uac00א", "\xb0\xa1"}, - // TODO: should we also handle Jamo? - - {dec, EUCKR, "\x80", "\ufffd"}, - {dec, EUCKR, "\xff", "\ufffd"}, - {dec, EUCKR, "\x81", "\ufffd"}, - {dec, EUCKR, "\xb0\x40", "\ufffd@"}, - {dec, EUCKR, "\xb0\xff", "\ufffd"}, - {dec, EUCKR, "\xd0\x20", "\ufffd "}, - {dec, EUCKR, "\xd0\xff", "\ufffd"}, - - {dec, EUCKR, strings.Repeat("\x81", n), strings.Repeat("걖", n/2)}, - } - for _, tc := range testCases { - dir, tr, wantErr := tc.init(tc.e) - - dst, _, err := transform.String(tr, tc.src) - if err != wantErr { - t.Errorf("%s %v(%q): got %v; want %v", dir, tc.e, tc.src, err, wantErr) - } - if got := string(dst); got != tc.want { - t.Errorf("%s %v(%q):\ngot %q\nwant %q", dir, tc.e, tc.src, got, tc.want) - } - } -} - -func TestBasics(t *testing.T) { - // The encoded forms can be verified by the iconv program: - // $ echo 月日は百代 | iconv -f UTF-8 -t SHIFT-JIS | xxd - testCases := []struct { - e encoding.Encoding - encoded string - utf8 string - }{{ - // Korean tests. - // - // "A\uac02\uac35\uac56\ud401B\ud408\ud620\ud624C\u4f3d\u8a70D" is a - // nonsense string that contains ASCII, Hangul and CJK ideographs. - // - // "세계야, 안녕" translates as "Hello, world". - e: EUCKR, - encoded: "A\x81\x41\x81\x61\x81\x81\xc6\xfeB\xc7\xa1\xc7\xfe\xc8\xa1C\xca\xa1\xfd\xfeD", - utf8: "A\uac02\uac35\uac56\ud401B\ud408\ud620\ud624C\u4f3d\u8a70D", - }, { - e: EUCKR, - encoded: "\xbc\xbc\xb0\xe8\xbe\xdf\x2c\x20\xbe\xc8\xb3\xe7", - utf8: "세계야, 안녕", - }} - - for _, tc := range testCases { - enctest.TestEncoding(t, tc.e, tc.encoded, tc.utf8, "", "") - } -} - -func TestFiles(t *testing.T) { enctest.TestFile(t, EUCKR) } - -func BenchmarkEncoding(b *testing.B) { enctest.Benchmark(b, EUCKR) } diff --git a/vendor/golang.org/x/text/encoding/simplifiedchinese/all_test.go b/vendor/golang.org/x/text/encoding/simplifiedchinese/all_test.go deleted file mode 100644 index b369da21ab..0000000000 --- a/vendor/golang.org/x/text/encoding/simplifiedchinese/all_test.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2015 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 simplifiedchinese - -import ( - "strings" - "testing" - - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/internal" - "golang.org/x/text/encoding/internal/enctest" - "golang.org/x/text/transform" -) - -func dec(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Decode", e.NewDecoder(), nil -} -func enc(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Encode", e.NewEncoder(), internal.ErrASCIIReplacement -} - -func TestNonRepertoire(t *testing.T) { - // Pick n large enough to overflow the destination buffer of transform.String. - const n = 10000 - testCases := []struct { - init func(e encoding.Encoding) (string, transform.Transformer, error) - e encoding.Encoding - src, want string - }{ - {dec, GBK, "a\xfe\xfeb", "a\ufffdb"}, - {dec, HZGB2312, "~{z~", "\ufffd"}, - - {enc, GBK, "갂", ""}, - {enc, GBK, "a갂", "a"}, - {enc, GBK, "\u4e02갂", "\x81@"}, - - {enc, HZGB2312, "갂", ""}, - {enc, HZGB2312, "a갂", "a"}, - {enc, HZGB2312, "\u6cf5갂", "~{1C~}"}, - - {dec, GB18030, "\x80", "€"}, - {dec, GB18030, "\x81", "\ufffd"}, - {dec, GB18030, "\x81\x20", "\ufffd "}, - {dec, GB18030, "\xfe\xfe", "\ufffd"}, - {dec, GB18030, "\xfe\xff", "\ufffd\ufffd"}, - {dec, GB18030, "\xfe\x30", "\ufffd0"}, - {dec, GB18030, "\xfe\x30\x30 ", "\ufffd00 "}, - {dec, GB18030, "\xfe\x30\xff ", "\ufffd0\ufffd "}, - {dec, GB18030, "\xfe\x30\x81\x21", "\ufffd0\ufffd!"}, - - {dec, GB18030, strings.Repeat("\xfe\x30", n), strings.Repeat("\ufffd0", n)}, - - {dec, HZGB2312, "~/", "\ufffd"}, - {dec, HZGB2312, "~{a\x80", "\ufffd"}, - {dec, HZGB2312, "~{a\x80", "\ufffd"}, - {dec, HZGB2312, "~{" + strings.Repeat("z~", n), strings.Repeat("\ufffd", n)}, - {dec, HZGB2312, "~{" + strings.Repeat("\xfe\x30", n), strings.Repeat("\ufffd", n*2)}, - } - for _, tc := range testCases { - dir, tr, wantErr := tc.init(tc.e) - - dst, _, err := transform.String(tr, tc.src) - if err != wantErr { - t.Errorf("%s %v(%q): got %v; want %v", dir, tc.e, tc.src, err, wantErr) - } - if got := string(dst); got != tc.want { - t.Errorf("%s %v(%q):\ngot %q\nwant %q", dir, tc.e, tc.src, got, tc.want) - } - } -} - -func TestBasics(t *testing.T) { - // The encoded forms can be verified by the iconv program: - // $ echo 月日は百代 | iconv -f UTF-8 -t SHIFT-JIS | xxd - testCases := []struct { - e encoding.Encoding - encPrefix string - encoded string - utf8 string - }{{ - // "\u0081\u00de\u00df\u00e0\u00e1\u00e2\u00e3\uffff\U00010000" is a - // nonsense string that contains GB18030 encodable codepoints of which - // only U+00E0 and U+00E1 are GBK encodable. - // - // "A\u3000\u554a\u4e02\u4e90\u72dc\u7349\u02ca\u2588Z€" is a nonsense - // string that contains ASCII and GBK encodable codepoints from Levels - // 1-5 as well as the Euro sign. - // - // "A\u43f0\u4c32\U00027267\u3000\U0002910d\u79d4Z€" is a nonsense string - // that contains ASCII and Big5 encodable codepoints from the Basic - // Multilingual Plane and the Supplementary Ideographic Plane as well as - // the Euro sign. - // - // "花间一壶酒,独酌无相亲。" (simplified) and - // "花間一壺酒,獨酌無相親。" (traditional) - // are from the 8th century poem "Yuè Xià Dú Zhuó". - e: GB18030, - encoded: "\x81\x30\x81\x31\x81\x30\x89\x37\x81\x30\x89\x38\xa8\xa4\xa8\xa2" + - "\x81\x30\x89\x39\x81\x30\x8a\x30\x84\x31\xa4\x39\x90\x30\x81\x30", - utf8: "\u0081\u00de\u00df\u00e0\u00e1\u00e2\u00e3\uffff\U00010000", - }, { - e: GB18030, - encoded: "\xbb\xa8\xbc\xe4\xd2\xbb\xba\xf8\xbe\xc6\xa3\xac\xb6\xc0\xd7\xc3" + - "\xce\xde\xcf\xe0\xc7\xd7\xa1\xa3", - utf8: "花间一壶酒,独酌无相亲。", - }, { - e: GBK, - encoded: "A\xa1\xa1\xb0\xa1\x81\x40\x81\x80\xaa\x40\xaa\x80\xa8\x40\xa8\x80Z\x80", - utf8: "A\u3000\u554a\u4e02\u4e90\u72dc\u7349\u02ca\u2588Z€", - }, { - e: GBK, - encoded: "\xbb\xa8\xbc\xe4\xd2\xbb\xba\xf8\xbe\xc6\xa3\xac\xb6\xc0\xd7\xc3" + - "\xce\xde\xcf\xe0\xc7\xd7\xa1\xa3", - utf8: "花间一壶酒,独酌无相亲。", - }, { - e: HZGB2312, - encoded: "A~{\x21\x21~~\x30\x21~}Z~~", - utf8: "A\u3000~\u554aZ~", - }, { - e: HZGB2312, - encPrefix: "~{", - encoded: ";(<dR;:x>F#,6@WCN^O`GW!#", - utf8: "花间一壶酒,独酌无相亲。", - }} - - for _, tc := range testCases { - enctest.TestEncoding(t, tc.e, tc.encoded, tc.utf8, tc.encPrefix, "") - } -} - -func TestFiles(t *testing.T) { - enctest.TestFile(t, GB18030) - enctest.TestFile(t, GBK) - enctest.TestFile(t, HZGB2312) -} - -func BenchmarkEncoding(b *testing.B) { - enctest.Benchmark(b, GB18030) - enctest.Benchmark(b, GBK) - enctest.Benchmark(b, HZGB2312) -} diff --git a/vendor/golang.org/x/text/encoding/traditionalchinese/all_test.go b/vendor/golang.org/x/text/encoding/traditionalchinese/all_test.go deleted file mode 100644 index 3825c7672d..0000000000 --- a/vendor/golang.org/x/text/encoding/traditionalchinese/all_test.go +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright 2015 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 traditionalchinese - -import ( - "fmt" - "io/ioutil" - "strings" - "testing" - - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/internal" - "golang.org/x/text/encoding/internal/enctest" - "golang.org/x/text/transform" -) - -func dec(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Decode", e.NewDecoder(), nil -} -func enc(e encoding.Encoding) (dir string, t transform.Transformer, err error) { - return "Encode", e.NewEncoder(), internal.ErrASCIIReplacement -} - -func TestNonRepertoire(t *testing.T) { - testCases := []struct { - init func(e encoding.Encoding) (string, transform.Transformer, error) - e encoding.Encoding - src, want string - }{ - {dec, Big5, "\x80", "\ufffd"}, - {dec, Big5, "\x81", "\ufffd"}, - {dec, Big5, "\x81\x30", "\ufffd\x30"}, - {dec, Big5, "\x81\x40", "\ufffd"}, - {dec, Big5, "\x81\xa0", "\ufffd"}, - {dec, Big5, "\xff", "\ufffd"}, - - {enc, Big5, "갂", ""}, - {enc, Big5, "a갂", "a"}, - {enc, Big5, "\u43f0갂", "\x87@"}, - } - for _, tc := range testCases { - dir, tr, wantErr := tc.init(tc.e) - t.Run(fmt.Sprintf("%s/%v/%q", dir, tc.e, tc.src), func(t *testing.T) { - dst := make([]byte, 100) - src := []byte(tc.src) - for i := 0; i <= len(tc.src); i++ { - nDst, nSrc, err := tr.Transform(dst, src[:i], false) - if err != nil && err != transform.ErrShortSrc && err != wantErr { - t.Fatalf("error on first call to Transform: %v", err) - } - n, _, err := tr.Transform(dst[nDst:], src[nSrc:], true) - nDst += n - if err != wantErr { - t.Fatalf("(%q|%q): got %v; want %v", tc.src[:i], tc.src[i:], err, wantErr) - } - if got := string(dst[:nDst]); got != tc.want { - t.Errorf("(%q|%q):\ngot %q\nwant %q", tc.src[:i], tc.src[i:], got, tc.want) - } - } - }) - } -} - -func TestBasics(t *testing.T) { - // The encoded forms can be verified by the iconv program: - // $ echo 月日は百代 | iconv -f UTF-8 -t SHIFT-JIS | xxd - testCases := []struct { - e encoding.Encoding - encPrefix string - encSuffix string - encoded string - utf8 string - }{{ - e: Big5, - encoded: "A\x87\x40\x87\x41\x87\x45\xa1\x40\xfe\xfd\xfe\xfeZ\xa3\xe1", - utf8: "A\u43f0\u4c32\U00027267\u3000\U0002910d\u79d4Z€", - }, { - e: Big5, - encoded: "\xaa\xe1\xb6\xa1\xa4\x40\xb3\xfd\xb0\x73\xa1\x41\xbf\x57\xb0\x75" + - "\xb5\x4c\xac\xdb\xbf\xcb\xa1\x43", - utf8: "花間一壺酒,獨酌無相親。", - }} - - for _, tc := range testCases { - enctest.TestEncoding(t, tc.e, tc.encoded, tc.utf8, "", "") - } -} - -func TestFiles(t *testing.T) { enctest.TestFile(t, Big5) } - -func BenchmarkEncoding(b *testing.B) { enctest.Benchmark(b, Big5) } - -// TestBig5CircumflexAndMacron tests the special cases listed in -// http://encoding.spec.whatwg.org/#big5 -// Note that these special cases aren't preserved by round-tripping through -// decoding and encoding (since -// http://encoding.spec.whatwg.org/index-big5.txt does not have an entry for -// U+0304 or U+030C), so we can't test this in TestBasics. -func TestBig5CircumflexAndMacron(t *testing.T) { - src := "\x88\x5f\x88\x60\x88\x61\x88\x62\x88\x63\x88\x64\x88\x65\x88\x66 " + - "\x88\xa2\x88\xa3\x88\xa4\x88\xa5\x88\xa6" - want := "ÓǑÒ\u00ca\u0304Ế\u00ca\u030cỀÊ " + - "ü\u00ea\u0304ế\u00ea\u030cề" - dst, err := ioutil.ReadAll(transform.NewReader( - strings.NewReader(src), Big5.NewDecoder())) - if err != nil { - t.Fatal(err) - } - if got := string(dst); got != want { - t.Fatalf("\ngot %q\nwant %q", got, want) - } -} diff --git a/vendor/golang.org/x/text/encoding/unicode/unicode_test.go b/vendor/golang.org/x/text/encoding/unicode/unicode_test.go deleted file mode 100644 index 51b4712d80..0000000000 --- a/vendor/golang.org/x/text/encoding/unicode/unicode_test.go +++ /dev/null @@ -1,499 +0,0 @@ -// Copyright 2015 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 unicode - -import ( - "testing" - - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/charmap" - "golang.org/x/text/encoding/internal/enctest" - "golang.org/x/text/transform" -) - -func TestBasics(t *testing.T) { - testCases := []struct { - e encoding.Encoding - encPrefix string - encSuffix string - encoded string - utf8 string - }{{ - e: utf16BEIB, - encoded: "\x00\x57\x00\xe4\xd8\x35\xdd\x65", - utf8: "\x57\u00e4\U0001d565", - }, { - e: utf16BEEB, - encPrefix: "\xfe\xff", - encoded: "\x00\x57\x00\xe4\xd8\x35\xdd\x65", - utf8: "\x57\u00e4\U0001d565", - }, { - e: utf16LEIB, - encoded: "\x57\x00\xe4\x00\x35\xd8\x65\xdd", - utf8: "\x57\u00e4\U0001d565", - }, { - e: utf16LEEB, - encPrefix: "\xff\xfe", - encoded: "\x57\x00\xe4\x00\x35\xd8\x65\xdd", - utf8: "\x57\u00e4\U0001d565", - }} - - for _, tc := range testCases { - enctest.TestEncoding(t, tc.e, tc.encoded, tc.utf8, tc.encPrefix, tc.encSuffix) - } -} - -func TestFiles(t *testing.T) { - enctest.TestFile(t, UTF8) - enctest.TestFile(t, utf16LEIB) -} - -func BenchmarkEncoding(b *testing.B) { - enctest.Benchmark(b, UTF8) - enctest.Benchmark(b, utf16LEIB) -} - -var ( - utf16LEIB = UTF16(LittleEndian, IgnoreBOM) // UTF-16LE (atypical interpretation) - utf16LEUB = UTF16(LittleEndian, UseBOM) // UTF-16, LE - utf16LEEB = UTF16(LittleEndian, ExpectBOM) // UTF-16, LE, Expect - utf16BEIB = UTF16(BigEndian, IgnoreBOM) // UTF-16BE (atypical interpretation) - utf16BEUB = UTF16(BigEndian, UseBOM) // UTF-16 default - utf16BEEB = UTF16(BigEndian, ExpectBOM) // UTF-16 Expect -) - -func TestUTF16(t *testing.T) { - testCases := []struct { - desc string - src string - notEOF bool // the inverse of atEOF - sizeDst int - want string - nSrc int - err error - t transform.Transformer - }{{ - desc: "utf-16 IgnoreBOM dec: empty string", - t: utf16BEIB.NewDecoder(), - }, { - desc: "utf-16 UseBOM dec: empty string", - t: utf16BEUB.NewDecoder(), - }, { - desc: "utf-16 ExpectBOM dec: empty string", - err: ErrMissingBOM, - t: utf16BEEB.NewDecoder(), - }, { - desc: "utf-16 dec: BOM determines encoding BE (RFC 2781:3.3)", - src: "\xFE\xFF\xD8\x08\xDF\x45\x00\x3D\x00\x52\x00\x61", - sizeDst: 100, - want: "\U00012345=Ra", - nSrc: 12, - t: utf16BEUB.NewDecoder(), - }, { - desc: "utf-16 dec: BOM determines encoding LE (RFC 2781:3.3)", - src: "\xFF\xFE\x08\xD8\x45\xDF\x3D\x00\x52\x00\x61\x00", - sizeDst: 100, - want: "\U00012345=Ra", - nSrc: 12, - t: utf16LEUB.NewDecoder(), - }, { - desc: "utf-16 dec: BOM determines encoding LE, change default (RFC 2781:3.3)", - src: "\xFF\xFE\x08\xD8\x45\xDF\x3D\x00\x52\x00\x61\x00", - sizeDst: 100, - want: "\U00012345=Ra", - nSrc: 12, - t: utf16BEUB.NewDecoder(), - }, { - desc: "utf-16 dec: Fail on missing BOM when required", - src: "\x08\xD8\x45\xDF\x3D\x00\xFF\xFE\xFE\xFF\x00\x52\x00\x61", - sizeDst: 100, - want: "", - nSrc: 0, - err: ErrMissingBOM, - t: utf16BEEB.NewDecoder(), - }, { - desc: "utf-16 dec: SHOULD interpret text as big-endian when BOM not present (RFC 2781:4.3)", - src: "\xD8\x08\xDF\x45\x00\x3D\x00\x52\x00\x61", - sizeDst: 100, - want: "\U00012345=Ra", - nSrc: 10, - t: utf16BEUB.NewDecoder(), - }, { - // This is an error according to RFC 2781. But errors in RFC 2781 are - // open to interpretations, so I guess this is fine. - desc: "utf-16le dec: incorrect BOM is an error (RFC 2781:4.1)", - src: "\xFE\xFF\x08\xD8\x45\xDF\x3D\x00\x52\x00\x61\x00", - sizeDst: 100, - want: "\uFFFE\U00012345=Ra", - nSrc: 12, - t: utf16LEIB.NewDecoder(), - }, { - desc: "utf-16 enc: SHOULD write BOM (RFC 2781:3.3)", - src: "\U00012345=Ra", - sizeDst: 100, - want: "\xFF\xFE\x08\xD8\x45\xDF\x3D\x00\x52\x00\x61\x00", - nSrc: 7, - t: utf16LEUB.NewEncoder(), - }, { - desc: "utf-16 enc: SHOULD write BOM (RFC 2781:3.3)", - src: "\U00012345=Ra", - sizeDst: 100, - want: "\xFE\xFF\xD8\x08\xDF\x45\x00\x3D\x00\x52\x00\x61", - nSrc: 7, - t: utf16BEUB.NewEncoder(), - }, { - desc: "utf-16le enc: MUST NOT write BOM (RFC 2781:3.3)", - src: "\U00012345=Ra", - sizeDst: 100, - want: "\x08\xD8\x45\xDF\x3D\x00\x52\x00\x61\x00", - nSrc: 7, - t: utf16LEIB.NewEncoder(), - }, { - desc: "utf-16be dec: incorrect UTF-16: odd bytes", - src: "\x00", - sizeDst: 100, - want: "\uFFFD", - nSrc: 1, - t: utf16BEIB.NewDecoder(), - }, { - desc: "utf-16be dec: unpaired surrogate, odd bytes", - src: "\xD8\x45\x00", - sizeDst: 100, - want: "\uFFFD\uFFFD", - nSrc: 3, - t: utf16BEIB.NewDecoder(), - }, { - desc: "utf-16be dec: unpaired low surrogate + valid text", - src: "\xD8\x45\x00a", - sizeDst: 100, - want: "\uFFFDa", - nSrc: 4, - t: utf16BEIB.NewDecoder(), - }, { - desc: "utf-16be dec: unpaired low surrogate + valid text + single byte", - src: "\xD8\x45\x00ab", - sizeDst: 100, - want: "\uFFFDa\uFFFD", - nSrc: 5, - t: utf16BEIB.NewDecoder(), - }, { - desc: "utf-16le dec: unpaired high surrogate", - src: "\x00\x00\x00\xDC\x12\xD8", - sizeDst: 100, - want: "\x00\uFFFD\uFFFD", - nSrc: 6, - t: utf16LEIB.NewDecoder(), - }, { - desc: "utf-16be dec: two unpaired low surrogates", - src: "\xD8\x45\xD8\x12", - sizeDst: 100, - want: "\uFFFD\uFFFD", - nSrc: 4, - t: utf16BEIB.NewDecoder(), - }, { - desc: "utf-16be dec: short dst", - src: "\x00a", - sizeDst: 0, - want: "", - nSrc: 0, - t: utf16BEIB.NewDecoder(), - err: transform.ErrShortDst, - }, { - desc: "utf-16be dec: short dst surrogate", - src: "\xD8\xF5\xDC\x12", - sizeDst: 3, - want: "", - nSrc: 0, - t: utf16BEIB.NewDecoder(), - err: transform.ErrShortDst, - }, { - desc: "utf-16be dec: short dst trailing byte", - src: "\x00", - sizeDst: 2, - want: "", - nSrc: 0, - t: utf16BEIB.NewDecoder(), - err: transform.ErrShortDst, - }, { - desc: "utf-16be dec: short src", - src: "\x00", - notEOF: true, - sizeDst: 3, - want: "", - nSrc: 0, - t: utf16BEIB.NewDecoder(), - err: transform.ErrShortSrc, - }, { - desc: "utf-16 enc", - src: "\U00012345=Ra", - sizeDst: 100, - want: "\xFE\xFF\xD8\x08\xDF\x45\x00\x3D\x00\x52\x00\x61", - nSrc: 7, - t: utf16BEUB.NewEncoder(), - }, { - desc: "utf-16 enc: short dst normal", - src: "\U00012345=Ra", - sizeDst: 9, - want: "\xD8\x08\xDF\x45\x00\x3D\x00\x52", - nSrc: 6, - t: utf16BEIB.NewEncoder(), - err: transform.ErrShortDst, - }, { - desc: "utf-16 enc: short dst surrogate", - src: "\U00012345=Ra", - sizeDst: 3, - want: "", - nSrc: 0, - t: utf16BEIB.NewEncoder(), - err: transform.ErrShortDst, - }, { - desc: "utf-16 enc: short src", - src: "\U00012345=Ra\xC2", - notEOF: true, - sizeDst: 100, - want: "\xD8\x08\xDF\x45\x00\x3D\x00\x52\x00\x61", - nSrc: 7, - t: utf16BEIB.NewEncoder(), - err: transform.ErrShortSrc, - }, { - desc: "utf-16be dec: don't change byte order mid-stream", - src: "\xFE\xFF\xD8\x08\xDF\x45\x00\x3D\xFF\xFE\x00\x52\x00\x61", - sizeDst: 100, - want: "\U00012345=\ufffeRa", - nSrc: 14, - t: utf16BEUB.NewDecoder(), - }, { - desc: "utf-16le dec: don't change byte order mid-stream", - src: "\xFF\xFE\x08\xD8\x45\xDF\x3D\x00\xFF\xFE\xFE\xFF\x52\x00\x61\x00", - sizeDst: 100, - want: "\U00012345=\ufeff\ufffeRa", - nSrc: 16, - t: utf16LEUB.NewDecoder(), - }} - for i, tc := range testCases { - b := make([]byte, tc.sizeDst) - nDst, nSrc, err := tc.t.Transform(b, []byte(tc.src), !tc.notEOF) - if err != tc.err { - t.Errorf("%d:%s: error was %v; want %v", i, tc.desc, err, tc.err) - } - if got := string(b[:nDst]); got != tc.want { - t.Errorf("%d:%s: result was %q: want %q", i, tc.desc, got, tc.want) - } - if nSrc != tc.nSrc { - t.Errorf("%d:%s: nSrc was %d; want %d", i, tc.desc, nSrc, tc.nSrc) - } - } -} - -func TestUTF8Decoder(t *testing.T) { - testCases := []struct { - desc string - src string - notEOF bool // the inverse of atEOF - sizeDst int - want string - nSrc int - err error - }{{ - desc: "empty string, empty dest buffer", - }, { - desc: "empty string", - sizeDst: 8, - }, { - desc: "empty string, streaming", - notEOF: true, - sizeDst: 8, - }, { - desc: "ascii", - src: "abcde", - sizeDst: 8, - want: "abcde", - nSrc: 5, - }, { - desc: "ascii and error", - src: "ab\x80de", - sizeDst: 7, - want: "ab\ufffdde", - nSrc: 5, - }, { - desc: "valid two-byte sequence", - src: "a\u0300bc", - sizeDst: 7, - want: "a\u0300bc", - nSrc: 5, - }, { - desc: "valid three-byte sequence", - src: "a\u0300中", - sizeDst: 7, - want: "a\u0300中", - nSrc: 6, - }, { - desc: "valid four-byte sequence", - src: "a中\U00016F50", - sizeDst: 8, - want: "a中\U00016F50", - nSrc: 8, - }, { - desc: "short source buffer", - src: "abc\xf0\x90", - notEOF: true, - sizeDst: 10, - want: "abc", - nSrc: 3, - err: transform.ErrShortSrc, - }, { - // We don't check for the maximal subpart of an ill-formed subsequence - // at the end of an open segment. - desc: "complete invalid that looks like short at end", - src: "abc\xf0\x80", - notEOF: true, - sizeDst: 10, - want: "abc", // instead of "abc\ufffd\ufffd", - nSrc: 3, - err: transform.ErrShortSrc, - }, { - desc: "incomplete sequence at end", - src: "a\x80bc\xf0\x90", - sizeDst: 9, - want: "a\ufffdbc\ufffd", - nSrc: 6, - }, { - desc: "invalid second byte", - src: "abc\xf0dddd", - sizeDst: 10, - want: "abc\ufffddddd", - nSrc: 8, - }, { - desc: "invalid second byte at end", - src: "abc\xf0d", - sizeDst: 10, - want: "abc\ufffdd", - nSrc: 5, - }, { - desc: "invalid third byte", - src: "a\u0300bc\xf0\x90dddd", - sizeDst: 12, - want: "a\u0300bc\ufffddddd", - nSrc: 11, - }, { - desc: "invalid third byte at end", - src: "a\u0300bc\xf0\x90d", - sizeDst: 12, - want: "a\u0300bc\ufffdd", - nSrc: 8, - }, { - desc: "invalid fourth byte, tight buffer", - src: "a\u0300bc\xf0\x90\x80d", - sizeDst: 9, - want: "a\u0300bc\ufffdd", - nSrc: 9, - }, { - desc: "invalid fourth byte at end", - src: "a\u0300bc\xf0\x90\x80", - sizeDst: 8, - want: "a\u0300bc\ufffd", - nSrc: 8, - }, { - desc: "invalid fourth byte and short four byte sequence", - src: "a\u0300bc\xf0\x90\x80\xf0\x90\x80", - notEOF: true, - sizeDst: 20, - want: "a\u0300bc\ufffd", - nSrc: 8, - err: transform.ErrShortSrc, - }, { - desc: "valid four-byte sequence overflowing short buffer", - src: "a\u0300bc\xf0\x90\x80\x80", - notEOF: true, - sizeDst: 8, - want: "a\u0300bc", - nSrc: 5, - err: transform.ErrShortDst, - }, { - desc: "invalid fourth byte at end short, but short dst", - src: "a\u0300bc\xf0\x90\x80\xf0\x90\x80", - notEOF: true, - sizeDst: 8, - // More bytes would fit in the buffer, but this seems to require a more - // complicated and slower algorithm. - want: "a\u0300bc", // instead of "a\u0300bc" - nSrc: 5, - err: transform.ErrShortDst, - }, { - desc: "short dst for error", - src: "abc\x80", - notEOF: true, - sizeDst: 5, - want: "abc", - nSrc: 3, - err: transform.ErrShortDst, - }, { - desc: "adjusting short dst buffer", - src: "abc\x80ef", - notEOF: true, - sizeDst: 6, - want: "abc\ufffd", - nSrc: 4, - err: transform.ErrShortDst, - }} - tr := UTF8.NewDecoder() - for i, tc := range testCases { - b := make([]byte, tc.sizeDst) - nDst, nSrc, err := tr.Transform(b, []byte(tc.src), !tc.notEOF) - if err != tc.err { - t.Errorf("%d:%s: error was %v; want %v", i, tc.desc, err, tc.err) - } - if got := string(b[:nDst]); got != tc.want { - t.Errorf("%d:%s: result was %q: want %q", i, tc.desc, got, tc.want) - } - if nSrc != tc.nSrc { - t.Errorf("%d:%s: nSrc was %d; want %d", i, tc.desc, nSrc, tc.nSrc) - } - } -} - -func TestBOMOverride(t *testing.T) { - dec := BOMOverride(charmap.CodePage437.NewDecoder()) - dst := make([]byte, 100) - for i, tc := range []struct { - src string - atEOF bool - dst string - nSrc int - err error - }{ - 0: {"H\x82ll\x93", true, "Héllô", 5, nil}, - 1: {"\uFEFFHéllö", true, "Héllö", 10, nil}, - 2: {"\xFE\xFF\x00H\x00e\x00l\x00l\x00o", true, "Hello", 12, nil}, - 3: {"\xFF\xFEH\x00e\x00l\x00l\x00o\x00", true, "Hello", 12, nil}, - 4: {"\uFEFF", true, "", 3, nil}, - 5: {"\xFE\xFF", true, "", 2, nil}, - 6: {"\xFF\xFE", true, "", 2, nil}, - 7: {"\xEF\xBB", true, "\u2229\u2557", 2, nil}, - 8: {"\xEF", true, "\u2229", 1, nil}, - 9: {"", true, "", 0, nil}, - 10: {"\xFE", true, "\u25a0", 1, nil}, - 11: {"\xFF", true, "\u00a0", 1, nil}, - 12: {"\xEF\xBB", false, "", 0, transform.ErrShortSrc}, - 13: {"\xEF", false, "", 0, transform.ErrShortSrc}, - 14: {"", false, "", 0, transform.ErrShortSrc}, - 15: {"\xFE", false, "", 0, transform.ErrShortSrc}, - 16: {"\xFF", false, "", 0, transform.ErrShortSrc}, - 17: {"\xFF\xFE", false, "", 0, transform.ErrShortSrc}, - } { - dec.Reset() - nDst, nSrc, err := dec.Transform(dst, []byte(tc.src), tc.atEOF) - got := string(dst[:nDst]) - if nSrc != tc.nSrc { - t.Errorf("%d: nSrc: got %d; want %d", i, nSrc, tc.nSrc) - } - if got != tc.dst { - t.Errorf("%d: got %+q; want %+q", i, got, tc.dst) - } - if err != tc.err { - t.Errorf("%d: error: got %v; want %v", i, err, tc.err) - } - } -} diff --git a/vendor/golang.org/x/text/gen.go b/vendor/golang.org/x/text/gen.go index 4257a18399..757fefb74c 100644 --- a/vendor/golang.org/x/text/gen.go +++ b/vendor/golang.org/x/text/gen.go @@ -117,14 +117,15 @@ pkg unicode, var <new script or property> *RangeTable width = generate("./width", unicode) bidi = generate("./unicode/bidi", unicode, norm, rangetable) mib = generate("./encoding/internal/identifier", unicode) + number = generate("./internal/number", unicode, cldr, language, internal) _ = generate("./encoding/htmlindex", unicode, language, mib) _ = generate("./encoding/ianaindex", unicode, language, mib) _ = generate("./secure/precis", unicode, norm, rangetable, cases, width, bidi) - _ = generate("./currency", unicode, cldr, language, internal) - _ = generate("./internal/number", unicode, cldr, language, internal) - _ = generate("./feature/plural", unicode, cldr, language, internal) + _ = generate("./internal/cldrtree", language) + _ = generate("./currency", unicode, cldr, language, internal, number) + _ = generate("./feature/plural", unicode, cldr, language, internal, number) _ = generate("./internal/export/idna", unicode, bidi, norm) - _ = generate("./language/display", unicode, cldr, language, internal) + _ = generate("./language/display", unicode, cldr, language, internal, number) _ = generate("./collate", unicode, norm, cldr, language, rangetable) _ = generate("./search", unicode, norm, cldr, language, rangetable) ) diff --git a/vendor/golang.org/x/text/internal/colltab/collate_test.go b/vendor/golang.org/x/text/internal/colltab/collate_test.go deleted file mode 100644 index 580c85c22d..0000000000 --- a/vendor/golang.org/x/text/internal/colltab/collate_test.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2014 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 colltab_test - -// This file contains tests which need to import package collate, which causes -// an import cycle when done within package colltab itself. - -import ( - "bytes" - "testing" - "unicode" - - "golang.org/x/text/collate" - "golang.org/x/text/language" - "golang.org/x/text/unicode/rangetable" -) - -// assigned is used to only test runes that are inside the scope of the Unicode -// version used to generation the collation table. -var assigned = rangetable.Assigned(collate.UnicodeVersion) - -func TestNonDigits(t *testing.T) { - c := collate.New(language.English, collate.Loose, collate.Numeric) - - // Verify that all non-digit numbers sort outside of the number range. - for r, hi := rune(unicode.N.R16[0].Lo), rune(unicode.N.R32[0].Hi); r <= hi; r++ { - if unicode.In(r, unicode.Nd) || !unicode.In(r, assigned) { - continue - } - if a := string(r); c.CompareString(a, "0") != -1 && c.CompareString(a, "999999") != 1 { - t.Errorf("%+q non-digit number is collated as digit", a) - } - } -} - -func TestNumericCompare(t *testing.T) { - c := collate.New(language.English, collate.Loose, collate.Numeric) - - // Iterate over all digits. - for _, r16 := range unicode.Nd.R16 { - testDigitCompare(t, c, rune(r16.Lo), rune(r16.Hi)) - } - for _, r32 := range unicode.Nd.R32 { - testDigitCompare(t, c, rune(r32.Lo), rune(r32.Hi)) - } -} - -func testDigitCompare(t *testing.T, c *collate.Collator, zero, nine rune) { - if !unicode.In(zero, assigned) { - return - } - n := int(nine - zero + 1) - if n%10 != 0 { - t.Fatalf("len([%+q, %+q]) = %d; want a multiple of 10", zero, nine, n) - } - for _, tt := range []struct { - prefix string - b [11]string - }{ - { - prefix: "", - b: [11]string{ - "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", - }, - }, - { - prefix: "1", - b: [11]string{ - "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", - }, - }, - { - prefix: "0", - b: [11]string{ - "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", - }, - }, - { - prefix: "00", - b: [11]string{ - "000", "001", "002", "003", "004", "005", "006", "007", "008", "009", "010", - }, - }, - { - prefix: "9", - b: [11]string{ - "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", - }, - }, - } { - for k := 0; k <= n; k++ { - i := k % 10 - a := tt.prefix + string(zero+rune(i)) - for j, b := range tt.b { - want := 0 - switch { - case i < j: - want = -1 - case i > j: - want = 1 - } - got := c.CompareString(a, b) - if got != want { - t.Errorf("Compare(%+q, %+q) = %d; want %d", a, b, got, want) - return - } - } - } - } -} - -func BenchmarkNumericWeighter(b *testing.B) { - c := collate.New(language.English, collate.Numeric) - input := bytes.Repeat([]byte("Testing, testing 123..."), 100) - b.SetBytes(int64(2 * len(input))) - for i := 0; i < b.N; i++ { - c.Compare(input, input) - } -} diff --git a/vendor/golang.org/x/text/internal/colltab/collelem_test.go b/vendor/golang.org/x/text/internal/colltab/collelem_test.go deleted file mode 100644 index f131ecc32d..0000000000 --- a/vendor/golang.org/x/text/internal/colltab/collelem_test.go +++ /dev/null @@ -1,183 +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 colltab - -import ( - "fmt" - "testing" - "unicode" -) - -func (e Elem) String() string { - q := "" - if v := e.Quaternary(); v == MaxQuaternary { - q = "max" - } else { - q = fmt.Sprint(v) - } - return fmt.Sprintf("[%d, %d, %d, %s]", - e.Primary(), - e.Secondary(), - e.Tertiary(), - q) -} - -type ceTest struct { - f func(inout []int) (Elem, ceType) - arg []int -} - -func makeCE(weights []int) Elem { - ce, _ := MakeElem(weights[0], weights[1], weights[2], uint8(weights[3])) - return ce -} - -var defaultValues = []int{0, defaultSecondary, defaultTertiary, 0} - -func e(w ...int) Elem { - return makeCE(append(w, defaultValues[len(w):]...)) -} - -func makeContractIndex(index, n, offset int) Elem { - const ( - contractID = 0xC0000000 - maxNBits = 4 - maxTrieIndexBits = 12 - maxContractOffsetBits = 13 - ) - ce := Elem(contractID) - ce += Elem(offset << (maxNBits + maxTrieIndexBits)) - ce += Elem(index << maxNBits) - ce += Elem(n) - return ce -} - -func makeExpandIndex(index int) Elem { - const expandID = 0xE0000000 - return expandID + Elem(index) -} - -func makeDecompose(t1, t2 int) Elem { - const decompID = 0xF0000000 - return Elem(t2<<8+t1) + decompID -} - -func normalCE(inout []int) (ce Elem, t ceType) { - ce = makeCE(inout) - inout[0] = ce.Primary() - inout[1] = ce.Secondary() - inout[2] = int(ce.Tertiary()) - inout[3] = int(ce.CCC()) - return ce, ceNormal -} - -func expandCE(inout []int) (ce Elem, t ceType) { - ce = makeExpandIndex(inout[0]) - inout[0] = splitExpandIndex(ce) - return ce, ceExpansionIndex -} - -func contractCE(inout []int) (ce Elem, t ceType) { - ce = makeContractIndex(inout[0], inout[1], inout[2]) - i, n, o := splitContractIndex(ce) - inout[0], inout[1], inout[2] = i, n, o - return ce, ceContractionIndex -} - -func decompCE(inout []int) (ce Elem, t ceType) { - ce = makeDecompose(inout[0], inout[1]) - t1, t2 := splitDecompose(ce) - inout[0], inout[1] = int(t1), int(t2) - return ce, ceDecompose -} - -var ceTests = []ceTest{ - {normalCE, []int{0, 0, 0, 0}}, - {normalCE, []int{0, 30, 3, 0}}, - {normalCE, []int{0, 30, 3, 0xFF}}, - {normalCE, []int{100, defaultSecondary, defaultTertiary, 0}}, - {normalCE, []int{100, defaultSecondary, defaultTertiary, 0xFF}}, - {normalCE, []int{100, defaultSecondary, 3, 0}}, - {normalCE, []int{0x123, defaultSecondary, 8, 0xFF}}, - - {contractCE, []int{0, 0, 0}}, - {contractCE, []int{1, 1, 1}}, - {contractCE, []int{1, (1 << maxNBits) - 1, 1}}, - {contractCE, []int{(1 << maxTrieIndexBits) - 1, 1, 1}}, - {contractCE, []int{1, 1, (1 << maxContractOffsetBits) - 1}}, - - {expandCE, []int{0}}, - {expandCE, []int{5}}, - {expandCE, []int{(1 << maxExpandIndexBits) - 1}}, - - {decompCE, []int{0, 0}}, - {decompCE, []int{1, 1}}, - {decompCE, []int{0x1F, 0x1F}}, -} - -func TestColElem(t *testing.T) { - for i, tt := range ceTests { - inout := make([]int, len(tt.arg)) - copy(inout, tt.arg) - ce, typ := tt.f(inout) - if ce.ctype() != typ { - t.Errorf("%d: type is %d; want %d (ColElem: %X)", i, ce.ctype(), typ, ce) - } - for j, a := range tt.arg { - if inout[j] != a { - t.Errorf("%d: argument %d is %X; want %X (ColElem: %X)", i, j, inout[j], a, ce) - } - } - } -} - -type implicitTest struct { - r rune - p int -} - -var implicitTests = []implicitTest{ - {0x33FF, 0x533FF}, - {0x3400, 0x23400}, - {0x4DC0, 0x54DC0}, - {0x4DFF, 0x54DFF}, - {0x4E00, 0x14E00}, - {0x9FCB, 0x19FCB}, - {0xA000, 0x5A000}, - {0xF8FF, 0x5F8FF}, - {0xF900, 0x1F900}, - {0xFA23, 0x1FA23}, - {0xFAD9, 0x1FAD9}, - {0xFB00, 0x5FB00}, - {0x20000, 0x40000}, - {0x2B81C, 0x4B81C}, - {unicode.MaxRune, 0x15FFFF}, // maximum primary value -} - -func TestImplicit(t *testing.T) { - for _, tt := range implicitTests { - if p := implicitPrimary(tt.r); p != tt.p { - t.Errorf("%U: was %X; want %X", tt.r, p, tt.p) - } - } -} - -func TestUpdateTertiary(t *testing.T) { - tests := []struct { - in, out Elem - t uint8 - }{ - {0x4000FE20, 0x0000FE8A, 0x0A}, - {0x4000FE21, 0x0000FEAA, 0x0A}, - {0x0000FE8B, 0x0000FE83, 0x03}, - {0x82FF0188, 0x9BFF0188, 0x1B}, - {0xAFF0CC02, 0xAFF0CC1B, 0x1B}, - } - for i, tt := range tests { - if out := tt.in.updateTertiary(tt.t); out != tt.out { - t.Errorf("%d: was %X; want %X", i, out, tt.out) - } - } -} diff --git a/vendor/golang.org/x/text/internal/colltab/colltab_test.go b/vendor/golang.org/x/text/internal/colltab/colltab_test.go deleted file mode 100644 index c403ac3461..0000000000 --- a/vendor/golang.org/x/text/internal/colltab/colltab_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package colltab - -import ( - "testing" - - "golang.org/x/text/language" -) - -func TestMatchLang(t *testing.T) { - tags := []language.Tag{ - 0: language.Und, - 1: language.MustParse("bs"), - 2: language.German, - 3: language.English, - 4: language.AmericanEnglish, - 5: language.MustParse("en-US-u-va-posix"), - 6: language.Portuguese, - 7: language.Serbian, - 8: language.MustParse("sr-Latn"), - 9: language.Chinese, - 10: language.MustParse("zh-u-co-stroke"), - 11: language.MustParse("zh-Hant-u-co-pinyin"), - 12: language.TraditionalChinese, - } - for i, tc := range []struct { - x int - t language.Tag - }{ - {0, language.Und}, - {0, language.Persian}, // Default to first element when no match. - {3, language.English}, - {4, language.AmericanEnglish}, - {5, language.MustParse("en-US-u-va-posix")}, // Ext. variant match. - {4, language.MustParse("en-US-u-va-noposix")}, // Ext. variant mismatch. - {3, language.MustParse("en-UK-u-va-noposix")}, // Ext. variant mismatch. - {7, language.Serbian}, - {0, language.Croatian}, // Don't match to close language! - {0, language.MustParse("gsw")}, // Don't match to close language! - {1, language.MustParse("bs-Cyrl")}, // Odd, but correct. - {1, language.MustParse("bs-Latn")}, // Estimated script drops. - {8, language.MustParse("sr-Latn")}, - {9, language.Chinese}, - {9, language.SimplifiedChinese}, - {12, language.TraditionalChinese}, - {11, language.MustParse("zh-Hant-u-co-pinyin")}, - // TODO: should this be 12? Either inherited value (10) or default is - // fine in this case, though. Other locales are not affected. - {10, language.MustParse("zh-Hant-u-co-stroke")}, - // There is no "phonebk" sorting order for zh-Hant, so use default. - {12, language.MustParse("zh-Hant-u-co-phonebk")}, - {10, language.MustParse("zh-u-co-stroke")}, - {12, language.MustParse("und-TW")}, // Infer script and language. - {12, language.MustParse("und-HK")}, // Infer script and language. - {6, language.MustParse("und-BR")}, // Infer script and language. - {6, language.MustParse("und-PT")}, // Infer script and language. - {2, language.MustParse("und-Latn-DE")}, // Infer language. - {0, language.MustParse("und-Jpan-BR")}, // Infers "ja", so no match. - {0, language.MustParse("zu")}, // No match past index. - } { - if x := MatchLang(tc.t, tags); x != tc.x { - t.Errorf("%d: MatchLang(%q, tags) = %d; want %d", i, tc.t, x, tc.x) - } - } -} diff --git a/vendor/golang.org/x/text/internal/colltab/contract_test.go b/vendor/golang.org/x/text/internal/colltab/contract_test.go deleted file mode 100644 index ce2871dd4f..0000000000 --- a/vendor/golang.org/x/text/internal/colltab/contract_test.go +++ /dev/null @@ -1,131 +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 colltab - -import ( - "testing" -) - -type lookupStrings struct { - str string - offset int - n int // bytes consumed from input -} - -type LookupTest struct { - lookup []lookupStrings - n int - tries ContractTrieSet -} - -var lookupTests = []LookupTest{{ - []lookupStrings{ - {"abc", 1, 3}, - {"a", 0, 0}, - {"b", 0, 0}, - {"c", 0, 0}, - {"d", 0, 0}, - }, - 1, - ContractTrieSet{ - {'a', 0, 1, 0xFF}, - {'b', 0, 1, 0xFF}, - {'c', 'c', 0, 1}, - }, -}, { - []lookupStrings{ - {"abc", 1, 3}, - {"abd", 2, 3}, - {"abe", 3, 3}, - {"a", 0, 0}, - {"ab", 0, 0}, - {"d", 0, 0}, - {"f", 0, 0}, - }, - 1, - ContractTrieSet{ - {'a', 0, 1, 0xFF}, - {'b', 0, 1, 0xFF}, - {'c', 'e', 0, 1}, - }, -}, { - []lookupStrings{ - {"abc", 1, 3}, - {"ab", 2, 2}, - {"a", 3, 1}, - {"abcd", 1, 3}, - {"abe", 2, 2}, - }, - 1, - ContractTrieSet{ - {'a', 0, 1, 3}, - {'b', 0, 1, 2}, - {'c', 'c', 0, 1}, - }, -}, { - []lookupStrings{ - {"abc", 1, 3}, - {"abd", 2, 3}, - {"ab", 3, 2}, - {"ac", 4, 2}, - {"a", 5, 1}, - {"b", 6, 1}, - {"ba", 6, 1}, - }, - 2, - ContractTrieSet{ - {'b', 'b', 0, 6}, - {'a', 0, 2, 5}, - {'c', 'c', 0, 4}, - {'b', 0, 1, 3}, - {'c', 'd', 0, 1}, - }, -}, { - []lookupStrings{ - {"bcde", 2, 4}, - {"bc", 7, 2}, - {"ab", 6, 2}, - {"bcd", 5, 3}, - {"abcd", 1, 4}, - {"abc", 4, 3}, - {"bcdf", 3, 4}, - }, - 2, - ContractTrieSet{ - {'b', 3, 1, 0xFF}, - {'a', 0, 1, 0xFF}, - {'b', 0, 1, 6}, - {'c', 0, 1, 4}, - {'d', 'd', 0, 1}, - {'c', 0, 1, 7}, - {'d', 0, 1, 5}, - {'e', 'f', 0, 2}, - }, -}} - -func lookup(c *ContractTrieSet, nnode int, s []uint8) (i, n int) { - scan := c.scanner(0, nnode, s) - scan.scan(0) - return scan.result() -} - -func TestLookupContraction(t *testing.T) { - for i, tt := range lookupTests { - cts := ContractTrieSet(tt.tries) - for j, lu := range tt.lookup { - str := lu.str - for _, s := range []string{str, str + "X"} { - const msg = `%d:%d: %s of "%s" %v; want %v` - offset, n := lookup(&cts, tt.n, []byte(s)) - if offset != lu.offset { - t.Errorf(msg, i, j, "offset", s, offset, lu.offset) - } - if n != lu.n { - t.Errorf(msg, i, j, "bytes consumed", s, n, len(str)) - } - } - } - } -} diff --git a/vendor/golang.org/x/text/internal/colltab/iter_test.go b/vendor/golang.org/x/text/internal/colltab/iter_test.go deleted file mode 100644 index 5783534c7d..0000000000 --- a/vendor/golang.org/x/text/internal/colltab/iter_test.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2015 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 colltab - -import ( - "testing" -) - -func TestDoNorm(t *testing.T) { - const div = -1 // The insertion point of the next block. - tests := []struct { - in, out []int - }{{ - in: []int{4, div, 3}, - out: []int{3, 4}, - }, { - in: []int{4, div, 3, 3, 3}, - out: []int{3, 3, 3, 4}, - }, { - in: []int{0, 4, div, 3}, - out: []int{0, 3, 4}, - }, { - in: []int{0, 0, 4, 5, div, 3, 3}, - out: []int{0, 0, 3, 3, 4, 5}, - }, { - in: []int{0, 0, 1, 4, 5, div, 3, 3}, - out: []int{0, 0, 1, 3, 3, 4, 5}, - }, { - in: []int{0, 0, 1, 4, 5, div, 4, 4}, - out: []int{0, 0, 1, 4, 4, 4, 5}, - }, - } - for j, tt := range tests { - i := Iter{} - var w, p int - for k, cc := range tt.in { - - if cc == div { - w = 100 - p = k - continue - } - i.Elems = append(i.Elems, makeCE([]int{w, defaultSecondary, 2, cc})) - } - i.doNorm(p, i.Elems[p].CCC()) - if len(i.Elems) != len(tt.out) { - t.Errorf("%d: length was %d; want %d", j, len(i.Elems), len(tt.out)) - } - prevCCC := uint8(0) - for k, ce := range i.Elems { - if int(ce.CCC()) != tt.out[k] { - t.Errorf("%d:%d: unexpected CCC. Was %d; want %d", j, k, ce.CCC(), tt.out[k]) - } - if k > 0 && ce.CCC() == prevCCC && i.Elems[k-1].Primary() > ce.Primary() { - t.Errorf("%d:%d: normalization crossed across CCC boundary.", j, k) - } - } - } - - // Combining rune overflow is tested in search/pattern_test.go. -} diff --git a/vendor/golang.org/x/text/internal/colltab/numeric_test.go b/vendor/golang.org/x/text/internal/colltab/numeric_test.go deleted file mode 100644 index e9406ae3fb..0000000000 --- a/vendor/golang.org/x/text/internal/colltab/numeric_test.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2014 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 colltab - -import ( - "reflect" - "strings" - "testing" - - "golang.org/x/text/internal/testtext" -) - -const ( - digSec = defaultSecondary - digTert = defaultTertiary -) - -var tPlus3 = e(0, 50, digTert+3) - -// numWeighter is a testWeighter used for testing numericWeighter. -var numWeighter = testWeighter{ - "0": p(100), - "0": []Elem{e(100, digSec, digTert+1)}, // U+FF10 FULLWIDTH DIGIT ZERO - "₀": []Elem{e(100, digSec, digTert+5)}, // U+2080 SUBSCRIPT ZERO - - "1": p(101), - // Allow non-primary collation elements to be inserted. - "١": append(p(101), tPlus3), // U+0661 ARABIC-INDIC DIGIT ONE - // Allow varying tertiary weight if the number is Nd. - "1": []Elem{e(101, digSec, digTert+1)}, // U+FF11 FULLWIDTH DIGIT ONE - "2": p(102), - // Allow non-primary collation elements to be inserted. - "٢": append(p(102), tPlus3), // U+0662 ARABIC-INDIC DIGIT TWO - // Varying tertiary weights should be ignored. - "2": []Elem{e(102, digSec, digTert+3)}, // U+FF12 FULLWIDTH DIGIT TWO - "3": p(103), - "4": p(104), - "5": p(105), - "6": p(106), - "7": p(107), - // Weights must be strictly monotonically increasing, but do not need to be - // consecutive. - "8": p(118), - "9": p(119), - // Allow non-primary collation elements to be inserted. - "٩": append(p(119), tPlus3), // U+0669 ARABIC-INDIC DIGIT NINE - // Varying tertiary weights should be ignored. - "9": []Elem{e(119, digSec, digTert+1)}, // U+FF19 FULLWIDTH DIGIT NINE - "₉": []Elem{e(119, digSec, digTert+5)}, // U+2089 SUBSCRIPT NINE - - "a": p(5), - "b": p(6), - "c": p(8, 2), - - "klm": p(99), - - "nop": p(121), - - "x": p(200), - "y": p(201), -} - -func p(w ...int) (elems []Elem) { - for _, x := range w { - e, _ := MakeElem(x, digSec, digTert, 0) - elems = append(elems, e) - } - return elems -} - -func TestNumericAppendNext(t *testing.T) { - for _, tt := range []struct { - in string - w []Elem - }{ - {"a", p(5)}, - {"klm", p(99)}, - {"aa", p(5, 5)}, - {"1", p(120, 1, 101)}, - {"0", p(120, 0)}, - {"01", p(120, 1, 101)}, - {"0001", p(120, 1, 101)}, - {"10", p(120, 2, 101, 100)}, - {"99", p(120, 2, 119, 119)}, - {"9999", p(120, 4, 119, 119, 119, 119)}, - {"1a", p(120, 1, 101, 5)}, - {"0b", p(120, 0, 6)}, - {"01c", p(120, 1, 101, 8, 2)}, - {"10x", p(120, 2, 101, 100, 200)}, - {"99y", p(120, 2, 119, 119, 201)}, - {"9999nop", p(120, 4, 119, 119, 119, 119, 121)}, - - // Allow follow-up collation elements if they have a zero non-primary. - {"١٢٩", []Elem{e(120), e(3), e(101), tPlus3, e(102), tPlus3, e(119), tPlus3}}, - { - "129", - []Elem{ - e(120), e(3), - e(101, digSec, digTert+1), - e(102, digSec, digTert+3), - e(119, digSec, digTert+1), - }, - }, - - // Ensure AppendNext* adds to the given buffer. - {"a10", p(5, 120, 2, 101, 100)}, - } { - nw := NewNumericWeighter(numWeighter) - - b := []byte(tt.in) - got := []Elem(nil) - for n, sz := 0, 0; n < len(b); { - got, sz = nw.AppendNext(got, b[n:]) - n += sz - } - if !reflect.DeepEqual(got, tt.w) { - t.Errorf("AppendNext(%q) =\n%v; want\n%v", tt.in, got, tt.w) - } - - got = nil - for n, sz := 0, 0; n < len(tt.in); { - got, sz = nw.AppendNextString(got, tt.in[n:]) - n += sz - } - if !reflect.DeepEqual(got, tt.w) { - t.Errorf("AppendNextString(%q) =\n%v; want\n%v", tt.in, got, tt.w) - } - } -} - -func TestNumericOverflow(t *testing.T) { - manyDigits := strings.Repeat("9", maxDigits+1) + "a" - - nw := NewNumericWeighter(numWeighter) - - got, n := nw.AppendNextString(nil, manyDigits) - - if n != maxDigits { - t.Errorf("n: got %d; want %d", n, maxDigits) - } - - if got[1].Primary() != maxDigits { - t.Errorf("primary(e[1]): got %d; want %d", n, maxDigits) - } -} - -func TestNumericWeighterAlloc(t *testing.T) { - buf := make([]Elem, 100) - w := NewNumericWeighter(numWeighter) - s := "1234567890a" - - nNormal := testtext.AllocsPerRun(3, func() { numWeighter.AppendNextString(buf, s) }) - nNumeric := testtext.AllocsPerRun(3, func() { w.AppendNextString(buf, s) }) - if n := nNumeric - nNormal; n > 0 { - t.Errorf("got %f; want 0", n) - } -} diff --git a/vendor/golang.org/x/text/internal/colltab/trie_test.go b/vendor/golang.org/x/text/internal/colltab/trie_test.go deleted file mode 100644 index b056a811eb..0000000000 --- a/vendor/golang.org/x/text/internal/colltab/trie_test.go +++ /dev/null @@ -1,106 +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 colltab - -import ( - "testing" -) - -// We take the smallest, largest and an arbitrary value for each -// of the UTF-8 sequence lengths. -var testRunes = []rune{ - 0x01, 0x0C, 0x7F, // 1-byte sequences - 0x80, 0x100, 0x7FF, // 2-byte sequences - 0x800, 0x999, 0xFFFF, // 3-byte sequences - 0x10000, 0x10101, 0x10FFFF, // 4-byte sequences - 0x200, 0x201, 0x202, 0x210, 0x215, // five entries in one sparse block -} - -// Test cases for illegal runes. -type trietest struct { - size int - bytes []byte -} - -var tests = []trietest{ - // illegal runes - {1, []byte{0x80}}, - {1, []byte{0xFF}}, - {1, []byte{t2, tx - 1}}, - {1, []byte{t2, t2}}, - {2, []byte{t3, tx, tx - 1}}, - {2, []byte{t3, tx, t2}}, - {1, []byte{t3, tx - 1, tx}}, - {3, []byte{t4, tx, tx, tx - 1}}, - {3, []byte{t4, tx, tx, t2}}, - {1, []byte{t4, t2, tx, tx - 1}}, - {2, []byte{t4, tx, t2, tx - 1}}, - - // short runes - {0, []byte{t2}}, - {0, []byte{t3, tx}}, - {0, []byte{t4, tx, tx}}, - - // we only support UTF-8 up to utf8.UTFMax bytes (4 bytes) - {1, []byte{t5, tx, tx, tx, tx}}, - {1, []byte{t6, tx, tx, tx, tx, tx}}, -} - -func TestLookupTrie(t *testing.T) { - for i, r := range testRunes { - b := []byte(string(r)) - v, sz := testTrie.lookup(b) - if int(v) != i { - t.Errorf("lookup(%U): found value %#x, expected %#x", r, v, i) - } - if sz != len(b) { - t.Errorf("lookup(%U): found size %d, expected %d", r, sz, len(b)) - } - } - for i, tt := range tests { - v, sz := testTrie.lookup(tt.bytes) - if int(v) != 0 { - t.Errorf("lookup of illegal rune, case %d: found value %#x, expected 0", i, v) - } - if sz != tt.size { - t.Errorf("lookup of illegal rune, case %d: found size %d, expected %d", i, sz, tt.size) - } - } -} - -// test data is taken from exp/collate/locale/build/trie_test.go -var testValues = [832]uint32{ - 0x000c: 0x00000001, - 0x007f: 0x00000002, - 0x00c0: 0x00000003, - 0x0100: 0x00000004, - 0x0140: 0x0000000c, 0x0141: 0x0000000d, 0x0142: 0x0000000e, - 0x0150: 0x0000000f, - 0x0155: 0x00000010, - 0x01bf: 0x00000005, - 0x01c0: 0x00000006, - 0x0219: 0x00000007, - 0x027f: 0x00000008, - 0x0280: 0x00000009, - 0x02c1: 0x0000000a, - 0x033f: 0x0000000b, -} - -var testLookup = [640]uint16{ - 0x0e0: 0x05, 0x0e6: 0x06, - 0x13f: 0x07, - 0x140: 0x08, 0x144: 0x09, - 0x190: 0x03, - 0x1ff: 0x0a, - 0x20f: 0x05, - 0x242: 0x01, 0x244: 0x02, - 0x248: 0x03, - 0x25f: 0x04, - 0x260: 0x01, - 0x26f: 0x02, - 0x270: 0x04, 0x274: 0x06, -} - -var testTrie = Trie{testLookup[6*blockSize:], testValues[:], testLookup[:], testValues[:]} diff --git a/vendor/golang.org/x/text/internal/colltab/weighter_test.go b/vendor/golang.org/x/text/internal/colltab/weighter_test.go deleted file mode 100644 index b5f8487b33..0000000000 --- a/vendor/golang.org/x/text/internal/colltab/weighter_test.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2014 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 colltab - -// testWeighter is a simple Weighter that returns weights from a user-defined map. -type testWeighter map[string][]Elem - -func (t testWeighter) Start(int, []byte) int { return 0 } -func (t testWeighter) StartString(int, string) int { return 0 } -func (t testWeighter) Domain() []string { return nil } -func (t testWeighter) Top() uint32 { return 0 } - -// maxContractBytes is the maximum length of any key in the map. -const maxContractBytes = 10 - -func (t testWeighter) AppendNext(buf []Elem, s []byte) ([]Elem, int) { - n := len(s) - if n > maxContractBytes { - n = maxContractBytes - } - for i := n; i > 0; i-- { - if e, ok := t[string(s[:i])]; ok { - return append(buf, e...), i - } - } - panic("incomplete testWeighter: could not find " + string(s)) -} - -func (t testWeighter) AppendNextString(buf []Elem, s string) ([]Elem, int) { - n := len(s) - if n > maxContractBytes { - n = maxContractBytes - } - for i := n; i > 0; i-- { - if e, ok := t[s[:i]]; ok { - return append(buf, e...), i - } - } - panic("incomplete testWeighter: could not find " + s) -} diff --git a/vendor/golang.org/x/text/internal/gen/code.go b/vendor/golang.org/x/text/internal/gen/code.go index d7031b6945..0389509f2c 100644 --- a/vendor/golang.org/x/text/internal/gen/code.go +++ b/vendor/golang.org/x/text/internal/gen/code.go @@ -55,18 +55,36 @@ func (w *CodeWriter) WriteGoFile(filename, pkg string) { log.Fatalf("Could not create file %s: %v", filename, err) } defer f.Close() - if _, err = w.WriteGo(f, pkg); err != nil { + if _, err = w.WriteGo(f, pkg, ""); err != nil { + log.Fatalf("Error writing file %s: %v", filename, err) + } +} + +// WriteVersionedGoFile appends the buffer with the total size of all created +// structures and writes it as a Go file to the the given file with the given +// package name and build tags for the current Unicode version, +func (w *CodeWriter) WriteVersionedGoFile(filename, pkg string) { + tags := buildTags() + if tags != "" { + filename = insertVersion(filename, UnicodeVersion()) + } + f, err := os.Create(filename) + if err != nil { + log.Fatalf("Could not create file %s: %v", filename, err) + } + defer f.Close() + if _, err = w.WriteGo(f, pkg, tags); err != nil { log.Fatalf("Error writing file %s: %v", filename, err) } } // WriteGo appends the buffer with the total size of all created structures and // writes it as a Go file to the the given writer with the given package name. -func (w *CodeWriter) WriteGo(out io.Writer, pkg string) (n int, err error) { +func (w *CodeWriter) WriteGo(out io.Writer, pkg, tags string) (n int, err error) { sz := w.Size w.WriteComment("Total table size %d bytes (%dKiB); checksum: %X\n", sz, sz/1024, w.Hash.Sum32()) defer w.buf.Reset() - return WriteGo(out, pkg, w.buf.Bytes()) + return WriteGo(out, pkg, tags, w.buf.Bytes()) } func (w *CodeWriter) printf(f string, x ...interface{}) { diff --git a/vendor/golang.org/x/text/internal/gen/gen.go b/vendor/golang.org/x/text/internal/gen/gen.go index 2acb0355a2..4c3f760689 100644 --- a/vendor/golang.org/x/text/internal/gen/gen.go +++ b/vendor/golang.org/x/text/internal/gen/gen.go @@ -31,6 +31,7 @@ import ( "os" "path" "path/filepath" + "strings" "sync" "unicode" @@ -69,8 +70,6 @@ func Init() { const header = `// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. -package %s - ` // UnicodeVersion reports the requested Unicode version. @@ -78,11 +77,33 @@ func UnicodeVersion() string { return *unicodeVersion } -// UnicodeVersion reports the requested CLDR version. +// CLDRVersion reports the requested CLDR version. func CLDRVersion() string { return *cldrVersion } +var tags = []struct{ version, buildTags string }{ + {"10.0.0", "go1.10"}, + {"", "!go1.10"}, +} + +// buildTags reports the build tags used for the current Unicode version. +func buildTags() string { + v := UnicodeVersion() + for _, x := range tags { + // We should do a numeric comparison, but including the collate package + // would create an import cycle. We approximate it by assuming that + // longer version strings are later. + if len(x.version) <= len(v) { + return x.buildTags + } + if len(x.version) == len(v) && x.version <= v { + return x.buildTags + } + } + return tags[0].buildTags +} + // IsLocal reports whether data files are available locally. func IsLocal() bool { dir, err := localReadmeFile() @@ -243,15 +264,46 @@ func WriteGoFile(filename, pkg string, b []byte) { log.Fatalf("Could not create file %s: %v", filename, err) } defer w.Close() - if _, err = WriteGo(w, pkg, b); err != nil { + if _, err = WriteGo(w, pkg, "", b); err != nil { + log.Fatalf("Error writing file %s: %v", filename, err) + } +} + +func insertVersion(filename, version string) string { + suffix := ".go" + if strings.HasSuffix(filename, "_test.go") { + suffix = "_test.go" + } + return fmt.Sprint(filename[:len(filename)-len(suffix)], version, suffix) +} + +// WriteVersionedGoFile prepends a standard file comment, adds build tags to +// version the file for the current Unicode version, and package statement to +// the given bytes, applies gofmt, and writes them to a file with the given +// name. It will call log.Fatal if there are any errors. +func WriteVersionedGoFile(filename, pkg string, b []byte) { + tags := buildTags() + if tags != "" { + filename = insertVersion(filename, UnicodeVersion()) + } + w, err := os.Create(filename) + if err != nil { + log.Fatalf("Could not create file %s: %v", filename, err) + } + defer w.Close() + if _, err = WriteGo(w, pkg, tags, b); err != nil { log.Fatalf("Error writing file %s: %v", filename, err) } } // WriteGo prepends a standard file comment and package statement to the given // bytes, applies gofmt, and writes them to w. -func WriteGo(w io.Writer, pkg string, b []byte) (n int, err error) { - src := []byte(fmt.Sprintf(header, pkg)) +func WriteGo(w io.Writer, pkg, tags string, b []byte) (n int, err error) { + src := []byte(header) + if tags != "" { + src = append(src, fmt.Sprintf("// +build %s\n\n", tags)...) + } + src = append(src, fmt.Sprintf("package %s\n\n", pkg)...) src = append(src, b...) formatted, err := format.Source(src) if err != nil { diff --git a/vendor/golang.org/x/text/internal/gen_test.go b/vendor/golang.org/x/text/internal/gen_test.go deleted file mode 100644 index a2e1981ae2..0000000000 --- a/vendor/golang.org/x/text/internal/gen_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015 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 internal - -import ( - "testing" - - "golang.org/x/text/language" -) - -func TestParents(t *testing.T) { - testCases := []struct { - tag, parent string - }{ - {"af", "und"}, - {"en", "und"}, - {"en-001", "en"}, - {"en-AU", "en-001"}, - {"en-US", "en"}, - {"en-US-u-va-posix", "en-US"}, - {"ca-ES-valencia", "ca-ES"}, - } - for _, tc := range testCases { - tag, ok := language.CompactIndex(language.MustParse(tc.tag)) - if !ok { - t.Fatalf("Could not get index of flag %s", tc.tag) - } - want, ok := language.CompactIndex(language.MustParse(tc.parent)) - if !ok { - t.Fatalf("Could not get index of parent %s of tag %s", tc.parent, tc.tag) - } - if got := int(Parent[tag]); got != want { - t.Errorf("Parent[%s] = %d; want %d (%s)", tc.tag, got, want, tc.parent) - } - } -} diff --git a/vendor/golang.org/x/text/internal/internal_test.go b/vendor/golang.org/x/text/internal/internal_test.go deleted file mode 100644 index ce1b9a3827..0000000000 --- a/vendor/golang.org/x/text/internal/internal_test.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015 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 internal - -import ( - "fmt" - "strings" - "testing" - - "golang.org/x/text/language" -) - -func TestUnique(t *testing.T) { - testCases := []struct { - in, want string - }{ - {"", "[]"}, - {"en", "[en]"}, - {"en en", "[en]"}, - {"en en en", "[en]"}, - {"en-u-cu-eur en", "[en en-u-cu-eur]"}, - {"nl en", "[en nl]"}, - {"pt-Pt pt", "[pt pt-PT]"}, - } - for _, tc := range testCases { - tags := []language.Tag{} - for _, s := range strings.Split(tc.in, " ") { - if s != "" { - tags = append(tags, language.MustParse(s)) - } - } - if got := fmt.Sprint(UniqueTags(tags)); got != tc.want { - t.Errorf("Unique(%s) = %s; want %s", tc.in, got, tc.want) - } - } -} diff --git a/vendor/golang.org/x/text/internal/match_test.go b/vendor/golang.org/x/text/internal/match_test.go deleted file mode 100644 index 8a3fe65729..0000000000 --- a/vendor/golang.org/x/text/internal/match_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2015 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 internal - -import ( - "strings" - "testing" - - "golang.org/x/text/language" -) - -func TestInheritanceMatcher(t *testing.T) { - for i, tt := range []struct { - haveTags string - wantTags string - match string - conf language.Confidence - }{ - {"und,en,en-US", "en-US", "en-US", language.Exact}, // most specific match - {"zh-Hant,zh", "zh-TW", "zh-Hant", language.High}, // zh-TW implies Hant. - {"und,zh", "zh-TW", "und", language.High}, // zh-TW does not match zh. - {"zh", "zh-TW", "und", language.No}, // zh-TW does not match zh. - {"iw,en,nl", "he", "he", language.Exact}, // matches after canonicalization - {"he,en,nl", "iw", "he", language.Exact}, // matches after canonicalization - // Prefer first match over more specific match for various reasons: - // a) consistency of user interface is more important than an exact match, - // b) _if_ und is specified, it should be considered a correct and useful match, - // Note that a call to this Match will almost always be with a single tag. - {"und,en,en-US", "he,en-US", "und", language.High}, - } { - have := parseTags(tt.haveTags) - m := NewInheritanceMatcher(have) - tag, index, conf := m.Match(parseTags(tt.wantTags)...) - want := language.Raw.Make(tt.match) - if tag != want { - t.Errorf("%d:tag: got %q; want %q", i, tag, want) - } - if conf != language.No { - if got, _ := language.All.Canonicalize(have[index]); got != want { - t.Errorf("%d:index: got %q; want %q ", i, got, want) - } - } - if conf != tt.conf { - t.Errorf("%d:conf: got %v; want %v", i, conf, tt.conf) - } - } -} - -func parseTags(list string) (out []language.Tag) { - for _, s := range strings.Split(list, ",") { - out = append(out, language.Raw.Make(strings.TrimSpace(s))) - } - return out -} diff --git a/vendor/golang.org/x/text/internal/tables.go b/vendor/golang.org/x/text/internal/tables.go index a53042aab3..85991d3d21 100644 --- a/vendor/golang.org/x/text/internal/tables.go +++ b/vendor/golang.org/x/text/internal/tables.go @@ -4,9 +4,9 @@ package internal // Parent maps a compact index of a tag to the compact index of the parent of // this tag. -var Parent = []uint16{ // 754 elements +var Parent = []uint16{ // 768 elements // Entry 0 - 3F - 0x0000, 0x0053, 0x00e5, 0x0000, 0x0003, 0x0003, 0x0000, 0x0006, + 0x0000, 0x0053, 0x00e8, 0x0000, 0x0003, 0x0003, 0x0000, 0x0006, 0x0000, 0x0008, 0x0000, 0x000a, 0x0000, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, 0x000c, @@ -18,100 +18,101 @@ var Parent = []uint16{ // 754 elements 0x0000, 0x0040, 0x0000, 0x0042, 0x0042, 0x0000, 0x0045, 0x0045, 0x0000, 0x0048, 0x0000, 0x004a, 0x0000, 0x0000, 0x004d, 0x004c, 0x004c, 0x0000, 0x0051, 0x0051, 0x0051, 0x0051, 0x0000, 0x0056, - 0x0000, 0x0058, 0x0000, 0x005a, 0x0000, 0x005c, 0x005c, 0x0000, - 0x005f, 0x0000, 0x0061, 0x0000, 0x0063, 0x0000, 0x0065, 0x0065, - 0x0000, 0x0068, 0x0000, 0x006a, 0x006a, 0x006a, 0x006a, 0x006a, - 0x006a, 0x006a, 0x0000, 0x0072, 0x0000, 0x0074, 0x0000, 0x0076, - 0x0000, 0x0000, 0x0079, 0x0000, 0x007b, 0x0000, 0x007d, 0x0000, + 0x0056, 0x0000, 0x0059, 0x0000, 0x005b, 0x0000, 0x005d, 0x0000, + 0x005f, 0x005f, 0x0000, 0x0062, 0x0000, 0x0064, 0x0000, 0x0066, + 0x0000, 0x0068, 0x0068, 0x0000, 0x006b, 0x0000, 0x006d, 0x006d, + 0x006d, 0x006d, 0x006d, 0x006d, 0x006d, 0x0000, 0x0075, 0x0000, + 0x0077, 0x0000, 0x0079, 0x0000, 0x0000, 0x007c, 0x0000, 0x007e, // Entry 80 - BF - 0x007f, 0x007f, 0x0000, 0x0082, 0x0082, 0x0000, 0x0085, 0x0086, - 0x0086, 0x0086, 0x0085, 0x0087, 0x0086, 0x0086, 0x0086, 0x0085, - 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0087, 0x0086, - 0x0086, 0x0086, 0x0086, 0x0087, 0x0086, 0x0087, 0x0086, 0x0086, - 0x0087, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, - 0x0086, 0x0086, 0x0085, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, - 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, - 0x0086, 0x0086, 0x0086, 0x0086, 0x0085, 0x0086, 0x0085, 0x0086, + 0x0000, 0x0080, 0x0000, 0x0082, 0x0082, 0x0000, 0x0085, 0x0085, + 0x0000, 0x0088, 0x0089, 0x0089, 0x0089, 0x0088, 0x008a, 0x0089, + 0x0089, 0x0089, 0x0088, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, + 0x0089, 0x008a, 0x0089, 0x0089, 0x0089, 0x0089, 0x008a, 0x0089, + 0x008a, 0x0089, 0x0089, 0x008a, 0x0089, 0x0089, 0x0089, 0x0089, + 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0088, 0x0089, 0x0089, + 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, + 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0088, // Entry C0 - FF - 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0087, - 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0085, - 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0087, 0x0086, 0x0086, - 0x0087, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, - 0x0086, 0x0086, 0x0086, 0x0086, 0x0085, 0x0085, 0x0086, 0x0086, - 0x0085, 0x0086, 0x0086, 0x0086, 0x0086, 0x0086, 0x0000, 0x00ee, - 0x0000, 0x00f0, 0x00f1, 0x00f1, 0x00f1, 0x00f1, 0x00f1, 0x00f1, - 0x00f1, 0x00f1, 0x00f1, 0x00f0, 0x00f1, 0x00f0, 0x00f0, 0x00f1, + 0x0089, 0x0088, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, + 0x0089, 0x0089, 0x008a, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, + 0x0089, 0x0089, 0x0088, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, + 0x008a, 0x0089, 0x0089, 0x008a, 0x0089, 0x0089, 0x0089, 0x0089, + 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0089, 0x0088, + 0x0088, 0x0089, 0x0089, 0x0088, 0x0089, 0x0089, 0x0089, 0x0089, + 0x0089, 0x0000, 0x00f1, 0x0000, 0x00f3, 0x00f4, 0x00f4, 0x00f4, + 0x00f4, 0x00f4, 0x00f4, 0x00f4, 0x00f4, 0x00f4, 0x00f3, 0x00f4, // Entry 100 - 13F - 0x00f1, 0x00f0, 0x00f1, 0x00f1, 0x00f1, 0x00f1, 0x00f0, 0x00f1, - 0x00f1, 0x00f1, 0x00f1, 0x00f1, 0x00f1, 0x0000, 0x010d, 0x0000, - 0x010f, 0x0000, 0x0111, 0x0000, 0x0113, 0x0113, 0x0000, 0x0116, - 0x0116, 0x0116, 0x0116, 0x0000, 0x011b, 0x0000, 0x011d, 0x0000, - 0x011f, 0x011f, 0x0000, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, - 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, - 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, - 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, + 0x00f3, 0x00f3, 0x00f4, 0x00f4, 0x00f3, 0x00f4, 0x00f4, 0x00f4, + 0x00f4, 0x00f3, 0x00f4, 0x00f4, 0x00f4, 0x00f4, 0x00f4, 0x00f4, + 0x0000, 0x0110, 0x0000, 0x0112, 0x0000, 0x0114, 0x0000, 0x0116, + 0x0116, 0x0000, 0x0119, 0x0119, 0x0119, 0x0119, 0x0000, 0x011e, + 0x0000, 0x0120, 0x0000, 0x0122, 0x0122, 0x0000, 0x0125, 0x0125, + 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, + 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, + 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, // Entry 140 - 17F - 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, - 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, 0x0122, - 0x0122, 0x0000, 0x0151, 0x0000, 0x0153, 0x0000, 0x0155, 0x0000, - 0x0157, 0x0000, 0x0159, 0x0000, 0x015b, 0x015b, 0x015b, 0x0000, - 0x015f, 0x0000, 0x0000, 0x0162, 0x0000, 0x0164, 0x0000, 0x0166, - 0x0166, 0x0166, 0x0000, 0x016a, 0x0000, 0x016c, 0x0000, 0x016e, - 0x0000, 0x0170, 0x0170, 0x0000, 0x0173, 0x0000, 0x0175, 0x0000, - 0x0177, 0x0000, 0x0179, 0x0000, 0x017b, 0x0000, 0x017d, 0x0000, + 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, + 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, 0x0125, + 0x0125, 0x0125, 0x0125, 0x0125, 0x0000, 0x0154, 0x0000, 0x0156, + 0x0000, 0x0158, 0x0000, 0x015a, 0x0000, 0x015c, 0x0000, 0x015e, + 0x015e, 0x015e, 0x0000, 0x0162, 0x0000, 0x0000, 0x0165, 0x0000, + 0x0167, 0x0000, 0x0169, 0x0169, 0x0169, 0x0000, 0x016d, 0x0000, + 0x016f, 0x0000, 0x0171, 0x0000, 0x0173, 0x0173, 0x0000, 0x0176, + 0x0000, 0x0178, 0x0000, 0x017a, 0x0000, 0x017c, 0x0000, 0x017e, // Entry 180 - 1BF - 0x017f, 0x0000, 0x0181, 0x0181, 0x0181, 0x0181, 0x0000, 0x0000, - 0x0187, 0x0000, 0x0000, 0x018a, 0x0000, 0x018c, 0x0000, 0x0000, - 0x018f, 0x0000, 0x0191, 0x0000, 0x0000, 0x0194, 0x0000, 0x0000, - 0x0197, 0x0000, 0x0199, 0x0000, 0x019b, 0x0000, 0x019d, 0x0000, + 0x0000, 0x0180, 0x0000, 0x0000, 0x0183, 0x0000, 0x0185, 0x0185, + 0x0185, 0x0185, 0x0000, 0x0000, 0x018b, 0x0000, 0x0000, 0x018e, + 0x0000, 0x0190, 0x0000, 0x0000, 0x0193, 0x0000, 0x0195, 0x0000, + 0x0000, 0x0198, 0x0000, 0x0000, 0x019b, 0x0000, 0x019d, 0x0000, 0x019f, 0x0000, 0x01a1, 0x0000, 0x01a3, 0x0000, 0x01a5, 0x0000, - 0x01a7, 0x0000, 0x01a9, 0x0000, 0x01ab, 0x01ab, 0x0000, 0x01ae, - 0x0000, 0x01b0, 0x0000, 0x01b2, 0x0000, 0x01b4, 0x0000, 0x01b6, - 0x0000, 0x0000, 0x01b9, 0x0000, 0x01bb, 0x0000, 0x01bd, 0x0000, + 0x01a7, 0x0000, 0x01a9, 0x0000, 0x01ab, 0x0000, 0x01ad, 0x0000, + 0x01af, 0x01af, 0x0000, 0x01b2, 0x0000, 0x01b4, 0x0000, 0x01b6, + 0x0000, 0x01b8, 0x0000, 0x01ba, 0x0000, 0x0000, 0x01bd, 0x0000, // Entry 1C0 - 1FF - 0x01bf, 0x0000, 0x01c1, 0x0000, 0x01c3, 0x0000, 0x01c5, 0x01c5, - 0x01c5, 0x01c5, 0x0000, 0x01ca, 0x0000, 0x01cc, 0x01cc, 0x0000, - 0x01cf, 0x0000, 0x01d1, 0x0000, 0x01d3, 0x0000, 0x01d5, 0x0000, - 0x01d7, 0x0000, 0x01d9, 0x01d9, 0x0000, 0x01dc, 0x0000, 0x01de, + 0x01bf, 0x0000, 0x01c1, 0x0000, 0x01c3, 0x0000, 0x01c5, 0x0000, + 0x01c7, 0x0000, 0x01c9, 0x01c9, 0x01c9, 0x01c9, 0x0000, 0x01ce, + 0x0000, 0x01d0, 0x01d0, 0x0000, 0x01d3, 0x0000, 0x01d5, 0x0000, + 0x01d7, 0x0000, 0x01d9, 0x0000, 0x01db, 0x0000, 0x01dd, 0x01dd, 0x0000, 0x01e0, 0x0000, 0x01e2, 0x0000, 0x01e4, 0x0000, 0x01e6, 0x0000, 0x01e8, 0x0000, 0x01ea, 0x0000, 0x01ec, 0x0000, 0x01ee, - 0x01ee, 0x01ee, 0x0000, 0x01f2, 0x0000, 0x01f4, 0x0000, 0x01f6, - 0x0000, 0x01f8, 0x0000, 0x0000, 0x01fb, 0x0000, 0x01fd, 0x01fd, + 0x0000, 0x01f0, 0x0000, 0x01f2, 0x01f2, 0x01f2, 0x0000, 0x01f6, + 0x0000, 0x01f8, 0x0000, 0x01fa, 0x0000, 0x01fc, 0x0000, 0x0000, // Entry 200 - 23F - 0x0000, 0x0200, 0x0000, 0x0202, 0x0202, 0x0000, 0x0205, 0x0205, - 0x0000, 0x0208, 0x0208, 0x0208, 0x0208, 0x0208, 0x0208, 0x0208, - 0x0000, 0x0210, 0x0000, 0x0212, 0x0000, 0x0214, 0x0000, 0x0000, - 0x0000, 0x0000, 0x0000, 0x021a, 0x0000, 0x0000, 0x021d, 0x0000, - 0x021f, 0x021f, 0x0000, 0x0222, 0x0000, 0x0224, 0x0224, 0x0000, - 0x0000, 0x0228, 0x0227, 0x0227, 0x0000, 0x0000, 0x022d, 0x0000, - 0x022f, 0x0000, 0x0231, 0x0000, 0x023d, 0x0233, 0x023d, 0x023d, - 0x023d, 0x023d, 0x023d, 0x023d, 0x023d, 0x0233, 0x023d, 0x023d, + 0x01ff, 0x0000, 0x0201, 0x0201, 0x0000, 0x0204, 0x0000, 0x0206, + 0x0206, 0x0000, 0x0209, 0x0209, 0x0000, 0x020c, 0x020c, 0x020c, + 0x020c, 0x020c, 0x020c, 0x020c, 0x0000, 0x0214, 0x0000, 0x0216, + 0x0000, 0x0218, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x021e, + 0x0000, 0x0000, 0x0221, 0x0000, 0x0223, 0x0223, 0x0000, 0x0226, + 0x0000, 0x0228, 0x0228, 0x0000, 0x0000, 0x022c, 0x022b, 0x022b, + 0x0000, 0x0000, 0x0231, 0x0000, 0x0233, 0x0000, 0x0235, 0x0000, + 0x0241, 0x0237, 0x0241, 0x0241, 0x0241, 0x0241, 0x0241, 0x0241, // Entry 240 - 27F - 0x0000, 0x0240, 0x0240, 0x0240, 0x0000, 0x0244, 0x0000, 0x0246, - 0x0000, 0x0248, 0x0248, 0x0000, 0x024b, 0x0000, 0x024d, 0x024d, - 0x024d, 0x024d, 0x024d, 0x024d, 0x0000, 0x0254, 0x0000, 0x0256, - 0x0000, 0x0258, 0x0000, 0x025a, 0x0000, 0x025c, 0x0000, 0x0000, - 0x025f, 0x025f, 0x025f, 0x0000, 0x0263, 0x0000, 0x0265, 0x0000, - 0x0267, 0x0000, 0x0000, 0x026a, 0x0269, 0x0269, 0x0000, 0x026e, - 0x0000, 0x0270, 0x0000, 0x0272, 0x0000, 0x0000, 0x0000, 0x0000, - 0x0277, 0x0000, 0x0000, 0x027a, 0x0000, 0x027c, 0x027c, 0x027c, + 0x0241, 0x0237, 0x0241, 0x0241, 0x0000, 0x0244, 0x0244, 0x0244, + 0x0000, 0x0248, 0x0000, 0x024a, 0x0000, 0x024c, 0x024c, 0x0000, + 0x024f, 0x0000, 0x0251, 0x0251, 0x0251, 0x0251, 0x0251, 0x0251, + 0x0000, 0x0258, 0x0000, 0x025a, 0x0000, 0x025c, 0x0000, 0x025e, + 0x0000, 0x0260, 0x0000, 0x0262, 0x0000, 0x0000, 0x0265, 0x0265, + 0x0265, 0x0000, 0x0269, 0x0000, 0x026b, 0x0000, 0x026d, 0x0000, + 0x0000, 0x0270, 0x026f, 0x026f, 0x0000, 0x0274, 0x0000, 0x0276, + 0x0000, 0x0278, 0x0000, 0x0000, 0x0000, 0x0000, 0x027d, 0x0000, // Entry 280 - 2BF - 0x027c, 0x0000, 0x0281, 0x0281, 0x0281, 0x0000, 0x0285, 0x0285, - 0x0285, 0x0285, 0x0285, 0x0000, 0x028b, 0x028b, 0x028b, 0x028b, - 0x0000, 0x0000, 0x0000, 0x0000, 0x0293, 0x0293, 0x0293, 0x0000, - 0x0297, 0x0297, 0x0297, 0x0297, 0x0000, 0x0000, 0x029d, 0x029d, - 0x029d, 0x029d, 0x0000, 0x02a2, 0x0000, 0x02a4, 0x02a4, 0x0000, - 0x02a7, 0x0000, 0x02a9, 0x02a9, 0x0000, 0x0000, 0x02ad, 0x0000, - 0x0000, 0x02b0, 0x0000, 0x02b2, 0x02b2, 0x0000, 0x0000, 0x02b6, - 0x0000, 0x02b8, 0x0000, 0x02ba, 0x0000, 0x02bc, 0x0000, 0x02be, + 0x0000, 0x0280, 0x0000, 0x0282, 0x0282, 0x0282, 0x0282, 0x0000, + 0x0287, 0x0287, 0x0287, 0x0000, 0x028b, 0x028b, 0x028b, 0x028b, + 0x028b, 0x0000, 0x0291, 0x0291, 0x0291, 0x0291, 0x0000, 0x0000, + 0x0000, 0x0000, 0x0299, 0x0299, 0x0299, 0x0000, 0x029d, 0x029d, + 0x029d, 0x029d, 0x0000, 0x0000, 0x02a3, 0x02a3, 0x02a3, 0x02a3, + 0x0000, 0x02a8, 0x0000, 0x02aa, 0x02aa, 0x0000, 0x02ad, 0x0000, + 0x02af, 0x0000, 0x02b1, 0x02b1, 0x0000, 0x0000, 0x02b5, 0x0000, + 0x0000, 0x02b8, 0x0000, 0x02ba, 0x02ba, 0x0000, 0x0000, 0x02be, // Entry 2C0 - 2FF - 0x02be, 0x0000, 0x0000, 0x02c2, 0x0000, 0x02c4, 0x02c1, 0x02c1, - 0x0000, 0x0000, 0x02c9, 0x02c8, 0x02c8, 0x0000, 0x0000, 0x02ce, - 0x0000, 0x02d0, 0x0000, 0x02d2, 0x0000, 0x0000, 0x02d5, 0x0000, - 0x0000, 0x0000, 0x02d9, 0x0000, 0x02db, 0x0000, 0x02dd, 0x0000, - 0x02df, 0x02df, 0x0000, 0x02e2, 0x0000, 0x02e4, 0x0000, 0x02e6, - 0x02e6, 0x02e6, 0x02e6, 0x02e6, 0x0000, 0x02ec, 0x02ed, 0x02ec, - 0x0000, 0x02f0, -} // Size: 1532 bytes + 0x0000, 0x02c0, 0x0000, 0x02c2, 0x0000, 0x02c4, 0x0000, 0x02c6, + 0x0000, 0x02c8, 0x02c8, 0x0000, 0x0000, 0x02cc, 0x0000, 0x02ce, + 0x02cb, 0x02cb, 0x0000, 0x0000, 0x02d3, 0x02d2, 0x02d2, 0x0000, + 0x0000, 0x02d8, 0x0000, 0x02da, 0x0000, 0x02dc, 0x0000, 0x0000, + 0x02df, 0x0000, 0x02e1, 0x0000, 0x0000, 0x02e4, 0x0000, 0x02e6, + 0x0000, 0x02e8, 0x0000, 0x02ea, 0x02ea, 0x0000, 0x0000, 0x02ee, + 0x02ed, 0x02ed, 0x0000, 0x02f2, 0x0000, 0x02f4, 0x02f4, 0x02f4, + 0x02f4, 0x02f4, 0x0000, 0x02fa, 0x02fb, 0x02fa, 0x0000, 0x02fe, +} // Size: 1560 bytes -// Total table size 1532 bytes (1KiB); checksum: 90718A2 +// Total table size 1560 bytes (1KiB); checksum: 4897681C diff --git a/vendor/golang.org/x/text/internal/tag/tag_test.go b/vendor/golang.org/x/text/internal/tag/tag_test.go deleted file mode 100644 index da174a24c4..0000000000 --- a/vendor/golang.org/x/text/internal/tag/tag_test.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2015 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 tag - -import ( - "strings" - "testing" -) - -var strdata = []string{ - "aa ", - "aaa ", - "aaaa", - "aaab", - "aab ", - "ab ", - "ba ", - "xxxx", - "\xff\xff\xff\xff", -} - -var testCases = map[string]int{ - "a": 0, - "aa": 0, - "aaa": 1, - "aa ": 0, - "aaaa": 2, - "aaab": 3, - "b": 6, - "ba": 6, - " ": -1, - "aaax": -1, - "bbbb": -1, - "zzzz": -1, -} - -func TestIndex(t *testing.T) { - index := Index(strings.Join(strdata, "")) - for k, v := range testCases { - if i := index.Index([]byte(k)); i != v { - t.Errorf("%s: got %d; want %d", k, i, v) - } - } -} - -func TestFixCase(t *testing.T) { - tests := []string{ - "aaaa", "AbCD", "abcd", - "Zzzz", "AbCD", "Abcd", - "Zzzz", "AbC", "", - "XXX", "ab ", "", - "XXX", "usd", "USD", - "cmn", "AB ", "", - "gsw", "CMN", "cmn", - } - for tc := tests; len(tc) > 0; tc = tc[3:] { - b := []byte(tc[1]) - if !FixCase(tc[0], b) { - b = nil - } - if string(b) != tc[2] { - t.Errorf("FixCase(%q, %q) = %q; want %q", tc[0], tc[1], b, tc[2]) - } - } -} diff --git a/vendor/golang.org/x/text/internal/triegen/data_test.go b/vendor/golang.org/x/text/internal/triegen/data_test.go deleted file mode 100644 index 91de547a55..0000000000 --- a/vendor/golang.org/x/text/internal/triegen/data_test.go +++ /dev/null @@ -1,875 +0,0 @@ -// This file is generated with "go test -tags generate". DO NOT EDIT! -// +build !generate - -package triegen_test - -// lookup returns the trie value for the first UTF-8 encoding in s and -// the width in bytes of this encoding. The size will be 0 if s does not -// hold enough bytes to complete the encoding. len(s) must be greater than 0. -func (t *randTrie) lookup(s []byte) (v uint8, sz int) { - c0 := s[0] - switch { - case c0 < 0x80: // is ASCII - return randValues[c0], 1 - case c0 < 0xC2: - return 0, 1 // Illegal UTF-8: not a starter, not ASCII. - case c0 < 0xE0: // 2-byte UTF-8 - if len(s) < 2 { - return 0, 0 - } - i := randIndex[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c1), 2 - case c0 < 0xF0: // 3-byte UTF-8 - if len(s) < 3 { - return 0, 0 - } - i := randIndex[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - o := uint32(i)<<6 + uint32(c1) - i = randIndex[o] - c2 := s[2] - if c2 < 0x80 || 0xC0 <= c2 { - return 0, 2 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c2), 3 - case c0 < 0xF8: // 4-byte UTF-8 - if len(s) < 4 { - return 0, 0 - } - i := randIndex[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - o := uint32(i)<<6 + uint32(c1) - i = randIndex[o] - c2 := s[2] - if c2 < 0x80 || 0xC0 <= c2 { - return 0, 2 // Illegal UTF-8: not a continuation byte. - } - o = uint32(i)<<6 + uint32(c2) - i = randIndex[o] - c3 := s[3] - if c3 < 0x80 || 0xC0 <= c3 { - return 0, 3 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c3), 4 - } - // Illegal rune - return 0, 1 -} - -// lookupUnsafe returns the trie value for the first UTF-8 encoding in s. -// s must start with a full and valid UTF-8 encoded rune. -func (t *randTrie) lookupUnsafe(s []byte) uint8 { - c0 := s[0] - if c0 < 0x80 { // is ASCII - return randValues[c0] - } - i := randIndex[c0] - if c0 < 0xE0 { // 2-byte UTF-8 - return t.lookupValue(uint32(i), s[1]) - } - i = randIndex[uint32(i)<<6+uint32(s[1])] - if c0 < 0xF0 { // 3-byte UTF-8 - return t.lookupValue(uint32(i), s[2]) - } - i = randIndex[uint32(i)<<6+uint32(s[2])] - if c0 < 0xF8 { // 4-byte UTF-8 - return t.lookupValue(uint32(i), s[3]) - } - return 0 -} - -// lookupString returns the trie value for the first UTF-8 encoding in s and -// the width in bytes of this encoding. The size will be 0 if s does not -// hold enough bytes to complete the encoding. len(s) must be greater than 0. -func (t *randTrie) lookupString(s string) (v uint8, sz int) { - c0 := s[0] - switch { - case c0 < 0x80: // is ASCII - return randValues[c0], 1 - case c0 < 0xC2: - return 0, 1 // Illegal UTF-8: not a starter, not ASCII. - case c0 < 0xE0: // 2-byte UTF-8 - if len(s) < 2 { - return 0, 0 - } - i := randIndex[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c1), 2 - case c0 < 0xF0: // 3-byte UTF-8 - if len(s) < 3 { - return 0, 0 - } - i := randIndex[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - o := uint32(i)<<6 + uint32(c1) - i = randIndex[o] - c2 := s[2] - if c2 < 0x80 || 0xC0 <= c2 { - return 0, 2 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c2), 3 - case c0 < 0xF8: // 4-byte UTF-8 - if len(s) < 4 { - return 0, 0 - } - i := randIndex[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - o := uint32(i)<<6 + uint32(c1) - i = randIndex[o] - c2 := s[2] - if c2 < 0x80 || 0xC0 <= c2 { - return 0, 2 // Illegal UTF-8: not a continuation byte. - } - o = uint32(i)<<6 + uint32(c2) - i = randIndex[o] - c3 := s[3] - if c3 < 0x80 || 0xC0 <= c3 { - return 0, 3 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c3), 4 - } - // Illegal rune - return 0, 1 -} - -// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s. -// s must start with a full and valid UTF-8 encoded rune. -func (t *randTrie) lookupStringUnsafe(s string) uint8 { - c0 := s[0] - if c0 < 0x80 { // is ASCII - return randValues[c0] - } - i := randIndex[c0] - if c0 < 0xE0 { // 2-byte UTF-8 - return t.lookupValue(uint32(i), s[1]) - } - i = randIndex[uint32(i)<<6+uint32(s[1])] - if c0 < 0xF0 { // 3-byte UTF-8 - return t.lookupValue(uint32(i), s[2]) - } - i = randIndex[uint32(i)<<6+uint32(s[2])] - if c0 < 0xF8 { // 4-byte UTF-8 - return t.lookupValue(uint32(i), s[3]) - } - return 0 -} - -// randTrie. Total size: 9280 bytes (9.06 KiB). Checksum: 6debd324a8debb8f. -type randTrie struct{} - -func newRandTrie(i int) *randTrie { - return &randTrie{} -} - -// lookupValue determines the type of block n and looks up the value for b. -func (t *randTrie) lookupValue(n uint32, b byte) uint8 { - switch { - default: - return uint8(randValues[n<<6+uint32(b)]) - } -} - -// randValues: 56 blocks, 3584 entries, 3584 bytes -// The third block is the zero block. -var randValues = [3584]uint8{ - // Block 0x0, offset 0x0 - // Block 0x1, offset 0x40 - // Block 0x2, offset 0x80 - // Block 0x3, offset 0xc0 - 0xc9: 0x0001, - // Block 0x4, offset 0x100 - 0x100: 0x0001, - // Block 0x5, offset 0x140 - 0x155: 0x0001, - // Block 0x6, offset 0x180 - 0x196: 0x0001, - // Block 0x7, offset 0x1c0 - 0x1ef: 0x0001, - // Block 0x8, offset 0x200 - 0x206: 0x0001, - // Block 0x9, offset 0x240 - 0x258: 0x0001, - // Block 0xa, offset 0x280 - 0x288: 0x0001, - // Block 0xb, offset 0x2c0 - 0x2f2: 0x0001, - // Block 0xc, offset 0x300 - 0x304: 0x0001, - // Block 0xd, offset 0x340 - 0x34b: 0x0001, - // Block 0xe, offset 0x380 - 0x3ba: 0x0001, - // Block 0xf, offset 0x3c0 - 0x3f5: 0x0001, - // Block 0x10, offset 0x400 - 0x41d: 0x0001, - // Block 0x11, offset 0x440 - 0x442: 0x0001, - // Block 0x12, offset 0x480 - 0x4bb: 0x0001, - // Block 0x13, offset 0x4c0 - 0x4e9: 0x0001, - // Block 0x14, offset 0x500 - 0x53e: 0x0001, - // Block 0x15, offset 0x540 - 0x55f: 0x0001, - // Block 0x16, offset 0x580 - 0x5b7: 0x0001, - // Block 0x17, offset 0x5c0 - 0x5d9: 0x0001, - // Block 0x18, offset 0x600 - 0x60e: 0x0001, - // Block 0x19, offset 0x640 - 0x652: 0x0001, - // Block 0x1a, offset 0x680 - 0x68f: 0x0001, - // Block 0x1b, offset 0x6c0 - 0x6dc: 0x0001, - // Block 0x1c, offset 0x700 - 0x703: 0x0001, - // Block 0x1d, offset 0x740 - 0x741: 0x0001, - // Block 0x1e, offset 0x780 - 0x79b: 0x0001, - // Block 0x1f, offset 0x7c0 - 0x7f1: 0x0001, - // Block 0x20, offset 0x800 - 0x833: 0x0001, - // Block 0x21, offset 0x840 - 0x853: 0x0001, - // Block 0x22, offset 0x880 - 0x8a2: 0x0001, - // Block 0x23, offset 0x8c0 - 0x8f8: 0x0001, - // Block 0x24, offset 0x900 - 0x917: 0x0001, - // Block 0x25, offset 0x940 - 0x945: 0x0001, - // Block 0x26, offset 0x980 - 0x99e: 0x0001, - // Block 0x27, offset 0x9c0 - 0x9fd: 0x0001, - // Block 0x28, offset 0xa00 - 0xa0d: 0x0001, - // Block 0x29, offset 0xa40 - 0xa66: 0x0001, - // Block 0x2a, offset 0xa80 - 0xaab: 0x0001, - // Block 0x2b, offset 0xac0 - 0xaea: 0x0001, - // Block 0x2c, offset 0xb00 - 0xb2d: 0x0001, - // Block 0x2d, offset 0xb40 - 0xb54: 0x0001, - // Block 0x2e, offset 0xb80 - 0xb90: 0x0001, - // Block 0x2f, offset 0xbc0 - 0xbe5: 0x0001, - // Block 0x30, offset 0xc00 - 0xc28: 0x0001, - // Block 0x31, offset 0xc40 - 0xc7c: 0x0001, - // Block 0x32, offset 0xc80 - 0xcbf: 0x0001, - // Block 0x33, offset 0xcc0 - 0xcc7: 0x0001, - // Block 0x34, offset 0xd00 - 0xd34: 0x0001, - // Block 0x35, offset 0xd40 - 0xd61: 0x0001, - // Block 0x36, offset 0xd80 - 0xdb9: 0x0001, - // Block 0x37, offset 0xdc0 - 0xdda: 0x0001, -} - -// randIndex: 89 blocks, 5696 entries, 5696 bytes -// Block 0 is the zero block. -var randIndex = [5696]uint8{ - // Block 0x0, offset 0x0 - // Block 0x1, offset 0x40 - // Block 0x2, offset 0x80 - // Block 0x3, offset 0xc0 - 0xe1: 0x02, 0xe3: 0x03, 0xe4: 0x04, - 0xea: 0x05, 0xeb: 0x06, 0xec: 0x07, - 0xf0: 0x10, 0xf1: 0x24, 0xf2: 0x3d, 0xf3: 0x4f, 0xf4: 0x56, - // Block 0x4, offset 0x100 - 0x107: 0x01, - // Block 0x5, offset 0x140 - 0x16c: 0x02, - // Block 0x6, offset 0x180 - 0x19c: 0x03, - 0x1ae: 0x04, - // Block 0x7, offset 0x1c0 - 0x1d8: 0x05, - 0x1f7: 0x06, - // Block 0x8, offset 0x200 - 0x20c: 0x07, - // Block 0x9, offset 0x240 - 0x24a: 0x08, - // Block 0xa, offset 0x280 - 0x2b6: 0x09, - // Block 0xb, offset 0x2c0 - 0x2d5: 0x0a, - // Block 0xc, offset 0x300 - 0x31a: 0x0b, - // Block 0xd, offset 0x340 - 0x373: 0x0c, - // Block 0xe, offset 0x380 - 0x38b: 0x0d, - // Block 0xf, offset 0x3c0 - 0x3f0: 0x0e, - // Block 0x10, offset 0x400 - 0x433: 0x0f, - // Block 0x11, offset 0x440 - 0x45d: 0x10, - // Block 0x12, offset 0x480 - 0x491: 0x08, 0x494: 0x09, 0x497: 0x0a, - 0x49b: 0x0b, 0x49c: 0x0c, - 0x4a1: 0x0d, - 0x4ad: 0x0e, - 0x4ba: 0x0f, - // Block 0x13, offset 0x4c0 - 0x4c1: 0x11, - // Block 0x14, offset 0x500 - 0x531: 0x12, - // Block 0x15, offset 0x540 - 0x546: 0x13, - // Block 0x16, offset 0x580 - 0x5ab: 0x14, - // Block 0x17, offset 0x5c0 - 0x5d4: 0x11, - 0x5fe: 0x11, - // Block 0x18, offset 0x600 - 0x618: 0x0a, - // Block 0x19, offset 0x640 - 0x65b: 0x15, - // Block 0x1a, offset 0x680 - 0x6a0: 0x16, - // Block 0x1b, offset 0x6c0 - 0x6d2: 0x17, - 0x6f6: 0x18, - // Block 0x1c, offset 0x700 - 0x711: 0x19, - // Block 0x1d, offset 0x740 - 0x768: 0x1a, - // Block 0x1e, offset 0x780 - 0x783: 0x1b, - // Block 0x1f, offset 0x7c0 - 0x7f9: 0x1c, - // Block 0x20, offset 0x800 - 0x831: 0x1d, - // Block 0x21, offset 0x840 - 0x85e: 0x1e, - // Block 0x22, offset 0x880 - 0x898: 0x1f, - // Block 0x23, offset 0x8c0 - 0x8c7: 0x18, - 0x8d5: 0x14, - 0x8f7: 0x20, - 0x8fe: 0x1f, - // Block 0x24, offset 0x900 - 0x905: 0x21, - // Block 0x25, offset 0x940 - 0x966: 0x03, - // Block 0x26, offset 0x980 - 0x981: 0x07, 0x983: 0x11, - 0x989: 0x12, 0x98a: 0x13, 0x98e: 0x14, 0x98f: 0x15, - 0x992: 0x16, 0x995: 0x17, 0x996: 0x18, - 0x998: 0x19, 0x999: 0x1a, 0x99b: 0x1b, 0x99f: 0x1c, - 0x9a3: 0x1d, - 0x9ad: 0x1e, 0x9af: 0x1f, - 0x9b0: 0x20, 0x9b1: 0x21, - 0x9b8: 0x22, 0x9bd: 0x23, - // Block 0x27, offset 0x9c0 - 0x9cd: 0x22, - // Block 0x28, offset 0xa00 - 0xa0c: 0x08, - // Block 0x29, offset 0xa40 - 0xa6f: 0x1c, - // Block 0x2a, offset 0xa80 - 0xa90: 0x1a, - 0xaaf: 0x23, - // Block 0x2b, offset 0xac0 - 0xae3: 0x19, - 0xae8: 0x24, - 0xafc: 0x25, - // Block 0x2c, offset 0xb00 - 0xb13: 0x26, - // Block 0x2d, offset 0xb40 - 0xb67: 0x1c, - // Block 0x2e, offset 0xb80 - 0xb8f: 0x0b, - // Block 0x2f, offset 0xbc0 - 0xbcb: 0x27, - 0xbe7: 0x26, - // Block 0x30, offset 0xc00 - 0xc34: 0x16, - // Block 0x31, offset 0xc40 - 0xc62: 0x03, - // Block 0x32, offset 0xc80 - 0xcbb: 0x12, - // Block 0x33, offset 0xcc0 - 0xcdf: 0x09, - // Block 0x34, offset 0xd00 - 0xd34: 0x0a, - // Block 0x35, offset 0xd40 - 0xd41: 0x1e, - // Block 0x36, offset 0xd80 - 0xd83: 0x28, - // Block 0x37, offset 0xdc0 - 0xdc0: 0x15, - // Block 0x38, offset 0xe00 - 0xe1a: 0x15, - // Block 0x39, offset 0xe40 - 0xe65: 0x29, - // Block 0x3a, offset 0xe80 - 0xe86: 0x1f, - // Block 0x3b, offset 0xec0 - 0xeec: 0x18, - // Block 0x3c, offset 0xf00 - 0xf28: 0x2a, - // Block 0x3d, offset 0xf40 - 0xf53: 0x08, - // Block 0x3e, offset 0xf80 - 0xfa2: 0x2b, - 0xfaa: 0x17, - // Block 0x3f, offset 0xfc0 - 0xfc0: 0x25, 0xfc2: 0x26, - 0xfc9: 0x27, 0xfcd: 0x28, 0xfce: 0x29, - 0xfd5: 0x2a, - 0xfd8: 0x2b, 0xfd9: 0x2c, 0xfdf: 0x2d, - 0xfe1: 0x2e, 0xfe2: 0x2f, 0xfe3: 0x30, 0xfe6: 0x31, - 0xfe9: 0x32, 0xfec: 0x33, 0xfed: 0x34, 0xfef: 0x35, - 0xff1: 0x36, 0xff2: 0x37, 0xff3: 0x38, 0xff4: 0x39, - 0xffa: 0x3a, 0xffc: 0x3b, 0xffe: 0x3c, - // Block 0x40, offset 0x1000 - 0x102c: 0x2c, - // Block 0x41, offset 0x1040 - 0x1074: 0x2c, - // Block 0x42, offset 0x1080 - 0x108c: 0x08, - 0x10a0: 0x2d, - // Block 0x43, offset 0x10c0 - 0x10e8: 0x10, - // Block 0x44, offset 0x1100 - 0x110f: 0x13, - // Block 0x45, offset 0x1140 - 0x114b: 0x2e, - // Block 0x46, offset 0x1180 - 0x118b: 0x23, - 0x119d: 0x0c, - // Block 0x47, offset 0x11c0 - 0x11c3: 0x12, - 0x11f9: 0x0f, - // Block 0x48, offset 0x1200 - 0x121e: 0x1b, - // Block 0x49, offset 0x1240 - 0x1270: 0x2f, - // Block 0x4a, offset 0x1280 - 0x128a: 0x1b, - 0x12a7: 0x02, - // Block 0x4b, offset 0x12c0 - 0x12fb: 0x14, - // Block 0x4c, offset 0x1300 - 0x1333: 0x30, - // Block 0x4d, offset 0x1340 - 0x134d: 0x31, - // Block 0x4e, offset 0x1380 - 0x138e: 0x15, - // Block 0x4f, offset 0x13c0 - 0x13f4: 0x32, - // Block 0x50, offset 0x1400 - 0x141b: 0x33, - // Block 0x51, offset 0x1440 - 0x1448: 0x3e, 0x1449: 0x3f, 0x144a: 0x40, 0x144f: 0x41, - 0x1459: 0x42, 0x145c: 0x43, 0x145e: 0x44, 0x145f: 0x45, - 0x1468: 0x46, 0x1469: 0x47, 0x146c: 0x48, 0x146d: 0x49, 0x146e: 0x4a, - 0x1472: 0x4b, 0x1473: 0x4c, - 0x1479: 0x4d, 0x147b: 0x4e, - // Block 0x52, offset 0x1480 - 0x1480: 0x34, - 0x1499: 0x11, - 0x14b6: 0x2c, - // Block 0x53, offset 0x14c0 - 0x14e4: 0x0d, - // Block 0x54, offset 0x1500 - 0x1527: 0x08, - // Block 0x55, offset 0x1540 - 0x1555: 0x2b, - // Block 0x56, offset 0x1580 - 0x15b2: 0x35, - // Block 0x57, offset 0x15c0 - 0x15f2: 0x1c, 0x15f4: 0x29, - // Block 0x58, offset 0x1600 - 0x1600: 0x50, 0x1603: 0x51, - 0x1608: 0x52, 0x160a: 0x53, 0x160d: 0x54, 0x160e: 0x55, -} - -// lookup returns the trie value for the first UTF-8 encoding in s and -// the width in bytes of this encoding. The size will be 0 if s does not -// hold enough bytes to complete the encoding. len(s) must be greater than 0. -func (t *multiTrie) lookup(s []byte) (v uint64, sz int) { - c0 := s[0] - switch { - case c0 < 0x80: // is ASCII - return t.ascii[c0], 1 - case c0 < 0xC2: - return 0, 1 // Illegal UTF-8: not a starter, not ASCII. - case c0 < 0xE0: // 2-byte UTF-8 - if len(s) < 2 { - return 0, 0 - } - i := t.utf8Start[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c1), 2 - case c0 < 0xF0: // 3-byte UTF-8 - if len(s) < 3 { - return 0, 0 - } - i := t.utf8Start[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - o := uint32(i)<<6 + uint32(c1) - i = multiIndex[o] - c2 := s[2] - if c2 < 0x80 || 0xC0 <= c2 { - return 0, 2 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c2), 3 - case c0 < 0xF8: // 4-byte UTF-8 - if len(s) < 4 { - return 0, 0 - } - i := t.utf8Start[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - o := uint32(i)<<6 + uint32(c1) - i = multiIndex[o] - c2 := s[2] - if c2 < 0x80 || 0xC0 <= c2 { - return 0, 2 // Illegal UTF-8: not a continuation byte. - } - o = uint32(i)<<6 + uint32(c2) - i = multiIndex[o] - c3 := s[3] - if c3 < 0x80 || 0xC0 <= c3 { - return 0, 3 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c3), 4 - } - // Illegal rune - return 0, 1 -} - -// lookupUnsafe returns the trie value for the first UTF-8 encoding in s. -// s must start with a full and valid UTF-8 encoded rune. -func (t *multiTrie) lookupUnsafe(s []byte) uint64 { - c0 := s[0] - if c0 < 0x80 { // is ASCII - return t.ascii[c0] - } - i := t.utf8Start[c0] - if c0 < 0xE0 { // 2-byte UTF-8 - return t.lookupValue(uint32(i), s[1]) - } - i = multiIndex[uint32(i)<<6+uint32(s[1])] - if c0 < 0xF0 { // 3-byte UTF-8 - return t.lookupValue(uint32(i), s[2]) - } - i = multiIndex[uint32(i)<<6+uint32(s[2])] - if c0 < 0xF8 { // 4-byte UTF-8 - return t.lookupValue(uint32(i), s[3]) - } - return 0 -} - -// lookupString returns the trie value for the first UTF-8 encoding in s and -// the width in bytes of this encoding. The size will be 0 if s does not -// hold enough bytes to complete the encoding. len(s) must be greater than 0. -func (t *multiTrie) lookupString(s string) (v uint64, sz int) { - c0 := s[0] - switch { - case c0 < 0x80: // is ASCII - return t.ascii[c0], 1 - case c0 < 0xC2: - return 0, 1 // Illegal UTF-8: not a starter, not ASCII. - case c0 < 0xE0: // 2-byte UTF-8 - if len(s) < 2 { - return 0, 0 - } - i := t.utf8Start[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c1), 2 - case c0 < 0xF0: // 3-byte UTF-8 - if len(s) < 3 { - return 0, 0 - } - i := t.utf8Start[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - o := uint32(i)<<6 + uint32(c1) - i = multiIndex[o] - c2 := s[2] - if c2 < 0x80 || 0xC0 <= c2 { - return 0, 2 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c2), 3 - case c0 < 0xF8: // 4-byte UTF-8 - if len(s) < 4 { - return 0, 0 - } - i := t.utf8Start[c0] - c1 := s[1] - if c1 < 0x80 || 0xC0 <= c1 { - return 0, 1 // Illegal UTF-8: not a continuation byte. - } - o := uint32(i)<<6 + uint32(c1) - i = multiIndex[o] - c2 := s[2] - if c2 < 0x80 || 0xC0 <= c2 { - return 0, 2 // Illegal UTF-8: not a continuation byte. - } - o = uint32(i)<<6 + uint32(c2) - i = multiIndex[o] - c3 := s[3] - if c3 < 0x80 || 0xC0 <= c3 { - return 0, 3 // Illegal UTF-8: not a continuation byte. - } - return t.lookupValue(uint32(i), c3), 4 - } - // Illegal rune - return 0, 1 -} - -// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s. -// s must start with a full and valid UTF-8 encoded rune. -func (t *multiTrie) lookupStringUnsafe(s string) uint64 { - c0 := s[0] - if c0 < 0x80 { // is ASCII - return t.ascii[c0] - } - i := t.utf8Start[c0] - if c0 < 0xE0 { // 2-byte UTF-8 - return t.lookupValue(uint32(i), s[1]) - } - i = multiIndex[uint32(i)<<6+uint32(s[1])] - if c0 < 0xF0 { // 3-byte UTF-8 - return t.lookupValue(uint32(i), s[2]) - } - i = multiIndex[uint32(i)<<6+uint32(s[2])] - if c0 < 0xF8 { // 4-byte UTF-8 - return t.lookupValue(uint32(i), s[3]) - } - return 0 -} - -// multiTrie. Total size: 18250 bytes (17.82 KiB). Checksum: a69a609d8696aa5e. -type multiTrie struct { - ascii []uint64 // index for ASCII bytes - utf8Start []uint8 // index for UTF-8 bytes >= 0xC0 -} - -func newMultiTrie(i int) *multiTrie { - h := multiTrieHandles[i] - return &multiTrie{multiValues[uint32(h.ascii)<<6:], multiIndex[uint32(h.multi)<<6:]} -} - -type multiTrieHandle struct { - ascii, multi uint8 -} - -// multiTrieHandles: 5 handles, 10 bytes -var multiTrieHandles = [5]multiTrieHandle{ - {0, 0}, // 8c1e77823143d35c: all - {0, 23}, // 8fb58ff8243b45b0: ASCII only - {0, 23}, // 8fb58ff8243b45b0: ASCII only 2 - {0, 24}, // 2ccc43994f11046f: BMP only - {30, 25}, // ce448591bdcb4733: No BMP -} - -// lookupValue determines the type of block n and looks up the value for b. -func (t *multiTrie) lookupValue(n uint32, b byte) uint64 { - switch { - default: - return uint64(multiValues[n<<6+uint32(b)]) - } -} - -// multiValues: 32 blocks, 2048 entries, 16384 bytes -// The third block is the zero block. -var multiValues = [2048]uint64{ - // Block 0x0, offset 0x0 - 0x03: 0x6e361699800b9fb8, 0x04: 0x52d3935a34f6f0b, 0x05: 0x2948319393e7ef10, - 0x07: 0x20f03b006704f663, 0x08: 0x6c15c0732bb2495f, 0x09: 0xe54e2c59d953551, - 0x0f: 0x33d8a825807d8037, 0x10: 0x6ecd93cb12168b92, 0x11: 0x6a81c9c0ce86e884, - 0x1f: 0xa03e77aac8be79b, 0x20: 0x28591d0e7e486efa, 0x21: 0x716fa3bc398dec8, - 0x3f: 0x4fd3bcfa72bce8b0, - // Block 0x1, offset 0x40 - 0x40: 0x3cbaef3db8ba5f12, 0x41: 0x2d262347c1f56357, - 0x7f: 0x782caa2d25a418a9, - // Block 0x2, offset 0x80 - // Block 0x3, offset 0xc0 - 0xc0: 0x6bbd1f937b1ff5d2, 0xc1: 0x732e23088d2eb8a4, - // Block 0x4, offset 0x100 - 0x13f: 0x56f8c4c82f5962dc, - // Block 0x5, offset 0x140 - 0x140: 0x57dc4544729a5da2, 0x141: 0x2f62f9cd307ffa0d, - // Block 0x6, offset 0x180 - 0x1bf: 0x7bf4d0ebf302a088, - // Block 0x7, offset 0x1c0 - 0x1c0: 0x1f0d67f249e59931, 0x1c1: 0x3011def73aa550c7, - // Block 0x8, offset 0x200 - 0x23f: 0x5de81c1dff6bf29d, - // Block 0x9, offset 0x240 - 0x240: 0x752c035737b825e8, 0x241: 0x1e793399081e3bb3, - // Block 0xa, offset 0x280 - 0x2bf: 0x6a28f01979cbf059, - // Block 0xb, offset 0x2c0 - 0x2c0: 0x373a4b0f2cbd4c74, 0x2c1: 0x4fd2c288683b767c, - // Block 0xc, offset 0x300 - 0x33f: 0x5a10ffa9e29184fb, - // Block 0xd, offset 0x340 - 0x340: 0x700f9bdb53fff6a5, 0x341: 0xcde93df0427eb79, - // Block 0xe, offset 0x380 - 0x3bf: 0x74071288fff39c76, - // Block 0xf, offset 0x3c0 - 0x3c0: 0x481fc2f510e5268a, 0x3c1: 0x7565c28164204849, - // Block 0x10, offset 0x400 - 0x43f: 0x5676a62fd49c6bec, - // Block 0x11, offset 0x440 - 0x440: 0x2f2d15776cbafc6b, 0x441: 0x4c55e8dc0ff11a3f, - // Block 0x12, offset 0x480 - 0x4bf: 0x69d6f0fe711fafc9, - // Block 0x13, offset 0x4c0 - 0x4c0: 0x33181de28cfb062d, 0x4c1: 0x2ef3adc6bb2f2d02, - // Block 0x14, offset 0x500 - 0x53f: 0xe03b31814c95f8b, - // Block 0x15, offset 0x540 - 0x540: 0x3bf6dc9a1c115603, 0x541: 0x6984ec9b7f51f7fc, - // Block 0x16, offset 0x580 - 0x5bf: 0x3c02ea92fb168559, - // Block 0x17, offset 0x5c0 - 0x5c0: 0x1badfe42e7629494, 0x5c1: 0x6dc4a554005f7645, - // Block 0x18, offset 0x600 - 0x63f: 0x3bb2ed2a72748f4b, - // Block 0x19, offset 0x640 - 0x640: 0x291354cd6767ec10, 0x641: 0x2c3a4715e3c070d6, - // Block 0x1a, offset 0x680 - 0x6bf: 0x352711cfb7236418, - // Block 0x1b, offset 0x6c0 - 0x6c0: 0x3a59d34fb8bceda, 0x6c1: 0x5e90d8ebedd64fa1, - // Block 0x1c, offset 0x700 - 0x73f: 0x7191a77b28d23110, - // Block 0x1d, offset 0x740 - 0x740: 0x4ca7f0c1623423d8, 0x741: 0x4f7156d996e2d0de, - // Block 0x1e, offset 0x780 - // Block 0x1f, offset 0x7c0 -} - -// multiIndex: 29 blocks, 1856 entries, 1856 bytes -// Block 0 is the zero block. -var multiIndex = [1856]uint8{ - // Block 0x0, offset 0x0 - // Block 0x1, offset 0x40 - // Block 0x2, offset 0x80 - // Block 0x3, offset 0xc0 - 0xc2: 0x01, 0xc3: 0x02, 0xc4: 0x03, 0xc7: 0x04, - 0xc8: 0x05, 0xcf: 0x06, - 0xd0: 0x07, - 0xdf: 0x08, - 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05, 0xe4: 0x06, 0xe7: 0x07, - 0xe8: 0x08, 0xef: 0x09, - 0xf0: 0x0e, 0xf1: 0x11, 0xf2: 0x13, 0xf3: 0x15, 0xf4: 0x17, - // Block 0x4, offset 0x100 - 0x120: 0x09, - 0x13f: 0x0a, - // Block 0x5, offset 0x140 - 0x140: 0x0b, - 0x17f: 0x0c, - // Block 0x6, offset 0x180 - 0x180: 0x0d, - // Block 0x7, offset 0x1c0 - 0x1ff: 0x0e, - // Block 0x8, offset 0x200 - 0x200: 0x0f, - // Block 0x9, offset 0x240 - 0x27f: 0x10, - // Block 0xa, offset 0x280 - 0x280: 0x11, - // Block 0xb, offset 0x2c0 - 0x2ff: 0x12, - // Block 0xc, offset 0x300 - 0x300: 0x13, - // Block 0xd, offset 0x340 - 0x37f: 0x14, - // Block 0xe, offset 0x380 - 0x380: 0x15, - // Block 0xf, offset 0x3c0 - 0x3ff: 0x16, - // Block 0x10, offset 0x400 - 0x410: 0x0a, - 0x41f: 0x0b, - 0x420: 0x0c, - 0x43f: 0x0d, - // Block 0x11, offset 0x440 - 0x440: 0x17, - // Block 0x12, offset 0x480 - 0x4bf: 0x18, - // Block 0x13, offset 0x4c0 - 0x4c0: 0x0f, - 0x4ff: 0x10, - // Block 0x14, offset 0x500 - 0x500: 0x19, - // Block 0x15, offset 0x540 - 0x540: 0x12, - // Block 0x16, offset 0x580 - 0x5bf: 0x1a, - // Block 0x17, offset 0x5c0 - 0x5ff: 0x14, - // Block 0x18, offset 0x600 - 0x600: 0x1b, - // Block 0x19, offset 0x640 - 0x640: 0x16, - // Block 0x1a, offset 0x680 - // Block 0x1b, offset 0x6c0 - 0x6c2: 0x01, 0x6c3: 0x02, 0x6c4: 0x03, 0x6c7: 0x04, - 0x6c8: 0x05, 0x6cf: 0x06, - 0x6d0: 0x07, - 0x6df: 0x08, - 0x6e0: 0x02, 0x6e1: 0x03, 0x6e2: 0x04, 0x6e3: 0x05, 0x6e4: 0x06, 0x6e7: 0x07, - 0x6e8: 0x08, 0x6ef: 0x09, - // Block 0x1c, offset 0x700 - 0x730: 0x0e, 0x731: 0x11, 0x732: 0x13, 0x733: 0x15, 0x734: 0x17, -} diff --git a/vendor/golang.org/x/text/internal/triegen/example_compact_test.go b/vendor/golang.org/x/text/internal/triegen/example_compact_test.go deleted file mode 100644 index 7cf604ca47..0000000000 --- a/vendor/golang.org/x/text/internal/triegen/example_compact_test.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2014 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 triegen_test - -import ( - "fmt" - "io" - "io/ioutil" - - "golang.org/x/text/internal/triegen" -) - -func ExampleCompacter() { - t := triegen.NewTrie("root") - for r := rune(0); r < 10000; r += 64 { - t.Insert(r, 0x9015BADA55^uint64(r)) - } - sz, _ := t.Gen(ioutil.Discard) - - fmt.Printf("Size normal: %5d\n", sz) - - var c myCompacter - sz, _ = t.Gen(ioutil.Discard, triegen.Compact(&c)) - - fmt.Printf("Size compacted: %5d\n", sz) - - // Output: - // Size normal: 81344 - // Size compacted: 3224 -} - -// A myCompacter accepts a block if only the first value is given. -type myCompacter []uint64 - -func (c *myCompacter) Size(values []uint64) (sz int, ok bool) { - for _, v := range values[1:] { - if v != 0 { - return 0, false - } - } - return 8, true // the size of a uint64 -} - -func (c *myCompacter) Store(v []uint64) uint32 { - x := uint32(len(*c)) - *c = append(*c, v[0]) - return x -} - -func (c *myCompacter) Print(w io.Writer) error { - fmt.Fprintln(w, "var firstValue = []uint64{") - for _, v := range *c { - fmt.Fprintf(w, "\t%#x,\n", v) - } - fmt.Fprintln(w, "}") - return nil -} - -func (c *myCompacter) Handler() string { - return "getFirstValue" - - // Where getFirstValue is included along with the generated code: - // func getFirstValue(n uint32, b byte) uint64 { - // if b == 0x80 { // the first continuation byte - // return firstValue[n] - // } - // return 0 - // } -} diff --git a/vendor/golang.org/x/text/internal/triegen/example_test.go b/vendor/golang.org/x/text/internal/triegen/example_test.go deleted file mode 100644 index 557a152e70..0000000000 --- a/vendor/golang.org/x/text/internal/triegen/example_test.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2014 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 triegen_test - -import ( - "fmt" - "io/ioutil" - "math/rand" - "unicode" - - "golang.org/x/text/internal/triegen" -) - -const seed = 0x12345 - -var genWriter = ioutil.Discard - -func randomRunes() map[rune]uint8 { - rnd := rand.New(rand.NewSource(seed)) - m := map[rune]uint8{} - for len(m) < 100 { - // Only set our random rune if it is a valid Unicode code point. - if r := rune(rnd.Int31n(unicode.MaxRune + 1)); []rune(string(r))[0] == r { - m[r] = 1 - } - } - return m -} - -// Example_build shows how to build a simple trie. It assigns the value 1 to -// 100 random runes generated by randomRunes. -func Example_build() { - t := triegen.NewTrie("rand") - - for r, _ := range randomRunes() { - t.Insert(r, 1) - } - sz, err := t.Gen(genWriter) - - fmt.Printf("Trie size: %d bytes\n", sz) - fmt.Printf("Error: %v\n", err) - - // Output: - // Trie size: 9280 bytes - // Error: <nil> -} - -// Example_lookup demonstrates how to use the trie generated by Example_build. -func Example_lookup() { - trie := newRandTrie(0) - - // The same set of runes used by Example_build. - runes := randomRunes() - - // Verify the right value is returned for all runes. - for r := rune(0); r <= unicode.MaxRune; r++ { - // Note that the return type of lookup is uint8. - if v, _ := trie.lookupString(string(r)); v != runes[r] { - fmt.Println("FAILURE") - return - } - } - fmt.Println("SUCCESS") - - // Output: - // SUCCESS -} - -// runeValues generates some random values for a set of interesting runes. -func runeValues() map[rune]uint64 { - rnd := rand.New(rand.NewSource(seed)) - m := map[rune]uint64{} - for p := 4; p <= unicode.MaxRune; p <<= 1 { - for d := -1; d <= 1; d++ { - m[rune(p+d)] = uint64(rnd.Int63()) - } - } - return m -} - -// ExampleGen_build demonstrates the creation of multiple tries sharing common -// blocks. ExampleGen_lookup demonstrates how to use the generated tries. -func ExampleGen_build() { - var tries []*triegen.Trie - - rv := runeValues() - for _, c := range []struct { - include func(rune) bool - name string - }{ - {func(r rune) bool { return true }, "all"}, - {func(r rune) bool { return r < 0x80 }, "ASCII only"}, - {func(r rune) bool { return r < 0x80 }, "ASCII only 2"}, - {func(r rune) bool { return r <= 0xFFFF }, "BMP only"}, - {func(r rune) bool { return r > 0xFFFF }, "No BMP"}, - } { - t := triegen.NewTrie(c.name) - tries = append(tries, t) - - for r, v := range rv { - if c.include(r) { - t.Insert(r, v) - } - } - } - sz, err := triegen.Gen(genWriter, "multi", tries) - - fmt.Printf("Trie size: %d bytes\n", sz) - fmt.Printf("Error: %v\n", err) - - // Output: - // Trie size: 18250 bytes - // Error: <nil> -} - -// ExampleGen_lookup shows how to look up values in the trie generated by -// ExampleGen_build. -func ExampleGen_lookup() { - rv := runeValues() - for i, include := range []func(rune) bool{ - func(r rune) bool { return true }, // all - func(r rune) bool { return r < 0x80 }, // ASCII only - func(r rune) bool { return r < 0x80 }, // ASCII only 2 - func(r rune) bool { return r <= 0xFFFF }, // BMP only - func(r rune) bool { return r > 0xFFFF }, // No BMP - } { - t := newMultiTrie(i) - - for r := rune(0); r <= unicode.MaxRune; r++ { - x := uint64(0) - if include(r) { - x = rv[r] - } - // As we convert from a valid rune, we know it is safe to use - // lookupStringUnsafe. - if v := t.lookupStringUnsafe(string(r)); x != v { - fmt.Println("FAILURE") - return - } - } - } - fmt.Println("SUCCESS") - - // Output: - // SUCCESS -} diff --git a/vendor/golang.org/x/text/internal/triegen/gen_test.go b/vendor/golang.org/x/text/internal/triegen/gen_test.go deleted file mode 100644 index 831627d7a0..0000000000 --- a/vendor/golang.org/x/text/internal/triegen/gen_test.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2014 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 generate - -package triegen_test - -// The code in this file generates captures and writes the tries generated in -// the examples to data_test.go. To invoke it, run: -// go test -tags=generate -// -// Making the generation code a "test" allows us to link in the necessary test -// code. - -import ( - "log" - "os" - "os/exec" -) - -func init() { - const tmpfile = "tmpout" - const dstfile = "data_test.go" - - f, err := os.Create(tmpfile) - if err != nil { - log.Fatalf("Could not create output file: %v", err) - } - defer os.Remove(tmpfile) - defer f.Close() - - // We exit before this function returns, regardless of success or failure, - // so there's no need to save (and later restore) the existing genWriter - // value. - genWriter = f - - f.Write([]byte(header)) - - Example_build() - ExampleGen_build() - - if err := exec.Command("gofmt", "-w", tmpfile).Run(); err != nil { - log.Fatal(err) - } - os.Remove(dstfile) - os.Rename(tmpfile, dstfile) - - os.Exit(0) -} - -const header = `// This file is generated with "go test -tags generate". DO NOT EDIT! -// +build !generate - -package triegen_test -` - -// Stubs for generated tries. These are needed as we exclude data_test.go if -// the generate flag is set. This will clearly make the tests fail, but that -// is okay. It allows us to bootstrap. - -type trie struct{} - -func (t *trie) lookupString(string) (uint8, int) { return 0, 1 } -func (t *trie) lookupStringUnsafe(string) uint64 { return 0 } - -func newRandTrie(i int) *trie { return &trie{} } -func newMultiTrie(i int) *trie { return &trie{} } diff --git a/vendor/golang.org/x/text/internal/ucd/example_test.go b/vendor/golang.org/x/text/internal/ucd/example_test.go deleted file mode 100644 index 338a50d1c9..0000000000 --- a/vendor/golang.org/x/text/internal/ucd/example_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2014 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 ucd_test - -import ( - "fmt" - "strings" - - "golang.org/x/text/internal/ucd" -) - -func Example() { - // Read rune-by-rune from UnicodeData. - var count int - p := ucd.New(strings.NewReader(unicodeData)) - for p.Next() { - count++ - if lower := p.Runes(ucd.SimpleLowercaseMapping); lower != nil { - fmt.Printf("lower(%U) -> %U\n", p.Rune(0), lower[0]) - } - } - if err := p.Err(); err != nil { - fmt.Println(err) - } - fmt.Println("Number of runes visited:", count) - - // Read raw ranges from Scripts. - p = ucd.New(strings.NewReader(scripts), ucd.KeepRanges) - for p.Next() { - start, end := p.Range(0) - fmt.Printf("%04X..%04X: %s\n", start, end, p.String(1)) - } - if err := p.Err(); err != nil { - fmt.Println(err) - } - - // Output: - // lower(U+00C0) -> U+00E0 - // lower(U+00C1) -> U+00E1 - // lower(U+00C2) -> U+00E2 - // lower(U+00C3) -> U+00E3 - // lower(U+00C4) -> U+00E4 - // Number of runes visited: 6594 - // 0000..001F: Common - // 0020..0020: Common - // 0021..0023: Common - // 0024..0024: Common -} - -// Excerpt from UnicodeData.txt -const unicodeData = ` -00B9;SUPERSCRIPT ONE;No;0;EN;<super> 0031;;1;1;N;SUPERSCRIPT DIGIT ONE;;;; -00BA;MASCULINE ORDINAL INDICATOR;Lo;0;L;<super> 006F;;;;N;;;;; -00BB;RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK;Pf;0;ON;;;;;Y;RIGHT POINTING GUILLEMET;;;; -00BC;VULGAR FRACTION ONE QUARTER;No;0;ON;<fraction> 0031 2044 0034;;;1/4;N;FRACTION ONE QUARTER;;;; -00BD;VULGAR FRACTION ONE HALF;No;0;ON;<fraction> 0031 2044 0032;;;1/2;N;FRACTION ONE HALF;;;; -00BE;VULGAR FRACTION THREE QUARTERS;No;0;ON;<fraction> 0033 2044 0034;;;3/4;N;FRACTION THREE QUARTERS;;;; -00BF;INVERTED QUESTION MARK;Po;0;ON;;;;;N;;;;; -00C0;LATIN CAPITAL LETTER A WITH GRAVE;Lu;0;L;0041 0300;;;;N;LATIN CAPITAL LETTER A GRAVE;;;00E0; -00C1;LATIN CAPITAL LETTER A WITH ACUTE;Lu;0;L;0041 0301;;;;N;LATIN CAPITAL LETTER A ACUTE;;;00E1; -00C2;LATIN CAPITAL LETTER A WITH CIRCUMFLEX;Lu;0;L;0041 0302;;;;N;LATIN CAPITAL LETTER A CIRCUMFLEX;;;00E2; -00C3;LATIN CAPITAL LETTER A WITH TILDE;Lu;0;L;0041 0303;;;;N;LATIN CAPITAL LETTER A TILDE;;;00E3; -00C4;LATIN CAPITAL LETTER A WITH DIAERESIS;Lu;0;L;0041 0308;;;;N;LATIN CAPITAL LETTER A DIAERESIS;;;00E4; - -# A legacy rune range. -3400;<CJK Ideograph Extension A, First>;Lo;0;L;;;;;N;;;;; -4DB5;<CJK Ideograph Extension A, Last>;Lo;0;L;;;;;N;;;;; -` - -// Excerpt from Scripts.txt -const scripts = ` -# Property: Script -# ================================================ - -0000..001F ; Common # Cc [32] <control-0000>..<control-001F> -0020 ; Common # Zs SPACE -0021..0023 ; Common # Po [3] EXCLAMATION MARK..NUMBER SIGN -0024 ; Common # Sc DOLLAR SIGN -` diff --git a/vendor/golang.org/x/text/internal/ucd/ucd_test.go b/vendor/golang.org/x/text/internal/ucd/ucd_test.go deleted file mode 100644 index 11a6542e41..0000000000 --- a/vendor/golang.org/x/text/internal/ucd/ucd_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package ucd - -import ( - "strings" - "testing" -) - -const file = ` -# Comments should be skipped -# rune; bool; uint; int; float; runes; # Y -0..0005; Y; 0; 2; -5.25 ; 0 1 2 3 4 5; -6..0007; Yes ; 6; 1; -4.25 ; 0006 0007; -8; T ; 8 ; 0 ;-3.25 ;;# T -9; True ;9 ; -1;-2.25 ; 0009; - -# more comments to be ignored -@Part0 - -A; N; 10 ; -2; -1.25; ;# N -B; No; 11 ; -3; -0.25; -C; False;12; -4; 0.75; -D; ;13;-5;1.75; - -@Part1 # Another part. -# We test part comments get removed by not commenting the the next line. -E..10FFFF; F; 14 ; -6; 2.75; -` - -var want = []struct { - start, end rune -}{ - {0x00, 0x05}, - {0x06, 0x07}, - {0x08, 0x08}, - {0x09, 0x09}, - {0x0A, 0x0A}, - {0x0B, 0x0B}, - {0x0C, 0x0C}, - {0x0D, 0x0D}, - {0x0E, 0x10FFFF}, -} - -func TestGetters(t *testing.T) { - parts := [][2]string{ - {"Part0", ""}, - {"Part1", "Another part."}, - } - handler := func(p *Parser) { - if len(parts) == 0 { - t.Error("Part handler invoked too many times.") - return - } - want := parts[0] - parts = parts[1:] - if got0, got1 := p.String(0), p.Comment(); got0 != want[0] || got1 != want[1] { - t.Errorf(`part: got %q, %q; want %q"`, got0, got1, want) - } - } - - p := New(strings.NewReader(file), KeepRanges, Part(handler)) - for i := 0; p.Next(); i++ { - start, end := p.Range(0) - w := want[i] - if start != w.start || end != w.end { - t.Fatalf("%d:Range(0); got %#x..%#x; want %#x..%#x", i, start, end, w.start, w.end) - } - if w.start == w.end && p.Rune(0) != w.start { - t.Errorf("%d:Range(0).start: got %U; want %U", i, p.Rune(0), w.start) - } - if got, want := p.Bool(1), w.start <= 9; got != want { - t.Errorf("%d:Bool(1): got %v; want %v", i, got, want) - } - if got := p.Rune(4); got != 0 || p.Err() == nil { - t.Errorf("%d:Rune(%q): got no error; want error", i, p.String(1)) - } - p.err = nil - if got := p.Uint(2); rune(got) != start { - t.Errorf("%d:Uint(2): got %v; want %v", i, got, start) - } - if got, want := p.Int(3), 2-i; got != want { - t.Errorf("%d:Int(3): got %v; want %v", i, got, want) - } - if got, want := p.Float(4), -5.25+float64(i); got != want { - t.Errorf("%d:Int(3): got %v; want %v", i, got, want) - } - if got := p.Runes(5); got == nil { - if p.String(5) != "" { - t.Errorf("%d:Runes(5): expected non-empty list", i) - } - } else { - if got[0] != start || got[len(got)-1] != end { - t.Errorf("%d:Runes(5): got %#x; want %#x..%#x", i, got, start, end) - } - } - if got := p.Comment(); got != "" && got != p.String(1) { - t.Errorf("%d:Comment(): got %v; want %v", i, got, p.String(1)) - } - } - if err := p.Err(); err != nil { - t.Errorf("Parser error: %v", err) - } - if len(parts) != 0 { - t.Errorf("expected %d more invocations of part handler", len(parts)) - } -} diff --git a/vendor/golang.org/x/text/language/coverage_test.go b/vendor/golang.org/x/text/language/coverage_test.go deleted file mode 100644 index 8e08e5ca4c..0000000000 --- a/vendor/golang.org/x/text/language/coverage_test.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2014 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 language - -import ( - "fmt" - "reflect" - "testing" -) - -func TestSupported(t *testing.T) { - // To prove the results are correct for a type, we test that the number of - // results is identical to the number of results on record, that all results - // are distinct and that all results are valid. - tests := map[string]int{ - "BaseLanguages": numLanguages, - "Scripts": numScripts, - "Regions": numRegions, - "Tags": 0, - } - sup := reflect.ValueOf(Supported) - for name, num := range tests { - v := sup.MethodByName(name).Call(nil)[0] - if n := v.Len(); n != num { - t.Errorf("len(%s()) was %d; want %d", name, n, num) - } - dup := make(map[string]bool) - for i := 0; i < v.Len(); i++ { - x := v.Index(i).Interface() - // An invalid value will either cause a crash or result in a - // duplicate when passed to Sprint. - s := fmt.Sprint(x) - if dup[s] { - t.Errorf("%s: duplicate entry %q", name, s) - } - dup[s] = true - } - if len(dup) != v.Len() { - t.Errorf("%s: # unique entries was %d; want %d", name, len(dup), v.Len()) - } - } -} - -func TestNewCoverage(t *testing.T) { - bases := []Base{Base{0}, Base{3}, Base{7}} - scripts := []Script{Script{11}, Script{17}, Script{23}} - regions := []Region{Region{101}, Region{103}, Region{107}} - tags := []Tag{Make("pt"), Make("en"), Make("en-GB"), Make("en-US"), Make("pt-PT")} - fbases := func() []Base { return bases } - fscripts := func() []Script { return scripts } - fregions := func() []Region { return regions } - ftags := func() []Tag { return tags } - - tests := []struct { - desc string - list []interface{} - bases []Base - scripts []Script - regions []Region - tags []Tag - }{ - { - desc: "empty", - }, - { - desc: "bases", - list: []interface{}{bases}, - bases: bases, - }, - { - desc: "scripts", - list: []interface{}{scripts}, - scripts: scripts, - }, - { - desc: "regions", - list: []interface{}{regions}, - regions: regions, - }, - { - desc: "bases derives from tags", - list: []interface{}{tags}, - bases: []Base{Base{_en}, Base{_pt}}, - tags: tags, - }, - { - desc: "tags and bases", - list: []interface{}{tags, bases}, - bases: bases, - tags: tags, - }, - { - desc: "fully specified", - list: []interface{}{tags, bases, scripts, regions}, - bases: bases, - scripts: scripts, - regions: regions, - tags: tags, - }, - { - desc: "bases func", - list: []interface{}{fbases}, - bases: bases, - }, - { - desc: "scripts func", - list: []interface{}{fscripts}, - scripts: scripts, - }, - { - desc: "regions func", - list: []interface{}{fregions}, - regions: regions, - }, - { - desc: "tags func", - list: []interface{}{ftags}, - bases: []Base{Base{_en}, Base{_pt}}, - tags: tags, - }, - { - desc: "tags and bases", - list: []interface{}{ftags, fbases}, - bases: bases, - tags: tags, - }, - { - desc: "fully specified", - list: []interface{}{ftags, fbases, fscripts, fregions}, - bases: bases, - scripts: scripts, - regions: regions, - tags: tags, - }, - } - - for i, tt := range tests { - l := NewCoverage(tt.list...) - if a := l.BaseLanguages(); !reflect.DeepEqual(a, tt.bases) { - t.Errorf("%d:%s: BaseLanguages was %v; want %v", i, tt.desc, a, tt.bases) - } - if a := l.Scripts(); !reflect.DeepEqual(a, tt.scripts) { - t.Errorf("%d:%s: Scripts was %v; want %v", i, tt.desc, a, tt.scripts) - } - if a := l.Regions(); !reflect.DeepEqual(a, tt.regions) { - t.Errorf("%d:%s: Regions was %v; want %v", i, tt.desc, a, tt.regions) - } - if a := l.Tags(); !reflect.DeepEqual(a, tt.tags) { - t.Errorf("%d:%s: Tags was %v; want %v", i, tt.desc, a, tt.tags) - } - } -} diff --git a/vendor/golang.org/x/text/language/examples_test.go b/vendor/golang.org/x/text/language/examples_test.go deleted file mode 100644 index d5e8176dce..0000000000 --- a/vendor/golang.org/x/text/language/examples_test.go +++ /dev/null @@ -1,413 +0,0 @@ -// Copyright 2013 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 language_test - -import ( - "fmt" - "net/http" - - "golang.org/x/text/language" -) - -func ExampleCanonType() { - p := func(id string) { - fmt.Printf("Default(%s) -> %s\n", id, language.Make(id)) - fmt.Printf("BCP47(%s) -> %s\n", id, language.BCP47.Make(id)) - fmt.Printf("Macro(%s) -> %s\n", id, language.Macro.Make(id)) - fmt.Printf("All(%s) -> %s\n", id, language.All.Make(id)) - } - p("en-Latn") - p("sh") - p("zh-cmn") - p("bjd") - p("iw-Latn-fonipa-u-cu-usd") - // Output: - // Default(en-Latn) -> en-Latn - // BCP47(en-Latn) -> en - // Macro(en-Latn) -> en-Latn - // All(en-Latn) -> en - // Default(sh) -> sr-Latn - // BCP47(sh) -> sh - // Macro(sh) -> sh - // All(sh) -> sr-Latn - // Default(zh-cmn) -> cmn - // BCP47(zh-cmn) -> cmn - // Macro(zh-cmn) -> zh - // All(zh-cmn) -> zh - // Default(bjd) -> drl - // BCP47(bjd) -> drl - // Macro(bjd) -> bjd - // All(bjd) -> drl - // Default(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd - // BCP47(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd - // Macro(iw-Latn-fonipa-u-cu-usd) -> iw-Latn-fonipa-u-cu-usd - // All(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd -} - -func ExampleTag_Base() { - fmt.Println(language.Make("und").Base()) - fmt.Println(language.Make("und-US").Base()) - fmt.Println(language.Make("und-NL").Base()) - fmt.Println(language.Make("und-419").Base()) // Latin America - fmt.Println(language.Make("und-ZZ").Base()) - // Output: - // en Low - // en High - // nl High - // es Low - // en Low -} - -func ExampleTag_Script() { - en := language.Make("en") - sr := language.Make("sr") - sr_Latn := language.Make("sr_Latn") - fmt.Println(en.Script()) - fmt.Println(sr.Script()) - // Was a script explicitly specified? - _, c := sr.Script() - fmt.Println(c == language.Exact) - _, c = sr_Latn.Script() - fmt.Println(c == language.Exact) - // Output: - // Latn High - // Cyrl Low - // false - // true -} - -func ExampleTag_Region() { - ru := language.Make("ru") - en := language.Make("en") - fmt.Println(ru.Region()) - fmt.Println(en.Region()) - // Output: - // RU Low - // US Low -} - -func ExampleRegion_TLD() { - us := language.MustParseRegion("US") - gb := language.MustParseRegion("GB") - uk := language.MustParseRegion("UK") - bu := language.MustParseRegion("BU") - - fmt.Println(us.TLD()) - fmt.Println(gb.TLD()) - fmt.Println(uk.TLD()) - fmt.Println(bu.TLD()) - - fmt.Println(us.Canonicalize().TLD()) - fmt.Println(gb.Canonicalize().TLD()) - fmt.Println(uk.Canonicalize().TLD()) - fmt.Println(bu.Canonicalize().TLD()) - // Output: - // US <nil> - // UK <nil> - // UK <nil> - // ZZ language: region is not a valid ccTLD - // US <nil> - // UK <nil> - // UK <nil> - // MM <nil> -} - -func ExampleCompose() { - nl, _ := language.ParseBase("nl") - us, _ := language.ParseRegion("US") - de := language.Make("de-1901-u-co-phonebk") - jp := language.Make("ja-JP") - fi := language.Make("fi-x-ing") - - u, _ := language.ParseExtension("u-nu-arabic") - x, _ := language.ParseExtension("x-piglatin") - - // Combine a base language and region. - fmt.Println(language.Compose(nl, us)) - // Combine a base language and extension. - fmt.Println(language.Compose(nl, x)) - // Replace the region. - fmt.Println(language.Compose(jp, us)) - // Combine several tags. - fmt.Println(language.Compose(us, nl, u)) - - // Replace the base language of a tag. - fmt.Println(language.Compose(de, nl)) - fmt.Println(language.Compose(de, nl, u)) - // Remove the base language. - fmt.Println(language.Compose(de, language.Base{})) - // Remove all variants. - fmt.Println(language.Compose(de, []language.Variant{})) - // Remove all extensions. - fmt.Println(language.Compose(de, []language.Extension{})) - fmt.Println(language.Compose(fi, []language.Extension{})) - // Remove all variants and extensions. - fmt.Println(language.Compose(de.Raw())) - - // An error is gobbled or returned if non-nil. - fmt.Println(language.Compose(language.ParseRegion("ZA"))) - fmt.Println(language.Compose(language.ParseRegion("HH"))) - - // Compose uses the same Default canonicalization as Make. - fmt.Println(language.Compose(language.Raw.Parse("en-Latn-UK"))) - - // Call compose on a different CanonType for different results. - fmt.Println(language.All.Compose(language.Raw.Parse("en-Latn-UK"))) - - // Output: - // nl-US <nil> - // nl-x-piglatin <nil> - // ja-US <nil> - // nl-US-u-nu-arabic <nil> - // nl-1901-u-co-phonebk <nil> - // nl-1901-u-nu-arabic <nil> - // und-1901-u-co-phonebk <nil> - // de-u-co-phonebk <nil> - // de-1901 <nil> - // fi <nil> - // de <nil> - // und-ZA <nil> - // und language: subtag "HH" is well-formed but unknown - // en-Latn-GB <nil> - // en-GB <nil> -} - -func ExampleParse_errors() { - for _, s := range []string{"Foo", "Bar", "Foobar"} { - _, err := language.Parse(s) - if err != nil { - if inv, ok := err.(language.ValueError); ok { - fmt.Println(inv.Subtag()) - } else { - fmt.Println(s) - } - } - } - for _, s := range []string{"en", "aa-Uuuu", "AC", "ac-u"} { - _, err := language.Parse(s) - switch e := err.(type) { - case language.ValueError: - fmt.Printf("%s: culprit %q\n", s, e.Subtag()) - case nil: - // No error. - default: - // A syntax error. - fmt.Printf("%s: ill-formed\n", s) - } - } - // Output: - // foo - // Foobar - // aa-Uuuu: culprit "Uuuu" - // AC: culprit "ac" - // ac-u: ill-formed -} - -func ExampleParent() { - p := func(tag string) { - fmt.Printf("parent(%v): %v\n", tag, language.Make(tag).Parent()) - } - p("zh-CN") - - // Australian English inherits from World English. - p("en-AU") - - // If the tag has a different maximized script from its parent, a tag with - // this maximized script is inserted. This allows different language tags - // which have the same base language and script in common to inherit from - // a common set of settings. - p("zh-HK") - - // If the maximized script of the parent is not identical, CLDR will skip - // inheriting from it, as it means there will not be many entries in common - // and inheriting from it is nonsensical. - p("zh-Hant") - - // The parent of a tag with variants and extensions is the tag with all - // variants and extensions removed. - p("de-1994-u-co-phonebk") - - // Remove default script. - p("de-Latn-LU") - - // Output: - // parent(zh-CN): zh - // parent(en-AU): en-001 - // parent(zh-HK): zh-Hant - // parent(zh-Hant): und - // parent(de-1994-u-co-phonebk): de - // parent(de-Latn-LU): de -} - -// ExampleMatcher_bestMatch gives some examples of getting the best match of -// a set of tags to any of the tags of given set. -func ExampleMatcher() { - // This is the set of tags from which we want to pick the best match. These - // can be, for example, the supported languages for some package. - tags := []language.Tag{ - language.English, - language.BritishEnglish, - language.French, - language.Afrikaans, - language.BrazilianPortuguese, - language.EuropeanPortuguese, - language.Croatian, - language.SimplifiedChinese, - language.Raw.Make("iw-IL"), - language.Raw.Make("iw"), - language.Raw.Make("he"), - } - m := language.NewMatcher(tags) - - // A simple match. - fmt.Println(m.Match(language.Make("fr"))) - - // Australian English is closer to British than American English. - fmt.Println(m.Match(language.Make("en-AU"))) - - // Default to the first tag passed to the Matcher if there is no match. - fmt.Println(m.Match(language.Make("ar"))) - - // Get the default tag. - fmt.Println(m.Match()) - - fmt.Println("----") - - // Someone specifying sr-Latn is probably fine with getting Croatian. - fmt.Println(m.Match(language.Make("sr-Latn"))) - - // We match SimplifiedChinese, but with Low confidence. - fmt.Println(m.Match(language.TraditionalChinese)) - - // Serbian in Latin script is a closer match to Croatian than Traditional - // Chinese to Simplified Chinese. - fmt.Println(m.Match(language.TraditionalChinese, language.Make("sr-Latn"))) - - fmt.Println("----") - - // In case a multiple variants of a language are available, the most spoken - // variant is typically returned. - fmt.Println(m.Match(language.Portuguese)) - - // Pick the first value passed to Match in case of a tie. - fmt.Println(m.Match(language.Dutch, language.Make("fr-BE"), language.Make("af-NA"))) - fmt.Println(m.Match(language.Dutch, language.Make("af-NA"), language.Make("fr-BE"))) - - fmt.Println("----") - - // If a Matcher is initialized with a language and it's deprecated version, - // it will distinguish between them. - fmt.Println(m.Match(language.Raw.Make("iw"))) - - // However, for non-exact matches, it will treat deprecated versions as - // equivalent and consider other factors first. - fmt.Println(m.Match(language.Raw.Make("he-IL"))) - - fmt.Println("----") - - // User settings passed to the Unicode extension are ignored for matching - // and preserved in the returned tag. - fmt.Println(m.Match(language.Make("de-u-co-phonebk"), language.Make("fr-u-cu-frf"))) - - // Even if the matching language is different. - fmt.Println(m.Match(language.Make("de-u-co-phonebk"), language.Make("br-u-cu-frf"))) - - // If there is no matching language, the options of the first preferred tag are used. - fmt.Println(m.Match(language.Make("de-u-co-phonebk"))) - - // Output: - // fr 2 Exact - // en-GB 1 High - // en 0 No - // en 0 No - // ---- - // hr 6 High - // zh-Hans 7 Low - // hr 6 High - // ---- - // pt-BR 4 High - // fr 2 High - // af 3 High - // ---- - // iw 9 Exact - // he 10 Exact - // ---- - // fr-u-cu-frf 2 Exact - // fr-u-cu-frf 2 High - // en-u-co-phonebk 0 No - - // TODO: "he" should be "he-u-rg-IL High" -} - -func ExampleMatchStrings() { - // languages supported by this service: - matcher := language.NewMatcher([]language.Tag{ - language.English, language.Dutch, language.German, - }) - - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - lang, _ := r.Cookie("lang") - tag, _ := language.MatchStrings(matcher, lang.String(), r.Header.Get("Accept-Language")) - - fmt.Println("User language:", tag) - }) -} - -func ExampleComprehends() { - // Various levels of comprehensibility. - fmt.Println(language.Comprehends(language.English, language.English)) - fmt.Println(language.Comprehends(language.AmericanEnglish, language.BritishEnglish)) - - // An explicit Und results in no match. - fmt.Println(language.Comprehends(language.English, language.Und)) - - fmt.Println("----") - - // There is usually no mutual comprehensibility between different scripts. - fmt.Println(language.Comprehends(language.Make("en-Dsrt"), language.English)) - - // One exception is for Traditional versus Simplified Chinese, albeit with - // a low confidence. - fmt.Println(language.Comprehends(language.TraditionalChinese, language.SimplifiedChinese)) - - fmt.Println("----") - - // A Swiss German speaker will often understand High German. - fmt.Println(language.Comprehends(language.Make("gsw"), language.Make("de"))) - - // The converse is not generally the case. - fmt.Println(language.Comprehends(language.Make("de"), language.Make("gsw"))) - - // Output: - // Exact - // High - // No - // ---- - // No - // Low - // ---- - // High - // No -} - -func ExampleTag_values() { - us := language.MustParseRegion("US") - en := language.MustParseBase("en") - - lang, _, region := language.AmericanEnglish.Raw() - fmt.Println(lang == en, region == us) - - lang, _, region = language.BritishEnglish.Raw() - fmt.Println(lang == en, region == us) - - // Tags can be compared for exact equivalence using '=='. - en_us, _ := language.Compose(en, us) - fmt.Println(en_us == language.AmericanEnglish) - - // Output: - // true true - // true false - // true -} diff --git a/vendor/golang.org/x/text/language/gen.go b/vendor/golang.org/x/text/language/gen.go index 7c260e5c27..302f1940aa 100644 --- a/vendor/golang.org/x/text/language/gen.go +++ b/vendor/golang.org/x/text/language/gen.go @@ -1497,8 +1497,14 @@ func (b *builder) writeMatchData() { if desired == supported && desired == "*_*_*" { continue } - if desired != supported { // (Weird but correct.) - log.Fatalf("not supported: desired=%q; supported=%q", desired, supported) + if desired != supported { + // This is now supported by CLDR, but only one case, which + // should already be covered by paradigm locales. For instance, + // test case "und, en, en-GU, en-IN, en-GB ; en-ZA ; en-GB" in + // testdata/CLDRLocaleMatcherTest.txt tests this. + if supported != "en_*_GB" { + log.Fatalf("not supported: desired=%q; supported=%q", desired, supported) + } continue } ri := regionIntelligibility{ diff --git a/vendor/golang.org/x/text/language/gen_index.go b/vendor/golang.org/x/text/language/gen_index.go index eef555cd3a..5ca9bccac5 100644 --- a/vendor/golang.org/x/text/language/gen_index.go +++ b/vendor/golang.org/x/text/language/gen_index.go @@ -49,7 +49,7 @@ func main() { defer func() { buf := &bytes.Buffer{} - if _, err = w.WriteGo(buf, "language"); err != nil { + if _, err = w.WriteGo(buf, "language", ""); err != nil { log.Fatalf("Error formatting file index.go: %v", err) } diff --git a/vendor/golang.org/x/text/language/httpexample_test.go b/vendor/golang.org/x/text/language/httpexample_test.go deleted file mode 100644 index 40d0663c8f..0000000000 --- a/vendor/golang.org/x/text/language/httpexample_test.go +++ /dev/null @@ -1,48 +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 language_test - -import ( - "fmt" - "net/http" - "strings" - - "golang.org/x/text/language" -) - -// matcher is a language.Matcher configured for all supported languages. -var matcher = language.NewMatcher([]language.Tag{ - language.BritishEnglish, - language.Norwegian, - language.German, -}) - -// handler is a http.HandlerFunc. -func handler(w http.ResponseWriter, r *http.Request) { - t, q, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language")) - // We ignore the error: the default language will be selected for t == nil. - tag, _, _ := matcher.Match(t...) - fmt.Printf("%5v (t: %6v; q: %3v; err: %v)\n", tag, t, q, err) -} - -func ExampleParseAcceptLanguage() { - for _, al := range []string{ - "nn;q=0.3, en-us;q=0.8, en,", - "gsw, en;q=0.7, en-US;q=0.8", - "gsw, nl, da", - "invalid", - } { - // Create dummy request with Accept-Language set and pass it to handler. - r, _ := http.NewRequest("GET", "example.com", strings.NewReader("Hello")) - r.Header.Set("Accept-Language", al) - handler(nil, r) - } - - // Output: - // en-GB (t: [ en en-US nn]; q: [ 1 0.8 0.3]; err: <nil>) - // en-GB (t: [ gsw en-US en]; q: [ 1 0.8 0.7]; err: <nil>) - // de (t: [ gsw nl da]; q: [ 1 1 1]; err: <nil>) - // en-GB (t: []; q: []; err: language: tag is not well-formed) -} diff --git a/vendor/golang.org/x/text/language/index.go b/vendor/golang.org/x/text/language/index.go index 69ac557dc1..5311e5cbe4 100644 --- a/vendor/golang.org/x/text/language/index.go +++ b/vendor/golang.org/x/text/language/index.go @@ -4,11 +4,11 @@ package language // NumCompactTags is the number of common tags. The maximum tag is // NumCompactTags-1. -const NumCompactTags = 754 +const NumCompactTags = 768 var specialTags = []Tag{ // 2 elements 0: {lang: 0xd7, region: 0x6e, script: 0x0, pVariant: 0x5, pExt: 0xe, str: "ca-ES-valencia"}, - 1: {lang: 0x138, region: 0x135, script: 0x0, pVariant: 0x5, pExt: 0x5, str: "en-US-u-va-posix"}, + 1: {lang: 0x139, region: 0x135, script: 0x0, pVariant: 0x5, pExt: 0x5, str: "en-US-u-va-posix"}, } // Size: 72 bytes var coreTags = map[uint32]uint16{ @@ -59,10 +59,10 @@ var coreTags = map[uint32]uint16{ 0x04800000: 46, // ast 0x0480006e: 47, // ast-ES 0x05800000: 48, // az - 0x0581e000: 49, // az-Cyrl - 0x0581e032: 50, // az-Cyrl-AZ - 0x05855000: 51, // az-Latn - 0x05855032: 52, // az-Latn-AZ + 0x0581f000: 49, // az-Cyrl + 0x0581f032: 50, // az-Cyrl-AZ + 0x05857000: 51, // az-Latn + 0x05857032: 52, // az-Latn-AZ 0x05e00000: 53, // bas 0x05e00052: 54, // bas-CM 0x07100000: 55, // be @@ -87,683 +87,697 @@ var coreTags = map[uint32]uint16{ 0x0b500000: 74, // brx 0x0b500099: 75, // brx-IN 0x0b700000: 76, // bs - 0x0b71e000: 77, // bs-Cyrl - 0x0b71e033: 78, // bs-Cyrl-BA - 0x0b755000: 79, // bs-Latn - 0x0b755033: 80, // bs-Latn-BA + 0x0b71f000: 77, // bs-Cyrl + 0x0b71f033: 78, // bs-Cyrl-BA + 0x0b757000: 79, // bs-Latn + 0x0b757033: 80, // bs-Latn-BA 0x0d700000: 81, // ca 0x0d700022: 82, // ca-AD 0x0d70006e: 83, // ca-ES 0x0d700078: 84, // ca-FR 0x0d70009e: 85, // ca-IT - 0x0dc00000: 86, // ce - 0x0dc00106: 87, // ce-RU - 0x0df00000: 88, // cgg - 0x0df00131: 89, // cgg-UG - 0x0e500000: 90, // chr - 0x0e500135: 91, // chr-US - 0x0e900000: 92, // ckb - 0x0e90009b: 93, // ckb-IQ - 0x0e90009c: 94, // ckb-IR - 0x0f900000: 95, // cs - 0x0f90005e: 96, // cs-CZ - 0x0fd00000: 97, // cu - 0x0fd00106: 98, // cu-RU - 0x0ff00000: 99, // cy - 0x0ff0007b: 100, // cy-GB - 0x10000000: 101, // da - 0x10000063: 102, // da-DK - 0x10000082: 103, // da-GL - 0x10700000: 104, // dav - 0x107000a4: 105, // dav-KE - 0x10c00000: 106, // de - 0x10c0002e: 107, // de-AT - 0x10c00036: 108, // de-BE - 0x10c0004e: 109, // de-CH - 0x10c00060: 110, // de-DE - 0x10c0009e: 111, // de-IT - 0x10c000b2: 112, // de-LI - 0x10c000b7: 113, // de-LU - 0x11600000: 114, // dje - 0x116000d4: 115, // dje-NE - 0x11e00000: 116, // dsb - 0x11e00060: 117, // dsb-DE - 0x12300000: 118, // dua - 0x12300052: 119, // dua-CM - 0x12700000: 120, // dv - 0x12a00000: 121, // dyo - 0x12a00114: 122, // dyo-SN - 0x12c00000: 123, // dz - 0x12c00043: 124, // dz-BT - 0x12e00000: 125, // ebu - 0x12e000a4: 126, // ebu-KE - 0x12f00000: 127, // ee - 0x12f00080: 128, // ee-GH - 0x12f00122: 129, // ee-TG - 0x13500000: 130, // el - 0x1350005d: 131, // el-CY - 0x13500087: 132, // el-GR - 0x13800000: 133, // en - 0x13800001: 134, // en-001 - 0x1380001a: 135, // en-150 - 0x13800025: 136, // en-AG - 0x13800026: 137, // en-AI - 0x1380002d: 138, // en-AS - 0x1380002e: 139, // en-AT - 0x1380002f: 140, // en-AU - 0x13800034: 141, // en-BB - 0x13800036: 142, // en-BE - 0x1380003a: 143, // en-BI - 0x1380003d: 144, // en-BM - 0x13800042: 145, // en-BS - 0x13800046: 146, // en-BW - 0x13800048: 147, // en-BZ - 0x13800049: 148, // en-CA - 0x1380004a: 149, // en-CC - 0x1380004e: 150, // en-CH - 0x13800050: 151, // en-CK - 0x13800052: 152, // en-CM - 0x1380005c: 153, // en-CX - 0x1380005d: 154, // en-CY - 0x13800060: 155, // en-DE - 0x13800061: 156, // en-DG - 0x13800063: 157, // en-DK - 0x13800064: 158, // en-DM - 0x1380006d: 159, // en-ER - 0x13800072: 160, // en-FI - 0x13800073: 161, // en-FJ - 0x13800074: 162, // en-FK - 0x13800075: 163, // en-FM - 0x1380007b: 164, // en-GB - 0x1380007c: 165, // en-GD - 0x1380007f: 166, // en-GG - 0x13800080: 167, // en-GH - 0x13800081: 168, // en-GI - 0x13800083: 169, // en-GM - 0x1380008a: 170, // en-GU - 0x1380008c: 171, // en-GY - 0x1380008d: 172, // en-HK - 0x13800096: 173, // en-IE - 0x13800097: 174, // en-IL - 0x13800098: 175, // en-IM - 0x13800099: 176, // en-IN - 0x1380009a: 177, // en-IO - 0x1380009f: 178, // en-JE - 0x138000a0: 179, // en-JM - 0x138000a4: 180, // en-KE - 0x138000a7: 181, // en-KI - 0x138000a9: 182, // en-KN - 0x138000ad: 183, // en-KY - 0x138000b1: 184, // en-LC - 0x138000b4: 185, // en-LR - 0x138000b5: 186, // en-LS - 0x138000bf: 187, // en-MG - 0x138000c0: 188, // en-MH - 0x138000c6: 189, // en-MO - 0x138000c7: 190, // en-MP - 0x138000ca: 191, // en-MS - 0x138000cb: 192, // en-MT - 0x138000cc: 193, // en-MU - 0x138000ce: 194, // en-MW - 0x138000d0: 195, // en-MY - 0x138000d2: 196, // en-NA - 0x138000d5: 197, // en-NF - 0x138000d6: 198, // en-NG - 0x138000d9: 199, // en-NL - 0x138000dd: 200, // en-NR - 0x138000df: 201, // en-NU - 0x138000e0: 202, // en-NZ - 0x138000e6: 203, // en-PG - 0x138000e7: 204, // en-PH - 0x138000e8: 205, // en-PK - 0x138000eb: 206, // en-PN - 0x138000ec: 207, // en-PR - 0x138000f0: 208, // en-PW - 0x13800107: 209, // en-RW - 0x13800109: 210, // en-SB - 0x1380010a: 211, // en-SC - 0x1380010b: 212, // en-SD - 0x1380010c: 213, // en-SE - 0x1380010d: 214, // en-SG - 0x1380010e: 215, // en-SH - 0x1380010f: 216, // en-SI - 0x13800112: 217, // en-SL - 0x13800117: 218, // en-SS - 0x1380011b: 219, // en-SX - 0x1380011d: 220, // en-SZ - 0x1380011f: 221, // en-TC - 0x13800125: 222, // en-TK - 0x13800129: 223, // en-TO - 0x1380012c: 224, // en-TT - 0x1380012d: 225, // en-TV - 0x1380012f: 226, // en-TZ - 0x13800131: 227, // en-UG - 0x13800133: 228, // en-UM - 0x13800135: 229, // en-US - 0x13800139: 230, // en-VC - 0x1380013c: 231, // en-VG - 0x1380013d: 232, // en-VI - 0x1380013f: 233, // en-VU - 0x13800142: 234, // en-WS - 0x13800161: 235, // en-ZA - 0x13800162: 236, // en-ZM - 0x13800164: 237, // en-ZW - 0x13b00000: 238, // eo - 0x13b00001: 239, // eo-001 - 0x13d00000: 240, // es - 0x13d0001f: 241, // es-419 - 0x13d0002c: 242, // es-AR - 0x13d0003f: 243, // es-BO - 0x13d00041: 244, // es-BR - 0x13d00048: 245, // es-BZ - 0x13d00051: 246, // es-CL - 0x13d00054: 247, // es-CO - 0x13d00056: 248, // es-CR - 0x13d00059: 249, // es-CU - 0x13d00065: 250, // es-DO - 0x13d00068: 251, // es-EA - 0x13d00069: 252, // es-EC - 0x13d0006e: 253, // es-ES - 0x13d00086: 254, // es-GQ - 0x13d00089: 255, // es-GT - 0x13d0008f: 256, // es-HN - 0x13d00094: 257, // es-IC - 0x13d000cf: 258, // es-MX - 0x13d000d8: 259, // es-NI - 0x13d000e2: 260, // es-PA - 0x13d000e4: 261, // es-PE - 0x13d000e7: 262, // es-PH - 0x13d000ec: 263, // es-PR - 0x13d000f1: 264, // es-PY - 0x13d0011a: 265, // es-SV - 0x13d00135: 266, // es-US - 0x13d00136: 267, // es-UY - 0x13d0013b: 268, // es-VE - 0x13f00000: 269, // et - 0x13f0006a: 270, // et-EE - 0x14400000: 271, // eu - 0x1440006e: 272, // eu-ES - 0x14500000: 273, // ewo - 0x14500052: 274, // ewo-CM - 0x14700000: 275, // fa - 0x14700024: 276, // fa-AF - 0x1470009c: 277, // fa-IR - 0x14d00000: 278, // ff - 0x14d00052: 279, // ff-CM - 0x14d00084: 280, // ff-GN - 0x14d000c9: 281, // ff-MR - 0x14d00114: 282, // ff-SN - 0x15000000: 283, // fi - 0x15000072: 284, // fi-FI - 0x15200000: 285, // fil - 0x152000e7: 286, // fil-PH - 0x15700000: 287, // fo - 0x15700063: 288, // fo-DK - 0x15700076: 289, // fo-FO - 0x15d00000: 290, // fr - 0x15d00036: 291, // fr-BE - 0x15d00037: 292, // fr-BF - 0x15d0003a: 293, // fr-BI - 0x15d0003b: 294, // fr-BJ - 0x15d0003c: 295, // fr-BL - 0x15d00049: 296, // fr-CA - 0x15d0004b: 297, // fr-CD - 0x15d0004c: 298, // fr-CF - 0x15d0004d: 299, // fr-CG - 0x15d0004e: 300, // fr-CH - 0x15d0004f: 301, // fr-CI - 0x15d00052: 302, // fr-CM - 0x15d00062: 303, // fr-DJ - 0x15d00067: 304, // fr-DZ - 0x15d00078: 305, // fr-FR - 0x15d0007a: 306, // fr-GA - 0x15d0007e: 307, // fr-GF - 0x15d00084: 308, // fr-GN - 0x15d00085: 309, // fr-GP - 0x15d00086: 310, // fr-GQ - 0x15d00091: 311, // fr-HT - 0x15d000a8: 312, // fr-KM - 0x15d000b7: 313, // fr-LU - 0x15d000ba: 314, // fr-MA - 0x15d000bb: 315, // fr-MC - 0x15d000be: 316, // fr-MF - 0x15d000bf: 317, // fr-MG - 0x15d000c3: 318, // fr-ML - 0x15d000c8: 319, // fr-MQ - 0x15d000c9: 320, // fr-MR - 0x15d000cc: 321, // fr-MU - 0x15d000d3: 322, // fr-NC - 0x15d000d4: 323, // fr-NE - 0x15d000e5: 324, // fr-PF - 0x15d000ea: 325, // fr-PM - 0x15d00102: 326, // fr-RE - 0x15d00107: 327, // fr-RW - 0x15d0010a: 328, // fr-SC - 0x15d00114: 329, // fr-SN - 0x15d0011c: 330, // fr-SY - 0x15d00120: 331, // fr-TD - 0x15d00122: 332, // fr-TG - 0x15d00128: 333, // fr-TN - 0x15d0013f: 334, // fr-VU - 0x15d00140: 335, // fr-WF - 0x15d0015f: 336, // fr-YT - 0x16800000: 337, // fur - 0x1680009e: 338, // fur-IT - 0x16c00000: 339, // fy - 0x16c000d9: 340, // fy-NL - 0x16d00000: 341, // ga - 0x16d00096: 342, // ga-IE - 0x17c00000: 343, // gd - 0x17c0007b: 344, // gd-GB - 0x18e00000: 345, // gl - 0x18e0006e: 346, // gl-ES - 0x1a100000: 347, // gsw - 0x1a10004e: 348, // gsw-CH - 0x1a100078: 349, // gsw-FR - 0x1a1000b2: 350, // gsw-LI - 0x1a200000: 351, // gu - 0x1a200099: 352, // gu-IN - 0x1a700000: 353, // guw - 0x1a900000: 354, // guz - 0x1a9000a4: 355, // guz-KE - 0x1aa00000: 356, // gv - 0x1aa00098: 357, // gv-IM - 0x1b200000: 358, // ha - 0x1b200080: 359, // ha-GH - 0x1b2000d4: 360, // ha-NE - 0x1b2000d6: 361, // ha-NG - 0x1b600000: 362, // haw - 0x1b600135: 363, // haw-US - 0x1ba00000: 364, // he - 0x1ba00097: 365, // he-IL - 0x1bc00000: 366, // hi - 0x1bc00099: 367, // hi-IN - 0x1cf00000: 368, // hr - 0x1cf00033: 369, // hr-BA - 0x1cf00090: 370, // hr-HR - 0x1d000000: 371, // hsb - 0x1d000060: 372, // hsb-DE - 0x1d300000: 373, // hu - 0x1d300092: 374, // hu-HU - 0x1d500000: 375, // hy - 0x1d500028: 376, // hy-AM - 0x1df00000: 377, // id - 0x1df00095: 378, // id-ID - 0x1e500000: 379, // ig - 0x1e5000d6: 380, // ig-NG - 0x1e800000: 381, // ii - 0x1e800053: 382, // ii-CN - 0x1f600000: 383, // is - 0x1f60009d: 384, // is-IS - 0x1f700000: 385, // it - 0x1f70004e: 386, // it-CH - 0x1f70009e: 387, // it-IT - 0x1f700113: 388, // it-SM - 0x1f700138: 389, // it-VA - 0x1f800000: 390, // iu - 0x1fe00000: 391, // ja - 0x1fe000a2: 392, // ja-JP - 0x20100000: 393, // jbo - 0x20500000: 394, // jgo - 0x20500052: 395, // jgo-CM - 0x20800000: 396, // jmc - 0x2080012f: 397, // jmc-TZ - 0x20c00000: 398, // jv - 0x20e00000: 399, // ka - 0x20e0007d: 400, // ka-GE - 0x21000000: 401, // kab - 0x21000067: 402, // kab-DZ - 0x21400000: 403, // kaj - 0x21500000: 404, // kam - 0x215000a4: 405, // kam-KE - 0x21d00000: 406, // kcg - 0x22100000: 407, // kde - 0x2210012f: 408, // kde-TZ - 0x22500000: 409, // kea - 0x2250005a: 410, // kea-CV - 0x23200000: 411, // khq - 0x232000c3: 412, // khq-ML - 0x23700000: 413, // ki - 0x237000a4: 414, // ki-KE - 0x24000000: 415, // kk - 0x240000ae: 416, // kk-KZ - 0x24200000: 417, // kkj - 0x24200052: 418, // kkj-CM - 0x24300000: 419, // kl - 0x24300082: 420, // kl-GL - 0x24400000: 421, // kln - 0x244000a4: 422, // kln-KE - 0x24800000: 423, // km - 0x248000a6: 424, // km-KH - 0x24f00000: 425, // kn - 0x24f00099: 426, // kn-IN - 0x25200000: 427, // ko - 0x252000aa: 428, // ko-KP - 0x252000ab: 429, // ko-KR - 0x25400000: 430, // kok - 0x25400099: 431, // kok-IN - 0x26800000: 432, // ks - 0x26800099: 433, // ks-IN - 0x26900000: 434, // ksb - 0x2690012f: 435, // ksb-TZ - 0x26b00000: 436, // ksf - 0x26b00052: 437, // ksf-CM - 0x26c00000: 438, // ksh - 0x26c00060: 439, // ksh-DE - 0x27200000: 440, // ku - 0x27f00000: 441, // kw - 0x27f0007b: 442, // kw-GB - 0x28800000: 443, // ky - 0x288000a5: 444, // ky-KG - 0x28f00000: 445, // lag - 0x28f0012f: 446, // lag-TZ - 0x29300000: 447, // lb - 0x293000b7: 448, // lb-LU - 0x2a100000: 449, // lg - 0x2a100131: 450, // lg-UG - 0x2ad00000: 451, // lkt - 0x2ad00135: 452, // lkt-US - 0x2b300000: 453, // ln - 0x2b30002a: 454, // ln-AO - 0x2b30004b: 455, // ln-CD - 0x2b30004c: 456, // ln-CF - 0x2b30004d: 457, // ln-CG - 0x2b600000: 458, // lo - 0x2b6000af: 459, // lo-LA - 0x2bd00000: 460, // lrc - 0x2bd0009b: 461, // lrc-IQ - 0x2bd0009c: 462, // lrc-IR - 0x2be00000: 463, // lt - 0x2be000b6: 464, // lt-LT - 0x2c000000: 465, // lu - 0x2c00004b: 466, // lu-CD - 0x2c200000: 467, // luo - 0x2c2000a4: 468, // luo-KE - 0x2c300000: 469, // luy - 0x2c3000a4: 470, // luy-KE - 0x2c500000: 471, // lv - 0x2c5000b8: 472, // lv-LV - 0x2cf00000: 473, // mas - 0x2cf000a4: 474, // mas-KE - 0x2cf0012f: 475, // mas-TZ - 0x2e700000: 476, // mer - 0x2e7000a4: 477, // mer-KE - 0x2eb00000: 478, // mfe - 0x2eb000cc: 479, // mfe-MU - 0x2ef00000: 480, // mg - 0x2ef000bf: 481, // mg-MG - 0x2f000000: 482, // mgh - 0x2f0000d1: 483, // mgh-MZ - 0x2f200000: 484, // mgo - 0x2f200052: 485, // mgo-CM - 0x2fd00000: 486, // mk - 0x2fd000c2: 487, // mk-MK - 0x30200000: 488, // ml - 0x30200099: 489, // ml-IN - 0x30900000: 490, // mn - 0x309000c5: 491, // mn-MN - 0x31900000: 492, // mr - 0x31900099: 493, // mr-IN - 0x31d00000: 494, // ms - 0x31d0003e: 495, // ms-BN - 0x31d000d0: 496, // ms-MY - 0x31d0010d: 497, // ms-SG - 0x31e00000: 498, // mt - 0x31e000cb: 499, // mt-MT - 0x32300000: 500, // mua - 0x32300052: 501, // mua-CM - 0x32f00000: 502, // my - 0x32f000c4: 503, // my-MM - 0x33800000: 504, // mzn - 0x3380009c: 505, // mzn-IR - 0x33f00000: 506, // nah - 0x34300000: 507, // naq - 0x343000d2: 508, // naq-NA - 0x34500000: 509, // nb - 0x345000da: 510, // nb-NO - 0x34500110: 511, // nb-SJ - 0x34c00000: 512, // nd - 0x34c00164: 513, // nd-ZW - 0x34e00000: 514, // nds - 0x34e00060: 515, // nds-DE - 0x34e000d9: 516, // nds-NL - 0x34f00000: 517, // ne - 0x34f00099: 518, // ne-IN - 0x34f000db: 519, // ne-NP - 0x36500000: 520, // nl - 0x36500030: 521, // nl-AW - 0x36500036: 522, // nl-BE - 0x36500040: 523, // nl-BQ - 0x3650005b: 524, // nl-CW - 0x365000d9: 525, // nl-NL - 0x36500116: 526, // nl-SR - 0x3650011b: 527, // nl-SX - 0x36600000: 528, // nmg - 0x36600052: 529, // nmg-CM - 0x36800000: 530, // nn - 0x368000da: 531, // nn-NO - 0x36a00000: 532, // nnh - 0x36a00052: 533, // nnh-CM - 0x36d00000: 534, // no - 0x37300000: 535, // nqo - 0x37400000: 536, // nr - 0x37800000: 537, // nso - 0x37e00000: 538, // nus - 0x37e00117: 539, // nus-SS - 0x38500000: 540, // ny - 0x38700000: 541, // nyn - 0x38700131: 542, // nyn-UG - 0x38e00000: 543, // om - 0x38e0006f: 544, // om-ET - 0x38e000a4: 545, // om-KE - 0x39300000: 546, // or - 0x39300099: 547, // or-IN - 0x39600000: 548, // os - 0x3960007d: 549, // os-GE - 0x39600106: 550, // os-RU - 0x39b00000: 551, // pa - 0x39b05000: 552, // pa-Arab - 0x39b050e8: 553, // pa-Arab-PK - 0x39b32000: 554, // pa-Guru - 0x39b32099: 555, // pa-Guru-IN - 0x39f00000: 556, // pap - 0x3b100000: 557, // pl - 0x3b1000e9: 558, // pl-PL - 0x3bb00000: 559, // prg - 0x3bb00001: 560, // prg-001 - 0x3bc00000: 561, // ps - 0x3bc00024: 562, // ps-AF - 0x3be00000: 563, // pt - 0x3be0002a: 564, // pt-AO - 0x3be00041: 565, // pt-BR - 0x3be0004e: 566, // pt-CH - 0x3be0005a: 567, // pt-CV - 0x3be00086: 568, // pt-GQ - 0x3be0008b: 569, // pt-GW - 0x3be000b7: 570, // pt-LU - 0x3be000c6: 571, // pt-MO - 0x3be000d1: 572, // pt-MZ - 0x3be000ee: 573, // pt-PT - 0x3be00118: 574, // pt-ST - 0x3be00126: 575, // pt-TL - 0x3c200000: 576, // qu - 0x3c20003f: 577, // qu-BO - 0x3c200069: 578, // qu-EC - 0x3c2000e4: 579, // qu-PE - 0x3d200000: 580, // rm - 0x3d20004e: 581, // rm-CH - 0x3d700000: 582, // rn - 0x3d70003a: 583, // rn-BI - 0x3da00000: 584, // ro - 0x3da000bc: 585, // ro-MD - 0x3da00104: 586, // ro-RO - 0x3dc00000: 587, // rof - 0x3dc0012f: 588, // rof-TZ - 0x3e000000: 589, // ru - 0x3e000047: 590, // ru-BY - 0x3e0000a5: 591, // ru-KG - 0x3e0000ae: 592, // ru-KZ - 0x3e0000bc: 593, // ru-MD - 0x3e000106: 594, // ru-RU - 0x3e000130: 595, // ru-UA - 0x3e300000: 596, // rw - 0x3e300107: 597, // rw-RW - 0x3e400000: 598, // rwk - 0x3e40012f: 599, // rwk-TZ - 0x3e900000: 600, // sah - 0x3e900106: 601, // sah-RU - 0x3ea00000: 602, // saq - 0x3ea000a4: 603, // saq-KE - 0x3f100000: 604, // sbp - 0x3f10012f: 605, // sbp-TZ - 0x3fa00000: 606, // sdh - 0x3fb00000: 607, // se - 0x3fb00072: 608, // se-FI - 0x3fb000da: 609, // se-NO - 0x3fb0010c: 610, // se-SE - 0x3fd00000: 611, // seh - 0x3fd000d1: 612, // seh-MZ - 0x3ff00000: 613, // ses - 0x3ff000c3: 614, // ses-ML - 0x40000000: 615, // sg - 0x4000004c: 616, // sg-CF - 0x40600000: 617, // shi - 0x40655000: 618, // shi-Latn - 0x406550ba: 619, // shi-Latn-MA - 0x406d8000: 620, // shi-Tfng - 0x406d80ba: 621, // shi-Tfng-MA - 0x40a00000: 622, // si - 0x40a000b3: 623, // si-LK - 0x41000000: 624, // sk - 0x41000111: 625, // sk-SK - 0x41400000: 626, // sl - 0x4140010f: 627, // sl-SI - 0x41a00000: 628, // sma - 0x41b00000: 629, // smi - 0x41c00000: 630, // smj - 0x41d00000: 631, // smn - 0x41d00072: 632, // smn-FI - 0x42000000: 633, // sms - 0x42100000: 634, // sn - 0x42100164: 635, // sn-ZW - 0x42700000: 636, // so - 0x42700062: 637, // so-DJ - 0x4270006f: 638, // so-ET - 0x427000a4: 639, // so-KE - 0x42700115: 640, // so-SO - 0x42f00000: 641, // sq - 0x42f00027: 642, // sq-AL - 0x42f000c2: 643, // sq-MK - 0x42f0014d: 644, // sq-XK - 0x43000000: 645, // sr - 0x4301e000: 646, // sr-Cyrl - 0x4301e033: 647, // sr-Cyrl-BA - 0x4301e0bd: 648, // sr-Cyrl-ME - 0x4301e105: 649, // sr-Cyrl-RS - 0x4301e14d: 650, // sr-Cyrl-XK - 0x43055000: 651, // sr-Latn - 0x43055033: 652, // sr-Latn-BA - 0x430550bd: 653, // sr-Latn-ME - 0x43055105: 654, // sr-Latn-RS - 0x4305514d: 655, // sr-Latn-XK - 0x43500000: 656, // ss - 0x43800000: 657, // ssy - 0x43900000: 658, // st - 0x44200000: 659, // sv - 0x44200031: 660, // sv-AX - 0x44200072: 661, // sv-FI - 0x4420010c: 662, // sv-SE - 0x44300000: 663, // sw - 0x4430004b: 664, // sw-CD - 0x443000a4: 665, // sw-KE - 0x4430012f: 666, // sw-TZ - 0x44300131: 667, // sw-UG - 0x44c00000: 668, // syr - 0x44e00000: 669, // ta - 0x44e00099: 670, // ta-IN - 0x44e000b3: 671, // ta-LK - 0x44e000d0: 672, // ta-MY - 0x44e0010d: 673, // ta-SG - 0x45f00000: 674, // te - 0x45f00099: 675, // te-IN - 0x46200000: 676, // teo - 0x462000a4: 677, // teo-KE - 0x46200131: 678, // teo-UG - 0x46900000: 679, // th - 0x46900123: 680, // th-TH - 0x46d00000: 681, // ti - 0x46d0006d: 682, // ti-ER - 0x46d0006f: 683, // ti-ET - 0x46f00000: 684, // tig - 0x47400000: 685, // tk - 0x47400127: 686, // tk-TM - 0x47e00000: 687, // tn - 0x48000000: 688, // to - 0x48000129: 689, // to-TO - 0x48800000: 690, // tr - 0x4880005d: 691, // tr-CY - 0x4880012b: 692, // tr-TR - 0x48c00000: 693, // ts - 0x4a200000: 694, // twq - 0x4a2000d4: 695, // twq-NE - 0x4a700000: 696, // tzm - 0x4a7000ba: 697, // tzm-MA - 0x4aa00000: 698, // ug - 0x4aa00053: 699, // ug-CN - 0x4ac00000: 700, // uk - 0x4ac00130: 701, // uk-UA - 0x4b200000: 702, // ur - 0x4b200099: 703, // ur-IN - 0x4b2000e8: 704, // ur-PK - 0x4ba00000: 705, // uz - 0x4ba05000: 706, // uz-Arab - 0x4ba05024: 707, // uz-Arab-AF - 0x4ba1e000: 708, // uz-Cyrl - 0x4ba1e137: 709, // uz-Cyrl-UZ - 0x4ba55000: 710, // uz-Latn - 0x4ba55137: 711, // uz-Latn-UZ - 0x4bc00000: 712, // vai - 0x4bc55000: 713, // vai-Latn - 0x4bc550b4: 714, // vai-Latn-LR - 0x4bcdf000: 715, // vai-Vaii - 0x4bcdf0b4: 716, // vai-Vaii-LR - 0x4be00000: 717, // ve - 0x4c100000: 718, // vi - 0x4c10013e: 719, // vi-VN - 0x4c700000: 720, // vo - 0x4c700001: 721, // vo-001 - 0x4ca00000: 722, // vun - 0x4ca0012f: 723, // vun-TZ - 0x4cc00000: 724, // wa - 0x4cd00000: 725, // wae - 0x4cd0004e: 726, // wae-CH - 0x4e300000: 727, // wo - 0x4f000000: 728, // xh - 0x4f900000: 729, // xog - 0x4f900131: 730, // xog-UG - 0x50700000: 731, // yav - 0x50700052: 732, // yav-CM - 0x51000000: 733, // yi - 0x51000001: 734, // yi-001 - 0x51600000: 735, // yo - 0x5160003b: 736, // yo-BJ - 0x516000d6: 737, // yo-NG - 0x51d00000: 738, // yue - 0x51d0008d: 739, // yue-HK - 0x52600000: 740, // zgh - 0x526000ba: 741, // zgh-MA - 0x52700000: 742, // zh - 0x52737000: 743, // zh-Hans - 0x52737053: 744, // zh-Hans-CN - 0x5273708d: 745, // zh-Hans-HK - 0x527370c6: 746, // zh-Hans-MO - 0x5273710d: 747, // zh-Hans-SG - 0x52738000: 748, // zh-Hant - 0x5273808d: 749, // zh-Hant-HK - 0x527380c6: 750, // zh-Hant-MO - 0x5273812e: 751, // zh-Hant-TW - 0x52c00000: 752, // zu - 0x52c00161: 753, // zu-ZA + 0x0db00000: 86, // ccp + 0x0db00035: 87, // ccp-BD + 0x0db00099: 88, // ccp-IN + 0x0dc00000: 89, // ce + 0x0dc00106: 90, // ce-RU + 0x0df00000: 91, // cgg + 0x0df00131: 92, // cgg-UG + 0x0e500000: 93, // chr + 0x0e500135: 94, // chr-US + 0x0e900000: 95, // ckb + 0x0e90009b: 96, // ckb-IQ + 0x0e90009c: 97, // ckb-IR + 0x0fa00000: 98, // cs + 0x0fa0005e: 99, // cs-CZ + 0x0fe00000: 100, // cu + 0x0fe00106: 101, // cu-RU + 0x10000000: 102, // cy + 0x1000007b: 103, // cy-GB + 0x10100000: 104, // da + 0x10100063: 105, // da-DK + 0x10100082: 106, // da-GL + 0x10800000: 107, // dav + 0x108000a4: 108, // dav-KE + 0x10d00000: 109, // de + 0x10d0002e: 110, // de-AT + 0x10d00036: 111, // de-BE + 0x10d0004e: 112, // de-CH + 0x10d00060: 113, // de-DE + 0x10d0009e: 114, // de-IT + 0x10d000b2: 115, // de-LI + 0x10d000b7: 116, // de-LU + 0x11700000: 117, // dje + 0x117000d4: 118, // dje-NE + 0x11f00000: 119, // dsb + 0x11f00060: 120, // dsb-DE + 0x12400000: 121, // dua + 0x12400052: 122, // dua-CM + 0x12800000: 123, // dv + 0x12b00000: 124, // dyo + 0x12b00114: 125, // dyo-SN + 0x12d00000: 126, // dz + 0x12d00043: 127, // dz-BT + 0x12f00000: 128, // ebu + 0x12f000a4: 129, // ebu-KE + 0x13000000: 130, // ee + 0x13000080: 131, // ee-GH + 0x13000122: 132, // ee-TG + 0x13600000: 133, // el + 0x1360005d: 134, // el-CY + 0x13600087: 135, // el-GR + 0x13900000: 136, // en + 0x13900001: 137, // en-001 + 0x1390001a: 138, // en-150 + 0x13900025: 139, // en-AG + 0x13900026: 140, // en-AI + 0x1390002d: 141, // en-AS + 0x1390002e: 142, // en-AT + 0x1390002f: 143, // en-AU + 0x13900034: 144, // en-BB + 0x13900036: 145, // en-BE + 0x1390003a: 146, // en-BI + 0x1390003d: 147, // en-BM + 0x13900042: 148, // en-BS + 0x13900046: 149, // en-BW + 0x13900048: 150, // en-BZ + 0x13900049: 151, // en-CA + 0x1390004a: 152, // en-CC + 0x1390004e: 153, // en-CH + 0x13900050: 154, // en-CK + 0x13900052: 155, // en-CM + 0x1390005c: 156, // en-CX + 0x1390005d: 157, // en-CY + 0x13900060: 158, // en-DE + 0x13900061: 159, // en-DG + 0x13900063: 160, // en-DK + 0x13900064: 161, // en-DM + 0x1390006d: 162, // en-ER + 0x13900072: 163, // en-FI + 0x13900073: 164, // en-FJ + 0x13900074: 165, // en-FK + 0x13900075: 166, // en-FM + 0x1390007b: 167, // en-GB + 0x1390007c: 168, // en-GD + 0x1390007f: 169, // en-GG + 0x13900080: 170, // en-GH + 0x13900081: 171, // en-GI + 0x13900083: 172, // en-GM + 0x1390008a: 173, // en-GU + 0x1390008c: 174, // en-GY + 0x1390008d: 175, // en-HK + 0x13900096: 176, // en-IE + 0x13900097: 177, // en-IL + 0x13900098: 178, // en-IM + 0x13900099: 179, // en-IN + 0x1390009a: 180, // en-IO + 0x1390009f: 181, // en-JE + 0x139000a0: 182, // en-JM + 0x139000a4: 183, // en-KE + 0x139000a7: 184, // en-KI + 0x139000a9: 185, // en-KN + 0x139000ad: 186, // en-KY + 0x139000b1: 187, // en-LC + 0x139000b4: 188, // en-LR + 0x139000b5: 189, // en-LS + 0x139000bf: 190, // en-MG + 0x139000c0: 191, // en-MH + 0x139000c6: 192, // en-MO + 0x139000c7: 193, // en-MP + 0x139000ca: 194, // en-MS + 0x139000cb: 195, // en-MT + 0x139000cc: 196, // en-MU + 0x139000ce: 197, // en-MW + 0x139000d0: 198, // en-MY + 0x139000d2: 199, // en-NA + 0x139000d5: 200, // en-NF + 0x139000d6: 201, // en-NG + 0x139000d9: 202, // en-NL + 0x139000dd: 203, // en-NR + 0x139000df: 204, // en-NU + 0x139000e0: 205, // en-NZ + 0x139000e6: 206, // en-PG + 0x139000e7: 207, // en-PH + 0x139000e8: 208, // en-PK + 0x139000eb: 209, // en-PN + 0x139000ec: 210, // en-PR + 0x139000f0: 211, // en-PW + 0x13900107: 212, // en-RW + 0x13900109: 213, // en-SB + 0x1390010a: 214, // en-SC + 0x1390010b: 215, // en-SD + 0x1390010c: 216, // en-SE + 0x1390010d: 217, // en-SG + 0x1390010e: 218, // en-SH + 0x1390010f: 219, // en-SI + 0x13900112: 220, // en-SL + 0x13900117: 221, // en-SS + 0x1390011b: 222, // en-SX + 0x1390011d: 223, // en-SZ + 0x1390011f: 224, // en-TC + 0x13900125: 225, // en-TK + 0x13900129: 226, // en-TO + 0x1390012c: 227, // en-TT + 0x1390012d: 228, // en-TV + 0x1390012f: 229, // en-TZ + 0x13900131: 230, // en-UG + 0x13900133: 231, // en-UM + 0x13900135: 232, // en-US + 0x13900139: 233, // en-VC + 0x1390013c: 234, // en-VG + 0x1390013d: 235, // en-VI + 0x1390013f: 236, // en-VU + 0x13900142: 237, // en-WS + 0x13900161: 238, // en-ZA + 0x13900162: 239, // en-ZM + 0x13900164: 240, // en-ZW + 0x13c00000: 241, // eo + 0x13c00001: 242, // eo-001 + 0x13e00000: 243, // es + 0x13e0001f: 244, // es-419 + 0x13e0002c: 245, // es-AR + 0x13e0003f: 246, // es-BO + 0x13e00041: 247, // es-BR + 0x13e00048: 248, // es-BZ + 0x13e00051: 249, // es-CL + 0x13e00054: 250, // es-CO + 0x13e00056: 251, // es-CR + 0x13e00059: 252, // es-CU + 0x13e00065: 253, // es-DO + 0x13e00068: 254, // es-EA + 0x13e00069: 255, // es-EC + 0x13e0006e: 256, // es-ES + 0x13e00086: 257, // es-GQ + 0x13e00089: 258, // es-GT + 0x13e0008f: 259, // es-HN + 0x13e00094: 260, // es-IC + 0x13e000cf: 261, // es-MX + 0x13e000d8: 262, // es-NI + 0x13e000e2: 263, // es-PA + 0x13e000e4: 264, // es-PE + 0x13e000e7: 265, // es-PH + 0x13e000ec: 266, // es-PR + 0x13e000f1: 267, // es-PY + 0x13e0011a: 268, // es-SV + 0x13e00135: 269, // es-US + 0x13e00136: 270, // es-UY + 0x13e0013b: 271, // es-VE + 0x14000000: 272, // et + 0x1400006a: 273, // et-EE + 0x14500000: 274, // eu + 0x1450006e: 275, // eu-ES + 0x14600000: 276, // ewo + 0x14600052: 277, // ewo-CM + 0x14800000: 278, // fa + 0x14800024: 279, // fa-AF + 0x1480009c: 280, // fa-IR + 0x14e00000: 281, // ff + 0x14e00052: 282, // ff-CM + 0x14e00084: 283, // ff-GN + 0x14e000c9: 284, // ff-MR + 0x14e00114: 285, // ff-SN + 0x15100000: 286, // fi + 0x15100072: 287, // fi-FI + 0x15300000: 288, // fil + 0x153000e7: 289, // fil-PH + 0x15800000: 290, // fo + 0x15800063: 291, // fo-DK + 0x15800076: 292, // fo-FO + 0x15e00000: 293, // fr + 0x15e00036: 294, // fr-BE + 0x15e00037: 295, // fr-BF + 0x15e0003a: 296, // fr-BI + 0x15e0003b: 297, // fr-BJ + 0x15e0003c: 298, // fr-BL + 0x15e00049: 299, // fr-CA + 0x15e0004b: 300, // fr-CD + 0x15e0004c: 301, // fr-CF + 0x15e0004d: 302, // fr-CG + 0x15e0004e: 303, // fr-CH + 0x15e0004f: 304, // fr-CI + 0x15e00052: 305, // fr-CM + 0x15e00062: 306, // fr-DJ + 0x15e00067: 307, // fr-DZ + 0x15e00078: 308, // fr-FR + 0x15e0007a: 309, // fr-GA + 0x15e0007e: 310, // fr-GF + 0x15e00084: 311, // fr-GN + 0x15e00085: 312, // fr-GP + 0x15e00086: 313, // fr-GQ + 0x15e00091: 314, // fr-HT + 0x15e000a8: 315, // fr-KM + 0x15e000b7: 316, // fr-LU + 0x15e000ba: 317, // fr-MA + 0x15e000bb: 318, // fr-MC + 0x15e000be: 319, // fr-MF + 0x15e000bf: 320, // fr-MG + 0x15e000c3: 321, // fr-ML + 0x15e000c8: 322, // fr-MQ + 0x15e000c9: 323, // fr-MR + 0x15e000cc: 324, // fr-MU + 0x15e000d3: 325, // fr-NC + 0x15e000d4: 326, // fr-NE + 0x15e000e5: 327, // fr-PF + 0x15e000ea: 328, // fr-PM + 0x15e00102: 329, // fr-RE + 0x15e00107: 330, // fr-RW + 0x15e0010a: 331, // fr-SC + 0x15e00114: 332, // fr-SN + 0x15e0011c: 333, // fr-SY + 0x15e00120: 334, // fr-TD + 0x15e00122: 335, // fr-TG + 0x15e00128: 336, // fr-TN + 0x15e0013f: 337, // fr-VU + 0x15e00140: 338, // fr-WF + 0x15e0015f: 339, // fr-YT + 0x16900000: 340, // fur + 0x1690009e: 341, // fur-IT + 0x16d00000: 342, // fy + 0x16d000d9: 343, // fy-NL + 0x16e00000: 344, // ga + 0x16e00096: 345, // ga-IE + 0x17e00000: 346, // gd + 0x17e0007b: 347, // gd-GB + 0x19000000: 348, // gl + 0x1900006e: 349, // gl-ES + 0x1a300000: 350, // gsw + 0x1a30004e: 351, // gsw-CH + 0x1a300078: 352, // gsw-FR + 0x1a3000b2: 353, // gsw-LI + 0x1a400000: 354, // gu + 0x1a400099: 355, // gu-IN + 0x1a900000: 356, // guw + 0x1ab00000: 357, // guz + 0x1ab000a4: 358, // guz-KE + 0x1ac00000: 359, // gv + 0x1ac00098: 360, // gv-IM + 0x1b400000: 361, // ha + 0x1b400080: 362, // ha-GH + 0x1b4000d4: 363, // ha-NE + 0x1b4000d6: 364, // ha-NG + 0x1b800000: 365, // haw + 0x1b800135: 366, // haw-US + 0x1bc00000: 367, // he + 0x1bc00097: 368, // he-IL + 0x1be00000: 369, // hi + 0x1be00099: 370, // hi-IN + 0x1d100000: 371, // hr + 0x1d100033: 372, // hr-BA + 0x1d100090: 373, // hr-HR + 0x1d200000: 374, // hsb + 0x1d200060: 375, // hsb-DE + 0x1d500000: 376, // hu + 0x1d500092: 377, // hu-HU + 0x1d700000: 378, // hy + 0x1d700028: 379, // hy-AM + 0x1e100000: 380, // id + 0x1e100095: 381, // id-ID + 0x1e700000: 382, // ig + 0x1e7000d6: 383, // ig-NG + 0x1ea00000: 384, // ii + 0x1ea00053: 385, // ii-CN + 0x1f500000: 386, // io + 0x1f800000: 387, // is + 0x1f80009d: 388, // is-IS + 0x1f900000: 389, // it + 0x1f90004e: 390, // it-CH + 0x1f90009e: 391, // it-IT + 0x1f900113: 392, // it-SM + 0x1f900138: 393, // it-VA + 0x1fa00000: 394, // iu + 0x20000000: 395, // ja + 0x200000a2: 396, // ja-JP + 0x20300000: 397, // jbo + 0x20700000: 398, // jgo + 0x20700052: 399, // jgo-CM + 0x20a00000: 400, // jmc + 0x20a0012f: 401, // jmc-TZ + 0x20e00000: 402, // jv + 0x21000000: 403, // ka + 0x2100007d: 404, // ka-GE + 0x21200000: 405, // kab + 0x21200067: 406, // kab-DZ + 0x21600000: 407, // kaj + 0x21700000: 408, // kam + 0x217000a4: 409, // kam-KE + 0x21f00000: 410, // kcg + 0x22300000: 411, // kde + 0x2230012f: 412, // kde-TZ + 0x22700000: 413, // kea + 0x2270005a: 414, // kea-CV + 0x23400000: 415, // khq + 0x234000c3: 416, // khq-ML + 0x23900000: 417, // ki + 0x239000a4: 418, // ki-KE + 0x24200000: 419, // kk + 0x242000ae: 420, // kk-KZ + 0x24400000: 421, // kkj + 0x24400052: 422, // kkj-CM + 0x24500000: 423, // kl + 0x24500082: 424, // kl-GL + 0x24600000: 425, // kln + 0x246000a4: 426, // kln-KE + 0x24a00000: 427, // km + 0x24a000a6: 428, // km-KH + 0x25100000: 429, // kn + 0x25100099: 430, // kn-IN + 0x25400000: 431, // ko + 0x254000aa: 432, // ko-KP + 0x254000ab: 433, // ko-KR + 0x25600000: 434, // kok + 0x25600099: 435, // kok-IN + 0x26a00000: 436, // ks + 0x26a00099: 437, // ks-IN + 0x26b00000: 438, // ksb + 0x26b0012f: 439, // ksb-TZ + 0x26d00000: 440, // ksf + 0x26d00052: 441, // ksf-CM + 0x26e00000: 442, // ksh + 0x26e00060: 443, // ksh-DE + 0x27400000: 444, // ku + 0x28100000: 445, // kw + 0x2810007b: 446, // kw-GB + 0x28a00000: 447, // ky + 0x28a000a5: 448, // ky-KG + 0x29100000: 449, // lag + 0x2910012f: 450, // lag-TZ + 0x29500000: 451, // lb + 0x295000b7: 452, // lb-LU + 0x2a300000: 453, // lg + 0x2a300131: 454, // lg-UG + 0x2af00000: 455, // lkt + 0x2af00135: 456, // lkt-US + 0x2b500000: 457, // ln + 0x2b50002a: 458, // ln-AO + 0x2b50004b: 459, // ln-CD + 0x2b50004c: 460, // ln-CF + 0x2b50004d: 461, // ln-CG + 0x2b800000: 462, // lo + 0x2b8000af: 463, // lo-LA + 0x2bf00000: 464, // lrc + 0x2bf0009b: 465, // lrc-IQ + 0x2bf0009c: 466, // lrc-IR + 0x2c000000: 467, // lt + 0x2c0000b6: 468, // lt-LT + 0x2c200000: 469, // lu + 0x2c20004b: 470, // lu-CD + 0x2c400000: 471, // luo + 0x2c4000a4: 472, // luo-KE + 0x2c500000: 473, // luy + 0x2c5000a4: 474, // luy-KE + 0x2c700000: 475, // lv + 0x2c7000b8: 476, // lv-LV + 0x2d100000: 477, // mas + 0x2d1000a4: 478, // mas-KE + 0x2d10012f: 479, // mas-TZ + 0x2e900000: 480, // mer + 0x2e9000a4: 481, // mer-KE + 0x2ed00000: 482, // mfe + 0x2ed000cc: 483, // mfe-MU + 0x2f100000: 484, // mg + 0x2f1000bf: 485, // mg-MG + 0x2f200000: 486, // mgh + 0x2f2000d1: 487, // mgh-MZ + 0x2f400000: 488, // mgo + 0x2f400052: 489, // mgo-CM + 0x2ff00000: 490, // mk + 0x2ff000c2: 491, // mk-MK + 0x30400000: 492, // ml + 0x30400099: 493, // ml-IN + 0x30b00000: 494, // mn + 0x30b000c5: 495, // mn-MN + 0x31b00000: 496, // mr + 0x31b00099: 497, // mr-IN + 0x31f00000: 498, // ms + 0x31f0003e: 499, // ms-BN + 0x31f000d0: 500, // ms-MY + 0x31f0010d: 501, // ms-SG + 0x32000000: 502, // mt + 0x320000cb: 503, // mt-MT + 0x32500000: 504, // mua + 0x32500052: 505, // mua-CM + 0x33100000: 506, // my + 0x331000c4: 507, // my-MM + 0x33a00000: 508, // mzn + 0x33a0009c: 509, // mzn-IR + 0x34100000: 510, // nah + 0x34500000: 511, // naq + 0x345000d2: 512, // naq-NA + 0x34700000: 513, // nb + 0x347000da: 514, // nb-NO + 0x34700110: 515, // nb-SJ + 0x34e00000: 516, // nd + 0x34e00164: 517, // nd-ZW + 0x35000000: 518, // nds + 0x35000060: 519, // nds-DE + 0x350000d9: 520, // nds-NL + 0x35100000: 521, // ne + 0x35100099: 522, // ne-IN + 0x351000db: 523, // ne-NP + 0x36700000: 524, // nl + 0x36700030: 525, // nl-AW + 0x36700036: 526, // nl-BE + 0x36700040: 527, // nl-BQ + 0x3670005b: 528, // nl-CW + 0x367000d9: 529, // nl-NL + 0x36700116: 530, // nl-SR + 0x3670011b: 531, // nl-SX + 0x36800000: 532, // nmg + 0x36800052: 533, // nmg-CM + 0x36a00000: 534, // nn + 0x36a000da: 535, // nn-NO + 0x36c00000: 536, // nnh + 0x36c00052: 537, // nnh-CM + 0x36f00000: 538, // no + 0x37500000: 539, // nqo + 0x37600000: 540, // nr + 0x37a00000: 541, // nso + 0x38000000: 542, // nus + 0x38000117: 543, // nus-SS + 0x38700000: 544, // ny + 0x38900000: 545, // nyn + 0x38900131: 546, // nyn-UG + 0x39000000: 547, // om + 0x3900006f: 548, // om-ET + 0x390000a4: 549, // om-KE + 0x39500000: 550, // or + 0x39500099: 551, // or-IN + 0x39800000: 552, // os + 0x3980007d: 553, // os-GE + 0x39800106: 554, // os-RU + 0x39d00000: 555, // pa + 0x39d05000: 556, // pa-Arab + 0x39d050e8: 557, // pa-Arab-PK + 0x39d33000: 558, // pa-Guru + 0x39d33099: 559, // pa-Guru-IN + 0x3a100000: 560, // pap + 0x3b300000: 561, // pl + 0x3b3000e9: 562, // pl-PL + 0x3bd00000: 563, // prg + 0x3bd00001: 564, // prg-001 + 0x3be00000: 565, // ps + 0x3be00024: 566, // ps-AF + 0x3c000000: 567, // pt + 0x3c00002a: 568, // pt-AO + 0x3c000041: 569, // pt-BR + 0x3c00004e: 570, // pt-CH + 0x3c00005a: 571, // pt-CV + 0x3c000086: 572, // pt-GQ + 0x3c00008b: 573, // pt-GW + 0x3c0000b7: 574, // pt-LU + 0x3c0000c6: 575, // pt-MO + 0x3c0000d1: 576, // pt-MZ + 0x3c0000ee: 577, // pt-PT + 0x3c000118: 578, // pt-ST + 0x3c000126: 579, // pt-TL + 0x3c400000: 580, // qu + 0x3c40003f: 581, // qu-BO + 0x3c400069: 582, // qu-EC + 0x3c4000e4: 583, // qu-PE + 0x3d400000: 584, // rm + 0x3d40004e: 585, // rm-CH + 0x3d900000: 586, // rn + 0x3d90003a: 587, // rn-BI + 0x3dc00000: 588, // ro + 0x3dc000bc: 589, // ro-MD + 0x3dc00104: 590, // ro-RO + 0x3de00000: 591, // rof + 0x3de0012f: 592, // rof-TZ + 0x3e200000: 593, // ru + 0x3e200047: 594, // ru-BY + 0x3e2000a5: 595, // ru-KG + 0x3e2000ae: 596, // ru-KZ + 0x3e2000bc: 597, // ru-MD + 0x3e200106: 598, // ru-RU + 0x3e200130: 599, // ru-UA + 0x3e500000: 600, // rw + 0x3e500107: 601, // rw-RW + 0x3e600000: 602, // rwk + 0x3e60012f: 603, // rwk-TZ + 0x3eb00000: 604, // sah + 0x3eb00106: 605, // sah-RU + 0x3ec00000: 606, // saq + 0x3ec000a4: 607, // saq-KE + 0x3f300000: 608, // sbp + 0x3f30012f: 609, // sbp-TZ + 0x3fa00000: 610, // sd + 0x3fa000e8: 611, // sd-PK + 0x3fc00000: 612, // sdh + 0x3fd00000: 613, // se + 0x3fd00072: 614, // se-FI + 0x3fd000da: 615, // se-NO + 0x3fd0010c: 616, // se-SE + 0x3ff00000: 617, // seh + 0x3ff000d1: 618, // seh-MZ + 0x40100000: 619, // ses + 0x401000c3: 620, // ses-ML + 0x40200000: 621, // sg + 0x4020004c: 622, // sg-CF + 0x40800000: 623, // shi + 0x40857000: 624, // shi-Latn + 0x408570ba: 625, // shi-Latn-MA + 0x408dc000: 626, // shi-Tfng + 0x408dc0ba: 627, // shi-Tfng-MA + 0x40c00000: 628, // si + 0x40c000b3: 629, // si-LK + 0x41200000: 630, // sk + 0x41200111: 631, // sk-SK + 0x41600000: 632, // sl + 0x4160010f: 633, // sl-SI + 0x41c00000: 634, // sma + 0x41d00000: 635, // smi + 0x41e00000: 636, // smj + 0x41f00000: 637, // smn + 0x41f00072: 638, // smn-FI + 0x42200000: 639, // sms + 0x42300000: 640, // sn + 0x42300164: 641, // sn-ZW + 0x42900000: 642, // so + 0x42900062: 643, // so-DJ + 0x4290006f: 644, // so-ET + 0x429000a4: 645, // so-KE + 0x42900115: 646, // so-SO + 0x43100000: 647, // sq + 0x43100027: 648, // sq-AL + 0x431000c2: 649, // sq-MK + 0x4310014d: 650, // sq-XK + 0x43200000: 651, // sr + 0x4321f000: 652, // sr-Cyrl + 0x4321f033: 653, // sr-Cyrl-BA + 0x4321f0bd: 654, // sr-Cyrl-ME + 0x4321f105: 655, // sr-Cyrl-RS + 0x4321f14d: 656, // sr-Cyrl-XK + 0x43257000: 657, // sr-Latn + 0x43257033: 658, // sr-Latn-BA + 0x432570bd: 659, // sr-Latn-ME + 0x43257105: 660, // sr-Latn-RS + 0x4325714d: 661, // sr-Latn-XK + 0x43700000: 662, // ss + 0x43a00000: 663, // ssy + 0x43b00000: 664, // st + 0x44400000: 665, // sv + 0x44400031: 666, // sv-AX + 0x44400072: 667, // sv-FI + 0x4440010c: 668, // sv-SE + 0x44500000: 669, // sw + 0x4450004b: 670, // sw-CD + 0x445000a4: 671, // sw-KE + 0x4450012f: 672, // sw-TZ + 0x44500131: 673, // sw-UG + 0x44e00000: 674, // syr + 0x45000000: 675, // ta + 0x45000099: 676, // ta-IN + 0x450000b3: 677, // ta-LK + 0x450000d0: 678, // ta-MY + 0x4500010d: 679, // ta-SG + 0x46100000: 680, // te + 0x46100099: 681, // te-IN + 0x46400000: 682, // teo + 0x464000a4: 683, // teo-KE + 0x46400131: 684, // teo-UG + 0x46700000: 685, // tg + 0x46700124: 686, // tg-TJ + 0x46b00000: 687, // th + 0x46b00123: 688, // th-TH + 0x46f00000: 689, // ti + 0x46f0006d: 690, // ti-ER + 0x46f0006f: 691, // ti-ET + 0x47100000: 692, // tig + 0x47600000: 693, // tk + 0x47600127: 694, // tk-TM + 0x48000000: 695, // tn + 0x48200000: 696, // to + 0x48200129: 697, // to-TO + 0x48a00000: 698, // tr + 0x48a0005d: 699, // tr-CY + 0x48a0012b: 700, // tr-TR + 0x48e00000: 701, // ts + 0x49400000: 702, // tt + 0x49400106: 703, // tt-RU + 0x4a400000: 704, // twq + 0x4a4000d4: 705, // twq-NE + 0x4a900000: 706, // tzm + 0x4a9000ba: 707, // tzm-MA + 0x4ac00000: 708, // ug + 0x4ac00053: 709, // ug-CN + 0x4ae00000: 710, // uk + 0x4ae00130: 711, // uk-UA + 0x4b400000: 712, // ur + 0x4b400099: 713, // ur-IN + 0x4b4000e8: 714, // ur-PK + 0x4bc00000: 715, // uz + 0x4bc05000: 716, // uz-Arab + 0x4bc05024: 717, // uz-Arab-AF + 0x4bc1f000: 718, // uz-Cyrl + 0x4bc1f137: 719, // uz-Cyrl-UZ + 0x4bc57000: 720, // uz-Latn + 0x4bc57137: 721, // uz-Latn-UZ + 0x4be00000: 722, // vai + 0x4be57000: 723, // vai-Latn + 0x4be570b4: 724, // vai-Latn-LR + 0x4bee3000: 725, // vai-Vaii + 0x4bee30b4: 726, // vai-Vaii-LR + 0x4c000000: 727, // ve + 0x4c300000: 728, // vi + 0x4c30013e: 729, // vi-VN + 0x4c900000: 730, // vo + 0x4c900001: 731, // vo-001 + 0x4cc00000: 732, // vun + 0x4cc0012f: 733, // vun-TZ + 0x4ce00000: 734, // wa + 0x4cf00000: 735, // wae + 0x4cf0004e: 736, // wae-CH + 0x4e500000: 737, // wo + 0x4e500114: 738, // wo-SN + 0x4f200000: 739, // xh + 0x4fb00000: 740, // xog + 0x4fb00131: 741, // xog-UG + 0x50900000: 742, // yav + 0x50900052: 743, // yav-CM + 0x51200000: 744, // yi + 0x51200001: 745, // yi-001 + 0x51800000: 746, // yo + 0x5180003b: 747, // yo-BJ + 0x518000d6: 748, // yo-NG + 0x51f00000: 749, // yue + 0x51f38000: 750, // yue-Hans + 0x51f38053: 751, // yue-Hans-CN + 0x51f39000: 752, // yue-Hant + 0x51f3908d: 753, // yue-Hant-HK + 0x52800000: 754, // zgh + 0x528000ba: 755, // zgh-MA + 0x52900000: 756, // zh + 0x52938000: 757, // zh-Hans + 0x52938053: 758, // zh-Hans-CN + 0x5293808d: 759, // zh-Hans-HK + 0x529380c6: 760, // zh-Hans-MO + 0x5293810d: 761, // zh-Hans-SG + 0x52939000: 762, // zh-Hant + 0x5293908d: 763, // zh-Hant-HK + 0x529390c6: 764, // zh-Hant-MO + 0x5293912e: 765, // zh-Hant-TW + 0x52f00000: 766, // zu + 0x52f00161: 767, // zu-ZA } -// Total table size 4592 bytes (4KiB); checksum: C25F8AFF +// Total table size 4676 bytes (4KiB); checksum: 17BE3673 diff --git a/vendor/golang.org/x/text/language/language.go b/vendor/golang.org/x/text/language/language.go index ed1011f186..b65e213ff8 100644 --- a/vendor/golang.org/x/text/language/language.go +++ b/vendor/golang.org/x/text/language/language.go @@ -299,6 +299,26 @@ func (t Tag) String() string { return string(buf[:t.genCoreBytes(buf[:])]) } +// MarshalText implements encoding.TextMarshaler. +func (t Tag) MarshalText() (text []byte, err error) { + if t.str != "" { + text = append(text, t.str...) + } else if t.script == 0 && t.region == 0 { + text = append(text, t.lang.String()...) + } else { + buf := [maxCoreSize]byte{} + text = buf[:t.genCoreBytes(buf[:])] + } + return text, nil +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (t *Tag) UnmarshalText(text []byte) error { + tag, err := Raw.Parse(string(text)) + *t = tag + return err +} + // Base returns the base language of the language tag. If the base language is // unspecified, an attempt will be made to infer it from the context. // It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change. diff --git a/vendor/golang.org/x/text/language/language_test.go b/vendor/golang.org/x/text/language/language_test.go deleted file mode 100644 index f7c2d88ab0..0000000000 --- a/vendor/golang.org/x/text/language/language_test.go +++ /dev/null @@ -1,878 +0,0 @@ -// Copyright 2013 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 language - -import ( - "reflect" - "testing" - - "golang.org/x/text/internal/testtext" -) - -func TestTagSize(t *testing.T) { - id := Tag{} - typ := reflect.TypeOf(id) - if typ.Size() > 24 { - t.Errorf("size of Tag was %d; want 24", typ.Size()) - } -} - -func TestIsRoot(t *testing.T) { - loc := Tag{} - if !loc.IsRoot() { - t.Errorf("unspecified should be root.") - } - for i, tt := range parseTests() { - loc, _ := Parse(tt.in) - undef := tt.lang == "und" && tt.script == "" && tt.region == "" && tt.ext == "" - if loc.IsRoot() != undef { - t.Errorf("%d: was %v; want %v", i, loc.IsRoot(), undef) - } - } -} - -func TestEquality(t *testing.T) { - for i, tt := range parseTests()[48:49] { - s := tt.in - tag := Make(s) - t1 := Make(tag.String()) - if tag != t1 { - t.Errorf("%d:%s: equality test 1 failed\n got: %#v\nwant: %#v)", i, s, t1, tag) - } - t2, _ := Compose(tag) - if tag != t2 { - t.Errorf("%d:%s: equality test 2 failed\n got: %#v\nwant: %#v", i, s, t2, tag) - } - } -} - -func TestMakeString(t *testing.T) { - tests := []struct{ in, out string }{ - {"und", "und"}, - {"und", "und-CW"}, - {"nl", "nl-NL"}, - {"de-1901", "nl-1901"}, - {"de-1901", "de-Arab-1901"}, - {"x-a-b", "de-Arab-x-a-b"}, - {"x-a-b", "x-a-b"}, - } - for i, tt := range tests { - id, _ := Parse(tt.in) - mod, _ := Parse(tt.out) - id.setTagsFrom(mod) - for j := 0; j < 2; j++ { - id.remakeString() - if str := id.String(); str != tt.out { - t.Errorf("%d:%d: found %s; want %s", i, j, id.String(), tt.out) - } - } - // The bytes to string conversion as used in remakeString - // occasionally measures as more than one alloc, breaking this test. - // To alleviate this we set the number of runs to more than 1. - if n := testtext.AllocsPerRun(8, id.remakeString); n > 1 { - t.Errorf("%d: # allocs got %.1f; want <= 1", i, n) - } - } -} - -func TestCompactIndex(t *testing.T) { - tests := []struct { - tag string - index int - ok bool - }{ - // TODO: these values will change with each CLDR update. This issue - // will be solved if we decide to fix the indexes. - {"und", 0, true}, - {"ca-ES-valencia", 1, true}, - {"ca-ES-valencia-u-va-posix", 0, false}, - {"ca-ES-valencia-u-co-phonebk", 1, true}, - {"ca-ES-valencia-u-co-phonebk-va-posix", 0, false}, - {"x-klingon", 0, false}, - {"en-US", 229, true}, - {"en-US-u-va-posix", 2, true}, - {"en", 133, true}, - {"en-u-co-phonebk", 133, true}, - {"en-001", 134, true}, - {"sh", 0, false}, // We don't normalize. - } - for _, tt := range tests { - x, ok := CompactIndex(Raw.MustParse(tt.tag)) - if x != tt.index || ok != tt.ok { - t.Errorf("%s: got %d, %v; want %d %v", tt.tag, x, ok, tt.index, tt.ok) - } - } -} - -func TestBase(t *testing.T) { - tests := []struct { - loc, lang string - conf Confidence - }{ - {"und", "en", Low}, - {"x-abc", "und", No}, - {"en", "en", Exact}, - {"und-Cyrl", "ru", High}, - // If a region is not included, the official language should be English. - {"und-US", "en", High}, - // TODO: not-explicitly listed scripts should probably be und, No - // Modify addTags to return info on how the match was derived. - // {"und-Aghb", "und", No}, - } - for i, tt := range tests { - loc, _ := Parse(tt.loc) - lang, conf := loc.Base() - if lang.String() != tt.lang { - t.Errorf("%d: language was %s; want %s", i, lang, tt.lang) - } - if conf != tt.conf { - t.Errorf("%d: confidence was %d; want %d", i, conf, tt.conf) - } - } -} - -func TestParseBase(t *testing.T) { - tests := []struct { - in string - out string - ok bool - }{ - {"en", "en", true}, - {"EN", "en", true}, - {"nld", "nl", true}, - {"dut", "dut", true}, // bibliographic - {"aaj", "und", false}, // unknown - {"qaa", "qaa", true}, - {"a", "und", false}, - {"", "und", false}, - {"aaaa", "und", false}, - } - for i, tt := range tests { - x, err := ParseBase(tt.in) - if x.String() != tt.out || err == nil != tt.ok { - t.Errorf("%d:%s: was %s, %v; want %s, %v", i, tt.in, x, err == nil, tt.out, tt.ok) - } - if y, _, _ := Raw.Make(tt.out).Raw(); x != y { - t.Errorf("%d:%s: tag was %s; want %s", i, tt.in, x, y) - } - } -} - -func TestScript(t *testing.T) { - tests := []struct { - loc, scr string - conf Confidence - }{ - {"und", "Latn", Low}, - {"en-Latn", "Latn", Exact}, - {"en", "Latn", High}, - {"sr", "Cyrl", Low}, - {"kk", "Cyrl", High}, - {"kk-CN", "Arab", Low}, - {"cmn", "Hans", Low}, - {"ru", "Cyrl", High}, - {"ru-RU", "Cyrl", High}, - {"yue", "Hant", Low}, - {"x-abc", "Zzzz", Low}, - {"und-zyyy", "Zyyy", Exact}, - } - for i, tt := range tests { - loc, _ := Parse(tt.loc) - sc, conf := loc.Script() - if sc.String() != tt.scr { - t.Errorf("%d:%s: script was %s; want %s", i, tt.loc, sc, tt.scr) - } - if conf != tt.conf { - t.Errorf("%d:%s: confidence was %d; want %d", i, tt.loc, conf, tt.conf) - } - } -} - -func TestParseScript(t *testing.T) { - tests := []struct { - in string - out string - ok bool - }{ - {"Latn", "Latn", true}, - {"zzzz", "Zzzz", true}, - {"zyyy", "Zyyy", true}, - {"Latm", "Zzzz", false}, - {"Zzz", "Zzzz", false}, - {"", "Zzzz", false}, - {"Zzzxx", "Zzzz", false}, - } - for i, tt := range tests { - x, err := ParseScript(tt.in) - if x.String() != tt.out || err == nil != tt.ok { - t.Errorf("%d:%s: was %s, %v; want %s, %v", i, tt.in, x, err == nil, tt.out, tt.ok) - } - if err == nil { - if _, y, _ := Raw.Make("und-" + tt.out).Raw(); x != y { - t.Errorf("%d:%s: tag was %s; want %s", i, tt.in, x, y) - } - } - } -} - -func TestRegion(t *testing.T) { - tests := []struct { - loc, reg string - conf Confidence - }{ - {"und", "US", Low}, - {"en", "US", Low}, - {"zh-Hant", "TW", Low}, - {"en-US", "US", Exact}, - {"cmn", "CN", Low}, - {"ru", "RU", Low}, - {"yue", "HK", Low}, - {"x-abc", "ZZ", Low}, - } - for i, tt := range tests { - loc, _ := Raw.Parse(tt.loc) - reg, conf := loc.Region() - if reg.String() != tt.reg { - t.Errorf("%d:%s: region was %s; want %s", i, tt.loc, reg, tt.reg) - } - if conf != tt.conf { - t.Errorf("%d:%s: confidence was %d; want %d", i, tt.loc, conf, tt.conf) - } - } -} - -func TestEncodeM49(t *testing.T) { - tests := []struct { - m49 int - code string - ok bool - }{ - {1, "001", true}, - {840, "US", true}, - {899, "ZZ", false}, - } - for i, tt := range tests { - if r, err := EncodeM49(tt.m49); r.String() != tt.code || err == nil != tt.ok { - t.Errorf("%d:%d: was %s, %v; want %s, %v", i, tt.m49, r, err == nil, tt.code, tt.ok) - } - } - for i := 1; i <= 1000; i++ { - if r, err := EncodeM49(i); err == nil && r.M49() == 0 { - t.Errorf("%d has no error, but maps to undefined region", i) - } - } -} - -func TestParseRegion(t *testing.T) { - tests := []struct { - in string - out string - ok bool - }{ - {"001", "001", true}, - {"840", "US", true}, - {"899", "ZZ", false}, - {"USA", "US", true}, - {"US", "US", true}, - {"BC", "ZZ", false}, - {"C", "ZZ", false}, - {"CCCC", "ZZ", false}, - {"01", "ZZ", false}, - } - for i, tt := range tests { - r, err := ParseRegion(tt.in) - if r.String() != tt.out || err == nil != tt.ok { - t.Errorf("%d:%s: was %s, %v; want %s, %v", i, tt.in, r, err == nil, tt.out, tt.ok) - } - if err == nil { - if _, _, y := Raw.Make("und-" + tt.out).Raw(); r != y { - t.Errorf("%d:%s: tag was %s; want %s", i, tt.in, r, y) - } - } - } -} - -func TestIsCountry(t *testing.T) { - tests := []struct { - reg string - country bool - }{ - {"US", true}, - {"001", false}, - {"958", false}, - {"419", false}, - {"203", true}, - {"020", true}, - {"900", false}, - {"999", false}, - {"QO", false}, - {"EU", false}, - {"AA", false}, - {"XK", true}, - } - for i, tt := range tests { - reg, _ := getRegionID([]byte(tt.reg)) - r := Region{reg} - if r.IsCountry() != tt.country { - t.Errorf("%d: IsCountry(%s) was %v; want %v", i, tt.reg, r.IsCountry(), tt.country) - } - } -} - -func TestIsGroup(t *testing.T) { - tests := []struct { - reg string - group bool - }{ - {"US", false}, - {"001", true}, - {"958", false}, - {"419", true}, - {"203", false}, - {"020", false}, - {"900", false}, - {"999", false}, - {"QO", true}, - {"EU", true}, - {"AA", false}, - {"XK", false}, - } - for i, tt := range tests { - reg, _ := getRegionID([]byte(tt.reg)) - r := Region{reg} - if r.IsGroup() != tt.group { - t.Errorf("%d: IsGroup(%s) was %v; want %v", i, tt.reg, r.IsGroup(), tt.group) - } - } -} - -func TestContains(t *testing.T) { - tests := []struct { - enclosing, contained string - contains bool - }{ - // A region contains itself. - {"US", "US", true}, - {"001", "001", true}, - - // Direct containment. - {"001", "002", true}, - {"039", "XK", true}, - {"150", "XK", true}, - {"EU", "AT", true}, - {"QO", "AQ", true}, - - // Indirect containemnt. - {"001", "US", true}, - {"001", "419", true}, - {"001", "013", true}, - - // No containment. - {"US", "001", false}, - {"155", "EU", false}, - } - for i, tt := range tests { - enc, _ := getRegionID([]byte(tt.enclosing)) - con, _ := getRegionID([]byte(tt.contained)) - r := Region{enc} - if got := r.Contains(Region{con}); got != tt.contains { - t.Errorf("%d: %s.Contains(%s) was %v; want %v", i, tt.enclosing, tt.contained, got, tt.contains) - } - } -} - -func TestRegionCanonicalize(t *testing.T) { - for i, tt := range []struct{ in, out string }{ - {"UK", "GB"}, - {"TP", "TL"}, - {"QU", "EU"}, - {"SU", "SU"}, - {"VD", "VN"}, - {"DD", "DE"}, - } { - r := MustParseRegion(tt.in) - want := MustParseRegion(tt.out) - if got := r.Canonicalize(); got != want { - t.Errorf("%d: got %v; want %v", i, got, want) - } - } -} - -func TestRegionTLD(t *testing.T) { - for _, tt := range []struct { - in, out string - ok bool - }{ - {"EH", "EH", true}, - {"FR", "FR", true}, - {"TL", "TL", true}, - - // In ccTLD before in ISO. - {"GG", "GG", true}, - - // Non-standard assignment of ccTLD to ISO code. - {"GB", "UK", true}, - - // Exceptionally reserved in ISO and valid ccTLD. - {"UK", "UK", true}, - {"AC", "AC", true}, - {"EU", "EU", true}, - {"SU", "SU", true}, - - // Exceptionally reserved in ISO and invalid ccTLD. - {"CP", "ZZ", false}, - {"DG", "ZZ", false}, - {"EA", "ZZ", false}, - {"FX", "ZZ", false}, - {"IC", "ZZ", false}, - {"TA", "ZZ", false}, - - // Transitionally reserved in ISO (e.g. deprecated) but valid ccTLD as - // it is still being phased out. - {"AN", "AN", true}, - {"TP", "TP", true}, - - // Transitionally reserved in ISO (e.g. deprecated) and invalid ccTLD. - // Defined in package language as it has a mapping in CLDR. - {"BU", "ZZ", false}, - {"CS", "ZZ", false}, - {"NT", "ZZ", false}, - {"YU", "ZZ", false}, - {"ZR", "ZZ", false}, - // Not defined in package: SF. - - // Indeterminately reserved in ISO. - // Defined in package language as it has a legacy mapping in CLDR. - {"DY", "ZZ", false}, - {"RH", "ZZ", false}, - {"VD", "ZZ", false}, - // Not defined in package: EW, FL, JA, LF, PI, RA, RB, RC, RI, RL, RM, - // RN, RP, WG, WL, WV, and YV. - - // Not assigned in ISO, but legacy definitions in CLDR. - {"DD", "ZZ", false}, - {"YD", "ZZ", false}, - - // Normal mappings but somewhat special status in ccTLD. - {"BL", "BL", true}, - {"MF", "MF", true}, - {"BV", "BV", true}, - {"SJ", "SJ", true}, - - // Have values when normalized, but not as is. - {"QU", "ZZ", false}, - - // ISO Private Use. - {"AA", "ZZ", false}, - {"QM", "ZZ", false}, - {"QO", "ZZ", false}, - {"XA", "ZZ", false}, - {"XK", "ZZ", false}, // Sometimes used for Kosovo, but invalid ccTLD. - } { - if tt.in == "" { - continue - } - - r := MustParseRegion(tt.in) - var want Region - if tt.out != "ZZ" { - want = MustParseRegion(tt.out) - } - tld, err := r.TLD() - if got := err == nil; got != tt.ok { - t.Errorf("error(%v): got %v; want %v", r, got, tt.ok) - } - if tld != want { - t.Errorf("TLD(%v): got %v; want %v", r, tld, want) - } - } -} - -func TestCanonicalize(t *testing.T) { - // TODO: do a full test using CLDR data in a separate regression test. - tests := []struct { - in, out string - option CanonType - }{ - {"en-Latn", "en", SuppressScript}, - {"sr-Cyrl", "sr-Cyrl", SuppressScript}, - {"sh", "sr-Latn", Legacy}, - {"sh-HR", "sr-Latn-HR", Legacy}, - {"sh-Cyrl-HR", "sr-Cyrl-HR", Legacy}, - {"tl", "fil", Legacy}, - {"no", "no", Legacy}, - {"no", "nb", Legacy | CLDR}, - {"cmn", "cmn", Legacy}, - {"cmn", "zh", Macro}, - {"cmn-u-co-stroke", "zh-u-co-stroke", Macro}, - {"yue", "yue", Macro}, - {"nb", "no", Macro}, - {"nb", "nb", Macro | CLDR}, - {"no", "no", Macro}, - {"no", "no", Macro | CLDR}, - {"iw", "he", DeprecatedBase}, - {"iw", "he", Deprecated | CLDR}, - {"mo", "ro-MD", Deprecated}, // Adopted by CLDR as of version 25. - {"alb", "sq", Legacy}, // bibliographic - {"dut", "nl", Legacy}, // bibliographic - // As of CLDR 25, mo is no longer considered a legacy mapping. - {"mo", "mo", Legacy | CLDR}, - {"und-AN", "und-AN", Deprecated}, - {"und-YD", "und-YE", DeprecatedRegion}, - {"und-YD", "und-YD", DeprecatedBase}, - {"und-Qaai", "und-Zinh", DeprecatedScript}, - {"und-Qaai", "und-Qaai", DeprecatedBase}, - {"drh", "mn", All}, // drh -> khk -> mn - } - for i, tt := range tests { - in, _ := Raw.Parse(tt.in) - in, _ = tt.option.Canonicalize(in) - if in.String() != tt.out { - t.Errorf("%d:%s: was %s; want %s", i, tt.in, in.String(), tt.out) - } - if int(in.pVariant) > int(in.pExt) || int(in.pExt) > len(in.str) { - t.Errorf("%d:%s:offsets %d <= %d <= %d must be true", i, tt.in, in.pVariant, in.pExt, len(in.str)) - } - } - // Test idempotence. - for _, base := range Supported.BaseLanguages() { - tag, _ := Raw.Compose(base) - got, _ := All.Canonicalize(tag) - want, _ := All.Canonicalize(got) - if got != want { - t.Errorf("idem(%s): got %s; want %s", tag, got, want) - } - } -} - -func TestTypeForKey(t *testing.T) { - tests := []struct{ key, in, out string }{ - {"co", "en", ""}, - {"co", "en-u-abc", ""}, - {"co", "en-u-co-phonebk", "phonebk"}, - {"co", "en-u-co-phonebk-cu-aud", "phonebk"}, - {"co", "x-foo-u-co-phonebk", ""}, - {"nu", "en-u-co-phonebk-nu-arabic", "arabic"}, - {"kc", "cmn-u-co-stroke", ""}, - } - for _, tt := range tests { - if v := Make(tt.in).TypeForKey(tt.key); v != tt.out { - t.Errorf("%q[%q]: was %q; want %q", tt.in, tt.key, v, tt.out) - } - } -} - -func TestSetTypeForKey(t *testing.T) { - tests := []struct { - key, value, in, out string - err bool - }{ - // replace existing value - {"co", "pinyin", "en-u-co-phonebk", "en-u-co-pinyin", false}, - {"co", "pinyin", "en-u-co-phonebk-cu-xau", "en-u-co-pinyin-cu-xau", false}, - {"co", "pinyin", "en-u-co-phonebk-v-xx", "en-u-co-pinyin-v-xx", false}, - {"co", "pinyin", "en-u-co-phonebk-x-x", "en-u-co-pinyin-x-x", false}, - {"nu", "arabic", "en-u-co-phonebk-nu-vaai", "en-u-co-phonebk-nu-arabic", false}, - // add to existing -u extension - {"co", "pinyin", "en-u-ca-gregory", "en-u-ca-gregory-co-pinyin", false}, - {"co", "pinyin", "en-u-ca-gregory-nu-vaai", "en-u-ca-gregory-co-pinyin-nu-vaai", false}, - {"co", "pinyin", "en-u-ca-gregory-v-va", "en-u-ca-gregory-co-pinyin-v-va", false}, - {"co", "pinyin", "en-u-ca-gregory-x-a", "en-u-ca-gregory-co-pinyin-x-a", false}, - {"ca", "gregory", "en-u-co-pinyin", "en-u-ca-gregory-co-pinyin", false}, - // remove pair - {"co", "", "en-u-co-phonebk", "en", false}, - {"co", "", "en-u-ca-gregory-co-phonebk", "en-u-ca-gregory", false}, - {"co", "", "en-u-co-phonebk-nu-arabic", "en-u-nu-arabic", false}, - {"co", "", "en", "en", false}, - // add -u extension - {"co", "pinyin", "en", "en-u-co-pinyin", false}, - {"co", "pinyin", "und", "und-u-co-pinyin", false}, - {"co", "pinyin", "en-a-aaa", "en-a-aaa-u-co-pinyin", false}, - {"co", "pinyin", "en-x-aaa", "en-u-co-pinyin-x-aaa", false}, - {"co", "pinyin", "en-v-aa", "en-u-co-pinyin-v-aa", false}, - {"co", "pinyin", "en-a-aaa-x-x", "en-a-aaa-u-co-pinyin-x-x", false}, - {"co", "pinyin", "en-a-aaa-v-va", "en-a-aaa-u-co-pinyin-v-va", false}, - // error on invalid values - {"co", "pinyinxxx", "en", "en", true}, - {"co", "piny.n", "en", "en", true}, - {"co", "pinyinxxx", "en-a-aaa", "en-a-aaa", true}, - {"co", "pinyinxxx", "en-u-aaa", "en-u-aaa", true}, - {"co", "pinyinxxx", "en-u-aaa-co-pinyin", "en-u-aaa-co-pinyin", true}, - {"co", "pinyi.", "en-u-aaa-co-pinyin", "en-u-aaa-co-pinyin", true}, - {"col", "pinyin", "en", "en", true}, - {"co", "cu", "en", "en", true}, - // error when setting on a private use tag - {"co", "phonebook", "x-foo", "x-foo", true}, - } - for i, tt := range tests { - tag := Make(tt.in) - if v, err := tag.SetTypeForKey(tt.key, tt.value); v.String() != tt.out { - t.Errorf("%d:%q[%q]=%q: was %q; want %q", i, tt.in, tt.key, tt.value, v, tt.out) - } else if (err != nil) != tt.err { - t.Errorf("%d:%q[%q]=%q: error was %v; want %v", i, tt.in, tt.key, tt.value, err != nil, tt.err) - } else if val := v.TypeForKey(tt.key); err == nil && val != tt.value { - t.Errorf("%d:%q[%q]==%q: was %v; want %v", i, tt.out, tt.key, tt.value, val, tt.value) - } - if len(tag.String()) <= 3 { - // Simulate a tag for which the string has not been set. - tag.str, tag.pExt, tag.pVariant = "", 0, 0 - if tag, err := tag.SetTypeForKey(tt.key, tt.value); err == nil { - if val := tag.TypeForKey(tt.key); err == nil && val != tt.value { - t.Errorf("%d:%q[%q]==%q: was %v; want %v", i, tt.out, tt.key, tt.value, val, tt.value) - } - } - } - } -} - -func TestFindKeyAndType(t *testing.T) { - // out is either the matched type in case of a match or the original - // string up till the insertion point. - tests := []struct { - key string - hasExt bool - in, out string - }{ - // Don't search past a private use extension. - {"co", false, "en-x-foo-u-co-pinyin", "en"}, - {"co", false, "x-foo-u-co-pinyin", ""}, - {"co", false, "en-s-fff-x-foo", "en-s-fff"}, - // Insertion points in absence of -u extension. - {"cu", false, "en", ""}, // t.str is "" - {"cu", false, "en-v-va", "en"}, - {"cu", false, "en-a-va", "en-a-va"}, - {"cu", false, "en-a-va-v-va", "en-a-va"}, - {"cu", false, "en-x-a", "en"}, - // Tags with the -u extension. - {"co", true, "en-u-co-standard", "standard"}, - {"co", true, "yue-u-co-pinyin", "pinyin"}, - {"co", true, "en-u-co-abc", "abc"}, - {"co", true, "en-u-co-abc-def", "abc-def"}, - {"co", true, "en-u-co-abc-def-x-foo", "abc-def"}, - {"co", true, "en-u-co-standard-nu-arab", "standard"}, - {"co", true, "yue-u-co-pinyin-nu-arab", "pinyin"}, - // Insertion points. - {"cu", true, "en-u-co-standard", "en-u-co-standard"}, - {"cu", true, "yue-u-co-pinyin-x-foo", "yue-u-co-pinyin"}, - {"cu", true, "en-u-co-abc", "en-u-co-abc"}, - {"cu", true, "en-u-nu-arabic", "en-u"}, - {"cu", true, "en-u-co-abc-def-nu-arabic", "en-u-co-abc-def"}, - } - for i, tt := range tests { - start, end, hasExt := Make(tt.in).findTypeForKey(tt.key) - if start != end { - res := tt.in[start:end] - if res != tt.out { - t.Errorf("%d:%s: was %q; want %q", i, tt.in, res, tt.out) - } - } else { - if hasExt != tt.hasExt { - t.Errorf("%d:%s: hasExt was %v; want %v", i, tt.in, hasExt, tt.hasExt) - continue - } - if tt.in[:start] != tt.out { - t.Errorf("%d:%s: insertion point was %q; want %q", i, tt.in, tt.in[:start], tt.out) - } - } - } -} - -func TestParent(t *testing.T) { - tests := []struct{ in, out string }{ - // Strip variants and extensions first - {"de-u-co-phonebk", "de"}, - {"de-1994", "de"}, - {"de-Latn-1994", "de"}, // remove superfluous script. - - // Ensure the canonical Tag for an entry is in the chain for base-script - // pairs. - {"zh-Hans", "zh"}, - - // Skip the script if it is the maximized version. CLDR files for the - // skipped tag are always empty. - {"zh-Hans-TW", "zh"}, - {"zh-Hans-CN", "zh"}, - - // Insert the script if the maximized script is not the same as the - // maximized script of the base language. - {"zh-TW", "zh-Hant"}, - {"zh-HK", "zh-Hant"}, - {"zh-Hant-TW", "zh-Hant"}, - {"zh-Hant-HK", "zh-Hant"}, - - // Non-default script skips to und. - // CLDR - {"az-Cyrl", "und"}, - {"bs-Cyrl", "und"}, - {"en-Dsrt", "und"}, - {"ha-Arab", "und"}, - {"mn-Mong", "und"}, - {"pa-Arab", "und"}, - {"shi-Latn", "und"}, - {"sr-Latn", "und"}, - {"uz-Arab", "und"}, - {"uz-Cyrl", "und"}, - {"vai-Latn", "und"}, - {"zh-Hant", "und"}, - // extra - {"nl-Cyrl", "und"}, - - // World english inherits from en-001. - {"en-150", "en-001"}, - {"en-AU", "en-001"}, - {"en-BE", "en-001"}, - {"en-GG", "en-001"}, - {"en-GI", "en-001"}, - {"en-HK", "en-001"}, - {"en-IE", "en-001"}, - {"en-IM", "en-001"}, - {"en-IN", "en-001"}, - {"en-JE", "en-001"}, - {"en-MT", "en-001"}, - {"en-NZ", "en-001"}, - {"en-PK", "en-001"}, - {"en-SG", "en-001"}, - - // Spanish in Latin-American countries have es-419 as parent. - {"es-AR", "es-419"}, - {"es-BO", "es-419"}, - {"es-CL", "es-419"}, - {"es-CO", "es-419"}, - {"es-CR", "es-419"}, - {"es-CU", "es-419"}, - {"es-DO", "es-419"}, - {"es-EC", "es-419"}, - {"es-GT", "es-419"}, - {"es-HN", "es-419"}, - {"es-MX", "es-419"}, - {"es-NI", "es-419"}, - {"es-PA", "es-419"}, - {"es-PE", "es-419"}, - {"es-PR", "es-419"}, - {"es-PY", "es-419"}, - {"es-SV", "es-419"}, - {"es-US", "es-419"}, - {"es-UY", "es-419"}, - {"es-VE", "es-419"}, - // exceptions (according to CLDR) - {"es-CW", "es"}, - - // Inherit from pt-PT, instead of pt for these countries. - {"pt-AO", "pt-PT"}, - {"pt-CV", "pt-PT"}, - {"pt-GW", "pt-PT"}, - {"pt-MO", "pt-PT"}, - {"pt-MZ", "pt-PT"}, - {"pt-ST", "pt-PT"}, - {"pt-TL", "pt-PT"}, - } - for _, tt := range tests { - tag := Raw.MustParse(tt.in) - if p := Raw.MustParse(tt.out); p != tag.Parent() { - t.Errorf("%s: was %v; want %v", tt.in, tag.Parent(), p) - } - } -} - -var ( - // Tags without error that don't need to be changed. - benchBasic = []string{ - "en", - "en-Latn", - "en-GB", - "za", - "zh-Hant", - "zh", - "zh-HK", - "ar-MK", - "en-CA", - "fr-CA", - "fr-CH", - "fr", - "lv", - "he-IT", - "tlh", - "ja", - "ja-Jpan", - "ja-Jpan-JP", - "de-1996", - "de-CH", - "sr", - "sr-Latn", - } - // Tags with extensions, not changes required. - benchExt = []string{ - "x-a-b-c-d", - "x-aa-bbbb-cccccccc-d", - "en-x_cc-b-bbb-a-aaa", - "en-c_cc-b-bbb-a-aaa-x-x", - "en-u-co-phonebk", - "en-Cyrl-u-co-phonebk", - "en-US-u-co-phonebk-cu-xau", - "en-nedix-u-co-phonebk", - "en-t-t0-abcd", - "en-t-nl-latn", - "en-t-t0-abcd-x-a", - } - // Change, but not memory allocation required. - benchSimpleChange = []string{ - "EN", - "i-klingon", - "en-latn", - "zh-cmn-Hans-CN", - "iw-NL", - } - // Change and memory allocation required. - benchChangeAlloc = []string{ - "en-c_cc-b-bbb-a-aaa", - "en-u-cu-xua-co-phonebk", - "en-u-cu-xua-co-phonebk-a-cd", - "en-u-def-abc-cu-xua-co-phonebk", - "en-t-en-Cyrl-NL-1994", - "en-t-en-Cyrl-NL-1994-t0-abc-def", - } - // Tags that result in errors. - benchErr = []string{ - // IllFormed - "x_A.-B-C_D", - "en-u-cu-co-phonebk", - "en-u-cu-xau-co", - "en-t-nl-abcd", - // Invalid - "xx", - "nl-Uuuu", - "nl-QB", - } - benchChange = append(benchSimpleChange, benchChangeAlloc...) - benchAll = append(append(append(benchBasic, benchExt...), benchChange...), benchErr...) -) - -func doParse(b *testing.B, tag []string) { - for i := 0; i < b.N; i++ { - // Use the modulo instead of looping over all tags so that we get a somewhat - // meaningful ns/op. - Parse(tag[i%len(tag)]) - } -} - -func BenchmarkParse(b *testing.B) { - doParse(b, benchAll) -} - -func BenchmarkParseBasic(b *testing.B) { - doParse(b, benchBasic) -} - -func BenchmarkParseError(b *testing.B) { - doParse(b, benchErr) -} - -func BenchmarkParseSimpleChange(b *testing.B) { - doParse(b, benchSimpleChange) -} - -func BenchmarkParseChangeAlloc(b *testing.B) { - doParse(b, benchChangeAlloc) -} diff --git a/vendor/golang.org/x/text/language/lookup_test.go b/vendor/golang.org/x/text/language/lookup_test.go deleted file mode 100644 index 9833830c41..0000000000 --- a/vendor/golang.org/x/text/language/lookup_test.go +++ /dev/null @@ -1,457 +0,0 @@ -// Copyright 2013 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 language - -import ( - "testing" - - "golang.org/x/text/internal/tag" -) - -func b(s string) []byte { - return []byte(s) -} - -func TestLangID(t *testing.T) { - tests := []struct { - id, bcp47, iso3, norm string - err error - }{ - {id: "", bcp47: "und", iso3: "und", err: errSyntax}, - {id: " ", bcp47: "und", iso3: "und", err: errSyntax}, - {id: " ", bcp47: "und", iso3: "und", err: errSyntax}, - {id: " ", bcp47: "und", iso3: "und", err: errSyntax}, - {id: "xxx", bcp47: "und", iso3: "und", err: mkErrInvalid([]byte("xxx"))}, - {id: "und", bcp47: "und", iso3: "und"}, - {id: "aju", bcp47: "aju", iso3: "aju", norm: "jrb"}, - {id: "jrb", bcp47: "jrb", iso3: "jrb"}, - {id: "es", bcp47: "es", iso3: "spa"}, - {id: "spa", bcp47: "es", iso3: "spa"}, - {id: "ji", bcp47: "ji", iso3: "yid-", norm: "yi"}, - {id: "jw", bcp47: "jw", iso3: "jav-", norm: "jv"}, - {id: "ar", bcp47: "ar", iso3: "ara"}, - {id: "kw", bcp47: "kw", iso3: "cor"}, - {id: "arb", bcp47: "arb", iso3: "arb", norm: "ar"}, - {id: "ar", bcp47: "ar", iso3: "ara"}, - {id: "kur", bcp47: "ku", iso3: "kur"}, - {id: "nl", bcp47: "nl", iso3: "nld"}, - {id: "NL", bcp47: "nl", iso3: "nld"}, - {id: "gsw", bcp47: "gsw", iso3: "gsw"}, - {id: "gSW", bcp47: "gsw", iso3: "gsw"}, - {id: "und", bcp47: "und", iso3: "und"}, - {id: "sh", bcp47: "sh", iso3: "hbs", norm: "sr"}, - {id: "hbs", bcp47: "sh", iso3: "hbs", norm: "sr"}, - {id: "no", bcp47: "no", iso3: "nor", norm: "no"}, - {id: "nor", bcp47: "no", iso3: "nor", norm: "no"}, - {id: "cmn", bcp47: "cmn", iso3: "cmn", norm: "zh"}, - } - for i, tt := range tests { - want, err := getLangID(b(tt.id)) - if err != tt.err { - t.Errorf("%d:err(%s): found %q; want %q", i, tt.id, err, tt.err) - } - if err != nil { - continue - } - if id, _ := getLangISO2(b(tt.bcp47)); len(tt.bcp47) == 2 && want != id { - t.Errorf("%d:getISO2(%s): found %v; want %v", i, tt.bcp47, id, want) - } - if len(tt.iso3) == 3 { - if id, _ := getLangISO3(b(tt.iso3)); want != id { - t.Errorf("%d:getISO3(%s): found %q; want %q", i, tt.iso3, id, want) - } - if id, _ := getLangID(b(tt.iso3)); want != id { - t.Errorf("%d:getID3(%s): found %v; want %v", i, tt.iso3, id, want) - } - } - norm := want - if tt.norm != "" { - norm, _ = getLangID(b(tt.norm)) - } - id, _ := normLang(want) - if id != norm { - t.Errorf("%d:norm(%s): found %v; want %v", i, tt.id, id, norm) - } - if id := want.String(); tt.bcp47 != id { - t.Errorf("%d:String(): found %s; want %s", i, id, tt.bcp47) - } - if id := want.ISO3(); tt.iso3[:3] != id { - t.Errorf("%d:iso3(): found %s; want %s", i, id, tt.iso3[:3]) - } - } -} - -func TestGrandfathered(t *testing.T) { - for _, tt := range []struct{ in, out string }{ - {"art-lojban", "jbo"}, - {"i-ami", "ami"}, - {"i-bnn", "bnn"}, - {"i-hak", "hak"}, - {"i-klingon", "tlh"}, - {"i-lux", "lb"}, - {"i-navajo", "nv"}, - {"i-pwn", "pwn"}, - {"i-tao", "tao"}, - {"i-tay", "tay"}, - {"i-tsu", "tsu"}, - {"no-bok", "nb"}, - {"no-nyn", "nn"}, - {"sgn-BE-FR", "sfb"}, - {"sgn-BE-NL", "vgt"}, - {"sgn-CH-DE", "sgg"}, - {"sgn-ch-de", "sgg"}, - {"zh-guoyu", "cmn"}, - {"zh-hakka", "hak"}, - {"zh-min-nan", "nan"}, - {"zh-xiang", "hsn"}, - - // Grandfathered tags with no modern replacement will be converted as follows: - {"cel-gaulish", "xtg-x-cel-gaulish"}, - {"en-GB-oed", "en-GB-oxendict"}, - {"en-gb-oed", "en-GB-oxendict"}, - {"i-default", "en-x-i-default"}, - {"i-enochian", "und-x-i-enochian"}, - {"i-mingo", "see-x-i-mingo"}, - {"zh-min", "nan-x-zh-min"}, - - {"root", "und"}, - {"en_US_POSIX", "en-US-u-va-posix"}, - {"en_us_posix", "en-US-u-va-posix"}, - {"en-us-posix", "en-US-u-va-posix"}, - } { - got := Raw.Make(tt.in) - want := Raw.MustParse(tt.out) - if got != want { - t.Errorf("%s: got %q; want %q", tt.in, got, want) - } - } -} - -func TestRegionID(t *testing.T) { - tests := []struct { - in, out string - }{ - {"_ ", ""}, - {"_000", ""}, - {"419", "419"}, - {"AA", "AA"}, - {"ATF", "TF"}, - {"HV", "HV"}, - {"CT", "CT"}, - {"DY", "DY"}, - {"IC", "IC"}, - {"FQ", "FQ"}, - {"JT", "JT"}, - {"ZZ", "ZZ"}, - {"EU", "EU"}, - {"QO", "QO"}, - {"FX", "FX"}, - } - for i, tt := range tests { - if tt.in[0] == '_' { - id := tt.in[1:] - if _, err := getRegionID(b(id)); err == nil { - t.Errorf("%d:err(%s): found nil; want error", i, id) - } - continue - } - want, _ := getRegionID(b(tt.in)) - if s := want.String(); s != tt.out { - t.Errorf("%d:%s: found %q; want %q", i, tt.in, s, tt.out) - } - if len(tt.in) == 2 { - want, _ := getRegionISO2(b(tt.in)) - if s := want.String(); s != tt.out { - t.Errorf("%d:getISO2(%s): found %q; want %q", i, tt.in, s, tt.out) - } - } - } -} - -func TestRegionType(t *testing.T) { - for _, tt := range []struct { - r string - t byte - }{ - {"NL", bcp47Region | ccTLD}, - {"EU", bcp47Region | ccTLD}, // exceptionally reserved - {"AN", bcp47Region | ccTLD}, // transitionally reserved - - {"DD", bcp47Region}, // deleted in ISO, deprecated in BCP 47 - {"NT", bcp47Region}, // transitionally reserved, deprecated in BCP 47 - - {"XA", iso3166UserAssigned | bcp47Region}, - {"ZZ", iso3166UserAssigned | bcp47Region}, - {"AA", iso3166UserAssigned | bcp47Region}, - {"QO", iso3166UserAssigned | bcp47Region}, - {"QM", iso3166UserAssigned | bcp47Region}, - {"XK", iso3166UserAssigned | bcp47Region}, - - {"CT", 0}, // deleted in ISO, not in BCP 47, canonicalized in CLDR - } { - r := MustParseRegion(tt.r) - if tp := r.typ(); tp != tt.t { - t.Errorf("Type(%s): got %x; want %x", tt.r, tp, tt.t) - } - } -} - -func TestRegionISO3(t *testing.T) { - tests := []struct { - from, iso3, to string - }{ - {" ", "ZZZ", "ZZ"}, - {"000", "ZZZ", "ZZ"}, - {"AA", "AAA", ""}, - {"CT", "CTE", ""}, - {"DY", "DHY", ""}, - {"EU", "QUU", ""}, - {"HV", "HVO", ""}, - {"IC", "ZZZ", "ZZ"}, - {"JT", "JTN", ""}, - {"PZ", "PCZ", ""}, - {"QU", "QUU", "EU"}, - {"QO", "QOO", ""}, - {"YD", "YMD", ""}, - {"FQ", "ATF", "TF"}, - {"TF", "ATF", ""}, - {"FX", "FXX", ""}, - {"ZZ", "ZZZ", ""}, - {"419", "ZZZ", "ZZ"}, - } - for _, tt := range tests { - r, _ := getRegionID(b(tt.from)) - if s := r.ISO3(); s != tt.iso3 { - t.Errorf("iso3(%q): found %q; want %q", tt.from, s, tt.iso3) - } - if tt.iso3 == "" { - continue - } - want := tt.to - if tt.to == "" { - want = tt.from - } - r, _ = getRegionID(b(want)) - if id, _ := getRegionISO3(b(tt.iso3)); id != r { - t.Errorf("%s: found %q; want %q", tt.iso3, id, want) - } - } -} - -func TestRegionM49(t *testing.T) { - fromTests := []struct { - m49 int - id string - }{ - {0, ""}, - {-1, ""}, - {1000, ""}, - {10000, ""}, - - {001, "001"}, - {104, "MM"}, - {180, "CD"}, - {230, "ET"}, - {231, "ET"}, - {249, "FX"}, - {250, "FR"}, - {276, "DE"}, - {278, "DD"}, - {280, "DE"}, - {419, "419"}, - {626, "TL"}, - {736, "SD"}, - {840, "US"}, - {854, "BF"}, - {891, "CS"}, - {899, ""}, - {958, "AA"}, - {966, "QT"}, - {967, "EU"}, - {999, "ZZ"}, - } - for _, tt := range fromTests { - id, err := getRegionM49(tt.m49) - if want, have := err != nil, tt.id == ""; want != have { - t.Errorf("error(%d): have %v; want %v", tt.m49, have, want) - continue - } - r, _ := getRegionID(b(tt.id)) - if r != id { - t.Errorf("region(%d): have %s; want %s", tt.m49, id, r) - } - } - - toTests := []struct { - m49 int - id string - }{ - {0, "000"}, - {0, "IC"}, // Some codes don't have an ID - - {001, "001"}, - {104, "MM"}, - {104, "BU"}, - {180, "CD"}, - {180, "ZR"}, - {231, "ET"}, - {250, "FR"}, - {249, "FX"}, - {276, "DE"}, - {278, "DD"}, - {419, "419"}, - {626, "TL"}, - {626, "TP"}, - {729, "SD"}, - {826, "GB"}, - {840, "US"}, - {854, "BF"}, - {891, "YU"}, - {891, "CS"}, - {958, "AA"}, - {966, "QT"}, - {967, "EU"}, - {967, "QU"}, - {999, "ZZ"}, - // For codes that don't have an M49 code use the replacement value, - // if available. - {854, "HV"}, // maps to Burkino Faso - } - for _, tt := range toTests { - r, _ := getRegionID(b(tt.id)) - if r.M49() != tt.m49 { - t.Errorf("m49(%q): have %d; want %d", tt.id, r.M49(), tt.m49) - } - } -} - -func TestRegionDeprecation(t *testing.T) { - tests := []struct{ in, out string }{ - {"BU", "MM"}, - {"BUR", "MM"}, - {"CT", "KI"}, - {"DD", "DE"}, - {"DDR", "DE"}, - {"DY", "BJ"}, - {"FX", "FR"}, - {"HV", "BF"}, - {"JT", "UM"}, - {"MI", "UM"}, - {"NH", "VU"}, - {"NQ", "AQ"}, - {"PU", "UM"}, - {"PZ", "PA"}, - {"QU", "EU"}, - {"RH", "ZW"}, - {"TP", "TL"}, - {"UK", "GB"}, - {"VD", "VN"}, - {"WK", "UM"}, - {"YD", "YE"}, - {"NL", "NL"}, - } - for _, tt := range tests { - rIn, _ := getRegionID([]byte(tt.in)) - rOut, _ := getRegionISO2([]byte(tt.out)) - r := normRegion(rIn) - if rOut == rIn && r != 0 { - t.Errorf("%s: was %q; want %q", tt.in, r, tt.in) - } - if rOut != rIn && r != rOut { - t.Errorf("%s: was %q; want %q", tt.in, r, tt.out) - } - - } -} - -func TestGetScriptID(t *testing.T) { - idx := tag.Index("0000BbbbDdddEeeeZzzz\xff\xff\xff\xff") - tests := []struct { - in string - out scriptID - }{ - {" ", 0}, - {" ", 0}, - {" ", 0}, - {"", 0}, - {"Aaaa", 0}, - {"Bbbb", 1}, - {"Dddd", 2}, - {"dddd", 2}, - {"dDDD", 2}, - {"Eeee", 3}, - {"Zzzz", 4}, - } - for i, tt := range tests { - if id, err := getScriptID(idx, b(tt.in)); id != tt.out { - t.Errorf("%d:%s: found %d; want %d", i, tt.in, id, tt.out) - } else if id == 0 && err == nil { - t.Errorf("%d:%s: no error; expected one", i, tt.in) - } - } -} - -func TestIsPrivateUse(t *testing.T) { - type test struct { - s string - private bool - } - tests := []test{ - {"en", false}, - {"und", false}, - {"pzn", false}, - {"qaa", true}, - {"qtz", true}, - {"qua", false}, - } - for i, tt := range tests { - x, _ := getLangID([]byte(tt.s)) - if b := x.IsPrivateUse(); b != tt.private { - t.Errorf("%d: langID.IsPrivateUse(%s) was %v; want %v", i, tt.s, b, tt.private) - } - } - tests = []test{ - {"001", false}, - {"419", false}, - {"899", false}, - {"900", false}, - {"957", false}, - {"958", true}, - {"AA", true}, - {"AC", false}, - {"EU", false}, // CLDR grouping, exceptionally reserved in ISO. - {"QU", true}, // Canonicalizes to EU, User-assigned in ISO. - {"QO", true}, // CLDR grouping, User-assigned in ISO. - {"QA", false}, - {"QM", true}, - {"QZ", true}, - {"XA", true}, - {"XK", true}, // Assigned to Kosovo in CLDR, User-assigned in ISO. - {"XZ", true}, - {"ZW", false}, - {"ZZ", true}, - } - for i, tt := range tests { - x, _ := getRegionID([]byte(tt.s)) - if b := x.IsPrivateUse(); b != tt.private { - t.Errorf("%d: regionID.IsPrivateUse(%s) was %v; want %v", i, tt.s, b, tt.private) - } - } - tests = []test{ - {"Latn", false}, - {"Laaa", false}, // invalid - {"Qaaa", true}, - {"Qabx", true}, - {"Qaby", false}, - {"Zyyy", false}, - {"Zzzz", false}, - } - for i, tt := range tests { - x, _ := getScriptID(script, []byte(tt.s)) - if b := x.IsPrivateUse(); b != tt.private { - t.Errorf("%d: scriptID.IsPrivateUse(%s) was %v; want %v", i, tt.s, b, tt.private) - } - } -} diff --git a/vendor/golang.org/x/text/language/match_test.go b/vendor/golang.org/x/text/language/match_test.go deleted file mode 100644 index 8b60b07a34..0000000000 --- a/vendor/golang.org/x/text/language/match_test.go +++ /dev/null @@ -1,505 +0,0 @@ -// Copyright 2013 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 language - -import ( - "bytes" - "flag" - "fmt" - "os" - "path" - "path/filepath" - "strings" - "testing" - - "golang.org/x/text/internal/testtext" - "golang.org/x/text/internal/ucd" -) - -var verbose = flag.Bool("verbose", false, "set to true to print the internal tables of matchers") - -func TestCompliance(t *testing.T) { - filepath.Walk("testdata", func(file string, info os.FileInfo, err error) error { - if info.IsDir() { - return nil - } - r, err := os.Open(file) - if err != nil { - t.Fatal(err) - } - ucd.Parse(r, func(p *ucd.Parser) { - name := strings.Replace(path.Join(p.String(0), p.String(1)), " ", "", -1) - if skip[name] { - return - } - t.Run(info.Name()+"/"+name, func(t *testing.T) { - supported := makeTagList(p.String(0)) - desired := makeTagList(p.String(1)) - gotCombined, index, conf := NewMatcher(supported).Match(desired...) - - gotMatch := supported[index] - wantMatch := mk(p.String(2)) - if gotMatch != wantMatch { - t.Fatalf("match: got %q; want %q (%v)", gotMatch, wantMatch, conf) - } - wantCombined, err := Raw.Parse(p.String(3)) - if err == nil && gotCombined != wantCombined { - t.Errorf("combined: got %q; want %q (%v)", gotCombined, wantCombined, conf) - } - }) - }) - return nil - }) -} - -var skip = map[string]bool{ - // TODO: bugs - // Honor the wildcard match. This may only be useful to select non-exact - // stuff. - "mul,af/nl": true, // match: got "af"; want "mul" - - // TODO: include other extensions. - // combined: got "en-GB-u-ca-buddhist-nu-arab"; want "en-GB-fonipa-t-m0-iso-i0-pinyin-u-ca-buddhist-nu-arab" - "und,en-GB-u-sd-gbsct/en-fonipa-u-nu-Arab-ca-buddhist-t-m0-iso-i0-pinyin": true, - - // Inconsistencies with Mark Davis' implementation where it is not clear - // which is better. - - // Inconsistencies in combined. I think the Go approach is more appropriate. - // We could use -u-rg- and -u-va- as alternative. - "und,fr/fr-BE-fonipa": true, // combined: got "fr"; want "fr-BE-fonipa" - "und,fr-CA/fr-BE-fonipa": true, // combined: got "fr-CA"; want "fr-BE-fonipa" - "und,fr-fonupa/fr-BE-fonipa": true, // combined: got "fr-fonupa"; want "fr-BE-fonipa" - "und,no/nn-BE-fonipa": true, // combined: got "no"; want "no-BE-fonipa" - "50,und,fr-CA-fonupa/fr-BE-fonipa": true, // combined: got "fr-CA-fonupa"; want "fr-BE-fonipa" - - // The initial number is a threshold. As we don't use scoring, we will not - // implement this. - "50,und,fr-Cyrl-CA-fonupa/fr-BE-fonipa": true, - // match: got "und"; want "fr-Cyrl-CA-fonupa" - // combined: got "und"; want "fr-Cyrl-BE-fonipa" - - // Other interesting cases to test: - // - Should same language or same script have the preference if there is - // usually no understanding of the other script? - // - More specific region in desired may replace enclosing supported. -} - -func makeTagList(s string) (tags []Tag) { - for _, s := range strings.Split(s, ",") { - tags = append(tags, mk(strings.TrimSpace(s))) - } - return tags -} - -func TestMatchStrings(t *testing.T) { - testCases := []struct { - supported string - desired string // strings separted by | - tag string - index int - }{{ - supported: "en", - desired: "", - tag: "en", - index: 0, - }, { - supported: "en", - desired: "nl", - tag: "en", - index: 0, - }, { - supported: "en,nl", - desired: "nl", - tag: "nl", - index: 1, - }, { - supported: "en,nl", - desired: "nl|en", - tag: "nl", - index: 1, - }, { - supported: "en-GB,nl", - desired: "en ; q=0.1,nl", - tag: "nl", - index: 1, - }, { - supported: "en-GB,nl", - desired: "en;q=0.005 | dk; q=0.1,nl ", - tag: "en-GB", - index: 0, - }, { - // do not match faulty tags with und - supported: "en,und", - desired: "|en", - tag: "en", - index: 0, - }} - for _, tc := range testCases { - t.Run(path.Join(tc.supported, tc.desired), func(t *testing.T) { - m := NewMatcher(makeTagList(tc.supported)) - tag, index := MatchStrings(m, strings.Split(tc.desired, "|")...) - if tag.String() != tc.tag || index != tc.index { - t.Errorf("got %v, %d; want %v, %d", tag, index, tc.tag, tc.index) - } - }) - } -} - -func TestAddLikelySubtags(t *testing.T) { - tests := []struct{ in, out string }{ - {"aa", "aa-Latn-ET"}, - {"aa-Latn", "aa-Latn-ET"}, - {"aa-Arab", "aa-Arab-ET"}, - {"aa-Arab-ER", "aa-Arab-ER"}, - {"kk", "kk-Cyrl-KZ"}, - {"kk-CN", "kk-Arab-CN"}, - {"cmn", "cmn"}, - {"zh-AU", "zh-Hant-AU"}, - {"zh-VN", "zh-Hant-VN"}, - {"zh-SG", "zh-Hans-SG"}, - {"zh-Hant", "zh-Hant-TW"}, - {"zh-Hani", "zh-Hani-CN"}, - {"und-Hani", "zh-Hani-CN"}, - {"und", "en-Latn-US"}, - {"und-GB", "en-Latn-GB"}, - {"und-CW", "pap-Latn-CW"}, - {"und-YT", "fr-Latn-YT"}, - {"und-Arab", "ar-Arab-EG"}, - {"und-AM", "hy-Armn-AM"}, - {"und-TW", "zh-Hant-TW"}, - {"und-002", "en-Latn-NG"}, - {"und-Latn-002", "en-Latn-NG"}, - {"en-Latn-002", "en-Latn-NG"}, - {"en-002", "en-Latn-NG"}, - {"en-001", "en-Latn-US"}, - {"und-003", "en-Latn-US"}, - {"und-GB", "en-Latn-GB"}, - {"Latn-001", "en-Latn-US"}, - {"en-001", "en-Latn-US"}, - {"es-419", "es-Latn-419"}, - {"he-145", "he-Hebr-IL"}, - {"ky-145", "ky-Latn-TR"}, - {"kk", "kk-Cyrl-KZ"}, - // Don't specialize duplicate and ambiguous matches. - {"kk-034", "kk-Arab-034"}, // Matches IR and AF. Both are Arab. - {"ku-145", "ku-Latn-TR"}, // Matches IQ, TR, and LB, but kk -> TR. - {"und-Arab-CC", "ms-Arab-CC"}, - {"und-Arab-GB", "ks-Arab-GB"}, - {"und-Hans-CC", "zh-Hans-CC"}, - {"und-CC", "en-Latn-CC"}, - {"sr", "sr-Cyrl-RS"}, - {"sr-151", "sr-Latn-151"}, // Matches RO and RU. - // We would like addLikelySubtags to generate the same results if the input - // only changes by adding tags that would otherwise have been added - // by the expansion. - // In other words: - // und-AA -> xx-Scrp-AA implies und-Scrp-AA -> xx-Scrp-AA - // und-AA -> xx-Scrp-AA implies xx-AA -> xx-Scrp-AA - // und-Scrp -> xx-Scrp-AA implies und-Scrp-AA -> xx-Scrp-AA - // und-Scrp -> xx-Scrp-AA implies xx-Scrp -> xx-Scrp-AA - // xx -> xx-Scrp-AA implies xx-Scrp -> xx-Scrp-AA - // xx -> xx-Scrp-AA implies xx-AA -> xx-Scrp-AA - // - // The algorithm specified in - // http://unicode.org/reports/tr35/tr35-9.html#Supplemental_Data, - // Section C.10, does not handle the first case. For example, - // the CLDR data contains an entry und-BJ -> fr-Latn-BJ, but not - // there is no rule for und-Latn-BJ. According to spec, und-Latn-BJ - // would expand to en-Latn-BJ, violating the aforementioned principle. - // We deviate from the spec by letting und-Scrp-AA expand to xx-Scrp-AA - // if a rule of the form und-AA -> xx-Scrp-AA is defined. - // Note that as of version 23, CLDR has some explicitly specified - // entries that do not conform to these rules. The implementation - // will not correct these explicit inconsistencies. A later versions of CLDR - // is supposed to fix this. - {"und-Latn-BJ", "fr-Latn-BJ"}, - {"und-Bugi-ID", "bug-Bugi-ID"}, - // regions, scripts and languages without definitions - {"und-Arab-AA", "ar-Arab-AA"}, - {"und-Afak-RE", "fr-Afak-RE"}, - {"und-Arab-GB", "ks-Arab-GB"}, - {"abp-Arab-GB", "abp-Arab-GB"}, - // script has preference over region - {"und-Arab-NL", "ar-Arab-NL"}, - {"zza", "zza-Latn-TR"}, - // preserve variants and extensions - {"de-1901", "de-Latn-DE-1901"}, - {"de-x-abc", "de-Latn-DE-x-abc"}, - {"de-1901-x-abc", "de-Latn-DE-1901-x-abc"}, - {"x-abc", "x-abc"}, // TODO: is this the desired behavior? - } - for i, tt := range tests { - in, _ := Parse(tt.in) - out, _ := Parse(tt.out) - in, _ = in.addLikelySubtags() - if in.String() != out.String() { - t.Errorf("%d: add(%s) was %s; want %s", i, tt.in, in, tt.out) - } - } -} -func TestMinimize(t *testing.T) { - tests := []struct{ in, out string }{ - {"aa", "aa"}, - {"aa-Latn", "aa"}, - {"aa-Latn-ET", "aa"}, - {"aa-ET", "aa"}, - {"aa-Arab", "aa-Arab"}, - {"aa-Arab-ER", "aa-Arab-ER"}, - {"aa-Arab-ET", "aa-Arab"}, - {"und", "und"}, - {"und-Latn", "und"}, - {"und-Latn-US", "und"}, - {"en-Latn-US", "en"}, - {"cmn", "cmn"}, - {"cmn-Hans", "cmn-Hans"}, - {"cmn-Hant", "cmn-Hant"}, - {"zh-AU", "zh-AU"}, - {"zh-VN", "zh-VN"}, - {"zh-SG", "zh-SG"}, - {"zh-Hant", "zh-Hant"}, - {"zh-Hant-TW", "zh-TW"}, - {"zh-Hans", "zh"}, - {"zh-Hani", "zh-Hani"}, - {"und-Hans", "und-Hans"}, - {"und-Hani", "und-Hani"}, - - {"und-CW", "und-CW"}, - {"und-YT", "und-YT"}, - {"und-Arab", "und-Arab"}, - {"und-AM", "und-AM"}, - {"und-Arab-CC", "und-Arab-CC"}, - {"und-CC", "und-CC"}, - {"und-Latn-BJ", "und-BJ"}, - {"und-Bugi-ID", "und-Bugi"}, - {"bug-Bugi-ID", "bug-Bugi"}, - // regions, scripts and languages without definitions - {"und-Arab-AA", "und-Arab-AA"}, - // preserve variants and extensions - {"de-Latn-1901", "de-1901"}, - {"de-Latn-x-abc", "de-x-abc"}, - {"de-DE-1901-x-abc", "de-1901-x-abc"}, - {"x-abc", "x-abc"}, // TODO: is this the desired behavior? - } - for i, tt := range tests { - in, _ := Parse(tt.in) - out, _ := Parse(tt.out) - min, _ := in.minimize() - if min.String() != out.String() { - t.Errorf("%d: min(%s) was %s; want %s", i, tt.in, min, tt.out) - } - max, _ := min.addLikelySubtags() - if x, _ := in.addLikelySubtags(); x.String() != max.String() { - t.Errorf("%d: max(min(%s)) = %s; want %s", i, tt.in, max, x) - } - } -} - -func TestRegionGroups(t *testing.T) { - testCases := []struct { - a, b string - distance uint8 - }{ - {"zh-TW", "zh-HK", 5}, - {"zh-MO", "zh-HK", 4}, - {"es-ES", "es-AR", 5}, - {"es-ES", "es", 4}, - {"es-419", "es-MX", 4}, - {"es-AR", "es-MX", 4}, - {"es-ES", "es-MX", 5}, - {"es-PT", "es-MX", 5}, - } - for _, tc := range testCases { - a := MustParse(tc.a) - aScript, _ := a.Script() - b := MustParse(tc.b) - bScript, _ := b.Script() - - if aScript != bScript { - t.Errorf("scripts differ: %q vs %q", aScript, bScript) - continue - } - d, _ := regionGroupDist(a.region, b.region, aScript.scriptID, a.lang) - if d != tc.distance { - t.Errorf("got %q; want %q", d, tc.distance) - } - } -} - -func TestIsParadigmLocale(t *testing.T) { - testCases := map[string]bool{ - "en-US": true, - "en-GB": true, - "en-VI": false, - "es-GB": false, - "es-ES": true, - "es-419": true, - } - for str, want := range testCases { - tag := Make(str) - got := isParadigmLocale(tag.lang, tag.region) - if got != want { - t.Errorf("isPL(%q) = %v; want %v", str, got, want) - } - } -} - -// Implementation of String methods for various types for debugging purposes. - -func (m *matcher) String() string { - w := &bytes.Buffer{} - fmt.Fprintln(w, "Default:", m.default_) - for tag, h := range m.index { - fmt.Fprintf(w, " %s: %v\n", tag, h) - } - return w.String() -} - -func (h *matchHeader) String() string { - w := &bytes.Buffer{} - fmt.Fprint(w, "haveTag: ") - for _, h := range h.haveTags { - fmt.Fprintf(w, "%v, ", h) - } - return w.String() -} - -func (t haveTag) String() string { - return fmt.Sprintf("%v:%d:%v:%v-%v|%v", t.tag, t.index, t.conf, t.maxRegion, t.maxScript, t.altScript) -} - -func TestBestMatchAlloc(t *testing.T) { - m := NewMatcher(makeTagList("en sr nl")) - // Go allocates when creating a list of tags from a single tag! - list := []Tag{English} - avg := testtext.AllocsPerRun(1, func() { - m.Match(list...) - }) - if avg > 0 { - t.Errorf("got %f; want 0", avg) - } -} - -var benchHave = []Tag{ - mk("en"), - mk("en-GB"), - mk("za"), - mk("zh-Hant"), - mk("zh-Hans-CN"), - mk("zh"), - mk("zh-HK"), - mk("ar-MK"), - mk("en-CA"), - mk("fr-CA"), - mk("fr-US"), - mk("fr-CH"), - mk("fr"), - mk("lt"), - mk("lv"), - mk("iw"), - mk("iw-NL"), - mk("he"), - mk("he-IT"), - mk("tlh"), - mk("ja"), - mk("ja-Jpan"), - mk("ja-Jpan-JP"), - mk("de"), - mk("de-CH"), - mk("de-AT"), - mk("de-DE"), - mk("sr"), - mk("sr-Latn"), - mk("sr-Cyrl"), - mk("sr-ME"), -} - -var benchWant = [][]Tag{ - []Tag{ - mk("en"), - }, - []Tag{ - mk("en-AU"), - mk("de-HK"), - mk("nl"), - mk("fy"), - mk("lv"), - }, - []Tag{ - mk("en-AU"), - mk("de-HK"), - mk("nl"), - mk("fy"), - }, - []Tag{ - mk("ja-Hant"), - mk("da-HK"), - mk("nl"), - mk("zh-TW"), - }, - []Tag{ - mk("ja-Hant"), - mk("da-HK"), - mk("nl"), - mk("hr"), - }, -} - -func BenchmarkMatch(b *testing.B) { - m := newMatcher(benchHave, nil) - for i := 0; i < b.N; i++ { - for _, want := range benchWant { - m.getBest(want...) - } - } -} - -func BenchmarkMatchExact(b *testing.B) { - want := mk("en") - m := newMatcher(benchHave, nil) - for i := 0; i < b.N; i++ { - m.getBest(want) - } -} - -func BenchmarkMatchAltLanguagePresent(b *testing.B) { - want := mk("hr") - m := newMatcher(benchHave, nil) - for i := 0; i < b.N; i++ { - m.getBest(want) - } -} - -func BenchmarkMatchAltLanguageNotPresent(b *testing.B) { - want := mk("nn") - m := newMatcher(benchHave, nil) - for i := 0; i < b.N; i++ { - m.getBest(want) - } -} - -func BenchmarkMatchAltScriptPresent(b *testing.B) { - want := mk("zh-Hant-CN") - m := newMatcher(benchHave, nil) - for i := 0; i < b.N; i++ { - m.getBest(want) - } -} - -func BenchmarkMatchAltScriptNotPresent(b *testing.B) { - want := mk("fr-Cyrl") - m := newMatcher(benchHave, nil) - for i := 0; i < b.N; i++ { - m.getBest(want) - } -} - -func BenchmarkMatchLimitedExact(b *testing.B) { - want := []Tag{mk("he-NL"), mk("iw-NL")} - m := newMatcher(benchHave, nil) - for i := 0; i < b.N; i++ { - m.getBest(want...) - } -} diff --git a/vendor/golang.org/x/text/language/parse_test.go b/vendor/golang.org/x/text/language/parse_test.go deleted file mode 100644 index 9b40eb444e..0000000000 --- a/vendor/golang.org/x/text/language/parse_test.go +++ /dev/null @@ -1,517 +0,0 @@ -// Copyright 2013 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 language - -import ( - "bytes" - "strings" - "testing" - - "golang.org/x/text/internal/tag" -) - -type scanTest struct { - ok bool // true if scanning does not result in an error - in string - tok []string // the expected tokens -} - -var tests = []scanTest{ - {true, "", []string{}}, - {true, "1", []string{"1"}}, - {true, "en", []string{"en"}}, - {true, "root", []string{"root"}}, - {true, "maxchars", []string{"maxchars"}}, - {false, "bad/", []string{}}, - {false, "morethan8", []string{}}, - {false, "-", []string{}}, - {false, "----", []string{}}, - {false, "_", []string{}}, - {true, "en-US", []string{"en", "US"}}, - {true, "en_US", []string{"en", "US"}}, - {false, "en-US-", []string{"en", "US"}}, - {false, "en-US--", []string{"en", "US"}}, - {false, "en-US---", []string{"en", "US"}}, - {false, "en--US", []string{"en", "US"}}, - {false, "-en-US", []string{"en", "US"}}, - {false, "-en--US-", []string{"en", "US"}}, - {false, "-en--US-", []string{"en", "US"}}, - {false, "en-.-US", []string{"en", "US"}}, - {false, ".-en--US-.", []string{"en", "US"}}, - {false, "en-u.-US", []string{"en", "US"}}, - {true, "en-u1-US", []string{"en", "u1", "US"}}, - {true, "maxchar1_maxchar2-maxchar3", []string{"maxchar1", "maxchar2", "maxchar3"}}, - {false, "moreThan8-moreThan8-e", []string{"e"}}, -} - -func TestScan(t *testing.T) { - for i, tt := range tests { - scan := makeScannerString(tt.in) - for j := 0; !scan.done; j++ { - if j >= len(tt.tok) { - t.Errorf("%d: extra token %q", i, scan.token) - } else if tag.Compare(tt.tok[j], scan.token) != 0 { - t.Errorf("%d: token %d: found %q; want %q", i, j, scan.token, tt.tok[j]) - break - } - scan.scan() - } - if s := strings.Join(tt.tok, "-"); tag.Compare(s, bytes.Replace(scan.b, b("_"), b("-"), -1)) != 0 { - t.Errorf("%d: input: found %q; want %q", i, scan.b, s) - } - if (scan.err == nil) != tt.ok { - t.Errorf("%d: ok: found %v; want %v", i, scan.err == nil, tt.ok) - } - } -} - -func TestAcceptMinSize(t *testing.T) { - for i, tt := range tests { - // count number of successive tokens with a minimum size. - for sz := 1; sz <= 8; sz++ { - scan := makeScannerString(tt.in) - scan.end, scan.next = 0, 0 - end := scan.acceptMinSize(sz) - n := 0 - for i := 0; i < len(tt.tok) && len(tt.tok[i]) >= sz; i++ { - n += len(tt.tok[i]) - if i > 0 { - n++ - } - } - if end != n { - t.Errorf("%d:%d: found len %d; want %d", i, sz, end, n) - } - } - } -} - -type parseTest struct { - i int // the index of this test - in string - lang, script, region string - variants, ext string - extList []string // only used when more than one extension is present - invalid bool - rewrite bool // special rewrite not handled by parseTag - changed bool // string needed to be reformatted -} - -func parseTests() []parseTest { - tests := []parseTest{ - {in: "root", lang: "und"}, - {in: "und", lang: "und"}, - {in: "en", lang: "en"}, - {in: "xy", lang: "und", invalid: true}, - {in: "en-ZY", lang: "en", invalid: true}, - {in: "gsw", lang: "gsw"}, - {in: "sr_Latn", lang: "sr", script: "Latn"}, - {in: "af-Arab", lang: "af", script: "Arab"}, - {in: "nl-BE", lang: "nl", region: "BE"}, - {in: "es-419", lang: "es", region: "419"}, - {in: "und-001", lang: "und", region: "001"}, - {in: "de-latn-be", lang: "de", script: "Latn", region: "BE"}, - // Variants - {in: "de-1901", lang: "de", variants: "1901"}, - // Accept with unsuppressed script. - {in: "de-Latn-1901", lang: "de", script: "Latn", variants: "1901"}, - // Specialized. - {in: "sl-rozaj", lang: "sl", variants: "rozaj"}, - {in: "sl-rozaj-lipaw", lang: "sl", variants: "rozaj-lipaw"}, - {in: "sl-rozaj-biske", lang: "sl", variants: "rozaj-biske"}, - {in: "sl-rozaj-biske-1994", lang: "sl", variants: "rozaj-biske-1994"}, - {in: "sl-rozaj-1994", lang: "sl", variants: "rozaj-1994"}, - // Maximum number of variants while adhering to prefix rules. - {in: "sl-rozaj-biske-1994-alalc97-fonipa-fonupa-fonxsamp", lang: "sl", variants: "rozaj-biske-1994-alalc97-fonipa-fonupa-fonxsamp"}, - - // Sorting. - {in: "sl-1994-biske-rozaj", lang: "sl", variants: "rozaj-biske-1994", changed: true}, - {in: "sl-rozaj-biske-1994-alalc97-fonupa-fonipa-fonxsamp", lang: "sl", variants: "rozaj-biske-1994-alalc97-fonipa-fonupa-fonxsamp", changed: true}, - {in: "nl-fonxsamp-alalc97-fonipa-fonupa", lang: "nl", variants: "alalc97-fonipa-fonupa-fonxsamp", changed: true}, - - // Duplicates variants are removed, but not an error. - {in: "nl-fonupa-fonupa", lang: "nl", variants: "fonupa"}, - - // Variants that do not have correct prefixes. We still accept these. - {in: "de-Cyrl-1901", lang: "de", script: "Cyrl", variants: "1901"}, - {in: "sl-rozaj-lipaw-1994", lang: "sl", variants: "rozaj-lipaw-1994"}, - {in: "sl-1994-biske-rozaj-1994-biske-rozaj", lang: "sl", variants: "rozaj-biske-1994", changed: true}, - {in: "de-Cyrl-1901", lang: "de", script: "Cyrl", variants: "1901"}, - - // Invalid variant. - {in: "de-1902", lang: "de", variants: "", invalid: true}, - - {in: "EN_CYRL", lang: "en", script: "Cyrl"}, - // private use and extensions - {in: "x-a-b-c-d", ext: "x-a-b-c-d"}, - {in: "x_A.-B-C_D", ext: "x-b-c-d", invalid: true, changed: true}, - {in: "x-aa-bbbb-cccccccc-d", ext: "x-aa-bbbb-cccccccc-d"}, - {in: "en-c_cc-b-bbb-a-aaa", lang: "en", changed: true, extList: []string{"a-aaa", "b-bbb", "c-cc"}}, - {in: "en-x_cc-b-bbb-a-aaa", lang: "en", ext: "x-cc-b-bbb-a-aaa", changed: true}, - {in: "en-c_cc-b-bbb-a-aaa-x-x", lang: "en", changed: true, extList: []string{"a-aaa", "b-bbb", "c-cc", "x-x"}}, - {in: "en-v-c", lang: "en", ext: "", invalid: true}, - {in: "en-v-abcdefghi", lang: "en", ext: "", invalid: true}, - {in: "en-v-abc-x", lang: "en", ext: "v-abc", invalid: true}, - {in: "en-v-abc-x-", lang: "en", ext: "v-abc", invalid: true}, - {in: "en-v-abc-w-x-xx", lang: "en", extList: []string{"v-abc", "x-xx"}, invalid: true, changed: true}, - {in: "en-v-abc-w-y-yx", lang: "en", extList: []string{"v-abc", "y-yx"}, invalid: true, changed: true}, - {in: "en-v-c-abc", lang: "en", ext: "c-abc", invalid: true, changed: true}, - {in: "en-v-w-abc", lang: "en", ext: "w-abc", invalid: true, changed: true}, - {in: "en-v-x-abc", lang: "en", ext: "x-abc", invalid: true, changed: true}, - {in: "en-v-x-a", lang: "en", ext: "x-a", invalid: true, changed: true}, - {in: "en-9-aa-0-aa-z-bb-x-a", lang: "en", extList: []string{"0-aa", "9-aa", "z-bb", "x-a"}, changed: true}, - {in: "en-u-c", lang: "en", ext: "", invalid: true}, - {in: "en-u-co-phonebk", lang: "en", ext: "u-co-phonebk"}, - {in: "en-u-co-phonebk-ca", lang: "en", ext: "u-co-phonebk", invalid: true}, - {in: "en-u-nu-arabic-co-phonebk-ca", lang: "en", ext: "u-co-phonebk-nu-arabic", invalid: true, changed: true}, - {in: "en-u-nu-arabic-co-phonebk-ca-x", lang: "en", ext: "u-co-phonebk-nu-arabic", invalid: true, changed: true}, - {in: "en-u-nu-arabic-co-phonebk-ca-s", lang: "en", ext: "u-co-phonebk-nu-arabic", invalid: true, changed: true}, - {in: "en-u-nu-arabic-co-phonebk-ca-a12345678", lang: "en", ext: "u-co-phonebk-nu-arabic", invalid: true, changed: true}, - {in: "en-u-co-phonebook", lang: "en", ext: "", invalid: true}, - {in: "en-u-co-phonebook-cu-xau", lang: "en", ext: "u-cu-xau", invalid: true, changed: true}, - {in: "en-Cyrl-u-co-phonebk", lang: "en", script: "Cyrl", ext: "u-co-phonebk"}, - {in: "en-US-u-co-phonebk", lang: "en", region: "US", ext: "u-co-phonebk"}, - {in: "en-US-u-co-phonebk-cu-xau", lang: "en", region: "US", ext: "u-co-phonebk-cu-xau"}, - {in: "en-scotland-u-co-phonebk", lang: "en", variants: "scotland", ext: "u-co-phonebk"}, - {in: "en-u-cu-xua-co-phonebk", lang: "en", ext: "u-co-phonebk-cu-xua", changed: true}, - {in: "en-u-def-abc-cu-xua-co-phonebk", lang: "en", ext: "u-abc-def-co-phonebk-cu-xua", changed: true}, - {in: "en-u-def-abc", lang: "en", ext: "u-abc-def", changed: true}, - {in: "en-u-cu-xua-co-phonebk-a-cd", lang: "en", extList: []string{"a-cd", "u-co-phonebk-cu-xua"}, changed: true}, - // Invalid "u" extension. Drop invalid parts. - {in: "en-u-cu-co-phonebk", lang: "en", extList: []string{"u-co-phonebk"}, invalid: true, changed: true}, - {in: "en-u-cu-xau-co", lang: "en", extList: []string{"u-cu-xau"}, invalid: true}, - // We allow duplicate keys as the LDML spec does not explicitly prohibit it. - // TODO: Consider eliminating duplicates and returning an error. - {in: "en-u-cu-xau-co-phonebk-cu-xau", lang: "en", ext: "u-co-phonebk-cu-xau-cu-xau", changed: true}, - {in: "en-t-en-Cyrl-NL-fonipa", lang: "en", ext: "t-en-cyrl-nl-fonipa", changed: true}, - {in: "en-t-en-Cyrl-NL-fonipa-t0-abc-def", lang: "en", ext: "t-en-cyrl-nl-fonipa-t0-abc-def", changed: true}, - {in: "en-t-t0-abcd", lang: "en", ext: "t-t0-abcd"}, - // Not necessary to have changed here. - {in: "en-t-nl-abcd", lang: "en", ext: "t-nl", invalid: true}, - {in: "en-t-nl-latn", lang: "en", ext: "t-nl-latn"}, - {in: "en-t-t0-abcd-x-a", lang: "en", extList: []string{"t-t0-abcd", "x-a"}}, - // invalid - {in: "", lang: "und", invalid: true}, - {in: "-", lang: "und", invalid: true}, - {in: "x", lang: "und", invalid: true}, - {in: "x-", lang: "und", invalid: true}, - {in: "x--", lang: "und", invalid: true}, - {in: "a-a-b-c-d", lang: "und", invalid: true}, - {in: "en-", lang: "en", invalid: true}, - {in: "enne-", lang: "und", invalid: true}, - {in: "en.", lang: "und", invalid: true}, - {in: "en.-latn", lang: "und", invalid: true}, - {in: "en.-en", lang: "en", invalid: true}, - {in: "x-a-tooManyChars-c-d", ext: "x-a-c-d", invalid: true, changed: true}, - {in: "a-tooManyChars-c-d", lang: "und", invalid: true}, - // TODO: check key-value validity - // { in: "en-u-cu-xd", lang: "en", ext: "u-cu-xd", invalid: true }, - {in: "en-t-abcd", lang: "en", invalid: true}, - {in: "en-Latn-US-en", lang: "en", script: "Latn", region: "US", invalid: true}, - // rewrites (more tests in TestGrandfathered) - {in: "zh-min-nan", lang: "nan"}, - {in: "zh-yue", lang: "yue"}, - {in: "zh-xiang", lang: "hsn", rewrite: true}, - {in: "zh-guoyu", lang: "cmn", rewrite: true}, - {in: "iw", lang: "iw"}, - {in: "sgn-BE-FR", lang: "sfb", rewrite: true}, - {in: "i-klingon", lang: "tlh", rewrite: true}, - } - for i, tt := range tests { - tests[i].i = i - if tt.extList != nil { - tests[i].ext = strings.Join(tt.extList, "-") - } - if tt.ext != "" && tt.extList == nil { - tests[i].extList = []string{tt.ext} - } - } - return tests -} - -func TestParseExtensions(t *testing.T) { - for i, tt := range parseTests() { - if tt.ext == "" || tt.rewrite { - continue - } - scan := makeScannerString(tt.in) - if len(scan.b) > 1 && scan.b[1] != '-' { - scan.end = nextExtension(string(scan.b), 0) - scan.next = scan.end + 1 - scan.scan() - } - start := scan.start - scan.toLower(start, len(scan.b)) - parseExtensions(&scan) - ext := string(scan.b[start:]) - if ext != tt.ext { - t.Errorf("%d(%s): ext was %v; want %v", i, tt.in, ext, tt.ext) - } - if changed := !strings.HasPrefix(tt.in[start:], ext); changed != tt.changed { - t.Errorf("%d(%s): changed was %v; want %v", i, tt.in, changed, tt.changed) - } - } -} - -// partChecks runs checks for each part by calling the function returned by f. -func partChecks(t *testing.T, f func(*parseTest) (Tag, bool)) { - for i, tt := range parseTests() { - tag, skip := f(&tt) - if skip { - continue - } - if l, _ := getLangID(b(tt.lang)); l != tag.lang { - t.Errorf("%d: lang was %q; want %q", i, tag.lang, l) - } - if sc, _ := getScriptID(script, b(tt.script)); sc != tag.script { - t.Errorf("%d: script was %q; want %q", i, tag.script, sc) - } - if r, _ := getRegionID(b(tt.region)); r != tag.region { - t.Errorf("%d: region was %q; want %q", i, tag.region, r) - } - if tag.str == "" { - continue - } - p := int(tag.pVariant) - if p < int(tag.pExt) { - p++ - } - if s, g := tag.str[p:tag.pExt], tt.variants; s != g { - t.Errorf("%d: variants was %q; want %q", i, s, g) - } - p = int(tag.pExt) - if p > 0 && p < len(tag.str) { - p++ - } - if s, g := (tag.str)[p:], tt.ext; s != g { - t.Errorf("%d: extensions were %q; want %q", i, s, g) - } - } -} - -func TestParseTag(t *testing.T) { - partChecks(t, func(tt *parseTest) (id Tag, skip bool) { - if strings.HasPrefix(tt.in, "x-") || tt.rewrite { - return Tag{}, true - } - scan := makeScannerString(tt.in) - id, end := parseTag(&scan) - id.str = string(scan.b[:end]) - tt.ext = "" - tt.extList = []string{} - return id, false - }) -} - -func TestParse(t *testing.T) { - partChecks(t, func(tt *parseTest) (id Tag, skip bool) { - id, err := Raw.Parse(tt.in) - ext := "" - if id.str != "" { - if strings.HasPrefix(id.str, "x-") { - ext = id.str - } else if int(id.pExt) < len(id.str) && id.pExt > 0 { - ext = id.str[id.pExt+1:] - } - } - if tag, _ := Raw.Parse(id.String()); tag.String() != id.String() { - t.Errorf("%d:%s: reparse was %q; want %q", tt.i, tt.in, id.String(), tag.String()) - } - if ext != tt.ext { - t.Errorf("%d:%s: ext was %q; want %q", tt.i, tt.in, ext, tt.ext) - } - changed := id.str != "" && !strings.HasPrefix(tt.in, id.str) - if changed != tt.changed { - t.Errorf("%d:%s: changed was %v; want %v", tt.i, tt.in, changed, tt.changed) - } - if (err != nil) != tt.invalid { - t.Errorf("%d:%s: invalid was %v; want %v. Error: %v", tt.i, tt.in, err != nil, tt.invalid, err) - } - return id, false - }) -} - -func TestErrors(t *testing.T) { - mkInvalid := func(s string) error { - return mkErrInvalid([]byte(s)) - } - tests := []struct { - in string - out error - }{ - // invalid subtags. - {"ac", mkInvalid("ac")}, - {"AC", mkInvalid("ac")}, - {"aa-Uuuu", mkInvalid("Uuuu")}, - {"aa-AB", mkInvalid("AB")}, - // ill-formed wins over invalid. - {"ac-u", errSyntax}, - {"ac-u-ca", errSyntax}, - {"ac-u-ca-co-pinyin", errSyntax}, - {"noob", errSyntax}, - } - for _, tt := range tests { - _, err := Parse(tt.in) - if err != tt.out { - t.Errorf("%s: was %q; want %q", tt.in, err, tt.out) - } - } -} - -func TestCompose1(t *testing.T) { - partChecks(t, func(tt *parseTest) (id Tag, skip bool) { - l, _ := ParseBase(tt.lang) - s, _ := ParseScript(tt.script) - r, _ := ParseRegion(tt.region) - v := []Variant{} - for _, x := range strings.Split(tt.variants, "-") { - p, _ := ParseVariant(x) - v = append(v, p) - } - e := []Extension{} - for _, x := range tt.extList { - p, _ := ParseExtension(x) - e = append(e, p) - } - id, _ = Raw.Compose(l, s, r, v, e) - return id, false - }) -} - -func TestCompose2(t *testing.T) { - partChecks(t, func(tt *parseTest) (id Tag, skip bool) { - l, _ := ParseBase(tt.lang) - s, _ := ParseScript(tt.script) - r, _ := ParseRegion(tt.region) - p := []interface{}{l, s, r, s, r, l} - for _, x := range strings.Split(tt.variants, "-") { - v, _ := ParseVariant(x) - p = append(p, v) - } - for _, x := range tt.extList { - e, _ := ParseExtension(x) - p = append(p, e) - } - id, _ = Raw.Compose(p...) - return id, false - }) -} - -func TestCompose3(t *testing.T) { - partChecks(t, func(tt *parseTest) (id Tag, skip bool) { - id, _ = Raw.Parse(tt.in) - id, _ = Raw.Compose(id) - return id, false - }) -} - -func mk(s string) Tag { - return Raw.Make(s) -} - -func TestParseAcceptLanguage(t *testing.T) { - type res struct { - t Tag - q float32 - } - en := []res{{mk("en"), 1.0}} - tests := []struct { - out []res - in string - ok bool - }{ - {en, "en", true}, - {en, " en", true}, - {en, "en ", true}, - {en, " en ", true}, - {en, "en,", true}, - {en, ",en", true}, - {en, ",,,en,,,", true}, - {en, ",en;q=1", true}, - - // We allow an empty input, contrary to spec. - {nil, "", true}, - {[]res{{mk("aa"), 1}}, "aa;", true}, // allow unspecified weight - - // errors - {nil, ";", false}, - {nil, "$", false}, - {nil, "e;", false}, - {nil, "x;", false}, - {nil, "x", false}, - {nil, "ac", false}, // non-existing language - {nil, "aa;q", false}, - {nil, "aa;q=", false}, - {nil, "aa;q=.", false}, - - // odd fallbacks - { - []res{{mk("en"), 0.1}}, - " english ;q=.1", - true, - }, - { - []res{{mk("it"), 1.0}, {mk("de"), 1.0}, {mk("fr"), 1.0}}, - " italian, deutsch, french", - true, - }, - - // lists - { - []res{{mk("en"), 0.1}}, - "en;q=.1", - true, - }, - { - []res{{mk("mul"), 1.0}}, - "*", - true, - }, - { - []res{{mk("en"), 1.0}, {mk("de"), 1.0}}, - "en,de", - true, - }, - { - []res{{mk("en"), 1.0}, {mk("de"), .5}}, - "en,de;q=0.5", - true, - }, - { - []res{{mk("de"), 0.8}, {mk("en"), 0.5}}, - " en ; q = 0.5 , , de;q=0.8", - true, - }, - { - []res{{mk("en"), 1.0}, {mk("de"), 1.0}, {mk("fr"), 1.0}, {mk("tlh"), 1.0}}, - "en,de,fr,i-klingon", - true, - }, - // sorting - { - []res{{mk("tlh"), 0.4}, {mk("de"), 0.2}, {mk("fr"), 0.2}, {mk("en"), 0.1}}, - "en;q=0.1,de;q=0.2,fr;q=0.2,i-klingon;q=0.4", - true, - }, - // dropping - { - []res{{mk("fr"), 0.2}, {mk("en"), 0.1}}, - "en;q=0.1,de;q=0,fr;q=0.2,i-klingon;q=0.0", - true, - }, - } - for i, tt := range tests { - tags, qs, e := ParseAcceptLanguage(tt.in) - if e == nil != tt.ok { - t.Errorf("%d:%s:err: was %v; want %v", i, tt.in, e == nil, tt.ok) - } - for j, tag := range tags { - if out := tt.out[j]; !tag.equalTags(out.t) || qs[j] != out.q { - t.Errorf("%d:%s: was %s, %1f; want %s, %1f", i, tt.in, tag, qs[j], out.t, out.q) - break - } - } - } -} diff --git a/vendor/golang.org/x/text/language/tables.go b/vendor/golang.org/x/text/language/tables.go index ec17f97add..b738d457b5 100644 --- a/vendor/golang.org/x/text/language/tables.go +++ b/vendor/golang.org/x/text/language/tables.go @@ -5,11 +5,11 @@ package language import "golang.org/x/text/internal/tag" // CLDRVersion is the CLDR version from which the tables in this package are derived. -const CLDRVersion = "31" +const CLDRVersion = "32" const numLanguages = 8665 -const numScripts = 237 +const numScripts = 242 const numRegions = 357 @@ -18,7 +18,7 @@ type fromTo struct { to uint16 } -const nonCanonicalUnd = 1199 +const nonCanonicalUnd = 1201 const ( _af = 22 _am = 39 @@ -27,96 +27,96 @@ const ( _bg = 126 _bn = 165 _ca = 215 - _cs = 249 - _da = 256 - _de = 268 - _el = 309 - _en = 312 - _es = 317 - _et = 319 - _fa = 327 - _fi = 336 - _fil = 338 - _fr = 349 - _gu = 418 - _he = 442 - _hi = 444 - _hr = 463 - _hu = 467 - _hy = 469 - _id = 479 - _is = 502 - _it = 503 - _ja = 510 - _ka = 526 - _kk = 576 - _km = 584 - _kn = 591 - _ko = 594 - _ky = 648 - _lo = 694 - _lt = 702 - _lv = 709 - _mk = 765 - _ml = 770 - _mn = 777 - _mo = 782 - _mr = 793 - _ms = 797 - _mul = 804 - _my = 815 - _nb = 837 - _ne = 847 - _nl = 869 - _no = 877 - _pa = 923 - _pl = 945 - _pt = 958 - _ro = 986 - _ru = 992 - _sh = 1029 - _si = 1034 - _sk = 1040 - _sl = 1044 - _sq = 1071 - _sr = 1072 - _sv = 1090 - _sw = 1091 - _ta = 1102 - _te = 1119 - _th = 1129 - _tl = 1144 - _tn = 1150 - _tr = 1160 - _uk = 1196 - _ur = 1202 - _uz = 1210 - _vi = 1217 - _zh = 1319 - _zu = 1324 - _jbo = 513 - _ami = 1647 - _bnn = 2354 - _hak = 436 - _tlh = 14464 - _lb = 659 - _nv = 897 - _pwn = 12052 - _tao = 14185 - _tay = 14195 - _tsu = 14659 - _nn = 872 - _sfb = 13626 - _vgt = 15698 - _sgg = 13657 - _cmn = 3004 - _nan = 833 - _hsn = 465 + _cs = 250 + _da = 257 + _de = 269 + _el = 310 + _en = 313 + _es = 318 + _et = 320 + _fa = 328 + _fi = 337 + _fil = 339 + _fr = 350 + _gu = 420 + _he = 444 + _hi = 446 + _hr = 465 + _hu = 469 + _hy = 471 + _id = 481 + _is = 504 + _it = 505 + _ja = 512 + _ka = 528 + _kk = 578 + _km = 586 + _kn = 593 + _ko = 596 + _ky = 650 + _lo = 696 + _lt = 704 + _lv = 711 + _mk = 767 + _ml = 772 + _mn = 779 + _mo = 784 + _mr = 795 + _ms = 799 + _mul = 806 + _my = 817 + _nb = 839 + _ne = 849 + _nl = 871 + _no = 879 + _pa = 925 + _pl = 947 + _pt = 960 + _ro = 988 + _ru = 994 + _sh = 1031 + _si = 1036 + _sk = 1042 + _sl = 1046 + _sq = 1073 + _sr = 1074 + _sv = 1092 + _sw = 1093 + _ta = 1104 + _te = 1121 + _th = 1131 + _tl = 1146 + _tn = 1152 + _tr = 1162 + _uk = 1198 + _ur = 1204 + _uz = 1212 + _vi = 1219 + _zh = 1321 + _zu = 1327 + _jbo = 515 + _ami = 1650 + _bnn = 2357 + _hak = 438 + _tlh = 14467 + _lb = 661 + _nv = 899 + _pwn = 12055 + _tao = 14188 + _tay = 14198 + _tsu = 14662 + _nn = 874 + _sfb = 13629 + _vgt = 15701 + _sgg = 13660 + _cmn = 3007 + _nan = 835 + _hsn = 467 ) -const langPrivateStart = 0x2f6f +const langPrivateStart = 0x2f72 -const langPrivateEnd = 0x3176 +const langPrivateEnd = 0x3179 // lang holds an alphabetically sorted list of ISO-639 language identifiers. // All entries are 4 bytes. The index of the identifier (divided by 4) is the language tag. @@ -125,7 +125,7 @@ const langPrivateEnd = 0x3176 // the second and third letter of the 3-letter ISO code. // - otherwise: a 0 and a by 2 bits right-shifted index into altLangISO3. // For 3-byte language identifiers the 4th byte is 0. -const lang tag.Index = "" + // Size: 5312 bytes +const lang tag.Index = "" + // Size: 5324 bytes "---\x00aaaraai\x00aak\x00aau\x00abbkabi\x00abq\x00abr\x00abt\x00aby\x00a" + "cd\x00ace\x00ach\x00ada\x00ade\x00adj\x00ady\x00adz\x00aeveaeb\x00aey" + "\x00affragc\x00agd\x00agg\x00agm\x00ago\x00agq\x00aha\x00ahl\x00aho\x00a" + @@ -148,110 +148,110 @@ const lang tag.Index = "" + // Size: 5312 bytes "\x00bxh\x00bye\x00byn\x00byr\x00bys\x00byv\x00byx\x00bza\x00bze\x00bzf" + "\x00bzh\x00bzw\x00caatcan\x00cbj\x00cch\x00ccp\x00ceheceb\x00cfa\x00cgg" + "\x00chhachk\x00chm\x00cho\x00chp\x00chr\x00cja\x00cjm\x00cjv\x00ckb\x00c" + - "kl\x00cko\x00cky\x00cla\x00cme\x00cooscop\x00cps\x00crrecrh\x00crj\x00cr" + - "k\x00crl\x00crm\x00crs\x00csescsb\x00csw\x00ctd\x00cuhucvhvcyymdaandad" + - "\x00daf\x00dag\x00dah\x00dak\x00dar\x00dav\x00dbd\x00dbq\x00dcc\x00ddn" + - "\x00deeuded\x00den\x00dga\x00dgh\x00dgi\x00dgl\x00dgr\x00dgz\x00dia\x00d" + - "je\x00dnj\x00dob\x00doi\x00dop\x00dow\x00dri\x00drs\x00dsb\x00dtm\x00dtp" + - "\x00dts\x00dty\x00dua\x00duc\x00dud\x00dug\x00dvivdva\x00dww\x00dyo\x00d" + - "yu\x00dzzodzg\x00ebu\x00eeweefi\x00egl\x00egy\x00eka\x00eky\x00elllema" + - "\x00emi\x00enngenn\x00enq\x00eopoeri\x00es\x00\x05esu\x00etstetr\x00ett" + - "\x00etu\x00etx\x00euusewo\x00ext\x00faasfaa\x00fab\x00fag\x00fai\x00fan" + - "\x00ffulffi\x00ffm\x00fiinfia\x00fil\x00fit\x00fjijflr\x00fmp\x00foaofod" + - "\x00fon\x00for\x00fpe\x00fqs\x00frrafrc\x00frp\x00frr\x00frs\x00fub\x00f" + - "ud\x00fue\x00fuf\x00fuh\x00fuq\x00fur\x00fuv\x00fuy\x00fvr\x00fyrygalega" + - "a\x00gaf\x00gag\x00gah\x00gaj\x00gam\x00gan\x00gaw\x00gay\x00gbf\x00gbm" + - "\x00gby\x00gbz\x00gcr\x00gdlagde\x00gdn\x00gdr\x00geb\x00gej\x00gel\x00g" + - "ez\x00gfk\x00ggn\x00ghs\x00gil\x00gim\x00gjk\x00gjn\x00gju\x00gkn\x00gkp" + - "\x00gllgglk\x00gmm\x00gmv\x00gnrngnd\x00gng\x00god\x00gof\x00goi\x00gom" + - "\x00gon\x00gor\x00gos\x00got\x00grb\x00grc\x00grt\x00grw\x00gsw\x00guujg" + - "ub\x00guc\x00gud\x00gur\x00guw\x00gux\x00guz\x00gvlvgvf\x00gvr\x00gvs" + - "\x00gwc\x00gwi\x00gwt\x00gyi\x00haauhag\x00hak\x00ham\x00haw\x00haz\x00h" + - "bb\x00hdy\x00heebhhy\x00hiinhia\x00hif\x00hig\x00hih\x00hil\x00hla\x00hl" + - "u\x00hmd\x00hmt\x00hnd\x00hne\x00hnj\x00hnn\x00hno\x00homohoc\x00hoj\x00" + - "hot\x00hrrvhsb\x00hsn\x00htathuunhui\x00hyyehzerianaian\x00iar\x00iba" + - "\x00ibb\x00iby\x00ica\x00ich\x00idndidd\x00idi\x00idu\x00ieleife\x00igbo" + - "igb\x00ige\x00iiiiijj\x00ikpkikk\x00ikt\x00ikw\x00ikx\x00ilo\x00imo\x00i" + - "nndinh\x00iodoiou\x00iri\x00isslittaiukuiw\x00\x03iwm\x00iws\x00izh\x00i" + - "zi\x00japnjab\x00jam\x00jbo\x00jbu\x00jen\x00jgk\x00jgo\x00ji\x00\x06jib" + - "\x00jmc\x00jml\x00jra\x00jut\x00jvavjwavkaatkaa\x00kab\x00kac\x00kad\x00" + - "kai\x00kaj\x00kam\x00kao\x00kbd\x00kbm\x00kbp\x00kbq\x00kbx\x00kby\x00kc" + - "g\x00kck\x00kcl\x00kct\x00kde\x00kdh\x00kdl\x00kdt\x00kea\x00ken\x00kez" + - "\x00kfo\x00kfr\x00kfy\x00kgonkge\x00kgf\x00kgp\x00kha\x00khb\x00khn\x00k" + - "hq\x00khs\x00kht\x00khw\x00khz\x00kiikkij\x00kiu\x00kiw\x00kjuakjd\x00kj" + - "g\x00kjs\x00kjy\x00kkazkkc\x00kkj\x00klalkln\x00klq\x00klt\x00klx\x00kmh" + - "mkmb\x00kmh\x00kmo\x00kms\x00kmu\x00kmw\x00knanknf\x00knp\x00koorkoi\x00" + - "kok\x00kol\x00kos\x00koz\x00kpe\x00kpf\x00kpo\x00kpr\x00kpx\x00kqb\x00kq" + - "f\x00kqs\x00kqy\x00kraukrc\x00kri\x00krj\x00krl\x00krs\x00kru\x00ksasksb" + - "\x00ksd\x00ksf\x00ksh\x00ksj\x00ksr\x00ktb\x00ktm\x00kto\x00kuurkub\x00k" + - "ud\x00kue\x00kuj\x00kum\x00kun\x00kup\x00kus\x00kvomkvg\x00kvr\x00kvx" + - "\x00kw\x00\x01kwj\x00kwo\x00kxa\x00kxc\x00kxm\x00kxp\x00kxw\x00kxz\x00ky" + - "irkye\x00kyx\x00kzr\x00laatlab\x00lad\x00lag\x00lah\x00laj\x00las\x00lbt" + - "zlbe\x00lbu\x00lbw\x00lcm\x00lcp\x00ldb\x00led\x00lee\x00lem\x00lep\x00l" + - "eq\x00leu\x00lez\x00lguglgg\x00liimlia\x00lid\x00lif\x00lig\x00lih\x00li" + - "j\x00lis\x00ljp\x00lki\x00lkt\x00lle\x00lln\x00lmn\x00lmo\x00lmp\x00lnin" + - "lns\x00lnu\x00loaoloj\x00lok\x00lol\x00lor\x00los\x00loz\x00lrc\x00ltitl" + - "tg\x00luublua\x00luo\x00luy\x00luz\x00lvavlwl\x00lzh\x00lzz\x00mad\x00ma" + - "f\x00mag\x00mai\x00mak\x00man\x00mas\x00maw\x00maz\x00mbh\x00mbo\x00mbq" + - "\x00mbu\x00mbw\x00mci\x00mcp\x00mcq\x00mcr\x00mcu\x00mda\x00mde\x00mdf" + - "\x00mdh\x00mdj\x00mdr\x00mdx\x00med\x00mee\x00mek\x00men\x00mer\x00met" + - "\x00meu\x00mfa\x00mfe\x00mfn\x00mfo\x00mfq\x00mglgmgh\x00mgl\x00mgo\x00m" + - "gp\x00mgy\x00mhahmhi\x00mhl\x00mirimif\x00min\x00mis\x00miw\x00mkkdmki" + - "\x00mkl\x00mkp\x00mkw\x00mlalmle\x00mlp\x00mls\x00mmo\x00mmu\x00mmx\x00m" + - "nonmna\x00mnf\x00mni\x00mnw\x00moolmoa\x00moe\x00moh\x00mos\x00mox\x00mp" + - "p\x00mps\x00mpt\x00mpx\x00mql\x00mrarmrd\x00mrj\x00mro\x00mssamtltmtc" + - "\x00mtf\x00mti\x00mtr\x00mua\x00mul\x00mur\x00mus\x00mva\x00mvn\x00mvy" + - "\x00mwk\x00mwr\x00mwv\x00mxc\x00mxm\x00myyamyk\x00mym\x00myv\x00myw\x00m" + - "yx\x00myz\x00mzk\x00mzm\x00mzn\x00mzp\x00mzw\x00mzz\x00naaunac\x00naf" + - "\x00nah\x00nak\x00nan\x00nap\x00naq\x00nas\x00nbobnca\x00nce\x00ncf\x00n" + - "ch\x00nco\x00ncu\x00nddendc\x00nds\x00neepneb\x00new\x00nex\x00nfr\x00ng" + - "donga\x00ngb\x00ngl\x00nhb\x00nhe\x00nhw\x00nif\x00nii\x00nij\x00nin\x00" + - "niu\x00niy\x00niz\x00njo\x00nkg\x00nko\x00nlldnmg\x00nmz\x00nnnonnf\x00n" + - "nh\x00nnk\x00nnm\x00noornod\x00noe\x00non\x00nop\x00nou\x00nqo\x00nrblnr" + - "b\x00nsk\x00nsn\x00nso\x00nss\x00ntm\x00ntr\x00nui\x00nup\x00nus\x00nuv" + - "\x00nux\x00nvavnwb\x00nxq\x00nxr\x00nyyanym\x00nyn\x00nzi\x00occiogc\x00" + - "ojjiokr\x00okv\x00omrmong\x00onn\x00ons\x00opm\x00orrioro\x00oru\x00osss" + - "osa\x00ota\x00otk\x00ozm\x00paanpag\x00pal\x00pam\x00pap\x00pau\x00pbi" + - "\x00pcd\x00pcm\x00pdc\x00pdt\x00ped\x00peo\x00pex\x00pfl\x00phl\x00phn" + - "\x00pilipil\x00pip\x00pka\x00pko\x00plolpla\x00pms\x00png\x00pnn\x00pnt" + - "\x00pon\x00ppo\x00pra\x00prd\x00prg\x00psuspss\x00ptorptp\x00puu\x00pwa" + - "\x00quuequc\x00qug\x00rai\x00raj\x00rao\x00rcf\x00rej\x00rel\x00res\x00r" + - "gn\x00rhg\x00ria\x00rif\x00rjs\x00rkt\x00rmohrmf\x00rmo\x00rmt\x00rmu" + - "\x00rnunrna\x00rng\x00roonrob\x00rof\x00roo\x00rro\x00rtm\x00ruusrue\x00" + - "rug\x00rw\x00\x04rwk\x00rwo\x00ryu\x00saansaf\x00sah\x00saq\x00sas\x00sa" + - "t\x00sav\x00saz\x00sba\x00sbe\x00sbp\x00scrdsck\x00scl\x00scn\x00sco\x00" + - "scs\x00sdndsdc\x00sdh\x00semesef\x00seh\x00sei\x00ses\x00sgagsga\x00sgs" + - "\x00sgw\x00sgz\x00sh\x00\x02shi\x00shk\x00shn\x00shu\x00siinsid\x00sig" + - "\x00sil\x00sim\x00sjr\x00sklkskc\x00skr\x00sks\x00sllvsld\x00sli\x00sll" + - "\x00sly\x00smmosma\x00smi\x00smj\x00smn\x00smp\x00smq\x00sms\x00snnasnc" + - "\x00snk\x00snp\x00snx\x00sny\x00soomsok\x00soq\x00sou\x00soy\x00spd\x00s" + - "pl\x00sps\x00sqqisrrpsrb\x00srn\x00srr\x00srx\x00ssswssd\x00ssg\x00ssy" + - "\x00stotstk\x00stq\x00suunsua\x00sue\x00suk\x00sur\x00sus\x00svweswwaswb" + - "\x00swc\x00swg\x00swp\x00swv\x00sxn\x00sxw\x00syl\x00syr\x00szl\x00taamt" + - "aj\x00tal\x00tan\x00taq\x00tbc\x00tbd\x00tbf\x00tbg\x00tbo\x00tbw\x00tbz" + - "\x00tci\x00tcy\x00tdd\x00tdg\x00tdh\x00teelted\x00tem\x00teo\x00tet\x00t" + - "fi\x00tggktgc\x00tgo\x00tgu\x00thhathl\x00thq\x00thr\x00tiirtif\x00tig" + - "\x00tik\x00tim\x00tio\x00tiv\x00tkuktkl\x00tkr\x00tkt\x00tlgltlf\x00tlx" + - "\x00tly\x00tmh\x00tmy\x00tnsntnh\x00toontof\x00tog\x00toq\x00tpi\x00tpm" + - "\x00tpz\x00tqo\x00trurtru\x00trv\x00trw\x00tssotsd\x00tsf\x00tsg\x00tsj" + - "\x00tsw\x00ttatttd\x00tte\x00ttj\x00ttr\x00tts\x00ttt\x00tuh\x00tul\x00t" + - "um\x00tuq\x00tvd\x00tvl\x00tvu\x00twwitwh\x00twq\x00txg\x00tyahtya\x00ty" + - "v\x00tzm\x00ubu\x00udm\x00ugiguga\x00ukkruli\x00umb\x00und\x00unr\x00unx" + - "\x00urrduri\x00urt\x00urw\x00usa\x00utr\x00uvh\x00uvl\x00uzzbvag\x00vai" + - "\x00van\x00veenvec\x00vep\x00viievic\x00viv\x00vls\x00vmf\x00vmw\x00vool" + - "vot\x00vro\x00vun\x00vut\x00walnwae\x00waj\x00wal\x00wan\x00war\x00wbp" + - "\x00wbq\x00wbr\x00wci\x00wer\x00wgi\x00whg\x00wib\x00wiu\x00wiv\x00wja" + - "\x00wji\x00wls\x00wmo\x00wnc\x00wni\x00wnu\x00woolwob\x00wos\x00wrs\x00w" + - "sk\x00wtm\x00wuu\x00wuv\x00wwa\x00xav\x00xbi\x00xcr\x00xes\x00xhhoxla" + - "\x00xlc\x00xld\x00xmf\x00xmn\x00xmr\x00xna\x00xnr\x00xog\x00xon\x00xpr" + - "\x00xrb\x00xsa\x00xsi\x00xsm\x00xsr\x00xwe\x00yam\x00yao\x00yap\x00yas" + - "\x00yat\x00yav\x00yay\x00yaz\x00yba\x00ybb\x00yby\x00yer\x00ygr\x00ygw" + - "\x00yiidyko\x00yle\x00ylg\x00yll\x00yml\x00yooryon\x00yrb\x00yre\x00yrl" + - "\x00yss\x00yua\x00yue\x00yuj\x00yut\x00yuw\x00zahazag\x00zbl\x00zdj\x00z" + - "ea\x00zgh\x00zhhozia\x00zlm\x00zmi\x00zne\x00zuulzxx\x00zza\x00\xff\xff" + - "\xff\xff" + "kl\x00cko\x00cky\x00cla\x00cme\x00cmg\x00cooscop\x00cps\x00crrecrh\x00cr" + + "j\x00crk\x00crl\x00crm\x00crs\x00csescsb\x00csw\x00ctd\x00cuhucvhvcyymda" + + "andad\x00daf\x00dag\x00dah\x00dak\x00dar\x00dav\x00dbd\x00dbq\x00dcc\x00" + + "ddn\x00deeuded\x00den\x00dga\x00dgh\x00dgi\x00dgl\x00dgr\x00dgz\x00dia" + + "\x00dje\x00dnj\x00dob\x00doi\x00dop\x00dow\x00dri\x00drs\x00dsb\x00dtm" + + "\x00dtp\x00dts\x00dty\x00dua\x00duc\x00dud\x00dug\x00dvivdva\x00dww\x00d" + + "yo\x00dyu\x00dzzodzg\x00ebu\x00eeweefi\x00egl\x00egy\x00eka\x00eky\x00el" + + "llema\x00emi\x00enngenn\x00enq\x00eopoeri\x00es\x00\x05esu\x00etstetr" + + "\x00ett\x00etu\x00etx\x00euusewo\x00ext\x00faasfaa\x00fab\x00fag\x00fai" + + "\x00fan\x00ffulffi\x00ffm\x00fiinfia\x00fil\x00fit\x00fjijflr\x00fmp\x00" + + "foaofod\x00fon\x00for\x00fpe\x00fqs\x00frrafrc\x00frp\x00frr\x00frs\x00f" + + "ub\x00fud\x00fue\x00fuf\x00fuh\x00fuq\x00fur\x00fuv\x00fuy\x00fvr\x00fyr" + + "ygalegaa\x00gaf\x00gag\x00gah\x00gaj\x00gam\x00gan\x00gaw\x00gay\x00gba" + + "\x00gbf\x00gbm\x00gby\x00gbz\x00gcr\x00gdlagde\x00gdn\x00gdr\x00geb\x00g" + + "ej\x00gel\x00gez\x00gfk\x00ggn\x00ghs\x00gil\x00gim\x00gjk\x00gjn\x00gju" + + "\x00gkn\x00gkp\x00gllgglk\x00gmm\x00gmv\x00gnrngnd\x00gng\x00god\x00gof" + + "\x00goi\x00gom\x00gon\x00gor\x00gos\x00got\x00grb\x00grc\x00grt\x00grw" + + "\x00gsw\x00guujgub\x00guc\x00gud\x00gur\x00guw\x00gux\x00guz\x00gvlvgvf" + + "\x00gvr\x00gvs\x00gwc\x00gwi\x00gwt\x00gyi\x00haauhag\x00hak\x00ham\x00h" + + "aw\x00haz\x00hbb\x00hdy\x00heebhhy\x00hiinhia\x00hif\x00hig\x00hih\x00hi" + + "l\x00hla\x00hlu\x00hmd\x00hmt\x00hnd\x00hne\x00hnj\x00hnn\x00hno\x00homo" + + "hoc\x00hoj\x00hot\x00hrrvhsb\x00hsn\x00htathuunhui\x00hyyehzerianaian" + + "\x00iar\x00iba\x00ibb\x00iby\x00ica\x00ich\x00idndidd\x00idi\x00idu\x00i" + + "eleife\x00igboigb\x00ige\x00iiiiijj\x00ikpkikk\x00ikt\x00ikw\x00ikx\x00i" + + "lo\x00imo\x00inndinh\x00iodoiou\x00iri\x00isslittaiukuiw\x00\x03iwm\x00i" + + "ws\x00izh\x00izi\x00japnjab\x00jam\x00jbo\x00jbu\x00jen\x00jgk\x00jgo" + + "\x00ji\x00\x06jib\x00jmc\x00jml\x00jra\x00jut\x00jvavjwavkaatkaa\x00kab" + + "\x00kac\x00kad\x00kai\x00kaj\x00kam\x00kao\x00kbd\x00kbm\x00kbp\x00kbq" + + "\x00kbx\x00kby\x00kcg\x00kck\x00kcl\x00kct\x00kde\x00kdh\x00kdl\x00kdt" + + "\x00kea\x00ken\x00kez\x00kfo\x00kfr\x00kfy\x00kgonkge\x00kgf\x00kgp\x00k" + + "ha\x00khb\x00khn\x00khq\x00khs\x00kht\x00khw\x00khz\x00kiikkij\x00kiu" + + "\x00kiw\x00kjuakjd\x00kjg\x00kjs\x00kjy\x00kkazkkc\x00kkj\x00klalkln\x00" + + "klq\x00klt\x00klx\x00kmhmkmb\x00kmh\x00kmo\x00kms\x00kmu\x00kmw\x00knank" + + "nf\x00knp\x00koorkoi\x00kok\x00kol\x00kos\x00koz\x00kpe\x00kpf\x00kpo" + + "\x00kpr\x00kpx\x00kqb\x00kqf\x00kqs\x00kqy\x00kraukrc\x00kri\x00krj\x00k" + + "rl\x00krs\x00kru\x00ksasksb\x00ksd\x00ksf\x00ksh\x00ksj\x00ksr\x00ktb" + + "\x00ktm\x00kto\x00kuurkub\x00kud\x00kue\x00kuj\x00kum\x00kun\x00kup\x00k" + + "us\x00kvomkvg\x00kvr\x00kvx\x00kw\x00\x01kwj\x00kwo\x00kxa\x00kxc\x00kxm" + + "\x00kxp\x00kxw\x00kxz\x00kyirkye\x00kyx\x00kzr\x00laatlab\x00lad\x00lag" + + "\x00lah\x00laj\x00las\x00lbtzlbe\x00lbu\x00lbw\x00lcm\x00lcp\x00ldb\x00l" + + "ed\x00lee\x00lem\x00lep\x00leq\x00leu\x00lez\x00lguglgg\x00liimlia\x00li" + + "d\x00lif\x00lig\x00lih\x00lij\x00lis\x00ljp\x00lki\x00lkt\x00lle\x00lln" + + "\x00lmn\x00lmo\x00lmp\x00lninlns\x00lnu\x00loaoloj\x00lok\x00lol\x00lor" + + "\x00los\x00loz\x00lrc\x00ltitltg\x00luublua\x00luo\x00luy\x00luz\x00lvav" + + "lwl\x00lzh\x00lzz\x00mad\x00maf\x00mag\x00mai\x00mak\x00man\x00mas\x00ma" + + "w\x00maz\x00mbh\x00mbo\x00mbq\x00mbu\x00mbw\x00mci\x00mcp\x00mcq\x00mcr" + + "\x00mcu\x00mda\x00mde\x00mdf\x00mdh\x00mdj\x00mdr\x00mdx\x00med\x00mee" + + "\x00mek\x00men\x00mer\x00met\x00meu\x00mfa\x00mfe\x00mfn\x00mfo\x00mfq" + + "\x00mglgmgh\x00mgl\x00mgo\x00mgp\x00mgy\x00mhahmhi\x00mhl\x00mirimif\x00" + + "min\x00mis\x00miw\x00mkkdmki\x00mkl\x00mkp\x00mkw\x00mlalmle\x00mlp\x00m" + + "ls\x00mmo\x00mmu\x00mmx\x00mnonmna\x00mnf\x00mni\x00mnw\x00moolmoa\x00mo" + + "e\x00moh\x00mos\x00mox\x00mpp\x00mps\x00mpt\x00mpx\x00mql\x00mrarmrd\x00" + + "mrj\x00mro\x00mssamtltmtc\x00mtf\x00mti\x00mtr\x00mua\x00mul\x00mur\x00m" + + "us\x00mva\x00mvn\x00mvy\x00mwk\x00mwr\x00mwv\x00mxc\x00mxm\x00myyamyk" + + "\x00mym\x00myv\x00myw\x00myx\x00myz\x00mzk\x00mzm\x00mzn\x00mzp\x00mzw" + + "\x00mzz\x00naaunac\x00naf\x00nah\x00nak\x00nan\x00nap\x00naq\x00nas\x00n" + + "bobnca\x00nce\x00ncf\x00nch\x00nco\x00ncu\x00nddendc\x00nds\x00neepneb" + + "\x00new\x00nex\x00nfr\x00ngdonga\x00ngb\x00ngl\x00nhb\x00nhe\x00nhw\x00n" + + "if\x00nii\x00nij\x00nin\x00niu\x00niy\x00niz\x00njo\x00nkg\x00nko\x00nll" + + "dnmg\x00nmz\x00nnnonnf\x00nnh\x00nnk\x00nnm\x00noornod\x00noe\x00non\x00" + + "nop\x00nou\x00nqo\x00nrblnrb\x00nsk\x00nsn\x00nso\x00nss\x00ntm\x00ntr" + + "\x00nui\x00nup\x00nus\x00nuv\x00nux\x00nvavnwb\x00nxq\x00nxr\x00nyyanym" + + "\x00nyn\x00nzi\x00occiogc\x00ojjiokr\x00okv\x00omrmong\x00onn\x00ons\x00" + + "opm\x00orrioro\x00oru\x00osssosa\x00ota\x00otk\x00ozm\x00paanpag\x00pal" + + "\x00pam\x00pap\x00pau\x00pbi\x00pcd\x00pcm\x00pdc\x00pdt\x00ped\x00peo" + + "\x00pex\x00pfl\x00phl\x00phn\x00pilipil\x00pip\x00pka\x00pko\x00plolpla" + + "\x00pms\x00png\x00pnn\x00pnt\x00pon\x00ppo\x00pra\x00prd\x00prg\x00psusp" + + "ss\x00ptorptp\x00puu\x00pwa\x00quuequc\x00qug\x00rai\x00raj\x00rao\x00rc" + + "f\x00rej\x00rel\x00res\x00rgn\x00rhg\x00ria\x00rif\x00rjs\x00rkt\x00rmoh" + + "rmf\x00rmo\x00rmt\x00rmu\x00rnunrna\x00rng\x00roonrob\x00rof\x00roo\x00r" + + "ro\x00rtm\x00ruusrue\x00rug\x00rw\x00\x04rwk\x00rwo\x00ryu\x00saansaf" + + "\x00sah\x00saq\x00sas\x00sat\x00sav\x00saz\x00sba\x00sbe\x00sbp\x00scrds" + + "ck\x00scl\x00scn\x00sco\x00scs\x00sdndsdc\x00sdh\x00semesef\x00seh\x00se" + + "i\x00ses\x00sgagsga\x00sgs\x00sgw\x00sgz\x00sh\x00\x02shi\x00shk\x00shn" + + "\x00shu\x00siinsid\x00sig\x00sil\x00sim\x00sjr\x00sklkskc\x00skr\x00sks" + + "\x00sllvsld\x00sli\x00sll\x00sly\x00smmosma\x00smi\x00smj\x00smn\x00smp" + + "\x00smq\x00sms\x00snnasnc\x00snk\x00snp\x00snx\x00sny\x00soomsok\x00soq" + + "\x00sou\x00soy\x00spd\x00spl\x00sps\x00sqqisrrpsrb\x00srn\x00srr\x00srx" + + "\x00ssswssd\x00ssg\x00ssy\x00stotstk\x00stq\x00suunsua\x00sue\x00suk\x00" + + "sur\x00sus\x00svweswwaswb\x00swc\x00swg\x00swp\x00swv\x00sxn\x00sxw\x00s" + + "yl\x00syr\x00szl\x00taamtaj\x00tal\x00tan\x00taq\x00tbc\x00tbd\x00tbf" + + "\x00tbg\x00tbo\x00tbw\x00tbz\x00tci\x00tcy\x00tdd\x00tdg\x00tdh\x00teelt" + + "ed\x00tem\x00teo\x00tet\x00tfi\x00tggktgc\x00tgo\x00tgu\x00thhathl\x00th" + + "q\x00thr\x00tiirtif\x00tig\x00tik\x00tim\x00tio\x00tiv\x00tkuktkl\x00tkr" + + "\x00tkt\x00tlgltlf\x00tlx\x00tly\x00tmh\x00tmy\x00tnsntnh\x00toontof\x00" + + "tog\x00toq\x00tpi\x00tpm\x00tpz\x00tqo\x00trurtru\x00trv\x00trw\x00tssot" + + "sd\x00tsf\x00tsg\x00tsj\x00tsw\x00ttatttd\x00tte\x00ttj\x00ttr\x00tts" + + "\x00ttt\x00tuh\x00tul\x00tum\x00tuq\x00tvd\x00tvl\x00tvu\x00twwitwh\x00t" + + "wq\x00txg\x00tyahtya\x00tyv\x00tzm\x00ubu\x00udm\x00ugiguga\x00ukkruli" + + "\x00umb\x00und\x00unr\x00unx\x00urrduri\x00urt\x00urw\x00usa\x00utr\x00u" + + "vh\x00uvl\x00uzzbvag\x00vai\x00van\x00veenvec\x00vep\x00viievic\x00viv" + + "\x00vls\x00vmf\x00vmw\x00voolvot\x00vro\x00vun\x00vut\x00walnwae\x00waj" + + "\x00wal\x00wan\x00war\x00wbp\x00wbq\x00wbr\x00wci\x00wer\x00wgi\x00whg" + + "\x00wib\x00wiu\x00wiv\x00wja\x00wji\x00wls\x00wmo\x00wnc\x00wni\x00wnu" + + "\x00woolwob\x00wos\x00wrs\x00wsk\x00wtm\x00wuu\x00wuv\x00wwa\x00xav\x00x" + + "bi\x00xcr\x00xes\x00xhhoxla\x00xlc\x00xld\x00xmf\x00xmn\x00xmr\x00xna" + + "\x00xnr\x00xog\x00xon\x00xpr\x00xrb\x00xsa\x00xsi\x00xsm\x00xsr\x00xwe" + + "\x00yam\x00yao\x00yap\x00yas\x00yat\x00yav\x00yay\x00yaz\x00yba\x00ybb" + + "\x00yby\x00yer\x00ygr\x00ygw\x00yiidyko\x00yle\x00ylg\x00yll\x00yml\x00y" + + "ooryon\x00yrb\x00yre\x00yrl\x00yss\x00yua\x00yue\x00yuj\x00yut\x00yuw" + + "\x00zahazag\x00zbl\x00zdj\x00zea\x00zgh\x00zhhozhx\x00zia\x00zlm\x00zmi" + + "\x00zne\x00zuulzxx\x00zza\x00\xff\xff\xff\xff" -const langNoIndexOffset = 1327 +const langNoIndexOffset = 1330 // langNoIndex is a bit vector of all 3-letter language codes that are not used as an index // in lookup tables. The language ids for these language codes are derived directly @@ -288,7 +288,7 @@ var langNoIndex = [2197]uint8{ // Entry C0 - FF 0xfb, 0x4a, 0xf2, 0x9f, 0xb4, 0x42, 0x41, 0x96, 0x1b, 0x14, 0x08, 0xf2, 0x2b, 0xe7, 0x17, 0x56, - 0x45, 0x7d, 0x0e, 0x1c, 0x37, 0x71, 0xf3, 0xef, + 0x05, 0x7d, 0x0e, 0x1c, 0x37, 0x71, 0xf3, 0xef, 0x97, 0xff, 0x5d, 0x38, 0x64, 0x08, 0x00, 0x10, 0xbc, 0x85, 0xaf, 0xdf, 0xff, 0xf7, 0x73, 0x35, 0x3e, 0x87, 0xc7, 0xdf, 0xff, 0x00, 0x81, 0x00, @@ -329,7 +329,7 @@ var langNoIndex = [2197]uint8{ 0x02, 0x10, 0x08, 0x04, 0x00, 0x00, 0x00, 0x40, 0x30, 0x83, 0x01, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x1e, 0xcd, 0xbf, 0x7e, 0xbf, + 0x00, 0x00, 0x00, 0x1e, 0xcd, 0xbf, 0x7a, 0xbf, // Entry 200 - 23F 0xdf, 0xc3, 0x83, 0x82, 0xc0, 0xfb, 0x57, 0x27, 0xcd, 0x55, 0xe7, 0x01, 0x00, 0x20, 0xb2, 0xc5, @@ -559,7 +559,7 @@ var langNoIndex = [2197]uint8{ 0xf0, 0xfb, 0xfd, 0x3f, 0x05, 0x00, 0x12, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x02, 0x00, 0x00, 0x00, 0x00, 0x03, 0x30, 0x02, 0x28, - 0x84, 0x00, 0x23, 0xc0, 0x23, 0x24, 0x00, 0x00, + 0x84, 0x00, 0x21, 0xc0, 0x23, 0x24, 0x00, 0x00, 0x00, 0xcb, 0xe4, 0x3a, 0x42, 0x88, 0x14, 0xf1, 0xef, 0xff, 0x7f, 0x12, 0x01, 0x01, 0x84, 0x50, 0x07, 0xfc, 0xff, 0xff, 0x0f, 0x01, 0x00, 0x40, @@ -578,176 +578,176 @@ const altLangISO3 tag.Index = "---\x00cor\x00hbs\x01heb\x02kin\x03spa\x04yid\x05 // altLangIndex is used to convert indexes in altLangISO3 to langIDs. // Size: 12 bytes, 6 elements var altLangIndex = [6]uint16{ - 0x027f, 0x0405, 0x01f9, 0x03e3, 0x013d, 0x0206, + 0x0281, 0x0407, 0x01fb, 0x03e5, 0x013e, 0x0208, } // langAliasMap maps langIDs to their suggested replacements. // Size: 656 bytes, 164 elements var langAliasMap = [164]fromTo{ 0: {from: 0x82, to: 0x88}, - 1: {from: 0x185, to: 0x1ac}, - 2: {from: 0x1f1, to: 0x1df}, - 3: {from: 0x1f9, to: 0x1ba}, - 4: {from: 0x206, to: 0x510}, - 5: {from: 0x20d, to: 0x20c}, - 6: {from: 0x30e, to: 0x3da}, - 7: {from: 0x345, to: 0x36d}, - 8: {from: 0x405, to: 0x430}, - 9: {from: 0x478, to: 0x152}, - 10: {from: 0x48e, to: 0x44f}, - 11: {from: 0x4a0, to: 0x21}, - 12: {from: 0x53b, to: 0x541}, - 13: {from: 0x58c, to: 0x12c}, - 14: {from: 0x62d, to: 0x1eae}, - 15: {from: 0x64e, to: 0x42f}, - 16: {from: 0x65f, to: 0x42f}, - 17: {from: 0x6ea, to: 0x3a}, - 18: {from: 0x6f5, to: 0x1d5}, - 19: {from: 0x73b, to: 0x219e}, - 20: {from: 0x7b0, to: 0x56}, - 21: {from: 0x7b6, to: 0x2998}, - 22: {from: 0x7c2, to: 0x58}, - 23: {from: 0x7e3, to: 0x144}, - 24: {from: 0x809, to: 0x5a}, - 25: {from: 0x812, to: 0x8d}, - 26: {from: 0x87b, to: 0x80d}, - 27: {from: 0x8c0, to: 0xee0}, - 28: {from: 0x9ec, to: 0x32f}, - 29: {from: 0xa33, to: 0x2c3}, - 30: {from: 0xa3a, to: 0xbf}, - 31: {from: 0xabb, to: 0x331f}, - 32: {from: 0xb35, to: 0x527}, - 33: {from: 0xb72, to: 0x2657}, - 34: {from: 0xb7b, to: 0xbc0}, - 35: {from: 0xb98, to: 0x44c}, - 36: {from: 0xbb9, to: 0x4226}, - 37: {from: 0xbbc, to: 0x527}, - 38: {from: 0xbfb, to: 0x2da4}, - 39: {from: 0xc2b, to: 0x317e}, - 40: {from: 0xcb6, to: 0xf2}, - 41: {from: 0xd05, to: 0xf9}, - 42: {from: 0xdc5, to: 0x119}, - 43: {from: 0xdd4, to: 0x32b}, - 44: {from: 0xdf5, to: 0xdf8}, - 45: {from: 0xdfb, to: 0x52e}, - 46: {from: 0xedc, to: 0x2057}, - 47: {from: 0xeeb, to: 0x2e97}, - 48: {from: 0xf36, to: 0x365}, - 49: {from: 0x10cd, to: 0x13f}, - 50: {from: 0x1101, to: 0x2ce}, - 51: {from: 0x119d, to: 0x1ea}, - 52: {from: 0x1276, to: 0x21}, - 53: {from: 0x1421, to: 0x15d}, - 54: {from: 0x146d, to: 0x14d}, - 55: {from: 0x151c, to: 0xd98}, - 56: {from: 0x1520, to: 0x38e}, - 57: {from: 0x152f, to: 0x19d}, - 58: {from: 0x157d, to: 0x20e}, - 59: {from: 0x1580, to: 0x10c}, - 60: {from: 0x15a0, to: 0x3cac}, - 61: {from: 0x1667, to: 0x199}, - 62: {from: 0x16c5, to: 0x135}, - 63: {from: 0x16fd, to: 0x29f5}, - 64: {from: 0x1715, to: 0x192}, - 65: {from: 0x1724, to: 0xf3c}, - 66: {from: 0x1777, to: 0x1521}, - 67: {from: 0x1806, to: 0x17b3}, - 68: {from: 0x1813, to: 0x18f0}, - 69: {from: 0x1887, to: 0x434}, - 70: {from: 0x1976, to: 0x1cfe}, - 71: {from: 0x1a71, to: 0x2bad}, - 72: {from: 0x1a87, to: 0x1f6}, - 73: {from: 0x1b57, to: 0x1f8}, - 74: {from: 0x1b83, to: 0x1512}, - 75: {from: 0x1d61, to: 0x2c98}, - 76: {from: 0x2035, to: 0x37ae}, - 77: {from: 0x203a, to: 0x20da}, - 78: {from: 0x2057, to: 0x309}, - 79: {from: 0x20e0, to: 0x272}, - 80: {from: 0x20eb, to: 0x261}, - 81: {from: 0x20ef, to: 0x22b}, - 82: {from: 0x20f6, to: 0x254}, - 83: {from: 0x210c, to: 0x21e8}, - 84: {from: 0x2132, to: 0x27b}, - 85: {from: 0x215d, to: 0x910}, - 86: {from: 0x2196, to: 0x120}, - 87: {from: 0x21cb, to: 0x155e}, - 88: {from: 0x21e3, to: 0x502}, - 89: {from: 0x21f1, to: 0x49d}, - 90: {from: 0x222a, to: 0x120}, - 91: {from: 0x2234, to: 0x120}, - 92: {from: 0x225f, to: 0x927}, - 93: {from: 0x2313, to: 0x3223}, - 94: {from: 0x237f, to: 0x3362}, - 95: {from: 0x246f, to: 0x2c5}, - 96: {from: 0x24e1, to: 0x2fd}, - 97: {from: 0x24ed, to: 0x2f8}, - 98: {from: 0x24f7, to: 0x31d}, - 99: {from: 0x254d, to: 0xb58}, - 100: {from: 0x25a6, to: 0xe2}, - 101: {from: 0x263b, to: 0x2ce}, - 102: {from: 0x26c6, to: 0x26b1}, - 103: {from: 0x26f6, to: 0x3c6}, - 104: {from: 0x2724, to: 0x3cac}, - 105: {from: 0x2762, to: 0x26b1}, - 106: {from: 0x2786, to: 0x4355}, - 107: {from: 0x28ec, to: 0x2834}, - 108: {from: 0x2911, to: 0x34f}, - 109: {from: 0x2983, to: 0x2da4}, - 110: {from: 0x2b17, to: 0x38b}, - 111: {from: 0x2bf9, to: 0x393}, - 112: {from: 0x2c3c, to: 0x3cac}, - 113: {from: 0x2cf9, to: 0x3bc}, - 114: {from: 0x2d10, to: 0x594}, - 115: {from: 0x2d44, to: 0x147}, - 116: {from: 0x2d45, to: 0x147}, - 117: {from: 0x2dfc, to: 0x2ef}, - 118: {from: 0x2e05, to: 0x19c9}, - 119: {from: 0x2e17, to: 0x2d92}, - 120: {from: 0x2e1e, to: 0x290}, - 121: {from: 0x2e51, to: 0x7d}, - 122: {from: 0x2e62, to: 0x227f}, - 123: {from: 0x2e9d, to: 0x2e98}, - 124: {from: 0x2eec, to: 0x2ed4}, - 125: {from: 0x3190, to: 0x3c2}, - 126: {from: 0x3363, to: 0x338b}, - 127: {from: 0x3427, to: 0x3da}, - 128: {from: 0x34eb, to: 0x18cd}, - 129: {from: 0x35c5, to: 0x2c98}, - 130: {from: 0x35e3, to: 0x410}, - 131: {from: 0x3655, to: 0x244}, - 132: {from: 0x3673, to: 0x3f2}, - 133: {from: 0x36fa, to: 0x443}, - 134: {from: 0x37bd, to: 0x120}, - 135: {from: 0x3813, to: 0x38ef}, - 136: {from: 0x3828, to: 0x2c98}, - 137: {from: 0x382c, to: 0xa9}, - 138: {from: 0x382f, to: 0x3225}, - 139: {from: 0x3869, to: 0x39a3}, - 140: {from: 0x388f, to: 0x3fbd}, - 141: {from: 0x38a2, to: 0x39d4}, - 142: {from: 0x38b1, to: 0x1fa1}, - 143: {from: 0x38b2, to: 0x2e97}, - 144: {from: 0x3959, to: 0x47c}, - 145: {from: 0x3b4b, to: 0xd8e}, - 146: {from: 0x3b75, to: 0x136}, - 147: {from: 0x3c96, to: 0x4ba}, - 148: {from: 0x3fba, to: 0xff}, - 149: {from: 0x4205, to: 0xa8e}, - 150: {from: 0x42bb, to: 0x570}, - 151: {from: 0x42f6, to: 0x3f5d}, - 152: {from: 0x4375, to: 0x258}, - 153: {from: 0x43c8, to: 0x36c8}, - 154: {from: 0x43ca, to: 0x10e}, - 155: {from: 0x44ac, to: 0x331f}, - 156: {from: 0x44e0, to: 0x510}, - 157: {from: 0x45c7, to: 0x2406}, - 158: {from: 0x45da, to: 0x26d9}, - 159: {from: 0x460d, to: 0x48ab}, - 160: {from: 0x46ab, to: 0x469d}, - 161: {from: 0x473b, to: 0x4742}, - 162: {from: 0x4913, to: 0x31d}, - 163: {from: 0x49a4, to: 0x521}, + 1: {from: 0x187, to: 0x1ae}, + 2: {from: 0x1f3, to: 0x1e1}, + 3: {from: 0x1fb, to: 0x1bc}, + 4: {from: 0x208, to: 0x512}, + 5: {from: 0x20f, to: 0x20e}, + 6: {from: 0x310, to: 0x3dc}, + 7: {from: 0x347, to: 0x36f}, + 8: {from: 0x407, to: 0x432}, + 9: {from: 0x47a, to: 0x153}, + 10: {from: 0x490, to: 0x451}, + 11: {from: 0x4a2, to: 0x21}, + 12: {from: 0x53e, to: 0x544}, + 13: {from: 0x58f, to: 0x12d}, + 14: {from: 0x630, to: 0x1eb1}, + 15: {from: 0x651, to: 0x431}, + 16: {from: 0x662, to: 0x431}, + 17: {from: 0x6ed, to: 0x3a}, + 18: {from: 0x6f8, to: 0x1d7}, + 19: {from: 0x73e, to: 0x21a1}, + 20: {from: 0x7b3, to: 0x56}, + 21: {from: 0x7b9, to: 0x299b}, + 22: {from: 0x7c5, to: 0x58}, + 23: {from: 0x7e6, to: 0x145}, + 24: {from: 0x80c, to: 0x5a}, + 25: {from: 0x815, to: 0x8d}, + 26: {from: 0x87e, to: 0x810}, + 27: {from: 0x8c3, to: 0xee3}, + 28: {from: 0x9ef, to: 0x331}, + 29: {from: 0xa36, to: 0x2c5}, + 30: {from: 0xa3d, to: 0xbf}, + 31: {from: 0xabe, to: 0x3322}, + 32: {from: 0xb38, to: 0x529}, + 33: {from: 0xb75, to: 0x265a}, + 34: {from: 0xb7e, to: 0xbc3}, + 35: {from: 0xb9b, to: 0x44e}, + 36: {from: 0xbbc, to: 0x4229}, + 37: {from: 0xbbf, to: 0x529}, + 38: {from: 0xbfe, to: 0x2da7}, + 39: {from: 0xc2e, to: 0x3181}, + 40: {from: 0xcb9, to: 0xf3}, + 41: {from: 0xd08, to: 0xfa}, + 42: {from: 0xdc8, to: 0x11a}, + 43: {from: 0xdd7, to: 0x32d}, + 44: {from: 0xdf8, to: 0xdfb}, + 45: {from: 0xdfe, to: 0x531}, + 46: {from: 0xedf, to: 0x205a}, + 47: {from: 0xeee, to: 0x2e9a}, + 48: {from: 0xf39, to: 0x367}, + 49: {from: 0x10d0, to: 0x140}, + 50: {from: 0x1104, to: 0x2d0}, + 51: {from: 0x11a0, to: 0x1ec}, + 52: {from: 0x1279, to: 0x21}, + 53: {from: 0x1424, to: 0x15e}, + 54: {from: 0x1470, to: 0x14e}, + 55: {from: 0x151f, to: 0xd9b}, + 56: {from: 0x1523, to: 0x390}, + 57: {from: 0x1532, to: 0x19f}, + 58: {from: 0x1580, to: 0x210}, + 59: {from: 0x1583, to: 0x10d}, + 60: {from: 0x15a3, to: 0x3caf}, + 61: {from: 0x166a, to: 0x19b}, + 62: {from: 0x16c8, to: 0x136}, + 63: {from: 0x1700, to: 0x29f8}, + 64: {from: 0x1718, to: 0x194}, + 65: {from: 0x1727, to: 0xf3f}, + 66: {from: 0x177a, to: 0x178}, + 67: {from: 0x1809, to: 0x17b6}, + 68: {from: 0x1816, to: 0x18f3}, + 69: {from: 0x188a, to: 0x436}, + 70: {from: 0x1979, to: 0x1d01}, + 71: {from: 0x1a74, to: 0x2bb0}, + 72: {from: 0x1a8a, to: 0x1f8}, + 73: {from: 0x1b5a, to: 0x1fa}, + 74: {from: 0x1b86, to: 0x1515}, + 75: {from: 0x1d64, to: 0x2c9b}, + 76: {from: 0x2038, to: 0x37b1}, + 77: {from: 0x203d, to: 0x20dd}, + 78: {from: 0x205a, to: 0x30b}, + 79: {from: 0x20e3, to: 0x274}, + 80: {from: 0x20ee, to: 0x263}, + 81: {from: 0x20f2, to: 0x22d}, + 82: {from: 0x20f9, to: 0x256}, + 83: {from: 0x210f, to: 0x21eb}, + 84: {from: 0x2135, to: 0x27d}, + 85: {from: 0x2160, to: 0x913}, + 86: {from: 0x2199, to: 0x121}, + 87: {from: 0x21ce, to: 0x1561}, + 88: {from: 0x21e6, to: 0x504}, + 89: {from: 0x21f4, to: 0x49f}, + 90: {from: 0x222d, to: 0x121}, + 91: {from: 0x2237, to: 0x121}, + 92: {from: 0x2262, to: 0x92a}, + 93: {from: 0x2316, to: 0x3226}, + 94: {from: 0x2382, to: 0x3365}, + 95: {from: 0x2472, to: 0x2c7}, + 96: {from: 0x24e4, to: 0x2ff}, + 97: {from: 0x24f0, to: 0x2fa}, + 98: {from: 0x24fa, to: 0x31f}, + 99: {from: 0x2550, to: 0xb5b}, + 100: {from: 0x25a9, to: 0xe2}, + 101: {from: 0x263e, to: 0x2d0}, + 102: {from: 0x26c9, to: 0x26b4}, + 103: {from: 0x26f9, to: 0x3c8}, + 104: {from: 0x2727, to: 0x3caf}, + 105: {from: 0x2765, to: 0x26b4}, + 106: {from: 0x2789, to: 0x4358}, + 107: {from: 0x28ef, to: 0x2837}, + 108: {from: 0x2914, to: 0x351}, + 109: {from: 0x2986, to: 0x2da7}, + 110: {from: 0x2b1a, to: 0x38d}, + 111: {from: 0x2bfc, to: 0x395}, + 112: {from: 0x2c3f, to: 0x3caf}, + 113: {from: 0x2cfc, to: 0x3be}, + 114: {from: 0x2d13, to: 0x597}, + 115: {from: 0x2d47, to: 0x148}, + 116: {from: 0x2d48, to: 0x148}, + 117: {from: 0x2dff, to: 0x2f1}, + 118: {from: 0x2e08, to: 0x19cc}, + 119: {from: 0x2e1a, to: 0x2d95}, + 120: {from: 0x2e21, to: 0x292}, + 121: {from: 0x2e54, to: 0x7d}, + 122: {from: 0x2e65, to: 0x2282}, + 123: {from: 0x2ea0, to: 0x2e9b}, + 124: {from: 0x2eef, to: 0x2ed7}, + 125: {from: 0x3193, to: 0x3c4}, + 126: {from: 0x3366, to: 0x338e}, + 127: {from: 0x342a, to: 0x3dc}, + 128: {from: 0x34ee, to: 0x18d0}, + 129: {from: 0x35c8, to: 0x2c9b}, + 130: {from: 0x35e6, to: 0x412}, + 131: {from: 0x3658, to: 0x246}, + 132: {from: 0x3676, to: 0x3f4}, + 133: {from: 0x36fd, to: 0x445}, + 134: {from: 0x37c0, to: 0x121}, + 135: {from: 0x3816, to: 0x38f2}, + 136: {from: 0x382b, to: 0x2c9b}, + 137: {from: 0x382f, to: 0xa9}, + 138: {from: 0x3832, to: 0x3228}, + 139: {from: 0x386c, to: 0x39a6}, + 140: {from: 0x3892, to: 0x3fc0}, + 141: {from: 0x38a5, to: 0x39d7}, + 142: {from: 0x38b4, to: 0x1fa4}, + 143: {from: 0x38b5, to: 0x2e9a}, + 144: {from: 0x395c, to: 0x47e}, + 145: {from: 0x3b4e, to: 0xd91}, + 146: {from: 0x3b78, to: 0x137}, + 147: {from: 0x3c99, to: 0x4bc}, + 148: {from: 0x3fbd, to: 0x100}, + 149: {from: 0x4208, to: 0xa91}, + 150: {from: 0x42be, to: 0x573}, + 151: {from: 0x42f9, to: 0x3f60}, + 152: {from: 0x4378, to: 0x25a}, + 153: {from: 0x43cb, to: 0x36cb}, + 154: {from: 0x43cd, to: 0x10f}, + 155: {from: 0x44af, to: 0x3322}, + 156: {from: 0x44e3, to: 0x512}, + 157: {from: 0x45ca, to: 0x2409}, + 158: {from: 0x45dd, to: 0x26dc}, + 159: {from: 0x4610, to: 0x48ae}, + 160: {from: 0x46ae, to: 0x46a0}, + 161: {from: 0x473e, to: 0x4745}, + 162: {from: 0x4916, to: 0x31f}, + 163: {from: 0x49a7, to: 0x523}, } // Size: 164 bytes, 164 elements @@ -769,58 +769,58 @@ var langAliasTypes = [164]langAliasType{ } const ( - _Latn = 85 - _Hani = 53 - _Hans = 55 - _Hant = 56 - _Qaaa = 136 - _Qaai = 144 - _Qabx = 185 - _Zinh = 231 - _Zyyy = 236 - _Zzzz = 237 + _Latn = 87 + _Hani = 54 + _Hans = 56 + _Hant = 57 + _Qaaa = 139 + _Qaai = 147 + _Qabx = 188 + _Zinh = 236 + _Zyyy = 241 + _Zzzz = 242 ) // script is an alphabetically sorted list of ISO 15924 codes. The index // of the script in the string, divided by 4, is the internal scriptID. -const script tag.Index = "" + // Size: 956 bytes +const script tag.Index = "" + // Size: 976 bytes "----AdlmAfakAghbAhomArabAranArmiArmnAvstBaliBamuBassBatkBengBhksBlisBopo" + - "BrahBraiBugiBuhdCakmCansCariChamCherCirtCoptCprtCyrlCyrsDevaDogrDsrtDupl" + - "EgydEgyhEgypElbaEthiGeokGeorGlagGongGonmGothGranGrekGujrGuruHanbHangHani" + - "HanoHansHantHatrHebrHiraHluwHmngHrktHungIndsItalJamoJavaJpanJurcKaliKana" + - "KharKhmrKhojKitlKitsKndaKoreKpelKthiLanaLaooLatfLatgLatnLekeLepcLimbLina" + - "LinbLisuLomaLyciLydiMahjMakaMandManiMarcMayaMedfMendMercMeroMlymModiMong" + - "MoonMrooMteiMultMymrNarbNbatNewaNkgbNkooNshuOgamOlckOrkhOryaOsgeOsmaPalm" + - "PaucPermPhagPhliPhlpPhlvPhnxPiqdPlrdPrtiQaaaQaabQaacQaadQaaeQaafQaagQaah" + - "QaaiQaajQaakQaalQaamQaanQaaoQaapQaaqQaarQaasQaatQaauQaavQaawQaaxQaayQaaz" + - "QabaQabbQabcQabdQabeQabfQabgQabhQabiQabjQabkQablQabmQabnQaboQabpQabqQabr" + - "QabsQabtQabuQabvQabwQabxRjngRoroRunrSamrSaraSarbSaurSgnwShawShrdSiddSind" + - "SinhSoraSoyoSundSyloSyrcSyreSyrjSyrnTagbTakrTaleTaluTamlTangTavtTeluTeng" + - "TfngTglgThaaThaiTibtTirhUgarVaiiVispWaraWoleXpeoXsuxYiiiZanbZinhZmthZsye" + - "ZsymZxxxZyyyZzzz\xff\xff\xff\xff" + "BrahBraiBugiBuhdCakmCansCariChamCherCirtCoptCpmnCprtCyrlCyrsDevaDogrDsrt" + + "DuplEgydEgyhEgypElbaEthiGeokGeorGlagGongGonmGothGranGrekGujrGuruHanbHang" + + "HaniHanoHansHantHatrHebrHiraHluwHmngHmnpHrktHungIndsItalJamoJavaJpanJurc" + + "KaliKanaKharKhmrKhojKitlKitsKndaKoreKpelKthiLanaLaooLatfLatgLatnLekeLepc" + + "LimbLinaLinbLisuLomaLyciLydiMahjMakaMandManiMarcMayaMedfMendMercMeroMlym" + + "ModiMongMoonMrooMteiMultMymrNarbNbatNewaNkdbNkgbNkooNshuOgamOlckOrkhOrya" + + "OsgeOsmaPalmPaucPermPhagPhliPhlpPhlvPhnxPiqdPlrdPrtiQaaaQaabQaacQaadQaae" + + "QaafQaagQaahQaaiQaajQaakQaalQaamQaanQaaoQaapQaaqQaarQaasQaatQaauQaavQaaw" + + "QaaxQaayQaazQabaQabbQabcQabdQabeQabfQabgQabhQabiQabjQabkQablQabmQabnQabo" + + "QabpQabqQabrQabsQabtQabuQabvQabwQabxRjngRoroRunrSamrSaraSarbSaurSgnwShaw" + + "ShrdShuiSiddSindSinhSoraSoyoSundSyloSyrcSyreSyrjSyrnTagbTakrTaleTaluTaml" + + "TangTavtTeluTengTfngTglgThaaThaiTibtTirhUgarVaiiVispWaraWchoWoleXpeoXsux" + + "YiiiZanbZinhZmthZsyeZsymZxxxZyyyZzzz\xff\xff\xff\xff" // suppressScript is an index from langID to the dominant script for that language, // if it exists. If a script is given, it should be suppressed from the language tag. -// Size: 1327 bytes, 1327 elements -var suppressScript = [1327]uint8{ +// Size: 1330 bytes, 1330 elements +var suppressScript = [1330]uint8{ // Entry 0 - 3F - 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, // Entry 40 - 7F 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 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, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, + 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, // Entry 80 - BF 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -828,66 +828,66 @@ var suppressScript = [1327]uint8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Entry C0 - FF 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, + 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, // Entry 100 - 13F - 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xda, - 0x00, 0x00, 0x00, 0x00, 0xdc, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, - 0x55, 0x00, 0x00, 0x55, 0x00, 0x55, 0x00, 0x55, - // Entry 140 - 17F - 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x05, + 0x57, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x55, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x55, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, - 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x55, 0x55, 0x00, 0x00, + 0xde, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31, 0x00, + 0x00, 0x57, 0x00, 0x00, 0x57, 0x00, 0x57, 0x00, + // Entry 140 - 17F + 0x57, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, + 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x57, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, + 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, + 0x00, 0x57, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Entry 180 - 1BF 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, - 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x55, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x57, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x57, 0x32, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x3a, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x21, 0x00, // Entry 1C0 - 1FF 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, - 0x55, 0x00, 0x55, 0x55, 0x00, 0x08, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x57, 0x57, 0x00, 0x57, 0x57, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x55, 0x55, - 0x00, 0x3a, 0x00, 0x00, 0x00, 0x00, 0x44, 0x00, - // Entry 200 - 23F + 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, 0x00, + 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, + 0x57, 0x57, 0x00, 0x3b, 0x00, 0x00, 0x00, 0x00, + // Entry 200 - 23F + 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x2b, 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, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Entry 240 - 27F - 0x1e, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, - 0x49, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4d, - 0x00, 0x00, 0x4e, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x1f, 0x00, 0x00, 0x57, 0x00, 0x00, + 0x00, 0x00, 0x4b, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x4f, 0x00, 0x00, 0x50, 0x00, 0x21, 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, @@ -895,101 +895,102 @@ var suppressScript = [1327]uint8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Entry 280 - 2BF 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 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, 0x55, 0x00, 0x00, 0x52, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, + 0x54, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Entry 2C0 - 2FF - 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, + 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, - // Entry 300 - 33F - 0x00, 0x00, 0x69, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x20, 0x00, 0x00, 0x00, 0x55, 0x55, 0x00, + 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, + // Entry 300 - 33F + 0x00, 0x00, 0x00, 0x00, 0x6b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, + 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x57, + 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, + 0x00, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, // Entry 340 - 37F - 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x55, 0x20, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, - 0x55, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x75, 0x55, 0x00, 0x00, 0x00, - 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, + 0x57, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, + 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x57, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x57, 0x00, + 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, // Entry 380 - 3BF - 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, - 0x00, 0x00, 0x00, 0x7a, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x57, 0x00, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x55, 0x00, + 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, // Entry 3C0 - 3FF - 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x57, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x55, - 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x1e, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, + 0x00, 0x57, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x1f, 0x00, 0x00, 0x57, 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, // Entry 400 - 43F - 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0xc6, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x55, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, - 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, - 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0xca, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x57, 0x00, + 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, + 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, // Entry 440 - 47F - 0x00, 0x00, 0x55, 0x55, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd6, - 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0xdb, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, - 0x55, 0x00, 0x00, 0x00, 0x55, 0x00, 0x55, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x57, 0x57, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xd7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xda, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xdf, 0x00, 0x00, 0x00, 0x29, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, + 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x57, 0x00, // Entry 480 - 4BF - 0x55, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, - 0x55, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, + 0x57, 0x00, 0x57, 0x00, 0x00, 0x00, 0x57, 0x00, + 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, + 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Entry 4C0 - 4FF - 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x57, 0x00, 0x00, 0x57, 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, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Entry 500 - 53F 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x3a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x3b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x55, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x57, + 0x00, 0x00, } const ( @@ -1356,147 +1357,151 @@ type likelyLangRegion struct { // likelyScript is a lookup table, indexed by scriptID, for the most likely // languages and regions given a script. -// Size: 956 bytes, 239 elements -var likelyScript = [239]likelyLangRegion{ - 1: {lang: 0x14d, region: 0x84}, - 3: {lang: 0x2a0, region: 0x106}, +// Size: 976 bytes, 244 elements +var likelyScript = [244]likelyLangRegion{ + 1: {lang: 0x14e, region: 0x84}, + 3: {lang: 0x2a2, region: 0x106}, 4: {lang: 0x1f, region: 0x99}, 5: {lang: 0x3a, region: 0x6b}, 7: {lang: 0x3b, region: 0x9c}, - 8: {lang: 0x1d5, region: 0x28}, + 8: {lang: 0x1d7, region: 0x28}, 9: {lang: 0x13, region: 0x9c}, 10: {lang: 0x5b, region: 0x95}, 11: {lang: 0x60, region: 0x52}, 12: {lang: 0xb9, region: 0xb4}, 13: {lang: 0x63, region: 0x95}, 14: {lang: 0xa5, region: 0x35}, - 15: {lang: 0x3e7, region: 0x99}, - 17: {lang: 0x527, region: 0x12e}, - 18: {lang: 0x3af, region: 0x99}, - 19: {lang: 0x15d, region: 0x78}, + 15: {lang: 0x3e9, region: 0x99}, + 17: {lang: 0x529, region: 0x12e}, + 18: {lang: 0x3b1, region: 0x99}, + 19: {lang: 0x15e, region: 0x78}, 20: {lang: 0xc2, region: 0x95}, 21: {lang: 0x9d, region: 0xe7}, 22: {lang: 0xdb, region: 0x35}, - 23: {lang: 0xf2, region: 0x49}, - 24: {lang: 0x4ee, region: 0x12b}, + 23: {lang: 0xf3, region: 0x49}, + 24: {lang: 0x4f0, region: 0x12b}, 25: {lang: 0xe7, region: 0x13e}, 26: {lang: 0xe5, region: 0x135}, - 28: {lang: 0xf0, region: 0x6b}, - 29: {lang: 0x19e, region: 0x5d}, - 30: {lang: 0x3e0, region: 0x106}, - 32: {lang: 0x1bc, region: 0x99}, - 35: {lang: 0x15d, region: 0x78}, - 38: {lang: 0x132, region: 0x6b}, - 39: {lang: 0x42f, region: 0x27}, - 40: {lang: 0x27, region: 0x6f}, - 42: {lang: 0x20e, region: 0x7d}, - 43: {lang: 0xfd, region: 0x38}, - 46: {lang: 0x19c, region: 0x130}, - 47: {lang: 0x3e7, region: 0x99}, - 48: {lang: 0x135, region: 0x87}, - 49: {lang: 0x1a2, region: 0x99}, - 50: {lang: 0x39b, region: 0x99}, - 51: {lang: 0x527, region: 0x12e}, - 52: {lang: 0x252, region: 0xab}, - 53: {lang: 0x527, region: 0x53}, - 54: {lang: 0x1c9, region: 0xe7}, - 55: {lang: 0x527, region: 0x53}, - 56: {lang: 0x527, region: 0x12e}, - 57: {lang: 0x2fb, region: 0x9b}, - 58: {lang: 0x1ba, region: 0x97}, - 59: {lang: 0x1fe, region: 0xa2}, - 60: {lang: 0x1c3, region: 0x12b}, - 61: {lang: 0x1c8, region: 0xaf}, - 63: {lang: 0x1d3, region: 0x92}, - 65: {lang: 0x141, region: 0x9e}, - 66: {lang: 0x252, region: 0xab}, - 67: {lang: 0x20c, region: 0x95}, - 68: {lang: 0x1fe, region: 0xa2}, - 70: {lang: 0x134, region: 0xc4}, - 71: {lang: 0x1fe, region: 0xa2}, - 72: {lang: 0x3b9, region: 0xe8}, - 73: {lang: 0x248, region: 0xa6}, - 74: {lang: 0x3f8, region: 0x99}, - 77: {lang: 0x24f, region: 0x99}, - 78: {lang: 0x252, region: 0xab}, - 80: {lang: 0x88, region: 0x99}, - 81: {lang: 0x36e, region: 0x123}, - 82: {lang: 0x2b6, region: 0xaf}, - 87: {lang: 0x29d, region: 0x99}, - 88: {lang: 0x2a6, region: 0x99}, - 89: {lang: 0x28d, region: 0x87}, - 90: {lang: 0x19e, region: 0x87}, - 91: {lang: 0x2aa, region: 0x53}, - 93: {lang: 0x4f2, region: 0x12b}, - 94: {lang: 0x4f3, region: 0x12b}, - 95: {lang: 0x1bc, region: 0x99}, - 97: {lang: 0x335, region: 0x9c}, - 98: {lang: 0x4f5, region: 0x53}, - 99: {lang: 0xa9, region: 0x53}, - 102: {lang: 0x2e6, region: 0x112}, - 103: {lang: 0x4f6, region: 0x10b}, - 104: {lang: 0x4f6, region: 0x10b}, - 105: {lang: 0x302, region: 0x99}, - 106: {lang: 0x319, region: 0x99}, - 107: {lang: 0x309, region: 0x53}, - 109: {lang: 0x31c, region: 0x35}, - 110: {lang: 0x30c, region: 0x99}, - 111: {lang: 0x412, region: 0xe8}, - 112: {lang: 0x32f, region: 0xc4}, - 113: {lang: 0x4f7, region: 0x108}, - 114: {lang: 0x3b, region: 0xa1}, - 115: {lang: 0x351, region: 0xdb}, - 117: {lang: 0x2ce, region: 0x84}, - 119: {lang: 0x401, region: 0x96}, - 120: {lang: 0x3ec, region: 0x99}, - 121: {lang: 0x399, region: 0xc5}, - 122: {lang: 0x393, region: 0x99}, - 123: {lang: 0x397, region: 0x135}, - 124: {lang: 0x427, region: 0x115}, - 125: {lang: 0x3b, region: 0x11c}, - 126: {lang: 0xfc, region: 0xc4}, - 127: {lang: 0x27b, region: 0x106}, - 128: {lang: 0x2c7, region: 0x53}, - 129: {lang: 0x39d, region: 0x9c}, - 130: {lang: 0x39d, region: 0x53}, - 132: {lang: 0x3ab, region: 0xb0}, - 134: {lang: 0x1c4, region: 0x53}, - 135: {lang: 0x4fb, region: 0x9c}, - 186: {lang: 0x3c9, region: 0x95}, - 188: {lang: 0x370, region: 0x10c}, - 189: {lang: 0x41e, region: 0x97}, - 191: {lang: 0x4fd, region: 0x15e}, - 192: {lang: 0x3ee, region: 0x99}, - 193: {lang: 0x45, region: 0x135}, - 194: {lang: 0x138, region: 0x7b}, - 195: {lang: 0x3e7, region: 0x99}, - 196: {lang: 0x3e7, region: 0x99}, - 197: {lang: 0x3f8, region: 0x99}, - 198: {lang: 0x40a, region: 0xb3}, - 199: {lang: 0x431, region: 0x99}, - 201: {lang: 0x43c, region: 0x95}, - 202: {lang: 0x44b, region: 0x35}, - 203: {lang: 0x44c, region: 0x9b}, - 207: {lang: 0x458, region: 0xe7}, - 208: {lang: 0x119, region: 0x99}, - 209: {lang: 0x45c, region: 0x53}, - 210: {lang: 0x230, region: 0x53}, - 211: {lang: 0x44e, region: 0x99}, - 212: {lang: 0x4a3, region: 0x53}, - 213: {lang: 0x9f, region: 0x13e}, - 214: {lang: 0x45f, region: 0x99}, - 216: {lang: 0x526, region: 0xba}, - 217: {lang: 0x152, region: 0xe7}, - 218: {lang: 0x127, region: 0xcd}, - 219: {lang: 0x469, region: 0x123}, - 220: {lang: 0xa9, region: 0x53}, - 221: {lang: 0x2cc, region: 0x99}, - 222: {lang: 0x4ab, region: 0x11c}, - 223: {lang: 0x4bc, region: 0xb4}, - 225: {lang: 0x1cc, region: 0x99}, - 227: {lang: 0x3a7, region: 0x9c}, - 228: {lang: 0x22, region: 0x9b}, - 229: {lang: 0x1e8, region: 0x53}, + 28: {lang: 0xf1, region: 0x6b}, + 30: {lang: 0x1a0, region: 0x5d}, + 31: {lang: 0x3e2, region: 0x106}, + 33: {lang: 0x1be, region: 0x99}, + 36: {lang: 0x15e, region: 0x78}, + 39: {lang: 0x133, region: 0x6b}, + 40: {lang: 0x431, region: 0x27}, + 41: {lang: 0x27, region: 0x6f}, + 43: {lang: 0x210, region: 0x7d}, + 44: {lang: 0xfe, region: 0x38}, + 46: {lang: 0x19b, region: 0x99}, + 47: {lang: 0x19e, region: 0x130}, + 48: {lang: 0x3e9, region: 0x99}, + 49: {lang: 0x136, region: 0x87}, + 50: {lang: 0x1a4, region: 0x99}, + 51: {lang: 0x39d, region: 0x99}, + 52: {lang: 0x529, region: 0x12e}, + 53: {lang: 0x254, region: 0xab}, + 54: {lang: 0x529, region: 0x53}, + 55: {lang: 0x1cb, region: 0xe7}, + 56: {lang: 0x529, region: 0x53}, + 57: {lang: 0x529, region: 0x12e}, + 58: {lang: 0x2fd, region: 0x9b}, + 59: {lang: 0x1bc, region: 0x97}, + 60: {lang: 0x200, region: 0xa2}, + 61: {lang: 0x1c5, region: 0x12b}, + 62: {lang: 0x1ca, region: 0xaf}, + 65: {lang: 0x1d5, region: 0x92}, + 67: {lang: 0x142, region: 0x9e}, + 68: {lang: 0x254, region: 0xab}, + 69: {lang: 0x20e, region: 0x95}, + 70: {lang: 0x200, region: 0xa2}, + 72: {lang: 0x135, region: 0xc4}, + 73: {lang: 0x200, region: 0xa2}, + 74: {lang: 0x3bb, region: 0xe8}, + 75: {lang: 0x24a, region: 0xa6}, + 76: {lang: 0x3fa, region: 0x99}, + 79: {lang: 0x251, region: 0x99}, + 80: {lang: 0x254, region: 0xab}, + 82: {lang: 0x88, region: 0x99}, + 83: {lang: 0x370, region: 0x123}, + 84: {lang: 0x2b8, region: 0xaf}, + 89: {lang: 0x29f, region: 0x99}, + 90: {lang: 0x2a8, region: 0x99}, + 91: {lang: 0x28f, region: 0x87}, + 92: {lang: 0x1a0, region: 0x87}, + 93: {lang: 0x2ac, region: 0x53}, + 95: {lang: 0x4f4, region: 0x12b}, + 96: {lang: 0x4f5, region: 0x12b}, + 97: {lang: 0x1be, region: 0x99}, + 99: {lang: 0x337, region: 0x9c}, + 100: {lang: 0x4f7, region: 0x53}, + 101: {lang: 0xa9, region: 0x53}, + 104: {lang: 0x2e8, region: 0x112}, + 105: {lang: 0x4f8, region: 0x10b}, + 106: {lang: 0x4f8, region: 0x10b}, + 107: {lang: 0x304, region: 0x99}, + 108: {lang: 0x31b, region: 0x99}, + 109: {lang: 0x30b, region: 0x53}, + 111: {lang: 0x31e, region: 0x35}, + 112: {lang: 0x30e, region: 0x99}, + 113: {lang: 0x414, region: 0xe8}, + 114: {lang: 0x331, region: 0xc4}, + 115: {lang: 0x4f9, region: 0x108}, + 116: {lang: 0x3b, region: 0xa1}, + 117: {lang: 0x353, region: 0xdb}, + 120: {lang: 0x2d0, region: 0x84}, + 121: {lang: 0x52a, region: 0x53}, + 122: {lang: 0x403, region: 0x96}, + 123: {lang: 0x3ee, region: 0x99}, + 124: {lang: 0x39b, region: 0xc5}, + 125: {lang: 0x395, region: 0x99}, + 126: {lang: 0x399, region: 0x135}, + 127: {lang: 0x429, region: 0x115}, + 128: {lang: 0x3b, region: 0x11c}, + 129: {lang: 0xfd, region: 0xc4}, + 130: {lang: 0x27d, region: 0x106}, + 131: {lang: 0x2c9, region: 0x53}, + 132: {lang: 0x39f, region: 0x9c}, + 133: {lang: 0x39f, region: 0x53}, + 135: {lang: 0x3ad, region: 0xb0}, + 137: {lang: 0x1c6, region: 0x53}, + 138: {lang: 0x4fd, region: 0x9c}, + 189: {lang: 0x3cb, region: 0x95}, + 191: {lang: 0x372, region: 0x10c}, + 192: {lang: 0x420, region: 0x97}, + 194: {lang: 0x4ff, region: 0x15e}, + 195: {lang: 0x3f0, region: 0x99}, + 196: {lang: 0x45, region: 0x135}, + 197: {lang: 0x139, region: 0x7b}, + 198: {lang: 0x3e9, region: 0x99}, + 200: {lang: 0x3e9, region: 0x99}, + 201: {lang: 0x3fa, region: 0x99}, + 202: {lang: 0x40c, region: 0xb3}, + 203: {lang: 0x433, region: 0x99}, + 204: {lang: 0xef, region: 0xc5}, + 205: {lang: 0x43e, region: 0x95}, + 206: {lang: 0x44d, region: 0x35}, + 207: {lang: 0x44e, region: 0x9b}, + 211: {lang: 0x45a, region: 0xe7}, + 212: {lang: 0x11a, region: 0x99}, + 213: {lang: 0x45e, region: 0x53}, + 214: {lang: 0x232, region: 0x53}, + 215: {lang: 0x450, region: 0x99}, + 216: {lang: 0x4a5, region: 0x53}, + 217: {lang: 0x9f, region: 0x13e}, + 218: {lang: 0x461, region: 0x99}, + 220: {lang: 0x528, region: 0xba}, + 221: {lang: 0x153, region: 0xe7}, + 222: {lang: 0x128, region: 0xcd}, + 223: {lang: 0x46b, region: 0x123}, + 224: {lang: 0xa9, region: 0x53}, + 225: {lang: 0x2ce, region: 0x99}, + 226: {lang: 0x4ad, region: 0x11c}, + 227: {lang: 0x4be, region: 0xb4}, + 229: {lang: 0x1ce, region: 0x99}, + 232: {lang: 0x3a9, region: 0x9c}, + 233: {lang: 0x22, region: 0x9b}, + 234: {lang: 0x1ea, region: 0x53}, + 235: {lang: 0xef, region: 0xc5}, } type likelyScriptRegion struct { @@ -1509,1419 +1514,1425 @@ type likelyScriptRegion struct { // scripts and regions given incomplete information. If more entries exist for a // given language, region and script are the index and size respectively // of the list in likelyLangList. -// Size: 5308 bytes, 1327 elements -var likelyLang = [1327]likelyScriptRegion{ - 0: {region: 0x135, script: 0x55, flags: 0x0}, - 1: {region: 0x6f, script: 0x55, flags: 0x0}, - 2: {region: 0x165, script: 0x55, flags: 0x0}, - 3: {region: 0x165, script: 0x55, flags: 0x0}, - 4: {region: 0x165, script: 0x55, flags: 0x0}, - 5: {region: 0x7d, script: 0x1e, flags: 0x0}, - 6: {region: 0x165, script: 0x55, flags: 0x0}, - 7: {region: 0x165, script: 0x1e, flags: 0x0}, - 8: {region: 0x80, script: 0x55, flags: 0x0}, - 9: {region: 0x165, script: 0x55, flags: 0x0}, - 10: {region: 0x165, script: 0x55, flags: 0x0}, - 11: {region: 0x165, script: 0x55, flags: 0x0}, - 12: {region: 0x95, script: 0x55, flags: 0x0}, - 13: {region: 0x131, script: 0x55, flags: 0x0}, - 14: {region: 0x80, script: 0x55, flags: 0x0}, - 15: {region: 0x165, script: 0x55, flags: 0x0}, - 16: {region: 0x165, script: 0x55, flags: 0x0}, - 17: {region: 0x106, script: 0x1e, flags: 0x0}, - 18: {region: 0x165, script: 0x55, flags: 0x0}, +// Size: 5320 bytes, 1330 elements +var likelyLang = [1330]likelyScriptRegion{ + 0: {region: 0x135, script: 0x57, flags: 0x0}, + 1: {region: 0x6f, script: 0x57, flags: 0x0}, + 2: {region: 0x165, script: 0x57, flags: 0x0}, + 3: {region: 0x165, script: 0x57, flags: 0x0}, + 4: {region: 0x165, script: 0x57, flags: 0x0}, + 5: {region: 0x7d, script: 0x1f, flags: 0x0}, + 6: {region: 0x165, script: 0x57, flags: 0x0}, + 7: {region: 0x165, script: 0x1f, flags: 0x0}, + 8: {region: 0x80, script: 0x57, flags: 0x0}, + 9: {region: 0x165, script: 0x57, flags: 0x0}, + 10: {region: 0x165, script: 0x57, flags: 0x0}, + 11: {region: 0x165, script: 0x57, flags: 0x0}, + 12: {region: 0x95, script: 0x57, flags: 0x0}, + 13: {region: 0x131, script: 0x57, flags: 0x0}, + 14: {region: 0x80, script: 0x57, flags: 0x0}, + 15: {region: 0x165, script: 0x57, flags: 0x0}, + 16: {region: 0x165, script: 0x57, flags: 0x0}, + 17: {region: 0x106, script: 0x1f, flags: 0x0}, + 18: {region: 0x165, script: 0x57, flags: 0x0}, 19: {region: 0x9c, script: 0x9, flags: 0x0}, 20: {region: 0x128, script: 0x5, flags: 0x0}, - 21: {region: 0x165, script: 0x55, flags: 0x0}, - 22: {region: 0x161, script: 0x55, flags: 0x0}, - 23: {region: 0x165, script: 0x55, flags: 0x0}, - 24: {region: 0x165, script: 0x55, flags: 0x0}, - 25: {region: 0x165, script: 0x55, flags: 0x0}, - 26: {region: 0x165, script: 0x55, flags: 0x0}, - 27: {region: 0x165, script: 0x55, flags: 0x0}, - 28: {region: 0x52, script: 0x55, flags: 0x0}, - 29: {region: 0x165, script: 0x55, flags: 0x0}, - 30: {region: 0x165, script: 0x55, flags: 0x0}, + 21: {region: 0x165, script: 0x57, flags: 0x0}, + 22: {region: 0x161, script: 0x57, flags: 0x0}, + 23: {region: 0x165, script: 0x57, flags: 0x0}, + 24: {region: 0x165, script: 0x57, flags: 0x0}, + 25: {region: 0x165, script: 0x57, flags: 0x0}, + 26: {region: 0x165, script: 0x57, flags: 0x0}, + 27: {region: 0x165, script: 0x57, flags: 0x0}, + 28: {region: 0x52, script: 0x57, flags: 0x0}, + 29: {region: 0x165, script: 0x57, flags: 0x0}, + 30: {region: 0x165, script: 0x57, flags: 0x0}, 31: {region: 0x99, script: 0x4, flags: 0x0}, - 32: {region: 0x165, script: 0x55, flags: 0x0}, - 33: {region: 0x80, script: 0x55, flags: 0x0}, - 34: {region: 0x9b, script: 0xe4, flags: 0x0}, - 35: {region: 0x165, script: 0x55, flags: 0x0}, - 36: {region: 0x165, script: 0x55, flags: 0x0}, - 37: {region: 0x14d, script: 0x55, flags: 0x0}, - 38: {region: 0x106, script: 0x1e, flags: 0x0}, - 39: {region: 0x6f, script: 0x28, flags: 0x0}, - 40: {region: 0x165, script: 0x55, flags: 0x0}, - 41: {region: 0x165, script: 0x55, flags: 0x0}, - 42: {region: 0xd6, script: 0x55, flags: 0x0}, - 43: {region: 0x165, script: 0x55, flags: 0x0}, - 45: {region: 0x165, script: 0x55, flags: 0x0}, - 46: {region: 0x165, script: 0x55, flags: 0x0}, - 47: {region: 0x165, script: 0x55, flags: 0x0}, - 48: {region: 0x165, script: 0x55, flags: 0x0}, - 49: {region: 0x165, script: 0x55, flags: 0x0}, - 50: {region: 0x165, script: 0x55, flags: 0x0}, - 51: {region: 0x95, script: 0x55, flags: 0x0}, + 32: {region: 0x165, script: 0x57, flags: 0x0}, + 33: {region: 0x80, script: 0x57, flags: 0x0}, + 34: {region: 0x9b, script: 0xe9, flags: 0x0}, + 35: {region: 0x165, script: 0x57, flags: 0x0}, + 36: {region: 0x165, script: 0x57, flags: 0x0}, + 37: {region: 0x14d, script: 0x57, flags: 0x0}, + 38: {region: 0x106, script: 0x1f, flags: 0x0}, + 39: {region: 0x6f, script: 0x29, flags: 0x0}, + 40: {region: 0x165, script: 0x57, flags: 0x0}, + 41: {region: 0x165, script: 0x57, flags: 0x0}, + 42: {region: 0xd6, script: 0x57, flags: 0x0}, + 43: {region: 0x165, script: 0x57, flags: 0x0}, + 45: {region: 0x165, script: 0x57, flags: 0x0}, + 46: {region: 0x165, script: 0x57, flags: 0x0}, + 47: {region: 0x165, script: 0x57, flags: 0x0}, + 48: {region: 0x165, script: 0x57, flags: 0x0}, + 49: {region: 0x165, script: 0x57, flags: 0x0}, + 50: {region: 0x165, script: 0x57, flags: 0x0}, + 51: {region: 0x95, script: 0x57, flags: 0x0}, 52: {region: 0x165, script: 0x5, flags: 0x0}, 53: {region: 0x122, script: 0x5, flags: 0x0}, - 54: {region: 0x165, script: 0x55, flags: 0x0}, - 55: {region: 0x165, script: 0x55, flags: 0x0}, - 56: {region: 0x165, script: 0x55, flags: 0x0}, - 57: {region: 0x165, script: 0x55, flags: 0x0}, + 54: {region: 0x165, script: 0x57, flags: 0x0}, + 55: {region: 0x165, script: 0x57, flags: 0x0}, + 56: {region: 0x165, script: 0x57, flags: 0x0}, + 57: {region: 0x165, script: 0x57, flags: 0x0}, 58: {region: 0x6b, script: 0x5, flags: 0x0}, 59: {region: 0x0, script: 0x3, flags: 0x1}, - 60: {region: 0x165, script: 0x55, flags: 0x0}, - 61: {region: 0x51, script: 0x55, flags: 0x0}, - 62: {region: 0x3f, script: 0x55, flags: 0x0}, + 60: {region: 0x165, script: 0x57, flags: 0x0}, + 61: {region: 0x51, script: 0x57, flags: 0x0}, + 62: {region: 0x3f, script: 0x57, flags: 0x0}, 63: {region: 0x67, script: 0x5, flags: 0x0}, 65: {region: 0xba, script: 0x5, flags: 0x0}, 66: {region: 0x6b, script: 0x5, flags: 0x0}, 67: {region: 0x99, script: 0xe, flags: 0x0}, - 68: {region: 0x12f, script: 0x55, flags: 0x0}, - 69: {region: 0x135, script: 0xc1, flags: 0x0}, - 70: {region: 0x165, script: 0x55, flags: 0x0}, - 71: {region: 0x165, script: 0x55, flags: 0x0}, - 72: {region: 0x6e, script: 0x55, flags: 0x0}, - 73: {region: 0x165, script: 0x55, flags: 0x0}, - 74: {region: 0x165, script: 0x55, flags: 0x0}, - 75: {region: 0x49, script: 0x55, flags: 0x0}, - 76: {region: 0x165, script: 0x55, flags: 0x0}, - 77: {region: 0x106, script: 0x1e, flags: 0x0}, + 68: {region: 0x12f, script: 0x57, flags: 0x0}, + 69: {region: 0x135, script: 0xc4, flags: 0x0}, + 70: {region: 0x165, script: 0x57, flags: 0x0}, + 71: {region: 0x165, script: 0x57, flags: 0x0}, + 72: {region: 0x6e, script: 0x57, flags: 0x0}, + 73: {region: 0x165, script: 0x57, flags: 0x0}, + 74: {region: 0x165, script: 0x57, flags: 0x0}, + 75: {region: 0x49, script: 0x57, flags: 0x0}, + 76: {region: 0x165, script: 0x57, flags: 0x0}, + 77: {region: 0x106, script: 0x1f, flags: 0x0}, 78: {region: 0x165, script: 0x5, flags: 0x0}, - 79: {region: 0x165, script: 0x55, flags: 0x0}, - 80: {region: 0x165, script: 0x55, flags: 0x0}, - 81: {region: 0x165, script: 0x55, flags: 0x0}, - 82: {region: 0x99, script: 0x20, flags: 0x0}, - 83: {region: 0x165, script: 0x55, flags: 0x0}, - 84: {region: 0x165, script: 0x55, flags: 0x0}, - 85: {region: 0x165, script: 0x55, flags: 0x0}, - 86: {region: 0x3f, script: 0x55, flags: 0x0}, - 87: {region: 0x165, script: 0x55, flags: 0x0}, + 79: {region: 0x165, script: 0x57, flags: 0x0}, + 80: {region: 0x165, script: 0x57, flags: 0x0}, + 81: {region: 0x165, script: 0x57, flags: 0x0}, + 82: {region: 0x99, script: 0x21, flags: 0x0}, + 83: {region: 0x165, script: 0x57, flags: 0x0}, + 84: {region: 0x165, script: 0x57, flags: 0x0}, + 85: {region: 0x165, script: 0x57, flags: 0x0}, + 86: {region: 0x3f, script: 0x57, flags: 0x0}, + 87: {region: 0x165, script: 0x57, flags: 0x0}, 88: {region: 0x3, script: 0x5, flags: 0x1}, - 89: {region: 0x106, script: 0x1e, flags: 0x0}, + 89: {region: 0x106, script: 0x1f, flags: 0x0}, 90: {region: 0xe8, script: 0x5, flags: 0x0}, - 91: {region: 0x95, script: 0x55, flags: 0x0}, - 92: {region: 0xdb, script: 0x20, flags: 0x0}, - 93: {region: 0x2e, script: 0x55, flags: 0x0}, - 94: {region: 0x52, script: 0x55, flags: 0x0}, - 95: {region: 0x165, script: 0x55, flags: 0x0}, + 91: {region: 0x95, script: 0x57, flags: 0x0}, + 92: {region: 0xdb, script: 0x21, flags: 0x0}, + 93: {region: 0x2e, script: 0x57, flags: 0x0}, + 94: {region: 0x52, script: 0x57, flags: 0x0}, + 95: {region: 0x165, script: 0x57, flags: 0x0}, 96: {region: 0x52, script: 0xb, flags: 0x0}, - 97: {region: 0x165, script: 0x55, flags: 0x0}, - 98: {region: 0x165, script: 0x55, flags: 0x0}, - 99: {region: 0x95, script: 0x55, flags: 0x0}, - 100: {region: 0x165, script: 0x55, flags: 0x0}, - 101: {region: 0x52, script: 0x55, flags: 0x0}, - 102: {region: 0x165, script: 0x55, flags: 0x0}, - 103: {region: 0x165, script: 0x55, flags: 0x0}, - 104: {region: 0x165, script: 0x55, flags: 0x0}, - 105: {region: 0x165, script: 0x55, flags: 0x0}, - 106: {region: 0x4f, script: 0x55, flags: 0x0}, - 107: {region: 0x165, script: 0x55, flags: 0x0}, - 108: {region: 0x165, script: 0x55, flags: 0x0}, - 109: {region: 0x165, script: 0x55, flags: 0x0}, - 110: {region: 0x165, script: 0x28, flags: 0x0}, - 111: {region: 0x165, script: 0x55, flags: 0x0}, - 112: {region: 0x165, script: 0x55, flags: 0x0}, - 113: {region: 0x47, script: 0x1e, flags: 0x0}, - 114: {region: 0x165, script: 0x55, flags: 0x0}, - 115: {region: 0x165, script: 0x55, flags: 0x0}, + 97: {region: 0x165, script: 0x57, flags: 0x0}, + 98: {region: 0x165, script: 0x57, flags: 0x0}, + 99: {region: 0x95, script: 0x57, flags: 0x0}, + 100: {region: 0x165, script: 0x57, flags: 0x0}, + 101: {region: 0x52, script: 0x57, flags: 0x0}, + 102: {region: 0x165, script: 0x57, flags: 0x0}, + 103: {region: 0x165, script: 0x57, flags: 0x0}, + 104: {region: 0x165, script: 0x57, flags: 0x0}, + 105: {region: 0x165, script: 0x57, flags: 0x0}, + 106: {region: 0x4f, script: 0x57, flags: 0x0}, + 107: {region: 0x165, script: 0x57, flags: 0x0}, + 108: {region: 0x165, script: 0x57, flags: 0x0}, + 109: {region: 0x165, script: 0x57, flags: 0x0}, + 110: {region: 0x165, script: 0x29, flags: 0x0}, + 111: {region: 0x165, script: 0x57, flags: 0x0}, + 112: {region: 0x165, script: 0x57, flags: 0x0}, + 113: {region: 0x47, script: 0x1f, flags: 0x0}, + 114: {region: 0x165, script: 0x57, flags: 0x0}, + 115: {region: 0x165, script: 0x57, flags: 0x0}, 116: {region: 0x10b, script: 0x5, flags: 0x0}, - 117: {region: 0x162, script: 0x55, flags: 0x0}, - 118: {region: 0x165, script: 0x55, flags: 0x0}, - 119: {region: 0x95, script: 0x55, flags: 0x0}, - 120: {region: 0x165, script: 0x55, flags: 0x0}, - 121: {region: 0x12f, script: 0x55, flags: 0x0}, - 122: {region: 0x52, script: 0x55, flags: 0x0}, - 123: {region: 0x99, script: 0xd3, flags: 0x0}, + 117: {region: 0x162, script: 0x57, flags: 0x0}, + 118: {region: 0x165, script: 0x57, flags: 0x0}, + 119: {region: 0x95, script: 0x57, flags: 0x0}, + 120: {region: 0x165, script: 0x57, flags: 0x0}, + 121: {region: 0x12f, script: 0x57, flags: 0x0}, + 122: {region: 0x52, script: 0x57, flags: 0x0}, + 123: {region: 0x99, script: 0xd7, flags: 0x0}, 124: {region: 0xe8, script: 0x5, flags: 0x0}, - 125: {region: 0x99, script: 0x20, flags: 0x0}, - 126: {region: 0x38, script: 0x1e, flags: 0x0}, - 127: {region: 0x99, script: 0x20, flags: 0x0}, + 125: {region: 0x99, script: 0x21, flags: 0x0}, + 126: {region: 0x38, script: 0x1f, flags: 0x0}, + 127: {region: 0x99, script: 0x21, flags: 0x0}, 128: {region: 0xe8, script: 0x5, flags: 0x0}, - 129: {region: 0x12b, script: 0x30, flags: 0x0}, - 131: {region: 0x99, script: 0x20, flags: 0x0}, - 132: {region: 0x165, script: 0x55, flags: 0x0}, - 133: {region: 0x99, script: 0x20, flags: 0x0}, - 134: {region: 0xe7, script: 0x55, flags: 0x0}, - 135: {region: 0x165, script: 0x55, flags: 0x0}, - 136: {region: 0x99, script: 0x20, flags: 0x0}, - 137: {region: 0x165, script: 0x55, flags: 0x0}, - 138: {region: 0x13f, script: 0x55, flags: 0x0}, - 139: {region: 0x165, script: 0x55, flags: 0x0}, - 140: {region: 0x165, script: 0x55, flags: 0x0}, - 141: {region: 0xe7, script: 0x55, flags: 0x0}, - 142: {region: 0x165, script: 0x55, flags: 0x0}, - 143: {region: 0xd6, script: 0x55, flags: 0x0}, - 144: {region: 0x165, script: 0x55, flags: 0x0}, - 145: {region: 0x165, script: 0x55, flags: 0x0}, - 146: {region: 0x165, script: 0x55, flags: 0x0}, - 147: {region: 0x165, script: 0x28, flags: 0x0}, - 148: {region: 0x99, script: 0x20, flags: 0x0}, - 149: {region: 0x95, script: 0x55, flags: 0x0}, - 150: {region: 0x165, script: 0x55, flags: 0x0}, - 151: {region: 0x165, script: 0x55, flags: 0x0}, - 152: {region: 0x114, script: 0x55, flags: 0x0}, - 153: {region: 0x165, script: 0x55, flags: 0x0}, - 154: {region: 0x165, script: 0x55, flags: 0x0}, - 155: {region: 0x52, script: 0x55, flags: 0x0}, - 156: {region: 0x165, script: 0x55, flags: 0x0}, - 157: {region: 0xe7, script: 0x55, flags: 0x0}, - 158: {region: 0x165, script: 0x55, flags: 0x0}, - 159: {region: 0x13e, script: 0xd5, flags: 0x0}, - 160: {region: 0xc3, script: 0x55, flags: 0x0}, - 161: {region: 0x165, script: 0x55, flags: 0x0}, - 162: {region: 0x165, script: 0x55, flags: 0x0}, - 163: {region: 0xc3, script: 0x55, flags: 0x0}, - 164: {region: 0x165, script: 0x55, flags: 0x0}, + 129: {region: 0x12b, script: 0x31, flags: 0x0}, + 131: {region: 0x99, script: 0x21, flags: 0x0}, + 132: {region: 0x165, script: 0x57, flags: 0x0}, + 133: {region: 0x99, script: 0x21, flags: 0x0}, + 134: {region: 0xe7, script: 0x57, flags: 0x0}, + 135: {region: 0x165, script: 0x57, flags: 0x0}, + 136: {region: 0x99, script: 0x21, flags: 0x0}, + 137: {region: 0x165, script: 0x57, flags: 0x0}, + 138: {region: 0x13f, script: 0x57, flags: 0x0}, + 139: {region: 0x165, script: 0x57, flags: 0x0}, + 140: {region: 0x165, script: 0x57, flags: 0x0}, + 141: {region: 0xe7, script: 0x57, flags: 0x0}, + 142: {region: 0x165, script: 0x57, flags: 0x0}, + 143: {region: 0xd6, script: 0x57, flags: 0x0}, + 144: {region: 0x165, script: 0x57, flags: 0x0}, + 145: {region: 0x165, script: 0x57, flags: 0x0}, + 146: {region: 0x165, script: 0x57, flags: 0x0}, + 147: {region: 0x165, script: 0x29, flags: 0x0}, + 148: {region: 0x99, script: 0x21, flags: 0x0}, + 149: {region: 0x95, script: 0x57, flags: 0x0}, + 150: {region: 0x165, script: 0x57, flags: 0x0}, + 151: {region: 0x165, script: 0x57, flags: 0x0}, + 152: {region: 0x114, script: 0x57, flags: 0x0}, + 153: {region: 0x165, script: 0x57, flags: 0x0}, + 154: {region: 0x165, script: 0x57, flags: 0x0}, + 155: {region: 0x52, script: 0x57, flags: 0x0}, + 156: {region: 0x165, script: 0x57, flags: 0x0}, + 157: {region: 0xe7, script: 0x57, flags: 0x0}, + 158: {region: 0x165, script: 0x57, flags: 0x0}, + 159: {region: 0x13e, script: 0xd9, flags: 0x0}, + 160: {region: 0xc3, script: 0x57, flags: 0x0}, + 161: {region: 0x165, script: 0x57, flags: 0x0}, + 162: {region: 0x165, script: 0x57, flags: 0x0}, + 163: {region: 0xc3, script: 0x57, flags: 0x0}, + 164: {region: 0x165, script: 0x57, flags: 0x0}, 165: {region: 0x35, script: 0xe, flags: 0x0}, - 166: {region: 0x165, script: 0x55, flags: 0x0}, - 167: {region: 0x165, script: 0x55, flags: 0x0}, - 168: {region: 0x165, script: 0x55, flags: 0x0}, - 169: {region: 0x53, script: 0xdc, flags: 0x0}, - 170: {region: 0x165, script: 0x55, flags: 0x0}, - 171: {region: 0x165, script: 0x55, flags: 0x0}, - 172: {region: 0x165, script: 0x55, flags: 0x0}, + 166: {region: 0x165, script: 0x57, flags: 0x0}, + 167: {region: 0x165, script: 0x57, flags: 0x0}, + 168: {region: 0x165, script: 0x57, flags: 0x0}, + 169: {region: 0x53, script: 0xe0, flags: 0x0}, + 170: {region: 0x165, script: 0x57, flags: 0x0}, + 171: {region: 0x165, script: 0x57, flags: 0x0}, + 172: {region: 0x165, script: 0x57, flags: 0x0}, 173: {region: 0x99, script: 0xe, flags: 0x0}, - 174: {region: 0x165, script: 0x55, flags: 0x0}, + 174: {region: 0x165, script: 0x57, flags: 0x0}, 175: {region: 0x9c, script: 0x5, flags: 0x0}, - 176: {region: 0x165, script: 0x55, flags: 0x0}, - 177: {region: 0x4f, script: 0x55, flags: 0x0}, - 178: {region: 0x78, script: 0x55, flags: 0x0}, - 179: {region: 0x99, script: 0x20, flags: 0x0}, + 176: {region: 0x165, script: 0x57, flags: 0x0}, + 177: {region: 0x4f, script: 0x57, flags: 0x0}, + 178: {region: 0x78, script: 0x57, flags: 0x0}, + 179: {region: 0x99, script: 0x21, flags: 0x0}, 180: {region: 0xe8, script: 0x5, flags: 0x0}, - 181: {region: 0x99, script: 0x20, flags: 0x0}, - 182: {region: 0x165, script: 0x55, flags: 0x0}, - 183: {region: 0x33, script: 0x55, flags: 0x0}, - 184: {region: 0x165, script: 0x55, flags: 0x0}, + 181: {region: 0x99, script: 0x21, flags: 0x0}, + 182: {region: 0x165, script: 0x57, flags: 0x0}, + 183: {region: 0x33, script: 0x57, flags: 0x0}, + 184: {region: 0x165, script: 0x57, flags: 0x0}, 185: {region: 0xb4, script: 0xc, flags: 0x0}, - 186: {region: 0x52, script: 0x55, flags: 0x0}, - 187: {region: 0x165, script: 0x28, flags: 0x0}, - 188: {region: 0xe7, script: 0x55, flags: 0x0}, - 189: {region: 0x165, script: 0x55, flags: 0x0}, - 190: {region: 0xe8, script: 0x20, flags: 0x0}, - 191: {region: 0x106, script: 0x1e, flags: 0x0}, - 192: {region: 0x15f, script: 0x55, flags: 0x0}, - 193: {region: 0x165, script: 0x55, flags: 0x0}, - 194: {region: 0x95, script: 0x55, flags: 0x0}, - 195: {region: 0x165, script: 0x55, flags: 0x0}, - 196: {region: 0x52, script: 0x55, flags: 0x0}, - 197: {region: 0x165, script: 0x55, flags: 0x0}, - 198: {region: 0x165, script: 0x55, flags: 0x0}, - 199: {region: 0x165, script: 0x55, flags: 0x0}, - 200: {region: 0x86, script: 0x55, flags: 0x0}, - 201: {region: 0x165, script: 0x55, flags: 0x0}, - 202: {region: 0x165, script: 0x55, flags: 0x0}, - 203: {region: 0x165, script: 0x55, flags: 0x0}, - 204: {region: 0x165, script: 0x55, flags: 0x0}, - 205: {region: 0x6d, script: 0x28, flags: 0x0}, - 206: {region: 0x165, script: 0x55, flags: 0x0}, - 207: {region: 0x165, script: 0x55, flags: 0x0}, - 208: {region: 0x52, script: 0x55, flags: 0x0}, - 209: {region: 0x165, script: 0x55, flags: 0x0}, - 210: {region: 0x165, script: 0x55, flags: 0x0}, - 211: {region: 0xc3, script: 0x55, flags: 0x0}, - 212: {region: 0x165, script: 0x55, flags: 0x0}, - 213: {region: 0x165, script: 0x55, flags: 0x0}, - 214: {region: 0x165, script: 0x55, flags: 0x0}, - 215: {region: 0x6e, script: 0x55, flags: 0x0}, - 216: {region: 0x165, script: 0x55, flags: 0x0}, - 217: {region: 0x165, script: 0x55, flags: 0x0}, - 218: {region: 0xd6, script: 0x55, flags: 0x0}, + 186: {region: 0x52, script: 0x57, flags: 0x0}, + 187: {region: 0x165, script: 0x29, flags: 0x0}, + 188: {region: 0xe7, script: 0x57, flags: 0x0}, + 189: {region: 0x165, script: 0x57, flags: 0x0}, + 190: {region: 0xe8, script: 0x21, flags: 0x0}, + 191: {region: 0x106, script: 0x1f, flags: 0x0}, + 192: {region: 0x15f, script: 0x57, flags: 0x0}, + 193: {region: 0x165, script: 0x57, flags: 0x0}, + 194: {region: 0x95, script: 0x57, flags: 0x0}, + 195: {region: 0x165, script: 0x57, flags: 0x0}, + 196: {region: 0x52, script: 0x57, flags: 0x0}, + 197: {region: 0x165, script: 0x57, flags: 0x0}, + 198: {region: 0x165, script: 0x57, flags: 0x0}, + 199: {region: 0x165, script: 0x57, flags: 0x0}, + 200: {region: 0x86, script: 0x57, flags: 0x0}, + 201: {region: 0x165, script: 0x57, flags: 0x0}, + 202: {region: 0x165, script: 0x57, flags: 0x0}, + 203: {region: 0x165, script: 0x57, flags: 0x0}, + 204: {region: 0x165, script: 0x57, flags: 0x0}, + 205: {region: 0x6d, script: 0x29, flags: 0x0}, + 206: {region: 0x165, script: 0x57, flags: 0x0}, + 207: {region: 0x165, script: 0x57, flags: 0x0}, + 208: {region: 0x52, script: 0x57, flags: 0x0}, + 209: {region: 0x165, script: 0x57, flags: 0x0}, + 210: {region: 0x165, script: 0x57, flags: 0x0}, + 211: {region: 0xc3, script: 0x57, flags: 0x0}, + 212: {region: 0x165, script: 0x57, flags: 0x0}, + 213: {region: 0x165, script: 0x57, flags: 0x0}, + 214: {region: 0x165, script: 0x57, flags: 0x0}, + 215: {region: 0x6e, script: 0x57, flags: 0x0}, + 216: {region: 0x165, script: 0x57, flags: 0x0}, + 217: {region: 0x165, script: 0x57, flags: 0x0}, + 218: {region: 0xd6, script: 0x57, flags: 0x0}, 219: {region: 0x35, script: 0x16, flags: 0x0}, - 220: {region: 0x106, script: 0x1e, flags: 0x0}, - 221: {region: 0xe7, script: 0x55, flags: 0x0}, - 222: {region: 0x165, script: 0x55, flags: 0x0}, - 223: {region: 0x131, script: 0x55, flags: 0x0}, - 224: {region: 0x8a, script: 0x55, flags: 0x0}, - 225: {region: 0x75, script: 0x55, flags: 0x0}, - 226: {region: 0x106, script: 0x1e, flags: 0x0}, - 227: {region: 0x135, script: 0x55, flags: 0x0}, - 228: {region: 0x49, script: 0x55, flags: 0x0}, + 220: {region: 0x106, script: 0x1f, flags: 0x0}, + 221: {region: 0xe7, script: 0x57, flags: 0x0}, + 222: {region: 0x165, script: 0x57, flags: 0x0}, + 223: {region: 0x131, script: 0x57, flags: 0x0}, + 224: {region: 0x8a, script: 0x57, flags: 0x0}, + 225: {region: 0x75, script: 0x57, flags: 0x0}, + 226: {region: 0x106, script: 0x1f, flags: 0x0}, + 227: {region: 0x135, script: 0x57, flags: 0x0}, + 228: {region: 0x49, script: 0x57, flags: 0x0}, 229: {region: 0x135, script: 0x1a, flags: 0x0}, 230: {region: 0xa6, script: 0x5, flags: 0x0}, 231: {region: 0x13e, script: 0x19, flags: 0x0}, - 232: {region: 0x165, script: 0x55, flags: 0x0}, + 232: {region: 0x165, script: 0x57, flags: 0x0}, 233: {region: 0x9b, script: 0x5, flags: 0x0}, - 234: {region: 0x165, script: 0x55, flags: 0x0}, - 235: {region: 0x165, script: 0x55, flags: 0x0}, - 236: {region: 0x165, script: 0x55, flags: 0x0}, - 237: {region: 0x165, script: 0x55, flags: 0x0}, - 238: {region: 0x165, script: 0x55, flags: 0x0}, - 239: {region: 0x78, script: 0x55, flags: 0x0}, - 240: {region: 0x6b, script: 0x1c, flags: 0x0}, - 241: {region: 0xe7, script: 0x55, flags: 0x0}, - 242: {region: 0x49, script: 0x17, flags: 0x0}, - 243: {region: 0x130, script: 0x1e, flags: 0x0}, - 244: {region: 0x49, script: 0x17, flags: 0x0}, + 234: {region: 0x165, script: 0x57, flags: 0x0}, + 235: {region: 0x165, script: 0x57, flags: 0x0}, + 236: {region: 0x165, script: 0x57, flags: 0x0}, + 237: {region: 0x165, script: 0x57, flags: 0x0}, + 238: {region: 0x165, script: 0x57, flags: 0x0}, + 239: {region: 0xc5, script: 0xcc, flags: 0x0}, + 240: {region: 0x78, script: 0x57, flags: 0x0}, + 241: {region: 0x6b, script: 0x1c, flags: 0x0}, + 242: {region: 0xe7, script: 0x57, flags: 0x0}, + 243: {region: 0x49, script: 0x17, flags: 0x0}, + 244: {region: 0x130, script: 0x1f, flags: 0x0}, 245: {region: 0x49, script: 0x17, flags: 0x0}, 246: {region: 0x49, script: 0x17, flags: 0x0}, 247: {region: 0x49, script: 0x17, flags: 0x0}, - 248: {region: 0x10a, script: 0x55, flags: 0x0}, - 249: {region: 0x5e, script: 0x55, flags: 0x0}, - 250: {region: 0xe9, script: 0x55, flags: 0x0}, - 251: {region: 0x49, script: 0x17, flags: 0x0}, - 252: {region: 0xc4, script: 0x7e, flags: 0x0}, - 253: {region: 0x8, script: 0x2, flags: 0x1}, - 254: {region: 0x106, script: 0x1e, flags: 0x0}, - 255: {region: 0x7b, script: 0x55, flags: 0x0}, - 256: {region: 0x63, script: 0x55, flags: 0x0}, - 257: {region: 0x165, script: 0x55, flags: 0x0}, - 258: {region: 0x165, script: 0x55, flags: 0x0}, - 259: {region: 0x165, script: 0x55, flags: 0x0}, - 260: {region: 0x165, script: 0x55, flags: 0x0}, - 261: {region: 0x135, script: 0x55, flags: 0x0}, - 262: {region: 0x106, script: 0x1e, flags: 0x0}, - 263: {region: 0xa4, script: 0x55, flags: 0x0}, - 264: {region: 0x165, script: 0x55, flags: 0x0}, - 265: {region: 0x165, script: 0x55, flags: 0x0}, - 266: {region: 0x99, script: 0x5, flags: 0x0}, - 267: {region: 0x165, script: 0x55, flags: 0x0}, - 268: {region: 0x60, script: 0x55, flags: 0x0}, - 269: {region: 0x165, script: 0x55, flags: 0x0}, - 270: {region: 0x49, script: 0x55, flags: 0x0}, - 271: {region: 0x165, script: 0x55, flags: 0x0}, - 272: {region: 0x165, script: 0x55, flags: 0x0}, - 273: {region: 0x165, script: 0x55, flags: 0x0}, - 274: {region: 0x165, script: 0x5, flags: 0x0}, - 275: {region: 0x49, script: 0x55, flags: 0x0}, - 276: {region: 0x165, script: 0x55, flags: 0x0}, - 277: {region: 0x165, script: 0x55, flags: 0x0}, - 278: {region: 0xd4, script: 0x55, flags: 0x0}, - 279: {region: 0x4f, script: 0x55, flags: 0x0}, - 280: {region: 0x165, script: 0x55, flags: 0x0}, - 281: {region: 0x99, script: 0x5, flags: 0x0}, - 282: {region: 0x165, script: 0x55, flags: 0x0}, - 283: {region: 0x165, script: 0x55, flags: 0x0}, - 284: {region: 0x165, script: 0x55, flags: 0x0}, - 285: {region: 0x165, script: 0x28, flags: 0x0}, - 286: {region: 0x60, script: 0x55, flags: 0x0}, - 287: {region: 0xc3, script: 0x55, flags: 0x0}, - 288: {region: 0xd0, script: 0x55, flags: 0x0}, - 289: {region: 0x165, script: 0x55, flags: 0x0}, - 290: {region: 0xdb, script: 0x20, flags: 0x0}, - 291: {region: 0x52, script: 0x55, flags: 0x0}, - 292: {region: 0x165, script: 0x55, flags: 0x0}, - 293: {region: 0x165, script: 0x55, flags: 0x0}, - 294: {region: 0x165, script: 0x55, flags: 0x0}, - 295: {region: 0xcd, script: 0xda, flags: 0x0}, - 296: {region: 0x165, script: 0x55, flags: 0x0}, - 297: {region: 0x165, script: 0x55, flags: 0x0}, - 298: {region: 0x114, script: 0x55, flags: 0x0}, - 299: {region: 0x37, script: 0x55, flags: 0x0}, - 300: {region: 0x43, script: 0xdc, flags: 0x0}, - 301: {region: 0x165, script: 0x55, flags: 0x0}, - 302: {region: 0xa4, script: 0x55, flags: 0x0}, - 303: {region: 0x80, script: 0x55, flags: 0x0}, - 304: {region: 0xd6, script: 0x55, flags: 0x0}, - 305: {region: 0x9e, script: 0x55, flags: 0x0}, - 306: {region: 0x6b, script: 0x26, flags: 0x0}, - 307: {region: 0x165, script: 0x55, flags: 0x0}, - 308: {region: 0xc4, script: 0x46, flags: 0x0}, - 309: {region: 0x87, script: 0x30, flags: 0x0}, - 310: {region: 0x165, script: 0x55, flags: 0x0}, - 311: {region: 0x165, script: 0x55, flags: 0x0}, - 312: {region: 0xa, script: 0x2, flags: 0x1}, - 313: {region: 0x165, script: 0x55, flags: 0x0}, - 314: {region: 0x165, script: 0x55, flags: 0x0}, - 315: {region: 0x1, script: 0x55, flags: 0x0}, - 316: {region: 0x165, script: 0x55, flags: 0x0}, - 317: {region: 0x6e, script: 0x55, flags: 0x0}, - 318: {region: 0x135, script: 0x55, flags: 0x0}, - 319: {region: 0x6a, script: 0x55, flags: 0x0}, - 320: {region: 0x165, script: 0x55, flags: 0x0}, - 321: {region: 0x9e, script: 0x41, flags: 0x0}, - 322: {region: 0x165, script: 0x55, flags: 0x0}, - 323: {region: 0x165, script: 0x55, flags: 0x0}, - 324: {region: 0x6e, script: 0x55, flags: 0x0}, - 325: {region: 0x52, script: 0x55, flags: 0x0}, - 326: {region: 0x6e, script: 0x55, flags: 0x0}, - 327: {region: 0x9c, script: 0x5, flags: 0x0}, - 328: {region: 0x165, script: 0x55, flags: 0x0}, - 329: {region: 0x165, script: 0x55, flags: 0x0}, - 330: {region: 0x165, script: 0x55, flags: 0x0}, - 331: {region: 0x165, script: 0x55, flags: 0x0}, - 332: {region: 0x86, script: 0x55, flags: 0x0}, - 333: {region: 0xc, script: 0x2, flags: 0x1}, - 334: {region: 0x165, script: 0x55, flags: 0x0}, - 335: {region: 0xc3, script: 0x55, flags: 0x0}, - 336: {region: 0x72, script: 0x55, flags: 0x0}, - 337: {region: 0x10b, script: 0x5, flags: 0x0}, - 338: {region: 0xe7, script: 0x55, flags: 0x0}, - 339: {region: 0x10c, script: 0x55, flags: 0x0}, - 340: {region: 0x73, script: 0x55, flags: 0x0}, - 341: {region: 0x165, script: 0x55, flags: 0x0}, - 342: {region: 0x165, script: 0x55, flags: 0x0}, - 343: {region: 0x76, script: 0x55, flags: 0x0}, - 344: {region: 0x165, script: 0x55, flags: 0x0}, - 345: {region: 0x3b, script: 0x55, flags: 0x0}, - 346: {region: 0x165, script: 0x55, flags: 0x0}, - 347: {region: 0x165, script: 0x55, flags: 0x0}, - 348: {region: 0x165, script: 0x55, flags: 0x0}, - 349: {region: 0x78, script: 0x55, flags: 0x0}, - 350: {region: 0x135, script: 0x55, flags: 0x0}, - 351: {region: 0x78, script: 0x55, flags: 0x0}, - 352: {region: 0x60, script: 0x55, flags: 0x0}, - 353: {region: 0x60, script: 0x55, flags: 0x0}, - 354: {region: 0x52, script: 0x5, flags: 0x0}, - 355: {region: 0x140, script: 0x55, flags: 0x0}, - 356: {region: 0x165, script: 0x55, flags: 0x0}, - 357: {region: 0x84, script: 0x55, flags: 0x0}, - 358: {region: 0x165, script: 0x55, flags: 0x0}, - 359: {region: 0xd4, script: 0x55, flags: 0x0}, - 360: {region: 0x9e, script: 0x55, flags: 0x0}, - 361: {region: 0xd6, script: 0x55, flags: 0x0}, - 362: {region: 0x165, script: 0x55, flags: 0x0}, - 363: {region: 0x10b, script: 0x55, flags: 0x0}, - 364: {region: 0xd9, script: 0x55, flags: 0x0}, - 365: {region: 0x96, script: 0x55, flags: 0x0}, - 366: {region: 0x80, script: 0x55, flags: 0x0}, - 367: {region: 0x165, script: 0x55, flags: 0x0}, - 368: {region: 0xbc, script: 0x55, flags: 0x0}, - 369: {region: 0x165, script: 0x55, flags: 0x0}, - 370: {region: 0x165, script: 0x55, flags: 0x0}, - 371: {region: 0x165, script: 0x55, flags: 0x0}, - 372: {region: 0x53, script: 0x37, flags: 0x0}, - 373: {region: 0x165, script: 0x55, flags: 0x0}, - 374: {region: 0x95, script: 0x55, flags: 0x0}, - 375: {region: 0x165, script: 0x55, flags: 0x0}, - 376: {region: 0x99, script: 0x20, flags: 0x0}, - 377: {region: 0x165, script: 0x55, flags: 0x0}, - 378: {region: 0x9c, script: 0x5, flags: 0x0}, - 379: {region: 0x7e, script: 0x55, flags: 0x0}, - 380: {region: 0x7b, script: 0x55, flags: 0x0}, - 381: {region: 0x165, script: 0x55, flags: 0x0}, - 382: {region: 0x165, script: 0x55, flags: 0x0}, - 383: {region: 0x165, script: 0x55, flags: 0x0}, - 384: {region: 0x165, script: 0x55, flags: 0x0}, - 385: {region: 0x165, script: 0x55, flags: 0x0}, - 386: {region: 0x165, script: 0x55, flags: 0x0}, - 387: {region: 0x6f, script: 0x28, flags: 0x0}, - 388: {region: 0x165, script: 0x55, flags: 0x0}, - 389: {region: 0xdb, script: 0x20, flags: 0x0}, - 390: {region: 0x165, script: 0x55, flags: 0x0}, - 391: {region: 0xa7, script: 0x55, flags: 0x0}, - 392: {region: 0x165, script: 0x55, flags: 0x0}, - 393: {region: 0xe8, script: 0x5, flags: 0x0}, - 394: {region: 0x165, script: 0x55, flags: 0x0}, + 248: {region: 0x49, script: 0x17, flags: 0x0}, + 249: {region: 0x10a, script: 0x57, flags: 0x0}, + 250: {region: 0x5e, script: 0x57, flags: 0x0}, + 251: {region: 0xe9, script: 0x57, flags: 0x0}, + 252: {region: 0x49, script: 0x17, flags: 0x0}, + 253: {region: 0xc4, script: 0x81, flags: 0x0}, + 254: {region: 0x8, script: 0x2, flags: 0x1}, + 255: {region: 0x106, script: 0x1f, flags: 0x0}, + 256: {region: 0x7b, script: 0x57, flags: 0x0}, + 257: {region: 0x63, script: 0x57, flags: 0x0}, + 258: {region: 0x165, script: 0x57, flags: 0x0}, + 259: {region: 0x165, script: 0x57, flags: 0x0}, + 260: {region: 0x165, script: 0x57, flags: 0x0}, + 261: {region: 0x165, script: 0x57, flags: 0x0}, + 262: {region: 0x135, script: 0x57, flags: 0x0}, + 263: {region: 0x106, script: 0x1f, flags: 0x0}, + 264: {region: 0xa4, script: 0x57, flags: 0x0}, + 265: {region: 0x165, script: 0x57, flags: 0x0}, + 266: {region: 0x165, script: 0x57, flags: 0x0}, + 267: {region: 0x99, script: 0x5, flags: 0x0}, + 268: {region: 0x165, script: 0x57, flags: 0x0}, + 269: {region: 0x60, script: 0x57, flags: 0x0}, + 270: {region: 0x165, script: 0x57, flags: 0x0}, + 271: {region: 0x49, script: 0x57, flags: 0x0}, + 272: {region: 0x165, script: 0x57, flags: 0x0}, + 273: {region: 0x165, script: 0x57, flags: 0x0}, + 274: {region: 0x165, script: 0x57, flags: 0x0}, + 275: {region: 0x165, script: 0x5, flags: 0x0}, + 276: {region: 0x49, script: 0x57, flags: 0x0}, + 277: {region: 0x165, script: 0x57, flags: 0x0}, + 278: {region: 0x165, script: 0x57, flags: 0x0}, + 279: {region: 0xd4, script: 0x57, flags: 0x0}, + 280: {region: 0x4f, script: 0x57, flags: 0x0}, + 281: {region: 0x165, script: 0x57, flags: 0x0}, + 282: {region: 0x99, script: 0x5, flags: 0x0}, + 283: {region: 0x165, script: 0x57, flags: 0x0}, + 284: {region: 0x165, script: 0x57, flags: 0x0}, + 285: {region: 0x165, script: 0x57, flags: 0x0}, + 286: {region: 0x165, script: 0x29, flags: 0x0}, + 287: {region: 0x60, script: 0x57, flags: 0x0}, + 288: {region: 0xc3, script: 0x57, flags: 0x0}, + 289: {region: 0xd0, script: 0x57, flags: 0x0}, + 290: {region: 0x165, script: 0x57, flags: 0x0}, + 291: {region: 0xdb, script: 0x21, flags: 0x0}, + 292: {region: 0x52, script: 0x57, flags: 0x0}, + 293: {region: 0x165, script: 0x57, flags: 0x0}, + 294: {region: 0x165, script: 0x57, flags: 0x0}, + 295: {region: 0x165, script: 0x57, flags: 0x0}, + 296: {region: 0xcd, script: 0xde, flags: 0x0}, + 297: {region: 0x165, script: 0x57, flags: 0x0}, + 298: {region: 0x165, script: 0x57, flags: 0x0}, + 299: {region: 0x114, script: 0x57, flags: 0x0}, + 300: {region: 0x37, script: 0x57, flags: 0x0}, + 301: {region: 0x43, script: 0xe0, flags: 0x0}, + 302: {region: 0x165, script: 0x57, flags: 0x0}, + 303: {region: 0xa4, script: 0x57, flags: 0x0}, + 304: {region: 0x80, script: 0x57, flags: 0x0}, + 305: {region: 0xd6, script: 0x57, flags: 0x0}, + 306: {region: 0x9e, script: 0x57, flags: 0x0}, + 307: {region: 0x6b, script: 0x27, flags: 0x0}, + 308: {region: 0x165, script: 0x57, flags: 0x0}, + 309: {region: 0xc4, script: 0x48, flags: 0x0}, + 310: {region: 0x87, script: 0x31, flags: 0x0}, + 311: {region: 0x165, script: 0x57, flags: 0x0}, + 312: {region: 0x165, script: 0x57, flags: 0x0}, + 313: {region: 0xa, script: 0x2, flags: 0x1}, + 314: {region: 0x165, script: 0x57, flags: 0x0}, + 315: {region: 0x165, script: 0x57, flags: 0x0}, + 316: {region: 0x1, script: 0x57, flags: 0x0}, + 317: {region: 0x165, script: 0x57, flags: 0x0}, + 318: {region: 0x6e, script: 0x57, flags: 0x0}, + 319: {region: 0x135, script: 0x57, flags: 0x0}, + 320: {region: 0x6a, script: 0x57, flags: 0x0}, + 321: {region: 0x165, script: 0x57, flags: 0x0}, + 322: {region: 0x9e, script: 0x43, flags: 0x0}, + 323: {region: 0x165, script: 0x57, flags: 0x0}, + 324: {region: 0x165, script: 0x57, flags: 0x0}, + 325: {region: 0x6e, script: 0x57, flags: 0x0}, + 326: {region: 0x52, script: 0x57, flags: 0x0}, + 327: {region: 0x6e, script: 0x57, flags: 0x0}, + 328: {region: 0x9c, script: 0x5, flags: 0x0}, + 329: {region: 0x165, script: 0x57, flags: 0x0}, + 330: {region: 0x165, script: 0x57, flags: 0x0}, + 331: {region: 0x165, script: 0x57, flags: 0x0}, + 332: {region: 0x165, script: 0x57, flags: 0x0}, + 333: {region: 0x86, script: 0x57, flags: 0x0}, + 334: {region: 0xc, script: 0x2, flags: 0x1}, + 335: {region: 0x165, script: 0x57, flags: 0x0}, + 336: {region: 0xc3, script: 0x57, flags: 0x0}, + 337: {region: 0x72, script: 0x57, flags: 0x0}, + 338: {region: 0x10b, script: 0x5, flags: 0x0}, + 339: {region: 0xe7, script: 0x57, flags: 0x0}, + 340: {region: 0x10c, script: 0x57, flags: 0x0}, + 341: {region: 0x73, script: 0x57, flags: 0x0}, + 342: {region: 0x165, script: 0x57, flags: 0x0}, + 343: {region: 0x165, script: 0x57, flags: 0x0}, + 344: {region: 0x76, script: 0x57, flags: 0x0}, + 345: {region: 0x165, script: 0x57, flags: 0x0}, + 346: {region: 0x3b, script: 0x57, flags: 0x0}, + 347: {region: 0x165, script: 0x57, flags: 0x0}, + 348: {region: 0x165, script: 0x57, flags: 0x0}, + 349: {region: 0x165, script: 0x57, flags: 0x0}, + 350: {region: 0x78, script: 0x57, flags: 0x0}, + 351: {region: 0x135, script: 0x57, flags: 0x0}, + 352: {region: 0x78, script: 0x57, flags: 0x0}, + 353: {region: 0x60, script: 0x57, flags: 0x0}, + 354: {region: 0x60, script: 0x57, flags: 0x0}, + 355: {region: 0x52, script: 0x5, flags: 0x0}, + 356: {region: 0x140, script: 0x57, flags: 0x0}, + 357: {region: 0x165, script: 0x57, flags: 0x0}, + 358: {region: 0x84, script: 0x57, flags: 0x0}, + 359: {region: 0x165, script: 0x57, flags: 0x0}, + 360: {region: 0xd4, script: 0x57, flags: 0x0}, + 361: {region: 0x9e, script: 0x57, flags: 0x0}, + 362: {region: 0xd6, script: 0x57, flags: 0x0}, + 363: {region: 0x165, script: 0x57, flags: 0x0}, + 364: {region: 0x10b, script: 0x57, flags: 0x0}, + 365: {region: 0xd9, script: 0x57, flags: 0x0}, + 366: {region: 0x96, script: 0x57, flags: 0x0}, + 367: {region: 0x80, script: 0x57, flags: 0x0}, + 368: {region: 0x165, script: 0x57, flags: 0x0}, + 369: {region: 0xbc, script: 0x57, flags: 0x0}, + 370: {region: 0x165, script: 0x57, flags: 0x0}, + 371: {region: 0x165, script: 0x57, flags: 0x0}, + 372: {region: 0x165, script: 0x57, flags: 0x0}, + 373: {region: 0x53, script: 0x38, flags: 0x0}, + 374: {region: 0x165, script: 0x57, flags: 0x0}, + 375: {region: 0x95, script: 0x57, flags: 0x0}, + 376: {region: 0x165, script: 0x57, flags: 0x0}, + 377: {region: 0x165, script: 0x57, flags: 0x0}, + 378: {region: 0x99, script: 0x21, flags: 0x0}, + 379: {region: 0x165, script: 0x57, flags: 0x0}, + 380: {region: 0x9c, script: 0x5, flags: 0x0}, + 381: {region: 0x7e, script: 0x57, flags: 0x0}, + 382: {region: 0x7b, script: 0x57, flags: 0x0}, + 383: {region: 0x165, script: 0x57, flags: 0x0}, + 384: {region: 0x165, script: 0x57, flags: 0x0}, + 385: {region: 0x165, script: 0x57, flags: 0x0}, + 386: {region: 0x165, script: 0x57, flags: 0x0}, + 387: {region: 0x165, script: 0x57, flags: 0x0}, + 388: {region: 0x165, script: 0x57, flags: 0x0}, + 389: {region: 0x6f, script: 0x29, flags: 0x0}, + 390: {region: 0x165, script: 0x57, flags: 0x0}, + 391: {region: 0xdb, script: 0x21, flags: 0x0}, + 392: {region: 0x165, script: 0x57, flags: 0x0}, + 393: {region: 0xa7, script: 0x57, flags: 0x0}, + 394: {region: 0x165, script: 0x57, flags: 0x0}, 395: {region: 0xe8, script: 0x5, flags: 0x0}, - 396: {region: 0x165, script: 0x55, flags: 0x0}, - 397: {region: 0x165, script: 0x55, flags: 0x0}, - 398: {region: 0x6e, script: 0x55, flags: 0x0}, - 399: {region: 0x9c, script: 0x5, flags: 0x0}, - 400: {region: 0x165, script: 0x55, flags: 0x0}, - 401: {region: 0x165, script: 0x28, flags: 0x0}, - 402: {region: 0xf1, script: 0x55, flags: 0x0}, - 403: {region: 0x165, script: 0x55, flags: 0x0}, - 404: {region: 0x165, script: 0x55, flags: 0x0}, - 405: {region: 0x165, script: 0x55, flags: 0x0}, - 406: {region: 0x165, script: 0x28, flags: 0x0}, - 407: {region: 0x165, script: 0x55, flags: 0x0}, - 408: {region: 0x99, script: 0x20, flags: 0x0}, - 409: {region: 0x99, script: 0xd6, flags: 0x0}, - 410: {region: 0x95, script: 0x55, flags: 0x0}, - 411: {region: 0xd9, script: 0x55, flags: 0x0}, - 412: {region: 0x130, script: 0x2e, flags: 0x0}, - 413: {region: 0x165, script: 0x55, flags: 0x0}, - 414: {region: 0xe, script: 0x2, flags: 0x1}, - 415: {region: 0x99, script: 0xe, flags: 0x0}, - 416: {region: 0x165, script: 0x55, flags: 0x0}, - 417: {region: 0x4e, script: 0x55, flags: 0x0}, - 418: {region: 0x99, script: 0x31, flags: 0x0}, - 419: {region: 0x41, script: 0x55, flags: 0x0}, - 420: {region: 0x54, script: 0x55, flags: 0x0}, - 421: {region: 0x165, script: 0x55, flags: 0x0}, - 422: {region: 0x80, script: 0x55, flags: 0x0}, - 423: {region: 0x165, script: 0x55, flags: 0x0}, - 424: {region: 0x165, script: 0x55, flags: 0x0}, - 425: {region: 0xa4, script: 0x55, flags: 0x0}, - 426: {region: 0x98, script: 0x55, flags: 0x0}, - 427: {region: 0x165, script: 0x55, flags: 0x0}, - 428: {region: 0xdb, script: 0x20, flags: 0x0}, - 429: {region: 0x165, script: 0x55, flags: 0x0}, - 430: {region: 0x165, script: 0x5, flags: 0x0}, - 431: {region: 0x49, script: 0x55, flags: 0x0}, + 396: {region: 0x165, script: 0x57, flags: 0x0}, + 397: {region: 0xe8, script: 0x5, flags: 0x0}, + 398: {region: 0x165, script: 0x57, flags: 0x0}, + 399: {region: 0x165, script: 0x57, flags: 0x0}, + 400: {region: 0x6e, script: 0x57, flags: 0x0}, + 401: {region: 0x9c, script: 0x5, flags: 0x0}, + 402: {region: 0x165, script: 0x57, flags: 0x0}, + 403: {region: 0x165, script: 0x29, flags: 0x0}, + 404: {region: 0xf1, script: 0x57, flags: 0x0}, + 405: {region: 0x165, script: 0x57, flags: 0x0}, + 406: {region: 0x165, script: 0x57, flags: 0x0}, + 407: {region: 0x165, script: 0x57, flags: 0x0}, + 408: {region: 0x165, script: 0x29, flags: 0x0}, + 409: {region: 0x165, script: 0x57, flags: 0x0}, + 410: {region: 0x99, script: 0x21, flags: 0x0}, + 411: {region: 0x99, script: 0xda, flags: 0x0}, + 412: {region: 0x95, script: 0x57, flags: 0x0}, + 413: {region: 0xd9, script: 0x57, flags: 0x0}, + 414: {region: 0x130, script: 0x2f, flags: 0x0}, + 415: {region: 0x165, script: 0x57, flags: 0x0}, + 416: {region: 0xe, script: 0x2, flags: 0x1}, + 417: {region: 0x99, script: 0xe, flags: 0x0}, + 418: {region: 0x165, script: 0x57, flags: 0x0}, + 419: {region: 0x4e, script: 0x57, flags: 0x0}, + 420: {region: 0x99, script: 0x32, flags: 0x0}, + 421: {region: 0x41, script: 0x57, flags: 0x0}, + 422: {region: 0x54, script: 0x57, flags: 0x0}, + 423: {region: 0x165, script: 0x57, flags: 0x0}, + 424: {region: 0x80, script: 0x57, flags: 0x0}, + 425: {region: 0x165, script: 0x57, flags: 0x0}, + 426: {region: 0x165, script: 0x57, flags: 0x0}, + 427: {region: 0xa4, script: 0x57, flags: 0x0}, + 428: {region: 0x98, script: 0x57, flags: 0x0}, + 429: {region: 0x165, script: 0x57, flags: 0x0}, + 430: {region: 0xdb, script: 0x21, flags: 0x0}, + 431: {region: 0x165, script: 0x57, flags: 0x0}, 432: {region: 0x165, script: 0x5, flags: 0x0}, - 433: {region: 0x165, script: 0x55, flags: 0x0}, - 434: {region: 0x10, script: 0x3, flags: 0x1}, - 435: {region: 0x165, script: 0x55, flags: 0x0}, - 436: {region: 0x53, script: 0x37, flags: 0x0}, - 437: {region: 0x165, script: 0x55, flags: 0x0}, - 438: {region: 0x135, script: 0x55, flags: 0x0}, - 439: {region: 0x24, script: 0x5, flags: 0x0}, - 440: {region: 0x165, script: 0x55, flags: 0x0}, - 441: {region: 0x165, script: 0x28, flags: 0x0}, - 442: {region: 0x97, script: 0x3a, flags: 0x0}, - 443: {region: 0x165, script: 0x55, flags: 0x0}, - 444: {region: 0x99, script: 0x20, flags: 0x0}, - 445: {region: 0x165, script: 0x55, flags: 0x0}, - 446: {region: 0x73, script: 0x55, flags: 0x0}, - 447: {region: 0x165, script: 0x55, flags: 0x0}, - 448: {region: 0x165, script: 0x55, flags: 0x0}, - 449: {region: 0xe7, script: 0x55, flags: 0x0}, - 450: {region: 0x165, script: 0x55, flags: 0x0}, - 451: {region: 0x12b, script: 0x3c, flags: 0x0}, - 452: {region: 0x53, script: 0x86, flags: 0x0}, - 453: {region: 0x165, script: 0x55, flags: 0x0}, - 454: {region: 0xe8, script: 0x5, flags: 0x0}, - 455: {region: 0x99, script: 0x20, flags: 0x0}, - 456: {region: 0xaf, script: 0x3d, flags: 0x0}, - 457: {region: 0xe7, script: 0x55, flags: 0x0}, - 458: {region: 0xe8, script: 0x5, flags: 0x0}, - 459: {region: 0xe6, script: 0x55, flags: 0x0}, - 460: {region: 0x99, script: 0x20, flags: 0x0}, - 461: {region: 0x99, script: 0x20, flags: 0x0}, - 462: {region: 0x165, script: 0x55, flags: 0x0}, - 463: {region: 0x90, script: 0x55, flags: 0x0}, - 464: {region: 0x60, script: 0x55, flags: 0x0}, - 465: {region: 0x53, script: 0x37, flags: 0x0}, - 466: {region: 0x91, script: 0x55, flags: 0x0}, - 467: {region: 0x92, script: 0x55, flags: 0x0}, - 468: {region: 0x165, script: 0x55, flags: 0x0}, - 469: {region: 0x28, script: 0x8, flags: 0x0}, - 470: {region: 0xd2, script: 0x55, flags: 0x0}, - 471: {region: 0x78, script: 0x55, flags: 0x0}, - 472: {region: 0x165, script: 0x55, flags: 0x0}, - 473: {region: 0x165, script: 0x55, flags: 0x0}, - 474: {region: 0xd0, script: 0x55, flags: 0x0}, - 475: {region: 0xd6, script: 0x55, flags: 0x0}, - 476: {region: 0x165, script: 0x55, flags: 0x0}, - 477: {region: 0x165, script: 0x55, flags: 0x0}, - 478: {region: 0x165, script: 0x55, flags: 0x0}, - 479: {region: 0x95, script: 0x55, flags: 0x0}, - 480: {region: 0x165, script: 0x55, flags: 0x0}, - 481: {region: 0x165, script: 0x55, flags: 0x0}, - 482: {region: 0x165, script: 0x55, flags: 0x0}, - 484: {region: 0x122, script: 0x55, flags: 0x0}, - 485: {region: 0xd6, script: 0x55, flags: 0x0}, - 486: {region: 0x165, script: 0x55, flags: 0x0}, - 487: {region: 0x165, script: 0x55, flags: 0x0}, - 488: {region: 0x53, script: 0xe5, flags: 0x0}, - 489: {region: 0x165, script: 0x55, flags: 0x0}, - 490: {region: 0x135, script: 0x55, flags: 0x0}, - 491: {region: 0x165, script: 0x55, flags: 0x0}, - 492: {region: 0x49, script: 0x55, flags: 0x0}, - 493: {region: 0x165, script: 0x55, flags: 0x0}, - 494: {region: 0x165, script: 0x55, flags: 0x0}, - 495: {region: 0xe7, script: 0x55, flags: 0x0}, - 496: {region: 0x165, script: 0x55, flags: 0x0}, - 497: {region: 0x95, script: 0x55, flags: 0x0}, - 498: {region: 0x106, script: 0x1e, flags: 0x0}, - 500: {region: 0x165, script: 0x55, flags: 0x0}, - 501: {region: 0x165, script: 0x55, flags: 0x0}, - 502: {region: 0x9d, script: 0x55, flags: 0x0}, - 503: {region: 0x9e, script: 0x55, flags: 0x0}, - 504: {region: 0x49, script: 0x17, flags: 0x0}, - 505: {region: 0x97, script: 0x3a, flags: 0x0}, - 506: {region: 0x165, script: 0x55, flags: 0x0}, - 507: {region: 0x165, script: 0x55, flags: 0x0}, - 508: {region: 0x106, script: 0x55, flags: 0x0}, - 509: {region: 0x165, script: 0x55, flags: 0x0}, - 510: {region: 0xa2, script: 0x44, flags: 0x0}, - 511: {region: 0x165, script: 0x55, flags: 0x0}, - 512: {region: 0xa0, script: 0x55, flags: 0x0}, - 514: {region: 0x165, script: 0x55, flags: 0x0}, - 515: {region: 0x165, script: 0x55, flags: 0x0}, - 516: {region: 0x165, script: 0x55, flags: 0x0}, - 517: {region: 0x52, script: 0x55, flags: 0x0}, - 518: {region: 0x130, script: 0x3a, flags: 0x0}, - 519: {region: 0x165, script: 0x55, flags: 0x0}, - 520: {region: 0x12f, script: 0x55, flags: 0x0}, - 521: {region: 0xdb, script: 0x20, flags: 0x0}, - 522: {region: 0x165, script: 0x55, flags: 0x0}, - 523: {region: 0x63, script: 0x55, flags: 0x0}, - 524: {region: 0x95, script: 0x55, flags: 0x0}, - 525: {region: 0x95, script: 0x55, flags: 0x0}, - 526: {region: 0x7d, script: 0x2a, flags: 0x0}, - 527: {region: 0x137, script: 0x1e, flags: 0x0}, - 528: {region: 0x67, script: 0x55, flags: 0x0}, - 529: {region: 0xc4, script: 0x55, flags: 0x0}, - 530: {region: 0x165, script: 0x55, flags: 0x0}, - 531: {region: 0x165, script: 0x55, flags: 0x0}, - 532: {region: 0xd6, script: 0x55, flags: 0x0}, - 533: {region: 0xa4, script: 0x55, flags: 0x0}, - 534: {region: 0xc3, script: 0x55, flags: 0x0}, - 535: {region: 0x106, script: 0x1e, flags: 0x0}, - 536: {region: 0x165, script: 0x55, flags: 0x0}, - 537: {region: 0x165, script: 0x55, flags: 0x0}, - 538: {region: 0x165, script: 0x55, flags: 0x0}, - 539: {region: 0x165, script: 0x55, flags: 0x0}, - 540: {region: 0xd4, script: 0x5, flags: 0x0}, - 541: {region: 0xd6, script: 0x55, flags: 0x0}, - 542: {region: 0x164, script: 0x55, flags: 0x0}, - 543: {region: 0x165, script: 0x55, flags: 0x0}, - 544: {region: 0x165, script: 0x55, flags: 0x0}, - 545: {region: 0x12f, script: 0x55, flags: 0x0}, - 546: {region: 0x122, script: 0x5, flags: 0x0}, - 547: {region: 0x165, script: 0x55, flags: 0x0}, - 548: {region: 0x123, script: 0xdb, flags: 0x0}, - 549: {region: 0x5a, script: 0x55, flags: 0x0}, - 550: {region: 0x52, script: 0x55, flags: 0x0}, - 551: {region: 0x165, script: 0x55, flags: 0x0}, - 552: {region: 0x4f, script: 0x55, flags: 0x0}, - 553: {region: 0x99, script: 0x20, flags: 0x0}, - 554: {region: 0x99, script: 0x20, flags: 0x0}, - 555: {region: 0x4b, script: 0x55, flags: 0x0}, - 556: {region: 0x95, script: 0x55, flags: 0x0}, - 557: {region: 0x165, script: 0x55, flags: 0x0}, - 558: {region: 0x41, script: 0x55, flags: 0x0}, - 559: {region: 0x99, script: 0x55, flags: 0x0}, - 560: {region: 0x53, script: 0xd2, flags: 0x0}, - 561: {region: 0x99, script: 0x20, flags: 0x0}, - 562: {region: 0xc3, script: 0x55, flags: 0x0}, - 563: {region: 0x165, script: 0x55, flags: 0x0}, - 564: {region: 0x99, script: 0x70, flags: 0x0}, - 565: {region: 0xe8, script: 0x5, flags: 0x0}, - 566: {region: 0x165, script: 0x55, flags: 0x0}, - 567: {region: 0xa4, script: 0x55, flags: 0x0}, - 568: {region: 0x165, script: 0x55, flags: 0x0}, - 569: {region: 0x12b, script: 0x55, flags: 0x0}, - 570: {region: 0x165, script: 0x55, flags: 0x0}, - 571: {region: 0xd2, script: 0x55, flags: 0x0}, - 572: {region: 0x165, script: 0x55, flags: 0x0}, - 573: {region: 0xaf, script: 0x52, flags: 0x0}, - 574: {region: 0x165, script: 0x55, flags: 0x0}, - 575: {region: 0x165, script: 0x55, flags: 0x0}, - 576: {region: 0x13, script: 0x6, flags: 0x1}, - 577: {region: 0x165, script: 0x55, flags: 0x0}, - 578: {region: 0x52, script: 0x55, flags: 0x0}, - 579: {region: 0x82, script: 0x55, flags: 0x0}, - 580: {region: 0xa4, script: 0x55, flags: 0x0}, - 581: {region: 0x165, script: 0x55, flags: 0x0}, - 582: {region: 0x165, script: 0x55, flags: 0x0}, - 583: {region: 0x165, script: 0x55, flags: 0x0}, - 584: {region: 0xa6, script: 0x49, flags: 0x0}, - 585: {region: 0x2a, script: 0x55, flags: 0x0}, - 586: {region: 0x165, script: 0x55, flags: 0x0}, - 587: {region: 0x165, script: 0x55, flags: 0x0}, - 588: {region: 0x165, script: 0x55, flags: 0x0}, - 589: {region: 0x165, script: 0x55, flags: 0x0}, - 590: {region: 0x165, script: 0x55, flags: 0x0}, - 591: {region: 0x99, script: 0x4d, flags: 0x0}, - 592: {region: 0x114, script: 0x55, flags: 0x0}, - 593: {region: 0x165, script: 0x55, flags: 0x0}, - 594: {region: 0xab, script: 0x4e, flags: 0x0}, - 595: {region: 0x106, script: 0x1e, flags: 0x0}, - 596: {region: 0x99, script: 0x20, flags: 0x0}, - 597: {region: 0x165, script: 0x55, flags: 0x0}, - 598: {region: 0x75, script: 0x55, flags: 0x0}, - 599: {region: 0x165, script: 0x55, flags: 0x0}, - 600: {region: 0xb4, script: 0x55, flags: 0x0}, - 601: {region: 0x165, script: 0x55, flags: 0x0}, - 602: {region: 0x165, script: 0x55, flags: 0x0}, - 603: {region: 0x165, script: 0x55, flags: 0x0}, - 604: {region: 0x165, script: 0x55, flags: 0x0}, - 605: {region: 0x165, script: 0x55, flags: 0x0}, - 606: {region: 0x165, script: 0x55, flags: 0x0}, - 607: {region: 0x165, script: 0x55, flags: 0x0}, - 608: {region: 0x165, script: 0x28, flags: 0x0}, - 610: {region: 0x106, script: 0x1e, flags: 0x0}, - 611: {region: 0x112, script: 0x55, flags: 0x0}, - 612: {region: 0xe7, script: 0x55, flags: 0x0}, - 613: {region: 0x106, script: 0x55, flags: 0x0}, - 614: {region: 0x165, script: 0x55, flags: 0x0}, - 615: {region: 0x99, script: 0x20, flags: 0x0}, - 616: {region: 0x99, script: 0x5, flags: 0x0}, - 617: {region: 0x12f, script: 0x55, flags: 0x0}, - 618: {region: 0x165, script: 0x55, flags: 0x0}, - 619: {region: 0x52, script: 0x55, flags: 0x0}, - 620: {region: 0x60, script: 0x55, flags: 0x0}, - 621: {region: 0x165, script: 0x55, flags: 0x0}, - 622: {region: 0x165, script: 0x55, flags: 0x0}, - 623: {region: 0x165, script: 0x28, flags: 0x0}, - 624: {region: 0x165, script: 0x55, flags: 0x0}, - 625: {region: 0x165, script: 0x55, flags: 0x0}, - 626: {region: 0x19, script: 0x3, flags: 0x1}, - 627: {region: 0x165, script: 0x55, flags: 0x0}, - 628: {region: 0x165, script: 0x55, flags: 0x0}, - 629: {region: 0x165, script: 0x55, flags: 0x0}, - 630: {region: 0x165, script: 0x55, flags: 0x0}, - 631: {region: 0x106, script: 0x1e, flags: 0x0}, - 632: {region: 0x165, script: 0x55, flags: 0x0}, - 633: {region: 0x165, script: 0x55, flags: 0x0}, - 634: {region: 0x165, script: 0x55, flags: 0x0}, - 635: {region: 0x106, script: 0x1e, flags: 0x0}, - 636: {region: 0x165, script: 0x55, flags: 0x0}, - 637: {region: 0x95, script: 0x55, flags: 0x0}, - 638: {region: 0xe8, script: 0x5, flags: 0x0}, - 639: {region: 0x7b, script: 0x55, flags: 0x0}, - 640: {region: 0x165, script: 0x55, flags: 0x0}, - 641: {region: 0x165, script: 0x55, flags: 0x0}, - 642: {region: 0x165, script: 0x55, flags: 0x0}, - 643: {region: 0x165, script: 0x28, flags: 0x0}, - 644: {region: 0x123, script: 0xdb, flags: 0x0}, - 645: {region: 0xe8, script: 0x5, flags: 0x0}, - 646: {region: 0x165, script: 0x55, flags: 0x0}, - 647: {region: 0x165, script: 0x55, flags: 0x0}, - 648: {region: 0x1c, script: 0x5, flags: 0x1}, - 649: {region: 0x165, script: 0x55, flags: 0x0}, - 650: {region: 0x165, script: 0x55, flags: 0x0}, - 651: {region: 0x165, script: 0x55, flags: 0x0}, - 652: {region: 0x138, script: 0x55, flags: 0x0}, - 653: {region: 0x87, script: 0x59, flags: 0x0}, - 654: {region: 0x97, script: 0x3a, flags: 0x0}, - 655: {region: 0x12f, script: 0x55, flags: 0x0}, - 656: {region: 0xe8, script: 0x5, flags: 0x0}, - 657: {region: 0x131, script: 0x55, flags: 0x0}, - 658: {region: 0x165, script: 0x55, flags: 0x0}, - 659: {region: 0xb7, script: 0x55, flags: 0x0}, - 660: {region: 0x106, script: 0x1e, flags: 0x0}, - 661: {region: 0x165, script: 0x55, flags: 0x0}, - 662: {region: 0x95, script: 0x55, flags: 0x0}, - 663: {region: 0x165, script: 0x55, flags: 0x0}, - 664: {region: 0x53, script: 0xdb, flags: 0x0}, - 665: {region: 0x165, script: 0x55, flags: 0x0}, - 666: {region: 0x165, script: 0x55, flags: 0x0}, - 667: {region: 0x165, script: 0x55, flags: 0x0}, - 668: {region: 0x165, script: 0x55, flags: 0x0}, - 669: {region: 0x99, script: 0x57, flags: 0x0}, - 670: {region: 0x165, script: 0x55, flags: 0x0}, - 671: {region: 0x165, script: 0x55, flags: 0x0}, - 672: {region: 0x106, script: 0x1e, flags: 0x0}, - 673: {region: 0x131, script: 0x55, flags: 0x0}, - 674: {region: 0x165, script: 0x55, flags: 0x0}, - 675: {region: 0xd9, script: 0x55, flags: 0x0}, - 676: {region: 0x165, script: 0x55, flags: 0x0}, - 677: {region: 0x165, script: 0x55, flags: 0x0}, - 678: {region: 0x21, script: 0x2, flags: 0x1}, - 679: {region: 0x165, script: 0x55, flags: 0x0}, - 680: {region: 0x165, script: 0x55, flags: 0x0}, - 681: {region: 0x9e, script: 0x55, flags: 0x0}, - 682: {region: 0x53, script: 0x5b, flags: 0x0}, - 683: {region: 0x95, script: 0x55, flags: 0x0}, - 684: {region: 0x9c, script: 0x5, flags: 0x0}, - 685: {region: 0x135, script: 0x55, flags: 0x0}, - 686: {region: 0x165, script: 0x55, flags: 0x0}, - 687: {region: 0x165, script: 0x55, flags: 0x0}, - 688: {region: 0x99, script: 0xd6, flags: 0x0}, - 689: {region: 0x9e, script: 0x55, flags: 0x0}, - 690: {region: 0x165, script: 0x55, flags: 0x0}, - 691: {region: 0x4b, script: 0x55, flags: 0x0}, - 692: {region: 0x165, script: 0x55, flags: 0x0}, - 693: {region: 0x165, script: 0x55, flags: 0x0}, - 694: {region: 0xaf, script: 0x52, flags: 0x0}, - 695: {region: 0x165, script: 0x55, flags: 0x0}, - 696: {region: 0x165, script: 0x55, flags: 0x0}, - 697: {region: 0x4b, script: 0x55, flags: 0x0}, - 698: {region: 0x165, script: 0x55, flags: 0x0}, - 699: {region: 0x165, script: 0x55, flags: 0x0}, - 700: {region: 0x162, script: 0x55, flags: 0x0}, - 701: {region: 0x9c, script: 0x5, flags: 0x0}, - 702: {region: 0xb6, script: 0x55, flags: 0x0}, - 703: {region: 0xb8, script: 0x55, flags: 0x0}, - 704: {region: 0x4b, script: 0x55, flags: 0x0}, - 705: {region: 0x4b, script: 0x55, flags: 0x0}, - 706: {region: 0xa4, script: 0x55, flags: 0x0}, - 707: {region: 0xa4, script: 0x55, flags: 0x0}, - 708: {region: 0x9c, script: 0x5, flags: 0x0}, - 709: {region: 0xb8, script: 0x55, flags: 0x0}, - 710: {region: 0x123, script: 0xdb, flags: 0x0}, - 711: {region: 0x53, script: 0x37, flags: 0x0}, - 712: {region: 0x12b, script: 0x55, flags: 0x0}, - 713: {region: 0x95, script: 0x55, flags: 0x0}, - 714: {region: 0x52, script: 0x55, flags: 0x0}, - 715: {region: 0x99, script: 0x20, flags: 0x0}, - 716: {region: 0x99, script: 0x20, flags: 0x0}, - 717: {region: 0x95, script: 0x55, flags: 0x0}, - 718: {region: 0x23, script: 0x3, flags: 0x1}, - 719: {region: 0xa4, script: 0x55, flags: 0x0}, - 720: {region: 0x165, script: 0x55, flags: 0x0}, - 721: {region: 0xcf, script: 0x55, flags: 0x0}, - 722: {region: 0x165, script: 0x55, flags: 0x0}, - 723: {region: 0x165, script: 0x55, flags: 0x0}, - 724: {region: 0x165, script: 0x55, flags: 0x0}, - 725: {region: 0x165, script: 0x55, flags: 0x0}, - 726: {region: 0x165, script: 0x55, flags: 0x0}, - 727: {region: 0x165, script: 0x55, flags: 0x0}, - 728: {region: 0x165, script: 0x55, flags: 0x0}, - 729: {region: 0x165, script: 0x55, flags: 0x0}, - 730: {region: 0x165, script: 0x55, flags: 0x0}, - 731: {region: 0x165, script: 0x55, flags: 0x0}, - 732: {region: 0x165, script: 0x55, flags: 0x0}, - 733: {region: 0x165, script: 0x5, flags: 0x0}, - 734: {region: 0x106, script: 0x1e, flags: 0x0}, - 735: {region: 0xe7, script: 0x55, flags: 0x0}, - 736: {region: 0x165, script: 0x55, flags: 0x0}, - 737: {region: 0x95, script: 0x55, flags: 0x0}, - 738: {region: 0x165, script: 0x28, flags: 0x0}, - 739: {region: 0x165, script: 0x55, flags: 0x0}, - 740: {region: 0x165, script: 0x55, flags: 0x0}, - 741: {region: 0x165, script: 0x55, flags: 0x0}, - 742: {region: 0x112, script: 0x55, flags: 0x0}, - 743: {region: 0xa4, script: 0x55, flags: 0x0}, - 744: {region: 0x165, script: 0x55, flags: 0x0}, - 745: {region: 0x165, script: 0x55, flags: 0x0}, - 746: {region: 0x123, script: 0x5, flags: 0x0}, - 747: {region: 0xcc, script: 0x55, flags: 0x0}, - 748: {region: 0x165, script: 0x55, flags: 0x0}, - 749: {region: 0x165, script: 0x55, flags: 0x0}, - 750: {region: 0x165, script: 0x55, flags: 0x0}, - 751: {region: 0xbf, script: 0x55, flags: 0x0}, - 752: {region: 0xd1, script: 0x55, flags: 0x0}, - 753: {region: 0x165, script: 0x55, flags: 0x0}, - 754: {region: 0x52, script: 0x55, flags: 0x0}, - 755: {region: 0xdb, script: 0x20, flags: 0x0}, - 756: {region: 0x12f, script: 0x55, flags: 0x0}, - 757: {region: 0xc0, script: 0x55, flags: 0x0}, - 758: {region: 0x165, script: 0x55, flags: 0x0}, - 759: {region: 0x165, script: 0x55, flags: 0x0}, - 760: {region: 0xe0, script: 0x55, flags: 0x0}, - 761: {region: 0x165, script: 0x55, flags: 0x0}, - 762: {region: 0x95, script: 0x55, flags: 0x0}, - 763: {region: 0x9b, script: 0x39, flags: 0x0}, - 764: {region: 0x165, script: 0x55, flags: 0x0}, - 765: {region: 0xc2, script: 0x1e, flags: 0x0}, - 766: {region: 0x165, script: 0x5, flags: 0x0}, - 767: {region: 0x165, script: 0x55, flags: 0x0}, - 768: {region: 0x165, script: 0x55, flags: 0x0}, - 769: {region: 0x165, script: 0x55, flags: 0x0}, - 770: {region: 0x99, script: 0x69, flags: 0x0}, - 771: {region: 0x165, script: 0x55, flags: 0x0}, - 772: {region: 0x165, script: 0x55, flags: 0x0}, - 773: {region: 0x10b, script: 0x55, flags: 0x0}, - 774: {region: 0x165, script: 0x55, flags: 0x0}, - 775: {region: 0x165, script: 0x55, flags: 0x0}, - 776: {region: 0x165, script: 0x55, flags: 0x0}, - 777: {region: 0x26, script: 0x3, flags: 0x1}, - 778: {region: 0x165, script: 0x55, flags: 0x0}, - 779: {region: 0x165, script: 0x55, flags: 0x0}, - 780: {region: 0x99, script: 0xe, flags: 0x0}, - 781: {region: 0xc4, script: 0x70, flags: 0x0}, - 783: {region: 0x165, script: 0x55, flags: 0x0}, - 784: {region: 0x49, script: 0x55, flags: 0x0}, - 785: {region: 0x49, script: 0x55, flags: 0x0}, - 786: {region: 0x37, script: 0x55, flags: 0x0}, - 787: {region: 0x165, script: 0x55, flags: 0x0}, - 788: {region: 0x165, script: 0x55, flags: 0x0}, - 789: {region: 0x165, script: 0x55, flags: 0x0}, - 790: {region: 0x165, script: 0x55, flags: 0x0}, - 791: {region: 0x165, script: 0x55, flags: 0x0}, - 792: {region: 0x165, script: 0x55, flags: 0x0}, - 793: {region: 0x99, script: 0x20, flags: 0x0}, - 794: {region: 0xdb, script: 0x20, flags: 0x0}, - 795: {region: 0x106, script: 0x1e, flags: 0x0}, - 796: {region: 0x35, script: 0x6d, flags: 0x0}, - 797: {region: 0x29, script: 0x3, flags: 0x1}, - 798: {region: 0xcb, script: 0x55, flags: 0x0}, - 799: {region: 0x165, script: 0x55, flags: 0x0}, - 800: {region: 0x165, script: 0x55, flags: 0x0}, - 801: {region: 0x165, script: 0x55, flags: 0x0}, - 802: {region: 0x99, script: 0x20, flags: 0x0}, - 803: {region: 0x52, script: 0x55, flags: 0x0}, - 805: {region: 0x165, script: 0x55, flags: 0x0}, - 806: {region: 0x135, script: 0x55, flags: 0x0}, - 807: {region: 0x165, script: 0x55, flags: 0x0}, - 808: {region: 0x165, script: 0x55, flags: 0x0}, - 809: {region: 0xe8, script: 0x5, flags: 0x0}, - 810: {region: 0xc3, script: 0x55, flags: 0x0}, - 811: {region: 0x99, script: 0x20, flags: 0x0}, - 812: {region: 0x95, script: 0x55, flags: 0x0}, - 813: {region: 0x164, script: 0x55, flags: 0x0}, - 814: {region: 0x165, script: 0x55, flags: 0x0}, - 815: {region: 0xc4, script: 0x70, flags: 0x0}, - 816: {region: 0x165, script: 0x55, flags: 0x0}, - 817: {region: 0x165, script: 0x28, flags: 0x0}, - 818: {region: 0x106, script: 0x1e, flags: 0x0}, - 819: {region: 0x165, script: 0x55, flags: 0x0}, - 820: {region: 0x131, script: 0x55, flags: 0x0}, - 821: {region: 0x9c, script: 0x61, flags: 0x0}, - 822: {region: 0x165, script: 0x55, flags: 0x0}, - 823: {region: 0x165, script: 0x55, flags: 0x0}, - 824: {region: 0x9c, script: 0x5, flags: 0x0}, - 825: {region: 0x165, script: 0x55, flags: 0x0}, - 826: {region: 0x165, script: 0x55, flags: 0x0}, - 827: {region: 0x165, script: 0x55, flags: 0x0}, - 828: {region: 0xdd, script: 0x55, flags: 0x0}, - 829: {region: 0x165, script: 0x55, flags: 0x0}, - 830: {region: 0x165, script: 0x55, flags: 0x0}, - 832: {region: 0x165, script: 0x55, flags: 0x0}, - 833: {region: 0x53, script: 0x37, flags: 0x0}, - 834: {region: 0x9e, script: 0x55, flags: 0x0}, - 835: {region: 0xd2, script: 0x55, flags: 0x0}, - 836: {region: 0x165, script: 0x55, flags: 0x0}, - 837: {region: 0xda, script: 0x55, flags: 0x0}, - 838: {region: 0x165, script: 0x55, flags: 0x0}, - 839: {region: 0x165, script: 0x55, flags: 0x0}, - 840: {region: 0x165, script: 0x55, flags: 0x0}, - 841: {region: 0xcf, script: 0x55, flags: 0x0}, - 842: {region: 0x165, script: 0x55, flags: 0x0}, - 843: {region: 0x165, script: 0x55, flags: 0x0}, - 844: {region: 0x164, script: 0x55, flags: 0x0}, - 845: {region: 0xd1, script: 0x55, flags: 0x0}, - 846: {region: 0x60, script: 0x55, flags: 0x0}, - 847: {region: 0xdb, script: 0x20, flags: 0x0}, - 848: {region: 0x165, script: 0x55, flags: 0x0}, - 849: {region: 0xdb, script: 0x20, flags: 0x0}, - 850: {region: 0x165, script: 0x55, flags: 0x0}, - 851: {region: 0x165, script: 0x55, flags: 0x0}, - 852: {region: 0xd2, script: 0x55, flags: 0x0}, - 853: {region: 0x165, script: 0x55, flags: 0x0}, - 854: {region: 0x165, script: 0x55, flags: 0x0}, - 855: {region: 0xd1, script: 0x55, flags: 0x0}, - 856: {region: 0x165, script: 0x55, flags: 0x0}, - 857: {region: 0xcf, script: 0x55, flags: 0x0}, - 858: {region: 0xcf, script: 0x55, flags: 0x0}, - 859: {region: 0x165, script: 0x55, flags: 0x0}, - 860: {region: 0x165, script: 0x55, flags: 0x0}, - 861: {region: 0x95, script: 0x55, flags: 0x0}, - 862: {region: 0x165, script: 0x55, flags: 0x0}, - 863: {region: 0xdf, script: 0x55, flags: 0x0}, - 864: {region: 0x165, script: 0x55, flags: 0x0}, - 865: {region: 0x165, script: 0x55, flags: 0x0}, - 866: {region: 0x99, script: 0x55, flags: 0x0}, - 867: {region: 0x165, script: 0x55, flags: 0x0}, - 868: {region: 0x165, script: 0x55, flags: 0x0}, - 869: {region: 0xd9, script: 0x55, flags: 0x0}, - 870: {region: 0x52, script: 0x55, flags: 0x0}, - 871: {region: 0x165, script: 0x55, flags: 0x0}, - 872: {region: 0xda, script: 0x55, flags: 0x0}, - 873: {region: 0x165, script: 0x55, flags: 0x0}, - 874: {region: 0x52, script: 0x55, flags: 0x0}, - 875: {region: 0x165, script: 0x55, flags: 0x0}, - 876: {region: 0x165, script: 0x55, flags: 0x0}, - 877: {region: 0xda, script: 0x55, flags: 0x0}, - 878: {region: 0x123, script: 0x51, flags: 0x0}, - 879: {region: 0x99, script: 0x20, flags: 0x0}, - 880: {region: 0x10c, script: 0xbc, flags: 0x0}, - 881: {region: 0x165, script: 0x55, flags: 0x0}, - 882: {region: 0x165, script: 0x55, flags: 0x0}, - 883: {region: 0x84, script: 0x75, flags: 0x0}, - 884: {region: 0x161, script: 0x55, flags: 0x0}, - 885: {region: 0x165, script: 0x55, flags: 0x0}, - 886: {region: 0x49, script: 0x17, flags: 0x0}, - 887: {region: 0x165, script: 0x55, flags: 0x0}, - 888: {region: 0x161, script: 0x55, flags: 0x0}, - 889: {region: 0x165, script: 0x55, flags: 0x0}, - 890: {region: 0x165, script: 0x55, flags: 0x0}, - 891: {region: 0x165, script: 0x55, flags: 0x0}, - 892: {region: 0x165, script: 0x55, flags: 0x0}, - 893: {region: 0x165, script: 0x55, flags: 0x0}, - 894: {region: 0x117, script: 0x55, flags: 0x0}, - 895: {region: 0x165, script: 0x55, flags: 0x0}, - 896: {region: 0x165, script: 0x55, flags: 0x0}, - 897: {region: 0x135, script: 0x55, flags: 0x0}, - 898: {region: 0x165, script: 0x55, flags: 0x0}, - 899: {region: 0x53, script: 0x55, flags: 0x0}, - 900: {region: 0x165, script: 0x55, flags: 0x0}, - 901: {region: 0xce, script: 0x55, flags: 0x0}, - 902: {region: 0x12f, script: 0x55, flags: 0x0}, - 903: {region: 0x131, script: 0x55, flags: 0x0}, - 904: {region: 0x80, script: 0x55, flags: 0x0}, - 905: {region: 0x78, script: 0x55, flags: 0x0}, - 906: {region: 0x165, script: 0x55, flags: 0x0}, - 908: {region: 0x165, script: 0x55, flags: 0x0}, - 909: {region: 0x165, script: 0x55, flags: 0x0}, - 910: {region: 0x6f, script: 0x55, flags: 0x0}, - 911: {region: 0x165, script: 0x55, flags: 0x0}, - 912: {region: 0x165, script: 0x55, flags: 0x0}, - 913: {region: 0x165, script: 0x55, flags: 0x0}, - 914: {region: 0x165, script: 0x55, flags: 0x0}, - 915: {region: 0x99, script: 0x7a, flags: 0x0}, - 916: {region: 0x165, script: 0x55, flags: 0x0}, - 917: {region: 0x165, script: 0x5, flags: 0x0}, - 918: {region: 0x7d, script: 0x1e, flags: 0x0}, - 919: {region: 0x135, script: 0x7b, flags: 0x0}, - 920: {region: 0x165, script: 0x5, flags: 0x0}, - 921: {region: 0xc5, script: 0x79, flags: 0x0}, - 922: {region: 0x165, script: 0x55, flags: 0x0}, - 923: {region: 0x2c, script: 0x3, flags: 0x1}, - 924: {region: 0xe7, script: 0x55, flags: 0x0}, - 925: {region: 0x2f, script: 0x2, flags: 0x1}, - 926: {region: 0xe7, script: 0x55, flags: 0x0}, - 927: {region: 0x30, script: 0x55, flags: 0x0}, - 928: {region: 0xf0, script: 0x55, flags: 0x0}, - 929: {region: 0x165, script: 0x55, flags: 0x0}, - 930: {region: 0x78, script: 0x55, flags: 0x0}, - 931: {region: 0xd6, script: 0x55, flags: 0x0}, - 932: {region: 0x135, script: 0x55, flags: 0x0}, - 933: {region: 0x49, script: 0x55, flags: 0x0}, - 934: {region: 0x165, script: 0x55, flags: 0x0}, - 935: {region: 0x9c, script: 0xe3, flags: 0x0}, - 936: {region: 0x165, script: 0x55, flags: 0x0}, - 937: {region: 0x60, script: 0x55, flags: 0x0}, - 938: {region: 0x165, script: 0x5, flags: 0x0}, - 939: {region: 0xb0, script: 0x84, flags: 0x0}, - 941: {region: 0x165, script: 0x55, flags: 0x0}, - 942: {region: 0x165, script: 0x55, flags: 0x0}, - 943: {region: 0x99, script: 0x12, flags: 0x0}, - 944: {region: 0xa4, script: 0x55, flags: 0x0}, - 945: {region: 0xe9, script: 0x55, flags: 0x0}, - 946: {region: 0x165, script: 0x55, flags: 0x0}, - 947: {region: 0x9e, script: 0x55, flags: 0x0}, - 948: {region: 0x165, script: 0x55, flags: 0x0}, - 949: {region: 0x165, script: 0x55, flags: 0x0}, - 950: {region: 0x87, script: 0x30, flags: 0x0}, - 951: {region: 0x75, script: 0x55, flags: 0x0}, - 952: {region: 0x165, script: 0x55, flags: 0x0}, - 953: {region: 0xe8, script: 0x48, flags: 0x0}, - 954: {region: 0x9c, script: 0x5, flags: 0x0}, - 955: {region: 0x1, script: 0x55, flags: 0x0}, - 956: {region: 0x24, script: 0x5, flags: 0x0}, - 957: {region: 0x165, script: 0x55, flags: 0x0}, - 958: {region: 0x41, script: 0x55, flags: 0x0}, - 959: {region: 0x165, script: 0x55, flags: 0x0}, - 960: {region: 0x7a, script: 0x55, flags: 0x0}, - 961: {region: 0x165, script: 0x55, flags: 0x0}, - 962: {region: 0xe4, script: 0x55, flags: 0x0}, - 963: {region: 0x89, script: 0x55, flags: 0x0}, - 964: {region: 0x69, script: 0x55, flags: 0x0}, - 965: {region: 0x165, script: 0x55, flags: 0x0}, - 966: {region: 0x99, script: 0x20, flags: 0x0}, - 967: {region: 0x165, script: 0x55, flags: 0x0}, - 968: {region: 0x102, script: 0x55, flags: 0x0}, - 969: {region: 0x95, script: 0x55, flags: 0x0}, - 970: {region: 0x165, script: 0x55, flags: 0x0}, - 971: {region: 0x165, script: 0x55, flags: 0x0}, - 972: {region: 0x9e, script: 0x55, flags: 0x0}, - 973: {region: 0x165, script: 0x5, flags: 0x0}, - 974: {region: 0x99, script: 0x55, flags: 0x0}, - 975: {region: 0x31, script: 0x2, flags: 0x1}, - 976: {region: 0xdb, script: 0x20, flags: 0x0}, - 977: {region: 0x35, script: 0xe, flags: 0x0}, - 978: {region: 0x4e, script: 0x55, flags: 0x0}, - 979: {region: 0x72, script: 0x55, flags: 0x0}, - 980: {region: 0x4e, script: 0x55, flags: 0x0}, - 981: {region: 0x9c, script: 0x5, flags: 0x0}, - 982: {region: 0x10c, script: 0x55, flags: 0x0}, - 983: {region: 0x3a, script: 0x55, flags: 0x0}, - 984: {region: 0x165, script: 0x55, flags: 0x0}, - 985: {region: 0xd1, script: 0x55, flags: 0x0}, - 986: {region: 0x104, script: 0x55, flags: 0x0}, - 987: {region: 0x95, script: 0x55, flags: 0x0}, - 988: {region: 0x12f, script: 0x55, flags: 0x0}, - 989: {region: 0x165, script: 0x55, flags: 0x0}, - 990: {region: 0x165, script: 0x55, flags: 0x0}, - 991: {region: 0x73, script: 0x55, flags: 0x0}, - 992: {region: 0x106, script: 0x1e, flags: 0x0}, - 993: {region: 0x130, script: 0x1e, flags: 0x0}, - 994: {region: 0x109, script: 0x55, flags: 0x0}, - 995: {region: 0x107, script: 0x55, flags: 0x0}, - 996: {region: 0x12f, script: 0x55, flags: 0x0}, - 997: {region: 0x165, script: 0x55, flags: 0x0}, - 998: {region: 0xa2, script: 0x47, flags: 0x0}, - 999: {region: 0x99, script: 0x20, flags: 0x0}, - 1000: {region: 0x80, script: 0x55, flags: 0x0}, - 1001: {region: 0x106, script: 0x1e, flags: 0x0}, - 1002: {region: 0xa4, script: 0x55, flags: 0x0}, - 1003: {region: 0x95, script: 0x55, flags: 0x0}, - 1004: {region: 0x99, script: 0x55, flags: 0x0}, - 1005: {region: 0x114, script: 0x55, flags: 0x0}, - 1006: {region: 0x99, script: 0xc0, flags: 0x0}, - 1007: {region: 0x165, script: 0x55, flags: 0x0}, - 1008: {region: 0x165, script: 0x55, flags: 0x0}, - 1009: {region: 0x12f, script: 0x55, flags: 0x0}, - 1010: {region: 0x9e, script: 0x55, flags: 0x0}, - 1011: {region: 0x99, script: 0x20, flags: 0x0}, - 1012: {region: 0x165, script: 0x5, flags: 0x0}, - 1013: {region: 0x9e, script: 0x55, flags: 0x0}, - 1014: {region: 0x7b, script: 0x55, flags: 0x0}, - 1015: {region: 0x49, script: 0x55, flags: 0x0}, - 1016: {region: 0x33, script: 0x4, flags: 0x1}, - 1017: {region: 0x9e, script: 0x55, flags: 0x0}, - 1018: {region: 0x9c, script: 0x5, flags: 0x0}, - 1019: {region: 0xda, script: 0x55, flags: 0x0}, - 1020: {region: 0x4f, script: 0x55, flags: 0x0}, - 1021: {region: 0xd1, script: 0x55, flags: 0x0}, - 1022: {region: 0xcf, script: 0x55, flags: 0x0}, - 1023: {region: 0xc3, script: 0x55, flags: 0x0}, - 1024: {region: 0x4c, script: 0x55, flags: 0x0}, - 1025: {region: 0x96, script: 0x77, flags: 0x0}, - 1026: {region: 0xb6, script: 0x55, flags: 0x0}, - 1027: {region: 0x165, script: 0x28, flags: 0x0}, - 1028: {region: 0x165, script: 0x55, flags: 0x0}, - 1030: {region: 0xba, script: 0xd8, flags: 0x0}, - 1031: {region: 0x165, script: 0x55, flags: 0x0}, - 1032: {region: 0xc4, script: 0x70, flags: 0x0}, - 1033: {region: 0x165, script: 0x5, flags: 0x0}, - 1034: {region: 0xb3, script: 0xc6, flags: 0x0}, - 1035: {region: 0x6f, script: 0x55, flags: 0x0}, - 1036: {region: 0x165, script: 0x55, flags: 0x0}, - 1037: {region: 0x165, script: 0x55, flags: 0x0}, - 1038: {region: 0x165, script: 0x55, flags: 0x0}, - 1039: {region: 0x165, script: 0x55, flags: 0x0}, - 1040: {region: 0x111, script: 0x55, flags: 0x0}, - 1041: {region: 0x165, script: 0x55, flags: 0x0}, - 1042: {region: 0xe8, script: 0x5, flags: 0x0}, - 1043: {region: 0x165, script: 0x55, flags: 0x0}, - 1044: {region: 0x10f, script: 0x55, flags: 0x0}, - 1045: {region: 0x165, script: 0x55, flags: 0x0}, - 1046: {region: 0xe9, script: 0x55, flags: 0x0}, - 1047: {region: 0x165, script: 0x55, flags: 0x0}, - 1048: {region: 0x95, script: 0x55, flags: 0x0}, - 1049: {region: 0x142, script: 0x55, flags: 0x0}, - 1050: {region: 0x10c, script: 0x55, flags: 0x0}, - 1052: {region: 0x10c, script: 0x55, flags: 0x0}, - 1053: {region: 0x72, script: 0x55, flags: 0x0}, - 1054: {region: 0x97, script: 0xbd, flags: 0x0}, - 1055: {region: 0x165, script: 0x55, flags: 0x0}, - 1056: {region: 0x72, script: 0x55, flags: 0x0}, - 1057: {region: 0x164, script: 0x55, flags: 0x0}, - 1058: {region: 0x165, script: 0x55, flags: 0x0}, - 1059: {region: 0xc3, script: 0x55, flags: 0x0}, - 1060: {region: 0x165, script: 0x55, flags: 0x0}, - 1061: {region: 0x165, script: 0x55, flags: 0x0}, - 1062: {region: 0x165, script: 0x55, flags: 0x0}, - 1063: {region: 0x115, script: 0x55, flags: 0x0}, - 1064: {region: 0x165, script: 0x55, flags: 0x0}, - 1065: {region: 0x165, script: 0x55, flags: 0x0}, - 1066: {region: 0x123, script: 0xdb, flags: 0x0}, - 1067: {region: 0x165, script: 0x55, flags: 0x0}, - 1068: {region: 0x165, script: 0x55, flags: 0x0}, - 1069: {region: 0x165, script: 0x55, flags: 0x0}, - 1070: {region: 0x165, script: 0x55, flags: 0x0}, - 1071: {region: 0x27, script: 0x55, flags: 0x0}, - 1072: {region: 0x37, script: 0x5, flags: 0x1}, - 1073: {region: 0x99, script: 0xc7, flags: 0x0}, - 1074: {region: 0x116, script: 0x55, flags: 0x0}, - 1075: {region: 0x114, script: 0x55, flags: 0x0}, - 1076: {region: 0x99, script: 0x20, flags: 0x0}, - 1077: {region: 0x161, script: 0x55, flags: 0x0}, - 1078: {region: 0x165, script: 0x55, flags: 0x0}, - 1079: {region: 0x165, script: 0x55, flags: 0x0}, - 1080: {region: 0x6d, script: 0x55, flags: 0x0}, - 1081: {region: 0x161, script: 0x55, flags: 0x0}, - 1082: {region: 0x165, script: 0x55, flags: 0x0}, - 1083: {region: 0x60, script: 0x55, flags: 0x0}, - 1084: {region: 0x95, script: 0x55, flags: 0x0}, - 1085: {region: 0x165, script: 0x55, flags: 0x0}, - 1086: {region: 0x165, script: 0x55, flags: 0x0}, - 1087: {region: 0x12f, script: 0x55, flags: 0x0}, - 1088: {region: 0x165, script: 0x55, flags: 0x0}, - 1089: {region: 0x84, script: 0x55, flags: 0x0}, - 1090: {region: 0x10c, script: 0x55, flags: 0x0}, - 1091: {region: 0x12f, script: 0x55, flags: 0x0}, - 1092: {region: 0x15f, script: 0x5, flags: 0x0}, - 1093: {region: 0x4b, script: 0x55, flags: 0x0}, - 1094: {region: 0x60, script: 0x55, flags: 0x0}, - 1095: {region: 0x165, script: 0x55, flags: 0x0}, - 1096: {region: 0x99, script: 0x20, flags: 0x0}, - 1097: {region: 0x95, script: 0x55, flags: 0x0}, - 1098: {region: 0x165, script: 0x55, flags: 0x0}, - 1099: {region: 0x35, script: 0xe, flags: 0x0}, - 1100: {region: 0x9b, script: 0xcb, flags: 0x0}, - 1101: {region: 0xe9, script: 0x55, flags: 0x0}, - 1102: {region: 0x99, script: 0xd3, flags: 0x0}, - 1103: {region: 0xdb, script: 0x20, flags: 0x0}, - 1104: {region: 0x165, script: 0x55, flags: 0x0}, - 1105: {region: 0x165, script: 0x55, flags: 0x0}, - 1106: {region: 0x165, script: 0x55, flags: 0x0}, - 1107: {region: 0x165, script: 0x55, flags: 0x0}, - 1108: {region: 0x165, script: 0x55, flags: 0x0}, - 1109: {region: 0x165, script: 0x55, flags: 0x0}, - 1110: {region: 0x165, script: 0x55, flags: 0x0}, - 1111: {region: 0x165, script: 0x55, flags: 0x0}, - 1112: {region: 0xe7, script: 0x55, flags: 0x0}, - 1113: {region: 0x165, script: 0x55, flags: 0x0}, - 1114: {region: 0x165, script: 0x55, flags: 0x0}, - 1115: {region: 0x99, script: 0x4d, flags: 0x0}, - 1116: {region: 0x53, script: 0xd1, flags: 0x0}, - 1117: {region: 0xdb, script: 0x20, flags: 0x0}, - 1118: {region: 0xdb, script: 0x20, flags: 0x0}, - 1119: {region: 0x99, script: 0xd6, flags: 0x0}, - 1120: {region: 0x165, script: 0x55, flags: 0x0}, - 1121: {region: 0x112, script: 0x55, flags: 0x0}, - 1122: {region: 0x131, script: 0x55, flags: 0x0}, - 1123: {region: 0x126, script: 0x55, flags: 0x0}, - 1124: {region: 0x165, script: 0x55, flags: 0x0}, - 1125: {region: 0x3c, script: 0x3, flags: 0x1}, - 1126: {region: 0x165, script: 0x55, flags: 0x0}, - 1127: {region: 0x165, script: 0x55, flags: 0x0}, - 1128: {region: 0x165, script: 0x55, flags: 0x0}, - 1129: {region: 0x123, script: 0xdb, flags: 0x0}, - 1130: {region: 0xdb, script: 0x20, flags: 0x0}, - 1131: {region: 0xdb, script: 0x20, flags: 0x0}, - 1132: {region: 0xdb, script: 0x20, flags: 0x0}, - 1133: {region: 0x6f, script: 0x28, flags: 0x0}, - 1134: {region: 0x165, script: 0x55, flags: 0x0}, - 1135: {region: 0x6d, script: 0x28, flags: 0x0}, - 1136: {region: 0x165, script: 0x55, flags: 0x0}, - 1137: {region: 0x165, script: 0x55, flags: 0x0}, - 1138: {region: 0x165, script: 0x55, flags: 0x0}, - 1139: {region: 0xd6, script: 0x55, flags: 0x0}, - 1140: {region: 0x127, script: 0x55, flags: 0x0}, - 1141: {region: 0x125, script: 0x55, flags: 0x0}, - 1142: {region: 0x32, script: 0x55, flags: 0x0}, - 1143: {region: 0xdb, script: 0x20, flags: 0x0}, - 1144: {region: 0xe7, script: 0x55, flags: 0x0}, - 1145: {region: 0x165, script: 0x55, flags: 0x0}, - 1146: {region: 0x165, script: 0x55, flags: 0x0}, - 1147: {region: 0x32, script: 0x55, flags: 0x0}, - 1148: {region: 0xd4, script: 0x55, flags: 0x0}, - 1149: {region: 0x165, script: 0x55, flags: 0x0}, - 1150: {region: 0x161, script: 0x55, flags: 0x0}, - 1151: {region: 0x165, script: 0x55, flags: 0x0}, - 1152: {region: 0x129, script: 0x55, flags: 0x0}, - 1153: {region: 0x165, script: 0x55, flags: 0x0}, - 1154: {region: 0xce, script: 0x55, flags: 0x0}, - 1155: {region: 0x165, script: 0x55, flags: 0x0}, - 1156: {region: 0xe6, script: 0x55, flags: 0x0}, - 1157: {region: 0x165, script: 0x55, flags: 0x0}, - 1158: {region: 0x165, script: 0x55, flags: 0x0}, - 1159: {region: 0x165, script: 0x55, flags: 0x0}, - 1160: {region: 0x12b, script: 0x55, flags: 0x0}, - 1161: {region: 0x12b, script: 0x55, flags: 0x0}, - 1162: {region: 0x12e, script: 0x55, flags: 0x0}, - 1163: {region: 0x165, script: 0x5, flags: 0x0}, - 1164: {region: 0x161, script: 0x55, flags: 0x0}, - 1165: {region: 0x87, script: 0x30, flags: 0x0}, - 1166: {region: 0xdb, script: 0x20, flags: 0x0}, - 1167: {region: 0xe7, script: 0x55, flags: 0x0}, - 1168: {region: 0x43, script: 0xdc, flags: 0x0}, - 1169: {region: 0x165, script: 0x55, flags: 0x0}, - 1170: {region: 0x106, script: 0x1e, flags: 0x0}, - 1171: {region: 0x165, script: 0x55, flags: 0x0}, - 1172: {region: 0x165, script: 0x55, flags: 0x0}, - 1173: {region: 0x131, script: 0x55, flags: 0x0}, - 1174: {region: 0x165, script: 0x55, flags: 0x0}, - 1175: {region: 0x123, script: 0xdb, flags: 0x0}, - 1176: {region: 0x32, script: 0x55, flags: 0x0}, - 1177: {region: 0x165, script: 0x55, flags: 0x0}, - 1178: {region: 0x165, script: 0x55, flags: 0x0}, - 1179: {region: 0xce, script: 0x55, flags: 0x0}, - 1180: {region: 0x165, script: 0x55, flags: 0x0}, - 1181: {region: 0x165, script: 0x55, flags: 0x0}, - 1182: {region: 0x12d, script: 0x55, flags: 0x0}, - 1183: {region: 0x165, script: 0x55, flags: 0x0}, - 1185: {region: 0x165, script: 0x55, flags: 0x0}, - 1186: {region: 0xd4, script: 0x55, flags: 0x0}, - 1187: {region: 0x53, script: 0xd4, flags: 0x0}, - 1188: {region: 0xe5, script: 0x55, flags: 0x0}, - 1189: {region: 0x165, script: 0x55, flags: 0x0}, - 1190: {region: 0x106, script: 0x1e, flags: 0x0}, - 1191: {region: 0xba, script: 0x55, flags: 0x0}, - 1192: {region: 0x165, script: 0x55, flags: 0x0}, - 1193: {region: 0x106, script: 0x1e, flags: 0x0}, - 1194: {region: 0x3f, script: 0x4, flags: 0x1}, - 1195: {region: 0x11c, script: 0xde, flags: 0x0}, - 1196: {region: 0x130, script: 0x1e, flags: 0x0}, - 1197: {region: 0x75, script: 0x55, flags: 0x0}, - 1198: {region: 0x2a, script: 0x55, flags: 0x0}, - 1200: {region: 0x43, script: 0x3, flags: 0x1}, - 1201: {region: 0x99, script: 0xe, flags: 0x0}, - 1202: {region: 0xe8, script: 0x5, flags: 0x0}, - 1203: {region: 0x165, script: 0x55, flags: 0x0}, - 1204: {region: 0x165, script: 0x55, flags: 0x0}, - 1205: {region: 0x165, script: 0x55, flags: 0x0}, - 1206: {region: 0x165, script: 0x55, flags: 0x0}, - 1207: {region: 0x165, script: 0x55, flags: 0x0}, - 1208: {region: 0x165, script: 0x55, flags: 0x0}, - 1209: {region: 0x165, script: 0x55, flags: 0x0}, - 1210: {region: 0x46, script: 0x4, flags: 0x1}, - 1211: {region: 0x165, script: 0x55, flags: 0x0}, - 1212: {region: 0xb4, script: 0xdf, flags: 0x0}, - 1213: {region: 0x165, script: 0x55, flags: 0x0}, - 1214: {region: 0x161, script: 0x55, flags: 0x0}, - 1215: {region: 0x9e, script: 0x55, flags: 0x0}, - 1216: {region: 0x106, script: 0x55, flags: 0x0}, - 1217: {region: 0x13e, script: 0x55, flags: 0x0}, - 1218: {region: 0x11b, script: 0x55, flags: 0x0}, - 1219: {region: 0x165, script: 0x55, flags: 0x0}, - 1220: {region: 0x36, script: 0x55, flags: 0x0}, - 1221: {region: 0x60, script: 0x55, flags: 0x0}, - 1222: {region: 0xd1, script: 0x55, flags: 0x0}, - 1223: {region: 0x1, script: 0x55, flags: 0x0}, - 1224: {region: 0x106, script: 0x55, flags: 0x0}, - 1225: {region: 0x6a, script: 0x55, flags: 0x0}, - 1226: {region: 0x12f, script: 0x55, flags: 0x0}, - 1227: {region: 0x165, script: 0x55, flags: 0x0}, - 1228: {region: 0x36, script: 0x55, flags: 0x0}, - 1229: {region: 0x4e, script: 0x55, flags: 0x0}, - 1230: {region: 0x165, script: 0x55, flags: 0x0}, - 1231: {region: 0x6f, script: 0x28, flags: 0x0}, - 1232: {region: 0x165, script: 0x55, flags: 0x0}, - 1233: {region: 0xe7, script: 0x55, flags: 0x0}, - 1234: {region: 0x2f, script: 0x55, flags: 0x0}, - 1235: {region: 0x99, script: 0xd6, flags: 0x0}, - 1236: {region: 0x99, script: 0x20, flags: 0x0}, - 1237: {region: 0x165, script: 0x55, flags: 0x0}, - 1238: {region: 0x165, script: 0x55, flags: 0x0}, - 1239: {region: 0x165, script: 0x55, flags: 0x0}, - 1240: {region: 0x165, script: 0x55, flags: 0x0}, - 1241: {region: 0x165, script: 0x55, flags: 0x0}, - 1242: {region: 0x165, script: 0x55, flags: 0x0}, - 1243: {region: 0x165, script: 0x55, flags: 0x0}, - 1244: {region: 0x165, script: 0x55, flags: 0x0}, - 1245: {region: 0x165, script: 0x55, flags: 0x0}, - 1246: {region: 0x140, script: 0x55, flags: 0x0}, - 1247: {region: 0x165, script: 0x55, flags: 0x0}, - 1248: {region: 0x165, script: 0x55, flags: 0x0}, - 1249: {region: 0xa8, script: 0x5, flags: 0x0}, - 1250: {region: 0x165, script: 0x55, flags: 0x0}, - 1251: {region: 0x114, script: 0x55, flags: 0x0}, - 1252: {region: 0x165, script: 0x55, flags: 0x0}, - 1253: {region: 0x165, script: 0x55, flags: 0x0}, - 1254: {region: 0x165, script: 0x55, flags: 0x0}, - 1255: {region: 0x165, script: 0x55, flags: 0x0}, - 1256: {region: 0x99, script: 0x20, flags: 0x0}, - 1257: {region: 0x53, script: 0x37, flags: 0x0}, - 1258: {region: 0x165, script: 0x55, flags: 0x0}, - 1259: {region: 0x165, script: 0x55, flags: 0x0}, - 1260: {region: 0x41, script: 0x55, flags: 0x0}, - 1261: {region: 0x165, script: 0x55, flags: 0x0}, - 1262: {region: 0x12b, script: 0x18, flags: 0x0}, - 1263: {region: 0x165, script: 0x55, flags: 0x0}, - 1264: {region: 0x161, script: 0x55, flags: 0x0}, - 1265: {region: 0x165, script: 0x55, flags: 0x0}, - 1266: {region: 0x12b, script: 0x5d, flags: 0x0}, - 1267: {region: 0x12b, script: 0x5e, flags: 0x0}, - 1268: {region: 0x7d, script: 0x2a, flags: 0x0}, - 1269: {region: 0x53, script: 0x62, flags: 0x0}, - 1270: {region: 0x10b, script: 0x67, flags: 0x0}, - 1271: {region: 0x108, script: 0x71, flags: 0x0}, - 1272: {region: 0x99, script: 0x20, flags: 0x0}, - 1273: {region: 0x131, script: 0x55, flags: 0x0}, - 1274: {region: 0x165, script: 0x55, flags: 0x0}, - 1275: {region: 0x9c, script: 0x87, flags: 0x0}, - 1276: {region: 0x165, script: 0x55, flags: 0x0}, - 1277: {region: 0x15e, script: 0xbf, flags: 0x0}, - 1278: {region: 0x165, script: 0x55, flags: 0x0}, - 1279: {region: 0x165, script: 0x55, flags: 0x0}, - 1280: {region: 0xdb, script: 0x20, flags: 0x0}, - 1281: {region: 0x165, script: 0x55, flags: 0x0}, - 1282: {region: 0x165, script: 0x55, flags: 0x0}, - 1283: {region: 0xd1, script: 0x55, flags: 0x0}, - 1284: {region: 0x75, script: 0x55, flags: 0x0}, - 1285: {region: 0x165, script: 0x55, flags: 0x0}, - 1286: {region: 0x165, script: 0x55, flags: 0x0}, - 1287: {region: 0x52, script: 0x55, flags: 0x0}, - 1288: {region: 0x165, script: 0x55, flags: 0x0}, - 1289: {region: 0x165, script: 0x55, flags: 0x0}, - 1290: {region: 0x165, script: 0x55, flags: 0x0}, - 1291: {region: 0x52, script: 0x55, flags: 0x0}, - 1292: {region: 0x165, script: 0x55, flags: 0x0}, - 1293: {region: 0x165, script: 0x55, flags: 0x0}, - 1294: {region: 0x165, script: 0x55, flags: 0x0}, - 1295: {region: 0x165, script: 0x55, flags: 0x0}, - 1296: {region: 0x1, script: 0x3a, flags: 0x0}, - 1297: {region: 0x165, script: 0x55, flags: 0x0}, - 1298: {region: 0x165, script: 0x55, flags: 0x0}, - 1299: {region: 0x165, script: 0x55, flags: 0x0}, - 1300: {region: 0x165, script: 0x55, flags: 0x0}, - 1301: {region: 0x165, script: 0x55, flags: 0x0}, - 1302: {region: 0xd6, script: 0x55, flags: 0x0}, - 1303: {region: 0x165, script: 0x55, flags: 0x0}, - 1304: {region: 0x165, script: 0x55, flags: 0x0}, - 1305: {region: 0x165, script: 0x55, flags: 0x0}, - 1306: {region: 0x41, script: 0x55, flags: 0x0}, - 1307: {region: 0x165, script: 0x55, flags: 0x0}, - 1308: {region: 0xcf, script: 0x55, flags: 0x0}, - 1309: {region: 0x4a, script: 0x3, flags: 0x1}, - 1310: {region: 0x165, script: 0x55, flags: 0x0}, - 1311: {region: 0x165, script: 0x55, flags: 0x0}, - 1312: {region: 0x165, script: 0x55, flags: 0x0}, - 1313: {region: 0x53, script: 0x55, flags: 0x0}, - 1314: {region: 0x10b, script: 0x55, flags: 0x0}, - 1316: {region: 0xa8, script: 0x5, flags: 0x0}, - 1317: {region: 0xd9, script: 0x55, flags: 0x0}, - 1318: {region: 0xba, script: 0xd8, flags: 0x0}, - 1319: {region: 0x4d, script: 0x14, flags: 0x1}, - 1320: {region: 0x165, script: 0x55, flags: 0x0}, - 1321: {region: 0x122, script: 0x55, flags: 0x0}, - 1322: {region: 0xd0, script: 0x55, flags: 0x0}, - 1323: {region: 0x165, script: 0x55, flags: 0x0}, - 1324: {region: 0x161, script: 0x55, flags: 0x0}, - 1326: {region: 0x12b, script: 0x55, flags: 0x0}, + 433: {region: 0x49, script: 0x57, flags: 0x0}, + 434: {region: 0x165, script: 0x5, flags: 0x0}, + 435: {region: 0x165, script: 0x57, flags: 0x0}, + 436: {region: 0x10, script: 0x3, flags: 0x1}, + 437: {region: 0x165, script: 0x57, flags: 0x0}, + 438: {region: 0x53, script: 0x38, flags: 0x0}, + 439: {region: 0x165, script: 0x57, flags: 0x0}, + 440: {region: 0x135, script: 0x57, flags: 0x0}, + 441: {region: 0x24, script: 0x5, flags: 0x0}, + 442: {region: 0x165, script: 0x57, flags: 0x0}, + 443: {region: 0x165, script: 0x29, flags: 0x0}, + 444: {region: 0x97, script: 0x3b, flags: 0x0}, + 445: {region: 0x165, script: 0x57, flags: 0x0}, + 446: {region: 0x99, script: 0x21, flags: 0x0}, + 447: {region: 0x165, script: 0x57, flags: 0x0}, + 448: {region: 0x73, script: 0x57, flags: 0x0}, + 449: {region: 0x165, script: 0x57, flags: 0x0}, + 450: {region: 0x165, script: 0x57, flags: 0x0}, + 451: {region: 0xe7, script: 0x57, flags: 0x0}, + 452: {region: 0x165, script: 0x57, flags: 0x0}, + 453: {region: 0x12b, script: 0x3d, flags: 0x0}, + 454: {region: 0x53, script: 0x89, flags: 0x0}, + 455: {region: 0x165, script: 0x57, flags: 0x0}, + 456: {region: 0xe8, script: 0x5, flags: 0x0}, + 457: {region: 0x99, script: 0x21, flags: 0x0}, + 458: {region: 0xaf, script: 0x3e, flags: 0x0}, + 459: {region: 0xe7, script: 0x57, flags: 0x0}, + 460: {region: 0xe8, script: 0x5, flags: 0x0}, + 461: {region: 0xe6, script: 0x57, flags: 0x0}, + 462: {region: 0x99, script: 0x21, flags: 0x0}, + 463: {region: 0x99, script: 0x21, flags: 0x0}, + 464: {region: 0x165, script: 0x57, flags: 0x0}, + 465: {region: 0x90, script: 0x57, flags: 0x0}, + 466: {region: 0x60, script: 0x57, flags: 0x0}, + 467: {region: 0x53, script: 0x38, flags: 0x0}, + 468: {region: 0x91, script: 0x57, flags: 0x0}, + 469: {region: 0x92, script: 0x57, flags: 0x0}, + 470: {region: 0x165, script: 0x57, flags: 0x0}, + 471: {region: 0x28, script: 0x8, flags: 0x0}, + 472: {region: 0xd2, script: 0x57, flags: 0x0}, + 473: {region: 0x78, script: 0x57, flags: 0x0}, + 474: {region: 0x165, script: 0x57, flags: 0x0}, + 475: {region: 0x165, script: 0x57, flags: 0x0}, + 476: {region: 0xd0, script: 0x57, flags: 0x0}, + 477: {region: 0xd6, script: 0x57, flags: 0x0}, + 478: {region: 0x165, script: 0x57, flags: 0x0}, + 479: {region: 0x165, script: 0x57, flags: 0x0}, + 480: {region: 0x165, script: 0x57, flags: 0x0}, + 481: {region: 0x95, script: 0x57, flags: 0x0}, + 482: {region: 0x165, script: 0x57, flags: 0x0}, + 483: {region: 0x165, script: 0x57, flags: 0x0}, + 484: {region: 0x165, script: 0x57, flags: 0x0}, + 486: {region: 0x122, script: 0x57, flags: 0x0}, + 487: {region: 0xd6, script: 0x57, flags: 0x0}, + 488: {region: 0x165, script: 0x57, flags: 0x0}, + 489: {region: 0x165, script: 0x57, flags: 0x0}, + 490: {region: 0x53, script: 0xea, flags: 0x0}, + 491: {region: 0x165, script: 0x57, flags: 0x0}, + 492: {region: 0x135, script: 0x57, flags: 0x0}, + 493: {region: 0x165, script: 0x57, flags: 0x0}, + 494: {region: 0x49, script: 0x57, flags: 0x0}, + 495: {region: 0x165, script: 0x57, flags: 0x0}, + 496: {region: 0x165, script: 0x57, flags: 0x0}, + 497: {region: 0xe7, script: 0x57, flags: 0x0}, + 498: {region: 0x165, script: 0x57, flags: 0x0}, + 499: {region: 0x95, script: 0x57, flags: 0x0}, + 500: {region: 0x106, script: 0x1f, flags: 0x0}, + 501: {region: 0x1, script: 0x57, flags: 0x0}, + 502: {region: 0x165, script: 0x57, flags: 0x0}, + 503: {region: 0x165, script: 0x57, flags: 0x0}, + 504: {region: 0x9d, script: 0x57, flags: 0x0}, + 505: {region: 0x9e, script: 0x57, flags: 0x0}, + 506: {region: 0x49, script: 0x17, flags: 0x0}, + 507: {region: 0x97, script: 0x3b, flags: 0x0}, + 508: {region: 0x165, script: 0x57, flags: 0x0}, + 509: {region: 0x165, script: 0x57, flags: 0x0}, + 510: {region: 0x106, script: 0x57, flags: 0x0}, + 511: {region: 0x165, script: 0x57, flags: 0x0}, + 512: {region: 0xa2, script: 0x46, flags: 0x0}, + 513: {region: 0x165, script: 0x57, flags: 0x0}, + 514: {region: 0xa0, script: 0x57, flags: 0x0}, + 515: {region: 0x1, script: 0x57, flags: 0x0}, + 516: {region: 0x165, script: 0x57, flags: 0x0}, + 517: {region: 0x165, script: 0x57, flags: 0x0}, + 518: {region: 0x165, script: 0x57, flags: 0x0}, + 519: {region: 0x52, script: 0x57, flags: 0x0}, + 520: {region: 0x130, script: 0x3b, flags: 0x0}, + 521: {region: 0x165, script: 0x57, flags: 0x0}, + 522: {region: 0x12f, script: 0x57, flags: 0x0}, + 523: {region: 0xdb, script: 0x21, flags: 0x0}, + 524: {region: 0x165, script: 0x57, flags: 0x0}, + 525: {region: 0x63, script: 0x57, flags: 0x0}, + 526: {region: 0x95, script: 0x57, flags: 0x0}, + 527: {region: 0x95, script: 0x57, flags: 0x0}, + 528: {region: 0x7d, script: 0x2b, flags: 0x0}, + 529: {region: 0x137, script: 0x1f, flags: 0x0}, + 530: {region: 0x67, script: 0x57, flags: 0x0}, + 531: {region: 0xc4, script: 0x57, flags: 0x0}, + 532: {region: 0x165, script: 0x57, flags: 0x0}, + 533: {region: 0x165, script: 0x57, flags: 0x0}, + 534: {region: 0xd6, script: 0x57, flags: 0x0}, + 535: {region: 0xa4, script: 0x57, flags: 0x0}, + 536: {region: 0xc3, script: 0x57, flags: 0x0}, + 537: {region: 0x106, script: 0x1f, flags: 0x0}, + 538: {region: 0x165, script: 0x57, flags: 0x0}, + 539: {region: 0x165, script: 0x57, flags: 0x0}, + 540: {region: 0x165, script: 0x57, flags: 0x0}, + 541: {region: 0x165, script: 0x57, flags: 0x0}, + 542: {region: 0xd4, script: 0x5, flags: 0x0}, + 543: {region: 0xd6, script: 0x57, flags: 0x0}, + 544: {region: 0x164, script: 0x57, flags: 0x0}, + 545: {region: 0x165, script: 0x57, flags: 0x0}, + 546: {region: 0x165, script: 0x57, flags: 0x0}, + 547: {region: 0x12f, script: 0x57, flags: 0x0}, + 548: {region: 0x122, script: 0x5, flags: 0x0}, + 549: {region: 0x165, script: 0x57, flags: 0x0}, + 550: {region: 0x123, script: 0xdf, flags: 0x0}, + 551: {region: 0x5a, script: 0x57, flags: 0x0}, + 552: {region: 0x52, script: 0x57, flags: 0x0}, + 553: {region: 0x165, script: 0x57, flags: 0x0}, + 554: {region: 0x4f, script: 0x57, flags: 0x0}, + 555: {region: 0x99, script: 0x21, flags: 0x0}, + 556: {region: 0x99, script: 0x21, flags: 0x0}, + 557: {region: 0x4b, script: 0x57, flags: 0x0}, + 558: {region: 0x95, script: 0x57, flags: 0x0}, + 559: {region: 0x165, script: 0x57, flags: 0x0}, + 560: {region: 0x41, script: 0x57, flags: 0x0}, + 561: {region: 0x99, script: 0x57, flags: 0x0}, + 562: {region: 0x53, script: 0xd6, flags: 0x0}, + 563: {region: 0x99, script: 0x21, flags: 0x0}, + 564: {region: 0xc3, script: 0x57, flags: 0x0}, + 565: {region: 0x165, script: 0x57, flags: 0x0}, + 566: {region: 0x99, script: 0x72, flags: 0x0}, + 567: {region: 0xe8, script: 0x5, flags: 0x0}, + 568: {region: 0x165, script: 0x57, flags: 0x0}, + 569: {region: 0xa4, script: 0x57, flags: 0x0}, + 570: {region: 0x165, script: 0x57, flags: 0x0}, + 571: {region: 0x12b, script: 0x57, flags: 0x0}, + 572: {region: 0x165, script: 0x57, flags: 0x0}, + 573: {region: 0xd2, script: 0x57, flags: 0x0}, + 574: {region: 0x165, script: 0x57, flags: 0x0}, + 575: {region: 0xaf, script: 0x54, flags: 0x0}, + 576: {region: 0x165, script: 0x57, flags: 0x0}, + 577: {region: 0x165, script: 0x57, flags: 0x0}, + 578: {region: 0x13, script: 0x6, flags: 0x1}, + 579: {region: 0x165, script: 0x57, flags: 0x0}, + 580: {region: 0x52, script: 0x57, flags: 0x0}, + 581: {region: 0x82, script: 0x57, flags: 0x0}, + 582: {region: 0xa4, script: 0x57, flags: 0x0}, + 583: {region: 0x165, script: 0x57, flags: 0x0}, + 584: {region: 0x165, script: 0x57, flags: 0x0}, + 585: {region: 0x165, script: 0x57, flags: 0x0}, + 586: {region: 0xa6, script: 0x4b, flags: 0x0}, + 587: {region: 0x2a, script: 0x57, flags: 0x0}, + 588: {region: 0x165, script: 0x57, flags: 0x0}, + 589: {region: 0x165, script: 0x57, flags: 0x0}, + 590: {region: 0x165, script: 0x57, flags: 0x0}, + 591: {region: 0x165, script: 0x57, flags: 0x0}, + 592: {region: 0x165, script: 0x57, flags: 0x0}, + 593: {region: 0x99, script: 0x4f, flags: 0x0}, + 594: {region: 0x8b, script: 0x57, flags: 0x0}, + 595: {region: 0x165, script: 0x57, flags: 0x0}, + 596: {region: 0xab, script: 0x50, flags: 0x0}, + 597: {region: 0x106, script: 0x1f, flags: 0x0}, + 598: {region: 0x99, script: 0x21, flags: 0x0}, + 599: {region: 0x165, script: 0x57, flags: 0x0}, + 600: {region: 0x75, script: 0x57, flags: 0x0}, + 601: {region: 0x165, script: 0x57, flags: 0x0}, + 602: {region: 0xb4, script: 0x57, flags: 0x0}, + 603: {region: 0x165, script: 0x57, flags: 0x0}, + 604: {region: 0x165, script: 0x57, flags: 0x0}, + 605: {region: 0x165, script: 0x57, flags: 0x0}, + 606: {region: 0x165, script: 0x57, flags: 0x0}, + 607: {region: 0x165, script: 0x57, flags: 0x0}, + 608: {region: 0x165, script: 0x57, flags: 0x0}, + 609: {region: 0x165, script: 0x57, flags: 0x0}, + 610: {region: 0x165, script: 0x29, flags: 0x0}, + 611: {region: 0x165, script: 0x57, flags: 0x0}, + 612: {region: 0x106, script: 0x1f, flags: 0x0}, + 613: {region: 0x112, script: 0x57, flags: 0x0}, + 614: {region: 0xe7, script: 0x57, flags: 0x0}, + 615: {region: 0x106, script: 0x57, flags: 0x0}, + 616: {region: 0x165, script: 0x57, flags: 0x0}, + 617: {region: 0x99, script: 0x21, flags: 0x0}, + 618: {region: 0x99, script: 0x5, flags: 0x0}, + 619: {region: 0x12f, script: 0x57, flags: 0x0}, + 620: {region: 0x165, script: 0x57, flags: 0x0}, + 621: {region: 0x52, script: 0x57, flags: 0x0}, + 622: {region: 0x60, script: 0x57, flags: 0x0}, + 623: {region: 0x165, script: 0x57, flags: 0x0}, + 624: {region: 0x165, script: 0x57, flags: 0x0}, + 625: {region: 0x165, script: 0x29, flags: 0x0}, + 626: {region: 0x165, script: 0x57, flags: 0x0}, + 627: {region: 0x165, script: 0x57, flags: 0x0}, + 628: {region: 0x19, script: 0x3, flags: 0x1}, + 629: {region: 0x165, script: 0x57, flags: 0x0}, + 630: {region: 0x165, script: 0x57, flags: 0x0}, + 631: {region: 0x165, script: 0x57, flags: 0x0}, + 632: {region: 0x165, script: 0x57, flags: 0x0}, + 633: {region: 0x106, script: 0x1f, flags: 0x0}, + 634: {region: 0x165, script: 0x57, flags: 0x0}, + 635: {region: 0x165, script: 0x57, flags: 0x0}, + 636: {region: 0x165, script: 0x57, flags: 0x0}, + 637: {region: 0x106, script: 0x1f, flags: 0x0}, + 638: {region: 0x165, script: 0x57, flags: 0x0}, + 639: {region: 0x95, script: 0x57, flags: 0x0}, + 640: {region: 0xe8, script: 0x5, flags: 0x0}, + 641: {region: 0x7b, script: 0x57, flags: 0x0}, + 642: {region: 0x165, script: 0x57, flags: 0x0}, + 643: {region: 0x165, script: 0x57, flags: 0x0}, + 644: {region: 0x165, script: 0x57, flags: 0x0}, + 645: {region: 0x165, script: 0x29, flags: 0x0}, + 646: {region: 0x123, script: 0xdf, flags: 0x0}, + 647: {region: 0xe8, script: 0x5, flags: 0x0}, + 648: {region: 0x165, script: 0x57, flags: 0x0}, + 649: {region: 0x165, script: 0x57, flags: 0x0}, + 650: {region: 0x1c, script: 0x5, flags: 0x1}, + 651: {region: 0x165, script: 0x57, flags: 0x0}, + 652: {region: 0x165, script: 0x57, flags: 0x0}, + 653: {region: 0x165, script: 0x57, flags: 0x0}, + 654: {region: 0x138, script: 0x57, flags: 0x0}, + 655: {region: 0x87, script: 0x5b, flags: 0x0}, + 656: {region: 0x97, script: 0x3b, flags: 0x0}, + 657: {region: 0x12f, script: 0x57, flags: 0x0}, + 658: {region: 0xe8, script: 0x5, flags: 0x0}, + 659: {region: 0x131, script: 0x57, flags: 0x0}, + 660: {region: 0x165, script: 0x57, flags: 0x0}, + 661: {region: 0xb7, script: 0x57, flags: 0x0}, + 662: {region: 0x106, script: 0x1f, flags: 0x0}, + 663: {region: 0x165, script: 0x57, flags: 0x0}, + 664: {region: 0x95, script: 0x57, flags: 0x0}, + 665: {region: 0x165, script: 0x57, flags: 0x0}, + 666: {region: 0x53, script: 0xdf, flags: 0x0}, + 667: {region: 0x165, script: 0x57, flags: 0x0}, + 668: {region: 0x165, script: 0x57, flags: 0x0}, + 669: {region: 0x165, script: 0x57, flags: 0x0}, + 670: {region: 0x165, script: 0x57, flags: 0x0}, + 671: {region: 0x99, script: 0x59, flags: 0x0}, + 672: {region: 0x165, script: 0x57, flags: 0x0}, + 673: {region: 0x165, script: 0x57, flags: 0x0}, + 674: {region: 0x106, script: 0x1f, flags: 0x0}, + 675: {region: 0x131, script: 0x57, flags: 0x0}, + 676: {region: 0x165, script: 0x57, flags: 0x0}, + 677: {region: 0xd9, script: 0x57, flags: 0x0}, + 678: {region: 0x165, script: 0x57, flags: 0x0}, + 679: {region: 0x165, script: 0x57, flags: 0x0}, + 680: {region: 0x21, script: 0x2, flags: 0x1}, + 681: {region: 0x165, script: 0x57, flags: 0x0}, + 682: {region: 0x165, script: 0x57, flags: 0x0}, + 683: {region: 0x9e, script: 0x57, flags: 0x0}, + 684: {region: 0x53, script: 0x5d, flags: 0x0}, + 685: {region: 0x95, script: 0x57, flags: 0x0}, + 686: {region: 0x9c, script: 0x5, flags: 0x0}, + 687: {region: 0x135, script: 0x57, flags: 0x0}, + 688: {region: 0x165, script: 0x57, flags: 0x0}, + 689: {region: 0x165, script: 0x57, flags: 0x0}, + 690: {region: 0x99, script: 0xda, flags: 0x0}, + 691: {region: 0x9e, script: 0x57, flags: 0x0}, + 692: {region: 0x165, script: 0x57, flags: 0x0}, + 693: {region: 0x4b, script: 0x57, flags: 0x0}, + 694: {region: 0x165, script: 0x57, flags: 0x0}, + 695: {region: 0x165, script: 0x57, flags: 0x0}, + 696: {region: 0xaf, script: 0x54, flags: 0x0}, + 697: {region: 0x165, script: 0x57, flags: 0x0}, + 698: {region: 0x165, script: 0x57, flags: 0x0}, + 699: {region: 0x4b, script: 0x57, flags: 0x0}, + 700: {region: 0x165, script: 0x57, flags: 0x0}, + 701: {region: 0x165, script: 0x57, flags: 0x0}, + 702: {region: 0x162, script: 0x57, flags: 0x0}, + 703: {region: 0x9c, script: 0x5, flags: 0x0}, + 704: {region: 0xb6, script: 0x57, flags: 0x0}, + 705: {region: 0xb8, script: 0x57, flags: 0x0}, + 706: {region: 0x4b, script: 0x57, flags: 0x0}, + 707: {region: 0x4b, script: 0x57, flags: 0x0}, + 708: {region: 0xa4, script: 0x57, flags: 0x0}, + 709: {region: 0xa4, script: 0x57, flags: 0x0}, + 710: {region: 0x9c, script: 0x5, flags: 0x0}, + 711: {region: 0xb8, script: 0x57, flags: 0x0}, + 712: {region: 0x123, script: 0xdf, flags: 0x0}, + 713: {region: 0x53, script: 0x38, flags: 0x0}, + 714: {region: 0x12b, script: 0x57, flags: 0x0}, + 715: {region: 0x95, script: 0x57, flags: 0x0}, + 716: {region: 0x52, script: 0x57, flags: 0x0}, + 717: {region: 0x99, script: 0x21, flags: 0x0}, + 718: {region: 0x99, script: 0x21, flags: 0x0}, + 719: {region: 0x95, script: 0x57, flags: 0x0}, + 720: {region: 0x23, script: 0x3, flags: 0x1}, + 721: {region: 0xa4, script: 0x57, flags: 0x0}, + 722: {region: 0x165, script: 0x57, flags: 0x0}, + 723: {region: 0xcf, script: 0x57, flags: 0x0}, + 724: {region: 0x165, script: 0x57, flags: 0x0}, + 725: {region: 0x165, script: 0x57, flags: 0x0}, + 726: {region: 0x165, script: 0x57, flags: 0x0}, + 727: {region: 0x165, script: 0x57, flags: 0x0}, + 728: {region: 0x165, script: 0x57, flags: 0x0}, + 729: {region: 0x165, script: 0x57, flags: 0x0}, + 730: {region: 0x165, script: 0x57, flags: 0x0}, + 731: {region: 0x165, script: 0x57, flags: 0x0}, + 732: {region: 0x165, script: 0x57, flags: 0x0}, + 733: {region: 0x165, script: 0x57, flags: 0x0}, + 734: {region: 0x165, script: 0x57, flags: 0x0}, + 735: {region: 0x165, script: 0x5, flags: 0x0}, + 736: {region: 0x106, script: 0x1f, flags: 0x0}, + 737: {region: 0xe7, script: 0x57, flags: 0x0}, + 738: {region: 0x165, script: 0x57, flags: 0x0}, + 739: {region: 0x95, script: 0x57, flags: 0x0}, + 740: {region: 0x165, script: 0x29, flags: 0x0}, + 741: {region: 0x165, script: 0x57, flags: 0x0}, + 742: {region: 0x165, script: 0x57, flags: 0x0}, + 743: {region: 0x165, script: 0x57, flags: 0x0}, + 744: {region: 0x112, script: 0x57, flags: 0x0}, + 745: {region: 0xa4, script: 0x57, flags: 0x0}, + 746: {region: 0x165, script: 0x57, flags: 0x0}, + 747: {region: 0x165, script: 0x57, flags: 0x0}, + 748: {region: 0x123, script: 0x5, flags: 0x0}, + 749: {region: 0xcc, script: 0x57, flags: 0x0}, + 750: {region: 0x165, script: 0x57, flags: 0x0}, + 751: {region: 0x165, script: 0x57, flags: 0x0}, + 752: {region: 0x165, script: 0x57, flags: 0x0}, + 753: {region: 0xbf, script: 0x57, flags: 0x0}, + 754: {region: 0xd1, script: 0x57, flags: 0x0}, + 755: {region: 0x165, script: 0x57, flags: 0x0}, + 756: {region: 0x52, script: 0x57, flags: 0x0}, + 757: {region: 0xdb, script: 0x21, flags: 0x0}, + 758: {region: 0x12f, script: 0x57, flags: 0x0}, + 759: {region: 0xc0, script: 0x57, flags: 0x0}, + 760: {region: 0x165, script: 0x57, flags: 0x0}, + 761: {region: 0x165, script: 0x57, flags: 0x0}, + 762: {region: 0xe0, script: 0x57, flags: 0x0}, + 763: {region: 0x165, script: 0x57, flags: 0x0}, + 764: {region: 0x95, script: 0x57, flags: 0x0}, + 765: {region: 0x9b, script: 0x3a, flags: 0x0}, + 766: {region: 0x165, script: 0x57, flags: 0x0}, + 767: {region: 0xc2, script: 0x1f, flags: 0x0}, + 768: {region: 0x165, script: 0x5, flags: 0x0}, + 769: {region: 0x165, script: 0x57, flags: 0x0}, + 770: {region: 0x165, script: 0x57, flags: 0x0}, + 771: {region: 0x165, script: 0x57, flags: 0x0}, + 772: {region: 0x99, script: 0x6b, flags: 0x0}, + 773: {region: 0x165, script: 0x57, flags: 0x0}, + 774: {region: 0x165, script: 0x57, flags: 0x0}, + 775: {region: 0x10b, script: 0x57, flags: 0x0}, + 776: {region: 0x165, script: 0x57, flags: 0x0}, + 777: {region: 0x165, script: 0x57, flags: 0x0}, + 778: {region: 0x165, script: 0x57, flags: 0x0}, + 779: {region: 0x26, script: 0x3, flags: 0x1}, + 780: {region: 0x165, script: 0x57, flags: 0x0}, + 781: {region: 0x165, script: 0x57, flags: 0x0}, + 782: {region: 0x99, script: 0xe, flags: 0x0}, + 783: {region: 0xc4, script: 0x72, flags: 0x0}, + 785: {region: 0x165, script: 0x57, flags: 0x0}, + 786: {region: 0x49, script: 0x57, flags: 0x0}, + 787: {region: 0x49, script: 0x57, flags: 0x0}, + 788: {region: 0x37, script: 0x57, flags: 0x0}, + 789: {region: 0x165, script: 0x57, flags: 0x0}, + 790: {region: 0x165, script: 0x57, flags: 0x0}, + 791: {region: 0x165, script: 0x57, flags: 0x0}, + 792: {region: 0x165, script: 0x57, flags: 0x0}, + 793: {region: 0x165, script: 0x57, flags: 0x0}, + 794: {region: 0x165, script: 0x57, flags: 0x0}, + 795: {region: 0x99, script: 0x21, flags: 0x0}, + 796: {region: 0xdb, script: 0x21, flags: 0x0}, + 797: {region: 0x106, script: 0x1f, flags: 0x0}, + 798: {region: 0x35, script: 0x6f, flags: 0x0}, + 799: {region: 0x29, script: 0x3, flags: 0x1}, + 800: {region: 0xcb, script: 0x57, flags: 0x0}, + 801: {region: 0x165, script: 0x57, flags: 0x0}, + 802: {region: 0x165, script: 0x57, flags: 0x0}, + 803: {region: 0x165, script: 0x57, flags: 0x0}, + 804: {region: 0x99, script: 0x21, flags: 0x0}, + 805: {region: 0x52, script: 0x57, flags: 0x0}, + 807: {region: 0x165, script: 0x57, flags: 0x0}, + 808: {region: 0x135, script: 0x57, flags: 0x0}, + 809: {region: 0x165, script: 0x57, flags: 0x0}, + 810: {region: 0x165, script: 0x57, flags: 0x0}, + 811: {region: 0xe8, script: 0x5, flags: 0x0}, + 812: {region: 0xc3, script: 0x57, flags: 0x0}, + 813: {region: 0x99, script: 0x21, flags: 0x0}, + 814: {region: 0x95, script: 0x57, flags: 0x0}, + 815: {region: 0x164, script: 0x57, flags: 0x0}, + 816: {region: 0x165, script: 0x57, flags: 0x0}, + 817: {region: 0xc4, script: 0x72, flags: 0x0}, + 818: {region: 0x165, script: 0x57, flags: 0x0}, + 819: {region: 0x165, script: 0x29, flags: 0x0}, + 820: {region: 0x106, script: 0x1f, flags: 0x0}, + 821: {region: 0x165, script: 0x57, flags: 0x0}, + 822: {region: 0x131, script: 0x57, flags: 0x0}, + 823: {region: 0x9c, script: 0x63, flags: 0x0}, + 824: {region: 0x165, script: 0x57, flags: 0x0}, + 825: {region: 0x165, script: 0x57, flags: 0x0}, + 826: {region: 0x9c, script: 0x5, flags: 0x0}, + 827: {region: 0x165, script: 0x57, flags: 0x0}, + 828: {region: 0x165, script: 0x57, flags: 0x0}, + 829: {region: 0x165, script: 0x57, flags: 0x0}, + 830: {region: 0xdd, script: 0x57, flags: 0x0}, + 831: {region: 0x165, script: 0x57, flags: 0x0}, + 832: {region: 0x165, script: 0x57, flags: 0x0}, + 834: {region: 0x165, script: 0x57, flags: 0x0}, + 835: {region: 0x53, script: 0x38, flags: 0x0}, + 836: {region: 0x9e, script: 0x57, flags: 0x0}, + 837: {region: 0xd2, script: 0x57, flags: 0x0}, + 838: {region: 0x165, script: 0x57, flags: 0x0}, + 839: {region: 0xda, script: 0x57, flags: 0x0}, + 840: {region: 0x165, script: 0x57, flags: 0x0}, + 841: {region: 0x165, script: 0x57, flags: 0x0}, + 842: {region: 0x165, script: 0x57, flags: 0x0}, + 843: {region: 0xcf, script: 0x57, flags: 0x0}, + 844: {region: 0x165, script: 0x57, flags: 0x0}, + 845: {region: 0x165, script: 0x57, flags: 0x0}, + 846: {region: 0x164, script: 0x57, flags: 0x0}, + 847: {region: 0xd1, script: 0x57, flags: 0x0}, + 848: {region: 0x60, script: 0x57, flags: 0x0}, + 849: {region: 0xdb, script: 0x21, flags: 0x0}, + 850: {region: 0x165, script: 0x57, flags: 0x0}, + 851: {region: 0xdb, script: 0x21, flags: 0x0}, + 852: {region: 0x165, script: 0x57, flags: 0x0}, + 853: {region: 0x165, script: 0x57, flags: 0x0}, + 854: {region: 0xd2, script: 0x57, flags: 0x0}, + 855: {region: 0x165, script: 0x57, flags: 0x0}, + 856: {region: 0x165, script: 0x57, flags: 0x0}, + 857: {region: 0xd1, script: 0x57, flags: 0x0}, + 858: {region: 0x165, script: 0x57, flags: 0x0}, + 859: {region: 0xcf, script: 0x57, flags: 0x0}, + 860: {region: 0xcf, script: 0x57, flags: 0x0}, + 861: {region: 0x165, script: 0x57, flags: 0x0}, + 862: {region: 0x165, script: 0x57, flags: 0x0}, + 863: {region: 0x95, script: 0x57, flags: 0x0}, + 864: {region: 0x165, script: 0x57, flags: 0x0}, + 865: {region: 0xdf, script: 0x57, flags: 0x0}, + 866: {region: 0x165, script: 0x57, flags: 0x0}, + 867: {region: 0x165, script: 0x57, flags: 0x0}, + 868: {region: 0x99, script: 0x57, flags: 0x0}, + 869: {region: 0x165, script: 0x57, flags: 0x0}, + 870: {region: 0x165, script: 0x57, flags: 0x0}, + 871: {region: 0xd9, script: 0x57, flags: 0x0}, + 872: {region: 0x52, script: 0x57, flags: 0x0}, + 873: {region: 0x165, script: 0x57, flags: 0x0}, + 874: {region: 0xda, script: 0x57, flags: 0x0}, + 875: {region: 0x165, script: 0x57, flags: 0x0}, + 876: {region: 0x52, script: 0x57, flags: 0x0}, + 877: {region: 0x165, script: 0x57, flags: 0x0}, + 878: {region: 0x165, script: 0x57, flags: 0x0}, + 879: {region: 0xda, script: 0x57, flags: 0x0}, + 880: {region: 0x123, script: 0x53, flags: 0x0}, + 881: {region: 0x99, script: 0x21, flags: 0x0}, + 882: {region: 0x10c, script: 0xbf, flags: 0x0}, + 883: {region: 0x165, script: 0x57, flags: 0x0}, + 884: {region: 0x165, script: 0x57, flags: 0x0}, + 885: {region: 0x84, script: 0x78, flags: 0x0}, + 886: {region: 0x161, script: 0x57, flags: 0x0}, + 887: {region: 0x165, script: 0x57, flags: 0x0}, + 888: {region: 0x49, script: 0x17, flags: 0x0}, + 889: {region: 0x165, script: 0x57, flags: 0x0}, + 890: {region: 0x161, script: 0x57, flags: 0x0}, + 891: {region: 0x165, script: 0x57, flags: 0x0}, + 892: {region: 0x165, script: 0x57, flags: 0x0}, + 893: {region: 0x165, script: 0x57, flags: 0x0}, + 894: {region: 0x165, script: 0x57, flags: 0x0}, + 895: {region: 0x165, script: 0x57, flags: 0x0}, + 896: {region: 0x117, script: 0x57, flags: 0x0}, + 897: {region: 0x165, script: 0x57, flags: 0x0}, + 898: {region: 0x165, script: 0x57, flags: 0x0}, + 899: {region: 0x135, script: 0x57, flags: 0x0}, + 900: {region: 0x165, script: 0x57, flags: 0x0}, + 901: {region: 0x53, script: 0x57, flags: 0x0}, + 902: {region: 0x165, script: 0x57, flags: 0x0}, + 903: {region: 0xce, script: 0x57, flags: 0x0}, + 904: {region: 0x12f, script: 0x57, flags: 0x0}, + 905: {region: 0x131, script: 0x57, flags: 0x0}, + 906: {region: 0x80, script: 0x57, flags: 0x0}, + 907: {region: 0x78, script: 0x57, flags: 0x0}, + 908: {region: 0x165, script: 0x57, flags: 0x0}, + 910: {region: 0x165, script: 0x57, flags: 0x0}, + 911: {region: 0x165, script: 0x57, flags: 0x0}, + 912: {region: 0x6f, script: 0x57, flags: 0x0}, + 913: {region: 0x165, script: 0x57, flags: 0x0}, + 914: {region: 0x165, script: 0x57, flags: 0x0}, + 915: {region: 0x165, script: 0x57, flags: 0x0}, + 916: {region: 0x165, script: 0x57, flags: 0x0}, + 917: {region: 0x99, script: 0x7d, flags: 0x0}, + 918: {region: 0x165, script: 0x57, flags: 0x0}, + 919: {region: 0x165, script: 0x5, flags: 0x0}, + 920: {region: 0x7d, script: 0x1f, flags: 0x0}, + 921: {region: 0x135, script: 0x7e, flags: 0x0}, + 922: {region: 0x165, script: 0x5, flags: 0x0}, + 923: {region: 0xc5, script: 0x7c, flags: 0x0}, + 924: {region: 0x165, script: 0x57, flags: 0x0}, + 925: {region: 0x2c, script: 0x3, flags: 0x1}, + 926: {region: 0xe7, script: 0x57, flags: 0x0}, + 927: {region: 0x2f, script: 0x2, flags: 0x1}, + 928: {region: 0xe7, script: 0x57, flags: 0x0}, + 929: {region: 0x30, script: 0x57, flags: 0x0}, + 930: {region: 0xf0, script: 0x57, flags: 0x0}, + 931: {region: 0x165, script: 0x57, flags: 0x0}, + 932: {region: 0x78, script: 0x57, flags: 0x0}, + 933: {region: 0xd6, script: 0x57, flags: 0x0}, + 934: {region: 0x135, script: 0x57, flags: 0x0}, + 935: {region: 0x49, script: 0x57, flags: 0x0}, + 936: {region: 0x165, script: 0x57, flags: 0x0}, + 937: {region: 0x9c, script: 0xe8, flags: 0x0}, + 938: {region: 0x165, script: 0x57, flags: 0x0}, + 939: {region: 0x60, script: 0x57, flags: 0x0}, + 940: {region: 0x165, script: 0x5, flags: 0x0}, + 941: {region: 0xb0, script: 0x87, flags: 0x0}, + 943: {region: 0x165, script: 0x57, flags: 0x0}, + 944: {region: 0x165, script: 0x57, flags: 0x0}, + 945: {region: 0x99, script: 0x12, flags: 0x0}, + 946: {region: 0xa4, script: 0x57, flags: 0x0}, + 947: {region: 0xe9, script: 0x57, flags: 0x0}, + 948: {region: 0x165, script: 0x57, flags: 0x0}, + 949: {region: 0x9e, script: 0x57, flags: 0x0}, + 950: {region: 0x165, script: 0x57, flags: 0x0}, + 951: {region: 0x165, script: 0x57, flags: 0x0}, + 952: {region: 0x87, script: 0x31, flags: 0x0}, + 953: {region: 0x75, script: 0x57, flags: 0x0}, + 954: {region: 0x165, script: 0x57, flags: 0x0}, + 955: {region: 0xe8, script: 0x4a, flags: 0x0}, + 956: {region: 0x9c, script: 0x5, flags: 0x0}, + 957: {region: 0x1, script: 0x57, flags: 0x0}, + 958: {region: 0x24, script: 0x5, flags: 0x0}, + 959: {region: 0x165, script: 0x57, flags: 0x0}, + 960: {region: 0x41, script: 0x57, flags: 0x0}, + 961: {region: 0x165, script: 0x57, flags: 0x0}, + 962: {region: 0x7a, script: 0x57, flags: 0x0}, + 963: {region: 0x165, script: 0x57, flags: 0x0}, + 964: {region: 0xe4, script: 0x57, flags: 0x0}, + 965: {region: 0x89, script: 0x57, flags: 0x0}, + 966: {region: 0x69, script: 0x57, flags: 0x0}, + 967: {region: 0x165, script: 0x57, flags: 0x0}, + 968: {region: 0x99, script: 0x21, flags: 0x0}, + 969: {region: 0x165, script: 0x57, flags: 0x0}, + 970: {region: 0x102, script: 0x57, flags: 0x0}, + 971: {region: 0x95, script: 0x57, flags: 0x0}, + 972: {region: 0x165, script: 0x57, flags: 0x0}, + 973: {region: 0x165, script: 0x57, flags: 0x0}, + 974: {region: 0x9e, script: 0x57, flags: 0x0}, + 975: {region: 0x165, script: 0x5, flags: 0x0}, + 976: {region: 0x99, script: 0x57, flags: 0x0}, + 977: {region: 0x31, script: 0x2, flags: 0x1}, + 978: {region: 0xdb, script: 0x21, flags: 0x0}, + 979: {region: 0x35, script: 0xe, flags: 0x0}, + 980: {region: 0x4e, script: 0x57, flags: 0x0}, + 981: {region: 0x72, script: 0x57, flags: 0x0}, + 982: {region: 0x4e, script: 0x57, flags: 0x0}, + 983: {region: 0x9c, script: 0x5, flags: 0x0}, + 984: {region: 0x10c, script: 0x57, flags: 0x0}, + 985: {region: 0x3a, script: 0x57, flags: 0x0}, + 986: {region: 0x165, script: 0x57, flags: 0x0}, + 987: {region: 0xd1, script: 0x57, flags: 0x0}, + 988: {region: 0x104, script: 0x57, flags: 0x0}, + 989: {region: 0x95, script: 0x57, flags: 0x0}, + 990: {region: 0x12f, script: 0x57, flags: 0x0}, + 991: {region: 0x165, script: 0x57, flags: 0x0}, + 992: {region: 0x165, script: 0x57, flags: 0x0}, + 993: {region: 0x73, script: 0x57, flags: 0x0}, + 994: {region: 0x106, script: 0x1f, flags: 0x0}, + 995: {region: 0x130, script: 0x1f, flags: 0x0}, + 996: {region: 0x109, script: 0x57, flags: 0x0}, + 997: {region: 0x107, script: 0x57, flags: 0x0}, + 998: {region: 0x12f, script: 0x57, flags: 0x0}, + 999: {region: 0x165, script: 0x57, flags: 0x0}, + 1000: {region: 0xa2, script: 0x49, flags: 0x0}, + 1001: {region: 0x99, script: 0x21, flags: 0x0}, + 1002: {region: 0x80, script: 0x57, flags: 0x0}, + 1003: {region: 0x106, script: 0x1f, flags: 0x0}, + 1004: {region: 0xa4, script: 0x57, flags: 0x0}, + 1005: {region: 0x95, script: 0x57, flags: 0x0}, + 1006: {region: 0x99, script: 0x57, flags: 0x0}, + 1007: {region: 0x114, script: 0x57, flags: 0x0}, + 1008: {region: 0x99, script: 0xc3, flags: 0x0}, + 1009: {region: 0x165, script: 0x57, flags: 0x0}, + 1010: {region: 0x165, script: 0x57, flags: 0x0}, + 1011: {region: 0x12f, script: 0x57, flags: 0x0}, + 1012: {region: 0x9e, script: 0x57, flags: 0x0}, + 1013: {region: 0x99, script: 0x21, flags: 0x0}, + 1014: {region: 0x165, script: 0x5, flags: 0x0}, + 1015: {region: 0x9e, script: 0x57, flags: 0x0}, + 1016: {region: 0x7b, script: 0x57, flags: 0x0}, + 1017: {region: 0x49, script: 0x57, flags: 0x0}, + 1018: {region: 0x33, script: 0x4, flags: 0x1}, + 1019: {region: 0x9e, script: 0x57, flags: 0x0}, + 1020: {region: 0x9c, script: 0x5, flags: 0x0}, + 1021: {region: 0xda, script: 0x57, flags: 0x0}, + 1022: {region: 0x4f, script: 0x57, flags: 0x0}, + 1023: {region: 0xd1, script: 0x57, flags: 0x0}, + 1024: {region: 0xcf, script: 0x57, flags: 0x0}, + 1025: {region: 0xc3, script: 0x57, flags: 0x0}, + 1026: {region: 0x4c, script: 0x57, flags: 0x0}, + 1027: {region: 0x96, script: 0x7a, flags: 0x0}, + 1028: {region: 0xb6, script: 0x57, flags: 0x0}, + 1029: {region: 0x165, script: 0x29, flags: 0x0}, + 1030: {region: 0x165, script: 0x57, flags: 0x0}, + 1032: {region: 0xba, script: 0xdc, flags: 0x0}, + 1033: {region: 0x165, script: 0x57, flags: 0x0}, + 1034: {region: 0xc4, script: 0x72, flags: 0x0}, + 1035: {region: 0x165, script: 0x5, flags: 0x0}, + 1036: {region: 0xb3, script: 0xca, flags: 0x0}, + 1037: {region: 0x6f, script: 0x57, flags: 0x0}, + 1038: {region: 0x165, script: 0x57, flags: 0x0}, + 1039: {region: 0x165, script: 0x57, flags: 0x0}, + 1040: {region: 0x165, script: 0x57, flags: 0x0}, + 1041: {region: 0x165, script: 0x57, flags: 0x0}, + 1042: {region: 0x111, script: 0x57, flags: 0x0}, + 1043: {region: 0x165, script: 0x57, flags: 0x0}, + 1044: {region: 0xe8, script: 0x5, flags: 0x0}, + 1045: {region: 0x165, script: 0x57, flags: 0x0}, + 1046: {region: 0x10f, script: 0x57, flags: 0x0}, + 1047: {region: 0x165, script: 0x57, flags: 0x0}, + 1048: {region: 0xe9, script: 0x57, flags: 0x0}, + 1049: {region: 0x165, script: 0x57, flags: 0x0}, + 1050: {region: 0x95, script: 0x57, flags: 0x0}, + 1051: {region: 0x142, script: 0x57, flags: 0x0}, + 1052: {region: 0x10c, script: 0x57, flags: 0x0}, + 1054: {region: 0x10c, script: 0x57, flags: 0x0}, + 1055: {region: 0x72, script: 0x57, flags: 0x0}, + 1056: {region: 0x97, script: 0xc0, flags: 0x0}, + 1057: {region: 0x165, script: 0x57, flags: 0x0}, + 1058: {region: 0x72, script: 0x57, flags: 0x0}, + 1059: {region: 0x164, script: 0x57, flags: 0x0}, + 1060: {region: 0x165, script: 0x57, flags: 0x0}, + 1061: {region: 0xc3, script: 0x57, flags: 0x0}, + 1062: {region: 0x165, script: 0x57, flags: 0x0}, + 1063: {region: 0x165, script: 0x57, flags: 0x0}, + 1064: {region: 0x165, script: 0x57, flags: 0x0}, + 1065: {region: 0x115, script: 0x57, flags: 0x0}, + 1066: {region: 0x165, script: 0x57, flags: 0x0}, + 1067: {region: 0x165, script: 0x57, flags: 0x0}, + 1068: {region: 0x123, script: 0xdf, flags: 0x0}, + 1069: {region: 0x165, script: 0x57, flags: 0x0}, + 1070: {region: 0x165, script: 0x57, flags: 0x0}, + 1071: {region: 0x165, script: 0x57, flags: 0x0}, + 1072: {region: 0x165, script: 0x57, flags: 0x0}, + 1073: {region: 0x27, script: 0x57, flags: 0x0}, + 1074: {region: 0x37, script: 0x5, flags: 0x1}, + 1075: {region: 0x99, script: 0xcb, flags: 0x0}, + 1076: {region: 0x116, script: 0x57, flags: 0x0}, + 1077: {region: 0x114, script: 0x57, flags: 0x0}, + 1078: {region: 0x99, script: 0x21, flags: 0x0}, + 1079: {region: 0x161, script: 0x57, flags: 0x0}, + 1080: {region: 0x165, script: 0x57, flags: 0x0}, + 1081: {region: 0x165, script: 0x57, flags: 0x0}, + 1082: {region: 0x6d, script: 0x57, flags: 0x0}, + 1083: {region: 0x161, script: 0x57, flags: 0x0}, + 1084: {region: 0x165, script: 0x57, flags: 0x0}, + 1085: {region: 0x60, script: 0x57, flags: 0x0}, + 1086: {region: 0x95, script: 0x57, flags: 0x0}, + 1087: {region: 0x165, script: 0x57, flags: 0x0}, + 1088: {region: 0x165, script: 0x57, flags: 0x0}, + 1089: {region: 0x12f, script: 0x57, flags: 0x0}, + 1090: {region: 0x165, script: 0x57, flags: 0x0}, + 1091: {region: 0x84, script: 0x57, flags: 0x0}, + 1092: {region: 0x10c, script: 0x57, flags: 0x0}, + 1093: {region: 0x12f, script: 0x57, flags: 0x0}, + 1094: {region: 0x15f, script: 0x5, flags: 0x0}, + 1095: {region: 0x4b, script: 0x57, flags: 0x0}, + 1096: {region: 0x60, script: 0x57, flags: 0x0}, + 1097: {region: 0x165, script: 0x57, flags: 0x0}, + 1098: {region: 0x99, script: 0x21, flags: 0x0}, + 1099: {region: 0x95, script: 0x57, flags: 0x0}, + 1100: {region: 0x165, script: 0x57, flags: 0x0}, + 1101: {region: 0x35, script: 0xe, flags: 0x0}, + 1102: {region: 0x9b, script: 0xcf, flags: 0x0}, + 1103: {region: 0xe9, script: 0x57, flags: 0x0}, + 1104: {region: 0x99, script: 0xd7, flags: 0x0}, + 1105: {region: 0xdb, script: 0x21, flags: 0x0}, + 1106: {region: 0x165, script: 0x57, flags: 0x0}, + 1107: {region: 0x165, script: 0x57, flags: 0x0}, + 1108: {region: 0x165, script: 0x57, flags: 0x0}, + 1109: {region: 0x165, script: 0x57, flags: 0x0}, + 1110: {region: 0x165, script: 0x57, flags: 0x0}, + 1111: {region: 0x165, script: 0x57, flags: 0x0}, + 1112: {region: 0x165, script: 0x57, flags: 0x0}, + 1113: {region: 0x165, script: 0x57, flags: 0x0}, + 1114: {region: 0xe7, script: 0x57, flags: 0x0}, + 1115: {region: 0x165, script: 0x57, flags: 0x0}, + 1116: {region: 0x165, script: 0x57, flags: 0x0}, + 1117: {region: 0x99, script: 0x4f, flags: 0x0}, + 1118: {region: 0x53, script: 0xd5, flags: 0x0}, + 1119: {region: 0xdb, script: 0x21, flags: 0x0}, + 1120: {region: 0xdb, script: 0x21, flags: 0x0}, + 1121: {region: 0x99, script: 0xda, flags: 0x0}, + 1122: {region: 0x165, script: 0x57, flags: 0x0}, + 1123: {region: 0x112, script: 0x57, flags: 0x0}, + 1124: {region: 0x131, script: 0x57, flags: 0x0}, + 1125: {region: 0x126, script: 0x57, flags: 0x0}, + 1126: {region: 0x165, script: 0x57, flags: 0x0}, + 1127: {region: 0x3c, script: 0x3, flags: 0x1}, + 1128: {region: 0x165, script: 0x57, flags: 0x0}, + 1129: {region: 0x165, script: 0x57, flags: 0x0}, + 1130: {region: 0x165, script: 0x57, flags: 0x0}, + 1131: {region: 0x123, script: 0xdf, flags: 0x0}, + 1132: {region: 0xdb, script: 0x21, flags: 0x0}, + 1133: {region: 0xdb, script: 0x21, flags: 0x0}, + 1134: {region: 0xdb, script: 0x21, flags: 0x0}, + 1135: {region: 0x6f, script: 0x29, flags: 0x0}, + 1136: {region: 0x165, script: 0x57, flags: 0x0}, + 1137: {region: 0x6d, script: 0x29, flags: 0x0}, + 1138: {region: 0x165, script: 0x57, flags: 0x0}, + 1139: {region: 0x165, script: 0x57, flags: 0x0}, + 1140: {region: 0x165, script: 0x57, flags: 0x0}, + 1141: {region: 0xd6, script: 0x57, flags: 0x0}, + 1142: {region: 0x127, script: 0x57, flags: 0x0}, + 1143: {region: 0x125, script: 0x57, flags: 0x0}, + 1144: {region: 0x32, script: 0x57, flags: 0x0}, + 1145: {region: 0xdb, script: 0x21, flags: 0x0}, + 1146: {region: 0xe7, script: 0x57, flags: 0x0}, + 1147: {region: 0x165, script: 0x57, flags: 0x0}, + 1148: {region: 0x165, script: 0x57, flags: 0x0}, + 1149: {region: 0x32, script: 0x57, flags: 0x0}, + 1150: {region: 0xd4, script: 0x57, flags: 0x0}, + 1151: {region: 0x165, script: 0x57, flags: 0x0}, + 1152: {region: 0x161, script: 0x57, flags: 0x0}, + 1153: {region: 0x165, script: 0x57, flags: 0x0}, + 1154: {region: 0x129, script: 0x57, flags: 0x0}, + 1155: {region: 0x165, script: 0x57, flags: 0x0}, + 1156: {region: 0xce, script: 0x57, flags: 0x0}, + 1157: {region: 0x165, script: 0x57, flags: 0x0}, + 1158: {region: 0xe6, script: 0x57, flags: 0x0}, + 1159: {region: 0x165, script: 0x57, flags: 0x0}, + 1160: {region: 0x165, script: 0x57, flags: 0x0}, + 1161: {region: 0x165, script: 0x57, flags: 0x0}, + 1162: {region: 0x12b, script: 0x57, flags: 0x0}, + 1163: {region: 0x12b, script: 0x57, flags: 0x0}, + 1164: {region: 0x12e, script: 0x57, flags: 0x0}, + 1165: {region: 0x165, script: 0x5, flags: 0x0}, + 1166: {region: 0x161, script: 0x57, flags: 0x0}, + 1167: {region: 0x87, script: 0x31, flags: 0x0}, + 1168: {region: 0xdb, script: 0x21, flags: 0x0}, + 1169: {region: 0xe7, script: 0x57, flags: 0x0}, + 1170: {region: 0x43, script: 0xe0, flags: 0x0}, + 1171: {region: 0x165, script: 0x57, flags: 0x0}, + 1172: {region: 0x106, script: 0x1f, flags: 0x0}, + 1173: {region: 0x165, script: 0x57, flags: 0x0}, + 1174: {region: 0x165, script: 0x57, flags: 0x0}, + 1175: {region: 0x131, script: 0x57, flags: 0x0}, + 1176: {region: 0x165, script: 0x57, flags: 0x0}, + 1177: {region: 0x123, script: 0xdf, flags: 0x0}, + 1178: {region: 0x32, script: 0x57, flags: 0x0}, + 1179: {region: 0x165, script: 0x57, flags: 0x0}, + 1180: {region: 0x165, script: 0x57, flags: 0x0}, + 1181: {region: 0xce, script: 0x57, flags: 0x0}, + 1182: {region: 0x165, script: 0x57, flags: 0x0}, + 1183: {region: 0x165, script: 0x57, flags: 0x0}, + 1184: {region: 0x12d, script: 0x57, flags: 0x0}, + 1185: {region: 0x165, script: 0x57, flags: 0x0}, + 1187: {region: 0x165, script: 0x57, flags: 0x0}, + 1188: {region: 0xd4, script: 0x57, flags: 0x0}, + 1189: {region: 0x53, script: 0xd8, flags: 0x0}, + 1190: {region: 0xe5, script: 0x57, flags: 0x0}, + 1191: {region: 0x165, script: 0x57, flags: 0x0}, + 1192: {region: 0x106, script: 0x1f, flags: 0x0}, + 1193: {region: 0xba, script: 0x57, flags: 0x0}, + 1194: {region: 0x165, script: 0x57, flags: 0x0}, + 1195: {region: 0x106, script: 0x1f, flags: 0x0}, + 1196: {region: 0x3f, script: 0x4, flags: 0x1}, + 1197: {region: 0x11c, script: 0xe2, flags: 0x0}, + 1198: {region: 0x130, script: 0x1f, flags: 0x0}, + 1199: {region: 0x75, script: 0x57, flags: 0x0}, + 1200: {region: 0x2a, script: 0x57, flags: 0x0}, + 1202: {region: 0x43, script: 0x3, flags: 0x1}, + 1203: {region: 0x99, script: 0xe, flags: 0x0}, + 1204: {region: 0xe8, script: 0x5, flags: 0x0}, + 1205: {region: 0x165, script: 0x57, flags: 0x0}, + 1206: {region: 0x165, script: 0x57, flags: 0x0}, + 1207: {region: 0x165, script: 0x57, flags: 0x0}, + 1208: {region: 0x165, script: 0x57, flags: 0x0}, + 1209: {region: 0x165, script: 0x57, flags: 0x0}, + 1210: {region: 0x165, script: 0x57, flags: 0x0}, + 1211: {region: 0x165, script: 0x57, flags: 0x0}, + 1212: {region: 0x46, script: 0x4, flags: 0x1}, + 1213: {region: 0x165, script: 0x57, flags: 0x0}, + 1214: {region: 0xb4, script: 0xe3, flags: 0x0}, + 1215: {region: 0x165, script: 0x57, flags: 0x0}, + 1216: {region: 0x161, script: 0x57, flags: 0x0}, + 1217: {region: 0x9e, script: 0x57, flags: 0x0}, + 1218: {region: 0x106, script: 0x57, flags: 0x0}, + 1219: {region: 0x13e, script: 0x57, flags: 0x0}, + 1220: {region: 0x11b, script: 0x57, flags: 0x0}, + 1221: {region: 0x165, script: 0x57, flags: 0x0}, + 1222: {region: 0x36, script: 0x57, flags: 0x0}, + 1223: {region: 0x60, script: 0x57, flags: 0x0}, + 1224: {region: 0xd1, script: 0x57, flags: 0x0}, + 1225: {region: 0x1, script: 0x57, flags: 0x0}, + 1226: {region: 0x106, script: 0x57, flags: 0x0}, + 1227: {region: 0x6a, script: 0x57, flags: 0x0}, + 1228: {region: 0x12f, script: 0x57, flags: 0x0}, + 1229: {region: 0x165, script: 0x57, flags: 0x0}, + 1230: {region: 0x36, script: 0x57, flags: 0x0}, + 1231: {region: 0x4e, script: 0x57, flags: 0x0}, + 1232: {region: 0x165, script: 0x57, flags: 0x0}, + 1233: {region: 0x6f, script: 0x29, flags: 0x0}, + 1234: {region: 0x165, script: 0x57, flags: 0x0}, + 1235: {region: 0xe7, script: 0x57, flags: 0x0}, + 1236: {region: 0x2f, script: 0x57, flags: 0x0}, + 1237: {region: 0x99, script: 0xda, flags: 0x0}, + 1238: {region: 0x99, script: 0x21, flags: 0x0}, + 1239: {region: 0x165, script: 0x57, flags: 0x0}, + 1240: {region: 0x165, script: 0x57, flags: 0x0}, + 1241: {region: 0x165, script: 0x57, flags: 0x0}, + 1242: {region: 0x165, script: 0x57, flags: 0x0}, + 1243: {region: 0x165, script: 0x57, flags: 0x0}, + 1244: {region: 0x165, script: 0x57, flags: 0x0}, + 1245: {region: 0x165, script: 0x57, flags: 0x0}, + 1246: {region: 0x165, script: 0x57, flags: 0x0}, + 1247: {region: 0x165, script: 0x57, flags: 0x0}, + 1248: {region: 0x140, script: 0x57, flags: 0x0}, + 1249: {region: 0x165, script: 0x57, flags: 0x0}, + 1250: {region: 0x165, script: 0x57, flags: 0x0}, + 1251: {region: 0xa8, script: 0x5, flags: 0x0}, + 1252: {region: 0x165, script: 0x57, flags: 0x0}, + 1253: {region: 0x114, script: 0x57, flags: 0x0}, + 1254: {region: 0x165, script: 0x57, flags: 0x0}, + 1255: {region: 0x165, script: 0x57, flags: 0x0}, + 1256: {region: 0x165, script: 0x57, flags: 0x0}, + 1257: {region: 0x165, script: 0x57, flags: 0x0}, + 1258: {region: 0x99, script: 0x21, flags: 0x0}, + 1259: {region: 0x53, script: 0x38, flags: 0x0}, + 1260: {region: 0x165, script: 0x57, flags: 0x0}, + 1261: {region: 0x165, script: 0x57, flags: 0x0}, + 1262: {region: 0x41, script: 0x57, flags: 0x0}, + 1263: {region: 0x165, script: 0x57, flags: 0x0}, + 1264: {region: 0x12b, script: 0x18, flags: 0x0}, + 1265: {region: 0x165, script: 0x57, flags: 0x0}, + 1266: {region: 0x161, script: 0x57, flags: 0x0}, + 1267: {region: 0x165, script: 0x57, flags: 0x0}, + 1268: {region: 0x12b, script: 0x5f, flags: 0x0}, + 1269: {region: 0x12b, script: 0x60, flags: 0x0}, + 1270: {region: 0x7d, script: 0x2b, flags: 0x0}, + 1271: {region: 0x53, script: 0x64, flags: 0x0}, + 1272: {region: 0x10b, script: 0x69, flags: 0x0}, + 1273: {region: 0x108, script: 0x73, flags: 0x0}, + 1274: {region: 0x99, script: 0x21, flags: 0x0}, + 1275: {region: 0x131, script: 0x57, flags: 0x0}, + 1276: {region: 0x165, script: 0x57, flags: 0x0}, + 1277: {region: 0x9c, script: 0x8a, flags: 0x0}, + 1278: {region: 0x165, script: 0x57, flags: 0x0}, + 1279: {region: 0x15e, script: 0xc2, flags: 0x0}, + 1280: {region: 0x165, script: 0x57, flags: 0x0}, + 1281: {region: 0x165, script: 0x57, flags: 0x0}, + 1282: {region: 0xdb, script: 0x21, flags: 0x0}, + 1283: {region: 0x165, script: 0x57, flags: 0x0}, + 1284: {region: 0x165, script: 0x57, flags: 0x0}, + 1285: {region: 0xd1, script: 0x57, flags: 0x0}, + 1286: {region: 0x75, script: 0x57, flags: 0x0}, + 1287: {region: 0x165, script: 0x57, flags: 0x0}, + 1288: {region: 0x165, script: 0x57, flags: 0x0}, + 1289: {region: 0x52, script: 0x57, flags: 0x0}, + 1290: {region: 0x165, script: 0x57, flags: 0x0}, + 1291: {region: 0x165, script: 0x57, flags: 0x0}, + 1292: {region: 0x165, script: 0x57, flags: 0x0}, + 1293: {region: 0x52, script: 0x57, flags: 0x0}, + 1294: {region: 0x165, script: 0x57, flags: 0x0}, + 1295: {region: 0x165, script: 0x57, flags: 0x0}, + 1296: {region: 0x165, script: 0x57, flags: 0x0}, + 1297: {region: 0x165, script: 0x57, flags: 0x0}, + 1298: {region: 0x1, script: 0x3b, flags: 0x0}, + 1299: {region: 0x165, script: 0x57, flags: 0x0}, + 1300: {region: 0x165, script: 0x57, flags: 0x0}, + 1301: {region: 0x165, script: 0x57, flags: 0x0}, + 1302: {region: 0x165, script: 0x57, flags: 0x0}, + 1303: {region: 0x165, script: 0x57, flags: 0x0}, + 1304: {region: 0xd6, script: 0x57, flags: 0x0}, + 1305: {region: 0x165, script: 0x57, flags: 0x0}, + 1306: {region: 0x165, script: 0x57, flags: 0x0}, + 1307: {region: 0x165, script: 0x57, flags: 0x0}, + 1308: {region: 0x41, script: 0x57, flags: 0x0}, + 1309: {region: 0x165, script: 0x57, flags: 0x0}, + 1310: {region: 0xcf, script: 0x57, flags: 0x0}, + 1311: {region: 0x4a, script: 0x3, flags: 0x1}, + 1312: {region: 0x165, script: 0x57, flags: 0x0}, + 1313: {region: 0x165, script: 0x57, flags: 0x0}, + 1314: {region: 0x165, script: 0x57, flags: 0x0}, + 1315: {region: 0x53, script: 0x57, flags: 0x0}, + 1316: {region: 0x10b, script: 0x57, flags: 0x0}, + 1318: {region: 0xa8, script: 0x5, flags: 0x0}, + 1319: {region: 0xd9, script: 0x57, flags: 0x0}, + 1320: {region: 0xba, script: 0xdc, flags: 0x0}, + 1321: {region: 0x4d, script: 0x14, flags: 0x1}, + 1322: {region: 0x53, script: 0x79, flags: 0x0}, + 1323: {region: 0x165, script: 0x57, flags: 0x0}, + 1324: {region: 0x122, script: 0x57, flags: 0x0}, + 1325: {region: 0xd0, script: 0x57, flags: 0x0}, + 1326: {region: 0x165, script: 0x57, flags: 0x0}, + 1327: {region: 0x161, script: 0x57, flags: 0x0}, + 1329: {region: 0x12b, script: 0x57, flags: 0x0}, } // likelyLangList holds lists info associated with likelyLang. // Size: 388 bytes, 97 elements var likelyLangList = [97]likelyScriptRegion{ 0: {region: 0x9c, script: 0x7, flags: 0x0}, - 1: {region: 0xa1, script: 0x72, flags: 0x2}, - 2: {region: 0x11c, script: 0x7d, flags: 0x2}, - 3: {region: 0x32, script: 0x55, flags: 0x0}, + 1: {region: 0xa1, script: 0x74, flags: 0x2}, + 2: {region: 0x11c, script: 0x80, flags: 0x2}, + 3: {region: 0x32, script: 0x57, flags: 0x0}, 4: {region: 0x9b, script: 0x5, flags: 0x4}, 5: {region: 0x9c, script: 0x5, flags: 0x4}, - 6: {region: 0x106, script: 0x1e, flags: 0x4}, + 6: {region: 0x106, script: 0x1f, flags: 0x4}, 7: {region: 0x9c, script: 0x5, flags: 0x2}, - 8: {region: 0x106, script: 0x1e, flags: 0x0}, - 9: {region: 0x38, script: 0x2b, flags: 0x2}, - 10: {region: 0x135, script: 0x55, flags: 0x0}, - 11: {region: 0x7b, script: 0xc2, flags: 0x2}, - 12: {region: 0x114, script: 0x55, flags: 0x0}, + 8: {region: 0x106, script: 0x1f, flags: 0x0}, + 9: {region: 0x38, script: 0x2c, flags: 0x2}, + 10: {region: 0x135, script: 0x57, flags: 0x0}, + 11: {region: 0x7b, script: 0xc5, flags: 0x2}, + 12: {region: 0x114, script: 0x57, flags: 0x0}, 13: {region: 0x84, script: 0x1, flags: 0x2}, - 14: {region: 0x5d, script: 0x1d, flags: 0x0}, - 15: {region: 0x87, script: 0x5a, flags: 0x2}, - 16: {region: 0xd6, script: 0x55, flags: 0x0}, + 14: {region: 0x5d, script: 0x1e, flags: 0x0}, + 15: {region: 0x87, script: 0x5c, flags: 0x2}, + 16: {region: 0xd6, script: 0x57, flags: 0x0}, 17: {region: 0x52, script: 0x5, flags: 0x4}, 18: {region: 0x10b, script: 0x5, flags: 0x4}, - 19: {region: 0xae, script: 0x1e, flags: 0x0}, + 19: {region: 0xae, script: 0x1f, flags: 0x0}, 20: {region: 0x24, script: 0x5, flags: 0x4}, 21: {region: 0x53, script: 0x5, flags: 0x4}, 22: {region: 0x9c, script: 0x5, flags: 0x4}, 23: {region: 0xc5, script: 0x5, flags: 0x4}, 24: {region: 0x53, script: 0x5, flags: 0x2}, - 25: {region: 0x12b, script: 0x55, flags: 0x0}, + 25: {region: 0x12b, script: 0x57, flags: 0x0}, 26: {region: 0xb0, script: 0x5, flags: 0x4}, 27: {region: 0x9b, script: 0x5, flags: 0x2}, - 28: {region: 0xa5, script: 0x1e, flags: 0x0}, + 28: {region: 0xa5, script: 0x1f, flags: 0x0}, 29: {region: 0x53, script: 0x5, flags: 0x4}, - 30: {region: 0x12b, script: 0x55, flags: 0x4}, + 30: {region: 0x12b, script: 0x57, flags: 0x4}, 31: {region: 0x53, script: 0x5, flags: 0x2}, - 32: {region: 0x12b, script: 0x55, flags: 0x2}, - 33: {region: 0xdb, script: 0x20, flags: 0x0}, - 34: {region: 0x99, script: 0x58, flags: 0x2}, - 35: {region: 0x83, script: 0x55, flags: 0x0}, - 36: {region: 0x84, script: 0x75, flags: 0x4}, - 37: {region: 0x84, script: 0x75, flags: 0x2}, - 38: {region: 0xc5, script: 0x1e, flags: 0x0}, - 39: {region: 0x53, script: 0x6b, flags: 0x4}, - 40: {region: 0x53, script: 0x6b, flags: 0x2}, - 41: {region: 0xd0, script: 0x55, flags: 0x0}, + 32: {region: 0x12b, script: 0x57, flags: 0x2}, + 33: {region: 0xdb, script: 0x21, flags: 0x0}, + 34: {region: 0x99, script: 0x5a, flags: 0x2}, + 35: {region: 0x83, script: 0x57, flags: 0x0}, + 36: {region: 0x84, script: 0x78, flags: 0x4}, + 37: {region: 0x84, script: 0x78, flags: 0x2}, + 38: {region: 0xc5, script: 0x1f, flags: 0x0}, + 39: {region: 0x53, script: 0x6d, flags: 0x4}, + 40: {region: 0x53, script: 0x6d, flags: 0x2}, + 41: {region: 0xd0, script: 0x57, flags: 0x0}, 42: {region: 0x4a, script: 0x5, flags: 0x4}, 43: {region: 0x95, script: 0x5, flags: 0x4}, - 44: {region: 0x99, script: 0x32, flags: 0x0}, + 44: {region: 0x99, script: 0x33, flags: 0x0}, 45: {region: 0xe8, script: 0x5, flags: 0x4}, 46: {region: 0xe8, script: 0x5, flags: 0x2}, - 47: {region: 0x9c, script: 0x81, flags: 0x0}, - 48: {region: 0x53, script: 0x82, flags: 0x2}, - 49: {region: 0xba, script: 0xd8, flags: 0x0}, - 50: {region: 0xd9, script: 0x55, flags: 0x4}, + 47: {region: 0x9c, script: 0x84, flags: 0x0}, + 48: {region: 0x53, script: 0x85, flags: 0x2}, + 49: {region: 0xba, script: 0xdc, flags: 0x0}, + 50: {region: 0xd9, script: 0x57, flags: 0x4}, 51: {region: 0xe8, script: 0x5, flags: 0x0}, - 52: {region: 0x99, script: 0x20, flags: 0x2}, - 53: {region: 0x99, script: 0x4a, flags: 0x2}, - 54: {region: 0x99, script: 0xc5, flags: 0x2}, - 55: {region: 0x105, script: 0x1e, flags: 0x0}, - 56: {region: 0xbd, script: 0x55, flags: 0x4}, - 57: {region: 0x104, script: 0x55, flags: 0x4}, - 58: {region: 0x106, script: 0x55, flags: 0x4}, - 59: {region: 0x12b, script: 0x55, flags: 0x4}, - 60: {region: 0x124, script: 0x1e, flags: 0x0}, + 52: {region: 0x99, script: 0x21, flags: 0x2}, + 53: {region: 0x99, script: 0x4c, flags: 0x2}, + 54: {region: 0x99, script: 0xc9, flags: 0x2}, + 55: {region: 0x105, script: 0x1f, flags: 0x0}, + 56: {region: 0xbd, script: 0x57, flags: 0x4}, + 57: {region: 0x104, script: 0x57, flags: 0x4}, + 58: {region: 0x106, script: 0x57, flags: 0x4}, + 59: {region: 0x12b, script: 0x57, flags: 0x4}, + 60: {region: 0x124, script: 0x1f, flags: 0x0}, 61: {region: 0xe8, script: 0x5, flags: 0x4}, 62: {region: 0xe8, script: 0x5, flags: 0x2}, 63: {region: 0x53, script: 0x5, flags: 0x0}, - 64: {region: 0xae, script: 0x1e, flags: 0x4}, - 65: {region: 0xc5, script: 0x1e, flags: 0x4}, - 66: {region: 0xae, script: 0x1e, flags: 0x2}, + 64: {region: 0xae, script: 0x1f, flags: 0x4}, + 65: {region: 0xc5, script: 0x1f, flags: 0x4}, + 66: {region: 0xae, script: 0x1f, flags: 0x2}, 67: {region: 0x99, script: 0xe, flags: 0x0}, - 68: {region: 0xdb, script: 0x20, flags: 0x4}, - 69: {region: 0xdb, script: 0x20, flags: 0x2}, - 70: {region: 0x137, script: 0x55, flags: 0x0}, + 68: {region: 0xdb, script: 0x21, flags: 0x4}, + 69: {region: 0xdb, script: 0x21, flags: 0x2}, + 70: {region: 0x137, script: 0x57, flags: 0x0}, 71: {region: 0x24, script: 0x5, flags: 0x4}, - 72: {region: 0x53, script: 0x1e, flags: 0x4}, + 72: {region: 0x53, script: 0x1f, flags: 0x4}, 73: {region: 0x24, script: 0x5, flags: 0x2}, - 74: {region: 0x8d, script: 0x38, flags: 0x0}, - 75: {region: 0x53, script: 0x37, flags: 0x4}, - 76: {region: 0x53, script: 0x37, flags: 0x2}, - 77: {region: 0x53, script: 0x37, flags: 0x0}, - 78: {region: 0x2f, script: 0x38, flags: 0x4}, - 79: {region: 0x3e, script: 0x38, flags: 0x4}, - 80: {region: 0x7b, script: 0x38, flags: 0x4}, - 81: {region: 0x7e, script: 0x38, flags: 0x4}, - 82: {region: 0x8d, script: 0x38, flags: 0x4}, - 83: {region: 0x95, script: 0x38, flags: 0x4}, - 84: {region: 0xc6, script: 0x38, flags: 0x4}, - 85: {region: 0xd0, script: 0x38, flags: 0x4}, - 86: {region: 0xe2, script: 0x38, flags: 0x4}, - 87: {region: 0xe5, script: 0x38, flags: 0x4}, - 88: {region: 0xe7, script: 0x38, flags: 0x4}, - 89: {region: 0x116, script: 0x38, flags: 0x4}, - 90: {region: 0x123, script: 0x38, flags: 0x4}, - 91: {region: 0x12e, script: 0x38, flags: 0x4}, - 92: {region: 0x135, script: 0x38, flags: 0x4}, - 93: {region: 0x13e, script: 0x38, flags: 0x4}, + 74: {region: 0x8d, script: 0x39, flags: 0x0}, + 75: {region: 0x53, script: 0x38, flags: 0x4}, + 76: {region: 0x53, script: 0x38, flags: 0x2}, + 77: {region: 0x53, script: 0x38, flags: 0x0}, + 78: {region: 0x2f, script: 0x39, flags: 0x4}, + 79: {region: 0x3e, script: 0x39, flags: 0x4}, + 80: {region: 0x7b, script: 0x39, flags: 0x4}, + 81: {region: 0x7e, script: 0x39, flags: 0x4}, + 82: {region: 0x8d, script: 0x39, flags: 0x4}, + 83: {region: 0x95, script: 0x39, flags: 0x4}, + 84: {region: 0xc6, script: 0x39, flags: 0x4}, + 85: {region: 0xd0, script: 0x39, flags: 0x4}, + 86: {region: 0xe2, script: 0x39, flags: 0x4}, + 87: {region: 0xe5, script: 0x39, flags: 0x4}, + 88: {region: 0xe7, script: 0x39, flags: 0x4}, + 89: {region: 0x116, script: 0x39, flags: 0x4}, + 90: {region: 0x123, script: 0x39, flags: 0x4}, + 91: {region: 0x12e, script: 0x39, flags: 0x4}, + 92: {region: 0x135, script: 0x39, flags: 0x4}, + 93: {region: 0x13e, script: 0x39, flags: 0x4}, 94: {region: 0x12e, script: 0x11, flags: 0x2}, - 95: {region: 0x12e, script: 0x33, flags: 0x2}, - 96: {region: 0x12e, script: 0x38, flags: 0x2}, + 95: {region: 0x12e, script: 0x34, flags: 0x2}, + 96: {region: 0x12e, script: 0x39, flags: 0x2}, } type likelyLangScript struct { @@ -2937,306 +2948,305 @@ type likelyLangScript struct { // TODO: exclude containers and user-definable regions from the list. // Size: 1432 bytes, 358 elements var likelyRegion = [358]likelyLangScript{ - 34: {lang: 0xd7, script: 0x55, flags: 0x0}, + 34: {lang: 0xd7, script: 0x57, flags: 0x0}, 35: {lang: 0x3a, script: 0x5, flags: 0x0}, 36: {lang: 0x0, script: 0x2, flags: 0x1}, 39: {lang: 0x2, script: 0x2, flags: 0x1}, 40: {lang: 0x4, script: 0x2, flags: 0x1}, - 42: {lang: 0x3be, script: 0x55, flags: 0x0}, - 43: {lang: 0x0, script: 0x55, flags: 0x0}, - 44: {lang: 0x13d, script: 0x55, flags: 0x0}, - 45: {lang: 0x419, script: 0x55, flags: 0x0}, - 46: {lang: 0x10c, script: 0x55, flags: 0x0}, - 48: {lang: 0x365, script: 0x55, flags: 0x0}, - 49: {lang: 0x442, script: 0x55, flags: 0x0}, - 50: {lang: 0x58, script: 0x55, flags: 0x0}, + 42: {lang: 0x3c0, script: 0x57, flags: 0x0}, + 43: {lang: 0x0, script: 0x57, flags: 0x0}, + 44: {lang: 0x13e, script: 0x57, flags: 0x0}, + 45: {lang: 0x41b, script: 0x57, flags: 0x0}, + 46: {lang: 0x10d, script: 0x57, flags: 0x0}, + 48: {lang: 0x367, script: 0x57, flags: 0x0}, + 49: {lang: 0x444, script: 0x57, flags: 0x0}, + 50: {lang: 0x58, script: 0x57, flags: 0x0}, 51: {lang: 0x6, script: 0x2, flags: 0x1}, 53: {lang: 0xa5, script: 0xe, flags: 0x0}, - 54: {lang: 0x365, script: 0x55, flags: 0x0}, - 55: {lang: 0x15d, script: 0x55, flags: 0x0}, - 56: {lang: 0x7e, script: 0x1e, flags: 0x0}, + 54: {lang: 0x367, script: 0x57, flags: 0x0}, + 55: {lang: 0x15e, script: 0x57, flags: 0x0}, + 56: {lang: 0x7e, script: 0x1f, flags: 0x0}, 57: {lang: 0x3a, script: 0x5, flags: 0x0}, - 58: {lang: 0x3d7, script: 0x55, flags: 0x0}, - 59: {lang: 0x15d, script: 0x55, flags: 0x0}, - 60: {lang: 0x15d, script: 0x55, flags: 0x0}, - 62: {lang: 0x31d, script: 0x55, flags: 0x0}, - 63: {lang: 0x13d, script: 0x55, flags: 0x0}, - 64: {lang: 0x39f, script: 0x55, flags: 0x0}, - 65: {lang: 0x3be, script: 0x55, flags: 0x0}, + 58: {lang: 0x3d9, script: 0x57, flags: 0x0}, + 59: {lang: 0x15e, script: 0x57, flags: 0x0}, + 60: {lang: 0x15e, script: 0x57, flags: 0x0}, + 62: {lang: 0x31f, script: 0x57, flags: 0x0}, + 63: {lang: 0x13e, script: 0x57, flags: 0x0}, + 64: {lang: 0x3a1, script: 0x57, flags: 0x0}, + 65: {lang: 0x3c0, script: 0x57, flags: 0x0}, 67: {lang: 0x8, script: 0x2, flags: 0x1}, - 69: {lang: 0x0, script: 0x55, flags: 0x0}, - 71: {lang: 0x71, script: 0x1e, flags: 0x0}, - 73: {lang: 0x510, script: 0x3a, flags: 0x2}, - 74: {lang: 0x31d, script: 0x5, flags: 0x2}, - 75: {lang: 0x443, script: 0x55, flags: 0x0}, - 76: {lang: 0x15d, script: 0x55, flags: 0x0}, - 77: {lang: 0x15d, script: 0x55, flags: 0x0}, - 78: {lang: 0x10c, script: 0x55, flags: 0x0}, - 79: {lang: 0x15d, script: 0x55, flags: 0x0}, - 81: {lang: 0x13d, script: 0x55, flags: 0x0}, - 82: {lang: 0x15d, script: 0x55, flags: 0x0}, - 83: {lang: 0xa, script: 0x5, flags: 0x1}, - 84: {lang: 0x13d, script: 0x55, flags: 0x0}, - 85: {lang: 0x0, script: 0x55, flags: 0x0}, - 86: {lang: 0x13d, script: 0x55, flags: 0x0}, - 89: {lang: 0x13d, script: 0x55, flags: 0x0}, - 90: {lang: 0x3be, script: 0x55, flags: 0x0}, - 91: {lang: 0x39f, script: 0x55, flags: 0x0}, - 93: {lang: 0xf, script: 0x2, flags: 0x1}, - 94: {lang: 0xf9, script: 0x55, flags: 0x0}, - 96: {lang: 0x10c, script: 0x55, flags: 0x0}, - 98: {lang: 0x1, script: 0x55, flags: 0x0}, - 99: {lang: 0x100, script: 0x55, flags: 0x0}, - 101: {lang: 0x13d, script: 0x55, flags: 0x0}, - 103: {lang: 0x11, script: 0x2, flags: 0x1}, - 104: {lang: 0x13d, script: 0x55, flags: 0x0}, - 105: {lang: 0x13d, script: 0x55, flags: 0x0}, - 106: {lang: 0x13f, script: 0x55, flags: 0x0}, + 69: {lang: 0x0, script: 0x57, flags: 0x0}, + 71: {lang: 0x71, script: 0x1f, flags: 0x0}, + 73: {lang: 0x512, script: 0x3b, flags: 0x2}, + 74: {lang: 0x31f, script: 0x5, flags: 0x2}, + 75: {lang: 0x445, script: 0x57, flags: 0x0}, + 76: {lang: 0x15e, script: 0x57, flags: 0x0}, + 77: {lang: 0x15e, script: 0x57, flags: 0x0}, + 78: {lang: 0x10d, script: 0x57, flags: 0x0}, + 79: {lang: 0x15e, script: 0x57, flags: 0x0}, + 81: {lang: 0x13e, script: 0x57, flags: 0x0}, + 82: {lang: 0x15e, script: 0x57, flags: 0x0}, + 83: {lang: 0xa, script: 0x4, flags: 0x1}, + 84: {lang: 0x13e, script: 0x57, flags: 0x0}, + 85: {lang: 0x0, script: 0x57, flags: 0x0}, + 86: {lang: 0x13e, script: 0x57, flags: 0x0}, + 89: {lang: 0x13e, script: 0x57, flags: 0x0}, + 90: {lang: 0x3c0, script: 0x57, flags: 0x0}, + 91: {lang: 0x3a1, script: 0x57, flags: 0x0}, + 93: {lang: 0xe, script: 0x2, flags: 0x1}, + 94: {lang: 0xfa, script: 0x57, flags: 0x0}, + 96: {lang: 0x10d, script: 0x57, flags: 0x0}, + 98: {lang: 0x1, script: 0x57, flags: 0x0}, + 99: {lang: 0x101, script: 0x57, flags: 0x0}, + 101: {lang: 0x13e, script: 0x57, flags: 0x0}, + 103: {lang: 0x10, script: 0x2, flags: 0x1}, + 104: {lang: 0x13e, script: 0x57, flags: 0x0}, + 105: {lang: 0x13e, script: 0x57, flags: 0x0}, + 106: {lang: 0x140, script: 0x57, flags: 0x0}, 107: {lang: 0x3a, script: 0x5, flags: 0x0}, 108: {lang: 0x3a, script: 0x5, flags: 0x0}, - 109: {lang: 0x46d, script: 0x28, flags: 0x0}, - 110: {lang: 0x13d, script: 0x55, flags: 0x0}, - 111: {lang: 0x13, script: 0x2, flags: 0x1}, - 113: {lang: 0x10c, script: 0x55, flags: 0x0}, - 114: {lang: 0x150, script: 0x55, flags: 0x0}, - 115: {lang: 0x1be, script: 0x20, flags: 0x2}, - 118: {lang: 0x157, script: 0x55, flags: 0x0}, - 120: {lang: 0x15d, script: 0x55, flags: 0x0}, - 122: {lang: 0x15d, script: 0x55, flags: 0x0}, - 123: {lang: 0x15, script: 0x2, flags: 0x1}, - 125: {lang: 0x17, script: 0x3, flags: 0x1}, - 126: {lang: 0x15d, script: 0x55, flags: 0x0}, - 128: {lang: 0x21, script: 0x55, flags: 0x0}, - 130: {lang: 0x243, script: 0x55, flags: 0x0}, - 132: {lang: 0x15d, script: 0x55, flags: 0x0}, - 133: {lang: 0x15d, script: 0x55, flags: 0x0}, - 134: {lang: 0x13d, script: 0x55, flags: 0x0}, - 135: {lang: 0x1a, script: 0x2, flags: 0x1}, - 136: {lang: 0x0, script: 0x55, flags: 0x0}, - 137: {lang: 0x13d, script: 0x55, flags: 0x0}, - 139: {lang: 0x3be, script: 0x55, flags: 0x0}, - 141: {lang: 0x527, script: 0x38, flags: 0x0}, - 142: {lang: 0x0, script: 0x55, flags: 0x0}, - 143: {lang: 0x13d, script: 0x55, flags: 0x0}, - 144: {lang: 0x1cf, script: 0x55, flags: 0x0}, - 145: {lang: 0x1d2, script: 0x55, flags: 0x0}, - 146: {lang: 0x1d3, script: 0x55, flags: 0x0}, - 148: {lang: 0x13d, script: 0x55, flags: 0x0}, - 149: {lang: 0x1c, script: 0x2, flags: 0x1}, - 151: {lang: 0x1ba, script: 0x3a, flags: 0x0}, - 153: {lang: 0x1e, script: 0x3, flags: 0x1}, + 109: {lang: 0x46f, script: 0x29, flags: 0x0}, + 110: {lang: 0x13e, script: 0x57, flags: 0x0}, + 111: {lang: 0x12, script: 0x2, flags: 0x1}, + 113: {lang: 0x10d, script: 0x57, flags: 0x0}, + 114: {lang: 0x151, script: 0x57, flags: 0x0}, + 115: {lang: 0x1c0, script: 0x21, flags: 0x2}, + 118: {lang: 0x158, script: 0x57, flags: 0x0}, + 120: {lang: 0x15e, script: 0x57, flags: 0x0}, + 122: {lang: 0x15e, script: 0x57, flags: 0x0}, + 123: {lang: 0x14, script: 0x2, flags: 0x1}, + 125: {lang: 0x16, script: 0x3, flags: 0x1}, + 126: {lang: 0x15e, script: 0x57, flags: 0x0}, + 128: {lang: 0x21, script: 0x57, flags: 0x0}, + 130: {lang: 0x245, script: 0x57, flags: 0x0}, + 132: {lang: 0x15e, script: 0x57, flags: 0x0}, + 133: {lang: 0x15e, script: 0x57, flags: 0x0}, + 134: {lang: 0x13e, script: 0x57, flags: 0x0}, + 135: {lang: 0x19, script: 0x2, flags: 0x1}, + 136: {lang: 0x0, script: 0x57, flags: 0x0}, + 137: {lang: 0x13e, script: 0x57, flags: 0x0}, + 139: {lang: 0x3c0, script: 0x57, flags: 0x0}, + 141: {lang: 0x529, script: 0x39, flags: 0x0}, + 142: {lang: 0x0, script: 0x57, flags: 0x0}, + 143: {lang: 0x13e, script: 0x57, flags: 0x0}, + 144: {lang: 0x1d1, script: 0x57, flags: 0x0}, + 145: {lang: 0x1d4, script: 0x57, flags: 0x0}, + 146: {lang: 0x1d5, script: 0x57, flags: 0x0}, + 148: {lang: 0x13e, script: 0x57, flags: 0x0}, + 149: {lang: 0x1b, script: 0x2, flags: 0x1}, + 151: {lang: 0x1bc, script: 0x3b, flags: 0x0}, + 153: {lang: 0x1d, script: 0x3, flags: 0x1}, 155: {lang: 0x3a, script: 0x5, flags: 0x0}, - 156: {lang: 0x21, script: 0x2, flags: 0x1}, - 157: {lang: 0x1f6, script: 0x55, flags: 0x0}, - 158: {lang: 0x1f7, script: 0x55, flags: 0x0}, + 156: {lang: 0x20, script: 0x2, flags: 0x1}, + 157: {lang: 0x1f8, script: 0x57, flags: 0x0}, + 158: {lang: 0x1f9, script: 0x57, flags: 0x0}, 161: {lang: 0x3a, script: 0x5, flags: 0x0}, - 162: {lang: 0x1fe, script: 0x44, flags: 0x0}, - 164: {lang: 0x443, script: 0x55, flags: 0x0}, - 165: {lang: 0x288, script: 0x1e, flags: 0x0}, - 166: {lang: 0x23, script: 0x3, flags: 0x1}, - 168: {lang: 0x26, script: 0x2, flags: 0x1}, - 170: {lang: 0x252, script: 0x4e, flags: 0x0}, - 171: {lang: 0x252, script: 0x4e, flags: 0x0}, + 162: {lang: 0x200, script: 0x46, flags: 0x0}, + 164: {lang: 0x445, script: 0x57, flags: 0x0}, + 165: {lang: 0x28a, script: 0x1f, flags: 0x0}, + 166: {lang: 0x22, script: 0x3, flags: 0x1}, + 168: {lang: 0x25, script: 0x2, flags: 0x1}, + 170: {lang: 0x254, script: 0x50, flags: 0x0}, + 171: {lang: 0x254, script: 0x50, flags: 0x0}, 172: {lang: 0x3a, script: 0x5, flags: 0x0}, - 174: {lang: 0x3e0, script: 0x1e, flags: 0x0}, - 175: {lang: 0x28, script: 0x2, flags: 0x1}, + 174: {lang: 0x3e2, script: 0x1f, flags: 0x0}, + 175: {lang: 0x27, script: 0x2, flags: 0x1}, 176: {lang: 0x3a, script: 0x5, flags: 0x0}, - 178: {lang: 0x10c, script: 0x55, flags: 0x0}, - 179: {lang: 0x40a, script: 0xc6, flags: 0x0}, - 181: {lang: 0x439, script: 0x55, flags: 0x0}, - 182: {lang: 0x2be, script: 0x55, flags: 0x0}, - 183: {lang: 0x15d, script: 0x55, flags: 0x0}, - 184: {lang: 0x2c5, script: 0x55, flags: 0x0}, + 178: {lang: 0x10d, script: 0x57, flags: 0x0}, + 179: {lang: 0x40c, script: 0xca, flags: 0x0}, + 181: {lang: 0x43b, script: 0x57, flags: 0x0}, + 182: {lang: 0x2c0, script: 0x57, flags: 0x0}, + 183: {lang: 0x15e, script: 0x57, flags: 0x0}, + 184: {lang: 0x2c7, script: 0x57, flags: 0x0}, 185: {lang: 0x3a, script: 0x5, flags: 0x0}, - 186: {lang: 0x2a, script: 0x2, flags: 0x1}, - 187: {lang: 0x15d, script: 0x55, flags: 0x0}, - 188: {lang: 0x2c, script: 0x2, flags: 0x1}, - 189: {lang: 0x430, script: 0x55, flags: 0x0}, - 190: {lang: 0x15d, script: 0x55, flags: 0x0}, - 191: {lang: 0x2ef, script: 0x55, flags: 0x0}, - 194: {lang: 0x2e, script: 0x2, flags: 0x1}, - 195: {lang: 0xa0, script: 0x55, flags: 0x0}, - 196: {lang: 0x30, script: 0x2, flags: 0x1}, - 197: {lang: 0x32, script: 0x2, flags: 0x1}, - 198: {lang: 0x34, script: 0x2, flags: 0x1}, - 200: {lang: 0x15d, script: 0x55, flags: 0x0}, - 201: {lang: 0x36, script: 0x2, flags: 0x1}, - 203: {lang: 0x31e, script: 0x55, flags: 0x0}, - 204: {lang: 0x38, script: 0x3, flags: 0x1}, - 205: {lang: 0x127, script: 0xda, flags: 0x0}, - 207: {lang: 0x13d, script: 0x55, flags: 0x0}, - 208: {lang: 0x31d, script: 0x55, flags: 0x0}, - 209: {lang: 0x3be, script: 0x55, flags: 0x0}, - 210: {lang: 0x16, script: 0x55, flags: 0x0}, - 211: {lang: 0x15d, script: 0x55, flags: 0x0}, - 212: {lang: 0x1b2, script: 0x55, flags: 0x0}, - 214: {lang: 0x1b2, script: 0x5, flags: 0x2}, - 216: {lang: 0x13d, script: 0x55, flags: 0x0}, - 217: {lang: 0x365, script: 0x55, flags: 0x0}, - 218: {lang: 0x345, script: 0x55, flags: 0x0}, - 219: {lang: 0x34f, script: 0x20, flags: 0x0}, + 186: {lang: 0x29, script: 0x2, flags: 0x1}, + 187: {lang: 0x15e, script: 0x57, flags: 0x0}, + 188: {lang: 0x2b, script: 0x2, flags: 0x1}, + 189: {lang: 0x432, script: 0x57, flags: 0x0}, + 190: {lang: 0x15e, script: 0x57, flags: 0x0}, + 191: {lang: 0x2f1, script: 0x57, flags: 0x0}, + 194: {lang: 0x2d, script: 0x2, flags: 0x1}, + 195: {lang: 0xa0, script: 0x57, flags: 0x0}, + 196: {lang: 0x2f, script: 0x2, flags: 0x1}, + 197: {lang: 0x31, script: 0x2, flags: 0x1}, + 198: {lang: 0x33, script: 0x2, flags: 0x1}, + 200: {lang: 0x15e, script: 0x57, flags: 0x0}, + 201: {lang: 0x35, script: 0x2, flags: 0x1}, + 203: {lang: 0x320, script: 0x57, flags: 0x0}, + 204: {lang: 0x37, script: 0x3, flags: 0x1}, + 205: {lang: 0x128, script: 0xde, flags: 0x0}, + 207: {lang: 0x13e, script: 0x57, flags: 0x0}, + 208: {lang: 0x31f, script: 0x57, flags: 0x0}, + 209: {lang: 0x3c0, script: 0x57, flags: 0x0}, + 210: {lang: 0x16, script: 0x57, flags: 0x0}, + 211: {lang: 0x15e, script: 0x57, flags: 0x0}, + 212: {lang: 0x1b4, script: 0x57, flags: 0x0}, + 214: {lang: 0x1b4, script: 0x5, flags: 0x2}, + 216: {lang: 0x13e, script: 0x57, flags: 0x0}, + 217: {lang: 0x367, script: 0x57, flags: 0x0}, + 218: {lang: 0x347, script: 0x57, flags: 0x0}, + 219: {lang: 0x351, script: 0x21, flags: 0x0}, 225: {lang: 0x3a, script: 0x5, flags: 0x0}, - 226: {lang: 0x13d, script: 0x55, flags: 0x0}, - 228: {lang: 0x13d, script: 0x55, flags: 0x0}, - 229: {lang: 0x15d, script: 0x55, flags: 0x0}, - 230: {lang: 0x484, script: 0x55, flags: 0x0}, - 231: {lang: 0x152, script: 0x55, flags: 0x0}, - 232: {lang: 0x3b, script: 0x3, flags: 0x1}, - 233: {lang: 0x3b1, script: 0x55, flags: 0x0}, - 234: {lang: 0x15d, script: 0x55, flags: 0x0}, - 236: {lang: 0x13d, script: 0x55, flags: 0x0}, + 226: {lang: 0x13e, script: 0x57, flags: 0x0}, + 228: {lang: 0x13e, script: 0x57, flags: 0x0}, + 229: {lang: 0x15e, script: 0x57, flags: 0x0}, + 230: {lang: 0x486, script: 0x57, flags: 0x0}, + 231: {lang: 0x153, script: 0x57, flags: 0x0}, + 232: {lang: 0x3a, script: 0x3, flags: 0x1}, + 233: {lang: 0x3b3, script: 0x57, flags: 0x0}, + 234: {lang: 0x15e, script: 0x57, flags: 0x0}, + 236: {lang: 0x13e, script: 0x57, flags: 0x0}, 237: {lang: 0x3a, script: 0x5, flags: 0x0}, - 238: {lang: 0x3be, script: 0x55, flags: 0x0}, - 240: {lang: 0x3a0, script: 0x55, flags: 0x0}, - 241: {lang: 0x192, script: 0x55, flags: 0x0}, + 238: {lang: 0x3c0, script: 0x57, flags: 0x0}, + 240: {lang: 0x3a2, script: 0x57, flags: 0x0}, + 241: {lang: 0x194, script: 0x57, flags: 0x0}, 243: {lang: 0x3a, script: 0x5, flags: 0x0}, - 258: {lang: 0x15d, script: 0x55, flags: 0x0}, - 260: {lang: 0x3e, script: 0x2, flags: 0x1}, - 261: {lang: 0x430, script: 0x1e, flags: 0x0}, - 262: {lang: 0x40, script: 0x2, flags: 0x1}, - 263: {lang: 0x3e3, script: 0x55, flags: 0x0}, + 258: {lang: 0x15e, script: 0x57, flags: 0x0}, + 260: {lang: 0x3d, script: 0x2, flags: 0x1}, + 261: {lang: 0x432, script: 0x1f, flags: 0x0}, + 262: {lang: 0x3f, script: 0x2, flags: 0x1}, + 263: {lang: 0x3e5, script: 0x57, flags: 0x0}, 264: {lang: 0x3a, script: 0x5, flags: 0x0}, - 266: {lang: 0x15d, script: 0x55, flags: 0x0}, + 266: {lang: 0x15e, script: 0x57, flags: 0x0}, 267: {lang: 0x3a, script: 0x5, flags: 0x0}, - 268: {lang: 0x42, script: 0x2, flags: 0x1}, - 271: {lang: 0x414, script: 0x55, flags: 0x0}, - 272: {lang: 0x345, script: 0x55, flags: 0x0}, - 273: {lang: 0x44, script: 0x2, flags: 0x1}, - 275: {lang: 0x1f7, script: 0x55, flags: 0x0}, - 276: {lang: 0x15d, script: 0x55, flags: 0x0}, - 277: {lang: 0x427, script: 0x55, flags: 0x0}, - 278: {lang: 0x365, script: 0x55, flags: 0x0}, - 280: {lang: 0x3be, script: 0x55, flags: 0x0}, - 282: {lang: 0x13d, script: 0x55, flags: 0x0}, - 284: {lang: 0x46, script: 0x2, flags: 0x1}, - 288: {lang: 0x15d, script: 0x55, flags: 0x0}, - 289: {lang: 0x15d, script: 0x55, flags: 0x0}, - 290: {lang: 0x48, script: 0x2, flags: 0x1}, - 291: {lang: 0x4a, script: 0x3, flags: 0x1}, - 292: {lang: 0x4d, script: 0x2, flags: 0x1}, - 293: {lang: 0x475, script: 0x55, flags: 0x0}, - 294: {lang: 0x3be, script: 0x55, flags: 0x0}, - 295: {lang: 0x474, script: 0x55, flags: 0x0}, - 296: {lang: 0x4f, script: 0x2, flags: 0x1}, - 297: {lang: 0x480, script: 0x55, flags: 0x0}, - 299: {lang: 0x51, script: 0x4, flags: 0x1}, - 301: {lang: 0x49e, script: 0x55, flags: 0x0}, - 302: {lang: 0x55, script: 0x2, flags: 0x1}, - 303: {lang: 0x443, script: 0x55, flags: 0x0}, - 304: {lang: 0x57, script: 0x3, flags: 0x1}, - 305: {lang: 0x443, script: 0x55, flags: 0x0}, - 309: {lang: 0x510, script: 0x3a, flags: 0x2}, - 310: {lang: 0x13d, script: 0x55, flags: 0x0}, - 311: {lang: 0x4ba, script: 0x55, flags: 0x0}, - 312: {lang: 0x1f7, script: 0x55, flags: 0x0}, - 315: {lang: 0x13d, script: 0x55, flags: 0x0}, - 318: {lang: 0x4c1, script: 0x55, flags: 0x0}, - 319: {lang: 0x8a, script: 0x55, flags: 0x0}, - 320: {lang: 0x15d, script: 0x55, flags: 0x0}, - 322: {lang: 0x419, script: 0x55, flags: 0x0}, - 333: {lang: 0x5a, script: 0x2, flags: 0x1}, + 268: {lang: 0x41, script: 0x2, flags: 0x1}, + 271: {lang: 0x416, script: 0x57, flags: 0x0}, + 272: {lang: 0x347, script: 0x57, flags: 0x0}, + 273: {lang: 0x43, script: 0x2, flags: 0x1}, + 275: {lang: 0x1f9, script: 0x57, flags: 0x0}, + 276: {lang: 0x15e, script: 0x57, flags: 0x0}, + 277: {lang: 0x429, script: 0x57, flags: 0x0}, + 278: {lang: 0x367, script: 0x57, flags: 0x0}, + 280: {lang: 0x3c0, script: 0x57, flags: 0x0}, + 282: {lang: 0x13e, script: 0x57, flags: 0x0}, + 284: {lang: 0x45, script: 0x2, flags: 0x1}, + 288: {lang: 0x15e, script: 0x57, flags: 0x0}, + 289: {lang: 0x15e, script: 0x57, flags: 0x0}, + 290: {lang: 0x47, script: 0x2, flags: 0x1}, + 291: {lang: 0x49, script: 0x3, flags: 0x1}, + 292: {lang: 0x4c, script: 0x2, flags: 0x1}, + 293: {lang: 0x477, script: 0x57, flags: 0x0}, + 294: {lang: 0x3c0, script: 0x57, flags: 0x0}, + 295: {lang: 0x476, script: 0x57, flags: 0x0}, + 296: {lang: 0x4e, script: 0x2, flags: 0x1}, + 297: {lang: 0x482, script: 0x57, flags: 0x0}, + 299: {lang: 0x50, script: 0x4, flags: 0x1}, + 301: {lang: 0x4a0, script: 0x57, flags: 0x0}, + 302: {lang: 0x54, script: 0x2, flags: 0x1}, + 303: {lang: 0x445, script: 0x57, flags: 0x0}, + 304: {lang: 0x56, script: 0x3, flags: 0x1}, + 305: {lang: 0x445, script: 0x57, flags: 0x0}, + 309: {lang: 0x512, script: 0x3b, flags: 0x2}, + 310: {lang: 0x13e, script: 0x57, flags: 0x0}, + 311: {lang: 0x4bc, script: 0x57, flags: 0x0}, + 312: {lang: 0x1f9, script: 0x57, flags: 0x0}, + 315: {lang: 0x13e, script: 0x57, flags: 0x0}, + 318: {lang: 0x4c3, script: 0x57, flags: 0x0}, + 319: {lang: 0x8a, script: 0x57, flags: 0x0}, + 320: {lang: 0x15e, script: 0x57, flags: 0x0}, + 322: {lang: 0x41b, script: 0x57, flags: 0x0}, + 333: {lang: 0x59, script: 0x2, flags: 0x1}, 350: {lang: 0x3a, script: 0x5, flags: 0x0}, - 351: {lang: 0x5c, script: 0x2, flags: 0x1}, - 356: {lang: 0x421, script: 0x55, flags: 0x0}, + 351: {lang: 0x5b, script: 0x2, flags: 0x1}, + 356: {lang: 0x423, script: 0x57, flags: 0x0}, } // likelyRegionList holds lists info associated with likelyRegion. -// Size: 376 bytes, 94 elements -var likelyRegionList = [94]likelyLangScript{ - 0: {lang: 0x147, script: 0x5, flags: 0x0}, - 1: {lang: 0x474, script: 0x55, flags: 0x0}, - 2: {lang: 0x42f, script: 0x55, flags: 0x0}, - 3: {lang: 0x2fd, script: 0x1e, flags: 0x0}, - 4: {lang: 0x1d5, script: 0x8, flags: 0x0}, - 5: {lang: 0x272, script: 0x55, flags: 0x0}, - 6: {lang: 0xb7, script: 0x55, flags: 0x0}, - 7: {lang: 0x430, script: 0x1e, flags: 0x0}, - 8: {lang: 0x12c, script: 0xdc, flags: 0x0}, - 9: {lang: 0x34f, script: 0x20, flags: 0x0}, - 10: {lang: 0x527, script: 0x37, flags: 0x0}, - 11: {lang: 0x4aa, script: 0x5, flags: 0x0}, - 12: {lang: 0x51d, script: 0x38, flags: 0x0}, - 13: {lang: 0x521, script: 0x55, flags: 0x0}, - 14: {lang: 0x298, script: 0xdb, flags: 0x0}, - 15: {lang: 0x135, script: 0x30, flags: 0x0}, - 16: {lang: 0x488, script: 0x55, flags: 0x0}, - 17: {lang: 0x3a, script: 0x5, flags: 0x0}, - 18: {lang: 0x15d, script: 0x55, flags: 0x0}, - 19: {lang: 0x27, script: 0x28, flags: 0x0}, - 20: {lang: 0x138, script: 0x55, flags: 0x0}, - 21: {lang: 0x268, script: 0x5, flags: 0x2}, - 22: {lang: 0x510, script: 0x3a, flags: 0x2}, - 23: {lang: 0x20e, script: 0x2a, flags: 0x0}, - 24: {lang: 0x5, script: 0x1e, flags: 0x0}, - 25: {lang: 0x272, script: 0x55, flags: 0x0}, - 26: {lang: 0x135, script: 0x30, flags: 0x0}, - 27: {lang: 0x2fd, script: 0x1e, flags: 0x0}, - 28: {lang: 0x1df, script: 0x55, flags: 0x0}, - 29: {lang: 0x31d, script: 0x5, flags: 0x0}, - 30: {lang: 0x1bc, script: 0x20, flags: 0x0}, - 31: {lang: 0x4b2, script: 0x5, flags: 0x0}, - 32: {lang: 0x234, script: 0x70, flags: 0x0}, - 33: {lang: 0x147, script: 0x5, flags: 0x0}, - 34: {lang: 0x474, script: 0x55, flags: 0x0}, - 35: {lang: 0x248, script: 0x49, flags: 0x0}, - 36: {lang: 0xe6, script: 0x5, flags: 0x0}, - 37: {lang: 0x224, script: 0xdb, flags: 0x0}, - 38: {lang: 0x3a, script: 0x5, flags: 0x0}, - 39: {lang: 0x15d, script: 0x55, flags: 0x0}, - 40: {lang: 0x2b6, script: 0x52, flags: 0x0}, - 41: {lang: 0x224, script: 0xdb, flags: 0x0}, - 42: {lang: 0x3a, script: 0x5, flags: 0x0}, - 43: {lang: 0x15d, script: 0x55, flags: 0x0}, - 44: {lang: 0x3da, script: 0x55, flags: 0x0}, - 45: {lang: 0x4ac, script: 0x1e, flags: 0x0}, - 46: {lang: 0x2fd, script: 0x1e, flags: 0x0}, - 47: {lang: 0x42f, script: 0x55, flags: 0x0}, - 48: {lang: 0x32f, script: 0x70, flags: 0x0}, - 49: {lang: 0x211, script: 0x55, flags: 0x0}, - 50: {lang: 0x309, script: 0x1e, flags: 0x0}, - 51: {lang: 0x240, script: 0x5, flags: 0x0}, - 52: {lang: 0x527, script: 0x38, flags: 0x0}, - 53: {lang: 0x3be, script: 0x55, flags: 0x0}, - 54: {lang: 0x3a, script: 0x5, flags: 0x0}, - 55: {lang: 0x15d, script: 0x55, flags: 0x0}, - 56: {lang: 0x2eb, script: 0x55, flags: 0x0}, - 57: {lang: 0x4b2, script: 0x5, flags: 0x0}, - 58: {lang: 0x88, script: 0x20, flags: 0x0}, - 59: {lang: 0x4b2, script: 0x5, flags: 0x0}, - 60: {lang: 0x4b2, script: 0x5, flags: 0x0}, - 61: {lang: 0xbe, script: 0x20, flags: 0x0}, - 62: {lang: 0x3da, script: 0x55, flags: 0x0}, - 63: {lang: 0x7e, script: 0x1e, flags: 0x0}, - 64: {lang: 0x3e0, script: 0x1e, flags: 0x0}, - 65: {lang: 0x265, script: 0x55, flags: 0x0}, - 66: {lang: 0x442, script: 0x55, flags: 0x0}, - 67: {lang: 0x510, script: 0x3a, flags: 0x0}, - 68: {lang: 0x410, script: 0x55, flags: 0x0}, - 69: {lang: 0x4ac, script: 0x1e, flags: 0x0}, - 70: {lang: 0x3a, script: 0x5, flags: 0x0}, - 71: {lang: 0x15d, script: 0x55, flags: 0x0}, - 72: {lang: 0x15d, script: 0x55, flags: 0x0}, - 73: {lang: 0x35, script: 0x5, flags: 0x0}, - 74: {lang: 0x469, script: 0xdb, flags: 0x0}, - 75: {lang: 0x2ea, script: 0x5, flags: 0x0}, - 76: {lang: 0x30d, script: 0x70, flags: 0x0}, - 77: {lang: 0x465, script: 0x1e, flags: 0x0}, - 78: {lang: 0x147, script: 0x5, flags: 0x0}, - 79: {lang: 0x3a, script: 0x5, flags: 0x0}, - 80: {lang: 0x15d, script: 0x55, flags: 0x0}, - 81: {lang: 0x488, script: 0x55, flags: 0x0}, - 82: {lang: 0x58, script: 0x5, flags: 0x0}, - 83: {lang: 0x217, script: 0x1e, flags: 0x0}, - 84: {lang: 0x81, script: 0x30, flags: 0x0}, - 85: {lang: 0x527, script: 0x38, flags: 0x0}, - 86: {lang: 0x48a, script: 0x55, flags: 0x0}, - 87: {lang: 0x4ac, script: 0x1e, flags: 0x0}, - 88: {lang: 0x510, script: 0x3a, flags: 0x0}, - 89: {lang: 0x3b1, script: 0x55, flags: 0x0}, - 90: {lang: 0x42f, script: 0x55, flags: 0x0}, - 91: {lang: 0x430, script: 0x1e, flags: 0x0}, - 92: {lang: 0x15d, script: 0x55, flags: 0x0}, - 93: {lang: 0x444, script: 0x5, flags: 0x0}, +// Size: 372 bytes, 93 elements +var likelyRegionList = [93]likelyLangScript{ + 0: {lang: 0x148, script: 0x5, flags: 0x0}, + 1: {lang: 0x476, script: 0x57, flags: 0x0}, + 2: {lang: 0x431, script: 0x57, flags: 0x0}, + 3: {lang: 0x2ff, script: 0x1f, flags: 0x0}, + 4: {lang: 0x1d7, script: 0x8, flags: 0x0}, + 5: {lang: 0x274, script: 0x57, flags: 0x0}, + 6: {lang: 0xb7, script: 0x57, flags: 0x0}, + 7: {lang: 0x432, script: 0x1f, flags: 0x0}, + 8: {lang: 0x12d, script: 0xe0, flags: 0x0}, + 9: {lang: 0x351, script: 0x21, flags: 0x0}, + 10: {lang: 0x529, script: 0x38, flags: 0x0}, + 11: {lang: 0x4ac, script: 0x5, flags: 0x0}, + 12: {lang: 0x523, script: 0x57, flags: 0x0}, + 13: {lang: 0x29a, script: 0xdf, flags: 0x0}, + 14: {lang: 0x136, script: 0x31, flags: 0x0}, + 15: {lang: 0x48a, script: 0x57, flags: 0x0}, + 16: {lang: 0x3a, script: 0x5, flags: 0x0}, + 17: {lang: 0x15e, script: 0x57, flags: 0x0}, + 18: {lang: 0x27, script: 0x29, flags: 0x0}, + 19: {lang: 0x139, script: 0x57, flags: 0x0}, + 20: {lang: 0x26a, script: 0x5, flags: 0x2}, + 21: {lang: 0x512, script: 0x3b, flags: 0x2}, + 22: {lang: 0x210, script: 0x2b, flags: 0x0}, + 23: {lang: 0x5, script: 0x1f, flags: 0x0}, + 24: {lang: 0x274, script: 0x57, flags: 0x0}, + 25: {lang: 0x136, script: 0x31, flags: 0x0}, + 26: {lang: 0x2ff, script: 0x1f, flags: 0x0}, + 27: {lang: 0x1e1, script: 0x57, flags: 0x0}, + 28: {lang: 0x31f, script: 0x5, flags: 0x0}, + 29: {lang: 0x1be, script: 0x21, flags: 0x0}, + 30: {lang: 0x4b4, script: 0x5, flags: 0x0}, + 31: {lang: 0x236, script: 0x72, flags: 0x0}, + 32: {lang: 0x148, script: 0x5, flags: 0x0}, + 33: {lang: 0x476, script: 0x57, flags: 0x0}, + 34: {lang: 0x24a, script: 0x4b, flags: 0x0}, + 35: {lang: 0xe6, script: 0x5, flags: 0x0}, + 36: {lang: 0x226, script: 0xdf, flags: 0x0}, + 37: {lang: 0x3a, script: 0x5, flags: 0x0}, + 38: {lang: 0x15e, script: 0x57, flags: 0x0}, + 39: {lang: 0x2b8, script: 0x54, flags: 0x0}, + 40: {lang: 0x226, script: 0xdf, flags: 0x0}, + 41: {lang: 0x3a, script: 0x5, flags: 0x0}, + 42: {lang: 0x15e, script: 0x57, flags: 0x0}, + 43: {lang: 0x3dc, script: 0x57, flags: 0x0}, + 44: {lang: 0x4ae, script: 0x1f, flags: 0x0}, + 45: {lang: 0x2ff, script: 0x1f, flags: 0x0}, + 46: {lang: 0x431, script: 0x57, flags: 0x0}, + 47: {lang: 0x331, script: 0x72, flags: 0x0}, + 48: {lang: 0x213, script: 0x57, flags: 0x0}, + 49: {lang: 0x30b, script: 0x1f, flags: 0x0}, + 50: {lang: 0x242, script: 0x5, flags: 0x0}, + 51: {lang: 0x529, script: 0x39, flags: 0x0}, + 52: {lang: 0x3c0, script: 0x57, flags: 0x0}, + 53: {lang: 0x3a, script: 0x5, flags: 0x0}, + 54: {lang: 0x15e, script: 0x57, flags: 0x0}, + 55: {lang: 0x2ed, script: 0x57, flags: 0x0}, + 56: {lang: 0x4b4, script: 0x5, flags: 0x0}, + 57: {lang: 0x88, script: 0x21, flags: 0x0}, + 58: {lang: 0x4b4, script: 0x5, flags: 0x0}, + 59: {lang: 0x4b4, script: 0x5, flags: 0x0}, + 60: {lang: 0xbe, script: 0x21, flags: 0x0}, + 61: {lang: 0x3dc, script: 0x57, flags: 0x0}, + 62: {lang: 0x7e, script: 0x1f, flags: 0x0}, + 63: {lang: 0x3e2, script: 0x1f, flags: 0x0}, + 64: {lang: 0x267, script: 0x57, flags: 0x0}, + 65: {lang: 0x444, script: 0x57, flags: 0x0}, + 66: {lang: 0x512, script: 0x3b, flags: 0x0}, + 67: {lang: 0x412, script: 0x57, flags: 0x0}, + 68: {lang: 0x4ae, script: 0x1f, flags: 0x0}, + 69: {lang: 0x3a, script: 0x5, flags: 0x0}, + 70: {lang: 0x15e, script: 0x57, flags: 0x0}, + 71: {lang: 0x15e, script: 0x57, flags: 0x0}, + 72: {lang: 0x35, script: 0x5, flags: 0x0}, + 73: {lang: 0x46b, script: 0xdf, flags: 0x0}, + 74: {lang: 0x2ec, script: 0x5, flags: 0x0}, + 75: {lang: 0x30f, script: 0x72, flags: 0x0}, + 76: {lang: 0x467, script: 0x1f, flags: 0x0}, + 77: {lang: 0x148, script: 0x5, flags: 0x0}, + 78: {lang: 0x3a, script: 0x5, flags: 0x0}, + 79: {lang: 0x15e, script: 0x57, flags: 0x0}, + 80: {lang: 0x48a, script: 0x57, flags: 0x0}, + 81: {lang: 0x58, script: 0x5, flags: 0x0}, + 82: {lang: 0x219, script: 0x1f, flags: 0x0}, + 83: {lang: 0x81, script: 0x31, flags: 0x0}, + 84: {lang: 0x529, script: 0x39, flags: 0x0}, + 85: {lang: 0x48c, script: 0x57, flags: 0x0}, + 86: {lang: 0x4ae, script: 0x1f, flags: 0x0}, + 87: {lang: 0x512, script: 0x3b, flags: 0x0}, + 88: {lang: 0x3b3, script: 0x57, flags: 0x0}, + 89: {lang: 0x431, script: 0x57, flags: 0x0}, + 90: {lang: 0x432, script: 0x1f, flags: 0x0}, + 91: {lang: 0x15e, script: 0x57, flags: 0x0}, + 92: {lang: 0x446, script: 0x5, flags: 0x0}, } type likelyTag struct { @@ -3247,37 +3257,38 @@ type likelyTag struct { // Size: 198 bytes, 33 elements var likelyRegionGroup = [33]likelyTag{ - 1: {lang: 0x138, region: 0xd6, script: 0x55}, - 2: {lang: 0x138, region: 0x135, script: 0x55}, - 3: {lang: 0x3be, region: 0x41, script: 0x55}, - 4: {lang: 0x138, region: 0x2f, script: 0x55}, - 5: {lang: 0x138, region: 0xd6, script: 0x55}, - 6: {lang: 0x13d, region: 0xcf, script: 0x55}, - 7: {lang: 0x443, region: 0x12f, script: 0x55}, + 1: {lang: 0x139, region: 0xd6, script: 0x57}, + 2: {lang: 0x139, region: 0x135, script: 0x57}, + 3: {lang: 0x3c0, region: 0x41, script: 0x57}, + 4: {lang: 0x139, region: 0x2f, script: 0x57}, + 5: {lang: 0x139, region: 0xd6, script: 0x57}, + 6: {lang: 0x13e, region: 0xcf, script: 0x57}, + 7: {lang: 0x445, region: 0x12f, script: 0x57}, 8: {lang: 0x3a, region: 0x6b, script: 0x5}, - 9: {lang: 0x443, region: 0x4b, script: 0x55}, - 10: {lang: 0x138, region: 0x161, script: 0x55}, - 11: {lang: 0x138, region: 0x135, script: 0x55}, - 12: {lang: 0x138, region: 0x135, script: 0x55}, - 13: {lang: 0x13d, region: 0x59, script: 0x55}, - 14: {lang: 0x527, region: 0x53, script: 0x37}, - 15: {lang: 0x1bc, region: 0x99, script: 0x20}, - 16: {lang: 0x1df, region: 0x95, script: 0x55}, - 17: {lang: 0x1f7, region: 0x9e, script: 0x55}, - 18: {lang: 0x138, region: 0x2f, script: 0x55}, - 19: {lang: 0x138, region: 0xe6, script: 0x55}, - 20: {lang: 0x138, region: 0x8a, script: 0x55}, - 21: {lang: 0x419, region: 0x142, script: 0x55}, - 22: {lang: 0x527, region: 0x53, script: 0x37}, - 23: {lang: 0x4ba, region: 0x137, script: 0x55}, + 9: {lang: 0x445, region: 0x4b, script: 0x57}, + 10: {lang: 0x139, region: 0x161, script: 0x57}, + 11: {lang: 0x139, region: 0x135, script: 0x57}, + 12: {lang: 0x139, region: 0x135, script: 0x57}, + 13: {lang: 0x13e, region: 0x59, script: 0x57}, + 14: {lang: 0x529, region: 0x53, script: 0x38}, + 15: {lang: 0x1be, region: 0x99, script: 0x21}, + 16: {lang: 0x1e1, region: 0x95, script: 0x57}, + 17: {lang: 0x1f9, region: 0x9e, script: 0x57}, + 18: {lang: 0x139, region: 0x2f, script: 0x57}, + 19: {lang: 0x139, region: 0xe6, script: 0x57}, + 20: {lang: 0x139, region: 0x8a, script: 0x57}, + 21: {lang: 0x41b, region: 0x142, script: 0x57}, + 22: {lang: 0x529, region: 0x53, script: 0x38}, + 23: {lang: 0x4bc, region: 0x137, script: 0x57}, 24: {lang: 0x3a, region: 0x108, script: 0x5}, - 25: {lang: 0x3e0, region: 0x106, script: 0x1e}, - 26: {lang: 0x3e0, region: 0x106, script: 0x1e}, - 27: {lang: 0x138, region: 0x7b, script: 0x55}, - 28: {lang: 0x10c, region: 0x60, script: 0x55}, - 30: {lang: 0x13d, region: 0x1f, script: 0x55}, - 31: {lang: 0x138, region: 0x9a, script: 0x55}, - 32: {lang: 0x138, region: 0x7b, script: 0x55}, + 25: {lang: 0x3e2, region: 0x106, script: 0x1f}, + 26: {lang: 0x3e2, region: 0x106, script: 0x1f}, + 27: {lang: 0x139, region: 0x7b, script: 0x57}, + 28: {lang: 0x10d, region: 0x60, script: 0x57}, + 29: {lang: 0x139, region: 0xd6, script: 0x57}, + 30: {lang: 0x13e, region: 0x1f, script: 0x57}, + 31: {lang: 0x139, region: 0x9a, script: 0x57}, + 32: {lang: 0x139, region: 0x7b, script: 0x57}, } // Size: 358 bytes, 358 elements @@ -3337,9 +3348,9 @@ var regionToGroups = [358]uint8{ // Size: 18 bytes, 3 elements var paradigmLocales = [3][3]uint16{ - 0: [3]uint16{0x138, 0x0, 0x7b}, - 1: [3]uint16{0x13d, 0x0, 0x1f}, - 2: [3]uint16{0x3be, 0x41, 0xee}, + 0: [3]uint16{0x139, 0x0, 0x7b}, + 1: [3]uint16{0x13e, 0x0, 0x1f}, + 2: [3]uint16{0x3c0, 0x41, 0xee}, } type mutualIntelligibility struct { @@ -3369,183 +3380,183 @@ type regionIntelligibility struct { // whether the intelligibility goes one or both ways. // Size: 678 bytes, 113 elements var matchLang = [113]mutualIntelligibility{ - 0: {want: 0x1cf, have: 0xb7, distance: 0x4, oneway: false}, - 1: {want: 0x405, have: 0xb7, distance: 0x4, oneway: false}, - 2: {want: 0x405, have: 0x1cf, distance: 0x4, oneway: false}, - 3: {want: 0x405, have: 0x430, distance: 0x4, oneway: false}, - 4: {want: 0x438, have: 0x1, distance: 0x4, oneway: false}, - 5: {want: 0x1a1, have: 0x10c, distance: 0x4, oneway: true}, - 6: {want: 0x293, have: 0x10c, distance: 0x4, oneway: true}, - 7: {want: 0x100, have: 0x36d, distance: 0x8, oneway: false}, - 8: {want: 0x100, have: 0x345, distance: 0x8, oneway: false}, - 9: {want: 0x5, have: 0x3e0, distance: 0xa, oneway: true}, - 10: {want: 0xd, have: 0x138, distance: 0xa, oneway: true}, - 11: {want: 0x16, have: 0x365, distance: 0xa, oneway: true}, - 12: {want: 0x21, have: 0x138, distance: 0xa, oneway: true}, - 13: {want: 0x56, have: 0x13d, distance: 0xa, oneway: true}, - 14: {want: 0x58, have: 0x3e0, distance: 0xa, oneway: true}, - 15: {want: 0x71, have: 0x3e0, distance: 0xa, oneway: true}, - 16: {want: 0x75, have: 0x138, distance: 0xa, oneway: true}, - 17: {want: 0x82, have: 0x1bc, distance: 0xa, oneway: true}, - 18: {want: 0xa5, have: 0x138, distance: 0xa, oneway: true}, - 19: {want: 0xb2, have: 0x15d, distance: 0xa, oneway: true}, - 20: {want: 0xdd, have: 0x152, distance: 0xa, oneway: true}, - 21: {want: 0xe5, have: 0x138, distance: 0xa, oneway: true}, + 0: {want: 0x1d1, have: 0xb7, distance: 0x4, oneway: false}, + 1: {want: 0x407, have: 0xb7, distance: 0x4, oneway: false}, + 2: {want: 0x407, have: 0x1d1, distance: 0x4, oneway: false}, + 3: {want: 0x407, have: 0x432, distance: 0x4, oneway: false}, + 4: {want: 0x43a, have: 0x1, distance: 0x4, oneway: false}, + 5: {want: 0x1a3, have: 0x10d, distance: 0x4, oneway: true}, + 6: {want: 0x295, have: 0x10d, distance: 0x4, oneway: true}, + 7: {want: 0x101, have: 0x36f, distance: 0x8, oneway: false}, + 8: {want: 0x101, have: 0x347, distance: 0x8, oneway: false}, + 9: {want: 0x5, have: 0x3e2, distance: 0xa, oneway: true}, + 10: {want: 0xd, have: 0x139, distance: 0xa, oneway: true}, + 11: {want: 0x16, have: 0x367, distance: 0xa, oneway: true}, + 12: {want: 0x21, have: 0x139, distance: 0xa, oneway: true}, + 13: {want: 0x56, have: 0x13e, distance: 0xa, oneway: true}, + 14: {want: 0x58, have: 0x3e2, distance: 0xa, oneway: true}, + 15: {want: 0x71, have: 0x3e2, distance: 0xa, oneway: true}, + 16: {want: 0x75, have: 0x139, distance: 0xa, oneway: true}, + 17: {want: 0x82, have: 0x1be, distance: 0xa, oneway: true}, + 18: {want: 0xa5, have: 0x139, distance: 0xa, oneway: true}, + 19: {want: 0xb2, have: 0x15e, distance: 0xa, oneway: true}, + 20: {want: 0xdd, have: 0x153, distance: 0xa, oneway: true}, + 21: {want: 0xe5, have: 0x139, distance: 0xa, oneway: true}, 22: {want: 0xe9, have: 0x3a, distance: 0xa, oneway: true}, - 23: {want: 0xef, have: 0x15d, distance: 0xa, oneway: true}, - 24: {want: 0xf8, have: 0x15d, distance: 0xa, oneway: true}, - 25: {want: 0xff, have: 0x138, distance: 0xa, oneway: true}, - 26: {want: 0x12f, have: 0x138, distance: 0xa, oneway: true}, - 27: {want: 0x13b, have: 0x138, distance: 0xa, oneway: true}, - 28: {want: 0x13f, have: 0x150, distance: 0xa, oneway: true}, - 29: {want: 0x144, have: 0x13d, distance: 0xa, oneway: true}, - 30: {want: 0x157, have: 0x100, distance: 0xa, oneway: true}, - 31: {want: 0x16c, have: 0x365, distance: 0xa, oneway: true}, - 32: {want: 0x16d, have: 0x138, distance: 0xa, oneway: true}, - 33: {want: 0x16e, have: 0x138, distance: 0xa, oneway: true}, - 34: {want: 0x17c, have: 0x138, distance: 0xa, oneway: true}, - 35: {want: 0x18e, have: 0x13d, distance: 0xa, oneway: true}, - 36: {want: 0x192, have: 0x13d, distance: 0xa, oneway: true}, - 37: {want: 0x1a2, have: 0x1bc, distance: 0xa, oneway: true}, - 38: {want: 0x1b2, have: 0x138, distance: 0xa, oneway: true}, - 39: {want: 0x1b6, have: 0x138, distance: 0xa, oneway: true}, - 40: {want: 0x1d2, have: 0x15d, distance: 0xa, oneway: true}, - 41: {want: 0x1d5, have: 0x3e0, distance: 0xa, oneway: true}, - 42: {want: 0x1d7, have: 0x138, distance: 0xa, oneway: true}, - 43: {want: 0x1e5, have: 0x138, distance: 0xa, oneway: true}, - 44: {want: 0x1f6, have: 0x138, distance: 0xa, oneway: true}, - 45: {want: 0x20c, have: 0x1df, distance: 0xa, oneway: true}, - 46: {want: 0x20e, have: 0x138, distance: 0xa, oneway: true}, - 47: {want: 0x22b, have: 0x15d, distance: 0xa, oneway: true}, - 48: {want: 0x240, have: 0x3e0, distance: 0xa, oneway: true}, - 49: {want: 0x248, have: 0x138, distance: 0xa, oneway: true}, - 50: {want: 0x24f, have: 0x138, distance: 0xa, oneway: true}, - 51: {want: 0x263, have: 0x138, distance: 0xa, oneway: true}, - 52: {want: 0x272, have: 0x488, distance: 0xa, oneway: true}, - 53: {want: 0x288, have: 0x3e0, distance: 0xa, oneway: true}, - 54: {want: 0x28c, have: 0x1f7, distance: 0xa, oneway: true}, - 55: {want: 0x2a1, have: 0x138, distance: 0xa, oneway: true}, - 56: {want: 0x2b3, have: 0x15d, distance: 0xa, oneway: true}, - 57: {want: 0x2b6, have: 0x138, distance: 0xa, oneway: true}, - 58: {want: 0x2bc, have: 0x138, distance: 0xa, oneway: true}, - 59: {want: 0x2c1, have: 0x15d, distance: 0xa, oneway: true}, - 60: {want: 0x2eb, have: 0x138, distance: 0xa, oneway: true}, - 61: {want: 0x2ef, have: 0x15d, distance: 0xa, oneway: true}, - 62: {want: 0x2f8, have: 0x138, distance: 0xa, oneway: true}, - 63: {want: 0x2fd, have: 0x7e, distance: 0xa, oneway: true}, - 64: {want: 0x302, have: 0x138, distance: 0xa, oneway: true}, - 65: {want: 0x309, have: 0x3e0, distance: 0xa, oneway: true}, - 66: {want: 0x319, have: 0x1bc, distance: 0xa, oneway: true}, - 67: {want: 0x31d, have: 0x1df, distance: 0xa, oneway: true}, - 68: {want: 0x31e, have: 0x138, distance: 0xa, oneway: true}, - 69: {want: 0x32f, have: 0x138, distance: 0xa, oneway: true}, - 70: {want: 0x34f, have: 0x138, distance: 0xa, oneway: true}, - 71: {want: 0x368, have: 0x345, distance: 0xa, oneway: false}, - 72: {want: 0x368, have: 0x36d, distance: 0xa, oneway: true}, - 73: {want: 0x378, have: 0x138, distance: 0xa, oneway: true}, - 74: {want: 0x385, have: 0x138, distance: 0xa, oneway: true}, - 75: {want: 0x387, have: 0x138, distance: 0xa, oneway: true}, - 76: {want: 0x389, have: 0x15d, distance: 0xa, oneway: true}, - 77: {want: 0x38e, have: 0x138, distance: 0xa, oneway: true}, - 78: {want: 0x393, have: 0x138, distance: 0xa, oneway: true}, - 79: {want: 0x39b, have: 0x138, distance: 0xa, oneway: true}, - 80: {want: 0x3a3, have: 0x138, distance: 0xa, oneway: true}, - 81: {want: 0x3bc, have: 0x138, distance: 0xa, oneway: true}, - 82: {want: 0x3c2, have: 0x13d, distance: 0xa, oneway: true}, - 83: {want: 0x3d2, have: 0x10c, distance: 0xa, oneway: true}, - 84: {want: 0x3d7, have: 0x138, distance: 0xa, oneway: true}, - 85: {want: 0x3e3, have: 0x15d, distance: 0xa, oneway: true}, - 86: {want: 0x3e7, have: 0x1bc, distance: 0xa, oneway: true}, - 87: {want: 0x3f8, have: 0x138, distance: 0xa, oneway: true}, - 88: {want: 0x40a, have: 0x138, distance: 0xa, oneway: true}, - 89: {want: 0x421, have: 0x138, distance: 0xa, oneway: true}, - 90: {want: 0x427, have: 0x138, distance: 0xa, oneway: true}, - 91: {want: 0x42f, have: 0x138, distance: 0xa, oneway: true}, - 92: {want: 0x439, have: 0x138, distance: 0xa, oneway: true}, - 93: {want: 0x43c, have: 0x1df, distance: 0xa, oneway: true}, - 94: {want: 0x443, have: 0x138, distance: 0xa, oneway: true}, - 95: {want: 0x44e, have: 0x138, distance: 0xa, oneway: true}, - 96: {want: 0x45f, have: 0x138, distance: 0xa, oneway: true}, - 97: {want: 0x465, have: 0x3e0, distance: 0xa, oneway: true}, - 98: {want: 0x46d, have: 0x138, distance: 0xa, oneway: true}, - 99: {want: 0x474, have: 0x3e0, distance: 0xa, oneway: true}, - 100: {want: 0x3880, have: 0x138, distance: 0xa, oneway: true}, - 101: {want: 0x47e, have: 0x138, distance: 0xa, oneway: true}, - 102: {want: 0x480, have: 0x138, distance: 0xa, oneway: true}, - 103: {want: 0x492, have: 0x3e0, distance: 0xa, oneway: true}, - 104: {want: 0x49b, have: 0x138, distance: 0xa, oneway: true}, - 105: {want: 0x4aa, have: 0x527, distance: 0xa, oneway: true}, - 106: {want: 0x4b2, have: 0x138, distance: 0xa, oneway: true}, - 107: {want: 0x4ba, have: 0x3e0, distance: 0xa, oneway: true}, - 108: {want: 0x4e3, have: 0x15d, distance: 0xa, oneway: true}, - 109: {want: 0x4f0, have: 0x138, distance: 0xa, oneway: true}, - 110: {want: 0x510, have: 0x138, distance: 0xa, oneway: true}, - 111: {want: 0x516, have: 0x138, distance: 0xa, oneway: true}, - 112: {want: 0x52c, have: 0x138, distance: 0xa, oneway: true}, + 23: {want: 0xf0, have: 0x15e, distance: 0xa, oneway: true}, + 24: {want: 0xf9, have: 0x15e, distance: 0xa, oneway: true}, + 25: {want: 0x100, have: 0x139, distance: 0xa, oneway: true}, + 26: {want: 0x130, have: 0x139, distance: 0xa, oneway: true}, + 27: {want: 0x13c, have: 0x139, distance: 0xa, oneway: true}, + 28: {want: 0x140, have: 0x151, distance: 0xa, oneway: true}, + 29: {want: 0x145, have: 0x13e, distance: 0xa, oneway: true}, + 30: {want: 0x158, have: 0x101, distance: 0xa, oneway: true}, + 31: {want: 0x16d, have: 0x367, distance: 0xa, oneway: true}, + 32: {want: 0x16e, have: 0x139, distance: 0xa, oneway: true}, + 33: {want: 0x16f, have: 0x139, distance: 0xa, oneway: true}, + 34: {want: 0x17e, have: 0x139, distance: 0xa, oneway: true}, + 35: {want: 0x190, have: 0x13e, distance: 0xa, oneway: true}, + 36: {want: 0x194, have: 0x13e, distance: 0xa, oneway: true}, + 37: {want: 0x1a4, have: 0x1be, distance: 0xa, oneway: true}, + 38: {want: 0x1b4, have: 0x139, distance: 0xa, oneway: true}, + 39: {want: 0x1b8, have: 0x139, distance: 0xa, oneway: true}, + 40: {want: 0x1d4, have: 0x15e, distance: 0xa, oneway: true}, + 41: {want: 0x1d7, have: 0x3e2, distance: 0xa, oneway: true}, + 42: {want: 0x1d9, have: 0x139, distance: 0xa, oneway: true}, + 43: {want: 0x1e7, have: 0x139, distance: 0xa, oneway: true}, + 44: {want: 0x1f8, have: 0x139, distance: 0xa, oneway: true}, + 45: {want: 0x20e, have: 0x1e1, distance: 0xa, oneway: true}, + 46: {want: 0x210, have: 0x139, distance: 0xa, oneway: true}, + 47: {want: 0x22d, have: 0x15e, distance: 0xa, oneway: true}, + 48: {want: 0x242, have: 0x3e2, distance: 0xa, oneway: true}, + 49: {want: 0x24a, have: 0x139, distance: 0xa, oneway: true}, + 50: {want: 0x251, have: 0x139, distance: 0xa, oneway: true}, + 51: {want: 0x265, have: 0x139, distance: 0xa, oneway: true}, + 52: {want: 0x274, have: 0x48a, distance: 0xa, oneway: true}, + 53: {want: 0x28a, have: 0x3e2, distance: 0xa, oneway: true}, + 54: {want: 0x28e, have: 0x1f9, distance: 0xa, oneway: true}, + 55: {want: 0x2a3, have: 0x139, distance: 0xa, oneway: true}, + 56: {want: 0x2b5, have: 0x15e, distance: 0xa, oneway: true}, + 57: {want: 0x2b8, have: 0x139, distance: 0xa, oneway: true}, + 58: {want: 0x2be, have: 0x139, distance: 0xa, oneway: true}, + 59: {want: 0x2c3, have: 0x15e, distance: 0xa, oneway: true}, + 60: {want: 0x2ed, have: 0x139, distance: 0xa, oneway: true}, + 61: {want: 0x2f1, have: 0x15e, distance: 0xa, oneway: true}, + 62: {want: 0x2fa, have: 0x139, distance: 0xa, oneway: true}, + 63: {want: 0x2ff, have: 0x7e, distance: 0xa, oneway: true}, + 64: {want: 0x304, have: 0x139, distance: 0xa, oneway: true}, + 65: {want: 0x30b, have: 0x3e2, distance: 0xa, oneway: true}, + 66: {want: 0x31b, have: 0x1be, distance: 0xa, oneway: true}, + 67: {want: 0x31f, have: 0x1e1, distance: 0xa, oneway: true}, + 68: {want: 0x320, have: 0x139, distance: 0xa, oneway: true}, + 69: {want: 0x331, have: 0x139, distance: 0xa, oneway: true}, + 70: {want: 0x351, have: 0x139, distance: 0xa, oneway: true}, + 71: {want: 0x36a, have: 0x347, distance: 0xa, oneway: false}, + 72: {want: 0x36a, have: 0x36f, distance: 0xa, oneway: true}, + 73: {want: 0x37a, have: 0x139, distance: 0xa, oneway: true}, + 74: {want: 0x387, have: 0x139, distance: 0xa, oneway: true}, + 75: {want: 0x389, have: 0x139, distance: 0xa, oneway: true}, + 76: {want: 0x38b, have: 0x15e, distance: 0xa, oneway: true}, + 77: {want: 0x390, have: 0x139, distance: 0xa, oneway: true}, + 78: {want: 0x395, have: 0x139, distance: 0xa, oneway: true}, + 79: {want: 0x39d, have: 0x139, distance: 0xa, oneway: true}, + 80: {want: 0x3a5, have: 0x139, distance: 0xa, oneway: true}, + 81: {want: 0x3be, have: 0x139, distance: 0xa, oneway: true}, + 82: {want: 0x3c4, have: 0x13e, distance: 0xa, oneway: true}, + 83: {want: 0x3d4, have: 0x10d, distance: 0xa, oneway: true}, + 84: {want: 0x3d9, have: 0x139, distance: 0xa, oneway: true}, + 85: {want: 0x3e5, have: 0x15e, distance: 0xa, oneway: true}, + 86: {want: 0x3e9, have: 0x1be, distance: 0xa, oneway: true}, + 87: {want: 0x3fa, have: 0x139, distance: 0xa, oneway: true}, + 88: {want: 0x40c, have: 0x139, distance: 0xa, oneway: true}, + 89: {want: 0x423, have: 0x139, distance: 0xa, oneway: true}, + 90: {want: 0x429, have: 0x139, distance: 0xa, oneway: true}, + 91: {want: 0x431, have: 0x139, distance: 0xa, oneway: true}, + 92: {want: 0x43b, have: 0x139, distance: 0xa, oneway: true}, + 93: {want: 0x43e, have: 0x1e1, distance: 0xa, oneway: true}, + 94: {want: 0x445, have: 0x139, distance: 0xa, oneway: true}, + 95: {want: 0x450, have: 0x139, distance: 0xa, oneway: true}, + 96: {want: 0x461, have: 0x139, distance: 0xa, oneway: true}, + 97: {want: 0x467, have: 0x3e2, distance: 0xa, oneway: true}, + 98: {want: 0x46f, have: 0x139, distance: 0xa, oneway: true}, + 99: {want: 0x476, have: 0x3e2, distance: 0xa, oneway: true}, + 100: {want: 0x3883, have: 0x139, distance: 0xa, oneway: true}, + 101: {want: 0x480, have: 0x139, distance: 0xa, oneway: true}, + 102: {want: 0x482, have: 0x139, distance: 0xa, oneway: true}, + 103: {want: 0x494, have: 0x3e2, distance: 0xa, oneway: true}, + 104: {want: 0x49d, have: 0x139, distance: 0xa, oneway: true}, + 105: {want: 0x4ac, have: 0x529, distance: 0xa, oneway: true}, + 106: {want: 0x4b4, have: 0x139, distance: 0xa, oneway: true}, + 107: {want: 0x4bc, have: 0x3e2, distance: 0xa, oneway: true}, + 108: {want: 0x4e5, have: 0x15e, distance: 0xa, oneway: true}, + 109: {want: 0x4f2, have: 0x139, distance: 0xa, oneway: true}, + 110: {want: 0x512, have: 0x139, distance: 0xa, oneway: true}, + 111: {want: 0x518, have: 0x139, distance: 0xa, oneway: true}, + 112: {want: 0x52f, have: 0x139, distance: 0xa, oneway: true}, } // matchScript holds pairs of scriptIDs where readers of one script // can typically also read the other. Each is associated with a confidence. // Size: 208 bytes, 26 elements var matchScript = [26]scriptIntelligibility{ - 0: {wantLang: 0x430, haveLang: 0x430, wantScript: 0x55, haveScript: 0x1e, distance: 0x5}, - 1: {wantLang: 0x430, haveLang: 0x430, wantScript: 0x1e, haveScript: 0x55, distance: 0x5}, - 2: {wantLang: 0x58, haveLang: 0x3e0, wantScript: 0x55, haveScript: 0x1e, distance: 0xa}, - 3: {wantLang: 0xa5, haveLang: 0x138, wantScript: 0xe, haveScript: 0x55, distance: 0xa}, - 4: {wantLang: 0x1d5, haveLang: 0x3e0, wantScript: 0x8, haveScript: 0x1e, distance: 0xa}, - 5: {wantLang: 0x20e, haveLang: 0x138, wantScript: 0x2a, haveScript: 0x55, distance: 0xa}, - 6: {wantLang: 0x248, haveLang: 0x138, wantScript: 0x49, haveScript: 0x55, distance: 0xa}, - 7: {wantLang: 0x24f, haveLang: 0x138, wantScript: 0x4d, haveScript: 0x55, distance: 0xa}, - 8: {wantLang: 0x2b6, haveLang: 0x138, wantScript: 0x52, haveScript: 0x55, distance: 0xa}, - 9: {wantLang: 0x302, haveLang: 0x138, wantScript: 0x69, haveScript: 0x55, distance: 0xa}, - 10: {wantLang: 0x32f, haveLang: 0x138, wantScript: 0x70, haveScript: 0x55, distance: 0xa}, - 11: {wantLang: 0x34f, haveLang: 0x138, wantScript: 0x20, haveScript: 0x55, distance: 0xa}, - 12: {wantLang: 0x393, haveLang: 0x138, wantScript: 0x7a, haveScript: 0x55, distance: 0xa}, - 13: {wantLang: 0x39b, haveLang: 0x138, wantScript: 0x32, haveScript: 0x55, distance: 0xa}, - 14: {wantLang: 0x3bc, haveLang: 0x138, wantScript: 0x5, haveScript: 0x55, distance: 0xa}, - 15: {wantLang: 0x3f8, haveLang: 0x138, wantScript: 0x5, haveScript: 0x55, distance: 0xa}, - 16: {wantLang: 0x40a, haveLang: 0x138, wantScript: 0xc6, haveScript: 0x55, distance: 0xa}, - 17: {wantLang: 0x44e, haveLang: 0x138, wantScript: 0xd3, haveScript: 0x55, distance: 0xa}, - 18: {wantLang: 0x45f, haveLang: 0x138, wantScript: 0xd6, haveScript: 0x55, distance: 0xa}, - 19: {wantLang: 0x46d, haveLang: 0x138, wantScript: 0x28, haveScript: 0x55, distance: 0xa}, - 20: {wantLang: 0x474, haveLang: 0x3e0, wantScript: 0x55, haveScript: 0x1e, distance: 0xa}, - 21: {wantLang: 0x4b2, haveLang: 0x138, wantScript: 0x5, haveScript: 0x55, distance: 0xa}, - 22: {wantLang: 0x4ba, haveLang: 0x3e0, wantScript: 0x55, haveScript: 0x1e, distance: 0xa}, - 23: {wantLang: 0x510, haveLang: 0x138, wantScript: 0x3a, haveScript: 0x55, distance: 0xa}, - 24: {wantLang: 0x527, haveLang: 0x527, wantScript: 0x37, haveScript: 0x38, distance: 0xf}, - 25: {wantLang: 0x527, haveLang: 0x527, wantScript: 0x38, haveScript: 0x37, distance: 0x13}, + 0: {wantLang: 0x432, haveLang: 0x432, wantScript: 0x57, haveScript: 0x1f, distance: 0x5}, + 1: {wantLang: 0x432, haveLang: 0x432, wantScript: 0x1f, haveScript: 0x57, distance: 0x5}, + 2: {wantLang: 0x58, haveLang: 0x3e2, wantScript: 0x57, haveScript: 0x1f, distance: 0xa}, + 3: {wantLang: 0xa5, haveLang: 0x139, wantScript: 0xe, haveScript: 0x57, distance: 0xa}, + 4: {wantLang: 0x1d7, haveLang: 0x3e2, wantScript: 0x8, haveScript: 0x1f, distance: 0xa}, + 5: {wantLang: 0x210, haveLang: 0x139, wantScript: 0x2b, haveScript: 0x57, distance: 0xa}, + 6: {wantLang: 0x24a, haveLang: 0x139, wantScript: 0x4b, haveScript: 0x57, distance: 0xa}, + 7: {wantLang: 0x251, haveLang: 0x139, wantScript: 0x4f, haveScript: 0x57, distance: 0xa}, + 8: {wantLang: 0x2b8, haveLang: 0x139, wantScript: 0x54, haveScript: 0x57, distance: 0xa}, + 9: {wantLang: 0x304, haveLang: 0x139, wantScript: 0x6b, haveScript: 0x57, distance: 0xa}, + 10: {wantLang: 0x331, haveLang: 0x139, wantScript: 0x72, haveScript: 0x57, distance: 0xa}, + 11: {wantLang: 0x351, haveLang: 0x139, wantScript: 0x21, haveScript: 0x57, distance: 0xa}, + 12: {wantLang: 0x395, haveLang: 0x139, wantScript: 0x7d, haveScript: 0x57, distance: 0xa}, + 13: {wantLang: 0x39d, haveLang: 0x139, wantScript: 0x33, haveScript: 0x57, distance: 0xa}, + 14: {wantLang: 0x3be, haveLang: 0x139, wantScript: 0x5, haveScript: 0x57, distance: 0xa}, + 15: {wantLang: 0x3fa, haveLang: 0x139, wantScript: 0x5, haveScript: 0x57, distance: 0xa}, + 16: {wantLang: 0x40c, haveLang: 0x139, wantScript: 0xca, haveScript: 0x57, distance: 0xa}, + 17: {wantLang: 0x450, haveLang: 0x139, wantScript: 0xd7, haveScript: 0x57, distance: 0xa}, + 18: {wantLang: 0x461, haveLang: 0x139, wantScript: 0xda, haveScript: 0x57, distance: 0xa}, + 19: {wantLang: 0x46f, haveLang: 0x139, wantScript: 0x29, haveScript: 0x57, distance: 0xa}, + 20: {wantLang: 0x476, haveLang: 0x3e2, wantScript: 0x57, haveScript: 0x1f, distance: 0xa}, + 21: {wantLang: 0x4b4, haveLang: 0x139, wantScript: 0x5, haveScript: 0x57, distance: 0xa}, + 22: {wantLang: 0x4bc, haveLang: 0x3e2, wantScript: 0x57, haveScript: 0x1f, distance: 0xa}, + 23: {wantLang: 0x512, haveLang: 0x139, wantScript: 0x3b, haveScript: 0x57, distance: 0xa}, + 24: {wantLang: 0x529, haveLang: 0x529, wantScript: 0x38, haveScript: 0x39, distance: 0xf}, + 25: {wantLang: 0x529, haveLang: 0x529, wantScript: 0x39, haveScript: 0x38, distance: 0x13}, } // Size: 90 bytes, 15 elements var matchRegion = [15]regionIntelligibility{ 0: {lang: 0x3a, script: 0x0, group: 0x4, distance: 0x4}, 1: {lang: 0x3a, script: 0x0, group: 0x84, distance: 0x4}, - 2: {lang: 0x138, script: 0x0, group: 0x1, distance: 0x4}, - 3: {lang: 0x138, script: 0x0, group: 0x81, distance: 0x4}, - 4: {lang: 0x13d, script: 0x0, group: 0x3, distance: 0x4}, - 5: {lang: 0x13d, script: 0x0, group: 0x83, distance: 0x4}, - 6: {lang: 0x3be, script: 0x0, group: 0x3, distance: 0x4}, - 7: {lang: 0x3be, script: 0x0, group: 0x83, distance: 0x4}, - 8: {lang: 0x527, script: 0x38, group: 0x2, distance: 0x4}, - 9: {lang: 0x527, script: 0x38, group: 0x82, distance: 0x4}, + 2: {lang: 0x139, script: 0x0, group: 0x1, distance: 0x4}, + 3: {lang: 0x139, script: 0x0, group: 0x81, distance: 0x4}, + 4: {lang: 0x13e, script: 0x0, group: 0x3, distance: 0x4}, + 5: {lang: 0x13e, script: 0x0, group: 0x83, distance: 0x4}, + 6: {lang: 0x3c0, script: 0x0, group: 0x3, distance: 0x4}, + 7: {lang: 0x3c0, script: 0x0, group: 0x83, distance: 0x4}, + 8: {lang: 0x529, script: 0x39, group: 0x2, distance: 0x4}, + 9: {lang: 0x529, script: 0x39, group: 0x82, distance: 0x4}, 10: {lang: 0x3a, script: 0x0, group: 0x80, distance: 0x5}, - 11: {lang: 0x138, script: 0x0, group: 0x80, distance: 0x5}, - 12: {lang: 0x13d, script: 0x0, group: 0x80, distance: 0x5}, - 13: {lang: 0x3be, script: 0x0, group: 0x80, distance: 0x5}, - 14: {lang: 0x527, script: 0x38, group: 0x80, distance: 0x5}, + 11: {lang: 0x139, script: 0x0, group: 0x80, distance: 0x5}, + 12: {lang: 0x13e, script: 0x0, group: 0x80, distance: 0x5}, + 13: {lang: 0x3c0, script: 0x0, group: 0x80, distance: 0x5}, + 14: {lang: 0x529, script: 0x39, group: 0x80, distance: 0x5}, } // Size: 264 bytes, 33 elements var regionContainment = [33]uint64{ // Entry 0 - 1F - 0x00000001dfffffff, 0x00000000000007a2, 0x0000000000003044, 0x0000000000000008, + 0x00000001ffffffff, 0x00000000200007a2, 0x0000000000003044, 0x0000000000000008, 0x00000000803c0010, 0x0000000000000020, 0x0000000000000040, 0x0000000000000080, 0x0000000000000100, 0x0000000000000200, 0x0000000000000400, 0x000000004000384c, 0x0000000000001000, 0x0000000000002000, 0x0000000000004000, 0x0000000000008000, 0x0000000000010000, 0x0000000000020000, 0x0000000000040000, 0x0000000000080000, 0x0000000000100000, 0x0000000000200000, 0x0000000001c1c000, 0x0000000000800000, 0x0000000001000000, 0x000000001e020000, 0x0000000004000000, 0x0000000008000000, - 0x0000000010000000, 0x0000000020000000, 0x0000000040002048, 0x0000000080000000, + 0x0000000010000000, 0x00000000200006a0, 0x0000000040002048, 0x0000000080000000, // Entry 20 - 3F 0x0000000100000000, } @@ -3614,14 +3625,14 @@ var regionInclusion = [358]uint8{ // Size: 584 bytes, 73 elements var regionInclusionBits = [73]uint64{ // Entry 0 - 1F - 0x0000000102400813, 0x00000000000007a3, 0x0000000000003844, 0x0000000040000808, - 0x00000000803c0011, 0x0000000000000022, 0x0000000040000844, 0x0000000000000082, - 0x0000000000000102, 0x0000000000000202, 0x0000000000000402, 0x000000004000384d, + 0x0000000102400813, 0x00000000200007a3, 0x0000000000003844, 0x0000000040000808, + 0x00000000803c0011, 0x0000000020000022, 0x0000000040000844, 0x0000000020000082, + 0x0000000000000102, 0x0000000020000202, 0x0000000020000402, 0x000000004000384d, 0x0000000000001804, 0x0000000040002804, 0x0000000000404000, 0x0000000000408000, 0x0000000000410000, 0x0000000002020000, 0x0000000000040010, 0x0000000000080010, 0x0000000000100010, 0x0000000000200010, 0x0000000001c1c001, 0x0000000000c00000, 0x0000000001400000, 0x000000001e020001, 0x0000000006000000, 0x000000000a000000, - 0x0000000012000000, 0x0000000020000000, 0x0000000040002848, 0x0000000080000010, + 0x0000000012000000, 0x00000000200006a2, 0x0000000040002848, 0x0000000080000010, // Entry 20 - 3F 0x0000000100000001, 0x0000000000000001, 0x0000000080000000, 0x0000000000020000, 0x0000000001000000, 0x0000000000008000, 0x0000000000002000, 0x0000000000000200, @@ -3630,7 +3641,7 @@ var regionInclusionBits = [73]uint64{ 0x0000000000001000, 0x0000000000010000, 0x0000000000000400, 0x0000000004000000, 0x0000000000000040, 0x0000000010000000, 0x0000000000004000, 0x0000000101000000, 0x0000000108000000, 0x0000000000000100, 0x0000000100020000, 0x0000000000080000, - 0x0000000000100000, 0x0000000000800000, 0x00000001dfffffff, 0x0000000102400fb3, + 0x0000000000100000, 0x0000000000800000, 0x00000001ffffffff, 0x0000000122400fb3, // Entry 40 - 5F 0x00000001827c0813, 0x000000014240385f, 0x0000000103c1c813, 0x000000011e420813, 0x0000000112000001, 0x0000000106000001, 0x0000000101400001, 0x000000010a000001, @@ -3645,7 +3656,7 @@ var regionInclusionNext = [73]uint8{ 0x3e, 0x3f, 0x0b, 0x0b, 0x40, 0x01, 0x0b, 0x01, 0x01, 0x01, 0x01, 0x41, 0x0b, 0x0b, 0x16, 0x16, 0x16, 0x19, 0x04, 0x04, 0x04, 0x04, 0x42, 0x16, - 0x16, 0x43, 0x19, 0x19, 0x19, 0x1d, 0x0b, 0x04, + 0x16, 0x43, 0x19, 0x19, 0x19, 0x01, 0x0b, 0x04, 0x00, 0x00, 0x1f, 0x11, 0x18, 0x0f, 0x0d, 0x09, 0x03, 0x15, 0x44, 0x12, 0x1b, 0x05, 0x45, 0x07, 0x0c, 0x10, 0x0a, 0x1a, 0x06, 0x1c, 0x0e, 0x46, @@ -3665,11 +3676,11 @@ type parentRel struct { // Size: 414 bytes, 5 elements var parents = [5]parentRel{ - 0: {lang: 0x138, script: 0x0, maxScript: 0x55, toRegion: 0x1, fromRegion: []uint16{0x1a, 0x25, 0x26, 0x2f, 0x34, 0x36, 0x3d, 0x42, 0x46, 0x48, 0x49, 0x4a, 0x50, 0x52, 0x5c, 0x5d, 0x61, 0x64, 0x6d, 0x73, 0x74, 0x75, 0x7b, 0x7c, 0x7f, 0x80, 0x81, 0x83, 0x8c, 0x8d, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9f, 0xa0, 0xa4, 0xa7, 0xa9, 0xad, 0xb1, 0xb4, 0xb5, 0xbf, 0xc6, 0xca, 0xcb, 0xcc, 0xce, 0xd0, 0xd2, 0xd5, 0xd6, 0xdd, 0xdf, 0xe0, 0xe6, 0xe7, 0xe8, 0xeb, 0xf0, 0x107, 0x109, 0x10a, 0x10b, 0x10d, 0x10e, 0x112, 0x117, 0x11b, 0x11d, 0x11f, 0x125, 0x129, 0x12c, 0x12d, 0x12f, 0x131, 0x139, 0x13c, 0x13f, 0x142, 0x161, 0x162, 0x164}}, - 1: {lang: 0x138, script: 0x0, maxScript: 0x55, toRegion: 0x1a, fromRegion: []uint16{0x2e, 0x4e, 0x60, 0x63, 0x72, 0xd9, 0x10c, 0x10f}}, - 2: {lang: 0x13d, script: 0x0, maxScript: 0x55, toRegion: 0x1f, fromRegion: []uint16{0x2c, 0x3f, 0x41, 0x48, 0x51, 0x54, 0x56, 0x59, 0x65, 0x69, 0x89, 0x8f, 0xcf, 0xd8, 0xe2, 0xe4, 0xec, 0xf1, 0x11a, 0x135, 0x136, 0x13b}}, - 3: {lang: 0x3be, script: 0x0, maxScript: 0x55, toRegion: 0xee, fromRegion: []uint16{0x2a, 0x4e, 0x5a, 0x86, 0x8b, 0xb7, 0xc6, 0xd1, 0x118, 0x126}}, - 4: {lang: 0x527, script: 0x38, maxScript: 0x38, toRegion: 0x8d, fromRegion: []uint16{0xc6}}, + 0: {lang: 0x139, script: 0x0, maxScript: 0x57, toRegion: 0x1, fromRegion: []uint16{0x1a, 0x25, 0x26, 0x2f, 0x34, 0x36, 0x3d, 0x42, 0x46, 0x48, 0x49, 0x4a, 0x50, 0x52, 0x5c, 0x5d, 0x61, 0x64, 0x6d, 0x73, 0x74, 0x75, 0x7b, 0x7c, 0x7f, 0x80, 0x81, 0x83, 0x8c, 0x8d, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9f, 0xa0, 0xa4, 0xa7, 0xa9, 0xad, 0xb1, 0xb4, 0xb5, 0xbf, 0xc6, 0xca, 0xcb, 0xcc, 0xce, 0xd0, 0xd2, 0xd5, 0xd6, 0xdd, 0xdf, 0xe0, 0xe6, 0xe7, 0xe8, 0xeb, 0xf0, 0x107, 0x109, 0x10a, 0x10b, 0x10d, 0x10e, 0x112, 0x117, 0x11b, 0x11d, 0x11f, 0x125, 0x129, 0x12c, 0x12d, 0x12f, 0x131, 0x139, 0x13c, 0x13f, 0x142, 0x161, 0x162, 0x164}}, + 1: {lang: 0x139, script: 0x0, maxScript: 0x57, toRegion: 0x1a, fromRegion: []uint16{0x2e, 0x4e, 0x60, 0x63, 0x72, 0xd9, 0x10c, 0x10f}}, + 2: {lang: 0x13e, script: 0x0, maxScript: 0x57, toRegion: 0x1f, fromRegion: []uint16{0x2c, 0x3f, 0x41, 0x48, 0x51, 0x54, 0x56, 0x59, 0x65, 0x69, 0x89, 0x8f, 0xcf, 0xd8, 0xe2, 0xe4, 0xec, 0xf1, 0x11a, 0x135, 0x136, 0x13b}}, + 3: {lang: 0x3c0, script: 0x0, maxScript: 0x57, toRegion: 0xee, fromRegion: []uint16{0x2a, 0x4e, 0x5a, 0x86, 0x8b, 0xb7, 0xc6, 0xd1, 0x118, 0x126}}, + 4: {lang: 0x529, script: 0x39, maxScript: 0x39, toRegion: 0x8d, fromRegion: []uint16{0xc6}}, } -// Total table size 27175 bytes (26KiB); checksum: 569649CD +// Total table size 27238 bytes (26KiB); checksum: C9BBE4D5 diff --git a/vendor/golang.org/x/text/runes/cond_test.go b/vendor/golang.org/x/text/runes/cond_test.go deleted file mode 100644 index 44cd36d0b1..0000000000 --- a/vendor/golang.org/x/text/runes/cond_test.go +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright 2015 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 runes - -import ( - "strings" - "testing" - "unicode" - - "golang.org/x/text/cases" - "golang.org/x/text/language" - "golang.org/x/text/transform" -) - -var ( - toUpper = cases.Upper(language.Und) - toLower = cases.Lower(language.Und) -) - -type spanformer interface { - transform.SpanningTransformer -} - -func TestPredicate(t *testing.T) { - testConditional(t, func(rt *unicode.RangeTable, t, f spanformer) spanformer { - return If(Predicate(func(r rune) bool { - return unicode.Is(rt, r) - }), t, f) - }) -} - -func TestIn(t *testing.T) { - testConditional(t, func(rt *unicode.RangeTable, t, f spanformer) spanformer { - return If(In(rt), t, f) - }) -} - -func TestNotIn(t *testing.T) { - testConditional(t, func(rt *unicode.RangeTable, t, f spanformer) spanformer { - return If(NotIn(rt), f, t) - }) -} - -func testConditional(t *testing.T, f func(rt *unicode.RangeTable, t, f spanformer) spanformer) { - lower := f(unicode.Latin, toLower, toLower) - - for i, tt := range []transformTest{{ - desc: "empty", - szDst: large, - atEOF: true, - in: "", - out: "", - outFull: "", - t: lower, - }, { - desc: "small", - szDst: 1, - atEOF: true, - in: "B", - out: "b", - outFull: "b", - errSpan: transform.ErrEndOfSpan, - t: lower, - }, { - desc: "short dst", - szDst: 2, - atEOF: true, - in: "AAA", - out: "aa", - outFull: "aaa", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: lower, - }, { - desc: "short dst writing error", - szDst: 1, - atEOF: false, - in: "A\x80", - out: "a", - outFull: "a\x80", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: lower, - }, { - desc: "short dst writing incomplete rune", - szDst: 2, - atEOF: true, - in: "Σ\xc2", - out: "Σ", - outFull: "Σ\xc2", - err: transform.ErrShortDst, - t: f(unicode.Latin, toLower, nil), - }, { - desc: "short dst, longer", - szDst: 5, - atEOF: true, - in: "Hellø", - out: "Hell", - outFull: "Hellø", - err: transform.ErrShortDst, - // idem is used to test short buffers by forcing processing of full-rune increments. - t: f(unicode.Latin, Map(idem), nil), - }, { - desc: "short dst, longer, writing error", - szDst: 6, - atEOF: false, - in: "\x80Hello\x80", - out: "\x80Hello", - outFull: "\x80Hello\x80", - err: transform.ErrShortDst, - t: f(unicode.Latin, Map(idem), nil), - }, { - desc: "short src", - szDst: 2, - atEOF: false, - in: "A\xc2", - out: "a", - outFull: "a\xc2", - err: transform.ErrShortSrc, - errSpan: transform.ErrEndOfSpan, - t: lower, - }, { - desc: "short src no change", - szDst: 2, - atEOF: false, - in: "a\xc2", - out: "a", - outFull: "a\xc2", - err: transform.ErrShortSrc, - errSpan: transform.ErrShortSrc, - nSpan: 1, - t: lower, - }, { - desc: "invalid input, atEOF", - szDst: large, - atEOF: true, - in: "\x80", - out: "\x80", - outFull: "\x80", - t: lower, - }, { - desc: "invalid input, !atEOF", - szDst: large, - atEOF: false, - in: "\x80", - out: "\x80", - outFull: "\x80", - t: lower, - }, { - desc: "invalid input, incomplete rune atEOF", - szDst: large, - atEOF: true, - in: "\xc2", - out: "\xc2", - outFull: "\xc2", - t: lower, - }, { - desc: "nop", - szDst: large, - atEOF: true, - in: "Hello World!", - out: "Hello World!", - outFull: "Hello World!", - t: f(unicode.Latin, nil, nil), - }, { - desc: "nop in", - szDst: large, - atEOF: true, - in: "THIS IS α ΤΕΣΤ", - out: "this is α ΤΕΣΤ", - outFull: "this is α ΤΕΣΤ", - errSpan: transform.ErrEndOfSpan, - t: f(unicode.Greek, nil, toLower), - }, { - desc: "nop in latin", - szDst: large, - atEOF: true, - in: "THIS IS α ΤΕΣΤ", - out: "THIS IS α τεστ", - outFull: "THIS IS α τεστ", - errSpan: transform.ErrEndOfSpan, - t: f(unicode.Latin, nil, toLower), - }, { - desc: "nop not in", - szDst: large, - atEOF: true, - in: "THIS IS α ΤΕΣΤ", - out: "this is α ΤΕΣΤ", - outFull: "this is α ΤΕΣΤ", - errSpan: transform.ErrEndOfSpan, - t: f(unicode.Latin, toLower, nil), - }, { - desc: "pass atEOF is true when at end", - szDst: large, - atEOF: true, - in: "hello", - out: "HELLO", - outFull: "HELLO", - errSpan: transform.ErrEndOfSpan, - t: f(unicode.Latin, upperAtEOF{}, nil), - }, { - desc: "pass atEOF is true when at end of segment", - szDst: large, - atEOF: true, - in: "hello ", - out: "HELLO ", - outFull: "HELLO ", - errSpan: transform.ErrEndOfSpan, - t: f(unicode.Latin, upperAtEOF{}, nil), - }, { - desc: "don't pass atEOF is true when atEOF is false", - szDst: large, - atEOF: false, - in: "hello", - out: "", - outFull: "HELLO", - err: transform.ErrShortSrc, - errSpan: transform.ErrShortSrc, - t: f(unicode.Latin, upperAtEOF{}, nil), - }, { - desc: "pass atEOF is true when at end, no change", - szDst: large, - atEOF: true, - in: "HELLO", - out: "HELLO", - outFull: "HELLO", - t: f(unicode.Latin, upperAtEOF{}, nil), - }, { - desc: "pass atEOF is true when at end of segment, no change", - szDst: large, - atEOF: true, - in: "HELLO ", - out: "HELLO ", - outFull: "HELLO ", - t: f(unicode.Latin, upperAtEOF{}, nil), - }, { - desc: "large input ASCII", - szDst: 12000, - atEOF: false, - in: strings.Repeat("HELLO", 2000), - out: strings.Repeat("hello", 2000), - outFull: strings.Repeat("hello", 2000), - errSpan: transform.ErrEndOfSpan, - err: nil, - t: lower, - }, { - desc: "large input non-ASCII", - szDst: 12000, - atEOF: false, - in: strings.Repeat("\u3333", 2000), - out: strings.Repeat("\u3333", 2000), - outFull: strings.Repeat("\u3333", 2000), - err: nil, - t: lower, - }} { - tt.check(t, i) - } -} - -// upperAtEOF is a strange Transformer that converts text to uppercase, but only -// if atEOF is true. -type upperAtEOF struct{ transform.NopResetter } - -func (upperAtEOF) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - if !atEOF { - return 0, 0, transform.ErrShortSrc - } - return toUpper.Transform(dst, src, atEOF) -} - -func (upperAtEOF) Span(src []byte, atEOF bool) (n int, err error) { - if !atEOF { - return 0, transform.ErrShortSrc - } - return toUpper.Span(src, atEOF) -} - -func BenchmarkConditional(b *testing.B) { - doBench(b, If(In(unicode.Hangul), transform.Nop, transform.Nop)) -} diff --git a/vendor/golang.org/x/text/runes/example_test.go b/vendor/golang.org/x/text/runes/example_test.go deleted file mode 100644 index a60bfd9d25..0000000000 --- a/vendor/golang.org/x/text/runes/example_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 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 runes_test - -import ( - "fmt" - "unicode" - - "golang.org/x/text/runes" - "golang.org/x/text/transform" - "golang.org/x/text/unicode/norm" - "golang.org/x/text/width" -) - -func ExampleRemove() { - t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC) - s, _, _ := transform.String(t, "résumé") - fmt.Println(s) - - // Output: - // resume -} - -func ExampleMap() { - replaceHyphens := runes.Map(func(r rune) rune { - if unicode.Is(unicode.Hyphen, r) { - return '|' - } - return r - }) - s, _, _ := transform.String(replaceHyphens, "a-b‐c⸗d﹣e") - fmt.Println(s) - - // Output: - // a|b|c|d|e -} - -func ExampleIn() { - // Convert Latin characters to their canonical form, while keeping other - // width distinctions. - t := runes.If(runes.In(unicode.Latin), width.Fold, nil) - s, _, _ := transform.String(t, "アルアノリウ tech / アルアノリウ tech") - fmt.Println(s) - - // Output: - // アルアノリウ tech / アルアノリウ tech -} - -func ExampleIf() { - // Widen everything but ASCII. - isASCII := func(r rune) bool { return r <= unicode.MaxASCII } - t := runes.If(runes.Predicate(isASCII), nil, width.Widen) - s, _, _ := transform.String(t, "アルアノリウ tech / 中國 / 5₩") - fmt.Println(s) - - // Output: - // アルアノリウ tech / 中國 / 5₩ -} diff --git a/vendor/golang.org/x/text/runes/runes_test.go b/vendor/golang.org/x/text/runes/runes_test.go deleted file mode 100644 index 23c5bc952a..0000000000 --- a/vendor/golang.org/x/text/runes/runes_test.go +++ /dev/null @@ -1,664 +0,0 @@ -// Copyright 2015 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 runes - -import ( - "strings" - "testing" - "unicode/utf8" - - "golang.org/x/text/internal/testtext" - "golang.org/x/text/transform" -) - -type transformTest struct { - desc string - szDst int - atEOF bool - repl string - in string - out string // result string of first call to Transform - outFull string // transform of entire input string - err error - errSpan error - nSpan int - - t transform.SpanningTransformer -} - -const large = 10240 - -func (tt *transformTest) check(t *testing.T, i int) { - if tt.t == nil { - return - } - dst := make([]byte, tt.szDst) - src := []byte(tt.in) - nDst, nSrc, err := tt.t.Transform(dst, src, tt.atEOF) - if err != tt.err { - t.Errorf("%d:%s:error: got %v; want %v", i, tt.desc, err, tt.err) - } - if got := string(dst[:nDst]); got != tt.out { - t.Errorf("%d:%s:out: got %q; want %q", i, tt.desc, got, tt.out) - } - - // Calls tt.t.Transform for the remainder of the input. We use this to test - // the nSrc return value. - out := make([]byte, large) - n := copy(out, dst[:nDst]) - nDst, _, _ = tt.t.Transform(out[n:], src[nSrc:], true) - if got, want := string(out[:n+nDst]), tt.outFull; got != want { - t.Errorf("%d:%s:outFull: got %q; want %q", i, tt.desc, got, want) - } - - tt.t.Reset() - p := 0 - for ; p < len(tt.in) && p < len(tt.outFull) && tt.in[p] == tt.outFull[p]; p++ { - } - if tt.nSpan != 0 { - p = tt.nSpan - } - if n, err = tt.t.Span([]byte(tt.in), tt.atEOF); n != p || err != tt.errSpan { - t.Errorf("%d:%s:span: got %d, %v; want %d, %v", i, tt.desc, n, err, p, tt.errSpan) - } -} - -func idem(r rune) rune { return r } - -func TestMap(t *testing.T) { - runes := []rune{'a', 'ç', '中', '\U00012345', 'a'} - // Default mapper used for this test. - rotate := Map(func(r rune) rune { - for i, m := range runes { - if m == r { - return runes[i+1] - } - } - return r - }) - - for i, tt := range []transformTest{{ - desc: "empty", - szDst: large, - atEOF: true, - in: "", - out: "", - outFull: "", - t: rotate, - }, { - desc: "no change", - szDst: 1, - atEOF: true, - in: "b", - out: "b", - outFull: "b", - t: rotate, - }, { - desc: "short dst", - szDst: 2, - atEOF: true, - in: "aaaa", - out: "ç", - outFull: "çççç", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "short dst ascii, no change", - szDst: 2, - atEOF: true, - in: "bbb", - out: "bb", - outFull: "bbb", - err: transform.ErrShortDst, - t: rotate, - }, { - desc: "short dst writing error", - szDst: 2, - atEOF: false, - in: "a\x80", - out: "ç", - outFull: "ç\ufffd", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "short dst writing incomplete rune", - szDst: 2, - atEOF: true, - in: "a\xc0", - out: "ç", - outFull: "ç\ufffd", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "short dst, longer", - szDst: 5, - atEOF: true, - in: "Hellø", - out: "Hell", - outFull: "Hellø", - err: transform.ErrShortDst, - t: rotate, - }, { - desc: "short dst, single", - szDst: 1, - atEOF: false, - in: "ø", - out: "", - outFull: "ø", - err: transform.ErrShortDst, - t: Map(idem), - }, { - desc: "short dst, longer, writing error", - szDst: 8, - atEOF: false, - in: "\x80Hello\x80", - out: "\ufffdHello", - outFull: "\ufffdHello\ufffd", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "short src", - szDst: 2, - atEOF: false, - in: "a\xc2", - out: "ç", - outFull: "ç\ufffd", - err: transform.ErrShortSrc, - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "invalid input, atEOF", - szDst: large, - atEOF: true, - in: "\x80", - out: "\ufffd", - outFull: "\ufffd", - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "invalid input, !atEOF", - szDst: large, - atEOF: false, - in: "\x80", - out: "\ufffd", - outFull: "\ufffd", - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "incomplete rune !atEOF", - szDst: large, - atEOF: false, - in: "\xc2", - out: "", - outFull: "\ufffd", - err: transform.ErrShortSrc, - errSpan: transform.ErrShortSrc, - t: rotate, - }, { - desc: "invalid input, incomplete rune atEOF", - szDst: large, - atEOF: true, - in: "\xc2", - out: "\ufffd", - outFull: "\ufffd", - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "misc correct", - szDst: large, - atEOF: true, - in: "a\U00012345 ç!", - out: "ça 中!", - outFull: "ça 中!", - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "misc correct and invalid", - szDst: large, - atEOF: true, - in: "Hello\x80 w\x80orl\xc0d!\xc0", - out: "Hello\ufffd w\ufffdorl\ufffdd!\ufffd", - outFull: "Hello\ufffd w\ufffdorl\ufffdd!\ufffd", - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "misc correct and invalid, short src", - szDst: large, - atEOF: false, - in: "Hello\x80 w\x80orl\xc0d!\xc2", - out: "Hello\ufffd w\ufffdorl\ufffdd!", - outFull: "Hello\ufffd w\ufffdorl\ufffdd!\ufffd", - err: transform.ErrShortSrc, - errSpan: transform.ErrEndOfSpan, - t: rotate, - }, { - desc: "misc correct and invalid, short src, replacing RuneError", - szDst: large, - atEOF: false, - in: "Hel\ufffdlo\x80 w\x80orl\xc0d!\xc2", - out: "Hel?lo? w?orl?d!", - outFull: "Hel?lo? w?orl?d!?", - errSpan: transform.ErrEndOfSpan, - err: transform.ErrShortSrc, - t: Map(func(r rune) rune { - if r == utf8.RuneError { - return '?' - } - return r - }), - }} { - tt.check(t, i) - } -} - -func TestRemove(t *testing.T) { - remove := Remove(Predicate(func(r rune) bool { - return strings.ContainsRune("aeiou\u0300\uFF24\U00012345", r) - })) - - for i, tt := range []transformTest{ - 0: { - szDst: large, - atEOF: true, - in: "", - out: "", - outFull: "", - t: remove, - }, - 1: { - szDst: 0, - atEOF: true, - in: "aaaa", - out: "", - outFull: "", - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 2: { - szDst: 1, - atEOF: true, - in: "aaaa", - out: "", - outFull: "", - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 3: { - szDst: 1, - atEOF: true, - in: "baaaa", - out: "b", - outFull: "b", - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 4: { - szDst: 2, - atEOF: true, - in: "açaaa", - out: "ç", - outFull: "ç", - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 5: { - szDst: 2, - atEOF: true, - in: "aaaç", - out: "ç", - outFull: "ç", - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 6: { - szDst: 2, - atEOF: false, - in: "a\x80", - out: "", - outFull: "\ufffd", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 7: { - szDst: 1, - atEOF: true, - in: "a\xc0", - out: "", - outFull: "\ufffd", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 8: { - szDst: 1, - atEOF: false, - in: "a\xc2", - out: "", - outFull: "\ufffd", - err: transform.ErrShortSrc, - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 9: { - szDst: large, - atEOF: true, - in: "\x80", - out: "\ufffd", - outFull: "\ufffd", - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 10: { - szDst: large, - atEOF: false, - in: "\x80", - out: "\ufffd", - outFull: "\ufffd", - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 11: { - szDst: large, - atEOF: true, - in: "\xc2", - out: "\ufffd", - outFull: "\ufffd", - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 12: { - szDst: large, - atEOF: false, - in: "\xc2", - out: "", - outFull: "\ufffd", - err: transform.ErrShortSrc, - errSpan: transform.ErrShortSrc, - t: remove, - }, - 13: { - szDst: large, - atEOF: true, - in: "Hello \U00012345world!", - out: "Hll wrld!", - outFull: "Hll wrld!", - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 14: { - szDst: large, - atEOF: true, - in: "Hello\x80 w\x80orl\xc0d!\xc0", - out: "Hll\ufffd w\ufffdrl\ufffdd!\ufffd", - outFull: "Hll\ufffd w\ufffdrl\ufffdd!\ufffd", - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 15: { - szDst: large, - atEOF: false, - in: "Hello\x80 w\x80orl\xc0d!\xc2", - out: "Hll\ufffd w\ufffdrl\ufffdd!", - outFull: "Hll\ufffd w\ufffdrl\ufffdd!\ufffd", - err: transform.ErrShortSrc, - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 16: { - szDst: large, - atEOF: false, - in: "Hel\ufffdlo\x80 w\x80orl\xc0d!\xc2", - out: "Hello world!", - outFull: "Hello world!", - err: transform.ErrShortSrc, - errSpan: transform.ErrEndOfSpan, - t: Remove(Predicate(func(r rune) bool { return r == utf8.RuneError })), - }, - 17: { - szDst: 4, - atEOF: true, - in: "Hellø", - out: "Hll", - outFull: "Hllø", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 18: { - szDst: 4, - atEOF: false, - in: "Hellø", - out: "Hll", - outFull: "Hllø", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 19: { - szDst: 8, - atEOF: false, - in: "\x80Hello\uFF24\x80", - out: "\ufffdHll", - outFull: "\ufffdHll\ufffd", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: remove, - }, - 20: { - szDst: 8, - atEOF: false, - in: "Hllll", - out: "Hllll", - outFull: "Hllll", - t: remove, - }} { - tt.check(t, i) - } -} - -func TestReplaceIllFormed(t *testing.T) { - replace := ReplaceIllFormed() - - for i, tt := range []transformTest{ - 0: { - szDst: large, - atEOF: true, - in: "", - out: "", - outFull: "", - t: replace, - }, - 1: { - szDst: 1, - atEOF: true, - in: "aa", - out: "a", - outFull: "aa", - err: transform.ErrShortDst, - t: replace, - }, - 2: { - szDst: 1, - atEOF: true, - in: "a\x80", - out: "a", - outFull: "a\ufffd", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: replace, - }, - 3: { - szDst: 1, - atEOF: true, - in: "a\xc2", - out: "a", - outFull: "a\ufffd", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: replace, - }, - 4: { - szDst: large, - atEOF: true, - in: "\x80", - out: "\ufffd", - outFull: "\ufffd", - errSpan: transform.ErrEndOfSpan, - t: replace, - }, - 5: { - szDst: large, - atEOF: false, - in: "\x80", - out: "\ufffd", - outFull: "\ufffd", - errSpan: transform.ErrEndOfSpan, - t: replace, - }, - 6: { - szDst: large, - atEOF: true, - in: "\xc2", - out: "\ufffd", - outFull: "\ufffd", - errSpan: transform.ErrEndOfSpan, - t: replace, - }, - 7: { - szDst: large, - atEOF: false, - in: "\xc2", - out: "", - outFull: "\ufffd", - err: transform.ErrShortSrc, - errSpan: transform.ErrShortSrc, - t: replace, - }, - 8: { - szDst: large, - atEOF: true, - in: "Hello world!", - out: "Hello world!", - outFull: "Hello world!", - t: replace, - }, - 9: { - szDst: large, - atEOF: true, - in: "Hello\x80 w\x80orl\xc2d!\xc2", - out: "Hello\ufffd w\ufffdorl\ufffdd!\ufffd", - outFull: "Hello\ufffd w\ufffdorl\ufffdd!\ufffd", - errSpan: transform.ErrEndOfSpan, - t: replace, - }, - 10: { - szDst: large, - atEOF: false, - in: "Hello\x80 w\x80orl\xc2d!\xc2", - out: "Hello\ufffd w\ufffdorl\ufffdd!", - outFull: "Hello\ufffd w\ufffdorl\ufffdd!\ufffd", - err: transform.ErrShortSrc, - errSpan: transform.ErrEndOfSpan, - t: replace, - }, - 16: { - szDst: 10, - atEOF: false, - in: "\x80Hello\x80", - out: "\ufffdHello", - outFull: "\ufffdHello\ufffd", - err: transform.ErrShortDst, - errSpan: transform.ErrEndOfSpan, - t: replace, - }, - 17: { - szDst: 10, - atEOF: false, - in: "\ufffdHello\ufffd", - out: "\ufffdHello", - outFull: "\ufffdHello\ufffd", - err: transform.ErrShortDst, - t: replace, - }, - } { - tt.check(t, i) - } -} - -func TestMapAlloc(t *testing.T) { - if n := testtext.AllocsPerRun(3, func() { - Map(idem).Transform(nil, nil, false) - }); n > 0 { - t.Errorf("got %f; want 0", n) - } -} - -func rmNop(r rune) bool { return false } - -func TestRemoveAlloc(t *testing.T) { - if n := testtext.AllocsPerRun(3, func() { - Remove(Predicate(rmNop)).Transform(nil, nil, false) - }); n > 0 { - t.Errorf("got %f; want 0", n) - } -} - -func TestReplaceIllFormedAlloc(t *testing.T) { - if n := testtext.AllocsPerRun(3, func() { - ReplaceIllFormed().Transform(nil, nil, false) - }); n > 0 { - t.Errorf("got %f; want 0", n) - } -} - -func doBench(b *testing.B, t Transformer) { - for _, bc := range []struct{ name, data string }{ - {"ascii", testtext.ASCII}, - {"3byte", testtext.ThreeByteUTF8}, - } { - dst := make([]byte, 2*len(bc.data)) - src := []byte(bc.data) - - testtext.Bench(b, bc.name+"/transform", func(b *testing.B) { - b.SetBytes(int64(len(src))) - for i := 0; i < b.N; i++ { - t.Transform(dst, src, true) - } - }) - src = t.Bytes(src) - t.Reset() - testtext.Bench(b, bc.name+"/span", func(b *testing.B) { - b.SetBytes(int64(len(src))) - for i := 0; i < b.N; i++ { - t.Span(src, true) - } - }) - } -} - -func BenchmarkRemove(b *testing.B) { - doBench(b, Remove(Predicate(func(r rune) bool { return r == 'e' }))) -} - -func BenchmarkMapAll(b *testing.B) { - doBench(b, Map(func(r rune) rune { return 'a' })) -} - -func BenchmarkMapNone(b *testing.B) { - doBench(b, Map(func(r rune) rune { return r })) -} - -func BenchmarkReplaceIllFormed(b *testing.B) { - doBench(b, ReplaceIllFormed()) -} - -var ( - input = strings.Repeat("Thé qüick brøwn føx jumps øver the lazy døg. ", 100) -) diff --git a/vendor/golang.org/x/text/secure/bidirule/bench_test.go b/vendor/golang.org/x/text/secure/bidirule/bench_test.go deleted file mode 100644 index 2db922bfdc..0000000000 --- a/vendor/golang.org/x/text/secure/bidirule/bench_test.go +++ /dev/null @@ -1,54 +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 bidirule - -import ( - "testing" - - "golang.org/x/text/internal/testtext" -) - -var benchData = []struct{ name, data string }{ - {"ascii", "Scheveningen"}, - {"arabic", "دبي"}, - {"hangul", "다음과"}, -} - -func doBench(b *testing.B, fn func(b *testing.B, data string)) { - for _, d := range benchData { - testtext.Bench(b, d.name, func(b *testing.B) { fn(b, d.data) }) - } -} - -func BenchmarkSpan(b *testing.B) { - r := New() - doBench(b, func(b *testing.B, str string) { - b.SetBytes(int64(len(str))) - data := []byte(str) - for i := 0; i < b.N; i++ { - r.Reset() - r.Span(data, true) - } - }) -} - -func BenchmarkDirectionASCII(b *testing.B) { - doBench(b, func(b *testing.B, str string) { - b.SetBytes(int64(len(str))) - data := []byte(str) - for i := 0; i < b.N; i++ { - Direction(data) - } - }) -} - -func BenchmarkDirectionStringASCII(b *testing.B) { - doBench(b, func(b *testing.B, str string) { - b.SetBytes(int64(len(str))) - for i := 0; i < b.N; i++ { - DirectionString(str) - } - }) -} diff --git a/vendor/golang.org/x/text/secure/bidirule/bidirule.go b/vendor/golang.org/x/text/secure/bidirule/bidirule.go index 0e6b85824b..e2b70f76c2 100644 --- a/vendor/golang.org/x/text/secure/bidirule/bidirule.go +++ b/vendor/golang.org/x/text/secure/bidirule/bidirule.go @@ -203,10 +203,6 @@ func (t *Transformer) isRTL() bool { return t.seen&isRTL != 0 } -func (t *Transformer) isFinal() bool { - return t.state == ruleLTRFinal || t.state == ruleRTLFinal || t.state == ruleInitial -} - // Reset implements transform.Transformer. func (t *Transformer) Reset() { *t = Transformer{} } diff --git a/vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go b/vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go new file mode 100644 index 0000000000..e4c62289f9 --- /dev/null +++ b/vendor/golang.org/x/text/secure/bidirule/bidirule10.0.0.go @@ -0,0 +1,11 @@ +// 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. + +// +build go1.10 + +package bidirule + +func (t *Transformer) isFinal() bool { + return t.state == ruleLTRFinal || t.state == ruleRTLFinal || t.state == ruleInitial +} diff --git a/vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go b/vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go new file mode 100644 index 0000000000..02b9e1e9d4 --- /dev/null +++ b/vendor/golang.org/x/text/secure/bidirule/bidirule9.0.0.go @@ -0,0 +1,14 @@ +// 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. + +// +build !go1.10 + +package bidirule + +func (t *Transformer) isFinal() bool { + if !t.isRTL() { + return true + } + return t.state == ruleLTRFinal || t.state == ruleRTLFinal || t.state == ruleInitial +} diff --git a/vendor/golang.org/x/text/secure/bidirule/bidirule_test.go b/vendor/golang.org/x/text/secure/bidirule/bidirule_test.go deleted file mode 100644 index 4b6c612dc1..0000000000 --- a/vendor/golang.org/x/text/secure/bidirule/bidirule_test.go +++ /dev/null @@ -1,851 +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 bidirule - -import ( - "fmt" - "testing" - - "golang.org/x/text/internal/testtext" - "golang.org/x/text/transform" - "golang.org/x/text/unicode/bidi" -) - -const ( - strL = "ABC" // Left to right - most letters in LTR scripts - strR = "עברית" // Right to left - most letters in non-Arabic RTL scripts - strAL = "دبي" // Arabic letters - most letters in the Arabic script - strEN = "123" // European Number (0-9, and Extended Arabic-Indic numbers) - strES = "+-" // European Number Separator (+ and -) - strET = "$" // European Number Terminator (currency symbols, the hash sign, the percent sign and so on) - strAN = "\u0660" // Arabic Number; this encompasses the Arabic-Indic numbers, but not the Extended Arabic-Indic numbers - strCS = "," // Common Number Separator (. , / : et al) - strNSM = "\u0300" // Nonspacing Mark - most combining accents - strBN = "\u200d" // Boundary Neutral - control characters (ZWNJ, ZWJ, and others) - strB = "\u2029" // Paragraph Separator - strS = "\u0009" // Segment Separator - strWS = " " // Whitespace, including the SPACE character - strON = "@" // Other Neutrals, including @, &, parentheses, MIDDLE DOT -) - -type ruleTest struct { - in string - dir bidi.Direction - n int // position at which the rule fails - err error - - // For tests that split the string in two. - pSrc int // number of source bytes to consume first - szDst int // size of destination buffer - nSrc int // source bytes consumed and bytes written - err0 error // error after first run -} - -var testCases = [][]ruleTest{ - // Go-specific rules. - // Invalid UTF-8 is invalid. - 0: []ruleTest{{ - in: "", - dir: bidi.LeftToRight, - }, { - in: "\x80", - dir: bidi.LeftToRight, - err: ErrInvalid, - n: 0, - }, { - in: "\xcc", - dir: bidi.LeftToRight, - err: ErrInvalid, - n: 0, - }, { - in: "abc\x80", - dir: bidi.LeftToRight, - err: ErrInvalid, - n: 3, - }, { - in: "abc\xcc", - dir: bidi.LeftToRight, - err: ErrInvalid, - n: 3, - }, { - in: "abc\xccdef", - dir: bidi.LeftToRight, - err: ErrInvalid, - n: 3, - }, { - in: "\xccdef", - dir: bidi.LeftToRight, - err: ErrInvalid, - n: 0, - }, { - in: strR + "\x80", - dir: bidi.RightToLeft, - err: ErrInvalid, - n: len(strR), - }, { - in: strR + "\xcc", - dir: bidi.RightToLeft, - err: ErrInvalid, - n: len(strR), - }, { - in: strAL + "\xcc" + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: len(strAL), - }, { - in: "\xcc" + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 0, - }}, - - // Rule 2.1: The first character must be a character with Bidi property L, - // R, or AL. If it has the R or AL property, it is an RTL label; if it has - // the L property, it is an LTR label. - 1: []ruleTest{{ - in: strL, - dir: bidi.LeftToRight, - }, { - in: strR, - dir: bidi.RightToLeft, - }, { - in: strAL, - dir: bidi.RightToLeft, - }, { - in: strAN, - dir: bidi.RightToLeft, - err: ErrInvalid, - }, { - in: strEN, - dir: bidi.LeftToRight, - err: ErrInvalid, - n: len(strEN), - }, { - in: strES, - dir: bidi.LeftToRight, - err: ErrInvalid, - n: len(strES), - }, { - in: strET, - dir: bidi.LeftToRight, - err: ErrInvalid, - n: len(strET), - }, { - in: strCS, - dir: bidi.LeftToRight, - err: ErrInvalid, - n: len(strCS), - }, { - in: strNSM, - dir: bidi.LeftToRight, - err: ErrInvalid, - n: len(strNSM), - }, { - in: strBN, - dir: bidi.LeftToRight, - err: ErrInvalid, - n: len(strBN), - }, { - in: strB, - dir: bidi.LeftToRight, - err: ErrInvalid, - n: len(strB), - }, { - in: strS, - dir: bidi.LeftToRight, - err: ErrInvalid, - n: len(strS), - }, { - in: strWS, - dir: bidi.LeftToRight, - err: ErrInvalid, - n: len(strWS), - }, { - in: strON, - dir: bidi.LeftToRight, - err: ErrInvalid, - n: len(strON), - }, { - in: strEN + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 3, - }, { - in: strES + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 2, - }, { - in: strET + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 1, - }, { - in: strCS + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 1, - }, { - in: strNSM + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 2, - }, { - in: strBN + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 3, - }, { - in: strB + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 3, - }, { - in: strS + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 1, - }, { - in: strWS + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 1, - }, { - in: strON + strR, - dir: bidi.RightToLeft, - err: ErrInvalid, - n: 1, - }}, - - // Rule 2.2: In an RTL label, only characters with the Bidi properties R, - // AL, AN, EN, ES, CS, ET, ON, BN, or NSM are allowed. - 2: []ruleTest{{ - in: strR + strR + strAL, - dir: bidi.RightToLeft, - }, { - in: strR + strAL + strR, - dir: bidi.RightToLeft, - }, { - in: strR + strAN + strAL, - dir: bidi.RightToLeft, - }, { - in: strR + strEN + strR, - dir: bidi.RightToLeft, - }, { - in: strR + strES + strR, - dir: bidi.RightToLeft, - }, { - in: strR + strCS + strR, - dir: bidi.RightToLeft, - }, { - in: strR + strET + strAL, - dir: bidi.RightToLeft, - }, { - in: strR + strON + strR, - dir: bidi.RightToLeft, - }, { - in: strR + strBN + strR, - dir: bidi.RightToLeft, - }, { - in: strR + strNSM + strAL, - dir: bidi.RightToLeft, - }, { - in: strR + strL + strR, - dir: bidi.RightToLeft, - n: len(strR), - err: ErrInvalid, - }, { - in: strR + strB + strR, - dir: bidi.RightToLeft, - n: len(strR), - err: ErrInvalid, - }, { - in: strR + strS + strAL, - dir: bidi.RightToLeft, - n: len(strR), - err: ErrInvalid, - }, { - in: strR + strWS + strAL, - dir: bidi.RightToLeft, - n: len(strR), - err: ErrInvalid, - }, { - in: strAL + strR + strAL, - dir: bidi.RightToLeft, - }, { - in: strAL + strAL + strR, - dir: bidi.RightToLeft, - }, { - in: strAL + strAN + strAL, - dir: bidi.RightToLeft, - }, { - in: strAL + strEN + strR, - dir: bidi.RightToLeft, - }, { - in: strAL + strES + strR, - dir: bidi.RightToLeft, - }, { - in: strAL + strCS + strR, - dir: bidi.RightToLeft, - }, { - in: strAL + strET + strAL, - dir: bidi.RightToLeft, - }, { - in: strAL + strON + strR, - dir: bidi.RightToLeft, - }, { - in: strAL + strBN + strR, - dir: bidi.RightToLeft, - }, { - in: strAL + strNSM + strAL, - dir: bidi.RightToLeft, - }, { - in: strAL + strL + strR, - dir: bidi.RightToLeft, - n: len(strAL), - err: ErrInvalid, - }, { - in: strAL + strB + strR, - dir: bidi.RightToLeft, - n: len(strAL), - err: ErrInvalid, - }, { - in: strAL + strS + strAL, - dir: bidi.RightToLeft, - n: len(strAL), - err: ErrInvalid, - }, { - in: strAL + strWS + strAL, - dir: bidi.RightToLeft, - n: len(strAL), - err: ErrInvalid, - }}, - - // Rule 2.3: In an RTL label, the end of the label must be a character with - // Bidi property R, AL, EN, or AN, followed by zero or more characters with - // Bidi property NSM. - 3: []ruleTest{{ - in: strR + strNSM, - dir: bidi.RightToLeft, - }, { - in: strR + strR, - dir: bidi.RightToLeft, - }, { - in: strR + strAL + strNSM, - dir: bidi.RightToLeft, - }, { - in: strR + strEN + strNSM + strNSM, - dir: bidi.RightToLeft, - }, { - in: strR + strAN, - dir: bidi.RightToLeft, - }, { - in: strR + strES + strNSM, - dir: bidi.RightToLeft, - n: len(strR + strES + strNSM), - err: ErrInvalid, - }, { - in: strR + strCS + strNSM + strNSM, - dir: bidi.RightToLeft, - n: len(strR + strCS + strNSM + strNSM), - err: ErrInvalid, - }, { - in: strR + strET, - dir: bidi.RightToLeft, - n: len(strR + strET), - err: ErrInvalid, - }, { - in: strR + strON + strNSM, - dir: bidi.RightToLeft, - n: len(strR + strON + strNSM), - err: ErrInvalid, - }, { - in: strR + strBN + strNSM + strNSM, - dir: bidi.RightToLeft, - n: len(strR + strBN + strNSM + strNSM), - err: ErrInvalid, - }, { - in: strR + strL + strNSM, - dir: bidi.RightToLeft, - n: len(strR), - err: ErrInvalid, - }, { - in: strR + strB + strNSM + strNSM, - dir: bidi.RightToLeft, - n: len(strR), - err: ErrInvalid, - }, { - in: strR + strS, - dir: bidi.RightToLeft, - n: len(strR), - err: ErrInvalid, - }, { - in: strR + strWS, - dir: bidi.RightToLeft, - n: len(strR), - err: ErrInvalid, - }, { - in: strAL + strNSM, - dir: bidi.RightToLeft, - }, { - in: strAL + strR, - dir: bidi.RightToLeft, - }, { - in: strAL + strAL + strNSM, - dir: bidi.RightToLeft, - }, { - in: strAL + strEN + strNSM + strNSM, - dir: bidi.RightToLeft, - }, { - in: strAL + strAN, - dir: bidi.RightToLeft, - }, { - in: strAL + strES + strNSM, - dir: bidi.RightToLeft, - n: len(strAL + strES + strNSM), - err: ErrInvalid, - }, { - in: strAL + strCS + strNSM + strNSM, - dir: bidi.RightToLeft, - n: len(strAL + strCS + strNSM + strNSM), - err: ErrInvalid, - }, { - in: strAL + strET, - dir: bidi.RightToLeft, - n: len(strAL + strET), - err: ErrInvalid, - }, { - in: strAL + strON + strNSM, - dir: bidi.RightToLeft, - n: len(strAL + strON + strNSM), - err: ErrInvalid, - }, { - in: strAL + strBN + strNSM + strNSM, - dir: bidi.RightToLeft, - n: len(strAL + strBN + strNSM + strNSM), - err: ErrInvalid, - }, { - in: strAL + strL + strNSM, - dir: bidi.RightToLeft, - n: len(strAL), - err: ErrInvalid, - }, { - in: strAL + strB + strNSM + strNSM, - dir: bidi.RightToLeft, - n: len(strAL), - err: ErrInvalid, - }, { - in: strAL + strS, - dir: bidi.RightToLeft, - n: len(strAL), - err: ErrInvalid, - }, { - in: strAL + strWS, - dir: bidi.RightToLeft, - n: len(strAL), - err: ErrInvalid, - }}, - - // Rule 2.4: In an RTL label, if an EN is present, no AN may be present, - // and vice versa. - 4: []ruleTest{{ - in: strR + strEN + strAN, - dir: bidi.RightToLeft, - n: len(strR + strEN), - err: ErrInvalid, - }, { - in: strR + strAN + strEN + strNSM, - dir: bidi.RightToLeft, - n: len(strR + strAN), - err: ErrInvalid, - }, { - in: strAL + strEN + strAN, - dir: bidi.RightToLeft, - n: len(strAL + strEN), - err: ErrInvalid, - }, { - in: strAL + strAN + strEN + strNSM, - dir: bidi.RightToLeft, - n: len(strAL + strAN), - err: ErrInvalid, - }}, - - // Rule 2.5: In an LTR label, only characters with the Bidi properties L, - // EN, ES, CS, ET, ON, BN, or NSM are allowed. - 5: []ruleTest{{ - in: strL + strL + strL, - dir: bidi.LeftToRight, - }, { - in: strL + strEN + strL, - dir: bidi.LeftToRight, - }, { - in: strL + strES + strL, - dir: bidi.LeftToRight, - }, { - in: strL + strCS + strL, - dir: bidi.LeftToRight, - }, { - in: strL + strET + strL, - dir: bidi.LeftToRight, - }, { - in: strL + strON + strL, - dir: bidi.LeftToRight, - }, { - in: strL + strBN + strL, - dir: bidi.LeftToRight, - }, { - in: strL + strNSM + strL, - dir: bidi.LeftToRight, - }, { - in: strL + strR + strL, - dir: bidi.RightToLeft, - n: len(strL), - err: ErrInvalid, - }, { - in: strL + strAL + strL, - dir: bidi.RightToLeft, - n: len(strL), - err: ErrInvalid, - }, { - in: strL + strAN + strL, - dir: bidi.RightToLeft, - n: len(strL), - err: ErrInvalid, - }, { - in: strL + strB + strL, - dir: bidi.LeftToRight, - n: len(strL + strB + strL), - err: ErrInvalid, - }, { - in: strL + strB + strL + strR, - dir: bidi.RightToLeft, - n: len(strL + strB + strL), - err: ErrInvalid, - }, { - in: strL + strS + strL, - dir: bidi.LeftToRight, - n: len(strL + strS + strL), - err: ErrInvalid, - }, { - in: strL + strS + strL + strR, - dir: bidi.RightToLeft, - n: len(strL + strS + strL), - err: ErrInvalid, - }, { - in: strL + strWS + strL, - dir: bidi.LeftToRight, - n: len(strL + strWS + strL), - err: ErrInvalid, - }, { - in: strL + strWS + strL + strR, - dir: bidi.RightToLeft, - n: len(strL + strWS + strL), - err: ErrInvalid, - }}, - - // Rule 2.6: In an LTR label, the end of the label must be a character with - // Bidi property L or EN, followed by zero or more characters with Bidi - // property NSM. - 6: []ruleTest{{ - in: strL, - dir: bidi.LeftToRight, - }, { - in: strL + strNSM, - dir: bidi.LeftToRight, - }, { - in: strL + strNSM + strNSM, - dir: bidi.LeftToRight, - }, { - in: strL + strEN, - dir: bidi.LeftToRight, - }, { - in: strL + strEN + strNSM, - dir: bidi.LeftToRight, - }, { - in: strL + strEN + strNSM + strNSM, - dir: bidi.LeftToRight, - }, { - in: strL + strES, - dir: bidi.LeftToRight, - n: len(strL + strES), - err: ErrInvalid, - }, { - in: strL + strES + strR, - dir: bidi.RightToLeft, - n: len(strL + strES), - err: ErrInvalid, - }, { - in: strL + strCS, - dir: bidi.LeftToRight, - n: len(strL + strCS), - err: ErrInvalid, - }, { - in: strL + strCS + strR, - dir: bidi.RightToLeft, - n: len(strL + strCS), - err: ErrInvalid, - }, { - in: strL + strET, - dir: bidi.LeftToRight, - n: len(strL + strET), - err: ErrInvalid, - }, { - in: strL + strET + strR, - dir: bidi.RightToLeft, - n: len(strL + strET), - err: ErrInvalid, - }, { - in: strL + strON, - dir: bidi.LeftToRight, - n: len(strL + strON), - err: ErrInvalid, - }, { - in: strL + strON + strR, - dir: bidi.RightToLeft, - n: len(strL + strON), - err: ErrInvalid, - }, { - in: strL + strBN, - dir: bidi.LeftToRight, - n: len(strL + strBN), - err: ErrInvalid, - }, { - in: strL + strBN + strR, - dir: bidi.RightToLeft, - n: len(strL + strBN), - err: ErrInvalid, - }, { - in: strL + strR, - dir: bidi.RightToLeft, - n: len(strL), - err: ErrInvalid, - }, { - in: strL + strAL, - dir: bidi.RightToLeft, - n: len(strL), - err: ErrInvalid, - }, { - in: strL + strAN, - dir: bidi.RightToLeft, - n: len(strL), - err: ErrInvalid, - }, { - in: strL + strB, - dir: bidi.LeftToRight, - n: len(strL + strB), - err: ErrInvalid, - }, { - in: strL + strB + strR, - dir: bidi.RightToLeft, - n: len(strL + strB), - err: ErrInvalid, - }, { - in: strL + strS, - dir: bidi.LeftToRight, - n: len(strL + strS), - err: ErrInvalid, - }, { - in: strL + strS + strR, - dir: bidi.RightToLeft, - n: len(strL + strS), - err: ErrInvalid, - }, { - in: strL + strWS, - dir: bidi.LeftToRight, - n: len(strL + strWS), - err: ErrInvalid, - }, { - in: strL + strWS + strR, - dir: bidi.RightToLeft, - n: len(strL + strWS), - err: ErrInvalid, - }}, - - // Incremental processing. - 9: []ruleTest{{ - in: "e\u0301", // é - dir: bidi.LeftToRight, - - pSrc: 2, - nSrc: 1, - err0: transform.ErrShortSrc, - }, { - in: "e\u1000f", // é - dir: bidi.LeftToRight, - - pSrc: 3, - nSrc: 1, - err0: transform.ErrShortSrc, - }, { - // Remain invalid once invalid. - in: strR + "ab", - dir: bidi.RightToLeft, - n: len(strR), - err: ErrInvalid, - - pSrc: len(strR) + 1, - nSrc: len(strR), - err0: ErrInvalid, - }, { - // Short destination - in: "abcdefghij", - dir: bidi.LeftToRight, - - pSrc: 10, - szDst: 5, - nSrc: 5, - err0: transform.ErrShortDst, - }, { - in: "\U000102f7", - dir: bidi.LeftToRight, - n: len("\U000102f7"), - err: ErrInvalid, - }, { - // Short destination splitting input rune - in: "e\u0301", - dir: bidi.LeftToRight, - - pSrc: 3, - szDst: 2, - nSrc: 1, - err0: transform.ErrShortDst, - }, { - // Unicode 10.0.0 IDNA test string. - in: "FAX\u2a77\U0001d186", - dir: bidi.LeftToRight, - n: len("FAX\u2a77\U0001d186"), - err: ErrInvalid, - }, { - in: "\x80\u0660", - dir: bidi.RightToLeft, - n: 0, - err: ErrInvalid, - }}, -} - -func init() { - for rule, cases := range testCases { - for i, tc := range cases { - if tc.err == nil { - testCases[rule][i].n = len(tc.in) - } - } - } -} - -func doTests(t *testing.T, fn func(t *testing.T, tc ruleTest)) { - for rule, cases := range testCases { - for i, tc := range cases { - name := fmt.Sprintf("%d/%d:%+q:%s", rule, i, tc.in, tc.in) - testtext.Run(t, name, func(t *testing.T) { - fn(t, tc) - }) - } - } -} - -func TestDirection(t *testing.T) { - doTests(t, func(t *testing.T, tc ruleTest) { - dir := Direction([]byte(tc.in)) - if dir != tc.dir { - t.Errorf("dir was %v; want %v", dir, tc.dir) - } - }) -} - -func TestDirectionString(t *testing.T) { - doTests(t, func(t *testing.T, tc ruleTest) { - dir := DirectionString(tc.in) - if dir != tc.dir { - t.Errorf("dir was %v; want %v", dir, tc.dir) - } - }) -} - -func TestValid(t *testing.T) { - doTests(t, func(t *testing.T, tc ruleTest) { - got := Valid([]byte(tc.in)) - want := tc.err == nil - if got != want { - t.Fatalf("Valid: got %v; want %v", got, want) - } - - got = ValidString(tc.in) - want = tc.err == nil - if got != want { - t.Fatalf("Valid: got %v; want %v", got, want) - } - }) -} - -func TestSpan(t *testing.T) { - doTests(t, func(t *testing.T, tc ruleTest) { - // Skip tests that test for limited destination buffer size. - if tc.szDst > 0 { - return - } - - r := New() - src := []byte(tc.in) - - n, err := r.Span(src[:tc.pSrc], tc.pSrc == len(tc.in)) - if err != tc.err0 { - t.Errorf("err0 was %v; want %v", err, tc.err0) - } - if n != tc.nSrc { - t.Fatalf("nSrc was %d; want %d", n, tc.nSrc) - } - - n, err = r.Span(src[n:], true) - if err != tc.err { - t.Errorf("error was %v; want %v", err, tc.err) - } - if got := n + tc.nSrc; got != tc.n { - t.Errorf("n was %d; want %d", got, tc.n) - } - }) -} - -func TestTransform(t *testing.T) { - doTests(t, func(t *testing.T, tc ruleTest) { - r := New() - - src := []byte(tc.in) - dst := make([]byte, len(tc.in)) - if tc.szDst > 0 { - dst = make([]byte, tc.szDst) - } - - // First transform operates on a zero-length string for most tests. - nDst, nSrc, err := r.Transform(dst, src[:tc.pSrc], tc.pSrc == len(tc.in)) - if err != tc.err0 { - t.Errorf("err0 was %v; want %v", err, tc.err0) - } - if nDst != nSrc { - t.Fatalf("nDst (%d) and nSrc (%d) should match", nDst, nSrc) - } - if nSrc != tc.nSrc { - t.Fatalf("nSrc was %d; want %d", nSrc, tc.nSrc) - } - - dst1 := make([]byte, len(tc.in)) - copy(dst1, dst[:nDst]) - - nDst, nSrc, err = r.Transform(dst1[nDst:], src[nSrc:], true) - if err != tc.err { - t.Errorf("error was %v; want %v", err, tc.err) - } - if nDst != nSrc { - t.Fatalf("nDst (%d) and nSrc (%d) should match", nDst, nSrc) - } - n := nSrc + tc.nSrc - if n != tc.n { - t.Fatalf("n was %d; want %d", n, tc.n) - } - if got, want := string(dst1[:n]), tc.in[:tc.n]; got != want { - t.Errorf("got %+q; want %+q", got, want) - } - }) -} diff --git a/vendor/golang.org/x/text/transform/examples_test.go b/vendor/golang.org/x/text/transform/examples_test.go deleted file mode 100644 index f2e284dba5..0000000000 --- a/vendor/golang.org/x/text/transform/examples_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2013 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 transform_test - -import ( - "fmt" - "unicode" - - "golang.org/x/text/transform" - "golang.org/x/text/unicode/norm" -) - -func ExampleRemoveFunc() { - input := []byte(`tschüß; до свидания`) - - b := make([]byte, len(input)) - - t := transform.RemoveFunc(unicode.IsSpace) - n, _, _ := t.Transform(b, input, true) - fmt.Println(string(b[:n])) - - t = transform.RemoveFunc(func(r rune) bool { - return !unicode.Is(unicode.Latin, r) - }) - n, _, _ = t.Transform(b, input, true) - fmt.Println(string(b[:n])) - - n, _, _ = t.Transform(b, norm.NFD.Bytes(input), true) - fmt.Println(string(b[:n])) - - // Output: - // tschüß;досвидания - // tschüß - // tschuß -} diff --git a/vendor/golang.org/x/text/transform/transform_test.go b/vendor/golang.org/x/text/transform/transform_test.go deleted file mode 100644 index 771633d1d9..0000000000 --- a/vendor/golang.org/x/text/transform/transform_test.go +++ /dev/null @@ -1,1317 +0,0 @@ -// Copyright 2013 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 transform - -import ( - "bytes" - "errors" - "fmt" - "io/ioutil" - "strconv" - "strings" - "testing" - "time" - "unicode/utf8" - - "golang.org/x/text/internal/testtext" -) - -type lowerCaseASCII struct{ NopResetter } - -func (lowerCaseASCII) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - n := len(src) - if n > len(dst) { - n, err = len(dst), ErrShortDst - } - for i, c := range src[:n] { - if 'A' <= c && c <= 'Z' { - c += 'a' - 'A' - } - dst[i] = c - } - return n, n, err -} - -// lowerCaseASCIILookahead lowercases the string and reports ErrShortSrc as long -// as the input is not atEOF. -type lowerCaseASCIILookahead struct{ NopResetter } - -func (lowerCaseASCIILookahead) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - n := len(src) - if n > len(dst) { - n, err = len(dst), ErrShortDst - } - for i, c := range src[:n] { - if 'A' <= c && c <= 'Z' { - c += 'a' - 'A' - } - dst[i] = c - } - if !atEOF { - err = ErrShortSrc - } - return n, n, err -} - -var errYouMentionedX = errors.New("you mentioned X") - -type dontMentionX struct{ NopResetter } - -func (dontMentionX) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - n := len(src) - if n > len(dst) { - n, err = len(dst), ErrShortDst - } - for i, c := range src[:n] { - if c == 'X' { - return i, i, errYouMentionedX - } - dst[i] = c - } - return n, n, err -} - -var errAtEnd = errors.New("error after all text") - -type errorAtEnd struct{ NopResetter } - -func (errorAtEnd) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - n := copy(dst, src) - if n < len(src) { - return n, n, ErrShortDst - } - if atEOF { - return n, n, errAtEnd - } - return n, n, nil -} - -type replaceWithConstant struct { - replacement string - written int -} - -func (t *replaceWithConstant) Reset() { - t.written = 0 -} - -func (t *replaceWithConstant) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - if atEOF { - nDst = copy(dst, t.replacement[t.written:]) - t.written += nDst - if t.written < len(t.replacement) { - err = ErrShortDst - } - } - return nDst, len(src), err -} - -type addAnXAtTheEnd struct{ NopResetter } - -func (addAnXAtTheEnd) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - n := copy(dst, src) - if n < len(src) { - return n, n, ErrShortDst - } - if !atEOF { - return n, n, nil - } - if len(dst) == n { - return n, n, ErrShortDst - } - dst[n] = 'X' - return n + 1, n, nil -} - -// doublerAtEOF is a strange Transformer that transforms "this" to "tthhiiss", -// but only if atEOF is true. -type doublerAtEOF struct{ NopResetter } - -func (doublerAtEOF) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - if !atEOF { - return 0, 0, ErrShortSrc - } - for i, c := range src { - if 2*i+2 >= len(dst) { - return 2 * i, i, ErrShortDst - } - dst[2*i+0] = c - dst[2*i+1] = c - } - return 2 * len(src), len(src), nil -} - -// rleDecode and rleEncode implement a toy run-length encoding: "aabbbbbbbbbb" -// is encoded as "2a10b". The decoding is assumed to not contain any numbers. - -type rleDecode struct{ NopResetter } - -func (rleDecode) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { -loop: - for len(src) > 0 { - n := 0 - for i, c := range src { - if '0' <= c && c <= '9' { - n = 10*n + int(c-'0') - continue - } - if i == 0 { - return nDst, nSrc, errors.New("rleDecode: bad input") - } - if n > len(dst) { - return nDst, nSrc, ErrShortDst - } - for j := 0; j < n; j++ { - dst[j] = c - } - dst, src = dst[n:], src[i+1:] - nDst, nSrc = nDst+n, nSrc+i+1 - continue loop - } - if atEOF { - return nDst, nSrc, errors.New("rleDecode: bad input") - } - return nDst, nSrc, ErrShortSrc - } - return nDst, nSrc, nil -} - -type rleEncode struct { - NopResetter - - // allowStutter means that "xxxxxxxx" can be encoded as "5x3x" - // instead of always as "8x". - allowStutter bool -} - -func (e rleEncode) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - for len(src) > 0 { - n, c0 := len(src), src[0] - for i, c := range src[1:] { - if c != c0 { - n = i + 1 - break - } - } - if n == len(src) && !atEOF && !e.allowStutter { - return nDst, nSrc, ErrShortSrc - } - s := strconv.Itoa(n) - if len(s) >= len(dst) { - return nDst, nSrc, ErrShortDst - } - copy(dst, s) - dst[len(s)] = c0 - dst, src = dst[len(s)+1:], src[n:] - nDst, nSrc = nDst+len(s)+1, nSrc+n - } - return nDst, nSrc, nil -} - -// trickler consumes all input bytes, but writes a single byte at a time to dst. -type trickler []byte - -func (t *trickler) Reset() { - *t = nil -} - -func (t *trickler) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - *t = append(*t, src...) - if len(*t) == 0 { - return 0, 0, nil - } - if len(dst) == 0 { - return 0, len(src), ErrShortDst - } - dst[0] = (*t)[0] - *t = (*t)[1:] - if len(*t) > 0 { - err = ErrShortDst - } - return 1, len(src), err -} - -// delayedTrickler is like trickler, but delays writing output to dst. This is -// highly unlikely to be relevant in practice, but it seems like a good idea -// to have some tolerance as long as progress can be detected. -type delayedTrickler []byte - -func (t *delayedTrickler) Reset() { - *t = nil -} - -func (t *delayedTrickler) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error) { - if len(*t) > 0 && len(dst) > 0 { - dst[0] = (*t)[0] - *t = (*t)[1:] - nDst = 1 - } - *t = append(*t, src...) - if len(*t) > 0 { - err = ErrShortDst - } - return nDst, len(src), err -} - -type testCase struct { - desc string - t Transformer - src string - dstSize int - srcSize int - ioSize int - wantStr string - wantErr error - wantIter int // number of iterations taken; 0 means we don't care. -} - -func (t testCase) String() string { - return tstr(t.t) + "; " + t.desc -} - -func tstr(t Transformer) string { - if stringer, ok := t.(fmt.Stringer); ok { - return stringer.String() - } - s := fmt.Sprintf("%T", t) - return s[1+strings.Index(s, "."):] -} - -func (c chain) String() string { - buf := &bytes.Buffer{} - buf.WriteString("Chain(") - for i, l := range c.link[:len(c.link)-1] { - if i != 0 { - fmt.Fprint(buf, ", ") - } - buf.WriteString(tstr(l.t)) - } - buf.WriteString(")") - return buf.String() -} - -var testCases = []testCase{ - { - desc: "empty", - t: lowerCaseASCII{}, - src: "", - dstSize: 100, - srcSize: 100, - wantStr: "", - }, - - { - desc: "basic", - t: lowerCaseASCII{}, - src: "Hello WORLD.", - dstSize: 100, - srcSize: 100, - wantStr: "hello world.", - }, - - { - desc: "small dst", - t: lowerCaseASCII{}, - src: "Hello WORLD.", - dstSize: 3, - srcSize: 100, - wantStr: "hello world.", - }, - - { - desc: "small src", - t: lowerCaseASCII{}, - src: "Hello WORLD.", - dstSize: 100, - srcSize: 4, - wantStr: "hello world.", - }, - - { - desc: "small buffers", - t: lowerCaseASCII{}, - src: "Hello WORLD.", - dstSize: 3, - srcSize: 4, - wantStr: "hello world.", - }, - - { - desc: "very small buffers", - t: lowerCaseASCII{}, - src: "Hello WORLD.", - dstSize: 1, - srcSize: 1, - wantStr: "hello world.", - }, - - { - desc: "small dst with lookahead", - t: lowerCaseASCIILookahead{}, - src: "Hello WORLD.", - dstSize: 3, - srcSize: 100, - wantStr: "hello world.", - }, - - { - desc: "small src with lookahead", - t: lowerCaseASCIILookahead{}, - src: "Hello WORLD.", - dstSize: 100, - srcSize: 4, - wantStr: "hello world.", - }, - - { - desc: "small buffers with lookahead", - t: lowerCaseASCIILookahead{}, - src: "Hello WORLD.", - dstSize: 3, - srcSize: 4, - wantStr: "hello world.", - }, - - { - desc: "very small buffers with lookahead", - t: lowerCaseASCIILookahead{}, - src: "Hello WORLD.", - dstSize: 1, - srcSize: 2, - wantStr: "hello world.", - }, - - { - desc: "user error", - t: dontMentionX{}, - src: "The First Rule of Transform Club: don't mention Mister X, ever.", - dstSize: 100, - srcSize: 100, - wantStr: "The First Rule of Transform Club: don't mention Mister ", - wantErr: errYouMentionedX, - }, - - { - desc: "user error at end", - t: errorAtEnd{}, - src: "All goes well until it doesn't.", - dstSize: 100, - srcSize: 100, - wantStr: "All goes well until it doesn't.", - wantErr: errAtEnd, - }, - - { - desc: "user error at end, incremental", - t: errorAtEnd{}, - src: "All goes well until it doesn't.", - dstSize: 10, - srcSize: 10, - wantStr: "All goes well until it doesn't.", - wantErr: errAtEnd, - }, - - { - desc: "replace entire non-empty string with one byte", - t: &replaceWithConstant{replacement: "X"}, - src: "none of this will be copied", - dstSize: 1, - srcSize: 10, - wantStr: "X", - }, - - { - desc: "replace entire empty string with one byte", - t: &replaceWithConstant{replacement: "X"}, - src: "", - dstSize: 1, - srcSize: 10, - wantStr: "X", - }, - - { - desc: "replace entire empty string with seven bytes", - t: &replaceWithConstant{replacement: "ABCDEFG"}, - src: "", - dstSize: 3, - srcSize: 10, - wantStr: "ABCDEFG", - }, - - { - desc: "add an X (initialBufSize-1)", - t: addAnXAtTheEnd{}, - src: aaa[:initialBufSize-1], - dstSize: 10, - srcSize: 10, - wantStr: aaa[:initialBufSize-1] + "X", - }, - - { - desc: "add an X (initialBufSize+0)", - t: addAnXAtTheEnd{}, - src: aaa[:initialBufSize+0], - dstSize: 10, - srcSize: 10, - wantStr: aaa[:initialBufSize+0] + "X", - }, - - { - desc: "add an X (initialBufSize+1)", - t: addAnXAtTheEnd{}, - src: aaa[:initialBufSize+1], - dstSize: 10, - srcSize: 10, - wantStr: aaa[:initialBufSize+1] + "X", - }, - - { - desc: "small buffers", - t: dontMentionX{}, - src: "The First Rule of Transform Club: don't mention Mister X, ever.", - dstSize: 10, - srcSize: 10, - wantStr: "The First Rule of Transform Club: don't mention Mister ", - wantErr: errYouMentionedX, - }, - - { - desc: "very small buffers", - t: dontMentionX{}, - src: "The First Rule of Transform Club: don't mention Mister X, ever.", - dstSize: 1, - srcSize: 1, - wantStr: "The First Rule of Transform Club: don't mention Mister ", - wantErr: errYouMentionedX, - }, - - { - desc: "only transform at EOF", - t: doublerAtEOF{}, - src: "this", - dstSize: 100, - srcSize: 100, - wantStr: "tthhiiss", - }, - - { - desc: "basic", - t: rleDecode{}, - src: "1a2b3c10d11e0f1g", - dstSize: 100, - srcSize: 100, - wantStr: "abbcccddddddddddeeeeeeeeeeeg", - }, - - { - desc: "long", - t: rleDecode{}, - src: "12a23b34c45d56e99z", - dstSize: 100, - srcSize: 100, - wantStr: strings.Repeat("a", 12) + - strings.Repeat("b", 23) + - strings.Repeat("c", 34) + - strings.Repeat("d", 45) + - strings.Repeat("e", 56) + - strings.Repeat("z", 99), - }, - - { - desc: "tight buffers", - t: rleDecode{}, - src: "1a2b3c10d11e0f1g", - dstSize: 11, - srcSize: 3, - wantStr: "abbcccddddddddddeeeeeeeeeeeg", - }, - - { - desc: "short dst", - t: rleDecode{}, - src: "1a2b3c10d11e0f1g", - dstSize: 10, - srcSize: 3, - wantStr: "abbcccdddddddddd", - wantErr: ErrShortDst, - }, - - { - desc: "short src", - t: rleDecode{}, - src: "1a2b3c10d11e0f1g", - dstSize: 11, - srcSize: 2, - ioSize: 2, - wantStr: "abbccc", - wantErr: ErrShortSrc, - }, - - { - desc: "basic", - t: rleEncode{}, - src: "abbcccddddddddddeeeeeeeeeeeg", - dstSize: 100, - srcSize: 100, - wantStr: "1a2b3c10d11e1g", - }, - - { - desc: "long", - t: rleEncode{}, - src: strings.Repeat("a", 12) + - strings.Repeat("b", 23) + - strings.Repeat("c", 34) + - strings.Repeat("d", 45) + - strings.Repeat("e", 56) + - strings.Repeat("z", 99), - dstSize: 100, - srcSize: 100, - wantStr: "12a23b34c45d56e99z", - }, - - { - desc: "tight buffers", - t: rleEncode{}, - src: "abbcccddddddddddeeeeeeeeeeeg", - dstSize: 3, - srcSize: 12, - wantStr: "1a2b3c10d11e1g", - }, - - { - desc: "short dst", - t: rleEncode{}, - src: "abbcccddddddddddeeeeeeeeeeeg", - dstSize: 2, - srcSize: 12, - wantStr: "1a2b3c", - wantErr: ErrShortDst, - }, - - { - desc: "short src", - t: rleEncode{}, - src: "abbcccddddddddddeeeeeeeeeeeg", - dstSize: 3, - srcSize: 11, - ioSize: 11, - wantStr: "1a2b3c10d", - wantErr: ErrShortSrc, - }, - - { - desc: "allowStutter = false", - t: rleEncode{allowStutter: false}, - src: "aaaabbbbbbbbccccddddd", - dstSize: 10, - srcSize: 10, - wantStr: "4a8b4c5d", - }, - - { - desc: "allowStutter = true", - t: rleEncode{allowStutter: true}, - src: "aaaabbbbbbbbccccddddd", - dstSize: 10, - srcSize: 10, - ioSize: 10, - wantStr: "4a6b2b4c4d1d", - }, - - { - desc: "trickler", - t: &trickler{}, - src: "abcdefghijklm", - dstSize: 3, - srcSize: 15, - wantStr: "abcdefghijklm", - }, - - { - desc: "delayedTrickler", - t: &delayedTrickler{}, - src: "abcdefghijklm", - dstSize: 3, - srcSize: 15, - wantStr: "abcdefghijklm", - }, -} - -func TestReader(t *testing.T) { - for _, tc := range testCases { - testtext.Run(t, tc.desc, func(t *testing.T) { - r := NewReader(strings.NewReader(tc.src), tc.t) - // Differently sized dst and src buffers are not part of the - // exported API. We override them manually. - r.dst = make([]byte, tc.dstSize) - r.src = make([]byte, tc.srcSize) - got, err := ioutil.ReadAll(r) - str := string(got) - if str != tc.wantStr || err != tc.wantErr { - t.Errorf("\ngot %q, %v\nwant %q, %v", str, err, tc.wantStr, tc.wantErr) - } - }) - } -} - -func TestWriter(t *testing.T) { - tests := append(testCases, chainTests()...) - for _, tc := range tests { - sizes := []int{1, 2, 3, 4, 5, 10, 100, 1000} - if tc.ioSize > 0 { - sizes = []int{tc.ioSize} - } - for _, sz := range sizes { - testtext.Run(t, fmt.Sprintf("%s/%d", tc.desc, sz), func(t *testing.T) { - bb := &bytes.Buffer{} - w := NewWriter(bb, tc.t) - // Differently sized dst and src buffers are not part of the - // exported API. We override them manually. - w.dst = make([]byte, tc.dstSize) - w.src = make([]byte, tc.srcSize) - src := make([]byte, sz) - var err error - for b := tc.src; len(b) > 0 && err == nil; { - n := copy(src, b) - b = b[n:] - m := 0 - m, err = w.Write(src[:n]) - if m != n && err == nil { - t.Errorf("did not consume all bytes %d < %d", m, n) - } - } - if err == nil { - err = w.Close() - } - str := bb.String() - if str != tc.wantStr || err != tc.wantErr { - t.Errorf("\ngot %q, %v\nwant %q, %v", str, err, tc.wantStr, tc.wantErr) - } - }) - } - } -} - -func TestNop(t *testing.T) { - testCases := []struct { - str string - dstSize int - err error - }{ - {"", 0, nil}, - {"", 10, nil}, - {"a", 0, ErrShortDst}, - {"a", 1, nil}, - {"a", 10, nil}, - } - for i, tc := range testCases { - dst := make([]byte, tc.dstSize) - nDst, nSrc, err := Nop.Transform(dst, []byte(tc.str), true) - want := tc.str - if tc.dstSize < len(want) { - want = want[:tc.dstSize] - } - if got := string(dst[:nDst]); got != want || err != tc.err || nSrc != nDst { - t.Errorf("%d:\ngot %q, %d, %v\nwant %q, %d, %v", i, got, nSrc, err, want, nDst, tc.err) - } - } -} - -func TestDiscard(t *testing.T) { - testCases := []struct { - str string - dstSize int - }{ - {"", 0}, - {"", 10}, - {"a", 0}, - {"ab", 10}, - } - for i, tc := range testCases { - nDst, nSrc, err := Discard.Transform(make([]byte, tc.dstSize), []byte(tc.str), true) - if nDst != 0 || nSrc != len(tc.str) || err != nil { - t.Errorf("%d:\ngot %q, %d, %v\nwant 0, %d, nil", i, nDst, nSrc, err, len(tc.str)) - } - } -} - -// mkChain creates a Chain transformer. x must be alternating between transformer -// and bufSize, like T, (sz, T)* -func mkChain(x ...interface{}) *chain { - t := []Transformer{} - for i := 0; i < len(x); i += 2 { - t = append(t, x[i].(Transformer)) - } - c := Chain(t...).(*chain) - for i, j := 1, 1; i < len(x); i, j = i+2, j+1 { - c.link[j].b = make([]byte, x[i].(int)) - } - return c -} - -func chainTests() []testCase { - return []testCase{ - { - desc: "nil error", - t: mkChain(rleEncode{}, 100, lowerCaseASCII{}), - src: "ABB", - dstSize: 100, - srcSize: 100, - wantStr: "1a2b", - wantErr: nil, - wantIter: 1, - }, - - { - desc: "short dst buffer", - t: mkChain(lowerCaseASCII{}, 3, rleDecode{}), - src: "1a2b3c10d11e0f1g", - dstSize: 10, - srcSize: 3, - wantStr: "abbcccdddddddddd", - wantErr: ErrShortDst, - }, - - { - desc: "short internal dst buffer", - t: mkChain(lowerCaseASCII{}, 3, rleDecode{}, 10, Nop), - src: "1a2b3c10d11e0f1g", - dstSize: 100, - srcSize: 3, - wantStr: "abbcccdddddddddd", - wantErr: errShortInternal, - }, - - { - desc: "short internal dst buffer from input", - t: mkChain(rleDecode{}, 10, Nop), - src: "1a2b3c10d11e0f1g", - dstSize: 100, - srcSize: 3, - wantStr: "abbcccdddddddddd", - wantErr: errShortInternal, - }, - - { - desc: "empty short internal dst buffer", - t: mkChain(lowerCaseASCII{}, 3, rleDecode{}, 10, Nop), - src: "4a7b11e0f1g", - dstSize: 100, - srcSize: 3, - wantStr: "aaaabbbbbbb", - wantErr: errShortInternal, - }, - - { - desc: "empty short internal dst buffer from input", - t: mkChain(rleDecode{}, 10, Nop), - src: "4a7b11e0f1g", - dstSize: 100, - srcSize: 3, - wantStr: "aaaabbbbbbb", - wantErr: errShortInternal, - }, - - { - desc: "short internal src buffer after full dst buffer", - t: mkChain(Nop, 5, rleEncode{}, 10, Nop), - src: "cccccddddd", - dstSize: 100, - srcSize: 100, - wantStr: "", - wantErr: errShortInternal, - wantIter: 1, - }, - - { - desc: "short internal src buffer after short dst buffer; test lastFull", - t: mkChain(rleDecode{}, 5, rleEncode{}, 4, Nop), - src: "2a1b4c6d", - dstSize: 100, - srcSize: 100, - wantStr: "2a1b", - wantErr: errShortInternal, - }, - - { - desc: "short internal src buffer after successful complete fill", - t: mkChain(Nop, 3, rleDecode{}), - src: "123a4b", - dstSize: 4, - srcSize: 3, - wantStr: "", - wantErr: errShortInternal, - wantIter: 1, - }, - - { - desc: "short internal src buffer after short dst buffer; test lastFull", - t: mkChain(rleDecode{}, 5, rleEncode{}), - src: "2a1b4c6d", - dstSize: 4, - srcSize: 100, - wantStr: "2a1b", - wantErr: errShortInternal, - }, - - { - desc: "short src buffer", - t: mkChain(rleEncode{}, 5, Nop), - src: "abbcccddddeeeee", - dstSize: 4, - srcSize: 4, - ioSize: 4, - wantStr: "1a2b3c", - wantErr: ErrShortSrc, - }, - - { - desc: "process all in one go", - t: mkChain(rleEncode{}, 5, Nop), - src: "abbcccddddeeeeeffffff", - dstSize: 100, - srcSize: 100, - wantStr: "1a2b3c4d5e6f", - wantErr: nil, - wantIter: 1, - }, - - { - desc: "complete processing downstream after error", - t: mkChain(dontMentionX{}, 2, rleDecode{}, 5, Nop), - src: "3a4b5eX", - dstSize: 100, - srcSize: 100, - ioSize: 100, - wantStr: "aaabbbbeeeee", - wantErr: errYouMentionedX, - }, - - { - desc: "return downstream fatal errors first (followed by short dst)", - t: mkChain(dontMentionX{}, 8, rleDecode{}, 4, Nop), - src: "3a4b5eX", - dstSize: 100, - srcSize: 100, - ioSize: 100, - wantStr: "aaabbbb", - wantErr: errShortInternal, - }, - - { - desc: "return downstream fatal errors first (followed by short src)", - t: mkChain(dontMentionX{}, 5, Nop, 1, rleDecode{}), - src: "1a5bX", - dstSize: 100, - srcSize: 100, - ioSize: 100, - wantStr: "", - wantErr: errShortInternal, - }, - - { - desc: "short internal", - t: mkChain(Nop, 11, rleEncode{}, 3, Nop), - src: "abbcccddddddddddeeeeeeeeeeeg", - dstSize: 3, - srcSize: 100, - wantStr: "1a2b3c10d", - wantErr: errShortInternal, - }, - } -} - -func doTransform(tc testCase) (res string, iter int, err error) { - tc.t.Reset() - dst := make([]byte, tc.dstSize) - out, in := make([]byte, 0, 2*len(tc.src)), []byte(tc.src) - for { - iter++ - src, atEOF := in, true - if len(src) > tc.srcSize { - src, atEOF = src[:tc.srcSize], false - } - nDst, nSrc, err := tc.t.Transform(dst, src, atEOF) - out = append(out, dst[:nDst]...) - in = in[nSrc:] - switch { - case err == nil && len(in) != 0: - case err == ErrShortSrc && nSrc > 0: - case err == ErrShortDst && (nDst > 0 || nSrc > 0): - default: - return string(out), iter, err - } - } -} - -func TestChain(t *testing.T) { - if c, ok := Chain().(nop); !ok { - t.Errorf("empty chain: %v; want Nop", c) - } - - // Test Chain for a single Transformer. - for _, tc := range testCases { - tc.t = Chain(tc.t) - str, _, err := doTransform(tc) - if str != tc.wantStr || err != tc.wantErr { - t.Errorf("%s:\ngot %q, %v\nwant %q, %v", tc, str, err, tc.wantStr, tc.wantErr) - } - } - - tests := chainTests() - sizes := []int{1, 2, 3, 4, 5, 7, 10, 100, 1000} - addTest := func(tc testCase, t *chain) { - if t.link[0].t != tc.t && tc.wantErr == ErrShortSrc { - tc.wantErr = errShortInternal - } - if t.link[len(t.link)-2].t != tc.t && tc.wantErr == ErrShortDst { - tc.wantErr = errShortInternal - } - tc.t = t - tests = append(tests, tc) - } - for _, tc := range testCases { - for _, sz := range sizes { - tt := tc - tt.dstSize = sz - addTest(tt, mkChain(tc.t, tc.dstSize, Nop)) - addTest(tt, mkChain(tc.t, tc.dstSize, Nop, 2, Nop)) - addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop)) - if sz >= tc.dstSize && (tc.wantErr != ErrShortDst || sz == tc.dstSize) { - addTest(tt, mkChain(Nop, tc.srcSize, tc.t)) - addTest(tt, mkChain(Nop, 100, Nop, tc.srcSize, tc.t)) - } - } - } - for _, tc := range testCases { - tt := tc - tt.dstSize = 1 - tt.wantStr = "" - addTest(tt, mkChain(tc.t, tc.dstSize, Discard)) - addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Discard)) - addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, tc.dstSize, Discard)) - } - for _, tc := range testCases { - tt := tc - tt.dstSize = 100 - tt.wantStr = strings.Replace(tc.src, "0f", "", -1) - // Chain encoders and decoders. - if _, ok := tc.t.(rleEncode); ok && tc.wantErr == nil { - addTest(tt, mkChain(tc.t, tc.dstSize, Nop, 1000, rleDecode{})) - addTest(tt, mkChain(tc.t, tc.dstSize, Nop, tc.dstSize, rleDecode{})) - addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 100, rleDecode{})) - // decoding needs larger destinations - addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, rleDecode{}, 100, Nop)) - addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 100, rleDecode{}, 100, Nop)) - } else if _, ok := tc.t.(rleDecode); ok && tc.wantErr == nil { - // The internal buffer size may need to be the sum of the maximum segment - // size of the two encoders! - addTest(tt, mkChain(tc.t, 2*tc.dstSize, rleEncode{})) - addTest(tt, mkChain(tc.t, tc.dstSize, Nop, 101, rleEncode{})) - addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 100, rleEncode{})) - addTest(tt, mkChain(Nop, tc.srcSize, tc.t, tc.dstSize, Nop, 200, rleEncode{}, 100, Nop)) - } - } - for _, tc := range tests { - str, iter, err := doTransform(tc) - mi := tc.wantIter != 0 && tc.wantIter != iter - if str != tc.wantStr || err != tc.wantErr || mi { - t.Errorf("%s:\ngot iter:%d, %q, %v\nwant iter:%d, %q, %v", tc, iter, str, err, tc.wantIter, tc.wantStr, tc.wantErr) - } - break - } -} - -func TestRemoveFunc(t *testing.T) { - filter := RemoveFunc(func(r rune) bool { - return strings.IndexRune("ab\u0300\u1234,", r) != -1 - }) - tests := []testCase{ - { - src: ",", - wantStr: "", - }, - - { - src: "c", - wantStr: "c", - }, - - { - src: "\u2345", - wantStr: "\u2345", - }, - - { - src: "tschüß", - wantStr: "tschüß", - }, - - { - src: ",до,свидания,", - wantStr: "досвидания", - }, - - { - src: "a\xbd\xb2=\xbc ⌘", - wantStr: "\uFFFD\uFFFD=\uFFFD ⌘", - }, - - { - // If we didn't replace illegal bytes with RuneError, the result - // would be \u0300 or the code would need to be more complex. - src: "\xcc\u0300\x80", - wantStr: "\uFFFD\uFFFD", - }, - - { - src: "\xcc\u0300\x80", - dstSize: 3, - wantStr: "\uFFFD\uFFFD", - wantIter: 2, - }, - - { - // Test a long buffer greater than the internal buffer size - src: "hello\xcc\xcc\xccworld", - srcSize: 13, - wantStr: "hello\uFFFD\uFFFD\uFFFDworld", - wantIter: 1, - }, - - { - src: "\u2345", - dstSize: 2, - wantStr: "", - wantErr: ErrShortDst, - }, - - { - src: "\xcc", - dstSize: 2, - wantStr: "", - wantErr: ErrShortDst, - }, - - { - src: "\u0300", - dstSize: 2, - srcSize: 1, - wantStr: "", - wantErr: ErrShortSrc, - }, - - { - t: RemoveFunc(func(r rune) bool { - return r == utf8.RuneError - }), - src: "\xcc\u0300\x80", - wantStr: "\u0300", - }, - } - - for _, tc := range tests { - tc.desc = tc.src - if tc.t == nil { - tc.t = filter - } - if tc.dstSize == 0 { - tc.dstSize = 100 - } - if tc.srcSize == 0 { - tc.srcSize = 100 - } - str, iter, err := doTransform(tc) - mi := tc.wantIter != 0 && tc.wantIter != iter - if str != tc.wantStr || err != tc.wantErr || mi { - t.Errorf("%+q:\ngot iter:%d, %+q, %v\nwant iter:%d, %+q, %v", tc.src, iter, str, err, tc.wantIter, tc.wantStr, tc.wantErr) - } - - tc.src = str - idem, _, _ := doTransform(tc) - if str != idem { - t.Errorf("%+q: found %+q; want %+q", tc.src, idem, str) - } - } -} - -func testString(t *testing.T, f func(Transformer, string) (string, int, error)) { - for _, tt := range append(testCases, chainTests()...) { - if tt.desc == "allowStutter = true" { - // We don't have control over the buffer size, so we eliminate tests - // that depend on a specific buffer size being set. - continue - } - if tt.wantErr == ErrShortDst || tt.wantErr == ErrShortSrc { - // The result string will be different. - continue - } - testtext.Run(t, tt.desc, func(t *testing.T) { - got, n, err := f(tt.t, tt.src) - if tt.wantErr != err { - t.Errorf("error: got %v; want %v", err, tt.wantErr) - } - // Check that err == nil implies that n == len(tt.src). Note that vice - // versa isn't necessarily true. - if err == nil && n != len(tt.src) { - t.Errorf("err == nil: got %d bytes, want %d", n, err) - } - if got != tt.wantStr { - t.Errorf("string: got %q; want %q", got, tt.wantStr) - } - }) - } -} - -func TestBytes(t *testing.T) { - testString(t, func(z Transformer, s string) (string, int, error) { - b, n, err := Bytes(z, []byte(s)) - return string(b), n, err - }) -} - -func TestAppend(t *testing.T) { - // Create a bunch of subtests for different buffer sizes. - testCases := [][]byte{ - nil, - make([]byte, 0, 0), - make([]byte, 0, 1), - make([]byte, 1, 1), - make([]byte, 1, 5), - make([]byte, 100, 100), - make([]byte, 100, 200), - } - for _, tc := range testCases { - testString(t, func(z Transformer, s string) (string, int, error) { - b, n, err := Append(z, tc, []byte(s)) - return string(b[len(tc):]), n, err - }) - } -} - -func TestString(t *testing.T) { - testtext.Run(t, "transform", func(t *testing.T) { testString(t, String) }) - - // Overrun the internal destination buffer. - for i, s := range []string{ - aaa[:1*initialBufSize-1], - aaa[:1*initialBufSize+0], - aaa[:1*initialBufSize+1], - AAA[:1*initialBufSize-1], - AAA[:1*initialBufSize+0], - AAA[:1*initialBufSize+1], - AAA[:2*initialBufSize-1], - AAA[:2*initialBufSize+0], - AAA[:2*initialBufSize+1], - aaa[:1*initialBufSize-2] + "A", - aaa[:1*initialBufSize-1] + "A", - aaa[:1*initialBufSize+0] + "A", - aaa[:1*initialBufSize+1] + "A", - } { - testtext.Run(t, fmt.Sprint("dst buffer test using lower/", i), func(t *testing.T) { - got, _, _ := String(lowerCaseASCII{}, s) - if want := strings.ToLower(s); got != want { - t.Errorf("got %s (%d); want %s (%d)", got, len(got), want, len(want)) - } - }) - } - - // Overrun the internal source buffer. - for i, s := range []string{ - aaa[:1*initialBufSize-1], - aaa[:1*initialBufSize+0], - aaa[:1*initialBufSize+1], - aaa[:2*initialBufSize+1], - aaa[:2*initialBufSize+0], - aaa[:2*initialBufSize+1], - } { - testtext.Run(t, fmt.Sprint("src buffer test using rleEncode/", i), func(t *testing.T) { - got, _, _ := String(rleEncode{}, s) - if want := fmt.Sprintf("%da", len(s)); got != want { - t.Errorf("got %s (%d); want %s (%d)", got, len(got), want, len(want)) - } - }) - } - - // Test allocations for non-changing strings. - // Note we still need to allocate a single buffer. - for i, s := range []string{ - "", - "123456789", - aaa[:initialBufSize-1], - aaa[:initialBufSize+0], - aaa[:initialBufSize+1], - aaa[:10*initialBufSize], - } { - testtext.Run(t, fmt.Sprint("alloc/", i), func(t *testing.T) { - if n := testtext.AllocsPerRun(5, func() { String(&lowerCaseASCIILookahead{}, s) }); n > 1 { - t.Errorf("#allocs was %f; want 1", n) - } - }) - } -} - -// TestBytesAllocation tests that buffer growth stays limited with the trickler -// transformer, which behaves oddly but within spec. In case buffer growth is -// not correctly handled, the test will either panic with a failed allocation or -// thrash. To ensure the tests terminate under the last condition, we time out -// after some sufficiently long period of time. -func TestBytesAllocation(t *testing.T) { - done := make(chan bool) - go func() { - in := bytes.Repeat([]byte{'a'}, 1000) - tr := trickler(make([]byte, 1)) - Bytes(&tr, in) - done <- true - }() - select { - case <-done: - case <-time.After(3 * time.Second): - t.Error("time out, likely due to excessive allocation") - } -} - -// TestStringAllocation tests that buffer growth stays limited with the trickler -// transformer, which behaves oddly but within spec. In case buffer growth is -// not correctly handled, the test will either panic with a failed allocation or -// thrash. To ensure the tests terminate under the last condition, we time out -// after some sufficiently long period of time. -func TestStringAllocation(t *testing.T) { - done := make(chan bool) - go func() { - tr := trickler(make([]byte, 1)) - String(&tr, aaa[:1000]) - done <- true - }() - select { - case <-done: - case <-time.After(3 * time.Second): - t.Error("time out, likely due to excessive allocation") - } -} - -func BenchmarkStringLowerEmpty(b *testing.B) { - for i := 0; i < b.N; i++ { - String(&lowerCaseASCIILookahead{}, "") - } -} - -func BenchmarkStringLowerIdentical(b *testing.B) { - for i := 0; i < b.N; i++ { - String(&lowerCaseASCIILookahead{}, aaa[:4096]) - } -} - -func BenchmarkStringLowerChanged(b *testing.B) { - for i := 0; i < b.N; i++ { - String(&lowerCaseASCIILookahead{}, AAA[:4096]) - } -} - -var ( - aaa = strings.Repeat("a", 4096) - AAA = strings.Repeat("A", 4096) -) diff --git a/vendor/golang.org/x/text/unicode/bidi/core_test.go b/vendor/golang.org/x/text/unicode/bidi/core_test.go deleted file mode 100644 index f28d386c8d..0000000000 --- a/vendor/golang.org/x/text/unicode/bidi/core_test.go +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2015 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 bidi - -import ( - "flag" - "fmt" - "log" - "strconv" - "strings" - "testing" - - "golang.org/x/text/internal/gen" - "golang.org/x/text/internal/testtext" - "golang.org/x/text/internal/ucd" - "golang.org/x/text/unicode/norm" -) - -var testLevels = flag.Bool("levels", false, "enable testing of levels") - -// TestBidiCore performs the tests in BidiTest.txt. -// See http://www.unicode.org/Public/UCD/latest/ucd/BidiTest.txt. -func TestBidiCore(t *testing.T) { - testtext.SkipIfNotLong(t) - - r := gen.OpenUCDFile("BidiTest.txt") - defer r.Close() - - var wantLevels, wantOrder []string - p := ucd.New(r, ucd.Part(func(p *ucd.Parser) { - s := strings.Split(p.String(0), ":") - switch s[0] { - case "Levels": - wantLevels = strings.Fields(s[1]) - case "Reorder": - wantOrder = strings.Fields(s[1]) - default: - log.Fatalf("Unknown part %q.", s[0]) - } - })) - - for p.Next() { - types := []Class{} - for _, s := range p.Strings(0) { - types = append(types, bidiClass[s]) - } - // We ignore the bracketing part of the algorithm. - pairTypes := make([]bracketType, len(types)) - pairValues := make([]rune, len(types)) - - for i := uint(0); i < 3; i++ { - if p.Uint(1)&(1<<i) == 0 { - continue - } - lev := level(int(i) - 1) - par := newParagraph(types, pairTypes, pairValues, lev) - - if *testLevels { - levels := par.getLevels([]int{len(types)}) - for i, s := range wantLevels { - if s == "x" { - continue - } - l, _ := strconv.ParseUint(s, 10, 8) - if level(l)&1 != levels[i]&1 { - t.Errorf("%s:%d:levels: got %v; want %v", p.String(0), lev, levels, wantLevels) - break - } - } - } - - order := par.getReordering([]int{len(types)}) - gotOrder := filterOrder(types, order) - if got, want := fmt.Sprint(gotOrder), fmt.Sprint(wantOrder); got != want { - t.Errorf("%s:%d:order: got %v; want %v\noriginal %v", p.String(0), lev, got, want, order) - } - } - } - if err := p.Err(); err != nil { - log.Fatal(err) - } -} - -var removeClasses = map[Class]bool{ - LRO: true, - RLO: true, - RLE: true, - LRE: true, - PDF: true, - BN: true, -} - -// TestBidiCharacters performs the tests in BidiCharacterTest.txt. -// See http://www.unicode.org/Public/UCD/latest/ucd/BidiCharacterTest.txt -func TestBidiCharacters(t *testing.T) { - testtext.SkipIfNotLong(t) - - ucd.Parse(gen.OpenUCDFile("BidiCharacterTest.txt"), func(p *ucd.Parser) { - var ( - types []Class - pairTypes []bracketType - pairValues []rune - parLevel level - - wantLevel = level(p.Int(2)) - wantLevels = p.Strings(3) - wantVisualOrder = p.Strings(4) - ) - - switch l := p.Int(1); l { - case 0, 1: - parLevel = level(l) - case 2: - parLevel = implicitLevel - default: - // Spec says to ignore unknown parts. - } - - runes := p.Runes(0) - - for _, r := range runes { - // Assign the bracket type. - if d := norm.NFKD.PropertiesString(string(r)).Decomposition(); d != nil { - r = []rune(string(d))[0] - } - p, _ := LookupRune(r) - - // Assign the class for this rune. - types = append(types, p.Class()) - - switch { - case !p.IsBracket(): - pairTypes = append(pairTypes, bpNone) - pairValues = append(pairValues, 0) - case p.IsOpeningBracket(): - pairTypes = append(pairTypes, bpOpen) - pairValues = append(pairValues, r) - default: - pairTypes = append(pairTypes, bpClose) - pairValues = append(pairValues, p.reverseBracket(r)) - } - } - par := newParagraph(types, pairTypes, pairValues, parLevel) - - // Test results: - if got := par.embeddingLevel; got != wantLevel { - t.Errorf("%v:level: got %d; want %d", string(runes), got, wantLevel) - } - - if *testLevels { - gotLevels := getLevelStrings(types, par.getLevels([]int{len(types)})) - if got, want := fmt.Sprint(gotLevels), fmt.Sprint(wantLevels); got != want { - t.Errorf("%04X %q:%d: got %v; want %v\nval: %x\npair: %v", runes, string(runes), parLevel, got, want, pairValues, pairTypes) - } - } - - order := par.getReordering([]int{len(types)}) - order = filterOrder(types, order) - if got, want := fmt.Sprint(order), fmt.Sprint(wantVisualOrder); got != want { - t.Errorf("%04X %q:%d: got %v; want %v\ngot order: %s", runes, string(runes), parLevel, got, want, reorder(runes, order)) - } - }) -} - -func getLevelStrings(cl []Class, levels []level) []string { - var results []string - for i, l := range levels { - if !removeClasses[cl[i]] { - results = append(results, fmt.Sprint(l)) - } else { - results = append(results, "x") - } - } - return results -} - -func filterOrder(cl []Class, order []int) []int { - no := []int{} - for _, o := range order { - if !removeClasses[cl[o]] { - no = append(no, o) - } - } - return no -} - -func reorder(r []rune, order []int) string { - nr := make([]rune, len(order)) - for i, o := range order { - nr[i] = r[o] - } - return string(nr) -} - -// bidiClass names and codes taken from class "bc" in -// http://www.unicode.org/Public/8.0.0/ucd/PropertyValueAliases.txt -var bidiClass = map[string]Class{ - "AL": AL, // classArabicLetter, - "AN": AN, // classArabicNumber, - "B": B, // classParagraphSeparator, - "BN": BN, // classBoundaryNeutral, - "CS": CS, // classCommonSeparator, - "EN": EN, // classEuropeanNumber, - "ES": ES, // classEuropeanSeparator, - "ET": ET, // classEuropeanTerminator, - "L": L, // classLeftToRight, - "NSM": NSM, // classNonspacingMark, - "ON": ON, // classOtherNeutral, - "R": R, // classRightToLeft, - "S": S, // classSegmentSeparator, - "WS": WS, // classWhiteSpace, - - "LRO": LRO, // classLeftToRightOverride, - "RLO": RLO, // classRightToLeftOverride, - "LRE": LRE, // classLeftToRightEmbedding, - "RLE": RLE, // classRightToLeftEmbedding, - "PDF": PDF, // classPopDirectionalFormat, - "LRI": LRI, // classLeftToRightIsolate, - "RLI": RLI, // classRightToLeftIsolate, - "FSI": FSI, // classFirstStrongIsolate, - "PDI": PDI, // classPopDirectionalIsolate, -} diff --git a/vendor/golang.org/x/text/unicode/bidi/gen.go b/vendor/golang.org/x/text/unicode/bidi/gen.go index 040f3013d5..4e1c7ba0bf 100644 --- a/vendor/golang.org/x/text/unicode/bidi/gen.go +++ b/vendor/golang.org/x/text/unicode/bidi/gen.go @@ -59,7 +59,7 @@ func genTables() { log.Fatalf("Too many Class constants (%#x > 0x0F).", numClass) } w := gen.NewCodeWriter() - defer w.WriteGoFile(*outputFile, "bidi") + defer w.WriteVersionedGoFile(*outputFile, "bidi") gen.WriteUnicodeVersion(w) diff --git a/vendor/golang.org/x/text/unicode/bidi/ranges_test.go b/vendor/golang.org/x/text/unicode/bidi/ranges_test.go deleted file mode 100644 index bfaecd502d..0000000000 --- a/vendor/golang.org/x/text/unicode/bidi/ranges_test.go +++ /dev/null @@ -1,53 +0,0 @@ -// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. - -package bidi - -import ( - "unicode" - - "golang.org/x/text/internal/gen" - "golang.org/x/text/internal/ucd" - "golang.org/x/text/unicode/rangetable" -) - -// These tables are hand-extracted from: -// http://www.unicode.org/Public/8.0.0/ucd/extracted/DerivedBidiClass.txt -func visitDefaults(fn func(r rune, c Class)) { - // first write default values for ranges listed above. - visitRunes(fn, AL, []rune{ - 0x0600, 0x07BF, // Arabic - 0x08A0, 0x08FF, // Arabic Extended-A - 0xFB50, 0xFDCF, // Arabic Presentation Forms - 0xFDF0, 0xFDFF, - 0xFE70, 0xFEFF, - 0x0001EE00, 0x0001EEFF, // Arabic Mathematical Alpha Symbols - }) - visitRunes(fn, R, []rune{ - 0x0590, 0x05FF, // Hebrew - 0x07C0, 0x089F, // Nko et al. - 0xFB1D, 0xFB4F, - 0x00010800, 0x00010FFF, // Cypriot Syllabary et. al. - 0x0001E800, 0x0001EDFF, - 0x0001EF00, 0x0001EFFF, - }) - visitRunes(fn, ET, []rune{ // European Terminator - 0x20A0, 0x20Cf, // Currency symbols - }) - rangetable.Visit(unicode.Noncharacter_Code_Point, func(r rune) { - fn(r, BN) // Boundary Neutral - }) - ucd.Parse(gen.OpenUCDFile("DerivedCoreProperties.txt"), func(p *ucd.Parser) { - if p.String(1) == "Default_Ignorable_Code_Point" { - fn(p.Rune(0), BN) // Boundary Neutral - } - }) -} - -func visitRunes(fn func(r rune, c Class), c Class, runes []rune) { - for i := 0; i < len(runes); i += 2 { - lo, hi := runes[i], runes[i+1] - for j := lo; j <= hi; j++ { - fn(j, c) - } - } -} diff --git a/vendor/golang.org/x/text/unicode/bidi/tables.go b/vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go similarity index 99% rename from vendor/golang.org/x/text/unicode/bidi/tables.go rename to vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go index a0b2b17a1e..2e1ff19599 100644 --- a/vendor/golang.org/x/text/unicode/bidi/tables.go +++ b/vendor/golang.org/x/text/unicode/bidi/tables10.0.0.go @@ -1,5 +1,7 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. +// +build go1.10 + package bidi // UnicodeVersion is the Unicode version from which the tables in this package are derived. diff --git a/vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go b/vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go new file mode 100644 index 0000000000..0ca0193ebe --- /dev/null +++ b/vendor/golang.org/x/text/unicode/bidi/tables9.0.0.go @@ -0,0 +1,1781 @@ +// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +// +build !go1.10 + +package bidi + +// UnicodeVersion is the Unicode version from which the tables in this package are derived. +const UnicodeVersion = "9.0.0" + +// xorMasks contains masks to be xor-ed with brackets to get the reverse +// version. +var xorMasks = []int32{ // 8 elements + 0, 1, 6, 7, 3, 15, 29, 63, +} // Size: 56 bytes + +// lookup returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *bidiTrie) lookup(s []byte) (v uint8, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return bidiValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = bidiIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = bidiIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = bidiIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *bidiTrie) lookupUnsafe(s []byte) uint8 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return bidiValues[c0] + } + i := bidiIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = bidiIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = bidiIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// lookupString returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *bidiTrie) lookupString(s string) (v uint8, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return bidiValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = bidiIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := bidiIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = bidiIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = bidiIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *bidiTrie) lookupStringUnsafe(s string) uint8 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return bidiValues[c0] + } + i := bidiIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = bidiIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = bidiIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// bidiTrie. Total size: 15744 bytes (15.38 KiB). Checksum: b4c3b70954803b86. +type bidiTrie struct{} + +func newBidiTrie(i int) *bidiTrie { + return &bidiTrie{} +} + +// lookupValue determines the type of block n and looks up the value for b. +func (t *bidiTrie) lookupValue(n uint32, b byte) uint8 { + switch { + default: + return uint8(bidiValues[n<<6+uint32(b)]) + } +} + +// bidiValues: 222 blocks, 14208 entries, 14208 bytes +// The third block is the zero block. +var bidiValues = [14208]uint8{ + // Block 0x0, offset 0x0 + 0x00: 0x000b, 0x01: 0x000b, 0x02: 0x000b, 0x03: 0x000b, 0x04: 0x000b, 0x05: 0x000b, + 0x06: 0x000b, 0x07: 0x000b, 0x08: 0x000b, 0x09: 0x0008, 0x0a: 0x0007, 0x0b: 0x0008, + 0x0c: 0x0009, 0x0d: 0x0007, 0x0e: 0x000b, 0x0f: 0x000b, 0x10: 0x000b, 0x11: 0x000b, + 0x12: 0x000b, 0x13: 0x000b, 0x14: 0x000b, 0x15: 0x000b, 0x16: 0x000b, 0x17: 0x000b, + 0x18: 0x000b, 0x19: 0x000b, 0x1a: 0x000b, 0x1b: 0x000b, 0x1c: 0x0007, 0x1d: 0x0007, + 0x1e: 0x0007, 0x1f: 0x0008, 0x20: 0x0009, 0x21: 0x000a, 0x22: 0x000a, 0x23: 0x0004, + 0x24: 0x0004, 0x25: 0x0004, 0x26: 0x000a, 0x27: 0x000a, 0x28: 0x003a, 0x29: 0x002a, + 0x2a: 0x000a, 0x2b: 0x0003, 0x2c: 0x0006, 0x2d: 0x0003, 0x2e: 0x0006, 0x2f: 0x0006, + 0x30: 0x0002, 0x31: 0x0002, 0x32: 0x0002, 0x33: 0x0002, 0x34: 0x0002, 0x35: 0x0002, + 0x36: 0x0002, 0x37: 0x0002, 0x38: 0x0002, 0x39: 0x0002, 0x3a: 0x0006, 0x3b: 0x000a, + 0x3c: 0x000a, 0x3d: 0x000a, 0x3e: 0x000a, 0x3f: 0x000a, + // Block 0x1, offset 0x40 + 0x40: 0x000a, + 0x5b: 0x005a, 0x5c: 0x000a, 0x5d: 0x004a, + 0x5e: 0x000a, 0x5f: 0x000a, 0x60: 0x000a, + 0x7b: 0x005a, + 0x7c: 0x000a, 0x7d: 0x004a, 0x7e: 0x000a, 0x7f: 0x000b, + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc0: 0x000b, 0xc1: 0x000b, 0xc2: 0x000b, 0xc3: 0x000b, 0xc4: 0x000b, 0xc5: 0x0007, + 0xc6: 0x000b, 0xc7: 0x000b, 0xc8: 0x000b, 0xc9: 0x000b, 0xca: 0x000b, 0xcb: 0x000b, + 0xcc: 0x000b, 0xcd: 0x000b, 0xce: 0x000b, 0xcf: 0x000b, 0xd0: 0x000b, 0xd1: 0x000b, + 0xd2: 0x000b, 0xd3: 0x000b, 0xd4: 0x000b, 0xd5: 0x000b, 0xd6: 0x000b, 0xd7: 0x000b, + 0xd8: 0x000b, 0xd9: 0x000b, 0xda: 0x000b, 0xdb: 0x000b, 0xdc: 0x000b, 0xdd: 0x000b, + 0xde: 0x000b, 0xdf: 0x000b, 0xe0: 0x0006, 0xe1: 0x000a, 0xe2: 0x0004, 0xe3: 0x0004, + 0xe4: 0x0004, 0xe5: 0x0004, 0xe6: 0x000a, 0xe7: 0x000a, 0xe8: 0x000a, 0xe9: 0x000a, + 0xeb: 0x000a, 0xec: 0x000a, 0xed: 0x000b, 0xee: 0x000a, 0xef: 0x000a, + 0xf0: 0x0004, 0xf1: 0x0004, 0xf2: 0x0002, 0xf3: 0x0002, 0xf4: 0x000a, + 0xf6: 0x000a, 0xf7: 0x000a, 0xf8: 0x000a, 0xf9: 0x0002, 0xfb: 0x000a, + 0xfc: 0x000a, 0xfd: 0x000a, 0xfe: 0x000a, 0xff: 0x000a, + // Block 0x4, offset 0x100 + 0x117: 0x000a, + 0x137: 0x000a, + // Block 0x5, offset 0x140 + 0x179: 0x000a, 0x17a: 0x000a, + // Block 0x6, offset 0x180 + 0x182: 0x000a, 0x183: 0x000a, 0x184: 0x000a, 0x185: 0x000a, + 0x186: 0x000a, 0x187: 0x000a, 0x188: 0x000a, 0x189: 0x000a, 0x18a: 0x000a, 0x18b: 0x000a, + 0x18c: 0x000a, 0x18d: 0x000a, 0x18e: 0x000a, 0x18f: 0x000a, + 0x192: 0x000a, 0x193: 0x000a, 0x194: 0x000a, 0x195: 0x000a, 0x196: 0x000a, 0x197: 0x000a, + 0x198: 0x000a, 0x199: 0x000a, 0x19a: 0x000a, 0x19b: 0x000a, 0x19c: 0x000a, 0x19d: 0x000a, + 0x19e: 0x000a, 0x19f: 0x000a, + 0x1a5: 0x000a, 0x1a6: 0x000a, 0x1a7: 0x000a, 0x1a8: 0x000a, 0x1a9: 0x000a, + 0x1aa: 0x000a, 0x1ab: 0x000a, 0x1ac: 0x000a, 0x1ad: 0x000a, 0x1af: 0x000a, + 0x1b0: 0x000a, 0x1b1: 0x000a, 0x1b2: 0x000a, 0x1b3: 0x000a, 0x1b4: 0x000a, 0x1b5: 0x000a, + 0x1b6: 0x000a, 0x1b7: 0x000a, 0x1b8: 0x000a, 0x1b9: 0x000a, 0x1ba: 0x000a, 0x1bb: 0x000a, + 0x1bc: 0x000a, 0x1bd: 0x000a, 0x1be: 0x000a, 0x1bf: 0x000a, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x000c, 0x1c1: 0x000c, 0x1c2: 0x000c, 0x1c3: 0x000c, 0x1c4: 0x000c, 0x1c5: 0x000c, + 0x1c6: 0x000c, 0x1c7: 0x000c, 0x1c8: 0x000c, 0x1c9: 0x000c, 0x1ca: 0x000c, 0x1cb: 0x000c, + 0x1cc: 0x000c, 0x1cd: 0x000c, 0x1ce: 0x000c, 0x1cf: 0x000c, 0x1d0: 0x000c, 0x1d1: 0x000c, + 0x1d2: 0x000c, 0x1d3: 0x000c, 0x1d4: 0x000c, 0x1d5: 0x000c, 0x1d6: 0x000c, 0x1d7: 0x000c, + 0x1d8: 0x000c, 0x1d9: 0x000c, 0x1da: 0x000c, 0x1db: 0x000c, 0x1dc: 0x000c, 0x1dd: 0x000c, + 0x1de: 0x000c, 0x1df: 0x000c, 0x1e0: 0x000c, 0x1e1: 0x000c, 0x1e2: 0x000c, 0x1e3: 0x000c, + 0x1e4: 0x000c, 0x1e5: 0x000c, 0x1e6: 0x000c, 0x1e7: 0x000c, 0x1e8: 0x000c, 0x1e9: 0x000c, + 0x1ea: 0x000c, 0x1eb: 0x000c, 0x1ec: 0x000c, 0x1ed: 0x000c, 0x1ee: 0x000c, 0x1ef: 0x000c, + 0x1f0: 0x000c, 0x1f1: 0x000c, 0x1f2: 0x000c, 0x1f3: 0x000c, 0x1f4: 0x000c, 0x1f5: 0x000c, + 0x1f6: 0x000c, 0x1f7: 0x000c, 0x1f8: 0x000c, 0x1f9: 0x000c, 0x1fa: 0x000c, 0x1fb: 0x000c, + 0x1fc: 0x000c, 0x1fd: 0x000c, 0x1fe: 0x000c, 0x1ff: 0x000c, + // Block 0x8, offset 0x200 + 0x200: 0x000c, 0x201: 0x000c, 0x202: 0x000c, 0x203: 0x000c, 0x204: 0x000c, 0x205: 0x000c, + 0x206: 0x000c, 0x207: 0x000c, 0x208: 0x000c, 0x209: 0x000c, 0x20a: 0x000c, 0x20b: 0x000c, + 0x20c: 0x000c, 0x20d: 0x000c, 0x20e: 0x000c, 0x20f: 0x000c, 0x210: 0x000c, 0x211: 0x000c, + 0x212: 0x000c, 0x213: 0x000c, 0x214: 0x000c, 0x215: 0x000c, 0x216: 0x000c, 0x217: 0x000c, + 0x218: 0x000c, 0x219: 0x000c, 0x21a: 0x000c, 0x21b: 0x000c, 0x21c: 0x000c, 0x21d: 0x000c, + 0x21e: 0x000c, 0x21f: 0x000c, 0x220: 0x000c, 0x221: 0x000c, 0x222: 0x000c, 0x223: 0x000c, + 0x224: 0x000c, 0x225: 0x000c, 0x226: 0x000c, 0x227: 0x000c, 0x228: 0x000c, 0x229: 0x000c, + 0x22a: 0x000c, 0x22b: 0x000c, 0x22c: 0x000c, 0x22d: 0x000c, 0x22e: 0x000c, 0x22f: 0x000c, + 0x234: 0x000a, 0x235: 0x000a, + 0x23e: 0x000a, + // Block 0x9, offset 0x240 + 0x244: 0x000a, 0x245: 0x000a, + 0x247: 0x000a, + // Block 0xa, offset 0x280 + 0x2b6: 0x000a, + // Block 0xb, offset 0x2c0 + 0x2c3: 0x000c, 0x2c4: 0x000c, 0x2c5: 0x000c, + 0x2c6: 0x000c, 0x2c7: 0x000c, 0x2c8: 0x000c, 0x2c9: 0x000c, + // Block 0xc, offset 0x300 + 0x30a: 0x000a, + 0x30d: 0x000a, 0x30e: 0x000a, 0x30f: 0x0004, 0x310: 0x0001, 0x311: 0x000c, + 0x312: 0x000c, 0x313: 0x000c, 0x314: 0x000c, 0x315: 0x000c, 0x316: 0x000c, 0x317: 0x000c, + 0x318: 0x000c, 0x319: 0x000c, 0x31a: 0x000c, 0x31b: 0x000c, 0x31c: 0x000c, 0x31d: 0x000c, + 0x31e: 0x000c, 0x31f: 0x000c, 0x320: 0x000c, 0x321: 0x000c, 0x322: 0x000c, 0x323: 0x000c, + 0x324: 0x000c, 0x325: 0x000c, 0x326: 0x000c, 0x327: 0x000c, 0x328: 0x000c, 0x329: 0x000c, + 0x32a: 0x000c, 0x32b: 0x000c, 0x32c: 0x000c, 0x32d: 0x000c, 0x32e: 0x000c, 0x32f: 0x000c, + 0x330: 0x000c, 0x331: 0x000c, 0x332: 0x000c, 0x333: 0x000c, 0x334: 0x000c, 0x335: 0x000c, + 0x336: 0x000c, 0x337: 0x000c, 0x338: 0x000c, 0x339: 0x000c, 0x33a: 0x000c, 0x33b: 0x000c, + 0x33c: 0x000c, 0x33d: 0x000c, 0x33e: 0x0001, 0x33f: 0x000c, + // Block 0xd, offset 0x340 + 0x340: 0x0001, 0x341: 0x000c, 0x342: 0x000c, 0x343: 0x0001, 0x344: 0x000c, 0x345: 0x000c, + 0x346: 0x0001, 0x347: 0x000c, 0x348: 0x0001, 0x349: 0x0001, 0x34a: 0x0001, 0x34b: 0x0001, + 0x34c: 0x0001, 0x34d: 0x0001, 0x34e: 0x0001, 0x34f: 0x0001, 0x350: 0x0001, 0x351: 0x0001, + 0x352: 0x0001, 0x353: 0x0001, 0x354: 0x0001, 0x355: 0x0001, 0x356: 0x0001, 0x357: 0x0001, + 0x358: 0x0001, 0x359: 0x0001, 0x35a: 0x0001, 0x35b: 0x0001, 0x35c: 0x0001, 0x35d: 0x0001, + 0x35e: 0x0001, 0x35f: 0x0001, 0x360: 0x0001, 0x361: 0x0001, 0x362: 0x0001, 0x363: 0x0001, + 0x364: 0x0001, 0x365: 0x0001, 0x366: 0x0001, 0x367: 0x0001, 0x368: 0x0001, 0x369: 0x0001, + 0x36a: 0x0001, 0x36b: 0x0001, 0x36c: 0x0001, 0x36d: 0x0001, 0x36e: 0x0001, 0x36f: 0x0001, + 0x370: 0x0001, 0x371: 0x0001, 0x372: 0x0001, 0x373: 0x0001, 0x374: 0x0001, 0x375: 0x0001, + 0x376: 0x0001, 0x377: 0x0001, 0x378: 0x0001, 0x379: 0x0001, 0x37a: 0x0001, 0x37b: 0x0001, + 0x37c: 0x0001, 0x37d: 0x0001, 0x37e: 0x0001, 0x37f: 0x0001, + // Block 0xe, offset 0x380 + 0x380: 0x0005, 0x381: 0x0005, 0x382: 0x0005, 0x383: 0x0005, 0x384: 0x0005, 0x385: 0x0005, + 0x386: 0x000a, 0x387: 0x000a, 0x388: 0x000d, 0x389: 0x0004, 0x38a: 0x0004, 0x38b: 0x000d, + 0x38c: 0x0006, 0x38d: 0x000d, 0x38e: 0x000a, 0x38f: 0x000a, 0x390: 0x000c, 0x391: 0x000c, + 0x392: 0x000c, 0x393: 0x000c, 0x394: 0x000c, 0x395: 0x000c, 0x396: 0x000c, 0x397: 0x000c, + 0x398: 0x000c, 0x399: 0x000c, 0x39a: 0x000c, 0x39b: 0x000d, 0x39c: 0x000d, 0x39d: 0x000d, + 0x39e: 0x000d, 0x39f: 0x000d, 0x3a0: 0x000d, 0x3a1: 0x000d, 0x3a2: 0x000d, 0x3a3: 0x000d, + 0x3a4: 0x000d, 0x3a5: 0x000d, 0x3a6: 0x000d, 0x3a7: 0x000d, 0x3a8: 0x000d, 0x3a9: 0x000d, + 0x3aa: 0x000d, 0x3ab: 0x000d, 0x3ac: 0x000d, 0x3ad: 0x000d, 0x3ae: 0x000d, 0x3af: 0x000d, + 0x3b0: 0x000d, 0x3b1: 0x000d, 0x3b2: 0x000d, 0x3b3: 0x000d, 0x3b4: 0x000d, 0x3b5: 0x000d, + 0x3b6: 0x000d, 0x3b7: 0x000d, 0x3b8: 0x000d, 0x3b9: 0x000d, 0x3ba: 0x000d, 0x3bb: 0x000d, + 0x3bc: 0x000d, 0x3bd: 0x000d, 0x3be: 0x000d, 0x3bf: 0x000d, + // Block 0xf, offset 0x3c0 + 0x3c0: 0x000d, 0x3c1: 0x000d, 0x3c2: 0x000d, 0x3c3: 0x000d, 0x3c4: 0x000d, 0x3c5: 0x000d, + 0x3c6: 0x000d, 0x3c7: 0x000d, 0x3c8: 0x000d, 0x3c9: 0x000d, 0x3ca: 0x000d, 0x3cb: 0x000c, + 0x3cc: 0x000c, 0x3cd: 0x000c, 0x3ce: 0x000c, 0x3cf: 0x000c, 0x3d0: 0x000c, 0x3d1: 0x000c, + 0x3d2: 0x000c, 0x3d3: 0x000c, 0x3d4: 0x000c, 0x3d5: 0x000c, 0x3d6: 0x000c, 0x3d7: 0x000c, + 0x3d8: 0x000c, 0x3d9: 0x000c, 0x3da: 0x000c, 0x3db: 0x000c, 0x3dc: 0x000c, 0x3dd: 0x000c, + 0x3de: 0x000c, 0x3df: 0x000c, 0x3e0: 0x0005, 0x3e1: 0x0005, 0x3e2: 0x0005, 0x3e3: 0x0005, + 0x3e4: 0x0005, 0x3e5: 0x0005, 0x3e6: 0x0005, 0x3e7: 0x0005, 0x3e8: 0x0005, 0x3e9: 0x0005, + 0x3ea: 0x0004, 0x3eb: 0x0005, 0x3ec: 0x0005, 0x3ed: 0x000d, 0x3ee: 0x000d, 0x3ef: 0x000d, + 0x3f0: 0x000c, 0x3f1: 0x000d, 0x3f2: 0x000d, 0x3f3: 0x000d, 0x3f4: 0x000d, 0x3f5: 0x000d, + 0x3f6: 0x000d, 0x3f7: 0x000d, 0x3f8: 0x000d, 0x3f9: 0x000d, 0x3fa: 0x000d, 0x3fb: 0x000d, + 0x3fc: 0x000d, 0x3fd: 0x000d, 0x3fe: 0x000d, 0x3ff: 0x000d, + // Block 0x10, offset 0x400 + 0x400: 0x000d, 0x401: 0x000d, 0x402: 0x000d, 0x403: 0x000d, 0x404: 0x000d, 0x405: 0x000d, + 0x406: 0x000d, 0x407: 0x000d, 0x408: 0x000d, 0x409: 0x000d, 0x40a: 0x000d, 0x40b: 0x000d, + 0x40c: 0x000d, 0x40d: 0x000d, 0x40e: 0x000d, 0x40f: 0x000d, 0x410: 0x000d, 0x411: 0x000d, + 0x412: 0x000d, 0x413: 0x000d, 0x414: 0x000d, 0x415: 0x000d, 0x416: 0x000d, 0x417: 0x000d, + 0x418: 0x000d, 0x419: 0x000d, 0x41a: 0x000d, 0x41b: 0x000d, 0x41c: 0x000d, 0x41d: 0x000d, + 0x41e: 0x000d, 0x41f: 0x000d, 0x420: 0x000d, 0x421: 0x000d, 0x422: 0x000d, 0x423: 0x000d, + 0x424: 0x000d, 0x425: 0x000d, 0x426: 0x000d, 0x427: 0x000d, 0x428: 0x000d, 0x429: 0x000d, + 0x42a: 0x000d, 0x42b: 0x000d, 0x42c: 0x000d, 0x42d: 0x000d, 0x42e: 0x000d, 0x42f: 0x000d, + 0x430: 0x000d, 0x431: 0x000d, 0x432: 0x000d, 0x433: 0x000d, 0x434: 0x000d, 0x435: 0x000d, + 0x436: 0x000d, 0x437: 0x000d, 0x438: 0x000d, 0x439: 0x000d, 0x43a: 0x000d, 0x43b: 0x000d, + 0x43c: 0x000d, 0x43d: 0x000d, 0x43e: 0x000d, 0x43f: 0x000d, + // Block 0x11, offset 0x440 + 0x440: 0x000d, 0x441: 0x000d, 0x442: 0x000d, 0x443: 0x000d, 0x444: 0x000d, 0x445: 0x000d, + 0x446: 0x000d, 0x447: 0x000d, 0x448: 0x000d, 0x449: 0x000d, 0x44a: 0x000d, 0x44b: 0x000d, + 0x44c: 0x000d, 0x44d: 0x000d, 0x44e: 0x000d, 0x44f: 0x000d, 0x450: 0x000d, 0x451: 0x000d, + 0x452: 0x000d, 0x453: 0x000d, 0x454: 0x000d, 0x455: 0x000d, 0x456: 0x000c, 0x457: 0x000c, + 0x458: 0x000c, 0x459: 0x000c, 0x45a: 0x000c, 0x45b: 0x000c, 0x45c: 0x000c, 0x45d: 0x0005, + 0x45e: 0x000a, 0x45f: 0x000c, 0x460: 0x000c, 0x461: 0x000c, 0x462: 0x000c, 0x463: 0x000c, + 0x464: 0x000c, 0x465: 0x000d, 0x466: 0x000d, 0x467: 0x000c, 0x468: 0x000c, 0x469: 0x000a, + 0x46a: 0x000c, 0x46b: 0x000c, 0x46c: 0x000c, 0x46d: 0x000c, 0x46e: 0x000d, 0x46f: 0x000d, + 0x470: 0x0002, 0x471: 0x0002, 0x472: 0x0002, 0x473: 0x0002, 0x474: 0x0002, 0x475: 0x0002, + 0x476: 0x0002, 0x477: 0x0002, 0x478: 0x0002, 0x479: 0x0002, 0x47a: 0x000d, 0x47b: 0x000d, + 0x47c: 0x000d, 0x47d: 0x000d, 0x47e: 0x000d, 0x47f: 0x000d, + // Block 0x12, offset 0x480 + 0x480: 0x000d, 0x481: 0x000d, 0x482: 0x000d, 0x483: 0x000d, 0x484: 0x000d, 0x485: 0x000d, + 0x486: 0x000d, 0x487: 0x000d, 0x488: 0x000d, 0x489: 0x000d, 0x48a: 0x000d, 0x48b: 0x000d, + 0x48c: 0x000d, 0x48d: 0x000d, 0x48e: 0x000d, 0x48f: 0x000d, 0x490: 0x000d, 0x491: 0x000c, + 0x492: 0x000d, 0x493: 0x000d, 0x494: 0x000d, 0x495: 0x000d, 0x496: 0x000d, 0x497: 0x000d, + 0x498: 0x000d, 0x499: 0x000d, 0x49a: 0x000d, 0x49b: 0x000d, 0x49c: 0x000d, 0x49d: 0x000d, + 0x49e: 0x000d, 0x49f: 0x000d, 0x4a0: 0x000d, 0x4a1: 0x000d, 0x4a2: 0x000d, 0x4a3: 0x000d, + 0x4a4: 0x000d, 0x4a5: 0x000d, 0x4a6: 0x000d, 0x4a7: 0x000d, 0x4a8: 0x000d, 0x4a9: 0x000d, + 0x4aa: 0x000d, 0x4ab: 0x000d, 0x4ac: 0x000d, 0x4ad: 0x000d, 0x4ae: 0x000d, 0x4af: 0x000d, + 0x4b0: 0x000c, 0x4b1: 0x000c, 0x4b2: 0x000c, 0x4b3: 0x000c, 0x4b4: 0x000c, 0x4b5: 0x000c, + 0x4b6: 0x000c, 0x4b7: 0x000c, 0x4b8: 0x000c, 0x4b9: 0x000c, 0x4ba: 0x000c, 0x4bb: 0x000c, + 0x4bc: 0x000c, 0x4bd: 0x000c, 0x4be: 0x000c, 0x4bf: 0x000c, + // Block 0x13, offset 0x4c0 + 0x4c0: 0x000c, 0x4c1: 0x000c, 0x4c2: 0x000c, 0x4c3: 0x000c, 0x4c4: 0x000c, 0x4c5: 0x000c, + 0x4c6: 0x000c, 0x4c7: 0x000c, 0x4c8: 0x000c, 0x4c9: 0x000c, 0x4ca: 0x000c, 0x4cb: 0x000d, + 0x4cc: 0x000d, 0x4cd: 0x000d, 0x4ce: 0x000d, 0x4cf: 0x000d, 0x4d0: 0x000d, 0x4d1: 0x000d, + 0x4d2: 0x000d, 0x4d3: 0x000d, 0x4d4: 0x000d, 0x4d5: 0x000d, 0x4d6: 0x000d, 0x4d7: 0x000d, + 0x4d8: 0x000d, 0x4d9: 0x000d, 0x4da: 0x000d, 0x4db: 0x000d, 0x4dc: 0x000d, 0x4dd: 0x000d, + 0x4de: 0x000d, 0x4df: 0x000d, 0x4e0: 0x000d, 0x4e1: 0x000d, 0x4e2: 0x000d, 0x4e3: 0x000d, + 0x4e4: 0x000d, 0x4e5: 0x000d, 0x4e6: 0x000d, 0x4e7: 0x000d, 0x4e8: 0x000d, 0x4e9: 0x000d, + 0x4ea: 0x000d, 0x4eb: 0x000d, 0x4ec: 0x000d, 0x4ed: 0x000d, 0x4ee: 0x000d, 0x4ef: 0x000d, + 0x4f0: 0x000d, 0x4f1: 0x000d, 0x4f2: 0x000d, 0x4f3: 0x000d, 0x4f4: 0x000d, 0x4f5: 0x000d, + 0x4f6: 0x000d, 0x4f7: 0x000d, 0x4f8: 0x000d, 0x4f9: 0x000d, 0x4fa: 0x000d, 0x4fb: 0x000d, + 0x4fc: 0x000d, 0x4fd: 0x000d, 0x4fe: 0x000d, 0x4ff: 0x000d, + // Block 0x14, offset 0x500 + 0x500: 0x000d, 0x501: 0x000d, 0x502: 0x000d, 0x503: 0x000d, 0x504: 0x000d, 0x505: 0x000d, + 0x506: 0x000d, 0x507: 0x000d, 0x508: 0x000d, 0x509: 0x000d, 0x50a: 0x000d, 0x50b: 0x000d, + 0x50c: 0x000d, 0x50d: 0x000d, 0x50e: 0x000d, 0x50f: 0x000d, 0x510: 0x000d, 0x511: 0x000d, + 0x512: 0x000d, 0x513: 0x000d, 0x514: 0x000d, 0x515: 0x000d, 0x516: 0x000d, 0x517: 0x000d, + 0x518: 0x000d, 0x519: 0x000d, 0x51a: 0x000d, 0x51b: 0x000d, 0x51c: 0x000d, 0x51d: 0x000d, + 0x51e: 0x000d, 0x51f: 0x000d, 0x520: 0x000d, 0x521: 0x000d, 0x522: 0x000d, 0x523: 0x000d, + 0x524: 0x000d, 0x525: 0x000d, 0x526: 0x000c, 0x527: 0x000c, 0x528: 0x000c, 0x529: 0x000c, + 0x52a: 0x000c, 0x52b: 0x000c, 0x52c: 0x000c, 0x52d: 0x000c, 0x52e: 0x000c, 0x52f: 0x000c, + 0x530: 0x000c, 0x531: 0x000d, 0x532: 0x000d, 0x533: 0x000d, 0x534: 0x000d, 0x535: 0x000d, + 0x536: 0x000d, 0x537: 0x000d, 0x538: 0x000d, 0x539: 0x000d, 0x53a: 0x000d, 0x53b: 0x000d, + 0x53c: 0x000d, 0x53d: 0x000d, 0x53e: 0x000d, 0x53f: 0x000d, + // Block 0x15, offset 0x540 + 0x540: 0x0001, 0x541: 0x0001, 0x542: 0x0001, 0x543: 0x0001, 0x544: 0x0001, 0x545: 0x0001, + 0x546: 0x0001, 0x547: 0x0001, 0x548: 0x0001, 0x549: 0x0001, 0x54a: 0x0001, 0x54b: 0x0001, + 0x54c: 0x0001, 0x54d: 0x0001, 0x54e: 0x0001, 0x54f: 0x0001, 0x550: 0x0001, 0x551: 0x0001, + 0x552: 0x0001, 0x553: 0x0001, 0x554: 0x0001, 0x555: 0x0001, 0x556: 0x0001, 0x557: 0x0001, + 0x558: 0x0001, 0x559: 0x0001, 0x55a: 0x0001, 0x55b: 0x0001, 0x55c: 0x0001, 0x55d: 0x0001, + 0x55e: 0x0001, 0x55f: 0x0001, 0x560: 0x0001, 0x561: 0x0001, 0x562: 0x0001, 0x563: 0x0001, + 0x564: 0x0001, 0x565: 0x0001, 0x566: 0x0001, 0x567: 0x0001, 0x568: 0x0001, 0x569: 0x0001, + 0x56a: 0x0001, 0x56b: 0x000c, 0x56c: 0x000c, 0x56d: 0x000c, 0x56e: 0x000c, 0x56f: 0x000c, + 0x570: 0x000c, 0x571: 0x000c, 0x572: 0x000c, 0x573: 0x000c, 0x574: 0x0001, 0x575: 0x0001, + 0x576: 0x000a, 0x577: 0x000a, 0x578: 0x000a, 0x579: 0x000a, 0x57a: 0x0001, 0x57b: 0x0001, + 0x57c: 0x0001, 0x57d: 0x0001, 0x57e: 0x0001, 0x57f: 0x0001, + // Block 0x16, offset 0x580 + 0x580: 0x0001, 0x581: 0x0001, 0x582: 0x0001, 0x583: 0x0001, 0x584: 0x0001, 0x585: 0x0001, + 0x586: 0x0001, 0x587: 0x0001, 0x588: 0x0001, 0x589: 0x0001, 0x58a: 0x0001, 0x58b: 0x0001, + 0x58c: 0x0001, 0x58d: 0x0001, 0x58e: 0x0001, 0x58f: 0x0001, 0x590: 0x0001, 0x591: 0x0001, + 0x592: 0x0001, 0x593: 0x0001, 0x594: 0x0001, 0x595: 0x0001, 0x596: 0x000c, 0x597: 0x000c, + 0x598: 0x000c, 0x599: 0x000c, 0x59a: 0x0001, 0x59b: 0x000c, 0x59c: 0x000c, 0x59d: 0x000c, + 0x59e: 0x000c, 0x59f: 0x000c, 0x5a0: 0x000c, 0x5a1: 0x000c, 0x5a2: 0x000c, 0x5a3: 0x000c, + 0x5a4: 0x0001, 0x5a5: 0x000c, 0x5a6: 0x000c, 0x5a7: 0x000c, 0x5a8: 0x0001, 0x5a9: 0x000c, + 0x5aa: 0x000c, 0x5ab: 0x000c, 0x5ac: 0x000c, 0x5ad: 0x000c, 0x5ae: 0x0001, 0x5af: 0x0001, + 0x5b0: 0x0001, 0x5b1: 0x0001, 0x5b2: 0x0001, 0x5b3: 0x0001, 0x5b4: 0x0001, 0x5b5: 0x0001, + 0x5b6: 0x0001, 0x5b7: 0x0001, 0x5b8: 0x0001, 0x5b9: 0x0001, 0x5ba: 0x0001, 0x5bb: 0x0001, + 0x5bc: 0x0001, 0x5bd: 0x0001, 0x5be: 0x0001, 0x5bf: 0x0001, + // Block 0x17, offset 0x5c0 + 0x5c0: 0x0001, 0x5c1: 0x0001, 0x5c2: 0x0001, 0x5c3: 0x0001, 0x5c4: 0x0001, 0x5c5: 0x0001, + 0x5c6: 0x0001, 0x5c7: 0x0001, 0x5c8: 0x0001, 0x5c9: 0x0001, 0x5ca: 0x0001, 0x5cb: 0x0001, + 0x5cc: 0x0001, 0x5cd: 0x0001, 0x5ce: 0x0001, 0x5cf: 0x0001, 0x5d0: 0x0001, 0x5d1: 0x0001, + 0x5d2: 0x0001, 0x5d3: 0x0001, 0x5d4: 0x0001, 0x5d5: 0x0001, 0x5d6: 0x0001, 0x5d7: 0x0001, + 0x5d8: 0x0001, 0x5d9: 0x000c, 0x5da: 0x000c, 0x5db: 0x000c, 0x5dc: 0x0001, 0x5dd: 0x0001, + 0x5de: 0x0001, 0x5df: 0x0001, 0x5e0: 0x0001, 0x5e1: 0x0001, 0x5e2: 0x0001, 0x5e3: 0x0001, + 0x5e4: 0x0001, 0x5e5: 0x0001, 0x5e6: 0x0001, 0x5e7: 0x0001, 0x5e8: 0x0001, 0x5e9: 0x0001, + 0x5ea: 0x0001, 0x5eb: 0x0001, 0x5ec: 0x0001, 0x5ed: 0x0001, 0x5ee: 0x0001, 0x5ef: 0x0001, + 0x5f0: 0x0001, 0x5f1: 0x0001, 0x5f2: 0x0001, 0x5f3: 0x0001, 0x5f4: 0x0001, 0x5f5: 0x0001, + 0x5f6: 0x0001, 0x5f7: 0x0001, 0x5f8: 0x0001, 0x5f9: 0x0001, 0x5fa: 0x0001, 0x5fb: 0x0001, + 0x5fc: 0x0001, 0x5fd: 0x0001, 0x5fe: 0x0001, 0x5ff: 0x0001, + // Block 0x18, offset 0x600 + 0x600: 0x0001, 0x601: 0x0001, 0x602: 0x0001, 0x603: 0x0001, 0x604: 0x0001, 0x605: 0x0001, + 0x606: 0x0001, 0x607: 0x0001, 0x608: 0x0001, 0x609: 0x0001, 0x60a: 0x0001, 0x60b: 0x0001, + 0x60c: 0x0001, 0x60d: 0x0001, 0x60e: 0x0001, 0x60f: 0x0001, 0x610: 0x0001, 0x611: 0x0001, + 0x612: 0x0001, 0x613: 0x0001, 0x614: 0x0001, 0x615: 0x0001, 0x616: 0x0001, 0x617: 0x0001, + 0x618: 0x0001, 0x619: 0x0001, 0x61a: 0x0001, 0x61b: 0x0001, 0x61c: 0x0001, 0x61d: 0x0001, + 0x61e: 0x0001, 0x61f: 0x0001, 0x620: 0x000d, 0x621: 0x000d, 0x622: 0x000d, 0x623: 0x000d, + 0x624: 0x000d, 0x625: 0x000d, 0x626: 0x000d, 0x627: 0x000d, 0x628: 0x000d, 0x629: 0x000d, + 0x62a: 0x000d, 0x62b: 0x000d, 0x62c: 0x000d, 0x62d: 0x000d, 0x62e: 0x000d, 0x62f: 0x000d, + 0x630: 0x000d, 0x631: 0x000d, 0x632: 0x000d, 0x633: 0x000d, 0x634: 0x000d, 0x635: 0x000d, + 0x636: 0x000d, 0x637: 0x000d, 0x638: 0x000d, 0x639: 0x000d, 0x63a: 0x000d, 0x63b: 0x000d, + 0x63c: 0x000d, 0x63d: 0x000d, 0x63e: 0x000d, 0x63f: 0x000d, + // Block 0x19, offset 0x640 + 0x640: 0x000d, 0x641: 0x000d, 0x642: 0x000d, 0x643: 0x000d, 0x644: 0x000d, 0x645: 0x000d, + 0x646: 0x000d, 0x647: 0x000d, 0x648: 0x000d, 0x649: 0x000d, 0x64a: 0x000d, 0x64b: 0x000d, + 0x64c: 0x000d, 0x64d: 0x000d, 0x64e: 0x000d, 0x64f: 0x000d, 0x650: 0x000d, 0x651: 0x000d, + 0x652: 0x000d, 0x653: 0x000d, 0x654: 0x000c, 0x655: 0x000c, 0x656: 0x000c, 0x657: 0x000c, + 0x658: 0x000c, 0x659: 0x000c, 0x65a: 0x000c, 0x65b: 0x000c, 0x65c: 0x000c, 0x65d: 0x000c, + 0x65e: 0x000c, 0x65f: 0x000c, 0x660: 0x000c, 0x661: 0x000c, 0x662: 0x0005, 0x663: 0x000c, + 0x664: 0x000c, 0x665: 0x000c, 0x666: 0x000c, 0x667: 0x000c, 0x668: 0x000c, 0x669: 0x000c, + 0x66a: 0x000c, 0x66b: 0x000c, 0x66c: 0x000c, 0x66d: 0x000c, 0x66e: 0x000c, 0x66f: 0x000c, + 0x670: 0x000c, 0x671: 0x000c, 0x672: 0x000c, 0x673: 0x000c, 0x674: 0x000c, 0x675: 0x000c, + 0x676: 0x000c, 0x677: 0x000c, 0x678: 0x000c, 0x679: 0x000c, 0x67a: 0x000c, 0x67b: 0x000c, + 0x67c: 0x000c, 0x67d: 0x000c, 0x67e: 0x000c, 0x67f: 0x000c, + // Block 0x1a, offset 0x680 + 0x680: 0x000c, 0x681: 0x000c, 0x682: 0x000c, + 0x6ba: 0x000c, + 0x6bc: 0x000c, + // Block 0x1b, offset 0x6c0 + 0x6c1: 0x000c, 0x6c2: 0x000c, 0x6c3: 0x000c, 0x6c4: 0x000c, 0x6c5: 0x000c, + 0x6c6: 0x000c, 0x6c7: 0x000c, 0x6c8: 0x000c, + 0x6cd: 0x000c, 0x6d1: 0x000c, + 0x6d2: 0x000c, 0x6d3: 0x000c, 0x6d4: 0x000c, 0x6d5: 0x000c, 0x6d6: 0x000c, 0x6d7: 0x000c, + 0x6e2: 0x000c, 0x6e3: 0x000c, + // Block 0x1c, offset 0x700 + 0x701: 0x000c, + 0x73c: 0x000c, + // Block 0x1d, offset 0x740 + 0x741: 0x000c, 0x742: 0x000c, 0x743: 0x000c, 0x744: 0x000c, + 0x74d: 0x000c, + 0x762: 0x000c, 0x763: 0x000c, + 0x772: 0x0004, 0x773: 0x0004, + 0x77b: 0x0004, + // Block 0x1e, offset 0x780 + 0x781: 0x000c, 0x782: 0x000c, + 0x7bc: 0x000c, + // Block 0x1f, offset 0x7c0 + 0x7c1: 0x000c, 0x7c2: 0x000c, + 0x7c7: 0x000c, 0x7c8: 0x000c, 0x7cb: 0x000c, + 0x7cc: 0x000c, 0x7cd: 0x000c, 0x7d1: 0x000c, + 0x7f0: 0x000c, 0x7f1: 0x000c, 0x7f5: 0x000c, + // Block 0x20, offset 0x800 + 0x801: 0x000c, 0x802: 0x000c, 0x803: 0x000c, 0x804: 0x000c, 0x805: 0x000c, + 0x807: 0x000c, 0x808: 0x000c, + 0x80d: 0x000c, + 0x822: 0x000c, 0x823: 0x000c, + 0x831: 0x0004, + // Block 0x21, offset 0x840 + 0x841: 0x000c, + 0x87c: 0x000c, 0x87f: 0x000c, + // Block 0x22, offset 0x880 + 0x881: 0x000c, 0x882: 0x000c, 0x883: 0x000c, 0x884: 0x000c, + 0x88d: 0x000c, + 0x896: 0x000c, + 0x8a2: 0x000c, 0x8a3: 0x000c, + // Block 0x23, offset 0x8c0 + 0x8c2: 0x000c, + // Block 0x24, offset 0x900 + 0x900: 0x000c, + 0x90d: 0x000c, + 0x933: 0x000a, 0x934: 0x000a, 0x935: 0x000a, + 0x936: 0x000a, 0x937: 0x000a, 0x938: 0x000a, 0x939: 0x0004, 0x93a: 0x000a, + // Block 0x25, offset 0x940 + 0x940: 0x000c, + 0x97e: 0x000c, 0x97f: 0x000c, + // Block 0x26, offset 0x980 + 0x980: 0x000c, + 0x986: 0x000c, 0x987: 0x000c, 0x988: 0x000c, 0x98a: 0x000c, 0x98b: 0x000c, + 0x98c: 0x000c, 0x98d: 0x000c, + 0x995: 0x000c, 0x996: 0x000c, + 0x9a2: 0x000c, 0x9a3: 0x000c, + 0x9b8: 0x000a, 0x9b9: 0x000a, 0x9ba: 0x000a, 0x9bb: 0x000a, + 0x9bc: 0x000a, 0x9bd: 0x000a, 0x9be: 0x000a, + // Block 0x27, offset 0x9c0 + 0x9cc: 0x000c, 0x9cd: 0x000c, + 0x9e2: 0x000c, 0x9e3: 0x000c, + // Block 0x28, offset 0xa00 + 0xa01: 0x000c, + // Block 0x29, offset 0xa40 + 0xa41: 0x000c, 0xa42: 0x000c, 0xa43: 0x000c, 0xa44: 0x000c, + 0xa4d: 0x000c, + 0xa62: 0x000c, 0xa63: 0x000c, + // Block 0x2a, offset 0xa80 + 0xa8a: 0x000c, + 0xa92: 0x000c, 0xa93: 0x000c, 0xa94: 0x000c, 0xa96: 0x000c, + // Block 0x2b, offset 0xac0 + 0xaf1: 0x000c, 0xaf4: 0x000c, 0xaf5: 0x000c, + 0xaf6: 0x000c, 0xaf7: 0x000c, 0xaf8: 0x000c, 0xaf9: 0x000c, 0xafa: 0x000c, + 0xaff: 0x0004, + // Block 0x2c, offset 0xb00 + 0xb07: 0x000c, 0xb08: 0x000c, 0xb09: 0x000c, 0xb0a: 0x000c, 0xb0b: 0x000c, + 0xb0c: 0x000c, 0xb0d: 0x000c, 0xb0e: 0x000c, + // Block 0x2d, offset 0xb40 + 0xb71: 0x000c, 0xb74: 0x000c, 0xb75: 0x000c, + 0xb76: 0x000c, 0xb77: 0x000c, 0xb78: 0x000c, 0xb79: 0x000c, 0xb7b: 0x000c, + 0xb7c: 0x000c, + // Block 0x2e, offset 0xb80 + 0xb88: 0x000c, 0xb89: 0x000c, 0xb8a: 0x000c, 0xb8b: 0x000c, + 0xb8c: 0x000c, 0xb8d: 0x000c, + // Block 0x2f, offset 0xbc0 + 0xbd8: 0x000c, 0xbd9: 0x000c, + 0xbf5: 0x000c, + 0xbf7: 0x000c, 0xbf9: 0x000c, 0xbfa: 0x003a, 0xbfb: 0x002a, + 0xbfc: 0x003a, 0xbfd: 0x002a, + // Block 0x30, offset 0xc00 + 0xc31: 0x000c, 0xc32: 0x000c, 0xc33: 0x000c, 0xc34: 0x000c, 0xc35: 0x000c, + 0xc36: 0x000c, 0xc37: 0x000c, 0xc38: 0x000c, 0xc39: 0x000c, 0xc3a: 0x000c, 0xc3b: 0x000c, + 0xc3c: 0x000c, 0xc3d: 0x000c, 0xc3e: 0x000c, + // Block 0x31, offset 0xc40 + 0xc40: 0x000c, 0xc41: 0x000c, 0xc42: 0x000c, 0xc43: 0x000c, 0xc44: 0x000c, + 0xc46: 0x000c, 0xc47: 0x000c, + 0xc4d: 0x000c, 0xc4e: 0x000c, 0xc4f: 0x000c, 0xc50: 0x000c, 0xc51: 0x000c, + 0xc52: 0x000c, 0xc53: 0x000c, 0xc54: 0x000c, 0xc55: 0x000c, 0xc56: 0x000c, 0xc57: 0x000c, + 0xc59: 0x000c, 0xc5a: 0x000c, 0xc5b: 0x000c, 0xc5c: 0x000c, 0xc5d: 0x000c, + 0xc5e: 0x000c, 0xc5f: 0x000c, 0xc60: 0x000c, 0xc61: 0x000c, 0xc62: 0x000c, 0xc63: 0x000c, + 0xc64: 0x000c, 0xc65: 0x000c, 0xc66: 0x000c, 0xc67: 0x000c, 0xc68: 0x000c, 0xc69: 0x000c, + 0xc6a: 0x000c, 0xc6b: 0x000c, 0xc6c: 0x000c, 0xc6d: 0x000c, 0xc6e: 0x000c, 0xc6f: 0x000c, + 0xc70: 0x000c, 0xc71: 0x000c, 0xc72: 0x000c, 0xc73: 0x000c, 0xc74: 0x000c, 0xc75: 0x000c, + 0xc76: 0x000c, 0xc77: 0x000c, 0xc78: 0x000c, 0xc79: 0x000c, 0xc7a: 0x000c, 0xc7b: 0x000c, + 0xc7c: 0x000c, + // Block 0x32, offset 0xc80 + 0xc86: 0x000c, + // Block 0x33, offset 0xcc0 + 0xced: 0x000c, 0xcee: 0x000c, 0xcef: 0x000c, + 0xcf0: 0x000c, 0xcf2: 0x000c, 0xcf3: 0x000c, 0xcf4: 0x000c, 0xcf5: 0x000c, + 0xcf6: 0x000c, 0xcf7: 0x000c, 0xcf9: 0x000c, 0xcfa: 0x000c, + 0xcfd: 0x000c, 0xcfe: 0x000c, + // Block 0x34, offset 0xd00 + 0xd18: 0x000c, 0xd19: 0x000c, + 0xd1e: 0x000c, 0xd1f: 0x000c, 0xd20: 0x000c, + 0xd31: 0x000c, 0xd32: 0x000c, 0xd33: 0x000c, 0xd34: 0x000c, + // Block 0x35, offset 0xd40 + 0xd42: 0x000c, 0xd45: 0x000c, + 0xd46: 0x000c, + 0xd4d: 0x000c, + 0xd5d: 0x000c, + // Block 0x36, offset 0xd80 + 0xd9d: 0x000c, + 0xd9e: 0x000c, 0xd9f: 0x000c, + // Block 0x37, offset 0xdc0 + 0xdd0: 0x000a, 0xdd1: 0x000a, + 0xdd2: 0x000a, 0xdd3: 0x000a, 0xdd4: 0x000a, 0xdd5: 0x000a, 0xdd6: 0x000a, 0xdd7: 0x000a, + 0xdd8: 0x000a, 0xdd9: 0x000a, + // Block 0x38, offset 0xe00 + 0xe00: 0x000a, + // Block 0x39, offset 0xe40 + 0xe40: 0x0009, + 0xe5b: 0x007a, 0xe5c: 0x006a, + // Block 0x3a, offset 0xe80 + 0xe92: 0x000c, 0xe93: 0x000c, 0xe94: 0x000c, + 0xeb2: 0x000c, 0xeb3: 0x000c, 0xeb4: 0x000c, + // Block 0x3b, offset 0xec0 + 0xed2: 0x000c, 0xed3: 0x000c, + 0xef2: 0x000c, 0xef3: 0x000c, + // Block 0x3c, offset 0xf00 + 0xf34: 0x000c, 0xf35: 0x000c, + 0xf37: 0x000c, 0xf38: 0x000c, 0xf39: 0x000c, 0xf3a: 0x000c, 0xf3b: 0x000c, + 0xf3c: 0x000c, 0xf3d: 0x000c, + // Block 0x3d, offset 0xf40 + 0xf46: 0x000c, 0xf49: 0x000c, 0xf4a: 0x000c, 0xf4b: 0x000c, + 0xf4c: 0x000c, 0xf4d: 0x000c, 0xf4e: 0x000c, 0xf4f: 0x000c, 0xf50: 0x000c, 0xf51: 0x000c, + 0xf52: 0x000c, 0xf53: 0x000c, + 0xf5b: 0x0004, 0xf5d: 0x000c, + 0xf70: 0x000a, 0xf71: 0x000a, 0xf72: 0x000a, 0xf73: 0x000a, 0xf74: 0x000a, 0xf75: 0x000a, + 0xf76: 0x000a, 0xf77: 0x000a, 0xf78: 0x000a, 0xf79: 0x000a, + // Block 0x3e, offset 0xf80 + 0xf80: 0x000a, 0xf81: 0x000a, 0xf82: 0x000a, 0xf83: 0x000a, 0xf84: 0x000a, 0xf85: 0x000a, + 0xf86: 0x000a, 0xf87: 0x000a, 0xf88: 0x000a, 0xf89: 0x000a, 0xf8a: 0x000a, 0xf8b: 0x000c, + 0xf8c: 0x000c, 0xf8d: 0x000c, 0xf8e: 0x000b, + // Block 0x3f, offset 0xfc0 + 0xfc5: 0x000c, + 0xfc6: 0x000c, + 0xfe9: 0x000c, + // Block 0x40, offset 0x1000 + 0x1020: 0x000c, 0x1021: 0x000c, 0x1022: 0x000c, + 0x1027: 0x000c, 0x1028: 0x000c, + 0x1032: 0x000c, + 0x1039: 0x000c, 0x103a: 0x000c, 0x103b: 0x000c, + // Block 0x41, offset 0x1040 + 0x1040: 0x000a, 0x1044: 0x000a, 0x1045: 0x000a, + // Block 0x42, offset 0x1080 + 0x109e: 0x000a, 0x109f: 0x000a, 0x10a0: 0x000a, 0x10a1: 0x000a, 0x10a2: 0x000a, 0x10a3: 0x000a, + 0x10a4: 0x000a, 0x10a5: 0x000a, 0x10a6: 0x000a, 0x10a7: 0x000a, 0x10a8: 0x000a, 0x10a9: 0x000a, + 0x10aa: 0x000a, 0x10ab: 0x000a, 0x10ac: 0x000a, 0x10ad: 0x000a, 0x10ae: 0x000a, 0x10af: 0x000a, + 0x10b0: 0x000a, 0x10b1: 0x000a, 0x10b2: 0x000a, 0x10b3: 0x000a, 0x10b4: 0x000a, 0x10b5: 0x000a, + 0x10b6: 0x000a, 0x10b7: 0x000a, 0x10b8: 0x000a, 0x10b9: 0x000a, 0x10ba: 0x000a, 0x10bb: 0x000a, + 0x10bc: 0x000a, 0x10bd: 0x000a, 0x10be: 0x000a, 0x10bf: 0x000a, + // Block 0x43, offset 0x10c0 + 0x10d7: 0x000c, + 0x10d8: 0x000c, 0x10db: 0x000c, + // Block 0x44, offset 0x1100 + 0x1116: 0x000c, + 0x1118: 0x000c, 0x1119: 0x000c, 0x111a: 0x000c, 0x111b: 0x000c, 0x111c: 0x000c, 0x111d: 0x000c, + 0x111e: 0x000c, 0x1120: 0x000c, 0x1122: 0x000c, + 0x1125: 0x000c, 0x1126: 0x000c, 0x1127: 0x000c, 0x1128: 0x000c, 0x1129: 0x000c, + 0x112a: 0x000c, 0x112b: 0x000c, 0x112c: 0x000c, + 0x1133: 0x000c, 0x1134: 0x000c, 0x1135: 0x000c, + 0x1136: 0x000c, 0x1137: 0x000c, 0x1138: 0x000c, 0x1139: 0x000c, 0x113a: 0x000c, 0x113b: 0x000c, + 0x113c: 0x000c, 0x113f: 0x000c, + // Block 0x45, offset 0x1140 + 0x1170: 0x000c, 0x1171: 0x000c, 0x1172: 0x000c, 0x1173: 0x000c, 0x1174: 0x000c, 0x1175: 0x000c, + 0x1176: 0x000c, 0x1177: 0x000c, 0x1178: 0x000c, 0x1179: 0x000c, 0x117a: 0x000c, 0x117b: 0x000c, + 0x117c: 0x000c, 0x117d: 0x000c, 0x117e: 0x000c, + // Block 0x46, offset 0x1180 + 0x1180: 0x000c, 0x1181: 0x000c, 0x1182: 0x000c, 0x1183: 0x000c, + 0x11b4: 0x000c, + 0x11b6: 0x000c, 0x11b7: 0x000c, 0x11b8: 0x000c, 0x11b9: 0x000c, 0x11ba: 0x000c, + 0x11bc: 0x000c, + // Block 0x47, offset 0x11c0 + 0x11c2: 0x000c, + 0x11eb: 0x000c, 0x11ec: 0x000c, 0x11ed: 0x000c, 0x11ee: 0x000c, 0x11ef: 0x000c, + 0x11f0: 0x000c, 0x11f1: 0x000c, 0x11f2: 0x000c, 0x11f3: 0x000c, + // Block 0x48, offset 0x1200 + 0x1200: 0x000c, 0x1201: 0x000c, + 0x1222: 0x000c, 0x1223: 0x000c, + 0x1224: 0x000c, 0x1225: 0x000c, 0x1228: 0x000c, 0x1229: 0x000c, + 0x122b: 0x000c, 0x122c: 0x000c, 0x122d: 0x000c, + // Block 0x49, offset 0x1240 + 0x1266: 0x000c, 0x1268: 0x000c, 0x1269: 0x000c, + 0x126d: 0x000c, 0x126f: 0x000c, + 0x1270: 0x000c, 0x1271: 0x000c, + // Block 0x4a, offset 0x1280 + 0x12ac: 0x000c, 0x12ad: 0x000c, 0x12ae: 0x000c, 0x12af: 0x000c, + 0x12b0: 0x000c, 0x12b1: 0x000c, 0x12b2: 0x000c, 0x12b3: 0x000c, + 0x12b6: 0x000c, 0x12b7: 0x000c, + // Block 0x4b, offset 0x12c0 + 0x12d0: 0x000c, 0x12d1: 0x000c, + 0x12d2: 0x000c, 0x12d4: 0x000c, 0x12d5: 0x000c, 0x12d6: 0x000c, 0x12d7: 0x000c, + 0x12d8: 0x000c, 0x12d9: 0x000c, 0x12da: 0x000c, 0x12db: 0x000c, 0x12dc: 0x000c, 0x12dd: 0x000c, + 0x12de: 0x000c, 0x12df: 0x000c, 0x12e0: 0x000c, 0x12e2: 0x000c, 0x12e3: 0x000c, + 0x12e4: 0x000c, 0x12e5: 0x000c, 0x12e6: 0x000c, 0x12e7: 0x000c, 0x12e8: 0x000c, + 0x12ed: 0x000c, + 0x12f4: 0x000c, + 0x12f8: 0x000c, 0x12f9: 0x000c, + // Block 0x4c, offset 0x1300 + 0x1300: 0x000c, 0x1301: 0x000c, 0x1302: 0x000c, 0x1303: 0x000c, 0x1304: 0x000c, 0x1305: 0x000c, + 0x1306: 0x000c, 0x1307: 0x000c, 0x1308: 0x000c, 0x1309: 0x000c, 0x130a: 0x000c, 0x130b: 0x000c, + 0x130c: 0x000c, 0x130d: 0x000c, 0x130e: 0x000c, 0x130f: 0x000c, 0x1310: 0x000c, 0x1311: 0x000c, + 0x1312: 0x000c, 0x1313: 0x000c, 0x1314: 0x000c, 0x1315: 0x000c, 0x1316: 0x000c, 0x1317: 0x000c, + 0x1318: 0x000c, 0x1319: 0x000c, 0x131a: 0x000c, 0x131b: 0x000c, 0x131c: 0x000c, 0x131d: 0x000c, + 0x131e: 0x000c, 0x131f: 0x000c, 0x1320: 0x000c, 0x1321: 0x000c, 0x1322: 0x000c, 0x1323: 0x000c, + 0x1324: 0x000c, 0x1325: 0x000c, 0x1326: 0x000c, 0x1327: 0x000c, 0x1328: 0x000c, 0x1329: 0x000c, + 0x132a: 0x000c, 0x132b: 0x000c, 0x132c: 0x000c, 0x132d: 0x000c, 0x132e: 0x000c, 0x132f: 0x000c, + 0x1330: 0x000c, 0x1331: 0x000c, 0x1332: 0x000c, 0x1333: 0x000c, 0x1334: 0x000c, 0x1335: 0x000c, + 0x133b: 0x000c, + 0x133c: 0x000c, 0x133d: 0x000c, 0x133e: 0x000c, 0x133f: 0x000c, + // Block 0x4d, offset 0x1340 + 0x137d: 0x000a, 0x137f: 0x000a, + // Block 0x4e, offset 0x1380 + 0x1380: 0x000a, 0x1381: 0x000a, + 0x138d: 0x000a, 0x138e: 0x000a, 0x138f: 0x000a, + 0x139d: 0x000a, + 0x139e: 0x000a, 0x139f: 0x000a, + 0x13ad: 0x000a, 0x13ae: 0x000a, 0x13af: 0x000a, + 0x13bd: 0x000a, 0x13be: 0x000a, + // Block 0x4f, offset 0x13c0 + 0x13c0: 0x0009, 0x13c1: 0x0009, 0x13c2: 0x0009, 0x13c3: 0x0009, 0x13c4: 0x0009, 0x13c5: 0x0009, + 0x13c6: 0x0009, 0x13c7: 0x0009, 0x13c8: 0x0009, 0x13c9: 0x0009, 0x13ca: 0x0009, 0x13cb: 0x000b, + 0x13cc: 0x000b, 0x13cd: 0x000b, 0x13cf: 0x0001, 0x13d0: 0x000a, 0x13d1: 0x000a, + 0x13d2: 0x000a, 0x13d3: 0x000a, 0x13d4: 0x000a, 0x13d5: 0x000a, 0x13d6: 0x000a, 0x13d7: 0x000a, + 0x13d8: 0x000a, 0x13d9: 0x000a, 0x13da: 0x000a, 0x13db: 0x000a, 0x13dc: 0x000a, 0x13dd: 0x000a, + 0x13de: 0x000a, 0x13df: 0x000a, 0x13e0: 0x000a, 0x13e1: 0x000a, 0x13e2: 0x000a, 0x13e3: 0x000a, + 0x13e4: 0x000a, 0x13e5: 0x000a, 0x13e6: 0x000a, 0x13e7: 0x000a, 0x13e8: 0x0009, 0x13e9: 0x0007, + 0x13ea: 0x000e, 0x13eb: 0x000e, 0x13ec: 0x000e, 0x13ed: 0x000e, 0x13ee: 0x000e, 0x13ef: 0x0006, + 0x13f0: 0x0004, 0x13f1: 0x0004, 0x13f2: 0x0004, 0x13f3: 0x0004, 0x13f4: 0x0004, 0x13f5: 0x000a, + 0x13f6: 0x000a, 0x13f7: 0x000a, 0x13f8: 0x000a, 0x13f9: 0x000a, 0x13fa: 0x000a, 0x13fb: 0x000a, + 0x13fc: 0x000a, 0x13fd: 0x000a, 0x13fe: 0x000a, 0x13ff: 0x000a, + // Block 0x50, offset 0x1400 + 0x1400: 0x000a, 0x1401: 0x000a, 0x1402: 0x000a, 0x1403: 0x000a, 0x1404: 0x0006, 0x1405: 0x009a, + 0x1406: 0x008a, 0x1407: 0x000a, 0x1408: 0x000a, 0x1409: 0x000a, 0x140a: 0x000a, 0x140b: 0x000a, + 0x140c: 0x000a, 0x140d: 0x000a, 0x140e: 0x000a, 0x140f: 0x000a, 0x1410: 0x000a, 0x1411: 0x000a, + 0x1412: 0x000a, 0x1413: 0x000a, 0x1414: 0x000a, 0x1415: 0x000a, 0x1416: 0x000a, 0x1417: 0x000a, + 0x1418: 0x000a, 0x1419: 0x000a, 0x141a: 0x000a, 0x141b: 0x000a, 0x141c: 0x000a, 0x141d: 0x000a, + 0x141e: 0x000a, 0x141f: 0x0009, 0x1420: 0x000b, 0x1421: 0x000b, 0x1422: 0x000b, 0x1423: 0x000b, + 0x1424: 0x000b, 0x1425: 0x000b, 0x1426: 0x000e, 0x1427: 0x000e, 0x1428: 0x000e, 0x1429: 0x000e, + 0x142a: 0x000b, 0x142b: 0x000b, 0x142c: 0x000b, 0x142d: 0x000b, 0x142e: 0x000b, 0x142f: 0x000b, + 0x1430: 0x0002, 0x1434: 0x0002, 0x1435: 0x0002, + 0x1436: 0x0002, 0x1437: 0x0002, 0x1438: 0x0002, 0x1439: 0x0002, 0x143a: 0x0003, 0x143b: 0x0003, + 0x143c: 0x000a, 0x143d: 0x009a, 0x143e: 0x008a, + // Block 0x51, offset 0x1440 + 0x1440: 0x0002, 0x1441: 0x0002, 0x1442: 0x0002, 0x1443: 0x0002, 0x1444: 0x0002, 0x1445: 0x0002, + 0x1446: 0x0002, 0x1447: 0x0002, 0x1448: 0x0002, 0x1449: 0x0002, 0x144a: 0x0003, 0x144b: 0x0003, + 0x144c: 0x000a, 0x144d: 0x009a, 0x144e: 0x008a, + 0x1460: 0x0004, 0x1461: 0x0004, 0x1462: 0x0004, 0x1463: 0x0004, + 0x1464: 0x0004, 0x1465: 0x0004, 0x1466: 0x0004, 0x1467: 0x0004, 0x1468: 0x0004, 0x1469: 0x0004, + 0x146a: 0x0004, 0x146b: 0x0004, 0x146c: 0x0004, 0x146d: 0x0004, 0x146e: 0x0004, 0x146f: 0x0004, + 0x1470: 0x0004, 0x1471: 0x0004, 0x1472: 0x0004, 0x1473: 0x0004, 0x1474: 0x0004, 0x1475: 0x0004, + 0x1476: 0x0004, 0x1477: 0x0004, 0x1478: 0x0004, 0x1479: 0x0004, 0x147a: 0x0004, 0x147b: 0x0004, + 0x147c: 0x0004, 0x147d: 0x0004, 0x147e: 0x0004, 0x147f: 0x0004, + // Block 0x52, offset 0x1480 + 0x1480: 0x0004, 0x1481: 0x0004, 0x1482: 0x0004, 0x1483: 0x0004, 0x1484: 0x0004, 0x1485: 0x0004, + 0x1486: 0x0004, 0x1487: 0x0004, 0x1488: 0x0004, 0x1489: 0x0004, 0x148a: 0x0004, 0x148b: 0x0004, + 0x148c: 0x0004, 0x148d: 0x0004, 0x148e: 0x0004, 0x148f: 0x0004, 0x1490: 0x000c, 0x1491: 0x000c, + 0x1492: 0x000c, 0x1493: 0x000c, 0x1494: 0x000c, 0x1495: 0x000c, 0x1496: 0x000c, 0x1497: 0x000c, + 0x1498: 0x000c, 0x1499: 0x000c, 0x149a: 0x000c, 0x149b: 0x000c, 0x149c: 0x000c, 0x149d: 0x000c, + 0x149e: 0x000c, 0x149f: 0x000c, 0x14a0: 0x000c, 0x14a1: 0x000c, 0x14a2: 0x000c, 0x14a3: 0x000c, + 0x14a4: 0x000c, 0x14a5: 0x000c, 0x14a6: 0x000c, 0x14a7: 0x000c, 0x14a8: 0x000c, 0x14a9: 0x000c, + 0x14aa: 0x000c, 0x14ab: 0x000c, 0x14ac: 0x000c, 0x14ad: 0x000c, 0x14ae: 0x000c, 0x14af: 0x000c, + 0x14b0: 0x000c, + // Block 0x53, offset 0x14c0 + 0x14c0: 0x000a, 0x14c1: 0x000a, 0x14c3: 0x000a, 0x14c4: 0x000a, 0x14c5: 0x000a, + 0x14c6: 0x000a, 0x14c8: 0x000a, 0x14c9: 0x000a, + 0x14d4: 0x000a, 0x14d6: 0x000a, 0x14d7: 0x000a, + 0x14d8: 0x000a, + 0x14de: 0x000a, 0x14df: 0x000a, 0x14e0: 0x000a, 0x14e1: 0x000a, 0x14e2: 0x000a, 0x14e3: 0x000a, + 0x14e5: 0x000a, 0x14e7: 0x000a, 0x14e9: 0x000a, + 0x14ee: 0x0004, + 0x14fa: 0x000a, 0x14fb: 0x000a, + // Block 0x54, offset 0x1500 + 0x1500: 0x000a, 0x1501: 0x000a, 0x1502: 0x000a, 0x1503: 0x000a, 0x1504: 0x000a, + 0x150a: 0x000a, 0x150b: 0x000a, + 0x150c: 0x000a, 0x150d: 0x000a, 0x1510: 0x000a, 0x1511: 0x000a, + 0x1512: 0x000a, 0x1513: 0x000a, 0x1514: 0x000a, 0x1515: 0x000a, 0x1516: 0x000a, 0x1517: 0x000a, + 0x1518: 0x000a, 0x1519: 0x000a, 0x151a: 0x000a, 0x151b: 0x000a, 0x151c: 0x000a, 0x151d: 0x000a, + 0x151e: 0x000a, 0x151f: 0x000a, + // Block 0x55, offset 0x1540 + 0x1549: 0x000a, 0x154a: 0x000a, 0x154b: 0x000a, + 0x1550: 0x000a, 0x1551: 0x000a, + 0x1552: 0x000a, 0x1553: 0x000a, 0x1554: 0x000a, 0x1555: 0x000a, 0x1556: 0x000a, 0x1557: 0x000a, + 0x1558: 0x000a, 0x1559: 0x000a, 0x155a: 0x000a, 0x155b: 0x000a, 0x155c: 0x000a, 0x155d: 0x000a, + 0x155e: 0x000a, 0x155f: 0x000a, 0x1560: 0x000a, 0x1561: 0x000a, 0x1562: 0x000a, 0x1563: 0x000a, + 0x1564: 0x000a, 0x1565: 0x000a, 0x1566: 0x000a, 0x1567: 0x000a, 0x1568: 0x000a, 0x1569: 0x000a, + 0x156a: 0x000a, 0x156b: 0x000a, 0x156c: 0x000a, 0x156d: 0x000a, 0x156e: 0x000a, 0x156f: 0x000a, + 0x1570: 0x000a, 0x1571: 0x000a, 0x1572: 0x000a, 0x1573: 0x000a, 0x1574: 0x000a, 0x1575: 0x000a, + 0x1576: 0x000a, 0x1577: 0x000a, 0x1578: 0x000a, 0x1579: 0x000a, 0x157a: 0x000a, 0x157b: 0x000a, + 0x157c: 0x000a, 0x157d: 0x000a, 0x157e: 0x000a, 0x157f: 0x000a, + // Block 0x56, offset 0x1580 + 0x1580: 0x000a, 0x1581: 0x000a, 0x1582: 0x000a, 0x1583: 0x000a, 0x1584: 0x000a, 0x1585: 0x000a, + 0x1586: 0x000a, 0x1587: 0x000a, 0x1588: 0x000a, 0x1589: 0x000a, 0x158a: 0x000a, 0x158b: 0x000a, + 0x158c: 0x000a, 0x158d: 0x000a, 0x158e: 0x000a, 0x158f: 0x000a, 0x1590: 0x000a, 0x1591: 0x000a, + 0x1592: 0x000a, 0x1593: 0x000a, 0x1594: 0x000a, 0x1595: 0x000a, 0x1596: 0x000a, 0x1597: 0x000a, + 0x1598: 0x000a, 0x1599: 0x000a, 0x159a: 0x000a, 0x159b: 0x000a, 0x159c: 0x000a, 0x159d: 0x000a, + 0x159e: 0x000a, 0x159f: 0x000a, 0x15a0: 0x000a, 0x15a1: 0x000a, 0x15a2: 0x000a, 0x15a3: 0x000a, + 0x15a4: 0x000a, 0x15a5: 0x000a, 0x15a6: 0x000a, 0x15a7: 0x000a, 0x15a8: 0x000a, 0x15a9: 0x000a, + 0x15aa: 0x000a, 0x15ab: 0x000a, 0x15ac: 0x000a, 0x15ad: 0x000a, 0x15ae: 0x000a, 0x15af: 0x000a, + 0x15b0: 0x000a, 0x15b1: 0x000a, 0x15b2: 0x000a, 0x15b3: 0x000a, 0x15b4: 0x000a, 0x15b5: 0x000a, + 0x15b6: 0x000a, 0x15b7: 0x000a, 0x15b8: 0x000a, 0x15b9: 0x000a, 0x15ba: 0x000a, 0x15bb: 0x000a, + 0x15bc: 0x000a, 0x15bd: 0x000a, 0x15be: 0x000a, 0x15bf: 0x000a, + // Block 0x57, offset 0x15c0 + 0x15c0: 0x000a, 0x15c1: 0x000a, 0x15c2: 0x000a, 0x15c3: 0x000a, 0x15c4: 0x000a, 0x15c5: 0x000a, + 0x15c6: 0x000a, 0x15c7: 0x000a, 0x15c8: 0x000a, 0x15c9: 0x000a, 0x15ca: 0x000a, 0x15cb: 0x000a, + 0x15cc: 0x000a, 0x15cd: 0x000a, 0x15ce: 0x000a, 0x15cf: 0x000a, 0x15d0: 0x000a, 0x15d1: 0x000a, + 0x15d2: 0x0003, 0x15d3: 0x0004, 0x15d4: 0x000a, 0x15d5: 0x000a, 0x15d6: 0x000a, 0x15d7: 0x000a, + 0x15d8: 0x000a, 0x15d9: 0x000a, 0x15da: 0x000a, 0x15db: 0x000a, 0x15dc: 0x000a, 0x15dd: 0x000a, + 0x15de: 0x000a, 0x15df: 0x000a, 0x15e0: 0x000a, 0x15e1: 0x000a, 0x15e2: 0x000a, 0x15e3: 0x000a, + 0x15e4: 0x000a, 0x15e5: 0x000a, 0x15e6: 0x000a, 0x15e7: 0x000a, 0x15e8: 0x000a, 0x15e9: 0x000a, + 0x15ea: 0x000a, 0x15eb: 0x000a, 0x15ec: 0x000a, 0x15ed: 0x000a, 0x15ee: 0x000a, 0x15ef: 0x000a, + 0x15f0: 0x000a, 0x15f1: 0x000a, 0x15f2: 0x000a, 0x15f3: 0x000a, 0x15f4: 0x000a, 0x15f5: 0x000a, + 0x15f6: 0x000a, 0x15f7: 0x000a, 0x15f8: 0x000a, 0x15f9: 0x000a, 0x15fa: 0x000a, 0x15fb: 0x000a, + 0x15fc: 0x000a, 0x15fd: 0x000a, 0x15fe: 0x000a, 0x15ff: 0x000a, + // Block 0x58, offset 0x1600 + 0x1600: 0x000a, 0x1601: 0x000a, 0x1602: 0x000a, 0x1603: 0x000a, 0x1604: 0x000a, 0x1605: 0x000a, + 0x1606: 0x000a, 0x1607: 0x000a, 0x1608: 0x003a, 0x1609: 0x002a, 0x160a: 0x003a, 0x160b: 0x002a, + 0x160c: 0x000a, 0x160d: 0x000a, 0x160e: 0x000a, 0x160f: 0x000a, 0x1610: 0x000a, 0x1611: 0x000a, + 0x1612: 0x000a, 0x1613: 0x000a, 0x1614: 0x000a, 0x1615: 0x000a, 0x1616: 0x000a, 0x1617: 0x000a, + 0x1618: 0x000a, 0x1619: 0x000a, 0x161a: 0x000a, 0x161b: 0x000a, 0x161c: 0x000a, 0x161d: 0x000a, + 0x161e: 0x000a, 0x161f: 0x000a, 0x1620: 0x000a, 0x1621: 0x000a, 0x1622: 0x000a, 0x1623: 0x000a, + 0x1624: 0x000a, 0x1625: 0x000a, 0x1626: 0x000a, 0x1627: 0x000a, 0x1628: 0x000a, 0x1629: 0x009a, + 0x162a: 0x008a, 0x162b: 0x000a, 0x162c: 0x000a, 0x162d: 0x000a, 0x162e: 0x000a, 0x162f: 0x000a, + 0x1630: 0x000a, 0x1631: 0x000a, 0x1632: 0x000a, 0x1633: 0x000a, 0x1634: 0x000a, 0x1635: 0x000a, + // Block 0x59, offset 0x1640 + 0x167b: 0x000a, + 0x167c: 0x000a, 0x167d: 0x000a, 0x167e: 0x000a, 0x167f: 0x000a, + // Block 0x5a, offset 0x1680 + 0x1680: 0x000a, 0x1681: 0x000a, 0x1682: 0x000a, 0x1683: 0x000a, 0x1684: 0x000a, 0x1685: 0x000a, + 0x1686: 0x000a, 0x1687: 0x000a, 0x1688: 0x000a, 0x1689: 0x000a, 0x168a: 0x000a, 0x168b: 0x000a, + 0x168c: 0x000a, 0x168d: 0x000a, 0x168e: 0x000a, 0x168f: 0x000a, 0x1690: 0x000a, 0x1691: 0x000a, + 0x1692: 0x000a, 0x1693: 0x000a, 0x1694: 0x000a, 0x1696: 0x000a, 0x1697: 0x000a, + 0x1698: 0x000a, 0x1699: 0x000a, 0x169a: 0x000a, 0x169b: 0x000a, 0x169c: 0x000a, 0x169d: 0x000a, + 0x169e: 0x000a, 0x169f: 0x000a, 0x16a0: 0x000a, 0x16a1: 0x000a, 0x16a2: 0x000a, 0x16a3: 0x000a, + 0x16a4: 0x000a, 0x16a5: 0x000a, 0x16a6: 0x000a, 0x16a7: 0x000a, 0x16a8: 0x000a, 0x16a9: 0x000a, + 0x16aa: 0x000a, 0x16ab: 0x000a, 0x16ac: 0x000a, 0x16ad: 0x000a, 0x16ae: 0x000a, 0x16af: 0x000a, + 0x16b0: 0x000a, 0x16b1: 0x000a, 0x16b2: 0x000a, 0x16b3: 0x000a, 0x16b4: 0x000a, 0x16b5: 0x000a, + 0x16b6: 0x000a, 0x16b7: 0x000a, 0x16b8: 0x000a, 0x16b9: 0x000a, 0x16ba: 0x000a, 0x16bb: 0x000a, + 0x16bc: 0x000a, 0x16bd: 0x000a, 0x16be: 0x000a, 0x16bf: 0x000a, + // Block 0x5b, offset 0x16c0 + 0x16c0: 0x000a, 0x16c1: 0x000a, 0x16c2: 0x000a, 0x16c3: 0x000a, 0x16c4: 0x000a, 0x16c5: 0x000a, + 0x16c6: 0x000a, 0x16c7: 0x000a, 0x16c8: 0x000a, 0x16c9: 0x000a, 0x16ca: 0x000a, 0x16cb: 0x000a, + 0x16cc: 0x000a, 0x16cd: 0x000a, 0x16ce: 0x000a, 0x16cf: 0x000a, 0x16d0: 0x000a, 0x16d1: 0x000a, + 0x16d2: 0x000a, 0x16d3: 0x000a, 0x16d4: 0x000a, 0x16d5: 0x000a, 0x16d6: 0x000a, 0x16d7: 0x000a, + 0x16d8: 0x000a, 0x16d9: 0x000a, 0x16da: 0x000a, 0x16db: 0x000a, 0x16dc: 0x000a, 0x16dd: 0x000a, + 0x16de: 0x000a, 0x16df: 0x000a, 0x16e0: 0x000a, 0x16e1: 0x000a, 0x16e2: 0x000a, 0x16e3: 0x000a, + 0x16e4: 0x000a, 0x16e5: 0x000a, 0x16e6: 0x000a, 0x16e7: 0x000a, 0x16e8: 0x000a, 0x16e9: 0x000a, + 0x16ea: 0x000a, 0x16eb: 0x000a, 0x16ec: 0x000a, 0x16ed: 0x000a, 0x16ee: 0x000a, 0x16ef: 0x000a, + 0x16f0: 0x000a, 0x16f1: 0x000a, 0x16f2: 0x000a, 0x16f3: 0x000a, 0x16f4: 0x000a, 0x16f5: 0x000a, + 0x16f6: 0x000a, 0x16f7: 0x000a, 0x16f8: 0x000a, 0x16f9: 0x000a, 0x16fa: 0x000a, 0x16fb: 0x000a, + 0x16fc: 0x000a, 0x16fd: 0x000a, 0x16fe: 0x000a, + // Block 0x5c, offset 0x1700 + 0x1700: 0x000a, 0x1701: 0x000a, 0x1702: 0x000a, 0x1703: 0x000a, 0x1704: 0x000a, 0x1705: 0x000a, + 0x1706: 0x000a, 0x1707: 0x000a, 0x1708: 0x000a, 0x1709: 0x000a, 0x170a: 0x000a, 0x170b: 0x000a, + 0x170c: 0x000a, 0x170d: 0x000a, 0x170e: 0x000a, 0x170f: 0x000a, 0x1710: 0x000a, 0x1711: 0x000a, + 0x1712: 0x000a, 0x1713: 0x000a, 0x1714: 0x000a, 0x1715: 0x000a, 0x1716: 0x000a, 0x1717: 0x000a, + 0x1718: 0x000a, 0x1719: 0x000a, 0x171a: 0x000a, 0x171b: 0x000a, 0x171c: 0x000a, 0x171d: 0x000a, + 0x171e: 0x000a, 0x171f: 0x000a, 0x1720: 0x000a, 0x1721: 0x000a, 0x1722: 0x000a, 0x1723: 0x000a, + 0x1724: 0x000a, 0x1725: 0x000a, 0x1726: 0x000a, + // Block 0x5d, offset 0x1740 + 0x1740: 0x000a, 0x1741: 0x000a, 0x1742: 0x000a, 0x1743: 0x000a, 0x1744: 0x000a, 0x1745: 0x000a, + 0x1746: 0x000a, 0x1747: 0x000a, 0x1748: 0x000a, 0x1749: 0x000a, 0x174a: 0x000a, + 0x1760: 0x000a, 0x1761: 0x000a, 0x1762: 0x000a, 0x1763: 0x000a, + 0x1764: 0x000a, 0x1765: 0x000a, 0x1766: 0x000a, 0x1767: 0x000a, 0x1768: 0x000a, 0x1769: 0x000a, + 0x176a: 0x000a, 0x176b: 0x000a, 0x176c: 0x000a, 0x176d: 0x000a, 0x176e: 0x000a, 0x176f: 0x000a, + 0x1770: 0x000a, 0x1771: 0x000a, 0x1772: 0x000a, 0x1773: 0x000a, 0x1774: 0x000a, 0x1775: 0x000a, + 0x1776: 0x000a, 0x1777: 0x000a, 0x1778: 0x000a, 0x1779: 0x000a, 0x177a: 0x000a, 0x177b: 0x000a, + 0x177c: 0x000a, 0x177d: 0x000a, 0x177e: 0x000a, 0x177f: 0x000a, + // Block 0x5e, offset 0x1780 + 0x1780: 0x000a, 0x1781: 0x000a, 0x1782: 0x000a, 0x1783: 0x000a, 0x1784: 0x000a, 0x1785: 0x000a, + 0x1786: 0x000a, 0x1787: 0x000a, 0x1788: 0x0002, 0x1789: 0x0002, 0x178a: 0x0002, 0x178b: 0x0002, + 0x178c: 0x0002, 0x178d: 0x0002, 0x178e: 0x0002, 0x178f: 0x0002, 0x1790: 0x0002, 0x1791: 0x0002, + 0x1792: 0x0002, 0x1793: 0x0002, 0x1794: 0x0002, 0x1795: 0x0002, 0x1796: 0x0002, 0x1797: 0x0002, + 0x1798: 0x0002, 0x1799: 0x0002, 0x179a: 0x0002, 0x179b: 0x0002, + // Block 0x5f, offset 0x17c0 + 0x17ea: 0x000a, 0x17eb: 0x000a, 0x17ec: 0x000a, 0x17ed: 0x000a, 0x17ee: 0x000a, 0x17ef: 0x000a, + 0x17f0: 0x000a, 0x17f1: 0x000a, 0x17f2: 0x000a, 0x17f3: 0x000a, 0x17f4: 0x000a, 0x17f5: 0x000a, + 0x17f6: 0x000a, 0x17f7: 0x000a, 0x17f8: 0x000a, 0x17f9: 0x000a, 0x17fa: 0x000a, 0x17fb: 0x000a, + 0x17fc: 0x000a, 0x17fd: 0x000a, 0x17fe: 0x000a, 0x17ff: 0x000a, + // Block 0x60, offset 0x1800 + 0x1800: 0x000a, 0x1801: 0x000a, 0x1802: 0x000a, 0x1803: 0x000a, 0x1804: 0x000a, 0x1805: 0x000a, + 0x1806: 0x000a, 0x1807: 0x000a, 0x1808: 0x000a, 0x1809: 0x000a, 0x180a: 0x000a, 0x180b: 0x000a, + 0x180c: 0x000a, 0x180d: 0x000a, 0x180e: 0x000a, 0x180f: 0x000a, 0x1810: 0x000a, 0x1811: 0x000a, + 0x1812: 0x000a, 0x1813: 0x000a, 0x1814: 0x000a, 0x1815: 0x000a, 0x1816: 0x000a, 0x1817: 0x000a, + 0x1818: 0x000a, 0x1819: 0x000a, 0x181a: 0x000a, 0x181b: 0x000a, 0x181c: 0x000a, 0x181d: 0x000a, + 0x181e: 0x000a, 0x181f: 0x000a, 0x1820: 0x000a, 0x1821: 0x000a, 0x1822: 0x000a, 0x1823: 0x000a, + 0x1824: 0x000a, 0x1825: 0x000a, 0x1826: 0x000a, 0x1827: 0x000a, 0x1828: 0x000a, 0x1829: 0x000a, + 0x182a: 0x000a, 0x182b: 0x000a, 0x182d: 0x000a, 0x182e: 0x000a, 0x182f: 0x000a, + 0x1830: 0x000a, 0x1831: 0x000a, 0x1832: 0x000a, 0x1833: 0x000a, 0x1834: 0x000a, 0x1835: 0x000a, + 0x1836: 0x000a, 0x1837: 0x000a, 0x1838: 0x000a, 0x1839: 0x000a, 0x183a: 0x000a, 0x183b: 0x000a, + 0x183c: 0x000a, 0x183d: 0x000a, 0x183e: 0x000a, 0x183f: 0x000a, + // Block 0x61, offset 0x1840 + 0x1840: 0x000a, 0x1841: 0x000a, 0x1842: 0x000a, 0x1843: 0x000a, 0x1844: 0x000a, 0x1845: 0x000a, + 0x1846: 0x000a, 0x1847: 0x000a, 0x1848: 0x000a, 0x1849: 0x000a, 0x184a: 0x000a, 0x184b: 0x000a, + 0x184c: 0x000a, 0x184d: 0x000a, 0x184e: 0x000a, 0x184f: 0x000a, 0x1850: 0x000a, 0x1851: 0x000a, + 0x1852: 0x000a, 0x1853: 0x000a, 0x1854: 0x000a, 0x1855: 0x000a, 0x1856: 0x000a, 0x1857: 0x000a, + 0x1858: 0x000a, 0x1859: 0x000a, 0x185a: 0x000a, 0x185b: 0x000a, 0x185c: 0x000a, 0x185d: 0x000a, + 0x185e: 0x000a, 0x185f: 0x000a, 0x1860: 0x000a, 0x1861: 0x000a, 0x1862: 0x000a, 0x1863: 0x000a, + 0x1864: 0x000a, 0x1865: 0x000a, 0x1866: 0x000a, 0x1867: 0x000a, 0x1868: 0x003a, 0x1869: 0x002a, + 0x186a: 0x003a, 0x186b: 0x002a, 0x186c: 0x003a, 0x186d: 0x002a, 0x186e: 0x003a, 0x186f: 0x002a, + 0x1870: 0x003a, 0x1871: 0x002a, 0x1872: 0x003a, 0x1873: 0x002a, 0x1874: 0x003a, 0x1875: 0x002a, + 0x1876: 0x000a, 0x1877: 0x000a, 0x1878: 0x000a, 0x1879: 0x000a, 0x187a: 0x000a, 0x187b: 0x000a, + 0x187c: 0x000a, 0x187d: 0x000a, 0x187e: 0x000a, 0x187f: 0x000a, + // Block 0x62, offset 0x1880 + 0x1880: 0x000a, 0x1881: 0x000a, 0x1882: 0x000a, 0x1883: 0x000a, 0x1884: 0x000a, 0x1885: 0x009a, + 0x1886: 0x008a, 0x1887: 0x000a, 0x1888: 0x000a, 0x1889: 0x000a, 0x188a: 0x000a, 0x188b: 0x000a, + 0x188c: 0x000a, 0x188d: 0x000a, 0x188e: 0x000a, 0x188f: 0x000a, 0x1890: 0x000a, 0x1891: 0x000a, + 0x1892: 0x000a, 0x1893: 0x000a, 0x1894: 0x000a, 0x1895: 0x000a, 0x1896: 0x000a, 0x1897: 0x000a, + 0x1898: 0x000a, 0x1899: 0x000a, 0x189a: 0x000a, 0x189b: 0x000a, 0x189c: 0x000a, 0x189d: 0x000a, + 0x189e: 0x000a, 0x189f: 0x000a, 0x18a0: 0x000a, 0x18a1: 0x000a, 0x18a2: 0x000a, 0x18a3: 0x000a, + 0x18a4: 0x000a, 0x18a5: 0x000a, 0x18a6: 0x003a, 0x18a7: 0x002a, 0x18a8: 0x003a, 0x18a9: 0x002a, + 0x18aa: 0x003a, 0x18ab: 0x002a, 0x18ac: 0x003a, 0x18ad: 0x002a, 0x18ae: 0x003a, 0x18af: 0x002a, + 0x18b0: 0x000a, 0x18b1: 0x000a, 0x18b2: 0x000a, 0x18b3: 0x000a, 0x18b4: 0x000a, 0x18b5: 0x000a, + 0x18b6: 0x000a, 0x18b7: 0x000a, 0x18b8: 0x000a, 0x18b9: 0x000a, 0x18ba: 0x000a, 0x18bb: 0x000a, + 0x18bc: 0x000a, 0x18bd: 0x000a, 0x18be: 0x000a, 0x18bf: 0x000a, + // Block 0x63, offset 0x18c0 + 0x18c0: 0x000a, 0x18c1: 0x000a, 0x18c2: 0x000a, 0x18c3: 0x007a, 0x18c4: 0x006a, 0x18c5: 0x009a, + 0x18c6: 0x008a, 0x18c7: 0x00ba, 0x18c8: 0x00aa, 0x18c9: 0x009a, 0x18ca: 0x008a, 0x18cb: 0x007a, + 0x18cc: 0x006a, 0x18cd: 0x00da, 0x18ce: 0x002a, 0x18cf: 0x003a, 0x18d0: 0x00ca, 0x18d1: 0x009a, + 0x18d2: 0x008a, 0x18d3: 0x007a, 0x18d4: 0x006a, 0x18d5: 0x009a, 0x18d6: 0x008a, 0x18d7: 0x00ba, + 0x18d8: 0x00aa, 0x18d9: 0x000a, 0x18da: 0x000a, 0x18db: 0x000a, 0x18dc: 0x000a, 0x18dd: 0x000a, + 0x18de: 0x000a, 0x18df: 0x000a, 0x18e0: 0x000a, 0x18e1: 0x000a, 0x18e2: 0x000a, 0x18e3: 0x000a, + 0x18e4: 0x000a, 0x18e5: 0x000a, 0x18e6: 0x000a, 0x18e7: 0x000a, 0x18e8: 0x000a, 0x18e9: 0x000a, + 0x18ea: 0x000a, 0x18eb: 0x000a, 0x18ec: 0x000a, 0x18ed: 0x000a, 0x18ee: 0x000a, 0x18ef: 0x000a, + 0x18f0: 0x000a, 0x18f1: 0x000a, 0x18f2: 0x000a, 0x18f3: 0x000a, 0x18f4: 0x000a, 0x18f5: 0x000a, + 0x18f6: 0x000a, 0x18f7: 0x000a, 0x18f8: 0x000a, 0x18f9: 0x000a, 0x18fa: 0x000a, 0x18fb: 0x000a, + 0x18fc: 0x000a, 0x18fd: 0x000a, 0x18fe: 0x000a, 0x18ff: 0x000a, + // Block 0x64, offset 0x1900 + 0x1900: 0x000a, 0x1901: 0x000a, 0x1902: 0x000a, 0x1903: 0x000a, 0x1904: 0x000a, 0x1905: 0x000a, + 0x1906: 0x000a, 0x1907: 0x000a, 0x1908: 0x000a, 0x1909: 0x000a, 0x190a: 0x000a, 0x190b: 0x000a, + 0x190c: 0x000a, 0x190d: 0x000a, 0x190e: 0x000a, 0x190f: 0x000a, 0x1910: 0x000a, 0x1911: 0x000a, + 0x1912: 0x000a, 0x1913: 0x000a, 0x1914: 0x000a, 0x1915: 0x000a, 0x1916: 0x000a, 0x1917: 0x000a, + 0x1918: 0x003a, 0x1919: 0x002a, 0x191a: 0x003a, 0x191b: 0x002a, 0x191c: 0x000a, 0x191d: 0x000a, + 0x191e: 0x000a, 0x191f: 0x000a, 0x1920: 0x000a, 0x1921: 0x000a, 0x1922: 0x000a, 0x1923: 0x000a, + 0x1924: 0x000a, 0x1925: 0x000a, 0x1926: 0x000a, 0x1927: 0x000a, 0x1928: 0x000a, 0x1929: 0x000a, + 0x192a: 0x000a, 0x192b: 0x000a, 0x192c: 0x000a, 0x192d: 0x000a, 0x192e: 0x000a, 0x192f: 0x000a, + 0x1930: 0x000a, 0x1931: 0x000a, 0x1932: 0x000a, 0x1933: 0x000a, 0x1934: 0x000a, 0x1935: 0x000a, + 0x1936: 0x000a, 0x1937: 0x000a, 0x1938: 0x000a, 0x1939: 0x000a, 0x193a: 0x000a, 0x193b: 0x000a, + 0x193c: 0x003a, 0x193d: 0x002a, 0x193e: 0x000a, 0x193f: 0x000a, + // Block 0x65, offset 0x1940 + 0x1940: 0x000a, 0x1941: 0x000a, 0x1942: 0x000a, 0x1943: 0x000a, 0x1944: 0x000a, 0x1945: 0x000a, + 0x1946: 0x000a, 0x1947: 0x000a, 0x1948: 0x000a, 0x1949: 0x000a, 0x194a: 0x000a, 0x194b: 0x000a, + 0x194c: 0x000a, 0x194d: 0x000a, 0x194e: 0x000a, 0x194f: 0x000a, 0x1950: 0x000a, 0x1951: 0x000a, + 0x1952: 0x000a, 0x1953: 0x000a, 0x1954: 0x000a, 0x1955: 0x000a, 0x1956: 0x000a, 0x1957: 0x000a, + 0x1958: 0x000a, 0x1959: 0x000a, 0x195a: 0x000a, 0x195b: 0x000a, 0x195c: 0x000a, 0x195d: 0x000a, + 0x195e: 0x000a, 0x195f: 0x000a, 0x1960: 0x000a, 0x1961: 0x000a, 0x1962: 0x000a, 0x1963: 0x000a, + 0x1964: 0x000a, 0x1965: 0x000a, 0x1966: 0x000a, 0x1967: 0x000a, 0x1968: 0x000a, 0x1969: 0x000a, + 0x196a: 0x000a, 0x196b: 0x000a, 0x196c: 0x000a, 0x196d: 0x000a, 0x196e: 0x000a, 0x196f: 0x000a, + 0x1970: 0x000a, 0x1971: 0x000a, 0x1972: 0x000a, 0x1973: 0x000a, + 0x1976: 0x000a, 0x1977: 0x000a, 0x1978: 0x000a, 0x1979: 0x000a, 0x197a: 0x000a, 0x197b: 0x000a, + 0x197c: 0x000a, 0x197d: 0x000a, 0x197e: 0x000a, 0x197f: 0x000a, + // Block 0x66, offset 0x1980 + 0x1980: 0x000a, 0x1981: 0x000a, 0x1982: 0x000a, 0x1983: 0x000a, 0x1984: 0x000a, 0x1985: 0x000a, + 0x1986: 0x000a, 0x1987: 0x000a, 0x1988: 0x000a, 0x1989: 0x000a, 0x198a: 0x000a, 0x198b: 0x000a, + 0x198c: 0x000a, 0x198d: 0x000a, 0x198e: 0x000a, 0x198f: 0x000a, 0x1990: 0x000a, 0x1991: 0x000a, + 0x1992: 0x000a, 0x1993: 0x000a, 0x1994: 0x000a, 0x1995: 0x000a, + 0x1998: 0x000a, 0x1999: 0x000a, 0x199a: 0x000a, 0x199b: 0x000a, 0x199c: 0x000a, 0x199d: 0x000a, + 0x199e: 0x000a, 0x199f: 0x000a, 0x19a0: 0x000a, 0x19a1: 0x000a, 0x19a2: 0x000a, 0x19a3: 0x000a, + 0x19a4: 0x000a, 0x19a5: 0x000a, 0x19a6: 0x000a, 0x19a7: 0x000a, 0x19a8: 0x000a, 0x19a9: 0x000a, + 0x19aa: 0x000a, 0x19ab: 0x000a, 0x19ac: 0x000a, 0x19ad: 0x000a, 0x19ae: 0x000a, 0x19af: 0x000a, + 0x19b0: 0x000a, 0x19b1: 0x000a, 0x19b2: 0x000a, 0x19b3: 0x000a, 0x19b4: 0x000a, 0x19b5: 0x000a, + 0x19b6: 0x000a, 0x19b7: 0x000a, 0x19b8: 0x000a, 0x19b9: 0x000a, + 0x19bd: 0x000a, 0x19be: 0x000a, 0x19bf: 0x000a, + // Block 0x67, offset 0x19c0 + 0x19c0: 0x000a, 0x19c1: 0x000a, 0x19c2: 0x000a, 0x19c3: 0x000a, 0x19c4: 0x000a, 0x19c5: 0x000a, + 0x19c6: 0x000a, 0x19c7: 0x000a, 0x19c8: 0x000a, 0x19ca: 0x000a, 0x19cb: 0x000a, + 0x19cc: 0x000a, 0x19cd: 0x000a, 0x19ce: 0x000a, 0x19cf: 0x000a, 0x19d0: 0x000a, 0x19d1: 0x000a, + 0x19ec: 0x000a, 0x19ed: 0x000a, 0x19ee: 0x000a, 0x19ef: 0x000a, + // Block 0x68, offset 0x1a00 + 0x1a25: 0x000a, 0x1a26: 0x000a, 0x1a27: 0x000a, 0x1a28: 0x000a, 0x1a29: 0x000a, + 0x1a2a: 0x000a, 0x1a2f: 0x000c, + 0x1a30: 0x000c, 0x1a31: 0x000c, + 0x1a39: 0x000a, 0x1a3a: 0x000a, 0x1a3b: 0x000a, + 0x1a3c: 0x000a, 0x1a3d: 0x000a, 0x1a3e: 0x000a, 0x1a3f: 0x000a, + // Block 0x69, offset 0x1a40 + 0x1a7f: 0x000c, + // Block 0x6a, offset 0x1a80 + 0x1aa0: 0x000c, 0x1aa1: 0x000c, 0x1aa2: 0x000c, 0x1aa3: 0x000c, + 0x1aa4: 0x000c, 0x1aa5: 0x000c, 0x1aa6: 0x000c, 0x1aa7: 0x000c, 0x1aa8: 0x000c, 0x1aa9: 0x000c, + 0x1aaa: 0x000c, 0x1aab: 0x000c, 0x1aac: 0x000c, 0x1aad: 0x000c, 0x1aae: 0x000c, 0x1aaf: 0x000c, + 0x1ab0: 0x000c, 0x1ab1: 0x000c, 0x1ab2: 0x000c, 0x1ab3: 0x000c, 0x1ab4: 0x000c, 0x1ab5: 0x000c, + 0x1ab6: 0x000c, 0x1ab7: 0x000c, 0x1ab8: 0x000c, 0x1ab9: 0x000c, 0x1aba: 0x000c, 0x1abb: 0x000c, + 0x1abc: 0x000c, 0x1abd: 0x000c, 0x1abe: 0x000c, 0x1abf: 0x000c, + // Block 0x6b, offset 0x1ac0 + 0x1ac0: 0x000a, 0x1ac1: 0x000a, 0x1ac2: 0x000a, 0x1ac3: 0x000a, 0x1ac4: 0x000a, 0x1ac5: 0x000a, + 0x1ac6: 0x000a, 0x1ac7: 0x000a, 0x1ac8: 0x000a, 0x1ac9: 0x000a, 0x1aca: 0x000a, 0x1acb: 0x000a, + 0x1acc: 0x000a, 0x1acd: 0x000a, 0x1ace: 0x000a, 0x1acf: 0x000a, 0x1ad0: 0x000a, 0x1ad1: 0x000a, + 0x1ad2: 0x000a, 0x1ad3: 0x000a, 0x1ad4: 0x000a, 0x1ad5: 0x000a, 0x1ad6: 0x000a, 0x1ad7: 0x000a, + 0x1ad8: 0x000a, 0x1ad9: 0x000a, 0x1ada: 0x000a, 0x1adb: 0x000a, 0x1adc: 0x000a, 0x1add: 0x000a, + 0x1ade: 0x000a, 0x1adf: 0x000a, 0x1ae0: 0x000a, 0x1ae1: 0x000a, 0x1ae2: 0x003a, 0x1ae3: 0x002a, + 0x1ae4: 0x003a, 0x1ae5: 0x002a, 0x1ae6: 0x003a, 0x1ae7: 0x002a, 0x1ae8: 0x003a, 0x1ae9: 0x002a, + 0x1aea: 0x000a, 0x1aeb: 0x000a, 0x1aec: 0x000a, 0x1aed: 0x000a, 0x1aee: 0x000a, 0x1aef: 0x000a, + 0x1af0: 0x000a, 0x1af1: 0x000a, 0x1af2: 0x000a, 0x1af3: 0x000a, 0x1af4: 0x000a, 0x1af5: 0x000a, + 0x1af6: 0x000a, 0x1af7: 0x000a, 0x1af8: 0x000a, 0x1af9: 0x000a, 0x1afa: 0x000a, 0x1afb: 0x000a, + 0x1afc: 0x000a, 0x1afd: 0x000a, 0x1afe: 0x000a, 0x1aff: 0x000a, + // Block 0x6c, offset 0x1b00 + 0x1b00: 0x000a, 0x1b01: 0x000a, 0x1b02: 0x000a, 0x1b03: 0x000a, 0x1b04: 0x000a, + // Block 0x6d, offset 0x1b40 + 0x1b40: 0x000a, 0x1b41: 0x000a, 0x1b42: 0x000a, 0x1b43: 0x000a, 0x1b44: 0x000a, 0x1b45: 0x000a, + 0x1b46: 0x000a, 0x1b47: 0x000a, 0x1b48: 0x000a, 0x1b49: 0x000a, 0x1b4a: 0x000a, 0x1b4b: 0x000a, + 0x1b4c: 0x000a, 0x1b4d: 0x000a, 0x1b4e: 0x000a, 0x1b4f: 0x000a, 0x1b50: 0x000a, 0x1b51: 0x000a, + 0x1b52: 0x000a, 0x1b53: 0x000a, 0x1b54: 0x000a, 0x1b55: 0x000a, 0x1b56: 0x000a, 0x1b57: 0x000a, + 0x1b58: 0x000a, 0x1b59: 0x000a, 0x1b5b: 0x000a, 0x1b5c: 0x000a, 0x1b5d: 0x000a, + 0x1b5e: 0x000a, 0x1b5f: 0x000a, 0x1b60: 0x000a, 0x1b61: 0x000a, 0x1b62: 0x000a, 0x1b63: 0x000a, + 0x1b64: 0x000a, 0x1b65: 0x000a, 0x1b66: 0x000a, 0x1b67: 0x000a, 0x1b68: 0x000a, 0x1b69: 0x000a, + 0x1b6a: 0x000a, 0x1b6b: 0x000a, 0x1b6c: 0x000a, 0x1b6d: 0x000a, 0x1b6e: 0x000a, 0x1b6f: 0x000a, + 0x1b70: 0x000a, 0x1b71: 0x000a, 0x1b72: 0x000a, 0x1b73: 0x000a, 0x1b74: 0x000a, 0x1b75: 0x000a, + 0x1b76: 0x000a, 0x1b77: 0x000a, 0x1b78: 0x000a, 0x1b79: 0x000a, 0x1b7a: 0x000a, 0x1b7b: 0x000a, + 0x1b7c: 0x000a, 0x1b7d: 0x000a, 0x1b7e: 0x000a, 0x1b7f: 0x000a, + // Block 0x6e, offset 0x1b80 + 0x1b80: 0x000a, 0x1b81: 0x000a, 0x1b82: 0x000a, 0x1b83: 0x000a, 0x1b84: 0x000a, 0x1b85: 0x000a, + 0x1b86: 0x000a, 0x1b87: 0x000a, 0x1b88: 0x000a, 0x1b89: 0x000a, 0x1b8a: 0x000a, 0x1b8b: 0x000a, + 0x1b8c: 0x000a, 0x1b8d: 0x000a, 0x1b8e: 0x000a, 0x1b8f: 0x000a, 0x1b90: 0x000a, 0x1b91: 0x000a, + 0x1b92: 0x000a, 0x1b93: 0x000a, 0x1b94: 0x000a, 0x1b95: 0x000a, 0x1b96: 0x000a, 0x1b97: 0x000a, + 0x1b98: 0x000a, 0x1b99: 0x000a, 0x1b9a: 0x000a, 0x1b9b: 0x000a, 0x1b9c: 0x000a, 0x1b9d: 0x000a, + 0x1b9e: 0x000a, 0x1b9f: 0x000a, 0x1ba0: 0x000a, 0x1ba1: 0x000a, 0x1ba2: 0x000a, 0x1ba3: 0x000a, + 0x1ba4: 0x000a, 0x1ba5: 0x000a, 0x1ba6: 0x000a, 0x1ba7: 0x000a, 0x1ba8: 0x000a, 0x1ba9: 0x000a, + 0x1baa: 0x000a, 0x1bab: 0x000a, 0x1bac: 0x000a, 0x1bad: 0x000a, 0x1bae: 0x000a, 0x1baf: 0x000a, + 0x1bb0: 0x000a, 0x1bb1: 0x000a, 0x1bb2: 0x000a, 0x1bb3: 0x000a, + // Block 0x6f, offset 0x1bc0 + 0x1bc0: 0x000a, 0x1bc1: 0x000a, 0x1bc2: 0x000a, 0x1bc3: 0x000a, 0x1bc4: 0x000a, 0x1bc5: 0x000a, + 0x1bc6: 0x000a, 0x1bc7: 0x000a, 0x1bc8: 0x000a, 0x1bc9: 0x000a, 0x1bca: 0x000a, 0x1bcb: 0x000a, + 0x1bcc: 0x000a, 0x1bcd: 0x000a, 0x1bce: 0x000a, 0x1bcf: 0x000a, 0x1bd0: 0x000a, 0x1bd1: 0x000a, + 0x1bd2: 0x000a, 0x1bd3: 0x000a, 0x1bd4: 0x000a, 0x1bd5: 0x000a, + 0x1bf0: 0x000a, 0x1bf1: 0x000a, 0x1bf2: 0x000a, 0x1bf3: 0x000a, 0x1bf4: 0x000a, 0x1bf5: 0x000a, + 0x1bf6: 0x000a, 0x1bf7: 0x000a, 0x1bf8: 0x000a, 0x1bf9: 0x000a, 0x1bfa: 0x000a, 0x1bfb: 0x000a, + // Block 0x70, offset 0x1c00 + 0x1c00: 0x0009, 0x1c01: 0x000a, 0x1c02: 0x000a, 0x1c03: 0x000a, 0x1c04: 0x000a, + 0x1c08: 0x003a, 0x1c09: 0x002a, 0x1c0a: 0x003a, 0x1c0b: 0x002a, + 0x1c0c: 0x003a, 0x1c0d: 0x002a, 0x1c0e: 0x003a, 0x1c0f: 0x002a, 0x1c10: 0x003a, 0x1c11: 0x002a, + 0x1c12: 0x000a, 0x1c13: 0x000a, 0x1c14: 0x003a, 0x1c15: 0x002a, 0x1c16: 0x003a, 0x1c17: 0x002a, + 0x1c18: 0x003a, 0x1c19: 0x002a, 0x1c1a: 0x003a, 0x1c1b: 0x002a, 0x1c1c: 0x000a, 0x1c1d: 0x000a, + 0x1c1e: 0x000a, 0x1c1f: 0x000a, 0x1c20: 0x000a, + 0x1c2a: 0x000c, 0x1c2b: 0x000c, 0x1c2c: 0x000c, 0x1c2d: 0x000c, + 0x1c30: 0x000a, + 0x1c36: 0x000a, 0x1c37: 0x000a, + 0x1c3d: 0x000a, 0x1c3e: 0x000a, 0x1c3f: 0x000a, + // Block 0x71, offset 0x1c40 + 0x1c59: 0x000c, 0x1c5a: 0x000c, 0x1c5b: 0x000a, 0x1c5c: 0x000a, + 0x1c60: 0x000a, + // Block 0x72, offset 0x1c80 + 0x1cbb: 0x000a, + // Block 0x73, offset 0x1cc0 + 0x1cc0: 0x000a, 0x1cc1: 0x000a, 0x1cc2: 0x000a, 0x1cc3: 0x000a, 0x1cc4: 0x000a, 0x1cc5: 0x000a, + 0x1cc6: 0x000a, 0x1cc7: 0x000a, 0x1cc8: 0x000a, 0x1cc9: 0x000a, 0x1cca: 0x000a, 0x1ccb: 0x000a, + 0x1ccc: 0x000a, 0x1ccd: 0x000a, 0x1cce: 0x000a, 0x1ccf: 0x000a, 0x1cd0: 0x000a, 0x1cd1: 0x000a, + 0x1cd2: 0x000a, 0x1cd3: 0x000a, 0x1cd4: 0x000a, 0x1cd5: 0x000a, 0x1cd6: 0x000a, 0x1cd7: 0x000a, + 0x1cd8: 0x000a, 0x1cd9: 0x000a, 0x1cda: 0x000a, 0x1cdb: 0x000a, 0x1cdc: 0x000a, 0x1cdd: 0x000a, + 0x1cde: 0x000a, 0x1cdf: 0x000a, 0x1ce0: 0x000a, 0x1ce1: 0x000a, 0x1ce2: 0x000a, 0x1ce3: 0x000a, + // Block 0x74, offset 0x1d00 + 0x1d1d: 0x000a, + 0x1d1e: 0x000a, + // Block 0x75, offset 0x1d40 + 0x1d50: 0x000a, 0x1d51: 0x000a, + 0x1d52: 0x000a, 0x1d53: 0x000a, 0x1d54: 0x000a, 0x1d55: 0x000a, 0x1d56: 0x000a, 0x1d57: 0x000a, + 0x1d58: 0x000a, 0x1d59: 0x000a, 0x1d5a: 0x000a, 0x1d5b: 0x000a, 0x1d5c: 0x000a, 0x1d5d: 0x000a, + 0x1d5e: 0x000a, 0x1d5f: 0x000a, + 0x1d7c: 0x000a, 0x1d7d: 0x000a, 0x1d7e: 0x000a, + // Block 0x76, offset 0x1d80 + 0x1db1: 0x000a, 0x1db2: 0x000a, 0x1db3: 0x000a, 0x1db4: 0x000a, 0x1db5: 0x000a, + 0x1db6: 0x000a, 0x1db7: 0x000a, 0x1db8: 0x000a, 0x1db9: 0x000a, 0x1dba: 0x000a, 0x1dbb: 0x000a, + 0x1dbc: 0x000a, 0x1dbd: 0x000a, 0x1dbe: 0x000a, 0x1dbf: 0x000a, + // Block 0x77, offset 0x1dc0 + 0x1dcc: 0x000a, 0x1dcd: 0x000a, 0x1dce: 0x000a, 0x1dcf: 0x000a, + // Block 0x78, offset 0x1e00 + 0x1e37: 0x000a, 0x1e38: 0x000a, 0x1e39: 0x000a, 0x1e3a: 0x000a, + // Block 0x79, offset 0x1e40 + 0x1e5e: 0x000a, 0x1e5f: 0x000a, + 0x1e7f: 0x000a, + // Block 0x7a, offset 0x1e80 + 0x1e90: 0x000a, 0x1e91: 0x000a, + 0x1e92: 0x000a, 0x1e93: 0x000a, 0x1e94: 0x000a, 0x1e95: 0x000a, 0x1e96: 0x000a, 0x1e97: 0x000a, + 0x1e98: 0x000a, 0x1e99: 0x000a, 0x1e9a: 0x000a, 0x1e9b: 0x000a, 0x1e9c: 0x000a, 0x1e9d: 0x000a, + 0x1e9e: 0x000a, 0x1e9f: 0x000a, 0x1ea0: 0x000a, 0x1ea1: 0x000a, 0x1ea2: 0x000a, 0x1ea3: 0x000a, + 0x1ea4: 0x000a, 0x1ea5: 0x000a, 0x1ea6: 0x000a, 0x1ea7: 0x000a, 0x1ea8: 0x000a, 0x1ea9: 0x000a, + 0x1eaa: 0x000a, 0x1eab: 0x000a, 0x1eac: 0x000a, 0x1ead: 0x000a, 0x1eae: 0x000a, 0x1eaf: 0x000a, + 0x1eb0: 0x000a, 0x1eb1: 0x000a, 0x1eb2: 0x000a, 0x1eb3: 0x000a, 0x1eb4: 0x000a, 0x1eb5: 0x000a, + 0x1eb6: 0x000a, 0x1eb7: 0x000a, 0x1eb8: 0x000a, 0x1eb9: 0x000a, 0x1eba: 0x000a, 0x1ebb: 0x000a, + 0x1ebc: 0x000a, 0x1ebd: 0x000a, 0x1ebe: 0x000a, 0x1ebf: 0x000a, + // Block 0x7b, offset 0x1ec0 + 0x1ec0: 0x000a, 0x1ec1: 0x000a, 0x1ec2: 0x000a, 0x1ec3: 0x000a, 0x1ec4: 0x000a, 0x1ec5: 0x000a, + 0x1ec6: 0x000a, + // Block 0x7c, offset 0x1f00 + 0x1f0d: 0x000a, 0x1f0e: 0x000a, 0x1f0f: 0x000a, + // Block 0x7d, offset 0x1f40 + 0x1f6f: 0x000c, + 0x1f70: 0x000c, 0x1f71: 0x000c, 0x1f72: 0x000c, 0x1f73: 0x000a, 0x1f74: 0x000c, 0x1f75: 0x000c, + 0x1f76: 0x000c, 0x1f77: 0x000c, 0x1f78: 0x000c, 0x1f79: 0x000c, 0x1f7a: 0x000c, 0x1f7b: 0x000c, + 0x1f7c: 0x000c, 0x1f7d: 0x000c, 0x1f7e: 0x000a, 0x1f7f: 0x000a, + // Block 0x7e, offset 0x1f80 + 0x1f9e: 0x000c, 0x1f9f: 0x000c, + // Block 0x7f, offset 0x1fc0 + 0x1ff0: 0x000c, 0x1ff1: 0x000c, + // Block 0x80, offset 0x2000 + 0x2000: 0x000a, 0x2001: 0x000a, 0x2002: 0x000a, 0x2003: 0x000a, 0x2004: 0x000a, 0x2005: 0x000a, + 0x2006: 0x000a, 0x2007: 0x000a, 0x2008: 0x000a, 0x2009: 0x000a, 0x200a: 0x000a, 0x200b: 0x000a, + 0x200c: 0x000a, 0x200d: 0x000a, 0x200e: 0x000a, 0x200f: 0x000a, 0x2010: 0x000a, 0x2011: 0x000a, + 0x2012: 0x000a, 0x2013: 0x000a, 0x2014: 0x000a, 0x2015: 0x000a, 0x2016: 0x000a, 0x2017: 0x000a, + 0x2018: 0x000a, 0x2019: 0x000a, 0x201a: 0x000a, 0x201b: 0x000a, 0x201c: 0x000a, 0x201d: 0x000a, + 0x201e: 0x000a, 0x201f: 0x000a, 0x2020: 0x000a, 0x2021: 0x000a, + // Block 0x81, offset 0x2040 + 0x2048: 0x000a, + // Block 0x82, offset 0x2080 + 0x2082: 0x000c, + 0x2086: 0x000c, 0x208b: 0x000c, + 0x20a5: 0x000c, 0x20a6: 0x000c, 0x20a8: 0x000a, 0x20a9: 0x000a, + 0x20aa: 0x000a, 0x20ab: 0x000a, + 0x20b8: 0x0004, 0x20b9: 0x0004, + // Block 0x83, offset 0x20c0 + 0x20f4: 0x000a, 0x20f5: 0x000a, + 0x20f6: 0x000a, 0x20f7: 0x000a, + // Block 0x84, offset 0x2100 + 0x2104: 0x000c, 0x2105: 0x000c, + 0x2120: 0x000c, 0x2121: 0x000c, 0x2122: 0x000c, 0x2123: 0x000c, + 0x2124: 0x000c, 0x2125: 0x000c, 0x2126: 0x000c, 0x2127: 0x000c, 0x2128: 0x000c, 0x2129: 0x000c, + 0x212a: 0x000c, 0x212b: 0x000c, 0x212c: 0x000c, 0x212d: 0x000c, 0x212e: 0x000c, 0x212f: 0x000c, + 0x2130: 0x000c, 0x2131: 0x000c, + // Block 0x85, offset 0x2140 + 0x2166: 0x000c, 0x2167: 0x000c, 0x2168: 0x000c, 0x2169: 0x000c, + 0x216a: 0x000c, 0x216b: 0x000c, 0x216c: 0x000c, 0x216d: 0x000c, + // Block 0x86, offset 0x2180 + 0x2187: 0x000c, 0x2188: 0x000c, 0x2189: 0x000c, 0x218a: 0x000c, 0x218b: 0x000c, + 0x218c: 0x000c, 0x218d: 0x000c, 0x218e: 0x000c, 0x218f: 0x000c, 0x2190: 0x000c, 0x2191: 0x000c, + // Block 0x87, offset 0x21c0 + 0x21c0: 0x000c, 0x21c1: 0x000c, 0x21c2: 0x000c, + 0x21f3: 0x000c, + 0x21f6: 0x000c, 0x21f7: 0x000c, 0x21f8: 0x000c, 0x21f9: 0x000c, + 0x21fc: 0x000c, + // Block 0x88, offset 0x2200 + 0x2225: 0x000c, + // Block 0x89, offset 0x2240 + 0x2269: 0x000c, + 0x226a: 0x000c, 0x226b: 0x000c, 0x226c: 0x000c, 0x226d: 0x000c, 0x226e: 0x000c, + 0x2271: 0x000c, 0x2272: 0x000c, 0x2275: 0x000c, + 0x2276: 0x000c, + // Block 0x8a, offset 0x2280 + 0x2283: 0x000c, + 0x228c: 0x000c, + 0x22bc: 0x000c, + // Block 0x8b, offset 0x22c0 + 0x22f0: 0x000c, 0x22f2: 0x000c, 0x22f3: 0x000c, 0x22f4: 0x000c, + 0x22f7: 0x000c, 0x22f8: 0x000c, + 0x22fe: 0x000c, 0x22ff: 0x000c, + // Block 0x8c, offset 0x2300 + 0x2301: 0x000c, + 0x232c: 0x000c, 0x232d: 0x000c, + 0x2336: 0x000c, + // Block 0x8d, offset 0x2340 + 0x2365: 0x000c, 0x2368: 0x000c, + 0x236d: 0x000c, + // Block 0x8e, offset 0x2380 + 0x239d: 0x0001, + 0x239e: 0x000c, 0x239f: 0x0001, 0x23a0: 0x0001, 0x23a1: 0x0001, 0x23a2: 0x0001, 0x23a3: 0x0001, + 0x23a4: 0x0001, 0x23a5: 0x0001, 0x23a6: 0x0001, 0x23a7: 0x0001, 0x23a8: 0x0001, 0x23a9: 0x0003, + 0x23aa: 0x0001, 0x23ab: 0x0001, 0x23ac: 0x0001, 0x23ad: 0x0001, 0x23ae: 0x0001, 0x23af: 0x0001, + 0x23b0: 0x0001, 0x23b1: 0x0001, 0x23b2: 0x0001, 0x23b3: 0x0001, 0x23b4: 0x0001, 0x23b5: 0x0001, + 0x23b6: 0x0001, 0x23b7: 0x0001, 0x23b8: 0x0001, 0x23b9: 0x0001, 0x23ba: 0x0001, 0x23bb: 0x0001, + 0x23bc: 0x0001, 0x23bd: 0x0001, 0x23be: 0x0001, 0x23bf: 0x0001, + // Block 0x8f, offset 0x23c0 + 0x23c0: 0x0001, 0x23c1: 0x0001, 0x23c2: 0x0001, 0x23c3: 0x0001, 0x23c4: 0x0001, 0x23c5: 0x0001, + 0x23c6: 0x0001, 0x23c7: 0x0001, 0x23c8: 0x0001, 0x23c9: 0x0001, 0x23ca: 0x0001, 0x23cb: 0x0001, + 0x23cc: 0x0001, 0x23cd: 0x0001, 0x23ce: 0x0001, 0x23cf: 0x0001, 0x23d0: 0x000d, 0x23d1: 0x000d, + 0x23d2: 0x000d, 0x23d3: 0x000d, 0x23d4: 0x000d, 0x23d5: 0x000d, 0x23d6: 0x000d, 0x23d7: 0x000d, + 0x23d8: 0x000d, 0x23d9: 0x000d, 0x23da: 0x000d, 0x23db: 0x000d, 0x23dc: 0x000d, 0x23dd: 0x000d, + 0x23de: 0x000d, 0x23df: 0x000d, 0x23e0: 0x000d, 0x23e1: 0x000d, 0x23e2: 0x000d, 0x23e3: 0x000d, + 0x23e4: 0x000d, 0x23e5: 0x000d, 0x23e6: 0x000d, 0x23e7: 0x000d, 0x23e8: 0x000d, 0x23e9: 0x000d, + 0x23ea: 0x000d, 0x23eb: 0x000d, 0x23ec: 0x000d, 0x23ed: 0x000d, 0x23ee: 0x000d, 0x23ef: 0x000d, + 0x23f0: 0x000d, 0x23f1: 0x000d, 0x23f2: 0x000d, 0x23f3: 0x000d, 0x23f4: 0x000d, 0x23f5: 0x000d, + 0x23f6: 0x000d, 0x23f7: 0x000d, 0x23f8: 0x000d, 0x23f9: 0x000d, 0x23fa: 0x000d, 0x23fb: 0x000d, + 0x23fc: 0x000d, 0x23fd: 0x000d, 0x23fe: 0x000d, 0x23ff: 0x000d, + // Block 0x90, offset 0x2400 + 0x2400: 0x000d, 0x2401: 0x000d, 0x2402: 0x000d, 0x2403: 0x000d, 0x2404: 0x000d, 0x2405: 0x000d, + 0x2406: 0x000d, 0x2407: 0x000d, 0x2408: 0x000d, 0x2409: 0x000d, 0x240a: 0x000d, 0x240b: 0x000d, + 0x240c: 0x000d, 0x240d: 0x000d, 0x240e: 0x000d, 0x240f: 0x000d, 0x2410: 0x000d, 0x2411: 0x000d, + 0x2412: 0x000d, 0x2413: 0x000d, 0x2414: 0x000d, 0x2415: 0x000d, 0x2416: 0x000d, 0x2417: 0x000d, + 0x2418: 0x000d, 0x2419: 0x000d, 0x241a: 0x000d, 0x241b: 0x000d, 0x241c: 0x000d, 0x241d: 0x000d, + 0x241e: 0x000d, 0x241f: 0x000d, 0x2420: 0x000d, 0x2421: 0x000d, 0x2422: 0x000d, 0x2423: 0x000d, + 0x2424: 0x000d, 0x2425: 0x000d, 0x2426: 0x000d, 0x2427: 0x000d, 0x2428: 0x000d, 0x2429: 0x000d, + 0x242a: 0x000d, 0x242b: 0x000d, 0x242c: 0x000d, 0x242d: 0x000d, 0x242e: 0x000d, 0x242f: 0x000d, + 0x2430: 0x000d, 0x2431: 0x000d, 0x2432: 0x000d, 0x2433: 0x000d, 0x2434: 0x000d, 0x2435: 0x000d, + 0x2436: 0x000d, 0x2437: 0x000d, 0x2438: 0x000d, 0x2439: 0x000d, 0x243a: 0x000d, 0x243b: 0x000d, + 0x243c: 0x000d, 0x243d: 0x000d, 0x243e: 0x000a, 0x243f: 0x000a, + // Block 0x91, offset 0x2440 + 0x2440: 0x000d, 0x2441: 0x000d, 0x2442: 0x000d, 0x2443: 0x000d, 0x2444: 0x000d, 0x2445: 0x000d, + 0x2446: 0x000d, 0x2447: 0x000d, 0x2448: 0x000d, 0x2449: 0x000d, 0x244a: 0x000d, 0x244b: 0x000d, + 0x244c: 0x000d, 0x244d: 0x000d, 0x244e: 0x000d, 0x244f: 0x000d, 0x2450: 0x000b, 0x2451: 0x000b, + 0x2452: 0x000b, 0x2453: 0x000b, 0x2454: 0x000b, 0x2455: 0x000b, 0x2456: 0x000b, 0x2457: 0x000b, + 0x2458: 0x000b, 0x2459: 0x000b, 0x245a: 0x000b, 0x245b: 0x000b, 0x245c: 0x000b, 0x245d: 0x000b, + 0x245e: 0x000b, 0x245f: 0x000b, 0x2460: 0x000b, 0x2461: 0x000b, 0x2462: 0x000b, 0x2463: 0x000b, + 0x2464: 0x000b, 0x2465: 0x000b, 0x2466: 0x000b, 0x2467: 0x000b, 0x2468: 0x000b, 0x2469: 0x000b, + 0x246a: 0x000b, 0x246b: 0x000b, 0x246c: 0x000b, 0x246d: 0x000b, 0x246e: 0x000b, 0x246f: 0x000b, + 0x2470: 0x000d, 0x2471: 0x000d, 0x2472: 0x000d, 0x2473: 0x000d, 0x2474: 0x000d, 0x2475: 0x000d, + 0x2476: 0x000d, 0x2477: 0x000d, 0x2478: 0x000d, 0x2479: 0x000d, 0x247a: 0x000d, 0x247b: 0x000d, + 0x247c: 0x000d, 0x247d: 0x000a, 0x247e: 0x000d, 0x247f: 0x000d, + // Block 0x92, offset 0x2480 + 0x2480: 0x000c, 0x2481: 0x000c, 0x2482: 0x000c, 0x2483: 0x000c, 0x2484: 0x000c, 0x2485: 0x000c, + 0x2486: 0x000c, 0x2487: 0x000c, 0x2488: 0x000c, 0x2489: 0x000c, 0x248a: 0x000c, 0x248b: 0x000c, + 0x248c: 0x000c, 0x248d: 0x000c, 0x248e: 0x000c, 0x248f: 0x000c, 0x2490: 0x000a, 0x2491: 0x000a, + 0x2492: 0x000a, 0x2493: 0x000a, 0x2494: 0x000a, 0x2495: 0x000a, 0x2496: 0x000a, 0x2497: 0x000a, + 0x2498: 0x000a, 0x2499: 0x000a, + 0x24a0: 0x000c, 0x24a1: 0x000c, 0x24a2: 0x000c, 0x24a3: 0x000c, + 0x24a4: 0x000c, 0x24a5: 0x000c, 0x24a6: 0x000c, 0x24a7: 0x000c, 0x24a8: 0x000c, 0x24a9: 0x000c, + 0x24aa: 0x000c, 0x24ab: 0x000c, 0x24ac: 0x000c, 0x24ad: 0x000c, 0x24ae: 0x000c, 0x24af: 0x000c, + 0x24b0: 0x000a, 0x24b1: 0x000a, 0x24b2: 0x000a, 0x24b3: 0x000a, 0x24b4: 0x000a, 0x24b5: 0x000a, + 0x24b6: 0x000a, 0x24b7: 0x000a, 0x24b8: 0x000a, 0x24b9: 0x000a, 0x24ba: 0x000a, 0x24bb: 0x000a, + 0x24bc: 0x000a, 0x24bd: 0x000a, 0x24be: 0x000a, 0x24bf: 0x000a, + // Block 0x93, offset 0x24c0 + 0x24c0: 0x000a, 0x24c1: 0x000a, 0x24c2: 0x000a, 0x24c3: 0x000a, 0x24c4: 0x000a, 0x24c5: 0x000a, + 0x24c6: 0x000a, 0x24c7: 0x000a, 0x24c8: 0x000a, 0x24c9: 0x000a, 0x24ca: 0x000a, 0x24cb: 0x000a, + 0x24cc: 0x000a, 0x24cd: 0x000a, 0x24ce: 0x000a, 0x24cf: 0x000a, 0x24d0: 0x0006, 0x24d1: 0x000a, + 0x24d2: 0x0006, 0x24d4: 0x000a, 0x24d5: 0x0006, 0x24d6: 0x000a, 0x24d7: 0x000a, + 0x24d8: 0x000a, 0x24d9: 0x009a, 0x24da: 0x008a, 0x24db: 0x007a, 0x24dc: 0x006a, 0x24dd: 0x009a, + 0x24de: 0x008a, 0x24df: 0x0004, 0x24e0: 0x000a, 0x24e1: 0x000a, 0x24e2: 0x0003, 0x24e3: 0x0003, + 0x24e4: 0x000a, 0x24e5: 0x000a, 0x24e6: 0x000a, 0x24e8: 0x000a, 0x24e9: 0x0004, + 0x24ea: 0x0004, 0x24eb: 0x000a, + 0x24f0: 0x000d, 0x24f1: 0x000d, 0x24f2: 0x000d, 0x24f3: 0x000d, 0x24f4: 0x000d, 0x24f5: 0x000d, + 0x24f6: 0x000d, 0x24f7: 0x000d, 0x24f8: 0x000d, 0x24f9: 0x000d, 0x24fa: 0x000d, 0x24fb: 0x000d, + 0x24fc: 0x000d, 0x24fd: 0x000d, 0x24fe: 0x000d, 0x24ff: 0x000d, + // Block 0x94, offset 0x2500 + 0x2500: 0x000d, 0x2501: 0x000d, 0x2502: 0x000d, 0x2503: 0x000d, 0x2504: 0x000d, 0x2505: 0x000d, + 0x2506: 0x000d, 0x2507: 0x000d, 0x2508: 0x000d, 0x2509: 0x000d, 0x250a: 0x000d, 0x250b: 0x000d, + 0x250c: 0x000d, 0x250d: 0x000d, 0x250e: 0x000d, 0x250f: 0x000d, 0x2510: 0x000d, 0x2511: 0x000d, + 0x2512: 0x000d, 0x2513: 0x000d, 0x2514: 0x000d, 0x2515: 0x000d, 0x2516: 0x000d, 0x2517: 0x000d, + 0x2518: 0x000d, 0x2519: 0x000d, 0x251a: 0x000d, 0x251b: 0x000d, 0x251c: 0x000d, 0x251d: 0x000d, + 0x251e: 0x000d, 0x251f: 0x000d, 0x2520: 0x000d, 0x2521: 0x000d, 0x2522: 0x000d, 0x2523: 0x000d, + 0x2524: 0x000d, 0x2525: 0x000d, 0x2526: 0x000d, 0x2527: 0x000d, 0x2528: 0x000d, 0x2529: 0x000d, + 0x252a: 0x000d, 0x252b: 0x000d, 0x252c: 0x000d, 0x252d: 0x000d, 0x252e: 0x000d, 0x252f: 0x000d, + 0x2530: 0x000d, 0x2531: 0x000d, 0x2532: 0x000d, 0x2533: 0x000d, 0x2534: 0x000d, 0x2535: 0x000d, + 0x2536: 0x000d, 0x2537: 0x000d, 0x2538: 0x000d, 0x2539: 0x000d, 0x253a: 0x000d, 0x253b: 0x000d, + 0x253c: 0x000d, 0x253d: 0x000d, 0x253e: 0x000d, 0x253f: 0x000b, + // Block 0x95, offset 0x2540 + 0x2541: 0x000a, 0x2542: 0x000a, 0x2543: 0x0004, 0x2544: 0x0004, 0x2545: 0x0004, + 0x2546: 0x000a, 0x2547: 0x000a, 0x2548: 0x003a, 0x2549: 0x002a, 0x254a: 0x000a, 0x254b: 0x0003, + 0x254c: 0x0006, 0x254d: 0x0003, 0x254e: 0x0006, 0x254f: 0x0006, 0x2550: 0x0002, 0x2551: 0x0002, + 0x2552: 0x0002, 0x2553: 0x0002, 0x2554: 0x0002, 0x2555: 0x0002, 0x2556: 0x0002, 0x2557: 0x0002, + 0x2558: 0x0002, 0x2559: 0x0002, 0x255a: 0x0006, 0x255b: 0x000a, 0x255c: 0x000a, 0x255d: 0x000a, + 0x255e: 0x000a, 0x255f: 0x000a, 0x2560: 0x000a, + 0x257b: 0x005a, + 0x257c: 0x000a, 0x257d: 0x004a, 0x257e: 0x000a, 0x257f: 0x000a, + // Block 0x96, offset 0x2580 + 0x2580: 0x000a, + 0x259b: 0x005a, 0x259c: 0x000a, 0x259d: 0x004a, + 0x259e: 0x000a, 0x259f: 0x00fa, 0x25a0: 0x00ea, 0x25a1: 0x000a, 0x25a2: 0x003a, 0x25a3: 0x002a, + 0x25a4: 0x000a, 0x25a5: 0x000a, + // Block 0x97, offset 0x25c0 + 0x25e0: 0x0004, 0x25e1: 0x0004, 0x25e2: 0x000a, 0x25e3: 0x000a, + 0x25e4: 0x000a, 0x25e5: 0x0004, 0x25e6: 0x0004, 0x25e8: 0x000a, 0x25e9: 0x000a, + 0x25ea: 0x000a, 0x25eb: 0x000a, 0x25ec: 0x000a, 0x25ed: 0x000a, 0x25ee: 0x000a, + 0x25f0: 0x000b, 0x25f1: 0x000b, 0x25f2: 0x000b, 0x25f3: 0x000b, 0x25f4: 0x000b, 0x25f5: 0x000b, + 0x25f6: 0x000b, 0x25f7: 0x000b, 0x25f8: 0x000b, 0x25f9: 0x000a, 0x25fa: 0x000a, 0x25fb: 0x000a, + 0x25fc: 0x000a, 0x25fd: 0x000a, 0x25fe: 0x000b, 0x25ff: 0x000b, + // Block 0x98, offset 0x2600 + 0x2601: 0x000a, + // Block 0x99, offset 0x2640 + 0x2640: 0x000a, 0x2641: 0x000a, 0x2642: 0x000a, 0x2643: 0x000a, 0x2644: 0x000a, 0x2645: 0x000a, + 0x2646: 0x000a, 0x2647: 0x000a, 0x2648: 0x000a, 0x2649: 0x000a, 0x264a: 0x000a, 0x264b: 0x000a, + 0x264c: 0x000a, 0x2650: 0x000a, 0x2651: 0x000a, + 0x2652: 0x000a, 0x2653: 0x000a, 0x2654: 0x000a, 0x2655: 0x000a, 0x2656: 0x000a, 0x2657: 0x000a, + 0x2658: 0x000a, 0x2659: 0x000a, 0x265a: 0x000a, 0x265b: 0x000a, + 0x2660: 0x000a, + // Block 0x9a, offset 0x2680 + 0x26bd: 0x000c, + // Block 0x9b, offset 0x26c0 + 0x26e0: 0x000c, 0x26e1: 0x0002, 0x26e2: 0x0002, 0x26e3: 0x0002, + 0x26e4: 0x0002, 0x26e5: 0x0002, 0x26e6: 0x0002, 0x26e7: 0x0002, 0x26e8: 0x0002, 0x26e9: 0x0002, + 0x26ea: 0x0002, 0x26eb: 0x0002, 0x26ec: 0x0002, 0x26ed: 0x0002, 0x26ee: 0x0002, 0x26ef: 0x0002, + 0x26f0: 0x0002, 0x26f1: 0x0002, 0x26f2: 0x0002, 0x26f3: 0x0002, 0x26f4: 0x0002, 0x26f5: 0x0002, + 0x26f6: 0x0002, 0x26f7: 0x0002, 0x26f8: 0x0002, 0x26f9: 0x0002, 0x26fa: 0x0002, 0x26fb: 0x0002, + // Block 0x9c, offset 0x2700 + 0x2736: 0x000c, 0x2737: 0x000c, 0x2738: 0x000c, 0x2739: 0x000c, 0x273a: 0x000c, + // Block 0x9d, offset 0x2740 + 0x2740: 0x0001, 0x2741: 0x0001, 0x2742: 0x0001, 0x2743: 0x0001, 0x2744: 0x0001, 0x2745: 0x0001, + 0x2746: 0x0001, 0x2747: 0x0001, 0x2748: 0x0001, 0x2749: 0x0001, 0x274a: 0x0001, 0x274b: 0x0001, + 0x274c: 0x0001, 0x274d: 0x0001, 0x274e: 0x0001, 0x274f: 0x0001, 0x2750: 0x0001, 0x2751: 0x0001, + 0x2752: 0x0001, 0x2753: 0x0001, 0x2754: 0x0001, 0x2755: 0x0001, 0x2756: 0x0001, 0x2757: 0x0001, + 0x2758: 0x0001, 0x2759: 0x0001, 0x275a: 0x0001, 0x275b: 0x0001, 0x275c: 0x0001, 0x275d: 0x0001, + 0x275e: 0x0001, 0x275f: 0x0001, 0x2760: 0x0001, 0x2761: 0x0001, 0x2762: 0x0001, 0x2763: 0x0001, + 0x2764: 0x0001, 0x2765: 0x0001, 0x2766: 0x0001, 0x2767: 0x0001, 0x2768: 0x0001, 0x2769: 0x0001, + 0x276a: 0x0001, 0x276b: 0x0001, 0x276c: 0x0001, 0x276d: 0x0001, 0x276e: 0x0001, 0x276f: 0x0001, + 0x2770: 0x0001, 0x2771: 0x0001, 0x2772: 0x0001, 0x2773: 0x0001, 0x2774: 0x0001, 0x2775: 0x0001, + 0x2776: 0x0001, 0x2777: 0x0001, 0x2778: 0x0001, 0x2779: 0x0001, 0x277a: 0x0001, 0x277b: 0x0001, + 0x277c: 0x0001, 0x277d: 0x0001, 0x277e: 0x0001, 0x277f: 0x0001, + // Block 0x9e, offset 0x2780 + 0x2780: 0x0001, 0x2781: 0x0001, 0x2782: 0x0001, 0x2783: 0x0001, 0x2784: 0x0001, 0x2785: 0x0001, + 0x2786: 0x0001, 0x2787: 0x0001, 0x2788: 0x0001, 0x2789: 0x0001, 0x278a: 0x0001, 0x278b: 0x0001, + 0x278c: 0x0001, 0x278d: 0x0001, 0x278e: 0x0001, 0x278f: 0x0001, 0x2790: 0x0001, 0x2791: 0x0001, + 0x2792: 0x0001, 0x2793: 0x0001, 0x2794: 0x0001, 0x2795: 0x0001, 0x2796: 0x0001, 0x2797: 0x0001, + 0x2798: 0x0001, 0x2799: 0x0001, 0x279a: 0x0001, 0x279b: 0x0001, 0x279c: 0x0001, 0x279d: 0x0001, + 0x279e: 0x0001, 0x279f: 0x000a, 0x27a0: 0x0001, 0x27a1: 0x0001, 0x27a2: 0x0001, 0x27a3: 0x0001, + 0x27a4: 0x0001, 0x27a5: 0x0001, 0x27a6: 0x0001, 0x27a7: 0x0001, 0x27a8: 0x0001, 0x27a9: 0x0001, + 0x27aa: 0x0001, 0x27ab: 0x0001, 0x27ac: 0x0001, 0x27ad: 0x0001, 0x27ae: 0x0001, 0x27af: 0x0001, + 0x27b0: 0x0001, 0x27b1: 0x0001, 0x27b2: 0x0001, 0x27b3: 0x0001, 0x27b4: 0x0001, 0x27b5: 0x0001, + 0x27b6: 0x0001, 0x27b7: 0x0001, 0x27b8: 0x0001, 0x27b9: 0x0001, 0x27ba: 0x0001, 0x27bb: 0x0001, + 0x27bc: 0x0001, 0x27bd: 0x0001, 0x27be: 0x0001, 0x27bf: 0x0001, + // Block 0x9f, offset 0x27c0 + 0x27c0: 0x0001, 0x27c1: 0x000c, 0x27c2: 0x000c, 0x27c3: 0x000c, 0x27c4: 0x0001, 0x27c5: 0x000c, + 0x27c6: 0x000c, 0x27c7: 0x0001, 0x27c8: 0x0001, 0x27c9: 0x0001, 0x27ca: 0x0001, 0x27cb: 0x0001, + 0x27cc: 0x000c, 0x27cd: 0x000c, 0x27ce: 0x000c, 0x27cf: 0x000c, 0x27d0: 0x0001, 0x27d1: 0x0001, + 0x27d2: 0x0001, 0x27d3: 0x0001, 0x27d4: 0x0001, 0x27d5: 0x0001, 0x27d6: 0x0001, 0x27d7: 0x0001, + 0x27d8: 0x0001, 0x27d9: 0x0001, 0x27da: 0x0001, 0x27db: 0x0001, 0x27dc: 0x0001, 0x27dd: 0x0001, + 0x27de: 0x0001, 0x27df: 0x0001, 0x27e0: 0x0001, 0x27e1: 0x0001, 0x27e2: 0x0001, 0x27e3: 0x0001, + 0x27e4: 0x0001, 0x27e5: 0x0001, 0x27e6: 0x0001, 0x27e7: 0x0001, 0x27e8: 0x0001, 0x27e9: 0x0001, + 0x27ea: 0x0001, 0x27eb: 0x0001, 0x27ec: 0x0001, 0x27ed: 0x0001, 0x27ee: 0x0001, 0x27ef: 0x0001, + 0x27f0: 0x0001, 0x27f1: 0x0001, 0x27f2: 0x0001, 0x27f3: 0x0001, 0x27f4: 0x0001, 0x27f5: 0x0001, + 0x27f6: 0x0001, 0x27f7: 0x0001, 0x27f8: 0x000c, 0x27f9: 0x000c, 0x27fa: 0x000c, 0x27fb: 0x0001, + 0x27fc: 0x0001, 0x27fd: 0x0001, 0x27fe: 0x0001, 0x27ff: 0x000c, + // Block 0xa0, offset 0x2800 + 0x2800: 0x0001, 0x2801: 0x0001, 0x2802: 0x0001, 0x2803: 0x0001, 0x2804: 0x0001, 0x2805: 0x0001, + 0x2806: 0x0001, 0x2807: 0x0001, 0x2808: 0x0001, 0x2809: 0x0001, 0x280a: 0x0001, 0x280b: 0x0001, + 0x280c: 0x0001, 0x280d: 0x0001, 0x280e: 0x0001, 0x280f: 0x0001, 0x2810: 0x0001, 0x2811: 0x0001, + 0x2812: 0x0001, 0x2813: 0x0001, 0x2814: 0x0001, 0x2815: 0x0001, 0x2816: 0x0001, 0x2817: 0x0001, + 0x2818: 0x0001, 0x2819: 0x0001, 0x281a: 0x0001, 0x281b: 0x0001, 0x281c: 0x0001, 0x281d: 0x0001, + 0x281e: 0x0001, 0x281f: 0x0001, 0x2820: 0x0001, 0x2821: 0x0001, 0x2822: 0x0001, 0x2823: 0x0001, + 0x2824: 0x0001, 0x2825: 0x000c, 0x2826: 0x000c, 0x2827: 0x0001, 0x2828: 0x0001, 0x2829: 0x0001, + 0x282a: 0x0001, 0x282b: 0x0001, 0x282c: 0x0001, 0x282d: 0x0001, 0x282e: 0x0001, 0x282f: 0x0001, + 0x2830: 0x0001, 0x2831: 0x0001, 0x2832: 0x0001, 0x2833: 0x0001, 0x2834: 0x0001, 0x2835: 0x0001, + 0x2836: 0x0001, 0x2837: 0x0001, 0x2838: 0x0001, 0x2839: 0x0001, 0x283a: 0x0001, 0x283b: 0x0001, + 0x283c: 0x0001, 0x283d: 0x0001, 0x283e: 0x0001, 0x283f: 0x0001, + // Block 0xa1, offset 0x2840 + 0x2840: 0x0001, 0x2841: 0x0001, 0x2842: 0x0001, 0x2843: 0x0001, 0x2844: 0x0001, 0x2845: 0x0001, + 0x2846: 0x0001, 0x2847: 0x0001, 0x2848: 0x0001, 0x2849: 0x0001, 0x284a: 0x0001, 0x284b: 0x0001, + 0x284c: 0x0001, 0x284d: 0x0001, 0x284e: 0x0001, 0x284f: 0x0001, 0x2850: 0x0001, 0x2851: 0x0001, + 0x2852: 0x0001, 0x2853: 0x0001, 0x2854: 0x0001, 0x2855: 0x0001, 0x2856: 0x0001, 0x2857: 0x0001, + 0x2858: 0x0001, 0x2859: 0x0001, 0x285a: 0x0001, 0x285b: 0x0001, 0x285c: 0x0001, 0x285d: 0x0001, + 0x285e: 0x0001, 0x285f: 0x0001, 0x2860: 0x0001, 0x2861: 0x0001, 0x2862: 0x0001, 0x2863: 0x0001, + 0x2864: 0x0001, 0x2865: 0x0001, 0x2866: 0x0001, 0x2867: 0x0001, 0x2868: 0x0001, 0x2869: 0x0001, + 0x286a: 0x0001, 0x286b: 0x0001, 0x286c: 0x0001, 0x286d: 0x0001, 0x286e: 0x0001, 0x286f: 0x0001, + 0x2870: 0x0001, 0x2871: 0x0001, 0x2872: 0x0001, 0x2873: 0x0001, 0x2874: 0x0001, 0x2875: 0x0001, + 0x2876: 0x0001, 0x2877: 0x0001, 0x2878: 0x0001, 0x2879: 0x000a, 0x287a: 0x000a, 0x287b: 0x000a, + 0x287c: 0x000a, 0x287d: 0x000a, 0x287e: 0x000a, 0x287f: 0x000a, + // Block 0xa2, offset 0x2880 + 0x2880: 0x0001, 0x2881: 0x0001, 0x2882: 0x0001, 0x2883: 0x0001, 0x2884: 0x0001, 0x2885: 0x0001, + 0x2886: 0x0001, 0x2887: 0x0001, 0x2888: 0x0001, 0x2889: 0x0001, 0x288a: 0x0001, 0x288b: 0x0001, + 0x288c: 0x0001, 0x288d: 0x0001, 0x288e: 0x0001, 0x288f: 0x0001, 0x2890: 0x0001, 0x2891: 0x0001, + 0x2892: 0x0001, 0x2893: 0x0001, 0x2894: 0x0001, 0x2895: 0x0001, 0x2896: 0x0001, 0x2897: 0x0001, + 0x2898: 0x0001, 0x2899: 0x0001, 0x289a: 0x0001, 0x289b: 0x0001, 0x289c: 0x0001, 0x289d: 0x0001, + 0x289e: 0x0001, 0x289f: 0x0001, 0x28a0: 0x0005, 0x28a1: 0x0005, 0x28a2: 0x0005, 0x28a3: 0x0005, + 0x28a4: 0x0005, 0x28a5: 0x0005, 0x28a6: 0x0005, 0x28a7: 0x0005, 0x28a8: 0x0005, 0x28a9: 0x0005, + 0x28aa: 0x0005, 0x28ab: 0x0005, 0x28ac: 0x0005, 0x28ad: 0x0005, 0x28ae: 0x0005, 0x28af: 0x0005, + 0x28b0: 0x0005, 0x28b1: 0x0005, 0x28b2: 0x0005, 0x28b3: 0x0005, 0x28b4: 0x0005, 0x28b5: 0x0005, + 0x28b6: 0x0005, 0x28b7: 0x0005, 0x28b8: 0x0005, 0x28b9: 0x0005, 0x28ba: 0x0005, 0x28bb: 0x0005, + 0x28bc: 0x0005, 0x28bd: 0x0005, 0x28be: 0x0005, 0x28bf: 0x0001, + // Block 0xa3, offset 0x28c0 + 0x28c1: 0x000c, + 0x28f8: 0x000c, 0x28f9: 0x000c, 0x28fa: 0x000c, 0x28fb: 0x000c, + 0x28fc: 0x000c, 0x28fd: 0x000c, 0x28fe: 0x000c, 0x28ff: 0x000c, + // Block 0xa4, offset 0x2900 + 0x2900: 0x000c, 0x2901: 0x000c, 0x2902: 0x000c, 0x2903: 0x000c, 0x2904: 0x000c, 0x2905: 0x000c, + 0x2906: 0x000c, + 0x2912: 0x000a, 0x2913: 0x000a, 0x2914: 0x000a, 0x2915: 0x000a, 0x2916: 0x000a, 0x2917: 0x000a, + 0x2918: 0x000a, 0x2919: 0x000a, 0x291a: 0x000a, 0x291b: 0x000a, 0x291c: 0x000a, 0x291d: 0x000a, + 0x291e: 0x000a, 0x291f: 0x000a, 0x2920: 0x000a, 0x2921: 0x000a, 0x2922: 0x000a, 0x2923: 0x000a, + 0x2924: 0x000a, 0x2925: 0x000a, + 0x293f: 0x000c, + // Block 0xa5, offset 0x2940 + 0x2940: 0x000c, 0x2941: 0x000c, + 0x2973: 0x000c, 0x2974: 0x000c, 0x2975: 0x000c, + 0x2976: 0x000c, 0x2979: 0x000c, 0x297a: 0x000c, + // Block 0xa6, offset 0x2980 + 0x2980: 0x000c, 0x2981: 0x000c, 0x2982: 0x000c, + 0x29a7: 0x000c, 0x29a8: 0x000c, 0x29a9: 0x000c, + 0x29aa: 0x000c, 0x29ab: 0x000c, 0x29ad: 0x000c, 0x29ae: 0x000c, 0x29af: 0x000c, + 0x29b0: 0x000c, 0x29b1: 0x000c, 0x29b2: 0x000c, 0x29b3: 0x000c, 0x29b4: 0x000c, + // Block 0xa7, offset 0x29c0 + 0x29f3: 0x000c, + // Block 0xa8, offset 0x2a00 + 0x2a00: 0x000c, 0x2a01: 0x000c, + 0x2a36: 0x000c, 0x2a37: 0x000c, 0x2a38: 0x000c, 0x2a39: 0x000c, 0x2a3a: 0x000c, 0x2a3b: 0x000c, + 0x2a3c: 0x000c, 0x2a3d: 0x000c, 0x2a3e: 0x000c, + // Block 0xa9, offset 0x2a40 + 0x2a4a: 0x000c, 0x2a4b: 0x000c, + 0x2a4c: 0x000c, + // Block 0xaa, offset 0x2a80 + 0x2aaf: 0x000c, + 0x2ab0: 0x000c, 0x2ab1: 0x000c, 0x2ab4: 0x000c, + 0x2ab6: 0x000c, 0x2ab7: 0x000c, + 0x2abe: 0x000c, + // Block 0xab, offset 0x2ac0 + 0x2adf: 0x000c, 0x2ae3: 0x000c, + 0x2ae4: 0x000c, 0x2ae5: 0x000c, 0x2ae6: 0x000c, 0x2ae7: 0x000c, 0x2ae8: 0x000c, 0x2ae9: 0x000c, + 0x2aea: 0x000c, + // Block 0xac, offset 0x2b00 + 0x2b00: 0x000c, 0x2b01: 0x000c, + 0x2b3c: 0x000c, + // Block 0xad, offset 0x2b40 + 0x2b40: 0x000c, + 0x2b66: 0x000c, 0x2b67: 0x000c, 0x2b68: 0x000c, 0x2b69: 0x000c, + 0x2b6a: 0x000c, 0x2b6b: 0x000c, 0x2b6c: 0x000c, + 0x2b70: 0x000c, 0x2b71: 0x000c, 0x2b72: 0x000c, 0x2b73: 0x000c, 0x2b74: 0x000c, + // Block 0xae, offset 0x2b80 + 0x2bb8: 0x000c, 0x2bb9: 0x000c, 0x2bba: 0x000c, 0x2bbb: 0x000c, + 0x2bbc: 0x000c, 0x2bbd: 0x000c, 0x2bbe: 0x000c, 0x2bbf: 0x000c, + // Block 0xaf, offset 0x2bc0 + 0x2bc2: 0x000c, 0x2bc3: 0x000c, 0x2bc4: 0x000c, + 0x2bc6: 0x000c, + // Block 0xb0, offset 0x2c00 + 0x2c33: 0x000c, 0x2c34: 0x000c, 0x2c35: 0x000c, + 0x2c36: 0x000c, 0x2c37: 0x000c, 0x2c38: 0x000c, 0x2c3a: 0x000c, + 0x2c3f: 0x000c, + // Block 0xb1, offset 0x2c40 + 0x2c40: 0x000c, 0x2c42: 0x000c, 0x2c43: 0x000c, + // Block 0xb2, offset 0x2c80 + 0x2cb2: 0x000c, 0x2cb3: 0x000c, 0x2cb4: 0x000c, 0x2cb5: 0x000c, + 0x2cbc: 0x000c, 0x2cbd: 0x000c, 0x2cbf: 0x000c, + // Block 0xb3, offset 0x2cc0 + 0x2cc0: 0x000c, + 0x2cdc: 0x000c, 0x2cdd: 0x000c, + // Block 0xb4, offset 0x2d00 + 0x2d33: 0x000c, 0x2d34: 0x000c, 0x2d35: 0x000c, + 0x2d36: 0x000c, 0x2d37: 0x000c, 0x2d38: 0x000c, 0x2d39: 0x000c, 0x2d3a: 0x000c, + 0x2d3d: 0x000c, 0x2d3f: 0x000c, + // Block 0xb5, offset 0x2d40 + 0x2d40: 0x000c, + 0x2d60: 0x000a, 0x2d61: 0x000a, 0x2d62: 0x000a, 0x2d63: 0x000a, + 0x2d64: 0x000a, 0x2d65: 0x000a, 0x2d66: 0x000a, 0x2d67: 0x000a, 0x2d68: 0x000a, 0x2d69: 0x000a, + 0x2d6a: 0x000a, 0x2d6b: 0x000a, 0x2d6c: 0x000a, + // Block 0xb6, offset 0x2d80 + 0x2dab: 0x000c, 0x2dad: 0x000c, + 0x2db0: 0x000c, 0x2db1: 0x000c, 0x2db2: 0x000c, 0x2db3: 0x000c, 0x2db4: 0x000c, 0x2db5: 0x000c, + 0x2db7: 0x000c, + // Block 0xb7, offset 0x2dc0 + 0x2ddd: 0x000c, + 0x2dde: 0x000c, 0x2ddf: 0x000c, 0x2de2: 0x000c, 0x2de3: 0x000c, + 0x2de4: 0x000c, 0x2de5: 0x000c, 0x2de7: 0x000c, 0x2de8: 0x000c, 0x2de9: 0x000c, + 0x2dea: 0x000c, 0x2deb: 0x000c, + // Block 0xb8, offset 0x2e00 + 0x2e30: 0x000c, 0x2e31: 0x000c, 0x2e32: 0x000c, 0x2e33: 0x000c, 0x2e34: 0x000c, 0x2e35: 0x000c, + 0x2e36: 0x000c, 0x2e38: 0x000c, 0x2e39: 0x000c, 0x2e3a: 0x000c, 0x2e3b: 0x000c, + 0x2e3c: 0x000c, 0x2e3d: 0x000c, + // Block 0xb9, offset 0x2e40 + 0x2e52: 0x000c, 0x2e53: 0x000c, 0x2e54: 0x000c, 0x2e55: 0x000c, 0x2e56: 0x000c, 0x2e57: 0x000c, + 0x2e58: 0x000c, 0x2e59: 0x000c, 0x2e5a: 0x000c, 0x2e5b: 0x000c, 0x2e5c: 0x000c, 0x2e5d: 0x000c, + 0x2e5e: 0x000c, 0x2e5f: 0x000c, 0x2e60: 0x000c, 0x2e61: 0x000c, 0x2e62: 0x000c, 0x2e63: 0x000c, + 0x2e64: 0x000c, 0x2e65: 0x000c, 0x2e66: 0x000c, 0x2e67: 0x000c, + 0x2e6a: 0x000c, 0x2e6b: 0x000c, 0x2e6c: 0x000c, 0x2e6d: 0x000c, 0x2e6e: 0x000c, 0x2e6f: 0x000c, + 0x2e70: 0x000c, 0x2e72: 0x000c, 0x2e73: 0x000c, 0x2e75: 0x000c, + 0x2e76: 0x000c, + // Block 0xba, offset 0x2e80 + 0x2eb0: 0x000c, 0x2eb1: 0x000c, 0x2eb2: 0x000c, 0x2eb3: 0x000c, 0x2eb4: 0x000c, + // Block 0xbb, offset 0x2ec0 + 0x2ef0: 0x000c, 0x2ef1: 0x000c, 0x2ef2: 0x000c, 0x2ef3: 0x000c, 0x2ef4: 0x000c, 0x2ef5: 0x000c, + 0x2ef6: 0x000c, + // Block 0xbc, offset 0x2f00 + 0x2f0f: 0x000c, 0x2f10: 0x000c, 0x2f11: 0x000c, + 0x2f12: 0x000c, + // Block 0xbd, offset 0x2f40 + 0x2f5d: 0x000c, + 0x2f5e: 0x000c, 0x2f60: 0x000b, 0x2f61: 0x000b, 0x2f62: 0x000b, 0x2f63: 0x000b, + // Block 0xbe, offset 0x2f80 + 0x2fa7: 0x000c, 0x2fa8: 0x000c, 0x2fa9: 0x000c, + 0x2fb3: 0x000b, 0x2fb4: 0x000b, 0x2fb5: 0x000b, + 0x2fb6: 0x000b, 0x2fb7: 0x000b, 0x2fb8: 0x000b, 0x2fb9: 0x000b, 0x2fba: 0x000b, 0x2fbb: 0x000c, + 0x2fbc: 0x000c, 0x2fbd: 0x000c, 0x2fbe: 0x000c, 0x2fbf: 0x000c, + // Block 0xbf, offset 0x2fc0 + 0x2fc0: 0x000c, 0x2fc1: 0x000c, 0x2fc2: 0x000c, 0x2fc5: 0x000c, + 0x2fc6: 0x000c, 0x2fc7: 0x000c, 0x2fc8: 0x000c, 0x2fc9: 0x000c, 0x2fca: 0x000c, 0x2fcb: 0x000c, + 0x2fea: 0x000c, 0x2feb: 0x000c, 0x2fec: 0x000c, 0x2fed: 0x000c, + // Block 0xc0, offset 0x3000 + 0x3000: 0x000a, 0x3001: 0x000a, 0x3002: 0x000c, 0x3003: 0x000c, 0x3004: 0x000c, 0x3005: 0x000a, + // Block 0xc1, offset 0x3040 + 0x3040: 0x000a, 0x3041: 0x000a, 0x3042: 0x000a, 0x3043: 0x000a, 0x3044: 0x000a, 0x3045: 0x000a, + 0x3046: 0x000a, 0x3047: 0x000a, 0x3048: 0x000a, 0x3049: 0x000a, 0x304a: 0x000a, 0x304b: 0x000a, + 0x304c: 0x000a, 0x304d: 0x000a, 0x304e: 0x000a, 0x304f: 0x000a, 0x3050: 0x000a, 0x3051: 0x000a, + 0x3052: 0x000a, 0x3053: 0x000a, 0x3054: 0x000a, 0x3055: 0x000a, 0x3056: 0x000a, + // Block 0xc2, offset 0x3080 + 0x309b: 0x000a, + // Block 0xc3, offset 0x30c0 + 0x30d5: 0x000a, + // Block 0xc4, offset 0x3100 + 0x310f: 0x000a, + // Block 0xc5, offset 0x3140 + 0x3149: 0x000a, + // Block 0xc6, offset 0x3180 + 0x3183: 0x000a, + 0x318e: 0x0002, 0x318f: 0x0002, 0x3190: 0x0002, 0x3191: 0x0002, + 0x3192: 0x0002, 0x3193: 0x0002, 0x3194: 0x0002, 0x3195: 0x0002, 0x3196: 0x0002, 0x3197: 0x0002, + 0x3198: 0x0002, 0x3199: 0x0002, 0x319a: 0x0002, 0x319b: 0x0002, 0x319c: 0x0002, 0x319d: 0x0002, + 0x319e: 0x0002, 0x319f: 0x0002, 0x31a0: 0x0002, 0x31a1: 0x0002, 0x31a2: 0x0002, 0x31a3: 0x0002, + 0x31a4: 0x0002, 0x31a5: 0x0002, 0x31a6: 0x0002, 0x31a7: 0x0002, 0x31a8: 0x0002, 0x31a9: 0x0002, + 0x31aa: 0x0002, 0x31ab: 0x0002, 0x31ac: 0x0002, 0x31ad: 0x0002, 0x31ae: 0x0002, 0x31af: 0x0002, + 0x31b0: 0x0002, 0x31b1: 0x0002, 0x31b2: 0x0002, 0x31b3: 0x0002, 0x31b4: 0x0002, 0x31b5: 0x0002, + 0x31b6: 0x0002, 0x31b7: 0x0002, 0x31b8: 0x0002, 0x31b9: 0x0002, 0x31ba: 0x0002, 0x31bb: 0x0002, + 0x31bc: 0x0002, 0x31bd: 0x0002, 0x31be: 0x0002, 0x31bf: 0x0002, + // Block 0xc7, offset 0x31c0 + 0x31c0: 0x000c, 0x31c1: 0x000c, 0x31c2: 0x000c, 0x31c3: 0x000c, 0x31c4: 0x000c, 0x31c5: 0x000c, + 0x31c6: 0x000c, 0x31c7: 0x000c, 0x31c8: 0x000c, 0x31c9: 0x000c, 0x31ca: 0x000c, 0x31cb: 0x000c, + 0x31cc: 0x000c, 0x31cd: 0x000c, 0x31ce: 0x000c, 0x31cf: 0x000c, 0x31d0: 0x000c, 0x31d1: 0x000c, + 0x31d2: 0x000c, 0x31d3: 0x000c, 0x31d4: 0x000c, 0x31d5: 0x000c, 0x31d6: 0x000c, 0x31d7: 0x000c, + 0x31d8: 0x000c, 0x31d9: 0x000c, 0x31da: 0x000c, 0x31db: 0x000c, 0x31dc: 0x000c, 0x31dd: 0x000c, + 0x31de: 0x000c, 0x31df: 0x000c, 0x31e0: 0x000c, 0x31e1: 0x000c, 0x31e2: 0x000c, 0x31e3: 0x000c, + 0x31e4: 0x000c, 0x31e5: 0x000c, 0x31e6: 0x000c, 0x31e7: 0x000c, 0x31e8: 0x000c, 0x31e9: 0x000c, + 0x31ea: 0x000c, 0x31eb: 0x000c, 0x31ec: 0x000c, 0x31ed: 0x000c, 0x31ee: 0x000c, 0x31ef: 0x000c, + 0x31f0: 0x000c, 0x31f1: 0x000c, 0x31f2: 0x000c, 0x31f3: 0x000c, 0x31f4: 0x000c, 0x31f5: 0x000c, + 0x31f6: 0x000c, 0x31fb: 0x000c, + 0x31fc: 0x000c, 0x31fd: 0x000c, 0x31fe: 0x000c, 0x31ff: 0x000c, + // Block 0xc8, offset 0x3200 + 0x3200: 0x000c, 0x3201: 0x000c, 0x3202: 0x000c, 0x3203: 0x000c, 0x3204: 0x000c, 0x3205: 0x000c, + 0x3206: 0x000c, 0x3207: 0x000c, 0x3208: 0x000c, 0x3209: 0x000c, 0x320a: 0x000c, 0x320b: 0x000c, + 0x320c: 0x000c, 0x320d: 0x000c, 0x320e: 0x000c, 0x320f: 0x000c, 0x3210: 0x000c, 0x3211: 0x000c, + 0x3212: 0x000c, 0x3213: 0x000c, 0x3214: 0x000c, 0x3215: 0x000c, 0x3216: 0x000c, 0x3217: 0x000c, + 0x3218: 0x000c, 0x3219: 0x000c, 0x321a: 0x000c, 0x321b: 0x000c, 0x321c: 0x000c, 0x321d: 0x000c, + 0x321e: 0x000c, 0x321f: 0x000c, 0x3220: 0x000c, 0x3221: 0x000c, 0x3222: 0x000c, 0x3223: 0x000c, + 0x3224: 0x000c, 0x3225: 0x000c, 0x3226: 0x000c, 0x3227: 0x000c, 0x3228: 0x000c, 0x3229: 0x000c, + 0x322a: 0x000c, 0x322b: 0x000c, 0x322c: 0x000c, + 0x3235: 0x000c, + // Block 0xc9, offset 0x3240 + 0x3244: 0x000c, + 0x325b: 0x000c, 0x325c: 0x000c, 0x325d: 0x000c, + 0x325e: 0x000c, 0x325f: 0x000c, 0x3261: 0x000c, 0x3262: 0x000c, 0x3263: 0x000c, + 0x3264: 0x000c, 0x3265: 0x000c, 0x3266: 0x000c, 0x3267: 0x000c, 0x3268: 0x000c, 0x3269: 0x000c, + 0x326a: 0x000c, 0x326b: 0x000c, 0x326c: 0x000c, 0x326d: 0x000c, 0x326e: 0x000c, 0x326f: 0x000c, + // Block 0xca, offset 0x3280 + 0x3280: 0x000c, 0x3281: 0x000c, 0x3282: 0x000c, 0x3283: 0x000c, 0x3284: 0x000c, 0x3285: 0x000c, + 0x3286: 0x000c, 0x3288: 0x000c, 0x3289: 0x000c, 0x328a: 0x000c, 0x328b: 0x000c, + 0x328c: 0x000c, 0x328d: 0x000c, 0x328e: 0x000c, 0x328f: 0x000c, 0x3290: 0x000c, 0x3291: 0x000c, + 0x3292: 0x000c, 0x3293: 0x000c, 0x3294: 0x000c, 0x3295: 0x000c, 0x3296: 0x000c, 0x3297: 0x000c, + 0x3298: 0x000c, 0x329b: 0x000c, 0x329c: 0x000c, 0x329d: 0x000c, + 0x329e: 0x000c, 0x329f: 0x000c, 0x32a0: 0x000c, 0x32a1: 0x000c, 0x32a3: 0x000c, + 0x32a4: 0x000c, 0x32a6: 0x000c, 0x32a7: 0x000c, 0x32a8: 0x000c, 0x32a9: 0x000c, + 0x32aa: 0x000c, + // Block 0xcb, offset 0x32c0 + 0x32c0: 0x0001, 0x32c1: 0x0001, 0x32c2: 0x0001, 0x32c3: 0x0001, 0x32c4: 0x0001, 0x32c5: 0x0001, + 0x32c6: 0x0001, 0x32c7: 0x0001, 0x32c8: 0x0001, 0x32c9: 0x0001, 0x32ca: 0x0001, 0x32cb: 0x0001, + 0x32cc: 0x0001, 0x32cd: 0x0001, 0x32ce: 0x0001, 0x32cf: 0x0001, 0x32d0: 0x000c, 0x32d1: 0x000c, + 0x32d2: 0x000c, 0x32d3: 0x000c, 0x32d4: 0x000c, 0x32d5: 0x000c, 0x32d6: 0x000c, 0x32d7: 0x0001, + 0x32d8: 0x0001, 0x32d9: 0x0001, 0x32da: 0x0001, 0x32db: 0x0001, 0x32dc: 0x0001, 0x32dd: 0x0001, + 0x32de: 0x0001, 0x32df: 0x0001, 0x32e0: 0x0001, 0x32e1: 0x0001, 0x32e2: 0x0001, 0x32e3: 0x0001, + 0x32e4: 0x0001, 0x32e5: 0x0001, 0x32e6: 0x0001, 0x32e7: 0x0001, 0x32e8: 0x0001, 0x32e9: 0x0001, + 0x32ea: 0x0001, 0x32eb: 0x0001, 0x32ec: 0x0001, 0x32ed: 0x0001, 0x32ee: 0x0001, 0x32ef: 0x0001, + 0x32f0: 0x0001, 0x32f1: 0x0001, 0x32f2: 0x0001, 0x32f3: 0x0001, 0x32f4: 0x0001, 0x32f5: 0x0001, + 0x32f6: 0x0001, 0x32f7: 0x0001, 0x32f8: 0x0001, 0x32f9: 0x0001, 0x32fa: 0x0001, 0x32fb: 0x0001, + 0x32fc: 0x0001, 0x32fd: 0x0001, 0x32fe: 0x0001, 0x32ff: 0x0001, + // Block 0xcc, offset 0x3300 + 0x3300: 0x0001, 0x3301: 0x0001, 0x3302: 0x0001, 0x3303: 0x0001, 0x3304: 0x000c, 0x3305: 0x000c, + 0x3306: 0x000c, 0x3307: 0x000c, 0x3308: 0x000c, 0x3309: 0x000c, 0x330a: 0x000c, 0x330b: 0x0001, + 0x330c: 0x0001, 0x330d: 0x0001, 0x330e: 0x0001, 0x330f: 0x0001, 0x3310: 0x0001, 0x3311: 0x0001, + 0x3312: 0x0001, 0x3313: 0x0001, 0x3314: 0x0001, 0x3315: 0x0001, 0x3316: 0x0001, 0x3317: 0x0001, + 0x3318: 0x0001, 0x3319: 0x0001, 0x331a: 0x0001, 0x331b: 0x0001, 0x331c: 0x0001, 0x331d: 0x0001, + 0x331e: 0x0001, 0x331f: 0x0001, 0x3320: 0x0001, 0x3321: 0x0001, 0x3322: 0x0001, 0x3323: 0x0001, + 0x3324: 0x0001, 0x3325: 0x0001, 0x3326: 0x0001, 0x3327: 0x0001, 0x3328: 0x0001, 0x3329: 0x0001, + 0x332a: 0x0001, 0x332b: 0x0001, 0x332c: 0x0001, 0x332d: 0x0001, 0x332e: 0x0001, 0x332f: 0x0001, + 0x3330: 0x0001, 0x3331: 0x0001, 0x3332: 0x0001, 0x3333: 0x0001, 0x3334: 0x0001, 0x3335: 0x0001, + 0x3336: 0x0001, 0x3337: 0x0001, 0x3338: 0x0001, 0x3339: 0x0001, 0x333a: 0x0001, 0x333b: 0x0001, + 0x333c: 0x0001, 0x333d: 0x0001, 0x333e: 0x0001, 0x333f: 0x0001, + // Block 0xcd, offset 0x3340 + 0x3340: 0x000d, 0x3341: 0x000d, 0x3342: 0x000d, 0x3343: 0x000d, 0x3344: 0x000d, 0x3345: 0x000d, + 0x3346: 0x000d, 0x3347: 0x000d, 0x3348: 0x000d, 0x3349: 0x000d, 0x334a: 0x000d, 0x334b: 0x000d, + 0x334c: 0x000d, 0x334d: 0x000d, 0x334e: 0x000d, 0x334f: 0x000d, 0x3350: 0x000d, 0x3351: 0x000d, + 0x3352: 0x000d, 0x3353: 0x000d, 0x3354: 0x000d, 0x3355: 0x000d, 0x3356: 0x000d, 0x3357: 0x000d, + 0x3358: 0x000d, 0x3359: 0x000d, 0x335a: 0x000d, 0x335b: 0x000d, 0x335c: 0x000d, 0x335d: 0x000d, + 0x335e: 0x000d, 0x335f: 0x000d, 0x3360: 0x000d, 0x3361: 0x000d, 0x3362: 0x000d, 0x3363: 0x000d, + 0x3364: 0x000d, 0x3365: 0x000d, 0x3366: 0x000d, 0x3367: 0x000d, 0x3368: 0x000d, 0x3369: 0x000d, + 0x336a: 0x000d, 0x336b: 0x000d, 0x336c: 0x000d, 0x336d: 0x000d, 0x336e: 0x000d, 0x336f: 0x000d, + 0x3370: 0x000a, 0x3371: 0x000a, 0x3372: 0x000d, 0x3373: 0x000d, 0x3374: 0x000d, 0x3375: 0x000d, + 0x3376: 0x000d, 0x3377: 0x000d, 0x3378: 0x000d, 0x3379: 0x000d, 0x337a: 0x000d, 0x337b: 0x000d, + 0x337c: 0x000d, 0x337d: 0x000d, 0x337e: 0x000d, 0x337f: 0x000d, + // Block 0xce, offset 0x3380 + 0x3380: 0x000a, 0x3381: 0x000a, 0x3382: 0x000a, 0x3383: 0x000a, 0x3384: 0x000a, 0x3385: 0x000a, + 0x3386: 0x000a, 0x3387: 0x000a, 0x3388: 0x000a, 0x3389: 0x000a, 0x338a: 0x000a, 0x338b: 0x000a, + 0x338c: 0x000a, 0x338d: 0x000a, 0x338e: 0x000a, 0x338f: 0x000a, 0x3390: 0x000a, 0x3391: 0x000a, + 0x3392: 0x000a, 0x3393: 0x000a, 0x3394: 0x000a, 0x3395: 0x000a, 0x3396: 0x000a, 0x3397: 0x000a, + 0x3398: 0x000a, 0x3399: 0x000a, 0x339a: 0x000a, 0x339b: 0x000a, 0x339c: 0x000a, 0x339d: 0x000a, + 0x339e: 0x000a, 0x339f: 0x000a, 0x33a0: 0x000a, 0x33a1: 0x000a, 0x33a2: 0x000a, 0x33a3: 0x000a, + 0x33a4: 0x000a, 0x33a5: 0x000a, 0x33a6: 0x000a, 0x33a7: 0x000a, 0x33a8: 0x000a, 0x33a9: 0x000a, + 0x33aa: 0x000a, 0x33ab: 0x000a, + 0x33b0: 0x000a, 0x33b1: 0x000a, 0x33b2: 0x000a, 0x33b3: 0x000a, 0x33b4: 0x000a, 0x33b5: 0x000a, + 0x33b6: 0x000a, 0x33b7: 0x000a, 0x33b8: 0x000a, 0x33b9: 0x000a, 0x33ba: 0x000a, 0x33bb: 0x000a, + 0x33bc: 0x000a, 0x33bd: 0x000a, 0x33be: 0x000a, 0x33bf: 0x000a, + // Block 0xcf, offset 0x33c0 + 0x33c0: 0x000a, 0x33c1: 0x000a, 0x33c2: 0x000a, 0x33c3: 0x000a, 0x33c4: 0x000a, 0x33c5: 0x000a, + 0x33c6: 0x000a, 0x33c7: 0x000a, 0x33c8: 0x000a, 0x33c9: 0x000a, 0x33ca: 0x000a, 0x33cb: 0x000a, + 0x33cc: 0x000a, 0x33cd: 0x000a, 0x33ce: 0x000a, 0x33cf: 0x000a, 0x33d0: 0x000a, 0x33d1: 0x000a, + 0x33d2: 0x000a, 0x33d3: 0x000a, + 0x33e0: 0x000a, 0x33e1: 0x000a, 0x33e2: 0x000a, 0x33e3: 0x000a, + 0x33e4: 0x000a, 0x33e5: 0x000a, 0x33e6: 0x000a, 0x33e7: 0x000a, 0x33e8: 0x000a, 0x33e9: 0x000a, + 0x33ea: 0x000a, 0x33eb: 0x000a, 0x33ec: 0x000a, 0x33ed: 0x000a, 0x33ee: 0x000a, + 0x33f1: 0x000a, 0x33f2: 0x000a, 0x33f3: 0x000a, 0x33f4: 0x000a, 0x33f5: 0x000a, + 0x33f6: 0x000a, 0x33f7: 0x000a, 0x33f8: 0x000a, 0x33f9: 0x000a, 0x33fa: 0x000a, 0x33fb: 0x000a, + 0x33fc: 0x000a, 0x33fd: 0x000a, 0x33fe: 0x000a, 0x33ff: 0x000a, + // Block 0xd0, offset 0x3400 + 0x3401: 0x000a, 0x3402: 0x000a, 0x3403: 0x000a, 0x3404: 0x000a, 0x3405: 0x000a, + 0x3406: 0x000a, 0x3407: 0x000a, 0x3408: 0x000a, 0x3409: 0x000a, 0x340a: 0x000a, 0x340b: 0x000a, + 0x340c: 0x000a, 0x340d: 0x000a, 0x340e: 0x000a, 0x340f: 0x000a, 0x3411: 0x000a, + 0x3412: 0x000a, 0x3413: 0x000a, 0x3414: 0x000a, 0x3415: 0x000a, 0x3416: 0x000a, 0x3417: 0x000a, + 0x3418: 0x000a, 0x3419: 0x000a, 0x341a: 0x000a, 0x341b: 0x000a, 0x341c: 0x000a, 0x341d: 0x000a, + 0x341e: 0x000a, 0x341f: 0x000a, 0x3420: 0x000a, 0x3421: 0x000a, 0x3422: 0x000a, 0x3423: 0x000a, + 0x3424: 0x000a, 0x3425: 0x000a, 0x3426: 0x000a, 0x3427: 0x000a, 0x3428: 0x000a, 0x3429: 0x000a, + 0x342a: 0x000a, 0x342b: 0x000a, 0x342c: 0x000a, 0x342d: 0x000a, 0x342e: 0x000a, 0x342f: 0x000a, + 0x3430: 0x000a, 0x3431: 0x000a, 0x3432: 0x000a, 0x3433: 0x000a, 0x3434: 0x000a, 0x3435: 0x000a, + // Block 0xd1, offset 0x3440 + 0x3440: 0x0002, 0x3441: 0x0002, 0x3442: 0x0002, 0x3443: 0x0002, 0x3444: 0x0002, 0x3445: 0x0002, + 0x3446: 0x0002, 0x3447: 0x0002, 0x3448: 0x0002, 0x3449: 0x0002, 0x344a: 0x0002, 0x344b: 0x000a, + 0x344c: 0x000a, + // Block 0xd2, offset 0x3480 + 0x34aa: 0x000a, 0x34ab: 0x000a, + // Block 0xd3, offset 0x34c0 + 0x34c0: 0x000a, 0x34c1: 0x000a, 0x34c2: 0x000a, 0x34c3: 0x000a, 0x34c4: 0x000a, 0x34c5: 0x000a, + 0x34c6: 0x000a, 0x34c7: 0x000a, 0x34c8: 0x000a, 0x34c9: 0x000a, 0x34ca: 0x000a, 0x34cb: 0x000a, + 0x34cc: 0x000a, 0x34cd: 0x000a, 0x34ce: 0x000a, 0x34cf: 0x000a, 0x34d0: 0x000a, 0x34d1: 0x000a, + 0x34d2: 0x000a, + 0x34e0: 0x000a, 0x34e1: 0x000a, 0x34e2: 0x000a, 0x34e3: 0x000a, + 0x34e4: 0x000a, 0x34e5: 0x000a, 0x34e6: 0x000a, 0x34e7: 0x000a, 0x34e8: 0x000a, 0x34e9: 0x000a, + 0x34ea: 0x000a, 0x34eb: 0x000a, 0x34ec: 0x000a, + 0x34f0: 0x000a, 0x34f1: 0x000a, 0x34f2: 0x000a, 0x34f3: 0x000a, 0x34f4: 0x000a, 0x34f5: 0x000a, + 0x34f6: 0x000a, + // Block 0xd4, offset 0x3500 + 0x3500: 0x000a, 0x3501: 0x000a, 0x3502: 0x000a, 0x3503: 0x000a, 0x3504: 0x000a, 0x3505: 0x000a, + 0x3506: 0x000a, 0x3507: 0x000a, 0x3508: 0x000a, 0x3509: 0x000a, 0x350a: 0x000a, 0x350b: 0x000a, + 0x350c: 0x000a, 0x350d: 0x000a, 0x350e: 0x000a, 0x350f: 0x000a, 0x3510: 0x000a, 0x3511: 0x000a, + 0x3512: 0x000a, 0x3513: 0x000a, 0x3514: 0x000a, + // Block 0xd5, offset 0x3540 + 0x3540: 0x000a, 0x3541: 0x000a, 0x3542: 0x000a, 0x3543: 0x000a, 0x3544: 0x000a, 0x3545: 0x000a, + 0x3546: 0x000a, 0x3547: 0x000a, 0x3548: 0x000a, 0x3549: 0x000a, 0x354a: 0x000a, 0x354b: 0x000a, + 0x3550: 0x000a, 0x3551: 0x000a, + 0x3552: 0x000a, 0x3553: 0x000a, 0x3554: 0x000a, 0x3555: 0x000a, 0x3556: 0x000a, 0x3557: 0x000a, + 0x3558: 0x000a, 0x3559: 0x000a, 0x355a: 0x000a, 0x355b: 0x000a, 0x355c: 0x000a, 0x355d: 0x000a, + 0x355e: 0x000a, 0x355f: 0x000a, 0x3560: 0x000a, 0x3561: 0x000a, 0x3562: 0x000a, 0x3563: 0x000a, + 0x3564: 0x000a, 0x3565: 0x000a, 0x3566: 0x000a, 0x3567: 0x000a, 0x3568: 0x000a, 0x3569: 0x000a, + 0x356a: 0x000a, 0x356b: 0x000a, 0x356c: 0x000a, 0x356d: 0x000a, 0x356e: 0x000a, 0x356f: 0x000a, + 0x3570: 0x000a, 0x3571: 0x000a, 0x3572: 0x000a, 0x3573: 0x000a, 0x3574: 0x000a, 0x3575: 0x000a, + 0x3576: 0x000a, 0x3577: 0x000a, 0x3578: 0x000a, 0x3579: 0x000a, 0x357a: 0x000a, 0x357b: 0x000a, + 0x357c: 0x000a, 0x357d: 0x000a, 0x357e: 0x000a, 0x357f: 0x000a, + // Block 0xd6, offset 0x3580 + 0x3580: 0x000a, 0x3581: 0x000a, 0x3582: 0x000a, 0x3583: 0x000a, 0x3584: 0x000a, 0x3585: 0x000a, + 0x3586: 0x000a, 0x3587: 0x000a, + 0x3590: 0x000a, 0x3591: 0x000a, + 0x3592: 0x000a, 0x3593: 0x000a, 0x3594: 0x000a, 0x3595: 0x000a, 0x3596: 0x000a, 0x3597: 0x000a, + 0x3598: 0x000a, 0x3599: 0x000a, + 0x35a0: 0x000a, 0x35a1: 0x000a, 0x35a2: 0x000a, 0x35a3: 0x000a, + 0x35a4: 0x000a, 0x35a5: 0x000a, 0x35a6: 0x000a, 0x35a7: 0x000a, 0x35a8: 0x000a, 0x35a9: 0x000a, + 0x35aa: 0x000a, 0x35ab: 0x000a, 0x35ac: 0x000a, 0x35ad: 0x000a, 0x35ae: 0x000a, 0x35af: 0x000a, + 0x35b0: 0x000a, 0x35b1: 0x000a, 0x35b2: 0x000a, 0x35b3: 0x000a, 0x35b4: 0x000a, 0x35b5: 0x000a, + 0x35b6: 0x000a, 0x35b7: 0x000a, 0x35b8: 0x000a, 0x35b9: 0x000a, 0x35ba: 0x000a, 0x35bb: 0x000a, + 0x35bc: 0x000a, 0x35bd: 0x000a, 0x35be: 0x000a, 0x35bf: 0x000a, + // Block 0xd7, offset 0x35c0 + 0x35c0: 0x000a, 0x35c1: 0x000a, 0x35c2: 0x000a, 0x35c3: 0x000a, 0x35c4: 0x000a, 0x35c5: 0x000a, + 0x35c6: 0x000a, 0x35c7: 0x000a, + 0x35d0: 0x000a, 0x35d1: 0x000a, + 0x35d2: 0x000a, 0x35d3: 0x000a, 0x35d4: 0x000a, 0x35d5: 0x000a, 0x35d6: 0x000a, 0x35d7: 0x000a, + 0x35d8: 0x000a, 0x35d9: 0x000a, 0x35da: 0x000a, 0x35db: 0x000a, 0x35dc: 0x000a, 0x35dd: 0x000a, + 0x35de: 0x000a, 0x35df: 0x000a, 0x35e0: 0x000a, 0x35e1: 0x000a, 0x35e2: 0x000a, 0x35e3: 0x000a, + 0x35e4: 0x000a, 0x35e5: 0x000a, 0x35e6: 0x000a, 0x35e7: 0x000a, 0x35e8: 0x000a, 0x35e9: 0x000a, + 0x35ea: 0x000a, 0x35eb: 0x000a, 0x35ec: 0x000a, 0x35ed: 0x000a, + // Block 0xd8, offset 0x3600 + 0x3610: 0x000a, 0x3611: 0x000a, + 0x3612: 0x000a, 0x3613: 0x000a, 0x3614: 0x000a, 0x3615: 0x000a, 0x3616: 0x000a, 0x3617: 0x000a, + 0x3618: 0x000a, 0x3619: 0x000a, 0x361a: 0x000a, 0x361b: 0x000a, 0x361c: 0x000a, 0x361d: 0x000a, + 0x361e: 0x000a, 0x3620: 0x000a, 0x3621: 0x000a, 0x3622: 0x000a, 0x3623: 0x000a, + 0x3624: 0x000a, 0x3625: 0x000a, 0x3626: 0x000a, 0x3627: 0x000a, + 0x3630: 0x000a, 0x3633: 0x000a, 0x3634: 0x000a, 0x3635: 0x000a, + 0x3636: 0x000a, 0x3637: 0x000a, 0x3638: 0x000a, 0x3639: 0x000a, 0x363a: 0x000a, 0x363b: 0x000a, + 0x363c: 0x000a, 0x363d: 0x000a, 0x363e: 0x000a, + // Block 0xd9, offset 0x3640 + 0x3640: 0x000a, 0x3641: 0x000a, 0x3642: 0x000a, 0x3643: 0x000a, 0x3644: 0x000a, 0x3645: 0x000a, + 0x3646: 0x000a, 0x3647: 0x000a, 0x3648: 0x000a, 0x3649: 0x000a, 0x364a: 0x000a, 0x364b: 0x000a, + 0x3650: 0x000a, 0x3651: 0x000a, + 0x3652: 0x000a, 0x3653: 0x000a, 0x3654: 0x000a, 0x3655: 0x000a, 0x3656: 0x000a, 0x3657: 0x000a, + 0x3658: 0x000a, 0x3659: 0x000a, 0x365a: 0x000a, 0x365b: 0x000a, 0x365c: 0x000a, 0x365d: 0x000a, + 0x365e: 0x000a, + // Block 0xda, offset 0x3680 + 0x3680: 0x000a, 0x3681: 0x000a, 0x3682: 0x000a, 0x3683: 0x000a, 0x3684: 0x000a, 0x3685: 0x000a, + 0x3686: 0x000a, 0x3687: 0x000a, 0x3688: 0x000a, 0x3689: 0x000a, 0x368a: 0x000a, 0x368b: 0x000a, + 0x368c: 0x000a, 0x368d: 0x000a, 0x368e: 0x000a, 0x368f: 0x000a, 0x3690: 0x000a, 0x3691: 0x000a, + // Block 0xdb, offset 0x36c0 + 0x36fe: 0x000b, 0x36ff: 0x000b, + // Block 0xdc, offset 0x3700 + 0x3700: 0x000b, 0x3701: 0x000b, 0x3702: 0x000b, 0x3703: 0x000b, 0x3704: 0x000b, 0x3705: 0x000b, + 0x3706: 0x000b, 0x3707: 0x000b, 0x3708: 0x000b, 0x3709: 0x000b, 0x370a: 0x000b, 0x370b: 0x000b, + 0x370c: 0x000b, 0x370d: 0x000b, 0x370e: 0x000b, 0x370f: 0x000b, 0x3710: 0x000b, 0x3711: 0x000b, + 0x3712: 0x000b, 0x3713: 0x000b, 0x3714: 0x000b, 0x3715: 0x000b, 0x3716: 0x000b, 0x3717: 0x000b, + 0x3718: 0x000b, 0x3719: 0x000b, 0x371a: 0x000b, 0x371b: 0x000b, 0x371c: 0x000b, 0x371d: 0x000b, + 0x371e: 0x000b, 0x371f: 0x000b, 0x3720: 0x000b, 0x3721: 0x000b, 0x3722: 0x000b, 0x3723: 0x000b, + 0x3724: 0x000b, 0x3725: 0x000b, 0x3726: 0x000b, 0x3727: 0x000b, 0x3728: 0x000b, 0x3729: 0x000b, + 0x372a: 0x000b, 0x372b: 0x000b, 0x372c: 0x000b, 0x372d: 0x000b, 0x372e: 0x000b, 0x372f: 0x000b, + 0x3730: 0x000b, 0x3731: 0x000b, 0x3732: 0x000b, 0x3733: 0x000b, 0x3734: 0x000b, 0x3735: 0x000b, + 0x3736: 0x000b, 0x3737: 0x000b, 0x3738: 0x000b, 0x3739: 0x000b, 0x373a: 0x000b, 0x373b: 0x000b, + 0x373c: 0x000b, 0x373d: 0x000b, 0x373e: 0x000b, 0x373f: 0x000b, + // Block 0xdd, offset 0x3740 + 0x3740: 0x000c, 0x3741: 0x000c, 0x3742: 0x000c, 0x3743: 0x000c, 0x3744: 0x000c, 0x3745: 0x000c, + 0x3746: 0x000c, 0x3747: 0x000c, 0x3748: 0x000c, 0x3749: 0x000c, 0x374a: 0x000c, 0x374b: 0x000c, + 0x374c: 0x000c, 0x374d: 0x000c, 0x374e: 0x000c, 0x374f: 0x000c, 0x3750: 0x000c, 0x3751: 0x000c, + 0x3752: 0x000c, 0x3753: 0x000c, 0x3754: 0x000c, 0x3755: 0x000c, 0x3756: 0x000c, 0x3757: 0x000c, + 0x3758: 0x000c, 0x3759: 0x000c, 0x375a: 0x000c, 0x375b: 0x000c, 0x375c: 0x000c, 0x375d: 0x000c, + 0x375e: 0x000c, 0x375f: 0x000c, 0x3760: 0x000c, 0x3761: 0x000c, 0x3762: 0x000c, 0x3763: 0x000c, + 0x3764: 0x000c, 0x3765: 0x000c, 0x3766: 0x000c, 0x3767: 0x000c, 0x3768: 0x000c, 0x3769: 0x000c, + 0x376a: 0x000c, 0x376b: 0x000c, 0x376c: 0x000c, 0x376d: 0x000c, 0x376e: 0x000c, 0x376f: 0x000c, + 0x3770: 0x000b, 0x3771: 0x000b, 0x3772: 0x000b, 0x3773: 0x000b, 0x3774: 0x000b, 0x3775: 0x000b, + 0x3776: 0x000b, 0x3777: 0x000b, 0x3778: 0x000b, 0x3779: 0x000b, 0x377a: 0x000b, 0x377b: 0x000b, + 0x377c: 0x000b, 0x377d: 0x000b, 0x377e: 0x000b, 0x377f: 0x000b, +} + +// bidiIndex: 24 blocks, 1536 entries, 1536 bytes +// Block 0 is the zero block. +var bidiIndex = [1536]uint8{ + // Block 0x0, offset 0x0 + // Block 0x1, offset 0x40 + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc2: 0x01, 0xc3: 0x02, + 0xca: 0x03, 0xcb: 0x04, 0xcc: 0x05, 0xcd: 0x06, 0xce: 0x07, 0xcf: 0x08, + 0xd2: 0x09, 0xd6: 0x0a, 0xd7: 0x0b, + 0xd8: 0x0c, 0xd9: 0x0d, 0xda: 0x0e, 0xdb: 0x0f, 0xdc: 0x10, 0xdd: 0x11, 0xde: 0x12, 0xdf: 0x13, + 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05, 0xe4: 0x06, + 0xea: 0x07, 0xef: 0x08, + 0xf0: 0x11, 0xf1: 0x12, 0xf2: 0x12, 0xf3: 0x14, 0xf4: 0x15, + // Block 0x4, offset 0x100 + 0x120: 0x14, 0x121: 0x15, 0x122: 0x16, 0x123: 0x17, 0x124: 0x18, 0x125: 0x19, 0x126: 0x1a, 0x127: 0x1b, + 0x128: 0x1c, 0x129: 0x1d, 0x12a: 0x1c, 0x12b: 0x1e, 0x12c: 0x1f, 0x12d: 0x20, 0x12e: 0x21, 0x12f: 0x22, + 0x130: 0x23, 0x131: 0x24, 0x132: 0x1a, 0x133: 0x25, 0x134: 0x26, 0x135: 0x27, 0x137: 0x28, + 0x138: 0x29, 0x139: 0x2a, 0x13a: 0x2b, 0x13b: 0x2c, 0x13c: 0x2d, 0x13d: 0x2e, 0x13e: 0x2f, 0x13f: 0x30, + // Block 0x5, offset 0x140 + 0x140: 0x31, 0x141: 0x32, 0x142: 0x33, + 0x14d: 0x34, 0x14e: 0x35, + 0x150: 0x36, + 0x15a: 0x37, 0x15c: 0x38, 0x15d: 0x39, 0x15e: 0x3a, 0x15f: 0x3b, + 0x160: 0x3c, 0x162: 0x3d, 0x164: 0x3e, 0x165: 0x3f, 0x167: 0x40, + 0x168: 0x41, 0x169: 0x42, 0x16a: 0x43, 0x16c: 0x44, 0x16d: 0x45, 0x16e: 0x46, 0x16f: 0x47, + 0x170: 0x48, 0x173: 0x49, 0x177: 0x4a, + 0x17e: 0x4b, 0x17f: 0x4c, + // Block 0x6, offset 0x180 + 0x180: 0x4d, 0x181: 0x4e, 0x182: 0x4f, 0x183: 0x50, 0x184: 0x51, 0x185: 0x52, 0x186: 0x53, 0x187: 0x54, + 0x188: 0x55, 0x189: 0x54, 0x18a: 0x54, 0x18b: 0x54, 0x18c: 0x56, 0x18d: 0x57, 0x18e: 0x58, 0x18f: 0x59, + 0x190: 0x5a, 0x191: 0x5b, 0x192: 0x5c, 0x193: 0x5d, 0x194: 0x54, 0x195: 0x54, 0x196: 0x54, 0x197: 0x54, + 0x198: 0x54, 0x199: 0x54, 0x19a: 0x5e, 0x19b: 0x54, 0x19c: 0x54, 0x19d: 0x5f, 0x19e: 0x54, 0x19f: 0x60, + 0x1a4: 0x54, 0x1a5: 0x54, 0x1a6: 0x61, 0x1a7: 0x62, + 0x1a8: 0x54, 0x1a9: 0x54, 0x1aa: 0x54, 0x1ab: 0x54, 0x1ac: 0x54, 0x1ad: 0x63, 0x1ae: 0x64, 0x1af: 0x65, + 0x1b3: 0x66, 0x1b5: 0x67, 0x1b7: 0x68, + 0x1b8: 0x69, 0x1b9: 0x6a, 0x1ba: 0x6b, 0x1bb: 0x6c, 0x1bc: 0x54, 0x1bd: 0x54, 0x1be: 0x54, 0x1bf: 0x6d, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x6e, 0x1c2: 0x6f, 0x1c3: 0x70, 0x1c7: 0x71, + 0x1c8: 0x72, 0x1c9: 0x73, 0x1ca: 0x74, 0x1cb: 0x75, 0x1cd: 0x76, 0x1cf: 0x77, + // Block 0x8, offset 0x200 + 0x237: 0x54, + // Block 0x9, offset 0x240 + 0x252: 0x78, 0x253: 0x79, + 0x258: 0x7a, 0x259: 0x7b, 0x25a: 0x7c, 0x25b: 0x7d, 0x25c: 0x7e, 0x25e: 0x7f, + 0x260: 0x80, 0x261: 0x81, 0x263: 0x82, 0x264: 0x83, 0x265: 0x84, 0x266: 0x85, 0x267: 0x86, + 0x268: 0x87, 0x269: 0x88, 0x26a: 0x89, 0x26b: 0x8a, 0x26f: 0x8b, + // Block 0xa, offset 0x280 + 0x2ac: 0x8c, 0x2ad: 0x8d, 0x2ae: 0x0e, 0x2af: 0x0e, + 0x2b0: 0x0e, 0x2b1: 0x0e, 0x2b2: 0x0e, 0x2b3: 0x0e, 0x2b4: 0x8e, 0x2b5: 0x0e, 0x2b6: 0x0e, 0x2b7: 0x8f, + 0x2b8: 0x90, 0x2b9: 0x91, 0x2ba: 0x0e, 0x2bb: 0x92, 0x2bc: 0x93, 0x2bd: 0x94, 0x2bf: 0x95, + // Block 0xb, offset 0x2c0 + 0x2c4: 0x96, 0x2c5: 0x54, 0x2c6: 0x97, 0x2c7: 0x98, + 0x2cb: 0x99, 0x2cd: 0x9a, + 0x2e0: 0x9b, 0x2e1: 0x9b, 0x2e2: 0x9b, 0x2e3: 0x9b, 0x2e4: 0x9c, 0x2e5: 0x9b, 0x2e6: 0x9b, 0x2e7: 0x9b, + 0x2e8: 0x9d, 0x2e9: 0x9b, 0x2ea: 0x9b, 0x2eb: 0x9e, 0x2ec: 0x9f, 0x2ed: 0x9b, 0x2ee: 0x9b, 0x2ef: 0x9b, + 0x2f0: 0x9b, 0x2f1: 0x9b, 0x2f2: 0x9b, 0x2f3: 0x9b, 0x2f4: 0x9b, 0x2f5: 0x9b, 0x2f6: 0x9b, 0x2f7: 0x9b, + 0x2f8: 0x9b, 0x2f9: 0xa0, 0x2fa: 0x9b, 0x2fb: 0x9b, 0x2fc: 0x9b, 0x2fd: 0x9b, 0x2fe: 0x9b, 0x2ff: 0x9b, + // Block 0xc, offset 0x300 + 0x300: 0xa1, 0x301: 0xa2, 0x302: 0xa3, 0x304: 0xa4, 0x305: 0xa5, 0x306: 0xa6, 0x307: 0xa7, + 0x308: 0xa8, 0x30b: 0xa9, 0x30c: 0xaa, 0x30d: 0xab, + 0x310: 0xac, 0x311: 0xad, 0x312: 0xae, 0x313: 0xaf, 0x316: 0xb0, 0x317: 0xb1, + 0x318: 0xb2, 0x319: 0xb3, 0x31a: 0xb4, 0x31c: 0xb5, + 0x330: 0xb6, 0x332: 0xb7, + // Block 0xd, offset 0x340 + 0x36b: 0xb8, 0x36c: 0xb9, + 0x37e: 0xba, + // Block 0xe, offset 0x380 + 0x3b2: 0xbb, + // Block 0xf, offset 0x3c0 + 0x3c5: 0xbc, 0x3c6: 0xbd, + 0x3c8: 0x54, 0x3c9: 0xbe, 0x3cc: 0x54, 0x3cd: 0xbf, + 0x3db: 0xc0, 0x3dc: 0xc1, 0x3dd: 0xc2, 0x3de: 0xc3, 0x3df: 0xc4, + 0x3e8: 0xc5, 0x3e9: 0xc6, 0x3ea: 0xc7, + // Block 0x10, offset 0x400 + 0x400: 0xc8, + 0x420: 0x9b, 0x421: 0x9b, 0x422: 0x9b, 0x423: 0xc9, 0x424: 0x9b, 0x425: 0xca, 0x426: 0x9b, 0x427: 0x9b, + 0x428: 0x9b, 0x429: 0x9b, 0x42a: 0x9b, 0x42b: 0x9b, 0x42c: 0x9b, 0x42d: 0x9b, 0x42e: 0x9b, 0x42f: 0x9b, + 0x430: 0x9b, 0x431: 0x9b, 0x432: 0x9b, 0x433: 0x9b, 0x434: 0x9b, 0x435: 0x9b, 0x436: 0x9b, 0x437: 0x9b, + 0x438: 0x0e, 0x439: 0x0e, 0x43a: 0x0e, 0x43b: 0xcb, 0x43c: 0x9b, 0x43d: 0x9b, 0x43e: 0x9b, 0x43f: 0x9b, + // Block 0x11, offset 0x440 + 0x440: 0xcc, 0x441: 0x54, 0x442: 0xcd, 0x443: 0xce, 0x444: 0xcf, 0x445: 0xd0, + 0x44c: 0x54, 0x44d: 0x54, 0x44e: 0x54, 0x44f: 0x54, + 0x450: 0x54, 0x451: 0x54, 0x452: 0x54, 0x453: 0x54, 0x454: 0x54, 0x455: 0x54, 0x456: 0x54, 0x457: 0x54, + 0x458: 0x54, 0x459: 0x54, 0x45a: 0x54, 0x45b: 0xd1, 0x45c: 0x54, 0x45d: 0x6c, 0x45e: 0x54, 0x45f: 0xd2, + 0x460: 0xd3, 0x461: 0xd4, 0x462: 0xd5, 0x464: 0xd6, 0x465: 0xd7, 0x466: 0xd8, 0x467: 0x36, + 0x47f: 0xd9, + // Block 0x12, offset 0x480 + 0x4bf: 0xd9, + // Block 0x13, offset 0x4c0 + 0x4d0: 0x09, 0x4d1: 0x0a, 0x4d6: 0x0b, + 0x4db: 0x0c, 0x4dd: 0x0d, 0x4de: 0x0e, 0x4df: 0x0f, + 0x4ef: 0x10, + 0x4ff: 0x10, + // Block 0x14, offset 0x500 + 0x50f: 0x10, + 0x51f: 0x10, + 0x52f: 0x10, + 0x53f: 0x10, + // Block 0x15, offset 0x540 + 0x540: 0xda, 0x541: 0xda, 0x542: 0xda, 0x543: 0xda, 0x544: 0x05, 0x545: 0x05, 0x546: 0x05, 0x547: 0xdb, + 0x548: 0xda, 0x549: 0xda, 0x54a: 0xda, 0x54b: 0xda, 0x54c: 0xda, 0x54d: 0xda, 0x54e: 0xda, 0x54f: 0xda, + 0x550: 0xda, 0x551: 0xda, 0x552: 0xda, 0x553: 0xda, 0x554: 0xda, 0x555: 0xda, 0x556: 0xda, 0x557: 0xda, + 0x558: 0xda, 0x559: 0xda, 0x55a: 0xda, 0x55b: 0xda, 0x55c: 0xda, 0x55d: 0xda, 0x55e: 0xda, 0x55f: 0xda, + 0x560: 0xda, 0x561: 0xda, 0x562: 0xda, 0x563: 0xda, 0x564: 0xda, 0x565: 0xda, 0x566: 0xda, 0x567: 0xda, + 0x568: 0xda, 0x569: 0xda, 0x56a: 0xda, 0x56b: 0xda, 0x56c: 0xda, 0x56d: 0xda, 0x56e: 0xda, 0x56f: 0xda, + 0x570: 0xda, 0x571: 0xda, 0x572: 0xda, 0x573: 0xda, 0x574: 0xda, 0x575: 0xda, 0x576: 0xda, 0x577: 0xda, + 0x578: 0xda, 0x579: 0xda, 0x57a: 0xda, 0x57b: 0xda, 0x57c: 0xda, 0x57d: 0xda, 0x57e: 0xda, 0x57f: 0xda, + // Block 0x16, offset 0x580 + 0x58f: 0x10, + 0x59f: 0x10, + 0x5a0: 0x13, + 0x5af: 0x10, + 0x5bf: 0x10, + // Block 0x17, offset 0x5c0 + 0x5cf: 0x10, +} + +// Total table size 15800 bytes (15KiB); checksum: F50EF68C diff --git a/vendor/golang.org/x/text/unicode/bidi/tables_test.go b/vendor/golang.org/x/text/unicode/bidi/tables_test.go deleted file mode 100644 index 356a4a58d8..0000000000 --- a/vendor/golang.org/x/text/unicode/bidi/tables_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2015 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 bidi - -import ( - "testing" - - "golang.org/x/text/internal/gen" - "golang.org/x/text/internal/testtext" - "golang.org/x/text/internal/ucd" -) - -var labels = []string{ - AL: "AL", - AN: "AN", - B: "B", - BN: "BN", - CS: "CS", - EN: "EN", - ES: "ES", - ET: "ET", - L: "L", - NSM: "NSM", - ON: "ON", - R: "R", - S: "S", - WS: "WS", - - LRO: "LRO", - RLO: "RLO", - LRE: "LRE", - RLE: "RLE", - PDF: "PDF", - LRI: "LRI", - RLI: "RLI", - FSI: "FSI", - PDI: "PDI", -} - -func TestTables(t *testing.T) { - testtext.SkipIfNotLong(t) - - ucd.Parse(gen.OpenUCDFile("BidiBrackets.txt"), func(p *ucd.Parser) { - r1 := p.Rune(0) - want := p.Rune(1) - - e, _ := LookupRune(r1) - if got := e.reverseBracket(r1); got != want { - t.Errorf("Reverse(%U) = %U; want %U", r1, got, want) - } - }) - - done := map[rune]bool{} - test := func(name string, r rune, want string) { - str := string(r) - e, _ := LookupString(str) - if got := labels[e.Class()]; got != want { - t.Errorf("%s:%U: got %s; want %s", name, r, got, want) - } - if e2, sz := LookupRune(r); e != e2 || sz != len(str) { - t.Errorf("LookupRune(%U) = %v, %d; want %v, %d", r, e2, e, sz, len(str)) - } - if e2, sz := Lookup([]byte(str)); e != e2 || sz != len(str) { - t.Errorf("Lookup(%U) = %v, %d; want %v, %d", r, e2, e, sz, len(str)) - } - done[r] = true - } - - // Insert the derived BiDi properties. - ucd.Parse(gen.OpenUCDFile("extracted/DerivedBidiClass.txt"), func(p *ucd.Parser) { - r := p.Rune(0) - test("derived", r, p.String(1)) - }) - visitDefaults(func(r rune, c Class) { - if !done[r] { - test("default", r, labels[c]) - } - }) - -} diff --git a/vendor/golang.org/x/text/unicode/cldr/cldr_test.go b/vendor/golang.org/x/text/unicode/cldr/cldr_test.go deleted file mode 100644 index 951028d7e1..0000000000 --- a/vendor/golang.org/x/text/unicode/cldr/cldr_test.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2014 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 cldr - -import "testing" - -func TestParseDraft(t *testing.T) { - tests := []struct { - in string - draft Draft - err bool - }{ - {"unconfirmed", Unconfirmed, false}, - {"provisional", Provisional, false}, - {"contributed", Contributed, false}, - {"approved", Approved, false}, - {"", Approved, false}, - {"foo", Approved, true}, - } - for _, tt := range tests { - if d, err := ParseDraft(tt.in); d != tt.draft || (err != nil) != tt.err { - t.Errorf("%q: was %v, %v; want %v, %v", tt.in, d, err != nil, tt.draft, tt.err) - } - } -} diff --git a/vendor/golang.org/x/text/unicode/cldr/collate_test.go b/vendor/golang.org/x/text/unicode/cldr/collate_test.go deleted file mode 100644 index f6721639a3..0000000000 --- a/vendor/golang.org/x/text/unicode/cldr/collate_test.go +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright 2014 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 cldr - -import ( - "fmt" - "strings" - "testing" -) - -// A recorder implements the RuleProcessor interface, whereby its methods -// simply record the invocations. -type recorder struct { - calls []string -} - -func (r *recorder) Reset(anchor string, before int) error { - if before > 5 { - return fmt.Errorf("before %d > 5", before) - } - r.calls = append(r.calls, fmt.Sprintf("R:%s-%d", anchor, before)) - return nil -} - -func (r *recorder) Insert(level int, str, context, extend string) error { - s := fmt.Sprintf("O:%d:%s", level, str) - if context != "" { - s += "|" + context - } - if extend != "" { - s += "/" + extend - } - r.calls = append(r.calls, s) - return nil -} - -func (r *recorder) Index(id string) { - r.calls = append(r.calls, fmt.Sprintf("I:%s", id)) -} - -func (r *recorder) Error(err error) { - r.calls = append(r.calls, fmt.Sprintf("E:%v", err)) -} - -func TestRuleProcessor(t *testing.T) { - for _, tt := range []struct { - desc string - in string - out string - }{ - {desc: "empty"}, - {desc: "whitespace and comments only", - in: ` - - - # adsfads -# adfadf - `, - }, - { - desc: "reset anchor", - in: ` - & a - &b # - & [ before 3 ] c - & [before 4] d & ee - & [first tertiary ignorable] - &'g' - & 'h''h'h'h' - &'\u0069' # LATIN SMALL LETTER I - `, - out: ` - R:a-0 - R:b-0 - R:c-3 - R:d-4 - R:ee-0 - R:<first tertiary ignorable/>-0 - R:g-0 - R:hhhh-0 - R:i-0 - `, - }, - { - desc: "ordering", - in: ` - & 0 - < 1 <<''2# -<<< 3'3''33'3# - <<<<4 - = 5 << 6 | s - <<<< 7 / z - << 8'' | s / ch - `, - out: ` - R:0-0 - O:1:1 - O:2:'2 - O:3:33333 - O:4:4 - O:5:5 - O:2:6|s - O:4:7/z - O:2:8'|s/ch - `, - }, - { - desc: "index", - in: "< '\ufdd0'A", - out: "I:A", - }, - { - desc: "sequence", - in: ` - & 0 - <<* 1234 - <* a-cde-f - =* q-q - `, - out: ` - R:0-0 - O:2:1 - O:2:2 - O:2:3 - O:2:4 - O:1:a - O:1:b - O:1:c - O:1:d - O:1:e - O:1:f - O:5:q - `, - }, - { - desc: "compact", - in: "&B<t<<<T<s<<<S<e<<<E", - out: ` - R:B-0 - O:1:t - O:3:T - O:1:s - O:3:S - O:1:e - O:3:E - `, - }, - { - desc: "err operator", - in: "a", - out: "E:1: illegal operator 'a'", - }, - { - desc: "err line number", - in: `& a - << b - a`, - out: ` - R:a-0 - O:2:b - E:3: illegal operator 'a'`, - }, - { - desc: "err empty anchor", - in: " & ", - out: "E:1: missing string", - }, - { - desc: "err anchor invalid special 1", - in: " & [ foo ", - out: "E:1: unmatched bracket", - }, - { - desc: "err anchor invalid special 2", - in: "&[", - out: "E:1: unmatched bracket", - }, - { - desc: "err anchor invalid before 1", - in: "&[before a]", - out: `E:1: strconv.ParseUint: parsing "a": invalid syntax`, - }, - { - desc: "err anchor invalid before 2", - in: "&[before 12]", - out: `E:1: strconv.ParseUint: parsing "12": value out of range`, - }, - { - desc: "err anchor invalid before 3", - in: "&[before 2]", - out: "E:1: missing string", - }, - { - desc: "err anchor invalid before 4", - in: "&[before 6] a", - out: "E:1: before 6 > 5", - }, - { - desc: "err empty order", - in: " < ", - out: "E:1: missing string", - }, - { - desc: "err empty identity", - in: " = ", - out: "E:1: missing string", - }, - { - desc: "err empty context", - in: " < a | ", - out: "E:1: missing string after context", - }, - { - desc: "err empty extend", - in: " < a / ", - out: "E:1: missing string after extension", - }, - { - desc: "err empty sequence", - in: " <* ", - out: "E:1: empty sequence", - }, - { - desc: "err sequence 1", - in: " <* -a", - out: "E:1: range without starter value", - }, - { - desc: "err sequence 3", - in: " <* a-a-b", - out: `O:1:a - E:1: range without starter value - `, - }, - { - desc: "err sequence 3", - in: " <* b-a", - out: `O:1:b - E:1: invalid range 'b'-'a' - `, - }, - { - desc: "err unmatched quote", - in: " < 'b", - out: ` E:1: unmatched single quote - `, - }, - } { - rec := &recorder{} - err := Collation{ - Cr: []*Common{ - {hidden: hidden{CharData: tt.in}}, - }, - }.Process(rec) - if err != nil { - rec.Error(err) - } - got := rec.calls - want := strings.Split(strings.TrimSpace(tt.out), "\n") - if tt.out == "" { - want = nil - } - if len(got) != len(want) { - t.Errorf("%s: nResults: got %d; want %d", tt.desc, len(got), len(want)) - continue - } - for i, g := range got { - if want := strings.TrimSpace(want[i]); g != want { - t.Errorf("%s:%d: got %q; want %q", tt.desc, i, g, want) - } - } - } -} diff --git a/vendor/golang.org/x/text/unicode/cldr/data_test.go b/vendor/golang.org/x/text/unicode/cldr/data_test.go deleted file mode 100644 index 1662189627..0000000000 --- a/vendor/golang.org/x/text/unicode/cldr/data_test.go +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright 2013 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 cldr - -// This file contains test data. - -import ( - "io" - "strings" -) - -type testLoader struct { -} - -func (t testLoader) Len() int { - return len(testFiles) -} - -func (t testLoader) Path(i int) string { - return testPaths[i] -} - -func (t testLoader) Reader(i int) (io.ReadCloser, error) { - return &reader{*strings.NewReader(testFiles[i])}, nil -} - -// reader adds a dummy Close method to strings.Reader so that it -// satisfies the io.ReadCloser interface. -type reader struct { - strings.Reader -} - -func (r reader) Close() error { - return nil -} - -var ( - testFiles = []string{de_xml, gsw_xml, root_xml} - testPaths = []string{ - "common/main/de.xml", - "common/main/gsw.xml", - "common/main/root.xml", - } -) - -var root_xml = `<?xml version="1.0" encoding="UTF-8" ?> -<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd"> -<ldml> - <identity> - <language type="root"/> - <generation date="now"/> - </identity> - <characters> - <exemplarCharacters>[]</exemplarCharacters> - <exemplarCharacters type="auxiliary">[]</exemplarCharacters> - <exemplarCharacters type="punctuation">[\- ‐ – — … ' ‘ ‚ &quot; “ „ \&amp; #]</exemplarCharacters> - <ellipsis type="final">{0}…</ellipsis> - <ellipsis type="initial">…{0}</ellipsis> - <moreInformation>?</moreInformation> - </characters> - <dates> - <calendars> - <default choice="gregorian"/> - <calendar type="buddhist"> - <months> - <alias source="locale" path="../../calendar[@type='gregorian']/months"/> - </months> - </calendar> - <calendar type="chinese"> - <months> - <alias source="locale" path="../../calendar[@type='gregorian']/months"/> - </months> - </calendar> - <calendar type="gregorian"> - <months> - <default choice="format"/> - <monthContext type="format"> - <default choice="wide"/> - <monthWidth type="narrow"> - <alias source="locale" path="../../monthContext[@type='stand-alone']/monthWidth[@type='narrow']"/> - </monthWidth> - <monthWidth type="wide"> - <month type="1">11</month> - <month type="2">22</month> - <month type="3">33</month> - <month type="4">44</month> - </monthWidth> - </monthContext> - <monthContext type="stand-alone"> - <monthWidth type="narrow"> - <month type="1">1</month> - <month type="2">2</month> - <month type="3">3</month> - <month type="4">4</month> - </monthWidth> - <monthWidth type="wide"> - <alias source="locale" path="../../monthContext[@type='format']/monthWidth[@type='wide']"/> - </monthWidth> - </monthContext> - </months> - </calendar> - </calendars> - </dates> -</ldml> -` - -var de_xml = `<?xml version="1.0" encoding="UTF-8" ?> -<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd"> -<ldml> - <identity> - <language type="de"/> - </identity> - <characters> - <exemplarCharacters>[a ä b c d e ö p q r s ß t u ü v w x y z]</exemplarCharacters> - <exemplarCharacters type="auxiliary">[á à ă]</exemplarCharacters> - <exemplarCharacters type="index">[A B C D E F G H Z]</exemplarCharacters> - <ellipsis type="final">{0} …</ellipsis> - <ellipsis type="initial">… {0}</ellipsis> - <moreInformation>?</moreInformation> - <stopwords> - <stopwordList type="collation" draft="provisional">der die das</stopwordList> - </stopwords> - </characters> - <dates> - <calendars> - <calendar type="buddhist"> - <months> - <monthContext type="format"> - <monthWidth type="narrow"> - <month type="3">BBB</month> - </monthWidth> - <monthWidth type="wide"> - <month type="3">bbb</month> - </monthWidth> - </monthContext> - </months> - </calendar> - <calendar type="gregorian"> - <months> - <monthContext type="format"> - <monthWidth type="narrow"> - <month type="3">M</month> - <month type="4">A</month> - </monthWidth> - <monthWidth type="wide"> - <month type="3">Maerz</month> - <month type="4">April</month> - <month type="5">Mai</month> - </monthWidth> - </monthContext> - <monthContext type="stand-alone"> - <monthWidth type="narrow"> - <month type="3">m</month> - <month type="5">m</month> - </monthWidth> - <monthWidth type="wide"> - <month type="4">april</month> - <month type="5">mai</month> - </monthWidth> - </monthContext> - </months> - </calendar> - </calendars> - </dates> - <posix> - <messages> - <yesstr>yes:y</yesstr> - <nostr>no:n</nostr> - </messages> - </posix> -</ldml> -` - -var gsw_xml = `<?xml version="1.0" encoding="UTF-8" ?> -<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd"> -<ldml> - <identity> - <language type="gsw"/> - </identity> - <posix> - <alias source="de" path="//ldml/posix"/> - </posix> -</ldml> -` diff --git a/vendor/golang.org/x/text/unicode/cldr/examples_test.go b/vendor/golang.org/x/text/unicode/cldr/examples_test.go deleted file mode 100644 index 1a69b00738..0000000000 --- a/vendor/golang.org/x/text/unicode/cldr/examples_test.go +++ /dev/null @@ -1,21 +0,0 @@ -package cldr_test - -import ( - "fmt" - - "golang.org/x/text/unicode/cldr" -) - -func ExampleSlice() { - var dr *cldr.CLDR // assume this is initialized - - x, _ := dr.LDML("en") - cs := x.Collations.Collation - // remove all but the default - cldr.MakeSlice(&cs).Filter(func(e cldr.Elem) bool { - return e.GetCommon().Type != x.Collations.Default() - }) - for i, c := range cs { - fmt.Println(i, c.Type) - } -} diff --git a/vendor/golang.org/x/text/unicode/cldr/resolve_test.go b/vendor/golang.org/x/text/unicode/cldr/resolve_test.go deleted file mode 100644 index 3d8edaec85..0000000000 --- a/vendor/golang.org/x/text/unicode/cldr/resolve_test.go +++ /dev/null @@ -1,368 +0,0 @@ -package cldr - -import ( - "fmt" - "log" - "reflect" - "testing" -) - -func failOnError(err error) { - if err != nil { - log.Panic(err) - } -} - -func data() *CLDR { - d := Decoder{} - data, err := d.Decode(testLoader{}) - failOnError(err) - return data -} - -type h struct { - A string `xml:"ha,attr"` - E string `xml:"he"` - D string `xml:",chardata"` - X string -} - -type fieldTest struct { - Common - To string `xml:"to,attr"` - Key string `xml:"key,attr"` - E string `xml:"e"` - D string `xml:",chardata"` - X string - h -} - -var testStruct = fieldTest{ - Common: Common{ - name: "mapping", // exclude "type" as distinguishing attribute - Type: "foo", - Alt: "foo", - }, - To: "nyc", - Key: "k", - E: "E", - D: "D", - h: h{ - A: "A", - E: "E", - D: "D", - }, -} - -func TestIter(t *testing.T) { - tests := map[string]string{ - "Type": "foo", - "Alt": "foo", - "To": "nyc", - "A": "A", - "Alias": "<nil>", - } - k := 0 - for i := iter(reflect.ValueOf(testStruct)); !i.done(); i.next() { - v := i.value() - if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.String { - v = v.Elem() - } - name := i.field().Name - if w, ok := tests[name]; ok { - s := fmt.Sprint(v.Interface()) - if w != s { - t.Errorf("value: found %q; want %q", w, s) - } - delete(tests, name) - } - k++ - } - if len(tests) != 0 { - t.Errorf("missing fields: %v", tests) - } -} - -func TestFindField(t *testing.T) { - tests := []struct { - name, val string - exist bool - }{ - {"type", "foo", true}, - {"alt", "foo", true}, - {"to", "nyc", true}, - {"he", "E", true}, - {"q", "", false}, - } - vf := reflect.ValueOf(testStruct) - for i, tt := range tests { - v, err := findField(vf, tt.name) - if (err == nil) != tt.exist { - t.Errorf("%d: field %q present is %v; want %v", i, tt.name, err == nil, tt.exist) - } else if tt.exist { - if v.Kind() == reflect.Ptr { - if v.IsNil() { - continue - } - v = v.Elem() - } - if v.String() != tt.val { - t.Errorf("%d: found value %q; want %q", i, v.String(), tt.val) - } - } - } -} - -var keyTests = []struct { - exclude []string - key string -}{ - {[]string{}, "alt=foo;key=k;to=nyc"}, - {[]string{"type"}, "alt=foo;key=k;to=nyc"}, - {[]string{"choice"}, "alt=foo;key=k;to=nyc"}, - {[]string{"alt"}, "key=k;to=nyc"}, - {[]string{"a"}, "alt=foo;key=k;to=nyc"}, - {[]string{"to"}, "alt=foo;key=k"}, - {[]string{"alt", "to"}, "key=k"}, - {[]string{"alt", "to", "key"}, ""}, -} - -func TestAttrKey(t *testing.T) { - v := reflect.ValueOf(&testStruct) - for i, tt := range keyTests { - key := attrKey(v, tt.exclude...) - if key != tt.key { - t.Errorf("%d: found %q, want %q", i, key, tt.key) - } - } -} - -func TestKey(t *testing.T) { - for i, tt := range keyTests { - key := Key(&testStruct, tt.exclude...) - if key != tt.key { - t.Errorf("%d: found %q, want %q", i, key, tt.key) - } - } -} - -func testEnclosing(t *testing.T, x *LDML, name string) { - eq := func(a, b Elem, i int) { - for ; i > 0; i-- { - b = b.enclosing() - } - if a != b { - t.Errorf("%s: found path %q, want %q", name, getPath(a), getPath(b)) - } - } - eq(x, x, 0) - eq(x, x.Identity, 1) - eq(x, x.Dates.Calendars, 2) - eq(x, x.Dates.Calendars.Calendar[0], 3) - eq(x, x.Dates.Calendars.Calendar[1], 3) - //eq(x, x.Dates.Calendars.Calendar[0].Months, 4) - eq(x, x.Dates.Calendars.Calendar[1].Months, 4) -} - -func TestEnclosing(t *testing.T) { - testEnclosing(t, data().RawLDML("de"), "enclosing-raw") - de, _ := data().LDML("de") - testEnclosing(t, de, "enclosing") -} - -func TestDeepCopy(t *testing.T) { - eq := func(have, want string) { - if have != want { - t.Errorf("found %q; want %q", have, want) - } - } - x, _ := data().LDML("de") - vc := deepCopy(reflect.ValueOf(x)) - c := vc.Interface().(*LDML) - linkEnclosing(nil, c) - if x == c { - t.Errorf("did not copy") - } - - eq(c.name, "ldml") - eq(c.Dates.name, "dates") - testEnclosing(t, c, "deepCopy") -} - -type getTest struct { - loc string - path string - field string // used in combination with length - data string - altData string // used for buddhist calendar if value != "" - typ string - length int - missing bool -} - -const ( - budMon = "dates/calendars/calendar[@type='buddhist']/months/" - chnMon = "dates/calendars/calendar[@type='chinese']/months/" - greMon = "dates/calendars/calendar[@type='gregorian']/months/" -) - -func monthVal(path, context, width string, month int) string { - const format = "%s/monthContext[@type='%s']/monthWidth[@type='%s']/month[@type='%d']" - return fmt.Sprintf(format, path, context, width, month) -} - -var rootGetTests = []getTest{ - {loc: "root", path: "identity/language", typ: "root"}, - {loc: "root", path: "characters/moreInformation", data: "?"}, - {loc: "root", path: "characters", field: "exemplarCharacters", length: 3}, - {loc: "root", path: greMon, field: "monthContext", length: 2}, - {loc: "root", path: greMon + "monthContext[@type='format']/monthWidth[@type='narrow']", field: "month", length: 4}, - {loc: "root", path: greMon + "monthContext[@type='stand-alone']/monthWidth[@type='wide']", field: "month", length: 4}, - // unescaping character data - {loc: "root", path: "characters/exemplarCharacters[@type='punctuation']", data: `[\- ‐ – — … ' ‘ ‚ " “ „ \& #]`}, - // default resolution - {loc: "root", path: "dates/calendars/calendar", typ: "gregorian"}, - // alias resolution - {loc: "root", path: budMon, field: "monthContext", length: 2}, - // crossing but non-circular alias resolution - {loc: "root", path: budMon + "monthContext[@type='format']/monthWidth[@type='narrow']", field: "month", length: 4}, - {loc: "root", path: budMon + "monthContext[@type='stand-alone']/monthWidth[@type='wide']", field: "month", length: 4}, - {loc: "root", path: monthVal(greMon, "format", "wide", 1), data: "11"}, - {loc: "root", path: monthVal(greMon, "format", "narrow", 2), data: "2"}, - {loc: "root", path: monthVal(greMon, "stand-alone", "wide", 3), data: "33"}, - {loc: "root", path: monthVal(greMon, "stand-alone", "narrow", 4), data: "4"}, - {loc: "root", path: monthVal(budMon, "format", "wide", 1), data: "11"}, - {loc: "root", path: monthVal(budMon, "format", "narrow", 2), data: "2"}, - {loc: "root", path: monthVal(budMon, "stand-alone", "wide", 3), data: "33"}, - {loc: "root", path: monthVal(budMon, "stand-alone", "narrow", 4), data: "4"}, -} - -// 19 -var deGetTests = []getTest{ - {loc: "de", path: "identity/language", typ: "de"}, - {loc: "de", path: "posix", length: 2}, - {loc: "de", path: "characters", field: "exemplarCharacters", length: 4}, - {loc: "de", path: "characters/exemplarCharacters[@type='auxiliary']", data: `[á à ă]`}, - // identity is a blocking element, so de should not inherit generation from root. - {loc: "de", path: "identity/generation", missing: true}, - // default resolution - {loc: "root", path: "dates/calendars/calendar", typ: "gregorian"}, - - // absolute path alias resolution - {loc: "gsw", path: "posix", field: "messages", length: 1}, - {loc: "gsw", path: "posix/messages/yesstr", data: "yes:y"}, -} - -// 27(greMon) - 52(budMon) - 77(chnMon) -func calGetTests(s string) []getTest { - tests := []getTest{ - {loc: "de", path: s, length: 2}, - {loc: "de", path: s + "monthContext[@type='format']/monthWidth[@type='wide']", field: "month", length: 5}, - {loc: "de", path: monthVal(s, "format", "wide", 1), data: "11"}, - {loc: "de", path: monthVal(s, "format", "wide", 2), data: "22"}, - {loc: "de", path: monthVal(s, "format", "wide", 3), data: "Maerz", altData: "bbb"}, - {loc: "de", path: monthVal(s, "format", "wide", 4), data: "April"}, - {loc: "de", path: monthVal(s, "format", "wide", 5), data: "Mai"}, - - {loc: "de", path: s + "monthContext[@type='format']/monthWidth[@type='narrow']", field: "month", length: 5}, - {loc: "de", path: monthVal(s, "format", "narrow", 1), data: "1"}, - {loc: "de", path: monthVal(s, "format", "narrow", 2), data: "2"}, - {loc: "de", path: monthVal(s, "format", "narrow", 3), data: "M", altData: "BBB"}, - {loc: "de", path: monthVal(s, "format", "narrow", 4), data: "A"}, - {loc: "de", path: monthVal(s, "format", "narrow", 5), data: "m"}, - - {loc: "de", path: s + "monthContext[@type='stand-alone']/monthWidth[@type='wide']", field: "month", length: 5}, - {loc: "de", path: monthVal(s, "stand-alone", "wide", 1), data: "11"}, - {loc: "de", path: monthVal(s, "stand-alone", "wide", 2), data: "22"}, - {loc: "de", path: monthVal(s, "stand-alone", "wide", 3), data: "Maerz", altData: "bbb"}, - {loc: "de", path: monthVal(s, "stand-alone", "wide", 4), data: "april"}, - {loc: "de", path: monthVal(s, "stand-alone", "wide", 5), data: "mai"}, - - {loc: "de", path: s + "monthContext[@type='stand-alone']/monthWidth[@type='narrow']", field: "month", length: 5}, - {loc: "de", path: monthVal(s, "stand-alone", "narrow", 1), data: "1"}, - {loc: "de", path: monthVal(s, "stand-alone", "narrow", 2), data: "2"}, - {loc: "de", path: monthVal(s, "stand-alone", "narrow", 3), data: "m"}, - {loc: "de", path: monthVal(s, "stand-alone", "narrow", 4), data: "4"}, - {loc: "de", path: monthVal(s, "stand-alone", "narrow", 5), data: "m"}, - } - if s == budMon { - for i, t := range tests { - if t.altData != "" { - tests[i].data = t.altData - } - } - } - return tests -} - -var getTests = append(rootGetTests, - append(deGetTests, - append(calGetTests(greMon), - append(calGetTests(budMon), - calGetTests(chnMon)...)...)...)...) - -func TestPath(t *testing.T) { - d := data() - for i, tt := range getTests { - x, _ := d.LDML(tt.loc) - e, err := walkXPath(x, tt.path) - if err != nil { - if !tt.missing { - t.Errorf("%d:error: %v %v", i, err, tt.missing) - } - continue - } - if tt.missing { - t.Errorf("%d: missing is %v; want %v", i, e == nil, tt.missing) - continue - } - if tt.data != "" && e.GetCommon().Data() != tt.data { - t.Errorf("%d: data is %v; want %v", i, e.GetCommon().Data(), tt.data) - continue - } - if tt.typ != "" && e.GetCommon().Type != tt.typ { - t.Errorf("%d: type is %v; want %v", i, e.GetCommon().Type, tt.typ) - continue - } - if tt.field != "" { - slice, _ := findField(reflect.ValueOf(e), tt.field) - if slice.Len() != tt.length { - t.Errorf("%d: length is %v; want %v", i, slice.Len(), tt.length) - continue - } - } - } -} - -func TestGet(t *testing.T) { - d := data() - for i, tt := range getTests { - x, _ := d.LDML(tt.loc) - e, err := Get(x, tt.path) - if err != nil { - if !tt.missing { - t.Errorf("%d:error: %v %v", i, err, tt.missing) - } - continue - } - if tt.missing { - t.Errorf("%d: missing is %v; want %v", i, e == nil, tt.missing) - continue - } - if tt.data != "" && e.GetCommon().Data() != tt.data { - t.Errorf("%d: data is %v; want %v", i, e.GetCommon().Data(), tt.data) - continue - } - if tt.typ != "" && e.GetCommon().Type != tt.typ { - t.Errorf("%d: type is %v; want %v", i, e.GetCommon().Type, tt.typ) - continue - } - if tt.field != "" { - slice, _ := findField(reflect.ValueOf(e), tt.field) - if slice.Len() != tt.length { - t.Errorf("%d: length is %v; want %v", i, slice.Len(), tt.length) - continue - } - } - } -} diff --git a/vendor/golang.org/x/text/unicode/cldr/slice_test.go b/vendor/golang.org/x/text/unicode/cldr/slice_test.go deleted file mode 100644 index 3d487d3bd1..0000000000 --- a/vendor/golang.org/x/text/unicode/cldr/slice_test.go +++ /dev/null @@ -1,175 +0,0 @@ -// Copyright 2013 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 cldr - -import ( - "reflect" - "testing" -) - -type testSlice []*Common - -func mkElem(alt, typ, ref string) *Common { - return &Common{ - Type: typ, - Reference: ref, - Alt: alt, - } -} - -var ( - testSlice1 = testSlice{ - mkElem("1", "a", "i.a"), - mkElem("1", "b", "i.b"), - mkElem("1", "c", "i.c"), - mkElem("2", "b", "ii"), - mkElem("3", "c", "iii"), - mkElem("4", "a", "iv.a"), - mkElem("4", "d", "iv.d"), - } - testSliceE = testSlice{} -) - -func panics(f func()) (panics bool) { - defer func() { - if err := recover(); err != nil { - panics = true - } - }() - f() - return panics -} - -func TestMakeSlice(t *testing.T) { - foo := 1 - bar := []int{} - tests := []struct { - i interface{} - panics bool - err string - }{ - {&foo, true, "should panic when passed a pointer to the wrong type"}, - {&bar, true, "should panic when slice element of the wrong type"}, - {testSlice1, true, "should panic when passed a slice"}, - {&testSlice1, false, "should not panic"}, - } - for i, tt := range tests { - if panics(func() { MakeSlice(tt.i) }) != tt.panics { - t.Errorf("%d: %s", i, tt.err) - } - } -} - -var anyOfTests = []struct { - sl testSlice - values []string - n int -}{ - {testSliceE, []string{}, 0}, - {testSliceE, []string{"1", "2", "3"}, 0}, - {testSlice1, []string{}, 0}, - {testSlice1, []string{"1"}, 3}, - {testSlice1, []string{"2"}, 1}, - {testSlice1, []string{"5"}, 0}, - {testSlice1, []string{"1", "2", "3"}, 5}, -} - -func TestSelectAnyOf(t *testing.T) { - for i, tt := range anyOfTests { - sl := tt.sl - s := MakeSlice(&sl) - s.SelectAnyOf("alt", tt.values...) - if len(sl) != tt.n { - t.Errorf("%d: found len == %d; want %d", i, len(sl), tt.n) - } - } - sl := testSlice1 - s := MakeSlice(&sl) - if !panics(func() { s.SelectAnyOf("foo") }) { - t.Errorf("should panic on non-existing attribute") - } -} - -func TestFilter(t *testing.T) { - for i, tt := range anyOfTests { - sl := tt.sl - s := MakeSlice(&sl) - s.Filter(func(e Elem) bool { - v, _ := findField(reflect.ValueOf(e), "alt") - return in(tt.values, v.String()) - }) - if len(sl) != tt.n { - t.Errorf("%d: found len == %d; want %d", i, len(sl), tt.n) - } - } -} - -func TestGroup(t *testing.T) { - f := func(excl ...string) func(Elem) string { - return func(e Elem) string { - return Key(e, excl...) - } - } - tests := []struct { - sl testSlice - f func(Elem) string - lens []int - }{ - {testSliceE, f(), []int{}}, - {testSlice1, f(), []int{1, 1, 1, 1, 1, 1, 1}}, - {testSlice1, f("type"), []int{3, 1, 1, 2}}, - {testSlice1, f("alt"), []int{2, 2, 2, 1}}, - {testSlice1, f("alt", "type"), []int{7}}, - {testSlice1, f("alt", "type"), []int{7}}, - } - for i, tt := range tests { - sl := tt.sl - s := MakeSlice(&sl) - g := s.Group(tt.f) - if len(tt.lens) != len(g) { - t.Errorf("%d: found %d; want %d", i, len(g), len(tt.lens)) - continue - } - for j, v := range tt.lens { - if n := g[j].Value().Len(); n != v { - t.Errorf("%d: found %d for length of group %d; want %d", i, n, j, v) - } - } - } -} - -func TestSelectOnePerGroup(t *testing.T) { - tests := []struct { - sl testSlice - attr string - values []string - refs []string - }{ - {testSliceE, "alt", []string{"1"}, []string{}}, - {testSliceE, "type", []string{"a"}, []string{}}, - {testSlice1, "alt", []string{"2", "3", "1"}, []string{"i.a", "ii", "iii"}}, - {testSlice1, "alt", []string{"1", "4"}, []string{"i.a", "i.b", "i.c", "iv.d"}}, - {testSlice1, "type", []string{"c", "d"}, []string{"i.c", "iii", "iv.d"}}, - } - for i, tt := range tests { - sl := tt.sl - s := MakeSlice(&sl) - s.SelectOnePerGroup(tt.attr, tt.values) - if len(sl) != len(tt.refs) { - t.Errorf("%d: found result length %d; want %d", i, len(sl), len(tt.refs)) - continue - } - for j, e := range sl { - if tt.refs[j] != e.Reference { - t.Errorf("%d:%d found %s; want %s", i, j, e.Reference, tt.refs[i]) - } - } - } - sl := testSlice1 - s := MakeSlice(&sl) - if !panics(func() { s.SelectOnePerGroup("foo", nil) }) { - t.Errorf("should panic on non-existing attribute") - } -} diff --git a/vendor/golang.org/x/text/unicode/cldr/xml.go b/vendor/golang.org/x/text/unicode/cldr/xml.go index ce3203827e..f847663b14 100644 --- a/vendor/golang.org/x/text/unicode/cldr/xml.go +++ b/vendor/golang.org/x/text/unicode/cldr/xml.go @@ -636,6 +636,13 @@ type SupplementalData struct { Path string `xml:"path,attr"` } `xml:"rgPath"` } `xml:"rgScope"` + LanguageGroups *struct { + Common + LanguageGroup []*struct { + Common + Parent string `xml:"parent,attr"` + } `xml:"languageGroup"` + } `xml:"languageGroups"` } // LDML is the top-level type for locale-specific data. @@ -1484,4 +1491,4 @@ type Numbers struct { } // Version is the version of CLDR from which the XML definitions are generated. -const Version = "31" +const Version = "32" diff --git a/vendor/golang.org/x/text/unicode/norm/composition_test.go b/vendor/golang.org/x/text/unicode/norm/composition_test.go deleted file mode 100644 index 11684069d3..0000000000 --- a/vendor/golang.org/x/text/unicode/norm/composition_test.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2011 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 norm - -import "testing" - -// TestCase is used for most tests. -type TestCase struct { - in []rune - out []rune -} - -func runTests(t *testing.T, name string, fm Form, tests []TestCase) { - rb := reorderBuffer{} - rb.init(fm, nil) - for i, test := range tests { - rb.setFlusher(nil, appendFlush) - for j, rune := range test.in { - b := []byte(string(rune)) - src := inputBytes(b) - info := rb.f.info(src, 0) - if j == 0 { - rb.ss.first(info) - } else { - rb.ss.next(info) - } - if rb.insertFlush(src, 0, info) < 0 { - t.Errorf("%s:%d: insert failed for rune %d", name, i, j) - } - } - rb.doFlush() - was := string(rb.out) - want := string(test.out) - if len(was) != len(want) { - t.Errorf("%s:%d: length = %d; want %d", name, i, len(was), len(want)) - } - if was != want { - k, pfx := pidx(was, want) - t.Errorf("%s:%d: \nwas %s%+q; \nwant %s%+q", name, i, pfx, was[k:], pfx, want[k:]) - } - } -} - -func TestFlush(t *testing.T) { - const ( - hello = "Hello " - world = "world!" - ) - buf := make([]byte, maxByteBufferSize) - p := copy(buf, hello) - out := buf[p:] - rb := reorderBuffer{} - rb.initString(NFC, world) - if i := rb.flushCopy(out); i != 0 { - t.Errorf("wrote bytes on flush of empty buffer. (len(out) = %d)", i) - } - - for i := range world { - // No need to set streamSafe values for this test. - rb.insertFlush(rb.src, i, rb.f.info(rb.src, i)) - n := rb.flushCopy(out) - out = out[n:] - p += n - } - - was := buf[:p] - want := hello + world - if string(was) != want { - t.Errorf(`output after flush was "%s"; want "%s"`, string(was), want) - } - if rb.nrune != 0 { - t.Errorf("non-null size of info buffer (rb.nrune == %d)", rb.nrune) - } - if rb.nbyte != 0 { - t.Errorf("non-null size of byte buffer (rb.nbyte == %d)", rb.nbyte) - } -} - -var insertTests = []TestCase{ - {[]rune{'a'}, []rune{'a'}}, - {[]rune{0x300}, []rune{0x300}}, - {[]rune{0x300, 0x316}, []rune{0x316, 0x300}}, // CCC(0x300)==230; CCC(0x316)==220 - {[]rune{0x316, 0x300}, []rune{0x316, 0x300}}, - {[]rune{0x41, 0x316, 0x300}, []rune{0x41, 0x316, 0x300}}, - {[]rune{0x41, 0x300, 0x316}, []rune{0x41, 0x316, 0x300}}, - {[]rune{0x300, 0x316, 0x41}, []rune{0x316, 0x300, 0x41}}, - {[]rune{0x41, 0x300, 0x40, 0x316}, []rune{0x41, 0x300, 0x40, 0x316}}, -} - -func TestInsert(t *testing.T) { - runTests(t, "TestInsert", NFD, insertTests) -} - -var decompositionNFDTest = []TestCase{ - {[]rune{0xC0}, []rune{0x41, 0x300}}, - {[]rune{0xAC00}, []rune{0x1100, 0x1161}}, - {[]rune{0x01C4}, []rune{0x01C4}}, - {[]rune{0x320E}, []rune{0x320E}}, - {[]rune("음ẻ과"), []rune{0x110B, 0x1173, 0x11B7, 0x65, 0x309, 0x1100, 0x116A}}, -} - -var decompositionNFKDTest = []TestCase{ - {[]rune{0xC0}, []rune{0x41, 0x300}}, - {[]rune{0xAC00}, []rune{0x1100, 0x1161}}, - {[]rune{0x01C4}, []rune{0x44, 0x5A, 0x030C}}, - {[]rune{0x320E}, []rune{0x28, 0x1100, 0x1161, 0x29}}, -} - -func TestDecomposition(t *testing.T) { - runTests(t, "TestDecompositionNFD", NFD, decompositionNFDTest) - runTests(t, "TestDecompositionNFKD", NFKD, decompositionNFKDTest) -} - -var compositionTest = []TestCase{ - {[]rune{0x41, 0x300}, []rune{0xC0}}, - {[]rune{0x41, 0x316}, []rune{0x41, 0x316}}, - {[]rune{0x41, 0x300, 0x35D}, []rune{0xC0, 0x35D}}, - {[]rune{0x41, 0x316, 0x300}, []rune{0xC0, 0x316}}, - // blocking starter - {[]rune{0x41, 0x316, 0x40, 0x300}, []rune{0x41, 0x316, 0x40, 0x300}}, - {[]rune{0x1100, 0x1161}, []rune{0xAC00}}, - // parenthesized Hangul, alternate between ASCII and Hangul. - {[]rune{0x28, 0x1100, 0x1161, 0x29}, []rune{0x28, 0xAC00, 0x29}}, -} - -func TestComposition(t *testing.T) { - runTests(t, "TestComposition", NFC, compositionTest) -} diff --git a/vendor/golang.org/x/text/unicode/norm/example_iter_test.go b/vendor/golang.org/x/text/unicode/norm/example_iter_test.go deleted file mode 100644 index 82df89c7bf..0000000000 --- a/vendor/golang.org/x/text/unicode/norm/example_iter_test.go +++ /dev/null @@ -1,82 +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 norm_test - -import ( - "bytes" - "fmt" - "unicode/utf8" - - "golang.org/x/text/unicode/norm" -) - -// EqualSimple uses a norm.Iter to compare two non-normalized -// strings for equivalence. -func EqualSimple(a, b string) bool { - var ia, ib norm.Iter - ia.InitString(norm.NFKD, a) - ib.InitString(norm.NFKD, b) - for !ia.Done() && !ib.Done() { - if !bytes.Equal(ia.Next(), ib.Next()) { - return false - } - } - return ia.Done() && ib.Done() -} - -// FindPrefix finds the longest common prefix of ASCII characters -// of a and b. -func FindPrefix(a, b string) int { - i := 0 - for ; i < len(a) && i < len(b) && a[i] < utf8.RuneSelf && a[i] == b[i]; i++ { - } - return i -} - -// EqualOpt is like EqualSimple, but optimizes the special -// case for ASCII characters. -func EqualOpt(a, b string) bool { - n := FindPrefix(a, b) - a, b = a[n:], b[n:] - var ia, ib norm.Iter - ia.InitString(norm.NFKD, a) - ib.InitString(norm.NFKD, b) - for !ia.Done() && !ib.Done() { - if !bytes.Equal(ia.Next(), ib.Next()) { - return false - } - if n := int64(FindPrefix(a[ia.Pos():], b[ib.Pos():])); n != 0 { - ia.Seek(n, 1) - ib.Seek(n, 1) - } - } - return ia.Done() && ib.Done() -} - -var compareTests = []struct{ a, b string }{ - {"aaa", "aaa"}, - {"aaa", "aab"}, - {"a\u0300a", "\u00E0a"}, - {"a\u0300\u0320b", "a\u0320\u0300b"}, - {"\u1E0A\u0323", "\x44\u0323\u0307"}, - // A character that decomposes into multiple segments - // spans several iterations. - {"\u3304", "\u30A4\u30CB\u30F3\u30AF\u3099"}, -} - -func ExampleIter() { - for i, t := range compareTests { - r0 := EqualSimple(t.a, t.b) - r1 := EqualOpt(t.a, t.b) - fmt.Printf("%d: %v %v\n", i, r0, r1) - } - // Output: - // 0: true true - // 1: false false - // 2: true true - // 3: true true - // 4: true true - // 5: true true -} diff --git a/vendor/golang.org/x/text/unicode/norm/example_test.go b/vendor/golang.org/x/text/unicode/norm/example_test.go deleted file mode 100644 index 8f3b15653c..0000000000 --- a/vendor/golang.org/x/text/unicode/norm/example_test.go +++ /dev/null @@ -1,27 +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 norm_test - -import ( - "fmt" - - "golang.org/x/text/unicode/norm" -) - -func ExampleForm_NextBoundary() { - s := norm.NFD.String("Mêlée") - - for i := 0; i < len(s); { - d := norm.NFC.NextBoundaryInString(s[i:], true) - fmt.Printf("%[1]s: %+[1]q\n", s[i:i+d]) - i += d - } - // Output: - // M: "M" - // ê: "e\u0302" - // l: "l" - // é: "e\u0301" - // e: "e" -} diff --git a/vendor/golang.org/x/text/unicode/norm/forminfo_test.go b/vendor/golang.org/x/text/unicode/norm/forminfo_test.go deleted file mode 100644 index e15ba9bee6..0000000000 --- a/vendor/golang.org/x/text/unicode/norm/forminfo_test.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2013 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 test - -package norm - -import "testing" - -func TestProperties(t *testing.T) { - var d runeData - CK := [2]string{"C", "K"} - for k, r := 1, rune(0); r < 0x2ffff; r++ { - if k < len(testData) && r == testData[k].r { - d = testData[k] - k++ - } - s := string(r) - for j, p := range []Properties{NFC.PropertiesString(s), NFKC.PropertiesString(s)} { - f := d.f[j] - if p.CCC() != d.ccc { - t.Errorf("%U: ccc(%s): was %d; want %d %X", r, CK[j], p.CCC(), d.ccc, p.index) - } - if p.isYesC() != (f.qc == Yes) { - t.Errorf("%U: YesC(%s): was %v; want %v", r, CK[j], p.isYesC(), f.qc == Yes) - } - if p.combinesBackward() != (f.qc == Maybe) { - t.Errorf("%U: combines backwards(%s): was %v; want %v", r, CK[j], p.combinesBackward(), f.qc == Maybe) - } - if p.nLeadingNonStarters() != d.nLead { - t.Errorf("%U: nLead(%s): was %d; want %d %#v %#v", r, CK[j], p.nLeadingNonStarters(), d.nLead, p, d) - } - if p.nTrailingNonStarters() != d.nTrail { - t.Errorf("%U: nTrail(%s): was %d; want %d %#v %#v", r, CK[j], p.nTrailingNonStarters(), d.nTrail, p, d) - } - if p.combinesForward() != f.combinesForward { - t.Errorf("%U: combines forward(%s): was %v; want %v %#v", r, CK[j], p.combinesForward(), f.combinesForward, p) - } - // Skip Hangul as it is algorithmically computed. - if r >= hangulBase && r < hangulEnd { - continue - } - if p.hasDecomposition() { - if has := f.decomposition != ""; !has { - t.Errorf("%U: hasDecomposition(%s): was %v; want %v", r, CK[j], p.hasDecomposition(), has) - } - if string(p.Decomposition()) != f.decomposition { - t.Errorf("%U: decomp(%s): was %+q; want %+q", r, CK[j], p.Decomposition(), f.decomposition) - } - } - } - } -} diff --git a/vendor/golang.org/x/text/unicode/norm/iter_test.go b/vendor/golang.org/x/text/unicode/norm/iter_test.go deleted file mode 100644 index d95aa304d4..0000000000 --- a/vendor/golang.org/x/text/unicode/norm/iter_test.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2011 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 norm - -import ( - "strings" - "testing" -) - -func doIterNorm(f Form, s string) []byte { - acc := []byte{} - i := Iter{} - i.InitString(f, s) - for !i.Done() { - acc = append(acc, i.Next()...) - } - return acc -} - -func TestIterNext(t *testing.T) { - runNormTests(t, "IterNext", func(f Form, out []byte, s string) []byte { - return doIterNorm(f, string(append(out, s...))) - }) -} - -type SegmentTest struct { - in string - out []string -} - -var segmentTests = []SegmentTest{ - {"\u1E0A\u0323a", []string{"\x44\u0323\u0307", "a", ""}}, - {rep('a', segSize), append(strings.Split(rep('a', segSize), ""), "")}, - {rep('a', segSize+2), append(strings.Split(rep('a', segSize+2), ""), "")}, - {rep('a', segSize) + "\u0300aa", - append(strings.Split(rep('a', segSize-1), ""), "a\u0300", "a", "a", "")}, - - // U+0f73 is NOT treated as a starter as it is a modifier - {"a" + grave(29) + "\u0f73", []string{"a" + grave(29), cgj + "\u0f73"}}, - {"a\u0f73", []string{"a\u0f73"}}, - - // U+ff9e is treated as a non-starter. - // TODO: should we? Note that this will only affect iteration, as whether - // or not we do so does not affect the normalization output and will either - // way result in consistent iteration output. - {"a" + grave(30) + "\uff9e", []string{"a" + grave(30), cgj + "\uff9e"}}, - {"a\uff9e", []string{"a\uff9e"}}, -} - -var segmentTestsK = []SegmentTest{ - {"\u3332", []string{"\u30D5", "\u30A1", "\u30E9", "\u30C3", "\u30C8\u3099", ""}}, - // last segment of multi-segment decomposition needs normalization - {"\u3332\u093C", []string{"\u30D5", "\u30A1", "\u30E9", "\u30C3", "\u30C8\u093C\u3099", ""}}, - {"\u320E", []string{"\x28", "\uAC00", "\x29"}}, - - // last segment should be copied to start of buffer. - {"\ufdfa", []string{"\u0635", "\u0644", "\u0649", " ", "\u0627", "\u0644", "\u0644", "\u0647", " ", "\u0639", "\u0644", "\u064a", "\u0647", " ", "\u0648", "\u0633", "\u0644", "\u0645", ""}}, - {"\ufdfa" + grave(30), []string{"\u0635", "\u0644", "\u0649", " ", "\u0627", "\u0644", "\u0644", "\u0647", " ", "\u0639", "\u0644", "\u064a", "\u0647", " ", "\u0648", "\u0633", "\u0644", "\u0645" + grave(30), ""}}, - {"\uFDFA" + grave(64), []string{"\u0635", "\u0644", "\u0649", " ", "\u0627", "\u0644", "\u0644", "\u0647", " ", "\u0639", "\u0644", "\u064a", "\u0647", " ", "\u0648", "\u0633", "\u0644", "\u0645" + grave(30), cgj + grave(30), cgj + grave(4), ""}}, - - // Hangul and Jamo are grouped together. - {"\uAC00", []string{"\u1100\u1161", ""}}, - {"\uAC01", []string{"\u1100\u1161\u11A8", ""}}, - {"\u1100\u1161", []string{"\u1100\u1161", ""}}, -} - -// Note that, by design, segmentation is equal for composing and decomposing forms. -func TestIterSegmentation(t *testing.T) { - segmentTest(t, "SegmentTestD", NFD, segmentTests) - segmentTest(t, "SegmentTestC", NFC, segmentTests) - segmentTest(t, "SegmentTestKD", NFKD, segmentTestsK) - segmentTest(t, "SegmentTestKC", NFKC, segmentTestsK) -} - -func segmentTest(t *testing.T, name string, f Form, tests []SegmentTest) { - iter := Iter{} - for i, tt := range tests { - iter.InitString(f, tt.in) - for j, seg := range tt.out { - if seg == "" { - if !iter.Done() { - res := string(iter.Next()) - t.Errorf(`%s:%d:%d: expected Done()==true, found segment %+q`, name, i, j, res) - } - continue - } - if iter.Done() { - t.Errorf("%s:%d:%d: Done()==true, want false", name, i, j) - } - seg = f.String(seg) - if res := string(iter.Next()); res != seg { - t.Errorf(`%s:%d:%d" segment was %+q (%d); want %+q (%d)`, name, i, j, pc(res), len(res), pc(seg), len(seg)) - } - } - } -} diff --git a/vendor/golang.org/x/text/unicode/norm/maketables.go b/vendor/golang.org/x/text/unicode/norm/maketables.go index 8d418160ca..338c395ee6 100644 --- a/vendor/golang.org/x/text/unicode/norm/maketables.go +++ b/vendor/golang.org/x/text/unicode/norm/maketables.go @@ -795,7 +795,7 @@ func makeTables() { } fmt.Fprintf(w, "// Total size of tables: %dKB (%d bytes)\n", (size+512)/1024, size) - gen.WriteGoFile("tables.go", "norm", w.Bytes()) + gen.WriteVersionedGoFile("tables.go", "norm", w.Bytes()) } func printChars() { @@ -972,5 +972,5 @@ func printTestdata() { } } fmt.Fprintln(w, "}") - gen.WriteGoFile("data_test.go", "norm", w.Bytes()) + gen.WriteVersionedGoFile("data_test.go", "norm", w.Bytes()) } diff --git a/vendor/golang.org/x/text/unicode/norm/normalize_test.go b/vendor/golang.org/x/text/unicode/norm/normalize_test.go deleted file mode 100644 index 4f837372ca..0000000000 --- a/vendor/golang.org/x/text/unicode/norm/normalize_test.go +++ /dev/null @@ -1,1287 +0,0 @@ -// Copyright 2011 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 norm - -import ( - "bytes" - "flag" - "fmt" - "io" - "log" - "strings" - "testing" - "unicode/utf8" - - "golang.org/x/text/internal/testtext" - "golang.org/x/text/transform" -) - -var ( - testn = flag.Int("testn", -1, "specific test number to run or -1 for all") -) - -// pc replaces any rune r that is repeated n times, for n > 1, with r{n}. -func pc(s string) []byte { - b := bytes.NewBuffer(make([]byte, 0, len(s))) - for i := 0; i < len(s); { - r, sz := utf8.DecodeRuneInString(s[i:]) - n := 0 - if sz == 1 { - // Special-case one-byte case to handle repetition for invalid UTF-8. - for c := s[i]; i+n < len(s) && s[i+n] == c; n++ { - } - } else { - for _, r2 := range s[i:] { - if r2 != r { - break - } - n++ - } - } - b.WriteString(s[i : i+sz]) - if n > 1 { - fmt.Fprintf(b, "{%d}", n) - } - i += sz * n - } - return b.Bytes() -} - -// pidx finds the index from which two strings start to differ, plus context. -// It returns the index and ellipsis if the index is greater than 0. -func pidx(a, b string) (i int, prefix string) { - for ; i < len(a) && i < len(b) && a[i] == b[i]; i++ { - } - if i < 8 { - return 0, "" - } - i -= 3 // ensure taking at least one full rune before the difference. - for k := i - 7; i > k && !utf8.RuneStart(a[i]); i-- { - } - return i, "..." -} - -type PositionTest struct { - input string - pos int - buffer string // expected contents of reorderBuffer, if applicable -} - -type positionFunc func(rb *reorderBuffer, s string) (int, []byte) - -func runPosTests(t *testing.T, name string, f Form, fn positionFunc, tests []PositionTest) { - rb := reorderBuffer{} - rb.init(f, nil) - for i, test := range tests { - rb.reset() - rb.src = inputString(test.input) - rb.nsrc = len(test.input) - pos, out := fn(&rb, test.input) - if pos != test.pos { - t.Errorf("%s:%d: position is %d; want %d", name, i, pos, test.pos) - } - if outs := string(out); outs != test.buffer { - k, pfx := pidx(outs, test.buffer) - t.Errorf("%s:%d: buffer \nwas %s%+q; \nwant %s%+q", name, i, pfx, pc(outs[k:]), pfx, pc(test.buffer[k:])) - } - } -} - -func grave(n int) string { - return rep(0x0300, n) -} - -func rep(r rune, n int) string { - return strings.Repeat(string(r), n) -} - -const segSize = maxByteBufferSize - -var cgj = GraphemeJoiner - -var decomposeSegmentTests = []PositionTest{ - // illegal runes - {"\xC2", 0, ""}, - {"\xC0", 1, "\xC0"}, - {"\u00E0\x80", 2, "\u0061\u0300"}, - // starter - {"a", 1, "a"}, - {"ab", 1, "a"}, - // starter + composing - {"a\u0300", 3, "a\u0300"}, - {"a\u0300b", 3, "a\u0300"}, - // with decomposition - {"\u00C0", 2, "A\u0300"}, - {"\u00C0b", 2, "A\u0300"}, - // long - {grave(31), 60, grave(30) + cgj}, - {"a" + grave(31), 61, "a" + grave(30) + cgj}, - - // Stability tests: see http://www.unicode.org/review/pr-29.html. - // U+0300 COMBINING GRAVE ACCENT;Mn;230;NSM;;;;;N;NON-SPACING GRAVE;;;; - // U+0B47 ORIYA VOWEL SIGN E;Mc;0;L;;;;;N;;;;; - // U+0B3E ORIYA VOWEL SIGN AA;Mc;0;L;;;;;N;;;;; - // U+1100 HANGUL CHOSEONG KIYEOK;Lo;0;L;;;;;N;;;;; - // U+1161 HANGUL JUNGSEONG A;Lo;0;L;;;;;N;;;;; - {"\u0B47\u0300\u0B3E", 8, "\u0B47\u0300\u0B3E"}, - {"\u1100\u0300\u1161", 8, "\u1100\u0300\u1161"}, - {"\u0B47\u0B3E", 6, "\u0B47\u0B3E"}, - {"\u1100\u1161", 6, "\u1100\u1161"}, - - // U+04DA MALAYALAM VOWEL SIGN O;Mc;0;L;0D46 0D3E;;;;N;;;;; - // Sequence of decomposing characters that are starters and modifiers. - {"\u0d4a" + strings.Repeat("\u0d3e", 31), 90, "\u0d46" + strings.Repeat("\u0d3e", 30) + cgj}, - - {grave(30), 60, grave(30)}, - // U+FF9E is a starter, but decomposes to U+3099, which is not. - {grave(30) + "\uff9e", 60, grave(30) + cgj}, - // ends with incomplete UTF-8 encoding - {"\xCC", 0, ""}, - {"\u0300\xCC", 2, "\u0300"}, -} - -func decomposeSegmentF(rb *reorderBuffer, s string) (int, []byte) { - rb.initString(NFD, s) - rb.setFlusher(nil, appendFlush) - p := decomposeSegment(rb, 0, true) - return p, rb.out -} - -func TestDecomposeSegment(t *testing.T) { - runPosTests(t, "TestDecomposeSegment", NFC, decomposeSegmentF, decomposeSegmentTests) -} - -var firstBoundaryTests = []PositionTest{ - // no boundary - {"", -1, ""}, - {"\u0300", -1, ""}, - {"\x80\x80", -1, ""}, - // illegal runes - {"\xff", 0, ""}, - {"\u0300\xff", 2, ""}, - {"\u0300\xc0\x80\x80", 2, ""}, - // boundaries - {"a", 0, ""}, - {"\u0300a", 2, ""}, - // Hangul - {"\u1103\u1161", 0, ""}, - {"\u110B\u1173\u11B7", 0, ""}, - {"\u1161\u110B\u1173\u11B7", 3, ""}, - {"\u1173\u11B7\u1103\u1161", 6, ""}, - // too many combining characters. - {grave(maxNonStarters - 1), -1, ""}, - {grave(maxNonStarters), 60, ""}, - {grave(maxNonStarters + 1), 60, ""}, -} - -func firstBoundaryF(rb *reorderBuffer, s string) (int, []byte) { - return rb.f.form.FirstBoundary([]byte(s)), nil -} - -func firstBoundaryStringF(rb *reorderBuffer, s string) (int, []byte) { - return rb.f.form.FirstBoundaryInString(s), nil -} - -func TestFirstBoundary(t *testing.T) { - runPosTests(t, "TestFirstBoundary", NFC, firstBoundaryF, firstBoundaryTests) - runPosTests(t, "TestFirstBoundaryInString", NFC, firstBoundaryStringF, firstBoundaryTests) -} - -func TestNextBoundary(t *testing.T) { - testCases := []struct { - input string - atEOF bool - want int - }{ - // no boundary - {"", true, 0}, - {"", false, -1}, - {"\u0300", true, 2}, - {"\u0300", false, -1}, - {"\x80\x80", true, 1}, - {"\x80\x80", false, 1}, - // illegal runes - {"\xff", false, 1}, - {"\u0300\xff", false, 2}, - {"\u0300\xc0\x80\x80", false, 2}, - {"\xc2\x80\x80", false, 2}, - {"\xc2", false, -1}, - {"\xc2", true, 1}, - {"a\u0300\xc2", false, -1}, - {"a\u0300\xc2", true, 3}, - // boundaries - {"a", true, 1}, - {"a", false, -1}, - {"aa", false, 1}, - {"\u0300", true, 2}, - {"\u0300", false, -1}, - {"\u0300a", false, 2}, - // Hangul - {"\u1103\u1161", true, 6}, - {"\u1103\u1161", false, -1}, - {"\u110B\u1173\u11B7", false, -1}, - {"\u110B\u1173\u11B7\u110B\u1173\u11B7", false, 9}, - {"\u1161\u110B\u1173\u11B7", false, 3}, - {"\u1173\u11B7\u1103\u1161", false, 6}, - // too many combining characters. - {grave(maxNonStarters - 1), false, -1}, - {grave(maxNonStarters), false, 60}, - {grave(maxNonStarters + 1), false, 60}, - } - - for _, tc := range testCases { - if got := NFC.NextBoundary([]byte(tc.input), tc.atEOF); got != tc.want { - t.Errorf("NextBoundary(%+q, %v) = %d; want %d", tc.input, tc.atEOF, got, tc.want) - } - if got := NFC.NextBoundaryInString(tc.input, tc.atEOF); got != tc.want { - t.Errorf("NextBoundaryInString(%+q, %v) = %d; want %d", tc.input, tc.atEOF, got, tc.want) - } - } -} - -var decomposeToLastTests = []PositionTest{ - // ends with inert character - {"Hello!", 6, ""}, - {"\u0632", 2, ""}, - {"a\u0301\u0635", 5, ""}, - // ends with non-inert starter - {"a", 0, "a"}, - {"a\u0301a", 3, "a"}, - {"a\u0301\u03B9", 3, "\u03B9"}, - {"a\u0327", 0, "a\u0327"}, - // illegal runes - {"\xFF", 1, ""}, - {"aa\xFF", 3, ""}, - {"\xC0\x80\x80", 3, ""}, - {"\xCC\x80\x80", 3, ""}, - // ends with incomplete UTF-8 encoding - {"a\xCC", 2, ""}, - // ends with combining characters - {"\u0300\u0301", 0, "\u0300\u0301"}, - {"a\u0300\u0301", 0, "a\u0300\u0301"}, - {"a\u0301\u0308", 0, "a\u0301\u0308"}, - {"a\u0308\u0301", 0, "a\u0308\u0301"}, - {"aaaa\u0300\u0301", 3, "a\u0300\u0301"}, - {"\u0300a\u0300\u0301", 2, "a\u0300\u0301"}, - {"\u00C0", 0, "A\u0300"}, - {"a\u00C0", 1, "A\u0300"}, - // decomposing - {"a\u0300\u00E0", 3, "a\u0300"}, - // multisegment decompositions (flushes leading segments) - {"a\u0300\uFDC0", 7, "\u064A"}, - {"\uFDC0" + grave(29), 4, "\u064A" + grave(29)}, - {"\uFDC0" + grave(30), 4, "\u064A" + grave(30)}, - {"\uFDC0" + grave(31), 5, grave(30)}, - {"\uFDFA" + grave(14), 31, "\u0645" + grave(14)}, - // Overflow - {"\u00E0" + grave(29), 0, "a" + grave(30)}, - {"\u00E0" + grave(30), 2, grave(30)}, - // Hangul - {"a\u1103", 1, "\u1103"}, - {"a\u110B", 1, "\u110B"}, - {"a\u110B\u1173", 1, "\u110B\u1173"}, - // See comment in composition.go:compBoundaryAfter. - {"a\u110B\u1173\u11B7", 1, "\u110B\u1173\u11B7"}, - {"a\uC73C", 1, "\u110B\u1173"}, - {"다음", 3, "\u110B\u1173\u11B7"}, - {"다", 0, "\u1103\u1161"}, - {"\u1103\u1161\u110B\u1173\u11B7", 6, "\u110B\u1173\u11B7"}, - {"\u110B\u1173\u11B7\u1103\u1161", 9, "\u1103\u1161"}, - {"다음음", 6, "\u110B\u1173\u11B7"}, - {"음다다", 6, "\u1103\u1161"}, - // maximized buffer - {"a" + grave(30), 0, "a" + grave(30)}, - // Buffer overflow - {"a" + grave(31), 3, grave(30)}, - // weird UTF-8 - {"a\u0300\u11B7", 0, "a\u0300\u11B7"}, -} - -func decomposeToLast(rb *reorderBuffer, s string) (int, []byte) { - rb.setFlusher([]byte(s), appendFlush) - decomposeToLastBoundary(rb) - buf := rb.flush(nil) - return len(rb.out), buf -} - -func TestDecomposeToLastBoundary(t *testing.T) { - runPosTests(t, "TestDecomposeToLastBoundary", NFKC, decomposeToLast, decomposeToLastTests) -} - -var lastBoundaryTests = []PositionTest{ - // ends with inert character - {"Hello!", 6, ""}, - {"\u0632", 2, ""}, - // ends with non-inert starter - {"a", 0, ""}, - // illegal runes - {"\xff", 1, ""}, - {"aa\xff", 3, ""}, - {"a\xff\u0300", 1, ""}, // TODO: should probably be 2. - {"\xc0\x80\x80", 3, ""}, - {"\xc0\x80\x80\u0300", 3, ""}, - // ends with incomplete UTF-8 encoding - {"\xCC", -1, ""}, - {"\xE0\x80", -1, ""}, - {"\xF0\x80\x80", -1, ""}, - {"a\xCC", 0, ""}, - {"\x80\xCC", 1, ""}, - {"\xCC\xCC", 1, ""}, - // ends with combining characters - {"a\u0300\u0301", 0, ""}, - {"aaaa\u0300\u0301", 3, ""}, - {"\u0300a\u0300\u0301", 2, ""}, - {"\u00C2", 0, ""}, - {"a\u00C2", 1, ""}, - // decomposition may recombine - {"\u0226", 0, ""}, - // no boundary - {"", -1, ""}, - {"\u0300\u0301", -1, ""}, - {"\u0300", -1, ""}, - {"\x80\x80", -1, ""}, - {"\x80\x80\u0301", -1, ""}, - // Hangul - {"다음", 3, ""}, - {"다", 0, ""}, - {"\u1103\u1161\u110B\u1173\u11B7", 6, ""}, - {"\u110B\u1173\u11B7\u1103\u1161", 9, ""}, - // too many combining characters. - {grave(maxNonStarters - 1), -1, ""}, - // May still be preceded with a non-starter. - {grave(maxNonStarters), -1, ""}, - // May still need to insert a cgj after the last combiner. - {grave(maxNonStarters + 1), 2, ""}, - {grave(maxNonStarters + 2), 4, ""}, - - {"a" + grave(maxNonStarters-1), 0, ""}, - {"a" + grave(maxNonStarters), 0, ""}, - // May still need to insert a cgj after the last combiner. - {"a" + grave(maxNonStarters+1), 3, ""}, - {"a" + grave(maxNonStarters+2), 5, ""}, -} - -func lastBoundaryF(rb *reorderBuffer, s string) (int, []byte) { - return rb.f.form.LastBoundary([]byte(s)), nil -} - -func TestLastBoundary(t *testing.T) { - runPosTests(t, "TestLastBoundary", NFC, lastBoundaryF, lastBoundaryTests) -} - -type spanTest struct { - input string - atEOF bool - n int - err error -} - -var quickSpanTests = []spanTest{ - {"", true, 0, nil}, - // starters - {"a", true, 1, nil}, - {"abc", true, 3, nil}, - {"\u043Eb", true, 3, nil}, - // incomplete last rune. - {"\xCC", true, 1, nil}, - {"\xCC", false, 0, transform.ErrShortSrc}, - {"a\xCC", true, 2, nil}, - {"a\xCC", false, 0, transform.ErrShortSrc}, // TODO: could be 1 for NFD - // incorrectly ordered combining characters - {"\u0300\u0316", true, 0, transform.ErrEndOfSpan}, - {"\u0300\u0316", false, 0, transform.ErrEndOfSpan}, - {"\u0300\u0316cd", true, 0, transform.ErrEndOfSpan}, - {"\u0300\u0316cd", false, 0, transform.ErrEndOfSpan}, - // have a maximum number of combining characters. - {rep(0x035D, 30) + "\u035B", true, 0, transform.ErrEndOfSpan}, - {"a" + rep(0x035D, 30) + "\u035B", true, 0, transform.ErrEndOfSpan}, - {"Ɵ" + rep(0x035D, 30) + "\u035B", true, 0, transform.ErrEndOfSpan}, - {"aa" + rep(0x035D, 30) + "\u035B", true, 1, transform.ErrEndOfSpan}, - {rep(0x035D, 30) + cgj + "\u035B", true, 64, nil}, - {"a" + rep(0x035D, 30) + cgj + "\u035B", true, 65, nil}, - {"Ɵ" + rep(0x035D, 30) + cgj + "\u035B", true, 66, nil}, - {"aa" + rep(0x035D, 30) + cgj + "\u035B", true, 66, nil}, - - {"a" + rep(0x035D, 30) + cgj + "\u035B", false, 61, transform.ErrShortSrc}, - {"Ɵ" + rep(0x035D, 30) + cgj + "\u035B", false, 62, transform.ErrShortSrc}, - {"aa" + rep(0x035D, 30) + cgj + "\u035B", false, 62, transform.ErrShortSrc}, -} - -var quickSpanNFDTests = []spanTest{ - // needs decomposing - {"\u00C0", true, 0, transform.ErrEndOfSpan}, - {"abc\u00C0", true, 3, transform.ErrEndOfSpan}, - // correctly ordered combining characters - {"\u0300", true, 2, nil}, - {"ab\u0300", true, 4, nil}, - {"ab\u0300cd", true, 6, nil}, - {"\u0300cd", true, 4, nil}, - {"\u0316\u0300", true, 4, nil}, - {"ab\u0316\u0300", true, 6, nil}, - {"ab\u0316\u0300cd", true, 8, nil}, - {"ab\u0316\u0300\u00C0", true, 6, transform.ErrEndOfSpan}, - {"\u0316\u0300cd", true, 6, nil}, - {"\u043E\u0308b", true, 5, nil}, - // incorrectly ordered combining characters - {"ab\u0300\u0316", true, 1, transform.ErrEndOfSpan}, // TODO: we could skip 'b' as well. - {"ab\u0300\u0316cd", true, 1, transform.ErrEndOfSpan}, - // Hangul - {"같은", true, 0, transform.ErrEndOfSpan}, -} - -var quickSpanNFCTests = []spanTest{ - // okay composed - {"\u00C0", true, 2, nil}, - {"abc\u00C0", true, 5, nil}, - // correctly ordered combining characters - // TODO: b may combine with modifiers, which is why this fails. We could - // make a more precise test that that actually checks whether last - // characters combines. Probably not worth it. - {"ab\u0300", true, 1, transform.ErrEndOfSpan}, - {"ab\u0300cd", true, 1, transform.ErrEndOfSpan}, - {"ab\u0316\u0300", true, 1, transform.ErrEndOfSpan}, - {"ab\u0316\u0300cd", true, 1, transform.ErrEndOfSpan}, - {"\u00C0\u035D", true, 4, nil}, - // we do not special case leading combining characters - {"\u0300cd", true, 0, transform.ErrEndOfSpan}, - {"\u0300", true, 0, transform.ErrEndOfSpan}, - {"\u0316\u0300", true, 0, transform.ErrEndOfSpan}, - {"\u0316\u0300cd", true, 0, transform.ErrEndOfSpan}, - // incorrectly ordered combining characters - {"ab\u0300\u0316", true, 1, transform.ErrEndOfSpan}, - {"ab\u0300\u0316cd", true, 1, transform.ErrEndOfSpan}, - // Hangul - {"같은", true, 6, nil}, - {"같은", false, 3, transform.ErrShortSrc}, - // We return the start of the violating segment in case of overflow. - {grave(30) + "\uff9e", true, 0, transform.ErrEndOfSpan}, - {grave(30), true, 0, transform.ErrEndOfSpan}, -} - -func runSpanTests(t *testing.T, name string, f Form, testCases []spanTest) { - for i, tc := range testCases { - s := fmt.Sprintf("Bytes/%s/%d=%+q/atEOF=%v", name, i, pc(tc.input), tc.atEOF) - ok := testtext.Run(t, s, func(t *testing.T) { - n, err := f.Span([]byte(tc.input), tc.atEOF) - if n != tc.n || err != tc.err { - t.Errorf("\n got %d, %v;\nwant %d, %v", n, err, tc.n, tc.err) - } - }) - if !ok { - continue // Don't do the String variant if the Bytes variant failed. - } - s = fmt.Sprintf("String/%s/%d=%+q/atEOF=%v", name, i, pc(tc.input), tc.atEOF) - testtext.Run(t, s, func(t *testing.T) { - n, err := f.SpanString(tc.input, tc.atEOF) - if n != tc.n || err != tc.err { - t.Errorf("\n got %d, %v;\nwant %d, %v", n, err, tc.n, tc.err) - } - }) - } -} - -func TestSpan(t *testing.T) { - runSpanTests(t, "NFD", NFD, quickSpanTests) - runSpanTests(t, "NFD", NFD, quickSpanNFDTests) - runSpanTests(t, "NFC", NFC, quickSpanTests) - runSpanTests(t, "NFC", NFC, quickSpanNFCTests) -} - -var isNormalTests = []PositionTest{ - {"", 1, ""}, - // illegal runes - {"\xff", 1, ""}, - // starters - {"a", 1, ""}, - {"abc", 1, ""}, - {"\u043Eb", 1, ""}, - // incorrectly ordered combining characters - {"\u0300\u0316", 0, ""}, - {"ab\u0300\u0316", 0, ""}, - {"ab\u0300\u0316cd", 0, ""}, - {"\u0300\u0316cd", 0, ""}, -} -var isNormalNFDTests = []PositionTest{ - // needs decomposing - {"\u00C0", 0, ""}, - {"abc\u00C0", 0, ""}, - // correctly ordered combining characters - {"\u0300", 1, ""}, - {"ab\u0300", 1, ""}, - {"ab\u0300cd", 1, ""}, - {"\u0300cd", 1, ""}, - {"\u0316\u0300", 1, ""}, - {"ab\u0316\u0300", 1, ""}, - {"ab\u0316\u0300cd", 1, ""}, - {"\u0316\u0300cd", 1, ""}, - {"\u043E\u0308b", 1, ""}, - // Hangul - {"같은", 0, ""}, -} -var isNormalNFCTests = []PositionTest{ - // okay composed - {"\u00C0", 1, ""}, - {"abc\u00C0", 1, ""}, - // need reordering - {"a\u0300", 0, ""}, - {"a\u0300cd", 0, ""}, - {"a\u0316\u0300", 0, ""}, - {"a\u0316\u0300cd", 0, ""}, - // correctly ordered combining characters - {"ab\u0300", 1, ""}, - {"ab\u0300cd", 1, ""}, - {"ab\u0316\u0300", 1, ""}, - {"ab\u0316\u0300cd", 1, ""}, - {"\u00C0\u035D", 1, ""}, - {"\u0300", 1, ""}, - {"\u0316\u0300cd", 1, ""}, - // Hangul - {"같은", 1, ""}, -} - -var isNormalNFKXTests = []PositionTest{ - // Special case. - {"\u00BC", 0, ""}, -} - -func isNormalF(rb *reorderBuffer, s string) (int, []byte) { - if rb.f.form.IsNormal([]byte(s)) { - return 1, nil - } - return 0, nil -} - -func isNormalStringF(rb *reorderBuffer, s string) (int, []byte) { - if rb.f.form.IsNormalString(s) { - return 1, nil - } - return 0, nil -} - -func TestIsNormal(t *testing.T) { - runPosTests(t, "TestIsNormalNFD1", NFD, isNormalF, isNormalTests) - runPosTests(t, "TestIsNormalNFD2", NFD, isNormalF, isNormalNFDTests) - runPosTests(t, "TestIsNormalNFC1", NFC, isNormalF, isNormalTests) - runPosTests(t, "TestIsNormalNFC2", NFC, isNormalF, isNormalNFCTests) - runPosTests(t, "TestIsNormalNFKD1", NFKD, isNormalF, isNormalTests) - runPosTests(t, "TestIsNormalNFKD2", NFKD, isNormalF, isNormalNFDTests) - runPosTests(t, "TestIsNormalNFKD3", NFKD, isNormalF, isNormalNFKXTests) - runPosTests(t, "TestIsNormalNFKC1", NFKC, isNormalF, isNormalTests) - runPosTests(t, "TestIsNormalNFKC2", NFKC, isNormalF, isNormalNFCTests) - runPosTests(t, "TestIsNormalNFKC3", NFKC, isNormalF, isNormalNFKXTests) -} - -func TestIsNormalString(t *testing.T) { - runPosTests(t, "TestIsNormalNFD1", NFD, isNormalStringF, isNormalTests) - runPosTests(t, "TestIsNormalNFD2", NFD, isNormalStringF, isNormalNFDTests) - runPosTests(t, "TestIsNormalNFC1", NFC, isNormalStringF, isNormalTests) - runPosTests(t, "TestIsNormalNFC2", NFC, isNormalStringF, isNormalNFCTests) -} - -type AppendTest struct { - left string - right string - out string -} - -type appendFunc func(f Form, out []byte, s string) []byte - -var fstr = []string{"NFC", "NFD", "NFKC", "NFKD"} - -func runNormTests(t *testing.T, name string, fn appendFunc) { - for f := NFC; f <= NFKD; f++ { - runAppendTests(t, name, f, fn, normTests[f]) - } -} - -func runAppendTests(t *testing.T, name string, f Form, fn appendFunc, tests []AppendTest) { - for i, test := range tests { - t.Run(fmt.Sprintf("%s/%d", fstr[f], i), func(t *testing.T) { - id := pc(test.left + test.right) - if *testn >= 0 && i != *testn { - return - } - t.Run("fn", func(t *testing.T) { - out := []byte(test.left) - have := string(fn(f, out, test.right)) - if len(have) != len(test.out) { - t.Errorf("%+q: length is %d; want %d (%+q vs %+q)", id, len(have), len(test.out), pc(have), pc(test.out)) - } - if have != test.out { - k, pf := pidx(have, test.out) - t.Errorf("%+q:\nwas %s%+q; \nwant %s%+q", id, pf, pc(have[k:]), pf, pc(test.out[k:])) - } - }) - - // Bootstrap by normalizing input. Ensures that the various variants - // behave the same. - for g := NFC; g <= NFKD; g++ { - if f == g { - continue - } - t.Run(fstr[g], func(t *testing.T) { - want := g.String(test.left + test.right) - have := string(fn(g, g.AppendString(nil, test.left), test.right)) - if len(have) != len(want) { - t.Errorf("%+q: length is %d; want %d (%+q vs %+q)", id, len(have), len(want), pc(have), pc(want)) - } - if have != want { - k, pf := pidx(have, want) - t.Errorf("%+q:\nwas %s%+q; \nwant %s%+q", id, pf, pc(have[k:]), pf, pc(want[k:])) - } - }) - } - }) - } -} - -var normTests = [][]AppendTest{ - appendTestsNFC, - appendTestsNFD, - appendTestsNFKC, - appendTestsNFKD, -} - -var appendTestsNFC = []AppendTest{ - {"", ascii, ascii}, - {"", txt_all, txt_all}, - {"\uff9e", grave(30), "\uff9e" + grave(29) + cgj + grave(1)}, - {grave(30), "\uff9e", grave(30) + cgj + "\uff9e"}, - - // Tests designed for Iter. - { // ordering of non-composing combining characters - "", - "\u0305\u0316", - "\u0316\u0305", - }, - { // segment overflow - "", - "a" + rep(0x0305, maxNonStarters+4) + "\u0316", - "a" + rep(0x0305, maxNonStarters) + cgj + "\u0316" + rep(0x305, 4), - }, - - { // Combine across non-blocking non-starters. - // U+0327 COMBINING CEDILLA;Mn;202;NSM;;;;;N;NON-SPACING CEDILLA;;;; - // U+0325 COMBINING RING BELOW;Mn;220;NSM;;;;;N;NON-SPACING RING BELOW;;;; - "", "a\u0327\u0325", "\u1e01\u0327", - }, - - { // Jamo V+T does not combine. - "", - "\u1161\u11a8", - "\u1161\u11a8", - }, - - // Stability tests: see http://www.unicode.org/review/pr-29.html. - {"", "\u0b47\u0300\u0b3e", "\u0b47\u0300\u0b3e"}, - {"", "\u1100\u0300\u1161", "\u1100\u0300\u1161"}, - {"", "\u0b47\u0b3e", "\u0b4b"}, - {"", "\u1100\u1161", "\uac00"}, - - // U+04DA MALAYALAM VOWEL SIGN O;Mc;0;L;0D46 0D3E;;;;N;;;;; - { // 0d4a starts a new segment. - "", - "\u0d4a" + strings.Repeat("\u0d3e", 15) + "\u0d4a" + strings.Repeat("\u0d3e", 15), - "\u0d4a" + strings.Repeat("\u0d3e", 15) + "\u0d4a" + strings.Repeat("\u0d3e", 15), - }, - - { // Split combining characters. - // TODO: don't insert CGJ before starters. - "", - "\u0d46" + strings.Repeat("\u0d3e", 31), - "\u0d4a" + strings.Repeat("\u0d3e", 29) + cgj + "\u0d3e", - }, - - { // Split combining characters. - "", - "\u0d4a" + strings.Repeat("\u0d3e", 30), - "\u0d4a" + strings.Repeat("\u0d3e", 29) + cgj + "\u0d3e", - }, - - { // https://golang.org/issues/20079 - "", - "\xeb\u0344", - "\xeb\u0308\u0301", - }, - - { // https://golang.org/issues/20079 - "", - "\uac00" + strings.Repeat("\u0300", 30), - "\uac00" + strings.Repeat("\u0300", 29) + "\u034f\u0300", - }, - - { // https://golang.org/issues/20079 - "", - "\xeb" + strings.Repeat("\u0300", 31), - "\xeb" + strings.Repeat("\u0300", 30) + "\u034f\u0300", - }, -} - -var appendTestsNFD = []AppendTest{ -// TODO: Move some of the tests here. -} - -var appendTestsNFKC = []AppendTest{ - // empty buffers - {"", "", ""}, - {"a", "", "a"}, - {"", "a", "a"}, - {"", "\u0041\u0307\u0304", "\u01E0"}, - // segment split across buffers - {"", "a\u0300b", "\u00E0b"}, - {"a", "\u0300b", "\u00E0b"}, - {"a", "\u0300\u0316", "\u00E0\u0316"}, - {"a", "\u0316\u0300", "\u00E0\u0316"}, - {"a", "\u0300a\u0300", "\u00E0\u00E0"}, - {"a", "\u0300a\u0300a\u0300", "\u00E0\u00E0\u00E0"}, - {"a", "\u0300aaa\u0300aaa\u0300", "\u00E0aa\u00E0aa\u00E0"}, - {"a\u0300", "\u0327", "\u00E0\u0327"}, - {"a\u0327", "\u0300", "\u00E0\u0327"}, - {"a\u0316", "\u0300", "\u00E0\u0316"}, - {"\u0041\u0307", "\u0304", "\u01E0"}, - // Hangul - {"", "\u110B\u1173", "\uC73C"}, - {"", "\u1103\u1161", "\uB2E4"}, - {"", "\u110B\u1173\u11B7", "\uC74C"}, - {"", "\u320E", "\x28\uAC00\x29"}, - {"", "\x28\u1100\u1161\x29", "\x28\uAC00\x29"}, - {"\u1103", "\u1161", "\uB2E4"}, - {"\u110B", "\u1173\u11B7", "\uC74C"}, - {"\u110B\u1173", "\u11B7", "\uC74C"}, - {"\uC73C", "\u11B7", "\uC74C"}, - // UTF-8 encoding split across buffers - {"a\xCC", "\x80", "\u00E0"}, - {"a\xCC", "\x80b", "\u00E0b"}, - {"a\xCC", "\x80a\u0300", "\u00E0\u00E0"}, - {"a\xCC", "\x80\x80", "\u00E0\x80"}, - {"a\xCC", "\x80\xCC", "\u00E0\xCC"}, - {"a\u0316\xCC", "\x80a\u0316\u0300", "\u00E0\u0316\u00E0\u0316"}, - // ending in incomplete UTF-8 encoding - {"", "\xCC", "\xCC"}, - {"a", "\xCC", "a\xCC"}, - {"a", "b\xCC", "ab\xCC"}, - {"\u0226", "\xCC", "\u0226\xCC"}, - // illegal runes - {"", "\x80", "\x80"}, - {"", "\x80\x80\x80", "\x80\x80\x80"}, - {"", "\xCC\x80\x80\x80", "\xCC\x80\x80\x80"}, - {"", "a\x80", "a\x80"}, - {"", "a\x80\x80\x80", "a\x80\x80\x80"}, - {"", "a\x80\x80\x80\x80\x80\x80", "a\x80\x80\x80\x80\x80\x80"}, - {"a", "\x80\x80\x80", "a\x80\x80\x80"}, - // overflow - {"", strings.Repeat("\x80", 33), strings.Repeat("\x80", 33)}, - {strings.Repeat("\x80", 33), "", strings.Repeat("\x80", 33)}, - {strings.Repeat("\x80", 33), strings.Repeat("\x80", 33), strings.Repeat("\x80", 66)}, - // overflow of combining characters - {"", grave(34), grave(30) + cgj + grave(4)}, - {"", grave(36), grave(30) + cgj + grave(6)}, - {grave(29), grave(5), grave(30) + cgj + grave(4)}, - {grave(30), grave(4), grave(30) + cgj + grave(4)}, - {grave(30), grave(3), grave(30) + cgj + grave(3)}, - {grave(30) + "\xCC", "\x80", grave(30) + cgj + grave(1)}, - {"", "\uFDFA" + grave(14), "\u0635\u0644\u0649 \u0627\u0644\u0644\u0647 \u0639\u0644\u064a\u0647 \u0648\u0633\u0644\u0645" + grave(14)}, - {"", "\uFDFA" + grave(28) + "\u0316", "\u0635\u0644\u0649 \u0627\u0644\u0644\u0647 \u0639\u0644\u064a\u0647 \u0648\u0633\u0644\u0645\u0316" + grave(28)}, - // - First rune has a trailing non-starter. - {"\u00d5", grave(30), "\u00d5" + grave(29) + cgj + grave(1)}, - // - U+FF9E decomposes into a non-starter in compatibility mode. A CGJ must be - // inserted even when FF9E starts a new segment. - {"\uff9e", grave(30), "\u3099" + grave(29) + cgj + grave(1)}, - {grave(30), "\uff9e", grave(30) + cgj + "\u3099"}, - // - Many non-starter decompositions in a row causing overflow. - {"", rep(0x340, 31), rep(0x300, 30) + cgj + "\u0300"}, - {"", rep(0xFF9E, 31), rep(0x3099, 30) + cgj + "\u3099"}, - - {"", "\u0644\u0625" + rep(0x300, 31), "\u0644\u0625" + rep(0x300, 29) + cgj + "\u0300\u0300"}, - {"", "\ufef9" + rep(0x300, 31), "\u0644\u0625" + rep(0x300, 29) + cgj + rep(0x0300, 2)}, - {"", "\ufef9" + rep(0x300, 31), "\u0644\u0625" + rep(0x300, 29) + cgj + rep(0x0300, 2)}, - - // U+0F81 TIBETAN VOWEL SIGN REVERSED II splits into two modifiers. - {"", "\u0f7f" + rep(0xf71, 29) + "\u0f81", "\u0f7f" + rep(0xf71, 29) + cgj + "\u0f71\u0f80"}, - {"", "\u0f7f" + rep(0xf71, 28) + "\u0f81", "\u0f7f" + rep(0xf71, 29) + "\u0f80"}, - {"", "\u0f7f" + rep(0xf81, 16), "\u0f7f" + rep(0xf71, 15) + rep(0xf80, 15) + cgj + "\u0f71\u0f80"}, - - // weird UTF-8 - {"\u00E0\xE1", "\x86", "\u00E0\xE1\x86"}, - {"a\u0300\u11B7", "\u0300", "\u00E0\u11B7\u0300"}, - {"a\u0300\u11B7\u0300", "\u0300", "\u00E0\u11B7\u0300\u0300"}, - {"\u0300", "\xF8\x80\x80\x80\x80\u0300", "\u0300\xF8\x80\x80\x80\x80\u0300"}, - {"\u0300", "\xFC\x80\x80\x80\x80\x80\u0300", "\u0300\xFC\x80\x80\x80\x80\x80\u0300"}, - {"\xF8\x80\x80\x80\x80\u0300", "\u0300", "\xF8\x80\x80\x80\x80\u0300\u0300"}, - {"\xFC\x80\x80\x80\x80\x80\u0300", "\u0300", "\xFC\x80\x80\x80\x80\x80\u0300\u0300"}, - {"\xF8\x80\x80\x80", "\x80\u0300\u0300", "\xF8\x80\x80\x80\x80\u0300\u0300"}, - - {"", strings.Repeat("a\u0316\u0300", 6), strings.Repeat("\u00E0\u0316", 6)}, - // large input. - {"", strings.Repeat("a\u0300\u0316", 31), strings.Repeat("\u00E0\u0316", 31)}, - {"", strings.Repeat("a\u0300\u0316", 4000), strings.Repeat("\u00E0\u0316", 4000)}, - {"", strings.Repeat("\x80\x80", 4000), strings.Repeat("\x80\x80", 4000)}, - {"", "\u0041\u0307\u0304", "\u01E0"}, -} - -var appendTestsNFKD = []AppendTest{ - {"", "a" + grave(64), "a" + grave(30) + cgj + grave(30) + cgj + grave(4)}, - - { // segment overflow on unchanged character - "", - "a" + grave(64) + "\u0316", - "a" + grave(30) + cgj + grave(30) + cgj + "\u0316" + grave(4), - }, - { // segment overflow on unchanged character + start value - "", - "a" + grave(98) + "\u0316", - "a" + grave(30) + cgj + grave(30) + cgj + grave(30) + cgj + "\u0316" + grave(8), - }, - { // segment overflow on decomposition. (U+0340 decomposes to U+0300.) - "", - "a" + grave(59) + "\u0340", - "a" + grave(30) + cgj + grave(30), - }, - { // segment overflow on non-starter decomposition - "", - "a" + grave(33) + "\u0340" + grave(30) + "\u0320", - "a" + grave(30) + cgj + grave(30) + cgj + "\u0320" + grave(4), - }, - { // start value after ASCII overflow - "", - rep('a', segSize) + grave(32) + "\u0320", - rep('a', segSize) + grave(30) + cgj + "\u0320" + grave(2), - }, - { // Jamo overflow - "", - "\u1100\u1161" + grave(30) + "\u0320" + grave(2), - "\u1100\u1161" + grave(29) + cgj + "\u0320" + grave(3), - }, - { // Hangul - "", - "\uac00", - "\u1100\u1161", - }, - { // Hangul overflow - "", - "\uac00" + grave(32) + "\u0320", - "\u1100\u1161" + grave(29) + cgj + "\u0320" + grave(3), - }, - { // Hangul overflow in Hangul mode. - "", - "\uac00\uac00" + grave(32) + "\u0320", - "\u1100\u1161\u1100\u1161" + grave(29) + cgj + "\u0320" + grave(3), - }, - { // Hangul overflow in Hangul mode. - "", - strings.Repeat("\uac00", 3) + grave(32) + "\u0320", - strings.Repeat("\u1100\u1161", 3) + grave(29) + cgj + "\u0320" + grave(3), - }, - { // start value after cc=0 - "", - "您您" + grave(34) + "\u0320", - "您您" + grave(30) + cgj + "\u0320" + grave(4), - }, - { // start value after normalization - "", - "\u0300\u0320a" + grave(34) + "\u0320", - "\u0320\u0300a" + grave(30) + cgj + "\u0320" + grave(4), - }, - { - // U+0F81 TIBETAN VOWEL SIGN REVERSED II splits into two modifiers. - "", - "a\u0f7f" + rep(0xf71, 29) + "\u0f81", - "a\u0f7f" + rep(0xf71, 29) + cgj + "\u0f71\u0f80", - }, -} - -func TestAppend(t *testing.T) { - runNormTests(t, "Append", func(f Form, out []byte, s string) []byte { - return f.Append(out, []byte(s)...) - }) -} - -func TestAppendString(t *testing.T) { - runNormTests(t, "AppendString", func(f Form, out []byte, s string) []byte { - return f.AppendString(out, s) - }) -} - -func TestBytes(t *testing.T) { - runNormTests(t, "Bytes", func(f Form, out []byte, s string) []byte { - buf := []byte{} - buf = append(buf, out...) - buf = append(buf, s...) - return f.Bytes(buf) - }) -} - -func TestString(t *testing.T) { - runNormTests(t, "String", func(f Form, out []byte, s string) []byte { - outs := string(out) + s - return []byte(f.String(outs)) - }) -} - -func TestLinking(t *testing.T) { - const prog = ` - package main - import "fmt" - import "golang.org/x/text/unicode/norm" - func main() { fmt.Println(norm.%s) } - ` - baseline, errB := testtext.CodeSize(fmt.Sprintf(prog, "MaxSegmentSize")) - withTables, errT := testtext.CodeSize(fmt.Sprintf(prog, `NFC.String("")`)) - if errB != nil || errT != nil { - t.Skipf("code size failed: %v and %v", errB, errT) - } - // Tables are at least 50K - if d := withTables - baseline; d < 50*1024 { - t.Errorf("tables appear not to be dropped: %d - %d = %d", - withTables, baseline, d) - } -} - -func appendBench(f Form, in []byte) func() { - buf := make([]byte, 0, 4*len(in)) - return func() { - f.Append(buf, in...) - } -} - -func bytesBench(f Form, in []byte) func() { - return func() { - f.Bytes(in) - } -} - -func iterBench(f Form, in []byte) func() { - iter := Iter{} - return func() { - iter.Init(f, in) - for !iter.Done() { - iter.Next() - } - } -} - -func transformBench(f Form, in []byte) func() { - buf := make([]byte, 4*len(in)) - return func() { - if _, n, err := f.Transform(buf, in, true); err != nil || len(in) != n { - log.Panic(n, len(in), err) - } - } -} - -func readerBench(f Form, in []byte) func() { - buf := make([]byte, 4*len(in)) - return func() { - r := f.Reader(bytes.NewReader(in)) - var err error - for err == nil { - _, err = r.Read(buf) - } - if err != io.EOF { - panic("") - } - } -} - -func writerBench(f Form, in []byte) func() { - buf := make([]byte, 0, 4*len(in)) - return func() { - r := f.Writer(bytes.NewBuffer(buf)) - if _, err := r.Write(in); err != nil { - panic("") - } - } -} - -func appendBenchmarks(bm []func(), f Form, in []byte) []func() { - bm = append(bm, appendBench(f, in)) - bm = append(bm, iterBench(f, in)) - bm = append(bm, transformBench(f, in)) - bm = append(bm, readerBench(f, in)) - bm = append(bm, writerBench(f, in)) - return bm -} - -func doFormBenchmark(b *testing.B, inf, f Form, s string) { - b.StopTimer() - in := inf.Bytes([]byte(s)) - bm := appendBenchmarks(nil, f, in) - b.SetBytes(int64(len(in) * len(bm))) - b.StartTimer() - for i := 0; i < b.N; i++ { - for _, fn := range bm { - fn() - } - } -} - -func doSingle(b *testing.B, f func(Form, []byte) func(), s []byte) { - b.StopTimer() - fn := f(NFC, s) - b.SetBytes(int64(len(s))) - b.StartTimer() - for i := 0; i < b.N; i++ { - fn() - } -} - -var ( - smallNoChange = []byte("nörmalization") - smallChange = []byte("No\u0308rmalization") - ascii = strings.Repeat("There is nothing to change here! ", 500) -) - -func lowerBench(f Form, in []byte) func() { - // Use package strings instead of bytes as it doesn't allocate memory - // if there aren't any changes. - s := string(in) - return func() { - strings.ToLower(s) - } -} - -func BenchmarkLowerCaseNoChange(b *testing.B) { - doSingle(b, lowerBench, smallNoChange) -} -func BenchmarkLowerCaseChange(b *testing.B) { - doSingle(b, lowerBench, smallChange) -} - -func quickSpanBench(f Form, in []byte) func() { - return func() { - f.QuickSpan(in) - } -} - -func BenchmarkQuickSpanChangeNFC(b *testing.B) { - doSingle(b, quickSpanBench, smallNoChange) -} - -func BenchmarkBytesNoChangeNFC(b *testing.B) { - doSingle(b, bytesBench, smallNoChange) -} -func BenchmarkBytesChangeNFC(b *testing.B) { - doSingle(b, bytesBench, smallChange) -} - -func BenchmarkAppendNoChangeNFC(b *testing.B) { - doSingle(b, appendBench, smallNoChange) -} -func BenchmarkAppendChangeNFC(b *testing.B) { - doSingle(b, appendBench, smallChange) -} -func BenchmarkAppendLargeNFC(b *testing.B) { - doSingle(b, appendBench, txt_all_bytes) -} - -func BenchmarkIterNoChangeNFC(b *testing.B) { - doSingle(b, iterBench, smallNoChange) -} -func BenchmarkIterChangeNFC(b *testing.B) { - doSingle(b, iterBench, smallChange) -} -func BenchmarkIterLargeNFC(b *testing.B) { - doSingle(b, iterBench, txt_all_bytes) -} - -func BenchmarkTransformNoChangeNFC(b *testing.B) { - doSingle(b, transformBench, smallNoChange) -} -func BenchmarkTransformChangeNFC(b *testing.B) { - doSingle(b, transformBench, smallChange) -} -func BenchmarkTransformLargeNFC(b *testing.B) { - doSingle(b, transformBench, txt_all_bytes) -} - -func BenchmarkNormalizeAsciiNFC(b *testing.B) { - doFormBenchmark(b, NFC, NFC, ascii) -} -func BenchmarkNormalizeAsciiNFD(b *testing.B) { - doFormBenchmark(b, NFC, NFD, ascii) -} -func BenchmarkNormalizeAsciiNFKC(b *testing.B) { - doFormBenchmark(b, NFC, NFKC, ascii) -} -func BenchmarkNormalizeAsciiNFKD(b *testing.B) { - doFormBenchmark(b, NFC, NFKD, ascii) -} - -func BenchmarkNormalizeNFC2NFC(b *testing.B) { - doFormBenchmark(b, NFC, NFC, txt_all) -} -func BenchmarkNormalizeNFC2NFD(b *testing.B) { - doFormBenchmark(b, NFC, NFD, txt_all) -} -func BenchmarkNormalizeNFD2NFC(b *testing.B) { - doFormBenchmark(b, NFD, NFC, txt_all) -} -func BenchmarkNormalizeNFD2NFD(b *testing.B) { - doFormBenchmark(b, NFD, NFD, txt_all) -} - -// Hangul is often special-cased, so we test it separately. -func BenchmarkNormalizeHangulNFC2NFC(b *testing.B) { - doFormBenchmark(b, NFC, NFC, txt_kr) -} -func BenchmarkNormalizeHangulNFC2NFD(b *testing.B) { - doFormBenchmark(b, NFC, NFD, txt_kr) -} -func BenchmarkNormalizeHangulNFD2NFC(b *testing.B) { - doFormBenchmark(b, NFD, NFC, txt_kr) -} -func BenchmarkNormalizeHangulNFD2NFD(b *testing.B) { - doFormBenchmark(b, NFD, NFD, txt_kr) -} - -var forms = []Form{NFC, NFD, NFKC, NFKD} - -func doTextBenchmark(b *testing.B, s string) { - b.StopTimer() - in := []byte(s) - bm := []func(){} - for _, f := range forms { - bm = appendBenchmarks(bm, f, in) - } - b.SetBytes(int64(len(s) * len(bm))) - b.StartTimer() - for i := 0; i < b.N; i++ { - for _, f := range bm { - f() - } - } -} - -func BenchmarkCanonicalOrdering(b *testing.B) { - doTextBenchmark(b, txt_canon) -} -func BenchmarkExtendedLatin(b *testing.B) { - doTextBenchmark(b, txt_vn) -} -func BenchmarkMiscTwoByteUtf8(b *testing.B) { - doTextBenchmark(b, twoByteUtf8) -} -func BenchmarkMiscThreeByteUtf8(b *testing.B) { - doTextBenchmark(b, threeByteUtf8) -} -func BenchmarkHangul(b *testing.B) { - doTextBenchmark(b, txt_kr) -} -func BenchmarkJapanese(b *testing.B) { - doTextBenchmark(b, txt_jp) -} -func BenchmarkChinese(b *testing.B) { - doTextBenchmark(b, txt_cn) -} -func BenchmarkOverflow(b *testing.B) { - doTextBenchmark(b, overflow) -} - -var overflow = string(bytes.Repeat([]byte("\u035D"), 4096)) + "\u035B" - -// Tests sampled from the Canonical ordering tests (Part 2) of -// http://unicode.org/Public/UNIDATA/NormalizationTest.txt -const txt_canon = `\u0061\u0315\u0300\u05AE\u0300\u0062 \u0061\u0300\u0315\u0300\u05AE\u0062 -\u0061\u0302\u0315\u0300\u05AE\u0062 \u0061\u0307\u0315\u0300\u05AE\u0062 -\u0061\u0315\u0300\u05AE\u030A\u0062 \u0061\u059A\u0316\u302A\u031C\u0062 -\u0061\u032E\u059A\u0316\u302A\u0062 \u0061\u0338\u093C\u0334\u0062 -\u0061\u059A\u0316\u302A\u0339 \u0061\u0341\u0315\u0300\u05AE\u0062 -\u0061\u0348\u059A\u0316\u302A\u0062 \u0061\u0361\u0345\u035D\u035C\u0062 -\u0061\u0366\u0315\u0300\u05AE\u0062 \u0061\u0315\u0300\u05AE\u0486\u0062 -\u0061\u05A4\u059A\u0316\u302A\u0062 \u0061\u0315\u0300\u05AE\u0613\u0062 -\u0061\u0315\u0300\u05AE\u0615\u0062 \u0061\u0617\u0315\u0300\u05AE\u0062 -\u0061\u0619\u0618\u064D\u064E\u0062 \u0061\u0315\u0300\u05AE\u0654\u0062 -\u0061\u0315\u0300\u05AE\u06DC\u0062 \u0061\u0733\u0315\u0300\u05AE\u0062 -\u0061\u0744\u059A\u0316\u302A\u0062 \u0061\u0315\u0300\u05AE\u0745\u0062 -\u0061\u09CD\u05B0\u094D\u3099\u0062 \u0061\u0E38\u0E48\u0E38\u0C56\u0062 -\u0061\u0EB8\u0E48\u0E38\u0E49\u0062 \u0061\u0F72\u0F71\u0EC8\u0F71\u0062 -\u0061\u1039\u05B0\u094D\u3099\u0062 \u0061\u05B0\u094D\u3099\u1A60\u0062 -\u0061\u3099\u093C\u0334\u1BE6\u0062 \u0061\u3099\u093C\u0334\u1C37\u0062 -\u0061\u1CD9\u059A\u0316\u302A\u0062 \u0061\u2DED\u0315\u0300\u05AE\u0062 -\u0061\u2DEF\u0315\u0300\u05AE\u0062 \u0061\u302D\u302E\u059A\u0316\u0062` - -// Taken from http://creativecommons.org/licenses/by-sa/3.0/vn/ -const txt_vn = `Với các điều kiện sau: Ghi nhận công của tác giả. -Nếu bạn sử dụng, chuyển đổi, hoặc xây dựng dự án từ -nội dung được chia sẻ này, bạn phải áp dụng giấy phép này hoặc -một giấy phép khác có các điều khoản tương tự như giấy phép này -cho dự án của bạn. Hiểu rằng: Miễn — Bất kỳ các điều kiện nào -trên đây cũng có thể được miễn bỏ nếu bạn được sự cho phép của -người sở hữu bản quyền. Phạm vi công chúng — Khi tác phẩm hoặc -bất kỳ chương nào của tác phẩm đã trong vùng dành cho công -chúng theo quy định của pháp luật thì tình trạng của nó không -bị ảnh hưởng bởi giấy phép trong bất kỳ trường hợp nào.` - -// Taken from http://creativecommons.org/licenses/by-sa/1.0/deed.ru -const txt_ru = `При обязательном соблюдении следующих условий: -Attribution — Вы должны атрибутировать произведение (указывать -автора и источник) в порядке, предусмотренном автором или -лицензиаром (но только так, чтобы никоим образом не подразумевалось, -что они поддерживают вас или использование вами данного произведения). -Υπό τις ακόλουθες προϋποθέσεις:` - -// Taken from http://creativecommons.org/licenses/by-sa/3.0/gr/ -const txt_gr = `Αναφορά Δημιουργού — Θα πρέπει να κάνετε την αναφορά στο έργο με τον -τρόπο που έχει οριστεί από το δημιουργό ή το χορηγούντο την άδεια -(χωρίς όμως να εννοείται με οποιονδήποτε τρόπο ότι εγκρίνουν εσάς ή -τη χρήση του έργου από εσάς). Παρόμοια Διανομή — Εάν αλλοιώσετε, -τροποποιήσετε ή δημιουργήσετε περαιτέρω βασισμένοι στο έργο θα -μπορείτε να διανέμετε το έργο που θα προκύψει μόνο με την ίδια ή -παρόμοια άδεια.` - -// Taken from http://creativecommons.org/licenses/by-sa/3.0/deed.ar -const txt_ar = `بموجب الشروط التالية نسب المصنف — يجب عليك أن -تنسب العمل بالطريقة التي تحددها المؤلف أو المرخص (ولكن ليس بأي حال من -الأحوال أن توحي وتقترح بتحول أو استخدامك للعمل). -المشاركة على قدم المساواة — إذا كنت يعدل ، والتغيير ، أو الاستفادة -من هذا العمل ، قد ينتج عن توزيع العمل إلا في ظل تشابه او تطابق فى واحد -لهذا الترخيص.` - -// Taken from http://creativecommons.org/licenses/by-sa/1.0/il/ -const txt_il = `בכפוף לתנאים הבאים: ייחוס — עליך לייחס את היצירה (לתת קרדיט) באופן -המצויין על-ידי היוצר או מעניק הרישיון (אך לא בשום אופן המרמז על כך -שהם תומכים בך או בשימוש שלך ביצירה). שיתוף זהה — אם תחליט/י לשנות, -לעבד או ליצור יצירה נגזרת בהסתמך על יצירה זו, תוכל/י להפיץ את יצירתך -החדשה רק תחת אותו הרישיון או רישיון דומה לרישיון זה.` - -const twoByteUtf8 = txt_ru + txt_gr + txt_ar + txt_il - -// Taken from http://creativecommons.org/licenses/by-sa/2.0/kr/ -const txt_kr = `다음과 같은 조건을 따라야 합니다: 저작자표시 -(Attribution) — 저작자나 이용허락자가 정한 방법으로 저작물의 -원저작자를 표시하여야 합니다(그러나 원저작자가 이용자나 이용자의 -이용을 보증하거나 추천한다는 의미로 표시해서는 안됩니다). -동일조건변경허락 — 이 저작물을 이용하여 만든 이차적 저작물에는 본 -라이선스와 동일한 라이선스를 적용해야 합니다.` - -// Taken from http://creativecommons.org/licenses/by-sa/3.0/th/ -const txt_th = `ภายใต้เงื่อนไข ดังต่อไปนี้ : แสดงที่มา — คุณต้องแสดงที่ -มาของงานดังกล่าว ตามรูปแบบที่ผู้สร้างสรรค์หรือผู้อนุญาตกำหนด (แต่ -ไม่ใช่ในลักษณะที่ว่า พวกเขาสนับสนุนคุณหรือสนับสนุนการที่ -คุณนำงานไปใช้) อนุญาตแบบเดียวกัน — หากคุณดัดแปลง เปลี่ยนรูป หรื -อต่อเติมงานนี้ คุณต้องใช้สัญญาอนุญาตแบบเดียวกันหรือแบบที่เหมื -อนกับสัญญาอนุญาตที่ใช้กับงานนี้เท่านั้น` - -const threeByteUtf8 = txt_th - -// Taken from http://creativecommons.org/licenses/by-sa/2.0/jp/ -const txt_jp = `あなたの従うべき条件は以下の通りです。 -表示 — あなたは原著作者のクレジットを表示しなければなりません。 -継承 — もしあなたがこの作品を改変、変形または加工した場合、 -あなたはその結果生じた作品をこの作品と同一の許諾条件の下でのみ -頒布することができます。` - -// http://creativecommons.org/licenses/by-sa/2.5/cn/ -const txt_cn = `您可以自由: 复制、发行、展览、表演、放映、 -广播或通过信息网络传播本作品 创作演绎作品 -对本作品进行商业性使用 惟须遵守下列条件: -署名 — 您必须按照作者或者许可人指定的方式对作品进行署名。 -相同方式共享 — 如果您改变、转换本作品或者以本作品为基础进行创作, -您只能采用与本协议相同的许可协议发布基于本作品的演绎作品。` - -const txt_cjk = txt_cn + txt_jp + txt_kr -const txt_all = txt_vn + twoByteUtf8 + threeByteUtf8 + txt_cjk - -var txt_all_bytes = []byte(txt_all) diff --git a/vendor/golang.org/x/text/unicode/norm/readwriter_test.go b/vendor/golang.org/x/text/unicode/norm/readwriter_test.go deleted file mode 100644 index b7756ba24e..0000000000 --- a/vendor/golang.org/x/text/unicode/norm/readwriter_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2011 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 norm - -import ( - "bytes" - "fmt" - "testing" -) - -var bufSizes = []int{1, 2, 3, 4, 5, 6, 7, 8, 100, 101, 102, 103, 4000, 4001, 4002, 4003} - -func readFunc(size int) appendFunc { - return func(f Form, out []byte, s string) []byte { - out = append(out, s...) - r := f.Reader(bytes.NewBuffer(out)) - buf := make([]byte, size) - result := []byte{} - for n, err := 0, error(nil); err == nil; { - n, err = r.Read(buf) - result = append(result, buf[:n]...) - } - return result - } -} - -func TestReader(t *testing.T) { - for _, s := range bufSizes { - name := fmt.Sprintf("TestReader%d", s) - runNormTests(t, name, readFunc(s)) - } -} - -func writeFunc(size int) appendFunc { - return func(f Form, out []byte, s string) []byte { - in := append(out, s...) - result := new(bytes.Buffer) - w := f.Writer(result) - buf := make([]byte, size) - for n := 0; len(in) > 0; in = in[n:] { - n = copy(buf, in) - _, _ = w.Write(buf[:n]) - } - w.Close() - return result.Bytes() - } -} - -func TestWriter(t *testing.T) { - for _, s := range bufSizes { - name := fmt.Sprintf("TestWriter%d", s) - runNormTests(t, name, writeFunc(s)) - } -} diff --git a/vendor/golang.org/x/text/unicode/norm/tables.go b/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go similarity index 99% rename from vendor/golang.org/x/text/unicode/norm/tables.go rename to vendor/golang.org/x/text/unicode/norm/tables10.0.0.go index 316b093c53..44dd3978ca 100644 --- a/vendor/golang.org/x/text/unicode/norm/tables.go +++ b/vendor/golang.org/x/text/unicode/norm/tables10.0.0.go @@ -1,5 +1,7 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. +// +build go1.10 + package norm const ( diff --git a/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go b/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go new file mode 100644 index 0000000000..a01274a8e8 --- /dev/null +++ b/vendor/golang.org/x/text/unicode/norm/tables9.0.0.go @@ -0,0 +1,7633 @@ +// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +// +build !go1.10 + +package norm + +const ( + // Version is the Unicode edition from which the tables are derived. + Version = "9.0.0" + + // MaxTransformChunkSize indicates the maximum number of bytes that Transform + // may need to write atomically for any Form. Making a destination buffer at + // least this size ensures that Transform can always make progress and that + // the user does not need to grow the buffer on an ErrShortDst. + MaxTransformChunkSize = 35 + maxNonStarters*4 +) + +var ccc = [55]uint8{ + 0, 1, 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, 33, 34, 35, 36, + 84, 91, 103, 107, 118, 122, 129, 130, + 132, 202, 214, 216, 218, 220, 222, 224, + 226, 228, 230, 232, 233, 234, 240, +} + +const ( + firstMulti = 0x186D + firstCCC = 0x2C9E + endMulti = 0x2F60 + firstLeadingCCC = 0x49AE + firstCCCZeroExcept = 0x4A78 + firstStarterWithNLead = 0x4A9F + lastDecomp = 0x4AA1 + maxDecomp = 0x8000 +) + +// decomps: 19105 bytes +var decomps = [...]byte{ + // Bytes 0 - 3f + 0x00, 0x41, 0x20, 0x41, 0x21, 0x41, 0x22, 0x41, + 0x23, 0x41, 0x24, 0x41, 0x25, 0x41, 0x26, 0x41, + 0x27, 0x41, 0x28, 0x41, 0x29, 0x41, 0x2A, 0x41, + 0x2B, 0x41, 0x2C, 0x41, 0x2D, 0x41, 0x2E, 0x41, + 0x2F, 0x41, 0x30, 0x41, 0x31, 0x41, 0x32, 0x41, + 0x33, 0x41, 0x34, 0x41, 0x35, 0x41, 0x36, 0x41, + 0x37, 0x41, 0x38, 0x41, 0x39, 0x41, 0x3A, 0x41, + 0x3B, 0x41, 0x3C, 0x41, 0x3D, 0x41, 0x3E, 0x41, + // Bytes 40 - 7f + 0x3F, 0x41, 0x40, 0x41, 0x41, 0x41, 0x42, 0x41, + 0x43, 0x41, 0x44, 0x41, 0x45, 0x41, 0x46, 0x41, + 0x47, 0x41, 0x48, 0x41, 0x49, 0x41, 0x4A, 0x41, + 0x4B, 0x41, 0x4C, 0x41, 0x4D, 0x41, 0x4E, 0x41, + 0x4F, 0x41, 0x50, 0x41, 0x51, 0x41, 0x52, 0x41, + 0x53, 0x41, 0x54, 0x41, 0x55, 0x41, 0x56, 0x41, + 0x57, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5A, 0x41, + 0x5B, 0x41, 0x5C, 0x41, 0x5D, 0x41, 0x5E, 0x41, + // Bytes 80 - bf + 0x5F, 0x41, 0x60, 0x41, 0x61, 0x41, 0x62, 0x41, + 0x63, 0x41, 0x64, 0x41, 0x65, 0x41, 0x66, 0x41, + 0x67, 0x41, 0x68, 0x41, 0x69, 0x41, 0x6A, 0x41, + 0x6B, 0x41, 0x6C, 0x41, 0x6D, 0x41, 0x6E, 0x41, + 0x6F, 0x41, 0x70, 0x41, 0x71, 0x41, 0x72, 0x41, + 0x73, 0x41, 0x74, 0x41, 0x75, 0x41, 0x76, 0x41, + 0x77, 0x41, 0x78, 0x41, 0x79, 0x41, 0x7A, 0x41, + 0x7B, 0x41, 0x7C, 0x41, 0x7D, 0x41, 0x7E, 0x42, + // Bytes c0 - ff + 0xC2, 0xA2, 0x42, 0xC2, 0xA3, 0x42, 0xC2, 0xA5, + 0x42, 0xC2, 0xA6, 0x42, 0xC2, 0xAC, 0x42, 0xC2, + 0xB7, 0x42, 0xC3, 0x86, 0x42, 0xC3, 0xB0, 0x42, + 0xC4, 0xA6, 0x42, 0xC4, 0xA7, 0x42, 0xC4, 0xB1, + 0x42, 0xC5, 0x8B, 0x42, 0xC5, 0x93, 0x42, 0xC6, + 0x8E, 0x42, 0xC6, 0x90, 0x42, 0xC6, 0xAB, 0x42, + 0xC8, 0xA2, 0x42, 0xC8, 0xB7, 0x42, 0xC9, 0x90, + 0x42, 0xC9, 0x91, 0x42, 0xC9, 0x92, 0x42, 0xC9, + // Bytes 100 - 13f + 0x94, 0x42, 0xC9, 0x95, 0x42, 0xC9, 0x99, 0x42, + 0xC9, 0x9B, 0x42, 0xC9, 0x9C, 0x42, 0xC9, 0x9F, + 0x42, 0xC9, 0xA1, 0x42, 0xC9, 0xA3, 0x42, 0xC9, + 0xA5, 0x42, 0xC9, 0xA6, 0x42, 0xC9, 0xA8, 0x42, + 0xC9, 0xA9, 0x42, 0xC9, 0xAA, 0x42, 0xC9, 0xAB, + 0x42, 0xC9, 0xAD, 0x42, 0xC9, 0xAF, 0x42, 0xC9, + 0xB0, 0x42, 0xC9, 0xB1, 0x42, 0xC9, 0xB2, 0x42, + 0xC9, 0xB3, 0x42, 0xC9, 0xB4, 0x42, 0xC9, 0xB5, + // Bytes 140 - 17f + 0x42, 0xC9, 0xB8, 0x42, 0xC9, 0xB9, 0x42, 0xC9, + 0xBB, 0x42, 0xCA, 0x81, 0x42, 0xCA, 0x82, 0x42, + 0xCA, 0x83, 0x42, 0xCA, 0x89, 0x42, 0xCA, 0x8A, + 0x42, 0xCA, 0x8B, 0x42, 0xCA, 0x8C, 0x42, 0xCA, + 0x90, 0x42, 0xCA, 0x91, 0x42, 0xCA, 0x92, 0x42, + 0xCA, 0x95, 0x42, 0xCA, 0x9D, 0x42, 0xCA, 0x9F, + 0x42, 0xCA, 0xB9, 0x42, 0xCE, 0x91, 0x42, 0xCE, + 0x92, 0x42, 0xCE, 0x93, 0x42, 0xCE, 0x94, 0x42, + // Bytes 180 - 1bf + 0xCE, 0x95, 0x42, 0xCE, 0x96, 0x42, 0xCE, 0x97, + 0x42, 0xCE, 0x98, 0x42, 0xCE, 0x99, 0x42, 0xCE, + 0x9A, 0x42, 0xCE, 0x9B, 0x42, 0xCE, 0x9C, 0x42, + 0xCE, 0x9D, 0x42, 0xCE, 0x9E, 0x42, 0xCE, 0x9F, + 0x42, 0xCE, 0xA0, 0x42, 0xCE, 0xA1, 0x42, 0xCE, + 0xA3, 0x42, 0xCE, 0xA4, 0x42, 0xCE, 0xA5, 0x42, + 0xCE, 0xA6, 0x42, 0xCE, 0xA7, 0x42, 0xCE, 0xA8, + 0x42, 0xCE, 0xA9, 0x42, 0xCE, 0xB1, 0x42, 0xCE, + // Bytes 1c0 - 1ff + 0xB2, 0x42, 0xCE, 0xB3, 0x42, 0xCE, 0xB4, 0x42, + 0xCE, 0xB5, 0x42, 0xCE, 0xB6, 0x42, 0xCE, 0xB7, + 0x42, 0xCE, 0xB8, 0x42, 0xCE, 0xB9, 0x42, 0xCE, + 0xBA, 0x42, 0xCE, 0xBB, 0x42, 0xCE, 0xBC, 0x42, + 0xCE, 0xBD, 0x42, 0xCE, 0xBE, 0x42, 0xCE, 0xBF, + 0x42, 0xCF, 0x80, 0x42, 0xCF, 0x81, 0x42, 0xCF, + 0x82, 0x42, 0xCF, 0x83, 0x42, 0xCF, 0x84, 0x42, + 0xCF, 0x85, 0x42, 0xCF, 0x86, 0x42, 0xCF, 0x87, + // Bytes 200 - 23f + 0x42, 0xCF, 0x88, 0x42, 0xCF, 0x89, 0x42, 0xCF, + 0x9C, 0x42, 0xCF, 0x9D, 0x42, 0xD0, 0xBD, 0x42, + 0xD1, 0x8A, 0x42, 0xD1, 0x8C, 0x42, 0xD7, 0x90, + 0x42, 0xD7, 0x91, 0x42, 0xD7, 0x92, 0x42, 0xD7, + 0x93, 0x42, 0xD7, 0x94, 0x42, 0xD7, 0x9B, 0x42, + 0xD7, 0x9C, 0x42, 0xD7, 0x9D, 0x42, 0xD7, 0xA2, + 0x42, 0xD7, 0xA8, 0x42, 0xD7, 0xAA, 0x42, 0xD8, + 0xA1, 0x42, 0xD8, 0xA7, 0x42, 0xD8, 0xA8, 0x42, + // Bytes 240 - 27f + 0xD8, 0xA9, 0x42, 0xD8, 0xAA, 0x42, 0xD8, 0xAB, + 0x42, 0xD8, 0xAC, 0x42, 0xD8, 0xAD, 0x42, 0xD8, + 0xAE, 0x42, 0xD8, 0xAF, 0x42, 0xD8, 0xB0, 0x42, + 0xD8, 0xB1, 0x42, 0xD8, 0xB2, 0x42, 0xD8, 0xB3, + 0x42, 0xD8, 0xB4, 0x42, 0xD8, 0xB5, 0x42, 0xD8, + 0xB6, 0x42, 0xD8, 0xB7, 0x42, 0xD8, 0xB8, 0x42, + 0xD8, 0xB9, 0x42, 0xD8, 0xBA, 0x42, 0xD9, 0x81, + 0x42, 0xD9, 0x82, 0x42, 0xD9, 0x83, 0x42, 0xD9, + // Bytes 280 - 2bf + 0x84, 0x42, 0xD9, 0x85, 0x42, 0xD9, 0x86, 0x42, + 0xD9, 0x87, 0x42, 0xD9, 0x88, 0x42, 0xD9, 0x89, + 0x42, 0xD9, 0x8A, 0x42, 0xD9, 0xAE, 0x42, 0xD9, + 0xAF, 0x42, 0xD9, 0xB1, 0x42, 0xD9, 0xB9, 0x42, + 0xD9, 0xBA, 0x42, 0xD9, 0xBB, 0x42, 0xD9, 0xBE, + 0x42, 0xD9, 0xBF, 0x42, 0xDA, 0x80, 0x42, 0xDA, + 0x83, 0x42, 0xDA, 0x84, 0x42, 0xDA, 0x86, 0x42, + 0xDA, 0x87, 0x42, 0xDA, 0x88, 0x42, 0xDA, 0x8C, + // Bytes 2c0 - 2ff + 0x42, 0xDA, 0x8D, 0x42, 0xDA, 0x8E, 0x42, 0xDA, + 0x91, 0x42, 0xDA, 0x98, 0x42, 0xDA, 0xA1, 0x42, + 0xDA, 0xA4, 0x42, 0xDA, 0xA6, 0x42, 0xDA, 0xA9, + 0x42, 0xDA, 0xAD, 0x42, 0xDA, 0xAF, 0x42, 0xDA, + 0xB1, 0x42, 0xDA, 0xB3, 0x42, 0xDA, 0xBA, 0x42, + 0xDA, 0xBB, 0x42, 0xDA, 0xBE, 0x42, 0xDB, 0x81, + 0x42, 0xDB, 0x85, 0x42, 0xDB, 0x86, 0x42, 0xDB, + 0x87, 0x42, 0xDB, 0x88, 0x42, 0xDB, 0x89, 0x42, + // Bytes 300 - 33f + 0xDB, 0x8B, 0x42, 0xDB, 0x8C, 0x42, 0xDB, 0x90, + 0x42, 0xDB, 0x92, 0x43, 0xE0, 0xBC, 0x8B, 0x43, + 0xE1, 0x83, 0x9C, 0x43, 0xE1, 0x84, 0x80, 0x43, + 0xE1, 0x84, 0x81, 0x43, 0xE1, 0x84, 0x82, 0x43, + 0xE1, 0x84, 0x83, 0x43, 0xE1, 0x84, 0x84, 0x43, + 0xE1, 0x84, 0x85, 0x43, 0xE1, 0x84, 0x86, 0x43, + 0xE1, 0x84, 0x87, 0x43, 0xE1, 0x84, 0x88, 0x43, + 0xE1, 0x84, 0x89, 0x43, 0xE1, 0x84, 0x8A, 0x43, + // Bytes 340 - 37f + 0xE1, 0x84, 0x8B, 0x43, 0xE1, 0x84, 0x8C, 0x43, + 0xE1, 0x84, 0x8D, 0x43, 0xE1, 0x84, 0x8E, 0x43, + 0xE1, 0x84, 0x8F, 0x43, 0xE1, 0x84, 0x90, 0x43, + 0xE1, 0x84, 0x91, 0x43, 0xE1, 0x84, 0x92, 0x43, + 0xE1, 0x84, 0x94, 0x43, 0xE1, 0x84, 0x95, 0x43, + 0xE1, 0x84, 0x9A, 0x43, 0xE1, 0x84, 0x9C, 0x43, + 0xE1, 0x84, 0x9D, 0x43, 0xE1, 0x84, 0x9E, 0x43, + 0xE1, 0x84, 0xA0, 0x43, 0xE1, 0x84, 0xA1, 0x43, + // Bytes 380 - 3bf + 0xE1, 0x84, 0xA2, 0x43, 0xE1, 0x84, 0xA3, 0x43, + 0xE1, 0x84, 0xA7, 0x43, 0xE1, 0x84, 0xA9, 0x43, + 0xE1, 0x84, 0xAB, 0x43, 0xE1, 0x84, 0xAC, 0x43, + 0xE1, 0x84, 0xAD, 0x43, 0xE1, 0x84, 0xAE, 0x43, + 0xE1, 0x84, 0xAF, 0x43, 0xE1, 0x84, 0xB2, 0x43, + 0xE1, 0x84, 0xB6, 0x43, 0xE1, 0x85, 0x80, 0x43, + 0xE1, 0x85, 0x87, 0x43, 0xE1, 0x85, 0x8C, 0x43, + 0xE1, 0x85, 0x97, 0x43, 0xE1, 0x85, 0x98, 0x43, + // Bytes 3c0 - 3ff + 0xE1, 0x85, 0x99, 0x43, 0xE1, 0x85, 0xA0, 0x43, + 0xE1, 0x86, 0x84, 0x43, 0xE1, 0x86, 0x85, 0x43, + 0xE1, 0x86, 0x88, 0x43, 0xE1, 0x86, 0x91, 0x43, + 0xE1, 0x86, 0x92, 0x43, 0xE1, 0x86, 0x94, 0x43, + 0xE1, 0x86, 0x9E, 0x43, 0xE1, 0x86, 0xA1, 0x43, + 0xE1, 0x87, 0x87, 0x43, 0xE1, 0x87, 0x88, 0x43, + 0xE1, 0x87, 0x8C, 0x43, 0xE1, 0x87, 0x8E, 0x43, + 0xE1, 0x87, 0x93, 0x43, 0xE1, 0x87, 0x97, 0x43, + // Bytes 400 - 43f + 0xE1, 0x87, 0x99, 0x43, 0xE1, 0x87, 0x9D, 0x43, + 0xE1, 0x87, 0x9F, 0x43, 0xE1, 0x87, 0xB1, 0x43, + 0xE1, 0x87, 0xB2, 0x43, 0xE1, 0xB4, 0x82, 0x43, + 0xE1, 0xB4, 0x96, 0x43, 0xE1, 0xB4, 0x97, 0x43, + 0xE1, 0xB4, 0x9C, 0x43, 0xE1, 0xB4, 0x9D, 0x43, + 0xE1, 0xB4, 0xA5, 0x43, 0xE1, 0xB5, 0xBB, 0x43, + 0xE1, 0xB6, 0x85, 0x43, 0xE2, 0x80, 0x82, 0x43, + 0xE2, 0x80, 0x83, 0x43, 0xE2, 0x80, 0x90, 0x43, + // Bytes 440 - 47f + 0xE2, 0x80, 0x93, 0x43, 0xE2, 0x80, 0x94, 0x43, + 0xE2, 0x82, 0xA9, 0x43, 0xE2, 0x86, 0x90, 0x43, + 0xE2, 0x86, 0x91, 0x43, 0xE2, 0x86, 0x92, 0x43, + 0xE2, 0x86, 0x93, 0x43, 0xE2, 0x88, 0x82, 0x43, + 0xE2, 0x88, 0x87, 0x43, 0xE2, 0x88, 0x91, 0x43, + 0xE2, 0x88, 0x92, 0x43, 0xE2, 0x94, 0x82, 0x43, + 0xE2, 0x96, 0xA0, 0x43, 0xE2, 0x97, 0x8B, 0x43, + 0xE2, 0xA6, 0x85, 0x43, 0xE2, 0xA6, 0x86, 0x43, + // Bytes 480 - 4bf + 0xE2, 0xB5, 0xA1, 0x43, 0xE3, 0x80, 0x81, 0x43, + 0xE3, 0x80, 0x82, 0x43, 0xE3, 0x80, 0x88, 0x43, + 0xE3, 0x80, 0x89, 0x43, 0xE3, 0x80, 0x8A, 0x43, + 0xE3, 0x80, 0x8B, 0x43, 0xE3, 0x80, 0x8C, 0x43, + 0xE3, 0x80, 0x8D, 0x43, 0xE3, 0x80, 0x8E, 0x43, + 0xE3, 0x80, 0x8F, 0x43, 0xE3, 0x80, 0x90, 0x43, + 0xE3, 0x80, 0x91, 0x43, 0xE3, 0x80, 0x92, 0x43, + 0xE3, 0x80, 0x94, 0x43, 0xE3, 0x80, 0x95, 0x43, + // Bytes 4c0 - 4ff + 0xE3, 0x80, 0x96, 0x43, 0xE3, 0x80, 0x97, 0x43, + 0xE3, 0x82, 0xA1, 0x43, 0xE3, 0x82, 0xA2, 0x43, + 0xE3, 0x82, 0xA3, 0x43, 0xE3, 0x82, 0xA4, 0x43, + 0xE3, 0x82, 0xA5, 0x43, 0xE3, 0x82, 0xA6, 0x43, + 0xE3, 0x82, 0xA7, 0x43, 0xE3, 0x82, 0xA8, 0x43, + 0xE3, 0x82, 0xA9, 0x43, 0xE3, 0x82, 0xAA, 0x43, + 0xE3, 0x82, 0xAB, 0x43, 0xE3, 0x82, 0xAD, 0x43, + 0xE3, 0x82, 0xAF, 0x43, 0xE3, 0x82, 0xB1, 0x43, + // Bytes 500 - 53f + 0xE3, 0x82, 0xB3, 0x43, 0xE3, 0x82, 0xB5, 0x43, + 0xE3, 0x82, 0xB7, 0x43, 0xE3, 0x82, 0xB9, 0x43, + 0xE3, 0x82, 0xBB, 0x43, 0xE3, 0x82, 0xBD, 0x43, + 0xE3, 0x82, 0xBF, 0x43, 0xE3, 0x83, 0x81, 0x43, + 0xE3, 0x83, 0x83, 0x43, 0xE3, 0x83, 0x84, 0x43, + 0xE3, 0x83, 0x86, 0x43, 0xE3, 0x83, 0x88, 0x43, + 0xE3, 0x83, 0x8A, 0x43, 0xE3, 0x83, 0x8B, 0x43, + 0xE3, 0x83, 0x8C, 0x43, 0xE3, 0x83, 0x8D, 0x43, + // Bytes 540 - 57f + 0xE3, 0x83, 0x8E, 0x43, 0xE3, 0x83, 0x8F, 0x43, + 0xE3, 0x83, 0x92, 0x43, 0xE3, 0x83, 0x95, 0x43, + 0xE3, 0x83, 0x98, 0x43, 0xE3, 0x83, 0x9B, 0x43, + 0xE3, 0x83, 0x9E, 0x43, 0xE3, 0x83, 0x9F, 0x43, + 0xE3, 0x83, 0xA0, 0x43, 0xE3, 0x83, 0xA1, 0x43, + 0xE3, 0x83, 0xA2, 0x43, 0xE3, 0x83, 0xA3, 0x43, + 0xE3, 0x83, 0xA4, 0x43, 0xE3, 0x83, 0xA5, 0x43, + 0xE3, 0x83, 0xA6, 0x43, 0xE3, 0x83, 0xA7, 0x43, + // Bytes 580 - 5bf + 0xE3, 0x83, 0xA8, 0x43, 0xE3, 0x83, 0xA9, 0x43, + 0xE3, 0x83, 0xAA, 0x43, 0xE3, 0x83, 0xAB, 0x43, + 0xE3, 0x83, 0xAC, 0x43, 0xE3, 0x83, 0xAD, 0x43, + 0xE3, 0x83, 0xAF, 0x43, 0xE3, 0x83, 0xB0, 0x43, + 0xE3, 0x83, 0xB1, 0x43, 0xE3, 0x83, 0xB2, 0x43, + 0xE3, 0x83, 0xB3, 0x43, 0xE3, 0x83, 0xBB, 0x43, + 0xE3, 0x83, 0xBC, 0x43, 0xE3, 0x92, 0x9E, 0x43, + 0xE3, 0x92, 0xB9, 0x43, 0xE3, 0x92, 0xBB, 0x43, + // Bytes 5c0 - 5ff + 0xE3, 0x93, 0x9F, 0x43, 0xE3, 0x94, 0x95, 0x43, + 0xE3, 0x9B, 0xAE, 0x43, 0xE3, 0x9B, 0xBC, 0x43, + 0xE3, 0x9E, 0x81, 0x43, 0xE3, 0xA0, 0xAF, 0x43, + 0xE3, 0xA1, 0xA2, 0x43, 0xE3, 0xA1, 0xBC, 0x43, + 0xE3, 0xA3, 0x87, 0x43, 0xE3, 0xA3, 0xA3, 0x43, + 0xE3, 0xA4, 0x9C, 0x43, 0xE3, 0xA4, 0xBA, 0x43, + 0xE3, 0xA8, 0xAE, 0x43, 0xE3, 0xA9, 0xAC, 0x43, + 0xE3, 0xAB, 0xA4, 0x43, 0xE3, 0xAC, 0x88, 0x43, + // Bytes 600 - 63f + 0xE3, 0xAC, 0x99, 0x43, 0xE3, 0xAD, 0x89, 0x43, + 0xE3, 0xAE, 0x9D, 0x43, 0xE3, 0xB0, 0x98, 0x43, + 0xE3, 0xB1, 0x8E, 0x43, 0xE3, 0xB4, 0xB3, 0x43, + 0xE3, 0xB6, 0x96, 0x43, 0xE3, 0xBA, 0xAC, 0x43, + 0xE3, 0xBA, 0xB8, 0x43, 0xE3, 0xBC, 0x9B, 0x43, + 0xE3, 0xBF, 0xBC, 0x43, 0xE4, 0x80, 0x88, 0x43, + 0xE4, 0x80, 0x98, 0x43, 0xE4, 0x80, 0xB9, 0x43, + 0xE4, 0x81, 0x86, 0x43, 0xE4, 0x82, 0x96, 0x43, + // Bytes 640 - 67f + 0xE4, 0x83, 0xA3, 0x43, 0xE4, 0x84, 0xAF, 0x43, + 0xE4, 0x88, 0x82, 0x43, 0xE4, 0x88, 0xA7, 0x43, + 0xE4, 0x8A, 0xA0, 0x43, 0xE4, 0x8C, 0x81, 0x43, + 0xE4, 0x8C, 0xB4, 0x43, 0xE4, 0x8D, 0x99, 0x43, + 0xE4, 0x8F, 0x95, 0x43, 0xE4, 0x8F, 0x99, 0x43, + 0xE4, 0x90, 0x8B, 0x43, 0xE4, 0x91, 0xAB, 0x43, + 0xE4, 0x94, 0xAB, 0x43, 0xE4, 0x95, 0x9D, 0x43, + 0xE4, 0x95, 0xA1, 0x43, 0xE4, 0x95, 0xAB, 0x43, + // Bytes 680 - 6bf + 0xE4, 0x97, 0x97, 0x43, 0xE4, 0x97, 0xB9, 0x43, + 0xE4, 0x98, 0xB5, 0x43, 0xE4, 0x9A, 0xBE, 0x43, + 0xE4, 0x9B, 0x87, 0x43, 0xE4, 0xA6, 0x95, 0x43, + 0xE4, 0xA7, 0xA6, 0x43, 0xE4, 0xA9, 0xAE, 0x43, + 0xE4, 0xA9, 0xB6, 0x43, 0xE4, 0xAA, 0xB2, 0x43, + 0xE4, 0xAC, 0xB3, 0x43, 0xE4, 0xAF, 0x8E, 0x43, + 0xE4, 0xB3, 0x8E, 0x43, 0xE4, 0xB3, 0xAD, 0x43, + 0xE4, 0xB3, 0xB8, 0x43, 0xE4, 0xB5, 0x96, 0x43, + // Bytes 6c0 - 6ff + 0xE4, 0xB8, 0x80, 0x43, 0xE4, 0xB8, 0x81, 0x43, + 0xE4, 0xB8, 0x83, 0x43, 0xE4, 0xB8, 0x89, 0x43, + 0xE4, 0xB8, 0x8A, 0x43, 0xE4, 0xB8, 0x8B, 0x43, + 0xE4, 0xB8, 0x8D, 0x43, 0xE4, 0xB8, 0x99, 0x43, + 0xE4, 0xB8, 0xA6, 0x43, 0xE4, 0xB8, 0xA8, 0x43, + 0xE4, 0xB8, 0xAD, 0x43, 0xE4, 0xB8, 0xB2, 0x43, + 0xE4, 0xB8, 0xB6, 0x43, 0xE4, 0xB8, 0xB8, 0x43, + 0xE4, 0xB8, 0xB9, 0x43, 0xE4, 0xB8, 0xBD, 0x43, + // Bytes 700 - 73f + 0xE4, 0xB8, 0xBF, 0x43, 0xE4, 0xB9, 0x81, 0x43, + 0xE4, 0xB9, 0x99, 0x43, 0xE4, 0xB9, 0x9D, 0x43, + 0xE4, 0xBA, 0x82, 0x43, 0xE4, 0xBA, 0x85, 0x43, + 0xE4, 0xBA, 0x86, 0x43, 0xE4, 0xBA, 0x8C, 0x43, + 0xE4, 0xBA, 0x94, 0x43, 0xE4, 0xBA, 0xA0, 0x43, + 0xE4, 0xBA, 0xA4, 0x43, 0xE4, 0xBA, 0xAE, 0x43, + 0xE4, 0xBA, 0xBA, 0x43, 0xE4, 0xBB, 0x80, 0x43, + 0xE4, 0xBB, 0x8C, 0x43, 0xE4, 0xBB, 0xA4, 0x43, + // Bytes 740 - 77f + 0xE4, 0xBC, 0x81, 0x43, 0xE4, 0xBC, 0x91, 0x43, + 0xE4, 0xBD, 0xA0, 0x43, 0xE4, 0xBE, 0x80, 0x43, + 0xE4, 0xBE, 0x86, 0x43, 0xE4, 0xBE, 0x8B, 0x43, + 0xE4, 0xBE, 0xAE, 0x43, 0xE4, 0xBE, 0xBB, 0x43, + 0xE4, 0xBE, 0xBF, 0x43, 0xE5, 0x80, 0x82, 0x43, + 0xE5, 0x80, 0xAB, 0x43, 0xE5, 0x81, 0xBA, 0x43, + 0xE5, 0x82, 0x99, 0x43, 0xE5, 0x83, 0x8F, 0x43, + 0xE5, 0x83, 0x9A, 0x43, 0xE5, 0x83, 0xA7, 0x43, + // Bytes 780 - 7bf + 0xE5, 0x84, 0xAA, 0x43, 0xE5, 0x84, 0xBF, 0x43, + 0xE5, 0x85, 0x80, 0x43, 0xE5, 0x85, 0x85, 0x43, + 0xE5, 0x85, 0x8D, 0x43, 0xE5, 0x85, 0x94, 0x43, + 0xE5, 0x85, 0xA4, 0x43, 0xE5, 0x85, 0xA5, 0x43, + 0xE5, 0x85, 0xA7, 0x43, 0xE5, 0x85, 0xA8, 0x43, + 0xE5, 0x85, 0xA9, 0x43, 0xE5, 0x85, 0xAB, 0x43, + 0xE5, 0x85, 0xAD, 0x43, 0xE5, 0x85, 0xB7, 0x43, + 0xE5, 0x86, 0x80, 0x43, 0xE5, 0x86, 0x82, 0x43, + // Bytes 7c0 - 7ff + 0xE5, 0x86, 0x8D, 0x43, 0xE5, 0x86, 0x92, 0x43, + 0xE5, 0x86, 0x95, 0x43, 0xE5, 0x86, 0x96, 0x43, + 0xE5, 0x86, 0x97, 0x43, 0xE5, 0x86, 0x99, 0x43, + 0xE5, 0x86, 0xA4, 0x43, 0xE5, 0x86, 0xAB, 0x43, + 0xE5, 0x86, 0xAC, 0x43, 0xE5, 0x86, 0xB5, 0x43, + 0xE5, 0x86, 0xB7, 0x43, 0xE5, 0x87, 0x89, 0x43, + 0xE5, 0x87, 0x8C, 0x43, 0xE5, 0x87, 0x9C, 0x43, + 0xE5, 0x87, 0x9E, 0x43, 0xE5, 0x87, 0xA0, 0x43, + // Bytes 800 - 83f + 0xE5, 0x87, 0xB5, 0x43, 0xE5, 0x88, 0x80, 0x43, + 0xE5, 0x88, 0x83, 0x43, 0xE5, 0x88, 0x87, 0x43, + 0xE5, 0x88, 0x97, 0x43, 0xE5, 0x88, 0x9D, 0x43, + 0xE5, 0x88, 0xA9, 0x43, 0xE5, 0x88, 0xBA, 0x43, + 0xE5, 0x88, 0xBB, 0x43, 0xE5, 0x89, 0x86, 0x43, + 0xE5, 0x89, 0x8D, 0x43, 0xE5, 0x89, 0xB2, 0x43, + 0xE5, 0x89, 0xB7, 0x43, 0xE5, 0x8A, 0x89, 0x43, + 0xE5, 0x8A, 0x9B, 0x43, 0xE5, 0x8A, 0xA3, 0x43, + // Bytes 840 - 87f + 0xE5, 0x8A, 0xB3, 0x43, 0xE5, 0x8A, 0xB4, 0x43, + 0xE5, 0x8B, 0x87, 0x43, 0xE5, 0x8B, 0x89, 0x43, + 0xE5, 0x8B, 0x92, 0x43, 0xE5, 0x8B, 0x9E, 0x43, + 0xE5, 0x8B, 0xA4, 0x43, 0xE5, 0x8B, 0xB5, 0x43, + 0xE5, 0x8B, 0xB9, 0x43, 0xE5, 0x8B, 0xBA, 0x43, + 0xE5, 0x8C, 0x85, 0x43, 0xE5, 0x8C, 0x86, 0x43, + 0xE5, 0x8C, 0x95, 0x43, 0xE5, 0x8C, 0x97, 0x43, + 0xE5, 0x8C, 0x9A, 0x43, 0xE5, 0x8C, 0xB8, 0x43, + // Bytes 880 - 8bf + 0xE5, 0x8C, 0xBB, 0x43, 0xE5, 0x8C, 0xBF, 0x43, + 0xE5, 0x8D, 0x81, 0x43, 0xE5, 0x8D, 0x84, 0x43, + 0xE5, 0x8D, 0x85, 0x43, 0xE5, 0x8D, 0x89, 0x43, + 0xE5, 0x8D, 0x91, 0x43, 0xE5, 0x8D, 0x94, 0x43, + 0xE5, 0x8D, 0x9A, 0x43, 0xE5, 0x8D, 0x9C, 0x43, + 0xE5, 0x8D, 0xA9, 0x43, 0xE5, 0x8D, 0xB0, 0x43, + 0xE5, 0x8D, 0xB3, 0x43, 0xE5, 0x8D, 0xB5, 0x43, + 0xE5, 0x8D, 0xBD, 0x43, 0xE5, 0x8D, 0xBF, 0x43, + // Bytes 8c0 - 8ff + 0xE5, 0x8E, 0x82, 0x43, 0xE5, 0x8E, 0xB6, 0x43, + 0xE5, 0x8F, 0x83, 0x43, 0xE5, 0x8F, 0x88, 0x43, + 0xE5, 0x8F, 0x8A, 0x43, 0xE5, 0x8F, 0x8C, 0x43, + 0xE5, 0x8F, 0x9F, 0x43, 0xE5, 0x8F, 0xA3, 0x43, + 0xE5, 0x8F, 0xA5, 0x43, 0xE5, 0x8F, 0xAB, 0x43, + 0xE5, 0x8F, 0xAF, 0x43, 0xE5, 0x8F, 0xB1, 0x43, + 0xE5, 0x8F, 0xB3, 0x43, 0xE5, 0x90, 0x86, 0x43, + 0xE5, 0x90, 0x88, 0x43, 0xE5, 0x90, 0x8D, 0x43, + // Bytes 900 - 93f + 0xE5, 0x90, 0x8F, 0x43, 0xE5, 0x90, 0x9D, 0x43, + 0xE5, 0x90, 0xB8, 0x43, 0xE5, 0x90, 0xB9, 0x43, + 0xE5, 0x91, 0x82, 0x43, 0xE5, 0x91, 0x88, 0x43, + 0xE5, 0x91, 0xA8, 0x43, 0xE5, 0x92, 0x9E, 0x43, + 0xE5, 0x92, 0xA2, 0x43, 0xE5, 0x92, 0xBD, 0x43, + 0xE5, 0x93, 0xB6, 0x43, 0xE5, 0x94, 0x90, 0x43, + 0xE5, 0x95, 0x8F, 0x43, 0xE5, 0x95, 0x93, 0x43, + 0xE5, 0x95, 0x95, 0x43, 0xE5, 0x95, 0xA3, 0x43, + // Bytes 940 - 97f + 0xE5, 0x96, 0x84, 0x43, 0xE5, 0x96, 0x87, 0x43, + 0xE5, 0x96, 0x99, 0x43, 0xE5, 0x96, 0x9D, 0x43, + 0xE5, 0x96, 0xAB, 0x43, 0xE5, 0x96, 0xB3, 0x43, + 0xE5, 0x96, 0xB6, 0x43, 0xE5, 0x97, 0x80, 0x43, + 0xE5, 0x97, 0x82, 0x43, 0xE5, 0x97, 0xA2, 0x43, + 0xE5, 0x98, 0x86, 0x43, 0xE5, 0x99, 0x91, 0x43, + 0xE5, 0x99, 0xA8, 0x43, 0xE5, 0x99, 0xB4, 0x43, + 0xE5, 0x9B, 0x97, 0x43, 0xE5, 0x9B, 0x9B, 0x43, + // Bytes 980 - 9bf + 0xE5, 0x9B, 0xB9, 0x43, 0xE5, 0x9C, 0x96, 0x43, + 0xE5, 0x9C, 0x97, 0x43, 0xE5, 0x9C, 0x9F, 0x43, + 0xE5, 0x9C, 0xB0, 0x43, 0xE5, 0x9E, 0x8B, 0x43, + 0xE5, 0x9F, 0x8E, 0x43, 0xE5, 0x9F, 0xB4, 0x43, + 0xE5, 0xA0, 0x8D, 0x43, 0xE5, 0xA0, 0xB1, 0x43, + 0xE5, 0xA0, 0xB2, 0x43, 0xE5, 0xA1, 0x80, 0x43, + 0xE5, 0xA1, 0x9A, 0x43, 0xE5, 0xA1, 0x9E, 0x43, + 0xE5, 0xA2, 0xA8, 0x43, 0xE5, 0xA2, 0xAC, 0x43, + // Bytes 9c0 - 9ff + 0xE5, 0xA2, 0xB3, 0x43, 0xE5, 0xA3, 0x98, 0x43, + 0xE5, 0xA3, 0x9F, 0x43, 0xE5, 0xA3, 0xAB, 0x43, + 0xE5, 0xA3, 0xAE, 0x43, 0xE5, 0xA3, 0xB0, 0x43, + 0xE5, 0xA3, 0xB2, 0x43, 0xE5, 0xA3, 0xB7, 0x43, + 0xE5, 0xA4, 0x82, 0x43, 0xE5, 0xA4, 0x86, 0x43, + 0xE5, 0xA4, 0x8A, 0x43, 0xE5, 0xA4, 0x95, 0x43, + 0xE5, 0xA4, 0x9A, 0x43, 0xE5, 0xA4, 0x9C, 0x43, + 0xE5, 0xA4, 0xA2, 0x43, 0xE5, 0xA4, 0xA7, 0x43, + // Bytes a00 - a3f + 0xE5, 0xA4, 0xA9, 0x43, 0xE5, 0xA5, 0x84, 0x43, + 0xE5, 0xA5, 0x88, 0x43, 0xE5, 0xA5, 0x91, 0x43, + 0xE5, 0xA5, 0x94, 0x43, 0xE5, 0xA5, 0xA2, 0x43, + 0xE5, 0xA5, 0xB3, 0x43, 0xE5, 0xA7, 0x98, 0x43, + 0xE5, 0xA7, 0xAC, 0x43, 0xE5, 0xA8, 0x9B, 0x43, + 0xE5, 0xA8, 0xA7, 0x43, 0xE5, 0xA9, 0xA2, 0x43, + 0xE5, 0xA9, 0xA6, 0x43, 0xE5, 0xAA, 0xB5, 0x43, + 0xE5, 0xAC, 0x88, 0x43, 0xE5, 0xAC, 0xA8, 0x43, + // Bytes a40 - a7f + 0xE5, 0xAC, 0xBE, 0x43, 0xE5, 0xAD, 0x90, 0x43, + 0xE5, 0xAD, 0x97, 0x43, 0xE5, 0xAD, 0xA6, 0x43, + 0xE5, 0xAE, 0x80, 0x43, 0xE5, 0xAE, 0x85, 0x43, + 0xE5, 0xAE, 0x97, 0x43, 0xE5, 0xAF, 0x83, 0x43, + 0xE5, 0xAF, 0x98, 0x43, 0xE5, 0xAF, 0xA7, 0x43, + 0xE5, 0xAF, 0xAE, 0x43, 0xE5, 0xAF, 0xB3, 0x43, + 0xE5, 0xAF, 0xB8, 0x43, 0xE5, 0xAF, 0xBF, 0x43, + 0xE5, 0xB0, 0x86, 0x43, 0xE5, 0xB0, 0x8F, 0x43, + // Bytes a80 - abf + 0xE5, 0xB0, 0xA2, 0x43, 0xE5, 0xB0, 0xB8, 0x43, + 0xE5, 0xB0, 0xBF, 0x43, 0xE5, 0xB1, 0xA0, 0x43, + 0xE5, 0xB1, 0xA2, 0x43, 0xE5, 0xB1, 0xA4, 0x43, + 0xE5, 0xB1, 0xA5, 0x43, 0xE5, 0xB1, 0xAE, 0x43, + 0xE5, 0xB1, 0xB1, 0x43, 0xE5, 0xB2, 0x8D, 0x43, + 0xE5, 0xB3, 0x80, 0x43, 0xE5, 0xB4, 0x99, 0x43, + 0xE5, 0xB5, 0x83, 0x43, 0xE5, 0xB5, 0x90, 0x43, + 0xE5, 0xB5, 0xAB, 0x43, 0xE5, 0xB5, 0xAE, 0x43, + // Bytes ac0 - aff + 0xE5, 0xB5, 0xBC, 0x43, 0xE5, 0xB6, 0xB2, 0x43, + 0xE5, 0xB6, 0xBA, 0x43, 0xE5, 0xB7, 0x9B, 0x43, + 0xE5, 0xB7, 0xA1, 0x43, 0xE5, 0xB7, 0xA2, 0x43, + 0xE5, 0xB7, 0xA5, 0x43, 0xE5, 0xB7, 0xA6, 0x43, + 0xE5, 0xB7, 0xB1, 0x43, 0xE5, 0xB7, 0xBD, 0x43, + 0xE5, 0xB7, 0xBE, 0x43, 0xE5, 0xB8, 0xA8, 0x43, + 0xE5, 0xB8, 0xBD, 0x43, 0xE5, 0xB9, 0xA9, 0x43, + 0xE5, 0xB9, 0xB2, 0x43, 0xE5, 0xB9, 0xB4, 0x43, + // Bytes b00 - b3f + 0xE5, 0xB9, 0xBA, 0x43, 0xE5, 0xB9, 0xBC, 0x43, + 0xE5, 0xB9, 0xBF, 0x43, 0xE5, 0xBA, 0xA6, 0x43, + 0xE5, 0xBA, 0xB0, 0x43, 0xE5, 0xBA, 0xB3, 0x43, + 0xE5, 0xBA, 0xB6, 0x43, 0xE5, 0xBB, 0x89, 0x43, + 0xE5, 0xBB, 0x8A, 0x43, 0xE5, 0xBB, 0x92, 0x43, + 0xE5, 0xBB, 0x93, 0x43, 0xE5, 0xBB, 0x99, 0x43, + 0xE5, 0xBB, 0xAC, 0x43, 0xE5, 0xBB, 0xB4, 0x43, + 0xE5, 0xBB, 0xBE, 0x43, 0xE5, 0xBC, 0x84, 0x43, + // Bytes b40 - b7f + 0xE5, 0xBC, 0x8B, 0x43, 0xE5, 0xBC, 0x93, 0x43, + 0xE5, 0xBC, 0xA2, 0x43, 0xE5, 0xBD, 0x90, 0x43, + 0xE5, 0xBD, 0x93, 0x43, 0xE5, 0xBD, 0xA1, 0x43, + 0xE5, 0xBD, 0xA2, 0x43, 0xE5, 0xBD, 0xA9, 0x43, + 0xE5, 0xBD, 0xAB, 0x43, 0xE5, 0xBD, 0xB3, 0x43, + 0xE5, 0xBE, 0x8B, 0x43, 0xE5, 0xBE, 0x8C, 0x43, + 0xE5, 0xBE, 0x97, 0x43, 0xE5, 0xBE, 0x9A, 0x43, + 0xE5, 0xBE, 0xA9, 0x43, 0xE5, 0xBE, 0xAD, 0x43, + // Bytes b80 - bbf + 0xE5, 0xBF, 0x83, 0x43, 0xE5, 0xBF, 0x8D, 0x43, + 0xE5, 0xBF, 0x97, 0x43, 0xE5, 0xBF, 0xB5, 0x43, + 0xE5, 0xBF, 0xB9, 0x43, 0xE6, 0x80, 0x92, 0x43, + 0xE6, 0x80, 0x9C, 0x43, 0xE6, 0x81, 0xB5, 0x43, + 0xE6, 0x82, 0x81, 0x43, 0xE6, 0x82, 0x94, 0x43, + 0xE6, 0x83, 0x87, 0x43, 0xE6, 0x83, 0x98, 0x43, + 0xE6, 0x83, 0xA1, 0x43, 0xE6, 0x84, 0x88, 0x43, + 0xE6, 0x85, 0x84, 0x43, 0xE6, 0x85, 0x88, 0x43, + // Bytes bc0 - bff + 0xE6, 0x85, 0x8C, 0x43, 0xE6, 0x85, 0x8E, 0x43, + 0xE6, 0x85, 0xA0, 0x43, 0xE6, 0x85, 0xA8, 0x43, + 0xE6, 0x85, 0xBA, 0x43, 0xE6, 0x86, 0x8E, 0x43, + 0xE6, 0x86, 0x90, 0x43, 0xE6, 0x86, 0xA4, 0x43, + 0xE6, 0x86, 0xAF, 0x43, 0xE6, 0x86, 0xB2, 0x43, + 0xE6, 0x87, 0x9E, 0x43, 0xE6, 0x87, 0xB2, 0x43, + 0xE6, 0x87, 0xB6, 0x43, 0xE6, 0x88, 0x80, 0x43, + 0xE6, 0x88, 0x88, 0x43, 0xE6, 0x88, 0x90, 0x43, + // Bytes c00 - c3f + 0xE6, 0x88, 0x9B, 0x43, 0xE6, 0x88, 0xAE, 0x43, + 0xE6, 0x88, 0xB4, 0x43, 0xE6, 0x88, 0xB6, 0x43, + 0xE6, 0x89, 0x8B, 0x43, 0xE6, 0x89, 0x93, 0x43, + 0xE6, 0x89, 0x9D, 0x43, 0xE6, 0x8A, 0x95, 0x43, + 0xE6, 0x8A, 0xB1, 0x43, 0xE6, 0x8B, 0x89, 0x43, + 0xE6, 0x8B, 0x8F, 0x43, 0xE6, 0x8B, 0x93, 0x43, + 0xE6, 0x8B, 0x94, 0x43, 0xE6, 0x8B, 0xBC, 0x43, + 0xE6, 0x8B, 0xBE, 0x43, 0xE6, 0x8C, 0x87, 0x43, + // Bytes c40 - c7f + 0xE6, 0x8C, 0xBD, 0x43, 0xE6, 0x8D, 0x90, 0x43, + 0xE6, 0x8D, 0x95, 0x43, 0xE6, 0x8D, 0xA8, 0x43, + 0xE6, 0x8D, 0xBB, 0x43, 0xE6, 0x8E, 0x83, 0x43, + 0xE6, 0x8E, 0xA0, 0x43, 0xE6, 0x8E, 0xA9, 0x43, + 0xE6, 0x8F, 0x84, 0x43, 0xE6, 0x8F, 0x85, 0x43, + 0xE6, 0x8F, 0xA4, 0x43, 0xE6, 0x90, 0x9C, 0x43, + 0xE6, 0x90, 0xA2, 0x43, 0xE6, 0x91, 0x92, 0x43, + 0xE6, 0x91, 0xA9, 0x43, 0xE6, 0x91, 0xB7, 0x43, + // Bytes c80 - cbf + 0xE6, 0x91, 0xBE, 0x43, 0xE6, 0x92, 0x9A, 0x43, + 0xE6, 0x92, 0x9D, 0x43, 0xE6, 0x93, 0x84, 0x43, + 0xE6, 0x94, 0xAF, 0x43, 0xE6, 0x94, 0xB4, 0x43, + 0xE6, 0x95, 0x8F, 0x43, 0xE6, 0x95, 0x96, 0x43, + 0xE6, 0x95, 0xAC, 0x43, 0xE6, 0x95, 0xB8, 0x43, + 0xE6, 0x96, 0x87, 0x43, 0xE6, 0x96, 0x97, 0x43, + 0xE6, 0x96, 0x99, 0x43, 0xE6, 0x96, 0xA4, 0x43, + 0xE6, 0x96, 0xB0, 0x43, 0xE6, 0x96, 0xB9, 0x43, + // Bytes cc0 - cff + 0xE6, 0x97, 0x85, 0x43, 0xE6, 0x97, 0xA0, 0x43, + 0xE6, 0x97, 0xA2, 0x43, 0xE6, 0x97, 0xA3, 0x43, + 0xE6, 0x97, 0xA5, 0x43, 0xE6, 0x98, 0x93, 0x43, + 0xE6, 0x98, 0xA0, 0x43, 0xE6, 0x99, 0x89, 0x43, + 0xE6, 0x99, 0xB4, 0x43, 0xE6, 0x9A, 0x88, 0x43, + 0xE6, 0x9A, 0x91, 0x43, 0xE6, 0x9A, 0x9C, 0x43, + 0xE6, 0x9A, 0xB4, 0x43, 0xE6, 0x9B, 0x86, 0x43, + 0xE6, 0x9B, 0xB0, 0x43, 0xE6, 0x9B, 0xB4, 0x43, + // Bytes d00 - d3f + 0xE6, 0x9B, 0xB8, 0x43, 0xE6, 0x9C, 0x80, 0x43, + 0xE6, 0x9C, 0x88, 0x43, 0xE6, 0x9C, 0x89, 0x43, + 0xE6, 0x9C, 0x97, 0x43, 0xE6, 0x9C, 0x9B, 0x43, + 0xE6, 0x9C, 0xA1, 0x43, 0xE6, 0x9C, 0xA8, 0x43, + 0xE6, 0x9D, 0x8E, 0x43, 0xE6, 0x9D, 0x93, 0x43, + 0xE6, 0x9D, 0x96, 0x43, 0xE6, 0x9D, 0x9E, 0x43, + 0xE6, 0x9D, 0xBB, 0x43, 0xE6, 0x9E, 0x85, 0x43, + 0xE6, 0x9E, 0x97, 0x43, 0xE6, 0x9F, 0xB3, 0x43, + // Bytes d40 - d7f + 0xE6, 0x9F, 0xBA, 0x43, 0xE6, 0xA0, 0x97, 0x43, + 0xE6, 0xA0, 0x9F, 0x43, 0xE6, 0xA0, 0xAA, 0x43, + 0xE6, 0xA1, 0x92, 0x43, 0xE6, 0xA2, 0x81, 0x43, + 0xE6, 0xA2, 0x85, 0x43, 0xE6, 0xA2, 0x8E, 0x43, + 0xE6, 0xA2, 0xA8, 0x43, 0xE6, 0xA4, 0x94, 0x43, + 0xE6, 0xA5, 0x82, 0x43, 0xE6, 0xA6, 0xA3, 0x43, + 0xE6, 0xA7, 0xAA, 0x43, 0xE6, 0xA8, 0x82, 0x43, + 0xE6, 0xA8, 0x93, 0x43, 0xE6, 0xAA, 0xA8, 0x43, + // Bytes d80 - dbf + 0xE6, 0xAB, 0x93, 0x43, 0xE6, 0xAB, 0x9B, 0x43, + 0xE6, 0xAC, 0x84, 0x43, 0xE6, 0xAC, 0xA0, 0x43, + 0xE6, 0xAC, 0xA1, 0x43, 0xE6, 0xAD, 0x94, 0x43, + 0xE6, 0xAD, 0xA2, 0x43, 0xE6, 0xAD, 0xA3, 0x43, + 0xE6, 0xAD, 0xB2, 0x43, 0xE6, 0xAD, 0xB7, 0x43, + 0xE6, 0xAD, 0xB9, 0x43, 0xE6, 0xAE, 0x9F, 0x43, + 0xE6, 0xAE, 0xAE, 0x43, 0xE6, 0xAE, 0xB3, 0x43, + 0xE6, 0xAE, 0xBA, 0x43, 0xE6, 0xAE, 0xBB, 0x43, + // Bytes dc0 - dff + 0xE6, 0xAF, 0x8B, 0x43, 0xE6, 0xAF, 0x8D, 0x43, + 0xE6, 0xAF, 0x94, 0x43, 0xE6, 0xAF, 0x9B, 0x43, + 0xE6, 0xB0, 0x8F, 0x43, 0xE6, 0xB0, 0x94, 0x43, + 0xE6, 0xB0, 0xB4, 0x43, 0xE6, 0xB1, 0x8E, 0x43, + 0xE6, 0xB1, 0xA7, 0x43, 0xE6, 0xB2, 0x88, 0x43, + 0xE6, 0xB2, 0xBF, 0x43, 0xE6, 0xB3, 0x8C, 0x43, + 0xE6, 0xB3, 0x8D, 0x43, 0xE6, 0xB3, 0xA5, 0x43, + 0xE6, 0xB3, 0xA8, 0x43, 0xE6, 0xB4, 0x96, 0x43, + // Bytes e00 - e3f + 0xE6, 0xB4, 0x9B, 0x43, 0xE6, 0xB4, 0x9E, 0x43, + 0xE6, 0xB4, 0xB4, 0x43, 0xE6, 0xB4, 0xBE, 0x43, + 0xE6, 0xB5, 0x81, 0x43, 0xE6, 0xB5, 0xA9, 0x43, + 0xE6, 0xB5, 0xAA, 0x43, 0xE6, 0xB5, 0xB7, 0x43, + 0xE6, 0xB5, 0xB8, 0x43, 0xE6, 0xB6, 0x85, 0x43, + 0xE6, 0xB7, 0x8B, 0x43, 0xE6, 0xB7, 0x9A, 0x43, + 0xE6, 0xB7, 0xAA, 0x43, 0xE6, 0xB7, 0xB9, 0x43, + 0xE6, 0xB8, 0x9A, 0x43, 0xE6, 0xB8, 0xAF, 0x43, + // Bytes e40 - e7f + 0xE6, 0xB9, 0xAE, 0x43, 0xE6, 0xBA, 0x80, 0x43, + 0xE6, 0xBA, 0x9C, 0x43, 0xE6, 0xBA, 0xBA, 0x43, + 0xE6, 0xBB, 0x87, 0x43, 0xE6, 0xBB, 0x8B, 0x43, + 0xE6, 0xBB, 0x91, 0x43, 0xE6, 0xBB, 0x9B, 0x43, + 0xE6, 0xBC, 0x8F, 0x43, 0xE6, 0xBC, 0x94, 0x43, + 0xE6, 0xBC, 0xA2, 0x43, 0xE6, 0xBC, 0xA3, 0x43, + 0xE6, 0xBD, 0xAE, 0x43, 0xE6, 0xBF, 0x86, 0x43, + 0xE6, 0xBF, 0xAB, 0x43, 0xE6, 0xBF, 0xBE, 0x43, + // Bytes e80 - ebf + 0xE7, 0x80, 0x9B, 0x43, 0xE7, 0x80, 0x9E, 0x43, + 0xE7, 0x80, 0xB9, 0x43, 0xE7, 0x81, 0x8A, 0x43, + 0xE7, 0x81, 0xAB, 0x43, 0xE7, 0x81, 0xB0, 0x43, + 0xE7, 0x81, 0xB7, 0x43, 0xE7, 0x81, 0xBD, 0x43, + 0xE7, 0x82, 0x99, 0x43, 0xE7, 0x82, 0xAD, 0x43, + 0xE7, 0x83, 0x88, 0x43, 0xE7, 0x83, 0x99, 0x43, + 0xE7, 0x84, 0xA1, 0x43, 0xE7, 0x85, 0x85, 0x43, + 0xE7, 0x85, 0x89, 0x43, 0xE7, 0x85, 0xAE, 0x43, + // Bytes ec0 - eff + 0xE7, 0x86, 0x9C, 0x43, 0xE7, 0x87, 0x8E, 0x43, + 0xE7, 0x87, 0x90, 0x43, 0xE7, 0x88, 0x90, 0x43, + 0xE7, 0x88, 0x9B, 0x43, 0xE7, 0x88, 0xA8, 0x43, + 0xE7, 0x88, 0xAA, 0x43, 0xE7, 0x88, 0xAB, 0x43, + 0xE7, 0x88, 0xB5, 0x43, 0xE7, 0x88, 0xB6, 0x43, + 0xE7, 0x88, 0xBB, 0x43, 0xE7, 0x88, 0xBF, 0x43, + 0xE7, 0x89, 0x87, 0x43, 0xE7, 0x89, 0x90, 0x43, + 0xE7, 0x89, 0x99, 0x43, 0xE7, 0x89, 0x9B, 0x43, + // Bytes f00 - f3f + 0xE7, 0x89, 0xA2, 0x43, 0xE7, 0x89, 0xB9, 0x43, + 0xE7, 0x8A, 0x80, 0x43, 0xE7, 0x8A, 0x95, 0x43, + 0xE7, 0x8A, 0xAC, 0x43, 0xE7, 0x8A, 0xAF, 0x43, + 0xE7, 0x8B, 0x80, 0x43, 0xE7, 0x8B, 0xBC, 0x43, + 0xE7, 0x8C, 0xAA, 0x43, 0xE7, 0x8D, 0xB5, 0x43, + 0xE7, 0x8D, 0xBA, 0x43, 0xE7, 0x8E, 0x84, 0x43, + 0xE7, 0x8E, 0x87, 0x43, 0xE7, 0x8E, 0x89, 0x43, + 0xE7, 0x8E, 0x8B, 0x43, 0xE7, 0x8E, 0xA5, 0x43, + // Bytes f40 - f7f + 0xE7, 0x8E, 0xB2, 0x43, 0xE7, 0x8F, 0x9E, 0x43, + 0xE7, 0x90, 0x86, 0x43, 0xE7, 0x90, 0x89, 0x43, + 0xE7, 0x90, 0xA2, 0x43, 0xE7, 0x91, 0x87, 0x43, + 0xE7, 0x91, 0x9C, 0x43, 0xE7, 0x91, 0xA9, 0x43, + 0xE7, 0x91, 0xB1, 0x43, 0xE7, 0x92, 0x85, 0x43, + 0xE7, 0x92, 0x89, 0x43, 0xE7, 0x92, 0x98, 0x43, + 0xE7, 0x93, 0x8A, 0x43, 0xE7, 0x93, 0x9C, 0x43, + 0xE7, 0x93, 0xA6, 0x43, 0xE7, 0x94, 0x86, 0x43, + // Bytes f80 - fbf + 0xE7, 0x94, 0x98, 0x43, 0xE7, 0x94, 0x9F, 0x43, + 0xE7, 0x94, 0xA4, 0x43, 0xE7, 0x94, 0xA8, 0x43, + 0xE7, 0x94, 0xB0, 0x43, 0xE7, 0x94, 0xB2, 0x43, + 0xE7, 0x94, 0xB3, 0x43, 0xE7, 0x94, 0xB7, 0x43, + 0xE7, 0x94, 0xBB, 0x43, 0xE7, 0x94, 0xBE, 0x43, + 0xE7, 0x95, 0x99, 0x43, 0xE7, 0x95, 0xA5, 0x43, + 0xE7, 0x95, 0xB0, 0x43, 0xE7, 0x96, 0x8B, 0x43, + 0xE7, 0x96, 0x92, 0x43, 0xE7, 0x97, 0xA2, 0x43, + // Bytes fc0 - fff + 0xE7, 0x98, 0x90, 0x43, 0xE7, 0x98, 0x9D, 0x43, + 0xE7, 0x98, 0x9F, 0x43, 0xE7, 0x99, 0x82, 0x43, + 0xE7, 0x99, 0xA9, 0x43, 0xE7, 0x99, 0xB6, 0x43, + 0xE7, 0x99, 0xBD, 0x43, 0xE7, 0x9A, 0xAE, 0x43, + 0xE7, 0x9A, 0xBF, 0x43, 0xE7, 0x9B, 0x8A, 0x43, + 0xE7, 0x9B, 0x9B, 0x43, 0xE7, 0x9B, 0xA3, 0x43, + 0xE7, 0x9B, 0xA7, 0x43, 0xE7, 0x9B, 0xAE, 0x43, + 0xE7, 0x9B, 0xB4, 0x43, 0xE7, 0x9C, 0x81, 0x43, + // Bytes 1000 - 103f + 0xE7, 0x9C, 0x9E, 0x43, 0xE7, 0x9C, 0x9F, 0x43, + 0xE7, 0x9D, 0x80, 0x43, 0xE7, 0x9D, 0x8A, 0x43, + 0xE7, 0x9E, 0x8B, 0x43, 0xE7, 0x9E, 0xA7, 0x43, + 0xE7, 0x9F, 0x9B, 0x43, 0xE7, 0x9F, 0xA2, 0x43, + 0xE7, 0x9F, 0xB3, 0x43, 0xE7, 0xA1, 0x8E, 0x43, + 0xE7, 0xA1, 0xAB, 0x43, 0xE7, 0xA2, 0x8C, 0x43, + 0xE7, 0xA2, 0x91, 0x43, 0xE7, 0xA3, 0x8A, 0x43, + 0xE7, 0xA3, 0x8C, 0x43, 0xE7, 0xA3, 0xBB, 0x43, + // Bytes 1040 - 107f + 0xE7, 0xA4, 0xAA, 0x43, 0xE7, 0xA4, 0xBA, 0x43, + 0xE7, 0xA4, 0xBC, 0x43, 0xE7, 0xA4, 0xBE, 0x43, + 0xE7, 0xA5, 0x88, 0x43, 0xE7, 0xA5, 0x89, 0x43, + 0xE7, 0xA5, 0x90, 0x43, 0xE7, 0xA5, 0x96, 0x43, + 0xE7, 0xA5, 0x9D, 0x43, 0xE7, 0xA5, 0x9E, 0x43, + 0xE7, 0xA5, 0xA5, 0x43, 0xE7, 0xA5, 0xBF, 0x43, + 0xE7, 0xA6, 0x81, 0x43, 0xE7, 0xA6, 0x8D, 0x43, + 0xE7, 0xA6, 0x8E, 0x43, 0xE7, 0xA6, 0x8F, 0x43, + // Bytes 1080 - 10bf + 0xE7, 0xA6, 0xAE, 0x43, 0xE7, 0xA6, 0xB8, 0x43, + 0xE7, 0xA6, 0xBE, 0x43, 0xE7, 0xA7, 0x8A, 0x43, + 0xE7, 0xA7, 0x98, 0x43, 0xE7, 0xA7, 0xAB, 0x43, + 0xE7, 0xA8, 0x9C, 0x43, 0xE7, 0xA9, 0x80, 0x43, + 0xE7, 0xA9, 0x8A, 0x43, 0xE7, 0xA9, 0x8F, 0x43, + 0xE7, 0xA9, 0xB4, 0x43, 0xE7, 0xA9, 0xBA, 0x43, + 0xE7, 0xAA, 0x81, 0x43, 0xE7, 0xAA, 0xB1, 0x43, + 0xE7, 0xAB, 0x8B, 0x43, 0xE7, 0xAB, 0xAE, 0x43, + // Bytes 10c0 - 10ff + 0xE7, 0xAB, 0xB9, 0x43, 0xE7, 0xAC, 0xA0, 0x43, + 0xE7, 0xAE, 0x8F, 0x43, 0xE7, 0xAF, 0x80, 0x43, + 0xE7, 0xAF, 0x86, 0x43, 0xE7, 0xAF, 0x89, 0x43, + 0xE7, 0xB0, 0xBE, 0x43, 0xE7, 0xB1, 0xA0, 0x43, + 0xE7, 0xB1, 0xB3, 0x43, 0xE7, 0xB1, 0xBB, 0x43, + 0xE7, 0xB2, 0x92, 0x43, 0xE7, 0xB2, 0xBE, 0x43, + 0xE7, 0xB3, 0x92, 0x43, 0xE7, 0xB3, 0x96, 0x43, + 0xE7, 0xB3, 0xA3, 0x43, 0xE7, 0xB3, 0xA7, 0x43, + // Bytes 1100 - 113f + 0xE7, 0xB3, 0xA8, 0x43, 0xE7, 0xB3, 0xB8, 0x43, + 0xE7, 0xB4, 0x80, 0x43, 0xE7, 0xB4, 0x90, 0x43, + 0xE7, 0xB4, 0xA2, 0x43, 0xE7, 0xB4, 0xAF, 0x43, + 0xE7, 0xB5, 0x82, 0x43, 0xE7, 0xB5, 0x9B, 0x43, + 0xE7, 0xB5, 0xA3, 0x43, 0xE7, 0xB6, 0xA0, 0x43, + 0xE7, 0xB6, 0xBE, 0x43, 0xE7, 0xB7, 0x87, 0x43, + 0xE7, 0xB7, 0xB4, 0x43, 0xE7, 0xB8, 0x82, 0x43, + 0xE7, 0xB8, 0x89, 0x43, 0xE7, 0xB8, 0xB7, 0x43, + // Bytes 1140 - 117f + 0xE7, 0xB9, 0x81, 0x43, 0xE7, 0xB9, 0x85, 0x43, + 0xE7, 0xBC, 0xB6, 0x43, 0xE7, 0xBC, 0xBE, 0x43, + 0xE7, 0xBD, 0x91, 0x43, 0xE7, 0xBD, 0xB2, 0x43, + 0xE7, 0xBD, 0xB9, 0x43, 0xE7, 0xBD, 0xBA, 0x43, + 0xE7, 0xBE, 0x85, 0x43, 0xE7, 0xBE, 0x8A, 0x43, + 0xE7, 0xBE, 0x95, 0x43, 0xE7, 0xBE, 0x9A, 0x43, + 0xE7, 0xBE, 0xBD, 0x43, 0xE7, 0xBF, 0xBA, 0x43, + 0xE8, 0x80, 0x81, 0x43, 0xE8, 0x80, 0x85, 0x43, + // Bytes 1180 - 11bf + 0xE8, 0x80, 0x8C, 0x43, 0xE8, 0x80, 0x92, 0x43, + 0xE8, 0x80, 0xB3, 0x43, 0xE8, 0x81, 0x86, 0x43, + 0xE8, 0x81, 0xA0, 0x43, 0xE8, 0x81, 0xAF, 0x43, + 0xE8, 0x81, 0xB0, 0x43, 0xE8, 0x81, 0xBE, 0x43, + 0xE8, 0x81, 0xBF, 0x43, 0xE8, 0x82, 0x89, 0x43, + 0xE8, 0x82, 0x8B, 0x43, 0xE8, 0x82, 0xAD, 0x43, + 0xE8, 0x82, 0xB2, 0x43, 0xE8, 0x84, 0x83, 0x43, + 0xE8, 0x84, 0xBE, 0x43, 0xE8, 0x87, 0x98, 0x43, + // Bytes 11c0 - 11ff + 0xE8, 0x87, 0xA3, 0x43, 0xE8, 0x87, 0xA8, 0x43, + 0xE8, 0x87, 0xAA, 0x43, 0xE8, 0x87, 0xAD, 0x43, + 0xE8, 0x87, 0xB3, 0x43, 0xE8, 0x87, 0xBC, 0x43, + 0xE8, 0x88, 0x81, 0x43, 0xE8, 0x88, 0x84, 0x43, + 0xE8, 0x88, 0x8C, 0x43, 0xE8, 0x88, 0x98, 0x43, + 0xE8, 0x88, 0x9B, 0x43, 0xE8, 0x88, 0x9F, 0x43, + 0xE8, 0x89, 0xAE, 0x43, 0xE8, 0x89, 0xAF, 0x43, + 0xE8, 0x89, 0xB2, 0x43, 0xE8, 0x89, 0xB8, 0x43, + // Bytes 1200 - 123f + 0xE8, 0x89, 0xB9, 0x43, 0xE8, 0x8A, 0x8B, 0x43, + 0xE8, 0x8A, 0x91, 0x43, 0xE8, 0x8A, 0x9D, 0x43, + 0xE8, 0x8A, 0xB1, 0x43, 0xE8, 0x8A, 0xB3, 0x43, + 0xE8, 0x8A, 0xBD, 0x43, 0xE8, 0x8B, 0xA5, 0x43, + 0xE8, 0x8B, 0xA6, 0x43, 0xE8, 0x8C, 0x9D, 0x43, + 0xE8, 0x8C, 0xA3, 0x43, 0xE8, 0x8C, 0xB6, 0x43, + 0xE8, 0x8D, 0x92, 0x43, 0xE8, 0x8D, 0x93, 0x43, + 0xE8, 0x8D, 0xA3, 0x43, 0xE8, 0x8E, 0xAD, 0x43, + // Bytes 1240 - 127f + 0xE8, 0x8E, 0xBD, 0x43, 0xE8, 0x8F, 0x89, 0x43, + 0xE8, 0x8F, 0x8A, 0x43, 0xE8, 0x8F, 0x8C, 0x43, + 0xE8, 0x8F, 0x9C, 0x43, 0xE8, 0x8F, 0xA7, 0x43, + 0xE8, 0x8F, 0xAF, 0x43, 0xE8, 0x8F, 0xB1, 0x43, + 0xE8, 0x90, 0xBD, 0x43, 0xE8, 0x91, 0x89, 0x43, + 0xE8, 0x91, 0x97, 0x43, 0xE8, 0x93, 0xAE, 0x43, + 0xE8, 0x93, 0xB1, 0x43, 0xE8, 0x93, 0xB3, 0x43, + 0xE8, 0x93, 0xBC, 0x43, 0xE8, 0x94, 0x96, 0x43, + // Bytes 1280 - 12bf + 0xE8, 0x95, 0xA4, 0x43, 0xE8, 0x97, 0x8D, 0x43, + 0xE8, 0x97, 0xBA, 0x43, 0xE8, 0x98, 0x86, 0x43, + 0xE8, 0x98, 0x92, 0x43, 0xE8, 0x98, 0xAD, 0x43, + 0xE8, 0x98, 0xBF, 0x43, 0xE8, 0x99, 0x8D, 0x43, + 0xE8, 0x99, 0x90, 0x43, 0xE8, 0x99, 0x9C, 0x43, + 0xE8, 0x99, 0xA7, 0x43, 0xE8, 0x99, 0xA9, 0x43, + 0xE8, 0x99, 0xAB, 0x43, 0xE8, 0x9A, 0x88, 0x43, + 0xE8, 0x9A, 0xA9, 0x43, 0xE8, 0x9B, 0xA2, 0x43, + // Bytes 12c0 - 12ff + 0xE8, 0x9C, 0x8E, 0x43, 0xE8, 0x9C, 0xA8, 0x43, + 0xE8, 0x9D, 0xAB, 0x43, 0xE8, 0x9D, 0xB9, 0x43, + 0xE8, 0x9E, 0x86, 0x43, 0xE8, 0x9E, 0xBA, 0x43, + 0xE8, 0x9F, 0xA1, 0x43, 0xE8, 0xA0, 0x81, 0x43, + 0xE8, 0xA0, 0x9F, 0x43, 0xE8, 0xA1, 0x80, 0x43, + 0xE8, 0xA1, 0x8C, 0x43, 0xE8, 0xA1, 0xA0, 0x43, + 0xE8, 0xA1, 0xA3, 0x43, 0xE8, 0xA3, 0x82, 0x43, + 0xE8, 0xA3, 0x8F, 0x43, 0xE8, 0xA3, 0x97, 0x43, + // Bytes 1300 - 133f + 0xE8, 0xA3, 0x9E, 0x43, 0xE8, 0xA3, 0xA1, 0x43, + 0xE8, 0xA3, 0xB8, 0x43, 0xE8, 0xA3, 0xBA, 0x43, + 0xE8, 0xA4, 0x90, 0x43, 0xE8, 0xA5, 0x81, 0x43, + 0xE8, 0xA5, 0xA4, 0x43, 0xE8, 0xA5, 0xBE, 0x43, + 0xE8, 0xA6, 0x86, 0x43, 0xE8, 0xA6, 0x8B, 0x43, + 0xE8, 0xA6, 0x96, 0x43, 0xE8, 0xA7, 0x92, 0x43, + 0xE8, 0xA7, 0xA3, 0x43, 0xE8, 0xA8, 0x80, 0x43, + 0xE8, 0xAA, 0xA0, 0x43, 0xE8, 0xAA, 0xAA, 0x43, + // Bytes 1340 - 137f + 0xE8, 0xAA, 0xBF, 0x43, 0xE8, 0xAB, 0x8B, 0x43, + 0xE8, 0xAB, 0x92, 0x43, 0xE8, 0xAB, 0x96, 0x43, + 0xE8, 0xAB, 0xAD, 0x43, 0xE8, 0xAB, 0xB8, 0x43, + 0xE8, 0xAB, 0xBE, 0x43, 0xE8, 0xAC, 0x81, 0x43, + 0xE8, 0xAC, 0xB9, 0x43, 0xE8, 0xAD, 0x98, 0x43, + 0xE8, 0xAE, 0x80, 0x43, 0xE8, 0xAE, 0x8A, 0x43, + 0xE8, 0xB0, 0xB7, 0x43, 0xE8, 0xB1, 0x86, 0x43, + 0xE8, 0xB1, 0x88, 0x43, 0xE8, 0xB1, 0x95, 0x43, + // Bytes 1380 - 13bf + 0xE8, 0xB1, 0xB8, 0x43, 0xE8, 0xB2, 0x9D, 0x43, + 0xE8, 0xB2, 0xA1, 0x43, 0xE8, 0xB2, 0xA9, 0x43, + 0xE8, 0xB2, 0xAB, 0x43, 0xE8, 0xB3, 0x81, 0x43, + 0xE8, 0xB3, 0x82, 0x43, 0xE8, 0xB3, 0x87, 0x43, + 0xE8, 0xB3, 0x88, 0x43, 0xE8, 0xB3, 0x93, 0x43, + 0xE8, 0xB4, 0x88, 0x43, 0xE8, 0xB4, 0x9B, 0x43, + 0xE8, 0xB5, 0xA4, 0x43, 0xE8, 0xB5, 0xB0, 0x43, + 0xE8, 0xB5, 0xB7, 0x43, 0xE8, 0xB6, 0xB3, 0x43, + // Bytes 13c0 - 13ff + 0xE8, 0xB6, 0xBC, 0x43, 0xE8, 0xB7, 0x8B, 0x43, + 0xE8, 0xB7, 0xAF, 0x43, 0xE8, 0xB7, 0xB0, 0x43, + 0xE8, 0xBA, 0xAB, 0x43, 0xE8, 0xBB, 0x8A, 0x43, + 0xE8, 0xBB, 0x94, 0x43, 0xE8, 0xBC, 0xA6, 0x43, + 0xE8, 0xBC, 0xAA, 0x43, 0xE8, 0xBC, 0xB8, 0x43, + 0xE8, 0xBC, 0xBB, 0x43, 0xE8, 0xBD, 0xA2, 0x43, + 0xE8, 0xBE, 0x9B, 0x43, 0xE8, 0xBE, 0x9E, 0x43, + 0xE8, 0xBE, 0xB0, 0x43, 0xE8, 0xBE, 0xB5, 0x43, + // Bytes 1400 - 143f + 0xE8, 0xBE, 0xB6, 0x43, 0xE9, 0x80, 0xA3, 0x43, + 0xE9, 0x80, 0xB8, 0x43, 0xE9, 0x81, 0x8A, 0x43, + 0xE9, 0x81, 0xA9, 0x43, 0xE9, 0x81, 0xB2, 0x43, + 0xE9, 0x81, 0xBC, 0x43, 0xE9, 0x82, 0x8F, 0x43, + 0xE9, 0x82, 0x91, 0x43, 0xE9, 0x82, 0x94, 0x43, + 0xE9, 0x83, 0x8E, 0x43, 0xE9, 0x83, 0x9E, 0x43, + 0xE9, 0x83, 0xB1, 0x43, 0xE9, 0x83, 0xBD, 0x43, + 0xE9, 0x84, 0x91, 0x43, 0xE9, 0x84, 0x9B, 0x43, + // Bytes 1440 - 147f + 0xE9, 0x85, 0x89, 0x43, 0xE9, 0x85, 0x8D, 0x43, + 0xE9, 0x85, 0xAA, 0x43, 0xE9, 0x86, 0x99, 0x43, + 0xE9, 0x86, 0xB4, 0x43, 0xE9, 0x87, 0x86, 0x43, + 0xE9, 0x87, 0x8C, 0x43, 0xE9, 0x87, 0x8F, 0x43, + 0xE9, 0x87, 0x91, 0x43, 0xE9, 0x88, 0xB4, 0x43, + 0xE9, 0x88, 0xB8, 0x43, 0xE9, 0x89, 0xB6, 0x43, + 0xE9, 0x89, 0xBC, 0x43, 0xE9, 0x8B, 0x97, 0x43, + 0xE9, 0x8B, 0x98, 0x43, 0xE9, 0x8C, 0x84, 0x43, + // Bytes 1480 - 14bf + 0xE9, 0x8D, 0x8A, 0x43, 0xE9, 0x8F, 0xB9, 0x43, + 0xE9, 0x90, 0x95, 0x43, 0xE9, 0x95, 0xB7, 0x43, + 0xE9, 0x96, 0x80, 0x43, 0xE9, 0x96, 0x8B, 0x43, + 0xE9, 0x96, 0xAD, 0x43, 0xE9, 0x96, 0xB7, 0x43, + 0xE9, 0x98, 0x9C, 0x43, 0xE9, 0x98, 0xAE, 0x43, + 0xE9, 0x99, 0x8B, 0x43, 0xE9, 0x99, 0x8D, 0x43, + 0xE9, 0x99, 0xB5, 0x43, 0xE9, 0x99, 0xB8, 0x43, + 0xE9, 0x99, 0xBC, 0x43, 0xE9, 0x9A, 0x86, 0x43, + // Bytes 14c0 - 14ff + 0xE9, 0x9A, 0xA3, 0x43, 0xE9, 0x9A, 0xB6, 0x43, + 0xE9, 0x9A, 0xB7, 0x43, 0xE9, 0x9A, 0xB8, 0x43, + 0xE9, 0x9A, 0xB9, 0x43, 0xE9, 0x9B, 0x83, 0x43, + 0xE9, 0x9B, 0xA2, 0x43, 0xE9, 0x9B, 0xA3, 0x43, + 0xE9, 0x9B, 0xA8, 0x43, 0xE9, 0x9B, 0xB6, 0x43, + 0xE9, 0x9B, 0xB7, 0x43, 0xE9, 0x9C, 0xA3, 0x43, + 0xE9, 0x9C, 0xB2, 0x43, 0xE9, 0x9D, 0x88, 0x43, + 0xE9, 0x9D, 0x91, 0x43, 0xE9, 0x9D, 0x96, 0x43, + // Bytes 1500 - 153f + 0xE9, 0x9D, 0x9E, 0x43, 0xE9, 0x9D, 0xA2, 0x43, + 0xE9, 0x9D, 0xA9, 0x43, 0xE9, 0x9F, 0x8B, 0x43, + 0xE9, 0x9F, 0x9B, 0x43, 0xE9, 0x9F, 0xA0, 0x43, + 0xE9, 0x9F, 0xAD, 0x43, 0xE9, 0x9F, 0xB3, 0x43, + 0xE9, 0x9F, 0xBF, 0x43, 0xE9, 0xA0, 0x81, 0x43, + 0xE9, 0xA0, 0x85, 0x43, 0xE9, 0xA0, 0x8B, 0x43, + 0xE9, 0xA0, 0x98, 0x43, 0xE9, 0xA0, 0xA9, 0x43, + 0xE9, 0xA0, 0xBB, 0x43, 0xE9, 0xA1, 0x9E, 0x43, + // Bytes 1540 - 157f + 0xE9, 0xA2, 0xA8, 0x43, 0xE9, 0xA3, 0x9B, 0x43, + 0xE9, 0xA3, 0x9F, 0x43, 0xE9, 0xA3, 0xA2, 0x43, + 0xE9, 0xA3, 0xAF, 0x43, 0xE9, 0xA3, 0xBC, 0x43, + 0xE9, 0xA4, 0xA8, 0x43, 0xE9, 0xA4, 0xA9, 0x43, + 0xE9, 0xA6, 0x96, 0x43, 0xE9, 0xA6, 0x99, 0x43, + 0xE9, 0xA6, 0xA7, 0x43, 0xE9, 0xA6, 0xAC, 0x43, + 0xE9, 0xA7, 0x82, 0x43, 0xE9, 0xA7, 0xB1, 0x43, + 0xE9, 0xA7, 0xBE, 0x43, 0xE9, 0xA9, 0xAA, 0x43, + // Bytes 1580 - 15bf + 0xE9, 0xAA, 0xA8, 0x43, 0xE9, 0xAB, 0x98, 0x43, + 0xE9, 0xAB, 0x9F, 0x43, 0xE9, 0xAC, 0x92, 0x43, + 0xE9, 0xAC, 0xA5, 0x43, 0xE9, 0xAC, 0xAF, 0x43, + 0xE9, 0xAC, 0xB2, 0x43, 0xE9, 0xAC, 0xBC, 0x43, + 0xE9, 0xAD, 0x9A, 0x43, 0xE9, 0xAD, 0xAF, 0x43, + 0xE9, 0xB1, 0x80, 0x43, 0xE9, 0xB1, 0x97, 0x43, + 0xE9, 0xB3, 0xA5, 0x43, 0xE9, 0xB3, 0xBD, 0x43, + 0xE9, 0xB5, 0xA7, 0x43, 0xE9, 0xB6, 0xB4, 0x43, + // Bytes 15c0 - 15ff + 0xE9, 0xB7, 0xBA, 0x43, 0xE9, 0xB8, 0x9E, 0x43, + 0xE9, 0xB9, 0xB5, 0x43, 0xE9, 0xB9, 0xBF, 0x43, + 0xE9, 0xBA, 0x97, 0x43, 0xE9, 0xBA, 0x9F, 0x43, + 0xE9, 0xBA, 0xA5, 0x43, 0xE9, 0xBA, 0xBB, 0x43, + 0xE9, 0xBB, 0x83, 0x43, 0xE9, 0xBB, 0x8D, 0x43, + 0xE9, 0xBB, 0x8E, 0x43, 0xE9, 0xBB, 0x91, 0x43, + 0xE9, 0xBB, 0xB9, 0x43, 0xE9, 0xBB, 0xBD, 0x43, + 0xE9, 0xBB, 0xBE, 0x43, 0xE9, 0xBC, 0x85, 0x43, + // Bytes 1600 - 163f + 0xE9, 0xBC, 0x8E, 0x43, 0xE9, 0xBC, 0x8F, 0x43, + 0xE9, 0xBC, 0x93, 0x43, 0xE9, 0xBC, 0x96, 0x43, + 0xE9, 0xBC, 0xA0, 0x43, 0xE9, 0xBC, 0xBB, 0x43, + 0xE9, 0xBD, 0x83, 0x43, 0xE9, 0xBD, 0x8A, 0x43, + 0xE9, 0xBD, 0x92, 0x43, 0xE9, 0xBE, 0x8D, 0x43, + 0xE9, 0xBE, 0x8E, 0x43, 0xE9, 0xBE, 0x9C, 0x43, + 0xE9, 0xBE, 0x9F, 0x43, 0xE9, 0xBE, 0xA0, 0x43, + 0xEA, 0x9C, 0xA7, 0x43, 0xEA, 0x9D, 0xAF, 0x43, + // Bytes 1640 - 167f + 0xEA, 0xAC, 0xB7, 0x43, 0xEA, 0xAD, 0x92, 0x44, + 0xF0, 0xA0, 0x84, 0xA2, 0x44, 0xF0, 0xA0, 0x94, + 0x9C, 0x44, 0xF0, 0xA0, 0x94, 0xA5, 0x44, 0xF0, + 0xA0, 0x95, 0x8B, 0x44, 0xF0, 0xA0, 0x98, 0xBA, + 0x44, 0xF0, 0xA0, 0xA0, 0x84, 0x44, 0xF0, 0xA0, + 0xA3, 0x9E, 0x44, 0xF0, 0xA0, 0xA8, 0xAC, 0x44, + 0xF0, 0xA0, 0xAD, 0xA3, 0x44, 0xF0, 0xA1, 0x93, + 0xA4, 0x44, 0xF0, 0xA1, 0x9A, 0xA8, 0x44, 0xF0, + // Bytes 1680 - 16bf + 0xA1, 0x9B, 0xAA, 0x44, 0xF0, 0xA1, 0xA7, 0x88, + 0x44, 0xF0, 0xA1, 0xAC, 0x98, 0x44, 0xF0, 0xA1, + 0xB4, 0x8B, 0x44, 0xF0, 0xA1, 0xB7, 0xA4, 0x44, + 0xF0, 0xA1, 0xB7, 0xA6, 0x44, 0xF0, 0xA2, 0x86, + 0x83, 0x44, 0xF0, 0xA2, 0x86, 0x9F, 0x44, 0xF0, + 0xA2, 0x8C, 0xB1, 0x44, 0xF0, 0xA2, 0x9B, 0x94, + 0x44, 0xF0, 0xA2, 0xA1, 0x84, 0x44, 0xF0, 0xA2, + 0xA1, 0x8A, 0x44, 0xF0, 0xA2, 0xAC, 0x8C, 0x44, + // Bytes 16c0 - 16ff + 0xF0, 0xA2, 0xAF, 0xB1, 0x44, 0xF0, 0xA3, 0x80, + 0x8A, 0x44, 0xF0, 0xA3, 0x8A, 0xB8, 0x44, 0xF0, + 0xA3, 0x8D, 0x9F, 0x44, 0xF0, 0xA3, 0x8E, 0x93, + 0x44, 0xF0, 0xA3, 0x8E, 0x9C, 0x44, 0xF0, 0xA3, + 0x8F, 0x83, 0x44, 0xF0, 0xA3, 0x8F, 0x95, 0x44, + 0xF0, 0xA3, 0x91, 0xAD, 0x44, 0xF0, 0xA3, 0x9A, + 0xA3, 0x44, 0xF0, 0xA3, 0xA2, 0xA7, 0x44, 0xF0, + 0xA3, 0xAA, 0x8D, 0x44, 0xF0, 0xA3, 0xAB, 0xBA, + // Bytes 1700 - 173f + 0x44, 0xF0, 0xA3, 0xB2, 0xBC, 0x44, 0xF0, 0xA3, + 0xB4, 0x9E, 0x44, 0xF0, 0xA3, 0xBB, 0x91, 0x44, + 0xF0, 0xA3, 0xBD, 0x9E, 0x44, 0xF0, 0xA3, 0xBE, + 0x8E, 0x44, 0xF0, 0xA4, 0x89, 0xA3, 0x44, 0xF0, + 0xA4, 0x8B, 0xAE, 0x44, 0xF0, 0xA4, 0x8E, 0xAB, + 0x44, 0xF0, 0xA4, 0x98, 0x88, 0x44, 0xF0, 0xA4, + 0x9C, 0xB5, 0x44, 0xF0, 0xA4, 0xA0, 0x94, 0x44, + 0xF0, 0xA4, 0xB0, 0xB6, 0x44, 0xF0, 0xA4, 0xB2, + // Bytes 1740 - 177f + 0x92, 0x44, 0xF0, 0xA4, 0xBE, 0xA1, 0x44, 0xF0, + 0xA4, 0xBE, 0xB8, 0x44, 0xF0, 0xA5, 0x81, 0x84, + 0x44, 0xF0, 0xA5, 0x83, 0xB2, 0x44, 0xF0, 0xA5, + 0x83, 0xB3, 0x44, 0xF0, 0xA5, 0x84, 0x99, 0x44, + 0xF0, 0xA5, 0x84, 0xB3, 0x44, 0xF0, 0xA5, 0x89, + 0x89, 0x44, 0xF0, 0xA5, 0x90, 0x9D, 0x44, 0xF0, + 0xA5, 0x98, 0xA6, 0x44, 0xF0, 0xA5, 0x9A, 0x9A, + 0x44, 0xF0, 0xA5, 0x9B, 0x85, 0x44, 0xF0, 0xA5, + // Bytes 1780 - 17bf + 0xA5, 0xBC, 0x44, 0xF0, 0xA5, 0xAA, 0xA7, 0x44, + 0xF0, 0xA5, 0xAE, 0xAB, 0x44, 0xF0, 0xA5, 0xB2, + 0x80, 0x44, 0xF0, 0xA5, 0xB3, 0x90, 0x44, 0xF0, + 0xA5, 0xBE, 0x86, 0x44, 0xF0, 0xA6, 0x87, 0x9A, + 0x44, 0xF0, 0xA6, 0x88, 0xA8, 0x44, 0xF0, 0xA6, + 0x89, 0x87, 0x44, 0xF0, 0xA6, 0x8B, 0x99, 0x44, + 0xF0, 0xA6, 0x8C, 0xBE, 0x44, 0xF0, 0xA6, 0x93, + 0x9A, 0x44, 0xF0, 0xA6, 0x94, 0xA3, 0x44, 0xF0, + // Bytes 17c0 - 17ff + 0xA6, 0x96, 0xA8, 0x44, 0xF0, 0xA6, 0x9E, 0xA7, + 0x44, 0xF0, 0xA6, 0x9E, 0xB5, 0x44, 0xF0, 0xA6, + 0xAC, 0xBC, 0x44, 0xF0, 0xA6, 0xB0, 0xB6, 0x44, + 0xF0, 0xA6, 0xB3, 0x95, 0x44, 0xF0, 0xA6, 0xB5, + 0xAB, 0x44, 0xF0, 0xA6, 0xBC, 0xAC, 0x44, 0xF0, + 0xA6, 0xBE, 0xB1, 0x44, 0xF0, 0xA7, 0x83, 0x92, + 0x44, 0xF0, 0xA7, 0x8F, 0x8A, 0x44, 0xF0, 0xA7, + 0x99, 0xA7, 0x44, 0xF0, 0xA7, 0xA2, 0xAE, 0x44, + // Bytes 1800 - 183f + 0xF0, 0xA7, 0xA5, 0xA6, 0x44, 0xF0, 0xA7, 0xB2, + 0xA8, 0x44, 0xF0, 0xA7, 0xBB, 0x93, 0x44, 0xF0, + 0xA7, 0xBC, 0xAF, 0x44, 0xF0, 0xA8, 0x97, 0x92, + 0x44, 0xF0, 0xA8, 0x97, 0xAD, 0x44, 0xF0, 0xA8, + 0x9C, 0xAE, 0x44, 0xF0, 0xA8, 0xAF, 0xBA, 0x44, + 0xF0, 0xA8, 0xB5, 0xB7, 0x44, 0xF0, 0xA9, 0x85, + 0x85, 0x44, 0xF0, 0xA9, 0x87, 0x9F, 0x44, 0xF0, + 0xA9, 0x88, 0x9A, 0x44, 0xF0, 0xA9, 0x90, 0x8A, + // Bytes 1840 - 187f + 0x44, 0xF0, 0xA9, 0x92, 0x96, 0x44, 0xF0, 0xA9, + 0x96, 0xB6, 0x44, 0xF0, 0xA9, 0xAC, 0xB0, 0x44, + 0xF0, 0xAA, 0x83, 0x8E, 0x44, 0xF0, 0xAA, 0x84, + 0x85, 0x44, 0xF0, 0xAA, 0x88, 0x8E, 0x44, 0xF0, + 0xAA, 0x8A, 0x91, 0x44, 0xF0, 0xAA, 0x8E, 0x92, + 0x44, 0xF0, 0xAA, 0x98, 0x80, 0x42, 0x21, 0x21, + 0x42, 0x21, 0x3F, 0x42, 0x2E, 0x2E, 0x42, 0x30, + 0x2C, 0x42, 0x30, 0x2E, 0x42, 0x31, 0x2C, 0x42, + // Bytes 1880 - 18bf + 0x31, 0x2E, 0x42, 0x31, 0x30, 0x42, 0x31, 0x31, + 0x42, 0x31, 0x32, 0x42, 0x31, 0x33, 0x42, 0x31, + 0x34, 0x42, 0x31, 0x35, 0x42, 0x31, 0x36, 0x42, + 0x31, 0x37, 0x42, 0x31, 0x38, 0x42, 0x31, 0x39, + 0x42, 0x32, 0x2C, 0x42, 0x32, 0x2E, 0x42, 0x32, + 0x30, 0x42, 0x32, 0x31, 0x42, 0x32, 0x32, 0x42, + 0x32, 0x33, 0x42, 0x32, 0x34, 0x42, 0x32, 0x35, + 0x42, 0x32, 0x36, 0x42, 0x32, 0x37, 0x42, 0x32, + // Bytes 18c0 - 18ff + 0x38, 0x42, 0x32, 0x39, 0x42, 0x33, 0x2C, 0x42, + 0x33, 0x2E, 0x42, 0x33, 0x30, 0x42, 0x33, 0x31, + 0x42, 0x33, 0x32, 0x42, 0x33, 0x33, 0x42, 0x33, + 0x34, 0x42, 0x33, 0x35, 0x42, 0x33, 0x36, 0x42, + 0x33, 0x37, 0x42, 0x33, 0x38, 0x42, 0x33, 0x39, + 0x42, 0x34, 0x2C, 0x42, 0x34, 0x2E, 0x42, 0x34, + 0x30, 0x42, 0x34, 0x31, 0x42, 0x34, 0x32, 0x42, + 0x34, 0x33, 0x42, 0x34, 0x34, 0x42, 0x34, 0x35, + // Bytes 1900 - 193f + 0x42, 0x34, 0x36, 0x42, 0x34, 0x37, 0x42, 0x34, + 0x38, 0x42, 0x34, 0x39, 0x42, 0x35, 0x2C, 0x42, + 0x35, 0x2E, 0x42, 0x35, 0x30, 0x42, 0x36, 0x2C, + 0x42, 0x36, 0x2E, 0x42, 0x37, 0x2C, 0x42, 0x37, + 0x2E, 0x42, 0x38, 0x2C, 0x42, 0x38, 0x2E, 0x42, + 0x39, 0x2C, 0x42, 0x39, 0x2E, 0x42, 0x3D, 0x3D, + 0x42, 0x3F, 0x21, 0x42, 0x3F, 0x3F, 0x42, 0x41, + 0x55, 0x42, 0x42, 0x71, 0x42, 0x43, 0x44, 0x42, + // Bytes 1940 - 197f + 0x44, 0x4A, 0x42, 0x44, 0x5A, 0x42, 0x44, 0x7A, + 0x42, 0x47, 0x42, 0x42, 0x47, 0x79, 0x42, 0x48, + 0x50, 0x42, 0x48, 0x56, 0x42, 0x48, 0x67, 0x42, + 0x48, 0x7A, 0x42, 0x49, 0x49, 0x42, 0x49, 0x4A, + 0x42, 0x49, 0x55, 0x42, 0x49, 0x56, 0x42, 0x49, + 0x58, 0x42, 0x4B, 0x42, 0x42, 0x4B, 0x4B, 0x42, + 0x4B, 0x4D, 0x42, 0x4C, 0x4A, 0x42, 0x4C, 0x6A, + 0x42, 0x4D, 0x42, 0x42, 0x4D, 0x43, 0x42, 0x4D, + // Bytes 1980 - 19bf + 0x44, 0x42, 0x4D, 0x56, 0x42, 0x4D, 0x57, 0x42, + 0x4E, 0x4A, 0x42, 0x4E, 0x6A, 0x42, 0x4E, 0x6F, + 0x42, 0x50, 0x48, 0x42, 0x50, 0x52, 0x42, 0x50, + 0x61, 0x42, 0x52, 0x73, 0x42, 0x53, 0x44, 0x42, + 0x53, 0x4D, 0x42, 0x53, 0x53, 0x42, 0x53, 0x76, + 0x42, 0x54, 0x4D, 0x42, 0x56, 0x49, 0x42, 0x57, + 0x43, 0x42, 0x57, 0x5A, 0x42, 0x57, 0x62, 0x42, + 0x58, 0x49, 0x42, 0x63, 0x63, 0x42, 0x63, 0x64, + // Bytes 19c0 - 19ff + 0x42, 0x63, 0x6D, 0x42, 0x64, 0x42, 0x42, 0x64, + 0x61, 0x42, 0x64, 0x6C, 0x42, 0x64, 0x6D, 0x42, + 0x64, 0x7A, 0x42, 0x65, 0x56, 0x42, 0x66, 0x66, + 0x42, 0x66, 0x69, 0x42, 0x66, 0x6C, 0x42, 0x66, + 0x6D, 0x42, 0x68, 0x61, 0x42, 0x69, 0x69, 0x42, + 0x69, 0x6A, 0x42, 0x69, 0x6E, 0x42, 0x69, 0x76, + 0x42, 0x69, 0x78, 0x42, 0x6B, 0x41, 0x42, 0x6B, + 0x56, 0x42, 0x6B, 0x57, 0x42, 0x6B, 0x67, 0x42, + // Bytes 1a00 - 1a3f + 0x6B, 0x6C, 0x42, 0x6B, 0x6D, 0x42, 0x6B, 0x74, + 0x42, 0x6C, 0x6A, 0x42, 0x6C, 0x6D, 0x42, 0x6C, + 0x6E, 0x42, 0x6C, 0x78, 0x42, 0x6D, 0x32, 0x42, + 0x6D, 0x33, 0x42, 0x6D, 0x41, 0x42, 0x6D, 0x56, + 0x42, 0x6D, 0x57, 0x42, 0x6D, 0x62, 0x42, 0x6D, + 0x67, 0x42, 0x6D, 0x6C, 0x42, 0x6D, 0x6D, 0x42, + 0x6D, 0x73, 0x42, 0x6E, 0x41, 0x42, 0x6E, 0x46, + 0x42, 0x6E, 0x56, 0x42, 0x6E, 0x57, 0x42, 0x6E, + // Bytes 1a40 - 1a7f + 0x6A, 0x42, 0x6E, 0x6D, 0x42, 0x6E, 0x73, 0x42, + 0x6F, 0x56, 0x42, 0x70, 0x41, 0x42, 0x70, 0x46, + 0x42, 0x70, 0x56, 0x42, 0x70, 0x57, 0x42, 0x70, + 0x63, 0x42, 0x70, 0x73, 0x42, 0x73, 0x72, 0x42, + 0x73, 0x74, 0x42, 0x76, 0x69, 0x42, 0x78, 0x69, + 0x43, 0x28, 0x31, 0x29, 0x43, 0x28, 0x32, 0x29, + 0x43, 0x28, 0x33, 0x29, 0x43, 0x28, 0x34, 0x29, + 0x43, 0x28, 0x35, 0x29, 0x43, 0x28, 0x36, 0x29, + // Bytes 1a80 - 1abf + 0x43, 0x28, 0x37, 0x29, 0x43, 0x28, 0x38, 0x29, + 0x43, 0x28, 0x39, 0x29, 0x43, 0x28, 0x41, 0x29, + 0x43, 0x28, 0x42, 0x29, 0x43, 0x28, 0x43, 0x29, + 0x43, 0x28, 0x44, 0x29, 0x43, 0x28, 0x45, 0x29, + 0x43, 0x28, 0x46, 0x29, 0x43, 0x28, 0x47, 0x29, + 0x43, 0x28, 0x48, 0x29, 0x43, 0x28, 0x49, 0x29, + 0x43, 0x28, 0x4A, 0x29, 0x43, 0x28, 0x4B, 0x29, + 0x43, 0x28, 0x4C, 0x29, 0x43, 0x28, 0x4D, 0x29, + // Bytes 1ac0 - 1aff + 0x43, 0x28, 0x4E, 0x29, 0x43, 0x28, 0x4F, 0x29, + 0x43, 0x28, 0x50, 0x29, 0x43, 0x28, 0x51, 0x29, + 0x43, 0x28, 0x52, 0x29, 0x43, 0x28, 0x53, 0x29, + 0x43, 0x28, 0x54, 0x29, 0x43, 0x28, 0x55, 0x29, + 0x43, 0x28, 0x56, 0x29, 0x43, 0x28, 0x57, 0x29, + 0x43, 0x28, 0x58, 0x29, 0x43, 0x28, 0x59, 0x29, + 0x43, 0x28, 0x5A, 0x29, 0x43, 0x28, 0x61, 0x29, + 0x43, 0x28, 0x62, 0x29, 0x43, 0x28, 0x63, 0x29, + // Bytes 1b00 - 1b3f + 0x43, 0x28, 0x64, 0x29, 0x43, 0x28, 0x65, 0x29, + 0x43, 0x28, 0x66, 0x29, 0x43, 0x28, 0x67, 0x29, + 0x43, 0x28, 0x68, 0x29, 0x43, 0x28, 0x69, 0x29, + 0x43, 0x28, 0x6A, 0x29, 0x43, 0x28, 0x6B, 0x29, + 0x43, 0x28, 0x6C, 0x29, 0x43, 0x28, 0x6D, 0x29, + 0x43, 0x28, 0x6E, 0x29, 0x43, 0x28, 0x6F, 0x29, + 0x43, 0x28, 0x70, 0x29, 0x43, 0x28, 0x71, 0x29, + 0x43, 0x28, 0x72, 0x29, 0x43, 0x28, 0x73, 0x29, + // Bytes 1b40 - 1b7f + 0x43, 0x28, 0x74, 0x29, 0x43, 0x28, 0x75, 0x29, + 0x43, 0x28, 0x76, 0x29, 0x43, 0x28, 0x77, 0x29, + 0x43, 0x28, 0x78, 0x29, 0x43, 0x28, 0x79, 0x29, + 0x43, 0x28, 0x7A, 0x29, 0x43, 0x2E, 0x2E, 0x2E, + 0x43, 0x31, 0x30, 0x2E, 0x43, 0x31, 0x31, 0x2E, + 0x43, 0x31, 0x32, 0x2E, 0x43, 0x31, 0x33, 0x2E, + 0x43, 0x31, 0x34, 0x2E, 0x43, 0x31, 0x35, 0x2E, + 0x43, 0x31, 0x36, 0x2E, 0x43, 0x31, 0x37, 0x2E, + // Bytes 1b80 - 1bbf + 0x43, 0x31, 0x38, 0x2E, 0x43, 0x31, 0x39, 0x2E, + 0x43, 0x32, 0x30, 0x2E, 0x43, 0x3A, 0x3A, 0x3D, + 0x43, 0x3D, 0x3D, 0x3D, 0x43, 0x43, 0x6F, 0x2E, + 0x43, 0x46, 0x41, 0x58, 0x43, 0x47, 0x48, 0x7A, + 0x43, 0x47, 0x50, 0x61, 0x43, 0x49, 0x49, 0x49, + 0x43, 0x4C, 0x54, 0x44, 0x43, 0x4C, 0xC2, 0xB7, + 0x43, 0x4D, 0x48, 0x7A, 0x43, 0x4D, 0x50, 0x61, + 0x43, 0x4D, 0xCE, 0xA9, 0x43, 0x50, 0x50, 0x4D, + // Bytes 1bc0 - 1bff + 0x43, 0x50, 0x50, 0x56, 0x43, 0x50, 0x54, 0x45, + 0x43, 0x54, 0x45, 0x4C, 0x43, 0x54, 0x48, 0x7A, + 0x43, 0x56, 0x49, 0x49, 0x43, 0x58, 0x49, 0x49, + 0x43, 0x61, 0x2F, 0x63, 0x43, 0x61, 0x2F, 0x73, + 0x43, 0x61, 0xCA, 0xBE, 0x43, 0x62, 0x61, 0x72, + 0x43, 0x63, 0x2F, 0x6F, 0x43, 0x63, 0x2F, 0x75, + 0x43, 0x63, 0x61, 0x6C, 0x43, 0x63, 0x6D, 0x32, + 0x43, 0x63, 0x6D, 0x33, 0x43, 0x64, 0x6D, 0x32, + // Bytes 1c00 - 1c3f + 0x43, 0x64, 0x6D, 0x33, 0x43, 0x65, 0x72, 0x67, + 0x43, 0x66, 0x66, 0x69, 0x43, 0x66, 0x66, 0x6C, + 0x43, 0x67, 0x61, 0x6C, 0x43, 0x68, 0x50, 0x61, + 0x43, 0x69, 0x69, 0x69, 0x43, 0x6B, 0x48, 0x7A, + 0x43, 0x6B, 0x50, 0x61, 0x43, 0x6B, 0x6D, 0x32, + 0x43, 0x6B, 0x6D, 0x33, 0x43, 0x6B, 0xCE, 0xA9, + 0x43, 0x6C, 0x6F, 0x67, 0x43, 0x6C, 0xC2, 0xB7, + 0x43, 0x6D, 0x69, 0x6C, 0x43, 0x6D, 0x6D, 0x32, + // Bytes 1c40 - 1c7f + 0x43, 0x6D, 0x6D, 0x33, 0x43, 0x6D, 0x6F, 0x6C, + 0x43, 0x72, 0x61, 0x64, 0x43, 0x76, 0x69, 0x69, + 0x43, 0x78, 0x69, 0x69, 0x43, 0xC2, 0xB0, 0x43, + 0x43, 0xC2, 0xB0, 0x46, 0x43, 0xCA, 0xBC, 0x6E, + 0x43, 0xCE, 0xBC, 0x41, 0x43, 0xCE, 0xBC, 0x46, + 0x43, 0xCE, 0xBC, 0x56, 0x43, 0xCE, 0xBC, 0x57, + 0x43, 0xCE, 0xBC, 0x67, 0x43, 0xCE, 0xBC, 0x6C, + 0x43, 0xCE, 0xBC, 0x6D, 0x43, 0xCE, 0xBC, 0x73, + // Bytes 1c80 - 1cbf + 0x44, 0x28, 0x31, 0x30, 0x29, 0x44, 0x28, 0x31, + 0x31, 0x29, 0x44, 0x28, 0x31, 0x32, 0x29, 0x44, + 0x28, 0x31, 0x33, 0x29, 0x44, 0x28, 0x31, 0x34, + 0x29, 0x44, 0x28, 0x31, 0x35, 0x29, 0x44, 0x28, + 0x31, 0x36, 0x29, 0x44, 0x28, 0x31, 0x37, 0x29, + 0x44, 0x28, 0x31, 0x38, 0x29, 0x44, 0x28, 0x31, + 0x39, 0x29, 0x44, 0x28, 0x32, 0x30, 0x29, 0x44, + 0x30, 0xE7, 0x82, 0xB9, 0x44, 0x31, 0xE2, 0x81, + // Bytes 1cc0 - 1cff + 0x84, 0x44, 0x31, 0xE6, 0x97, 0xA5, 0x44, 0x31, + 0xE6, 0x9C, 0x88, 0x44, 0x31, 0xE7, 0x82, 0xB9, + 0x44, 0x32, 0xE6, 0x97, 0xA5, 0x44, 0x32, 0xE6, + 0x9C, 0x88, 0x44, 0x32, 0xE7, 0x82, 0xB9, 0x44, + 0x33, 0xE6, 0x97, 0xA5, 0x44, 0x33, 0xE6, 0x9C, + 0x88, 0x44, 0x33, 0xE7, 0x82, 0xB9, 0x44, 0x34, + 0xE6, 0x97, 0xA5, 0x44, 0x34, 0xE6, 0x9C, 0x88, + 0x44, 0x34, 0xE7, 0x82, 0xB9, 0x44, 0x35, 0xE6, + // Bytes 1d00 - 1d3f + 0x97, 0xA5, 0x44, 0x35, 0xE6, 0x9C, 0x88, 0x44, + 0x35, 0xE7, 0x82, 0xB9, 0x44, 0x36, 0xE6, 0x97, + 0xA5, 0x44, 0x36, 0xE6, 0x9C, 0x88, 0x44, 0x36, + 0xE7, 0x82, 0xB9, 0x44, 0x37, 0xE6, 0x97, 0xA5, + 0x44, 0x37, 0xE6, 0x9C, 0x88, 0x44, 0x37, 0xE7, + 0x82, 0xB9, 0x44, 0x38, 0xE6, 0x97, 0xA5, 0x44, + 0x38, 0xE6, 0x9C, 0x88, 0x44, 0x38, 0xE7, 0x82, + 0xB9, 0x44, 0x39, 0xE6, 0x97, 0xA5, 0x44, 0x39, + // Bytes 1d40 - 1d7f + 0xE6, 0x9C, 0x88, 0x44, 0x39, 0xE7, 0x82, 0xB9, + 0x44, 0x56, 0x49, 0x49, 0x49, 0x44, 0x61, 0x2E, + 0x6D, 0x2E, 0x44, 0x6B, 0x63, 0x61, 0x6C, 0x44, + 0x70, 0x2E, 0x6D, 0x2E, 0x44, 0x76, 0x69, 0x69, + 0x69, 0x44, 0xD5, 0xA5, 0xD6, 0x82, 0x44, 0xD5, + 0xB4, 0xD5, 0xA5, 0x44, 0xD5, 0xB4, 0xD5, 0xAB, + 0x44, 0xD5, 0xB4, 0xD5, 0xAD, 0x44, 0xD5, 0xB4, + 0xD5, 0xB6, 0x44, 0xD5, 0xBE, 0xD5, 0xB6, 0x44, + // Bytes 1d80 - 1dbf + 0xD7, 0x90, 0xD7, 0x9C, 0x44, 0xD8, 0xA7, 0xD9, + 0xB4, 0x44, 0xD8, 0xA8, 0xD8, 0xAC, 0x44, 0xD8, + 0xA8, 0xD8, 0xAD, 0x44, 0xD8, 0xA8, 0xD8, 0xAE, + 0x44, 0xD8, 0xA8, 0xD8, 0xB1, 0x44, 0xD8, 0xA8, + 0xD8, 0xB2, 0x44, 0xD8, 0xA8, 0xD9, 0x85, 0x44, + 0xD8, 0xA8, 0xD9, 0x86, 0x44, 0xD8, 0xA8, 0xD9, + 0x87, 0x44, 0xD8, 0xA8, 0xD9, 0x89, 0x44, 0xD8, + 0xA8, 0xD9, 0x8A, 0x44, 0xD8, 0xAA, 0xD8, 0xAC, + // Bytes 1dc0 - 1dff + 0x44, 0xD8, 0xAA, 0xD8, 0xAD, 0x44, 0xD8, 0xAA, + 0xD8, 0xAE, 0x44, 0xD8, 0xAA, 0xD8, 0xB1, 0x44, + 0xD8, 0xAA, 0xD8, 0xB2, 0x44, 0xD8, 0xAA, 0xD9, + 0x85, 0x44, 0xD8, 0xAA, 0xD9, 0x86, 0x44, 0xD8, + 0xAA, 0xD9, 0x87, 0x44, 0xD8, 0xAA, 0xD9, 0x89, + 0x44, 0xD8, 0xAA, 0xD9, 0x8A, 0x44, 0xD8, 0xAB, + 0xD8, 0xAC, 0x44, 0xD8, 0xAB, 0xD8, 0xB1, 0x44, + 0xD8, 0xAB, 0xD8, 0xB2, 0x44, 0xD8, 0xAB, 0xD9, + // Bytes 1e00 - 1e3f + 0x85, 0x44, 0xD8, 0xAB, 0xD9, 0x86, 0x44, 0xD8, + 0xAB, 0xD9, 0x87, 0x44, 0xD8, 0xAB, 0xD9, 0x89, + 0x44, 0xD8, 0xAB, 0xD9, 0x8A, 0x44, 0xD8, 0xAC, + 0xD8, 0xAD, 0x44, 0xD8, 0xAC, 0xD9, 0x85, 0x44, + 0xD8, 0xAC, 0xD9, 0x89, 0x44, 0xD8, 0xAC, 0xD9, + 0x8A, 0x44, 0xD8, 0xAD, 0xD8, 0xAC, 0x44, 0xD8, + 0xAD, 0xD9, 0x85, 0x44, 0xD8, 0xAD, 0xD9, 0x89, + 0x44, 0xD8, 0xAD, 0xD9, 0x8A, 0x44, 0xD8, 0xAE, + // Bytes 1e40 - 1e7f + 0xD8, 0xAC, 0x44, 0xD8, 0xAE, 0xD8, 0xAD, 0x44, + 0xD8, 0xAE, 0xD9, 0x85, 0x44, 0xD8, 0xAE, 0xD9, + 0x89, 0x44, 0xD8, 0xAE, 0xD9, 0x8A, 0x44, 0xD8, + 0xB3, 0xD8, 0xAC, 0x44, 0xD8, 0xB3, 0xD8, 0xAD, + 0x44, 0xD8, 0xB3, 0xD8, 0xAE, 0x44, 0xD8, 0xB3, + 0xD8, 0xB1, 0x44, 0xD8, 0xB3, 0xD9, 0x85, 0x44, + 0xD8, 0xB3, 0xD9, 0x87, 0x44, 0xD8, 0xB3, 0xD9, + 0x89, 0x44, 0xD8, 0xB3, 0xD9, 0x8A, 0x44, 0xD8, + // Bytes 1e80 - 1ebf + 0xB4, 0xD8, 0xAC, 0x44, 0xD8, 0xB4, 0xD8, 0xAD, + 0x44, 0xD8, 0xB4, 0xD8, 0xAE, 0x44, 0xD8, 0xB4, + 0xD8, 0xB1, 0x44, 0xD8, 0xB4, 0xD9, 0x85, 0x44, + 0xD8, 0xB4, 0xD9, 0x87, 0x44, 0xD8, 0xB4, 0xD9, + 0x89, 0x44, 0xD8, 0xB4, 0xD9, 0x8A, 0x44, 0xD8, + 0xB5, 0xD8, 0xAD, 0x44, 0xD8, 0xB5, 0xD8, 0xAE, + 0x44, 0xD8, 0xB5, 0xD8, 0xB1, 0x44, 0xD8, 0xB5, + 0xD9, 0x85, 0x44, 0xD8, 0xB5, 0xD9, 0x89, 0x44, + // Bytes 1ec0 - 1eff + 0xD8, 0xB5, 0xD9, 0x8A, 0x44, 0xD8, 0xB6, 0xD8, + 0xAC, 0x44, 0xD8, 0xB6, 0xD8, 0xAD, 0x44, 0xD8, + 0xB6, 0xD8, 0xAE, 0x44, 0xD8, 0xB6, 0xD8, 0xB1, + 0x44, 0xD8, 0xB6, 0xD9, 0x85, 0x44, 0xD8, 0xB6, + 0xD9, 0x89, 0x44, 0xD8, 0xB6, 0xD9, 0x8A, 0x44, + 0xD8, 0xB7, 0xD8, 0xAD, 0x44, 0xD8, 0xB7, 0xD9, + 0x85, 0x44, 0xD8, 0xB7, 0xD9, 0x89, 0x44, 0xD8, + 0xB7, 0xD9, 0x8A, 0x44, 0xD8, 0xB8, 0xD9, 0x85, + // Bytes 1f00 - 1f3f + 0x44, 0xD8, 0xB9, 0xD8, 0xAC, 0x44, 0xD8, 0xB9, + 0xD9, 0x85, 0x44, 0xD8, 0xB9, 0xD9, 0x89, 0x44, + 0xD8, 0xB9, 0xD9, 0x8A, 0x44, 0xD8, 0xBA, 0xD8, + 0xAC, 0x44, 0xD8, 0xBA, 0xD9, 0x85, 0x44, 0xD8, + 0xBA, 0xD9, 0x89, 0x44, 0xD8, 0xBA, 0xD9, 0x8A, + 0x44, 0xD9, 0x81, 0xD8, 0xAC, 0x44, 0xD9, 0x81, + 0xD8, 0xAD, 0x44, 0xD9, 0x81, 0xD8, 0xAE, 0x44, + 0xD9, 0x81, 0xD9, 0x85, 0x44, 0xD9, 0x81, 0xD9, + // Bytes 1f40 - 1f7f + 0x89, 0x44, 0xD9, 0x81, 0xD9, 0x8A, 0x44, 0xD9, + 0x82, 0xD8, 0xAD, 0x44, 0xD9, 0x82, 0xD9, 0x85, + 0x44, 0xD9, 0x82, 0xD9, 0x89, 0x44, 0xD9, 0x82, + 0xD9, 0x8A, 0x44, 0xD9, 0x83, 0xD8, 0xA7, 0x44, + 0xD9, 0x83, 0xD8, 0xAC, 0x44, 0xD9, 0x83, 0xD8, + 0xAD, 0x44, 0xD9, 0x83, 0xD8, 0xAE, 0x44, 0xD9, + 0x83, 0xD9, 0x84, 0x44, 0xD9, 0x83, 0xD9, 0x85, + 0x44, 0xD9, 0x83, 0xD9, 0x89, 0x44, 0xD9, 0x83, + // Bytes 1f80 - 1fbf + 0xD9, 0x8A, 0x44, 0xD9, 0x84, 0xD8, 0xA7, 0x44, + 0xD9, 0x84, 0xD8, 0xAC, 0x44, 0xD9, 0x84, 0xD8, + 0xAD, 0x44, 0xD9, 0x84, 0xD8, 0xAE, 0x44, 0xD9, + 0x84, 0xD9, 0x85, 0x44, 0xD9, 0x84, 0xD9, 0x87, + 0x44, 0xD9, 0x84, 0xD9, 0x89, 0x44, 0xD9, 0x84, + 0xD9, 0x8A, 0x44, 0xD9, 0x85, 0xD8, 0xA7, 0x44, + 0xD9, 0x85, 0xD8, 0xAC, 0x44, 0xD9, 0x85, 0xD8, + 0xAD, 0x44, 0xD9, 0x85, 0xD8, 0xAE, 0x44, 0xD9, + // Bytes 1fc0 - 1fff + 0x85, 0xD9, 0x85, 0x44, 0xD9, 0x85, 0xD9, 0x89, + 0x44, 0xD9, 0x85, 0xD9, 0x8A, 0x44, 0xD9, 0x86, + 0xD8, 0xAC, 0x44, 0xD9, 0x86, 0xD8, 0xAD, 0x44, + 0xD9, 0x86, 0xD8, 0xAE, 0x44, 0xD9, 0x86, 0xD8, + 0xB1, 0x44, 0xD9, 0x86, 0xD8, 0xB2, 0x44, 0xD9, + 0x86, 0xD9, 0x85, 0x44, 0xD9, 0x86, 0xD9, 0x86, + 0x44, 0xD9, 0x86, 0xD9, 0x87, 0x44, 0xD9, 0x86, + 0xD9, 0x89, 0x44, 0xD9, 0x86, 0xD9, 0x8A, 0x44, + // Bytes 2000 - 203f + 0xD9, 0x87, 0xD8, 0xAC, 0x44, 0xD9, 0x87, 0xD9, + 0x85, 0x44, 0xD9, 0x87, 0xD9, 0x89, 0x44, 0xD9, + 0x87, 0xD9, 0x8A, 0x44, 0xD9, 0x88, 0xD9, 0xB4, + 0x44, 0xD9, 0x8A, 0xD8, 0xAC, 0x44, 0xD9, 0x8A, + 0xD8, 0xAD, 0x44, 0xD9, 0x8A, 0xD8, 0xAE, 0x44, + 0xD9, 0x8A, 0xD8, 0xB1, 0x44, 0xD9, 0x8A, 0xD8, + 0xB2, 0x44, 0xD9, 0x8A, 0xD9, 0x85, 0x44, 0xD9, + 0x8A, 0xD9, 0x86, 0x44, 0xD9, 0x8A, 0xD9, 0x87, + // Bytes 2040 - 207f + 0x44, 0xD9, 0x8A, 0xD9, 0x89, 0x44, 0xD9, 0x8A, + 0xD9, 0x8A, 0x44, 0xD9, 0x8A, 0xD9, 0xB4, 0x44, + 0xDB, 0x87, 0xD9, 0xB4, 0x45, 0x28, 0xE1, 0x84, + 0x80, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x82, 0x29, + 0x45, 0x28, 0xE1, 0x84, 0x83, 0x29, 0x45, 0x28, + 0xE1, 0x84, 0x85, 0x29, 0x45, 0x28, 0xE1, 0x84, + 0x86, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x87, 0x29, + 0x45, 0x28, 0xE1, 0x84, 0x89, 0x29, 0x45, 0x28, + // Bytes 2080 - 20bf + 0xE1, 0x84, 0x8B, 0x29, 0x45, 0x28, 0xE1, 0x84, + 0x8C, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x8E, 0x29, + 0x45, 0x28, 0xE1, 0x84, 0x8F, 0x29, 0x45, 0x28, + 0xE1, 0x84, 0x90, 0x29, 0x45, 0x28, 0xE1, 0x84, + 0x91, 0x29, 0x45, 0x28, 0xE1, 0x84, 0x92, 0x29, + 0x45, 0x28, 0xE4, 0xB8, 0x80, 0x29, 0x45, 0x28, + 0xE4, 0xB8, 0x83, 0x29, 0x45, 0x28, 0xE4, 0xB8, + 0x89, 0x29, 0x45, 0x28, 0xE4, 0xB9, 0x9D, 0x29, + // Bytes 20c0 - 20ff + 0x45, 0x28, 0xE4, 0xBA, 0x8C, 0x29, 0x45, 0x28, + 0xE4, 0xBA, 0x94, 0x29, 0x45, 0x28, 0xE4, 0xBB, + 0xA3, 0x29, 0x45, 0x28, 0xE4, 0xBC, 0x81, 0x29, + 0x45, 0x28, 0xE4, 0xBC, 0x91, 0x29, 0x45, 0x28, + 0xE5, 0x85, 0xAB, 0x29, 0x45, 0x28, 0xE5, 0x85, + 0xAD, 0x29, 0x45, 0x28, 0xE5, 0x8A, 0xB4, 0x29, + 0x45, 0x28, 0xE5, 0x8D, 0x81, 0x29, 0x45, 0x28, + 0xE5, 0x8D, 0x94, 0x29, 0x45, 0x28, 0xE5, 0x90, + // Bytes 2100 - 213f + 0x8D, 0x29, 0x45, 0x28, 0xE5, 0x91, 0xBC, 0x29, + 0x45, 0x28, 0xE5, 0x9B, 0x9B, 0x29, 0x45, 0x28, + 0xE5, 0x9C, 0x9F, 0x29, 0x45, 0x28, 0xE5, 0xAD, + 0xA6, 0x29, 0x45, 0x28, 0xE6, 0x97, 0xA5, 0x29, + 0x45, 0x28, 0xE6, 0x9C, 0x88, 0x29, 0x45, 0x28, + 0xE6, 0x9C, 0x89, 0x29, 0x45, 0x28, 0xE6, 0x9C, + 0xA8, 0x29, 0x45, 0x28, 0xE6, 0xA0, 0xAA, 0x29, + 0x45, 0x28, 0xE6, 0xB0, 0xB4, 0x29, 0x45, 0x28, + // Bytes 2140 - 217f + 0xE7, 0x81, 0xAB, 0x29, 0x45, 0x28, 0xE7, 0x89, + 0xB9, 0x29, 0x45, 0x28, 0xE7, 0x9B, 0xA3, 0x29, + 0x45, 0x28, 0xE7, 0xA4, 0xBE, 0x29, 0x45, 0x28, + 0xE7, 0xA5, 0x9D, 0x29, 0x45, 0x28, 0xE7, 0xA5, + 0xAD, 0x29, 0x45, 0x28, 0xE8, 0x87, 0xAA, 0x29, + 0x45, 0x28, 0xE8, 0x87, 0xB3, 0x29, 0x45, 0x28, + 0xE8, 0xB2, 0xA1, 0x29, 0x45, 0x28, 0xE8, 0xB3, + 0x87, 0x29, 0x45, 0x28, 0xE9, 0x87, 0x91, 0x29, + // Bytes 2180 - 21bf + 0x45, 0x30, 0xE2, 0x81, 0x84, 0x33, 0x45, 0x31, + 0x30, 0xE6, 0x97, 0xA5, 0x45, 0x31, 0x30, 0xE6, + 0x9C, 0x88, 0x45, 0x31, 0x30, 0xE7, 0x82, 0xB9, + 0x45, 0x31, 0x31, 0xE6, 0x97, 0xA5, 0x45, 0x31, + 0x31, 0xE6, 0x9C, 0x88, 0x45, 0x31, 0x31, 0xE7, + 0x82, 0xB9, 0x45, 0x31, 0x32, 0xE6, 0x97, 0xA5, + 0x45, 0x31, 0x32, 0xE6, 0x9C, 0x88, 0x45, 0x31, + 0x32, 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x33, 0xE6, + // Bytes 21c0 - 21ff + 0x97, 0xA5, 0x45, 0x31, 0x33, 0xE7, 0x82, 0xB9, + 0x45, 0x31, 0x34, 0xE6, 0x97, 0xA5, 0x45, 0x31, + 0x34, 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x35, 0xE6, + 0x97, 0xA5, 0x45, 0x31, 0x35, 0xE7, 0x82, 0xB9, + 0x45, 0x31, 0x36, 0xE6, 0x97, 0xA5, 0x45, 0x31, + 0x36, 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x37, 0xE6, + 0x97, 0xA5, 0x45, 0x31, 0x37, 0xE7, 0x82, 0xB9, + 0x45, 0x31, 0x38, 0xE6, 0x97, 0xA5, 0x45, 0x31, + // Bytes 2200 - 223f + 0x38, 0xE7, 0x82, 0xB9, 0x45, 0x31, 0x39, 0xE6, + 0x97, 0xA5, 0x45, 0x31, 0x39, 0xE7, 0x82, 0xB9, + 0x45, 0x31, 0xE2, 0x81, 0x84, 0x32, 0x45, 0x31, + 0xE2, 0x81, 0x84, 0x33, 0x45, 0x31, 0xE2, 0x81, + 0x84, 0x34, 0x45, 0x31, 0xE2, 0x81, 0x84, 0x35, + 0x45, 0x31, 0xE2, 0x81, 0x84, 0x36, 0x45, 0x31, + 0xE2, 0x81, 0x84, 0x37, 0x45, 0x31, 0xE2, 0x81, + 0x84, 0x38, 0x45, 0x31, 0xE2, 0x81, 0x84, 0x39, + // Bytes 2240 - 227f + 0x45, 0x32, 0x30, 0xE6, 0x97, 0xA5, 0x45, 0x32, + 0x30, 0xE7, 0x82, 0xB9, 0x45, 0x32, 0x31, 0xE6, + 0x97, 0xA5, 0x45, 0x32, 0x31, 0xE7, 0x82, 0xB9, + 0x45, 0x32, 0x32, 0xE6, 0x97, 0xA5, 0x45, 0x32, + 0x32, 0xE7, 0x82, 0xB9, 0x45, 0x32, 0x33, 0xE6, + 0x97, 0xA5, 0x45, 0x32, 0x33, 0xE7, 0x82, 0xB9, + 0x45, 0x32, 0x34, 0xE6, 0x97, 0xA5, 0x45, 0x32, + 0x34, 0xE7, 0x82, 0xB9, 0x45, 0x32, 0x35, 0xE6, + // Bytes 2280 - 22bf + 0x97, 0xA5, 0x45, 0x32, 0x36, 0xE6, 0x97, 0xA5, + 0x45, 0x32, 0x37, 0xE6, 0x97, 0xA5, 0x45, 0x32, + 0x38, 0xE6, 0x97, 0xA5, 0x45, 0x32, 0x39, 0xE6, + 0x97, 0xA5, 0x45, 0x32, 0xE2, 0x81, 0x84, 0x33, + 0x45, 0x32, 0xE2, 0x81, 0x84, 0x35, 0x45, 0x33, + 0x30, 0xE6, 0x97, 0xA5, 0x45, 0x33, 0x31, 0xE6, + 0x97, 0xA5, 0x45, 0x33, 0xE2, 0x81, 0x84, 0x34, + 0x45, 0x33, 0xE2, 0x81, 0x84, 0x35, 0x45, 0x33, + // Bytes 22c0 - 22ff + 0xE2, 0x81, 0x84, 0x38, 0x45, 0x34, 0xE2, 0x81, + 0x84, 0x35, 0x45, 0x35, 0xE2, 0x81, 0x84, 0x36, + 0x45, 0x35, 0xE2, 0x81, 0x84, 0x38, 0x45, 0x37, + 0xE2, 0x81, 0x84, 0x38, 0x45, 0x41, 0xE2, 0x88, + 0x95, 0x6D, 0x45, 0x56, 0xE2, 0x88, 0x95, 0x6D, + 0x45, 0x6D, 0xE2, 0x88, 0x95, 0x73, 0x46, 0x31, + 0xE2, 0x81, 0x84, 0x31, 0x30, 0x46, 0x43, 0xE2, + 0x88, 0x95, 0x6B, 0x67, 0x46, 0x6D, 0xE2, 0x88, + // Bytes 2300 - 233f + 0x95, 0x73, 0x32, 0x46, 0xD8, 0xA8, 0xD8, 0xAD, + 0xD9, 0x8A, 0x46, 0xD8, 0xA8, 0xD8, 0xAE, 0xD9, + 0x8A, 0x46, 0xD8, 0xAA, 0xD8, 0xAC, 0xD9, 0x85, + 0x46, 0xD8, 0xAA, 0xD8, 0xAC, 0xD9, 0x89, 0x46, + 0xD8, 0xAA, 0xD8, 0xAC, 0xD9, 0x8A, 0x46, 0xD8, + 0xAA, 0xD8, 0xAD, 0xD8, 0xAC, 0x46, 0xD8, 0xAA, + 0xD8, 0xAD, 0xD9, 0x85, 0x46, 0xD8, 0xAA, 0xD8, + 0xAE, 0xD9, 0x85, 0x46, 0xD8, 0xAA, 0xD8, 0xAE, + // Bytes 2340 - 237f + 0xD9, 0x89, 0x46, 0xD8, 0xAA, 0xD8, 0xAE, 0xD9, + 0x8A, 0x46, 0xD8, 0xAA, 0xD9, 0x85, 0xD8, 0xAC, + 0x46, 0xD8, 0xAA, 0xD9, 0x85, 0xD8, 0xAD, 0x46, + 0xD8, 0xAA, 0xD9, 0x85, 0xD8, 0xAE, 0x46, 0xD8, + 0xAA, 0xD9, 0x85, 0xD9, 0x89, 0x46, 0xD8, 0xAA, + 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD8, 0xAC, 0xD8, + 0xAD, 0xD9, 0x89, 0x46, 0xD8, 0xAC, 0xD8, 0xAD, + 0xD9, 0x8A, 0x46, 0xD8, 0xAC, 0xD9, 0x85, 0xD8, + // Bytes 2380 - 23bf + 0xAD, 0x46, 0xD8, 0xAC, 0xD9, 0x85, 0xD9, 0x89, + 0x46, 0xD8, 0xAC, 0xD9, 0x85, 0xD9, 0x8A, 0x46, + 0xD8, 0xAD, 0xD8, 0xAC, 0xD9, 0x8A, 0x46, 0xD8, + 0xAD, 0xD9, 0x85, 0xD9, 0x89, 0x46, 0xD8, 0xAD, + 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD8, 0xB3, 0xD8, + 0xAC, 0xD8, 0xAD, 0x46, 0xD8, 0xB3, 0xD8, 0xAC, + 0xD9, 0x89, 0x46, 0xD8, 0xB3, 0xD8, 0xAD, 0xD8, + 0xAC, 0x46, 0xD8, 0xB3, 0xD8, 0xAE, 0xD9, 0x89, + // Bytes 23c0 - 23ff + 0x46, 0xD8, 0xB3, 0xD8, 0xAE, 0xD9, 0x8A, 0x46, + 0xD8, 0xB3, 0xD9, 0x85, 0xD8, 0xAC, 0x46, 0xD8, + 0xB3, 0xD9, 0x85, 0xD8, 0xAD, 0x46, 0xD8, 0xB3, + 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD8, 0xB4, 0xD8, + 0xAC, 0xD9, 0x8A, 0x46, 0xD8, 0xB4, 0xD8, 0xAD, + 0xD9, 0x85, 0x46, 0xD8, 0xB4, 0xD8, 0xAD, 0xD9, + 0x8A, 0x46, 0xD8, 0xB4, 0xD9, 0x85, 0xD8, 0xAE, + 0x46, 0xD8, 0xB4, 0xD9, 0x85, 0xD9, 0x85, 0x46, + // Bytes 2400 - 243f + 0xD8, 0xB5, 0xD8, 0xAD, 0xD8, 0xAD, 0x46, 0xD8, + 0xB5, 0xD8, 0xAD, 0xD9, 0x8A, 0x46, 0xD8, 0xB5, + 0xD9, 0x84, 0xD9, 0x89, 0x46, 0xD8, 0xB5, 0xD9, + 0x84, 0xDB, 0x92, 0x46, 0xD8, 0xB5, 0xD9, 0x85, + 0xD9, 0x85, 0x46, 0xD8, 0xB6, 0xD8, 0xAD, 0xD9, + 0x89, 0x46, 0xD8, 0xB6, 0xD8, 0xAD, 0xD9, 0x8A, + 0x46, 0xD8, 0xB6, 0xD8, 0xAE, 0xD9, 0x85, 0x46, + 0xD8, 0xB7, 0xD9, 0x85, 0xD8, 0xAD, 0x46, 0xD8, + // Bytes 2440 - 247f + 0xB7, 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD8, 0xB7, + 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD8, 0xB9, 0xD8, + 0xAC, 0xD9, 0x85, 0x46, 0xD8, 0xB9, 0xD9, 0x85, + 0xD9, 0x85, 0x46, 0xD8, 0xB9, 0xD9, 0x85, 0xD9, + 0x89, 0x46, 0xD8, 0xB9, 0xD9, 0x85, 0xD9, 0x8A, + 0x46, 0xD8, 0xBA, 0xD9, 0x85, 0xD9, 0x85, 0x46, + 0xD8, 0xBA, 0xD9, 0x85, 0xD9, 0x89, 0x46, 0xD8, + 0xBA, 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x81, + // Bytes 2480 - 24bf + 0xD8, 0xAE, 0xD9, 0x85, 0x46, 0xD9, 0x81, 0xD9, + 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x82, 0xD9, 0x84, + 0xDB, 0x92, 0x46, 0xD9, 0x82, 0xD9, 0x85, 0xD8, + 0xAD, 0x46, 0xD9, 0x82, 0xD9, 0x85, 0xD9, 0x85, + 0x46, 0xD9, 0x82, 0xD9, 0x85, 0xD9, 0x8A, 0x46, + 0xD9, 0x83, 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD9, + 0x83, 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x84, + 0xD8, 0xAC, 0xD8, 0xAC, 0x46, 0xD9, 0x84, 0xD8, + // Bytes 24c0 - 24ff + 0xAC, 0xD9, 0x85, 0x46, 0xD9, 0x84, 0xD8, 0xAC, + 0xD9, 0x8A, 0x46, 0xD9, 0x84, 0xD8, 0xAD, 0xD9, + 0x85, 0x46, 0xD9, 0x84, 0xD8, 0xAD, 0xD9, 0x89, + 0x46, 0xD9, 0x84, 0xD8, 0xAD, 0xD9, 0x8A, 0x46, + 0xD9, 0x84, 0xD8, 0xAE, 0xD9, 0x85, 0x46, 0xD9, + 0x84, 0xD9, 0x85, 0xD8, 0xAD, 0x46, 0xD9, 0x84, + 0xD9, 0x85, 0xD9, 0x8A, 0x46, 0xD9, 0x85, 0xD8, + 0xAC, 0xD8, 0xAD, 0x46, 0xD9, 0x85, 0xD8, 0xAC, + // Bytes 2500 - 253f + 0xD8, 0xAE, 0x46, 0xD9, 0x85, 0xD8, 0xAC, 0xD9, + 0x85, 0x46, 0xD9, 0x85, 0xD8, 0xAC, 0xD9, 0x8A, + 0x46, 0xD9, 0x85, 0xD8, 0xAD, 0xD8, 0xAC, 0x46, + 0xD9, 0x85, 0xD8, 0xAD, 0xD9, 0x85, 0x46, 0xD9, + 0x85, 0xD8, 0xAD, 0xD9, 0x8A, 0x46, 0xD9, 0x85, + 0xD8, 0xAE, 0xD8, 0xAC, 0x46, 0xD9, 0x85, 0xD8, + 0xAE, 0xD9, 0x85, 0x46, 0xD9, 0x85, 0xD8, 0xAE, + 0xD9, 0x8A, 0x46, 0xD9, 0x85, 0xD9, 0x85, 0xD9, + // Bytes 2540 - 257f + 0x8A, 0x46, 0xD9, 0x86, 0xD8, 0xAC, 0xD8, 0xAD, + 0x46, 0xD9, 0x86, 0xD8, 0xAC, 0xD9, 0x85, 0x46, + 0xD9, 0x86, 0xD8, 0xAC, 0xD9, 0x89, 0x46, 0xD9, + 0x86, 0xD8, 0xAC, 0xD9, 0x8A, 0x46, 0xD9, 0x86, + 0xD8, 0xAD, 0xD9, 0x85, 0x46, 0xD9, 0x86, 0xD8, + 0xAD, 0xD9, 0x89, 0x46, 0xD9, 0x86, 0xD8, 0xAD, + 0xD9, 0x8A, 0x46, 0xD9, 0x86, 0xD9, 0x85, 0xD9, + 0x89, 0x46, 0xD9, 0x86, 0xD9, 0x85, 0xD9, 0x8A, + // Bytes 2580 - 25bf + 0x46, 0xD9, 0x87, 0xD9, 0x85, 0xD8, 0xAC, 0x46, + 0xD9, 0x87, 0xD9, 0x85, 0xD9, 0x85, 0x46, 0xD9, + 0x8A, 0xD8, 0xAC, 0xD9, 0x8A, 0x46, 0xD9, 0x8A, + 0xD8, 0xAD, 0xD9, 0x8A, 0x46, 0xD9, 0x8A, 0xD9, + 0x85, 0xD9, 0x85, 0x46, 0xD9, 0x8A, 0xD9, 0x85, + 0xD9, 0x8A, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD8, + 0xA7, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD8, 0xAC, + 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD8, 0xAD, 0x46, + // Bytes 25c0 - 25ff + 0xD9, 0x8A, 0xD9, 0x94, 0xD8, 0xAE, 0x46, 0xD9, + 0x8A, 0xD9, 0x94, 0xD8, 0xB1, 0x46, 0xD9, 0x8A, + 0xD9, 0x94, 0xD8, 0xB2, 0x46, 0xD9, 0x8A, 0xD9, + 0x94, 0xD9, 0x85, 0x46, 0xD9, 0x8A, 0xD9, 0x94, + 0xD9, 0x86, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD9, + 0x87, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD9, 0x88, + 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xD9, 0x89, 0x46, + 0xD9, 0x8A, 0xD9, 0x94, 0xD9, 0x8A, 0x46, 0xD9, + // Bytes 2600 - 263f + 0x8A, 0xD9, 0x94, 0xDB, 0x86, 0x46, 0xD9, 0x8A, + 0xD9, 0x94, 0xDB, 0x87, 0x46, 0xD9, 0x8A, 0xD9, + 0x94, 0xDB, 0x88, 0x46, 0xD9, 0x8A, 0xD9, 0x94, + 0xDB, 0x90, 0x46, 0xD9, 0x8A, 0xD9, 0x94, 0xDB, + 0x95, 0x46, 0xE0, 0xB9, 0x8D, 0xE0, 0xB8, 0xB2, + 0x46, 0xE0, 0xBA, 0xAB, 0xE0, 0xBA, 0x99, 0x46, + 0xE0, 0xBA, 0xAB, 0xE0, 0xBA, 0xA1, 0x46, 0xE0, + 0xBB, 0x8D, 0xE0, 0xBA, 0xB2, 0x46, 0xE0, 0xBD, + // Bytes 2640 - 267f + 0x80, 0xE0, 0xBE, 0xB5, 0x46, 0xE0, 0xBD, 0x82, + 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBD, 0x8C, 0xE0, + 0xBE, 0xB7, 0x46, 0xE0, 0xBD, 0x91, 0xE0, 0xBE, + 0xB7, 0x46, 0xE0, 0xBD, 0x96, 0xE0, 0xBE, 0xB7, + 0x46, 0xE0, 0xBD, 0x9B, 0xE0, 0xBE, 0xB7, 0x46, + 0xE0, 0xBE, 0x90, 0xE0, 0xBE, 0xB5, 0x46, 0xE0, + 0xBE, 0x92, 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBE, + 0x9C, 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBE, 0xA1, + // Bytes 2680 - 26bf + 0xE0, 0xBE, 0xB7, 0x46, 0xE0, 0xBE, 0xA6, 0xE0, + 0xBE, 0xB7, 0x46, 0xE0, 0xBE, 0xAB, 0xE0, 0xBE, + 0xB7, 0x46, 0xE2, 0x80, 0xB2, 0xE2, 0x80, 0xB2, + 0x46, 0xE2, 0x80, 0xB5, 0xE2, 0x80, 0xB5, 0x46, + 0xE2, 0x88, 0xAB, 0xE2, 0x88, 0xAB, 0x46, 0xE2, + 0x88, 0xAE, 0xE2, 0x88, 0xAE, 0x46, 0xE3, 0x81, + 0xBB, 0xE3, 0x81, 0x8B, 0x46, 0xE3, 0x82, 0x88, + 0xE3, 0x82, 0x8A, 0x46, 0xE3, 0x82, 0xAD, 0xE3, + // Bytes 26c0 - 26ff + 0x83, 0xAD, 0x46, 0xE3, 0x82, 0xB3, 0xE3, 0x82, + 0xB3, 0x46, 0xE3, 0x82, 0xB3, 0xE3, 0x83, 0x88, + 0x46, 0xE3, 0x83, 0x88, 0xE3, 0x83, 0xB3, 0x46, + 0xE3, 0x83, 0x8A, 0xE3, 0x83, 0x8E, 0x46, 0xE3, + 0x83, 0x9B, 0xE3, 0x83, 0xB3, 0x46, 0xE3, 0x83, + 0x9F, 0xE3, 0x83, 0xAA, 0x46, 0xE3, 0x83, 0xAA, + 0xE3, 0x83, 0xA9, 0x46, 0xE3, 0x83, 0xAC, 0xE3, + 0x83, 0xA0, 0x46, 0xE5, 0xA4, 0xA7, 0xE6, 0xAD, + // Bytes 2700 - 273f + 0xA3, 0x46, 0xE5, 0xB9, 0xB3, 0xE6, 0x88, 0x90, + 0x46, 0xE6, 0x98, 0x8E, 0xE6, 0xB2, 0xBB, 0x46, + 0xE6, 0x98, 0xAD, 0xE5, 0x92, 0x8C, 0x47, 0x72, + 0x61, 0x64, 0xE2, 0x88, 0x95, 0x73, 0x47, 0xE3, + 0x80, 0x94, 0x53, 0xE3, 0x80, 0x95, 0x48, 0x28, + 0xE1, 0x84, 0x80, 0xE1, 0x85, 0xA1, 0x29, 0x48, + 0x28, 0xE1, 0x84, 0x82, 0xE1, 0x85, 0xA1, 0x29, + 0x48, 0x28, 0xE1, 0x84, 0x83, 0xE1, 0x85, 0xA1, + // Bytes 2740 - 277f + 0x29, 0x48, 0x28, 0xE1, 0x84, 0x85, 0xE1, 0x85, + 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x86, 0xE1, + 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x87, + 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, + 0x89, 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, + 0x84, 0x8B, 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, + 0xE1, 0x84, 0x8C, 0xE1, 0x85, 0xA1, 0x29, 0x48, + 0x28, 0xE1, 0x84, 0x8C, 0xE1, 0x85, 0xAE, 0x29, + // Bytes 2780 - 27bf + 0x48, 0x28, 0xE1, 0x84, 0x8E, 0xE1, 0x85, 0xA1, + 0x29, 0x48, 0x28, 0xE1, 0x84, 0x8F, 0xE1, 0x85, + 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x90, 0xE1, + 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, 0x91, + 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x28, 0xE1, 0x84, + 0x92, 0xE1, 0x85, 0xA1, 0x29, 0x48, 0x72, 0x61, + 0x64, 0xE2, 0x88, 0x95, 0x73, 0x32, 0x48, 0xD8, + 0xA7, 0xD9, 0x83, 0xD8, 0xA8, 0xD8, 0xB1, 0x48, + // Bytes 27c0 - 27ff + 0xD8, 0xA7, 0xD9, 0x84, 0xD9, 0x84, 0xD9, 0x87, + 0x48, 0xD8, 0xB1, 0xD8, 0xB3, 0xD9, 0x88, 0xD9, + 0x84, 0x48, 0xD8, 0xB1, 0xDB, 0x8C, 0xD8, 0xA7, + 0xD9, 0x84, 0x48, 0xD8, 0xB5, 0xD9, 0x84, 0xD8, + 0xB9, 0xD9, 0x85, 0x48, 0xD8, 0xB9, 0xD9, 0x84, + 0xD9, 0x8A, 0xD9, 0x87, 0x48, 0xD9, 0x85, 0xD8, + 0xAD, 0xD9, 0x85, 0xD8, 0xAF, 0x48, 0xD9, 0x88, + 0xD8, 0xB3, 0xD9, 0x84, 0xD9, 0x85, 0x49, 0xE2, + // Bytes 2800 - 283f + 0x80, 0xB2, 0xE2, 0x80, 0xB2, 0xE2, 0x80, 0xB2, + 0x49, 0xE2, 0x80, 0xB5, 0xE2, 0x80, 0xB5, 0xE2, + 0x80, 0xB5, 0x49, 0xE2, 0x88, 0xAB, 0xE2, 0x88, + 0xAB, 0xE2, 0x88, 0xAB, 0x49, 0xE2, 0x88, 0xAE, + 0xE2, 0x88, 0xAE, 0xE2, 0x88, 0xAE, 0x49, 0xE3, + 0x80, 0x94, 0xE4, 0xB8, 0x89, 0xE3, 0x80, 0x95, + 0x49, 0xE3, 0x80, 0x94, 0xE4, 0xBA, 0x8C, 0xE3, + 0x80, 0x95, 0x49, 0xE3, 0x80, 0x94, 0xE5, 0x8B, + // Bytes 2840 - 287f + 0x9D, 0xE3, 0x80, 0x95, 0x49, 0xE3, 0x80, 0x94, + 0xE5, 0xAE, 0x89, 0xE3, 0x80, 0x95, 0x49, 0xE3, + 0x80, 0x94, 0xE6, 0x89, 0x93, 0xE3, 0x80, 0x95, + 0x49, 0xE3, 0x80, 0x94, 0xE6, 0x95, 0x97, 0xE3, + 0x80, 0x95, 0x49, 0xE3, 0x80, 0x94, 0xE6, 0x9C, + 0xAC, 0xE3, 0x80, 0x95, 0x49, 0xE3, 0x80, 0x94, + 0xE7, 0x82, 0xB9, 0xE3, 0x80, 0x95, 0x49, 0xE3, + 0x80, 0x94, 0xE7, 0x9B, 0x97, 0xE3, 0x80, 0x95, + // Bytes 2880 - 28bf + 0x49, 0xE3, 0x82, 0xA2, 0xE3, 0x83, 0xBC, 0xE3, + 0x83, 0xAB, 0x49, 0xE3, 0x82, 0xA4, 0xE3, 0x83, + 0xB3, 0xE3, 0x83, 0x81, 0x49, 0xE3, 0x82, 0xA6, + 0xE3, 0x82, 0xA9, 0xE3, 0x83, 0xB3, 0x49, 0xE3, + 0x82, 0xAA, 0xE3, 0x83, 0xB3, 0xE3, 0x82, 0xB9, + 0x49, 0xE3, 0x82, 0xAA, 0xE3, 0x83, 0xBC, 0xE3, + 0x83, 0xA0, 0x49, 0xE3, 0x82, 0xAB, 0xE3, 0x82, + 0xA4, 0xE3, 0x83, 0xAA, 0x49, 0xE3, 0x82, 0xB1, + // Bytes 28c0 - 28ff + 0xE3, 0x83, 0xBC, 0xE3, 0x82, 0xB9, 0x49, 0xE3, + 0x82, 0xB3, 0xE3, 0x83, 0xAB, 0xE3, 0x83, 0x8A, + 0x49, 0xE3, 0x82, 0xBB, 0xE3, 0x83, 0xB3, 0xE3, + 0x83, 0x81, 0x49, 0xE3, 0x82, 0xBB, 0xE3, 0x83, + 0xB3, 0xE3, 0x83, 0x88, 0x49, 0xE3, 0x83, 0x86, + 0xE3, 0x82, 0x99, 0xE3, 0x82, 0xB7, 0x49, 0xE3, + 0x83, 0x88, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xAB, + 0x49, 0xE3, 0x83, 0x8E, 0xE3, 0x83, 0x83, 0xE3, + // Bytes 2900 - 293f + 0x83, 0x88, 0x49, 0xE3, 0x83, 0x8F, 0xE3, 0x82, + 0xA4, 0xE3, 0x83, 0x84, 0x49, 0xE3, 0x83, 0x92, + 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xAB, 0x49, 0xE3, + 0x83, 0x92, 0xE3, 0x82, 0x9A, 0xE3, 0x82, 0xB3, + 0x49, 0xE3, 0x83, 0x95, 0xE3, 0x83, 0xA9, 0xE3, + 0x83, 0xB3, 0x49, 0xE3, 0x83, 0x98, 0xE3, 0x82, + 0x9A, 0xE3, 0x82, 0xBD, 0x49, 0xE3, 0x83, 0x98, + 0xE3, 0x83, 0xAB, 0xE3, 0x83, 0x84, 0x49, 0xE3, + // Bytes 2940 - 297f + 0x83, 0x9B, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0xAB, + 0x49, 0xE3, 0x83, 0x9B, 0xE3, 0x83, 0xBC, 0xE3, + 0x83, 0xB3, 0x49, 0xE3, 0x83, 0x9E, 0xE3, 0x82, + 0xA4, 0xE3, 0x83, 0xAB, 0x49, 0xE3, 0x83, 0x9E, + 0xE3, 0x83, 0x83, 0xE3, 0x83, 0x8F, 0x49, 0xE3, + 0x83, 0x9E, 0xE3, 0x83, 0xAB, 0xE3, 0x82, 0xAF, + 0x49, 0xE3, 0x83, 0xA4, 0xE3, 0x83, 0xBC, 0xE3, + 0x83, 0xAB, 0x49, 0xE3, 0x83, 0xA6, 0xE3, 0x82, + // Bytes 2980 - 29bf + 0xA2, 0xE3, 0x83, 0xB3, 0x49, 0xE3, 0x83, 0xAF, + 0xE3, 0x83, 0x83, 0xE3, 0x83, 0x88, 0x4C, 0xE2, + 0x80, 0xB2, 0xE2, 0x80, 0xB2, 0xE2, 0x80, 0xB2, + 0xE2, 0x80, 0xB2, 0x4C, 0xE2, 0x88, 0xAB, 0xE2, + 0x88, 0xAB, 0xE2, 0x88, 0xAB, 0xE2, 0x88, 0xAB, + 0x4C, 0xE3, 0x82, 0xA2, 0xE3, 0x83, 0xAB, 0xE3, + 0x83, 0x95, 0xE3, 0x82, 0xA1, 0x4C, 0xE3, 0x82, + 0xA8, 0xE3, 0x83, 0xBC, 0xE3, 0x82, 0xAB, 0xE3, + // Bytes 29c0 - 29ff + 0x83, 0xBC, 0x4C, 0xE3, 0x82, 0xAB, 0xE3, 0x82, + 0x99, 0xE3, 0x83, 0xAD, 0xE3, 0x83, 0xB3, 0x4C, + 0xE3, 0x82, 0xAB, 0xE3, 0x82, 0x99, 0xE3, 0x83, + 0xB3, 0xE3, 0x83, 0x9E, 0x4C, 0xE3, 0x82, 0xAB, + 0xE3, 0x83, 0xA9, 0xE3, 0x83, 0x83, 0xE3, 0x83, + 0x88, 0x4C, 0xE3, 0x82, 0xAB, 0xE3, 0x83, 0xAD, + 0xE3, 0x83, 0xAA, 0xE3, 0x83, 0xBC, 0x4C, 0xE3, + 0x82, 0xAD, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0x8B, + // Bytes 2a00 - 2a3f + 0xE3, 0x83, 0xBC, 0x4C, 0xE3, 0x82, 0xAD, 0xE3, + 0x83, 0xA5, 0xE3, 0x83, 0xAA, 0xE3, 0x83, 0xBC, + 0x4C, 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0x99, 0xE3, + 0x83, 0xA9, 0xE3, 0x83, 0xA0, 0x4C, 0xE3, 0x82, + 0xAF, 0xE3, 0x83, 0xAD, 0xE3, 0x83, 0xBC, 0xE3, + 0x83, 0x8D, 0x4C, 0xE3, 0x82, 0xB5, 0xE3, 0x82, + 0xA4, 0xE3, 0x82, 0xAF, 0xE3, 0x83, 0xAB, 0x4C, + 0xE3, 0x82, 0xBF, 0xE3, 0x82, 0x99, 0xE3, 0x83, + // Bytes 2a40 - 2a7f + 0xBC, 0xE3, 0x82, 0xB9, 0x4C, 0xE3, 0x83, 0x8F, + 0xE3, 0x82, 0x9A, 0xE3, 0x83, 0xBC, 0xE3, 0x83, + 0x84, 0x4C, 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x9A, + 0xE3, 0x82, 0xAF, 0xE3, 0x83, 0xAB, 0x4C, 0xE3, + 0x83, 0x95, 0xE3, 0x82, 0xA3, 0xE3, 0x83, 0xBC, + 0xE3, 0x83, 0x88, 0x4C, 0xE3, 0x83, 0x98, 0xE3, + 0x82, 0x99, 0xE3, 0x83, 0xBC, 0xE3, 0x82, 0xBF, + 0x4C, 0xE3, 0x83, 0x98, 0xE3, 0x82, 0x9A, 0xE3, + // Bytes 2a80 - 2abf + 0x83, 0x8B, 0xE3, 0x83, 0x92, 0x4C, 0xE3, 0x83, + 0x98, 0xE3, 0x82, 0x9A, 0xE3, 0x83, 0xB3, 0xE3, + 0x82, 0xB9, 0x4C, 0xE3, 0x83, 0x9B, 0xE3, 0x82, + 0x99, 0xE3, 0x83, 0xAB, 0xE3, 0x83, 0x88, 0x4C, + 0xE3, 0x83, 0x9E, 0xE3, 0x82, 0xA4, 0xE3, 0x82, + 0xAF, 0xE3, 0x83, 0xAD, 0x4C, 0xE3, 0x83, 0x9F, + 0xE3, 0x82, 0xAF, 0xE3, 0x83, 0xAD, 0xE3, 0x83, + 0xB3, 0x4C, 0xE3, 0x83, 0xA1, 0xE3, 0x83, 0xBC, + // Bytes 2ac0 - 2aff + 0xE3, 0x83, 0x88, 0xE3, 0x83, 0xAB, 0x4C, 0xE3, + 0x83, 0xAA, 0xE3, 0x83, 0x83, 0xE3, 0x83, 0x88, + 0xE3, 0x83, 0xAB, 0x4C, 0xE3, 0x83, 0xAB, 0xE3, + 0x83, 0x92, 0xE3, 0x82, 0x9A, 0xE3, 0x83, 0xBC, + 0x4C, 0xE6, 0xA0, 0xAA, 0xE5, 0xBC, 0x8F, 0xE4, + 0xBC, 0x9A, 0xE7, 0xA4, 0xBE, 0x4E, 0x28, 0xE1, + 0x84, 0x8B, 0xE1, 0x85, 0xA9, 0xE1, 0x84, 0x92, + 0xE1, 0x85, 0xAE, 0x29, 0x4F, 0xD8, 0xAC, 0xD9, + // Bytes 2b00 - 2b3f + 0x84, 0x20, 0xD8, 0xAC, 0xD9, 0x84, 0xD8, 0xA7, + 0xD9, 0x84, 0xD9, 0x87, 0x4F, 0xE3, 0x82, 0xA2, + 0xE3, 0x83, 0x8F, 0xE3, 0x82, 0x9A, 0xE3, 0x83, + 0xBC, 0xE3, 0x83, 0x88, 0x4F, 0xE3, 0x82, 0xA2, + 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x98, 0xE3, 0x82, + 0x9A, 0xE3, 0x82, 0xA2, 0x4F, 0xE3, 0x82, 0xAD, + 0xE3, 0x83, 0xAD, 0xE3, 0x83, 0xAF, 0xE3, 0x83, + 0x83, 0xE3, 0x83, 0x88, 0x4F, 0xE3, 0x82, 0xB5, + // Bytes 2b40 - 2b7f + 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x81, 0xE3, 0x83, + 0xBC, 0xE3, 0x83, 0xA0, 0x4F, 0xE3, 0x83, 0x8F, + 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xBC, 0xE3, 0x83, + 0xAC, 0xE3, 0x83, 0xAB, 0x4F, 0xE3, 0x83, 0x98, + 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0xBF, 0xE3, 0x83, + 0xBC, 0xE3, 0x83, 0xAB, 0x4F, 0xE3, 0x83, 0x9B, + 0xE3, 0x82, 0x9A, 0xE3, 0x82, 0xA4, 0xE3, 0x83, + 0xB3, 0xE3, 0x83, 0x88, 0x4F, 0xE3, 0x83, 0x9E, + // Bytes 2b80 - 2bbf + 0xE3, 0x83, 0xB3, 0xE3, 0x82, 0xB7, 0xE3, 0x83, + 0xA7, 0xE3, 0x83, 0xB3, 0x4F, 0xE3, 0x83, 0xA1, + 0xE3, 0x82, 0xAB, 0xE3, 0x82, 0x99, 0xE3, 0x83, + 0x88, 0xE3, 0x83, 0xB3, 0x4F, 0xE3, 0x83, 0xAB, + 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x95, 0xE3, 0x82, + 0x99, 0xE3, 0x83, 0xAB, 0x51, 0x28, 0xE1, 0x84, + 0x8B, 0xE1, 0x85, 0xA9, 0xE1, 0x84, 0x8C, 0xE1, + 0x85, 0xA5, 0xE1, 0x86, 0xAB, 0x29, 0x52, 0xE3, + // Bytes 2bc0 - 2bff + 0x82, 0xAD, 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xAB, + 0xE3, 0x82, 0xBF, 0xE3, 0x82, 0x99, 0xE3, 0x83, + 0xBC, 0x52, 0xE3, 0x82, 0xAD, 0xE3, 0x83, 0xAD, + 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0x99, 0xE3, 0x83, + 0xA9, 0xE3, 0x83, 0xA0, 0x52, 0xE3, 0x82, 0xAD, + 0xE3, 0x83, 0xAD, 0xE3, 0x83, 0xA1, 0xE3, 0x83, + 0xBC, 0xE3, 0x83, 0x88, 0xE3, 0x83, 0xAB, 0x52, + 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0x99, 0xE3, 0x83, + // Bytes 2c00 - 2c3f + 0xA9, 0xE3, 0x83, 0xA0, 0xE3, 0x83, 0x88, 0xE3, + 0x83, 0xB3, 0x52, 0xE3, 0x82, 0xAF, 0xE3, 0x83, + 0xAB, 0xE3, 0x82, 0xBB, 0xE3, 0x82, 0x99, 0xE3, + 0x82, 0xA4, 0xE3, 0x83, 0xAD, 0x52, 0xE3, 0x83, + 0x8F, 0xE3, 0x82, 0x9A, 0xE3, 0x83, 0xBC, 0xE3, + 0x82, 0xBB, 0xE3, 0x83, 0xB3, 0xE3, 0x83, 0x88, + 0x52, 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x9A, 0xE3, + 0x82, 0xA2, 0xE3, 0x82, 0xB9, 0xE3, 0x83, 0x88, + // Bytes 2c40 - 2c7f + 0xE3, 0x83, 0xAB, 0x52, 0xE3, 0x83, 0x95, 0xE3, + 0x82, 0x99, 0xE3, 0x83, 0x83, 0xE3, 0x82, 0xB7, + 0xE3, 0x82, 0xA7, 0xE3, 0x83, 0xAB, 0x52, 0xE3, + 0x83, 0x9F, 0xE3, 0x83, 0xAA, 0xE3, 0x83, 0x8F, + 0xE3, 0x82, 0x99, 0xE3, 0x83, 0xBC, 0xE3, 0x83, + 0xAB, 0x52, 0xE3, 0x83, 0xAC, 0xE3, 0x83, 0xB3, + 0xE3, 0x83, 0x88, 0xE3, 0x82, 0xB1, 0xE3, 0x82, + 0x99, 0xE3, 0x83, 0xB3, 0x61, 0xD8, 0xB5, 0xD9, + // Bytes 2c80 - 2cbf + 0x84, 0xD9, 0x89, 0x20, 0xD8, 0xA7, 0xD9, 0x84, + 0xD9, 0x84, 0xD9, 0x87, 0x20, 0xD8, 0xB9, 0xD9, + 0x84, 0xD9, 0x8A, 0xD9, 0x87, 0x20, 0xD9, 0x88, + 0xD8, 0xB3, 0xD9, 0x84, 0xD9, 0x85, 0x06, 0xE0, + 0xA7, 0x87, 0xE0, 0xA6, 0xBE, 0x01, 0x06, 0xE0, + 0xA7, 0x87, 0xE0, 0xA7, 0x97, 0x01, 0x06, 0xE0, + 0xAD, 0x87, 0xE0, 0xAC, 0xBE, 0x01, 0x06, 0xE0, + 0xAD, 0x87, 0xE0, 0xAD, 0x96, 0x01, 0x06, 0xE0, + // Bytes 2cc0 - 2cff + 0xAD, 0x87, 0xE0, 0xAD, 0x97, 0x01, 0x06, 0xE0, + 0xAE, 0x92, 0xE0, 0xAF, 0x97, 0x01, 0x06, 0xE0, + 0xAF, 0x86, 0xE0, 0xAE, 0xBE, 0x01, 0x06, 0xE0, + 0xAF, 0x86, 0xE0, 0xAF, 0x97, 0x01, 0x06, 0xE0, + 0xAF, 0x87, 0xE0, 0xAE, 0xBE, 0x01, 0x06, 0xE0, + 0xB2, 0xBF, 0xE0, 0xB3, 0x95, 0x01, 0x06, 0xE0, + 0xB3, 0x86, 0xE0, 0xB3, 0x95, 0x01, 0x06, 0xE0, + 0xB3, 0x86, 0xE0, 0xB3, 0x96, 0x01, 0x06, 0xE0, + // Bytes 2d00 - 2d3f + 0xB5, 0x86, 0xE0, 0xB4, 0xBE, 0x01, 0x06, 0xE0, + 0xB5, 0x86, 0xE0, 0xB5, 0x97, 0x01, 0x06, 0xE0, + 0xB5, 0x87, 0xE0, 0xB4, 0xBE, 0x01, 0x06, 0xE0, + 0xB7, 0x99, 0xE0, 0xB7, 0x9F, 0x01, 0x06, 0xE1, + 0x80, 0xA5, 0xE1, 0x80, 0xAE, 0x01, 0x06, 0xE1, + 0xAC, 0x85, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1, + 0xAC, 0x87, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1, + 0xAC, 0x89, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1, + // Bytes 2d40 - 2d7f + 0xAC, 0x8B, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1, + 0xAC, 0x8D, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1, + 0xAC, 0x91, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1, + 0xAC, 0xBA, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1, + 0xAC, 0xBC, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1, + 0xAC, 0xBE, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1, + 0xAC, 0xBF, 0xE1, 0xAC, 0xB5, 0x01, 0x06, 0xE1, + 0xAD, 0x82, 0xE1, 0xAC, 0xB5, 0x01, 0x08, 0xF0, + // Bytes 2d80 - 2dbf + 0x91, 0x84, 0xB1, 0xF0, 0x91, 0x84, 0xA7, 0x01, + 0x08, 0xF0, 0x91, 0x84, 0xB2, 0xF0, 0x91, 0x84, + 0xA7, 0x01, 0x08, 0xF0, 0x91, 0x8D, 0x87, 0xF0, + 0x91, 0x8C, 0xBE, 0x01, 0x08, 0xF0, 0x91, 0x8D, + 0x87, 0xF0, 0x91, 0x8D, 0x97, 0x01, 0x08, 0xF0, + 0x91, 0x92, 0xB9, 0xF0, 0x91, 0x92, 0xB0, 0x01, + 0x08, 0xF0, 0x91, 0x92, 0xB9, 0xF0, 0x91, 0x92, + 0xBA, 0x01, 0x08, 0xF0, 0x91, 0x92, 0xB9, 0xF0, + // Bytes 2dc0 - 2dff + 0x91, 0x92, 0xBD, 0x01, 0x08, 0xF0, 0x91, 0x96, + 0xB8, 0xF0, 0x91, 0x96, 0xAF, 0x01, 0x08, 0xF0, + 0x91, 0x96, 0xB9, 0xF0, 0x91, 0x96, 0xAF, 0x01, + 0x09, 0xE0, 0xB3, 0x86, 0xE0, 0xB3, 0x82, 0xE0, + 0xB3, 0x95, 0x02, 0x09, 0xE0, 0xB7, 0x99, 0xE0, + 0xB7, 0x8F, 0xE0, 0xB7, 0x8A, 0x12, 0x44, 0x44, + 0x5A, 0xCC, 0x8C, 0xC9, 0x44, 0x44, 0x7A, 0xCC, + 0x8C, 0xC9, 0x44, 0x64, 0x7A, 0xCC, 0x8C, 0xC9, + // Bytes 2e00 - 2e3f + 0x46, 0xD9, 0x84, 0xD8, 0xA7, 0xD9, 0x93, 0xC9, + 0x46, 0xD9, 0x84, 0xD8, 0xA7, 0xD9, 0x94, 0xC9, + 0x46, 0xD9, 0x84, 0xD8, 0xA7, 0xD9, 0x95, 0xB5, + 0x46, 0xE1, 0x84, 0x80, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x82, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x83, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x85, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x86, 0xE1, 0x85, 0xA1, 0x01, + // Bytes 2e40 - 2e7f + 0x46, 0xE1, 0x84, 0x87, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x89, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x8B, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x8B, 0xE1, 0x85, 0xAE, 0x01, + 0x46, 0xE1, 0x84, 0x8C, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x8E, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x8F, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x90, 0xE1, 0x85, 0xA1, 0x01, + // Bytes 2e80 - 2ebf + 0x46, 0xE1, 0x84, 0x91, 0xE1, 0x85, 0xA1, 0x01, + 0x46, 0xE1, 0x84, 0x92, 0xE1, 0x85, 0xA1, 0x01, + 0x49, 0xE3, 0x83, 0xA1, 0xE3, 0x82, 0xAB, 0xE3, + 0x82, 0x99, 0x0D, 0x4C, 0xE1, 0x84, 0x8C, 0xE1, + 0x85, 0xAE, 0xE1, 0x84, 0x8B, 0xE1, 0x85, 0xB4, + 0x01, 0x4C, 0xE3, 0x82, 0xAD, 0xE3, 0x82, 0x99, + 0xE3, 0x82, 0xAB, 0xE3, 0x82, 0x99, 0x0D, 0x4C, + 0xE3, 0x82, 0xB3, 0xE3, 0x83, 0xBC, 0xE3, 0x83, + // Bytes 2ec0 - 2eff + 0x9B, 0xE3, 0x82, 0x9A, 0x0D, 0x4C, 0xE3, 0x83, + 0xA4, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x88, 0xE3, + 0x82, 0x99, 0x0D, 0x4F, 0xE1, 0x84, 0x8E, 0xE1, + 0x85, 0xA1, 0xE1, 0x86, 0xB7, 0xE1, 0x84, 0x80, + 0xE1, 0x85, 0xA9, 0x01, 0x4F, 0xE3, 0x82, 0xA4, + 0xE3, 0x83, 0x8B, 0xE3, 0x83, 0xB3, 0xE3, 0x82, + 0xAF, 0xE3, 0x82, 0x99, 0x0D, 0x4F, 0xE3, 0x82, + 0xB7, 0xE3, 0x83, 0xAA, 0xE3, 0x83, 0xB3, 0xE3, + // Bytes 2f00 - 2f3f + 0x82, 0xAF, 0xE3, 0x82, 0x99, 0x0D, 0x4F, 0xE3, + 0x83, 0x98, 0xE3, 0x82, 0x9A, 0xE3, 0x83, 0xBC, + 0xE3, 0x82, 0xB7, 0xE3, 0x82, 0x99, 0x0D, 0x4F, + 0xE3, 0x83, 0x9B, 0xE3, 0x82, 0x9A, 0xE3, 0x83, + 0xB3, 0xE3, 0x83, 0x88, 0xE3, 0x82, 0x99, 0x0D, + 0x52, 0xE3, 0x82, 0xA8, 0xE3, 0x82, 0xB9, 0xE3, + 0x82, 0xAF, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x88, + 0xE3, 0x82, 0x99, 0x0D, 0x52, 0xE3, 0x83, 0x95, + // Bytes 2f40 - 2f7f + 0xE3, 0x82, 0xA1, 0xE3, 0x83, 0xA9, 0xE3, 0x83, + 0x83, 0xE3, 0x83, 0x88, 0xE3, 0x82, 0x99, 0x0D, + 0x86, 0xE0, 0xB3, 0x86, 0xE0, 0xB3, 0x82, 0x01, + 0x86, 0xE0, 0xB7, 0x99, 0xE0, 0xB7, 0x8F, 0x01, + 0x03, 0x3C, 0xCC, 0xB8, 0x05, 0x03, 0x3D, 0xCC, + 0xB8, 0x05, 0x03, 0x3E, 0xCC, 0xB8, 0x05, 0x03, + 0x41, 0xCC, 0x80, 0xC9, 0x03, 0x41, 0xCC, 0x81, + 0xC9, 0x03, 0x41, 0xCC, 0x83, 0xC9, 0x03, 0x41, + // Bytes 2f80 - 2fbf + 0xCC, 0x84, 0xC9, 0x03, 0x41, 0xCC, 0x89, 0xC9, + 0x03, 0x41, 0xCC, 0x8C, 0xC9, 0x03, 0x41, 0xCC, + 0x8F, 0xC9, 0x03, 0x41, 0xCC, 0x91, 0xC9, 0x03, + 0x41, 0xCC, 0xA5, 0xB5, 0x03, 0x41, 0xCC, 0xA8, + 0xA5, 0x03, 0x42, 0xCC, 0x87, 0xC9, 0x03, 0x42, + 0xCC, 0xA3, 0xB5, 0x03, 0x42, 0xCC, 0xB1, 0xB5, + 0x03, 0x43, 0xCC, 0x81, 0xC9, 0x03, 0x43, 0xCC, + 0x82, 0xC9, 0x03, 0x43, 0xCC, 0x87, 0xC9, 0x03, + // Bytes 2fc0 - 2fff + 0x43, 0xCC, 0x8C, 0xC9, 0x03, 0x44, 0xCC, 0x87, + 0xC9, 0x03, 0x44, 0xCC, 0x8C, 0xC9, 0x03, 0x44, + 0xCC, 0xA3, 0xB5, 0x03, 0x44, 0xCC, 0xA7, 0xA5, + 0x03, 0x44, 0xCC, 0xAD, 0xB5, 0x03, 0x44, 0xCC, + 0xB1, 0xB5, 0x03, 0x45, 0xCC, 0x80, 0xC9, 0x03, + 0x45, 0xCC, 0x81, 0xC9, 0x03, 0x45, 0xCC, 0x83, + 0xC9, 0x03, 0x45, 0xCC, 0x86, 0xC9, 0x03, 0x45, + 0xCC, 0x87, 0xC9, 0x03, 0x45, 0xCC, 0x88, 0xC9, + // Bytes 3000 - 303f + 0x03, 0x45, 0xCC, 0x89, 0xC9, 0x03, 0x45, 0xCC, + 0x8C, 0xC9, 0x03, 0x45, 0xCC, 0x8F, 0xC9, 0x03, + 0x45, 0xCC, 0x91, 0xC9, 0x03, 0x45, 0xCC, 0xA8, + 0xA5, 0x03, 0x45, 0xCC, 0xAD, 0xB5, 0x03, 0x45, + 0xCC, 0xB0, 0xB5, 0x03, 0x46, 0xCC, 0x87, 0xC9, + 0x03, 0x47, 0xCC, 0x81, 0xC9, 0x03, 0x47, 0xCC, + 0x82, 0xC9, 0x03, 0x47, 0xCC, 0x84, 0xC9, 0x03, + 0x47, 0xCC, 0x86, 0xC9, 0x03, 0x47, 0xCC, 0x87, + // Bytes 3040 - 307f + 0xC9, 0x03, 0x47, 0xCC, 0x8C, 0xC9, 0x03, 0x47, + 0xCC, 0xA7, 0xA5, 0x03, 0x48, 0xCC, 0x82, 0xC9, + 0x03, 0x48, 0xCC, 0x87, 0xC9, 0x03, 0x48, 0xCC, + 0x88, 0xC9, 0x03, 0x48, 0xCC, 0x8C, 0xC9, 0x03, + 0x48, 0xCC, 0xA3, 0xB5, 0x03, 0x48, 0xCC, 0xA7, + 0xA5, 0x03, 0x48, 0xCC, 0xAE, 0xB5, 0x03, 0x49, + 0xCC, 0x80, 0xC9, 0x03, 0x49, 0xCC, 0x81, 0xC9, + 0x03, 0x49, 0xCC, 0x82, 0xC9, 0x03, 0x49, 0xCC, + // Bytes 3080 - 30bf + 0x83, 0xC9, 0x03, 0x49, 0xCC, 0x84, 0xC9, 0x03, + 0x49, 0xCC, 0x86, 0xC9, 0x03, 0x49, 0xCC, 0x87, + 0xC9, 0x03, 0x49, 0xCC, 0x89, 0xC9, 0x03, 0x49, + 0xCC, 0x8C, 0xC9, 0x03, 0x49, 0xCC, 0x8F, 0xC9, + 0x03, 0x49, 0xCC, 0x91, 0xC9, 0x03, 0x49, 0xCC, + 0xA3, 0xB5, 0x03, 0x49, 0xCC, 0xA8, 0xA5, 0x03, + 0x49, 0xCC, 0xB0, 0xB5, 0x03, 0x4A, 0xCC, 0x82, + 0xC9, 0x03, 0x4B, 0xCC, 0x81, 0xC9, 0x03, 0x4B, + // Bytes 30c0 - 30ff + 0xCC, 0x8C, 0xC9, 0x03, 0x4B, 0xCC, 0xA3, 0xB5, + 0x03, 0x4B, 0xCC, 0xA7, 0xA5, 0x03, 0x4B, 0xCC, + 0xB1, 0xB5, 0x03, 0x4C, 0xCC, 0x81, 0xC9, 0x03, + 0x4C, 0xCC, 0x8C, 0xC9, 0x03, 0x4C, 0xCC, 0xA7, + 0xA5, 0x03, 0x4C, 0xCC, 0xAD, 0xB5, 0x03, 0x4C, + 0xCC, 0xB1, 0xB5, 0x03, 0x4D, 0xCC, 0x81, 0xC9, + 0x03, 0x4D, 0xCC, 0x87, 0xC9, 0x03, 0x4D, 0xCC, + 0xA3, 0xB5, 0x03, 0x4E, 0xCC, 0x80, 0xC9, 0x03, + // Bytes 3100 - 313f + 0x4E, 0xCC, 0x81, 0xC9, 0x03, 0x4E, 0xCC, 0x83, + 0xC9, 0x03, 0x4E, 0xCC, 0x87, 0xC9, 0x03, 0x4E, + 0xCC, 0x8C, 0xC9, 0x03, 0x4E, 0xCC, 0xA3, 0xB5, + 0x03, 0x4E, 0xCC, 0xA7, 0xA5, 0x03, 0x4E, 0xCC, + 0xAD, 0xB5, 0x03, 0x4E, 0xCC, 0xB1, 0xB5, 0x03, + 0x4F, 0xCC, 0x80, 0xC9, 0x03, 0x4F, 0xCC, 0x81, + 0xC9, 0x03, 0x4F, 0xCC, 0x86, 0xC9, 0x03, 0x4F, + 0xCC, 0x89, 0xC9, 0x03, 0x4F, 0xCC, 0x8B, 0xC9, + // Bytes 3140 - 317f + 0x03, 0x4F, 0xCC, 0x8C, 0xC9, 0x03, 0x4F, 0xCC, + 0x8F, 0xC9, 0x03, 0x4F, 0xCC, 0x91, 0xC9, 0x03, + 0x50, 0xCC, 0x81, 0xC9, 0x03, 0x50, 0xCC, 0x87, + 0xC9, 0x03, 0x52, 0xCC, 0x81, 0xC9, 0x03, 0x52, + 0xCC, 0x87, 0xC9, 0x03, 0x52, 0xCC, 0x8C, 0xC9, + 0x03, 0x52, 0xCC, 0x8F, 0xC9, 0x03, 0x52, 0xCC, + 0x91, 0xC9, 0x03, 0x52, 0xCC, 0xA7, 0xA5, 0x03, + 0x52, 0xCC, 0xB1, 0xB5, 0x03, 0x53, 0xCC, 0x82, + // Bytes 3180 - 31bf + 0xC9, 0x03, 0x53, 0xCC, 0x87, 0xC9, 0x03, 0x53, + 0xCC, 0xA6, 0xB5, 0x03, 0x53, 0xCC, 0xA7, 0xA5, + 0x03, 0x54, 0xCC, 0x87, 0xC9, 0x03, 0x54, 0xCC, + 0x8C, 0xC9, 0x03, 0x54, 0xCC, 0xA3, 0xB5, 0x03, + 0x54, 0xCC, 0xA6, 0xB5, 0x03, 0x54, 0xCC, 0xA7, + 0xA5, 0x03, 0x54, 0xCC, 0xAD, 0xB5, 0x03, 0x54, + 0xCC, 0xB1, 0xB5, 0x03, 0x55, 0xCC, 0x80, 0xC9, + 0x03, 0x55, 0xCC, 0x81, 0xC9, 0x03, 0x55, 0xCC, + // Bytes 31c0 - 31ff + 0x82, 0xC9, 0x03, 0x55, 0xCC, 0x86, 0xC9, 0x03, + 0x55, 0xCC, 0x89, 0xC9, 0x03, 0x55, 0xCC, 0x8A, + 0xC9, 0x03, 0x55, 0xCC, 0x8B, 0xC9, 0x03, 0x55, + 0xCC, 0x8C, 0xC9, 0x03, 0x55, 0xCC, 0x8F, 0xC9, + 0x03, 0x55, 0xCC, 0x91, 0xC9, 0x03, 0x55, 0xCC, + 0xA3, 0xB5, 0x03, 0x55, 0xCC, 0xA4, 0xB5, 0x03, + 0x55, 0xCC, 0xA8, 0xA5, 0x03, 0x55, 0xCC, 0xAD, + 0xB5, 0x03, 0x55, 0xCC, 0xB0, 0xB5, 0x03, 0x56, + // Bytes 3200 - 323f + 0xCC, 0x83, 0xC9, 0x03, 0x56, 0xCC, 0xA3, 0xB5, + 0x03, 0x57, 0xCC, 0x80, 0xC9, 0x03, 0x57, 0xCC, + 0x81, 0xC9, 0x03, 0x57, 0xCC, 0x82, 0xC9, 0x03, + 0x57, 0xCC, 0x87, 0xC9, 0x03, 0x57, 0xCC, 0x88, + 0xC9, 0x03, 0x57, 0xCC, 0xA3, 0xB5, 0x03, 0x58, + 0xCC, 0x87, 0xC9, 0x03, 0x58, 0xCC, 0x88, 0xC9, + 0x03, 0x59, 0xCC, 0x80, 0xC9, 0x03, 0x59, 0xCC, + 0x81, 0xC9, 0x03, 0x59, 0xCC, 0x82, 0xC9, 0x03, + // Bytes 3240 - 327f + 0x59, 0xCC, 0x83, 0xC9, 0x03, 0x59, 0xCC, 0x84, + 0xC9, 0x03, 0x59, 0xCC, 0x87, 0xC9, 0x03, 0x59, + 0xCC, 0x88, 0xC9, 0x03, 0x59, 0xCC, 0x89, 0xC9, + 0x03, 0x59, 0xCC, 0xA3, 0xB5, 0x03, 0x5A, 0xCC, + 0x81, 0xC9, 0x03, 0x5A, 0xCC, 0x82, 0xC9, 0x03, + 0x5A, 0xCC, 0x87, 0xC9, 0x03, 0x5A, 0xCC, 0x8C, + 0xC9, 0x03, 0x5A, 0xCC, 0xA3, 0xB5, 0x03, 0x5A, + 0xCC, 0xB1, 0xB5, 0x03, 0x61, 0xCC, 0x80, 0xC9, + // Bytes 3280 - 32bf + 0x03, 0x61, 0xCC, 0x81, 0xC9, 0x03, 0x61, 0xCC, + 0x83, 0xC9, 0x03, 0x61, 0xCC, 0x84, 0xC9, 0x03, + 0x61, 0xCC, 0x89, 0xC9, 0x03, 0x61, 0xCC, 0x8C, + 0xC9, 0x03, 0x61, 0xCC, 0x8F, 0xC9, 0x03, 0x61, + 0xCC, 0x91, 0xC9, 0x03, 0x61, 0xCC, 0xA5, 0xB5, + 0x03, 0x61, 0xCC, 0xA8, 0xA5, 0x03, 0x62, 0xCC, + 0x87, 0xC9, 0x03, 0x62, 0xCC, 0xA3, 0xB5, 0x03, + 0x62, 0xCC, 0xB1, 0xB5, 0x03, 0x63, 0xCC, 0x81, + // Bytes 32c0 - 32ff + 0xC9, 0x03, 0x63, 0xCC, 0x82, 0xC9, 0x03, 0x63, + 0xCC, 0x87, 0xC9, 0x03, 0x63, 0xCC, 0x8C, 0xC9, + 0x03, 0x64, 0xCC, 0x87, 0xC9, 0x03, 0x64, 0xCC, + 0x8C, 0xC9, 0x03, 0x64, 0xCC, 0xA3, 0xB5, 0x03, + 0x64, 0xCC, 0xA7, 0xA5, 0x03, 0x64, 0xCC, 0xAD, + 0xB5, 0x03, 0x64, 0xCC, 0xB1, 0xB5, 0x03, 0x65, + 0xCC, 0x80, 0xC9, 0x03, 0x65, 0xCC, 0x81, 0xC9, + 0x03, 0x65, 0xCC, 0x83, 0xC9, 0x03, 0x65, 0xCC, + // Bytes 3300 - 333f + 0x86, 0xC9, 0x03, 0x65, 0xCC, 0x87, 0xC9, 0x03, + 0x65, 0xCC, 0x88, 0xC9, 0x03, 0x65, 0xCC, 0x89, + 0xC9, 0x03, 0x65, 0xCC, 0x8C, 0xC9, 0x03, 0x65, + 0xCC, 0x8F, 0xC9, 0x03, 0x65, 0xCC, 0x91, 0xC9, + 0x03, 0x65, 0xCC, 0xA8, 0xA5, 0x03, 0x65, 0xCC, + 0xAD, 0xB5, 0x03, 0x65, 0xCC, 0xB0, 0xB5, 0x03, + 0x66, 0xCC, 0x87, 0xC9, 0x03, 0x67, 0xCC, 0x81, + 0xC9, 0x03, 0x67, 0xCC, 0x82, 0xC9, 0x03, 0x67, + // Bytes 3340 - 337f + 0xCC, 0x84, 0xC9, 0x03, 0x67, 0xCC, 0x86, 0xC9, + 0x03, 0x67, 0xCC, 0x87, 0xC9, 0x03, 0x67, 0xCC, + 0x8C, 0xC9, 0x03, 0x67, 0xCC, 0xA7, 0xA5, 0x03, + 0x68, 0xCC, 0x82, 0xC9, 0x03, 0x68, 0xCC, 0x87, + 0xC9, 0x03, 0x68, 0xCC, 0x88, 0xC9, 0x03, 0x68, + 0xCC, 0x8C, 0xC9, 0x03, 0x68, 0xCC, 0xA3, 0xB5, + 0x03, 0x68, 0xCC, 0xA7, 0xA5, 0x03, 0x68, 0xCC, + 0xAE, 0xB5, 0x03, 0x68, 0xCC, 0xB1, 0xB5, 0x03, + // Bytes 3380 - 33bf + 0x69, 0xCC, 0x80, 0xC9, 0x03, 0x69, 0xCC, 0x81, + 0xC9, 0x03, 0x69, 0xCC, 0x82, 0xC9, 0x03, 0x69, + 0xCC, 0x83, 0xC9, 0x03, 0x69, 0xCC, 0x84, 0xC9, + 0x03, 0x69, 0xCC, 0x86, 0xC9, 0x03, 0x69, 0xCC, + 0x89, 0xC9, 0x03, 0x69, 0xCC, 0x8C, 0xC9, 0x03, + 0x69, 0xCC, 0x8F, 0xC9, 0x03, 0x69, 0xCC, 0x91, + 0xC9, 0x03, 0x69, 0xCC, 0xA3, 0xB5, 0x03, 0x69, + 0xCC, 0xA8, 0xA5, 0x03, 0x69, 0xCC, 0xB0, 0xB5, + // Bytes 33c0 - 33ff + 0x03, 0x6A, 0xCC, 0x82, 0xC9, 0x03, 0x6A, 0xCC, + 0x8C, 0xC9, 0x03, 0x6B, 0xCC, 0x81, 0xC9, 0x03, + 0x6B, 0xCC, 0x8C, 0xC9, 0x03, 0x6B, 0xCC, 0xA3, + 0xB5, 0x03, 0x6B, 0xCC, 0xA7, 0xA5, 0x03, 0x6B, + 0xCC, 0xB1, 0xB5, 0x03, 0x6C, 0xCC, 0x81, 0xC9, + 0x03, 0x6C, 0xCC, 0x8C, 0xC9, 0x03, 0x6C, 0xCC, + 0xA7, 0xA5, 0x03, 0x6C, 0xCC, 0xAD, 0xB5, 0x03, + 0x6C, 0xCC, 0xB1, 0xB5, 0x03, 0x6D, 0xCC, 0x81, + // Bytes 3400 - 343f + 0xC9, 0x03, 0x6D, 0xCC, 0x87, 0xC9, 0x03, 0x6D, + 0xCC, 0xA3, 0xB5, 0x03, 0x6E, 0xCC, 0x80, 0xC9, + 0x03, 0x6E, 0xCC, 0x81, 0xC9, 0x03, 0x6E, 0xCC, + 0x83, 0xC9, 0x03, 0x6E, 0xCC, 0x87, 0xC9, 0x03, + 0x6E, 0xCC, 0x8C, 0xC9, 0x03, 0x6E, 0xCC, 0xA3, + 0xB5, 0x03, 0x6E, 0xCC, 0xA7, 0xA5, 0x03, 0x6E, + 0xCC, 0xAD, 0xB5, 0x03, 0x6E, 0xCC, 0xB1, 0xB5, + 0x03, 0x6F, 0xCC, 0x80, 0xC9, 0x03, 0x6F, 0xCC, + // Bytes 3440 - 347f + 0x81, 0xC9, 0x03, 0x6F, 0xCC, 0x86, 0xC9, 0x03, + 0x6F, 0xCC, 0x89, 0xC9, 0x03, 0x6F, 0xCC, 0x8B, + 0xC9, 0x03, 0x6F, 0xCC, 0x8C, 0xC9, 0x03, 0x6F, + 0xCC, 0x8F, 0xC9, 0x03, 0x6F, 0xCC, 0x91, 0xC9, + 0x03, 0x70, 0xCC, 0x81, 0xC9, 0x03, 0x70, 0xCC, + 0x87, 0xC9, 0x03, 0x72, 0xCC, 0x81, 0xC9, 0x03, + 0x72, 0xCC, 0x87, 0xC9, 0x03, 0x72, 0xCC, 0x8C, + 0xC9, 0x03, 0x72, 0xCC, 0x8F, 0xC9, 0x03, 0x72, + // Bytes 3480 - 34bf + 0xCC, 0x91, 0xC9, 0x03, 0x72, 0xCC, 0xA7, 0xA5, + 0x03, 0x72, 0xCC, 0xB1, 0xB5, 0x03, 0x73, 0xCC, + 0x82, 0xC9, 0x03, 0x73, 0xCC, 0x87, 0xC9, 0x03, + 0x73, 0xCC, 0xA6, 0xB5, 0x03, 0x73, 0xCC, 0xA7, + 0xA5, 0x03, 0x74, 0xCC, 0x87, 0xC9, 0x03, 0x74, + 0xCC, 0x88, 0xC9, 0x03, 0x74, 0xCC, 0x8C, 0xC9, + 0x03, 0x74, 0xCC, 0xA3, 0xB5, 0x03, 0x74, 0xCC, + 0xA6, 0xB5, 0x03, 0x74, 0xCC, 0xA7, 0xA5, 0x03, + // Bytes 34c0 - 34ff + 0x74, 0xCC, 0xAD, 0xB5, 0x03, 0x74, 0xCC, 0xB1, + 0xB5, 0x03, 0x75, 0xCC, 0x80, 0xC9, 0x03, 0x75, + 0xCC, 0x81, 0xC9, 0x03, 0x75, 0xCC, 0x82, 0xC9, + 0x03, 0x75, 0xCC, 0x86, 0xC9, 0x03, 0x75, 0xCC, + 0x89, 0xC9, 0x03, 0x75, 0xCC, 0x8A, 0xC9, 0x03, + 0x75, 0xCC, 0x8B, 0xC9, 0x03, 0x75, 0xCC, 0x8C, + 0xC9, 0x03, 0x75, 0xCC, 0x8F, 0xC9, 0x03, 0x75, + 0xCC, 0x91, 0xC9, 0x03, 0x75, 0xCC, 0xA3, 0xB5, + // Bytes 3500 - 353f + 0x03, 0x75, 0xCC, 0xA4, 0xB5, 0x03, 0x75, 0xCC, + 0xA8, 0xA5, 0x03, 0x75, 0xCC, 0xAD, 0xB5, 0x03, + 0x75, 0xCC, 0xB0, 0xB5, 0x03, 0x76, 0xCC, 0x83, + 0xC9, 0x03, 0x76, 0xCC, 0xA3, 0xB5, 0x03, 0x77, + 0xCC, 0x80, 0xC9, 0x03, 0x77, 0xCC, 0x81, 0xC9, + 0x03, 0x77, 0xCC, 0x82, 0xC9, 0x03, 0x77, 0xCC, + 0x87, 0xC9, 0x03, 0x77, 0xCC, 0x88, 0xC9, 0x03, + 0x77, 0xCC, 0x8A, 0xC9, 0x03, 0x77, 0xCC, 0xA3, + // Bytes 3540 - 357f + 0xB5, 0x03, 0x78, 0xCC, 0x87, 0xC9, 0x03, 0x78, + 0xCC, 0x88, 0xC9, 0x03, 0x79, 0xCC, 0x80, 0xC9, + 0x03, 0x79, 0xCC, 0x81, 0xC9, 0x03, 0x79, 0xCC, + 0x82, 0xC9, 0x03, 0x79, 0xCC, 0x83, 0xC9, 0x03, + 0x79, 0xCC, 0x84, 0xC9, 0x03, 0x79, 0xCC, 0x87, + 0xC9, 0x03, 0x79, 0xCC, 0x88, 0xC9, 0x03, 0x79, + 0xCC, 0x89, 0xC9, 0x03, 0x79, 0xCC, 0x8A, 0xC9, + 0x03, 0x79, 0xCC, 0xA3, 0xB5, 0x03, 0x7A, 0xCC, + // Bytes 3580 - 35bf + 0x81, 0xC9, 0x03, 0x7A, 0xCC, 0x82, 0xC9, 0x03, + 0x7A, 0xCC, 0x87, 0xC9, 0x03, 0x7A, 0xCC, 0x8C, + 0xC9, 0x03, 0x7A, 0xCC, 0xA3, 0xB5, 0x03, 0x7A, + 0xCC, 0xB1, 0xB5, 0x04, 0xC2, 0xA8, 0xCC, 0x80, + 0xCA, 0x04, 0xC2, 0xA8, 0xCC, 0x81, 0xCA, 0x04, + 0xC2, 0xA8, 0xCD, 0x82, 0xCA, 0x04, 0xC3, 0x86, + 0xCC, 0x81, 0xC9, 0x04, 0xC3, 0x86, 0xCC, 0x84, + 0xC9, 0x04, 0xC3, 0x98, 0xCC, 0x81, 0xC9, 0x04, + // Bytes 35c0 - 35ff + 0xC3, 0xA6, 0xCC, 0x81, 0xC9, 0x04, 0xC3, 0xA6, + 0xCC, 0x84, 0xC9, 0x04, 0xC3, 0xB8, 0xCC, 0x81, + 0xC9, 0x04, 0xC5, 0xBF, 0xCC, 0x87, 0xC9, 0x04, + 0xC6, 0xB7, 0xCC, 0x8C, 0xC9, 0x04, 0xCA, 0x92, + 0xCC, 0x8C, 0xC9, 0x04, 0xCE, 0x91, 0xCC, 0x80, + 0xC9, 0x04, 0xCE, 0x91, 0xCC, 0x81, 0xC9, 0x04, + 0xCE, 0x91, 0xCC, 0x84, 0xC9, 0x04, 0xCE, 0x91, + 0xCC, 0x86, 0xC9, 0x04, 0xCE, 0x91, 0xCD, 0x85, + // Bytes 3600 - 363f + 0xD9, 0x04, 0xCE, 0x95, 0xCC, 0x80, 0xC9, 0x04, + 0xCE, 0x95, 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0x97, + 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0x97, 0xCC, 0x81, + 0xC9, 0x04, 0xCE, 0x97, 0xCD, 0x85, 0xD9, 0x04, + 0xCE, 0x99, 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0x99, + 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0x99, 0xCC, 0x84, + 0xC9, 0x04, 0xCE, 0x99, 0xCC, 0x86, 0xC9, 0x04, + 0xCE, 0x99, 0xCC, 0x88, 0xC9, 0x04, 0xCE, 0x9F, + // Bytes 3640 - 367f + 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0x9F, 0xCC, 0x81, + 0xC9, 0x04, 0xCE, 0xA1, 0xCC, 0x94, 0xC9, 0x04, + 0xCE, 0xA5, 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0xA5, + 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0xA5, 0xCC, 0x84, + 0xC9, 0x04, 0xCE, 0xA5, 0xCC, 0x86, 0xC9, 0x04, + 0xCE, 0xA5, 0xCC, 0x88, 0xC9, 0x04, 0xCE, 0xA9, + 0xCC, 0x80, 0xC9, 0x04, 0xCE, 0xA9, 0xCC, 0x81, + 0xC9, 0x04, 0xCE, 0xA9, 0xCD, 0x85, 0xD9, 0x04, + // Bytes 3680 - 36bf + 0xCE, 0xB1, 0xCC, 0x84, 0xC9, 0x04, 0xCE, 0xB1, + 0xCC, 0x86, 0xC9, 0x04, 0xCE, 0xB1, 0xCD, 0x85, + 0xD9, 0x04, 0xCE, 0xB5, 0xCC, 0x80, 0xC9, 0x04, + 0xCE, 0xB5, 0xCC, 0x81, 0xC9, 0x04, 0xCE, 0xB7, + 0xCD, 0x85, 0xD9, 0x04, 0xCE, 0xB9, 0xCC, 0x80, + 0xC9, 0x04, 0xCE, 0xB9, 0xCC, 0x81, 0xC9, 0x04, + 0xCE, 0xB9, 0xCC, 0x84, 0xC9, 0x04, 0xCE, 0xB9, + 0xCC, 0x86, 0xC9, 0x04, 0xCE, 0xB9, 0xCD, 0x82, + // Bytes 36c0 - 36ff + 0xC9, 0x04, 0xCE, 0xBF, 0xCC, 0x80, 0xC9, 0x04, + 0xCE, 0xBF, 0xCC, 0x81, 0xC9, 0x04, 0xCF, 0x81, + 0xCC, 0x93, 0xC9, 0x04, 0xCF, 0x81, 0xCC, 0x94, + 0xC9, 0x04, 0xCF, 0x85, 0xCC, 0x80, 0xC9, 0x04, + 0xCF, 0x85, 0xCC, 0x81, 0xC9, 0x04, 0xCF, 0x85, + 0xCC, 0x84, 0xC9, 0x04, 0xCF, 0x85, 0xCC, 0x86, + 0xC9, 0x04, 0xCF, 0x85, 0xCD, 0x82, 0xC9, 0x04, + 0xCF, 0x89, 0xCD, 0x85, 0xD9, 0x04, 0xCF, 0x92, + // Bytes 3700 - 373f + 0xCC, 0x81, 0xC9, 0x04, 0xCF, 0x92, 0xCC, 0x88, + 0xC9, 0x04, 0xD0, 0x86, 0xCC, 0x88, 0xC9, 0x04, + 0xD0, 0x90, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0x90, + 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0x93, 0xCC, 0x81, + 0xC9, 0x04, 0xD0, 0x95, 0xCC, 0x80, 0xC9, 0x04, + 0xD0, 0x95, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0x95, + 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0x96, 0xCC, 0x86, + 0xC9, 0x04, 0xD0, 0x96, 0xCC, 0x88, 0xC9, 0x04, + // Bytes 3740 - 377f + 0xD0, 0x97, 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0x98, + 0xCC, 0x80, 0xC9, 0x04, 0xD0, 0x98, 0xCC, 0x84, + 0xC9, 0x04, 0xD0, 0x98, 0xCC, 0x86, 0xC9, 0x04, + 0xD0, 0x98, 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0x9A, + 0xCC, 0x81, 0xC9, 0x04, 0xD0, 0x9E, 0xCC, 0x88, + 0xC9, 0x04, 0xD0, 0xA3, 0xCC, 0x84, 0xC9, 0x04, + 0xD0, 0xA3, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0xA3, + 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xA3, 0xCC, 0x8B, + // Bytes 3780 - 37bf + 0xC9, 0x04, 0xD0, 0xA7, 0xCC, 0x88, 0xC9, 0x04, + 0xD0, 0xAB, 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xAD, + 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xB0, 0xCC, 0x86, + 0xC9, 0x04, 0xD0, 0xB0, 0xCC, 0x88, 0xC9, 0x04, + 0xD0, 0xB3, 0xCC, 0x81, 0xC9, 0x04, 0xD0, 0xB5, + 0xCC, 0x80, 0xC9, 0x04, 0xD0, 0xB5, 0xCC, 0x86, + 0xC9, 0x04, 0xD0, 0xB5, 0xCC, 0x88, 0xC9, 0x04, + 0xD0, 0xB6, 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0xB6, + // Bytes 37c0 - 37ff + 0xCC, 0x88, 0xC9, 0x04, 0xD0, 0xB7, 0xCC, 0x88, + 0xC9, 0x04, 0xD0, 0xB8, 0xCC, 0x80, 0xC9, 0x04, + 0xD0, 0xB8, 0xCC, 0x84, 0xC9, 0x04, 0xD0, 0xB8, + 0xCC, 0x86, 0xC9, 0x04, 0xD0, 0xB8, 0xCC, 0x88, + 0xC9, 0x04, 0xD0, 0xBA, 0xCC, 0x81, 0xC9, 0x04, + 0xD0, 0xBE, 0xCC, 0x88, 0xC9, 0x04, 0xD1, 0x83, + 0xCC, 0x84, 0xC9, 0x04, 0xD1, 0x83, 0xCC, 0x86, + 0xC9, 0x04, 0xD1, 0x83, 0xCC, 0x88, 0xC9, 0x04, + // Bytes 3800 - 383f + 0xD1, 0x83, 0xCC, 0x8B, 0xC9, 0x04, 0xD1, 0x87, + 0xCC, 0x88, 0xC9, 0x04, 0xD1, 0x8B, 0xCC, 0x88, + 0xC9, 0x04, 0xD1, 0x8D, 0xCC, 0x88, 0xC9, 0x04, + 0xD1, 0x96, 0xCC, 0x88, 0xC9, 0x04, 0xD1, 0xB4, + 0xCC, 0x8F, 0xC9, 0x04, 0xD1, 0xB5, 0xCC, 0x8F, + 0xC9, 0x04, 0xD3, 0x98, 0xCC, 0x88, 0xC9, 0x04, + 0xD3, 0x99, 0xCC, 0x88, 0xC9, 0x04, 0xD3, 0xA8, + 0xCC, 0x88, 0xC9, 0x04, 0xD3, 0xA9, 0xCC, 0x88, + // Bytes 3840 - 387f + 0xC9, 0x04, 0xD8, 0xA7, 0xD9, 0x93, 0xC9, 0x04, + 0xD8, 0xA7, 0xD9, 0x94, 0xC9, 0x04, 0xD8, 0xA7, + 0xD9, 0x95, 0xB5, 0x04, 0xD9, 0x88, 0xD9, 0x94, + 0xC9, 0x04, 0xD9, 0x8A, 0xD9, 0x94, 0xC9, 0x04, + 0xDB, 0x81, 0xD9, 0x94, 0xC9, 0x04, 0xDB, 0x92, + 0xD9, 0x94, 0xC9, 0x04, 0xDB, 0x95, 0xD9, 0x94, + 0xC9, 0x05, 0x41, 0xCC, 0x82, 0xCC, 0x80, 0xCA, + 0x05, 0x41, 0xCC, 0x82, 0xCC, 0x81, 0xCA, 0x05, + // Bytes 3880 - 38bf + 0x41, 0xCC, 0x82, 0xCC, 0x83, 0xCA, 0x05, 0x41, + 0xCC, 0x82, 0xCC, 0x89, 0xCA, 0x05, 0x41, 0xCC, + 0x86, 0xCC, 0x80, 0xCA, 0x05, 0x41, 0xCC, 0x86, + 0xCC, 0x81, 0xCA, 0x05, 0x41, 0xCC, 0x86, 0xCC, + 0x83, 0xCA, 0x05, 0x41, 0xCC, 0x86, 0xCC, 0x89, + 0xCA, 0x05, 0x41, 0xCC, 0x87, 0xCC, 0x84, 0xCA, + 0x05, 0x41, 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, + 0x41, 0xCC, 0x8A, 0xCC, 0x81, 0xCA, 0x05, 0x41, + // Bytes 38c0 - 38ff + 0xCC, 0xA3, 0xCC, 0x82, 0xCA, 0x05, 0x41, 0xCC, + 0xA3, 0xCC, 0x86, 0xCA, 0x05, 0x43, 0xCC, 0xA7, + 0xCC, 0x81, 0xCA, 0x05, 0x45, 0xCC, 0x82, 0xCC, + 0x80, 0xCA, 0x05, 0x45, 0xCC, 0x82, 0xCC, 0x81, + 0xCA, 0x05, 0x45, 0xCC, 0x82, 0xCC, 0x83, 0xCA, + 0x05, 0x45, 0xCC, 0x82, 0xCC, 0x89, 0xCA, 0x05, + 0x45, 0xCC, 0x84, 0xCC, 0x80, 0xCA, 0x05, 0x45, + 0xCC, 0x84, 0xCC, 0x81, 0xCA, 0x05, 0x45, 0xCC, + // Bytes 3900 - 393f + 0xA3, 0xCC, 0x82, 0xCA, 0x05, 0x45, 0xCC, 0xA7, + 0xCC, 0x86, 0xCA, 0x05, 0x49, 0xCC, 0x88, 0xCC, + 0x81, 0xCA, 0x05, 0x4C, 0xCC, 0xA3, 0xCC, 0x84, + 0xCA, 0x05, 0x4F, 0xCC, 0x82, 0xCC, 0x80, 0xCA, + 0x05, 0x4F, 0xCC, 0x82, 0xCC, 0x81, 0xCA, 0x05, + 0x4F, 0xCC, 0x82, 0xCC, 0x83, 0xCA, 0x05, 0x4F, + 0xCC, 0x82, 0xCC, 0x89, 0xCA, 0x05, 0x4F, 0xCC, + 0x83, 0xCC, 0x81, 0xCA, 0x05, 0x4F, 0xCC, 0x83, + // Bytes 3940 - 397f + 0xCC, 0x84, 0xCA, 0x05, 0x4F, 0xCC, 0x83, 0xCC, + 0x88, 0xCA, 0x05, 0x4F, 0xCC, 0x84, 0xCC, 0x80, + 0xCA, 0x05, 0x4F, 0xCC, 0x84, 0xCC, 0x81, 0xCA, + 0x05, 0x4F, 0xCC, 0x87, 0xCC, 0x84, 0xCA, 0x05, + 0x4F, 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, 0x4F, + 0xCC, 0x9B, 0xCC, 0x80, 0xCA, 0x05, 0x4F, 0xCC, + 0x9B, 0xCC, 0x81, 0xCA, 0x05, 0x4F, 0xCC, 0x9B, + 0xCC, 0x83, 0xCA, 0x05, 0x4F, 0xCC, 0x9B, 0xCC, + // Bytes 3980 - 39bf + 0x89, 0xCA, 0x05, 0x4F, 0xCC, 0x9B, 0xCC, 0xA3, + 0xB6, 0x05, 0x4F, 0xCC, 0xA3, 0xCC, 0x82, 0xCA, + 0x05, 0x4F, 0xCC, 0xA8, 0xCC, 0x84, 0xCA, 0x05, + 0x52, 0xCC, 0xA3, 0xCC, 0x84, 0xCA, 0x05, 0x53, + 0xCC, 0x81, 0xCC, 0x87, 0xCA, 0x05, 0x53, 0xCC, + 0x8C, 0xCC, 0x87, 0xCA, 0x05, 0x53, 0xCC, 0xA3, + 0xCC, 0x87, 0xCA, 0x05, 0x55, 0xCC, 0x83, 0xCC, + 0x81, 0xCA, 0x05, 0x55, 0xCC, 0x84, 0xCC, 0x88, + // Bytes 39c0 - 39ff + 0xCA, 0x05, 0x55, 0xCC, 0x88, 0xCC, 0x80, 0xCA, + 0x05, 0x55, 0xCC, 0x88, 0xCC, 0x81, 0xCA, 0x05, + 0x55, 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, 0x55, + 0xCC, 0x88, 0xCC, 0x8C, 0xCA, 0x05, 0x55, 0xCC, + 0x9B, 0xCC, 0x80, 0xCA, 0x05, 0x55, 0xCC, 0x9B, + 0xCC, 0x81, 0xCA, 0x05, 0x55, 0xCC, 0x9B, 0xCC, + 0x83, 0xCA, 0x05, 0x55, 0xCC, 0x9B, 0xCC, 0x89, + 0xCA, 0x05, 0x55, 0xCC, 0x9B, 0xCC, 0xA3, 0xB6, + // Bytes 3a00 - 3a3f + 0x05, 0x61, 0xCC, 0x82, 0xCC, 0x80, 0xCA, 0x05, + 0x61, 0xCC, 0x82, 0xCC, 0x81, 0xCA, 0x05, 0x61, + 0xCC, 0x82, 0xCC, 0x83, 0xCA, 0x05, 0x61, 0xCC, + 0x82, 0xCC, 0x89, 0xCA, 0x05, 0x61, 0xCC, 0x86, + 0xCC, 0x80, 0xCA, 0x05, 0x61, 0xCC, 0x86, 0xCC, + 0x81, 0xCA, 0x05, 0x61, 0xCC, 0x86, 0xCC, 0x83, + 0xCA, 0x05, 0x61, 0xCC, 0x86, 0xCC, 0x89, 0xCA, + 0x05, 0x61, 0xCC, 0x87, 0xCC, 0x84, 0xCA, 0x05, + // Bytes 3a40 - 3a7f + 0x61, 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, 0x61, + 0xCC, 0x8A, 0xCC, 0x81, 0xCA, 0x05, 0x61, 0xCC, + 0xA3, 0xCC, 0x82, 0xCA, 0x05, 0x61, 0xCC, 0xA3, + 0xCC, 0x86, 0xCA, 0x05, 0x63, 0xCC, 0xA7, 0xCC, + 0x81, 0xCA, 0x05, 0x65, 0xCC, 0x82, 0xCC, 0x80, + 0xCA, 0x05, 0x65, 0xCC, 0x82, 0xCC, 0x81, 0xCA, + 0x05, 0x65, 0xCC, 0x82, 0xCC, 0x83, 0xCA, 0x05, + 0x65, 0xCC, 0x82, 0xCC, 0x89, 0xCA, 0x05, 0x65, + // Bytes 3a80 - 3abf + 0xCC, 0x84, 0xCC, 0x80, 0xCA, 0x05, 0x65, 0xCC, + 0x84, 0xCC, 0x81, 0xCA, 0x05, 0x65, 0xCC, 0xA3, + 0xCC, 0x82, 0xCA, 0x05, 0x65, 0xCC, 0xA7, 0xCC, + 0x86, 0xCA, 0x05, 0x69, 0xCC, 0x88, 0xCC, 0x81, + 0xCA, 0x05, 0x6C, 0xCC, 0xA3, 0xCC, 0x84, 0xCA, + 0x05, 0x6F, 0xCC, 0x82, 0xCC, 0x80, 0xCA, 0x05, + 0x6F, 0xCC, 0x82, 0xCC, 0x81, 0xCA, 0x05, 0x6F, + 0xCC, 0x82, 0xCC, 0x83, 0xCA, 0x05, 0x6F, 0xCC, + // Bytes 3ac0 - 3aff + 0x82, 0xCC, 0x89, 0xCA, 0x05, 0x6F, 0xCC, 0x83, + 0xCC, 0x81, 0xCA, 0x05, 0x6F, 0xCC, 0x83, 0xCC, + 0x84, 0xCA, 0x05, 0x6F, 0xCC, 0x83, 0xCC, 0x88, + 0xCA, 0x05, 0x6F, 0xCC, 0x84, 0xCC, 0x80, 0xCA, + 0x05, 0x6F, 0xCC, 0x84, 0xCC, 0x81, 0xCA, 0x05, + 0x6F, 0xCC, 0x87, 0xCC, 0x84, 0xCA, 0x05, 0x6F, + 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, 0x6F, 0xCC, + 0x9B, 0xCC, 0x80, 0xCA, 0x05, 0x6F, 0xCC, 0x9B, + // Bytes 3b00 - 3b3f + 0xCC, 0x81, 0xCA, 0x05, 0x6F, 0xCC, 0x9B, 0xCC, + 0x83, 0xCA, 0x05, 0x6F, 0xCC, 0x9B, 0xCC, 0x89, + 0xCA, 0x05, 0x6F, 0xCC, 0x9B, 0xCC, 0xA3, 0xB6, + 0x05, 0x6F, 0xCC, 0xA3, 0xCC, 0x82, 0xCA, 0x05, + 0x6F, 0xCC, 0xA8, 0xCC, 0x84, 0xCA, 0x05, 0x72, + 0xCC, 0xA3, 0xCC, 0x84, 0xCA, 0x05, 0x73, 0xCC, + 0x81, 0xCC, 0x87, 0xCA, 0x05, 0x73, 0xCC, 0x8C, + 0xCC, 0x87, 0xCA, 0x05, 0x73, 0xCC, 0xA3, 0xCC, + // Bytes 3b40 - 3b7f + 0x87, 0xCA, 0x05, 0x75, 0xCC, 0x83, 0xCC, 0x81, + 0xCA, 0x05, 0x75, 0xCC, 0x84, 0xCC, 0x88, 0xCA, + 0x05, 0x75, 0xCC, 0x88, 0xCC, 0x80, 0xCA, 0x05, + 0x75, 0xCC, 0x88, 0xCC, 0x81, 0xCA, 0x05, 0x75, + 0xCC, 0x88, 0xCC, 0x84, 0xCA, 0x05, 0x75, 0xCC, + 0x88, 0xCC, 0x8C, 0xCA, 0x05, 0x75, 0xCC, 0x9B, + 0xCC, 0x80, 0xCA, 0x05, 0x75, 0xCC, 0x9B, 0xCC, + 0x81, 0xCA, 0x05, 0x75, 0xCC, 0x9B, 0xCC, 0x83, + // Bytes 3b80 - 3bbf + 0xCA, 0x05, 0x75, 0xCC, 0x9B, 0xCC, 0x89, 0xCA, + 0x05, 0x75, 0xCC, 0x9B, 0xCC, 0xA3, 0xB6, 0x05, + 0xE1, 0xBE, 0xBF, 0xCC, 0x80, 0xCA, 0x05, 0xE1, + 0xBE, 0xBF, 0xCC, 0x81, 0xCA, 0x05, 0xE1, 0xBE, + 0xBF, 0xCD, 0x82, 0xCA, 0x05, 0xE1, 0xBF, 0xBE, + 0xCC, 0x80, 0xCA, 0x05, 0xE1, 0xBF, 0xBE, 0xCC, + 0x81, 0xCA, 0x05, 0xE1, 0xBF, 0xBE, 0xCD, 0x82, + 0xCA, 0x05, 0xE2, 0x86, 0x90, 0xCC, 0xB8, 0x05, + // Bytes 3bc0 - 3bff + 0x05, 0xE2, 0x86, 0x92, 0xCC, 0xB8, 0x05, 0x05, + 0xE2, 0x86, 0x94, 0xCC, 0xB8, 0x05, 0x05, 0xE2, + 0x87, 0x90, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x87, + 0x92, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x87, 0x94, + 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x88, 0x83, 0xCC, + 0xB8, 0x05, 0x05, 0xE2, 0x88, 0x88, 0xCC, 0xB8, + 0x05, 0x05, 0xE2, 0x88, 0x8B, 0xCC, 0xB8, 0x05, + 0x05, 0xE2, 0x88, 0xA3, 0xCC, 0xB8, 0x05, 0x05, + // Bytes 3c00 - 3c3f + 0xE2, 0x88, 0xA5, 0xCC, 0xB8, 0x05, 0x05, 0xE2, + 0x88, 0xBC, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, + 0x83, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0x85, + 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0x88, 0xCC, + 0xB8, 0x05, 0x05, 0xE2, 0x89, 0x8D, 0xCC, 0xB8, + 0x05, 0x05, 0xE2, 0x89, 0xA1, 0xCC, 0xB8, 0x05, + 0x05, 0xE2, 0x89, 0xA4, 0xCC, 0xB8, 0x05, 0x05, + 0xE2, 0x89, 0xA5, 0xCC, 0xB8, 0x05, 0x05, 0xE2, + // Bytes 3c40 - 3c7f + 0x89, 0xB2, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, + 0xB3, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xB6, + 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xB7, 0xCC, + 0xB8, 0x05, 0x05, 0xE2, 0x89, 0xBA, 0xCC, 0xB8, + 0x05, 0x05, 0xE2, 0x89, 0xBB, 0xCC, 0xB8, 0x05, + 0x05, 0xE2, 0x89, 0xBC, 0xCC, 0xB8, 0x05, 0x05, + 0xE2, 0x89, 0xBD, 0xCC, 0xB8, 0x05, 0x05, 0xE2, + 0x8A, 0x82, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, + // Bytes 3c80 - 3cbf + 0x83, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0x86, + 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0x87, 0xCC, + 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0x91, 0xCC, 0xB8, + 0x05, 0x05, 0xE2, 0x8A, 0x92, 0xCC, 0xB8, 0x05, + 0x05, 0xE2, 0x8A, 0xA2, 0xCC, 0xB8, 0x05, 0x05, + 0xE2, 0x8A, 0xA8, 0xCC, 0xB8, 0x05, 0x05, 0xE2, + 0x8A, 0xA9, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, + 0xAB, 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0xB2, + // Bytes 3cc0 - 3cff + 0xCC, 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0xB3, 0xCC, + 0xB8, 0x05, 0x05, 0xE2, 0x8A, 0xB4, 0xCC, 0xB8, + 0x05, 0x05, 0xE2, 0x8A, 0xB5, 0xCC, 0xB8, 0x05, + 0x06, 0xCE, 0x91, 0xCC, 0x93, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0x91, 0xCC, 0x94, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0x95, 0xCC, 0x93, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0x95, 0xCC, 0x93, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0x95, 0xCC, 0x94, 0xCC, 0x80, 0xCA, + // Bytes 3d00 - 3d3f + 0x06, 0xCE, 0x95, 0xCC, 0x94, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0x97, 0xCC, 0x93, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0x97, 0xCC, 0x94, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0x99, 0xCC, 0x93, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0x99, 0xCC, 0x93, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0x99, 0xCC, 0x93, 0xCD, 0x82, 0xCA, + 0x06, 0xCE, 0x99, 0xCC, 0x94, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0x99, 0xCC, 0x94, 0xCC, 0x81, 0xCA, + // Bytes 3d40 - 3d7f + 0x06, 0xCE, 0x99, 0xCC, 0x94, 0xCD, 0x82, 0xCA, + 0x06, 0xCE, 0x9F, 0xCC, 0x93, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0x9F, 0xCC, 0x93, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0x9F, 0xCC, 0x94, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0x9F, 0xCC, 0x94, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0xA5, 0xCC, 0x94, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0xA5, 0xCC, 0x94, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0xA5, 0xCC, 0x94, 0xCD, 0x82, 0xCA, + // Bytes 3d80 - 3dbf + 0x06, 0xCE, 0xA9, 0xCC, 0x93, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xA9, 0xCC, 0x94, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xB1, 0xCC, 0x80, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xB1, 0xCC, 0x81, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xB1, 0xCC, 0x93, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xB1, 0xCC, 0x94, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xB1, 0xCD, 0x82, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xB5, 0xCC, 0x93, 0xCC, 0x80, 0xCA, + // Bytes 3dc0 - 3dff + 0x06, 0xCE, 0xB5, 0xCC, 0x93, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0xB5, 0xCC, 0x94, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0xB5, 0xCC, 0x94, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0xB7, 0xCC, 0x80, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xB7, 0xCC, 0x81, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xB7, 0xCC, 0x93, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xB7, 0xCC, 0x94, 0xCD, 0x85, 0xDA, + 0x06, 0xCE, 0xB7, 0xCD, 0x82, 0xCD, 0x85, 0xDA, + // Bytes 3e00 - 3e3f + 0x06, 0xCE, 0xB9, 0xCC, 0x88, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0xB9, 0xCC, 0x88, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0xB9, 0xCC, 0x88, 0xCD, 0x82, 0xCA, + 0x06, 0xCE, 0xB9, 0xCC, 0x93, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0xB9, 0xCC, 0x93, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0xB9, 0xCC, 0x93, 0xCD, 0x82, 0xCA, + 0x06, 0xCE, 0xB9, 0xCC, 0x94, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0xB9, 0xCC, 0x94, 0xCC, 0x81, 0xCA, + // Bytes 3e40 - 3e7f + 0x06, 0xCE, 0xB9, 0xCC, 0x94, 0xCD, 0x82, 0xCA, + 0x06, 0xCE, 0xBF, 0xCC, 0x93, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0xBF, 0xCC, 0x93, 0xCC, 0x81, 0xCA, + 0x06, 0xCE, 0xBF, 0xCC, 0x94, 0xCC, 0x80, 0xCA, + 0x06, 0xCE, 0xBF, 0xCC, 0x94, 0xCC, 0x81, 0xCA, + 0x06, 0xCF, 0x85, 0xCC, 0x88, 0xCC, 0x80, 0xCA, + 0x06, 0xCF, 0x85, 0xCC, 0x88, 0xCC, 0x81, 0xCA, + 0x06, 0xCF, 0x85, 0xCC, 0x88, 0xCD, 0x82, 0xCA, + // Bytes 3e80 - 3ebf + 0x06, 0xCF, 0x85, 0xCC, 0x93, 0xCC, 0x80, 0xCA, + 0x06, 0xCF, 0x85, 0xCC, 0x93, 0xCC, 0x81, 0xCA, + 0x06, 0xCF, 0x85, 0xCC, 0x93, 0xCD, 0x82, 0xCA, + 0x06, 0xCF, 0x85, 0xCC, 0x94, 0xCC, 0x80, 0xCA, + 0x06, 0xCF, 0x85, 0xCC, 0x94, 0xCC, 0x81, 0xCA, + 0x06, 0xCF, 0x85, 0xCC, 0x94, 0xCD, 0x82, 0xCA, + 0x06, 0xCF, 0x89, 0xCC, 0x80, 0xCD, 0x85, 0xDA, + 0x06, 0xCF, 0x89, 0xCC, 0x81, 0xCD, 0x85, 0xDA, + // Bytes 3ec0 - 3eff + 0x06, 0xCF, 0x89, 0xCC, 0x93, 0xCD, 0x85, 0xDA, + 0x06, 0xCF, 0x89, 0xCC, 0x94, 0xCD, 0x85, 0xDA, + 0x06, 0xCF, 0x89, 0xCD, 0x82, 0xCD, 0x85, 0xDA, + 0x06, 0xE0, 0xA4, 0xA8, 0xE0, 0xA4, 0xBC, 0x09, + 0x06, 0xE0, 0xA4, 0xB0, 0xE0, 0xA4, 0xBC, 0x09, + 0x06, 0xE0, 0xA4, 0xB3, 0xE0, 0xA4, 0xBC, 0x09, + 0x06, 0xE0, 0xB1, 0x86, 0xE0, 0xB1, 0x96, 0x85, + 0x06, 0xE0, 0xB7, 0x99, 0xE0, 0xB7, 0x8A, 0x11, + // Bytes 3f00 - 3f3f + 0x06, 0xE3, 0x81, 0x86, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0x8B, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0x8D, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0x8F, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0x91, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0x93, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0x95, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0x97, 0xE3, 0x82, 0x99, 0x0D, + // Bytes 3f40 - 3f7f + 0x06, 0xE3, 0x81, 0x99, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0x9B, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0x9D, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0x9F, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0xA4, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0xA6, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0xA8, 0xE3, 0x82, 0x99, 0x0D, + // Bytes 3f80 - 3fbf + 0x06, 0xE3, 0x81, 0xAF, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0xAF, 0xE3, 0x82, 0x9A, 0x0D, + 0x06, 0xE3, 0x81, 0xB2, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0xB2, 0xE3, 0x82, 0x9A, 0x0D, + 0x06, 0xE3, 0x81, 0xB5, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0xB5, 0xE3, 0x82, 0x9A, 0x0D, + 0x06, 0xE3, 0x81, 0xB8, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0xB8, 0xE3, 0x82, 0x9A, 0x0D, + // Bytes 3fc0 - 3fff + 0x06, 0xE3, 0x81, 0xBB, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x81, 0xBB, 0xE3, 0x82, 0x9A, 0x0D, + 0x06, 0xE3, 0x82, 0x9D, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xA6, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xAB, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xAD, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xAF, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xB1, 0xE3, 0x82, 0x99, 0x0D, + // Bytes 4000 - 403f + 0x06, 0xE3, 0x82, 0xB3, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xB5, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xB7, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xB9, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xBB, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xBD, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x82, 0xBF, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0x81, 0xE3, 0x82, 0x99, 0x0D, + // Bytes 4040 - 407f + 0x06, 0xE3, 0x83, 0x84, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0x86, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0x88, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0x8F, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0x8F, 0xE3, 0x82, 0x9A, 0x0D, + 0x06, 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0x92, 0xE3, 0x82, 0x9A, 0x0D, + 0x06, 0xE3, 0x83, 0x95, 0xE3, 0x82, 0x99, 0x0D, + // Bytes 4080 - 40bf + 0x06, 0xE3, 0x83, 0x95, 0xE3, 0x82, 0x9A, 0x0D, + 0x06, 0xE3, 0x83, 0x98, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0x98, 0xE3, 0x82, 0x9A, 0x0D, + 0x06, 0xE3, 0x83, 0x9B, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0x9B, 0xE3, 0x82, 0x9A, 0x0D, + 0x06, 0xE3, 0x83, 0xAF, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0xB0, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0xB1, 0xE3, 0x82, 0x99, 0x0D, + // Bytes 40c0 - 40ff + 0x06, 0xE3, 0x83, 0xB2, 0xE3, 0x82, 0x99, 0x0D, + 0x06, 0xE3, 0x83, 0xBD, 0xE3, 0x82, 0x99, 0x0D, + 0x08, 0xCE, 0x91, 0xCC, 0x93, 0xCC, 0x80, 0xCD, + 0x85, 0xDB, 0x08, 0xCE, 0x91, 0xCC, 0x93, 0xCC, + 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x91, 0xCC, + 0x93, 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE, + 0x91, 0xCC, 0x94, 0xCC, 0x80, 0xCD, 0x85, 0xDB, + 0x08, 0xCE, 0x91, 0xCC, 0x94, 0xCC, 0x81, 0xCD, + // Bytes 4100 - 413f + 0x85, 0xDB, 0x08, 0xCE, 0x91, 0xCC, 0x94, 0xCD, + 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x97, 0xCC, + 0x93, 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE, + 0x97, 0xCC, 0x93, 0xCC, 0x81, 0xCD, 0x85, 0xDB, + 0x08, 0xCE, 0x97, 0xCC, 0x93, 0xCD, 0x82, 0xCD, + 0x85, 0xDB, 0x08, 0xCE, 0x97, 0xCC, 0x94, 0xCC, + 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0x97, 0xCC, + 0x94, 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, + // Bytes 4140 - 417f + 0x97, 0xCC, 0x94, 0xCD, 0x82, 0xCD, 0x85, 0xDB, + 0x08, 0xCE, 0xA9, 0xCC, 0x93, 0xCC, 0x80, 0xCD, + 0x85, 0xDB, 0x08, 0xCE, 0xA9, 0xCC, 0x93, 0xCC, + 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xA9, 0xCC, + 0x93, 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE, + 0xA9, 0xCC, 0x94, 0xCC, 0x80, 0xCD, 0x85, 0xDB, + 0x08, 0xCE, 0xA9, 0xCC, 0x94, 0xCC, 0x81, 0xCD, + 0x85, 0xDB, 0x08, 0xCE, 0xA9, 0xCC, 0x94, 0xCD, + // Bytes 4180 - 41bf + 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB1, 0xCC, + 0x93, 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE, + 0xB1, 0xCC, 0x93, 0xCC, 0x81, 0xCD, 0x85, 0xDB, + 0x08, 0xCE, 0xB1, 0xCC, 0x93, 0xCD, 0x82, 0xCD, + 0x85, 0xDB, 0x08, 0xCE, 0xB1, 0xCC, 0x94, 0xCC, + 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB1, 0xCC, + 0x94, 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, + 0xB1, 0xCC, 0x94, 0xCD, 0x82, 0xCD, 0x85, 0xDB, + // Bytes 41c0 - 41ff + 0x08, 0xCE, 0xB7, 0xCC, 0x93, 0xCC, 0x80, 0xCD, + 0x85, 0xDB, 0x08, 0xCE, 0xB7, 0xCC, 0x93, 0xCC, + 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCE, 0xB7, 0xCC, + 0x93, 0xCD, 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCE, + 0xB7, 0xCC, 0x94, 0xCC, 0x80, 0xCD, 0x85, 0xDB, + 0x08, 0xCE, 0xB7, 0xCC, 0x94, 0xCC, 0x81, 0xCD, + 0x85, 0xDB, 0x08, 0xCE, 0xB7, 0xCC, 0x94, 0xCD, + 0x82, 0xCD, 0x85, 0xDB, 0x08, 0xCF, 0x89, 0xCC, + // Bytes 4200 - 423f + 0x93, 0xCC, 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCF, + 0x89, 0xCC, 0x93, 0xCC, 0x81, 0xCD, 0x85, 0xDB, + 0x08, 0xCF, 0x89, 0xCC, 0x93, 0xCD, 0x82, 0xCD, + 0x85, 0xDB, 0x08, 0xCF, 0x89, 0xCC, 0x94, 0xCC, + 0x80, 0xCD, 0x85, 0xDB, 0x08, 0xCF, 0x89, 0xCC, + 0x94, 0xCC, 0x81, 0xCD, 0x85, 0xDB, 0x08, 0xCF, + 0x89, 0xCC, 0x94, 0xCD, 0x82, 0xCD, 0x85, 0xDB, + 0x08, 0xF0, 0x91, 0x82, 0x99, 0xF0, 0x91, 0x82, + // Bytes 4240 - 427f + 0xBA, 0x09, 0x08, 0xF0, 0x91, 0x82, 0x9B, 0xF0, + 0x91, 0x82, 0xBA, 0x09, 0x08, 0xF0, 0x91, 0x82, + 0xA5, 0xF0, 0x91, 0x82, 0xBA, 0x09, 0x42, 0xC2, + 0xB4, 0x01, 0x43, 0x20, 0xCC, 0x81, 0xC9, 0x43, + 0x20, 0xCC, 0x83, 0xC9, 0x43, 0x20, 0xCC, 0x84, + 0xC9, 0x43, 0x20, 0xCC, 0x85, 0xC9, 0x43, 0x20, + 0xCC, 0x86, 0xC9, 0x43, 0x20, 0xCC, 0x87, 0xC9, + 0x43, 0x20, 0xCC, 0x88, 0xC9, 0x43, 0x20, 0xCC, + // Bytes 4280 - 42bf + 0x8A, 0xC9, 0x43, 0x20, 0xCC, 0x8B, 0xC9, 0x43, + 0x20, 0xCC, 0x93, 0xC9, 0x43, 0x20, 0xCC, 0x94, + 0xC9, 0x43, 0x20, 0xCC, 0xA7, 0xA5, 0x43, 0x20, + 0xCC, 0xA8, 0xA5, 0x43, 0x20, 0xCC, 0xB3, 0xB5, + 0x43, 0x20, 0xCD, 0x82, 0xC9, 0x43, 0x20, 0xCD, + 0x85, 0xD9, 0x43, 0x20, 0xD9, 0x8B, 0x59, 0x43, + 0x20, 0xD9, 0x8C, 0x5D, 0x43, 0x20, 0xD9, 0x8D, + 0x61, 0x43, 0x20, 0xD9, 0x8E, 0x65, 0x43, 0x20, + // Bytes 42c0 - 42ff + 0xD9, 0x8F, 0x69, 0x43, 0x20, 0xD9, 0x90, 0x6D, + 0x43, 0x20, 0xD9, 0x91, 0x71, 0x43, 0x20, 0xD9, + 0x92, 0x75, 0x43, 0x41, 0xCC, 0x8A, 0xC9, 0x43, + 0x73, 0xCC, 0x87, 0xC9, 0x44, 0x20, 0xE3, 0x82, + 0x99, 0x0D, 0x44, 0x20, 0xE3, 0x82, 0x9A, 0x0D, + 0x44, 0xC2, 0xA8, 0xCC, 0x81, 0xCA, 0x44, 0xCE, + 0x91, 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0x95, 0xCC, + 0x81, 0xC9, 0x44, 0xCE, 0x97, 0xCC, 0x81, 0xC9, + // Bytes 4300 - 433f + 0x44, 0xCE, 0x99, 0xCC, 0x81, 0xC9, 0x44, 0xCE, + 0x9F, 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0xA5, 0xCC, + 0x81, 0xC9, 0x44, 0xCE, 0xA5, 0xCC, 0x88, 0xC9, + 0x44, 0xCE, 0xA9, 0xCC, 0x81, 0xC9, 0x44, 0xCE, + 0xB1, 0xCC, 0x81, 0xC9, 0x44, 0xCE, 0xB5, 0xCC, + 0x81, 0xC9, 0x44, 0xCE, 0xB7, 0xCC, 0x81, 0xC9, + 0x44, 0xCE, 0xB9, 0xCC, 0x81, 0xC9, 0x44, 0xCE, + 0xBF, 0xCC, 0x81, 0xC9, 0x44, 0xCF, 0x85, 0xCC, + // Bytes 4340 - 437f + 0x81, 0xC9, 0x44, 0xCF, 0x89, 0xCC, 0x81, 0xC9, + 0x44, 0xD7, 0x90, 0xD6, 0xB7, 0x31, 0x44, 0xD7, + 0x90, 0xD6, 0xB8, 0x35, 0x44, 0xD7, 0x90, 0xD6, + 0xBC, 0x41, 0x44, 0xD7, 0x91, 0xD6, 0xBC, 0x41, + 0x44, 0xD7, 0x91, 0xD6, 0xBF, 0x49, 0x44, 0xD7, + 0x92, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x93, 0xD6, + 0xBC, 0x41, 0x44, 0xD7, 0x94, 0xD6, 0xBC, 0x41, + 0x44, 0xD7, 0x95, 0xD6, 0xB9, 0x39, 0x44, 0xD7, + // Bytes 4380 - 43bf + 0x95, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x96, 0xD6, + 0xBC, 0x41, 0x44, 0xD7, 0x98, 0xD6, 0xBC, 0x41, + 0x44, 0xD7, 0x99, 0xD6, 0xB4, 0x25, 0x44, 0xD7, + 0x99, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x9A, 0xD6, + 0xBC, 0x41, 0x44, 0xD7, 0x9B, 0xD6, 0xBC, 0x41, + 0x44, 0xD7, 0x9B, 0xD6, 0xBF, 0x49, 0x44, 0xD7, + 0x9C, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0x9E, 0xD6, + 0xBC, 0x41, 0x44, 0xD7, 0xA0, 0xD6, 0xBC, 0x41, + // Bytes 43c0 - 43ff + 0x44, 0xD7, 0xA1, 0xD6, 0xBC, 0x41, 0x44, 0xD7, + 0xA3, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0xA4, 0xD6, + 0xBC, 0x41, 0x44, 0xD7, 0xA4, 0xD6, 0xBF, 0x49, + 0x44, 0xD7, 0xA6, 0xD6, 0xBC, 0x41, 0x44, 0xD7, + 0xA7, 0xD6, 0xBC, 0x41, 0x44, 0xD7, 0xA8, 0xD6, + 0xBC, 0x41, 0x44, 0xD7, 0xA9, 0xD6, 0xBC, 0x41, + 0x44, 0xD7, 0xA9, 0xD7, 0x81, 0x4D, 0x44, 0xD7, + 0xA9, 0xD7, 0x82, 0x51, 0x44, 0xD7, 0xAA, 0xD6, + // Bytes 4400 - 443f + 0xBC, 0x41, 0x44, 0xD7, 0xB2, 0xD6, 0xB7, 0x31, + 0x44, 0xD8, 0xA7, 0xD9, 0x8B, 0x59, 0x44, 0xD8, + 0xA7, 0xD9, 0x93, 0xC9, 0x44, 0xD8, 0xA7, 0xD9, + 0x94, 0xC9, 0x44, 0xD8, 0xA7, 0xD9, 0x95, 0xB5, + 0x44, 0xD8, 0xB0, 0xD9, 0xB0, 0x79, 0x44, 0xD8, + 0xB1, 0xD9, 0xB0, 0x79, 0x44, 0xD9, 0x80, 0xD9, + 0x8B, 0x59, 0x44, 0xD9, 0x80, 0xD9, 0x8E, 0x65, + 0x44, 0xD9, 0x80, 0xD9, 0x8F, 0x69, 0x44, 0xD9, + // Bytes 4440 - 447f + 0x80, 0xD9, 0x90, 0x6D, 0x44, 0xD9, 0x80, 0xD9, + 0x91, 0x71, 0x44, 0xD9, 0x80, 0xD9, 0x92, 0x75, + 0x44, 0xD9, 0x87, 0xD9, 0xB0, 0x79, 0x44, 0xD9, + 0x88, 0xD9, 0x94, 0xC9, 0x44, 0xD9, 0x89, 0xD9, + 0xB0, 0x79, 0x44, 0xD9, 0x8A, 0xD9, 0x94, 0xC9, + 0x44, 0xDB, 0x92, 0xD9, 0x94, 0xC9, 0x44, 0xDB, + 0x95, 0xD9, 0x94, 0xC9, 0x45, 0x20, 0xCC, 0x88, + 0xCC, 0x80, 0xCA, 0x45, 0x20, 0xCC, 0x88, 0xCC, + // Bytes 4480 - 44bf + 0x81, 0xCA, 0x45, 0x20, 0xCC, 0x88, 0xCD, 0x82, + 0xCA, 0x45, 0x20, 0xCC, 0x93, 0xCC, 0x80, 0xCA, + 0x45, 0x20, 0xCC, 0x93, 0xCC, 0x81, 0xCA, 0x45, + 0x20, 0xCC, 0x93, 0xCD, 0x82, 0xCA, 0x45, 0x20, + 0xCC, 0x94, 0xCC, 0x80, 0xCA, 0x45, 0x20, 0xCC, + 0x94, 0xCC, 0x81, 0xCA, 0x45, 0x20, 0xCC, 0x94, + 0xCD, 0x82, 0xCA, 0x45, 0x20, 0xD9, 0x8C, 0xD9, + 0x91, 0x72, 0x45, 0x20, 0xD9, 0x8D, 0xD9, 0x91, + // Bytes 44c0 - 44ff + 0x72, 0x45, 0x20, 0xD9, 0x8E, 0xD9, 0x91, 0x72, + 0x45, 0x20, 0xD9, 0x8F, 0xD9, 0x91, 0x72, 0x45, + 0x20, 0xD9, 0x90, 0xD9, 0x91, 0x72, 0x45, 0x20, + 0xD9, 0x91, 0xD9, 0xB0, 0x7A, 0x45, 0xE2, 0xAB, + 0x9D, 0xCC, 0xB8, 0x05, 0x46, 0xCE, 0xB9, 0xCC, + 0x88, 0xCC, 0x81, 0xCA, 0x46, 0xCF, 0x85, 0xCC, + 0x88, 0xCC, 0x81, 0xCA, 0x46, 0xD7, 0xA9, 0xD6, + 0xBC, 0xD7, 0x81, 0x4E, 0x46, 0xD7, 0xA9, 0xD6, + // Bytes 4500 - 453f + 0xBC, 0xD7, 0x82, 0x52, 0x46, 0xD9, 0x80, 0xD9, + 0x8E, 0xD9, 0x91, 0x72, 0x46, 0xD9, 0x80, 0xD9, + 0x8F, 0xD9, 0x91, 0x72, 0x46, 0xD9, 0x80, 0xD9, + 0x90, 0xD9, 0x91, 0x72, 0x46, 0xE0, 0xA4, 0x95, + 0xE0, 0xA4, 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0x96, + 0xE0, 0xA4, 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0x97, + 0xE0, 0xA4, 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0x9C, + 0xE0, 0xA4, 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0xA1, + // Bytes 4540 - 457f + 0xE0, 0xA4, 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0xA2, + 0xE0, 0xA4, 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0xAB, + 0xE0, 0xA4, 0xBC, 0x09, 0x46, 0xE0, 0xA4, 0xAF, + 0xE0, 0xA4, 0xBC, 0x09, 0x46, 0xE0, 0xA6, 0xA1, + 0xE0, 0xA6, 0xBC, 0x09, 0x46, 0xE0, 0xA6, 0xA2, + 0xE0, 0xA6, 0xBC, 0x09, 0x46, 0xE0, 0xA6, 0xAF, + 0xE0, 0xA6, 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0x96, + 0xE0, 0xA8, 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0x97, + // Bytes 4580 - 45bf + 0xE0, 0xA8, 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0x9C, + 0xE0, 0xA8, 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0xAB, + 0xE0, 0xA8, 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0xB2, + 0xE0, 0xA8, 0xBC, 0x09, 0x46, 0xE0, 0xA8, 0xB8, + 0xE0, 0xA8, 0xBC, 0x09, 0x46, 0xE0, 0xAC, 0xA1, + 0xE0, 0xAC, 0xBC, 0x09, 0x46, 0xE0, 0xAC, 0xA2, + 0xE0, 0xAC, 0xBC, 0x09, 0x46, 0xE0, 0xBE, 0xB2, + 0xE0, 0xBE, 0x80, 0x9D, 0x46, 0xE0, 0xBE, 0xB3, + // Bytes 45c0 - 45ff + 0xE0, 0xBE, 0x80, 0x9D, 0x46, 0xE3, 0x83, 0x86, + 0xE3, 0x82, 0x99, 0x0D, 0x48, 0xF0, 0x9D, 0x85, + 0x97, 0xF0, 0x9D, 0x85, 0xA5, 0xAD, 0x48, 0xF0, + 0x9D, 0x85, 0x98, 0xF0, 0x9D, 0x85, 0xA5, 0xAD, + 0x48, 0xF0, 0x9D, 0x86, 0xB9, 0xF0, 0x9D, 0x85, + 0xA5, 0xAD, 0x48, 0xF0, 0x9D, 0x86, 0xBA, 0xF0, + 0x9D, 0x85, 0xA5, 0xAD, 0x49, 0xE0, 0xBE, 0xB2, + 0xE0, 0xBD, 0xB1, 0xE0, 0xBE, 0x80, 0x9E, 0x49, + // Bytes 4600 - 463f + 0xE0, 0xBE, 0xB3, 0xE0, 0xBD, 0xB1, 0xE0, 0xBE, + 0x80, 0x9E, 0x4C, 0xF0, 0x9D, 0x85, 0x98, 0xF0, + 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85, 0xAE, 0xAE, + 0x4C, 0xF0, 0x9D, 0x85, 0x98, 0xF0, 0x9D, 0x85, + 0xA5, 0xF0, 0x9D, 0x85, 0xAF, 0xAE, 0x4C, 0xF0, + 0x9D, 0x85, 0x98, 0xF0, 0x9D, 0x85, 0xA5, 0xF0, + 0x9D, 0x85, 0xB0, 0xAE, 0x4C, 0xF0, 0x9D, 0x85, + 0x98, 0xF0, 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85, + // Bytes 4640 - 467f + 0xB1, 0xAE, 0x4C, 0xF0, 0x9D, 0x85, 0x98, 0xF0, + 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85, 0xB2, 0xAE, + 0x4C, 0xF0, 0x9D, 0x86, 0xB9, 0xF0, 0x9D, 0x85, + 0xA5, 0xF0, 0x9D, 0x85, 0xAE, 0xAE, 0x4C, 0xF0, + 0x9D, 0x86, 0xB9, 0xF0, 0x9D, 0x85, 0xA5, 0xF0, + 0x9D, 0x85, 0xAF, 0xAE, 0x4C, 0xF0, 0x9D, 0x86, + 0xBA, 0xF0, 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85, + 0xAE, 0xAE, 0x4C, 0xF0, 0x9D, 0x86, 0xBA, 0xF0, + // Bytes 4680 - 46bf + 0x9D, 0x85, 0xA5, 0xF0, 0x9D, 0x85, 0xAF, 0xAE, + 0x83, 0x41, 0xCC, 0x82, 0xC9, 0x83, 0x41, 0xCC, + 0x86, 0xC9, 0x83, 0x41, 0xCC, 0x87, 0xC9, 0x83, + 0x41, 0xCC, 0x88, 0xC9, 0x83, 0x41, 0xCC, 0x8A, + 0xC9, 0x83, 0x41, 0xCC, 0xA3, 0xB5, 0x83, 0x43, + 0xCC, 0xA7, 0xA5, 0x83, 0x45, 0xCC, 0x82, 0xC9, + 0x83, 0x45, 0xCC, 0x84, 0xC9, 0x83, 0x45, 0xCC, + 0xA3, 0xB5, 0x83, 0x45, 0xCC, 0xA7, 0xA5, 0x83, + // Bytes 46c0 - 46ff + 0x49, 0xCC, 0x88, 0xC9, 0x83, 0x4C, 0xCC, 0xA3, + 0xB5, 0x83, 0x4F, 0xCC, 0x82, 0xC9, 0x83, 0x4F, + 0xCC, 0x83, 0xC9, 0x83, 0x4F, 0xCC, 0x84, 0xC9, + 0x83, 0x4F, 0xCC, 0x87, 0xC9, 0x83, 0x4F, 0xCC, + 0x88, 0xC9, 0x83, 0x4F, 0xCC, 0x9B, 0xAD, 0x83, + 0x4F, 0xCC, 0xA3, 0xB5, 0x83, 0x4F, 0xCC, 0xA8, + 0xA5, 0x83, 0x52, 0xCC, 0xA3, 0xB5, 0x83, 0x53, + 0xCC, 0x81, 0xC9, 0x83, 0x53, 0xCC, 0x8C, 0xC9, + // Bytes 4700 - 473f + 0x83, 0x53, 0xCC, 0xA3, 0xB5, 0x83, 0x55, 0xCC, + 0x83, 0xC9, 0x83, 0x55, 0xCC, 0x84, 0xC9, 0x83, + 0x55, 0xCC, 0x88, 0xC9, 0x83, 0x55, 0xCC, 0x9B, + 0xAD, 0x83, 0x61, 0xCC, 0x82, 0xC9, 0x83, 0x61, + 0xCC, 0x86, 0xC9, 0x83, 0x61, 0xCC, 0x87, 0xC9, + 0x83, 0x61, 0xCC, 0x88, 0xC9, 0x83, 0x61, 0xCC, + 0x8A, 0xC9, 0x83, 0x61, 0xCC, 0xA3, 0xB5, 0x83, + 0x63, 0xCC, 0xA7, 0xA5, 0x83, 0x65, 0xCC, 0x82, + // Bytes 4740 - 477f + 0xC9, 0x83, 0x65, 0xCC, 0x84, 0xC9, 0x83, 0x65, + 0xCC, 0xA3, 0xB5, 0x83, 0x65, 0xCC, 0xA7, 0xA5, + 0x83, 0x69, 0xCC, 0x88, 0xC9, 0x83, 0x6C, 0xCC, + 0xA3, 0xB5, 0x83, 0x6F, 0xCC, 0x82, 0xC9, 0x83, + 0x6F, 0xCC, 0x83, 0xC9, 0x83, 0x6F, 0xCC, 0x84, + 0xC9, 0x83, 0x6F, 0xCC, 0x87, 0xC9, 0x83, 0x6F, + 0xCC, 0x88, 0xC9, 0x83, 0x6F, 0xCC, 0x9B, 0xAD, + 0x83, 0x6F, 0xCC, 0xA3, 0xB5, 0x83, 0x6F, 0xCC, + // Bytes 4780 - 47bf + 0xA8, 0xA5, 0x83, 0x72, 0xCC, 0xA3, 0xB5, 0x83, + 0x73, 0xCC, 0x81, 0xC9, 0x83, 0x73, 0xCC, 0x8C, + 0xC9, 0x83, 0x73, 0xCC, 0xA3, 0xB5, 0x83, 0x75, + 0xCC, 0x83, 0xC9, 0x83, 0x75, 0xCC, 0x84, 0xC9, + 0x83, 0x75, 0xCC, 0x88, 0xC9, 0x83, 0x75, 0xCC, + 0x9B, 0xAD, 0x84, 0xCE, 0x91, 0xCC, 0x93, 0xC9, + 0x84, 0xCE, 0x91, 0xCC, 0x94, 0xC9, 0x84, 0xCE, + 0x95, 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0x95, 0xCC, + // Bytes 47c0 - 47ff + 0x94, 0xC9, 0x84, 0xCE, 0x97, 0xCC, 0x93, 0xC9, + 0x84, 0xCE, 0x97, 0xCC, 0x94, 0xC9, 0x84, 0xCE, + 0x99, 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0x99, 0xCC, + 0x94, 0xC9, 0x84, 0xCE, 0x9F, 0xCC, 0x93, 0xC9, + 0x84, 0xCE, 0x9F, 0xCC, 0x94, 0xC9, 0x84, 0xCE, + 0xA5, 0xCC, 0x94, 0xC9, 0x84, 0xCE, 0xA9, 0xCC, + 0x93, 0xC9, 0x84, 0xCE, 0xA9, 0xCC, 0x94, 0xC9, + 0x84, 0xCE, 0xB1, 0xCC, 0x80, 0xC9, 0x84, 0xCE, + // Bytes 4800 - 483f + 0xB1, 0xCC, 0x81, 0xC9, 0x84, 0xCE, 0xB1, 0xCC, + 0x93, 0xC9, 0x84, 0xCE, 0xB1, 0xCC, 0x94, 0xC9, + 0x84, 0xCE, 0xB1, 0xCD, 0x82, 0xC9, 0x84, 0xCE, + 0xB5, 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0xB5, 0xCC, + 0x94, 0xC9, 0x84, 0xCE, 0xB7, 0xCC, 0x80, 0xC9, + 0x84, 0xCE, 0xB7, 0xCC, 0x81, 0xC9, 0x84, 0xCE, + 0xB7, 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0xB7, 0xCC, + 0x94, 0xC9, 0x84, 0xCE, 0xB7, 0xCD, 0x82, 0xC9, + // Bytes 4840 - 487f + 0x84, 0xCE, 0xB9, 0xCC, 0x88, 0xC9, 0x84, 0xCE, + 0xB9, 0xCC, 0x93, 0xC9, 0x84, 0xCE, 0xB9, 0xCC, + 0x94, 0xC9, 0x84, 0xCE, 0xBF, 0xCC, 0x93, 0xC9, + 0x84, 0xCE, 0xBF, 0xCC, 0x94, 0xC9, 0x84, 0xCF, + 0x85, 0xCC, 0x88, 0xC9, 0x84, 0xCF, 0x85, 0xCC, + 0x93, 0xC9, 0x84, 0xCF, 0x85, 0xCC, 0x94, 0xC9, + 0x84, 0xCF, 0x89, 0xCC, 0x80, 0xC9, 0x84, 0xCF, + 0x89, 0xCC, 0x81, 0xC9, 0x84, 0xCF, 0x89, 0xCC, + // Bytes 4880 - 48bf + 0x93, 0xC9, 0x84, 0xCF, 0x89, 0xCC, 0x94, 0xC9, + 0x84, 0xCF, 0x89, 0xCD, 0x82, 0xC9, 0x86, 0xCE, + 0x91, 0xCC, 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCE, + 0x91, 0xCC, 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCE, + 0x91, 0xCC, 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCE, + 0x91, 0xCC, 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCE, + 0x91, 0xCC, 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCE, + 0x91, 0xCC, 0x94, 0xCD, 0x82, 0xCA, 0x86, 0xCE, + // Bytes 48c0 - 48ff + 0x97, 0xCC, 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCE, + 0x97, 0xCC, 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCE, + 0x97, 0xCC, 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCE, + 0x97, 0xCC, 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCE, + 0x97, 0xCC, 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCE, + 0x97, 0xCC, 0x94, 0xCD, 0x82, 0xCA, 0x86, 0xCE, + 0xA9, 0xCC, 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCE, + 0xA9, 0xCC, 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCE, + // Bytes 4900 - 493f + 0xA9, 0xCC, 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCE, + 0xA9, 0xCC, 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCE, + 0xA9, 0xCC, 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCE, + 0xA9, 0xCC, 0x94, 0xCD, 0x82, 0xCA, 0x86, 0xCE, + 0xB1, 0xCC, 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCE, + 0xB1, 0xCC, 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCE, + 0xB1, 0xCC, 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCE, + 0xB1, 0xCC, 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCE, + // Bytes 4940 - 497f + 0xB1, 0xCC, 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCE, + 0xB1, 0xCC, 0x94, 0xCD, 0x82, 0xCA, 0x86, 0xCE, + 0xB7, 0xCC, 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCE, + 0xB7, 0xCC, 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCE, + 0xB7, 0xCC, 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCE, + 0xB7, 0xCC, 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCE, + 0xB7, 0xCC, 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCE, + 0xB7, 0xCC, 0x94, 0xCD, 0x82, 0xCA, 0x86, 0xCF, + // Bytes 4980 - 49bf + 0x89, 0xCC, 0x93, 0xCC, 0x80, 0xCA, 0x86, 0xCF, + 0x89, 0xCC, 0x93, 0xCC, 0x81, 0xCA, 0x86, 0xCF, + 0x89, 0xCC, 0x93, 0xCD, 0x82, 0xCA, 0x86, 0xCF, + 0x89, 0xCC, 0x94, 0xCC, 0x80, 0xCA, 0x86, 0xCF, + 0x89, 0xCC, 0x94, 0xCC, 0x81, 0xCA, 0x86, 0xCF, + 0x89, 0xCC, 0x94, 0xCD, 0x82, 0xCA, 0x42, 0xCC, + 0x80, 0xC9, 0x32, 0x42, 0xCC, 0x81, 0xC9, 0x32, + 0x42, 0xCC, 0x93, 0xC9, 0x32, 0x43, 0xE1, 0x85, + // Bytes 49c0 - 49ff + 0xA1, 0x01, 0x00, 0x43, 0xE1, 0x85, 0xA2, 0x01, + 0x00, 0x43, 0xE1, 0x85, 0xA3, 0x01, 0x00, 0x43, + 0xE1, 0x85, 0xA4, 0x01, 0x00, 0x43, 0xE1, 0x85, + 0xA5, 0x01, 0x00, 0x43, 0xE1, 0x85, 0xA6, 0x01, + 0x00, 0x43, 0xE1, 0x85, 0xA7, 0x01, 0x00, 0x43, + 0xE1, 0x85, 0xA8, 0x01, 0x00, 0x43, 0xE1, 0x85, + 0xA9, 0x01, 0x00, 0x43, 0xE1, 0x85, 0xAA, 0x01, + 0x00, 0x43, 0xE1, 0x85, 0xAB, 0x01, 0x00, 0x43, + // Bytes 4a00 - 4a3f + 0xE1, 0x85, 0xAC, 0x01, 0x00, 0x43, 0xE1, 0x85, + 0xAD, 0x01, 0x00, 0x43, 0xE1, 0x85, 0xAE, 0x01, + 0x00, 0x43, 0xE1, 0x85, 0xAF, 0x01, 0x00, 0x43, + 0xE1, 0x85, 0xB0, 0x01, 0x00, 0x43, 0xE1, 0x85, + 0xB1, 0x01, 0x00, 0x43, 0xE1, 0x85, 0xB2, 0x01, + 0x00, 0x43, 0xE1, 0x85, 0xB3, 0x01, 0x00, 0x43, + 0xE1, 0x85, 0xB4, 0x01, 0x00, 0x43, 0xE1, 0x85, + 0xB5, 0x01, 0x00, 0x43, 0xE1, 0x86, 0xAA, 0x01, + // Bytes 4a40 - 4a7f + 0x00, 0x43, 0xE1, 0x86, 0xAC, 0x01, 0x00, 0x43, + 0xE1, 0x86, 0xAD, 0x01, 0x00, 0x43, 0xE1, 0x86, + 0xB0, 0x01, 0x00, 0x43, 0xE1, 0x86, 0xB1, 0x01, + 0x00, 0x43, 0xE1, 0x86, 0xB2, 0x01, 0x00, 0x43, + 0xE1, 0x86, 0xB3, 0x01, 0x00, 0x43, 0xE1, 0x86, + 0xB4, 0x01, 0x00, 0x43, 0xE1, 0x86, 0xB5, 0x01, + 0x00, 0x44, 0xCC, 0x88, 0xCC, 0x81, 0xCA, 0x32, + 0x43, 0xE3, 0x82, 0x99, 0x0D, 0x03, 0x43, 0xE3, + // Bytes 4a80 - 4abf + 0x82, 0x9A, 0x0D, 0x03, 0x46, 0xE0, 0xBD, 0xB1, + 0xE0, 0xBD, 0xB2, 0x9E, 0x26, 0x46, 0xE0, 0xBD, + 0xB1, 0xE0, 0xBD, 0xB4, 0xA2, 0x26, 0x46, 0xE0, + 0xBD, 0xB1, 0xE0, 0xBE, 0x80, 0x9E, 0x26, 0x00, + 0x01, +} + +// lookup returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *nfcTrie) lookup(s []byte) (v uint16, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return nfcValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = nfcIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *nfcTrie) lookupUnsafe(s []byte) uint16 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return nfcValues[c0] + } + i := nfcIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = nfcIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = nfcIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// lookupString returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *nfcTrie) lookupString(s string) (v uint16, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return nfcValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := nfcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = nfcIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *nfcTrie) lookupStringUnsafe(s string) uint16 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return nfcValues[c0] + } + i := nfcIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = nfcIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = nfcIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// nfcTrie. Total size: 10332 bytes (10.09 KiB). Checksum: 51cc525b297fc970. +type nfcTrie struct{} + +func newNfcTrie(i int) *nfcTrie { + return &nfcTrie{} +} + +// lookupValue determines the type of block n and looks up the value for b. +func (t *nfcTrie) lookupValue(n uint32, b byte) uint16 { + switch { + case n < 44: + return uint16(nfcValues[n<<6+uint32(b)]) + default: + n -= 44 + return uint16(nfcSparse.lookup(n, b)) + } +} + +// nfcValues: 46 blocks, 2944 entries, 5888 bytes +// The third block is the zero block. +var nfcValues = [2944]uint16{ + // Block 0x0, offset 0x0 + 0x3c: 0xa000, 0x3d: 0xa000, 0x3e: 0xa000, + // Block 0x1, offset 0x40 + 0x41: 0xa000, 0x42: 0xa000, 0x43: 0xa000, 0x44: 0xa000, 0x45: 0xa000, + 0x46: 0xa000, 0x47: 0xa000, 0x48: 0xa000, 0x49: 0xa000, 0x4a: 0xa000, 0x4b: 0xa000, + 0x4c: 0xa000, 0x4d: 0xa000, 0x4e: 0xa000, 0x4f: 0xa000, 0x50: 0xa000, + 0x52: 0xa000, 0x53: 0xa000, 0x54: 0xa000, 0x55: 0xa000, 0x56: 0xa000, 0x57: 0xa000, + 0x58: 0xa000, 0x59: 0xa000, 0x5a: 0xa000, + 0x61: 0xa000, 0x62: 0xa000, 0x63: 0xa000, + 0x64: 0xa000, 0x65: 0xa000, 0x66: 0xa000, 0x67: 0xa000, 0x68: 0xa000, 0x69: 0xa000, + 0x6a: 0xa000, 0x6b: 0xa000, 0x6c: 0xa000, 0x6d: 0xa000, 0x6e: 0xa000, 0x6f: 0xa000, + 0x70: 0xa000, 0x72: 0xa000, 0x73: 0xa000, 0x74: 0xa000, 0x75: 0xa000, + 0x76: 0xa000, 0x77: 0xa000, 0x78: 0xa000, 0x79: 0xa000, 0x7a: 0xa000, + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc0: 0x2f6f, 0xc1: 0x2f74, 0xc2: 0x4688, 0xc3: 0x2f79, 0xc4: 0x4697, 0xc5: 0x469c, + 0xc6: 0xa000, 0xc7: 0x46a6, 0xc8: 0x2fe2, 0xc9: 0x2fe7, 0xca: 0x46ab, 0xcb: 0x2ffb, + 0xcc: 0x306e, 0xcd: 0x3073, 0xce: 0x3078, 0xcf: 0x46bf, 0xd1: 0x3104, + 0xd2: 0x3127, 0xd3: 0x312c, 0xd4: 0x46c9, 0xd5: 0x46ce, 0xd6: 0x46dd, + 0xd8: 0xa000, 0xd9: 0x31b3, 0xda: 0x31b8, 0xdb: 0x31bd, 0xdc: 0x470f, 0xdd: 0x3235, + 0xe0: 0x327b, 0xe1: 0x3280, 0xe2: 0x4719, 0xe3: 0x3285, + 0xe4: 0x4728, 0xe5: 0x472d, 0xe6: 0xa000, 0xe7: 0x4737, 0xe8: 0x32ee, 0xe9: 0x32f3, + 0xea: 0x473c, 0xeb: 0x3307, 0xec: 0x337f, 0xed: 0x3384, 0xee: 0x3389, 0xef: 0x4750, + 0xf1: 0x3415, 0xf2: 0x3438, 0xf3: 0x343d, 0xf4: 0x475a, 0xf5: 0x475f, + 0xf6: 0x476e, 0xf8: 0xa000, 0xf9: 0x34c9, 0xfa: 0x34ce, 0xfb: 0x34d3, + 0xfc: 0x47a0, 0xfd: 0x3550, 0xff: 0x3569, + // Block 0x4, offset 0x100 + 0x100: 0x2f7e, 0x101: 0x328a, 0x102: 0x468d, 0x103: 0x471e, 0x104: 0x2f9c, 0x105: 0x32a8, + 0x106: 0x2fb0, 0x107: 0x32bc, 0x108: 0x2fb5, 0x109: 0x32c1, 0x10a: 0x2fba, 0x10b: 0x32c6, + 0x10c: 0x2fbf, 0x10d: 0x32cb, 0x10e: 0x2fc9, 0x10f: 0x32d5, + 0x112: 0x46b0, 0x113: 0x4741, 0x114: 0x2ff1, 0x115: 0x32fd, 0x116: 0x2ff6, 0x117: 0x3302, + 0x118: 0x3014, 0x119: 0x3320, 0x11a: 0x3005, 0x11b: 0x3311, 0x11c: 0x302d, 0x11d: 0x3339, + 0x11e: 0x3037, 0x11f: 0x3343, 0x120: 0x303c, 0x121: 0x3348, 0x122: 0x3046, 0x123: 0x3352, + 0x124: 0x304b, 0x125: 0x3357, 0x128: 0x307d, 0x129: 0x338e, + 0x12a: 0x3082, 0x12b: 0x3393, 0x12c: 0x3087, 0x12d: 0x3398, 0x12e: 0x30aa, 0x12f: 0x33b6, + 0x130: 0x308c, 0x134: 0x30b4, 0x135: 0x33c0, + 0x136: 0x30c8, 0x137: 0x33d9, 0x139: 0x30d2, 0x13a: 0x33e3, 0x13b: 0x30dc, + 0x13c: 0x33ed, 0x13d: 0x30d7, 0x13e: 0x33e8, + // Block 0x5, offset 0x140 + 0x143: 0x30ff, 0x144: 0x3410, 0x145: 0x3118, + 0x146: 0x3429, 0x147: 0x310e, 0x148: 0x341f, + 0x14c: 0x46d3, 0x14d: 0x4764, 0x14e: 0x3131, 0x14f: 0x3442, 0x150: 0x313b, 0x151: 0x344c, + 0x154: 0x3159, 0x155: 0x346a, 0x156: 0x3172, 0x157: 0x3483, + 0x158: 0x3163, 0x159: 0x3474, 0x15a: 0x46f6, 0x15b: 0x4787, 0x15c: 0x317c, 0x15d: 0x348d, + 0x15e: 0x318b, 0x15f: 0x349c, 0x160: 0x46fb, 0x161: 0x478c, 0x162: 0x31a4, 0x163: 0x34ba, + 0x164: 0x3195, 0x165: 0x34ab, 0x168: 0x4705, 0x169: 0x4796, + 0x16a: 0x470a, 0x16b: 0x479b, 0x16c: 0x31c2, 0x16d: 0x34d8, 0x16e: 0x31cc, 0x16f: 0x34e2, + 0x170: 0x31d1, 0x171: 0x34e7, 0x172: 0x31ef, 0x173: 0x3505, 0x174: 0x3212, 0x175: 0x3528, + 0x176: 0x323a, 0x177: 0x3555, 0x178: 0x324e, 0x179: 0x325d, 0x17a: 0x357d, 0x17b: 0x3267, + 0x17c: 0x3587, 0x17d: 0x326c, 0x17e: 0x358c, 0x17f: 0xa000, + // Block 0x6, offset 0x180 + 0x184: 0x8100, 0x185: 0x8100, + 0x186: 0x8100, + 0x18d: 0x2f88, 0x18e: 0x3294, 0x18f: 0x3096, 0x190: 0x33a2, 0x191: 0x3140, + 0x192: 0x3451, 0x193: 0x31d6, 0x194: 0x34ec, 0x195: 0x39cf, 0x196: 0x3b5e, 0x197: 0x39c8, + 0x198: 0x3b57, 0x199: 0x39d6, 0x19a: 0x3b65, 0x19b: 0x39c1, 0x19c: 0x3b50, + 0x19e: 0x38b0, 0x19f: 0x3a3f, 0x1a0: 0x38a9, 0x1a1: 0x3a38, 0x1a2: 0x35b3, 0x1a3: 0x35c5, + 0x1a6: 0x3041, 0x1a7: 0x334d, 0x1a8: 0x30be, 0x1a9: 0x33cf, + 0x1aa: 0x46ec, 0x1ab: 0x477d, 0x1ac: 0x3990, 0x1ad: 0x3b1f, 0x1ae: 0x35d7, 0x1af: 0x35dd, + 0x1b0: 0x33c5, 0x1b4: 0x3028, 0x1b5: 0x3334, + 0x1b8: 0x30fa, 0x1b9: 0x340b, 0x1ba: 0x38b7, 0x1bb: 0x3a46, + 0x1bc: 0x35ad, 0x1bd: 0x35bf, 0x1be: 0x35b9, 0x1bf: 0x35cb, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x2f8d, 0x1c1: 0x3299, 0x1c2: 0x2f92, 0x1c3: 0x329e, 0x1c4: 0x300a, 0x1c5: 0x3316, + 0x1c6: 0x300f, 0x1c7: 0x331b, 0x1c8: 0x309b, 0x1c9: 0x33a7, 0x1ca: 0x30a0, 0x1cb: 0x33ac, + 0x1cc: 0x3145, 0x1cd: 0x3456, 0x1ce: 0x314a, 0x1cf: 0x345b, 0x1d0: 0x3168, 0x1d1: 0x3479, + 0x1d2: 0x316d, 0x1d3: 0x347e, 0x1d4: 0x31db, 0x1d5: 0x34f1, 0x1d6: 0x31e0, 0x1d7: 0x34f6, + 0x1d8: 0x3186, 0x1d9: 0x3497, 0x1da: 0x319f, 0x1db: 0x34b5, + 0x1de: 0x305a, 0x1df: 0x3366, + 0x1e6: 0x4692, 0x1e7: 0x4723, 0x1e8: 0x46ba, 0x1e9: 0x474b, + 0x1ea: 0x395f, 0x1eb: 0x3aee, 0x1ec: 0x393c, 0x1ed: 0x3acb, 0x1ee: 0x46d8, 0x1ef: 0x4769, + 0x1f0: 0x3958, 0x1f1: 0x3ae7, 0x1f2: 0x3244, 0x1f3: 0x355f, + // Block 0x8, offset 0x200 + 0x200: 0x9932, 0x201: 0x9932, 0x202: 0x9932, 0x203: 0x9932, 0x204: 0x9932, 0x205: 0x8132, + 0x206: 0x9932, 0x207: 0x9932, 0x208: 0x9932, 0x209: 0x9932, 0x20a: 0x9932, 0x20b: 0x9932, + 0x20c: 0x9932, 0x20d: 0x8132, 0x20e: 0x8132, 0x20f: 0x9932, 0x210: 0x8132, 0x211: 0x9932, + 0x212: 0x8132, 0x213: 0x9932, 0x214: 0x9932, 0x215: 0x8133, 0x216: 0x812d, 0x217: 0x812d, + 0x218: 0x812d, 0x219: 0x812d, 0x21a: 0x8133, 0x21b: 0x992b, 0x21c: 0x812d, 0x21d: 0x812d, + 0x21e: 0x812d, 0x21f: 0x812d, 0x220: 0x812d, 0x221: 0x8129, 0x222: 0x8129, 0x223: 0x992d, + 0x224: 0x992d, 0x225: 0x992d, 0x226: 0x992d, 0x227: 0x9929, 0x228: 0x9929, 0x229: 0x812d, + 0x22a: 0x812d, 0x22b: 0x812d, 0x22c: 0x812d, 0x22d: 0x992d, 0x22e: 0x992d, 0x22f: 0x812d, + 0x230: 0x992d, 0x231: 0x992d, 0x232: 0x812d, 0x233: 0x812d, 0x234: 0x8101, 0x235: 0x8101, + 0x236: 0x8101, 0x237: 0x8101, 0x238: 0x9901, 0x239: 0x812d, 0x23a: 0x812d, 0x23b: 0x812d, + 0x23c: 0x812d, 0x23d: 0x8132, 0x23e: 0x8132, 0x23f: 0x8132, + // Block 0x9, offset 0x240 + 0x240: 0x49ae, 0x241: 0x49b3, 0x242: 0x9932, 0x243: 0x49b8, 0x244: 0x4a71, 0x245: 0x9936, + 0x246: 0x8132, 0x247: 0x812d, 0x248: 0x812d, 0x249: 0x812d, 0x24a: 0x8132, 0x24b: 0x8132, + 0x24c: 0x8132, 0x24d: 0x812d, 0x24e: 0x812d, 0x250: 0x8132, 0x251: 0x8132, + 0x252: 0x8132, 0x253: 0x812d, 0x254: 0x812d, 0x255: 0x812d, 0x256: 0x812d, 0x257: 0x8132, + 0x258: 0x8133, 0x259: 0x812d, 0x25a: 0x812d, 0x25b: 0x8132, 0x25c: 0x8134, 0x25d: 0x8135, + 0x25e: 0x8135, 0x25f: 0x8134, 0x260: 0x8135, 0x261: 0x8135, 0x262: 0x8134, 0x263: 0x8132, + 0x264: 0x8132, 0x265: 0x8132, 0x266: 0x8132, 0x267: 0x8132, 0x268: 0x8132, 0x269: 0x8132, + 0x26a: 0x8132, 0x26b: 0x8132, 0x26c: 0x8132, 0x26d: 0x8132, 0x26e: 0x8132, 0x26f: 0x8132, + 0x274: 0x0170, + 0x27a: 0x8100, + 0x27e: 0x0037, + // Block 0xa, offset 0x280 + 0x284: 0x8100, 0x285: 0x35a1, + 0x286: 0x35e9, 0x287: 0x00ce, 0x288: 0x3607, 0x289: 0x3613, 0x28a: 0x3625, + 0x28c: 0x3643, 0x28e: 0x3655, 0x28f: 0x3673, 0x290: 0x3e08, 0x291: 0xa000, + 0x295: 0xa000, 0x297: 0xa000, + 0x299: 0xa000, + 0x29f: 0xa000, 0x2a1: 0xa000, + 0x2a5: 0xa000, 0x2a9: 0xa000, + 0x2aa: 0x3637, 0x2ab: 0x3667, 0x2ac: 0x47fe, 0x2ad: 0x3697, 0x2ae: 0x4828, 0x2af: 0x36a9, + 0x2b0: 0x3e70, 0x2b1: 0xa000, 0x2b5: 0xa000, + 0x2b7: 0xa000, 0x2b9: 0xa000, + 0x2bf: 0xa000, + // Block 0xb, offset 0x2c0 + 0x2c0: 0x3721, 0x2c1: 0x372d, 0x2c3: 0x371b, + 0x2c6: 0xa000, 0x2c7: 0x3709, + 0x2cc: 0x375d, 0x2cd: 0x3745, 0x2ce: 0x376f, 0x2d0: 0xa000, + 0x2d3: 0xa000, 0x2d5: 0xa000, 0x2d6: 0xa000, 0x2d7: 0xa000, + 0x2d8: 0xa000, 0x2d9: 0x3751, 0x2da: 0xa000, + 0x2de: 0xa000, 0x2e3: 0xa000, + 0x2e7: 0xa000, + 0x2eb: 0xa000, 0x2ed: 0xa000, + 0x2f0: 0xa000, 0x2f3: 0xa000, 0x2f5: 0xa000, + 0x2f6: 0xa000, 0x2f7: 0xa000, 0x2f8: 0xa000, 0x2f9: 0x37d5, 0x2fa: 0xa000, + 0x2fe: 0xa000, + // Block 0xc, offset 0x300 + 0x301: 0x3733, 0x302: 0x37b7, + 0x310: 0x370f, 0x311: 0x3793, + 0x312: 0x3715, 0x313: 0x3799, 0x316: 0x3727, 0x317: 0x37ab, + 0x318: 0xa000, 0x319: 0xa000, 0x31a: 0x3829, 0x31b: 0x382f, 0x31c: 0x3739, 0x31d: 0x37bd, + 0x31e: 0x373f, 0x31f: 0x37c3, 0x322: 0x374b, 0x323: 0x37cf, + 0x324: 0x3757, 0x325: 0x37db, 0x326: 0x3763, 0x327: 0x37e7, 0x328: 0xa000, 0x329: 0xa000, + 0x32a: 0x3835, 0x32b: 0x383b, 0x32c: 0x378d, 0x32d: 0x3811, 0x32e: 0x3769, 0x32f: 0x37ed, + 0x330: 0x3775, 0x331: 0x37f9, 0x332: 0x377b, 0x333: 0x37ff, 0x334: 0x3781, 0x335: 0x3805, + 0x338: 0x3787, 0x339: 0x380b, + // Block 0xd, offset 0x340 + 0x351: 0x812d, + 0x352: 0x8132, 0x353: 0x8132, 0x354: 0x8132, 0x355: 0x8132, 0x356: 0x812d, 0x357: 0x8132, + 0x358: 0x8132, 0x359: 0x8132, 0x35a: 0x812e, 0x35b: 0x812d, 0x35c: 0x8132, 0x35d: 0x8132, + 0x35e: 0x8132, 0x35f: 0x8132, 0x360: 0x8132, 0x361: 0x8132, 0x362: 0x812d, 0x363: 0x812d, + 0x364: 0x812d, 0x365: 0x812d, 0x366: 0x812d, 0x367: 0x812d, 0x368: 0x8132, 0x369: 0x8132, + 0x36a: 0x812d, 0x36b: 0x8132, 0x36c: 0x8132, 0x36d: 0x812e, 0x36e: 0x8131, 0x36f: 0x8132, + 0x370: 0x8105, 0x371: 0x8106, 0x372: 0x8107, 0x373: 0x8108, 0x374: 0x8109, 0x375: 0x810a, + 0x376: 0x810b, 0x377: 0x810c, 0x378: 0x810d, 0x379: 0x810e, 0x37a: 0x810e, 0x37b: 0x810f, + 0x37c: 0x8110, 0x37d: 0x8111, 0x37f: 0x8112, + // Block 0xe, offset 0x380 + 0x388: 0xa000, 0x38a: 0xa000, 0x38b: 0x8116, + 0x38c: 0x8117, 0x38d: 0x8118, 0x38e: 0x8119, 0x38f: 0x811a, 0x390: 0x811b, 0x391: 0x811c, + 0x392: 0x811d, 0x393: 0x9932, 0x394: 0x9932, 0x395: 0x992d, 0x396: 0x812d, 0x397: 0x8132, + 0x398: 0x8132, 0x399: 0x8132, 0x39a: 0x8132, 0x39b: 0x8132, 0x39c: 0x812d, 0x39d: 0x8132, + 0x39e: 0x8132, 0x39f: 0x812d, + 0x3b0: 0x811e, + // Block 0xf, offset 0x3c0 + 0x3c5: 0xa000, + 0x3c6: 0x2d26, 0x3c7: 0xa000, 0x3c8: 0x2d2e, 0x3c9: 0xa000, 0x3ca: 0x2d36, 0x3cb: 0xa000, + 0x3cc: 0x2d3e, 0x3cd: 0xa000, 0x3ce: 0x2d46, 0x3d1: 0xa000, + 0x3d2: 0x2d4e, + 0x3f4: 0x8102, 0x3f5: 0x9900, + 0x3fa: 0xa000, 0x3fb: 0x2d56, + 0x3fc: 0xa000, 0x3fd: 0x2d5e, 0x3fe: 0xa000, 0x3ff: 0xa000, + // Block 0x10, offset 0x400 + 0x400: 0x2f97, 0x401: 0x32a3, 0x402: 0x2fa1, 0x403: 0x32ad, 0x404: 0x2fa6, 0x405: 0x32b2, + 0x406: 0x2fab, 0x407: 0x32b7, 0x408: 0x38cc, 0x409: 0x3a5b, 0x40a: 0x2fc4, 0x40b: 0x32d0, + 0x40c: 0x2fce, 0x40d: 0x32da, 0x40e: 0x2fdd, 0x40f: 0x32e9, 0x410: 0x2fd3, 0x411: 0x32df, + 0x412: 0x2fd8, 0x413: 0x32e4, 0x414: 0x38ef, 0x415: 0x3a7e, 0x416: 0x38f6, 0x417: 0x3a85, + 0x418: 0x3019, 0x419: 0x3325, 0x41a: 0x301e, 0x41b: 0x332a, 0x41c: 0x3904, 0x41d: 0x3a93, + 0x41e: 0x3023, 0x41f: 0x332f, 0x420: 0x3032, 0x421: 0x333e, 0x422: 0x3050, 0x423: 0x335c, + 0x424: 0x305f, 0x425: 0x336b, 0x426: 0x3055, 0x427: 0x3361, 0x428: 0x3064, 0x429: 0x3370, + 0x42a: 0x3069, 0x42b: 0x3375, 0x42c: 0x30af, 0x42d: 0x33bb, 0x42e: 0x390b, 0x42f: 0x3a9a, + 0x430: 0x30b9, 0x431: 0x33ca, 0x432: 0x30c3, 0x433: 0x33d4, 0x434: 0x30cd, 0x435: 0x33de, + 0x436: 0x46c4, 0x437: 0x4755, 0x438: 0x3912, 0x439: 0x3aa1, 0x43a: 0x30e6, 0x43b: 0x33f7, + 0x43c: 0x30e1, 0x43d: 0x33f2, 0x43e: 0x30eb, 0x43f: 0x33fc, + // Block 0x11, offset 0x440 + 0x440: 0x30f0, 0x441: 0x3401, 0x442: 0x30f5, 0x443: 0x3406, 0x444: 0x3109, 0x445: 0x341a, + 0x446: 0x3113, 0x447: 0x3424, 0x448: 0x3122, 0x449: 0x3433, 0x44a: 0x311d, 0x44b: 0x342e, + 0x44c: 0x3935, 0x44d: 0x3ac4, 0x44e: 0x3943, 0x44f: 0x3ad2, 0x450: 0x394a, 0x451: 0x3ad9, + 0x452: 0x3951, 0x453: 0x3ae0, 0x454: 0x314f, 0x455: 0x3460, 0x456: 0x3154, 0x457: 0x3465, + 0x458: 0x315e, 0x459: 0x346f, 0x45a: 0x46f1, 0x45b: 0x4782, 0x45c: 0x3997, 0x45d: 0x3b26, + 0x45e: 0x3177, 0x45f: 0x3488, 0x460: 0x3181, 0x461: 0x3492, 0x462: 0x4700, 0x463: 0x4791, + 0x464: 0x399e, 0x465: 0x3b2d, 0x466: 0x39a5, 0x467: 0x3b34, 0x468: 0x39ac, 0x469: 0x3b3b, + 0x46a: 0x3190, 0x46b: 0x34a1, 0x46c: 0x319a, 0x46d: 0x34b0, 0x46e: 0x31ae, 0x46f: 0x34c4, + 0x470: 0x31a9, 0x471: 0x34bf, 0x472: 0x31ea, 0x473: 0x3500, 0x474: 0x31f9, 0x475: 0x350f, + 0x476: 0x31f4, 0x477: 0x350a, 0x478: 0x39b3, 0x479: 0x3b42, 0x47a: 0x39ba, 0x47b: 0x3b49, + 0x47c: 0x31fe, 0x47d: 0x3514, 0x47e: 0x3203, 0x47f: 0x3519, + // Block 0x12, offset 0x480 + 0x480: 0x3208, 0x481: 0x351e, 0x482: 0x320d, 0x483: 0x3523, 0x484: 0x321c, 0x485: 0x3532, + 0x486: 0x3217, 0x487: 0x352d, 0x488: 0x3221, 0x489: 0x353c, 0x48a: 0x3226, 0x48b: 0x3541, + 0x48c: 0x322b, 0x48d: 0x3546, 0x48e: 0x3249, 0x48f: 0x3564, 0x490: 0x3262, 0x491: 0x3582, + 0x492: 0x3271, 0x493: 0x3591, 0x494: 0x3276, 0x495: 0x3596, 0x496: 0x337a, 0x497: 0x34a6, + 0x498: 0x3537, 0x499: 0x3573, 0x49b: 0x35d1, + 0x4a0: 0x46a1, 0x4a1: 0x4732, 0x4a2: 0x2f83, 0x4a3: 0x328f, + 0x4a4: 0x3878, 0x4a5: 0x3a07, 0x4a6: 0x3871, 0x4a7: 0x3a00, 0x4a8: 0x3886, 0x4a9: 0x3a15, + 0x4aa: 0x387f, 0x4ab: 0x3a0e, 0x4ac: 0x38be, 0x4ad: 0x3a4d, 0x4ae: 0x3894, 0x4af: 0x3a23, + 0x4b0: 0x388d, 0x4b1: 0x3a1c, 0x4b2: 0x38a2, 0x4b3: 0x3a31, 0x4b4: 0x389b, 0x4b5: 0x3a2a, + 0x4b6: 0x38c5, 0x4b7: 0x3a54, 0x4b8: 0x46b5, 0x4b9: 0x4746, 0x4ba: 0x3000, 0x4bb: 0x330c, + 0x4bc: 0x2fec, 0x4bd: 0x32f8, 0x4be: 0x38da, 0x4bf: 0x3a69, + // Block 0x13, offset 0x4c0 + 0x4c0: 0x38d3, 0x4c1: 0x3a62, 0x4c2: 0x38e8, 0x4c3: 0x3a77, 0x4c4: 0x38e1, 0x4c5: 0x3a70, + 0x4c6: 0x38fd, 0x4c7: 0x3a8c, 0x4c8: 0x3091, 0x4c9: 0x339d, 0x4ca: 0x30a5, 0x4cb: 0x33b1, + 0x4cc: 0x46e7, 0x4cd: 0x4778, 0x4ce: 0x3136, 0x4cf: 0x3447, 0x4d0: 0x3920, 0x4d1: 0x3aaf, + 0x4d2: 0x3919, 0x4d3: 0x3aa8, 0x4d4: 0x392e, 0x4d5: 0x3abd, 0x4d6: 0x3927, 0x4d7: 0x3ab6, + 0x4d8: 0x3989, 0x4d9: 0x3b18, 0x4da: 0x396d, 0x4db: 0x3afc, 0x4dc: 0x3966, 0x4dd: 0x3af5, + 0x4de: 0x397b, 0x4df: 0x3b0a, 0x4e0: 0x3974, 0x4e1: 0x3b03, 0x4e2: 0x3982, 0x4e3: 0x3b11, + 0x4e4: 0x31e5, 0x4e5: 0x34fb, 0x4e6: 0x31c7, 0x4e7: 0x34dd, 0x4e8: 0x39e4, 0x4e9: 0x3b73, + 0x4ea: 0x39dd, 0x4eb: 0x3b6c, 0x4ec: 0x39f2, 0x4ed: 0x3b81, 0x4ee: 0x39eb, 0x4ef: 0x3b7a, + 0x4f0: 0x39f9, 0x4f1: 0x3b88, 0x4f2: 0x3230, 0x4f3: 0x354b, 0x4f4: 0x3258, 0x4f5: 0x3578, + 0x4f6: 0x3253, 0x4f7: 0x356e, 0x4f8: 0x323f, 0x4f9: 0x355a, + // Block 0x14, offset 0x500 + 0x500: 0x4804, 0x501: 0x480a, 0x502: 0x491e, 0x503: 0x4936, 0x504: 0x4926, 0x505: 0x493e, + 0x506: 0x492e, 0x507: 0x4946, 0x508: 0x47aa, 0x509: 0x47b0, 0x50a: 0x488e, 0x50b: 0x48a6, + 0x50c: 0x4896, 0x50d: 0x48ae, 0x50e: 0x489e, 0x50f: 0x48b6, 0x510: 0x4816, 0x511: 0x481c, + 0x512: 0x3db8, 0x513: 0x3dc8, 0x514: 0x3dc0, 0x515: 0x3dd0, + 0x518: 0x47b6, 0x519: 0x47bc, 0x51a: 0x3ce8, 0x51b: 0x3cf8, 0x51c: 0x3cf0, 0x51d: 0x3d00, + 0x520: 0x482e, 0x521: 0x4834, 0x522: 0x494e, 0x523: 0x4966, + 0x524: 0x4956, 0x525: 0x496e, 0x526: 0x495e, 0x527: 0x4976, 0x528: 0x47c2, 0x529: 0x47c8, + 0x52a: 0x48be, 0x52b: 0x48d6, 0x52c: 0x48c6, 0x52d: 0x48de, 0x52e: 0x48ce, 0x52f: 0x48e6, + 0x530: 0x4846, 0x531: 0x484c, 0x532: 0x3e18, 0x533: 0x3e30, 0x534: 0x3e20, 0x535: 0x3e38, + 0x536: 0x3e28, 0x537: 0x3e40, 0x538: 0x47ce, 0x539: 0x47d4, 0x53a: 0x3d18, 0x53b: 0x3d30, + 0x53c: 0x3d20, 0x53d: 0x3d38, 0x53e: 0x3d28, 0x53f: 0x3d40, + // Block 0x15, offset 0x540 + 0x540: 0x4852, 0x541: 0x4858, 0x542: 0x3e48, 0x543: 0x3e58, 0x544: 0x3e50, 0x545: 0x3e60, + 0x548: 0x47da, 0x549: 0x47e0, 0x54a: 0x3d48, 0x54b: 0x3d58, + 0x54c: 0x3d50, 0x54d: 0x3d60, 0x550: 0x4864, 0x551: 0x486a, + 0x552: 0x3e80, 0x553: 0x3e98, 0x554: 0x3e88, 0x555: 0x3ea0, 0x556: 0x3e90, 0x557: 0x3ea8, + 0x559: 0x47e6, 0x55b: 0x3d68, 0x55d: 0x3d70, + 0x55f: 0x3d78, 0x560: 0x487c, 0x561: 0x4882, 0x562: 0x497e, 0x563: 0x4996, + 0x564: 0x4986, 0x565: 0x499e, 0x566: 0x498e, 0x567: 0x49a6, 0x568: 0x47ec, 0x569: 0x47f2, + 0x56a: 0x48ee, 0x56b: 0x4906, 0x56c: 0x48f6, 0x56d: 0x490e, 0x56e: 0x48fe, 0x56f: 0x4916, + 0x570: 0x47f8, 0x571: 0x431e, 0x572: 0x3691, 0x573: 0x4324, 0x574: 0x4822, 0x575: 0x432a, + 0x576: 0x36a3, 0x577: 0x4330, 0x578: 0x36c1, 0x579: 0x4336, 0x57a: 0x36d9, 0x57b: 0x433c, + 0x57c: 0x4870, 0x57d: 0x4342, + // Block 0x16, offset 0x580 + 0x580: 0x3da0, 0x581: 0x3da8, 0x582: 0x4184, 0x583: 0x41a2, 0x584: 0x418e, 0x585: 0x41ac, + 0x586: 0x4198, 0x587: 0x41b6, 0x588: 0x3cd8, 0x589: 0x3ce0, 0x58a: 0x40d0, 0x58b: 0x40ee, + 0x58c: 0x40da, 0x58d: 0x40f8, 0x58e: 0x40e4, 0x58f: 0x4102, 0x590: 0x3de8, 0x591: 0x3df0, + 0x592: 0x41c0, 0x593: 0x41de, 0x594: 0x41ca, 0x595: 0x41e8, 0x596: 0x41d4, 0x597: 0x41f2, + 0x598: 0x3d08, 0x599: 0x3d10, 0x59a: 0x410c, 0x59b: 0x412a, 0x59c: 0x4116, 0x59d: 0x4134, + 0x59e: 0x4120, 0x59f: 0x413e, 0x5a0: 0x3ec0, 0x5a1: 0x3ec8, 0x5a2: 0x41fc, 0x5a3: 0x421a, + 0x5a4: 0x4206, 0x5a5: 0x4224, 0x5a6: 0x4210, 0x5a7: 0x422e, 0x5a8: 0x3d80, 0x5a9: 0x3d88, + 0x5aa: 0x4148, 0x5ab: 0x4166, 0x5ac: 0x4152, 0x5ad: 0x4170, 0x5ae: 0x415c, 0x5af: 0x417a, + 0x5b0: 0x3685, 0x5b1: 0x367f, 0x5b2: 0x3d90, 0x5b3: 0x368b, 0x5b4: 0x3d98, + 0x5b6: 0x4810, 0x5b7: 0x3db0, 0x5b8: 0x35f5, 0x5b9: 0x35ef, 0x5ba: 0x35e3, 0x5bb: 0x42ee, + 0x5bc: 0x35fb, 0x5bd: 0x8100, 0x5be: 0x01d3, 0x5bf: 0xa100, + // Block 0x17, offset 0x5c0 + 0x5c0: 0x8100, 0x5c1: 0x35a7, 0x5c2: 0x3dd8, 0x5c3: 0x369d, 0x5c4: 0x3de0, + 0x5c6: 0x483a, 0x5c7: 0x3df8, 0x5c8: 0x3601, 0x5c9: 0x42f4, 0x5ca: 0x360d, 0x5cb: 0x42fa, + 0x5cc: 0x3619, 0x5cd: 0x3b8f, 0x5ce: 0x3b96, 0x5cf: 0x3b9d, 0x5d0: 0x36b5, 0x5d1: 0x36af, + 0x5d2: 0x3e00, 0x5d3: 0x44e4, 0x5d6: 0x36bb, 0x5d7: 0x3e10, + 0x5d8: 0x3631, 0x5d9: 0x362b, 0x5da: 0x361f, 0x5db: 0x4300, 0x5dd: 0x3ba4, + 0x5de: 0x3bab, 0x5df: 0x3bb2, 0x5e0: 0x36eb, 0x5e1: 0x36e5, 0x5e2: 0x3e68, 0x5e3: 0x44ec, + 0x5e4: 0x36cd, 0x5e5: 0x36d3, 0x5e6: 0x36f1, 0x5e7: 0x3e78, 0x5e8: 0x3661, 0x5e9: 0x365b, + 0x5ea: 0x364f, 0x5eb: 0x430c, 0x5ec: 0x3649, 0x5ed: 0x359b, 0x5ee: 0x42e8, 0x5ef: 0x0081, + 0x5f2: 0x3eb0, 0x5f3: 0x36f7, 0x5f4: 0x3eb8, + 0x5f6: 0x4888, 0x5f7: 0x3ed0, 0x5f8: 0x363d, 0x5f9: 0x4306, 0x5fa: 0x366d, 0x5fb: 0x4318, + 0x5fc: 0x3679, 0x5fd: 0x4256, 0x5fe: 0xa100, + // Block 0x18, offset 0x600 + 0x601: 0x3c06, 0x603: 0xa000, 0x604: 0x3c0d, 0x605: 0xa000, + 0x607: 0x3c14, 0x608: 0xa000, 0x609: 0x3c1b, + 0x60d: 0xa000, + 0x620: 0x2f65, 0x621: 0xa000, 0x622: 0x3c29, + 0x624: 0xa000, 0x625: 0xa000, + 0x62d: 0x3c22, 0x62e: 0x2f60, 0x62f: 0x2f6a, + 0x630: 0x3c30, 0x631: 0x3c37, 0x632: 0xa000, 0x633: 0xa000, 0x634: 0x3c3e, 0x635: 0x3c45, + 0x636: 0xa000, 0x637: 0xa000, 0x638: 0x3c4c, 0x639: 0x3c53, 0x63a: 0xa000, 0x63b: 0xa000, + 0x63c: 0xa000, 0x63d: 0xa000, + // Block 0x19, offset 0x640 + 0x640: 0x3c5a, 0x641: 0x3c61, 0x642: 0xa000, 0x643: 0xa000, 0x644: 0x3c76, 0x645: 0x3c7d, + 0x646: 0xa000, 0x647: 0xa000, 0x648: 0x3c84, 0x649: 0x3c8b, + 0x651: 0xa000, + 0x652: 0xa000, + 0x662: 0xa000, + 0x668: 0xa000, 0x669: 0xa000, + 0x66b: 0xa000, 0x66c: 0x3ca0, 0x66d: 0x3ca7, 0x66e: 0x3cae, 0x66f: 0x3cb5, + 0x672: 0xa000, 0x673: 0xa000, 0x674: 0xa000, 0x675: 0xa000, + // Block 0x1a, offset 0x680 + 0x686: 0xa000, 0x68b: 0xa000, + 0x68c: 0x3f08, 0x68d: 0xa000, 0x68e: 0x3f10, 0x68f: 0xa000, 0x690: 0x3f18, 0x691: 0xa000, + 0x692: 0x3f20, 0x693: 0xa000, 0x694: 0x3f28, 0x695: 0xa000, 0x696: 0x3f30, 0x697: 0xa000, + 0x698: 0x3f38, 0x699: 0xa000, 0x69a: 0x3f40, 0x69b: 0xa000, 0x69c: 0x3f48, 0x69d: 0xa000, + 0x69e: 0x3f50, 0x69f: 0xa000, 0x6a0: 0x3f58, 0x6a1: 0xa000, 0x6a2: 0x3f60, + 0x6a4: 0xa000, 0x6a5: 0x3f68, 0x6a6: 0xa000, 0x6a7: 0x3f70, 0x6a8: 0xa000, 0x6a9: 0x3f78, + 0x6af: 0xa000, + 0x6b0: 0x3f80, 0x6b1: 0x3f88, 0x6b2: 0xa000, 0x6b3: 0x3f90, 0x6b4: 0x3f98, 0x6b5: 0xa000, + 0x6b6: 0x3fa0, 0x6b7: 0x3fa8, 0x6b8: 0xa000, 0x6b9: 0x3fb0, 0x6ba: 0x3fb8, 0x6bb: 0xa000, + 0x6bc: 0x3fc0, 0x6bd: 0x3fc8, + // Block 0x1b, offset 0x6c0 + 0x6d4: 0x3f00, + 0x6d9: 0x9903, 0x6da: 0x9903, 0x6db: 0x8100, 0x6dc: 0x8100, 0x6dd: 0xa000, + 0x6de: 0x3fd0, + 0x6e6: 0xa000, + 0x6eb: 0xa000, 0x6ec: 0x3fe0, 0x6ed: 0xa000, 0x6ee: 0x3fe8, 0x6ef: 0xa000, + 0x6f0: 0x3ff0, 0x6f1: 0xa000, 0x6f2: 0x3ff8, 0x6f3: 0xa000, 0x6f4: 0x4000, 0x6f5: 0xa000, + 0x6f6: 0x4008, 0x6f7: 0xa000, 0x6f8: 0x4010, 0x6f9: 0xa000, 0x6fa: 0x4018, 0x6fb: 0xa000, + 0x6fc: 0x4020, 0x6fd: 0xa000, 0x6fe: 0x4028, 0x6ff: 0xa000, + // Block 0x1c, offset 0x700 + 0x700: 0x4030, 0x701: 0xa000, 0x702: 0x4038, 0x704: 0xa000, 0x705: 0x4040, + 0x706: 0xa000, 0x707: 0x4048, 0x708: 0xa000, 0x709: 0x4050, + 0x70f: 0xa000, 0x710: 0x4058, 0x711: 0x4060, + 0x712: 0xa000, 0x713: 0x4068, 0x714: 0x4070, 0x715: 0xa000, 0x716: 0x4078, 0x717: 0x4080, + 0x718: 0xa000, 0x719: 0x4088, 0x71a: 0x4090, 0x71b: 0xa000, 0x71c: 0x4098, 0x71d: 0x40a0, + 0x72f: 0xa000, + 0x730: 0xa000, 0x731: 0xa000, 0x732: 0xa000, 0x734: 0x3fd8, + 0x737: 0x40a8, 0x738: 0x40b0, 0x739: 0x40b8, 0x73a: 0x40c0, + 0x73d: 0xa000, 0x73e: 0x40c8, + // Block 0x1d, offset 0x740 + 0x740: 0x1377, 0x741: 0x0cfb, 0x742: 0x13d3, 0x743: 0x139f, 0x744: 0x0e57, 0x745: 0x06eb, + 0x746: 0x08df, 0x747: 0x162b, 0x748: 0x162b, 0x749: 0x0a0b, 0x74a: 0x145f, 0x74b: 0x0943, + 0x74c: 0x0a07, 0x74d: 0x0bef, 0x74e: 0x0fcf, 0x74f: 0x115f, 0x750: 0x1297, 0x751: 0x12d3, + 0x752: 0x1307, 0x753: 0x141b, 0x754: 0x0d73, 0x755: 0x0dff, 0x756: 0x0eab, 0x757: 0x0f43, + 0x758: 0x125f, 0x759: 0x1447, 0x75a: 0x1573, 0x75b: 0x070f, 0x75c: 0x08b3, 0x75d: 0x0d87, + 0x75e: 0x0ecf, 0x75f: 0x1293, 0x760: 0x15c3, 0x761: 0x0ab3, 0x762: 0x0e77, 0x763: 0x1283, + 0x764: 0x1317, 0x765: 0x0c23, 0x766: 0x11bb, 0x767: 0x12df, 0x768: 0x0b1f, 0x769: 0x0d0f, + 0x76a: 0x0e17, 0x76b: 0x0f1b, 0x76c: 0x1427, 0x76d: 0x074f, 0x76e: 0x07e7, 0x76f: 0x0853, + 0x770: 0x0c8b, 0x771: 0x0d7f, 0x772: 0x0ecb, 0x773: 0x0fef, 0x774: 0x1177, 0x775: 0x128b, + 0x776: 0x12a3, 0x777: 0x13c7, 0x778: 0x14ef, 0x779: 0x15a3, 0x77a: 0x15bf, 0x77b: 0x102b, + 0x77c: 0x106b, 0x77d: 0x1123, 0x77e: 0x1243, 0x77f: 0x147b, + // Block 0x1e, offset 0x780 + 0x780: 0x15cb, 0x781: 0x134b, 0x782: 0x09c7, 0x783: 0x0b3b, 0x784: 0x10db, 0x785: 0x119b, + 0x786: 0x0eff, 0x787: 0x1033, 0x788: 0x1397, 0x789: 0x14e7, 0x78a: 0x09c3, 0x78b: 0x0a8f, + 0x78c: 0x0d77, 0x78d: 0x0e2b, 0x78e: 0x0e5f, 0x78f: 0x1113, 0x790: 0x113b, 0x791: 0x14a7, + 0x792: 0x084f, 0x793: 0x11a7, 0x794: 0x07f3, 0x795: 0x07ef, 0x796: 0x1097, 0x797: 0x1127, + 0x798: 0x125b, 0x799: 0x14af, 0x79a: 0x1367, 0x79b: 0x0c27, 0x79c: 0x0d73, 0x79d: 0x1357, + 0x79e: 0x06f7, 0x79f: 0x0a63, 0x7a0: 0x0b93, 0x7a1: 0x0f2f, 0x7a2: 0x0faf, 0x7a3: 0x0873, + 0x7a4: 0x103b, 0x7a5: 0x075f, 0x7a6: 0x0b77, 0x7a7: 0x06d7, 0x7a8: 0x0deb, 0x7a9: 0x0ca3, + 0x7aa: 0x110f, 0x7ab: 0x08c7, 0x7ac: 0x09b3, 0x7ad: 0x0ffb, 0x7ae: 0x1263, 0x7af: 0x133b, + 0x7b0: 0x0db7, 0x7b1: 0x13f7, 0x7b2: 0x0de3, 0x7b3: 0x0c37, 0x7b4: 0x121b, 0x7b5: 0x0c57, + 0x7b6: 0x0fab, 0x7b7: 0x072b, 0x7b8: 0x07a7, 0x7b9: 0x07eb, 0x7ba: 0x0d53, 0x7bb: 0x10fb, + 0x7bc: 0x11f3, 0x7bd: 0x1347, 0x7be: 0x145b, 0x7bf: 0x085b, + // Block 0x1f, offset 0x7c0 + 0x7c0: 0x090f, 0x7c1: 0x0a17, 0x7c2: 0x0b2f, 0x7c3: 0x0cbf, 0x7c4: 0x0e7b, 0x7c5: 0x103f, + 0x7c6: 0x1497, 0x7c7: 0x157b, 0x7c8: 0x15cf, 0x7c9: 0x15e7, 0x7ca: 0x0837, 0x7cb: 0x0cf3, + 0x7cc: 0x0da3, 0x7cd: 0x13eb, 0x7ce: 0x0afb, 0x7cf: 0x0bd7, 0x7d0: 0x0bf3, 0x7d1: 0x0c83, + 0x7d2: 0x0e6b, 0x7d3: 0x0eb7, 0x7d4: 0x0f67, 0x7d5: 0x108b, 0x7d6: 0x112f, 0x7d7: 0x1193, + 0x7d8: 0x13db, 0x7d9: 0x126b, 0x7da: 0x1403, 0x7db: 0x147f, 0x7dc: 0x080f, 0x7dd: 0x083b, + 0x7de: 0x0923, 0x7df: 0x0ea7, 0x7e0: 0x12f3, 0x7e1: 0x133b, 0x7e2: 0x0b1b, 0x7e3: 0x0b8b, + 0x7e4: 0x0c4f, 0x7e5: 0x0daf, 0x7e6: 0x10d7, 0x7e7: 0x0f23, 0x7e8: 0x073b, 0x7e9: 0x097f, + 0x7ea: 0x0a63, 0x7eb: 0x0ac7, 0x7ec: 0x0b97, 0x7ed: 0x0f3f, 0x7ee: 0x0f5b, 0x7ef: 0x116b, + 0x7f0: 0x118b, 0x7f1: 0x1463, 0x7f2: 0x14e3, 0x7f3: 0x14f3, 0x7f4: 0x152f, 0x7f5: 0x0753, + 0x7f6: 0x107f, 0x7f7: 0x144f, 0x7f8: 0x14cb, 0x7f9: 0x0baf, 0x7fa: 0x0717, 0x7fb: 0x0777, + 0x7fc: 0x0a67, 0x7fd: 0x0a87, 0x7fe: 0x0caf, 0x7ff: 0x0d73, + // Block 0x20, offset 0x800 + 0x800: 0x0ec3, 0x801: 0x0fcb, 0x802: 0x1277, 0x803: 0x1417, 0x804: 0x1623, 0x805: 0x0ce3, + 0x806: 0x14a3, 0x807: 0x0833, 0x808: 0x0d2f, 0x809: 0x0d3b, 0x80a: 0x0e0f, 0x80b: 0x0e47, + 0x80c: 0x0f4b, 0x80d: 0x0fa7, 0x80e: 0x1027, 0x80f: 0x110b, 0x810: 0x153b, 0x811: 0x07af, + 0x812: 0x0c03, 0x813: 0x14b3, 0x814: 0x0767, 0x815: 0x0aab, 0x816: 0x0e2f, 0x817: 0x13df, + 0x818: 0x0b67, 0x819: 0x0bb7, 0x81a: 0x0d43, 0x81b: 0x0f2f, 0x81c: 0x14bb, 0x81d: 0x0817, + 0x81e: 0x08ff, 0x81f: 0x0a97, 0x820: 0x0cd3, 0x821: 0x0d1f, 0x822: 0x0d5f, 0x823: 0x0df3, + 0x824: 0x0f47, 0x825: 0x0fbb, 0x826: 0x1157, 0x827: 0x12f7, 0x828: 0x1303, 0x829: 0x1457, + 0x82a: 0x14d7, 0x82b: 0x0883, 0x82c: 0x0e4b, 0x82d: 0x0903, 0x82e: 0x0ec7, 0x82f: 0x0f6b, + 0x830: 0x1287, 0x831: 0x14bf, 0x832: 0x15ab, 0x833: 0x15d3, 0x834: 0x0d37, 0x835: 0x0e27, + 0x836: 0x11c3, 0x837: 0x10b7, 0x838: 0x10c3, 0x839: 0x10e7, 0x83a: 0x0f17, 0x83b: 0x0e9f, + 0x83c: 0x1363, 0x83d: 0x0733, 0x83e: 0x122b, 0x83f: 0x081b, + // Block 0x21, offset 0x840 + 0x840: 0x080b, 0x841: 0x0b0b, 0x842: 0x0c2b, 0x843: 0x10f3, 0x844: 0x0a53, 0x845: 0x0e03, + 0x846: 0x0cef, 0x847: 0x13e7, 0x848: 0x12e7, 0x849: 0x14ab, 0x84a: 0x1323, 0x84b: 0x0b27, + 0x84c: 0x0787, 0x84d: 0x095b, 0x850: 0x09af, + 0x852: 0x0cdf, 0x855: 0x07f7, 0x856: 0x0f1f, 0x857: 0x0fe3, + 0x858: 0x1047, 0x859: 0x1063, 0x85a: 0x1067, 0x85b: 0x107b, 0x85c: 0x14fb, 0x85d: 0x10eb, + 0x85e: 0x116f, 0x860: 0x128f, 0x862: 0x1353, + 0x865: 0x1407, 0x866: 0x1433, + 0x86a: 0x154f, 0x86b: 0x1553, 0x86c: 0x1557, 0x86d: 0x15bb, 0x86e: 0x142b, 0x86f: 0x14c7, + 0x870: 0x0757, 0x871: 0x077b, 0x872: 0x078f, 0x873: 0x084b, 0x874: 0x0857, 0x875: 0x0897, + 0x876: 0x094b, 0x877: 0x0967, 0x878: 0x096f, 0x879: 0x09ab, 0x87a: 0x09b7, 0x87b: 0x0a93, + 0x87c: 0x0a9b, 0x87d: 0x0ba3, 0x87e: 0x0bcb, 0x87f: 0x0bd3, + // Block 0x22, offset 0x880 + 0x880: 0x0beb, 0x881: 0x0c97, 0x882: 0x0cc7, 0x883: 0x0ce7, 0x884: 0x0d57, 0x885: 0x0e1b, + 0x886: 0x0e37, 0x887: 0x0e67, 0x888: 0x0ebb, 0x889: 0x0edb, 0x88a: 0x0f4f, 0x88b: 0x102f, + 0x88c: 0x104b, 0x88d: 0x1053, 0x88e: 0x104f, 0x88f: 0x1057, 0x890: 0x105b, 0x891: 0x105f, + 0x892: 0x1073, 0x893: 0x1077, 0x894: 0x109b, 0x895: 0x10af, 0x896: 0x10cb, 0x897: 0x112f, + 0x898: 0x1137, 0x899: 0x113f, 0x89a: 0x1153, 0x89b: 0x117b, 0x89c: 0x11cb, 0x89d: 0x11ff, + 0x89e: 0x11ff, 0x89f: 0x1267, 0x8a0: 0x130f, 0x8a1: 0x1327, 0x8a2: 0x135b, 0x8a3: 0x135f, + 0x8a4: 0x13a3, 0x8a5: 0x13a7, 0x8a6: 0x13ff, 0x8a7: 0x1407, 0x8a8: 0x14db, 0x8a9: 0x151f, + 0x8aa: 0x1537, 0x8ab: 0x0b9b, 0x8ac: 0x171e, 0x8ad: 0x11e3, + 0x8b0: 0x06df, 0x8b1: 0x07e3, 0x8b2: 0x07a3, 0x8b3: 0x074b, 0x8b4: 0x078b, 0x8b5: 0x07b7, + 0x8b6: 0x0847, 0x8b7: 0x0863, 0x8b8: 0x094b, 0x8b9: 0x0937, 0x8ba: 0x0947, 0x8bb: 0x0963, + 0x8bc: 0x09af, 0x8bd: 0x09bf, 0x8be: 0x0a03, 0x8bf: 0x0a0f, + // Block 0x23, offset 0x8c0 + 0x8c0: 0x0a2b, 0x8c1: 0x0a3b, 0x8c2: 0x0b23, 0x8c3: 0x0b2b, 0x8c4: 0x0b5b, 0x8c5: 0x0b7b, + 0x8c6: 0x0bab, 0x8c7: 0x0bc3, 0x8c8: 0x0bb3, 0x8c9: 0x0bd3, 0x8ca: 0x0bc7, 0x8cb: 0x0beb, + 0x8cc: 0x0c07, 0x8cd: 0x0c5f, 0x8ce: 0x0c6b, 0x8cf: 0x0c73, 0x8d0: 0x0c9b, 0x8d1: 0x0cdf, + 0x8d2: 0x0d0f, 0x8d3: 0x0d13, 0x8d4: 0x0d27, 0x8d5: 0x0da7, 0x8d6: 0x0db7, 0x8d7: 0x0e0f, + 0x8d8: 0x0e5b, 0x8d9: 0x0e53, 0x8da: 0x0e67, 0x8db: 0x0e83, 0x8dc: 0x0ebb, 0x8dd: 0x1013, + 0x8de: 0x0edf, 0x8df: 0x0f13, 0x8e0: 0x0f1f, 0x8e1: 0x0f5f, 0x8e2: 0x0f7b, 0x8e3: 0x0f9f, + 0x8e4: 0x0fc3, 0x8e5: 0x0fc7, 0x8e6: 0x0fe3, 0x8e7: 0x0fe7, 0x8e8: 0x0ff7, 0x8e9: 0x100b, + 0x8ea: 0x1007, 0x8eb: 0x1037, 0x8ec: 0x10b3, 0x8ed: 0x10cb, 0x8ee: 0x10e3, 0x8ef: 0x111b, + 0x8f0: 0x112f, 0x8f1: 0x114b, 0x8f2: 0x117b, 0x8f3: 0x122f, 0x8f4: 0x1257, 0x8f5: 0x12cb, + 0x8f6: 0x1313, 0x8f7: 0x131f, 0x8f8: 0x1327, 0x8f9: 0x133f, 0x8fa: 0x1353, 0x8fb: 0x1343, + 0x8fc: 0x135b, 0x8fd: 0x1357, 0x8fe: 0x134f, 0x8ff: 0x135f, + // Block 0x24, offset 0x900 + 0x900: 0x136b, 0x901: 0x13a7, 0x902: 0x13e3, 0x903: 0x1413, 0x904: 0x144b, 0x905: 0x146b, + 0x906: 0x14b7, 0x907: 0x14db, 0x908: 0x14fb, 0x909: 0x150f, 0x90a: 0x151f, 0x90b: 0x152b, + 0x90c: 0x1537, 0x90d: 0x158b, 0x90e: 0x162b, 0x90f: 0x16b5, 0x910: 0x16b0, 0x911: 0x16e2, + 0x912: 0x0607, 0x913: 0x062f, 0x914: 0x0633, 0x915: 0x1764, 0x916: 0x1791, 0x917: 0x1809, + 0x918: 0x1617, 0x919: 0x1627, + // Block 0x25, offset 0x940 + 0x940: 0x06fb, 0x941: 0x06f3, 0x942: 0x0703, 0x943: 0x1647, 0x944: 0x0747, 0x945: 0x0757, + 0x946: 0x075b, 0x947: 0x0763, 0x948: 0x076b, 0x949: 0x076f, 0x94a: 0x077b, 0x94b: 0x0773, + 0x94c: 0x05b3, 0x94d: 0x165b, 0x94e: 0x078f, 0x94f: 0x0793, 0x950: 0x0797, 0x951: 0x07b3, + 0x952: 0x164c, 0x953: 0x05b7, 0x954: 0x079f, 0x955: 0x07bf, 0x956: 0x1656, 0x957: 0x07cf, + 0x958: 0x07d7, 0x959: 0x0737, 0x95a: 0x07df, 0x95b: 0x07e3, 0x95c: 0x1831, 0x95d: 0x07ff, + 0x95e: 0x0807, 0x95f: 0x05bf, 0x960: 0x081f, 0x961: 0x0823, 0x962: 0x082b, 0x963: 0x082f, + 0x964: 0x05c3, 0x965: 0x0847, 0x966: 0x084b, 0x967: 0x0857, 0x968: 0x0863, 0x969: 0x0867, + 0x96a: 0x086b, 0x96b: 0x0873, 0x96c: 0x0893, 0x96d: 0x0897, 0x96e: 0x089f, 0x96f: 0x08af, + 0x970: 0x08b7, 0x971: 0x08bb, 0x972: 0x08bb, 0x973: 0x08bb, 0x974: 0x166a, 0x975: 0x0e93, + 0x976: 0x08cf, 0x977: 0x08d7, 0x978: 0x166f, 0x979: 0x08e3, 0x97a: 0x08eb, 0x97b: 0x08f3, + 0x97c: 0x091b, 0x97d: 0x0907, 0x97e: 0x0913, 0x97f: 0x0917, + // Block 0x26, offset 0x980 + 0x980: 0x091f, 0x981: 0x0927, 0x982: 0x092b, 0x983: 0x0933, 0x984: 0x093b, 0x985: 0x093f, + 0x986: 0x093f, 0x987: 0x0947, 0x988: 0x094f, 0x989: 0x0953, 0x98a: 0x095f, 0x98b: 0x0983, + 0x98c: 0x0967, 0x98d: 0x0987, 0x98e: 0x096b, 0x98f: 0x0973, 0x990: 0x080b, 0x991: 0x09cf, + 0x992: 0x0997, 0x993: 0x099b, 0x994: 0x099f, 0x995: 0x0993, 0x996: 0x09a7, 0x997: 0x09a3, + 0x998: 0x09bb, 0x999: 0x1674, 0x99a: 0x09d7, 0x99b: 0x09db, 0x99c: 0x09e3, 0x99d: 0x09ef, + 0x99e: 0x09f7, 0x99f: 0x0a13, 0x9a0: 0x1679, 0x9a1: 0x167e, 0x9a2: 0x0a1f, 0x9a3: 0x0a23, + 0x9a4: 0x0a27, 0x9a5: 0x0a1b, 0x9a6: 0x0a2f, 0x9a7: 0x05c7, 0x9a8: 0x05cb, 0x9a9: 0x0a37, + 0x9aa: 0x0a3f, 0x9ab: 0x0a3f, 0x9ac: 0x1683, 0x9ad: 0x0a5b, 0x9ae: 0x0a5f, 0x9af: 0x0a63, + 0x9b0: 0x0a6b, 0x9b1: 0x1688, 0x9b2: 0x0a73, 0x9b3: 0x0a77, 0x9b4: 0x0b4f, 0x9b5: 0x0a7f, + 0x9b6: 0x05cf, 0x9b7: 0x0a8b, 0x9b8: 0x0a9b, 0x9b9: 0x0aa7, 0x9ba: 0x0aa3, 0x9bb: 0x1692, + 0x9bc: 0x0aaf, 0x9bd: 0x1697, 0x9be: 0x0abb, 0x9bf: 0x0ab7, + // Block 0x27, offset 0x9c0 + 0x9c0: 0x0abf, 0x9c1: 0x0acf, 0x9c2: 0x0ad3, 0x9c3: 0x05d3, 0x9c4: 0x0ae3, 0x9c5: 0x0aeb, + 0x9c6: 0x0aef, 0x9c7: 0x0af3, 0x9c8: 0x05d7, 0x9c9: 0x169c, 0x9ca: 0x05db, 0x9cb: 0x0b0f, + 0x9cc: 0x0b13, 0x9cd: 0x0b17, 0x9ce: 0x0b1f, 0x9cf: 0x1863, 0x9d0: 0x0b37, 0x9d1: 0x16a6, + 0x9d2: 0x16a6, 0x9d3: 0x11d7, 0x9d4: 0x0b47, 0x9d5: 0x0b47, 0x9d6: 0x05df, 0x9d7: 0x16c9, + 0x9d8: 0x179b, 0x9d9: 0x0b57, 0x9da: 0x0b5f, 0x9db: 0x05e3, 0x9dc: 0x0b73, 0x9dd: 0x0b83, + 0x9de: 0x0b87, 0x9df: 0x0b8f, 0x9e0: 0x0b9f, 0x9e1: 0x05eb, 0x9e2: 0x05e7, 0x9e3: 0x0ba3, + 0x9e4: 0x16ab, 0x9e5: 0x0ba7, 0x9e6: 0x0bbb, 0x9e7: 0x0bbf, 0x9e8: 0x0bc3, 0x9e9: 0x0bbf, + 0x9ea: 0x0bcf, 0x9eb: 0x0bd3, 0x9ec: 0x0be3, 0x9ed: 0x0bdb, 0x9ee: 0x0bdf, 0x9ef: 0x0be7, + 0x9f0: 0x0beb, 0x9f1: 0x0bef, 0x9f2: 0x0bfb, 0x9f3: 0x0bff, 0x9f4: 0x0c17, 0x9f5: 0x0c1f, + 0x9f6: 0x0c2f, 0x9f7: 0x0c43, 0x9f8: 0x16ba, 0x9f9: 0x0c3f, 0x9fa: 0x0c33, 0x9fb: 0x0c4b, + 0x9fc: 0x0c53, 0x9fd: 0x0c67, 0x9fe: 0x16bf, 0x9ff: 0x0c6f, + // Block 0x28, offset 0xa00 + 0xa00: 0x0c63, 0xa01: 0x0c5b, 0xa02: 0x05ef, 0xa03: 0x0c77, 0xa04: 0x0c7f, 0xa05: 0x0c87, + 0xa06: 0x0c7b, 0xa07: 0x05f3, 0xa08: 0x0c97, 0xa09: 0x0c9f, 0xa0a: 0x16c4, 0xa0b: 0x0ccb, + 0xa0c: 0x0cff, 0xa0d: 0x0cdb, 0xa0e: 0x05ff, 0xa0f: 0x0ce7, 0xa10: 0x05fb, 0xa11: 0x05f7, + 0xa12: 0x07c3, 0xa13: 0x07c7, 0xa14: 0x0d03, 0xa15: 0x0ceb, 0xa16: 0x11ab, 0xa17: 0x0663, + 0xa18: 0x0d0f, 0xa19: 0x0d13, 0xa1a: 0x0d17, 0xa1b: 0x0d2b, 0xa1c: 0x0d23, 0xa1d: 0x16dd, + 0xa1e: 0x0603, 0xa1f: 0x0d3f, 0xa20: 0x0d33, 0xa21: 0x0d4f, 0xa22: 0x0d57, 0xa23: 0x16e7, + 0xa24: 0x0d5b, 0xa25: 0x0d47, 0xa26: 0x0d63, 0xa27: 0x0607, 0xa28: 0x0d67, 0xa29: 0x0d6b, + 0xa2a: 0x0d6f, 0xa2b: 0x0d7b, 0xa2c: 0x16ec, 0xa2d: 0x0d83, 0xa2e: 0x060b, 0xa2f: 0x0d8f, + 0xa30: 0x16f1, 0xa31: 0x0d93, 0xa32: 0x060f, 0xa33: 0x0d9f, 0xa34: 0x0dab, 0xa35: 0x0db7, + 0xa36: 0x0dbb, 0xa37: 0x16f6, 0xa38: 0x168d, 0xa39: 0x16fb, 0xa3a: 0x0ddb, 0xa3b: 0x1700, + 0xa3c: 0x0de7, 0xa3d: 0x0def, 0xa3e: 0x0ddf, 0xa3f: 0x0dfb, + // Block 0x29, offset 0xa40 + 0xa40: 0x0e0b, 0xa41: 0x0e1b, 0xa42: 0x0e0f, 0xa43: 0x0e13, 0xa44: 0x0e1f, 0xa45: 0x0e23, + 0xa46: 0x1705, 0xa47: 0x0e07, 0xa48: 0x0e3b, 0xa49: 0x0e3f, 0xa4a: 0x0613, 0xa4b: 0x0e53, + 0xa4c: 0x0e4f, 0xa4d: 0x170a, 0xa4e: 0x0e33, 0xa4f: 0x0e6f, 0xa50: 0x170f, 0xa51: 0x1714, + 0xa52: 0x0e73, 0xa53: 0x0e87, 0xa54: 0x0e83, 0xa55: 0x0e7f, 0xa56: 0x0617, 0xa57: 0x0e8b, + 0xa58: 0x0e9b, 0xa59: 0x0e97, 0xa5a: 0x0ea3, 0xa5b: 0x1651, 0xa5c: 0x0eb3, 0xa5d: 0x1719, + 0xa5e: 0x0ebf, 0xa5f: 0x1723, 0xa60: 0x0ed3, 0xa61: 0x0edf, 0xa62: 0x0ef3, 0xa63: 0x1728, + 0xa64: 0x0f07, 0xa65: 0x0f0b, 0xa66: 0x172d, 0xa67: 0x1732, 0xa68: 0x0f27, 0xa69: 0x0f37, + 0xa6a: 0x061b, 0xa6b: 0x0f3b, 0xa6c: 0x061f, 0xa6d: 0x061f, 0xa6e: 0x0f53, 0xa6f: 0x0f57, + 0xa70: 0x0f5f, 0xa71: 0x0f63, 0xa72: 0x0f6f, 0xa73: 0x0623, 0xa74: 0x0f87, 0xa75: 0x1737, + 0xa76: 0x0fa3, 0xa77: 0x173c, 0xa78: 0x0faf, 0xa79: 0x16a1, 0xa7a: 0x0fbf, 0xa7b: 0x1741, + 0xa7c: 0x1746, 0xa7d: 0x174b, 0xa7e: 0x0627, 0xa7f: 0x062b, + // Block 0x2a, offset 0xa80 + 0xa80: 0x0ff7, 0xa81: 0x1755, 0xa82: 0x1750, 0xa83: 0x175a, 0xa84: 0x175f, 0xa85: 0x0fff, + 0xa86: 0x1003, 0xa87: 0x1003, 0xa88: 0x100b, 0xa89: 0x0633, 0xa8a: 0x100f, 0xa8b: 0x0637, + 0xa8c: 0x063b, 0xa8d: 0x1769, 0xa8e: 0x1023, 0xa8f: 0x102b, 0xa90: 0x1037, 0xa91: 0x063f, + 0xa92: 0x176e, 0xa93: 0x105b, 0xa94: 0x1773, 0xa95: 0x1778, 0xa96: 0x107b, 0xa97: 0x1093, + 0xa98: 0x0643, 0xa99: 0x109b, 0xa9a: 0x109f, 0xa9b: 0x10a3, 0xa9c: 0x177d, 0xa9d: 0x1782, + 0xa9e: 0x1782, 0xa9f: 0x10bb, 0xaa0: 0x0647, 0xaa1: 0x1787, 0xaa2: 0x10cf, 0xaa3: 0x10d3, + 0xaa4: 0x064b, 0xaa5: 0x178c, 0xaa6: 0x10ef, 0xaa7: 0x064f, 0xaa8: 0x10ff, 0xaa9: 0x10f7, + 0xaaa: 0x1107, 0xaab: 0x1796, 0xaac: 0x111f, 0xaad: 0x0653, 0xaae: 0x112b, 0xaaf: 0x1133, + 0xab0: 0x1143, 0xab1: 0x0657, 0xab2: 0x17a0, 0xab3: 0x17a5, 0xab4: 0x065b, 0xab5: 0x17aa, + 0xab6: 0x115b, 0xab7: 0x17af, 0xab8: 0x1167, 0xab9: 0x1173, 0xaba: 0x117b, 0xabb: 0x17b4, + 0xabc: 0x17b9, 0xabd: 0x118f, 0xabe: 0x17be, 0xabf: 0x1197, + // Block 0x2b, offset 0xac0 + 0xac0: 0x16ce, 0xac1: 0x065f, 0xac2: 0x11af, 0xac3: 0x11b3, 0xac4: 0x0667, 0xac5: 0x11b7, + 0xac6: 0x0a33, 0xac7: 0x17c3, 0xac8: 0x17c8, 0xac9: 0x16d3, 0xaca: 0x16d8, 0xacb: 0x11d7, + 0xacc: 0x11db, 0xacd: 0x13f3, 0xace: 0x066b, 0xacf: 0x1207, 0xad0: 0x1203, 0xad1: 0x120b, + 0xad2: 0x083f, 0xad3: 0x120f, 0xad4: 0x1213, 0xad5: 0x1217, 0xad6: 0x121f, 0xad7: 0x17cd, + 0xad8: 0x121b, 0xad9: 0x1223, 0xada: 0x1237, 0xadb: 0x123b, 0xadc: 0x1227, 0xadd: 0x123f, + 0xade: 0x1253, 0xadf: 0x1267, 0xae0: 0x1233, 0xae1: 0x1247, 0xae2: 0x124b, 0xae3: 0x124f, + 0xae4: 0x17d2, 0xae5: 0x17dc, 0xae6: 0x17d7, 0xae7: 0x066f, 0xae8: 0x126f, 0xae9: 0x1273, + 0xaea: 0x127b, 0xaeb: 0x17f0, 0xaec: 0x127f, 0xaed: 0x17e1, 0xaee: 0x0673, 0xaef: 0x0677, + 0xaf0: 0x17e6, 0xaf1: 0x17eb, 0xaf2: 0x067b, 0xaf3: 0x129f, 0xaf4: 0x12a3, 0xaf5: 0x12a7, + 0xaf6: 0x12ab, 0xaf7: 0x12b7, 0xaf8: 0x12b3, 0xaf9: 0x12bf, 0xafa: 0x12bb, 0xafb: 0x12cb, + 0xafc: 0x12c3, 0xafd: 0x12c7, 0xafe: 0x12cf, 0xaff: 0x067f, + // Block 0x2c, offset 0xb00 + 0xb00: 0x12d7, 0xb01: 0x12db, 0xb02: 0x0683, 0xb03: 0x12eb, 0xb04: 0x12ef, 0xb05: 0x17f5, + 0xb06: 0x12fb, 0xb07: 0x12ff, 0xb08: 0x0687, 0xb09: 0x130b, 0xb0a: 0x05bb, 0xb0b: 0x17fa, + 0xb0c: 0x17ff, 0xb0d: 0x068b, 0xb0e: 0x068f, 0xb0f: 0x1337, 0xb10: 0x134f, 0xb11: 0x136b, + 0xb12: 0x137b, 0xb13: 0x1804, 0xb14: 0x138f, 0xb15: 0x1393, 0xb16: 0x13ab, 0xb17: 0x13b7, + 0xb18: 0x180e, 0xb19: 0x1660, 0xb1a: 0x13c3, 0xb1b: 0x13bf, 0xb1c: 0x13cb, 0xb1d: 0x1665, + 0xb1e: 0x13d7, 0xb1f: 0x13e3, 0xb20: 0x1813, 0xb21: 0x1818, 0xb22: 0x1423, 0xb23: 0x142f, + 0xb24: 0x1437, 0xb25: 0x181d, 0xb26: 0x143b, 0xb27: 0x1467, 0xb28: 0x1473, 0xb29: 0x1477, + 0xb2a: 0x146f, 0xb2b: 0x1483, 0xb2c: 0x1487, 0xb2d: 0x1822, 0xb2e: 0x1493, 0xb2f: 0x0693, + 0xb30: 0x149b, 0xb31: 0x1827, 0xb32: 0x0697, 0xb33: 0x14d3, 0xb34: 0x0ac3, 0xb35: 0x14eb, + 0xb36: 0x182c, 0xb37: 0x1836, 0xb38: 0x069b, 0xb39: 0x069f, 0xb3a: 0x1513, 0xb3b: 0x183b, + 0xb3c: 0x06a3, 0xb3d: 0x1840, 0xb3e: 0x152b, 0xb3f: 0x152b, + // Block 0x2d, offset 0xb40 + 0xb40: 0x1533, 0xb41: 0x1845, 0xb42: 0x154b, 0xb43: 0x06a7, 0xb44: 0x155b, 0xb45: 0x1567, + 0xb46: 0x156f, 0xb47: 0x1577, 0xb48: 0x06ab, 0xb49: 0x184a, 0xb4a: 0x158b, 0xb4b: 0x15a7, + 0xb4c: 0x15b3, 0xb4d: 0x06af, 0xb4e: 0x06b3, 0xb4f: 0x15b7, 0xb50: 0x184f, 0xb51: 0x06b7, + 0xb52: 0x1854, 0xb53: 0x1859, 0xb54: 0x185e, 0xb55: 0x15db, 0xb56: 0x06bb, 0xb57: 0x15ef, + 0xb58: 0x15f7, 0xb59: 0x15fb, 0xb5a: 0x1603, 0xb5b: 0x160b, 0xb5c: 0x1613, 0xb5d: 0x1868, +} + +// nfcIndex: 22 blocks, 1408 entries, 1408 bytes +// Block 0 is the zero block. +var nfcIndex = [1408]uint8{ + // Block 0x0, offset 0x0 + // Block 0x1, offset 0x40 + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc2: 0x2c, 0xc3: 0x01, 0xc4: 0x02, 0xc5: 0x03, 0xc6: 0x2d, 0xc7: 0x04, + 0xc8: 0x05, 0xca: 0x2e, 0xcb: 0x2f, 0xcc: 0x06, 0xcd: 0x07, 0xce: 0x08, 0xcf: 0x30, + 0xd0: 0x09, 0xd1: 0x31, 0xd2: 0x32, 0xd3: 0x0a, 0xd6: 0x0b, 0xd7: 0x33, + 0xd8: 0x34, 0xd9: 0x0c, 0xdb: 0x35, 0xdc: 0x36, 0xdd: 0x37, 0xdf: 0x38, + 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05, + 0xea: 0x06, 0xeb: 0x07, 0xec: 0x08, 0xed: 0x09, 0xef: 0x0a, + 0xf0: 0x13, + // Block 0x4, offset 0x100 + 0x120: 0x39, 0x121: 0x3a, 0x123: 0x3b, 0x124: 0x3c, 0x125: 0x3d, 0x126: 0x3e, 0x127: 0x3f, + 0x128: 0x40, 0x129: 0x41, 0x12a: 0x42, 0x12b: 0x43, 0x12c: 0x3e, 0x12d: 0x44, 0x12e: 0x45, 0x12f: 0x46, + 0x131: 0x47, 0x132: 0x48, 0x133: 0x49, 0x134: 0x4a, 0x135: 0x4b, 0x137: 0x4c, + 0x138: 0x4d, 0x139: 0x4e, 0x13a: 0x4f, 0x13b: 0x50, 0x13c: 0x51, 0x13d: 0x52, 0x13e: 0x53, 0x13f: 0x54, + // Block 0x5, offset 0x140 + 0x140: 0x55, 0x142: 0x56, 0x144: 0x57, 0x145: 0x58, 0x146: 0x59, 0x147: 0x5a, + 0x14d: 0x5b, + 0x15c: 0x5c, 0x15f: 0x5d, + 0x162: 0x5e, 0x164: 0x5f, + 0x168: 0x60, 0x169: 0x61, 0x16a: 0x62, 0x16c: 0x0d, 0x16d: 0x63, 0x16e: 0x64, 0x16f: 0x65, + 0x170: 0x66, 0x173: 0x67, 0x177: 0x68, + 0x178: 0x0e, 0x179: 0x0f, 0x17a: 0x10, 0x17b: 0x11, 0x17c: 0x12, 0x17d: 0x13, 0x17e: 0x14, 0x17f: 0x15, + // Block 0x6, offset 0x180 + 0x180: 0x69, 0x183: 0x6a, 0x184: 0x6b, 0x186: 0x6c, 0x187: 0x6d, + 0x188: 0x6e, 0x189: 0x16, 0x18a: 0x17, 0x18b: 0x6f, 0x18c: 0x70, + 0x1ab: 0x71, + 0x1b3: 0x72, 0x1b5: 0x73, 0x1b7: 0x74, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x75, 0x1c1: 0x18, 0x1c2: 0x19, 0x1c3: 0x1a, 0x1c4: 0x76, 0x1c5: 0x77, + 0x1c9: 0x78, 0x1cc: 0x79, 0x1cd: 0x7a, + // Block 0x8, offset 0x200 + 0x219: 0x7b, 0x21a: 0x7c, 0x21b: 0x7d, + 0x220: 0x7e, 0x223: 0x7f, 0x224: 0x80, 0x225: 0x81, 0x226: 0x82, 0x227: 0x83, + 0x22a: 0x84, 0x22b: 0x85, 0x22f: 0x86, + 0x230: 0x87, 0x231: 0x88, 0x232: 0x89, 0x233: 0x8a, 0x234: 0x8b, 0x235: 0x8c, 0x236: 0x8d, 0x237: 0x87, + 0x238: 0x88, 0x239: 0x89, 0x23a: 0x8a, 0x23b: 0x8b, 0x23c: 0x8c, 0x23d: 0x8d, 0x23e: 0x87, 0x23f: 0x88, + // Block 0x9, offset 0x240 + 0x240: 0x89, 0x241: 0x8a, 0x242: 0x8b, 0x243: 0x8c, 0x244: 0x8d, 0x245: 0x87, 0x246: 0x88, 0x247: 0x89, + 0x248: 0x8a, 0x249: 0x8b, 0x24a: 0x8c, 0x24b: 0x8d, 0x24c: 0x87, 0x24d: 0x88, 0x24e: 0x89, 0x24f: 0x8a, + 0x250: 0x8b, 0x251: 0x8c, 0x252: 0x8d, 0x253: 0x87, 0x254: 0x88, 0x255: 0x89, 0x256: 0x8a, 0x257: 0x8b, + 0x258: 0x8c, 0x259: 0x8d, 0x25a: 0x87, 0x25b: 0x88, 0x25c: 0x89, 0x25d: 0x8a, 0x25e: 0x8b, 0x25f: 0x8c, + 0x260: 0x8d, 0x261: 0x87, 0x262: 0x88, 0x263: 0x89, 0x264: 0x8a, 0x265: 0x8b, 0x266: 0x8c, 0x267: 0x8d, + 0x268: 0x87, 0x269: 0x88, 0x26a: 0x89, 0x26b: 0x8a, 0x26c: 0x8b, 0x26d: 0x8c, 0x26e: 0x8d, 0x26f: 0x87, + 0x270: 0x88, 0x271: 0x89, 0x272: 0x8a, 0x273: 0x8b, 0x274: 0x8c, 0x275: 0x8d, 0x276: 0x87, 0x277: 0x88, + 0x278: 0x89, 0x279: 0x8a, 0x27a: 0x8b, 0x27b: 0x8c, 0x27c: 0x8d, 0x27d: 0x87, 0x27e: 0x88, 0x27f: 0x89, + // Block 0xa, offset 0x280 + 0x280: 0x8a, 0x281: 0x8b, 0x282: 0x8c, 0x283: 0x8d, 0x284: 0x87, 0x285: 0x88, 0x286: 0x89, 0x287: 0x8a, + 0x288: 0x8b, 0x289: 0x8c, 0x28a: 0x8d, 0x28b: 0x87, 0x28c: 0x88, 0x28d: 0x89, 0x28e: 0x8a, 0x28f: 0x8b, + 0x290: 0x8c, 0x291: 0x8d, 0x292: 0x87, 0x293: 0x88, 0x294: 0x89, 0x295: 0x8a, 0x296: 0x8b, 0x297: 0x8c, + 0x298: 0x8d, 0x299: 0x87, 0x29a: 0x88, 0x29b: 0x89, 0x29c: 0x8a, 0x29d: 0x8b, 0x29e: 0x8c, 0x29f: 0x8d, + 0x2a0: 0x87, 0x2a1: 0x88, 0x2a2: 0x89, 0x2a3: 0x8a, 0x2a4: 0x8b, 0x2a5: 0x8c, 0x2a6: 0x8d, 0x2a7: 0x87, + 0x2a8: 0x88, 0x2a9: 0x89, 0x2aa: 0x8a, 0x2ab: 0x8b, 0x2ac: 0x8c, 0x2ad: 0x8d, 0x2ae: 0x87, 0x2af: 0x88, + 0x2b0: 0x89, 0x2b1: 0x8a, 0x2b2: 0x8b, 0x2b3: 0x8c, 0x2b4: 0x8d, 0x2b5: 0x87, 0x2b6: 0x88, 0x2b7: 0x89, + 0x2b8: 0x8a, 0x2b9: 0x8b, 0x2ba: 0x8c, 0x2bb: 0x8d, 0x2bc: 0x87, 0x2bd: 0x88, 0x2be: 0x89, 0x2bf: 0x8a, + // Block 0xb, offset 0x2c0 + 0x2c0: 0x8b, 0x2c1: 0x8c, 0x2c2: 0x8d, 0x2c3: 0x87, 0x2c4: 0x88, 0x2c5: 0x89, 0x2c6: 0x8a, 0x2c7: 0x8b, + 0x2c8: 0x8c, 0x2c9: 0x8d, 0x2ca: 0x87, 0x2cb: 0x88, 0x2cc: 0x89, 0x2cd: 0x8a, 0x2ce: 0x8b, 0x2cf: 0x8c, + 0x2d0: 0x8d, 0x2d1: 0x87, 0x2d2: 0x88, 0x2d3: 0x89, 0x2d4: 0x8a, 0x2d5: 0x8b, 0x2d6: 0x8c, 0x2d7: 0x8d, + 0x2d8: 0x87, 0x2d9: 0x88, 0x2da: 0x89, 0x2db: 0x8a, 0x2dc: 0x8b, 0x2dd: 0x8c, 0x2de: 0x8e, + // Block 0xc, offset 0x300 + 0x324: 0x1b, 0x325: 0x1c, 0x326: 0x1d, 0x327: 0x1e, + 0x328: 0x1f, 0x329: 0x20, 0x32a: 0x21, 0x32b: 0x22, 0x32c: 0x8f, 0x32d: 0x90, 0x32e: 0x91, + 0x331: 0x92, 0x332: 0x93, 0x333: 0x94, 0x334: 0x95, + 0x338: 0x96, 0x339: 0x97, 0x33a: 0x98, 0x33b: 0x99, 0x33e: 0x9a, 0x33f: 0x9b, + // Block 0xd, offset 0x340 + 0x347: 0x9c, + 0x34b: 0x9d, 0x34d: 0x9e, + 0x368: 0x9f, 0x36b: 0xa0, + // Block 0xe, offset 0x380 + 0x381: 0xa1, 0x382: 0xa2, 0x384: 0xa3, 0x385: 0x82, 0x387: 0xa4, + 0x388: 0xa5, 0x38b: 0xa6, 0x38c: 0x3e, 0x38d: 0xa7, + 0x391: 0xa8, 0x392: 0xa9, 0x393: 0xaa, 0x396: 0xab, 0x397: 0xac, + 0x398: 0x73, 0x39a: 0xad, 0x39c: 0xae, + 0x3b0: 0x73, + // Block 0xf, offset 0x3c0 + 0x3eb: 0xaf, 0x3ec: 0xb0, + // Block 0x10, offset 0x400 + 0x432: 0xb1, + // Block 0x11, offset 0x440 + 0x445: 0xb2, 0x446: 0xb3, 0x447: 0xb4, + 0x449: 0xb5, + // Block 0x12, offset 0x480 + 0x480: 0xb6, + 0x4a3: 0xb7, 0x4a5: 0xb8, + // Block 0x13, offset 0x4c0 + 0x4c8: 0xb9, + // Block 0x14, offset 0x500 + 0x520: 0x23, 0x521: 0x24, 0x522: 0x25, 0x523: 0x26, 0x524: 0x27, 0x525: 0x28, 0x526: 0x29, 0x527: 0x2a, + 0x528: 0x2b, + // Block 0x15, offset 0x540 + 0x550: 0x0b, 0x551: 0x0c, 0x556: 0x0d, + 0x55b: 0x0e, 0x55d: 0x0f, 0x55e: 0x10, 0x55f: 0x11, + 0x56f: 0x12, +} + +// nfcSparseOffset: 142 entries, 284 bytes +var nfcSparseOffset = []uint16{0x0, 0x5, 0x9, 0xb, 0xd, 0x18, 0x28, 0x2a, 0x2f, 0x3a, 0x49, 0x56, 0x5e, 0x62, 0x67, 0x69, 0x7a, 0x82, 0x89, 0x8c, 0x93, 0x97, 0x9b, 0x9d, 0x9f, 0xa8, 0xac, 0xb3, 0xb8, 0xbb, 0xc5, 0xc7, 0xce, 0xd6, 0xd9, 0xdb, 0xdd, 0xdf, 0xe4, 0xf5, 0x101, 0x103, 0x109, 0x10b, 0x10d, 0x10f, 0x111, 0x113, 0x115, 0x118, 0x11b, 0x11d, 0x120, 0x123, 0x127, 0x12c, 0x135, 0x137, 0x13a, 0x13c, 0x147, 0x157, 0x15b, 0x169, 0x16c, 0x172, 0x178, 0x183, 0x187, 0x189, 0x18b, 0x18d, 0x18f, 0x191, 0x197, 0x19b, 0x19d, 0x19f, 0x1a7, 0x1ab, 0x1ae, 0x1b0, 0x1b2, 0x1b4, 0x1b7, 0x1b9, 0x1bb, 0x1bd, 0x1bf, 0x1c5, 0x1c8, 0x1ca, 0x1d1, 0x1d7, 0x1dd, 0x1e5, 0x1eb, 0x1f1, 0x1f7, 0x1fb, 0x209, 0x212, 0x215, 0x218, 0x21a, 0x21d, 0x21f, 0x223, 0x228, 0x22a, 0x22c, 0x231, 0x237, 0x239, 0x23b, 0x23d, 0x243, 0x246, 0x249, 0x251, 0x258, 0x25b, 0x25e, 0x260, 0x268, 0x26b, 0x272, 0x275, 0x27b, 0x27d, 0x280, 0x282, 0x284, 0x286, 0x288, 0x295, 0x29f, 0x2a1, 0x2a3, 0x2a9, 0x2ab, 0x2ae} + +// nfcSparseValues: 688 entries, 2752 bytes +var nfcSparseValues = [688]valueRange{ + // Block 0x0, offset 0x0 + {value: 0x0000, lo: 0x04}, + {value: 0xa100, lo: 0xa8, hi: 0xa8}, + {value: 0x8100, lo: 0xaf, hi: 0xaf}, + {value: 0x8100, lo: 0xb4, hi: 0xb4}, + {value: 0x8100, lo: 0xb8, hi: 0xb8}, + // Block 0x1, offset 0x5 + {value: 0x0091, lo: 0x03}, + {value: 0x46e2, lo: 0xa0, hi: 0xa1}, + {value: 0x4714, lo: 0xaf, hi: 0xb0}, + {value: 0xa000, lo: 0xb7, hi: 0xb7}, + // Block 0x2, offset 0x9 + {value: 0x0000, lo: 0x01}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + // Block 0x3, offset 0xb + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0x98, hi: 0x9d}, + // Block 0x4, offset 0xd + {value: 0x0006, lo: 0x0a}, + {value: 0xa000, lo: 0x81, hi: 0x81}, + {value: 0xa000, lo: 0x85, hi: 0x85}, + {value: 0xa000, lo: 0x89, hi: 0x89}, + {value: 0x4840, lo: 0x8a, hi: 0x8a}, + {value: 0x485e, lo: 0x8b, hi: 0x8b}, + {value: 0x36c7, lo: 0x8c, hi: 0x8c}, + {value: 0x36df, lo: 0x8d, hi: 0x8d}, + {value: 0x4876, lo: 0x8e, hi: 0x8e}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x36fd, lo: 0x93, hi: 0x94}, + // Block 0x5, offset 0x18 + {value: 0x0000, lo: 0x0f}, + {value: 0xa000, lo: 0x83, hi: 0x83}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0xa000, lo: 0x8b, hi: 0x8b}, + {value: 0xa000, lo: 0x8d, hi: 0x8d}, + {value: 0x37a5, lo: 0x90, hi: 0x90}, + {value: 0x37b1, lo: 0x91, hi: 0x91}, + {value: 0x379f, lo: 0x93, hi: 0x93}, + {value: 0xa000, lo: 0x96, hi: 0x96}, + {value: 0x3817, lo: 0x97, hi: 0x97}, + {value: 0x37e1, lo: 0x9c, hi: 0x9c}, + {value: 0x37c9, lo: 0x9d, hi: 0x9d}, + {value: 0x37f3, lo: 0x9e, hi: 0x9e}, + {value: 0xa000, lo: 0xb4, hi: 0xb5}, + {value: 0x381d, lo: 0xb6, hi: 0xb6}, + {value: 0x3823, lo: 0xb7, hi: 0xb7}, + // Block 0x6, offset 0x28 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x83, hi: 0x87}, + // Block 0x7, offset 0x2a + {value: 0x0001, lo: 0x04}, + {value: 0x8113, lo: 0x81, hi: 0x82}, + {value: 0x8132, lo: 0x84, hi: 0x84}, + {value: 0x812d, lo: 0x85, hi: 0x85}, + {value: 0x810d, lo: 0x87, hi: 0x87}, + // Block 0x8, offset 0x2f + {value: 0x0000, lo: 0x0a}, + {value: 0x8132, lo: 0x90, hi: 0x97}, + {value: 0x8119, lo: 0x98, hi: 0x98}, + {value: 0x811a, lo: 0x99, hi: 0x99}, + {value: 0x811b, lo: 0x9a, hi: 0x9a}, + {value: 0x3841, lo: 0xa2, hi: 0xa2}, + {value: 0x3847, lo: 0xa3, hi: 0xa3}, + {value: 0x3853, lo: 0xa4, hi: 0xa4}, + {value: 0x384d, lo: 0xa5, hi: 0xa5}, + {value: 0x3859, lo: 0xa6, hi: 0xa6}, + {value: 0xa000, lo: 0xa7, hi: 0xa7}, + // Block 0x9, offset 0x3a + {value: 0x0000, lo: 0x0e}, + {value: 0x386b, lo: 0x80, hi: 0x80}, + {value: 0xa000, lo: 0x81, hi: 0x81}, + {value: 0x385f, lo: 0x82, hi: 0x82}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x3865, lo: 0x93, hi: 0x93}, + {value: 0xa000, lo: 0x95, hi: 0x95}, + {value: 0x8132, lo: 0x96, hi: 0x9c}, + {value: 0x8132, lo: 0x9f, hi: 0xa2}, + {value: 0x812d, lo: 0xa3, hi: 0xa3}, + {value: 0x8132, lo: 0xa4, hi: 0xa4}, + {value: 0x8132, lo: 0xa7, hi: 0xa8}, + {value: 0x812d, lo: 0xaa, hi: 0xaa}, + {value: 0x8132, lo: 0xab, hi: 0xac}, + {value: 0x812d, lo: 0xad, hi: 0xad}, + // Block 0xa, offset 0x49 + {value: 0x0000, lo: 0x0c}, + {value: 0x811f, lo: 0x91, hi: 0x91}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + {value: 0x812d, lo: 0xb1, hi: 0xb1}, + {value: 0x8132, lo: 0xb2, hi: 0xb3}, + {value: 0x812d, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb5, hi: 0xb6}, + {value: 0x812d, lo: 0xb7, hi: 0xb9}, + {value: 0x8132, lo: 0xba, hi: 0xba}, + {value: 0x812d, lo: 0xbb, hi: 0xbc}, + {value: 0x8132, lo: 0xbd, hi: 0xbd}, + {value: 0x812d, lo: 0xbe, hi: 0xbe}, + {value: 0x8132, lo: 0xbf, hi: 0xbf}, + // Block 0xb, offset 0x56 + {value: 0x0005, lo: 0x07}, + {value: 0x8132, lo: 0x80, hi: 0x80}, + {value: 0x8132, lo: 0x81, hi: 0x81}, + {value: 0x812d, lo: 0x82, hi: 0x83}, + {value: 0x812d, lo: 0x84, hi: 0x85}, + {value: 0x812d, lo: 0x86, hi: 0x87}, + {value: 0x812d, lo: 0x88, hi: 0x89}, + {value: 0x8132, lo: 0x8a, hi: 0x8a}, + // Block 0xc, offset 0x5e + {value: 0x0000, lo: 0x03}, + {value: 0x8132, lo: 0xab, hi: 0xb1}, + {value: 0x812d, lo: 0xb2, hi: 0xb2}, + {value: 0x8132, lo: 0xb3, hi: 0xb3}, + // Block 0xd, offset 0x62 + {value: 0x0000, lo: 0x04}, + {value: 0x8132, lo: 0x96, hi: 0x99}, + {value: 0x8132, lo: 0x9b, hi: 0xa3}, + {value: 0x8132, lo: 0xa5, hi: 0xa7}, + {value: 0x8132, lo: 0xa9, hi: 0xad}, + // Block 0xe, offset 0x67 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x99, hi: 0x9b}, + // Block 0xf, offset 0x69 + {value: 0x0000, lo: 0x10}, + {value: 0x8132, lo: 0x94, hi: 0xa1}, + {value: 0x812d, lo: 0xa3, hi: 0xa3}, + {value: 0x8132, lo: 0xa4, hi: 0xa5}, + {value: 0x812d, lo: 0xa6, hi: 0xa6}, + {value: 0x8132, lo: 0xa7, hi: 0xa8}, + {value: 0x812d, lo: 0xa9, hi: 0xa9}, + {value: 0x8132, lo: 0xaa, hi: 0xac}, + {value: 0x812d, lo: 0xad, hi: 0xaf}, + {value: 0x8116, lo: 0xb0, hi: 0xb0}, + {value: 0x8117, lo: 0xb1, hi: 0xb1}, + {value: 0x8118, lo: 0xb2, hi: 0xb2}, + {value: 0x8132, lo: 0xb3, hi: 0xb5}, + {value: 0x812d, lo: 0xb6, hi: 0xb6}, + {value: 0x8132, lo: 0xb7, hi: 0xb8}, + {value: 0x812d, lo: 0xb9, hi: 0xba}, + {value: 0x8132, lo: 0xbb, hi: 0xbf}, + // Block 0x10, offset 0x7a + {value: 0x0000, lo: 0x07}, + {value: 0xa000, lo: 0xa8, hi: 0xa8}, + {value: 0x3ed8, lo: 0xa9, hi: 0xa9}, + {value: 0xa000, lo: 0xb0, hi: 0xb0}, + {value: 0x3ee0, lo: 0xb1, hi: 0xb1}, + {value: 0xa000, lo: 0xb3, hi: 0xb3}, + {value: 0x3ee8, lo: 0xb4, hi: 0xb4}, + {value: 0x9902, lo: 0xbc, hi: 0xbc}, + // Block 0x11, offset 0x82 + {value: 0x0008, lo: 0x06}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x8132, lo: 0x91, hi: 0x91}, + {value: 0x812d, lo: 0x92, hi: 0x92}, + {value: 0x8132, lo: 0x93, hi: 0x93}, + {value: 0x8132, lo: 0x94, hi: 0x94}, + {value: 0x451c, lo: 0x98, hi: 0x9f}, + // Block 0x12, offset 0x89 + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x13, offset 0x8c + {value: 0x0008, lo: 0x06}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2c9e, lo: 0x8b, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + {value: 0x455c, lo: 0x9c, hi: 0x9d}, + {value: 0x456c, lo: 0x9f, hi: 0x9f}, + // Block 0x14, offset 0x93 + {value: 0x0000, lo: 0x03}, + {value: 0x4594, lo: 0xb3, hi: 0xb3}, + {value: 0x459c, lo: 0xb6, hi: 0xb6}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + // Block 0x15, offset 0x97 + {value: 0x0008, lo: 0x03}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x4574, lo: 0x99, hi: 0x9b}, + {value: 0x458c, lo: 0x9e, hi: 0x9e}, + // Block 0x16, offset 0x9b + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + // Block 0x17, offset 0x9d + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + // Block 0x18, offset 0x9f + {value: 0x0000, lo: 0x08}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2cb6, lo: 0x88, hi: 0x88}, + {value: 0x2cae, lo: 0x8b, hi: 0x8b}, + {value: 0x2cbe, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x96, hi: 0x97}, + {value: 0x45a4, lo: 0x9c, hi: 0x9c}, + {value: 0x45ac, lo: 0x9d, hi: 0x9d}, + // Block 0x19, offset 0xa8 + {value: 0x0000, lo: 0x03}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x2cc6, lo: 0x94, hi: 0x94}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x1a, offset 0xac + {value: 0x0000, lo: 0x06}, + {value: 0xa000, lo: 0x86, hi: 0x87}, + {value: 0x2cce, lo: 0x8a, hi: 0x8a}, + {value: 0x2cde, lo: 0x8b, hi: 0x8b}, + {value: 0x2cd6, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + // Block 0x1b, offset 0xb3 + {value: 0x1801, lo: 0x04}, + {value: 0xa000, lo: 0x86, hi: 0x86}, + {value: 0x3ef0, lo: 0x88, hi: 0x88}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x8120, lo: 0x95, hi: 0x96}, + // Block 0x1c, offset 0xb8 + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + {value: 0xa000, lo: 0xbf, hi: 0xbf}, + // Block 0x1d, offset 0xbb + {value: 0x0000, lo: 0x09}, + {value: 0x2ce6, lo: 0x80, hi: 0x80}, + {value: 0x9900, lo: 0x82, hi: 0x82}, + {value: 0xa000, lo: 0x86, hi: 0x86}, + {value: 0x2cee, lo: 0x87, hi: 0x87}, + {value: 0x2cf6, lo: 0x88, hi: 0x88}, + {value: 0x2f50, lo: 0x8a, hi: 0x8a}, + {value: 0x2dd8, lo: 0x8b, hi: 0x8b}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x95, hi: 0x96}, + // Block 0x1e, offset 0xc5 + {value: 0x0000, lo: 0x01}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x1f, offset 0xc7 + {value: 0x0000, lo: 0x06}, + {value: 0xa000, lo: 0x86, hi: 0x87}, + {value: 0x2cfe, lo: 0x8a, hi: 0x8a}, + {value: 0x2d0e, lo: 0x8b, hi: 0x8b}, + {value: 0x2d06, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + // Block 0x20, offset 0xce + {value: 0x6bea, lo: 0x07}, + {value: 0x9904, lo: 0x8a, hi: 0x8a}, + {value: 0x9900, lo: 0x8f, hi: 0x8f}, + {value: 0xa000, lo: 0x99, hi: 0x99}, + {value: 0x3ef8, lo: 0x9a, hi: 0x9a}, + {value: 0x2f58, lo: 0x9c, hi: 0x9c}, + {value: 0x2de3, lo: 0x9d, hi: 0x9d}, + {value: 0x2d16, lo: 0x9e, hi: 0x9f}, + // Block 0x21, offset 0xd6 + {value: 0x0000, lo: 0x02}, + {value: 0x8122, lo: 0xb8, hi: 0xb9}, + {value: 0x8104, lo: 0xba, hi: 0xba}, + // Block 0x22, offset 0xd9 + {value: 0x0000, lo: 0x01}, + {value: 0x8123, lo: 0x88, hi: 0x8b}, + // Block 0x23, offset 0xdb + {value: 0x0000, lo: 0x01}, + {value: 0x8124, lo: 0xb8, hi: 0xb9}, + // Block 0x24, offset 0xdd + {value: 0x0000, lo: 0x01}, + {value: 0x8125, lo: 0x88, hi: 0x8b}, + // Block 0x25, offset 0xdf + {value: 0x0000, lo: 0x04}, + {value: 0x812d, lo: 0x98, hi: 0x99}, + {value: 0x812d, lo: 0xb5, hi: 0xb5}, + {value: 0x812d, lo: 0xb7, hi: 0xb7}, + {value: 0x812b, lo: 0xb9, hi: 0xb9}, + // Block 0x26, offset 0xe4 + {value: 0x0000, lo: 0x10}, + {value: 0x2644, lo: 0x83, hi: 0x83}, + {value: 0x264b, lo: 0x8d, hi: 0x8d}, + {value: 0x2652, lo: 0x92, hi: 0x92}, + {value: 0x2659, lo: 0x97, hi: 0x97}, + {value: 0x2660, lo: 0x9c, hi: 0x9c}, + {value: 0x263d, lo: 0xa9, hi: 0xa9}, + {value: 0x8126, lo: 0xb1, hi: 0xb1}, + {value: 0x8127, lo: 0xb2, hi: 0xb2}, + {value: 0x4a84, lo: 0xb3, hi: 0xb3}, + {value: 0x8128, lo: 0xb4, hi: 0xb4}, + {value: 0x4a8d, lo: 0xb5, hi: 0xb5}, + {value: 0x45b4, lo: 0xb6, hi: 0xb6}, + {value: 0x8200, lo: 0xb7, hi: 0xb7}, + {value: 0x45bc, lo: 0xb8, hi: 0xb8}, + {value: 0x8200, lo: 0xb9, hi: 0xb9}, + {value: 0x8127, lo: 0xba, hi: 0xbd}, + // Block 0x27, offset 0xf5 + {value: 0x0000, lo: 0x0b}, + {value: 0x8127, lo: 0x80, hi: 0x80}, + {value: 0x4a96, lo: 0x81, hi: 0x81}, + {value: 0x8132, lo: 0x82, hi: 0x83}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0x86, hi: 0x87}, + {value: 0x266e, lo: 0x93, hi: 0x93}, + {value: 0x2675, lo: 0x9d, hi: 0x9d}, + {value: 0x267c, lo: 0xa2, hi: 0xa2}, + {value: 0x2683, lo: 0xa7, hi: 0xa7}, + {value: 0x268a, lo: 0xac, hi: 0xac}, + {value: 0x2667, lo: 0xb9, hi: 0xb9}, + // Block 0x28, offset 0x101 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x86, hi: 0x86}, + // Block 0x29, offset 0x103 + {value: 0x0000, lo: 0x05}, + {value: 0xa000, lo: 0xa5, hi: 0xa5}, + {value: 0x2d1e, lo: 0xa6, hi: 0xa6}, + {value: 0x9900, lo: 0xae, hi: 0xae}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + {value: 0x8104, lo: 0xb9, hi: 0xba}, + // Block 0x2a, offset 0x109 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x8d, hi: 0x8d}, + // Block 0x2b, offset 0x10b + {value: 0x0000, lo: 0x01}, + {value: 0xa000, lo: 0x80, hi: 0x92}, + // Block 0x2c, offset 0x10d + {value: 0x0000, lo: 0x01}, + {value: 0xb900, lo: 0xa1, hi: 0xb5}, + // Block 0x2d, offset 0x10f + {value: 0x0000, lo: 0x01}, + {value: 0x9900, lo: 0xa8, hi: 0xbf}, + // Block 0x2e, offset 0x111 + {value: 0x0000, lo: 0x01}, + {value: 0x9900, lo: 0x80, hi: 0x82}, + // Block 0x2f, offset 0x113 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x9d, hi: 0x9f}, + // Block 0x30, offset 0x115 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x94, hi: 0x94}, + {value: 0x8104, lo: 0xb4, hi: 0xb4}, + // Block 0x31, offset 0x118 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x92, hi: 0x92}, + {value: 0x8132, lo: 0x9d, hi: 0x9d}, + // Block 0x32, offset 0x11b + {value: 0x0000, lo: 0x01}, + {value: 0x8131, lo: 0xa9, hi: 0xa9}, + // Block 0x33, offset 0x11d + {value: 0x0004, lo: 0x02}, + {value: 0x812e, lo: 0xb9, hi: 0xba}, + {value: 0x812d, lo: 0xbb, hi: 0xbb}, + // Block 0x34, offset 0x120 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x97, hi: 0x97}, + {value: 0x812d, lo: 0x98, hi: 0x98}, + // Block 0x35, offset 0x123 + {value: 0x0000, lo: 0x03}, + {value: 0x8104, lo: 0xa0, hi: 0xa0}, + {value: 0x8132, lo: 0xb5, hi: 0xbc}, + {value: 0x812d, lo: 0xbf, hi: 0xbf}, + // Block 0x36, offset 0x127 + {value: 0x0000, lo: 0x04}, + {value: 0x8132, lo: 0xb0, hi: 0xb4}, + {value: 0x812d, lo: 0xb5, hi: 0xba}, + {value: 0x8132, lo: 0xbb, hi: 0xbc}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + // Block 0x37, offset 0x12c + {value: 0x0000, lo: 0x08}, + {value: 0x2d66, lo: 0x80, hi: 0x80}, + {value: 0x2d6e, lo: 0x81, hi: 0x81}, + {value: 0xa000, lo: 0x82, hi: 0x82}, + {value: 0x2d76, lo: 0x83, hi: 0x83}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0xab, hi: 0xab}, + {value: 0x812d, lo: 0xac, hi: 0xac}, + {value: 0x8132, lo: 0xad, hi: 0xb3}, + // Block 0x38, offset 0x135 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xaa, hi: 0xab}, + // Block 0x39, offset 0x137 + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xa6, hi: 0xa6}, + {value: 0x8104, lo: 0xb2, hi: 0xb3}, + // Block 0x3a, offset 0x13a + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + // Block 0x3b, offset 0x13c + {value: 0x0000, lo: 0x0a}, + {value: 0x8132, lo: 0x90, hi: 0x92}, + {value: 0x8101, lo: 0x94, hi: 0x94}, + {value: 0x812d, lo: 0x95, hi: 0x99}, + {value: 0x8132, lo: 0x9a, hi: 0x9b}, + {value: 0x812d, lo: 0x9c, hi: 0x9f}, + {value: 0x8132, lo: 0xa0, hi: 0xa0}, + {value: 0x8101, lo: 0xa2, hi: 0xa8}, + {value: 0x812d, lo: 0xad, hi: 0xad}, + {value: 0x8132, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb8, hi: 0xb9}, + // Block 0x3c, offset 0x147 + {value: 0x0000, lo: 0x0f}, + {value: 0x8132, lo: 0x80, hi: 0x81}, + {value: 0x812d, lo: 0x82, hi: 0x82}, + {value: 0x8132, lo: 0x83, hi: 0x89}, + {value: 0x812d, lo: 0x8a, hi: 0x8a}, + {value: 0x8132, lo: 0x8b, hi: 0x8c}, + {value: 0x8135, lo: 0x8d, hi: 0x8d}, + {value: 0x812a, lo: 0x8e, hi: 0x8e}, + {value: 0x812d, lo: 0x8f, hi: 0x8f}, + {value: 0x8129, lo: 0x90, hi: 0x90}, + {value: 0x8132, lo: 0x91, hi: 0xb5}, + {value: 0x8132, lo: 0xbb, hi: 0xbb}, + {value: 0x8134, lo: 0xbc, hi: 0xbc}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + {value: 0x8132, lo: 0xbe, hi: 0xbe}, + {value: 0x812d, lo: 0xbf, hi: 0xbf}, + // Block 0x3d, offset 0x157 + {value: 0x0004, lo: 0x03}, + {value: 0x0433, lo: 0x80, hi: 0x81}, + {value: 0x8100, lo: 0x97, hi: 0x97}, + {value: 0x8100, lo: 0xbe, hi: 0xbe}, + // Block 0x3e, offset 0x15b + {value: 0x0000, lo: 0x0d}, + {value: 0x8132, lo: 0x90, hi: 0x91}, + {value: 0x8101, lo: 0x92, hi: 0x93}, + {value: 0x8132, lo: 0x94, hi: 0x97}, + {value: 0x8101, lo: 0x98, hi: 0x9a}, + {value: 0x8132, lo: 0x9b, hi: 0x9c}, + {value: 0x8132, lo: 0xa1, hi: 0xa1}, + {value: 0x8101, lo: 0xa5, hi: 0xa6}, + {value: 0x8132, lo: 0xa7, hi: 0xa7}, + {value: 0x812d, lo: 0xa8, hi: 0xa8}, + {value: 0x8132, lo: 0xa9, hi: 0xa9}, + {value: 0x8101, lo: 0xaa, hi: 0xab}, + {value: 0x812d, lo: 0xac, hi: 0xaf}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + // Block 0x3f, offset 0x169 + {value: 0x427b, lo: 0x02}, + {value: 0x01b8, lo: 0xa6, hi: 0xa6}, + {value: 0x0057, lo: 0xaa, hi: 0xab}, + // Block 0x40, offset 0x16c + {value: 0x0007, lo: 0x05}, + {value: 0xa000, lo: 0x90, hi: 0x90}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0xa000, lo: 0x94, hi: 0x94}, + {value: 0x3bb9, lo: 0x9a, hi: 0x9b}, + {value: 0x3bc7, lo: 0xae, hi: 0xae}, + // Block 0x41, offset 0x172 + {value: 0x000e, lo: 0x05}, + {value: 0x3bce, lo: 0x8d, hi: 0x8e}, + {value: 0x3bd5, lo: 0x8f, hi: 0x8f}, + {value: 0xa000, lo: 0x90, hi: 0x90}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0xa000, lo: 0x94, hi: 0x94}, + // Block 0x42, offset 0x178 + {value: 0x6408, lo: 0x0a}, + {value: 0xa000, lo: 0x83, hi: 0x83}, + {value: 0x3be3, lo: 0x84, hi: 0x84}, + {value: 0xa000, lo: 0x88, hi: 0x88}, + {value: 0x3bea, lo: 0x89, hi: 0x89}, + {value: 0xa000, lo: 0x8b, hi: 0x8b}, + {value: 0x3bf1, lo: 0x8c, hi: 0x8c}, + {value: 0xa000, lo: 0xa3, hi: 0xa3}, + {value: 0x3bf8, lo: 0xa4, hi: 0xa5}, + {value: 0x3bff, lo: 0xa6, hi: 0xa6}, + {value: 0xa000, lo: 0xbc, hi: 0xbc}, + // Block 0x43, offset 0x183 + {value: 0x0007, lo: 0x03}, + {value: 0x3c68, lo: 0xa0, hi: 0xa1}, + {value: 0x3c92, lo: 0xa2, hi: 0xa3}, + {value: 0x3cbc, lo: 0xaa, hi: 0xad}, + // Block 0x44, offset 0x187 + {value: 0x0004, lo: 0x01}, + {value: 0x048b, lo: 0xa9, hi: 0xaa}, + // Block 0x45, offset 0x189 + {value: 0x0000, lo: 0x01}, + {value: 0x44dd, lo: 0x9c, hi: 0x9c}, + // Block 0x46, offset 0x18b + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xaf, hi: 0xb1}, + // Block 0x47, offset 0x18d + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x48, offset 0x18f + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xa0, hi: 0xbf}, + // Block 0x49, offset 0x191 + {value: 0x0000, lo: 0x05}, + {value: 0x812c, lo: 0xaa, hi: 0xaa}, + {value: 0x8131, lo: 0xab, hi: 0xab}, + {value: 0x8133, lo: 0xac, hi: 0xac}, + {value: 0x812e, lo: 0xad, hi: 0xad}, + {value: 0x812f, lo: 0xae, hi: 0xaf}, + // Block 0x4a, offset 0x197 + {value: 0x0000, lo: 0x03}, + {value: 0x4a9f, lo: 0xb3, hi: 0xb3}, + {value: 0x4a9f, lo: 0xb5, hi: 0xb6}, + {value: 0x4a9f, lo: 0xba, hi: 0xbf}, + // Block 0x4b, offset 0x19b + {value: 0x0000, lo: 0x01}, + {value: 0x4a9f, lo: 0x8f, hi: 0xa3}, + // Block 0x4c, offset 0x19d + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0xae, hi: 0xbe}, + // Block 0x4d, offset 0x19f + {value: 0x0000, lo: 0x07}, + {value: 0x8100, lo: 0x84, hi: 0x84}, + {value: 0x8100, lo: 0x87, hi: 0x87}, + {value: 0x8100, lo: 0x90, hi: 0x90}, + {value: 0x8100, lo: 0x9e, hi: 0x9e}, + {value: 0x8100, lo: 0xa1, hi: 0xa1}, + {value: 0x8100, lo: 0xb2, hi: 0xb2}, + {value: 0x8100, lo: 0xbb, hi: 0xbb}, + // Block 0x4e, offset 0x1a7 + {value: 0x0000, lo: 0x03}, + {value: 0x8100, lo: 0x80, hi: 0x80}, + {value: 0x8100, lo: 0x8b, hi: 0x8b}, + {value: 0x8100, lo: 0x8e, hi: 0x8e}, + // Block 0x4f, offset 0x1ab + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0xaf, hi: 0xaf}, + {value: 0x8132, lo: 0xb4, hi: 0xbd}, + // Block 0x50, offset 0x1ae + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x9e, hi: 0x9f}, + // Block 0x51, offset 0x1b0 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb0, hi: 0xb1}, + // Block 0x52, offset 0x1b2 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x86, hi: 0x86}, + // Block 0x53, offset 0x1b4 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0xa0, hi: 0xb1}, + // Block 0x54, offset 0x1b7 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xab, hi: 0xad}, + // Block 0x55, offset 0x1b9 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x93, hi: 0x93}, + // Block 0x56, offset 0x1bb + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xb3, hi: 0xb3}, + // Block 0x57, offset 0x1bd + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x80, hi: 0x80}, + // Block 0x58, offset 0x1bf + {value: 0x0000, lo: 0x05}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + {value: 0x8132, lo: 0xb2, hi: 0xb3}, + {value: 0x812d, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb7, hi: 0xb8}, + {value: 0x8132, lo: 0xbe, hi: 0xbf}, + // Block 0x59, offset 0x1c5 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x81, hi: 0x81}, + {value: 0x8104, lo: 0xb6, hi: 0xb6}, + // Block 0x5a, offset 0x1c8 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xad, hi: 0xad}, + // Block 0x5b, offset 0x1ca + {value: 0x0000, lo: 0x06}, + {value: 0xe500, lo: 0x80, hi: 0x80}, + {value: 0xc600, lo: 0x81, hi: 0x9b}, + {value: 0xe500, lo: 0x9c, hi: 0x9c}, + {value: 0xc600, lo: 0x9d, hi: 0xb7}, + {value: 0xe500, lo: 0xb8, hi: 0xb8}, + {value: 0xc600, lo: 0xb9, hi: 0xbf}, + // Block 0x5c, offset 0x1d1 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x93}, + {value: 0xe500, lo: 0x94, hi: 0x94}, + {value: 0xc600, lo: 0x95, hi: 0xaf}, + {value: 0xe500, lo: 0xb0, hi: 0xb0}, + {value: 0xc600, lo: 0xb1, hi: 0xbf}, + // Block 0x5d, offset 0x1d7 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x8b}, + {value: 0xe500, lo: 0x8c, hi: 0x8c}, + {value: 0xc600, lo: 0x8d, hi: 0xa7}, + {value: 0xe500, lo: 0xa8, hi: 0xa8}, + {value: 0xc600, lo: 0xa9, hi: 0xbf}, + // Block 0x5e, offset 0x1dd + {value: 0x0000, lo: 0x07}, + {value: 0xc600, lo: 0x80, hi: 0x83}, + {value: 0xe500, lo: 0x84, hi: 0x84}, + {value: 0xc600, lo: 0x85, hi: 0x9f}, + {value: 0xe500, lo: 0xa0, hi: 0xa0}, + {value: 0xc600, lo: 0xa1, hi: 0xbb}, + {value: 0xe500, lo: 0xbc, hi: 0xbc}, + {value: 0xc600, lo: 0xbd, hi: 0xbf}, + // Block 0x5f, offset 0x1e5 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x97}, + {value: 0xe500, lo: 0x98, hi: 0x98}, + {value: 0xc600, lo: 0x99, hi: 0xb3}, + {value: 0xe500, lo: 0xb4, hi: 0xb4}, + {value: 0xc600, lo: 0xb5, hi: 0xbf}, + // Block 0x60, offset 0x1eb + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x8f}, + {value: 0xe500, lo: 0x90, hi: 0x90}, + {value: 0xc600, lo: 0x91, hi: 0xab}, + {value: 0xe500, lo: 0xac, hi: 0xac}, + {value: 0xc600, lo: 0xad, hi: 0xbf}, + // Block 0x61, offset 0x1f1 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x87}, + {value: 0xe500, lo: 0x88, hi: 0x88}, + {value: 0xc600, lo: 0x89, hi: 0xa3}, + {value: 0xe500, lo: 0xa4, hi: 0xa4}, + {value: 0xc600, lo: 0xa5, hi: 0xbf}, + // Block 0x62, offset 0x1f7 + {value: 0x0000, lo: 0x03}, + {value: 0xc600, lo: 0x80, hi: 0x87}, + {value: 0xe500, lo: 0x88, hi: 0x88}, + {value: 0xc600, lo: 0x89, hi: 0xa3}, + // Block 0x63, offset 0x1fb + {value: 0x0006, lo: 0x0d}, + {value: 0x4390, lo: 0x9d, hi: 0x9d}, + {value: 0x8115, lo: 0x9e, hi: 0x9e}, + {value: 0x4402, lo: 0x9f, hi: 0x9f}, + {value: 0x43f0, lo: 0xaa, hi: 0xab}, + {value: 0x44f4, lo: 0xac, hi: 0xac}, + {value: 0x44fc, lo: 0xad, hi: 0xad}, + {value: 0x4348, lo: 0xae, hi: 0xb1}, + {value: 0x4366, lo: 0xb2, hi: 0xb4}, + {value: 0x437e, lo: 0xb5, hi: 0xb6}, + {value: 0x438a, lo: 0xb8, hi: 0xb8}, + {value: 0x4396, lo: 0xb9, hi: 0xbb}, + {value: 0x43ae, lo: 0xbc, hi: 0xbc}, + {value: 0x43b4, lo: 0xbe, hi: 0xbe}, + // Block 0x64, offset 0x209 + {value: 0x0006, lo: 0x08}, + {value: 0x43ba, lo: 0x80, hi: 0x81}, + {value: 0x43c6, lo: 0x83, hi: 0x84}, + {value: 0x43d8, lo: 0x86, hi: 0x89}, + {value: 0x43fc, lo: 0x8a, hi: 0x8a}, + {value: 0x4378, lo: 0x8b, hi: 0x8b}, + {value: 0x4360, lo: 0x8c, hi: 0x8c}, + {value: 0x43a8, lo: 0x8d, hi: 0x8d}, + {value: 0x43d2, lo: 0x8e, hi: 0x8e}, + // Block 0x65, offset 0x212 + {value: 0x0000, lo: 0x02}, + {value: 0x8100, lo: 0xa4, hi: 0xa5}, + {value: 0x8100, lo: 0xb0, hi: 0xb1}, + // Block 0x66, offset 0x215 + {value: 0x0000, lo: 0x02}, + {value: 0x8100, lo: 0x9b, hi: 0x9d}, + {value: 0x8200, lo: 0x9e, hi: 0xa3}, + // Block 0x67, offset 0x218 + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0x90, hi: 0x90}, + // Block 0x68, offset 0x21a + {value: 0x0000, lo: 0x02}, + {value: 0x8100, lo: 0x99, hi: 0x99}, + {value: 0x8200, lo: 0xb2, hi: 0xb4}, + // Block 0x69, offset 0x21d + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0xbc, hi: 0xbd}, + // Block 0x6a, offset 0x21f + {value: 0x0000, lo: 0x03}, + {value: 0x8132, lo: 0xa0, hi: 0xa6}, + {value: 0x812d, lo: 0xa7, hi: 0xad}, + {value: 0x8132, lo: 0xae, hi: 0xaf}, + // Block 0x6b, offset 0x223 + {value: 0x0000, lo: 0x04}, + {value: 0x8100, lo: 0x89, hi: 0x8c}, + {value: 0x8100, lo: 0xb0, hi: 0xb2}, + {value: 0x8100, lo: 0xb4, hi: 0xb4}, + {value: 0x8100, lo: 0xb6, hi: 0xbf}, + // Block 0x6c, offset 0x228 + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0x81, hi: 0x8c}, + // Block 0x6d, offset 0x22a + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0xb5, hi: 0xba}, + // Block 0x6e, offset 0x22c + {value: 0x0000, lo: 0x04}, + {value: 0x4a9f, lo: 0x9e, hi: 0x9f}, + {value: 0x4a9f, lo: 0xa3, hi: 0xa3}, + {value: 0x4a9f, lo: 0xa5, hi: 0xa6}, + {value: 0x4a9f, lo: 0xaa, hi: 0xaf}, + // Block 0x6f, offset 0x231 + {value: 0x0000, lo: 0x05}, + {value: 0x4a9f, lo: 0x82, hi: 0x87}, + {value: 0x4a9f, lo: 0x8a, hi: 0x8f}, + {value: 0x4a9f, lo: 0x92, hi: 0x97}, + {value: 0x4a9f, lo: 0x9a, hi: 0x9c}, + {value: 0x8100, lo: 0xa3, hi: 0xa3}, + // Block 0x70, offset 0x237 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + // Block 0x71, offset 0x239 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xa0, hi: 0xa0}, + // Block 0x72, offset 0x23b + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb6, hi: 0xba}, + // Block 0x73, offset 0x23d + {value: 0x002c, lo: 0x05}, + {value: 0x812d, lo: 0x8d, hi: 0x8d}, + {value: 0x8132, lo: 0x8f, hi: 0x8f}, + {value: 0x8132, lo: 0xb8, hi: 0xb8}, + {value: 0x8101, lo: 0xb9, hi: 0xba}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x74, offset 0x243 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0xa5, hi: 0xa5}, + {value: 0x812d, lo: 0xa6, hi: 0xa6}, + // Block 0x75, offset 0x246 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x86, hi: 0x86}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x76, offset 0x249 + {value: 0x17fe, lo: 0x07}, + {value: 0xa000, lo: 0x99, hi: 0x99}, + {value: 0x4238, lo: 0x9a, hi: 0x9a}, + {value: 0xa000, lo: 0x9b, hi: 0x9b}, + {value: 0x4242, lo: 0x9c, hi: 0x9c}, + {value: 0xa000, lo: 0xa5, hi: 0xa5}, + {value: 0x424c, lo: 0xab, hi: 0xab}, + {value: 0x8104, lo: 0xb9, hi: 0xba}, + // Block 0x77, offset 0x251 + {value: 0x0000, lo: 0x06}, + {value: 0x8132, lo: 0x80, hi: 0x82}, + {value: 0x9900, lo: 0xa7, hi: 0xa7}, + {value: 0x2d7e, lo: 0xae, hi: 0xae}, + {value: 0x2d88, lo: 0xaf, hi: 0xaf}, + {value: 0xa000, lo: 0xb1, hi: 0xb2}, + {value: 0x8104, lo: 0xb3, hi: 0xb4}, + // Block 0x78, offset 0x258 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x80, hi: 0x80}, + {value: 0x8102, lo: 0x8a, hi: 0x8a}, + // Block 0x79, offset 0x25b + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xb5, hi: 0xb5}, + {value: 0x8102, lo: 0xb6, hi: 0xb6}, + // Block 0x7a, offset 0x25e + {value: 0x0002, lo: 0x01}, + {value: 0x8102, lo: 0xa9, hi: 0xaa}, + // Block 0x7b, offset 0x260 + {value: 0x0000, lo: 0x07}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2d92, lo: 0x8b, hi: 0x8b}, + {value: 0x2d9c, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + {value: 0x8132, lo: 0xa6, hi: 0xac}, + {value: 0x8132, lo: 0xb0, hi: 0xb4}, + // Block 0x7c, offset 0x268 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x82, hi: 0x82}, + {value: 0x8102, lo: 0x86, hi: 0x86}, + // Block 0x7d, offset 0x26b + {value: 0x6b5a, lo: 0x06}, + {value: 0x9900, lo: 0xb0, hi: 0xb0}, + {value: 0xa000, lo: 0xb9, hi: 0xb9}, + {value: 0x9900, lo: 0xba, hi: 0xba}, + {value: 0x2db0, lo: 0xbb, hi: 0xbb}, + {value: 0x2da6, lo: 0xbc, hi: 0xbd}, + {value: 0x2dba, lo: 0xbe, hi: 0xbe}, + // Block 0x7e, offset 0x272 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x82, hi: 0x82}, + {value: 0x8102, lo: 0x83, hi: 0x83}, + // Block 0x7f, offset 0x275 + {value: 0x0000, lo: 0x05}, + {value: 0x9900, lo: 0xaf, hi: 0xaf}, + {value: 0xa000, lo: 0xb8, hi: 0xb9}, + {value: 0x2dc4, lo: 0xba, hi: 0xba}, + {value: 0x2dce, lo: 0xbb, hi: 0xbb}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x80, offset 0x27b + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0x80, hi: 0x80}, + // Block 0x81, offset 0x27d + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xb6, hi: 0xb6}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + // Block 0x82, offset 0x280 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xab, hi: 0xab}, + // Block 0x83, offset 0x282 + {value: 0x0000, lo: 0x01}, + {value: 0x8101, lo: 0xb0, hi: 0xb4}, + // Block 0x84, offset 0x284 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb0, hi: 0xb6}, + // Block 0x85, offset 0x286 + {value: 0x0000, lo: 0x01}, + {value: 0x8101, lo: 0x9e, hi: 0x9e}, + // Block 0x86, offset 0x288 + {value: 0x0000, lo: 0x0c}, + {value: 0x45cc, lo: 0x9e, hi: 0x9e}, + {value: 0x45d6, lo: 0x9f, hi: 0x9f}, + {value: 0x460a, lo: 0xa0, hi: 0xa0}, + {value: 0x4618, lo: 0xa1, hi: 0xa1}, + {value: 0x4626, lo: 0xa2, hi: 0xa2}, + {value: 0x4634, lo: 0xa3, hi: 0xa3}, + {value: 0x4642, lo: 0xa4, hi: 0xa4}, + {value: 0x812b, lo: 0xa5, hi: 0xa6}, + {value: 0x8101, lo: 0xa7, hi: 0xa9}, + {value: 0x8130, lo: 0xad, hi: 0xad}, + {value: 0x812b, lo: 0xae, hi: 0xb2}, + {value: 0x812d, lo: 0xbb, hi: 0xbf}, + // Block 0x87, offset 0x295 + {value: 0x0000, lo: 0x09}, + {value: 0x812d, lo: 0x80, hi: 0x82}, + {value: 0x8132, lo: 0x85, hi: 0x89}, + {value: 0x812d, lo: 0x8a, hi: 0x8b}, + {value: 0x8132, lo: 0xaa, hi: 0xad}, + {value: 0x45e0, lo: 0xbb, hi: 0xbb}, + {value: 0x45ea, lo: 0xbc, hi: 0xbc}, + {value: 0x4650, lo: 0xbd, hi: 0xbd}, + {value: 0x466c, lo: 0xbe, hi: 0xbe}, + {value: 0x465e, lo: 0xbf, hi: 0xbf}, + // Block 0x88, offset 0x29f + {value: 0x0000, lo: 0x01}, + {value: 0x467a, lo: 0x80, hi: 0x80}, + // Block 0x89, offset 0x2a1 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x82, hi: 0x84}, + // Block 0x8a, offset 0x2a3 + {value: 0x0000, lo: 0x05}, + {value: 0x8132, lo: 0x80, hi: 0x86}, + {value: 0x8132, lo: 0x88, hi: 0x98}, + {value: 0x8132, lo: 0x9b, hi: 0xa1}, + {value: 0x8132, lo: 0xa3, hi: 0xa4}, + {value: 0x8132, lo: 0xa6, hi: 0xaa}, + // Block 0x8b, offset 0x2a9 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x90, hi: 0x96}, + // Block 0x8c, offset 0x2ab + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x84, hi: 0x89}, + {value: 0x8102, lo: 0x8a, hi: 0x8a}, + // Block 0x8d, offset 0x2ae + {value: 0x0000, lo: 0x01}, + {value: 0x8100, lo: 0x93, hi: 0x93}, +} + +// lookup returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *nfkcTrie) lookup(s []byte) (v uint16, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return nfkcValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfkcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfkcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = nfkcIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *nfkcTrie) lookupUnsafe(s []byte) uint16 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return nfkcValues[c0] + } + i := nfkcIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = nfkcIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = nfkcIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// lookupString returns the trie value for the first UTF-8 encoding in s and +// the width in bytes of this encoding. The size will be 0 if s does not +// hold enough bytes to complete the encoding. len(s) must be greater than 0. +func (t *nfkcTrie) lookupString(s string) (v uint16, sz int) { + c0 := s[0] + switch { + case c0 < 0x80: // is ASCII + return nfkcValues[c0], 1 + case c0 < 0xC2: + return 0, 1 // Illegal UTF-8: not a starter, not ASCII. + case c0 < 0xE0: // 2-byte UTF-8 + if len(s) < 2 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c1), 2 + case c0 < 0xF0: // 3-byte UTF-8 + if len(s) < 3 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfkcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c2), 3 + case c0 < 0xF8: // 4-byte UTF-8 + if len(s) < 4 { + return 0, 0 + } + i := nfkcIndex[c0] + c1 := s[1] + if c1 < 0x80 || 0xC0 <= c1 { + return 0, 1 // Illegal UTF-8: not a continuation byte. + } + o := uint32(i)<<6 + uint32(c1) + i = nfkcIndex[o] + c2 := s[2] + if c2 < 0x80 || 0xC0 <= c2 { + return 0, 2 // Illegal UTF-8: not a continuation byte. + } + o = uint32(i)<<6 + uint32(c2) + i = nfkcIndex[o] + c3 := s[3] + if c3 < 0x80 || 0xC0 <= c3 { + return 0, 3 // Illegal UTF-8: not a continuation byte. + } + return t.lookupValue(uint32(i), c3), 4 + } + // Illegal rune + return 0, 1 +} + +// lookupStringUnsafe returns the trie value for the first UTF-8 encoding in s. +// s must start with a full and valid UTF-8 encoded rune. +func (t *nfkcTrie) lookupStringUnsafe(s string) uint16 { + c0 := s[0] + if c0 < 0x80 { // is ASCII + return nfkcValues[c0] + } + i := nfkcIndex[c0] + if c0 < 0xE0 { // 2-byte UTF-8 + return t.lookupValue(uint32(i), s[1]) + } + i = nfkcIndex[uint32(i)<<6+uint32(s[1])] + if c0 < 0xF0 { // 3-byte UTF-8 + return t.lookupValue(uint32(i), s[2]) + } + i = nfkcIndex[uint32(i)<<6+uint32(s[2])] + if c0 < 0xF8 { // 4-byte UTF-8 + return t.lookupValue(uint32(i), s[3]) + } + return 0 +} + +// nfkcTrie. Total size: 16994 bytes (16.60 KiB). Checksum: c3ed54ee046f3c46. +type nfkcTrie struct{} + +func newNfkcTrie(i int) *nfkcTrie { + return &nfkcTrie{} +} + +// lookupValue determines the type of block n and looks up the value for b. +func (t *nfkcTrie) lookupValue(n uint32, b byte) uint16 { + switch { + case n < 90: + return uint16(nfkcValues[n<<6+uint32(b)]) + default: + n -= 90 + return uint16(nfkcSparse.lookup(n, b)) + } +} + +// nfkcValues: 92 blocks, 5888 entries, 11776 bytes +// The third block is the zero block. +var nfkcValues = [5888]uint16{ + // Block 0x0, offset 0x0 + 0x3c: 0xa000, 0x3d: 0xa000, 0x3e: 0xa000, + // Block 0x1, offset 0x40 + 0x41: 0xa000, 0x42: 0xa000, 0x43: 0xa000, 0x44: 0xa000, 0x45: 0xa000, + 0x46: 0xa000, 0x47: 0xa000, 0x48: 0xa000, 0x49: 0xa000, 0x4a: 0xa000, 0x4b: 0xa000, + 0x4c: 0xa000, 0x4d: 0xa000, 0x4e: 0xa000, 0x4f: 0xa000, 0x50: 0xa000, + 0x52: 0xa000, 0x53: 0xa000, 0x54: 0xa000, 0x55: 0xa000, 0x56: 0xa000, 0x57: 0xa000, + 0x58: 0xa000, 0x59: 0xa000, 0x5a: 0xa000, + 0x61: 0xa000, 0x62: 0xa000, 0x63: 0xa000, + 0x64: 0xa000, 0x65: 0xa000, 0x66: 0xa000, 0x67: 0xa000, 0x68: 0xa000, 0x69: 0xa000, + 0x6a: 0xa000, 0x6b: 0xa000, 0x6c: 0xa000, 0x6d: 0xa000, 0x6e: 0xa000, 0x6f: 0xa000, + 0x70: 0xa000, 0x72: 0xa000, 0x73: 0xa000, 0x74: 0xa000, 0x75: 0xa000, + 0x76: 0xa000, 0x77: 0xa000, 0x78: 0xa000, 0x79: 0xa000, 0x7a: 0xa000, + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc0: 0x2f6f, 0xc1: 0x2f74, 0xc2: 0x4688, 0xc3: 0x2f79, 0xc4: 0x4697, 0xc5: 0x469c, + 0xc6: 0xa000, 0xc7: 0x46a6, 0xc8: 0x2fe2, 0xc9: 0x2fe7, 0xca: 0x46ab, 0xcb: 0x2ffb, + 0xcc: 0x306e, 0xcd: 0x3073, 0xce: 0x3078, 0xcf: 0x46bf, 0xd1: 0x3104, + 0xd2: 0x3127, 0xd3: 0x312c, 0xd4: 0x46c9, 0xd5: 0x46ce, 0xd6: 0x46dd, + 0xd8: 0xa000, 0xd9: 0x31b3, 0xda: 0x31b8, 0xdb: 0x31bd, 0xdc: 0x470f, 0xdd: 0x3235, + 0xe0: 0x327b, 0xe1: 0x3280, 0xe2: 0x4719, 0xe3: 0x3285, + 0xe4: 0x4728, 0xe5: 0x472d, 0xe6: 0xa000, 0xe7: 0x4737, 0xe8: 0x32ee, 0xe9: 0x32f3, + 0xea: 0x473c, 0xeb: 0x3307, 0xec: 0x337f, 0xed: 0x3384, 0xee: 0x3389, 0xef: 0x4750, + 0xf1: 0x3415, 0xf2: 0x3438, 0xf3: 0x343d, 0xf4: 0x475a, 0xf5: 0x475f, + 0xf6: 0x476e, 0xf8: 0xa000, 0xf9: 0x34c9, 0xfa: 0x34ce, 0xfb: 0x34d3, + 0xfc: 0x47a0, 0xfd: 0x3550, 0xff: 0x3569, + // Block 0x4, offset 0x100 + 0x100: 0x2f7e, 0x101: 0x328a, 0x102: 0x468d, 0x103: 0x471e, 0x104: 0x2f9c, 0x105: 0x32a8, + 0x106: 0x2fb0, 0x107: 0x32bc, 0x108: 0x2fb5, 0x109: 0x32c1, 0x10a: 0x2fba, 0x10b: 0x32c6, + 0x10c: 0x2fbf, 0x10d: 0x32cb, 0x10e: 0x2fc9, 0x10f: 0x32d5, + 0x112: 0x46b0, 0x113: 0x4741, 0x114: 0x2ff1, 0x115: 0x32fd, 0x116: 0x2ff6, 0x117: 0x3302, + 0x118: 0x3014, 0x119: 0x3320, 0x11a: 0x3005, 0x11b: 0x3311, 0x11c: 0x302d, 0x11d: 0x3339, + 0x11e: 0x3037, 0x11f: 0x3343, 0x120: 0x303c, 0x121: 0x3348, 0x122: 0x3046, 0x123: 0x3352, + 0x124: 0x304b, 0x125: 0x3357, 0x128: 0x307d, 0x129: 0x338e, + 0x12a: 0x3082, 0x12b: 0x3393, 0x12c: 0x3087, 0x12d: 0x3398, 0x12e: 0x30aa, 0x12f: 0x33b6, + 0x130: 0x308c, 0x132: 0x195d, 0x133: 0x19e7, 0x134: 0x30b4, 0x135: 0x33c0, + 0x136: 0x30c8, 0x137: 0x33d9, 0x139: 0x30d2, 0x13a: 0x33e3, 0x13b: 0x30dc, + 0x13c: 0x33ed, 0x13d: 0x30d7, 0x13e: 0x33e8, 0x13f: 0x1bac, + // Block 0x5, offset 0x140 + 0x140: 0x1c34, 0x143: 0x30ff, 0x144: 0x3410, 0x145: 0x3118, + 0x146: 0x3429, 0x147: 0x310e, 0x148: 0x341f, 0x149: 0x1c5c, + 0x14c: 0x46d3, 0x14d: 0x4764, 0x14e: 0x3131, 0x14f: 0x3442, 0x150: 0x313b, 0x151: 0x344c, + 0x154: 0x3159, 0x155: 0x346a, 0x156: 0x3172, 0x157: 0x3483, + 0x158: 0x3163, 0x159: 0x3474, 0x15a: 0x46f6, 0x15b: 0x4787, 0x15c: 0x317c, 0x15d: 0x348d, + 0x15e: 0x318b, 0x15f: 0x349c, 0x160: 0x46fb, 0x161: 0x478c, 0x162: 0x31a4, 0x163: 0x34ba, + 0x164: 0x3195, 0x165: 0x34ab, 0x168: 0x4705, 0x169: 0x4796, + 0x16a: 0x470a, 0x16b: 0x479b, 0x16c: 0x31c2, 0x16d: 0x34d8, 0x16e: 0x31cc, 0x16f: 0x34e2, + 0x170: 0x31d1, 0x171: 0x34e7, 0x172: 0x31ef, 0x173: 0x3505, 0x174: 0x3212, 0x175: 0x3528, + 0x176: 0x323a, 0x177: 0x3555, 0x178: 0x324e, 0x179: 0x325d, 0x17a: 0x357d, 0x17b: 0x3267, + 0x17c: 0x3587, 0x17d: 0x326c, 0x17e: 0x358c, 0x17f: 0x00a7, + // Block 0x6, offset 0x180 + 0x184: 0x2dee, 0x185: 0x2df4, + 0x186: 0x2dfa, 0x187: 0x1972, 0x188: 0x1975, 0x189: 0x1a08, 0x18a: 0x1987, 0x18b: 0x198a, + 0x18c: 0x1a3e, 0x18d: 0x2f88, 0x18e: 0x3294, 0x18f: 0x3096, 0x190: 0x33a2, 0x191: 0x3140, + 0x192: 0x3451, 0x193: 0x31d6, 0x194: 0x34ec, 0x195: 0x39cf, 0x196: 0x3b5e, 0x197: 0x39c8, + 0x198: 0x3b57, 0x199: 0x39d6, 0x19a: 0x3b65, 0x19b: 0x39c1, 0x19c: 0x3b50, + 0x19e: 0x38b0, 0x19f: 0x3a3f, 0x1a0: 0x38a9, 0x1a1: 0x3a38, 0x1a2: 0x35b3, 0x1a3: 0x35c5, + 0x1a6: 0x3041, 0x1a7: 0x334d, 0x1a8: 0x30be, 0x1a9: 0x33cf, + 0x1aa: 0x46ec, 0x1ab: 0x477d, 0x1ac: 0x3990, 0x1ad: 0x3b1f, 0x1ae: 0x35d7, 0x1af: 0x35dd, + 0x1b0: 0x33c5, 0x1b1: 0x1942, 0x1b2: 0x1945, 0x1b3: 0x19cf, 0x1b4: 0x3028, 0x1b5: 0x3334, + 0x1b8: 0x30fa, 0x1b9: 0x340b, 0x1ba: 0x38b7, 0x1bb: 0x3a46, + 0x1bc: 0x35ad, 0x1bd: 0x35bf, 0x1be: 0x35b9, 0x1bf: 0x35cb, + // Block 0x7, offset 0x1c0 + 0x1c0: 0x2f8d, 0x1c1: 0x3299, 0x1c2: 0x2f92, 0x1c3: 0x329e, 0x1c4: 0x300a, 0x1c5: 0x3316, + 0x1c6: 0x300f, 0x1c7: 0x331b, 0x1c8: 0x309b, 0x1c9: 0x33a7, 0x1ca: 0x30a0, 0x1cb: 0x33ac, + 0x1cc: 0x3145, 0x1cd: 0x3456, 0x1ce: 0x314a, 0x1cf: 0x345b, 0x1d0: 0x3168, 0x1d1: 0x3479, + 0x1d2: 0x316d, 0x1d3: 0x347e, 0x1d4: 0x31db, 0x1d5: 0x34f1, 0x1d6: 0x31e0, 0x1d7: 0x34f6, + 0x1d8: 0x3186, 0x1d9: 0x3497, 0x1da: 0x319f, 0x1db: 0x34b5, + 0x1de: 0x305a, 0x1df: 0x3366, + 0x1e6: 0x4692, 0x1e7: 0x4723, 0x1e8: 0x46ba, 0x1e9: 0x474b, + 0x1ea: 0x395f, 0x1eb: 0x3aee, 0x1ec: 0x393c, 0x1ed: 0x3acb, 0x1ee: 0x46d8, 0x1ef: 0x4769, + 0x1f0: 0x3958, 0x1f1: 0x3ae7, 0x1f2: 0x3244, 0x1f3: 0x355f, + // Block 0x8, offset 0x200 + 0x200: 0x9932, 0x201: 0x9932, 0x202: 0x9932, 0x203: 0x9932, 0x204: 0x9932, 0x205: 0x8132, + 0x206: 0x9932, 0x207: 0x9932, 0x208: 0x9932, 0x209: 0x9932, 0x20a: 0x9932, 0x20b: 0x9932, + 0x20c: 0x9932, 0x20d: 0x8132, 0x20e: 0x8132, 0x20f: 0x9932, 0x210: 0x8132, 0x211: 0x9932, + 0x212: 0x8132, 0x213: 0x9932, 0x214: 0x9932, 0x215: 0x8133, 0x216: 0x812d, 0x217: 0x812d, + 0x218: 0x812d, 0x219: 0x812d, 0x21a: 0x8133, 0x21b: 0x992b, 0x21c: 0x812d, 0x21d: 0x812d, + 0x21e: 0x812d, 0x21f: 0x812d, 0x220: 0x812d, 0x221: 0x8129, 0x222: 0x8129, 0x223: 0x992d, + 0x224: 0x992d, 0x225: 0x992d, 0x226: 0x992d, 0x227: 0x9929, 0x228: 0x9929, 0x229: 0x812d, + 0x22a: 0x812d, 0x22b: 0x812d, 0x22c: 0x812d, 0x22d: 0x992d, 0x22e: 0x992d, 0x22f: 0x812d, + 0x230: 0x992d, 0x231: 0x992d, 0x232: 0x812d, 0x233: 0x812d, 0x234: 0x8101, 0x235: 0x8101, + 0x236: 0x8101, 0x237: 0x8101, 0x238: 0x9901, 0x239: 0x812d, 0x23a: 0x812d, 0x23b: 0x812d, + 0x23c: 0x812d, 0x23d: 0x8132, 0x23e: 0x8132, 0x23f: 0x8132, + // Block 0x9, offset 0x240 + 0x240: 0x49ae, 0x241: 0x49b3, 0x242: 0x9932, 0x243: 0x49b8, 0x244: 0x4a71, 0x245: 0x9936, + 0x246: 0x8132, 0x247: 0x812d, 0x248: 0x812d, 0x249: 0x812d, 0x24a: 0x8132, 0x24b: 0x8132, + 0x24c: 0x8132, 0x24d: 0x812d, 0x24e: 0x812d, 0x250: 0x8132, 0x251: 0x8132, + 0x252: 0x8132, 0x253: 0x812d, 0x254: 0x812d, 0x255: 0x812d, 0x256: 0x812d, 0x257: 0x8132, + 0x258: 0x8133, 0x259: 0x812d, 0x25a: 0x812d, 0x25b: 0x8132, 0x25c: 0x8134, 0x25d: 0x8135, + 0x25e: 0x8135, 0x25f: 0x8134, 0x260: 0x8135, 0x261: 0x8135, 0x262: 0x8134, 0x263: 0x8132, + 0x264: 0x8132, 0x265: 0x8132, 0x266: 0x8132, 0x267: 0x8132, 0x268: 0x8132, 0x269: 0x8132, + 0x26a: 0x8132, 0x26b: 0x8132, 0x26c: 0x8132, 0x26d: 0x8132, 0x26e: 0x8132, 0x26f: 0x8132, + 0x274: 0x0170, + 0x27a: 0x42a5, + 0x27e: 0x0037, + // Block 0xa, offset 0x280 + 0x284: 0x425a, 0x285: 0x447b, + 0x286: 0x35e9, 0x287: 0x00ce, 0x288: 0x3607, 0x289: 0x3613, 0x28a: 0x3625, + 0x28c: 0x3643, 0x28e: 0x3655, 0x28f: 0x3673, 0x290: 0x3e08, 0x291: 0xa000, + 0x295: 0xa000, 0x297: 0xa000, + 0x299: 0xa000, + 0x29f: 0xa000, 0x2a1: 0xa000, + 0x2a5: 0xa000, 0x2a9: 0xa000, + 0x2aa: 0x3637, 0x2ab: 0x3667, 0x2ac: 0x47fe, 0x2ad: 0x3697, 0x2ae: 0x4828, 0x2af: 0x36a9, + 0x2b0: 0x3e70, 0x2b1: 0xa000, 0x2b5: 0xa000, + 0x2b7: 0xa000, 0x2b9: 0xa000, + 0x2bf: 0xa000, + // Block 0xb, offset 0x2c0 + 0x2c1: 0xa000, 0x2c5: 0xa000, + 0x2c9: 0xa000, 0x2ca: 0x4840, 0x2cb: 0x485e, + 0x2cc: 0x36c7, 0x2cd: 0x36df, 0x2ce: 0x4876, 0x2d0: 0x01be, 0x2d1: 0x01d0, + 0x2d2: 0x01ac, 0x2d3: 0x430c, 0x2d4: 0x4312, 0x2d5: 0x01fa, 0x2d6: 0x01e8, + 0x2f0: 0x01d6, 0x2f1: 0x01eb, 0x2f2: 0x01ee, 0x2f4: 0x0188, 0x2f5: 0x01c7, + 0x2f9: 0x01a6, + // Block 0xc, offset 0x300 + 0x300: 0x3721, 0x301: 0x372d, 0x303: 0x371b, + 0x306: 0xa000, 0x307: 0x3709, + 0x30c: 0x375d, 0x30d: 0x3745, 0x30e: 0x376f, 0x310: 0xa000, + 0x313: 0xa000, 0x315: 0xa000, 0x316: 0xa000, 0x317: 0xa000, + 0x318: 0xa000, 0x319: 0x3751, 0x31a: 0xa000, + 0x31e: 0xa000, 0x323: 0xa000, + 0x327: 0xa000, + 0x32b: 0xa000, 0x32d: 0xa000, + 0x330: 0xa000, 0x333: 0xa000, 0x335: 0xa000, + 0x336: 0xa000, 0x337: 0xa000, 0x338: 0xa000, 0x339: 0x37d5, 0x33a: 0xa000, + 0x33e: 0xa000, + // Block 0xd, offset 0x340 + 0x341: 0x3733, 0x342: 0x37b7, + 0x350: 0x370f, 0x351: 0x3793, + 0x352: 0x3715, 0x353: 0x3799, 0x356: 0x3727, 0x357: 0x37ab, + 0x358: 0xa000, 0x359: 0xa000, 0x35a: 0x3829, 0x35b: 0x382f, 0x35c: 0x3739, 0x35d: 0x37bd, + 0x35e: 0x373f, 0x35f: 0x37c3, 0x362: 0x374b, 0x363: 0x37cf, + 0x364: 0x3757, 0x365: 0x37db, 0x366: 0x3763, 0x367: 0x37e7, 0x368: 0xa000, 0x369: 0xa000, + 0x36a: 0x3835, 0x36b: 0x383b, 0x36c: 0x378d, 0x36d: 0x3811, 0x36e: 0x3769, 0x36f: 0x37ed, + 0x370: 0x3775, 0x371: 0x37f9, 0x372: 0x377b, 0x373: 0x37ff, 0x374: 0x3781, 0x375: 0x3805, + 0x378: 0x3787, 0x379: 0x380b, + // Block 0xe, offset 0x380 + 0x387: 0x1d61, + 0x391: 0x812d, + 0x392: 0x8132, 0x393: 0x8132, 0x394: 0x8132, 0x395: 0x8132, 0x396: 0x812d, 0x397: 0x8132, + 0x398: 0x8132, 0x399: 0x8132, 0x39a: 0x812e, 0x39b: 0x812d, 0x39c: 0x8132, 0x39d: 0x8132, + 0x39e: 0x8132, 0x39f: 0x8132, 0x3a0: 0x8132, 0x3a1: 0x8132, 0x3a2: 0x812d, 0x3a3: 0x812d, + 0x3a4: 0x812d, 0x3a5: 0x812d, 0x3a6: 0x812d, 0x3a7: 0x812d, 0x3a8: 0x8132, 0x3a9: 0x8132, + 0x3aa: 0x812d, 0x3ab: 0x8132, 0x3ac: 0x8132, 0x3ad: 0x812e, 0x3ae: 0x8131, 0x3af: 0x8132, + 0x3b0: 0x8105, 0x3b1: 0x8106, 0x3b2: 0x8107, 0x3b3: 0x8108, 0x3b4: 0x8109, 0x3b5: 0x810a, + 0x3b6: 0x810b, 0x3b7: 0x810c, 0x3b8: 0x810d, 0x3b9: 0x810e, 0x3ba: 0x810e, 0x3bb: 0x810f, + 0x3bc: 0x8110, 0x3bd: 0x8111, 0x3bf: 0x8112, + // Block 0xf, offset 0x3c0 + 0x3c8: 0xa000, 0x3ca: 0xa000, 0x3cb: 0x8116, + 0x3cc: 0x8117, 0x3cd: 0x8118, 0x3ce: 0x8119, 0x3cf: 0x811a, 0x3d0: 0x811b, 0x3d1: 0x811c, + 0x3d2: 0x811d, 0x3d3: 0x9932, 0x3d4: 0x9932, 0x3d5: 0x992d, 0x3d6: 0x812d, 0x3d7: 0x8132, + 0x3d8: 0x8132, 0x3d9: 0x8132, 0x3da: 0x8132, 0x3db: 0x8132, 0x3dc: 0x812d, 0x3dd: 0x8132, + 0x3de: 0x8132, 0x3df: 0x812d, + 0x3f0: 0x811e, 0x3f5: 0x1d84, + 0x3f6: 0x2013, 0x3f7: 0x204f, 0x3f8: 0x204a, + // Block 0x10, offset 0x400 + 0x405: 0xa000, + 0x406: 0x2d26, 0x407: 0xa000, 0x408: 0x2d2e, 0x409: 0xa000, 0x40a: 0x2d36, 0x40b: 0xa000, + 0x40c: 0x2d3e, 0x40d: 0xa000, 0x40e: 0x2d46, 0x411: 0xa000, + 0x412: 0x2d4e, + 0x434: 0x8102, 0x435: 0x9900, + 0x43a: 0xa000, 0x43b: 0x2d56, + 0x43c: 0xa000, 0x43d: 0x2d5e, 0x43e: 0xa000, 0x43f: 0xa000, + // Block 0x11, offset 0x440 + 0x440: 0x0069, 0x441: 0x006b, 0x442: 0x006f, 0x443: 0x0083, 0x444: 0x00f5, 0x445: 0x00f8, + 0x446: 0x0413, 0x447: 0x0085, 0x448: 0x0089, 0x449: 0x008b, 0x44a: 0x0104, 0x44b: 0x0107, + 0x44c: 0x010a, 0x44d: 0x008f, 0x44f: 0x0097, 0x450: 0x009b, 0x451: 0x00e0, + 0x452: 0x009f, 0x453: 0x00fe, 0x454: 0x0417, 0x455: 0x041b, 0x456: 0x00a1, 0x457: 0x00a9, + 0x458: 0x00ab, 0x459: 0x0423, 0x45a: 0x012b, 0x45b: 0x00ad, 0x45c: 0x0427, 0x45d: 0x01be, + 0x45e: 0x01c1, 0x45f: 0x01c4, 0x460: 0x01fa, 0x461: 0x01fd, 0x462: 0x0093, 0x463: 0x00a5, + 0x464: 0x00ab, 0x465: 0x00ad, 0x466: 0x01be, 0x467: 0x01c1, 0x468: 0x01eb, 0x469: 0x01fa, + 0x46a: 0x01fd, + 0x478: 0x020c, + // Block 0x12, offset 0x480 + 0x49b: 0x00fb, 0x49c: 0x0087, 0x49d: 0x0101, + 0x49e: 0x00d4, 0x49f: 0x010a, 0x4a0: 0x008d, 0x4a1: 0x010d, 0x4a2: 0x0110, 0x4a3: 0x0116, + 0x4a4: 0x011c, 0x4a5: 0x011f, 0x4a6: 0x0122, 0x4a7: 0x042b, 0x4a8: 0x016a, 0x4a9: 0x0128, + 0x4aa: 0x042f, 0x4ab: 0x016d, 0x4ac: 0x0131, 0x4ad: 0x012e, 0x4ae: 0x0134, 0x4af: 0x0137, + 0x4b0: 0x013a, 0x4b1: 0x013d, 0x4b2: 0x0140, 0x4b3: 0x014c, 0x4b4: 0x014f, 0x4b5: 0x00ec, + 0x4b6: 0x0152, 0x4b7: 0x0155, 0x4b8: 0x041f, 0x4b9: 0x0158, 0x4ba: 0x015b, 0x4bb: 0x00b5, + 0x4bc: 0x015e, 0x4bd: 0x0161, 0x4be: 0x0164, 0x4bf: 0x01d0, + // Block 0x13, offset 0x4c0 + 0x4c0: 0x2f97, 0x4c1: 0x32a3, 0x4c2: 0x2fa1, 0x4c3: 0x32ad, 0x4c4: 0x2fa6, 0x4c5: 0x32b2, + 0x4c6: 0x2fab, 0x4c7: 0x32b7, 0x4c8: 0x38cc, 0x4c9: 0x3a5b, 0x4ca: 0x2fc4, 0x4cb: 0x32d0, + 0x4cc: 0x2fce, 0x4cd: 0x32da, 0x4ce: 0x2fdd, 0x4cf: 0x32e9, 0x4d0: 0x2fd3, 0x4d1: 0x32df, + 0x4d2: 0x2fd8, 0x4d3: 0x32e4, 0x4d4: 0x38ef, 0x4d5: 0x3a7e, 0x4d6: 0x38f6, 0x4d7: 0x3a85, + 0x4d8: 0x3019, 0x4d9: 0x3325, 0x4da: 0x301e, 0x4db: 0x332a, 0x4dc: 0x3904, 0x4dd: 0x3a93, + 0x4de: 0x3023, 0x4df: 0x332f, 0x4e0: 0x3032, 0x4e1: 0x333e, 0x4e2: 0x3050, 0x4e3: 0x335c, + 0x4e4: 0x305f, 0x4e5: 0x336b, 0x4e6: 0x3055, 0x4e7: 0x3361, 0x4e8: 0x3064, 0x4e9: 0x3370, + 0x4ea: 0x3069, 0x4eb: 0x3375, 0x4ec: 0x30af, 0x4ed: 0x33bb, 0x4ee: 0x390b, 0x4ef: 0x3a9a, + 0x4f0: 0x30b9, 0x4f1: 0x33ca, 0x4f2: 0x30c3, 0x4f3: 0x33d4, 0x4f4: 0x30cd, 0x4f5: 0x33de, + 0x4f6: 0x46c4, 0x4f7: 0x4755, 0x4f8: 0x3912, 0x4f9: 0x3aa1, 0x4fa: 0x30e6, 0x4fb: 0x33f7, + 0x4fc: 0x30e1, 0x4fd: 0x33f2, 0x4fe: 0x30eb, 0x4ff: 0x33fc, + // Block 0x14, offset 0x500 + 0x500: 0x30f0, 0x501: 0x3401, 0x502: 0x30f5, 0x503: 0x3406, 0x504: 0x3109, 0x505: 0x341a, + 0x506: 0x3113, 0x507: 0x3424, 0x508: 0x3122, 0x509: 0x3433, 0x50a: 0x311d, 0x50b: 0x342e, + 0x50c: 0x3935, 0x50d: 0x3ac4, 0x50e: 0x3943, 0x50f: 0x3ad2, 0x510: 0x394a, 0x511: 0x3ad9, + 0x512: 0x3951, 0x513: 0x3ae0, 0x514: 0x314f, 0x515: 0x3460, 0x516: 0x3154, 0x517: 0x3465, + 0x518: 0x315e, 0x519: 0x346f, 0x51a: 0x46f1, 0x51b: 0x4782, 0x51c: 0x3997, 0x51d: 0x3b26, + 0x51e: 0x3177, 0x51f: 0x3488, 0x520: 0x3181, 0x521: 0x3492, 0x522: 0x4700, 0x523: 0x4791, + 0x524: 0x399e, 0x525: 0x3b2d, 0x526: 0x39a5, 0x527: 0x3b34, 0x528: 0x39ac, 0x529: 0x3b3b, + 0x52a: 0x3190, 0x52b: 0x34a1, 0x52c: 0x319a, 0x52d: 0x34b0, 0x52e: 0x31ae, 0x52f: 0x34c4, + 0x530: 0x31a9, 0x531: 0x34bf, 0x532: 0x31ea, 0x533: 0x3500, 0x534: 0x31f9, 0x535: 0x350f, + 0x536: 0x31f4, 0x537: 0x350a, 0x538: 0x39b3, 0x539: 0x3b42, 0x53a: 0x39ba, 0x53b: 0x3b49, + 0x53c: 0x31fe, 0x53d: 0x3514, 0x53e: 0x3203, 0x53f: 0x3519, + // Block 0x15, offset 0x540 + 0x540: 0x3208, 0x541: 0x351e, 0x542: 0x320d, 0x543: 0x3523, 0x544: 0x321c, 0x545: 0x3532, + 0x546: 0x3217, 0x547: 0x352d, 0x548: 0x3221, 0x549: 0x353c, 0x54a: 0x3226, 0x54b: 0x3541, + 0x54c: 0x322b, 0x54d: 0x3546, 0x54e: 0x3249, 0x54f: 0x3564, 0x550: 0x3262, 0x551: 0x3582, + 0x552: 0x3271, 0x553: 0x3591, 0x554: 0x3276, 0x555: 0x3596, 0x556: 0x337a, 0x557: 0x34a6, + 0x558: 0x3537, 0x559: 0x3573, 0x55a: 0x1be0, 0x55b: 0x42d7, + 0x560: 0x46a1, 0x561: 0x4732, 0x562: 0x2f83, 0x563: 0x328f, + 0x564: 0x3878, 0x565: 0x3a07, 0x566: 0x3871, 0x567: 0x3a00, 0x568: 0x3886, 0x569: 0x3a15, + 0x56a: 0x387f, 0x56b: 0x3a0e, 0x56c: 0x38be, 0x56d: 0x3a4d, 0x56e: 0x3894, 0x56f: 0x3a23, + 0x570: 0x388d, 0x571: 0x3a1c, 0x572: 0x38a2, 0x573: 0x3a31, 0x574: 0x389b, 0x575: 0x3a2a, + 0x576: 0x38c5, 0x577: 0x3a54, 0x578: 0x46b5, 0x579: 0x4746, 0x57a: 0x3000, 0x57b: 0x330c, + 0x57c: 0x2fec, 0x57d: 0x32f8, 0x57e: 0x38da, 0x57f: 0x3a69, + // Block 0x16, offset 0x580 + 0x580: 0x38d3, 0x581: 0x3a62, 0x582: 0x38e8, 0x583: 0x3a77, 0x584: 0x38e1, 0x585: 0x3a70, + 0x586: 0x38fd, 0x587: 0x3a8c, 0x588: 0x3091, 0x589: 0x339d, 0x58a: 0x30a5, 0x58b: 0x33b1, + 0x58c: 0x46e7, 0x58d: 0x4778, 0x58e: 0x3136, 0x58f: 0x3447, 0x590: 0x3920, 0x591: 0x3aaf, + 0x592: 0x3919, 0x593: 0x3aa8, 0x594: 0x392e, 0x595: 0x3abd, 0x596: 0x3927, 0x597: 0x3ab6, + 0x598: 0x3989, 0x599: 0x3b18, 0x59a: 0x396d, 0x59b: 0x3afc, 0x59c: 0x3966, 0x59d: 0x3af5, + 0x59e: 0x397b, 0x59f: 0x3b0a, 0x5a0: 0x3974, 0x5a1: 0x3b03, 0x5a2: 0x3982, 0x5a3: 0x3b11, + 0x5a4: 0x31e5, 0x5a5: 0x34fb, 0x5a6: 0x31c7, 0x5a7: 0x34dd, 0x5a8: 0x39e4, 0x5a9: 0x3b73, + 0x5aa: 0x39dd, 0x5ab: 0x3b6c, 0x5ac: 0x39f2, 0x5ad: 0x3b81, 0x5ae: 0x39eb, 0x5af: 0x3b7a, + 0x5b0: 0x39f9, 0x5b1: 0x3b88, 0x5b2: 0x3230, 0x5b3: 0x354b, 0x5b4: 0x3258, 0x5b5: 0x3578, + 0x5b6: 0x3253, 0x5b7: 0x356e, 0x5b8: 0x323f, 0x5b9: 0x355a, + // Block 0x17, offset 0x5c0 + 0x5c0: 0x4804, 0x5c1: 0x480a, 0x5c2: 0x491e, 0x5c3: 0x4936, 0x5c4: 0x4926, 0x5c5: 0x493e, + 0x5c6: 0x492e, 0x5c7: 0x4946, 0x5c8: 0x47aa, 0x5c9: 0x47b0, 0x5ca: 0x488e, 0x5cb: 0x48a6, + 0x5cc: 0x4896, 0x5cd: 0x48ae, 0x5ce: 0x489e, 0x5cf: 0x48b6, 0x5d0: 0x4816, 0x5d1: 0x481c, + 0x5d2: 0x3db8, 0x5d3: 0x3dc8, 0x5d4: 0x3dc0, 0x5d5: 0x3dd0, + 0x5d8: 0x47b6, 0x5d9: 0x47bc, 0x5da: 0x3ce8, 0x5db: 0x3cf8, 0x5dc: 0x3cf0, 0x5dd: 0x3d00, + 0x5e0: 0x482e, 0x5e1: 0x4834, 0x5e2: 0x494e, 0x5e3: 0x4966, + 0x5e4: 0x4956, 0x5e5: 0x496e, 0x5e6: 0x495e, 0x5e7: 0x4976, 0x5e8: 0x47c2, 0x5e9: 0x47c8, + 0x5ea: 0x48be, 0x5eb: 0x48d6, 0x5ec: 0x48c6, 0x5ed: 0x48de, 0x5ee: 0x48ce, 0x5ef: 0x48e6, + 0x5f0: 0x4846, 0x5f1: 0x484c, 0x5f2: 0x3e18, 0x5f3: 0x3e30, 0x5f4: 0x3e20, 0x5f5: 0x3e38, + 0x5f6: 0x3e28, 0x5f7: 0x3e40, 0x5f8: 0x47ce, 0x5f9: 0x47d4, 0x5fa: 0x3d18, 0x5fb: 0x3d30, + 0x5fc: 0x3d20, 0x5fd: 0x3d38, 0x5fe: 0x3d28, 0x5ff: 0x3d40, + // Block 0x18, offset 0x600 + 0x600: 0x4852, 0x601: 0x4858, 0x602: 0x3e48, 0x603: 0x3e58, 0x604: 0x3e50, 0x605: 0x3e60, + 0x608: 0x47da, 0x609: 0x47e0, 0x60a: 0x3d48, 0x60b: 0x3d58, + 0x60c: 0x3d50, 0x60d: 0x3d60, 0x610: 0x4864, 0x611: 0x486a, + 0x612: 0x3e80, 0x613: 0x3e98, 0x614: 0x3e88, 0x615: 0x3ea0, 0x616: 0x3e90, 0x617: 0x3ea8, + 0x619: 0x47e6, 0x61b: 0x3d68, 0x61d: 0x3d70, + 0x61f: 0x3d78, 0x620: 0x487c, 0x621: 0x4882, 0x622: 0x497e, 0x623: 0x4996, + 0x624: 0x4986, 0x625: 0x499e, 0x626: 0x498e, 0x627: 0x49a6, 0x628: 0x47ec, 0x629: 0x47f2, + 0x62a: 0x48ee, 0x62b: 0x4906, 0x62c: 0x48f6, 0x62d: 0x490e, 0x62e: 0x48fe, 0x62f: 0x4916, + 0x630: 0x47f8, 0x631: 0x431e, 0x632: 0x3691, 0x633: 0x4324, 0x634: 0x4822, 0x635: 0x432a, + 0x636: 0x36a3, 0x637: 0x4330, 0x638: 0x36c1, 0x639: 0x4336, 0x63a: 0x36d9, 0x63b: 0x433c, + 0x63c: 0x4870, 0x63d: 0x4342, + // Block 0x19, offset 0x640 + 0x640: 0x3da0, 0x641: 0x3da8, 0x642: 0x4184, 0x643: 0x41a2, 0x644: 0x418e, 0x645: 0x41ac, + 0x646: 0x4198, 0x647: 0x41b6, 0x648: 0x3cd8, 0x649: 0x3ce0, 0x64a: 0x40d0, 0x64b: 0x40ee, + 0x64c: 0x40da, 0x64d: 0x40f8, 0x64e: 0x40e4, 0x64f: 0x4102, 0x650: 0x3de8, 0x651: 0x3df0, + 0x652: 0x41c0, 0x653: 0x41de, 0x654: 0x41ca, 0x655: 0x41e8, 0x656: 0x41d4, 0x657: 0x41f2, + 0x658: 0x3d08, 0x659: 0x3d10, 0x65a: 0x410c, 0x65b: 0x412a, 0x65c: 0x4116, 0x65d: 0x4134, + 0x65e: 0x4120, 0x65f: 0x413e, 0x660: 0x3ec0, 0x661: 0x3ec8, 0x662: 0x41fc, 0x663: 0x421a, + 0x664: 0x4206, 0x665: 0x4224, 0x666: 0x4210, 0x667: 0x422e, 0x668: 0x3d80, 0x669: 0x3d88, + 0x66a: 0x4148, 0x66b: 0x4166, 0x66c: 0x4152, 0x66d: 0x4170, 0x66e: 0x415c, 0x66f: 0x417a, + 0x670: 0x3685, 0x671: 0x367f, 0x672: 0x3d90, 0x673: 0x368b, 0x674: 0x3d98, + 0x676: 0x4810, 0x677: 0x3db0, 0x678: 0x35f5, 0x679: 0x35ef, 0x67a: 0x35e3, 0x67b: 0x42ee, + 0x67c: 0x35fb, 0x67d: 0x4287, 0x67e: 0x01d3, 0x67f: 0x4287, + // Block 0x1a, offset 0x680 + 0x680: 0x42a0, 0x681: 0x4482, 0x682: 0x3dd8, 0x683: 0x369d, 0x684: 0x3de0, + 0x686: 0x483a, 0x687: 0x3df8, 0x688: 0x3601, 0x689: 0x42f4, 0x68a: 0x360d, 0x68b: 0x42fa, + 0x68c: 0x3619, 0x68d: 0x4489, 0x68e: 0x4490, 0x68f: 0x4497, 0x690: 0x36b5, 0x691: 0x36af, + 0x692: 0x3e00, 0x693: 0x44e4, 0x696: 0x36bb, 0x697: 0x3e10, + 0x698: 0x3631, 0x699: 0x362b, 0x69a: 0x361f, 0x69b: 0x4300, 0x69d: 0x449e, + 0x69e: 0x44a5, 0x69f: 0x44ac, 0x6a0: 0x36eb, 0x6a1: 0x36e5, 0x6a2: 0x3e68, 0x6a3: 0x44ec, + 0x6a4: 0x36cd, 0x6a5: 0x36d3, 0x6a6: 0x36f1, 0x6a7: 0x3e78, 0x6a8: 0x3661, 0x6a9: 0x365b, + 0x6aa: 0x364f, 0x6ab: 0x430c, 0x6ac: 0x3649, 0x6ad: 0x4474, 0x6ae: 0x447b, 0x6af: 0x0081, + 0x6b2: 0x3eb0, 0x6b3: 0x36f7, 0x6b4: 0x3eb8, + 0x6b6: 0x4888, 0x6b7: 0x3ed0, 0x6b8: 0x363d, 0x6b9: 0x4306, 0x6ba: 0x366d, 0x6bb: 0x4318, + 0x6bc: 0x3679, 0x6bd: 0x425a, 0x6be: 0x428c, + // Block 0x1b, offset 0x6c0 + 0x6c0: 0x1bd8, 0x6c1: 0x1bdc, 0x6c2: 0x0047, 0x6c3: 0x1c54, 0x6c5: 0x1be8, + 0x6c6: 0x1bec, 0x6c7: 0x00e9, 0x6c9: 0x1c58, 0x6ca: 0x008f, 0x6cb: 0x0051, + 0x6cc: 0x0051, 0x6cd: 0x0051, 0x6ce: 0x0091, 0x6cf: 0x00da, 0x6d0: 0x0053, 0x6d1: 0x0053, + 0x6d2: 0x0059, 0x6d3: 0x0099, 0x6d5: 0x005d, 0x6d6: 0x198d, + 0x6d9: 0x0061, 0x6da: 0x0063, 0x6db: 0x0065, 0x6dc: 0x0065, 0x6dd: 0x0065, + 0x6e0: 0x199f, 0x6e1: 0x1bc8, 0x6e2: 0x19a8, + 0x6e4: 0x0075, 0x6e6: 0x01b8, 0x6e8: 0x0075, + 0x6ea: 0x0057, 0x6eb: 0x42d2, 0x6ec: 0x0045, 0x6ed: 0x0047, 0x6ef: 0x008b, + 0x6f0: 0x004b, 0x6f1: 0x004d, 0x6f3: 0x005b, 0x6f4: 0x009f, 0x6f5: 0x0215, + 0x6f6: 0x0218, 0x6f7: 0x021b, 0x6f8: 0x021e, 0x6f9: 0x0093, 0x6fb: 0x1b98, + 0x6fc: 0x01e8, 0x6fd: 0x01c1, 0x6fe: 0x0179, 0x6ff: 0x01a0, + // Block 0x1c, offset 0x700 + 0x700: 0x0463, 0x705: 0x0049, + 0x706: 0x0089, 0x707: 0x008b, 0x708: 0x0093, 0x709: 0x0095, + 0x710: 0x222e, 0x711: 0x223a, + 0x712: 0x22ee, 0x713: 0x2216, 0x714: 0x229a, 0x715: 0x2222, 0x716: 0x22a0, 0x717: 0x22b8, + 0x718: 0x22c4, 0x719: 0x2228, 0x71a: 0x22ca, 0x71b: 0x2234, 0x71c: 0x22be, 0x71d: 0x22d0, + 0x71e: 0x22d6, 0x71f: 0x1cbc, 0x720: 0x0053, 0x721: 0x195a, 0x722: 0x1ba4, 0x723: 0x1963, + 0x724: 0x006d, 0x725: 0x19ab, 0x726: 0x1bd0, 0x727: 0x1d48, 0x728: 0x1966, 0x729: 0x0071, + 0x72a: 0x19b7, 0x72b: 0x1bd4, 0x72c: 0x0059, 0x72d: 0x0047, 0x72e: 0x0049, 0x72f: 0x005b, + 0x730: 0x0093, 0x731: 0x19e4, 0x732: 0x1c18, 0x733: 0x19ed, 0x734: 0x00ad, 0x735: 0x1a62, + 0x736: 0x1c4c, 0x737: 0x1d5c, 0x738: 0x19f0, 0x739: 0x00b1, 0x73a: 0x1a65, 0x73b: 0x1c50, + 0x73c: 0x0099, 0x73d: 0x0087, 0x73e: 0x0089, 0x73f: 0x009b, + // Block 0x1d, offset 0x740 + 0x741: 0x3c06, 0x743: 0xa000, 0x744: 0x3c0d, 0x745: 0xa000, + 0x747: 0x3c14, 0x748: 0xa000, 0x749: 0x3c1b, + 0x74d: 0xa000, + 0x760: 0x2f65, 0x761: 0xa000, 0x762: 0x3c29, + 0x764: 0xa000, 0x765: 0xa000, + 0x76d: 0x3c22, 0x76e: 0x2f60, 0x76f: 0x2f6a, + 0x770: 0x3c30, 0x771: 0x3c37, 0x772: 0xa000, 0x773: 0xa000, 0x774: 0x3c3e, 0x775: 0x3c45, + 0x776: 0xa000, 0x777: 0xa000, 0x778: 0x3c4c, 0x779: 0x3c53, 0x77a: 0xa000, 0x77b: 0xa000, + 0x77c: 0xa000, 0x77d: 0xa000, + // Block 0x1e, offset 0x780 + 0x780: 0x3c5a, 0x781: 0x3c61, 0x782: 0xa000, 0x783: 0xa000, 0x784: 0x3c76, 0x785: 0x3c7d, + 0x786: 0xa000, 0x787: 0xa000, 0x788: 0x3c84, 0x789: 0x3c8b, + 0x791: 0xa000, + 0x792: 0xa000, + 0x7a2: 0xa000, + 0x7a8: 0xa000, 0x7a9: 0xa000, + 0x7ab: 0xa000, 0x7ac: 0x3ca0, 0x7ad: 0x3ca7, 0x7ae: 0x3cae, 0x7af: 0x3cb5, + 0x7b2: 0xa000, 0x7b3: 0xa000, 0x7b4: 0xa000, 0x7b5: 0xa000, + // Block 0x1f, offset 0x7c0 + 0x7e0: 0x0023, 0x7e1: 0x0025, 0x7e2: 0x0027, 0x7e3: 0x0029, + 0x7e4: 0x002b, 0x7e5: 0x002d, 0x7e6: 0x002f, 0x7e7: 0x0031, 0x7e8: 0x0033, 0x7e9: 0x1882, + 0x7ea: 0x1885, 0x7eb: 0x1888, 0x7ec: 0x188b, 0x7ed: 0x188e, 0x7ee: 0x1891, 0x7ef: 0x1894, + 0x7f0: 0x1897, 0x7f1: 0x189a, 0x7f2: 0x189d, 0x7f3: 0x18a6, 0x7f4: 0x1a68, 0x7f5: 0x1a6c, + 0x7f6: 0x1a70, 0x7f7: 0x1a74, 0x7f8: 0x1a78, 0x7f9: 0x1a7c, 0x7fa: 0x1a80, 0x7fb: 0x1a84, + 0x7fc: 0x1a88, 0x7fd: 0x1c80, 0x7fe: 0x1c85, 0x7ff: 0x1c8a, + // Block 0x20, offset 0x800 + 0x800: 0x1c8f, 0x801: 0x1c94, 0x802: 0x1c99, 0x803: 0x1c9e, 0x804: 0x1ca3, 0x805: 0x1ca8, + 0x806: 0x1cad, 0x807: 0x1cb2, 0x808: 0x187f, 0x809: 0x18a3, 0x80a: 0x18c7, 0x80b: 0x18eb, + 0x80c: 0x190f, 0x80d: 0x1918, 0x80e: 0x191e, 0x80f: 0x1924, 0x810: 0x192a, 0x811: 0x1b60, + 0x812: 0x1b64, 0x813: 0x1b68, 0x814: 0x1b6c, 0x815: 0x1b70, 0x816: 0x1b74, 0x817: 0x1b78, + 0x818: 0x1b7c, 0x819: 0x1b80, 0x81a: 0x1b84, 0x81b: 0x1b88, 0x81c: 0x1af4, 0x81d: 0x1af8, + 0x81e: 0x1afc, 0x81f: 0x1b00, 0x820: 0x1b04, 0x821: 0x1b08, 0x822: 0x1b0c, 0x823: 0x1b10, + 0x824: 0x1b14, 0x825: 0x1b18, 0x826: 0x1b1c, 0x827: 0x1b20, 0x828: 0x1b24, 0x829: 0x1b28, + 0x82a: 0x1b2c, 0x82b: 0x1b30, 0x82c: 0x1b34, 0x82d: 0x1b38, 0x82e: 0x1b3c, 0x82f: 0x1b40, + 0x830: 0x1b44, 0x831: 0x1b48, 0x832: 0x1b4c, 0x833: 0x1b50, 0x834: 0x1b54, 0x835: 0x1b58, + 0x836: 0x0043, 0x837: 0x0045, 0x838: 0x0047, 0x839: 0x0049, 0x83a: 0x004b, 0x83b: 0x004d, + 0x83c: 0x004f, 0x83d: 0x0051, 0x83e: 0x0053, 0x83f: 0x0055, + // Block 0x21, offset 0x840 + 0x840: 0x06bf, 0x841: 0x06e3, 0x842: 0x06ef, 0x843: 0x06ff, 0x844: 0x0707, 0x845: 0x0713, + 0x846: 0x071b, 0x847: 0x0723, 0x848: 0x072f, 0x849: 0x0783, 0x84a: 0x079b, 0x84b: 0x07ab, + 0x84c: 0x07bb, 0x84d: 0x07cb, 0x84e: 0x07db, 0x84f: 0x07fb, 0x850: 0x07ff, 0x851: 0x0803, + 0x852: 0x0837, 0x853: 0x085f, 0x854: 0x086f, 0x855: 0x0877, 0x856: 0x087b, 0x857: 0x0887, + 0x858: 0x08a3, 0x859: 0x08a7, 0x85a: 0x08bf, 0x85b: 0x08c3, 0x85c: 0x08cb, 0x85d: 0x08db, + 0x85e: 0x0977, 0x85f: 0x098b, 0x860: 0x09cb, 0x861: 0x09df, 0x862: 0x09e7, 0x863: 0x09eb, + 0x864: 0x09fb, 0x865: 0x0a17, 0x866: 0x0a43, 0x867: 0x0a4f, 0x868: 0x0a6f, 0x869: 0x0a7b, + 0x86a: 0x0a7f, 0x86b: 0x0a83, 0x86c: 0x0a9b, 0x86d: 0x0a9f, 0x86e: 0x0acb, 0x86f: 0x0ad7, + 0x870: 0x0adf, 0x871: 0x0ae7, 0x872: 0x0af7, 0x873: 0x0aff, 0x874: 0x0b07, 0x875: 0x0b33, + 0x876: 0x0b37, 0x877: 0x0b3f, 0x878: 0x0b43, 0x879: 0x0b4b, 0x87a: 0x0b53, 0x87b: 0x0b63, + 0x87c: 0x0b7f, 0x87d: 0x0bf7, 0x87e: 0x0c0b, 0x87f: 0x0c0f, + // Block 0x22, offset 0x880 + 0x880: 0x0c8f, 0x881: 0x0c93, 0x882: 0x0ca7, 0x883: 0x0cab, 0x884: 0x0cb3, 0x885: 0x0cbb, + 0x886: 0x0cc3, 0x887: 0x0ccf, 0x888: 0x0cf7, 0x889: 0x0d07, 0x88a: 0x0d1b, 0x88b: 0x0d8b, + 0x88c: 0x0d97, 0x88d: 0x0da7, 0x88e: 0x0db3, 0x88f: 0x0dbf, 0x890: 0x0dc7, 0x891: 0x0dcb, + 0x892: 0x0dcf, 0x893: 0x0dd3, 0x894: 0x0dd7, 0x895: 0x0e8f, 0x896: 0x0ed7, 0x897: 0x0ee3, + 0x898: 0x0ee7, 0x899: 0x0eeb, 0x89a: 0x0eef, 0x89b: 0x0ef7, 0x89c: 0x0efb, 0x89d: 0x0f0f, + 0x89e: 0x0f2b, 0x89f: 0x0f33, 0x8a0: 0x0f73, 0x8a1: 0x0f77, 0x8a2: 0x0f7f, 0x8a3: 0x0f83, + 0x8a4: 0x0f8b, 0x8a5: 0x0f8f, 0x8a6: 0x0fb3, 0x8a7: 0x0fb7, 0x8a8: 0x0fd3, 0x8a9: 0x0fd7, + 0x8aa: 0x0fdb, 0x8ab: 0x0fdf, 0x8ac: 0x0ff3, 0x8ad: 0x1017, 0x8ae: 0x101b, 0x8af: 0x101f, + 0x8b0: 0x1043, 0x8b1: 0x1083, 0x8b2: 0x1087, 0x8b3: 0x10a7, 0x8b4: 0x10b7, 0x8b5: 0x10bf, + 0x8b6: 0x10df, 0x8b7: 0x1103, 0x8b8: 0x1147, 0x8b9: 0x114f, 0x8ba: 0x1163, 0x8bb: 0x116f, + 0x8bc: 0x1177, 0x8bd: 0x117f, 0x8be: 0x1183, 0x8bf: 0x1187, + // Block 0x23, offset 0x8c0 + 0x8c0: 0x119f, 0x8c1: 0x11a3, 0x8c2: 0x11bf, 0x8c3: 0x11c7, 0x8c4: 0x11cf, 0x8c5: 0x11d3, + 0x8c6: 0x11df, 0x8c7: 0x11e7, 0x8c8: 0x11eb, 0x8c9: 0x11ef, 0x8ca: 0x11f7, 0x8cb: 0x11fb, + 0x8cc: 0x129b, 0x8cd: 0x12af, 0x8ce: 0x12e3, 0x8cf: 0x12e7, 0x8d0: 0x12ef, 0x8d1: 0x131b, + 0x8d2: 0x1323, 0x8d3: 0x132b, 0x8d4: 0x1333, 0x8d5: 0x136f, 0x8d6: 0x1373, 0x8d7: 0x137b, + 0x8d8: 0x137f, 0x8d9: 0x1383, 0x8da: 0x13af, 0x8db: 0x13b3, 0x8dc: 0x13bb, 0x8dd: 0x13cf, + 0x8de: 0x13d3, 0x8df: 0x13ef, 0x8e0: 0x13f7, 0x8e1: 0x13fb, 0x8e2: 0x141f, 0x8e3: 0x143f, + 0x8e4: 0x1453, 0x8e5: 0x1457, 0x8e6: 0x145f, 0x8e7: 0x148b, 0x8e8: 0x148f, 0x8e9: 0x149f, + 0x8ea: 0x14c3, 0x8eb: 0x14cf, 0x8ec: 0x14df, 0x8ed: 0x14f7, 0x8ee: 0x14ff, 0x8ef: 0x1503, + 0x8f0: 0x1507, 0x8f1: 0x150b, 0x8f2: 0x1517, 0x8f3: 0x151b, 0x8f4: 0x1523, 0x8f5: 0x153f, + 0x8f6: 0x1543, 0x8f7: 0x1547, 0x8f8: 0x155f, 0x8f9: 0x1563, 0x8fa: 0x156b, 0x8fb: 0x157f, + 0x8fc: 0x1583, 0x8fd: 0x1587, 0x8fe: 0x158f, 0x8ff: 0x1593, + // Block 0x24, offset 0x900 + 0x906: 0xa000, 0x90b: 0xa000, + 0x90c: 0x3f08, 0x90d: 0xa000, 0x90e: 0x3f10, 0x90f: 0xa000, 0x910: 0x3f18, 0x911: 0xa000, + 0x912: 0x3f20, 0x913: 0xa000, 0x914: 0x3f28, 0x915: 0xa000, 0x916: 0x3f30, 0x917: 0xa000, + 0x918: 0x3f38, 0x919: 0xa000, 0x91a: 0x3f40, 0x91b: 0xa000, 0x91c: 0x3f48, 0x91d: 0xa000, + 0x91e: 0x3f50, 0x91f: 0xa000, 0x920: 0x3f58, 0x921: 0xa000, 0x922: 0x3f60, + 0x924: 0xa000, 0x925: 0x3f68, 0x926: 0xa000, 0x927: 0x3f70, 0x928: 0xa000, 0x929: 0x3f78, + 0x92f: 0xa000, + 0x930: 0x3f80, 0x931: 0x3f88, 0x932: 0xa000, 0x933: 0x3f90, 0x934: 0x3f98, 0x935: 0xa000, + 0x936: 0x3fa0, 0x937: 0x3fa8, 0x938: 0xa000, 0x939: 0x3fb0, 0x93a: 0x3fb8, 0x93b: 0xa000, + 0x93c: 0x3fc0, 0x93d: 0x3fc8, + // Block 0x25, offset 0x940 + 0x954: 0x3f00, + 0x959: 0x9903, 0x95a: 0x9903, 0x95b: 0x42dc, 0x95c: 0x42e2, 0x95d: 0xa000, + 0x95e: 0x3fd0, 0x95f: 0x26b4, + 0x966: 0xa000, + 0x96b: 0xa000, 0x96c: 0x3fe0, 0x96d: 0xa000, 0x96e: 0x3fe8, 0x96f: 0xa000, + 0x970: 0x3ff0, 0x971: 0xa000, 0x972: 0x3ff8, 0x973: 0xa000, 0x974: 0x4000, 0x975: 0xa000, + 0x976: 0x4008, 0x977: 0xa000, 0x978: 0x4010, 0x979: 0xa000, 0x97a: 0x4018, 0x97b: 0xa000, + 0x97c: 0x4020, 0x97d: 0xa000, 0x97e: 0x4028, 0x97f: 0xa000, + // Block 0x26, offset 0x980 + 0x980: 0x4030, 0x981: 0xa000, 0x982: 0x4038, 0x984: 0xa000, 0x985: 0x4040, + 0x986: 0xa000, 0x987: 0x4048, 0x988: 0xa000, 0x989: 0x4050, + 0x98f: 0xa000, 0x990: 0x4058, 0x991: 0x4060, + 0x992: 0xa000, 0x993: 0x4068, 0x994: 0x4070, 0x995: 0xa000, 0x996: 0x4078, 0x997: 0x4080, + 0x998: 0xa000, 0x999: 0x4088, 0x99a: 0x4090, 0x99b: 0xa000, 0x99c: 0x4098, 0x99d: 0x40a0, + 0x9af: 0xa000, + 0x9b0: 0xa000, 0x9b1: 0xa000, 0x9b2: 0xa000, 0x9b4: 0x3fd8, + 0x9b7: 0x40a8, 0x9b8: 0x40b0, 0x9b9: 0x40b8, 0x9ba: 0x40c0, + 0x9bd: 0xa000, 0x9be: 0x40c8, 0x9bf: 0x26c9, + // Block 0x27, offset 0x9c0 + 0x9c0: 0x0367, 0x9c1: 0x032b, 0x9c2: 0x032f, 0x9c3: 0x0333, 0x9c4: 0x037b, 0x9c5: 0x0337, + 0x9c6: 0x033b, 0x9c7: 0x033f, 0x9c8: 0x0343, 0x9c9: 0x0347, 0x9ca: 0x034b, 0x9cb: 0x034f, + 0x9cc: 0x0353, 0x9cd: 0x0357, 0x9ce: 0x035b, 0x9cf: 0x49bd, 0x9d0: 0x49c3, 0x9d1: 0x49c9, + 0x9d2: 0x49cf, 0x9d3: 0x49d5, 0x9d4: 0x49db, 0x9d5: 0x49e1, 0x9d6: 0x49e7, 0x9d7: 0x49ed, + 0x9d8: 0x49f3, 0x9d9: 0x49f9, 0x9da: 0x49ff, 0x9db: 0x4a05, 0x9dc: 0x4a0b, 0x9dd: 0x4a11, + 0x9de: 0x4a17, 0x9df: 0x4a1d, 0x9e0: 0x4a23, 0x9e1: 0x4a29, 0x9e2: 0x4a2f, 0x9e3: 0x4a35, + 0x9e4: 0x03c3, 0x9e5: 0x035f, 0x9e6: 0x0363, 0x9e7: 0x03e7, 0x9e8: 0x03eb, 0x9e9: 0x03ef, + 0x9ea: 0x03f3, 0x9eb: 0x03f7, 0x9ec: 0x03fb, 0x9ed: 0x03ff, 0x9ee: 0x036b, 0x9ef: 0x0403, + 0x9f0: 0x0407, 0x9f1: 0x036f, 0x9f2: 0x0373, 0x9f3: 0x0377, 0x9f4: 0x037f, 0x9f5: 0x0383, + 0x9f6: 0x0387, 0x9f7: 0x038b, 0x9f8: 0x038f, 0x9f9: 0x0393, 0x9fa: 0x0397, 0x9fb: 0x039b, + 0x9fc: 0x039f, 0x9fd: 0x03a3, 0x9fe: 0x03a7, 0x9ff: 0x03ab, + // Block 0x28, offset 0xa00 + 0xa00: 0x03af, 0xa01: 0x03b3, 0xa02: 0x040b, 0xa03: 0x040f, 0xa04: 0x03b7, 0xa05: 0x03bb, + 0xa06: 0x03bf, 0xa07: 0x03c7, 0xa08: 0x03cb, 0xa09: 0x03cf, 0xa0a: 0x03d3, 0xa0b: 0x03d7, + 0xa0c: 0x03db, 0xa0d: 0x03df, 0xa0e: 0x03e3, + 0xa12: 0x06bf, 0xa13: 0x071b, 0xa14: 0x06cb, 0xa15: 0x097b, 0xa16: 0x06cf, 0xa17: 0x06e7, + 0xa18: 0x06d3, 0xa19: 0x0f93, 0xa1a: 0x0707, 0xa1b: 0x06db, 0xa1c: 0x06c3, 0xa1d: 0x09ff, + 0xa1e: 0x098f, 0xa1f: 0x072f, + // Block 0x29, offset 0xa40 + 0xa40: 0x2054, 0xa41: 0x205a, 0xa42: 0x2060, 0xa43: 0x2066, 0xa44: 0x206c, 0xa45: 0x2072, + 0xa46: 0x2078, 0xa47: 0x207e, 0xa48: 0x2084, 0xa49: 0x208a, 0xa4a: 0x2090, 0xa4b: 0x2096, + 0xa4c: 0x209c, 0xa4d: 0x20a2, 0xa4e: 0x2726, 0xa4f: 0x272f, 0xa50: 0x2738, 0xa51: 0x2741, + 0xa52: 0x274a, 0xa53: 0x2753, 0xa54: 0x275c, 0xa55: 0x2765, 0xa56: 0x276e, 0xa57: 0x2780, + 0xa58: 0x2789, 0xa59: 0x2792, 0xa5a: 0x279b, 0xa5b: 0x27a4, 0xa5c: 0x2777, 0xa5d: 0x2bac, + 0xa5e: 0x2aed, 0xa60: 0x20a8, 0xa61: 0x20c0, 0xa62: 0x20b4, 0xa63: 0x2108, + 0xa64: 0x20c6, 0xa65: 0x20e4, 0xa66: 0x20ae, 0xa67: 0x20de, 0xa68: 0x20ba, 0xa69: 0x20f0, + 0xa6a: 0x2120, 0xa6b: 0x213e, 0xa6c: 0x2138, 0xa6d: 0x212c, 0xa6e: 0x217a, 0xa6f: 0x210e, + 0xa70: 0x211a, 0xa71: 0x2132, 0xa72: 0x2126, 0xa73: 0x2150, 0xa74: 0x20fc, 0xa75: 0x2144, + 0xa76: 0x216e, 0xa77: 0x2156, 0xa78: 0x20ea, 0xa79: 0x20cc, 0xa7a: 0x2102, 0xa7b: 0x2114, + 0xa7c: 0x214a, 0xa7d: 0x20d2, 0xa7e: 0x2174, 0xa7f: 0x20f6, + // Block 0x2a, offset 0xa80 + 0xa80: 0x215c, 0xa81: 0x20d8, 0xa82: 0x2162, 0xa83: 0x2168, 0xa84: 0x092f, 0xa85: 0x0b03, + 0xa86: 0x0ca7, 0xa87: 0x10c7, + 0xa90: 0x1bc4, 0xa91: 0x18a9, + 0xa92: 0x18ac, 0xa93: 0x18af, 0xa94: 0x18b2, 0xa95: 0x18b5, 0xa96: 0x18b8, 0xa97: 0x18bb, + 0xa98: 0x18be, 0xa99: 0x18c1, 0xa9a: 0x18ca, 0xa9b: 0x18cd, 0xa9c: 0x18d0, 0xa9d: 0x18d3, + 0xa9e: 0x18d6, 0xa9f: 0x18d9, 0xaa0: 0x0313, 0xaa1: 0x031b, 0xaa2: 0x031f, 0xaa3: 0x0327, + 0xaa4: 0x032b, 0xaa5: 0x032f, 0xaa6: 0x0337, 0xaa7: 0x033f, 0xaa8: 0x0343, 0xaa9: 0x034b, + 0xaaa: 0x034f, 0xaab: 0x0353, 0xaac: 0x0357, 0xaad: 0x035b, 0xaae: 0x2e18, 0xaaf: 0x2e20, + 0xab0: 0x2e28, 0xab1: 0x2e30, 0xab2: 0x2e38, 0xab3: 0x2e40, 0xab4: 0x2e48, 0xab5: 0x2e50, + 0xab6: 0x2e60, 0xab7: 0x2e68, 0xab8: 0x2e70, 0xab9: 0x2e78, 0xaba: 0x2e80, 0xabb: 0x2e88, + 0xabc: 0x2ed3, 0xabd: 0x2e9b, 0xabe: 0x2e58, + // Block 0x2b, offset 0xac0 + 0xac0: 0x06bf, 0xac1: 0x071b, 0xac2: 0x06cb, 0xac3: 0x097b, 0xac4: 0x071f, 0xac5: 0x07af, + 0xac6: 0x06c7, 0xac7: 0x07ab, 0xac8: 0x070b, 0xac9: 0x0887, 0xaca: 0x0d07, 0xacb: 0x0e8f, + 0xacc: 0x0dd7, 0xacd: 0x0d1b, 0xace: 0x145f, 0xacf: 0x098b, 0xad0: 0x0ccf, 0xad1: 0x0d4b, + 0xad2: 0x0d0b, 0xad3: 0x104b, 0xad4: 0x08fb, 0xad5: 0x0f03, 0xad6: 0x1387, 0xad7: 0x105f, + 0xad8: 0x0843, 0xad9: 0x108f, 0xada: 0x0f9b, 0xadb: 0x0a17, 0xadc: 0x140f, 0xadd: 0x077f, + 0xade: 0x08ab, 0xadf: 0x0df7, 0xae0: 0x1527, 0xae1: 0x0743, 0xae2: 0x07d3, 0xae3: 0x0d9b, + 0xae4: 0x06cf, 0xae5: 0x06e7, 0xae6: 0x06d3, 0xae7: 0x0adb, 0xae8: 0x08ef, 0xae9: 0x087f, + 0xaea: 0x0a57, 0xaeb: 0x0a4b, 0xaec: 0x0feb, 0xaed: 0x073f, 0xaee: 0x139b, 0xaef: 0x089b, + 0xaf0: 0x09f3, 0xaf1: 0x18dc, 0xaf2: 0x18df, 0xaf3: 0x18e2, 0xaf4: 0x18e5, 0xaf5: 0x18ee, + 0xaf6: 0x18f1, 0xaf7: 0x18f4, 0xaf8: 0x18f7, 0xaf9: 0x18fa, 0xafa: 0x18fd, 0xafb: 0x1900, + 0xafc: 0x1903, 0xafd: 0x1906, 0xafe: 0x1909, 0xaff: 0x1912, + // Block 0x2c, offset 0xb00 + 0xb00: 0x1cc6, 0xb01: 0x1cd5, 0xb02: 0x1ce4, 0xb03: 0x1cf3, 0xb04: 0x1d02, 0xb05: 0x1d11, + 0xb06: 0x1d20, 0xb07: 0x1d2f, 0xb08: 0x1d3e, 0xb09: 0x218c, 0xb0a: 0x219e, 0xb0b: 0x21b0, + 0xb0c: 0x1954, 0xb0d: 0x1c04, 0xb0e: 0x19d2, 0xb0f: 0x1ba8, 0xb10: 0x04cb, 0xb11: 0x04d3, + 0xb12: 0x04db, 0xb13: 0x04e3, 0xb14: 0x04eb, 0xb15: 0x04ef, 0xb16: 0x04f3, 0xb17: 0x04f7, + 0xb18: 0x04fb, 0xb19: 0x04ff, 0xb1a: 0x0503, 0xb1b: 0x0507, 0xb1c: 0x050b, 0xb1d: 0x050f, + 0xb1e: 0x0513, 0xb1f: 0x0517, 0xb20: 0x051b, 0xb21: 0x0523, 0xb22: 0x0527, 0xb23: 0x052b, + 0xb24: 0x052f, 0xb25: 0x0533, 0xb26: 0x0537, 0xb27: 0x053b, 0xb28: 0x053f, 0xb29: 0x0543, + 0xb2a: 0x0547, 0xb2b: 0x054b, 0xb2c: 0x054f, 0xb2d: 0x0553, 0xb2e: 0x0557, 0xb2f: 0x055b, + 0xb30: 0x055f, 0xb31: 0x0563, 0xb32: 0x0567, 0xb33: 0x056f, 0xb34: 0x0577, 0xb35: 0x057f, + 0xb36: 0x0583, 0xb37: 0x0587, 0xb38: 0x058b, 0xb39: 0x058f, 0xb3a: 0x0593, 0xb3b: 0x0597, + 0xb3c: 0x059b, 0xb3d: 0x059f, 0xb3e: 0x05a3, + // Block 0x2d, offset 0xb40 + 0xb40: 0x2b0c, 0xb41: 0x29a8, 0xb42: 0x2b1c, 0xb43: 0x2880, 0xb44: 0x2ee4, 0xb45: 0x288a, + 0xb46: 0x2894, 0xb47: 0x2f28, 0xb48: 0x29b5, 0xb49: 0x289e, 0xb4a: 0x28a8, 0xb4b: 0x28b2, + 0xb4c: 0x29dc, 0xb4d: 0x29e9, 0xb4e: 0x29c2, 0xb4f: 0x29cf, 0xb50: 0x2ea9, 0xb51: 0x29f6, + 0xb52: 0x2a03, 0xb53: 0x2bbe, 0xb54: 0x26bb, 0xb55: 0x2bd1, 0xb56: 0x2be4, 0xb57: 0x2b2c, + 0xb58: 0x2a10, 0xb59: 0x2bf7, 0xb5a: 0x2c0a, 0xb5b: 0x2a1d, 0xb5c: 0x28bc, 0xb5d: 0x28c6, + 0xb5e: 0x2eb7, 0xb5f: 0x2a2a, 0xb60: 0x2b3c, 0xb61: 0x2ef5, 0xb62: 0x28d0, 0xb63: 0x28da, + 0xb64: 0x2a37, 0xb65: 0x28e4, 0xb66: 0x28ee, 0xb67: 0x26d0, 0xb68: 0x26d7, 0xb69: 0x28f8, + 0xb6a: 0x2902, 0xb6b: 0x2c1d, 0xb6c: 0x2a44, 0xb6d: 0x2b4c, 0xb6e: 0x2c30, 0xb6f: 0x2a51, + 0xb70: 0x2916, 0xb71: 0x290c, 0xb72: 0x2f3c, 0xb73: 0x2a5e, 0xb74: 0x2c43, 0xb75: 0x2920, + 0xb76: 0x2b5c, 0xb77: 0x292a, 0xb78: 0x2a78, 0xb79: 0x2934, 0xb7a: 0x2a85, 0xb7b: 0x2f06, + 0xb7c: 0x2a6b, 0xb7d: 0x2b6c, 0xb7e: 0x2a92, 0xb7f: 0x26de, + // Block 0x2e, offset 0xb80 + 0xb80: 0x2f17, 0xb81: 0x293e, 0xb82: 0x2948, 0xb83: 0x2a9f, 0xb84: 0x2952, 0xb85: 0x295c, + 0xb86: 0x2966, 0xb87: 0x2b7c, 0xb88: 0x2aac, 0xb89: 0x26e5, 0xb8a: 0x2c56, 0xb8b: 0x2e90, + 0xb8c: 0x2b8c, 0xb8d: 0x2ab9, 0xb8e: 0x2ec5, 0xb8f: 0x2970, 0xb90: 0x297a, 0xb91: 0x2ac6, + 0xb92: 0x26ec, 0xb93: 0x2ad3, 0xb94: 0x2b9c, 0xb95: 0x26f3, 0xb96: 0x2c69, 0xb97: 0x2984, + 0xb98: 0x1cb7, 0xb99: 0x1ccb, 0xb9a: 0x1cda, 0xb9b: 0x1ce9, 0xb9c: 0x1cf8, 0xb9d: 0x1d07, + 0xb9e: 0x1d16, 0xb9f: 0x1d25, 0xba0: 0x1d34, 0xba1: 0x1d43, 0xba2: 0x2192, 0xba3: 0x21a4, + 0xba4: 0x21b6, 0xba5: 0x21c2, 0xba6: 0x21ce, 0xba7: 0x21da, 0xba8: 0x21e6, 0xba9: 0x21f2, + 0xbaa: 0x21fe, 0xbab: 0x220a, 0xbac: 0x2246, 0xbad: 0x2252, 0xbae: 0x225e, 0xbaf: 0x226a, + 0xbb0: 0x2276, 0xbb1: 0x1c14, 0xbb2: 0x19c6, 0xbb3: 0x1936, 0xbb4: 0x1be4, 0xbb5: 0x1a47, + 0xbb6: 0x1a56, 0xbb7: 0x19cc, 0xbb8: 0x1bfc, 0xbb9: 0x1c00, 0xbba: 0x1960, 0xbbb: 0x2701, + 0xbbc: 0x270f, 0xbbd: 0x26fa, 0xbbe: 0x2708, 0xbbf: 0x2ae0, + // Block 0x2f, offset 0xbc0 + 0xbc0: 0x1a4a, 0xbc1: 0x1a32, 0xbc2: 0x1c60, 0xbc3: 0x1a1a, 0xbc4: 0x19f3, 0xbc5: 0x1969, + 0xbc6: 0x1978, 0xbc7: 0x1948, 0xbc8: 0x1bf0, 0xbc9: 0x1d52, 0xbca: 0x1a4d, 0xbcb: 0x1a35, + 0xbcc: 0x1c64, 0xbcd: 0x1c70, 0xbce: 0x1a26, 0xbcf: 0x19fc, 0xbd0: 0x1957, 0xbd1: 0x1c1c, + 0xbd2: 0x1bb0, 0xbd3: 0x1b9c, 0xbd4: 0x1bcc, 0xbd5: 0x1c74, 0xbd6: 0x1a29, 0xbd7: 0x19c9, + 0xbd8: 0x19ff, 0xbd9: 0x19de, 0xbda: 0x1a41, 0xbdb: 0x1c78, 0xbdc: 0x1a2c, 0xbdd: 0x19c0, + 0xbde: 0x1a02, 0xbdf: 0x1c3c, 0xbe0: 0x1bf4, 0xbe1: 0x1a14, 0xbe2: 0x1c24, 0xbe3: 0x1c40, + 0xbe4: 0x1bf8, 0xbe5: 0x1a17, 0xbe6: 0x1c28, 0xbe7: 0x22e8, 0xbe8: 0x22fc, 0xbe9: 0x1996, + 0xbea: 0x1c20, 0xbeb: 0x1bb4, 0xbec: 0x1ba0, 0xbed: 0x1c48, 0xbee: 0x2716, 0xbef: 0x27ad, + 0xbf0: 0x1a59, 0xbf1: 0x1a44, 0xbf2: 0x1c7c, 0xbf3: 0x1a2f, 0xbf4: 0x1a50, 0xbf5: 0x1a38, + 0xbf6: 0x1c68, 0xbf7: 0x1a1d, 0xbf8: 0x19f6, 0xbf9: 0x1981, 0xbfa: 0x1a53, 0xbfb: 0x1a3b, + 0xbfc: 0x1c6c, 0xbfd: 0x1a20, 0xbfe: 0x19f9, 0xbff: 0x1984, + // Block 0x30, offset 0xc00 + 0xc00: 0x1c2c, 0xc01: 0x1bb8, 0xc02: 0x1d4d, 0xc03: 0x1939, 0xc04: 0x19ba, 0xc05: 0x19bd, + 0xc06: 0x22f5, 0xc07: 0x1b94, 0xc08: 0x19c3, 0xc09: 0x194b, 0xc0a: 0x19e1, 0xc0b: 0x194e, + 0xc0c: 0x19ea, 0xc0d: 0x196c, 0xc0e: 0x196f, 0xc0f: 0x1a05, 0xc10: 0x1a0b, 0xc11: 0x1a0e, + 0xc12: 0x1c30, 0xc13: 0x1a11, 0xc14: 0x1a23, 0xc15: 0x1c38, 0xc16: 0x1c44, 0xc17: 0x1990, + 0xc18: 0x1d57, 0xc19: 0x1bbc, 0xc1a: 0x1993, 0xc1b: 0x1a5c, 0xc1c: 0x19a5, 0xc1d: 0x19b4, + 0xc1e: 0x22e2, 0xc1f: 0x22dc, 0xc20: 0x1cc1, 0xc21: 0x1cd0, 0xc22: 0x1cdf, 0xc23: 0x1cee, + 0xc24: 0x1cfd, 0xc25: 0x1d0c, 0xc26: 0x1d1b, 0xc27: 0x1d2a, 0xc28: 0x1d39, 0xc29: 0x2186, + 0xc2a: 0x2198, 0xc2b: 0x21aa, 0xc2c: 0x21bc, 0xc2d: 0x21c8, 0xc2e: 0x21d4, 0xc2f: 0x21e0, + 0xc30: 0x21ec, 0xc31: 0x21f8, 0xc32: 0x2204, 0xc33: 0x2240, 0xc34: 0x224c, 0xc35: 0x2258, + 0xc36: 0x2264, 0xc37: 0x2270, 0xc38: 0x227c, 0xc39: 0x2282, 0xc3a: 0x2288, 0xc3b: 0x228e, + 0xc3c: 0x2294, 0xc3d: 0x22a6, 0xc3e: 0x22ac, 0xc3f: 0x1c10, + // Block 0x31, offset 0xc40 + 0xc40: 0x1377, 0xc41: 0x0cfb, 0xc42: 0x13d3, 0xc43: 0x139f, 0xc44: 0x0e57, 0xc45: 0x06eb, + 0xc46: 0x08df, 0xc47: 0x162b, 0xc48: 0x162b, 0xc49: 0x0a0b, 0xc4a: 0x145f, 0xc4b: 0x0943, + 0xc4c: 0x0a07, 0xc4d: 0x0bef, 0xc4e: 0x0fcf, 0xc4f: 0x115f, 0xc50: 0x1297, 0xc51: 0x12d3, + 0xc52: 0x1307, 0xc53: 0x141b, 0xc54: 0x0d73, 0xc55: 0x0dff, 0xc56: 0x0eab, 0xc57: 0x0f43, + 0xc58: 0x125f, 0xc59: 0x1447, 0xc5a: 0x1573, 0xc5b: 0x070f, 0xc5c: 0x08b3, 0xc5d: 0x0d87, + 0xc5e: 0x0ecf, 0xc5f: 0x1293, 0xc60: 0x15c3, 0xc61: 0x0ab3, 0xc62: 0x0e77, 0xc63: 0x1283, + 0xc64: 0x1317, 0xc65: 0x0c23, 0xc66: 0x11bb, 0xc67: 0x12df, 0xc68: 0x0b1f, 0xc69: 0x0d0f, + 0xc6a: 0x0e17, 0xc6b: 0x0f1b, 0xc6c: 0x1427, 0xc6d: 0x074f, 0xc6e: 0x07e7, 0xc6f: 0x0853, + 0xc70: 0x0c8b, 0xc71: 0x0d7f, 0xc72: 0x0ecb, 0xc73: 0x0fef, 0xc74: 0x1177, 0xc75: 0x128b, + 0xc76: 0x12a3, 0xc77: 0x13c7, 0xc78: 0x14ef, 0xc79: 0x15a3, 0xc7a: 0x15bf, 0xc7b: 0x102b, + 0xc7c: 0x106b, 0xc7d: 0x1123, 0xc7e: 0x1243, 0xc7f: 0x147b, + // Block 0x32, offset 0xc80 + 0xc80: 0x15cb, 0xc81: 0x134b, 0xc82: 0x09c7, 0xc83: 0x0b3b, 0xc84: 0x10db, 0xc85: 0x119b, + 0xc86: 0x0eff, 0xc87: 0x1033, 0xc88: 0x1397, 0xc89: 0x14e7, 0xc8a: 0x09c3, 0xc8b: 0x0a8f, + 0xc8c: 0x0d77, 0xc8d: 0x0e2b, 0xc8e: 0x0e5f, 0xc8f: 0x1113, 0xc90: 0x113b, 0xc91: 0x14a7, + 0xc92: 0x084f, 0xc93: 0x11a7, 0xc94: 0x07f3, 0xc95: 0x07ef, 0xc96: 0x1097, 0xc97: 0x1127, + 0xc98: 0x125b, 0xc99: 0x14af, 0xc9a: 0x1367, 0xc9b: 0x0c27, 0xc9c: 0x0d73, 0xc9d: 0x1357, + 0xc9e: 0x06f7, 0xc9f: 0x0a63, 0xca0: 0x0b93, 0xca1: 0x0f2f, 0xca2: 0x0faf, 0xca3: 0x0873, + 0xca4: 0x103b, 0xca5: 0x075f, 0xca6: 0x0b77, 0xca7: 0x06d7, 0xca8: 0x0deb, 0xca9: 0x0ca3, + 0xcaa: 0x110f, 0xcab: 0x08c7, 0xcac: 0x09b3, 0xcad: 0x0ffb, 0xcae: 0x1263, 0xcaf: 0x133b, + 0xcb0: 0x0db7, 0xcb1: 0x13f7, 0xcb2: 0x0de3, 0xcb3: 0x0c37, 0xcb4: 0x121b, 0xcb5: 0x0c57, + 0xcb6: 0x0fab, 0xcb7: 0x072b, 0xcb8: 0x07a7, 0xcb9: 0x07eb, 0xcba: 0x0d53, 0xcbb: 0x10fb, + 0xcbc: 0x11f3, 0xcbd: 0x1347, 0xcbe: 0x145b, 0xcbf: 0x085b, + // Block 0x33, offset 0xcc0 + 0xcc0: 0x090f, 0xcc1: 0x0a17, 0xcc2: 0x0b2f, 0xcc3: 0x0cbf, 0xcc4: 0x0e7b, 0xcc5: 0x103f, + 0xcc6: 0x1497, 0xcc7: 0x157b, 0xcc8: 0x15cf, 0xcc9: 0x15e7, 0xcca: 0x0837, 0xccb: 0x0cf3, + 0xccc: 0x0da3, 0xccd: 0x13eb, 0xcce: 0x0afb, 0xccf: 0x0bd7, 0xcd0: 0x0bf3, 0xcd1: 0x0c83, + 0xcd2: 0x0e6b, 0xcd3: 0x0eb7, 0xcd4: 0x0f67, 0xcd5: 0x108b, 0xcd6: 0x112f, 0xcd7: 0x1193, + 0xcd8: 0x13db, 0xcd9: 0x126b, 0xcda: 0x1403, 0xcdb: 0x147f, 0xcdc: 0x080f, 0xcdd: 0x083b, + 0xcde: 0x0923, 0xcdf: 0x0ea7, 0xce0: 0x12f3, 0xce1: 0x133b, 0xce2: 0x0b1b, 0xce3: 0x0b8b, + 0xce4: 0x0c4f, 0xce5: 0x0daf, 0xce6: 0x10d7, 0xce7: 0x0f23, 0xce8: 0x073b, 0xce9: 0x097f, + 0xcea: 0x0a63, 0xceb: 0x0ac7, 0xcec: 0x0b97, 0xced: 0x0f3f, 0xcee: 0x0f5b, 0xcef: 0x116b, + 0xcf0: 0x118b, 0xcf1: 0x1463, 0xcf2: 0x14e3, 0xcf3: 0x14f3, 0xcf4: 0x152f, 0xcf5: 0x0753, + 0xcf6: 0x107f, 0xcf7: 0x144f, 0xcf8: 0x14cb, 0xcf9: 0x0baf, 0xcfa: 0x0717, 0xcfb: 0x0777, + 0xcfc: 0x0a67, 0xcfd: 0x0a87, 0xcfe: 0x0caf, 0xcff: 0x0d73, + // Block 0x34, offset 0xd00 + 0xd00: 0x0ec3, 0xd01: 0x0fcb, 0xd02: 0x1277, 0xd03: 0x1417, 0xd04: 0x1623, 0xd05: 0x0ce3, + 0xd06: 0x14a3, 0xd07: 0x0833, 0xd08: 0x0d2f, 0xd09: 0x0d3b, 0xd0a: 0x0e0f, 0xd0b: 0x0e47, + 0xd0c: 0x0f4b, 0xd0d: 0x0fa7, 0xd0e: 0x1027, 0xd0f: 0x110b, 0xd10: 0x153b, 0xd11: 0x07af, + 0xd12: 0x0c03, 0xd13: 0x14b3, 0xd14: 0x0767, 0xd15: 0x0aab, 0xd16: 0x0e2f, 0xd17: 0x13df, + 0xd18: 0x0b67, 0xd19: 0x0bb7, 0xd1a: 0x0d43, 0xd1b: 0x0f2f, 0xd1c: 0x14bb, 0xd1d: 0x0817, + 0xd1e: 0x08ff, 0xd1f: 0x0a97, 0xd20: 0x0cd3, 0xd21: 0x0d1f, 0xd22: 0x0d5f, 0xd23: 0x0df3, + 0xd24: 0x0f47, 0xd25: 0x0fbb, 0xd26: 0x1157, 0xd27: 0x12f7, 0xd28: 0x1303, 0xd29: 0x1457, + 0xd2a: 0x14d7, 0xd2b: 0x0883, 0xd2c: 0x0e4b, 0xd2d: 0x0903, 0xd2e: 0x0ec7, 0xd2f: 0x0f6b, + 0xd30: 0x1287, 0xd31: 0x14bf, 0xd32: 0x15ab, 0xd33: 0x15d3, 0xd34: 0x0d37, 0xd35: 0x0e27, + 0xd36: 0x11c3, 0xd37: 0x10b7, 0xd38: 0x10c3, 0xd39: 0x10e7, 0xd3a: 0x0f17, 0xd3b: 0x0e9f, + 0xd3c: 0x1363, 0xd3d: 0x0733, 0xd3e: 0x122b, 0xd3f: 0x081b, + // Block 0x35, offset 0xd40 + 0xd40: 0x080b, 0xd41: 0x0b0b, 0xd42: 0x0c2b, 0xd43: 0x10f3, 0xd44: 0x0a53, 0xd45: 0x0e03, + 0xd46: 0x0cef, 0xd47: 0x13e7, 0xd48: 0x12e7, 0xd49: 0x14ab, 0xd4a: 0x1323, 0xd4b: 0x0b27, + 0xd4c: 0x0787, 0xd4d: 0x095b, 0xd50: 0x09af, + 0xd52: 0x0cdf, 0xd55: 0x07f7, 0xd56: 0x0f1f, 0xd57: 0x0fe3, + 0xd58: 0x1047, 0xd59: 0x1063, 0xd5a: 0x1067, 0xd5b: 0x107b, 0xd5c: 0x14fb, 0xd5d: 0x10eb, + 0xd5e: 0x116f, 0xd60: 0x128f, 0xd62: 0x1353, + 0xd65: 0x1407, 0xd66: 0x1433, + 0xd6a: 0x154f, 0xd6b: 0x1553, 0xd6c: 0x1557, 0xd6d: 0x15bb, 0xd6e: 0x142b, 0xd6f: 0x14c7, + 0xd70: 0x0757, 0xd71: 0x077b, 0xd72: 0x078f, 0xd73: 0x084b, 0xd74: 0x0857, 0xd75: 0x0897, + 0xd76: 0x094b, 0xd77: 0x0967, 0xd78: 0x096f, 0xd79: 0x09ab, 0xd7a: 0x09b7, 0xd7b: 0x0a93, + 0xd7c: 0x0a9b, 0xd7d: 0x0ba3, 0xd7e: 0x0bcb, 0xd7f: 0x0bd3, + // Block 0x36, offset 0xd80 + 0xd80: 0x0beb, 0xd81: 0x0c97, 0xd82: 0x0cc7, 0xd83: 0x0ce7, 0xd84: 0x0d57, 0xd85: 0x0e1b, + 0xd86: 0x0e37, 0xd87: 0x0e67, 0xd88: 0x0ebb, 0xd89: 0x0edb, 0xd8a: 0x0f4f, 0xd8b: 0x102f, + 0xd8c: 0x104b, 0xd8d: 0x1053, 0xd8e: 0x104f, 0xd8f: 0x1057, 0xd90: 0x105b, 0xd91: 0x105f, + 0xd92: 0x1073, 0xd93: 0x1077, 0xd94: 0x109b, 0xd95: 0x10af, 0xd96: 0x10cb, 0xd97: 0x112f, + 0xd98: 0x1137, 0xd99: 0x113f, 0xd9a: 0x1153, 0xd9b: 0x117b, 0xd9c: 0x11cb, 0xd9d: 0x11ff, + 0xd9e: 0x11ff, 0xd9f: 0x1267, 0xda0: 0x130f, 0xda1: 0x1327, 0xda2: 0x135b, 0xda3: 0x135f, + 0xda4: 0x13a3, 0xda5: 0x13a7, 0xda6: 0x13ff, 0xda7: 0x1407, 0xda8: 0x14db, 0xda9: 0x151f, + 0xdaa: 0x1537, 0xdab: 0x0b9b, 0xdac: 0x171e, 0xdad: 0x11e3, + 0xdb0: 0x06df, 0xdb1: 0x07e3, 0xdb2: 0x07a3, 0xdb3: 0x074b, 0xdb4: 0x078b, 0xdb5: 0x07b7, + 0xdb6: 0x0847, 0xdb7: 0x0863, 0xdb8: 0x094b, 0xdb9: 0x0937, 0xdba: 0x0947, 0xdbb: 0x0963, + 0xdbc: 0x09af, 0xdbd: 0x09bf, 0xdbe: 0x0a03, 0xdbf: 0x0a0f, + // Block 0x37, offset 0xdc0 + 0xdc0: 0x0a2b, 0xdc1: 0x0a3b, 0xdc2: 0x0b23, 0xdc3: 0x0b2b, 0xdc4: 0x0b5b, 0xdc5: 0x0b7b, + 0xdc6: 0x0bab, 0xdc7: 0x0bc3, 0xdc8: 0x0bb3, 0xdc9: 0x0bd3, 0xdca: 0x0bc7, 0xdcb: 0x0beb, + 0xdcc: 0x0c07, 0xdcd: 0x0c5f, 0xdce: 0x0c6b, 0xdcf: 0x0c73, 0xdd0: 0x0c9b, 0xdd1: 0x0cdf, + 0xdd2: 0x0d0f, 0xdd3: 0x0d13, 0xdd4: 0x0d27, 0xdd5: 0x0da7, 0xdd6: 0x0db7, 0xdd7: 0x0e0f, + 0xdd8: 0x0e5b, 0xdd9: 0x0e53, 0xdda: 0x0e67, 0xddb: 0x0e83, 0xddc: 0x0ebb, 0xddd: 0x1013, + 0xdde: 0x0edf, 0xddf: 0x0f13, 0xde0: 0x0f1f, 0xde1: 0x0f5f, 0xde2: 0x0f7b, 0xde3: 0x0f9f, + 0xde4: 0x0fc3, 0xde5: 0x0fc7, 0xde6: 0x0fe3, 0xde7: 0x0fe7, 0xde8: 0x0ff7, 0xde9: 0x100b, + 0xdea: 0x1007, 0xdeb: 0x1037, 0xdec: 0x10b3, 0xded: 0x10cb, 0xdee: 0x10e3, 0xdef: 0x111b, + 0xdf0: 0x112f, 0xdf1: 0x114b, 0xdf2: 0x117b, 0xdf3: 0x122f, 0xdf4: 0x1257, 0xdf5: 0x12cb, + 0xdf6: 0x1313, 0xdf7: 0x131f, 0xdf8: 0x1327, 0xdf9: 0x133f, 0xdfa: 0x1353, 0xdfb: 0x1343, + 0xdfc: 0x135b, 0xdfd: 0x1357, 0xdfe: 0x134f, 0xdff: 0x135f, + // Block 0x38, offset 0xe00 + 0xe00: 0x136b, 0xe01: 0x13a7, 0xe02: 0x13e3, 0xe03: 0x1413, 0xe04: 0x144b, 0xe05: 0x146b, + 0xe06: 0x14b7, 0xe07: 0x14db, 0xe08: 0x14fb, 0xe09: 0x150f, 0xe0a: 0x151f, 0xe0b: 0x152b, + 0xe0c: 0x1537, 0xe0d: 0x158b, 0xe0e: 0x162b, 0xe0f: 0x16b5, 0xe10: 0x16b0, 0xe11: 0x16e2, + 0xe12: 0x0607, 0xe13: 0x062f, 0xe14: 0x0633, 0xe15: 0x1764, 0xe16: 0x1791, 0xe17: 0x1809, + 0xe18: 0x1617, 0xe19: 0x1627, + // Block 0x39, offset 0xe40 + 0xe40: 0x19d5, 0xe41: 0x19d8, 0xe42: 0x19db, 0xe43: 0x1c08, 0xe44: 0x1c0c, 0xe45: 0x1a5f, + 0xe46: 0x1a5f, + 0xe53: 0x1d75, 0xe54: 0x1d66, 0xe55: 0x1d6b, 0xe56: 0x1d7a, 0xe57: 0x1d70, + 0xe5d: 0x4390, + 0xe5e: 0x8115, 0xe5f: 0x4402, 0xe60: 0x022d, 0xe61: 0x0215, 0xe62: 0x021e, 0xe63: 0x0221, + 0xe64: 0x0224, 0xe65: 0x0227, 0xe66: 0x022a, 0xe67: 0x0230, 0xe68: 0x0233, 0xe69: 0x0017, + 0xe6a: 0x43f0, 0xe6b: 0x43f6, 0xe6c: 0x44f4, 0xe6d: 0x44fc, 0xe6e: 0x4348, 0xe6f: 0x434e, + 0xe70: 0x4354, 0xe71: 0x435a, 0xe72: 0x4366, 0xe73: 0x436c, 0xe74: 0x4372, 0xe75: 0x437e, + 0xe76: 0x4384, 0xe78: 0x438a, 0xe79: 0x4396, 0xe7a: 0x439c, 0xe7b: 0x43a2, + 0xe7c: 0x43ae, 0xe7e: 0x43b4, + // Block 0x3a, offset 0xe80 + 0xe80: 0x43ba, 0xe81: 0x43c0, 0xe83: 0x43c6, 0xe84: 0x43cc, + 0xe86: 0x43d8, 0xe87: 0x43de, 0xe88: 0x43e4, 0xe89: 0x43ea, 0xe8a: 0x43fc, 0xe8b: 0x4378, + 0xe8c: 0x4360, 0xe8d: 0x43a8, 0xe8e: 0x43d2, 0xe8f: 0x1d7f, 0xe90: 0x0299, 0xe91: 0x0299, + 0xe92: 0x02a2, 0xe93: 0x02a2, 0xe94: 0x02a2, 0xe95: 0x02a2, 0xe96: 0x02a5, 0xe97: 0x02a5, + 0xe98: 0x02a5, 0xe99: 0x02a5, 0xe9a: 0x02ab, 0xe9b: 0x02ab, 0xe9c: 0x02ab, 0xe9d: 0x02ab, + 0xe9e: 0x029f, 0xe9f: 0x029f, 0xea0: 0x029f, 0xea1: 0x029f, 0xea2: 0x02a8, 0xea3: 0x02a8, + 0xea4: 0x02a8, 0xea5: 0x02a8, 0xea6: 0x029c, 0xea7: 0x029c, 0xea8: 0x029c, 0xea9: 0x029c, + 0xeaa: 0x02cf, 0xeab: 0x02cf, 0xeac: 0x02cf, 0xead: 0x02cf, 0xeae: 0x02d2, 0xeaf: 0x02d2, + 0xeb0: 0x02d2, 0xeb1: 0x02d2, 0xeb2: 0x02b1, 0xeb3: 0x02b1, 0xeb4: 0x02b1, 0xeb5: 0x02b1, + 0xeb6: 0x02ae, 0xeb7: 0x02ae, 0xeb8: 0x02ae, 0xeb9: 0x02ae, 0xeba: 0x02b4, 0xebb: 0x02b4, + 0xebc: 0x02b4, 0xebd: 0x02b4, 0xebe: 0x02b7, 0xebf: 0x02b7, + // Block 0x3b, offset 0xec0 + 0xec0: 0x02b7, 0xec1: 0x02b7, 0xec2: 0x02c0, 0xec3: 0x02c0, 0xec4: 0x02bd, 0xec5: 0x02bd, + 0xec6: 0x02c3, 0xec7: 0x02c3, 0xec8: 0x02ba, 0xec9: 0x02ba, 0xeca: 0x02c9, 0xecb: 0x02c9, + 0xecc: 0x02c6, 0xecd: 0x02c6, 0xece: 0x02d5, 0xecf: 0x02d5, 0xed0: 0x02d5, 0xed1: 0x02d5, + 0xed2: 0x02db, 0xed3: 0x02db, 0xed4: 0x02db, 0xed5: 0x02db, 0xed6: 0x02e1, 0xed7: 0x02e1, + 0xed8: 0x02e1, 0xed9: 0x02e1, 0xeda: 0x02de, 0xedb: 0x02de, 0xedc: 0x02de, 0xedd: 0x02de, + 0xede: 0x02e4, 0xedf: 0x02e4, 0xee0: 0x02e7, 0xee1: 0x02e7, 0xee2: 0x02e7, 0xee3: 0x02e7, + 0xee4: 0x446e, 0xee5: 0x446e, 0xee6: 0x02ed, 0xee7: 0x02ed, 0xee8: 0x02ed, 0xee9: 0x02ed, + 0xeea: 0x02ea, 0xeeb: 0x02ea, 0xeec: 0x02ea, 0xeed: 0x02ea, 0xeee: 0x0308, 0xeef: 0x0308, + 0xef0: 0x4468, 0xef1: 0x4468, + // Block 0x3c, offset 0xf00 + 0xf13: 0x02d8, 0xf14: 0x02d8, 0xf15: 0x02d8, 0xf16: 0x02d8, 0xf17: 0x02f6, + 0xf18: 0x02f6, 0xf19: 0x02f3, 0xf1a: 0x02f3, 0xf1b: 0x02f9, 0xf1c: 0x02f9, 0xf1d: 0x204f, + 0xf1e: 0x02ff, 0xf1f: 0x02ff, 0xf20: 0x02f0, 0xf21: 0x02f0, 0xf22: 0x02fc, 0xf23: 0x02fc, + 0xf24: 0x0305, 0xf25: 0x0305, 0xf26: 0x0305, 0xf27: 0x0305, 0xf28: 0x028d, 0xf29: 0x028d, + 0xf2a: 0x25aa, 0xf2b: 0x25aa, 0xf2c: 0x261a, 0xf2d: 0x261a, 0xf2e: 0x25e9, 0xf2f: 0x25e9, + 0xf30: 0x2605, 0xf31: 0x2605, 0xf32: 0x25fe, 0xf33: 0x25fe, 0xf34: 0x260c, 0xf35: 0x260c, + 0xf36: 0x2613, 0xf37: 0x2613, 0xf38: 0x2613, 0xf39: 0x25f0, 0xf3a: 0x25f0, 0xf3b: 0x25f0, + 0xf3c: 0x0302, 0xf3d: 0x0302, 0xf3e: 0x0302, 0xf3f: 0x0302, + // Block 0x3d, offset 0xf40 + 0xf40: 0x25b1, 0xf41: 0x25b8, 0xf42: 0x25d4, 0xf43: 0x25f0, 0xf44: 0x25f7, 0xf45: 0x1d89, + 0xf46: 0x1d8e, 0xf47: 0x1d93, 0xf48: 0x1da2, 0xf49: 0x1db1, 0xf4a: 0x1db6, 0xf4b: 0x1dbb, + 0xf4c: 0x1dc0, 0xf4d: 0x1dc5, 0xf4e: 0x1dd4, 0xf4f: 0x1de3, 0xf50: 0x1de8, 0xf51: 0x1ded, + 0xf52: 0x1dfc, 0xf53: 0x1e0b, 0xf54: 0x1e10, 0xf55: 0x1e15, 0xf56: 0x1e1a, 0xf57: 0x1e29, + 0xf58: 0x1e2e, 0xf59: 0x1e3d, 0xf5a: 0x1e42, 0xf5b: 0x1e47, 0xf5c: 0x1e56, 0xf5d: 0x1e5b, + 0xf5e: 0x1e60, 0xf5f: 0x1e6a, 0xf60: 0x1ea6, 0xf61: 0x1eb5, 0xf62: 0x1ec4, 0xf63: 0x1ec9, + 0xf64: 0x1ece, 0xf65: 0x1ed8, 0xf66: 0x1ee7, 0xf67: 0x1eec, 0xf68: 0x1efb, 0xf69: 0x1f00, + 0xf6a: 0x1f05, 0xf6b: 0x1f14, 0xf6c: 0x1f19, 0xf6d: 0x1f28, 0xf6e: 0x1f2d, 0xf6f: 0x1f32, + 0xf70: 0x1f37, 0xf71: 0x1f3c, 0xf72: 0x1f41, 0xf73: 0x1f46, 0xf74: 0x1f4b, 0xf75: 0x1f50, + 0xf76: 0x1f55, 0xf77: 0x1f5a, 0xf78: 0x1f5f, 0xf79: 0x1f64, 0xf7a: 0x1f69, 0xf7b: 0x1f6e, + 0xf7c: 0x1f73, 0xf7d: 0x1f78, 0xf7e: 0x1f7d, 0xf7f: 0x1f87, + // Block 0x3e, offset 0xf80 + 0xf80: 0x1f8c, 0xf81: 0x1f91, 0xf82: 0x1f96, 0xf83: 0x1fa0, 0xf84: 0x1fa5, 0xf85: 0x1faf, + 0xf86: 0x1fb4, 0xf87: 0x1fb9, 0xf88: 0x1fbe, 0xf89: 0x1fc3, 0xf8a: 0x1fc8, 0xf8b: 0x1fcd, + 0xf8c: 0x1fd2, 0xf8d: 0x1fd7, 0xf8e: 0x1fe6, 0xf8f: 0x1ff5, 0xf90: 0x1ffa, 0xf91: 0x1fff, + 0xf92: 0x2004, 0xf93: 0x2009, 0xf94: 0x200e, 0xf95: 0x2018, 0xf96: 0x201d, 0xf97: 0x2022, + 0xf98: 0x2031, 0xf99: 0x2040, 0xf9a: 0x2045, 0xf9b: 0x4420, 0xf9c: 0x4426, 0xf9d: 0x445c, + 0xf9e: 0x44b3, 0xf9f: 0x44ba, 0xfa0: 0x44c1, 0xfa1: 0x44c8, 0xfa2: 0x44cf, 0xfa3: 0x44d6, + 0xfa4: 0x25c6, 0xfa5: 0x25cd, 0xfa6: 0x25d4, 0xfa7: 0x25db, 0xfa8: 0x25f0, 0xfa9: 0x25f7, + 0xfaa: 0x1d98, 0xfab: 0x1d9d, 0xfac: 0x1da2, 0xfad: 0x1da7, 0xfae: 0x1db1, 0xfaf: 0x1db6, + 0xfb0: 0x1dca, 0xfb1: 0x1dcf, 0xfb2: 0x1dd4, 0xfb3: 0x1dd9, 0xfb4: 0x1de3, 0xfb5: 0x1de8, + 0xfb6: 0x1df2, 0xfb7: 0x1df7, 0xfb8: 0x1dfc, 0xfb9: 0x1e01, 0xfba: 0x1e0b, 0xfbb: 0x1e10, + 0xfbc: 0x1f3c, 0xfbd: 0x1f41, 0xfbe: 0x1f50, 0xfbf: 0x1f55, + // Block 0x3f, offset 0xfc0 + 0xfc0: 0x1f5a, 0xfc1: 0x1f6e, 0xfc2: 0x1f73, 0xfc3: 0x1f78, 0xfc4: 0x1f7d, 0xfc5: 0x1f96, + 0xfc6: 0x1fa0, 0xfc7: 0x1fa5, 0xfc8: 0x1faa, 0xfc9: 0x1fbe, 0xfca: 0x1fdc, 0xfcb: 0x1fe1, + 0xfcc: 0x1fe6, 0xfcd: 0x1feb, 0xfce: 0x1ff5, 0xfcf: 0x1ffa, 0xfd0: 0x445c, 0xfd1: 0x2027, + 0xfd2: 0x202c, 0xfd3: 0x2031, 0xfd4: 0x2036, 0xfd5: 0x2040, 0xfd6: 0x2045, 0xfd7: 0x25b1, + 0xfd8: 0x25b8, 0xfd9: 0x25bf, 0xfda: 0x25d4, 0xfdb: 0x25e2, 0xfdc: 0x1d89, 0xfdd: 0x1d8e, + 0xfde: 0x1d93, 0xfdf: 0x1da2, 0xfe0: 0x1dac, 0xfe1: 0x1dbb, 0xfe2: 0x1dc0, 0xfe3: 0x1dc5, + 0xfe4: 0x1dd4, 0xfe5: 0x1dde, 0xfe6: 0x1dfc, 0xfe7: 0x1e15, 0xfe8: 0x1e1a, 0xfe9: 0x1e29, + 0xfea: 0x1e2e, 0xfeb: 0x1e3d, 0xfec: 0x1e47, 0xfed: 0x1e56, 0xfee: 0x1e5b, 0xfef: 0x1e60, + 0xff0: 0x1e6a, 0xff1: 0x1ea6, 0xff2: 0x1eab, 0xff3: 0x1eb5, 0xff4: 0x1ec4, 0xff5: 0x1ec9, + 0xff6: 0x1ece, 0xff7: 0x1ed8, 0xff8: 0x1ee7, 0xff9: 0x1efb, 0xffa: 0x1f00, 0xffb: 0x1f05, + 0xffc: 0x1f14, 0xffd: 0x1f19, 0xffe: 0x1f28, 0xfff: 0x1f2d, + // Block 0x40, offset 0x1000 + 0x1000: 0x1f32, 0x1001: 0x1f37, 0x1002: 0x1f46, 0x1003: 0x1f4b, 0x1004: 0x1f5f, 0x1005: 0x1f64, + 0x1006: 0x1f69, 0x1007: 0x1f6e, 0x1008: 0x1f73, 0x1009: 0x1f87, 0x100a: 0x1f8c, 0x100b: 0x1f91, + 0x100c: 0x1f96, 0x100d: 0x1f9b, 0x100e: 0x1faf, 0x100f: 0x1fb4, 0x1010: 0x1fb9, 0x1011: 0x1fbe, + 0x1012: 0x1fcd, 0x1013: 0x1fd2, 0x1014: 0x1fd7, 0x1015: 0x1fe6, 0x1016: 0x1ff0, 0x1017: 0x1fff, + 0x1018: 0x2004, 0x1019: 0x4450, 0x101a: 0x2018, 0x101b: 0x201d, 0x101c: 0x2022, 0x101d: 0x2031, + 0x101e: 0x203b, 0x101f: 0x25d4, 0x1020: 0x25e2, 0x1021: 0x1da2, 0x1022: 0x1dac, 0x1023: 0x1dd4, + 0x1024: 0x1dde, 0x1025: 0x1dfc, 0x1026: 0x1e06, 0x1027: 0x1e6a, 0x1028: 0x1e6f, 0x1029: 0x1e92, + 0x102a: 0x1e97, 0x102b: 0x1f6e, 0x102c: 0x1f73, 0x102d: 0x1f96, 0x102e: 0x1fe6, 0x102f: 0x1ff0, + 0x1030: 0x2031, 0x1031: 0x203b, 0x1032: 0x4504, 0x1033: 0x450c, 0x1034: 0x4514, 0x1035: 0x1ef1, + 0x1036: 0x1ef6, 0x1037: 0x1f0a, 0x1038: 0x1f0f, 0x1039: 0x1f1e, 0x103a: 0x1f23, 0x103b: 0x1e74, + 0x103c: 0x1e79, 0x103d: 0x1e9c, 0x103e: 0x1ea1, 0x103f: 0x1e33, + // Block 0x41, offset 0x1040 + 0x1040: 0x1e38, 0x1041: 0x1e1f, 0x1042: 0x1e24, 0x1043: 0x1e4c, 0x1044: 0x1e51, 0x1045: 0x1eba, + 0x1046: 0x1ebf, 0x1047: 0x1edd, 0x1048: 0x1ee2, 0x1049: 0x1e7e, 0x104a: 0x1e83, 0x104b: 0x1e88, + 0x104c: 0x1e92, 0x104d: 0x1e8d, 0x104e: 0x1e65, 0x104f: 0x1eb0, 0x1050: 0x1ed3, 0x1051: 0x1ef1, + 0x1052: 0x1ef6, 0x1053: 0x1f0a, 0x1054: 0x1f0f, 0x1055: 0x1f1e, 0x1056: 0x1f23, 0x1057: 0x1e74, + 0x1058: 0x1e79, 0x1059: 0x1e9c, 0x105a: 0x1ea1, 0x105b: 0x1e33, 0x105c: 0x1e38, 0x105d: 0x1e1f, + 0x105e: 0x1e24, 0x105f: 0x1e4c, 0x1060: 0x1e51, 0x1061: 0x1eba, 0x1062: 0x1ebf, 0x1063: 0x1edd, + 0x1064: 0x1ee2, 0x1065: 0x1e7e, 0x1066: 0x1e83, 0x1067: 0x1e88, 0x1068: 0x1e92, 0x1069: 0x1e8d, + 0x106a: 0x1e65, 0x106b: 0x1eb0, 0x106c: 0x1ed3, 0x106d: 0x1e7e, 0x106e: 0x1e83, 0x106f: 0x1e88, + 0x1070: 0x1e92, 0x1071: 0x1e6f, 0x1072: 0x1e97, 0x1073: 0x1eec, 0x1074: 0x1e56, 0x1075: 0x1e5b, + 0x1076: 0x1e60, 0x1077: 0x1e7e, 0x1078: 0x1e83, 0x1079: 0x1e88, 0x107a: 0x1eec, 0x107b: 0x1efb, + 0x107c: 0x4408, 0x107d: 0x4408, + // Block 0x42, offset 0x1080 + 0x1090: 0x2311, 0x1091: 0x2326, + 0x1092: 0x2326, 0x1093: 0x232d, 0x1094: 0x2334, 0x1095: 0x2349, 0x1096: 0x2350, 0x1097: 0x2357, + 0x1098: 0x237a, 0x1099: 0x237a, 0x109a: 0x239d, 0x109b: 0x2396, 0x109c: 0x23b2, 0x109d: 0x23a4, + 0x109e: 0x23ab, 0x109f: 0x23ce, 0x10a0: 0x23ce, 0x10a1: 0x23c7, 0x10a2: 0x23d5, 0x10a3: 0x23d5, + 0x10a4: 0x23ff, 0x10a5: 0x23ff, 0x10a6: 0x241b, 0x10a7: 0x23e3, 0x10a8: 0x23e3, 0x10a9: 0x23dc, + 0x10aa: 0x23f1, 0x10ab: 0x23f1, 0x10ac: 0x23f8, 0x10ad: 0x23f8, 0x10ae: 0x2422, 0x10af: 0x2430, + 0x10b0: 0x2430, 0x10b1: 0x2437, 0x10b2: 0x2437, 0x10b3: 0x243e, 0x10b4: 0x2445, 0x10b5: 0x244c, + 0x10b6: 0x2453, 0x10b7: 0x2453, 0x10b8: 0x245a, 0x10b9: 0x2468, 0x10ba: 0x2476, 0x10bb: 0x246f, + 0x10bc: 0x247d, 0x10bd: 0x247d, 0x10be: 0x2492, 0x10bf: 0x2499, + // Block 0x43, offset 0x10c0 + 0x10c0: 0x24ca, 0x10c1: 0x24d8, 0x10c2: 0x24d1, 0x10c3: 0x24b5, 0x10c4: 0x24b5, 0x10c5: 0x24df, + 0x10c6: 0x24df, 0x10c7: 0x24e6, 0x10c8: 0x24e6, 0x10c9: 0x2510, 0x10ca: 0x2517, 0x10cb: 0x251e, + 0x10cc: 0x24f4, 0x10cd: 0x2502, 0x10ce: 0x2525, 0x10cf: 0x252c, + 0x10d2: 0x24fb, 0x10d3: 0x2580, 0x10d4: 0x2587, 0x10d5: 0x255d, 0x10d6: 0x2564, 0x10d7: 0x2548, + 0x10d8: 0x2548, 0x10d9: 0x254f, 0x10da: 0x2579, 0x10db: 0x2572, 0x10dc: 0x259c, 0x10dd: 0x259c, + 0x10de: 0x230a, 0x10df: 0x231f, 0x10e0: 0x2318, 0x10e1: 0x2342, 0x10e2: 0x233b, 0x10e3: 0x2365, + 0x10e4: 0x235e, 0x10e5: 0x2388, 0x10e6: 0x236c, 0x10e7: 0x2381, 0x10e8: 0x23b9, 0x10e9: 0x2406, + 0x10ea: 0x23ea, 0x10eb: 0x2429, 0x10ec: 0x24c3, 0x10ed: 0x24ed, 0x10ee: 0x2595, 0x10ef: 0x258e, + 0x10f0: 0x25a3, 0x10f1: 0x253a, 0x10f2: 0x24a0, 0x10f3: 0x256b, 0x10f4: 0x2492, 0x10f5: 0x24ca, + 0x10f6: 0x2461, 0x10f7: 0x24ae, 0x10f8: 0x2541, 0x10f9: 0x2533, 0x10fa: 0x24bc, 0x10fb: 0x24a7, + 0x10fc: 0x24bc, 0x10fd: 0x2541, 0x10fe: 0x2373, 0x10ff: 0x238f, + // Block 0x44, offset 0x1100 + 0x1100: 0x2509, 0x1101: 0x2484, 0x1102: 0x2303, 0x1103: 0x24a7, 0x1104: 0x244c, 0x1105: 0x241b, + 0x1106: 0x23c0, 0x1107: 0x2556, + 0x1130: 0x2414, 0x1131: 0x248b, 0x1132: 0x27bf, 0x1133: 0x27b6, 0x1134: 0x27ec, 0x1135: 0x27da, + 0x1136: 0x27c8, 0x1137: 0x27e3, 0x1138: 0x27f5, 0x1139: 0x240d, 0x113a: 0x2c7c, 0x113b: 0x2afc, + 0x113c: 0x27d1, + // Block 0x45, offset 0x1140 + 0x1150: 0x0019, 0x1151: 0x0483, + 0x1152: 0x0487, 0x1153: 0x0035, 0x1154: 0x0037, 0x1155: 0x0003, 0x1156: 0x003f, 0x1157: 0x04bf, + 0x1158: 0x04c3, 0x1159: 0x1b5c, + 0x1160: 0x8132, 0x1161: 0x8132, 0x1162: 0x8132, 0x1163: 0x8132, + 0x1164: 0x8132, 0x1165: 0x8132, 0x1166: 0x8132, 0x1167: 0x812d, 0x1168: 0x812d, 0x1169: 0x812d, + 0x116a: 0x812d, 0x116b: 0x812d, 0x116c: 0x812d, 0x116d: 0x812d, 0x116e: 0x8132, 0x116f: 0x8132, + 0x1170: 0x1873, 0x1171: 0x0443, 0x1172: 0x043f, 0x1173: 0x007f, 0x1174: 0x007f, 0x1175: 0x0011, + 0x1176: 0x0013, 0x1177: 0x00b7, 0x1178: 0x00bb, 0x1179: 0x04b7, 0x117a: 0x04bb, 0x117b: 0x04ab, + 0x117c: 0x04af, 0x117d: 0x0493, 0x117e: 0x0497, 0x117f: 0x048b, + // Block 0x46, offset 0x1180 + 0x1180: 0x048f, 0x1181: 0x049b, 0x1182: 0x049f, 0x1183: 0x04a3, 0x1184: 0x04a7, + 0x1187: 0x0077, 0x1188: 0x007b, 0x1189: 0x4269, 0x118a: 0x4269, 0x118b: 0x4269, + 0x118c: 0x4269, 0x118d: 0x007f, 0x118e: 0x007f, 0x118f: 0x007f, 0x1190: 0x0019, 0x1191: 0x0483, + 0x1192: 0x001d, 0x1194: 0x0037, 0x1195: 0x0035, 0x1196: 0x003f, 0x1197: 0x0003, + 0x1198: 0x0443, 0x1199: 0x0011, 0x119a: 0x0013, 0x119b: 0x00b7, 0x119c: 0x00bb, 0x119d: 0x04b7, + 0x119e: 0x04bb, 0x119f: 0x0007, 0x11a0: 0x000d, 0x11a1: 0x0015, 0x11a2: 0x0017, 0x11a3: 0x001b, + 0x11a4: 0x0039, 0x11a5: 0x003d, 0x11a6: 0x003b, 0x11a8: 0x0079, 0x11a9: 0x0009, + 0x11aa: 0x000b, 0x11ab: 0x0041, + 0x11b0: 0x42aa, 0x11b1: 0x442c, 0x11b2: 0x42af, 0x11b4: 0x42b4, + 0x11b6: 0x42b9, 0x11b7: 0x4432, 0x11b8: 0x42be, 0x11b9: 0x4438, 0x11ba: 0x42c3, 0x11bb: 0x443e, + 0x11bc: 0x42c8, 0x11bd: 0x4444, 0x11be: 0x42cd, 0x11bf: 0x444a, + // Block 0x47, offset 0x11c0 + 0x11c0: 0x0236, 0x11c1: 0x440e, 0x11c2: 0x440e, 0x11c3: 0x4414, 0x11c4: 0x4414, 0x11c5: 0x4456, + 0x11c6: 0x4456, 0x11c7: 0x441a, 0x11c8: 0x441a, 0x11c9: 0x4462, 0x11ca: 0x4462, 0x11cb: 0x4462, + 0x11cc: 0x4462, 0x11cd: 0x0239, 0x11ce: 0x0239, 0x11cf: 0x023c, 0x11d0: 0x023c, 0x11d1: 0x023c, + 0x11d2: 0x023c, 0x11d3: 0x023f, 0x11d4: 0x023f, 0x11d5: 0x0242, 0x11d6: 0x0242, 0x11d7: 0x0242, + 0x11d8: 0x0242, 0x11d9: 0x0245, 0x11da: 0x0245, 0x11db: 0x0245, 0x11dc: 0x0245, 0x11dd: 0x0248, + 0x11de: 0x0248, 0x11df: 0x0248, 0x11e0: 0x0248, 0x11e1: 0x024b, 0x11e2: 0x024b, 0x11e3: 0x024b, + 0x11e4: 0x024b, 0x11e5: 0x024e, 0x11e6: 0x024e, 0x11e7: 0x024e, 0x11e8: 0x024e, 0x11e9: 0x0251, + 0x11ea: 0x0251, 0x11eb: 0x0254, 0x11ec: 0x0254, 0x11ed: 0x0257, 0x11ee: 0x0257, 0x11ef: 0x025a, + 0x11f0: 0x025a, 0x11f1: 0x025d, 0x11f2: 0x025d, 0x11f3: 0x025d, 0x11f4: 0x025d, 0x11f5: 0x0260, + 0x11f6: 0x0260, 0x11f7: 0x0260, 0x11f8: 0x0260, 0x11f9: 0x0263, 0x11fa: 0x0263, 0x11fb: 0x0263, + 0x11fc: 0x0263, 0x11fd: 0x0266, 0x11fe: 0x0266, 0x11ff: 0x0266, + // Block 0x48, offset 0x1200 + 0x1200: 0x0266, 0x1201: 0x0269, 0x1202: 0x0269, 0x1203: 0x0269, 0x1204: 0x0269, 0x1205: 0x026c, + 0x1206: 0x026c, 0x1207: 0x026c, 0x1208: 0x026c, 0x1209: 0x026f, 0x120a: 0x026f, 0x120b: 0x026f, + 0x120c: 0x026f, 0x120d: 0x0272, 0x120e: 0x0272, 0x120f: 0x0272, 0x1210: 0x0272, 0x1211: 0x0275, + 0x1212: 0x0275, 0x1213: 0x0275, 0x1214: 0x0275, 0x1215: 0x0278, 0x1216: 0x0278, 0x1217: 0x0278, + 0x1218: 0x0278, 0x1219: 0x027b, 0x121a: 0x027b, 0x121b: 0x027b, 0x121c: 0x027b, 0x121d: 0x027e, + 0x121e: 0x027e, 0x121f: 0x027e, 0x1220: 0x027e, 0x1221: 0x0281, 0x1222: 0x0281, 0x1223: 0x0281, + 0x1224: 0x0281, 0x1225: 0x0284, 0x1226: 0x0284, 0x1227: 0x0284, 0x1228: 0x0284, 0x1229: 0x0287, + 0x122a: 0x0287, 0x122b: 0x0287, 0x122c: 0x0287, 0x122d: 0x028a, 0x122e: 0x028a, 0x122f: 0x028d, + 0x1230: 0x028d, 0x1231: 0x0290, 0x1232: 0x0290, 0x1233: 0x0290, 0x1234: 0x0290, 0x1235: 0x2e00, + 0x1236: 0x2e00, 0x1237: 0x2e08, 0x1238: 0x2e08, 0x1239: 0x2e10, 0x123a: 0x2e10, 0x123b: 0x1f82, + 0x123c: 0x1f82, + // Block 0x49, offset 0x1240 + 0x1240: 0x0081, 0x1241: 0x0083, 0x1242: 0x0085, 0x1243: 0x0087, 0x1244: 0x0089, 0x1245: 0x008b, + 0x1246: 0x008d, 0x1247: 0x008f, 0x1248: 0x0091, 0x1249: 0x0093, 0x124a: 0x0095, 0x124b: 0x0097, + 0x124c: 0x0099, 0x124d: 0x009b, 0x124e: 0x009d, 0x124f: 0x009f, 0x1250: 0x00a1, 0x1251: 0x00a3, + 0x1252: 0x00a5, 0x1253: 0x00a7, 0x1254: 0x00a9, 0x1255: 0x00ab, 0x1256: 0x00ad, 0x1257: 0x00af, + 0x1258: 0x00b1, 0x1259: 0x00b3, 0x125a: 0x00b5, 0x125b: 0x00b7, 0x125c: 0x00b9, 0x125d: 0x00bb, + 0x125e: 0x00bd, 0x125f: 0x0477, 0x1260: 0x047b, 0x1261: 0x0487, 0x1262: 0x049b, 0x1263: 0x049f, + 0x1264: 0x0483, 0x1265: 0x05ab, 0x1266: 0x05a3, 0x1267: 0x04c7, 0x1268: 0x04cf, 0x1269: 0x04d7, + 0x126a: 0x04df, 0x126b: 0x04e7, 0x126c: 0x056b, 0x126d: 0x0573, 0x126e: 0x057b, 0x126f: 0x051f, + 0x1270: 0x05af, 0x1271: 0x04cb, 0x1272: 0x04d3, 0x1273: 0x04db, 0x1274: 0x04e3, 0x1275: 0x04eb, + 0x1276: 0x04ef, 0x1277: 0x04f3, 0x1278: 0x04f7, 0x1279: 0x04fb, 0x127a: 0x04ff, 0x127b: 0x0503, + 0x127c: 0x0507, 0x127d: 0x050b, 0x127e: 0x050f, 0x127f: 0x0513, + // Block 0x4a, offset 0x1280 + 0x1280: 0x0517, 0x1281: 0x051b, 0x1282: 0x0523, 0x1283: 0x0527, 0x1284: 0x052b, 0x1285: 0x052f, + 0x1286: 0x0533, 0x1287: 0x0537, 0x1288: 0x053b, 0x1289: 0x053f, 0x128a: 0x0543, 0x128b: 0x0547, + 0x128c: 0x054b, 0x128d: 0x054f, 0x128e: 0x0553, 0x128f: 0x0557, 0x1290: 0x055b, 0x1291: 0x055f, + 0x1292: 0x0563, 0x1293: 0x0567, 0x1294: 0x056f, 0x1295: 0x0577, 0x1296: 0x057f, 0x1297: 0x0583, + 0x1298: 0x0587, 0x1299: 0x058b, 0x129a: 0x058f, 0x129b: 0x0593, 0x129c: 0x0597, 0x129d: 0x05a7, + 0x129e: 0x4a78, 0x129f: 0x4a7e, 0x12a0: 0x03c3, 0x12a1: 0x0313, 0x12a2: 0x0317, 0x12a3: 0x4a3b, + 0x12a4: 0x031b, 0x12a5: 0x4a41, 0x12a6: 0x4a47, 0x12a7: 0x031f, 0x12a8: 0x0323, 0x12a9: 0x0327, + 0x12aa: 0x4a4d, 0x12ab: 0x4a53, 0x12ac: 0x4a59, 0x12ad: 0x4a5f, 0x12ae: 0x4a65, 0x12af: 0x4a6b, + 0x12b0: 0x0367, 0x12b1: 0x032b, 0x12b2: 0x032f, 0x12b3: 0x0333, 0x12b4: 0x037b, 0x12b5: 0x0337, + 0x12b6: 0x033b, 0x12b7: 0x033f, 0x12b8: 0x0343, 0x12b9: 0x0347, 0x12ba: 0x034b, 0x12bb: 0x034f, + 0x12bc: 0x0353, 0x12bd: 0x0357, 0x12be: 0x035b, + // Block 0x4b, offset 0x12c0 + 0x12c2: 0x49bd, 0x12c3: 0x49c3, 0x12c4: 0x49c9, 0x12c5: 0x49cf, + 0x12c6: 0x49d5, 0x12c7: 0x49db, 0x12ca: 0x49e1, 0x12cb: 0x49e7, + 0x12cc: 0x49ed, 0x12cd: 0x49f3, 0x12ce: 0x49f9, 0x12cf: 0x49ff, + 0x12d2: 0x4a05, 0x12d3: 0x4a0b, 0x12d4: 0x4a11, 0x12d5: 0x4a17, 0x12d6: 0x4a1d, 0x12d7: 0x4a23, + 0x12da: 0x4a29, 0x12db: 0x4a2f, 0x12dc: 0x4a35, + 0x12e0: 0x00bf, 0x12e1: 0x00c2, 0x12e2: 0x00cb, 0x12e3: 0x4264, + 0x12e4: 0x00c8, 0x12e5: 0x00c5, 0x12e6: 0x0447, 0x12e8: 0x046b, 0x12e9: 0x044b, + 0x12ea: 0x044f, 0x12eb: 0x0453, 0x12ec: 0x0457, 0x12ed: 0x046f, 0x12ee: 0x0473, + // Block 0x4c, offset 0x1300 + 0x1300: 0x0063, 0x1301: 0x0065, 0x1302: 0x0067, 0x1303: 0x0069, 0x1304: 0x006b, 0x1305: 0x006d, + 0x1306: 0x006f, 0x1307: 0x0071, 0x1308: 0x0073, 0x1309: 0x0075, 0x130a: 0x0083, 0x130b: 0x0085, + 0x130c: 0x0087, 0x130d: 0x0089, 0x130e: 0x008b, 0x130f: 0x008d, 0x1310: 0x008f, 0x1311: 0x0091, + 0x1312: 0x0093, 0x1313: 0x0095, 0x1314: 0x0097, 0x1315: 0x0099, 0x1316: 0x009b, 0x1317: 0x009d, + 0x1318: 0x009f, 0x1319: 0x00a1, 0x131a: 0x00a3, 0x131b: 0x00a5, 0x131c: 0x00a7, 0x131d: 0x00a9, + 0x131e: 0x00ab, 0x131f: 0x00ad, 0x1320: 0x00af, 0x1321: 0x00b1, 0x1322: 0x00b3, 0x1323: 0x00b5, + 0x1324: 0x00dd, 0x1325: 0x00f2, 0x1328: 0x0173, 0x1329: 0x0176, + 0x132a: 0x0179, 0x132b: 0x017c, 0x132c: 0x017f, 0x132d: 0x0182, 0x132e: 0x0185, 0x132f: 0x0188, + 0x1330: 0x018b, 0x1331: 0x018e, 0x1332: 0x0191, 0x1333: 0x0194, 0x1334: 0x0197, 0x1335: 0x019a, + 0x1336: 0x019d, 0x1337: 0x01a0, 0x1338: 0x01a3, 0x1339: 0x0188, 0x133a: 0x01a6, 0x133b: 0x01a9, + 0x133c: 0x01ac, 0x133d: 0x01af, 0x133e: 0x01b2, 0x133f: 0x01b5, + // Block 0x4d, offset 0x1340 + 0x1340: 0x01fd, 0x1341: 0x0200, 0x1342: 0x0203, 0x1343: 0x045b, 0x1344: 0x01c7, 0x1345: 0x01d0, + 0x1346: 0x01d6, 0x1347: 0x01fa, 0x1348: 0x01eb, 0x1349: 0x01e8, 0x134a: 0x0206, 0x134b: 0x0209, + 0x134e: 0x0021, 0x134f: 0x0023, 0x1350: 0x0025, 0x1351: 0x0027, + 0x1352: 0x0029, 0x1353: 0x002b, 0x1354: 0x002d, 0x1355: 0x002f, 0x1356: 0x0031, 0x1357: 0x0033, + 0x1358: 0x0021, 0x1359: 0x0023, 0x135a: 0x0025, 0x135b: 0x0027, 0x135c: 0x0029, 0x135d: 0x002b, + 0x135e: 0x002d, 0x135f: 0x002f, 0x1360: 0x0031, 0x1361: 0x0033, 0x1362: 0x0021, 0x1363: 0x0023, + 0x1364: 0x0025, 0x1365: 0x0027, 0x1366: 0x0029, 0x1367: 0x002b, 0x1368: 0x002d, 0x1369: 0x002f, + 0x136a: 0x0031, 0x136b: 0x0033, 0x136c: 0x0021, 0x136d: 0x0023, 0x136e: 0x0025, 0x136f: 0x0027, + 0x1370: 0x0029, 0x1371: 0x002b, 0x1372: 0x002d, 0x1373: 0x002f, 0x1374: 0x0031, 0x1375: 0x0033, + 0x1376: 0x0021, 0x1377: 0x0023, 0x1378: 0x0025, 0x1379: 0x0027, 0x137a: 0x0029, 0x137b: 0x002b, + 0x137c: 0x002d, 0x137d: 0x002f, 0x137e: 0x0031, 0x137f: 0x0033, + // Block 0x4e, offset 0x1380 + 0x1380: 0x0239, 0x1381: 0x023c, 0x1382: 0x0248, 0x1383: 0x0251, 0x1385: 0x028a, + 0x1386: 0x025a, 0x1387: 0x024b, 0x1388: 0x0269, 0x1389: 0x0290, 0x138a: 0x027b, 0x138b: 0x027e, + 0x138c: 0x0281, 0x138d: 0x0284, 0x138e: 0x025d, 0x138f: 0x026f, 0x1390: 0x0275, 0x1391: 0x0263, + 0x1392: 0x0278, 0x1393: 0x0257, 0x1394: 0x0260, 0x1395: 0x0242, 0x1396: 0x0245, 0x1397: 0x024e, + 0x1398: 0x0254, 0x1399: 0x0266, 0x139a: 0x026c, 0x139b: 0x0272, 0x139c: 0x0293, 0x139d: 0x02e4, + 0x139e: 0x02cc, 0x139f: 0x0296, 0x13a1: 0x023c, 0x13a2: 0x0248, + 0x13a4: 0x0287, 0x13a7: 0x024b, 0x13a9: 0x0290, + 0x13aa: 0x027b, 0x13ab: 0x027e, 0x13ac: 0x0281, 0x13ad: 0x0284, 0x13ae: 0x025d, 0x13af: 0x026f, + 0x13b0: 0x0275, 0x13b1: 0x0263, 0x13b2: 0x0278, 0x13b4: 0x0260, 0x13b5: 0x0242, + 0x13b6: 0x0245, 0x13b7: 0x024e, 0x13b9: 0x0266, 0x13bb: 0x0272, + // Block 0x4f, offset 0x13c0 + 0x13c2: 0x0248, + 0x13c7: 0x024b, 0x13c9: 0x0290, 0x13cb: 0x027e, + 0x13cd: 0x0284, 0x13ce: 0x025d, 0x13cf: 0x026f, 0x13d1: 0x0263, + 0x13d2: 0x0278, 0x13d4: 0x0260, 0x13d7: 0x024e, + 0x13d9: 0x0266, 0x13db: 0x0272, 0x13dd: 0x02e4, + 0x13df: 0x0296, 0x13e1: 0x023c, 0x13e2: 0x0248, + 0x13e4: 0x0287, 0x13e7: 0x024b, 0x13e8: 0x0269, 0x13e9: 0x0290, + 0x13ea: 0x027b, 0x13ec: 0x0281, 0x13ed: 0x0284, 0x13ee: 0x025d, 0x13ef: 0x026f, + 0x13f0: 0x0275, 0x13f1: 0x0263, 0x13f2: 0x0278, 0x13f4: 0x0260, 0x13f5: 0x0242, + 0x13f6: 0x0245, 0x13f7: 0x024e, 0x13f9: 0x0266, 0x13fa: 0x026c, 0x13fb: 0x0272, + 0x13fc: 0x0293, 0x13fe: 0x02cc, + // Block 0x50, offset 0x1400 + 0x1400: 0x0239, 0x1401: 0x023c, 0x1402: 0x0248, 0x1403: 0x0251, 0x1404: 0x0287, 0x1405: 0x028a, + 0x1406: 0x025a, 0x1407: 0x024b, 0x1408: 0x0269, 0x1409: 0x0290, 0x140b: 0x027e, + 0x140c: 0x0281, 0x140d: 0x0284, 0x140e: 0x025d, 0x140f: 0x026f, 0x1410: 0x0275, 0x1411: 0x0263, + 0x1412: 0x0278, 0x1413: 0x0257, 0x1414: 0x0260, 0x1415: 0x0242, 0x1416: 0x0245, 0x1417: 0x024e, + 0x1418: 0x0254, 0x1419: 0x0266, 0x141a: 0x026c, 0x141b: 0x0272, + 0x1421: 0x023c, 0x1422: 0x0248, 0x1423: 0x0251, + 0x1425: 0x028a, 0x1426: 0x025a, 0x1427: 0x024b, 0x1428: 0x0269, 0x1429: 0x0290, + 0x142b: 0x027e, 0x142c: 0x0281, 0x142d: 0x0284, 0x142e: 0x025d, 0x142f: 0x026f, + 0x1430: 0x0275, 0x1431: 0x0263, 0x1432: 0x0278, 0x1433: 0x0257, 0x1434: 0x0260, 0x1435: 0x0242, + 0x1436: 0x0245, 0x1437: 0x024e, 0x1438: 0x0254, 0x1439: 0x0266, 0x143a: 0x026c, 0x143b: 0x0272, + // Block 0x51, offset 0x1440 + 0x1440: 0x1879, 0x1441: 0x1876, 0x1442: 0x187c, 0x1443: 0x18a0, 0x1444: 0x18c4, 0x1445: 0x18e8, + 0x1446: 0x190c, 0x1447: 0x1915, 0x1448: 0x191b, 0x1449: 0x1921, 0x144a: 0x1927, + 0x1450: 0x1a8c, 0x1451: 0x1a90, + 0x1452: 0x1a94, 0x1453: 0x1a98, 0x1454: 0x1a9c, 0x1455: 0x1aa0, 0x1456: 0x1aa4, 0x1457: 0x1aa8, + 0x1458: 0x1aac, 0x1459: 0x1ab0, 0x145a: 0x1ab4, 0x145b: 0x1ab8, 0x145c: 0x1abc, 0x145d: 0x1ac0, + 0x145e: 0x1ac4, 0x145f: 0x1ac8, 0x1460: 0x1acc, 0x1461: 0x1ad0, 0x1462: 0x1ad4, 0x1463: 0x1ad8, + 0x1464: 0x1adc, 0x1465: 0x1ae0, 0x1466: 0x1ae4, 0x1467: 0x1ae8, 0x1468: 0x1aec, 0x1469: 0x1af0, + 0x146a: 0x271e, 0x146b: 0x0047, 0x146c: 0x0065, 0x146d: 0x193c, 0x146e: 0x19b1, + 0x1470: 0x0043, 0x1471: 0x0045, 0x1472: 0x0047, 0x1473: 0x0049, 0x1474: 0x004b, 0x1475: 0x004d, + 0x1476: 0x004f, 0x1477: 0x0051, 0x1478: 0x0053, 0x1479: 0x0055, 0x147a: 0x0057, 0x147b: 0x0059, + 0x147c: 0x005b, 0x147d: 0x005d, 0x147e: 0x005f, 0x147f: 0x0061, + // Block 0x52, offset 0x1480 + 0x1480: 0x26ad, 0x1481: 0x26c2, 0x1482: 0x0503, + 0x1490: 0x0c0f, 0x1491: 0x0a47, + 0x1492: 0x08d3, 0x1493: 0x45c4, 0x1494: 0x071b, 0x1495: 0x09ef, 0x1496: 0x132f, 0x1497: 0x09ff, + 0x1498: 0x0727, 0x1499: 0x0cd7, 0x149a: 0x0eaf, 0x149b: 0x0caf, 0x149c: 0x0827, 0x149d: 0x0b6b, + 0x149e: 0x07bf, 0x149f: 0x0cb7, 0x14a0: 0x0813, 0x14a1: 0x1117, 0x14a2: 0x0f83, 0x14a3: 0x138b, + 0x14a4: 0x09d3, 0x14a5: 0x090b, 0x14a6: 0x0e63, 0x14a7: 0x0c1b, 0x14a8: 0x0c47, 0x14a9: 0x06bf, + 0x14aa: 0x06cb, 0x14ab: 0x140b, 0x14ac: 0x0adb, 0x14ad: 0x06e7, 0x14ae: 0x08ef, 0x14af: 0x0c3b, + 0x14b0: 0x13b3, 0x14b1: 0x0c13, 0x14b2: 0x106f, 0x14b3: 0x10ab, 0x14b4: 0x08f7, 0x14b5: 0x0e43, + 0x14b6: 0x0d0b, 0x14b7: 0x0d07, 0x14b8: 0x0f97, 0x14b9: 0x082b, 0x14ba: 0x0957, 0x14bb: 0x1443, + // Block 0x53, offset 0x14c0 + 0x14c0: 0x06fb, 0x14c1: 0x06f3, 0x14c2: 0x0703, 0x14c3: 0x1647, 0x14c4: 0x0747, 0x14c5: 0x0757, + 0x14c6: 0x075b, 0x14c7: 0x0763, 0x14c8: 0x076b, 0x14c9: 0x076f, 0x14ca: 0x077b, 0x14cb: 0x0773, + 0x14cc: 0x05b3, 0x14cd: 0x165b, 0x14ce: 0x078f, 0x14cf: 0x0793, 0x14d0: 0x0797, 0x14d1: 0x07b3, + 0x14d2: 0x164c, 0x14d3: 0x05b7, 0x14d4: 0x079f, 0x14d5: 0x07bf, 0x14d6: 0x1656, 0x14d7: 0x07cf, + 0x14d8: 0x07d7, 0x14d9: 0x0737, 0x14da: 0x07df, 0x14db: 0x07e3, 0x14dc: 0x1831, 0x14dd: 0x07ff, + 0x14de: 0x0807, 0x14df: 0x05bf, 0x14e0: 0x081f, 0x14e1: 0x0823, 0x14e2: 0x082b, 0x14e3: 0x082f, + 0x14e4: 0x05c3, 0x14e5: 0x0847, 0x14e6: 0x084b, 0x14e7: 0x0857, 0x14e8: 0x0863, 0x14e9: 0x0867, + 0x14ea: 0x086b, 0x14eb: 0x0873, 0x14ec: 0x0893, 0x14ed: 0x0897, 0x14ee: 0x089f, 0x14ef: 0x08af, + 0x14f0: 0x08b7, 0x14f1: 0x08bb, 0x14f2: 0x08bb, 0x14f3: 0x08bb, 0x14f4: 0x166a, 0x14f5: 0x0e93, + 0x14f6: 0x08cf, 0x14f7: 0x08d7, 0x14f8: 0x166f, 0x14f9: 0x08e3, 0x14fa: 0x08eb, 0x14fb: 0x08f3, + 0x14fc: 0x091b, 0x14fd: 0x0907, 0x14fe: 0x0913, 0x14ff: 0x0917, + // Block 0x54, offset 0x1500 + 0x1500: 0x091f, 0x1501: 0x0927, 0x1502: 0x092b, 0x1503: 0x0933, 0x1504: 0x093b, 0x1505: 0x093f, + 0x1506: 0x093f, 0x1507: 0x0947, 0x1508: 0x094f, 0x1509: 0x0953, 0x150a: 0x095f, 0x150b: 0x0983, + 0x150c: 0x0967, 0x150d: 0x0987, 0x150e: 0x096b, 0x150f: 0x0973, 0x1510: 0x080b, 0x1511: 0x09cf, + 0x1512: 0x0997, 0x1513: 0x099b, 0x1514: 0x099f, 0x1515: 0x0993, 0x1516: 0x09a7, 0x1517: 0x09a3, + 0x1518: 0x09bb, 0x1519: 0x1674, 0x151a: 0x09d7, 0x151b: 0x09db, 0x151c: 0x09e3, 0x151d: 0x09ef, + 0x151e: 0x09f7, 0x151f: 0x0a13, 0x1520: 0x1679, 0x1521: 0x167e, 0x1522: 0x0a1f, 0x1523: 0x0a23, + 0x1524: 0x0a27, 0x1525: 0x0a1b, 0x1526: 0x0a2f, 0x1527: 0x05c7, 0x1528: 0x05cb, 0x1529: 0x0a37, + 0x152a: 0x0a3f, 0x152b: 0x0a3f, 0x152c: 0x1683, 0x152d: 0x0a5b, 0x152e: 0x0a5f, 0x152f: 0x0a63, + 0x1530: 0x0a6b, 0x1531: 0x1688, 0x1532: 0x0a73, 0x1533: 0x0a77, 0x1534: 0x0b4f, 0x1535: 0x0a7f, + 0x1536: 0x05cf, 0x1537: 0x0a8b, 0x1538: 0x0a9b, 0x1539: 0x0aa7, 0x153a: 0x0aa3, 0x153b: 0x1692, + 0x153c: 0x0aaf, 0x153d: 0x1697, 0x153e: 0x0abb, 0x153f: 0x0ab7, + // Block 0x55, offset 0x1540 + 0x1540: 0x0abf, 0x1541: 0x0acf, 0x1542: 0x0ad3, 0x1543: 0x05d3, 0x1544: 0x0ae3, 0x1545: 0x0aeb, + 0x1546: 0x0aef, 0x1547: 0x0af3, 0x1548: 0x05d7, 0x1549: 0x169c, 0x154a: 0x05db, 0x154b: 0x0b0f, + 0x154c: 0x0b13, 0x154d: 0x0b17, 0x154e: 0x0b1f, 0x154f: 0x1863, 0x1550: 0x0b37, 0x1551: 0x16a6, + 0x1552: 0x16a6, 0x1553: 0x11d7, 0x1554: 0x0b47, 0x1555: 0x0b47, 0x1556: 0x05df, 0x1557: 0x16c9, + 0x1558: 0x179b, 0x1559: 0x0b57, 0x155a: 0x0b5f, 0x155b: 0x05e3, 0x155c: 0x0b73, 0x155d: 0x0b83, + 0x155e: 0x0b87, 0x155f: 0x0b8f, 0x1560: 0x0b9f, 0x1561: 0x05eb, 0x1562: 0x05e7, 0x1563: 0x0ba3, + 0x1564: 0x16ab, 0x1565: 0x0ba7, 0x1566: 0x0bbb, 0x1567: 0x0bbf, 0x1568: 0x0bc3, 0x1569: 0x0bbf, + 0x156a: 0x0bcf, 0x156b: 0x0bd3, 0x156c: 0x0be3, 0x156d: 0x0bdb, 0x156e: 0x0bdf, 0x156f: 0x0be7, + 0x1570: 0x0beb, 0x1571: 0x0bef, 0x1572: 0x0bfb, 0x1573: 0x0bff, 0x1574: 0x0c17, 0x1575: 0x0c1f, + 0x1576: 0x0c2f, 0x1577: 0x0c43, 0x1578: 0x16ba, 0x1579: 0x0c3f, 0x157a: 0x0c33, 0x157b: 0x0c4b, + 0x157c: 0x0c53, 0x157d: 0x0c67, 0x157e: 0x16bf, 0x157f: 0x0c6f, + // Block 0x56, offset 0x1580 + 0x1580: 0x0c63, 0x1581: 0x0c5b, 0x1582: 0x05ef, 0x1583: 0x0c77, 0x1584: 0x0c7f, 0x1585: 0x0c87, + 0x1586: 0x0c7b, 0x1587: 0x05f3, 0x1588: 0x0c97, 0x1589: 0x0c9f, 0x158a: 0x16c4, 0x158b: 0x0ccb, + 0x158c: 0x0cff, 0x158d: 0x0cdb, 0x158e: 0x05ff, 0x158f: 0x0ce7, 0x1590: 0x05fb, 0x1591: 0x05f7, + 0x1592: 0x07c3, 0x1593: 0x07c7, 0x1594: 0x0d03, 0x1595: 0x0ceb, 0x1596: 0x11ab, 0x1597: 0x0663, + 0x1598: 0x0d0f, 0x1599: 0x0d13, 0x159a: 0x0d17, 0x159b: 0x0d2b, 0x159c: 0x0d23, 0x159d: 0x16dd, + 0x159e: 0x0603, 0x159f: 0x0d3f, 0x15a0: 0x0d33, 0x15a1: 0x0d4f, 0x15a2: 0x0d57, 0x15a3: 0x16e7, + 0x15a4: 0x0d5b, 0x15a5: 0x0d47, 0x15a6: 0x0d63, 0x15a7: 0x0607, 0x15a8: 0x0d67, 0x15a9: 0x0d6b, + 0x15aa: 0x0d6f, 0x15ab: 0x0d7b, 0x15ac: 0x16ec, 0x15ad: 0x0d83, 0x15ae: 0x060b, 0x15af: 0x0d8f, + 0x15b0: 0x16f1, 0x15b1: 0x0d93, 0x15b2: 0x060f, 0x15b3: 0x0d9f, 0x15b4: 0x0dab, 0x15b5: 0x0db7, + 0x15b6: 0x0dbb, 0x15b7: 0x16f6, 0x15b8: 0x168d, 0x15b9: 0x16fb, 0x15ba: 0x0ddb, 0x15bb: 0x1700, + 0x15bc: 0x0de7, 0x15bd: 0x0def, 0x15be: 0x0ddf, 0x15bf: 0x0dfb, + // Block 0x57, offset 0x15c0 + 0x15c0: 0x0e0b, 0x15c1: 0x0e1b, 0x15c2: 0x0e0f, 0x15c3: 0x0e13, 0x15c4: 0x0e1f, 0x15c5: 0x0e23, + 0x15c6: 0x1705, 0x15c7: 0x0e07, 0x15c8: 0x0e3b, 0x15c9: 0x0e3f, 0x15ca: 0x0613, 0x15cb: 0x0e53, + 0x15cc: 0x0e4f, 0x15cd: 0x170a, 0x15ce: 0x0e33, 0x15cf: 0x0e6f, 0x15d0: 0x170f, 0x15d1: 0x1714, + 0x15d2: 0x0e73, 0x15d3: 0x0e87, 0x15d4: 0x0e83, 0x15d5: 0x0e7f, 0x15d6: 0x0617, 0x15d7: 0x0e8b, + 0x15d8: 0x0e9b, 0x15d9: 0x0e97, 0x15da: 0x0ea3, 0x15db: 0x1651, 0x15dc: 0x0eb3, 0x15dd: 0x1719, + 0x15de: 0x0ebf, 0x15df: 0x1723, 0x15e0: 0x0ed3, 0x15e1: 0x0edf, 0x15e2: 0x0ef3, 0x15e3: 0x1728, + 0x15e4: 0x0f07, 0x15e5: 0x0f0b, 0x15e6: 0x172d, 0x15e7: 0x1732, 0x15e8: 0x0f27, 0x15e9: 0x0f37, + 0x15ea: 0x061b, 0x15eb: 0x0f3b, 0x15ec: 0x061f, 0x15ed: 0x061f, 0x15ee: 0x0f53, 0x15ef: 0x0f57, + 0x15f0: 0x0f5f, 0x15f1: 0x0f63, 0x15f2: 0x0f6f, 0x15f3: 0x0623, 0x15f4: 0x0f87, 0x15f5: 0x1737, + 0x15f6: 0x0fa3, 0x15f7: 0x173c, 0x15f8: 0x0faf, 0x15f9: 0x16a1, 0x15fa: 0x0fbf, 0x15fb: 0x1741, + 0x15fc: 0x1746, 0x15fd: 0x174b, 0x15fe: 0x0627, 0x15ff: 0x062b, + // Block 0x58, offset 0x1600 + 0x1600: 0x0ff7, 0x1601: 0x1755, 0x1602: 0x1750, 0x1603: 0x175a, 0x1604: 0x175f, 0x1605: 0x0fff, + 0x1606: 0x1003, 0x1607: 0x1003, 0x1608: 0x100b, 0x1609: 0x0633, 0x160a: 0x100f, 0x160b: 0x0637, + 0x160c: 0x063b, 0x160d: 0x1769, 0x160e: 0x1023, 0x160f: 0x102b, 0x1610: 0x1037, 0x1611: 0x063f, + 0x1612: 0x176e, 0x1613: 0x105b, 0x1614: 0x1773, 0x1615: 0x1778, 0x1616: 0x107b, 0x1617: 0x1093, + 0x1618: 0x0643, 0x1619: 0x109b, 0x161a: 0x109f, 0x161b: 0x10a3, 0x161c: 0x177d, 0x161d: 0x1782, + 0x161e: 0x1782, 0x161f: 0x10bb, 0x1620: 0x0647, 0x1621: 0x1787, 0x1622: 0x10cf, 0x1623: 0x10d3, + 0x1624: 0x064b, 0x1625: 0x178c, 0x1626: 0x10ef, 0x1627: 0x064f, 0x1628: 0x10ff, 0x1629: 0x10f7, + 0x162a: 0x1107, 0x162b: 0x1796, 0x162c: 0x111f, 0x162d: 0x0653, 0x162e: 0x112b, 0x162f: 0x1133, + 0x1630: 0x1143, 0x1631: 0x0657, 0x1632: 0x17a0, 0x1633: 0x17a5, 0x1634: 0x065b, 0x1635: 0x17aa, + 0x1636: 0x115b, 0x1637: 0x17af, 0x1638: 0x1167, 0x1639: 0x1173, 0x163a: 0x117b, 0x163b: 0x17b4, + 0x163c: 0x17b9, 0x163d: 0x118f, 0x163e: 0x17be, 0x163f: 0x1197, + // Block 0x59, offset 0x1640 + 0x1640: 0x16ce, 0x1641: 0x065f, 0x1642: 0x11af, 0x1643: 0x11b3, 0x1644: 0x0667, 0x1645: 0x11b7, + 0x1646: 0x0a33, 0x1647: 0x17c3, 0x1648: 0x17c8, 0x1649: 0x16d3, 0x164a: 0x16d8, 0x164b: 0x11d7, + 0x164c: 0x11db, 0x164d: 0x13f3, 0x164e: 0x066b, 0x164f: 0x1207, 0x1650: 0x1203, 0x1651: 0x120b, + 0x1652: 0x083f, 0x1653: 0x120f, 0x1654: 0x1213, 0x1655: 0x1217, 0x1656: 0x121f, 0x1657: 0x17cd, + 0x1658: 0x121b, 0x1659: 0x1223, 0x165a: 0x1237, 0x165b: 0x123b, 0x165c: 0x1227, 0x165d: 0x123f, + 0x165e: 0x1253, 0x165f: 0x1267, 0x1660: 0x1233, 0x1661: 0x1247, 0x1662: 0x124b, 0x1663: 0x124f, + 0x1664: 0x17d2, 0x1665: 0x17dc, 0x1666: 0x17d7, 0x1667: 0x066f, 0x1668: 0x126f, 0x1669: 0x1273, + 0x166a: 0x127b, 0x166b: 0x17f0, 0x166c: 0x127f, 0x166d: 0x17e1, 0x166e: 0x0673, 0x166f: 0x0677, + 0x1670: 0x17e6, 0x1671: 0x17eb, 0x1672: 0x067b, 0x1673: 0x129f, 0x1674: 0x12a3, 0x1675: 0x12a7, + 0x1676: 0x12ab, 0x1677: 0x12b7, 0x1678: 0x12b3, 0x1679: 0x12bf, 0x167a: 0x12bb, 0x167b: 0x12cb, + 0x167c: 0x12c3, 0x167d: 0x12c7, 0x167e: 0x12cf, 0x167f: 0x067f, + // Block 0x5a, offset 0x1680 + 0x1680: 0x12d7, 0x1681: 0x12db, 0x1682: 0x0683, 0x1683: 0x12eb, 0x1684: 0x12ef, 0x1685: 0x17f5, + 0x1686: 0x12fb, 0x1687: 0x12ff, 0x1688: 0x0687, 0x1689: 0x130b, 0x168a: 0x05bb, 0x168b: 0x17fa, + 0x168c: 0x17ff, 0x168d: 0x068b, 0x168e: 0x068f, 0x168f: 0x1337, 0x1690: 0x134f, 0x1691: 0x136b, + 0x1692: 0x137b, 0x1693: 0x1804, 0x1694: 0x138f, 0x1695: 0x1393, 0x1696: 0x13ab, 0x1697: 0x13b7, + 0x1698: 0x180e, 0x1699: 0x1660, 0x169a: 0x13c3, 0x169b: 0x13bf, 0x169c: 0x13cb, 0x169d: 0x1665, + 0x169e: 0x13d7, 0x169f: 0x13e3, 0x16a0: 0x1813, 0x16a1: 0x1818, 0x16a2: 0x1423, 0x16a3: 0x142f, + 0x16a4: 0x1437, 0x16a5: 0x181d, 0x16a6: 0x143b, 0x16a7: 0x1467, 0x16a8: 0x1473, 0x16a9: 0x1477, + 0x16aa: 0x146f, 0x16ab: 0x1483, 0x16ac: 0x1487, 0x16ad: 0x1822, 0x16ae: 0x1493, 0x16af: 0x0693, + 0x16b0: 0x149b, 0x16b1: 0x1827, 0x16b2: 0x0697, 0x16b3: 0x14d3, 0x16b4: 0x0ac3, 0x16b5: 0x14eb, + 0x16b6: 0x182c, 0x16b7: 0x1836, 0x16b8: 0x069b, 0x16b9: 0x069f, 0x16ba: 0x1513, 0x16bb: 0x183b, + 0x16bc: 0x06a3, 0x16bd: 0x1840, 0x16be: 0x152b, 0x16bf: 0x152b, + // Block 0x5b, offset 0x16c0 + 0x16c0: 0x1533, 0x16c1: 0x1845, 0x16c2: 0x154b, 0x16c3: 0x06a7, 0x16c4: 0x155b, 0x16c5: 0x1567, + 0x16c6: 0x156f, 0x16c7: 0x1577, 0x16c8: 0x06ab, 0x16c9: 0x184a, 0x16ca: 0x158b, 0x16cb: 0x15a7, + 0x16cc: 0x15b3, 0x16cd: 0x06af, 0x16ce: 0x06b3, 0x16cf: 0x15b7, 0x16d0: 0x184f, 0x16d1: 0x06b7, + 0x16d2: 0x1854, 0x16d3: 0x1859, 0x16d4: 0x185e, 0x16d5: 0x15db, 0x16d6: 0x06bb, 0x16d7: 0x15ef, + 0x16d8: 0x15f7, 0x16d9: 0x15fb, 0x16da: 0x1603, 0x16db: 0x160b, 0x16dc: 0x1613, 0x16dd: 0x1868, +} + +// nfkcIndex: 22 blocks, 1408 entries, 1408 bytes +// Block 0 is the zero block. +var nfkcIndex = [1408]uint8{ + // Block 0x0, offset 0x0 + // Block 0x1, offset 0x40 + // Block 0x2, offset 0x80 + // Block 0x3, offset 0xc0 + 0xc2: 0x5a, 0xc3: 0x01, 0xc4: 0x02, 0xc5: 0x03, 0xc6: 0x5b, 0xc7: 0x04, + 0xc8: 0x05, 0xca: 0x5c, 0xcb: 0x5d, 0xcc: 0x06, 0xcd: 0x07, 0xce: 0x08, 0xcf: 0x09, + 0xd0: 0x0a, 0xd1: 0x5e, 0xd2: 0x5f, 0xd3: 0x0b, 0xd6: 0x0c, 0xd7: 0x60, + 0xd8: 0x61, 0xd9: 0x0d, 0xdb: 0x62, 0xdc: 0x63, 0xdd: 0x64, 0xdf: 0x65, + 0xe0: 0x02, 0xe1: 0x03, 0xe2: 0x04, 0xe3: 0x05, + 0xea: 0x06, 0xeb: 0x07, 0xec: 0x08, 0xed: 0x09, 0xef: 0x0a, + 0xf0: 0x13, + // Block 0x4, offset 0x100 + 0x120: 0x66, 0x121: 0x67, 0x123: 0x68, 0x124: 0x69, 0x125: 0x6a, 0x126: 0x6b, 0x127: 0x6c, + 0x128: 0x6d, 0x129: 0x6e, 0x12a: 0x6f, 0x12b: 0x70, 0x12c: 0x6b, 0x12d: 0x71, 0x12e: 0x72, 0x12f: 0x73, + 0x131: 0x74, 0x132: 0x75, 0x133: 0x76, 0x134: 0x77, 0x135: 0x78, 0x137: 0x79, + 0x138: 0x7a, 0x139: 0x7b, 0x13a: 0x7c, 0x13b: 0x7d, 0x13c: 0x7e, 0x13d: 0x7f, 0x13e: 0x80, 0x13f: 0x81, + // Block 0x5, offset 0x140 + 0x140: 0x82, 0x142: 0x83, 0x143: 0x84, 0x144: 0x85, 0x145: 0x86, 0x146: 0x87, 0x147: 0x88, + 0x14d: 0x89, + 0x15c: 0x8a, 0x15f: 0x8b, + 0x162: 0x8c, 0x164: 0x8d, + 0x168: 0x8e, 0x169: 0x8f, 0x16a: 0x90, 0x16c: 0x0e, 0x16d: 0x91, 0x16e: 0x92, 0x16f: 0x93, + 0x170: 0x94, 0x173: 0x95, 0x174: 0x96, 0x175: 0x0f, 0x176: 0x10, 0x177: 0x97, + 0x178: 0x11, 0x179: 0x12, 0x17a: 0x13, 0x17b: 0x14, 0x17c: 0x15, 0x17d: 0x16, 0x17e: 0x17, 0x17f: 0x18, + // Block 0x6, offset 0x180 + 0x180: 0x98, 0x181: 0x99, 0x182: 0x9a, 0x183: 0x9b, 0x184: 0x19, 0x185: 0x1a, 0x186: 0x9c, 0x187: 0x9d, + 0x188: 0x9e, 0x189: 0x1b, 0x18a: 0x1c, 0x18b: 0x9f, 0x18c: 0xa0, + 0x191: 0x1d, 0x192: 0x1e, 0x193: 0xa1, + 0x1a8: 0xa2, 0x1a9: 0xa3, 0x1ab: 0xa4, + 0x1b1: 0xa5, 0x1b3: 0xa6, 0x1b5: 0xa7, 0x1b7: 0xa8, + 0x1ba: 0xa9, 0x1bb: 0xaa, 0x1bc: 0x1f, 0x1bd: 0x20, 0x1be: 0x21, 0x1bf: 0xab, + // Block 0x7, offset 0x1c0 + 0x1c0: 0xac, 0x1c1: 0x22, 0x1c2: 0x23, 0x1c3: 0x24, 0x1c4: 0xad, 0x1c5: 0x25, 0x1c6: 0x26, + 0x1c8: 0x27, 0x1c9: 0x28, 0x1ca: 0x29, 0x1cb: 0x2a, 0x1cc: 0x2b, 0x1cd: 0x2c, 0x1ce: 0x2d, 0x1cf: 0x2e, + // Block 0x8, offset 0x200 + 0x219: 0xae, 0x21a: 0xaf, 0x21b: 0xb0, 0x21d: 0xb1, 0x21f: 0xb2, + 0x220: 0xb3, 0x223: 0xb4, 0x224: 0xb5, 0x225: 0xb6, 0x226: 0xb7, 0x227: 0xb8, + 0x22a: 0xb9, 0x22b: 0xba, 0x22d: 0xbb, 0x22f: 0xbc, + 0x230: 0xbd, 0x231: 0xbe, 0x232: 0xbf, 0x233: 0xc0, 0x234: 0xc1, 0x235: 0xc2, 0x236: 0xc3, 0x237: 0xbd, + 0x238: 0xbe, 0x239: 0xbf, 0x23a: 0xc0, 0x23b: 0xc1, 0x23c: 0xc2, 0x23d: 0xc3, 0x23e: 0xbd, 0x23f: 0xbe, + // Block 0x9, offset 0x240 + 0x240: 0xbf, 0x241: 0xc0, 0x242: 0xc1, 0x243: 0xc2, 0x244: 0xc3, 0x245: 0xbd, 0x246: 0xbe, 0x247: 0xbf, + 0x248: 0xc0, 0x249: 0xc1, 0x24a: 0xc2, 0x24b: 0xc3, 0x24c: 0xbd, 0x24d: 0xbe, 0x24e: 0xbf, 0x24f: 0xc0, + 0x250: 0xc1, 0x251: 0xc2, 0x252: 0xc3, 0x253: 0xbd, 0x254: 0xbe, 0x255: 0xbf, 0x256: 0xc0, 0x257: 0xc1, + 0x258: 0xc2, 0x259: 0xc3, 0x25a: 0xbd, 0x25b: 0xbe, 0x25c: 0xbf, 0x25d: 0xc0, 0x25e: 0xc1, 0x25f: 0xc2, + 0x260: 0xc3, 0x261: 0xbd, 0x262: 0xbe, 0x263: 0xbf, 0x264: 0xc0, 0x265: 0xc1, 0x266: 0xc2, 0x267: 0xc3, + 0x268: 0xbd, 0x269: 0xbe, 0x26a: 0xbf, 0x26b: 0xc0, 0x26c: 0xc1, 0x26d: 0xc2, 0x26e: 0xc3, 0x26f: 0xbd, + 0x270: 0xbe, 0x271: 0xbf, 0x272: 0xc0, 0x273: 0xc1, 0x274: 0xc2, 0x275: 0xc3, 0x276: 0xbd, 0x277: 0xbe, + 0x278: 0xbf, 0x279: 0xc0, 0x27a: 0xc1, 0x27b: 0xc2, 0x27c: 0xc3, 0x27d: 0xbd, 0x27e: 0xbe, 0x27f: 0xbf, + // Block 0xa, offset 0x280 + 0x280: 0xc0, 0x281: 0xc1, 0x282: 0xc2, 0x283: 0xc3, 0x284: 0xbd, 0x285: 0xbe, 0x286: 0xbf, 0x287: 0xc0, + 0x288: 0xc1, 0x289: 0xc2, 0x28a: 0xc3, 0x28b: 0xbd, 0x28c: 0xbe, 0x28d: 0xbf, 0x28e: 0xc0, 0x28f: 0xc1, + 0x290: 0xc2, 0x291: 0xc3, 0x292: 0xbd, 0x293: 0xbe, 0x294: 0xbf, 0x295: 0xc0, 0x296: 0xc1, 0x297: 0xc2, + 0x298: 0xc3, 0x299: 0xbd, 0x29a: 0xbe, 0x29b: 0xbf, 0x29c: 0xc0, 0x29d: 0xc1, 0x29e: 0xc2, 0x29f: 0xc3, + 0x2a0: 0xbd, 0x2a1: 0xbe, 0x2a2: 0xbf, 0x2a3: 0xc0, 0x2a4: 0xc1, 0x2a5: 0xc2, 0x2a6: 0xc3, 0x2a7: 0xbd, + 0x2a8: 0xbe, 0x2a9: 0xbf, 0x2aa: 0xc0, 0x2ab: 0xc1, 0x2ac: 0xc2, 0x2ad: 0xc3, 0x2ae: 0xbd, 0x2af: 0xbe, + 0x2b0: 0xbf, 0x2b1: 0xc0, 0x2b2: 0xc1, 0x2b3: 0xc2, 0x2b4: 0xc3, 0x2b5: 0xbd, 0x2b6: 0xbe, 0x2b7: 0xbf, + 0x2b8: 0xc0, 0x2b9: 0xc1, 0x2ba: 0xc2, 0x2bb: 0xc3, 0x2bc: 0xbd, 0x2bd: 0xbe, 0x2be: 0xbf, 0x2bf: 0xc0, + // Block 0xb, offset 0x2c0 + 0x2c0: 0xc1, 0x2c1: 0xc2, 0x2c2: 0xc3, 0x2c3: 0xbd, 0x2c4: 0xbe, 0x2c5: 0xbf, 0x2c6: 0xc0, 0x2c7: 0xc1, + 0x2c8: 0xc2, 0x2c9: 0xc3, 0x2ca: 0xbd, 0x2cb: 0xbe, 0x2cc: 0xbf, 0x2cd: 0xc0, 0x2ce: 0xc1, 0x2cf: 0xc2, + 0x2d0: 0xc3, 0x2d1: 0xbd, 0x2d2: 0xbe, 0x2d3: 0xbf, 0x2d4: 0xc0, 0x2d5: 0xc1, 0x2d6: 0xc2, 0x2d7: 0xc3, + 0x2d8: 0xbd, 0x2d9: 0xbe, 0x2da: 0xbf, 0x2db: 0xc0, 0x2dc: 0xc1, 0x2dd: 0xc2, 0x2de: 0xc4, + // Block 0xc, offset 0x300 + 0x324: 0x2f, 0x325: 0x30, 0x326: 0x31, 0x327: 0x32, + 0x328: 0x33, 0x329: 0x34, 0x32a: 0x35, 0x32b: 0x36, 0x32c: 0x37, 0x32d: 0x38, 0x32e: 0x39, 0x32f: 0x3a, + 0x330: 0x3b, 0x331: 0x3c, 0x332: 0x3d, 0x333: 0x3e, 0x334: 0x3f, 0x335: 0x40, 0x336: 0x41, 0x337: 0x42, + 0x338: 0x43, 0x339: 0x44, 0x33a: 0x45, 0x33b: 0x46, 0x33c: 0xc5, 0x33d: 0x47, 0x33e: 0x48, 0x33f: 0x49, + // Block 0xd, offset 0x340 + 0x347: 0xc6, + 0x34b: 0xc7, 0x34d: 0xc8, + 0x368: 0xc9, 0x36b: 0xca, + // Block 0xe, offset 0x380 + 0x381: 0xcb, 0x382: 0xcc, 0x384: 0xcd, 0x385: 0xb7, 0x387: 0xce, + 0x388: 0xcf, 0x38b: 0xd0, 0x38c: 0x6b, 0x38d: 0xd1, + 0x391: 0xd2, 0x392: 0xd3, 0x393: 0xd4, 0x396: 0xd5, 0x397: 0xd6, + 0x398: 0xd7, 0x39a: 0xd8, 0x39c: 0xd9, + 0x3b0: 0xd7, + // Block 0xf, offset 0x3c0 + 0x3eb: 0xda, 0x3ec: 0xdb, + // Block 0x10, offset 0x400 + 0x432: 0xdc, + // Block 0x11, offset 0x440 + 0x445: 0xdd, 0x446: 0xde, 0x447: 0xdf, + 0x449: 0xe0, + 0x450: 0xe1, 0x451: 0xe2, 0x452: 0xe3, 0x453: 0xe4, 0x454: 0xe5, 0x455: 0xe6, 0x456: 0xe7, 0x457: 0xe8, + 0x458: 0xe9, 0x459: 0xea, 0x45a: 0x4a, 0x45b: 0xeb, 0x45c: 0xec, 0x45d: 0xed, 0x45e: 0xee, 0x45f: 0x4b, + // Block 0x12, offset 0x480 + 0x480: 0xef, + 0x4a3: 0xf0, 0x4a5: 0xf1, + 0x4b8: 0x4c, 0x4b9: 0x4d, 0x4ba: 0x4e, + // Block 0x13, offset 0x4c0 + 0x4c4: 0x4f, 0x4c5: 0xf2, 0x4c6: 0xf3, + 0x4c8: 0x50, 0x4c9: 0xf4, + // Block 0x14, offset 0x500 + 0x520: 0x51, 0x521: 0x52, 0x522: 0x53, 0x523: 0x54, 0x524: 0x55, 0x525: 0x56, 0x526: 0x57, 0x527: 0x58, + 0x528: 0x59, + // Block 0x15, offset 0x540 + 0x550: 0x0b, 0x551: 0x0c, 0x556: 0x0d, + 0x55b: 0x0e, 0x55d: 0x0f, 0x55e: 0x10, 0x55f: 0x11, + 0x56f: 0x12, +} + +// nfkcSparseOffset: 155 entries, 310 bytes +var nfkcSparseOffset = []uint16{0x0, 0xe, 0x12, 0x1b, 0x25, 0x35, 0x37, 0x3c, 0x47, 0x56, 0x63, 0x6b, 0x6f, 0x74, 0x76, 0x87, 0x8f, 0x96, 0x99, 0xa0, 0xa4, 0xa8, 0xaa, 0xac, 0xb5, 0xb9, 0xc0, 0xc5, 0xc8, 0xd2, 0xd4, 0xdb, 0xe3, 0xe7, 0xe9, 0xec, 0xf0, 0xf6, 0x107, 0x113, 0x115, 0x11b, 0x11d, 0x11f, 0x121, 0x123, 0x125, 0x127, 0x129, 0x12c, 0x12f, 0x131, 0x134, 0x137, 0x13b, 0x140, 0x149, 0x14b, 0x14e, 0x150, 0x15b, 0x166, 0x176, 0x184, 0x192, 0x1a2, 0x1b0, 0x1b7, 0x1bd, 0x1cc, 0x1d0, 0x1d2, 0x1d6, 0x1d8, 0x1db, 0x1dd, 0x1e0, 0x1e2, 0x1e5, 0x1e7, 0x1e9, 0x1eb, 0x1f7, 0x201, 0x20b, 0x20e, 0x212, 0x214, 0x216, 0x218, 0x21a, 0x21d, 0x21f, 0x221, 0x223, 0x225, 0x22b, 0x22e, 0x232, 0x234, 0x23b, 0x241, 0x247, 0x24f, 0x255, 0x25b, 0x261, 0x265, 0x267, 0x269, 0x26b, 0x26d, 0x273, 0x276, 0x279, 0x281, 0x288, 0x28b, 0x28e, 0x290, 0x298, 0x29b, 0x2a2, 0x2a5, 0x2ab, 0x2ad, 0x2af, 0x2b2, 0x2b4, 0x2b6, 0x2b8, 0x2ba, 0x2c7, 0x2d1, 0x2d3, 0x2d5, 0x2d9, 0x2de, 0x2ea, 0x2ef, 0x2f8, 0x2fe, 0x303, 0x307, 0x30c, 0x310, 0x320, 0x32e, 0x33c, 0x34a, 0x350, 0x352, 0x355, 0x35f, 0x361} + +// nfkcSparseValues: 875 entries, 3500 bytes +var nfkcSparseValues = [875]valueRange{ + // Block 0x0, offset 0x0 + {value: 0x0002, lo: 0x0d}, + {value: 0x0001, lo: 0xa0, hi: 0xa0}, + {value: 0x4278, lo: 0xa8, hi: 0xa8}, + {value: 0x0083, lo: 0xaa, hi: 0xaa}, + {value: 0x4264, lo: 0xaf, hi: 0xaf}, + {value: 0x0025, lo: 0xb2, hi: 0xb3}, + {value: 0x425a, lo: 0xb4, hi: 0xb4}, + {value: 0x01dc, lo: 0xb5, hi: 0xb5}, + {value: 0x4291, lo: 0xb8, hi: 0xb8}, + {value: 0x0023, lo: 0xb9, hi: 0xb9}, + {value: 0x009f, lo: 0xba, hi: 0xba}, + {value: 0x221c, lo: 0xbc, hi: 0xbc}, + {value: 0x2210, lo: 0xbd, hi: 0xbd}, + {value: 0x22b2, lo: 0xbe, hi: 0xbe}, + // Block 0x1, offset 0xe + {value: 0x0091, lo: 0x03}, + {value: 0x46e2, lo: 0xa0, hi: 0xa1}, + {value: 0x4714, lo: 0xaf, hi: 0xb0}, + {value: 0xa000, lo: 0xb7, hi: 0xb7}, + // Block 0x2, offset 0x12 + {value: 0x0003, lo: 0x08}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x0091, lo: 0xb0, hi: 0xb0}, + {value: 0x0119, lo: 0xb1, hi: 0xb1}, + {value: 0x0095, lo: 0xb2, hi: 0xb2}, + {value: 0x00a5, lo: 0xb3, hi: 0xb3}, + {value: 0x0143, lo: 0xb4, hi: 0xb6}, + {value: 0x00af, lo: 0xb7, hi: 0xb7}, + {value: 0x00b3, lo: 0xb8, hi: 0xb8}, + // Block 0x3, offset 0x1b + {value: 0x000a, lo: 0x09}, + {value: 0x426e, lo: 0x98, hi: 0x98}, + {value: 0x4273, lo: 0x99, hi: 0x9a}, + {value: 0x4296, lo: 0x9b, hi: 0x9b}, + {value: 0x425f, lo: 0x9c, hi: 0x9c}, + {value: 0x4282, lo: 0x9d, hi: 0x9d}, + {value: 0x0113, lo: 0xa0, hi: 0xa0}, + {value: 0x0099, lo: 0xa1, hi: 0xa1}, + {value: 0x00a7, lo: 0xa2, hi: 0xa3}, + {value: 0x0167, lo: 0xa4, hi: 0xa4}, + // Block 0x4, offset 0x25 + {value: 0x0000, lo: 0x0f}, + {value: 0xa000, lo: 0x83, hi: 0x83}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0xa000, lo: 0x8b, hi: 0x8b}, + {value: 0xa000, lo: 0x8d, hi: 0x8d}, + {value: 0x37a5, lo: 0x90, hi: 0x90}, + {value: 0x37b1, lo: 0x91, hi: 0x91}, + {value: 0x379f, lo: 0x93, hi: 0x93}, + {value: 0xa000, lo: 0x96, hi: 0x96}, + {value: 0x3817, lo: 0x97, hi: 0x97}, + {value: 0x37e1, lo: 0x9c, hi: 0x9c}, + {value: 0x37c9, lo: 0x9d, hi: 0x9d}, + {value: 0x37f3, lo: 0x9e, hi: 0x9e}, + {value: 0xa000, lo: 0xb4, hi: 0xb5}, + {value: 0x381d, lo: 0xb6, hi: 0xb6}, + {value: 0x3823, lo: 0xb7, hi: 0xb7}, + // Block 0x5, offset 0x35 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x83, hi: 0x87}, + // Block 0x6, offset 0x37 + {value: 0x0001, lo: 0x04}, + {value: 0x8113, lo: 0x81, hi: 0x82}, + {value: 0x8132, lo: 0x84, hi: 0x84}, + {value: 0x812d, lo: 0x85, hi: 0x85}, + {value: 0x810d, lo: 0x87, hi: 0x87}, + // Block 0x7, offset 0x3c + {value: 0x0000, lo: 0x0a}, + {value: 0x8132, lo: 0x90, hi: 0x97}, + {value: 0x8119, lo: 0x98, hi: 0x98}, + {value: 0x811a, lo: 0x99, hi: 0x99}, + {value: 0x811b, lo: 0x9a, hi: 0x9a}, + {value: 0x3841, lo: 0xa2, hi: 0xa2}, + {value: 0x3847, lo: 0xa3, hi: 0xa3}, + {value: 0x3853, lo: 0xa4, hi: 0xa4}, + {value: 0x384d, lo: 0xa5, hi: 0xa5}, + {value: 0x3859, lo: 0xa6, hi: 0xa6}, + {value: 0xa000, lo: 0xa7, hi: 0xa7}, + // Block 0x8, offset 0x47 + {value: 0x0000, lo: 0x0e}, + {value: 0x386b, lo: 0x80, hi: 0x80}, + {value: 0xa000, lo: 0x81, hi: 0x81}, + {value: 0x385f, lo: 0x82, hi: 0x82}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x3865, lo: 0x93, hi: 0x93}, + {value: 0xa000, lo: 0x95, hi: 0x95}, + {value: 0x8132, lo: 0x96, hi: 0x9c}, + {value: 0x8132, lo: 0x9f, hi: 0xa2}, + {value: 0x812d, lo: 0xa3, hi: 0xa3}, + {value: 0x8132, lo: 0xa4, hi: 0xa4}, + {value: 0x8132, lo: 0xa7, hi: 0xa8}, + {value: 0x812d, lo: 0xaa, hi: 0xaa}, + {value: 0x8132, lo: 0xab, hi: 0xac}, + {value: 0x812d, lo: 0xad, hi: 0xad}, + // Block 0x9, offset 0x56 + {value: 0x0000, lo: 0x0c}, + {value: 0x811f, lo: 0x91, hi: 0x91}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + {value: 0x812d, lo: 0xb1, hi: 0xb1}, + {value: 0x8132, lo: 0xb2, hi: 0xb3}, + {value: 0x812d, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb5, hi: 0xb6}, + {value: 0x812d, lo: 0xb7, hi: 0xb9}, + {value: 0x8132, lo: 0xba, hi: 0xba}, + {value: 0x812d, lo: 0xbb, hi: 0xbc}, + {value: 0x8132, lo: 0xbd, hi: 0xbd}, + {value: 0x812d, lo: 0xbe, hi: 0xbe}, + {value: 0x8132, lo: 0xbf, hi: 0xbf}, + // Block 0xa, offset 0x63 + {value: 0x0005, lo: 0x07}, + {value: 0x8132, lo: 0x80, hi: 0x80}, + {value: 0x8132, lo: 0x81, hi: 0x81}, + {value: 0x812d, lo: 0x82, hi: 0x83}, + {value: 0x812d, lo: 0x84, hi: 0x85}, + {value: 0x812d, lo: 0x86, hi: 0x87}, + {value: 0x812d, lo: 0x88, hi: 0x89}, + {value: 0x8132, lo: 0x8a, hi: 0x8a}, + // Block 0xb, offset 0x6b + {value: 0x0000, lo: 0x03}, + {value: 0x8132, lo: 0xab, hi: 0xb1}, + {value: 0x812d, lo: 0xb2, hi: 0xb2}, + {value: 0x8132, lo: 0xb3, hi: 0xb3}, + // Block 0xc, offset 0x6f + {value: 0x0000, lo: 0x04}, + {value: 0x8132, lo: 0x96, hi: 0x99}, + {value: 0x8132, lo: 0x9b, hi: 0xa3}, + {value: 0x8132, lo: 0xa5, hi: 0xa7}, + {value: 0x8132, lo: 0xa9, hi: 0xad}, + // Block 0xd, offset 0x74 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x99, hi: 0x9b}, + // Block 0xe, offset 0x76 + {value: 0x0000, lo: 0x10}, + {value: 0x8132, lo: 0x94, hi: 0xa1}, + {value: 0x812d, lo: 0xa3, hi: 0xa3}, + {value: 0x8132, lo: 0xa4, hi: 0xa5}, + {value: 0x812d, lo: 0xa6, hi: 0xa6}, + {value: 0x8132, lo: 0xa7, hi: 0xa8}, + {value: 0x812d, lo: 0xa9, hi: 0xa9}, + {value: 0x8132, lo: 0xaa, hi: 0xac}, + {value: 0x812d, lo: 0xad, hi: 0xaf}, + {value: 0x8116, lo: 0xb0, hi: 0xb0}, + {value: 0x8117, lo: 0xb1, hi: 0xb1}, + {value: 0x8118, lo: 0xb2, hi: 0xb2}, + {value: 0x8132, lo: 0xb3, hi: 0xb5}, + {value: 0x812d, lo: 0xb6, hi: 0xb6}, + {value: 0x8132, lo: 0xb7, hi: 0xb8}, + {value: 0x812d, lo: 0xb9, hi: 0xba}, + {value: 0x8132, lo: 0xbb, hi: 0xbf}, + // Block 0xf, offset 0x87 + {value: 0x0000, lo: 0x07}, + {value: 0xa000, lo: 0xa8, hi: 0xa8}, + {value: 0x3ed8, lo: 0xa9, hi: 0xa9}, + {value: 0xa000, lo: 0xb0, hi: 0xb0}, + {value: 0x3ee0, lo: 0xb1, hi: 0xb1}, + {value: 0xa000, lo: 0xb3, hi: 0xb3}, + {value: 0x3ee8, lo: 0xb4, hi: 0xb4}, + {value: 0x9902, lo: 0xbc, hi: 0xbc}, + // Block 0x10, offset 0x8f + {value: 0x0008, lo: 0x06}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x8132, lo: 0x91, hi: 0x91}, + {value: 0x812d, lo: 0x92, hi: 0x92}, + {value: 0x8132, lo: 0x93, hi: 0x93}, + {value: 0x8132, lo: 0x94, hi: 0x94}, + {value: 0x451c, lo: 0x98, hi: 0x9f}, + // Block 0x11, offset 0x96 + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x12, offset 0x99 + {value: 0x0008, lo: 0x06}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2c9e, lo: 0x8b, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + {value: 0x455c, lo: 0x9c, hi: 0x9d}, + {value: 0x456c, lo: 0x9f, hi: 0x9f}, + // Block 0x13, offset 0xa0 + {value: 0x0000, lo: 0x03}, + {value: 0x4594, lo: 0xb3, hi: 0xb3}, + {value: 0x459c, lo: 0xb6, hi: 0xb6}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + // Block 0x14, offset 0xa4 + {value: 0x0008, lo: 0x03}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x4574, lo: 0x99, hi: 0x9b}, + {value: 0x458c, lo: 0x9e, hi: 0x9e}, + // Block 0x15, offset 0xa8 + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + // Block 0x16, offset 0xaa + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + // Block 0x17, offset 0xac + {value: 0x0000, lo: 0x08}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2cb6, lo: 0x88, hi: 0x88}, + {value: 0x2cae, lo: 0x8b, hi: 0x8b}, + {value: 0x2cbe, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x96, hi: 0x97}, + {value: 0x45a4, lo: 0x9c, hi: 0x9c}, + {value: 0x45ac, lo: 0x9d, hi: 0x9d}, + // Block 0x18, offset 0xb5 + {value: 0x0000, lo: 0x03}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0x2cc6, lo: 0x94, hi: 0x94}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x19, offset 0xb9 + {value: 0x0000, lo: 0x06}, + {value: 0xa000, lo: 0x86, hi: 0x87}, + {value: 0x2cce, lo: 0x8a, hi: 0x8a}, + {value: 0x2cde, lo: 0x8b, hi: 0x8b}, + {value: 0x2cd6, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + // Block 0x1a, offset 0xc0 + {value: 0x1801, lo: 0x04}, + {value: 0xa000, lo: 0x86, hi: 0x86}, + {value: 0x3ef0, lo: 0x88, hi: 0x88}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x8120, lo: 0x95, hi: 0x96}, + // Block 0x1b, offset 0xc5 + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xbc, hi: 0xbc}, + {value: 0xa000, lo: 0xbf, hi: 0xbf}, + // Block 0x1c, offset 0xc8 + {value: 0x0000, lo: 0x09}, + {value: 0x2ce6, lo: 0x80, hi: 0x80}, + {value: 0x9900, lo: 0x82, hi: 0x82}, + {value: 0xa000, lo: 0x86, hi: 0x86}, + {value: 0x2cee, lo: 0x87, hi: 0x87}, + {value: 0x2cf6, lo: 0x88, hi: 0x88}, + {value: 0x2f50, lo: 0x8a, hi: 0x8a}, + {value: 0x2dd8, lo: 0x8b, hi: 0x8b}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x95, hi: 0x96}, + // Block 0x1d, offset 0xd2 + {value: 0x0000, lo: 0x01}, + {value: 0x9900, lo: 0xbe, hi: 0xbe}, + // Block 0x1e, offset 0xd4 + {value: 0x0000, lo: 0x06}, + {value: 0xa000, lo: 0x86, hi: 0x87}, + {value: 0x2cfe, lo: 0x8a, hi: 0x8a}, + {value: 0x2d0e, lo: 0x8b, hi: 0x8b}, + {value: 0x2d06, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + // Block 0x1f, offset 0xdb + {value: 0x6bea, lo: 0x07}, + {value: 0x9904, lo: 0x8a, hi: 0x8a}, + {value: 0x9900, lo: 0x8f, hi: 0x8f}, + {value: 0xa000, lo: 0x99, hi: 0x99}, + {value: 0x3ef8, lo: 0x9a, hi: 0x9a}, + {value: 0x2f58, lo: 0x9c, hi: 0x9c}, + {value: 0x2de3, lo: 0x9d, hi: 0x9d}, + {value: 0x2d16, lo: 0x9e, hi: 0x9f}, + // Block 0x20, offset 0xe3 + {value: 0x0000, lo: 0x03}, + {value: 0x2621, lo: 0xb3, hi: 0xb3}, + {value: 0x8122, lo: 0xb8, hi: 0xb9}, + {value: 0x8104, lo: 0xba, hi: 0xba}, + // Block 0x21, offset 0xe7 + {value: 0x0000, lo: 0x01}, + {value: 0x8123, lo: 0x88, hi: 0x8b}, + // Block 0x22, offset 0xe9 + {value: 0x0000, lo: 0x02}, + {value: 0x2636, lo: 0xb3, hi: 0xb3}, + {value: 0x8124, lo: 0xb8, hi: 0xb9}, + // Block 0x23, offset 0xec + {value: 0x0000, lo: 0x03}, + {value: 0x8125, lo: 0x88, hi: 0x8b}, + {value: 0x2628, lo: 0x9c, hi: 0x9c}, + {value: 0x262f, lo: 0x9d, hi: 0x9d}, + // Block 0x24, offset 0xf0 + {value: 0x0000, lo: 0x05}, + {value: 0x030b, lo: 0x8c, hi: 0x8c}, + {value: 0x812d, lo: 0x98, hi: 0x99}, + {value: 0x812d, lo: 0xb5, hi: 0xb5}, + {value: 0x812d, lo: 0xb7, hi: 0xb7}, + {value: 0x812b, lo: 0xb9, hi: 0xb9}, + // Block 0x25, offset 0xf6 + {value: 0x0000, lo: 0x10}, + {value: 0x2644, lo: 0x83, hi: 0x83}, + {value: 0x264b, lo: 0x8d, hi: 0x8d}, + {value: 0x2652, lo: 0x92, hi: 0x92}, + {value: 0x2659, lo: 0x97, hi: 0x97}, + {value: 0x2660, lo: 0x9c, hi: 0x9c}, + {value: 0x263d, lo: 0xa9, hi: 0xa9}, + {value: 0x8126, lo: 0xb1, hi: 0xb1}, + {value: 0x8127, lo: 0xb2, hi: 0xb2}, + {value: 0x4a84, lo: 0xb3, hi: 0xb3}, + {value: 0x8128, lo: 0xb4, hi: 0xb4}, + {value: 0x4a8d, lo: 0xb5, hi: 0xb5}, + {value: 0x45b4, lo: 0xb6, hi: 0xb6}, + {value: 0x45f4, lo: 0xb7, hi: 0xb7}, + {value: 0x45bc, lo: 0xb8, hi: 0xb8}, + {value: 0x45ff, lo: 0xb9, hi: 0xb9}, + {value: 0x8127, lo: 0xba, hi: 0xbd}, + // Block 0x26, offset 0x107 + {value: 0x0000, lo: 0x0b}, + {value: 0x8127, lo: 0x80, hi: 0x80}, + {value: 0x4a96, lo: 0x81, hi: 0x81}, + {value: 0x8132, lo: 0x82, hi: 0x83}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0x86, hi: 0x87}, + {value: 0x266e, lo: 0x93, hi: 0x93}, + {value: 0x2675, lo: 0x9d, hi: 0x9d}, + {value: 0x267c, lo: 0xa2, hi: 0xa2}, + {value: 0x2683, lo: 0xa7, hi: 0xa7}, + {value: 0x268a, lo: 0xac, hi: 0xac}, + {value: 0x2667, lo: 0xb9, hi: 0xb9}, + // Block 0x27, offset 0x113 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x86, hi: 0x86}, + // Block 0x28, offset 0x115 + {value: 0x0000, lo: 0x05}, + {value: 0xa000, lo: 0xa5, hi: 0xa5}, + {value: 0x2d1e, lo: 0xa6, hi: 0xa6}, + {value: 0x9900, lo: 0xae, hi: 0xae}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + {value: 0x8104, lo: 0xb9, hi: 0xba}, + // Block 0x29, offset 0x11b + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x8d, hi: 0x8d}, + // Block 0x2a, offset 0x11d + {value: 0x0000, lo: 0x01}, + {value: 0x030f, lo: 0xbc, hi: 0xbc}, + // Block 0x2b, offset 0x11f + {value: 0x0000, lo: 0x01}, + {value: 0xa000, lo: 0x80, hi: 0x92}, + // Block 0x2c, offset 0x121 + {value: 0x0000, lo: 0x01}, + {value: 0xb900, lo: 0xa1, hi: 0xb5}, + // Block 0x2d, offset 0x123 + {value: 0x0000, lo: 0x01}, + {value: 0x9900, lo: 0xa8, hi: 0xbf}, + // Block 0x2e, offset 0x125 + {value: 0x0000, lo: 0x01}, + {value: 0x9900, lo: 0x80, hi: 0x82}, + // Block 0x2f, offset 0x127 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x9d, hi: 0x9f}, + // Block 0x30, offset 0x129 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x94, hi: 0x94}, + {value: 0x8104, lo: 0xb4, hi: 0xb4}, + // Block 0x31, offset 0x12c + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x92, hi: 0x92}, + {value: 0x8132, lo: 0x9d, hi: 0x9d}, + // Block 0x32, offset 0x12f + {value: 0x0000, lo: 0x01}, + {value: 0x8131, lo: 0xa9, hi: 0xa9}, + // Block 0x33, offset 0x131 + {value: 0x0004, lo: 0x02}, + {value: 0x812e, lo: 0xb9, hi: 0xba}, + {value: 0x812d, lo: 0xbb, hi: 0xbb}, + // Block 0x34, offset 0x134 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x97, hi: 0x97}, + {value: 0x812d, lo: 0x98, hi: 0x98}, + // Block 0x35, offset 0x137 + {value: 0x0000, lo: 0x03}, + {value: 0x8104, lo: 0xa0, hi: 0xa0}, + {value: 0x8132, lo: 0xb5, hi: 0xbc}, + {value: 0x812d, lo: 0xbf, hi: 0xbf}, + // Block 0x36, offset 0x13b + {value: 0x0000, lo: 0x04}, + {value: 0x8132, lo: 0xb0, hi: 0xb4}, + {value: 0x812d, lo: 0xb5, hi: 0xba}, + {value: 0x8132, lo: 0xbb, hi: 0xbc}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + // Block 0x37, offset 0x140 + {value: 0x0000, lo: 0x08}, + {value: 0x2d66, lo: 0x80, hi: 0x80}, + {value: 0x2d6e, lo: 0x81, hi: 0x81}, + {value: 0xa000, lo: 0x82, hi: 0x82}, + {value: 0x2d76, lo: 0x83, hi: 0x83}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0xab, hi: 0xab}, + {value: 0x812d, lo: 0xac, hi: 0xac}, + {value: 0x8132, lo: 0xad, hi: 0xb3}, + // Block 0x38, offset 0x149 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xaa, hi: 0xab}, + // Block 0x39, offset 0x14b + {value: 0x0000, lo: 0x02}, + {value: 0x8102, lo: 0xa6, hi: 0xa6}, + {value: 0x8104, lo: 0xb2, hi: 0xb3}, + // Block 0x3a, offset 0x14e + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + // Block 0x3b, offset 0x150 + {value: 0x0000, lo: 0x0a}, + {value: 0x8132, lo: 0x90, hi: 0x92}, + {value: 0x8101, lo: 0x94, hi: 0x94}, + {value: 0x812d, lo: 0x95, hi: 0x99}, + {value: 0x8132, lo: 0x9a, hi: 0x9b}, + {value: 0x812d, lo: 0x9c, hi: 0x9f}, + {value: 0x8132, lo: 0xa0, hi: 0xa0}, + {value: 0x8101, lo: 0xa2, hi: 0xa8}, + {value: 0x812d, lo: 0xad, hi: 0xad}, + {value: 0x8132, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb8, hi: 0xb9}, + // Block 0x3c, offset 0x15b + {value: 0x0002, lo: 0x0a}, + {value: 0x0043, lo: 0xac, hi: 0xac}, + {value: 0x00d1, lo: 0xad, hi: 0xad}, + {value: 0x0045, lo: 0xae, hi: 0xae}, + {value: 0x0049, lo: 0xb0, hi: 0xb1}, + {value: 0x00e6, lo: 0xb2, hi: 0xb2}, + {value: 0x004f, lo: 0xb3, hi: 0xba}, + {value: 0x005f, lo: 0xbc, hi: 0xbc}, + {value: 0x00ef, lo: 0xbd, hi: 0xbd}, + {value: 0x0061, lo: 0xbe, hi: 0xbe}, + {value: 0x0065, lo: 0xbf, hi: 0xbf}, + // Block 0x3d, offset 0x166 + {value: 0x0000, lo: 0x0f}, + {value: 0x8132, lo: 0x80, hi: 0x81}, + {value: 0x812d, lo: 0x82, hi: 0x82}, + {value: 0x8132, lo: 0x83, hi: 0x89}, + {value: 0x812d, lo: 0x8a, hi: 0x8a}, + {value: 0x8132, lo: 0x8b, hi: 0x8c}, + {value: 0x8135, lo: 0x8d, hi: 0x8d}, + {value: 0x812a, lo: 0x8e, hi: 0x8e}, + {value: 0x812d, lo: 0x8f, hi: 0x8f}, + {value: 0x8129, lo: 0x90, hi: 0x90}, + {value: 0x8132, lo: 0x91, hi: 0xb5}, + {value: 0x8132, lo: 0xbb, hi: 0xbb}, + {value: 0x8134, lo: 0xbc, hi: 0xbc}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + {value: 0x8132, lo: 0xbe, hi: 0xbe}, + {value: 0x812d, lo: 0xbf, hi: 0xbf}, + // Block 0x3e, offset 0x176 + {value: 0x0000, lo: 0x0d}, + {value: 0x0001, lo: 0x80, hi: 0x8a}, + {value: 0x043b, lo: 0x91, hi: 0x91}, + {value: 0x429b, lo: 0x97, hi: 0x97}, + {value: 0x001d, lo: 0xa4, hi: 0xa4}, + {value: 0x1873, lo: 0xa5, hi: 0xa5}, + {value: 0x1b5c, lo: 0xa6, hi: 0xa6}, + {value: 0x0001, lo: 0xaf, hi: 0xaf}, + {value: 0x2691, lo: 0xb3, hi: 0xb3}, + {value: 0x27fe, lo: 0xb4, hi: 0xb4}, + {value: 0x2698, lo: 0xb6, hi: 0xb6}, + {value: 0x2808, lo: 0xb7, hi: 0xb7}, + {value: 0x186d, lo: 0xbc, hi: 0xbc}, + {value: 0x4269, lo: 0xbe, hi: 0xbe}, + // Block 0x3f, offset 0x184 + {value: 0x0002, lo: 0x0d}, + {value: 0x1933, lo: 0x87, hi: 0x87}, + {value: 0x1930, lo: 0x88, hi: 0x88}, + {value: 0x1870, lo: 0x89, hi: 0x89}, + {value: 0x298e, lo: 0x97, hi: 0x97}, + {value: 0x0001, lo: 0x9f, hi: 0x9f}, + {value: 0x0021, lo: 0xb0, hi: 0xb0}, + {value: 0x0093, lo: 0xb1, hi: 0xb1}, + {value: 0x0029, lo: 0xb4, hi: 0xb9}, + {value: 0x0017, lo: 0xba, hi: 0xba}, + {value: 0x0467, lo: 0xbb, hi: 0xbb}, + {value: 0x003b, lo: 0xbc, hi: 0xbc}, + {value: 0x0011, lo: 0xbd, hi: 0xbe}, + {value: 0x009d, lo: 0xbf, hi: 0xbf}, + // Block 0x40, offset 0x192 + {value: 0x0002, lo: 0x0f}, + {value: 0x0021, lo: 0x80, hi: 0x89}, + {value: 0x0017, lo: 0x8a, hi: 0x8a}, + {value: 0x0467, lo: 0x8b, hi: 0x8b}, + {value: 0x003b, lo: 0x8c, hi: 0x8c}, + {value: 0x0011, lo: 0x8d, hi: 0x8e}, + {value: 0x0083, lo: 0x90, hi: 0x90}, + {value: 0x008b, lo: 0x91, hi: 0x91}, + {value: 0x009f, lo: 0x92, hi: 0x92}, + {value: 0x00b1, lo: 0x93, hi: 0x93}, + {value: 0x0104, lo: 0x94, hi: 0x94}, + {value: 0x0091, lo: 0x95, hi: 0x95}, + {value: 0x0097, lo: 0x96, hi: 0x99}, + {value: 0x00a1, lo: 0x9a, hi: 0x9a}, + {value: 0x00a7, lo: 0x9b, hi: 0x9c}, + {value: 0x1999, lo: 0xa8, hi: 0xa8}, + // Block 0x41, offset 0x1a2 + {value: 0x0000, lo: 0x0d}, + {value: 0x8132, lo: 0x90, hi: 0x91}, + {value: 0x8101, lo: 0x92, hi: 0x93}, + {value: 0x8132, lo: 0x94, hi: 0x97}, + {value: 0x8101, lo: 0x98, hi: 0x9a}, + {value: 0x8132, lo: 0x9b, hi: 0x9c}, + {value: 0x8132, lo: 0xa1, hi: 0xa1}, + {value: 0x8101, lo: 0xa5, hi: 0xa6}, + {value: 0x8132, lo: 0xa7, hi: 0xa7}, + {value: 0x812d, lo: 0xa8, hi: 0xa8}, + {value: 0x8132, lo: 0xa9, hi: 0xa9}, + {value: 0x8101, lo: 0xaa, hi: 0xab}, + {value: 0x812d, lo: 0xac, hi: 0xaf}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + // Block 0x42, offset 0x1b0 + {value: 0x0007, lo: 0x06}, + {value: 0x2180, lo: 0x89, hi: 0x89}, + {value: 0xa000, lo: 0x90, hi: 0x90}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0xa000, lo: 0x94, hi: 0x94}, + {value: 0x3bb9, lo: 0x9a, hi: 0x9b}, + {value: 0x3bc7, lo: 0xae, hi: 0xae}, + // Block 0x43, offset 0x1b7 + {value: 0x000e, lo: 0x05}, + {value: 0x3bce, lo: 0x8d, hi: 0x8e}, + {value: 0x3bd5, lo: 0x8f, hi: 0x8f}, + {value: 0xa000, lo: 0x90, hi: 0x90}, + {value: 0xa000, lo: 0x92, hi: 0x92}, + {value: 0xa000, lo: 0x94, hi: 0x94}, + // Block 0x44, offset 0x1bd + {value: 0x0173, lo: 0x0e}, + {value: 0xa000, lo: 0x83, hi: 0x83}, + {value: 0x3be3, lo: 0x84, hi: 0x84}, + {value: 0xa000, lo: 0x88, hi: 0x88}, + {value: 0x3bea, lo: 0x89, hi: 0x89}, + {value: 0xa000, lo: 0x8b, hi: 0x8b}, + {value: 0x3bf1, lo: 0x8c, hi: 0x8c}, + {value: 0xa000, lo: 0xa3, hi: 0xa3}, + {value: 0x3bf8, lo: 0xa4, hi: 0xa4}, + {value: 0xa000, lo: 0xa5, hi: 0xa5}, + {value: 0x3bff, lo: 0xa6, hi: 0xa6}, + {value: 0x269f, lo: 0xac, hi: 0xad}, + {value: 0x26a6, lo: 0xaf, hi: 0xaf}, + {value: 0x281c, lo: 0xb0, hi: 0xb0}, + {value: 0xa000, lo: 0xbc, hi: 0xbc}, + // Block 0x45, offset 0x1cc + {value: 0x0007, lo: 0x03}, + {value: 0x3c68, lo: 0xa0, hi: 0xa1}, + {value: 0x3c92, lo: 0xa2, hi: 0xa3}, + {value: 0x3cbc, lo: 0xaa, hi: 0xad}, + // Block 0x46, offset 0x1d0 + {value: 0x0004, lo: 0x01}, + {value: 0x048b, lo: 0xa9, hi: 0xaa}, + // Block 0x47, offset 0x1d2 + {value: 0x0002, lo: 0x03}, + {value: 0x0057, lo: 0x80, hi: 0x8f}, + {value: 0x0083, lo: 0x90, hi: 0xa9}, + {value: 0x0021, lo: 0xaa, hi: 0xaa}, + // Block 0x48, offset 0x1d6 + {value: 0x0000, lo: 0x01}, + {value: 0x299b, lo: 0x8c, hi: 0x8c}, + // Block 0x49, offset 0x1d8 + {value: 0x0263, lo: 0x02}, + {value: 0x1b8c, lo: 0xb4, hi: 0xb4}, + {value: 0x192d, lo: 0xb5, hi: 0xb6}, + // Block 0x4a, offset 0x1db + {value: 0x0000, lo: 0x01}, + {value: 0x44dd, lo: 0x9c, hi: 0x9c}, + // Block 0x4b, offset 0x1dd + {value: 0x0000, lo: 0x02}, + {value: 0x0095, lo: 0xbc, hi: 0xbc}, + {value: 0x006d, lo: 0xbd, hi: 0xbd}, + // Block 0x4c, offset 0x1e0 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xaf, hi: 0xb1}, + // Block 0x4d, offset 0x1e2 + {value: 0x0000, lo: 0x02}, + {value: 0x047f, lo: 0xaf, hi: 0xaf}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x4e, offset 0x1e5 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xa0, hi: 0xbf}, + // Block 0x4f, offset 0x1e7 + {value: 0x0000, lo: 0x01}, + {value: 0x0dc3, lo: 0x9f, hi: 0x9f}, + // Block 0x50, offset 0x1e9 + {value: 0x0000, lo: 0x01}, + {value: 0x162f, lo: 0xb3, hi: 0xb3}, + // Block 0x51, offset 0x1eb + {value: 0x0004, lo: 0x0b}, + {value: 0x1597, lo: 0x80, hi: 0x82}, + {value: 0x15af, lo: 0x83, hi: 0x83}, + {value: 0x15c7, lo: 0x84, hi: 0x85}, + {value: 0x15d7, lo: 0x86, hi: 0x89}, + {value: 0x15eb, lo: 0x8a, hi: 0x8c}, + {value: 0x15ff, lo: 0x8d, hi: 0x8d}, + {value: 0x1607, lo: 0x8e, hi: 0x8e}, + {value: 0x160f, lo: 0x8f, hi: 0x90}, + {value: 0x161b, lo: 0x91, hi: 0x93}, + {value: 0x162b, lo: 0x94, hi: 0x94}, + {value: 0x1633, lo: 0x95, hi: 0x95}, + // Block 0x52, offset 0x1f7 + {value: 0x0004, lo: 0x09}, + {value: 0x0001, lo: 0x80, hi: 0x80}, + {value: 0x812c, lo: 0xaa, hi: 0xaa}, + {value: 0x8131, lo: 0xab, hi: 0xab}, + {value: 0x8133, lo: 0xac, hi: 0xac}, + {value: 0x812e, lo: 0xad, hi: 0xad}, + {value: 0x812f, lo: 0xae, hi: 0xae}, + {value: 0x812f, lo: 0xaf, hi: 0xaf}, + {value: 0x04b3, lo: 0xb6, hi: 0xb6}, + {value: 0x0887, lo: 0xb8, hi: 0xba}, + // Block 0x53, offset 0x201 + {value: 0x0006, lo: 0x09}, + {value: 0x0313, lo: 0xb1, hi: 0xb1}, + {value: 0x0317, lo: 0xb2, hi: 0xb2}, + {value: 0x4a3b, lo: 0xb3, hi: 0xb3}, + {value: 0x031b, lo: 0xb4, hi: 0xb4}, + {value: 0x4a41, lo: 0xb5, hi: 0xb6}, + {value: 0x031f, lo: 0xb7, hi: 0xb7}, + {value: 0x0323, lo: 0xb8, hi: 0xb8}, + {value: 0x0327, lo: 0xb9, hi: 0xb9}, + {value: 0x4a4d, lo: 0xba, hi: 0xbf}, + // Block 0x54, offset 0x20b + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0xaf, hi: 0xaf}, + {value: 0x8132, lo: 0xb4, hi: 0xbd}, + // Block 0x55, offset 0x20e + {value: 0x0000, lo: 0x03}, + {value: 0x020f, lo: 0x9c, hi: 0x9c}, + {value: 0x0212, lo: 0x9d, hi: 0x9d}, + {value: 0x8132, lo: 0x9e, hi: 0x9f}, + // Block 0x56, offset 0x212 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb0, hi: 0xb1}, + // Block 0x57, offset 0x214 + {value: 0x0000, lo: 0x01}, + {value: 0x163b, lo: 0xb0, hi: 0xb0}, + // Block 0x58, offset 0x216 + {value: 0x000c, lo: 0x01}, + {value: 0x00d7, lo: 0xb8, hi: 0xb9}, + // Block 0x59, offset 0x218 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x86, hi: 0x86}, + // Block 0x5a, offset 0x21a + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x84, hi: 0x84}, + {value: 0x8132, lo: 0xa0, hi: 0xb1}, + // Block 0x5b, offset 0x21d + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xab, hi: 0xad}, + // Block 0x5c, offset 0x21f + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x93, hi: 0x93}, + // Block 0x5d, offset 0x221 + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0xb3, hi: 0xb3}, + // Block 0x5e, offset 0x223 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0x80, hi: 0x80}, + // Block 0x5f, offset 0x225 + {value: 0x0000, lo: 0x05}, + {value: 0x8132, lo: 0xb0, hi: 0xb0}, + {value: 0x8132, lo: 0xb2, hi: 0xb3}, + {value: 0x812d, lo: 0xb4, hi: 0xb4}, + {value: 0x8132, lo: 0xb7, hi: 0xb8}, + {value: 0x8132, lo: 0xbe, hi: 0xbf}, + // Block 0x60, offset 0x22b + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x81, hi: 0x81}, + {value: 0x8104, lo: 0xb6, hi: 0xb6}, + // Block 0x61, offset 0x22e + {value: 0x0008, lo: 0x03}, + {value: 0x1637, lo: 0x9c, hi: 0x9d}, + {value: 0x0125, lo: 0x9e, hi: 0x9e}, + {value: 0x1643, lo: 0x9f, hi: 0x9f}, + // Block 0x62, offset 0x232 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xad, hi: 0xad}, + // Block 0x63, offset 0x234 + {value: 0x0000, lo: 0x06}, + {value: 0xe500, lo: 0x80, hi: 0x80}, + {value: 0xc600, lo: 0x81, hi: 0x9b}, + {value: 0xe500, lo: 0x9c, hi: 0x9c}, + {value: 0xc600, lo: 0x9d, hi: 0xb7}, + {value: 0xe500, lo: 0xb8, hi: 0xb8}, + {value: 0xc600, lo: 0xb9, hi: 0xbf}, + // Block 0x64, offset 0x23b + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x93}, + {value: 0xe500, lo: 0x94, hi: 0x94}, + {value: 0xc600, lo: 0x95, hi: 0xaf}, + {value: 0xe500, lo: 0xb0, hi: 0xb0}, + {value: 0xc600, lo: 0xb1, hi: 0xbf}, + // Block 0x65, offset 0x241 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x8b}, + {value: 0xe500, lo: 0x8c, hi: 0x8c}, + {value: 0xc600, lo: 0x8d, hi: 0xa7}, + {value: 0xe500, lo: 0xa8, hi: 0xa8}, + {value: 0xc600, lo: 0xa9, hi: 0xbf}, + // Block 0x66, offset 0x247 + {value: 0x0000, lo: 0x07}, + {value: 0xc600, lo: 0x80, hi: 0x83}, + {value: 0xe500, lo: 0x84, hi: 0x84}, + {value: 0xc600, lo: 0x85, hi: 0x9f}, + {value: 0xe500, lo: 0xa0, hi: 0xa0}, + {value: 0xc600, lo: 0xa1, hi: 0xbb}, + {value: 0xe500, lo: 0xbc, hi: 0xbc}, + {value: 0xc600, lo: 0xbd, hi: 0xbf}, + // Block 0x67, offset 0x24f + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x97}, + {value: 0xe500, lo: 0x98, hi: 0x98}, + {value: 0xc600, lo: 0x99, hi: 0xb3}, + {value: 0xe500, lo: 0xb4, hi: 0xb4}, + {value: 0xc600, lo: 0xb5, hi: 0xbf}, + // Block 0x68, offset 0x255 + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x8f}, + {value: 0xe500, lo: 0x90, hi: 0x90}, + {value: 0xc600, lo: 0x91, hi: 0xab}, + {value: 0xe500, lo: 0xac, hi: 0xac}, + {value: 0xc600, lo: 0xad, hi: 0xbf}, + // Block 0x69, offset 0x25b + {value: 0x0000, lo: 0x05}, + {value: 0xc600, lo: 0x80, hi: 0x87}, + {value: 0xe500, lo: 0x88, hi: 0x88}, + {value: 0xc600, lo: 0x89, hi: 0xa3}, + {value: 0xe500, lo: 0xa4, hi: 0xa4}, + {value: 0xc600, lo: 0xa5, hi: 0xbf}, + // Block 0x6a, offset 0x261 + {value: 0x0000, lo: 0x03}, + {value: 0xc600, lo: 0x80, hi: 0x87}, + {value: 0xe500, lo: 0x88, hi: 0x88}, + {value: 0xc600, lo: 0x89, hi: 0xa3}, + // Block 0x6b, offset 0x265 + {value: 0x0002, lo: 0x01}, + {value: 0x0003, lo: 0x81, hi: 0xbf}, + // Block 0x6c, offset 0x267 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xbd, hi: 0xbd}, + // Block 0x6d, offset 0x269 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0xa0, hi: 0xa0}, + // Block 0x6e, offset 0x26b + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb6, hi: 0xba}, + // Block 0x6f, offset 0x26d + {value: 0x002c, lo: 0x05}, + {value: 0x812d, lo: 0x8d, hi: 0x8d}, + {value: 0x8132, lo: 0x8f, hi: 0x8f}, + {value: 0x8132, lo: 0xb8, hi: 0xb8}, + {value: 0x8101, lo: 0xb9, hi: 0xba}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x70, offset 0x273 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0xa5, hi: 0xa5}, + {value: 0x812d, lo: 0xa6, hi: 0xa6}, + // Block 0x71, offset 0x276 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x86, hi: 0x86}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x72, offset 0x279 + {value: 0x17fe, lo: 0x07}, + {value: 0xa000, lo: 0x99, hi: 0x99}, + {value: 0x4238, lo: 0x9a, hi: 0x9a}, + {value: 0xa000, lo: 0x9b, hi: 0x9b}, + {value: 0x4242, lo: 0x9c, hi: 0x9c}, + {value: 0xa000, lo: 0xa5, hi: 0xa5}, + {value: 0x424c, lo: 0xab, hi: 0xab}, + {value: 0x8104, lo: 0xb9, hi: 0xba}, + // Block 0x73, offset 0x281 + {value: 0x0000, lo: 0x06}, + {value: 0x8132, lo: 0x80, hi: 0x82}, + {value: 0x9900, lo: 0xa7, hi: 0xa7}, + {value: 0x2d7e, lo: 0xae, hi: 0xae}, + {value: 0x2d88, lo: 0xaf, hi: 0xaf}, + {value: 0xa000, lo: 0xb1, hi: 0xb2}, + {value: 0x8104, lo: 0xb3, hi: 0xb4}, + // Block 0x74, offset 0x288 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x80, hi: 0x80}, + {value: 0x8102, lo: 0x8a, hi: 0x8a}, + // Block 0x75, offset 0x28b + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xb5, hi: 0xb5}, + {value: 0x8102, lo: 0xb6, hi: 0xb6}, + // Block 0x76, offset 0x28e + {value: 0x0002, lo: 0x01}, + {value: 0x8102, lo: 0xa9, hi: 0xaa}, + // Block 0x77, offset 0x290 + {value: 0x0000, lo: 0x07}, + {value: 0xa000, lo: 0x87, hi: 0x87}, + {value: 0x2d92, lo: 0x8b, hi: 0x8b}, + {value: 0x2d9c, lo: 0x8c, hi: 0x8c}, + {value: 0x8104, lo: 0x8d, hi: 0x8d}, + {value: 0x9900, lo: 0x97, hi: 0x97}, + {value: 0x8132, lo: 0xa6, hi: 0xac}, + {value: 0x8132, lo: 0xb0, hi: 0xb4}, + // Block 0x78, offset 0x298 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x82, hi: 0x82}, + {value: 0x8102, lo: 0x86, hi: 0x86}, + // Block 0x79, offset 0x29b + {value: 0x6b5a, lo: 0x06}, + {value: 0x9900, lo: 0xb0, hi: 0xb0}, + {value: 0xa000, lo: 0xb9, hi: 0xb9}, + {value: 0x9900, lo: 0xba, hi: 0xba}, + {value: 0x2db0, lo: 0xbb, hi: 0xbb}, + {value: 0x2da6, lo: 0xbc, hi: 0xbd}, + {value: 0x2dba, lo: 0xbe, hi: 0xbe}, + // Block 0x7a, offset 0x2a2 + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0x82, hi: 0x82}, + {value: 0x8102, lo: 0x83, hi: 0x83}, + // Block 0x7b, offset 0x2a5 + {value: 0x0000, lo: 0x05}, + {value: 0x9900, lo: 0xaf, hi: 0xaf}, + {value: 0xa000, lo: 0xb8, hi: 0xb9}, + {value: 0x2dc4, lo: 0xba, hi: 0xba}, + {value: 0x2dce, lo: 0xbb, hi: 0xbb}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x7c, offset 0x2ab + {value: 0x0000, lo: 0x01}, + {value: 0x8102, lo: 0x80, hi: 0x80}, + // Block 0x7d, offset 0x2ad + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xbf, hi: 0xbf}, + // Block 0x7e, offset 0x2af + {value: 0x0000, lo: 0x02}, + {value: 0x8104, lo: 0xb6, hi: 0xb6}, + {value: 0x8102, lo: 0xb7, hi: 0xb7}, + // Block 0x7f, offset 0x2b2 + {value: 0x0000, lo: 0x01}, + {value: 0x8104, lo: 0xab, hi: 0xab}, + // Block 0x80, offset 0x2b4 + {value: 0x0000, lo: 0x01}, + {value: 0x8101, lo: 0xb0, hi: 0xb4}, + // Block 0x81, offset 0x2b6 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0xb0, hi: 0xb6}, + // Block 0x82, offset 0x2b8 + {value: 0x0000, lo: 0x01}, + {value: 0x8101, lo: 0x9e, hi: 0x9e}, + // Block 0x83, offset 0x2ba + {value: 0x0000, lo: 0x0c}, + {value: 0x45cc, lo: 0x9e, hi: 0x9e}, + {value: 0x45d6, lo: 0x9f, hi: 0x9f}, + {value: 0x460a, lo: 0xa0, hi: 0xa0}, + {value: 0x4618, lo: 0xa1, hi: 0xa1}, + {value: 0x4626, lo: 0xa2, hi: 0xa2}, + {value: 0x4634, lo: 0xa3, hi: 0xa3}, + {value: 0x4642, lo: 0xa4, hi: 0xa4}, + {value: 0x812b, lo: 0xa5, hi: 0xa6}, + {value: 0x8101, lo: 0xa7, hi: 0xa9}, + {value: 0x8130, lo: 0xad, hi: 0xad}, + {value: 0x812b, lo: 0xae, hi: 0xb2}, + {value: 0x812d, lo: 0xbb, hi: 0xbf}, + // Block 0x84, offset 0x2c7 + {value: 0x0000, lo: 0x09}, + {value: 0x812d, lo: 0x80, hi: 0x82}, + {value: 0x8132, lo: 0x85, hi: 0x89}, + {value: 0x812d, lo: 0x8a, hi: 0x8b}, + {value: 0x8132, lo: 0xaa, hi: 0xad}, + {value: 0x45e0, lo: 0xbb, hi: 0xbb}, + {value: 0x45ea, lo: 0xbc, hi: 0xbc}, + {value: 0x4650, lo: 0xbd, hi: 0xbd}, + {value: 0x466c, lo: 0xbe, hi: 0xbe}, + {value: 0x465e, lo: 0xbf, hi: 0xbf}, + // Block 0x85, offset 0x2d1 + {value: 0x0000, lo: 0x01}, + {value: 0x467a, lo: 0x80, hi: 0x80}, + // Block 0x86, offset 0x2d3 + {value: 0x0000, lo: 0x01}, + {value: 0x8132, lo: 0x82, hi: 0x84}, + // Block 0x87, offset 0x2d5 + {value: 0x0002, lo: 0x03}, + {value: 0x0043, lo: 0x80, hi: 0x99}, + {value: 0x0083, lo: 0x9a, hi: 0xb3}, + {value: 0x0043, lo: 0xb4, hi: 0xbf}, + // Block 0x88, offset 0x2d9 + {value: 0x0002, lo: 0x04}, + {value: 0x005b, lo: 0x80, hi: 0x8d}, + {value: 0x0083, lo: 0x8e, hi: 0x94}, + {value: 0x0093, lo: 0x96, hi: 0xa7}, + {value: 0x0043, lo: 0xa8, hi: 0xbf}, + // Block 0x89, offset 0x2de + {value: 0x0002, lo: 0x0b}, + {value: 0x0073, lo: 0x80, hi: 0x81}, + {value: 0x0083, lo: 0x82, hi: 0x9b}, + {value: 0x0043, lo: 0x9c, hi: 0x9c}, + {value: 0x0047, lo: 0x9e, hi: 0x9f}, + {value: 0x004f, lo: 0xa2, hi: 0xa2}, + {value: 0x0055, lo: 0xa5, hi: 0xa6}, + {value: 0x005d, lo: 0xa9, hi: 0xac}, + {value: 0x0067, lo: 0xae, hi: 0xb5}, + {value: 0x0083, lo: 0xb6, hi: 0xb9}, + {value: 0x008d, lo: 0xbb, hi: 0xbb}, + {value: 0x0091, lo: 0xbd, hi: 0xbf}, + // Block 0x8a, offset 0x2ea + {value: 0x0002, lo: 0x04}, + {value: 0x0097, lo: 0x80, hi: 0x83}, + {value: 0x00a1, lo: 0x85, hi: 0x8f}, + {value: 0x0043, lo: 0x90, hi: 0xa9}, + {value: 0x0083, lo: 0xaa, hi: 0xbf}, + // Block 0x8b, offset 0x2ef + {value: 0x0002, lo: 0x08}, + {value: 0x00af, lo: 0x80, hi: 0x83}, + {value: 0x0043, lo: 0x84, hi: 0x85}, + {value: 0x0049, lo: 0x87, hi: 0x8a}, + {value: 0x0055, lo: 0x8d, hi: 0x94}, + {value: 0x0067, lo: 0x96, hi: 0x9c}, + {value: 0x0083, lo: 0x9e, hi: 0xb7}, + {value: 0x0043, lo: 0xb8, hi: 0xb9}, + {value: 0x0049, lo: 0xbb, hi: 0xbe}, + // Block 0x8c, offset 0x2f8 + {value: 0x0002, lo: 0x05}, + {value: 0x0053, lo: 0x80, hi: 0x84}, + {value: 0x005f, lo: 0x86, hi: 0x86}, + {value: 0x0067, lo: 0x8a, hi: 0x90}, + {value: 0x0083, lo: 0x92, hi: 0xab}, + {value: 0x0043, lo: 0xac, hi: 0xbf}, + // Block 0x8d, offset 0x2fe + {value: 0x0002, lo: 0x04}, + {value: 0x006b, lo: 0x80, hi: 0x85}, + {value: 0x0083, lo: 0x86, hi: 0x9f}, + {value: 0x0043, lo: 0xa0, hi: 0xb9}, + {value: 0x0083, lo: 0xba, hi: 0xbf}, + // Block 0x8e, offset 0x303 + {value: 0x0002, lo: 0x03}, + {value: 0x008f, lo: 0x80, hi: 0x93}, + {value: 0x0043, lo: 0x94, hi: 0xad}, + {value: 0x0083, lo: 0xae, hi: 0xbf}, + // Block 0x8f, offset 0x307 + {value: 0x0002, lo: 0x04}, + {value: 0x00a7, lo: 0x80, hi: 0x87}, + {value: 0x0043, lo: 0x88, hi: 0xa1}, + {value: 0x0083, lo: 0xa2, hi: 0xbb}, + {value: 0x0043, lo: 0xbc, hi: 0xbf}, + // Block 0x90, offset 0x30c + {value: 0x0002, lo: 0x03}, + {value: 0x004b, lo: 0x80, hi: 0x95}, + {value: 0x0083, lo: 0x96, hi: 0xaf}, + {value: 0x0043, lo: 0xb0, hi: 0xbf}, + // Block 0x91, offset 0x310 + {value: 0x0003, lo: 0x0f}, + {value: 0x01b8, lo: 0x80, hi: 0x80}, + {value: 0x045f, lo: 0x81, hi: 0x81}, + {value: 0x01bb, lo: 0x82, hi: 0x9a}, + {value: 0x045b, lo: 0x9b, hi: 0x9b}, + {value: 0x01c7, lo: 0x9c, hi: 0x9c}, + {value: 0x01d0, lo: 0x9d, hi: 0x9d}, + {value: 0x01d6, lo: 0x9e, hi: 0x9e}, + {value: 0x01fa, lo: 0x9f, hi: 0x9f}, + {value: 0x01eb, lo: 0xa0, hi: 0xa0}, + {value: 0x01e8, lo: 0xa1, hi: 0xa1}, + {value: 0x0173, lo: 0xa2, hi: 0xb2}, + {value: 0x0188, lo: 0xb3, hi: 0xb3}, + {value: 0x01a6, lo: 0xb4, hi: 0xba}, + {value: 0x045f, lo: 0xbb, hi: 0xbb}, + {value: 0x01bb, lo: 0xbc, hi: 0xbf}, + // Block 0x92, offset 0x320 + {value: 0x0003, lo: 0x0d}, + {value: 0x01c7, lo: 0x80, hi: 0x94}, + {value: 0x045b, lo: 0x95, hi: 0x95}, + {value: 0x01c7, lo: 0x96, hi: 0x96}, + {value: 0x01d0, lo: 0x97, hi: 0x97}, + {value: 0x01d6, lo: 0x98, hi: 0x98}, + {value: 0x01fa, lo: 0x99, hi: 0x99}, + {value: 0x01eb, lo: 0x9a, hi: 0x9a}, + {value: 0x01e8, lo: 0x9b, hi: 0x9b}, + {value: 0x0173, lo: 0x9c, hi: 0xac}, + {value: 0x0188, lo: 0xad, hi: 0xad}, + {value: 0x01a6, lo: 0xae, hi: 0xb4}, + {value: 0x045f, lo: 0xb5, hi: 0xb5}, + {value: 0x01bb, lo: 0xb6, hi: 0xbf}, + // Block 0x93, offset 0x32e + {value: 0x0003, lo: 0x0d}, + {value: 0x01d9, lo: 0x80, hi: 0x8e}, + {value: 0x045b, lo: 0x8f, hi: 0x8f}, + {value: 0x01c7, lo: 0x90, hi: 0x90}, + {value: 0x01d0, lo: 0x91, hi: 0x91}, + {value: 0x01d6, lo: 0x92, hi: 0x92}, + {value: 0x01fa, lo: 0x93, hi: 0x93}, + {value: 0x01eb, lo: 0x94, hi: 0x94}, + {value: 0x01e8, lo: 0x95, hi: 0x95}, + {value: 0x0173, lo: 0x96, hi: 0xa6}, + {value: 0x0188, lo: 0xa7, hi: 0xa7}, + {value: 0x01a6, lo: 0xa8, hi: 0xae}, + {value: 0x045f, lo: 0xaf, hi: 0xaf}, + {value: 0x01bb, lo: 0xb0, hi: 0xbf}, + // Block 0x94, offset 0x33c + {value: 0x0003, lo: 0x0d}, + {value: 0x01eb, lo: 0x80, hi: 0x88}, + {value: 0x045b, lo: 0x89, hi: 0x89}, + {value: 0x01c7, lo: 0x8a, hi: 0x8a}, + {value: 0x01d0, lo: 0x8b, hi: 0x8b}, + {value: 0x01d6, lo: 0x8c, hi: 0x8c}, + {value: 0x01fa, lo: 0x8d, hi: 0x8d}, + {value: 0x01eb, lo: 0x8e, hi: 0x8e}, + {value: 0x01e8, lo: 0x8f, hi: 0x8f}, + {value: 0x0173, lo: 0x90, hi: 0xa0}, + {value: 0x0188, lo: 0xa1, hi: 0xa1}, + {value: 0x01a6, lo: 0xa2, hi: 0xa8}, + {value: 0x045f, lo: 0xa9, hi: 0xa9}, + {value: 0x01bb, lo: 0xaa, hi: 0xbf}, + // Block 0x95, offset 0x34a + {value: 0x0000, lo: 0x05}, + {value: 0x8132, lo: 0x80, hi: 0x86}, + {value: 0x8132, lo: 0x88, hi: 0x98}, + {value: 0x8132, lo: 0x9b, hi: 0xa1}, + {value: 0x8132, lo: 0xa3, hi: 0xa4}, + {value: 0x8132, lo: 0xa6, hi: 0xaa}, + // Block 0x96, offset 0x350 + {value: 0x0000, lo: 0x01}, + {value: 0x812d, lo: 0x90, hi: 0x96}, + // Block 0x97, offset 0x352 + {value: 0x0000, lo: 0x02}, + {value: 0x8132, lo: 0x84, hi: 0x89}, + {value: 0x8102, lo: 0x8a, hi: 0x8a}, + // Block 0x98, offset 0x355 + {value: 0x0002, lo: 0x09}, + {value: 0x0063, lo: 0x80, hi: 0x89}, + {value: 0x1951, lo: 0x8a, hi: 0x8a}, + {value: 0x1981, lo: 0x8b, hi: 0x8b}, + {value: 0x199c, lo: 0x8c, hi: 0x8c}, + {value: 0x19a2, lo: 0x8d, hi: 0x8d}, + {value: 0x1bc0, lo: 0x8e, hi: 0x8e}, + {value: 0x19ae, lo: 0x8f, hi: 0x8f}, + {value: 0x197b, lo: 0xaa, hi: 0xaa}, + {value: 0x197e, lo: 0xab, hi: 0xab}, + // Block 0x99, offset 0x35f + {value: 0x0000, lo: 0x01}, + {value: 0x193f, lo: 0x90, hi: 0x90}, + // Block 0x9a, offset 0x361 + {value: 0x0028, lo: 0x09}, + {value: 0x2862, lo: 0x80, hi: 0x80}, + {value: 0x2826, lo: 0x81, hi: 0x81}, + {value: 0x2830, lo: 0x82, hi: 0x82}, + {value: 0x2844, lo: 0x83, hi: 0x84}, + {value: 0x284e, lo: 0x85, hi: 0x86}, + {value: 0x283a, lo: 0x87, hi: 0x87}, + {value: 0x2858, lo: 0x88, hi: 0x88}, + {value: 0x0b6f, lo: 0x90, hi: 0x90}, + {value: 0x08e7, lo: 0x91, hi: 0x91}, +} + +// recompMap: 7520 bytes (entries only) +var recompMap = map[uint32]rune{ + 0x00410300: 0x00C0, + 0x00410301: 0x00C1, + 0x00410302: 0x00C2, + 0x00410303: 0x00C3, + 0x00410308: 0x00C4, + 0x0041030A: 0x00C5, + 0x00430327: 0x00C7, + 0x00450300: 0x00C8, + 0x00450301: 0x00C9, + 0x00450302: 0x00CA, + 0x00450308: 0x00CB, + 0x00490300: 0x00CC, + 0x00490301: 0x00CD, + 0x00490302: 0x00CE, + 0x00490308: 0x00CF, + 0x004E0303: 0x00D1, + 0x004F0300: 0x00D2, + 0x004F0301: 0x00D3, + 0x004F0302: 0x00D4, + 0x004F0303: 0x00D5, + 0x004F0308: 0x00D6, + 0x00550300: 0x00D9, + 0x00550301: 0x00DA, + 0x00550302: 0x00DB, + 0x00550308: 0x00DC, + 0x00590301: 0x00DD, + 0x00610300: 0x00E0, + 0x00610301: 0x00E1, + 0x00610302: 0x00E2, + 0x00610303: 0x00E3, + 0x00610308: 0x00E4, + 0x0061030A: 0x00E5, + 0x00630327: 0x00E7, + 0x00650300: 0x00E8, + 0x00650301: 0x00E9, + 0x00650302: 0x00EA, + 0x00650308: 0x00EB, + 0x00690300: 0x00EC, + 0x00690301: 0x00ED, + 0x00690302: 0x00EE, + 0x00690308: 0x00EF, + 0x006E0303: 0x00F1, + 0x006F0300: 0x00F2, + 0x006F0301: 0x00F3, + 0x006F0302: 0x00F4, + 0x006F0303: 0x00F5, + 0x006F0308: 0x00F6, + 0x00750300: 0x00F9, + 0x00750301: 0x00FA, + 0x00750302: 0x00FB, + 0x00750308: 0x00FC, + 0x00790301: 0x00FD, + 0x00790308: 0x00FF, + 0x00410304: 0x0100, + 0x00610304: 0x0101, + 0x00410306: 0x0102, + 0x00610306: 0x0103, + 0x00410328: 0x0104, + 0x00610328: 0x0105, + 0x00430301: 0x0106, + 0x00630301: 0x0107, + 0x00430302: 0x0108, + 0x00630302: 0x0109, + 0x00430307: 0x010A, + 0x00630307: 0x010B, + 0x0043030C: 0x010C, + 0x0063030C: 0x010D, + 0x0044030C: 0x010E, + 0x0064030C: 0x010F, + 0x00450304: 0x0112, + 0x00650304: 0x0113, + 0x00450306: 0x0114, + 0x00650306: 0x0115, + 0x00450307: 0x0116, + 0x00650307: 0x0117, + 0x00450328: 0x0118, + 0x00650328: 0x0119, + 0x0045030C: 0x011A, + 0x0065030C: 0x011B, + 0x00470302: 0x011C, + 0x00670302: 0x011D, + 0x00470306: 0x011E, + 0x00670306: 0x011F, + 0x00470307: 0x0120, + 0x00670307: 0x0121, + 0x00470327: 0x0122, + 0x00670327: 0x0123, + 0x00480302: 0x0124, + 0x00680302: 0x0125, + 0x00490303: 0x0128, + 0x00690303: 0x0129, + 0x00490304: 0x012A, + 0x00690304: 0x012B, + 0x00490306: 0x012C, + 0x00690306: 0x012D, + 0x00490328: 0x012E, + 0x00690328: 0x012F, + 0x00490307: 0x0130, + 0x004A0302: 0x0134, + 0x006A0302: 0x0135, + 0x004B0327: 0x0136, + 0x006B0327: 0x0137, + 0x004C0301: 0x0139, + 0x006C0301: 0x013A, + 0x004C0327: 0x013B, + 0x006C0327: 0x013C, + 0x004C030C: 0x013D, + 0x006C030C: 0x013E, + 0x004E0301: 0x0143, + 0x006E0301: 0x0144, + 0x004E0327: 0x0145, + 0x006E0327: 0x0146, + 0x004E030C: 0x0147, + 0x006E030C: 0x0148, + 0x004F0304: 0x014C, + 0x006F0304: 0x014D, + 0x004F0306: 0x014E, + 0x006F0306: 0x014F, + 0x004F030B: 0x0150, + 0x006F030B: 0x0151, + 0x00520301: 0x0154, + 0x00720301: 0x0155, + 0x00520327: 0x0156, + 0x00720327: 0x0157, + 0x0052030C: 0x0158, + 0x0072030C: 0x0159, + 0x00530301: 0x015A, + 0x00730301: 0x015B, + 0x00530302: 0x015C, + 0x00730302: 0x015D, + 0x00530327: 0x015E, + 0x00730327: 0x015F, + 0x0053030C: 0x0160, + 0x0073030C: 0x0161, + 0x00540327: 0x0162, + 0x00740327: 0x0163, + 0x0054030C: 0x0164, + 0x0074030C: 0x0165, + 0x00550303: 0x0168, + 0x00750303: 0x0169, + 0x00550304: 0x016A, + 0x00750304: 0x016B, + 0x00550306: 0x016C, + 0x00750306: 0x016D, + 0x0055030A: 0x016E, + 0x0075030A: 0x016F, + 0x0055030B: 0x0170, + 0x0075030B: 0x0171, + 0x00550328: 0x0172, + 0x00750328: 0x0173, + 0x00570302: 0x0174, + 0x00770302: 0x0175, + 0x00590302: 0x0176, + 0x00790302: 0x0177, + 0x00590308: 0x0178, + 0x005A0301: 0x0179, + 0x007A0301: 0x017A, + 0x005A0307: 0x017B, + 0x007A0307: 0x017C, + 0x005A030C: 0x017D, + 0x007A030C: 0x017E, + 0x004F031B: 0x01A0, + 0x006F031B: 0x01A1, + 0x0055031B: 0x01AF, + 0x0075031B: 0x01B0, + 0x0041030C: 0x01CD, + 0x0061030C: 0x01CE, + 0x0049030C: 0x01CF, + 0x0069030C: 0x01D0, + 0x004F030C: 0x01D1, + 0x006F030C: 0x01D2, + 0x0055030C: 0x01D3, + 0x0075030C: 0x01D4, + 0x00DC0304: 0x01D5, + 0x00FC0304: 0x01D6, + 0x00DC0301: 0x01D7, + 0x00FC0301: 0x01D8, + 0x00DC030C: 0x01D9, + 0x00FC030C: 0x01DA, + 0x00DC0300: 0x01DB, + 0x00FC0300: 0x01DC, + 0x00C40304: 0x01DE, + 0x00E40304: 0x01DF, + 0x02260304: 0x01E0, + 0x02270304: 0x01E1, + 0x00C60304: 0x01E2, + 0x00E60304: 0x01E3, + 0x0047030C: 0x01E6, + 0x0067030C: 0x01E7, + 0x004B030C: 0x01E8, + 0x006B030C: 0x01E9, + 0x004F0328: 0x01EA, + 0x006F0328: 0x01EB, + 0x01EA0304: 0x01EC, + 0x01EB0304: 0x01ED, + 0x01B7030C: 0x01EE, + 0x0292030C: 0x01EF, + 0x006A030C: 0x01F0, + 0x00470301: 0x01F4, + 0x00670301: 0x01F5, + 0x004E0300: 0x01F8, + 0x006E0300: 0x01F9, + 0x00C50301: 0x01FA, + 0x00E50301: 0x01FB, + 0x00C60301: 0x01FC, + 0x00E60301: 0x01FD, + 0x00D80301: 0x01FE, + 0x00F80301: 0x01FF, + 0x0041030F: 0x0200, + 0x0061030F: 0x0201, + 0x00410311: 0x0202, + 0x00610311: 0x0203, + 0x0045030F: 0x0204, + 0x0065030F: 0x0205, + 0x00450311: 0x0206, + 0x00650311: 0x0207, + 0x0049030F: 0x0208, + 0x0069030F: 0x0209, + 0x00490311: 0x020A, + 0x00690311: 0x020B, + 0x004F030F: 0x020C, + 0x006F030F: 0x020D, + 0x004F0311: 0x020E, + 0x006F0311: 0x020F, + 0x0052030F: 0x0210, + 0x0072030F: 0x0211, + 0x00520311: 0x0212, + 0x00720311: 0x0213, + 0x0055030F: 0x0214, + 0x0075030F: 0x0215, + 0x00550311: 0x0216, + 0x00750311: 0x0217, + 0x00530326: 0x0218, + 0x00730326: 0x0219, + 0x00540326: 0x021A, + 0x00740326: 0x021B, + 0x0048030C: 0x021E, + 0x0068030C: 0x021F, + 0x00410307: 0x0226, + 0x00610307: 0x0227, + 0x00450327: 0x0228, + 0x00650327: 0x0229, + 0x00D60304: 0x022A, + 0x00F60304: 0x022B, + 0x00D50304: 0x022C, + 0x00F50304: 0x022D, + 0x004F0307: 0x022E, + 0x006F0307: 0x022F, + 0x022E0304: 0x0230, + 0x022F0304: 0x0231, + 0x00590304: 0x0232, + 0x00790304: 0x0233, + 0x00A80301: 0x0385, + 0x03910301: 0x0386, + 0x03950301: 0x0388, + 0x03970301: 0x0389, + 0x03990301: 0x038A, + 0x039F0301: 0x038C, + 0x03A50301: 0x038E, + 0x03A90301: 0x038F, + 0x03CA0301: 0x0390, + 0x03990308: 0x03AA, + 0x03A50308: 0x03AB, + 0x03B10301: 0x03AC, + 0x03B50301: 0x03AD, + 0x03B70301: 0x03AE, + 0x03B90301: 0x03AF, + 0x03CB0301: 0x03B0, + 0x03B90308: 0x03CA, + 0x03C50308: 0x03CB, + 0x03BF0301: 0x03CC, + 0x03C50301: 0x03CD, + 0x03C90301: 0x03CE, + 0x03D20301: 0x03D3, + 0x03D20308: 0x03D4, + 0x04150300: 0x0400, + 0x04150308: 0x0401, + 0x04130301: 0x0403, + 0x04060308: 0x0407, + 0x041A0301: 0x040C, + 0x04180300: 0x040D, + 0x04230306: 0x040E, + 0x04180306: 0x0419, + 0x04380306: 0x0439, + 0x04350300: 0x0450, + 0x04350308: 0x0451, + 0x04330301: 0x0453, + 0x04560308: 0x0457, + 0x043A0301: 0x045C, + 0x04380300: 0x045D, + 0x04430306: 0x045E, + 0x0474030F: 0x0476, + 0x0475030F: 0x0477, + 0x04160306: 0x04C1, + 0x04360306: 0x04C2, + 0x04100306: 0x04D0, + 0x04300306: 0x04D1, + 0x04100308: 0x04D2, + 0x04300308: 0x04D3, + 0x04150306: 0x04D6, + 0x04350306: 0x04D7, + 0x04D80308: 0x04DA, + 0x04D90308: 0x04DB, + 0x04160308: 0x04DC, + 0x04360308: 0x04DD, + 0x04170308: 0x04DE, + 0x04370308: 0x04DF, + 0x04180304: 0x04E2, + 0x04380304: 0x04E3, + 0x04180308: 0x04E4, + 0x04380308: 0x04E5, + 0x041E0308: 0x04E6, + 0x043E0308: 0x04E7, + 0x04E80308: 0x04EA, + 0x04E90308: 0x04EB, + 0x042D0308: 0x04EC, + 0x044D0308: 0x04ED, + 0x04230304: 0x04EE, + 0x04430304: 0x04EF, + 0x04230308: 0x04F0, + 0x04430308: 0x04F1, + 0x0423030B: 0x04F2, + 0x0443030B: 0x04F3, + 0x04270308: 0x04F4, + 0x04470308: 0x04F5, + 0x042B0308: 0x04F8, + 0x044B0308: 0x04F9, + 0x06270653: 0x0622, + 0x06270654: 0x0623, + 0x06480654: 0x0624, + 0x06270655: 0x0625, + 0x064A0654: 0x0626, + 0x06D50654: 0x06C0, + 0x06C10654: 0x06C2, + 0x06D20654: 0x06D3, + 0x0928093C: 0x0929, + 0x0930093C: 0x0931, + 0x0933093C: 0x0934, + 0x09C709BE: 0x09CB, + 0x09C709D7: 0x09CC, + 0x0B470B56: 0x0B48, + 0x0B470B3E: 0x0B4B, + 0x0B470B57: 0x0B4C, + 0x0B920BD7: 0x0B94, + 0x0BC60BBE: 0x0BCA, + 0x0BC70BBE: 0x0BCB, + 0x0BC60BD7: 0x0BCC, + 0x0C460C56: 0x0C48, + 0x0CBF0CD5: 0x0CC0, + 0x0CC60CD5: 0x0CC7, + 0x0CC60CD6: 0x0CC8, + 0x0CC60CC2: 0x0CCA, + 0x0CCA0CD5: 0x0CCB, + 0x0D460D3E: 0x0D4A, + 0x0D470D3E: 0x0D4B, + 0x0D460D57: 0x0D4C, + 0x0DD90DCA: 0x0DDA, + 0x0DD90DCF: 0x0DDC, + 0x0DDC0DCA: 0x0DDD, + 0x0DD90DDF: 0x0DDE, + 0x1025102E: 0x1026, + 0x1B051B35: 0x1B06, + 0x1B071B35: 0x1B08, + 0x1B091B35: 0x1B0A, + 0x1B0B1B35: 0x1B0C, + 0x1B0D1B35: 0x1B0E, + 0x1B111B35: 0x1B12, + 0x1B3A1B35: 0x1B3B, + 0x1B3C1B35: 0x1B3D, + 0x1B3E1B35: 0x1B40, + 0x1B3F1B35: 0x1B41, + 0x1B421B35: 0x1B43, + 0x00410325: 0x1E00, + 0x00610325: 0x1E01, + 0x00420307: 0x1E02, + 0x00620307: 0x1E03, + 0x00420323: 0x1E04, + 0x00620323: 0x1E05, + 0x00420331: 0x1E06, + 0x00620331: 0x1E07, + 0x00C70301: 0x1E08, + 0x00E70301: 0x1E09, + 0x00440307: 0x1E0A, + 0x00640307: 0x1E0B, + 0x00440323: 0x1E0C, + 0x00640323: 0x1E0D, + 0x00440331: 0x1E0E, + 0x00640331: 0x1E0F, + 0x00440327: 0x1E10, + 0x00640327: 0x1E11, + 0x0044032D: 0x1E12, + 0x0064032D: 0x1E13, + 0x01120300: 0x1E14, + 0x01130300: 0x1E15, + 0x01120301: 0x1E16, + 0x01130301: 0x1E17, + 0x0045032D: 0x1E18, + 0x0065032D: 0x1E19, + 0x00450330: 0x1E1A, + 0x00650330: 0x1E1B, + 0x02280306: 0x1E1C, + 0x02290306: 0x1E1D, + 0x00460307: 0x1E1E, + 0x00660307: 0x1E1F, + 0x00470304: 0x1E20, + 0x00670304: 0x1E21, + 0x00480307: 0x1E22, + 0x00680307: 0x1E23, + 0x00480323: 0x1E24, + 0x00680323: 0x1E25, + 0x00480308: 0x1E26, + 0x00680308: 0x1E27, + 0x00480327: 0x1E28, + 0x00680327: 0x1E29, + 0x0048032E: 0x1E2A, + 0x0068032E: 0x1E2B, + 0x00490330: 0x1E2C, + 0x00690330: 0x1E2D, + 0x00CF0301: 0x1E2E, + 0x00EF0301: 0x1E2F, + 0x004B0301: 0x1E30, + 0x006B0301: 0x1E31, + 0x004B0323: 0x1E32, + 0x006B0323: 0x1E33, + 0x004B0331: 0x1E34, + 0x006B0331: 0x1E35, + 0x004C0323: 0x1E36, + 0x006C0323: 0x1E37, + 0x1E360304: 0x1E38, + 0x1E370304: 0x1E39, + 0x004C0331: 0x1E3A, + 0x006C0331: 0x1E3B, + 0x004C032D: 0x1E3C, + 0x006C032D: 0x1E3D, + 0x004D0301: 0x1E3E, + 0x006D0301: 0x1E3F, + 0x004D0307: 0x1E40, + 0x006D0307: 0x1E41, + 0x004D0323: 0x1E42, + 0x006D0323: 0x1E43, + 0x004E0307: 0x1E44, + 0x006E0307: 0x1E45, + 0x004E0323: 0x1E46, + 0x006E0323: 0x1E47, + 0x004E0331: 0x1E48, + 0x006E0331: 0x1E49, + 0x004E032D: 0x1E4A, + 0x006E032D: 0x1E4B, + 0x00D50301: 0x1E4C, + 0x00F50301: 0x1E4D, + 0x00D50308: 0x1E4E, + 0x00F50308: 0x1E4F, + 0x014C0300: 0x1E50, + 0x014D0300: 0x1E51, + 0x014C0301: 0x1E52, + 0x014D0301: 0x1E53, + 0x00500301: 0x1E54, + 0x00700301: 0x1E55, + 0x00500307: 0x1E56, + 0x00700307: 0x1E57, + 0x00520307: 0x1E58, + 0x00720307: 0x1E59, + 0x00520323: 0x1E5A, + 0x00720323: 0x1E5B, + 0x1E5A0304: 0x1E5C, + 0x1E5B0304: 0x1E5D, + 0x00520331: 0x1E5E, + 0x00720331: 0x1E5F, + 0x00530307: 0x1E60, + 0x00730307: 0x1E61, + 0x00530323: 0x1E62, + 0x00730323: 0x1E63, + 0x015A0307: 0x1E64, + 0x015B0307: 0x1E65, + 0x01600307: 0x1E66, + 0x01610307: 0x1E67, + 0x1E620307: 0x1E68, + 0x1E630307: 0x1E69, + 0x00540307: 0x1E6A, + 0x00740307: 0x1E6B, + 0x00540323: 0x1E6C, + 0x00740323: 0x1E6D, + 0x00540331: 0x1E6E, + 0x00740331: 0x1E6F, + 0x0054032D: 0x1E70, + 0x0074032D: 0x1E71, + 0x00550324: 0x1E72, + 0x00750324: 0x1E73, + 0x00550330: 0x1E74, + 0x00750330: 0x1E75, + 0x0055032D: 0x1E76, + 0x0075032D: 0x1E77, + 0x01680301: 0x1E78, + 0x01690301: 0x1E79, + 0x016A0308: 0x1E7A, + 0x016B0308: 0x1E7B, + 0x00560303: 0x1E7C, + 0x00760303: 0x1E7D, + 0x00560323: 0x1E7E, + 0x00760323: 0x1E7F, + 0x00570300: 0x1E80, + 0x00770300: 0x1E81, + 0x00570301: 0x1E82, + 0x00770301: 0x1E83, + 0x00570308: 0x1E84, + 0x00770308: 0x1E85, + 0x00570307: 0x1E86, + 0x00770307: 0x1E87, + 0x00570323: 0x1E88, + 0x00770323: 0x1E89, + 0x00580307: 0x1E8A, + 0x00780307: 0x1E8B, + 0x00580308: 0x1E8C, + 0x00780308: 0x1E8D, + 0x00590307: 0x1E8E, + 0x00790307: 0x1E8F, + 0x005A0302: 0x1E90, + 0x007A0302: 0x1E91, + 0x005A0323: 0x1E92, + 0x007A0323: 0x1E93, + 0x005A0331: 0x1E94, + 0x007A0331: 0x1E95, + 0x00680331: 0x1E96, + 0x00740308: 0x1E97, + 0x0077030A: 0x1E98, + 0x0079030A: 0x1E99, + 0x017F0307: 0x1E9B, + 0x00410323: 0x1EA0, + 0x00610323: 0x1EA1, + 0x00410309: 0x1EA2, + 0x00610309: 0x1EA3, + 0x00C20301: 0x1EA4, + 0x00E20301: 0x1EA5, + 0x00C20300: 0x1EA6, + 0x00E20300: 0x1EA7, + 0x00C20309: 0x1EA8, + 0x00E20309: 0x1EA9, + 0x00C20303: 0x1EAA, + 0x00E20303: 0x1EAB, + 0x1EA00302: 0x1EAC, + 0x1EA10302: 0x1EAD, + 0x01020301: 0x1EAE, + 0x01030301: 0x1EAF, + 0x01020300: 0x1EB0, + 0x01030300: 0x1EB1, + 0x01020309: 0x1EB2, + 0x01030309: 0x1EB3, + 0x01020303: 0x1EB4, + 0x01030303: 0x1EB5, + 0x1EA00306: 0x1EB6, + 0x1EA10306: 0x1EB7, + 0x00450323: 0x1EB8, + 0x00650323: 0x1EB9, + 0x00450309: 0x1EBA, + 0x00650309: 0x1EBB, + 0x00450303: 0x1EBC, + 0x00650303: 0x1EBD, + 0x00CA0301: 0x1EBE, + 0x00EA0301: 0x1EBF, + 0x00CA0300: 0x1EC0, + 0x00EA0300: 0x1EC1, + 0x00CA0309: 0x1EC2, + 0x00EA0309: 0x1EC3, + 0x00CA0303: 0x1EC4, + 0x00EA0303: 0x1EC5, + 0x1EB80302: 0x1EC6, + 0x1EB90302: 0x1EC7, + 0x00490309: 0x1EC8, + 0x00690309: 0x1EC9, + 0x00490323: 0x1ECA, + 0x00690323: 0x1ECB, + 0x004F0323: 0x1ECC, + 0x006F0323: 0x1ECD, + 0x004F0309: 0x1ECE, + 0x006F0309: 0x1ECF, + 0x00D40301: 0x1ED0, + 0x00F40301: 0x1ED1, + 0x00D40300: 0x1ED2, + 0x00F40300: 0x1ED3, + 0x00D40309: 0x1ED4, + 0x00F40309: 0x1ED5, + 0x00D40303: 0x1ED6, + 0x00F40303: 0x1ED7, + 0x1ECC0302: 0x1ED8, + 0x1ECD0302: 0x1ED9, + 0x01A00301: 0x1EDA, + 0x01A10301: 0x1EDB, + 0x01A00300: 0x1EDC, + 0x01A10300: 0x1EDD, + 0x01A00309: 0x1EDE, + 0x01A10309: 0x1EDF, + 0x01A00303: 0x1EE0, + 0x01A10303: 0x1EE1, + 0x01A00323: 0x1EE2, + 0x01A10323: 0x1EE3, + 0x00550323: 0x1EE4, + 0x00750323: 0x1EE5, + 0x00550309: 0x1EE6, + 0x00750309: 0x1EE7, + 0x01AF0301: 0x1EE8, + 0x01B00301: 0x1EE9, + 0x01AF0300: 0x1EEA, + 0x01B00300: 0x1EEB, + 0x01AF0309: 0x1EEC, + 0x01B00309: 0x1EED, + 0x01AF0303: 0x1EEE, + 0x01B00303: 0x1EEF, + 0x01AF0323: 0x1EF0, + 0x01B00323: 0x1EF1, + 0x00590300: 0x1EF2, + 0x00790300: 0x1EF3, + 0x00590323: 0x1EF4, + 0x00790323: 0x1EF5, + 0x00590309: 0x1EF6, + 0x00790309: 0x1EF7, + 0x00590303: 0x1EF8, + 0x00790303: 0x1EF9, + 0x03B10313: 0x1F00, + 0x03B10314: 0x1F01, + 0x1F000300: 0x1F02, + 0x1F010300: 0x1F03, + 0x1F000301: 0x1F04, + 0x1F010301: 0x1F05, + 0x1F000342: 0x1F06, + 0x1F010342: 0x1F07, + 0x03910313: 0x1F08, + 0x03910314: 0x1F09, + 0x1F080300: 0x1F0A, + 0x1F090300: 0x1F0B, + 0x1F080301: 0x1F0C, + 0x1F090301: 0x1F0D, + 0x1F080342: 0x1F0E, + 0x1F090342: 0x1F0F, + 0x03B50313: 0x1F10, + 0x03B50314: 0x1F11, + 0x1F100300: 0x1F12, + 0x1F110300: 0x1F13, + 0x1F100301: 0x1F14, + 0x1F110301: 0x1F15, + 0x03950313: 0x1F18, + 0x03950314: 0x1F19, + 0x1F180300: 0x1F1A, + 0x1F190300: 0x1F1B, + 0x1F180301: 0x1F1C, + 0x1F190301: 0x1F1D, + 0x03B70313: 0x1F20, + 0x03B70314: 0x1F21, + 0x1F200300: 0x1F22, + 0x1F210300: 0x1F23, + 0x1F200301: 0x1F24, + 0x1F210301: 0x1F25, + 0x1F200342: 0x1F26, + 0x1F210342: 0x1F27, + 0x03970313: 0x1F28, + 0x03970314: 0x1F29, + 0x1F280300: 0x1F2A, + 0x1F290300: 0x1F2B, + 0x1F280301: 0x1F2C, + 0x1F290301: 0x1F2D, + 0x1F280342: 0x1F2E, + 0x1F290342: 0x1F2F, + 0x03B90313: 0x1F30, + 0x03B90314: 0x1F31, + 0x1F300300: 0x1F32, + 0x1F310300: 0x1F33, + 0x1F300301: 0x1F34, + 0x1F310301: 0x1F35, + 0x1F300342: 0x1F36, + 0x1F310342: 0x1F37, + 0x03990313: 0x1F38, + 0x03990314: 0x1F39, + 0x1F380300: 0x1F3A, + 0x1F390300: 0x1F3B, + 0x1F380301: 0x1F3C, + 0x1F390301: 0x1F3D, + 0x1F380342: 0x1F3E, + 0x1F390342: 0x1F3F, + 0x03BF0313: 0x1F40, + 0x03BF0314: 0x1F41, + 0x1F400300: 0x1F42, + 0x1F410300: 0x1F43, + 0x1F400301: 0x1F44, + 0x1F410301: 0x1F45, + 0x039F0313: 0x1F48, + 0x039F0314: 0x1F49, + 0x1F480300: 0x1F4A, + 0x1F490300: 0x1F4B, + 0x1F480301: 0x1F4C, + 0x1F490301: 0x1F4D, + 0x03C50313: 0x1F50, + 0x03C50314: 0x1F51, + 0x1F500300: 0x1F52, + 0x1F510300: 0x1F53, + 0x1F500301: 0x1F54, + 0x1F510301: 0x1F55, + 0x1F500342: 0x1F56, + 0x1F510342: 0x1F57, + 0x03A50314: 0x1F59, + 0x1F590300: 0x1F5B, + 0x1F590301: 0x1F5D, + 0x1F590342: 0x1F5F, + 0x03C90313: 0x1F60, + 0x03C90314: 0x1F61, + 0x1F600300: 0x1F62, + 0x1F610300: 0x1F63, + 0x1F600301: 0x1F64, + 0x1F610301: 0x1F65, + 0x1F600342: 0x1F66, + 0x1F610342: 0x1F67, + 0x03A90313: 0x1F68, + 0x03A90314: 0x1F69, + 0x1F680300: 0x1F6A, + 0x1F690300: 0x1F6B, + 0x1F680301: 0x1F6C, + 0x1F690301: 0x1F6D, + 0x1F680342: 0x1F6E, + 0x1F690342: 0x1F6F, + 0x03B10300: 0x1F70, + 0x03B50300: 0x1F72, + 0x03B70300: 0x1F74, + 0x03B90300: 0x1F76, + 0x03BF0300: 0x1F78, + 0x03C50300: 0x1F7A, + 0x03C90300: 0x1F7C, + 0x1F000345: 0x1F80, + 0x1F010345: 0x1F81, + 0x1F020345: 0x1F82, + 0x1F030345: 0x1F83, + 0x1F040345: 0x1F84, + 0x1F050345: 0x1F85, + 0x1F060345: 0x1F86, + 0x1F070345: 0x1F87, + 0x1F080345: 0x1F88, + 0x1F090345: 0x1F89, + 0x1F0A0345: 0x1F8A, + 0x1F0B0345: 0x1F8B, + 0x1F0C0345: 0x1F8C, + 0x1F0D0345: 0x1F8D, + 0x1F0E0345: 0x1F8E, + 0x1F0F0345: 0x1F8F, + 0x1F200345: 0x1F90, + 0x1F210345: 0x1F91, + 0x1F220345: 0x1F92, + 0x1F230345: 0x1F93, + 0x1F240345: 0x1F94, + 0x1F250345: 0x1F95, + 0x1F260345: 0x1F96, + 0x1F270345: 0x1F97, + 0x1F280345: 0x1F98, + 0x1F290345: 0x1F99, + 0x1F2A0345: 0x1F9A, + 0x1F2B0345: 0x1F9B, + 0x1F2C0345: 0x1F9C, + 0x1F2D0345: 0x1F9D, + 0x1F2E0345: 0x1F9E, + 0x1F2F0345: 0x1F9F, + 0x1F600345: 0x1FA0, + 0x1F610345: 0x1FA1, + 0x1F620345: 0x1FA2, + 0x1F630345: 0x1FA3, + 0x1F640345: 0x1FA4, + 0x1F650345: 0x1FA5, + 0x1F660345: 0x1FA6, + 0x1F670345: 0x1FA7, + 0x1F680345: 0x1FA8, + 0x1F690345: 0x1FA9, + 0x1F6A0345: 0x1FAA, + 0x1F6B0345: 0x1FAB, + 0x1F6C0345: 0x1FAC, + 0x1F6D0345: 0x1FAD, + 0x1F6E0345: 0x1FAE, + 0x1F6F0345: 0x1FAF, + 0x03B10306: 0x1FB0, + 0x03B10304: 0x1FB1, + 0x1F700345: 0x1FB2, + 0x03B10345: 0x1FB3, + 0x03AC0345: 0x1FB4, + 0x03B10342: 0x1FB6, + 0x1FB60345: 0x1FB7, + 0x03910306: 0x1FB8, + 0x03910304: 0x1FB9, + 0x03910300: 0x1FBA, + 0x03910345: 0x1FBC, + 0x00A80342: 0x1FC1, + 0x1F740345: 0x1FC2, + 0x03B70345: 0x1FC3, + 0x03AE0345: 0x1FC4, + 0x03B70342: 0x1FC6, + 0x1FC60345: 0x1FC7, + 0x03950300: 0x1FC8, + 0x03970300: 0x1FCA, + 0x03970345: 0x1FCC, + 0x1FBF0300: 0x1FCD, + 0x1FBF0301: 0x1FCE, + 0x1FBF0342: 0x1FCF, + 0x03B90306: 0x1FD0, + 0x03B90304: 0x1FD1, + 0x03CA0300: 0x1FD2, + 0x03B90342: 0x1FD6, + 0x03CA0342: 0x1FD7, + 0x03990306: 0x1FD8, + 0x03990304: 0x1FD9, + 0x03990300: 0x1FDA, + 0x1FFE0300: 0x1FDD, + 0x1FFE0301: 0x1FDE, + 0x1FFE0342: 0x1FDF, + 0x03C50306: 0x1FE0, + 0x03C50304: 0x1FE1, + 0x03CB0300: 0x1FE2, + 0x03C10313: 0x1FE4, + 0x03C10314: 0x1FE5, + 0x03C50342: 0x1FE6, + 0x03CB0342: 0x1FE7, + 0x03A50306: 0x1FE8, + 0x03A50304: 0x1FE9, + 0x03A50300: 0x1FEA, + 0x03A10314: 0x1FEC, + 0x00A80300: 0x1FED, + 0x1F7C0345: 0x1FF2, + 0x03C90345: 0x1FF3, + 0x03CE0345: 0x1FF4, + 0x03C90342: 0x1FF6, + 0x1FF60345: 0x1FF7, + 0x039F0300: 0x1FF8, + 0x03A90300: 0x1FFA, + 0x03A90345: 0x1FFC, + 0x21900338: 0x219A, + 0x21920338: 0x219B, + 0x21940338: 0x21AE, + 0x21D00338: 0x21CD, + 0x21D40338: 0x21CE, + 0x21D20338: 0x21CF, + 0x22030338: 0x2204, + 0x22080338: 0x2209, + 0x220B0338: 0x220C, + 0x22230338: 0x2224, + 0x22250338: 0x2226, + 0x223C0338: 0x2241, + 0x22430338: 0x2244, + 0x22450338: 0x2247, + 0x22480338: 0x2249, + 0x003D0338: 0x2260, + 0x22610338: 0x2262, + 0x224D0338: 0x226D, + 0x003C0338: 0x226E, + 0x003E0338: 0x226F, + 0x22640338: 0x2270, + 0x22650338: 0x2271, + 0x22720338: 0x2274, + 0x22730338: 0x2275, + 0x22760338: 0x2278, + 0x22770338: 0x2279, + 0x227A0338: 0x2280, + 0x227B0338: 0x2281, + 0x22820338: 0x2284, + 0x22830338: 0x2285, + 0x22860338: 0x2288, + 0x22870338: 0x2289, + 0x22A20338: 0x22AC, + 0x22A80338: 0x22AD, + 0x22A90338: 0x22AE, + 0x22AB0338: 0x22AF, + 0x227C0338: 0x22E0, + 0x227D0338: 0x22E1, + 0x22910338: 0x22E2, + 0x22920338: 0x22E3, + 0x22B20338: 0x22EA, + 0x22B30338: 0x22EB, + 0x22B40338: 0x22EC, + 0x22B50338: 0x22ED, + 0x304B3099: 0x304C, + 0x304D3099: 0x304E, + 0x304F3099: 0x3050, + 0x30513099: 0x3052, + 0x30533099: 0x3054, + 0x30553099: 0x3056, + 0x30573099: 0x3058, + 0x30593099: 0x305A, + 0x305B3099: 0x305C, + 0x305D3099: 0x305E, + 0x305F3099: 0x3060, + 0x30613099: 0x3062, + 0x30643099: 0x3065, + 0x30663099: 0x3067, + 0x30683099: 0x3069, + 0x306F3099: 0x3070, + 0x306F309A: 0x3071, + 0x30723099: 0x3073, + 0x3072309A: 0x3074, + 0x30753099: 0x3076, + 0x3075309A: 0x3077, + 0x30783099: 0x3079, + 0x3078309A: 0x307A, + 0x307B3099: 0x307C, + 0x307B309A: 0x307D, + 0x30463099: 0x3094, + 0x309D3099: 0x309E, + 0x30AB3099: 0x30AC, + 0x30AD3099: 0x30AE, + 0x30AF3099: 0x30B0, + 0x30B13099: 0x30B2, + 0x30B33099: 0x30B4, + 0x30B53099: 0x30B6, + 0x30B73099: 0x30B8, + 0x30B93099: 0x30BA, + 0x30BB3099: 0x30BC, + 0x30BD3099: 0x30BE, + 0x30BF3099: 0x30C0, + 0x30C13099: 0x30C2, + 0x30C43099: 0x30C5, + 0x30C63099: 0x30C7, + 0x30C83099: 0x30C9, + 0x30CF3099: 0x30D0, + 0x30CF309A: 0x30D1, + 0x30D23099: 0x30D3, + 0x30D2309A: 0x30D4, + 0x30D53099: 0x30D6, + 0x30D5309A: 0x30D7, + 0x30D83099: 0x30D9, + 0x30D8309A: 0x30DA, + 0x30DB3099: 0x30DC, + 0x30DB309A: 0x30DD, + 0x30A63099: 0x30F4, + 0x30EF3099: 0x30F7, + 0x30F03099: 0x30F8, + 0x30F13099: 0x30F9, + 0x30F23099: 0x30FA, + 0x30FD3099: 0x30FE, + 0x109910BA: 0x1109A, + 0x109B10BA: 0x1109C, + 0x10A510BA: 0x110AB, + 0x11311127: 0x1112E, + 0x11321127: 0x1112F, + 0x1347133E: 0x1134B, + 0x13471357: 0x1134C, + 0x14B914BA: 0x114BB, + 0x14B914B0: 0x114BC, + 0x14B914BD: 0x114BE, + 0x15B815AF: 0x115BA, + 0x15B915AF: 0x115BB, +} + +// Total size of tables: 53KB (54006 bytes) diff --git a/vendor/golang.org/x/text/unicode/norm/transform_test.go b/vendor/golang.org/x/text/unicode/norm/transform_test.go deleted file mode 100644 index d596ff3d89..0000000000 --- a/vendor/golang.org/x/text/unicode/norm/transform_test.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2011 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 norm - -import ( - "fmt" - "testing" - - "golang.org/x/text/transform" -) - -func TestTransform(t *testing.T) { - tests := []struct { - f Form - in, out string - eof bool - dstSize int - err error - }{ - {NFC, "ab", "ab", true, 2, nil}, - {NFC, "qx", "qx", true, 2, nil}, - {NFD, "qx", "qx", true, 2, nil}, - {NFC, "", "", true, 1, nil}, - {NFD, "", "", true, 1, nil}, - {NFC, "", "", false, 1, nil}, - {NFD, "", "", false, 1, nil}, - - // Normalized segment does not fit in destination. - {NFD, "ö", "", true, 1, transform.ErrShortDst}, - {NFD, "ö", "", true, 2, transform.ErrShortDst}, - - // As an artifact of the algorithm, only full segments are written. - // This is not strictly required, and some bytes could be written. - // In practice, for Transform to not block, the destination buffer - // should be at least MaxSegmentSize to work anyway and these edge - // conditions will be relatively rare. - {NFC, "ab", "", true, 1, transform.ErrShortDst}, - // This is even true for inert runes. - {NFC, "qx", "", true, 1, transform.ErrShortDst}, - {NFC, "a\u0300abc", "\u00e0a", true, 4, transform.ErrShortDst}, - - // We cannot write a segment if successive runes could still change the result. - {NFD, "ö", "", false, 3, transform.ErrShortSrc}, - {NFC, "a\u0300", "", false, 4, transform.ErrShortSrc}, - {NFD, "a\u0300", "", false, 4, transform.ErrShortSrc}, - {NFC, "ö", "", false, 3, transform.ErrShortSrc}, - - {NFC, "a\u0300", "", true, 1, transform.ErrShortDst}, - // Theoretically could fit, but won't due to simplified checks. - {NFC, "a\u0300", "", true, 2, transform.ErrShortDst}, - {NFC, "a\u0300", "", true, 3, transform.ErrShortDst}, - {NFC, "a\u0300", "\u00e0", true, 4, nil}, - - {NFD, "öa\u0300", "o\u0308", false, 8, transform.ErrShortSrc}, - {NFD, "öa\u0300ö", "o\u0308a\u0300", true, 8, transform.ErrShortDst}, - {NFD, "öa\u0300ö", "o\u0308a\u0300", false, 12, transform.ErrShortSrc}, - - // Illegal input is copied verbatim. - {NFD, "\xbd\xb2=\xbc ", "\xbd\xb2=\xbc ", true, 8, nil}, - } - b := make([]byte, 100) - for i, tt := range tests { - nDst, _, err := tt.f.Transform(b[:tt.dstSize], []byte(tt.in), tt.eof) - out := string(b[:nDst]) - if out != tt.out || err != tt.err { - t.Errorf("%d: was %+q (%v); want %+q (%v)", i, out, err, tt.out, tt.err) - } - if want := tt.f.String(tt.in)[:nDst]; want != out { - t.Errorf("%d: incorrect normalization: was %+q; want %+q", i, out, want) - } - } -} - -var transBufSizes = []int{ - MaxTransformChunkSize, - 3 * MaxTransformChunkSize / 2, - 2 * MaxTransformChunkSize, - 3 * MaxTransformChunkSize, - 100 * MaxTransformChunkSize, -} - -func doTransNorm(f Form, buf []byte, b []byte) []byte { - acc := []byte{} - for p := 0; p < len(b); { - nd, ns, _ := f.Transform(buf[:], b[p:], true) - p += ns - acc = append(acc, buf[:nd]...) - } - return acc -} - -func TestTransformNorm(t *testing.T) { - for _, sz := range transBufSizes { - buf := make([]byte, sz) - runNormTests(t, fmt.Sprintf("Transform:%d", sz), func(f Form, out []byte, s string) []byte { - return doTransNorm(f, buf, append(out, s...)) - }) - } -} diff --git a/vendor/golang.org/x/text/unicode/norm/ucd_test.go b/vendor/golang.org/x/text/unicode/norm/ucd_test.go deleted file mode 100644 index 29205a6aa8..0000000000 --- a/vendor/golang.org/x/text/unicode/norm/ucd_test.go +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright 2011 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 norm - -import ( - "bufio" - "bytes" - "fmt" - "regexp" - "runtime" - "strconv" - "strings" - "sync" - "testing" - "time" - "unicode/utf8" - - "golang.org/x/text/internal/gen" - "golang.org/x/text/internal/testtext" -) - -var once sync.Once - -func skipShort(t *testing.T) { - testtext.SkipIfNotLong(t) - - once.Do(func() { loadTestData(t) }) -} - -// This regression test runs the test set in NormalizationTest.txt -// (taken from http://www.unicode.org/Public/<unicode.Version>/ucd/). -// -// NormalizationTest.txt has form: -// @Part0 # Specific cases -// # -// 1E0A;1E0A;0044 0307;1E0A;0044 0307; # (Ḋ; Ḋ; D◌̇; Ḋ; D◌̇; ) LATIN CAPITAL LETTER D WITH DOT ABOVE -// 1E0C;1E0C;0044 0323;1E0C;0044 0323; # (Ḍ; Ḍ; D◌̣; Ḍ; D◌̣; ) LATIN CAPITAL LETTER D WITH DOT BELOW -// -// Each test has 5 columns (c1, c2, c3, c4, c5), where -// (c1, c2, c3, c4, c5) == (c1, NFC(c1), NFD(c1), NFKC(c1), NFKD(c1)) -// -// CONFORMANCE: -// 1. The following invariants must be true for all conformant implementations -// -// NFC -// c2 == NFC(c1) == NFC(c2) == NFC(c3) -// c4 == NFC(c4) == NFC(c5) -// -// NFD -// c3 == NFD(c1) == NFD(c2) == NFD(c3) -// c5 == NFD(c4) == NFD(c5) -// -// NFKC -// c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5) -// -// NFKD -// c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5) -// -// 2. For every code point X assigned in this version of Unicode that is not -// specifically listed in Part 1, the following invariants must be true -// for all conformant implementations: -// -// X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X) -// - -// Column types. -const ( - cRaw = iota - cNFC - cNFD - cNFKC - cNFKD - cMaxColumns -) - -// Holds data from NormalizationTest.txt -var part []Part - -type Part struct { - name string - number int - tests []Test -} - -type Test struct { - name string - partnr int - number int - r rune // used for character by character test - cols [cMaxColumns]string // Each has 5 entries, see below. -} - -func (t Test) Name() string { - if t.number < 0 { - return part[t.partnr].name - } - return fmt.Sprintf("%s:%d", part[t.partnr].name, t.number) -} - -var partRe = regexp.MustCompile(`@Part(\d) # (.*)$`) -var testRe = regexp.MustCompile(`^` + strings.Repeat(`([\dA-F ]+);`, 5) + ` # (.*)$`) - -var counter int - -// Load the data form NormalizationTest.txt -func loadTestData(t *testing.T) { - f := gen.OpenUCDFile("NormalizationTest.txt") - defer f.Close() - scanner := bufio.NewScanner(f) - for scanner.Scan() { - line := scanner.Text() - if len(line) == 0 || line[0] == '#' { - continue - } - m := partRe.FindStringSubmatch(line) - if m != nil { - if len(m) < 3 { - t.Fatal("Failed to parse Part: ", line) - } - i, err := strconv.Atoi(m[1]) - if err != nil { - t.Fatal(err) - } - name := m[2] - part = append(part, Part{name: name[:len(name)-1], number: i}) - continue - } - m = testRe.FindStringSubmatch(line) - if m == nil || len(m) < 7 { - t.Fatalf(`Failed to parse: "%s" result: %#v`, line, m) - } - test := Test{name: m[6], partnr: len(part) - 1, number: counter} - counter++ - for j := 1; j < len(m)-1; j++ { - for _, split := range strings.Split(m[j], " ") { - r, err := strconv.ParseUint(split, 16, 64) - if err != nil { - t.Fatal(err) - } - if test.r == 0 { - // save for CharacterByCharacterTests - test.r = rune(r) - } - var buf [utf8.UTFMax]byte - sz := utf8.EncodeRune(buf[:], rune(r)) - test.cols[j-1] += string(buf[:sz]) - } - } - part := &part[len(part)-1] - part.tests = append(part.tests, test) - } - if scanner.Err() != nil { - t.Fatal(scanner.Err()) - } -} - -func cmpResult(t *testing.T, tc *Test, name string, f Form, gold, test, result string) { - if gold != result { - t.Errorf("%s:%s: %s(%+q)=%+q; want %+q: %s", - tc.Name(), name, fstr[f], test, result, gold, tc.name) - } -} - -func cmpIsNormal(t *testing.T, tc *Test, name string, f Form, test string, result, want bool) { - if result != want { - t.Errorf("%s:%s: %s(%+q)=%v; want %v", tc.Name(), name, fstr[f], test, result, want) - } -} - -func doTest(t *testing.T, tc *Test, f Form, gold, test string) { - testb := []byte(test) - result := f.Bytes(testb) - cmpResult(t, tc, "Bytes", f, gold, test, string(result)) - - sresult := f.String(test) - cmpResult(t, tc, "String", f, gold, test, sresult) - - acc := []byte{} - i := Iter{} - i.InitString(f, test) - for !i.Done() { - acc = append(acc, i.Next()...) - } - cmpResult(t, tc, "Iter.Next", f, gold, test, string(acc)) - - buf := make([]byte, 128) - acc = nil - for p := 0; p < len(testb); { - nDst, nSrc, _ := f.Transform(buf, testb[p:], true) - acc = append(acc, buf[:nDst]...) - p += nSrc - } - cmpResult(t, tc, "Transform", f, gold, test, string(acc)) - - for i := range test { - out := f.Append(f.Bytes([]byte(test[:i])), []byte(test[i:])...) - cmpResult(t, tc, fmt.Sprintf(":Append:%d", i), f, gold, test, string(out)) - } - cmpIsNormal(t, tc, "IsNormal", f, test, f.IsNormal([]byte(test)), test == gold) - cmpIsNormal(t, tc, "IsNormalString", f, test, f.IsNormalString(test), test == gold) -} - -func doConformanceTests(t *testing.T, tc *Test, partn int) { - for i := 0; i <= 2; i++ { - doTest(t, tc, NFC, tc.cols[1], tc.cols[i]) - doTest(t, tc, NFD, tc.cols[2], tc.cols[i]) - doTest(t, tc, NFKC, tc.cols[3], tc.cols[i]) - doTest(t, tc, NFKD, tc.cols[4], tc.cols[i]) - } - for i := 3; i <= 4; i++ { - doTest(t, tc, NFC, tc.cols[3], tc.cols[i]) - doTest(t, tc, NFD, tc.cols[4], tc.cols[i]) - doTest(t, tc, NFKC, tc.cols[3], tc.cols[i]) - doTest(t, tc, NFKD, tc.cols[4], tc.cols[i]) - } -} - -func TestCharacterByCharacter(t *testing.T) { - skipShort(t) - tests := part[1].tests - var last rune = 0 - for i := 0; i <= len(tests); i++ { // last one is special case - var r rune - if i == len(tests) { - r = 0x2FA1E // Don't have to go to 0x10FFFF - } else { - r = tests[i].r - } - for last++; last < r; last++ { - // Check all characters that were not explicitly listed in the test. - tc := &Test{partnr: 1, number: -1} - char := string(last) - doTest(t, tc, NFC, char, char) - doTest(t, tc, NFD, char, char) - doTest(t, tc, NFKC, char, char) - doTest(t, tc, NFKD, char, char) - } - if i < len(tests) { - doConformanceTests(t, &tests[i], 1) - } - } -} - -func TestStandardTests(t *testing.T) { - skipShort(t) - for _, j := range []int{0, 2, 3} { - for _, test := range part[j].tests { - doConformanceTests(t, &test, j) - } - } -} - -// TestPerformance verifies that normalization is O(n). If any of the -// code does not properly check for maxCombiningChars, normalization -// may exhibit O(n**2) behavior. -func TestPerformance(t *testing.T) { - skipShort(t) - runtime.GOMAXPROCS(2) - success := make(chan bool, 1) - go func() { - buf := bytes.Repeat([]byte("\u035D"), 1024*1024) - buf = append(buf, "\u035B"...) - NFC.Append(nil, buf...) - success <- true - }() - timeout := time.After(1 * time.Second) - select { - case <-success: - // test completed before the timeout - case <-timeout: - t.Errorf(`unexpectedly long time to complete PerformanceTest`) - } -} diff --git a/vendor/golang.org/x/text/unicode/rangetable/gen.go b/vendor/golang.org/x/text/unicode/rangetable/gen.go index 6a64e42aba..5b5f828a16 100644 --- a/vendor/golang.org/x/text/unicode/rangetable/gen.go +++ b/vendor/golang.org/x/text/unicode/rangetable/gen.go @@ -95,7 +95,7 @@ func main() { fmt.Fprintf(w, "// Total size %d bytes (%d KiB)\n", size, size/1024) - gen.WriteGoFile("tables.go", "rangetable", w.Bytes()) + gen.WriteVersionedGoFile("tables.go", "rangetable", w.Bytes()) } func print(w io.Writer, rt *unicode.RangeTable) { diff --git a/vendor/golang.org/x/text/unicode/rangetable/merge_test.go b/vendor/golang.org/x/text/unicode/rangetable/merge_test.go deleted file mode 100644 index 93ed0fcadc..0000000000 --- a/vendor/golang.org/x/text/unicode/rangetable/merge_test.go +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2015 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 rangetable - -import ( - "testing" - "unicode" -) - -var ( - maxRuneTable = &unicode.RangeTable{ - R32: []unicode.Range32{ - {unicode.MaxRune, unicode.MaxRune, 1}, - }, - } - - overlap1 = &unicode.RangeTable{ - R16: []unicode.Range16{ - {0x100, 0xfffc, 4}, - }, - R32: []unicode.Range32{ - {0x100000, 0x10fffc, 4}, - }, - } - - overlap2 = &unicode.RangeTable{ - R16: []unicode.Range16{ - {0x101, 0xfffd, 4}, - }, - R32: []unicode.Range32{ - {0x100001, 0x10fffd, 3}, - }, - } - - // The following table should be compacted into two entries for R16 and R32. - optimize = &unicode.RangeTable{ - R16: []unicode.Range16{ - {0x1, 0x1, 1}, - {0x2, 0x2, 1}, - {0x3, 0x3, 1}, - {0x5, 0x5, 1}, - {0x7, 0x7, 1}, - {0x9, 0x9, 1}, - {0xb, 0xf, 2}, - }, - R32: []unicode.Range32{ - {0x10001, 0x10001, 1}, - {0x10002, 0x10002, 1}, - {0x10003, 0x10003, 1}, - {0x10005, 0x10005, 1}, - {0x10007, 0x10007, 1}, - {0x10009, 0x10009, 1}, - {0x1000b, 0x1000f, 2}, - }, - } -) - -func TestMerge(t *testing.T) { - for i, tt := range [][]*unicode.RangeTable{ - {unicode.Cc, unicode.Cf}, - {unicode.L, unicode.Ll}, - {unicode.L, unicode.Ll, unicode.Lu}, - {unicode.Ll, unicode.Lu}, - {unicode.M}, - unicode.GraphicRanges, - cased, - - // Merge R16 only and R32 only and vice versa. - {unicode.Khmer, unicode.Khudawadi}, - {unicode.Imperial_Aramaic, unicode.Radical}, - - // Merge with empty. - {&unicode.RangeTable{}}, - {&unicode.RangeTable{}, &unicode.RangeTable{}}, - {&unicode.RangeTable{}, &unicode.RangeTable{}, &unicode.RangeTable{}}, - {&unicode.RangeTable{}, unicode.Hiragana}, - {unicode.Inherited, &unicode.RangeTable{}}, - {&unicode.RangeTable{}, unicode.Hanunoo, &unicode.RangeTable{}}, - - // Hypothetical tables. - {maxRuneTable}, - {overlap1, overlap2}, - - // Optimization - {optimize}, - } { - rt := Merge(tt...) - for r := rune(0); r <= unicode.MaxRune; r++ { - if got, want := unicode.Is(rt, r), unicode.In(r, tt...); got != want { - t.Fatalf("%d:%U: got %v; want %v", i, r, got, want) - } - } - // Test optimization and correctness for R16. - for k := 0; k < len(rt.R16)-1; k++ { - if lo, hi := rt.R16[k].Lo, rt.R16[k].Hi; lo > hi { - t.Errorf("%d: Lo (%x) > Hi (%x)", i, lo, hi) - } - if hi, lo := rt.R16[k].Hi, rt.R16[k+1].Lo; hi >= lo { - t.Errorf("%d: Hi (%x) >= next Lo (%x)", i, hi, lo) - } - if rt.R16[k].Hi+rt.R16[k].Stride == rt.R16[k+1].Lo { - t.Errorf("%d: missed optimization for R16 at %d between %X and %x", - i, k, rt.R16[k], rt.R16[k+1]) - } - } - // Test optimization and correctness for R32. - for k := 0; k < len(rt.R32)-1; k++ { - if lo, hi := rt.R32[k].Lo, rt.R32[k].Hi; lo > hi { - t.Errorf("%d: Lo (%x) > Hi (%x)", i, lo, hi) - } - if hi, lo := rt.R32[k].Hi, rt.R32[k+1].Lo; hi >= lo { - t.Errorf("%d: Hi (%x) >= next Lo (%x)", i, hi, lo) - } - if rt.R32[k].Hi+rt.R32[k].Stride == rt.R32[k+1].Lo { - t.Errorf("%d: missed optimization for R32 at %d between %X and %X", - i, k, rt.R32[k], rt.R32[k+1]) - } - } - } -} - -const runes = "Hello World in 2015!,\U0010fffd" - -func BenchmarkNotMerged(t *testing.B) { - for i := 0; i < t.N; i++ { - for _, r := range runes { - unicode.In(r, unicode.GraphicRanges...) - } - } -} - -func BenchmarkMerged(t *testing.B) { - rt := Merge(unicode.GraphicRanges...) - - for i := 0; i < t.N; i++ { - for _, r := range runes { - unicode.Is(rt, r) - } - } -} - -var cased = []*unicode.RangeTable{ - unicode.Lower, - unicode.Upper, - unicode.Title, - unicode.Other_Lowercase, - unicode.Other_Uppercase, -} - -func BenchmarkNotMergedCased(t *testing.B) { - for i := 0; i < t.N; i++ { - for _, r := range runes { - unicode.In(r, cased...) - } - } -} - -func BenchmarkMergedCased(t *testing.B) { - // This reduces len(R16) from 243 to 82 and len(R32) from 65 to 35 for - // Unicode 7.0.0. - rt := Merge(cased...) - - for i := 0; i < t.N; i++ { - for _, r := range runes { - unicode.Is(rt, r) - } - } -} - -func BenchmarkInit(t *testing.B) { - for i := 0; i < t.N; i++ { - Merge(cased...) - Merge(unicode.GraphicRanges...) - } -} - -func BenchmarkInit2(t *testing.B) { - // Hypothetical near-worst-case performance. - for i := 0; i < t.N; i++ { - Merge(overlap1, overlap2) - } -} diff --git a/vendor/golang.org/x/text/unicode/rangetable/rangetable_test.go b/vendor/golang.org/x/text/unicode/rangetable/rangetable_test.go deleted file mode 100644 index 5a355aa353..0000000000 --- a/vendor/golang.org/x/text/unicode/rangetable/rangetable_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package rangetable - -import ( - "reflect" - "testing" - "unicode" -) - -var ( - empty = &unicode.RangeTable{} - many = &unicode.RangeTable{ - R16: []unicode.Range16{{0, 0xffff, 5}}, - R32: []unicode.Range32{{0x10004, 0x10009, 5}}, - LatinOffset: 0, - } -) - -func TestVisit(t *testing.T) { - Visit(empty, func(got rune) { - t.Error("call from empty RangeTable") - }) - - var want rune - Visit(many, func(got rune) { - if got != want { - t.Errorf("got %U; want %U", got, want) - } - want += 5 - }) - if want -= 5; want != 0x10009 { - t.Errorf("last run was %U; want U+10009", want) - } -} - -func TestNew(t *testing.T) { - for i, rt := range []*unicode.RangeTable{ - empty, - unicode.Co, - unicode.Letter, - unicode.ASCII_Hex_Digit, - many, - maxRuneTable, - } { - var got, want []rune - Visit(rt, func(r rune) { - want = append(want, r) - }) - Visit(New(want...), func(r rune) { - got = append(got, r) - }) - if !reflect.DeepEqual(got, want) { - t.Errorf("%d:\ngot %v;\nwant %v", i, got, want) - } - } -} diff --git a/vendor/golang.org/x/text/unicode/rangetable/tables.go b/vendor/golang.org/x/text/unicode/rangetable/tables10.0.0.go similarity index 99% rename from vendor/golang.org/x/text/unicode/rangetable/tables.go rename to vendor/golang.org/x/text/unicode/rangetable/tables10.0.0.go index 73179c0e0e..f15a873ac0 100644 --- a/vendor/golang.org/x/text/unicode/rangetable/tables.go +++ b/vendor/golang.org/x/text/unicode/rangetable/tables10.0.0.go @@ -1,5 +1,7 @@ // Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. +// +build go1.10 + package rangetable //go:generate go run gen.go --versions=4.1.0,5.1.0,5.2.0,5.0.0,6.1.0,6.2.0,6.3.0,6.0.0,7.0.0,8.0.0,9.0.0,10.0.0 diff --git a/vendor/golang.org/x/text/unicode/rangetable/tables9.0.0.go b/vendor/golang.org/x/text/unicode/rangetable/tables9.0.0.go new file mode 100644 index 0000000000..aef876d963 --- /dev/null +++ b/vendor/golang.org/x/text/unicode/rangetable/tables9.0.0.go @@ -0,0 +1,5737 @@ +// Code generated by running "go generate" in golang.org/x/text. DO NOT EDIT. + +// +build !go1.10 + +package rangetable + +//go:generate go run gen.go --versions=4.1.0,5.1.0,5.2.0,5.0.0,6.1.0,6.2.0,6.3.0,6.0.0,7.0.0,8.0.0,9.0.0 + +import "unicode" + +var assigned = map[string]*unicode.RangeTable{ + "4.1.0": assigned4_1_0, + "5.1.0": assigned5_1_0, + "5.2.0": assigned5_2_0, + "5.0.0": assigned5_0_0, + "6.1.0": assigned6_1_0, + "6.2.0": assigned6_2_0, + "6.3.0": assigned6_3_0, + "6.0.0": assigned6_0_0, + "7.0.0": assigned7_0_0, + "8.0.0": assigned8_0_0, + "9.0.0": assigned9_0_0, +} + +// size 2924 bytes (2 KiB) +var assigned4_1_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x0241, 1}, + {0x0250, 0x036f, 1}, + {0x0374, 0x0375, 1}, + {0x037a, 0x037e, 4}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x03ce, 1}, + {0x03d0, 0x0486, 1}, + {0x0488, 0x04ce, 1}, + {0x04d0, 0x04f9, 1}, + {0x0500, 0x050f, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x0591, 0x05b9, 1}, + {0x05bb, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x0603, 1}, + {0x060b, 0x0615, 1}, + {0x061b, 0x061e, 3}, + {0x061f, 0x0621, 2}, + {0x0622, 0x063a, 1}, + {0x0640, 0x065e, 1}, + {0x0660, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x076d, 1}, + {0x0780, 0x07b1, 1}, + {0x0901, 0x0939, 1}, + {0x093c, 0x094d, 1}, + {0x0950, 0x0954, 1}, + {0x0958, 0x0970, 1}, + {0x097d, 0x0981, 4}, + {0x0982, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fa, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a59, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a74, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0aef, 1}, + {0x0af1, 0x0b01, 16}, + {0x0b02, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b43, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b61, 1}, + {0x0b66, 0x0b71, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd7, 0x0be6, 15}, + {0x0be7, 0x0bfa, 1}, + {0x0c01, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c33, 1}, + {0x0c35, 0x0c39, 1}, + {0x0c3e, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c60, 0x0c61, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c82, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce6, 5}, + {0x0ce7, 0x0cef, 1}, + {0x0d02, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d28, 1}, + {0x0d2a, 0x0d39, 1}, + {0x0d3e, 0x0d43, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4d, 1}, + {0x0d57, 0x0d60, 9}, + {0x0d61, 0x0d66, 5}, + {0x0d67, 0x0d6f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edd, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6a, 1}, + {0x0f71, 0x0f8b, 1}, + {0x0f90, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fcf, 0x0fd1, 1}, + {0x1000, 0x1021, 1}, + {0x1023, 0x1027, 1}, + {0x1029, 0x102a, 1}, + {0x102c, 0x1032, 1}, + {0x1036, 0x1039, 1}, + {0x1040, 0x1059, 1}, + {0x10a0, 0x10c5, 1}, + {0x10d0, 0x10fc, 1}, + {0x1100, 0x1159, 1}, + {0x115f, 0x11a2, 1}, + {0x11a8, 0x11f9, 1}, + {0x1200, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135f, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f4, 1}, + {0x1401, 0x1676, 1}, + {0x1680, 0x169c, 1}, + {0x16a0, 0x16f0, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18a9, 1}, + {0x1900, 0x191c, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19a9, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19d9, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a1f, 1}, + {0x1d00, 0x1dc3, 1}, + {0x1e00, 0x1e9b, 1}, + {0x1ea0, 0x1ef9, 1}, + {0x1f00, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2063, 1}, + {0x206a, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x2094, 1}, + {0x20a0, 0x20b5, 1}, + {0x20d0, 0x20eb, 1}, + {0x2100, 0x214c, 1}, + {0x2153, 0x2183, 1}, + {0x2190, 0x23db, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x269c, 1}, + {0x26a0, 0x26b1, 1}, + {0x2701, 0x2704, 1}, + {0x2706, 0x2709, 1}, + {0x270c, 0x2727, 1}, + {0x2729, 0x274b, 1}, + {0x274d, 0x274f, 2}, + {0x2750, 0x2752, 1}, + {0x2756, 0x2758, 2}, + {0x2759, 0x275e, 1}, + {0x2761, 0x2794, 1}, + {0x2798, 0x27af, 1}, + {0x27b1, 0x27be, 1}, + {0x27c0, 0x27c6, 1}, + {0x27d0, 0x27eb, 1}, + {0x27f0, 0x2b13, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c80, 0x2cea, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d30, 0x2d65, 1}, + {0x2d6f, 0x2d80, 17}, + {0x2d81, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2e00, 0x2e17, 1}, + {0x2e1c, 0x2e1d, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312c, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31b7, 1}, + {0x31c0, 0x31cf, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x3243, 1}, + {0x3250, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fbb, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa700, 0xa716, 1}, + {0xa800, 0xa82b, 1}, + {0xac00, 0xd7a3, 1}, + {0xd800, 0xfa2d, 1}, + {0xfa30, 0xfa6a, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbb1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe23, 1}, + {0xfe30, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018a, 1}, + {0x00010300, 0x0001031e, 1}, + {0x00010320, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010a00, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d12a, 0x0001d1dd, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7c9, 1}, + {0x0001d7ce, 0x0001d7ff, 1}, + {0x00020000, 0x0002a6d6, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// size 3152 bytes (3 KiB) +var assigned5_1_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x0377, 1}, + {0x037a, 0x037e, 1}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x0523, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x0591, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x0603, 1}, + {0x0606, 0x061b, 1}, + {0x061e, 0x061f, 1}, + {0x0621, 0x065e, 1}, + {0x0660, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x07b1, 1}, + {0x07c0, 0x07fa, 1}, + {0x0901, 0x0939, 1}, + {0x093c, 0x094d, 1}, + {0x0950, 0x0954, 1}, + {0x0958, 0x0972, 1}, + {0x097b, 0x097f, 1}, + {0x0981, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fa, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a51, 0x0a59, 8}, + {0x0a5a, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a75, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0aef, 1}, + {0x0af1, 0x0b01, 16}, + {0x0b02, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b44, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b63, 1}, + {0x0b66, 0x0b71, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd0, 0x0bd7, 7}, + {0x0be6, 0x0bfa, 1}, + {0x0c01, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c33, 1}, + {0x0c35, 0x0c39, 1}, + {0x0c3d, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c58, 0x0c59, 1}, + {0x0c60, 0x0c63, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c78, 0x0c7f, 1}, + {0x0c82, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce3, 1}, + {0x0ce6, 0x0cef, 1}, + {0x0cf1, 0x0cf2, 1}, + {0x0d02, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d28, 1}, + {0x0d2a, 0x0d39, 1}, + {0x0d3d, 0x0d44, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4d, 1}, + {0x0d57, 0x0d60, 9}, + {0x0d61, 0x0d63, 1}, + {0x0d66, 0x0d75, 1}, + {0x0d79, 0x0d7f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edd, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6c, 1}, + {0x0f71, 0x0f8b, 1}, + {0x0f90, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fce, 0x0fd4, 1}, + {0x1000, 0x1099, 1}, + {0x109e, 0x10c5, 1}, + {0x10d0, 0x10fc, 1}, + {0x1100, 0x1159, 1}, + {0x115f, 0x11a2, 1}, + {0x11a8, 0x11f9, 1}, + {0x1200, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135f, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f4, 1}, + {0x1401, 0x1676, 1}, + {0x1680, 0x169c, 1}, + {0x16a0, 0x16f0, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18aa, 1}, + {0x1900, 0x191c, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19a9, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19d9, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a1f, 1}, + {0x1b00, 0x1b4b, 1}, + {0x1b50, 0x1b7c, 1}, + {0x1b80, 0x1baa, 1}, + {0x1bae, 0x1bb9, 1}, + {0x1c00, 0x1c37, 1}, + {0x1c3b, 0x1c49, 1}, + {0x1c4d, 0x1c7f, 1}, + {0x1d00, 0x1de6, 1}, + {0x1dfe, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2064, 1}, + {0x206a, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x2094, 1}, + {0x20a0, 0x20b5, 1}, + {0x20d0, 0x20f0, 1}, + {0x2100, 0x214f, 1}, + {0x2153, 0x2188, 1}, + {0x2190, 0x23e7, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x269d, 1}, + {0x26a0, 0x26bc, 1}, + {0x26c0, 0x26c3, 1}, + {0x2701, 0x2704, 1}, + {0x2706, 0x2709, 1}, + {0x270c, 0x2727, 1}, + {0x2729, 0x274b, 1}, + {0x274d, 0x274f, 2}, + {0x2750, 0x2752, 1}, + {0x2756, 0x2758, 2}, + {0x2759, 0x275e, 1}, + {0x2761, 0x2794, 1}, + {0x2798, 0x27af, 1}, + {0x27b1, 0x27be, 1}, + {0x27c0, 0x27ca, 1}, + {0x27cc, 0x27d0, 4}, + {0x27d1, 0x2b4c, 1}, + {0x2b50, 0x2b54, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c60, 0x2c6f, 1}, + {0x2c71, 0x2c7d, 1}, + {0x2c80, 0x2cea, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d30, 0x2d65, 1}, + {0x2d6f, 0x2d80, 17}, + {0x2d81, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2de0, 0x2e30, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312d, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31b7, 1}, + {0x31c0, 0x31e3, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x3243, 1}, + {0x3250, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fc3, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa500, 0xa62b, 1}, + {0xa640, 0xa65f, 1}, + {0xa662, 0xa673, 1}, + {0xa67c, 0xa697, 1}, + {0xa700, 0xa78c, 1}, + {0xa7fb, 0xa82b, 1}, + {0xa840, 0xa877, 1}, + {0xa880, 0xa8c4, 1}, + {0xa8ce, 0xa8d9, 1}, + {0xa900, 0xa953, 1}, + {0xa95f, 0xaa00, 161}, + {0xaa01, 0xaa36, 1}, + {0xaa40, 0xaa4d, 1}, + {0xaa50, 0xaa59, 1}, + {0xaa5c, 0xaa5f, 1}, + {0xac00, 0xd7a3, 1}, + {0xd800, 0xfa2d, 1}, + {0xfa30, 0xfa6a, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbb1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe26, 1}, + {0xfe30, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018a, 1}, + {0x00010190, 0x0001019b, 1}, + {0x000101d0, 0x000101fd, 1}, + {0x00010280, 0x0001029c, 1}, + {0x000102a0, 0x000102d0, 1}, + {0x00010300, 0x0001031e, 1}, + {0x00010320, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010900, 0x00010919, 1}, + {0x0001091f, 0x00010939, 1}, + {0x0001093f, 0x00010a00, 193}, + {0x00010a01, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x00012000, 0x0001236e, 1}, + {0x00012400, 0x00012462, 1}, + {0x00012470, 0x00012473, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d129, 0x0001d1dd, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d360, 0x0001d371, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7cb, 1}, + {0x0001d7ce, 0x0001d7ff, 1}, + {0x0001f000, 0x0001f02b, 1}, + {0x0001f030, 0x0001f093, 1}, + {0x00020000, 0x0002a6d6, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// size 3518 bytes (3 KiB) +var assigned5_2_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x0377, 1}, + {0x037a, 0x037e, 1}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x0525, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x0591, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x0603, 1}, + {0x0606, 0x061b, 1}, + {0x061e, 0x061f, 1}, + {0x0621, 0x065e, 1}, + {0x0660, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x07b1, 1}, + {0x07c0, 0x07fa, 1}, + {0x0800, 0x082d, 1}, + {0x0830, 0x083e, 1}, + {0x0900, 0x0939, 1}, + {0x093c, 0x094e, 1}, + {0x0950, 0x0955, 1}, + {0x0958, 0x0972, 1}, + {0x0979, 0x097f, 1}, + {0x0981, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fb, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a51, 0x0a59, 8}, + {0x0a5a, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a75, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0aef, 1}, + {0x0af1, 0x0b01, 16}, + {0x0b02, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b44, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b63, 1}, + {0x0b66, 0x0b71, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd0, 0x0bd7, 7}, + {0x0be6, 0x0bfa, 1}, + {0x0c01, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c33, 1}, + {0x0c35, 0x0c39, 1}, + {0x0c3d, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c58, 0x0c59, 1}, + {0x0c60, 0x0c63, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c78, 0x0c7f, 1}, + {0x0c82, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce3, 1}, + {0x0ce6, 0x0cef, 1}, + {0x0cf1, 0x0cf2, 1}, + {0x0d02, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d28, 1}, + {0x0d2a, 0x0d39, 1}, + {0x0d3d, 0x0d44, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4d, 1}, + {0x0d57, 0x0d60, 9}, + {0x0d61, 0x0d63, 1}, + {0x0d66, 0x0d75, 1}, + {0x0d79, 0x0d7f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edd, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6c, 1}, + {0x0f71, 0x0f8b, 1}, + {0x0f90, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fce, 0x0fd8, 1}, + {0x1000, 0x10c5, 1}, + {0x10d0, 0x10fc, 1}, + {0x1100, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135f, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f4, 1}, + {0x1400, 0x169c, 1}, + {0x16a0, 0x16f0, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18aa, 1}, + {0x18b0, 0x18f5, 1}, + {0x1900, 0x191c, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19ab, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19da, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a5e, 1}, + {0x1a60, 0x1a7c, 1}, + {0x1a7f, 0x1a89, 1}, + {0x1a90, 0x1a99, 1}, + {0x1aa0, 0x1aad, 1}, + {0x1b00, 0x1b4b, 1}, + {0x1b50, 0x1b7c, 1}, + {0x1b80, 0x1baa, 1}, + {0x1bae, 0x1bb9, 1}, + {0x1c00, 0x1c37, 1}, + {0x1c3b, 0x1c49, 1}, + {0x1c4d, 0x1c7f, 1}, + {0x1cd0, 0x1cf2, 1}, + {0x1d00, 0x1de6, 1}, + {0x1dfd, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2064, 1}, + {0x206a, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x2094, 1}, + {0x20a0, 0x20b8, 1}, + {0x20d0, 0x20f0, 1}, + {0x2100, 0x2189, 1}, + {0x2190, 0x23e8, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x26cd, 1}, + {0x26cf, 0x26e1, 1}, + {0x26e3, 0x26e8, 5}, + {0x26e9, 0x26ff, 1}, + {0x2701, 0x2704, 1}, + {0x2706, 0x2709, 1}, + {0x270c, 0x2727, 1}, + {0x2729, 0x274b, 1}, + {0x274d, 0x274f, 2}, + {0x2750, 0x2752, 1}, + {0x2756, 0x275e, 1}, + {0x2761, 0x2794, 1}, + {0x2798, 0x27af, 1}, + {0x27b1, 0x27be, 1}, + {0x27c0, 0x27ca, 1}, + {0x27cc, 0x27d0, 4}, + {0x27d1, 0x2b4c, 1}, + {0x2b50, 0x2b59, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c60, 0x2cf1, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d30, 0x2d65, 1}, + {0x2d6f, 0x2d80, 17}, + {0x2d81, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2de0, 0x2e31, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312d, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31b7, 1}, + {0x31c0, 0x31e3, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fcb, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa4d0, 0xa62b, 1}, + {0xa640, 0xa65f, 1}, + {0xa662, 0xa673, 1}, + {0xa67c, 0xa697, 1}, + {0xa6a0, 0xa6f7, 1}, + {0xa700, 0xa78c, 1}, + {0xa7fb, 0xa82b, 1}, + {0xa830, 0xa839, 1}, + {0xa840, 0xa877, 1}, + {0xa880, 0xa8c4, 1}, + {0xa8ce, 0xa8d9, 1}, + {0xa8e0, 0xa8fb, 1}, + {0xa900, 0xa953, 1}, + {0xa95f, 0xa97c, 1}, + {0xa980, 0xa9cd, 1}, + {0xa9cf, 0xa9d9, 1}, + {0xa9de, 0xa9df, 1}, + {0xaa00, 0xaa36, 1}, + {0xaa40, 0xaa4d, 1}, + {0xaa50, 0xaa59, 1}, + {0xaa5c, 0xaa7b, 1}, + {0xaa80, 0xaac2, 1}, + {0xaadb, 0xaadf, 1}, + {0xabc0, 0xabed, 1}, + {0xabf0, 0xabf9, 1}, + {0xac00, 0xd7a3, 1}, + {0xd7b0, 0xd7c6, 1}, + {0xd7cb, 0xd7fb, 1}, + {0xd800, 0xfa2d, 1}, + {0xfa30, 0xfa6d, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbb1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe26, 1}, + {0xfe30, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018a, 1}, + {0x00010190, 0x0001019b, 1}, + {0x000101d0, 0x000101fd, 1}, + {0x00010280, 0x0001029c, 1}, + {0x000102a0, 0x000102d0, 1}, + {0x00010300, 0x0001031e, 1}, + {0x00010320, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010840, 0x00010855, 1}, + {0x00010857, 0x0001085f, 1}, + {0x00010900, 0x0001091b, 1}, + {0x0001091f, 0x00010939, 1}, + {0x0001093f, 0x00010a00, 193}, + {0x00010a01, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x00010a60, 0x00010a7f, 1}, + {0x00010b00, 0x00010b35, 1}, + {0x00010b39, 0x00010b55, 1}, + {0x00010b58, 0x00010b72, 1}, + {0x00010b78, 0x00010b7f, 1}, + {0x00010c00, 0x00010c48, 1}, + {0x00010e60, 0x00010e7e, 1}, + {0x00011080, 0x000110c1, 1}, + {0x00012000, 0x0001236e, 1}, + {0x00012400, 0x00012462, 1}, + {0x00012470, 0x00012473, 1}, + {0x00013000, 0x0001342e, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d129, 0x0001d1dd, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d360, 0x0001d371, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7cb, 1}, + {0x0001d7ce, 0x0001d7ff, 1}, + {0x0001f000, 0x0001f02b, 1}, + {0x0001f030, 0x0001f093, 1}, + {0x0001f100, 0x0001f10a, 1}, + {0x0001f110, 0x0001f12e, 1}, + {0x0001f131, 0x0001f13d, 12}, + {0x0001f13f, 0x0001f142, 3}, + {0x0001f146, 0x0001f14a, 4}, + {0x0001f14b, 0x0001f14e, 1}, + {0x0001f157, 0x0001f15f, 8}, + {0x0001f179, 0x0001f17b, 2}, + {0x0001f17c, 0x0001f17f, 3}, + {0x0001f18a, 0x0001f18d, 1}, + {0x0001f190, 0x0001f200, 112}, + {0x0001f210, 0x0001f231, 1}, + {0x0001f240, 0x0001f248, 1}, + {0x00020000, 0x0002a6d6, 1}, + {0x0002a700, 0x0002b734, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// size 3026 bytes (2 KiB) +var assigned5_0_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x036f, 1}, + {0x0374, 0x0375, 1}, + {0x037a, 0x037e, 1}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x03ce, 1}, + {0x03d0, 0x0486, 1}, + {0x0488, 0x0513, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x0591, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x0603, 1}, + {0x060b, 0x0615, 1}, + {0x061b, 0x061e, 3}, + {0x061f, 0x0621, 2}, + {0x0622, 0x063a, 1}, + {0x0640, 0x065e, 1}, + {0x0660, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x076d, 1}, + {0x0780, 0x07b1, 1}, + {0x07c0, 0x07fa, 1}, + {0x0901, 0x0939, 1}, + {0x093c, 0x094d, 1}, + {0x0950, 0x0954, 1}, + {0x0958, 0x0970, 1}, + {0x097b, 0x097f, 1}, + {0x0981, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fa, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a59, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a74, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0aef, 1}, + {0x0af1, 0x0b01, 16}, + {0x0b02, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b43, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b61, 1}, + {0x0b66, 0x0b71, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd7, 0x0be6, 15}, + {0x0be7, 0x0bfa, 1}, + {0x0c01, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c33, 1}, + {0x0c35, 0x0c39, 1}, + {0x0c3e, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c60, 0x0c61, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c82, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce3, 1}, + {0x0ce6, 0x0cef, 1}, + {0x0cf1, 0x0cf2, 1}, + {0x0d02, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d28, 1}, + {0x0d2a, 0x0d39, 1}, + {0x0d3e, 0x0d43, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4d, 1}, + {0x0d57, 0x0d60, 9}, + {0x0d61, 0x0d66, 5}, + {0x0d67, 0x0d6f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edd, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6a, 1}, + {0x0f71, 0x0f8b, 1}, + {0x0f90, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fcf, 0x0fd1, 1}, + {0x1000, 0x1021, 1}, + {0x1023, 0x1027, 1}, + {0x1029, 0x102a, 1}, + {0x102c, 0x1032, 1}, + {0x1036, 0x1039, 1}, + {0x1040, 0x1059, 1}, + {0x10a0, 0x10c5, 1}, + {0x10d0, 0x10fc, 1}, + {0x1100, 0x1159, 1}, + {0x115f, 0x11a2, 1}, + {0x11a8, 0x11f9, 1}, + {0x1200, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135f, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f4, 1}, + {0x1401, 0x1676, 1}, + {0x1680, 0x169c, 1}, + {0x16a0, 0x16f0, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18a9, 1}, + {0x1900, 0x191c, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19a9, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19d9, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a1f, 1}, + {0x1b00, 0x1b4b, 1}, + {0x1b50, 0x1b7c, 1}, + {0x1d00, 0x1dca, 1}, + {0x1dfe, 0x1e9b, 1}, + {0x1ea0, 0x1ef9, 1}, + {0x1f00, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2063, 1}, + {0x206a, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x2094, 1}, + {0x20a0, 0x20b5, 1}, + {0x20d0, 0x20ef, 1}, + {0x2100, 0x214e, 1}, + {0x2153, 0x2184, 1}, + {0x2190, 0x23e7, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x269c, 1}, + {0x26a0, 0x26b2, 1}, + {0x2701, 0x2704, 1}, + {0x2706, 0x2709, 1}, + {0x270c, 0x2727, 1}, + {0x2729, 0x274b, 1}, + {0x274d, 0x274f, 2}, + {0x2750, 0x2752, 1}, + {0x2756, 0x2758, 2}, + {0x2759, 0x275e, 1}, + {0x2761, 0x2794, 1}, + {0x2798, 0x27af, 1}, + {0x27b1, 0x27be, 1}, + {0x27c0, 0x27ca, 1}, + {0x27d0, 0x27eb, 1}, + {0x27f0, 0x2b1a, 1}, + {0x2b20, 0x2b23, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c60, 0x2c6c, 1}, + {0x2c74, 0x2c77, 1}, + {0x2c80, 0x2cea, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d30, 0x2d65, 1}, + {0x2d6f, 0x2d80, 17}, + {0x2d81, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2e00, 0x2e17, 1}, + {0x2e1c, 0x2e1d, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312c, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31b7, 1}, + {0x31c0, 0x31cf, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x3243, 1}, + {0x3250, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fbb, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa700, 0xa71a, 1}, + {0xa720, 0xa721, 1}, + {0xa800, 0xa82b, 1}, + {0xa840, 0xa877, 1}, + {0xac00, 0xd7a3, 1}, + {0xd800, 0xfa2d, 1}, + {0xfa30, 0xfa6a, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbb1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe23, 1}, + {0xfe30, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018a, 1}, + {0x00010300, 0x0001031e, 1}, + {0x00010320, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010900, 0x00010919, 1}, + {0x0001091f, 0x00010a00, 225}, + {0x00010a01, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x00012000, 0x0001236e, 1}, + {0x00012400, 0x00012462, 1}, + {0x00012470, 0x00012473, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d12a, 0x0001d1dd, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d360, 0x0001d371, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7cb, 1}, + {0x0001d7ce, 0x0001d7ff, 1}, + {0x00020000, 0x0002a6d6, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// size 4160 bytes (4 KiB) +var assigned6_1_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x0377, 1}, + {0x037a, 0x037e, 1}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x0527, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x058f, 0x0591, 2}, + {0x0592, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x0604, 1}, + {0x0606, 0x061b, 1}, + {0x061e, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x07b1, 1}, + {0x07c0, 0x07fa, 1}, + {0x0800, 0x082d, 1}, + {0x0830, 0x083e, 1}, + {0x0840, 0x085b, 1}, + {0x085e, 0x08a0, 66}, + {0x08a2, 0x08ac, 1}, + {0x08e4, 0x08fe, 1}, + {0x0900, 0x0977, 1}, + {0x0979, 0x097f, 1}, + {0x0981, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fb, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a51, 0x0a59, 8}, + {0x0a5a, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a75, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0af1, 1}, + {0x0b01, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b44, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b63, 1}, + {0x0b66, 0x0b77, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd0, 0x0bd7, 7}, + {0x0be6, 0x0bfa, 1}, + {0x0c01, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c33, 1}, + {0x0c35, 0x0c39, 1}, + {0x0c3d, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c58, 0x0c59, 1}, + {0x0c60, 0x0c63, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c78, 0x0c7f, 1}, + {0x0c82, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce3, 1}, + {0x0ce6, 0x0cef, 1}, + {0x0cf1, 0x0cf2, 1}, + {0x0d02, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d3a, 1}, + {0x0d3d, 0x0d44, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4e, 1}, + {0x0d57, 0x0d60, 9}, + {0x0d61, 0x0d63, 1}, + {0x0d66, 0x0d75, 1}, + {0x0d79, 0x0d7f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edf, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6c, 1}, + {0x0f71, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fce, 0x0fda, 1}, + {0x1000, 0x10c5, 1}, + {0x10c7, 0x10cd, 6}, + {0x10d0, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135d, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f4, 1}, + {0x1400, 0x169c, 1}, + {0x16a0, 0x16f0, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18aa, 1}, + {0x18b0, 0x18f5, 1}, + {0x1900, 0x191c, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19ab, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19da, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a5e, 1}, + {0x1a60, 0x1a7c, 1}, + {0x1a7f, 0x1a89, 1}, + {0x1a90, 0x1a99, 1}, + {0x1aa0, 0x1aad, 1}, + {0x1b00, 0x1b4b, 1}, + {0x1b50, 0x1b7c, 1}, + {0x1b80, 0x1bf3, 1}, + {0x1bfc, 0x1c37, 1}, + {0x1c3b, 0x1c49, 1}, + {0x1c4d, 0x1c7f, 1}, + {0x1cc0, 0x1cc7, 1}, + {0x1cd0, 0x1cf6, 1}, + {0x1d00, 0x1de6, 1}, + {0x1dfc, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2064, 1}, + {0x206a, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x209c, 1}, + {0x20a0, 0x20b9, 1}, + {0x20d0, 0x20f0, 1}, + {0x2100, 0x2189, 1}, + {0x2190, 0x23f3, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x26ff, 1}, + {0x2701, 0x2b4c, 1}, + {0x2b50, 0x2b59, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c60, 0x2cf3, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d27, 0x2d2d, 6}, + {0x2d30, 0x2d67, 1}, + {0x2d6f, 0x2d70, 1}, + {0x2d7f, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2de0, 0x2e3b, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312d, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31ba, 1}, + {0x31c0, 0x31e3, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fcc, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa4d0, 0xa62b, 1}, + {0xa640, 0xa697, 1}, + {0xa69f, 0xa6f7, 1}, + {0xa700, 0xa78e, 1}, + {0xa790, 0xa793, 1}, + {0xa7a0, 0xa7aa, 1}, + {0xa7f8, 0xa82b, 1}, + {0xa830, 0xa839, 1}, + {0xa840, 0xa877, 1}, + {0xa880, 0xa8c4, 1}, + {0xa8ce, 0xa8d9, 1}, + {0xa8e0, 0xa8fb, 1}, + {0xa900, 0xa953, 1}, + {0xa95f, 0xa97c, 1}, + {0xa980, 0xa9cd, 1}, + {0xa9cf, 0xa9d9, 1}, + {0xa9de, 0xa9df, 1}, + {0xaa00, 0xaa36, 1}, + {0xaa40, 0xaa4d, 1}, + {0xaa50, 0xaa59, 1}, + {0xaa5c, 0xaa7b, 1}, + {0xaa80, 0xaac2, 1}, + {0xaadb, 0xaaf6, 1}, + {0xab01, 0xab06, 1}, + {0xab09, 0xab0e, 1}, + {0xab11, 0xab16, 1}, + {0xab20, 0xab26, 1}, + {0xab28, 0xab2e, 1}, + {0xabc0, 0xabed, 1}, + {0xabf0, 0xabf9, 1}, + {0xac00, 0xd7a3, 1}, + {0xd7b0, 0xd7c6, 1}, + {0xd7cb, 0xd7fb, 1}, + {0xd800, 0xfa6d, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbc1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe26, 1}, + {0xfe30, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018a, 1}, + {0x00010190, 0x0001019b, 1}, + {0x000101d0, 0x000101fd, 1}, + {0x00010280, 0x0001029c, 1}, + {0x000102a0, 0x000102d0, 1}, + {0x00010300, 0x0001031e, 1}, + {0x00010320, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010840, 0x00010855, 1}, + {0x00010857, 0x0001085f, 1}, + {0x00010900, 0x0001091b, 1}, + {0x0001091f, 0x00010939, 1}, + {0x0001093f, 0x00010980, 65}, + {0x00010981, 0x000109b7, 1}, + {0x000109be, 0x000109bf, 1}, + {0x00010a00, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x00010a60, 0x00010a7f, 1}, + {0x00010b00, 0x00010b35, 1}, + {0x00010b39, 0x00010b55, 1}, + {0x00010b58, 0x00010b72, 1}, + {0x00010b78, 0x00010b7f, 1}, + {0x00010c00, 0x00010c48, 1}, + {0x00010e60, 0x00010e7e, 1}, + {0x00011000, 0x0001104d, 1}, + {0x00011052, 0x0001106f, 1}, + {0x00011080, 0x000110c1, 1}, + {0x000110d0, 0x000110e8, 1}, + {0x000110f0, 0x000110f9, 1}, + {0x00011100, 0x00011134, 1}, + {0x00011136, 0x00011143, 1}, + {0x00011180, 0x000111c8, 1}, + {0x000111d0, 0x000111d9, 1}, + {0x00011680, 0x000116b7, 1}, + {0x000116c0, 0x000116c9, 1}, + {0x00012000, 0x0001236e, 1}, + {0x00012400, 0x00012462, 1}, + {0x00012470, 0x00012473, 1}, + {0x00013000, 0x0001342e, 1}, + {0x00016800, 0x00016a38, 1}, + {0x00016f00, 0x00016f44, 1}, + {0x00016f50, 0x00016f7e, 1}, + {0x00016f8f, 0x00016f9f, 1}, + {0x0001b000, 0x0001b001, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d129, 0x0001d1dd, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d360, 0x0001d371, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7cb, 1}, + {0x0001d7ce, 0x0001d7ff, 1}, + {0x0001ee00, 0x0001ee03, 1}, + {0x0001ee05, 0x0001ee1f, 1}, + {0x0001ee21, 0x0001ee22, 1}, + {0x0001ee24, 0x0001ee27, 3}, + {0x0001ee29, 0x0001ee32, 1}, + {0x0001ee34, 0x0001ee37, 1}, + {0x0001ee39, 0x0001ee3b, 2}, + {0x0001ee42, 0x0001ee47, 5}, + {0x0001ee49, 0x0001ee4d, 2}, + {0x0001ee4e, 0x0001ee4f, 1}, + {0x0001ee51, 0x0001ee52, 1}, + {0x0001ee54, 0x0001ee57, 3}, + {0x0001ee59, 0x0001ee61, 2}, + {0x0001ee62, 0x0001ee64, 2}, + {0x0001ee67, 0x0001ee6a, 1}, + {0x0001ee6c, 0x0001ee72, 1}, + {0x0001ee74, 0x0001ee77, 1}, + {0x0001ee79, 0x0001ee7c, 1}, + {0x0001ee7e, 0x0001ee80, 2}, + {0x0001ee81, 0x0001ee89, 1}, + {0x0001ee8b, 0x0001ee9b, 1}, + {0x0001eea1, 0x0001eea3, 1}, + {0x0001eea5, 0x0001eea9, 1}, + {0x0001eeab, 0x0001eebb, 1}, + {0x0001eef0, 0x0001eef1, 1}, + {0x0001f000, 0x0001f02b, 1}, + {0x0001f030, 0x0001f093, 1}, + {0x0001f0a0, 0x0001f0ae, 1}, + {0x0001f0b1, 0x0001f0be, 1}, + {0x0001f0c1, 0x0001f0cf, 1}, + {0x0001f0d1, 0x0001f0df, 1}, + {0x0001f100, 0x0001f10a, 1}, + {0x0001f110, 0x0001f12e, 1}, + {0x0001f130, 0x0001f16b, 1}, + {0x0001f170, 0x0001f19a, 1}, + {0x0001f1e6, 0x0001f202, 1}, + {0x0001f210, 0x0001f23a, 1}, + {0x0001f240, 0x0001f248, 1}, + {0x0001f250, 0x0001f251, 1}, + {0x0001f300, 0x0001f320, 1}, + {0x0001f330, 0x0001f335, 1}, + {0x0001f337, 0x0001f37c, 1}, + {0x0001f380, 0x0001f393, 1}, + {0x0001f3a0, 0x0001f3c4, 1}, + {0x0001f3c6, 0x0001f3ca, 1}, + {0x0001f3e0, 0x0001f3f0, 1}, + {0x0001f400, 0x0001f43e, 1}, + {0x0001f440, 0x0001f442, 2}, + {0x0001f443, 0x0001f4f7, 1}, + {0x0001f4f9, 0x0001f4fc, 1}, + {0x0001f500, 0x0001f53d, 1}, + {0x0001f540, 0x0001f543, 1}, + {0x0001f550, 0x0001f567, 1}, + {0x0001f5fb, 0x0001f640, 1}, + {0x0001f645, 0x0001f64f, 1}, + {0x0001f680, 0x0001f6c5, 1}, + {0x0001f700, 0x0001f773, 1}, + {0x00020000, 0x0002a6d6, 1}, + {0x0002a700, 0x0002b734, 1}, + {0x0002b740, 0x0002b81d, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// size 4160 bytes (4 KiB) +var assigned6_2_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x0377, 1}, + {0x037a, 0x037e, 1}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x0527, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x058f, 0x0591, 2}, + {0x0592, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x0604, 1}, + {0x0606, 0x061b, 1}, + {0x061e, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x07b1, 1}, + {0x07c0, 0x07fa, 1}, + {0x0800, 0x082d, 1}, + {0x0830, 0x083e, 1}, + {0x0840, 0x085b, 1}, + {0x085e, 0x08a0, 66}, + {0x08a2, 0x08ac, 1}, + {0x08e4, 0x08fe, 1}, + {0x0900, 0x0977, 1}, + {0x0979, 0x097f, 1}, + {0x0981, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fb, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a51, 0x0a59, 8}, + {0x0a5a, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a75, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0af1, 1}, + {0x0b01, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b44, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b63, 1}, + {0x0b66, 0x0b77, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd0, 0x0bd7, 7}, + {0x0be6, 0x0bfa, 1}, + {0x0c01, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c33, 1}, + {0x0c35, 0x0c39, 1}, + {0x0c3d, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c58, 0x0c59, 1}, + {0x0c60, 0x0c63, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c78, 0x0c7f, 1}, + {0x0c82, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce3, 1}, + {0x0ce6, 0x0cef, 1}, + {0x0cf1, 0x0cf2, 1}, + {0x0d02, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d3a, 1}, + {0x0d3d, 0x0d44, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4e, 1}, + {0x0d57, 0x0d60, 9}, + {0x0d61, 0x0d63, 1}, + {0x0d66, 0x0d75, 1}, + {0x0d79, 0x0d7f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edf, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6c, 1}, + {0x0f71, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fce, 0x0fda, 1}, + {0x1000, 0x10c5, 1}, + {0x10c7, 0x10cd, 6}, + {0x10d0, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135d, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f4, 1}, + {0x1400, 0x169c, 1}, + {0x16a0, 0x16f0, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18aa, 1}, + {0x18b0, 0x18f5, 1}, + {0x1900, 0x191c, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19ab, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19da, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a5e, 1}, + {0x1a60, 0x1a7c, 1}, + {0x1a7f, 0x1a89, 1}, + {0x1a90, 0x1a99, 1}, + {0x1aa0, 0x1aad, 1}, + {0x1b00, 0x1b4b, 1}, + {0x1b50, 0x1b7c, 1}, + {0x1b80, 0x1bf3, 1}, + {0x1bfc, 0x1c37, 1}, + {0x1c3b, 0x1c49, 1}, + {0x1c4d, 0x1c7f, 1}, + {0x1cc0, 0x1cc7, 1}, + {0x1cd0, 0x1cf6, 1}, + {0x1d00, 0x1de6, 1}, + {0x1dfc, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2064, 1}, + {0x206a, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x209c, 1}, + {0x20a0, 0x20ba, 1}, + {0x20d0, 0x20f0, 1}, + {0x2100, 0x2189, 1}, + {0x2190, 0x23f3, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x26ff, 1}, + {0x2701, 0x2b4c, 1}, + {0x2b50, 0x2b59, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c60, 0x2cf3, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d27, 0x2d2d, 6}, + {0x2d30, 0x2d67, 1}, + {0x2d6f, 0x2d70, 1}, + {0x2d7f, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2de0, 0x2e3b, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312d, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31ba, 1}, + {0x31c0, 0x31e3, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fcc, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa4d0, 0xa62b, 1}, + {0xa640, 0xa697, 1}, + {0xa69f, 0xa6f7, 1}, + {0xa700, 0xa78e, 1}, + {0xa790, 0xa793, 1}, + {0xa7a0, 0xa7aa, 1}, + {0xa7f8, 0xa82b, 1}, + {0xa830, 0xa839, 1}, + {0xa840, 0xa877, 1}, + {0xa880, 0xa8c4, 1}, + {0xa8ce, 0xa8d9, 1}, + {0xa8e0, 0xa8fb, 1}, + {0xa900, 0xa953, 1}, + {0xa95f, 0xa97c, 1}, + {0xa980, 0xa9cd, 1}, + {0xa9cf, 0xa9d9, 1}, + {0xa9de, 0xa9df, 1}, + {0xaa00, 0xaa36, 1}, + {0xaa40, 0xaa4d, 1}, + {0xaa50, 0xaa59, 1}, + {0xaa5c, 0xaa7b, 1}, + {0xaa80, 0xaac2, 1}, + {0xaadb, 0xaaf6, 1}, + {0xab01, 0xab06, 1}, + {0xab09, 0xab0e, 1}, + {0xab11, 0xab16, 1}, + {0xab20, 0xab26, 1}, + {0xab28, 0xab2e, 1}, + {0xabc0, 0xabed, 1}, + {0xabf0, 0xabf9, 1}, + {0xac00, 0xd7a3, 1}, + {0xd7b0, 0xd7c6, 1}, + {0xd7cb, 0xd7fb, 1}, + {0xd800, 0xfa6d, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbc1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe26, 1}, + {0xfe30, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018a, 1}, + {0x00010190, 0x0001019b, 1}, + {0x000101d0, 0x000101fd, 1}, + {0x00010280, 0x0001029c, 1}, + {0x000102a0, 0x000102d0, 1}, + {0x00010300, 0x0001031e, 1}, + {0x00010320, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010840, 0x00010855, 1}, + {0x00010857, 0x0001085f, 1}, + {0x00010900, 0x0001091b, 1}, + {0x0001091f, 0x00010939, 1}, + {0x0001093f, 0x00010980, 65}, + {0x00010981, 0x000109b7, 1}, + {0x000109be, 0x000109bf, 1}, + {0x00010a00, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x00010a60, 0x00010a7f, 1}, + {0x00010b00, 0x00010b35, 1}, + {0x00010b39, 0x00010b55, 1}, + {0x00010b58, 0x00010b72, 1}, + {0x00010b78, 0x00010b7f, 1}, + {0x00010c00, 0x00010c48, 1}, + {0x00010e60, 0x00010e7e, 1}, + {0x00011000, 0x0001104d, 1}, + {0x00011052, 0x0001106f, 1}, + {0x00011080, 0x000110c1, 1}, + {0x000110d0, 0x000110e8, 1}, + {0x000110f0, 0x000110f9, 1}, + {0x00011100, 0x00011134, 1}, + {0x00011136, 0x00011143, 1}, + {0x00011180, 0x000111c8, 1}, + {0x000111d0, 0x000111d9, 1}, + {0x00011680, 0x000116b7, 1}, + {0x000116c0, 0x000116c9, 1}, + {0x00012000, 0x0001236e, 1}, + {0x00012400, 0x00012462, 1}, + {0x00012470, 0x00012473, 1}, + {0x00013000, 0x0001342e, 1}, + {0x00016800, 0x00016a38, 1}, + {0x00016f00, 0x00016f44, 1}, + {0x00016f50, 0x00016f7e, 1}, + {0x00016f8f, 0x00016f9f, 1}, + {0x0001b000, 0x0001b001, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d129, 0x0001d1dd, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d360, 0x0001d371, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7cb, 1}, + {0x0001d7ce, 0x0001d7ff, 1}, + {0x0001ee00, 0x0001ee03, 1}, + {0x0001ee05, 0x0001ee1f, 1}, + {0x0001ee21, 0x0001ee22, 1}, + {0x0001ee24, 0x0001ee27, 3}, + {0x0001ee29, 0x0001ee32, 1}, + {0x0001ee34, 0x0001ee37, 1}, + {0x0001ee39, 0x0001ee3b, 2}, + {0x0001ee42, 0x0001ee47, 5}, + {0x0001ee49, 0x0001ee4d, 2}, + {0x0001ee4e, 0x0001ee4f, 1}, + {0x0001ee51, 0x0001ee52, 1}, + {0x0001ee54, 0x0001ee57, 3}, + {0x0001ee59, 0x0001ee61, 2}, + {0x0001ee62, 0x0001ee64, 2}, + {0x0001ee67, 0x0001ee6a, 1}, + {0x0001ee6c, 0x0001ee72, 1}, + {0x0001ee74, 0x0001ee77, 1}, + {0x0001ee79, 0x0001ee7c, 1}, + {0x0001ee7e, 0x0001ee80, 2}, + {0x0001ee81, 0x0001ee89, 1}, + {0x0001ee8b, 0x0001ee9b, 1}, + {0x0001eea1, 0x0001eea3, 1}, + {0x0001eea5, 0x0001eea9, 1}, + {0x0001eeab, 0x0001eebb, 1}, + {0x0001eef0, 0x0001eef1, 1}, + {0x0001f000, 0x0001f02b, 1}, + {0x0001f030, 0x0001f093, 1}, + {0x0001f0a0, 0x0001f0ae, 1}, + {0x0001f0b1, 0x0001f0be, 1}, + {0x0001f0c1, 0x0001f0cf, 1}, + {0x0001f0d1, 0x0001f0df, 1}, + {0x0001f100, 0x0001f10a, 1}, + {0x0001f110, 0x0001f12e, 1}, + {0x0001f130, 0x0001f16b, 1}, + {0x0001f170, 0x0001f19a, 1}, + {0x0001f1e6, 0x0001f202, 1}, + {0x0001f210, 0x0001f23a, 1}, + {0x0001f240, 0x0001f248, 1}, + {0x0001f250, 0x0001f251, 1}, + {0x0001f300, 0x0001f320, 1}, + {0x0001f330, 0x0001f335, 1}, + {0x0001f337, 0x0001f37c, 1}, + {0x0001f380, 0x0001f393, 1}, + {0x0001f3a0, 0x0001f3c4, 1}, + {0x0001f3c6, 0x0001f3ca, 1}, + {0x0001f3e0, 0x0001f3f0, 1}, + {0x0001f400, 0x0001f43e, 1}, + {0x0001f440, 0x0001f442, 2}, + {0x0001f443, 0x0001f4f7, 1}, + {0x0001f4f9, 0x0001f4fc, 1}, + {0x0001f500, 0x0001f53d, 1}, + {0x0001f540, 0x0001f543, 1}, + {0x0001f550, 0x0001f567, 1}, + {0x0001f5fb, 0x0001f640, 1}, + {0x0001f645, 0x0001f64f, 1}, + {0x0001f680, 0x0001f6c5, 1}, + {0x0001f700, 0x0001f773, 1}, + {0x00020000, 0x0002a6d6, 1}, + {0x0002a700, 0x0002b734, 1}, + {0x0002b740, 0x0002b81d, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// size 4160 bytes (4 KiB) +var assigned6_3_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x0377, 1}, + {0x037a, 0x037e, 1}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x0527, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x058f, 0x0591, 2}, + {0x0592, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x0604, 1}, + {0x0606, 0x061c, 1}, + {0x061e, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x07b1, 1}, + {0x07c0, 0x07fa, 1}, + {0x0800, 0x082d, 1}, + {0x0830, 0x083e, 1}, + {0x0840, 0x085b, 1}, + {0x085e, 0x08a0, 66}, + {0x08a2, 0x08ac, 1}, + {0x08e4, 0x08fe, 1}, + {0x0900, 0x0977, 1}, + {0x0979, 0x097f, 1}, + {0x0981, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fb, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a51, 0x0a59, 8}, + {0x0a5a, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a75, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0af1, 1}, + {0x0b01, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b44, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b63, 1}, + {0x0b66, 0x0b77, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd0, 0x0bd7, 7}, + {0x0be6, 0x0bfa, 1}, + {0x0c01, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c33, 1}, + {0x0c35, 0x0c39, 1}, + {0x0c3d, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c58, 0x0c59, 1}, + {0x0c60, 0x0c63, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c78, 0x0c7f, 1}, + {0x0c82, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce3, 1}, + {0x0ce6, 0x0cef, 1}, + {0x0cf1, 0x0cf2, 1}, + {0x0d02, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d3a, 1}, + {0x0d3d, 0x0d44, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4e, 1}, + {0x0d57, 0x0d60, 9}, + {0x0d61, 0x0d63, 1}, + {0x0d66, 0x0d75, 1}, + {0x0d79, 0x0d7f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edf, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6c, 1}, + {0x0f71, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fce, 0x0fda, 1}, + {0x1000, 0x10c5, 1}, + {0x10c7, 0x10cd, 6}, + {0x10d0, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135d, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f4, 1}, + {0x1400, 0x169c, 1}, + {0x16a0, 0x16f0, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18aa, 1}, + {0x18b0, 0x18f5, 1}, + {0x1900, 0x191c, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19ab, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19da, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a5e, 1}, + {0x1a60, 0x1a7c, 1}, + {0x1a7f, 0x1a89, 1}, + {0x1a90, 0x1a99, 1}, + {0x1aa0, 0x1aad, 1}, + {0x1b00, 0x1b4b, 1}, + {0x1b50, 0x1b7c, 1}, + {0x1b80, 0x1bf3, 1}, + {0x1bfc, 0x1c37, 1}, + {0x1c3b, 0x1c49, 1}, + {0x1c4d, 0x1c7f, 1}, + {0x1cc0, 0x1cc7, 1}, + {0x1cd0, 0x1cf6, 1}, + {0x1d00, 0x1de6, 1}, + {0x1dfc, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2064, 1}, + {0x2066, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x209c, 1}, + {0x20a0, 0x20ba, 1}, + {0x20d0, 0x20f0, 1}, + {0x2100, 0x2189, 1}, + {0x2190, 0x23f3, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x26ff, 1}, + {0x2701, 0x2b4c, 1}, + {0x2b50, 0x2b59, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c60, 0x2cf3, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d27, 0x2d2d, 6}, + {0x2d30, 0x2d67, 1}, + {0x2d6f, 0x2d70, 1}, + {0x2d7f, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2de0, 0x2e3b, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312d, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31ba, 1}, + {0x31c0, 0x31e3, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fcc, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa4d0, 0xa62b, 1}, + {0xa640, 0xa697, 1}, + {0xa69f, 0xa6f7, 1}, + {0xa700, 0xa78e, 1}, + {0xa790, 0xa793, 1}, + {0xa7a0, 0xa7aa, 1}, + {0xa7f8, 0xa82b, 1}, + {0xa830, 0xa839, 1}, + {0xa840, 0xa877, 1}, + {0xa880, 0xa8c4, 1}, + {0xa8ce, 0xa8d9, 1}, + {0xa8e0, 0xa8fb, 1}, + {0xa900, 0xa953, 1}, + {0xa95f, 0xa97c, 1}, + {0xa980, 0xa9cd, 1}, + {0xa9cf, 0xa9d9, 1}, + {0xa9de, 0xa9df, 1}, + {0xaa00, 0xaa36, 1}, + {0xaa40, 0xaa4d, 1}, + {0xaa50, 0xaa59, 1}, + {0xaa5c, 0xaa7b, 1}, + {0xaa80, 0xaac2, 1}, + {0xaadb, 0xaaf6, 1}, + {0xab01, 0xab06, 1}, + {0xab09, 0xab0e, 1}, + {0xab11, 0xab16, 1}, + {0xab20, 0xab26, 1}, + {0xab28, 0xab2e, 1}, + {0xabc0, 0xabed, 1}, + {0xabf0, 0xabf9, 1}, + {0xac00, 0xd7a3, 1}, + {0xd7b0, 0xd7c6, 1}, + {0xd7cb, 0xd7fb, 1}, + {0xd800, 0xfa6d, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbc1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe26, 1}, + {0xfe30, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018a, 1}, + {0x00010190, 0x0001019b, 1}, + {0x000101d0, 0x000101fd, 1}, + {0x00010280, 0x0001029c, 1}, + {0x000102a0, 0x000102d0, 1}, + {0x00010300, 0x0001031e, 1}, + {0x00010320, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010840, 0x00010855, 1}, + {0x00010857, 0x0001085f, 1}, + {0x00010900, 0x0001091b, 1}, + {0x0001091f, 0x00010939, 1}, + {0x0001093f, 0x00010980, 65}, + {0x00010981, 0x000109b7, 1}, + {0x000109be, 0x000109bf, 1}, + {0x00010a00, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x00010a60, 0x00010a7f, 1}, + {0x00010b00, 0x00010b35, 1}, + {0x00010b39, 0x00010b55, 1}, + {0x00010b58, 0x00010b72, 1}, + {0x00010b78, 0x00010b7f, 1}, + {0x00010c00, 0x00010c48, 1}, + {0x00010e60, 0x00010e7e, 1}, + {0x00011000, 0x0001104d, 1}, + {0x00011052, 0x0001106f, 1}, + {0x00011080, 0x000110c1, 1}, + {0x000110d0, 0x000110e8, 1}, + {0x000110f0, 0x000110f9, 1}, + {0x00011100, 0x00011134, 1}, + {0x00011136, 0x00011143, 1}, + {0x00011180, 0x000111c8, 1}, + {0x000111d0, 0x000111d9, 1}, + {0x00011680, 0x000116b7, 1}, + {0x000116c0, 0x000116c9, 1}, + {0x00012000, 0x0001236e, 1}, + {0x00012400, 0x00012462, 1}, + {0x00012470, 0x00012473, 1}, + {0x00013000, 0x0001342e, 1}, + {0x00016800, 0x00016a38, 1}, + {0x00016f00, 0x00016f44, 1}, + {0x00016f50, 0x00016f7e, 1}, + {0x00016f8f, 0x00016f9f, 1}, + {0x0001b000, 0x0001b001, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d129, 0x0001d1dd, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d360, 0x0001d371, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7cb, 1}, + {0x0001d7ce, 0x0001d7ff, 1}, + {0x0001ee00, 0x0001ee03, 1}, + {0x0001ee05, 0x0001ee1f, 1}, + {0x0001ee21, 0x0001ee22, 1}, + {0x0001ee24, 0x0001ee27, 3}, + {0x0001ee29, 0x0001ee32, 1}, + {0x0001ee34, 0x0001ee37, 1}, + {0x0001ee39, 0x0001ee3b, 2}, + {0x0001ee42, 0x0001ee47, 5}, + {0x0001ee49, 0x0001ee4d, 2}, + {0x0001ee4e, 0x0001ee4f, 1}, + {0x0001ee51, 0x0001ee52, 1}, + {0x0001ee54, 0x0001ee57, 3}, + {0x0001ee59, 0x0001ee61, 2}, + {0x0001ee62, 0x0001ee64, 2}, + {0x0001ee67, 0x0001ee6a, 1}, + {0x0001ee6c, 0x0001ee72, 1}, + {0x0001ee74, 0x0001ee77, 1}, + {0x0001ee79, 0x0001ee7c, 1}, + {0x0001ee7e, 0x0001ee80, 2}, + {0x0001ee81, 0x0001ee89, 1}, + {0x0001ee8b, 0x0001ee9b, 1}, + {0x0001eea1, 0x0001eea3, 1}, + {0x0001eea5, 0x0001eea9, 1}, + {0x0001eeab, 0x0001eebb, 1}, + {0x0001eef0, 0x0001eef1, 1}, + {0x0001f000, 0x0001f02b, 1}, + {0x0001f030, 0x0001f093, 1}, + {0x0001f0a0, 0x0001f0ae, 1}, + {0x0001f0b1, 0x0001f0be, 1}, + {0x0001f0c1, 0x0001f0cf, 1}, + {0x0001f0d1, 0x0001f0df, 1}, + {0x0001f100, 0x0001f10a, 1}, + {0x0001f110, 0x0001f12e, 1}, + {0x0001f130, 0x0001f16b, 1}, + {0x0001f170, 0x0001f19a, 1}, + {0x0001f1e6, 0x0001f202, 1}, + {0x0001f210, 0x0001f23a, 1}, + {0x0001f240, 0x0001f248, 1}, + {0x0001f250, 0x0001f251, 1}, + {0x0001f300, 0x0001f320, 1}, + {0x0001f330, 0x0001f335, 1}, + {0x0001f337, 0x0001f37c, 1}, + {0x0001f380, 0x0001f393, 1}, + {0x0001f3a0, 0x0001f3c4, 1}, + {0x0001f3c6, 0x0001f3ca, 1}, + {0x0001f3e0, 0x0001f3f0, 1}, + {0x0001f400, 0x0001f43e, 1}, + {0x0001f440, 0x0001f442, 2}, + {0x0001f443, 0x0001f4f7, 1}, + {0x0001f4f9, 0x0001f4fc, 1}, + {0x0001f500, 0x0001f53d, 1}, + {0x0001f540, 0x0001f543, 1}, + {0x0001f550, 0x0001f567, 1}, + {0x0001f5fb, 0x0001f640, 1}, + {0x0001f645, 0x0001f64f, 1}, + {0x0001f680, 0x0001f6c5, 1}, + {0x0001f700, 0x0001f773, 1}, + {0x00020000, 0x0002a6d6, 1}, + {0x0002a700, 0x0002b734, 1}, + {0x0002b740, 0x0002b81d, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// size 3812 bytes (3 KiB) +var assigned6_0_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x0377, 1}, + {0x037a, 0x037e, 1}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x0527, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x0591, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x0603, 1}, + {0x0606, 0x061b, 1}, + {0x061e, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x07b1, 1}, + {0x07c0, 0x07fa, 1}, + {0x0800, 0x082d, 1}, + {0x0830, 0x083e, 1}, + {0x0840, 0x085b, 1}, + {0x085e, 0x0900, 162}, + {0x0901, 0x0977, 1}, + {0x0979, 0x097f, 1}, + {0x0981, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fb, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a51, 0x0a59, 8}, + {0x0a5a, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a75, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0aef, 1}, + {0x0af1, 0x0b01, 16}, + {0x0b02, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b44, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b63, 1}, + {0x0b66, 0x0b77, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd0, 0x0bd7, 7}, + {0x0be6, 0x0bfa, 1}, + {0x0c01, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c33, 1}, + {0x0c35, 0x0c39, 1}, + {0x0c3d, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c58, 0x0c59, 1}, + {0x0c60, 0x0c63, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c78, 0x0c7f, 1}, + {0x0c82, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce3, 1}, + {0x0ce6, 0x0cef, 1}, + {0x0cf1, 0x0cf2, 1}, + {0x0d02, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d3a, 1}, + {0x0d3d, 0x0d44, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4e, 1}, + {0x0d57, 0x0d60, 9}, + {0x0d61, 0x0d63, 1}, + {0x0d66, 0x0d75, 1}, + {0x0d79, 0x0d7f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edd, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6c, 1}, + {0x0f71, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fce, 0x0fda, 1}, + {0x1000, 0x10c5, 1}, + {0x10d0, 0x10fc, 1}, + {0x1100, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135d, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f4, 1}, + {0x1400, 0x169c, 1}, + {0x16a0, 0x16f0, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18aa, 1}, + {0x18b0, 0x18f5, 1}, + {0x1900, 0x191c, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19ab, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19da, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a5e, 1}, + {0x1a60, 0x1a7c, 1}, + {0x1a7f, 0x1a89, 1}, + {0x1a90, 0x1a99, 1}, + {0x1aa0, 0x1aad, 1}, + {0x1b00, 0x1b4b, 1}, + {0x1b50, 0x1b7c, 1}, + {0x1b80, 0x1baa, 1}, + {0x1bae, 0x1bb9, 1}, + {0x1bc0, 0x1bf3, 1}, + {0x1bfc, 0x1c37, 1}, + {0x1c3b, 0x1c49, 1}, + {0x1c4d, 0x1c7f, 1}, + {0x1cd0, 0x1cf2, 1}, + {0x1d00, 0x1de6, 1}, + {0x1dfc, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2064, 1}, + {0x206a, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x209c, 1}, + {0x20a0, 0x20b9, 1}, + {0x20d0, 0x20f0, 1}, + {0x2100, 0x2189, 1}, + {0x2190, 0x23f3, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x26ff, 1}, + {0x2701, 0x27ca, 1}, + {0x27cc, 0x27ce, 2}, + {0x27cf, 0x2b4c, 1}, + {0x2b50, 0x2b59, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c60, 0x2cf1, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d30, 0x2d65, 1}, + {0x2d6f, 0x2d70, 1}, + {0x2d7f, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2de0, 0x2e31, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312d, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31ba, 1}, + {0x31c0, 0x31e3, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fcb, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa4d0, 0xa62b, 1}, + {0xa640, 0xa673, 1}, + {0xa67c, 0xa697, 1}, + {0xa6a0, 0xa6f7, 1}, + {0xa700, 0xa78e, 1}, + {0xa790, 0xa791, 1}, + {0xa7a0, 0xa7a9, 1}, + {0xa7fa, 0xa82b, 1}, + {0xa830, 0xa839, 1}, + {0xa840, 0xa877, 1}, + {0xa880, 0xa8c4, 1}, + {0xa8ce, 0xa8d9, 1}, + {0xa8e0, 0xa8fb, 1}, + {0xa900, 0xa953, 1}, + {0xa95f, 0xa97c, 1}, + {0xa980, 0xa9cd, 1}, + {0xa9cf, 0xa9d9, 1}, + {0xa9de, 0xa9df, 1}, + {0xaa00, 0xaa36, 1}, + {0xaa40, 0xaa4d, 1}, + {0xaa50, 0xaa59, 1}, + {0xaa5c, 0xaa7b, 1}, + {0xaa80, 0xaac2, 1}, + {0xaadb, 0xaadf, 1}, + {0xab01, 0xab06, 1}, + {0xab09, 0xab0e, 1}, + {0xab11, 0xab16, 1}, + {0xab20, 0xab26, 1}, + {0xab28, 0xab2e, 1}, + {0xabc0, 0xabed, 1}, + {0xabf0, 0xabf9, 1}, + {0xac00, 0xd7a3, 1}, + {0xd7b0, 0xd7c6, 1}, + {0xd7cb, 0xd7fb, 1}, + {0xd800, 0xfa2d, 1}, + {0xfa30, 0xfa6d, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbc1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe26, 1}, + {0xfe30, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018a, 1}, + {0x00010190, 0x0001019b, 1}, + {0x000101d0, 0x000101fd, 1}, + {0x00010280, 0x0001029c, 1}, + {0x000102a0, 0x000102d0, 1}, + {0x00010300, 0x0001031e, 1}, + {0x00010320, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010840, 0x00010855, 1}, + {0x00010857, 0x0001085f, 1}, + {0x00010900, 0x0001091b, 1}, + {0x0001091f, 0x00010939, 1}, + {0x0001093f, 0x00010a00, 193}, + {0x00010a01, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x00010a60, 0x00010a7f, 1}, + {0x00010b00, 0x00010b35, 1}, + {0x00010b39, 0x00010b55, 1}, + {0x00010b58, 0x00010b72, 1}, + {0x00010b78, 0x00010b7f, 1}, + {0x00010c00, 0x00010c48, 1}, + {0x00010e60, 0x00010e7e, 1}, + {0x00011000, 0x0001104d, 1}, + {0x00011052, 0x0001106f, 1}, + {0x00011080, 0x000110c1, 1}, + {0x00012000, 0x0001236e, 1}, + {0x00012400, 0x00012462, 1}, + {0x00012470, 0x00012473, 1}, + {0x00013000, 0x0001342e, 1}, + {0x00016800, 0x00016a38, 1}, + {0x0001b000, 0x0001b001, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d129, 0x0001d1dd, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d360, 0x0001d371, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7cb, 1}, + {0x0001d7ce, 0x0001d7ff, 1}, + {0x0001f000, 0x0001f02b, 1}, + {0x0001f030, 0x0001f093, 1}, + {0x0001f0a0, 0x0001f0ae, 1}, + {0x0001f0b1, 0x0001f0be, 1}, + {0x0001f0c1, 0x0001f0cf, 1}, + {0x0001f0d1, 0x0001f0df, 1}, + {0x0001f100, 0x0001f10a, 1}, + {0x0001f110, 0x0001f12e, 1}, + {0x0001f130, 0x0001f169, 1}, + {0x0001f170, 0x0001f19a, 1}, + {0x0001f1e6, 0x0001f202, 1}, + {0x0001f210, 0x0001f23a, 1}, + {0x0001f240, 0x0001f248, 1}, + {0x0001f250, 0x0001f251, 1}, + {0x0001f300, 0x0001f320, 1}, + {0x0001f330, 0x0001f335, 1}, + {0x0001f337, 0x0001f37c, 1}, + {0x0001f380, 0x0001f393, 1}, + {0x0001f3a0, 0x0001f3c4, 1}, + {0x0001f3c6, 0x0001f3ca, 1}, + {0x0001f3e0, 0x0001f3f0, 1}, + {0x0001f400, 0x0001f43e, 1}, + {0x0001f440, 0x0001f442, 2}, + {0x0001f443, 0x0001f4f7, 1}, + {0x0001f4f9, 0x0001f4fc, 1}, + {0x0001f500, 0x0001f53d, 1}, + {0x0001f550, 0x0001f567, 1}, + {0x0001f5fb, 0x0001f5ff, 1}, + {0x0001f601, 0x0001f610, 1}, + {0x0001f612, 0x0001f614, 1}, + {0x0001f616, 0x0001f61c, 2}, + {0x0001f61d, 0x0001f61e, 1}, + {0x0001f620, 0x0001f625, 1}, + {0x0001f628, 0x0001f62b, 1}, + {0x0001f62d, 0x0001f630, 3}, + {0x0001f631, 0x0001f633, 1}, + {0x0001f635, 0x0001f640, 1}, + {0x0001f645, 0x0001f64f, 1}, + {0x0001f680, 0x0001f6c5, 1}, + {0x0001f700, 0x0001f773, 1}, + {0x00020000, 0x0002a6d6, 1}, + {0x0002a700, 0x0002b734, 1}, + {0x0002b740, 0x0002b81d, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// size 4898 bytes (4 KiB) +var assigned7_0_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x0377, 1}, + {0x037a, 0x037f, 1}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x052f, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x058d, 0x058f, 1}, + {0x0591, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x061c, 1}, + {0x061e, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x07b1, 1}, + {0x07c0, 0x07fa, 1}, + {0x0800, 0x082d, 1}, + {0x0830, 0x083e, 1}, + {0x0840, 0x085b, 1}, + {0x085e, 0x08a0, 66}, + {0x08a1, 0x08b2, 1}, + {0x08e4, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fb, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a51, 0x0a59, 8}, + {0x0a5a, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a75, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0af1, 1}, + {0x0b01, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b44, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b63, 1}, + {0x0b66, 0x0b77, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd0, 0x0bd7, 7}, + {0x0be6, 0x0bfa, 1}, + {0x0c00, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c39, 1}, + {0x0c3d, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c58, 0x0c59, 1}, + {0x0c60, 0x0c63, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c78, 0x0c7f, 1}, + {0x0c81, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce3, 1}, + {0x0ce6, 0x0cef, 1}, + {0x0cf1, 0x0cf2, 1}, + {0x0d01, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d3a, 1}, + {0x0d3d, 0x0d44, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4e, 1}, + {0x0d57, 0x0d60, 9}, + {0x0d61, 0x0d63, 1}, + {0x0d66, 0x0d75, 1}, + {0x0d79, 0x0d7f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0de6, 0x0def, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edf, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6c, 1}, + {0x0f71, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fce, 0x0fda, 1}, + {0x1000, 0x10c5, 1}, + {0x10c7, 0x10cd, 6}, + {0x10d0, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135d, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f4, 1}, + {0x1400, 0x169c, 1}, + {0x16a0, 0x16f8, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18aa, 1}, + {0x18b0, 0x18f5, 1}, + {0x1900, 0x191e, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19ab, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19da, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a5e, 1}, + {0x1a60, 0x1a7c, 1}, + {0x1a7f, 0x1a89, 1}, + {0x1a90, 0x1a99, 1}, + {0x1aa0, 0x1aad, 1}, + {0x1ab0, 0x1abe, 1}, + {0x1b00, 0x1b4b, 1}, + {0x1b50, 0x1b7c, 1}, + {0x1b80, 0x1bf3, 1}, + {0x1bfc, 0x1c37, 1}, + {0x1c3b, 0x1c49, 1}, + {0x1c4d, 0x1c7f, 1}, + {0x1cc0, 0x1cc7, 1}, + {0x1cd0, 0x1cf6, 1}, + {0x1cf8, 0x1cf9, 1}, + {0x1d00, 0x1df5, 1}, + {0x1dfc, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2064, 1}, + {0x2066, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x209c, 1}, + {0x20a0, 0x20bd, 1}, + {0x20d0, 0x20f0, 1}, + {0x2100, 0x2189, 1}, + {0x2190, 0x23fa, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x2b73, 1}, + {0x2b76, 0x2b95, 1}, + {0x2b98, 0x2bb9, 1}, + {0x2bbd, 0x2bc8, 1}, + {0x2bca, 0x2bd1, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c60, 0x2cf3, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d27, 0x2d2d, 6}, + {0x2d30, 0x2d67, 1}, + {0x2d6f, 0x2d70, 1}, + {0x2d7f, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2de0, 0x2e42, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312d, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31ba, 1}, + {0x31c0, 0x31e3, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fcc, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa4d0, 0xa62b, 1}, + {0xa640, 0xa69d, 1}, + {0xa69f, 0xa6f7, 1}, + {0xa700, 0xa78e, 1}, + {0xa790, 0xa7ad, 1}, + {0xa7b0, 0xa7b1, 1}, + {0xa7f7, 0xa82b, 1}, + {0xa830, 0xa839, 1}, + {0xa840, 0xa877, 1}, + {0xa880, 0xa8c4, 1}, + {0xa8ce, 0xa8d9, 1}, + {0xa8e0, 0xa8fb, 1}, + {0xa900, 0xa953, 1}, + {0xa95f, 0xa97c, 1}, + {0xa980, 0xa9cd, 1}, + {0xa9cf, 0xa9d9, 1}, + {0xa9de, 0xa9fe, 1}, + {0xaa00, 0xaa36, 1}, + {0xaa40, 0xaa4d, 1}, + {0xaa50, 0xaa59, 1}, + {0xaa5c, 0xaac2, 1}, + {0xaadb, 0xaaf6, 1}, + {0xab01, 0xab06, 1}, + {0xab09, 0xab0e, 1}, + {0xab11, 0xab16, 1}, + {0xab20, 0xab26, 1}, + {0xab28, 0xab2e, 1}, + {0xab30, 0xab5f, 1}, + {0xab64, 0xab65, 1}, + {0xabc0, 0xabed, 1}, + {0xabf0, 0xabf9, 1}, + {0xac00, 0xd7a3, 1}, + {0xd7b0, 0xd7c6, 1}, + {0xd7cb, 0xd7fb, 1}, + {0xd800, 0xfa6d, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbc1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe2d, 1}, + {0xfe30, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018c, 1}, + {0x00010190, 0x0001019b, 1}, + {0x000101a0, 0x000101d0, 48}, + {0x000101d1, 0x000101fd, 1}, + {0x00010280, 0x0001029c, 1}, + {0x000102a0, 0x000102d0, 1}, + {0x000102e0, 0x000102fb, 1}, + {0x00010300, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010350, 0x0001037a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x00010500, 0x00010527, 1}, + {0x00010530, 0x00010563, 1}, + {0x0001056f, 0x00010600, 145}, + {0x00010601, 0x00010736, 1}, + {0x00010740, 0x00010755, 1}, + {0x00010760, 0x00010767, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010840, 0x00010855, 1}, + {0x00010857, 0x0001089e, 1}, + {0x000108a7, 0x000108af, 1}, + {0x00010900, 0x0001091b, 1}, + {0x0001091f, 0x00010939, 1}, + {0x0001093f, 0x00010980, 65}, + {0x00010981, 0x000109b7, 1}, + {0x000109be, 0x000109bf, 1}, + {0x00010a00, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x00010a60, 0x00010a9f, 1}, + {0x00010ac0, 0x00010ae6, 1}, + {0x00010aeb, 0x00010af6, 1}, + {0x00010b00, 0x00010b35, 1}, + {0x00010b39, 0x00010b55, 1}, + {0x00010b58, 0x00010b72, 1}, + {0x00010b78, 0x00010b91, 1}, + {0x00010b99, 0x00010b9c, 1}, + {0x00010ba9, 0x00010baf, 1}, + {0x00010c00, 0x00010c48, 1}, + {0x00010e60, 0x00010e7e, 1}, + {0x00011000, 0x0001104d, 1}, + {0x00011052, 0x0001106f, 1}, + {0x0001107f, 0x000110c1, 1}, + {0x000110d0, 0x000110e8, 1}, + {0x000110f0, 0x000110f9, 1}, + {0x00011100, 0x00011134, 1}, + {0x00011136, 0x00011143, 1}, + {0x00011150, 0x00011176, 1}, + {0x00011180, 0x000111c8, 1}, + {0x000111cd, 0x000111d0, 3}, + {0x000111d1, 0x000111da, 1}, + {0x000111e1, 0x000111f4, 1}, + {0x00011200, 0x00011211, 1}, + {0x00011213, 0x0001123d, 1}, + {0x000112b0, 0x000112ea, 1}, + {0x000112f0, 0x000112f9, 1}, + {0x00011301, 0x00011303, 1}, + {0x00011305, 0x0001130c, 1}, + {0x0001130f, 0x00011310, 1}, + {0x00011313, 0x00011328, 1}, + {0x0001132a, 0x00011330, 1}, + {0x00011332, 0x00011333, 1}, + {0x00011335, 0x00011339, 1}, + {0x0001133c, 0x00011344, 1}, + {0x00011347, 0x00011348, 1}, + {0x0001134b, 0x0001134d, 1}, + {0x00011357, 0x0001135d, 6}, + {0x0001135e, 0x00011363, 1}, + {0x00011366, 0x0001136c, 1}, + {0x00011370, 0x00011374, 1}, + {0x00011480, 0x000114c7, 1}, + {0x000114d0, 0x000114d9, 1}, + {0x00011580, 0x000115b5, 1}, + {0x000115b8, 0x000115c9, 1}, + {0x00011600, 0x00011644, 1}, + {0x00011650, 0x00011659, 1}, + {0x00011680, 0x000116b7, 1}, + {0x000116c0, 0x000116c9, 1}, + {0x000118a0, 0x000118f2, 1}, + {0x000118ff, 0x00011ac0, 449}, + {0x00011ac1, 0x00011af8, 1}, + {0x00012000, 0x00012398, 1}, + {0x00012400, 0x0001246e, 1}, + {0x00012470, 0x00012474, 1}, + {0x00013000, 0x0001342e, 1}, + {0x00016800, 0x00016a38, 1}, + {0x00016a40, 0x00016a5e, 1}, + {0x00016a60, 0x00016a69, 1}, + {0x00016a6e, 0x00016a6f, 1}, + {0x00016ad0, 0x00016aed, 1}, + {0x00016af0, 0x00016af5, 1}, + {0x00016b00, 0x00016b45, 1}, + {0x00016b50, 0x00016b59, 1}, + {0x00016b5b, 0x00016b61, 1}, + {0x00016b63, 0x00016b77, 1}, + {0x00016b7d, 0x00016b8f, 1}, + {0x00016f00, 0x00016f44, 1}, + {0x00016f50, 0x00016f7e, 1}, + {0x00016f8f, 0x00016f9f, 1}, + {0x0001b000, 0x0001b001, 1}, + {0x0001bc00, 0x0001bc6a, 1}, + {0x0001bc70, 0x0001bc7c, 1}, + {0x0001bc80, 0x0001bc88, 1}, + {0x0001bc90, 0x0001bc99, 1}, + {0x0001bc9c, 0x0001bca3, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d129, 0x0001d1dd, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d360, 0x0001d371, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7cb, 1}, + {0x0001d7ce, 0x0001d7ff, 1}, + {0x0001e800, 0x0001e8c4, 1}, + {0x0001e8c7, 0x0001e8d6, 1}, + {0x0001ee00, 0x0001ee03, 1}, + {0x0001ee05, 0x0001ee1f, 1}, + {0x0001ee21, 0x0001ee22, 1}, + {0x0001ee24, 0x0001ee27, 3}, + {0x0001ee29, 0x0001ee32, 1}, + {0x0001ee34, 0x0001ee37, 1}, + {0x0001ee39, 0x0001ee3b, 2}, + {0x0001ee42, 0x0001ee47, 5}, + {0x0001ee49, 0x0001ee4d, 2}, + {0x0001ee4e, 0x0001ee4f, 1}, + {0x0001ee51, 0x0001ee52, 1}, + {0x0001ee54, 0x0001ee57, 3}, + {0x0001ee59, 0x0001ee61, 2}, + {0x0001ee62, 0x0001ee64, 2}, + {0x0001ee67, 0x0001ee6a, 1}, + {0x0001ee6c, 0x0001ee72, 1}, + {0x0001ee74, 0x0001ee77, 1}, + {0x0001ee79, 0x0001ee7c, 1}, + {0x0001ee7e, 0x0001ee80, 2}, + {0x0001ee81, 0x0001ee89, 1}, + {0x0001ee8b, 0x0001ee9b, 1}, + {0x0001eea1, 0x0001eea3, 1}, + {0x0001eea5, 0x0001eea9, 1}, + {0x0001eeab, 0x0001eebb, 1}, + {0x0001eef0, 0x0001eef1, 1}, + {0x0001f000, 0x0001f02b, 1}, + {0x0001f030, 0x0001f093, 1}, + {0x0001f0a0, 0x0001f0ae, 1}, + {0x0001f0b1, 0x0001f0bf, 1}, + {0x0001f0c1, 0x0001f0cf, 1}, + {0x0001f0d1, 0x0001f0f5, 1}, + {0x0001f100, 0x0001f10c, 1}, + {0x0001f110, 0x0001f12e, 1}, + {0x0001f130, 0x0001f16b, 1}, + {0x0001f170, 0x0001f19a, 1}, + {0x0001f1e6, 0x0001f202, 1}, + {0x0001f210, 0x0001f23a, 1}, + {0x0001f240, 0x0001f248, 1}, + {0x0001f250, 0x0001f251, 1}, + {0x0001f300, 0x0001f32c, 1}, + {0x0001f330, 0x0001f37d, 1}, + {0x0001f380, 0x0001f3ce, 1}, + {0x0001f3d4, 0x0001f3f7, 1}, + {0x0001f400, 0x0001f4fe, 1}, + {0x0001f500, 0x0001f54a, 1}, + {0x0001f550, 0x0001f579, 1}, + {0x0001f57b, 0x0001f5a3, 1}, + {0x0001f5a5, 0x0001f642, 1}, + {0x0001f645, 0x0001f6cf, 1}, + {0x0001f6e0, 0x0001f6ec, 1}, + {0x0001f6f0, 0x0001f6f3, 1}, + {0x0001f700, 0x0001f773, 1}, + {0x0001f780, 0x0001f7d4, 1}, + {0x0001f800, 0x0001f80b, 1}, + {0x0001f810, 0x0001f847, 1}, + {0x0001f850, 0x0001f859, 1}, + {0x0001f860, 0x0001f887, 1}, + {0x0001f890, 0x0001f8ad, 1}, + {0x00020000, 0x0002a6d6, 1}, + {0x0002a700, 0x0002b734, 1}, + {0x0002b740, 0x0002b81d, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// size 5048 bytes (4 KiB) +var assigned8_0_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x0377, 1}, + {0x037a, 0x037f, 1}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x052f, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x058d, 0x058f, 1}, + {0x0591, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x061c, 1}, + {0x061e, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x07b1, 1}, + {0x07c0, 0x07fa, 1}, + {0x0800, 0x082d, 1}, + {0x0830, 0x083e, 1}, + {0x0840, 0x085b, 1}, + {0x085e, 0x08a0, 66}, + {0x08a1, 0x08b4, 1}, + {0x08e3, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fb, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a51, 0x0a59, 8}, + {0x0a5a, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a75, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0af1, 1}, + {0x0af9, 0x0b01, 8}, + {0x0b02, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b44, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b63, 1}, + {0x0b66, 0x0b77, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd0, 0x0bd7, 7}, + {0x0be6, 0x0bfa, 1}, + {0x0c00, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c39, 1}, + {0x0c3d, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c58, 0x0c5a, 1}, + {0x0c60, 0x0c63, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c78, 0x0c7f, 1}, + {0x0c81, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce3, 1}, + {0x0ce6, 0x0cef, 1}, + {0x0cf1, 0x0cf2, 1}, + {0x0d01, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d3a, 1}, + {0x0d3d, 0x0d44, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4e, 1}, + {0x0d57, 0x0d5f, 8}, + {0x0d60, 0x0d63, 1}, + {0x0d66, 0x0d75, 1}, + {0x0d79, 0x0d7f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0de6, 0x0def, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edf, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6c, 1}, + {0x0f71, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fce, 0x0fda, 1}, + {0x1000, 0x10c5, 1}, + {0x10c7, 0x10cd, 6}, + {0x10d0, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135d, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f5, 1}, + {0x13f8, 0x13fd, 1}, + {0x1400, 0x169c, 1}, + {0x16a0, 0x16f8, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18aa, 1}, + {0x18b0, 0x18f5, 1}, + {0x1900, 0x191e, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19ab, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19da, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a5e, 1}, + {0x1a60, 0x1a7c, 1}, + {0x1a7f, 0x1a89, 1}, + {0x1a90, 0x1a99, 1}, + {0x1aa0, 0x1aad, 1}, + {0x1ab0, 0x1abe, 1}, + {0x1b00, 0x1b4b, 1}, + {0x1b50, 0x1b7c, 1}, + {0x1b80, 0x1bf3, 1}, + {0x1bfc, 0x1c37, 1}, + {0x1c3b, 0x1c49, 1}, + {0x1c4d, 0x1c7f, 1}, + {0x1cc0, 0x1cc7, 1}, + {0x1cd0, 0x1cf6, 1}, + {0x1cf8, 0x1cf9, 1}, + {0x1d00, 0x1df5, 1}, + {0x1dfc, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2064, 1}, + {0x2066, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x209c, 1}, + {0x20a0, 0x20be, 1}, + {0x20d0, 0x20f0, 1}, + {0x2100, 0x218b, 1}, + {0x2190, 0x23fa, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x2b73, 1}, + {0x2b76, 0x2b95, 1}, + {0x2b98, 0x2bb9, 1}, + {0x2bbd, 0x2bc8, 1}, + {0x2bca, 0x2bd1, 1}, + {0x2bec, 0x2bef, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c60, 0x2cf3, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d27, 0x2d2d, 6}, + {0x2d30, 0x2d67, 1}, + {0x2d6f, 0x2d70, 1}, + {0x2d7f, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2de0, 0x2e42, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312d, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31ba, 1}, + {0x31c0, 0x31e3, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fd5, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa4d0, 0xa62b, 1}, + {0xa640, 0xa6f7, 1}, + {0xa700, 0xa7ad, 1}, + {0xa7b0, 0xa7b7, 1}, + {0xa7f7, 0xa82b, 1}, + {0xa830, 0xa839, 1}, + {0xa840, 0xa877, 1}, + {0xa880, 0xa8c4, 1}, + {0xa8ce, 0xa8d9, 1}, + {0xa8e0, 0xa8fd, 1}, + {0xa900, 0xa953, 1}, + {0xa95f, 0xa97c, 1}, + {0xa980, 0xa9cd, 1}, + {0xa9cf, 0xa9d9, 1}, + {0xa9de, 0xa9fe, 1}, + {0xaa00, 0xaa36, 1}, + {0xaa40, 0xaa4d, 1}, + {0xaa50, 0xaa59, 1}, + {0xaa5c, 0xaac2, 1}, + {0xaadb, 0xaaf6, 1}, + {0xab01, 0xab06, 1}, + {0xab09, 0xab0e, 1}, + {0xab11, 0xab16, 1}, + {0xab20, 0xab26, 1}, + {0xab28, 0xab2e, 1}, + {0xab30, 0xab65, 1}, + {0xab70, 0xabed, 1}, + {0xabf0, 0xabf9, 1}, + {0xac00, 0xd7a3, 1}, + {0xd7b0, 0xd7c6, 1}, + {0xd7cb, 0xd7fb, 1}, + {0xd800, 0xfa6d, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbc1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018c, 1}, + {0x00010190, 0x0001019b, 1}, + {0x000101a0, 0x000101d0, 48}, + {0x000101d1, 0x000101fd, 1}, + {0x00010280, 0x0001029c, 1}, + {0x000102a0, 0x000102d0, 1}, + {0x000102e0, 0x000102fb, 1}, + {0x00010300, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010350, 0x0001037a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x00010500, 0x00010527, 1}, + {0x00010530, 0x00010563, 1}, + {0x0001056f, 0x00010600, 145}, + {0x00010601, 0x00010736, 1}, + {0x00010740, 0x00010755, 1}, + {0x00010760, 0x00010767, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010840, 0x00010855, 1}, + {0x00010857, 0x0001089e, 1}, + {0x000108a7, 0x000108af, 1}, + {0x000108e0, 0x000108f2, 1}, + {0x000108f4, 0x000108f5, 1}, + {0x000108fb, 0x0001091b, 1}, + {0x0001091f, 0x00010939, 1}, + {0x0001093f, 0x00010980, 65}, + {0x00010981, 0x000109b7, 1}, + {0x000109bc, 0x000109cf, 1}, + {0x000109d2, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x00010a60, 0x00010a9f, 1}, + {0x00010ac0, 0x00010ae6, 1}, + {0x00010aeb, 0x00010af6, 1}, + {0x00010b00, 0x00010b35, 1}, + {0x00010b39, 0x00010b55, 1}, + {0x00010b58, 0x00010b72, 1}, + {0x00010b78, 0x00010b91, 1}, + {0x00010b99, 0x00010b9c, 1}, + {0x00010ba9, 0x00010baf, 1}, + {0x00010c00, 0x00010c48, 1}, + {0x00010c80, 0x00010cb2, 1}, + {0x00010cc0, 0x00010cf2, 1}, + {0x00010cfa, 0x00010cff, 1}, + {0x00010e60, 0x00010e7e, 1}, + {0x00011000, 0x0001104d, 1}, + {0x00011052, 0x0001106f, 1}, + {0x0001107f, 0x000110c1, 1}, + {0x000110d0, 0x000110e8, 1}, + {0x000110f0, 0x000110f9, 1}, + {0x00011100, 0x00011134, 1}, + {0x00011136, 0x00011143, 1}, + {0x00011150, 0x00011176, 1}, + {0x00011180, 0x000111cd, 1}, + {0x000111d0, 0x000111df, 1}, + {0x000111e1, 0x000111f4, 1}, + {0x00011200, 0x00011211, 1}, + {0x00011213, 0x0001123d, 1}, + {0x00011280, 0x00011286, 1}, + {0x00011288, 0x0001128a, 2}, + {0x0001128b, 0x0001128d, 1}, + {0x0001128f, 0x0001129d, 1}, + {0x0001129f, 0x000112a9, 1}, + {0x000112b0, 0x000112ea, 1}, + {0x000112f0, 0x000112f9, 1}, + {0x00011300, 0x00011303, 1}, + {0x00011305, 0x0001130c, 1}, + {0x0001130f, 0x00011310, 1}, + {0x00011313, 0x00011328, 1}, + {0x0001132a, 0x00011330, 1}, + {0x00011332, 0x00011333, 1}, + {0x00011335, 0x00011339, 1}, + {0x0001133c, 0x00011344, 1}, + {0x00011347, 0x00011348, 1}, + {0x0001134b, 0x0001134d, 1}, + {0x00011350, 0x00011357, 7}, + {0x0001135d, 0x00011363, 1}, + {0x00011366, 0x0001136c, 1}, + {0x00011370, 0x00011374, 1}, + {0x00011480, 0x000114c7, 1}, + {0x000114d0, 0x000114d9, 1}, + {0x00011580, 0x000115b5, 1}, + {0x000115b8, 0x000115dd, 1}, + {0x00011600, 0x00011644, 1}, + {0x00011650, 0x00011659, 1}, + {0x00011680, 0x000116b7, 1}, + {0x000116c0, 0x000116c9, 1}, + {0x00011700, 0x00011719, 1}, + {0x0001171d, 0x0001172b, 1}, + {0x00011730, 0x0001173f, 1}, + {0x000118a0, 0x000118f2, 1}, + {0x000118ff, 0x00011ac0, 449}, + {0x00011ac1, 0x00011af8, 1}, + {0x00012000, 0x00012399, 1}, + {0x00012400, 0x0001246e, 1}, + {0x00012470, 0x00012474, 1}, + {0x00012480, 0x00012543, 1}, + {0x00013000, 0x0001342e, 1}, + {0x00014400, 0x00014646, 1}, + {0x00016800, 0x00016a38, 1}, + {0x00016a40, 0x00016a5e, 1}, + {0x00016a60, 0x00016a69, 1}, + {0x00016a6e, 0x00016a6f, 1}, + {0x00016ad0, 0x00016aed, 1}, + {0x00016af0, 0x00016af5, 1}, + {0x00016b00, 0x00016b45, 1}, + {0x00016b50, 0x00016b59, 1}, + {0x00016b5b, 0x00016b61, 1}, + {0x00016b63, 0x00016b77, 1}, + {0x00016b7d, 0x00016b8f, 1}, + {0x00016f00, 0x00016f44, 1}, + {0x00016f50, 0x00016f7e, 1}, + {0x00016f8f, 0x00016f9f, 1}, + {0x0001b000, 0x0001b001, 1}, + {0x0001bc00, 0x0001bc6a, 1}, + {0x0001bc70, 0x0001bc7c, 1}, + {0x0001bc80, 0x0001bc88, 1}, + {0x0001bc90, 0x0001bc99, 1}, + {0x0001bc9c, 0x0001bca3, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d129, 0x0001d1e8, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d360, 0x0001d371, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7cb, 1}, + {0x0001d7ce, 0x0001da8b, 1}, + {0x0001da9b, 0x0001da9f, 1}, + {0x0001daa1, 0x0001daaf, 1}, + {0x0001e800, 0x0001e8c4, 1}, + {0x0001e8c7, 0x0001e8d6, 1}, + {0x0001ee00, 0x0001ee03, 1}, + {0x0001ee05, 0x0001ee1f, 1}, + {0x0001ee21, 0x0001ee22, 1}, + {0x0001ee24, 0x0001ee27, 3}, + {0x0001ee29, 0x0001ee32, 1}, + {0x0001ee34, 0x0001ee37, 1}, + {0x0001ee39, 0x0001ee3b, 2}, + {0x0001ee42, 0x0001ee47, 5}, + {0x0001ee49, 0x0001ee4d, 2}, + {0x0001ee4e, 0x0001ee4f, 1}, + {0x0001ee51, 0x0001ee52, 1}, + {0x0001ee54, 0x0001ee57, 3}, + {0x0001ee59, 0x0001ee61, 2}, + {0x0001ee62, 0x0001ee64, 2}, + {0x0001ee67, 0x0001ee6a, 1}, + {0x0001ee6c, 0x0001ee72, 1}, + {0x0001ee74, 0x0001ee77, 1}, + {0x0001ee79, 0x0001ee7c, 1}, + {0x0001ee7e, 0x0001ee80, 2}, + {0x0001ee81, 0x0001ee89, 1}, + {0x0001ee8b, 0x0001ee9b, 1}, + {0x0001eea1, 0x0001eea3, 1}, + {0x0001eea5, 0x0001eea9, 1}, + {0x0001eeab, 0x0001eebb, 1}, + {0x0001eef0, 0x0001eef1, 1}, + {0x0001f000, 0x0001f02b, 1}, + {0x0001f030, 0x0001f093, 1}, + {0x0001f0a0, 0x0001f0ae, 1}, + {0x0001f0b1, 0x0001f0bf, 1}, + {0x0001f0c1, 0x0001f0cf, 1}, + {0x0001f0d1, 0x0001f0f5, 1}, + {0x0001f100, 0x0001f10c, 1}, + {0x0001f110, 0x0001f12e, 1}, + {0x0001f130, 0x0001f16b, 1}, + {0x0001f170, 0x0001f19a, 1}, + {0x0001f1e6, 0x0001f202, 1}, + {0x0001f210, 0x0001f23a, 1}, + {0x0001f240, 0x0001f248, 1}, + {0x0001f250, 0x0001f251, 1}, + {0x0001f300, 0x0001f579, 1}, + {0x0001f57b, 0x0001f5a3, 1}, + {0x0001f5a5, 0x0001f6d0, 1}, + {0x0001f6e0, 0x0001f6ec, 1}, + {0x0001f6f0, 0x0001f6f3, 1}, + {0x0001f700, 0x0001f773, 1}, + {0x0001f780, 0x0001f7d4, 1}, + {0x0001f800, 0x0001f80b, 1}, + {0x0001f810, 0x0001f847, 1}, + {0x0001f850, 0x0001f859, 1}, + {0x0001f860, 0x0001f887, 1}, + {0x0001f890, 0x0001f8ad, 1}, + {0x0001f910, 0x0001f918, 1}, + {0x0001f980, 0x0001f984, 1}, + {0x0001f9c0, 0x00020000, 1600}, + {0x00020001, 0x0002a6d6, 1}, + {0x0002a700, 0x0002b734, 1}, + {0x0002b740, 0x0002b81d, 1}, + {0x0002b820, 0x0002cea1, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// size 5348 bytes (5 KiB) +var assigned9_0_0 = &unicode.RangeTable{ + R16: []unicode.Range16{ + {0x0000, 0x0377, 1}, + {0x037a, 0x037f, 1}, + {0x0384, 0x038a, 1}, + {0x038c, 0x038e, 2}, + {0x038f, 0x03a1, 1}, + {0x03a3, 0x052f, 1}, + {0x0531, 0x0556, 1}, + {0x0559, 0x055f, 1}, + {0x0561, 0x0587, 1}, + {0x0589, 0x058a, 1}, + {0x058d, 0x058f, 1}, + {0x0591, 0x05c7, 1}, + {0x05d0, 0x05ea, 1}, + {0x05f0, 0x05f4, 1}, + {0x0600, 0x061c, 1}, + {0x061e, 0x070d, 1}, + {0x070f, 0x074a, 1}, + {0x074d, 0x07b1, 1}, + {0x07c0, 0x07fa, 1}, + {0x0800, 0x082d, 1}, + {0x0830, 0x083e, 1}, + {0x0840, 0x085b, 1}, + {0x085e, 0x08a0, 66}, + {0x08a1, 0x08b4, 1}, + {0x08b6, 0x08bd, 1}, + {0x08d4, 0x0983, 1}, + {0x0985, 0x098c, 1}, + {0x098f, 0x0990, 1}, + {0x0993, 0x09a8, 1}, + {0x09aa, 0x09b0, 1}, + {0x09b2, 0x09b6, 4}, + {0x09b7, 0x09b9, 1}, + {0x09bc, 0x09c4, 1}, + {0x09c7, 0x09c8, 1}, + {0x09cb, 0x09ce, 1}, + {0x09d7, 0x09dc, 5}, + {0x09dd, 0x09df, 2}, + {0x09e0, 0x09e3, 1}, + {0x09e6, 0x09fb, 1}, + {0x0a01, 0x0a03, 1}, + {0x0a05, 0x0a0a, 1}, + {0x0a0f, 0x0a10, 1}, + {0x0a13, 0x0a28, 1}, + {0x0a2a, 0x0a30, 1}, + {0x0a32, 0x0a33, 1}, + {0x0a35, 0x0a36, 1}, + {0x0a38, 0x0a39, 1}, + {0x0a3c, 0x0a3e, 2}, + {0x0a3f, 0x0a42, 1}, + {0x0a47, 0x0a48, 1}, + {0x0a4b, 0x0a4d, 1}, + {0x0a51, 0x0a59, 8}, + {0x0a5a, 0x0a5c, 1}, + {0x0a5e, 0x0a66, 8}, + {0x0a67, 0x0a75, 1}, + {0x0a81, 0x0a83, 1}, + {0x0a85, 0x0a8d, 1}, + {0x0a8f, 0x0a91, 1}, + {0x0a93, 0x0aa8, 1}, + {0x0aaa, 0x0ab0, 1}, + {0x0ab2, 0x0ab3, 1}, + {0x0ab5, 0x0ab9, 1}, + {0x0abc, 0x0ac5, 1}, + {0x0ac7, 0x0ac9, 1}, + {0x0acb, 0x0acd, 1}, + {0x0ad0, 0x0ae0, 16}, + {0x0ae1, 0x0ae3, 1}, + {0x0ae6, 0x0af1, 1}, + {0x0af9, 0x0b01, 8}, + {0x0b02, 0x0b03, 1}, + {0x0b05, 0x0b0c, 1}, + {0x0b0f, 0x0b10, 1}, + {0x0b13, 0x0b28, 1}, + {0x0b2a, 0x0b30, 1}, + {0x0b32, 0x0b33, 1}, + {0x0b35, 0x0b39, 1}, + {0x0b3c, 0x0b44, 1}, + {0x0b47, 0x0b48, 1}, + {0x0b4b, 0x0b4d, 1}, + {0x0b56, 0x0b57, 1}, + {0x0b5c, 0x0b5d, 1}, + {0x0b5f, 0x0b63, 1}, + {0x0b66, 0x0b77, 1}, + {0x0b82, 0x0b83, 1}, + {0x0b85, 0x0b8a, 1}, + {0x0b8e, 0x0b90, 1}, + {0x0b92, 0x0b95, 1}, + {0x0b99, 0x0b9a, 1}, + {0x0b9c, 0x0b9e, 2}, + {0x0b9f, 0x0ba3, 4}, + {0x0ba4, 0x0ba8, 4}, + {0x0ba9, 0x0baa, 1}, + {0x0bae, 0x0bb9, 1}, + {0x0bbe, 0x0bc2, 1}, + {0x0bc6, 0x0bc8, 1}, + {0x0bca, 0x0bcd, 1}, + {0x0bd0, 0x0bd7, 7}, + {0x0be6, 0x0bfa, 1}, + {0x0c00, 0x0c03, 1}, + {0x0c05, 0x0c0c, 1}, + {0x0c0e, 0x0c10, 1}, + {0x0c12, 0x0c28, 1}, + {0x0c2a, 0x0c39, 1}, + {0x0c3d, 0x0c44, 1}, + {0x0c46, 0x0c48, 1}, + {0x0c4a, 0x0c4d, 1}, + {0x0c55, 0x0c56, 1}, + {0x0c58, 0x0c5a, 1}, + {0x0c60, 0x0c63, 1}, + {0x0c66, 0x0c6f, 1}, + {0x0c78, 0x0c83, 1}, + {0x0c85, 0x0c8c, 1}, + {0x0c8e, 0x0c90, 1}, + {0x0c92, 0x0ca8, 1}, + {0x0caa, 0x0cb3, 1}, + {0x0cb5, 0x0cb9, 1}, + {0x0cbc, 0x0cc4, 1}, + {0x0cc6, 0x0cc8, 1}, + {0x0cca, 0x0ccd, 1}, + {0x0cd5, 0x0cd6, 1}, + {0x0cde, 0x0ce0, 2}, + {0x0ce1, 0x0ce3, 1}, + {0x0ce6, 0x0cef, 1}, + {0x0cf1, 0x0cf2, 1}, + {0x0d01, 0x0d03, 1}, + {0x0d05, 0x0d0c, 1}, + {0x0d0e, 0x0d10, 1}, + {0x0d12, 0x0d3a, 1}, + {0x0d3d, 0x0d44, 1}, + {0x0d46, 0x0d48, 1}, + {0x0d4a, 0x0d4f, 1}, + {0x0d54, 0x0d63, 1}, + {0x0d66, 0x0d7f, 1}, + {0x0d82, 0x0d83, 1}, + {0x0d85, 0x0d96, 1}, + {0x0d9a, 0x0db1, 1}, + {0x0db3, 0x0dbb, 1}, + {0x0dbd, 0x0dc0, 3}, + {0x0dc1, 0x0dc6, 1}, + {0x0dca, 0x0dcf, 5}, + {0x0dd0, 0x0dd4, 1}, + {0x0dd6, 0x0dd8, 2}, + {0x0dd9, 0x0ddf, 1}, + {0x0de6, 0x0def, 1}, + {0x0df2, 0x0df4, 1}, + {0x0e01, 0x0e3a, 1}, + {0x0e3f, 0x0e5b, 1}, + {0x0e81, 0x0e82, 1}, + {0x0e84, 0x0e87, 3}, + {0x0e88, 0x0e8a, 2}, + {0x0e8d, 0x0e94, 7}, + {0x0e95, 0x0e97, 1}, + {0x0e99, 0x0e9f, 1}, + {0x0ea1, 0x0ea3, 1}, + {0x0ea5, 0x0ea7, 2}, + {0x0eaa, 0x0eab, 1}, + {0x0ead, 0x0eb9, 1}, + {0x0ebb, 0x0ebd, 1}, + {0x0ec0, 0x0ec4, 1}, + {0x0ec6, 0x0ec8, 2}, + {0x0ec9, 0x0ecd, 1}, + {0x0ed0, 0x0ed9, 1}, + {0x0edc, 0x0edf, 1}, + {0x0f00, 0x0f47, 1}, + {0x0f49, 0x0f6c, 1}, + {0x0f71, 0x0f97, 1}, + {0x0f99, 0x0fbc, 1}, + {0x0fbe, 0x0fcc, 1}, + {0x0fce, 0x0fda, 1}, + {0x1000, 0x10c5, 1}, + {0x10c7, 0x10cd, 6}, + {0x10d0, 0x1248, 1}, + {0x124a, 0x124d, 1}, + {0x1250, 0x1256, 1}, + {0x1258, 0x125a, 2}, + {0x125b, 0x125d, 1}, + {0x1260, 0x1288, 1}, + {0x128a, 0x128d, 1}, + {0x1290, 0x12b0, 1}, + {0x12b2, 0x12b5, 1}, + {0x12b8, 0x12be, 1}, + {0x12c0, 0x12c2, 2}, + {0x12c3, 0x12c5, 1}, + {0x12c8, 0x12d6, 1}, + {0x12d8, 0x1310, 1}, + {0x1312, 0x1315, 1}, + {0x1318, 0x135a, 1}, + {0x135d, 0x137c, 1}, + {0x1380, 0x1399, 1}, + {0x13a0, 0x13f5, 1}, + {0x13f8, 0x13fd, 1}, + {0x1400, 0x169c, 1}, + {0x16a0, 0x16f8, 1}, + {0x1700, 0x170c, 1}, + {0x170e, 0x1714, 1}, + {0x1720, 0x1736, 1}, + {0x1740, 0x1753, 1}, + {0x1760, 0x176c, 1}, + {0x176e, 0x1770, 1}, + {0x1772, 0x1773, 1}, + {0x1780, 0x17dd, 1}, + {0x17e0, 0x17e9, 1}, + {0x17f0, 0x17f9, 1}, + {0x1800, 0x180e, 1}, + {0x1810, 0x1819, 1}, + {0x1820, 0x1877, 1}, + {0x1880, 0x18aa, 1}, + {0x18b0, 0x18f5, 1}, + {0x1900, 0x191e, 1}, + {0x1920, 0x192b, 1}, + {0x1930, 0x193b, 1}, + {0x1940, 0x1944, 4}, + {0x1945, 0x196d, 1}, + {0x1970, 0x1974, 1}, + {0x1980, 0x19ab, 1}, + {0x19b0, 0x19c9, 1}, + {0x19d0, 0x19da, 1}, + {0x19de, 0x1a1b, 1}, + {0x1a1e, 0x1a5e, 1}, + {0x1a60, 0x1a7c, 1}, + {0x1a7f, 0x1a89, 1}, + {0x1a90, 0x1a99, 1}, + {0x1aa0, 0x1aad, 1}, + {0x1ab0, 0x1abe, 1}, + {0x1b00, 0x1b4b, 1}, + {0x1b50, 0x1b7c, 1}, + {0x1b80, 0x1bf3, 1}, + {0x1bfc, 0x1c37, 1}, + {0x1c3b, 0x1c49, 1}, + {0x1c4d, 0x1c88, 1}, + {0x1cc0, 0x1cc7, 1}, + {0x1cd0, 0x1cf6, 1}, + {0x1cf8, 0x1cf9, 1}, + {0x1d00, 0x1df5, 1}, + {0x1dfb, 0x1f15, 1}, + {0x1f18, 0x1f1d, 1}, + {0x1f20, 0x1f45, 1}, + {0x1f48, 0x1f4d, 1}, + {0x1f50, 0x1f57, 1}, + {0x1f59, 0x1f5f, 2}, + {0x1f60, 0x1f7d, 1}, + {0x1f80, 0x1fb4, 1}, + {0x1fb6, 0x1fc4, 1}, + {0x1fc6, 0x1fd3, 1}, + {0x1fd6, 0x1fdb, 1}, + {0x1fdd, 0x1fef, 1}, + {0x1ff2, 0x1ff4, 1}, + {0x1ff6, 0x1ffe, 1}, + {0x2000, 0x2064, 1}, + {0x2066, 0x2071, 1}, + {0x2074, 0x208e, 1}, + {0x2090, 0x209c, 1}, + {0x20a0, 0x20be, 1}, + {0x20d0, 0x20f0, 1}, + {0x2100, 0x218b, 1}, + {0x2190, 0x23fe, 1}, + {0x2400, 0x2426, 1}, + {0x2440, 0x244a, 1}, + {0x2460, 0x2b73, 1}, + {0x2b76, 0x2b95, 1}, + {0x2b98, 0x2bb9, 1}, + {0x2bbd, 0x2bc8, 1}, + {0x2bca, 0x2bd1, 1}, + {0x2bec, 0x2bef, 1}, + {0x2c00, 0x2c2e, 1}, + {0x2c30, 0x2c5e, 1}, + {0x2c60, 0x2cf3, 1}, + {0x2cf9, 0x2d25, 1}, + {0x2d27, 0x2d2d, 6}, + {0x2d30, 0x2d67, 1}, + {0x2d6f, 0x2d70, 1}, + {0x2d7f, 0x2d96, 1}, + {0x2da0, 0x2da6, 1}, + {0x2da8, 0x2dae, 1}, + {0x2db0, 0x2db6, 1}, + {0x2db8, 0x2dbe, 1}, + {0x2dc0, 0x2dc6, 1}, + {0x2dc8, 0x2dce, 1}, + {0x2dd0, 0x2dd6, 1}, + {0x2dd8, 0x2dde, 1}, + {0x2de0, 0x2e44, 1}, + {0x2e80, 0x2e99, 1}, + {0x2e9b, 0x2ef3, 1}, + {0x2f00, 0x2fd5, 1}, + {0x2ff0, 0x2ffb, 1}, + {0x3000, 0x303f, 1}, + {0x3041, 0x3096, 1}, + {0x3099, 0x30ff, 1}, + {0x3105, 0x312d, 1}, + {0x3131, 0x318e, 1}, + {0x3190, 0x31ba, 1}, + {0x31c0, 0x31e3, 1}, + {0x31f0, 0x321e, 1}, + {0x3220, 0x32fe, 1}, + {0x3300, 0x4db5, 1}, + {0x4dc0, 0x9fd5, 1}, + {0xa000, 0xa48c, 1}, + {0xa490, 0xa4c6, 1}, + {0xa4d0, 0xa62b, 1}, + {0xa640, 0xa6f7, 1}, + {0xa700, 0xa7ae, 1}, + {0xa7b0, 0xa7b7, 1}, + {0xa7f7, 0xa82b, 1}, + {0xa830, 0xa839, 1}, + {0xa840, 0xa877, 1}, + {0xa880, 0xa8c5, 1}, + {0xa8ce, 0xa8d9, 1}, + {0xa8e0, 0xa8fd, 1}, + {0xa900, 0xa953, 1}, + {0xa95f, 0xa97c, 1}, + {0xa980, 0xa9cd, 1}, + {0xa9cf, 0xa9d9, 1}, + {0xa9de, 0xa9fe, 1}, + {0xaa00, 0xaa36, 1}, + {0xaa40, 0xaa4d, 1}, + {0xaa50, 0xaa59, 1}, + {0xaa5c, 0xaac2, 1}, + {0xaadb, 0xaaf6, 1}, + {0xab01, 0xab06, 1}, + {0xab09, 0xab0e, 1}, + {0xab11, 0xab16, 1}, + {0xab20, 0xab26, 1}, + {0xab28, 0xab2e, 1}, + {0xab30, 0xab65, 1}, + {0xab70, 0xabed, 1}, + {0xabf0, 0xabf9, 1}, + {0xac00, 0xd7a3, 1}, + {0xd7b0, 0xd7c6, 1}, + {0xd7cb, 0xd7fb, 1}, + {0xd800, 0xfa6d, 1}, + {0xfa70, 0xfad9, 1}, + {0xfb00, 0xfb06, 1}, + {0xfb13, 0xfb17, 1}, + {0xfb1d, 0xfb36, 1}, + {0xfb38, 0xfb3c, 1}, + {0xfb3e, 0xfb40, 2}, + {0xfb41, 0xfb43, 2}, + {0xfb44, 0xfb46, 2}, + {0xfb47, 0xfbc1, 1}, + {0xfbd3, 0xfd3f, 1}, + {0xfd50, 0xfd8f, 1}, + {0xfd92, 0xfdc7, 1}, + {0xfdf0, 0xfdfd, 1}, + {0xfe00, 0xfe19, 1}, + {0xfe20, 0xfe52, 1}, + {0xfe54, 0xfe66, 1}, + {0xfe68, 0xfe6b, 1}, + {0xfe70, 0xfe74, 1}, + {0xfe76, 0xfefc, 1}, + {0xfeff, 0xff01, 2}, + {0xff02, 0xffbe, 1}, + {0xffc2, 0xffc7, 1}, + {0xffca, 0xffcf, 1}, + {0xffd2, 0xffd7, 1}, + {0xffda, 0xffdc, 1}, + {0xffe0, 0xffe6, 1}, + {0xffe8, 0xffee, 1}, + {0xfff9, 0xfffd, 1}, + }, + R32: []unicode.Range32{ + {0x00010000, 0x0001000b, 1}, + {0x0001000d, 0x00010026, 1}, + {0x00010028, 0x0001003a, 1}, + {0x0001003c, 0x0001003d, 1}, + {0x0001003f, 0x0001004d, 1}, + {0x00010050, 0x0001005d, 1}, + {0x00010080, 0x000100fa, 1}, + {0x00010100, 0x00010102, 1}, + {0x00010107, 0x00010133, 1}, + {0x00010137, 0x0001018e, 1}, + {0x00010190, 0x0001019b, 1}, + {0x000101a0, 0x000101d0, 48}, + {0x000101d1, 0x000101fd, 1}, + {0x00010280, 0x0001029c, 1}, + {0x000102a0, 0x000102d0, 1}, + {0x000102e0, 0x000102fb, 1}, + {0x00010300, 0x00010323, 1}, + {0x00010330, 0x0001034a, 1}, + {0x00010350, 0x0001037a, 1}, + {0x00010380, 0x0001039d, 1}, + {0x0001039f, 0x000103c3, 1}, + {0x000103c8, 0x000103d5, 1}, + {0x00010400, 0x0001049d, 1}, + {0x000104a0, 0x000104a9, 1}, + {0x000104b0, 0x000104d3, 1}, + {0x000104d8, 0x000104fb, 1}, + {0x00010500, 0x00010527, 1}, + {0x00010530, 0x00010563, 1}, + {0x0001056f, 0x00010600, 145}, + {0x00010601, 0x00010736, 1}, + {0x00010740, 0x00010755, 1}, + {0x00010760, 0x00010767, 1}, + {0x00010800, 0x00010805, 1}, + {0x00010808, 0x0001080a, 2}, + {0x0001080b, 0x00010835, 1}, + {0x00010837, 0x00010838, 1}, + {0x0001083c, 0x0001083f, 3}, + {0x00010840, 0x00010855, 1}, + {0x00010857, 0x0001089e, 1}, + {0x000108a7, 0x000108af, 1}, + {0x000108e0, 0x000108f2, 1}, + {0x000108f4, 0x000108f5, 1}, + {0x000108fb, 0x0001091b, 1}, + {0x0001091f, 0x00010939, 1}, + {0x0001093f, 0x00010980, 65}, + {0x00010981, 0x000109b7, 1}, + {0x000109bc, 0x000109cf, 1}, + {0x000109d2, 0x00010a03, 1}, + {0x00010a05, 0x00010a06, 1}, + {0x00010a0c, 0x00010a13, 1}, + {0x00010a15, 0x00010a17, 1}, + {0x00010a19, 0x00010a33, 1}, + {0x00010a38, 0x00010a3a, 1}, + {0x00010a3f, 0x00010a47, 1}, + {0x00010a50, 0x00010a58, 1}, + {0x00010a60, 0x00010a9f, 1}, + {0x00010ac0, 0x00010ae6, 1}, + {0x00010aeb, 0x00010af6, 1}, + {0x00010b00, 0x00010b35, 1}, + {0x00010b39, 0x00010b55, 1}, + {0x00010b58, 0x00010b72, 1}, + {0x00010b78, 0x00010b91, 1}, + {0x00010b99, 0x00010b9c, 1}, + {0x00010ba9, 0x00010baf, 1}, + {0x00010c00, 0x00010c48, 1}, + {0x00010c80, 0x00010cb2, 1}, + {0x00010cc0, 0x00010cf2, 1}, + {0x00010cfa, 0x00010cff, 1}, + {0x00010e60, 0x00010e7e, 1}, + {0x00011000, 0x0001104d, 1}, + {0x00011052, 0x0001106f, 1}, + {0x0001107f, 0x000110c1, 1}, + {0x000110d0, 0x000110e8, 1}, + {0x000110f0, 0x000110f9, 1}, + {0x00011100, 0x00011134, 1}, + {0x00011136, 0x00011143, 1}, + {0x00011150, 0x00011176, 1}, + {0x00011180, 0x000111cd, 1}, + {0x000111d0, 0x000111df, 1}, + {0x000111e1, 0x000111f4, 1}, + {0x00011200, 0x00011211, 1}, + {0x00011213, 0x0001123e, 1}, + {0x00011280, 0x00011286, 1}, + {0x00011288, 0x0001128a, 2}, + {0x0001128b, 0x0001128d, 1}, + {0x0001128f, 0x0001129d, 1}, + {0x0001129f, 0x000112a9, 1}, + {0x000112b0, 0x000112ea, 1}, + {0x000112f0, 0x000112f9, 1}, + {0x00011300, 0x00011303, 1}, + {0x00011305, 0x0001130c, 1}, + {0x0001130f, 0x00011310, 1}, + {0x00011313, 0x00011328, 1}, + {0x0001132a, 0x00011330, 1}, + {0x00011332, 0x00011333, 1}, + {0x00011335, 0x00011339, 1}, + {0x0001133c, 0x00011344, 1}, + {0x00011347, 0x00011348, 1}, + {0x0001134b, 0x0001134d, 1}, + {0x00011350, 0x00011357, 7}, + {0x0001135d, 0x00011363, 1}, + {0x00011366, 0x0001136c, 1}, + {0x00011370, 0x00011374, 1}, + {0x00011400, 0x00011459, 1}, + {0x0001145b, 0x0001145d, 2}, + {0x00011480, 0x000114c7, 1}, + {0x000114d0, 0x000114d9, 1}, + {0x00011580, 0x000115b5, 1}, + {0x000115b8, 0x000115dd, 1}, + {0x00011600, 0x00011644, 1}, + {0x00011650, 0x00011659, 1}, + {0x00011660, 0x0001166c, 1}, + {0x00011680, 0x000116b7, 1}, + {0x000116c0, 0x000116c9, 1}, + {0x00011700, 0x00011719, 1}, + {0x0001171d, 0x0001172b, 1}, + {0x00011730, 0x0001173f, 1}, + {0x000118a0, 0x000118f2, 1}, + {0x000118ff, 0x00011ac0, 449}, + {0x00011ac1, 0x00011af8, 1}, + {0x00011c00, 0x00011c08, 1}, + {0x00011c0a, 0x00011c36, 1}, + {0x00011c38, 0x00011c45, 1}, + {0x00011c50, 0x00011c6c, 1}, + {0x00011c70, 0x00011c8f, 1}, + {0x00011c92, 0x00011ca7, 1}, + {0x00011ca9, 0x00011cb6, 1}, + {0x00012000, 0x00012399, 1}, + {0x00012400, 0x0001246e, 1}, + {0x00012470, 0x00012474, 1}, + {0x00012480, 0x00012543, 1}, + {0x00013000, 0x0001342e, 1}, + {0x00014400, 0x00014646, 1}, + {0x00016800, 0x00016a38, 1}, + {0x00016a40, 0x00016a5e, 1}, + {0x00016a60, 0x00016a69, 1}, + {0x00016a6e, 0x00016a6f, 1}, + {0x00016ad0, 0x00016aed, 1}, + {0x00016af0, 0x00016af5, 1}, + {0x00016b00, 0x00016b45, 1}, + {0x00016b50, 0x00016b59, 1}, + {0x00016b5b, 0x00016b61, 1}, + {0x00016b63, 0x00016b77, 1}, + {0x00016b7d, 0x00016b8f, 1}, + {0x00016f00, 0x00016f44, 1}, + {0x00016f50, 0x00016f7e, 1}, + {0x00016f8f, 0x00016f9f, 1}, + {0x00016fe0, 0x00017000, 32}, + {0x00017001, 0x000187ec, 1}, + {0x00018800, 0x00018af2, 1}, + {0x0001b000, 0x0001b001, 1}, + {0x0001bc00, 0x0001bc6a, 1}, + {0x0001bc70, 0x0001bc7c, 1}, + {0x0001bc80, 0x0001bc88, 1}, + {0x0001bc90, 0x0001bc99, 1}, + {0x0001bc9c, 0x0001bca3, 1}, + {0x0001d000, 0x0001d0f5, 1}, + {0x0001d100, 0x0001d126, 1}, + {0x0001d129, 0x0001d1e8, 1}, + {0x0001d200, 0x0001d245, 1}, + {0x0001d300, 0x0001d356, 1}, + {0x0001d360, 0x0001d371, 1}, + {0x0001d400, 0x0001d454, 1}, + {0x0001d456, 0x0001d49c, 1}, + {0x0001d49e, 0x0001d49f, 1}, + {0x0001d4a2, 0x0001d4a5, 3}, + {0x0001d4a6, 0x0001d4a9, 3}, + {0x0001d4aa, 0x0001d4ac, 1}, + {0x0001d4ae, 0x0001d4b9, 1}, + {0x0001d4bb, 0x0001d4bd, 2}, + {0x0001d4be, 0x0001d4c3, 1}, + {0x0001d4c5, 0x0001d505, 1}, + {0x0001d507, 0x0001d50a, 1}, + {0x0001d50d, 0x0001d514, 1}, + {0x0001d516, 0x0001d51c, 1}, + {0x0001d51e, 0x0001d539, 1}, + {0x0001d53b, 0x0001d53e, 1}, + {0x0001d540, 0x0001d544, 1}, + {0x0001d546, 0x0001d54a, 4}, + {0x0001d54b, 0x0001d550, 1}, + {0x0001d552, 0x0001d6a5, 1}, + {0x0001d6a8, 0x0001d7cb, 1}, + {0x0001d7ce, 0x0001da8b, 1}, + {0x0001da9b, 0x0001da9f, 1}, + {0x0001daa1, 0x0001daaf, 1}, + {0x0001e000, 0x0001e006, 1}, + {0x0001e008, 0x0001e018, 1}, + {0x0001e01b, 0x0001e021, 1}, + {0x0001e023, 0x0001e024, 1}, + {0x0001e026, 0x0001e02a, 1}, + {0x0001e800, 0x0001e8c4, 1}, + {0x0001e8c7, 0x0001e8d6, 1}, + {0x0001e900, 0x0001e94a, 1}, + {0x0001e950, 0x0001e959, 1}, + {0x0001e95e, 0x0001e95f, 1}, + {0x0001ee00, 0x0001ee03, 1}, + {0x0001ee05, 0x0001ee1f, 1}, + {0x0001ee21, 0x0001ee22, 1}, + {0x0001ee24, 0x0001ee27, 3}, + {0x0001ee29, 0x0001ee32, 1}, + {0x0001ee34, 0x0001ee37, 1}, + {0x0001ee39, 0x0001ee3b, 2}, + {0x0001ee42, 0x0001ee47, 5}, + {0x0001ee49, 0x0001ee4d, 2}, + {0x0001ee4e, 0x0001ee4f, 1}, + {0x0001ee51, 0x0001ee52, 1}, + {0x0001ee54, 0x0001ee57, 3}, + {0x0001ee59, 0x0001ee61, 2}, + {0x0001ee62, 0x0001ee64, 2}, + {0x0001ee67, 0x0001ee6a, 1}, + {0x0001ee6c, 0x0001ee72, 1}, + {0x0001ee74, 0x0001ee77, 1}, + {0x0001ee79, 0x0001ee7c, 1}, + {0x0001ee7e, 0x0001ee80, 2}, + {0x0001ee81, 0x0001ee89, 1}, + {0x0001ee8b, 0x0001ee9b, 1}, + {0x0001eea1, 0x0001eea3, 1}, + {0x0001eea5, 0x0001eea9, 1}, + {0x0001eeab, 0x0001eebb, 1}, + {0x0001eef0, 0x0001eef1, 1}, + {0x0001f000, 0x0001f02b, 1}, + {0x0001f030, 0x0001f093, 1}, + {0x0001f0a0, 0x0001f0ae, 1}, + {0x0001f0b1, 0x0001f0bf, 1}, + {0x0001f0c1, 0x0001f0cf, 1}, + {0x0001f0d1, 0x0001f0f5, 1}, + {0x0001f100, 0x0001f10c, 1}, + {0x0001f110, 0x0001f12e, 1}, + {0x0001f130, 0x0001f16b, 1}, + {0x0001f170, 0x0001f1ac, 1}, + {0x0001f1e6, 0x0001f202, 1}, + {0x0001f210, 0x0001f23b, 1}, + {0x0001f240, 0x0001f248, 1}, + {0x0001f250, 0x0001f251, 1}, + {0x0001f300, 0x0001f6d2, 1}, + {0x0001f6e0, 0x0001f6ec, 1}, + {0x0001f6f0, 0x0001f6f6, 1}, + {0x0001f700, 0x0001f773, 1}, + {0x0001f780, 0x0001f7d4, 1}, + {0x0001f800, 0x0001f80b, 1}, + {0x0001f810, 0x0001f847, 1}, + {0x0001f850, 0x0001f859, 1}, + {0x0001f860, 0x0001f887, 1}, + {0x0001f890, 0x0001f8ad, 1}, + {0x0001f910, 0x0001f91e, 1}, + {0x0001f920, 0x0001f927, 1}, + {0x0001f930, 0x0001f933, 3}, + {0x0001f934, 0x0001f93e, 1}, + {0x0001f940, 0x0001f94b, 1}, + {0x0001f950, 0x0001f95e, 1}, + {0x0001f980, 0x0001f991, 1}, + {0x0001f9c0, 0x00020000, 1600}, + {0x00020001, 0x0002a6d6, 1}, + {0x0002a700, 0x0002b734, 1}, + {0x0002b740, 0x0002b81d, 1}, + {0x0002b820, 0x0002cea1, 1}, + {0x0002f800, 0x0002fa1d, 1}, + {0x000e0001, 0x000e0020, 31}, + {0x000e0021, 0x000e007f, 1}, + {0x000e0100, 0x000e01ef, 1}, + {0x000f0000, 0x000ffffd, 1}, + {0x00100000, 0x0010fffd, 1}, + }, + LatinOffset: 0, +} + +// Total size 44206 bytes (43 KiB) diff --git a/vendor/golang.org/x/time/rate/rate.go b/vendor/golang.org/x/time/rate/rate.go index eabcd11474..7228d97e96 100644 --- a/vendor/golang.org/x/time/rate/rate.go +++ b/vendor/golang.org/x/time/rate/rate.go @@ -253,8 +253,12 @@ func (lim *Limiter) waitN(ctx contextContext, n int) (err error) { if !r.ok { return fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n) } - // Wait - t := time.NewTimer(r.DelayFrom(now)) + // Wait if necessary + delay := r.DelayFrom(now) + if delay == 0 { + return nil + } + t := time.NewTimer(delay) defer t.Stop() select { case <-t.C: diff --git a/vendor/golang.org/x/time/rate/rate_test.go b/vendor/golang.org/x/time/rate/rate_test.go deleted file mode 100644 index e8add694fd..0000000000 --- a/vendor/golang.org/x/time/rate/rate_test.go +++ /dev/null @@ -1,449 +0,0 @@ -// Copyright 2015 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 go1.7 - -package rate - -import ( - "context" - "math" - "runtime" - "sync" - "sync/atomic" - "testing" - "time" -) - -func TestLimit(t *testing.T) { - if Limit(10) == Inf { - t.Errorf("Limit(10) == Inf should be false") - } -} - -func closeEnough(a, b Limit) bool { - return (math.Abs(float64(a)/float64(b)) - 1.0) < 1e-9 -} - -func TestEvery(t *testing.T) { - cases := []struct { - interval time.Duration - lim Limit - }{ - {0, Inf}, - {-1, Inf}, - {1 * time.Nanosecond, Limit(1e9)}, - {1 * time.Microsecond, Limit(1e6)}, - {1 * time.Millisecond, Limit(1e3)}, - {10 * time.Millisecond, Limit(100)}, - {100 * time.Millisecond, Limit(10)}, - {1 * time.Second, Limit(1)}, - {2 * time.Second, Limit(0.5)}, - {time.Duration(2.5 * float64(time.Second)), Limit(0.4)}, - {4 * time.Second, Limit(0.25)}, - {10 * time.Second, Limit(0.1)}, - {time.Duration(math.MaxInt64), Limit(1e9 / float64(math.MaxInt64))}, - } - for _, tc := range cases { - lim := Every(tc.interval) - if !closeEnough(lim, tc.lim) { - t.Errorf("Every(%v) = %v want %v", tc.interval, lim, tc.lim) - } - } -} - -const ( - d = 100 * time.Millisecond -) - -var ( - t0 = time.Now() - t1 = t0.Add(time.Duration(1) * d) - t2 = t0.Add(time.Duration(2) * d) - t3 = t0.Add(time.Duration(3) * d) - t4 = t0.Add(time.Duration(4) * d) - t5 = t0.Add(time.Duration(5) * d) - t9 = t0.Add(time.Duration(9) * d) -) - -type allow struct { - t time.Time - n int - ok bool -} - -func run(t *testing.T, lim *Limiter, allows []allow) { - for i, allow := range allows { - ok := lim.AllowN(allow.t, allow.n) - if ok != allow.ok { - t.Errorf("step %d: lim.AllowN(%v, %v) = %v want %v", - i, allow.t, allow.n, ok, allow.ok) - } - } -} - -func TestLimiterBurst1(t *testing.T) { - run(t, NewLimiter(10, 1), []allow{ - {t0, 1, true}, - {t0, 1, false}, - {t0, 1, false}, - {t1, 1, true}, - {t1, 1, false}, - {t1, 1, false}, - {t2, 2, false}, // burst size is 1, so n=2 always fails - {t2, 1, true}, - {t2, 1, false}, - }) -} - -func TestLimiterBurst3(t *testing.T) { - run(t, NewLimiter(10, 3), []allow{ - {t0, 2, true}, - {t0, 2, false}, - {t0, 1, true}, - {t0, 1, false}, - {t1, 4, false}, - {t2, 1, true}, - {t3, 1, true}, - {t4, 1, true}, - {t4, 1, true}, - {t4, 1, false}, - {t4, 1, false}, - {t9, 3, true}, - {t9, 0, true}, - }) -} - -func TestLimiterJumpBackwards(t *testing.T) { - run(t, NewLimiter(10, 3), []allow{ - {t1, 1, true}, // start at t1 - {t0, 1, true}, // jump back to t0, two tokens remain - {t0, 1, true}, - {t0, 1, false}, - {t0, 1, false}, - {t1, 1, true}, // got a token - {t1, 1, false}, - {t1, 1, false}, - {t2, 1, true}, // got another token - {t2, 1, false}, - {t2, 1, false}, - }) -} - -func TestSimultaneousRequests(t *testing.T) { - const ( - limit = 1 - burst = 5 - numRequests = 15 - ) - var ( - wg sync.WaitGroup - numOK = uint32(0) - ) - - // Very slow replenishing bucket. - lim := NewLimiter(limit, burst) - - // Tries to take a token, atomically updates the counter and decreases the wait - // group counter. - f := func() { - defer wg.Done() - if ok := lim.Allow(); ok { - atomic.AddUint32(&numOK, 1) - } - } - - wg.Add(numRequests) - for i := 0; i < numRequests; i++ { - go f() - } - wg.Wait() - if numOK != burst { - t.Errorf("numOK = %d, want %d", numOK, burst) - } -} - -func TestLongRunningQPS(t *testing.T) { - if testing.Short() { - t.Skip("skipping in short mode") - } - if runtime.GOOS == "openbsd" { - t.Skip("low resolution time.Sleep invalidates test (golang.org/issue/14183)") - return - } - - // The test runs for a few seconds executing many requests and then checks - // that overall number of requests is reasonable. - const ( - limit = 100 - burst = 100 - ) - var numOK = int32(0) - - lim := NewLimiter(limit, burst) - - var wg sync.WaitGroup - f := func() { - if ok := lim.Allow(); ok { - atomic.AddInt32(&numOK, 1) - } - wg.Done() - } - - start := time.Now() - end := start.Add(5 * time.Second) - for time.Now().Before(end) { - wg.Add(1) - go f() - - // This will still offer ~500 requests per second, but won't consume - // outrageous amount of CPU. - time.Sleep(2 * time.Millisecond) - } - wg.Wait() - elapsed := time.Since(start) - ideal := burst + (limit * float64(elapsed) / float64(time.Second)) - - // We should never get more requests than allowed. - if want := int32(ideal + 1); numOK > want { - t.Errorf("numOK = %d, want %d (ideal %f)", numOK, want, ideal) - } - // We should get very close to the number of requests allowed. - if want := int32(0.999 * ideal); numOK < want { - t.Errorf("numOK = %d, want %d (ideal %f)", numOK, want, ideal) - } -} - -type request struct { - t time.Time - n int - act time.Time - ok bool -} - -// dFromDuration converts a duration to a multiple of the global constant d -func dFromDuration(dur time.Duration) int { - // Adding a millisecond to be swallowed by the integer division - // because we don't care about small inaccuracies - return int((dur + time.Millisecond) / d) -} - -// dSince returns multiples of d since t0 -func dSince(t time.Time) int { - return dFromDuration(t.Sub(t0)) -} - -func runReserve(t *testing.T, lim *Limiter, req request) *Reservation { - return runReserveMax(t, lim, req, InfDuration) -} - -func runReserveMax(t *testing.T, lim *Limiter, req request, maxReserve time.Duration) *Reservation { - r := lim.reserveN(req.t, req.n, maxReserve) - if r.ok && (dSince(r.timeToAct) != dSince(req.act)) || r.ok != req.ok { - t.Errorf("lim.reserveN(t%d, %v, %v) = (t%d, %v) want (t%d, %v)", - dSince(req.t), req.n, maxReserve, dSince(r.timeToAct), r.ok, dSince(req.act), req.ok) - } - return &r -} - -func TestSimpleReserve(t *testing.T) { - lim := NewLimiter(10, 2) - - runReserve(t, lim, request{t0, 2, t0, true}) - runReserve(t, lim, request{t0, 2, t2, true}) - runReserve(t, lim, request{t3, 2, t4, true}) -} - -func TestMix(t *testing.T) { - lim := NewLimiter(10, 2) - - runReserve(t, lim, request{t0, 3, t1, false}) // should return false because n > Burst - runReserve(t, lim, request{t0, 2, t0, true}) - run(t, lim, []allow{{t1, 2, false}}) // not enought tokens - don't allow - runReserve(t, lim, request{t1, 2, t2, true}) - run(t, lim, []allow{{t1, 1, false}}) // negative tokens - don't allow - run(t, lim, []allow{{t3, 1, true}}) -} - -func TestCancelInvalid(t *testing.T) { - lim := NewLimiter(10, 2) - - runReserve(t, lim, request{t0, 2, t0, true}) - r := runReserve(t, lim, request{t0, 3, t3, false}) - r.CancelAt(t0) // should have no effect - runReserve(t, lim, request{t0, 2, t2, true}) // did not get extra tokens -} - -func TestCancelLast(t *testing.T) { - lim := NewLimiter(10, 2) - - runReserve(t, lim, request{t0, 2, t0, true}) - r := runReserve(t, lim, request{t0, 2, t2, true}) - r.CancelAt(t1) // got 2 tokens back - runReserve(t, lim, request{t1, 2, t2, true}) -} - -func TestCancelTooLate(t *testing.T) { - lim := NewLimiter(10, 2) - - runReserve(t, lim, request{t0, 2, t0, true}) - r := runReserve(t, lim, request{t0, 2, t2, true}) - r.CancelAt(t3) // too late to cancel - should have no effect - runReserve(t, lim, request{t3, 2, t4, true}) -} - -func TestCancel0Tokens(t *testing.T) { - lim := NewLimiter(10, 2) - - runReserve(t, lim, request{t0, 2, t0, true}) - r := runReserve(t, lim, request{t0, 1, t1, true}) - runReserve(t, lim, request{t0, 1, t2, true}) - r.CancelAt(t0) // got 0 tokens back - runReserve(t, lim, request{t0, 1, t3, true}) -} - -func TestCancel1Token(t *testing.T) { - lim := NewLimiter(10, 2) - - runReserve(t, lim, request{t0, 2, t0, true}) - r := runReserve(t, lim, request{t0, 2, t2, true}) - runReserve(t, lim, request{t0, 1, t3, true}) - r.CancelAt(t2) // got 1 token back - runReserve(t, lim, request{t2, 2, t4, true}) -} - -func TestCancelMulti(t *testing.T) { - lim := NewLimiter(10, 4) - - runReserve(t, lim, request{t0, 4, t0, true}) - rA := runReserve(t, lim, request{t0, 3, t3, true}) - runReserve(t, lim, request{t0, 1, t4, true}) - rC := runReserve(t, lim, request{t0, 1, t5, true}) - rC.CancelAt(t1) // get 1 token back - rA.CancelAt(t1) // get 2 tokens back, as if C was never reserved - runReserve(t, lim, request{t1, 3, t5, true}) -} - -func TestReserveJumpBack(t *testing.T) { - lim := NewLimiter(10, 2) - - runReserve(t, lim, request{t1, 2, t1, true}) // start at t1 - runReserve(t, lim, request{t0, 1, t1, true}) // should violate Limit,Burst - runReserve(t, lim, request{t2, 2, t3, true}) -} - -func TestReserveJumpBackCancel(t *testing.T) { - lim := NewLimiter(10, 2) - - runReserve(t, lim, request{t1, 2, t1, true}) // start at t1 - r := runReserve(t, lim, request{t1, 2, t3, true}) - runReserve(t, lim, request{t1, 1, t4, true}) - r.CancelAt(t0) // cancel at t0, get 1 token back - runReserve(t, lim, request{t1, 2, t4, true}) // should violate Limit,Burst -} - -func TestReserveSetLimit(t *testing.T) { - lim := NewLimiter(5, 2) - - runReserve(t, lim, request{t0, 2, t0, true}) - runReserve(t, lim, request{t0, 2, t4, true}) - lim.SetLimitAt(t2, 10) - runReserve(t, lim, request{t2, 1, t4, true}) // violates Limit and Burst -} - -func TestReserveSetLimitCancel(t *testing.T) { - lim := NewLimiter(5, 2) - - runReserve(t, lim, request{t0, 2, t0, true}) - r := runReserve(t, lim, request{t0, 2, t4, true}) - lim.SetLimitAt(t2, 10) - r.CancelAt(t2) // 2 tokens back - runReserve(t, lim, request{t2, 2, t3, true}) -} - -func TestReserveMax(t *testing.T) { - lim := NewLimiter(10, 2) - maxT := d - - runReserveMax(t, lim, request{t0, 2, t0, true}, maxT) - runReserveMax(t, lim, request{t0, 1, t1, true}, maxT) // reserve for close future - runReserveMax(t, lim, request{t0, 1, t2, false}, maxT) // time to act too far in the future -} - -type wait struct { - name string - ctx context.Context - n int - delay int // in multiples of d - nilErr bool -} - -func runWait(t *testing.T, lim *Limiter, w wait) { - start := time.Now() - err := lim.WaitN(w.ctx, w.n) - delay := time.Now().Sub(start) - if (w.nilErr && err != nil) || (!w.nilErr && err == nil) || w.delay != dFromDuration(delay) { - errString := "<nil>" - if !w.nilErr { - errString = "<non-nil error>" - } - t.Errorf("lim.WaitN(%v, lim, %v) = %v with delay %v ; want %v with delay %v", - w.name, w.n, err, delay, errString, d*time.Duration(w.delay)) - } -} - -func TestWaitSimple(t *testing.T) { - lim := NewLimiter(10, 3) - - ctx, cancel := context.WithCancel(context.Background()) - cancel() - runWait(t, lim, wait{"already-cancelled", ctx, 1, 0, false}) - - runWait(t, lim, wait{"exceed-burst-error", context.Background(), 4, 0, false}) - - runWait(t, lim, wait{"act-now", context.Background(), 2, 0, true}) - runWait(t, lim, wait{"act-later", context.Background(), 3, 2, true}) -} - -func TestWaitCancel(t *testing.T) { - lim := NewLimiter(10, 3) - - ctx, cancel := context.WithCancel(context.Background()) - runWait(t, lim, wait{"act-now", ctx, 2, 0, true}) // after this lim.tokens = 1 - go func() { - time.Sleep(d) - cancel() - }() - runWait(t, lim, wait{"will-cancel", ctx, 3, 1, false}) - // should get 3 tokens back, and have lim.tokens = 2 - t.Logf("tokens:%v last:%v lastEvent:%v", lim.tokens, lim.last, lim.lastEvent) - runWait(t, lim, wait{"act-now-after-cancel", context.Background(), 2, 0, true}) -} - -func TestWaitTimeout(t *testing.T) { - lim := NewLimiter(10, 3) - - ctx, cancel := context.WithTimeout(context.Background(), d) - defer cancel() - runWait(t, lim, wait{"act-now", ctx, 2, 0, true}) - runWait(t, lim, wait{"w-timeout-err", ctx, 3, 0, false}) -} - -func TestWaitInf(t *testing.T) { - lim := NewLimiter(Inf, 0) - - runWait(t, lim, wait{"exceed-burst-no-error", context.Background(), 3, 0, true}) -} - -func BenchmarkAllowN(b *testing.B) { - lim := NewLimiter(Every(1*time.Second), 1) - now := time.Now() - b.ReportAllocs() - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - lim.AllowN(now, 1) - } - }) -} diff --git a/vendor/google.golang.org/appengine/appengine_test.go b/vendor/google.golang.org/appengine/appengine_test.go deleted file mode 100644 index f1cf0a1b96..0000000000 --- a/vendor/google.golang.org/appengine/appengine_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package appengine - -import ( - "testing" -) - -func TestValidGeoPoint(t *testing.T) { - testCases := []struct { - desc string - pt GeoPoint - want bool - }{ - { - "valid", - GeoPoint{67.21, 13.37}, - true, - }, - { - "high lat", - GeoPoint{-90.01, 13.37}, - false, - }, - { - "low lat", - GeoPoint{90.01, 13.37}, - false, - }, - { - "high lng", - GeoPoint{67.21, 182}, - false, - }, - { - "low lng", - GeoPoint{67.21, -181}, - false, - }, - } - - for _, tc := range testCases { - if got := tc.pt.Valid(); got != tc.want { - t.Errorf("%s: got %v, want %v", tc.desc, got, tc.want) - } - } -} diff --git a/vendor/google.golang.org/appengine/internal/api_race_test.go b/vendor/google.golang.org/appengine/internal/api_race_test.go deleted file mode 100644 index 6cfe90649c..0000000000 --- a/vendor/google.golang.org/appengine/internal/api_race_test.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build race - -package internal - -func init() { raceDetector = true } diff --git a/vendor/google.golang.org/appengine/internal/api_test.go b/vendor/google.golang.org/appengine/internal/api_test.go deleted file mode 100644 index 386d7f6cf4..0000000000 --- a/vendor/google.golang.org/appengine/internal/api_test.go +++ /dev/null @@ -1,467 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build !appengine - -package internal - -import ( - "bufio" - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "net/url" - "os" - "os/exec" - "strings" - "sync/atomic" - "testing" - "time" - - "github.com/golang/protobuf/proto" - netcontext "golang.org/x/net/context" - - basepb "google.golang.org/appengine/internal/base" - remotepb "google.golang.org/appengine/internal/remote_api" -) - -const testTicketHeader = "X-Magic-Ticket-Header" - -func init() { - ticketHeader = testTicketHeader -} - -type fakeAPIHandler struct { - hang chan int // used for RunSlowly RPC - - LogFlushes int32 // atomic -} - -func (f *fakeAPIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - writeResponse := func(res *remotepb.Response) { - hresBody, err := proto.Marshal(res) - if err != nil { - http.Error(w, fmt.Sprintf("Failed encoding API response: %v", err), 500) - return - } - w.Write(hresBody) - } - - if r.URL.Path != "/rpc_http" { - http.NotFound(w, r) - return - } - hreqBody, err := ioutil.ReadAll(r.Body) - if err != nil { - http.Error(w, fmt.Sprintf("Bad body: %v", err), 500) - return - } - apiReq := &remotepb.Request{} - if err := proto.Unmarshal(hreqBody, apiReq); err != nil { - http.Error(w, fmt.Sprintf("Bad encoded API request: %v", err), 500) - return - } - if *apiReq.RequestId != "s3cr3t" { - writeResponse(&remotepb.Response{ - RpcError: &remotepb.RpcError{ - Code: proto.Int32(int32(remotepb.RpcError_SECURITY_VIOLATION)), - Detail: proto.String("bad security ticket"), - }, - }) - return - } - if got, want := r.Header.Get(dapperHeader), "trace-001"; got != want { - writeResponse(&remotepb.Response{ - RpcError: &remotepb.RpcError{ - Code: proto.Int32(int32(remotepb.RpcError_BAD_REQUEST)), - Detail: proto.String(fmt.Sprintf("trace info = %q, want %q", got, want)), - }, - }) - return - } - - service, method := *apiReq.ServiceName, *apiReq.Method - var resOut proto.Message - if service == "actordb" && method == "LookupActor" { - req := &basepb.StringProto{} - res := &basepb.StringProto{} - if err := proto.Unmarshal(apiReq.Request, req); err != nil { - http.Error(w, fmt.Sprintf("Bad encoded request: %v", err), 500) - return - } - if *req.Value == "Doctor Who" { - res.Value = proto.String("David Tennant") - } - resOut = res - } - if service == "errors" { - switch method { - case "Non200": - http.Error(w, "I'm a little teapot.", 418) - return - case "ShortResponse": - w.Header().Set("Content-Length", "100") - w.Write([]byte("way too short")) - return - case "OverQuota": - writeResponse(&remotepb.Response{ - RpcError: &remotepb.RpcError{ - Code: proto.Int32(int32(remotepb.RpcError_OVER_QUOTA)), - Detail: proto.String("you are hogging the resources!"), - }, - }) - return - case "RunSlowly": - // TestAPICallRPCFailure creates f.hang, but does not strobe it - // until Call returns with remotepb.RpcError_CANCELLED. - // This is here to force a happens-before relationship between - // the httptest server handler and shutdown. - <-f.hang - resOut = &basepb.VoidProto{} - } - } - if service == "logservice" && method == "Flush" { - // Pretend log flushing is slow. - time.Sleep(50 * time.Millisecond) - atomic.AddInt32(&f.LogFlushes, 1) - resOut = &basepb.VoidProto{} - } - - encOut, err := proto.Marshal(resOut) - if err != nil { - http.Error(w, fmt.Sprintf("Failed encoding response: %v", err), 500) - return - } - writeResponse(&remotepb.Response{ - Response: encOut, - }) -} - -func setup() (f *fakeAPIHandler, c *context, cleanup func()) { - f = &fakeAPIHandler{} - srv := httptest.NewServer(f) - u, err := url.Parse(srv.URL + apiPath) - if err != nil { - panic(fmt.Sprintf("url.Parse(%q): %v", srv.URL+apiPath, err)) - } - return f, &context{ - req: &http.Request{ - Header: http.Header{ - ticketHeader: []string{"s3cr3t"}, - dapperHeader: []string{"trace-001"}, - }, - }, - apiURL: u, - }, srv.Close -} - -func TestAPICall(t *testing.T) { - _, c, cleanup := setup() - defer cleanup() - - req := &basepb.StringProto{ - Value: proto.String("Doctor Who"), - } - res := &basepb.StringProto{} - err := Call(toContext(c), "actordb", "LookupActor", req, res) - if err != nil { - t.Fatalf("API call failed: %v", err) - } - if got, want := *res.Value, "David Tennant"; got != want { - t.Errorf("Response is %q, want %q", got, want) - } -} - -func TestAPICallRPCFailure(t *testing.T) { - f, c, cleanup := setup() - defer cleanup() - - testCases := []struct { - method string - code remotepb.RpcError_ErrorCode - }{ - {"Non200", remotepb.RpcError_UNKNOWN}, - {"ShortResponse", remotepb.RpcError_UNKNOWN}, - {"OverQuota", remotepb.RpcError_OVER_QUOTA}, - {"RunSlowly", remotepb.RpcError_CANCELLED}, - } - f.hang = make(chan int) // only for RunSlowly - for _, tc := range testCases { - ctx, _ := netcontext.WithTimeout(toContext(c), 100*time.Millisecond) - err := Call(ctx, "errors", tc.method, &basepb.VoidProto{}, &basepb.VoidProto{}) - ce, ok := err.(*CallError) - if !ok { - t.Errorf("%s: API call error is %T (%v), want *CallError", tc.method, err, err) - continue - } - if ce.Code != int32(tc.code) { - t.Errorf("%s: ce.Code = %d, want %d", tc.method, ce.Code, tc.code) - } - if tc.method == "RunSlowly" { - f.hang <- 1 // release the HTTP handler - } - } -} - -func TestAPICallDialFailure(t *testing.T) { - // See what happens if the API host is unresponsive. - // This should time out quickly, not hang forever. - _, c, cleanup := setup() - defer cleanup() - // Reset the URL to the production address so that dialing fails. - c.apiURL = apiURL() - - start := time.Now() - err := Call(toContext(c), "foo", "bar", &basepb.VoidProto{}, &basepb.VoidProto{}) - const max = 1 * time.Second - if taken := time.Since(start); taken > max { - t.Errorf("Dial hang took too long: %v > %v", taken, max) - } - if err == nil { - t.Error("Call did not fail") - } -} - -func TestDelayedLogFlushing(t *testing.T) { - f, c, cleanup := setup() - defer cleanup() - - http.HandleFunc("/quick_log", func(w http.ResponseWriter, r *http.Request) { - logC := WithContext(netcontext.Background(), r) - fromContext(logC).apiURL = c.apiURL // Otherwise it will try to use the default URL. - Logf(logC, 1, "It's a lovely day.") - w.WriteHeader(200) - w.Write(make([]byte, 100<<10)) // write 100 KB to force HTTP flush - }) - - r := &http.Request{ - Method: "GET", - URL: &url.URL{ - Scheme: "http", - Path: "/quick_log", - }, - Header: c.req.Header, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - } - w := httptest.NewRecorder() - - // Check that log flushing does not hold up the HTTP response. - start := time.Now() - handleHTTP(w, r) - if d := time.Since(start); d > 10*time.Millisecond { - t.Errorf("handleHTTP took %v, want under 10ms", d) - } - const hdr = "X-AppEngine-Log-Flush-Count" - if h := w.HeaderMap.Get(hdr); h != "1" { - t.Errorf("%s header = %q, want %q", hdr, h, "1") - } - if f := atomic.LoadInt32(&f.LogFlushes); f != 0 { - t.Errorf("After HTTP response: f.LogFlushes = %d, want 0", f) - } - - // Check that the log flush eventually comes in. - time.Sleep(100 * time.Millisecond) - if f := atomic.LoadInt32(&f.LogFlushes); f != 1 { - t.Errorf("After 100ms: f.LogFlushes = %d, want 1", f) - } -} - -func TestRemoteAddr(t *testing.T) { - var addr string - http.HandleFunc("/remote_addr", func(w http.ResponseWriter, r *http.Request) { - addr = r.RemoteAddr - }) - - testCases := []struct { - headers http.Header - addr string - }{ - {http.Header{"X-Appengine-User-Ip": []string{"10.5.2.1"}}, "10.5.2.1:80"}, - {http.Header{"X-Appengine-Remote-Addr": []string{"1.2.3.4"}}, "1.2.3.4:80"}, - {http.Header{"X-Appengine-Remote-Addr": []string{"1.2.3.4:8080"}}, "1.2.3.4:8080"}, - { - http.Header{"X-Appengine-Remote-Addr": []string{"2401:fa00:9:1:7646:a0ff:fe90:ca66"}}, - "[2401:fa00:9:1:7646:a0ff:fe90:ca66]:80", - }, - { - http.Header{"X-Appengine-Remote-Addr": []string{"[::1]:http"}}, - "[::1]:http", - }, - {http.Header{}, "127.0.0.1:80"}, - } - - for _, tc := range testCases { - r := &http.Request{ - Method: "GET", - URL: &url.URL{Scheme: "http", Path: "/remote_addr"}, - Header: tc.headers, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - } - handleHTTP(httptest.NewRecorder(), r) - if addr != tc.addr { - t.Errorf("Header %v, got %q, want %q", tc.headers, addr, tc.addr) - } - } -} - -func TestPanickingHandler(t *testing.T) { - http.HandleFunc("/panic", func(http.ResponseWriter, *http.Request) { - panic("whoops!") - }) - r := &http.Request{ - Method: "GET", - URL: &url.URL{Scheme: "http", Path: "/panic"}, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - } - rec := httptest.NewRecorder() - handleHTTP(rec, r) - if rec.Code != 500 { - t.Errorf("Panicking handler returned HTTP %d, want HTTP %d", rec.Code, 500) - } -} - -var raceDetector = false - -func TestAPICallAllocations(t *testing.T) { - if raceDetector { - t.Skip("not running under race detector") - } - - // Run the test API server in a subprocess so we aren't counting its allocations. - u, cleanup := launchHelperProcess(t) - defer cleanup() - c := &context{ - req: &http.Request{ - Header: http.Header{ - ticketHeader: []string{"s3cr3t"}, - dapperHeader: []string{"trace-001"}, - }, - }, - apiURL: u, - } - - req := &basepb.StringProto{ - Value: proto.String("Doctor Who"), - } - res := &basepb.StringProto{} - var apiErr error - avg := testing.AllocsPerRun(100, func() { - ctx, _ := netcontext.WithTimeout(toContext(c), 100*time.Millisecond) - if err := Call(ctx, "actordb", "LookupActor", req, res); err != nil && apiErr == nil { - apiErr = err // get the first error only - } - }) - if apiErr != nil { - t.Errorf("API call failed: %v", apiErr) - } - - // Lots of room for improvement... - // TODO(djd): Reduce maximum to 85 once the App Engine SDK is based on 1.6. - const min, max float64 = 70, 90 - if avg < min || max < avg { - t.Errorf("Allocations per API call = %g, want in [%g,%g]", avg, min, max) - } -} - -func launchHelperProcess(t *testing.T) (apiURL *url.URL, cleanup func()) { - cmd := exec.Command(os.Args[0], "-test.run=TestHelperProcess") - cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} - stdin, err := cmd.StdinPipe() - if err != nil { - t.Fatalf("StdinPipe: %v", err) - } - stdout, err := cmd.StdoutPipe() - if err != nil { - t.Fatalf("StdoutPipe: %v", err) - } - if err := cmd.Start(); err != nil { - t.Fatalf("Starting helper process: %v", err) - } - - scan := bufio.NewScanner(stdout) - var u *url.URL - for scan.Scan() { - line := scan.Text() - if hp := strings.TrimPrefix(line, helperProcessMagic); hp != line { - var err error - u, err = url.Parse(hp) - if err != nil { - t.Fatalf("Failed to parse %q: %v", hp, err) - } - break - } - } - if err := scan.Err(); err != nil { - t.Fatalf("Scanning helper process stdout: %v", err) - } - if u == nil { - t.Fatal("Helper process never reported") - } - - return u, func() { - stdin.Close() - if err := cmd.Wait(); err != nil { - t.Errorf("Helper process did not exit cleanly: %v", err) - } - } -} - -const helperProcessMagic = "A lovely helper process is listening at " - -// This isn't a real test. It's used as a helper process. -func TestHelperProcess(*testing.T) { - if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { - return - } - defer os.Exit(0) - - f := &fakeAPIHandler{} - srv := httptest.NewServer(f) - defer srv.Close() - fmt.Println(helperProcessMagic + srv.URL + apiPath) - - // Wait for stdin to be closed. - io.Copy(ioutil.Discard, os.Stdin) -} - -func TestBackgroundContext(t *testing.T) { - environ := []struct { - key, value string - }{ - {"GAE_LONG_APP_ID", "my-app-id"}, - {"GAE_MINOR_VERSION", "067924799508853122"}, - {"GAE_MODULE_INSTANCE", "0"}, - {"GAE_MODULE_NAME", "default"}, - {"GAE_MODULE_VERSION", "20150612t184001"}, - } - for _, v := range environ { - old := os.Getenv(v.key) - os.Setenv(v.key, v.value) - v.value = old - } - defer func() { // Restore old environment after the test completes. - for _, v := range environ { - if v.value == "" { - os.Unsetenv(v.key) - continue - } - os.Setenv(v.key, v.value) - } - }() - - ctx, key := fromContext(BackgroundContext()), "X-Magic-Ticket-Header" - if g, w := ctx.req.Header.Get(key), "my-app-id/default.20150612t184001.0"; g != w { - t.Errorf("%v = %q, want %q", key, g, w) - } - - // Check that using the background context doesn't panic. - req := &basepb.StringProto{ - Value: proto.String("Doctor Who"), - } - res := &basepb.StringProto{} - Call(BackgroundContext(), "actordb", "LookupActor", req, res) // expected to fail -} diff --git a/vendor/google.golang.org/appengine/internal/app_id_test.go b/vendor/google.golang.org/appengine/internal/app_id_test.go deleted file mode 100644 index e69195cd40..0000000000 --- a/vendor/google.golang.org/appengine/internal/app_id_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2011 Google Inc. All Rights Reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package internal - -import ( - "testing" -) - -func TestAppIDParsing(t *testing.T) { - testCases := []struct { - in string - partition, domain, displayID string - }{ - {"simple-app-id", "", "", "simple-app-id"}, - {"domain.com:domain-app-id", "", "domain.com", "domain-app-id"}, - {"part~partition-app-id", "part", "", "partition-app-id"}, - {"part~domain.com:display", "part", "domain.com", "display"}, - } - - for _, tc := range testCases { - part, dom, dis := parseFullAppID(tc.in) - if part != tc.partition { - t.Errorf("partition of %q: got %q, want %q", tc.in, part, tc.partition) - } - if dom != tc.domain { - t.Errorf("domain of %q: got %q, want %q", tc.in, dom, tc.domain) - } - if dis != tc.displayID { - t.Errorf("displayID of %q: got %q, want %q", tc.in, dis, tc.displayID) - } - } -} diff --git a/vendor/google.golang.org/appengine/internal/internal_vm_test.go b/vendor/google.golang.org/appengine/internal/internal_vm_test.go deleted file mode 100644 index f8097616b9..0000000000 --- a/vendor/google.golang.org/appengine/internal/internal_vm_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build !appengine - -package internal - -import ( - "io" - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" -) - -func TestInstallingHealthChecker(t *testing.T) { - try := func(desc string, mux *http.ServeMux, wantCode int, wantBody string) { - installHealthChecker(mux) - srv := httptest.NewServer(mux) - defer srv.Close() - - resp, err := http.Get(srv.URL + "/_ah/health") - if err != nil { - t.Errorf("%s: http.Get: %v", desc, err) - return - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("%s: reading body: %v", desc, err) - return - } - - if resp.StatusCode != wantCode { - t.Errorf("%s: got HTTP %d, want %d", desc, resp.StatusCode, wantCode) - return - } - if wantBody != "" && string(body) != wantBody { - t.Errorf("%s: got HTTP body %q, want %q", desc, body, wantBody) - return - } - } - - // If there's no handlers, or only a root handler, a health checker should be installed. - try("empty mux", http.NewServeMux(), 200, "ok") - mux := http.NewServeMux() - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "root handler") - }) - try("mux with root handler", mux, 200, "ok") - - // If there's a custom health check handler, one should not be installed. - mux = http.NewServeMux() - mux.HandleFunc("/_ah/health", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(418) - io.WriteString(w, "I'm short and stout!") - }) - try("mux with custom health checker", mux, 418, "I'm short and stout!") -} diff --git a/vendor/google.golang.org/appengine/internal/net_test.go b/vendor/google.golang.org/appengine/internal/net_test.go deleted file mode 100644 index 24da8bb2b1..0000000000 --- a/vendor/google.golang.org/appengine/internal/net_test.go +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build !appengine - -package internal - -import ( - "sync" - "testing" - "time" - - netcontext "golang.org/x/net/context" - - basepb "google.golang.org/appengine/internal/base" -) - -func TestDialLimit(t *testing.T) { - // Fill up semaphore with false acquisitions to permit only two TCP connections at a time. - // We don't replace limitSem because that results in a data race when net/http lazily closes connections. - nFake := cap(limitSem) - 2 - for i := 0; i < nFake; i++ { - limitSem <- 1 - } - defer func() { - for i := 0; i < nFake; i++ { - <-limitSem - } - }() - - f, c, cleanup := setup() // setup is in api_test.go - defer cleanup() - f.hang = make(chan int) - - // If we make two RunSlowly RPCs (which will wait for f.hang to be strobed), - // then the simple Non200 RPC should hang. - var wg sync.WaitGroup - wg.Add(2) - for i := 0; i < 2; i++ { - go func() { - defer wg.Done() - Call(toContext(c), "errors", "RunSlowly", &basepb.VoidProto{}, &basepb.VoidProto{}) - }() - } - time.Sleep(50 * time.Millisecond) // let those two RPCs start - - ctx, _ := netcontext.WithTimeout(toContext(c), 50*time.Millisecond) - err := Call(ctx, "errors", "Non200", &basepb.VoidProto{}, &basepb.VoidProto{}) - if err != errTimeout { - t.Errorf("Non200 RPC returned with err %v, want errTimeout", err) - } - - // Drain the two RunSlowly calls. - f.hang <- 1 - f.hang <- 1 - wg.Wait() -} diff --git a/vendor/google.golang.org/appengine/namespace_test.go b/vendor/google.golang.org/appengine/namespace_test.go deleted file mode 100644 index 847f640bd0..0000000000 --- a/vendor/google.golang.org/appengine/namespace_test.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package appengine - -import ( - "testing" - - "golang.org/x/net/context" -) - -func TestNamespaceValidity(t *testing.T) { - testCases := []struct { - namespace string - ok bool - }{ - // data from Python's namespace_manager_test.py - {"", true}, - {"__a.namespace.123__", true}, - {"-_A....NAMESPACE-_", true}, - {"-", true}, - {".", true}, - {".-", true}, - - {"?", false}, - {"+", false}, - {"!", false}, - {" ", false}, - } - for _, tc := range testCases { - _, err := Namespace(context.Background(), tc.namespace) - if err == nil && !tc.ok { - t.Errorf("Namespace %q should be rejected, but wasn't", tc.namespace) - } else if err != nil && tc.ok { - t.Errorf("Namespace %q should be accepted, but wasn't", tc.namespace) - } - } -} diff --git a/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go b/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go index 8867ae7812..fb104e6dfb 100644 --- a/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go +++ b/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go @@ -1,21 +1,12 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/rpc/status.proto -/* -Package status is a generated protocol buffer package. - -It is generated from these files: - google/rpc/status.proto - -It has these top-level messages: - Status -*/ -package status +package status // import "google.golang.org/genproto/googleapis/rpc/status" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" -import google_protobuf "github.com/golang/protobuf/ptypes/any" +import any "github.com/golang/protobuf/ptypes/any" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal @@ -89,13 +80,35 @@ type Status struct { Message string `protobuf:"bytes,2,opt,name=message" json:"message,omitempty"` // A list of messages that carry the error details. There is a common set of // message types for APIs to use. - Details []*google_protobuf.Any `protobuf:"bytes,3,rep,name=details" json:"details,omitempty"` + Details []*any.Any `protobuf:"bytes,3,rep,name=details" json:"details,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Status) Reset() { *m = Status{} } +func (m *Status) String() string { return proto.CompactTextString(m) } +func (*Status) ProtoMessage() {} +func (*Status) Descriptor() ([]byte, []int) { + return fileDescriptor_status_c656c685916bdf47, []int{0} +} +func (m *Status) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Status.Unmarshal(m, b) +} +func (m *Status) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Status.Marshal(b, m, deterministic) +} +func (dst *Status) XXX_Merge(src proto.Message) { + xxx_messageInfo_Status.Merge(dst, src) +} +func (m *Status) XXX_Size() int { + return xxx_messageInfo_Status.Size(m) +} +func (m *Status) XXX_DiscardUnknown() { + xxx_messageInfo_Status.DiscardUnknown(m) } -func (m *Status) Reset() { *m = Status{} } -func (m *Status) String() string { return proto.CompactTextString(m) } -func (*Status) ProtoMessage() {} -func (*Status) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } +var xxx_messageInfo_Status proto.InternalMessageInfo func (m *Status) GetCode() int32 { if m != nil { @@ -111,7 +124,7 @@ func (m *Status) GetMessage() string { return "" } -func (m *Status) GetDetails() []*google_protobuf.Any { +func (m *Status) GetDetails() []*any.Any { if m != nil { return m.Details } @@ -122,9 +135,9 @@ func init() { proto.RegisterType((*Status)(nil), "google.rpc.Status") } -func init() { proto.RegisterFile("google/rpc/status.proto", fileDescriptor0) } +func init() { proto.RegisterFile("google/rpc/status.proto", fileDescriptor_status_c656c685916bdf47) } -var fileDescriptor0 = []byte{ +var fileDescriptor_status_c656c685916bdf47 = []byte{ // 209 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4f, 0xcf, 0xcf, 0x4f, 0xcf, 0x49, 0xd5, 0x2f, 0x2a, 0x48, 0xd6, 0x2f, 0x2e, 0x49, 0x2c, 0x29, 0x2d, 0xd6, 0x2b, 0x28, diff --git a/vendor/google.golang.org/grpc/.travis.yml b/vendor/google.golang.org/grpc/.travis.yml index 22bf25004a..3c2621ab75 100644 --- a/vendor/google.golang.org/grpc/.travis.yml +++ b/vendor/google.golang.org/grpc/.travis.yml @@ -1,20 +1,24 @@ language: go go: + - 1.6.x - 1.7.x - 1.8.x - 1.9.x + - 1.10.x matrix: include: - - go: 1.9.x - env: ARCH=386 + - go: 1.10.x + env: RUN386=1 go_import_path: google.golang.org/grpc before_install: - - if [[ "$TRAVIS_GO_VERSION" = 1.9* && "$ARCH" != "386" ]]; then ./vet.sh -install || exit 1; fi + - if [[ -n "$RUN386" ]]; then export GOARCH=386; fi + - if [[ "$TRAVIS_GO_VERSION" = 1.10* && "$GOARCH" != "386" ]]; then ./vet.sh -install || exit 1; fi script: - - if [[ "$TRAVIS_GO_VERSION" = 1.9* && "$ARCH" != "386" ]]; then ./vet.sh || exit 1; fi - - make test testrace + - if [[ "$TRAVIS_GO_VERSION" = 1.10* && "$GOARCH" != "386" ]]; then ./vet.sh || exit 1; fi + - make test || exit 1 + - if [[ "$GOARCH" != "386" ]]; then make testrace; fi diff --git a/vendor/google.golang.org/grpc/CONTRIBUTING.md b/vendor/google.golang.org/grpc/CONTRIBUTING.md index a5c6e06e25..0863eb26b6 100644 --- a/vendor/google.golang.org/grpc/CONTRIBUTING.md +++ b/vendor/google.golang.org/grpc/CONTRIBUTING.md @@ -7,7 +7,7 @@ If you are new to github, please start by reading [Pull Request howto](https://h ## Legal requirements In order to protect both you and ourselves, you will need to sign the -[Contributor License Agreement](https://cla.developers.google.com/clas). +[Contributor License Agreement](https://identity.linuxfoundation.org/projects/cncf). ## Guidelines for Pull Requests How to get your contributions merged smoothly and quickly. @@ -27,6 +27,10 @@ How to get your contributions merged smoothly and quickly. - Keep your PR up to date with upstream/master (if there are merge conflicts, we can't really merge your change). - **All tests need to be passing** before your change can be merged. We recommend you **run tests locally** before creating your PR to catch breakages early on. + - `make all` to test everything, OR + - `make vet` to catch vet errors + - `make test` to run the tests + - `make testrace` to run tests in race mode - Exceptions to the rules can be made if there's a compelling reason for doing so. diff --git a/vendor/google.golang.org/grpc/Makefile b/vendor/google.golang.org/grpc/Makefile index 39606b564a..6f393a808d 100644 --- a/vendor/google.golang.org/grpc/Makefile +++ b/vendor/google.golang.org/grpc/Makefile @@ -1,4 +1,4 @@ -all: test testrace +all: vet test testrace deps: go get -d -v google.golang.org/grpc/... @@ -22,11 +22,14 @@ proto: fi go generate google.golang.org/grpc/... +vet: + ./vet.sh + test: testdeps - go test -cpu 1,4 google.golang.org/grpc/... + go test -cpu 1,4 -timeout 5m google.golang.org/grpc/... testrace: testdeps - go test -race -cpu 1,4 google.golang.org/grpc/... + go test -race -cpu 1,4 -timeout 7m google.golang.org/grpc/... clean: go clean -i google.golang.org/grpc/... @@ -39,7 +42,7 @@ clean: updatetestdeps \ build \ proto \ + vet \ test \ testrace \ - clean \ - coverage + clean diff --git a/vendor/google.golang.org/grpc/README.md b/vendor/google.golang.org/grpc/README.md index 622a5dc3e8..789adfd653 100644 --- a/vendor/google.golang.org/grpc/README.md +++ b/vendor/google.golang.org/grpc/README.md @@ -1,6 +1,6 @@ # gRPC-Go -[![Build Status](https://travis-ci.org/grpc/grpc-go.svg)](https://travis-ci.org/grpc/grpc-go) [![GoDoc](https://godoc.org/google.golang.org/grpc?status.svg)](https://godoc.org/google.golang.org/grpc) +[![Build Status](https://travis-ci.org/grpc/grpc-go.svg)](https://travis-ci.org/grpc/grpc-go) [![GoDoc](https://godoc.org/google.golang.org/grpc?status.svg)](https://godoc.org/google.golang.org/grpc) [![GoReportCard](https://goreportcard.com/badge/grpc/grpc-go)](https://goreportcard.com/report/github.com/grpc/grpc-go) The Go implementation of [gRPC](https://grpc.io/): A high performance, open source, general RPC framework that puts mobile and HTTP/2 first. For more information see the [gRPC Quick Start: Go](https://grpc.io/docs/quickstart/go.html) guide. @@ -16,7 +16,7 @@ $ go get -u google.golang.org/grpc Prerequisites ------------- -This requires Go 1.7 or later. +This requires Go 1.6 or later. Go 1.7 will be required soon. Constraints ----------- diff --git a/vendor/google.golang.org/grpc/backoff.go b/vendor/google.golang.org/grpc/backoff.go index 090fbe87c5..c40facce51 100644 --- a/vendor/google.golang.org/grpc/backoff.go +++ b/vendor/google.golang.org/grpc/backoff.go @@ -25,14 +25,12 @@ import ( // DefaultBackoffConfig uses values specified for backoff in // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. -var ( - DefaultBackoffConfig = BackoffConfig{ - MaxDelay: 120 * time.Second, - baseDelay: 1.0 * time.Second, - factor: 1.6, - jitter: 0.2, - } -) +var DefaultBackoffConfig = BackoffConfig{ + MaxDelay: 120 * time.Second, + baseDelay: 1.0 * time.Second, + factor: 1.6, + jitter: 0.2, +} // backoffStrategy defines the methodology for backing off after a grpc // connection failure. diff --git a/vendor/google.golang.org/grpc/balancer.go b/vendor/google.golang.org/grpc/balancer.go index ab65049ddc..e1730166cd 100644 --- a/vendor/google.golang.org/grpc/balancer.go +++ b/vendor/google.golang.org/grpc/balancer.go @@ -28,10 +28,12 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/naming" + "google.golang.org/grpc/status" ) // Address represents a server the client connects to. -// This is the EXPERIMENTAL API and may be changed or extended in the future. +// +// Deprecated: please use package balancer. type Address struct { // Addr is the server address on which a connection will be established. Addr string @@ -41,6 +43,8 @@ type Address struct { } // BalancerConfig specifies the configurations for Balancer. +// +// Deprecated: please use package balancer. type BalancerConfig struct { // DialCreds is the transport credential the Balancer implementation can // use to dial to a remote load balancer server. The Balancer implementations @@ -53,7 +57,8 @@ type BalancerConfig struct { } // BalancerGetOptions configures a Get call. -// This is the EXPERIMENTAL API and may be changed or extended in the future. +// +// Deprecated: please use package balancer. type BalancerGetOptions struct { // BlockingWait specifies whether Get should block when there is no // connected address. @@ -61,7 +66,8 @@ type BalancerGetOptions struct { } // Balancer chooses network addresses for RPCs. -// This is the EXPERIMENTAL API and may be changed or extended in the future. +// +// Deprecated: please use package balancer. type Balancer interface { // Start does the initialization work to bootstrap a Balancer. For example, // this function may start the name resolution and watch the updates. It will @@ -134,6 +140,8 @@ func downErrorf(timeout, temporary bool, format string, a ...interface{}) downEr // RoundRobin returns a Balancer that selects addresses round-robin. It uses r to watch // the name resolution updates and updates the addresses available correspondingly. +// +// Deprecated: please use package balancer/roundrobin. func RoundRobin(r naming.Resolver) Balancer { return &roundRobin{r: r} } @@ -310,7 +318,7 @@ func (rr *roundRobin) Get(ctx context.Context, opts BalancerGetOptions) (addr Ad if !opts.BlockingWait { if len(rr.addrs) == 0 { rr.mu.Unlock() - err = Errorf(codes.Unavailable, "there is no address available") + err = status.Errorf(codes.Unavailable, "there is no address available") return } // Returns the next addr on rr.addrs for failfast RPCs. diff --git a/vendor/google.golang.org/grpc/balancer/balancer.go b/vendor/google.golang.org/grpc/balancer/balancer.go index 84e10b630e..63b8d71371 100644 --- a/vendor/google.golang.org/grpc/balancer/balancer.go +++ b/vendor/google.golang.org/grpc/balancer/balancer.go @@ -23,6 +23,7 @@ package balancer import ( "errors" "net" + "strings" "golang.org/x/net/context" "google.golang.org/grpc/connectivity" @@ -33,24 +34,26 @@ import ( var ( // m is a map from name to balancer builder. m = make(map[string]Builder) - // defaultBuilder is the default balancer to use. - defaultBuilder Builder // TODO(bar) install pickfirst as default. ) -// Register registers the balancer builder to the balancer map. -// b.Name will be used as the name registered with this builder. +// Register registers the balancer builder to the balancer map. b.Name +// (lowercased) will be used as the name registered with this builder. +// +// NOTE: this function must only be called during initialization time (i.e. in +// an init() function), and is not thread-safe. If multiple Balancers are +// registered with the same name, the one registered last will take effect. func Register(b Builder) { - m[b.Name()] = b + m[strings.ToLower(b.Name())] = b } // Get returns the resolver builder registered with the given name. -// If no builder is register with the name, the default pickfirst will -// be used. +// Note that the compare is done in a case-insenstive fashion. +// If no builder is register with the name, nil will be returned. func Get(name string) Builder { - if b, ok := m[name]; ok { + if b, ok := m[strings.ToLower(name)]; ok { return b } - return defaultBuilder + return nil } // SubConn represents a gRPC sub connection. @@ -66,6 +69,11 @@ func Get(name string) Builder { // When the connection encounters an error, it will reconnect immediately. // When the connection becomes IDLE, it will not reconnect unless Connect is // called. +// +// This interface is to be implemented by gRPC. Users should not need a +// brand new implementation of this interface. For the situations like +// testing, the new implementation should embed this interface. This allows +// gRPC to add new methods to this interface. type SubConn interface { // UpdateAddresses updates the addresses used in this SubConn. // gRPC checks if currently-connected address is still in the new list. @@ -83,6 +91,11 @@ type SubConn interface { type NewSubConnOptions struct{} // ClientConn represents a gRPC ClientConn. +// +// This interface is to be implemented by gRPC. Users should not need a +// brand new implementation of this interface. For the situations like +// testing, the new implementation should embed this interface. This allows +// gRPC to add new methods to this interface. type ClientConn interface { // NewSubConn is called by balancer to create a new SubConn. // It doesn't block and wait for the connections to be established. @@ -99,6 +112,9 @@ type ClientConn interface { // on the new picker to pick new SubConn. UpdateBalancerState(s connectivity.State, p Picker) + // ResolveNow is called by balancer to notify gRPC to do a name resolving. + ResolveNow(resolver.ResolveNowOption) + // Target returns the dial target for this ClientConn. Target() string } @@ -113,6 +129,8 @@ type BuildOptions struct { // to a remote load balancer server. The Balancer implementations // can ignore this if it doesn't need to talk to remote balancer. Dialer func(context.Context, string) (net.Conn, error) + // ChannelzParentID is the entity parent's channelz unique identification number. + ChannelzParentID int64 } // Builder creates a balancer. @@ -131,6 +149,10 @@ type PickOptions struct{} type DoneInfo struct { // Err is the rpc error the RPC finished with. It could be nil. Err error + // BytesSent indicates if any bytes have been sent to the server. + BytesSent bool + // BytesReceived indicates if any byte has been received from the server. + BytesReceived bool } var ( @@ -143,7 +165,7 @@ var ( ) // Picker is used by gRPC to pick a SubConn to send an RPC. -// Balancer is expected to generate a new picker from its snapshot everytime its +// Balancer is expected to generate a new picker from its snapshot every time its // internal state has changed. // // The pickers used by gRPC can be updated by ClientConn.UpdateBalancerState(). @@ -161,7 +183,7 @@ type Picker interface { // If a SubConn is returned: // - If it is READY, gRPC will send the RPC on it; // - If it is not ready, or becomes not ready after it's returned, gRPC will block - // this call until a new picker is updated and will call pick on the new picker. + // until UpdateBalancerState() is called and will call pick on the new picker. // // If the returned error is not nil: // - If the error is ErrNoSubConnAvailable, gRPC will block until UpdateBalancerState() diff --git a/vendor/google.golang.org/grpc/balancer/base/balancer.go b/vendor/google.golang.org/grpc/balancer/base/balancer.go new file mode 100644 index 0000000000..23d13511bb --- /dev/null +++ b/vendor/google.golang.org/grpc/balancer/base/balancer.go @@ -0,0 +1,208 @@ +/* + * + * Copyright 2017 gRPC 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 base + +import ( + "golang.org/x/net/context" + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/resolver" +) + +type baseBuilder struct { + name string + pickerBuilder PickerBuilder +} + +func (bb *baseBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer { + return &baseBalancer{ + cc: cc, + pickerBuilder: bb.pickerBuilder, + + subConns: make(map[resolver.Address]balancer.SubConn), + scStates: make(map[balancer.SubConn]connectivity.State), + csEvltr: &connectivityStateEvaluator{}, + // Initialize picker to a picker that always return + // ErrNoSubConnAvailable, because when state of a SubConn changes, we + // may call UpdateBalancerState with this picker. + picker: NewErrPicker(balancer.ErrNoSubConnAvailable), + } +} + +func (bb *baseBuilder) Name() string { + return bb.name +} + +type baseBalancer struct { + cc balancer.ClientConn + pickerBuilder PickerBuilder + + csEvltr *connectivityStateEvaluator + state connectivity.State + + subConns map[resolver.Address]balancer.SubConn + scStates map[balancer.SubConn]connectivity.State + picker balancer.Picker +} + +func (b *baseBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { + if err != nil { + grpclog.Infof("base.baseBalancer: HandleResolvedAddrs called with error %v", err) + return + } + grpclog.Infoln("base.baseBalancer: got new resolved addresses: ", addrs) + // addrsSet is the set converted from addrs, it's used for quick lookup of an address. + addrsSet := make(map[resolver.Address]struct{}) + for _, a := range addrs { + addrsSet[a] = struct{}{} + if _, ok := b.subConns[a]; !ok { + // a is a new address (not existing in b.subConns). + sc, err := b.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) + if err != nil { + grpclog.Warningf("base.baseBalancer: failed to create new SubConn: %v", err) + continue + } + b.subConns[a] = sc + b.scStates[sc] = connectivity.Idle + sc.Connect() + } + } + for a, sc := range b.subConns { + // a was removed by resolver. + if _, ok := addrsSet[a]; !ok { + b.cc.RemoveSubConn(sc) + delete(b.subConns, a) + // Keep the state of this sc in b.scStates until sc's state becomes Shutdown. + // The entry will be deleted in HandleSubConnStateChange. + } + } +} + +// regeneratePicker takes a snapshot of the balancer, and generates a picker +// from it. The picker is +// - errPicker with ErrTransientFailure if the balancer is in TransientFailure, +// - built by the pickerBuilder with all READY SubConns otherwise. +func (b *baseBalancer) regeneratePicker() { + if b.state == connectivity.TransientFailure { + b.picker = NewErrPicker(balancer.ErrTransientFailure) + return + } + readySCs := make(map[resolver.Address]balancer.SubConn) + + // Filter out all ready SCs from full subConn map. + for addr, sc := range b.subConns { + if st, ok := b.scStates[sc]; ok && st == connectivity.Ready { + readySCs[addr] = sc + } + } + b.picker = b.pickerBuilder.Build(readySCs) +} + +func (b *baseBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { + grpclog.Infof("base.baseBalancer: handle SubConn state change: %p, %v", sc, s) + oldS, ok := b.scStates[sc] + if !ok { + grpclog.Infof("base.baseBalancer: got state changes for an unknown SubConn: %p, %v", sc, s) + return + } + b.scStates[sc] = s + switch s { + case connectivity.Idle: + sc.Connect() + case connectivity.Shutdown: + // When an address was removed by resolver, b called RemoveSubConn but + // kept the sc's state in scStates. Remove state for this sc here. + delete(b.scStates, sc) + } + + oldAggrState := b.state + b.state = b.csEvltr.recordTransition(oldS, s) + + // Regenerate picker when one of the following happens: + // - this sc became ready from not-ready + // - this sc became not-ready from ready + // - the aggregated state of balancer became TransientFailure from non-TransientFailure + // - the aggregated state of balancer became non-TransientFailure from TransientFailure + if (s == connectivity.Ready) != (oldS == connectivity.Ready) || + (b.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) { + b.regeneratePicker() + } + + b.cc.UpdateBalancerState(b.state, b.picker) +} + +// Close is a nop because base balancer doesn't have internal state to clean up, +// and it doesn't need to call RemoveSubConn for the SubConns. +func (b *baseBalancer) Close() { +} + +// NewErrPicker returns a picker that always returns err on Pick(). +func NewErrPicker(err error) balancer.Picker { + return &errPicker{err: err} +} + +type errPicker struct { + err error // Pick() always returns this err. +} + +func (p *errPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { + return nil, nil, p.err +} + +// connectivityStateEvaluator gets updated by addrConns when their +// states transition, based on which it evaluates the state of +// ClientConn. +type connectivityStateEvaluator struct { + numReady uint64 // Number of addrConns in ready state. + numConnecting uint64 // Number of addrConns in connecting state. + numTransientFailure uint64 // Number of addrConns in transientFailure. +} + +// recordTransition records state change happening in every subConn and based on +// that it evaluates what aggregated state should be. +// It can only transition between Ready, Connecting and TransientFailure. Other states, +// Idle and Shutdown are transitioned into by ClientConn; in the beginning of the connection +// before any subConn is created ClientConn is in idle state. In the end when ClientConn +// closes it is in Shutdown state. +// +// recordTransition should only be called synchronously from the same goroutine. +func (cse *connectivityStateEvaluator) recordTransition(oldState, newState connectivity.State) connectivity.State { + // Update counters. + for idx, state := range []connectivity.State{oldState, newState} { + updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new. + switch state { + case connectivity.Ready: + cse.numReady += updateVal + case connectivity.Connecting: + cse.numConnecting += updateVal + case connectivity.TransientFailure: + cse.numTransientFailure += updateVal + } + } + + // Evaluate. + if cse.numReady > 0 { + return connectivity.Ready + } + if cse.numConnecting > 0 { + return connectivity.Connecting + } + return connectivity.TransientFailure +} diff --git a/vendor/google.golang.org/grpc/balancer/base/base.go b/vendor/google.golang.org/grpc/balancer/base/base.go new file mode 100644 index 0000000000..012ace2f2f --- /dev/null +++ b/vendor/google.golang.org/grpc/balancer/base/base.go @@ -0,0 +1,52 @@ +/* + * + * Copyright 2017 gRPC 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 base defines a balancer base that can be used to build balancers with +// different picking algorithms. +// +// The base balancer creates a new SubConn for each resolved address. The +// provided picker will only be notified about READY SubConns. +// +// This package is the base of round_robin balancer, its purpose is to be used +// to build round_robin like balancers with complex picking algorithms. +// Balancers with more complicated logic should try to implement a balancer +// builder from scratch. +// +// All APIs in this package are experimental. +package base + +import ( + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/resolver" +) + +// PickerBuilder creates balancer.Picker. +type PickerBuilder interface { + // Build takes a slice of ready SubConns, and returns a picker that will be + // used by gRPC to pick a SubConn. + Build(readySCs map[resolver.Address]balancer.SubConn) balancer.Picker +} + +// NewBalancerBuilder returns a balancer builder. The balancers +// built by this builder will use the picker builder to build pickers. +func NewBalancerBuilder(name string, pb PickerBuilder) balancer.Builder { + return &baseBuilder{ + name: name, + pickerBuilder: pb, + } +} diff --git a/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go new file mode 100644 index 0000000000..2eda0a1c21 --- /dev/null +++ b/vendor/google.golang.org/grpc/balancer/roundrobin/roundrobin.go @@ -0,0 +1,79 @@ +/* + * + * Copyright 2017 gRPC 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 roundrobin defines a roundrobin balancer. Roundrobin balancer is +// installed as one of the default balancers in gRPC, users don't need to +// explicitly install this balancer. +package roundrobin + +import ( + "sync" + + "golang.org/x/net/context" + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/balancer/base" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/resolver" +) + +// Name is the name of round_robin balancer. +const Name = "round_robin" + +// newBuilder creates a new roundrobin balancer builder. +func newBuilder() balancer.Builder { + return base.NewBalancerBuilder(Name, &rrPickerBuilder{}) +} + +func init() { + balancer.Register(newBuilder()) +} + +type rrPickerBuilder struct{} + +func (*rrPickerBuilder) Build(readySCs map[resolver.Address]balancer.SubConn) balancer.Picker { + grpclog.Infof("roundrobinPicker: newPicker called with readySCs: %v", readySCs) + var scs []balancer.SubConn + for _, sc := range readySCs { + scs = append(scs, sc) + } + return &rrPicker{ + subConns: scs, + } +} + +type rrPicker struct { + // subConns is the snapshot of the roundrobin balancer when this picker was + // created. The slice is immutable. Each Get() will do a round robin + // selection from it and return the selected SubConn. + subConns []balancer.SubConn + + mu sync.Mutex + next int +} + +func (p *rrPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { + if len(p.subConns) <= 0 { + return nil, nil, balancer.ErrNoSubConnAvailable + } + + p.mu.Lock() + sc := p.subConns[p.next] + p.next = (p.next + 1) % len(p.subConns) + p.mu.Unlock() + return sc, nil, nil +} diff --git a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go index e4a95fd5cd..c23f81706f 100644 --- a/vendor/google.golang.org/grpc/balancer_conn_wrappers.go +++ b/vendor/google.golang.org/grpc/balancer_conn_wrappers.go @@ -19,6 +19,7 @@ package grpc import ( + "fmt" "sync" "google.golang.org/grpc/balancer" @@ -73,7 +74,7 @@ func (b *scStateUpdateBuffer) load() { } } -// get returns the channel that receives a recvMsg in the buffer. +// get returns the channel that the scStateUpdate will be sent to. // // Upon receiving, the caller should call load to send another // scStateChangeTuple onto the channel if there is any. @@ -96,6 +97,9 @@ type ccBalancerWrapper struct { stateChangeQueue *scStateUpdateBuffer resolverUpdateCh chan *resolverUpdate done chan struct{} + + mu sync.Mutex + subConns map[*acBalancerWrapper]struct{} } func newCCBalancerWrapper(cc *ClientConn, b balancer.Builder, bopts balancer.BuildOptions) *ccBalancerWrapper { @@ -104,21 +108,34 @@ func newCCBalancerWrapper(cc *ClientConn, b balancer.Builder, bopts balancer.Bui stateChangeQueue: newSCStateUpdateBuffer(), resolverUpdateCh: make(chan *resolverUpdate, 1), done: make(chan struct{}), + subConns: make(map[*acBalancerWrapper]struct{}), } go ccb.watcher() ccb.balancer = b.Build(ccb, bopts) return ccb } -// watcher balancer functions sequencially, so the balancer can be implemeneted +// watcher balancer functions sequentially, so the balancer can be implemented // lock-free. func (ccb *ccBalancerWrapper) watcher() { for { select { case t := <-ccb.stateChangeQueue.get(): ccb.stateChangeQueue.load() + select { + case <-ccb.done: + ccb.balancer.Close() + return + default: + } ccb.balancer.HandleSubConnStateChange(t.sc, t.state) case t := <-ccb.resolverUpdateCh: + select { + case <-ccb.done: + ccb.balancer.Close() + return + default: + } ccb.balancer.HandleResolvedAddrs(t.addrs, t.err) case <-ccb.done: } @@ -126,6 +143,13 @@ func (ccb *ccBalancerWrapper) watcher() { select { case <-ccb.done: ccb.balancer.Close() + ccb.mu.Lock() + scs := ccb.subConns + ccb.subConns = nil + ccb.mu.Unlock() + for acbw := range scs { + ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) + } return default: } @@ -165,31 +189,54 @@ func (ccb *ccBalancerWrapper) handleResolvedAddrs(addrs []resolver.Address, err } func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { - grpclog.Infof("ccBalancerWrapper: new subconn: %v", addrs) + if len(addrs) <= 0 { + return nil, fmt.Errorf("grpc: cannot create SubConn with empty address list") + } + ccb.mu.Lock() + defer ccb.mu.Unlock() + if ccb.subConns == nil { + return nil, fmt.Errorf("grpc: ClientConn balancer wrapper was closed") + } ac, err := ccb.cc.newAddrConn(addrs) if err != nil { return nil, err } acbw := &acBalancerWrapper{ac: ac} + acbw.ac.mu.Lock() ac.acbw = acbw + acbw.ac.mu.Unlock() + ccb.subConns[acbw] = struct{}{} return acbw, nil } func (ccb *ccBalancerWrapper) RemoveSubConn(sc balancer.SubConn) { - grpclog.Infof("ccBalancerWrapper: removing subconn") acbw, ok := sc.(*acBalancerWrapper) if !ok { return } + ccb.mu.Lock() + defer ccb.mu.Unlock() + if ccb.subConns == nil { + return + } + delete(ccb.subConns, acbw) ccb.cc.removeAddrConn(acbw.getAddrConn(), errConnDrain) } func (ccb *ccBalancerWrapper) UpdateBalancerState(s connectivity.State, p balancer.Picker) { - grpclog.Infof("ccBalancerWrapper: updating state and picker called by balancer: %v, %p", s, p) + ccb.mu.Lock() + defer ccb.mu.Unlock() + if ccb.subConns == nil { + return + } ccb.cc.csMgr.updateState(s) ccb.cc.blockingpicker.updatePicker(p) } +func (ccb *ccBalancerWrapper) ResolveNow(o resolver.ResolveNowOption) { + ccb.cc.resolveNow(o) +} + func (ccb *ccBalancerWrapper) Target() string { return ccb.cc.target } @@ -202,9 +249,12 @@ type acBalancerWrapper struct { } func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { - grpclog.Infof("acBalancerWrapper: UpdateAddresses called with %v", addrs) acbw.mu.Lock() defer acbw.mu.Unlock() + if len(addrs) <= 0 { + acbw.ac.tearDown(errConnDrain) + return + } if !acbw.ac.tryUpdateAddrs(addrs) { cc := acbw.ac.cc acbw.ac.mu.Lock() @@ -228,9 +278,11 @@ func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { return } acbw.ac = ac + ac.mu.Lock() ac.acbw = acbw + ac.mu.Unlock() if acState != connectivity.Idle { - ac.connect(false) + ac.connect() } } } @@ -238,7 +290,7 @@ func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { func (acbw *acBalancerWrapper) Connect() { acbw.mu.Lock() defer acbw.mu.Unlock() - acbw.ac.connect(false) + acbw.ac.connect() } func (acbw *acBalancerWrapper) getAddrConn() *addrConn { diff --git a/vendor/google.golang.org/grpc/balancer_test.go b/vendor/google.golang.org/grpc/balancer_test.go deleted file mode 100644 index 29dbe0a676..0000000000 --- a/vendor/google.golang.org/grpc/balancer_test.go +++ /dev/null @@ -1,798 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 grpc - -import ( - "fmt" - "math" - "strconv" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - _ "google.golang.org/grpc/grpclog/glogger" - "google.golang.org/grpc/naming" - "google.golang.org/grpc/test/leakcheck" -) - -type testWatcher struct { - // the channel to receives name resolution updates - update chan *naming.Update - // the side channel to get to know how many updates in a batch - side chan int - // the channel to notifiy update injector that the update reading is done - readDone chan int -} - -func (w *testWatcher) Next() (updates []*naming.Update, err error) { - n := <-w.side - if n == 0 { - return nil, fmt.Errorf("w.side is closed") - } - for i := 0; i < n; i++ { - u := <-w.update - if u != nil { - updates = append(updates, u) - } - } - w.readDone <- 0 - return -} - -func (w *testWatcher) Close() { - close(w.side) -} - -// Inject naming resolution updates to the testWatcher. -func (w *testWatcher) inject(updates []*naming.Update) { - w.side <- len(updates) - for _, u := range updates { - w.update <- u - } - <-w.readDone -} - -type testNameResolver struct { - w *testWatcher - addr string -} - -func (r *testNameResolver) Resolve(target string) (naming.Watcher, error) { - r.w = &testWatcher{ - update: make(chan *naming.Update, 1), - side: make(chan int, 1), - readDone: make(chan int), - } - r.w.side <- 1 - r.w.update <- &naming.Update{ - Op: naming.Add, - Addr: r.addr, - } - go func() { - <-r.w.readDone - }() - return r.w, nil -} - -func startServers(t *testing.T, numServers int, maxStreams uint32) ([]*server, *testNameResolver, func()) { - var servers []*server - for i := 0; i < numServers; i++ { - s := newTestServer() - servers = append(servers, s) - go s.start(t, 0, maxStreams) - s.wait(t, 2*time.Second) - } - // Point to server[0] - addr := "localhost:" + servers[0].port - return servers, &testNameResolver{ - addr: addr, - }, func() { - for i := 0; i < numServers; i++ { - servers[i].stop() - } - } -} - -func TestNameDiscovery(t *testing.T) { - defer leakcheck.Check(t) - // Start 2 servers on 2 ports. - numServers := 2 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - req := "port" - var reply string - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[0].port { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want %s", err, servers[0].port) - } - // Inject the name resolution change to remove servers[0] and add servers[1]. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }) - updates = append(updates, &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - }) - r.w.inject(updates) - // Loop until the rpcs in flight talks to servers[1]. - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } -} - -func TestEmptyAddrs(t *testing.T) { - defer leakcheck.Check(t) - servers, r, cleanup := startServers(t, 1, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - var reply string - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc); err != nil || reply != expectedResponse { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, reply = %q, want %q, <nil>", err, reply, expectedResponse) - } - // Inject name resolution change to remove the server so that there is no address - // available after that. - u := &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - } - r.w.inject([]*naming.Update{u}) - // Loop until the above updates apply. - for { - time.Sleep(10 * time.Millisecond) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if err := Invoke(ctx, "/foo/bar", &expectedRequest, &reply, cc); err != nil { - cancel() - break - } - cancel() - } -} - -func TestRoundRobin(t *testing.T) { - defer leakcheck.Check(t) - // Start 3 servers on 3 ports. - numServers := 3 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] to the service discovery. - u := &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - } - r.w.inject([]*naming.Update{u}) - req := "port" - var reply string - // Loop until servers[1] is up - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } - // Add server2[2] to the service discovery. - u = &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[2].port, - } - r.w.inject([]*naming.Update{u}) - // Loop until both servers[2] are up. - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[2].port { - break - } - time.Sleep(10 * time.Millisecond) - } - // Check the incoming RPCs served in a round-robin manner. - for i := 0; i < 10; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[i%numServers].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", i, err, servers[i%numServers].port) - } - } -} - -func TestCloseWithPendingRPC(t *testing.T) { - defer leakcheck.Check(t) - servers, r, cleanup := startServers(t, 1, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - var reply string - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); err != nil { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want %s", err, servers[0].port) - } - // Remove the server. - updates := []*naming.Update{{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }} - r.w.inject(updates) - // Loop until the above update applies. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if err := Invoke(ctx, "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); Code(err) == codes.DeadlineExceeded { - cancel() - break - } - time.Sleep(10 * time.Millisecond) - cancel() - } - // Issue 2 RPCs which should be completed with error status once cc is closed. - var wg sync.WaitGroup - wg.Add(2) - go func() { - defer wg.Done() - var reply string - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); err == nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want not nil", err) - } - }() - go func() { - defer wg.Done() - var reply string - time.Sleep(5 * time.Millisecond) - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); err == nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want not nil", err) - } - }() - time.Sleep(5 * time.Millisecond) - cc.Close() - wg.Wait() -} - -func TestGetOnWaitChannel(t *testing.T) { - defer leakcheck.Check(t) - servers, r, cleanup := startServers(t, 1, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Remove all servers so that all upcoming RPCs will block on waitCh. - updates := []*naming.Update{{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }} - r.w.inject(updates) - for { - var reply string - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if err := Invoke(ctx, "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); Code(err) == codes.DeadlineExceeded { - cancel() - break - } - cancel() - time.Sleep(10 * time.Millisecond) - } - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - var reply string - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); err != nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want <nil>", err) - } - }() - // Add a connected server to get the above RPC through. - updates = []*naming.Update{{ - Op: naming.Add, - Addr: "localhost:" + servers[0].port, - }} - r.w.inject(updates) - // Wait until the above RPC succeeds. - wg.Wait() -} - -func TestOneServerDown(t *testing.T) { - defer leakcheck.Check(t) - // Start 2 servers. - numServers := 2 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] to the service discovery. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - }) - r.w.inject(updates) - req := "port" - var reply string - // Loop until servers[1] is up - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } - - var wg sync.WaitGroup - numRPC := 100 - sleepDuration := 10 * time.Millisecond - wg.Add(1) - go func() { - time.Sleep(sleepDuration) - // After sleepDuration, kill server[0]. - servers[0].stop() - wg.Done() - }() - - // All non-failfast RPCs should not block because there's at least one connection available. - for i := 0; i < numRPC; i++ { - wg.Add(1) - go func() { - time.Sleep(sleepDuration) - // After sleepDuration, invoke RPC. - // server[0] is killed around the same time to make it racy between balancer and gRPC internals. - Invoke(context.Background(), "/foo/bar", &req, &reply, cc, FailFast(false)) - wg.Done() - }() - } - wg.Wait() -} - -func TestOneAddressRemoval(t *testing.T) { - defer leakcheck.Check(t) - // Start 2 servers. - numServers := 2 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] to the service discovery. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - }) - r.w.inject(updates) - req := "port" - var reply string - // Loop until servers[1] is up - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } - - var wg sync.WaitGroup - numRPC := 100 - sleepDuration := 10 * time.Millisecond - wg.Add(1) - go func() { - time.Sleep(sleepDuration) - // After sleepDuration, delete server[0]. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }) - r.w.inject(updates) - wg.Done() - }() - - // All non-failfast RPCs should not fail because there's at least one connection available. - for i := 0; i < numRPC; i++ { - wg.Add(1) - go func() { - var reply string - time.Sleep(sleepDuration) - // After sleepDuration, invoke RPC. - // server[0] is removed around the same time to make it racy between balancer and gRPC internals. - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); err != nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want not nil", err) - } - wg.Done() - }() - } - wg.Wait() -} - -func checkServerUp(t *testing.T, currentServer *server) { - req := "port" - port := currentServer.port - cc, err := Dial("localhost:"+port, WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - var reply string - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == port { - break - } - time.Sleep(10 * time.Millisecond) - } -} - -func TestPickFirstEmptyAddrs(t *testing.T) { - defer leakcheck.Check(t) - servers, r, cleanup := startServers(t, 1, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - var reply string - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc); err != nil || reply != expectedResponse { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, reply = %q, want %q, <nil>", err, reply, expectedResponse) - } - // Inject name resolution change to remove the server so that there is no address - // available after that. - u := &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - } - r.w.inject([]*naming.Update{u}) - // Loop until the above updates apply. - for { - time.Sleep(10 * time.Millisecond) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if err := Invoke(ctx, "/foo/bar", &expectedRequest, &reply, cc); err != nil { - cancel() - break - } - cancel() - } -} - -func TestPickFirstCloseWithPendingRPC(t *testing.T) { - defer leakcheck.Check(t) - servers, r, cleanup := startServers(t, 1, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - var reply string - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); err != nil { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want %s", err, servers[0].port) - } - // Remove the server. - updates := []*naming.Update{{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }} - r.w.inject(updates) - // Loop until the above update applies. - for { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) - if err := Invoke(ctx, "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); Code(err) == codes.DeadlineExceeded { - cancel() - break - } - time.Sleep(10 * time.Millisecond) - cancel() - } - // Issue 2 RPCs which should be completed with error status once cc is closed. - var wg sync.WaitGroup - wg.Add(2) - go func() { - defer wg.Done() - var reply string - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); err == nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want not nil", err) - } - }() - go func() { - defer wg.Done() - var reply string - time.Sleep(5 * time.Millisecond) - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); err == nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want not nil", err) - } - }() - time.Sleep(5 * time.Millisecond) - cc.Close() - wg.Wait() -} - -func TestPickFirstOrderAllServerUp(t *testing.T) { - defer leakcheck.Check(t) - // Start 3 servers on 3 ports. - numServers := 3 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] and [2] to the service discovery. - u := &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - } - r.w.inject([]*naming.Update{u}) - - u = &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[2].port, - } - r.w.inject([]*naming.Update{u}) - - // Loop until all 3 servers are up - checkServerUp(t, servers[0]) - checkServerUp(t, servers[1]) - checkServerUp(t, servers[2]) - - // Check the incoming RPCs served in server[0] - req := "port" - var reply string - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Delete server[0] in the balancer, the incoming RPCs served in server[1] - // For test addrconn, close server[0] instead - u = &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - } - r.w.inject([]*naming.Update{u}) - // Loop until it changes to server[1] - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Add server[0] back to the balancer, the incoming RPCs served in server[1] - // Add is append operation, the order of Notify now is {server[1].port server[2].port server[0].port} - u = &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[0].port, - } - r.w.inject([]*naming.Update{u}) - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Delete server[1] in the balancer, the incoming RPCs served in server[2] - u = &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[1].port, - } - r.w.inject([]*naming.Update{u}) - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[2].port { - break - } - time.Sleep(1 * time.Second) - } - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[2].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 2, err, servers[2].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Delete server[2] in the balancer, the incoming RPCs served in server[0] - u = &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[2].port, - } - r.w.inject([]*naming.Update{u}) - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[0].port { - break - } - time.Sleep(1 * time.Second) - } - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } -} - -func TestPickFirstOrderOneServerDown(t *testing.T) { - defer leakcheck.Check(t) - // Start 3 servers on 3 ports. - numServers := 3 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] and [2] to the service discovery. - u := &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - } - r.w.inject([]*naming.Update{u}) - - u = &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[2].port, - } - r.w.inject([]*naming.Update{u}) - - // Loop until all 3 servers are up - checkServerUp(t, servers[0]) - checkServerUp(t, servers[1]) - checkServerUp(t, servers[2]) - - // Check the incoming RPCs served in server[0] - req := "port" - var reply string - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } - - // server[0] down, incoming RPCs served in server[1], but the order of Notify still remains - // {server[0] server[1] server[2]} - servers[0].stop() - // Loop until it changes to server[1] - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[1].port { - break - } - time.Sleep(10 * time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // up the server[0] back, the incoming RPCs served in server[1] - p, _ := strconv.Atoi(servers[0].port) - servers[0] = newTestServer() - go servers[0].start(t, p, math.MaxUint32) - defer servers[0].stop() - servers[0].wait(t, 2*time.Second) - checkServerUp(t, servers[0]) - - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Delete server[1] in the balancer, the incoming RPCs served in server[0] - u = &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[1].port, - } - r.w.inject([]*naming.Update{u}) - for { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[0].port { - break - } - time.Sleep(1 * time.Second) - } - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } -} - -func TestPickFirstOneAddressRemoval(t *testing.T) { - defer leakcheck.Check(t) - // Start 2 servers. - numServers := 2 - servers, r, cleanup := startServers(t, numServers, math.MaxUint32) - defer cleanup() - cc, err := Dial("localhost:"+servers[0].port, WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - defer cc.Close() - // Add servers[1] to the service discovery. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - }) - r.w.inject(updates) - - // Create a new cc to Loop until servers[1] is up - checkServerUp(t, servers[0]) - checkServerUp(t, servers[1]) - - var wg sync.WaitGroup - numRPC := 100 - sleepDuration := 10 * time.Millisecond - wg.Add(1) - go func() { - time.Sleep(sleepDuration) - // After sleepDuration, delete server[0]. - var updates []*naming.Update - updates = append(updates, &naming.Update{ - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }) - r.w.inject(updates) - wg.Done() - }() - - // All non-failfast RPCs should not fail because there's at least one connection available. - for i := 0; i < numRPC; i++ { - wg.Add(1) - go func() { - var reply string - time.Sleep(sleepDuration) - // After sleepDuration, invoke RPC. - // server[0] is removed around the same time to make it racy between balancer and gRPC internals. - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc, FailFast(false)); err != nil { - t.Errorf("grpc.Invoke(_, _, _, _, _) = %v, want not nil", err) - } - wg.Done() - }() - } - wg.Wait() -} diff --git a/vendor/google.golang.org/grpc/balancer_v1_wrapper.go b/vendor/google.golang.org/grpc/balancer_v1_wrapper.go index 9d0616080a..b7abc6b745 100644 --- a/vendor/google.golang.org/grpc/balancer_v1_wrapper.go +++ b/vendor/google.golang.org/grpc/balancer_v1_wrapper.go @@ -19,6 +19,7 @@ package grpc import ( + "strings" "sync" "golang.org/x/net/context" @@ -27,6 +28,7 @@ import ( "google.golang.org/grpc/connectivity" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/resolver" + "google.golang.org/grpc/status" ) type balancerWrapperBuilder struct { @@ -34,20 +36,27 @@ type balancerWrapperBuilder struct { } func (bwb *balancerWrapperBuilder) Build(cc balancer.ClientConn, opts balancer.BuildOptions) balancer.Balancer { - bwb.b.Start(cc.Target(), BalancerConfig{ + targetAddr := cc.Target() + targetSplitted := strings.Split(targetAddr, ":///") + if len(targetSplitted) >= 2 { + targetAddr = targetSplitted[1] + } + + bwb.b.Start(targetAddr, BalancerConfig{ DialCreds: opts.DialCreds, Dialer: opts.Dialer, }) _, pickfirst := bwb.b.(*pickFirst) bw := &balancerWrapper{ - balancer: bwb.b, - pickfirst: pickfirst, - cc: cc, - startCh: make(chan struct{}), - conns: make(map[resolver.Address]balancer.SubConn), - connSt: make(map[balancer.SubConn]*scState), - csEvltr: &connectivityStateEvaluator{}, - state: connectivity.Idle, + balancer: bwb.b, + pickfirst: pickfirst, + cc: cc, + targetAddr: targetAddr, + startCh: make(chan struct{}), + conns: make(map[resolver.Address]balancer.SubConn), + connSt: make(map[balancer.SubConn]*scState), + csEvltr: &connectivityStateEvaluator{}, + state: connectivity.Idle, } cc.UpdateBalancerState(connectivity.Idle, bw) go bw.lbWatcher() @@ -68,7 +77,8 @@ type balancerWrapper struct { balancer Balancer // The v1 balancer. pickfirst bool - cc balancer.ClientConn + cc balancer.ClientConn + targetAddr string // Target without the scheme. // To aggregate the connectivity state. csEvltr *connectivityStateEvaluator @@ -88,12 +98,11 @@ type balancerWrapper struct { // connections accordingly. func (bw *balancerWrapper) lbWatcher() { <-bw.startCh - grpclog.Infof("balancerWrapper: is pickfirst: %v\n", bw.pickfirst) notifyCh := bw.balancer.Notify() if notifyCh == nil { // There's no resolver in the balancer. Connect directly. a := resolver.Address{ - Addr: bw.cc.Target(), + Addr: bw.targetAddr, Type: resolver.Backend, } sc, err := bw.cc.NewSubConn([]resolver.Address{a}, balancer.NewSubConnOptions{}) @@ -103,7 +112,7 @@ func (bw *balancerWrapper) lbWatcher() { bw.mu.Lock() bw.conns[a] = sc bw.connSt[sc] = &scState{ - addr: Address{Addr: bw.cc.Target()}, + addr: Address{Addr: bw.targetAddr}, s: connectivity.Idle, } bw.mu.Unlock() @@ -165,10 +174,10 @@ func (bw *balancerWrapper) lbWatcher() { sc.Connect() } } else { - oldSC.UpdateAddresses(newAddrs) bw.mu.Lock() bw.connSt[oldSC].addr = addrs[0] bw.mu.Unlock() + oldSC.UpdateAddresses(newAddrs) } } else { var ( @@ -221,7 +230,6 @@ func (bw *balancerWrapper) lbWatcher() { } func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { - grpclog.Infof("balancerWrapper: handle subconn state change: %p, %v", sc, s) bw.mu.Lock() defer bw.mu.Unlock() scSt, ok := bw.connSt[sc] @@ -249,7 +257,6 @@ func (bw *balancerWrapper) HandleSubConnStateChange(sc balancer.SubConn, s conne // Remove state for this sc. delete(bw.connSt, sc) } - return } func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) { @@ -262,7 +269,6 @@ func (bw *balancerWrapper) HandleResolvedAddrs([]resolver.Address, error) { } // There should be a resolver inside the balancer. // All updates here, if any, are ignored. - return } func (bw *balancerWrapper) Close() { @@ -274,7 +280,6 @@ func (bw *balancerWrapper) Close() { close(bw.startCh) } bw.balancer.Close() - return } // The picker is the balancerWrapper itself. @@ -310,12 +315,12 @@ func (bw *balancerWrapper) Pick(ctx context.Context, opts balancer.PickOptions) Metadata: a.Metadata, }] if !ok && failfast { - return nil, nil, Errorf(codes.Unavailable, "there is no connection available") + return nil, nil, status.Errorf(codes.Unavailable, "there is no connection available") } if s, ok := bw.connSt[sc]; failfast && (!ok || s.s != connectivity.Ready) { // If the returned sc is not ready and RPC is failfast, // return error, and this RPC will fail. - return nil, nil, Errorf(codes.Unavailable, "there is no connection available") + return nil, nil, status.Errorf(codes.Unavailable, "there is no connection available") } } diff --git a/vendor/google.golang.org/grpc/call.go b/vendor/google.golang.org/grpc/call.go index 1ef2507c35..f73b7d5528 100644 --- a/vendor/google.golang.org/grpc/call.go +++ b/vendor/google.golang.org/grpc/call.go @@ -19,289 +19,75 @@ package grpc import ( - "bytes" - "io" - "time" - "golang.org/x/net/context" - "golang.org/x/net/trace" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/peer" - "google.golang.org/grpc/stats" - "google.golang.org/grpc/status" - "google.golang.org/grpc/transport" ) -// recvResponse receives and parses an RPC response. -// On error, it returns the error and indicates whether the call should be retried. +// Invoke sends the RPC request on the wire and returns after response is +// received. This is typically called by generated code. // -// TODO(zhaoq): Check whether the received message sequence is valid. -// TODO ctx is used for stats collection and processing. It is the context passed from the application. -func recvResponse(ctx context.Context, dopts dialOptions, t transport.ClientTransport, c *callInfo, stream *transport.Stream, reply interface{}) (err error) { - // Try to acquire header metadata from the server if there is any. - defer func() { - if err != nil { - if _, ok := err.(transport.ConnectionError); !ok { - t.CloseStream(stream, err) - } - } - }() - c.headerMD, err = stream.Header() - if err != nil { - return - } - p := &parser{r: stream} - var inPayload *stats.InPayload - if dopts.copts.StatsHandler != nil { - inPayload = &stats.InPayload{ - Client: true, - } - } - for { - if c.maxReceiveMessageSize == nil { - return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)") - } - if err = recv(p, dopts.codec, stream, dopts.dc, reply, *c.maxReceiveMessageSize, inPayload); err != nil { - if err == io.EOF { - break - } - return - } - } - if inPayload != nil && err == io.EOF && stream.Status().Code() == codes.OK { - // TODO in the current implementation, inTrailer may be handled before inPayload in some cases. - // Fix the order if necessary. - dopts.copts.StatsHandler.HandleRPC(ctx, inPayload) - } - c.trailerMD = stream.Trailer() - return nil -} +// All errors returned by Invoke are compatible with the status package. +func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply interface{}, opts ...CallOption) error { + // allow interceptor to see all applicable call options, which means those + // configured as defaults from dial option as well as per-call options + opts = combine(cc.dopts.callOptions, opts) -// sendRequest writes out various information of an RPC such as Context and Message. -func sendRequest(ctx context.Context, dopts dialOptions, compressor Compressor, c *callInfo, callHdr *transport.CallHdr, stream *transport.Stream, t transport.ClientTransport, args interface{}, opts *transport.Options) (err error) { - defer func() { - if err != nil { - // If err is connection error, t will be closed, no need to close stream here. - if _, ok := err.(transport.ConnectionError); !ok { - t.CloseStream(stream, err) - } - } - }() - var ( - cbuf *bytes.Buffer - outPayload *stats.OutPayload - ) - if compressor != nil { - cbuf = new(bytes.Buffer) - } - if dopts.copts.StatsHandler != nil { - outPayload = &stats.OutPayload{ - Client: true, - } - } - hdr, data, err := encode(dopts.codec, args, compressor, cbuf, outPayload) - if err != nil { - return err - } - if c.maxSendMessageSize == nil { - return Errorf(codes.Internal, "callInfo maxSendMessageSize field uninitialized(nil)") - } - if len(data) > *c.maxSendMessageSize { - return Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(data), *c.maxSendMessageSize) - } - err = t.Write(stream, hdr, data, opts) - if err == nil && outPayload != nil { - outPayload.SentTime = time.Now() - dopts.copts.StatsHandler.HandleRPC(ctx, outPayload) - } - // t.NewStream(...) could lead to an early rejection of the RPC (e.g., the service/method - // does not exist.) so that t.Write could get io.EOF from wait(...). Leave the following - // recvResponse to get the final status. - if err != nil && err != io.EOF { - return err - } - // Sent successfully. - return nil -} - -// Invoke sends the RPC request on the wire and returns after response is received. -// Invoke is called by generated code. Also users can call Invoke directly when it -// is really needed in their use cases. -func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error { if cc.dopts.unaryInt != nil { return cc.dopts.unaryInt(ctx, method, args, reply, cc, invoke, opts...) } return invoke(ctx, method, args, reply, cc, opts...) } -func invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) (e error) { - c := defaultCallInfo() - mc := cc.GetMethodConfig(method) - if mc.WaitForReady != nil { - c.failFast = !*mc.WaitForReady - } - - if mc.Timeout != nil && *mc.Timeout >= 0 { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, *mc.Timeout) - defer cancel() - } +func combine(o1 []CallOption, o2 []CallOption) []CallOption { + // we don't use append because o1 could have extra capacity whose + // elements would be overwritten, which could cause inadvertent + // sharing (and race connditions) between concurrent calls + if len(o1) == 0 { + return o2 + } else if len(o2) == 0 { + return o1 + } + ret := make([]CallOption, len(o1)+len(o2)) + copy(ret, o1) + copy(ret[len(o1):], o2) + return ret +} - opts = append(cc.dopts.callOptions, opts...) - for _, o := range opts { - if err := o.before(c); err != nil { - return toRPCErr(err) - } - } - defer func() { - for _, o := range opts { - o.after(c) - } - }() +// Invoke sends the RPC request on the wire and returns after response is +// received. This is typically called by generated code. +// +// DEPRECATED: Use ClientConn.Invoke instead. +func Invoke(ctx context.Context, method string, args, reply interface{}, cc *ClientConn, opts ...CallOption) error { + return cc.Invoke(ctx, method, args, reply, opts...) +} - c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize) - c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize) +var unaryStreamDesc = &StreamDesc{ServerStreams: false, ClientStreams: false} - if EnableTracing { - c.traceInfo.tr = trace.New("grpc.Sent."+methodFamily(method), method) - defer c.traceInfo.tr.Finish() - c.traceInfo.firstLine.client = true - if deadline, ok := ctx.Deadline(); ok { - c.traceInfo.firstLine.deadline = deadline.Sub(time.Now()) - } - c.traceInfo.tr.LazyLog(&c.traceInfo.firstLine, false) - // TODO(dsymonds): Arrange for c.traceInfo.firstLine.remoteAddr to be set. - defer func() { - if e != nil { - c.traceInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{e}}, true) - c.traceInfo.tr.SetError() - } - }() - } - ctx = newContextWithRPCInfo(ctx, c.failFast) - sh := cc.dopts.copts.StatsHandler - if sh != nil { - ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast}) - begin := &stats.Begin{ - Client: true, - BeginTime: time.Now(), - FailFast: c.failFast, - } - sh.HandleRPC(ctx, begin) - defer func() { - end := &stats.End{ - Client: true, - EndTime: time.Now(), - Error: e, - } - sh.HandleRPC(ctx, end) - }() - } - topts := &transport.Options{ - Last: true, - Delay: false, - } +func invoke(ctx context.Context, method string, req, reply interface{}, cc *ClientConn, opts ...CallOption) error { + // TODO: implement retries in clientStream and make this simply + // newClientStream, SendMsg, RecvMsg. + firstAttempt := true for { - var ( - err error - t transport.ClientTransport - stream *transport.Stream - // Record the done handler from Balancer.Get(...). It is called once the - // RPC has completed or failed. - done func(balancer.DoneInfo) - ) - // TODO(zhaoq): Need a formal spec of fail-fast. - callHdr := &transport.CallHdr{ - Host: cc.authority, - Method: method, - } - if cc.dopts.cp != nil { - callHdr.SendCompress = cc.dopts.cp.Type() - } - if c.creds != nil { - callHdr.Creds = c.creds - } - - t, done, err = cc.getTransport(ctx, c.failFast) + csInt, err := newClientStream(ctx, unaryStreamDesc, cc, method, opts...) if err != nil { - // TODO(zhaoq): Probably revisit the error handling. - if _, ok := status.FromError(err); ok { - return err - } - if err == errConnClosing || err == errConnUnavailable { - if c.failFast { - return Errorf(codes.Unavailable, "%v", err) - } - continue - } - // All the other errors are treated as Internal errors. - return Errorf(codes.Internal, "%v", err) - } - if c.traceInfo.tr != nil { - c.traceInfo.tr.LazyLog(&payload{sent: true, msg: args}, true) - } - stream, err = t.NewStream(ctx, callHdr) - if err != nil { - if done != nil { - if _, ok := err.(transport.ConnectionError); ok { - // If error is connection error, transport was sending data on wire, - // and we are not sure if anything has been sent on wire. - // If error is not connection error, we are sure nothing has been sent. - updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false}) - } - done(balancer.DoneInfo{Err: err}) - } - if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast { - continue - } - return toRPCErr(err) - } - if peer, ok := peer.FromContext(stream.Context()); ok { - c.peer = peer + return err } - err = sendRequest(ctx, cc.dopts, cc.dopts.cp, c, callHdr, stream, t, args, topts) - if err != nil { - if done != nil { - updateRPCInfoInContext(ctx, rpcInfo{ - bytesSent: stream.BytesSent(), - bytesReceived: stream.BytesReceived(), - }) - done(balancer.DoneInfo{Err: err}) - } - // Retry a non-failfast RPC when - // i) there is a connection error; or - // ii) the server started to drain before this RPC was initiated. - if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast { + cs := csInt.(*clientStream) + if err := cs.SendMsg(req); err != nil { + if !cs.c.failFast && cs.attempt.s.Unprocessed() && firstAttempt { + // TODO: Add a field to header for grpc-transparent-retry-attempts + firstAttempt = false continue } - return toRPCErr(err) + return err } - err = recvResponse(ctx, cc.dopts, t, c, stream, reply) - if err != nil { - if done != nil { - updateRPCInfoInContext(ctx, rpcInfo{ - bytesSent: stream.BytesSent(), - bytesReceived: stream.BytesReceived(), - }) - done(balancer.DoneInfo{Err: err}) - } - if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast { + if err := cs.RecvMsg(reply); err != nil { + if !cs.c.failFast && cs.attempt.s.Unprocessed() && firstAttempt { + // TODO: Add a field to header for grpc-transparent-retry-attempts + firstAttempt = false continue } - return toRPCErr(err) - } - if c.traceInfo.tr != nil { - c.traceInfo.tr.LazyLog(&payload{sent: false, msg: reply}, true) - } - t.CloseStream(stream, nil) - if done != nil { - updateRPCInfoInContext(ctx, rpcInfo{ - bytesSent: stream.BytesSent(), - bytesReceived: stream.BytesReceived(), - }) - done(balancer.DoneInfo{Err: err}) + return err } - return stream.Status().Err() + return nil } } diff --git a/vendor/google.golang.org/grpc/call_test.go b/vendor/google.golang.org/grpc/call_test.go deleted file mode 100644 index f48d30e879..0000000000 --- a/vendor/google.golang.org/grpc/call_test.go +++ /dev/null @@ -1,292 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "fmt" - "io" - "math" - "net" - "strconv" - "strings" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "google.golang.org/grpc/test/leakcheck" - "google.golang.org/grpc/transport" -) - -var ( - expectedRequest = "ping" - expectedResponse = "pong" - weirdError = "format verbs: %v%s" - sizeLargeErr = 1024 * 1024 - canceled = 0 -) - -type testCodec struct { -} - -func (testCodec) Marshal(v interface{}) ([]byte, error) { - return []byte(*(v.(*string))), nil -} - -func (testCodec) Unmarshal(data []byte, v interface{}) error { - *(v.(*string)) = string(data) - return nil -} - -func (testCodec) String() string { - return "test" -} - -type testStreamHandler struct { - port string - t transport.ServerTransport -} - -func (h *testStreamHandler) handleStream(t *testing.T, s *transport.Stream) { - p := &parser{r: s} - for { - pf, req, err := p.recvMsg(math.MaxInt32) - if err == io.EOF { - break - } - if err != nil { - return - } - if pf != compressionNone { - t.Errorf("Received the mistaken message format %d, want %d", pf, compressionNone) - return - } - var v string - codec := testCodec{} - if err := codec.Unmarshal(req, &v); err != nil { - t.Errorf("Failed to unmarshal the received message: %v", err) - return - } - if v == "weird error" { - h.t.WriteStatus(s, status.New(codes.Internal, weirdError)) - return - } - if v == "canceled" { - canceled++ - h.t.WriteStatus(s, status.New(codes.Internal, "")) - return - } - if v == "port" { - h.t.WriteStatus(s, status.New(codes.Internal, h.port)) - return - } - - if v != expectedRequest { - h.t.WriteStatus(s, status.New(codes.Internal, strings.Repeat("A", sizeLargeErr))) - return - } - } - // send a response back to end the stream. - hdr, data, err := encode(testCodec{}, &expectedResponse, nil, nil, nil) - if err != nil { - t.Errorf("Failed to encode the response: %v", err) - return - } - h.t.Write(s, hdr, data, &transport.Options{}) - h.t.WriteStatus(s, status.New(codes.OK, "")) -} - -type server struct { - lis net.Listener - port string - addr string - startedErr chan error // sent nil or an error after server starts - mu sync.Mutex - conns map[transport.ServerTransport]bool -} - -func newTestServer() *server { - return &server{startedErr: make(chan error, 1)} -} - -// start starts server. Other goroutines should block on s.startedErr for further operations. -func (s *server) start(t *testing.T, port int, maxStreams uint32) { - var err error - if port == 0 { - s.lis, err = net.Listen("tcp", "localhost:0") - } else { - s.lis, err = net.Listen("tcp", "localhost:"+strconv.Itoa(port)) - } - if err != nil { - s.startedErr <- fmt.Errorf("failed to listen: %v", err) - return - } - s.addr = s.lis.Addr().String() - _, p, err := net.SplitHostPort(s.addr) - if err != nil { - s.startedErr <- fmt.Errorf("failed to parse listener address: %v", err) - return - } - s.port = p - s.conns = make(map[transport.ServerTransport]bool) - s.startedErr <- nil - for { - conn, err := s.lis.Accept() - if err != nil { - return - } - config := &transport.ServerConfig{ - MaxStreams: maxStreams, - } - st, err := transport.NewServerTransport("http2", conn, config) - if err != nil { - continue - } - s.mu.Lock() - if s.conns == nil { - s.mu.Unlock() - st.Close() - return - } - s.conns[st] = true - s.mu.Unlock() - h := &testStreamHandler{ - port: s.port, - t: st, - } - go st.HandleStreams(func(s *transport.Stream) { - go h.handleStream(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - } -} - -func (s *server) wait(t *testing.T, timeout time.Duration) { - select { - case err := <-s.startedErr: - if err != nil { - t.Fatal(err) - } - case <-time.After(timeout): - t.Fatalf("Timed out after %v waiting for server to be ready", timeout) - } -} - -func (s *server) stop() { - s.lis.Close() - s.mu.Lock() - for c := range s.conns { - c.Close() - } - s.conns = nil - s.mu.Unlock() -} - -func setUp(t *testing.T, port int, maxStreams uint32) (*server, *ClientConn) { - server := newTestServer() - go server.start(t, port, maxStreams) - server.wait(t, 2*time.Second) - addr := "localhost:" + server.port - cc, err := Dial(addr, WithBlock(), WithInsecure(), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("Failed to create ClientConn: %v", err) - } - return server, cc -} - -func TestInvoke(t *testing.T) { - defer leakcheck.Check(t) - server, cc := setUp(t, 0, math.MaxUint32) - var reply string - if err := Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply, cc); err != nil || reply != expectedResponse { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want <nil>", err) - } - cc.Close() - server.stop() -} - -func TestInvokeLargeErr(t *testing.T) { - defer leakcheck.Check(t) - server, cc := setUp(t, 0, math.MaxUint32) - var reply string - req := "hello" - err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc) - if _, ok := status.FromError(err); !ok { - t.Fatalf("grpc.Invoke(_, _, _, _, _) receives non rpc error.") - } - if Code(err) != codes.Internal || len(ErrorDesc(err)) != sizeLargeErr { - t.Fatalf("grpc.Invoke(_, _, _, _, _) = %v, want an error of code %d and desc size %d", err, codes.Internal, sizeLargeErr) - } - cc.Close() - server.stop() -} - -// TestInvokeErrorSpecialChars checks that error messages don't get mangled. -func TestInvokeErrorSpecialChars(t *testing.T) { - defer leakcheck.Check(t) - server, cc := setUp(t, 0, math.MaxUint32) - var reply string - req := "weird error" - err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc) - if _, ok := status.FromError(err); !ok { - t.Fatalf("grpc.Invoke(_, _, _, _, _) receives non rpc error.") - } - if got, want := ErrorDesc(err), weirdError; got != want { - t.Fatalf("grpc.Invoke(_, _, _, _, _) error = %q, want %q", got, want) - } - cc.Close() - server.stop() -} - -// TestInvokeCancel checks that an Invoke with a canceled context is not sent. -func TestInvokeCancel(t *testing.T) { - defer leakcheck.Check(t) - server, cc := setUp(t, 0, math.MaxUint32) - var reply string - req := "canceled" - for i := 0; i < 100; i++ { - ctx, cancel := context.WithCancel(context.Background()) - cancel() - Invoke(ctx, "/foo/bar", &req, &reply, cc) - } - if canceled != 0 { - t.Fatalf("received %d of 100 canceled requests", canceled) - } - cc.Close() - server.stop() -} - -// TestInvokeCancelClosedNonFail checks that a canceled non-failfast RPC -// on a closed client will terminate. -func TestInvokeCancelClosedNonFailFast(t *testing.T) { - defer leakcheck.Check(t) - server, cc := setUp(t, 0, math.MaxUint32) - var reply string - cc.Close() - req := "hello" - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if err := Invoke(ctx, "/foo/bar", &req, &reply, cc, FailFast(false)); err == nil { - t.Fatalf("canceled invoke on closed connection should fail") - } - server.stop() -} diff --git a/vendor/google.golang.org/grpc/channelz/funcs.go b/vendor/google.golang.org/grpc/channelz/funcs.go new file mode 100644 index 0000000000..586a0336b4 --- /dev/null +++ b/vendor/google.golang.org/grpc/channelz/funcs.go @@ -0,0 +1,573 @@ +/* + * + * Copyright 2018 gRPC 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 channelz defines APIs for enabling channelz service, entry +// registration/deletion, and accessing channelz data. It also defines channelz +// metric struct formats. +// +// All APIs in this package are experimental. +package channelz + +import ( + "sort" + "sync" + "sync/atomic" + + "google.golang.org/grpc/grpclog" +) + +var ( + db dbWrapper + idGen idGenerator + // EntryPerPage defines the number of channelz entries to be shown on a web page. + EntryPerPage = 50 + curState int32 +) + +// TurnOn turns on channelz data collection. +func TurnOn() { + if !IsOn() { + NewChannelzStorage() + atomic.StoreInt32(&curState, 1) + } +} + +// IsOn returns whether channelz data collection is on. +func IsOn() bool { + return atomic.CompareAndSwapInt32(&curState, 1, 1) +} + +// dbWarpper wraps around a reference to internal channelz data storage, and +// provide synchronized functionality to set and get the reference. +type dbWrapper struct { + mu sync.RWMutex + DB *channelMap +} + +func (d *dbWrapper) set(db *channelMap) { + d.mu.Lock() + d.DB = db + d.mu.Unlock() +} + +func (d *dbWrapper) get() *channelMap { + d.mu.RLock() + defer d.mu.RUnlock() + return d.DB +} + +// NewChannelzStorage initializes channelz data storage and id generator. +// +// Note: This function is exported for testing purpose only. User should not call +// it in most cases. +func NewChannelzStorage() { + db.set(&channelMap{ + topLevelChannels: make(map[int64]struct{}), + channels: make(map[int64]*channel), + listenSockets: make(map[int64]*listenSocket), + normalSockets: make(map[int64]*normalSocket), + servers: make(map[int64]*server), + subChannels: make(map[int64]*subChannel), + }) + idGen.reset() +} + +// GetTopChannels returns a slice of top channel's ChannelMetric, along with a +// boolean indicating whether there's more top channels to be queried for. +// +// The arg id specifies that only top channel with id at or above it will be included +// in the result. The returned slice is up to a length of EntryPerPage, and is +// sorted in ascending id order. +func GetTopChannels(id int64) ([]*ChannelMetric, bool) { + return db.get().GetTopChannels(id) +} + +// GetServers returns a slice of server's ServerMetric, along with a +// boolean indicating whether there's more servers to be queried for. +// +// The arg id specifies that only server with id at or above it will be included +// in the result. The returned slice is up to a length of EntryPerPage, and is +// sorted in ascending id order. +func GetServers(id int64) ([]*ServerMetric, bool) { + return db.get().GetServers(id) +} + +// GetServerSockets returns a slice of server's (identified by id) normal socket's +// SocketMetric, along with a boolean indicating whether there's more sockets to +// be queried for. +// +// The arg startID specifies that only sockets with id at or above it will be +// included in the result. The returned slice is up to a length of EntryPerPage, +// and is sorted in ascending id order. +func GetServerSockets(id int64, startID int64) ([]*SocketMetric, bool) { + return db.get().GetServerSockets(id, startID) +} + +// GetChannel returns the ChannelMetric for the channel (identified by id). +func GetChannel(id int64) *ChannelMetric { + return db.get().GetChannel(id) +} + +// GetSubChannel returns the SubChannelMetric for the subchannel (identified by id). +func GetSubChannel(id int64) *SubChannelMetric { + return db.get().GetSubChannel(id) +} + +// GetSocket returns the SocketInternalMetric for the socket (identified by id). +func GetSocket(id int64) *SocketMetric { + return db.get().GetSocket(id) +} + +// RegisterChannel registers the given channel c in channelz database with ref +// as its reference name, and add it to the child list of its parent (identified +// by pid). pid = 0 means no parent. It returns the unique channelz tracking id +// assigned to this channel. +func RegisterChannel(c Channel, pid int64, ref string) int64 { + id := idGen.genID() + cn := &channel{ + refName: ref, + c: c, + subChans: make(map[int64]string), + nestedChans: make(map[int64]string), + id: id, + pid: pid, + } + if pid == 0 { + db.get().addChannel(id, cn, true, pid, ref) + } else { + db.get().addChannel(id, cn, false, pid, ref) + } + return id +} + +// RegisterSubChannel registers the given channel c in channelz database with ref +// as its reference name, and add it to the child list of its parent (identified +// by pid). It returns the unique channelz tracking id assigned to this subchannel. +func RegisterSubChannel(c Channel, pid int64, ref string) int64 { + if pid == 0 { + grpclog.Error("a SubChannel's parent id cannot be 0") + return 0 + } + id := idGen.genID() + sc := &subChannel{ + refName: ref, + c: c, + sockets: make(map[int64]string), + id: id, + pid: pid, + } + db.get().addSubChannel(id, sc, pid, ref) + return id +} + +// RegisterServer registers the given server s in channelz database. It returns +// the unique channelz tracking id assigned to this server. +func RegisterServer(s Server, ref string) int64 { + id := idGen.genID() + svr := &server{ + refName: ref, + s: s, + sockets: make(map[int64]string), + listenSockets: make(map[int64]string), + id: id, + } + db.get().addServer(id, svr) + return id +} + +// RegisterListenSocket registers the given listen socket s in channelz database +// with ref as its reference name, and add it to the child list of its parent +// (identified by pid). It returns the unique channelz tracking id assigned to +// this listen socket. +func RegisterListenSocket(s Socket, pid int64, ref string) int64 { + if pid == 0 { + grpclog.Error("a ListenSocket's parent id cannot be 0") + return 0 + } + id := idGen.genID() + ls := &listenSocket{refName: ref, s: s, id: id, pid: pid} + db.get().addListenSocket(id, ls, pid, ref) + return id +} + +// RegisterNormalSocket registers the given normal socket s in channelz database +// with ref as its reference name, and add it to the child list of its parent +// (identified by pid). It returns the unique channelz tracking id assigned to +// this normal socket. +func RegisterNormalSocket(s Socket, pid int64, ref string) int64 { + if pid == 0 { + grpclog.Error("a NormalSocket's parent id cannot be 0") + return 0 + } + id := idGen.genID() + ns := &normalSocket{refName: ref, s: s, id: id, pid: pid} + db.get().addNormalSocket(id, ns, pid, ref) + return id +} + +// RemoveEntry removes an entry with unique channelz trakcing id to be id from +// channelz database. +func RemoveEntry(id int64) { + db.get().removeEntry(id) +} + +// channelMap is the storage data structure for channelz. +// Methods of channelMap can be divided in two two categories with respect to locking. +// 1. Methods acquire the global lock. +// 2. Methods that can only be called when global lock is held. +// A second type of method need always to be called inside a first type of method. +type channelMap struct { + mu sync.RWMutex + topLevelChannels map[int64]struct{} + servers map[int64]*server + channels map[int64]*channel + subChannels map[int64]*subChannel + listenSockets map[int64]*listenSocket + normalSockets map[int64]*normalSocket +} + +func (c *channelMap) addServer(id int64, s *server) { + c.mu.Lock() + s.cm = c + c.servers[id] = s + c.mu.Unlock() +} + +func (c *channelMap) addChannel(id int64, cn *channel, isTopChannel bool, pid int64, ref string) { + c.mu.Lock() + cn.cm = c + c.channels[id] = cn + if isTopChannel { + c.topLevelChannels[id] = struct{}{} + } else { + c.findEntry(pid).addChild(id, cn) + } + c.mu.Unlock() +} + +func (c *channelMap) addSubChannel(id int64, sc *subChannel, pid int64, ref string) { + c.mu.Lock() + sc.cm = c + c.subChannels[id] = sc + c.findEntry(pid).addChild(id, sc) + c.mu.Unlock() +} + +func (c *channelMap) addListenSocket(id int64, ls *listenSocket, pid int64, ref string) { + c.mu.Lock() + ls.cm = c + c.listenSockets[id] = ls + c.findEntry(pid).addChild(id, ls) + c.mu.Unlock() +} + +func (c *channelMap) addNormalSocket(id int64, ns *normalSocket, pid int64, ref string) { + c.mu.Lock() + ns.cm = c + c.normalSockets[id] = ns + c.findEntry(pid).addChild(id, ns) + c.mu.Unlock() +} + +// removeEntry triggers the removal of an entry, which may not indeed delete the +// entry, if it has to wait on the deletion of its children, or may lead to a chain +// of entry deletion. For example, deleting the last socket of a gracefully shutting +// down server will lead to the server being also deleted. +func (c *channelMap) removeEntry(id int64) { + c.mu.Lock() + c.findEntry(id).triggerDelete() + c.mu.Unlock() +} + +// c.mu must be held by the caller. +func (c *channelMap) findEntry(id int64) entry { + var v entry + var ok bool + if v, ok = c.channels[id]; ok { + return v + } + if v, ok = c.subChannels[id]; ok { + return v + } + if v, ok = c.servers[id]; ok { + return v + } + if v, ok = c.listenSockets[id]; ok { + return v + } + if v, ok = c.normalSockets[id]; ok { + return v + } + return &dummyEntry{idNotFound: id} +} + +// c.mu must be held by the caller +// deleteEntry simply deletes an entry from the channelMap. Before calling this +// method, caller must check this entry is ready to be deleted, i.e removeEntry() +// has been called on it, and no children still exist. +// Conditionals are ordered by the expected frequency of deletion of each entity +// type, in order to optimize performance. +func (c *channelMap) deleteEntry(id int64) { + var ok bool + if _, ok = c.normalSockets[id]; ok { + delete(c.normalSockets, id) + return + } + if _, ok = c.subChannels[id]; ok { + delete(c.subChannels, id) + return + } + if _, ok = c.channels[id]; ok { + delete(c.channels, id) + delete(c.topLevelChannels, id) + return + } + if _, ok = c.listenSockets[id]; ok { + delete(c.listenSockets, id) + return + } + if _, ok = c.servers[id]; ok { + delete(c.servers, id) + return + } +} + +type int64Slice []int64 + +func (s int64Slice) Len() int { return len(s) } +func (s int64Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s int64Slice) Less(i, j int) bool { return s[i] < s[j] } + +func copyMap(m map[int64]string) map[int64]string { + n := make(map[int64]string) + for k, v := range m { + n[k] = v + } + return n +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func (c *channelMap) GetTopChannels(id int64) ([]*ChannelMetric, bool) { + c.mu.RLock() + l := len(c.topLevelChannels) + ids := make([]int64, 0, l) + cns := make([]*channel, 0, min(l, EntryPerPage)) + + for k := range c.topLevelChannels { + ids = append(ids, k) + } + sort.Sort(int64Slice(ids)) + idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) + count := 0 + var end bool + var t []*ChannelMetric + for i, v := range ids[idx:] { + if count == EntryPerPage { + break + } + if cn, ok := c.channels[v]; ok { + cns = append(cns, cn) + t = append(t, &ChannelMetric{ + NestedChans: copyMap(cn.nestedChans), + SubChans: copyMap(cn.subChans), + }) + count++ + } + if i == len(ids[idx:])-1 { + end = true + break + } + } + c.mu.RUnlock() + if count == 0 { + end = true + } + + for i, cn := range cns { + t[i].ChannelData = cn.c.ChannelzMetric() + t[i].ID = cn.id + t[i].RefName = cn.refName + } + return t, end +} + +func (c *channelMap) GetServers(id int64) ([]*ServerMetric, bool) { + c.mu.RLock() + l := len(c.servers) + ids := make([]int64, 0, l) + ss := make([]*server, 0, min(l, EntryPerPage)) + for k := range c.servers { + ids = append(ids, k) + } + sort.Sort(int64Slice(ids)) + idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) + count := 0 + var end bool + var s []*ServerMetric + for i, v := range ids[idx:] { + if count == EntryPerPage { + break + } + if svr, ok := c.servers[v]; ok { + ss = append(ss, svr) + s = append(s, &ServerMetric{ + ListenSockets: copyMap(svr.listenSockets), + }) + count++ + } + if i == len(ids[idx:])-1 { + end = true + break + } + } + c.mu.RUnlock() + if count == 0 { + end = true + } + + for i, svr := range ss { + s[i].ServerData = svr.s.ChannelzMetric() + s[i].ID = svr.id + s[i].RefName = svr.refName + } + return s, end +} + +func (c *channelMap) GetServerSockets(id int64, startID int64) ([]*SocketMetric, bool) { + var svr *server + var ok bool + c.mu.RLock() + if svr, ok = c.servers[id]; !ok { + // server with id doesn't exist. + c.mu.RUnlock() + return nil, true + } + svrskts := svr.sockets + l := len(svrskts) + ids := make([]int64, 0, l) + sks := make([]*normalSocket, 0, min(l, EntryPerPage)) + for k := range svrskts { + ids = append(ids, k) + } + sort.Sort((int64Slice(ids))) + idx := sort.Search(len(ids), func(i int) bool { return ids[i] >= id }) + count := 0 + var end bool + for i, v := range ids[idx:] { + if count == EntryPerPage { + break + } + if ns, ok := c.normalSockets[v]; ok { + sks = append(sks, ns) + count++ + } + if i == len(ids[idx:])-1 { + end = true + break + } + } + c.mu.RUnlock() + if count == 0 { + end = true + } + var s []*SocketMetric + for _, ns := range sks { + sm := &SocketMetric{} + sm.SocketData = ns.s.ChannelzMetric() + sm.ID = ns.id + sm.RefName = ns.refName + s = append(s, sm) + } + return s, end +} + +func (c *channelMap) GetChannel(id int64) *ChannelMetric { + cm := &ChannelMetric{} + var cn *channel + var ok bool + c.mu.RLock() + if cn, ok = c.channels[id]; !ok { + // channel with id doesn't exist. + c.mu.RUnlock() + return nil + } + cm.NestedChans = copyMap(cn.nestedChans) + cm.SubChans = copyMap(cn.subChans) + c.mu.RUnlock() + cm.ChannelData = cn.c.ChannelzMetric() + cm.ID = cn.id + cm.RefName = cn.refName + return cm +} + +func (c *channelMap) GetSubChannel(id int64) *SubChannelMetric { + cm := &SubChannelMetric{} + var sc *subChannel + var ok bool + c.mu.RLock() + if sc, ok = c.subChannels[id]; !ok { + // subchannel with id doesn't exist. + c.mu.RUnlock() + return nil + } + cm.Sockets = copyMap(sc.sockets) + c.mu.RUnlock() + cm.ChannelData = sc.c.ChannelzMetric() + cm.ID = sc.id + cm.RefName = sc.refName + return cm +} + +func (c *channelMap) GetSocket(id int64) *SocketMetric { + sm := &SocketMetric{} + c.mu.RLock() + if ls, ok := c.listenSockets[id]; ok { + c.mu.RUnlock() + sm.SocketData = ls.s.ChannelzMetric() + sm.ID = ls.id + sm.RefName = ls.refName + return sm + } + if ns, ok := c.normalSockets[id]; ok { + c.mu.RUnlock() + sm.SocketData = ns.s.ChannelzMetric() + sm.ID = ns.id + sm.RefName = ns.refName + return sm + } + c.mu.RUnlock() + return nil +} + +type idGenerator struct { + id int64 +} + +func (i *idGenerator) reset() { + atomic.StoreInt64(&i.id, 0) +} + +func (i *idGenerator) genID() int64 { + return atomic.AddInt64(&i.id, 1) +} diff --git a/vendor/google.golang.org/grpc/channelz/types.go b/vendor/google.golang.org/grpc/channelz/types.go new file mode 100644 index 0000000000..153d75340e --- /dev/null +++ b/vendor/google.golang.org/grpc/channelz/types.go @@ -0,0 +1,418 @@ +/* + * + * Copyright 2018 gRPC 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 channelz + +import ( + "net" + "time" + + "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/grpclog" +) + +// entry represents a node in the channelz database. +type entry interface { + // addChild adds a child e, whose channelz id is id to child list + addChild(id int64, e entry) + // deleteChild deletes a child with channelz id to be id from child list + deleteChild(id int64) + // triggerDelete tries to delete self from channelz database. However, if child + // list is not empty, then deletion from the database is on hold until the last + // child is deleted from database. + triggerDelete() + // deleteSelfIfReady check whether triggerDelete() has been called before, and whether child + // list is now empty. If both conditions are met, then delete self from database. + deleteSelfIfReady() +} + +// dummyEntry is a fake entry to handle entry not found case. +type dummyEntry struct { + idNotFound int64 +} + +func (d *dummyEntry) addChild(id int64, e entry) { + // Note: It is possible for a normal program to reach here under race condition. + // For example, there could be a race between ClientConn.Close() info being propagated + // to addrConn and http2Client. ClientConn.Close() cancel the context and result + // in http2Client to error. The error info is then caught by transport monitor + // and before addrConn.tearDown() is called in side ClientConn.Close(). Therefore, + // the addrConn will create a new transport. And when registering the new transport in + // channelz, its parent addrConn could have already been torn down and deleted + // from channelz tracking, and thus reach the code here. + grpclog.Infof("attempt to add child of type %T with id %d to a parent (id=%d) that doesn't currently exist", e, id, d.idNotFound) +} + +func (d *dummyEntry) deleteChild(id int64) { + // It is possible for a normal program to reach here under race condition. + // Refer to the example described in addChild(). + grpclog.Infof("attempt to delete child with id %d from a parent (id=%d) that doesn't currently exist", id, d.idNotFound) +} + +func (d *dummyEntry) triggerDelete() { + grpclog.Warningf("attempt to delete an entry (id=%d) that doesn't currently exist", d.idNotFound) +} + +func (*dummyEntry) deleteSelfIfReady() { + // code should not reach here. deleteSelfIfReady is always called on an existing entry. +} + +// ChannelMetric defines the info channelz provides for a specific Channel, which +// includes ChannelInternalMetric and channelz-specific data, such as channelz id, +// child list, etc. +type ChannelMetric struct { + // ID is the channelz id of this channel. + ID int64 + // RefName is the human readable reference string of this channel. + RefName string + // ChannelData contains channel internal metric reported by the channel through + // ChannelzMetric(). + ChannelData *ChannelInternalMetric + // NestedChans tracks the nested channel type children of this channel in the format of + // a map from nested channel channelz id to corresponding reference string. + NestedChans map[int64]string + // SubChans tracks the subchannel type children of this channel in the format of a + // map from subchannel channelz id to corresponding reference string. + SubChans map[int64]string + // Sockets tracks the socket type children of this channel in the format of a map + // from socket channelz id to corresponding reference string. + // Note current grpc implementation doesn't allow channel having sockets directly, + // therefore, this is field is unused. + Sockets map[int64]string +} + +// SubChannelMetric defines the info channelz provides for a specific SubChannel, +// which includes ChannelInternalMetric and channelz-specific data, such as +// channelz id, child list, etc. +type SubChannelMetric struct { + // ID is the channelz id of this subchannel. + ID int64 + // RefName is the human readable reference string of this subchannel. + RefName string + // ChannelData contains subchannel internal metric reported by the subchannel + // through ChannelzMetric(). + ChannelData *ChannelInternalMetric + // NestedChans tracks the nested channel type children of this subchannel in the format of + // a map from nested channel channelz id to corresponding reference string. + // Note current grpc implementation doesn't allow subchannel to have nested channels + // as children, therefore, this field is unused. + NestedChans map[int64]string + // SubChans tracks the subchannel type children of this subchannel in the format of a + // map from subchannel channelz id to corresponding reference string. + // Note current grpc implementation doesn't allow subchannel to have subchannels + // as children, therefore, this field is unused. + SubChans map[int64]string + // Sockets tracks the socket type children of this subchannel in the format of a map + // from socket channelz id to corresponding reference string. + Sockets map[int64]string +} + +// ChannelInternalMetric defines the struct that the implementor of Channel interface +// should return from ChannelzMetric(). +type ChannelInternalMetric struct { + // current connectivity state of the channel. + State connectivity.State + // The target this channel originally tried to connect to. May be absent + Target string + // The number of calls started on the channel. + CallsStarted int64 + // The number of calls that have completed with an OK status. + CallsSucceeded int64 + // The number of calls that have a completed with a non-OK status. + CallsFailed int64 + // The last time a call was started on the channel. + LastCallStartedTimestamp time.Time + //TODO: trace +} + +// Channel is the interface that should be satisfied in order to be tracked by +// channelz as Channel or SubChannel. +type Channel interface { + ChannelzMetric() *ChannelInternalMetric +} + +type channel struct { + refName string + c Channel + closeCalled bool + nestedChans map[int64]string + subChans map[int64]string + id int64 + pid int64 + cm *channelMap +} + +func (c *channel) addChild(id int64, e entry) { + switch v := e.(type) { + case *subChannel: + c.subChans[id] = v.refName + case *channel: + c.nestedChans[id] = v.refName + default: + grpclog.Errorf("cannot add a child (id = %d) of type %T to a channel", id, e) + } +} + +func (c *channel) deleteChild(id int64) { + delete(c.subChans, id) + delete(c.nestedChans, id) + c.deleteSelfIfReady() +} + +func (c *channel) triggerDelete() { + c.closeCalled = true + c.deleteSelfIfReady() +} + +func (c *channel) deleteSelfIfReady() { + if !c.closeCalled || len(c.subChans)+len(c.nestedChans) != 0 { + return + } + c.cm.deleteEntry(c.id) + // not top channel + if c.pid != 0 { + c.cm.findEntry(c.pid).deleteChild(c.id) + } +} + +type subChannel struct { + refName string + c Channel + closeCalled bool + sockets map[int64]string + id int64 + pid int64 + cm *channelMap +} + +func (sc *subChannel) addChild(id int64, e entry) { + if v, ok := e.(*normalSocket); ok { + sc.sockets[id] = v.refName + } else { + grpclog.Errorf("cannot add a child (id = %d) of type %T to a subChannel", id, e) + } +} + +func (sc *subChannel) deleteChild(id int64) { + delete(sc.sockets, id) + sc.deleteSelfIfReady() +} + +func (sc *subChannel) triggerDelete() { + sc.closeCalled = true + sc.deleteSelfIfReady() +} + +func (sc *subChannel) deleteSelfIfReady() { + if !sc.closeCalled || len(sc.sockets) != 0 { + return + } + sc.cm.deleteEntry(sc.id) + sc.cm.findEntry(sc.pid).deleteChild(sc.id) +} + +// SocketMetric defines the info channelz provides for a specific Socket, which +// includes SocketInternalMetric and channelz-specific data, such as channelz id, etc. +type SocketMetric struct { + // ID is the channelz id of this socket. + ID int64 + // RefName is the human readable reference string of this socket. + RefName string + // SocketData contains socket internal metric reported by the socket through + // ChannelzMetric(). + SocketData *SocketInternalMetric +} + +// SocketInternalMetric defines the struct that the implementor of Socket interface +// should return from ChannelzMetric(). +type SocketInternalMetric struct { + // The number of streams that have been started. + StreamsStarted int64 + // The number of streams that have ended successfully: + // On client side, receiving frame with eos bit set. + // On server side, sending frame with eos bit set. + StreamsSucceeded int64 + // The number of streams that have ended unsuccessfully: + // On client side, termination without receiving frame with eos bit set. + // On server side, termination without sending frame with eos bit set. + StreamsFailed int64 + // The number of messages successfully sent on this socket. + MessagesSent int64 + MessagesReceived int64 + // The number of keep alives sent. This is typically implemented with HTTP/2 + // ping messages. + KeepAlivesSent int64 + // The last time a stream was created by this endpoint. Usually unset for + // servers. + LastLocalStreamCreatedTimestamp time.Time + // The last time a stream was created by the remote endpoint. Usually unset + // for clients. + LastRemoteStreamCreatedTimestamp time.Time + // The last time a message was sent by this endpoint. + LastMessageSentTimestamp time.Time + // The last time a message was received by this endpoint. + LastMessageReceivedTimestamp time.Time + // The amount of window, granted to the local endpoint by the remote endpoint. + // This may be slightly out of date due to network latency. This does NOT + // include stream level or TCP level flow control info. + LocalFlowControlWindow int64 + // The amount of window, granted to the remote endpoint by the local endpoint. + // This may be slightly out of date due to network latency. This does NOT + // include stream level or TCP level flow control info. + RemoteFlowControlWindow int64 + // The locally bound address. + LocalAddr net.Addr + // The remote bound address. May be absent. + RemoteAddr net.Addr + // Optional, represents the name of the remote endpoint, if different than + // the original target name. + RemoteName string + //TODO: socket options + //TODO: Security +} + +// Socket is the interface that should be satisfied in order to be tracked by +// channelz as Socket. +type Socket interface { + ChannelzMetric() *SocketInternalMetric +} + +type listenSocket struct { + refName string + s Socket + id int64 + pid int64 + cm *channelMap +} + +func (ls *listenSocket) addChild(id int64, e entry) { + grpclog.Errorf("cannot add a child (id = %d) of type %T to a listen socket", id, e) +} + +func (ls *listenSocket) deleteChild(id int64) { + grpclog.Errorf("cannot delete a child (id = %d) from a listen socket", id) +} + +func (ls *listenSocket) triggerDelete() { + ls.cm.deleteEntry(ls.id) + ls.cm.findEntry(ls.pid).deleteChild(ls.id) +} + +func (ls *listenSocket) deleteSelfIfReady() { + grpclog.Errorf("cannot call deleteSelfIfReady on a listen socket") +} + +type normalSocket struct { + refName string + s Socket + id int64 + pid int64 + cm *channelMap +} + +func (ns *normalSocket) addChild(id int64, e entry) { + grpclog.Errorf("cannot add a child (id = %d) of type %T to a normal socket", id, e) +} + +func (ns *normalSocket) deleteChild(id int64) { + grpclog.Errorf("cannot delete a child (id = %d) from a normal socket", id) +} + +func (ns *normalSocket) triggerDelete() { + ns.cm.deleteEntry(ns.id) + ns.cm.findEntry(ns.pid).deleteChild(ns.id) +} + +func (ns *normalSocket) deleteSelfIfReady() { + grpclog.Errorf("cannot call deleteSelfIfReady on a normal socket") +} + +// ServerMetric defines the info channelz provides for a specific Server, which +// includes ServerInternalMetric and channelz-specific data, such as channelz id, +// child list, etc. +type ServerMetric struct { + // ID is the channelz id of this server. + ID int64 + // RefName is the human readable reference string of this server. + RefName string + // ServerData contains server internal metric reported by the server through + // ChannelzMetric(). + ServerData *ServerInternalMetric + // ListenSockets tracks the listener socket type children of this server in the + // format of a map from socket channelz id to corresponding reference string. + ListenSockets map[int64]string +} + +// ServerInternalMetric defines the struct that the implementor of Server interface +// should return from ChannelzMetric(). +type ServerInternalMetric struct { + // The number of incoming calls started on the server. + CallsStarted int64 + // The number of incoming calls that have completed with an OK status. + CallsSucceeded int64 + // The number of incoming calls that have a completed with a non-OK status. + CallsFailed int64 + // The last time a call was started on the server. + LastCallStartedTimestamp time.Time + //TODO: trace +} + +// Server is the interface to be satisfied in order to be tracked by channelz as +// Server. +type Server interface { + ChannelzMetric() *ServerInternalMetric +} + +type server struct { + refName string + s Server + closeCalled bool + sockets map[int64]string + listenSockets map[int64]string + id int64 + cm *channelMap +} + +func (s *server) addChild(id int64, e entry) { + switch v := e.(type) { + case *normalSocket: + s.sockets[id] = v.refName + case *listenSocket: + s.listenSockets[id] = v.refName + default: + grpclog.Errorf("cannot add a child (id = %d) of type %T to a server", id, e) + } +} + +func (s *server) deleteChild(id int64) { + delete(s.sockets, id) + delete(s.listenSockets, id) + s.deleteSelfIfReady() +} + +func (s *server) triggerDelete() { + s.closeCalled = true + s.deleteSelfIfReady() +} + +func (s *server) deleteSelfIfReady() { + if !s.closeCalled || len(s.sockets)+len(s.listenSockets) != 0 { + return + } + s.cm.deleteEntry(s.id) +} diff --git a/vendor/google.golang.org/grpc/clientconn.go b/vendor/google.golang.org/grpc/clientconn.go index 5462062bea..e8d95b43b7 100644 --- a/vendor/google.golang.org/grpc/clientconn.go +++ b/vendor/google.golang.org/grpc/clientconn.go @@ -31,24 +31,50 @@ import ( "golang.org/x/net/context" "golang.org/x/net/trace" "google.golang.org/grpc/balancer" + _ "google.golang.org/grpc/balancer/roundrobin" // To register roundrobin. + "google.golang.org/grpc/channelz" + "google.golang.org/grpc/codes" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/resolver" + _ "google.golang.org/grpc/resolver/dns" // To register dns resolver. + _ "google.golang.org/grpc/resolver/passthrough" // To register passthrough resolver. "google.golang.org/grpc/stats" + "google.golang.org/grpc/status" "google.golang.org/grpc/transport" ) +const ( + // minimum time to give a connection to complete + minConnectTimeout = 20 * time.Second +) + var ( // ErrClientConnClosing indicates that the operation is illegal because // the ClientConn is closing. - ErrClientConnClosing = errors.New("grpc: the client connection is closing") - // ErrClientConnTimeout indicates that the ClientConn cannot establish the - // underlying connections within the specified timeout. - // DEPRECATED: Please use context.DeadlineExceeded instead. - ErrClientConnTimeout = errors.New("grpc: timed out when dialing") + // + // Deprecated: this error should not be relied upon by users; use the status + // code of Canceled instead. + ErrClientConnClosing = status.Error(codes.Canceled, "grpc: the client connection is closing") + // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs. + errConnDrain = errors.New("grpc: the connection is drained") + // errConnClosing indicates that the connection is closing. + errConnClosing = errors.New("grpc: the connection is closing") + // errConnUnavailable indicates that the connection is unavailable. + errConnUnavailable = errors.New("grpc: the connection is unavailable") + // errBalancerClosed indicates that the balancer is closed. + errBalancerClosed = errors.New("grpc: balancer is closed") + // We use an accessor so that minConnectTimeout can be + // atomically read and updated while testing. + getMinConnectTimeout = func() time.Duration { + return minConnectTimeout + } +) +// The following errors are returned from Dial and DialContext +var ( // errNoTransportSecurity indicates that there is no transport security // being set for ClientConn. Users should either set one or explicitly // call WithInsecure DialOption to disable security. @@ -62,16 +88,6 @@ var ( errCredentialsConflict = errors.New("grpc: transport credentials are set for an insecure connection (grpc.WithTransportCredentials() and grpc.WithInsecure() are both called)") // errNetworkIO indicates that the connection is down due to some network I/O error. errNetworkIO = errors.New("grpc: failed with network I/O error") - // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs. - errConnDrain = errors.New("grpc: the connection is drained") - // errConnClosing indicates that the connection is closing. - errConnClosing = errors.New("grpc: the connection is closing") - // errConnUnavailable indicates that the connection is unavailable. - errConnUnavailable = errors.New("grpc: the connection is unavailable") - // errBalancerClosed indicates that the balancer is closed. - errBalancerClosed = errors.New("grpc: balancer is closed") - // minimum time to give a connection to complete - minConnectTimeout = 20 * time.Second ) // dialOptions configure a Dial call. dialOptions are set by the DialOption @@ -79,7 +95,6 @@ var ( type dialOptions struct { unaryInt UnaryClientInterceptor streamInt StreamClientInterceptor - codec Codec cp Compressor dc Decompressor bs backoffStrategy @@ -89,8 +104,14 @@ type dialOptions struct { scChan <-chan ServiceConfig copts transport.ConnectOptions callOptions []CallOption - // This is to support v1 balancer. + // This is used by v1 balancer dial option WithBalancer to support v1 + // balancer, and also by WithBalancerName dial option. balancerBuilder balancer.Builder + // This is to support grpclb. + resolverBuilder resolver.Builder + waitForHandshake bool + channelzParentID int64 + disableServiceConfig bool } const ( @@ -98,9 +119,24 @@ const ( defaultClientMaxSendMessageSize = math.MaxInt32 ) +// RegisterChannelz turns on channelz service. +// This is an EXPERIMENTAL API. +func RegisterChannelz() { + channelz.TurnOn() +} + // DialOption configures how we set up the connection. type DialOption func(*dialOptions) +// WithWaitForHandshake blocks until the initial settings frame is received from the +// server before assigning RPCs to the connection. +// Experimental API. +func WithWaitForHandshake() DialOption { + return func(o *dialOptions) { + o.waitForHandshake = true + } +} + // WithWriteBufferSize lets you set the size of write buffer, this determines how much data can be batched // before doing a write on the wire. func WithWriteBufferSize(s int) DialOption { @@ -133,7 +169,9 @@ func WithInitialConnWindowSize(s int32) DialOption { } } -// WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive. Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead. +// WithMaxMsgSize returns a DialOption which sets the maximum message size the client can receive. +// +// Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead. func WithMaxMsgSize(s int) DialOption { return WithDefaultCallOptions(MaxCallRecvMsgSize(s)) } @@ -146,22 +184,32 @@ func WithDefaultCallOptions(cos ...CallOption) DialOption { } // WithCodec returns a DialOption which sets a codec for message marshaling and unmarshaling. +// +// Deprecated: use WithDefaultCallOptions(CallCustomCodec(c)) instead. func WithCodec(c Codec) DialOption { - return func(o *dialOptions) { - o.codec = c - } + return WithDefaultCallOptions(CallCustomCodec(c)) } -// WithCompressor returns a DialOption which sets a CompressorGenerator for generating message -// compressor. +// WithCompressor returns a DialOption which sets a Compressor to use for +// message compression. It has lower priority than the compressor set by +// the UseCompressor CallOption. +// +// Deprecated: use UseCompressor instead. func WithCompressor(cp Compressor) DialOption { return func(o *dialOptions) { o.cp = cp } } -// WithDecompressor returns a DialOption which sets a DecompressorGenerator for generating -// message decompressor. +// WithDecompressor returns a DialOption which sets a Decompressor to use for +// incoming message decompression. If incoming response messages are encoded +// using the decompressor's Type(), it will be used. Otherwise, the message +// encoding will be used to look up the compressor registered via +// encoding.RegisterCompressor, which will then be used to decompress the +// message. If no compressor is registered for the encoding, an Unimplemented +// status error will be returned. +// +// Deprecated: use encoding.RegisterCompressor instead. func WithDecompressor(dc Decompressor) DialOption { return func(o *dialOptions) { o.dc = dc @@ -170,7 +218,8 @@ func WithDecompressor(dc Decompressor) DialOption { // WithBalancer returns a DialOption which sets a load balancer with the v1 API. // Name resolver will be ignored if this DialOption is specified. -// Deprecated: use the new balancer APIs in balancer package instead. +// +// Deprecated: use the new balancer APIs in balancer package and WithBalancerName. func WithBalancer(b Balancer) DialOption { return func(o *dialOptions) { o.balancerBuilder = &balancerWrapperBuilder{ @@ -179,16 +228,35 @@ func WithBalancer(b Balancer) DialOption { } } -// WithBalancerBuilder is for testing only. Users using custom balancers should -// register their balancer and use service config to choose the balancer to use. -func WithBalancerBuilder(b balancer.Builder) DialOption { - // TODO(bar) remove this when switching balancer is done. +// WithBalancerName sets the balancer that the ClientConn will be initialized +// with. Balancer registered with balancerName will be used. This function +// panics if no balancer was registered by balancerName. +// +// The balancer cannot be overridden by balancer option specified by service +// config. +// +// This is an EXPERIMENTAL API. +func WithBalancerName(balancerName string) DialOption { + builder := balancer.Get(balancerName) + if builder == nil { + panic(fmt.Sprintf("grpc.WithBalancerName: no balancer is registered for name %v", balancerName)) + } + return func(o *dialOptions) { + o.balancerBuilder = builder + } +} + +// withResolverBuilder is only for grpclb. +func withResolverBuilder(b resolver.Builder) DialOption { return func(o *dialOptions) { - o.balancerBuilder = b + o.resolverBuilder = b } } // WithServiceConfig returns a DialOption which has a channel to read the service configuration. +// +// Deprecated: service config should be received through name resolver, as specified here. +// https://github.com/grpc/grpc/blob/master/doc/service_config.md func WithServiceConfig(c <-chan ServiceConfig) DialOption { return func(o *dialOptions) { o.scChan = c @@ -213,7 +281,7 @@ func WithBackoffConfig(b BackoffConfig) DialOption { return withBackoff(b) } -// withBackoff sets the backoff strategy used for retries after a +// withBackoff sets the backoff strategy used for connectRetryNum after a // failed connection attempt. // // This can be exported if arbitrary backoff strategies are allowed by gRPC. @@ -258,6 +326,7 @@ func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption { // WithTimeout returns a DialOption that configures a timeout for dialing a ClientConn // initially. This is valid if and only if WithBlock() is present. +// // Deprecated: use DialContext and context.WithTimeout instead. func WithTimeout(d time.Duration) DialOption { return func(o *dialOptions) { @@ -265,18 +334,23 @@ func WithTimeout(d time.Duration) DialOption { } } +func withContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption { + return func(o *dialOptions) { + o.copts.Dialer = f + } +} + // WithDialer returns a DialOption that specifies a function to use for dialing network addresses. // If FailOnNonTempDialError() is set to true, and an error is returned by f, gRPC checks the error's // Temporary() method to decide if it should try to reconnect to the network address. func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption { - return func(o *dialOptions) { - o.copts.Dialer = func(ctx context.Context, addr string) (net.Conn, error) { + return withContextDialer( + func(ctx context.Context, addr string) (net.Conn, error) { if deadline, ok := ctx.Deadline(); ok { return f(addr, deadline.Sub(time.Now())) } return f(addr, 0) - } - } + }) } // WithStatsHandler returns a DialOption that specifies the stats handler @@ -335,15 +409,44 @@ func WithAuthority(a string) DialOption { } } +// WithChannelzParentID returns a DialOption that specifies the channelz ID of current ClientConn's +// parent. This function is used in nested channel creation (e.g. grpclb dial). +func WithChannelzParentID(id int64) DialOption { + return func(o *dialOptions) { + o.channelzParentID = id + } +} + +// WithDisableServiceConfig returns a DialOption that causes grpc to ignore any +// service config provided by the resolver and provides a hint to the resolver +// to not fetch service configs. +func WithDisableServiceConfig() DialOption { + return func(o *dialOptions) { + o.disableServiceConfig = true + } +} + // Dial creates a client connection to the given target. func Dial(target string, opts ...DialOption) (*ClientConn, error) { return DialContext(context.Background(), target, opts...) } -// DialContext creates a client connection to the given target. ctx can be used to -// cancel or expire the pending connection. Once this function returns, the -// cancellation and expiration of ctx will be noop. Users should call ClientConn.Close -// to terminate all the pending operations after this function returns. +// DialContext creates a client connection to the given target. By default, it's +// a non-blocking dial (the function won't wait for connections to be +// established, and connecting happens in the background). To make it a blocking +// dial, use WithBlock() dial option. +// +// In the non-blocking case, the ctx does not act against the connection. It +// only controls the setup steps. +// +// In the blocking case, ctx can be used to cancel or expire the pending +// connection. Once this function returns, the cancellation and expiration of +// ctx will be noop. Users should call ClientConn.Close to terminate all the +// pending operations after this function returns. +// +// The target name syntax is defined in +// https://github.com/grpc/grpc/blob/master/doc/naming.md. +// e.g. to use dns resolver, a "dns:///" prefix should be applied to the target. func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error) { cc := &ClientConn{ target: target, @@ -358,6 +461,14 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * opt(&cc.dopts) } + if channelz.IsOn() { + if cc.dopts.channelzParentID != 0 { + cc.channelzID = channelz.RegisterChannel(cc, cc.dopts.channelzParentID, target) + } else { + cc.channelzID = channelz.RegisterChannel(cc, 0, target) + } + } + if !cc.dopts.insecure { if cc.dopts.copts.TransportCredentials == nil { return nil, errNoTransportSecurity @@ -378,7 +489,8 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * if cc.dopts.copts.Dialer == nil { cc.dopts.copts.Dialer = newProxyDialer( func(ctx context.Context, addr string) (net.Conn, error) { - return (&net.Dialer{}).DialContext(ctx, "tcp", addr) + network, addr := parseDialTarget(addr) + return dialContext(ctx, network, addr) }, ) } @@ -419,58 +531,39 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * default: } } - // Set defaults. - if cc.dopts.codec == nil { - cc.dopts.codec = protoCodec{} - } if cc.dopts.bs == nil { cc.dopts.bs = DefaultBackoffConfig } + if cc.dopts.resolverBuilder == nil { + // Only try to parse target when resolver builder is not already set. + cc.parsedTarget = parseTarget(cc.target) + grpclog.Infof("parsed scheme: %q", cc.parsedTarget.Scheme) + cc.dopts.resolverBuilder = resolver.Get(cc.parsedTarget.Scheme) + if cc.dopts.resolverBuilder == nil { + // If resolver builder is still nil, the parse target's scheme is + // not registered. Fallback to default resolver and set Endpoint to + // the original unparsed target. + grpclog.Infof("scheme %q not registered, fallback to default scheme", cc.parsedTarget.Scheme) + cc.parsedTarget = resolver.Target{ + Scheme: resolver.GetDefaultScheme(), + Endpoint: target, + } + cc.dopts.resolverBuilder = resolver.Get(cc.parsedTarget.Scheme) + } + } else { + cc.parsedTarget = resolver.Target{Endpoint: target} + } creds := cc.dopts.copts.TransportCredentials if creds != nil && creds.Info().ServerName != "" { cc.authority = creds.Info().ServerName } else if cc.dopts.insecure && cc.dopts.copts.Authority != "" { cc.authority = cc.dopts.copts.Authority } else { - cc.authority = target + // Use endpoint from "scheme://authority/endpoint" as the default + // authority for ClientConn. + cc.authority = cc.parsedTarget.Endpoint } - if cc.dopts.balancerBuilder != nil { - var credsClone credentials.TransportCredentials - if creds != nil { - credsClone = creds.Clone() - } - buildOpts := balancer.BuildOptions{ - DialCreds: credsClone, - Dialer: cc.dopts.copts.Dialer, - } - // Build should not take long time. So it's ok to not have a goroutine for it. - // TODO(bar) init balancer after first resolver result to support service config balancer. - cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, buildOpts) - } else { - waitC := make(chan error, 1) - go func() { - defer close(waitC) - // No balancer, or no resolver within the balancer. Connect directly. - ac, err := cc.newAddrConn([]resolver.Address{{Addr: target}}) - if err != nil { - waitC <- err - return - } - if err := ac.connect(cc.dopts.block); err != nil { - waitC <- err - return - } - }() - select { - case <-ctx.Done(): - return nil, ctx.Err() - case err := <-waitC: - if err != nil { - return nil, err - } - } - } if cc.dopts.scChan != nil && !scSet { // Blocking wait for the initial service config. select { @@ -486,19 +579,29 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * go cc.scWatcher() } + var credsClone credentials.TransportCredentials + if creds := cc.dopts.copts.TransportCredentials; creds != nil { + credsClone = creds.Clone() + } + cc.balancerBuildOpts = balancer.BuildOptions{ + DialCreds: credsClone, + Dialer: cc.dopts.copts.Dialer, + ChannelzParentID: cc.channelzID, + } + // Build the resolver. cc.resolverWrapper, err = newCCResolverWrapper(cc) if err != nil { return nil, fmt.Errorf("failed to build resolver: %v", err) } - - if cc.balancerWrapper != nil && cc.resolverWrapper == nil { - // TODO(bar) there should always be a resolver (DNS as the default). - // Unblock balancer initialization with a fake resolver update if there's no resolver. - // The balancer wrapper will not read the addresses, so an empty list works. - // TODO(bar) remove this after the real resolver is started. - cc.balancerWrapper.handleResolvedAddrs([]resolver.Address{}, nil) - } + // Start the resolver wrapper goroutine after resolverWrapper is created. + // + // If the goroutine is started before resolverWrapper is ready, the + // following may happen: The goroutine sends updates to cc. cc forwards + // those to balancer. Balancer creates new addrConn. addrConn fails to + // connect, and calls resolveNow(). resolveNow() tries to use the non-ready + // resolverWrapper. + cc.resolverWrapper.start() // A blocking dial blocks until the clientConn is ready. if cc.dopts.block { @@ -565,21 +668,33 @@ type ClientConn struct { ctx context.Context cancel context.CancelFunc - target string - authority string - dopts dialOptions - csMgr *connectivityStateManager - - balancerWrapper *ccBalancerWrapper - resolverWrapper *ccResolverWrapper + target string + parsedTarget resolver.Target + authority string + dopts dialOptions + csMgr *connectivityStateManager - blockingpicker *pickerWrapper + balancerBuildOpts balancer.BuildOptions + resolverWrapper *ccResolverWrapper + blockingpicker *pickerWrapper mu sync.RWMutex sc ServiceConfig + scRaw string conns map[*addrConn]struct{} // Keepalive parameter can be updated if a GoAway is received. - mkp keepalive.ClientParameters + mkp keepalive.ClientParameters + curBalancerName string + preBalancerName string // previous balancer name. + curAddresses []resolver.Address + balancerWrapper *ccBalancerWrapper + + channelzID int64 // channelz unique identification number + czmu sync.RWMutex + callsStarted int64 + callsSucceeded int64 + callsFailed int64 + lastCallStartedTime time.Time } // WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or @@ -615,6 +730,7 @@ func (cc *ClientConn) scWatcher() { // TODO: load balance policy runtime change is ignored. // We may revist this decision in the future. cc.sc = sc + cc.scRaw = "" cc.mu.Unlock() case <-cc.ctx.Done(): return @@ -622,7 +738,115 @@ func (cc *ClientConn) scWatcher() { } } +func (cc *ClientConn) handleResolvedAddrs(addrs []resolver.Address, err error) { + cc.mu.Lock() + defer cc.mu.Unlock() + if cc.conns == nil { + // cc was closed. + return + } + + if reflect.DeepEqual(cc.curAddresses, addrs) { + return + } + + cc.curAddresses = addrs + + if cc.dopts.balancerBuilder == nil { + // Only look at balancer types and switch balancer if balancer dial + // option is not set. + var isGRPCLB bool + for _, a := range addrs { + if a.Type == resolver.GRPCLB { + isGRPCLB = true + break + } + } + var newBalancerName string + if isGRPCLB { + newBalancerName = grpclbName + } else { + // Address list doesn't contain grpclb address. Try to pick a + // non-grpclb balancer. + newBalancerName = cc.curBalancerName + // If current balancer is grpclb, switch to the previous one. + if newBalancerName == grpclbName { + newBalancerName = cc.preBalancerName + } + // The following could be true in two cases: + // - the first time handling resolved addresses + // (curBalancerName="") + // - the first time handling non-grpclb addresses + // (curBalancerName="grpclb", preBalancerName="") + if newBalancerName == "" { + newBalancerName = PickFirstBalancerName + } + } + cc.switchBalancer(newBalancerName) + } else if cc.balancerWrapper == nil { + // Balancer dial option was set, and this is the first time handling + // resolved addresses. Build a balancer with dopts.balancerBuilder. + cc.balancerWrapper = newCCBalancerWrapper(cc, cc.dopts.balancerBuilder, cc.balancerBuildOpts) + } + + cc.balancerWrapper.handleResolvedAddrs(addrs, nil) +} + +// switchBalancer starts the switching from current balancer to the balancer +// with the given name. +// +// It will NOT send the current address list to the new balancer. If needed, +// caller of this function should send address list to the new balancer after +// this function returns. +// +// Caller must hold cc.mu. +func (cc *ClientConn) switchBalancer(name string) { + if cc.conns == nil { + return + } + + if strings.ToLower(cc.curBalancerName) == strings.ToLower(name) { + return + } + + grpclog.Infof("ClientConn switching balancer to %q", name) + if cc.dopts.balancerBuilder != nil { + grpclog.Infoln("ignoring balancer switching: Balancer DialOption used instead") + return + } + // TODO(bar switching) change this to two steps: drain and close. + // Keep track of sc in wrapper. + if cc.balancerWrapper != nil { + cc.balancerWrapper.close() + } + // Clear all stickiness state. + cc.blockingpicker.clearStickinessState() + + builder := balancer.Get(name) + if builder == nil { + grpclog.Infof("failed to get balancer builder for: %v, using pick_first instead", name) + builder = newPickfirstBuilder() + } + cc.preBalancerName = cc.curBalancerName + cc.curBalancerName = builder.Name() + cc.balancerWrapper = newCCBalancerWrapper(cc, builder, cc.balancerBuildOpts) +} + +func (cc *ClientConn) handleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { + cc.mu.Lock() + if cc.conns == nil { + cc.mu.Unlock() + return + } + // TODO(bar switching) send updates to all balancer wrappers when balancer + // gracefully switching is supported. + cc.balancerWrapper.handleSubConnStateChange(sc, s) + cc.mu.Unlock() +} + // newAddrConn creates an addrConn for addrs and adds it to cc.conns. +// +// Caller needs to make sure len(addrs) > 0. func (cc *ClientConn) newAddrConn(addrs []resolver.Address) (*addrConn, error) { ac := &addrConn{ cc: cc, @@ -636,6 +860,9 @@ func (cc *ClientConn) newAddrConn(addrs []resolver.Address) (*addrConn, error) { cc.mu.Unlock() return nil, ErrClientConnClosing } + if channelz.IsOn() { + ac.channelzID = channelz.RegisterSubChannel(ac, cc.channelzID, "") + } cc.conns[ac] = struct{}{} cc.mu.Unlock() return ac, nil @@ -654,12 +881,48 @@ func (cc *ClientConn) removeAddrConn(ac *addrConn, err error) { ac.tearDown(err) } +// ChannelzMetric returns ChannelInternalMetric of current ClientConn. +// This is an EXPERIMENTAL API. +func (cc *ClientConn) ChannelzMetric() *channelz.ChannelInternalMetric { + state := cc.GetState() + cc.czmu.RLock() + defer cc.czmu.RUnlock() + return &channelz.ChannelInternalMetric{ + State: state, + Target: cc.target, + CallsStarted: cc.callsStarted, + CallsSucceeded: cc.callsSucceeded, + CallsFailed: cc.callsFailed, + LastCallStartedTimestamp: cc.lastCallStartedTime, + } +} + +func (cc *ClientConn) incrCallsStarted() { + cc.czmu.Lock() + cc.callsStarted++ + // TODO(yuxuanli): will make this a time.Time pointer improve performance? + cc.lastCallStartedTime = time.Now() + cc.czmu.Unlock() +} + +func (cc *ClientConn) incrCallsSucceeded() { + cc.czmu.Lock() + cc.callsSucceeded++ + cc.czmu.Unlock() +} + +func (cc *ClientConn) incrCallsFailed() { + cc.czmu.Lock() + cc.callsFailed++ + cc.czmu.Unlock() +} + // connect starts to creating transport and also starts the transport monitor // goroutine for this ac. // It does nothing if the ac is not IDLE. // TODO(bar) Move this to the addrConn section. // This was part of resetAddrConn, keep it here to make the diff look clean. -func (ac *addrConn) connect(block bool) error { +func (ac *addrConn) connect() error { ac.mu.Lock() if ac.state == connectivity.Shutdown { ac.mu.Unlock() @@ -670,39 +933,21 @@ func (ac *addrConn) connect(block bool) error { return nil } ac.state = connectivity.Connecting - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) ac.mu.Unlock() - if block { + // Start a goroutine connecting to the server asynchronously. + go func() { if err := ac.resetTransport(); err != nil { + grpclog.Warningf("Failed to dial %s: %v; please retry.", ac.addrs[0].Addr, err) if err != errConnClosing { + // Keep this ac in cc.conns, to get the reason it's torn down. ac.tearDown(err) } - if e, ok := err.(transport.ConnectionError); ok && !e.Temporary() { - return e.Origin() - } - return err + return } - // Start to monitor the error status of transport. - go ac.transportMonitor() - } else { - // Start a goroutine connecting to the server asynchronously. - go func() { - if err := ac.resetTransport(); err != nil { - grpclog.Warningf("Failed to dial %s: %v; please retry.", ac.addrs[0].Addr, err) - if err != errConnClosing { - // Keep this ac in cc.conns, to get the reason it's torn down. - ac.tearDown(err) - } - return - } - ac.transportMonitor() - }() - } + ac.transportMonitor() + }() return nil } @@ -731,6 +976,7 @@ func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool { grpclog.Infof("addrConn: tryUpdateAddrs curAddrFound: %v", curAddrFound) if curAddrFound { ac.addrs = addrs + ac.reconnectIdx = 0 // Start reconnecting from beginning in the new list. } return curAddrFound @@ -741,7 +987,7 @@ func (ac *addrConn) tryUpdateAddrs(addrs []resolver.Address) bool { // the corresponding MethodConfig. // If there isn't an exact match for the input method, we look for the default config // under the service (i.e /service/). If there is a default MethodConfig for -// the serivce, we return it. +// the service, we return it. // Otherwise, we return an empty MethodConfig. func (cc *ClientConn) GetMethodConfig(method string) MethodConfig { // TODO: Avoid the locking here. @@ -750,37 +996,12 @@ func (cc *ClientConn) GetMethodConfig(method string) MethodConfig { m, ok := cc.sc.Methods[method] if !ok { i := strings.LastIndex(method, "/") - m, _ = cc.sc.Methods[method[:i+1]] + m = cc.sc.Methods[method[:i+1]] } return m } func (cc *ClientConn) getTransport(ctx context.Context, failfast bool) (transport.ClientTransport, func(balancer.DoneInfo), error) { - if cc.balancerWrapper == nil { - // If balancer is nil, there should be only one addrConn available. - cc.mu.RLock() - if cc.conns == nil { - cc.mu.RUnlock() - // TODO this function returns toRPCErr and non-toRPCErr. Clean up - // the errors in ClientConn. - return nil, nil, toRPCErr(ErrClientConnClosing) - } - var ac *addrConn - for ac = range cc.conns { - // Break after the first iteration to get the first addrConn. - break - } - cc.mu.RUnlock() - if ac == nil { - return nil, nil, errConnClosing - } - t, err := ac.wait(ctx, false /*hasBalancer*/, failfast) - if err != nil { - return nil, nil, err - } - return t, nil, nil - } - t, done, err := cc.blockingpicker.pick(ctx, failfast, balancer.PickOptions{}) if err != nil { return nil, nil, toRPCErr(err) @@ -788,9 +1009,61 @@ func (cc *ClientConn) getTransport(ctx context.Context, failfast bool) (transpor return t, done, nil } +// handleServiceConfig parses the service config string in JSON format to Go native +// struct ServiceConfig, and store both the struct and the JSON string in ClientConn. +func (cc *ClientConn) handleServiceConfig(js string) error { + if cc.dopts.disableServiceConfig { + return nil + } + sc, err := parseServiceConfig(js) + if err != nil { + return err + } + cc.mu.Lock() + cc.scRaw = js + cc.sc = sc + if sc.LB != nil && *sc.LB != grpclbName { // "grpclb" is not a valid balancer option in service config. + if cc.curBalancerName == grpclbName { + // If current balancer is grpclb, there's at least one grpclb + // balancer address in the resolved list. Don't switch the balancer, + // but change the previous balancer name, so if a new resolved + // address list doesn't contain grpclb address, balancer will be + // switched to *sc.LB. + cc.preBalancerName = *sc.LB + } else { + cc.switchBalancer(*sc.LB) + cc.balancerWrapper.handleResolvedAddrs(cc.curAddresses, nil) + } + } + + if envConfigStickinessOn { + var newStickinessMDKey string + if sc.stickinessMetadataKey != nil && *sc.stickinessMetadataKey != "" { + newStickinessMDKey = *sc.stickinessMetadataKey + } + // newStickinessMDKey is "" if one of the following happens: + // - stickinessMetadataKey is set to "" + // - stickinessMetadataKey field doesn't exist in service config + cc.blockingpicker.updateStickinessMDKey(strings.ToLower(newStickinessMDKey)) + } + + cc.mu.Unlock() + return nil +} + +func (cc *ClientConn) resolveNow(o resolver.ResolveNowOption) { + cc.mu.Lock() + r := cc.resolverWrapper + cc.mu.Unlock() + if r == nil { + return + } + go r.resolveNow(o) +} + // Close tears down the ClientConn and all underlying connections. func (cc *ClientConn) Close() error { - cc.cancel() + defer cc.cancel() cc.mu.Lock() if cc.conns == nil { @@ -800,17 +1073,28 @@ func (cc *ClientConn) Close() error { conns := cc.conns cc.conns = nil cc.csMgr.updateState(connectivity.Shutdown) + + rWrapper := cc.resolverWrapper + cc.resolverWrapper = nil + bWrapper := cc.balancerWrapper + cc.balancerWrapper = nil cc.mu.Unlock() + cc.blockingpicker.close() - if cc.resolverWrapper != nil { - cc.resolverWrapper.close() + + if rWrapper != nil { + rWrapper.close() } - if cc.balancerWrapper != nil { - cc.balancerWrapper.close() + if bWrapper != nil { + bWrapper.close() } + for ac := range conns { ac.tearDown(ErrClientConnClosing) } + if channelz.IsOn() { + channelz.RemoveEntry(cc.channelzID) + } return nil } @@ -819,15 +1103,16 @@ type addrConn struct { ctx context.Context cancel context.CancelFunc - cc *ClientConn - curAddr resolver.Address - addrs []resolver.Address - dopts dialOptions - events trace.EventLog - acbw balancer.SubConn + cc *ClientConn + addrs []resolver.Address + dopts dialOptions + events trace.EventLog + acbw balancer.SubConn - mu sync.Mutex - state connectivity.State + mu sync.Mutex + curAddr resolver.Address + reconnectIdx int // The index in addrs list to start reconnecting from. + state connectivity.State // ready is closed and becomes nil when a new transport is up or failed // due to timeout. ready chan struct{} @@ -835,13 +1120,28 @@ type addrConn struct { // The reason this addrConn is torn down. tearDownErr error + + connectRetryNum int + // backoffDeadline is the time until which resetTransport needs to + // wait before increasing connectRetryNum count. + backoffDeadline time.Time + // connectDeadline is the time by which all connection + // negotiations must complete. + connectDeadline time.Time + + channelzID int64 // channelz unique identification number + czmu sync.RWMutex + callsStarted int64 + callsSucceeded int64 + callsFailed int64 + lastCallStartedTime time.Time } // adjustParams updates parameters used to create transports upon // receiving a GoAway. func (ac *addrConn) adjustParams(r transport.GoAwayReason) { switch r { - case transport.TooManyPings: + case transport.GoAwayTooManyPings: v := 2 * ac.dopts.copts.KeepaliveParams.Time ac.cc.mu.Lock() if v > ac.cc.mkp.Time { @@ -869,6 +1169,15 @@ func (ac *addrConn) errorf(format string, a ...interface{}) { // resetTransport recreates a transport to the address for ac. The old // transport will close itself on error or when the clientconn is closed. +// The created transport must receive initial settings frame from the server. +// In case that doesn't happen, transportMonitor will kill the newly created +// transport after connectDeadline has expired. +// In case there was an error on the transport before the settings frame was +// received, resetTransport resumes connecting to backends after the one that +// was previously connected to. In case end of the list is reached, resetTransport +// backs off until the original deadline. +// If the DialOption WithWaitForHandshake was set, resetTrasport returns +// successfully only after server settings are received. // // TODO(bar) make sure all state transitions are valid. func (ac *addrConn) resetTransport() error { @@ -882,19 +1191,38 @@ func (ac *addrConn) resetTransport() error { ac.ready = nil } ac.transport = nil - ac.curAddr = resolver.Address{} + ridx := ac.reconnectIdx ac.mu.Unlock() ac.cc.mu.RLock() ac.dopts.copts.KeepaliveParams = ac.cc.mkp ac.cc.mu.RUnlock() - for retries := 0; ; retries++ { - sleepTime := ac.dopts.bs.backoff(retries) - timeout := minConnectTimeout + var backoffDeadline, connectDeadline time.Time + for connectRetryNum := 0; ; connectRetryNum++ { ac.mu.Lock() - if timeout < time.Duration(int(sleepTime)/len(ac.addrs)) { - timeout = time.Duration(int(sleepTime) / len(ac.addrs)) + if ac.backoffDeadline.IsZero() { + // This means either a successful HTTP2 connection was established + // or this is the first time this addrConn is trying to establish a + // connection. + backoffFor := ac.dopts.bs.backoff(connectRetryNum) // time.Duration. + // This will be the duration that dial gets to finish. + dialDuration := getMinConnectTimeout() + if backoffFor > dialDuration { + // Give dial more time as we keep failing to connect. + dialDuration = backoffFor + } + start := time.Now() + backoffDeadline = start.Add(backoffFor) + connectDeadline = start.Add(dialDuration) + ridx = 0 // Start connecting from the beginning. + } else { + // Continue trying to connect with the same deadlines. + connectRetryNum = ac.connectRetryNum + backoffDeadline = ac.backoffDeadline + connectDeadline = ac.connectDeadline + ac.backoffDeadline = time.Time{} + ac.connectDeadline = time.Time{} + ac.connectRetryNum = 0 } - connectTime := time.Now() if ac.state == connectivity.Shutdown { ac.mu.Unlock() return errConnClosing @@ -902,106 +1230,178 @@ func (ac *addrConn) resetTransport() error { ac.printf("connecting") if ac.state != connectivity.Connecting { ac.state = connectivity.Connecting - // TODO(bar) remove condition once we always have a balancer. - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) } // copy ac.addrs in case of race addrsIter := make([]resolver.Address, len(ac.addrs)) copy(addrsIter, ac.addrs) copts := ac.dopts.copts ac.mu.Unlock() - for _, addr := range addrsIter { + connected, err := ac.createTransport(connectRetryNum, ridx, backoffDeadline, connectDeadline, addrsIter, copts) + if err != nil { + return err + } + if connected { + return nil + } + } +} + +// createTransport creates a connection to one of the backends in addrs. +// It returns true if a connection was established. +func (ac *addrConn) createTransport(connectRetryNum, ridx int, backoffDeadline, connectDeadline time.Time, addrs []resolver.Address, copts transport.ConnectOptions) (bool, error) { + for i := ridx; i < len(addrs); i++ { + addr := addrs[i] + target := transport.TargetInfo{ + Addr: addr.Addr, + Metadata: addr.Metadata, + Authority: ac.cc.authority, + } + done := make(chan struct{}) + onPrefaceReceipt := func() { ac.mu.Lock() - if ac.state == connectivity.Shutdown { - // ac.tearDown(...) has been invoked. - ac.mu.Unlock() - return errConnClosing + close(done) + if !ac.backoffDeadline.IsZero() { + // If we haven't already started reconnecting to + // other backends. + // Note, this can happen when writer notices an error + // and triggers resetTransport while at the same time + // reader receives the preface and invokes this closure. + ac.backoffDeadline = time.Time{} + ac.connectDeadline = time.Time{} + ac.connectRetryNum = 0 } ac.mu.Unlock() - sinfo := transport.TargetInfo{ - Addr: addr.Addr, - Metadata: addr.Metadata, - } - newTransport, err := transport.NewClientTransport(ac.cc.ctx, sinfo, copts, timeout) - if err != nil { - if e, ok := err.(transport.ConnectionError); ok && !e.Temporary() { - return err - } - grpclog.Warningf("grpc: addrConn.resetTransport failed to create client transport: %v; Reconnecting to %v", err, addr) - ac.mu.Lock() - if ac.state == connectivity.Shutdown { - // ac.tearDown(...) has been invoked. - ac.mu.Unlock() - return errConnClosing - } - ac.mu.Unlock() - continue - } + } + // Do not cancel in the success path because of + // this issue in Go1.6: https://github.com/golang/go/issues/15078. + connectCtx, cancel := context.WithDeadline(ac.ctx, connectDeadline) + if channelz.IsOn() { + copts.ChannelzParentID = ac.channelzID + } + newTr, err := transport.NewClientTransport(connectCtx, ac.cc.ctx, target, copts, onPrefaceReceipt) + if err != nil { + cancel() + ac.cc.blockingpicker.updateConnectionError(err) ac.mu.Lock() - ac.printf("ready") if ac.state == connectivity.Shutdown { // ac.tearDown(...) has been invoked. ac.mu.Unlock() - newTransport.Close() - return errConnClosing - } - ac.state = connectivity.Ready - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } - t := ac.transport - ac.transport = newTransport - if t != nil { - t.Close() - } - ac.curAddr = addr - if ac.ready != nil { - close(ac.ready) - ac.ready = nil + return false, errConnClosing } ac.mu.Unlock() - return nil + grpclog.Warningf("grpc: addrConn.createTransport failed to connect to %v. Err :%v. Reconnecting...", addr, err) + continue + } + if ac.dopts.waitForHandshake { + select { + case <-done: + case <-connectCtx.Done(): + // Didn't receive server preface, must kill this new transport now. + grpclog.Warningf("grpc: addrConn.createTransport failed to receive server preface before deadline.") + newTr.Close() + break + case <-ac.ctx.Done(): + } } ac.mu.Lock() - ac.state = connectivity.TransientFailure - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) + if ac.state == connectivity.Shutdown { + ac.mu.Unlock() + // ac.tearDonn(...) has been invoked. + newTr.Close() + return false, errConnClosing } + ac.printf("ready") + ac.state = connectivity.Ready + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) + ac.transport = newTr + ac.curAddr = addr if ac.ready != nil { close(ac.ready) ac.ready = nil } - ac.mu.Unlock() - timer := time.NewTimer(sleepTime - time.Since(connectTime)) select { - case <-timer.C: - case <-ac.ctx.Done(): - timer.Stop() - return ac.ctx.Err() + case <-done: + // If the server has responded back with preface already, + // don't set the reconnect parameters. + default: + ac.connectRetryNum = connectRetryNum + ac.backoffDeadline = backoffDeadline + ac.connectDeadline = connectDeadline + ac.reconnectIdx = i + 1 // Start reconnecting from the next backend in the list. } + ac.mu.Unlock() + return true, nil + } + ac.mu.Lock() + if ac.state == connectivity.Shutdown { + ac.mu.Unlock() + return false, errConnClosing + } + ac.state = connectivity.TransientFailure + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) + ac.cc.resolveNow(resolver.ResolveNowOption{}) + if ac.ready != nil { + close(ac.ready) + ac.ready = nil + } + ac.mu.Unlock() + timer := time.NewTimer(backoffDeadline.Sub(time.Now())) + select { + case <-timer.C: + case <-ac.ctx.Done(): timer.Stop() + return false, ac.ctx.Err() } + return false, nil } // Run in a goroutine to track the error in transport and create the // new transport if an error happens. It returns when the channel is closing. func (ac *addrConn) transportMonitor() { for { + var timer *time.Timer + var cdeadline <-chan time.Time ac.mu.Lock() t := ac.transport + if !ac.connectDeadline.IsZero() { + timer = time.NewTimer(ac.connectDeadline.Sub(time.Now())) + cdeadline = timer.C + } ac.mu.Unlock() // Block until we receive a goaway or an error occurs. select { case <-t.GoAway(): + done := t.Error() + cleanup := t.Close + // Since this transport will be orphaned (won't have a transportMonitor) + // we need to launch a goroutine to keep track of clientConn.Close() + // happening since it might not be noticed by any other goroutine for a while. + go func() { + <-done + cleanup() + }() case <-t.Error(): + // In case this is triggered because clientConn.Close() + // was called, we want to immeditately close the transport + // since no other goroutine might notice it for a while. + t.Close() + case <-cdeadline: + ac.mu.Lock() + // This implies that client received server preface. + if ac.backoffDeadline.IsZero() { + ac.mu.Unlock() + continue + } + ac.mu.Unlock() + timer = nil + // No server preface received until deadline. + // Kill the connection. + grpclog.Warningf("grpc: addrConn.transportMonitor didn't get server preface after waiting. Closing the new transport now.") + t.Close() + } + if timer != nil { + timer.Stop() } // If a GoAway happened, regardless of error, adjust our keepalive // parameters as appropriate. @@ -1018,11 +1418,8 @@ func (ac *addrConn) transportMonitor() { // Set connectivity state to TransientFailure before calling // resetTransport. Transition READY->CONNECTING is not valid. ac.state = connectivity.TransientFailure - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) + ac.cc.resolveNow(resolver.ResolveNowOption{}) ac.curAddr = resolver.Address{} ac.mu.Unlock() if err := ac.resetTransport(); err != nil { @@ -1096,7 +1493,7 @@ func (ac *addrConn) getReadyTransport() (transport.ClientTransport, bool) { ac.mu.Unlock() // Trigger idle ac to connect. if idle { - ac.connect(false) + ac.connect() } return nil, false } @@ -1109,8 +1506,11 @@ func (ac *addrConn) getReadyTransport() (transport.ClientTransport, bool) { func (ac *addrConn) tearDown(err error) { ac.cancel() ac.mu.Lock() - ac.curAddr = resolver.Address{} defer ac.mu.Unlock() + if ac.state == connectivity.Shutdown { + return + } + ac.curAddr = resolver.Address{} if err == errConnDrain && ac.transport != nil { // GracefulClose(...) may be executed multiple times when // i) receiving multiple GoAway frames from the server; or @@ -1118,16 +1518,9 @@ func (ac *addrConn) tearDown(err error) { // address removal and GoAway. ac.transport.GracefulClose() } - if ac.state == connectivity.Shutdown { - return - } ac.state = connectivity.Shutdown ac.tearDownErr = err - if ac.cc.balancerWrapper != nil { - ac.cc.balancerWrapper.handleSubConnStateChange(ac.acbw, ac.state) - } else { - ac.cc.csMgr.updateState(ac.state) - } + ac.cc.handleSubConnStateChange(ac.acbw, ac.state) if ac.events != nil { ac.events.Finish() ac.events = nil @@ -1136,7 +1529,9 @@ func (ac *addrConn) tearDown(err error) { close(ac.ready) ac.ready = nil } - return + if channelz.IsOn() { + channelz.RemoveEntry(ac.channelzID) + } } func (ac *addrConn) getState() connectivity.State { @@ -1144,3 +1539,53 @@ func (ac *addrConn) getState() connectivity.State { defer ac.mu.Unlock() return ac.state } + +func (ac *addrConn) getCurAddr() (ret resolver.Address) { + ac.mu.Lock() + ret = ac.curAddr + ac.mu.Unlock() + return +} + +func (ac *addrConn) ChannelzMetric() *channelz.ChannelInternalMetric { + ac.mu.Lock() + addr := ac.curAddr.Addr + ac.mu.Unlock() + state := ac.getState() + ac.czmu.RLock() + defer ac.czmu.RUnlock() + return &channelz.ChannelInternalMetric{ + State: state, + Target: addr, + CallsStarted: ac.callsStarted, + CallsSucceeded: ac.callsSucceeded, + CallsFailed: ac.callsFailed, + LastCallStartedTimestamp: ac.lastCallStartedTime, + } +} + +func (ac *addrConn) incrCallsStarted() { + ac.czmu.Lock() + ac.callsStarted++ + ac.lastCallStartedTime = time.Now() + ac.czmu.Unlock() +} + +func (ac *addrConn) incrCallsSucceeded() { + ac.czmu.Lock() + ac.callsSucceeded++ + ac.czmu.Unlock() +} + +func (ac *addrConn) incrCallsFailed() { + ac.czmu.Lock() + ac.callsFailed++ + ac.czmu.Unlock() +} + +// ErrClientConnTimeout indicates that the ClientConn cannot establish the +// underlying connections within the specified timeout. +// +// Deprecated: This error is never returned by grpc and should not be +// referenced by users. +var ErrClientConnTimeout = errors.New("grpc: timed out when dialing") diff --git a/vendor/google.golang.org/grpc/clientconn_test.go b/vendor/google.golang.org/grpc/clientconn_test.go deleted file mode 100644 index 47801e9625..0000000000 --- a/vendor/google.golang.org/grpc/clientconn_test.go +++ /dev/null @@ -1,390 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "math" - "net" - "testing" - "time" - - "golang.org/x/net/context" - - "google.golang.org/grpc/connectivity" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/naming" - "google.golang.org/grpc/test/leakcheck" - "google.golang.org/grpc/testdata" -) - -func assertState(wantState connectivity.State, cc *ClientConn) (connectivity.State, bool) { - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - var state connectivity.State - for state = cc.GetState(); state != wantState && cc.WaitForStateChange(ctx, state); state = cc.GetState() { - } - return state, state == wantState -} - -func TestConnectivityStates(t *testing.T) { - defer leakcheck.Check(t) - servers, resolver, cleanup := startServers(t, 2, math.MaxUint32) - defer cleanup() - cc, err := Dial("foo.bar.com", WithBalancer(RoundRobin(resolver)), WithInsecure()) - if err != nil { - t.Fatalf("Dial(\"foo.bar.com\", WithBalancer(_)) = _, %v, want _ <nil>", err) - } - defer cc.Close() - wantState := connectivity.Ready - if state, ok := assertState(wantState, cc); !ok { - t.Fatalf("asserState(%s) = %s, false, want %s, true", wantState, state, wantState) - } - // Send an update to delete the server connection (tearDown addrConn). - update := []*naming.Update{ - { - Op: naming.Delete, - Addr: "localhost:" + servers[0].port, - }, - } - resolver.w.inject(update) - wantState = connectivity.TransientFailure - if state, ok := assertState(wantState, cc); !ok { - t.Fatalf("asserState(%s) = %s, false, want %s, true", wantState, state, wantState) - } - update[0] = &naming.Update{ - Op: naming.Add, - Addr: "localhost:" + servers[1].port, - } - resolver.w.inject(update) - wantState = connectivity.Ready - if state, ok := assertState(wantState, cc); !ok { - t.Fatalf("asserState(%s) = %s, false, want %s, true", wantState, state, wantState) - } - -} - -func TestDialTimeout(t *testing.T) { - defer leakcheck.Check(t) - conn, err := Dial("Non-Existent.Server:80", WithTimeout(time.Millisecond), WithBlock(), WithInsecure()) - if err == nil { - conn.Close() - } - if err != context.DeadlineExceeded { - t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) - } -} - -func TestTLSDialTimeout(t *testing.T) { - defer leakcheck.Check(t) - creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com") - if err != nil { - t.Fatalf("Failed to create credentials %v", err) - } - conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds), WithTimeout(time.Millisecond), WithBlock()) - if err == nil { - conn.Close() - } - if err != context.DeadlineExceeded { - t.Fatalf("Dial(_, _) = %v, %v, want %v", conn, err, context.DeadlineExceeded) - } -} - -func TestDefaultAuthority(t *testing.T) { - defer leakcheck.Check(t) - target := "Non-Existent.Server:8080" - conn, err := Dial(target, WithInsecure()) - if err != nil { - t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) - } - conn.Close() - if conn.authority != target { - t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, target) - } -} - -func TestTLSServerNameOverwrite(t *testing.T) { - defer leakcheck.Check(t) - overwriteServerName := "over.write.server.name" - creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), overwriteServerName) - if err != nil { - t.Fatalf("Failed to create credentials %v", err) - } - conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds)) - if err != nil { - t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) - } - conn.Close() - if conn.authority != overwriteServerName { - t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) - } -} - -func TestWithAuthority(t *testing.T) { - defer leakcheck.Check(t) - overwriteServerName := "over.write.server.name" - conn, err := Dial("Non-Existent.Server:80", WithInsecure(), WithAuthority(overwriteServerName)) - if err != nil { - t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) - } - conn.Close() - if conn.authority != overwriteServerName { - t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) - } -} - -func TestWithAuthorityAndTLS(t *testing.T) { - defer leakcheck.Check(t) - overwriteServerName := "over.write.server.name" - creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), overwriteServerName) - if err != nil { - t.Fatalf("Failed to create credentials %v", err) - } - conn, err := Dial("Non-Existent.Server:80", WithTransportCredentials(creds), WithAuthority("no.effect.authority")) - if err != nil { - t.Fatalf("Dial(_, _) = _, %v, want _, <nil>", err) - } - conn.Close() - if conn.authority != overwriteServerName { - t.Fatalf("%v.authority = %v, want %v", conn, conn.authority, overwriteServerName) - } -} - -func TestDialContextCancel(t *testing.T) { - defer leakcheck.Check(t) - ctx, cancel := context.WithCancel(context.Background()) - cancel() - if _, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure()); err != context.Canceled { - t.Fatalf("DialContext(%v, _) = _, %v, want _, %v", ctx, err, context.Canceled) - } -} - -// blockingBalancer mimics the behavior of balancers whose initialization takes a long time. -// In this test, reading from blockingBalancer.Notify() blocks forever. -type blockingBalancer struct { - ch chan []Address -} - -func newBlockingBalancer() Balancer { - return &blockingBalancer{ch: make(chan []Address)} -} -func (b *blockingBalancer) Start(target string, config BalancerConfig) error { - return nil -} -func (b *blockingBalancer) Up(addr Address) func(error) { - return nil -} -func (b *blockingBalancer) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) { - return Address{}, nil, nil -} -func (b *blockingBalancer) Notify() <-chan []Address { - return b.ch -} -func (b *blockingBalancer) Close() error { - close(b.ch) - return nil -} - -func TestDialWithBlockingBalancer(t *testing.T) { - defer leakcheck.Check(t) - ctx, cancel := context.WithCancel(context.Background()) - dialDone := make(chan struct{}) - go func() { - DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure(), WithBalancer(newBlockingBalancer())) - close(dialDone) - }() - cancel() - <-dialDone -} - -// securePerRPCCredentials always requires transport security. -type securePerRPCCredentials struct{} - -func (c securePerRPCCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - return nil, nil -} - -func (c securePerRPCCredentials) RequireTransportSecurity() bool { - return true -} - -func TestCredentialsMisuse(t *testing.T) { - defer leakcheck.Check(t) - tlsCreds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com") - if err != nil { - t.Fatalf("Failed to create authenticator %v", err) - } - // Two conflicting credential configurations - if _, err := Dial("Non-Existent.Server:80", WithTransportCredentials(tlsCreds), WithBlock(), WithInsecure()); err != errCredentialsConflict { - t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errCredentialsConflict) - } - // security info on insecure connection - if _, err := Dial("Non-Existent.Server:80", WithPerRPCCredentials(securePerRPCCredentials{}), WithBlock(), WithInsecure()); err != errTransportCredentialsMissing { - t.Fatalf("Dial(_, _) = _, %v, want _, %v", err, errTransportCredentialsMissing) - } -} - -func TestWithBackoffConfigDefault(t *testing.T) { - defer leakcheck.Check(t) - testBackoffConfigSet(t, &DefaultBackoffConfig) -} - -func TestWithBackoffConfig(t *testing.T) { - defer leakcheck.Check(t) - b := BackoffConfig{MaxDelay: DefaultBackoffConfig.MaxDelay / 2} - expected := b - setDefaults(&expected) // defaults should be set - testBackoffConfigSet(t, &expected, WithBackoffConfig(b)) -} - -func TestWithBackoffMaxDelay(t *testing.T) { - defer leakcheck.Check(t) - md := DefaultBackoffConfig.MaxDelay / 2 - expected := BackoffConfig{MaxDelay: md} - setDefaults(&expected) - testBackoffConfigSet(t, &expected, WithBackoffMaxDelay(md)) -} - -func testBackoffConfigSet(t *testing.T, expected *BackoffConfig, opts ...DialOption) { - opts = append(opts, WithInsecure()) - conn, err := Dial("foo:80", opts...) - if err != nil { - t.Fatalf("unexpected error dialing connection: %v", err) - } - - if conn.dopts.bs == nil { - t.Fatalf("backoff config not set") - } - - actual, ok := conn.dopts.bs.(BackoffConfig) - if !ok { - t.Fatalf("unexpected type of backoff config: %#v", conn.dopts.bs) - } - - if actual != *expected { - t.Fatalf("unexpected backoff config on connection: %v, want %v", actual, expected) - } - conn.Close() -} - -type testErr struct { - temp bool -} - -func (e *testErr) Error() string { - return "test error" -} - -func (e *testErr) Temporary() bool { - return e.temp -} - -var nonTemporaryError = &testErr{false} - -func nonTemporaryErrorDialer(addr string, timeout time.Duration) (net.Conn, error) { - return nil, nonTemporaryError -} - -func TestDialWithBlockErrorOnNonTemporaryErrorDialer(t *testing.T) { - defer leakcheck.Check(t) - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) - defer cancel() - if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(nonTemporaryErrorDialer), WithBlock(), FailOnNonTempDialError(true)); err != nonTemporaryError { - t.Fatalf("Dial(%q) = %v, want %v", "", err, nonTemporaryError) - } - - // Without FailOnNonTempDialError, gRPC will retry to connect, and dial should exit with time out error. - if _, err := DialContext(ctx, "", WithInsecure(), WithDialer(nonTemporaryErrorDialer), WithBlock()); err != context.DeadlineExceeded { - t.Fatalf("Dial(%q) = %v, want %v", "", err, context.DeadlineExceeded) - } -} - -// emptyBalancer returns an empty set of servers. -type emptyBalancer struct { - ch chan []Address -} - -func newEmptyBalancer() Balancer { - return &emptyBalancer{ch: make(chan []Address, 1)} -} -func (b *emptyBalancer) Start(_ string, _ BalancerConfig) error { - b.ch <- nil - return nil -} -func (b *emptyBalancer) Up(_ Address) func(error) { - return nil -} -func (b *emptyBalancer) Get(_ context.Context, _ BalancerGetOptions) (Address, func(), error) { - return Address{}, nil, nil -} -func (b *emptyBalancer) Notify() <-chan []Address { - return b.ch -} -func (b *emptyBalancer) Close() error { - close(b.ch) - return nil -} - -func TestNonblockingDialWithEmptyBalancer(t *testing.T) { - defer leakcheck.Check(t) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - dialDone := make(chan error) - go func() { - dialDone <- func() error { - conn, err := DialContext(ctx, "Non-Existent.Server:80", WithInsecure(), WithBalancer(newEmptyBalancer())) - if err != nil { - return err - } - return conn.Close() - }() - }() - if err := <-dialDone; err != nil { - t.Fatalf("unexpected error dialing connection: %s", err) - } -} - -func TestClientUpdatesParamsAfterGoAway(t *testing.T) { - defer leakcheck.Check(t) - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen. Err: %v", err) - } - defer lis.Close() - addr := lis.Addr().String() - s := NewServer() - go s.Serve(lis) - defer s.Stop() - cc, err := Dial(addr, WithBlock(), WithInsecure(), WithKeepaliveParams(keepalive.ClientParameters{ - Time: 50 * time.Millisecond, - Timeout: 1 * time.Millisecond, - PermitWithoutStream: true, - })) - if err != nil { - t.Fatalf("Dial(%s, _) = _, %v, want _, <nil>", addr, err) - } - defer cc.Close() - time.Sleep(1 * time.Second) - cc.mu.RLock() - defer cc.mu.RUnlock() - v := cc.mkp.Time - if v < 100*time.Millisecond { - t.Fatalf("cc.dopts.copts.Keepalive.Time = %v , want 100ms", v) - } -} diff --git a/vendor/google.golang.org/grpc/codec.go b/vendor/google.golang.org/grpc/codec.go index 905b048e2a..1297765478 100644 --- a/vendor/google.golang.org/grpc/codec.go +++ b/vendor/google.golang.org/grpc/codec.go @@ -19,86 +19,32 @@ package grpc import ( - "math" - "sync" - - "github.com/golang/protobuf/proto" + "google.golang.org/grpc/encoding" + _ "google.golang.org/grpc/encoding/proto" // to register the Codec for "proto" ) +// baseCodec contains the functionality of both Codec and encoding.Codec, but +// omits the name/string, which vary between the two and are not needed for +// anything besides the registry in the encoding package. +type baseCodec interface { + Marshal(v interface{}) ([]byte, error) + Unmarshal(data []byte, v interface{}) error +} + +var _ baseCodec = Codec(nil) +var _ baseCodec = encoding.Codec(nil) + // Codec defines the interface gRPC uses to encode and decode messages. // Note that implementations of this interface must be thread safe; // a Codec's methods can be called from concurrent goroutines. +// +// Deprecated: use encoding.Codec instead. type Codec interface { // Marshal returns the wire format of v. Marshal(v interface{}) ([]byte, error) // Unmarshal parses the wire format into v. Unmarshal(data []byte, v interface{}) error - // String returns the name of the Codec implementation. The returned - // string will be used as part of content type in transmission. + // String returns the name of the Codec implementation. This is unused by + // gRPC. String() string } - -// protoCodec is a Codec implementation with protobuf. It is the default codec for gRPC. -type protoCodec struct { -} - -type cachedProtoBuffer struct { - lastMarshaledSize uint32 - proto.Buffer -} - -func capToMaxInt32(val int) uint32 { - if val > math.MaxInt32 { - return uint32(math.MaxInt32) - } - return uint32(val) -} - -func (p protoCodec) marshal(v interface{}, cb *cachedProtoBuffer) ([]byte, error) { - protoMsg := v.(proto.Message) - newSlice := make([]byte, 0, cb.lastMarshaledSize) - - cb.SetBuf(newSlice) - cb.Reset() - if err := cb.Marshal(protoMsg); err != nil { - return nil, err - } - out := cb.Bytes() - cb.lastMarshaledSize = capToMaxInt32(len(out)) - return out, nil -} - -func (p protoCodec) Marshal(v interface{}) ([]byte, error) { - cb := protoBufferPool.Get().(*cachedProtoBuffer) - out, err := p.marshal(v, cb) - - // put back buffer and lose the ref to the slice - cb.SetBuf(nil) - protoBufferPool.Put(cb) - return out, err -} - -func (p protoCodec) Unmarshal(data []byte, v interface{}) error { - cb := protoBufferPool.Get().(*cachedProtoBuffer) - cb.SetBuf(data) - v.(proto.Message).Reset() - err := cb.Unmarshal(v.(proto.Message)) - cb.SetBuf(nil) - protoBufferPool.Put(cb) - return err -} - -func (protoCodec) String() string { - return "proto" -} - -var ( - protoBufferPool = &sync.Pool{ - New: func() interface{} { - return &cachedProtoBuffer{ - Buffer: proto.Buffer{}, - lastMarshaledSize: 16, - } - }, - } -) diff --git a/vendor/google.golang.org/grpc/codec_benchmark_test.go b/vendor/google.golang.org/grpc/codec_benchmark_test.go deleted file mode 100644 index dee617ca25..0000000000 --- a/vendor/google.golang.org/grpc/codec_benchmark_test.go +++ /dev/null @@ -1,100 +0,0 @@ -// +build go1.7 - -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "fmt" - "testing" - - "github.com/golang/protobuf/proto" - "google.golang.org/grpc/test/codec_perf" -) - -func setupBenchmarkProtoCodecInputs(b *testing.B, payloadBaseSize uint32) []proto.Message { - payloadBase := make([]byte, payloadBaseSize) - // arbitrary byte slices - payloadSuffixes := [][]byte{ - []byte("one"), - []byte("two"), - []byte("three"), - []byte("four"), - []byte("five"), - } - protoStructs := make([]proto.Message, 0) - - for _, p := range payloadSuffixes { - ps := &codec_perf.Buffer{} - ps.Body = append(payloadBase, p...) - protoStructs = append(protoStructs, ps) - } - - return protoStructs -} - -// The possible use of certain protobuf APIs like the proto.Buffer API potentially involves caching -// on our side. This can add checks around memory allocations and possible contention. -// Example run: go test -v -run=^$ -bench=BenchmarkProtoCodec -benchmem -func BenchmarkProtoCodec(b *testing.B) { - // range of message sizes - payloadBaseSizes := make([]uint32, 0) - for i := uint32(0); i <= 12; i += 4 { - payloadBaseSizes = append(payloadBaseSizes, 1<<i) - } - // range of SetParallelism - parallelisms := make([]uint32, 0) - for i := uint32(0); i <= 16; i += 4 { - parallelisms = append(parallelisms, 1<<i) - } - for _, s := range payloadBaseSizes { - for _, p := range parallelisms { - func(parallelism int, payloadBaseSize uint32) { - protoStructs := setupBenchmarkProtoCodecInputs(b, payloadBaseSize) - name := fmt.Sprintf("MinPayloadSize:%v/SetParallelism(%v)", payloadBaseSize, parallelism) - b.Run(name, func(b *testing.B) { - codec := &protoCodec{} - b.SetParallelism(parallelism) - b.RunParallel(func(pb *testing.PB) { - benchmarkProtoCodec(codec, protoStructs, pb, b) - }) - }) - }(int(p), s) - } - } -} - -func benchmarkProtoCodec(codec *protoCodec, protoStructs []proto.Message, pb *testing.PB, b *testing.B) { - counter := 0 - for pb.Next() { - counter++ - ps := protoStructs[counter%len(protoStructs)] - fastMarshalAndUnmarshal(codec, ps, b) - } -} - -func fastMarshalAndUnmarshal(protoCodec Codec, protoStruct proto.Message, b *testing.B) { - marshaledBytes, err := protoCodec.Marshal(protoStruct) - if err != nil { - b.Errorf("protoCodec.Marshal(_) returned an error") - } - if err := protoCodec.Unmarshal(marshaledBytes, protoStruct); err != nil { - b.Errorf("protoCodec.Unmarshal(_) returned an error") - } -} diff --git a/vendor/google.golang.org/grpc/codec_test.go b/vendor/google.golang.org/grpc/codec_test.go deleted file mode 100644 index 246b13b08c..0000000000 --- a/vendor/google.golang.org/grpc/codec_test.go +++ /dev/null @@ -1,128 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "bytes" - "sync" - "testing" - - "google.golang.org/grpc/test/codec_perf" -) - -func marshalAndUnmarshal(t *testing.T, protoCodec Codec, expectedBody []byte) { - p := &codec_perf.Buffer{} - p.Body = expectedBody - - marshalledBytes, err := protoCodec.Marshal(p) - if err != nil { - t.Errorf("protoCodec.Marshal(_) returned an error") - } - - if err := protoCodec.Unmarshal(marshalledBytes, p); err != nil { - t.Errorf("protoCodec.Unmarshal(_) returned an error") - } - - if bytes.Compare(p.GetBody(), expectedBody) != 0 { - t.Errorf("Unexpected body; got %v; want %v", p.GetBody(), expectedBody) - } -} - -func TestBasicProtoCodecMarshalAndUnmarshal(t *testing.T) { - marshalAndUnmarshal(t, protoCodec{}, []byte{1, 2, 3}) -} - -// Try to catch possible race conditions around use of pools -func TestConcurrentUsage(t *testing.T) { - const ( - numGoRoutines = 100 - numMarshUnmarsh = 1000 - ) - - // small, arbitrary byte slices - protoBodies := [][]byte{ - []byte("one"), - []byte("two"), - []byte("three"), - []byte("four"), - []byte("five"), - } - - var wg sync.WaitGroup - codec := protoCodec{} - - for i := 0; i < numGoRoutines; i++ { - wg.Add(1) - go func() { - defer wg.Done() - for k := 0; k < numMarshUnmarsh; k++ { - marshalAndUnmarshal(t, codec, protoBodies[k%len(protoBodies)]) - } - }() - } - - wg.Wait() -} - -// TestStaggeredMarshalAndUnmarshalUsingSamePool tries to catch potential errors in which slices get -// stomped on during reuse of a proto.Buffer. -func TestStaggeredMarshalAndUnmarshalUsingSamePool(t *testing.T) { - codec1 := protoCodec{} - codec2 := protoCodec{} - - expectedBody1 := []byte{1, 2, 3} - expectedBody2 := []byte{4, 5, 6} - - proto1 := codec_perf.Buffer{Body: expectedBody1} - proto2 := codec_perf.Buffer{Body: expectedBody2} - - var m1, m2 []byte - var err error - - if m1, err = codec1.Marshal(&proto1); err != nil { - t.Errorf("protoCodec.Marshal(%v) failed", proto1) - } - - if m2, err = codec2.Marshal(&proto2); err != nil { - t.Errorf("protoCodec.Marshal(%v) failed", proto2) - } - - if err = codec1.Unmarshal(m1, &proto1); err != nil { - t.Errorf("protoCodec.Unmarshal(%v) failed", m1) - } - - if err = codec2.Unmarshal(m2, &proto2); err != nil { - t.Errorf("protoCodec.Unmarshal(%v) failed", m2) - } - - b1 := proto1.GetBody() - b2 := proto2.GetBody() - - for i, v := range b1 { - if expectedBody1[i] != v { - t.Errorf("expected %v at index %v but got %v", i, expectedBody1[i], v) - } - } - - for i, v := range b2 { - if expectedBody2[i] != v { - t.Errorf("expected %v at index %v but got %v", i, expectedBody2[i], v) - } - } -} diff --git a/vendor/google.golang.org/grpc/codes/code_string.go b/vendor/google.golang.org/grpc/codes/code_string.go index 259837060a..0b206a5782 100644 --- a/vendor/google.golang.org/grpc/codes/code_string.go +++ b/vendor/google.golang.org/grpc/codes/code_string.go @@ -1,16 +1,62 @@ -// Code generated by "stringer -type=Code"; DO NOT EDIT. +/* + * + * Copyright 2017 gRPC 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 codes -import "fmt" +import "strconv" -const _Code_name = "OKCanceledUnknownInvalidArgumentDeadlineExceededNotFoundAlreadyExistsPermissionDeniedResourceExhaustedFailedPreconditionAbortedOutOfRangeUnimplementedInternalUnavailableDataLossUnauthenticated" - -var _Code_index = [...]uint8{0, 2, 10, 17, 32, 48, 56, 69, 85, 102, 120, 127, 137, 150, 158, 169, 177, 192} - -func (i Code) String() string { - if i >= Code(len(_Code_index)-1) { - return fmt.Sprintf("Code(%d)", i) +func (c Code) String() string { + switch c { + case OK: + return "OK" + case Canceled: + return "Canceled" + case Unknown: + return "Unknown" + case InvalidArgument: + return "InvalidArgument" + case DeadlineExceeded: + return "DeadlineExceeded" + case NotFound: + return "NotFound" + case AlreadyExists: + return "AlreadyExists" + case PermissionDenied: + return "PermissionDenied" + case ResourceExhausted: + return "ResourceExhausted" + case FailedPrecondition: + return "FailedPrecondition" + case Aborted: + return "Aborted" + case OutOfRange: + return "OutOfRange" + case Unimplemented: + return "Unimplemented" + case Internal: + return "Internal" + case Unavailable: + return "Unavailable" + case DataLoss: + return "DataLoss" + case Unauthenticated: + return "Unauthenticated" + default: + return "Code(" + strconv.FormatInt(int64(c), 10) + ")" } - return _Code_name[_Code_index[i]:_Code_index[i+1]] } diff --git a/vendor/google.golang.org/grpc/codes/codes.go b/vendor/google.golang.org/grpc/codes/codes.go index 21e7733a5f..a8280ae660 100644 --- a/vendor/google.golang.org/grpc/codes/codes.go +++ b/vendor/google.golang.org/grpc/codes/codes.go @@ -20,11 +20,13 @@ // consistent across various languages. package codes // import "google.golang.org/grpc/codes" +import ( + "fmt" +) + // A Code is an unsigned 32-bit error code as defined in the gRPC spec. type Code uint32 -//go:generate stringer -type=Code - const ( // OK is returned on success. OK Code = 0 @@ -32,9 +34,9 @@ const ( // Canceled indicates the operation was canceled (typically by the caller). Canceled Code = 1 - // Unknown error. An example of where this error may be returned is + // Unknown error. An example of where this error may be returned is // if a Status value received from another address space belongs to - // an error-space that is not known in this address space. Also + // an error-space that is not known in this address space. Also // errors raised by APIs that do not return enough error information // may be converted to this error. Unknown Code = 2 @@ -63,15 +65,11 @@ const ( // PermissionDenied indicates the caller does not have permission to // execute the specified operation. It must not be used for rejections // caused by exhausting some resource (use ResourceExhausted - // instead for those errors). It must not be + // instead for those errors). It must not be // used if the caller cannot be identified (use Unauthenticated // instead for those errors). PermissionDenied Code = 7 - // Unauthenticated indicates the request does not have valid - // authentication credentials for the operation. - Unauthenticated Code = 16 - // ResourceExhausted indicates some resource has been exhausted, perhaps // a per-user quota, or perhaps the entire file system is out of space. ResourceExhausted Code = 8 @@ -87,7 +85,7 @@ const ( // (b) Use Aborted if the client should retry at a higher-level // (e.g., restarting a read-modify-write sequence). // (c) Use FailedPrecondition if the client should not retry until - // the system state has been explicitly fixed. E.g., if an "rmdir" + // the system state has been explicitly fixed. E.g., if an "rmdir" // fails because the directory is non-empty, FailedPrecondition // should be returned since the client should not retry unless // they have first fixed up the directory by deleting files from it. @@ -116,7 +114,7 @@ const ( // file size. // // There is a fair bit of overlap between FailedPrecondition and - // OutOfRange. We recommend using OutOfRange (the more specific + // OutOfRange. We recommend using OutOfRange (the more specific // error) when it applies so that callers who are iterating through // a space can easily look for an OutOfRange error to detect when // they are done. @@ -126,8 +124,8 @@ const ( // supported/enabled in this service. Unimplemented Code = 12 - // Internal errors. Means some invariants expected by underlying - // system has been broken. If you see one of these errors, + // Internal errors. Means some invariants expected by underlying + // system has been broken. If you see one of these errors, // something is very broken. Internal Code = 13 @@ -141,4 +139,46 @@ const ( // DataLoss indicates unrecoverable data loss or corruption. DataLoss Code = 15 + + // Unauthenticated indicates the request does not have valid + // authentication credentials for the operation. + Unauthenticated Code = 16 ) + +var strToCode = map[string]Code{ + `"OK"`: OK, + `"CANCELLED"`:/* [sic] */ Canceled, + `"UNKNOWN"`: Unknown, + `"INVALID_ARGUMENT"`: InvalidArgument, + `"DEADLINE_EXCEEDED"`: DeadlineExceeded, + `"NOT_FOUND"`: NotFound, + `"ALREADY_EXISTS"`: AlreadyExists, + `"PERMISSION_DENIED"`: PermissionDenied, + `"RESOURCE_EXHAUSTED"`: ResourceExhausted, + `"FAILED_PRECONDITION"`: FailedPrecondition, + `"ABORTED"`: Aborted, + `"OUT_OF_RANGE"`: OutOfRange, + `"UNIMPLEMENTED"`: Unimplemented, + `"INTERNAL"`: Internal, + `"UNAVAILABLE"`: Unavailable, + `"DATA_LOSS"`: DataLoss, + `"UNAUTHENTICATED"`: Unauthenticated, +} + +// UnmarshalJSON unmarshals b into the Code. +func (c *Code) UnmarshalJSON(b []byte) error { + // From json.Unmarshaler: By convention, to approximate the behavior of + // Unmarshal itself, Unmarshalers implement UnmarshalJSON([]byte("null")) as + // a no-op. + if string(b) == "null" { + return nil + } + if c == nil { + return fmt.Errorf("nil receiver passed to UnmarshalJSON") + } + if jc, ok := strToCode[string(b)]; ok { + *c = jc + return nil + } + return fmt.Errorf("invalid code: %q", string(b)) +} diff --git a/vendor/google.golang.org/grpc/credentials/credentials.go b/vendor/google.golang.org/grpc/credentials/credentials.go index 2475fe8322..3351bf0ee5 100644 --- a/vendor/google.golang.org/grpc/credentials/credentials.go +++ b/vendor/google.golang.org/grpc/credentials/credentials.go @@ -34,10 +34,8 @@ import ( "golang.org/x/net/context" ) -var ( - // alpnProtoStr are the specified application level protocols for gRPC. - alpnProtoStr = []string{"h2"} -) +// alpnProtoStr are the specified application level protocols for gRPC. +var alpnProtoStr = []string{"h2"} // PerRPCCredentials defines the common interface for the credentials which need to // attach security information to every RPC (e.g., oauth2). @@ -45,8 +43,9 @@ type PerRPCCredentials interface { // GetRequestMetadata gets the current request metadata, refreshing // tokens if required. This should be called by the transport layer on // each request, and the data should be populated in headers or other - // context. uri is the URI of the entry point for the request. When - // supported by the underlying implementation, ctx can be used for + // context. If a status code is returned, it will be used as the status + // for the RPC. uri is the URI of the entry point for the request. + // When supported by the underlying implementation, ctx can be used for // timeout and cancellation. // TODO(zhaoq): Define the set of the qualified keys instead of leaving // it as an arbitrary string. @@ -74,11 +73,9 @@ type AuthInfo interface { AuthType() string } -var ( - // ErrConnDispatched indicates that rawConn has been dispatched out of gRPC - // and the caller should not close rawConn. - ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC") -) +// ErrConnDispatched indicates that rawConn has been dispatched out of gRPC +// and the caller should not close rawConn. +var ErrConnDispatched = errors.New("credentials: rawConn is dispatched out of gRPC") // TransportCredentials defines the common interface for all the live gRPC wire // protocols and supported transport security protocols (e.g., TLS, SSL). @@ -91,10 +88,14 @@ type TransportCredentials interface { // (io.EOF, context.DeadlineExceeded or err.Temporary() == true). // If the returned error is a wrapper error, implementations should make sure that // the error implements Temporary() to have the correct retry behaviors. + // + // If the returned net.Conn is closed, it MUST close the net.Conn provided. ClientHandshake(context.Context, string, net.Conn) (net.Conn, AuthInfo, error) // ServerHandshake does the authentication handshake for servers. It returns // the authenticated connection and the corresponding auth information about // the connection. + // + // If the returned net.Conn is closed, it MUST close the net.Conn provided. ServerHandshake(net.Conn) (net.Conn, AuthInfo, error) // Info provides the ProtocolInfo of this TransportCredentials. Info() ProtocolInfo @@ -131,15 +132,15 @@ func (c tlsCreds) Info() ProtocolInfo { } } -func (c *tlsCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) { +func (c *tlsCreds) ClientHandshake(ctx context.Context, authority string, rawConn net.Conn) (_ net.Conn, _ AuthInfo, err error) { // use local cfg to avoid clobbering ServerName if using multiple endpoints cfg := cloneTLSConfig(c.config) if cfg.ServerName == "" { - colonPos := strings.LastIndex(addr, ":") + colonPos := strings.LastIndex(authority, ":") if colonPos == -1 { - colonPos = len(addr) + colonPos = len(authority) } - cfg.ServerName = addr[:colonPos] + cfg.ServerName = authority[:colonPos] } conn := tls.Client(rawConn, cfg) errChannel := make(chan error, 1) diff --git a/vendor/google.golang.org/grpc/credentials/credentials_test.go b/vendor/google.golang.org/grpc/credentials/credentials_test.go deleted file mode 100644 index 9b13db51d4..0000000000 --- a/vendor/google.golang.org/grpc/credentials/credentials_test.go +++ /dev/null @@ -1,206 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 credentials - -import ( - "crypto/tls" - "net" - "testing" - - "golang.org/x/net/context" - "google.golang.org/grpc/testdata" -) - -func TestTLSOverrideServerName(t *testing.T) { - expectedServerName := "server.name" - c := NewTLS(nil) - c.OverrideServerName(expectedServerName) - if c.Info().ServerName != expectedServerName { - t.Fatalf("c.Info().ServerName = %v, want %v", c.Info().ServerName, expectedServerName) - } -} - -func TestTLSClone(t *testing.T) { - expectedServerName := "server.name" - c := NewTLS(nil) - c.OverrideServerName(expectedServerName) - cc := c.Clone() - if cc.Info().ServerName != expectedServerName { - t.Fatalf("cc.Info().ServerName = %v, want %v", cc.Info().ServerName, expectedServerName) - } - cc.OverrideServerName("") - if c.Info().ServerName != expectedServerName { - t.Fatalf("Change in clone should not affect the original, c.Info().ServerName = %v, want %v", c.Info().ServerName, expectedServerName) - } - -} - -type serverHandshake func(net.Conn) (AuthInfo, error) - -func TestClientHandshakeReturnsAuthInfo(t *testing.T) { - done := make(chan AuthInfo, 1) - lis := launchServer(t, tlsServerHandshake, done) - defer lis.Close() - lisAddr := lis.Addr().String() - clientAuthInfo := clientHandle(t, gRPCClientHandshake, lisAddr) - // wait until server sends serverAuthInfo or fails. - serverAuthInfo, ok := <-done - if !ok { - t.Fatalf("Error at server-side") - } - if !compare(clientAuthInfo, serverAuthInfo) { - t.Fatalf("c.ClientHandshake(_, %v, _) = %v, want %v.", lisAddr, clientAuthInfo, serverAuthInfo) - } -} - -func TestServerHandshakeReturnsAuthInfo(t *testing.T) { - done := make(chan AuthInfo, 1) - lis := launchServer(t, gRPCServerHandshake, done) - defer lis.Close() - clientAuthInfo := clientHandle(t, tlsClientHandshake, lis.Addr().String()) - // wait until server sends serverAuthInfo or fails. - serverAuthInfo, ok := <-done - if !ok { - t.Fatalf("Error at server-side") - } - if !compare(clientAuthInfo, serverAuthInfo) { - t.Fatalf("ServerHandshake(_) = %v, want %v.", serverAuthInfo, clientAuthInfo) - } -} - -func TestServerAndClientHandshake(t *testing.T) { - done := make(chan AuthInfo, 1) - lis := launchServer(t, gRPCServerHandshake, done) - defer lis.Close() - clientAuthInfo := clientHandle(t, gRPCClientHandshake, lis.Addr().String()) - // wait until server sends serverAuthInfo or fails. - serverAuthInfo, ok := <-done - if !ok { - t.Fatalf("Error at server-side") - } - if !compare(clientAuthInfo, serverAuthInfo) { - t.Fatalf("AuthInfo returned by server: %v and client: %v aren't same", serverAuthInfo, clientAuthInfo) - } -} - -func compare(a1, a2 AuthInfo) bool { - if a1.AuthType() != a2.AuthType() { - return false - } - switch a1.AuthType() { - case "tls": - state1 := a1.(TLSInfo).State - state2 := a2.(TLSInfo).State - if state1.Version == state2.Version && - state1.HandshakeComplete == state2.HandshakeComplete && - state1.CipherSuite == state2.CipherSuite && - state1.NegotiatedProtocol == state2.NegotiatedProtocol { - return true - } - return false - default: - return false - } -} - -func launchServer(t *testing.T, hs serverHandshake, done chan AuthInfo) net.Listener { - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - go serverHandle(t, hs, done, lis) - return lis -} - -// Is run in a separate goroutine. -func serverHandle(t *testing.T, hs serverHandshake, done chan AuthInfo, lis net.Listener) { - serverRawConn, err := lis.Accept() - if err != nil { - t.Errorf("Server failed to accept connection: %v", err) - close(done) - return - } - serverAuthInfo, err := hs(serverRawConn) - if err != nil { - t.Errorf("Server failed while handshake. Error: %v", err) - serverRawConn.Close() - close(done) - return - } - done <- serverAuthInfo -} - -func clientHandle(t *testing.T, hs func(net.Conn, string) (AuthInfo, error), lisAddr string) AuthInfo { - conn, err := net.Dial("tcp", lisAddr) - if err != nil { - t.Fatalf("Client failed to connect to %s. Error: %v", lisAddr, err) - } - defer conn.Close() - clientAuthInfo, err := hs(conn, lisAddr) - if err != nil { - t.Fatalf("Error on client while handshake. Error: %v", err) - } - return clientAuthInfo -} - -// Server handshake implementation in gRPC. -func gRPCServerHandshake(conn net.Conn) (AuthInfo, error) { - serverTLS, err := NewServerTLSFromFile(testdata.Path("server1.pem"), testdata.Path("server1.key")) - if err != nil { - return nil, err - } - _, serverAuthInfo, err := serverTLS.ServerHandshake(conn) - if err != nil { - return nil, err - } - return serverAuthInfo, nil -} - -// Client handshake implementation in gRPC. -func gRPCClientHandshake(conn net.Conn, lisAddr string) (AuthInfo, error) { - clientTLS := NewTLS(&tls.Config{InsecureSkipVerify: true}) - _, authInfo, err := clientTLS.ClientHandshake(context.Background(), lisAddr, conn) - if err != nil { - return nil, err - } - return authInfo, nil -} - -func tlsServerHandshake(conn net.Conn) (AuthInfo, error) { - cert, err := tls.LoadX509KeyPair(testdata.Path("server1.pem"), testdata.Path("server1.key")) - if err != nil { - return nil, err - } - serverTLSConfig := &tls.Config{Certificates: []tls.Certificate{cert}} - serverConn := tls.Server(conn, serverTLSConfig) - err = serverConn.Handshake() - if err != nil { - return nil, err - } - return TLSInfo{State: serverConn.ConnectionState()}, nil -} - -func tlsClientHandshake(conn net.Conn, _ string) (AuthInfo, error) { - clientTLSConfig := &tls.Config{InsecureSkipVerify: true} - clientConn := tls.Client(conn, clientTLSConfig) - if err := clientConn.Handshake(); err != nil { - return nil, err - } - return TLSInfo{State: clientConn.ConnectionState()}, nil -} diff --git a/vendor/google.golang.org/grpc/encoding/encoding.go b/vendor/google.golang.org/grpc/encoding/encoding.go new file mode 100644 index 0000000000..ade8b7cec7 --- /dev/null +++ b/vendor/google.golang.org/grpc/encoding/encoding.go @@ -0,0 +1,118 @@ +/* + * + * Copyright 2017 gRPC 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 encoding defines the interface for the compressor and codec, and +// functions to register and retrieve compressors and codecs. +// +// This package is EXPERIMENTAL. +package encoding + +import ( + "io" + "strings" +) + +// Identity specifies the optional encoding for uncompressed streams. +// It is intended for grpc internal use only. +const Identity = "identity" + +// Compressor is used for compressing and decompressing when sending or +// receiving messages. +type Compressor interface { + // Compress writes the data written to wc to w after compressing it. If an + // error occurs while initializing the compressor, that error is returned + // instead. + Compress(w io.Writer) (io.WriteCloser, error) + // Decompress reads data from r, decompresses it, and provides the + // uncompressed data via the returned io.Reader. If an error occurs while + // initializing the decompressor, that error is returned instead. + Decompress(r io.Reader) (io.Reader, error) + // Name is the name of the compression codec and is used to set the content + // coding header. The result must be static; the result cannot change + // between calls. + Name() string +} + +var registeredCompressor = make(map[string]Compressor) + +// RegisterCompressor registers the compressor with gRPC by its name. It can +// be activated when sending an RPC via grpc.UseCompressor(). It will be +// automatically accessed when receiving a message based on the content coding +// header. Servers also use it to send a response with the same encoding as +// the request. +// +// NOTE: this function must only be called during initialization time (i.e. in +// an init() function), and is not thread-safe. If multiple Compressors are +// registered with the same name, the one registered last will take effect. +func RegisterCompressor(c Compressor) { + registeredCompressor[c.Name()] = c +} + +// GetCompressor returns Compressor for the given compressor name. +func GetCompressor(name string) Compressor { + return registeredCompressor[name] +} + +// Codec defines the interface gRPC uses to encode and decode messages. Note +// that implementations of this interface must be thread safe; a Codec's +// methods can be called from concurrent goroutines. +type Codec interface { + // Marshal returns the wire format of v. + Marshal(v interface{}) ([]byte, error) + // Unmarshal parses the wire format into v. + Unmarshal(data []byte, v interface{}) error + // Name returns the name of the Codec implementation. The returned string + // will be used as part of content type in transmission. The result must be + // static; the result cannot change between calls. + Name() string +} + +var registeredCodecs = make(map[string]Codec) + +// RegisterCodec registers the provided Codec for use with all gRPC clients and +// servers. +// +// The Codec will be stored and looked up by result of its Name() method, which +// should match the content-subtype of the encoding handled by the Codec. This +// is case-insensitive, and is stored and looked up as lowercase. If the +// result of calling Name() is an empty string, RegisterCodec will panic. See +// Content-Type on +// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for +// more details. +// +// NOTE: this function must only be called during initialization time (i.e. in +// an init() function), and is not thread-safe. If multiple Compressors are +// registered with the same name, the one registered last will take effect. +func RegisterCodec(codec Codec) { + if codec == nil { + panic("cannot register a nil Codec") + } + contentSubtype := strings.ToLower(codec.Name()) + if contentSubtype == "" { + panic("cannot register Codec with empty string result for String()") + } + registeredCodecs[contentSubtype] = codec +} + +// GetCodec gets a registered Codec by content-subtype, or nil if no Codec is +// registered for the content-subtype. +// +// The content-subtype is expected to be lowercase. +func GetCodec(contentSubtype string) Codec { + return registeredCodecs[contentSubtype] +} diff --git a/vendor/google.golang.org/grpc/encoding/proto/proto.go b/vendor/google.golang.org/grpc/encoding/proto/proto.go new file mode 100644 index 0000000000..66b97a6f69 --- /dev/null +++ b/vendor/google.golang.org/grpc/encoding/proto/proto.go @@ -0,0 +1,110 @@ +/* + * + * Copyright 2018 gRPC 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 proto defines the protobuf codec. Importing this package will +// register the codec. +package proto + +import ( + "math" + "sync" + + "github.com/golang/protobuf/proto" + "google.golang.org/grpc/encoding" +) + +// Name is the name registered for the proto compressor. +const Name = "proto" + +func init() { + encoding.RegisterCodec(codec{}) +} + +// codec is a Codec implementation with protobuf. It is the default codec for gRPC. +type codec struct{} + +type cachedProtoBuffer struct { + lastMarshaledSize uint32 + proto.Buffer +} + +func capToMaxInt32(val int) uint32 { + if val > math.MaxInt32 { + return uint32(math.MaxInt32) + } + return uint32(val) +} + +func marshal(v interface{}, cb *cachedProtoBuffer) ([]byte, error) { + protoMsg := v.(proto.Message) + newSlice := make([]byte, 0, cb.lastMarshaledSize) + + cb.SetBuf(newSlice) + cb.Reset() + if err := cb.Marshal(protoMsg); err != nil { + return nil, err + } + out := cb.Bytes() + cb.lastMarshaledSize = capToMaxInt32(len(out)) + return out, nil +} + +func (codec) Marshal(v interface{}) ([]byte, error) { + if pm, ok := v.(proto.Marshaler); ok { + // object can marshal itself, no need for buffer + return pm.Marshal() + } + + cb := protoBufferPool.Get().(*cachedProtoBuffer) + out, err := marshal(v, cb) + + // put back buffer and lose the ref to the slice + cb.SetBuf(nil) + protoBufferPool.Put(cb) + return out, err +} + +func (codec) Unmarshal(data []byte, v interface{}) error { + protoMsg := v.(proto.Message) + protoMsg.Reset() + + if pu, ok := protoMsg.(proto.Unmarshaler); ok { + // object can unmarshal itself, no need for buffer + return pu.Unmarshal(data) + } + + cb := protoBufferPool.Get().(*cachedProtoBuffer) + cb.SetBuf(data) + err := cb.Unmarshal(protoMsg) + cb.SetBuf(nil) + protoBufferPool.Put(cb) + return err +} + +func (codec) Name() string { + return Name +} + +var protoBufferPool = &sync.Pool{ + New: func() interface{} { + return &cachedProtoBuffer{ + Buffer: proto.Buffer{}, + lastMarshaledSize: 16, + } + }, +} diff --git a/vendor/google.golang.org/grpc/naming/go18_test.go b/vendor/google.golang.org/grpc/envconfig.go similarity index 54% rename from vendor/google.golang.org/grpc/naming/go18_test.go rename to vendor/google.golang.org/grpc/envconfig.go index 5e297539ba..d50178e517 100644 --- a/vendor/google.golang.org/grpc/naming/go18_test.go +++ b/vendor/google.golang.org/grpc/envconfig.go @@ -1,8 +1,6 @@ -// +build go1.8 - /* * - * Copyright 2017 gRPC authors. + * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,24 +16,22 @@ * */ -package naming +package grpc import ( - "context" - "net" + "os" + "strings" +) + +const ( + envConfigPrefix = "GRPC_GO_" + envConfigStickinessStr = envConfigPrefix + "STICKINESS" +) + +var ( + envConfigStickinessOn bool ) -func replaceNetFunc() func() { - oldLookupHost := lookupHost - oldLookupSRV := lookupSRV - lookupHost = func(ctx context.Context, host string) ([]string, error) { - return hostLookup(host) - } - lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { - return srvLookup(service, proto, name) - } - return func() { - lookupHost = oldLookupHost - lookupSRV = oldLookupSRV - } +func init() { + envConfigStickinessOn = strings.EqualFold(os.Getenv(envConfigStickinessStr), "on") } diff --git a/vendor/google.golang.org/grpc/go16.go b/vendor/google.golang.org/grpc/go16.go new file mode 100644 index 0000000000..535ee9356f --- /dev/null +++ b/vendor/google.golang.org/grpc/go16.go @@ -0,0 +1,70 @@ +// +build go1.6,!go1.7 + +/* + * + * Copyright 2016 gRPC 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 grpc + +import ( + "fmt" + "io" + "net" + "net/http" + + "golang.org/x/net/context" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/grpc/transport" +) + +// dialContext connects to the address on the named network. +func dialContext(ctx context.Context, network, address string) (net.Conn, error) { + return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address) +} + +func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { + req.Cancel = ctx.Done() + if err := req.Write(conn); err != nil { + return fmt.Errorf("failed to write the HTTP request: %v", err) + } + return nil +} + +// toRPCErr converts an error into an error from the status package. +func toRPCErr(err error) error { + if err == nil || err == io.EOF { + return err + } + if _, ok := status.FromError(err); ok { + return err + } + switch e := err.(type) { + case transport.StreamError: + return status.Error(e.Code, e.Desc) + case transport.ConnectionError: + return status.Error(codes.Unavailable, e.Desc) + default: + switch err { + case context.DeadlineExceeded: + return status.Error(codes.DeadlineExceeded, err.Error()) + case context.Canceled: + return status.Error(codes.Canceled, err.Error()) + } + } + return status.Error(codes.Unknown, err.Error()) +} diff --git a/vendor/google.golang.org/grpc/go17.go b/vendor/google.golang.org/grpc/go17.go new file mode 100644 index 0000000000..ec676a93c3 --- /dev/null +++ b/vendor/google.golang.org/grpc/go17.go @@ -0,0 +1,71 @@ +// +build go1.7 + +/* + * + * Copyright 2016 gRPC 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 grpc + +import ( + "context" + "fmt" + "io" + "net" + "net/http" + + netctx "golang.org/x/net/context" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/grpc/transport" +) + +// dialContext connects to the address on the named network. +func dialContext(ctx context.Context, network, address string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, network, address) +} + +func sendHTTPRequest(ctx context.Context, req *http.Request, conn net.Conn) error { + req = req.WithContext(ctx) + if err := req.Write(conn); err != nil { + return fmt.Errorf("failed to write the HTTP request: %v", err) + } + return nil +} + +// toRPCErr converts an error into an error from the status package. +func toRPCErr(err error) error { + if err == nil || err == io.EOF { + return err + } + if _, ok := status.FromError(err); ok { + return err + } + switch e := err.(type) { + case transport.StreamError: + return status.Error(e.Code, e.Desc) + case transport.ConnectionError: + return status.Error(codes.Unavailable, e.Desc) + default: + switch err { + case context.DeadlineExceeded, netctx.DeadlineExceeded: + return status.Error(codes.DeadlineExceeded, err.Error()) + case context.Canceled, netctx.Canceled: + return status.Error(codes.Canceled, err.Error()) + } + } + return status.Error(codes.Unknown, err.Error()) +} diff --git a/vendor/google.golang.org/grpc/grpclb.go b/vendor/google.golang.org/grpc/grpclb.go index db56ff3621..bc2b445255 100644 --- a/vendor/google.golang.org/grpc/grpclb.go +++ b/vendor/google.golang.org/grpc/grpclb.go @@ -19,21 +19,32 @@ package grpc import ( - "errors" - "fmt" - "math/rand" - "net" + "strconv" + "strings" "sync" "time" "golang.org/x/net/context" - "google.golang.org/grpc/codes" - lbmpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/connectivity" + lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" "google.golang.org/grpc/grpclog" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/naming" + "google.golang.org/grpc/resolver" ) +const ( + lbTokeyKey = "lb-token" + defaultFallbackTimeout = 10 * time.Second + grpclbName = "grpclb" +) + +func convertDuration(d *lbpb.Duration) time.Duration { + if d == nil { + return 0 + } + return time.Duration(d.Seconds)*time.Second + time.Duration(d.Nanos)*time.Nanosecond +} + // Client API for LoadBalancer service. // Mostly copied from generated pb.go file. // To avoid circular dependency. @@ -47,7 +58,7 @@ func (c *loadBalancerClient) BalanceLoad(ctx context.Context, opts ...CallOption ServerStreams: true, ClientStreams: true, } - stream, err := NewClientStream(ctx, desc, c.cc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) + stream, err := c.cc.NewStream(ctx, desc, "/grpc.lb.v1.LoadBalancer/BalanceLoad", opts...) if err != nil { return nil, err } @@ -59,646 +70,272 @@ type balanceLoadClientStream struct { ClientStream } -func (x *balanceLoadClientStream) Send(m *lbmpb.LoadBalanceRequest) error { +func (x *balanceLoadClientStream) Send(m *lbpb.LoadBalanceRequest) error { return x.ClientStream.SendMsg(m) } -func (x *balanceLoadClientStream) Recv() (*lbmpb.LoadBalanceResponse, error) { - m := new(lbmpb.LoadBalanceResponse) +func (x *balanceLoadClientStream) Recv() (*lbpb.LoadBalanceResponse, error) { + m := new(lbpb.LoadBalanceResponse) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } -// NewGRPCLBBalancer creates a grpclb load balancer. -func NewGRPCLBBalancer(r naming.Resolver) Balancer { - return &grpclbBalancer{ - r: r, - } +func init() { + balancer.Register(newLBBuilder()) } -type remoteBalancerInfo struct { - addr string - // the server name used for authentication with the remote LB server. - name string +// newLBBuilder creates a builder for grpclb. +func newLBBuilder() balancer.Builder { + return NewLBBuilderWithFallbackTimeout(defaultFallbackTimeout) } -// grpclbAddrInfo consists of the information of a backend server. -type grpclbAddrInfo struct { - addr Address - connected bool - // dropForRateLimiting indicates whether this particular request should be - // dropped by the client for rate limiting. - dropForRateLimiting bool - // dropForLoadBalancing indicates whether this particular request should be - // dropped by the client for load balancing. - dropForLoadBalancing bool +// NewLBBuilderWithFallbackTimeout creates a grpclb builder with the given +// fallbackTimeout. If no response is received from the remote balancer within +// fallbackTimeout, the backend addresses from the resolved address list will be +// used. +// +// Only call this function when a non-default fallback timeout is needed. +func NewLBBuilderWithFallbackTimeout(fallbackTimeout time.Duration) balancer.Builder { + return &lbBuilder{ + fallbackTimeout: fallbackTimeout, + } } -type grpclbBalancer struct { - r naming.Resolver - target string - mu sync.Mutex - seq int // a sequence number to make sure addrCh does not get stale addresses. - w naming.Watcher - addrCh chan []Address - rbs []remoteBalancerInfo - addrs []*grpclbAddrInfo - next int - waitCh chan struct{} - done bool - rand *rand.Rand - - clientStats lbmpb.ClientStats +type lbBuilder struct { + fallbackTimeout time.Duration } -func (b *grpclbBalancer) watchAddrUpdates(w naming.Watcher, ch chan []remoteBalancerInfo) error { - updates, err := w.Next() - if err != nil { - grpclog.Warningf("grpclb: failed to get next addr update from watcher: %v", err) - return err - } - b.mu.Lock() - defer b.mu.Unlock() - if b.done { - return ErrClientConnClosing - } - for _, update := range updates { - switch update.Op { - case naming.Add: - var exist bool - for _, v := range b.rbs { - // TODO: Is the same addr with different server name a different balancer? - if update.Addr == v.addr { - exist = true - break - } - } - if exist { - continue - } - md, ok := update.Metadata.(*naming.AddrMetadataGRPCLB) - if !ok { - // TODO: Revisit the handling here and may introduce some fallback mechanism. - grpclog.Errorf("The name resolution contains unexpected metadata %v", update.Metadata) - continue - } - switch md.AddrType { - case naming.Backend: - // TODO: Revisit the handling here and may introduce some fallback mechanism. - grpclog.Errorf("The name resolution does not give grpclb addresses") - continue - case naming.GRPCLB: - b.rbs = append(b.rbs, remoteBalancerInfo{ - addr: update.Addr, - name: md.ServerName, - }) - default: - grpclog.Errorf("Received unknow address type %d", md.AddrType) - continue - } - case naming.Delete: - for i, v := range b.rbs { - if update.Addr == v.addr { - copy(b.rbs[i:], b.rbs[i+1:]) - b.rbs = b.rbs[:len(b.rbs)-1] - break - } - } - default: - grpclog.Errorf("Unknown update.Op %v", update.Op) - } +func (b *lbBuilder) Name() string { + return grpclbName +} + +func (b *lbBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions) balancer.Balancer { + // This generates a manual resolver builder with a random scheme. This + // scheme will be used to dial to remote LB, so we can send filtered address + // updates to remote LB ClientConn using this manual resolver. + scheme := "grpclb_internal_" + strconv.FormatInt(time.Now().UnixNano(), 36) + r := &lbManualResolver{scheme: scheme, ccb: cc} + + var target string + targetSplitted := strings.Split(cc.Target(), ":///") + if len(targetSplitted) < 2 { + target = cc.Target() + } else { + target = targetSplitted[1] } - // TODO: Fall back to the basic round-robin load balancing if the resulting address is - // not a load balancer. - select { - case <-ch: - default: + + lb := &lbBalancer{ + cc: newLBCacheClientConn(cc), + target: target, + opt: opt, + fallbackTimeout: b.fallbackTimeout, + doneCh: make(chan struct{}), + + manualResolver: r, + csEvltr: &connectivityStateEvaluator{}, + subConns: make(map[resolver.Address]balancer.SubConn), + scStates: make(map[balancer.SubConn]connectivity.State), + picker: &errPicker{err: balancer.ErrNoSubConnAvailable}, + clientStats: &rpcStats{}, } - ch <- b.rbs - return nil + + return lb } -func convertDuration(d *lbmpb.Duration) time.Duration { - if d == nil { - return 0 - } - return time.Duration(d.Seconds)*time.Second + time.Duration(d.Nanos)*time.Nanosecond +type lbBalancer struct { + cc *lbCacheClientConn + target string + opt balancer.BuildOptions + fallbackTimeout time.Duration + doneCh chan struct{} + + // manualResolver is used in the remote LB ClientConn inside grpclb. When + // resolved address updates are received by grpclb, filtered updates will be + // send to remote LB ClientConn through this resolver. + manualResolver *lbManualResolver + // The ClientConn to talk to the remote balancer. + ccRemoteLB *ClientConn + + // Support client side load reporting. Each picker gets a reference to this, + // and will update its content. + clientStats *rpcStats + + mu sync.Mutex // guards everything following. + // The full server list including drops, used to check if the newly received + // serverList contains anything new. Each generate picker will also have + // reference to this list to do the first layer pick. + fullServerList []*lbpb.Server + // All backends addresses, with metadata set to nil. This list contains all + // backend addresses in the same order and with the same duplicates as in + // serverlist. When generating picker, a SubConn slice with the same order + // but with only READY SCs will be gerenated. + backendAddrs []resolver.Address + // Roundrobin functionalities. + csEvltr *connectivityStateEvaluator + state connectivity.State + subConns map[resolver.Address]balancer.SubConn // Used to new/remove SubConn. + scStates map[balancer.SubConn]connectivity.State // Used to filter READY SubConns. + picker balancer.Picker + // Support fallback to resolved backend addresses if there's no response + // from remote balancer within fallbackTimeout. + fallbackTimerExpired bool + serverListReceived bool + // resolvedBackendAddrs is resolvedAddrs minus remote balancers. It's set + // when resolved address updates are received, and read in the goroutine + // handling fallback. + resolvedBackendAddrs []resolver.Address } -func (b *grpclbBalancer) processServerList(l *lbmpb.ServerList, seq int) { - if l == nil { +// regeneratePicker takes a snapshot of the balancer, and generates a picker from +// it. The picker +// - always returns ErrTransientFailure if the balancer is in TransientFailure, +// - does two layer roundrobin pick otherwise. +// Caller must hold lb.mu. +func (lb *lbBalancer) regeneratePicker() { + if lb.state == connectivity.TransientFailure { + lb.picker = &errPicker{err: balancer.ErrTransientFailure} return } - servers := l.GetServers() - var ( - sl []*grpclbAddrInfo - addrs []Address - ) - for _, s := range servers { - md := metadata.Pairs("lb-token", s.LoadBalanceToken) - ip := net.IP(s.IpAddress) - ipStr := ip.String() - if ip.To4() == nil { - // Add square brackets to ipv6 addresses, otherwise net.Dial() and - // net.SplitHostPort() will return too many colons error. - ipStr = fmt.Sprintf("[%s]", ipStr) - } - addr := Address{ - Addr: fmt.Sprintf("%s:%d", ipStr, s.Port), - Metadata: &md, + var readySCs []balancer.SubConn + for _, a := range lb.backendAddrs { + if sc, ok := lb.subConns[a]; ok { + if st, ok := lb.scStates[sc]; ok && st == connectivity.Ready { + readySCs = append(readySCs, sc) + } } - sl = append(sl, &grpclbAddrInfo{ - addr: addr, - dropForRateLimiting: s.DropForRateLimiting, - dropForLoadBalancing: s.DropForLoadBalancing, - }) - addrs = append(addrs, addr) } - b.mu.Lock() - defer b.mu.Unlock() - if b.done || seq < b.seq { - return - } - if len(sl) > 0 { - // reset b.next to 0 when replacing the server list. - b.next = 0 - b.addrs = sl - b.addrCh <- addrs - } - return -} -func (b *grpclbBalancer) sendLoadReport(s *balanceLoadClientStream, interval time.Duration, done <-chan struct{}) { - ticker := time.NewTicker(interval) - defer ticker.Stop() - for { - select { - case <-ticker.C: - case <-done: - return - } - b.mu.Lock() - stats := b.clientStats - b.clientStats = lbmpb.ClientStats{} // Clear the stats. - b.mu.Unlock() - t := time.Now() - stats.Timestamp = &lbmpb.Timestamp{ - Seconds: t.Unix(), - Nanos: int32(t.Nanosecond()), - } - if err := s.Send(&lbmpb.LoadBalanceRequest{ - LoadBalanceRequestType: &lbmpb.LoadBalanceRequest_ClientStats{ - ClientStats: &stats, - }, - }); err != nil { - grpclog.Errorf("grpclb: failed to send load report: %v", err) + if len(lb.fullServerList) <= 0 { + if len(readySCs) <= 0 { + lb.picker = &errPicker{err: balancer.ErrNoSubConnAvailable} return } - } -} - -func (b *grpclbBalancer) callRemoteBalancer(lbc *loadBalancerClient, seq int) (retry bool) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - stream, err := lbc.BalanceLoad(ctx) - if err != nil { - grpclog.Errorf("grpclb: failed to perform RPC to the remote balancer %v", err) - return - } - b.mu.Lock() - if b.done { - b.mu.Unlock() - return - } - b.mu.Unlock() - initReq := &lbmpb.LoadBalanceRequest{ - LoadBalanceRequestType: &lbmpb.LoadBalanceRequest_InitialRequest{ - InitialRequest: &lbmpb.InitialLoadBalanceRequest{ - Name: b.target, - }, - }, - } - if err := stream.Send(initReq); err != nil { - grpclog.Errorf("grpclb: failed to send init request: %v", err) - // TODO: backoff on retry? - return true - } - reply, err := stream.Recv() - if err != nil { - grpclog.Errorf("grpclb: failed to recv init response: %v", err) - // TODO: backoff on retry? - return true - } - initResp := reply.GetInitialResponse() - if initResp == nil { - grpclog.Errorf("grpclb: reply from remote balancer did not include initial response.") - return - } - // TODO: Support delegation. - if initResp.LoadBalancerDelegate != "" { - // delegation - grpclog.Errorf("TODO: Delegation is not supported yet.") + lb.picker = &rrPicker{subConns: readySCs} return } - streamDone := make(chan struct{}) - defer close(streamDone) - b.mu.Lock() - b.clientStats = lbmpb.ClientStats{} // Clear client stats. - b.mu.Unlock() - if d := convertDuration(initResp.ClientStatsReportInterval); d > 0 { - go b.sendLoadReport(stream, d, streamDone) + lb.picker = &lbPicker{ + serverList: lb.fullServerList, + subConns: readySCs, + stats: lb.clientStats, } - // Retrieve the server list. - for { - reply, err := stream.Recv() - if err != nil { - grpclog.Errorf("grpclb: failed to recv server list: %v", err) - break - } - b.mu.Lock() - if b.done || seq < b.seq { - b.mu.Unlock() - return - } - b.seq++ // tick when receiving a new list of servers. - seq = b.seq - b.mu.Unlock() - if serverList := reply.GetServerList(); serverList != nil { - b.processServerList(serverList, seq) - } - } - return true } -func (b *grpclbBalancer) Start(target string, config BalancerConfig) error { - b.rand = rand.New(rand.NewSource(time.Now().Unix())) - // TODO: Fall back to the basic direct connection if there is no name resolver. - if b.r == nil { - return errors.New("there is no name resolver installed") +func (lb *lbBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { + grpclog.Infof("lbBalancer: handle SubConn state change: %p, %v", sc, s) + lb.mu.Lock() + defer lb.mu.Unlock() + + oldS, ok := lb.scStates[sc] + if !ok { + grpclog.Infof("lbBalancer: got state changes for an unknown SubConn: %p, %v", sc, s) + return } - b.target = target - b.mu.Lock() - if b.done { - b.mu.Unlock() - return ErrClientConnClosing + lb.scStates[sc] = s + switch s { + case connectivity.Idle: + sc.Connect() + case connectivity.Shutdown: + // When an address was removed by resolver, b called RemoveSubConn but + // kept the sc's state in scStates. Remove state for this sc here. + delete(lb.scStates, sc) } - b.addrCh = make(chan []Address) - w, err := b.r.Resolve(target) - if err != nil { - b.mu.Unlock() - grpclog.Errorf("grpclb: failed to resolve address: %v, err: %v", target, err) - return err - } - b.w = w - b.mu.Unlock() - balancerAddrsCh := make(chan []remoteBalancerInfo, 1) - // Spawn a goroutine to monitor the name resolution of remote load balancer. - go func() { - for { - if err := b.watchAddrUpdates(w, balancerAddrsCh); err != nil { - grpclog.Warningf("grpclb: the naming watcher stops working due to %v.\n", err) - close(balancerAddrsCh) - return - } - } - }() - // Spawn a goroutine to talk to the remote load balancer. - go func() { - var ( - cc *ClientConn - // ccError is closed when there is an error in the current cc. - // A new rb should be picked from rbs and connected. - ccError chan struct{} - rb *remoteBalancerInfo - rbs []remoteBalancerInfo - rbIdx int - ) - - defer func() { - if ccError != nil { - select { - case <-ccError: - default: - close(ccError) - } - } - if cc != nil { - cc.Close() - } - }() - - for { - var ok bool - select { - case rbs, ok = <-balancerAddrsCh: - if !ok { - return - } - foundIdx := -1 - if rb != nil { - for i, trb := range rbs { - if trb == *rb { - foundIdx = i - break - } - } - } - if foundIdx >= 0 { - if foundIdx >= 1 { - // Move the address in use to the beginning of the list. - b.rbs[0], b.rbs[foundIdx] = b.rbs[foundIdx], b.rbs[0] - rbIdx = 0 - } - continue // If found, don't dial new cc. - } else if len(rbs) > 0 { - // Pick a random one from the list, instead of always using the first one. - if l := len(rbs); l > 1 && rb != nil { - tmpIdx := b.rand.Intn(l - 1) - b.rbs[0], b.rbs[tmpIdx] = b.rbs[tmpIdx], b.rbs[0] - } - rbIdx = 0 - rb = &rbs[0] - } else { - // foundIdx < 0 && len(rbs) <= 0. - rb = nil - } - case <-ccError: - ccError = nil - if rbIdx < len(rbs)-1 { - rbIdx++ - rb = &rbs[rbIdx] - } else { - rb = nil - } - } - if rb == nil { - continue - } + oldAggrState := lb.state + lb.state = lb.csEvltr.recordTransition(oldS, s) - if cc != nil { - cc.Close() - } - // Talk to the remote load balancer to get the server list. - var ( - err error - dopts []DialOption - ) - if creds := config.DialCreds; creds != nil { - if rb.name != "" { - if err := creds.OverrideServerName(rb.name); err != nil { - grpclog.Warningf("grpclb: failed to override the server name in the credentials: %v", err) - continue - } - } - dopts = append(dopts, WithTransportCredentials(creds)) - } else { - dopts = append(dopts, WithInsecure()) - } - if dialer := config.Dialer; dialer != nil { - // WithDialer takes a different type of function, so we instead use a special DialOption here. - dopts = append(dopts, func(o *dialOptions) { o.copts.Dialer = dialer }) - } - dopts = append(dopts, WithBlock()) - ccError = make(chan struct{}) - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - cc, err = DialContext(ctx, rb.addr, dopts...) - cancel() - if err != nil { - grpclog.Warningf("grpclb: failed to setup a connection to the remote balancer %v: %v", rb.addr, err) - close(ccError) - continue - } - b.mu.Lock() - b.seq++ // tick when getting a new balancer address - seq := b.seq - b.next = 0 - b.mu.Unlock() - go func(cc *ClientConn, ccError chan struct{}) { - lbc := &loadBalancerClient{cc} - b.callRemoteBalancer(lbc, seq) - cc.Close() - select { - case <-ccError: - default: - close(ccError) - } - }(cc, ccError) - } - }() - return nil -} - -func (b *grpclbBalancer) down(addr Address, err error) { - b.mu.Lock() - defer b.mu.Unlock() - for _, a := range b.addrs { - if addr == a.addr { - a.connected = false - break - } + // Regenerate picker when one of the following happens: + // - this sc became ready from not-ready + // - this sc became not-ready from ready + // - the aggregated state of balancer became TransientFailure from non-TransientFailure + // - the aggregated state of balancer became non-TransientFailure from TransientFailure + if (oldS == connectivity.Ready) != (s == connectivity.Ready) || + (lb.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) { + lb.regeneratePicker() } + + lb.cc.UpdateBalancerState(lb.state, lb.picker) } -func (b *grpclbBalancer) Up(addr Address) func(error) { - b.mu.Lock() - defer b.mu.Unlock() - if b.done { - return nil - } - var cnt int - for _, a := range b.addrs { - if a.addr == addr { - if a.connected { - return nil - } - a.connected = true - } - if a.connected && !a.dropForRateLimiting && !a.dropForLoadBalancing { - cnt++ - } - } - // addr is the only one which is connected. Notify the Get() callers who are blocking. - if cnt == 1 && b.waitCh != nil { - close(b.waitCh) - b.waitCh = nil +// fallbackToBackendsAfter blocks for fallbackTimeout and falls back to use +// resolved backends (backends received from resolver, not from remote balancer) +// if no connection to remote balancers was successful. +func (lb *lbBalancer) fallbackToBackendsAfter(fallbackTimeout time.Duration) { + timer := time.NewTimer(fallbackTimeout) + defer timer.Stop() + select { + case <-timer.C: + case <-lb.doneCh: + return } - return func(err error) { - b.down(addr, err) + lb.mu.Lock() + if lb.serverListReceived { + lb.mu.Unlock() + return } + lb.fallbackTimerExpired = true + lb.refreshSubConns(lb.resolvedBackendAddrs) + lb.mu.Unlock() } -func (b *grpclbBalancer) Get(ctx context.Context, opts BalancerGetOptions) (addr Address, put func(), err error) { - var ch chan struct{} - b.mu.Lock() - if b.done { - b.mu.Unlock() - err = ErrClientConnClosing +// HandleResolvedAddrs sends the updated remoteLB addresses to remoteLB +// clientConn. The remoteLB clientConn will handle creating/removing remoteLB +// connections. +func (lb *lbBalancer) HandleResolvedAddrs(addrs []resolver.Address, err error) { + grpclog.Infof("lbBalancer: handleResolvedResult: %+v", addrs) + if len(addrs) <= 0 { return } - seq := b.seq - defer func() { - if err != nil { - return - } - put = func() { - s, ok := rpcInfoFromContext(ctx) - if !ok { - return - } - b.mu.Lock() - defer b.mu.Unlock() - if b.done || seq < b.seq { - return - } - b.clientStats.NumCallsFinished++ - if !s.bytesSent { - b.clientStats.NumCallsFinishedWithClientFailedToSend++ - } else if s.bytesReceived { - b.clientStats.NumCallsFinishedKnownReceived++ - } + var remoteBalancerAddrs, backendAddrs []resolver.Address + for _, a := range addrs { + if a.Type == resolver.GRPCLB { + remoteBalancerAddrs = append(remoteBalancerAddrs, a) + } else { + backendAddrs = append(backendAddrs, a) } - }() - - b.clientStats.NumCallsStarted++ - if len(b.addrs) > 0 { - if b.next >= len(b.addrs) { - b.next = 0 - } - next := b.next - for { - a := b.addrs[next] - next = (next + 1) % len(b.addrs) - if a.connected { - if !a.dropForRateLimiting && !a.dropForLoadBalancing { - addr = a.addr - b.next = next - b.mu.Unlock() - return - } - if !opts.BlockingWait { - b.next = next - if a.dropForLoadBalancing { - b.clientStats.NumCallsFinished++ - b.clientStats.NumCallsFinishedWithDropForLoadBalancing++ - } else if a.dropForRateLimiting { - b.clientStats.NumCallsFinished++ - b.clientStats.NumCallsFinishedWithDropForRateLimiting++ - } - b.mu.Unlock() - err = Errorf(codes.Unavailable, "%s drops requests", a.addr.Addr) - return - } - } - if next == b.next { - // Has iterated all the possible address but none is connected. - break - } - } - } - if !opts.BlockingWait { - b.clientStats.NumCallsFinished++ - b.clientStats.NumCallsFinishedWithClientFailedToSend++ - b.mu.Unlock() - err = Errorf(codes.Unavailable, "there is no address available") - return } - // Wait on b.waitCh for non-failfast RPCs. - if b.waitCh == nil { - ch = make(chan struct{}) - b.waitCh = ch - } else { - ch = b.waitCh - } - b.mu.Unlock() - for { - select { - case <-ctx.Done(): - b.mu.Lock() - b.clientStats.NumCallsFinished++ - b.clientStats.NumCallsFinishedWithClientFailedToSend++ - b.mu.Unlock() - err = ctx.Err() - return - case <-ch: - b.mu.Lock() - if b.done { - b.clientStats.NumCallsFinished++ - b.clientStats.NumCallsFinishedWithClientFailedToSend++ - b.mu.Unlock() - err = ErrClientConnClosing - return - } - if len(b.addrs) > 0 { - if b.next >= len(b.addrs) { - b.next = 0 - } - next := b.next - for { - a := b.addrs[next] - next = (next + 1) % len(b.addrs) - if a.connected { - if !a.dropForRateLimiting && !a.dropForLoadBalancing { - addr = a.addr - b.next = next - b.mu.Unlock() - return - } - if !opts.BlockingWait { - b.next = next - if a.dropForLoadBalancing { - b.clientStats.NumCallsFinished++ - b.clientStats.NumCallsFinishedWithDropForLoadBalancing++ - } else if a.dropForRateLimiting { - b.clientStats.NumCallsFinished++ - b.clientStats.NumCallsFinishedWithDropForRateLimiting++ - } - b.mu.Unlock() - err = Errorf(codes.Unavailable, "drop requests for the addreess %s", a.addr.Addr) - return - } - } - if next == b.next { - // Has iterated all the possible address but none is connected. - break - } - } - } - // The newly added addr got removed by Down() again. - if b.waitCh == nil { - ch = make(chan struct{}) - b.waitCh = ch - } else { - ch = b.waitCh - } - b.mu.Unlock() + if lb.ccRemoteLB == nil { + if len(remoteBalancerAddrs) <= 0 { + grpclog.Errorf("grpclb: no remote balancer address is available, should never happen") + return } + // First time receiving resolved addresses, create a cc to remote + // balancers. + lb.dialRemoteLB(remoteBalancerAddrs[0].ServerName) + // Start the fallback goroutine. + go lb.fallbackToBackendsAfter(lb.fallbackTimeout) } -} -func (b *grpclbBalancer) Notify() <-chan []Address { - return b.addrCh + // cc to remote balancers uses lb.manualResolver. Send the updated remote + // balancer addresses to it through manualResolver. + lb.manualResolver.NewAddress(remoteBalancerAddrs) + + lb.mu.Lock() + lb.resolvedBackendAddrs = backendAddrs + // If serverListReceived is true, connection to remote balancer was + // successful and there's no need to do fallback anymore. + // If fallbackTimerExpired is false, fallback hasn't happened yet. + if !lb.serverListReceived && lb.fallbackTimerExpired { + // This means we received a new list of resolved backends, and we are + // still in fallback mode. Need to update the list of backends we are + // using to the new list of backends. + lb.refreshSubConns(lb.resolvedBackendAddrs) + } + lb.mu.Unlock() } -func (b *grpclbBalancer) Close() error { - b.mu.Lock() - defer b.mu.Unlock() - if b.done { - return errBalancerClosed - } - b.done = true - if b.waitCh != nil { - close(b.waitCh) - } - if b.addrCh != nil { - close(b.addrCh) +func (lb *lbBalancer) Close() { + select { + case <-lb.doneCh: + return + default: } - if b.w != nil { - b.w.Close() + close(lb.doneCh) + if lb.ccRemoteLB != nil { + lb.ccRemoteLB.Close() } - return nil + lb.cc.close() } diff --git a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go index f4a27125a4..b3b32b48e8 100644 --- a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go +++ b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.pb.go @@ -1,24 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // source: grpc_lb_v1/messages/messages.proto -/* -Package messages is a generated protocol buffer package. - -It is generated from these files: - grpc_lb_v1/messages/messages.proto - -It has these top-level messages: - Duration - Timestamp - LoadBalanceRequest - InitialLoadBalanceRequest - ClientStats - LoadBalanceResponse - InitialLoadBalanceResponse - ServerList - Server -*/ -package messages +package messages // import "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" import proto "github.com/golang/protobuf/proto" import fmt "fmt" @@ -45,13 +28,35 @@ type Duration struct { // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. - Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` + Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *Duration) Reset() { *m = Duration{} } -func (m *Duration) String() string { return proto.CompactTextString(m) } -func (*Duration) ProtoMessage() {} -func (*Duration) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } +func (m *Duration) Reset() { *m = Duration{} } +func (m *Duration) String() string { return proto.CompactTextString(m) } +func (*Duration) ProtoMessage() {} +func (*Duration) Descriptor() ([]byte, []int) { + return fileDescriptor_messages_b81c731f0e83edbd, []int{0} +} +func (m *Duration) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Duration.Unmarshal(m, b) +} +func (m *Duration) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Duration.Marshal(b, m, deterministic) +} +func (dst *Duration) XXX_Merge(src proto.Message) { + xxx_messageInfo_Duration.Merge(dst, src) +} +func (m *Duration) XXX_Size() int { + return xxx_messageInfo_Duration.Size(m) +} +func (m *Duration) XXX_DiscardUnknown() { + xxx_messageInfo_Duration.DiscardUnknown(m) +} + +var xxx_messageInfo_Duration proto.InternalMessageInfo func (m *Duration) GetSeconds() int64 { if m != nil { @@ -76,13 +81,35 @@ type Timestamp struct { // 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. - Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` + Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *Timestamp) Reset() { *m = Timestamp{} } +func (m *Timestamp) String() string { return proto.CompactTextString(m) } +func (*Timestamp) ProtoMessage() {} +func (*Timestamp) Descriptor() ([]byte, []int) { + return fileDescriptor_messages_b81c731f0e83edbd, []int{1} +} +func (m *Timestamp) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Timestamp.Unmarshal(m, b) +} +func (m *Timestamp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Timestamp.Marshal(b, m, deterministic) +} +func (dst *Timestamp) XXX_Merge(src proto.Message) { + xxx_messageInfo_Timestamp.Merge(dst, src) +} +func (m *Timestamp) XXX_Size() int { + return xxx_messageInfo_Timestamp.Size(m) +} +func (m *Timestamp) XXX_DiscardUnknown() { + xxx_messageInfo_Timestamp.DiscardUnknown(m) } -func (m *Timestamp) Reset() { *m = Timestamp{} } -func (m *Timestamp) String() string { return proto.CompactTextString(m) } -func (*Timestamp) ProtoMessage() {} -func (*Timestamp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } +var xxx_messageInfo_Timestamp proto.InternalMessageInfo func (m *Timestamp) GetSeconds() int64 { if m != nil { @@ -103,12 +130,34 @@ type LoadBalanceRequest struct { // *LoadBalanceRequest_InitialRequest // *LoadBalanceRequest_ClientStats LoadBalanceRequestType isLoadBalanceRequest_LoadBalanceRequestType `protobuf_oneof:"load_balance_request_type"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *LoadBalanceRequest) Reset() { *m = LoadBalanceRequest{} } +func (m *LoadBalanceRequest) String() string { return proto.CompactTextString(m) } +func (*LoadBalanceRequest) ProtoMessage() {} +func (*LoadBalanceRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_messages_b81c731f0e83edbd, []int{2} +} +func (m *LoadBalanceRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_LoadBalanceRequest.Unmarshal(m, b) +} +func (m *LoadBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_LoadBalanceRequest.Marshal(b, m, deterministic) +} +func (dst *LoadBalanceRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_LoadBalanceRequest.Merge(dst, src) +} +func (m *LoadBalanceRequest) XXX_Size() int { + return xxx_messageInfo_LoadBalanceRequest.Size(m) +} +func (m *LoadBalanceRequest) XXX_DiscardUnknown() { + xxx_messageInfo_LoadBalanceRequest.DiscardUnknown(m) } -func (m *LoadBalanceRequest) Reset() { *m = LoadBalanceRequest{} } -func (m *LoadBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*LoadBalanceRequest) ProtoMessage() {} -func (*LoadBalanceRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } +var xxx_messageInfo_LoadBalanceRequest proto.InternalMessageInfo type isLoadBalanceRequest_LoadBalanceRequestType interface { isLoadBalanceRequest_LoadBalanceRequestType() @@ -204,12 +253,12 @@ func _LoadBalanceRequest_OneofSizer(msg proto.Message) (n int) { switch x := m.LoadBalanceRequestType.(type) { case *LoadBalanceRequest_InitialRequest: s := proto.Size(x.InitialRequest) - n += proto.SizeVarint(1<<3 | proto.WireBytes) + n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case *LoadBalanceRequest_ClientStats: s := proto.Size(x.ClientStats) - n += proto.SizeVarint(2<<3 | proto.WireBytes) + n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case nil: @@ -222,13 +271,35 @@ func _LoadBalanceRequest_OneofSizer(msg proto.Message) (n int) { type InitialLoadBalanceRequest struct { // Name of load balanced service (IE, balancer.service.com) // length should be less than 256 bytes. - Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *InitialLoadBalanceRequest) Reset() { *m = InitialLoadBalanceRequest{} } +func (m *InitialLoadBalanceRequest) String() string { return proto.CompactTextString(m) } +func (*InitialLoadBalanceRequest) ProtoMessage() {} +func (*InitialLoadBalanceRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_messages_b81c731f0e83edbd, []int{3} +} +func (m *InitialLoadBalanceRequest) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_InitialLoadBalanceRequest.Unmarshal(m, b) +} +func (m *InitialLoadBalanceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_InitialLoadBalanceRequest.Marshal(b, m, deterministic) +} +func (dst *InitialLoadBalanceRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_InitialLoadBalanceRequest.Merge(dst, src) +} +func (m *InitialLoadBalanceRequest) XXX_Size() int { + return xxx_messageInfo_InitialLoadBalanceRequest.Size(m) +} +func (m *InitialLoadBalanceRequest) XXX_DiscardUnknown() { + xxx_messageInfo_InitialLoadBalanceRequest.DiscardUnknown(m) } -func (m *InitialLoadBalanceRequest) Reset() { *m = InitialLoadBalanceRequest{} } -func (m *InitialLoadBalanceRequest) String() string { return proto.CompactTextString(m) } -func (*InitialLoadBalanceRequest) ProtoMessage() {} -func (*InitialLoadBalanceRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} } +var xxx_messageInfo_InitialLoadBalanceRequest proto.InternalMessageInfo func (m *InitialLoadBalanceRequest) GetName() string { if m != nil { @@ -256,13 +327,35 @@ type ClientStats struct { NumCallsFinishedWithClientFailedToSend int64 `protobuf:"varint,6,opt,name=num_calls_finished_with_client_failed_to_send,json=numCallsFinishedWithClientFailedToSend" json:"num_calls_finished_with_client_failed_to_send,omitempty"` // The total number of RPCs that finished and are known to have been received // by a server. - NumCallsFinishedKnownReceived int64 `protobuf:"varint,7,opt,name=num_calls_finished_known_received,json=numCallsFinishedKnownReceived" json:"num_calls_finished_known_received,omitempty"` + NumCallsFinishedKnownReceived int64 `protobuf:"varint,7,opt,name=num_calls_finished_known_received,json=numCallsFinishedKnownReceived" json:"num_calls_finished_known_received,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ClientStats) Reset() { *m = ClientStats{} } +func (m *ClientStats) String() string { return proto.CompactTextString(m) } +func (*ClientStats) ProtoMessage() {} +func (*ClientStats) Descriptor() ([]byte, []int) { + return fileDescriptor_messages_b81c731f0e83edbd, []int{4} +} +func (m *ClientStats) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ClientStats.Unmarshal(m, b) +} +func (m *ClientStats) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ClientStats.Marshal(b, m, deterministic) +} +func (dst *ClientStats) XXX_Merge(src proto.Message) { + xxx_messageInfo_ClientStats.Merge(dst, src) +} +func (m *ClientStats) XXX_Size() int { + return xxx_messageInfo_ClientStats.Size(m) +} +func (m *ClientStats) XXX_DiscardUnknown() { + xxx_messageInfo_ClientStats.DiscardUnknown(m) } -func (m *ClientStats) Reset() { *m = ClientStats{} } -func (m *ClientStats) String() string { return proto.CompactTextString(m) } -func (*ClientStats) ProtoMessage() {} -func (*ClientStats) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} } +var xxx_messageInfo_ClientStats proto.InternalMessageInfo func (m *ClientStats) GetTimestamp() *Timestamp { if m != nil { @@ -318,12 +411,34 @@ type LoadBalanceResponse struct { // *LoadBalanceResponse_InitialResponse // *LoadBalanceResponse_ServerList LoadBalanceResponseType isLoadBalanceResponse_LoadBalanceResponseType `protobuf_oneof:"load_balance_response_type"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *LoadBalanceResponse) Reset() { *m = LoadBalanceResponse{} } +func (m *LoadBalanceResponse) String() string { return proto.CompactTextString(m) } +func (*LoadBalanceResponse) ProtoMessage() {} +func (*LoadBalanceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_messages_b81c731f0e83edbd, []int{5} +} +func (m *LoadBalanceResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_LoadBalanceResponse.Unmarshal(m, b) +} +func (m *LoadBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_LoadBalanceResponse.Marshal(b, m, deterministic) +} +func (dst *LoadBalanceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_LoadBalanceResponse.Merge(dst, src) +} +func (m *LoadBalanceResponse) XXX_Size() int { + return xxx_messageInfo_LoadBalanceResponse.Size(m) +} +func (m *LoadBalanceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_LoadBalanceResponse.DiscardUnknown(m) } -func (m *LoadBalanceResponse) Reset() { *m = LoadBalanceResponse{} } -func (m *LoadBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*LoadBalanceResponse) ProtoMessage() {} -func (*LoadBalanceResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} } +var xxx_messageInfo_LoadBalanceResponse proto.InternalMessageInfo type isLoadBalanceResponse_LoadBalanceResponseType interface { isLoadBalanceResponse_LoadBalanceResponseType() @@ -419,12 +534,12 @@ func _LoadBalanceResponse_OneofSizer(msg proto.Message) (n int) { switch x := m.LoadBalanceResponseType.(type) { case *LoadBalanceResponse_InitialResponse: s := proto.Size(x.InitialResponse) - n += proto.SizeVarint(1<<3 | proto.WireBytes) + n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case *LoadBalanceResponse_ServerList: s := proto.Size(x.ServerList) - n += proto.SizeVarint(2<<3 | proto.WireBytes) + n += 1 // tag and wire n += proto.SizeVarint(uint64(s)) n += s case nil: @@ -445,12 +560,34 @@ type InitialLoadBalanceResponse struct { // to the load balancer. Stats should only be reported when the duration is // positive. ClientStatsReportInterval *Duration `protobuf:"bytes,2,opt,name=client_stats_report_interval,json=clientStatsReportInterval" json:"client_stats_report_interval,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *InitialLoadBalanceResponse) Reset() { *m = InitialLoadBalanceResponse{} } +func (m *InitialLoadBalanceResponse) String() string { return proto.CompactTextString(m) } +func (*InitialLoadBalanceResponse) ProtoMessage() {} +func (*InitialLoadBalanceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_messages_b81c731f0e83edbd, []int{6} +} +func (m *InitialLoadBalanceResponse) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_InitialLoadBalanceResponse.Unmarshal(m, b) +} +func (m *InitialLoadBalanceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_InitialLoadBalanceResponse.Marshal(b, m, deterministic) +} +func (dst *InitialLoadBalanceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_InitialLoadBalanceResponse.Merge(dst, src) +} +func (m *InitialLoadBalanceResponse) XXX_Size() int { + return xxx_messageInfo_InitialLoadBalanceResponse.Size(m) +} +func (m *InitialLoadBalanceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_InitialLoadBalanceResponse.DiscardUnknown(m) } -func (m *InitialLoadBalanceResponse) Reset() { *m = InitialLoadBalanceResponse{} } -func (m *InitialLoadBalanceResponse) String() string { return proto.CompactTextString(m) } -func (*InitialLoadBalanceResponse) ProtoMessage() {} -func (*InitialLoadBalanceResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} } +var xxx_messageInfo_InitialLoadBalanceResponse proto.InternalMessageInfo func (m *InitialLoadBalanceResponse) GetLoadBalancerDelegate() string { if m != nil { @@ -471,13 +608,35 @@ type ServerList struct { // be updated when server resolutions change or as needed to balance load // across more servers. The client should consume the server list in order // unless instructed otherwise via the client_config. - Servers []*Server `protobuf:"bytes,1,rep,name=servers" json:"servers,omitempty"` + Servers []*Server `protobuf:"bytes,1,rep,name=servers" json:"servers,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *ServerList) Reset() { *m = ServerList{} } +func (m *ServerList) String() string { return proto.CompactTextString(m) } +func (*ServerList) ProtoMessage() {} +func (*ServerList) Descriptor() ([]byte, []int) { + return fileDescriptor_messages_b81c731f0e83edbd, []int{7} +} +func (m *ServerList) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_ServerList.Unmarshal(m, b) +} +func (m *ServerList) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_ServerList.Marshal(b, m, deterministic) +} +func (dst *ServerList) XXX_Merge(src proto.Message) { + xxx_messageInfo_ServerList.Merge(dst, src) +} +func (m *ServerList) XXX_Size() int { + return xxx_messageInfo_ServerList.Size(m) +} +func (m *ServerList) XXX_DiscardUnknown() { + xxx_messageInfo_ServerList.DiscardUnknown(m) } -func (m *ServerList) Reset() { *m = ServerList{} } -func (m *ServerList) String() string { return proto.CompactTextString(m) } -func (*ServerList) ProtoMessage() {} -func (*ServerList) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} } +var xxx_messageInfo_ServerList proto.InternalMessageInfo func (m *ServerList) GetServers() []*Server { if m != nil { @@ -508,13 +667,35 @@ type Server struct { DropForRateLimiting bool `protobuf:"varint,4,opt,name=drop_for_rate_limiting,json=dropForRateLimiting" json:"drop_for_rate_limiting,omitempty"` // Indicates whether this particular request should be dropped by the client // for load balancing. - DropForLoadBalancing bool `protobuf:"varint,5,opt,name=drop_for_load_balancing,json=dropForLoadBalancing" json:"drop_for_load_balancing,omitempty"` + DropForLoadBalancing bool `protobuf:"varint,5,opt,name=drop_for_load_balancing,json=dropForLoadBalancing" json:"drop_for_load_balancing,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } -func (m *Server) Reset() { *m = Server{} } -func (m *Server) String() string { return proto.CompactTextString(m) } -func (*Server) ProtoMessage() {} -func (*Server) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} } +func (m *Server) Reset() { *m = Server{} } +func (m *Server) String() string { return proto.CompactTextString(m) } +func (*Server) ProtoMessage() {} +func (*Server) Descriptor() ([]byte, []int) { + return fileDescriptor_messages_b81c731f0e83edbd, []int{8} +} +func (m *Server) XXX_Unmarshal(b []byte) error { + return xxx_messageInfo_Server.Unmarshal(m, b) +} +func (m *Server) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + return xxx_messageInfo_Server.Marshal(b, m, deterministic) +} +func (dst *Server) XXX_Merge(src proto.Message) { + xxx_messageInfo_Server.Merge(dst, src) +} +func (m *Server) XXX_Size() int { + return xxx_messageInfo_Server.Size(m) +} +func (m *Server) XXX_DiscardUnknown() { + xxx_messageInfo_Server.DiscardUnknown(m) +} + +var xxx_messageInfo_Server proto.InternalMessageInfo func (m *Server) GetIpAddress() []byte { if m != nil { @@ -563,53 +744,56 @@ func init() { proto.RegisterType((*Server)(nil), "grpc.lb.v1.Server") } -func init() { proto.RegisterFile("grpc_lb_v1/messages/messages.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 709 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0xdd, 0x4e, 0x1b, 0x3b, - 0x10, 0x26, 0x27, 0x01, 0x92, 0x09, 0x3a, 0xe4, 0x98, 0x1c, 0x08, 0x14, 0x24, 0xba, 0x52, 0x69, - 0x54, 0xd1, 0x20, 0xa0, 0xbd, 0xe8, 0xcf, 0x45, 0x1b, 0x10, 0x0a, 0x2d, 0x17, 0x95, 0x43, 0x55, - 0xa9, 0x52, 0x65, 0x39, 0xd9, 0x21, 0x58, 0x6c, 0xec, 0xad, 0xed, 0x04, 0xf5, 0x11, 0xfa, 0x28, - 0x7d, 0x8c, 0xaa, 0xcf, 0xd0, 0xf7, 0xa9, 0xd6, 0xbb, 0x9b, 0x5d, 0x20, 0x80, 0x7a, 0x67, 0x8f, - 0xbf, 0xf9, 0xbe, 0xf1, 0xac, 0xbf, 0x59, 0xf0, 0x06, 0x3a, 0xec, 0xb3, 0xa0, 0xc7, 0xc6, 0xbb, - 0x3b, 0x43, 0x34, 0x86, 0x0f, 0xd0, 0x4c, 0x16, 0xad, 0x50, 0x2b, 0xab, 0x08, 0x44, 0x98, 0x56, - 0xd0, 0x6b, 0x8d, 0x77, 0xbd, 0x97, 0x50, 0x3e, 0x1c, 0x69, 0x6e, 0x85, 0x92, 0xa4, 0x01, 0xf3, - 0x06, 0xfb, 0x4a, 0xfa, 0xa6, 0x51, 0xd8, 0x2c, 0x34, 0x8b, 0x34, 0xdd, 0x92, 0x3a, 0xcc, 0x4a, - 0x2e, 0x95, 0x69, 0xfc, 0xb3, 0x59, 0x68, 0xce, 0xd2, 0x78, 0xe3, 0xbd, 0x82, 0xca, 0xa9, 0x18, - 0xa2, 0xb1, 0x7c, 0x18, 0xfe, 0x75, 0xf2, 0xcf, 0x02, 0x90, 0x13, 0xc5, 0xfd, 0x36, 0x0f, 0xb8, - 0xec, 0x23, 0xc5, 0xaf, 0x23, 0x34, 0x96, 0x7c, 0x80, 0x45, 0x21, 0x85, 0x15, 0x3c, 0x60, 0x3a, - 0x0e, 0x39, 0xba, 0xea, 0xde, 0xa3, 0x56, 0x56, 0x75, 0xeb, 0x38, 0x86, 0xdc, 0xcc, 0xef, 0xcc, - 0xd0, 0x7f, 0x93, 0xfc, 0x94, 0xf1, 0x35, 0x2c, 0xf4, 0x03, 0x81, 0xd2, 0x32, 0x63, 0xb9, 0x8d, - 0xab, 0xa8, 0xee, 0xad, 0xe4, 0xe9, 0x0e, 0xdc, 0x79, 0x37, 0x3a, 0xee, 0xcc, 0xd0, 0x6a, 0x3f, - 0xdb, 0xb6, 0x1f, 0xc0, 0x6a, 0xa0, 0xb8, 0xcf, 0x7a, 0xb1, 0x4c, 0x5a, 0x14, 0xb3, 0xdf, 0x42, - 0xf4, 0x76, 0x60, 0xf5, 0xd6, 0x4a, 0x08, 0x81, 0x92, 0xe4, 0x43, 0x74, 0xe5, 0x57, 0xa8, 0x5b, - 0x7b, 0xdf, 0x4b, 0x50, 0xcd, 0x89, 0x91, 0x7d, 0xa8, 0xd8, 0xb4, 0x83, 0xc9, 0x3d, 0xff, 0xcf, - 0x17, 0x36, 0x69, 0x2f, 0xcd, 0x70, 0xe4, 0x09, 0xfc, 0x27, 0x47, 0x43, 0xd6, 0xe7, 0x41, 0x60, - 0xa2, 0x3b, 0x69, 0x8b, 0xbe, 0xbb, 0x55, 0x91, 0x2e, 0xca, 0xd1, 0xf0, 0x20, 0x8a, 0x77, 0xe3, - 0x30, 0xd9, 0x06, 0x92, 0x61, 0xcf, 0x84, 0x14, 0xe6, 0x1c, 0xfd, 0x46, 0xd1, 0x81, 0x6b, 0x29, - 0xf8, 0x28, 0x89, 0x13, 0x06, 0xad, 0x9b, 0x68, 0x76, 0x29, 0xec, 0x39, 0xf3, 0xb5, 0x0a, 0xd9, - 0x99, 0xd2, 0x4c, 0x73, 0x8b, 0x2c, 0x10, 0x43, 0x61, 0x85, 0x1c, 0x34, 0x4a, 0x8e, 0xe9, 0xf1, - 0x75, 0xa6, 0x4f, 0xc2, 0x9e, 0x1f, 0x6a, 0x15, 0x1e, 0x29, 0x4d, 0xb9, 0xc5, 0x93, 0x04, 0x4e, - 0x38, 0xec, 0xdc, 0x2b, 0x90, 0x6b, 0x77, 0xa4, 0x30, 0xeb, 0x14, 0x9a, 0x77, 0x28, 0x64, 0xbd, - 0x8f, 0x24, 0xbe, 0xc0, 0xd3, 0xdb, 0x24, 0x92, 0x67, 0x70, 0xc6, 0x45, 0x80, 0x3e, 0xb3, 0x8a, - 0x19, 0x94, 0x7e, 0x63, 0xce, 0x09, 0x6c, 0x4d, 0x13, 0x88, 0x3f, 0xd5, 0x91, 0xc3, 0x9f, 0xaa, - 0x2e, 0x4a, 0x9f, 0x74, 0xe0, 0xe1, 0x14, 0xfa, 0x0b, 0xa9, 0x2e, 0x25, 0xd3, 0xd8, 0x47, 0x31, - 0x46, 0xbf, 0x31, 0xef, 0x28, 0x37, 0xae, 0x53, 0xbe, 0x8f, 0x50, 0x34, 0x01, 0x79, 0xbf, 0x0a, - 0xb0, 0x74, 0xe5, 0xd9, 0x98, 0x50, 0x49, 0x83, 0xa4, 0x0b, 0xb5, 0xcc, 0x01, 0x71, 0x2c, 0x79, - 0x1a, 0x5b, 0xf7, 0x59, 0x20, 0x46, 0x77, 0x66, 0xe8, 0xe2, 0xc4, 0x03, 0x09, 0xe9, 0x0b, 0xa8, - 0x1a, 0xd4, 0x63, 0xd4, 0x2c, 0x10, 0xc6, 0x26, 0x1e, 0x58, 0xce, 0xf3, 0x75, 0xdd, 0xf1, 0x89, - 0x70, 0x1e, 0x02, 0x33, 0xd9, 0xb5, 0xd7, 0x61, 0xed, 0x9a, 0x03, 0x62, 0xce, 0xd8, 0x02, 0x3f, - 0x0a, 0xb0, 0x76, 0x7b, 0x29, 0xe4, 0x19, 0x2c, 0xe7, 0x93, 0x35, 0xf3, 0x31, 0xc0, 0x01, 0xb7, - 0xa9, 0x2d, 0xea, 0x41, 0x96, 0xa4, 0x0f, 0x93, 0x33, 0xf2, 0x11, 0xd6, 0xf3, 0x96, 0x65, 0x1a, - 0x43, 0xa5, 0x2d, 0x13, 0xd2, 0xa2, 0x1e, 0xf3, 0x20, 0x29, 0xbf, 0x9e, 0x2f, 0x3f, 0x1d, 0x62, - 0x74, 0x35, 0xe7, 0x5e, 0xea, 0xf2, 0x8e, 0x93, 0x34, 0xef, 0x0d, 0x40, 0x76, 0x4b, 0xb2, 0x1d, - 0x0d, 0xac, 0x68, 0x17, 0x0d, 0xac, 0x62, 0xb3, 0xba, 0x47, 0x6e, 0xb6, 0x83, 0xa6, 0x90, 0x77, - 0xa5, 0x72, 0xb1, 0x56, 0xf2, 0x7e, 0x17, 0x60, 0x2e, 0x3e, 0x21, 0x1b, 0x00, 0x22, 0x64, 0xdc, - 0xf7, 0x35, 0x9a, 0x78, 0xe4, 0x2d, 0xd0, 0x8a, 0x08, 0xdf, 0xc6, 0x81, 0xc8, 0xfd, 0x91, 0x76, - 0x32, 0xf3, 0xdc, 0x3a, 0x32, 0xe3, 0x95, 0x4e, 0x5a, 0x75, 0x81, 0xd2, 0x99, 0xb1, 0x42, 0x6b, - 0xb9, 0x46, 0x9c, 0x46, 0x71, 0xb2, 0x0f, 0xcb, 0x77, 0x98, 0xae, 0x4c, 0x97, 0xfc, 0x29, 0x06, - 0x7b, 0x0e, 0x2b, 0x77, 0x19, 0xa9, 0x4c, 0xeb, 0xfe, 0x14, 0xd3, 0xb4, 0xe1, 0x73, 0x39, 0xfd, - 0x47, 0xf4, 0xe6, 0xdc, 0x4f, 0x62, 0xff, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xa3, 0x36, 0x86, - 0xa6, 0x4a, 0x06, 0x00, 0x00, +func init() { + proto.RegisterFile("grpc_lb_v1/messages/messages.proto", fileDescriptor_messages_b81c731f0e83edbd) +} + +var fileDescriptor_messages_b81c731f0e83edbd = []byte{ + // 731 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x55, 0xdd, 0x4e, 0x1b, 0x39, + 0x14, 0x26, 0x9b, 0x00, 0xc9, 0x09, 0x5a, 0xb2, 0x26, 0x0b, 0x81, 0x05, 0x89, 0x1d, 0x69, 0xd9, + 0x68, 0xc5, 0x4e, 0x04, 0xd9, 0xbd, 0xe8, 0xcf, 0x45, 0x1b, 0x10, 0x0a, 0x2d, 0x17, 0x95, 0x43, + 0x55, 0xa9, 0x52, 0x65, 0x39, 0x19, 0x33, 0x58, 0x38, 0xf6, 0xd4, 0x76, 0x82, 0xfa, 0x08, 0x7d, + 0x94, 0x3e, 0x46, 0xd5, 0x67, 0xe8, 0xfb, 0x54, 0xe3, 0x99, 0xc9, 0x0c, 0x10, 0x40, 0xbd, 0x89, + 0xec, 0xe3, 0xef, 0x7c, 0xdf, 0xf1, 0x89, 0xbf, 0x33, 0xe0, 0x85, 0x3a, 0x1a, 0x11, 0x31, 0x24, + 0xd3, 0x83, 0xce, 0x98, 0x19, 0x43, 0x43, 0x66, 0x66, 0x0b, 0x3f, 0xd2, 0xca, 0x2a, 0x04, 0x31, + 0xc6, 0x17, 0x43, 0x7f, 0x7a, 0xe0, 0x3d, 0x85, 0xea, 0xf1, 0x44, 0x53, 0xcb, 0x95, 0x44, 0x2d, + 0x58, 0x36, 0x6c, 0xa4, 0x64, 0x60, 0x5a, 0xa5, 0xdd, 0x52, 0xbb, 0x8c, 0xb3, 0x2d, 0x6a, 0xc2, + 0xa2, 0xa4, 0x52, 0x99, 0xd6, 0x2f, 0xbb, 0xa5, 0xf6, 0x22, 0x4e, 0x36, 0xde, 0x33, 0xa8, 0x9d, + 0xf3, 0x31, 0x33, 0x96, 0x8e, 0xa3, 0x9f, 0x4e, 0xfe, 0x5a, 0x02, 0x74, 0xa6, 0x68, 0xd0, 0xa3, + 0x82, 0xca, 0x11, 0xc3, 0xec, 0xe3, 0x84, 0x19, 0x8b, 0xde, 0xc0, 0x2a, 0x97, 0xdc, 0x72, 0x2a, + 0x88, 0x4e, 0x42, 0x8e, 0xae, 0x7e, 0xf8, 0x97, 0x9f, 0x57, 0xed, 0x9f, 0x26, 0x90, 0xbb, 0xf9, + 0xfd, 0x05, 0xfc, 0x6b, 0x9a, 0x9f, 0x31, 0x3e, 0x87, 0x95, 0x91, 0xe0, 0x4c, 0x5a, 0x62, 0x2c, + 0xb5, 0x49, 0x15, 0xf5, 0xc3, 0x8d, 0x22, 0xdd, 0x91, 0x3b, 0x1f, 0xc4, 0xc7, 0xfd, 0x05, 0x5c, + 0x1f, 0xe5, 0xdb, 0xde, 0x1f, 0xb0, 0x29, 0x14, 0x0d, 0xc8, 0x30, 0x91, 0xc9, 0x8a, 0x22, 0xf6, + 0x53, 0xc4, 0xbc, 0x0e, 0x6c, 0xde, 0x5b, 0x09, 0x42, 0x50, 0x91, 0x74, 0xcc, 0x5c, 0xf9, 0x35, + 0xec, 0xd6, 0xde, 0xe7, 0x0a, 0xd4, 0x0b, 0x62, 0xa8, 0x0b, 0x35, 0x9b, 0x75, 0x30, 0xbd, 0xe7, + 0xef, 0xc5, 0xc2, 0x66, 0xed, 0xc5, 0x39, 0x0e, 0xfd, 0x03, 0xbf, 0xc9, 0xc9, 0x98, 0x8c, 0xa8, + 0x10, 0x26, 0xbe, 0x93, 0xb6, 0x2c, 0x70, 0xb7, 0x2a, 0xe3, 0x55, 0x39, 0x19, 0x1f, 0xc5, 0xf1, + 0x41, 0x12, 0x46, 0xfb, 0x80, 0x72, 0xec, 0x05, 0x97, 0xdc, 0x5c, 0xb2, 0xa0, 0x55, 0x76, 0xe0, + 0x46, 0x06, 0x3e, 0x49, 0xe3, 0x88, 0x80, 0x7f, 0x17, 0x4d, 0xae, 0xb9, 0xbd, 0x24, 0x81, 0x56, + 0x11, 0xb9, 0x50, 0x9a, 0x68, 0x6a, 0x19, 0x11, 0x7c, 0xcc, 0x2d, 0x97, 0x61, 0xab, 0xe2, 0x98, + 0xfe, 0xbe, 0xcd, 0xf4, 0x8e, 0xdb, 0xcb, 0x63, 0xad, 0xa2, 0x13, 0xa5, 0x31, 0xb5, 0xec, 0x2c, + 0x85, 0x23, 0x0a, 0x9d, 0x47, 0x05, 0x0a, 0xed, 0x8e, 0x15, 0x16, 0x9d, 0x42, 0xfb, 0x01, 0x85, + 0xbc, 0xf7, 0xb1, 0xc4, 0x07, 0xf8, 0xf7, 0x3e, 0x89, 0xf4, 0x19, 0x5c, 0x50, 0x2e, 0x58, 0x40, + 0xac, 0x22, 0x86, 0xc9, 0xa0, 0xb5, 0xe4, 0x04, 0xf6, 0xe6, 0x09, 0x24, 0x7f, 0xd5, 0x89, 0xc3, + 0x9f, 0xab, 0x01, 0x93, 0x01, 0xea, 0xc3, 0x9f, 0x73, 0xe8, 0xaf, 0xa4, 0xba, 0x96, 0x44, 0xb3, + 0x11, 0xe3, 0x53, 0x16, 0xb4, 0x96, 0x1d, 0xe5, 0xce, 0x6d, 0xca, 0xd7, 0x31, 0x0a, 0xa7, 0x20, + 0xef, 0x5b, 0x09, 0xd6, 0x6e, 0x3c, 0x1b, 0x13, 0x29, 0x69, 0x18, 0x1a, 0x40, 0x23, 0x77, 0x40, + 0x12, 0x4b, 0x9f, 0xc6, 0xde, 0x63, 0x16, 0x48, 0xd0, 0xfd, 0x05, 0xbc, 0x3a, 0xf3, 0x40, 0x4a, + 0xfa, 0x04, 0xea, 0x86, 0xe9, 0x29, 0xd3, 0x44, 0x70, 0x63, 0x53, 0x0f, 0xac, 0x17, 0xf9, 0x06, + 0xee, 0xf8, 0x8c, 0x3b, 0x0f, 0x81, 0x99, 0xed, 0x7a, 0xdb, 0xb0, 0x75, 0xcb, 0x01, 0x09, 0x67, + 0x62, 0x81, 0x2f, 0x25, 0xd8, 0xba, 0xbf, 0x14, 0xf4, 0x1f, 0xac, 0x17, 0x93, 0x35, 0x09, 0x98, + 0x60, 0x21, 0xb5, 0x99, 0x2d, 0x9a, 0x22, 0x4f, 0xd2, 0xc7, 0xe9, 0x19, 0x7a, 0x0b, 0xdb, 0x45, + 0xcb, 0x12, 0xcd, 0x22, 0xa5, 0x2d, 0xe1, 0xd2, 0x32, 0x3d, 0xa5, 0x22, 0x2d, 0xbf, 0x59, 0x2c, + 0x3f, 0x1b, 0x62, 0x78, 0xb3, 0xe0, 0x5e, 0xec, 0xf2, 0x4e, 0xd3, 0x34, 0xef, 0x05, 0x40, 0x7e, + 0x4b, 0xb4, 0x1f, 0x0f, 0xac, 0x78, 0x17, 0x0f, 0xac, 0x72, 0xbb, 0x7e, 0x88, 0xee, 0xb6, 0x03, + 0x67, 0x90, 0x57, 0x95, 0x6a, 0xb9, 0x51, 0xf1, 0xbe, 0x97, 0x60, 0x29, 0x39, 0x41, 0x3b, 0x00, + 0x3c, 0x22, 0x34, 0x08, 0x34, 0x33, 0xc9, 0xc8, 0x5b, 0xc1, 0x35, 0x1e, 0xbd, 0x4c, 0x02, 0xb1, + 0xfb, 0x63, 0xed, 0x74, 0xe6, 0xb9, 0x75, 0x6c, 0xc6, 0x1b, 0x9d, 0xb4, 0xea, 0x8a, 0x49, 0x67, + 0xc6, 0x1a, 0x6e, 0x14, 0x1a, 0x71, 0x1e, 0xc7, 0x51, 0x17, 0xd6, 0x1f, 0x30, 0x5d, 0x15, 0xaf, + 0x05, 0x73, 0x0c, 0xf6, 0x3f, 0x6c, 0x3c, 0x64, 0xa4, 0x2a, 0x6e, 0x06, 0x73, 0x4c, 0xd3, 0xeb, + 0xbe, 0x3f, 0x08, 0x95, 0x0a, 0x05, 0xf3, 0x43, 0x25, 0xa8, 0x0c, 0x7d, 0xa5, 0xc3, 0x4e, 0xdc, + 0x0d, 0xf7, 0x23, 0x86, 0x9d, 0x39, 0x5f, 0x95, 0xe1, 0x92, 0xfb, 0x9a, 0x74, 0x7f, 0x04, 0x00, + 0x00, 0xff, 0xff, 0x8e, 0xd0, 0x70, 0xb7, 0x73, 0x06, 0x00, 0x00, } diff --git a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto index 2ed04551fa..42d99c109f 100644 --- a/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto +++ b/vendor/google.golang.org/grpc/grpclb/grpc_lb_v1/messages/messages.proto @@ -15,7 +15,7 @@ syntax = "proto3"; package grpc.lb.v1; -option go_package = "messages"; +option go_package = "google.golang.org/grpc/grpclb/grpc_lb_v1/messages"; message Duration { // Signed seconds of the span of time. Must be from -315,576,000,000 diff --git a/vendor/google.golang.org/grpc/grpclb/grpclb_test.go b/vendor/google.golang.org/grpc/grpclb/grpclb_test.go deleted file mode 100644 index 46c1fe5b9a..0000000000 --- a/vendor/google.golang.org/grpc/grpclb/grpclb_test.go +++ /dev/null @@ -1,891 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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:generate protoc --go_out=plugins=:. grpc_lb_v1/messages/messages.proto -//go:generate protoc --go_out=Mgrpc_lb_v1/messages/messages.proto=google.golang.org/grpc/grpclb/grpc_lb_v1/messages,plugins=grpc:. grpc_lb_v1/service/service.proto - -// Package grpclb_test is currently used only for grpclb testing. -package grpclb_test - -import ( - "errors" - "fmt" - "io" - "net" - "strings" - "sync" - "testing" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - lbmpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" - lbspb "google.golang.org/grpc/grpclb/grpc_lb_v1/service" - _ "google.golang.org/grpc/grpclog/glogger" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/naming" - testpb "google.golang.org/grpc/test/grpc_testing" - "google.golang.org/grpc/test/leakcheck" -) - -var ( - lbsn = "bar.com" - besn = "foo.com" - lbToken = "iamatoken" - - // Resolver replaces localhost with fakeName in Next(). - // Dialer replaces fakeName with localhost when dialing. - // This will test that custom dialer is passed from Dial to grpclb. - fakeName = "fake.Name" -) - -type testWatcher struct { - // the channel to receives name resolution updates - update chan *naming.Update - // the side channel to get to know how many updates in a batch - side chan int - // the channel to notifiy update injector that the update reading is done - readDone chan int -} - -func (w *testWatcher) Next() (updates []*naming.Update, err error) { - n, ok := <-w.side - if !ok { - return nil, fmt.Errorf("w.side is closed") - } - for i := 0; i < n; i++ { - u, ok := <-w.update - if !ok { - break - } - if u != nil { - // Resolver replaces localhost with fakeName in Next(). - // Custom dialer will replace fakeName with localhost when dialing. - u.Addr = strings.Replace(u.Addr, "localhost", fakeName, 1) - updates = append(updates, u) - } - } - w.readDone <- 0 - return -} - -func (w *testWatcher) Close() { - close(w.side) -} - -// Inject naming resolution updates to the testWatcher. -func (w *testWatcher) inject(updates []*naming.Update) { - w.side <- len(updates) - for _, u := range updates { - w.update <- u - } - <-w.readDone -} - -type testNameResolver struct { - w *testWatcher - addrs []string -} - -func (r *testNameResolver) Resolve(target string) (naming.Watcher, error) { - r.w = &testWatcher{ - update: make(chan *naming.Update, len(r.addrs)), - side: make(chan int, 1), - readDone: make(chan int), - } - r.w.side <- len(r.addrs) - for _, addr := range r.addrs { - r.w.update <- &naming.Update{ - Op: naming.Add, - Addr: addr, - Metadata: &naming.AddrMetadataGRPCLB{ - AddrType: naming.GRPCLB, - ServerName: lbsn, - }, - } - } - go func() { - <-r.w.readDone - }() - return r.w, nil -} - -func (r *testNameResolver) inject(updates []*naming.Update) { - if r.w != nil { - r.w.inject(updates) - } -} - -type serverNameCheckCreds struct { - mu sync.Mutex - sn string - expected string -} - -func (c *serverNameCheckCreds) ServerHandshake(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - if _, err := io.WriteString(rawConn, c.sn); err != nil { - fmt.Printf("Failed to write the server name %s to the client %v", c.sn, err) - return nil, nil, err - } - return rawConn, nil, nil -} -func (c *serverNameCheckCreds) ClientHandshake(ctx context.Context, addr string, rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { - c.mu.Lock() - defer c.mu.Unlock() - b := make([]byte, len(c.expected)) - if _, err := rawConn.Read(b); err != nil { - fmt.Printf("Failed to read the server name from the server %v", err) - return nil, nil, err - } - if c.expected != string(b) { - fmt.Printf("Read the server name %s want %s", string(b), c.expected) - return nil, nil, errors.New("received unexpected server name") - } - return rawConn, nil, nil -} -func (c *serverNameCheckCreds) Info() credentials.ProtocolInfo { - c.mu.Lock() - defer c.mu.Unlock() - return credentials.ProtocolInfo{} -} -func (c *serverNameCheckCreds) Clone() credentials.TransportCredentials { - c.mu.Lock() - defer c.mu.Unlock() - return &serverNameCheckCreds{ - expected: c.expected, - } -} -func (c *serverNameCheckCreds) OverrideServerName(s string) error { - c.mu.Lock() - defer c.mu.Unlock() - c.expected = s - return nil -} - -// fakeNameDialer replaces fakeName with localhost when dialing. -// This will test that custom dialer is passed from Dial to grpclb. -func fakeNameDialer(addr string, timeout time.Duration) (net.Conn, error) { - addr = strings.Replace(addr, fakeName, "localhost", 1) - return net.DialTimeout("tcp", addr, timeout) -} - -type remoteBalancer struct { - sls []*lbmpb.ServerList - intervals []time.Duration - statsDura time.Duration - done chan struct{} - mu sync.Mutex - stats lbmpb.ClientStats -} - -func newRemoteBalancer(sls []*lbmpb.ServerList, intervals []time.Duration) *remoteBalancer { - return &remoteBalancer{ - sls: sls, - intervals: intervals, - done: make(chan struct{}), - } -} - -func (b *remoteBalancer) stop() { - close(b.done) -} - -func (b *remoteBalancer) BalanceLoad(stream lbspb.LoadBalancer_BalanceLoadServer) error { - req, err := stream.Recv() - if err != nil { - return err - } - initReq := req.GetInitialRequest() - if initReq.Name != besn { - return grpc.Errorf(codes.InvalidArgument, "invalid service name: %v", initReq.Name) - } - resp := &lbmpb.LoadBalanceResponse{ - LoadBalanceResponseType: &lbmpb.LoadBalanceResponse_InitialResponse{ - InitialResponse: &lbmpb.InitialLoadBalanceResponse{ - ClientStatsReportInterval: &lbmpb.Duration{ - Seconds: int64(b.statsDura.Seconds()), - Nanos: int32(b.statsDura.Nanoseconds() - int64(b.statsDura.Seconds())*1e9), - }, - }, - }, - } - if err := stream.Send(resp); err != nil { - return err - } - go func() { - for { - var ( - req *lbmpb.LoadBalanceRequest - err error - ) - if req, err = stream.Recv(); err != nil { - return - } - b.mu.Lock() - b.stats.NumCallsStarted += req.GetClientStats().NumCallsStarted - b.stats.NumCallsFinished += req.GetClientStats().NumCallsFinished - b.stats.NumCallsFinishedWithDropForRateLimiting += req.GetClientStats().NumCallsFinishedWithDropForRateLimiting - b.stats.NumCallsFinishedWithDropForLoadBalancing += req.GetClientStats().NumCallsFinishedWithDropForLoadBalancing - b.stats.NumCallsFinishedWithClientFailedToSend += req.GetClientStats().NumCallsFinishedWithClientFailedToSend - b.stats.NumCallsFinishedKnownReceived += req.GetClientStats().NumCallsFinishedKnownReceived - b.mu.Unlock() - } - }() - for k, v := range b.sls { - time.Sleep(b.intervals[k]) - resp = &lbmpb.LoadBalanceResponse{ - LoadBalanceResponseType: &lbmpb.LoadBalanceResponse_ServerList{ - ServerList: v, - }, - } - if err := stream.Send(resp); err != nil { - return err - } - } - <-b.done - return nil -} - -type testServer struct { - testpb.TestServiceServer - - addr string -} - -const testmdkey = "testmd" - -func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return nil, grpc.Errorf(codes.Internal, "failed to receive metadata") - } - if md == nil || md["lb-token"][0] != lbToken { - return nil, grpc.Errorf(codes.Internal, "received unexpected metadata: %v", md) - } - grpc.SetTrailer(ctx, metadata.Pairs(testmdkey, s.addr)) - return &testpb.Empty{}, nil -} - -func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - return nil -} - -func startBackends(sn string, lis ...net.Listener) (servers []*grpc.Server) { - for _, l := range lis { - creds := &serverNameCheckCreds{ - sn: sn, - } - s := grpc.NewServer(grpc.Creds(creds)) - testpb.RegisterTestServiceServer(s, &testServer{addr: l.Addr().String()}) - servers = append(servers, s) - go func(s *grpc.Server, l net.Listener) { - s.Serve(l) - }(s, l) - } - return -} - -func stopBackends(servers []*grpc.Server) { - for _, s := range servers { - s.Stop() - } -} - -type testServers struct { - lbAddr string - ls *remoteBalancer - lb *grpc.Server - beIPs []net.IP - bePorts []int -} - -func newLoadBalancer(numberOfBackends int) (tss *testServers, cleanup func(), err error) { - var ( - beListeners []net.Listener - ls *remoteBalancer - lb *grpc.Server - beIPs []net.IP - bePorts []int - ) - for i := 0; i < numberOfBackends; i++ { - // Start a backend. - beLis, e := net.Listen("tcp", "localhost:0") - if e != nil { - err = fmt.Errorf("Failed to listen %v", err) - return - } - beIPs = append(beIPs, beLis.Addr().(*net.TCPAddr).IP) - bePorts = append(bePorts, beLis.Addr().(*net.TCPAddr).Port) - - beListeners = append(beListeners, beLis) - } - backends := startBackends(besn, beListeners...) - - // Start a load balancer. - lbLis, err := net.Listen("tcp", "localhost:0") - if err != nil { - err = fmt.Errorf("Failed to create the listener for the load balancer %v", err) - return - } - lbCreds := &serverNameCheckCreds{ - sn: lbsn, - } - lb = grpc.NewServer(grpc.Creds(lbCreds)) - if err != nil { - err = fmt.Errorf("Failed to generate the port number %v", err) - return - } - ls = newRemoteBalancer(nil, nil) - lbspb.RegisterLoadBalancerServer(lb, ls) - go func() { - lb.Serve(lbLis) - }() - - tss = &testServers{ - lbAddr: lbLis.Addr().String(), - ls: ls, - lb: lb, - beIPs: beIPs, - bePorts: bePorts, - } - cleanup = func() { - defer stopBackends(backends) - defer func() { - ls.stop() - lb.Stop() - }() - } - return -} - -func TestGRPCLB(t *testing.T) { - defer leakcheck.Check(t) - tss, cleanup, err := newLoadBalancer(1) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - - be := &lbmpb.Server{ - IpAddress: tss.beIPs[0], - Port: int32(tss.bePorts[0]), - LoadBalanceToken: lbToken, - } - var bes []*lbmpb.Server - bes = append(bes, be) - sl := &lbmpb.ServerList{ - Servers: bes, - } - tss.ls.sls = []*lbmpb.ServerList{sl} - tss.ls.intervals = []time.Duration{0} - creds := serverNameCheckCreds{ - expected: besn, - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, besn, - grpc.WithBalancer(grpc.NewGRPCLBBalancer(&testNameResolver{addrs: []string{tss.lbAddr}})), - grpc.WithBlock(), grpc.WithTransportCredentials(&creds), grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - testC := testpb.NewTestServiceClient(cc) - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, <nil>", testC, err) - } -} - -func TestDropRequest(t *testing.T) { - defer leakcheck.Check(t) - tss, cleanup, err := newLoadBalancer(2) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - tss.ls.sls = []*lbmpb.ServerList{{ - Servers: []*lbmpb.Server{{ - IpAddress: tss.beIPs[0], - Port: int32(tss.bePorts[0]), - LoadBalanceToken: lbToken, - DropForLoadBalancing: true, - }, { - IpAddress: tss.beIPs[1], - Port: int32(tss.bePorts[1]), - LoadBalanceToken: lbToken, - DropForLoadBalancing: false, - }}, - }} - tss.ls.intervals = []time.Duration{0} - creds := serverNameCheckCreds{ - expected: besn, - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, besn, - grpc.WithBalancer(grpc.NewGRPCLBBalancer(&testNameResolver{addrs: []string{tss.lbAddr}})), - grpc.WithBlock(), grpc.WithTransportCredentials(&creds), grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - testC := testpb.NewTestServiceClient(cc) - // Wait until the first connection is up. - // The first one has Drop set to true, error should contain "drop requests". - for { - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - if strings.Contains(err.Error(), "drops requests") { - break - } - } - } - // The 1st, non-fail-fast RPC should succeed. This ensures both server - // connections are made, because the first one has DropForLoadBalancing set to true. - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.SayHello(_, _) = _, %v, want _, <nil>", testC, err) - } - for i := 0; i < 3; i++ { - // Odd fail-fast RPCs should fail, because the 1st backend has DropForLoadBalancing - // set to true. - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}); grpc.Code(err) != codes.Unavailable { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, %s", testC, err, codes.Unavailable) - } - // Even fail-fast RPCs should succeed since they choose the - // non-drop-request backend according to the round robin policy. - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, <nil>", testC, err) - } - } -} - -func TestDropRequestFailedNonFailFast(t *testing.T) { - defer leakcheck.Check(t) - tss, cleanup, err := newLoadBalancer(1) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - be := &lbmpb.Server{ - IpAddress: tss.beIPs[0], - Port: int32(tss.bePorts[0]), - LoadBalanceToken: lbToken, - DropForLoadBalancing: true, - } - var bes []*lbmpb.Server - bes = append(bes, be) - sl := &lbmpb.ServerList{ - Servers: bes, - } - tss.ls.sls = []*lbmpb.ServerList{sl} - tss.ls.intervals = []time.Duration{0} - creds := serverNameCheckCreds{ - expected: besn, - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, besn, - grpc.WithBalancer(grpc.NewGRPCLBBalancer(&testNameResolver{addrs: []string{tss.lbAddr}})), - grpc.WithBlock(), grpc.WithTransportCredentials(&creds), grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - testC := testpb.NewTestServiceClient(cc) - ctx, cancel = context.WithTimeout(context.Background(), 10*time.Millisecond) - defer cancel() - if _, err := testC.EmptyCall(ctx, &testpb.Empty{}, grpc.FailFast(false)); grpc.Code(err) != codes.DeadlineExceeded { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, %s", testC, err, codes.DeadlineExceeded) - } -} - -// When the balancer in use disconnects, grpclb should connect to the next address from resolved balancer address list. -func TestBalancerDisconnects(t *testing.T) { - defer leakcheck.Check(t) - var ( - lbAddrs []string - lbs []*grpc.Server - ) - for i := 0; i < 3; i++ { - tss, cleanup, err := newLoadBalancer(1) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - - be := &lbmpb.Server{ - IpAddress: tss.beIPs[0], - Port: int32(tss.bePorts[0]), - LoadBalanceToken: lbToken, - } - var bes []*lbmpb.Server - bes = append(bes, be) - sl := &lbmpb.ServerList{ - Servers: bes, - } - tss.ls.sls = []*lbmpb.ServerList{sl} - tss.ls.intervals = []time.Duration{0} - - lbAddrs = append(lbAddrs, tss.lbAddr) - lbs = append(lbs, tss.lb) - } - - creds := serverNameCheckCreds{ - expected: besn, - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - resolver := &testNameResolver{ - addrs: lbAddrs[:2], - } - cc, err := grpc.DialContext(ctx, besn, - grpc.WithBalancer(grpc.NewGRPCLBBalancer(resolver)), - grpc.WithBlock(), grpc.WithTransportCredentials(&creds), grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - testC := testpb.NewTestServiceClient(cc) - var previousTrailer string - trailer := metadata.MD{} - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Trailer(&trailer), grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, <nil>", testC, err) - } else { - previousTrailer = trailer[testmdkey][0] - } - // The initial resolver update contains lbs[0] and lbs[1]. - // When lbs[0] is stopped, lbs[1] should be used. - lbs[0].Stop() - for { - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Trailer(&trailer), grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, <nil>", testC, err) - } else if trailer[testmdkey][0] != previousTrailer { - // A new backend server should receive the request. - // The trailer contains the backend address, so the trailer should be different from the previous one. - previousTrailer = trailer[testmdkey][0] - break - } - time.Sleep(100 * time.Millisecond) - } - // Inject a update to add lbs[2] to resolved addresses. - resolver.inject([]*naming.Update{ - {Op: naming.Add, - Addr: lbAddrs[2], - Metadata: &naming.AddrMetadataGRPCLB{ - AddrType: naming.GRPCLB, - ServerName: lbsn, - }, - }, - }) - // Stop lbs[1]. Now lbs[0] and lbs[1] are all stopped. lbs[2] should be used. - lbs[1].Stop() - for { - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.Trailer(&trailer), grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, <nil>", testC, err) - } else if trailer[testmdkey][0] != previousTrailer { - // A new backend server should receive the request. - // The trailer contains the backend address, so the trailer should be different from the previous one. - break - } - time.Sleep(100 * time.Millisecond) - } -} - -type failPreRPCCred struct{} - -func (failPreRPCCred) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - if strings.Contains(uri[0], "failtosend") { - return nil, fmt.Errorf("rpc should fail to send") - } - return nil, nil -} - -func (failPreRPCCred) RequireTransportSecurity() bool { - return false -} - -func checkStats(stats *lbmpb.ClientStats, expected *lbmpb.ClientStats) error { - if !proto.Equal(stats, expected) { - return fmt.Errorf("stats not equal: got %+v, want %+v", stats, expected) - } - return nil -} - -func runAndGetStats(t *testing.T, dropForLoadBalancing, dropForRateLimiting bool, runRPCs func(*grpc.ClientConn)) lbmpb.ClientStats { - tss, cleanup, err := newLoadBalancer(3) - if err != nil { - t.Fatalf("failed to create new load balancer: %v", err) - } - defer cleanup() - tss.ls.sls = []*lbmpb.ServerList{{ - Servers: []*lbmpb.Server{{ - IpAddress: tss.beIPs[2], - Port: int32(tss.bePorts[2]), - LoadBalanceToken: lbToken, - DropForLoadBalancing: dropForLoadBalancing, - DropForRateLimiting: dropForRateLimiting, - }}, - }} - tss.ls.intervals = []time.Duration{0} - tss.ls.statsDura = 100 * time.Millisecond - creds := serverNameCheckCreds{expected: besn} - - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - cc, err := grpc.DialContext(ctx, besn, - grpc.WithBalancer(grpc.NewGRPCLBBalancer(&testNameResolver{addrs: []string{tss.lbAddr}})), - grpc.WithTransportCredentials(&creds), grpc.WithPerRPCCredentials(failPreRPCCred{}), - grpc.WithBlock(), grpc.WithDialer(fakeNameDialer)) - if err != nil { - t.Fatalf("Failed to dial to the backend %v", err) - } - defer cc.Close() - - runRPCs(cc) - time.Sleep(1 * time.Second) - tss.ls.mu.Lock() - stats := tss.ls.stats - tss.ls.mu.Unlock() - return stats -} - -const countRPC = 40 - -func TestGRPCLBStatsUnarySuccess(t *testing.T) { - defer leakcheck.Check(t) - stats := runAndGetStats(t, false, false, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - // The first non-failfast RPC succeeds, all connections are up. - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, <nil>", testC, err) - } - for i := 0; i < countRPC-1; i++ { - testC.EmptyCall(context.Background(), &testpb.Empty{}) - } - }) - - if err := checkStats(&stats, &lbmpb.ClientStats{ - NumCallsStarted: int64(countRPC), - NumCallsFinished: int64(countRPC), - NumCallsFinishedKnownReceived: int64(countRPC), - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsUnaryDropLoadBalancing(t *testing.T) { - defer leakcheck.Check(t) - c := 0 - stats := runAndGetStats(t, true, false, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - for { - c++ - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - if strings.Contains(err.Error(), "drops requests") { - break - } - } - } - for i := 0; i < countRPC; i++ { - testC.EmptyCall(context.Background(), &testpb.Empty{}) - } - }) - - if err := checkStats(&stats, &lbmpb.ClientStats{ - NumCallsStarted: int64(countRPC + c), - NumCallsFinished: int64(countRPC + c), - NumCallsFinishedWithDropForLoadBalancing: int64(countRPC + 1), - NumCallsFinishedWithClientFailedToSend: int64(c - 1), - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsUnaryDropRateLimiting(t *testing.T) { - defer leakcheck.Check(t) - c := 0 - stats := runAndGetStats(t, false, true, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - for { - c++ - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - if strings.Contains(err.Error(), "drops requests") { - break - } - } - } - for i := 0; i < countRPC; i++ { - testC.EmptyCall(context.Background(), &testpb.Empty{}) - } - }) - - if err := checkStats(&stats, &lbmpb.ClientStats{ - NumCallsStarted: int64(countRPC + c), - NumCallsFinished: int64(countRPC + c), - NumCallsFinishedWithDropForRateLimiting: int64(countRPC + 1), - NumCallsFinishedWithClientFailedToSend: int64(c - 1), - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsUnaryFailedToSend(t *testing.T) { - defer leakcheck.Check(t) - stats := runAndGetStats(t, false, false, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - // The first non-failfast RPC succeeds, all connections are up. - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}, grpc.FailFast(false)); err != nil { - t.Fatalf("%v.EmptyCall(_, _) = _, %v, want _, <nil>", testC, err) - } - for i := 0; i < countRPC-1; i++ { - grpc.Invoke(context.Background(), "failtosend", &testpb.Empty{}, nil, cc) - } - }) - - if err := checkStats(&stats, &lbmpb.ClientStats{ - NumCallsStarted: int64(countRPC), - NumCallsFinished: int64(countRPC), - NumCallsFinishedWithClientFailedToSend: int64(countRPC - 1), - NumCallsFinishedKnownReceived: 1, - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsStreamingSuccess(t *testing.T) { - defer leakcheck.Check(t) - stats := runAndGetStats(t, false, false, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - // The first non-failfast RPC succeeds, all connections are up. - stream, err := testC.FullDuplexCall(context.Background(), grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_, _) = _, %v, want _, <nil>", testC, err) - } - for { - if _, err = stream.Recv(); err == io.EOF { - break - } - } - for i := 0; i < countRPC-1; i++ { - stream, err = testC.FullDuplexCall(context.Background()) - if err == nil { - // Wait for stream to end if err is nil. - for { - if _, err = stream.Recv(); err == io.EOF { - break - } - } - } - } - }) - - if err := checkStats(&stats, &lbmpb.ClientStats{ - NumCallsStarted: int64(countRPC), - NumCallsFinished: int64(countRPC), - NumCallsFinishedKnownReceived: int64(countRPC), - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsStreamingDropLoadBalancing(t *testing.T) { - defer leakcheck.Check(t) - c := 0 - stats := runAndGetStats(t, true, false, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - for { - c++ - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - if strings.Contains(err.Error(), "drops requests") { - break - } - } - } - for i := 0; i < countRPC; i++ { - testC.FullDuplexCall(context.Background()) - } - }) - - if err := checkStats(&stats, &lbmpb.ClientStats{ - NumCallsStarted: int64(countRPC + c), - NumCallsFinished: int64(countRPC + c), - NumCallsFinishedWithDropForLoadBalancing: int64(countRPC + 1), - NumCallsFinishedWithClientFailedToSend: int64(c - 1), - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsStreamingDropRateLimiting(t *testing.T) { - defer leakcheck.Check(t) - c := 0 - stats := runAndGetStats(t, false, true, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - for { - c++ - if _, err := testC.EmptyCall(context.Background(), &testpb.Empty{}); err != nil { - if strings.Contains(err.Error(), "drops requests") { - break - } - } - } - for i := 0; i < countRPC; i++ { - testC.FullDuplexCall(context.Background()) - } - }) - - if err := checkStats(&stats, &lbmpb.ClientStats{ - NumCallsStarted: int64(countRPC + c), - NumCallsFinished: int64(countRPC + c), - NumCallsFinishedWithDropForRateLimiting: int64(countRPC + 1), - NumCallsFinishedWithClientFailedToSend: int64(c - 1), - }); err != nil { - t.Fatal(err) - } -} - -func TestGRPCLBStatsStreamingFailedToSend(t *testing.T) { - defer leakcheck.Check(t) - stats := runAndGetStats(t, false, false, func(cc *grpc.ClientConn) { - testC := testpb.NewTestServiceClient(cc) - // The first non-failfast RPC succeeds, all connections are up. - stream, err := testC.FullDuplexCall(context.Background(), grpc.FailFast(false)) - if err != nil { - t.Fatalf("%v.FullDuplexCall(_, _) = _, %v, want _, <nil>", testC, err) - } - for { - if _, err = stream.Recv(); err == io.EOF { - break - } - } - for i := 0; i < countRPC-1; i++ { - grpc.NewClientStream(context.Background(), &grpc.StreamDesc{}, cc, "failtosend") - } - }) - - if err := checkStats(&stats, &lbmpb.ClientStats{ - NumCallsStarted: int64(countRPC), - NumCallsFinished: int64(countRPC), - NumCallsFinishedWithClientFailedToSend: int64(countRPC - 1), - NumCallsFinishedKnownReceived: 1, - }); err != nil { - t.Fatal(err) - } -} diff --git a/vendor/google.golang.org/grpc/grpclb_picker.go b/vendor/google.golang.org/grpc/grpclb_picker.go new file mode 100644 index 0000000000..872c7ccea0 --- /dev/null +++ b/vendor/google.golang.org/grpc/grpclb_picker.go @@ -0,0 +1,159 @@ +/* + * + * Copyright 2017 gRPC 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 grpc + +import ( + "sync" + "sync/atomic" + + "golang.org/x/net/context" + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/codes" + lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" + "google.golang.org/grpc/status" +) + +type rpcStats struct { + NumCallsStarted int64 + NumCallsFinished int64 + NumCallsFinishedWithDropForRateLimiting int64 + NumCallsFinishedWithDropForLoadBalancing int64 + NumCallsFinishedWithClientFailedToSend int64 + NumCallsFinishedKnownReceived int64 +} + +// toClientStats converts rpcStats to lbpb.ClientStats, and clears rpcStats. +func (s *rpcStats) toClientStats() *lbpb.ClientStats { + stats := &lbpb.ClientStats{ + NumCallsStarted: atomic.SwapInt64(&s.NumCallsStarted, 0), + NumCallsFinished: atomic.SwapInt64(&s.NumCallsFinished, 0), + NumCallsFinishedWithDropForRateLimiting: atomic.SwapInt64(&s.NumCallsFinishedWithDropForRateLimiting, 0), + NumCallsFinishedWithDropForLoadBalancing: atomic.SwapInt64(&s.NumCallsFinishedWithDropForLoadBalancing, 0), + NumCallsFinishedWithClientFailedToSend: atomic.SwapInt64(&s.NumCallsFinishedWithClientFailedToSend, 0), + NumCallsFinishedKnownReceived: atomic.SwapInt64(&s.NumCallsFinishedKnownReceived, 0), + } + return stats +} + +func (s *rpcStats) dropForRateLimiting() { + atomic.AddInt64(&s.NumCallsStarted, 1) + atomic.AddInt64(&s.NumCallsFinishedWithDropForRateLimiting, 1) + atomic.AddInt64(&s.NumCallsFinished, 1) +} + +func (s *rpcStats) dropForLoadBalancing() { + atomic.AddInt64(&s.NumCallsStarted, 1) + atomic.AddInt64(&s.NumCallsFinishedWithDropForLoadBalancing, 1) + atomic.AddInt64(&s.NumCallsFinished, 1) +} + +func (s *rpcStats) failedToSend() { + atomic.AddInt64(&s.NumCallsStarted, 1) + atomic.AddInt64(&s.NumCallsFinishedWithClientFailedToSend, 1) + atomic.AddInt64(&s.NumCallsFinished, 1) +} + +func (s *rpcStats) knownReceived() { + atomic.AddInt64(&s.NumCallsStarted, 1) + atomic.AddInt64(&s.NumCallsFinishedKnownReceived, 1) + atomic.AddInt64(&s.NumCallsFinished, 1) +} + +type errPicker struct { + // Pick always returns this err. + err error +} + +func (p *errPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { + return nil, nil, p.err +} + +// rrPicker does roundrobin on subConns. It's typically used when there's no +// response from remote balancer, and grpclb falls back to the resolved +// backends. +// +// It guaranteed that len(subConns) > 0. +type rrPicker struct { + mu sync.Mutex + subConns []balancer.SubConn // The subConns that were READY when taking the snapshot. + subConnsNext int +} + +func (p *rrPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { + p.mu.Lock() + defer p.mu.Unlock() + sc := p.subConns[p.subConnsNext] + p.subConnsNext = (p.subConnsNext + 1) % len(p.subConns) + return sc, nil, nil +} + +// lbPicker does two layers of picks: +// +// First layer: roundrobin on all servers in serverList, including drops and backends. +// - If it picks a drop, the RPC will fail as being dropped. +// - If it picks a backend, do a second layer pick to pick the real backend. +// +// Second layer: roundrobin on all READY backends. +// +// It's guaranteed that len(serverList) > 0. +type lbPicker struct { + mu sync.Mutex + serverList []*lbpb.Server + serverListNext int + subConns []balancer.SubConn // The subConns that were READY when taking the snapshot. + subConnsNext int + + stats *rpcStats +} + +func (p *lbPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { + p.mu.Lock() + defer p.mu.Unlock() + + // Layer one roundrobin on serverList. + s := p.serverList[p.serverListNext] + p.serverListNext = (p.serverListNext + 1) % len(p.serverList) + + // If it's a drop, return an error and fail the RPC. + if s.DropForRateLimiting { + p.stats.dropForRateLimiting() + return nil, nil, status.Errorf(codes.Unavailable, "request dropped by grpclb") + } + if s.DropForLoadBalancing { + p.stats.dropForLoadBalancing() + return nil, nil, status.Errorf(codes.Unavailable, "request dropped by grpclb") + } + + // If not a drop but there's no ready subConns. + if len(p.subConns) <= 0 { + return nil, nil, balancer.ErrNoSubConnAvailable + } + + // Return the next ready subConn in the list, also collect rpc stats. + sc := p.subConns[p.subConnsNext] + p.subConnsNext = (p.subConnsNext + 1) % len(p.subConns) + done := func(info balancer.DoneInfo) { + if !info.BytesSent { + p.stats.failedToSend() + } else if info.BytesReceived { + p.stats.knownReceived() + } + } + return sc, done, nil +} diff --git a/vendor/google.golang.org/grpc/grpclb_remote_balancer.go b/vendor/google.golang.org/grpc/grpclb_remote_balancer.go new file mode 100644 index 0000000000..b8dd4f18ce --- /dev/null +++ b/vendor/google.golang.org/grpc/grpclb_remote_balancer.go @@ -0,0 +1,266 @@ +/* + * + * Copyright 2017 gRPC 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 grpc + +import ( + "fmt" + "net" + "reflect" + "time" + + "golang.org/x/net/context" + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/channelz" + + "google.golang.org/grpc/connectivity" + lbpb "google.golang.org/grpc/grpclb/grpc_lb_v1/messages" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/resolver" +) + +// processServerList updates balaner's internal state, create/remove SubConns +// and regenerates picker using the received serverList. +func (lb *lbBalancer) processServerList(l *lbpb.ServerList) { + grpclog.Infof("lbBalancer: processing server list: %+v", l) + lb.mu.Lock() + defer lb.mu.Unlock() + + // Set serverListReceived to true so fallback will not take effect if it has + // not hit timeout. + lb.serverListReceived = true + + // If the new server list == old server list, do nothing. + if reflect.DeepEqual(lb.fullServerList, l.Servers) { + grpclog.Infof("lbBalancer: new serverlist same as the previous one, ignoring") + return + } + lb.fullServerList = l.Servers + + var backendAddrs []resolver.Address + for _, s := range l.Servers { + if s.DropForLoadBalancing || s.DropForRateLimiting { + continue + } + + md := metadata.Pairs(lbTokeyKey, s.LoadBalanceToken) + ip := net.IP(s.IpAddress) + ipStr := ip.String() + if ip.To4() == nil { + // Add square brackets to ipv6 addresses, otherwise net.Dial() and + // net.SplitHostPort() will return too many colons error. + ipStr = fmt.Sprintf("[%s]", ipStr) + } + addr := resolver.Address{ + Addr: fmt.Sprintf("%s:%d", ipStr, s.Port), + Metadata: &md, + } + + backendAddrs = append(backendAddrs, addr) + } + + // Call refreshSubConns to create/remove SubConns. + lb.refreshSubConns(backendAddrs) + // Regenerate and update picker no matter if there's update on backends (if + // any SubConn will be newed/removed). Because since the full serverList was + // different, there might be updates in drops or pick weights(different + // number of duplicates). We need to update picker with the fulllist. + // + // Now with cache, even if SubConn was newed/removed, there might be no + // state changes. + lb.regeneratePicker() + lb.cc.UpdateBalancerState(lb.state, lb.picker) +} + +// refreshSubConns creates/removes SubConns with backendAddrs. It returns a bool +// indicating whether the backendAddrs are different from the cached +// backendAddrs (whether any SubConn was newed/removed). +// Caller must hold lb.mu. +func (lb *lbBalancer) refreshSubConns(backendAddrs []resolver.Address) bool { + lb.backendAddrs = nil + var backendsUpdated bool + // addrsSet is the set converted from backendAddrs, it's used to quick + // lookup for an address. + addrsSet := make(map[resolver.Address]struct{}) + // Create new SubConns. + for _, addr := range backendAddrs { + addrWithoutMD := addr + addrWithoutMD.Metadata = nil + addrsSet[addrWithoutMD] = struct{}{} + lb.backendAddrs = append(lb.backendAddrs, addrWithoutMD) + + if _, ok := lb.subConns[addrWithoutMD]; !ok { + backendsUpdated = true + + // Use addrWithMD to create the SubConn. + sc, err := lb.cc.NewSubConn([]resolver.Address{addr}, balancer.NewSubConnOptions{}) + if err != nil { + grpclog.Warningf("roundrobinBalancer: failed to create new SubConn: %v", err) + continue + } + lb.subConns[addrWithoutMD] = sc // Use the addr without MD as key for the map. + if _, ok := lb.scStates[sc]; !ok { + // Only set state of new sc to IDLE. The state could already be + // READY for cached SubConns. + lb.scStates[sc] = connectivity.Idle + } + sc.Connect() + } + } + + for a, sc := range lb.subConns { + // a was removed by resolver. + if _, ok := addrsSet[a]; !ok { + backendsUpdated = true + + lb.cc.RemoveSubConn(sc) + delete(lb.subConns, a) + // Keep the state of this sc in b.scStates until sc's state becomes Shutdown. + // The entry will be deleted in HandleSubConnStateChange. + } + } + + return backendsUpdated +} + +func (lb *lbBalancer) readServerList(s *balanceLoadClientStream) error { + for { + reply, err := s.Recv() + if err != nil { + return fmt.Errorf("grpclb: failed to recv server list: %v", err) + } + if serverList := reply.GetServerList(); serverList != nil { + lb.processServerList(serverList) + } + } +} + +func (lb *lbBalancer) sendLoadReport(s *balanceLoadClientStream, interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + case <-s.Context().Done(): + return + } + stats := lb.clientStats.toClientStats() + t := time.Now() + stats.Timestamp = &lbpb.Timestamp{ + Seconds: t.Unix(), + Nanos: int32(t.Nanosecond()), + } + if err := s.Send(&lbpb.LoadBalanceRequest{ + LoadBalanceRequestType: &lbpb.LoadBalanceRequest_ClientStats{ + ClientStats: stats, + }, + }); err != nil { + return + } + } +} + +func (lb *lbBalancer) callRemoteBalancer() error { + lbClient := &loadBalancerClient{cc: lb.ccRemoteLB} + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + stream, err := lbClient.BalanceLoad(ctx, FailFast(false)) + if err != nil { + return fmt.Errorf("grpclb: failed to perform RPC to the remote balancer %v", err) + } + + // grpclb handshake on the stream. + initReq := &lbpb.LoadBalanceRequest{ + LoadBalanceRequestType: &lbpb.LoadBalanceRequest_InitialRequest{ + InitialRequest: &lbpb.InitialLoadBalanceRequest{ + Name: lb.target, + }, + }, + } + if err := stream.Send(initReq); err != nil { + return fmt.Errorf("grpclb: failed to send init request: %v", err) + } + reply, err := stream.Recv() + if err != nil { + return fmt.Errorf("grpclb: failed to recv init response: %v", err) + } + initResp := reply.GetInitialResponse() + if initResp == nil { + return fmt.Errorf("grpclb: reply from remote balancer did not include initial response") + } + if initResp.LoadBalancerDelegate != "" { + return fmt.Errorf("grpclb: Delegation is not supported") + } + + go func() { + if d := convertDuration(initResp.ClientStatsReportInterval); d > 0 { + lb.sendLoadReport(stream, d) + } + }() + return lb.readServerList(stream) +} + +func (lb *lbBalancer) watchRemoteBalancer() { + for { + err := lb.callRemoteBalancer() + select { + case <-lb.doneCh: + return + default: + if err != nil { + grpclog.Error(err) + } + } + + } +} + +func (lb *lbBalancer) dialRemoteLB(remoteLBName string) { + var dopts []DialOption + if creds := lb.opt.DialCreds; creds != nil { + if err := creds.OverrideServerName(remoteLBName); err == nil { + dopts = append(dopts, WithTransportCredentials(creds)) + } else { + grpclog.Warningf("grpclb: failed to override the server name in the credentials: %v, using Insecure", err) + dopts = append(dopts, WithInsecure()) + } + } else { + dopts = append(dopts, WithInsecure()) + } + if lb.opt.Dialer != nil { + // WithDialer takes a different type of function, so we instead use a + // special DialOption here. + dopts = append(dopts, withContextDialer(lb.opt.Dialer)) + } + // Explicitly set pickfirst as the balancer. + dopts = append(dopts, WithBalancerName(PickFirstBalancerName)) + dopts = append(dopts, withResolverBuilder(lb.manualResolver)) + if channelz.IsOn() { + dopts = append(dopts, WithChannelzParentID(lb.opt.ChannelzParentID)) + } + + // DialContext using manualResolver.Scheme, which is a random scheme generated + // when init grpclb. The target name is not important. + cc, err := DialContext(context.Background(), "grpclb:///grpclb.server", dopts...) + if err != nil { + grpclog.Fatalf("failed to dial: %v", err) + } + lb.ccRemoteLB = cc + go lb.watchRemoteBalancer() +} diff --git a/vendor/google.golang.org/grpc/grpclb_util.go b/vendor/google.golang.org/grpc/grpclb_util.go new file mode 100644 index 0000000000..063ba9d859 --- /dev/null +++ b/vendor/google.golang.org/grpc/grpclb_util.go @@ -0,0 +1,214 @@ +/* + * + * Copyright 2016 gRPC 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 grpc + +import ( + "fmt" + "sync" + "time" + + "google.golang.org/grpc/balancer" + "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/resolver" +) + +// The parent ClientConn should re-resolve when grpclb loses connection to the +// remote balancer. When the ClientConn inside grpclb gets a TransientFailure, +// it calls lbManualResolver.ResolveNow(), which calls parent ClientConn's +// ResolveNow, and eventually results in re-resolve happening in parent +// ClientConn's resolver (DNS for example). +// +// parent +// ClientConn +// +-----------------------------------------------------------------+ +// | parent +---------------------------------+ | +// | DNS ClientConn | grpclb | | +// | resolver balancerWrapper | | | +// | + + | grpclb grpclb | | +// | | | | ManualResolver ClientConn | | +// | | | | + + | | +// | | | | | | Transient | | +// | | | | | | Failure | | +// | | | | | <--------- | | | +// | | | <--------------- | ResolveNow | | | +// | | <--------- | ResolveNow | | | | | +// | | ResolveNow | | | | | | +// | | | | | | | | +// | + + | + + | | +// | +---------------------------------+ | +// +-----------------------------------------------------------------+ + +// lbManualResolver is used by the ClientConn inside grpclb. It's a manual +// resolver with a special ResolveNow() function. +// +// When ResolveNow() is called, it calls ResolveNow() on the parent ClientConn, +// so when grpclb client lose contact with remote balancers, the parent +// ClientConn's resolver will re-resolve. +type lbManualResolver struct { + scheme string + ccr resolver.ClientConn + + ccb balancer.ClientConn +} + +func (r *lbManualResolver) Build(_ resolver.Target, cc resolver.ClientConn, _ resolver.BuildOption) (resolver.Resolver, error) { + r.ccr = cc + return r, nil +} + +func (r *lbManualResolver) Scheme() string { + return r.scheme +} + +// ResolveNow calls resolveNow on the parent ClientConn. +func (r *lbManualResolver) ResolveNow(o resolver.ResolveNowOption) { + r.ccb.ResolveNow(o) +} + +// Close is a noop for Resolver. +func (*lbManualResolver) Close() {} + +// NewAddress calls cc.NewAddress. +func (r *lbManualResolver) NewAddress(addrs []resolver.Address) { + r.ccr.NewAddress(addrs) +} + +// NewServiceConfig calls cc.NewServiceConfig. +func (r *lbManualResolver) NewServiceConfig(sc string) { + r.ccr.NewServiceConfig(sc) +} + +const subConnCacheTime = time.Second * 10 + +// lbCacheClientConn is a wrapper balancer.ClientConn with a SubConn cache. +// SubConns will be kept in cache for subConnCacheTime before being removed. +// +// Its new and remove methods are updated to do cache first. +type lbCacheClientConn struct { + cc balancer.ClientConn + timeout time.Duration + + mu sync.Mutex + // subConnCache only keeps subConns that are being deleted. + subConnCache map[resolver.Address]*subConnCacheEntry + subConnToAddr map[balancer.SubConn]resolver.Address +} + +type subConnCacheEntry struct { + sc balancer.SubConn + + cancel func() + abortDeleting bool +} + +func newLBCacheClientConn(cc balancer.ClientConn) *lbCacheClientConn { + return &lbCacheClientConn{ + cc: cc, + timeout: subConnCacheTime, + subConnCache: make(map[resolver.Address]*subConnCacheEntry), + subConnToAddr: make(map[balancer.SubConn]resolver.Address), + } +} + +func (ccc *lbCacheClientConn) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { + if len(addrs) != 1 { + return nil, fmt.Errorf("grpclb calling NewSubConn with addrs of length %v", len(addrs)) + } + addrWithoutMD := addrs[0] + addrWithoutMD.Metadata = nil + + ccc.mu.Lock() + defer ccc.mu.Unlock() + if entry, ok := ccc.subConnCache[addrWithoutMD]; ok { + // If entry is in subConnCache, the SubConn was being deleted. + // cancel function will never be nil. + entry.cancel() + delete(ccc.subConnCache, addrWithoutMD) + return entry.sc, nil + } + + scNew, err := ccc.cc.NewSubConn(addrs, opts) + if err != nil { + return nil, err + } + + ccc.subConnToAddr[scNew] = addrWithoutMD + return scNew, nil +} + +func (ccc *lbCacheClientConn) RemoveSubConn(sc balancer.SubConn) { + ccc.mu.Lock() + defer ccc.mu.Unlock() + addr, ok := ccc.subConnToAddr[sc] + if !ok { + return + } + + if entry, ok := ccc.subConnCache[addr]; ok { + if entry.sc != sc { + // This could happen if NewSubConn was called multiple times for the + // same address, and those SubConns are all removed. We remove sc + // immediately here. + delete(ccc.subConnToAddr, sc) + ccc.cc.RemoveSubConn(sc) + } + return + } + + entry := &subConnCacheEntry{ + sc: sc, + } + ccc.subConnCache[addr] = entry + + timer := time.AfterFunc(ccc.timeout, func() { + ccc.mu.Lock() + if entry.abortDeleting { + return + } + ccc.cc.RemoveSubConn(sc) + delete(ccc.subConnToAddr, sc) + delete(ccc.subConnCache, addr) + ccc.mu.Unlock() + }) + entry.cancel = func() { + if !timer.Stop() { + // If stop was not successful, the timer has fired (this can only + // happen in a race). But the deleting function is blocked on ccc.mu + // because the mutex was held by the caller of this function. + // + // Set abortDeleting to true to abort the deleting function. When + // the lock is released, the deleting function will acquire the + // lock, check the value of abortDeleting and return. + entry.abortDeleting = true + } + } +} + +func (ccc *lbCacheClientConn) UpdateBalancerState(s connectivity.State, p balancer.Picker) { + ccc.cc.UpdateBalancerState(s, p) +} + +func (ccc *lbCacheClientConn) close() { + ccc.mu.Lock() + // Only cancel all existing timers. There's no need to remove SubConns. + for _, entry := range ccc.subConnCache { + entry.cancel() + } + ccc.mu.Unlock() +} diff --git a/vendor/google.golang.org/grpc/grpclog/grpclog.go b/vendor/google.golang.org/grpc/grpclog/grpclog.go index 16a7d88867..1fabb11e1b 100644 --- a/vendor/google.golang.org/grpc/grpclog/grpclog.go +++ b/vendor/google.golang.org/grpc/grpclog/grpclog.go @@ -105,18 +105,21 @@ func Fatalln(args ...interface{}) { } // Print prints to the logger. Arguments are handled in the manner of fmt.Print. +// // Deprecated: use Info. func Print(args ...interface{}) { logger.Info(args...) } // Printf prints to the logger. Arguments are handled in the manner of fmt.Printf. +// // Deprecated: use Infof. func Printf(format string, args ...interface{}) { logger.Infof(format, args...) } // Println prints to the logger. Arguments are handled in the manner of fmt.Println. +// // Deprecated: use Infoln. func Println(args ...interface{}) { logger.Infoln(args...) diff --git a/vendor/google.golang.org/grpc/grpclog/logger.go b/vendor/google.golang.org/grpc/grpclog/logger.go index d03b2397bf..097494f710 100644 --- a/vendor/google.golang.org/grpc/grpclog/logger.go +++ b/vendor/google.golang.org/grpc/grpclog/logger.go @@ -19,6 +19,7 @@ package grpclog // Logger mimics golang's standard Logger as an interface. +// // Deprecated: use LoggerV2. type Logger interface { Fatal(args ...interface{}) @@ -31,6 +32,7 @@ type Logger interface { // SetLogger sets the logger that is used in grpc. Call only from // init() functions. +// // Deprecated: use SetLoggerV2. func SetLogger(l Logger) { logger = &loggerWrapper{Logger: l} diff --git a/vendor/google.golang.org/grpc/grpclog/loggerv2_test.go b/vendor/google.golang.org/grpc/grpclog/loggerv2_test.go deleted file mode 100644 index 756f215f9c..0000000000 --- a/vendor/google.golang.org/grpc/grpclog/loggerv2_test.go +++ /dev/null @@ -1,62 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpclog - -import ( - "bytes" - "fmt" - "regexp" - "testing" -) - -func TestLoggerV2Severity(t *testing.T) { - buffers := []*bytes.Buffer{new(bytes.Buffer), new(bytes.Buffer), new(bytes.Buffer)} - SetLoggerV2(NewLoggerV2(buffers[infoLog], buffers[warningLog], buffers[errorLog])) - - Info(severityName[infoLog]) - Warning(severityName[warningLog]) - Error(severityName[errorLog]) - - for i := 0; i < fatalLog; i++ { - buf := buffers[i] - // The content of info buffer should be something like: - // INFO: 2017/04/07 14:55:42 INFO - // WARNING: 2017/04/07 14:55:42 WARNING - // ERROR: 2017/04/07 14:55:42 ERROR - for j := i; j < fatalLog; j++ { - b, err := buf.ReadBytes('\n') - if err != nil { - t.Fatal(err) - } - if err := checkLogForSeverity(j, b); err != nil { - t.Fatal(err) - } - } - } -} - -// check if b is in the format of: -// WARNING: 2017/04/07 14:55:42 WARNING -func checkLogForSeverity(s int, b []byte) error { - expected := regexp.MustCompile(fmt.Sprintf(`^%s: [0-9]{4}/[0-9]{2}/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} %s\n$`, severityName[s], severityName[s])) - if m := expected.Match(b); !m { - return fmt.Errorf("got: %v, want string in format of: %v", string(b), severityName[s]+": 2016/10/05 17:09:26 "+severityName[s]) - } - return nil -} diff --git a/vendor/google.golang.org/grpc/interceptor.go b/vendor/google.golang.org/grpc/interceptor.go index 06dc825b9f..1f6ef67803 100644 --- a/vendor/google.golang.org/grpc/interceptor.go +++ b/vendor/google.golang.org/grpc/interceptor.go @@ -48,7 +48,9 @@ type UnaryServerInfo struct { } // UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal -// execution of a unary RPC. +// execution of a unary RPC. If a UnaryHandler returns an error, it should be produced by the +// status package, or else gRPC will use codes.Unknown as the status code and err.Error() as +// the status message of the RPC. type UnaryHandler func(ctx context.Context, req interface{}) (interface{}, error) // UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info diff --git a/vendor/google.golang.org/grpc/internal/internal.go b/vendor/google.golang.org/grpc/internal/internal.go index 07083832c3..53f1775201 100644 --- a/vendor/google.golang.org/grpc/internal/internal.go +++ b/vendor/google.golang.org/grpc/internal/internal.go @@ -19,13 +19,6 @@ // the godoc of the top-level grpc package. package internal -// TestingCloseConns closes all existing transports but keeps -// grpcServer.lis accepting new connections. -// -// The provided grpcServer must be of type *grpc.Server. It is untyped -// for circular dependency reasons. -var TestingCloseConns func(grpcServer interface{}) - // TestingUseHandlerImpl enables the http.Handler-based server implementation. // It must be called before Serve and requires TLS credentials. // diff --git a/vendor/google.golang.org/grpc/metadata/metadata.go b/vendor/google.golang.org/grpc/metadata/metadata.go index ccfea5d453..bd2eaf4083 100644 --- a/vendor/google.golang.org/grpc/metadata/metadata.go +++ b/vendor/google.golang.org/grpc/metadata/metadata.go @@ -17,7 +17,8 @@ */ // Package metadata define the structure of the metadata supported by gRPC library. -// Please refer to https://grpc.io/docs/guides/wire.html for more information about custom-metadata. +// Please refer to https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md +// for more information about custom-metadata. package metadata // import "google.golang.org/grpc/metadata" import ( @@ -27,7 +28,9 @@ import ( "golang.org/x/net/context" ) -// DecodeKeyValue returns k, v, nil. It is deprecated and should not be used. +// DecodeKeyValue returns k, v, nil. +// +// Deprecated: use k and v directly instead. func DecodeKeyValue(k, v string) (string, string, error) { return k, v, nil } @@ -94,6 +97,30 @@ func (md MD) Copy() MD { return Join(md) } +// Get obtains the values for a given key. +func (md MD) Get(k string) []string { + k = strings.ToLower(k) + return md[k] +} + +// Set sets the value of a given key with a slice of values. +func (md MD) Set(k string, vals ...string) { + if len(vals) == 0 { + return + } + k = strings.ToLower(k) + md[k] = vals +} + +// Append adds the values to key k, not overwriting what was already stored at that key. +func (md MD) Append(k string, vals ...string) { + if len(vals) == 0 { + return + } + k = strings.ToLower(k) + md[k] = append(md[k], vals...) +} + // Join joins any number of mds into a single MD. // The order of values for each key is determined by the order in which // the mds containing those values are presented to Join. @@ -115,9 +142,26 @@ func NewIncomingContext(ctx context.Context, md MD) context.Context { return context.WithValue(ctx, mdIncomingKey{}, md) } -// NewOutgoingContext creates a new context with outgoing md attached. +// NewOutgoingContext creates a new context with outgoing md attached. If used +// in conjunction with AppendToOutgoingContext, NewOutgoingContext will +// overwrite any previously-appended metadata. func NewOutgoingContext(ctx context.Context, md MD) context.Context { - return context.WithValue(ctx, mdOutgoingKey{}, md) + return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md}) +} + +// AppendToOutgoingContext returns a new context with the provided kv merged +// with any existing metadata in the context. Please refer to the +// documentation of Pairs for a description of kv. +func AppendToOutgoingContext(ctx context.Context, kv ...string) context.Context { + if len(kv)%2 == 1 { + panic(fmt.Sprintf("metadata: AppendToOutgoingContext got an odd number of input pairs for metadata: %d", len(kv))) + } + md, _ := ctx.Value(mdOutgoingKey{}).(rawMD) + added := make([][]string, len(md.added)+1) + copy(added, md.added) + added[len(added)-1] = make([]string, len(kv)) + copy(added[len(added)-1], kv) + return context.WithValue(ctx, mdOutgoingKey{}, rawMD{md: md.md, added: added}) } // FromIncomingContext returns the incoming metadata in ctx if it exists. The @@ -128,10 +172,39 @@ func FromIncomingContext(ctx context.Context) (md MD, ok bool) { return } +// FromOutgoingContextRaw returns the un-merged, intermediary contents +// of rawMD. Remember to perform strings.ToLower on the keys. The returned +// MD should not be modified. Writing to it may cause races. Modification +// should be made to copies of the returned MD. +// +// This is intended for gRPC-internal use ONLY. +func FromOutgoingContextRaw(ctx context.Context) (MD, [][]string, bool) { + raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) + if !ok { + return nil, nil, false + } + + return raw.md, raw.added, true +} + // FromOutgoingContext returns the outgoing metadata in ctx if it exists. The // returned MD should not be modified. Writing to it may cause races. -// Modification should be made to the copies of the returned MD. -func FromOutgoingContext(ctx context.Context) (md MD, ok bool) { - md, ok = ctx.Value(mdOutgoingKey{}).(MD) - return +// Modification should be made to copies of the returned MD. +func FromOutgoingContext(ctx context.Context) (MD, bool) { + raw, ok := ctx.Value(mdOutgoingKey{}).(rawMD) + if !ok { + return nil, false + } + + mds := make([]MD, 0, len(raw.added)+1) + mds = append(mds, raw.md) + for _, vv := range raw.added { + mds = append(mds, Pairs(vv...)) + } + return Join(mds...), ok +} + +type rawMD struct { + md MD + added [][]string } diff --git a/vendor/google.golang.org/grpc/metadata/metadata_test.go b/vendor/google.golang.org/grpc/metadata/metadata_test.go deleted file mode 100644 index 210cbb2676..0000000000 --- a/vendor/google.golang.org/grpc/metadata/metadata_test.go +++ /dev/null @@ -1,71 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 metadata - -import ( - "reflect" - "testing" -) - -func TestPairsMD(t *testing.T) { - for _, test := range []struct { - // input - kv []string - // output - md MD - }{ - {[]string{}, MD{}}, - {[]string{"k1", "v1", "k1", "v2"}, MD{"k1": []string{"v1", "v2"}}}, - } { - md := Pairs(test.kv...) - if !reflect.DeepEqual(md, test.md) { - t.Fatalf("Pairs(%v) = %v, want %v", test.kv, md, test.md) - } - } -} - -func TestCopy(t *testing.T) { - const key, val = "key", "val" - orig := Pairs(key, val) - copy := orig.Copy() - if !reflect.DeepEqual(orig, copy) { - t.Errorf("copied value not equal to the original, got %v, want %v", copy, orig) - } - orig[key][0] = "foo" - if v := copy[key][0]; v != val { - t.Errorf("change in original should not affect copy, got %q, want %q", v, val) - } -} - -func TestJoin(t *testing.T) { - for _, test := range []struct { - mds []MD - want MD - }{ - {[]MD{}, MD{}}, - {[]MD{Pairs("foo", "bar")}, Pairs("foo", "bar")}, - {[]MD{Pairs("foo", "bar"), Pairs("foo", "baz")}, Pairs("foo", "bar", "foo", "baz")}, - {[]MD{Pairs("foo", "bar"), Pairs("foo", "baz"), Pairs("zip", "zap")}, Pairs("foo", "bar", "foo", "baz", "zip", "zap")}, - } { - md := Join(test.mds...) - if !reflect.DeepEqual(md, test.want) { - t.Errorf("context's metadata is %v, want %v", md, test.want) - } - } -} diff --git a/vendor/google.golang.org/grpc/naming/dns_resolver.go b/vendor/google.golang.org/grpc/naming/dns_resolver.go index 7e69a2ca0a..0f8a908ea9 100644 --- a/vendor/google.golang.org/grpc/naming/dns_resolver.go +++ b/vendor/google.golang.org/grpc/naming/dns_resolver.go @@ -153,10 +153,10 @@ type ipWatcher struct { updateChan chan *Update } -// Next returns the adrress resolution Update for the target. For IP address, -// the resolution is itself, thus polling name server is unncessary. Therefore, +// Next returns the address resolution Update for the target. For IP address, +// the resolution is itself, thus polling name server is unnecessary. Therefore, // Next() will return an Update the first time it is called, and will be blocked -// for all following calls as no Update exisits until watcher is closed. +// for all following calls as no Update exists until watcher is closed. func (i *ipWatcher) Next() ([]*Update, error) { u, ok := <-i.updateChan if !ok { diff --git a/vendor/google.golang.org/grpc/naming/dns_resolver_test.go b/vendor/google.golang.org/grpc/naming/dns_resolver_test.go deleted file mode 100644 index be1ac1aeca..0000000000 --- a/vendor/google.golang.org/grpc/naming/dns_resolver_test.go +++ /dev/null @@ -1,315 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 naming - -import ( - "fmt" - "net" - "reflect" - "sync" - "testing" - "time" -) - -func newUpdateWithMD(op Operation, addr, lb string) *Update { - return &Update{ - Op: op, - Addr: addr, - Metadata: AddrMetadataGRPCLB{AddrType: GRPCLB, ServerName: lb}, - } -} - -func toMap(u []*Update) map[string]*Update { - m := make(map[string]*Update) - for _, v := range u { - m[v.Addr] = v - } - return m -} - -func TestCompileUpdate(t *testing.T) { - tests := []struct { - oldAddrs []string - newAddrs []string - want []*Update - }{ - { - []string{}, - []string{"1.0.0.1"}, - []*Update{{Op: Add, Addr: "1.0.0.1"}}, - }, - { - []string{"1.0.0.1"}, - []string{"1.0.0.1"}, - []*Update{}, - }, - { - []string{"1.0.0.0"}, - []string{"1.0.0.1"}, - []*Update{{Op: Delete, Addr: "1.0.0.0"}, {Op: Add, Addr: "1.0.0.1"}}, - }, - { - []string{"1.0.0.1"}, - []string{"1.0.0.0"}, - []*Update{{Op: Add, Addr: "1.0.0.0"}, {Op: Delete, Addr: "1.0.0.1"}}, - }, - { - []string{"1.0.0.1"}, - []string{"1.0.0.1", "1.0.0.2", "1.0.0.3"}, - []*Update{{Op: Add, Addr: "1.0.0.2"}, {Op: Add, Addr: "1.0.0.3"}}, - }, - { - []string{"1.0.0.1", "1.0.0.2", "1.0.0.3"}, - []string{"1.0.0.0"}, - []*Update{{Op: Add, Addr: "1.0.0.0"}, {Op: Delete, Addr: "1.0.0.1"}, {Op: Delete, Addr: "1.0.0.2"}, {Op: Delete, Addr: "1.0.0.3"}}, - }, - { - []string{"1.0.0.1", "1.0.0.3", "1.0.0.5"}, - []string{"1.0.0.2", "1.0.0.3", "1.0.0.6"}, - []*Update{{Op: Delete, Addr: "1.0.0.1"}, {Op: Add, Addr: "1.0.0.2"}, {Op: Delete, Addr: "1.0.0.5"}, {Op: Add, Addr: "1.0.0.6"}}, - }, - { - []string{"1.0.0.1", "1.0.0.1", "1.0.0.2"}, - []string{"1.0.0.1"}, - []*Update{{Op: Delete, Addr: "1.0.0.2"}}, - }, - } - - var w dnsWatcher - for _, c := range tests { - w.curAddrs = make(map[string]*Update) - newUpdates := make(map[string]*Update) - for _, a := range c.oldAddrs { - w.curAddrs[a] = &Update{Addr: a} - } - for _, a := range c.newAddrs { - newUpdates[a] = &Update{Addr: a} - } - r := w.compileUpdate(newUpdates) - if !reflect.DeepEqual(toMap(c.want), toMap(r)) { - t.Errorf("w(%+v).compileUpdate(%+v) = %+v, want %+v", c.oldAddrs, c.newAddrs, updatesToSlice(r), updatesToSlice(c.want)) - } - } -} - -func TestResolveFunc(t *testing.T) { - tests := []struct { - addr string - want error - }{ - // TODO(yuxuanli): More false cases? - {"www.google.com", nil}, - {"foo.bar:12345", nil}, - {"127.0.0.1", nil}, - {"127.0.0.1:12345", nil}, - {"[::1]:80", nil}, - {"[2001:db8:a0b:12f0::1]:21", nil}, - {":80", nil}, - {"127.0.0...1:12345", nil}, - {"[fe80::1%lo0]:80", nil}, - {"golang.org:http", nil}, - {"[2001:db8::1]:http", nil}, - {":", nil}, - {"", errMissingAddr}, - {"[2001:db8:a0b:12f0::1", fmt.Errorf("invalid target address %v", "[2001:db8:a0b:12f0::1")}, - } - - r, err := NewDNSResolver() - if err != nil { - t.Errorf("%v", err) - } - for _, v := range tests { - _, err := r.Resolve(v.addr) - if !reflect.DeepEqual(err, v.want) { - t.Errorf("Resolve(%q) = %v, want %v", v.addr, err, v.want) - } - } -} - -var hostLookupTbl = map[string][]string{ - "foo.bar.com": {"1.2.3.4", "5.6.7.8"}, - "ipv4.single.fake": {"1.2.3.4"}, - "ipv4.multi.fake": {"1.2.3.4", "5.6.7.8", "9.10.11.12"}, - "ipv6.single.fake": {"2607:f8b0:400a:801::1001"}, - "ipv6.multi.fake": {"2607:f8b0:400a:801::1001", "2607:f8b0:400a:801::1002", "2607:f8b0:400a:801::1003"}, -} - -func hostLookup(host string) ([]string, error) { - if addrs, ok := hostLookupTbl[host]; ok { - return addrs, nil - } - return nil, fmt.Errorf("failed to lookup host:%s resolution in hostLookupTbl", host) -} - -var srvLookupTbl = map[string][]*net.SRV{ - "_grpclb._tcp.srv.ipv4.single.fake": {&net.SRV{Target: "ipv4.single.fake", Port: 1234}}, - "_grpclb._tcp.srv.ipv4.multi.fake": {&net.SRV{Target: "ipv4.multi.fake", Port: 1234}}, - "_grpclb._tcp.srv.ipv6.single.fake": {&net.SRV{Target: "ipv6.single.fake", Port: 1234}}, - "_grpclb._tcp.srv.ipv6.multi.fake": {&net.SRV{Target: "ipv6.multi.fake", Port: 1234}}, -} - -func srvLookup(service, proto, name string) (string, []*net.SRV, error) { - cname := "_" + service + "._" + proto + "." + name - if srvs, ok := srvLookupTbl[cname]; ok { - return cname, srvs, nil - } - return "", nil, fmt.Errorf("failed to lookup srv record for %s in srvLookupTbl", cname) -} - -func updatesToSlice(updates []*Update) []Update { - res := make([]Update, len(updates)) - for i, u := range updates { - res[i] = *u - } - return res -} - -func testResolver(t *testing.T, freq time.Duration, slp time.Duration) { - tests := []struct { - target string - want []*Update - }{ - { - "foo.bar.com", - []*Update{{Op: Add, Addr: "1.2.3.4" + colonDefaultPort}, {Op: Add, Addr: "5.6.7.8" + colonDefaultPort}}, - }, - { - "foo.bar.com:1234", - []*Update{{Op: Add, Addr: "1.2.3.4:1234"}, {Op: Add, Addr: "5.6.7.8:1234"}}, - }, - { - "srv.ipv4.single.fake", - []*Update{newUpdateWithMD(Add, "1.2.3.4:1234", "ipv4.single.fake")}, - }, - { - "srv.ipv4.multi.fake", - []*Update{ - newUpdateWithMD(Add, "1.2.3.4:1234", "ipv4.multi.fake"), - newUpdateWithMD(Add, "5.6.7.8:1234", "ipv4.multi.fake"), - newUpdateWithMD(Add, "9.10.11.12:1234", "ipv4.multi.fake")}, - }, - { - "srv.ipv6.single.fake", - []*Update{newUpdateWithMD(Add, "[2607:f8b0:400a:801::1001]:1234", "ipv6.single.fake")}, - }, - { - "srv.ipv6.multi.fake", - []*Update{ - newUpdateWithMD(Add, "[2607:f8b0:400a:801::1001]:1234", "ipv6.multi.fake"), - newUpdateWithMD(Add, "[2607:f8b0:400a:801::1002]:1234", "ipv6.multi.fake"), - newUpdateWithMD(Add, "[2607:f8b0:400a:801::1003]:1234", "ipv6.multi.fake"), - }, - }, - } - - for _, a := range tests { - r, err := NewDNSResolverWithFreq(freq) - if err != nil { - t.Fatalf("%v\n", err) - } - w, err := r.Resolve(a.target) - if err != nil { - t.Fatalf("%v\n", err) - } - updates, err := w.Next() - if err != nil { - t.Fatalf("%v\n", err) - } - if !reflect.DeepEqual(toMap(a.want), toMap(updates)) { - t.Errorf("Resolve(%q) = %+v, want %+v\n", a.target, updatesToSlice(updates), updatesToSlice(a.want)) - } - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - for { - _, err := w.Next() - if err != nil { - return - } - t.Error("Execution shouldn't reach here, since w.Next() should be blocked until close happen.") - } - }() - // Sleep for sometime to let watcher do more than one lookup - time.Sleep(slp) - w.Close() - wg.Wait() - } -} - -func TestResolve(t *testing.T) { - defer replaceNetFunc()() - testResolver(t, time.Millisecond*5, time.Millisecond*10) -} - -const colonDefaultPort = ":" + defaultPort - -func TestIPWatcher(t *testing.T) { - tests := []struct { - target string - want []*Update - }{ - {"127.0.0.1", []*Update{{Op: Add, Addr: "127.0.0.1" + colonDefaultPort}}}, - {"127.0.0.1:12345", []*Update{{Op: Add, Addr: "127.0.0.1:12345"}}}, - {"::1", []*Update{{Op: Add, Addr: "[::1]" + colonDefaultPort}}}, - {"[::1]:12345", []*Update{{Op: Add, Addr: "[::1]:12345"}}}, - {"[::1]:", []*Update{{Op: Add, Addr: "[::1]:443"}}}, - {"2001:db8:85a3::8a2e:370:7334", []*Update{{Op: Add, Addr: "[2001:db8:85a3::8a2e:370:7334]" + colonDefaultPort}}}, - {"[2001:db8:85a3::8a2e:370:7334]", []*Update{{Op: Add, Addr: "[2001:db8:85a3::8a2e:370:7334]" + colonDefaultPort}}}, - {"[2001:db8:85a3::8a2e:370:7334]:12345", []*Update{{Op: Add, Addr: "[2001:db8:85a3::8a2e:370:7334]:12345"}}}, - {"[2001:db8::1]:http", []*Update{{Op: Add, Addr: "[2001:db8::1]:http"}}}, - // TODO(yuxuanli): zone support? - } - - for _, v := range tests { - r, err := NewDNSResolverWithFreq(time.Millisecond * 5) - if err != nil { - t.Fatalf("%v\n", err) - } - w, err := r.Resolve(v.target) - if err != nil { - t.Fatalf("%v\n", err) - } - var updates []*Update - var wg sync.WaitGroup - wg.Add(1) - count := 0 - go func() { - defer wg.Done() - for { - u, err := w.Next() - if err != nil { - return - } - updates = u - count++ - } - }() - // Sleep for sometime to let watcher do more than one lookup - time.Sleep(time.Millisecond * 10) - w.Close() - wg.Wait() - if !reflect.DeepEqual(v.want, updates) { - t.Errorf("Resolve(%q) = %v, want %+v\n", v.target, updatesToSlice(updates), updatesToSlice(v.want)) - } - if count != 1 { - t.Errorf("IPWatcher Next() should return only once, not %d times\n", count) - } - } -} diff --git a/vendor/google.golang.org/grpc/naming/go17.go b/vendor/google.golang.org/grpc/naming/go17.go index 8bdf21e799..57b65d7b88 100644 --- a/vendor/google.golang.org/grpc/naming/go17.go +++ b/vendor/google.golang.org/grpc/naming/go17.go @@ -1,4 +1,4 @@ -// +build go1.7, !go1.8 +// +build go1.6,!go1.8 /* * diff --git a/vendor/google.golang.org/grpc/naming/naming.go b/vendor/google.golang.org/grpc/naming/naming.go index 1af7e32f86..8cc39e9375 100644 --- a/vendor/google.golang.org/grpc/naming/naming.go +++ b/vendor/google.golang.org/grpc/naming/naming.go @@ -18,20 +18,26 @@ // Package naming defines the naming API and related data structures for gRPC. // The interface is EXPERIMENTAL and may be suject to change. +// +// Deprecated: please use package resolver. package naming // Operation defines the corresponding operations for a name resolution change. +// +// Deprecated: please use package resolver. type Operation uint8 const ( // Add indicates a new address is added. Add Operation = iota - // Delete indicates an exisiting address is deleted. + // Delete indicates an existing address is deleted. Delete ) // Update defines a name resolution update. Notice that it is not valid having both // empty string Addr and nil Metadata in an Update. +// +// Deprecated: please use package resolver. type Update struct { // Op indicates the operation of the update. Op Operation @@ -43,12 +49,16 @@ type Update struct { } // Resolver creates a Watcher for a target to track its resolution changes. +// +// Deprecated: please use package resolver. type Resolver interface { // Resolve creates a Watcher for target. Resolve(target string) (Watcher, error) } // Watcher watches for the updates on the specified target. +// +// Deprecated: please use package resolver. type Watcher interface { // Next blocks until an update or error happens. It may return one or more // updates. The first call should get the full set of the results. It should diff --git a/vendor/google.golang.org/grpc/picker_wrapper.go b/vendor/google.golang.org/grpc/picker_wrapper.go index 9085dbc9c9..0a984e6c8a 100644 --- a/vendor/google.golang.org/grpc/picker_wrapper.go +++ b/vendor/google.golang.org/grpc/picker_wrapper.go @@ -19,12 +19,17 @@ package grpc import ( + "io" "sync" + "sync/atomic" "golang.org/x/net/context" "google.golang.org/grpc/balancer" + "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/resolver" "google.golang.org/grpc/status" "google.golang.org/grpc/transport" ) @@ -36,13 +41,57 @@ type pickerWrapper struct { done bool blockingCh chan struct{} picker balancer.Picker + + // The latest connection happened. + connErrMu sync.Mutex + connErr error + + stickinessMDKey atomic.Value + stickiness *stickyStore } func newPickerWrapper() *pickerWrapper { - bp := &pickerWrapper{blockingCh: make(chan struct{})} + bp := &pickerWrapper{ + blockingCh: make(chan struct{}), + stickiness: newStickyStore(), + } return bp } +func (bp *pickerWrapper) updateConnectionError(err error) { + bp.connErrMu.Lock() + bp.connErr = err + bp.connErrMu.Unlock() +} + +func (bp *pickerWrapper) connectionError() error { + bp.connErrMu.Lock() + err := bp.connErr + bp.connErrMu.Unlock() + return err +} + +func (bp *pickerWrapper) updateStickinessMDKey(newKey string) { + // No need to check ok because mdKey == "" if ok == false. + if oldKey, _ := bp.stickinessMDKey.Load().(string); oldKey != newKey { + bp.stickinessMDKey.Store(newKey) + bp.stickiness.reset(newKey) + } +} + +func (bp *pickerWrapper) getStickinessMDKey() string { + // No need to check ok because mdKey == "" if ok == false. + mdKey, _ := bp.stickinessMDKey.Load().(string) + return mdKey +} + +func (bp *pickerWrapper) clearStickinessState() { + if oldKey := bp.getStickinessMDKey(); oldKey != "" { + // There's no need to reset store if mdKey was "". + bp.stickiness.reset(oldKey) + } +} + // updatePicker is called by UpdateBalancerState. It unblocks all blocked pick. func (bp *pickerWrapper) updatePicker(p balancer.Picker) { bp.mu.Lock() @@ -57,6 +106,23 @@ func (bp *pickerWrapper) updatePicker(p balancer.Picker) { bp.mu.Unlock() } +func doneChannelzWrapper(acw *acBalancerWrapper, done func(balancer.DoneInfo)) func(balancer.DoneInfo) { + acw.mu.Lock() + ac := acw.ac + acw.mu.Unlock() + ac.incrCallsStarted() + return func(b balancer.DoneInfo) { + if b.Err != nil && b.Err != io.EOF { + ac.incrCallsFailed() + } else { + ac.incrCallsSucceeded() + } + if done != nil { + done(b) + } + } +} + // pick returns the transport that will be used for the RPC. // It may block in the following cases: // - there's no picker @@ -65,6 +131,27 @@ func (bp *pickerWrapper) updatePicker(p balancer.Picker) { // - the subConn returned by the current picker is not READY // When one of these situations happens, pick blocks until the picker gets updated. func (bp *pickerWrapper) pick(ctx context.Context, failfast bool, opts balancer.PickOptions) (transport.ClientTransport, func(balancer.DoneInfo), error) { + + mdKey := bp.getStickinessMDKey() + stickyKey, isSticky := stickyKeyFromContext(ctx, mdKey) + + // Potential race here: if stickinessMDKey is updated after the above two + // lines, and this pick is a sticky pick, the following put could add an + // entry to sticky store with an outdated sticky key. + // + // The solution: keep the current md key in sticky store, and at the + // beginning of each get/put, check the mdkey against store.curMDKey. + // - Cons: one more string comparing for each get/put. + // - Pros: the string matching happens inside get/put, so the overhead for + // non-sticky RPCs will be minimal. + + if isSticky { + if t, ok := bp.stickiness.get(mdKey, stickyKey); ok { + // Done function returned is always nil. + return t, nil, nil + } + } + var ( p balancer.Picker ch chan struct{} @@ -97,7 +184,7 @@ func (bp *pickerWrapper) pick(ctx context.Context, failfast bool, opts balancer. p = bp.picker bp.mu.Unlock() - subConn, put, err := p.Pick(ctx, opts) + subConn, done, err := p.Pick(ctx, opts) if err != nil { switch err { @@ -107,7 +194,7 @@ func (bp *pickerWrapper) pick(ctx context.Context, failfast bool, opts balancer. if !failfast { continue } - return nil, nil, status.Errorf(codes.Unavailable, "%v", err) + return nil, nil, status.Errorf(codes.Unavailable, "%v, latest connection error: %v", err, bp.connectionError()) default: // err is some other error. return nil, nil, toRPCErr(err) @@ -120,7 +207,13 @@ func (bp *pickerWrapper) pick(ctx context.Context, failfast bool, opts balancer. continue } if t, ok := acw.getAddrConn().getReadyTransport(); ok { - return t, put, nil + if isSticky { + bp.stickiness.put(mdKey, stickyKey, acw) + } + if channelz.IsOn() { + return t, doneChannelzWrapper(acw, done), nil + } + return t, done, nil } grpclog.Infof("blockingPicker: the picked transport is not ready, loop back to repick") // If ok == false, ac.state is not READY. @@ -139,3 +232,100 @@ func (bp *pickerWrapper) close() { bp.done = true close(bp.blockingCh) } + +type stickyStoreEntry struct { + acw *acBalancerWrapper + addr resolver.Address +} + +type stickyStore struct { + mu sync.Mutex + // curMDKey is check before every get/put to avoid races. The operation will + // abort immediately when the given mdKey is different from the curMDKey. + curMDKey string + store map[string]*stickyStoreEntry +} + +func newStickyStore() *stickyStore { + return &stickyStore{ + store: make(map[string]*stickyStoreEntry), + } +} + +// reset clears the map in stickyStore, and set the currentMDKey to newMDKey. +func (ss *stickyStore) reset(newMDKey string) { + ss.mu.Lock() + ss.curMDKey = newMDKey + ss.store = make(map[string]*stickyStoreEntry) + ss.mu.Unlock() +} + +// stickyKey is the key to look up in store. mdKey will be checked against +// curMDKey to avoid races. +func (ss *stickyStore) put(mdKey, stickyKey string, acw *acBalancerWrapper) { + ss.mu.Lock() + defer ss.mu.Unlock() + if mdKey != ss.curMDKey { + return + } + // TODO(stickiness): limit the total number of entries. + ss.store[stickyKey] = &stickyStoreEntry{ + acw: acw, + addr: acw.getAddrConn().getCurAddr(), + } +} + +// stickyKey is the key to look up in store. mdKey will be checked against +// curMDKey to avoid races. +func (ss *stickyStore) get(mdKey, stickyKey string) (transport.ClientTransport, bool) { + ss.mu.Lock() + defer ss.mu.Unlock() + if mdKey != ss.curMDKey { + return nil, false + } + entry, ok := ss.store[stickyKey] + if !ok { + return nil, false + } + ac := entry.acw.getAddrConn() + if ac.getCurAddr() != entry.addr { + delete(ss.store, stickyKey) + return nil, false + } + t, ok := ac.getReadyTransport() + if !ok { + delete(ss.store, stickyKey) + return nil, false + } + return t, true +} + +// Get one value from metadata in ctx with key stickinessMDKey. +// +// It returns "", false if stickinessMDKey is an empty string. +func stickyKeyFromContext(ctx context.Context, stickinessMDKey string) (string, bool) { + if stickinessMDKey == "" { + return "", false + } + + md, added, ok := metadata.FromOutgoingContextRaw(ctx) + if !ok { + return "", false + } + + if vv, ok := md[stickinessMDKey]; ok { + if len(vv) > 0 { + return vv[0], true + } + } + + for _, ss := range added { + for i := 0; i < len(ss)-1; i += 2 { + if ss[i] == stickinessMDKey { + return ss[i+1], true + } + } + } + + return "", false +} diff --git a/vendor/google.golang.org/grpc/picker_wrapper_test.go b/vendor/google.golang.org/grpc/picker_wrapper_test.go deleted file mode 100644 index 23bc8f2433..0000000000 --- a/vendor/google.golang.org/grpc/picker_wrapper_test.go +++ /dev/null @@ -1,160 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "fmt" - "sync/atomic" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/balancer" - "google.golang.org/grpc/connectivity" - _ "google.golang.org/grpc/grpclog/glogger" - "google.golang.org/grpc/test/leakcheck" - "google.golang.org/grpc/transport" -) - -const goroutineCount = 5 - -var ( - testT = &testTransport{} - testSC = &acBalancerWrapper{ac: &addrConn{ - state: connectivity.Ready, - transport: testT, - }} - testSCNotReady = &acBalancerWrapper{ac: &addrConn{ - state: connectivity.TransientFailure, - }} -) - -type testTransport struct { - transport.ClientTransport -} - -type testingPicker struct { - err error - sc balancer.SubConn - maxCalled int64 -} - -func (p *testingPicker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.SubConn, func(balancer.DoneInfo), error) { - if atomic.AddInt64(&p.maxCalled, -1) < 0 { - return nil, nil, fmt.Errorf("Pick called to many times (> goroutineCount)") - } - if p.err != nil { - return nil, nil, p.err - } - return p.sc, nil, nil -} - -func TestBlockingPickTimeout(t *testing.T) { - defer leakcheck.Check(t) - bp := newPickerWrapper() - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - if _, _, err := bp.pick(ctx, true, balancer.PickOptions{}); err != context.DeadlineExceeded { - t.Errorf("bp.pick returned error %v, want DeadlineExceeded", err) - } -} - -func TestBlockingPick(t *testing.T) { - defer leakcheck.Check(t) - bp := newPickerWrapper() - // All goroutines should block because picker is nil in bp. - var finishedCount uint64 - for i := goroutineCount; i > 0; i-- { - go func() { - if tr, _, err := bp.pick(context.Background(), true, balancer.PickOptions{}); err != nil || tr != testT { - t.Errorf("bp.pick returned non-nil error: %v", err) - } - atomic.AddUint64(&finishedCount, 1) - }() - } - time.Sleep(50 * time.Millisecond) - if c := atomic.LoadUint64(&finishedCount); c != 0 { - t.Errorf("finished goroutines count: %v, want 0", c) - } - bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount}) -} - -func TestBlockingPickNoSubAvailable(t *testing.T) { - defer leakcheck.Check(t) - bp := newPickerWrapper() - var finishedCount uint64 - bp.updatePicker(&testingPicker{err: balancer.ErrNoSubConnAvailable, maxCalled: goroutineCount}) - // All goroutines should block because picker returns no sc avilable. - for i := goroutineCount; i > 0; i-- { - go func() { - if tr, _, err := bp.pick(context.Background(), true, balancer.PickOptions{}); err != nil || tr != testT { - t.Errorf("bp.pick returned non-nil error: %v", err) - } - atomic.AddUint64(&finishedCount, 1) - }() - } - time.Sleep(50 * time.Millisecond) - if c := atomic.LoadUint64(&finishedCount); c != 0 { - t.Errorf("finished goroutines count: %v, want 0", c) - } - bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount}) -} - -func TestBlockingPickTransientWaitforready(t *testing.T) { - defer leakcheck.Check(t) - bp := newPickerWrapper() - bp.updatePicker(&testingPicker{err: balancer.ErrTransientFailure, maxCalled: goroutineCount}) - var finishedCount uint64 - // All goroutines should block because picker returns transientFailure and - // picks are not failfast. - for i := goroutineCount; i > 0; i-- { - go func() { - if tr, _, err := bp.pick(context.Background(), false, balancer.PickOptions{}); err != nil || tr != testT { - t.Errorf("bp.pick returned non-nil error: %v", err) - } - atomic.AddUint64(&finishedCount, 1) - }() - } - time.Sleep(time.Millisecond) - if c := atomic.LoadUint64(&finishedCount); c != 0 { - t.Errorf("finished goroutines count: %v, want 0", c) - } - bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount}) -} - -func TestBlockingPickSCNotReady(t *testing.T) { - defer leakcheck.Check(t) - bp := newPickerWrapper() - bp.updatePicker(&testingPicker{sc: testSCNotReady, maxCalled: goroutineCount}) - var finishedCount uint64 - // All goroutines should block because sc is not ready. - for i := goroutineCount; i > 0; i-- { - go func() { - if tr, _, err := bp.pick(context.Background(), true, balancer.PickOptions{}); err != nil || tr != testT { - t.Errorf("bp.pick returned non-nil error: %v", err) - } - atomic.AddUint64(&finishedCount, 1) - }() - } - time.Sleep(time.Millisecond) - if c := atomic.LoadUint64(&finishedCount); c != 0 { - t.Errorf("finished goroutines count: %v, want 0", c) - } - bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount}) -} diff --git a/vendor/google.golang.org/grpc/pickfirst.go b/vendor/google.golang.org/grpc/pickfirst.go index 7f993ef5a3..bf659d49d2 100644 --- a/vendor/google.golang.org/grpc/pickfirst.go +++ b/vendor/google.golang.org/grpc/pickfirst.go @@ -26,6 +26,9 @@ import ( "google.golang.org/grpc/resolver" ) +// PickFirstBalancerName is the name of the pick_first balancer. +const PickFirstBalancerName = "pick_first" + func newPickfirstBuilder() balancer.Builder { return &pickfirstBuilder{} } @@ -37,7 +40,7 @@ func (*pickfirstBuilder) Build(cc balancer.ClientConn, opt balancer.BuildOptions } func (*pickfirstBuilder) Name() string { - return "pickfirst" + return PickFirstBalancerName } type pickfirstBalancer struct { @@ -57,14 +60,20 @@ func (b *pickfirstBalancer) HandleResolvedAddrs(addrs []resolver.Address, err er return } b.cc.UpdateBalancerState(connectivity.Idle, &picker{sc: b.sc}) + b.sc.Connect() } else { b.sc.UpdateAddresses(addrs) + b.sc.Connect() } } func (b *pickfirstBalancer) HandleSubConnStateChange(sc balancer.SubConn, s connectivity.State) { grpclog.Infof("pickfirstBalancer: HandleSubConnStateChange: %p, %v", sc, s) - if b.sc != sc || s == connectivity.Shutdown { + if b.sc != sc { + grpclog.Infof("pickfirstBalancer: ignored state change because sc is not recognized") + return + } + if s == connectivity.Shutdown { b.sc = nil return } @@ -93,3 +102,7 @@ func (p *picker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer. } return p.sc, nil, nil } + +func init() { + balancer.Register(newPickfirstBuilder()) +} diff --git a/vendor/google.golang.org/grpc/pickfirst_test.go b/vendor/google.golang.org/grpc/pickfirst_test.go deleted file mode 100644 index e58b3422c1..0000000000 --- a/vendor/google.golang.org/grpc/pickfirst_test.go +++ /dev/null @@ -1,352 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "math" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/resolver/manual" - "google.golang.org/grpc/test/leakcheck" -) - -func TestOneBackendPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 1 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithBalancerBuilder(newPickfirstBuilder()), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := Invoke(ctx, "/foo/bar", &req, &reply, cc); err == nil || Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}}) - // The second RPC should succeed. - for i := 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[0].port { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("EmptyCall() = _, %v, want _, %v", err, servers[0].port) -} - -func TestBackendsPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithBalancerBuilder(newPickfirstBuilder()), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := Invoke(ctx, "/foo/bar", &req, &reply, cc); err == nil || Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - // The second RPC should succeed with the first server. - for i := 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[0].port { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("EmptyCall() = _, %v, want _, %v", err, servers[0].port) -} - -func TestNewAddressWhileBlockingPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 1 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithBalancerBuilder(newPickfirstBuilder()), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := Invoke(ctx, "/foo/bar", &req, &reply, cc); err == nil || Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - var wg sync.WaitGroup - for i := 0; i < 3; i++ { - wg.Add(1) - go func() { - defer wg.Done() - // This RPC blocks until NewAddress is called. - Invoke(context.Background(), "/foo/bar", &req, &reply, cc) - }() - } - time.Sleep(50 * time.Millisecond) - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}}) - wg.Wait() -} - -func TestCloseWithPendingRPCPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 1 - _, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithBalancerBuilder(newPickfirstBuilder()), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := Invoke(ctx, "/foo/bar", &req, &reply, cc); err == nil || Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - var wg sync.WaitGroup - for i := 0; i < 3; i++ { - wg.Add(1) - go func() { - defer wg.Done() - // This RPC blocks until NewAddress is called. - Invoke(context.Background(), "/foo/bar", &req, &reply, cc) - }() - } - time.Sleep(50 * time.Millisecond) - cc.Close() - wg.Wait() -} - -func TestOneServerDownPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithBalancerBuilder(newPickfirstBuilder()), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := Invoke(ctx, "/foo/bar", &req, &reply, cc); err == nil || Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - // The second RPC should succeed with the first server. - for i := 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[0].port { - break - } - time.Sleep(time.Millisecond) - } - - servers[0].stop() - for i := 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[1].port { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("EmptyCall() = _, %v, want _, %v", err, servers[0].port) -} - -func TestAllServersDownPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 2 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithBalancerBuilder(newPickfirstBuilder()), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := Invoke(ctx, "/foo/bar", &req, &reply, cc); err == nil || Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}}) - // The second RPC should succeed with the first server. - for i := 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[0].port { - break - } - time.Sleep(time.Millisecond) - } - - for i := 0; i < numServers; i++ { - servers[i].stop() - } - for i := 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); Code(err) == codes.Unavailable { - return - } - time.Sleep(time.Millisecond) - } - t.Fatalf("EmptyCall() = _, %v, want _, error with code unavailable", err) -} - -func TestAddressesRemovedPickfirst(t *testing.T) { - defer leakcheck.Check(t) - r, rcleanup := manual.GenerateAndRegisterManualResolver() - defer rcleanup() - - numServers := 3 - servers, _, scleanup := startServers(t, numServers, math.MaxInt32) - defer scleanup() - - cc, err := Dial(r.Scheme()+":///test.server", WithInsecure(), WithBalancerBuilder(newPickfirstBuilder()), WithCodec(testCodec{})) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer cc.Close() - // The first RPC should fail because there's no address. - ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond) - defer cancel() - req := "port" - var reply string - if err := Invoke(ctx, "/foo/bar", &req, &reply, cc); err == nil || Code(err) != codes.DeadlineExceeded { - t.Fatalf("EmptyCall() = _, %v, want _, DeadlineExceeded", err) - } - - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}, {Addr: servers[1].addr}, {Addr: servers[2].addr}}) - for i := 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[0].port { - break - } - time.Sleep(time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Remove server[0]. - r.NewAddress([]resolver.Address{{Addr: servers[1].addr}, {Addr: servers[2].addr}}) - for i := 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[1].port { - break - } - time.Sleep(time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Append server[0], nothing should change. - r.NewAddress([]resolver.Address{{Addr: servers[1].addr}, {Addr: servers[2].addr}, {Addr: servers[0].addr}}) - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[1].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 1, err, servers[1].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Remove server[1]. - r.NewAddress([]resolver.Address{{Addr: servers[2].addr}, {Addr: servers[0].addr}}) - for i := 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[2].port { - break - } - time.Sleep(time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[2].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 2, err, servers[2].port) - } - time.Sleep(10 * time.Millisecond) - } - - // Remove server[2]. - r.NewAddress([]resolver.Address{{Addr: servers[0].addr}}) - for i := 0; i < 1000; i++ { - if err = Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err != nil && ErrorDesc(err) == servers[0].port { - break - } - time.Sleep(time.Millisecond) - } - for i := 0; i < 20; i++ { - if err := Invoke(context.Background(), "/foo/bar", &req, &reply, cc); err == nil || ErrorDesc(err) != servers[0].port { - t.Fatalf("Index %d: Invoke(_, _, _, _, _) = %v, want %s", 0, err, servers[0].port) - } - time.Sleep(10 * time.Millisecond) - } -} diff --git a/vendor/google.golang.org/grpc/proxy.go b/vendor/google.golang.org/grpc/proxy.go index 3e17efec61..2d40236e21 100644 --- a/vendor/google.golang.org/grpc/proxy.go +++ b/vendor/google.golang.org/grpc/proxy.go @@ -82,8 +82,7 @@ func doHTTPConnectHandshake(ctx context.Context, conn net.Conn, addr string) (_ Header: map[string][]string{"User-Agent": {grpcUA}}, }) - req = req.WithContext(ctx) - if err := req.Write(conn); err != nil { + if err := sendHTTPRequest(ctx, req, conn); err != nil { return nil, fmt.Errorf("failed to write the HTTP request: %v", err) } diff --git a/vendor/google.golang.org/grpc/proxy_test.go b/vendor/google.golang.org/grpc/proxy_test.go deleted file mode 100644 index 39ee123cca..0000000000 --- a/vendor/google.golang.org/grpc/proxy_test.go +++ /dev/null @@ -1,182 +0,0 @@ -// +build !race - -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "bufio" - "io" - "net" - "net/http" - "net/url" - "testing" - "time" - - "golang.org/x/net/context" - "google.golang.org/grpc/test/leakcheck" -) - -const ( - envTestAddr = "1.2.3.4:8080" - envProxyAddr = "2.3.4.5:7687" -) - -// overwriteAndRestore overwrite function httpProxyFromEnvironment and -// returns a function to restore the default values. -func overwrite(hpfe func(req *http.Request) (*url.URL, error)) func() { - backHPFE := httpProxyFromEnvironment - httpProxyFromEnvironment = hpfe - return func() { - httpProxyFromEnvironment = backHPFE - } -} - -type proxyServer struct { - t *testing.T - lis net.Listener - in net.Conn - out net.Conn -} - -func (p *proxyServer) run() { - in, err := p.lis.Accept() - if err != nil { - return - } - p.in = in - - req, err := http.ReadRequest(bufio.NewReader(in)) - if err != nil { - p.t.Errorf("failed to read CONNECT req: %v", err) - return - } - if req.Method != http.MethodConnect || req.UserAgent() != grpcUA { - resp := http.Response{StatusCode: http.StatusMethodNotAllowed} - resp.Write(p.in) - p.in.Close() - p.t.Errorf("get wrong CONNECT req: %+v", req) - return - } - - out, err := net.Dial("tcp", req.URL.Host) - if err != nil { - p.t.Errorf("failed to dial to server: %v", err) - return - } - resp := http.Response{StatusCode: http.StatusOK, Proto: "HTTP/1.0"} - resp.Write(p.in) - p.out = out - go io.Copy(p.in, p.out) - go io.Copy(p.out, p.in) -} - -func (p *proxyServer) stop() { - p.lis.Close() - if p.in != nil { - p.in.Close() - } - if p.out != nil { - p.out.Close() - } -} - -func TestHTTPConnect(t *testing.T) { - defer leakcheck.Check(t) - plis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - p := &proxyServer{t: t, lis: plis} - go p.run() - defer p.stop() - - blis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - - msg := []byte{4, 3, 5, 2} - recvBuf := make([]byte, len(msg), len(msg)) - done := make(chan struct{}) - go func() { - in, err := blis.Accept() - if err != nil { - t.Errorf("failed to accept: %v", err) - return - } - defer in.Close() - in.Read(recvBuf) - close(done) - }() - - // Overwrite the function in the test and restore them in defer. - hpfe := func(req *http.Request) (*url.URL, error) { - return &url.URL{Host: plis.Addr().String()}, nil - } - defer overwrite(hpfe)() - - // Dial to proxy server. - dialer := newProxyDialer(func(ctx context.Context, addr string) (net.Conn, error) { - if deadline, ok := ctx.Deadline(); ok { - return net.DialTimeout("tcp", addr, deadline.Sub(time.Now())) - } - return net.Dial("tcp", addr) - }) - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - c, err := dialer(ctx, blis.Addr().String()) - if err != nil { - t.Fatalf("http connect Dial failed: %v", err) - } - defer c.Close() - - // Send msg on the connection. - c.Write(msg) - <-done - - // Check received msg. - if string(recvBuf) != string(msg) { - t.Fatalf("received msg: %v, want %v", recvBuf, msg) - } -} - -func TestMapAddressEnv(t *testing.T) { - defer leakcheck.Check(t) - // Overwrite the function in the test and restore them in defer. - hpfe := func(req *http.Request) (*url.URL, error) { - if req.URL.Host == envTestAddr { - return &url.URL{ - Scheme: "https", - Host: envProxyAddr, - }, nil - } - return nil, nil - } - defer overwrite(hpfe)() - - // envTestAddr should be handled by ProxyFromEnvironment. - got, err := mapAddress(context.Background(), envTestAddr) - if err != nil { - t.Error(err) - } - if got != envProxyAddr { - t.Errorf("want %v, got %v", envProxyAddr, got) - } -} diff --git a/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go b/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go new file mode 100644 index 0000000000..c1cabfc995 --- /dev/null +++ b/vendor/google.golang.org/grpc/resolver/dns/dns_resolver.go @@ -0,0 +1,379 @@ +/* + * + * Copyright 2017 gRPC 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 dns implements a dns resolver to be installed as the default resolver +// in grpc. +package dns + +import ( + "encoding/json" + "errors" + "fmt" + "math/rand" + "net" + "os" + "strconv" + "strings" + "sync" + "time" + + "golang.org/x/net/context" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/resolver" +) + +func init() { + resolver.Register(NewBuilder()) +} + +const ( + defaultPort = "443" + defaultFreq = time.Minute * 30 + golang = "GO" + // In DNS, service config is encoded in a TXT record via the mechanism + // described in RFC-1464 using the attribute name grpc_config. + txtAttribute = "grpc_config=" +) + +var ( + errMissingAddr = errors.New("missing address") + randomGen = rand.New(rand.NewSource(time.Now().UnixNano())) +) + +// NewBuilder creates a dnsBuilder which is used to factory DNS resolvers. +func NewBuilder() resolver.Builder { + return &dnsBuilder{freq: defaultFreq} +} + +type dnsBuilder struct { + // frequency of polling the DNS server. + freq time.Duration +} + +// Build creates and starts a DNS resolver that watches the name resolution of the target. +func (b *dnsBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { + host, port, err := parseTarget(target.Endpoint) + if err != nil { + return nil, err + } + + // IP address. + if net.ParseIP(host) != nil { + host, _ = formatIP(host) + addr := []resolver.Address{{Addr: host + ":" + port}} + i := &ipResolver{ + cc: cc, + ip: addr, + rn: make(chan struct{}, 1), + q: make(chan struct{}), + } + cc.NewAddress(addr) + go i.watcher() + return i, nil + } + + // DNS address (non-IP). + ctx, cancel := context.WithCancel(context.Background()) + d := &dnsResolver{ + freq: b.freq, + host: host, + port: port, + ctx: ctx, + cancel: cancel, + cc: cc, + t: time.NewTimer(0), + rn: make(chan struct{}, 1), + disableServiceConfig: opts.DisableServiceConfig, + } + + d.wg.Add(1) + go d.watcher() + return d, nil +} + +// Scheme returns the naming scheme of this resolver builder, which is "dns". +func (b *dnsBuilder) Scheme() string { + return "dns" +} + +// ipResolver watches for the name resolution update for an IP address. +type ipResolver struct { + cc resolver.ClientConn + ip []resolver.Address + // rn channel is used by ResolveNow() to force an immediate resolution of the target. + rn chan struct{} + q chan struct{} +} + +// ResolveNow resend the address it stores, no resolution is needed. +func (i *ipResolver) ResolveNow(opt resolver.ResolveNowOption) { + select { + case i.rn <- struct{}{}: + default: + } +} + +// Close closes the ipResolver. +func (i *ipResolver) Close() { + close(i.q) +} + +func (i *ipResolver) watcher() { + for { + select { + case <-i.rn: + i.cc.NewAddress(i.ip) + case <-i.q: + return + } + } +} + +// dnsResolver watches for the name resolution update for a non-IP target. +type dnsResolver struct { + freq time.Duration + host string + port string + ctx context.Context + cancel context.CancelFunc + cc resolver.ClientConn + // rn channel is used by ResolveNow() to force an immediate resolution of the target. + rn chan struct{} + t *time.Timer + // wg is used to enforce Close() to return after the watcher() goroutine has finished. + // Otherwise, data race will be possible. [Race Example] in dns_resolver_test we + // replace the real lookup functions with mocked ones to facilitate testing. + // If Close() doesn't wait for watcher() goroutine finishes, race detector sometimes + // will warns lookup (READ the lookup function pointers) inside watcher() goroutine + // has data race with replaceNetFunc (WRITE the lookup function pointers). + wg sync.WaitGroup + disableServiceConfig bool +} + +// ResolveNow invoke an immediate resolution of the target that this dnsResolver watches. +func (d *dnsResolver) ResolveNow(opt resolver.ResolveNowOption) { + select { + case d.rn <- struct{}{}: + default: + } +} + +// Close closes the dnsResolver. +func (d *dnsResolver) Close() { + d.cancel() + d.wg.Wait() + d.t.Stop() +} + +func (d *dnsResolver) watcher() { + defer d.wg.Done() + for { + select { + case <-d.ctx.Done(): + return + case <-d.t.C: + case <-d.rn: + } + result, sc := d.lookup() + // Next lookup should happen after an interval defined by d.freq. + d.t.Reset(d.freq) + d.cc.NewServiceConfig(sc) + d.cc.NewAddress(result) + } +} + +func (d *dnsResolver) lookupSRV() []resolver.Address { + var newAddrs []resolver.Address + _, srvs, err := lookupSRV(d.ctx, "grpclb", "tcp", d.host) + if err != nil { + grpclog.Infof("grpc: failed dns SRV record lookup due to %v.\n", err) + return nil + } + for _, s := range srvs { + lbAddrs, err := lookupHost(d.ctx, s.Target) + if err != nil { + grpclog.Infof("grpc: failed load balancer address dns lookup due to %v.\n", err) + continue + } + for _, a := range lbAddrs { + a, ok := formatIP(a) + if !ok { + grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) + continue + } + addr := a + ":" + strconv.Itoa(int(s.Port)) + newAddrs = append(newAddrs, resolver.Address{Addr: addr, Type: resolver.GRPCLB, ServerName: s.Target}) + } + } + return newAddrs +} + +func (d *dnsResolver) lookupTXT() string { + ss, err := lookupTXT(d.ctx, d.host) + if err != nil { + grpclog.Infof("grpc: failed dns TXT record lookup due to %v.\n", err) + return "" + } + var res string + for _, s := range ss { + res += s + } + + // TXT record must have "grpc_config=" attribute in order to be used as service config. + if !strings.HasPrefix(res, txtAttribute) { + grpclog.Warningf("grpc: TXT record %v missing %v attribute", res, txtAttribute) + return "" + } + return strings.TrimPrefix(res, txtAttribute) +} + +func (d *dnsResolver) lookupHost() []resolver.Address { + var newAddrs []resolver.Address + addrs, err := lookupHost(d.ctx, d.host) + if err != nil { + grpclog.Warningf("grpc: failed dns A record lookup due to %v.\n", err) + return nil + } + for _, a := range addrs { + a, ok := formatIP(a) + if !ok { + grpclog.Errorf("grpc: failed IP parsing due to %v.\n", err) + continue + } + addr := a + ":" + d.port + newAddrs = append(newAddrs, resolver.Address{Addr: addr}) + } + return newAddrs +} + +func (d *dnsResolver) lookup() ([]resolver.Address, string) { + newAddrs := d.lookupSRV() + // Support fallback to non-balancer address. + newAddrs = append(newAddrs, d.lookupHost()...) + if d.disableServiceConfig { + return newAddrs, "" + } + sc := d.lookupTXT() + return newAddrs, canaryingSC(sc) +} + +// formatIP returns ok = false if addr is not a valid textual representation of an IP address. +// If addr is an IPv4 address, return the addr and ok = true. +// If addr is an IPv6 address, return the addr enclosed in square brackets and ok = true. +func formatIP(addr string) (addrIP string, ok bool) { + ip := net.ParseIP(addr) + if ip == nil { + return "", false + } + if ip.To4() != nil { + return addr, true + } + return "[" + addr + "]", true +} + +// parseTarget takes the user input target string, returns formatted host and port info. +// If target doesn't specify a port, set the port to be the defaultPort. +// If target is in IPv6 format and host-name is enclosed in sqarue brackets, brackets +// are strippd when setting the host. +// examples: +// target: "www.google.com" returns host: "www.google.com", port: "443" +// target: "ipv4-host:80" returns host: "ipv4-host", port: "80" +// target: "[ipv6-host]" returns host: "ipv6-host", port: "443" +// target: ":80" returns host: "localhost", port: "80" +// target: ":" returns host: "localhost", port: "443" +func parseTarget(target string) (host, port string, err error) { + if target == "" { + return "", "", errMissingAddr + } + if ip := net.ParseIP(target); ip != nil { + // target is an IPv4 or IPv6(without brackets) address + return target, defaultPort, nil + } + if host, port, err = net.SplitHostPort(target); err == nil { + // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port + if host == "" { + // Keep consistent with net.Dial(): If the host is empty, as in ":80", the local system is assumed. + host = "localhost" + } + if port == "" { + // If the port field is empty(target ends with colon), e.g. "[::1]:", defaultPort is used. + port = defaultPort + } + return host, port, nil + } + if host, port, err = net.SplitHostPort(target + ":" + defaultPort); err == nil { + // target doesn't have port + return host, port, nil + } + return "", "", fmt.Errorf("invalid target address %v, error info: %v", target, err) +} + +type rawChoice struct { + ClientLanguage *[]string `json:"clientLanguage,omitempty"` + Percentage *int `json:"percentage,omitempty"` + ClientHostName *[]string `json:"clientHostName,omitempty"` + ServiceConfig *json.RawMessage `json:"serviceConfig,omitempty"` +} + +func containsString(a *[]string, b string) bool { + if a == nil { + return true + } + for _, c := range *a { + if c == b { + return true + } + } + return false +} + +func chosenByPercentage(a *int) bool { + if a == nil { + return true + } + return randomGen.Intn(100)+1 <= *a +} + +func canaryingSC(js string) string { + if js == "" { + return "" + } + var rcs []rawChoice + err := json.Unmarshal([]byte(js), &rcs) + if err != nil { + grpclog.Warningf("grpc: failed to parse service config json string due to %v.\n", err) + return "" + } + cliHostname, err := os.Hostname() + if err != nil { + grpclog.Warningf("grpc: failed to get client hostname due to %v.\n", err) + return "" + } + var sc string + for _, c := range rcs { + if !containsString(c.ClientLanguage, golang) || + !chosenByPercentage(c.Percentage) || + !containsString(c.ClientHostName, cliHostname) || + c.ServiceConfig == nil { + continue + } + sc = string(*c.ServiceConfig) + break + } + return sc +} diff --git a/vendor/google.golang.org/grpc/naming/go17_test.go b/vendor/google.golang.org/grpc/resolver/dns/go17.go similarity index 65% rename from vendor/google.golang.org/grpc/naming/go17_test.go rename to vendor/google.golang.org/grpc/resolver/dns/go17.go index d1de221a5e..b466bc8f6d 100644 --- a/vendor/google.golang.org/grpc/naming/go17_test.go +++ b/vendor/google.golang.org/grpc/resolver/dns/go17.go @@ -1,4 +1,4 @@ -// +build go1.7, !go1.8 +// +build go1.6, !go1.8 /* * @@ -18,7 +18,7 @@ * */ -package naming +package dns import ( "net" @@ -26,17 +26,10 @@ import ( "golang.org/x/net/context" ) -func replaceNetFunc() func() { - oldLookupHost := lookupHost - oldLookupSRV := lookupSRV - lookupHost = func(ctx context.Context, host string) ([]string, error) { - return hostLookup(host) +var ( + lookupHost = func(ctx context.Context, host string) ([]string, error) { return net.LookupHost(host) } + lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { + return net.LookupSRV(service, proto, name) } - lookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error) { - return srvLookup(service, proto, name) - } - return func() { - lookupHost = oldLookupHost - lookupSRV = oldLookupSRV - } -} + lookupTXT = func(ctx context.Context, name string) ([]string, error) { return net.LookupTXT(name) } +) diff --git a/vendor/google.golang.org/grpc/backoff_test.go b/vendor/google.golang.org/grpc/resolver/dns/go18.go similarity index 70% rename from vendor/google.golang.org/grpc/backoff_test.go rename to vendor/google.golang.org/grpc/resolver/dns/go18.go index 37e8e3f62b..fa34f14cad 100644 --- a/vendor/google.golang.org/grpc/backoff_test.go +++ b/vendor/google.golang.org/grpc/resolver/dns/go18.go @@ -1,3 +1,5 @@ +// +build go1.8 + /* * * Copyright 2017 gRPC authors. @@ -16,14 +18,12 @@ * */ -package grpc +package dns -import "testing" +import "net" -func TestBackoffConfigDefaults(t *testing.T) { - b := BackoffConfig{} - setDefaults(&b) - if b != DefaultBackoffConfig { - t.Fatalf("expected BackoffConfig to pickup default parameters: %v != %v", b, DefaultBackoffConfig) - } -} +var ( + lookupHost = net.DefaultResolver.LookupHost + lookupSRV = net.DefaultResolver.LookupSRV + lookupTXT = net.DefaultResolver.LookupTXT +) diff --git a/vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go b/vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go new file mode 100644 index 0000000000..b76010d74d --- /dev/null +++ b/vendor/google.golang.org/grpc/resolver/passthrough/passthrough.go @@ -0,0 +1,57 @@ +/* + * + * Copyright 2017 gRPC 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 passthrough implements a pass-through resolver. It sends the target +// name without scheme back to gRPC as resolved address. +package passthrough + +import "google.golang.org/grpc/resolver" + +const scheme = "passthrough" + +type passthroughBuilder struct{} + +func (*passthroughBuilder) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOption) (resolver.Resolver, error) { + r := &passthroughResolver{ + target: target, + cc: cc, + } + r.start() + return r, nil +} + +func (*passthroughBuilder) Scheme() string { + return scheme +} + +type passthroughResolver struct { + target resolver.Target + cc resolver.ClientConn +} + +func (r *passthroughResolver) start() { + r.cc.NewAddress([]resolver.Address{{Addr: r.target.Endpoint}}) +} + +func (*passthroughResolver) ResolveNow(o resolver.ResolveNowOption) {} + +func (*passthroughResolver) Close() {} + +func init() { + resolver.Register(&passthroughBuilder{}) +} diff --git a/vendor/google.golang.org/grpc/resolver/resolver.go b/vendor/google.golang.org/grpc/resolver/resolver.go index 49307e8fe9..506afac88a 100644 --- a/vendor/google.golang.org/grpc/resolver/resolver.go +++ b/vendor/google.golang.org/grpc/resolver/resolver.go @@ -24,42 +24,42 @@ var ( // m is a map from scheme to resolver builder. m = make(map[string]Builder) // defaultScheme is the default scheme to use. - defaultScheme string + defaultScheme = "passthrough" ) // TODO(bar) install dns resolver in init(){}. -// Register registers the resolver builder to the resolver map. -// b.Scheme will be used as the scheme registered with this builder. +// Register registers the resolver builder to the resolver map. b.Scheme will be +// used as the scheme registered with this builder. +// +// NOTE: this function must only be called during initialization time (i.e. in +// an init() function), and is not thread-safe. If multiple Resolvers are +// registered with the same name, the one registered last will take effect. func Register(b Builder) { m[b.Scheme()] = b } // Get returns the resolver builder registered with the given scheme. -// If no builder is register with the scheme, the default scheme will -// be used. -// If the default scheme is not modified, "dns" will be the default -// scheme, and the preinstalled dns resolver will be used. -// If the default scheme is modified, and a resolver is registered with -// the scheme, that resolver will be returned. -// If the default scheme is modified, and no resolver is registered with -// the scheme, nil will be returned. +// +// If no builder is register with the scheme, nil will be returned. func Get(scheme string) Builder { if b, ok := m[scheme]; ok { return b } - if b, ok := m[defaultScheme]; ok { - return b - } return nil } // SetDefaultScheme sets the default scheme that will be used. -// The default default scheme is "dns". +// The default default scheme is "passthrough". func SetDefaultScheme(scheme string) { defaultScheme = scheme } +// GetDefaultScheme gets the default scheme that will be used. +func GetDefaultScheme() string { + return defaultScheme +} + // AddressType indicates the address type returned by name resolution. type AddressType uint8 @@ -78,7 +78,9 @@ type Address struct { // Type is the type of this address. Type AddressType // ServerName is the name of this address. - // It's the name of the grpc load balancer, which will be used for authentication. + // + // e.g. if Type is GRPCLB, ServerName should be the name of the remote load + // balancer, not the name of the backend. ServerName string // Metadata is the information associated with Addr, which may be used // to make load balancing decision. @@ -88,10 +90,17 @@ type Address struct { // BuildOption includes additional information for the builder to create // the resolver. type BuildOption struct { + // DisableServiceConfig indicates whether resolver should fetch service config data. + DisableServiceConfig bool } // ClientConn contains the callbacks for resolver to notify any updates // to the gRPC ClientConn. +// +// This interface is to be implemented by gRPC. Users should not need a +// brand new implementation of this interface. For the situations like +// testing, the new implementation should embed this interface. This allows +// gRPC to add new methods to this interface. type ClientConn interface { // NewAddress is called by resolver to notify ClientConn a new list // of resolved addresses. @@ -128,8 +137,10 @@ type ResolveNowOption struct{} // Resolver watches for the updates on the specified target. // Updates include address updates and service config updates. type Resolver interface { - // ResolveNow will be called by gRPC to try to resolve the target name again. - // It's just a hint, resolver can ignore this if it's not necessary. + // ResolveNow will be called by gRPC to try to resolve the target name + // again. It's just a hint, resolver can ignore this if it's not necessary. + // + // It could be called multiple times concurrently. ResolveNow(ResolveNowOption) // Close closes the resolver. Close() diff --git a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go index 7d53964d09..1b493db2e6 100644 --- a/vendor/google.golang.org/grpc/resolver_conn_wrapper.go +++ b/vendor/google.golang.org/grpc/resolver_conn_wrapper.go @@ -19,6 +19,7 @@ package grpc import ( + "fmt" "strings" "google.golang.org/grpc/grpclog" @@ -36,20 +37,30 @@ type ccResolverWrapper struct { } // split2 returns the values from strings.SplitN(s, sep, 2). -// If sep is not found, it returns "", s instead. -func split2(s, sep string) (string, string) { +// If sep is not found, it returns ("", s, false) instead. +func split2(s, sep string) (string, string, bool) { spl := strings.SplitN(s, sep, 2) if len(spl) < 2 { - return "", s + return "", "", false } - return spl[0], spl[1] + return spl[0], spl[1], true } // parseTarget splits target into a struct containing scheme, authority and // endpoint. +// +// If target is not a valid scheme://authority/endpoint, it returns {Endpoint: +// target}. func parseTarget(target string) (ret resolver.Target) { - ret.Scheme, ret.Endpoint = split2(target, "://") - ret.Authority, ret.Endpoint = split2(ret.Endpoint, "/") + var ok bool + ret.Scheme, ret.Endpoint, ok = split2(target, "://") + if !ok { + return resolver.Target{Endpoint: target} + } + ret.Authority, ret.Endpoint, ok = split2(ret.Endpoint, "/") + if !ok { + return resolver.Target{Endpoint: target} + } return ret } @@ -57,18 +68,12 @@ func parseTarget(target string) (ret resolver.Target) { // builder for this scheme. It then builds the resolver and starts the // monitoring goroutine for it. // -// This function could return nil, nil, in tests for old behaviors. -// TODO(bar) never return nil, nil when DNS becomes the default resolver. +// If withResolverBuilder dial option is set, the specified resolver will be +// used instead. func newCCResolverWrapper(cc *ClientConn) (*ccResolverWrapper, error) { - target := parseTarget(cc.target) - grpclog.Infof("dialing to target with scheme: %q", target.Scheme) - - rb := resolver.Get(target.Scheme) + rb := cc.dopts.resolverBuilder if rb == nil { - // TODO(bar) return error when DNS becomes the default (implemented and - // registered by DNS package). - grpclog.Infof("could not get resolver for scheme: %q", target.Scheme) - return nil, nil + return nil, fmt.Errorf("could not get resolver for scheme: %q", cc.parsedTarget.Scheme) } ccr := &ccResolverWrapper{ @@ -79,15 +84,18 @@ func newCCResolverWrapper(cc *ClientConn) (*ccResolverWrapper, error) { } var err error - ccr.resolver, err = rb.Build(target, ccr, resolver.BuildOption{}) + ccr.resolver, err = rb.Build(cc.parsedTarget, ccr, resolver.BuildOption{DisableServiceConfig: cc.dopts.disableServiceConfig}) if err != nil { return nil, err } - go ccr.watcher() return ccr, nil } -// watcher processes address updates and service config updates sequencially. +func (ccr *ccResolverWrapper) start() { + go ccr.watcher() +} + +// watcher processes address updates and service config updates sequentially. // Otherwise, we need to resolve possible races between address and service // config (e.g. they specify different balancer types). func (ccr *ccResolverWrapper) watcher() { @@ -100,20 +108,31 @@ func (ccr *ccResolverWrapper) watcher() { select { case addrs := <-ccr.addrCh: - grpclog.Infof("ccResolverWrapper: sending new addresses to balancer wrapper: %v", addrs) - // TODO(bar switching) this should never be nil. Pickfirst should be default. - if ccr.cc.balancerWrapper != nil { - // TODO(bar switching) create balancer if it's nil? - ccr.cc.balancerWrapper.handleResolvedAddrs(addrs, nil) + select { + case <-ccr.done: + return + default: } + grpclog.Infof("ccResolverWrapper: sending new addresses to cc: %v", addrs) + ccr.cc.handleResolvedAddrs(addrs, nil) case sc := <-ccr.scCh: + select { + case <-ccr.done: + return + default: + } grpclog.Infof("ccResolverWrapper: got new service config: %v", sc) + ccr.cc.handleServiceConfig(sc) case <-ccr.done: return } } } +func (ccr *ccResolverWrapper) resolveNow(o resolver.ResolveNowOption) { + ccr.resolver.ResolveNow(o) +} + func (ccr *ccResolverWrapper) close() { ccr.resolver.Close() close(ccr.done) diff --git a/vendor/google.golang.org/grpc/resolver_conn_wrapper_test.go b/vendor/google.golang.org/grpc/resolver_conn_wrapper_test.go deleted file mode 100644 index 024942301d..0000000000 --- a/vendor/google.golang.org/grpc/resolver_conn_wrapper_test.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 grpc - -import ( - "testing" - - "google.golang.org/grpc/resolver" -) - -func TestParseTarget(t *testing.T) { - for _, test := range []resolver.Target{ - {"", "", ""}, - {"a", "", ""}, - {"", "a", ""}, - {"", "", "a"}, - {"a", "b", ""}, - {"a", "", "b"}, - {"", "a", "b"}, - {"a", "b", "c"}, - {"dns", "a.server.com", "google.com"}, - {"dns", "a.server.com", "google.com"}, - {"dns", "a.server.com", "google.com/?a=b"}, - } { - str := test.Scheme + "://" + test.Authority + "/" + test.Endpoint - got := parseTarget(str) - if got != test { - t.Errorf("parseTarget(%q) = %v, want %v", str, got, test) - } - } -} diff --git a/vendor/google.golang.org/grpc/rpc_util.go b/vendor/google.golang.org/grpc/rpc_util.go index e71c77bb68..69ef3c0b59 100644 --- a/vendor/google.golang.org/grpc/rpc_util.go +++ b/vendor/google.golang.org/grpc/rpc_util.go @@ -21,18 +21,21 @@ package grpc import ( "bytes" "compress/gzip" - stdctx "context" "encoding/binary" + "fmt" "io" "io/ioutil" "math" - "os" + "net/url" + "strings" "sync" "time" "golang.org/x/net/context" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/encoding" + "google.golang.org/grpc/encoding/proto" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" @@ -41,6 +44,8 @@ import ( ) // Compressor defines the interface gRPC uses to compress a message. +// +// Deprecated: use package encoding. type Compressor interface { // Do compresses p into w. Do(w io.Writer, p []byte) error @@ -53,14 +58,34 @@ type gzipCompressor struct { } // NewGZIPCompressor creates a Compressor based on GZIP. +// +// Deprecated: use package encoding/gzip. func NewGZIPCompressor() Compressor { + c, _ := NewGZIPCompressorWithLevel(gzip.DefaultCompression) + return c +} + +// NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead +// of assuming DefaultCompression. +// +// The error returned will be nil if the level is valid. +// +// Deprecated: use package encoding/gzip. +func NewGZIPCompressorWithLevel(level int) (Compressor, error) { + if level < gzip.DefaultCompression || level > gzip.BestCompression { + return nil, fmt.Errorf("grpc: invalid compression level: %d", level) + } return &gzipCompressor{ pool: sync.Pool{ New: func() interface{} { - return gzip.NewWriter(ioutil.Discard) + w, err := gzip.NewWriterLevel(ioutil.Discard, level) + if err != nil { + panic(err) + } + return w }, }, - } + }, nil } func (c *gzipCompressor) Do(w io.Writer, p []byte) error { @@ -78,6 +103,8 @@ func (c *gzipCompressor) Type() string { } // Decompressor defines the interface gRPC uses to decompress a message. +// +// Deprecated: use package encoding. type Decompressor interface { // Do reads the data from r and uncompress them. Do(r io.Reader) ([]byte, error) @@ -90,6 +117,8 @@ type gzipDecompressor struct { } // NewGZIPDecompressor creates a Decompressor based on GZIP. +// +// Deprecated: use package encoding/gzip. func NewGZIPDecompressor() Decompressor { return &gzipDecompressor{} } @@ -124,14 +153,15 @@ func (d *gzipDecompressor) Type() string { // callInfo contains all related configuration and information about an RPC. type callInfo struct { + compressorType string failFast bool - headerMD metadata.MD - trailerMD metadata.MD - peer *peer.Peer + stream *clientStream traceInfo traceInfo // in trace.go maxReceiveMessageSize *int maxSendMessageSize *int creds credentials.PerRPCCredentials + contentSubtype string + codec baseCodec } func defaultCallInfo() *callInfo { @@ -158,81 +188,233 @@ type EmptyCallOption struct{} func (EmptyCallOption) before(*callInfo) error { return nil } func (EmptyCallOption) after(*callInfo) {} -type beforeCall func(c *callInfo) error - -func (o beforeCall) before(c *callInfo) error { return o(c) } -func (o beforeCall) after(c *callInfo) {} - -type afterCall func(c *callInfo) - -func (o afterCall) before(c *callInfo) error { return nil } -func (o afterCall) after(c *callInfo) { o(c) } - // Header returns a CallOptions that retrieves the header metadata // for a unary RPC. func Header(md *metadata.MD) CallOption { - return afterCall(func(c *callInfo) { - *md = c.headerMD - }) + return HeaderCallOption{HeaderAddr: md} +} + +// HeaderCallOption is a CallOption for collecting response header metadata. +// The metadata field will be populated *after* the RPC completes. +// This is an EXPERIMENTAL API. +type HeaderCallOption struct { + HeaderAddr *metadata.MD +} + +func (o HeaderCallOption) before(c *callInfo) error { return nil } +func (o HeaderCallOption) after(c *callInfo) { + if c.stream != nil { + *o.HeaderAddr, _ = c.stream.Header() + } } // Trailer returns a CallOptions that retrieves the trailer metadata // for a unary RPC. func Trailer(md *metadata.MD) CallOption { - return afterCall(func(c *callInfo) { - *md = c.trailerMD - }) + return TrailerCallOption{TrailerAddr: md} +} + +// TrailerCallOption is a CallOption for collecting response trailer metadata. +// The metadata field will be populated *after* the RPC completes. +// This is an EXPERIMENTAL API. +type TrailerCallOption struct { + TrailerAddr *metadata.MD +} + +func (o TrailerCallOption) before(c *callInfo) error { return nil } +func (o TrailerCallOption) after(c *callInfo) { + if c.stream != nil { + *o.TrailerAddr = c.stream.Trailer() + } +} + +// Peer returns a CallOption that retrieves peer information for a unary RPC. +// The peer field will be populated *after* the RPC completes. +func Peer(p *peer.Peer) CallOption { + return PeerCallOption{PeerAddr: p} } -// Peer returns a CallOption that retrieves peer information for a -// unary RPC. -func Peer(peer *peer.Peer) CallOption { - return afterCall(func(c *callInfo) { - if c.peer != nil { - *peer = *c.peer +// PeerCallOption is a CallOption for collecting the identity of the remote +// peer. The peer field will be populated *after* the RPC completes. +// This is an EXPERIMENTAL API. +type PeerCallOption struct { + PeerAddr *peer.Peer +} + +func (o PeerCallOption) before(c *callInfo) error { return nil } +func (o PeerCallOption) after(c *callInfo) { + if c.stream != nil { + if x, ok := peer.FromContext(c.stream.Context()); ok { + *o.PeerAddr = *x } - }) + } } // FailFast configures the action to take when an RPC is attempted on broken -// connections or unreachable servers. If failfast is true, the RPC will fail +// connections or unreachable servers. If failFast is true, the RPC will fail // immediately. Otherwise, the RPC client will block the call until a -// connection is available (or the call is canceled or times out) and will retry -// the call if it fails due to a transient error. Please refer to +// connection is available (or the call is canceled or times out) and will +// retry the call if it fails due to a transient error. gRPC will not retry if +// data was written to the wire unless the server indicates it did not process +// the data. Please refer to // https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md. -// Note: failFast is default to true. +// +// By default, RPCs are "Fail Fast". func FailFast(failFast bool) CallOption { - return beforeCall(func(c *callInfo) error { - c.failFast = failFast - return nil - }) + return FailFastCallOption{FailFast: failFast} +} + +// FailFastCallOption is a CallOption for indicating whether an RPC should fail +// fast or not. +// This is an EXPERIMENTAL API. +type FailFastCallOption struct { + FailFast bool } +func (o FailFastCallOption) before(c *callInfo) error { + c.failFast = o.FailFast + return nil +} +func (o FailFastCallOption) after(c *callInfo) {} + // MaxCallRecvMsgSize returns a CallOption which sets the maximum message size the client can receive. func MaxCallRecvMsgSize(s int) CallOption { - return beforeCall(func(o *callInfo) error { - o.maxReceiveMessageSize = &s - return nil - }) + return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: s} +} + +// MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message +// size the client can receive. +// This is an EXPERIMENTAL API. +type MaxRecvMsgSizeCallOption struct { + MaxRecvMsgSize int } +func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error { + c.maxReceiveMessageSize = &o.MaxRecvMsgSize + return nil +} +func (o MaxRecvMsgSizeCallOption) after(c *callInfo) {} + // MaxCallSendMsgSize returns a CallOption which sets the maximum message size the client can send. func MaxCallSendMsgSize(s int) CallOption { - return beforeCall(func(o *callInfo) error { - o.maxSendMessageSize = &s - return nil - }) + return MaxSendMsgSizeCallOption{MaxSendMsgSize: s} } +// MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message +// size the client can send. +// This is an EXPERIMENTAL API. +type MaxSendMsgSizeCallOption struct { + MaxSendMsgSize int +} + +func (o MaxSendMsgSizeCallOption) before(c *callInfo) error { + c.maxSendMessageSize = &o.MaxSendMsgSize + return nil +} +func (o MaxSendMsgSizeCallOption) after(c *callInfo) {} + // PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials // for a call. func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption { - return beforeCall(func(c *callInfo) error { - c.creds = creds - return nil - }) + return PerRPCCredsCallOption{Creds: creds} +} + +// PerRPCCredsCallOption is a CallOption that indicates the per-RPC +// credentials to use for the call. +// This is an EXPERIMENTAL API. +type PerRPCCredsCallOption struct { + Creds credentials.PerRPCCredentials +} + +func (o PerRPCCredsCallOption) before(c *callInfo) error { + c.creds = o.Creds + return nil +} +func (o PerRPCCredsCallOption) after(c *callInfo) {} + +// UseCompressor returns a CallOption which sets the compressor used when +// sending the request. If WithCompressor is also set, UseCompressor has +// higher priority. +// +// This API is EXPERIMENTAL. +func UseCompressor(name string) CallOption { + return CompressorCallOption{CompressorType: name} +} + +// CompressorCallOption is a CallOption that indicates the compressor to use. +// This is an EXPERIMENTAL API. +type CompressorCallOption struct { + CompressorType string +} + +func (o CompressorCallOption) before(c *callInfo) error { + c.compressorType = o.CompressorType + return nil +} +func (o CompressorCallOption) after(c *callInfo) {} + +// CallContentSubtype returns a CallOption that will set the content-subtype +// for a call. For example, if content-subtype is "json", the Content-Type over +// the wire will be "application/grpc+json". The content-subtype is converted +// to lowercase before being included in Content-Type. See Content-Type on +// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for +// more details. +// +// If CallCustomCodec is not also used, the content-subtype will be used to +// look up the Codec to use in the registry controlled by RegisterCodec. See +// the documentation on RegisterCodec for details on registration. The lookup +// of content-subtype is case-insensitive. If no such Codec is found, the call +// will result in an error with code codes.Internal. +// +// If CallCustomCodec is also used, that Codec will be used for all request and +// response messages, with the content-subtype set to the given contentSubtype +// here for requests. +func CallContentSubtype(contentSubtype string) CallOption { + return ContentSubtypeCallOption{ContentSubtype: strings.ToLower(contentSubtype)} +} + +// ContentSubtypeCallOption is a CallOption that indicates the content-subtype +// used for marshaling messages. +// This is an EXPERIMENTAL API. +type ContentSubtypeCallOption struct { + ContentSubtype string } +func (o ContentSubtypeCallOption) before(c *callInfo) error { + c.contentSubtype = o.ContentSubtype + return nil +} +func (o ContentSubtypeCallOption) after(c *callInfo) {} + +// CallCustomCodec returns a CallOption that will set the given Codec to be +// used for all request and response messages for a call. The result of calling +// String() will be used as the content-subtype in a case-insensitive manner. +// +// See Content-Type on +// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for +// more details. Also see the documentation on RegisterCodec and +// CallContentSubtype for more details on the interaction between Codec and +// content-subtype. +// +// This function is provided for advanced users; prefer to use only +// CallContentSubtype to select a registered codec instead. +func CallCustomCodec(codec Codec) CallOption { + return CustomCodecCallOption{Codec: codec} +} + +// CustomCodecCallOption is a CallOption that indicates the codec used for +// marshaling messages. +// This is an EXPERIMENTAL API. +type CustomCodecCallOption struct { + Codec Codec +} + +func (o CustomCodecCallOption) before(c *callInfo) error { + c.codec = o.Codec + return nil +} +func (o CustomCodecCallOption) after(c *callInfo) {} + // The format of the payload: compressed or not? type payloadFormat uint8 @@ -248,8 +430,8 @@ type parser struct { // error types. r io.Reader - // The header of a gRPC message. Find more detail - // at https://grpc.io/docs/guides/wire.html. + // The header of a gRPC message. Find more detail at + // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md header [5]byte } @@ -277,8 +459,11 @@ func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byt if length == 0 { return pf, nil, nil } - if length > uint32(maxReceiveMessageSize) { - return 0, nil, Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize) + if int64(length) > int64(maxInt) { + return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt) + } + if int(length) > maxReceiveMessageSize { + return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize) } // TODO(bradfitz,zhaoq): garbage. reuse buffer after proto decoding instead // of making it for each message: @@ -294,18 +479,21 @@ func (p *parser) recvMsg(maxReceiveMessageSize int) (pf payloadFormat, msg []byt // encode serializes msg and returns a buffer of message header and a buffer of msg. // If msg is nil, it generates the message header and an empty msg buffer. -func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer, outPayload *stats.OutPayload) ([]byte, []byte, error) { - var b []byte +// TODO(ddyihai): eliminate extra Compressor parameter. +func encode(c baseCodec, msg interface{}, cp Compressor, outPayload *stats.OutPayload, compressor encoding.Compressor) ([]byte, []byte, error) { + var ( + b []byte + cbuf *bytes.Buffer + ) const ( payloadLen = 1 sizeLen = 4 ) - if msg != nil { var err error b, err = c.Marshal(msg) if err != nil { - return nil, nil, Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error()) + return nil, nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error()) } if outPayload != nil { outPayload.Payload = msg @@ -313,24 +501,35 @@ func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer, outPayl outPayload.Data = b outPayload.Length = len(b) } - if cp != nil { - if err := cp.Do(cbuf, b); err != nil { - return nil, nil, Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) + if compressor != nil || cp != nil { + cbuf = new(bytes.Buffer) + // Has compressor, check Compressor is set by UseCompressor first. + if compressor != nil { + z, _ := compressor.Compress(cbuf) + if _, err := z.Write(b); err != nil { + return nil, nil, status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) + } + z.Close() + } else { + // If Compressor is not set by UseCompressor, use default Compressor + if err := cp.Do(cbuf, b); err != nil { + return nil, nil, status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) + } } b = cbuf.Bytes() } } - if uint(len(b)) > math.MaxUint32 { - return nil, nil, Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b)) + return nil, nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", len(b)) } bufHeader := make([]byte, payloadLen+sizeLen) - if cp == nil { - bufHeader[0] = byte(compressionNone) - } else { + if compressor != nil || cp != nil { bufHeader[0] = byte(compressionMade) + } else { + bufHeader[0] = byte(compressionNone) } + // Write length of b into buf binary.BigEndian.PutUint32(bufHeader[payloadLen:], uint32(len(b))) if outPayload != nil { @@ -339,20 +538,26 @@ func encode(c Codec, msg interface{}, cp Compressor, cbuf *bytes.Buffer, outPayl return bufHeader, b, nil } -func checkRecvPayload(pf payloadFormat, recvCompress string, dc Decompressor) error { +func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool) *status.Status { switch pf { case compressionNone: case compressionMade: - if dc == nil || recvCompress != dc.Type() { - return Errorf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress) + if recvCompress == "" || recvCompress == encoding.Identity { + return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding") + } + if !haveCompressor { + return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress) } default: - return Errorf(codes.Internal, "grpc: received unexpected payload format %d", pf) + return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf) } return nil } -func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, inPayload *stats.InPayload) error { +// For the two compressor parameters, both should not be set, but if they are, +// dc takes precedence over compressor. +// TODO(dfawley): wrap the old compressor/decompressor using the new API? +func recv(p *parser, c baseCodec, s *transport.Stream, dc Decompressor, m interface{}, maxReceiveMessageSize int, inPayload *stats.InPayload, compressor encoding.Compressor) error { pf, d, err := p.recvMsg(maxReceiveMessageSize) if err != nil { return err @@ -360,22 +565,37 @@ func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{ if inPayload != nil { inPayload.WireLength = len(d) } - if err := checkRecvPayload(pf, s.RecvCompress(), dc); err != nil { - return err + + if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil); st != nil { + return st.Err() } + if pf == compressionMade { - d, err = dc.Do(bytes.NewReader(d)) - if err != nil { - return Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) + // To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor, + // use this decompressor as the default. + if dc != nil { + d, err = dc.Do(bytes.NewReader(d)) + if err != nil { + return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) + } + } else { + dcReader, err := compressor.Decompress(bytes.NewReader(d)) + if err != nil { + return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) + } + d, err = ioutil.ReadAll(dcReader) + if err != nil { + return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) + } } } if len(d) > maxReceiveMessageSize { // TODO: Revisit the error code. Currently keep it consistent with java // implementation. - return Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(d), maxReceiveMessageSize) + return status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(d), maxReceiveMessageSize) } if err := c.Unmarshal(d, m); err != nil { - return Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err) + return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message %v", err) } if inPayload != nil { inPayload.RecvTime = time.Now() @@ -388,9 +608,7 @@ func recv(p *parser, c Codec, s *transport.Stream, dc Decompressor, m interface{ } type rpcInfo struct { - failfast bool - bytesSent bool - bytesReceived bool + failfast bool } type rpcInfoContextKey struct{} @@ -404,69 +622,10 @@ func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) { return } -func updateRPCInfoInContext(ctx context.Context, s rpcInfo) { - if ss, ok := rpcInfoFromContext(ctx); ok { - ss.bytesReceived = s.bytesReceived - ss.bytesSent = s.bytesSent - } - return -} - -// toRPCErr converts an error into an error from the status package. -func toRPCErr(err error) error { - if _, ok := status.FromError(err); ok { - return err - } - switch e := err.(type) { - case transport.StreamError: - return status.Error(e.Code, e.Desc) - case transport.ConnectionError: - return status.Error(codes.Unavailable, e.Desc) - default: - switch err { - case context.DeadlineExceeded, stdctx.DeadlineExceeded: - return status.Error(codes.DeadlineExceeded, err.Error()) - case context.Canceled, stdctx.Canceled: - return status.Error(codes.Canceled, err.Error()) - case ErrClientConnClosing: - return status.Error(codes.FailedPrecondition, err.Error()) - } - } - return status.Error(codes.Unknown, err.Error()) -} - -// convertCode converts a standard Go error into its canonical code. Note that -// this is only used to translate the error returned by the server applications. -func convertCode(err error) codes.Code { - switch err { - case nil: - return codes.OK - case io.EOF: - return codes.OutOfRange - case io.ErrClosedPipe, io.ErrNoProgress, io.ErrShortBuffer, io.ErrShortWrite, io.ErrUnexpectedEOF: - return codes.FailedPrecondition - case os.ErrInvalid: - return codes.InvalidArgument - case context.Canceled, stdctx.Canceled: - return codes.Canceled - case context.DeadlineExceeded, stdctx.DeadlineExceeded: - return codes.DeadlineExceeded - } - switch { - case os.IsExist(err): - return codes.AlreadyExists - case os.IsNotExist(err): - return codes.NotFound - case os.IsPermission(err): - return codes.PermissionDenied - } - return codes.Unknown -} - // Code returns the error code for err if it was produced by the rpc system. // Otherwise, it returns codes.Unknown. // -// Deprecated; use status.FromError and Code method instead. +// Deprecated: use status.FromError and Code method instead. func Code(err error) codes.Code { if s, ok := status.FromError(err); ok { return s.Code() @@ -477,7 +636,7 @@ func Code(err error) codes.Code { // ErrorDesc returns the error description of err if it was produced by the rpc system. // Otherwise, it returns err.Error() or empty string when err is nil. // -// Deprecated; use status.FromError and Message method instead. +// Deprecated: use status.FromError and Message method instead. func ErrorDesc(err error) string { if s, ok := status.FromError(err); ok { return s.Message() @@ -488,85 +647,81 @@ func ErrorDesc(err error) string { // Errorf returns an error containing an error code and a description; // Errorf returns nil if c is OK. // -// Deprecated; use status.Errorf instead. +// Deprecated: use status.Errorf instead. func Errorf(c codes.Code, format string, a ...interface{}) error { return status.Errorf(c, format, a...) } -// MethodConfig defines the configuration recommended by the service providers for a -// particular method. -// This is EXPERIMENTAL and subject to change. -type MethodConfig struct { - // WaitForReady indicates whether RPCs sent to this method should wait until - // the connection is ready by default (!failfast). The value specified via the - // gRPC client API will override the value set here. - WaitForReady *bool - // Timeout is the default timeout for RPCs sent to this method. The actual - // deadline used will be the minimum of the value specified here and the value - // set by the application via the gRPC client API. If either one is not set, - // then the other will be used. If neither is set, then the RPC has no deadline. - Timeout *time.Duration - // MaxReqSize is the maximum allowed payload size for an individual request in a - // stream (client->server) in bytes. The size which is measured is the serialized - // payload after per-message compression (but before stream compression) in bytes. - // The actual value used is the minimum of the value specified here and the value set - // by the application via the gRPC client API. If either one is not set, then the other - // will be used. If neither is set, then the built-in default is used. - MaxReqSize *int - // MaxRespSize is the maximum allowed payload size for an individual response in a - // stream (server->client) in bytes. - MaxRespSize *int -} - -// ServiceConfig is provided by the service provider and contains parameters for how -// clients that connect to the service should behave. -// This is EXPERIMENTAL and subject to change. -type ServiceConfig struct { - // LB is the load balancer the service providers recommends. The balancer specified - // via grpc.WithBalancer will override this. - LB Balancer - // Methods contains a map for the methods in this service. - // If there is an exact match for a method (i.e. /service/method) in the map, use the corresponding MethodConfig. - // If there's no exact match, look for the default config for the service (/service/) and use the corresponding MethodConfig if it exists. - // Otherwise, the method has no MethodConfig to use. - Methods map[string]MethodConfig -} - -func min(a, b *int) *int { - if *a < *b { - return a +// setCallInfoCodec should only be called after CallOptions have been applied. +func setCallInfoCodec(c *callInfo) error { + if c.codec != nil { + // codec was already set by a CallOption; use it. + return nil } - return b -} -func getMaxSize(mcMax, doptMax *int, defaultVal int) *int { - if mcMax == nil && doptMax == nil { - return &defaultVal - } - if mcMax != nil && doptMax != nil { - return min(mcMax, doptMax) + if c.contentSubtype == "" { + // No codec specified in CallOptions; use proto by default. + c.codec = encoding.GetCodec(proto.Name) + return nil } - if mcMax != nil { - return mcMax + + // c.contentSubtype is already lowercased in CallContentSubtype + c.codec = encoding.GetCodec(c.contentSubtype) + if c.codec == nil { + return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype) } - return doptMax + return nil } -// SupportPackageIsVersion3 is referenced from generated protocol buffer files. -// The latest support package version is 4. -// SupportPackageIsVersion3 is kept for compatibility. It will be removed in the -// next support package version update. -const SupportPackageIsVersion3 = true +// parseDialTarget returns the network and address to pass to dialer +func parseDialTarget(target string) (net string, addr string) { + net = "tcp" + + m1 := strings.Index(target, ":") + m2 := strings.Index(target, ":/") + + // handle unix:addr which will fail with url.Parse + if m1 >= 0 && m2 < 0 { + if n := target[0:m1]; n == "unix" { + net = n + addr = target[m1+1:] + return net, addr + } + } + if m2 >= 0 { + t, err := url.Parse(target) + if err != nil { + return net, target + } + scheme := t.Scheme + addr = t.Path + if scheme == "unix" { + net = scheme + if addr == "" { + addr = t.Host + } + return net, addr + } + } + + return net, target +} -// SupportPackageIsVersion4 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the grpc package. +// The SupportPackageIsVersion variables are referenced from generated protocol +// buffer files to ensure compatibility with the gRPC version used. The latest +// support package version is 5. +// +// Older versions are kept for compatibility. They may be removed if +// compatibility cannot be maintained. // -// This constant may be renamed in the future if a change in the generated code -// requires a synchronised update of grpc-go and protoc-gen-go. This constant -// should not be referenced from any other code. -const SupportPackageIsVersion4 = true +// These constants should not be referenced from any other code. +const ( + SupportPackageIsVersion3 = true + SupportPackageIsVersion4 = true + SupportPackageIsVersion5 = true +) // Version is the current grpc version. -const Version = "1.7.2" +const Version = "1.12.0" const grpcUA = "grpc-go/" + Version diff --git a/vendor/google.golang.org/grpc/rpc_util_test.go b/vendor/google.golang.org/grpc/rpc_util_test.go deleted file mode 100644 index 23c471e2e4..0000000000 --- a/vendor/google.golang.org/grpc/rpc_util_test.go +++ /dev/null @@ -1,237 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 grpc - -import ( - "bytes" - "io" - "math" - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - perfpb "google.golang.org/grpc/test/codec_perf" - "google.golang.org/grpc/transport" -) - -type fullReader struct { - reader io.Reader -} - -func (f fullReader) Read(p []byte) (int, error) { - return io.ReadFull(f.reader, p) -} - -var _ CallOption = EmptyCallOption{} // ensure EmptyCallOption implements the interface - -func TestSimpleParsing(t *testing.T) { - bigMsg := bytes.Repeat([]byte{'x'}, 1<<24) - for _, test := range []struct { - // input - p []byte - // outputs - err error - b []byte - pt payloadFormat - }{ - {nil, io.EOF, nil, compressionNone}, - {[]byte{0, 0, 0, 0, 0}, nil, nil, compressionNone}, - {[]byte{0, 0, 0, 0, 1, 'a'}, nil, []byte{'a'}, compressionNone}, - {[]byte{1, 0}, io.ErrUnexpectedEOF, nil, compressionNone}, - {[]byte{0, 0, 0, 0, 10, 'a'}, io.ErrUnexpectedEOF, nil, compressionNone}, - // Check that messages with length >= 2^24 are parsed. - {append([]byte{0, 1, 0, 0, 0}, bigMsg...), nil, bigMsg, compressionNone}, - } { - buf := fullReader{bytes.NewReader(test.p)} - parser := &parser{r: buf} - pt, b, err := parser.recvMsg(math.MaxInt32) - if err != test.err || !bytes.Equal(b, test.b) || pt != test.pt { - t.Fatalf("parser{%v}.recvMsg(_) = %v, %v, %v\nwant %v, %v, %v", test.p, pt, b, err, test.pt, test.b, test.err) - } - } -} - -func TestMultipleParsing(t *testing.T) { - // Set a byte stream consists of 3 messages with their headers. - p := []byte{0, 0, 0, 0, 1, 'a', 0, 0, 0, 0, 2, 'b', 'c', 0, 0, 0, 0, 1, 'd'} - b := fullReader{bytes.NewReader(p)} - parser := &parser{r: b} - - wantRecvs := []struct { - pt payloadFormat - data []byte - }{ - {compressionNone, []byte("a")}, - {compressionNone, []byte("bc")}, - {compressionNone, []byte("d")}, - } - for i, want := range wantRecvs { - pt, data, err := parser.recvMsg(math.MaxInt32) - if err != nil || pt != want.pt || !reflect.DeepEqual(data, want.data) { - t.Fatalf("after %d calls, parser{%v}.recvMsg(_) = %v, %v, %v\nwant %v, %v, <nil>", - i, p, pt, data, err, want.pt, want.data) - } - } - - pt, data, err := parser.recvMsg(math.MaxInt32) - if err != io.EOF { - t.Fatalf("after %d recvMsgs calls, parser{%v}.recvMsg(_) = %v, %v, %v\nwant _, _, %v", - len(wantRecvs), p, pt, data, err, io.EOF) - } -} - -func TestEncode(t *testing.T) { - for _, test := range []struct { - // input - msg proto.Message - cp Compressor - // outputs - hdr []byte - data []byte - err error - }{ - {nil, nil, []byte{0, 0, 0, 0, 0}, []byte{}, nil}, - } { - hdr, data, err := encode(protoCodec{}, test.msg, nil, nil, nil) - if err != test.err || !bytes.Equal(hdr, test.hdr) || !bytes.Equal(data, test.data) { - t.Fatalf("encode(_, _, %v, _) = %v, %v, %v\nwant %v, %v, %v", test.cp, hdr, data, err, test.hdr, test.data, test.err) - } - } -} - -func TestCompress(t *testing.T) { - for _, test := range []struct { - // input - data []byte - cp Compressor - dc Decompressor - // outputs - err error - }{ - {make([]byte, 1024), NewGZIPCompressor(), NewGZIPDecompressor(), nil}, - } { - b := new(bytes.Buffer) - if err := test.cp.Do(b, test.data); err != test.err { - t.Fatalf("Compressor.Do(_, %v) = %v, want %v", test.data, err, test.err) - } - if b.Len() >= len(test.data) { - t.Fatalf("The compressor fails to compress data.") - } - if p, err := test.dc.Do(b); err != nil || !bytes.Equal(test.data, p) { - t.Fatalf("Decompressor.Do(%v) = %v, %v, want %v, <nil>", b, p, err, test.data) - } - } -} - -func TestToRPCErr(t *testing.T) { - for _, test := range []struct { - // input - errIn error - // outputs - errOut error - }{ - {transport.StreamError{Code: codes.Unknown, Desc: ""}, status.Error(codes.Unknown, "")}, - {transport.ErrConnClosing, status.Error(codes.Unavailable, transport.ErrConnClosing.Desc)}, - } { - err := toRPCErr(test.errIn) - if _, ok := status.FromError(err); !ok { - t.Fatalf("toRPCErr{%v} returned type %T, want %T", test.errIn, err, status.Error(codes.Unknown, "")) - } - if !reflect.DeepEqual(err, test.errOut) { - t.Fatalf("toRPCErr{%v} = %v \nwant %v", test.errIn, err, test.errOut) - } - } -} - -// bmEncode benchmarks encoding a Protocol Buffer message containing mSize -// bytes. -func bmEncode(b *testing.B, mSize int) { - msg := &perfpb.Buffer{Body: make([]byte, mSize)} - encodeHdr, encodeData, _ := encode(protoCodec{}, msg, nil, nil, nil) - encodedSz := int64(len(encodeHdr) + len(encodeData)) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - encode(protoCodec{}, msg, nil, nil, nil) - } - b.SetBytes(encodedSz) -} - -func BenchmarkEncode1B(b *testing.B) { - bmEncode(b, 1) -} - -func BenchmarkEncode1KiB(b *testing.B) { - bmEncode(b, 1024) -} - -func BenchmarkEncode8KiB(b *testing.B) { - bmEncode(b, 8*1024) -} - -func BenchmarkEncode64KiB(b *testing.B) { - bmEncode(b, 64*1024) -} - -func BenchmarkEncode512KiB(b *testing.B) { - bmEncode(b, 512*1024) -} - -func BenchmarkEncode1MiB(b *testing.B) { - bmEncode(b, 1024*1024) -} - -// bmCompressor benchmarks a compressor of a Protocol Buffer message containing -// mSize bytes. -func bmCompressor(b *testing.B, mSize int, cp Compressor) { - payload := make([]byte, mSize) - cBuf := bytes.NewBuffer(make([]byte, mSize)) - b.ReportAllocs() - b.ResetTimer() - for i := 0; i < b.N; i++ { - cp.Do(cBuf, payload) - cBuf.Reset() - } -} - -func BenchmarkGZIPCompressor1B(b *testing.B) { - bmCompressor(b, 1, NewGZIPCompressor()) -} - -func BenchmarkGZIPCompressor1KiB(b *testing.B) { - bmCompressor(b, 1024, NewGZIPCompressor()) -} - -func BenchmarkGZIPCompressor8KiB(b *testing.B) { - bmCompressor(b, 8*1024, NewGZIPCompressor()) -} - -func BenchmarkGZIPCompressor64KiB(b *testing.B) { - bmCompressor(b, 64*1024, NewGZIPCompressor()) -} - -func BenchmarkGZIPCompressor512KiB(b *testing.B) { - bmCompressor(b, 512*1024, NewGZIPCompressor()) -} - -func BenchmarkGZIPCompressor1MiB(b *testing.B) { - bmCompressor(b, 1024*1024, NewGZIPCompressor()) -} diff --git a/vendor/google.golang.org/grpc/server.go b/vendor/google.golang.org/grpc/server.go index 7c882dbe6d..4969331cb3 100644 --- a/vendor/google.golang.org/grpc/server.go +++ b/vendor/google.golang.org/grpc/server.go @@ -32,11 +32,17 @@ import ( "sync" "time" + "io/ioutil" + "golang.org/x/net/context" "golang.org/x/net/http2" "golang.org/x/net/trace" + + "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/encoding" + "google.golang.org/grpc/encoding/proto" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal" "google.golang.org/grpc/keepalive" @@ -89,18 +95,28 @@ type Server struct { conns map[io.Closer]bool serve bool drain bool - ctx context.Context - cancel context.CancelFunc - // A CondVar to let GracefulStop() blocks until all the pending RPCs are finished - // and all the transport goes away. - cv *sync.Cond + cv *sync.Cond // signaled when connections close for GracefulStop m map[string]*service // service name -> service info events trace.EventLog + + quit chan struct{} + done chan struct{} + quitOnce sync.Once + doneOnce sync.Once + channelzRemoveOnce sync.Once + serveWG sync.WaitGroup // counts active Serve goroutines for GracefulStop + + channelzID int64 // channelz unique identification number + czmu sync.RWMutex + callsStarted int64 + callsFailed int64 + callsSucceeded int64 + lastCallStartedTime time.Time } type options struct { creds credentials.TransportCredentials - codec Codec + codec baseCodec cp Compressor dc Decompressor unaryInt UnaryServerInterceptor @@ -118,11 +134,13 @@ type options struct { initialConnWindowSize int32 writeBufferSize int readBufferSize int + connectionTimeout time.Duration } var defaultServerOptions = options{ maxReceiveMessageSize: defaultServerMaxReceiveMessageSize, maxSendMessageSize: defaultServerMaxSendMessageSize, + connectionTimeout: 120 * time.Second, } // A ServerOption sets options such as credentials, codec and keepalive parameters, etc. @@ -175,20 +193,32 @@ func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption { } // CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling. +// +// This will override any lookups by content-subtype for Codecs registered with RegisterCodec. func CustomCodec(codec Codec) ServerOption { return func(o *options) { o.codec = codec } } -// RPCCompressor returns a ServerOption that sets a compressor for outbound messages. +// RPCCompressor returns a ServerOption that sets a compressor for outbound +// messages. For backward compatibility, all outbound messages will be sent +// using this compressor, regardless of incoming message compression. By +// default, server messages will be sent using the same compressor with which +// request messages were sent. +// +// Deprecated: use encoding.RegisterCompressor instead. func RPCCompressor(cp Compressor) ServerOption { return func(o *options) { o.cp = cp } } -// RPCDecompressor returns a ServerOption that sets a decompressor for inbound messages. +// RPCDecompressor returns a ServerOption that sets a decompressor for inbound +// messages. It has higher priority than decompressors registered via +// encoding.RegisterCompressor. +// +// Deprecated: use encoding.RegisterCompressor instead. func RPCDecompressor(dc Decompressor) ServerOption { return func(o *options) { o.dc = dc @@ -196,7 +226,9 @@ func RPCDecompressor(dc Decompressor) ServerOption { } // MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive. -// If this is not set, gRPC uses the default limit. Deprecated: use MaxRecvMsgSize instead. +// If this is not set, gRPC uses the default limit. +// +// Deprecated: use MaxRecvMsgSize instead. func MaxMsgSize(m int) ServerOption { return MaxRecvMsgSize(m) } @@ -291,6 +323,18 @@ func UnknownServiceHandler(streamHandler StreamHandler) ServerOption { } } +// ConnectionTimeout returns a ServerOption that sets the timeout for +// connection establishment (up to and including HTTP/2 handshaking) for all +// new connections. If this is not set, the default is 120 seconds. A zero or +// negative value will result in an immediate timeout. +// +// This API is EXPERIMENTAL. +func ConnectionTimeout(d time.Duration) ServerOption { + return func(o *options) { + o.connectionTimeout = d + } +} + // NewServer creates a gRPC server which has no service registered and has not // started to accept requests yet. func NewServer(opt ...ServerOption) *Server { @@ -298,22 +342,23 @@ func NewServer(opt ...ServerOption) *Server { for _, o := range opt { o(&opts) } - if opts.codec == nil { - // Set the default codec. - opts.codec = protoCodec{} - } s := &Server{ lis: make(map[net.Listener]bool), opts: opts, conns: make(map[io.Closer]bool), m: make(map[string]*service), + quit: make(chan struct{}), + done: make(chan struct{}), } s.cv = sync.NewCond(&s.mu) - s.ctx, s.cancel = context.WithCancel(context.Background()) if EnableTracing { _, file, line, _ := runtime.Caller(1) s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line)) } + + if channelz.IsOn() { + s.channelzID = channelz.RegisterServer(s, "") + } return s } @@ -418,11 +463,9 @@ func (s *Server) GetServiceInfo() map[string]ServiceInfo { return ret } -var ( - // ErrServerStopped indicates that the operation is now illegal because of - // the server being stopped. - ErrServerStopped = errors.New("grpc: the server has been stopped") -) +// ErrServerStopped indicates that the operation is now illegal because of +// the server being stopped. +var ErrServerStopped = errors.New("grpc: the server has been stopped") func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) { if s.opts.creds == nil { @@ -431,28 +474,66 @@ func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credenti return s.opts.creds.ServerHandshake(rawConn) } +type listenSocket struct { + net.Listener + channelzID int64 +} + +func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric { + return &channelz.SocketInternalMetric{ + LocalAddr: l.Listener.Addr(), + } +} + +func (l *listenSocket) Close() error { + err := l.Listener.Close() + if channelz.IsOn() { + channelz.RemoveEntry(l.channelzID) + } + return err +} + // Serve accepts incoming connections on the listener lis, creating a new // ServerTransport and service goroutine for each. The service goroutines // read gRPC requests and then call the registered handlers to reply to them. // Serve returns when lis.Accept fails with fatal errors. lis will be closed when // this method returns. -// Serve always returns non-nil error. +// Serve will return a non-nil error unless Stop or GracefulStop is called. func (s *Server) Serve(lis net.Listener) error { s.mu.Lock() s.printf("serving") s.serve = true if s.lis == nil { + // Serve called after Stop or GracefulStop. s.mu.Unlock() lis.Close() return ErrServerStopped } - s.lis[lis] = true + + s.serveWG.Add(1) + defer func() { + s.serveWG.Done() + select { + // Stop or GracefulStop called; block until done and return nil. + case <-s.quit: + <-s.done + default: + } + }() + + ls := &listenSocket{Listener: lis} + s.lis[ls] = true + + if channelz.IsOn() { + ls.channelzID = channelz.RegisterListenSocket(ls, s.channelzID, "") + } s.mu.Unlock() + defer func() { s.mu.Lock() - if s.lis != nil && s.lis[lis] { - lis.Close() - delete(s.lis, lis) + if s.lis != nil && s.lis[ls] { + ls.Close() + delete(s.lis, ls) } s.mu.Unlock() }() @@ -479,36 +560,52 @@ func (s *Server) Serve(lis net.Listener) error { timer := time.NewTimer(tempDelay) select { case <-timer.C: - case <-s.ctx.Done(): + case <-s.quit: + timer.Stop() + return nil } - timer.Stop() continue } s.mu.Lock() s.printf("done serving; Accept = %v", err) s.mu.Unlock() + + select { + case <-s.quit: + return nil + default: + } return err } tempDelay = 0 - // Start a new goroutine to deal with rawConn - // so we don't stall this Accept loop goroutine. - go s.handleRawConn(rawConn) + // Start a new goroutine to deal with rawConn so we don't stall this Accept + // loop goroutine. + // + // Make sure we account for the goroutine so GracefulStop doesn't nil out + // s.conns before this conn can be added. + s.serveWG.Add(1) + go func() { + s.handleRawConn(rawConn) + s.serveWG.Done() + }() } } -// handleRawConn is run in its own goroutine and handles a just-accepted -// connection that has not had any I/O performed on it yet. +// handleRawConn forks a goroutine to handle a just-accepted connection that +// has not had any I/O performed on it yet. func (s *Server) handleRawConn(rawConn net.Conn) { + rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout)) conn, authInfo, err := s.useTransportAuthenticator(rawConn) if err != nil { s.mu.Lock() s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err) s.mu.Unlock() grpclog.Warningf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err) - // If serverHandShake returns ErrConnDispatched, keep rawConn open. + // If serverHandshake returns ErrConnDispatched, keep rawConn open. if err != credentials.ErrConnDispatched { rawConn.Close() } + rawConn.SetDeadline(time.Time{}) return } @@ -520,19 +617,33 @@ func (s *Server) handleRawConn(rawConn net.Conn) { } s.mu.Unlock() + var serve func() + c := conn.(io.Closer) if s.opts.useHandlerImpl { - s.serveUsingHandler(conn) + serve = func() { s.serveUsingHandler(conn) } } else { - s.serveHTTP2Transport(conn, authInfo) + // Finish handshaking (HTTP2) + st := s.newHTTP2Transport(conn, authInfo) + if st == nil { + return + } + c = st + serve = func() { s.serveStreams(st) } } + + rawConn.SetDeadline(time.Time{}) + if !s.addConn(c) { + return + } + go func() { + serve() + s.removeConn(c) + }() } -// serveHTTP2Transport sets up a http/2 transport (using the -// gRPC http2 server transport in transport/http2_server.go) and -// serves streams on it. -// This is run in its own goroutine (it does network I/O in -// transport.NewServerTransport). -func (s *Server) serveHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) { +// newHTTP2Transport sets up a http/2 transport (using the +// gRPC http2 server transport in transport/http2_server.go). +func (s *Server) newHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) transport.ServerTransport { config := &transport.ServerConfig{ MaxStreams: s.opts.maxConcurrentStreams, AuthInfo: authInfo, @@ -544,6 +655,7 @@ func (s *Server) serveHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) InitialConnWindowSize: s.opts.initialConnWindowSize, WriteBufferSize: s.opts.writeBufferSize, ReadBufferSize: s.opts.readBufferSize, + ChannelzParentID: s.channelzID, } st, err := transport.NewServerTransport("http2", c, config) if err != nil { @@ -552,17 +664,13 @@ func (s *Server) serveHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) s.mu.Unlock() c.Close() grpclog.Warningln("grpc: Server.Serve failed to create ServerTransport: ", err) - return - } - if !s.addConn(st) { - st.Close() - return + return nil } - s.serveStreams(st) + + return st } func (s *Server) serveStreams(st transport.ServerTransport) { - defer s.removeConn(st) defer st.Close() var wg sync.WaitGroup st.HandleStreams(func(stream *transport.Stream) { @@ -596,11 +704,6 @@ var _ http.Handler = (*Server)(nil) // // conn is the *tls.Conn that's already been authenticated. func (s *Server) serveUsingHandler(conn net.Conn) { - if !s.addConn(conn) { - conn.Close() - return - } - defer s.removeConn(conn) h2s := &http2.Server{ MaxConcurrentStreams: s.opts.maxConcurrentStreams, } @@ -634,13 +737,12 @@ func (s *Server) serveUsingHandler(conn net.Conn) { // available through grpc-go's HTTP/2 server, and it is currently EXPERIMENTAL // and subject to change. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { - st, err := transport.NewServerHandlerTransport(w, r) + st, err := transport.NewServerHandlerTransport(w, r, s.opts.statsHandler) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if !s.addConn(st) { - st.Close() return } defer s.removeConn(st) @@ -670,9 +772,15 @@ func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Strea func (s *Server) addConn(c io.Closer) bool { s.mu.Lock() defer s.mu.Unlock() - if s.conns == nil || s.drain { + if s.conns == nil { + c.Close() return false } + if s.drain { + // Transport added after we drained our existing conns: drain it + // immediately. + c.(transport.ServerTransport).Drain() + } s.conns[c] = true return true } @@ -686,18 +794,46 @@ func (s *Server) removeConn(c io.Closer) { } } -func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options) error { +// ChannelzMetric returns ServerInternalMetric of current server. +// This is an EXPERIMENTAL API. +func (s *Server) ChannelzMetric() *channelz.ServerInternalMetric { + s.czmu.RLock() + defer s.czmu.RUnlock() + return &channelz.ServerInternalMetric{ + CallsStarted: s.callsStarted, + CallsSucceeded: s.callsSucceeded, + CallsFailed: s.callsFailed, + LastCallStartedTimestamp: s.lastCallStartedTime, + } +} + +func (s *Server) incrCallsStarted() { + s.czmu.Lock() + s.callsStarted++ + s.lastCallStartedTime = time.Now() + s.czmu.Unlock() +} + +func (s *Server) incrCallsSucceeded() { + s.czmu.Lock() + s.callsSucceeded++ + s.czmu.Unlock() +} + +func (s *Server) incrCallsFailed() { + s.czmu.Lock() + s.callsFailed++ + s.czmu.Unlock() +} + +func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options, comp encoding.Compressor) error { var ( - cbuf *bytes.Buffer outPayload *stats.OutPayload ) - if cp != nil { - cbuf = new(bytes.Buffer) - } if s.opts.statsHandler != nil { outPayload = &stats.OutPayload{} } - hdr, data, err := encode(s.opts.codec, msg, cp, cbuf, outPayload) + hdr, data, err := encode(s.getCodec(stream.ContentSubtype()), msg, cp, outPayload, comp) if err != nil { grpclog.Errorln("grpc: server failed to encode response: ", err) return err @@ -714,15 +850,27 @@ func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Str } func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) { + if channelz.IsOn() { + s.incrCallsStarted() + defer func() { + if err != nil && err != io.EOF { + s.incrCallsFailed() + } else { + s.incrCallsSucceeded() + } + }() + } sh := s.opts.statsHandler if sh != nil { + beginTime := time.Now() begin := &stats.Begin{ - BeginTime: time.Now(), + BeginTime: beginTime, } sh.HandleRPC(stream.Context(), begin) defer func() { end := &stats.End{ - EndTime: time.Now(), + BeginTime: beginTime, + EndTime: time.Now(), } if err != nil && err != io.EOF { end.Error = toRPCErr(err) @@ -741,10 +889,43 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } }() } + + // comp and cp are used for compression. decomp and dc are used for + // decompression. If comp and decomp are both set, they are the same; + // however they are kept separate to ensure that at most one of the + // compressor/decompressor variable pairs are set for use later. + var comp, decomp encoding.Compressor + var cp Compressor + var dc Decompressor + + // If dc is set and matches the stream's compression, use it. Otherwise, try + // to find a matching registered compressor for decomp. + if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc { + dc = s.opts.dc + } else if rc != "" && rc != encoding.Identity { + decomp = encoding.GetCompressor(rc) + if decomp == nil { + st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) + t.WriteStatus(stream, st) + return st.Err() + } + } + + // If cp is set, use it. Otherwise, attempt to compress the response using + // the incoming message compression method. + // + // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. if s.opts.cp != nil { - // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. - stream.SetSendCompress(s.opts.cp.Type()) + cp = s.opts.cp + stream.SetSendCompress(cp.Type()) + } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { + // Legacy compressor not specified; attempt to respond with same encoding. + comp = encoding.GetCompressor(rc) + if comp != nil { + stream.SetSendCompress(rc) + } } + p := &parser{r: stream} pf, req, err := p.recvMsg(s.opts.maxReceiveMessageSize) if err == io.EOF { @@ -752,7 +933,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. return err } if err == io.ErrUnexpectedEOF { - err = Errorf(codes.Internal, io.ErrUnexpectedEOF.Error()) + err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error()) } if err != nil { if st, ok := status.FromError(err); ok { @@ -773,19 +954,14 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } return err } - - if err := checkRecvPayload(pf, stream.RecvCompress(), s.opts.dc); err != nil { - if st, ok := status.FromError(err); ok { - if e := t.WriteStatus(stream, st); e != nil { - grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) - } - return err - } - if e := t.WriteStatus(stream, status.New(codes.Internal, err.Error())); e != nil { + if channelz.IsOn() { + t.IncrMsgRecv() + } + if st := checkRecvPayload(pf, stream.RecvCompress(), dc != nil || decomp != nil); st != nil { + if e := t.WriteStatus(stream, st); e != nil { grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e) } - - // TODO checkRecvPayload always return RPC error. Add a return here if necessary. + return st.Err() } var inPayload *stats.InPayload if sh != nil { @@ -799,9 +975,17 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } if pf == compressionMade { var err error - req, err = s.opts.dc.Do(bytes.NewReader(req)) - if err != nil { - return Errorf(codes.Internal, err.Error()) + if dc != nil { + req, err = dc.Do(bytes.NewReader(req)) + if err != nil { + return status.Errorf(codes.Internal, err.Error()) + } + } else { + tmp, _ := decomp.Decompress(bytes.NewReader(req)) + req, err = ioutil.ReadAll(tmp) + if err != nil { + return status.Errorf(codes.Internal, "grpc: failed to decompress the received message %v", err) + } } } if len(req) > s.opts.maxReceiveMessageSize { @@ -809,7 +993,7 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. // java implementation. return status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(req), s.opts.maxReceiveMessageSize) } - if err := s.opts.codec.Unmarshal(req, v); err != nil { + if err := s.getCodec(stream.ContentSubtype()).Unmarshal(req, v); err != nil { return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err) } if inPayload != nil { @@ -823,12 +1007,13 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } return nil } - reply, appErr := md.Handler(srv.server, stream.Context(), df, s.opts.unaryInt) + ctx := NewContextWithServerTransportStream(stream.Context(), stream) + reply, appErr := md.Handler(srv.server, ctx, df, s.opts.unaryInt) if appErr != nil { appStatus, ok := status.FromError(appErr) if !ok { // Convert appErr if it is not a grpc status error. - appErr = status.Error(convertCode(appErr), appErr.Error()) + appErr = status.Error(codes.Unknown, appErr.Error()) appStatus, _ = status.FromError(appErr) } if trInfo != nil { @@ -847,7 +1032,8 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. Last: true, Delay: false, } - if err := s.sendResponse(t, stream, reply, s.opts.cp, opts); err != nil { + + if err := s.sendResponse(t, stream, reply, cp, opts, comp); err != nil { if err == io.EOF { // The entire stream is done (for unary RPC only). return err @@ -870,6 +1056,9 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } return err } + if channelz.IsOn() { + t.IncrMsgSent() + } if trInfo != nil { trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true) } @@ -880,15 +1069,27 @@ func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport. } func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) { + if channelz.IsOn() { + s.incrCallsStarted() + defer func() { + if err != nil && err != io.EOF { + s.incrCallsFailed() + } else { + s.incrCallsSucceeded() + } + }() + } sh := s.opts.statsHandler if sh != nil { + beginTime := time.Now() begin := &stats.Begin{ - BeginTime: time.Now(), + BeginTime: beginTime, } sh.HandleRPC(stream.Context(), begin) defer func() { end := &stats.End{ - EndTime: time.Now(), + BeginTime: beginTime, + EndTime: time.Now(), } if err != nil && err != io.EOF { end.Error = toRPCErr(err) @@ -896,21 +1097,47 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp sh.HandleRPC(stream.Context(), end) }() } - if s.opts.cp != nil { - stream.SetSendCompress(s.opts.cp.Type()) - } + ctx := NewContextWithServerTransportStream(stream.Context(), stream) ss := &serverStream{ + ctx: ctx, t: t, s: stream, p: &parser{r: stream}, - codec: s.opts.codec, - cp: s.opts.cp, - dc: s.opts.dc, + codec: s.getCodec(stream.ContentSubtype()), maxReceiveMessageSize: s.opts.maxReceiveMessageSize, maxSendMessageSize: s.opts.maxSendMessageSize, trInfo: trInfo, statsHandler: sh, } + + // If dc is set and matches the stream's compression, use it. Otherwise, try + // to find a matching registered compressor for decomp. + if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc { + ss.dc = s.opts.dc + } else if rc != "" && rc != encoding.Identity { + ss.decomp = encoding.GetCompressor(rc) + if ss.decomp == nil { + st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc) + t.WriteStatus(ss.s, st) + return st.Err() + } + } + + // If cp is set, use it. Otherwise, attempt to compress the response using + // the incoming message compression method. + // + // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686. + if s.opts.cp != nil { + ss.cp = s.opts.cp + stream.SetSendCompress(s.opts.cp.Type()) + } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity { + // Legacy compressor not specified; attempt to respond with same encoding. + ss.comp = encoding.GetCompressor(rc) + if ss.comp != nil { + stream.SetSendCompress(rc) + } + } + if trInfo != nil { trInfo.tr.LazyLog(&trInfo.firstLine, false) defer func() { @@ -946,7 +1173,7 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp case transport.StreamError: appStatus = status.New(err.Code, err.Desc) default: - appStatus = status.New(convertCode(appErr), appErr.Error()) + appStatus = status.New(codes.Unknown, appErr.Error()) } appErr = appStatus.Err() } @@ -966,7 +1193,6 @@ func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transp ss.mu.Unlock() } return t.WriteStatus(ss.s, status.New(codes.OK, "")) - } func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) { @@ -1048,12 +1274,65 @@ func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Str } } +// The key to save ServerTransportStream in the context. +type streamKey struct{} + +// NewContextWithServerTransportStream creates a new context from ctx and +// attaches stream to it. +// +// This API is EXPERIMENTAL. +func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context { + return context.WithValue(ctx, streamKey{}, stream) +} + +// ServerTransportStream is a minimal interface that a transport stream must +// implement. This can be used to mock an actual transport stream for tests of +// handler code that use, for example, grpc.SetHeader (which requires some +// stream to be in context). +// +// See also NewContextWithServerTransportStream. +// +// This API is EXPERIMENTAL. +type ServerTransportStream interface { + Method() string + SetHeader(md metadata.MD) error + SendHeader(md metadata.MD) error + SetTrailer(md metadata.MD) error +} + +// ServerTransportStreamFromContext returns the ServerTransportStream saved in +// ctx. Returns nil if the given context has no stream associated with it +// (which implies it is not an RPC invocation context). +// +// This API is EXPERIMENTAL. +func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream { + s, _ := ctx.Value(streamKey{}).(ServerTransportStream) + return s +} + // Stop stops the gRPC server. It immediately closes all open // connections and listeners. // It cancels all active RPCs on the server side and the corresponding // pending RPCs on the client side will get notified by connection // errors. func (s *Server) Stop() { + s.quitOnce.Do(func() { + close(s.quit) + }) + + defer func() { + s.serveWG.Wait() + s.doneOnce.Do(func() { + close(s.done) + }) + }() + + s.channelzRemoveOnce.Do(func() { + if channelz.IsOn() { + channelz.RemoveEntry(s.channelzID) + } + }) + s.mu.Lock() listeners := s.lis s.lis = nil @@ -1071,7 +1350,6 @@ func (s *Server) Stop() { } s.mu.Lock() - s.cancel() if s.events != nil { s.events.Finish() s.events = nil @@ -1083,22 +1361,44 @@ func (s *Server) Stop() { // accepting new connections and RPCs and blocks until all the pending RPCs are // finished. func (s *Server) GracefulStop() { + s.quitOnce.Do(func() { + close(s.quit) + }) + + defer func() { + s.doneOnce.Do(func() { + close(s.done) + }) + }() + + s.channelzRemoveOnce.Do(func() { + if channelz.IsOn() { + channelz.RemoveEntry(s.channelzID) + } + }) s.mu.Lock() - defer s.mu.Unlock() if s.conns == nil { + s.mu.Unlock() return } + for lis := range s.lis { lis.Close() } s.lis = nil - s.cancel() if !s.drain { for c := range s.conns { c.(transport.ServerTransport).Drain() } s.drain = true } + + // Wait for serving threads to be ready to exit. Only then can we be sure no + // new conns will be created. + s.mu.Unlock() + s.serveWG.Wait() + s.mu.Lock() + for len(s.conns) != 0 { s.cv.Wait() } @@ -1107,26 +1407,29 @@ func (s *Server) GracefulStop() { s.events.Finish() s.events = nil } + s.mu.Unlock() } func init() { - internal.TestingCloseConns = func(arg interface{}) { - arg.(*Server).testingCloseConns() - } internal.TestingUseHandlerImpl = func(arg interface{}) { arg.(*Server).opts.useHandlerImpl = true } } -// testingCloseConns closes all existing transports but keeps s.lis -// accepting new connections. -func (s *Server) testingCloseConns() { - s.mu.Lock() - for c := range s.conns { - c.Close() - delete(s.conns, c) +// contentSubtype must be lowercase +// cannot return nil +func (s *Server) getCodec(contentSubtype string) baseCodec { + if s.opts.codec != nil { + return s.opts.codec } - s.mu.Unlock() + if contentSubtype == "" { + return encoding.GetCodec(proto.Name) + } + codec := encoding.GetCodec(contentSubtype) + if codec == nil { + return encoding.GetCodec(proto.Name) + } + return codec } // SetHeader sets the header metadata. @@ -1139,9 +1442,9 @@ func SetHeader(ctx context.Context, md metadata.MD) error { if md.Len() == 0 { return nil } - stream, ok := transport.StreamFromContext(ctx) - if !ok { - return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) + stream := ServerTransportStreamFromContext(ctx) + if stream == nil { + return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) } return stream.SetHeader(md) } @@ -1149,15 +1452,11 @@ func SetHeader(ctx context.Context, md metadata.MD) error { // SendHeader sends header metadata. It may be called at most once. // The provided md and headers set by SetHeader() will be sent. func SendHeader(ctx context.Context, md metadata.MD) error { - stream, ok := transport.StreamFromContext(ctx) - if !ok { - return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) + stream := ServerTransportStreamFromContext(ctx) + if stream == nil { + return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) } - t := stream.ServerTransport() - if t == nil { - grpclog.Fatalf("grpc: SendHeader: %v has no ServerTransport to send header metadata.", stream) - } - if err := t.WriteHeader(stream, md); err != nil { + if err := stream.SendHeader(md); err != nil { return toRPCErr(err) } return nil @@ -1169,9 +1468,19 @@ func SetTrailer(ctx context.Context, md metadata.MD) error { if md.Len() == 0 { return nil } - stream, ok := transport.StreamFromContext(ctx) - if !ok { - return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) + stream := ServerTransportStreamFromContext(ctx) + if stream == nil { + return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx) } return stream.SetTrailer(md) } + +// Method returns the method string for the server context. The returned +// string is in the format of "/service/method". +func Method(ctx context.Context) (string, bool) { + s := ServerTransportStreamFromContext(ctx) + if s == nil { + return "", false + } + return s.Method(), true +} diff --git a/vendor/google.golang.org/grpc/server_test.go b/vendor/google.golang.org/grpc/server_test.go deleted file mode 100644 index 6438b5f8ab..0000000000 --- a/vendor/google.golang.org/grpc/server_test.go +++ /dev/null @@ -1,102 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 grpc - -import ( - "net" - "reflect" - "strings" - "testing" - - "google.golang.org/grpc/test/leakcheck" -) - -type emptyServiceServer interface{} - -type testServer struct{} - -func TestStopBeforeServe(t *testing.T) { - defer leakcheck.Check(t) - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to create listener: %v", err) - } - - server := NewServer() - server.Stop() - err = server.Serve(lis) - if err != ErrServerStopped { - t.Fatalf("server.Serve() error = %v, want %v", err, ErrServerStopped) - } - - // server.Serve is responsible for closing the listener, even if the - // server was already stopped. - err = lis.Close() - if got, want := ErrorDesc(err), "use of closed"; !strings.Contains(got, want) { - t.Errorf("Close() error = %q, want %q", got, want) - } -} - -func TestGetServiceInfo(t *testing.T) { - defer leakcheck.Check(t) - testSd := ServiceDesc{ - ServiceName: "grpc.testing.EmptyService", - HandlerType: (*emptyServiceServer)(nil), - Methods: []MethodDesc{ - { - MethodName: "EmptyCall", - Handler: nil, - }, - }, - Streams: []StreamDesc{ - { - StreamName: "EmptyStream", - Handler: nil, - ServerStreams: false, - ClientStreams: true, - }, - }, - Metadata: []int{0, 2, 1, 3}, - } - - server := NewServer() - server.RegisterService(&testSd, &testServer{}) - - info := server.GetServiceInfo() - want := map[string]ServiceInfo{ - "grpc.testing.EmptyService": { - Methods: []MethodInfo{ - { - Name: "EmptyCall", - IsClientStream: false, - IsServerStream: false, - }, - { - Name: "EmptyStream", - IsClientStream: true, - IsServerStream: false, - }}, - Metadata: []int{0, 2, 1, 3}, - }, - } - - if !reflect.DeepEqual(info, want) { - t.Errorf("GetServiceInfo() = %+v, want %+v", info, want) - } -} diff --git a/vendor/google.golang.org/grpc/service_config.go b/vendor/google.golang.org/grpc/service_config.go new file mode 100644 index 0000000000..015631d8d3 --- /dev/null +++ b/vendor/google.golang.org/grpc/service_config.go @@ -0,0 +1,233 @@ +/* + * + * Copyright 2017 gRPC 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 grpc + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" + "time" + + "google.golang.org/grpc/grpclog" +) + +const maxInt = int(^uint(0) >> 1) + +// MethodConfig defines the configuration recommended by the service providers for a +// particular method. +// +// Deprecated: Users should not use this struct. Service config should be received +// through name resolver, as specified here +// https://github.com/grpc/grpc/blob/master/doc/service_config.md +type MethodConfig struct { + // WaitForReady indicates whether RPCs sent to this method should wait until + // the connection is ready by default (!failfast). The value specified via the + // gRPC client API will override the value set here. + WaitForReady *bool + // Timeout is the default timeout for RPCs sent to this method. The actual + // deadline used will be the minimum of the value specified here and the value + // set by the application via the gRPC client API. If either one is not set, + // then the other will be used. If neither is set, then the RPC has no deadline. + Timeout *time.Duration + // MaxReqSize is the maximum allowed payload size for an individual request in a + // stream (client->server) in bytes. The size which is measured is the serialized + // payload after per-message compression (but before stream compression) in bytes. + // The actual value used is the minimum of the value specified here and the value set + // by the application via the gRPC client API. If either one is not set, then the other + // will be used. If neither is set, then the built-in default is used. + MaxReqSize *int + // MaxRespSize is the maximum allowed payload size for an individual response in a + // stream (server->client) in bytes. + MaxRespSize *int +} + +// ServiceConfig is provided by the service provider and contains parameters for how +// clients that connect to the service should behave. +// +// Deprecated: Users should not use this struct. Service config should be received +// through name resolver, as specified here +// https://github.com/grpc/grpc/blob/master/doc/service_config.md +type ServiceConfig struct { + // LB is the load balancer the service providers recommends. The balancer specified + // via grpc.WithBalancer will override this. + LB *string + // Methods contains a map for the methods in this service. + // If there is an exact match for a method (i.e. /service/method) in the map, use the corresponding MethodConfig. + // If there's no exact match, look for the default config for the service (/service/) and use the corresponding MethodConfig if it exists. + // Otherwise, the method has no MethodConfig to use. + Methods map[string]MethodConfig + + stickinessMetadataKey *string +} + +func parseDuration(s *string) (*time.Duration, error) { + if s == nil { + return nil, nil + } + if !strings.HasSuffix(*s, "s") { + return nil, fmt.Errorf("malformed duration %q", *s) + } + ss := strings.SplitN((*s)[:len(*s)-1], ".", 3) + if len(ss) > 2 { + return nil, fmt.Errorf("malformed duration %q", *s) + } + // hasDigits is set if either the whole or fractional part of the number is + // present, since both are optional but one is required. + hasDigits := false + var d time.Duration + if len(ss[0]) > 0 { + i, err := strconv.ParseInt(ss[0], 10, 32) + if err != nil { + return nil, fmt.Errorf("malformed duration %q: %v", *s, err) + } + d = time.Duration(i) * time.Second + hasDigits = true + } + if len(ss) == 2 && len(ss[1]) > 0 { + if len(ss[1]) > 9 { + return nil, fmt.Errorf("malformed duration %q", *s) + } + f, err := strconv.ParseInt(ss[1], 10, 64) + if err != nil { + return nil, fmt.Errorf("malformed duration %q: %v", *s, err) + } + for i := 9; i > len(ss[1]); i-- { + f *= 10 + } + d += time.Duration(f) + hasDigits = true + } + if !hasDigits { + return nil, fmt.Errorf("malformed duration %q", *s) + } + + return &d, nil +} + +type jsonName struct { + Service *string + Method *string +} + +func (j jsonName) generatePath() (string, bool) { + if j.Service == nil { + return "", false + } + res := "/" + *j.Service + "/" + if j.Method != nil { + res += *j.Method + } + return res, true +} + +// TODO(lyuxuan): delete this struct after cleaning up old service config implementation. +type jsonMC struct { + Name *[]jsonName + WaitForReady *bool + Timeout *string + MaxRequestMessageBytes *int64 + MaxResponseMessageBytes *int64 +} + +// TODO(lyuxuan): delete this struct after cleaning up old service config implementation. +type jsonSC struct { + LoadBalancingPolicy *string + StickinessMetadataKey *string + MethodConfig *[]jsonMC +} + +func parseServiceConfig(js string) (ServiceConfig, error) { + var rsc jsonSC + err := json.Unmarshal([]byte(js), &rsc) + if err != nil { + grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) + return ServiceConfig{}, err + } + sc := ServiceConfig{ + LB: rsc.LoadBalancingPolicy, + Methods: make(map[string]MethodConfig), + + stickinessMetadataKey: rsc.StickinessMetadataKey, + } + if rsc.MethodConfig == nil { + return sc, nil + } + + for _, m := range *rsc.MethodConfig { + if m.Name == nil { + continue + } + d, err := parseDuration(m.Timeout) + if err != nil { + grpclog.Warningf("grpc: parseServiceConfig error unmarshaling %s due to %v", js, err) + return ServiceConfig{}, err + } + + mc := MethodConfig{ + WaitForReady: m.WaitForReady, + Timeout: d, + } + if m.MaxRequestMessageBytes != nil { + if *m.MaxRequestMessageBytes > int64(maxInt) { + mc.MaxReqSize = newInt(maxInt) + } else { + mc.MaxReqSize = newInt(int(*m.MaxRequestMessageBytes)) + } + } + if m.MaxResponseMessageBytes != nil { + if *m.MaxResponseMessageBytes > int64(maxInt) { + mc.MaxRespSize = newInt(maxInt) + } else { + mc.MaxRespSize = newInt(int(*m.MaxResponseMessageBytes)) + } + } + for _, n := range *m.Name { + if path, valid := n.generatePath(); valid { + sc.Methods[path] = mc + } + } + } + + return sc, nil +} + +func min(a, b *int) *int { + if *a < *b { + return a + } + return b +} + +func getMaxSize(mcMax, doptMax *int, defaultVal int) *int { + if mcMax == nil && doptMax == nil { + return &defaultVal + } + if mcMax != nil && doptMax != nil { + return min(mcMax, doptMax) + } + if mcMax != nil { + return mcMax + } + return doptMax +} + +func newInt(b int) *int { + return &b +} diff --git a/vendor/google.golang.org/grpc/stats/stats.go b/vendor/google.golang.org/grpc/stats/stats.go index d5aa2f793b..3f13190a0a 100644 --- a/vendor/google.golang.org/grpc/stats/stats.go +++ b/vendor/google.golang.org/grpc/stats/stats.go @@ -169,6 +169,8 @@ func (s *OutTrailer) isRPCStats() {} type End struct { // Client is true if this End is from client side. Client bool + // BeginTime is the time when the RPC began. + BeginTime time.Time // EndTime is the time when the RPC ends. EndTime time.Time // Error is the error the RPC ended with. It is an error generated from diff --git a/vendor/google.golang.org/grpc/stats/stats_test.go b/vendor/google.golang.org/grpc/stats/stats_test.go deleted file mode 100644 index 141324c0d0..0000000000 --- a/vendor/google.golang.org/grpc/stats/stats_test.go +++ /dev/null @@ -1,1265 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 stats_test - -import ( - "fmt" - "io" - "net" - "reflect" - "sync" - "testing" - "time" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/stats" - testpb "google.golang.org/grpc/stats/grpc_testing" -) - -func init() { - grpc.EnableTracing = false -} - -type connCtxKey struct{} -type rpcCtxKey struct{} - -var ( - // For headers: - testMetadata = metadata.MD{ - "key1": []string{"value1"}, - "key2": []string{"value2"}, - } - // For trailers: - testTrailerMetadata = metadata.MD{ - "tkey1": []string{"trailerValue1"}, - "tkey2": []string{"trailerValue2"}, - } - // The id for which the service handler should return error. - errorID int32 = 32202 -) - -type testServer struct{} - -func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { - md, ok := metadata.FromIncomingContext(ctx) - if ok { - if err := grpc.SendHeader(ctx, md); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SendHeader(_, %v) = %v, want <nil>", md, err) - } - if err := grpc.SetTrailer(ctx, testTrailerMetadata); err != nil { - return nil, grpc.Errorf(grpc.Code(err), "grpc.SetTrailer(_, %v) = %v, want <nil>", testTrailerMetadata, err) - } - } - - if in.Id == errorID { - return nil, fmt.Errorf("got error id: %v", in.Id) - } - - return &testpb.SimpleResponse{Id: in.Id}, nil -} - -func (s *testServer) FullDuplexCall(stream testpb.TestService_FullDuplexCallServer) error { - md, ok := metadata.FromIncomingContext(stream.Context()) - if ok { - if err := stream.SendHeader(md); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) - } - stream.SetTrailer(testTrailerMetadata) - } - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - return nil - } - if err != nil { - return err - } - - if in.Id == errorID { - return fmt.Errorf("got error id: %v", in.Id) - } - - if err := stream.Send(&testpb.SimpleResponse{Id: in.Id}); err != nil { - return err - } - } -} - -func (s *testServer) ClientStreamCall(stream testpb.TestService_ClientStreamCallServer) error { - md, ok := metadata.FromIncomingContext(stream.Context()) - if ok { - if err := stream.SendHeader(md); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) - } - stream.SetTrailer(testTrailerMetadata) - } - for { - in, err := stream.Recv() - if err == io.EOF { - // read done. - return stream.SendAndClose(&testpb.SimpleResponse{Id: int32(0)}) - } - if err != nil { - return err - } - - if in.Id == errorID { - return fmt.Errorf("got error id: %v", in.Id) - } - } -} - -func (s *testServer) ServerStreamCall(in *testpb.SimpleRequest, stream testpb.TestService_ServerStreamCallServer) error { - md, ok := metadata.FromIncomingContext(stream.Context()) - if ok { - if err := stream.SendHeader(md); err != nil { - return grpc.Errorf(grpc.Code(err), "%v.SendHeader(%v) = %v, want %v", stream, md, err, nil) - } - stream.SetTrailer(testTrailerMetadata) - } - - if in.Id == errorID { - return fmt.Errorf("got error id: %v", in.Id) - } - - for i := 0; i < 5; i++ { - if err := stream.Send(&testpb.SimpleResponse{Id: in.Id}); err != nil { - return err - } - } - return nil -} - -// test is an end-to-end test. It should be created with the newTest -// func, modified as needed, and then started with its startServer method. -// It should be cleaned up with the tearDown method. -type test struct { - t *testing.T - compress string - clientStatsHandler stats.Handler - serverStatsHandler stats.Handler - - testServer testpb.TestServiceServer // nil means none - // srv and srvAddr are set once startServer is called. - srv *grpc.Server - srvAddr string - - cc *grpc.ClientConn // nil until requested via clientConn -} - -func (te *test) tearDown() { - if te.cc != nil { - te.cc.Close() - te.cc = nil - } - te.srv.Stop() -} - -type testConfig struct { - compress string -} - -// newTest returns a new test using the provided testing.T and -// environment. It is returned with default values. Tests should -// modify it before calling its startServer and clientConn methods. -func newTest(t *testing.T, tc *testConfig, ch stats.Handler, sh stats.Handler) *test { - te := &test{ - t: t, - compress: tc.compress, - clientStatsHandler: ch, - serverStatsHandler: sh, - } - return te -} - -// startServer starts a gRPC server listening. Callers should defer a -// call to te.tearDown to clean up. -func (te *test) startServer(ts testpb.TestServiceServer) { - te.testServer = ts - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - te.t.Fatalf("Failed to listen: %v", err) - } - var opts []grpc.ServerOption - if te.compress == "gzip" { - opts = append(opts, - grpc.RPCCompressor(grpc.NewGZIPCompressor()), - grpc.RPCDecompressor(grpc.NewGZIPDecompressor()), - ) - } - if te.serverStatsHandler != nil { - opts = append(opts, grpc.StatsHandler(te.serverStatsHandler)) - } - s := grpc.NewServer(opts...) - te.srv = s - if te.testServer != nil { - testpb.RegisterTestServiceServer(s, te.testServer) - } - - go s.Serve(lis) - te.srvAddr = lis.Addr().String() -} - -func (te *test) clientConn() *grpc.ClientConn { - if te.cc != nil { - return te.cc - } - opts := []grpc.DialOption{grpc.WithInsecure(), grpc.WithBlock()} - if te.compress == "gzip" { - opts = append(opts, - grpc.WithCompressor(grpc.NewGZIPCompressor()), - grpc.WithDecompressor(grpc.NewGZIPDecompressor()), - ) - } - if te.clientStatsHandler != nil { - opts = append(opts, grpc.WithStatsHandler(te.clientStatsHandler)) - } - - var err error - te.cc, err = grpc.Dial(te.srvAddr, opts...) - if err != nil { - te.t.Fatalf("Dial(%q) = %v", te.srvAddr, err) - } - return te.cc -} - -type rpcType int - -const ( - unaryRPC rpcType = iota - clientStreamRPC - serverStreamRPC - fullDuplexStreamRPC -) - -type rpcConfig struct { - count int // Number of requests and responses for streaming RPCs. - success bool // Whether the RPC should succeed or return error. - failfast bool - callType rpcType // Type of RPC. - noLastRecv bool // Whether to call recv for io.EOF. When true, last recv won't be called. Only valid for streaming RPCs. -} - -func (te *test) doUnaryCall(c *rpcConfig) (*testpb.SimpleRequest, *testpb.SimpleResponse, error) { - var ( - resp *testpb.SimpleResponse - req *testpb.SimpleRequest - err error - ) - tc := testpb.NewTestServiceClient(te.clientConn()) - if c.success { - req = &testpb.SimpleRequest{Id: errorID + 1} - } else { - req = &testpb.SimpleRequest{Id: errorID} - } - ctx := metadata.NewOutgoingContext(context.Background(), testMetadata) - - resp, err = tc.UnaryCall(ctx, req, grpc.FailFast(c.failfast)) - return req, resp, err -} - -func (te *test) doFullDuplexCallRoundtrip(c *rpcConfig) ([]*testpb.SimpleRequest, []*testpb.SimpleResponse, error) { - var ( - reqs []*testpb.SimpleRequest - resps []*testpb.SimpleResponse - err error - ) - tc := testpb.NewTestServiceClient(te.clientConn()) - stream, err := tc.FullDuplexCall(metadata.NewOutgoingContext(context.Background(), testMetadata), grpc.FailFast(c.failfast)) - if err != nil { - return reqs, resps, err - } - var startID int32 - if !c.success { - startID = errorID - } - for i := 0; i < c.count; i++ { - req := &testpb.SimpleRequest{ - Id: int32(i) + startID, - } - reqs = append(reqs, req) - if err = stream.Send(req); err != nil { - return reqs, resps, err - } - var resp *testpb.SimpleResponse - if resp, err = stream.Recv(); err != nil { - return reqs, resps, err - } - resps = append(resps, resp) - } - if err = stream.CloseSend(); err != nil && err != io.EOF { - return reqs, resps, err - } - if !c.noLastRecv { - if _, err = stream.Recv(); err != io.EOF { - return reqs, resps, err - } - } else { - // In the case of not calling the last recv, sleep to avoid - // returning too fast to miss the remaining stats (InTrailer and End). - time.Sleep(time.Second) - } - - return reqs, resps, nil -} - -func (te *test) doClientStreamCall(c *rpcConfig) ([]*testpb.SimpleRequest, *testpb.SimpleResponse, error) { - var ( - reqs []*testpb.SimpleRequest - resp *testpb.SimpleResponse - err error - ) - tc := testpb.NewTestServiceClient(te.clientConn()) - stream, err := tc.ClientStreamCall(metadata.NewOutgoingContext(context.Background(), testMetadata), grpc.FailFast(c.failfast)) - if err != nil { - return reqs, resp, err - } - var startID int32 - if !c.success { - startID = errorID - } - for i := 0; i < c.count; i++ { - req := &testpb.SimpleRequest{ - Id: int32(i) + startID, - } - reqs = append(reqs, req) - if err = stream.Send(req); err != nil { - return reqs, resp, err - } - } - resp, err = stream.CloseAndRecv() - return reqs, resp, err -} - -func (te *test) doServerStreamCall(c *rpcConfig) (*testpb.SimpleRequest, []*testpb.SimpleResponse, error) { - var ( - req *testpb.SimpleRequest - resps []*testpb.SimpleResponse - err error - ) - - tc := testpb.NewTestServiceClient(te.clientConn()) - - var startID int32 - if !c.success { - startID = errorID - } - req = &testpb.SimpleRequest{Id: startID} - stream, err := tc.ServerStreamCall(metadata.NewOutgoingContext(context.Background(), testMetadata), req, grpc.FailFast(c.failfast)) - if err != nil { - return req, resps, err - } - for { - var resp *testpb.SimpleResponse - resp, err := stream.Recv() - if err == io.EOF { - return req, resps, nil - } else if err != nil { - return req, resps, err - } - resps = append(resps, resp) - } -} - -type expectedData struct { - method string - serverAddr string - compression string - reqIdx int - requests []*testpb.SimpleRequest - respIdx int - responses []*testpb.SimpleResponse - err error - failfast bool -} - -type gotData struct { - ctx context.Context - client bool - s interface{} // This could be RPCStats or ConnStats. -} - -const ( - begin int = iota - end - inPayload - inHeader - inTrailer - outPayload - outHeader - outTrailer - connbegin - connend -) - -func checkBegin(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.Begin - ) - if st, ok = d.s.(*stats.Begin); !ok { - t.Fatalf("got %T, want Begin", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want <non-nil>") - } - if st.BeginTime.IsZero() { - t.Fatalf("st.BeginTime = %v, want <non-zero>", st.BeginTime) - } - if d.client { - if st.FailFast != e.failfast { - t.Fatalf("st.FailFast = %v, want %v", st.FailFast, e.failfast) - } - } -} - -func checkInHeader(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.InHeader - ) - if st, ok = d.s.(*stats.InHeader); !ok { - t.Fatalf("got %T, want InHeader", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want <non-nil>") - } - if !d.client { - if st.FullMethod != e.method { - t.Fatalf("st.FullMethod = %s, want %v", st.FullMethod, e.method) - } - if st.LocalAddr.String() != e.serverAddr { - t.Fatalf("st.LocalAddr = %v, want %v", st.LocalAddr, e.serverAddr) - } - if st.Compression != e.compression { - t.Fatalf("st.Compression = %v, want %v", st.Compression, e.compression) - } - - if connInfo, ok := d.ctx.Value(connCtxKey{}).(*stats.ConnTagInfo); ok { - if connInfo.RemoteAddr != st.RemoteAddr { - t.Fatalf("connInfo.RemoteAddr = %v, want %v", connInfo.RemoteAddr, st.RemoteAddr) - } - if connInfo.LocalAddr != st.LocalAddr { - t.Fatalf("connInfo.LocalAddr = %v, want %v", connInfo.LocalAddr, st.LocalAddr) - } - } else { - t.Fatalf("got context %v, want one with connCtxKey", d.ctx) - } - if rpcInfo, ok := d.ctx.Value(rpcCtxKey{}).(*stats.RPCTagInfo); ok { - if rpcInfo.FullMethodName != st.FullMethod { - t.Fatalf("rpcInfo.FullMethod = %s, want %v", rpcInfo.FullMethodName, st.FullMethod) - } - } else { - t.Fatalf("got context %v, want one with rpcCtxKey", d.ctx) - } - } -} - -func checkInPayload(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.InPayload - ) - if st, ok = d.s.(*stats.InPayload); !ok { - t.Fatalf("got %T, want InPayload", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want <non-nil>") - } - if d.client { - b, err := proto.Marshal(e.responses[e.respIdx]) - if err != nil { - t.Fatalf("failed to marshal message: %v", err) - } - if reflect.TypeOf(st.Payload) != reflect.TypeOf(e.responses[e.respIdx]) { - t.Fatalf("st.Payload = %T, want %T", st.Payload, e.responses[e.respIdx]) - } - e.respIdx++ - if string(st.Data) != string(b) { - t.Fatalf("st.Data = %v, want %v", st.Data, b) - } - if st.Length != len(b) { - t.Fatalf("st.Lenght = %v, want %v", st.Length, len(b)) - } - } else { - b, err := proto.Marshal(e.requests[e.reqIdx]) - if err != nil { - t.Fatalf("failed to marshal message: %v", err) - } - if reflect.TypeOf(st.Payload) != reflect.TypeOf(e.requests[e.reqIdx]) { - t.Fatalf("st.Payload = %T, want %T", st.Payload, e.requests[e.reqIdx]) - } - e.reqIdx++ - if string(st.Data) != string(b) { - t.Fatalf("st.Data = %v, want %v", st.Data, b) - } - if st.Length != len(b) { - t.Fatalf("st.Lenght = %v, want %v", st.Length, len(b)) - } - } - // TODO check WireLength and ReceivedTime. - if st.RecvTime.IsZero() { - t.Fatalf("st.ReceivedTime = %v, want <non-zero>", st.RecvTime) - } -} - -func checkInTrailer(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - ) - if _, ok = d.s.(*stats.InTrailer); !ok { - t.Fatalf("got %T, want InTrailer", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want <non-nil>") - } -} - -func checkOutHeader(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.OutHeader - ) - if st, ok = d.s.(*stats.OutHeader); !ok { - t.Fatalf("got %T, want OutHeader", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want <non-nil>") - } - if d.client { - if st.FullMethod != e.method { - t.Fatalf("st.FullMethod = %s, want %v", st.FullMethod, e.method) - } - if st.RemoteAddr.String() != e.serverAddr { - t.Fatalf("st.RemoteAddr = %v, want %v", st.RemoteAddr, e.serverAddr) - } - if st.Compression != e.compression { - t.Fatalf("st.Compression = %v, want %v", st.Compression, e.compression) - } - - if rpcInfo, ok := d.ctx.Value(rpcCtxKey{}).(*stats.RPCTagInfo); ok { - if rpcInfo.FullMethodName != st.FullMethod { - t.Fatalf("rpcInfo.FullMethod = %s, want %v", rpcInfo.FullMethodName, st.FullMethod) - } - } else { - t.Fatalf("got context %v, want one with rpcCtxKey", d.ctx) - } - } -} - -func checkOutPayload(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.OutPayload - ) - if st, ok = d.s.(*stats.OutPayload); !ok { - t.Fatalf("got %T, want OutPayload", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want <non-nil>") - } - if d.client { - b, err := proto.Marshal(e.requests[e.reqIdx]) - if err != nil { - t.Fatalf("failed to marshal message: %v", err) - } - if reflect.TypeOf(st.Payload) != reflect.TypeOf(e.requests[e.reqIdx]) { - t.Fatalf("st.Payload = %T, want %T", st.Payload, e.requests[e.reqIdx]) - } - e.reqIdx++ - if string(st.Data) != string(b) { - t.Fatalf("st.Data = %v, want %v", st.Data, b) - } - if st.Length != len(b) { - t.Fatalf("st.Lenght = %v, want %v", st.Length, len(b)) - } - } else { - b, err := proto.Marshal(e.responses[e.respIdx]) - if err != nil { - t.Fatalf("failed to marshal message: %v", err) - } - if reflect.TypeOf(st.Payload) != reflect.TypeOf(e.responses[e.respIdx]) { - t.Fatalf("st.Payload = %T, want %T", st.Payload, e.responses[e.respIdx]) - } - e.respIdx++ - if string(st.Data) != string(b) { - t.Fatalf("st.Data = %v, want %v", st.Data, b) - } - if st.Length != len(b) { - t.Fatalf("st.Lenght = %v, want %v", st.Length, len(b)) - } - } - // TODO check WireLength and ReceivedTime. - if st.SentTime.IsZero() { - t.Fatalf("st.SentTime = %v, want <non-zero>", st.SentTime) - } -} - -func checkOutTrailer(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.OutTrailer - ) - if st, ok = d.s.(*stats.OutTrailer); !ok { - t.Fatalf("got %T, want OutTrailer", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want <non-nil>") - } - if st.Client { - t.Fatalf("st IsClient = true, want false") - } -} - -func checkEnd(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.End - ) - if st, ok = d.s.(*stats.End); !ok { - t.Fatalf("got %T, want End", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want <non-nil>") - } - if st.EndTime.IsZero() { - t.Fatalf("st.EndTime = %v, want <non-zero>", st.EndTime) - } - if grpc.Code(st.Error) != grpc.Code(e.err) || grpc.ErrorDesc(st.Error) != grpc.ErrorDesc(e.err) { - t.Fatalf("st.Error = %v, want %v", st.Error, e.err) - } -} - -func checkConnBegin(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.ConnBegin - ) - if st, ok = d.s.(*stats.ConnBegin); !ok { - t.Fatalf("got %T, want ConnBegin", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want <non-nil>") - } - st.IsClient() // TODO remove this. -} - -func checkConnEnd(t *testing.T, d *gotData, e *expectedData) { - var ( - ok bool - st *stats.ConnEnd - ) - if st, ok = d.s.(*stats.ConnEnd); !ok { - t.Fatalf("got %T, want ConnEnd", d.s) - } - if d.ctx == nil { - t.Fatalf("d.ctx = nil, want <non-nil>") - } - st.IsClient() // TODO remove this. -} - -type statshandler struct { - mu sync.Mutex - gotRPC []*gotData - gotConn []*gotData -} - -func (h *statshandler) TagConn(ctx context.Context, info *stats.ConnTagInfo) context.Context { - return context.WithValue(ctx, connCtxKey{}, info) -} - -func (h *statshandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { - return context.WithValue(ctx, rpcCtxKey{}, info) -} - -func (h *statshandler) HandleConn(ctx context.Context, s stats.ConnStats) { - h.mu.Lock() - defer h.mu.Unlock() - h.gotConn = append(h.gotConn, &gotData{ctx, s.IsClient(), s}) -} - -func (h *statshandler) HandleRPC(ctx context.Context, s stats.RPCStats) { - h.mu.Lock() - defer h.mu.Unlock() - h.gotRPC = append(h.gotRPC, &gotData{ctx, s.IsClient(), s}) -} - -func checkConnStats(t *testing.T, got []*gotData) { - if len(got) <= 0 || len(got)%2 != 0 { - for i, g := range got { - t.Errorf(" - %v, %T = %+v, ctx: %v", i, g.s, g.s, g.ctx) - } - t.Fatalf("got %v stats, want even positive number", len(got)) - } - // The first conn stats must be a ConnBegin. - checkConnBegin(t, got[0], nil) - // The last conn stats must be a ConnEnd. - checkConnEnd(t, got[len(got)-1], nil) -} - -func checkServerStats(t *testing.T, got []*gotData, expect *expectedData, checkFuncs []func(t *testing.T, d *gotData, e *expectedData)) { - if len(got) != len(checkFuncs) { - for i, g := range got { - t.Errorf(" - %v, %T", i, g.s) - } - t.Fatalf("got %v stats, want %v stats", len(got), len(checkFuncs)) - } - - var rpcctx context.Context - for i := 0; i < len(got); i++ { - if _, ok := got[i].s.(stats.RPCStats); ok { - if rpcctx != nil && got[i].ctx != rpcctx { - t.Fatalf("got different contexts with stats %T", got[i].s) - } - rpcctx = got[i].ctx - } - } - - for i, f := range checkFuncs { - f(t, got[i], expect) - } -} - -func testServerStats(t *testing.T, tc *testConfig, cc *rpcConfig, checkFuncs []func(t *testing.T, d *gotData, e *expectedData)) { - h := &statshandler{} - te := newTest(t, tc, nil, h) - te.startServer(&testServer{}) - defer te.tearDown() - - var ( - reqs []*testpb.SimpleRequest - resps []*testpb.SimpleResponse - err error - method string - - req *testpb.SimpleRequest - resp *testpb.SimpleResponse - e error - ) - - switch cc.callType { - case unaryRPC: - method = "/grpc.testing.TestService/UnaryCall" - req, resp, e = te.doUnaryCall(cc) - reqs = []*testpb.SimpleRequest{req} - resps = []*testpb.SimpleResponse{resp} - err = e - case clientStreamRPC: - method = "/grpc.testing.TestService/ClientStreamCall" - reqs, resp, e = te.doClientStreamCall(cc) - resps = []*testpb.SimpleResponse{resp} - err = e - case serverStreamRPC: - method = "/grpc.testing.TestService/ServerStreamCall" - req, resps, e = te.doServerStreamCall(cc) - reqs = []*testpb.SimpleRequest{req} - err = e - case fullDuplexStreamRPC: - method = "/grpc.testing.TestService/FullDuplexCall" - reqs, resps, err = te.doFullDuplexCallRoundtrip(cc) - } - if cc.success != (err == nil) { - t.Fatalf("cc.success: %v, got error: %v", cc.success, err) - } - te.cc.Close() - te.srv.GracefulStop() // Wait for the server to stop. - - for { - h.mu.Lock() - if len(h.gotRPC) >= len(checkFuncs) { - h.mu.Unlock() - break - } - h.mu.Unlock() - time.Sleep(10 * time.Millisecond) - } - - for { - h.mu.Lock() - if _, ok := h.gotConn[len(h.gotConn)-1].s.(*stats.ConnEnd); ok { - h.mu.Unlock() - break - } - h.mu.Unlock() - time.Sleep(10 * time.Millisecond) - } - - expect := &expectedData{ - serverAddr: te.srvAddr, - compression: tc.compress, - method: method, - requests: reqs, - responses: resps, - err: err, - } - - h.mu.Lock() - checkConnStats(t, h.gotConn) - h.mu.Unlock() - checkServerStats(t, h.gotRPC, expect, checkFuncs) -} - -func TestServerStatsUnaryRPC(t *testing.T) { - testServerStats(t, &testConfig{compress: ""}, &rpcConfig{success: true, callType: unaryRPC}, []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkInPayload, - checkOutHeader, - checkOutPayload, - checkOutTrailer, - checkEnd, - }) -} - -func TestServerStatsUnaryRPCError(t *testing.T) { - testServerStats(t, &testConfig{compress: ""}, &rpcConfig{success: false, callType: unaryRPC}, []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkInPayload, - checkOutHeader, - checkOutTrailer, - checkEnd, - }) -} - -func TestServerStatsClientStreamRPC(t *testing.T) { - count := 5 - checkFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkOutHeader, - } - ioPayFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkInPayload, - } - for i := 0; i < count; i++ { - checkFuncs = append(checkFuncs, ioPayFuncs...) - } - checkFuncs = append(checkFuncs, - checkOutPayload, - checkOutTrailer, - checkEnd, - ) - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, callType: clientStreamRPC}, checkFuncs) -} - -func TestServerStatsClientStreamRPCError(t *testing.T) { - count := 1 - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, callType: clientStreamRPC}, []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkOutHeader, - checkInPayload, - checkOutTrailer, - checkEnd, - }) -} - -func TestServerStatsServerStreamRPC(t *testing.T) { - count := 5 - checkFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkInPayload, - checkOutHeader, - } - ioPayFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkOutPayload, - } - for i := 0; i < count; i++ { - checkFuncs = append(checkFuncs, ioPayFuncs...) - } - checkFuncs = append(checkFuncs, - checkOutTrailer, - checkEnd, - ) - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, callType: serverStreamRPC}, checkFuncs) -} - -func TestServerStatsServerStreamRPCError(t *testing.T) { - count := 5 - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, callType: serverStreamRPC}, []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkInPayload, - checkOutHeader, - checkOutTrailer, - checkEnd, - }) -} - -func TestServerStatsFullDuplexRPC(t *testing.T) { - count := 5 - checkFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkOutHeader, - } - ioPayFuncs := []func(t *testing.T, d *gotData, e *expectedData){ - checkInPayload, - checkOutPayload, - } - for i := 0; i < count; i++ { - checkFuncs = append(checkFuncs, ioPayFuncs...) - } - checkFuncs = append(checkFuncs, - checkOutTrailer, - checkEnd, - ) - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, callType: fullDuplexStreamRPC}, checkFuncs) -} - -func TestServerStatsFullDuplexRPCError(t *testing.T) { - count := 5 - testServerStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, callType: fullDuplexStreamRPC}, []func(t *testing.T, d *gotData, e *expectedData){ - checkInHeader, - checkBegin, - checkOutHeader, - checkInPayload, - checkOutTrailer, - checkEnd, - }) -} - -type checkFuncWithCount struct { - f func(t *testing.T, d *gotData, e *expectedData) - c int // expected count -} - -func checkClientStats(t *testing.T, got []*gotData, expect *expectedData, checkFuncs map[int]*checkFuncWithCount) { - var expectLen int - for _, v := range checkFuncs { - expectLen += v.c - } - if len(got) != expectLen { - for i, g := range got { - t.Errorf(" - %v, %T", i, g.s) - } - t.Fatalf("got %v stats, want %v stats", len(got), expectLen) - } - - var tagInfoInCtx *stats.RPCTagInfo - for i := 0; i < len(got); i++ { - if _, ok := got[i].s.(stats.RPCStats); ok { - tagInfoInCtxNew, _ := got[i].ctx.Value(rpcCtxKey{}).(*stats.RPCTagInfo) - if tagInfoInCtx != nil && tagInfoInCtx != tagInfoInCtxNew { - t.Fatalf("got context containing different tagInfo with stats %T", got[i].s) - } - tagInfoInCtx = tagInfoInCtxNew - } - } - - for _, s := range got { - switch s.s.(type) { - case *stats.Begin: - if checkFuncs[begin].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[begin].f(t, s, expect) - checkFuncs[begin].c-- - case *stats.OutHeader: - if checkFuncs[outHeader].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[outHeader].f(t, s, expect) - checkFuncs[outHeader].c-- - case *stats.OutPayload: - if checkFuncs[outPayload].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[outPayload].f(t, s, expect) - checkFuncs[outPayload].c-- - case *stats.InHeader: - if checkFuncs[inHeader].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[inHeader].f(t, s, expect) - checkFuncs[inHeader].c-- - case *stats.InPayload: - if checkFuncs[inPayload].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[inPayload].f(t, s, expect) - checkFuncs[inPayload].c-- - case *stats.InTrailer: - if checkFuncs[inTrailer].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[inTrailer].f(t, s, expect) - checkFuncs[inTrailer].c-- - case *stats.End: - if checkFuncs[end].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[end].f(t, s, expect) - checkFuncs[end].c-- - case *stats.ConnBegin: - if checkFuncs[connbegin].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[connbegin].f(t, s, expect) - checkFuncs[connbegin].c-- - case *stats.ConnEnd: - if checkFuncs[connend].c <= 0 { - t.Fatalf("unexpected stats: %T", s.s) - } - checkFuncs[connend].f(t, s, expect) - checkFuncs[connend].c-- - default: - t.Fatalf("unexpected stats: %T", s.s) - } - } -} - -func testClientStats(t *testing.T, tc *testConfig, cc *rpcConfig, checkFuncs map[int]*checkFuncWithCount) { - h := &statshandler{} - te := newTest(t, tc, h, nil) - te.startServer(&testServer{}) - defer te.tearDown() - - var ( - reqs []*testpb.SimpleRequest - resps []*testpb.SimpleResponse - method string - err error - - req *testpb.SimpleRequest - resp *testpb.SimpleResponse - e error - ) - switch cc.callType { - case unaryRPC: - method = "/grpc.testing.TestService/UnaryCall" - req, resp, e = te.doUnaryCall(cc) - reqs = []*testpb.SimpleRequest{req} - resps = []*testpb.SimpleResponse{resp} - err = e - case clientStreamRPC: - method = "/grpc.testing.TestService/ClientStreamCall" - reqs, resp, e = te.doClientStreamCall(cc) - resps = []*testpb.SimpleResponse{resp} - err = e - case serverStreamRPC: - method = "/grpc.testing.TestService/ServerStreamCall" - req, resps, e = te.doServerStreamCall(cc) - reqs = []*testpb.SimpleRequest{req} - err = e - case fullDuplexStreamRPC: - method = "/grpc.testing.TestService/FullDuplexCall" - reqs, resps, err = te.doFullDuplexCallRoundtrip(cc) - } - if cc.success != (err == nil) { - t.Fatalf("cc.success: %v, got error: %v", cc.success, err) - } - te.cc.Close() - te.srv.GracefulStop() // Wait for the server to stop. - - lenRPCStats := 0 - for _, v := range checkFuncs { - lenRPCStats += v.c - } - for { - h.mu.Lock() - if len(h.gotRPC) >= lenRPCStats { - h.mu.Unlock() - break - } - h.mu.Unlock() - time.Sleep(10 * time.Millisecond) - } - - for { - h.mu.Lock() - if _, ok := h.gotConn[len(h.gotConn)-1].s.(*stats.ConnEnd); ok { - h.mu.Unlock() - break - } - h.mu.Unlock() - time.Sleep(10 * time.Millisecond) - } - - expect := &expectedData{ - serverAddr: te.srvAddr, - compression: tc.compress, - method: method, - requests: reqs, - responses: resps, - failfast: cc.failfast, - err: err, - } - - h.mu.Lock() - checkConnStats(t, h.gotConn) - h.mu.Unlock() - checkClientStats(t, h.gotRPC, expect, checkFuncs) -} - -func TestClientStatsUnaryRPC(t *testing.T) { - testClientStats(t, &testConfig{compress: ""}, &rpcConfig{success: true, failfast: false, callType: unaryRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, 1}, - inHeader: {checkInHeader, 1}, - inPayload: {checkInPayload, 1}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsUnaryRPCError(t *testing.T) { - testClientStats(t, &testConfig{compress: ""}, &rpcConfig{success: false, failfast: false, callType: unaryRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, 1}, - inHeader: {checkInHeader, 1}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsClientStreamRPC(t *testing.T) { - count := 5 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, failfast: false, callType: clientStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - inHeader: {checkInHeader, 1}, - outPayload: {checkOutPayload, count}, - inTrailer: {checkInTrailer, 1}, - inPayload: {checkInPayload, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsClientStreamRPCError(t *testing.T) { - count := 1 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, failfast: false, callType: clientStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - inHeader: {checkInHeader, 1}, - outPayload: {checkOutPayload, 1}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsServerStreamRPC(t *testing.T) { - count := 5 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, failfast: false, callType: serverStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, 1}, - inHeader: {checkInHeader, 1}, - inPayload: {checkInPayload, count}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsServerStreamRPCError(t *testing.T) { - count := 5 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, failfast: false, callType: serverStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, 1}, - inHeader: {checkInHeader, 1}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsFullDuplexRPC(t *testing.T) { - count := 5 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, failfast: false, callType: fullDuplexStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, count}, - inHeader: {checkInHeader, 1}, - inPayload: {checkInPayload, count}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestClientStatsFullDuplexRPCError(t *testing.T) { - count := 5 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: false, failfast: false, callType: fullDuplexStreamRPC}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, 1}, - inHeader: {checkInHeader, 1}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -// If the user doesn't call the last recv() on clientStream. -func TestClientStatsFullDuplexRPCNotCallingLastRecv(t *testing.T) { - count := 1 - testClientStats(t, &testConfig{compress: "gzip"}, &rpcConfig{count: count, success: true, failfast: false, callType: fullDuplexStreamRPC, noLastRecv: true}, map[int]*checkFuncWithCount{ - begin: {checkBegin, 1}, - outHeader: {checkOutHeader, 1}, - outPayload: {checkOutPayload, count}, - inHeader: {checkInHeader, 1}, - inPayload: {checkInPayload, count}, - inTrailer: {checkInTrailer, 1}, - end: {checkEnd, 1}, - }) -} - -func TestTags(t *testing.T) { - b := []byte{5, 2, 4, 3, 1} - ctx := stats.SetTags(context.Background(), b) - if tg := stats.OutgoingTags(ctx); !reflect.DeepEqual(tg, b) { - t.Errorf("OutgoingTags(%v) = %v; want %v", ctx, tg, b) - } - if tg := stats.Tags(ctx); tg != nil { - t.Errorf("Tags(%v) = %v; want nil", ctx, tg) - } - - ctx = stats.SetIncomingTags(context.Background(), b) - if tg := stats.Tags(ctx); !reflect.DeepEqual(tg, b) { - t.Errorf("Tags(%v) = %v; want %v", ctx, tg, b) - } - if tg := stats.OutgoingTags(ctx); tg != nil { - t.Errorf("OutgoingTags(%v) = %v; want nil", ctx, tg) - } -} - -func TestTrace(t *testing.T) { - b := []byte{5, 2, 4, 3, 1} - ctx := stats.SetTrace(context.Background(), b) - if tr := stats.OutgoingTrace(ctx); !reflect.DeepEqual(tr, b) { - t.Errorf("OutgoingTrace(%v) = %v; want %v", ctx, tr, b) - } - if tr := stats.Trace(ctx); tr != nil { - t.Errorf("Trace(%v) = %v; want nil", ctx, tr) - } - - ctx = stats.SetIncomingTrace(context.Background(), b) - if tr := stats.Trace(ctx); !reflect.DeepEqual(tr, b) { - t.Errorf("Trace(%v) = %v; want %v", ctx, tr, b) - } - if tr := stats.OutgoingTrace(ctx); tr != nil { - t.Errorf("OutgoingTrace(%v) = %v; want nil", ctx, tr) - } -} diff --git a/vendor/google.golang.org/grpc/status/status.go b/vendor/google.golang.org/grpc/status/status.go index 871dc4b31c..9c61b09450 100644 --- a/vendor/google.golang.org/grpc/status/status.go +++ b/vendor/google.golang.org/grpc/status/status.go @@ -46,7 +46,7 @@ func (se *statusError) Error() string { return fmt.Sprintf("rpc error: code = %s desc = %s", codes.Code(p.GetCode()), p.GetMessage()) } -func (se *statusError) status() *Status { +func (se *statusError) GRPCStatus() *Status { return &Status{s: (*spb.Status)(se)} } @@ -120,15 +120,23 @@ func FromProto(s *spb.Status) *Status { } // FromError returns a Status representing err if it was produced from this -// package, otherwise it returns nil, false. +// package or has a method `GRPCStatus() *Status`. Otherwise, ok is false and a +// Status is returned with codes.Unknown and the original error message. func FromError(err error) (s *Status, ok bool) { if err == nil { return &Status{s: &spb.Status{Code: int32(codes.OK)}}, true } - if s, ok := err.(*statusError); ok { - return s.status(), true + if se, ok := err.(interface{ GRPCStatus() *Status }); ok { + return se.GRPCStatus(), true } - return nil, false + return New(codes.Unknown, err.Error()), false +} + +// Convert is a convenience function which removes the need to handle the +// boolean return value from FromError. +func Convert(err error) *Status { + s, _ := FromError(err) + return s } // WithDetails returns a new status with the provided details messages appended to the status. @@ -166,3 +174,16 @@ func (s *Status) Details() []interface{} { } return details } + +// Code returns the Code of the error if it is a Status error, codes.OK if err +// is nil, or codes.Unknown otherwise. +func Code(err error) codes.Code { + // Don't use FromError to avoid allocation of OK status. + if err == nil { + return codes.OK + } + if se, ok := err.(interface{ GRPCStatus() *Status }); ok { + return se.GRPCStatus().Code() + } + return codes.Unknown +} diff --git a/vendor/google.golang.org/grpc/status/status_test.go b/vendor/google.golang.org/grpc/status/status_test.go deleted file mode 100644 index 69be8c9f6a..0000000000 --- a/vendor/google.golang.org/grpc/status/status_test.go +++ /dev/null @@ -1,261 +0,0 @@ -/* - * - * Copyright 2017 gRPC 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 status - -import ( - "errors" - "fmt" - "reflect" - "testing" - - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes" - apb "github.com/golang/protobuf/ptypes/any" - dpb "github.com/golang/protobuf/ptypes/duration" - cpb "google.golang.org/genproto/googleapis/rpc/code" - epb "google.golang.org/genproto/googleapis/rpc/errdetails" - spb "google.golang.org/genproto/googleapis/rpc/status" - "google.golang.org/grpc/codes" -) - -func TestErrorsWithSameParameters(t *testing.T) { - const description = "some description" - e1 := Errorf(codes.AlreadyExists, description) - e2 := Errorf(codes.AlreadyExists, description) - if e1 == e2 || !reflect.DeepEqual(e1, e2) { - t.Fatalf("Errors should be equivalent but unique - e1: %v, %v e2: %p, %v", e1.(*statusError), e1, e2.(*statusError), e2) - } -} - -func TestFromToProto(t *testing.T) { - s := &spb.Status{ - Code: int32(codes.Internal), - Message: "test test test", - Details: []*apb.Any{{TypeUrl: "foo", Value: []byte{3, 2, 1}}}, - } - - err := FromProto(s) - if got := err.Proto(); !proto.Equal(s, got) { - t.Fatalf("Expected errors to be identical - s: %v got: %v", s, got) - } -} - -func TestFromNilProto(t *testing.T) { - tests := []*Status{nil, FromProto(nil)} - for _, s := range tests { - if c := s.Code(); c != codes.OK { - t.Errorf("s: %v - Expected s.Code() = OK; got %v", s, c) - } - if m := s.Message(); m != "" { - t.Errorf("s: %v - Expected s.Message() = \"\"; got %q", s, m) - } - if p := s.Proto(); p != nil { - t.Errorf("s: %v - Expected s.Proto() = nil; got %q", s, p) - } - if e := s.Err(); e != nil { - t.Errorf("s: %v - Expected s.Err() = nil; got %v", s, e) - } - } -} - -func TestError(t *testing.T) { - err := Error(codes.Internal, "test description") - if got, want := err.Error(), "rpc error: code = Internal desc = test description"; got != want { - t.Fatalf("err.Error() = %q; want %q", got, want) - } - s, _ := FromError(err) - if got, want := s.Code(), codes.Internal; got != want { - t.Fatalf("err.Code() = %s; want %s", got, want) - } - if got, want := s.Message(), "test description"; got != want { - t.Fatalf("err.Message() = %s; want %s", got, want) - } -} - -func TestErrorOK(t *testing.T) { - err := Error(codes.OK, "foo") - if err != nil { - t.Fatalf("Error(codes.OK, _) = %p; want nil", err.(*statusError)) - } -} - -func TestErrorProtoOK(t *testing.T) { - s := &spb.Status{Code: int32(codes.OK)} - if got := ErrorProto(s); got != nil { - t.Fatalf("ErrorProto(%v) = %v; want nil", s, got) - } -} - -func TestFromError(t *testing.T) { - code, message := codes.Internal, "test description" - err := Error(code, message) - s, ok := FromError(err) - if !ok || s.Code() != code || s.Message() != message || s.Err() == nil { - t.Fatalf("FromError(%v) = %v, %v; want <Code()=%s, Message()=%q, Err()!=nil>, true", err, s, ok, code, message) - } -} - -func TestFromErrorOK(t *testing.T) { - code, message := codes.OK, "" - s, ok := FromError(nil) - if !ok || s.Code() != code || s.Message() != message || s.Err() != nil { - t.Fatalf("FromError(nil) = %v, %v; want <Code()=%s, Message()=%q, Err=nil>, true", s, ok, code, message) - } -} - -func TestStatus_ErrorDetails(t *testing.T) { - tests := []struct { - code codes.Code - details []proto.Message - }{ - { - code: codes.NotFound, - details: nil, - }, - { - code: codes.NotFound, - details: []proto.Message{ - &epb.ResourceInfo{ - ResourceType: "book", - ResourceName: "projects/1234/books/5678", - Owner: "User", - }, - }, - }, - { - code: codes.Internal, - details: []proto.Message{ - &epb.DebugInfo{ - StackEntries: []string{ - "first stack", - "second stack", - }, - }, - }, - }, - { - code: codes.Unavailable, - details: []proto.Message{ - &epb.RetryInfo{ - RetryDelay: &dpb.Duration{Seconds: 60}, - }, - &epb.ResourceInfo{ - ResourceType: "book", - ResourceName: "projects/1234/books/5678", - Owner: "User", - }, - }, - }, - } - - for _, tc := range tests { - s, err := New(tc.code, "").WithDetails(tc.details...) - if err != nil { - t.Fatalf("(%v).WithDetails(%+v) failed: %v", str(s), tc.details, err) - } - details := s.Details() - for i := range details { - if !proto.Equal(details[i].(proto.Message), tc.details[i]) { - t.Fatalf("(%v).Details()[%d] = %+v, want %+v", str(s), i, details[i], tc.details[i]) - } - } - } -} - -func TestStatus_WithDetails_Fail(t *testing.T) { - tests := []*Status{ - nil, - FromProto(nil), - New(codes.OK, ""), - } - for _, s := range tests { - if s, err := s.WithDetails(); err == nil || s != nil { - t.Fatalf("(%v).WithDetails(%+v) = %v, %v; want nil, non-nil", str(s), []proto.Message{}, s, err) - } - } -} - -func TestStatus_ErrorDetails_Fail(t *testing.T) { - tests := []struct { - s *Status - i []interface{} - }{ - { - nil, - nil, - }, - { - FromProto(nil), - nil, - }, - { - New(codes.OK, ""), - []interface{}{}, - }, - { - FromProto(&spb.Status{ - Code: int32(cpb.Code_CANCELLED), - Details: []*apb.Any{ - { - TypeUrl: "", - Value: []byte{}, - }, - mustMarshalAny(&epb.ResourceInfo{ - ResourceType: "book", - ResourceName: "projects/1234/books/5678", - Owner: "User", - }), - }, - }), - []interface{}{ - errors.New(`message type url "" is invalid`), - &epb.ResourceInfo{ - ResourceType: "book", - ResourceName: "projects/1234/books/5678", - Owner: "User", - }, - }, - }, - } - for _, tc := range tests { - got := tc.s.Details() - if !reflect.DeepEqual(got, tc.i) { - t.Errorf("(%v).Details() = %+v, want %+v", str(tc.s), got, tc.i) - } - } -} - -func str(s *Status) string { - if s == nil { - return "nil" - } - if s.s == nil { - return "<Code=OK>" - } - return fmt.Sprintf("<Code=%v, Message=%q, Details=%+v>", codes.Code(s.s.GetCode()), s.s.GetMessage(), s.s.GetDetails()) -} - -// mustMarshalAny converts a protobuf message to an any. -func mustMarshalAny(msg proto.Message) *apb.Any { - any, err := ptypes.MarshalAny(msg) - if err != nil { - panic(fmt.Sprintf("ptypes.MarshalAny(%+v) failed: %v", msg, err)) - } - return any -} diff --git a/vendor/google.golang.org/grpc/stream.go b/vendor/google.golang.org/grpc/stream.go index 75eab40b10..82921a15a3 100644 --- a/vendor/google.golang.org/grpc/stream.go +++ b/vendor/google.golang.org/grpc/stream.go @@ -19,7 +19,6 @@ package grpc import ( - "bytes" "errors" "io" "sync" @@ -28,16 +27,20 @@ import ( "golang.org/x/net/context" "golang.org/x/net/trace" "google.golang.org/grpc/balancer" + "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" + "google.golang.org/grpc/encoding" "google.golang.org/grpc/metadata" - "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" "google.golang.org/grpc/transport" ) // StreamHandler defines the handler called by gRPC server to complete the -// execution of a streaming RPC. +// execution of a streaming RPC. If a StreamHandler returns an error, it +// should be produced by the status package, or else gRPC will use +// codes.Unknown as the status code and err.Error() as the status message +// of the RPC. type StreamHandler func(srv interface{}, stream ServerStream) error // StreamDesc represents a streaming RPC service's method specification. @@ -51,6 +54,8 @@ type StreamDesc struct { } // Stream defines the common interface a client or server stream has to satisfy. +// +// All errors returned from Stream are compatible with the status package. type Stream interface { // Context returns the context for this stream. Context() context.Context @@ -89,43 +94,65 @@ type ClientStream interface { // Stream.SendMsg() may return a non-nil error when something wrong happens sending // the request. The returned error indicates the status of this sending, not the final // status of the RPC. - // Always call Stream.RecvMsg() to get the final status if you care about the status of - // the RPC. + // + // Always call Stream.RecvMsg() to drain the stream and get the final + // status, otherwise there could be leaked resources. Stream } -// NewClientStream creates a new Stream for the client side. This is called -// by generated code. -func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { +// NewStream creates a new Stream for the client side. This is typically +// called by generated code. +func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) { + // allow interceptor to see all applicable call options, which means those + // configured as defaults from dial option as well as per-call options + opts = combine(cc.dopts.callOptions, opts) + if cc.dopts.streamInt != nil { return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...) } return newClientStream(ctx, desc, cc, method, opts...) } +// NewClientStream creates a new Stream for the client side. This is typically +// called by generated code. +// +// DEPRECATED: Use ClientConn.NewStream instead. +func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) { + return cc.NewStream(ctx, desc, method, opts...) +} + func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { - var ( - t transport.ClientTransport - s *transport.Stream - done func(balancer.DoneInfo) - cancel context.CancelFunc - ) + if channelz.IsOn() { + cc.incrCallsStarted() + defer func() { + if err != nil { + cc.incrCallsFailed() + } + }() + } c := defaultCallInfo() mc := cc.GetMethodConfig(method) if mc.WaitForReady != nil { c.failFast = !*mc.WaitForReady } - if mc.Timeout != nil { + // Possible context leak: + // The cancel function for the child context we create will only be called + // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if + // an error is generated by SendMsg. + // https://github.com/grpc/grpc-go/issues/1818. + var cancel context.CancelFunc + if mc.Timeout != nil && *mc.Timeout >= 0 { ctx, cancel = context.WithTimeout(ctx, *mc.Timeout) - defer func() { - if err != nil { - cancel() - } - }() + } else { + ctx, cancel = context.WithCancel(ctx) } + defer func() { + if err != nil { + cancel() + } + }() - opts = append(cc.dopts.callOptions, opts...) for _, o := range opts { if err := o.before(c); err != nil { return nil, toRPCErr(err) @@ -133,6 +160,9 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth } c.maxSendMessageSize = getMaxSize(mc.MaxReqSize, c.maxSendMessageSize, defaultClientMaxSendMessageSize) c.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, c.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize) + if err := setCallInfoCodec(c); err != nil { + return nil, err + } callHdr := &transport.CallHdr{ Host: cc.authority, @@ -141,10 +171,27 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth // so we don't flush the header. // If it's client streaming, the user may never send a request or send it any // time soon, so we ask the transport to flush the header. - Flush: desc.ClientStreams, - } - if cc.dopts.cp != nil { + Flush: desc.ClientStreams, + ContentSubtype: c.contentSubtype, + } + + // Set our outgoing compression according to the UseCompressor CallOption, if + // set. In that case, also find the compressor from the encoding package. + // Otherwise, use the compressor configured by the WithCompressor DialOption, + // if set. + var cp Compressor + var comp encoding.Compressor + if ct := c.compressorType; ct != "" { + callHdr.SendCompress = ct + if ct != encoding.Identity { + comp = encoding.GetCompressor(ct) + if comp == nil { + return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct) + } + } + } else if cc.dopts.cp != nil { callHdr.SendCompress = cc.dopts.cp.Type() + cp = cc.dopts.cp } if c.creds != nil { callHdr.Creds = c.creds @@ -170,11 +217,13 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth } ctx = newContextWithRPCInfo(ctx, c.failFast) sh := cc.dopts.copts.StatsHandler + var beginTime time.Time if sh != nil { ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: c.failFast}) + beginTime = time.Now() begin := &stats.Begin{ Client: true, - BeginTime: time.Now(), + BeginTime: beginTime, FailFast: c.failFast, } sh.HandleRPC(ctx, begin) @@ -182,341 +231,384 @@ func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, meth if err != nil { // Only handle end stats if err != nil. end := &stats.End{ - Client: true, - Error: err, + Client: true, + Error: err, + BeginTime: beginTime, + EndTime: time.Now(), } sh.HandleRPC(ctx, end) } }() } + + var ( + t transport.ClientTransport + s *transport.Stream + done func(balancer.DoneInfo) + ) for { + // Check to make sure the context has expired. This will prevent us from + // looping forever if an error occurs for wait-for-ready RPCs where no data + // is sent on the wire. + select { + case <-ctx.Done(): + return nil, toRPCErr(ctx.Err()) + default: + } + t, done, err = cc.getTransport(ctx, c.failFast) if err != nil { - // TODO(zhaoq): Probably revisit the error handling. - if _, ok := status.FromError(err); ok { - return nil, err - } - if err == errConnClosing || err == errConnUnavailable { - if c.failFast { - return nil, Errorf(codes.Unavailable, "%v", err) - } - continue - } - // All the other errors are treated as Internal errors. - return nil, Errorf(codes.Internal, "%v", err) + return nil, err } s, err = t.NewStream(ctx, callHdr) if err != nil { - if _, ok := err.(transport.ConnectionError); ok && done != nil { - // If error is connection error, transport was sending data on wire, - // and we are not sure if anything has been sent on wire. - // If error is not connection error, we are sure nothing has been sent. - updateRPCInfoInContext(ctx, rpcInfo{bytesSent: true, bytesReceived: false}) - } if done != nil { done(balancer.DoneInfo{Err: err}) done = nil } - if _, ok := err.(transport.ConnectionError); (ok || err == transport.ErrStreamDrain) && !c.failFast { + // In the event of any error from NewStream, we never attempted to write + // anything to the wire, so we can retry indefinitely for non-fail-fast + // RPCs. + if !c.failFast { continue } return nil, toRPCErr(err) } break } - // Set callInfo.peer object from stream's context. - if peer, ok := peer.FromContext(s.Context()); ok { - c.peer = peer - } + cs := &clientStream{ opts: opts, c: c, + cc: cc, desc: desc, - codec: cc.dopts.codec, - cp: cc.dopts.cp, - dc: cc.dopts.dc, + codec: c.codec, + cp: cp, + comp: comp, cancel: cancel, - - done: done, - t: t, - s: s, - p: &parser{r: s}, - - tracing: EnableTracing, - trInfo: trInfo, - - statsCtx: ctx, - statsHandler: cc.dopts.copts.StatsHandler, + attempt: &csAttempt{ + t: t, + s: s, + p: &parser{r: s}, + done: done, + dc: cc.dopts.dc, + ctx: ctx, + trInfo: trInfo, + statsHandler: sh, + beginTime: beginTime, + }, + } + cs.c.stream = cs + cs.attempt.cs = cs + if desc != unaryStreamDesc { + // Listen on cc and stream contexts to cleanup when the user closes the + // ClientConn or cancels the stream context. In all other cases, an error + // should already be injected into the recv buffer by the transport, which + // the client will eventually receive, and then we will cancel the stream's + // context in clientStream.finish. + go func() { + select { + case <-cc.ctx.Done(): + cs.finish(ErrClientConnClosing) + case <-ctx.Done(): + cs.finish(toRPCErr(ctx.Err())) + } + }() } - // Listen on ctx.Done() to detect cancellation and s.Done() to detect normal termination - // when there is no pending I/O operations on this stream. - go func() { - select { - case <-t.Error(): - // Incur transport error, simply exit. - case <-cc.ctx.Done(): - cs.finish(ErrClientConnClosing) - cs.closeTransportStream(ErrClientConnClosing) - case <-s.Done(): - // TODO: The trace of the RPC is terminated here when there is no pending - // I/O, which is probably not the optimal solution. - cs.finish(s.Status().Err()) - cs.closeTransportStream(nil) - case <-s.GoAway(): - cs.finish(errConnDrain) - cs.closeTransportStream(errConnDrain) - case <-s.Context().Done(): - err := s.Context().Err() - cs.finish(err) - cs.closeTransportStream(transport.ContextErr(err)) - } - }() return cs, nil } // clientStream implements a client side Stream. type clientStream struct { - opts []CallOption - c *callInfo - t transport.ClientTransport - s *transport.Stream - p *parser - desc *StreamDesc - codec Codec - cp Compressor - dc Decompressor - cancel context.CancelFunc + opts []CallOption + c *callInfo + cc *ClientConn + desc *StreamDesc + + codec baseCodec + cp Compressor + comp encoding.Compressor + + cancel context.CancelFunc // cancels all attempts - tracing bool // set to EnableTracing when the clientStream is created. + sentLast bool // sent an end stream + + mu sync.Mutex // guards finished + finished bool // TODO: replace with atomic cmpxchg or sync.Once? + + attempt *csAttempt // the active client stream attempt + // TODO(hedging): hedging will have multiple attempts simultaneously. +} - mu sync.Mutex - done func(balancer.DoneInfo) - closed bool - finished bool - // trInfo.tr is set when the clientStream is created (if EnableTracing is true), - // and is set to nil when the clientStream's finish method is called. +// csAttempt implements a single transport stream attempt within a +// clientStream. +type csAttempt struct { + cs *clientStream + t transport.ClientTransport + s *transport.Stream + p *parser + done func(balancer.DoneInfo) + + dc Decompressor + decomp encoding.Compressor + decompSet bool + + ctx context.Context // the application's context, wrapped by stats/tracing + + mu sync.Mutex // guards trInfo.tr + // trInfo.tr is set when created (if EnableTracing is true), + // and cleared when the finish method is called. trInfo traceInfo - // statsCtx keeps the user context for stats handling. - // All stats collection should use the statsCtx (instead of the stream context) - // so that all the generated stats for a particular RPC can be associated in the processing phase. - statsCtx context.Context statsHandler stats.Handler + beginTime time.Time } func (cs *clientStream) Context() context.Context { - return cs.s.Context() + // TODO(retry): commit the current attempt (the context has peer-aware data). + return cs.attempt.context() } func (cs *clientStream) Header() (metadata.MD, error) { - m, err := cs.s.Header() + m, err := cs.attempt.header() if err != nil { - if _, ok := err.(transport.ConnectionError); !ok { - cs.closeTransportStream(err) - } + // TODO(retry): maybe retry on error or commit attempt on success. + err = toRPCErr(err) + cs.finish(err) } return m, err } func (cs *clientStream) Trailer() metadata.MD { - return cs.s.Trailer() + // TODO(retry): on error, maybe retry (trailers-only). + return cs.attempt.trailer() } func (cs *clientStream) SendMsg(m interface{}) (err error) { - if cs.tracing { - cs.mu.Lock() - if cs.trInfo.tr != nil { - cs.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) - } + // TODO(retry): buffer message for replaying if not committed. + return cs.attempt.sendMsg(m) +} + +func (cs *clientStream) RecvMsg(m interface{}) (err error) { + // TODO(retry): maybe retry on error or commit attempt on success. + return cs.attempt.recvMsg(m) +} + +func (cs *clientStream) CloseSend() error { + cs.attempt.closeSend() + return nil +} + +func (cs *clientStream) finish(err error) { + if err == io.EOF { + // Ending a stream with EOF indicates a success. + err = nil + } + cs.mu.Lock() + if cs.finished { cs.mu.Unlock() + return + } + cs.finished = true + cs.mu.Unlock() + if channelz.IsOn() { + if err != nil { + cs.cc.incrCallsFailed() + } else { + cs.cc.incrCallsSucceeded() + } + } + // TODO(retry): commit current attempt if necessary. + cs.attempt.finish(err) + for _, o := range cs.opts { + o.after(cs.c) } + cs.cancel() +} + +func (a *csAttempt) context() context.Context { + return a.s.Context() +} + +func (a *csAttempt) header() (metadata.MD, error) { + return a.s.Header() +} + +func (a *csAttempt) trailer() metadata.MD { + return a.s.Trailer() +} + +func (a *csAttempt) sendMsg(m interface{}) (err error) { // TODO Investigate how to signal the stats handling party. // generate error stats if err != nil && err != io.EOF? + cs := a.cs defer func() { - if err != nil { - cs.finish(err) - } - if err == nil { - return - } - if err == io.EOF { - // Specialize the process for server streaming. SendMsg is only called - // once when creating the stream object. io.EOF needs to be skipped when - // the rpc is early finished (before the stream object is created.). - // TODO: It is probably better to move this into the generated code. - if !cs.desc.ClientStreams && cs.desc.ServerStreams { - err = nil - } - return + // For non-client-streaming RPCs, we return nil instead of EOF on success + // because the generated code requires it. finish is not called; RecvMsg() + // will call it with the stream's status independently. + if err == io.EOF && !cs.desc.ClientStreams { + err = nil } - if _, ok := err.(transport.ConnectionError); !ok { - cs.closeTransportStream(err) + if err != nil && err != io.EOF { + // Call finish on the client stream for errors generated by this SendMsg + // call, as these indicate problems created by this client. (Transport + // errors are converted to an io.EOF error below; the real error will be + // returned from RecvMsg eventually in that case, or be retried.) + cs.finish(err) } - err = toRPCErr(err) }() + // TODO: Check cs.sentLast and error if we already ended the stream. + if EnableTracing { + a.mu.Lock() + if a.trInfo.tr != nil { + a.trInfo.tr.LazyLog(&payload{sent: true, msg: m}, true) + } + a.mu.Unlock() + } var outPayload *stats.OutPayload - if cs.statsHandler != nil { + if a.statsHandler != nil { outPayload = &stats.OutPayload{ Client: true, } } - hdr, data, err := encode(cs.codec, m, cs.cp, bytes.NewBuffer([]byte{}), outPayload) + hdr, data, err := encode(cs.codec, m, cs.cp, outPayload, cs.comp) if err != nil { return err } - if cs.c.maxSendMessageSize == nil { - return Errorf(codes.Internal, "callInfo maxSendMessageSize field uninitialized(nil)") - } if len(data) > *cs.c.maxSendMessageSize { - return Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(data), *cs.c.maxSendMessageSize) + return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(data), *cs.c.maxSendMessageSize) } - err = cs.t.Write(cs.s, hdr, data, &transport.Options{Last: false}) - if err == nil && outPayload != nil { - outPayload.SentTime = time.Now() - cs.statsHandler.HandleRPC(cs.statsCtx, outPayload) + if !cs.desc.ClientStreams { + cs.sentLast = true } - return err + err = a.t.Write(a.s, hdr, data, &transport.Options{Last: !cs.desc.ClientStreams}) + if err == nil { + if outPayload != nil { + outPayload.SentTime = time.Now() + a.statsHandler.HandleRPC(a.ctx, outPayload) + } + if channelz.IsOn() { + a.t.IncrMsgSent() + } + return nil + } + return io.EOF } -func (cs *clientStream) RecvMsg(m interface{}) (err error) { +func (a *csAttempt) recvMsg(m interface{}) (err error) { + cs := a.cs + defer func() { + if err != nil || !cs.desc.ServerStreams { + // err != nil or non-server-streaming indicates end of stream. + cs.finish(err) + } + }() var inPayload *stats.InPayload - if cs.statsHandler != nil { + if a.statsHandler != nil { inPayload = &stats.InPayload{ Client: true, } } - if cs.c.maxReceiveMessageSize == nil { - return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)") - } - err = recv(cs.p, cs.codec, cs.s, cs.dc, m, *cs.c.maxReceiveMessageSize, inPayload) - defer func() { - // err != nil indicates the termination of the stream. - if err != nil { - cs.finish(err) - } - }() - if err == nil { - if cs.tracing { - cs.mu.Lock() - if cs.trInfo.tr != nil { - cs.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) + if !a.decompSet { + // Block until we receive headers containing received message encoding. + if ct := a.s.RecvCompress(); ct != "" && ct != encoding.Identity { + if a.dc == nil || a.dc.Type() != ct { + // No configured decompressor, or it does not match the incoming + // message encoding; attempt to find a registered compressor that does. + a.dc = nil + a.decomp = encoding.GetCompressor(ct) } - cs.mu.Unlock() - } - if inPayload != nil { - cs.statsHandler.HandleRPC(cs.statsCtx, inPayload) - } - if !cs.desc.ClientStreams || cs.desc.ServerStreams { - return - } - // Special handling for client streaming rpc. - // This recv expects EOF or errors, so we don't collect inPayload. - if cs.c.maxReceiveMessageSize == nil { - return Errorf(codes.Internal, "callInfo maxReceiveMessageSize field uninitialized(nil)") - } - err = recv(cs.p, cs.codec, cs.s, cs.dc, m, *cs.c.maxReceiveMessageSize, nil) - cs.closeTransportStream(err) - if err == nil { - return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>")) + } else { + // No compression is used; disable our decompressor. + a.dc = nil } + // Only initialize this state once per stream. + a.decompSet = true + } + err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.c.maxReceiveMessageSize, inPayload, a.decomp) + if err != nil { if err == io.EOF { - if se := cs.s.Status().Err(); se != nil { - return se + if statusErr := a.s.Status().Err(); statusErr != nil { + return statusErr } - cs.finish(err) - return nil + return io.EOF // indicates successful end of stream. } return toRPCErr(err) } - if _, ok := err.(transport.ConnectionError); !ok { - cs.closeTransportStream(err) - } - if err == io.EOF { - if statusErr := cs.s.Status().Err(); statusErr != nil { - return statusErr + if EnableTracing { + a.mu.Lock() + if a.trInfo.tr != nil { + a.trInfo.tr.LazyLog(&payload{sent: false, msg: m}, true) } - // Returns io.EOF to indicate the end of the stream. - return + a.mu.Unlock() } - return toRPCErr(err) -} - -func (cs *clientStream) CloseSend() (err error) { - err = cs.t.Write(cs.s, nil, nil, &transport.Options{Last: true}) - defer func() { - if err != nil { - cs.finish(err) - } - }() - if err == nil || err == io.EOF { + if inPayload != nil { + a.statsHandler.HandleRPC(a.ctx, inPayload) + } + if channelz.IsOn() { + a.t.IncrMsgRecv() + } + if cs.desc.ServerStreams { + // Subsequent messages should be received by subsequent RecvMsg calls. return nil } - if _, ok := err.(transport.ConnectionError); !ok { - cs.closeTransportStream(err) + + // Special handling for non-server-stream rpcs. + // This recv expects EOF or errors, so we don't collect inPayload. + err = recv(a.p, cs.codec, a.s, a.dc, m, *cs.c.maxReceiveMessageSize, nil, a.decomp) + if err == nil { + return toRPCErr(errors.New("grpc: client streaming protocol violation: get <nil>, want <EOF>")) + } + if err == io.EOF { + return a.s.Status().Err() // non-server streaming Recv returns nil on success } - err = toRPCErr(err) - return + return toRPCErr(err) } -func (cs *clientStream) closeTransportStream(err error) { - cs.mu.Lock() - if cs.closed { - cs.mu.Unlock() +func (a *csAttempt) closeSend() { + cs := a.cs + if cs.sentLast { return } - cs.closed = true - cs.mu.Unlock() - cs.t.CloseStream(cs.s, err) + cs.sentLast = true + cs.attempt.t.Write(cs.attempt.s, nil, nil, &transport.Options{Last: true}) + // We ignore errors from Write. Any error it would return would also be + // returned by a subsequent RecvMsg call, and the user is supposed to always + // finish the stream by calling RecvMsg until it returns err != nil. } -func (cs *clientStream) finish(err error) { - cs.mu.Lock() - defer cs.mu.Unlock() - if cs.finished { - return - } - cs.finished = true - defer func() { - if cs.cancel != nil { - cs.cancel() - } - }() - for _, o := range cs.opts { - o.after(cs.c) - } - if cs.done != nil { - updateRPCInfoInContext(cs.s.Context(), rpcInfo{ - bytesSent: cs.s.BytesSent(), - bytesReceived: cs.s.BytesReceived(), +func (a *csAttempt) finish(err error) { + a.mu.Lock() + a.t.CloseStream(a.s, err) + + if a.done != nil { + a.done(balancer.DoneInfo{ + Err: err, + BytesSent: true, + BytesReceived: a.s.BytesReceived(), }) - cs.done(balancer.DoneInfo{Err: err}) - cs.done = nil } - if cs.statsHandler != nil { + if a.statsHandler != nil { end := &stats.End{ - Client: true, - EndTime: time.Now(), - } - if err != io.EOF { - // end.Error is nil if the RPC finished successfully. - end.Error = toRPCErr(err) + Client: true, + BeginTime: a.beginTime, + EndTime: time.Now(), + Error: err, } - cs.statsHandler.HandleRPC(cs.statsCtx, end) + a.statsHandler.HandleRPC(a.ctx, end) } - if !cs.tracing { - return - } - if cs.trInfo.tr != nil { - if err == nil || err == io.EOF { - cs.trInfo.tr.LazyPrintf("RPC: [OK]") + if a.trInfo.tr != nil { + if err == nil { + a.trInfo.tr.LazyPrintf("RPC: [OK]") } else { - cs.trInfo.tr.LazyPrintf("RPC: [%v]", err) - cs.trInfo.tr.SetError() + a.trInfo.tr.LazyPrintf("RPC: [%v]", err) + a.trInfo.tr.SetError() } - cs.trInfo.tr.Finish() - cs.trInfo.tr = nil + a.trInfo.tr.Finish() + a.trInfo.tr = nil } + a.mu.Unlock() } // ServerStream defines the interface a server stream has to satisfy. @@ -540,12 +632,17 @@ type ServerStream interface { // serverStream implements a server side Stream. type serverStream struct { - t transport.ServerTransport - s *transport.Stream - p *parser - codec Codec - cp Compressor - dc Decompressor + ctx context.Context + t transport.ServerTransport + s *transport.Stream + p *parser + codec baseCodec + + cp Compressor + dc Decompressor + comp encoding.Compressor + decomp encoding.Compressor + maxReceiveMessageSize int maxSendMessageSize int trInfo *traceInfo @@ -556,7 +653,7 @@ type serverStream struct { } func (ss *serverStream) Context() context.Context { - return ss.s.Context() + return ss.ctx } func (ss *serverStream) SetHeader(md metadata.MD) error { @@ -575,7 +672,6 @@ func (ss *serverStream) SetTrailer(md metadata.MD) { return } ss.s.SetTrailer(md) - return } func (ss *serverStream) SendMsg(m interface{}) (err error) { @@ -596,17 +692,20 @@ func (ss *serverStream) SendMsg(m interface{}) (err error) { st, _ := status.FromError(toRPCErr(err)) ss.t.WriteStatus(ss.s, st) } + if channelz.IsOn() && err == nil { + ss.t.IncrMsgSent() + } }() var outPayload *stats.OutPayload if ss.statsHandler != nil { outPayload = &stats.OutPayload{} } - hdr, data, err := encode(ss.codec, m, ss.cp, bytes.NewBuffer([]byte{}), outPayload) + hdr, data, err := encode(ss.codec, m, ss.cp, outPayload, ss.comp) if err != nil { return err } if len(data) > ss.maxSendMessageSize { - return Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(data), ss.maxSendMessageSize) + return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", len(data), ss.maxSendMessageSize) } if err := ss.t.Write(ss.s, hdr, data, &transport.Options{Last: false}); err != nil { return toRPCErr(err) @@ -636,17 +735,20 @@ func (ss *serverStream) RecvMsg(m interface{}) (err error) { st, _ := status.FromError(toRPCErr(err)) ss.t.WriteStatus(ss.s, st) } + if channelz.IsOn() && err == nil { + ss.t.IncrMsgRecv() + } }() var inPayload *stats.InPayload if ss.statsHandler != nil { inPayload = &stats.InPayload{} } - if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload); err != nil { + if err := recv(ss.p, ss.codec, ss.s, ss.dc, m, ss.maxReceiveMessageSize, inPayload, ss.decomp); err != nil { if err == io.EOF { return err } if err == io.ErrUnexpectedEOF { - err = Errorf(codes.Internal, io.ErrUnexpectedEOF.Error()) + err = status.Errorf(codes.Internal, io.ErrUnexpectedEOF.Error()) } return toRPCErr(err) } @@ -655,3 +757,9 @@ func (ss *serverStream) RecvMsg(m interface{}) (err error) { } return nil } + +// MethodFromServerStream returns the method string for the input stream. +// The returned string is in the format of "/service/method". +func MethodFromServerStream(stream ServerStream) (string, bool) { + return Method(stream.Context()) +} diff --git a/vendor/google.golang.org/grpc/transport/bdp_estimator.go b/vendor/google.golang.org/grpc/transport/bdp_estimator.go index 8dd2ed4279..63cd2627c8 100644 --- a/vendor/google.golang.org/grpc/transport/bdp_estimator.go +++ b/vendor/google.golang.org/grpc/transport/bdp_estimator.go @@ -41,12 +41,9 @@ const ( gamma = 2 ) -var ( - // Adding arbitrary data to ping so that its ack can be - // identified. - // Easter-egg: what does the ping message say? - bdpPing = &ping{data: [8]byte{2, 4, 16, 16, 9, 14, 7, 7}} -) +// Adding arbitrary data to ping so that its ack can be identified. +// Easter-egg: what does the ping message say? +var bdpPing = &ping{data: [8]byte{2, 4, 16, 16, 9, 14, 7, 7}} type bdpEstimator struct { // sentAt is the time when the ping was sent. diff --git a/vendor/google.golang.org/grpc/transport/controlbuf.go b/vendor/google.golang.org/grpc/transport/controlbuf.go new file mode 100644 index 0000000000..e147cd51bf --- /dev/null +++ b/vendor/google.golang.org/grpc/transport/controlbuf.go @@ -0,0 +1,769 @@ +/* + * + * Copyright 2014 gRPC 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 transport + +import ( + "bytes" + "fmt" + "runtime" + "sync" + + "golang.org/x/net/http2" + "golang.org/x/net/http2/hpack" +) + +type itemNode struct { + it interface{} + next *itemNode +} + +type itemList struct { + head *itemNode + tail *itemNode +} + +func (il *itemList) enqueue(i interface{}) { + n := &itemNode{it: i} + if il.tail == nil { + il.head, il.tail = n, n + return + } + il.tail.next = n + il.tail = n +} + +// peek returns the first item in the list without removing it from the +// list. +func (il *itemList) peek() interface{} { + return il.head.it +} + +func (il *itemList) dequeue() interface{} { + if il.head == nil { + return nil + } + i := il.head.it + il.head = il.head.next + if il.head == nil { + il.tail = nil + } + return i +} + +func (il *itemList) dequeueAll() *itemNode { + h := il.head + il.head, il.tail = nil, nil + return h +} + +func (il *itemList) isEmpty() bool { + return il.head == nil +} + +// The following defines various control items which could flow through +// the control buffer of transport. They represent different aspects of +// control tasks, e.g., flow control, settings, streaming resetting, etc. + +type headerFrame struct { + streamID uint32 + hf []hpack.HeaderField + endStream bool // Valid on server side. + initStream func(uint32) (bool, error) // Used only on the client side. + onWrite func() + wq *writeQuota // write quota for the stream created. + cleanup *cleanupStream // Valid on the server side. + onOrphaned func(error) // Valid on client-side +} + +type cleanupStream struct { + streamID uint32 + idPtr *uint32 + rst bool + rstCode http2.ErrCode + onWrite func() +} + +type dataFrame struct { + streamID uint32 + endStream bool + h []byte + d []byte + // onEachWrite is called every time + // a part of d is written out. + onEachWrite func() +} + +type incomingWindowUpdate struct { + streamID uint32 + increment uint32 +} + +type outgoingWindowUpdate struct { + streamID uint32 + increment uint32 +} + +type incomingSettings struct { + ss []http2.Setting +} + +type outgoingSettings struct { + ss []http2.Setting +} + +type settingsAck struct { +} + +type incomingGoAway struct { +} + +type goAway struct { + code http2.ErrCode + debugData []byte + headsUp bool + closeConn bool +} + +type ping struct { + ack bool + data [8]byte +} + +type outFlowControlSizeRequest struct { + resp chan uint32 +} + +type outStreamState int + +const ( + active outStreamState = iota + empty + waitingOnStreamQuota +) + +type outStream struct { + id uint32 + state outStreamState + itl *itemList + bytesOutStanding int + wq *writeQuota + + next *outStream + prev *outStream +} + +func (s *outStream) deleteSelf() { + if s.prev != nil { + s.prev.next = s.next + } + if s.next != nil { + s.next.prev = s.prev + } + s.next, s.prev = nil, nil +} + +type outStreamList struct { + // Following are sentinel objects that mark the + // beginning and end of the list. They do not + // contain any item lists. All valid objects are + // inserted in between them. + // This is needed so that an outStream object can + // deleteSelf() in O(1) time without knowing which + // list it belongs to. + head *outStream + tail *outStream +} + +func newOutStreamList() *outStreamList { + head, tail := new(outStream), new(outStream) + head.next = tail + tail.prev = head + return &outStreamList{ + head: head, + tail: tail, + } +} + +func (l *outStreamList) enqueue(s *outStream) { + e := l.tail.prev + e.next = s + s.prev = e + s.next = l.tail + l.tail.prev = s +} + +// remove from the beginning of the list. +func (l *outStreamList) dequeue() *outStream { + b := l.head.next + if b == l.tail { + return nil + } + b.deleteSelf() + return b +} + +type controlBuffer struct { + ch chan struct{} + done <-chan struct{} + mu sync.Mutex + consumerWaiting bool + list *itemList + err error +} + +func newControlBuffer(done <-chan struct{}) *controlBuffer { + return &controlBuffer{ + ch: make(chan struct{}, 1), + list: &itemList{}, + done: done, + } +} + +func (c *controlBuffer) put(it interface{}) error { + _, err := c.executeAndPut(nil, it) + return err +} + +func (c *controlBuffer) executeAndPut(f func(it interface{}) bool, it interface{}) (bool, error) { + var wakeUp bool + c.mu.Lock() + if c.err != nil { + c.mu.Unlock() + return false, c.err + } + if f != nil { + if !f(it) { // f wasn't successful + c.mu.Unlock() + return false, nil + } + } + if c.consumerWaiting { + wakeUp = true + c.consumerWaiting = false + } + c.list.enqueue(it) + c.mu.Unlock() + if wakeUp { + select { + case c.ch <- struct{}{}: + default: + } + } + return true, nil +} + +func (c *controlBuffer) get(block bool) (interface{}, error) { + for { + c.mu.Lock() + if c.err != nil { + c.mu.Unlock() + return nil, c.err + } + if !c.list.isEmpty() { + h := c.list.dequeue() + c.mu.Unlock() + return h, nil + } + if !block { + c.mu.Unlock() + return nil, nil + } + c.consumerWaiting = true + c.mu.Unlock() + select { + case <-c.ch: + case <-c.done: + c.finish() + return nil, ErrConnClosing + } + } +} + +func (c *controlBuffer) finish() { + c.mu.Lock() + if c.err != nil { + c.mu.Unlock() + return + } + c.err = ErrConnClosing + // There may be headers for streams in the control buffer. + // These streams need to be cleaned out since the transport + // is still not aware of these yet. + for head := c.list.dequeueAll(); head != nil; head = head.next { + hdr, ok := head.it.(*headerFrame) + if !ok { + continue + } + if hdr.onOrphaned != nil { // It will be nil on the server-side. + hdr.onOrphaned(ErrConnClosing) + } + } + c.mu.Unlock() +} + +type side int + +const ( + clientSide side = iota + serverSide +) + +type loopyWriter struct { + side side + cbuf *controlBuffer + sendQuota uint32 + oiws uint32 // outbound initial window size. + estdStreams map[uint32]*outStream // Established streams. + activeStreams *outStreamList // Streams that are sending data. + framer *framer + hBuf *bytes.Buffer // The buffer for HPACK encoding. + hEnc *hpack.Encoder // HPACK encoder. + bdpEst *bdpEstimator + draining bool + + // Side-specific handlers + ssGoAwayHandler func(*goAway) (bool, error) +} + +func newLoopyWriter(s side, fr *framer, cbuf *controlBuffer, bdpEst *bdpEstimator) *loopyWriter { + var buf bytes.Buffer + l := &loopyWriter{ + side: s, + cbuf: cbuf, + sendQuota: defaultWindowSize, + oiws: defaultWindowSize, + estdStreams: make(map[uint32]*outStream), + activeStreams: newOutStreamList(), + framer: fr, + hBuf: &buf, + hEnc: hpack.NewEncoder(&buf), + bdpEst: bdpEst, + } + return l +} + +const minBatchSize = 1000 + +// run should be run in a separate goroutine. +func (l *loopyWriter) run() { + var ( + it interface{} + err error + isEmpty bool + ) + defer func() { + errorf("transport: loopyWriter.run returning. Err: %v", err) + }() + for { + it, err = l.cbuf.get(true) + if err != nil { + return + } + if err = l.handle(it); err != nil { + return + } + if _, err = l.processData(); err != nil { + return + } + gosched := true + hasdata: + for { + it, err = l.cbuf.get(false) + if err != nil { + return + } + if it != nil { + if err = l.handle(it); err != nil { + return + } + if _, err = l.processData(); err != nil { + return + } + continue hasdata + } + if isEmpty, err = l.processData(); err != nil { + return + } + if !isEmpty { + continue hasdata + } + if gosched { + gosched = false + if l.framer.writer.offset < minBatchSize { + runtime.Gosched() + continue hasdata + } + } + l.framer.writer.Flush() + break hasdata + + } + } +} + +func (l *loopyWriter) outgoingWindowUpdateHandler(w *outgoingWindowUpdate) error { + return l.framer.fr.WriteWindowUpdate(w.streamID, w.increment) +} + +func (l *loopyWriter) incomingWindowUpdateHandler(w *incomingWindowUpdate) error { + // Otherwise update the quota. + if w.streamID == 0 { + l.sendQuota += w.increment + return nil + } + // Find the stream and update it. + if str, ok := l.estdStreams[w.streamID]; ok { + str.bytesOutStanding -= int(w.increment) + if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota > 0 && str.state == waitingOnStreamQuota { + str.state = active + l.activeStreams.enqueue(str) + return nil + } + } + return nil +} + +func (l *loopyWriter) outgoingSettingsHandler(s *outgoingSettings) error { + return l.framer.fr.WriteSettings(s.ss...) +} + +func (l *loopyWriter) incomingSettingsHandler(s *incomingSettings) error { + if err := l.applySettings(s.ss); err != nil { + return err + } + return l.framer.fr.WriteSettingsAck() +} + +func (l *loopyWriter) headerHandler(h *headerFrame) error { + if l.side == serverSide { + if h.endStream { // Case 1.A: Server wants to close stream. + // Make sure it's not a trailers only response. + if str, ok := l.estdStreams[h.streamID]; ok { + if str.state != empty { // either active or waiting on stream quota. + // add it str's list of items. + str.itl.enqueue(h) + return nil + } + } + if err := l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite); err != nil { + return err + } + return l.cleanupStreamHandler(h.cleanup) + } + // Case 1.B: Server is responding back with headers. + str := &outStream{ + state: empty, + itl: &itemList{}, + wq: h.wq, + } + l.estdStreams[h.streamID] = str + return l.writeHeader(h.streamID, h.endStream, h.hf, h.onWrite) + } + // Case 2: Client wants to originate stream. + str := &outStream{ + id: h.streamID, + state: empty, + itl: &itemList{}, + wq: h.wq, + } + str.itl.enqueue(h) + return l.originateStream(str) +} + +func (l *loopyWriter) originateStream(str *outStream) error { + hdr := str.itl.dequeue().(*headerFrame) + sendPing, err := hdr.initStream(str.id) + if err != nil { + if err == ErrConnClosing { + return err + } + // Other errors(errStreamDrain) need not close transport. + return nil + } + if err = l.writeHeader(str.id, hdr.endStream, hdr.hf, hdr.onWrite); err != nil { + return err + } + l.estdStreams[str.id] = str + if sendPing { + return l.pingHandler(&ping{data: [8]byte{}}) + } + return nil +} + +func (l *loopyWriter) writeHeader(streamID uint32, endStream bool, hf []hpack.HeaderField, onWrite func()) error { + if onWrite != nil { + onWrite() + } + l.hBuf.Reset() + for _, f := range hf { + if err := l.hEnc.WriteField(f); err != nil { + warningf("transport: loopyWriter.writeHeader encountered error while encoding headers:", err) + } + } + var ( + err error + endHeaders, first bool + ) + first = true + for !endHeaders { + size := l.hBuf.Len() + if size > http2MaxFrameLen { + size = http2MaxFrameLen + } else { + endHeaders = true + } + if first { + first = false + err = l.framer.fr.WriteHeaders(http2.HeadersFrameParam{ + StreamID: streamID, + BlockFragment: l.hBuf.Next(size), + EndStream: endStream, + EndHeaders: endHeaders, + }) + } else { + err = l.framer.fr.WriteContinuation( + streamID, + endHeaders, + l.hBuf.Next(size), + ) + } + if err != nil { + return err + } + } + return nil +} + +func (l *loopyWriter) preprocessData(df *dataFrame) error { + str, ok := l.estdStreams[df.streamID] + if !ok { + return nil + } + // If we got data for a stream it means that + // stream was originated and the headers were sent out. + str.itl.enqueue(df) + if str.state == empty { + str.state = active + l.activeStreams.enqueue(str) + } + return nil +} + +func (l *loopyWriter) pingHandler(p *ping) error { + if !p.ack { + l.bdpEst.timesnap(p.data) + } + return l.framer.fr.WritePing(p.ack, p.data) + +} + +func (l *loopyWriter) outFlowControlSizeRequestHandler(o *outFlowControlSizeRequest) error { + o.resp <- l.sendQuota + return nil +} + +func (l *loopyWriter) cleanupStreamHandler(c *cleanupStream) error { + c.onWrite() + if str, ok := l.estdStreams[c.streamID]; ok { + // On the server side it could be a trailers-only response or + // a RST_STREAM before stream initialization thus the stream might + // not be established yet. + delete(l.estdStreams, c.streamID) + str.deleteSelf() + } + if c.rst { // If RST_STREAM needs to be sent. + if err := l.framer.fr.WriteRSTStream(c.streamID, c.rstCode); err != nil { + return err + } + } + if l.side == clientSide && l.draining && len(l.estdStreams) == 0 { + return ErrConnClosing + } + return nil +} + +func (l *loopyWriter) incomingGoAwayHandler(*incomingGoAway) error { + if l.side == clientSide { + l.draining = true + if len(l.estdStreams) == 0 { + return ErrConnClosing + } + } + return nil +} + +func (l *loopyWriter) goAwayHandler(g *goAway) error { + // Handling of outgoing GoAway is very specific to side. + if l.ssGoAwayHandler != nil { + draining, err := l.ssGoAwayHandler(g) + if err != nil { + return err + } + l.draining = draining + } + return nil +} + +func (l *loopyWriter) handle(i interface{}) error { + switch i := i.(type) { + case *incomingWindowUpdate: + return l.incomingWindowUpdateHandler(i) + case *outgoingWindowUpdate: + return l.outgoingWindowUpdateHandler(i) + case *incomingSettings: + return l.incomingSettingsHandler(i) + case *outgoingSettings: + return l.outgoingSettingsHandler(i) + case *headerFrame: + return l.headerHandler(i) + case *cleanupStream: + return l.cleanupStreamHandler(i) + case *incomingGoAway: + return l.incomingGoAwayHandler(i) + case *dataFrame: + return l.preprocessData(i) + case *ping: + return l.pingHandler(i) + case *goAway: + return l.goAwayHandler(i) + case *outFlowControlSizeRequest: + return l.outFlowControlSizeRequestHandler(i) + default: + return fmt.Errorf("transport: unknown control message type %T", i) + } +} + +func (l *loopyWriter) applySettings(ss []http2.Setting) error { + for _, s := range ss { + switch s.ID { + case http2.SettingInitialWindowSize: + o := l.oiws + l.oiws = s.Val + if o < l.oiws { + // If the new limit is greater make all depleted streams active. + for _, stream := range l.estdStreams { + if stream.state == waitingOnStreamQuota { + stream.state = active + l.activeStreams.enqueue(stream) + } + } + } + } + } + return nil +} + +func (l *loopyWriter) processData() (bool, error) { + if l.sendQuota == 0 { + return true, nil + } + str := l.activeStreams.dequeue() + if str == nil { + return true, nil + } + dataItem := str.itl.peek().(*dataFrame) + if len(dataItem.h) == 0 && len(dataItem.d) == 0 { + // Client sends out empty data frame with endStream = true + if err := l.framer.fr.WriteData(dataItem.streamID, dataItem.endStream, nil); err != nil { + return false, err + } + str.itl.dequeue() + if str.itl.isEmpty() { + str.state = empty + } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // the next item is trailers. + if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { + return false, err + } + if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { + return false, nil + } + } else { + l.activeStreams.enqueue(str) + } + return false, nil + } + var ( + idx int + buf []byte + ) + if len(dataItem.h) != 0 { // data header has not been written out yet. + buf = dataItem.h + } else { + idx = 1 + buf = dataItem.d + } + size := http2MaxFrameLen + if len(buf) < size { + size = len(buf) + } + if strQuota := int(l.oiws) - str.bytesOutStanding; strQuota <= 0 { + str.state = waitingOnStreamQuota + return false, nil + } else if strQuota < size { + size = strQuota + } + + if l.sendQuota < uint32(size) { + size = int(l.sendQuota) + } + // Now that outgoing flow controls are checked we can replenish str's write quota + str.wq.replenish(size) + var endStream bool + // This last data message on this stream and all + // of it can be written in this go. + if dataItem.endStream && size == len(buf) { + // buf contains either data or it contains header but data is empty. + if idx == 1 || len(dataItem.d) == 0 { + endStream = true + } + } + if dataItem.onEachWrite != nil { + dataItem.onEachWrite() + } + if err := l.framer.fr.WriteData(dataItem.streamID, endStream, buf[:size]); err != nil { + return false, err + } + buf = buf[size:] + str.bytesOutStanding += size + l.sendQuota -= uint32(size) + if idx == 0 { + dataItem.h = buf + } else { + dataItem.d = buf + } + + if len(dataItem.h) == 0 && len(dataItem.d) == 0 { // All the data from that message was written out. + str.itl.dequeue() + } + if str.itl.isEmpty() { + str.state = empty + } else if trailer, ok := str.itl.peek().(*headerFrame); ok { // The next item is trailers. + if err := l.writeHeader(trailer.streamID, trailer.endStream, trailer.hf, trailer.onWrite); err != nil { + return false, err + } + if err := l.cleanupStreamHandler(trailer.cleanup); err != nil { + return false, err + } + } else if int(l.oiws)-str.bytesOutStanding <= 0 { // Ran out of stream quota. + str.state = waitingOnStreamQuota + } else { // Otherwise add it back to the list of active streams. + l.activeStreams.enqueue(str) + } + return false, nil +} diff --git a/vendor/google.golang.org/grpc/transport/control.go b/vendor/google.golang.org/grpc/transport/flowcontrol.go similarity index 51% rename from vendor/google.golang.org/grpc/transport/control.go rename to vendor/google.golang.org/grpc/transport/flowcontrol.go index dd1a8d42e7..378f5c4502 100644 --- a/vendor/google.golang.org/grpc/transport/control.go +++ b/vendor/google.golang.org/grpc/transport/flowcontrol.go @@ -24,9 +24,6 @@ import ( "sync" "sync/atomic" "time" - - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" ) const ( @@ -36,179 +33,109 @@ const ( initialWindowSize = defaultWindowSize // for an RPC infinity = time.Duration(math.MaxInt64) defaultClientKeepaliveTime = infinity - defaultClientKeepaliveTimeout = time.Duration(20 * time.Second) + defaultClientKeepaliveTimeout = 20 * time.Second defaultMaxStreamsClient = 100 defaultMaxConnectionIdle = infinity defaultMaxConnectionAge = infinity defaultMaxConnectionAgeGrace = infinity - defaultServerKeepaliveTime = time.Duration(2 * time.Hour) - defaultServerKeepaliveTimeout = time.Duration(20 * time.Second) - defaultKeepalivePolicyMinTime = time.Duration(5 * time.Minute) + defaultServerKeepaliveTime = 2 * time.Hour + defaultServerKeepaliveTimeout = 20 * time.Second + defaultKeepalivePolicyMinTime = 5 * time.Minute // max window limit set by HTTP2 Specs. maxWindowSize = math.MaxInt32 - // defaultLocalSendQuota sets is default value for number of data + // defaultWriteQuota is the default value for number of data // bytes that each stream can schedule before some of it being // flushed out. - defaultLocalSendQuota = 64 * 1024 + defaultWriteQuota = 64 * 1024 ) -// The following defines various control items which could flow through -// the control buffer of transport. They represent different aspects of -// control tasks, e.g., flow control, settings, streaming resetting, etc. - -type headerFrame struct { - streamID uint32 - hf []hpack.HeaderField - endStream bool -} - -func (*headerFrame) item() {} - -type continuationFrame struct { - streamID uint32 - endHeaders bool - headerBlockFragment []byte -} - -type dataFrame struct { - streamID uint32 - endStream bool - d []byte - f func() -} - -func (*dataFrame) item() {} - -func (*continuationFrame) item() {} - -type windowUpdate struct { - streamID uint32 - increment uint32 -} - -func (*windowUpdate) item() {} - -type settings struct { - ack bool - ss []http2.Setting -} - -func (*settings) item() {} - -type resetStream struct { - streamID uint32 - code http2.ErrCode -} - -func (*resetStream) item() {} - -type goAway struct { - code http2.ErrCode - debugData []byte - headsUp bool - closeConn bool -} - -func (*goAway) item() {} - -type flushIO struct { -} - -func (*flushIO) item() {} - -type ping struct { - ack bool - data [8]byte +// writeQuota is a soft limit on the amount of data a stream can +// schedule before some of it is written out. +type writeQuota struct { + quota int32 + // get waits on read from when quota goes less than or equal to zero. + // replenish writes on it when quota goes positive again. + ch chan struct{} + // done is triggered in error case. + done <-chan struct{} +} + +func newWriteQuota(sz int32, done <-chan struct{}) *writeQuota { + return &writeQuota{ + quota: sz, + ch: make(chan struct{}, 1), + done: done, + } } -func (*ping) item() {} - -// quotaPool is a pool which accumulates the quota and sends it to acquire() -// when it is available. -type quotaPool struct { - c chan int - - mu sync.Mutex - version uint32 - quota int +func (w *writeQuota) get(sz int32) error { + for { + if atomic.LoadInt32(&w.quota) > 0 { + atomic.AddInt32(&w.quota, -sz) + return nil + } + select { + case <-w.ch: + continue + case <-w.done: + return errStreamDone + } + } } -// newQuotaPool creates a quotaPool which has quota q available to consume. -func newQuotaPool(q int) *quotaPool { - qb := &quotaPool{ - c: make(chan int, 1), - } - if q > 0 { - qb.c <- q - } else { - qb.quota = q +func (w *writeQuota) replenish(n int) { + sz := int32(n) + a := atomic.AddInt32(&w.quota, sz) + b := a - sz + if b <= 0 && a > 0 { + select { + case w.ch <- struct{}{}: + default: + } } - return qb } -// add cancels the pending quota sent on acquired, incremented by v and sends -// it back on acquire. -func (qb *quotaPool) add(v int) { - qb.mu.Lock() - defer qb.mu.Unlock() - qb.lockedAdd(v) +type trInFlow struct { + limit uint32 + unacked uint32 + effectiveWindowSize uint32 } -func (qb *quotaPool) lockedAdd(v int) { - select { - case n := <-qb.c: - qb.quota += n - default: - } - qb.quota += v - if qb.quota <= 0 { - return - } - // After the pool has been created, this is the only place that sends on - // the channel. Since mu is held at this point and any quota that was sent - // on the channel has been retrieved, we know that this code will always - // place any positive quota value on the channel. - select { - case qb.c <- qb.quota: - qb.quota = 0 - default: - } +func (f *trInFlow) newLimit(n uint32) uint32 { + d := n - f.limit + f.limit = n + f.updateEffectiveWindowSize() + return d } -func (qb *quotaPool) addAndUpdate(v int) { - qb.mu.Lock() - defer qb.mu.Unlock() - qb.lockedAdd(v) - // Update the version only after having added to the quota - // so that if acquireWithVesrion sees the new vesrion it is - // guaranteed to have seen the updated quota. - // Also, still keep this inside of the lock, so that when - // compareAndExecute is processing, this function doesn't - // get executed partially (quota gets updated but the version - // doesn't). - atomic.AddUint32(&(qb.version), 1) +func (f *trInFlow) onData(n uint32) uint32 { + f.unacked += n + if f.unacked >= f.limit/4 { + w := f.unacked + f.unacked = 0 + f.updateEffectiveWindowSize() + return w + } + f.updateEffectiveWindowSize() + return 0 } -func (qb *quotaPool) acquireWithVersion() (<-chan int, uint32) { - return qb.c, atomic.LoadUint32(&(qb.version)) +func (f *trInFlow) reset() uint32 { + w := f.unacked + f.unacked = 0 + f.updateEffectiveWindowSize() + return w } -func (qb *quotaPool) compareAndExecute(version uint32, success, failure func()) bool { - qb.mu.Lock() - defer qb.mu.Unlock() - if version == atomic.LoadUint32(&(qb.version)) { - success() - return true - } - failure() - return false +func (f *trInFlow) updateEffectiveWindowSize() { + atomic.StoreUint32(&f.effectiveWindowSize, f.limit-f.unacked) } -// acquire returns the channel on which available quota amounts are sent. -func (qb *quotaPool) acquire() <-chan int { - return qb.c +func (f *trInFlow) getSize() uint32 { + return atomic.LoadUint32(&f.effectiveWindowSize) } +// TODO(mmukhi): Simplify this code. // inFlow deals with inbound flow control type inFlow struct { mu sync.Mutex @@ -229,9 +156,9 @@ type inFlow struct { // It assumes that n is always greater than the old limit. func (f *inFlow) newLimit(n uint32) uint32 { f.mu.Lock() - defer f.mu.Unlock() d := n - f.limit f.limit = n + f.mu.Unlock() return d } @@ -240,7 +167,6 @@ func (f *inFlow) maybeAdjust(n uint32) uint32 { n = uint32(math.MaxInt32) } f.mu.Lock() - defer f.mu.Unlock() // estSenderQuota is the receiver's view of the maximum number of bytes the sender // can send without a window update. estSenderQuota := int32(f.limit - (f.pendingData + f.pendingUpdate)) @@ -252,7 +178,7 @@ func (f *inFlow) maybeAdjust(n uint32) uint32 { // for this message. Therefore we must send an update over the limit since there's an active read // request from the application. if estUntransmittedData > estSenderQuota { - // Sender's window shouldn't go more than 2^31 - 1 as speecified in the HTTP spec. + // Sender's window shouldn't go more than 2^31 - 1 as specified in the HTTP spec. if f.limit+n > maxWindowSize { f.delta = maxWindowSize - f.limit } else { @@ -261,19 +187,24 @@ func (f *inFlow) maybeAdjust(n uint32) uint32 { // is padded; We will fallback on the current available window(at least a 1/4th of the limit). f.delta = n } + f.mu.Unlock() return f.delta } + f.mu.Unlock() return 0 } // onData is invoked when some data frame is received. It updates pendingData. func (f *inFlow) onData(n uint32) error { f.mu.Lock() - defer f.mu.Unlock() f.pendingData += n if f.pendingData+f.pendingUpdate > f.limit+f.delta { - return fmt.Errorf("received %d-bytes data exceeding the limit %d bytes", f.pendingData+f.pendingUpdate, f.limit) + limit := f.limit + rcvd := f.pendingData + f.pendingUpdate + f.mu.Unlock() + return fmt.Errorf("received %d-bytes data exceeding the limit %d bytes", rcvd, limit) } + f.mu.Unlock() return nil } @@ -281,8 +212,8 @@ func (f *inFlow) onData(n uint32) error { // to be sent to the peer. func (f *inFlow) onRead(n uint32) uint32 { f.mu.Lock() - defer f.mu.Unlock() if f.pendingData == 0 { + f.mu.Unlock() return 0 } f.pendingData -= n @@ -297,15 +228,9 @@ func (f *inFlow) onRead(n uint32) uint32 { if f.pendingUpdate >= f.limit/4 { wu := f.pendingUpdate f.pendingUpdate = 0 + f.mu.Unlock() return wu } + f.mu.Unlock() return 0 } - -func (f *inFlow) resetPendingUpdate() uint32 { - f.mu.Lock() - defer f.mu.Unlock() - n := f.pendingUpdate - f.pendingUpdate = 0 - return n -} diff --git a/vendor/google.golang.org/grpc/transport/go16.go b/vendor/google.golang.org/grpc/transport/go16.go new file mode 100644 index 0000000000..5babcf9b87 --- /dev/null +++ b/vendor/google.golang.org/grpc/transport/go16.go @@ -0,0 +1,51 @@ +// +build go1.6,!go1.7 + +/* + * + * Copyright 2016 gRPC 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 transport + +import ( + "net" + "net/http" + + "google.golang.org/grpc/codes" + + "golang.org/x/net/context" +) + +// dialContext connects to the address on the named network. +func dialContext(ctx context.Context, network, address string) (net.Conn, error) { + return (&net.Dialer{Cancel: ctx.Done()}).Dial(network, address) +} + +// ContextErr converts the error from context package into a StreamError. +func ContextErr(err error) StreamError { + switch err { + case context.DeadlineExceeded: + return streamErrorf(codes.DeadlineExceeded, "%v", err) + case context.Canceled: + return streamErrorf(codes.Canceled, "%v", err) + } + return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) +} + +// contextFromRequest returns a background context. +func contextFromRequest(r *http.Request) context.Context { + return context.Background() +} diff --git a/vendor/google.golang.org/grpc/transport/go17.go b/vendor/google.golang.org/grpc/transport/go17.go new file mode 100644 index 0000000000..b7fa6bdb9c --- /dev/null +++ b/vendor/google.golang.org/grpc/transport/go17.go @@ -0,0 +1,52 @@ +// +build go1.7 + +/* + * + * Copyright 2016 gRPC 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 transport + +import ( + "context" + "net" + "net/http" + + "google.golang.org/grpc/codes" + + netctx "golang.org/x/net/context" +) + +// dialContext connects to the address on the named network. +func dialContext(ctx context.Context, network, address string) (net.Conn, error) { + return (&net.Dialer{}).DialContext(ctx, network, address) +} + +// ContextErr converts the error from context package into a StreamError. +func ContextErr(err error) StreamError { + switch err { + case context.DeadlineExceeded, netctx.DeadlineExceeded: + return streamErrorf(codes.DeadlineExceeded, "%v", err) + case context.Canceled, netctx.Canceled: + return streamErrorf(codes.Canceled, "%v", err) + } + return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) +} + +// contextFromRequest returns a context from the HTTP Request. +func contextFromRequest(r *http.Request) context.Context { + return r.Context() +} diff --git a/vendor/google.golang.org/grpc/transport/handler_server.go b/vendor/google.golang.org/grpc/transport/handler_server.go index f1f6caf89c..f71b748217 100644 --- a/vendor/google.golang.org/grpc/transport/handler_server.go +++ b/vendor/google.golang.org/grpc/transport/handler_server.go @@ -40,20 +40,24 @@ import ( "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" + "google.golang.org/grpc/stats" "google.golang.org/grpc/status" ) // NewServerHandlerTransport returns a ServerTransport handling gRPC // from inside an http.Handler. It requires that the http Server // supports HTTP/2. -func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request) (ServerTransport, error) { +func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request, stats stats.Handler) (ServerTransport, error) { if r.ProtoMajor != 2 { return nil, errors.New("gRPC requires HTTP/2") } if r.Method != "POST" { return nil, errors.New("invalid gRPC request method") } - if !validContentType(r.Header.Get("Content-Type")) { + contentType := r.Header.Get("Content-Type") + // TODO: do we assume contentType is lowercase? we did before + contentSubtype, validContentType := contentSubtype(contentType) + if !validContentType { return nil, errors.New("invalid gRPC request content-type") } if _, ok := w.(http.Flusher); !ok { @@ -64,10 +68,13 @@ func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request) (ServerTr } st := &serverHandlerTransport{ - rw: w, - req: r, - closedCh: make(chan struct{}), - writes: make(chan func()), + rw: w, + req: r, + closedCh: make(chan struct{}), + writes: make(chan func()), + contentType: contentType, + contentSubtype: contentSubtype, + stats: stats, } if v := r.Header.Get("grpc-timeout"); v != "" { @@ -79,19 +86,19 @@ func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request) (ServerTr st.timeout = to } - var metakv []string + metakv := []string{"content-type", contentType} if r.Host != "" { metakv = append(metakv, ":authority", r.Host) } for k, vv := range r.Header { k = strings.ToLower(k) - if isReservedHeader(k) && !isWhitelistedPseudoHeader(k) { + if isReservedHeader(k) && !isWhitelistedHeader(k) { continue } for _, v := range vv { v, err := decodeMetadataHeader(k, v) if err != nil { - return nil, streamErrorf(codes.InvalidArgument, "malformed binary metadata: %v", err) + return nil, streamErrorf(codes.Internal, "malformed binary metadata: %v", err) } metakv = append(metakv, k, v) } @@ -123,10 +130,17 @@ type serverHandlerTransport struct { // when WriteStatus is called. writes chan func() - mu sync.Mutex - // streamDone indicates whether WriteStatus has been called and writes channel - // has been closed. - streamDone bool + // block concurrent WriteStatus calls + // e.g. grpc/(*serverStream).SendMsg/RecvMsg + writeStatusMu sync.Mutex + + // we just mirror the request content-type + contentType string + // we store both contentType and contentSubtype so we don't keep recreating them + // TODO make sure this is consistent across handler_server and http2_server + contentSubtype string + + stats stats.Handler } func (ht *serverHandlerTransport) Close() error { @@ -177,13 +191,9 @@ func (ht *serverHandlerTransport) do(fn func()) error { } func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) error { - ht.mu.Lock() - if ht.streamDone { - ht.mu.Unlock() - return nil - } - ht.streamDone = true - ht.mu.Unlock() + ht.writeStatusMu.Lock() + defer ht.writeStatusMu.Unlock() + err := ht.do(func() { ht.writeCommonHeaders(s) @@ -222,7 +232,14 @@ func (ht *serverHandlerTransport) WriteStatus(s *Stream, st *status.Status) erro } } }) - close(ht.writes) + + if err == nil { // transport has not been closed + if ht.stats != nil { + ht.stats.HandleRPC(s.Context(), &stats.OutTrailer{}) + } + ht.Close() + close(ht.writes) + } return err } @@ -236,7 +253,7 @@ func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) { h := ht.rw.Header() h["Date"] = nil // suppress Date to make tests happy; TODO: restore - h.Set("Content-Type", "application/grpc") + h.Set("Content-Type", ht.contentType) // Predeclare trailers we'll set later in WriteStatus (after the body). // This is a SHOULD in the HTTP RFC, and the way you add (known) @@ -264,7 +281,7 @@ func (ht *serverHandlerTransport) Write(s *Stream, hdr []byte, data []byte, opts } func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error { - return ht.do(func() { + err := ht.do(func() { ht.writeCommonHeaders(s) h := ht.rw.Header() for k, vv := range md { @@ -280,17 +297,24 @@ func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error { ht.rw.WriteHeader(200) ht.rw.(http.Flusher).Flush() }) + + if err == nil { + if ht.stats != nil { + ht.stats.HandleRPC(s.Context(), &stats.OutHeader{}) + } + } + return err } func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), traceCtx func(context.Context, string) context.Context) { // With this transport type there will be exactly 1 stream: this HTTP request. - var ctx context.Context + ctx := contextFromRequest(ht.req) var cancel context.CancelFunc if ht.timeoutSet { - ctx, cancel = context.WithTimeout(context.Background(), ht.timeout) + ctx, cancel = context.WithTimeout(ctx, ht.timeout) } else { - ctx, cancel = context.WithCancel(context.Background()) + ctx, cancel = context.WithCancel(ctx) } // requestOver is closed when either the request's context is done @@ -314,13 +338,14 @@ func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), trace req := ht.req s := &Stream{ - id: 0, // irrelevant - requestRead: func(int) {}, - cancel: cancel, - buf: newRecvBuffer(), - st: ht, - method: req.URL.Path, - recvCompress: req.Header.Get("grpc-encoding"), + id: 0, // irrelevant + requestRead: func(int) {}, + cancel: cancel, + buf: newRecvBuffer(), + st: ht, + method: req.URL.Path, + recvCompress: req.Header.Get("grpc-encoding"), + contentSubtype: ht.contentSubtype, } pr := &peer.Peer{ Addr: ht.RemoteAddr(), @@ -329,10 +354,18 @@ func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream), trace pr.AuthInfo = credentials.TLSInfo{State: *req.TLS} } ctx = metadata.NewIncomingContext(ctx, ht.headerMD) - ctx = peer.NewContext(ctx, pr) - s.ctx = newContextWithStream(ctx, s) + s.ctx = peer.NewContext(ctx, pr) + if ht.stats != nil { + s.ctx = ht.stats.TagRPC(s.ctx, &stats.RPCTagInfo{FullMethodName: s.method}) + inHeader := &stats.InHeader{ + FullMethod: s.method, + RemoteAddr: ht.RemoteAddr(), + Compression: s.recvCompress, + } + ht.stats.HandleRPC(s.ctx, inHeader) + } s.trReader = &transportReader{ - reader: &recvBufferReader{ctx: s.ctx, recv: s.buf}, + reader: &recvBufferReader{ctx: s.ctx, ctxDone: s.ctx.Done(), recv: s.buf}, windowHandler: func(int) {}, } @@ -387,6 +420,10 @@ func (ht *serverHandlerTransport) runStream() { } } +func (ht *serverHandlerTransport) IncrMsgSent() {} + +func (ht *serverHandlerTransport) IncrMsgRecv() {} + func (ht *serverHandlerTransport) Drain() { panic("Drain() is not implemented") } diff --git a/vendor/google.golang.org/grpc/transport/handler_server_test.go b/vendor/google.golang.org/grpc/transport/handler_server_test.go deleted file mode 100644 index 06fe813ca9..0000000000 --- a/vendor/google.golang.org/grpc/transport/handler_server_test.go +++ /dev/null @@ -1,462 +0,0 @@ -/* - * - * Copyright 2016 gRPC 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 transport - -import ( - "errors" - "fmt" - "io" - "net/http" - "net/http/httptest" - "net/url" - "reflect" - "sync" - "testing" - "time" - - "github.com/golang/protobuf/proto" - dpb "github.com/golang/protobuf/ptypes/duration" - "golang.org/x/net/context" - epb "google.golang.org/genproto/googleapis/rpc/errdetails" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -func TestHandlerTransport_NewServerHandlerTransport(t *testing.T) { - type testCase struct { - name string - req *http.Request - wantErr string - modrw func(http.ResponseWriter) http.ResponseWriter - check func(*serverHandlerTransport, *testCase) error - } - tests := []testCase{ - { - name: "http/1.1", - req: &http.Request{ - ProtoMajor: 1, - ProtoMinor: 1, - }, - wantErr: "gRPC requires HTTP/2", - }, - { - name: "bad method", - req: &http.Request{ - ProtoMajor: 2, - Method: "GET", - Header: http.Header{}, - RequestURI: "/", - }, - wantErr: "invalid gRPC request method", - }, - { - name: "bad content type", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/foo"}, - }, - RequestURI: "/service/foo.bar", - }, - wantErr: "invalid gRPC request content-type", - }, - { - name: "not flusher", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/grpc"}, - }, - RequestURI: "/service/foo.bar", - }, - modrw: func(w http.ResponseWriter) http.ResponseWriter { - // Return w without its Flush method - type onlyCloseNotifier interface { - http.ResponseWriter - http.CloseNotifier - } - return struct{ onlyCloseNotifier }{w.(onlyCloseNotifier)} - }, - wantErr: "gRPC requires a ResponseWriter supporting http.Flusher", - }, - { - name: "not closenotifier", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/grpc"}, - }, - RequestURI: "/service/foo.bar", - }, - modrw: func(w http.ResponseWriter) http.ResponseWriter { - // Return w without its CloseNotify method - type onlyFlusher interface { - http.ResponseWriter - http.Flusher - } - return struct{ onlyFlusher }{w.(onlyFlusher)} - }, - wantErr: "gRPC requires a ResponseWriter supporting http.CloseNotifier", - }, - { - name: "valid", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/grpc"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - }, - check: func(t *serverHandlerTransport, tt *testCase) error { - if t.req != tt.req { - return fmt.Errorf("t.req = %p; want %p", t.req, tt.req) - } - if t.rw == nil { - return errors.New("t.rw = nil; want non-nil") - } - return nil - }, - }, - { - name: "with timeout", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": []string{"application/grpc"}, - "Grpc-Timeout": {"200m"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - }, - check: func(t *serverHandlerTransport, tt *testCase) error { - if !t.timeoutSet { - return errors.New("timeout not set") - } - if want := 200 * time.Millisecond; t.timeout != want { - return fmt.Errorf("timeout = %v; want %v", t.timeout, want) - } - return nil - }, - }, - { - name: "with bad timeout", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": []string{"application/grpc"}, - "Grpc-Timeout": {"tomorrow"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - }, - wantErr: `stream error: code = Internal desc = "malformed time-out: transport: timeout unit is not recognized: \"tomorrow\""`, - }, - { - name: "with metadata", - req: &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": []string{"application/grpc"}, - "meta-foo": {"foo-val"}, - "meta-bar": {"bar-val1", "bar-val2"}, - "user-agent": {"x/y a/b"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - }, - check: func(ht *serverHandlerTransport, tt *testCase) error { - want := metadata.MD{ - "meta-bar": {"bar-val1", "bar-val2"}, - "user-agent": {"x/y a/b"}, - "meta-foo": {"foo-val"}, - } - - if !reflect.DeepEqual(ht.headerMD, want) { - return fmt.Errorf("metdata = %#v; want %#v", ht.headerMD, want) - } - return nil - }, - }, - } - - for _, tt := range tests { - rw := newTestHandlerResponseWriter() - if tt.modrw != nil { - rw = tt.modrw(rw) - } - got, gotErr := NewServerHandlerTransport(rw, tt.req) - if (gotErr != nil) != (tt.wantErr != "") || (gotErr != nil && gotErr.Error() != tt.wantErr) { - t.Errorf("%s: error = %v; want %q", tt.name, gotErr, tt.wantErr) - continue - } - if gotErr != nil { - continue - } - if tt.check != nil { - if err := tt.check(got.(*serverHandlerTransport), &tt); err != nil { - t.Errorf("%s: %v", tt.name, err) - } - } - } -} - -type testHandlerResponseWriter struct { - *httptest.ResponseRecorder - closeNotify chan bool -} - -func (w testHandlerResponseWriter) CloseNotify() <-chan bool { return w.closeNotify } -func (w testHandlerResponseWriter) Flush() {} - -func newTestHandlerResponseWriter() http.ResponseWriter { - return testHandlerResponseWriter{ - ResponseRecorder: httptest.NewRecorder(), - closeNotify: make(chan bool, 1), - } -} - -type handleStreamTest struct { - t *testing.T - bodyw *io.PipeWriter - req *http.Request - rw testHandlerResponseWriter - ht *serverHandlerTransport -} - -func newHandleStreamTest(t *testing.T) *handleStreamTest { - bodyr, bodyw := io.Pipe() - req := &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/grpc"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - Body: bodyr, - } - rw := newTestHandlerResponseWriter().(testHandlerResponseWriter) - ht, err := NewServerHandlerTransport(rw, req) - if err != nil { - t.Fatal(err) - } - return &handleStreamTest{ - t: t, - bodyw: bodyw, - ht: ht.(*serverHandlerTransport), - rw: rw, - } -} - -func TestHandlerTransport_HandleStreams(t *testing.T) { - st := newHandleStreamTest(t) - handleStream := func(s *Stream) { - if want := "/service/foo.bar"; s.method != want { - t.Errorf("stream method = %q; want %q", s.method, want) - } - st.bodyw.Close() // no body - st.ht.WriteStatus(s, status.New(codes.OK, "")) - } - st.ht.HandleStreams( - func(s *Stream) { go handleStream(s) }, - func(ctx context.Context, method string) context.Context { return ctx }, - ) - wantHeader := http.Header{ - "Date": nil, - "Content-Type": {"application/grpc"}, - "Trailer": {"Grpc-Status", "Grpc-Message", "Grpc-Status-Details-Bin"}, - "Grpc-Status": {"0"}, - } - if !reflect.DeepEqual(st.rw.HeaderMap, wantHeader) { - t.Errorf("Header+Trailer Map: %#v; want %#v", st.rw.HeaderMap, wantHeader) - } -} - -// Tests that codes.Unimplemented will close the body, per comment in handler_server.go. -func TestHandlerTransport_HandleStreams_Unimplemented(t *testing.T) { - handleStreamCloseBodyTest(t, codes.Unimplemented, "thingy is unimplemented") -} - -// Tests that codes.InvalidArgument will close the body, per comment in handler_server.go. -func TestHandlerTransport_HandleStreams_InvalidArgument(t *testing.T) { - handleStreamCloseBodyTest(t, codes.InvalidArgument, "bad arg") -} - -func handleStreamCloseBodyTest(t *testing.T, statusCode codes.Code, msg string) { - st := newHandleStreamTest(t) - - handleStream := func(s *Stream) { - st.ht.WriteStatus(s, status.New(statusCode, msg)) - } - st.ht.HandleStreams( - func(s *Stream) { go handleStream(s) }, - func(ctx context.Context, method string) context.Context { return ctx }, - ) - wantHeader := http.Header{ - "Date": nil, - "Content-Type": {"application/grpc"}, - "Trailer": {"Grpc-Status", "Grpc-Message", "Grpc-Status-Details-Bin"}, - "Grpc-Status": {fmt.Sprint(uint32(statusCode))}, - "Grpc-Message": {encodeGrpcMessage(msg)}, - } - - if !reflect.DeepEqual(st.rw.HeaderMap, wantHeader) { - t.Errorf("Header+Trailer mismatch.\n got: %#v\nwant: %#v", st.rw.HeaderMap, wantHeader) - } -} - -func TestHandlerTransport_HandleStreams_Timeout(t *testing.T) { - bodyr, bodyw := io.Pipe() - req := &http.Request{ - ProtoMajor: 2, - Method: "POST", - Header: http.Header{ - "Content-Type": {"application/grpc"}, - "Grpc-Timeout": {"200m"}, - }, - URL: &url.URL{ - Path: "/service/foo.bar", - }, - RequestURI: "/service/foo.bar", - Body: bodyr, - } - rw := newTestHandlerResponseWriter().(testHandlerResponseWriter) - ht, err := NewServerHandlerTransport(rw, req) - if err != nil { - t.Fatal(err) - } - runStream := func(s *Stream) { - defer bodyw.Close() - select { - case <-s.ctx.Done(): - case <-time.After(5 * time.Second): - t.Errorf("timeout waiting for ctx.Done") - return - } - err := s.ctx.Err() - if err != context.DeadlineExceeded { - t.Errorf("ctx.Err = %v; want %v", err, context.DeadlineExceeded) - return - } - ht.WriteStatus(s, status.New(codes.DeadlineExceeded, "too slow")) - } - ht.HandleStreams( - func(s *Stream) { go runStream(s) }, - func(ctx context.Context, method string) context.Context { return ctx }, - ) - wantHeader := http.Header{ - "Date": nil, - "Content-Type": {"application/grpc"}, - "Trailer": {"Grpc-Status", "Grpc-Message", "Grpc-Status-Details-Bin"}, - "Grpc-Status": {"4"}, - "Grpc-Message": {encodeGrpcMessage("too slow")}, - } - if !reflect.DeepEqual(rw.HeaderMap, wantHeader) { - t.Errorf("Header+Trailer Map mismatch.\n got: %#v\nwant: %#v", rw.HeaderMap, wantHeader) - } -} - -func TestHandlerTransport_HandleStreams_MultiWriteStatus(t *testing.T) { - st := newHandleStreamTest(t) - handleStream := func(s *Stream) { - if want := "/service/foo.bar"; s.method != want { - t.Errorf("stream method = %q; want %q", s.method, want) - } - st.bodyw.Close() // no body - - var wg sync.WaitGroup - wg.Add(5) - for i := 0; i < 5; i++ { - go func() { - defer wg.Done() - st.ht.WriteStatus(s, status.New(codes.OK, "")) - }() - } - wg.Wait() - } - st.ht.HandleStreams( - func(s *Stream) { go handleStream(s) }, - func(ctx context.Context, method string) context.Context { return ctx }, - ) -} - -func TestHandlerTransport_HandleStreams_ErrDetails(t *testing.T) { - errDetails := []proto.Message{ - &epb.RetryInfo{ - RetryDelay: &dpb.Duration{Seconds: 60}, - }, - &epb.ResourceInfo{ - ResourceType: "foo bar", - ResourceName: "service.foo.bar", - Owner: "User", - }, - } - - statusCode := codes.ResourceExhausted - msg := "you are being throttled" - st, err := status.New(statusCode, msg).WithDetails(errDetails...) - if err != nil { - t.Fatal(err) - } - - stBytes, err := proto.Marshal(st.Proto()) - if err != nil { - t.Fatal(err) - } - - hst := newHandleStreamTest(t) - handleStream := func(s *Stream) { - hst.ht.WriteStatus(s, st) - } - hst.ht.HandleStreams( - func(s *Stream) { go handleStream(s) }, - func(ctx context.Context, method string) context.Context { return ctx }, - ) - wantHeader := http.Header{ - "Date": nil, - "Content-Type": {"application/grpc"}, - "Trailer": {"Grpc-Status", "Grpc-Message", "Grpc-Status-Details-Bin"}, - "Grpc-Status": {fmt.Sprint(uint32(statusCode))}, - "Grpc-Message": {encodeGrpcMessage(msg)}, - "Grpc-Status-Details-Bin": {encodeBinHeader(stBytes)}, - } - - if !reflect.DeepEqual(hst.rw.HeaderMap, wantHeader) { - t.Errorf("Header+Trailer mismatch.\n got: %#v\nwant: %#v", hst.rw.HeaderMap, wantHeader) - } -} diff --git a/vendor/google.golang.org/grpc/transport/http2_client.go b/vendor/google.golang.org/grpc/transport/http2_client.go index 1abb62e6df..1fdabd954e 100644 --- a/vendor/google.golang.org/grpc/transport/http2_client.go +++ b/vendor/google.golang.org/grpc/transport/http2_client.go @@ -19,7 +19,6 @@ package transport import ( - "bytes" "io" "math" "net" @@ -31,6 +30,8 @@ import ( "golang.org/x/net/context" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" + + "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/keepalive" @@ -44,15 +45,17 @@ import ( type http2Client struct { ctx context.Context cancel context.CancelFunc - target string // server name/addr + ctxDone <-chan struct{} // Cache the ctx.Done() chan. userAgent string md interface{} conn net.Conn // underlying communication channel + loopy *loopyWriter remoteAddr net.Addr localAddr net.Addr authInfo credentials.AuthInfo // auth info about the connection - nextID uint32 // the next stream ID to be used + readerDone chan struct{} // sync point to enable testing. + writerDone chan struct{} // sync point to enable testing. // goAway is closed to notify the upper layer (i.e., addrConn.transportMonitor) // that the server sent GoAway on this transport. goAway chan struct{} @@ -60,18 +63,10 @@ type http2Client struct { awakenKeepalive chan struct{} framer *framer - hBuf *bytes.Buffer // the buffer for HPACK encoding - hEnc *hpack.Encoder // HPACK encoder - // controlBuf delivers all the control related tasks (e.g., window // updates, reset streams, and various settings) to the controller. controlBuf *controlBuffer - fc *inFlow - // sendQuotaPool provides flow control to outbound message. - sendQuotaPool *quotaPool - // streamsQuota limits the max number of concurrent streams. - streamsQuota *quotaPool - + fc *trInFlow // The scheme used: https if TLS is on, http otherwise. scheme string @@ -88,43 +83,52 @@ type http2Client struct { initialWindowSize int32 - bdpEst *bdpEstimator - outQuotaVersion uint32 + bdpEst *bdpEstimator + // onSuccess is a callback that client transport calls upon + // receiving server preface to signal that a succefull HTTP2 + // connection was established. + onSuccess func() - mu sync.Mutex // guard the following variables - state transportState // the state of underlying connection + maxConcurrentStreams uint32 + streamQuota int64 + streamsQuotaAvailable chan struct{} + waitingStreams uint32 + nextID uint32 + + mu sync.Mutex // guard the following variables + state transportState activeStreams map[uint32]*Stream - // The max number of concurrent streams - maxStreams int - // the per-stream outbound flow control window size set by the peer. - streamSendQuota uint32 // prevGoAway ID records the Last-Stream-ID in the previous GOAway frame. prevGoAwayID uint32 // goAwayReason records the http2.ErrCode and debug data received with the // GoAway frame. goAwayReason GoAwayReason + + // Fields below are for channelz metric collection. + channelzID int64 // channelz unique identification number + czmu sync.RWMutex + kpCount int64 + // The number of streams that have started, including already finished ones. + streamsStarted int64 + // The number of streams that have ended successfully by receiving EoS bit set + // frame from server. + streamsSucceeded int64 + streamsFailed int64 + lastStreamCreated time.Time + msgSent int64 + msgRecv int64 + lastMsgSent time.Time + lastMsgRecv time.Time } func dial(ctx context.Context, fn func(context.Context, string) (net.Conn, error), addr string) (net.Conn, error) { if fn != nil { return fn(ctx, addr) } - return (&net.Dialer{}).DialContext(ctx, "tcp", addr) + return dialContext(ctx, "tcp", addr) } func isTemporary(err error) bool { - switch err { - case io.EOF: - // Connection closures may be resolved upon retry, and are thus - // treated as temporary. - return true - case context.DeadlineExceeded: - // In Go 1.7, context.DeadlineExceeded implements Timeout(), and this - // special case is not needed. Until then, we need to keep this - // clause. - return true - } - switch err := err.(type) { case interface { Temporary() bool @@ -137,18 +141,16 @@ func isTemporary(err error) bool { // temporary. return err.Timeout() } - return false + return true } // newHTTP2Client constructs a connected ClientTransport to addr based on HTTP2 // and starts to receive messages on it. Non-nil error returns if construction // fails. -func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, timeout time.Duration) (_ ClientTransport, err error) { +func newHTTP2Client(connectCtx, ctx context.Context, addr TargetInfo, opts ConnectOptions, onSuccess func()) (_ ClientTransport, err error) { scheme := "http" ctx, cancel := context.WithCancel(ctx) - connectCtx, connectCancel := context.WithTimeout(ctx, timeout) defer func() { - connectCancel() if err != nil { cancel() } @@ -173,12 +175,9 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t ) if creds := opts.TransportCredentials; creds != nil { scheme = "https" - conn, authInfo, err = creds.ClientHandshake(connectCtx, addr.Addr, conn) + conn, authInfo, err = creds.ClientHandshake(connectCtx, addr.Authority, conn) if err != nil { - // Credentials handshake errors are typically considered permanent - // to avoid retrying on e.g. bad certificates. - temp := isTemporary(err) - return nil, connectionErrorf(temp, err, "transport: authentication handshake failed: %v", err) + return nil, connectionErrorf(isTemporary(err), err, "transport: authentication handshake failed: %v", err) } isSecure = true } @@ -196,7 +195,6 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t icwz = opts.InitialConnWindowSize dynamicWindow = false } - var buf bytes.Buffer writeBufSize := defaultWriteBufSize if opts.WriteBufferSize > 0 { writeBufSize = opts.WriteBufferSize @@ -206,37 +204,35 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t readBufSize = opts.ReadBufferSize } t := &http2Client{ - ctx: ctx, - cancel: cancel, - target: addr.Addr, - userAgent: opts.UserAgent, - md: addr.Metadata, - conn: conn, - remoteAddr: conn.RemoteAddr(), - localAddr: conn.LocalAddr(), - authInfo: authInfo, - // The client initiated stream id is odd starting from 1. - nextID: 1, - goAway: make(chan struct{}), - awakenKeepalive: make(chan struct{}, 1), - hBuf: &buf, - hEnc: hpack.NewEncoder(&buf), - framer: newFramer(conn, writeBufSize, readBufSize), - controlBuf: newControlBuffer(), - fc: &inFlow{limit: uint32(icwz)}, - sendQuotaPool: newQuotaPool(defaultWindowSize), - scheme: scheme, - state: reachable, - activeStreams: make(map[uint32]*Stream), - isSecure: isSecure, - creds: opts.PerRPCCredentials, - maxStreams: defaultMaxStreamsClient, - streamsQuota: newQuotaPool(defaultMaxStreamsClient), - streamSendQuota: defaultWindowSize, - kp: kp, - statsHandler: opts.StatsHandler, - initialWindowSize: initialWindowSize, - } + ctx: ctx, + ctxDone: ctx.Done(), // Cache Done chan. + cancel: cancel, + userAgent: opts.UserAgent, + md: addr.Metadata, + conn: conn, + remoteAddr: conn.RemoteAddr(), + localAddr: conn.LocalAddr(), + authInfo: authInfo, + readerDone: make(chan struct{}), + writerDone: make(chan struct{}), + goAway: make(chan struct{}), + awakenKeepalive: make(chan struct{}, 1), + framer: newFramer(conn, writeBufSize, readBufSize), + fc: &trInFlow{limit: uint32(icwz)}, + scheme: scheme, + activeStreams: make(map[uint32]*Stream), + isSecure: isSecure, + creds: opts.PerRPCCredentials, + kp: kp, + statsHandler: opts.StatsHandler, + initialWindowSize: initialWindowSize, + onSuccess: onSuccess, + nextID: 1, + maxConcurrentStreams: defaultMaxStreamsClient, + streamQuota: defaultMaxStreamsClient, + streamsQuotaAvailable: make(chan struct{}, 1), + } + t.controlBuf = newControlBuffer(t.ctxDone) if opts.InitialWindowSize >= defaultWindowSize { t.initialWindowSize = opts.InitialWindowSize dynamicWindow = false @@ -260,6 +256,9 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t } t.statsHandler.HandleConn(t.ctx, connBegin) } + if channelz.IsOn() { + t.channelzID = channelz.RegisterNormalSocket(t, opts.ChannelzParentID, "") + } // Start the reader goroutine for incoming message. Each transport has // a dedicated goroutine which reads HTTP2 frame from network. Then it // dispatches the frame to the corresponding stream entity. @@ -295,8 +294,10 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t } t.framer.writer.Flush() go func() { - loopyWriter(t.ctx, t.controlBuf, t.itemHandler) - t.Close() + t.loopy = newLoopyWriter(clientSide, t.framer, t.controlBuf, t.bdpEst) + t.loopy.run() + t.conn.Close() + close(t.writerDone) }() if t.kp.Time != infinity { go t.keepalive() @@ -307,18 +308,14 @@ func newHTTP2Client(ctx context.Context, addr TargetInfo, opts ConnectOptions, t func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream { // TODO(zhaoq): Handle uint32 overflow of Stream.id. s := &Stream{ - id: t.nextID, done: make(chan struct{}), - goAway: make(chan struct{}), method: callHdr.Method, sendCompress: callHdr.SendCompress, buf: newRecvBuffer(), - fc: &inFlow{limit: uint32(t.initialWindowSize)}, - sendQuotaPool: newQuotaPool(int(t.streamSendQuota)), - localSendQuota: newQuotaPool(defaultLocalSendQuota), headerChan: make(chan struct{}), + contentSubtype: callHdr.ContentSubtype, } - t.nextID += 2 + s.wq = newWriteQuota(defaultWriteQuota, s.done) s.requestRead = func(n int) { t.adjustWindow(s, uint32(n)) } @@ -328,21 +325,18 @@ func (t *http2Client) newStream(ctx context.Context, callHdr *CallHdr) *Stream { s.ctx = ctx s.trReader = &transportReader{ reader: &recvBufferReader{ - ctx: s.ctx, - goAway: s.goAway, - recv: s.buf, + ctx: s.ctx, + ctxDone: s.ctx.Done(), + recv: s.buf, }, windowHandler: func(n int) { t.updateWindow(s, uint32(n)) }, } - return s } -// NewStream creates a stream and registers it into the transport as "active" -// streams. -func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) { +func (t *http2Client) getPeer() *peer.Peer { pr := &peer.Peer{ Addr: t.remoteAddr, } @@ -350,74 +344,20 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea if t.authInfo != nil { pr.AuthInfo = t.authInfo } - ctx = peer.NewContext(ctx, pr) - var ( - authData = make(map[string]string) - audience string - ) - // Create an audience string only if needed. - if len(t.creds) > 0 || callHdr.Creds != nil { - // Construct URI required to get auth request metadata. - // Omit port if it is the default one. - host := strings.TrimSuffix(callHdr.Host, ":443") - pos := strings.LastIndex(callHdr.Method, "/") - if pos == -1 { - pos = len(callHdr.Method) - } - audience = "https://" + host + callHdr.Method[:pos] - } - for _, c := range t.creds { - data, err := c.GetRequestMetadata(ctx, audience) - if err != nil { - return nil, streamErrorf(codes.Internal, "transport: %v", err) - } - for k, v := range data { - // Capital header names are illegal in HTTP/2. - k = strings.ToLower(k) - authData[k] = v - } - } - callAuthData := map[string]string{} - // Check if credentials.PerRPCCredentials were provided via call options. - // Note: if these credentials are provided both via dial options and call - // options, then both sets of credentials will be applied. - if callCreds := callHdr.Creds; callCreds != nil { - if !t.isSecure && callCreds.RequireTransportSecurity() { - return nil, streamErrorf(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection") - } - data, err := callCreds.GetRequestMetadata(ctx, audience) - if err != nil { - return nil, streamErrorf(codes.Internal, "transport: %v", err) - } - for k, v := range data { - // Capital header names are illegal in HTTP/2 - k = strings.ToLower(k) - callAuthData[k] = v - } - } - t.mu.Lock() - if t.activeStreams == nil { - t.mu.Unlock() - return nil, ErrConnClosing - } - if t.state == draining { - t.mu.Unlock() - return nil, ErrStreamDrain - } - if t.state != reachable { - t.mu.Unlock() - return nil, ErrConnClosing - } - t.mu.Unlock() - sq, err := wait(ctx, t.ctx, nil, nil, t.streamsQuota.acquire()) + return pr +} + +func (t *http2Client) createHeaderFields(ctx context.Context, callHdr *CallHdr) ([]hpack.HeaderField, error) { + aud := t.createAudience(callHdr) + authData, err := t.getTrAuthData(ctx, aud) if err != nil { return nil, err } - // Returns the quota balance back. - if sq > 1 { - t.streamsQuota.add(sq - 1) + callAuthData, err := t.getCallAuthData(ctx, aud, callHdr) + if err != nil { + return nil, err } - // TODO(mmukhi): Benchmark if the perfomance gets better if count the metadata and other header fields + // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields // first and create a slice of that exact size. // Make the slice of certain predictable size to reduce allocations made by append. hfLen := 7 // :method, :scheme, :path, :authority, content-type, user-agent, te @@ -427,7 +367,7 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea headerFields = append(headerFields, hpack.HeaderField{Name: ":scheme", Value: t.scheme}) headerFields = append(headerFields, hpack.HeaderField{Name: ":path", Value: callHdr.Method}) headerFields = append(headerFields, hpack.HeaderField{Name: ":authority", Value: callHdr.Host}) - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: "application/grpc"}) + headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(callHdr.ContentSubtype)}) headerFields = append(headerFields, hpack.HeaderField{Name: "user-agent", Value: t.userAgent}) headerFields = append(headerFields, hpack.HeaderField{Name: "te", Value: "trailers"}) @@ -452,7 +392,22 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea if b := stats.OutgoingTrace(ctx); b != nil { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-trace-bin", Value: encodeBinHeader(b)}) } - if md, ok := metadata.FromOutgoingContext(ctx); ok { + + if md, added, ok := metadata.FromOutgoingContextRaw(ctx); ok { + var k string + for _, vv := range added { + for i, v := range vv { + if i%2 == 0 { + k = v + continue + } + // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. + if isReservedHeader(k) { + continue + } + headerFields = append(headerFields, hpack.HeaderField{Name: strings.ToLower(k), Value: encodeMetadataHeader(k, v)}) + } + } for k, vv := range md { // HTTP doesn't allow you to set pseudoheaders after non pseudoheaders were set. if isReservedHeader(k) { @@ -473,42 +428,178 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea } } } - t.mu.Lock() - if t.state == draining { - t.mu.Unlock() - t.streamsQuota.add(1) - return nil, ErrStreamDrain + return headerFields, nil +} + +func (t *http2Client) createAudience(callHdr *CallHdr) string { + // Create an audience string only if needed. + if len(t.creds) == 0 && callHdr.Creds == nil { + return "" } - if t.state != reachable { - t.mu.Unlock() - return nil, ErrConnClosing + // Construct URI required to get auth request metadata. + // Omit port if it is the default one. + host := strings.TrimSuffix(callHdr.Host, ":443") + pos := strings.LastIndex(callHdr.Method, "/") + if pos == -1 { + pos = len(callHdr.Method) + } + return "https://" + host + callHdr.Method[:pos] +} + +func (t *http2Client) getTrAuthData(ctx context.Context, audience string) (map[string]string, error) { + authData := map[string]string{} + for _, c := range t.creds { + data, err := c.GetRequestMetadata(ctx, audience) + if err != nil { + if _, ok := status.FromError(err); ok { + return nil, err + } + + return nil, streamErrorf(codes.Unauthenticated, "transport: %v", err) + } + for k, v := range data { + // Capital header names are illegal in HTTP/2. + k = strings.ToLower(k) + authData[k] = v + } + } + return authData, nil +} + +func (t *http2Client) getCallAuthData(ctx context.Context, audience string, callHdr *CallHdr) (map[string]string, error) { + callAuthData := map[string]string{} + // Check if credentials.PerRPCCredentials were provided via call options. + // Note: if these credentials are provided both via dial options and call + // options, then both sets of credentials will be applied. + if callCreds := callHdr.Creds; callCreds != nil { + if !t.isSecure && callCreds.RequireTransportSecurity() { + return nil, streamErrorf(codes.Unauthenticated, "transport: cannot send secure credentials on an insecure connection") + } + data, err := callCreds.GetRequestMetadata(ctx, audience) + if err != nil { + return nil, streamErrorf(codes.Internal, "transport: %v", err) + } + for k, v := range data { + // Capital header names are illegal in HTTP/2 + k = strings.ToLower(k) + callAuthData[k] = v + } + } + return callAuthData, nil +} + +// NewStream creates a stream and registers it into the transport as "active" +// streams. +func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Stream, err error) { + ctx = peer.NewContext(ctx, t.getPeer()) + headerFields, err := t.createHeaderFields(ctx, callHdr) + if err != nil { + return nil, err } s := t.newStream(ctx, callHdr) - t.activeStreams[s.id] = s - // If the number of active streams change from 0 to 1, then check if keepalive - // has gone dormant. If so, wake it up. - if len(t.activeStreams) == 1 { - select { - case t.awakenKeepalive <- struct{}{}: - t.controlBuf.put(&ping{data: [8]byte{}}) - // Fill the awakenKeepalive channel again as this channel must be - // kept non-writable except at the point that the keepalive() - // goroutine is waiting either to be awaken or shutdown. - t.awakenKeepalive <- struct{}{} - default: + cleanup := func(err error) { + if s.swapState(streamDone) == streamDone { + // If it was already done, return. + return + } + // The stream was unprocessed by the server. + atomic.StoreUint32(&s.unprocessed, 1) + s.write(recvMsg{err: err}) + close(s.done) + // If headerChan isn't closed, then close it. + if atomic.SwapUint32(&s.headerDone, 1) == 0 { + close(s.headerChan) } + } - t.controlBuf.put(&headerFrame{ - streamID: s.id, + hdr := &headerFrame{ hf: headerFields, endStream: false, - }) - t.mu.Unlock() - - s.mu.Lock() - s.bytesSent = true - s.mu.Unlock() - + initStream: func(id uint32) (bool, error) { + t.mu.Lock() + if state := t.state; state != reachable { + t.mu.Unlock() + // Do a quick cleanup. + err := error(errStreamDrain) + if state == closing { + err = ErrConnClosing + } + cleanup(err) + return false, err + } + t.activeStreams[id] = s + if channelz.IsOn() { + t.czmu.Lock() + t.streamsStarted++ + t.lastStreamCreated = time.Now() + t.czmu.Unlock() + } + var sendPing bool + // If the number of active streams change from 0 to 1, then check if keepalive + // has gone dormant. If so, wake it up. + if len(t.activeStreams) == 1 { + select { + case t.awakenKeepalive <- struct{}{}: + sendPing = true + // Fill the awakenKeepalive channel again as this channel must be + // kept non-writable except at the point that the keepalive() + // goroutine is waiting either to be awaken or shutdown. + t.awakenKeepalive <- struct{}{} + default: + } + } + t.mu.Unlock() + return sendPing, nil + }, + onOrphaned: cleanup, + wq: s.wq, + } + firstTry := true + var ch chan struct{} + checkForStreamQuota := func(it interface{}) bool { + if t.streamQuota <= 0 { // Can go negative if server decreases it. + if firstTry { + t.waitingStreams++ + } + ch = t.streamsQuotaAvailable + return false + } + if !firstTry { + t.waitingStreams-- + } + t.streamQuota-- + h := it.(*headerFrame) + h.streamID = t.nextID + t.nextID += 2 + s.id = h.streamID + s.fc = &inFlow{limit: uint32(t.initialWindowSize)} + if t.streamQuota > 0 && t.waitingStreams > 0 { + select { + case t.streamsQuotaAvailable <- struct{}{}: + default: + } + } + return true + } + for { + success, err := t.controlBuf.executeAndPut(checkForStreamQuota, hdr) + if err != nil { + return nil, err + } + if success { + break + } + firstTry = false + select { + case <-ch: + case <-s.ctx.Done(): + return nil, ContextErr(s.ctx.Err()) + case <-t.goAway: + return nil, errStreamDrain + case <-t.ctx.Done(): + return nil, ErrConnClosing + } + } if t.statsHandler != nil { outHeader := &stats.OutHeader{ Client: true, @@ -525,86 +616,97 @@ func (t *http2Client) NewStream(ctx context.Context, callHdr *CallHdr) (_ *Strea // CloseStream clears the footprint of a stream when the stream is not needed any more. // This must not be executed in reader's goroutine. func (t *http2Client) CloseStream(s *Stream, err error) { - t.mu.Lock() - if t.activeStreams == nil { - t.mu.Unlock() - return - } + var ( + rst bool + rstCode http2.ErrCode + ) if err != nil { - // notify in-flight streams, before the deletion - s.write(recvMsg{err: err}) + rst = true + rstCode = http2.ErrCodeCancel } - delete(t.activeStreams, s.id) - if t.state == draining && len(t.activeStreams) == 0 { - // The transport is draining and s is the last live stream on t. - t.mu.Unlock() - t.Close() + t.closeStream(s, err, rst, rstCode, nil, nil, false) +} + +func (t *http2Client) closeStream(s *Stream, err error, rst bool, rstCode http2.ErrCode, st *status.Status, mdata map[string][]string, eosReceived bool) { + // Set stream status to done. + if s.swapState(streamDone) == streamDone { + // If it was already done, return. return } - t.mu.Unlock() - // rstStream is true in case the stream is being closed at the client-side - // and the server needs to be intimated about it by sending a RST_STREAM - // frame. - // To make sure this frame is written to the wire before the headers of the - // next stream waiting for streamsQuota, we add to streamsQuota pool only - // after having acquired the writableChan to send RST_STREAM out (look at - // the controller() routine). - var rstStream bool - var rstError http2.ErrCode - defer func() { - // In case, the client doesn't have to send RST_STREAM to server - // we can safely add back to streamsQuota pool now. - if !rstStream { - t.streamsQuota.add(1) - return - } - t.controlBuf.put(&resetStream{s.id, rstError}) - }() - s.mu.Lock() - rstStream = s.rstStream - rstError = s.rstError - if s.state == streamDone { - s.mu.Unlock() - return + // status and trailers can be updated here without any synchronization because the stream goroutine will + // only read it after it sees an io.EOF error from read or write and we'll write those errors + // only after updating this. + s.status = st + if len(mdata) > 0 { + s.trailer = mdata + } + if err != nil { + // This will unblock reads eventually. + s.write(recvMsg{err: err}) } - if !s.headerDone { + // This will unblock write. + close(s.done) + // If headerChan isn't closed, then close it. + if atomic.SwapUint32(&s.headerDone, 1) == 0 { close(s.headerChan) - s.headerDone = true } - s.state = streamDone - s.mu.Unlock() - if _, ok := err.(StreamError); ok { - rstStream = true - rstError = http2.ErrCodeCancel + cleanup := &cleanupStream{ + streamID: s.id, + onWrite: func() { + t.mu.Lock() + if t.activeStreams != nil { + delete(t.activeStreams, s.id) + } + t.mu.Unlock() + if channelz.IsOn() { + t.czmu.Lock() + if eosReceived { + t.streamsSucceeded++ + } else { + t.streamsFailed++ + } + t.czmu.Unlock() + } + }, + rst: rst, + rstCode: rstCode, } + addBackStreamQuota := func(interface{}) bool { + t.streamQuota++ + if t.streamQuota > 0 && t.waitingStreams > 0 { + select { + case t.streamsQuotaAvailable <- struct{}{}: + default: + } + } + return true + } + t.controlBuf.executeAndPut(addBackStreamQuota, cleanup) } // Close kicks off the shutdown process of the transport. This should be called // only once on a transport. Once it is called, the transport should not be // accessed any more. -func (t *http2Client) Close() (err error) { +func (t *http2Client) Close() error { t.mu.Lock() + // Make sure we only Close once. if t.state == closing { t.mu.Unlock() - return + return nil } t.state = closing - t.mu.Unlock() - t.cancel() - err = t.conn.Close() - t.mu.Lock() streams := t.activeStreams t.activeStreams = nil t.mu.Unlock() + t.controlBuf.finish() + t.cancel() + err := t.conn.Close() + if channelz.IsOn() { + channelz.RemoveEntry(t.channelzID) + } // Notify all active streams. for _, s := range streams { - s.mu.Lock() - if !s.headerDone { - close(s.headerChan) - s.headerDone = true - } - s.mu.Unlock() - s.write(recvMsg{err: ErrConnClosing}) + t.closeStream(s, ErrConnClosing, false, http2.ErrCodeNo, nil, nil, false) } if t.statsHandler != nil { connEnd := &stats.ConnEnd{ @@ -622,8 +724,8 @@ func (t *http2Client) Close() (err error) { // closing. func (t *http2Client) GracefulClose() error { t.mu.Lock() - switch t.state { - case closing, draining: + // Make sure we move to draining only from active. + if t.state == draining || t.state == closing { t.mu.Unlock() return nil } @@ -639,102 +741,34 @@ func (t *http2Client) GracefulClose() error { // Write formats the data into HTTP2 data frame(s) and sends it out. The caller // should proceed only if Write returns nil. func (t *http2Client) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { - select { - case <-s.ctx.Done(): - return ContextErr(s.ctx.Err()) - case <-t.ctx.Done(): - return ErrConnClosing - default: - } - - if hdr == nil && data == nil && opts.Last { - // stream.CloseSend uses this to send an empty frame with endStream=True - t.controlBuf.put(&dataFrame{streamID: s.id, endStream: true, f: func() {}}) - return nil - } - // Add data to header frame so that we can equally distribute data across frames. - emptyLen := http2MaxFrameLen - len(hdr) - if emptyLen > len(data) { - emptyLen = len(data) - } - hdr = append(hdr, data[:emptyLen]...) - data = data[emptyLen:] - for idx, r := range [][]byte{hdr, data} { - for len(r) > 0 { - size := http2MaxFrameLen - // Wait until the stream has some quota to send the data. - quotaChan, quotaVer := s.sendQuotaPool.acquireWithVersion() - sq, err := wait(s.ctx, t.ctx, s.done, s.goAway, quotaChan) - if err != nil { - return err - } - // Wait until the transport has some quota to send the data. - tq, err := wait(s.ctx, t.ctx, s.done, s.goAway, t.sendQuotaPool.acquire()) - if err != nil { - return err - } - if sq < size { - size = sq - } - if tq < size { - size = tq - } - if size > len(r) { - size = len(r) - } - p := r[:size] - ps := len(p) - if ps < tq { - // Overbooked transport quota. Return it back. - t.sendQuotaPool.add(tq - ps) - } - // Acquire local send quota to be able to write to the controlBuf. - ltq, err := wait(s.ctx, t.ctx, s.done, s.goAway, s.localSendQuota.acquire()) - if err != nil { - if _, ok := err.(ConnectionError); !ok { - t.sendQuotaPool.add(ps) - } - return err - } - s.localSendQuota.add(ltq - ps) // It's ok if we make it negative. - var endStream bool - // See if this is the last frame to be written. - if opts.Last { - if len(r)-size == 0 { // No more data in r after this iteration. - if idx == 0 { // We're writing data header. - if len(data) == 0 { // There's no data to follow. - endStream = true - } - } else { // We're writing data. - endStream = true - } - } - } - success := func() { - t.controlBuf.put(&dataFrame{streamID: s.id, endStream: endStream, d: p, f: func() { s.localSendQuota.add(ps) }}) - if ps < sq { - s.sendQuotaPool.lockedAdd(sq - ps) - } - r = r[ps:] - } - failure := func() { - s.sendQuotaPool.lockedAdd(sq) - } - if !s.sendQuotaPool.compareAndExecute(quotaVer, success, failure) { - t.sendQuotaPool.add(ps) - s.localSendQuota.add(ps) - } + if opts.Last { + // If it's the last message, update stream state. + if !s.compareAndSwapState(streamActive, streamWriteDone) { + return errStreamDone } + } else if s.getState() != streamActive { + return errStreamDone } - if !opts.Last { - return nil - } - s.mu.Lock() - if s.state != streamDone { - s.state = streamWriteDone + df := &dataFrame{ + streamID: s.id, + endStream: opts.Last, + } + if hdr != nil || data != nil { // If it's not an empty data frame. + // Add some data to grpc message header so that we can equally + // distribute bytes across frames. + emptyLen := http2MaxFrameLen - len(hdr) + if emptyLen > len(data) { + emptyLen = len(data) + } + hdr = append(hdr, data[:emptyLen]...) + data = data[emptyLen:] + df.h, df.d = hdr, data + // TODO(mmukhi): The above logic in this if can be moved to loopyWriter's data handler. + if err := s.wq.get(int32(len(hdr) + len(data))); err != nil { + return err + } } - s.mu.Unlock() - return nil + return t.controlBuf.put(df) } func (t *http2Client) getStream(f http2.Frame) (*Stream, bool) { @@ -748,34 +782,17 @@ func (t *http2Client) getStream(f http2.Frame) (*Stream, bool) { // of stream if the application is requesting data larger in size than // the window. func (t *http2Client) adjustWindow(s *Stream, n uint32) { - s.mu.Lock() - defer s.mu.Unlock() - if s.state == streamDone { - return - } if w := s.fc.maybeAdjust(n); w > 0 { - // Piggyback connection's window update along. - if cw := t.fc.resetPendingUpdate(); cw > 0 { - t.controlBuf.put(&windowUpdate{0, cw}) - } - t.controlBuf.put(&windowUpdate{s.id, w}) + t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) } } -// updateWindow adjusts the inbound quota for the stream and the transport. -// Window updates will deliver to the controller for sending when -// the cumulative quota exceeds the corresponding threshold. +// updateWindow adjusts the inbound quota for the stream. +// Window updates will be sent out when the cumulative quota +// exceeds the corresponding threshold. func (t *http2Client) updateWindow(s *Stream, n uint32) { - s.mu.Lock() - defer s.mu.Unlock() - if s.state == streamDone { - return - } if w := s.fc.onRead(n); w > 0 { - if cw := t.fc.resetPendingUpdate(); cw > 0 { - t.controlBuf.put(&windowUpdate{0, cw}) - } - t.controlBuf.put(&windowUpdate{s.id, w}) + t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) } } @@ -787,15 +804,17 @@ func (t *http2Client) updateFlowControl(n uint32) { for _, s := range t.activeStreams { s.fc.newLimit(n) } - t.initialWindowSize = int32(n) t.mu.Unlock() - t.controlBuf.put(&windowUpdate{0, t.fc.newLimit(n)}) - t.controlBuf.put(&settings{ - ack: false, + updateIWS := func(interface{}) bool { + t.initialWindowSize = int32(n) + return true + } + t.controlBuf.executeAndPut(updateIWS, &outgoingWindowUpdate{streamID: 0, increment: t.fc.newLimit(n)}) + t.controlBuf.put(&outgoingSettings{ ss: []http2.Setting{ { ID: http2.SettingInitialWindowSize, - Val: uint32(n), + Val: n, }, }, }) @@ -805,7 +824,7 @@ func (t *http2Client) handleData(f *http2.DataFrame) { size := f.Header().Length var sendBDPPing bool if t.bdpEst != nil { - sendBDPPing = t.bdpEst.add(uint32(size)) + sendBDPPing = t.bdpEst.add(size) } // Decouple connection's flow control from application's read. // An update on connection's flow control should not depend on @@ -816,21 +835,24 @@ func (t *http2Client) handleData(f *http2.DataFrame) { // active(fast) streams from starving in presence of slow or // inactive streams. // - // Furthermore, if a bdpPing is being sent out we can piggyback - // connection's window update for the bytes we just received. + if w := t.fc.onData(size); w > 0 { + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: 0, + increment: w, + }) + } if sendBDPPing { - if size != 0 { // Could've been an empty data frame. - t.controlBuf.put(&windowUpdate{0, uint32(size)}) + // Avoid excessive ping detection (e.g. in an L7 proxy) + // by sending a window update prior to the BDP ping. + + if w := t.fc.reset(); w > 0 { + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: 0, + increment: w, + }) } + t.controlBuf.put(bdpPing) - } else { - if err := t.fc.onData(uint32(size)); err != nil { - t.Close() - return - } - if w := t.fc.onRead(uint32(size)); w > 0 { - t.controlBuf.put(&windowUpdate{0, w}) - } } // Select the right stream to dispatch. s, ok := t.getStream(f) @@ -838,25 +860,15 @@ func (t *http2Client) handleData(f *http2.DataFrame) { return } if size > 0 { - s.mu.Lock() - if s.state == streamDone { - s.mu.Unlock() - return - } - if err := s.fc.onData(uint32(size)); err != nil { - s.rstStream = true - s.rstError = http2.ErrCodeFlowControl - s.finish(status.New(codes.Internal, err.Error())) - s.mu.Unlock() - s.write(recvMsg{err: io.EOF}) + if err := s.fc.onData(size); err != nil { + t.closeStream(s, io.EOF, true, http2.ErrCodeFlowControl, status.New(codes.Internal, err.Error()), nil, false) return } if f.Header().Flags.Has(http2.FlagDataPadded) { - if w := s.fc.onRead(uint32(size) - uint32(len(f.Data()))); w > 0 { - t.controlBuf.put(&windowUpdate{s.id, w}) + if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 { + t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) } } - s.mu.Unlock() // TODO(bradfitz, zhaoq): A copy is required here because there is no // guarantee f.Data() is consumed before the arrival of next frame. // Can this copy be eliminated? @@ -869,14 +881,7 @@ func (t *http2Client) handleData(f *http2.DataFrame) { // The server has closed the stream without sending trailers. Record that // the read direction is closed, and set the status appropriately. if f.FrameHeader.Flags.Has(http2.FlagDataEndStream) { - s.mu.Lock() - if s.state == streamDone { - s.mu.Unlock() - return - } - s.finish(status.New(codes.Internal, "server closed the stream without sending trailers")) - s.mu.Unlock() - s.write(recvMsg{err: io.EOF}) + t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.New(codes.Internal, "server closed the stream without sending trailers"), nil, true) } } @@ -885,36 +890,55 @@ func (t *http2Client) handleRSTStream(f *http2.RSTStreamFrame) { if !ok { return } - s.mu.Lock() - if s.state == streamDone { - s.mu.Unlock() - return - } - if !s.headerDone { - close(s.headerChan) - s.headerDone = true + if f.ErrCode == http2.ErrCodeRefusedStream { + // The stream was unprocessed by the server. + atomic.StoreUint32(&s.unprocessed, 1) } - statusCode, ok := http2ErrConvTab[http2.ErrCode(f.ErrCode)] + statusCode, ok := http2ErrConvTab[f.ErrCode] if !ok { warningf("transport: http2Client.handleRSTStream found no mapped gRPC status for the received http2 error %v", f.ErrCode) statusCode = codes.Unknown } - s.finish(status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode)) - s.mu.Unlock() - s.write(recvMsg{err: io.EOF}) + t.closeStream(s, io.EOF, false, http2.ErrCodeNo, status.Newf(statusCode, "stream terminated by RST_STREAM with error code: %v", f.ErrCode), nil, false) } -func (t *http2Client) handleSettings(f *http2.SettingsFrame) { +func (t *http2Client) handleSettings(f *http2.SettingsFrame, isFirst bool) { if f.IsAck() { return } + var maxStreams *uint32 var ss []http2.Setting f.ForeachSetting(func(s http2.Setting) error { + if s.ID == http2.SettingMaxConcurrentStreams { + maxStreams = new(uint32) + *maxStreams = s.Val + return nil + } ss = append(ss, s) return nil }) - // The settings will be applied once the ack is sent. - t.controlBuf.put(&settings{ack: true, ss: ss}) + if isFirst && maxStreams == nil { + maxStreams = new(uint32) + *maxStreams = math.MaxUint32 + } + sf := &incomingSettings{ + ss: ss, + } + if maxStreams == nil { + t.controlBuf.put(sf) + return + } + updateStreamQuota := func(interface{}) bool { + delta := int64(*maxStreams) - int64(t.maxConcurrentStreams) + t.maxConcurrentStreams = *maxStreams + t.streamQuota += delta + if delta > 0 && t.waitingStreams > 0 { + close(t.streamsQuotaAvailable) // wake all of them up. + t.streamsQuotaAvailable = make(chan struct{}, 1) + } + return true + } + t.controlBuf.executeAndPut(updateStreamQuota, sf) } func (t *http2Client) handlePing(f *http2.PingFrame) { @@ -932,7 +956,7 @@ func (t *http2Client) handlePing(f *http2.PingFrame) { func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { t.mu.Lock() - if t.state != reachable && t.state != draining { + if t.state == closing { t.mu.Unlock() return } @@ -945,12 +969,16 @@ func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { t.Close() return } - // A client can receive multiple GoAways from server (look at https://github.com/grpc/grpc-go/issues/1387). - // The idea is that the first GoAway will be sent with an ID of MaxInt32 and the second GoAway will be sent after an RTT delay - // with the ID of the last stream the server will process. - // Therefore, when we get the first GoAway we don't really close any streams. While in case of second GoAway we - // close all streams created after the second GoAwayId. This way streams that were in-flight while the GoAway from server - // was being sent don't get killed. + // A client can receive multiple GoAways from the server (see + // https://github.com/grpc/grpc-go/issues/1387). The idea is that the first + // GoAway will be sent with an ID of MaxInt32 and the second GoAway will be + // sent after an RTT delay with the ID of the last stream the server will + // process. + // + // Therefore, when we get the first GoAway we don't necessarily close any + // streams. While in case of second GoAway we close all streams created after + // the GoAwayId. This way streams that were in-flight while the GoAway from + // server was being sent don't get killed. select { case <-t.goAway: // t.goAway has been closed (i.e.,multiple GoAways). // If there are multiple GoAways the first one should always have an ID greater than the following ones. @@ -963,6 +991,7 @@ func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { t.setGoAwayReason(f) close(t.goAway) t.state = draining + t.controlBuf.put(&incomingGoAway{}) } // All streams with IDs greater than the GoAwayId // and smaller than the previous GoAway ID should be killed. @@ -972,7 +1001,9 @@ func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { } for streamID, stream := range t.activeStreams { if streamID > id && streamID <= upperLimit { - close(stream.goAway) + // The stream was unprocessed by the server. + atomic.StoreUint32(&stream.unprocessed, 1) + t.closeStream(stream, errStreamDrain, false, http2.ErrCodeNo, statusGoAway, nil, false) } } t.prevGoAwayID = id @@ -988,11 +1019,11 @@ func (t *http2Client) handleGoAway(f *http2.GoAwayFrame) { // It expects a lock on transport's mutext to be held by // the caller. func (t *http2Client) setGoAwayReason(f *http2.GoAwayFrame) { - t.goAwayReason = NoReason + t.goAwayReason = GoAwayNoReason switch f.ErrCode { case http2.ErrCodeEnhanceYourCalm: if string(f.DebugData()) == "too_many_pings" { - t.goAwayReason = TooManyPings + t.goAwayReason = GoAwayTooManyPings } } } @@ -1004,15 +1035,10 @@ func (t *http2Client) GetGoAwayReason() GoAwayReason { } func (t *http2Client) handleWindowUpdate(f *http2.WindowUpdateFrame) { - id := f.Header().StreamID - incr := f.Increment - if id == 0 { - t.sendQuotaPool.add(int(incr)) - return - } - if s, ok := t.getStream(f); ok { - s.sendQuotaPool.add(int(incr)) - } + t.controlBuf.put(&incomingWindowUpdate{ + streamID: f.Header().StreamID, + increment: f.Increment, + }) } // operateHeaders takes action on the decoded headers. @@ -1021,18 +1047,10 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { if !ok { return } - s.mu.Lock() - s.bytesReceived = true - s.mu.Unlock() + atomic.StoreUint32(&s.bytesReceived, 1) var state decodeState if err := state.decodeResponseHeader(frame); err != nil { - s.mu.Lock() - if !s.headerDone { - close(s.headerChan) - s.headerDone = true - } - s.mu.Unlock() - s.write(recvMsg{err: err}) + t.closeStream(s, err, true, http2.ErrCodeProtocol, nil, nil, false) // Something wrong. Stops reading even when there is remaining. return } @@ -1056,40 +1074,25 @@ func (t *http2Client) operateHeaders(frame *http2.MetaHeadersFrame) { } } }() - - s.mu.Lock() - if !endStream { - s.recvCompress = state.encoding - } - if !s.headerDone { - if !endStream && len(state.mdata) > 0 { - s.header = state.mdata + // If headers haven't been received yet. + if atomic.SwapUint32(&s.headerDone, 1) == 0 { + if !endStream { + // Headers frame is not actually a trailers-only frame. + isHeader = true + // These values can be set without any synchronization because + // stream goroutine will read it only after seeing a closed + // headerChan which we'll close after setting this. + s.recvCompress = state.encoding + if len(state.mdata) > 0 { + s.header = state.mdata + } } close(s.headerChan) - s.headerDone = true - isHeader = true } - if !endStream || s.state == streamDone { - s.mu.Unlock() + if !endStream { return } - - if len(state.mdata) > 0 { - s.trailer = state.mdata - } - s.finish(state.status()) - s.mu.Unlock() - s.write(recvMsg{err: io.EOF}) -} - -func handleMalformedHTTP2(s *Stream, err error) { - s.mu.Lock() - if !s.headerDone { - close(s.headerChan) - s.headerDone = true - } - s.mu.Unlock() - s.write(recvMsg{err: err}) + t.closeStream(s, io.EOF, false, http2.ErrCodeNo, state.status(), state.mdata, true) } // reader runs as a separate goroutine in charge of reading data from network @@ -1099,6 +1102,7 @@ func handleMalformedHTTP2(s *Stream, err error) { // optimal. // TODO(zhaoq): Check the validity of the incoming frame sequence. func (t *http2Client) reader() { + defer close(t.readerDone) // Check the validity of server preface. frame, err := t.framer.fr.ReadFrame() if err != nil { @@ -1111,7 +1115,8 @@ func (t *http2Client) reader() { t.Close() return } - t.handleSettings(sf) + t.onSuccess() + t.handleSettings(sf, true) // loop to keep reading incoming messages on this transport. for { @@ -1127,7 +1132,7 @@ func (t *http2Client) reader() { t.mu.Unlock() if s != nil { // use error detail to provide better err message - handleMalformedHTTP2(s, streamErrorf(http2ErrConvTab[se.Code], "%v", t.framer.fr.ErrorDetail())) + t.closeStream(s, streamErrorf(http2ErrConvTab[se.Code], "%v", t.framer.fr.ErrorDetail()), true, http2.ErrCodeProtocol, nil, nil, false) } continue } else { @@ -1144,7 +1149,7 @@ func (t *http2Client) reader() { case *http2.RSTStreamFrame: t.handleRSTStream(frame) case *http2.SettingsFrame: - t.handleSettings(frame) + t.handleSettings(frame, false) case *http2.PingFrame: t.handlePing(frame) case *http2.GoAwayFrame: @@ -1157,107 +1162,6 @@ func (t *http2Client) reader() { } } -func (t *http2Client) applySettings(ss []http2.Setting) { - for _, s := range ss { - switch s.ID { - case http2.SettingMaxConcurrentStreams: - // TODO(zhaoq): This is a hack to avoid significant refactoring of the - // code to deal with the unrealistic int32 overflow. Probably will try - // to find a better way to handle this later. - if s.Val > math.MaxInt32 { - s.Val = math.MaxInt32 - } - t.mu.Lock() - ms := t.maxStreams - t.maxStreams = int(s.Val) - t.mu.Unlock() - t.streamsQuota.add(int(s.Val) - ms) - case http2.SettingInitialWindowSize: - t.mu.Lock() - for _, stream := range t.activeStreams { - // Adjust the sending quota for each stream. - stream.sendQuotaPool.addAndUpdate(int(s.Val) - int(t.streamSendQuota)) - } - t.streamSendQuota = s.Val - t.mu.Unlock() - } - } -} - -// TODO(mmukhi): A lot of this code(and code in other places in the tranpsort layer) -// is duplicated between the client and the server. -// The transport layer needs to be refactored to take care of this. -func (t *http2Client) itemHandler(i item) error { - var err error - switch i := i.(type) { - case *dataFrame: - err = t.framer.fr.WriteData(i.streamID, i.endStream, i.d) - if err == nil { - i.f() - } - case *headerFrame: - t.hBuf.Reset() - for _, f := range i.hf { - t.hEnc.WriteField(f) - } - endHeaders := false - first := true - for !endHeaders { - size := t.hBuf.Len() - if size > http2MaxFrameLen { - size = http2MaxFrameLen - } else { - endHeaders = true - } - if first { - first = false - err = t.framer.fr.WriteHeaders(http2.HeadersFrameParam{ - StreamID: i.streamID, - BlockFragment: t.hBuf.Next(size), - EndStream: i.endStream, - EndHeaders: endHeaders, - }) - } else { - err = t.framer.fr.WriteContinuation( - i.streamID, - endHeaders, - t.hBuf.Next(size), - ) - } - if err != nil { - return err - } - } - case *windowUpdate: - err = t.framer.fr.WriteWindowUpdate(i.streamID, i.increment) - case *settings: - if i.ack { - t.applySettings(i.ss) - err = t.framer.fr.WriteSettingsAck() - } else { - err = t.framer.fr.WriteSettings(i.ss...) - } - case *resetStream: - // If the server needs to be to intimated about stream closing, - // then we need to make sure the RST_STREAM frame is written to - // the wire before the headers of the next stream waiting on - // streamQuota. We ensure this by adding to the streamsQuota pool - // only after having acquired the writableChan to send RST_STREAM. - err = t.framer.fr.WriteRSTStream(i.streamID, i.code) - t.streamsQuota.add(1) - case *flushIO: - err = t.framer.writer.Flush() - case *ping: - if !i.ack { - t.bdpEst.timesnap(i.data) - } - err = t.framer.fr.WritePing(i.ack, i.data) - default: - errorf("transport: http2Client.controller got unexpected item type %v\n", i) - } - return err -} - // keepalive running in a separate goroutune makes sure the connection is alive by sending pings. func (t *http2Client) keepalive() { p := &ping{data: [8]byte{}} @@ -1284,6 +1188,11 @@ func (t *http2Client) keepalive() { } } else { t.mu.Unlock() + if channelz.IsOn() { + t.czmu.Lock() + t.kpCount++ + t.czmu.Unlock() + } // Send ping. t.controlBuf.put(p) } @@ -1320,3 +1229,56 @@ func (t *http2Client) Error() <-chan struct{} { func (t *http2Client) GoAway() <-chan struct{} { return t.goAway } + +func (t *http2Client) ChannelzMetric() *channelz.SocketInternalMetric { + t.czmu.RLock() + s := channelz.SocketInternalMetric{ + StreamsStarted: t.streamsStarted, + StreamsSucceeded: t.streamsSucceeded, + StreamsFailed: t.streamsFailed, + MessagesSent: t.msgSent, + MessagesReceived: t.msgRecv, + KeepAlivesSent: t.kpCount, + LastLocalStreamCreatedTimestamp: t.lastStreamCreated, + LastMessageSentTimestamp: t.lastMsgSent, + LastMessageReceivedTimestamp: t.lastMsgRecv, + LocalFlowControlWindow: int64(t.fc.getSize()), + //socket options + LocalAddr: t.localAddr, + RemoteAddr: t.remoteAddr, + // Security + // RemoteName : + } + t.czmu.RUnlock() + s.RemoteFlowControlWindow = t.getOutFlowWindow() + return &s +} + +func (t *http2Client) IncrMsgSent() { + t.czmu.Lock() + t.msgSent++ + t.lastMsgSent = time.Now() + t.czmu.Unlock() +} + +func (t *http2Client) IncrMsgRecv() { + t.czmu.Lock() + t.msgRecv++ + t.lastMsgRecv = time.Now() + t.czmu.Unlock() +} + +func (t *http2Client) getOutFlowWindow() int64 { + resp := make(chan uint32, 1) + timer := time.NewTimer(time.Second) + defer timer.Stop() + t.controlBuf.put(&outFlowControlSizeRequest{resp}) + select { + case sz := <-resp: + return int64(sz) + case <-t.ctxDone: + return -1 + case <-timer.C: + return -2 + } +} diff --git a/vendor/google.golang.org/grpc/transport/http2_server.go b/vendor/google.golang.org/grpc/transport/http2_server.go index bad29b88ab..8b93e222e9 100644 --- a/vendor/google.golang.org/grpc/transport/http2_server.go +++ b/vendor/google.golang.org/grpc/transport/http2_server.go @@ -35,6 +35,8 @@ import ( "golang.org/x/net/context" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" + + "google.golang.org/grpc/channelz" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/keepalive" @@ -52,25 +54,25 @@ var ErrIllegalHeaderWrite = errors.New("transport: the stream is done or WriteHe // http2Server implements the ServerTransport interface with HTTP2. type http2Server struct { ctx context.Context + ctxDone <-chan struct{} // Cache the context.Done() chan cancel context.CancelFunc conn net.Conn + loopy *loopyWriter + readerDone chan struct{} // sync point to enable testing. + writerDone chan struct{} // sync point to enable testing. remoteAddr net.Addr localAddr net.Addr maxStreamID uint32 // max stream ID ever seen authInfo credentials.AuthInfo // auth info about the connection inTapHandle tap.ServerInHandle framer *framer - hBuf *bytes.Buffer // the buffer for HPACK encoding - hEnc *hpack.Encoder // HPACK encoder // The max number of concurrent streams. maxStreams uint32 // controlBuf delivers all the control related tasks (e.g., window // updates, reset streams, and various settings) to the controller. controlBuf *controlBuffer - fc *inFlow - // sendQuotaPool provides flow control to outbound message. - sendQuotaPool *quotaPool - stats stats.Handler + fc *trInFlow + stats stats.Handler // Flag to keep track of reading activity on transport. // 1 is true and 0 is false. activity uint32 // Accessed atomically. @@ -101,13 +103,27 @@ type http2Server struct { drainChan chan struct{} state transportState activeStreams map[uint32]*Stream - // the per-stream outbound flow control window size set by the peer. - streamSendQuota uint32 // idle is the time instant when the connection went idle. // This is either the beginning of the connection or when the number of // RPCs go down to 0. // When the connection is busy, this value is set to 0. idle time.Time + + // Fields below are for channelz metric collection. + channelzID int64 // channelz unique identification number + czmu sync.RWMutex + kpCount int64 + // The number of streams that have started, including already finished ones. + streamsStarted int64 + // The number of streams that have ended successfully by sending frame with + // EoS bit set. + streamsSucceeded int64 + streamsFailed int64 + lastStreamCreated time.Time + msgSent int64 + msgRecv int64 + lastMsgSent time.Time + lastMsgRecv time.Time } // newHTTP2Server constructs a ServerTransport based on HTTP2. ConnectionError is @@ -152,12 +168,12 @@ func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err Val: uint32(iwz)}) } if err := framer.fr.WriteSettings(isettings...); err != nil { - return nil, connectionErrorf(true, err, "transport: %v", err) + return nil, connectionErrorf(false, err, "transport: %v", err) } // Adjust the connection flow control window if needed. if delta := uint32(icwz - defaultWindowSize); delta > 0 { if err := framer.fr.WriteWindowUpdate(0, delta); err != nil { - return nil, connectionErrorf(true, err, "transport: %v", err) + return nil, connectionErrorf(false, err, "transport: %v", err) } } kp := config.KeepaliveParams @@ -182,32 +198,30 @@ func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err if kep.MinTime == 0 { kep.MinTime = defaultKeepalivePolicyMinTime } - var buf bytes.Buffer ctx, cancel := context.WithCancel(context.Background()) t := &http2Server{ ctx: ctx, cancel: cancel, + ctxDone: ctx.Done(), conn: conn, remoteAddr: conn.RemoteAddr(), localAddr: conn.LocalAddr(), authInfo: config.AuthInfo, framer: framer, - hBuf: &buf, - hEnc: hpack.NewEncoder(&buf), + readerDone: make(chan struct{}), + writerDone: make(chan struct{}), maxStreams: maxStreams, inTapHandle: config.InTapHandle, - controlBuf: newControlBuffer(), - fc: &inFlow{limit: uint32(icwz)}, - sendQuotaPool: newQuotaPool(defaultWindowSize), + fc: &trInFlow{limit: uint32(icwz)}, state: reachable, activeStreams: make(map[uint32]*Stream), - streamSendQuota: defaultWindowSize, stats: config.StatsHandler, kp: kp, idle: time.Now(), kep: kep, initialWindowSize: iwz, } + t.controlBuf = newControlBuffer(t.ctxDone) if dynamicWindow { t.bdpEst = &bdpEstimator{ bdp: initialWindowSize, @@ -222,10 +236,46 @@ func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err connBegin := &stats.ConnBegin{} t.stats.HandleConn(t.ctx, connBegin) } + if channelz.IsOn() { + t.channelzID = channelz.RegisterNormalSocket(t, config.ChannelzParentID, "") + } t.framer.writer.Flush() + + defer func() { + if err != nil { + t.Close() + } + }() + + // Check the validity of client preface. + preface := make([]byte, len(clientPreface)) + if _, err := io.ReadFull(t.conn, preface); err != nil { + return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to receive the preface from client: %v", err) + } + if !bytes.Equal(preface, clientPreface) { + return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams received bogus greeting from client: %q", preface) + } + + frame, err := t.framer.fr.ReadFrame() + if err == io.EOF || err == io.ErrUnexpectedEOF { + return nil, err + } + if err != nil { + return nil, connectionErrorf(false, err, "transport: http2Server.HandleStreams failed to read initial settings frame: %v", err) + } + atomic.StoreUint32(&t.activity, 1) + sf, ok := frame.(*http2.SettingsFrame) + if !ok { + return nil, connectionErrorf(false, nil, "transport: http2Server.HandleStreams saw invalid preface type %T from client", frame) + } + t.handleSettings(sf) + go func() { - loopyWriter(t.ctx, t.controlBuf, t.itemHandler) - t.Close() + t.loopy = newLoopyWriter(serverSide, t.framer, t.controlBuf, t.bdpEst) + t.loopy.ssGoAwayHandler = t.outgoingGoAwayHandler + t.loopy.run() + t.conn.Close() + close(t.writerDone) }() go t.keepalive() return t, nil @@ -234,12 +284,16 @@ func newHTTP2Server(conn net.Conn, config *ServerConfig) (_ ServerTransport, err // operateHeader takes action on the decoded headers. func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func(*Stream), traceCtx func(context.Context, string) context.Context) (close bool) { streamID := frame.Header().StreamID - var state decodeState for _, hf := range frame.Fields { if err := state.processHeaderField(hf); err != nil { if se, ok := err.(StreamError); ok { - t.controlBuf.put(&resetStream{streamID, statusCodeConvTab[se.Code]}) + t.controlBuf.put(&cleanupStream{ + streamID: streamID, + rst: true, + rstCode: statusCodeConvTab[se.Code], + onWrite: func() {}, + }) } return } @@ -247,14 +301,14 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( buf := newRecvBuffer() s := &Stream{ - id: streamID, - st: t, - buf: buf, - fc: &inFlow{limit: uint32(t.initialWindowSize)}, - recvCompress: state.encoding, - method: state.method, + id: streamID, + st: t, + buf: buf, + fc: &inFlow{limit: uint32(t.initialWindowSize)}, + recvCompress: state.encoding, + method: state.method, + contentSubtype: state.contentSubtype, } - if frame.StreamEnded() { // s is just created by the caller. No lock needed. s.state = streamReadDone @@ -272,10 +326,6 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( pr.AuthInfo = t.authInfo } s.ctx = peer.NewContext(s.ctx, pr) - // Cache the current stream to the context so that the server application - // can find out. Required when the server wants to send some metadata - // back to the client (unary call only). - s.ctx = newContextWithStream(s.ctx, s) // Attach the received metadata to the context. if len(state.mdata) > 0 { s.ctx = metadata.NewIncomingContext(s.ctx, state.mdata) @@ -294,7 +344,12 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( s.ctx, err = t.inTapHandle(s.ctx, info) if err != nil { warningf("transport: http2Server.operateHeaders got an error from InTapHandle: %v", err) - t.controlBuf.put(&resetStream{s.id, http2.ErrCodeRefusedStream}) + t.controlBuf.put(&cleanupStream{ + streamID: s.id, + rst: true, + rstCode: http2.ErrCodeRefusedStream, + onWrite: func() {}, + }) return } } @@ -305,7 +360,12 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( } if uint32(len(t.activeStreams)) >= t.maxStreams { t.mu.Unlock() - t.controlBuf.put(&resetStream{streamID, http2.ErrCodeRefusedStream}) + t.controlBuf.put(&cleanupStream{ + streamID: streamID, + rst: true, + rstCode: http2.ErrCodeRefusedStream, + onWrite: func() {}, + }) return } if streamID%2 != 1 || streamID <= t.maxStreamID { @@ -315,13 +375,17 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( return true } t.maxStreamID = streamID - s.sendQuotaPool = newQuotaPool(int(t.streamSendQuota)) - s.localSendQuota = newQuotaPool(defaultLocalSendQuota) t.activeStreams[streamID] = s if len(t.activeStreams) == 1 { t.idle = time.Time{} } t.mu.Unlock() + if channelz.IsOn() { + t.czmu.Lock() + t.streamsStarted++ + t.lastStreamCreated = time.Now() + t.czmu.Unlock() + } s.requestRead = func(n int) { t.adjustWindow(s, uint32(n)) } @@ -337,10 +401,13 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( } t.stats.HandleRPC(s.ctx, inHeader) } + s.ctxDone = s.ctx.Done() + s.wq = newWriteQuota(defaultWriteQuota, s.ctxDone) s.trReader = &transportReader{ reader: &recvBufferReader{ - ctx: s.ctx, - recv: s.buf, + ctx: s.ctx, + ctxDone: s.ctxDone, + recv: s.buf, }, windowHandler: func(n int) { t.updateWindow(s, uint32(n)) @@ -354,53 +421,26 @@ func (t *http2Server) operateHeaders(frame *http2.MetaHeadersFrame, handle func( // typically run in a separate goroutine. // traceCtx attaches trace to ctx and returns the new context. func (t *http2Server) HandleStreams(handle func(*Stream), traceCtx func(context.Context, string) context.Context) { - // Check the validity of client preface. - preface := make([]byte, len(clientPreface)) - if _, err := io.ReadFull(t.conn, preface); err != nil { - // Only log if it isn't a simple tcp accept check (ie: tcp balancer doing open/close socket) - if err != io.EOF { - errorf("transport: http2Server.HandleStreams failed to receive the preface from client: %v", err) - } - t.Close() - return - } - if !bytes.Equal(preface, clientPreface) { - errorf("transport: http2Server.HandleStreams received bogus greeting from client: %q", preface) - t.Close() - return - } - - frame, err := t.framer.fr.ReadFrame() - if err == io.EOF || err == io.ErrUnexpectedEOF { - t.Close() - return - } - if err != nil { - errorf("transport: http2Server.HandleStreams failed to read initial settings frame: %v", err) - t.Close() - return - } - atomic.StoreUint32(&t.activity, 1) - sf, ok := frame.(*http2.SettingsFrame) - if !ok { - errorf("transport: http2Server.HandleStreams saw invalid preface type %T from client", frame) - t.Close() - return - } - t.handleSettings(sf) - + defer close(t.readerDone) for { frame, err := t.framer.fr.ReadFrame() atomic.StoreUint32(&t.activity, 1) if err != nil { if se, ok := err.(http2.StreamError); ok { + warningf("transport: http2Server.HandleStreams encountered http2.StreamError: %v", se) t.mu.Lock() s := t.activeStreams[se.StreamID] t.mu.Unlock() if s != nil { - t.closeStream(s) + t.closeStream(s, true, se.Code, nil, false) + } else { + t.controlBuf.put(&cleanupStream{ + streamID: se.StreamID, + rst: true, + rstCode: se.Code, + onWrite: func() {}, + }) } - t.controlBuf.put(&resetStream{se.StreamID, se.Code}) continue } if err == io.EOF || err == io.ErrUnexpectedEOF { @@ -454,33 +494,20 @@ func (t *http2Server) getStream(f http2.Frame) (*Stream, bool) { // of stream if the application is requesting data larger in size than // the window. func (t *http2Server) adjustWindow(s *Stream, n uint32) { - s.mu.Lock() - defer s.mu.Unlock() - if s.state == streamDone { - return - } if w := s.fc.maybeAdjust(n); w > 0 { - if cw := t.fc.resetPendingUpdate(); cw > 0 { - t.controlBuf.put(&windowUpdate{0, cw}) - } - t.controlBuf.put(&windowUpdate{s.id, w}) + t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, increment: w}) } + } // updateWindow adjusts the inbound quota for the stream and the transport. // Window updates will deliver to the controller for sending when // the cumulative quota exceeds the corresponding threshold. func (t *http2Server) updateWindow(s *Stream, n uint32) { - s.mu.Lock() - defer s.mu.Unlock() - if s.state == streamDone { - return - } if w := s.fc.onRead(n); w > 0 { - if cw := t.fc.resetPendingUpdate(); cw > 0 { - t.controlBuf.put(&windowUpdate{0, cw}) - } - t.controlBuf.put(&windowUpdate{s.id, w}) + t.controlBuf.put(&outgoingWindowUpdate{streamID: s.id, + increment: w, + }) } } @@ -494,13 +521,15 @@ func (t *http2Server) updateFlowControl(n uint32) { } t.initialWindowSize = int32(n) t.mu.Unlock() - t.controlBuf.put(&windowUpdate{0, t.fc.newLimit(n)}) - t.controlBuf.put(&settings{ - ack: false, + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: 0, + increment: t.fc.newLimit(n), + }) + t.controlBuf.put(&outgoingSettings{ ss: []http2.Setting{ { ID: http2.SettingInitialWindowSize, - Val: uint32(n), + Val: n, }, }, }) @@ -511,7 +540,7 @@ func (t *http2Server) handleData(f *http2.DataFrame) { size := f.Header().Length var sendBDPPing bool if t.bdpEst != nil { - sendBDPPing = t.bdpEst.add(uint32(size)) + sendBDPPing = t.bdpEst.add(size) } // Decouple connection's flow control from application's read. // An update on connection's flow control should not depend on @@ -521,23 +550,22 @@ func (t *http2Server) handleData(f *http2.DataFrame) { // Decoupling the connection flow control will prevent other // active(fast) streams from starving in presence of slow or // inactive streams. - // - // Furthermore, if a bdpPing is being sent out we can piggyback - // connection's window update for the bytes we just received. + if w := t.fc.onData(size); w > 0 { + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: 0, + increment: w, + }) + } if sendBDPPing { - if size != 0 { // Could be an empty frame. - t.controlBuf.put(&windowUpdate{0, uint32(size)}) + // Avoid excessive ping detection (e.g. in an L7 proxy) + // by sending a window update prior to the BDP ping. + if w := t.fc.reset(); w > 0 { + t.controlBuf.put(&outgoingWindowUpdate{ + streamID: 0, + increment: w, + }) } t.controlBuf.put(bdpPing) - } else { - if err := t.fc.onData(uint32(size)); err != nil { - errorf("transport: http2Server %v", err) - t.Close() - return - } - if w := t.fc.onRead(uint32(size)); w > 0 { - t.controlBuf.put(&windowUpdate{0, w}) - } } // Select the right stream to dispatch. s, ok := t.getStream(f) @@ -545,23 +573,15 @@ func (t *http2Server) handleData(f *http2.DataFrame) { return } if size > 0 { - s.mu.Lock() - if s.state == streamDone { - s.mu.Unlock() - return - } - if err := s.fc.onData(uint32(size)); err != nil { - s.mu.Unlock() - t.closeStream(s) - t.controlBuf.put(&resetStream{s.id, http2.ErrCodeFlowControl}) + if err := s.fc.onData(size); err != nil { + t.closeStream(s, true, http2.ErrCodeFlowControl, nil, false) return } if f.Header().Flags.Has(http2.FlagDataPadded) { - if w := s.fc.onRead(uint32(size) - uint32(len(f.Data()))); w > 0 { - t.controlBuf.put(&windowUpdate{s.id, w}) + if w := s.fc.onRead(size - uint32(len(f.Data()))); w > 0 { + t.controlBuf.put(&outgoingWindowUpdate{s.id, w}) } } - s.mu.Unlock() // TODO(bradfitz, zhaoq): A copy is required here because there is no // guarantee f.Data() is consumed before the arrival of next frame. // Can this copy be eliminated? @@ -573,11 +593,7 @@ func (t *http2Server) handleData(f *http2.DataFrame) { } if f.Header().Flags.Has(http2.FlagDataEndStream) { // Received the end of stream from the client. - s.mu.Lock() - if s.state != streamDone { - s.state = streamReadDone - } - s.mu.Unlock() + s.compareAndSwapState(streamActive, streamReadDone) s.write(recvMsg{err: io.EOF}) } } @@ -587,7 +603,7 @@ func (t *http2Server) handleRSTStream(f *http2.RSTStreamFrame) { if !ok { return } - t.closeStream(s) + t.closeStream(s, false, 0, nil, false) } func (t *http2Server) handleSettings(f *http2.SettingsFrame) { @@ -599,21 +615,9 @@ func (t *http2Server) handleSettings(f *http2.SettingsFrame) { ss = append(ss, s) return nil }) - t.controlBuf.put(&settings{ack: true, ss: ss}) -} - -func (t *http2Server) applySettings(ss []http2.Setting) { - for _, s := range ss { - if s.ID == http2.SettingInitialWindowSize { - t.mu.Lock() - for _, stream := range t.activeStreams { - stream.sendQuotaPool.addAndUpdate(int(s.Val) - int(t.streamSendQuota)) - } - t.streamSendQuota = s.Val - t.mu.Unlock() - } - - } + t.controlBuf.put(&incomingSettings{ + ss: ss, + }) } const ( @@ -666,36 +670,21 @@ func (t *http2Server) handlePing(f *http2.PingFrame) { if t.pingStrikes > maxPingStrikes { // Send goaway and close the connection. - errorf("transport: Got to too many pings from the client, closing the connection.") + errorf("transport: Got too many pings from the client, closing the connection.") t.controlBuf.put(&goAway{code: http2.ErrCodeEnhanceYourCalm, debugData: []byte("too_many_pings"), closeConn: true}) } } func (t *http2Server) handleWindowUpdate(f *http2.WindowUpdateFrame) { - id := f.Header().StreamID - incr := f.Increment - if id == 0 { - t.sendQuotaPool.add(int(incr)) - return - } - if s, ok := t.getStream(f); ok { - s.sendQuotaPool.add(int(incr)) - } + t.controlBuf.put(&incomingWindowUpdate{ + streamID: f.Header().StreamID, + increment: f.Increment, + }) } // WriteHeader sends the header metedata md back to the client. func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error { - select { - case <-s.ctx.Done(): - return ContextErr(s.ctx.Err()) - case <-t.ctx.Done(): - return ErrConnClosing - default: - } - - s.mu.Lock() - if s.headerOk || s.state == streamDone { - s.mu.Unlock() + if s.headerOk || s.getState() == streamDone { return ErrIllegalHeaderWrite } s.headerOk = true @@ -707,12 +696,11 @@ func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error { } } md = s.header - s.mu.Unlock() - // TODO(mmukhi): Benchmark if the perfomance gets better if count the metadata and other header fields + // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields // first and create a slice of that exact size. headerFields := make([]hpack.HeaderField, 0, 2) // at least :status, content-type will be there if none else. headerFields = append(headerFields, hpack.HeaderField{Name: ":status", Value: "200"}) - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: "application/grpc"}) + headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(s.contentSubtype)}) if s.sendCompress != "" { headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-encoding", Value: s.sendCompress}) } @@ -729,11 +717,15 @@ func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error { streamID: s.id, hf: headerFields, endStream: false, + onWrite: func() { + atomic.StoreUint32(&t.resetPingStrikes, 1) + }, + wq: s.wq, }) if t.stats != nil { - outHeader := &stats.OutHeader{ - //WireLength: // TODO(mmukhi): Revisit this later, if needed. - } + // Note: WireLength is not set in outHeader. + // TODO(mmukhi): Revisit this later, if needed. + outHeader := &stats.OutHeader{} t.stats.HandleRPC(s.Context(), outHeader) } return nil @@ -744,37 +736,21 @@ func (t *http2Server) WriteHeader(s *Stream, md metadata.MD) error { // TODO(zhaoq): Now it indicates the end of entire stream. Revisit if early // OK is adopted. func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { - select { - case <-t.ctx.Done(): - return ErrConnClosing - default: - } - - var headersSent, hasHeader bool - s.mu.Lock() - if s.state == streamDone { - s.mu.Unlock() - return nil - } - if s.headerOk { - headersSent = true - } - if s.header.Len() > 0 { - hasHeader = true - } - s.mu.Unlock() - - if !headersSent && hasHeader { - t.WriteHeader(s, nil) - headersSent = true + if !s.headerOk && s.header.Len() > 0 { + if err := t.WriteHeader(s, nil); err != nil { + return err + } + } else { + if s.getState() == streamDone { + return nil + } } - - // TODO(mmukhi): Benchmark if the perfomance gets better if count the metadata and other header fields + // TODO(mmukhi): Benchmark if the performance gets better if count the metadata and other header fields // first and create a slice of that exact size. headerFields := make([]hpack.HeaderField, 0, 2) // grpc-status and grpc-message will be there if none else. - if !headersSent { + if !s.headerOk { headerFields = append(headerFields, hpack.HeaderField{Name: ":status", Value: "200"}) - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: "application/grpc"}) + headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: contentType(s.contentSubtype)}) } headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-status", Value: strconv.Itoa(int(st.Code()))}) headerFields = append(headerFields, hpack.HeaderField{Name: "grpc-message", Value: encodeGrpcMessage(st.Message())}) @@ -799,110 +775,66 @@ func (t *http2Server) WriteStatus(s *Stream, st *status.Status) error { headerFields = append(headerFields, hpack.HeaderField{Name: k, Value: encodeMetadataHeader(k, v)}) } } - t.controlBuf.put(&headerFrame{ + trailer := &headerFrame{ streamID: s.id, hf: headerFields, endStream: true, - }) + onWrite: func() { + atomic.StoreUint32(&t.resetPingStrikes, 1) + }, + } + t.closeStream(s, false, 0, trailer, true) if t.stats != nil { t.stats.HandleRPC(s.Context(), &stats.OutTrailer{}) } - t.closeStream(s) return nil } // Write converts the data into HTTP2 data frame and sends it out. Non-nil error // is returns if it fails (e.g., framing error, transport error). -func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) (err error) { - select { - case <-s.ctx.Done(): - return ContextErr(s.ctx.Err()) - case <-t.ctx.Done(): - return ErrConnClosing - default: - } - - var writeHeaderFrame bool - s.mu.Lock() - if s.state == streamDone { - s.mu.Unlock() - return streamErrorf(codes.Unknown, "the stream has been done") - } - if !s.headerOk { - writeHeaderFrame = true - } - s.mu.Unlock() - if writeHeaderFrame { - t.WriteHeader(s, nil) +func (t *http2Server) Write(s *Stream, hdr []byte, data []byte, opts *Options) error { + if !s.headerOk { // Headers haven't been written yet. + if err := t.WriteHeader(s, nil); err != nil { + // TODO(mmukhi, dfawley): Make sure this is the right code to return. + return streamErrorf(codes.Internal, "transport: %v", err) + } + } else { + // Writing headers checks for this condition. + if s.getState() == streamDone { + // TODO(mmukhi, dfawley): Should the server write also return io.EOF? + s.cancel() + select { + case <-t.ctx.Done(): + return ErrConnClosing + default: + } + return ContextErr(s.ctx.Err()) + } } - // Add data to header frame so that we can equally distribute data across frames. + // Add some data to header frame so that we can equally distribute bytes across frames. emptyLen := http2MaxFrameLen - len(hdr) if emptyLen > len(data) { emptyLen = len(data) } hdr = append(hdr, data[:emptyLen]...) data = data[emptyLen:] - for _, r := range [][]byte{hdr, data} { - for len(r) > 0 { - size := http2MaxFrameLen - // Wait until the stream has some quota to send the data. - quotaChan, quotaVer := s.sendQuotaPool.acquireWithVersion() - sq, err := wait(s.ctx, t.ctx, nil, nil, quotaChan) - if err != nil { - return err - } - // Wait until the transport has some quota to send the data. - tq, err := wait(s.ctx, t.ctx, nil, nil, t.sendQuotaPool.acquire()) - if err != nil { - return err - } - if sq < size { - size = sq - } - if tq < size { - size = tq - } - if size > len(r) { - size = len(r) - } - p := r[:size] - ps := len(p) - if ps < tq { - // Overbooked transport quota. Return it back. - t.sendQuotaPool.add(tq - ps) - } - // Acquire local send quota to be able to write to the controlBuf. - ltq, err := wait(s.ctx, t.ctx, nil, nil, s.localSendQuota.acquire()) - if err != nil { - if _, ok := err.(ConnectionError); !ok { - t.sendQuotaPool.add(ps) - } - return err - } - s.localSendQuota.add(ltq - ps) // It's ok we make this negative. - // Reset ping strikes when sending data since this might cause - // the peer to send ping. + df := &dataFrame{ + streamID: s.id, + h: hdr, + d: data, + onEachWrite: func() { atomic.StoreUint32(&t.resetPingStrikes, 1) - success := func() { - t.controlBuf.put(&dataFrame{streamID: s.id, endStream: false, d: p, f: func() { - s.localSendQuota.add(ps) - }}) - if ps < sq { - // Overbooked stream quota. Return it back. - s.sendQuotaPool.lockedAdd(sq - ps) - } - r = r[ps:] - } - failure := func() { - s.sendQuotaPool.lockedAdd(sq) - } - if !s.sendQuotaPool.compareAndExecute(quotaVer, success, failure) { - t.sendQuotaPool.add(ps) - s.localSendQuota.add(ps) - } + }, + } + if err := s.wq.get(int32(len(hdr) + len(data))); err != nil { + select { + case <-t.ctx.Done(): + return ErrConnClosing + default: } + return ContextErr(s.ctx.Err()) } - return nil + return t.controlBuf.put(df) } // keepalive running in a separate goroutine does the following: @@ -947,7 +879,7 @@ func (t *http2Server) keepalive() { // The connection has been idle for a duration of keepalive.MaxConnectionIdle or more. // Gracefully close the connection. t.drain(http2.ErrCodeNo, []byte{}) - // Reseting the timer so that the clean-up doesn't deadlock. + // Resetting the timer so that the clean-up doesn't deadlock. maxIdle.Reset(infinity) return } @@ -959,7 +891,7 @@ func (t *http2Server) keepalive() { case <-maxAge.C: // Close the connection after grace period. t.Close() - // Reseting the timer so that the clean-up doesn't deadlock. + // Resetting the timer so that the clean-up doesn't deadlock. maxAge.Reset(infinity) case <-t.ctx.Done(): } @@ -972,11 +904,16 @@ func (t *http2Server) keepalive() { } if pingSent { t.Close() - // Reseting the timer so that the clean-up doesn't deadlock. + // Resetting the timer so that the clean-up doesn't deadlock. keepalive.Reset(infinity) return } pingSent = true + if channelz.IsOn() { + t.czmu.Lock() + t.kpCount++ + t.czmu.Unlock() + } t.controlBuf.put(p) keepalive.Reset(t.kp.Timeout) case <-t.ctx.Done(): @@ -985,127 +922,6 @@ func (t *http2Server) keepalive() { } } -var goAwayPing = &ping{data: [8]byte{1, 6, 1, 8, 0, 3, 3, 9}} - -// TODO(mmukhi): A lot of this code(and code in other places in the tranpsort layer) -// is duplicated between the client and the server. -// The transport layer needs to be refactored to take care of this. -func (t *http2Server) itemHandler(i item) error { - switch i := i.(type) { - case *dataFrame: - if err := t.framer.fr.WriteData(i.streamID, i.endStream, i.d); err != nil { - return err - } - i.f() - return nil - case *headerFrame: - t.hBuf.Reset() - for _, f := range i.hf { - t.hEnc.WriteField(f) - } - first := true - endHeaders := false - for !endHeaders { - size := t.hBuf.Len() - if size > http2MaxFrameLen { - size = http2MaxFrameLen - } else { - endHeaders = true - } - var err error - if first { - first = false - err = t.framer.fr.WriteHeaders(http2.HeadersFrameParam{ - StreamID: i.streamID, - BlockFragment: t.hBuf.Next(size), - EndStream: i.endStream, - EndHeaders: endHeaders, - }) - } else { - err = t.framer.fr.WriteContinuation( - i.streamID, - endHeaders, - t.hBuf.Next(size), - ) - } - if err != nil { - return err - } - } - atomic.StoreUint32(&t.resetPingStrikes, 1) - return nil - case *windowUpdate: - return t.framer.fr.WriteWindowUpdate(i.streamID, i.increment) - case *settings: - if i.ack { - t.applySettings(i.ss) - return t.framer.fr.WriteSettingsAck() - } - return t.framer.fr.WriteSettings(i.ss...) - case *resetStream: - return t.framer.fr.WriteRSTStream(i.streamID, i.code) - case *goAway: - t.mu.Lock() - if t.state == closing { - t.mu.Unlock() - // The transport is closing. - return fmt.Errorf("transport: Connection closing") - } - sid := t.maxStreamID - if !i.headsUp { - // Stop accepting more streams now. - t.state = draining - t.mu.Unlock() - if err := t.framer.fr.WriteGoAway(sid, i.code, i.debugData); err != nil { - return err - } - if i.closeConn { - // Abruptly close the connection following the GoAway (via - // loopywriter). But flush out what's inside the buffer first. - t.framer.writer.Flush() - return fmt.Errorf("transport: Connection closing") - } - return nil - } - t.mu.Unlock() - // For a graceful close, send out a GoAway with stream ID of MaxUInt32, - // Follow that with a ping and wait for the ack to come back or a timer - // to expire. During this time accept new streams since they might have - // originated before the GoAway reaches the client. - // After getting the ack or timer expiration send out another GoAway this - // time with an ID of the max stream server intends to process. - if err := t.framer.fr.WriteGoAway(math.MaxUint32, http2.ErrCodeNo, []byte{}); err != nil { - return err - } - if err := t.framer.fr.WritePing(false, goAwayPing.data); err != nil { - return err - } - go func() { - timer := time.NewTimer(time.Minute) - defer timer.Stop() - select { - case <-t.drainChan: - case <-timer.C: - case <-t.ctx.Done(): - return - } - t.controlBuf.put(&goAway{code: i.code, debugData: i.debugData}) - }() - return nil - case *flushIO: - return t.framer.writer.Flush() - case *ping: - if !i.ack { - t.bdpEst.timesnap(i.data) - } - return t.framer.fr.WritePing(i.ack, i.data) - default: - err := status.Errorf(codes.Internal, "transport: http2Server.controller got unexpected item type %t", i) - errorf("%v", err) - return err - } -} - // Close starts shutting down the http2Server transport. // TODO(zhaoq): Now the destruction is not blocked on any pending streams. This // could cause some resource issue. Revisit this later. @@ -1119,8 +935,12 @@ func (t *http2Server) Close() error { streams := t.activeStreams t.activeStreams = nil t.mu.Unlock() + t.controlBuf.finish() t.cancel() err := t.conn.Close() + if channelz.IsOn() { + channelz.RemoveEntry(t.channelzID) + } // Cancel all active streams. for _, s := range streams { s.cancel() @@ -1134,27 +954,45 @@ func (t *http2Server) Close() error { // closeStream clears the footprint of a stream when the stream is not needed // any more. -func (t *http2Server) closeStream(s *Stream) { - t.mu.Lock() - delete(t.activeStreams, s.id) - if len(t.activeStreams) == 0 { - t.idle = time.Now() - } - if t.state == draining && len(t.activeStreams) == 0 { - defer t.Close() +func (t *http2Server) closeStream(s *Stream, rst bool, rstCode http2.ErrCode, hdr *headerFrame, eosReceived bool) { + if s.swapState(streamDone) == streamDone { + // If the stream was already done, return. + return } - t.mu.Unlock() // In case stream sending and receiving are invoked in separate // goroutines (e.g., bi-directional streaming), cancel needs to be // called to interrupt the potential blocking on other goroutines. s.cancel() - s.mu.Lock() - if s.state == streamDone { - s.mu.Unlock() - return + cleanup := &cleanupStream{ + streamID: s.id, + rst: rst, + rstCode: rstCode, + onWrite: func() { + t.mu.Lock() + if t.activeStreams != nil { + delete(t.activeStreams, s.id) + if len(t.activeStreams) == 0 { + t.idle = time.Now() + } + } + t.mu.Unlock() + if channelz.IsOn() { + t.czmu.Lock() + if eosReceived { + t.streamsSucceeded++ + } else { + t.streamsFailed++ + } + t.czmu.Unlock() + } + }, + } + if hdr != nil { + hdr.cleanup = cleanup + t.controlBuf.put(hdr) + } else { + t.controlBuf.put(cleanup) } - s.state = streamDone - s.mu.Unlock() } func (t *http2Server) RemoteAddr() net.Addr { @@ -1175,6 +1013,116 @@ func (t *http2Server) drain(code http2.ErrCode, debugData []byte) { t.controlBuf.put(&goAway{code: code, debugData: debugData, headsUp: true}) } +var goAwayPing = &ping{data: [8]byte{1, 6, 1, 8, 0, 3, 3, 9}} + +// Handles outgoing GoAway and returns true if loopy needs to put itself +// in draining mode. +func (t *http2Server) outgoingGoAwayHandler(g *goAway) (bool, error) { + t.mu.Lock() + if t.state == closing { // TODO(mmukhi): This seems unnecessary. + t.mu.Unlock() + // The transport is closing. + return false, ErrConnClosing + } + sid := t.maxStreamID + if !g.headsUp { + // Stop accepting more streams now. + t.state = draining + if len(t.activeStreams) == 0 { + g.closeConn = true + } + t.mu.Unlock() + if err := t.framer.fr.WriteGoAway(sid, g.code, g.debugData); err != nil { + return false, err + } + if g.closeConn { + // Abruptly close the connection following the GoAway (via + // loopywriter). But flush out what's inside the buffer first. + t.framer.writer.Flush() + return false, fmt.Errorf("transport: Connection closing") + } + return true, nil + } + t.mu.Unlock() + // For a graceful close, send out a GoAway with stream ID of MaxUInt32, + // Follow that with a ping and wait for the ack to come back or a timer + // to expire. During this time accept new streams since they might have + // originated before the GoAway reaches the client. + // After getting the ack or timer expiration send out another GoAway this + // time with an ID of the max stream server intends to process. + if err := t.framer.fr.WriteGoAway(math.MaxUint32, http2.ErrCodeNo, []byte{}); err != nil { + return false, err + } + if err := t.framer.fr.WritePing(false, goAwayPing.data); err != nil { + return false, err + } + go func() { + timer := time.NewTimer(time.Minute) + defer timer.Stop() + select { + case <-t.drainChan: + case <-timer.C: + case <-t.ctx.Done(): + return + } + t.controlBuf.put(&goAway{code: g.code, debugData: g.debugData}) + }() + return false, nil +} + +func (t *http2Server) ChannelzMetric() *channelz.SocketInternalMetric { + t.czmu.RLock() + s := channelz.SocketInternalMetric{ + StreamsStarted: t.streamsStarted, + StreamsSucceeded: t.streamsSucceeded, + StreamsFailed: t.streamsFailed, + MessagesSent: t.msgSent, + MessagesReceived: t.msgRecv, + KeepAlivesSent: t.kpCount, + LastRemoteStreamCreatedTimestamp: t.lastStreamCreated, + LastMessageSentTimestamp: t.lastMsgSent, + LastMessageReceivedTimestamp: t.lastMsgRecv, + LocalFlowControlWindow: int64(t.fc.getSize()), + //socket options + LocalAddr: t.localAddr, + RemoteAddr: t.remoteAddr, + // Security + // RemoteName : + } + t.czmu.RUnlock() + s.RemoteFlowControlWindow = t.getOutFlowWindow() + return &s +} + +func (t *http2Server) IncrMsgSent() { + t.czmu.Lock() + t.msgSent++ + t.lastMsgSent = time.Now() + t.czmu.Unlock() +} + +func (t *http2Server) IncrMsgRecv() { + t.czmu.Lock() + t.msgRecv++ + t.lastMsgRecv = time.Now() + t.czmu.Unlock() +} + +func (t *http2Server) getOutFlowWindow() int64 { + resp := make(chan uint32) + timer := time.NewTimer(time.Second) + defer timer.Stop() + t.controlBuf.put(&outFlowControlSizeRequest{resp}) + select { + case sz := <-resp: + return int64(sz) + case <-t.ctxDone: + return -1 + case <-timer.C: + return -2 + } +} + var rgen = rand.New(rand.NewSource(time.Now().UnixNano())) func getJitter(v time.Duration) time.Duration { diff --git a/vendor/google.golang.org/grpc/transport/http_util.go b/vendor/google.golang.org/grpc/transport/http_util.go index 39f878cfd5..a355866089 100644 --- a/vendor/google.golang.org/grpc/transport/http_util.go +++ b/vendor/google.golang.org/grpc/transport/http_util.go @@ -23,7 +23,6 @@ import ( "bytes" "encoding/base64" "fmt" - "io" "net" "net/http" "strconv" @@ -46,6 +45,12 @@ const ( // http2IOBufSize specifies the buffer size for sending frames. defaultWriteBufSize = 32 * 1024 defaultReadBufSize = 32 * 1024 + // baseContentType is the base content-type for gRPC. This is a valid + // content-type on it's own, but can also include a content-subtype such as + // "proto" as a suffix after "+" or ";". See + // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests + // for more details. + baseContentType = "application/grpc" ) var ( @@ -64,7 +69,7 @@ var ( http2.ErrCodeConnect: codes.Internal, http2.ErrCodeEnhanceYourCalm: codes.ResourceExhausted, http2.ErrCodeInadequateSecurity: codes.PermissionDenied, - http2.ErrCodeHTTP11Required: codes.FailedPrecondition, + http2.ErrCodeHTTP11Required: codes.Internal, } statusCodeConvTab = map[codes.Code]http2.ErrCode{ codes.Internal: http2.ErrCodeInternal, @@ -111,9 +116,10 @@ type decodeState struct { timeout time.Duration method string // key-value metadata map from the peer. - mdata map[string][]string - statsTags []byte - statsTrace []byte + mdata map[string][]string + statsTags []byte + statsTrace []byte + contentSubtype string } // isReservedHeader checks whether hdr belongs to HTTP2 headers @@ -125,6 +131,7 @@ func isReservedHeader(hdr string) bool { } switch hdr { case "content-type", + "user-agent", "grpc-message-type", "grpc-encoding", "grpc-message", @@ -138,28 +145,55 @@ func isReservedHeader(hdr string) bool { } } -// isWhitelistedPseudoHeader checks whether hdr belongs to HTTP2 pseudoheaders -// that should be propagated into metadata visible to users. -func isWhitelistedPseudoHeader(hdr string) bool { +// isWhitelistedHeader checks whether hdr should be propagated +// into metadata visible to users. +func isWhitelistedHeader(hdr string) bool { switch hdr { - case ":authority": + case ":authority", "user-agent": return true default: return false } } -func validContentType(t string) bool { - e := "application/grpc" - if !strings.HasPrefix(t, e) { - return false +// contentSubtype returns the content-subtype for the given content-type. The +// given content-type must be a valid content-type that starts with +// "application/grpc". A content-subtype will follow "application/grpc" after a +// "+" or ";". See +// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for +// more details. +// +// If contentType is not a valid content-type for gRPC, the boolean +// will be false, otherwise true. If content-type == "application/grpc", +// "application/grpc+", or "application/grpc;", the boolean will be true, +// but no content-subtype will be returned. +// +// contentType is assumed to be lowercase already. +func contentSubtype(contentType string) (string, bool) { + if contentType == baseContentType { + return "", true + } + if !strings.HasPrefix(contentType, baseContentType) { + return "", false + } + // guaranteed since != baseContentType and has baseContentType prefix + switch contentType[len(baseContentType)] { + case '+', ';': + // this will return true for "application/grpc+" or "application/grpc;" + // which the previous validContentType function tested to be valid, so we + // just say that no content-subtype is specified in this case + return contentType[len(baseContentType)+1:], true + default: + return "", false } - // Support variations on the content-type - // (e.g. "application/grpc+blah", "application/grpc;blah"). - if len(t) > len(e) && t[len(e)] != '+' && t[len(e)] != ';' { - return false +} + +// contentSubtype is assumed to be lowercase +func contentType(contentSubtype string) string { + if contentSubtype == "" { + return baseContentType } - return true + return baseContentType + "+" + contentSubtype } func (d *decodeState) status() *status.Status { @@ -228,9 +262,9 @@ func (d *decodeState) decodeResponseHeader(frame *http2.MetaHeadersFrame) error // gRPC status doesn't exist and http status is OK. // Set rawStatusCode to be unknown and return nil error. // So that, if the stream has ended this Unknown status - // will be propogated to the user. + // will be propagated to the user. // Otherwise, it will be ignored. In which case, status from - // a later trailer, that has StreamEnded flag set, is propogated. + // a later trailer, that has StreamEnded flag set, is propagated. code := int(codes.Unknown) d.rawStatusCode = &code return nil @@ -247,9 +281,16 @@ func (d *decodeState) addMetadata(k, v string) { func (d *decodeState) processHeaderField(f hpack.HeaderField) error { switch f.Name { case "content-type": - if !validContentType(f.Value) { - return streamErrorf(codes.FailedPrecondition, "transport: received the unexpected content-type %q", f.Value) + contentSubtype, validContentType := contentSubtype(f.Value) + if !validContentType { + return streamErrorf(codes.Internal, "transport: received the unexpected content-type %q", f.Value) } + d.contentSubtype = contentSubtype + // TODO: do we want to propagate the whole content-type in the metadata, + // or come up with a way to just propagate the content-subtype if it was set? + // ie {"content-type": "application/grpc+proto"} or {"content-subtype": "proto"} + // in the metadata? + d.addMetadata(f.Name, f.Value) case "grpc-encoding": d.encoding = f.Value case "grpc-status": @@ -299,7 +340,7 @@ func (d *decodeState) processHeaderField(f hpack.HeaderField) error { d.statsTrace = v d.addMetadata(f.Name, string(v)) default: - if isReservedHeader(f.Name) && !isWhitelistedPseudoHeader(f.Name) { + if isReservedHeader(f.Name) && !isWhitelistedHeader(f.Name) { break } v, err := decodeMetadataHeader(f.Name, f.Value) @@ -307,7 +348,7 @@ func (d *decodeState) processHeaderField(f hpack.HeaderField) error { errorf("Failed to decode metadata header (%q, %q): %v", f.Name, f.Value, err) return nil } - d.addMetadata(f.Name, string(v)) + d.addMetadata(f.Name, v) } return nil } @@ -468,19 +509,63 @@ func decodeGrpcMessageUnchecked(msg string) string { return buf.String() } +type bufWriter struct { + buf []byte + offset int + batchSize int + conn net.Conn + err error + + onFlush func() +} + +func newBufWriter(conn net.Conn, batchSize int) *bufWriter { + return &bufWriter{ + buf: make([]byte, batchSize*2), + batchSize: batchSize, + conn: conn, + } +} + +func (w *bufWriter) Write(b []byte) (n int, err error) { + if w.err != nil { + return 0, w.err + } + n = copy(w.buf[w.offset:], b) + w.offset += n + if w.offset >= w.batchSize { + err = w.Flush() + } + return n, err +} + +func (w *bufWriter) Flush() error { + if w.err != nil { + return w.err + } + if w.offset == 0 { + return nil + } + if w.onFlush != nil { + w.onFlush() + } + _, w.err = w.conn.Write(w.buf[:w.offset]) + w.offset = 0 + return w.err +} + type framer struct { - numWriters int32 - reader io.Reader - writer *bufio.Writer - fr *http2.Framer + writer *bufWriter + fr *http2.Framer } func newFramer(conn net.Conn, writeBufferSize, readBufferSize int) *framer { + r := bufio.NewReaderSize(conn, readBufferSize) + w := newBufWriter(conn, writeBufferSize) f := &framer{ - reader: bufio.NewReaderSize(conn, readBufferSize), - writer: bufio.NewWriterSize(conn, writeBufferSize), + writer: w, + fr: http2.NewFramer(w, r), } - f.fr = http2.NewFramer(f.writer, f.reader) // Opt-in to Frame reuse API on framer to reduce garbage. // Frames aren't safe to read from after a subsequent call to ReadFrame. f.fr.SetReuseFrames() diff --git a/vendor/google.golang.org/grpc/transport/http_util_test.go b/vendor/google.golang.org/grpc/transport/http_util_test.go deleted file mode 100644 index 4ebb239050..0000000000 --- a/vendor/google.golang.org/grpc/transport/http_util_test.go +++ /dev/null @@ -1,175 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 transport - -import ( - "fmt" - "reflect" - "testing" - "time" -) - -func TestTimeoutEncode(t *testing.T) { - for _, test := range []struct { - in string - out string - }{ - {"12345678ns", "12345678n"}, - {"123456789ns", "123457u"}, - {"12345678us", "12345678u"}, - {"123456789us", "123457m"}, - {"12345678ms", "12345678m"}, - {"123456789ms", "123457S"}, - {"12345678s", "12345678S"}, - {"123456789s", "2057614M"}, - {"12345678m", "12345678M"}, - {"123456789m", "2057614H"}, - } { - d, err := time.ParseDuration(test.in) - if err != nil { - t.Fatalf("failed to parse duration string %s: %v", test.in, err) - } - out := encodeTimeout(d) - if out != test.out { - t.Fatalf("timeoutEncode(%s) = %s, want %s", test.in, out, test.out) - } - } -} - -func TestTimeoutDecode(t *testing.T) { - for _, test := range []struct { - // input - s string - // output - d time.Duration - err error - }{ - {"1234S", time.Second * 1234, nil}, - {"1234x", 0, fmt.Errorf("transport: timeout unit is not recognized: %q", "1234x")}, - {"1", 0, fmt.Errorf("transport: timeout string is too short: %q", "1")}, - {"", 0, fmt.Errorf("transport: timeout string is too short: %q", "")}, - } { - d, err := decodeTimeout(test.s) - if d != test.d || fmt.Sprint(err) != fmt.Sprint(test.err) { - t.Fatalf("timeoutDecode(%q) = %d, %v, want %d, %v", test.s, int64(d), err, int64(test.d), test.err) - } - } -} - -func TestValidContentType(t *testing.T) { - tests := []struct { - h string - want bool - }{ - {"application/grpc", true}, - {"application/grpc+", true}, - {"application/grpc+blah", true}, - {"application/grpc;", true}, - {"application/grpc;blah", true}, - {"application/grpcd", false}, - {"application/grpd", false}, - {"application/grp", false}, - } - for _, tt := range tests { - got := validContentType(tt.h) - if got != tt.want { - t.Errorf("validContentType(%q) = %v; want %v", tt.h, got, tt.want) - } - } -} - -func TestEncodeGrpcMessage(t *testing.T) { - for _, tt := range []struct { - input string - expected string - }{ - {"", ""}, - {"Hello", "Hello"}, - {"my favorite character is \u0000", "my favorite character is %00"}, - {"my favorite character is %", "my favorite character is %25"}, - } { - actual := encodeGrpcMessage(tt.input) - if tt.expected != actual { - t.Errorf("encodeGrpcMessage(%v) = %v, want %v", tt.input, actual, tt.expected) - } - } -} - -func TestDecodeGrpcMessage(t *testing.T) { - for _, tt := range []struct { - input string - expected string - }{ - {"", ""}, - {"Hello", "Hello"}, - {"H%61o", "Hao"}, - {"H%6", "H%6"}, - {"%G0", "%G0"}, - {"%E7%B3%BB%E7%BB%9F", "系统"}, - } { - actual := decodeGrpcMessage(tt.input) - if tt.expected != actual { - t.Errorf("dncodeGrpcMessage(%v) = %v, want %v", tt.input, actual, tt.expected) - } - } -} - -const binaryValue = string(128) - -func TestEncodeMetadataHeader(t *testing.T) { - for _, test := range []struct { - // input - kin string - vin string - // output - vout string - }{ - {"key", "abc", "abc"}, - {"KEY", "abc", "abc"}, - {"key-bin", "abc", "YWJj"}, - {"key-bin", binaryValue, "woA"}, - } { - v := encodeMetadataHeader(test.kin, test.vin) - if !reflect.DeepEqual(v, test.vout) { - t.Fatalf("encodeMetadataHeader(%q, %q) = %q, want %q", test.kin, test.vin, v, test.vout) - } - } -} - -func TestDecodeMetadataHeader(t *testing.T) { - for _, test := range []struct { - // input - kin string - vin string - // output - vout string - err error - }{ - {"a", "abc", "abc", nil}, - {"key-bin", "Zm9vAGJhcg==", "foo\x00bar", nil}, - {"key-bin", "Zm9vAGJhcg", "foo\x00bar", nil}, - {"key-bin", "woA=", binaryValue, nil}, - {"a", "abc,efg", "abc,efg", nil}, - } { - v, err := decodeMetadataHeader(test.kin, test.vin) - if !reflect.DeepEqual(v, test.vout) || !reflect.DeepEqual(err, test.err) { - t.Fatalf("decodeMetadataHeader(%q, %q) = %q, %v, want %q, %v", test.kin, test.vin, v, err, test.vout, test.err) - } - } -} diff --git a/vendor/google.golang.org/grpc/transport/transport.go b/vendor/google.golang.org/grpc/transport/transport.go index bde8fa5c3a..2f643a3d04 100644 --- a/vendor/google.golang.org/grpc/transport/transport.go +++ b/vendor/google.golang.org/grpc/transport/transport.go @@ -17,19 +17,19 @@ */ // Package transport defines and implements message oriented communication -// channel to complete various transactions (e.g., an RPC). -package transport // import "google.golang.org/grpc/transport" +// channel to complete various transactions (e.g., an RPC). It is meant for +// grpc-internal usage and is not intended to be imported directly by users. +package transport // externally used as import "google.golang.org/grpc/transport" import ( - stdctx "context" + "errors" "fmt" "io" "net" "sync" - "time" + "sync/atomic" "golang.org/x/net/context" - "golang.org/x/net/http2" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/keepalive" @@ -58,6 +58,7 @@ type recvBuffer struct { c chan recvMsg mu sync.Mutex backlog []recvMsg + err error } func newRecvBuffer() *recvBuffer { @@ -69,6 +70,13 @@ func newRecvBuffer() *recvBuffer { func (b *recvBuffer) put(r recvMsg) { b.mu.Lock() + if b.err != nil { + b.mu.Unlock() + // An error had occurred earlier, don't accept more + // data or errors. + return + } + b.err = r.err if len(b.backlog) == 0 { select { case b.c <- r: @@ -102,14 +110,15 @@ func (b *recvBuffer) get() <-chan recvMsg { return b.c } +// // recvBufferReader implements io.Reader interface to read the data from // recvBuffer. type recvBufferReader struct { - ctx context.Context - goAway chan struct{} - recv *recvBuffer - last []byte // Stores the remaining data in the previous calls. - err error + ctx context.Context + ctxDone <-chan struct{} // cache of ctx.Done() (for performance). + recv *recvBuffer + last []byte // Stores the remaining data in the previous calls. + err error } // Read reads the next len(p) bytes from last. If last is drained, it tries to @@ -131,10 +140,8 @@ func (r *recvBufferReader) read(p []byte) (n int, err error) { return copied, nil } select { - case <-r.ctx.Done(): + case <-r.ctxDone: return 0, ContextErr(r.ctx.Err()) - case <-r.goAway: - return 0, ErrStreamDrain case m := <-r.recv.get(): r.recv.load() if m.err != nil { @@ -146,61 +153,7 @@ func (r *recvBufferReader) read(p []byte) (n int, err error) { } } -// All items in an out of a controlBuffer should be the same type. -type item interface { - item() -} - -// controlBuffer is an unbounded channel of item. -type controlBuffer struct { - c chan item - mu sync.Mutex - backlog []item -} - -func newControlBuffer() *controlBuffer { - b := &controlBuffer{ - c: make(chan item, 1), - } - return b -} - -func (b *controlBuffer) put(r item) { - b.mu.Lock() - if len(b.backlog) == 0 { - select { - case b.c <- r: - b.mu.Unlock() - return - default: - } - } - b.backlog = append(b.backlog, r) - b.mu.Unlock() -} - -func (b *controlBuffer) load() { - b.mu.Lock() - if len(b.backlog) > 0 { - select { - case b.c <- b.backlog[0]: - b.backlog[0] = nil - b.backlog = b.backlog[1:] - default: - } - } - b.mu.Unlock() -} - -// get returns the channel that receives an item in the buffer. -// -// Upon receipt of an item, the caller should call load to send another -// item onto the channel if there is any. -func (b *controlBuffer) get() <-chan item { - return b.c -} - -type streamState uint8 +type streamState uint32 const ( streamActive streamState = iota @@ -211,66 +164,75 @@ const ( // Stream represents an RPC in the transport layer. type Stream struct { - id uint32 - // nil for client side Stream. - st ServerTransport - // ctx is the associated context of the stream. - ctx context.Context - // cancel is always nil for client side Stream. - cancel context.CancelFunc - // done is closed when the final status arrives. - done chan struct{} - // goAway is closed when the server sent GoAways signal before this stream was initiated. - goAway chan struct{} - // method records the associated RPC method of the stream. - method string + id uint32 + st ServerTransport // nil for client side Stream + ctx context.Context // the associated context of the stream + cancel context.CancelFunc // always nil for client side Stream + done chan struct{} // closed at the end of stream to unblock writers. On the client side. + ctxDone <-chan struct{} // same as done chan but for server side. Cache of ctx.Done() (for performance) + method string // the associated RPC method of the stream recvCompress string sendCompress string buf *recvBuffer trReader io.Reader fc *inFlow recvQuota uint32 - - // TODO: Remote this unused variable. - // The accumulated inbound quota pending for window update. - updateQuota uint32 + wq *writeQuota // Callback to state application's intentions to read data. This - // is used to adjust flow control, if need be. + // is used to adjust flow control, if needed. requestRead func(int) - sendQuotaPool *quotaPool - localSendQuota *quotaPool - // Close headerChan to indicate the end of reception of header metadata. - headerChan chan struct{} - // header caches the received header metadata. - header metadata.MD - // The key-value map of trailer metadata. - trailer metadata.MD - - mu sync.RWMutex // guard the following - // headerOK becomes true from the first header is about to send. - headerOk bool + headerChan chan struct{} // closed to indicate the end of header metadata. + headerDone uint32 // set when headerChan is closed. Used to avoid closing headerChan multiple times. + header metadata.MD // the received header metadata. + trailer metadata.MD // the key-value map of trailer metadata. + + headerOk bool // becomes true from the first header is about to send state streamState - // true iff headerChan is closed. Used to avoid closing headerChan - // multiple times. - headerDone bool - // the status error received from the server. - status *status.Status - // rstStream indicates whether a RST_STREAM frame needs to be sent - // to the server to signify that this stream is closing. - rstStream bool - // rstError is the error that needs to be sent along with the RST_STREAM frame. - rstError http2.ErrCode - // bytesSent and bytesReceived indicates whether any bytes have been sent or - // received on this stream. - bytesSent bool - bytesReceived bool + + status *status.Status // the status error received from the server + + bytesReceived uint32 // indicates whether any bytes have been received on this stream + unprocessed uint32 // set if the server sends a refused stream or GOAWAY including this stream + + // contentSubtype is the content-subtype for requests. + // this must be lowercase or the behavior is undefined. + contentSubtype string +} + +func (s *Stream) swapState(st streamState) streamState { + return streamState(atomic.SwapUint32((*uint32)(&s.state), uint32(st))) +} + +func (s *Stream) compareAndSwapState(oldState, newState streamState) bool { + return atomic.CompareAndSwapUint32((*uint32)(&s.state), uint32(oldState), uint32(newState)) +} + +func (s *Stream) getState() streamState { + return streamState(atomic.LoadUint32((*uint32)(&s.state))) +} + +func (s *Stream) waitOnHeader() error { + if s.headerChan == nil { + // On the server headerChan is always nil since a stream originates + // only after having received headers. + return nil + } + select { + case <-s.ctx.Done(): + return ContextErr(s.ctx.Err()) + case <-s.headerChan: + return nil + } } // RecvCompress returns the compression algorithm applied to the inbound // message. It is empty string if there is no compression applied. func (s *Stream) RecvCompress() string { + if err := s.waitOnHeader(); err != nil { + return "" + } return s.recvCompress } @@ -285,28 +247,17 @@ func (s *Stream) Done() <-chan struct{} { return s.done } -// GoAway returns a channel which is closed when the server sent GoAways signal -// before this stream was initiated. -func (s *Stream) GoAway() <-chan struct{} { - return s.goAway -} - // Header acquires the key-value pairs of header metadata once it // is available. It blocks until i) the metadata is ready or ii) there is no // header metadata or iii) the stream is canceled/expired. func (s *Stream) Header() (metadata.MD, error) { - var err error - select { - case <-s.ctx.Done(): - err = ContextErr(s.ctx.Err()) - case <-s.goAway: - err = ErrStreamDrain - case <-s.headerChan: - return s.header.Copy(), nil - } + err := s.waitOnHeader() // Even if the stream is closed, header is returned if available. select { case <-s.headerChan: + if s.header == nil { + return nil, nil + } return s.header.Copy(), nil default: } @@ -316,10 +267,10 @@ func (s *Stream) Header() (metadata.MD, error) { // Trailer returns the cached trailer metedata. Note that if it is not called // after the entire stream is done, it could return an empty MD. Client // side only. +// It can be safely read only after stream has ended that is either read +// or write have returned io.EOF. func (s *Stream) Trailer() metadata.MD { - s.mu.RLock() c := s.trailer.Copy() - s.mu.RUnlock() return c } @@ -329,6 +280,15 @@ func (s *Stream) ServerTransport() ServerTransport { return s.st } +// ContentSubtype returns the content-subtype for a request. For example, a +// content-subtype of "proto" will result in a content-type of +// "application/grpc+proto". This will always be lowercase. See +// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for +// more details. +func (s *Stream) ContentSubtype() string { + return s.contentSubtype +} + // Context returns the context of the stream. func (s *Stream) Context() context.Context { return s.ctx @@ -340,36 +300,42 @@ func (s *Stream) Method() string { } // Status returns the status received from the server. +// Status can be read safely only after the stream has ended, +// that is, read or write has returned io.EOF. func (s *Stream) Status() *status.Status { return s.status } // SetHeader sets the header metadata. This can be called multiple times. // Server side only. +// This should not be called in parallel to other data writes. func (s *Stream) SetHeader(md metadata.MD) error { - s.mu.Lock() - if s.headerOk || s.state == streamDone { - s.mu.Unlock() - return ErrIllegalHeaderWrite - } if md.Len() == 0 { - s.mu.Unlock() return nil } + if s.headerOk || atomic.LoadUint32((*uint32)(&s.state)) == uint32(streamDone) { + return ErrIllegalHeaderWrite + } s.header = metadata.Join(s.header, md) - s.mu.Unlock() return nil } +// SendHeader sends the given header metadata. The given metadata is +// combined with any metadata set by previous calls to SetHeader and +// then written to the transport stream. +func (s *Stream) SendHeader(md metadata.MD) error { + t := s.ServerTransport() + return t.WriteHeader(s, md) +} + // SetTrailer sets the trailer metadata which will be sent with the RPC status // by the server. This can be called multiple times. Server side only. +// This should not be called parallel to other data writes. func (s *Stream) SetTrailer(md metadata.MD) error { if md.Len() == 0 { return nil } - s.mu.Lock() s.trailer = metadata.Join(s.trailer, md) - s.mu.Unlock() return nil } @@ -409,28 +375,15 @@ func (t *transportReader) Read(p []byte) (n int, err error) { return } -// finish sets the stream's state and status, and closes the done channel. -// s.mu must be held by the caller. st must always be non-nil. -func (s *Stream) finish(st *status.Status) { - s.status = st - s.state = streamDone - close(s.done) -} - -// BytesSent indicates whether any bytes have been sent on this stream. -func (s *Stream) BytesSent() bool { - s.mu.Lock() - bs := s.bytesSent - s.mu.Unlock() - return bs -} - // BytesReceived indicates whether any bytes have been received on this stream. func (s *Stream) BytesReceived() bool { - s.mu.Lock() - br := s.bytesReceived - s.mu.Unlock() - return br + return atomic.LoadUint32(&s.bytesReceived) == 1 +} + +// Unprocessed indicates whether the server did not process this stream -- +// i.e. it sent a refused stream or GOAWAY including this stream ID. +func (s *Stream) Unprocessed() bool { + return atomic.LoadUint32(&s.unprocessed) == 1 } // GoString is implemented by Stream so context.String() won't @@ -439,21 +392,6 @@ func (s *Stream) GoString() string { return fmt.Sprintf("<stream: %p, %v>", s, s.method) } -// The key to save transport.Stream in the context. -type streamKey struct{} - -// newContextWithStream creates a new context from ctx and attaches stream -// to it. -func newContextWithStream(ctx context.Context, stream *Stream) context.Context { - return context.WithValue(ctx, streamKey{}, stream) -} - -// StreamFromContext returns the stream saved in ctx. -func StreamFromContext(ctx context.Context) (s *Stream, ok bool) { - s, ok = ctx.Value(streamKey{}).(*Stream) - return -} - // state of transport type transportState int @@ -475,6 +413,7 @@ type ServerConfig struct { InitialConnWindowSize int32 WriteBufferSize int ReadBufferSize int + ChannelzParentID int64 } // NewServerTransport creates a ServerTransport with conn or non-nil error @@ -510,18 +449,21 @@ type ConnectOptions struct { WriteBufferSize int // ReadBufferSize sets the size of read buffer, which in turn determines how much data can be read at most for one read syscall. ReadBufferSize int + // ChannelzParentID sets the addrConn id which initiate the creation of this client transport. + ChannelzParentID int64 } // TargetInfo contains the information of the target such as network address and metadata. type TargetInfo struct { - Addr string - Metadata interface{} + Addr string + Metadata interface{} + Authority string } // NewClientTransport establishes the transport with the required ConnectOptions // and returns it to the caller. -func NewClientTransport(ctx context.Context, target TargetInfo, opts ConnectOptions, timeout time.Duration) (ClientTransport, error) { - return newHTTP2Client(ctx, target, opts, timeout) +func NewClientTransport(connectCtx, ctx context.Context, target TargetInfo, opts ConnectOptions, onSuccess func()) (ClientTransport, error) { + return newHTTP2Client(connectCtx, ctx, target, opts, onSuccess) } // Options provides additional hints and information for message @@ -545,10 +487,6 @@ type CallHdr struct { // Method specifies the operation to perform. Method string - // RecvCompress specifies the compression algorithm applied on - // inbound messages. - RecvCompress string - // SendCompress specifies the compression algorithm applied on // outbound message. SendCompress string @@ -563,6 +501,14 @@ type CallHdr struct { // for performance purposes. // If it's false, new stream will never be flushed. Flush bool + + // ContentSubtype specifies the content-subtype for a request. For example, a + // content-subtype of "proto" will result in a content-type of + // "application/grpc+proto". The value of ContentSubtype must be all + // lowercase, otherwise the behavior is undefined. See + // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests + // for more details. + ContentSubtype string } // ClientTransport is the common interface for all gRPC client-side transport @@ -604,6 +550,12 @@ type ClientTransport interface { // GetGoAwayReason returns the reason why GoAway frame was received. GetGoAwayReason() GoAwayReason + + // IncrMsgSent increments the number of message sent through this transport. + IncrMsgSent() + + // IncrMsgRecv increments the number of message received through this transport. + IncrMsgRecv() } // ServerTransport is the common interface for all gRPC server-side transport @@ -637,6 +589,12 @@ type ServerTransport interface { // Drain notifies the client this ServerTransport stops accepting new RPCs. Drain() + + // IncrMsgSent increments the number of message sent through this transport. + IncrMsgSent() + + // IncrMsgRecv increments the number of message received through this transport. + IncrMsgRecv() } // streamErrorf creates an StreamError with the specified error code and description. @@ -686,9 +644,16 @@ func (e ConnectionError) Origin() error { var ( // ErrConnClosing indicates that the transport is closing. ErrConnClosing = connectionErrorf(true, nil, "transport is closing") - // ErrStreamDrain indicates that the stream is rejected by the server because - // the server stops accepting new RPCs. - ErrStreamDrain = streamErrorf(codes.Unavailable, "the server stops accepting new RPCs") + // errStreamDrain indicates that the stream is rejected because the + // connection is draining. This could be caused by goaway or balancer + // removing the address. + errStreamDrain = streamErrorf(codes.Unavailable, "the connection is draining") + // errStreamDone is returned from write at the client side to indiacte application + // layer of an error. + errStreamDone = errors.New("the stream is done") + // StatusGoAway indicates that the server sent a GOAWAY that included this + // stream's ID in unprocessed RPCs. + statusGoAway = status.New(codes.Unavailable, "the stream is rejected because server is draining the connection") ) // TODO: See if we can replace StreamError with status package errors. @@ -703,75 +668,16 @@ func (e StreamError) Error() string { return fmt.Sprintf("stream error: code = %s desc = %q", e.Code, e.Desc) } -// wait blocks until it can receive from one of the provided contexts or channels -func wait(ctx, tctx context.Context, done, goAway <-chan struct{}, proceed <-chan int) (int, error) { - select { - case <-ctx.Done(): - return 0, ContextErr(ctx.Err()) - case <-done: - return 0, io.EOF - case <-goAway: - return 0, ErrStreamDrain - case <-tctx.Done(): - return 0, ErrConnClosing - case i := <-proceed: - return i, nil - } -} - -// ContextErr converts the error from context package into a StreamError. -func ContextErr(err error) StreamError { - switch err { - case context.DeadlineExceeded, stdctx.DeadlineExceeded: - return streamErrorf(codes.DeadlineExceeded, "%v", err) - case context.Canceled, stdctx.Canceled: - return streamErrorf(codes.Canceled, "%v", err) - } - return streamErrorf(codes.Internal, "Unexpected error from context packet: %v", err) -} - // GoAwayReason contains the reason for the GoAway frame received. type GoAwayReason uint8 const ( - // Invalid indicates that no GoAway frame is received. - Invalid GoAwayReason = 0 - // NoReason is the default value when GoAway frame is received. - NoReason GoAwayReason = 1 - // TooManyPings indicates that a GoAway frame with ErrCodeEnhanceYourCalm - // was received and that the debug data said "too_many_pings". - TooManyPings GoAwayReason = 2 + // GoAwayInvalid indicates that no GoAway frame is received. + GoAwayInvalid GoAwayReason = 0 + // GoAwayNoReason is the default value when GoAway frame is received. + GoAwayNoReason GoAwayReason = 1 + // GoAwayTooManyPings indicates that a GoAway frame with + // ErrCodeEnhanceYourCalm was received and that the debug data said + // "too_many_pings". + GoAwayTooManyPings GoAwayReason = 2 ) - -// loopyWriter is run in a separate go routine. It is the single code path that will -// write data on wire. -func loopyWriter(ctx context.Context, cbuf *controlBuffer, handler func(item) error) { - for { - select { - case i := <-cbuf.get(): - cbuf.load() - if err := handler(i); err != nil { - return - } - case <-ctx.Done(): - return - } - hasData: - for { - select { - case i := <-cbuf.get(): - cbuf.load() - if err := handler(i); err != nil { - return - } - case <-ctx.Done(): - return - default: - if err := handler(&flushIO{}); err != nil { - return - } - break hasData - } - } - } -} diff --git a/vendor/google.golang.org/grpc/transport/transport_test.go b/vendor/google.golang.org/grpc/transport/transport_test.go deleted file mode 100644 index e1dd080a15..0000000000 --- a/vendor/google.golang.org/grpc/transport/transport_test.go +++ /dev/null @@ -1,2158 +0,0 @@ -/* - * - * Copyright 2014 gRPC 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 transport - -import ( - "bufio" - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "math" - "net" - "net/http" - "reflect" - "strconv" - "strings" - "sync" - "testing" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/http2" - "golang.org/x/net/http2/hpack" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/status" -) - -type server struct { - lis net.Listener - port string - startedErr chan error // error (or nil) with server start value - mu sync.Mutex - conns map[ServerTransport]bool - h *testStreamHandler -} - -var ( - expectedRequest = []byte("ping") - expectedResponse = []byte("pong") - expectedRequestLarge = make([]byte, initialWindowSize*2) - expectedResponseLarge = make([]byte, initialWindowSize*2) - expectedInvalidHeaderField = "invalid/content-type" -) - -type testStreamHandler struct { - t *http2Server - notify chan struct{} -} - -type hType int - -const ( - normal hType = iota - suspended - notifyCall - misbehaved - encodingRequiredStatus - invalidHeaderField - delayRead - delayWrite - pingpong -) - -func (h *testStreamHandler) handleStreamAndNotify(s *Stream) { - if h.notify == nil { - return - } - go func() { - select { - case <-h.notify: - default: - close(h.notify) - } - }() -} - -func (h *testStreamHandler) handleStream(t *testing.T, s *Stream) { - req := expectedRequest - resp := expectedResponse - if s.Method() == "foo.Large" { - req = expectedRequestLarge - resp = expectedResponseLarge - } - p := make([]byte, len(req)) - _, err := s.Read(p) - if err != nil { - return - } - if !bytes.Equal(p, req) { - t.Fatalf("handleStream got %v, want %v", p, req) - } - // send a response back to the client. - h.t.Write(s, nil, resp, &Options{}) - // send the trailer to end the stream. - h.t.WriteStatus(s, status.New(codes.OK, "")) -} - -func (h *testStreamHandler) handleStreamPingPong(t *testing.T, s *Stream) { - header := make([]byte, 5) - for i := 0; i < 10; i++ { - if _, err := s.Read(header); err != nil { - t.Fatalf("Error on server while reading data header: %v", err) - } - sz := binary.BigEndian.Uint32(header[1:]) - msg := make([]byte, int(sz)) - if _, err := s.Read(msg); err != nil { - t.Fatalf("Error on server while reading message: %v", err) - } - buf := make([]byte, sz+5) - buf[0] = byte(0) - binary.BigEndian.PutUint32(buf[1:], uint32(sz)) - copy(buf[5:], msg) - h.t.Write(s, nil, buf, &Options{}) - } -} - -func (h *testStreamHandler) handleStreamMisbehave(t *testing.T, s *Stream) { - conn, ok := s.ServerTransport().(*http2Server) - if !ok { - t.Fatalf("Failed to convert %v to *http2Server", s.ServerTransport()) - } - var sent int - p := make([]byte, http2MaxFrameLen) - for sent < initialWindowSize { - n := initialWindowSize - sent - // The last message may be smaller than http2MaxFrameLen - if n <= http2MaxFrameLen { - if s.Method() == "foo.Connection" { - // Violate connection level flow control window of client but do not - // violate any stream level windows. - p = make([]byte, n) - } else { - // Violate stream level flow control window of client. - p = make([]byte, n+1) - } - } - conn.controlBuf.put(&dataFrame{s.id, false, p, func() {}}) - sent += len(p) - } -} - -func (h *testStreamHandler) handleStreamEncodingRequiredStatus(t *testing.T, s *Stream) { - // raw newline is not accepted by http2 framer so it must be encoded. - h.t.WriteStatus(s, encodingTestStatus) -} - -func (h *testStreamHandler) handleStreamInvalidHeaderField(t *testing.T, s *Stream) { - headerFields := []hpack.HeaderField{} - headerFields = append(headerFields, hpack.HeaderField{Name: "content-type", Value: expectedInvalidHeaderField}) - h.t.controlBuf.put(&headerFrame{ - streamID: s.id, - hf: headerFields, - endStream: false, - }) -} - -func (h *testStreamHandler) handleStreamDelayRead(t *testing.T, s *Stream) { - req := expectedRequest - resp := expectedResponse - if s.Method() == "foo.Large" { - req = expectedRequestLarge - resp = expectedResponseLarge - } - p := make([]byte, len(req)) - - // Wait before reading. Give time to client to start sending - // before server starts reading. - time.Sleep(2 * time.Second) - _, err := s.Read(p) - if err != nil { - t.Fatalf("s.Read(_) = _, %v, want _, <nil>", err) - return - } - - if !bytes.Equal(p, req) { - t.Fatalf("handleStream got %v, want %v", p, req) - } - // send a response back to the client. - h.t.Write(s, nil, resp, &Options{}) - // send the trailer to end the stream. - h.t.WriteStatus(s, status.New(codes.OK, "")) -} - -func (h *testStreamHandler) handleStreamDelayWrite(t *testing.T, s *Stream) { - req := expectedRequest - resp := expectedResponse - if s.Method() == "foo.Large" { - req = expectedRequestLarge - resp = expectedResponseLarge - } - p := make([]byte, len(req)) - _, err := s.Read(p) - if err != nil { - t.Fatalf("s.Read(_) = _, %v, want _, <nil>", err) - return - } - if !bytes.Equal(p, req) { - t.Fatalf("handleStream got %v, want %v", p, req) - } - - // Wait before sending. Give time to client to start reading - // before server starts sending. - time.Sleep(2 * time.Second) - h.t.Write(s, nil, resp, &Options{}) - // send the trailer to end the stream. - h.t.WriteStatus(s, status.New(codes.OK, "")) -} - -// start starts server. Other goroutines should block on s.readyChan for further operations. -func (s *server) start(t *testing.T, port int, serverConfig *ServerConfig, ht hType) { - var err error - if port == 0 { - s.lis, err = net.Listen("tcp", "localhost:0") - } else { - s.lis, err = net.Listen("tcp", "localhost:"+strconv.Itoa(port)) - } - if err != nil { - s.startedErr <- fmt.Errorf("failed to listen: %v", err) - return - } - _, p, err := net.SplitHostPort(s.lis.Addr().String()) - if err != nil { - s.startedErr <- fmt.Errorf("failed to parse listener address: %v", err) - return - } - s.port = p - s.conns = make(map[ServerTransport]bool) - s.startedErr <- nil - for { - conn, err := s.lis.Accept() - if err != nil { - return - } - transport, err := NewServerTransport("http2", conn, serverConfig) - if err != nil { - return - } - s.mu.Lock() - if s.conns == nil { - s.mu.Unlock() - transport.Close() - return - } - s.conns[transport] = true - h := &testStreamHandler{t: transport.(*http2Server)} - s.h = h - s.mu.Unlock() - switch ht { - case notifyCall: - go transport.HandleStreams(h.handleStreamAndNotify, - func(ctx context.Context, _ string) context.Context { - return ctx - }) - case suspended: - go transport.HandleStreams(func(*Stream) {}, // Do nothing to handle the stream. - func(ctx context.Context, method string) context.Context { - return ctx - }) - case misbehaved: - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamMisbehave(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - case encodingRequiredStatus: - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamEncodingRequiredStatus(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - case invalidHeaderField: - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamInvalidHeaderField(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - case delayRead: - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamDelayRead(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - case delayWrite: - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamDelayWrite(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - case pingpong: - go transport.HandleStreams(func(s *Stream) { - go h.handleStreamPingPong(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - default: - go transport.HandleStreams(func(s *Stream) { - go h.handleStream(t, s) - }, func(ctx context.Context, method string) context.Context { - return ctx - }) - } - } -} - -func (s *server) wait(t *testing.T, timeout time.Duration) { - select { - case err := <-s.startedErr: - if err != nil { - t.Fatal(err) - } - case <-time.After(timeout): - t.Fatalf("Timed out after %v waiting for server to be ready", timeout) - } -} - -func (s *server) stop() { - s.lis.Close() - s.mu.Lock() - for c := range s.conns { - c.Close() - } - s.conns = nil - s.mu.Unlock() -} - -func setUp(t *testing.T, port int, maxStreams uint32, ht hType) (*server, ClientTransport) { - return setUpWithOptions(t, port, &ServerConfig{MaxStreams: maxStreams}, ht, ConnectOptions{}) -} - -func setUpWithOptions(t *testing.T, port int, serverConfig *ServerConfig, ht hType, copts ConnectOptions) (*server, ClientTransport) { - server := &server{startedErr: make(chan error, 1)} - go server.start(t, port, serverConfig, ht) - server.wait(t, 2*time.Second) - addr := "localhost:" + server.port - var ( - ct ClientTransport - connErr error - ) - target := TargetInfo{ - Addr: addr, - } - ct, connErr = NewClientTransport(context.Background(), target, copts, 2*time.Second) - if connErr != nil { - t.Fatalf("failed to create transport: %v", connErr) - } - return server, ct -} - -func setUpWithNoPingServer(t *testing.T, copts ConnectOptions, done chan net.Conn) ClientTransport { - lis, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen: %v", err) - } - // Launch a non responsive server. - go func() { - defer lis.Close() - conn, err := lis.Accept() - if err != nil { - t.Errorf("Error at server-side while accepting: %v", err) - close(done) - return - } - done <- conn - }() - tr, err := NewClientTransport(context.Background(), TargetInfo{Addr: lis.Addr().String()}, copts, 2*time.Second) - if err != nil { - // Server clean-up. - lis.Close() - if conn, ok := <-done; ok { - conn.Close() - } - t.Fatalf("Failed to dial: %v", err) - } - return tr -} - -// TestInflightStreamClosing ensures that closing in-flight stream -// sends StreamError to concurrent stream reader. -func TestInflightStreamClosing(t *testing.T) { - serverConfig := &ServerConfig{} - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}) - defer server.stop() - defer client.Close() - - stream, err := client.NewStream(context.Background(), &CallHdr{}) - if err != nil { - t.Fatalf("Client failed to create RPC request: %v", err) - } - - donec := make(chan struct{}) - serr := StreamError{Desc: "client connection is closing"} - go func() { - defer close(donec) - if _, err := stream.Read(make([]byte, defaultWindowSize)); err != serr { - t.Errorf("unexpected Stream error %v, expected %v", err, serr) - } - }() - - // should unblock concurrent stream.Read - client.CloseStream(stream, serr) - - // wait for stream.Read error - timeout := time.NewTimer(5 * time.Second) - select { - case <-donec: - if !timeout.Stop() { - <-timeout.C - } - case <-timeout.C: - t.Fatalf("Test timed out, expected a StreamError.") - } -} - -// TestMaxConnectionIdle tests that a server will send GoAway to a idle client. -// An idle client is one who doesn't make any RPC calls for a duration of -// MaxConnectionIdle time. -func TestMaxConnectionIdle(t *testing.T) { - serverConfig := &ServerConfig{ - KeepaliveParams: keepalive.ServerParameters{ - MaxConnectionIdle: 2 * time.Second, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}) - defer server.stop() - defer client.Close() - stream, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Client failed to create RPC request: %v", err) - } - stream.mu.Lock() - stream.rstStream = true - stream.mu.Unlock() - client.CloseStream(stream, nil) - // wait for server to see that closed stream and max-age logic to send goaway after no new RPCs are mode - timeout := time.NewTimer(time.Second * 4) - select { - case <-client.GoAway(): - if !timeout.Stop() { - <-timeout.C - } - case <-timeout.C: - t.Fatalf("Test timed out, expected a GoAway from the server.") - } -} - -// TestMaxConenctionIdleNegative tests that a server will not send GoAway to a non-idle(busy) client. -func TestMaxConnectionIdleNegative(t *testing.T) { - serverConfig := &ServerConfig{ - KeepaliveParams: keepalive.ServerParameters{ - MaxConnectionIdle: 2 * time.Second, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}) - defer server.stop() - defer client.Close() - _, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Client failed to create RPC request: %v", err) - } - timeout := time.NewTimer(time.Second * 4) - select { - case <-client.GoAway(): - if !timeout.Stop() { - <-timeout.C - } - t.Fatalf("A non-idle client received a GoAway.") - case <-timeout.C: - } - -} - -// TestMaxConnectionAge tests that a server will send GoAway after a duration of MaxConnectionAge. -func TestMaxConnectionAge(t *testing.T) { - serverConfig := &ServerConfig{ - KeepaliveParams: keepalive.ServerParameters{ - MaxConnectionAge: 2 * time.Second, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}) - defer server.stop() - defer client.Close() - _, err := client.NewStream(context.Background(), &CallHdr{}) - if err != nil { - t.Fatalf("Client failed to create stream: %v", err) - } - // Wait for max-age logic to send GoAway. - timeout := time.NewTimer(4 * time.Second) - select { - case <-client.GoAway(): - if !timeout.Stop() { - <-timeout.C - } - case <-timeout.C: - t.Fatalf("Test timer out, expected a GoAway from the server.") - } -} - -// TestKeepaliveServer tests that a server closes connection with a client that doesn't respond to keepalive pings. -func TestKeepaliveServer(t *testing.T) { - serverConfig := &ServerConfig{ - KeepaliveParams: keepalive.ServerParameters{ - Time: 2 * time.Second, - Timeout: 1 * time.Second, - }, - } - server, c := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}) - defer server.stop() - defer c.Close() - client, err := net.Dial("tcp", server.lis.Addr().String()) - if err != nil { - t.Fatalf("Failed to dial: %v", err) - } - defer client.Close() - // Set read deadline on client conn so that it doesn't block forever in errorsome cases. - client.SetReadDeadline(time.Now().Add(10 * time.Second)) - // Wait for keepalive logic to close the connection. - time.Sleep(4 * time.Second) - b := make([]byte, 24) - for { - _, err = client.Read(b) - if err == nil { - continue - } - if err != io.EOF { - t.Fatalf("client.Read(_) = _,%v, want io.EOF", err) - } - break - } -} - -// TestKeepaliveServerNegative tests that a server doesn't close connection with a client that responds to keepalive pings. -func TestKeepaliveServerNegative(t *testing.T) { - serverConfig := &ServerConfig{ - KeepaliveParams: keepalive.ServerParameters{ - Time: 2 * time.Second, - Timeout: 1 * time.Second, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}) - defer server.stop() - defer client.Close() - // Give keepalive logic some time by sleeping. - time.Sleep(4 * time.Second) - // Assert that client is still active. - clientTr := client.(*http2Client) - clientTr.mu.Lock() - defer clientTr.mu.Unlock() - if clientTr.state != reachable { - t.Fatalf("Test failed: Expected server-client connection to be healthy.") - } -} - -func TestKeepaliveClientClosesIdleTransport(t *testing.T) { - done := make(chan net.Conn, 1) - tr := setUpWithNoPingServer(t, ConnectOptions{KeepaliveParams: keepalive.ClientParameters{ - Time: 2 * time.Second, // Keepalive time = 2 sec. - Timeout: 1 * time.Second, // Keepalive timeout = 1 sec. - PermitWithoutStream: true, // Run keepalive even with no RPCs. - }}, done) - defer tr.Close() - conn, ok := <-done - if !ok { - t.Fatalf("Server didn't return connection object") - } - defer conn.Close() - // Sleep for keepalive to close the connection. - time.Sleep(4 * time.Second) - // Assert that the connection was closed. - ct := tr.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state == reachable { - t.Fatalf("Test Failed: Expected client transport to have closed.") - } -} - -func TestKeepaliveClientStaysHealthyOnIdleTransport(t *testing.T) { - done := make(chan net.Conn, 1) - tr := setUpWithNoPingServer(t, ConnectOptions{KeepaliveParams: keepalive.ClientParameters{ - Time: 2 * time.Second, // Keepalive time = 2 sec. - Timeout: 1 * time.Second, // Keepalive timeout = 1 sec. - }}, done) - defer tr.Close() - conn, ok := <-done - if !ok { - t.Fatalf("server didn't reutrn connection object") - } - defer conn.Close() - // Give keepalive some time. - time.Sleep(4 * time.Second) - // Assert that connections is still healthy. - ct := tr.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state != reachable { - t.Fatalf("Test failed: Expected client transport to be healthy.") - } -} - -func TestKeepaliveClientClosesWithActiveStreams(t *testing.T) { - done := make(chan net.Conn, 1) - tr := setUpWithNoPingServer(t, ConnectOptions{KeepaliveParams: keepalive.ClientParameters{ - Time: 2 * time.Second, // Keepalive time = 2 sec. - Timeout: 1 * time.Second, // Keepalive timeout = 1 sec. - }}, done) - defer tr.Close() - conn, ok := <-done - if !ok { - t.Fatalf("Server didn't return connection object") - } - defer conn.Close() - // Create a stream. - _, err := tr.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Failed to create a new stream: %v", err) - } - // Give keepalive some time. - time.Sleep(4 * time.Second) - // Assert that transport was closed. - ct := tr.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state == reachable { - t.Fatalf("Test failed: Expected client transport to have closed.") - } -} - -func TestKeepaliveClientStaysHealthyWithResponsiveServer(t *testing.T) { - s, tr := setUpWithOptions(t, 0, &ServerConfig{MaxStreams: math.MaxUint32}, normal, ConnectOptions{KeepaliveParams: keepalive.ClientParameters{ - Time: 2 * time.Second, // Keepalive time = 2 sec. - Timeout: 1 * time.Second, // Keepalive timeout = 1 sec. - PermitWithoutStream: true, // Run keepalive even with no RPCs. - }}) - defer s.stop() - defer tr.Close() - // Give keep alive some time. - time.Sleep(4 * time.Second) - // Assert that transport is healthy. - ct := tr.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state != reachable { - t.Fatalf("Test failed: Expected client transport to be healthy.") - } -} - -func TestKeepaliveServerEnforcementWithAbusiveClientNoRPC(t *testing.T) { - serverConfig := &ServerConfig{ - KeepalivePolicy: keepalive.EnforcementPolicy{ - MinTime: 2 * time.Second, - }, - } - clientOptions := ConnectOptions{ - KeepaliveParams: keepalive.ClientParameters{ - Time: 50 * time.Millisecond, - Timeout: 50 * time.Millisecond, - PermitWithoutStream: true, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, normal, clientOptions) - defer server.stop() - defer client.Close() - - timeout := time.NewTimer(2 * time.Second) - select { - case <-client.GoAway(): - if !timeout.Stop() { - <-timeout.C - } - case <-timeout.C: - t.Fatalf("Test failed: Expected a GoAway from server.") - } - time.Sleep(500 * time.Millisecond) - ct := client.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state == reachable { - t.Fatalf("Test failed: Expected the connection to be closed.") - } -} - -func TestKeepaliveServerEnforcementWithAbusiveClientWithRPC(t *testing.T) { - serverConfig := &ServerConfig{ - KeepalivePolicy: keepalive.EnforcementPolicy{ - MinTime: 2 * time.Second, - }, - } - clientOptions := ConnectOptions{ - KeepaliveParams: keepalive.ClientParameters{ - Time: 50 * time.Millisecond, - Timeout: 50 * time.Millisecond, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, clientOptions) - defer server.stop() - defer client.Close() - - if _, err := client.NewStream(context.Background(), &CallHdr{Flush: true}); err != nil { - t.Fatalf("Client failed to create stream.") - } - timeout := time.NewTimer(2 * time.Second) - select { - case <-client.GoAway(): - if !timeout.Stop() { - <-timeout.C - } - case <-timeout.C: - t.Fatalf("Test failed: Expected a GoAway from server.") - } - time.Sleep(500 * time.Millisecond) - ct := client.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state == reachable { - t.Fatalf("Test failed: Expected the connection to be closed.") - } -} - -func TestKeepaliveServerEnforcementWithObeyingClientNoRPC(t *testing.T) { - serverConfig := &ServerConfig{ - KeepalivePolicy: keepalive.EnforcementPolicy{ - MinTime: 100 * time.Millisecond, - PermitWithoutStream: true, - }, - } - clientOptions := ConnectOptions{ - KeepaliveParams: keepalive.ClientParameters{ - Time: 101 * time.Millisecond, - Timeout: 50 * time.Millisecond, - PermitWithoutStream: true, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, normal, clientOptions) - defer server.stop() - defer client.Close() - - // Give keepalive enough time. - time.Sleep(2 * time.Second) - // Assert that connection is healthy. - ct := client.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state != reachable { - t.Fatalf("Test failed: Expected connection to be healthy.") - } -} - -func TestKeepaliveServerEnforcementWithObeyingClientWithRPC(t *testing.T) { - serverConfig := &ServerConfig{ - KeepalivePolicy: keepalive.EnforcementPolicy{ - MinTime: 100 * time.Millisecond, - }, - } - clientOptions := ConnectOptions{ - KeepaliveParams: keepalive.ClientParameters{ - Time: 101 * time.Millisecond, - Timeout: 50 * time.Millisecond, - }, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, clientOptions) - defer server.stop() - defer client.Close() - - if _, err := client.NewStream(context.Background(), &CallHdr{Flush: true}); err != nil { - t.Fatalf("Client failed to create stream.") - } - - // Give keepalive enough time. - time.Sleep(2 * time.Second) - // Assert that connection is healthy. - ct := client.(*http2Client) - ct.mu.Lock() - defer ct.mu.Unlock() - if ct.state != reachable { - t.Fatalf("Test failed: Expected connection to be healthy.") - } -} - -func TestClientSendAndReceive(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, normal) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Small", - } - s1, err1 := ct.NewStream(context.Background(), callHdr) - if err1 != nil { - t.Fatalf("failed to open stream: %v", err1) - } - if s1.id != 1 { - t.Fatalf("wrong stream id: %d", s1.id) - } - s2, err2 := ct.NewStream(context.Background(), callHdr) - if err2 != nil { - t.Fatalf("failed to open stream: %v", err2) - } - if s2.id != 3 { - t.Fatalf("wrong stream id: %d", s2.id) - } - opts := Options{ - Last: true, - Delay: false, - } - if err := ct.Write(s1, nil, expectedRequest, &opts); err != nil && err != io.EOF { - t.Fatalf("failed to send data: %v", err) - } - p := make([]byte, len(expectedResponse)) - _, recvErr := s1.Read(p) - if recvErr != nil || !bytes.Equal(p, expectedResponse) { - t.Fatalf("Error: %v, want <nil>; Result: %v, want %v", recvErr, p, expectedResponse) - } - _, recvErr = s1.Read(p) - if recvErr != io.EOF { - t.Fatalf("Error: %v; want <EOF>", recvErr) - } - ct.Close() - server.stop() -} - -func TestClientErrorNotify(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, normal) - go server.stop() - // ct.reader should detect the error and activate ct.Error(). - <-ct.Error() - ct.Close() -} - -func performOneRPC(ct ClientTransport) { - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Small", - } - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - return - } - opts := Options{ - Last: true, - Delay: false, - } - if err := ct.Write(s, []byte{}, expectedRequest, &opts); err == nil || err == io.EOF { - time.Sleep(5 * time.Millisecond) - // The following s.Recv()'s could error out because the - // underlying transport is gone. - // - // Read response - p := make([]byte, len(expectedResponse)) - s.Read(p) - // Read io.EOF - s.Read(p) - } -} - -func TestClientMix(t *testing.T) { - s, ct := setUp(t, 0, math.MaxUint32, normal) - go func(s *server) { - time.Sleep(5 * time.Second) - s.stop() - }(s) - go func(ct ClientTransport) { - <-ct.Error() - ct.Close() - }(ct) - for i := 0; i < 1000; i++ { - time.Sleep(10 * time.Millisecond) - go performOneRPC(ct) - } -} - -func TestLargeMessage(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, normal) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Large", - } - var wg sync.WaitGroup - for i := 0; i < 2; i++ { - wg.Add(1) - go func() { - defer wg.Done() - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Errorf("%v.NewStream(_, _) = _, %v, want _, <nil>", ct, err) - } - if err := ct.Write(s, []byte{}, expectedRequestLarge, &Options{Last: true, Delay: false}); err != nil && err != io.EOF { - t.Errorf("%v.Write(_, _, _) = %v, want <nil>", ct, err) - } - p := make([]byte, len(expectedResponseLarge)) - if _, err := s.Read(p); err != nil || !bytes.Equal(p, expectedResponseLarge) { - t.Errorf("s.Read(%v) = _, %v, want %v, <nil>", err, p, expectedResponse) - } - if _, err = s.Read(p); err != io.EOF { - t.Errorf("Failed to complete the stream %v; want <EOF>", err) - } - }() - } - wg.Wait() - ct.Close() - server.stop() -} - -func TestLargeMessageWithDelayRead(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, delayRead) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Large", - } - var wg sync.WaitGroup - for i := 0; i < 2; i++ { - wg.Add(1) - go func() { - defer wg.Done() - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Errorf("%v.NewStream(_, _) = _, %v, want _, <nil>", ct, err) - } - if err := ct.Write(s, []byte{}, expectedRequestLarge, &Options{Last: true, Delay: false}); err != nil && err != io.EOF { - t.Errorf("%v.Write(_, _, _) = %v, want <nil>", ct, err) - } - p := make([]byte, len(expectedResponseLarge)) - - // Give time to server to begin sending before client starts reading. - time.Sleep(2 * time.Second) - if _, err := s.Read(p); err != nil || !bytes.Equal(p, expectedResponseLarge) { - t.Errorf("s.Read(_) = _, %v, want _, <nil>", err) - } - if _, err = s.Read(p); err != io.EOF { - t.Errorf("Failed to complete the stream %v; want <EOF>", err) - } - }() - } - wg.Wait() - ct.Close() - server.stop() -} - -func TestLargeMessageDelayWrite(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, delayWrite) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Large", - } - var wg sync.WaitGroup - for i := 0; i < 2; i++ { - wg.Add(1) - go func() { - defer wg.Done() - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Errorf("%v.NewStream(_, _) = _, %v, want _, <nil>", ct, err) - } - - // Give time to server to start reading before client starts sending. - time.Sleep(2 * time.Second) - if err := ct.Write(s, []byte{}, expectedRequestLarge, &Options{Last: true, Delay: false}); err != nil && err != io.EOF { - t.Errorf("%v.Write(_, _, _) = %v, want <nil>", ct, err) - } - p := make([]byte, len(expectedResponseLarge)) - if _, err := s.Read(p); err != nil || !bytes.Equal(p, expectedResponseLarge) { - t.Errorf("io.ReadFull(%v) = _, %v, want %v, <nil>", err, p, expectedResponse) - } - if _, err = s.Read(p); err != io.EOF { - t.Errorf("Failed to complete the stream %v; want <EOF>", err) - } - }() - } - wg.Wait() - ct.Close() - server.stop() -} - -func TestGracefulClose(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, normal) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Small", - } - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Fatalf("%v.NewStream(_, _) = _, %v, want _, <nil>", ct, err) - } - if err = ct.GracefulClose(); err != nil { - t.Fatalf("%v.GracefulClose() = %v, want <nil>", ct, err) - } - var wg sync.WaitGroup - // Expect the failure for all the follow-up streams because ct has been closed gracefully. - for i := 0; i < 100; i++ { - wg.Add(1) - go func() { - defer wg.Done() - if _, err := ct.NewStream(context.Background(), callHdr); err != ErrStreamDrain { - t.Errorf("%v.NewStream(_, _) = _, %v, want _, %v", ct, err, ErrStreamDrain) - } - }() - } - opts := Options{ - Last: true, - Delay: false, - } - // The stream which was created before graceful close can still proceed. - if err := ct.Write(s, nil, expectedRequest, &opts); err != nil && err != io.EOF { - t.Fatalf("%v.Write(_, _, _) = %v, want <nil>", ct, err) - } - p := make([]byte, len(expectedResponse)) - if _, err := s.Read(p); err != nil || !bytes.Equal(p, expectedResponse) { - t.Fatalf("s.Read(%v) = _, %v, want %v, <nil>", err, p, expectedResponse) - } - if _, err = s.Read(p); err != io.EOF { - t.Fatalf("Failed to complete the stream %v; want <EOF>", err) - } - wg.Wait() - ct.Close() - server.stop() -} - -func TestLargeMessageSuspension(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, suspended) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Large", - } - // Set a long enough timeout for writing a large message out. - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - defer cancel() - s, err := ct.NewStream(ctx, callHdr) - if err != nil { - t.Fatalf("failed to open stream: %v", err) - } - // Write should not be done successfully due to flow control. - msg := make([]byte, initialWindowSize*8) - err = ct.Write(s, nil, msg, &Options{Last: true, Delay: false}) - expectedErr := streamErrorf(codes.DeadlineExceeded, "%v", context.DeadlineExceeded) - if err != expectedErr { - t.Fatalf("Write got %v, want %v", err, expectedErr) - } - ct.Close() - server.stop() -} - -func TestMaxStreams(t *testing.T) { - server, ct := setUp(t, 0, 1, suspended) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Large", - } - // Have a pending stream which takes all streams quota. - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Fatalf("Failed to open stream: %v", err) - } - cc, ok := ct.(*http2Client) - if !ok { - t.Fatalf("Failed to convert %v to *http2Client", ct) - } - done := make(chan struct{}) - ch := make(chan int) - ready := make(chan struct{}) - go func() { - for { - select { - case <-time.After(5 * time.Millisecond): - select { - case ch <- 0: - case <-ready: - return - } - case <-time.After(5 * time.Second): - close(done) - return - case <-ready: - return - } - } - }() - for { - select { - case <-ch: - case <-done: - t.Fatalf("Client has not received the max stream setting in 5 seconds.") - } - cc.mu.Lock() - // cc.maxStreams should be equal to 1 after having received settings frame from - // server. - if cc.maxStreams == 1 { - cc.mu.Unlock() - select { - case <-cc.streamsQuota.acquire(): - t.Fatalf("streamsQuota.acquire() becomes readable mistakenly.") - default: - cc.streamsQuota.mu.Lock() - quota := cc.streamsQuota.quota - cc.streamsQuota.mu.Unlock() - if quota != 0 { - t.Fatalf("streamsQuota.quota got non-zero quota mistakenly.") - } - } - break - } - cc.mu.Unlock() - } - close(ready) - // Close the pending stream so that the streams quota becomes available for the next new stream. - ct.CloseStream(s, nil) - select { - case i := <-cc.streamsQuota.acquire(): - if i != 1 { - t.Fatalf("streamsQuota.acquire() got %d quota, want 1.", i) - } - cc.streamsQuota.add(i) - default: - t.Fatalf("streamsQuota.acquire() is not readable.") - } - if _, err := ct.NewStream(context.Background(), callHdr); err != nil { - t.Fatalf("Failed to open stream: %v", err) - } - ct.Close() - server.stop() -} - -func TestServerContextCanceledOnClosedConnection(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, suspended) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo", - } - var sc *http2Server - // Wait until the server transport is setup. - for { - server.mu.Lock() - if len(server.conns) == 0 { - server.mu.Unlock() - time.Sleep(time.Millisecond) - continue - } - for k := range server.conns { - var ok bool - sc, ok = k.(*http2Server) - if !ok { - t.Fatalf("Failed to convert %v to *http2Server", k) - } - } - server.mu.Unlock() - break - } - cc, ok := ct.(*http2Client) - if !ok { - t.Fatalf("Failed to convert %v to *http2Client", ct) - } - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Fatalf("Failed to open stream: %v", err) - } - cc.controlBuf.put(&dataFrame{s.id, false, make([]byte, http2MaxFrameLen), func() {}}) - // Loop until the server side stream is created. - var ss *Stream - for { - time.Sleep(time.Second) - sc.mu.Lock() - if len(sc.activeStreams) == 0 { - sc.mu.Unlock() - continue - } - ss = sc.activeStreams[s.id] - sc.mu.Unlock() - break - } - cc.Close() - select { - case <-ss.Context().Done(): - if ss.Context().Err() != context.Canceled { - t.Fatalf("ss.Context().Err() got %v, want %v", ss.Context().Err(), context.Canceled) - } - case <-time.After(5 * time.Second): - t.Fatalf("Failed to cancel the context of the sever side stream.") - } - server.stop() -} - -func TestClientConnDecoupledFromApplicationRead(t *testing.T) { - connectOptions := ConnectOptions{ - InitialWindowSize: defaultWindowSize, - InitialConnWindowSize: defaultWindowSize, - } - server, client := setUpWithOptions(t, 0, &ServerConfig{}, notifyCall, connectOptions) - defer server.stop() - defer client.Close() - - waitWhileTrue(t, func() (bool, error) { - server.mu.Lock() - defer server.mu.Unlock() - - if len(server.conns) == 0 { - return true, fmt.Errorf("timed-out while waiting for connection to be created on the server") - } - return false, nil - }) - - var st *http2Server - server.mu.Lock() - for k := range server.conns { - st = k.(*http2Server) - } - notifyChan := make(chan struct{}) - server.h.notify = notifyChan - server.mu.Unlock() - cstream1, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Client failed to create first stream. Err: %v", err) - } - - <-notifyChan - var sstream1 *Stream - // Access stream on the server. - st.mu.Lock() - for _, v := range st.activeStreams { - if v.id == cstream1.id { - sstream1 = v - } - } - st.mu.Unlock() - if sstream1 == nil { - t.Fatalf("Didn't find stream corresponding to client cstream.id: %v on the server", cstream1.id) - } - // Exhaust client's connection window. - if err := st.Write(sstream1, []byte{}, make([]byte, defaultWindowSize), &Options{}); err != nil { - t.Fatalf("Server failed to write data. Err: %v", err) - } - notifyChan = make(chan struct{}) - server.mu.Lock() - server.h.notify = notifyChan - server.mu.Unlock() - // Create another stream on client. - cstream2, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Client failed to create second stream. Err: %v", err) - } - <-notifyChan - var sstream2 *Stream - st.mu.Lock() - for _, v := range st.activeStreams { - if v.id == cstream2.id { - sstream2 = v - } - } - st.mu.Unlock() - if sstream2 == nil { - t.Fatalf("Didn't find stream corresponding to client cstream.id: %v on the server", cstream2.id) - } - // Server should be able to send data on the new stream, even though the client hasn't read anything on the first stream. - if err := st.Write(sstream2, []byte{}, make([]byte, defaultWindowSize), &Options{}); err != nil { - t.Fatalf("Server failed to write data. Err: %v", err) - } - - // Client should be able to read data on second stream. - if _, err := cstream2.Read(make([]byte, defaultWindowSize)); err != nil { - t.Fatalf("_.Read(_) = _, %v, want _, <nil>", err) - } - - // Client should be able to read data on first stream. - if _, err := cstream1.Read(make([]byte, defaultWindowSize)); err != nil { - t.Fatalf("_.Read(_) = _, %v, want _, <nil>", err) - } -} - -func TestServerConnDecoupledFromApplicationRead(t *testing.T) { - serverConfig := &ServerConfig{ - InitialWindowSize: defaultWindowSize, - InitialConnWindowSize: defaultWindowSize, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, ConnectOptions{}) - defer server.stop() - defer client.Close() - waitWhileTrue(t, func() (bool, error) { - server.mu.Lock() - defer server.mu.Unlock() - - if len(server.conns) == 0 { - return true, fmt.Errorf("timed-out while waiting for connection to be created on the server") - } - return false, nil - }) - var st *http2Server - server.mu.Lock() - for k := range server.conns { - st = k.(*http2Server) - } - server.mu.Unlock() - cstream1, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Failed to create 1st stream. Err: %v", err) - } - // Exhaust server's connection window. - if err := client.Write(cstream1, nil, make([]byte, defaultWindowSize), &Options{Last: true}); err != nil { - t.Fatalf("Client failed to write data. Err: %v", err) - } - //Client should be able to create another stream and send data on it. - cstream2, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Failed to create 2nd stream. Err: %v", err) - } - if err := client.Write(cstream2, nil, make([]byte, defaultWindowSize), &Options{}); err != nil { - t.Fatalf("Client failed to write data. Err: %v", err) - } - // Get the streams on server. - waitWhileTrue(t, func() (bool, error) { - st.mu.Lock() - defer st.mu.Unlock() - - if len(st.activeStreams) != 2 { - return true, fmt.Errorf("timed-out while waiting for server to have created the streams") - } - return false, nil - }) - var sstream1 *Stream - st.mu.Lock() - for _, v := range st.activeStreams { - if v.id == 1 { - sstream1 = v - } - } - st.mu.Unlock() - // Trying to write more on a max-ed out stream should result in a RST_STREAM from the server. - ct := client.(*http2Client) - ct.controlBuf.put(&dataFrame{cstream2.id, true, make([]byte, 1), func() {}}) - code := http2ErrConvTab[http2.ErrCodeFlowControl] - waitWhileTrue(t, func() (bool, error) { - cstream2.mu.Lock() - defer cstream2.mu.Unlock() - if cstream2.status.Code() != code { - return true, fmt.Errorf("want code = %v, got %v", code, cstream2.status.Code()) - } - return false, nil - }) - // Reading from the stream on server should succeed. - if _, err := sstream1.Read(make([]byte, defaultWindowSize)); err != nil { - t.Fatalf("_.Read(_) = %v, want <nil>", err) - } - - if _, err := sstream1.Read(make([]byte, 1)); err != io.EOF { - t.Fatalf("_.Read(_) = %v, want io.EOF", err) - } - -} - -func TestServerWithMisbehavedClient(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, suspended) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo", - } - var sc *http2Server - // Wait until the server transport is setup. - for { - server.mu.Lock() - if len(server.conns) == 0 { - server.mu.Unlock() - time.Sleep(time.Millisecond) - continue - } - for k := range server.conns { - var ok bool - sc, ok = k.(*http2Server) - if !ok { - t.Fatalf("Failed to convert %v to *http2Server", k) - } - } - server.mu.Unlock() - break - } - cc, ok := ct.(*http2Client) - if !ok { - t.Fatalf("Failed to convert %v to *http2Client", ct) - } - // Test server behavior for violation of stream flow control window size restriction. - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Fatalf("Failed to open stream: %v", err) - } - var sent int - // Drain the stream flow control window - cc.controlBuf.put(&dataFrame{s.id, false, make([]byte, http2MaxFrameLen), func() {}}) - sent += http2MaxFrameLen - // Wait until the server creates the corresponding stream and receive some data. - var ss *Stream - for { - time.Sleep(time.Millisecond) - sc.mu.Lock() - if len(sc.activeStreams) == 0 { - sc.mu.Unlock() - continue - } - ss = sc.activeStreams[s.id] - sc.mu.Unlock() - ss.fc.mu.Lock() - if ss.fc.pendingData > 0 { - ss.fc.mu.Unlock() - break - } - ss.fc.mu.Unlock() - } - if ss.fc.pendingData != http2MaxFrameLen || ss.fc.pendingUpdate != 0 || sc.fc.pendingData != 0 || sc.fc.pendingUpdate != 0 { - t.Fatalf("Server mistakenly updates inbound flow control params: got %d, %d, %d, %d; want %d, %d, %d, %d", ss.fc.pendingData, ss.fc.pendingUpdate, sc.fc.pendingData, sc.fc.pendingUpdate, http2MaxFrameLen, 0, 0, 0) - } - // Keep sending until the server inbound window is drained for that stream. - for sent <= initialWindowSize { - cc.controlBuf.put(&dataFrame{s.id, false, make([]byte, 1), func() {}}) - sent++ - } - // Server sent a resetStream for s already. - code := http2ErrConvTab[http2.ErrCodeFlowControl] - if _, err := s.Read(make([]byte, 1)); err != io.EOF { - t.Fatalf("%v got err %v want <EOF>", s, err) - } - if s.status.Code() != code { - t.Fatalf("%v got status %v; want Code=%v", s, s.status, code) - } - - ct.CloseStream(s, nil) - ct.Close() - server.stop() -} - -func TestClientWithMisbehavedServer(t *testing.T) { - // Turn off BDP estimation so that the server can - // violate stream window. - connectOptions := ConnectOptions{ - InitialWindowSize: initialWindowSize, - } - server, ct := setUpWithOptions(t, 0, &ServerConfig{}, misbehaved, connectOptions) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo.Stream", - } - conn, ok := ct.(*http2Client) - if !ok { - t.Fatalf("Failed to convert %v to *http2Client", ct) - } - // Test the logic for the violation of stream flow control window size restriction. - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - t.Fatalf("Failed to open stream: %v", err) - } - d := make([]byte, 1) - if err := ct.Write(s, nil, d, &Options{Last: true, Delay: false}); err != nil && err != io.EOF { - t.Fatalf("Failed to write: %v", err) - } - // Read without window update. - for { - p := make([]byte, http2MaxFrameLen) - if _, err = s.trReader.(*transportReader).reader.Read(p); err != nil { - break - } - } - if s.fc.pendingData <= initialWindowSize || s.fc.pendingUpdate != 0 || conn.fc.pendingData != 0 || conn.fc.pendingUpdate != 0 { - t.Fatalf("Client mistakenly updates inbound flow control params: got %d, %d, %d, %d; want >%d, %d, %d, >%d", s.fc.pendingData, s.fc.pendingUpdate, conn.fc.pendingData, conn.fc.pendingUpdate, initialWindowSize, 0, 0, 0) - } - - if err != io.EOF { - t.Fatalf("Got err %v, want <EOF>", err) - } - if s.status.Code() != codes.Internal { - t.Fatalf("Got s.status %v, want s.status.Code()=Internal", s.status) - } - - conn.CloseStream(s, err) - ct.Close() - server.stop() -} - -var encodingTestStatus = status.New(codes.Internal, "\n") - -func TestEncodingRequiredStatus(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, encodingRequiredStatus) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo", - } - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - return - } - opts := Options{ - Last: true, - Delay: false, - } - if err := ct.Write(s, nil, expectedRequest, &opts); err != nil && err != io.EOF { - t.Fatalf("Failed to write the request: %v", err) - } - p := make([]byte, http2MaxFrameLen) - if _, err := s.trReader.(*transportReader).Read(p); err != io.EOF { - t.Fatalf("Read got error %v, want %v", err, io.EOF) - } - if !reflect.DeepEqual(s.Status(), encodingTestStatus) { - t.Fatalf("stream with status %v, want %v", s.Status(), encodingTestStatus) - } - ct.Close() - server.stop() -} - -func TestInvalidHeaderField(t *testing.T) { - server, ct := setUp(t, 0, math.MaxUint32, invalidHeaderField) - callHdr := &CallHdr{ - Host: "localhost", - Method: "foo", - } - s, err := ct.NewStream(context.Background(), callHdr) - if err != nil { - return - } - opts := Options{ - Last: true, - Delay: false, - } - if err := ct.Write(s, nil, expectedRequest, &opts); err != nil && err != io.EOF { - t.Fatalf("Failed to write the request: %v", err) - } - p := make([]byte, http2MaxFrameLen) - _, err = s.trReader.(*transportReader).Read(p) - if se, ok := err.(StreamError); !ok || se.Code != codes.FailedPrecondition || !strings.Contains(err.Error(), expectedInvalidHeaderField) { - t.Fatalf("Read got error %v, want error with code %s and contains %q", err, codes.FailedPrecondition, expectedInvalidHeaderField) - } - ct.Close() - server.stop() -} - -func TestStreamContext(t *testing.T) { - expectedStream := &Stream{} - ctx := newContextWithStream(context.Background(), expectedStream) - s, ok := StreamFromContext(ctx) - if !ok || expectedStream != s { - t.Fatalf("GetStreamFromContext(%v) = %v, %t, want: %v, true", ctx, s, ok, expectedStream) - } -} - -func TestIsReservedHeader(t *testing.T) { - tests := []struct { - h string - want bool - }{ - {"", false}, // but should be rejected earlier - {"foo", false}, - {"content-type", true}, - {"grpc-message-type", true}, - {"grpc-encoding", true}, - {"grpc-message", true}, - {"grpc-status", true}, - {"grpc-timeout", true}, - {"te", true}, - } - for _, tt := range tests { - got := isReservedHeader(tt.h) - if got != tt.want { - t.Errorf("isReservedHeader(%q) = %v; want %v", tt.h, got, tt.want) - } - } -} - -func TestContextErr(t *testing.T) { - for _, test := range []struct { - // input - errIn error - // outputs - errOut StreamError - }{ - {context.DeadlineExceeded, StreamError{codes.DeadlineExceeded, context.DeadlineExceeded.Error()}}, - {context.Canceled, StreamError{codes.Canceled, context.Canceled.Error()}}, - } { - err := ContextErr(test.errIn) - if err != test.errOut { - t.Fatalf("ContextErr{%v} = %v \nwant %v", test.errIn, err, test.errOut) - } - } -} - -func max(a, b int32) int32 { - if a > b { - return a - } - return b -} - -type windowSizeConfig struct { - serverStream int32 - serverConn int32 - clientStream int32 - clientConn int32 -} - -func TestAccountCheckWindowSizeWithLargeWindow(t *testing.T) { - wc := windowSizeConfig{ - serverStream: 10 * 1024 * 1024, - serverConn: 12 * 1024 * 1024, - clientStream: 6 * 1024 * 1024, - clientConn: 8 * 1024 * 1024, - } - testAccountCheckWindowSize(t, wc) -} - -func TestAccountCheckWindowSizeWithSmallWindow(t *testing.T) { - wc := windowSizeConfig{ - serverStream: defaultWindowSize, - // Note this is smaller than initialConnWindowSize which is the current default. - serverConn: defaultWindowSize, - clientStream: defaultWindowSize, - clientConn: defaultWindowSize, - } - testAccountCheckWindowSize(t, wc) -} - -func testAccountCheckWindowSize(t *testing.T, wc windowSizeConfig) { - serverConfig := &ServerConfig{ - InitialWindowSize: wc.serverStream, - InitialConnWindowSize: wc.serverConn, - } - connectOptions := ConnectOptions{ - InitialWindowSize: wc.clientStream, - InitialConnWindowSize: wc.clientConn, - } - server, client := setUpWithOptions(t, 0, serverConfig, suspended, connectOptions) - defer server.stop() - defer client.Close() - - // Wait for server conns to be populated with new server transport. - waitWhileTrue(t, func() (bool, error) { - server.mu.Lock() - defer server.mu.Unlock() - if len(server.conns) == 0 { - return true, fmt.Errorf("timed out waiting for server transport to be created") - } - return false, nil - }) - var st *http2Server - server.mu.Lock() - for k := range server.conns { - st = k.(*http2Server) - } - server.mu.Unlock() - ct := client.(*http2Client) - cstream, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Failed to create stream. Err: %v", err) - } - // Wait for server to receive headers. - waitWhileTrue(t, func() (bool, error) { - st.mu.Lock() - defer st.mu.Unlock() - if len(st.activeStreams) == 0 { - return true, fmt.Errorf("timed out waiting for server to receive headers") - } - return false, nil - }) - // Sleeping to make sure the settings are applied in case of negative test. - time.Sleep(time.Second) - - waitWhileTrue(t, func() (bool, error) { - st.fc.mu.Lock() - lim := st.fc.limit - st.fc.mu.Unlock() - if lim != uint32(serverConfig.InitialConnWindowSize) { - return true, fmt.Errorf("Server transport flow control window size: got %v, want %v", lim, serverConfig.InitialConnWindowSize) - } - return false, nil - }) - - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - serverSendQuota, err := wait(ctx, context.Background(), nil, nil, st.sendQuotaPool.acquire()) - if err != nil { - t.Fatalf("Error while acquiring sendQuota on server. Err: %v", err) - } - cancel() - st.sendQuotaPool.add(serverSendQuota) - if serverSendQuota != int(connectOptions.InitialConnWindowSize) { - t.Fatalf("Server send quota(%v) not equal to client's window size(%v) on conn.", serverSendQuota, connectOptions.InitialConnWindowSize) - } - st.mu.Lock() - ssq := st.streamSendQuota - st.mu.Unlock() - if ssq != uint32(connectOptions.InitialWindowSize) { - t.Fatalf("Server stream send quota(%v) not equal to client's window size(%v) on stream.", ssq, connectOptions.InitialWindowSize) - } - ct.fc.mu.Lock() - limit := ct.fc.limit - ct.fc.mu.Unlock() - if limit != uint32(connectOptions.InitialConnWindowSize) { - t.Fatalf("Client transport flow control window size is %v, want %v", limit, connectOptions.InitialConnWindowSize) - } - ctx, cancel = context.WithTimeout(context.Background(), time.Second) - clientSendQuota, err := wait(ctx, context.Background(), nil, nil, ct.sendQuotaPool.acquire()) - if err != nil { - t.Fatalf("Error while acquiring sendQuota on client. Err: %v", err) - } - cancel() - ct.sendQuotaPool.add(clientSendQuota) - if clientSendQuota != int(serverConfig.InitialConnWindowSize) { - t.Fatalf("Client send quota(%v) not equal to server's window size(%v) on conn.", clientSendQuota, serverConfig.InitialConnWindowSize) - } - ct.mu.Lock() - ssq = ct.streamSendQuota - ct.mu.Unlock() - if ssq != uint32(serverConfig.InitialWindowSize) { - t.Fatalf("Client stream send quota(%v) not equal to server's window size(%v) on stream.", ssq, serverConfig.InitialWindowSize) - } - cstream.fc.mu.Lock() - limit = cstream.fc.limit - cstream.fc.mu.Unlock() - if limit != uint32(connectOptions.InitialWindowSize) { - t.Fatalf("Client stream flow control window size is %v, want %v", limit, connectOptions.InitialWindowSize) - } - var sstream *Stream - st.mu.Lock() - for _, v := range st.activeStreams { - sstream = v - } - st.mu.Unlock() - sstream.fc.mu.Lock() - limit = sstream.fc.limit - sstream.fc.mu.Unlock() - if limit != uint32(serverConfig.InitialWindowSize) { - t.Fatalf("Server stream flow control window size is %v, want %v", limit, serverConfig.InitialWindowSize) - } -} - -// Check accounting on both sides after sending and receiving large messages. -func TestAccountCheckExpandingWindow(t *testing.T) { - server, client := setUp(t, 0, 0, pingpong) - defer server.stop() - defer client.Close() - waitWhileTrue(t, func() (bool, error) { - server.mu.Lock() - defer server.mu.Unlock() - if len(server.conns) == 0 { - return true, fmt.Errorf("timed out while waiting for server transport to be created") - } - return false, nil - }) - var st *http2Server - server.mu.Lock() - for k := range server.conns { - st = k.(*http2Server) - } - server.mu.Unlock() - ct := client.(*http2Client) - cstream, err := client.NewStream(context.Background(), &CallHdr{Flush: true}) - if err != nil { - t.Fatalf("Failed to create stream. Err: %v", err) - } - - msgSize := 65535 * 16 * 2 - msg := make([]byte, msgSize) - buf := make([]byte, msgSize+5) - buf[0] = byte(0) - binary.BigEndian.PutUint32(buf[1:], uint32(msgSize)) - copy(buf[5:], msg) - opts := Options{} - header := make([]byte, 5) - for i := 1; i <= 10; i++ { - if err := ct.Write(cstream, nil, buf, &opts); err != nil { - t.Fatalf("Error on client while writing message: %v", err) - } - if _, err := cstream.Read(header); err != nil { - t.Fatalf("Error on client while reading data frame header: %v", err) - } - sz := binary.BigEndian.Uint32(header[1:]) - recvMsg := make([]byte, int(sz)) - if _, err := cstream.Read(recvMsg); err != nil { - t.Fatalf("Error on client while reading data: %v", err) - } - if len(recvMsg) != len(msg) { - t.Fatalf("Length of message received by client: %v, want: %v", len(recvMsg), len(msg)) - } - } - var sstream *Stream - st.mu.Lock() - for _, v := range st.activeStreams { - sstream = v - } - st.mu.Unlock() - - waitWhileTrue(t, func() (bool, error) { - // Check that pendingData and delta on flow control windows on both sides are 0. - cstream.fc.mu.Lock() - if cstream.fc.delta != 0 { - cstream.fc.mu.Unlock() - return true, fmt.Errorf("delta on flow control window of client stream is non-zero") - } - if cstream.fc.pendingData != 0 { - cstream.fc.mu.Unlock() - return true, fmt.Errorf("pendingData on flow control window of client stream is non-zero") - } - cstream.fc.mu.Unlock() - sstream.fc.mu.Lock() - if sstream.fc.delta != 0 { - sstream.fc.mu.Unlock() - return true, fmt.Errorf("delta on flow control window of server stream is non-zero") - } - if sstream.fc.pendingData != 0 { - sstream.fc.mu.Unlock() - return true, fmt.Errorf("pendingData on flow control window of sercer stream is non-zero") - } - sstream.fc.mu.Unlock() - ct.fc.mu.Lock() - if ct.fc.delta != 0 { - ct.fc.mu.Unlock() - return true, fmt.Errorf("delta on flow control window of client transport is non-zero") - } - if ct.fc.pendingData != 0 { - ct.fc.mu.Unlock() - return true, fmt.Errorf("pendingData on flow control window of client transport is non-zero") - } - ct.fc.mu.Unlock() - st.fc.mu.Lock() - if st.fc.delta != 0 { - st.fc.mu.Unlock() - return true, fmt.Errorf("delta on flow control window of server transport is non-zero") - } - if st.fc.pendingData != 0 { - st.fc.mu.Unlock() - return true, fmt.Errorf("pendingData on flow control window of server transport is non-zero") - } - st.fc.mu.Unlock() - - // Check flow conrtrol window on client stream is equal to out flow on server stream. - ctx, cancel := context.WithTimeout(context.Background(), time.Second) - serverStreamSendQuota, err := wait(ctx, context.Background(), nil, nil, sstream.sendQuotaPool.acquire()) - cancel() - if err != nil { - return true, fmt.Errorf("error while acquiring server stream send quota. Err: %v", err) - } - sstream.sendQuotaPool.add(serverStreamSendQuota) - cstream.fc.mu.Lock() - clientEst := cstream.fc.limit - cstream.fc.pendingUpdate - cstream.fc.mu.Unlock() - if uint32(serverStreamSendQuota) != clientEst { - return true, fmt.Errorf("server stream outflow: %v, estimated by client: %v", serverStreamSendQuota, clientEst) - } - - // Check flow control window on server stream is equal to out flow on client stream. - ctx, cancel = context.WithTimeout(context.Background(), time.Second) - clientStreamSendQuota, err := wait(ctx, context.Background(), nil, nil, cstream.sendQuotaPool.acquire()) - cancel() - if err != nil { - return true, fmt.Errorf("error while acquiring client stream send quota. Err: %v", err) - } - cstream.sendQuotaPool.add(clientStreamSendQuota) - sstream.fc.mu.Lock() - serverEst := sstream.fc.limit - sstream.fc.pendingUpdate - sstream.fc.mu.Unlock() - if uint32(clientStreamSendQuota) != serverEst { - return true, fmt.Errorf("client stream outflow: %v. estimated by server: %v", clientStreamSendQuota, serverEst) - } - - // Check flow control window on client transport is equal to out flow of server transport. - ctx, cancel = context.WithTimeout(context.Background(), time.Second) - serverTrSendQuota, err := wait(ctx, context.Background(), nil, nil, st.sendQuotaPool.acquire()) - cancel() - if err != nil { - return true, fmt.Errorf("error while acquring server transport send quota. Err: %v", err) - } - st.sendQuotaPool.add(serverTrSendQuota) - ct.fc.mu.Lock() - clientEst = ct.fc.limit - ct.fc.pendingUpdate - ct.fc.mu.Unlock() - if uint32(serverTrSendQuota) != clientEst { - return true, fmt.Errorf("server transport outflow: %v, estimated by client: %v", serverTrSendQuota, clientEst) - } - - // Check flow control window on server transport is equal to out flow of client transport. - ctx, cancel = context.WithTimeout(context.Background(), time.Second) - clientTrSendQuota, err := wait(ctx, context.Background(), nil, nil, ct.sendQuotaPool.acquire()) - cancel() - if err != nil { - return true, fmt.Errorf("error while acquiring client transport send quota. Err: %v", err) - } - ct.sendQuotaPool.add(clientTrSendQuota) - st.fc.mu.Lock() - serverEst = st.fc.limit - st.fc.pendingUpdate - st.fc.mu.Unlock() - if uint32(clientTrSendQuota) != serverEst { - return true, fmt.Errorf("client transport outflow: %v, estimated by client: %v", clientTrSendQuota, serverEst) - } - - return false, nil - }) - -} - -func waitWhileTrue(t *testing.T, condition func() (bool, error)) { - var ( - wait bool - err error - ) - timer := time.NewTimer(time.Second * 5) - for { - wait, err = condition() - if wait { - select { - case <-timer.C: - t.Fatalf(err.Error()) - default: - time.Sleep(50 * time.Millisecond) - continue - } - } - if !timer.Stop() { - <-timer.C - } - break - } -} - -// A function of type writeHeaders writes out -// http status with the given stream ID using the given framer. -type writeHeaders func(*http2.Framer, uint32, int) error - -func writeOneHeader(framer *http2.Framer, sid uint32, httpStatus int) error { - var buf bytes.Buffer - henc := hpack.NewEncoder(&buf) - henc.WriteField(hpack.HeaderField{Name: ":status", Value: fmt.Sprint(httpStatus)}) - return framer.WriteHeaders(http2.HeadersFrameParam{ - StreamID: sid, - BlockFragment: buf.Bytes(), - EndStream: true, - EndHeaders: true, - }) -} - -func writeTwoHeaders(framer *http2.Framer, sid uint32, httpStatus int) error { - var buf bytes.Buffer - henc := hpack.NewEncoder(&buf) - henc.WriteField(hpack.HeaderField{ - Name: ":status", - Value: fmt.Sprint(http.StatusOK), - }) - if err := framer.WriteHeaders(http2.HeadersFrameParam{ - StreamID: sid, - BlockFragment: buf.Bytes(), - EndHeaders: true, - }); err != nil { - return err - } - buf.Reset() - henc.WriteField(hpack.HeaderField{ - Name: ":status", - Value: fmt.Sprint(httpStatus), - }) - return framer.WriteHeaders(http2.HeadersFrameParam{ - StreamID: sid, - BlockFragment: buf.Bytes(), - EndStream: true, - EndHeaders: true, - }) -} - -type httpServer struct { - conn net.Conn - httpStatus int - wh writeHeaders -} - -func (s *httpServer) start(t *testing.T, lis net.Listener) { - // Launch an HTTP server to send back header with httpStatus. - go func() { - var err error - s.conn, err = lis.Accept() - if err != nil { - t.Errorf("Error accepting connection: %v", err) - return - } - defer s.conn.Close() - // Read preface sent by client. - if _, err = io.ReadFull(s.conn, make([]byte, len(http2.ClientPreface))); err != nil { - t.Errorf("Error at server-side while reading preface from cleint. Err: %v", err) - return - } - reader := bufio.NewReaderSize(s.conn, defaultWriteBufSize) - writer := bufio.NewWriterSize(s.conn, defaultReadBufSize) - framer := http2.NewFramer(writer, reader) - if err = framer.WriteSettingsAck(); err != nil { - t.Errorf("Error at server-side while sending Settings ack. Err: %v", err) - return - } - var sid uint32 - // Read frames until a header is received. - for { - frame, err := framer.ReadFrame() - if err != nil { - t.Errorf("Error at server-side while reading frame. Err: %v", err) - return - } - if hframe, ok := frame.(*http2.HeadersFrame); ok { - sid = hframe.Header().StreamID - break - } - } - if err = s.wh(framer, sid, s.httpStatus); err != nil { - t.Errorf("Error at server-side while writing headers. Err: %v", err) - return - } - writer.Flush() - }() -} - -func (s *httpServer) cleanUp() { - if s.conn != nil { - s.conn.Close() - } -} - -func setUpHTTPStatusTest(t *testing.T, httpStatus int, wh writeHeaders) (stream *Stream, cleanUp func()) { - var ( - err error - lis net.Listener - server *httpServer - client ClientTransport - ) - cleanUp = func() { - if lis != nil { - lis.Close() - } - if server != nil { - server.cleanUp() - } - if client != nil { - client.Close() - } - } - defer func() { - if err != nil { - cleanUp() - } - }() - lis, err = net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatalf("Failed to listen. Err: %v", err) - } - server = &httpServer{ - httpStatus: httpStatus, - wh: wh, - } - server.start(t, lis) - client, err = newHTTP2Client(context.Background(), TargetInfo{Addr: lis.Addr().String()}, ConnectOptions{}, 2*time.Second) - if err != nil { - t.Fatalf("Error creating client. Err: %v", err) - } - stream, err = client.NewStream(context.Background(), &CallHdr{Method: "bogus/method", Flush: true}) - if err != nil { - t.Fatalf("Error creating stream at client-side. Err: %v", err) - } - return -} - -func TestHTTPToGRPCStatusMapping(t *testing.T) { - for k := range httpStatusConvTab { - testHTTPToGRPCStatusMapping(t, k, writeOneHeader) - } -} - -func testHTTPToGRPCStatusMapping(t *testing.T, httpStatus int, wh writeHeaders) { - stream, cleanUp := setUpHTTPStatusTest(t, httpStatus, wh) - defer cleanUp() - want := httpStatusConvTab[httpStatus] - buf := make([]byte, 8) - _, err := stream.Read(buf) - if err == nil { - t.Fatalf("Stream.Read(_) unexpectedly returned no error. Expected stream error with code %v", want) - } - serr, ok := err.(StreamError) - if !ok { - t.Fatalf("err.(Type) = %T, want StreamError", err) - } - if want != serr.Code { - t.Fatalf("Want error code: %v, got: %v", want, serr.Code) - } -} - -func TestHTTPStatusOKAndMissingGRPCStatus(t *testing.T) { - stream, cleanUp := setUpHTTPStatusTest(t, http.StatusOK, writeOneHeader) - defer cleanUp() - buf := make([]byte, 8) - _, err := stream.Read(buf) - if err != io.EOF { - t.Fatalf("stream.Read(_) = _, %v, want _, io.EOF", err) - } - want := codes.Unknown - stream.mu.Lock() - defer stream.mu.Unlock() - if stream.status.Code() != want { - t.Fatalf("Status code of stream: %v, want: %v", stream.status.Code(), want) - } -} - -func TestHTTPStatusNottOKAndMissingGRPCStatusInSecondHeader(t *testing.T) { - testHTTPToGRPCStatusMapping(t, http.StatusUnauthorized, writeTwoHeaders) -} - -// If any error occurs on a call to Stream.Read, future calls -// should continue to return that same error. -func TestReadGivesSameErrorAfterAnyErrorOccurs(t *testing.T) { - testRecvBuffer := newRecvBuffer() - s := &Stream{ - ctx: context.Background(), - goAway: make(chan struct{}), - buf: testRecvBuffer, - requestRead: func(int) {}, - } - s.trReader = &transportReader{ - reader: &recvBufferReader{ - ctx: s.ctx, - goAway: s.goAway, - recv: s.buf, - }, - windowHandler: func(int) {}, - } - testData := make([]byte, 1) - testData[0] = 5 - testErr := errors.New("test error") - s.write(recvMsg{data: testData, err: testErr}) - - inBuf := make([]byte, 1) - actualCount, actualErr := s.Read(inBuf) - if actualCount != 0 { - t.Errorf("actualCount, _ := s.Read(_) differs; want 0; got %v", actualCount) - } - if actualErr.Error() != testErr.Error() { - t.Errorf("_ , actualErr := s.Read(_) differs; want actualErr.Error() to be %v; got %v", testErr.Error(), actualErr.Error()) - } - - s.write(recvMsg{data: testData, err: nil}) - s.write(recvMsg{data: testData, err: errors.New("different error from first")}) - - for i := 0; i < 2; i++ { - inBuf := make([]byte, 1) - actualCount, actualErr := s.Read(inBuf) - if actualCount != 0 { - t.Errorf("actualCount, _ := s.Read(_) differs; want %v; got %v", 0, actualCount) - } - if actualErr.Error() != testErr.Error() { - t.Errorf("_ , actualErr := s.Read(_) differs; want actualErr.Error() to be %v; got %v", testErr.Error(), actualErr.Error()) - } - } -} diff --git a/vendor/google.golang.org/grpc/vet.sh b/vendor/google.golang.org/grpc/vet.sh index 72ef3290ad..6126ab64bd 100755 --- a/vendor/google.golang.org/grpc/vet.sh +++ b/vendor/google.golang.org/grpc/vet.sh @@ -1,5 +1,10 @@ #!/bin/bash +if [[ `uname -a` = *"Darwin"* ]]; then + echo "It seems you are running on Mac. This script does not work on Mac. See https://github.com/grpc/grpc-go/issues/2047" + exit 1 +fi + set -ex # Exit on error; debugging enabled. set -o pipefail # Fail a pipe if any sub-command fails. @@ -8,12 +13,6 @@ die() { exit 1 } -# TODO: Remove this check and the mangling below once "context" is imported -# directly. -if git status --porcelain | read; then - die "Uncommitted or untracked files found; commit changes first" -fi - PATH="$GOPATH/bin:$GOROOT/bin:$PATH" # Check proto in manual runs or cron runs. @@ -28,8 +27,8 @@ if [ "$1" = "-install" ]; then github.com/golang/lint/golint \ golang.org/x/tools/cmd/goimports \ honnef.co/go/tools/cmd/staticcheck \ - github.com/golang/protobuf/protoc-gen-go \ - golang.org/x/tools/cmd/stringer + github.com/client9/misspell/cmd/misspell \ + github.com/golang/protobuf/protoc-gen-go if [[ "$check_proto" = "true" ]]; then if [[ "$TRAVIS" = "true" ]]; then PROTOBUF_VERSION=3.3.0 @@ -48,10 +47,17 @@ elif [[ "$#" -ne 0 ]]; then die "Unknown argument(s): $*" fi +# TODO: Remove this check and the mangling below once "context" is imported +# directly. +if git status --porcelain | read; then + die "Uncommitted or untracked files found; commit changes first" +fi + git ls-files "*.go" | xargs grep -L "\(Copyright [0-9]\{4,\} gRPC authors\)\|DO NOT EDIT" 2>&1 | tee /dev/stderr | (! read) +git ls-files "*.go" | xargs grep -l "\"unsafe\"" 2>&1 | (! grep -v '_test.go') | tee /dev/stderr | (! read) gofmt -s -d -l . 2>&1 | tee /dev/stderr | (! read) goimports -l . 2>&1 | tee /dev/stderr | (! read) -golint ./... 2>&1 | (grep -vE "(_mock|_string|\.pb)\.go:" || true) | tee /dev/stderr | (! read) +golint ./... 2>&1 | (grep -vE "(_mock|\.pb)\.go:" || true) | tee /dev/stderr | (! read) # Undo any edits made by this script. cleanup() { @@ -64,7 +70,7 @@ trap cleanup EXIT git ls-files "*.go" | xargs sed -i 's:"golang.org/x/net/context":"context":' set +o pipefail # TODO: Stop filtering pb.go files once golang/protobuf#214 is fixed. -go tool vet -all . 2>&1 | grep -vF '.pb.go:' | tee /dev/stderr | (! read) +go tool vet -all . 2>&1 | grep -vE '(clientconn|transport\/transport_test).go:.*cancel (function|var)' | grep -vF '.pb.go:' | tee /dev/stderr | (! read) set -o pipefail git reset --hard HEAD @@ -75,4 +81,13 @@ if [[ "$check_proto" = "true" ]]; then fi # TODO(menghanl): fix errors in transport_test. -staticcheck -ignore google.golang.org/grpc/transport/transport_test.go:SA2002 ./... +staticcheck -ignore ' +google.golang.org/grpc/transport/transport_test.go:SA2002 +google.golang.org/grpc/benchmark/benchmain/main.go:SA1019 +google.golang.org/grpc/stats/stats_test.go:SA1019 +google.golang.org/grpc/test/end2end_test.go:SA1019 +google.golang.org/grpc/balancer_test.go:SA1019 +google.golang.org/grpc/balancer.go:SA1019 +google.golang.org/grpc/clientconn_test.go:SA1019 +' ./... +misspell -error . diff --git a/vendor/gopkg.in/fsnotify/fsnotify.v1/example_test.go b/vendor/gopkg.in/fsnotify/fsnotify.v1/example_test.go deleted file mode 100644 index 700502cb3a..0000000000 --- a/vendor/gopkg.in/fsnotify/fsnotify.v1/example_test.go +++ /dev/null @@ -1,42 +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 !plan9 - -package fsnotify_test - -import ( - "log" - - "github.com/fsnotify/fsnotify" -) - -func ExampleNewWatcher() { - watcher, err := fsnotify.NewWatcher() - if err != nil { - log.Fatal(err) - } - defer watcher.Close() - - done := make(chan bool) - go func() { - for { - select { - case event := <-watcher.Events: - log.Println("event:", event) - if event.Op&fsnotify.Write == fsnotify.Write { - log.Println("modified file:", event.Name) - } - case err := <-watcher.Errors: - log.Println("error:", err) - } - } - }() - - err = watcher.Add("/tmp/foo") - if err != nil { - log.Fatal(err) - } - <-done -} diff --git a/vendor/gopkg.in/fsnotify/fsnotify.v1/fsnotify_test.go b/vendor/gopkg.in/fsnotify/fsnotify.v1/fsnotify_test.go deleted file mode 100644 index f9771d9dfe..0000000000 --- a/vendor/gopkg.in/fsnotify/fsnotify.v1/fsnotify_test.go +++ /dev/null @@ -1,70 +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. - -// +build !plan9 - -package fsnotify - -import ( - "os" - "testing" - "time" -) - -func TestEventStringWithValue(t *testing.T) { - for opMask, expectedString := range map[Op]string{ - Chmod | Create: `"/usr/someFile": CREATE|CHMOD`, - Rename: `"/usr/someFile": RENAME`, - Remove: `"/usr/someFile": REMOVE`, - Write | Chmod: `"/usr/someFile": WRITE|CHMOD`, - } { - event := Event{Name: "/usr/someFile", Op: opMask} - if event.String() != expectedString { - t.Fatalf("Expected %s, got: %v", expectedString, event.String()) - } - - } -} - -func TestEventOpStringWithValue(t *testing.T) { - expectedOpString := "WRITE|CHMOD" - event := Event{Name: "someFile", Op: Write | Chmod} - if event.Op.String() != expectedOpString { - t.Fatalf("Expected %s, got: %v", expectedOpString, event.Op.String()) - } -} - -func TestEventOpStringWithNoValue(t *testing.T) { - expectedOpString := "" - event := Event{Name: "testFile", Op: 0} - if event.Op.String() != expectedOpString { - t.Fatalf("Expected %s, got: %v", expectedOpString, event.Op.String()) - } -} - -// TestWatcherClose tests that the goroutine started by creating the watcher can be -// signalled to return at any time, even if there is no goroutine listening on the events -// or errors channels. -func TestWatcherClose(t *testing.T) { - t.Parallel() - - name := tempMkFile(t, "") - w := newWatcher(t) - err := w.Add(name) - if err != nil { - t.Fatal(err) - } - - err = os.Remove(name) - if err != nil { - t.Fatal(err) - } - // Allow the watcher to receive the event. - time.Sleep(time.Millisecond * 100) - - err = w.Close() - if err != nil { - t.Fatal(err) - } -} diff --git a/vendor/gopkg.in/fsnotify/fsnotify.v1/inotify_poller_test.go b/vendor/gopkg.in/fsnotify/fsnotify.v1/inotify_poller_test.go deleted file mode 100644 index 26623efeff..0000000000 --- a/vendor/gopkg.in/fsnotify/fsnotify.v1/inotify_poller_test.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2015 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 - -package fsnotify - -import ( - "testing" - "time" - - "golang.org/x/sys/unix" -) - -type testFd [2]int - -func makeTestFd(t *testing.T) testFd { - var tfd testFd - errno := unix.Pipe(tfd[:]) - if errno != nil { - t.Fatalf("Failed to create pipe: %v", errno) - } - return tfd -} - -func (tfd testFd) fd() int { - return tfd[0] -} - -func (tfd testFd) closeWrite(t *testing.T) { - errno := unix.Close(tfd[1]) - if errno != nil { - t.Fatalf("Failed to close write end of pipe: %v", errno) - } -} - -func (tfd testFd) put(t *testing.T) { - buf := make([]byte, 10) - _, errno := unix.Write(tfd[1], buf) - if errno != nil { - t.Fatalf("Failed to write to pipe: %v", errno) - } -} - -func (tfd testFd) get(t *testing.T) { - buf := make([]byte, 10) - _, errno := unix.Read(tfd[0], buf) - if errno != nil { - t.Fatalf("Failed to read from pipe: %v", errno) - } -} - -func (tfd testFd) close() { - unix.Close(tfd[1]) - unix.Close(tfd[0]) -} - -func makePoller(t *testing.T) (testFd, *fdPoller) { - tfd := makeTestFd(t) - poller, err := newFdPoller(tfd.fd()) - if err != nil { - t.Fatalf("Failed to create poller: %v", err) - } - return tfd, poller -} - -func TestPollerWithBadFd(t *testing.T) { - _, err := newFdPoller(-1) - if err != unix.EBADF { - t.Fatalf("Expected EBADF, got: %v", err) - } -} - -func TestPollerWithData(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - tfd.put(t) - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } - tfd.get(t) -} - -func TestPollerWithWakeup(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - err := poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if ok { - t.Fatalf("expected poller to return false") - } -} - -func TestPollerWithClose(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - tfd.closeWrite(t) - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } -} - -func TestPollerWithWakeupAndData(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - tfd.put(t) - err := poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - - // both data and wakeup - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } - - // data is still in the buffer, wakeup is cleared - ok, err = poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if !ok { - t.Fatalf("expected poller to return true") - } - - tfd.get(t) - // data is gone, only wakeup now - err = poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - ok, err = poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - if ok { - t.Fatalf("expected poller to return false") - } -} - -func TestPollerConcurrent(t *testing.T) { - tfd, poller := makePoller(t) - defer tfd.close() - defer poller.close() - - oks := make(chan bool) - live := make(chan bool) - defer close(live) - go func() { - defer close(oks) - for { - ok, err := poller.wait() - if err != nil { - t.Fatalf("poller failed: %v", err) - } - oks <- ok - if !<-live { - return - } - } - }() - - // Try a write - select { - case <-time.After(50 * time.Millisecond): - case <-oks: - t.Fatalf("poller did not wait") - } - tfd.put(t) - if !<-oks { - t.Fatalf("expected true") - } - tfd.get(t) - live <- true - - // Try a wakeup - select { - case <-time.After(50 * time.Millisecond): - case <-oks: - t.Fatalf("poller did not wait") - } - err := poller.wake() - if err != nil { - t.Fatalf("wake failed: %v", err) - } - if <-oks { - t.Fatalf("expected false") - } - live <- true - - // Try a close - select { - case <-time.After(50 * time.Millisecond): - case <-oks: - t.Fatalf("poller did not wait") - } - tfd.closeWrite(t) - if !<-oks { - t.Fatalf("expected true") - } - tfd.get(t) -} diff --git a/vendor/gopkg.in/fsnotify/fsnotify.v1/inotify_test.go b/vendor/gopkg.in/fsnotify/fsnotify.v1/inotify_test.go deleted file mode 100644 index 54f3f00eba..0000000000 --- a/vendor/gopkg.in/fsnotify/fsnotify.v1/inotify_test.go +++ /dev/null @@ -1,449 +0,0 @@ -// Copyright 2015 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 - -package fsnotify - -import ( - "fmt" - "os" - "path/filepath" - "strings" - "testing" - "time" -) - -func TestInotifyCloseRightAway(t *testing.T) { - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - - // Close immediately; it won't even reach the first unix.Read. - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func TestInotifyCloseSlightlyLater(t *testing.T) { - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - - // Wait until readEvents has reached unix.Read, and Close. - <-time.After(50 * time.Millisecond) - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func TestInotifyCloseSlightlyLaterWithWatch(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - w.Add(testDir) - - // Wait until readEvents has reached unix.Read, and Close. - <-time.After(50 * time.Millisecond) - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func TestInotifyCloseAfterRead(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher") - } - - err = w.Add(testDir) - if err != nil { - t.Fatalf("Failed to add .") - } - - // Generate an event. - os.Create(filepath.Join(testDir, "somethingSOMETHINGsomethingSOMETHING")) - - // Wait for readEvents to read the event, then close the watcher. - <-time.After(50 * time.Millisecond) - w.Close() - - // Wait for the close to complete. - <-time.After(50 * time.Millisecond) - isWatcherReallyClosed(t, w) -} - -func isWatcherReallyClosed(t *testing.T, w *Watcher) { - select { - case err, ok := <-w.Errors: - if ok { - t.Fatalf("w.Errors is not closed; readEvents is still alive after closing (error: %v)", err) - } - default: - t.Fatalf("w.Errors would have blocked; readEvents is still alive!") - } - - select { - case _, ok := <-w.Events: - if ok { - t.Fatalf("w.Events is not closed; readEvents is still alive after closing") - } - default: - t.Fatalf("w.Events would have blocked; readEvents is still alive!") - } -} - -func TestInotifyCloseCreate(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testDir) - if err != nil { - t.Fatalf("Failed to add testDir: %v", err) - } - h, err := os.Create(filepath.Join(testDir, "testfile")) - if err != nil { - t.Fatalf("Failed to create file in testdir: %v", err) - } - h.Close() - select { - case _ = <-w.Events: - case err := <-w.Errors: - t.Fatalf("Error from watcher: %v", err) - case <-time.After(50 * time.Millisecond): - t.Fatalf("Took too long to wait for event") - } - - // At this point, we've received one event, so the goroutine is ready. - // It's also blocking on unix.Read. - // Now we try to swap the file descriptor under its nose. - w.Close() - w, err = NewWatcher() - defer w.Close() - if err != nil { - t.Fatalf("Failed to create second watcher: %v", err) - } - - <-time.After(50 * time.Millisecond) - err = w.Add(testDir) - if err != nil { - t.Fatalf("Error adding testDir again: %v", err) - } -} - -// This test verifies the watcher can keep up with file creations/deletions -// when under load. -func TestInotifyStress(t *testing.T) { - maxNumToCreate := 1000 - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - testFilePrefix := filepath.Join(testDir, "testfile") - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testDir) - if err != nil { - t.Fatalf("Failed to add testDir: %v", err) - } - - doneChan := make(chan struct{}) - // The buffer ensures that the file generation goroutine is never blocked. - errChan := make(chan error, 2*maxNumToCreate) - - go func() { - for i := 0; i < maxNumToCreate; i++ { - testFile := fmt.Sprintf("%s%d", testFilePrefix, i) - - handle, err := os.Create(testFile) - if err != nil { - errChan <- fmt.Errorf("Create failed: %v", err) - continue - } - - err = handle.Close() - if err != nil { - errChan <- fmt.Errorf("Close failed: %v", err) - continue - } - } - - // If we delete a newly created file too quickly, inotify will skip the - // create event and only send the delete event. - time.Sleep(100 * time.Millisecond) - - for i := 0; i < maxNumToCreate; i++ { - testFile := fmt.Sprintf("%s%d", testFilePrefix, i) - err = os.Remove(testFile) - if err != nil { - errChan <- fmt.Errorf("Remove failed: %v", err) - } - } - - close(doneChan) - }() - - creates := 0 - removes := 0 - - finished := false - after := time.After(10 * time.Second) - for !finished { - select { - case <-after: - t.Fatalf("Not done") - case <-doneChan: - finished = true - case err := <-errChan: - t.Fatalf("Got an error from file creator goroutine: %v", err) - case err := <-w.Errors: - t.Fatalf("Got an error from watcher: %v", err) - case evt := <-w.Events: - if !strings.HasPrefix(evt.Name, testFilePrefix) { - t.Fatalf("Got an event for an unknown file: %s", evt.Name) - } - if evt.Op == Create { - creates++ - } - if evt.Op == Remove { - removes++ - } - } - } - - // Drain remaining events from channels - count := 0 - for count < 10 { - select { - case err := <-errChan: - t.Fatalf("Got an error from file creator goroutine: %v", err) - case err := <-w.Errors: - t.Fatalf("Got an error from watcher: %v", err) - case evt := <-w.Events: - if !strings.HasPrefix(evt.Name, testFilePrefix) { - t.Fatalf("Got an event for an unknown file: %s", evt.Name) - } - if evt.Op == Create { - creates++ - } - if evt.Op == Remove { - removes++ - } - count = 0 - default: - count++ - // Give the watcher chances to fill the channels. - time.Sleep(time.Millisecond) - } - } - - if creates-removes > 1 || creates-removes < -1 { - t.Fatalf("Creates and removes should not be off by more than one: %d creates, %d removes", creates, removes) - } - if creates < 50 { - t.Fatalf("Expected at least 50 creates, got %d", creates) - } -} - -func TestInotifyRemoveTwice(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - testFile := filepath.Join(testDir, "testfile") - - handle, err := os.Create(testFile) - if err != nil { - t.Fatalf("Create failed: %v", err) - } - handle.Close() - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testFile) - if err != nil { - t.Fatalf("Failed to add testFile: %v", err) - } - - err = w.Remove(testFile) - if err != nil { - t.Fatalf("wanted successful remove but got: %v", err) - } - - err = w.Remove(testFile) - if err == nil { - t.Fatalf("no error on removing invalid file") - } - - w.mu.Lock() - defer w.mu.Unlock() - if len(w.watches) != 0 { - t.Fatalf("Expected watches len is 0, but got: %d, %v", len(w.watches), w.watches) - } - if len(w.paths) != 0 { - t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths) - } -} - -func TestInotifyInnerMapLength(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - testFile := filepath.Join(testDir, "testfile") - - handle, err := os.Create(testFile) - if err != nil { - t.Fatalf("Create failed: %v", err) - } - handle.Close() - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - err = w.Add(testFile) - if err != nil { - t.Fatalf("Failed to add testFile: %v", err) - } - go func() { - for err := range w.Errors { - t.Fatalf("error received: %s", err) - } - }() - - err = os.Remove(testFile) - if err != nil { - t.Fatalf("Failed to remove testFile: %v", err) - } - _ = <-w.Events // consume Remove event - <-time.After(50 * time.Millisecond) // wait IN_IGNORE propagated - - w.mu.Lock() - defer w.mu.Unlock() - if len(w.watches) != 0 { - t.Fatalf("Expected watches len is 0, but got: %d, %v", len(w.watches), w.watches) - } - if len(w.paths) != 0 { - t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths) - } -} - -func TestInotifyOverflow(t *testing.T) { - // We need to generate many more events than the - // fs.inotify.max_queued_events sysctl setting. - // We use multiple goroutines (one per directory) - // to speed up file creation. - numDirs := 128 - numFiles := 1024 - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - w, err := NewWatcher() - if err != nil { - t.Fatalf("Failed to create watcher: %v", err) - } - defer w.Close() - - for dn := 0; dn < numDirs; dn++ { - testSubdir := fmt.Sprintf("%s/%d", testDir, dn) - - err := os.Mkdir(testSubdir, 0777) - if err != nil { - t.Fatalf("Cannot create subdir: %v", err) - } - - err = w.Add(testSubdir) - if err != nil { - t.Fatalf("Failed to add subdir: %v", err) - } - } - - errChan := make(chan error, numDirs*numFiles) - - for dn := 0; dn < numDirs; dn++ { - testSubdir := fmt.Sprintf("%s/%d", testDir, dn) - - go func() { - for fn := 0; fn < numFiles; fn++ { - testFile := fmt.Sprintf("%s/%d", testSubdir, fn) - - handle, err := os.Create(testFile) - if err != nil { - errChan <- fmt.Errorf("Create failed: %v", err) - continue - } - - err = handle.Close() - if err != nil { - errChan <- fmt.Errorf("Close failed: %v", err) - continue - } - } - }() - } - - creates := 0 - overflows := 0 - - after := time.After(10 * time.Second) - for overflows == 0 && creates < numDirs*numFiles { - select { - case <-after: - t.Fatalf("Not done") - case err := <-errChan: - t.Fatalf("Got an error from file creator goroutine: %v", err) - case err := <-w.Errors: - if err == ErrEventOverflow { - overflows++ - } else { - t.Fatalf("Got an error from watcher: %v", err) - } - case evt := <-w.Events: - if !strings.HasPrefix(evt.Name, testDir) { - t.Fatalf("Got an event for an unknown file: %s", evt.Name) - } - if evt.Op == Create { - creates++ - } - } - } - - if creates == numDirs*numFiles { - t.Fatalf("Could not trigger overflow") - } - - if overflows == 0 { - t.Fatalf("No overflow and not enough creates (expected %d, got %d)", - numDirs*numFiles, creates) - } -} diff --git a/vendor/gopkg.in/fsnotify/fsnotify.v1/integration_darwin_test.go b/vendor/gopkg.in/fsnotify/fsnotify.v1/integration_darwin_test.go deleted file mode 100644 index cd6adc273e..0000000000 --- a/vendor/gopkg.in/fsnotify/fsnotify.v1/integration_darwin_test.go +++ /dev/null @@ -1,147 +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 fsnotify - -import ( - "os" - "path/filepath" - "testing" - "time" - - "golang.org/x/sys/unix" -) - -// testExchangedataForWatcher tests the watcher with the exchangedata operation on macOS. -// -// This is widely used for atomic saves on macOS, e.g. TextMate and in Apple's NSDocument. -// -// See https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/exchangedata.2.html -// Also see: https://github.com/textmate/textmate/blob/cd016be29489eba5f3c09b7b70b06da134dda550/Frameworks/io/src/swap_file_data.cc#L20 -func testExchangedataForWatcher(t *testing.T, watchDir bool) { - // Create directory to watch - testDir1 := tempMkdir(t) - - // For the intermediate file - testDir2 := tempMkdir(t) - - defer os.RemoveAll(testDir1) - defer os.RemoveAll(testDir2) - - resolvedFilename := "TestFsnotifyEvents.file" - - // TextMate does: - // - // 1. exchangedata (intermediate, resolved) - // 2. unlink intermediate - // - // Let's try to simulate that: - resolved := filepath.Join(testDir1, resolvedFilename) - intermediate := filepath.Join(testDir2, resolvedFilename+"~") - - // Make sure we create the file before we start watching - createAndSyncFile(t, resolved) - - watcher := newWatcher(t) - - // Test both variants in isolation - if watchDir { - addWatch(t, watcher, testDir1) - } else { - addWatch(t, watcher, resolved) - } - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var removeReceived counter - var createReceived counter - - done := make(chan bool) - - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(resolved) { - if event.Op&Remove == Remove { - removeReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - } - t.Logf("event received: %s", event) - } - done <- true - }() - - // Repeat to make sure the watched file/directory "survives" the REMOVE/CREATE loop. - for i := 1; i <= 3; i++ { - // The intermediate file is created in a folder outside the watcher - createAndSyncFile(t, intermediate) - - // 1. Swap - if err := unix.Exchangedata(intermediate, resolved, 0); err != nil { - t.Fatalf("[%d] exchangedata failed: %s", i, err) - } - - time.Sleep(50 * time.Millisecond) - - // 2. Delete the intermediate file - err := os.Remove(intermediate) - - if err != nil { - t.Fatalf("[%d] remove %s failed: %s", i, intermediate, err) - } - - time.Sleep(50 * time.Millisecond) - - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - - // The events will be (CHMOD + REMOVE + CREATE) X 2. Let's focus on the last two: - if removeReceived.value() < 3 { - t.Fatal("fsnotify remove events have not been received after 500 ms") - } - - if createReceived.value() < 3 { - t.Fatal("fsnotify create events have not been received after 500 ms") - } - - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -// TestExchangedataInWatchedDir test exchangedata operation on file in watched dir. -func TestExchangedataInWatchedDir(t *testing.T) { - testExchangedataForWatcher(t, true) -} - -// TestExchangedataInWatchedDir test exchangedata operation on watched file. -func TestExchangedataInWatchedFile(t *testing.T) { - testExchangedataForWatcher(t, false) -} - -func createAndSyncFile(t *testing.T, filepath string) { - f1, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating %s failed: %s", filepath, err) - } - f1.Sync() - f1.Close() -} diff --git a/vendor/gopkg.in/fsnotify/fsnotify.v1/integration_test.go b/vendor/gopkg.in/fsnotify/fsnotify.v1/integration_test.go deleted file mode 100644 index 8b7e9d3ec8..0000000000 --- a/vendor/gopkg.in/fsnotify/fsnotify.v1/integration_test.go +++ /dev/null @@ -1,1237 +0,0 @@ -// Copyright 2010 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 !plan9,!solaris - -package fsnotify - -import ( - "io/ioutil" - "os" - "os/exec" - "path" - "path/filepath" - "runtime" - "sync/atomic" - "testing" - "time" -) - -// An atomic counter -type counter struct { - val int32 -} - -func (c *counter) increment() { - atomic.AddInt32(&c.val, 1) -} - -func (c *counter) value() int32 { - return atomic.LoadInt32(&c.val) -} - -func (c *counter) reset() { - atomic.StoreInt32(&c.val, 0) -} - -// tempMkdir makes a temporary directory -func tempMkdir(t *testing.T) string { - dir, err := ioutil.TempDir("", "fsnotify") - if err != nil { - t.Fatalf("failed to create test directory: %s", err) - } - return dir -} - -// tempMkFile makes a temporary file. -func tempMkFile(t *testing.T, dir string) string { - f, err := ioutil.TempFile(dir, "fsnotify") - if err != nil { - t.Fatalf("failed to create test file: %v", err) - } - defer f.Close() - return f.Name() -} - -// newWatcher initializes an fsnotify Watcher instance. -func newWatcher(t *testing.T) *Watcher { - watcher, err := NewWatcher() - if err != nil { - t.Fatalf("NewWatcher() failed: %s", err) - } - return watcher -} - -// addWatch adds a watch for a directory -func addWatch(t *testing.T, watcher *Watcher, dir string) { - if err := watcher.Add(dir); err != nil { - t.Fatalf("watcher.Add(%q) failed: %s", dir, err) - } -} - -func TestFsnotifyMultipleOperations(t *testing.T) { - watcher := newWatcher(t) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create directory that's not watched - testDirToMoveFiles := tempMkdir(t) - defer os.RemoveAll(testDirToMoveFiles) - - testFile := filepath.Join(testDir, "TestFsnotifySeq.testfile") - testFileRenamed := filepath.Join(testDirToMoveFiles, "TestFsnotifySeqRename.testfile") - - addWatch(t, watcher, testDir) - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, modifyReceived, deleteReceived, renameReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - if event.Op&Write == Write { - modifyReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - if event.Op&Rename == Rename { - renameReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // Modify the file outside of the watched dir - f, err = os.Open(testFileRenamed) - if err != nil { - t.Fatalf("open test renamed file failed: %s", err) - } - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Recreate the file that was moved - f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Close() - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 2 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2) - } - mReceived := modifyReceived.value() - if mReceived != 1 { - t.Fatalf("incorrect number of modify events received after 500 ms (%d vs %d)", mReceived, 1) - } - dReceived := deleteReceived.value() - rReceived := renameReceived.value() - if dReceived+rReceived != 1 { - t.Fatalf("incorrect number of rename+delete events received after 500 ms (%d vs %d)", rReceived+dReceived, 1) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyMultipleCreates(t *testing.T) { - watcher := newWatcher(t) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - testFile := filepath.Join(testDir, "TestFsnotifySeq.testfile") - - addWatch(t, watcher, testDir) - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, modifyReceived, deleteReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - if event.Op&Write == Write { - modifyReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - os.Remove(testFile) - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Recreate the file - f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Close() - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Modify - f, err = os.OpenFile(testFile, os.O_WRONLY, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // Modify - f, err = os.OpenFile(testFile, os.O_WRONLY, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 2 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2) - } - mReceived := modifyReceived.value() - if mReceived < 3 { - t.Fatalf("incorrect number of modify events received after 500 ms (%d vs atleast %d)", mReceived, 3) - } - dReceived := deleteReceived.value() - if dReceived != 1 { - t.Fatalf("incorrect number of rename+delete events received after 500 ms (%d vs %d)", dReceived, 1) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyDirOnly(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - // This should NOT add any events to the fsnotify event queue - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDir, "TestFsnotifyDirOnly.testfile") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, modifyReceived, deleteReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileAlreadyExists) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - if event.Op&Write == Write { - modifyReceived.increment() - } - if event.Op&Create == Create { - createReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - time.Sleep(time.Millisecond) - f.WriteString("data") - f.Sync() - f.Close() - - time.Sleep(50 * time.Millisecond) // give system time to sync write change before delete - - os.Remove(testFile) - os.Remove(testFileAlreadyExists) - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 1 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 1) - } - mReceived := modifyReceived.value() - if mReceived != 1 { - t.Fatalf("incorrect number of modify events received after 500 ms (%d vs %d)", mReceived, 1) - } - dReceived := deleteReceived.value() - if dReceived != 2 { - t.Fatalf("incorrect number of delete events received after 500 ms (%d vs %d)", dReceived, 2) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyDeleteWatchedDir(t *testing.T) { - watcher := newWatcher(t) - defer watcher.Close() - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - addWatch(t, watcher, testDir) - - // Add a watch for testFile - addWatch(t, watcher, testFileAlreadyExists) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var deleteReceived counter - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFileAlreadyExists) { - t.Logf("event received: %s", event) - if event.Op&Remove == Remove { - deleteReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - }() - - os.RemoveAll(testDir) - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - dReceived := deleteReceived.value() - if dReceived < 2 { - t.Fatalf("did not receive at least %d delete events, received %d after 500 ms", 2, dReceived) - } -} - -func TestFsnotifySubDir(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - testFile1 := filepath.Join(testDir, "TestFsnotifyFile1.testfile") - testSubDir := filepath.Join(testDir, "sub") - testSubDirFile := filepath.Join(testDir, "sub/TestFsnotifyFile1.testfile") - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived, deleteReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testSubDir) || event.Name == filepath.Clean(testFile1) { - t.Logf("event received: %s", event) - if event.Op&Create == Create { - createReceived.increment() - } - if event.Op&Remove == Remove { - deleteReceived.increment() - } - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - addWatch(t, watcher, testDir) - - // Create sub-directory - if err := os.Mkdir(testSubDir, 0777); err != nil { - t.Fatalf("failed to create test sub-directory: %s", err) - } - - // Create a file - var f *os.File - f, err := os.OpenFile(testFile1, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - - // Create a file (Should not see this! we are not watching subdir) - var fs *os.File - fs, err = os.OpenFile(testSubDirFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - fs.Sync() - fs.Close() - - time.Sleep(200 * time.Millisecond) - - // Make sure receive deletes for both file and sub-directory - os.RemoveAll(testSubDir) - os.Remove(testFile1) - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - cReceived := createReceived.value() - if cReceived != 2 { - t.Fatalf("incorrect number of create events received after 500 ms (%d vs %d)", cReceived, 2) - } - dReceived := deleteReceived.value() - if dReceived != 2 { - t.Fatalf("incorrect number of delete events received after 500 ms (%d vs %d)", dReceived, 2) - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } -} - -func TestFsnotifyRename(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDir, "TestFsnotifyEvents.testfile") - testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var renameReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileRenamed) { - if event.Op&Rename == Rename { - renameReceived.increment() - } - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - f.WriteString("data") - f.Sync() - f.Close() - - // Add a watch for testFile - addWatch(t, watcher, testFile) - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - if renameReceived.value() == 0 { - t.Fatal("fsnotify rename events have not been received after 500 ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } - - os.Remove(testFileRenamed) -} - -func TestFsnotifyRenameToCreate(t *testing.T) { - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create directory to get file - testDirFrom := tempMkdir(t) - defer os.RemoveAll(testDirFrom) - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDirFrom, "TestFsnotifyEvents.testfile") - testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var createReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) || event.Name == filepath.Clean(testFileRenamed) { - if event.Op&Create == Create { - createReceived.increment() - } - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - if createReceived.value() == 0 { - t.Fatal("fsnotify create events have not been received after 500 ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } - - os.Remove(testFileRenamed) -} - -func TestFsnotifyRenameToOverwrite(t *testing.T) { - switch runtime.GOOS { - case "plan9", "windows": - t.Skipf("skipping test on %q (os.Rename over existing file does not create event).", runtime.GOOS) - } - - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create directory to get file - testDirFrom := tempMkdir(t) - defer os.RemoveAll(testDirFrom) - - testFile := filepath.Join(testDirFrom, "TestFsnotifyEvents.testfile") - testFileRenamed := filepath.Join(testDir, "TestFsnotifyEvents.testfileRenamed") - - // Create a file - var fr *os.File - fr, err := os.OpenFile(testFileRenamed, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - fr.Sync() - fr.Close() - - addWatch(t, watcher, testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - var eventReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testFileRenamed) { - eventReceived.increment() - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err = os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - - if err := testRename(testFile, testFileRenamed); err != nil { - t.Fatalf("rename failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - if eventReceived.value() == 0 { - t.Fatal("fsnotify events have not been received after 500 ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(2 * time.Second): - t.Fatal("event stream was not closed after 2 seconds") - } - - os.Remove(testFileRenamed) -} - -func TestRemovalOfWatch(t *testing.T) { - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - watcher := newWatcher(t) - defer watcher.Close() - - addWatch(t, watcher, testDir) - if err := watcher.Remove(testDir); err != nil { - t.Fatalf("Could not remove the watch: %v\n", err) - } - - go func() { - select { - case ev := <-watcher.Events: - t.Fatalf("We received event: %v\n", ev) - case <-time.After(500 * time.Millisecond): - t.Log("No event received, as expected.") - } - }() - - time.Sleep(200 * time.Millisecond) - // Modify the file outside of the watched dir - f, err := os.Open(testFileAlreadyExists) - if err != nil { - t.Fatalf("Open test file failed: %s", err) - } - f.WriteString("data") - f.Sync() - f.Close() - if err := os.Chmod(testFileAlreadyExists, 0700); err != nil { - t.Fatalf("chmod failed: %s", err) - } - time.Sleep(400 * time.Millisecond) -} - -func TestFsnotifyAttrib(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("attributes don't work on Windows.") - } - - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Receive errors on the error channel on a separate goroutine - go func() { - for err := range watcher.Errors { - t.Fatalf("error received: %s", err) - } - }() - - testFile := filepath.Join(testDir, "TestFsnotifyAttrib.testfile") - - // Receive events on the event channel on a separate goroutine - eventstream := watcher.Events - // The modifyReceived counter counts IsModify events that are not IsAttrib, - // and the attribReceived counts IsAttrib events (which are also IsModify as - // a consequence). - var modifyReceived counter - var attribReceived counter - done := make(chan bool) - go func() { - for event := range eventstream { - // Only count relevant events - if event.Name == filepath.Clean(testDir) || event.Name == filepath.Clean(testFile) { - if event.Op&Write == Write { - modifyReceived.increment() - } - if event.Op&Chmod == Chmod { - attribReceived.increment() - } - t.Logf("event received: %s", event) - } else { - t.Logf("unexpected event received: %s", event) - } - } - done <- true - }() - - // Create a file - // This should add at least one event to the fsnotify event queue - var f *os.File - f, err := os.OpenFile(testFile, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - - f.WriteString("data") - f.Sync() - f.Close() - - // Add a watch for testFile - addWatch(t, watcher, testFile) - - if err := os.Chmod(testFile, 0700); err != nil { - t.Fatalf("chmod failed: %s", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - // Creating/writing a file changes also the mtime, so IsAttrib should be set to true here - time.Sleep(500 * time.Millisecond) - if modifyReceived.value() != 0 { - t.Fatal("received an unexpected modify event when creating a test file") - } - if attribReceived.value() == 0 { - t.Fatal("fsnotify attribute events have not received after 500 ms") - } - - // Modifying the contents of the file does not set the attrib flag (although eg. the mtime - // might have been modified). - modifyReceived.reset() - attribReceived.reset() - - f, err = os.OpenFile(testFile, os.O_WRONLY, 0) - if err != nil { - t.Fatalf("reopening test file failed: %s", err) - } - - f.WriteString("more data") - f.Sync() - f.Close() - - time.Sleep(500 * time.Millisecond) - - if modifyReceived.value() != 1 { - t.Fatal("didn't receive a modify event after changing test file contents") - } - - if attribReceived.value() != 0 { - t.Fatal("did receive an unexpected attrib event after changing test file contents") - } - - modifyReceived.reset() - attribReceived.reset() - - // Doing a chmod on the file should trigger an event with the "attrib" flag set (the contents - // of the file are not changed though) - if err := os.Chmod(testFile, 0600); err != nil { - t.Fatalf("chmod failed: %s", err) - } - - time.Sleep(500 * time.Millisecond) - - if attribReceived.value() != 1 { - t.Fatal("didn't receive an attribute change after 500ms") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() - t.Log("waiting for the event channel to become closed...") - select { - case <-done: - t.Log("event channel closed") - case <-time.After(1e9): - t.Fatal("event stream was not closed after 1 second") - } - - os.Remove(testFile) -} - -func TestFsnotifyClose(t *testing.T) { - watcher := newWatcher(t) - watcher.Close() - - var done int32 - go func() { - watcher.Close() - atomic.StoreInt32(&done, 1) - }() - - time.Sleep(50e6) // 50 ms - if atomic.LoadInt32(&done) == 0 { - t.Fatal("double Close() test failed: second Close() call didn't return") - } - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - if err := watcher.Add(testDir); err == nil { - t.Fatal("expected error on Watch() after Close(), got nil") - } -} - -func TestFsnotifyFakeSymlink(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("symlinks don't work on Windows.") - } - - watcher := newWatcher(t) - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - var errorsReceived counter - // Receive errors on the error channel on a separate goroutine - go func() { - for errors := range watcher.Errors { - t.Logf("Received error: %s", errors) - errorsReceived.increment() - } - }() - - // Count the CREATE events received - var createEventsReceived, otherEventsReceived counter - go func() { - for ev := range watcher.Events { - t.Logf("event received: %s", ev) - if ev.Op&Create == Create { - createEventsReceived.increment() - } else { - otherEventsReceived.increment() - } - } - }() - - addWatch(t, watcher, testDir) - - if err := os.Symlink(filepath.Join(testDir, "zzz"), filepath.Join(testDir, "zzznew")); err != nil { - t.Fatalf("Failed to create bogus symlink: %s", err) - } - t.Logf("Created bogus symlink") - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - - // Should not be error, just no events for broken links (watching nothing) - if errorsReceived.value() > 0 { - t.Fatal("fsnotify errors have been received.") - } - if otherEventsReceived.value() > 0 { - t.Fatal("fsnotify other events received on the broken link") - } - - // Except for 1 create event (for the link itself) - if createEventsReceived.value() == 0 { - t.Fatal("fsnotify create events were not received after 500 ms") - } - if createEventsReceived.value() > 1 { - t.Fatal("fsnotify more create events received than expected") - } - - // Try closing the fsnotify instance - t.Log("calling Close()") - watcher.Close() -} - -func TestCyclicSymlink(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("symlinks don't work on Windows.") - } - - watcher := newWatcher(t) - - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - link := path.Join(testDir, "link") - if err := os.Symlink(".", link); err != nil { - t.Fatalf("could not make symlink: %v", err) - } - addWatch(t, watcher, testDir) - - var createEventsReceived counter - go func() { - for ev := range watcher.Events { - if ev.Op&Create == Create { - createEventsReceived.increment() - } - } - }() - - if err := os.Remove(link); err != nil { - t.Fatalf("Error removing link: %v", err) - } - - // It would be nice to be able to expect a delete event here, but kqueue has - // no way for us to get events on symlinks themselves, because opening them - // opens an fd to the file to which they point. - - if err := ioutil.WriteFile(link, []byte("foo"), 0700); err != nil { - t.Fatalf("could not make symlink: %v", err) - } - - // We expect this event to be received almost immediately, but let's wait 500 ms to be sure - time.Sleep(500 * time.Millisecond) - - if got := createEventsReceived.value(); got == 0 { - t.Errorf("want at least 1 create event got %v", got) - } - - watcher.Close() -} - -// TestConcurrentRemovalOfWatch tests that concurrent calls to RemoveWatch do not race. -// See https://codereview.appspot.com/103300045/ -// go test -test.run=TestConcurrentRemovalOfWatch -test.cpu=1,1,1,1,1 -race -func TestConcurrentRemovalOfWatch(t *testing.T) { - if runtime.GOOS != "darwin" { - t.Skip("regression test for race only present on darwin") - } - - // Create directory to watch - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - // Create a file before watching directory - testFileAlreadyExists := filepath.Join(testDir, "TestFsnotifyEventsExisting.testfile") - { - var f *os.File - f, err := os.OpenFile(testFileAlreadyExists, os.O_WRONLY|os.O_CREATE, 0666) - if err != nil { - t.Fatalf("creating test file failed: %s", err) - } - f.Sync() - f.Close() - } - - watcher := newWatcher(t) - defer watcher.Close() - - addWatch(t, watcher, testDir) - - // Test that RemoveWatch can be invoked concurrently, with no data races. - removed1 := make(chan struct{}) - go func() { - defer close(removed1) - watcher.Remove(testDir) - }() - removed2 := make(chan struct{}) - go func() { - close(removed2) - watcher.Remove(testDir) - }() - <-removed1 - <-removed2 -} - -func TestClose(t *testing.T) { - // Regression test for #59 bad file descriptor from Close - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - watcher := newWatcher(t) - if err := watcher.Add(testDir); err != nil { - t.Fatalf("Expected no error on Add, got %v", err) - } - err := watcher.Close() - if err != nil { - t.Fatalf("Expected no error on Close, got %v.", err) - } -} - -// TestRemoveWithClose tests if one can handle Remove events and, at the same -// time, close Watcher object without any data races. -func TestRemoveWithClose(t *testing.T) { - testDir := tempMkdir(t) - defer os.RemoveAll(testDir) - - const fileN = 200 - tempFiles := make([]string, 0, fileN) - for i := 0; i < fileN; i++ { - tempFiles = append(tempFiles, tempMkFile(t, testDir)) - } - watcher := newWatcher(t) - if err := watcher.Add(testDir); err != nil { - t.Fatalf("Expected no error on Add, got %v", err) - } - startC, stopC := make(chan struct{}), make(chan struct{}) - errC := make(chan error) - go func() { - for { - select { - case <-watcher.Errors: - case <-watcher.Events: - case <-stopC: - return - } - } - }() - go func() { - <-startC - for _, fileName := range tempFiles { - os.Remove(fileName) - } - }() - go func() { - <-startC - errC <- watcher.Close() - }() - close(startC) - defer close(stopC) - if err := <-errC; err != nil { - t.Fatalf("Expected no error on Close, got %v.", err) - } -} - -func testRename(file1, file2 string) error { - switch runtime.GOOS { - case "windows", "plan9": - return os.Rename(file1, file2) - default: - cmd := exec.Command("mv", file1, file2) - return cmd.Run() - } -} diff --git a/vendor/gopkg.in/go-playground/pool.v3/batch_limited_test.go b/vendor/gopkg.in/go-playground/pool.v3/batch_limited_test.go deleted file mode 100644 index 6eae3226cd..0000000000 --- a/vendor/gopkg.in/go-playground/pool.v3/batch_limited_test.go +++ /dev/null @@ -1,172 +0,0 @@ -package pool - -import ( - "sync" - "testing" - "time" - - . "gopkg.in/go-playground/assert.v1" -) - -// NOTES: -// - Run "go test" to run tests -// - Run "gocov test | gocov report" to report on test converage by file -// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called -// -// or -// -// -- may be a good idea to change to output path to somewherelike /tmp -// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html -// - -func TestLimitedBatch(t *testing.T) { - - newFunc := func(i int) func(WorkUnit) (interface{}, error) { - return func(WorkUnit) (interface{}, error) { - time.Sleep(time.Second * 1) - return i, nil - } - } - - pool := NewLimited(4) - defer pool.Close() - - batch := pool.Batch() - - for i := 0; i < 4; i++ { - batch.Queue(newFunc(i)) - } - - batch.QueueComplete() - - var count int - - for range batch.Results() { - count++ - } - - Equal(t, count, 4) -} - -func TestLimitedBatchGlobalPool(t *testing.T) { - - newFunc := func(i int) func(WorkUnit) (interface{}, error) { - return func(WorkUnit) (interface{}, error) { - time.Sleep(time.Second * 1) - return i, nil - } - } - - batch := limitedGpool.Batch() - - for i := 0; i < 4; i++ { - batch.Queue(newFunc(i)) - } - - batch.QueueComplete() - - var count int - - for range batch.Results() { - count++ - } - - Equal(t, count, 4) -} - -func TestLimitedBatchCancelItemsThrownAway(t *testing.T) { - - newFunc := func(i int) func(WorkUnit) (interface{}, error) { - return func(WorkUnit) (interface{}, error) { - time.Sleep(time.Second * 1) - return i, nil - } - } - - pool := NewLimited(4) - defer pool.Close() - - batch := pool.Batch() - - go func() { - for i := 0; i < 40; i++ { - batch.Queue(newFunc(i)) - } - }() - - batch.Cancel() - - var count int - - for range batch.Results() { - count++ - } - - NotEqual(t, count, 40) -} - -func TestLimitedBatchCancelItemsCancelledAfterward(t *testing.T) { - - newFunc := func(i int) func(WorkUnit) (interface{}, error) { - return func(WorkUnit) (interface{}, error) { - time.Sleep(time.Second * 1) - return i, nil - } - } - - pool := NewLimited(4) - defer pool.Close() - - batch := pool.Batch() - - go func() { - for i := 0; i < 40; i++ { - batch.Queue(newFunc(i)) - } - }() - - time.Sleep(time.Second * 2) - batch.Cancel() - - var count int - - for range batch.Results() { - count++ - } - - Equal(t, count, 40) -} - -func TestLimitedBatchWaitAll(t *testing.T) { - - var count int - var m sync.Mutex - - newFunc := func(i int) func(WorkUnit) (interface{}, error) { - return func(WorkUnit) (interface{}, error) { - time.Sleep(time.Second * 1) - m.Lock() - count++ - m.Unlock() - return i, nil - } - } - - pool := NewLimited(4) - defer pool.Close() - - batch := pool.Batch() - - go func() { - - for i := 0; i < 10; i++ { - batch.Queue(newFunc(i)) - } - - batch.QueueComplete() - }() - - batch.WaitAll() - - Equal(t, count, 10) -} diff --git a/vendor/gopkg.in/go-playground/pool.v3/batch_unlimited_test.go b/vendor/gopkg.in/go-playground/pool.v3/batch_unlimited_test.go deleted file mode 100644 index ad234bc564..0000000000 --- a/vendor/gopkg.in/go-playground/pool.v3/batch_unlimited_test.go +++ /dev/null @@ -1,172 +0,0 @@ -package pool - -import ( - "sync" - "testing" - "time" - - . "gopkg.in/go-playground/assert.v1" -) - -// NOTES: -// - Run "go test" to run tests -// - Run "gocov test | gocov report" to report on test converage by file -// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called -// -// or -// -// -- may be a good idea to change to output path to somewherelike /tmp -// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html -// - -func TestUnlimitedBatch(t *testing.T) { - - newFunc := func(i int) func(WorkUnit) (interface{}, error) { - return func(WorkUnit) (interface{}, error) { - time.Sleep(time.Second * 1) - return i, nil - } - } - - pool := New() - defer pool.Close() - - batch := pool.Batch() - - for i := 0; i < 4; i++ { - batch.Queue(newFunc(i)) - } - - batch.QueueComplete() - - var count int - - for range batch.Results() { - count++ - } - - Equal(t, count, 4) -} - -func TestUnlimitedBatchGlobalPool(t *testing.T) { - - newFunc := func(i int) func(WorkUnit) (interface{}, error) { - return func(WorkUnit) (interface{}, error) { - time.Sleep(time.Second * 1) - return i, nil - } - } - - batch := unlimitedGpool.Batch() - - for i := 0; i < 4; i++ { - batch.Queue(newFunc(i)) - } - - batch.QueueComplete() - - var count int - - for range batch.Results() { - count++ - } - - Equal(t, count, 4) -} - -func TestUnlimitedBatchCancelItemsThrownAway(t *testing.T) { - - newFunc := func(i int) func(WorkUnit) (interface{}, error) { - return func(WorkUnit) (interface{}, error) { - time.Sleep(time.Second * 1) - return i, nil - } - } - - pool := New() - defer pool.Close() - - batch := pool.Batch() - - go func() { - for i := 0; i < 40; i++ { - batch.Queue(newFunc(i)) - } - }() - - batch.Cancel() - - var count int - - for range batch.Results() { - count++ - } - - NotEqual(t, count, 40) -} - -func TestUnlimitedBatchCancelItemsCancelledAfterward(t *testing.T) { - - newFunc := func(i int) func(WorkUnit) (interface{}, error) { - return func(WorkUnit) (interface{}, error) { - time.Sleep(time.Second * 1) - return i, nil - } - } - - pool := New() - defer pool.Close() - - batch := pool.Batch() - - go func() { - for i := 0; i < 40; i++ { - batch.Queue(newFunc(i)) - } - }() - - time.Sleep(time.Second * 2) - batch.Cancel() - - var count int - - for range batch.Results() { - count++ - } - - Equal(t, count, 40) -} - -func TestUnlimitedBatchWaitAll(t *testing.T) { - - var count int - var m sync.Mutex - - newFunc := func(i int) func(WorkUnit) (interface{}, error) { - return func(WorkUnit) (interface{}, error) { - time.Sleep(time.Second * 1) - m.Lock() - count++ - m.Unlock() - return i, nil - } - } - - pool := New() - defer pool.Close() - - batch := pool.Batch() - - go func() { - - for i := 0; i < 10; i++ { - batch.Queue(newFunc(i)) - } - - batch.QueueComplete() - }() - - batch.WaitAll() - - Equal(t, count, 10) -} diff --git a/vendor/gopkg.in/go-playground/pool.v3/limited_pool_benchmarks_test.go b/vendor/gopkg.in/go-playground/pool.v3/limited_pool_benchmarks_test.go deleted file mode 100644 index 6ae5e9b97a..0000000000 --- a/vendor/gopkg.in/go-playground/pool.v3/limited_pool_benchmarks_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package pool - -import ( - "testing" - "time" -) - -func BenchmarkLimitedSmallRun(b *testing.B) { - - res := make([]WorkUnit, 10) - - b.ReportAllocs() - - pool := NewLimited(10) - defer pool.Close() - - fn := func(wu WorkUnit) (interface{}, error) { - time.Sleep(time.Millisecond * 500) - if wu.IsCancelled() { - return nil, nil - } - time.Sleep(time.Millisecond * 500) - return 1, nil - } - - for i := 0; i < 10; i++ { - res[i] = pool.Queue(fn) - } - - var count int - - for _, cw := range res { - - cw.Wait() - - if cw.Error() == nil { - count += cw.Value().(int) - } - } - - if count != 10 { - b.Fatal("Count Incorrect") - } -} - -func BenchmarkLimitedSmallCancel(b *testing.B) { - - res := make([]WorkUnit, 0, 20) - - b.ReportAllocs() - - pool := NewLimited(4) - defer pool.Close() - - newFunc := func(i int) WorkFunc { - return func(wu WorkUnit) (interface{}, error) { - time.Sleep(time.Millisecond * 500) - if wu.IsCancelled() { - return nil, nil - } - time.Sleep(time.Millisecond * 500) - return i, nil - } - } - - for i := 0; i < 20; i++ { - if i == 6 { - pool.Cancel() - } - res = append(res, pool.Queue(newFunc(i))) - } - - for _, wrk := range res { - if wrk == nil { - continue - } - wrk.Wait() - } -} - -func BenchmarkLimitedLargeCancel(b *testing.B) { - - res := make([]WorkUnit, 0, 1000) - - b.ReportAllocs() - - pool := NewLimited(4) - defer pool.Close() - - newFunc := func(i int) WorkFunc { - return func(wu WorkUnit) (interface{}, error) { - time.Sleep(time.Millisecond * 500) - if wu.IsCancelled() { - return nil, nil - } - time.Sleep(time.Millisecond * 500) - return i, nil - } - } - - for i := 0; i < 1000; i++ { - if i == 6 { - pool.Cancel() - } - res = append(res, pool.Queue(newFunc(i))) - } - - for _, wrk := range res { - if wrk == nil { - continue - } - wrk.Wait() - } -} - -func BenchmarkLimitedOverconsumeLargeRun(b *testing.B) { - - res := make([]WorkUnit, 100) - - b.ReportAllocs() - - pool := NewLimited(25) - defer pool.Close() - - newFunc := func(i int) WorkFunc { - return func(wu WorkUnit) (interface{}, error) { - time.Sleep(time.Millisecond * 500) - if wu.IsCancelled() { - return nil, nil - } - time.Sleep(time.Millisecond * 500) - return 1, nil - } - } - - for i := 0; i < 100; i++ { - res[i] = pool.Queue(newFunc(i)) - } - - var count int - - for _, cw := range res { - - cw.Wait() - - count += cw.Value().(int) - } - - if count != 100 { - b.Fatalf("Count Incorrect, Expected '100' Got '%d'", count) - } -} - -func BenchmarkLimitedBatchSmallRun(b *testing.B) { - - fn := func(wu WorkUnit) (interface{}, error) { - time.Sleep(time.Millisecond * 500) - if wu.IsCancelled() { - return nil, nil - } - time.Sleep(time.Millisecond * 500) - return 1, nil - } - - pool := NewLimited(10) - defer pool.Close() - - batch := pool.Batch() - - for i := 0; i < 10; i++ { - batch.Queue(fn) - } - - batch.QueueComplete() - - var count int - - for cw := range batch.Results() { - count += cw.Value().(int) - } - - if count != 10 { - b.Fatal("Count Incorrect") - } -} diff --git a/vendor/gopkg.in/go-playground/pool.v3/limited_pool_test.go b/vendor/gopkg.in/go-playground/pool.v3/limited_pool_test.go deleted file mode 100644 index d3323e4d37..0000000000 --- a/vendor/gopkg.in/go-playground/pool.v3/limited_pool_test.go +++ /dev/null @@ -1,177 +0,0 @@ -package pool - -import ( - "sync" - "testing" - "time" - - . "gopkg.in/go-playground/assert.v1" -) - -// NOTES: -// - Run "go test" to run tests -// - Run "gocov test | gocov report" to report on test converage by file -// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called -// -// or -// -// -- may be a good idea to change to output path to somewherelike /tmp -// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html -// - -func TestPool(t *testing.T) { - - var res []WorkUnit - - pool := NewLimited(4) - defer pool.Close() - - newFunc := func(d time.Duration) WorkFunc { - return func(WorkUnit) (interface{}, error) { - time.Sleep(d) - return nil, nil - } - } - - for i := 0; i < 4; i++ { - wu := pool.Queue(newFunc(time.Second * 1)) - res = append(res, wu) - } - - var count int - - for _, wu := range res { - wu.Wait() - Equal(t, wu.Error(), nil) - Equal(t, wu.Value(), nil) - count++ - } - - Equal(t, count, 4) - - pool.Close() // testing no error occurs as Close will be called twice once defer pool.Close() fires -} - -func TestCancel(t *testing.T) { - - m := new(sync.RWMutex) - var closed bool - c := make(chan WorkUnit, 100) - - pool := limitedGpool - defer pool.Close() - - newFunc := func(d time.Duration) WorkFunc { - return func(WorkUnit) (interface{}, error) { - time.Sleep(d) - return 1, nil - } - } - - go func(ch chan WorkUnit) { - for i := 0; i < 40; i++ { - - go func(ch chan WorkUnit) { - m.RLock() - if closed { - m.RUnlock() - return - } - - ch <- pool.Queue(newFunc(time.Second * 1)) - m.RUnlock() - }(ch) - } - }(c) - - time.Sleep(time.Second * 1) - pool.Cancel() - m.Lock() - closed = true - close(c) - m.Unlock() - - var count int - - for wu := range c { - wu.Wait() - - if wu.Error() != nil { - _, ok := wu.Error().(*ErrCancelled) - if !ok { - _, ok = wu.Error().(*ErrPoolClosed) - if ok { - Equal(t, wu.Error().Error(), "ERROR: Work Unit added/run after the pool had been closed or cancelled") - } - } else { - Equal(t, wu.Error().Error(), "ERROR: Work Unit Cancelled") - } - - Equal(t, ok, true) - continue - } - - count += wu.Value().(int) - } - - NotEqual(t, count, 40) - - // reset and test again - pool.Reset() - - wrk := pool.Queue(newFunc(time.Millisecond * 300)) - wrk.Wait() - - _, ok := wrk.Value().(int) - Equal(t, ok, true) - - wrk = pool.Queue(newFunc(time.Millisecond * 300)) - time.Sleep(time.Second * 1) - wrk.Cancel() - wrk.Wait() // proving we don't get stuck here after cancel - Equal(t, wrk.Error(), nil) - - pool.Reset() // testing that we can do this and nothing bad will happen as it checks if pool closed - - pool.Close() - - wu := pool.Queue(newFunc(time.Second * 1)) - wu.Wait() - NotEqual(t, wu.Error(), nil) - Equal(t, wu.Error().Error(), "ERROR: Work Unit added/run after the pool had been closed or cancelled") -} - -func TestPanicRecovery(t *testing.T) { - - pool := NewLimited(2) - defer pool.Close() - - newFunc := func(d time.Duration, i int) WorkFunc { - return func(WorkUnit) (interface{}, error) { - if i == 1 { - panic("OMG OMG OMG! something bad happened!") - } - time.Sleep(d) - return 1, nil - } - } - - var wrk WorkUnit - for i := 0; i < 4; i++ { - time.Sleep(time.Second * 1) - if i == 1 { - wrk = pool.Queue(newFunc(time.Second*1, i)) - continue - } - pool.Queue(newFunc(time.Second*1, i)) - } - wrk.Wait() - - NotEqual(t, wrk.Error(), nil) - Equal(t, wrk.Error().Error()[0:90], "ERROR: Work Unit failed due to a recoverable error: 'OMG OMG OMG! something bad happened!'") - -} - -func TestBadWorkerCount(t *testing.T) { - PanicMatches(t, func() { NewLimited(0) }, "invalid workers '0'") -} diff --git a/vendor/gopkg.in/go-playground/pool.v3/pool_test.go b/vendor/gopkg.in/go-playground/pool.v3/pool_test.go deleted file mode 100644 index d79375553d..0000000000 --- a/vendor/gopkg.in/go-playground/pool.v3/pool_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package pool - -import ( - "os" - "testing" -) - -// NOTES: -// - Run "go test" to run tests -// - Run "gocov test | gocov report" to report on test converage by file -// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called -// -// or -// -// -- may be a good idea to change to output path to somewherelike /tmp -// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html -// - -// global pool for testing long running pool -var limitedGpool Pool - -var unlimitedGpool Pool - -func TestMain(m *testing.M) { - - // setup - limitedGpool = NewLimited(4) - defer limitedGpool.Close() - - unlimitedGpool = New() - defer unlimitedGpool.Close() - - os.Exit(m.Run()) - - // teardown -} diff --git a/vendor/gopkg.in/go-playground/pool.v3/unlimited_pool_benchmarks_test.go b/vendor/gopkg.in/go-playground/pool.v3/unlimited_pool_benchmarks_test.go deleted file mode 100644 index 572a554364..0000000000 --- a/vendor/gopkg.in/go-playground/pool.v3/unlimited_pool_benchmarks_test.go +++ /dev/null @@ -1,185 +0,0 @@ -package pool - -import ( - "testing" - "time" -) - -func BenchmarkUnlimitedSmallRun(b *testing.B) { - - res := make([]WorkUnit, 10) - - b.ReportAllocs() - - pool := New() - defer pool.Close() - - fn := func(wu WorkUnit) (interface{}, error) { - time.Sleep(time.Millisecond * 500) - if wu.IsCancelled() { - return nil, nil - } - time.Sleep(time.Millisecond * 500) - return 1, nil - } - - for i := 0; i < 10; i++ { - res[i] = pool.Queue(fn) - } - - var count int - - for _, cw := range res { - - cw.Wait() - - if cw.Error() == nil { - count += cw.Value().(int) - } - } - - if count != 10 { - b.Fatal("Count Incorrect") - } -} - -func BenchmarkUnlimitedSmallCancel(b *testing.B) { - - res := make([]WorkUnit, 0, 20) - - b.ReportAllocs() - - pool := New() - defer pool.Close() - - newFunc := func(i int) WorkFunc { - return func(wu WorkUnit) (interface{}, error) { - time.Sleep(time.Millisecond * 500) - if wu.IsCancelled() { - return nil, nil - } - time.Sleep(time.Millisecond * 500) - return i, nil - } - } - - for i := 0; i < 20; i++ { - if i == 6 { - pool.Cancel() - } - res = append(res, pool.Queue(newFunc(i))) - } - - for _, wrk := range res { - if wrk == nil { - continue - } - wrk.Wait() - } -} - -func BenchmarkUnlimitedLargeCancel(b *testing.B) { - - res := make([]WorkUnit, 0, 1000) - - b.ReportAllocs() - - pool := New() - defer pool.Close() - - newFunc := func(i int) WorkFunc { - return func(wu WorkUnit) (interface{}, error) { - time.Sleep(time.Millisecond * 500) - if wu.IsCancelled() { - return nil, nil - } - time.Sleep(time.Millisecond * 500) - return i, nil - } - } - - for i := 0; i < 1000; i++ { - if i == 6 { - pool.Cancel() - } - res = append(res, pool.Queue(newFunc(i))) - } - - for _, wrk := range res { - if wrk == nil { - continue - } - wrk.Wait() - } -} - -func BenchmarkUnlimitedLargeRun(b *testing.B) { - - res := make([]WorkUnit, 100) - - b.ReportAllocs() - - pool := New() - defer pool.Close() - - newFunc := func(i int) WorkFunc { - return func(wu WorkUnit) (interface{}, error) { - time.Sleep(time.Millisecond * 500) - if wu.IsCancelled() { - return nil, nil - } - time.Sleep(time.Millisecond * 500) - return 1, nil - } - } - - for i := 0; i < 100; i++ { - res[i] = pool.Queue(newFunc(i)) - } - - var count int - - for _, cw := range res { - - cw.Wait() - - count += cw.Value().(int) - } - - if count != 100 { - b.Fatalf("Count Incorrect, Expected '100' Got '%d'", count) - } -} - -func BenchmarkUnlimitedBatchSmallRun(b *testing.B) { - - fn := func(wu WorkUnit) (interface{}, error) { - time.Sleep(time.Millisecond * 500) - if wu.IsCancelled() { - return nil, nil - } - time.Sleep(time.Millisecond * 500) - return 1, nil - } - - pool := New() - defer pool.Close() - - batch := pool.Batch() - - for i := 0; i < 10; i++ { - batch.Queue(fn) - } - - batch.QueueComplete() - - var count int - - for cw := range batch.Results() { - count += cw.Value().(int) - } - - if count != 10 { - b.Fatal("Count Incorrect") - } -} diff --git a/vendor/gopkg.in/go-playground/pool.v3/unlimited_pool_test.go b/vendor/gopkg.in/go-playground/pool.v3/unlimited_pool_test.go deleted file mode 100644 index 6ac9623b8c..0000000000 --- a/vendor/gopkg.in/go-playground/pool.v3/unlimited_pool_test.go +++ /dev/null @@ -1,194 +0,0 @@ -package pool - -import ( - "sync" - "testing" - "time" - - . "gopkg.in/go-playground/assert.v1" -) - -// NOTES: -// - Run "go test" to run tests -// - Run "gocov test | gocov report" to report on test converage by file -// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called -// -// or -// -// -- may be a good idea to change to output path to somewherelike /tmp -// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html -// - -func TestUnlimitedPool(t *testing.T) { - - var res []WorkUnit - - pool := New() - defer pool.Close() - - newFunc := func(d time.Duration) WorkFunc { - return func(WorkUnit) (interface{}, error) { - time.Sleep(d) - return nil, nil - } - } - - for i := 0; i < 4; i++ { - wu := pool.Queue(newFunc(time.Second * 1)) - res = append(res, wu) - } - - var count int - - for _, wu := range res { - wu.Wait() - Equal(t, wu.Error(), nil) - Equal(t, wu.Value(), nil) - count++ - } - - Equal(t, count, 4) - - pool.Close() // testing no error occurs as Close will be called twice once defer pool.Close() fires -} - -func TestUnlimitedCancel(t *testing.T) { - - m := new(sync.RWMutex) - var closed bool - c := make(chan WorkUnit, 100) - - pool := unlimitedGpool - defer pool.Close() - - newFunc := func(d time.Duration) WorkFunc { - return func(WorkUnit) (interface{}, error) { - time.Sleep(d) - return 1, nil - } - } - - go func(ch chan WorkUnit) { - for i := 0; i < 40; i++ { - - go func(ch chan WorkUnit) { - m.RLock() - if !closed { - ch <- pool.Queue(newFunc(time.Second * 1)) - } - m.RUnlock() - }(ch) - } - }(c) - - time.Sleep(time.Second * 1) - pool.Cancel() - m.Lock() - closed = true - close(c) - m.Unlock() - - var count int - - for wu := range c { - wu.Wait() - - if wu.Error() != nil { - _, ok := wu.Error().(*ErrCancelled) - if !ok { - _, ok = wu.Error().(*ErrPoolClosed) - if ok { - Equal(t, wu.Error().Error(), "ERROR: Work Unit added/run after the pool had been closed or cancelled") - } - } else { - Equal(t, wu.Error().Error(), "ERROR: Work Unit Cancelled") - } - - Equal(t, ok, true) - continue - } - - count += wu.Value().(int) - } - - NotEqual(t, count, 40) - - // reset and test again - pool.Reset() - - wrk := pool.Queue(newFunc(time.Millisecond * 300)) - wrk.Wait() - - _, ok := wrk.Value().(int) - Equal(t, ok, true) - - wrk = pool.Queue(newFunc(time.Millisecond * 300)) - time.Sleep(time.Second * 1) - wrk.Cancel() - wrk.Wait() // proving we don't get stuck here after cancel - Equal(t, wrk.Error(), nil) - - pool.Reset() // testing that we can do this and nothing bad will happen as it checks if pool closed - - pool.Close() - - wu := pool.Queue(newFunc(time.Second * 1)) - wu.Wait() - NotEqual(t, wu.Error(), nil) - Equal(t, wu.Error().Error(), "ERROR: Work Unit added/run after the pool had been closed or cancelled") -} - -func TestCancelFromWithin(t *testing.T) { - pool := New() - defer pool.Close() - - newFunc := func(d time.Duration) WorkFunc { - return func(wu WorkUnit) (interface{}, error) { - time.Sleep(d) - if wu.IsCancelled() { - return nil, nil - } - - return 1, nil - } - } - - q := pool.Queue(newFunc(time.Second * 5)) - - time.Sleep(time.Second * 2) - pool.Cancel() - - Equal(t, q.Value() == nil, true) - NotEqual(t, q.Error(), nil) - Equal(t, q.Error().Error(), "ERROR: Work Unit Cancelled") -} - -func TestUnlimitedPanicRecovery(t *testing.T) { - - pool := New() - defer pool.Close() - - newFunc := func(d time.Duration, i int) WorkFunc { - return func(WorkUnit) (interface{}, error) { - if i == 1 { - panic("OMG OMG OMG! something bad happened!") - } - time.Sleep(d) - return 1, nil - } - } - - var wrk WorkUnit - for i := 0; i < 4; i++ { - time.Sleep(time.Second * 1) - if i == 1 { - wrk = pool.Queue(newFunc(time.Second*1, i)) - continue - } - pool.Queue(newFunc(time.Second*1, i)) - } - wrk.Wait() - - NotEqual(t, wrk.Error(), nil) - Equal(t, wrk.Error().Error()[0:90], "ERROR: Work Unit failed due to a recoverable error: 'OMG OMG OMG! something bad happened!'") -} diff --git a/vendor/gopkg.in/inf.v0/benchmark_test.go b/vendor/gopkg.in/inf.v0/benchmark_test.go deleted file mode 100644 index 27071da0e8..0000000000 --- a/vendor/gopkg.in/inf.v0/benchmark_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package inf - -import ( - "fmt" - "math/big" - "math/rand" - "sync" - "testing" -) - -const maxcap = 1024 * 1024 -const bits = 256 -const maxscale = 32 - -var once sync.Once - -var decInput [][2]Dec -var intInput [][2]big.Int - -var initBench = func() { - decInput = make([][2]Dec, maxcap) - intInput = make([][2]big.Int, maxcap) - max := new(big.Int).Lsh(big.NewInt(1), bits) - r := rand.New(rand.NewSource(0)) - for i := 0; i < cap(decInput); i++ { - decInput[i][0].SetUnscaledBig(new(big.Int).Rand(r, max)). - SetScale(Scale(r.Int31n(int32(2*maxscale-1)) - int32(maxscale))) - decInput[i][1].SetUnscaledBig(new(big.Int).Rand(r, max)). - SetScale(Scale(r.Int31n(int32(2*maxscale-1)) - int32(maxscale))) - } - for i := 0; i < cap(intInput); i++ { - intInput[i][0].Rand(r, max) - intInput[i][1].Rand(r, max) - } -} - -func doBenchmarkDec1(b *testing.B, f func(z *Dec)) { - once.Do(initBench) - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - f(&decInput[i%maxcap][0]) - } -} - -func doBenchmarkDec2(b *testing.B, f func(x, y *Dec)) { - once.Do(initBench) - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - f(&decInput[i%maxcap][0], &decInput[i%maxcap][1]) - } -} - -func doBenchmarkInt1(b *testing.B, f func(z *big.Int)) { - once.Do(initBench) - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - f(&intInput[i%maxcap][0]) - } -} - -func doBenchmarkInt2(b *testing.B, f func(x, y *big.Int)) { - once.Do(initBench) - b.ResetTimer() - b.StartTimer() - for i := 0; i < b.N; i++ { - f(&intInput[i%maxcap][0], &intInput[i%maxcap][1]) - } -} - -func Benchmark_Dec_String(b *testing.B) { - doBenchmarkDec1(b, func(x *Dec) { - x.String() - }) -} - -func Benchmark_Dec_StringScan(b *testing.B) { - doBenchmarkDec1(b, func(x *Dec) { - s := x.String() - d := new(Dec) - fmt.Sscan(s, d) - }) -} - -func Benchmark_Dec_GobEncode(b *testing.B) { - doBenchmarkDec1(b, func(x *Dec) { - x.GobEncode() - }) -} - -func Benchmark_Dec_GobEnDecode(b *testing.B) { - doBenchmarkDec1(b, func(x *Dec) { - g, _ := x.GobEncode() - new(Dec).GobDecode(g) - }) -} - -func Benchmark_Dec_Add(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - ys := y.Scale() - y.SetScale(x.Scale()) - _ = new(Dec).Add(x, y) - y.SetScale(ys) - }) -} - -func Benchmark_Dec_AddMixed(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - _ = new(Dec).Add(x, y) - }) -} - -func Benchmark_Dec_Sub(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - ys := y.Scale() - y.SetScale(x.Scale()) - _ = new(Dec).Sub(x, y) - y.SetScale(ys) - }) -} - -func Benchmark_Dec_SubMixed(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - _ = new(Dec).Sub(x, y) - }) -} - -func Benchmark_Dec_Mul(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - _ = new(Dec).Mul(x, y) - }) -} - -func Benchmark_Dec_Mul_QuoExact(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - v := new(Dec).Mul(x, y) - _ = new(Dec).QuoExact(v, y) - }) -} - -func Benchmark_Dec_QuoRound_Fixed_Down(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - _ = new(Dec).QuoRound(x, y, 0, RoundDown) - }) -} - -func Benchmark_Dec_QuoRound_Fixed_HalfUp(b *testing.B) { - doBenchmarkDec2(b, func(x, y *Dec) { - _ = new(Dec).QuoRound(x, y, 0, RoundHalfUp) - }) -} - -func Benchmark_Int_String(b *testing.B) { - doBenchmarkInt1(b, func(x *big.Int) { - x.String() - }) -} - -func Benchmark_Int_StringScan(b *testing.B) { - doBenchmarkInt1(b, func(x *big.Int) { - s := x.String() - d := new(big.Int) - fmt.Sscan(s, d) - }) -} - -func Benchmark_Int_GobEncode(b *testing.B) { - doBenchmarkInt1(b, func(x *big.Int) { - x.GobEncode() - }) -} - -func Benchmark_Int_GobEnDecode(b *testing.B) { - doBenchmarkInt1(b, func(x *big.Int) { - g, _ := x.GobEncode() - new(big.Int).GobDecode(g) - }) -} - -func Benchmark_Int_Add(b *testing.B) { - doBenchmarkInt2(b, func(x, y *big.Int) { - _ = new(big.Int).Add(x, y) - }) -} - -func Benchmark_Int_Sub(b *testing.B) { - doBenchmarkInt2(b, func(x, y *big.Int) { - _ = new(big.Int).Sub(x, y) - }) -} - -func Benchmark_Int_Mul(b *testing.B) { - doBenchmarkInt2(b, func(x, y *big.Int) { - _ = new(big.Int).Mul(x, y) - }) -} - -func Benchmark_Int_Quo(b *testing.B) { - doBenchmarkInt2(b, func(x, y *big.Int) { - _ = new(big.Int).Quo(x, y) - }) -} - -func Benchmark_Int_QuoRem(b *testing.B) { - doBenchmarkInt2(b, func(x, y *big.Int) { - _, _ = new(big.Int).QuoRem(x, y, new(big.Int)) - }) -} diff --git a/vendor/gopkg.in/inf.v0/dec.go b/vendor/gopkg.in/inf.v0/dec.go index 3b4afedf1a..26548b63ce 100644 --- a/vendor/gopkg.in/inf.v0/dec.go +++ b/vendor/gopkg.in/inf.v0/dec.go @@ -104,7 +104,7 @@ var bigInt = [...]*big.Int{ var exp10cache [64]big.Int = func() [64]big.Int { e10, e10i := [64]big.Int{}, bigInt[1] - for i, _ := range e10 { + for i := range e10 { e10[i].Set(e10i) e10i = new(big.Int).Mul(e10i, bigInt[10]) } diff --git a/vendor/gopkg.in/inf.v0/dec_go1_2_test.go b/vendor/gopkg.in/inf.v0/dec_go1_2_test.go deleted file mode 100644 index 5df0f7b553..0000000000 --- a/vendor/gopkg.in/inf.v0/dec_go1_2_test.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build go1.2 - -package inf - -import ( - "encoding" - "encoding/json" - "testing" -) - -var _ encoding.TextMarshaler = new(Dec) -var _ encoding.TextUnmarshaler = new(Dec) - -type Obj struct { - Val *Dec -} - -func TestDecJsonMarshalUnmarshal(t *testing.T) { - o := Obj{Val: NewDec(123, 2)} - js, err := json.Marshal(o) - if err != nil { - t.Fatalf("json.Marshal(%v): got %v, want ok", o, err) - } - o2 := &Obj{} - err = json.Unmarshal(js, o2) - if err != nil { - t.Fatalf("json.Unmarshal(%#q): got %v, want ok", js, err) - } - if o.Val.Scale() != o2.Val.Scale() || - o.Val.UnscaledBig().Cmp(o2.Val.UnscaledBig()) != 0 { - t.Fatalf("json.Unmarshal(json.Marshal(%v)): want %v, got %v", o, o, o2) - } -} diff --git a/vendor/gopkg.in/inf.v0/dec_internal_test.go b/vendor/gopkg.in/inf.v0/dec_internal_test.go deleted file mode 100644 index d4fbe3e5bc..0000000000 --- a/vendor/gopkg.in/inf.v0/dec_internal_test.go +++ /dev/null @@ -1,40 +0,0 @@ -package inf - -import ( - "math/big" - "testing" -) - -var decQuoRemZZZ = []struct { - z, x, y *Dec - r *big.Rat - srA, srB int -}{ - // basic examples - {NewDec(1, 0), NewDec(2, 0), NewDec(2, 0), big.NewRat(0, 1), 0, 1}, - {NewDec(15, 1), NewDec(3, 0), NewDec(2, 0), big.NewRat(0, 1), 0, 1}, - {NewDec(1, 1), NewDec(1, 0), NewDec(10, 0), big.NewRat(0, 1), 0, 1}, - {NewDec(0, 0), NewDec(2, 0), NewDec(3, 0), big.NewRat(2, 3), 1, 1}, - {NewDec(0, 0), NewDec(2, 0), NewDec(6, 0), big.NewRat(1, 3), 1, 1}, - {NewDec(1, 1), NewDec(2, 0), NewDec(12, 0), big.NewRat(2, 3), 1, 1}, - - // examples from the Go Language Specification - {NewDec(1, 0), NewDec(5, 0), NewDec(3, 0), big.NewRat(2, 3), 1, 1}, - {NewDec(-1, 0), NewDec(-5, 0), NewDec(3, 0), big.NewRat(-2, 3), -1, 1}, - {NewDec(-1, 0), NewDec(5, 0), NewDec(-3, 0), big.NewRat(-2, 3), 1, -1}, - {NewDec(1, 0), NewDec(-5, 0), NewDec(-3, 0), big.NewRat(2, 3), -1, -1}, -} - -func TestDecQuoRem(t *testing.T) { - for i, a := range decQuoRemZZZ { - z, rA, rB := new(Dec), new(big.Int), new(big.Int) - s := scaleQuoExact{}.Scale(a.x, a.y) - z.quoRem(a.x, a.y, s, true, rA, rB) - if a.z.Cmp(z) != 0 || a.r.Cmp(new(big.Rat).SetFrac(rA, rB)) != 0 { - t.Errorf("#%d QuoRemZZZ got %v, %v, %v; expected %v, %v", i, z, rA, rB, a.z, a.r) - } - if a.srA != rA.Sign() || a.srB != rB.Sign() { - t.Errorf("#%d QuoRemZZZ wrong signs, got %v, %v; expected %v, %v", i, rA.Sign(), rB.Sign(), a.srA, a.srB) - } - } -} diff --git a/vendor/gopkg.in/inf.v0/dec_test.go b/vendor/gopkg.in/inf.v0/dec_test.go deleted file mode 100644 index e4b09b3fdc..0000000000 --- a/vendor/gopkg.in/inf.v0/dec_test.go +++ /dev/null @@ -1,379 +0,0 @@ -package inf_test - -import ( - "bytes" - "encoding/gob" - "fmt" - "math/big" - "strings" - "testing" - - "gopkg.in/inf.v0" -) - -type decFunZZ func(z, x, y *inf.Dec) *inf.Dec -type decArgZZ struct { - z, x, y *inf.Dec -} - -var decSumZZ = []decArgZZ{ - {inf.NewDec(0, 0), inf.NewDec(0, 0), inf.NewDec(0, 0)}, - {inf.NewDec(1, 0), inf.NewDec(1, 0), inf.NewDec(0, 0)}, - {inf.NewDec(1111111110, 0), inf.NewDec(123456789, 0), inf.NewDec(987654321, 0)}, - {inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(0, 0)}, - {inf.NewDec(864197532, 0), inf.NewDec(-123456789, 0), inf.NewDec(987654321, 0)}, - {inf.NewDec(-1111111110, 0), inf.NewDec(-123456789, 0), inf.NewDec(-987654321, 0)}, - {inf.NewDec(12, 2), inf.NewDec(1, 1), inf.NewDec(2, 2)}, -} - -var decProdZZ = []decArgZZ{ - {inf.NewDec(0, 0), inf.NewDec(0, 0), inf.NewDec(0, 0)}, - {inf.NewDec(0, 0), inf.NewDec(1, 0), inf.NewDec(0, 0)}, - {inf.NewDec(1, 0), inf.NewDec(1, 0), inf.NewDec(1, 0)}, - {inf.NewDec(-991*991, 0), inf.NewDec(991, 0), inf.NewDec(-991, 0)}, - {inf.NewDec(2, 3), inf.NewDec(1, 1), inf.NewDec(2, 2)}, - {inf.NewDec(2, -3), inf.NewDec(1, -1), inf.NewDec(2, -2)}, - {inf.NewDec(2, 3), inf.NewDec(1, 1), inf.NewDec(2, 2)}, -} - -func TestDecSignZ(t *testing.T) { - var zero inf.Dec - for _, a := range decSumZZ { - s := a.z.Sign() - e := a.z.Cmp(&zero) - if s != e { - t.Errorf("got %d; want %d for z = %v", s, e, a.z) - } - } -} - -func TestDecAbsZ(t *testing.T) { - var zero inf.Dec - for _, a := range decSumZZ { - var z inf.Dec - z.Abs(a.z) - var e inf.Dec - e.Set(a.z) - if e.Cmp(&zero) < 0 { - e.Sub(&zero, &e) - } - if z.Cmp(&e) != 0 { - t.Errorf("got z = %v; want %v", z, e) - } - } -} - -func testDecFunZZ(t *testing.T, msg string, f decFunZZ, a decArgZZ) { - var z inf.Dec - f(&z, a.x, a.y) - if (&z).Cmp(a.z) != 0 { - t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, &z, a.z) - } -} - -func TestDecSumZZ(t *testing.T) { - AddZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Add(x, y) } - SubZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Sub(x, y) } - for _, a := range decSumZZ { - arg := a - testDecFunZZ(t, "AddZZ", AddZZ, arg) - - arg = decArgZZ{a.z, a.y, a.x} - testDecFunZZ(t, "AddZZ symmetric", AddZZ, arg) - - arg = decArgZZ{a.x, a.z, a.y} - testDecFunZZ(t, "SubZZ", SubZZ, arg) - - arg = decArgZZ{a.y, a.z, a.x} - testDecFunZZ(t, "SubZZ symmetric", SubZZ, arg) - } -} - -func TestDecProdZZ(t *testing.T) { - MulZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Mul(x, y) } - for _, a := range decProdZZ { - arg := a - testDecFunZZ(t, "MulZZ", MulZZ, arg) - - arg = decArgZZ{a.z, a.y, a.x} - testDecFunZZ(t, "MulZZ symmetric", MulZZ, arg) - } -} - -var decUnscaledTests = []struct { - d *inf.Dec - u int64 // ignored when ok == false - ok bool -}{ - {new(inf.Dec), 0, true}, - {inf.NewDec(-1<<63, 0), -1 << 63, true}, - {inf.NewDec(-(-1<<63 + 1), 0), -(-1<<63 + 1), true}, - {new(inf.Dec).Neg(inf.NewDec(-1<<63, 0)), 0, false}, - {new(inf.Dec).Sub(inf.NewDec(-1<<63, 0), inf.NewDec(1, 0)), 0, false}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), 0, false}, -} - -func TestDecUnscaled(t *testing.T) { - for i, tt := range decUnscaledTests { - u, ok := tt.d.Unscaled() - if ok != tt.ok { - t.Errorf("#%d Unscaled: got %v, expected %v", i, ok, tt.ok) - } else if ok && u != tt.u { - t.Errorf("#%d Unscaled: got %v, expected %v", i, u, tt.u) - } - } -} - -var decRoundTests = [...]struct { - in *inf.Dec - s inf.Scale - r inf.Rounder - exp *inf.Dec -}{ - {inf.NewDec(123424999999999993, 15), 2, inf.RoundHalfUp, inf.NewDec(12342, 2)}, - {inf.NewDec(123425000000000001, 15), 2, inf.RoundHalfUp, inf.NewDec(12343, 2)}, - {inf.NewDec(123424999999999993, 15), 15, inf.RoundHalfUp, inf.NewDec(123424999999999993, 15)}, - {inf.NewDec(123424999999999993, 15), 16, inf.RoundHalfUp, inf.NewDec(1234249999999999930, 16)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -1, inf.RoundHalfUp, inf.NewDec(1844674407370955162, -1)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -2, inf.RoundHalfUp, inf.NewDec(184467440737095516, -2)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -3, inf.RoundHalfUp, inf.NewDec(18446744073709552, -3)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -4, inf.RoundHalfUp, inf.NewDec(1844674407370955, -4)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -5, inf.RoundHalfUp, inf.NewDec(184467440737096, -5)}, - {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -6, inf.RoundHalfUp, inf.NewDec(18446744073710, -6)}, -} - -func TestDecRound(t *testing.T) { - for i, tt := range decRoundTests { - z := new(inf.Dec).Round(tt.in, tt.s, tt.r) - if tt.exp.Cmp(z) != 0 { - t.Errorf("#%d Round got %v; expected %v", i, z, tt.exp) - } - } -} - -var decStringTests = []struct { - in string - out string - val int64 - scale inf.Scale // skip SetString if negative - ok bool - scanOk bool -}{ - {in: "", ok: false, scanOk: false}, - {in: "a", ok: false, scanOk: false}, - {in: "z", ok: false, scanOk: false}, - {in: "+", ok: false, scanOk: false}, - {in: "-", ok: false, scanOk: false}, - {in: "g", ok: false, scanOk: false}, - {in: ".", ok: false, scanOk: false}, - {in: ".-0", ok: false, scanOk: false}, - {in: ".+0", ok: false, scanOk: false}, - // Scannable but not SetStringable - {"0b", "ignored", 0, 0, false, true}, - {"0x", "ignored", 0, 0, false, true}, - {"0xg", "ignored", 0, 0, false, true}, - {"0.0g", "ignored", 0, 1, false, true}, - // examples from godoc for Dec - {"0", "0", 0, 0, true, true}, - {"0.00", "0.00", 0, 2, true, true}, - {"ignored", "0", 0, -2, true, false}, - {"1", "1", 1, 0, true, true}, - {"1.00", "1.00", 100, 2, true, true}, - {"10", "10", 10, 0, true, true}, - {"ignored", "10", 1, -1, true, false}, - // other tests - {"+0", "0", 0, 0, true, true}, - {"-0", "0", 0, 0, true, true}, - {"0.0", "0.0", 0, 1, true, true}, - {"0.1", "0.1", 1, 1, true, true}, - {"0.", "0", 0, 0, true, true}, - {"-10", "-10", -1, -1, true, true}, - {"-1", "-1", -1, 0, true, true}, - {"-0.1", "-0.1", -1, 1, true, true}, - {"-0.01", "-0.01", -1, 2, true, true}, - {"+0.", "0", 0, 0, true, true}, - {"-0.", "0", 0, 0, true, true}, - {".0", "0.0", 0, 1, true, true}, - {"+.0", "0.0", 0, 1, true, true}, - {"-.0", "0.0", 0, 1, true, true}, - {"0.0000000000", "0.0000000000", 0, 10, true, true}, - {"0.0000000001", "0.0000000001", 1, 10, true, true}, - {"-0.0000000000", "0.0000000000", 0, 10, true, true}, - {"-0.0000000001", "-0.0000000001", -1, 10, true, true}, - {"-10", "-10", -10, 0, true, true}, - {"+10", "10", 10, 0, true, true}, - {"00", "0", 0, 0, true, true}, - {"023", "23", 23, 0, true, true}, // decimal, not octal - {"-02.3", "-2.3", -23, 1, true, true}, // decimal, not octal -} - -func TestDecGetString(t *testing.T) { - z := new(inf.Dec) - for i, test := range decStringTests { - if !test.ok { - continue - } - z.SetUnscaled(test.val) - z.SetScale(test.scale) - - s := z.String() - if s != test.out { - t.Errorf("#%da got %s; want %s", i, s, test.out) - } - - s = fmt.Sprintf("%d", z) - if s != test.out { - t.Errorf("#%db got %s; want %s", i, s, test.out) - } - } -} - -func TestDecSetString(t *testing.T) { - tmp := new(inf.Dec) - for i, test := range decStringTests { - if test.scale < 0 { - // SetString only supports scale >= 0 - continue - } - // initialize to a non-zero value so that issues with parsing - // 0 are detected - tmp.Set(inf.NewDec(1234567890, 123)) - n1, ok1 := new(inf.Dec).SetString(test.in) - n2, ok2 := tmp.SetString(test.in) - expected := inf.NewDec(test.val, test.scale) - if ok1 != test.ok || ok2 != test.ok { - t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok) - continue - } - if !ok1 { - if n1 != nil { - t.Errorf("#%d (input '%s') n1 != nil", i, test.in) - } - continue - } - if !ok2 { - if n2 != nil { - t.Errorf("#%d (input '%s') n2 != nil", i, test.in) - } - continue - } - - if n1.Cmp(expected) != 0 { - t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val) - } - if n2.Cmp(expected) != 0 { - t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val) - } - } -} - -func TestDecScan(t *testing.T) { - tmp := new(inf.Dec) - for i, test := range decStringTests { - if test.scale < 0 { - // SetString only supports scale >= 0 - continue - } - // initialize to a non-zero value so that issues with parsing - // 0 are detected - tmp.Set(inf.NewDec(1234567890, 123)) - n1, n2 := new(inf.Dec), tmp - nn1, err1 := fmt.Sscan(test.in, n1) - nn2, err2 := fmt.Sscan(test.in, n2) - if !test.scanOk { - if err1 == nil || err2 == nil { - t.Errorf("#%d (input '%s') ok incorrect, should be %t", i, test.in, test.scanOk) - } - continue - } - expected := inf.NewDec(test.val, test.scale) - if nn1 != 1 || err1 != nil || nn2 != 1 || err2 != nil { - t.Errorf("#%d (input '%s') error %d %v, %d %v", i, test.in, nn1, err1, nn2, err2) - continue - } - if n1.Cmp(expected) != 0 { - t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val) - } - if n2.Cmp(expected) != 0 { - t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val) - } - } -} - -var decScanNextTests = []struct { - in string - ok bool - next rune -}{ - {"", false, 0}, - {"a", false, 'a'}, - {"z", false, 'z'}, - {"+", false, 0}, - {"-", false, 0}, - {"g", false, 'g'}, - {".", false, 0}, - {".-0", false, '-'}, - {".+0", false, '+'}, - {"0b", true, 'b'}, - {"0x", true, 'x'}, - {"0xg", true, 'x'}, - {"0.0g", true, 'g'}, -} - -func TestDecScanNext(t *testing.T) { - for i, test := range decScanNextTests { - rdr := strings.NewReader(test.in) - n1 := new(inf.Dec) - nn1, _ := fmt.Fscan(rdr, n1) - if (test.ok && nn1 == 0) || (!test.ok && nn1 > 0) { - t.Errorf("#%d (input '%s') ok incorrect should be %t", i, test.in, test.ok) - continue - } - r := rune(0) - nn2, err := fmt.Fscanf(rdr, "%c", &r) - if test.next != r { - t.Errorf("#%d (input '%s') next incorrect, got %c should be %c, %d, %v", i, test.in, r, test.next, nn2, err) - } - } -} - -var decGobEncodingTests = []string{ - "0", - "1", - "2", - "10", - "42", - "1234567890", - "298472983472983471903246121093472394872319615612417471234712061", -} - -func TestDecGobEncoding(t *testing.T) { - var medium bytes.Buffer - enc := gob.NewEncoder(&medium) - dec := gob.NewDecoder(&medium) - for i, test := range decGobEncodingTests { - for j := 0; j < 2; j++ { - for k := inf.Scale(-5); k <= 5; k++ { - medium.Reset() // empty buffer for each test case (in case of failures) - stest := test - if j != 0 { - // negative numbers - stest = "-" + test - } - var tx inf.Dec - tx.SetString(stest) - tx.SetScale(k) // test with positive, negative, and zero scale - if err := enc.Encode(&tx); err != nil { - t.Errorf("#%d%c: encoding failed: %s", i, 'a'+j, err) - } - var rx inf.Dec - if err := dec.Decode(&rx); err != nil { - t.Errorf("#%d%c: decoding failed: %s", i, 'a'+j, err) - } - if rx.Cmp(&tx) != 0 { - t.Errorf("#%d%c: transmission failed: got %s want %s", i, 'a'+j, &rx, &tx) - } - } - } - } -} diff --git a/vendor/gopkg.in/inf.v0/example_test.go b/vendor/gopkg.in/inf.v0/example_test.go deleted file mode 100644 index fa1e54d16e..0000000000 --- a/vendor/gopkg.in/inf.v0/example_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package inf_test - -import ( - "fmt" - "log" -) - -import "gopkg.in/inf.v0" - -func ExampleDec_SetString() { - d := new(inf.Dec) - d.SetString("012345.67890") // decimal; leading 0 ignored; trailing 0 kept - fmt.Println(d) - // Output: 12345.67890 -} - -func ExampleDec_Scan() { - // The Scan function is rarely used directly; - // the fmt package recognizes it as an implementation of fmt.Scanner. - d := new(inf.Dec) - _, err := fmt.Sscan("184467440.73709551617", d) - if err != nil { - log.Println("error scanning value:", err) - } else { - fmt.Println(d) - } - // Output: 184467440.73709551617 -} - -func ExampleDec_QuoRound_scale2RoundDown() { - // 10 / 3 is an infinite decimal; it has no exact Dec representation - x, y := inf.NewDec(10, 0), inf.NewDec(3, 0) - // use 2 digits beyond the decimal point, round towards 0 - z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundDown) - fmt.Println(z) - // Output: 3.33 -} - -func ExampleDec_QuoRound_scale2RoundCeil() { - // -42 / 400 is an finite decimal with 3 digits beyond the decimal point - x, y := inf.NewDec(-42, 0), inf.NewDec(400, 0) - // use 2 digits beyond decimal point, round towards positive infinity - z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundCeil) - fmt.Println(z) - // Output: -0.10 -} - -func ExampleDec_QuoExact_ok() { - // 1 / 25 is a finite decimal; it has exact Dec representation - x, y := inf.NewDec(1, 0), inf.NewDec(25, 0) - z := new(inf.Dec).QuoExact(x, y) - fmt.Println(z) - // Output: 0.04 -} - -func ExampleDec_QuoExact_fail() { - // 1 / 3 is an infinite decimal; it has no exact Dec representation - x, y := inf.NewDec(1, 0), inf.NewDec(3, 0) - z := new(inf.Dec).QuoExact(x, y) - fmt.Println(z) - // Output: <nil> -} diff --git a/vendor/gopkg.in/inf.v0/rounder_example_test.go b/vendor/gopkg.in/inf.v0/rounder_example_test.go deleted file mode 100644 index 803c1d7ee5..0000000000 --- a/vendor/gopkg.in/inf.v0/rounder_example_test.go +++ /dev/null @@ -1,72 +0,0 @@ -package inf_test - -import ( - "fmt" - "os" - "text/tabwriter" - - "gopkg.in/inf.v0" -) - -// This example displays the results of Dec.Round with each of the Rounders. -// -func ExampleRounder() { - var vals = []struct { - x string - s inf.Scale - }{ - {"-0.18", 1}, {"-0.15", 1}, {"-0.12", 1}, {"-0.10", 1}, - {"-0.08", 1}, {"-0.05", 1}, {"-0.02", 1}, {"0.00", 1}, - {"0.02", 1}, {"0.05", 1}, {"0.08", 1}, {"0.10", 1}, - {"0.12", 1}, {"0.15", 1}, {"0.18", 1}, - } - - var rounders = []struct { - name string - rounder inf.Rounder - }{ - {"RoundDown", inf.RoundDown}, {"RoundUp", inf.RoundUp}, - {"RoundCeil", inf.RoundCeil}, {"RoundFloor", inf.RoundFloor}, - {"RoundHalfDown", inf.RoundHalfDown}, {"RoundHalfUp", inf.RoundHalfUp}, - {"RoundHalfEven", inf.RoundHalfEven}, {"RoundExact", inf.RoundExact}, - } - - fmt.Println("The results of new(inf.Dec).Round(x, s, inf.RoundXXX):\n") - w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight) - fmt.Fprint(w, "x\ts\t|\t") - for _, r := range rounders { - fmt.Fprintf(w, "%s\t", r.name[5:]) - } - fmt.Fprintln(w) - for _, v := range vals { - fmt.Fprintf(w, "%s\t%d\t|\t", v.x, v.s) - for _, r := range rounders { - x, _ := new(inf.Dec).SetString(v.x) - z := new(inf.Dec).Round(x, v.s, r.rounder) - fmt.Fprintf(w, "%d\t", z) - } - fmt.Fprintln(w) - } - w.Flush() - - // Output: - // The results of new(inf.Dec).Round(x, s, inf.RoundXXX): - // - // x s | Down Up Ceil Floor HalfDown HalfUp HalfEven Exact - // -0.18 1 | -0.1 -0.2 -0.1 -0.2 -0.2 -0.2 -0.2 <nil> - // -0.15 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.2 -0.2 <nil> - // -0.12 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.1 -0.1 <nil> - // -0.10 1 | -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 - // -0.08 1 | 0.0 -0.1 0.0 -0.1 -0.1 -0.1 -0.1 <nil> - // -0.05 1 | 0.0 -0.1 0.0 -0.1 0.0 -0.1 0.0 <nil> - // -0.02 1 | 0.0 -0.1 0.0 -0.1 0.0 0.0 0.0 <nil> - // 0.00 1 | 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 - // 0.02 1 | 0.0 0.1 0.1 0.0 0.0 0.0 0.0 <nil> - // 0.05 1 | 0.0 0.1 0.1 0.0 0.0 0.1 0.0 <nil> - // 0.08 1 | 0.0 0.1 0.1 0.0 0.1 0.1 0.1 <nil> - // 0.10 1 | 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 - // 0.12 1 | 0.1 0.2 0.2 0.1 0.1 0.1 0.1 <nil> - // 0.15 1 | 0.1 0.2 0.2 0.1 0.1 0.2 0.2 <nil> - // 0.18 1 | 0.1 0.2 0.2 0.1 0.2 0.2 0.2 <nil> - -} diff --git a/vendor/gopkg.in/inf.v0/rounder_test.go b/vendor/gopkg.in/inf.v0/rounder_test.go deleted file mode 100644 index d7e14c58c6..0000000000 --- a/vendor/gopkg.in/inf.v0/rounder_test.go +++ /dev/null @@ -1,109 +0,0 @@ -package inf_test - -import ( - "math/big" - "testing" - - "gopkg.in/inf.v0" -) - -var decRounderInputs = [...]struct { - quo *inf.Dec - rA, rB *big.Int -}{ - // examples from go language spec - {inf.NewDec(1, 0), big.NewInt(2), big.NewInt(3)}, // 5 / 3 - {inf.NewDec(-1, 0), big.NewInt(-2), big.NewInt(3)}, // -5 / 3 - {inf.NewDec(-1, 0), big.NewInt(2), big.NewInt(-3)}, // 5 / -3 - {inf.NewDec(1, 0), big.NewInt(-2), big.NewInt(-3)}, // -5 / -3 - // examples from godoc - {inf.NewDec(-1, 1), big.NewInt(-8), big.NewInt(10)}, - {inf.NewDec(-1, 1), big.NewInt(-5), big.NewInt(10)}, - {inf.NewDec(-1, 1), big.NewInt(-2), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(-8), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(-5), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(-2), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(0), big.NewInt(1)}, - {inf.NewDec(0, 1), big.NewInt(2), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(5), big.NewInt(10)}, - {inf.NewDec(0, 1), big.NewInt(8), big.NewInt(10)}, - {inf.NewDec(1, 1), big.NewInt(2), big.NewInt(10)}, - {inf.NewDec(1, 1), big.NewInt(5), big.NewInt(10)}, - {inf.NewDec(1, 1), big.NewInt(8), big.NewInt(10)}, -} - -var decRounderResults = [...]struct { - rounder inf.Rounder - results [len(decRounderInputs)]*inf.Dec -}{ - {inf.RoundExact, [...]*inf.Dec{nil, nil, nil, nil, - nil, nil, nil, nil, nil, nil, - inf.NewDec(0, 1), nil, nil, nil, nil, nil, nil}}, - {inf.RoundDown, [...]*inf.Dec{ - inf.NewDec(1, 0), inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(1, 0), - inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(0, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1)}}, - {inf.RoundUp, [...]*inf.Dec{ - inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), - inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-2, 1), - inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), - inf.NewDec(0, 1), - inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), - inf.NewDec(2, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, - {inf.RoundHalfDown, [...]*inf.Dec{ - inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), - inf.NewDec(-2, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), - inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(0, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), - inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(2, 1)}}, - {inf.RoundHalfUp, [...]*inf.Dec{ - inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), - inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-1, 1), - inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(0, 1), - inf.NewDec(0, 1), - inf.NewDec(0, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), - inf.NewDec(1, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, - {inf.RoundHalfEven, [...]*inf.Dec{ - inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), - inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-1, 1), - inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(0, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), - inf.NewDec(1, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, - {inf.RoundFloor, [...]*inf.Dec{ - inf.NewDec(1, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(1, 0), - inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-2, 1), - inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), - inf.NewDec(0, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1)}}, - {inf.RoundCeil, [...]*inf.Dec{ - inf.NewDec(2, 0), inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(2, 0), - inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), - inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), - inf.NewDec(0, 1), - inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), - inf.NewDec(2, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, -} - -func TestDecRounders(t *testing.T) { - for i, a := range decRounderResults { - for j, input := range decRounderInputs { - q := new(inf.Dec).Set(input.quo) - rA, rB := new(big.Int).Set(input.rA), new(big.Int).Set(input.rB) - res := a.rounder.Round(new(inf.Dec), q, rA, rB) - if a.results[j] == nil && res == nil { - continue - } - if (a.results[j] == nil && res != nil) || - (a.results[j] != nil && res == nil) || - a.results[j].Cmp(res) != 0 { - t.Errorf("#%d,%d Rounder got %v; expected %v", i, j, res, a.results[j]) - } - } - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/asymmetric_test.go b/vendor/gopkg.in/square/go-jose.v2/asymmetric_test.go deleted file mode 100644 index 66aea365c7..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/asymmetric_test.go +++ /dev/null @@ -1,504 +0,0 @@ -/*- - * Copyright 2014 Square 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 jose - -import ( - "bytes" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "errors" - "io" - "math/big" - "testing" -) - -func TestVectorsRSA(t *testing.T) { - // Sources: - // http://www.emc.com/emc-plus/rsa-labs/standards-initiatives/pkcs-rsa-cryptography-standard.htm - // ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15crypt-vectors.txt - priv := &rsa.PrivateKey{ - PublicKey: rsa.PublicKey{ - N: fromHexInt(` - a8b3b284af8eb50b387034a860f146c4919f318763cd6c5598c8 - ae4811a1e0abc4c7e0b082d693a5e7fced675cf4668512772c0c - bc64a742c6c630f533c8cc72f62ae833c40bf25842e984bb78bd - bf97c0107d55bdb662f5c4e0fab9845cb5148ef7392dd3aaff93 - ae1e6b667bb3d4247616d4f5ba10d4cfd226de88d39f16fb`), - E: 65537, - }, - D: fromHexInt(` - 53339cfdb79fc8466a655c7316aca85c55fd8f6dd898fdaf1195 - 17ef4f52e8fd8e258df93fee180fa0e4ab29693cd83b152a553d - 4ac4d1812b8b9fa5af0e7f55fe7304df41570926f3311f15c4d6 - 5a732c483116ee3d3d2d0af3549ad9bf7cbfb78ad884f84d5beb - 04724dc7369b31def37d0cf539e9cfcdd3de653729ead5d1`), - Primes: []*big.Int{ - fromHexInt(` - d32737e7267ffe1341b2d5c0d150a81b586fb3132bed2f8d5262 - 864a9cb9f30af38be448598d413a172efb802c21acf1c11c520c - 2f26a471dcad212eac7ca39d`), - fromHexInt(` - cc8853d1d54da630fac004f471f281c7b8982d8224a490edbeb3 - 3d3e3d5cc93c4765703d1dd791642f1f116a0dd852be2419b2af - 72bfe9a030e860b0288b5d77`), - }, - } - - input := fromHexBytes( - "6628194e12073db03ba94cda9ef9532397d50dba79b987004afefe34") - - expectedPKCS := fromHexBytes(` - 50b4c14136bd198c2f3c3ed243fce036e168d56517984a263cd66492b808 - 04f169d210f2b9bdfb48b12f9ea05009c77da257cc600ccefe3a6283789d - 8ea0e607ac58e2690ec4ebc10146e8cbaa5ed4d5cce6fe7b0ff9efc1eabb - 564dbf498285f449ee61dd7b42ee5b5892cb90601f30cda07bf26489310b - cd23b528ceab3c31`) - - expectedOAEP := fromHexBytes(` - 354fe67b4a126d5d35fe36c777791a3f7ba13def484e2d3908aff722fad4 - 68fb21696de95d0be911c2d3174f8afcc201035f7b6d8e69402de5451618 - c21a535fa9d7bfc5b8dd9fc243f8cf927db31322d6e881eaa91a996170e6 - 57a05a266426d98c88003f8477c1227094a0d9fa1e8c4024309ce1ecccb5 - 210035d47ac72e8a`) - - // Mock random reader - randReader = bytes.NewReader(fromHexBytes(` - 017341ae3875d5f87101f8cc4fa9b9bc156bb04628fccdb2f4f11e905bd3 - a155d376f593bd7304210874eba08a5e22bcccb4c9d3882a93a54db022f5 - 03d16338b6b7ce16dc7f4bbf9a96b59772d6606e9747c7649bf9e083db98 - 1884a954ab3c6f18b776ea21069d69776a33e96bad48e1dda0a5ef`)) - defer resetRandReader() - - // RSA-PKCS1v1.5 encrypt - enc := new(rsaEncrypterVerifier) - enc.publicKey = &priv.PublicKey - encryptedPKCS, err := enc.encrypt(input, RSA1_5) - if err != nil { - t.Error("Encryption failed:", err) - return - } - - if bytes.Compare(encryptedPKCS, expectedPKCS) != 0 { - t.Error("Output does not match expected value (PKCS1v1.5)") - } - - // RSA-OAEP encrypt - encryptedOAEP, err := enc.encrypt(input, RSA_OAEP) - if err != nil { - t.Error("Encryption failed:", err) - return - } - - if bytes.Compare(encryptedOAEP, expectedOAEP) != 0 { - t.Error("Output does not match expected value (OAEP)") - } - - // Need fake cipher for PKCS1v1.5 decrypt - resetRandReader() - aes := newAESGCM(len(input)) - - keygen := randomKeyGenerator{ - size: aes.keySize(), - } - - // RSA-PKCS1v1.5 decrypt - dec := new(rsaDecrypterSigner) - dec.privateKey = priv - decryptedPKCS, err := dec.decrypt(encryptedPKCS, RSA1_5, keygen) - if err != nil { - t.Error("Decryption failed:", err) - return - } - - if bytes.Compare(input, decryptedPKCS) != 0 { - t.Error("Output does not match expected value (PKCS1v1.5)") - } - - // RSA-OAEP decrypt - decryptedOAEP, err := dec.decrypt(encryptedOAEP, RSA_OAEP, keygen) - if err != nil { - t.Error("decryption failed:", err) - return - } - - if bytes.Compare(input, decryptedOAEP) != 0 { - t.Error("output does not match expected value (OAEP)") - } -} - -func TestEd25519(t *testing.T) { - _, err := newEd25519Signer("XYZ", nil) - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } - - enc := new(edEncrypterVerifier) - enc.publicKey = ed25519PublicKey - err = enc.verifyPayload([]byte{}, []byte{}, "XYZ") - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } - - dec := new(edDecrypterSigner) - dec.privateKey = ed25519PrivateKey - _, err = dec.signPayload([]byte{}, "XYZ") - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } - - sig, err := dec.signPayload([]byte("This is a test"), "EdDSA") - if err != nil { - t.Error("should not error trying to sign payload") - } - if sig.Signature == nil { - t.Error("Check the signature") - } - err = enc.verifyPayload([]byte("This is a test"), sig.Signature, "EdDSA") - if err != nil { - t.Error("should not error trying to verify payload") - } - - err = enc.verifyPayload([]byte("This is test number 2"), sig.Signature, "EdDSA") - if err == nil { - t.Error("should not error trying to verify payload") - } -} - -func TestInvalidAlgorithmsRSA(t *testing.T) { - _, err := newRSARecipient("XYZ", nil) - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } - - _, err = newRSASigner("XYZ", nil) - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } - - enc := new(rsaEncrypterVerifier) - enc.publicKey = &rsaTestKey.PublicKey - _, err = enc.encryptKey([]byte{}, "XYZ") - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } - - err = enc.verifyPayload([]byte{}, []byte{}, "XYZ") - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } - - dec := new(rsaDecrypterSigner) - dec.privateKey = rsaTestKey - _, err = dec.decrypt(make([]byte, 256), "XYZ", randomKeyGenerator{size: 16}) - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } - - _, err = dec.signPayload([]byte{}, "XYZ") - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } -} - -type failingKeyGenerator struct{} - -func (ctx failingKeyGenerator) keySize() int { - return 0 -} - -func (ctx failingKeyGenerator) genKey() ([]byte, rawHeader, error) { - return nil, rawHeader{}, errors.New("failed to generate key") -} - -func TestPKCSKeyGeneratorFailure(t *testing.T) { - dec := new(rsaDecrypterSigner) - dec.privateKey = rsaTestKey - generator := failingKeyGenerator{} - _, err := dec.decrypt(make([]byte, 256), RSA1_5, generator) - if err != ErrCryptoFailure { - t.Error("should return error on invalid algorithm") - } -} - -func TestInvalidAlgorithmsEC(t *testing.T) { - _, err := newECDHRecipient("XYZ", nil) - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } - - _, err = newECDSASigner("XYZ", nil) - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } - - enc := new(ecEncrypterVerifier) - enc.publicKey = &ecTestKey256.PublicKey - _, err = enc.encryptKey([]byte{}, "XYZ") - if err != ErrUnsupportedAlgorithm { - t.Error("should return error on invalid algorithm") - } -} - -func TestInvalidECKeyGen(t *testing.T) { - gen := ecKeyGenerator{ - size: 16, - algID: "A128GCM", - publicKey: &ecTestKey256.PublicKey, - } - - if gen.keySize() != 16 { - t.Error("ec key generator reported incorrect key size") - } - - _, _, err := gen.genKey() - if err != nil { - t.Error("ec key generator failed to generate key", err) - } -} - -func TestInvalidECDecrypt(t *testing.T) { - dec := ecDecrypterSigner{ - privateKey: ecTestKey256, - } - - generator := randomKeyGenerator{size: 16} - - // Missing epk header - headers := rawHeader{} - headers.set(headerAlgorithm, ECDH_ES) - - _, err := dec.decryptKey(headers, nil, generator) - if err == nil { - t.Error("ec decrypter accepted object with missing epk header") - } - - // Invalid epk header - headers.set(headerEPK, &JSONWebKey{}) - - _, err = dec.decryptKey(headers, nil, generator) - if err == nil { - t.Error("ec decrypter accepted object with invalid epk header") - } -} - -func TestDecryptWithIncorrectSize(t *testing.T) { - priv, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Error(err) - return - } - - dec := new(rsaDecrypterSigner) - dec.privateKey = priv - aes := newAESGCM(16) - - keygen := randomKeyGenerator{ - size: aes.keySize(), - } - - payload := make([]byte, 254) - _, err = dec.decrypt(payload, RSA1_5, keygen) - if err == nil { - t.Error("Invalid payload size should return error") - } - - payload = make([]byte, 257) - _, err = dec.decrypt(payload, RSA1_5, keygen) - if err == nil { - t.Error("Invalid payload size should return error") - } -} - -func TestPKCSDecryptNeverFails(t *testing.T) { - // We don't want RSA-PKCS1 v1.5 decryption to ever fail, in order to prevent - // side-channel timing attacks (Bleichenbacher attack in particular). - priv, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - t.Error(err) - return - } - - dec := new(rsaDecrypterSigner) - dec.privateKey = priv - aes := newAESGCM(16) - - keygen := randomKeyGenerator{ - size: aes.keySize(), - } - - for i := 1; i < 50; i++ { - payload := make([]byte, 256) - _, err := io.ReadFull(rand.Reader, payload) - if err != nil { - t.Error("Unable to get random data:", err) - return - } - _, err = dec.decrypt(payload, RSA1_5, keygen) - if err != nil { - t.Error("PKCS1v1.5 decrypt should never fail:", err) - return - } - } -} - -func BenchmarkPKCSDecryptWithValidPayloads(b *testing.B) { - priv, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - panic(err) - } - - enc := new(rsaEncrypterVerifier) - enc.publicKey = &priv.PublicKey - dec := new(rsaDecrypterSigner) - dec.privateKey = priv - aes := newAESGCM(32) - - b.StopTimer() - b.ResetTimer() - for i := 0; i < b.N; i++ { - plaintext := make([]byte, 32) - _, err = io.ReadFull(rand.Reader, plaintext) - if err != nil { - panic(err) - } - - ciphertext, err := enc.encrypt(plaintext, RSA1_5) - if err != nil { - panic(err) - } - - keygen := randomKeyGenerator{ - size: aes.keySize(), - } - - b.StartTimer() - _, err = dec.decrypt(ciphertext, RSA1_5, keygen) - b.StopTimer() - if err != nil { - panic(err) - } - } -} - -func BenchmarkPKCSDecryptWithInvalidPayloads(b *testing.B) { - priv, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - panic(err) - } - - enc := new(rsaEncrypterVerifier) - enc.publicKey = &priv.PublicKey - dec := new(rsaDecrypterSigner) - dec.privateKey = priv - aes := newAESGCM(16) - - keygen := randomKeyGenerator{ - size: aes.keySize(), - } - - b.StopTimer() - b.ResetTimer() - for i := 0; i < b.N; i++ { - plaintext := make([]byte, 16) - _, err = io.ReadFull(rand.Reader, plaintext) - if err != nil { - panic(err) - } - - ciphertext, err := enc.encrypt(plaintext, RSA1_5) - if err != nil { - panic(err) - } - - // Do some simple scrambling - ciphertext[128] ^= 0xFF - - b.StartTimer() - _, err = dec.decrypt(ciphertext, RSA1_5, keygen) - b.StopTimer() - if err != nil { - panic(err) - } - } -} - -func TestInvalidEllipticCurve(t *testing.T) { - signer256 := ecDecrypterSigner{privateKey: ecTestKey256} - signer384 := ecDecrypterSigner{privateKey: ecTestKey384} - signer521 := ecDecrypterSigner{privateKey: ecTestKey521} - - _, err := signer256.signPayload([]byte{}, ES384) - if err == nil { - t.Error("should not generate ES384 signature with P-256 key") - } - _, err = signer256.signPayload([]byte{}, ES512) - if err == nil { - t.Error("should not generate ES512 signature with P-256 key") - } - _, err = signer384.signPayload([]byte{}, ES256) - if err == nil { - t.Error("should not generate ES256 signature with P-384 key") - } - _, err = signer384.signPayload([]byte{}, ES512) - if err == nil { - t.Error("should not generate ES512 signature with P-384 key") - } - _, err = signer521.signPayload([]byte{}, ES256) - if err == nil { - t.Error("should not generate ES256 signature with P-521 key") - } - _, err = signer521.signPayload([]byte{}, ES384) - if err == nil { - t.Error("should not generate ES384 signature with P-521 key") - } -} - -func estInvalidECPublicKey(t *testing.T) { - // Invalid key - invalid := &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: elliptic.P256(), - X: fromBase64Int("MTEx"), - Y: fromBase64Int("MTEx"), - }, - D: fromBase64Int("0_NxaRPUMQoAJt50Gz8YiTr8gRTwyEaCumd-MToTmIo"), - } - - headers := rawHeader{} - headers.set(headerAlgorithm, ECDH_ES) - headers.set(headerEPK, &JSONWebKey{ - Key: &invalid.PublicKey, - }) - - dec := ecDecrypterSigner{ - privateKey: ecTestKey256, - } - - _, err := dec.decryptKey(headers, nil, randomKeyGenerator{size: 16}) - if err == nil { - t.Fatal("decrypter accepted JWS with invalid ECDH public key") - } -} - -func TestInvalidAlgorithmEC(t *testing.T) { - err := ecEncrypterVerifier{publicKey: &ecTestKey256.PublicKey}.verifyPayload([]byte{}, []byte{}, "XYZ") - if err != ErrUnsupportedAlgorithm { - t.Fatal("should not accept invalid/unsupported algorithm") - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/cipher/cbc_hmac_test.go b/vendor/gopkg.in/square/go-jose.v2/cipher/cbc_hmac_test.go deleted file mode 100644 index 40bcb20fa0..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/cipher/cbc_hmac_test.go +++ /dev/null @@ -1,498 +0,0 @@ -/*- - * Copyright 2014 Square 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 josecipher - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "io" - "strings" - "testing" -) - -func TestInvalidInputs(t *testing.T) { - key := []byte{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - } - - nonce := []byte{ - 92, 80, 104, 49, 133, 25, 161, 215, 173, 101, 219, 211, 136, 91, 210, 145} - - aead, _ := NewCBCHMAC(key, aes.NewCipher) - ciphertext := aead.Seal(nil, nonce, []byte("plaintext"), []byte("aad")) - - // Changed AAD, must fail - _, err := aead.Open(nil, nonce, ciphertext, []byte("INVALID")) - if err == nil { - t.Error("must detect invalid aad") - } - - // Empty ciphertext, must fail - _, err = aead.Open(nil, nonce, []byte{}, []byte("aad")) - if err == nil { - t.Error("must detect invalid/empty ciphertext") - } - - // Corrupt ciphertext, must fail - corrupt := make([]byte, len(ciphertext)) - copy(corrupt, ciphertext) - corrupt[0] ^= 0xFF - - _, err = aead.Open(nil, nonce, corrupt, []byte("aad")) - if err == nil { - t.Error("must detect corrupt ciphertext") - } - - // Corrupt authtag, must fail - copy(corrupt, ciphertext) - corrupt[len(ciphertext)-1] ^= 0xFF - - _, err = aead.Open(nil, nonce, corrupt, []byte("aad")) - if err == nil { - t.Error("must detect corrupt authtag") - } - - // Truncated data, must fail - _, err = aead.Open(nil, nonce, ciphertext[:10], []byte("aad")) - if err == nil { - t.Error("must detect corrupt authtag") - } -} - -func TestVectorsAESCBC128(t *testing.T) { - // Source: http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-29#appendix-A.2 - plaintext := []byte{ - 76, 105, 118, 101, 32, 108, 111, 110, 103, 32, 97, 110, 100, 32, - 112, 114, 111, 115, 112, 101, 114, 46} - - aad := []byte{ - 101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 48, 69, - 120, 88, 122, 85, 105, 76, 67, 74, 108, 98, 109, 77, 105, 79, 105, - 74, 66, 77, 84, 73, 52, 81, 48, 74, 68, 76, 85, 104, 84, 77, 106, 85, - 50, 73, 110, 48} - - expectedCiphertext := []byte{ - 40, 57, 83, 181, 119, 33, 133, 148, 198, 185, 243, 24, 152, 230, 6, - 75, 129, 223, 127, 19, 210, 82, 183, 230, 168, 33, 215, 104, 143, - 112, 56, 102} - - expectedAuthtag := []byte{ - 246, 17, 244, 190, 4, 95, 98, 3, 231, 0, 115, 157, 242, 203, 100, - 191} - - key := []byte{ - 4, 211, 31, 197, 84, 157, 252, 254, 11, 100, 157, 250, 63, 170, 106, 206, - 107, 124, 212, 45, 111, 107, 9, 219, 200, 177, 0, 240, 143, 156, 44, 207} - - nonce := []byte{ - 3, 22, 60, 12, 43, 67, 104, 105, 108, 108, 105, 99, 111, 116, 104, 101} - - enc, err := NewCBCHMAC(key, aes.NewCipher) - out := enc.Seal(nil, nonce, plaintext, aad) - if err != nil { - t.Error("Unable to encrypt:", err) - return - } - - if bytes.Compare(out[:len(out)-16], expectedCiphertext) != 0 { - t.Error("Ciphertext did not match") - } - if bytes.Compare(out[len(out)-16:], expectedAuthtag) != 0 { - t.Error("Auth tag did not match") - } -} - -func TestVectorsAESCBC256(t *testing.T) { - // Source: https://tools.ietf.org/html/draft-mcgrew-aead-aes-cbc-hmac-sha2-05#section-5.4 - plaintext := []byte{ - 0x41, 0x20, 0x63, 0x69, 0x70, 0x68, 0x65, 0x72, 0x20, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x20, - 0x6d, 0x75, 0x73, 0x74, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x65, 0x71, 0x75, - 0x69, 0x72, 0x65, 0x64, 0x20, 0x74, 0x6f, 0x20, 0x62, 0x65, 0x20, 0x73, 0x65, 0x63, 0x72, 0x65, - 0x74, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x69, 0x74, 0x20, 0x6d, 0x75, 0x73, 0x74, 0x20, 0x62, - 0x65, 0x20, 0x61, 0x62, 0x6c, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x66, 0x61, 0x6c, 0x6c, 0x20, 0x69, - 0x6e, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x68, 0x61, 0x6e, 0x64, 0x73, 0x20, 0x6f, 0x66, - 0x20, 0x74, 0x68, 0x65, 0x20, 0x65, 0x6e, 0x65, 0x6d, 0x79, 0x20, 0x77, 0x69, 0x74, 0x68, 0x6f, - 0x75, 0x74, 0x20, 0x69, 0x6e, 0x63, 0x6f, 0x6e, 0x76, 0x65, 0x6e, 0x69, 0x65, 0x6e, 0x63, 0x65} - - aad := []byte{ - 0x54, 0x68, 0x65, 0x20, 0x73, 0x65, 0x63, 0x6f, 0x6e, 0x64, 0x20, 0x70, 0x72, 0x69, 0x6e, 0x63, - 0x69, 0x70, 0x6c, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x41, 0x75, 0x67, 0x75, 0x73, 0x74, 0x65, 0x20, - 0x4b, 0x65, 0x72, 0x63, 0x6b, 0x68, 0x6f, 0x66, 0x66, 0x73} - - expectedCiphertext := []byte{ - 0x4a, 0xff, 0xaa, 0xad, 0xb7, 0x8c, 0x31, 0xc5, 0xda, 0x4b, 0x1b, 0x59, 0x0d, 0x10, 0xff, 0xbd, - 0x3d, 0xd8, 0xd5, 0xd3, 0x02, 0x42, 0x35, 0x26, 0x91, 0x2d, 0xa0, 0x37, 0xec, 0xbc, 0xc7, 0xbd, - 0x82, 0x2c, 0x30, 0x1d, 0xd6, 0x7c, 0x37, 0x3b, 0xcc, 0xb5, 0x84, 0xad, 0x3e, 0x92, 0x79, 0xc2, - 0xe6, 0xd1, 0x2a, 0x13, 0x74, 0xb7, 0x7f, 0x07, 0x75, 0x53, 0xdf, 0x82, 0x94, 0x10, 0x44, 0x6b, - 0x36, 0xeb, 0xd9, 0x70, 0x66, 0x29, 0x6a, 0xe6, 0x42, 0x7e, 0xa7, 0x5c, 0x2e, 0x08, 0x46, 0xa1, - 0x1a, 0x09, 0xcc, 0xf5, 0x37, 0x0d, 0xc8, 0x0b, 0xfe, 0xcb, 0xad, 0x28, 0xc7, 0x3f, 0x09, 0xb3, - 0xa3, 0xb7, 0x5e, 0x66, 0x2a, 0x25, 0x94, 0x41, 0x0a, 0xe4, 0x96, 0xb2, 0xe2, 0xe6, 0x60, 0x9e, - 0x31, 0xe6, 0xe0, 0x2c, 0xc8, 0x37, 0xf0, 0x53, 0xd2, 0x1f, 0x37, 0xff, 0x4f, 0x51, 0x95, 0x0b, - 0xbe, 0x26, 0x38, 0xd0, 0x9d, 0xd7, 0xa4, 0x93, 0x09, 0x30, 0x80, 0x6d, 0x07, 0x03, 0xb1, 0xf6} - - expectedAuthtag := []byte{ - 0x4d, 0xd3, 0xb4, 0xc0, 0x88, 0xa7, 0xf4, 0x5c, 0x21, 0x68, 0x39, 0x64, 0x5b, 0x20, 0x12, 0xbf, - 0x2e, 0x62, 0x69, 0xa8, 0xc5, 0x6a, 0x81, 0x6d, 0xbc, 0x1b, 0x26, 0x77, 0x61, 0x95, 0x5b, 0xc5} - - key := []byte{ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f} - - nonce := []byte{ - 0x1a, 0xf3, 0x8c, 0x2d, 0xc2, 0xb9, 0x6f, 0xfd, 0xd8, 0x66, 0x94, 0x09, 0x23, 0x41, 0xbc, 0x04} - - enc, err := NewCBCHMAC(key, aes.NewCipher) - out := enc.Seal(nil, nonce, plaintext, aad) - if err != nil { - t.Error("Unable to encrypt:", err) - return - } - - if bytes.Compare(out[:len(out)-32], expectedCiphertext) != 0 { - t.Error("Ciphertext did not match, got", out[:len(out)-32], "wanted", expectedCiphertext) - } - if bytes.Compare(out[len(out)-32:], expectedAuthtag) != 0 { - t.Error("Auth tag did not match, got", out[len(out)-32:], "wanted", expectedAuthtag) - } -} - -func TestAESCBCRoundtrip(t *testing.T) { - key128 := []byte{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} - - key192 := []byte{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7} - - key256 := []byte{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} - - nonce := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} - - RunRoundtrip(t, key128, nonce) - RunRoundtrip(t, key192, nonce) - RunRoundtrip(t, key256, nonce) -} - -func RunRoundtrip(t *testing.T, key, nonce []byte) { - aead, err := NewCBCHMAC(key, aes.NewCipher) - if err != nil { - panic(err) - } - - if aead.NonceSize() != len(nonce) { - panic("invalid nonce") - } - - // Test pre-existing data in dst buffer - dst := []byte{15, 15, 15, 15} - plaintext := []byte{0, 0, 0, 0} - aad := []byte{4, 3, 2, 1} - - result := aead.Seal(dst, nonce, plaintext, aad) - if bytes.Compare(dst, result[:4]) != 0 { - t.Error("Existing data in dst not preserved") - } - - // Test pre-existing (empty) dst buffer with sufficient capacity - dst = make([]byte, 256)[:0] - result, err = aead.Open(dst, nonce, result[4:], aad) - if err != nil { - panic(err) - } - - if bytes.Compare(result, plaintext) != 0 { - t.Error("Plaintext does not match output") - } -} - -func TestAESCBCOverhead(t *testing.T) { - aead, err := NewCBCHMAC(make([]byte, 32), aes.NewCipher) - if err != nil { - panic(err) - } - - if aead.Overhead() != 32 { - t.Error("CBC-HMAC reports incorrect overhead value") - } -} - -func TestPadding(t *testing.T) { - for i := 0; i < 256; i++ { - slice := make([]byte, i) - padded := padBuffer(slice, 16) - if len(padded)%16 != 0 { - t.Error("failed to pad slice properly", i) - return - } - unpadded, err := unpadBuffer(padded, 16) - if err != nil || len(unpadded) != i { - t.Error("failed to unpad slice properly", i) - return - } - } -} - -func TestInvalidKey(t *testing.T) { - key := make([]byte, 30) - _, err := NewCBCHMAC(key, aes.NewCipher) - if err == nil { - t.Error("should not be able to instantiate CBC-HMAC with invalid key") - } -} - -func TestTruncatedCiphertext(t *testing.T) { - key := make([]byte, 32) - nonce := make([]byte, 16) - data := make([]byte, 32) - - io.ReadFull(rand.Reader, key) - io.ReadFull(rand.Reader, nonce) - - aead, err := NewCBCHMAC(key, aes.NewCipher) - if err != nil { - panic(err) - } - - ctx := aead.(*cbcAEAD) - ct := aead.Seal(nil, nonce, data, nil) - - // Truncated ciphertext, but with correct auth tag - truncated, tail := resize(ct[:len(ct)-ctx.authtagBytes-2], uint64(len(ct))-2) - copy(tail, ctx.computeAuthTag(nil, nonce, truncated[:len(truncated)-ctx.authtagBytes])) - - // Open should fail - _, err = aead.Open(nil, nonce, truncated, nil) - if err == nil { - t.Error("open on truncated ciphertext should fail") - } -} - -func TestInvalidPaddingOpen(t *testing.T) { - key := make([]byte, 32) - nonce := make([]byte, 16) - - // Plaintext with invalid padding - plaintext := padBuffer(make([]byte, 28), aes.BlockSize) - plaintext[len(plaintext)-1] = 0xFF - - io.ReadFull(rand.Reader, key) - io.ReadFull(rand.Reader, nonce) - - block, _ := aes.NewCipher(key) - cbc := cipher.NewCBCEncrypter(block, nonce) - buffer := append([]byte{}, plaintext...) - cbc.CryptBlocks(buffer, buffer) - - aead, _ := NewCBCHMAC(key, aes.NewCipher) - ctx := aead.(*cbcAEAD) - - // Mutated ciphertext, but with correct auth tag - size := uint64(len(buffer)) - ciphertext, tail := resize(buffer, size+(uint64(len(key))/2)) - copy(tail, ctx.computeAuthTag(nil, nonce, ciphertext[:size])) - - // Open should fail (b/c of invalid padding, even though tag matches) - _, err := aead.Open(nil, nonce, ciphertext, nil) - if err == nil || !strings.Contains(err.Error(), "invalid padding") { - t.Error("no or unexpected error on open with invalid padding:", err) - } -} - -func TestInvalidPadding(t *testing.T) { - for i := 0; i < 256; i++ { - slice := make([]byte, i) - padded := padBuffer(slice, 16) - if len(padded)%16 != 0 { - t.Error("failed to pad slice properly", i) - return - } - - paddingBytes := 16 - (i % 16) - - // Mutate padding for testing - for j := 1; j <= paddingBytes; j++ { - mutated := make([]byte, len(padded)) - copy(mutated, padded) - mutated[len(mutated)-j] ^= 0xFF - - _, err := unpadBuffer(mutated, 16) - if err == nil { - t.Error("unpad on invalid padding should fail", i) - return - } - } - - // Test truncated padding - _, err := unpadBuffer(padded[:len(padded)-1], 16) - if err == nil { - t.Error("unpad on truncated padding should fail", i) - return - } - } -} - -func TestZeroLengthPadding(t *testing.T) { - data := make([]byte, 16) - data, err := unpadBuffer(data, 16) - if err == nil { - t.Error("padding with 0x00 should never be valid") - } -} - -func benchEncryptCBCHMAC(b *testing.B, keySize, chunkSize int) { - key := make([]byte, keySize*2) - nonce := make([]byte, 16) - - io.ReadFull(rand.Reader, key) - io.ReadFull(rand.Reader, nonce) - - chunk := make([]byte, chunkSize) - - aead, err := NewCBCHMAC(key, aes.NewCipher) - if err != nil { - panic(err) - } - - b.SetBytes(int64(chunkSize)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - aead.Seal(nil, nonce, chunk, nil) - } -} - -func benchDecryptCBCHMAC(b *testing.B, keySize, chunkSize int) { - key := make([]byte, keySize*2) - nonce := make([]byte, 16) - - io.ReadFull(rand.Reader, key) - io.ReadFull(rand.Reader, nonce) - - chunk := make([]byte, chunkSize) - - aead, err := NewCBCHMAC(key, aes.NewCipher) - if err != nil { - panic(err) - } - - out := aead.Seal(nil, nonce, chunk, nil) - - b.SetBytes(int64(chunkSize)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - aead.Open(nil, nonce, out, nil) - } -} - -func BenchmarkEncryptAES128_CBCHMAC_1k(b *testing.B) { - benchEncryptCBCHMAC(b, 16, 1024) -} - -func BenchmarkEncryptAES128_CBCHMAC_64k(b *testing.B) { - benchEncryptCBCHMAC(b, 16, 65536) -} - -func BenchmarkEncryptAES128_CBCHMAC_1MB(b *testing.B) { - benchEncryptCBCHMAC(b, 16, 1048576) -} - -func BenchmarkEncryptAES128_CBCHMAC_64MB(b *testing.B) { - benchEncryptCBCHMAC(b, 16, 67108864) -} - -func BenchmarkDecryptAES128_CBCHMAC_1k(b *testing.B) { - benchDecryptCBCHMAC(b, 16, 1024) -} - -func BenchmarkDecryptAES128_CBCHMAC_64k(b *testing.B) { - benchDecryptCBCHMAC(b, 16, 65536) -} - -func BenchmarkDecryptAES128_CBCHMAC_1MB(b *testing.B) { - benchDecryptCBCHMAC(b, 16, 1048576) -} - -func BenchmarkDecryptAES128_CBCHMAC_64MB(b *testing.B) { - benchDecryptCBCHMAC(b, 16, 67108864) -} - -func BenchmarkEncryptAES192_CBCHMAC_64k(b *testing.B) { - benchEncryptCBCHMAC(b, 24, 65536) -} - -func BenchmarkEncryptAES192_CBCHMAC_1MB(b *testing.B) { - benchEncryptCBCHMAC(b, 24, 1048576) -} - -func BenchmarkEncryptAES192_CBCHMAC_64MB(b *testing.B) { - benchEncryptCBCHMAC(b, 24, 67108864) -} - -func BenchmarkDecryptAES192_CBCHMAC_1k(b *testing.B) { - benchDecryptCBCHMAC(b, 24, 1024) -} - -func BenchmarkDecryptAES192_CBCHMAC_64k(b *testing.B) { - benchDecryptCBCHMAC(b, 24, 65536) -} - -func BenchmarkDecryptAES192_CBCHMAC_1MB(b *testing.B) { - benchDecryptCBCHMAC(b, 24, 1048576) -} - -func BenchmarkDecryptAES192_CBCHMAC_64MB(b *testing.B) { - benchDecryptCBCHMAC(b, 24, 67108864) -} - -func BenchmarkEncryptAES256_CBCHMAC_64k(b *testing.B) { - benchEncryptCBCHMAC(b, 32, 65536) -} - -func BenchmarkEncryptAES256_CBCHMAC_1MB(b *testing.B) { - benchEncryptCBCHMAC(b, 32, 1048576) -} - -func BenchmarkEncryptAES256_CBCHMAC_64MB(b *testing.B) { - benchEncryptCBCHMAC(b, 32, 67108864) -} - -func BenchmarkDecryptAES256_CBCHMAC_1k(b *testing.B) { - benchDecryptCBCHMAC(b, 32, 1032) -} - -func BenchmarkDecryptAES256_CBCHMAC_64k(b *testing.B) { - benchDecryptCBCHMAC(b, 32, 65536) -} - -func BenchmarkDecryptAES256_CBCHMAC_1MB(b *testing.B) { - benchDecryptCBCHMAC(b, 32, 1048576) -} - -func BenchmarkDecryptAES256_CBCHMAC_64MB(b *testing.B) { - benchDecryptCBCHMAC(b, 32, 67108864) -} diff --git a/vendor/gopkg.in/square/go-jose.v2/cipher/concat_kdf_test.go b/vendor/gopkg.in/square/go-jose.v2/cipher/concat_kdf_test.go deleted file mode 100644 index 48219b3e1d..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/cipher/concat_kdf_test.go +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * Copyright 2014 Square 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 josecipher - -import ( - "bytes" - "crypto" - "testing" -) - -// Taken from: https://tools.ietf.org/id/draft-ietf-jose-json-web-algorithms-38.txt -func TestVectorConcatKDF(t *testing.T) { - z := []byte{ - 158, 86, 217, 29, 129, 113, 53, 211, 114, 131, 66, 131, 191, 132, - 38, 156, 251, 49, 110, 163, 218, 128, 106, 72, 246, 218, 167, 121, - 140, 254, 144, 196} - - algID := []byte{0, 0, 0, 7, 65, 49, 50, 56, 71, 67, 77} - - ptyUInfo := []byte{0, 0, 0, 5, 65, 108, 105, 99, 101} - ptyVInfo := []byte{0, 0, 0, 3, 66, 111, 98} - - supPubInfo := []byte{0, 0, 0, 128} - supPrivInfo := []byte{} - - expected := []byte{ - 86, 170, 141, 234, 248, 35, 109, 32, 92, 34, 40, 205, 113, 167, 16, 26} - - ckdf := NewConcatKDF(crypto.SHA256, z, algID, ptyUInfo, ptyVInfo, supPubInfo, supPrivInfo) - - out0 := make([]byte, 9) - out1 := make([]byte, 7) - - read0, err := ckdf.Read(out0) - if err != nil { - t.Error("error when reading from concat kdf reader", err) - return - } - - read1, err := ckdf.Read(out1) - if err != nil { - t.Error("error when reading from concat kdf reader", err) - return - } - - if read0+read1 != len(out0)+len(out1) { - t.Error("did not receive enough bytes from concat kdf reader") - return - } - - out := []byte{} - out = append(out, out0...) - out = append(out, out1...) - - if bytes.Compare(out, expected) != 0 { - t.Error("did not receive expected output from concat kdf reader") - return - } -} - -func TestCache(t *testing.T) { - z := []byte{ - 158, 86, 217, 29, 129, 113, 53, 211, 114, 131, 66, 131, 191, 132, - 38, 156, 251, 49, 110, 163, 218, 128, 106, 72, 246, 218, 167, 121, - 140, 254, 144, 196} - - algID := []byte{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4} - - ptyUInfo := []byte{1, 2, 3, 4} - ptyVInfo := []byte{4, 3, 2, 1} - - supPubInfo := []byte{} - supPrivInfo := []byte{} - - outputs := [][]byte{} - - // Read the same amount of data in different chunk sizes - chunkSizes := []int{1, 2, 4, 8, 16, 32, 64, 128, 256, 512} - - for _, c := range chunkSizes { - out := make([]byte, 1024) - reader := NewConcatKDF(crypto.SHA256, z, algID, ptyUInfo, ptyVInfo, supPubInfo, supPrivInfo) - - for i := 0; i < 1024; i += c { - _, _ = reader.Read(out[i : i+c]) - } - - outputs = append(outputs, out) - } - - for i := range outputs { - if bytes.Compare(outputs[i], outputs[(i+1)%len(outputs)]) != 0 { - t.Error("not all outputs from KDF matched") - } - } -} - -func benchmarkKDF(b *testing.B, total int) { - z := []byte{ - 158, 86, 217, 29, 129, 113, 53, 211, 114, 131, 66, 131, 191, 132, - 38, 156, 251, 49, 110, 163, 218, 128, 106, 72, 246, 218, 167, 121, - 140, 254, 144, 196} - - algID := []byte{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4} - - ptyUInfo := []byte{1, 2, 3, 4} - ptyVInfo := []byte{4, 3, 2, 1} - - supPubInfo := []byte{} - supPrivInfo := []byte{} - - out := make([]byte, total) - reader := NewConcatKDF(crypto.SHA256, z, algID, ptyUInfo, ptyVInfo, supPubInfo, supPrivInfo) - - b.ResetTimer() - b.SetBytes(int64(total)) - for i := 0; i < b.N; i++ { - _, _ = reader.Read(out) - } -} - -func BenchmarkConcatKDF_1k(b *testing.B) { - benchmarkKDF(b, 1024) -} - -func BenchmarkConcatKDF_64k(b *testing.B) { - benchmarkKDF(b, 65536) -} - -func BenchmarkConcatKDF_1MB(b *testing.B) { - benchmarkKDF(b, 1048576) -} - -func BenchmarkConcatKDF_64MB(b *testing.B) { - benchmarkKDF(b, 67108864) -} diff --git a/vendor/gopkg.in/square/go-jose.v2/cipher/ecdh_es_test.go b/vendor/gopkg.in/square/go-jose.v2/cipher/ecdh_es_test.go deleted file mode 100644 index 58fb4c67b1..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/cipher/ecdh_es_test.go +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * Copyright 2014 Square 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 josecipher - -import ( - "bytes" - "crypto/ecdsa" - "crypto/elliptic" - "encoding/base64" - "math/big" - "testing" -) - -// Example keys from JWA, Appendix C -var aliceKey = &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: elliptic.P256(), - X: fromBase64Int("gI0GAILBdu7T53akrFmMyGcsF3n5dO7MmwNBHKW5SV0="), - Y: fromBase64Int("SLW_xSffzlPWrHEVI30DHM_4egVwt3NQqeUD7nMFpps="), - }, - D: fromBase64Int("0_NxaRPUMQoAJt50Gz8YiTr8gRTwyEaCumd-MToTmIo="), -} - -var bobKey = &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: elliptic.P256(), - X: fromBase64Int("weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ="), - Y: fromBase64Int("e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck="), - }, - D: fromBase64Int("VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw="), -} - -// Build big int from base64-encoded string. Strips whitespace (for testing). -func fromBase64Int(data string) *big.Int { - val, err := base64.URLEncoding.DecodeString(data) - if err != nil { - panic("Invalid test data: " + err.Error()) - } - return new(big.Int).SetBytes(val) -} - -func TestVectorECDHES(t *testing.T) { - apuData := []byte("Alice") - apvData := []byte("Bob") - - expected := []byte{ - 86, 170, 141, 234, 248, 35, 109, 32, 92, 34, 40, 205, 113, 167, 16, 26} - - output := DeriveECDHES("A128GCM", apuData, apvData, bobKey, &aliceKey.PublicKey, 16) - - if bytes.Compare(output, expected) != 0 { - t.Error("output did not match what we expect, got", output, "wanted", expected) - } -} - -func TestInvalidECPublicKey(t *testing.T) { - defer func() { recover() }() - - // Invalid key - invalid := &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: elliptic.P256(), - X: fromBase64Int("MTEx"), - Y: fromBase64Int("MTEx"), - }, - D: fromBase64Int("0_NxaRPUMQoAJt50Gz8YiTr8gRTwyEaCumd-MToTmIo="), - } - - DeriveECDHES("A128GCM", []byte{}, []byte{}, bobKey, &invalid.PublicKey, 16) - t.Fatal("should panic if public key was invalid") -} - -func BenchmarkECDHES_128(b *testing.B) { - apuData := []byte("APU") - apvData := []byte("APV") - - b.ResetTimer() - for i := 0; i < b.N; i++ { - DeriveECDHES("ID", apuData, apvData, bobKey, &aliceKey.PublicKey, 16) - } -} - -func BenchmarkECDHES_192(b *testing.B) { - apuData := []byte("APU") - apvData := []byte("APV") - - b.ResetTimer() - for i := 0; i < b.N; i++ { - DeriveECDHES("ID", apuData, apvData, bobKey, &aliceKey.PublicKey, 24) - } -} - -func BenchmarkECDHES_256(b *testing.B) { - apuData := []byte("APU") - apvData := []byte("APV") - - b.ResetTimer() - for i := 0; i < b.N; i++ { - DeriveECDHES("ID", apuData, apvData, bobKey, &aliceKey.PublicKey, 32) - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/cipher/key_wrap_test.go b/vendor/gopkg.in/square/go-jose.v2/cipher/key_wrap_test.go deleted file mode 100644 index ceecf812bf..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/cipher/key_wrap_test.go +++ /dev/null @@ -1,133 +0,0 @@ -/*- - * Copyright 2014 Square 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 josecipher - -import ( - "bytes" - "crypto/aes" - "encoding/hex" - "testing" -) - -func TestAesKeyWrap(t *testing.T) { - // Test vectors from: http://csrc.nist.gov/groups/ST/toolkit/documents/kms/key-wrap.pdf - kek0, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F") - cek0, _ := hex.DecodeString("00112233445566778899AABBCCDDEEFF") - - expected0, _ := hex.DecodeString("1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5") - - kek1, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F1011121314151617") - cek1, _ := hex.DecodeString("00112233445566778899AABBCCDDEEFF") - - expected1, _ := hex.DecodeString("96778B25AE6CA435F92B5B97C050AED2468AB8A17AD84E5D") - - kek2, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F") - cek2, _ := hex.DecodeString("00112233445566778899AABBCCDDEEFF0001020304050607") - - expected2, _ := hex.DecodeString("A8F9BC1612C68B3FF6E6F4FBE30E71E4769C8B80A32CB8958CD5D17D6B254DA1") - - block0, _ := aes.NewCipher(kek0) - block1, _ := aes.NewCipher(kek1) - block2, _ := aes.NewCipher(kek2) - - out0, _ := KeyWrap(block0, cek0) - out1, _ := KeyWrap(block1, cek1) - out2, _ := KeyWrap(block2, cek2) - - if bytes.Compare(out0, expected0) != 0 { - t.Error("output 0 not as expected, got", out0, "wanted", expected0) - } - - if bytes.Compare(out1, expected1) != 0 { - t.Error("output 1 not as expected, got", out1, "wanted", expected1) - } - - if bytes.Compare(out2, expected2) != 0 { - t.Error("output 2 not as expected, got", out2, "wanted", expected2) - } - - unwrap0, _ := KeyUnwrap(block0, out0) - unwrap1, _ := KeyUnwrap(block1, out1) - unwrap2, _ := KeyUnwrap(block2, out2) - - if bytes.Compare(unwrap0, cek0) != 0 { - t.Error("key unwrap did not return original input, got", unwrap0, "wanted", cek0) - } - - if bytes.Compare(unwrap1, cek1) != 0 { - t.Error("key unwrap did not return original input, got", unwrap1, "wanted", cek1) - } - - if bytes.Compare(unwrap2, cek2) != 0 { - t.Error("key unwrap did not return original input, got", unwrap2, "wanted", cek2) - } -} - -func TestAesKeyWrapInvalid(t *testing.T) { - kek, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F") - - // Invalid unwrap input (bit flipped) - input0, _ := hex.DecodeString("1EA68C1A8112B447AEF34BD8FB5A7B828D3E862371D2CFE5") - - block, _ := aes.NewCipher(kek) - - _, err := KeyUnwrap(block, input0) - if err == nil { - t.Error("key unwrap failed to detect invalid input") - } - - // Invalid unwrap input (truncated) - input1, _ := hex.DecodeString("1EA68C1A8112B447AEF34BD8FB5A7B828D3E862371D2CF") - - _, err = KeyUnwrap(block, input1) - if err == nil { - t.Error("key unwrap failed to detect truncated input") - } - - // Invalid wrap input (not multiple of 8) - input2, _ := hex.DecodeString("0123456789ABCD") - - _, err = KeyWrap(block, input2) - if err == nil { - t.Error("key wrap accepted invalid input") - } - -} - -func BenchmarkAesKeyWrap(b *testing.B) { - kek, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F") - key, _ := hex.DecodeString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF") - - block, _ := aes.NewCipher(kek) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - KeyWrap(block, key) - } -} - -func BenchmarkAesKeyUnwrap(b *testing.B) { - kek, _ := hex.DecodeString("000102030405060708090A0B0C0D0E0F") - input, _ := hex.DecodeString("1FA68B0A8112B447AEF34BD8FB5A7B829D3E862371D2CFE5") - - block, _ := aes.NewCipher(kek) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - KeyUnwrap(block, input) - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/crypter_test.go b/vendor/gopkg.in/square/go-jose.v2/crypter_test.go deleted file mode 100644 index 57eff1c377..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/crypter_test.go +++ /dev/null @@ -1,838 +0,0 @@ -/*- - * Copyright 2014 Square 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 jose - -import ( - "bytes" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "fmt" - "io" - "reflect" - "testing" - - "golang.org/x/crypto/ed25519" -) - -// We generate only a single RSA and EC key for testing, speeds up tests. -var rsaTestKey, _ = rsa.GenerateKey(rand.Reader, 2048) - -var ecTestKey256, _ = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) -var ecTestKey384, _ = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) -var ecTestKey521, _ = ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - -var ed25519PublicKey, ed25519PrivateKey, _ = ed25519.GenerateKey(rand.Reader) - -func RoundtripJWE(keyAlg KeyAlgorithm, encAlg ContentEncryption, compressionAlg CompressionAlgorithm, serializer func(*JSONWebEncryption) (string, error), corrupter func(*JSONWebEncryption) bool, aad []byte, encryptionKey interface{}, decryptionKey interface{}) error { - enc, err := NewEncrypter(encAlg, Recipient{Algorithm: keyAlg, Key: encryptionKey}, &EncrypterOptions{Compression: compressionAlg}) - if err != nil { - return fmt.Errorf("error on new encrypter: %s", err) - } - - input := []byte("Lorem ipsum dolor sit amet") - obj, err := enc.EncryptWithAuthData(input, aad) - if err != nil { - return fmt.Errorf("error in encrypt: %s", err) - } - - msg, err := serializer(obj) - if err != nil { - return fmt.Errorf("error in serializer: %s", err) - } - - parsed, err := ParseEncrypted(msg) - if err != nil { - return fmt.Errorf("error in parse: %s, on msg '%s'", err, msg) - } - - // (Maybe) mangle object - skip := corrupter(parsed) - if skip { - return fmt.Errorf("corrupter indicated message should be skipped") - } - - if bytes.Compare(parsed.GetAuthData(), aad) != 0 { - return fmt.Errorf("auth data in parsed object does not match") - } - - output, err := parsed.Decrypt(decryptionKey) - if err != nil { - return fmt.Errorf("error on decrypt: %s", err) - } - - if bytes.Compare(input, output) != 0 { - return fmt.Errorf("Decrypted output does not match input, got '%s' but wanted '%s'", output, input) - } - - return nil -} - -func TestRoundtripsJWE(t *testing.T) { - // Test matrix - keyAlgs := []KeyAlgorithm{ - DIRECT, ECDH_ES, ECDH_ES_A128KW, ECDH_ES_A192KW, ECDH_ES_A256KW, A128KW, A192KW, A256KW, - RSA1_5, RSA_OAEP, RSA_OAEP_256, A128GCMKW, A192GCMKW, A256GCMKW} - encAlgs := []ContentEncryption{A128GCM, A192GCM, A256GCM, A128CBC_HS256, A192CBC_HS384, A256CBC_HS512} - zipAlgs := []CompressionAlgorithm{NONE, DEFLATE} - - serializers := []func(*JSONWebEncryption) (string, error){ - func(obj *JSONWebEncryption) (string, error) { return obj.CompactSerialize() }, - func(obj *JSONWebEncryption) (string, error) { return obj.FullSerialize(), nil }, - } - - corrupter := func(obj *JSONWebEncryption) bool { return false } - - // Note: can't use AAD with compact serialization - aads := [][]byte{ - nil, - []byte("Ut enim ad minim veniam"), - } - - // Test all different configurations - for _, alg := range keyAlgs { - for _, enc := range encAlgs { - for _, key := range generateTestKeys(alg, enc) { - for _, zip := range zipAlgs { - for i, serializer := range serializers { - err := RoundtripJWE(alg, enc, zip, serializer, corrupter, aads[i], key.enc, key.dec) - if err != nil { - t.Error(err, alg, enc, zip, i) - } - } - } - } - } - } -} - -func TestRoundtripsJWECorrupted(t *testing.T) { - // Test matrix - keyAlgs := []KeyAlgorithm{DIRECT, ECDH_ES, ECDH_ES_A128KW, A128KW, RSA1_5, RSA_OAEP, RSA_OAEP_256, A128GCMKW} - encAlgs := []ContentEncryption{A128GCM, A192GCM, A256GCM, A128CBC_HS256, A192CBC_HS384, A256CBC_HS512} - zipAlgs := []CompressionAlgorithm{NONE, DEFLATE} - - serializers := []func(*JSONWebEncryption) (string, error){ - func(obj *JSONWebEncryption) (string, error) { return obj.CompactSerialize() }, - func(obj *JSONWebEncryption) (string, error) { return obj.FullSerialize(), nil }, - } - - bitflip := func(slice []byte) bool { - if len(slice) > 0 { - slice[0] ^= 0xFF - return false - } - return true - } - - corrupters := []func(*JSONWebEncryption) bool{ - func(obj *JSONWebEncryption) bool { - // Set invalid ciphertext - return bitflip(obj.ciphertext) - }, - func(obj *JSONWebEncryption) bool { - // Set invalid auth tag - return bitflip(obj.tag) - }, - func(obj *JSONWebEncryption) bool { - // Set invalid AAD - return bitflip(obj.aad) - }, - func(obj *JSONWebEncryption) bool { - // Mess with encrypted key - return bitflip(obj.recipients[0].encryptedKey) - }, - func(obj *JSONWebEncryption) bool { - // Mess with GCM-KW auth tag - tag, _ := obj.protected.getTag() - skip := bitflip(tag.bytes()) - if skip { - return true - } - obj.protected.set(headerTag, tag) - return false - }, - } - - // Note: can't use AAD with compact serialization - aads := [][]byte{ - nil, - []byte("Ut enim ad minim veniam"), - } - - // Test all different configurations - for _, alg := range keyAlgs { - for _, enc := range encAlgs { - for _, key := range generateTestKeys(alg, enc) { - for _, zip := range zipAlgs { - for i, serializer := range serializers { - for j, corrupter := range corrupters { - err := RoundtripJWE(alg, enc, zip, serializer, corrupter, aads[i], key.enc, key.dec) - if err == nil { - t.Error("failed to detect corrupt data", err, alg, enc, zip, i, j) - } - } - } - } - } - } - } -} - -func TestEncrypterWithJWKAndKeyID(t *testing.T) { - enc, err := NewEncrypter(A128GCM, Recipient{Algorithm: A128KW, Key: &JSONWebKey{ - KeyID: "test-id", - Key: []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, - }}, nil) - if err != nil { - t.Error(err) - } - - ciphertext, _ := enc.Encrypt([]byte("Lorem ipsum dolor sit amet")) - - serialized1, _ := ciphertext.CompactSerialize() - serialized2 := ciphertext.FullSerialize() - - parsed1, _ := ParseEncrypted(serialized1) - parsed2, _ := ParseEncrypted(serialized2) - - if parsed1.Header.KeyID != "test-id" { - t.Errorf("expected message to have key id from JWK, but found '%s' instead", parsed1.Header.KeyID) - } - if parsed2.Header.KeyID != "test-id" { - t.Errorf("expected message to have key id from JWK, but found '%s' instead", parsed2.Header.KeyID) - } -} - -func TestEncrypterWithBrokenRand(t *testing.T) { - keyAlgs := []KeyAlgorithm{ECDH_ES_A128KW, A128KW, RSA1_5, RSA_OAEP, RSA_OAEP_256, A128GCMKW} - encAlgs := []ContentEncryption{A128GCM, A192GCM, A256GCM, A128CBC_HS256, A192CBC_HS384, A256CBC_HS512} - - serializer := func(obj *JSONWebEncryption) (string, error) { return obj.CompactSerialize() } - corrupter := func(obj *JSONWebEncryption) bool { return false } - - // Break rand reader - readers := []func() io.Reader{ - // Totally broken - func() io.Reader { return bytes.NewReader([]byte{}) }, - // Not enough bytes - func() io.Reader { return io.LimitReader(rand.Reader, 20) }, - } - - defer resetRandReader() - - for _, alg := range keyAlgs { - for _, enc := range encAlgs { - for _, key := range generateTestKeys(alg, enc) { - for i, getReader := range readers { - randReader = getReader() - err := RoundtripJWE(alg, enc, NONE, serializer, corrupter, nil, key.enc, key.dec) - if err == nil { - t.Error("encrypter should fail if rand is broken", i) - } - } - } - } - } -} - -func TestNewEncrypterErrors(t *testing.T) { - _, err := NewEncrypter("XYZ", Recipient{}, nil) - if err == nil { - t.Error("was able to instantiate encrypter with invalid cipher") - } - - _, err = NewMultiEncrypter("XYZ", []Recipient{}, nil) - if err == nil { - t.Error("was able to instantiate multi-encrypter with invalid cipher") - } - - _, err = NewEncrypter(A128GCM, Recipient{Algorithm: DIRECT, Key: nil}, nil) - if err == nil { - t.Error("was able to instantiate encrypter with invalid direct key") - } - - _, err = NewEncrypter(A128GCM, Recipient{Algorithm: ECDH_ES, Key: nil}, nil) - if err == nil { - t.Error("was able to instantiate encrypter with invalid EC key") - } -} - -func TestMultiRecipientJWE(t *testing.T) { - sharedKey := []byte{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - } - - enc, err := NewMultiEncrypter(A128GCM, []Recipient{ - {Algorithm: RSA_OAEP, Key: &rsaTestKey.PublicKey}, - {Algorithm: A256GCMKW, Key: sharedKey}, - }, nil) - if err != nil { - panic(err) - } - - input := []byte("Lorem ipsum dolor sit amet") - obj, err := enc.Encrypt(input) - if err != nil { - t.Fatal("error in encrypt: ", err) - } - - msg := obj.FullSerialize() - - parsed, err := ParseEncrypted(msg) - if err != nil { - t.Fatal("error in parse: ", err) - } - - i, _, output, err := parsed.DecryptMulti(rsaTestKey) - if err != nil { - t.Fatal("error on decrypt with RSA: ", err) - } - - if i != 0 { - t.Fatal("recipient index should be 0 for RSA key") - } - - if bytes.Compare(input, output) != 0 { - t.Fatal("Decrypted output does not match input: ", output, input) - } - - i, _, output, err = parsed.DecryptMulti(sharedKey) - if err != nil { - t.Fatal("error on decrypt with AES: ", err) - } - - if i != 1 { - t.Fatal("recipient index should be 1 for shared key") - } - - if bytes.Compare(input, output) != 0 { - t.Fatal("Decrypted output does not match input", output, input) - } -} - -func TestMultiRecipientErrors(t *testing.T) { - _, err := NewMultiEncrypter(A128GCM, []Recipient{}, nil) - if err == nil { - t.Error("should fail to instantiate with zero recipients") - } -} - -func TestEncrypterOptions(t *testing.T) { - sharedKey := []byte{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - } - - opts := &EncrypterOptions{ - Compression: DEFLATE, - } - opts.WithType("JWT") - opts.WithContentType("JWT") - enc, err := NewEncrypter(A256GCM, Recipient{Algorithm: A256GCMKW, Key: sharedKey}, opts) - if err != nil { - fmt.Println(err) - t.Error("Failed to create encrypter") - } - - if !reflect.DeepEqual(*opts, enc.Options()) { - t.Error("Encrypter options do not match") - } -} - -// Test that extra headers are generated and parsed in a round trip. -func TestEncrypterExtraHeaderInclusion(t *testing.T) { - sharedKey := []byte{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - } - - opts := &EncrypterOptions{ - Compression: DEFLATE, - } - opts.WithType("JWT") - opts.WithContentType("JWT") - opts.WithHeader(HeaderKey("myCustomHeader"), "xyz") - enc, err := NewEncrypter(A256GCM, Recipient{Algorithm: A256GCMKW, Key: sharedKey}, opts) - if err != nil { - fmt.Println(err) - t.Error("Failed to create encrypter") - } - - if !reflect.DeepEqual(*opts, enc.Options()) { - t.Error("Encrypter options do not match") - } - - input := []byte("Lorem ipsum dolor sit amet") - obj, err := enc.Encrypt(input) - if err != nil { - t.Fatal("error in encrypt: ", err) - } - - parsed, err := ParseEncrypted(obj.FullSerialize()) - if err != nil { - t.Fatal("error in parse: ", err) - } - - output, err := parsed.Decrypt(sharedKey) - if err != nil { - t.Fatal("error on decrypt: ", err) - } - - if bytes.Compare(input, output) != 0 { - t.Fatal("Decrypted output does not match input: ", output, input) - } - - if parsed.Header.ExtraHeaders[HeaderType] != "JWT" || - parsed.Header.ExtraHeaders[HeaderContentType] != "JWT" || - parsed.Header.ExtraHeaders[HeaderKey("myCustomHeader")] != "xyz" { - t.Fatalf("Mismatch in extra headers: %#v", parsed.Header.ExtraHeaders) - } -} - -type testKey struct { - enc, dec interface{} -} - -func symmetricTestKey(size int) []testKey { - key, _, _ := randomKeyGenerator{size: size}.genKey() - - return []testKey{ - { - enc: key, - dec: key, - }, - { - enc: &JSONWebKey{KeyID: "test", Key: key}, - dec: &JSONWebKey{KeyID: "test", Key: key}, - }, - } -} - -func generateTestKeys(keyAlg KeyAlgorithm, encAlg ContentEncryption) []testKey { - switch keyAlg { - case DIRECT: - return symmetricTestKey(getContentCipher(encAlg).keySize()) - case ECDH_ES, ECDH_ES_A128KW, ECDH_ES_A192KW, ECDH_ES_A256KW: - return []testKey{ - { - dec: ecTestKey256, - enc: &ecTestKey256.PublicKey, - }, - { - dec: ecTestKey384, - enc: &ecTestKey384.PublicKey, - }, - { - dec: ecTestKey521, - enc: &ecTestKey521.PublicKey, - }, - { - dec: &JSONWebKey{KeyID: "test", Key: ecTestKey256}, - enc: &JSONWebKey{KeyID: "test", Key: &ecTestKey256.PublicKey}, - }, - } - case A128GCMKW, A128KW: - return symmetricTestKey(16) - case A192GCMKW, A192KW: - return symmetricTestKey(24) - case A256GCMKW, A256KW: - return symmetricTestKey(32) - case RSA1_5, RSA_OAEP, RSA_OAEP_256: - return []testKey{{ - dec: rsaTestKey, - enc: &rsaTestKey.PublicKey, - }} - } - - panic("Must update test case") -} - -func RunRoundtripsJWE(b *testing.B, alg KeyAlgorithm, enc ContentEncryption, zip CompressionAlgorithm, priv, pub interface{}) { - serializer := func(obj *JSONWebEncryption) (string, error) { - return obj.CompactSerialize() - } - - corrupter := func(obj *JSONWebEncryption) bool { return false } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - err := RoundtripJWE(alg, enc, zip, serializer, corrupter, nil, pub, priv) - if err != nil { - b.Error(err) - } - } -} - -var ( - chunks = map[string][]byte{ - "1B": make([]byte, 1), - "64B": make([]byte, 64), - "1KB": make([]byte, 1024), - "64KB": make([]byte, 65536), - "1MB": make([]byte, 1048576), - "64MB": make([]byte, 67108864), - } - - symKey, _, _ = randomKeyGenerator{size: 32}.genKey() - - encrypters = map[string]Encrypter{ - "OAEPAndGCM": mustEncrypter(RSA_OAEP, A128GCM, &rsaTestKey.PublicKey), - "PKCSAndGCM": mustEncrypter(RSA1_5, A128GCM, &rsaTestKey.PublicKey), - "OAEPAndCBC": mustEncrypter(RSA_OAEP, A128CBC_HS256, &rsaTestKey.PublicKey), - "PKCSAndCBC": mustEncrypter(RSA1_5, A128CBC_HS256, &rsaTestKey.PublicKey), - "DirectGCM128": mustEncrypter(DIRECT, A128GCM, symKey), - "DirectCBC128": mustEncrypter(DIRECT, A128CBC_HS256, symKey), - "DirectGCM256": mustEncrypter(DIRECT, A256GCM, symKey), - "DirectCBC256": mustEncrypter(DIRECT, A256CBC_HS512, symKey), - "AESKWAndGCM128": mustEncrypter(A128KW, A128GCM, symKey), - "AESKWAndCBC256": mustEncrypter(A256KW, A256GCM, symKey), - "ECDHOnP256AndGCM128": mustEncrypter(ECDH_ES, A128GCM, &ecTestKey256.PublicKey), - "ECDHOnP384AndGCM128": mustEncrypter(ECDH_ES, A128GCM, &ecTestKey384.PublicKey), - "ECDHOnP521AndGCM128": mustEncrypter(ECDH_ES, A128GCM, &ecTestKey521.PublicKey), - } -) - -func BenchmarkEncrypt1BWithOAEPAndGCM(b *testing.B) { benchEncrypt("1B", "OAEPAndGCM", b) } -func BenchmarkEncrypt64BWithOAEPAndGCM(b *testing.B) { benchEncrypt("64B", "OAEPAndGCM", b) } -func BenchmarkEncrypt1KBWithOAEPAndGCM(b *testing.B) { benchEncrypt("1KB", "OAEPAndGCM", b) } -func BenchmarkEncrypt64KBWithOAEPAndGCM(b *testing.B) { benchEncrypt("64KB", "OAEPAndGCM", b) } -func BenchmarkEncrypt1MBWithOAEPAndGCM(b *testing.B) { benchEncrypt("1MB", "OAEPAndGCM", b) } -func BenchmarkEncrypt64MBWithOAEPAndGCM(b *testing.B) { benchEncrypt("64MB", "OAEPAndGCM", b) } - -func BenchmarkEncrypt1BWithPKCSAndGCM(b *testing.B) { benchEncrypt("1B", "PKCSAndGCM", b) } -func BenchmarkEncrypt64BWithPKCSAndGCM(b *testing.B) { benchEncrypt("64B", "PKCSAndGCM", b) } -func BenchmarkEncrypt1KBWithPKCSAndGCM(b *testing.B) { benchEncrypt("1KB", "PKCSAndGCM", b) } -func BenchmarkEncrypt64KBWithPKCSAndGCM(b *testing.B) { benchEncrypt("64KB", "PKCSAndGCM", b) } -func BenchmarkEncrypt1MBWithPKCSAndGCM(b *testing.B) { benchEncrypt("1MB", "PKCSAndGCM", b) } -func BenchmarkEncrypt64MBWithPKCSAndGCM(b *testing.B) { benchEncrypt("64MB", "PKCSAndGCM", b) } - -func BenchmarkEncrypt1BWithOAEPAndCBC(b *testing.B) { benchEncrypt("1B", "OAEPAndCBC", b) } -func BenchmarkEncrypt64BWithOAEPAndCBC(b *testing.B) { benchEncrypt("64B", "OAEPAndCBC", b) } -func BenchmarkEncrypt1KBWithOAEPAndCBC(b *testing.B) { benchEncrypt("1KB", "OAEPAndCBC", b) } -func BenchmarkEncrypt64KBWithOAEPAndCBC(b *testing.B) { benchEncrypt("64KB", "OAEPAndCBC", b) } -func BenchmarkEncrypt1MBWithOAEPAndCBC(b *testing.B) { benchEncrypt("1MB", "OAEPAndCBC", b) } -func BenchmarkEncrypt64MBWithOAEPAndCBC(b *testing.B) { benchEncrypt("64MB", "OAEPAndCBC", b) } - -func BenchmarkEncrypt1BWithPKCSAndCBC(b *testing.B) { benchEncrypt("1B", "PKCSAndCBC", b) } -func BenchmarkEncrypt64BWithPKCSAndCBC(b *testing.B) { benchEncrypt("64B", "PKCSAndCBC", b) } -func BenchmarkEncrypt1KBWithPKCSAndCBC(b *testing.B) { benchEncrypt("1KB", "PKCSAndCBC", b) } -func BenchmarkEncrypt64KBWithPKCSAndCBC(b *testing.B) { benchEncrypt("64KB", "PKCSAndCBC", b) } -func BenchmarkEncrypt1MBWithPKCSAndCBC(b *testing.B) { benchEncrypt("1MB", "PKCSAndCBC", b) } -func BenchmarkEncrypt64MBWithPKCSAndCBC(b *testing.B) { benchEncrypt("64MB", "PKCSAndCBC", b) } - -func BenchmarkEncrypt1BWithDirectGCM128(b *testing.B) { benchEncrypt("1B", "DirectGCM128", b) } -func BenchmarkEncrypt64BWithDirectGCM128(b *testing.B) { benchEncrypt("64B", "DirectGCM128", b) } -func BenchmarkEncrypt1KBWithDirectGCM128(b *testing.B) { benchEncrypt("1KB", "DirectGCM128", b) } -func BenchmarkEncrypt64KBWithDirectGCM128(b *testing.B) { benchEncrypt("64KB", "DirectGCM128", b) } -func BenchmarkEncrypt1MBWithDirectGCM128(b *testing.B) { benchEncrypt("1MB", "DirectGCM128", b) } -func BenchmarkEncrypt64MBWithDirectGCM128(b *testing.B) { benchEncrypt("64MB", "DirectGCM128", b) } - -func BenchmarkEncrypt1BWithDirectCBC128(b *testing.B) { benchEncrypt("1B", "DirectCBC128", b) } -func BenchmarkEncrypt64BWithDirectCBC128(b *testing.B) { benchEncrypt("64B", "DirectCBC128", b) } -func BenchmarkEncrypt1KBWithDirectCBC128(b *testing.B) { benchEncrypt("1KB", "DirectCBC128", b) } -func BenchmarkEncrypt64KBWithDirectCBC128(b *testing.B) { benchEncrypt("64KB", "DirectCBC128", b) } -func BenchmarkEncrypt1MBWithDirectCBC128(b *testing.B) { benchEncrypt("1MB", "DirectCBC128", b) } -func BenchmarkEncrypt64MBWithDirectCBC128(b *testing.B) { benchEncrypt("64MB", "DirectCBC128", b) } - -func BenchmarkEncrypt1BWithDirectGCM256(b *testing.B) { benchEncrypt("1B", "DirectGCM256", b) } -func BenchmarkEncrypt64BWithDirectGCM256(b *testing.B) { benchEncrypt("64B", "DirectGCM256", b) } -func BenchmarkEncrypt1KBWithDirectGCM256(b *testing.B) { benchEncrypt("1KB", "DirectGCM256", b) } -func BenchmarkEncrypt64KBWithDirectGCM256(b *testing.B) { benchEncrypt("64KB", "DirectGCM256", b) } -func BenchmarkEncrypt1MBWithDirectGCM256(b *testing.B) { benchEncrypt("1MB", "DirectGCM256", b) } -func BenchmarkEncrypt64MBWithDirectGCM256(b *testing.B) { benchEncrypt("64MB", "DirectGCM256", b) } - -func BenchmarkEncrypt1BWithDirectCBC256(b *testing.B) { benchEncrypt("1B", "DirectCBC256", b) } -func BenchmarkEncrypt64BWithDirectCBC256(b *testing.B) { benchEncrypt("64B", "DirectCBC256", b) } -func BenchmarkEncrypt1KBWithDirectCBC256(b *testing.B) { benchEncrypt("1KB", "DirectCBC256", b) } -func BenchmarkEncrypt64KBWithDirectCBC256(b *testing.B) { benchEncrypt("64KB", "DirectCBC256", b) } -func BenchmarkEncrypt1MBWithDirectCBC256(b *testing.B) { benchEncrypt("1MB", "DirectCBC256", b) } -func BenchmarkEncrypt64MBWithDirectCBC256(b *testing.B) { benchEncrypt("64MB", "DirectCBC256", b) } - -func BenchmarkEncrypt1BWithAESKWAndGCM128(b *testing.B) { benchEncrypt("1B", "AESKWAndGCM128", b) } -func BenchmarkEncrypt64BWithAESKWAndGCM128(b *testing.B) { benchEncrypt("64B", "AESKWAndGCM128", b) } -func BenchmarkEncrypt1KBWithAESKWAndGCM128(b *testing.B) { benchEncrypt("1KB", "AESKWAndGCM128", b) } -func BenchmarkEncrypt64KBWithAESKWAndGCM128(b *testing.B) { benchEncrypt("64KB", "AESKWAndGCM128", b) } -func BenchmarkEncrypt1MBWithAESKWAndGCM128(b *testing.B) { benchEncrypt("1MB", "AESKWAndGCM128", b) } -func BenchmarkEncrypt64MBWithAESKWAndGCM128(b *testing.B) { benchEncrypt("64MB", "AESKWAndGCM128", b) } - -func BenchmarkEncrypt1BWithAESKWAndCBC256(b *testing.B) { benchEncrypt("1B", "AESKWAndCBC256", b) } -func BenchmarkEncrypt64BWithAESKWAndCBC256(b *testing.B) { benchEncrypt("64B", "AESKWAndCBC256", b) } -func BenchmarkEncrypt1KBWithAESKWAndCBC256(b *testing.B) { benchEncrypt("1KB", "AESKWAndCBC256", b) } -func BenchmarkEncrypt64KBWithAESKWAndCBC256(b *testing.B) { benchEncrypt("64KB", "AESKWAndCBC256", b) } -func BenchmarkEncrypt1MBWithAESKWAndCBC256(b *testing.B) { benchEncrypt("1MB", "AESKWAndCBC256", b) } -func BenchmarkEncrypt64MBWithAESKWAndCBC256(b *testing.B) { benchEncrypt("64MB", "AESKWAndCBC256", b) } - -func BenchmarkEncrypt1BWithECDHOnP256AndGCM128(b *testing.B) { - benchEncrypt("1B", "ECDHOnP256AndGCM128", b) -} -func BenchmarkEncrypt64BWithECDHOnP256AndGCM128(b *testing.B) { - benchEncrypt("64B", "ECDHOnP256AndGCM128", b) -} -func BenchmarkEncrypt1KBWithECDHOnP256AndGCM128(b *testing.B) { - benchEncrypt("1KB", "ECDHOnP256AndGCM128", b) -} -func BenchmarkEncrypt64KBWithECDHOnP256AndGCM128(b *testing.B) { - benchEncrypt("64KB", "ECDHOnP256AndGCM128", b) -} -func BenchmarkEncrypt1MBWithECDHOnP256AndGCM128(b *testing.B) { - benchEncrypt("1MB", "ECDHOnP256AndGCM128", b) -} -func BenchmarkEncrypt64MBWithECDHOnP256AndGCM128(b *testing.B) { - benchEncrypt("64MB", "ECDHOnP256AndGCM128", b) -} - -func BenchmarkEncrypt1BWithECDHOnP384AndGCM128(b *testing.B) { - benchEncrypt("1B", "ECDHOnP384AndGCM128", b) -} -func BenchmarkEncrypt64BWithECDHOnP384AndGCM128(b *testing.B) { - benchEncrypt("64B", "ECDHOnP384AndGCM128", b) -} -func BenchmarkEncrypt1KBWithECDHOnP384AndGCM128(b *testing.B) { - benchEncrypt("1KB", "ECDHOnP384AndGCM128", b) -} -func BenchmarkEncrypt64KBWithECDHOnP384AndGCM128(b *testing.B) { - benchEncrypt("64KB", "ECDHOnP384AndGCM128", b) -} -func BenchmarkEncrypt1MBWithECDHOnP384AndGCM128(b *testing.B) { - benchEncrypt("1MB", "ECDHOnP384AndGCM128", b) -} -func BenchmarkEncrypt64MBWithECDHOnP384AndGCM128(b *testing.B) { - benchEncrypt("64MB", "ECDHOnP384AndGCM128", b) -} - -func BenchmarkEncrypt1BWithECDHOnP521AndGCM128(b *testing.B) { - benchEncrypt("1B", "ECDHOnP521AndGCM128", b) -} -func BenchmarkEncrypt64BWithECDHOnP521AndGCM128(b *testing.B) { - benchEncrypt("64B", "ECDHOnP521AndGCM128", b) -} -func BenchmarkEncrypt1KBWithECDHOnP521AndGCM128(b *testing.B) { - benchEncrypt("1KB", "ECDHOnP521AndGCM128", b) -} -func BenchmarkEncrypt64KBWithECDHOnP521AndGCM128(b *testing.B) { - benchEncrypt("64KB", "ECDHOnP521AndGCM128", b) -} -func BenchmarkEncrypt1MBWithECDHOnP521AndGCM128(b *testing.B) { - benchEncrypt("1MB", "ECDHOnP521AndGCM128", b) -} -func BenchmarkEncrypt64MBWithECDHOnP521AndGCM128(b *testing.B) { - benchEncrypt("64MB", "ECDHOnP521AndGCM128", b) -} - -func benchEncrypt(chunkKey, primKey string, b *testing.B) { - data, ok := chunks[chunkKey] - if !ok { - b.Fatalf("unknown chunk size %s", chunkKey) - } - - enc, ok := encrypters[primKey] - if !ok { - b.Fatalf("unknown encrypter %s", primKey) - } - - b.SetBytes(int64(len(data))) - for i := 0; i < b.N; i++ { - enc.Encrypt(data) - } -} - -var ( - decryptionKeys = map[string]interface{}{ - "OAEPAndGCM": rsaTestKey, - "PKCSAndGCM": rsaTestKey, - "OAEPAndCBC": rsaTestKey, - "PKCSAndCBC": rsaTestKey, - - "DirectGCM128": symKey, - "DirectCBC128": symKey, - "DirectGCM256": symKey, - "DirectCBC256": symKey, - - "AESKWAndGCM128": symKey, - "AESKWAndCBC256": symKey, - - "ECDHOnP256AndGCM128": ecTestKey256, - "ECDHOnP384AndGCM128": ecTestKey384, - "ECDHOnP521AndGCM128": ecTestKey521, - } -) - -func BenchmarkDecrypt1BWithOAEPAndGCM(b *testing.B) { benchDecrypt("1B", "OAEPAndGCM", b) } -func BenchmarkDecrypt64BWithOAEPAndGCM(b *testing.B) { benchDecrypt("64B", "OAEPAndGCM", b) } -func BenchmarkDecrypt1KBWithOAEPAndGCM(b *testing.B) { benchDecrypt("1KB", "OAEPAndGCM", b) } -func BenchmarkDecrypt64KBWithOAEPAndGCM(b *testing.B) { benchDecrypt("64KB", "OAEPAndGCM", b) } -func BenchmarkDecrypt1MBWithOAEPAndGCM(b *testing.B) { benchDecrypt("1MB", "OAEPAndGCM", b) } -func BenchmarkDecrypt64MBWithOAEPAndGCM(b *testing.B) { benchDecrypt("64MB", "OAEPAndGCM", b) } - -func BenchmarkDecrypt1BWithPKCSAndGCM(b *testing.B) { benchDecrypt("1B", "PKCSAndGCM", b) } -func BenchmarkDecrypt64BWithPKCSAndGCM(b *testing.B) { benchDecrypt("64B", "PKCSAndGCM", b) } -func BenchmarkDecrypt1KBWithPKCSAndGCM(b *testing.B) { benchDecrypt("1KB", "PKCSAndGCM", b) } -func BenchmarkDecrypt64KBWithPKCSAndGCM(b *testing.B) { benchDecrypt("64KB", "PKCSAndGCM", b) } -func BenchmarkDecrypt1MBWithPKCSAndGCM(b *testing.B) { benchDecrypt("1MB", "PKCSAndGCM", b) } -func BenchmarkDecrypt64MBWithPKCSAndGCM(b *testing.B) { benchDecrypt("64MB", "PKCSAndGCM", b) } - -func BenchmarkDecrypt1BWithOAEPAndCBC(b *testing.B) { benchDecrypt("1B", "OAEPAndCBC", b) } -func BenchmarkDecrypt64BWithOAEPAndCBC(b *testing.B) { benchDecrypt("64B", "OAEPAndCBC", b) } -func BenchmarkDecrypt1KBWithOAEPAndCBC(b *testing.B) { benchDecrypt("1KB", "OAEPAndCBC", b) } -func BenchmarkDecrypt64KBWithOAEPAndCBC(b *testing.B) { benchDecrypt("64KB", "OAEPAndCBC", b) } -func BenchmarkDecrypt1MBWithOAEPAndCBC(b *testing.B) { benchDecrypt("1MB", "OAEPAndCBC", b) } -func BenchmarkDecrypt64MBWithOAEPAndCBC(b *testing.B) { benchDecrypt("64MB", "OAEPAndCBC", b) } - -func BenchmarkDecrypt1BWithPKCSAndCBC(b *testing.B) { benchDecrypt("1B", "PKCSAndCBC", b) } -func BenchmarkDecrypt64BWithPKCSAndCBC(b *testing.B) { benchDecrypt("64B", "PKCSAndCBC", b) } -func BenchmarkDecrypt1KBWithPKCSAndCBC(b *testing.B) { benchDecrypt("1KB", "PKCSAndCBC", b) } -func BenchmarkDecrypt64KBWithPKCSAndCBC(b *testing.B) { benchDecrypt("64KB", "PKCSAndCBC", b) } -func BenchmarkDecrypt1MBWithPKCSAndCBC(b *testing.B) { benchDecrypt("1MB", "PKCSAndCBC", b) } -func BenchmarkDecrypt64MBWithPKCSAndCBC(b *testing.B) { benchDecrypt("64MB", "PKCSAndCBC", b) } - -func BenchmarkDecrypt1BWithDirectGCM128(b *testing.B) { benchDecrypt("1B", "DirectGCM128", b) } -func BenchmarkDecrypt64BWithDirectGCM128(b *testing.B) { benchDecrypt("64B", "DirectGCM128", b) } -func BenchmarkDecrypt1KBWithDirectGCM128(b *testing.B) { benchDecrypt("1KB", "DirectGCM128", b) } -func BenchmarkDecrypt64KBWithDirectGCM128(b *testing.B) { benchDecrypt("64KB", "DirectGCM128", b) } -func BenchmarkDecrypt1MBWithDirectGCM128(b *testing.B) { benchDecrypt("1MB", "DirectGCM128", b) } -func BenchmarkDecrypt64MBWithDirectGCM128(b *testing.B) { benchDecrypt("64MB", "DirectGCM128", b) } - -func BenchmarkDecrypt1BWithDirectCBC128(b *testing.B) { benchDecrypt("1B", "DirectCBC128", b) } -func BenchmarkDecrypt64BWithDirectCBC128(b *testing.B) { benchDecrypt("64B", "DirectCBC128", b) } -func BenchmarkDecrypt1KBWithDirectCBC128(b *testing.B) { benchDecrypt("1KB", "DirectCBC128", b) } -func BenchmarkDecrypt64KBWithDirectCBC128(b *testing.B) { benchDecrypt("64KB", "DirectCBC128", b) } -func BenchmarkDecrypt1MBWithDirectCBC128(b *testing.B) { benchDecrypt("1MB", "DirectCBC128", b) } -func BenchmarkDecrypt64MBWithDirectCBC128(b *testing.B) { benchDecrypt("64MB", "DirectCBC128", b) } - -func BenchmarkDecrypt1BWithDirectGCM256(b *testing.B) { benchDecrypt("1B", "DirectGCM256", b) } -func BenchmarkDecrypt64BWithDirectGCM256(b *testing.B) { benchDecrypt("64B", "DirectGCM256", b) } -func BenchmarkDecrypt1KBWithDirectGCM256(b *testing.B) { benchDecrypt("1KB", "DirectGCM256", b) } -func BenchmarkDecrypt64KBWithDirectGCM256(b *testing.B) { benchDecrypt("64KB", "DirectGCM256", b) } -func BenchmarkDecrypt1MBWithDirectGCM256(b *testing.B) { benchDecrypt("1MB", "DirectGCM256", b) } -func BenchmarkDecrypt64MBWithDirectGCM256(b *testing.B) { benchDecrypt("64MB", "DirectGCM256", b) } - -func BenchmarkDecrypt1BWithDirectCBC256(b *testing.B) { benchDecrypt("1B", "DirectCBC256", b) } -func BenchmarkDecrypt64BWithDirectCBC256(b *testing.B) { benchDecrypt("64B", "DirectCBC256", b) } -func BenchmarkDecrypt1KBWithDirectCBC256(b *testing.B) { benchDecrypt("1KB", "DirectCBC256", b) } -func BenchmarkDecrypt64KBWithDirectCBC256(b *testing.B) { benchDecrypt("64KB", "DirectCBC256", b) } -func BenchmarkDecrypt1MBWithDirectCBC256(b *testing.B) { benchDecrypt("1MB", "DirectCBC256", b) } -func BenchmarkDecrypt64MBWithDirectCBC256(b *testing.B) { benchDecrypt("64MB", "DirectCBC256", b) } - -func BenchmarkDecrypt1BWithAESKWAndGCM128(b *testing.B) { benchDecrypt("1B", "AESKWAndGCM128", b) } -func BenchmarkDecrypt64BWithAESKWAndGCM128(b *testing.B) { benchDecrypt("64B", "AESKWAndGCM128", b) } -func BenchmarkDecrypt1KBWithAESKWAndGCM128(b *testing.B) { benchDecrypt("1KB", "AESKWAndGCM128", b) } -func BenchmarkDecrypt64KBWithAESKWAndGCM128(b *testing.B) { benchDecrypt("64KB", "AESKWAndGCM128", b) } -func BenchmarkDecrypt1MBWithAESKWAndGCM128(b *testing.B) { benchDecrypt("1MB", "AESKWAndGCM128", b) } -func BenchmarkDecrypt64MBWithAESKWAndGCM128(b *testing.B) { benchDecrypt("64MB", "AESKWAndGCM128", b) } - -func BenchmarkDecrypt1BWithAESKWAndCBC256(b *testing.B) { benchDecrypt("1B", "AESKWAndCBC256", b) } -func BenchmarkDecrypt64BWithAESKWAndCBC256(b *testing.B) { benchDecrypt("64B", "AESKWAndCBC256", b) } -func BenchmarkDecrypt1KBWithAESKWAndCBC256(b *testing.B) { benchDecrypt("1KB", "AESKWAndCBC256", b) } -func BenchmarkDecrypt64KBWithAESKWAndCBC256(b *testing.B) { benchDecrypt("64KB", "AESKWAndCBC256", b) } -func BenchmarkDecrypt1MBWithAESKWAndCBC256(b *testing.B) { benchDecrypt("1MB", "AESKWAndCBC256", b) } -func BenchmarkDecrypt64MBWithAESKWAndCBC256(b *testing.B) { benchDecrypt("64MB", "AESKWAndCBC256", b) } - -func BenchmarkDecrypt1BWithECDHOnP256AndGCM128(b *testing.B) { - benchDecrypt("1B", "ECDHOnP256AndGCM128", b) -} -func BenchmarkDecrypt64BWithECDHOnP256AndGCM128(b *testing.B) { - benchDecrypt("64B", "ECDHOnP256AndGCM128", b) -} -func BenchmarkDecrypt1KBWithECDHOnP256AndGCM128(b *testing.B) { - benchDecrypt("1KB", "ECDHOnP256AndGCM128", b) -} -func BenchmarkDecrypt64KBWithECDHOnP256AndGCM128(b *testing.B) { - benchDecrypt("64KB", "ECDHOnP256AndGCM128", b) -} -func BenchmarkDecrypt1MBWithECDHOnP256AndGCM128(b *testing.B) { - benchDecrypt("1MB", "ECDHOnP256AndGCM128", b) -} -func BenchmarkDecrypt64MBWithECDHOnP256AndGCM128(b *testing.B) { - benchDecrypt("64MB", "ECDHOnP256AndGCM128", b) -} - -func BenchmarkDecrypt1BWithECDHOnP384AndGCM128(b *testing.B) { - benchDecrypt("1B", "ECDHOnP384AndGCM128", b) -} -func BenchmarkDecrypt64BWithECDHOnP384AndGCM128(b *testing.B) { - benchDecrypt("64B", "ECDHOnP384AndGCM128", b) -} -func BenchmarkDecrypt1KBWithECDHOnP384AndGCM128(b *testing.B) { - benchDecrypt("1KB", "ECDHOnP384AndGCM128", b) -} -func BenchmarkDecrypt64KBWithECDHOnP384AndGCM128(b *testing.B) { - benchDecrypt("64KB", "ECDHOnP384AndGCM128", b) -} -func BenchmarkDecrypt1MBWithECDHOnP384AndGCM128(b *testing.B) { - benchDecrypt("1MB", "ECDHOnP384AndGCM128", b) -} -func BenchmarkDecrypt64MBWithECDHOnP384AndGCM128(b *testing.B) { - benchDecrypt("64MB", "ECDHOnP384AndGCM128", b) -} - -func BenchmarkDecrypt1BWithECDHOnP521AndGCM128(b *testing.B) { - benchDecrypt("1B", "ECDHOnP521AndGCM128", b) -} -func BenchmarkDecrypt64BWithECDHOnP521AndGCM128(b *testing.B) { - benchDecrypt("64B", "ECDHOnP521AndGCM128", b) -} -func BenchmarkDecrypt1KBWithECDHOnP521AndGCM128(b *testing.B) { - benchDecrypt("1KB", "ECDHOnP521AndGCM128", b) -} -func BenchmarkDecrypt64KBWithECDHOnP521AndGCM128(b *testing.B) { - benchDecrypt("64KB", "ECDHOnP521AndGCM128", b) -} -func BenchmarkDecrypt1MBWithECDHOnP521AndGCM128(b *testing.B) { - benchDecrypt("1MB", "ECDHOnP521AndGCM128", b) -} -func BenchmarkDecrypt64MBWithECDHOnP521AndGCM128(b *testing.B) { - benchDecrypt("64MB", "ECDHOnP521AndGCM128", b) -} - -func benchDecrypt(chunkKey, primKey string, b *testing.B) { - chunk, ok := chunks[chunkKey] - if !ok { - b.Fatalf("unknown chunk size %s", chunkKey) - } - - enc, ok := encrypters[primKey] - if !ok { - b.Fatalf("unknown encrypter %s", primKey) - } - - dec, ok := decryptionKeys[primKey] - if !ok { - b.Fatalf("unknown decryption key %s", primKey) - } - - data, err := enc.Encrypt(chunk) - if err != nil { - b.Fatal(err) - } - - b.SetBytes(int64(len(chunk))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - data.Decrypt(dec) - } -} - -func mustEncrypter(keyAlg KeyAlgorithm, encAlg ContentEncryption, encryptionKey interface{}) Encrypter { - enc, err := NewEncrypter(encAlg, Recipient{Algorithm: keyAlg, Key: encryptionKey}, nil) - if err != nil { - panic(err) - } - return enc -} diff --git a/vendor/gopkg.in/square/go-jose.v2/doc_test.go b/vendor/gopkg.in/square/go-jose.v2/doc_test.go deleted file mode 100644 index 1ee1478bc4..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/doc_test.go +++ /dev/null @@ -1,201 +0,0 @@ -/*- - * Copyright 2014 Square 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 jose - -import ( - "crypto/ecdsa" - "crypto/rand" - "crypto/rsa" - "fmt" -) - -// Dummy encrypter for use in examples -var encrypter Encrypter - -func Example_jWE() { - // Generate a public/private key pair to use for this example. - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - panic(err) - } - - // Instantiate an encrypter using RSA-OAEP with AES128-GCM. An error would - // indicate that the selected algorithm(s) are not currently supported. - publicKey := &privateKey.PublicKey - encrypter, err := NewEncrypter(A128GCM, Recipient{Algorithm: RSA_OAEP, Key: publicKey}, nil) - if err != nil { - panic(err) - } - - // Encrypt a sample plaintext. Calling the encrypter returns an encrypted - // JWE object, which can then be serialized for output afterwards. An error - // would indicate a problem in an underlying cryptographic primitive. - var plaintext = []byte("Lorem ipsum dolor sit amet") - object, err := encrypter.Encrypt(plaintext) - if err != nil { - panic(err) - } - - // Serialize the encrypted object using the full serialization format. - // Alternatively you can also use the compact format here by calling - // object.CompactSerialize() instead. - serialized := object.FullSerialize() - - // Parse the serialized, encrypted JWE object. An error would indicate that - // the given input did not represent a valid message. - object, err = ParseEncrypted(serialized) - if err != nil { - panic(err) - } - - // Now we can decrypt and get back our original plaintext. An error here - // would indicate the the message failed to decrypt, e.g. because the auth - // tag was broken or the message was tampered with. - decrypted, err := object.Decrypt(privateKey) - if err != nil { - panic(err) - } - - fmt.Printf(string(decrypted)) - // output: Lorem ipsum dolor sit amet -} - -func Example_jWS() { - // Generate a public/private key pair to use for this example. - privateKey, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - panic(err) - } - - // Instantiate a signer using RSASSA-PSS (SHA512) with the given private key. - signer, err := NewSigner(SigningKey{Algorithm: PS512, Key: privateKey}, nil) - if err != nil { - panic(err) - } - - // Sign a sample payload. Calling the signer returns a protected JWS object, - // which can then be serialized for output afterwards. An error would - // indicate a problem in an underlying cryptographic primitive. - var payload = []byte("Lorem ipsum dolor sit amet") - object, err := signer.Sign(payload) - if err != nil { - panic(err) - } - - // Serialize the encrypted object using the full serialization format. - // Alternatively you can also use the compact format here by calling - // object.CompactSerialize() instead. - serialized := object.FullSerialize() - - // Parse the serialized, protected JWS object. An error would indicate that - // the given input did not represent a valid message. - object, err = ParseSigned(serialized) - if err != nil { - panic(err) - } - - // Now we can verify the signature on the payload. An error here would - // indicate the the message failed to verify, e.g. because the signature was - // broken or the message was tampered with. - output, err := object.Verify(&privateKey.PublicKey) - if err != nil { - panic(err) - } - - fmt.Printf(string(output)) - // output: Lorem ipsum dolor sit amet -} - -func ExampleNewEncrypter_publicKey() { - var publicKey *rsa.PublicKey - - // Instantiate an encrypter using RSA-OAEP with AES128-GCM. - NewEncrypter(A128GCM, Recipient{Algorithm: RSA_OAEP, Key: publicKey}, nil) - - // Instantiate an encrypter using RSA-PKCS1v1.5 with AES128-CBC+HMAC. - NewEncrypter(A128CBC_HS256, Recipient{Algorithm: RSA1_5, Key: publicKey}, nil) -} - -func ExampleNewEncrypter_symmetric() { - var sharedKey []byte - - // Instantiate an encrypter using AES128-GCM with AES-GCM key wrap. - NewEncrypter(A128GCM, Recipient{Algorithm: A128GCMKW, Key: sharedKey}, nil) - - // Instantiate an encrypter using AES128-GCM directly, w/o key wrapping. - NewEncrypter(A128GCM, Recipient{Algorithm: DIRECT, Key: sharedKey}, nil) -} - -func ExampleNewSigner_publicKey() { - var rsaPrivateKey *rsa.PrivateKey - var ecdsaPrivateKey *ecdsa.PrivateKey - - // Instantiate a signer using RSA-PKCS#1v1.5 with SHA-256. - NewSigner(SigningKey{Algorithm: RS256, Key: rsaPrivateKey}, nil) - - // Instantiate a signer using ECDSA with SHA-384. - NewSigner(SigningKey{Algorithm: ES384, Key: ecdsaPrivateKey}, nil) -} - -func ExampleNewSigner_symmetric() { - var sharedKey []byte - - // Instantiate an signer using HMAC-SHA256. - NewSigner(SigningKey{Algorithm: HS256, Key: sharedKey}, nil) - - // Instantiate an signer using HMAC-SHA512. - NewSigner(SigningKey{Algorithm: HS512, Key: sharedKey}, nil) -} - -func ExampleNewMultiEncrypter() { - var publicKey *rsa.PublicKey - var sharedKey []byte - - // Instantiate an encrypter using AES-GCM. - NewMultiEncrypter(A128GCM, []Recipient{ - {Algorithm: A128GCMKW, Key: sharedKey}, - {Algorithm: RSA_OAEP, Key: publicKey}, - }, nil) -} - -func ExampleNewMultiSigner() { - var privateKey *rsa.PrivateKey - var sharedKey []byte - - // Instantiate a signer for multiple recipients. - NewMultiSigner([]SigningKey{ - {Algorithm: HS256, Key: sharedKey}, - {Algorithm: PS384, Key: privateKey}, - }, nil) -} - -func ExampleEncrypter_encrypt() { - // Encrypt a plaintext in order to get an encrypted JWE object. - var plaintext = []byte("This is a secret message") - - encrypter.Encrypt(plaintext) -} - -func ExampleEncrypter_encryptWithAuthData() { - // Encrypt a plaintext in order to get an encrypted JWE object. Also attach - // some additional authenticated data (AAD) to the object. Note that objects - // with attached AAD can only be represented using full serialization. - var plaintext = []byte("This is a secret message") - var aad = []byte("This is authenticated, but public data") - - encrypter.EncryptWithAuthData(plaintext, aad) -} diff --git a/vendor/gopkg.in/square/go-jose.v2/encoding_test.go b/vendor/gopkg.in/square/go-jose.v2/encoding_test.go deleted file mode 100644 index c824e4c59c..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/encoding_test.go +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * Copyright 2014 Square 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 jose - -import ( - "bytes" - "strings" - "testing" -) - -func TestDeflateRoundtrip(t *testing.T) { - original := []byte("Lorem ipsum dolor sit amet") - - compressed, err := deflate(original) - if err != nil { - panic(err) - } - - output, err := inflate(compressed) - if err != nil { - panic(err) - } - - if bytes.Compare(output, original) != 0 { - t.Error("Input and output do not match") - } -} - -func TestInvalidCompression(t *testing.T) { - _, err := compress("XYZ", []byte{}) - if err == nil { - t.Error("should not accept invalid algorithm") - } - - _, err = decompress("XYZ", []byte{}) - if err == nil { - t.Error("should not accept invalid algorithm") - } - - _, err = decompress(DEFLATE, []byte{1, 2, 3, 4}) - if err == nil { - t.Error("should not accept invalid data") - } -} - -func TestByteBufferTrim(t *testing.T) { - buf := newBufferFromInt(1) - if !bytes.Equal(buf.data, []byte{1}) { - t.Error("Byte buffer for integer '1' should contain [0x01]") - } - - buf = newBufferFromInt(65537) - if !bytes.Equal(buf.data, []byte{1, 0, 1}) { - t.Error("Byte buffer for integer '65537' should contain [0x01, 0x00, 0x01]") - } -} - -func TestFixedSizeBuffer(t *testing.T) { - data0 := []byte{} - data1 := []byte{1} - data2 := []byte{1, 2} - data3 := []byte{1, 2, 3} - data4 := []byte{1, 2, 3, 4} - - buf0 := newFixedSizeBuffer(data0, 4) - buf1 := newFixedSizeBuffer(data1, 4) - buf2 := newFixedSizeBuffer(data2, 4) - buf3 := newFixedSizeBuffer(data3, 4) - buf4 := newFixedSizeBuffer(data4, 4) - - if !bytes.Equal(buf0.data, []byte{0, 0, 0, 0}) { - t.Error("Invalid padded buffer for buf0") - } - if !bytes.Equal(buf1.data, []byte{0, 0, 0, 1}) { - t.Error("Invalid padded buffer for buf1") - } - if !bytes.Equal(buf2.data, []byte{0, 0, 1, 2}) { - t.Error("Invalid padded buffer for buf2") - } - if !bytes.Equal(buf3.data, []byte{0, 1, 2, 3}) { - t.Error("Invalid padded buffer for buf3") - } - if !bytes.Equal(buf4.data, []byte{1, 2, 3, 4}) { - t.Error("Invalid padded buffer for buf4") - } -} - -func TestSerializeJSONRejectsNil(t *testing.T) { - defer func() { - r := recover() - if r == nil || !strings.Contains(r.(string), "nil pointer") { - t.Error("serialize function should not accept nil pointer") - } - }() - - mustSerializeJSON(nil) -} - -func TestFixedSizeBufferTooLarge(t *testing.T) { - defer func() { - r := recover() - if r == nil { - t.Error("should not be able to create fixed size buffer with oversized data") - } - }() - - newFixedSizeBuffer(make([]byte, 2), 1) -} diff --git a/vendor/gopkg.in/square/go-jose.v2/json/bench_test.go b/vendor/gopkg.in/square/go-jose.v2/json/bench_test.go deleted file mode 100644 index ed89d1156e..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/json/bench_test.go +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2011 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. - -// Large data benchmark. -// The JSON data is a summary of agl's changes in the -// go, webkit, and chromium open source projects. -// We benchmark converting between the JSON form -// and in-memory data structures. - -package json - -import ( - "bytes" - "compress/gzip" - "io/ioutil" - "os" - "strings" - "testing" -) - -type codeResponse struct { - Tree *codeNode `json:"tree"` - Username string `json:"username"` -} - -type codeNode struct { - Name string `json:"name"` - Kids []*codeNode `json:"kids"` - CLWeight float64 `json:"cl_weight"` - Touches int `json:"touches"` - MinT int64 `json:"min_t"` - MaxT int64 `json:"max_t"` - MeanT int64 `json:"mean_t"` -} - -var codeJSON []byte -var codeStruct codeResponse - -func codeInit() { - f, err := os.Open("testdata/code.json.gz") - if err != nil { - panic(err) - } - defer f.Close() - gz, err := gzip.NewReader(f) - if err != nil { - panic(err) - } - data, err := ioutil.ReadAll(gz) - if err != nil { - panic(err) - } - - codeJSON = data - - if err := Unmarshal(codeJSON, &codeStruct); err != nil { - panic("unmarshal code.json: " + err.Error()) - } - - if data, err = Marshal(&codeStruct); err != nil { - panic("marshal code.json: " + err.Error()) - } - - if !bytes.Equal(data, codeJSON) { - println("different lengths", len(data), len(codeJSON)) - for i := 0; i < len(data) && i < len(codeJSON); i++ { - if data[i] != codeJSON[i] { - println("re-marshal: changed at byte", i) - println("orig: ", string(codeJSON[i-10:i+10])) - println("new: ", string(data[i-10:i+10])) - break - } - } - panic("re-marshal code.json: different result") - } -} - -func BenchmarkCodeEncoder(b *testing.B) { - if codeJSON == nil { - b.StopTimer() - codeInit() - b.StartTimer() - } - enc := NewEncoder(ioutil.Discard) - for i := 0; i < b.N; i++ { - if err := enc.Encode(&codeStruct); err != nil { - b.Fatal("Encode:", err) - } - } - b.SetBytes(int64(len(codeJSON))) -} - -func BenchmarkCodeMarshal(b *testing.B) { - if codeJSON == nil { - b.StopTimer() - codeInit() - b.StartTimer() - } - for i := 0; i < b.N; i++ { - if _, err := Marshal(&codeStruct); err != nil { - b.Fatal("Marshal:", err) - } - } - b.SetBytes(int64(len(codeJSON))) -} - -func BenchmarkCodeDecoder(b *testing.B) { - if codeJSON == nil { - b.StopTimer() - codeInit() - b.StartTimer() - } - var buf bytes.Buffer - dec := NewDecoder(&buf) - var r codeResponse - for i := 0; i < b.N; i++ { - buf.Write(codeJSON) - // hide EOF - buf.WriteByte('\n') - buf.WriteByte('\n') - buf.WriteByte('\n') - if err := dec.Decode(&r); err != nil { - b.Fatal("Decode:", err) - } - } - b.SetBytes(int64(len(codeJSON))) -} - -func BenchmarkDecoderStream(b *testing.B) { - b.StopTimer() - var buf bytes.Buffer - dec := NewDecoder(&buf) - buf.WriteString(`"` + strings.Repeat("x", 1000000) + `"` + "\n\n\n") - var x interface{} - if err := dec.Decode(&x); err != nil { - b.Fatal("Decode:", err) - } - ones := strings.Repeat(" 1\n", 300000) + "\n\n\n" - b.StartTimer() - for i := 0; i < b.N; i++ { - if i%300000 == 0 { - buf.WriteString(ones) - } - x = nil - if err := dec.Decode(&x); err != nil || x != 1.0 { - b.Fatalf("Decode: %v after %d", err, i) - } - } -} - -func BenchmarkCodeUnmarshal(b *testing.B) { - if codeJSON == nil { - b.StopTimer() - codeInit() - b.StartTimer() - } - for i := 0; i < b.N; i++ { - var r codeResponse - if err := Unmarshal(codeJSON, &r); err != nil { - b.Fatal("Unmmarshal:", err) - } - } - b.SetBytes(int64(len(codeJSON))) -} - -func BenchmarkCodeUnmarshalReuse(b *testing.B) { - if codeJSON == nil { - b.StopTimer() - codeInit() - b.StartTimer() - } - var r codeResponse - for i := 0; i < b.N; i++ { - if err := Unmarshal(codeJSON, &r); err != nil { - b.Fatal("Unmmarshal:", err) - } - } -} - -func BenchmarkUnmarshalString(b *testing.B) { - data := []byte(`"hello, world"`) - var s string - - for i := 0; i < b.N; i++ { - if err := Unmarshal(data, &s); err != nil { - b.Fatal("Unmarshal:", err) - } - } -} - -func BenchmarkUnmarshalFloat64(b *testing.B) { - var f float64 - data := []byte(`3.14`) - - for i := 0; i < b.N; i++ { - if err := Unmarshal(data, &f); err != nil { - b.Fatal("Unmarshal:", err) - } - } -} - -func BenchmarkUnmarshalInt64(b *testing.B) { - var x int64 - data := []byte(`3`) - - for i := 0; i < b.N; i++ { - if err := Unmarshal(data, &x); err != nil { - b.Fatal("Unmarshal:", err) - } - } -} - -func BenchmarkIssue10335(b *testing.B) { - b.ReportAllocs() - var s struct{} - j := []byte(`{"a":{ }}`) - for n := 0; n < b.N; n++ { - if err := Unmarshal(j, &s); err != nil { - b.Fatal(err) - } - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/json/decode_test.go b/vendor/gopkg.in/square/go-jose.v2/json/decode_test.go deleted file mode 100644 index 32394654e3..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/json/decode_test.go +++ /dev/null @@ -1,1474 +0,0 @@ -// Copyright 2010 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 json - -import ( - "bytes" - "encoding" - "fmt" - "image" - "net" - "reflect" - "strings" - "testing" - "time" -) - -type T struct { - X string - Y int - Z int `json:"-"` -} - -type U struct { - Alphabet string `json:"alpha"` -} - -type V struct { - F1 interface{} - F2 int32 - F3 Number -} - -// ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and -// without UseNumber -var ifaceNumAsFloat64 = map[string]interface{}{ - "k1": float64(1), - "k2": "s", - "k3": []interface{}{float64(1), float64(2.0), float64(3e-3)}, - "k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)}, -} - -var ifaceNumAsNumber = map[string]interface{}{ - "k1": Number("1"), - "k2": "s", - "k3": []interface{}{Number("1"), Number("2.0"), Number("3e-3")}, - "k4": map[string]interface{}{"kk1": "s", "kk2": Number("2")}, -} - -type tx struct { - x int -} - -// A type that can unmarshal itself. - -type unmarshaler struct { - T bool -} - -func (u *unmarshaler) UnmarshalJSON(b []byte) error { - *u = unmarshaler{true} // All we need to see that UnmarshalJSON is called. - return nil -} - -type ustruct struct { - M unmarshaler -} - -type unmarshalerText struct { - T bool -} - -// needed for re-marshaling tests -func (u *unmarshalerText) MarshalText() ([]byte, error) { - return []byte(""), nil -} - -func (u *unmarshalerText) UnmarshalText(b []byte) error { - *u = unmarshalerText{true} // All we need to see that UnmarshalText is called. - return nil -} - -var _ encoding.TextUnmarshaler = (*unmarshalerText)(nil) - -type ustructText struct { - M unmarshalerText -} - -var ( - um0, um1 unmarshaler // target2 of unmarshaling - ump = &um1 - umtrue = unmarshaler{true} - umslice = []unmarshaler{{true}} - umslicep = new([]unmarshaler) - umstruct = ustruct{unmarshaler{true}} - - um0T, um1T unmarshalerText // target2 of unmarshaling - umpT = &um1T - umtrueT = unmarshalerText{true} - umsliceT = []unmarshalerText{{true}} - umslicepT = new([]unmarshalerText) - umstructT = ustructText{unmarshalerText{true}} -) - -// Test data structures for anonymous fields. - -type Point struct { - Z int -} - -type Top struct { - Level0 int - Embed0 - *Embed0a - *Embed0b `json:"e,omitempty"` // treated as named - Embed0c `json:"-"` // ignored - Loop - Embed0p // has Point with X, Y, used - Embed0q // has Point with Z, used - embed // contains exported field -} - -type Embed0 struct { - Level1a int // overridden by Embed0a's Level1a with json tag - Level1b int // used because Embed0a's Level1b is renamed - Level1c int // used because Embed0a's Level1c is ignored - Level1d int // annihilated by Embed0a's Level1d - Level1e int `json:"x"` // annihilated by Embed0a.Level1e -} - -type Embed0a struct { - Level1a int `json:"Level1a,omitempty"` - Level1b int `json:"LEVEL1B,omitempty"` - Level1c int `json:"-"` - Level1d int // annihilated by Embed0's Level1d - Level1f int `json:"x"` // annihilated by Embed0's Level1e -} - -type Embed0b Embed0 - -type Embed0c Embed0 - -type Embed0p struct { - image.Point -} - -type Embed0q struct { - Point -} - -type embed struct { - Q int -} - -type Loop struct { - Loop1 int `json:",omitempty"` - Loop2 int `json:",omitempty"` - *Loop -} - -// From reflect test: -// The X in S6 and S7 annihilate, but they also block the X in S8.S9. -type S5 struct { - S6 - S7 - S8 -} - -type S6 struct { - X int -} - -type S7 S6 - -type S8 struct { - S9 -} - -type S9 struct { - X int - Y int -} - -// From reflect test: -// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9. -type S10 struct { - S11 - S12 - S13 -} - -type S11 struct { - S6 -} - -type S12 struct { - S6 -} - -type S13 struct { - S8 -} - -type unmarshalTest struct { - in string - ptr interface{} - out interface{} - err error - useNumber bool -} - -type XYZ struct { - X interface{} - Y interface{} - Z interface{} -} - -func sliceAddr(x []int) *[]int { return &x } -func mapAddr(x map[string]int) *map[string]int { return &x } - -var unmarshalTests = []unmarshalTest{ - // basic types - {in: `true`, ptr: new(bool), out: true}, - {in: `1`, ptr: new(int), out: 1}, - {in: `1.2`, ptr: new(float64), out: 1.2}, - {in: `-5`, ptr: new(int16), out: int16(-5)}, - {in: `2`, ptr: new(Number), out: Number("2"), useNumber: true}, - {in: `2`, ptr: new(Number), out: Number("2")}, - {in: `2`, ptr: new(interface{}), out: float64(2.0)}, - {in: `2`, ptr: new(interface{}), out: Number("2"), useNumber: true}, - {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"}, - {in: `"http:\/\/"`, ptr: new(string), out: "http://"}, - {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"}, - {in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"}, - {in: "null", ptr: new(interface{}), out: nil}, - {in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeOf(""), 7}}, - {in: `{"x": 1}`, ptr: new(tx), out: tx{}}, - {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}}, - {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true}, - {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64}, - {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsNumber, useNumber: true}, - - // raw values with whitespace - {in: "\n true ", ptr: new(bool), out: true}, - {in: "\t 1 ", ptr: new(int), out: 1}, - {in: "\r 1.2 ", ptr: new(float64), out: 1.2}, - {in: "\t -5 \n", ptr: new(int16), out: int16(-5)}, - {in: "\t \"a\\u1234\" \n", ptr: new(string), out: "a\u1234"}, - - // Z has a "-" tag. - {in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}}, - - {in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}}, - {in: `{"alpha": "abc"}`, ptr: new(U), out: U{Alphabet: "abc"}}, - {in: `{"alphabet": "xyz"}`, ptr: new(U), out: U{}}, - - // syntax errors - {in: `{"X": "foo", "Y"}`, err: &SyntaxError{"invalid character '}' after object key", 17}}, - {in: `[1, 2, 3+]`, err: &SyntaxError{"invalid character '+' after array element", 9}}, - {in: `{"X":12x}`, err: &SyntaxError{"invalid character 'x' after object key:value pair", 8}, useNumber: true}, - - // raw value errors - {in: "\x01 42", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " 42 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 5}}, - {in: "\x01 true", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " false \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 8}}, - {in: "\x01 1.2", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " 3.4 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 6}}, - {in: "\x01 \"string\"", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " \"string\" \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 11}}, - - // array tests - {in: `[1, 2, 3]`, ptr: new([3]int), out: [3]int{1, 2, 3}}, - {in: `[1, 2, 3]`, ptr: new([1]int), out: [1]int{1}}, - {in: `[1, 2, 3]`, ptr: new([5]int), out: [5]int{1, 2, 3, 0, 0}}, - - // empty array to interface test - {in: `[]`, ptr: new([]interface{}), out: []interface{}{}}, - {in: `null`, ptr: new([]interface{}), out: []interface{}(nil)}, - {in: `{"T":[]}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": []interface{}{}}}, - {in: `{"T":null}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": interface{}(nil)}}, - - // composite tests - {in: allValueIndent, ptr: new(All), out: allValue}, - {in: allValueCompact, ptr: new(All), out: allValue}, - {in: allValueIndent, ptr: new(*All), out: &allValue}, - {in: allValueCompact, ptr: new(*All), out: &allValue}, - {in: pallValueIndent, ptr: new(All), out: pallValue}, - {in: pallValueCompact, ptr: new(All), out: pallValue}, - {in: pallValueIndent, ptr: new(*All), out: &pallValue}, - {in: pallValueCompact, ptr: new(*All), out: &pallValue}, - - // unmarshal interface test - {in: `{"T":false}`, ptr: &um0, out: umtrue}, // use "false" so test will fail if custom unmarshaler is not called - {in: `{"T":false}`, ptr: &ump, out: &umtrue}, - {in: `[{"T":false}]`, ptr: &umslice, out: umslice}, - {in: `[{"T":false}]`, ptr: &umslicep, out: &umslice}, - {in: `{"M":{"T":false}}`, ptr: &umstruct, out: umstruct}, - - // UnmarshalText interface test - {in: `"X"`, ptr: &um0T, out: umtrueT}, // use "false" so test will fail if custom unmarshaler is not called - {in: `"X"`, ptr: &umpT, out: &umtrueT}, - {in: `["X"]`, ptr: &umsliceT, out: umsliceT}, - {in: `["X"]`, ptr: &umslicepT, out: &umsliceT}, - {in: `{"M":"X"}`, ptr: &umstructT, out: umstructT}, - - // Overwriting of data. - // This is different from package xml, but it's what we've always done. - // Now documented and tested. - {in: `[2]`, ptr: sliceAddr([]int{1}), out: []int{2}}, - {in: `{"key": 2}`, ptr: mapAddr(map[string]int{"old": 0, "key": 1}), out: map[string]int{"key": 2}}, - - { - in: `{ - "Level0": 1, - "Level1b": 2, - "Level1c": 3, - "x": 4, - "Level1a": 5, - "LEVEL1B": 6, - "e": { - "Level1a": 8, - "Level1b": 9, - "Level1c": 10, - "Level1d": 11, - "x": 12 - }, - "Loop1": 13, - "Loop2": 14, - "X": 15, - "Y": 16, - "Z": 17, - "Q": 18 - }`, - ptr: new(Top), - out: Top{ - Level0: 1, - Embed0: Embed0{ - Level1b: 2, - Level1c: 3, - }, - Embed0a: &Embed0a{ - Level1a: 5, - Level1b: 6, - }, - Embed0b: &Embed0b{ - Level1a: 8, - Level1b: 9, - Level1c: 10, - Level1d: 11, - Level1e: 12, - }, - Loop: Loop{ - Loop1: 13, - Loop2: 14, - }, - Embed0p: Embed0p{ - Point: image.Point{X: 15, Y: 16}, - }, - Embed0q: Embed0q{ - Point: Point{Z: 17}, - }, - embed: embed{ - Q: 18, - }, - }, - }, - { - in: `{"X": 1,"Y":2}`, - ptr: new(S5), - out: S5{S8: S8{S9: S9{Y: 2}}}, - }, - { - in: `{"X": 1,"Y":2}`, - ptr: new(S10), - out: S10{S13: S13{S8: S8{S9: S9{Y: 2}}}}, - }, - - // invalid UTF-8 is coerced to valid UTF-8. - { - in: "\"hello\xffworld\"", - ptr: new(string), - out: "hello\ufffdworld", - }, - { - in: "\"hello\xc2\xc2world\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\xc2\xffworld\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\\ud800world\"", - ptr: new(string), - out: "hello\ufffdworld", - }, - { - in: "\"hello\\ud800\\ud800world\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\\ud800\\ud800world\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\xed\xa0\x80\xed\xb0\x80world\"", - ptr: new(string), - out: "hello\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdworld", - }, - - // issue 8305 - { - in: `{"2009-11-10T23:00:00Z": "hello world"}`, - ptr: &map[time.Time]string{}, - err: &UnmarshalTypeError{"object", reflect.TypeOf(map[time.Time]string{}), 1}, - }, -} - -func TestMarshal(t *testing.T) { - b, err := Marshal(allValue) - if err != nil { - t.Fatalf("Marshal allValue: %v", err) - } - if string(b) != allValueCompact { - t.Errorf("Marshal allValueCompact") - diff(t, b, []byte(allValueCompact)) - return - } - - b, err = Marshal(pallValue) - if err != nil { - t.Fatalf("Marshal pallValue: %v", err) - } - if string(b) != pallValueCompact { - t.Errorf("Marshal pallValueCompact") - diff(t, b, []byte(pallValueCompact)) - return - } -} - -var badUTF8 = []struct { - in, out string -}{ - {"hello\xffworld", `"hello\ufffdworld"`}, - {"", `""`}, - {"\xff", `"\ufffd"`}, - {"\xff\xff", `"\ufffd\ufffd"`}, - {"a\xffb", `"a\ufffdb"`}, - {"\xe6\x97\xa5\xe6\x9c\xac\xff\xaa\x9e", `"日本\ufffd\ufffd\ufffd"`}, -} - -func TestMarshalBadUTF8(t *testing.T) { - for _, tt := range badUTF8 { - b, err := Marshal(tt.in) - if string(b) != tt.out || err != nil { - t.Errorf("Marshal(%q) = %#q, %v, want %#q, nil", tt.in, b, err, tt.out) - } - } -} - -func TestMarshalNumberZeroVal(t *testing.T) { - var n Number - out, err := Marshal(n) - if err != nil { - t.Fatal(err) - } - outStr := string(out) - if outStr != "0" { - t.Fatalf("Invalid zero val for Number: %q", outStr) - } -} - -func TestMarshalEmbeds(t *testing.T) { - top := &Top{ - Level0: 1, - Embed0: Embed0{ - Level1b: 2, - Level1c: 3, - }, - Embed0a: &Embed0a{ - Level1a: 5, - Level1b: 6, - }, - Embed0b: &Embed0b{ - Level1a: 8, - Level1b: 9, - Level1c: 10, - Level1d: 11, - Level1e: 12, - }, - Loop: Loop{ - Loop1: 13, - Loop2: 14, - }, - Embed0p: Embed0p{ - Point: image.Point{X: 15, Y: 16}, - }, - Embed0q: Embed0q{ - Point: Point{Z: 17}, - }, - embed: embed{ - Q: 18, - }, - } - b, err := Marshal(top) - if err != nil { - t.Fatal(err) - } - want := "{\"Level0\":1,\"Level1b\":2,\"Level1c\":3,\"Level1a\":5,\"LEVEL1B\":6,\"e\":{\"Level1a\":8,\"Level1b\":9,\"Level1c\":10,\"Level1d\":11,\"x\":12},\"Loop1\":13,\"Loop2\":14,\"X\":15,\"Y\":16,\"Z\":17,\"Q\":18}" - if string(b) != want { - t.Errorf("Wrong marshal result.\n got: %q\nwant: %q", b, want) - } -} - -func TestUnmarshal(t *testing.T) { - for i, tt := range unmarshalTests { - var scan scanner - in := []byte(tt.in) - if err := checkValid(in, &scan); err != nil { - if !reflect.DeepEqual(err, tt.err) { - t.Errorf("#%d: checkValid: %#v", i, err) - continue - } - } - if tt.ptr == nil { - continue - } - - // v = new(right-type) - v := reflect.New(reflect.TypeOf(tt.ptr).Elem()) - dec := NewDecoder(bytes.NewReader(in)) - if tt.useNumber { - dec.UseNumber() - } - if err := dec.Decode(v.Interface()); !reflect.DeepEqual(err, tt.err) { - t.Errorf("#%d: %v, want %v", i, err, tt.err) - continue - } else if err != nil { - continue - } - if !reflect.DeepEqual(v.Elem().Interface(), tt.out) { - t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out) - data, _ := Marshal(v.Elem().Interface()) - println(string(data)) - data, _ = Marshal(tt.out) - println(string(data)) - continue - } - - // Check round trip. - if tt.err == nil { - enc, err := Marshal(v.Interface()) - if err != nil { - t.Errorf("#%d: error re-marshaling: %v", i, err) - continue - } - vv := reflect.New(reflect.TypeOf(tt.ptr).Elem()) - dec = NewDecoder(bytes.NewReader(enc)) - if tt.useNumber { - dec.UseNumber() - } - if err := dec.Decode(vv.Interface()); err != nil { - t.Errorf("#%d: error re-unmarshaling %#q: %v", i, enc, err) - continue - } - if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) { - t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface()) - t.Errorf(" In: %q", strings.Map(noSpace, string(in))) - t.Errorf("Marshal: %q", strings.Map(noSpace, string(enc))) - continue - } - } - } -} - -func TestUnmarshalMarshal(t *testing.T) { - initBig() - var v interface{} - if err := Unmarshal(jsonBig, &v); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - b, err := Marshal(v) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(jsonBig, b) { - t.Errorf("Marshal jsonBig") - diff(t, b, jsonBig) - return - } -} - -var numberTests = []struct { - in string - i int64 - intErr string - f float64 - floatErr string -}{ - {in: "-1.23e1", intErr: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f: -1.23e1}, - {in: "-12", i: -12, f: -12.0}, - {in: "1e1000", intErr: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr: "strconv.ParseFloat: parsing \"1e1000\": value out of range"}, -} - -// Independent of Decode, basic coverage of the accessors in Number -func TestNumberAccessors(t *testing.T) { - for _, tt := range numberTests { - n := Number(tt.in) - if s := n.String(); s != tt.in { - t.Errorf("Number(%q).String() is %q", tt.in, s) - } - if i, err := n.Int64(); err == nil && tt.intErr == "" && i != tt.i { - t.Errorf("Number(%q).Int64() is %d", tt.in, i) - } else if (err == nil && tt.intErr != "") || (err != nil && err.Error() != tt.intErr) { - t.Errorf("Number(%q).Int64() wanted error %q but got: %v", tt.in, tt.intErr, err) - } - if f, err := n.Float64(); err == nil && tt.floatErr == "" && f != tt.f { - t.Errorf("Number(%q).Float64() is %g", tt.in, f) - } else if (err == nil && tt.floatErr != "") || (err != nil && err.Error() != tt.floatErr) { - t.Errorf("Number(%q).Float64() wanted error %q but got: %v", tt.in, tt.floatErr, err) - } - } -} - -func TestLargeByteSlice(t *testing.T) { - s0 := make([]byte, 2000) - for i := range s0 { - s0[i] = byte(i) - } - b, err := Marshal(s0) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - var s1 []byte - if err := Unmarshal(b, &s1); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !bytes.Equal(s0, s1) { - t.Errorf("Marshal large byte slice") - diff(t, s0, s1) - } -} - -type Xint struct { - X int -} - -func TestUnmarshalInterface(t *testing.T) { - var xint Xint - var i interface{} = &xint - if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if xint.X != 1 { - t.Fatalf("Did not write to xint") - } -} - -func TestUnmarshalPtrPtr(t *testing.T) { - var xint Xint - pxint := &xint - if err := Unmarshal([]byte(`{"X":1}`), &pxint); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if xint.X != 1 { - t.Fatalf("Did not write to xint") - } -} - -func TestEscape(t *testing.T) { - const input = `"foobar"<html>` + " [\u2028 \u2029]" - const expected = `"\"foobar\"\u003chtml\u003e [\u2028 \u2029]"` - b, err := Marshal(input) - if err != nil { - t.Fatalf("Marshal error: %v", err) - } - if s := string(b); s != expected { - t.Errorf("Encoding of [%s]:\n got [%s]\nwant [%s]", input, s, expected) - } -} - -// WrongString is a struct that's misusing the ,string modifier. -type WrongString struct { - Message string `json:"result,string"` -} - -type wrongStringTest struct { - in, err string -} - -var wrongStringTests = []wrongStringTest{ - {`{"result":"x"}`, `json: invalid use of ,string struct tag, trying to unmarshal "x" into string`}, - {`{"result":"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "foo" into string`}, - {`{"result":"123"}`, `json: invalid use of ,string struct tag, trying to unmarshal "123" into string`}, - {`{"result":123}`, `json: invalid use of ,string struct tag, trying to unmarshal unquoted value into string`}, -} - -// If people misuse the ,string modifier, the error message should be -// helpful, telling the user that they're doing it wrong. -func TestErrorMessageFromMisusedString(t *testing.T) { - for n, tt := range wrongStringTests { - r := strings.NewReader(tt.in) - var s WrongString - err := NewDecoder(r).Decode(&s) - got := fmt.Sprintf("%v", err) - if got != tt.err { - t.Errorf("%d. got err = %q, want %q", n, got, tt.err) - } - } -} - -func noSpace(c rune) rune { - if isSpace(byte(c)) { //only used for ascii - return -1 - } - return c -} - -type All struct { - Bool bool - Int int - Int8 int8 - Int16 int16 - Int32 int32 - Int64 int64 - Uint uint - Uint8 uint8 - Uint16 uint16 - Uint32 uint32 - Uint64 uint64 - Uintptr uintptr - Float32 float32 - Float64 float64 - - Foo string `json:"bar"` - Foo2 string `json:"bar2,dummyopt"` - - IntStr int64 `json:",string"` - - PBool *bool - PInt *int - PInt8 *int8 - PInt16 *int16 - PInt32 *int32 - PInt64 *int64 - PUint *uint - PUint8 *uint8 - PUint16 *uint16 - PUint32 *uint32 - PUint64 *uint64 - PUintptr *uintptr - PFloat32 *float32 - PFloat64 *float64 - - String string - PString *string - - Map map[string]Small - MapP map[string]*Small - PMap *map[string]Small - PMapP *map[string]*Small - - EmptyMap map[string]Small - NilMap map[string]Small - - Slice []Small - SliceP []*Small - PSlice *[]Small - PSliceP *[]*Small - - EmptySlice []Small - NilSlice []Small - - StringSlice []string - ByteSlice []byte - - Small Small - PSmall *Small - PPSmall **Small - - Interface interface{} - PInterface *interface{} - - unexported int -} - -type Small struct { - Tag string -} - -var allValue = All{ - Bool: true, - Int: 2, - Int8: 3, - Int16: 4, - Int32: 5, - Int64: 6, - Uint: 7, - Uint8: 8, - Uint16: 9, - Uint32: 10, - Uint64: 11, - Uintptr: 12, - Float32: 14.1, - Float64: 15.1, - Foo: "foo", - Foo2: "foo2", - IntStr: 42, - String: "16", - Map: map[string]Small{ - "17": {Tag: "tag17"}, - "18": {Tag: "tag18"}, - }, - MapP: map[string]*Small{ - "19": {Tag: "tag19"}, - "20": nil, - }, - EmptyMap: map[string]Small{}, - Slice: []Small{{Tag: "tag20"}, {Tag: "tag21"}}, - SliceP: []*Small{{Tag: "tag22"}, nil, {Tag: "tag23"}}, - EmptySlice: []Small{}, - StringSlice: []string{"str24", "str25", "str26"}, - ByteSlice: []byte{27, 28, 29}, - Small: Small{Tag: "tag30"}, - PSmall: &Small{Tag: "tag31"}, - Interface: 5.2, -} - -var pallValue = All{ - PBool: &allValue.Bool, - PInt: &allValue.Int, - PInt8: &allValue.Int8, - PInt16: &allValue.Int16, - PInt32: &allValue.Int32, - PInt64: &allValue.Int64, - PUint: &allValue.Uint, - PUint8: &allValue.Uint8, - PUint16: &allValue.Uint16, - PUint32: &allValue.Uint32, - PUint64: &allValue.Uint64, - PUintptr: &allValue.Uintptr, - PFloat32: &allValue.Float32, - PFloat64: &allValue.Float64, - PString: &allValue.String, - PMap: &allValue.Map, - PMapP: &allValue.MapP, - PSlice: &allValue.Slice, - PSliceP: &allValue.SliceP, - PPSmall: &allValue.PSmall, - PInterface: &allValue.Interface, -} - -var allValueIndent = `{ - "Bool": true, - "Int": 2, - "Int8": 3, - "Int16": 4, - "Int32": 5, - "Int64": 6, - "Uint": 7, - "Uint8": 8, - "Uint16": 9, - "Uint32": 10, - "Uint64": 11, - "Uintptr": 12, - "Float32": 14.1, - "Float64": 15.1, - "bar": "foo", - "bar2": "foo2", - "IntStr": "42", - "PBool": null, - "PInt": null, - "PInt8": null, - "PInt16": null, - "PInt32": null, - "PInt64": null, - "PUint": null, - "PUint8": null, - "PUint16": null, - "PUint32": null, - "PUint64": null, - "PUintptr": null, - "PFloat32": null, - "PFloat64": null, - "String": "16", - "PString": null, - "Map": { - "17": { - "Tag": "tag17" - }, - "18": { - "Tag": "tag18" - } - }, - "MapP": { - "19": { - "Tag": "tag19" - }, - "20": null - }, - "PMap": null, - "PMapP": null, - "EmptyMap": {}, - "NilMap": null, - "Slice": [ - { - "Tag": "tag20" - }, - { - "Tag": "tag21" - } - ], - "SliceP": [ - { - "Tag": "tag22" - }, - null, - { - "Tag": "tag23" - } - ], - "PSlice": null, - "PSliceP": null, - "EmptySlice": [], - "NilSlice": null, - "StringSlice": [ - "str24", - "str25", - "str26" - ], - "ByteSlice": "Gxwd", - "Small": { - "Tag": "tag30" - }, - "PSmall": { - "Tag": "tag31" - }, - "PPSmall": null, - "Interface": 5.2, - "PInterface": null -}` - -var allValueCompact = strings.Map(noSpace, allValueIndent) - -var pallValueIndent = `{ - "Bool": false, - "Int": 0, - "Int8": 0, - "Int16": 0, - "Int32": 0, - "Int64": 0, - "Uint": 0, - "Uint8": 0, - "Uint16": 0, - "Uint32": 0, - "Uint64": 0, - "Uintptr": 0, - "Float32": 0, - "Float64": 0, - "bar": "", - "bar2": "", - "IntStr": "0", - "PBool": true, - "PInt": 2, - "PInt8": 3, - "PInt16": 4, - "PInt32": 5, - "PInt64": 6, - "PUint": 7, - "PUint8": 8, - "PUint16": 9, - "PUint32": 10, - "PUint64": 11, - "PUintptr": 12, - "PFloat32": 14.1, - "PFloat64": 15.1, - "String": "", - "PString": "16", - "Map": null, - "MapP": null, - "PMap": { - "17": { - "Tag": "tag17" - }, - "18": { - "Tag": "tag18" - } - }, - "PMapP": { - "19": { - "Tag": "tag19" - }, - "20": null - }, - "EmptyMap": null, - "NilMap": null, - "Slice": null, - "SliceP": null, - "PSlice": [ - { - "Tag": "tag20" - }, - { - "Tag": "tag21" - } - ], - "PSliceP": [ - { - "Tag": "tag22" - }, - null, - { - "Tag": "tag23" - } - ], - "EmptySlice": null, - "NilSlice": null, - "StringSlice": null, - "ByteSlice": null, - "Small": { - "Tag": "" - }, - "PSmall": null, - "PPSmall": { - "Tag": "tag31" - }, - "Interface": null, - "PInterface": 5.2 -}` - -var pallValueCompact = strings.Map(noSpace, pallValueIndent) - -func TestRefUnmarshal(t *testing.T) { - type S struct { - // Ref is defined in encode_test.go. - R0 Ref - R1 *Ref - R2 RefText - R3 *RefText - } - want := S{ - R0: 12, - R1: new(Ref), - R2: 13, - R3: new(RefText), - } - *want.R1 = 12 - *want.R3 = 13 - - var got S - if err := Unmarshal([]byte(`{"R0":"ref","R1":"ref","R2":"ref","R3":"ref"}`), &got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !reflect.DeepEqual(got, want) { - t.Errorf("got %+v, want %+v", got, want) - } -} - -// Test that the empty string doesn't panic decoding when ,string is specified -// Issue 3450 -func TestEmptyString(t *testing.T) { - type T2 struct { - Number1 int `json:",string"` - Number2 int `json:",string"` - } - data := `{"Number1":"1", "Number2":""}` - dec := NewDecoder(strings.NewReader(data)) - var t2 T2 - err := dec.Decode(&t2) - if err == nil { - t.Fatal("Decode: did not return error") - } - if t2.Number1 != 1 { - t.Fatal("Decode: did not set Number1") - } -} - -// Test that a null for ,string is not replaced with the previous quoted string (issue 7046). -// It should also not be an error (issue 2540, issue 8587). -func TestNullString(t *testing.T) { - type T struct { - A int `json:",string"` - B int `json:",string"` - C *int `json:",string"` - } - data := []byte(`{"A": "1", "B": null, "C": null}`) - var s T - s.B = 1 - s.C = new(int) - *s.C = 2 - err := Unmarshal(data, &s) - if err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if s.B != 1 || s.C != nil { - t.Fatalf("after Unmarshal, s.B=%d, s.C=%p, want 1, nil", s.B, s.C) - } -} - -func intp(x int) *int { - p := new(int) - *p = x - return p -} - -func intpp(x *int) **int { - pp := new(*int) - *pp = x - return pp -} - -var interfaceSetTests = []struct { - pre interface{} - json string - post interface{} -}{ - {"foo", `"bar"`, "bar"}, - {"foo", `2`, 2.0}, - {"foo", `true`, true}, - {"foo", `null`, nil}, - - {nil, `null`, nil}, - {new(int), `null`, nil}, - {(*int)(nil), `null`, nil}, - {new(*int), `null`, new(*int)}, - {(**int)(nil), `null`, nil}, - {intp(1), `null`, nil}, - {intpp(nil), `null`, intpp(nil)}, - {intpp(intp(1)), `null`, intpp(nil)}, -} - -func TestInterfaceSet(t *testing.T) { - for _, tt := range interfaceSetTests { - b := struct{ X interface{} }{tt.pre} - blob := `{"X":` + tt.json + `}` - if err := Unmarshal([]byte(blob), &b); err != nil { - t.Errorf("Unmarshal %#q: %v", blob, err) - continue - } - if !reflect.DeepEqual(b.X, tt.post) { - t.Errorf("Unmarshal %#q into %#v: X=%#v, want %#v", blob, tt.pre, b.X, tt.post) - } - } -} - -// JSON null values should be ignored for primitives and string values instead of resulting in an error. -// Issue 2540 -func TestUnmarshalNulls(t *testing.T) { - jsonData := []byte(`{ - "Bool" : null, - "Int" : null, - "Int8" : null, - "Int16" : null, - "Int32" : null, - "Int64" : null, - "Uint" : null, - "Uint8" : null, - "Uint16" : null, - "Uint32" : null, - "Uint64" : null, - "Float32" : null, - "Float64" : null, - "String" : null}`) - - nulls := All{ - Bool: true, - Int: 2, - Int8: 3, - Int16: 4, - Int32: 5, - Int64: 6, - Uint: 7, - Uint8: 8, - Uint16: 9, - Uint32: 10, - Uint64: 11, - Float32: 12.1, - Float64: 13.1, - String: "14"} - - err := Unmarshal(jsonData, &nulls) - if err != nil { - t.Errorf("Unmarshal of null values failed: %v", err) - } - if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 || - nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 || - nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" { - - t.Errorf("Unmarshal of null values affected primitives") - } -} - -func TestStringKind(t *testing.T) { - type stringKind string - - var m1, m2 map[stringKind]int - m1 = map[stringKind]int{ - "foo": 42, - } - - data, err := Marshal(m1) - if err != nil { - t.Errorf("Unexpected error marshaling: %v", err) - } - - err = Unmarshal(data, &m2) - if err != nil { - t.Errorf("Unexpected error unmarshaling: %v", err) - } - - if !reflect.DeepEqual(m1, m2) { - t.Error("Items should be equal after encoding and then decoding") - } -} - -// Custom types with []byte as underlying type could not be marshalled -// and then unmarshalled. -// Issue 8962. -func TestByteKind(t *testing.T) { - type byteKind []byte - - a := byteKind("hello") - - data, err := Marshal(a) - if err != nil { - t.Error(err) - } - var b byteKind - err = Unmarshal(data, &b) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(a, b) { - t.Errorf("expected %v == %v", a, b) - } -} - -// The fix for issue 8962 introduced a regression. -// Issue 12921. -func TestSliceOfCustomByte(t *testing.T) { - type Uint8 uint8 - - a := []Uint8("hello") - - data, err := Marshal(a) - if err != nil { - t.Fatal(err) - } - var b []Uint8 - err = Unmarshal(data, &b) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(a, b) { - t.Fatalf("expected %v == %v", a, b) - } -} - -var decodeTypeErrorTests = []struct { - dest interface{} - src string -}{ - {new(string), `{"user": "name"}`}, // issue 4628. - {new(error), `{}`}, // issue 4222 - {new(error), `[]`}, - {new(error), `""`}, - {new(error), `123`}, - {new(error), `true`}, -} - -func TestUnmarshalTypeError(t *testing.T) { - for _, item := range decodeTypeErrorTests { - err := Unmarshal([]byte(item.src), item.dest) - if _, ok := err.(*UnmarshalTypeError); !ok { - t.Errorf("expected type error for Unmarshal(%q, type %T): got %T", - item.src, item.dest, err) - } - } -} - -var unmarshalSyntaxTests = []string{ - "tru", - "fals", - "nul", - "123e", - `"hello`, - `[1,2,3`, - `{"key":1`, - `{"key":1,`, -} - -func TestUnmarshalSyntax(t *testing.T) { - var x interface{} - for _, src := range unmarshalSyntaxTests { - err := Unmarshal([]byte(src), &x) - if _, ok := err.(*SyntaxError); !ok { - t.Errorf("expected syntax error for Unmarshal(%q): got %T", src, err) - } - } -} - -// Test handling of unexported fields that should be ignored. -// Issue 4660 -type unexportedFields struct { - Name string - m map[string]interface{} `json:"-"` - m2 map[string]interface{} `json:"abcd"` -} - -func TestUnmarshalUnexported(t *testing.T) { - input := `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}}` - want := &unexportedFields{Name: "Bob"} - - out := &unexportedFields{} - err := Unmarshal([]byte(input), out) - if err != nil { - t.Errorf("got error %v, expected nil", err) - } - if !reflect.DeepEqual(out, want) { - t.Errorf("got %q, want %q", out, want) - } -} - -// Time3339 is a time.Time which encodes to and from JSON -// as an RFC 3339 time in UTC. -type Time3339 time.Time - -func (t *Time3339) UnmarshalJSON(b []byte) error { - if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' { - return fmt.Errorf("types: failed to unmarshal non-string value %q as an RFC 3339 time", b) - } - tm, err := time.Parse(time.RFC3339, string(b[1:len(b)-1])) - if err != nil { - return err - } - *t = Time3339(tm) - return nil -} - -func TestUnmarshalJSONLiteralError(t *testing.T) { - var t3 Time3339 - err := Unmarshal([]byte(`"0000-00-00T00:00:00Z"`), &t3) - if err == nil { - t.Fatalf("expected error; got time %v", time.Time(t3)) - } - if !strings.Contains(err.Error(), "range") { - t.Errorf("got err = %v; want out of range error", err) - } -} - -// Test that extra object elements in an array do not result in a -// "data changing underfoot" error. -// Issue 3717 -func TestSkipArrayObjects(t *testing.T) { - json := `[{}]` - var dest [0]interface{} - - err := Unmarshal([]byte(json), &dest) - if err != nil { - t.Errorf("got error %q, want nil", err) - } -} - -// Test semantics of pre-filled struct fields and pre-filled map fields. -// Issue 4900. -func TestPrefilled(t *testing.T) { - ptrToMap := func(m map[string]interface{}) *map[string]interface{} { return &m } - - // Values here change, cannot reuse table across runs. - var prefillTests = []struct { - in string - ptr interface{} - out interface{} - }{ - { - in: `{"X": 1, "Y": 2}`, - ptr: &XYZ{X: float32(3), Y: int16(4), Z: 1.5}, - out: &XYZ{X: float64(1), Y: float64(2), Z: 1.5}, - }, - { - in: `{"X": 1, "Y": 2}`, - ptr: ptrToMap(map[string]interface{}{"X": float32(3), "Y": int16(4), "Z": 1.5}), - out: ptrToMap(map[string]interface{}{"X": float64(1), "Y": float64(2), "Z": 1.5}), - }, - } - - for _, tt := range prefillTests { - ptrstr := fmt.Sprintf("%v", tt.ptr) - err := Unmarshal([]byte(tt.in), tt.ptr) // tt.ptr edited here - if err != nil { - t.Errorf("Unmarshal: %v", err) - } - if !reflect.DeepEqual(tt.ptr, tt.out) { - t.Errorf("Unmarshal(%#q, %s): have %v, want %v", tt.in, ptrstr, tt.ptr, tt.out) - } - } -} - -var invalidUnmarshalTests = []struct { - v interface{} - want string -}{ - {nil, "json: Unmarshal(nil)"}, - {struct{}{}, "json: Unmarshal(non-pointer struct {})"}, - {(*int)(nil), "json: Unmarshal(nil *int)"}, -} - -func TestInvalidUnmarshal(t *testing.T) { - buf := []byte(`{"a":"1"}`) - for _, tt := range invalidUnmarshalTests { - err := Unmarshal(buf, tt.v) - if err == nil { - t.Errorf("Unmarshal expecting error, got nil") - continue - } - if got := err.Error(); got != tt.want { - t.Errorf("Unmarshal = %q; want %q", got, tt.want) - } - } -} - -var invalidUnmarshalTextTests = []struct { - v interface{} - want string -}{ - {nil, "json: Unmarshal(nil)"}, - {struct{}{}, "json: Unmarshal(non-pointer struct {})"}, - {(*int)(nil), "json: Unmarshal(nil *int)"}, - {new(net.IP), "json: cannot unmarshal string into Go value of type *net.IP"}, -} - -func TestInvalidUnmarshalText(t *testing.T) { - buf := []byte(`123`) - for _, tt := range invalidUnmarshalTextTests { - err := Unmarshal(buf, tt.v) - if err == nil { - t.Errorf("Unmarshal expecting error, got nil") - continue - } - if got := err.Error(); got != tt.want { - t.Errorf("Unmarshal = %q; want %q", got, tt.want) - } - } -} - -// Test that string option is ignored for invalid types. -// Issue 9812. -func TestInvalidStringOption(t *testing.T) { - num := 0 - item := struct { - T time.Time `json:",string"` - M map[string]string `json:",string"` - S []string `json:",string"` - A [1]string `json:",string"` - I interface{} `json:",string"` - P *int `json:",string"` - }{M: make(map[string]string), S: make([]string, 0), I: num, P: &num} - - data, err := Marshal(item) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - - err = Unmarshal(data, &item) - if err != nil { - t.Fatalf("Unmarshal: %v", err) - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/json/encode_test.go b/vendor/gopkg.in/square/go-jose.v2/json/encode_test.go deleted file mode 100644 index c00491e00c..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/json/encode_test.go +++ /dev/null @@ -1,538 +0,0 @@ -// Copyright 2011 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 json - -import ( - "bytes" - "math" - "reflect" - "testing" - "unicode" -) - -type Optionals struct { - Sr string `json:"sr"` - So string `json:"so,omitempty"` - Sw string `json:"-"` - - Ir int `json:"omitempty"` // actually named omitempty, not an option - Io int `json:"io,omitempty"` - - Slr []string `json:"slr,random"` - Slo []string `json:"slo,omitempty"` - - Mr map[string]interface{} `json:"mr"` - Mo map[string]interface{} `json:",omitempty"` - - Fr float64 `json:"fr"` - Fo float64 `json:"fo,omitempty"` - - Br bool `json:"br"` - Bo bool `json:"bo,omitempty"` - - Ur uint `json:"ur"` - Uo uint `json:"uo,omitempty"` - - Str struct{} `json:"str"` - Sto struct{} `json:"sto,omitempty"` -} - -var optionalsExpected = `{ - "sr": "", - "omitempty": 0, - "slr": null, - "mr": {}, - "fr": 0, - "br": false, - "ur": 0, - "str": {}, - "sto": {} -}` - -func TestOmitEmpty(t *testing.T) { - var o Optionals - o.Sw = "something" - o.Mr = map[string]interface{}{} - o.Mo = map[string]interface{}{} - - got, err := MarshalIndent(&o, "", " ") - if err != nil { - t.Fatal(err) - } - if got := string(got); got != optionalsExpected { - t.Errorf(" got: %s\nwant: %s\n", got, optionalsExpected) - } -} - -type StringTag struct { - BoolStr bool `json:",string"` - IntStr int64 `json:",string"` - StrStr string `json:",string"` -} - -var stringTagExpected = `{ - "BoolStr": "true", - "IntStr": "42", - "StrStr": "\"xzbit\"" -}` - -func TestStringTag(t *testing.T) { - var s StringTag - s.BoolStr = true - s.IntStr = 42 - s.StrStr = "xzbit" - got, err := MarshalIndent(&s, "", " ") - if err != nil { - t.Fatal(err) - } - if got := string(got); got != stringTagExpected { - t.Fatalf(" got: %s\nwant: %s\n", got, stringTagExpected) - } - - // Verify that it round-trips. - var s2 StringTag - err = NewDecoder(bytes.NewReader(got)).Decode(&s2) - if err != nil { - t.Fatalf("Decode: %v", err) - } - if !reflect.DeepEqual(s, s2) { - t.Fatalf("decode didn't match.\nsource: %#v\nEncoded as:\n%s\ndecode: %#v", s, string(got), s2) - } -} - -// byte slices are special even if they're renamed types. -type renamedByte byte -type renamedByteSlice []byte -type renamedRenamedByteSlice []renamedByte - -func TestEncodeRenamedByteSlice(t *testing.T) { - s := renamedByteSlice("abc") - result, err := Marshal(s) - if err != nil { - t.Fatal(err) - } - expect := `"YWJj"` - if string(result) != expect { - t.Errorf(" got %s want %s", result, expect) - } - r := renamedRenamedByteSlice("abc") - result, err = Marshal(r) - if err != nil { - t.Fatal(err) - } - if string(result) != expect { - t.Errorf(" got %s want %s", result, expect) - } -} - -var unsupportedValues = []interface{}{ - math.NaN(), - math.Inf(-1), - math.Inf(1), -} - -func TestUnsupportedValues(t *testing.T) { - for _, v := range unsupportedValues { - if _, err := Marshal(v); err != nil { - if _, ok := err.(*UnsupportedValueError); !ok { - t.Errorf("for %v, got %T want UnsupportedValueError", v, err) - } - } else { - t.Errorf("for %v, expected error", v) - } - } -} - -// Ref has Marshaler and Unmarshaler methods with pointer receiver. -type Ref int - -func (*Ref) MarshalJSON() ([]byte, error) { - return []byte(`"ref"`), nil -} - -func (r *Ref) UnmarshalJSON([]byte) error { - *r = 12 - return nil -} - -// Val has Marshaler methods with value receiver. -type Val int - -func (Val) MarshalJSON() ([]byte, error) { - return []byte(`"val"`), nil -} - -// RefText has Marshaler and Unmarshaler methods with pointer receiver. -type RefText int - -func (*RefText) MarshalText() ([]byte, error) { - return []byte(`"ref"`), nil -} - -func (r *RefText) UnmarshalText([]byte) error { - *r = 13 - return nil -} - -// ValText has Marshaler methods with value receiver. -type ValText int - -func (ValText) MarshalText() ([]byte, error) { - return []byte(`"val"`), nil -} - -func TestRefValMarshal(t *testing.T) { - var s = struct { - R0 Ref - R1 *Ref - R2 RefText - R3 *RefText - V0 Val - V1 *Val - V2 ValText - V3 *ValText - }{ - R0: 12, - R1: new(Ref), - R2: 14, - R3: new(RefText), - V0: 13, - V1: new(Val), - V2: 15, - V3: new(ValText), - } - const want = `{"R0":"ref","R1":"ref","R2":"\"ref\"","R3":"\"ref\"","V0":"val","V1":"val","V2":"\"val\"","V3":"\"val\""}` - b, err := Marshal(&s) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if got := string(b); got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -// C implements Marshaler and returns unescaped JSON. -type C int - -func (C) MarshalJSON() ([]byte, error) { - return []byte(`"<&>"`), nil -} - -// CText implements Marshaler and returns unescaped text. -type CText int - -func (CText) MarshalText() ([]byte, error) { - return []byte(`"<&>"`), nil -} - -func TestMarshalerEscaping(t *testing.T) { - var c C - want := `"\u003c\u0026\u003e"` - b, err := Marshal(c) - if err != nil { - t.Fatalf("Marshal(c): %v", err) - } - if got := string(b); got != want { - t.Errorf("Marshal(c) = %#q, want %#q", got, want) - } - - var ct CText - want = `"\"\u003c\u0026\u003e\""` - b, err = Marshal(ct) - if err != nil { - t.Fatalf("Marshal(ct): %v", err) - } - if got := string(b); got != want { - t.Errorf("Marshal(ct) = %#q, want %#q", got, want) - } -} - -type IntType int - -type MyStruct struct { - IntType -} - -func TestAnonymousNonstruct(t *testing.T) { - var i IntType = 11 - a := MyStruct{i} - const want = `{"IntType":11}` - - b, err := Marshal(a) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if got := string(b); got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -type BugA struct { - S string -} - -type BugB struct { - BugA - S string -} - -type BugC struct { - S string -} - -// Legal Go: We never use the repeated embedded field (S). -type BugX struct { - A int - BugA - BugB -} - -// Issue 5245. -func TestEmbeddedBug(t *testing.T) { - v := BugB{ - BugA{"A"}, - "B", - } - b, err := Marshal(v) - if err != nil { - t.Fatal("Marshal:", err) - } - want := `{"S":"B"}` - got := string(b) - if got != want { - t.Fatalf("Marshal: got %s want %s", got, want) - } - // Now check that the duplicate field, S, does not appear. - x := BugX{ - A: 23, - } - b, err = Marshal(x) - if err != nil { - t.Fatal("Marshal:", err) - } - want = `{"A":23}` - got = string(b) - if got != want { - t.Fatalf("Marshal: got %s want %s", got, want) - } -} - -type BugD struct { // Same as BugA after tagging. - XXX string `json:"S"` -} - -// BugD's tagged S field should dominate BugA's. -type BugY struct { - BugA - BugD -} - -// Test that a field with a tag dominates untagged fields. -func TestTaggedFieldDominates(t *testing.T) { - v := BugY{ - BugA{"BugA"}, - BugD{"BugD"}, - } - b, err := Marshal(v) - if err != nil { - t.Fatal("Marshal:", err) - } - want := `{"S":"BugD"}` - got := string(b) - if got != want { - t.Fatalf("Marshal: got %s want %s", got, want) - } -} - -// There are no tags here, so S should not appear. -type BugZ struct { - BugA - BugC - BugY // Contains a tagged S field through BugD; should not dominate. -} - -func TestDuplicatedFieldDisappears(t *testing.T) { - v := BugZ{ - BugA{"BugA"}, - BugC{"BugC"}, - BugY{ - BugA{"nested BugA"}, - BugD{"nested BugD"}, - }, - } - b, err := Marshal(v) - if err != nil { - t.Fatal("Marshal:", err) - } - want := `{}` - got := string(b) - if got != want { - t.Fatalf("Marshal: got %s want %s", got, want) - } -} - -func TestStringBytes(t *testing.T) { - // Test that encodeState.stringBytes and encodeState.string use the same encoding. - es := &encodeState{} - var r []rune - for i := '\u0000'; i <= unicode.MaxRune; i++ { - r = append(r, i) - } - s := string(r) + "\xff\xff\xffhello" // some invalid UTF-8 too - es.string(s) - - esBytes := &encodeState{} - esBytes.stringBytes([]byte(s)) - - enc := es.Buffer.String() - encBytes := esBytes.Buffer.String() - if enc != encBytes { - i := 0 - for i < len(enc) && i < len(encBytes) && enc[i] == encBytes[i] { - i++ - } - enc = enc[i:] - encBytes = encBytes[i:] - i = 0 - for i < len(enc) && i < len(encBytes) && enc[len(enc)-i-1] == encBytes[len(encBytes)-i-1] { - i++ - } - enc = enc[:len(enc)-i] - encBytes = encBytes[:len(encBytes)-i] - - if len(enc) > 20 { - enc = enc[:20] + "..." - } - if len(encBytes) > 20 { - encBytes = encBytes[:20] + "..." - } - - t.Errorf("encodings differ at %#q vs %#q", enc, encBytes) - } -} - -func TestIssue6458(t *testing.T) { - type Foo struct { - M RawMessage - } - x := Foo{RawMessage(`"foo"`)} - - b, err := Marshal(&x) - if err != nil { - t.Fatal(err) - } - if want := `{"M":"foo"}`; string(b) != want { - t.Errorf("Marshal(&x) = %#q; want %#q", b, want) - } - - b, err = Marshal(x) - if err != nil { - t.Fatal(err) - } - - if want := `{"M":"ImZvbyI="}`; string(b) != want { - t.Errorf("Marshal(x) = %#q; want %#q", b, want) - } -} - -func TestIssue10281(t *testing.T) { - type Foo struct { - N Number - } - x := Foo{Number(`invalid`)} - - b, err := Marshal(&x) - if err == nil { - t.Errorf("Marshal(&x) = %#q; want error", b) - } -} - -func TestHTMLEscape(t *testing.T) { - var b, want bytes.Buffer - m := `{"M":"<html>foo &` + "\xe2\x80\xa8 \xe2\x80\xa9" + `</html>"}` - want.Write([]byte(`{"M":"\u003chtml\u003efoo \u0026\u2028 \u2029\u003c/html\u003e"}`)) - HTMLEscape(&b, []byte(m)) - if !bytes.Equal(b.Bytes(), want.Bytes()) { - t.Errorf("HTMLEscape(&b, []byte(m)) = %s; want %s", b.Bytes(), want.Bytes()) - } -} - -// golang.org/issue/8582 -func TestEncodePointerString(t *testing.T) { - type stringPointer struct { - N *int64 `json:"n,string"` - } - var n int64 = 42 - b, err := Marshal(stringPointer{N: &n}) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if got, want := string(b), `{"n":"42"}`; got != want { - t.Errorf("Marshal = %s, want %s", got, want) - } - var back stringPointer - err = Unmarshal(b, &back) - if err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if back.N == nil { - t.Fatalf("Unmarshalled nil N field") - } - if *back.N != 42 { - t.Fatalf("*N = %d; want 42", *back.N) - } -} - -var encodeStringTests = []struct { - in string - out string -}{ - {"\x00", `"\u0000"`}, - {"\x01", `"\u0001"`}, - {"\x02", `"\u0002"`}, - {"\x03", `"\u0003"`}, - {"\x04", `"\u0004"`}, - {"\x05", `"\u0005"`}, - {"\x06", `"\u0006"`}, - {"\x07", `"\u0007"`}, - {"\x08", `"\u0008"`}, - {"\x09", `"\t"`}, - {"\x0a", `"\n"`}, - {"\x0b", `"\u000b"`}, - {"\x0c", `"\u000c"`}, - {"\x0d", `"\r"`}, - {"\x0e", `"\u000e"`}, - {"\x0f", `"\u000f"`}, - {"\x10", `"\u0010"`}, - {"\x11", `"\u0011"`}, - {"\x12", `"\u0012"`}, - {"\x13", `"\u0013"`}, - {"\x14", `"\u0014"`}, - {"\x15", `"\u0015"`}, - {"\x16", `"\u0016"`}, - {"\x17", `"\u0017"`}, - {"\x18", `"\u0018"`}, - {"\x19", `"\u0019"`}, - {"\x1a", `"\u001a"`}, - {"\x1b", `"\u001b"`}, - {"\x1c", `"\u001c"`}, - {"\x1d", `"\u001d"`}, - {"\x1e", `"\u001e"`}, - {"\x1f", `"\u001f"`}, -} - -func TestEncodeString(t *testing.T) { - for _, tt := range encodeStringTests { - b, err := Marshal(tt.in) - if err != nil { - t.Errorf("Marshal(%q): %v", tt.in, err) - continue - } - out := string(b) - if out != tt.out { - t.Errorf("Marshal(%q) = %#q, want %#q", tt.in, out, tt.out) - } - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/json/number_test.go b/vendor/gopkg.in/square/go-jose.v2/json/number_test.go deleted file mode 100644 index 4e63cf9c74..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/json/number_test.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2011 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 json - -import ( - "regexp" - "testing" -) - -func TestNumberIsValid(t *testing.T) { - // From: http://stackoverflow.com/a/13340826 - var jsonNumberRegexp = regexp.MustCompile(`^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$`) - - validTests := []string{ - "0", - "-0", - "1", - "-1", - "0.1", - "-0.1", - "1234", - "-1234", - "12.34", - "-12.34", - "12E0", - "12E1", - "12e34", - "12E-0", - "12e+1", - "12e-34", - "-12E0", - "-12E1", - "-12e34", - "-12E-0", - "-12e+1", - "-12e-34", - "1.2E0", - "1.2E1", - "1.2e34", - "1.2E-0", - "1.2e+1", - "1.2e-34", - "-1.2E0", - "-1.2E1", - "-1.2e34", - "-1.2E-0", - "-1.2e+1", - "-1.2e-34", - "0E0", - "0E1", - "0e34", - "0E-0", - "0e+1", - "0e-34", - "-0E0", - "-0E1", - "-0e34", - "-0E-0", - "-0e+1", - "-0e-34", - } - - for _, test := range validTests { - if !isValidNumber(test) { - t.Errorf("%s should be valid", test) - } - - var f float64 - if err := Unmarshal([]byte(test), &f); err != nil { - t.Errorf("%s should be valid but Unmarshal failed: %v", test, err) - } - - if !jsonNumberRegexp.MatchString(test) { - t.Errorf("%s should be valid but regexp does not match", test) - } - } - - invalidTests := []string{ - "", - "invalid", - "1.0.1", - "1..1", - "-1-2", - "012a42", - "01.2", - "012", - "12E12.12", - "1e2e3", - "1e+-2", - "1e--23", - "1e", - "e1", - "1e+", - "1ea", - "1a", - "1.a", - "1.", - "01", - "1.e1", - } - - for _, test := range invalidTests { - if isValidNumber(test) { - t.Errorf("%s should be invalid", test) - } - - var f float64 - if err := Unmarshal([]byte(test), &f); err == nil { - t.Errorf("%s should be invalid but unmarshal wrote %v", test, f) - } - - if jsonNumberRegexp.MatchString(test) { - t.Errorf("%s should be invalid but matches regexp", test) - } - } -} - -func BenchmarkNumberIsValid(b *testing.B) { - s := "-61657.61667E+61673" - for i := 0; i < b.N; i++ { - isValidNumber(s) - } -} - -func BenchmarkNumberIsValidRegexp(b *testing.B) { - var jsonNumberRegexp = regexp.MustCompile(`^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$`) - s := "-61657.61667E+61673" - for i := 0; i < b.N; i++ { - jsonNumberRegexp.MatchString(s) - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/json/scanner_test.go b/vendor/gopkg.in/square/go-jose.v2/json/scanner_test.go deleted file mode 100644 index 66383ef0ef..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/json/scanner_test.go +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright 2010 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 json - -import ( - "bytes" - "math" - "math/rand" - "reflect" - "testing" -) - -// Tests of simple examples. - -type example struct { - compact string - indent string -} - -var examples = []example{ - {`1`, `1`}, - {`{}`, `{}`}, - {`[]`, `[]`}, - {`{"":2}`, "{\n\t\"\": 2\n}"}, - {`[3]`, "[\n\t3\n]"}, - {`[1,2,3]`, "[\n\t1,\n\t2,\n\t3\n]"}, - {`{"x":1}`, "{\n\t\"x\": 1\n}"}, - {ex1, ex1i}, -} - -var ex1 = `[true,false,null,"x",1,1.5,0,-5e+2]` - -var ex1i = `[ - true, - false, - null, - "x", - 1, - 1.5, - 0, - -5e+2 -]` - -func TestCompact(t *testing.T) { - var buf bytes.Buffer - for _, tt := range examples { - buf.Reset() - if err := Compact(&buf, []byte(tt.compact)); err != nil { - t.Errorf("Compact(%#q): %v", tt.compact, err) - } else if s := buf.String(); s != tt.compact { - t.Errorf("Compact(%#q) = %#q, want original", tt.compact, s) - } - - buf.Reset() - if err := Compact(&buf, []byte(tt.indent)); err != nil { - t.Errorf("Compact(%#q): %v", tt.indent, err) - continue - } else if s := buf.String(); s != tt.compact { - t.Errorf("Compact(%#q) = %#q, want %#q", tt.indent, s, tt.compact) - } - } -} - -func TestCompactSeparators(t *testing.T) { - // U+2028 and U+2029 should be escaped inside strings. - // They should not appear outside strings. - tests := []struct { - in, compact string - }{ - {"{\"\u2028\": 1}", `{"\u2028":1}`}, - {"{\"\u2029\" :2}", `{"\u2029":2}`}, - } - for _, tt := range tests { - var buf bytes.Buffer - if err := Compact(&buf, []byte(tt.in)); err != nil { - t.Errorf("Compact(%q): %v", tt.in, err) - } else if s := buf.String(); s != tt.compact { - t.Errorf("Compact(%q) = %q, want %q", tt.in, s, tt.compact) - } - } -} - -func TestIndent(t *testing.T) { - var buf bytes.Buffer - for _, tt := range examples { - buf.Reset() - if err := Indent(&buf, []byte(tt.indent), "", "\t"); err != nil { - t.Errorf("Indent(%#q): %v", tt.indent, err) - } else if s := buf.String(); s != tt.indent { - t.Errorf("Indent(%#q) = %#q, want original", tt.indent, s) - } - - buf.Reset() - if err := Indent(&buf, []byte(tt.compact), "", "\t"); err != nil { - t.Errorf("Indent(%#q): %v", tt.compact, err) - continue - } else if s := buf.String(); s != tt.indent { - t.Errorf("Indent(%#q) = %#q, want %#q", tt.compact, s, tt.indent) - } - } -} - -// Tests of a large random structure. - -func TestCompactBig(t *testing.T) { - initBig() - var buf bytes.Buffer - if err := Compact(&buf, jsonBig); err != nil { - t.Fatalf("Compact: %v", err) - } - b := buf.Bytes() - if !bytes.Equal(b, jsonBig) { - t.Error("Compact(jsonBig) != jsonBig") - diff(t, b, jsonBig) - return - } -} - -func TestIndentBig(t *testing.T) { - initBig() - var buf bytes.Buffer - if err := Indent(&buf, jsonBig, "", "\t"); err != nil { - t.Fatalf("Indent1: %v", err) - } - b := buf.Bytes() - if len(b) == len(jsonBig) { - // jsonBig is compact (no unnecessary spaces); - // indenting should make it bigger - t.Fatalf("Indent(jsonBig) did not get bigger") - } - - // should be idempotent - var buf1 bytes.Buffer - if err := Indent(&buf1, b, "", "\t"); err != nil { - t.Fatalf("Indent2: %v", err) - } - b1 := buf1.Bytes() - if !bytes.Equal(b1, b) { - t.Error("Indent(Indent(jsonBig)) != Indent(jsonBig)") - diff(t, b1, b) - return - } - - // should get back to original - buf1.Reset() - if err := Compact(&buf1, b); err != nil { - t.Fatalf("Compact: %v", err) - } - b1 = buf1.Bytes() - if !bytes.Equal(b1, jsonBig) { - t.Error("Compact(Indent(jsonBig)) != jsonBig") - diff(t, b1, jsonBig) - return - } -} - -type indentErrorTest struct { - in string - err error -} - -var indentErrorTests = []indentErrorTest{ - {`{"X": "foo", "Y"}`, &SyntaxError{"invalid character '}' after object key", 17}}, - {`{"X": "foo" "Y": "bar"}`, &SyntaxError{"invalid character '\"' after object key:value pair", 13}}, -} - -func TestIndentErrors(t *testing.T) { - for i, tt := range indentErrorTests { - slice := make([]uint8, 0) - buf := bytes.NewBuffer(slice) - if err := Indent(buf, []uint8(tt.in), "", ""); err != nil { - if !reflect.DeepEqual(err, tt.err) { - t.Errorf("#%d: Indent: %#v", i, err) - continue - } - } - } -} - -func TestNextValueBig(t *testing.T) { - initBig() - var scan scanner - item, rest, err := nextValue(jsonBig, &scan) - if err != nil { - t.Fatalf("nextValue: %s", err) - } - if len(item) != len(jsonBig) || &item[0] != &jsonBig[0] { - t.Errorf("invalid item: %d %d", len(item), len(jsonBig)) - } - if len(rest) != 0 { - t.Errorf("invalid rest: %d", len(rest)) - } - - item, rest, err = nextValue(append(jsonBig, "HELLO WORLD"...), &scan) - if err != nil { - t.Fatalf("nextValue extra: %s", err) - } - if len(item) != len(jsonBig) { - t.Errorf("invalid item: %d %d", len(item), len(jsonBig)) - } - if string(rest) != "HELLO WORLD" { - t.Errorf("invalid rest: %d", len(rest)) - } -} - -var benchScan scanner - -func BenchmarkSkipValue(b *testing.B) { - initBig() - b.ResetTimer() - for i := 0; i < b.N; i++ { - nextValue(jsonBig, &benchScan) - } - b.SetBytes(int64(len(jsonBig))) -} - -func diff(t *testing.T, a, b []byte) { - for i := 0; ; i++ { - if i >= len(a) || i >= len(b) || a[i] != b[i] { - j := i - 10 - if j < 0 { - j = 0 - } - t.Errorf("diverge at %d: «%s» vs «%s»", i, trim(a[j:]), trim(b[j:])) - return - } - } -} - -func trim(b []byte) []byte { - if len(b) > 20 { - return b[0:20] - } - return b -} - -// Generate a random JSON object. - -var jsonBig []byte - -func initBig() { - n := 10000 - if testing.Short() { - n = 100 - } - b, err := Marshal(genValue(n)) - if err != nil { - panic(err) - } - jsonBig = b -} - -func genValue(n int) interface{} { - if n > 1 { - switch rand.Intn(2) { - case 0: - return genArray(n) - case 1: - return genMap(n) - } - } - switch rand.Intn(3) { - case 0: - return rand.Intn(2) == 0 - case 1: - return rand.NormFloat64() - case 2: - return genString(30) - } - panic("unreachable") -} - -func genString(stddev float64) string { - n := int(math.Abs(rand.NormFloat64()*stddev + stddev/2)) - c := make([]rune, n) - for i := range c { - f := math.Abs(rand.NormFloat64()*64 + 32) - if f > 0x10ffff { - f = 0x10ffff - } - c[i] = rune(f) - } - return string(c) -} - -func genArray(n int) []interface{} { - f := int(math.Abs(rand.NormFloat64()) * math.Min(10, float64(n/2))) - if f > n { - f = n - } - if f < 1 { - f = 1 - } - x := make([]interface{}, f) - for i := range x { - x[i] = genValue(((i+1)*n)/f - (i*n)/f) - } - return x -} - -func genMap(n int) map[string]interface{} { - f := int(math.Abs(rand.NormFloat64()) * math.Min(10, float64(n/2))) - if f > n { - f = n - } - if n > 0 && f == 0 { - f = 1 - } - x := make(map[string]interface{}) - for i := 0; i < f; i++ { - x[genString(10)] = genValue(((i+1)*n)/f - (i*n)/f) - } - return x -} diff --git a/vendor/gopkg.in/square/go-jose.v2/json/stream_test.go b/vendor/gopkg.in/square/go-jose.v2/json/stream_test.go deleted file mode 100644 index eccf365b2d..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/json/stream_test.go +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright 2010 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 json - -import ( - "bytes" - "io" - "io/ioutil" - "log" - "net" - "net/http" - "net/http/httptest" - "reflect" - "strings" - "testing" -) - -// Test values for the stream test. -// One of each JSON kind. -var streamTest = []interface{}{ - 0.1, - "hello", - nil, - true, - false, - []interface{}{"a", "b", "c"}, - map[string]interface{}{"K": "Kelvin", "ß": "long s"}, - 3.14, // another value to make sure something can follow map -} - -var streamEncoded = `0.1 -"hello" -null -true -false -["a","b","c"] -{"ß":"long s","K":"Kelvin"} -3.14 -` - -func TestEncoder(t *testing.T) { - for i := 0; i <= len(streamTest); i++ { - var buf bytes.Buffer - enc := NewEncoder(&buf) - for j, v := range streamTest[0:i] { - if err := enc.Encode(v); err != nil { - t.Fatalf("encode #%d: %v", j, err) - } - } - if have, want := buf.String(), nlines(streamEncoded, i); have != want { - t.Errorf("encoding %d items: mismatch", i) - diff(t, []byte(have), []byte(want)) - break - } - } -} - -func TestDecoder(t *testing.T) { - for i := 0; i <= len(streamTest); i++ { - // Use stream without newlines as input, - // just to stress the decoder even more. - // Our test input does not include back-to-back numbers. - // Otherwise stripping the newlines would - // merge two adjacent JSON values. - var buf bytes.Buffer - for _, c := range nlines(streamEncoded, i) { - if c != '\n' { - buf.WriteRune(c) - } - } - out := make([]interface{}, i) - dec := NewDecoder(&buf) - for j := range out { - if err := dec.Decode(&out[j]); err != nil { - t.Fatalf("decode #%d/%d: %v", j, i, err) - } - } - if !reflect.DeepEqual(out, streamTest[0:i]) { - t.Errorf("decoding %d items: mismatch", i) - for j := range out { - if !reflect.DeepEqual(out[j], streamTest[j]) { - t.Errorf("#%d: have %v want %v", j, out[j], streamTest[j]) - } - } - break - } - } -} - -func TestDecoderBuffered(t *testing.T) { - r := strings.NewReader(`{"Name": "Gopher"} extra `) - var m struct { - Name string - } - d := NewDecoder(r) - err := d.Decode(&m) - if err != nil { - t.Fatal(err) - } - if m.Name != "Gopher" { - t.Errorf("Name = %q; want Gopher", m.Name) - } - rest, err := ioutil.ReadAll(d.Buffered()) - if err != nil { - t.Fatal(err) - } - if g, w := string(rest), " extra "; g != w { - t.Errorf("Remaining = %q; want %q", g, w) - } -} - -func nlines(s string, n int) string { - if n <= 0 { - return "" - } - for i, c := range s { - if c == '\n' { - if n--; n == 0 { - return s[0 : i+1] - } - } - } - return s -} - -func TestRawMessage(t *testing.T) { - // TODO(rsc): Should not need the * in *RawMessage - var data struct { - X float64 - Id *RawMessage - Y float32 - } - const raw = `["\u0056",null]` - const msg = `{"X":0.1,"Id":["\u0056",null],"Y":0.2}` - err := Unmarshal([]byte(msg), &data) - if err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if string([]byte(*data.Id)) != raw { - t.Fatalf("Raw mismatch: have %#q want %#q", []byte(*data.Id), raw) - } - b, err := Marshal(&data) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if string(b) != msg { - t.Fatalf("Marshal: have %#q want %#q", b, msg) - } -} - -func TestNullRawMessage(t *testing.T) { - // TODO(rsc): Should not need the * in *RawMessage - var data struct { - X float64 - Id *RawMessage - Y float32 - } - data.Id = new(RawMessage) - const msg = `{"X":0.1,"Id":null,"Y":0.2}` - err := Unmarshal([]byte(msg), &data) - if err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if data.Id != nil { - t.Fatalf("Raw mismatch: have non-nil, want nil") - } - b, err := Marshal(&data) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if string(b) != msg { - t.Fatalf("Marshal: have %#q want %#q", b, msg) - } -} - -var blockingTests = []string{ - `{"x": 1}`, - `[1, 2, 3]`, -} - -func TestBlocking(t *testing.T) { - for _, enc := range blockingTests { - r, w := net.Pipe() - go w.Write([]byte(enc)) - var val interface{} - - // If Decode reads beyond what w.Write writes above, - // it will block, and the test will deadlock. - if err := NewDecoder(r).Decode(&val); err != nil { - t.Errorf("decoding %s: %v", enc, err) - } - r.Close() - w.Close() - } -} - -func BenchmarkEncoderEncode(b *testing.B) { - b.ReportAllocs() - type T struct { - X, Y string - } - v := &T{"foo", "bar"} - for i := 0; i < b.N; i++ { - if err := NewEncoder(ioutil.Discard).Encode(v); err != nil { - b.Fatal(err) - } - } -} - -type tokenStreamCase struct { - json string - expTokens []interface{} -} - -type decodeThis struct { - v interface{} -} - -var tokenStreamCases []tokenStreamCase = []tokenStreamCase{ - // streaming token cases - {json: `10`, expTokens: []interface{}{float64(10)}}, - {json: ` [10] `, expTokens: []interface{}{ - Delim('['), float64(10), Delim(']')}}, - {json: ` [false,10,"b"] `, expTokens: []interface{}{ - Delim('['), false, float64(10), "b", Delim(']')}}, - {json: `{ "a": 1 }`, expTokens: []interface{}{ - Delim('{'), "a", float64(1), Delim('}')}}, - {json: `{"a": 1, "b":"3"}`, expTokens: []interface{}{ - Delim('{'), "a", float64(1), "b", "3", Delim('}')}}, - {json: ` [{"a": 1},{"a": 2}] `, expTokens: []interface{}{ - Delim('['), - Delim('{'), "a", float64(1), Delim('}'), - Delim('{'), "a", float64(2), Delim('}'), - Delim(']')}}, - {json: `{"obj": {"a": 1}}`, expTokens: []interface{}{ - Delim('{'), "obj", Delim('{'), "a", float64(1), Delim('}'), - Delim('}')}}, - {json: `{"obj": [{"a": 1}]}`, expTokens: []interface{}{ - Delim('{'), "obj", Delim('['), - Delim('{'), "a", float64(1), Delim('}'), - Delim(']'), Delim('}')}}, - - // streaming tokens with intermittent Decode() - {json: `{ "a": 1 }`, expTokens: []interface{}{ - Delim('{'), "a", - decodeThis{float64(1)}, - Delim('}')}}, - {json: ` [ { "a" : 1 } ] `, expTokens: []interface{}{ - Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, - Delim(']')}}, - {json: ` [{"a": 1},{"a": 2}] `, expTokens: []interface{}{ - Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, - decodeThis{map[string]interface{}{"a": float64(2)}}, - Delim(']')}}, - {json: `{ "obj" : [ { "a" : 1 } ] }`, expTokens: []interface{}{ - Delim('{'), "obj", Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, - Delim(']'), Delim('}')}}, - - {json: `{"obj": {"a": 1}}`, expTokens: []interface{}{ - Delim('{'), "obj", - decodeThis{map[string]interface{}{"a": float64(1)}}, - Delim('}')}}, - {json: `{"obj": [{"a": 1}]}`, expTokens: []interface{}{ - Delim('{'), "obj", - decodeThis{[]interface{}{ - map[string]interface{}{"a": float64(1)}, - }}, - Delim('}')}}, - {json: ` [{"a": 1} {"a": 2}] `, expTokens: []interface{}{ - Delim('['), - decodeThis{map[string]interface{}{"a": float64(1)}}, - decodeThis{&SyntaxError{"expected comma after array element", 0}}, - }}, - {json: `{ "a" 1 }`, expTokens: []interface{}{ - Delim('{'), "a", - decodeThis{&SyntaxError{"expected colon after object key", 0}}, - }}, -} - -func TestDecodeInStream(t *testing.T) { - - for ci, tcase := range tokenStreamCases { - - dec := NewDecoder(strings.NewReader(tcase.json)) - for i, etk := range tcase.expTokens { - - var tk interface{} - var err error - - if dt, ok := etk.(decodeThis); ok { - etk = dt.v - err = dec.Decode(&tk) - } else { - tk, err = dec.Token() - } - if experr, ok := etk.(error); ok { - if err == nil || err.Error() != experr.Error() { - t.Errorf("case %v: Expected error %v in %q, but was %v", ci, experr, tcase.json, err) - } - break - } else if err == io.EOF { - t.Errorf("case %v: Unexpected EOF in %q", ci, tcase.json) - break - } else if err != nil { - t.Errorf("case %v: Unexpected error '%v' in %q", ci, err, tcase.json) - break - } - if !reflect.DeepEqual(tk, etk) { - t.Errorf(`case %v: %q @ %v expected %T(%v) was %T(%v)`, ci, tcase.json, i, etk, etk, tk, tk) - break - } - } - } - -} - -// Test from golang.org/issue/11893 -func TestHTTPDecoding(t *testing.T) { - const raw = `{ "foo": "bar" }` - - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(raw)) - })) - defer ts.Close() - res, err := http.Get(ts.URL) - if err != nil { - log.Fatalf("GET failed: %v", err) - } - defer res.Body.Close() - - foo := struct { - Foo string `json:"foo"` - }{} - - d := NewDecoder(res.Body) - err = d.Decode(&foo) - if err != nil { - t.Fatalf("Decode: %v", err) - } - if foo.Foo != "bar" { - t.Errorf("decoded %q; want \"bar\"", foo.Foo) - } - - // make sure we get the EOF the second time - err = d.Decode(&foo) - if err != io.EOF { - t.Errorf("err = %v; want io.EOF", err) - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/json/tagkey_test.go b/vendor/gopkg.in/square/go-jose.v2/json/tagkey_test.go deleted file mode 100644 index 85bb4ba837..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/json/tagkey_test.go +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2011 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 json - -import ( - "testing" -) - -type basicLatin2xTag struct { - V string `json:"$%-/"` -} - -type basicLatin3xTag struct { - V string `json:"0123456789"` -} - -type basicLatin4xTag struct { - V string `json:"ABCDEFGHIJKLMO"` -} - -type basicLatin5xTag struct { - V string `json:"PQRSTUVWXYZ_"` -} - -type basicLatin6xTag struct { - V string `json:"abcdefghijklmno"` -} - -type basicLatin7xTag struct { - V string `json:"pqrstuvwxyz"` -} - -type miscPlaneTag struct { - V string `json:"色は匂へど"` -} - -type percentSlashTag struct { - V string `json:"text/html%"` // https://golang.org/issue/2718 -} - -type punctuationTag struct { - V string `json:"!#$%&()*+-./:<=>?@[]^_{|}~"` // https://golang.org/issue/3546 -} - -type emptyTag struct { - W string -} - -type misnamedTag struct { - X string `jsom:"Misnamed"` -} - -type badFormatTag struct { - Y string `:"BadFormat"` -} - -type badCodeTag struct { - Z string `json:" !\"#&'()*+,."` -} - -type spaceTag struct { - Q string `json:"With space"` -} - -type unicodeTag struct { - W string `json:"Ελλάδα"` -} - -var structTagObjectKeyTests = []struct { - raw interface{} - value string - key string -}{ - {basicLatin2xTag{"2x"}, "2x", "$%-/"}, - {basicLatin3xTag{"3x"}, "3x", "0123456789"}, - {basicLatin4xTag{"4x"}, "4x", "ABCDEFGHIJKLMO"}, - {basicLatin5xTag{"5x"}, "5x", "PQRSTUVWXYZ_"}, - {basicLatin6xTag{"6x"}, "6x", "abcdefghijklmno"}, - {basicLatin7xTag{"7x"}, "7x", "pqrstuvwxyz"}, - {miscPlaneTag{"いろはにほへと"}, "いろはにほへと", "色は匂へど"}, - {emptyTag{"Pour Moi"}, "Pour Moi", "W"}, - {misnamedTag{"Animal Kingdom"}, "Animal Kingdom", "X"}, - {badFormatTag{"Orfevre"}, "Orfevre", "Y"}, - {badCodeTag{"Reliable Man"}, "Reliable Man", "Z"}, - {percentSlashTag{"brut"}, "brut", "text/html%"}, - {punctuationTag{"Union Rags"}, "Union Rags", "!#$%&()*+-./:<=>?@[]^_{|}~"}, - {spaceTag{"Perreddu"}, "Perreddu", "With space"}, - {unicodeTag{"Loukanikos"}, "Loukanikos", "Ελλάδα"}, -} - -func TestStructTagObjectKey(t *testing.T) { - for _, tt := range structTagObjectKeyTests { - b, err := Marshal(tt.raw) - if err != nil { - t.Fatalf("Marshal(%#q) failed: %v", tt.raw, err) - } - var f interface{} - err = Unmarshal(b, &f) - if err != nil { - t.Fatalf("Unmarshal(%#q) failed: %v", b, err) - } - for i, v := range f.(map[string]interface{}) { - switch i { - case tt.key: - if s, ok := v.(string); !ok || s != tt.value { - t.Fatalf("Unexpected value: %#q, want %v", s, tt.value) - } - default: - t.Fatalf("Unexpected key: %#q, from %#q", i, b) - } - } - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/json/tags_test.go b/vendor/gopkg.in/square/go-jose.v2/json/tags_test.go deleted file mode 100644 index 91fb18831e..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/json/tags_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2011 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 json - -import ( - "testing" -) - -func TestTagParsing(t *testing.T) { - name, opts := parseTag("field,foobar,foo") - if name != "field" { - t.Fatalf("name = %q, want field", name) - } - for _, tt := range []struct { - opt string - want bool - }{ - {"foobar", true}, - {"foo", true}, - {"bar", false}, - } { - if opts.Contains(tt.opt) != tt.want { - t.Errorf("Contains(%q) = %v", tt.opt, !tt.want) - } - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/jwe_test.go b/vendor/gopkg.in/square/go-jose.v2/jwe_test.go deleted file mode 100644 index dc772af678..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/jwe_test.go +++ /dev/null @@ -1,543 +0,0 @@ -/*- - * Copyright 2014 Square 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 jose - -import ( - "bytes" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "crypto/x509" - "math/big" - "testing" -) - -func TestCompactParseJWE(t *testing.T) { - // Should parse - msg := "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.dGVzdA.dGVzdA.dGVzdA.dGVzdA" - _, err := ParseEncrypted(msg) - if err != nil { - t.Error("Unable to parse valid message:", err) - } - - // Messages that should fail to parse - failures := []string{ - // Too many parts - "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.dGVzdA.dGVzdA.dGVzdA.dGVzdA.dGVzdA", - // Not enough parts - "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.dGVzdA.dGVzdA.dGVzdA", - // Invalid encrypted key - "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.//////.dGVzdA.dGVzdA.dGVzdA", - // Invalid IV - "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.dGVzdA.//////.dGVzdA.dGVzdA", - // Invalid ciphertext - "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.dGVzdA.dGVzdA.//////.dGVzdA", - // Invalid tag - "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.dGVzdA.dGVzdA.dGVzdA.//////", - // Invalid header - "W10.dGVzdA.dGVzdA.dGVzdA.dGVzdA", - // Invalid header - "######.dGVzdA.dGVzdA.dGVzdA.dGVzdA", - // Missing alc/enc params - "e30.dGVzdA.dGVzdA.dGVzdA.dGVzdA", - } - - for _, msg := range failures { - _, err = ParseEncrypted(msg) - if err == nil { - t.Error("Able to parse invalid message", msg) - } - } -} - -func TestFullParseJWE(t *testing.T) { - // Messages that should succeed to parse - successes := []string{ - // Flattened serialization, single recipient - "{\"protected\":\"eyJhbGciOiJYWVoiLCJlbmMiOiJYWVoifQo\",\"encrypted_key\":\"QUJD\",\"iv\":\"QUJD\",\"ciphertext\":\"QUJD\",\"tag\":\"QUJD\"}", - // Unflattened serialization, single recipient - "{\"protected\":\"\",\"unprotected\":{\"enc\":\"XYZ\"},\"recipients\":[{\"header\":{\"alg\":\"XYZ\"},\"encrypted_key\":\"QUJD\"}],\"iv\":\"QUJD\",\"ciphertext\":\"QUJD\",\"tag\":\"QUJD\"}", - } - - for i := range successes { - _, err := ParseEncrypted(successes[i]) - if err != nil { - t.Error("Unble to parse valid message", err, successes[i]) - } - } - - // Messages that should fail to parse - failures := []string{ - // Empty - "{}", - // Invalid JSON - "{XX", - // Invalid protected header - "{\"protected\":\"###\"}", - // Invalid protected header - "{\"protected\":\"e1gK\"}", - // Invalid encrypted key - "{\"protected\":\"e30\",\"encrypted_key\":\"###\"}", - // Invalid IV - "{\"protected\":\"e30\",\"encrypted_key\":\"QUJD\",\"iv\":\"###\"}", - // Invalid ciphertext - "{\"protected\":\"e30\",\"encrypted_key\":\"QUJD\",\"iv\":\"QUJD\",\"ciphertext\":\"###\"}", - // Invalid tag - "{\"protected\":\"e30\",\"encrypted_key\":\"QUJD\",\"iv\":\"QUJD\",\"ciphertext\":\"QUJD\",\"tag\":\"###\"}", - // Invalid AAD - "{\"protected\":\"e30\",\"encrypted_key\":\"QUJD\",\"iv\":\"QUJD\",\"ciphertext\":\"QUJD\",\"tag\":\"QUJD\",\"aad\":\"###\"}", - // Missing alg/enc headers - "{\"protected\":\"e30\",\"encrypted_key\":\"QUJD\",\"iv\":\"QUJD\",\"ciphertext\":\"QUJD\",\"tag\":\"QUJD\"}", - // Missing enc header - "{\"protected\":\"eyJhbGciOiJYWVoifQ\",\"encrypted_key\":\"QUJD\",\"iv\":\"QUJD\",\"ciphertext\":\"QUJD\",\"tag\":\"QUJD\"}", - // Missing alg header - "{\"protected\":\"eyJlbmMiOiJYWVoifQ\",\"encrypted_key\":\"QUJD\",\"iv\":\"QUJD\",\"ciphertext\":\"QUJD\",\"tag\":\"QUJD\"}", - // Unflattened serialization, single recipient, invalid encrypted_key - "{\"protected\":\"\",\"recipients\":[{\"header\":{\"alg\":\"XYZ\", \"enc\":\"XYZ\"},\"encrypted_key\":\"###\"}],\"iv\":\"QUJD\",\"ciphertext\":\"QUJD\",\"tag\":\"QUJD\"}", - // Unflattened serialization, single recipient, missing alg - "{\"protected\":\"eyJhbGciOiJYWVoifQ\",\"recipients\":[{\"encrypted_key\":\"QUJD\"}],\"iv\":\"QUJD\",\"ciphertext\":\"QUJD\",\"tag\":\"QUJD\"}", - } - - for i := range failures { - _, err := ParseEncrypted(failures[i]) - if err == nil { - t.Error("Able to parse invalid message", err, failures[i]) - } - } -} - -func TestMissingInvalidHeaders(t *testing.T) { - protected := &rawHeader{} - protected.set(headerEncryption, A128GCM) - - obj := &JSONWebEncryption{ - protected: protected, - unprotected: &rawHeader{}, - recipients: []recipientInfo{ - {}, - }, - } - - _, err := obj.Decrypt(nil) - if err != ErrUnsupportedKeyType { - t.Error("should detect invalid key") - } - - obj.unprotected.set(headerCritical, []string{"1", "2"}) - - _, err = obj.Decrypt(nil) - if err == nil { - t.Error("should reject message with crit header") - } - - obj.unprotected.set(headerCritical, nil) - obj.protected = &rawHeader{} - obj.protected.set(headerAlgorithm, RSA1_5) - - _, err = obj.Decrypt(rsaTestKey) - if err == nil || err == ErrCryptoFailure { - t.Error("should detect missing enc header") - } -} - -func TestRejectUnprotectedJWENonce(t *testing.T) { - // No need to test compact, since that's always protected - - // Flattened JSON - input := `{ - "header": { - "alg": "XYZ", "enc": "XYZ", - "nonce": "should-cause-an-error" - }, - "encrypted_key": "does-not-matter", - "aad": "does-not-matter", - "iv": "does-not-matter", - "ciphertext": "does-not-matter", - "tag": "does-not-matter" - }` - _, err := ParseEncrypted(input) - if err == nil { - t.Error("JWE with an unprotected nonce parsed as valid.") - } else if err.Error() != "square/go-jose: Nonce parameter included in unprotected header" { - t.Errorf("Improper error for unprotected nonce: %v", err) - } - - input = `{ - "unprotected": { - "alg": "XYZ", "enc": "XYZ", - "nonce": "should-cause-an-error" - }, - "encrypted_key": "does-not-matter", - "aad": "does-not-matter", - "iv": "does-not-matter", - "ciphertext": "does-not-matter", - "tag": "does-not-matter" - }` - _, err = ParseEncrypted(input) - if err == nil { - t.Error("JWE with an unprotected nonce parsed as valid.") - } else if err.Error() != "square/go-jose: Nonce parameter included in unprotected header" { - t.Errorf("Improper error for unprotected nonce: %v", err) - } - - // Full JSON - input = `{ - "header": { "alg": "XYZ", "enc": "XYZ" }, - "aad": "does-not-matter", - "iv": "does-not-matter", - "ciphertext": "does-not-matter", - "tag": "does-not-matter", - "recipients": [{ - "header": { "nonce": "should-cause-an-error" }, - "encrypted_key": "does-not-matter" - }] - }` - _, err = ParseEncrypted(input) - if err == nil { - t.Error("JWS with an unprotected nonce parsed as valid.") - } else if err.Error() != "square/go-jose: Nonce parameter included in unprotected header" { - t.Errorf("Improper error for unprotected nonce: %v", err) - } -} - -func TestCompactSerialize(t *testing.T) { - // Compact serialization must fail if we have unprotected headers - obj := &JSONWebEncryption{ - unprotected: &rawHeader{}, - } - obj.unprotected.set(headerAlgorithm, "XYZ") - - _, err := obj.CompactSerialize() - if err == nil { - t.Error("Object with unprotected headers can't be compact serialized") - } -} - -func TestVectorsJWE(t *testing.T) { - plaintext := []byte("The true sign of intelligence is not knowledge but imagination.") - - publicKey := &rsa.PublicKey{ - N: fromBase64Int(` - oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW - cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S - psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a - sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS - tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj - YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw`), - E: 65537, - } - - expectedCompact := stripWhitespace(` - eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ.ROQCfge4JPm_ - yACxv1C1NSXmwNbL6kvmCuyxBRGpW57DvlwByjyjsb6g8m7wtLMqKEyhFCn - tV7sjippEePIlKln6BvVnz5ZLXHNYQgmubuNq8MC0KTwcaGJ_C0z_T8j4PZ - a1nfpbhSe-ePYaALrf_nIsSRKu7cWsrwOSlaRPecRnYeDd_ytAxEQWYEKFi - Pszc70fP9geZOB_09y9jq0vaOF0jGmpIAmgk71lCcUpSdrhNokTKo5y8MH8 - 3NcbIvmuZ51cjXQj1f0_AwM9RW3oCh2Hu0z0C5l4BujZVsDuGgMsGZsjUhS - RZsAQSXHCAmlJ2NlnN60U7y4SPJhKv5tKYw.48V1_ALb6US04U3b.5eym8T - W_c8SuK0ltJ3rpYIzOeDQz7TALvtu6UG9oMo4vpzs9tX_EFShS8iB7j6jiS - diwkIr3ajwQzaBtQD_A.XFBoMYUZodetZdvTiFvSkQ`) - - expectedFull := stripWhitespace(` - { "protected":"eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ", - "encrypted_key": - "ROQCfge4JPm_yACxv1C1NSXmwNbL6kvmCuyxBRGpW57DvlwByjyjsb - 6g8m7wtLMqKEyhFCntV7sjippEePIlKln6BvVnz5ZLXHNYQgmubuNq - 8MC0KTwcaGJ_C0z_T8j4PZa1nfpbhSe-ePYaALrf_nIsSRKu7cWsrw - OSlaRPecRnYeDd_ytAxEQWYEKFiPszc70fP9geZOB_09y9jq0vaOF0 - jGmpIAmgk71lCcUpSdrhNokTKo5y8MH83NcbIvmuZ51cjXQj1f0_Aw - M9RW3oCh2Hu0z0C5l4BujZVsDuGgMsGZsjUhSRZsAQSXHCAmlJ2Nln - N60U7y4SPJhKv5tKYw", - "iv": "48V1_ALb6US04U3b", - "ciphertext": - "5eym8TW_c8SuK0ltJ3rpYIzOeDQz7TALvtu6UG9oMo4vpzs9tX_EFS - hS8iB7j6jiSdiwkIr3ajwQzaBtQD_A", - "tag":"XFBoMYUZodetZdvTiFvSkQ" }`) - - // Mock random reader - randReader = bytes.NewReader([]byte{ - // Encryption key - 177, 161, 244, 128, 84, 143, 225, 115, 63, 180, 3, 255, 107, 154, - 212, 246, 138, 7, 110, 91, 112, 46, 34, 105, 47, 130, 203, 46, 122, - 234, 64, 252, - // Randomness for RSA-OAEP - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - // Initialization vector - 227, 197, 117, 252, 2, 219, 233, 68, 180, 225, 77, 219}) - defer resetRandReader() - - // Encrypt with a dummy key - encrypter, err := NewEncrypter(A256GCM, Recipient{Algorithm: RSA_OAEP, Key: publicKey}, nil) - if err != nil { - panic(err) - } - - object, err := encrypter.Encrypt(plaintext) - if err != nil { - panic(err) - } - - serialized, err := object.CompactSerialize() - if serialized != expectedCompact { - t.Error("Compact serialization is not what we expected", serialized, expectedCompact) - } - - serialized = object.FullSerialize() - if serialized != expectedFull { - t.Error("Full serialization is not what we expected") - } -} - -func TestVectorsJWECorrupt(t *testing.T) { - priv := &rsa.PrivateKey{ - PublicKey: rsa.PublicKey{ - N: fromHexInt(` - a8b3b284af8eb50b387034a860f146c4919f318763cd6c5598c8 - ae4811a1e0abc4c7e0b082d693a5e7fced675cf4668512772c0c - bc64a742c6c630f533c8cc72f62ae833c40bf25842e984bb78bd - bf97c0107d55bdb662f5c4e0fab9845cb5148ef7392dd3aaff93 - ae1e6b667bb3d4247616d4f5ba10d4cfd226de88d39f16fb`), - E: 65537, - }, - D: fromHexInt(` - 53339cfdb79fc8466a655c7316aca85c55fd8f6dd898fdaf1195 - 17ef4f52e8fd8e258df93fee180fa0e4ab29693cd83b152a553d - 4ac4d1812b8b9fa5af0e7f55fe7304df41570926f3311f15c4d6 - 5a732c483116ee3d3d2d0af3549ad9bf7cbfb78ad884f84d5beb - 04724dc7369b31def37d0cf539e9cfcdd3de653729ead5d1`), - Primes: []*big.Int{ - fromHexInt(` - d32737e7267ffe1341b2d5c0d150a81b586fb3132bed2f8d5262 - 864a9cb9f30af38be448598d413a172efb802c21acf1c11c520c - 2f26a471dcad212eac7ca39d`), - fromHexInt(` - cc8853d1d54da630fac004f471f281c7b8982d8224a490edbeb3 - 3d3e3d5cc93c4765703d1dd791642f1f116a0dd852be2419b2af - 72bfe9a030e860b0288b5d77`), - }, - } - - corruptCiphertext := stripWhitespace(` - eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.NFl09dehy - IR2Oh5iSsvEa82Ps7DLjRHeo0RnuTuSR45OsaIP6U8yu7vLlWaZKSZMy - B2qRBSujf-5XIRoNhtyIyjk81eJRXGa_Bxaor1XBCMyyhGchW2H2P71f - PhDO6ufSC7kV4bNqgHR-4ziS7KXwzN83_5kogXqxUpymUoJDNc.tk-GT - W_VVhiTIKFF.D_BE6ImZUl9F.52a-zFnRb3YQwIC7UrhVyQ`) - - corruptAuthtag := stripWhitespace(` - eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhHQ00ifQ.NFl09dehy - IR2Oh5iSsvEa82Ps7DLjRHeo0RnuTuSR45OsaIP6U8yu7vLlWaZKSZMy - B2qRBSujf-5XIRoNhtyIyjk81eJRXGa_Bxaor1XBCMyyhGchW2H2P71f - PhDO6ufSC7kV4bNqgHR-4ziS7KNwzN83_5kogXqxUpymUoJDNc.tk-GT - W_VVhiTIKFF.D_BE6ImZUl9F.52a-zFnRb3YQwiC7UrhVyQ`) - - msg, _ := ParseEncrypted(corruptCiphertext) - _, err := msg.Decrypt(priv) - if err != ErrCryptoFailure { - t.Error("should detect corrupt ciphertext") - } - - msg, _ = ParseEncrypted(corruptAuthtag) - _, err = msg.Decrypt(priv) - if err != ErrCryptoFailure { - t.Error("should detect corrupt auth tag") - } -} - -// Test vectors generated with nimbus-jose-jwt -func TestSampleNimbusJWEMessagesRSA(t *testing.T) { - rsaPrivateKey, err := x509.ParsePKCS8PrivateKey(fromBase64Bytes(` - MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCNRCEmf5PlbXKuT4uwnb - wGKvFrtpi+bDYxOZxxqxdVkZM/bYATAnD1fg9pNvLMKeF+MWJ9kPIMmDgOh9RdnRdLvQGb - BzhLmxwhhcua2QYiHEZizXmiaXvNP12bzEBhebdX7ObW8izMVW0p0lqHPNzkK3K75B0Sxo - FMVKkZ7KtBHgepBT5yPhPPcNe5lXQeTne5bo3I60DRcN9jTBgMJOXdq0I9o4y6ZmoXdNTm - 0EyLzn9/EYiHqBxtKFh791EHR7wYgyi/t+nOKr4sO74NbEByP0mHDil+mPvZSzFW4l7fPx - OclRZvpRIKIub2TroZA9s2WsshGf79eqqXYbBB9NNRAgMBAAECggEAIExbZ/nzTplfhwsY - 3SCzRJW87OuqsJ79JPQPGM4NX7sQ94eJqM7+FKLl0yCFErjgnYGdCyiArvB+oJPdsimgke - h83X0hGeg03lVA3/6OsG3WifCAxulnLN44AM8KST8S9D9t5+cm5vEBLHazzAfWWTS13s+g - 9hH8rf8NSqgZ36EutjKlvLdHx1mWcKX7SREFVHT8FWPAbdhTLEHUjoWHrfSektnczaSHnt - q8fFJy6Ld13QkF1ZJRUhtA24XrD+qLTc+M36IuedjeZaLHFB+KyhYR3YvXEtrbCug7dCRd - uG6uTlDCSaSy7xHeTPolWtWo9F202jal54otxiAJFGUHgQKBgQDRAT0s6YQZUfwE0wluXV - k0JdhDdCo8sC1aMmKlRKWUkBAqrDl7BI3MF56VOr4ybr90buuscshFf9TtrtBOjHSGcfDI - tSKfhhkW5ewQKB0YqyHzoD6UKT0/XAshFY3esc3uCxuJ/6vOiXV0og9o7eFvr51O0TfDFh - mcTvW4wirKlQKBgQCtB7UAu8I9Nn8czkd6oXLDRyTWYviuiqFmxR+PM9klgZtsumkeSxO1 - lkfFoj9+G8nFaqYEBA9sPeNtJVTSROCvj/iQtoqpV2NiI/wWeVszpBwsswx2mlks4LJa8a - Yz9xrsfNoroKYVppefc/MCoSx4M+99RSm3FSpLGZQHAUGyzQKBgQDMQmq4JuuMF1y2lk0E - SESyuz21BqV0tDVOjilsHT+5hmXWXoS6nkO6L2czrrpM7YE82F6JJZBmo7zEIXHBInGLJ3 - XLoYLZ5qNEhqYDUEDHaBCBWZ1vDTKnZlwWFEuXVavNNZvPbUhKTHq25t8qjDki/r09Vykp - BsM2yNBKpbBOVQKBgCJyUVd3CaFUExQyAMrqD0XPCQdhJq7gzGcAQVsp8EXmOoH3zmuIeM - ECzQEMXuWFNLMHm0tbX5Kl83vMHcnKioyI9ewhWxOBYTitf0ceG8j5F97SOl32NmCXzwoJ - 55Oa0xJXfLuIvOe8hZzp4WwZmBfKBxiCR166aPQQgIawelrVAoGAEJsHomfCI4epxH4oMw - qYJMCGy95zloB+2+c86BZCOJAGwnfzbtc2eutWZw61/9sSO8sQCfzA8oX+5HwAgnFVzwW4 - lNMZohppYcpwN9EyjkPaCXuALC7p5rF2o63wY7JLvnjS2aYZliknh2yW6X6fSB0PK0Cpvd - lAIyRw6Kud0zI=`)) - if err != nil { - panic(err) - } - - rsaSampleMessages := []string{ - "eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBMV81In0.EW0KOhHeoAxTBnLjYhh2T6HjwI-srNs6RpcSdZvE-GJ5iww3EYWBCmeGGj1UVz6OcBfwW3wllZ6GPOHU-hxVQH5KYpVOjkmrFIYU6-8BHhxBP_PjSJEBCZzjOgsCm9Th4-zmlO7UWTdK_UtwE7nk4X-kkmEy-aZBCShA8nFe2MVvqD5F7nvEWNFBOHh8ae_juo-kvycoIzvxLV9g1B0Zn8K9FAlu8YF1KiL5NFekn76f3jvAwlExuRbFPUx4gJN6CeBDK_D57ABsY2aBVDSiQceuYZxvCIAajqSS6dMT382FNJzAiQhToOpo_1w5FnnBjzJLLEKDk_I-Eo2YCWxxsQ.5mCMuxJqLRuPXGAr.Ghe4INeBhP3MDWGvyNko7qanKdZIzKjfeiU.ja3UlVWJXKNFJ-rZsJWycw", - "eyJlbmMiOiJBMTkyR0NNIiwiYWxnIjoiUlNBMV81In0.JsJeYoP0St1bRYNUaAmA34DAA27usE7RNuC2grGikBRmh1xrwUOpnEIXXpwr7fjVmNi52zzWkNHC8JkkRTrLcCh2VXvnOnarpH8DCr9qM6440bSrahzbxIvDds8z8q0wT1W4kjVnq1mGwGxg8RQNBWTV6Sp2FLQkZyjzt_aXsgYzr3zEmLZxB-d41lBS81Mguk_hdFJIg_WO4ao54lozvxkCn_uMiIZ8eLb8qHy0h-N21tiHGCaiC2vV8KXomwoqbJ0SXrEH4r9_R2J844H80TBZdbvNBd8whvoQNHvOX659LNs9EQ9xxvHU2kqGZekXBu7sDXXTjctMkMITobGSzw.1v5govaDvanP3LGp.llwYNBDrD7MwVLaFHesljlratfmndWs4XPQ.ZGT1zk9_yIKi2GzW6CuAyA", - "eyJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUlNBMV81In0.fBv3fA3TMS3ML8vlsCuvwdsKvB0ym8R30jJrlOiqkWKk7WVUkjDInFzr1zw3Owla6c5BqOJNoACXt4IWbkLbkoWV3tweXlWwpafuaWPkjLOUH_K31rS2fCX5x-MTj8_hScquVQXpbz3vk2EfulRmGXZc_8JU2NqQCAsYy3a28houqP3rDe5jEAvZS2SOFvJkKW--f5S-z39t1D7fNz1N8Btd9SmXWQzjbul5YNxI9ctqxhJpkKYpxOLlvrzdA6YdJjOlDx3n6S-HnSZGM6kQd_xKtAf8l1EGwhQmhbXhMhjVxMvGwE5BX7PAb8Ccde5bzOCJx-PVbVetuLb169ZYqQ._jiZbOPRR82FEWMZ.88j68LI-K2KT6FMBEdlz6amG5nvaJU8a-90.EnEbUTJsWNqJYKzfO0x4Yw", - "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiUlNBMV81In0.bN6FN0qmGxhkESiVukrCaDVG3woL0xE-0bHN_Mu0WZXTQWbzzT-7jOvaN1xhGK8nzi8qpCSRgE5onONNB9i8OnJm3MMIxF7bUUEAXO9SUAFn2v--wNc4drPc5OjIu0RiJrDVDkkGjNrBDIuBaEQcke7A0v91PH58dXE7o4TLPzC8UJmRtXWhUSwjXVF3-UmYRMht2rjHJlvRbtm6Tu2LMBIopRL0zj6tlPP4Dm7I7sz9OEB3VahYAhpXnFR7D_f8RjLSXQmBvB1FiI5l_vMz2NFt2hYUmQF3EJMLIEdHvvPp3iHDGiXC1obJrDID_CCf3qs9UY7DMYL622KLvP2NIg.qb72oxECzxd_aNuHVR0aNg.Gwet9Ms8hB8rKEb0h4RGdFNRq97Qs2LQaJM0HWrCqoI.03ljVThOFvgXzMmQJ79VjQ", - "eyJlbmMiOiJBMTkyQ0JDLUhTMzg0IiwiYWxnIjoiUlNBMV81In0.ZbEOP6rqdiIP4g7Nl1PL5gwhgDwv9RinyiUQxZXPOmD7kwEZrZ093dJnhqI9kEd3QGFlHDpB7HgNz53d27z2zmEj1-27v6miizq6tH4sN2MoeZLwSyk16O1_n3bVdDmROawsTYYFJfHsuLwyVJxPd37duIYnbUCFO9J8lLIv-2VI50KJ1t47YfE4P-Wt9jVzxP2CVUQaJwTlcwfiDLJTagYmfyrDjf525WlQFlgfJGqsJKp8BX9gmKvAo-1iCBAM8VpEjS0u0_hW9VSye36yh8BthVV-VJkhJ-0tMpto3bbBmj7M25Xf4gbTrrVU7Nz6wb18YZuhHZWmj2Y2nHV6Jg.AjnS44blTrIIfFlqVw0_Mg.muCRgaEXNKKpW8rMfW7jf7Zpn3VwSYDz-JTRg16jZxY.qjc9OGlMaaWKDWQSIwVpR4K556Pp6SF9", - "eyJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIjoiUlNBMV81In0.c7_F1lMlRHQQE3WbKmtHBYTosdZrG9hPfs-F9gNQYet61zKG8NXVkSy0Zf2UFHt0vhcO8hP2qrqOFsy7vmRj20xnGHQ2EE29HH6hwX5bx1Jj3uE5WT9Gvh0OewpvF9VubbwWTIObBpdEG7XdJsMAQlIxtXUmQYAtLTWcy2ZJipyJtVlWQLaPuE8BKfZH-XAsp2CpQNiRPI8Ftza3EAspiyRfVQbjKt7nF8nuZ2sESjt7Y50q4CSiiCuGT28T3diMN0_rWrH-I-xx7OQvJlrQaNGglGtu3jKUcrJDcvxW2e1OxriaTeuQ848ayuRvGUNeSv6WoVYmkiK1x_gNwUAAbw.7XtSqHJA7kjt6JrfxJMwiA.Yvi4qukAbdT-k-Fd2s4G8xzL4VFxaFC0ZIzgFDAI6n0.JSWPJ-HjOE3SK9Lm0yHclmjS7Z1ahtQga9FHGCWVRcc", - "eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.SYVxJbCnJ_tcR13LJpaqHQj-nGNkMxre4A1FmnUdxnvzeJwuvyrLiUdRsZR1IkP4fqLtDON2mumx39QeJQf0WIObPBYlIxycRLkwxDHRVlyTmPvdZHAxN26jPrk09wa5SgK1UF1W1VSQIPm-Tek8jNAmarF1Yxzxl-t54wZFlQiHP4TuaczugO5f-J4nlWenfla2mU1snDgdUMlEZGOAQ_gTEtwSgd1MqXmK_7LZBkoDqqoCujMZhziafJPXPDaUUqBLW3hHkkDA7GpVec3XcTtNUWQJqOpMyQhqo1KQMc8jg3fuirILp-hjvvNVtBnCRBvbrKUCPzu2_yH3HM_agA.2VsdijtonAxShNIW.QzzB3P9CxYP3foNKN0Ma1Z9tMwijAlkWo08.ZdQkIPDY_M-hxqi5fD4NGw", - "eyJlbmMiOiJBMTkyR0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.Z2oTJXXib1u-S38Vn3DRKE3JnhnwgUa92UhsefzY2Wpdn0dmxMfYt9iRoJGFfSAcA97MOfjyvXVRCKWXGrG5AZCMAXEqU8SNQwKPRjlcqojcVzQyMucXI0ikLC4mUgeRlfKTwsBicq6JZZylzRoLGGSNJQbni3_BLsf7H3Qor0BYg0FPCLG9Z2OVvrFzvjTLmZtV6gFlVrMHBxJub_aUet9gAkxiu1Wx_Kx46TlLX2tkumXIpTGlzX6pef6jLeZ5EIg_K-Uz4tkWgWQIEkLD7qmTyk5pAGmzukHa_08jIh5-U-Sd8XGZdx4J1pVPJ5CPg0qDJGZ_cfgkgpWbP_wB6A.4qgKfokK1EwYxz20._Md82bv_KH2Vru0Ue2Eb6oAqHP2xBBP5jF8.WFRojvQpD5VmZlOr_dN0rQ", - "eyJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUlNBLU9BRVAifQ.JzCUgJcBJmBgByp4PBAABUfhezPvndxBIVzaoZ96DAS0HPni0OjMbsOGsz6JwNsiTr1gSn_S6R1WpZM8GJc9R2z0EKKVP67TR62ZSG0MEWyLpHmG_4ug0fAp1HWWMa9bT4ApSaOLgwlpVAb_-BPZZgIu6c8cREuMon6UBHDqW1euTBbzk8zix3-FTZ6p5b_3soDL1wXfRiRBEsxxUGMnpryx1OFb8Od0JdyGF0GgfLt6OoaujDJpo-XtLRawu1Xlg6GqRs0NQwSHZ5jXgQ6-zgCufXonAmYTiIyBXY2no9XmECTexjwrS_05nA7H-UyIZEBOCp3Yhz2zxrt5j_0pvQ.SJR-ghhaUKP4zXtZ.muiuzLfZA0y0BDNsroGTw2r2-l73SLf9lK8.XFMH1oHr1G6ByP3dWSUUPA", - "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiUlNBLU9BRVAifQ.U946MVfIm4Dpk_86HrnIA-QXyiUu0LZ67PL93CMLmEtJemMNDqmRd9fXyenCIhAC7jPIV1aaqW7gS194xyrrnUpBoJBdbegiPqOfquy493Iq_GQ8OXnFxFibPNQ6rU0l8BwIfh28ei_VIF2jqN6bhxFURCVW7fG6n6zkCCuEyc7IcxWafSHjH2FNttREuVj-jS-4LYDZsFzSKbpqoYF6mHt8H3btNEZDTSmy_6v0fV1foNtUKNfWopCp-iE4hNh4EzJfDuU8eXLhDb03aoOockrUiUCh-E0tQx9su4rOv-mDEOHHAQK7swm5etxoa7__9PC3Hg97_p4GM9gC9ykNgw.pnXwvoSPi0kMQP54of-HGg.RPJt1CMWs1nyotx1fOIfZ8760mYQ69HlyDp3XmdVsZ8.Yxw2iPVWaBROFE_FGbvodA", - "eyJlbmMiOiJBMTkyQ0JDLUhTMzg0IiwiYWxnIjoiUlNBLU9BRVAifQ.eKEOIJUJpXmO_ghH_nGCJmoEspqKyiy3D5l0P8lKutlo8AuYHPQlgOsaFYnDkypyUVWd9zi-JaQuCeo7dzoBiS1L71nAZo-SUoN0anQBkVuyuRjr-deJMhPPfq1H86tTk-4rKzPr1Ivd2RGXMtWsrUpNGk81r1v8DdMntLE7UxZQqT34ONuZg1IXnD_U6di7k07unI29zuU1ySeUr6w1YPw5aUDErMlpZcEJWrgOEYWaS2nuC8sWGlPGYEjqkACMFGn-y40UoS_JatNZO6gHK3SKZnXD7vN5NAaMo_mFNbh50e1t_zO8DaUdLtXPOBLcx_ULoteNd9H8HyDGWqwAPw.0xmtzJfeVMoIT1Cp68QrXA.841l1aA4c3uvSYfw6l180gn5JZQjL53WQ5fr8ejtvoI.lojzeWql_3gDq-AoaIbl_aGQRH_54w_f", - "eyJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIjoiUlNBLU9BRVAifQ.D0QkvIXR1TL7dIHWuPNMybmmD8UPyQd1bRKjRDNbA2HmKGpamCtcJmpNB_EetNFe-LDmhe44BYI_XN2wIBbYURKgDK_WG9BH0LQw_nCVqQ-sKqjtj3yQeytXhLHYTDmiF0TO-uW-RFR7GbPAdARBfuf4zj82r_wDD9sD5WSCGx89iPfozDOYQ_OLwdL2WD99VvDyfwS3ZhxA-9IMSYv5pwqPkxj4C0JdjCqrN0YNrZn_1ORgjtsVmcWXsmusObTozUGA7n5GeVepfZdU1vrMulAwdRYqOYtlqKaOpFowe9xFN3ncBG7wb4f9pmzbS_Dgt-1_Ii_4SEB9GQ4NiuBZ0w.N4AZeCxMGUv52A0UVJsaZw.5eHOGbZdtahnp3l_PDY-YojYib4ft4SRmdsQ2kggrTs.WsmGH8ZDv4ctBFs7qsQvw2obe4dVToRcAQaZ3PYL34E", - "eyJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiUlNBLU9BRVAtMjU2In0.fDTxO_ZzZ3Jdrdw-bxvg7u-xWB2q1tp3kI5zH6JfhLUm4h6rt9qDA_wZlRym8-GzEtkUjkTtQGs6HgQx_qlyy8ylCakY5GHsNhCG4m0UNhRiNfcasAs03JSXfON9-tfTJimWD9n4k5OHHhvcrsCW1G3jYeLsK9WHCGRIhNz5ULbo8HBrCTbmZ6bOEQ9mqhdssLpdV24HDpebotf3bgPJqoaTfWU6Uy7tLmPiNuuNRLQ-iTpLyNMTVvGqqZhpcV3lAEN5l77QabI5xLJYucvYjrXQhAEZ7YXO8oRYhGkdG2XXIRcwr87rBeRH-47HAyhZgF_PBPBhhrJNS9UNMqdfBw.FvU4_s7Md6vxnXWd.fw29Q4_gHt4f026DPPV-CNebQ8plJ6IVLX8._apBZrw7WsT8HOmxgCrTwA", - "eyJlbmMiOiJBMTkyR0NNIiwiYWxnIjoiUlNBLU9BRVAtMjU2In0.bYuorK-rHMbO4c2CRWtvyOEaM1EN-o-wLRZ0wFWRX9mCXQ-iTNarZn7ksYM1XnGmZ4u3CSowX1Hpca9Rg72_VJCmKapqCT7r3YfasN4_oeLwuSKI_gT-uVOznod97tn3Gf_EDv0y1V4H0k9BEIFGbajAcG1znTD_ODY3j2KZJxisfrsBoslc6N-HI0kKZMC2hSGuHOcOf8HN1sTE-BLqZCtoj-zxQECJK8Wh14Ih4jzzdmmiu_qmSR780K6su-4PRt3j8uY7oCiLBfwpCsCmhJgp8rKd91zoedZmamfvX38mJIfE52j4fG6HmIYw9Ov814fk9OffV6tzixjcg54Q2g.yeVJz4aSh2s-GUr9.TBzzWP5llEiDdugpP2SmPf2U4MEGG9EoPWk.g25UoWpsBaOd45J__FX7mA", - "eyJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiUlNBLU9BRVAtMjU2In0.h9tFtmh762JuffBxlSQbJujCyI4Zs9yc3IOb1yR8g65W4ZHosIvzVGHWbShj4EY9MNrz-RbKtHfqQGGzDeo3Xb4-HcQ2ZDHyWoUg7VfA8JafJ5zIKL1npz8eUExOVMLsAaRfHg8qNfczodg3egoSmX5Q-nrx4DeidDSXYZaZjV0C72stLTPcuQ7XPV7z1tvERAkqpvcsRmJn_PiRNxIbAgoyHMJ4Gijuzt1bWZwezlxYmw0TEuwCTVC2fl9NJTZyxOntS1Lcm-WQGlPkVYeVgYTOQXLlp7tF9t-aAvYpth2oWGT6Y-hbPrjx_19WaKD0XyWCR46V32DlXEVDP3Xl2A.NUgfnzQyEaJjzt9r.k2To43B2YVWMeR-w3n4Pr2b5wYq2o87giHk.X8_QYCg0IGnn1pJqe8p_KA", - "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiUlNBLU9BRVAtMjU2In0.EDq6cNP6Yp1sds5HZ4CkXYp7bs9plIYVZScKvuyxUy0H1VyBC_YWg0HvndPNb-vwh1LA6KMxRazlOwJ9iPR9YzHnYmGgPM3Je_ZzBfiPlRfq6hQBpGnNaypBI1XZ2tyFBhulsVLqyJe2SmM2Ud00kasOdMYgcN8FNFzq7IOE7E0FUQkIwLdUL1nrzepiYDp-5bGkxWRcL02cYfdqdm00G4m0GkUxAmdxa3oPNxZlt2NeBI_UVWQSgJE-DJVJQkDcyA0id27TV2RCDnmujYauNT_wYlyb0bFDx3pYzzNXfAXd4wHZxt75QaLZ5APJ0EVfiXJ0qki6kT-GRVmOimUbQA.vTULZL7LvS0WD8kR8ZUtLg.mb2f0StEmmkuuvsyz8UplMvF58FtZzlu8eEwzvPUvN0.hbhveEN40V-pgG2hSVgyKg", - "eyJlbmMiOiJBMTkyQ0JDLUhTMzg0IiwiYWxnIjoiUlNBLU9BRVAtMjU2In0.DuYk92p7u-YIN-JKn-XThmlVcnhU9x5TieQ2uhsLQVNlo0iWC9JJPP6bT6aI6u_1BIS3yE8_tSGGL7eM-zyEk6LuTqSWFRaZcZC06d0MnS9eYZcw1T2D17fL-ki-NtCaTahJD7jE2s0HevRVW49YtL-_V8whnO_EyVjvXIAQlPYqhH_o-0Nzcpng9ggdAnuF2rY1_6iRPYFJ3BLQvG1oWhyJ9s6SBttlOa0i6mmFCVLHx6sRpdGAB3lbCL3wfmHq4tpIv77gfoYUNP0SNff-zNmBXF_wp3dCntLZFTjbfMpGyHlruF_uoaLqwdjYpUGNUFVUoeSiMnSbMKm9NxiDgQ.6Mdgcqz7bMU1UeoAwFC8pg.W36QWOlBaJezakUX5FMZzbAgeAu_R14AYKZCQmuhguw.5OeyIJ03olxmJft8uBmjuOFQPWNZMYLI", - "eyJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIjoiUlNBLU9BRVAtMjU2In0.ECulJArWFsPL2FlpCN0W8E7IseSjJg1cZqE3wz5jk9gvwgNForAUEv5KYZqhNI-p5IxkGV0f8K6Y2X8pWzbLwiPIjZe8_dVqHYJoINxqCSgWLBhz0V36qL9Nc_xARTBk4-ZteIu75NoXVeos9gNvFnkOCj4tm-jGo8z8EFO9XfODgjhiR4xv8VqUtvrkjo9GQConaga5zpV-J4JQlXbdqbDjnuwacnJAxYpFyuemqcgqsl6BnFX3tovGkmSUPqcvF1A6tiHqr-TEmcgVqo5C3xswknRBKTQRM00iAmJ92WlVdkoOCx6E6O7cVHFawZ14BLzWzm66Crb4tv0ucYvk_Q.mxolwUaoj5S5kHCfph0w8g.nFpgYdnYg3blHCCEi2XXQGkkKQBXs2OkZaH11m3PRvk.k8BAVT4EcyrUFVIKr-KOSPbF89xyL0Vri2rFTu2iIWM", - } - - for _, msg := range rsaSampleMessages { - obj, err := ParseEncrypted(msg) - if err != nil { - t.Error("unable to parse message", msg, err) - continue - } - plaintext, err := obj.Decrypt(rsaPrivateKey) - if err != nil { - t.Error("unable to decrypt message", msg, err) - continue - } - if string(plaintext) != "Lorem ipsum dolor sit amet" { - t.Error("plaintext is not what we expected for msg", msg) - } - } -} - -// Test vectors generated with nimbus-jose-jwt -func TestSampleNimbusJWEMessagesAESKW(t *testing.T) { - aesTestKeys := [][]byte{ - fromHexBytes("DF1FA4F36FFA7FC42C81D4B3C033928D"), - fromHexBytes("DF1FA4F36FFA7FC42C81D4B3C033928D95EC9CDC2D82233C"), - fromHexBytes("DF1FA4F36FFA7FC42C81D4B3C033928D95EC9CDC2D82233C333C35BA29044E90"), - } - - aesSampleMessages := [][]string{ - { - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4R0NNIiwidGFnIjoib2ZMd2Q5NGloVWFRckJ0T1pQUDdjUSIsImFsZyI6IkExMjhHQ01LVyIsIml2IjoiV2Z3TnN5cjEwWUFjY2p2diJ9.9x3RxdqIS6P9xjh93Eu1bQ.6fs3_fSGt2jull_5.YDlzr6sWACkFg_GU5MEc-ZEWxNLwI_JMKe_jFA.f-pq-V7rlSSg_q2e1gDygw", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyR0NNIiwidGFnIjoic2RneXB1ckFjTEFzTmZJU0lkZUNpUSIsImFsZyI6IkExMjhHQ01LVyIsIml2IjoieVFMR0dCdDJFZ0c1THdyViJ9.arslKo4aKlh6f4s0z1_-U-8JbmhAoZHN.Xw2Q-GX98YXwuc4i.halTEWMWAYZbv-qOD52G6bte4x6sxlh1_VpGEA.Z1spn016v58cW6Q2o0Qxag", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2R0NNIiwidGFnIjoicTNzejF5VUlhbVBDYXJfZ05kSVJqQSIsImFsZyI6IkExMjhHQ01LVyIsIml2IjoiM0ZRM0FsLWJWdWhmcEIyQyJ9.dhVipWbzIdsINttuZM4hnjpHvwEHf0VsVrOp4GAg01g.dk7dUyt1Qj13Pipw.5Tt70ONATF0BZAS8dBkYmCV7AQUrfb8qmKNLmw.A6ton9MQjZg0b3C0QcW-hg", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwidGFnIjoiUHNpTGphZnJZNE16UlRmNlBPLTZfdyIsImFsZyI6IkExMjhHQ01LVyIsIml2IjoiSUFPbnd2ODR5YXFEaUxtbSJ9.swf92_LyCvjsvkynHTuMNXRl_MX2keU-fMDWIMezHG4.LOp9SVIXzs4yTnOtMyXZYQ.HUlXrzqJ1qXYl3vUA-ydezCg77WvJNtKdmZ3FPABoZw.8UYl1LOofQLAxHHvWqoTbg", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyQ0JDLUhTMzg0IiwidGFnIjoiWGRndHQ5dUVEMVlVeU1rVHl6M3lqZyIsImFsZyI6IkExMjhHQ01LVyIsIml2IjoiWF90V2RhSmh6X3J1SHJvQSJ9.JQ3dS1JSgzIFi5M9ig63FoFU1nHBTmPwXY_ovNE2m1JOSUvHtalmihIuraPDloCf.e920JVryUIWt7zJJQM-www.8DUrl4LmsxIEhRr9RLTHG9tBTOcwXqEbQHAJd_qMHzE.wHinoqGUhL4O7lx125kponpwNtlp8VGJ", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwidGFnIjoicGgyaTdoY0FWNlh3ZkQta1RHYlVXdyIsImFsZyI6IkExMjhHQ01LVyIsIml2IjoiaG41Smk4Wm1rUmRrSUxWVSJ9._bQlJXl22dhsBgYPhkxUyinBNi871teGWbviOueWj2PqG9OPxIc9SDS8a27YLSVDMircd5Q1Df28--vcXIABQA.DssmhrAg6w_f2VDaPpxTbQ.OGclEmqrxwvZqAfn7EgXlIfXgr0wiGvEbZz3zADnqJs.YZeP0uKVEiDl8VyC-s20YN-RbdyGNsbdtoGDP3eMof8", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiQTEyOEtXIn0.TEMcXEoY8WyqGjYs5GZgS-M_Niwu6wDY.i-26KtTt51Td6Iwd.wvhkagvPsLj3QxhPBbfH_th8OqxisUtme2UadQ.vlfvBPv3bw2Zk2H60JVNLQ", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyR0NNIiwiYWxnIjoiQTEyOEtXIn0.gPaR6mgQ9TUx05V6DRfgTQeZxl0ZSzBa5uQd-qw6yLs.MojplOD77FkMooS-.2yuD7dKR_C3sFbhgwiBccKKOF8DrSvNiwX7wPQ.qDKUbSvMnJv0qifjpWC14g", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiQTEyOEtXIn0.Fg-dgSkUW1KEaL5YDPoWHNL8fpX1WxWVLA9OOWsjIFhQVDKyUZI7BQ.mjRBpyJTZf7H-quf.YlNHezMadtaSKp23G-ozmYhHOeHwuJnvWGTtGg.YagnR7awBItUlMDo4uklvg", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiQTEyOEtXIn0.x1vYzUE-E2XBWva9OPuwtqfQaf9rlJCIBAyAe6N2q2kWfJrkxGxFsQ.gAwe78dyODFaoP2IOityAA.Yh5YfovkWxGBNAs1sVhvXow_2izHHsBiYEc9JYD6kVg.mio1p3ncp2wLEaEaRa7P0w", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyQ0JDLUhTMzg0IiwiYWxnIjoiQTEyOEtXIn0.szGrdnmF7D5put2aRBvSSFfp0vRgkRGYaafijJIqAF6PWd1IxsysZRV8aQkQOW1cB6d0fXsTfYM.Ru25LVOOk4xhaK-cIZ0ThA.pF9Ok5zot7elVqXFW5YYHV8MuF9gVGzpQnG1XDs_g_w.-7la0uwcNPpteev185pMHZjbVDXlrec8", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIjoiQTEyOEtXIn0.cz-hRv0xR5CnOcnoRWNK8Q9poyVYzRCVTjfmEXQN6xPOZUkJ3zKNqb8Pir_FS0o2TVvxmIbuxeISeATTR2Ttx_YGCNgMkc93.SF5rEQT94lZR-UORcMKqGw.xphygoU7zE0ZggOczXCi_ytt-Evln8CL-7WLDlWcUHg.5h99r8xCCwP2PgDbZqzCJ13oFfB2vZWetD5qZjmmVho", - }, - { - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4R0NNIiwidGFnIjoiVWR5WUVKdEJ5ZTA5dzdjclY0cXI1QSIsImFsZyI6IkExOTJHQ01LVyIsIml2IjoiZlBBV0QwUmdSbHlFdktQcCJ9.P1uTfTuH-imL-NJJMpuTRA.22yqZ1NIfx3KNPgc.hORWZaTSgni1FS-JT90vJly-cU37qTn-tWSqTg.gMN0ufXF92rSXupTtBNkhA", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyR0NNIiwidGFnIjoiOU9qX3B2LTJSNW5lZl9YbWVkUWltUSIsImFsZyI6IkExOTJHQ01LVyIsIml2IjoiY3BybGEwYUYzREVQNmFJTSJ9.6NVpAm_APiC7km2v-oNR8g23K9U_kf1-.jIg-p8tNwSvwxch0.1i-GPaxS4qR6Gy4tzeVtSdRFRSKQSMpmn-VhzA.qhFWPqtA6vVPl7OM3DThsA", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2R0NNIiwidGFnIjoiOVc3THg3MVhGQVJCb3NaLVZ5dXc4ZyIsImFsZyI6IkExOTJHQ01LVyIsIml2IjoiZ1N4ZE5heFdBSVBRR0tHYiJ9.3YjPz6dVQwAtCekvtXiHZrooOUlmCsMSvyfwmGwdrOA.hA_C0IDJmGaRzsB0.W4l7OPqpFxiVOZTGfAlRktquyRTo4cEOk9KurQ.l4bGxOkO_ql_jlPo3Oz3TQ", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwidGFnIjoiOHJYbWl2WXFWZjNfbHhhd2NUbHJoUSIsImFsZyI6IkExOTJHQ01LVyIsIml2IjoiVXBWeXprVTNKcjEwYXRqYyJ9.8qft-Q_xqUbo5j_aVrVNHchooeLttR4Kb6j01O8k98M.hXO-5IKBYCL9UdwBFVm0tg.EBM4lCZX_K6tfqYmfoDxVPHcf6cT--AegXTTjfSqsIw.Of8xUvEQSh3xgFT3uENnAg", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyQ0JDLUhTMzg0IiwidGFnIjoiVnItSnVaX0tqV2hSWWMzdzFwZ3cwdyIsImFsZyI6IkExOTJHQ01LVyIsIml2IjoiRGg2R3dISVBVS3ljZGNZeCJ9.YSEDjCnGWr_n9H94AvLoRnwm6bdU9w6-Q67k-QQRVcKRd6673pgH9zEF9A9Dt6o1.gcmVN4kxqBuMq6c7GrK3UQ.vWzJb0He6OY1lhYYjYS7CLh55REAAq1O7yNN-ND4R5Q.OD0B6nwyFaDr_92ysDOtlVnJaeoIqhGw", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwidGFnIjoieEtad1BGYURpQ3NqUnBqZUprZHhmZyIsImFsZyI6IkExOTJHQ01LVyIsIml2IjoieTVHRFdteXdkb2R1SDJlYyJ9.AW0gbhWqlptOQ1y9aoNVwrTIIkBfrp33C2OWJsbrDRk6lhxg_IgFhMDTE37moReySGUtttC4CXQD_7etHmd3Hw.OvKXK-aRKlXHOpJQ9ZY_YQ.Ngv7WarDDvR2uBj_DavPAR3DYuIaygvSSdcHrc8-ZqM.MJ6ElitzFCKf_0h5fIJw8uOLC6ps7dKZPozF8juQmUY", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiQTE5MktXIn0.8qu63pppcSvp1vv37WrZ44qcCTg7dQMA.cDp-f8dJTrDEpZW4.H6OBJYs4UvFR_IZHLYQZxB6u9a0wOdAif2LNfQ.1dB-id0UIwRSlmwHx5BJCg", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyR0NNIiwiYWxnIjoiQTE5MktXIn0._FdoKQvC8qUs7K0upriEihUwztK8gOwonXpOxdIwrfs.UO38ok8gDdpLVa1T.x1GvHdVCy4fxoQRg-OQK4Ez3jDOvu9gllLPeEA.3dLeZGIprh_nHizOTVi1xw", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiQTE5MktXIn0.uzCJskgSIK6VkjJIu-dQi18biqaY0INc_A1Ehx0oESafgtR99_n4IA.W2eKK8Y14WwTowI_.J2cJC7R6Bz6maR0s1UBMPyRi5BebNUAmof4pvw.-7w6htAlc4iUsOJ6I04rFg", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiQTE5MktXIn0.gImQeQETp_6dfJypFDPLlv7c5pCzuq86U16gzrLiCXth6X9XfxJpvQ.YlC4MxjtLWrsyEvlFhvsqw.Vlpvmg9F3gkz4e1xG01Yl2RXx-jG99rF5UvCxOBXSLc.RZUrU_FoR5bG3M-j3GY0Dw", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyQ0JDLUhTMzg0IiwiYWxnIjoiQTE5MktXIn0.T2EfQ6Tu2wJyRMgZzfvBYmQNCCfdMudMrg86ibEMVAOUKJPtR3WMPEb_Syy9p2VjrLKRlv7nebo.GPc8VbarPPRtzIRATB8NsA.ugPCqLvVLwh55bWlwjsFkmWzJ31z5z-wuih2oJqmG_U.m7FY3EjvV6mKosEYJ5cY7ezFoVQoJS8X", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIjoiQTE5MktXIn0.OgLMhZ-2ZhslQyHfzOfyC-qmT6bNg9AdpP59B4jtyxWkQu3eW475WCdiAjojjeyBtVRGQ5vOomwaOIFejY_IekzH6I_taii3.U9x44MF6Wyz5TIwIzwhoxQ.vK7yvSF2beKdNxNY_7n4XdF7JluCGZoxdFJyTJVkSmI.bXRlI8KL-g7gpprQxGmXjVYjYghhWJq7mlCfWI8q2uA", - }, - { - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4R0NNIiwidGFnIjoiR3BjX3pfbjduZjJVZlEtWGdsaTBaQSIsImFsZyI6IkEyNTZHQ01LVyIsIml2IjoiUk40eUdhOVlvYlFhUmZ1TCJ9.Q4ukD6_hZpmASAVcqWJ9Wg.Zfhny_1WNdlp4fH-.3sekDCjkExQCcv28ZW4yrcFnz0vma3vgoenSXA.g8_Ird2Y0itTCDP61du-Yg", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyR0NNIiwidGFnIjoiWC05UkNVWVh4U3NRelcwelVJS01VUSIsImFsZyI6IkEyNTZHQ01LVyIsIml2IjoiY3JNMnJfa3RrdWpyQ1h5OSJ9.c0q2jCxxV4y1h9u_Xvn7FqUDnbkmNEG4.S_noOTZKuUo9z1l6.ez0RdA25vXMUGH96iXmj3DEVox0J7TasJMnzgg.RbuSPTte_NzTtEEokbc5Ig", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2R0NNIiwidGFnIjoiWmwyaDFpUW11QWZWd2lJeVp5RHloZyIsImFsZyI6IkEyNTZHQ01LVyIsIml2Ijoib19xZmljb0N0NzNzRWo1QyJ9.NpJxRJ0aqcpekD6HU2u9e6_pL_11JXjWvjfeQnAKkZU.4c5qBcBBrMWi27Lf.NKwNIb4b6cRDJ1TwMKsPrjs7ADn6aNoBdQClVw.yNWmSSRBqQfIQObzj8zDqw", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwidGFnIjoiMXdwVEI3LWhjdzZUVXhCbVh2UzdhUSIsImFsZyI6IkEyNTZHQ01LVyIsIml2IjoiOUdIVnZJaDZ0a09vX2pHUSJ9.MFgIhp9mzlq9hoPqqKVKHJ3HL79EBYtV4iNhD63yqiU.UzW5iq8ou21VpZYJgKEN8A.1gOEzA4uAPvHP76GMfs9uLloAV10mKaxiZVAeL7iQA0.i1X_2i0bCAz-soXF9bI_zw", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyQ0JDLUhTMzg0IiwidGFnIjoiNThocUtsSk15Y1BFUEFRUlNfSzlNUSIsImFsZyI6IkEyNTZHQ01LVyIsIml2IjoiUDh3aTBWMTluVnZqNXpkOSJ9.FXidOWHNFJODO74Thq3J2cC-Z2B8UZkn7SikeosU0bUK6Jx_lzzmUZ-Lafadpdpj.iLfcDbpuBKFiSfiBzUQc7Q.VZK-aD7BFspqfvbwa0wE2wwWxdomzk2IKMetFe8bI44.7wC6rJRGa4x48xbYMd6NH9VzK8uNn4Cb", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwidGFnIjoicGcwOEpUcXdzMXdEaXBaRUlpVExoQSIsImFsZyI6IkEyNTZHQ01LVyIsIml2IjoiSlpodk9CdU1RUDFFZTZTNSJ9.wqVgTPm6TcYCTkpbwmn9sW4mgJROH2A3dIdSXo5oKIQUIVbQsmy7KXH8UYO2RS9slMGtb869C8o0My67GKg9dQ.ogrRiLlqjB1S5j-7a05OwA.2Y_LyqhU4S_RXMsB74bxcBacd23J2Sp5Lblw-sOkaUY.XGMiYoU-f3GaEzSvG41vpJP2DMGbeDFoWmkUGLUjc4M", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4R0NNIiwiYWxnIjoiQTI1NktXIn0.QiIZm9NYfahqYFIbiaoUhCCHjotHMkup.EsU0XLn4FjzzCILn.WuCoQkm9vzo95E7hxBtfYpt-Mooc_vmSTyzj6Q.NbeeYVy6gQPlmhoWDrZwaQ", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyR0NNIiwiYWxnIjoiQTI1NktXIn0.1ol3j_Lt0Os3UMe2Gypj0o8b77k0FSmqD7kNRNoMa9U.vZ2HMTgN2dgUd42h.JvNcy8-c8sYzOC089VtFSg2BOQx3YF8CqSTuJw.t03LRioWWKN3d7SjinU6SQ", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2R0NNIiwiYWxnIjoiQTI1NktXIn0.gbkk03l1gyrE9qGEMVtORiyyUqKsgzbqjLd8lw0RQ07WWn--TV4BgA.J8ThH4ac2UhSsMIP.g-W1piEGrdi3tNwQDJXpYm3fQjTf82mtVCrCOg.-vY05P4kiB9FgF2vwrSeXQ", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiQTI1NktXIn0.k86pQs7gmQIzuIWRFwesF32XY2xi1WbYxi7XUf_CYlOlehwGCTINHg.3NcC9VzfQgsECISKf4xy-g.v2amdo-rgeGsg-II_tvPukX9D-KAP27xxf2uQJ277Ws.E4LIE3fte3glAnPpnd8D9Q", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMTkyQ0JDLUhTMzg0IiwiYWxnIjoiQTI1NktXIn0.b8iN0Am3fCUvj7sBd7Z0lpfzBjh1MOgojV7J5rDfrcTU3b35RGYgEV1RdcrtUTBgUwITDjmU7jM.wsSDBFghDga_ERv36I2AOg.6uJsucCb2YReFOJGBdo4zidTIKLUmZBIXfm_M0AJpKk.YwdAfXI3HHcw2wLSnfCRtw4huZQtSKhz", - "eyJ6aXAiOiJERUYiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIjoiQTI1NktXIn0.akY9pHCbkHPh5VpXIrX0At41XnJIKBR9iMMkf301vKeJNAZYJTxWzeJhFd-DhQ47tMctc3YYkwZkQ5I_9fGYb_f0oBcw4esh.JNwuuHud78h6S99NO1oBQQ.0RwckPYATBgvw67upkAQ1AezETHc-gh3rryz19i5ryc.3XClRTScgzfMgLCHxHHoRF8mm9VVGXv_Ahtx65PskKQ", - }, - } - - for i, msgs := range aesSampleMessages { - for _, msg := range msgs { - obj, err := ParseEncrypted(msg) - if err != nil { - t.Error("unable to parse message", msg, err) - continue - } - plaintext, err := obj.Decrypt(aesTestKeys[i]) - if err != nil { - t.Error("unable to decrypt message", msg, err) - continue - } - if string(plaintext) != "Lorem ipsum dolor sit amet" { - t.Error("plaintext is not what we expected for msg", msg) - } - } - } -} - -// Test vectors generated with jose4j -func TestSampleJose4jJWEMessagesECDH(t *testing.T) { - ecTestKey := &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: elliptic.P256(), - X: fromBase64Int("weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ"), - Y: fromBase64Int("e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck"), - }, - D: fromBase64Int("VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw"), - } - - ecSampleMessages := []string{ - "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTEyOENCQy1IUzI1NiIsImVwayI6eyJrdHkiOiJFQyIsIngiOiJTQzAtRnJHUkVvVkpKSmg1TGhORmZqZnFXMC1XSUFyd3RZMzJzQmFQVVh3IiwieSI6ImFQMWlPRENveU9laTVyS1l2VENMNlRMZFN5UEdUN0djMnFsRnBwNXdiWFEiLCJjcnYiOiJQLTI1NiJ9fQ..3mifklTnTTGuA_etSUBBCw.dj8KFM8OlrQ3rT35nHcHZ7A5p84VB2OZb054ghSjS-M.KOIgnJjz87LGqMtikXGxXw", - "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTE5MkNCQy1IUzM4NCIsImVwayI6eyJrdHkiOiJFQyIsIngiOiJUaHRGc0lRZ1E5MkZOYWFMbUFDQURLbE93dmNGVlRORHc4ampfWlJidUxjIiwieSI6IjJmRDZ3UXc3YmpYTm1nVThXMGpFbnl5ZUZkX3Y4ZmpDa3l1R29vTFhGM0EiLCJjcnYiOiJQLTI1NiJ9fQ..90zFayMkKc-fQC_19f6P3A.P1Y_7lMnfkUQOXW_en31lKZ3zAn1nEYn6fXLjmyVPrQ.hrgwy1cePVfhMWT0h-crKTXldglHZ-4g", - "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkNCQy1IUzUxMiIsImVwayI6eyJrdHkiOiJFQyIsIngiOiI5R1Z6c3VKNWgySl96UURVUFR3WU5zUkFzVzZfY2RzN0pELVQ2RDREQ1ZVIiwieSI6InFZVGl1dVU4aTB1WFpoaS14VGlRNlZJQm5vanFoWENPVnpmWm1pR2lRTEUiLCJjcnYiOiJQLTI1NiJ9fQ..v2reRlDkIsw3eWEsTCc1NA.0qakrFdbhtBCTSl7EREf9sxgHBP9I-Xw29OTJYnrqP8.54ozViEBYYmRkcKp7d2Ztt4hzjQ9Vb5zCeijN_RQrcI", - "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiOElUemg3VVFaaUthTWtfME9qX1hFaHZENXpUWjE2Ti13WVdjeTJYUC1tdyIsInkiOiJPNUJiVEk0bUFpU005ZmpCejBRU3pXaU5vbnl3cWlQLUN0RGgwdnNGYXNRIiwiY3J2IjoiUC0yNTYifX0.D3DP3wqPvJv4TYYfhnfrOG6nsM-MMH_CqGfnOGjgdXHNF7xRwEJBOA.WL9Kz3gNYA7S5Rs5mKcXmA.EmQkXhO_nFqAwxJWaM0DH4s3pmCscZovB8YWJ3Ru4N8.Bf88uzwfxiyTjpejU5B0Ng", - "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkExOTJDQkMtSFMzODQiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiMjlJMk4zRkF0UlBlNGhzYjRLWlhTbmVyV0wyTVhtSUN1LXJJaXhNSHpJQSIsInkiOiJvMjY1bzFReEdmbDhzMHQ0U1JROS00RGNpc3otbXh4NlJ6WVF4SktyeWpJIiwiY3J2IjoiUC0yNTYifX0.DRmsmXz6fCnLc_njDIKdpM7Oc4jTqd_yd9J94TOUksAstEUkAl9Ie3Wg-Ji_LzbdX2xRLXIimcw.FwJOHPQhnqKJCfxt1_qRnQ.ssx3q1ZYILsMTln5q-K8HVn93BVPI5ViusstKMxZzRs.zzcfzWNYSdNDdQ4CiHfymj0bePaAbVaT", - "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkEyNTZDQkMtSFM1MTIiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiRUp6bTViQnRzVXJNYTl2Y1Q2d1hZRXI3ZjNMcjB0N1V4SDZuZzdGcFF0VSIsInkiOiJRYTNDSDllVTFXYjItdFdVSDN3Sk9fTDVMZXRsRUlMQWNkNE9XR2tFd0hZIiwiY3J2IjoiUC0yNTYifX0.5WxwluZpVWAOJdVrsnDIlEc4_wfRE1gXOaQyx_rKkElNz157Ykf-JsAD7aEvXfx--NKF4js5zYyjeCtxWBhRWPOoNNZJlqV_.Iuo82-qsP2S1SgQQklAnrw.H4wB6XoLKOKWCu6Y3LPAEuHkvyvr-xAh4IBm53uRF8g._fOLKq0bqDZ8KNjni_MJ4olHNaYz376dV9eNmp9O9PU", - "eyJhbGciOiJFQ0RILUVTK0ExOTJLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiZktNSG5sRkoxajBTSnJ3WGtVWlpaX3BtWHdUQlJtcHhlaTkxdUpaczUycyIsInkiOiJLRkxKaXhEUTJQcjEybWp1aFdYb3pna2U1V3lhWnhmTWlxZkJ0OEJpbkRvIiwiY3J2IjoiUC0yNTYifX0.2LSD2Mw4tyYJyfsmpVmzBtJRd12jMEYGdlhFbaXIbKi5A33CGNQ1tg.s40aAjmZOvK8Us86FCBdHg.jpYSMAKp___oMCoWM495mTfbi_YC80ObeoCmGE3H_gs.A6V-jJJRY1yz24CaXGUbzg", - "eyJhbGciOiJFQ0RILUVTK0ExOTJLVyIsImVuYyI6IkExOTJDQkMtSFMzODQiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiSDRxcFUzeWtuRktWRnV4SmxLa3NZSE5ieHF3aXM0WWtCVVFHVE1Td05JQSIsInkiOiJHb0lpRUZaUGRRSHJCbVR4ZTA3akJoZmxrdWNqUjVoX1QwNWVXc3Zib0prIiwiY3J2IjoiUC0yNTYifX0.KTrwwV2uzD--gf3PGG-kjEAGgi7u0eMqZPZfa4kpyFGm3x8t2m1NHdz3t9rfiqjuaqsxPKhF4gs.cu16fEOzYaSxhHu_Ht9w4g.BRJdxVBI9spVtY5KQ6gTR4CNcKvmLUMKZap0AO-RF2I.DZyUaa2p6YCIaYtjWOjC9GN_VIYgySlZ", - "eyJhbGciOiJFQ0RILUVTK0ExOTJLVyIsImVuYyI6IkEyNTZDQkMtSFM1MTIiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoieDBYSGRkSGM2Q0ktSnlfbUVMOEZZRExhWnV0UkVFczR4c3BMQmcwZk1jbyIsInkiOiJEa0xzOUJGTlBkTTVTNkpLYVJ3cnV1TWMwcUFzWW9yNW9fZWp6NXBNVXFrIiwiY3J2IjoiUC0yNTYifX0.mfCxJ7JYIqTMqcAh5Vp2USF0eF7OhOeluqda7YagOUJNwxA9wC9o23DSoLUylfrZUfanZrJJJcG69awlv-LY7anOLHlp3Ht5.ec48A_JWb4qa_PVHWZaTfQ.kDAjIDb3LzJpfxNh-DiAmAuaKMYaOGSTb0rkiJLuVeY.oxGCpPlii4pr89XMk4b9s084LucTqPGU6TLbOW2MZoc", - "eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkExMjhDQkMtSFMyNTYiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiQXB5TnlqU2d0bmRUcFg0eENYenNDRnZva1l3X18weXg2dGRUYzdPUUhIMCIsInkiOiJYUHdHMDVDaW1vOGlhWmxZbDNsMEp3ZllhY1FZWHFuM2RRZEJUWFpldDZBIiwiY3J2IjoiUC0yNTYifX0.yTA2PwK9IPqkaGPenZ9R-gOn9m9rvcSEfuX_Nm8AkuwHIYLzzYeAEA.ZW1F1iyHYKfo-YoanNaIVg.PouKQD94DlPA5lbpfGJXY-EJhidC7l4vSayVN2vVzvA.MexquqtGaXKUvX7WBmD4bA", - "eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkExOTJDQkMtSFMzODQiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiaDRWeGNzNVUzWk1fTlp4WmJxQ3hMTVB5UmEtR2ktSVNZa0xDTzE1RHJkZyIsInkiOiJFeVotS3dWNVE5OXlnWk5zU0lpSldpR3hqbXNLUk1WVE5sTTNSd1VYTFRvIiwiY3J2IjoiUC0yNTYifX0.wo56VISyL1QAbi2HLuVut5NGF2FvxKt7B8zHzJ3FpmavPozfbVZV08-GSYQ6jLQWJ4xsO80I4Kg.3_9Bo5ozvD96WHGhqp_tfQ.48UkJ6jk6WK70QItb2QZr0edKH7O-aMuVahTEeqyfW4.ulMlY2tbC341ct20YSmNdtc84FRz1I4g", - "eyJhbGciOiJFQ0RILUVTK0ExMjhLVyIsImVuYyI6IkEyNTZDQkMtSFM1MTIiLCJlcGsiOnsia3R5IjoiRUMiLCJ4IjoiN0xZRzZZWTJkel9ZaGNvNnRCcG1IX0tPREQ2X2hwX05tajdEc1c2RXgxcyIsInkiOiI5Y2lPeDcwUkdGT0tpVnBRX0NHQXB5NVlyeThDazBmUkpwNHVrQ2tjNmQ0IiwiY3J2IjoiUC0yNTYifX0.bWwW3J80k46HG1fQAZxUroko2OO8OKkeRavr_o3AnhJDMvp78OR229x-fZUaBm4uWv27_Yjm0X9T2H2lhlIli2Rl9v1PNC77.1NmsJBDGI1fDjRzyc4mtyA.9KfCFynQj7LmJq08qxAG4c-6ZPz1Lh3h3nUbgVwB0TI.cqech0d8XHzWfkWqgKZq1SlAfmO0PUwOsNVkuByVGWk", - } - - for _, msg := range ecSampleMessages { - obj, err := ParseEncrypted(msg) - if err != nil { - t.Error("unable to parse message", msg, err) - continue - } - plaintext, err := obj.Decrypt(ecTestKey) - if err != nil { - t.Error("unable to decrypt message", msg, err) - continue - } - if string(plaintext) != "Lorem ipsum dolor sit amet." { - t.Error("plaintext is not what we expected for msg", msg) - } - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/jwk_test.go b/vendor/gopkg.in/square/go-jose.v2/jwk_test.go deleted file mode 100644 index b7d48ec873..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/jwk_test.go +++ /dev/null @@ -1,715 +0,0 @@ -/*- - * Copyright 2014 Square 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 jose - -import ( - "bytes" - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "crypto/x509" - "encoding/hex" - "math/big" - "reflect" - "testing" - - "golang.org/x/crypto/ed25519" - - "gopkg.in/square/go-jose.v2/json" -) - -// Test chain of two X.509 certificates -var testCertificates, _ = x509.ParseCertificates(fromBase64Bytes(` -MIIDfDCCAmSgAwIBAgIJANWAkzF7PA8/MA0GCSqGSIb3DQEBCwUAMFUxCzAJ -BgNVBAYTAlVTMQswCQYDVQQIEwJDQTEQMA4GA1UEChMHY2VydGlnbzEQMA4G -A1UECxMHZXhhbXBsZTEVMBMGA1UEAxMMZXhhbXBsZS1sZWFmMB4XDTE2MDYx -MDIyMTQxMVoXDTIzMDQxNTIyMTQxMVowVTELMAkGA1UEBhMCVVMxCzAJBgNV -BAgTAkNBMRAwDgYDVQQKEwdjZXJ0aWdvMRAwDgYDVQQLEwdleGFtcGxlMRUw -EwYDVQQDEwxleGFtcGxlLWxlYWYwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw -ggEKAoIBAQC7stSvfQyGuHw3v34fisqIdDXberrFoFk9ht/WdXgYzX2uLNKd -sR/J5sbWSl8K/5djpzj31eIzqU69w8v7SChM5x9bouDsABHz3kZucx5cSafE -gJojysBkcrq3VY+aJanzbL+qErYX+lhRpPcZK6JMWIwar8Y3B2la4yWwieec -w2/WfEVvG0M/DOYKnR8QHFsfl3US1dnBM84czKPyt9r40gDk2XiH/lGts5a9 -4rAGvbr8IMCtq0mA5aH3Fx3mDSi3+4MZwygCAHrF5O5iSV9rEI+m2+7j2S+j -HDUnvV+nqcpb9m6ENECnYX8FD2KcqlOjTmw8smDy09N2Np6i464lAgMBAAGj -TzBNMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATAsBgNVHREEJTAj -hwR/AAABhxAAAAAAAAAAAAAAAAAAAAABgglsb2NhbGhvc3QwDQYJKoZIhvcN -AQELBQADggEBAGM4aa/qrURUweZBIwZYv8O9b2+r4l0HjGAh982/B9sMlM05 -kojyDCUGvj86z18Lm8mKr4/y+i0nJ+vDIksEvfDuzw5ALAXGcBzPJKtICUf7 -LstA/n9NNpshWz0kld9ylnB5mbUzSFDncVyeXkEf5sGQXdIIZT9ChRBoiloS -aa7dvBVCcsX1LGP2LWqKtD+7nUnw5qCwtyAVT8pthEUxFTpywoiJS5ZdzeEx -8MNGvUeLFj2kleqPF78EioEQlSOxViCuctEtnQuPcDLHNFr10byTZY9roObi -qdsJLMVvb2XliJjAqaPa9AkYwGE6xHw2ispwg64Rse0+AtKups19WIUwggNT -MIICO6ADAgECAgkAqD4tCWKt9/AwDQYJKoZIhvcNAQELBQAwVTELMAkGA1UE -BhMCVVMxCzAJBgNVBAgTAkNBMRAwDgYDVQQKEwdjZXJ0aWdvMRAwDgYDVQQL -EwdleGFtcGxlMRUwEwYDVQQDEwxleGFtcGxlLXJvb3QwHhcNMTYwNjEwMjIx -NDExWhcNMjMwNDE1MjIxNDExWjBVMQswCQYDVQQGEwJVUzELMAkGA1UECBMC -Q0ExEDAOBgNVBAoTB2NlcnRpZ28xEDAOBgNVBAsTB2V4YW1wbGUxFTATBgNV -BAMTDGV4YW1wbGUtcm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC -ggEBAMo4ShKI2MxDz/NQVxBbz0tbD5R5NcobA0NKkaPKLyMEpnWVY9ucyauM -joNn1F568cfOoF0pm3700U8UTPt2MMxEHIi4mFG/OF8UF+Voh1J42Tb42lRo -W5RRR3ogh4+7QB1G94nxkYddHAJ4QMhUJlLigFg8c6Ff/MxYODy9I7ilLFOM -Zzsjx8fFpRKRXNQFt471P/V4WTSba7GzdTOJRyTZf/xipF36n8RoEQPvyde8 -pEAsCC4oDOrEiCTdxw8rRJVAU0Wr55XX+qjxyi55C6oykIC/BWR+lUqGd7IL -Y2Uyt/OVxllt8b+KuVKNCfn4TFlfgizLWkJRs6JV9KuwJ20CAwEAAaMmMCQw -DgYDVR0PAQH/BAQDAgIEMBIGA1UdEwEB/wQIMAYBAf8CAQAwDQYJKoZIhvcN -AQELBQADggEBAIsQlTrm9NT6gts0cs4JHp8AutuMrvGyLpIUOlJcEybvgxaz -LebIMGZek5w3yEJiCyCK9RdNDP3Kdc/+nM6PhvzfPOVo58+0tMCYyEpZVXhD -zmasNDP4fMbiUpczvx5OwPw/KuhwD+1ITuZUQnQlqXgTYoj9n39+qlgUsHos -WXHmfzd6Fcz96ADSXg54IL2cEoJ41Q3ewhA7zmWWPLMAl21aex2haiAmzqqN -xXyfZTnGNnE3lkV1yVguOrqDZyMRdcxDFvxvtmEeMtYV2Mc/zlS9ccrcOkrc -mZSDxthLu3UMl98NA2NrCGWwzJwpk36vQ0PRSbibsCMarFspP8zbIoU=`)) - -func TestCurveSize(t *testing.T) { - size256 := curveSize(elliptic.P256()) - size384 := curveSize(elliptic.P384()) - size521 := curveSize(elliptic.P521()) - if size256 != 32 { - t.Error("P-256 have 32 bytes") - } - if size384 != 48 { - t.Error("P-384 have 48 bytes") - } - if size521 != 66 { - t.Error("P-521 have 66 bytes") - } -} - -func TestRoundtripRsaPrivate(t *testing.T) { - jwk, err := fromRsaPrivateKey(rsaTestKey) - if err != nil { - t.Error("problem constructing JWK from rsa key", err) - } - - rsa2, err := jwk.rsaPrivateKey() - if err != nil { - t.Error("problem converting RSA private -> JWK", err) - } - - if rsa2.N.Cmp(rsaTestKey.N) != 0 { - t.Error("RSA private N mismatch") - } - if rsa2.E != rsaTestKey.E { - t.Error("RSA private E mismatch") - } - if rsa2.D.Cmp(rsaTestKey.D) != 0 { - t.Error("RSA private D mismatch") - } - if len(rsa2.Primes) != 2 { - t.Error("RSA private roundtrip expected two primes") - } - if rsa2.Primes[0].Cmp(rsaTestKey.Primes[0]) != 0 { - t.Error("RSA private P mismatch") - } - if rsa2.Primes[1].Cmp(rsaTestKey.Primes[1]) != 0 { - t.Error("RSA private Q mismatch") - } -} - -func TestRsaPrivateInsufficientPrimes(t *testing.T) { - brokenRsaPrivateKey := rsa.PrivateKey{ - PublicKey: rsa.PublicKey{ - N: rsaTestKey.N, - E: rsaTestKey.E, - }, - D: rsaTestKey.D, - Primes: []*big.Int{rsaTestKey.Primes[0]}, - } - - _, err := fromRsaPrivateKey(&brokenRsaPrivateKey) - if err != ErrUnsupportedKeyType { - t.Error("expected unsupported key type error, got", err) - } -} - -func TestRsaPrivateExcessPrimes(t *testing.T) { - brokenRsaPrivateKey := rsa.PrivateKey{ - PublicKey: rsa.PublicKey{ - N: rsaTestKey.N, - E: rsaTestKey.E, - }, - D: rsaTestKey.D, - Primes: []*big.Int{ - rsaTestKey.Primes[0], - rsaTestKey.Primes[1], - big.NewInt(3), - }, - } - - _, err := fromRsaPrivateKey(&brokenRsaPrivateKey) - if err != ErrUnsupportedKeyType { - t.Error("expected unsupported key type error, got", err) - } -} - -func TestRoundtripEcPublic(t *testing.T) { - for i, ecTestKey := range []*ecdsa.PrivateKey{ecTestKey256, ecTestKey384, ecTestKey521} { - jwk, err := fromEcPublicKey(&ecTestKey.PublicKey) - - ec2, err := jwk.ecPublicKey() - if err != nil { - t.Error("problem converting ECDSA private -> JWK", i, err) - } - - if !reflect.DeepEqual(ec2.Curve, ecTestKey.Curve) { - t.Error("ECDSA private curve mismatch", i) - } - if ec2.X.Cmp(ecTestKey.X) != 0 { - t.Error("ECDSA X mismatch", i) - } - if ec2.Y.Cmp(ecTestKey.Y) != 0 { - t.Error("ECDSA Y mismatch", i) - } - } -} - -func TestRoundtripEcPrivate(t *testing.T) { - for i, ecTestKey := range []*ecdsa.PrivateKey{ecTestKey256, ecTestKey384, ecTestKey521} { - jwk, err := fromEcPrivateKey(ecTestKey) - - ec2, err := jwk.ecPrivateKey() - if err != nil { - t.Error("problem converting ECDSA private -> JWK", i, err) - } - - if !reflect.DeepEqual(ec2.Curve, ecTestKey.Curve) { - t.Error("ECDSA private curve mismatch", i) - } - if ec2.X.Cmp(ecTestKey.X) != 0 { - t.Error("ECDSA X mismatch", i) - } - if ec2.Y.Cmp(ecTestKey.Y) != 0 { - t.Error("ECDSA Y mismatch", i) - } - if ec2.D.Cmp(ecTestKey.D) != 0 { - t.Error("ECDSA D mismatch", i) - } - } -} - -func TestRoundtripX5C(t *testing.T) { - jwk := JSONWebKey{ - Key: rsaTestKey, - KeyID: "bar", - Algorithm: "foo", - Certificates: testCertificates, - } - - jsonbar, err := jwk.MarshalJSON() - if err != nil { - t.Error("problem marshaling", err) - } - - var jwk2 JSONWebKey - err = jwk2.UnmarshalJSON(jsonbar) - if err != nil { - t.Error("problem unmarshalling", err) - } - - if !reflect.DeepEqual(testCertificates, jwk2.Certificates) { - t.Error("Certificates not equal", jwk.Certificates, jwk2.Certificates) - } - - jsonbar2, err := jwk2.MarshalJSON() - if err != nil { - t.Error("problem marshaling", err) - } - if !bytes.Equal(jsonbar, jsonbar2) { - t.Error("roundtrip should not lose information") - } -} - -func TestMarshalUnmarshal(t *testing.T) { - kid := "DEADBEEF" - - for i, key := range []interface{}{ecTestKey256, ecTestKey384, ecTestKey521, rsaTestKey, ed25519PrivateKey} { - for _, use := range []string{"", "sig", "enc"} { - jwk := JSONWebKey{Key: key, KeyID: kid, Algorithm: "foo"} - if use != "" { - jwk.Use = use - } - - jsonbar, err := jwk.MarshalJSON() - if err != nil { - t.Error("problem marshaling", i, err) - } - - var jwk2 JSONWebKey - err = jwk2.UnmarshalJSON(jsonbar) - if err != nil { - t.Error("problem unmarshalling", i, err) - } - - jsonbar2, err := jwk2.MarshalJSON() - if err != nil { - t.Error("problem marshaling", i, err) - } - - if !bytes.Equal(jsonbar, jsonbar2) { - t.Error("roundtrip should not lose information", i) - } - if jwk2.KeyID != kid { - t.Error("kid did not roundtrip JSON marshalling", i) - } - - if jwk2.Algorithm != "foo" { - t.Error("alg did not roundtrip JSON marshalling", i) - } - - if jwk2.Use != use { - t.Error("use did not roundtrip JSON marshalling", i) - } - } - } -} - -func TestMarshalNonPointer(t *testing.T) { - type EmbedsKey struct { - Key JSONWebKey - } - - keyJSON := []byte(`{ - "e": "AQAB", - "kty": "RSA", - "n": "vd7rZIoTLEe-z1_8G1FcXSw9CQFEJgV4g9V277sER7yx5Qjz_Pkf2YVth6wwwFJEmzc0hoKY-MMYFNwBE4hQHw" - }`) - var parsedKey JSONWebKey - err := json.Unmarshal(keyJSON, &parsedKey) - if err != nil { - t.Errorf("Error unmarshalling key: %v", err) - return - } - ek := EmbedsKey{ - Key: parsedKey, - } - out, err := json.Marshal(ek) - if err != nil { - t.Errorf("Error marshalling JSON: %v", err) - return - } - expected := "{\"Key\":{\"kty\":\"RSA\",\"n\":\"vd7rZIoTLEe-z1_8G1FcXSw9CQFEJgV4g9V277sER7yx5Qjz_Pkf2YVth6wwwFJEmzc0hoKY-MMYFNwBE4hQHw\",\"e\":\"AQAB\"}}" - if string(out) != expected { - t.Error("Failed to marshal embedded non-pointer JWK properly:", string(out)) - } -} - -func TestMarshalUnmarshalInvalid(t *testing.T) { - // Make an invalid curve coordinate by creating a byte array that is one - // byte too large, and setting the first byte to 1 (otherwise it's just zero). - invalidCoord := make([]byte, curveSize(ecTestKey256.Curve)+1) - invalidCoord[0] = 1 - - keys := []interface{}{ - // Empty keys - &rsa.PrivateKey{}, - &ecdsa.PrivateKey{}, - // Invalid keys - &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - // Missing values in pub key - Curve: elliptic.P256(), - }, - }, - &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - // Invalid curve - Curve: nil, - X: ecTestKey256.X, - Y: ecTestKey256.Y, - }, - }, - &ecdsa.PrivateKey{ - // Valid pub key, but missing priv key values - PublicKey: ecTestKey256.PublicKey, - }, - &ecdsa.PrivateKey{ - // Invalid pub key, values too large - PublicKey: ecdsa.PublicKey{ - Curve: ecTestKey256.Curve, - X: big.NewInt(0).SetBytes(invalidCoord), - Y: big.NewInt(0).SetBytes(invalidCoord), - }, - D: ecTestKey256.D, - }, - nil, - } - - for i, key := range keys { - jwk := JSONWebKey{Key: key} - _, err := jwk.MarshalJSON() - if err == nil { - t.Error("managed to serialize invalid key", i) - } - } -} - -func TestWebKeyVectorsInvalid(t *testing.T) { - keys := []string{ - // Invalid JSON - "{X", - // Empty key - "{}", - // Invalid RSA keys - `{"kty":"RSA"}`, - `{"kty":"RSA","e":""}`, - `{"kty":"RSA","e":"XXXX"}`, - `{"kty":"RSA","d":"XXXX"}`, - // Invalid EC keys - `{"kty":"EC","crv":"ABC"}`, - `{"kty":"EC","crv":"P-256"}`, - `{"kty":"EC","crv":"P-256","d":"XXX"}`, - `{"kty":"EC","crv":"ABC","d":"dGVzdA","x":"dGVzdA"}`, - `{"kty":"EC","crv":"P-256","d":"dGVzdA","x":"dGVzdA"}`, - } - - for _, key := range keys { - var jwk2 JSONWebKey - err := jwk2.UnmarshalJSON([]byte(key)) - if err == nil { - t.Error("managed to parse invalid key:", key) - } - } -} - -// Test vectors from RFC 7520 -var cookbookJWKs = []string{ - // EC Public - stripWhitespace(`{ - "kty": "EC", - "kid": "bilbo.baggins@hobbiton.example", - "use": "sig", - "crv": "P-521", - "x": "AHKZLLOsCOzz5cY97ewNUajB957y-C-U88c3v13nmGZx6sYl_oJXu9 - A5RkTKqjqvjyekWF-7ytDyRXYgCF5cj0Kt", - "y": "AdymlHvOiLxXkEhayXQnNCvDX4h9htZaCJN34kfmC6pV5OhQHiraVy - SsUdaQkAgDPrwQrJmbnX9cwlGfP-HqHZR1" - }`), - - //ED Private - stripWhitespace(`{ - "kty": "OKP", - "crv": "Ed25519", - "d": "nWGxne_9WmC6hEr0kuwsxERJxWl7MmkZcDusAxyuf2A", - "x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo" - }`), - - // EC Private - stripWhitespace(`{ - "kty": "EC", - "kid": "bilbo.baggins@hobbiton.example", - "use": "sig", - "crv": "P-521", - "x": "AHKZLLOsCOzz5cY97ewNUajB957y-C-U88c3v13nmGZx6sYl_oJXu9 - A5RkTKqjqvjyekWF-7ytDyRXYgCF5cj0Kt", - "y": "AdymlHvOiLxXkEhayXQnNCvDX4h9htZaCJN34kfmC6pV5OhQHiraVy - SsUdaQkAgDPrwQrJmbnX9cwlGfP-HqHZR1", - "d": "AAhRON2r9cqXX1hg-RoI6R1tX5p2rUAYdmpHZoC1XNM56KtscrX6zb - KipQrCW9CGZH3T4ubpnoTKLDYJ_fF3_rJt" - }`), - - // RSA Public - stripWhitespace(`{ - "kty": "RSA", - "kid": "bilbo.baggins@hobbiton.example", - "use": "sig", - "n": "n4EPtAOCc9AlkeQHPzHStgAbgs7bTZLwUBZdR8_KuKPEHLd4rHVTeT - -O-XV2jRojdNhxJWTDvNd7nqQ0VEiZQHz_AJmSCpMaJMRBSFKrKb2wqV - wGU_NsYOYL-QtiWN2lbzcEe6XC0dApr5ydQLrHqkHHig3RBordaZ6Aj- - oBHqFEHYpPe7Tpe-OfVfHd1E6cS6M1FZcD1NNLYD5lFHpPI9bTwJlsde - 3uhGqC0ZCuEHg8lhzwOHrtIQbS0FVbb9k3-tVTU4fg_3L_vniUFAKwuC - LqKnS2BYwdq_mzSnbLY7h_qixoR7jig3__kRhuaxwUkRz5iaiQkqgc5g - HdrNP5zw", - "e": "AQAB" - }`), - - // RSA Private - stripWhitespace(`{"kty":"RSA", - "kid":"juliet@capulet.lit", - "use":"enc", - "n":"t6Q8PWSi1dkJj9hTP8hNYFlvadM7DflW9mWepOJhJ66w7nyoK1gPNqFMSQRy - O125Gp-TEkodhWr0iujjHVx7BcV0llS4w5ACGgPrcAd6ZcSR0-Iqom-QFcNP - 8Sjg086MwoqQU_LYywlAGZ21WSdS_PERyGFiNnj3QQlO8Yns5jCtLCRwLHL0 - Pb1fEv45AuRIuUfVcPySBWYnDyGxvjYGDSM-AqWS9zIQ2ZilgT-GqUmipg0X - OC0Cc20rgLe2ymLHjpHciCKVAbY5-L32-lSeZO-Os6U15_aXrk9Gw8cPUaX1 - _I8sLGuSiVdt3C_Fn2PZ3Z8i744FPFGGcG1qs2Wz-Q", - "e":"AQAB", - "d":"GRtbIQmhOZtyszfgKdg4u_N-R_mZGU_9k7JQ_jn1DnfTuMdSNprTeaSTyWfS - NkuaAwnOEbIQVy1IQbWVV25NY3ybc_IhUJtfri7bAXYEReWaCl3hdlPKXy9U - vqPYGR0kIXTQRqns-dVJ7jahlI7LyckrpTmrM8dWBo4_PMaenNnPiQgO0xnu - ToxutRZJfJvG4Ox4ka3GORQd9CsCZ2vsUDmsXOfUENOyMqADC6p1M3h33tsu - rY15k9qMSpG9OX_IJAXmxzAh_tWiZOwk2K4yxH9tS3Lq1yX8C1EWmeRDkK2a - hecG85-oLKQt5VEpWHKmjOi_gJSdSgqcN96X52esAQ", - "p":"2rnSOV4hKSN8sS4CgcQHFbs08XboFDqKum3sc4h3GRxrTmQdl1ZK9uw-PIHf - QP0FkxXVrx-WE-ZEbrqivH_2iCLUS7wAl6XvARt1KkIaUxPPSYB9yk31s0Q8 - UK96E3_OrADAYtAJs-M3JxCLfNgqh56HDnETTQhH3rCT5T3yJws", - "q":"1u_RiFDP7LBYh3N4GXLT9OpSKYP0uQZyiaZwBtOCBNJgQxaj10RWjsZu0c6I - edis4S7B_coSKB0Kj9PaPaBzg-IySRvvcQuPamQu66riMhjVtG6TlV8CLCYK - rYl52ziqK0E_ym2QnkwsUX7eYTB7LbAHRK9GqocDE5B0f808I4s", - "dp":"KkMTWqBUefVwZ2_Dbj1pPQqyHSHjj90L5x_MOzqYAJMcLMZtbUtwKqvVDq3 - tbEo3ZIcohbDtt6SbfmWzggabpQxNxuBpoOOf_a_HgMXK_lhqigI4y_kqS1w - Y52IwjUn5rgRrJ-yYo1h41KR-vz2pYhEAeYrhttWtxVqLCRViD6c", - "dq":"AvfS0-gRxvn0bwJoMSnFxYcK1WnuEjQFluMGfwGitQBWtfZ1Er7t1xDkbN9 - GQTB9yqpDoYaN06H7CFtrkxhJIBQaj6nkF5KKS3TQtQ5qCzkOkmxIe3KRbBy - mXxkb5qwUpX5ELD5xFc6FeiafWYY63TmmEAu_lRFCOJ3xDea-ots", - "qi":"lSQi-w9CpyUReMErP1RsBLk7wNtOvs5EQpPqmuMvqW57NBUczScEoPwmUqq - abu9V0-Py4dQ57_bapoKRu1R90bvuFnU63SHWEFglZQvJDMeAvmj4sm-Fp0o - Yu_neotgQ0hzbI5gry7ajdYy9-2lNx_76aBZoOUu9HCJ-UsfSOI8"}`), - - // X.509 Certificate Chain - stripWhitespace(`{"kty":"RSA", - "use":"sig", - "kid":"1b94c", - "n":"vrjOfz9Ccdgx5nQudyhdoR17V-IubWMeOZCwX_jj0hgAsz2J_pqYW08 - PLbK_PdiVGKPrqzmDIsLI7sA25VEnHU1uCLNwBuUiCO11_-7dYbsr4iJmG0Q - u2j8DsVyT1azpJC_NG84Ty5KKthuCaPod7iI7w0LK9orSMhBEwwZDCxTWq4a - YWAchc8t-emd9qOvWtVMDC2BXksRngh6X5bUYLy6AyHKvj-nUy1wgzjYQDwH - MTplCoLtU-o-8SNnZ1tmRoGE9uJkBLdh5gFENabWnU5m1ZqZPdwS-qo-meMv - VfJb6jJVWRpl2SUtCnYG2C32qvbWbjZ_jBPD5eunqsIo1vQ", - "e":"AQAB", - "x5c": - ["MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQEBBQUAMGIxCzAJB - gNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYD - VQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1 - wYmVsbDAeFw0xMzAyMjEyMzI5MTVaFw0xODA4MTQyMjI5MTVaMGIxCzAJBg - NVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRwwGgYDV - QQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5CcmlhbiBDYW1w - YmVsbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL64zn8/QnH - YMeZ0LncoXaEde1fiLm1jHjmQsF/449IYALM9if6amFtPDy2yvz3YlRij66 - s5gyLCyO7ANuVRJx1NbgizcAblIgjtdf/u3WG7K+IiZhtELto/A7Fck9Ws6 - SQvzRvOE8uSirYbgmj6He4iO8NCyvaK0jIQRMMGQwsU1quGmFgHIXPLfnpn - fajr1rVTAwtgV5LEZ4Iel+W1GC8ugMhyr4/p1MtcIM42EA8BzE6ZQqC7VPq - PvEjZ2dbZkaBhPbiZAS3YeYBRDWm1p1OZtWamT3cEvqqPpnjL1XyW+oyVVk - aZdklLQp2Btgt9qr21m42f4wTw+Xrp6rCKNb0CAwEAATANBgkqhkiG9w0BA - QUFAAOCAQEAh8zGlfSlcI0o3rYDPBB07aXNswb4ECNIKG0CETTUxmXl9KUL - +9gGlqCz5iWLOgWsnrcKcY0vXPG9J1r9AqBNTqNgHq2G03X09266X5CpOe1 - zFo+Owb1zxtp3PehFdfQJ610CDLEaS9V9Rqp17hCyybEpOGVwe8fnk+fbEL - 2Bo3UPGrpsHzUoaGpDftmWssZkhpBJKVMJyf/RuP2SmmaIzmnw9JiSlYhzo - 4tpzd5rFXhjRbg4zW9C+2qok+2+qDM1iJ684gPHMIY8aLWrdgQTxkumGmTq - gawR+N5MDtdPTEQ0XfIBc2cJEUyMTY5MPvACWpkA6SdS4xSvdXK3IVfOWA=="]}`), -} - -// SHA-256 thumbprints of the above keys, hex-encoded -var cookbookJWKThumbprints = []string{ - "747ae2dd2003664aeeb21e4753fe7402846170a16bc8df8f23a8cf06d3cbe793", - "f6934029a341ddf81dceb753e91d17efe16664f40d9f4ed84bc5ea87e111f29d", - "747ae2dd2003664aeeb21e4753fe7402846170a16bc8df8f23a8cf06d3cbe793", - "f63838e96077ad1fc01c3f8405774dedc0641f558ebb4b40dccf5f9b6d66a932", - "0fc478f8579325fcee0d4cbc6d9d1ce21730a6e97e435d6008fb379b0ebe47d4", - "0ddb05bfedbec2070fa037324ba397396561d3425d6d69245570c261dc49dee3", -} - -func TestWebKeyVectorsValid(t *testing.T) { - for _, key := range cookbookJWKs { - var jwk2 JSONWebKey - err := jwk2.UnmarshalJSON([]byte(key)) - if err != nil { - t.Error("unable to parse valid key:", key, err) - } - } -} - -func TestThumbprint(t *testing.T) { - for i, key := range cookbookJWKs { - var jwk2 JSONWebKey - err := jwk2.UnmarshalJSON([]byte(key)) - if err != nil { - t.Error("unable to parse valid key:", key, err) - } - - tp, err := jwk2.Thumbprint(crypto.SHA256) - if err != nil { - t.Error("unable to compute thumbprint:", key, err) - } - - tpHex := hex.EncodeToString(tp) - if cookbookJWKThumbprints[i] != tpHex { - t.Error("incorrect thumbprint:", i, cookbookJWKThumbprints[i], tpHex) - } - } -} - -func TestMarshalUnmarshalJWKSet(t *testing.T) { - jwk1 := JSONWebKey{Key: rsaTestKey, KeyID: "ABCDEFG", Algorithm: "foo"} - jwk2 := JSONWebKey{Key: rsaTestKey, KeyID: "GFEDCBA", Algorithm: "foo"} - var set JSONWebKeySet - set.Keys = append(set.Keys, jwk1) - set.Keys = append(set.Keys, jwk2) - - jsonbar, err := json.Marshal(&set) - if err != nil { - t.Error("problem marshalling set", err) - } - var set2 JSONWebKeySet - err = json.Unmarshal(jsonbar, &set2) - if err != nil { - t.Error("problem unmarshalling set", err) - } - jsonbar2, err := json.Marshal(&set2) - if err != nil { - t.Error("problem marshalling set", err) - } - if !bytes.Equal(jsonbar, jsonbar2) { - t.Error("roundtrip should not lose information") - } -} - -func TestJWKSetKey(t *testing.T) { - jwk1 := JSONWebKey{Key: rsaTestKey, KeyID: "ABCDEFG", Algorithm: "foo"} - jwk2 := JSONWebKey{Key: rsaTestKey, KeyID: "GFEDCBA", Algorithm: "foo"} - var set JSONWebKeySet - set.Keys = append(set.Keys, jwk1) - set.Keys = append(set.Keys, jwk2) - k := set.Key("ABCDEFG") - if len(k) != 1 { - t.Errorf("method should return slice with one key not %d", len(k)) - } - if k[0].KeyID != "ABCDEFG" { - t.Error("method should return key with ID ABCDEFG") - } -} - -func TestJWKSymmetricKey(t *testing.T) { - sample1 := `{"kty":"oct","alg":"A128KW","k":"GawgguFyGrWKav7AX4VKUg"}` - sample2 := `{"kty":"oct","k":"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow","kid":"HMAC key used in JWS spec Appendix A.1 example"}` - - var jwk1 JSONWebKey - json.Unmarshal([]byte(sample1), &jwk1) - - if jwk1.Algorithm != "A128KW" { - t.Errorf("expected Algorithm to be A128KW, but was '%s'", jwk1.Algorithm) - } - expected1 := fromHexBytes("19ac2082e1721ab58a6afec05f854a52") - if !bytes.Equal(jwk1.Key.([]byte), expected1) { - t.Errorf("expected Key to be '%s', but was '%s'", hex.EncodeToString(expected1), hex.EncodeToString(jwk1.Key.([]byte))) - } - - var jwk2 JSONWebKey - json.Unmarshal([]byte(sample2), &jwk2) - - if jwk2.KeyID != "HMAC key used in JWS spec Appendix A.1 example" { - t.Errorf("expected KeyID to be 'HMAC key used in JWS spec Appendix A.1 example', but was '%s'", jwk2.KeyID) - } - expected2 := fromHexBytes(` - 0323354b2b0fa5bc837e0665777ba68f5ab328e6f054c928a90f84b2d2502ebf - d3fb5a92d20647ef968ab4c377623d223d2e2172052e4f08c0cd9af567d080a3`) - if !bytes.Equal(jwk2.Key.([]byte), expected2) { - t.Errorf("expected Key to be '%s', but was '%s'", hex.EncodeToString(expected2), hex.EncodeToString(jwk2.Key.([]byte))) - } -} - -func TestJWKSymmetricRoundtrip(t *testing.T) { - jwk1 := JSONWebKey{Key: []byte{1, 2, 3, 4}} - marshaled, err := jwk1.MarshalJSON() - if err != nil { - t.Error("failed to marshal valid JWK object", err) - } - - var jwk2 JSONWebKey - err = jwk2.UnmarshalJSON(marshaled) - if err != nil { - t.Error("failed to unmarshal valid JWK object", err) - } - - if !bytes.Equal(jwk1.Key.([]byte), jwk2.Key.([]byte)) { - t.Error("round-trip of symmetric JWK gave different raw keys") - } -} - -func TestJWKSymmetricInvalid(t *testing.T) { - invalid := JSONWebKey{} - _, err := invalid.MarshalJSON() - if err == nil { - t.Error("excepted error on marshaling invalid symmetric JWK object") - } - - var jwk JSONWebKey - err = jwk.UnmarshalJSON([]byte(`{"kty":"oct"}`)) - if err == nil { - t.Error("excepted error on unmarshaling invalid symmetric JWK object") - } -} - -func TestJWKIsPublic(t *testing.T) { - bigInt := big.NewInt(0) - eccPub := ecdsa.PublicKey{elliptic.P256(), bigInt, bigInt} - rsaPub := rsa.PublicKey{bigInt, 1} - - cases := []struct { - key interface{} - expectedIsPublic bool - }{ - {&eccPub, true}, - {&ecdsa.PrivateKey{eccPub, bigInt}, false}, - {&rsaPub, true}, - {&rsa.PrivateKey{rsaPub, bigInt, []*big.Int{bigInt, bigInt}, rsa.PrecomputedValues{}}, false}, - {ed25519PublicKey, true}, - {ed25519PrivateKey, false}, - } - - for _, tc := range cases { - k := &JSONWebKey{Key: tc.key} - if public := k.IsPublic(); public != tc.expectedIsPublic { - t.Errorf("expected IsPublic to return %t, got %t", tc.expectedIsPublic, public) - } - } -} - -func TestJWKValid(t *testing.T) { - bigInt := big.NewInt(0) - eccPub := ecdsa.PublicKey{elliptic.P256(), bigInt, bigInt} - rsaPub := rsa.PublicKey{bigInt, 1} - edPubEmpty := ed25519.PublicKey([]byte{}) - edPrivEmpty := ed25519.PublicKey([]byte{}) - - cases := []struct { - key interface{} - expectedValidity bool - }{ - {nil, false}, - {&ecdsa.PublicKey{}, false}, - {&eccPub, true}, - {&ecdsa.PrivateKey{}, false}, - {&ecdsa.PrivateKey{eccPub, bigInt}, true}, - {&rsa.PublicKey{}, false}, - {&rsaPub, true}, - {&rsa.PrivateKey{}, false}, - {&rsa.PrivateKey{rsaPub, bigInt, []*big.Int{bigInt, bigInt}, rsa.PrecomputedValues{}}, true}, - {ed25519PublicKey, true}, - {ed25519PrivateKey, true}, - {edPubEmpty, false}, - {edPrivEmpty, false}, - } - - for _, tc := range cases { - k := &JSONWebKey{Key: tc.key} - valid := k.Valid() - if valid != tc.expectedValidity { - t.Errorf("expected Valid to return %t, got %t", tc.expectedValidity, valid) - } - if valid { - wasPublic := k.IsPublic() - p := k.Public() // all aforemention keys are asymmetric - if !p.Valid() { - t.Errorf("unable to derive public key from valid asymmetric key") - } - if wasPublic != k.IsPublic() { - t.Errorf("original key was touched during public key derivation") - } - } - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/jws_test.go b/vendor/gopkg.in/square/go-jose.v2/jws_test.go deleted file mode 100644 index 1b80419ddd..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/jws_test.go +++ /dev/null @@ -1,616 +0,0 @@ -/*- - * Copyright 2014 Square 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 jose - -import ( - "crypto/x509" - "strings" - "testing" -) - -const trustedCA = ` ------BEGIN CERTIFICATE----- -MIIE6DCCAtCgAwIBAgIBATANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDEwlUcnVz -dGVkQ0EwHhcNMTgwMzI4MTg0MzA0WhcNMzgwMzI4MTg0MzA0WjAUMRIwEAYDVQQD -EwlUcnVzdGVkQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCsHcd3 -uaKBilWQUe2epNf86xvq2HZV+JDULjJlKfUQAkpG+huHDEMiPEFPSlQK17bFj7gc -qOx/INeeCU2nBVtZDtlm3U0jfQWO2F2kZgH1JWnEArrAWWy3BP/NYv7apBLcl7nD -hkL4USVUnXF8mtuegiSMI2YT7TVchGzYMjrj/j+oRuDm1GF1OxoIMeUuVmqyJ6jK -Kxv9YVmCB+e/QaUltkPGwxl2dKWdBwECXDgSr7hcZhT8ANmgFR1dJjLCy0Us12yw -5eKUANDlfNP+z9urykoAwHXpBlmga1ze45aL+p+7K+8sl/PgMqKO7VdT5GBsOCzf -xaBDG5Qy92Di34Sc27ZZz0mfaIy5kySnceBclMyWb8vdhEGkyHVsGpWc63JBmtg+ -bKeh876m7KVLfiykfpMqHUhq/ImQwiQTwX2RonFK5gP+XU0I9V+4rE0iqucbcvCS -HuHzhf6B+TybhalRsvOZ6GB/SokF5YCmf8ylAq4be/HSxnJQcBhpSSQp0zz4ZKOD -ikXuwf29yhWZ0lgIyaZpT9H4QecWNcyx4UcqO3wQAGjxadTG3gzjLu/OJwPkw+bK -RvXWSBZjlQ9+JPmrHH+oKMgHshR4TQmtmXqXLaarrAe+HXCZEiBKFOqPgeo2RMxr -LAO+MYIsVtEz39gISRhEvqcAls01sV1l7oGicQIDAQABo0UwQzAOBgNVHQ8BAf8E -BAMCAQYwEgYDVR0TAQH/BAgwBgEB/wIBATAdBgNVHQ4EFgQUy9Nqk0mDRwC5tcmN -xQ1YWO5MAhgwDQYJKoZIhvcNAQELBQADggIBAHbpsqY+tPSj8BSky+acZoZjF7fZ -Ae3MKVogwm5tecmwTKf5xDj9J99ZpGvcWCKtoxxWw0LZ+JI/aeqANSRDXZIelcIw -yZefw06z/coQJwAIy1RSoKJPV72mkG0Es9w2HxSEoLaZ9tql0TyV8D/QseUM8Yt/ -nNtShRoj6iMnZjhmut5pLfrLWHwQkt4fguBpL7rtydS/wAsOmnJ7lmOrU6zrBJzD -vEER3AJtgdIt4GvKf4MupKLgKvYDB4sUQVmMyAS78B9+WZDDRTClsx+/Oc1ggkWz -8X7EmIw+3U9V2hd67qZ81EwcSB8ixV06E7ZcbhnJs7ds7swqUjwMArFWuzqO4cjW -2BnyVzCO9pymFLI7qol32xCEgaQlOVS/kFHP3meygfeaeYe902sJw6NevOA4e0AO -AKR8FDfGRXJ9cOmYzeHeWKex8yt1Ul6+N8SXzjOhf39JM0QqTfHN7pPfFthTAFOs -9rI/buJteJqR1WxgVk/jY4wLGEOcEyO6Y/Uj5iWWTvm5G/C1yZfSg+NvWoytxZ7P -3S0qtEfmT4UwuHBsd5ZfEZoxb+GbqL/nhrKz/0B9LyKS0SJP9+mz7nSORz7t35Uc -BhiG6T9W7P/NRW4Tqb2tEN1VwU6eP5SEf7c7C1VVaepk0fvc1p5dl67IERqPucPD -dT2rDsCMBV7SXMUM ------END CERTIFICATE-----` - -const intermediateCA = ` ------BEGIN CERTIFICATE----- -MIIEHTCCAgWgAwIBAgIQXzZsEQv0cvSRLJAkS9FmWTANBgkqhkiG9w0BAQsFADAU -MRIwEAYDVQQDEwlUcnVzdGVkQ0EwHhcNMTgwMzI4MTg0MzMzWhcNMzgwMzI4MTg0 -MzAzWjAZMRcwFQYDVQQDEw5JbnRlcm1lZGlhdGVDQTCCASIwDQYJKoZIhvcNAQEB -BQADggEPADCCAQoCggEBAN3aYpH/1yEYf/kHuHWyO3AO4tgwlYYLhCDT2GvaPdaE -cqhe/VuYiqx3xY7IRDqsW2rau/OXgW6KzLHdRZHogK07hUj1Lfr7X+Oqbp22IV4y -dyiL7jwK9AtVXvDuuv5ET+oRfV82j0uhyk0ueGD9r6C/h+6NTzHBD+3xo6Yuc0Vk -BfY5zIyhaFqlm1aRYvupDRjC/63uBgAlrGxy2LyiTMVnYMuxoJM5ahDepz3sqjuN -WVyPhfGwIezjXuXRdEvlmWX05XLnsTdP4zu4fHq9Z7c3TKWWONM3z64ECAZmGQVf -MAcEDX7qP0gZX5PCT+0WcvTgTWE4Q+WIh5AmYyxQ04cCAwEAAaNmMGQwDgYDVR0P -AQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMAYlq86RZzT -WxLpYE7KTTM7DHOuMB8GA1UdIwQYMBaAFMvTapNJg0cAubXJjcUNWFjuTAIYMA0G -CSqGSIb3DQEBCwUAA4ICAQBmYRpQoWEm5g16kwUrpwWrH7OIqqMtUhM1dcskECfk -i3/hcsV+MQRkGHLIItucYIWqs7oOQIglsyGcohAbnvE1PVtKKojUHC0lfbjgIenD -Pbvz15QB6A3KLDR82QbQGeGniACy924p66zlfPwHJbkMo5ZaqtNqI//EIa2YCpyy -okhFXaSFmPWXXrTOCsEEsFJKsoSCH1KUpTcwACGkkilNseg1edZB6/lBDwybxVuY -+dbUlHip3r5tFcP66Co3tKAaEcVY0AsZ/8GKwH+IM2AR6q7jdn9Gp2OX4E1ul9Wy -+hW5GHMmfixkgTVwRowuKgkCPEKV2/Xy3k9rlSpnKr2NpYYq0mu6An9HYt8THQ+e -wGZHwWufuDFDWuzlu7CxFOjpXLKv8qqVnwSFC91S3HsPAzPKLC9ZMEC+iQs2Vkes -Os0nFLZeMaMGAO5W6xiyQ5p94oo0bqa1XbmSV1bNp1HWuNEGIiZKrEUDxfYuDc6f -C6hJZKsjJkMkBeadlQAlLcjIx1rDV171CKLLTxy/dT5kv4p9UrJlnleyMVG6S/3d -6nX/WLSgZIMYbOwiZVVPlSrobuG38ULJMCSuxndxD0l+HahJaH8vYXuR67A0XT+b -TEe305AI6A/9MEaRrActBnq6/OviQgBsKAvtTv1FmDbnpZsKeoFuwc3OPdTveQdC -RA== ------END CERTIFICATE-----` - -func TestEmbeddedHMAC(t *testing.T) { - // protected: {"alg":"HS256", "jwk":{"kty":"oct", "k":"MTEx"}}, aka HMAC key. - msg := `{"payload":"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ","protected":"eyJhbGciOiJIUzI1NiIsICJqd2siOnsia3R5Ijoib2N0IiwgImsiOiJNVEV4In19","signature":"lvo41ZZsuHwQvSh0uJtEXRR3vmuBJ7in6qMoD7p9jyo"}` - - _, err := ParseSigned(msg) - if err == nil { - t.Error("should not allow parsing JWS with embedded JWK with HMAC key") - } -} - -func TestCompactParseJWS(t *testing.T) { - // Should parse - msg := "eyJhbGciOiJYWVoifQ.cGF5bG9hZA.c2lnbmF0dXJl" - _, err := ParseSigned(msg) - if err != nil { - t.Error("Unable to parse valid message:", err) - } - - // Should parse (detached signature missing payload) - msg = "eyJhbGciOiJYWVoifQ..c2lnbmF0dXJl" - _, err = ParseSigned(msg) - if err != nil { - t.Error("Unable to parse valid message:", err) - } - - // Messages that should fail to parse - failures := []string{ - // Not enough parts - "eyJhbGciOiJYWVoifQ.cGF5bG9hZA", - // Invalid signature - "eyJhbGciOiJYWVoifQ.cGF5bG9hZA.////", - // Invalid payload - "eyJhbGciOiJYWVoifQ.////.c2lnbmF0dXJl", - // Invalid header - "////.eyJhbGciOiJYWVoifQ.c2lnbmF0dXJl", - // Invalid header - "cGF5bG9hZA.cGF5bG9hZA.c2lnbmF0dXJl", - } - - for i := range failures { - _, err = ParseSigned(failures[i]) - if err == nil { - t.Error("Able to parse invalid message") - } - } -} - -func TestFullParseJWS(t *testing.T) { - // Messages that should succeed to parse - successes := []string{ - "{\"payload\":\"CUJD\",\"signatures\":[{\"protected\":\"e30\",\"header\":{\"kid\":\"XYZ\"},\"signature\":\"CUJD\"},{\"protected\":\"e30\",\"signature\":\"CUJD\"}]}", - } - - for i := range successes { - _, err := ParseSigned(successes[i]) - if err != nil { - t.Error("Unble to parse valid message", err, successes[i]) - } - } - - // Messages that should fail to parse - failures := []string{ - // Empty - "{}", - // Invalid JSON - "{XX", - // Invalid protected header - "{\"payload\":\"CUJD\",\"signatures\":[{\"protected\":\"CUJD\",\"header\":{\"kid\":\"XYZ\"},\"signature\":\"CUJD\"}]}", - // Invalid protected header - "{\"payload\":\"CUJD\",\"protected\":\"CUJD\",\"header\":{\"kid\":\"XYZ\"},\"signature\":\"CUJD\"}", - // Invalid protected header - "{\"payload\":\"CUJD\",\"signatures\":[{\"protected\":\"###\",\"header\":{\"kid\":\"XYZ\"},\"signature\":\"CUJD\"}]}", - // Invalid payload - "{\"payload\":\"###\",\"signatures\":[{\"protected\":\"CUJD\",\"header\":{\"kid\":\"XYZ\"},\"signature\":\"CUJD\"}]}", - // Invalid payload - "{\"payload\":\"CUJD\",\"signatures\":[{\"protected\":\"e30\",\"header\":{\"kid\":\"XYZ\"},\"signature\":\"###\"}]}", - } - - for i := range failures { - _, err := ParseSigned(failures[i]) - if err == nil { - t.Error("Able to parse invalid message", err, failures[i]) - } - } -} - -func TestRejectUnprotectedJWSNonce(t *testing.T) { - // No need to test compact, since that's always protected - - // Flattened JSON - input := `{ - "header": { "nonce": "should-cause-an-error" }, - "payload": "does-not-matter", - "signature": "does-not-matter" - }` - _, err := ParseSigned(input) - if err == nil { - t.Error("JWS with an unprotected nonce parsed as valid.") - } else if err != ErrUnprotectedNonce { - t.Errorf("Improper error for unprotected nonce: %v", err) - } - - // Full JSON - input = `{ - "payload": "does-not-matter", - "signatures": [{ - "header": { "nonce": "should-cause-an-error" }, - "signature": "does-not-matter" - }] - }` - _, err = ParseSigned(input) - if err == nil { - t.Error("JWS with an unprotected nonce parsed as valid.") - } else if err != ErrUnprotectedNonce { - t.Errorf("Improper error for unprotected nonce: %v", err) - } -} - -func TestVerifyFlattenedWithIncludedUnprotectedKey(t *testing.T) { - input := `{ - "header": { - "alg": "RS256", - "jwk": { - "e": "AQAB", - "kty": "RSA", - "n": "tSwgy3ORGvc7YJI9B2qqkelZRUC6F1S5NwXFvM4w5-M0TsxbFsH5UH6adigV0jzsDJ5imAechcSoOhAh9POceCbPN1sTNwLpNbOLiQQ7RD5mY_pSUHWXNmS9R4NZ3t2fQAzPeW7jOfF0LKuJRGkekx6tXP1uSnNibgpJULNc4208dgBaCHo3mvaE2HV2GmVl1yxwWX5QZZkGQGjNDZYnjFfa2DKVvFs0QbAk21ROm594kAxlRlMMrvqlf24Eq4ERO0ptzpZgm_3j_e4hGRD39gJS7kAzK-j2cacFQ5Qi2Y6wZI2p-FCq_wiYsfEAIkATPBiLKl_6d_Jfcvs_impcXQ" - } - }, - "payload": "Zm9vCg", - "signature": "hRt2eYqBd_MyMRNIh8PEIACoFtmBi7BHTLBaAhpSU6zyDAFdEBaX7us4VB9Vo1afOL03Q8iuoRA0AT4akdV_mQTAQ_jhTcVOAeXPr0tB8b8Q11UPQ0tXJYmU4spAW2SapJIvO50ntUaqU05kZd0qw8-noH1Lja-aNnU-tQII4iYVvlTiRJ5g8_CADsvJqOk6FcHuo2mG643TRnhkAxUtazvHyIHeXMxydMMSrpwUwzMtln4ZJYBNx4QGEq6OhpAD_VSp-w8Lq5HOwGQoNs0bPxH1SGrArt67LFQBfjlVr94E1sn26p4vigXm83nJdNhWAMHHE9iV67xN-r29LT-FjA" - }` - - jws, err := ParseSigned(input) - if err != nil { - t.Error("Unable to parse valid message.") - } - if len(jws.Signatures) != 1 { - t.Error("Too many or too few signatures.") - } - sig := jws.Signatures[0] - if sig.Header.JSONWebKey == nil { - t.Error("No JWK in signature header.") - } - payload, err := jws.Verify(sig.Header.JSONWebKey) - if err != nil { - t.Errorf("Signature did not validate: %v", err) - } - if string(payload) != "foo\n" { - t.Errorf("Payload was incorrect: '%s' should have been 'foo\\n'", string(payload)) - } -} - -// Test verification of a detached signature -func TestDetachedVerifyJWS(t *testing.T) { - rsaPublicKey, err := x509.ParsePKIXPublicKey(fromBase64Bytes(` - MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3aLSGwbeX0ZA2Ha+EvELaIFGzO - 91+Q15JQc/tdGdCgGW3XAbrh7ZUhDh1XKzbs+UOQxqn3Eq4YOx18IG0WsJSuCaHQIxnDlZ - t/GP8WLwjMC0izlJLm2SyfM/EEoNpmTC3w6MQ2dHK7SZ9Zoq+sKijQd+V7CYdr8zHMpDrd - NKoEcR0HjmvzzdMoUChhkGH5TaNbZyollULTggepaYUKS8QphqdSDMWiSetKG+g6V87lv6 - CVYyK1FF6g7Esp5OOj5pNn3/bmF+7V+b7TvK91NCIlURCjE9toRgNoIP4TDnWRn/vvfZ3G - zNrtWmlizqz3r5KdvIs71ahWgMUSD4wfazrwIDAQAB`)) - if err != nil { - t.Fatal(err) - } - - sampleMessages := []string{ - "eyJhbGciOiJSUzI1NiJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.YHX849fvekz6wJGeyqnQhFqyHFcUXNJKj3o2w3ddR46YLlsCopUJrlifRU_ZuTWzpYxt5oC--T2eoqMhlCvltSWrE5_1_EumqiMfAYsZULx9E6Jns7q3w7mttonYFSIh7aR3-yg2HMMfTCgoAY1y_AZ4VjXwHDcZ5gu1oZDYgvZF4uXtCmwT6e5YtR1m8abiWPF8BgoTG_BD3KV6ClLj_QQiNFdfdxAMDw7vKVOKG1T7BFtz6cDs2Q3ILS4To5E2IjcVSSYS8mi77EitCrWmrqbK_G3WCdKeUFGnMnyuKXaCDy_7FLpAZ6Z5RomRr5iskXeJZdZqIKcJV8zl4fpsPA", - "eyJhbGciOiJSUzM4NCJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.meyfoOTjAAjXHFYiNlU7EEnsYtbeUYeEglK6BL_cxISEr2YAGLr1Gwnn2HnucTnH6YilyRio7ZC1ohy_ZojzmaljPHqpr8kn1iqNFu9nFE2M16ZPgJi38-PGzppcDNliyzOQO-c7L-eA-v8Gfww5uyRaOJdiWg-hUJmeGBIngPIeLtSVmhJtz8oTeqeNdUOqQv7f7VRCuvagLhW1PcEM91VUS-gS0WEUXoXWZ2lp91No0v1O24izgX3__FKiX_16XhrOfAgJ82F61vjbTIQYwhexHPZyYTlXYt_scNRzFGhSKeGFin4zVdFLOXWJqKWdUd5IrDP5Nya3FSoWbWDXAg", - } - - for _, msg := range sampleMessages { - obj, err := ParseSigned(msg) - if err != nil { - t.Error("unable to parse message", msg, err) - continue - } - payload := obj.payload - obj.payload = nil - err = obj.DetachedVerify(payload, rsaPublicKey) - if err != nil { - t.Error("unable to verify message", msg, err) - continue - } - idx, _, err := obj.DetachedVerifyMulti(payload, rsaPublicKey) - if idx != 0 || err != nil { - t.Error("unable to verify message", msg, err) - continue - } - } -} - -func TestVerifyFlattenedWithPrivateProtected(t *testing.T) { - // The protected field contains a Private Header Parameter name, per - // https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-4 - // Base64-decoded, it's '{"nonce":"8HIepUNFZUa-exKTrXVf4g"}' - input := `{"header":{"alg":"RS256","jwk":{"kty":"RSA","n":"7ixeydcbxxppzxrBphrW1atUiEZqTpiHDpI-79olav5XxAgWolHmVsJyxzoZXRxmtED8PF9-EICZWBGdSAL9ZTD0hLUCIsPcpdgT_LqNW3Sh2b2caPL2hbMF7vsXvnCGg9varpnHWuYTyRrCLUF9vM7ES-V3VCYTa7LcCSRm56Gg9r19qar43Z9kIKBBxpgt723v2cC4bmLmoAX2s217ou3uCpCXGLOeV_BesG4--Nl3pso1VhCfO85wEWjmW6lbv7Kg4d7Jdkv5DjDZfJ086fkEAYZVYGRpIgAvJBH3d3yKDCrSByUEud1bWuFjQBmMaeYOrVDXO_mbYg5PwUDMhw","e":"AQAB"}},"protected":"eyJub25jZSI6IjhISWVwVU5GWlVhLWV4S1RyWFZmNGcifQ","payload":"eyJjb250YWN0IjpbIm1haWx0bzpmb29AYmFyLmNvbSJdfQ","signature":"AyvVGMgXsQ1zTdXrZxE_gyO63pQgotL1KbI7gv6Wi8I7NRy0iAOkDAkWcTQT9pcCYApJ04lXfEDZfP5i0XgcFUm_6spxi5mFBZU-NemKcvK9dUiAbXvb4hB3GnaZtZiuVnMQUb_ku4DOaFFKbteA6gOYCnED_x7v0kAPHIYrQnvIa-KZ6pTajbV9348zgh9TL7NgGIIsTcMHd-Jatr4z1LQ0ubGa8tS300hoDhVzfoDQaEetYjCo1drR1RmdEN1SIzXdHOHfubjA3ZZRbrF_AJnNKpRRoIwzu1VayOhRmdy1qVSQZq_tENF4VrQFycEL7DhG7JLoXC4T2p1urwMlsw"}` - - jws, err := ParseSigned(input) - if err != nil { - t.Error("Unable to parse valid message.") - } - if len(jws.Signatures) != 1 { - t.Error("Too many or too few signatures.") - } - sig := jws.Signatures[0] - if sig.Header.JSONWebKey == nil { - t.Error("No JWK in signature header.") - } - payload, err := jws.Verify(sig.Header.JSONWebKey) - if err != nil { - t.Errorf("Signature did not validate: %v", err) - } - expected := "{\"contact\":[\"mailto:foo@bar.com\"]}" - if string(payload) != expected { - t.Errorf("Payload was incorrect: '%s' should have been '%s'", string(payload), expected) - } -} - -// Test vectors generated with nimbus-jose-jwt -func TestSampleNimbusJWSMessagesRSA(t *testing.T) { - rsaPublicKey, err := x509.ParsePKIXPublicKey(fromBase64Bytes(` - MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3aLSGwbeX0ZA2Ha+EvELaIFGzO - 91+Q15JQc/tdGdCgGW3XAbrh7ZUhDh1XKzbs+UOQxqn3Eq4YOx18IG0WsJSuCaHQIxnDlZ - t/GP8WLwjMC0izlJLm2SyfM/EEoNpmTC3w6MQ2dHK7SZ9Zoq+sKijQd+V7CYdr8zHMpDrd - NKoEcR0HjmvzzdMoUChhkGH5TaNbZyollULTggepaYUKS8QphqdSDMWiSetKG+g6V87lv6 - CVYyK1FF6g7Esp5OOj5pNn3/bmF+7V+b7TvK91NCIlURCjE9toRgNoIP4TDnWRn/vvfZ3G - zNrtWmlizqz3r5KdvIs71ahWgMUSD4wfazrwIDAQAB`)) - if err != nil { - panic(err) - } - - rsaSampleMessages := []string{ - "eyJhbGciOiJSUzI1NiJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.YHX849fvekz6wJGeyqnQhFqyHFcUXNJKj3o2w3ddR46YLlsCopUJrlifRU_ZuTWzpYxt5oC--T2eoqMhlCvltSWrE5_1_EumqiMfAYsZULx9E6Jns7q3w7mttonYFSIh7aR3-yg2HMMfTCgoAY1y_AZ4VjXwHDcZ5gu1oZDYgvZF4uXtCmwT6e5YtR1m8abiWPF8BgoTG_BD3KV6ClLj_QQiNFdfdxAMDw7vKVOKG1T7BFtz6cDs2Q3ILS4To5E2IjcVSSYS8mi77EitCrWmrqbK_G3WCdKeUFGnMnyuKXaCDy_7FLpAZ6Z5RomRr5iskXeJZdZqIKcJV8zl4fpsPA", - "eyJhbGciOiJSUzM4NCJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.meyfoOTjAAjXHFYiNlU7EEnsYtbeUYeEglK6BL_cxISEr2YAGLr1Gwnn2HnucTnH6YilyRio7ZC1ohy_ZojzmaljPHqpr8kn1iqNFu9nFE2M16ZPgJi38-PGzppcDNliyzOQO-c7L-eA-v8Gfww5uyRaOJdiWg-hUJmeGBIngPIeLtSVmhJtz8oTeqeNdUOqQv7f7VRCuvagLhW1PcEM91VUS-gS0WEUXoXWZ2lp91No0v1O24izgX3__FKiX_16XhrOfAgJ82F61vjbTIQYwhexHPZyYTlXYt_scNRzFGhSKeGFin4zVdFLOXWJqKWdUd5IrDP5Nya3FSoWbWDXAg", - "eyJhbGciOiJSUzUxMiJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.rQPz0PDh8KyE2AX6JorgI0MLwv-qi1tcWlz6tuZuWQG1hdrlzq5tR1tQg1evYNc_SDDX87DWTSKXT7JEqhKoFixLfZa13IJrOc7FB8r5ZLx7OwOBC4F--OWrvxMA9Y3MTJjPN3FemQePUo-na2vNUZv-YgkcbuOgbO3hTxwQ7j1JGuqy-YutXOFnccdXvntp3t8zYZ4Mg1It_IyL9pzgGqHIEmMV1pCFGHsDa-wStB4ffmdhrADdYZc0q_SvxUdobyC_XzZCz9ENzGIhgwYxyyrqg7kjqUGoKmCLmoSlUFW7goTk9IC5SXdUyLPuESxOWNfHoRClGav230GYjPFQFA", - "eyJhbGciOiJQUzI1NiJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.UTtxjsv_6x4CdlAmZfAW6Lun3byMjJbcwRp_OlPH2W4MZaZar7aql052mIB_ddK45O9VUz2aphYVRvKPZY8WHmvlTUU30bk0z_cDJRYB9eIJVMOiRCYj0oNkz1iEZqsP0YgngxwuUDv4Q4A6aJ0Bo5E_rZo3AnrVHMHUjPp_ZRRSBFs30tQma1qQ0ApK4Gxk0XYCYAcxIv99e78vldVRaGzjEZmQeAVZx4tGcqZP20vG1L84nlhSGnOuZ0FhR8UjRFLXuob6M7EqtMRoqPgRYw47EI3fYBdeSivAg98E5S8R7R1NJc7ef-l03RvfUSY0S3_zBq_4PlHK6A-2kHb__w", - "eyJhbGciOiJSUzM4NCJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.meyfoOTjAAjXHFYiNlU7EEnsYtbeUYeEglK6BL_cxISEr2YAGLr1Gwnn2HnucTnH6YilyRio7ZC1ohy_ZojzmaljPHqpr8kn1iqNFu9nFE2M16ZPgJi38-PGzppcDNliyzOQO-c7L-eA-v8Gfww5uyRaOJdiWg-hUJmeGBIngPIeLtSVmhJtz8oTeqeNdUOqQv7f7VRCuvagLhW1PcEM91VUS-gS0WEUXoXWZ2lp91No0v1O24izgX3__FKiX_16XhrOfAgJ82F61vjbTIQYwhexHPZyYTlXYt_scNRzFGhSKeGFin4zVdFLOXWJqKWdUd5IrDP5Nya3FSoWbWDXAg", - "eyJhbGciOiJSUzUxMiJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.rQPz0PDh8KyE2AX6JorgI0MLwv-qi1tcWlz6tuZuWQG1hdrlzq5tR1tQg1evYNc_SDDX87DWTSKXT7JEqhKoFixLfZa13IJrOc7FB8r5ZLx7OwOBC4F--OWrvxMA9Y3MTJjPN3FemQePUo-na2vNUZv-YgkcbuOgbO3hTxwQ7j1JGuqy-YutXOFnccdXvntp3t8zYZ4Mg1It_IyL9pzgGqHIEmMV1pCFGHsDa-wStB4ffmdhrADdYZc0q_SvxUdobyC_XzZCz9ENzGIhgwYxyyrqg7kjqUGoKmCLmoSlUFW7goTk9IC5SXdUyLPuESxOWNfHoRClGav230GYjPFQFA", - } - - for _, msg := range rsaSampleMessages { - obj, err := ParseSigned(msg) - if err != nil { - t.Error("unable to parse message", msg, err) - continue - } - payload, err := obj.Verify(rsaPublicKey) - if err != nil { - t.Error("unable to verify message", msg, err) - continue - } - if string(payload) != "Lorem ipsum dolor sit amet" { - t.Error("payload is not what we expected for msg", msg) - } - } -} - -// Test vectors generated with nimbus-jose-jwt -func TestSampleNimbusJWSMessagesEC(t *testing.T) { - ecPublicKeyP256, err := x509.ParsePKIXPublicKey(fromBase64Bytes("MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEIg62jq6FyL1otEj9Up7S35BUrwGF9TVrAzrrY1rHUKZqYIGEg67u/imjgadVcr7y9Q32I0gB8W8FHqbqt696rA==")) - if err != nil { - panic(err) - } - ecPublicKeyP384, err := x509.ParsePKIXPublicKey(fromBase64Bytes("MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEPXsVlqCtN2oTY+F+hFZm3M0ldYpb7IeeJM5wYmT0k1RaqzBFDhDMNnYK5Q5x+OyssZrAtHgYDFw02AVJhhng/eHRp7mqmL/vI3wbxJtrLKYldIbBA+9fYBQcKeibjlu5")) - if err != nil { - panic(err) - } - ecPublicKeyP521, err := x509.ParsePKIXPublicKey(fromBase64Bytes("MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAa2w3MMJ5FWD6tSf68G+Wy5jIhWXOD3IA7pE5IC/myQzo1lWcD8KS57SM6nm4POtPcxyLmDhL7FLuh8DKoIZyvtAAdK8+tOQP7XXRlT2bkvzIuazp05It3TAPu00YzTIpKfDlc19Y1lvf7etrbFqhShD92B+hHmhT4ddrdbPCBDW8hvU=")) - if err != nil { - panic(err) - } - - ecPublicKeys := []interface{}{ecPublicKeyP256, ecPublicKeyP384, ecPublicKeyP521} - - ecSampleMessages := []string{ - "eyJhbGciOiJFUzI1NiJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.MEWJVlvGRQyzMEGOYm4rwuiwxrX-6LjnlbaRDAuhwmnBm2Gtn7pRpGXRTMFZUXsSGDz2L1p-Hz1qn8j9bFIBtQ", - "eyJhbGciOiJFUzM4NCJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.nbdjPnJPYQtVNNdBIx8-KbFKplTxrz-hnW5UNhYUY7SBkwHK4NZnqc2Lv4DXoA0aWHq9eiypgOh1kmyPWGEmqKAHUx0xdIEkBoHk3ZsbmhOQuq2jL_wcMUG6nTWNhLrB", - "eyJhbGciOiJFUzUxMiJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.AeYNFC1rwIgQv-5fwd8iRyYzvTaSCYTEICepgu9gRId-IW99kbSVY7yH0MvrQnqI-a0L8zwKWDR35fW5dukPAYRkADp3Y1lzqdShFcEFziUVGo46vqbiSajmKFrjBktJcCsfjKSaLHwxErF-T10YYPCQFHWb2nXJOOI3CZfACYqgO84g", - } - - for i, msg := range ecSampleMessages { - obj, err := ParseSigned(msg) - if err != nil { - t.Error("unable to parse message", msg, err) - continue - } - payload, err := obj.Verify(ecPublicKeys[i]) - if err != nil { - t.Error("unable to verify message", msg, err) - continue - } - if string(payload) != "Lorem ipsum dolor sit amet" { - t.Error("payload is not what we expected for msg", msg) - } - } -} - -// Test vectors generated with nimbus-jose-jwt -func TestSampleNimbusJWSMessagesHMAC(t *testing.T) { - hmacTestKey := fromHexBytes("DF1FA4F36FFA7FC42C81D4B3C033928D") - - hmacSampleMessages := []string{ - "eyJhbGciOiJIUzI1NiJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.W5tc_EUhxexcvLYEEOckyyvdb__M5DQIVpg6Nmk1XGM", - "eyJhbGciOiJIUzM4NCJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.sBu44lXOJa4Nd10oqOdYH2uz3lxlZ6o32QSGHaoGdPtYTDG5zvSja6N48CXKqdAh", - "eyJhbGciOiJIUzUxMiJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.M0yR4tmipsORIix-BitIbxEPGaxPchDfj8UNOpKuhDEfnb7URjGvCKn4nOlyQ1z9mG1FKbwnqR1hOVAWSzAU_w", - } - - for _, msg := range hmacSampleMessages { - obj, err := ParseSigned(msg) - if err != nil { - t.Error("unable to parse message", msg, err) - continue - } - payload, err := obj.Verify(hmacTestKey) - if err != nil { - t.Error("unable to verify message", msg, err) - continue - } - if string(payload) != "Lorem ipsum dolor sit amet" { - t.Error("payload is not what we expected for msg", msg) - } - } -} - -func TestHeaderFieldsCompact(t *testing.T) { - msg := "eyJhbGciOiJFUzUxMiJ9.TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ.AeYNFC1rwIgQv-5fwd8iRyYzvTaSCYTEICepgu9gRId-IW99kbSVY7yH0MvrQnqI-a0L8zwKWDR35fW5dukPAYRkADp3Y1lzqdShFcEFziUVGo46vqbiSajmKFrjBktJcCsfjKSaLHwxErF-T10YYPCQFHWb2nXJOOI3CZfACYqgO84g" - - obj, err := ParseSigned(msg) - if err != nil { - t.Fatal("unable to parse message", msg, err) - } - if obj.Signatures[0].Header.Algorithm != "ES512" { - t.Error("merged header did not contain expected alg value") - } - if obj.Signatures[0].Protected.Algorithm != "ES512" { - t.Error("protected header did not contain expected alg value") - } - if obj.Signatures[0].Unprotected.Algorithm != "" { - t.Error("unprotected header contained an alg value") - } -} - -func TestHeaderFieldsFull(t *testing.T) { - msg := `{"payload":"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ","protected":"eyJhbGciOiJFUzUxMiJ9","header":{"custom":"test"},"signature":"AeYNFC1rwIgQv-5fwd8iRyYzvTaSCYTEICepgu9gRId-IW99kbSVY7yH0MvrQnqI-a0L8zwKWDR35fW5dukPAYRkADp3Y1lzqdShFcEFziUVGo46vqbiSajmKFrjBktJcCsfjKSaLHwxErF-T10YYPCQFHWb2nXJOOI3CZfACYqgO84g"}` - - obj, err := ParseSigned(msg) - if err != nil { - t.Fatal("unable to parse message", msg, err) - } - if obj.Signatures[0].Header.Algorithm != "ES512" { - t.Error("merged header did not contain expected alg value") - } - if obj.Signatures[0].Protected.Algorithm != "ES512" { - t.Error("protected header did not contain expected alg value") - } - if obj.Signatures[0].Unprotected.Algorithm != "" { - t.Error("unprotected header contained an alg value") - } - if obj.Signatures[0].Unprotected.ExtraHeaders["custom"] != "test" { - t.Error("unprotected header did not contain custom header value") - } -} - -// Test vectors generated with nimbus-jose-jwt -func TestErrorMissingPayloadJWS(t *testing.T) { - _, err := (&rawJSONWebSignature{}).sanitized() - if err == nil { - t.Error("was able to parse message with missing payload") - } - if !strings.Contains(err.Error(), "missing payload") { - t.Errorf("unexpected error message, should contain 'missing payload': %s", err) - } -} - -// Test that a null value in the header doesn't panic -func TestNullHeaderValue(t *testing.T) { - msg := `{ - "payload": - "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGF - tcGxlLmNvbS9pc19yb290Ijp0cnVlfQ", - "protected":"eyJhbGciOiJFUzI1NiIsIm5vbmNlIjpudWxsfQ", - "header": - {"kid":"e9bc097a-ce51-4036-9562-d2ade882db0d"}, - "signature": - "DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8IS - lSApmWQxfKTUJqPP3-Kg6NU1Q" - }` - - defer func() { - if r := recover(); r != nil { - t.Errorf("ParseSigned panic'd when parsing a message with a null protected header value") - } - }() - ParseSigned(msg) -} - -// Test for bug: -// https://github.com/square/go-jose/issues/157 -func TestEmbedJWKBug(t *testing.T) { - signerKey := SigningKey{ - Key: &JSONWebKey{ - Key: rsaTestKey, - KeyID: "rsa-test-key", - }, - Algorithm: RS256, - } - - signer, err := NewSigner(signerKey, &SignerOptions{EmbedJWK: true}) - if err != nil { - t.Fatal(err) - } - - signerNoEmbed, err := NewSigner(signerKey, &SignerOptions{EmbedJWK: false}) - if err != nil { - t.Fatal(err) - } - - jws, err := signer.Sign([]byte("Lorem ipsum dolor sit amet")) - if err != nil { - t.Fatal(err) - } - - jwsNoEmbed, err := signerNoEmbed.Sign([]byte("Lorem ipsum dolor sit amet")) - if err != nil { - t.Fatal(err) - } - - // This used to panic with: - // json: error calling MarshalJSON for type *jose.JSONWebKey: square/go-jose: unknown key type '%!s(<nil>)' - output := jws.FullSerialize() - outputNoEmbed := jwsNoEmbed.FullSerialize() - - // Expected output with embed set to true is a JWS with the public JWK embedded, with kid header empty. - // Expected output with embed set to false is that we set the kid header for key identification instead. - parsed, err := ParseSigned(output) - if err != nil { - t.Fatal(err) - } - - parsedNoEmbed, err := ParseSigned(outputNoEmbed) - if err != nil { - t.Fatal(err) - } - - if parsed.Signatures[0].Header.KeyID != "" { - t.Error("expected kid field in protected header to be empty") - } - if parsed.Signatures[0].Header.JSONWebKey.KeyID != "rsa-test-key" { - t.Error("expected rsa-test-key to be kid in embedded JWK in protected header") - } - if parsedNoEmbed.Signatures[0].Header.KeyID != "rsa-test-key" { - t.Error("expected kid field in protected header to be rsa-test-key") - } - if parsedNoEmbed.Signatures[0].Header.JSONWebKey != nil { - t.Error("expected no embedded JWK to be present") - } -} - -func TestJWSWithCertificateChain(t *testing.T) { - signerKey := SigningKey{ - Key: rsaTestKey, - Algorithm: RS256, - } - - certs := []string{ - // CN=TrustedSigner, signed by IntermediateCA - "MIIDLDCCAhSgAwIBAgIQNsV1i7m3kXGugqOQuuC7FzANBgkqhkiG9w0BAQsFADAZMRcwFQYDVQQDEw5JbnRlcm1lZGlhdGVDQTAeFw0xODAzMjgxODQzNDlaFw0zODAzMjgxODQzMDJaMBgxFjAUBgNVBAMTDVRydXN0ZWRTaWduZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDLpvmOEDRxzQJUKHLkLQSsFDo9eGnolSERa6fz1E1F4wmk6nieHqssPd28C6Vb1sHJFne/j93DXNrx7W9Gy9fQvWa+VNHfGuYAodaS2pyV4VUPWMXI2a+qjxW85orq34XtcHzU+qm+ekR5W06ypW+xewbXJW//P9ulrsv3bDoDFaiggHY/u3p5CRSB9mg+Pbpf6E/k/N85sFJUsRE9hzgwg27Kqhh6p3hP3QnA+0WZRcWhwG0gykoD6layRLCPVcxlTSUdpyStDiK8w2whLJQfixCBGLS3/tB/GKb726bxTQK72OLzIMtOo4ZMtTva7bcA2PRgwfRz7bJg4DXz7oHTAgMBAAGjcTBvMA4GA1UdDwEB/wQEAwIDuDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwHQYDVR0OBBYEFCpZEyJGAyK//NsYSSC4xkOqNnh3MB8GA1UdIwQYMBaAFMAYlq86RZzTWxLpYE7KTTM7DHOuMA0GCSqGSIb3DQEBCwUAA4IBAQBSIln6jPFkctPC17le0O+wkCStFOuqUM9cjwPuj4xBQ47RxmC0Pjv52N3TuVH7slmMykITQO/vVqQZguf+N5u4BCh223qWiu1muYBTfBPXCPgJjJ79bUL/dy9QEocOfPiIqTFC6xHKeSUCu6qi5jCPFynOaoVvlNPZEb2MR+QrkKVzg09aDEfk6J+wE6eH9+kNOtwvd/z2a2t2hterURtJEnYt7AQGviEpUf1gbHxCE9f3FW5iJGdgcshrk5ZwUfxvND2x4qFq2fYQRxNBnkO+TSYzwYoAItcGAUvlZFH+rdsq3N+UpRptXRkj5iMq59VlcXFOT675EkkNREgromWn", - // CN=IntermediateCA, signed by TrustedCA - "MIIEHTCCAgWgAwIBAgIQXzZsEQv0cvSRLJAkS9FmWTANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDEwlUcnVzdGVkQ0EwHhcNMTgwMzI4MTg0MzMzWhcNMzgwMzI4MTg0MzAzWjAZMRcwFQYDVQQDEw5JbnRlcm1lZGlhdGVDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAN3aYpH/1yEYf/kHuHWyO3AO4tgwlYYLhCDT2GvaPdaEcqhe/VuYiqx3xY7IRDqsW2rau/OXgW6KzLHdRZHogK07hUj1Lfr7X+Oqbp22IV4ydyiL7jwK9AtVXvDuuv5ET+oRfV82j0uhyk0ueGD9r6C/h+6NTzHBD+3xo6Yuc0VkBfY5zIyhaFqlm1aRYvupDRjC/63uBgAlrGxy2LyiTMVnYMuxoJM5ahDepz3sqjuNWVyPhfGwIezjXuXRdEvlmWX05XLnsTdP4zu4fHq9Z7c3TKWWONM3z64ECAZmGQVfMAcEDX7qP0gZX5PCT+0WcvTgTWE4Q+WIh5AmYyxQ04cCAwEAAaNmMGQwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQIMAYBAf8CAQEwHQYDVR0OBBYEFMAYlq86RZzTWxLpYE7KTTM7DHOuMB8GA1UdIwQYMBaAFMvTapNJg0cAubXJjcUNWFjuTAIYMA0GCSqGSIb3DQEBCwUAA4ICAQBmYRpQoWEm5g16kwUrpwWrH7OIqqMtUhM1dcskECfki3/hcsV+MQRkGHLIItucYIWqs7oOQIglsyGcohAbnvE1PVtKKojUHC0lfbjgIenDPbvz15QB6A3KLDR82QbQGeGniACy924p66zlfPwHJbkMo5ZaqtNqI//EIa2YCpyyokhFXaSFmPWXXrTOCsEEsFJKsoSCH1KUpTcwACGkkilNseg1edZB6/lBDwybxVuY+dbUlHip3r5tFcP66Co3tKAaEcVY0AsZ/8GKwH+IM2AR6q7jdn9Gp2OX4E1ul9Wy+hW5GHMmfixkgTVwRowuKgkCPEKV2/Xy3k9rlSpnKr2NpYYq0mu6An9HYt8THQ+ewGZHwWufuDFDWuzlu7CxFOjpXLKv8qqVnwSFC91S3HsPAzPKLC9ZMEC+iQs2VkesOs0nFLZeMaMGAO5W6xiyQ5p94oo0bqa1XbmSV1bNp1HWuNEGIiZKrEUDxfYuDc6fC6hJZKsjJkMkBeadlQAlLcjIx1rDV171CKLLTxy/dT5kv4p9UrJlnleyMVG6S/3d6nX/WLSgZIMYbOwiZVVPlSrobuG38ULJMCSuxndxD0l+HahJaH8vYXuR67A0XT+bTEe305AI6A/9MEaRrActBnq6/OviQgBsKAvtTv1FmDbnpZsKeoFuwc3OPdTveQdCRA==", - } - - testCases := []struct { - // Cert chain to embed in message - chain []string - // Intermediates & root certificate to verify against - intermediates []string - root string - // Should this test case verify? - success bool - }{ - {certs, nil, trustedCA, true}, - {certs, []string{intermediateCA}, trustedCA, true}, - {certs[0:1], nil, intermediateCA, true}, - {certs[0:1], nil, trustedCA, false}, - {[]string{}, nil, trustedCA, false}, - } - - for i, testCase := range testCases { - signer, err := NewSigner(signerKey, &SignerOptions{ - ExtraHeaders: map[HeaderKey]interface{}{HeaderKey("x5c"): testCase.chain}, - }) - if err != nil { - t.Fatal(err) - } - - signed, err := signer.Sign([]byte("Lorem ipsum dolor sit amet")) - if err != nil { - t.Fatal(err) - } - - parsed, err := ParseSigned(signed.FullSerialize()) - if err != nil { - t.Fatal(err) - } - - opts := x509.VerifyOptions{ - DNSName: "TrustedSigner", - Roots: x509.NewCertPool(), - } - - ok := opts.Roots.AppendCertsFromPEM([]byte(testCase.root)) - if !ok { - t.Fatal("failed to parse trusted root certificate") - } - - if len(testCase.intermediates) > 0 { - opts.Intermediates = x509.NewCertPool() - for _, intermediate := range testCase.intermediates { - ok := opts.Intermediates.AppendCertsFromPEM([]byte(intermediate)) - if !ok { - t.Fatal("failed to parse trusted root certificate") - } - } - } - - chains, err := parsed.Signatures[0].Protected.Certificates(opts) - if testCase.success && (len(chains) == 0 || err != nil) { - t.Fatalf("failed to verify certificate chain for test case %d: %s", i, err) - } - if !testCase.success && (len(chains) != 0 && err == nil) { - t.Fatalf("incorrectly verified certificate chain for test case %d (should fail)", i) - } - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/jwt/builder_test.go b/vendor/gopkg.in/square/go-jose.v2/jwt/builder_test.go deleted file mode 100644 index 8213c47fc3..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/jwt/builder_test.go +++ /dev/null @@ -1,507 +0,0 @@ -/*- - * Copyright 2016 Zbigniew Mandziejewicz - * Copyright 2016 Square, 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 jwt - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/hex" - "encoding/pem" - "errors" - "fmt" - "io" - "reflect" - "sort" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "gopkg.in/square/go-jose.v2" - "gopkg.in/square/go-jose.v2/json" -) - -type testClaims struct { - Subject string `json:"sub"` -} - -type invalidMarshalClaims struct { -} - -var errInvalidMarshalClaims = errors.New("Failed marshaling invalid claims.") - -func (c invalidMarshalClaims) MarshalJSON() ([]byte, error) { - return nil, errInvalidMarshalClaims -} - -var sampleClaims = Claims{ - Subject: "42", - IssuedAt: NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)), - Issuer: "issuer", - Audience: Audience{"a1", "a2"}, -} - -type numberClaims struct { - Int int64 `json:"int"` - Float float64 `json:"float"` -} - -func TestIntegerAndFloatsNormalize(t *testing.T) { - c := numberClaims{1 << 60, 12345.6789} - - normalized, err := normalize(c) - if err != nil { - t.Fatal(err) - } - - ni, err := (normalized["int"].(json.Number)).Int64() - nf, err := (normalized["float"].(json.Number)).Float64() - - if ni != c.Int { - t.Error(fmt.Sprintf("normalize failed to preserve int64 (got %v, wanted %v, type %s)", normalized["int"], c.Int, reflect.TypeOf(normalized["int"]))) - } - if nf != c.Float { - t.Error(fmt.Sprintf("normalize failed to preserve float64 (got %v, wanted %v, type %s)", normalized["float"], c.Float, reflect.TypeOf(normalized["float"]))) - } -} - -func TestBuilderCustomClaimsNonPointer(t *testing.T) { - jwt, err := Signed(rsaSigner).Claims(testClaims{"foo"}).CompactSerialize() - require.NoError(t, err, "Error creating JWT.") - - parsed, err := ParseSigned(jwt) - require.NoError(t, err, "Error parsing JWT.") - - out := &testClaims{} - if assert.NoError(t, parsed.Claims(&testPrivRSAKey1.PublicKey, out), "Error unmarshaling claims.") { - assert.Equal(t, "foo", out.Subject) - } -} - -func TestBuilderCustomClaimsPointer(t *testing.T) { - jwt, err := Signed(rsaSigner).Claims(&testClaims{"foo"}).CompactSerialize() - require.NoError(t, err, "Error creating JWT.") - - parsed, err := ParseSigned(jwt) - require.NoError(t, err, "Error parsing JWT.") - - out := &testClaims{} - if assert.NoError(t, parsed.Claims(&testPrivRSAKey1.PublicKey, out), "Error unmarshaling claims.") { - assert.Equal(t, "foo", out.Subject) - } -} - -func TestBuilderMergeClaims(t *testing.T) { - jwt, err := Signed(rsaSigner). - Claims(&Claims{ - Subject: "42", - }). - Claims(map[string]interface{}{ - "Scopes": []string{"read:users"}, - }). - CompactSerialize() - require.NoError(t, err, "Error creating JWT.") - - parsed, err := ParseSigned(jwt) - require.NoError(t, err, "Error parsing JWT.") - - out := make(map[string]interface{}) - if assert.NoError(t, parsed.Claims(&testPrivRSAKey1.PublicKey, &out), "Error unmarshaling claims.") { - assert.Equal(t, map[string]interface{}{ - "sub": "42", - "Scopes": []interface{}{"read:users"}, - }, out) - } - - _, err = Signed(rsaSigner).Claims("invalid-claims").Claims(&testClaims{"foo"}).CompactSerialize() - assert.Equal(t, err, ErrInvalidClaims) - - _, err = Signed(rsaSigner).Claims(&invalidMarshalClaims{}).CompactSerialize() - assert.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.") -} - -func TestSignedFullSerializeAndToken(t *testing.T) { - b := Signed(rsaSigner).Claims(&testClaims{"foo"}) - - jwt, err := b.FullSerialize() - require.NoError(t, err, "Error creating JWT.") - parsed, err := ParseSigned(jwt) - require.NoError(t, err, "Error parsing JWT.") - out := &testClaims{} - if assert.NoError(t, parsed.Claims(&testPrivRSAKey1.PublicKey, &out), "Error unmarshaling claims.") { - assert.Equal(t, &testClaims{ - Subject: "foo", - }, out) - } - - jwt2, err := b.Token() - require.NoError(t, err, "Error creating JWT.") - out2 := &testClaims{} - if assert.NoError(t, jwt2.Claims(&testPrivRSAKey1.PublicKey, &out2), "Error unmarshaling claims.") { - assert.Equal(t, &testClaims{ - Subject: "foo", - }, out2) - } - - b2 := Signed(rsaSigner).Claims(&invalidMarshalClaims{}) - _, err = b2.FullSerialize() - require.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.") - _, err = b2.Token() - require.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.") -} - -func TestEncryptedFullSerializeAndToken(t *testing.T) { - recipient := jose.Recipient{ - Algorithm: jose.RSA1_5, - Key: testPrivRSAKey1.Public(), - } - encrypter, err := jose.NewEncrypter(jose.A128CBC_HS256, recipient, nil) - require.NoError(t, err, "Error creating encrypter.") - - b := Encrypted(encrypter).Claims(&testClaims{"foo"}) - - jwt, err := b.FullSerialize() - require.NoError(t, err, "Error creating JWT.") - parsed, err := ParseEncrypted(jwt) - require.NoError(t, err, "Error parsing JWT.") - out := &testClaims{} - if assert.NoError(t, parsed.Claims(testPrivRSAKey1, &out)) { - assert.Equal(t, &testClaims{ - Subject: "foo", - }, out) - } - - jwt2, err := b.Token() - require.NoError(t, err, "Error creating JWT.") - out2 := &testClaims{} - if assert.NoError(t, jwt2.Claims(testPrivRSAKey1, &out2)) { - assert.Equal(t, &testClaims{ - Subject: "foo", - }, out2) - } - - b2 := Encrypted(encrypter).Claims(&invalidMarshalClaims{}) - - _, err = b2.FullSerialize() - require.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.") - _, err = b2.Token() - require.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.") -} - -func TestBuilderSignedAndEncrypted(t *testing.T) { - recipient := jose.Recipient{ - Algorithm: jose.RSA1_5, - Key: testPrivRSAKey1.Public(), - } - encrypter, err := jose.NewEncrypter(jose.A128CBC_HS256, recipient, (&jose.EncrypterOptions{}).WithContentType("JWT").WithType("JWT")) - require.NoError(t, err, "Error creating encrypter.") - - jwt1, err := SignedAndEncrypted(rsaSigner, encrypter).Claims(&testClaims{"foo"}).Token() - require.NoError(t, err, "Error marshaling signed-then-encrypted token.") - if nested, err := jwt1.Decrypt(testPrivRSAKey1); assert.NoError(t, err, "Error decrypting signed-then-encrypted token.") { - out := &testClaims{} - assert.NoError(t, nested.Claims(&testPrivRSAKey1.PublicKey, out)) - assert.Equal(t, &testClaims{"foo"}, out) - } - - b := SignedAndEncrypted(rsaSigner, encrypter).Claims(&testClaims{"foo"}) - tok1, err := b.CompactSerialize() - if assert.NoError(t, err) { - jwt, err := ParseSignedAndEncrypted(tok1) - if assert.NoError(t, err, "Error parsing signed-then-encrypted compact token.") { - if nested, err := jwt.Decrypt(testPrivRSAKey1); assert.NoError(t, err) { - out := &testClaims{} - assert.NoError(t, nested.Claims(&testPrivRSAKey1.PublicKey, out)) - assert.Equal(t, &testClaims{"foo"}, out) - } - } - } - - tok2, err := b.FullSerialize() - if assert.NoError(t, err) { - jwe, err := ParseSignedAndEncrypted(tok2) - if assert.NoError(t, err, "Error parsing signed-then-encrypted full token.") { - assert.Equal(t, []jose.Header{{ - Algorithm: string(jose.RSA1_5), - ExtraHeaders: map[jose.HeaderKey]interface{}{ - jose.HeaderType: "JWT", - jose.HeaderContentType: "JWT", - "enc": "A128CBC-HS256", - }, - }}, jwe.Headers) - if jws, err := jwe.Decrypt(testPrivRSAKey1); assert.NoError(t, err) { - assert.Equal(t, []jose.Header{{ - Algorithm: string(jose.RS256), - ExtraHeaders: map[jose.HeaderKey]interface{}{ - jose.HeaderType: "JWT", - }, - }}, jws.Headers) - out := &testClaims{} - assert.NoError(t, jws.Claims(&testPrivRSAKey1.PublicKey, out)) - assert.Equal(t, &testClaims{"foo"}, out) - } - } - } - - b2 := SignedAndEncrypted(rsaSigner, encrypter).Claims(&invalidMarshalClaims{}) - _, err = b2.CompactSerialize() - assert.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.") - _, err = b2.FullSerialize() - assert.EqualError(t, err, "json: error calling MarshalJSON for type *jwt.invalidMarshalClaims: Failed marshaling invalid claims.") - - encrypter2, err := jose.NewEncrypter(jose.A128CBC_HS256, recipient, nil) - require.NoError(t, err, "Error creating encrypter.") - _, err = SignedAndEncrypted(rsaSigner, encrypter2).CompactSerialize() - assert.EqualError(t, err, "square/go-jose/jwt: expected content type to be JWT (cty header)") -} - -func TestBuilderHeadersSigner(t *testing.T) { - tests := []struct { - Keys []*rsa.PrivateKey - Claims interface{} - }{ - { - Keys: []*rsa.PrivateKey{testPrivRSAKey1}, - Claims: &Claims{Issuer: "foo"}, - }, - { - Keys: []*rsa.PrivateKey{testPrivRSAKey1, testPrivRSAKey2}, - Claims: &Claims{Issuer: "foo"}, - }, - } - - for i, tc := range tests { - wantKeyIDs := make([]string, len(tc.Keys)) - signingKeys := make([]jose.SigningKey, len(tc.Keys)) - - for j, key := range tc.Keys { - keyIDBytes := make([]byte, 20) - if _, err := io.ReadFull(rand.Reader, keyIDBytes); err != nil { - t.Fatalf("failed to read random bytes: %v", err) - } - keyID := hex.EncodeToString(keyIDBytes) - - wantKeyIDs[j] = keyID - signingKeys[j] = jose.SigningKey{ - Algorithm: jose.RS256, - Key: &jose.JSONWebKey{ - KeyID: keyID, - Algorithm: "RSA", - Key: key, - }, - } - } - - signer, err := jose.NewMultiSigner(signingKeys, nil) - if err != nil { - t.Errorf("case %d: NewMultiSigner(): %v", i, err) - continue - } - - var token string - if len(tc.Keys) == 1 { - token, err = Signed(signer).Claims(tc.Claims).CompactSerialize() - } else { - token, err = Signed(signer).Claims(tc.Claims).FullSerialize() - } - if err != nil { - t.Errorf("case %d: failed to create token: %v", i, err) - continue - } - jws, err := jose.ParseSigned(token) - if err != nil { - t.Errorf("case %d: parse signed: %v", i, err) - continue - } - gotKeyIDs := make([]string, len(jws.Signatures)) - for i, sig := range jws.Signatures { - gotKeyIDs[i] = sig.Header.KeyID - } - sort.Strings(wantKeyIDs) - sort.Strings(gotKeyIDs) - if !reflect.DeepEqual(wantKeyIDs, gotKeyIDs) { - t.Errorf("case %d: wanted=%q got=%q", i, wantKeyIDs, gotKeyIDs) - } - } -} - -func TestBuilderHeadersEncrypter(t *testing.T) { - key := testPrivRSAKey1 - claims := &Claims{Issuer: "foo"} - - keyIDBytes := make([]byte, 20) - if _, err := io.ReadFull(rand.Reader, keyIDBytes); err != nil { - t.Fatalf("failed to read random bytes: %v", err) - } - keyID := hex.EncodeToString(keyIDBytes) - - wantKeyID := keyID - recipient := jose.Recipient{ - Algorithm: jose.RSA1_5, - Key: key.Public(), - KeyID: keyID, - } - - wantType := jose.ContentType("JWT") - encrypter, err := jose.NewEncrypter(jose.A128CBC_HS256, recipient, (&jose.EncrypterOptions{}).WithType(wantType)) - require.NoError(t, err, "failed to create encrypter") - - token, err := Encrypted(encrypter).Claims(claims).CompactSerialize() - require.NoError(t, err, "failed to create token") - - jwe, err := jose.ParseEncrypted(token) - if assert.NoError(t, err, "error parsing encrypted token") { - assert.Equal(t, jose.Header{ - ExtraHeaders: map[jose.HeaderKey]interface{}{ - jose.HeaderType: string(wantType), - "enc": "A128CBC-HS256", - }, - Algorithm: string(jose.RSA1_5), - KeyID: wantKeyID, - }, jwe.Header) - } -} - -func BenchmarkMapClaims(b *testing.B) { - m := map[string]interface{}{ - "sub": "42", - "iat": 1451606400, - "iss": "issuer", - "aud": []string{"a1", "a2"}, - } - - for i := 0; i < b.N; i++ { - Signed(rsaSigner).Claims(m) - } -} - -func BenchmarkStructClaims(b *testing.B) { - for i := 0; i < b.N; i++ { - Signed(rsaSigner).Claims(sampleClaims) - } -} - -func BenchmarkSignedCompactSerializeRSA(b *testing.B) { - tb := Signed(rsaSigner).Claims(sampleClaims) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - tb.CompactSerialize() - } -} - -func BenchmarkSignedCompactSerializeSHA(b *testing.B) { - tb := Signed(hmacSigner).Claims(sampleClaims) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - tb.CompactSerialize() - } -} - -func mustUnmarshalRSA(data string) *rsa.PrivateKey { - block, _ := pem.Decode([]byte(data)) - if block == nil { - panic("failed to decode PEM data") - } - key, err := x509.ParsePKCS8PrivateKey(block.Bytes) - if err != nil { - panic("failed to parse RSA key: " + err.Error()) - } - if key, ok := key.(*rsa.PrivateKey); ok { - return key - } - panic("key is not of type *rsa.PrivateKey") -} - -func mustMakeSigner(alg jose.SignatureAlgorithm, k interface{}) jose.Signer { - sig, err := jose.NewSigner(jose.SigningKey{Algorithm: alg, Key: k}, (&jose.SignerOptions{}).WithType("JWT")) - if err != nil { - panic("failed to create signer:" + err.Error()) - } - - return sig -} - -var ( - sharedKey = []byte("secret") - sharedEncryptionKey = []byte("itsa16bytesecret") - - testPrivRSAKey1 = mustUnmarshalRSA(`-----BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDIHBvDHAr7jh8h -xaqBCl11fjI9YZtdC5b3HtXTXZW3c2dIOImNUjffT8POP6p5OpzivmC1om7iOyuZ -3nJjC9LT3zqqs3f2i5d4mImxEuqG6uWdryFfkp0uIv5VkjVO+iQWd6pDAPGP7r1Z -foXCleyCtmyNH4JSkJneNPOk/4BxO8vcvRnCMT/Gv81IT6H+OQ6OovWOuJr8RX9t -1wuCjC9ezZxeI9ONffhiO5FMrVh5H9LJTl3dPOVa4aEcOvgd45hBmvxAyXqf8daE -6Kl2O7vQ4uwgnSTVXYIIjCjbepuersApIMGx/XPSgiU1K3Xtah/TBvep+S3VlwPc -q/QH25S9AgMBAAECggEAe+y8XKYfPw4SxY1uPB+5JSwT3ON3nbWxtjSIYy9Pqp5z -Vcx9kuFZ7JevQSk4X38m7VzM8282kC/ono+d8yy9Uayq3k/qeOqV0X9Vti1qxEbw -ECkG1/MqGApfy4qSLOjINInDDV+mOWa2KJgsKgdCwuhKbVMYGB2ozG2qfYIlfvlY -vLcBEpGWmswJHNmkcjTtGFIyJgPbsI6ndkkOeQbqQKAaadXtG1xUzH+vIvqaUl/l -AkNf+p4qhPkHsoAWXf1qu9cYa2T8T+mEo79AwlgVC6awXQWNRTiyClDJC7cu6NBy -ZHXCLFMbalzWF9qeI2OPaFX2x3IBWrbyDxcJ4TSdQQKBgQD/Fp/uQonMBh1h4Vi4 -HlxZdqSOArTitXValdLFGVJ23MngTGV/St4WH6eRp4ICfPyldsfcv6MZpNwNm1Rn -lB5Gtpqpby1dsrOSfvVbY7U3vpLnd8+hJ/lT5zCYt5Eor46N6iWRkYWzNe4PixiF -z1puGUvFCbZdeeACVrPLmW3JKQKBgQDI0y9WTf8ezKPbtap4UEE6yBf49ftohVGz -p4iD6Ng1uqePwKahwoVXKOc179CjGGtW/UUBORAoKRmxdHajHq6LJgsBxpaARz21 -COPy99BUyp9ER5P8vYn63lC7Cpd/K7uyMjaz1DAzYBZIeVZHIw8O9wuGNJKjRFy9 -SZyD3V0ddQKBgFMdohrWH2QVEfnUnT3Q1rJn0BJdm2bLTWOosbZ7G72TD0xAWEnz -sQ1wXv88n0YER6X6YADziEdQykq8s/HT91F/KkHO8e83zP8M0xFmGaQCOoelKEgQ -aFMIX3NDTM7+9OoUwwz9Z50PE3SJFAJ1n7eEEoYvNfabQXxBl+/dHEKRAoGAPEvU -EaiXacrtg8EWrssB2sFLGU/ZrTciIbuybFCT4gXp22pvXXAHEvVP/kzDqsRhLhwb -BNP6OuSkNziNikpjA5pngZ/7fgZly54gusmW/m5bxWdsUl0iOXVYbeAvPlqGH2me -LP4Pfs1hw17S/cbT9Z1NE31jbavP4HFikeD73SUCgYEArQfuudml6ei7XZ1Emjq8 -jZiD+fX6e6BD/ISatVnuyZmGj9wPFsEhY2BpLiAMQHMDIvH9nlKzsFvjkTPB86qG -jCh3D67Os8eSBk5uRC6iW3Fc4DXvB5EFS0W9/15Sl+V5vXAcrNMpYS82OTSMG2Gt -b9Ym/nxaqyTu0PxajXkKm5Q= ------END PRIVATE KEY-----`) - - testPrivRSAKey2 = mustUnmarshalRSA(`-----BEGIN PRIVATE KEY----- -MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCxJ09jkXZ5Okyq -FrEKrs+GTzZRvoLziyzDTIZLJC6BVryau4gaFjuBG+pnm4z53oDP0XVnjFsx1mBw -R6RHeXlXbxLXsMfJpMzU9I2SRen9DokpD187CAnjLOoN9QRl1h8CA+sqR5Jw9mdl -mdaBKC99M9QYAPK3vGNfPC4soo8LDSBiemmt5raL4WSfoYh/6qg5rHUTymY28uxV -ew3I9Yp+3ltIw+WlRDtW5l+MM5CSUofjj2zcgcG3LEuPtvyZ+CSObxxcZZugm9zc -JdiazNyUxtX8yAj3Xg8Hde0jt0QDXv7A+U0KMVi9lX6PJEaNj4tOhOmQhJVMzAyr -1W/bifZVAgMBAAECggEAduKnn21GMZLTUi4KP94SvNK55F/Sp7hVoPbhBNpSL1BT -IBAMBV24LyvZwhAcqq8MiOrLPGNv6+EvNQqPD7xQl0GeRouHeCYVpDA+NdSfc8jm -eVysjwQVBpTkudsdSW5JvuN8VRJVD2P8/a0gy+p4/C/k/Prd6DoQAiBz6FZrYoEd -iYgIegHOMXWd4vzO3ENOWSIUI6ci7Aro+Y0Z75kfiVokAGhUcFgrZ58E82fBYh8I -cxO20oMnucGrLicQzj536jx4wX3Cdd4jr9UVEJ9ZII1ldlp03nZlFLXqJH1547Aq -ZM+3vVcBGoJ8T9ZQ4VDAL++0K2DLC9JkTARAYCEi/QKBgQDebIc1+2zblhQtVQ/e -IbEErZcB7v+TkUoRoBfR0lj7bKBFJgRe37fgu1xf95/s63okdnOw/OuQqtGmgx/J -TL3yULBdNcwTCRm41t+cqoGymjK0VRbqk6CWBId0E3r5TaCVWedk2JI2XwTvIJ1A -eDiqfJeDHUD44yaonwbysj9ZDwKBgQDL5VQfTppVaJk2PXNwhAkRQklZ8RFmt/7p -yA3dddQNdwMk4Fl8F7QuO1gBxDiHdnwIrlEOz6fTsM3LwIS+Q12P1vYFIhpo7HDB -wvjfMwCPxBIS4jI28RgcAf0VbZ/+CHAm6bb9iDwsjXhh1J5oOm5VKnju6/rPH/QY -+md40pnSWwKBgBnKPbdNquafNUG4XjmkcHEZa6wGuU20CAGZLYnfuP+WLdM2wET7 -7cc6ElDyVnHTL/twXKPF/85rcBm9lH7zzgZ9wqVcKoh+gqQDDjSNNLKv3Hc6cojK -i1E5vzb/Vz/290q5/PGdhv6U7+6GOpWSGwfxoGPMjY8OT5o3rkeP0XaTAoGBALLR -GQmr4eZtqZDMK+XNpjYgsDvVE7HGRCW7cY17vNFiQruglloiX778BJ7n+7uxye3D -EwuuSj15ncLHwKMsaW2w1GqEEi1azzjfSWxWSnPLPR6aifdtUfueMtsMHXio5dL6 -vaV0SXG5UI5b7eDy/bhrW0wOYRQtreIKGZz49jZpAoGBAIvxYngkLwmq6g6MmnAc -YK4oT6YAm2wfSy2mzpEQP5r1igp1rN7T46o7FMUPDLS9wK3ESAaIYe01qT6Yftcc -5qF+yiOGDTr9XQiHwe4BcyrNEMfUjDhDU5ao2gH8+t1VGr1KspLsUNbedrJwZsY4 -UCZVKEEDHzKfLO/iBgKjJQF7 ------END PRIVATE KEY-----`) - - rsaSigner = mustMakeSigner(jose.RS256, testPrivRSAKey1) - hmacSigner = mustMakeSigner(jose.HS256, sharedKey) -) diff --git a/vendor/gopkg.in/square/go-jose.v2/jwt/claims_test.go b/vendor/gopkg.in/square/go-jose.v2/jwt/claims_test.go deleted file mode 100644 index 6799aab237..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/jwt/claims_test.go +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * Copyright 2016 Zbigniew Mandziejewicz - * Copyright 2016 Square, 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 jwt - -import ( - "testing" - "time" - - "gopkg.in/square/go-jose.v2/json" - - "github.com/stretchr/testify/assert" -) - -func TestEncodeClaims(t *testing.T) { - now := time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC) - - c := Claims{ - Issuer: "issuer", - Subject: "subject", - Audience: Audience{"a1", "a2"}, - NotBefore: NewNumericDate(time.Time{}), - IssuedAt: NewNumericDate(now), - Expiry: NewNumericDate(now.Add(1 * time.Hour)), - } - - b, err := json.Marshal(c) - assert.NoError(t, err) - - expected := `{"iss":"issuer","sub":"subject","aud":["a1","a2"],"exp":1451610000,"iat":1451606400}` - assert.Equal(t, expected, string(b)) -} - -func TestDecodeClaims(t *testing.T) { - s := []byte(`{"iss":"issuer","sub":"subject","aud":["a1","a2"],"exp":1451610000,"iat":1451606400}`) - now := time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC) - - c := Claims{} - if err := json.Unmarshal(s, &c); assert.NoError(t, err) { - assert.Equal(t, "issuer", c.Issuer) - assert.Equal(t, "subject", c.Subject) - assert.Equal(t, Audience{"a1", "a2"}, c.Audience) - assert.True(t, now.Equal(c.IssuedAt.Time())) - assert.True(t, now.Add(1*time.Hour).Equal(c.Expiry.Time())) - } - - s2 := []byte(`{"aud": "a1"}`) - c2 := Claims{} - if err := json.Unmarshal(s2, &c2); assert.NoError(t, err) { - assert.Equal(t, Audience{"a1"}, c2.Audience) - } - - invalid := []struct { - Raw string - Err error - }{ - {`{"aud": 5}`, ErrUnmarshalAudience}, - {`{"aud": ["foo", 5, "bar"]}`, ErrUnmarshalAudience}, - {`{"exp": "invalid"}`, ErrUnmarshalNumericDate}, - } - - for _, v := range invalid { - c := Claims{} - assert.Equal(t, v.Err, json.Unmarshal([]byte(v.Raw), &c)) - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/jwt/example_test.go b/vendor/gopkg.in/square/go-jose.v2/jwt/example_test.go deleted file mode 100644 index bebe64da01..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/jwt/example_test.go +++ /dev/null @@ -1,340 +0,0 @@ -/*- - * Copyright 2016 Zbigniew Mandziejewicz - * Copyright 2016 Square, 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 jwt_test - -import ( - "fmt" - "strings" - "time" - - "crypto/rsa" - "crypto/x509" - "encoding/pem" - - "gopkg.in/square/go-jose.v2" - "gopkg.in/square/go-jose.v2/jwt" -) - -var sharedKey = []byte("secret") -var sharedEncryptionKey = []byte("itsa16bytesecret") -var signer, _ = jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: sharedKey}, &jose.SignerOptions{}) - -func ExampleParseSigned() { - raw := `eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.gpHyA1B1H6X4a4Edm9wo7D3X2v3aLSDBDG2_5BzXYe0` - tok, err := jwt.ParseSigned(raw) - if err != nil { - panic(err) - } - - out := jwt.Claims{} - if err := tok.Claims(sharedKey, &out); err != nil { - panic(err) - } - fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject) - // Output: iss: issuer, sub: subject -} - -func ExampleParseEncrypted() { - key := []byte("itsa16bytesecret") - raw := `eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..jg45D9nmr6-8awml.z-zglLlEw9MVkYHi-Znd9bSwc-oRGbqKzf9WjXqZxno.kqji2DiZHZmh-1bLF6ARPw` - tok, err := jwt.ParseEncrypted(raw) - if err != nil { - panic(err) - } - - out := jwt.Claims{} - if err := tok.Claims(key, &out); err != nil { - panic(err) - } - fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject) - // Output: iss: issuer, sub: subject -} - -func ExampleParseSignedAndEncrypted() { - raw := `eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIiwiY3R5IjoiSldUIn0..-keV-9YpsxotBEHw.yC9SHWgnkjykgJqXZGlzYC5Wg_EdWKO5TgfqeqsWWJYw7fX9zXQE3NtXmA3nAiUrYOr3H2s0AgTeAhTNbELLEHQu0blfRaPa_uKOAgFgmhJwbGe2iFLn9J0U72wk56318nI-pTLCV8FijoGpXvAxQlaKrPLKkl9yDQimPhb7UiDwLWYkJeoayciAXhR5f40E8ORGjCz8oawXRvjDaSjgRElUwy4kMGzvJy_difemEh4lfMSIwUNVEqJkEYaalRttSymMYuV6NvBVU0N0Jb6omdM4tW961OySB4KPWCWH9UJUX0XSEcqbW9WLxpg3ftx5R7xNiCnaVaCx_gJZfXJ9yFLqztIrKh2N05zHM0tddSOwCOnq7_1rJtaVz0nTXjSjf1RrVaxJya59p3K-e41QutiGFiJGzXG-L2OyLETIaVSU3ptvaCz4IxCF3GzeCvOgaICvXkpBY1-bv-fk1ilyjmcTDnLp2KivWIxcnoQmpN9xj06ZjagdG09AHUhS5WixADAg8mIdGcanNblALecnCWG-otjM9Kw.RZoaHtSgnzOin2od3D9tnA` - tok, err := jwt.ParseSignedAndEncrypted(raw) - if err != nil { - panic(err) - } - - nested, err := tok.Decrypt(sharedEncryptionKey) - if err != nil { - panic(err) - } - - out := jwt.Claims{} - if err := nested.Claims(&rsaPrivKey.PublicKey, &out); err != nil { - panic(err) - } - - fmt.Printf("iss: %s, sub: %s\n", out.Issuer, out.Subject) - // Output: iss: issuer, sub: subject -} - -func ExampleClaims_Validate() { - cl := jwt.Claims{ - Subject: "subject", - Issuer: "issuer", - NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)), - Expiry: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 15, 0, 0, time.UTC)), - Audience: jwt.Audience{"leela", "fry"}, - } - - err := cl.Validate(jwt.Expected{ - Issuer: "issuer", - Time: time.Date(2016, 1, 1, 0, 10, 0, 0, time.UTC), - }) - if err != nil { - panic(err) - } - - fmt.Printf("valid!") - // Output: valid! -} - -func ExampleClaims_Validate_withParse() { - raw := `eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.gpHyA1B1H6X4a4Edm9wo7D3X2v3aLSDBDG2_5BzXYe0` - tok, err := jwt.ParseSigned(raw) - if err != nil { - panic(err) - } - - cl := jwt.Claims{} - if err := tok.Claims(sharedKey, &cl); err != nil { - panic(err) - } - - err = cl.Validate(jwt.Expected{ - Issuer: "issuer", - Subject: "subject", - }) - if err != nil { - panic(err) - } - - fmt.Printf("valid!") - // Output: valid! -} - -func ExampleSigned() { - key := []byte("secret") - sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: key}, (&jose.SignerOptions{}).WithType("JWT")) - if err != nil { - panic(err) - } - - cl := jwt.Claims{ - Subject: "subject", - Issuer: "issuer", - NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)), - Audience: jwt.Audience{"leela", "fry"}, - } - raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize() - if err != nil { - panic(err) - } - - fmt.Println(raw) - // Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsibGVlbGEiLCJmcnkiXSwiaXNzIjoiaXNzdWVyIiwibmJmIjoxNDUxNjA2NDAwLCJzdWIiOiJzdWJqZWN0In0.4PgCj0VO-uG_cb1mNA38NjJyp0N-NdGIDLoYelEkciw -} - -func ExampleSigned_privateClaims() { - key := []byte("secret") - sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: key}, (&jose.SignerOptions{}).WithType("JWT")) - if err != nil { - panic(err) - } - - cl := jwt.Claims{ - Subject: "subject", - Issuer: "issuer", - NotBefore: jwt.NewNumericDate(time.Date(2016, 1, 1, 0, 0, 0, 0, time.UTC)), - Audience: jwt.Audience{"leela", "fry"}, - } - - // When setting private claims, make sure to add struct tags - // to specify how to serialize the field. The naming behavior - // should match the encoding/json package otherwise. - privateCl := struct { - CustomClaim string `json:"custom"` - }{ - "custom claim value", - } - - raw, err := jwt.Signed(sig).Claims(cl).Claims(privateCl).CompactSerialize() - if err != nil { - panic(err) - } - - fmt.Println(raw) - // Ouput: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsibGVlbGEiLCJmcnkiXSwiY3VzdG9tIjoiY3VzdG9tIGNsYWltIHZhbHVlIiwiaXNzIjoiaXNzdWVyIiwibmJmIjoxNDUxNjA2NDAwLCJzdWIiOiJzdWJqZWN0In0.knXH3ReNJToS5XI7BMCkk80ugpCup3tOy53xq-ga47o -} - -func ExampleEncrypted() { - enc, err := jose.NewEncrypter( - jose.A128GCM, - jose.Recipient{Algorithm: jose.DIRECT, Key: sharedEncryptionKey}, - (&jose.EncrypterOptions{}).WithType("JWT"), - ) - if err != nil { - panic(err) - } - - cl := jwt.Claims{ - Subject: "subject", - Issuer: "issuer", - } - raw, err := jwt.Encrypted(enc).Claims(cl).CompactSerialize() - if err != nil { - panic(err) - } - - fmt.Println(raw) -} - -func ExampleSignedAndEncrypted() { - enc, err := jose.NewEncrypter( - jose.A128GCM, - jose.Recipient{ - Algorithm: jose.DIRECT, - Key: sharedEncryptionKey, - }, - (&jose.EncrypterOptions{}).WithType("JWT").WithContentType("JWT")) - if err != nil { - panic(err) - } - - cl := jwt.Claims{ - Subject: "subject", - Issuer: "issuer", - } - raw, err := jwt.SignedAndEncrypted(rsaSigner, enc).Claims(cl).CompactSerialize() - if err != nil { - panic(err) - } - - fmt.Println(raw) -} - -func ExampleSigned_multipleClaims() { - c := &jwt.Claims{ - Subject: "subject", - Issuer: "issuer", - } - c2 := struct { - Scopes []string - }{ - []string{"foo", "bar"}, - } - raw, err := jwt.Signed(signer).Claims(c).Claims(c2).CompactSerialize() - if err != nil { - panic(err) - } - - fmt.Println(raw) - // Output: eyJhbGciOiJIUzI1NiJ9.eyJTY29wZXMiOlsiZm9vIiwiYmFyIl0sImlzcyI6Imlzc3VlciIsInN1YiI6InN1YmplY3QifQ.esKOIsmwkudr_gnfnB4SngxIr-7pspd5XzG3PImfQ6Y -} - -func ExampleJSONWebToken_Claims_map() { - raw := `eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJzdWIiOiJzdWJqZWN0In0.gpHyA1B1H6X4a4Edm9wo7D3X2v3aLSDBDG2_5BzXYe0` - tok, err := jwt.ParseSigned(raw) - if err != nil { - panic(err) - } - - out := make(map[string]interface{}) - if err := tok.Claims(sharedKey, &out); err != nil { - panic(err) - } - - fmt.Printf("iss: %s, sub: %s\n", out["iss"], out["sub"]) - // Output: iss: issuer, sub: subject -} - -func ExampleJSONWebToken_Claims_multiple() { - raw := `eyJhbGciOiJIUzI1NiJ9.eyJTY29wZXMiOlsiZm9vIiwiYmFyIl0sImlzcyI6Imlzc3VlciIsInN1YiI6InN1YmplY3QifQ.esKOIsmwkudr_gnfnB4SngxIr-7pspd5XzG3PImfQ6Y` - tok, err := jwt.ParseSigned(raw) - if err != nil { - panic(err) - } - - out := jwt.Claims{} - out2 := struct { - Scopes []string - }{} - if err := tok.Claims(sharedKey, &out, &out2); err != nil { - panic(err) - } - fmt.Printf("iss: %s, sub: %s, scopes: %s\n", out.Issuer, out.Subject, strings.Join(out2.Scopes, ",")) - // Output: iss: issuer, sub: subject, scopes: foo,bar -} - -func mustUnmarshalRSA(data string) *rsa.PrivateKey { - block, _ := pem.Decode([]byte(data)) - if block == nil { - panic("failed to decode PEM data") - } - key, err := x509.ParsePKCS8PrivateKey(block.Bytes) - if err != nil { - panic("failed to parse RSA key: " + err.Error()) - } - if key, ok := key.(*rsa.PrivateKey); ok { - return key - } - panic("key is not of type *rsa.PrivateKey") -} - -func mustMakeSigner(alg jose.SignatureAlgorithm, k interface{}) jose.Signer { - sig, err := jose.NewSigner(jose.SigningKey{Algorithm: alg, Key: k}, nil) - if err != nil { - panic("failed to create signer:" + err.Error()) - } - - return sig -} - -var rsaPrivKey = mustUnmarshalRSA(`-----BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDIHBvDHAr7jh8h -xaqBCl11fjI9YZtdC5b3HtXTXZW3c2dIOImNUjffT8POP6p5OpzivmC1om7iOyuZ -3nJjC9LT3zqqs3f2i5d4mImxEuqG6uWdryFfkp0uIv5VkjVO+iQWd6pDAPGP7r1Z -foXCleyCtmyNH4JSkJneNPOk/4BxO8vcvRnCMT/Gv81IT6H+OQ6OovWOuJr8RX9t -1wuCjC9ezZxeI9ONffhiO5FMrVh5H9LJTl3dPOVa4aEcOvgd45hBmvxAyXqf8daE -6Kl2O7vQ4uwgnSTVXYIIjCjbepuersApIMGx/XPSgiU1K3Xtah/TBvep+S3VlwPc -q/QH25S9AgMBAAECggEAe+y8XKYfPw4SxY1uPB+5JSwT3ON3nbWxtjSIYy9Pqp5z -Vcx9kuFZ7JevQSk4X38m7VzM8282kC/ono+d8yy9Uayq3k/qeOqV0X9Vti1qxEbw -ECkG1/MqGApfy4qSLOjINInDDV+mOWa2KJgsKgdCwuhKbVMYGB2ozG2qfYIlfvlY -vLcBEpGWmswJHNmkcjTtGFIyJgPbsI6ndkkOeQbqQKAaadXtG1xUzH+vIvqaUl/l -AkNf+p4qhPkHsoAWXf1qu9cYa2T8T+mEo79AwlgVC6awXQWNRTiyClDJC7cu6NBy -ZHXCLFMbalzWF9qeI2OPaFX2x3IBWrbyDxcJ4TSdQQKBgQD/Fp/uQonMBh1h4Vi4 -HlxZdqSOArTitXValdLFGVJ23MngTGV/St4WH6eRp4ICfPyldsfcv6MZpNwNm1Rn -lB5Gtpqpby1dsrOSfvVbY7U3vpLnd8+hJ/lT5zCYt5Eor46N6iWRkYWzNe4PixiF -z1puGUvFCbZdeeACVrPLmW3JKQKBgQDI0y9WTf8ezKPbtap4UEE6yBf49ftohVGz -p4iD6Ng1uqePwKahwoVXKOc179CjGGtW/UUBORAoKRmxdHajHq6LJgsBxpaARz21 -COPy99BUyp9ER5P8vYn63lC7Cpd/K7uyMjaz1DAzYBZIeVZHIw8O9wuGNJKjRFy9 -SZyD3V0ddQKBgFMdohrWH2QVEfnUnT3Q1rJn0BJdm2bLTWOosbZ7G72TD0xAWEnz -sQ1wXv88n0YER6X6YADziEdQykq8s/HT91F/KkHO8e83zP8M0xFmGaQCOoelKEgQ -aFMIX3NDTM7+9OoUwwz9Z50PE3SJFAJ1n7eEEoYvNfabQXxBl+/dHEKRAoGAPEvU -EaiXacrtg8EWrssB2sFLGU/ZrTciIbuybFCT4gXp22pvXXAHEvVP/kzDqsRhLhwb -BNP6OuSkNziNikpjA5pngZ/7fgZly54gusmW/m5bxWdsUl0iOXVYbeAvPlqGH2me -LP4Pfs1hw17S/cbT9Z1NE31jbavP4HFikeD73SUCgYEArQfuudml6ei7XZ1Emjq8 -jZiD+fX6e6BD/ISatVnuyZmGj9wPFsEhY2BpLiAMQHMDIvH9nlKzsFvjkTPB86qG -jCh3D67Os8eSBk5uRC6iW3Fc4DXvB5EFS0W9/15Sl+V5vXAcrNMpYS82OTSMG2Gt -b9Ym/nxaqyTu0PxajXkKm5Q= ------END PRIVATE KEY-----`) - -var rsaSigner = mustMakeSigner(jose.RS256, rsaPrivKey) diff --git a/vendor/gopkg.in/square/go-jose.v2/jwt/jwt_test.go b/vendor/gopkg.in/square/go-jose.v2/jwt/jwt_test.go deleted file mode 100644 index 130c283f88..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/jwt/jwt_test.go +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * Copyright 2016 Zbigniew Mandziejewicz - * Copyright 2016 Square, 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 jwt - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -var ( - hmacSignedToken = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdWJqZWN0IiwiaXNzIjoiaXNzdWVyIiwic2NvcGVzIjpbInMxIiwiczIiXX0.Y6_PfQHrzRJ_Vlxij5VI07-pgDIuJNN3Z_g5sSaGQ0c` - rsaSignedToken = `eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJpc3N1ZXIiLCJzY29wZXMiOlsiczEiLCJzMiJdLCJzdWIiOiJzdWJqZWN0In0.UDDtyK9gC9kyHltcP7E_XODsnqcJWZIiXeGmSAH7SE9YKy3N0KSfFIN85dCNjTfs6zvy4rkrCHzLB7uKAtzMearh3q7jL4nxbhUMhlUcs_9QDVoN4q_j58XmRqBqRnBk-RmDu9TgcV8RbErP4awpIhwWb5UU-hR__4_iNbHdKqwSUPDKYGlf5eicuiYrPxH8mxivk4LRD-vyRdBZZKBt0XIDnEU4TdcNCzAXojkftqcFWYsczwS8R4JHd1qYsMyiaWl4trdHZkO4QkeLe34z4ZAaPMt3wE-gcU-VoqYTGxz-K3Le2VaZ0r3j_z6bOInsv0yngC_cD1dCXMyQJWnWjQ` - invalidPayloadSignedToken = `eyJhbGciOiJIUzI1NiJ9.aW52YWxpZC1wYXlsb2Fk.ScBKKm18jcaMLGYDNRUqB5gVMRZl4DM6dh3ShcxeNgY` - invalidPartsSignedToken = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdWJqZWN0IiwiaXNzIjoiaXNzdWVyIiwic2NvcGVzIjpbInMxIiwiczIiXX0` - hmacEncryptedToken = `eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..NZrU98U4QNO0y-u6.HSq5CvlmkUT1BPqLGZ4.1-zuiZ4RbHrTTUoA8Dvfhg` - rsaEncryptedToken = `eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.IvkVHHiI8JwwavvTR80xGjYvkzubMrZ-TDDx8k8SNJMEylfFfNUc7F2rC3WAABF_xmJ3SW2A6on-S6EAG97k0RsjqHHNqZuaFpDvjeuLqZFfYKzI45aCtkGG4C2ij2GbeySqJ784CcvFJPUWJ-6VPN2Ho2nhefUSqig0jE2IvOKy1ywTj_VBVBxF_dyXFnXwxPKGUQr3apxrWeRJfDh2Cf8YPBlLiRznjfBfwgePB1jP7WCZNwItj10L7hsT_YWEx01XJcbxHaXFLwKyVzwWaDhreFyaWMRbGqEfqVuOT34zfmhLDhQlgLLwkXrvYqX90NsQ9Ftg0LLIfRMbsfdgug.BFy2Tj1RZN8yq2Lk-kMiZQ.9Z0eOyPiv5cEzmXh64RlAQ36Uvz0WpZgqRcc2_69zHTmUOv0Vnl1I6ks8sTraUEvukAilolNBjBj47s0b4b-Og.VM8-eJg5ZsqnTqs0LtGX_Q` - invalidPayloadEncryptedToken = `eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..T4jCS4Yyw1GCH0aW.y4gFaMITdBs_QZM8RKrL.6MPyk1cMVaOJFoNGlEuaRQ` - invalidPartsEncryptedToken = `eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..NZrU98U4QNO0y-u6.HSq5CvlmkUT1BPqLGZ4` - signedAndEncryptedToken = `eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiY3R5IjoiSldUIn0.icnR7M1HSgMDaUnJhfzT5nLmT0eRPeNsKPkioNcyq9TZsm-LgbE7wZkNFGfQqYwvbmrZ3UpOhNkrq4n2KN3N1dtjH9TVxzfMxz2OMh0dRWUNMi58EMadhmIpH3PLyyaeDyd0dyHpOIRPFTAoOdn2GoO_flV5CvPMhgdVKYB3h3vQW-ZZDu4cOZwXAjTuThdoUZCNWFhJhXyj-PrKLyVpX6rE1o4X05IS8008SLZyx-PZlsUPyLs6CJi7Z4PzZRzOJTV00a-7UOi-fBKBZV5V8eRpWuzJ673pMALlRCBzrRin-JeEA_QnAejtMAHG7RSGP60easQN4I-0jLTQNNNynw.oFrO-5ZgRrnWmbkPsbyMiQ.BVaWUzlrdfhe0otPJpb3DGoDCT6-BOmN_Pgq5NOqVFYIAwG5pM4pf7TaiPUJeQLf0phbLgpT4RfJ20Zhwfc2MH5unCqc8TZEP2dOrYRhb8o-X57x6IQppIDbjK2i_CAWf3yF5JUB7qRqOizpKZTh3HFTVEglY3WF8tAJ8KpnatTUmwcnqlyjdBFvYu4usiyvc_u9wNbXx5-lFt0slQYleHQMUirBprKyswIBjMoFJEe7kDvU_MCKI4NI9_fSfWJpaUdNxQEvRYR1PV4ZQdwBY0X9u2n2QH5iVQMrmgmQ5hPbWxwRv1-7jXBMPBpGeFQZHeEtSwif1_Umwyt8cDyRChb3OM7XQ3eY0UJRrbmvhcLWIcMp8FpblDaBinbjD6qIVXZVmaAdIbi2a_HblfoeL3-UABb82AAxOqQcAFjDEDTR2TFalDXSwgPZrAaQ_Mql3eFe9r2y0UVkgG7XYF4ik8sSK48CkZPUvkZFr-K9QMq-RZLzT3Zw0edxNaKgje27S26H9qClh6CCr9nk38AZZ76_Xz7f-Fil5xI0Dq95UzvwW__U3JJWE6OVUVx_RVJgdOJn8_B7hluckwBLUblscA.83pPXNnH0sKgHvFboiJVDA` - invalidSignedAndEncryptedToken = `eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.QKYu3DkFEXBUa2U0Sgtm-e44BMuaFVbMu2T-GB3qEGONrmOuaB5BtNCvBUnuj6HR0v6u-tvawToRSzExQQLFTvPcLiQR8iclWirqAFUqLrg8kRU3qIRLkmErYeGIfCML1jq9ofKg0DI5-YrU5RSyUg9cwfXKEx8KNwFcjeVeDZwWEACdU8xBnQp57rNfr0Tj-dPnGKID7LU5ZV0vhK90FpEG7UqOeSHFmvONQyz6Ca-ZkE8X2swqGad-q5xl8f9pApdFqHzADox5OlgtxPkr-Khkm6WGfvf1K_e-iW5LYtvWIAjNByft2TexsNcYpdAO2oNAgh2nkhoohl-zCWU-og.UAU65JWKqvHZ_Z0V-xLyjQ.M6sQ4lAzKFelSmL6C6uoK00rB8IFCAK-eJ0iByGhtg8eYtmSBFsP_oUySfKPtxcPRkQ7YxnEX5D-DOo20wCV7il2Be9No__0R6_5heISOMXcKmKP3D6pFusaPisNGOgLw8SKXBuVpe20PvOJ9RgOXRKucSR2UMINXtqIn9RdxbKOlBBmMJhnX4TeQ00fRILng2sMbUHsWExSthQODHGx6VcwLFp-Aqmsnv2q2KkLpA8sEm48AHHFQXSGtlVGVgWKi3dOQYUnDJW4P64Xxr1Uq3yT7w_dRwK4BA7l3Biecj5dwkKrFMJ_RaCt-ED_R15zpxg6PmnXeeJnif58Fai40ZWOsGvLZNYwL1jbi-TrsargpdUQedfzuTk8Na2NkCzFNg2BYXVDHJ_WAX1daVyhvunaURwAlBatAcmnOGxWebwV1xQoQ7iHg6ZGohCannn_pqGwJlMHMgnCcnCIhwfj9uL9Ejz_TVceZNMlT1KvLRafVfxGhkp48bdnd8OcXmjT9pQzZUB3OqrstWKhbItZ1xMpy6dZ54ldWvtTTyQ4tQJaVWgXERUM1erDT6Ypyl15-fumOB9MRcgMG3NDblKowA.P9WTBITvVUgrLjX6bS0opQ` -) - -type customClaims struct { - Scopes []string `json:"scopes,omitempty"` -} - -func TestDecodeToken(t *testing.T) { - tok, err := ParseSigned(hmacSignedToken) - if assert.NoError(t, err, "Error parsing signed token.") { - c := &Claims{} - c2 := &customClaims{} - if assert.NoError(t, tok.Claims(sharedKey, c, c2)) { - assert.Equal(t, "subject", c.Subject) - assert.Equal(t, "issuer", c.Issuer) - assert.Equal(t, []string{"s1", "s2"}, c2.Scopes) - } - } - assert.EqualError(t, tok.Claims([]byte("invalid-secret")), "square/go-jose: error in cryptographic primitive") - - tok2, err := ParseSigned(rsaSignedToken) - if assert.NoError(t, err, "Error parsing encrypted token.") { - c := make(map[string]interface{}) - if assert.NoError(t, tok2.Claims(&testPrivRSAKey1.PublicKey, &c)) { - assert.Equal(t, map[string]interface{}{ - "sub": "subject", - "iss": "issuer", - "scopes": []interface{}{"s1", "s2"}, - }, c) - } - } - assert.EqualError(t, tok.Claims(&testPrivRSAKey2.PublicKey), "square/go-jose: error in cryptographic primitive") - - tok3, err := ParseSigned(invalidPayloadSignedToken) - if assert.NoError(t, err, "Error parsing signed token.") { - assert.Error(t, tok3.Claims(sharedKey, &Claims{}), "Expected unmarshaling claims to fail.") - } - - _, err = ParseSigned(invalidPartsSignedToken) - assert.EqualError(t, err, "square/go-jose: compact JWS format must have three parts") - - tok4, err := ParseEncrypted(hmacEncryptedToken) - if assert.NoError(t, err, "Error parsing encrypted token.") { - c := Claims{} - if assert.NoError(t, tok4.Claims(sharedEncryptionKey, &c)) { - assert.Equal(t, "foo", c.Subject) - } - } - assert.EqualError(t, tok4.Claims([]byte("invalid-secret-key")), "square/go-jose: error in cryptographic primitive") - - tok5, err := ParseEncrypted(rsaEncryptedToken) - if assert.NoError(t, err, "Error parsing encrypted token.") { - c := make(map[string]interface{}) - if assert.NoError(t, tok5.Claims(testPrivRSAKey1, &c)) { - assert.Equal(t, map[string]interface{}{ - "sub": "subject", - "iss": "issuer", - "scopes": []interface{}{"s1", "s2"}, - }, c) - } - } - assert.EqualError(t, tok5.Claims(testPrivRSAKey2), "square/go-jose: error in cryptographic primitive") - - tok6, err := ParseEncrypted(invalidPayloadEncryptedToken) - if assert.NoError(t, err, "Error parsing encrypted token.") { - assert.Error(t, tok6.Claims(sharedEncryptionKey, &Claims{})) - } - - _, err = ParseEncrypted(invalidPartsEncryptedToken) - assert.EqualError(t, err, "square/go-jose: compact JWE format must have five parts") - - tok7, err := ParseSignedAndEncrypted(signedAndEncryptedToken) - if assert.NoError(t, err, "Error parsing signed-then-encrypted token.") { - c := make(map[string]interface{}) - if nested, err := tok7.Decrypt(testPrivRSAKey1); assert.NoError(t, err) { - assert.NoError(t, nested.Claims(testPrivRSAKey1.Public(), &c)) - assert.Equal(t, map[string]interface{}{ - "sub": "subject", - "iss": "issuer", - "scopes": []interface{}{"s1", "s2"}, - }, c) - assert.EqualError(t, nested.Claims(testPrivRSAKey2.Public()), "square/go-jose: error in cryptographic primitive") - } - } - _, err = tok7.Decrypt(testPrivRSAKey2) - assert.EqualError(t, err, "square/go-jose: error in cryptographic primitive") - - _, err = ParseSignedAndEncrypted(invalidSignedAndEncryptedToken) - assert.EqualError(t, err, "square/go-jose/jwt: expected content type to be JWT (cty header)") -} - -func BenchmarkDecodeSignedToken(b *testing.B) { - for i := 0; i < b.N; i++ { - ParseSigned(hmacSignedToken) - } -} - -func BenchmarkDecodeEncryptedHMACToken(b *testing.B) { - for i := 0; i < b.N; i++ { - ParseEncrypted(hmacEncryptedToken) - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/jwt/validation_test.go b/vendor/gopkg.in/square/go-jose.v2/jwt/validation_test.go deleted file mode 100644 index 7df850f792..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/jwt/validation_test.go +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * Copyright 2016 Zbigniew Mandziejewicz - * Copyright 2016 Square, 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 jwt - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -func TestFieldsMatch(t *testing.T) { - c := Claims{ - Issuer: "issuer", - Subject: "subject", - Audience: []string{"a1", "a2"}, - ID: "42", - } - - valid := []Expected{ - {Issuer: "issuer"}, - {Subject: "subject"}, - {Audience: Audience{"a1", "a2"}}, - {Audience: Audience{"a2", "a1"}}, - {ID: "42"}, - } - - for _, v := range valid { - assert.NoError(t, c.Validate(v)) - } - - invalid := []struct { - Expected Expected - Error error - }{ - {Expected{Issuer: "invalid-issuer"}, ErrInvalidIssuer}, - {Expected{Subject: "invalid-subject"}, ErrInvalidSubject}, - {Expected{Audience: Audience{"invalid-audience"}}, ErrInvalidAudience}, - {Expected{ID: "invalid-id"}, ErrInvalidID}, - } - - for _, v := range invalid { - assert.Equal(t, v.Error, c.Validate(v.Expected)) - } -} - -func TestExpiryAndNotBefore(t *testing.T) { - now := time.Date(2016, 1, 1, 12, 0, 0, 0, time.UTC) - twelveHoursAgo := now.Add(-12 * time.Hour) - - c := Claims{ - IssuedAt: NewNumericDate(twelveHoursAgo), - NotBefore: NewNumericDate(twelveHoursAgo), - Expiry: NewNumericDate(now), - } - - // expired - default leeway (1 minute) - assert.NoError(t, c.Validate(Expected{Time: now})) - err := c.Validate(Expected{Time: now.Add(2 * DefaultLeeway)}) - if assert.Error(t, err) { - assert.Equal(t, err, ErrExpired) - } - - // expired - no leeway - assert.NoError(t, c.ValidateWithLeeway(Expected{Time: now}, 0)) - err = c.ValidateWithLeeway(Expected{Time: now.Add(1 * time.Second)}, 0) - if assert.Error(t, err) { - assert.Equal(t, err, ErrExpired) - } - - // not before - default leeway (1 minute) - assert.NoError(t, c.Validate(Expected{Time: twelveHoursAgo})) - err = c.Validate(Expected{Time: twelveHoursAgo.Add(-2 * DefaultLeeway)}) - if assert.Error(t, err) { - assert.Equal(t, err, ErrNotValidYet) - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/signing_test.go b/vendor/gopkg.in/square/go-jose.v2/signing_test.go deleted file mode 100644 index 4ed2482e86..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/signing_test.go +++ /dev/null @@ -1,523 +0,0 @@ -/*- - * Copyright 2014 Square 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 jose - -import ( - "bytes" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "fmt" - "io" - "reflect" - "testing" - - "gopkg.in/square/go-jose.v2/json" -) - -type staticNonceSource string - -func (sns staticNonceSource) Nonce() (string, error) { - return string(sns), nil -} - -func RoundtripJWS(sigAlg SignatureAlgorithm, serializer func(*JSONWebSignature) (string, error), corrupter func(*JSONWebSignature), signingKey interface{}, verificationKey interface{}, nonce string) error { - opts := &SignerOptions{} - if nonce != "" { - opts.NonceSource = staticNonceSource(nonce) - } - - signer, err := NewSigner(SigningKey{Algorithm: sigAlg, Key: signingKey}, opts) - if err != nil { - return fmt.Errorf("error on new signer: %s", err) - } - - input := []byte("Lorem ipsum dolor sit amet") - obj, err := signer.Sign(input) - if err != nil { - return fmt.Errorf("error on sign: %s", err) - } - - msg, err := serializer(obj) - if err != nil { - return fmt.Errorf("error on serialize: %s", err) - } - - obj, err = ParseSigned(msg) - if err != nil { - return fmt.Errorf("error on parse: %s", err) - } - - // (Maybe) mangle the object - corrupter(obj) - - output, err := obj.Verify(verificationKey) - if err != nil { - return fmt.Errorf("error on verify: %s", err) - } - - // Check that verify works with embedded keys (if present) - for i, sig := range obj.Signatures { - if sig.Header.JSONWebKey != nil { - _, err = obj.Verify(sig.Header.JSONWebKey) - if err != nil { - return fmt.Errorf("error on verify with embedded key %d: %s", i, err) - } - } - - // Check that the nonce correctly round-tripped (if present) - if sig.Header.Nonce != nonce { - return fmt.Errorf("Incorrect nonce returned: [%s]", sig.Header.Nonce) - } - } - - if bytes.Compare(output, input) != 0 { - return fmt.Errorf("input/output do not match, got '%s', expected '%s'", output, input) - } - - return nil -} - -func TestRoundtripsJWS(t *testing.T) { - // Test matrix - sigAlgs := []SignatureAlgorithm{RS256, RS384, RS512, PS256, PS384, PS512, HS256, HS384, HS512, ES256, ES384, ES512, EdDSA} - - serializers := []func(*JSONWebSignature) (string, error){ - func(obj *JSONWebSignature) (string, error) { return obj.CompactSerialize() }, - func(obj *JSONWebSignature) (string, error) { return obj.FullSerialize(), nil }, - } - - corrupter := func(obj *JSONWebSignature) {} - - for _, alg := range sigAlgs { - signingKey, verificationKey := GenerateSigningTestKey(alg) - - for i, serializer := range serializers { - err := RoundtripJWS(alg, serializer, corrupter, signingKey, verificationKey, "test_nonce") - if err != nil { - t.Error(err, alg, i) - } - } - } -} - -func TestRoundtripsJWSCorruptSignature(t *testing.T) { - // Test matrix - sigAlgs := []SignatureAlgorithm{RS256, RS384, RS512, PS256, PS384, PS512, HS256, HS384, HS512, ES256, ES384, ES512, EdDSA} - - serializers := []func(*JSONWebSignature) (string, error){ - func(obj *JSONWebSignature) (string, error) { return obj.CompactSerialize() }, - func(obj *JSONWebSignature) (string, error) { return obj.FullSerialize(), nil }, - } - - corrupters := []func(*JSONWebSignature){ - func(obj *JSONWebSignature) { - // Changes bytes in signature - obj.Signatures[0].Signature[10]++ - }, - func(obj *JSONWebSignature) { - // Set totally invalid signature - obj.Signatures[0].Signature = []byte("###") - }, - } - - // Test all different configurations - for _, alg := range sigAlgs { - signingKey, verificationKey := GenerateSigningTestKey(alg) - - for i, serializer := range serializers { - for j, corrupter := range corrupters { - err := RoundtripJWS(alg, serializer, corrupter, signingKey, verificationKey, "test_nonce") - if err == nil { - t.Error("failed to detect corrupt signature", err, alg, i, j) - } - } - } - } -} - -func TestSignerWithBrokenRand(t *testing.T) { - sigAlgs := []SignatureAlgorithm{RS256, RS384, RS512, PS256, PS384, PS512} - - serializer := func(obj *JSONWebSignature) (string, error) { return obj.CompactSerialize() } - corrupter := func(obj *JSONWebSignature) {} - - // Break rand reader - readers := []func() io.Reader{ - // Totally broken - func() io.Reader { return bytes.NewReader([]byte{}) }, - // Not enough bytes - func() io.Reader { return io.LimitReader(rand.Reader, 20) }, - } - - defer resetRandReader() - - for _, alg := range sigAlgs { - signingKey, verificationKey := GenerateSigningTestKey(alg) - for i, getReader := range readers { - randReader = getReader() - err := RoundtripJWS(alg, serializer, corrupter, signingKey, verificationKey, "test_nonce") - if err == nil { - t.Error("signer should fail if rand is broken", alg, i) - } - } - } -} - -func TestJWSInvalidKey(t *testing.T) { - signingKey0, verificationKey0 := GenerateSigningTestKey(RS256) - _, verificationKey1 := GenerateSigningTestKey(ES256) - _, verificationKey2 := GenerateSigningTestKey(EdDSA) - - signer, err := NewSigner(SigningKey{Algorithm: RS256, Key: signingKey0}, nil) - if err != nil { - panic(err) - } - - input := []byte("Lorem ipsum dolor sit amet") - obj, err := signer.Sign(input) - if err != nil { - panic(err) - } - - // Must work with correct key - _, err = obj.Verify(verificationKey0) - if err != nil { - t.Error("error on verify", err) - } - - // Must not work with incorrect key - _, err = obj.Verify(verificationKey1) - if err == nil { - t.Error("verification should fail with incorrect key") - } - - // Must not work with incorrect key - _, err = obj.Verify(verificationKey2) - if err == nil { - t.Error("verification should fail with incorrect key") - } - - // Must not work with invalid key - _, err = obj.Verify("") - if err == nil { - t.Error("verification should fail with incorrect key") - } -} - -func TestMultiRecipientJWS(t *testing.T) { - sharedKey := []byte{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - } - jwkSharedKey := JSONWebKey{ - KeyID: "123", - Key: sharedKey, - } - - signer, err := NewMultiSigner([]SigningKey{ - {RS256, rsaTestKey}, - {HS384, sharedKey}, - {HS512, jwkSharedKey}, - }, nil) - if err != nil { - t.Fatal("error creating signer: ", err) - } - - input := []byte("Lorem ipsum dolor sit amet") - obj, err := signer.Sign(input) - if err != nil { - t.Fatal("error on sign: ", err) - } - - _, err = obj.CompactSerialize() - if err == nil { - t.Fatal("message with multiple recipient was compact serialized") - } - - msg := obj.FullSerialize() - - obj, err = ParseSigned(msg) - if err != nil { - t.Fatal("error on parse: ", err) - } - - i, _, output, err := obj.VerifyMulti(&rsaTestKey.PublicKey) - if err != nil { - t.Fatal("error on verify: ", err) - } - - if i != 0 { - t.Fatal("signature index should be 0 for RSA key") - } - - if bytes.Compare(output, input) != 0 { - t.Fatal("input/output do not match", output, input) - } - - i, _, output, err = obj.VerifyMulti(sharedKey) - if err != nil { - t.Fatal("error on verify: ", err) - } - - if i != 1 { - t.Fatal("signature index should be 1 for EC key") - } - - if bytes.Compare(output, input) != 0 { - t.Fatal("input/output do not match", output, input) - } -} - -func GenerateSigningTestKey(sigAlg SignatureAlgorithm) (sig, ver interface{}) { - switch sigAlg { - case EdDSA: - sig = ed25519PrivateKey - ver = ed25519PublicKey - case RS256, RS384, RS512, PS256, PS384, PS512: - sig = rsaTestKey - ver = &rsaTestKey.PublicKey - case HS256, HS384, HS512: - sig, _, _ = randomKeyGenerator{size: 16}.genKey() - ver = sig - case ES256: - key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - sig = key - ver = &key.PublicKey - case ES384: - key, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) - sig = key - ver = &key.PublicKey - case ES512: - key, _ := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - sig = key - ver = &key.PublicKey - default: - panic("Must update test case") - } - - return -} - -func TestInvalidSignerAlg(t *testing.T) { - _, err := NewSigner(SigningKey{"XYZ", nil}, nil) - if err == nil { - t.Error("should not accept invalid algorithm") - } - - _, err = NewSigner(SigningKey{"XYZ", []byte{}}, nil) - if err == nil { - t.Error("should not accept invalid algorithm") - } -} - -func TestInvalidJWS(t *testing.T) { - signer, err := NewSigner(SigningKey{PS256, rsaTestKey}, nil) - if err != nil { - panic(err) - } - - obj, err := signer.Sign([]byte("Lorem ipsum dolor sit amet")) - obj.Signatures[0].header = &rawHeader{} - obj.Signatures[0].header.set(headerCritical, []string{"TEST"}) - - _, err = obj.Verify(&rsaTestKey.PublicKey) - if err == nil { - t.Error("should not verify message with unknown crit header") - } - - // Try without alg header - obj.Signatures[0].protected = &rawHeader{} - obj.Signatures[0].header = &rawHeader{} - - _, err = obj.Verify(&rsaTestKey.PublicKey) - if err == nil { - t.Error("should not verify message with missing headers") - } -} - -func TestSignerKid(t *testing.T) { - kid := "DEADBEEF" - payload := []byte("Lorem ipsum dolor sit amet") - - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Error("problem generating test signing key", err) - } - - basejwk := JSONWebKey{Key: key} - jsonbar, err := basejwk.MarshalJSON() - if err != nil { - t.Error("problem marshalling base JWK", err) - } - - var jsonmsi map[string]interface{} - err = json.Unmarshal(jsonbar, &jsonmsi) - if err != nil { - t.Error("problem unmarshalling base JWK", err) - } - jsonmsi["kid"] = kid - jsonbar2, err := json.Marshal(jsonmsi) - if err != nil { - t.Error("problem marshalling kided JWK", err) - } - - var jwk JSONWebKey - err = jwk.UnmarshalJSON(jsonbar2) - if err != nil { - t.Error("problem unmarshalling kided JWK", err) - } - - signer, err := NewSigner(SigningKey{ES256, &jwk}, nil) - if err != nil { - t.Error("problem creating signer with *JSONWebKey", err) - } - signed, err := signer.Sign(payload) - - serialized := signed.FullSerialize() - - parsed, err := ParseSigned(serialized) - if err != nil { - t.Error("problem parsing signed object", err) - } - - if parsed.Signatures[0].Header.KeyID != kid { - t.Error("KeyID did not survive trip") - } - - signer, err = NewSigner(SigningKey{ES256, jwk}, nil) - if err != nil { - t.Error("problem creating signer with JSONWebKey", err) - } -} - -func TestEmbedJwk(t *testing.T) { - var payload = []byte("Lorem ipsum dolor sit amet") - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Error("Failed to generate key") - } - - signer, err := NewSigner(SigningKey{ES256, key}, &SignerOptions{EmbedJWK: true}) - if err != nil { - t.Error("Failed to create signer") - } - - object, err := signer.Sign(payload) - if err != nil { - t.Error("Failed to sign payload") - } - - object, err = ParseSigned(object.FullSerialize()) - if err != nil { - t.Error("Failed to parse jws") - } - - jwk, err := object.Signatures[0].protected.getJWK() - if jwk == nil || err != nil { - t.Error("JWK isn't set in protected header") - } - - // This time, sign and do not embed JWK in message - signer, err = NewSigner(SigningKey{ES256, key}, &SignerOptions{EmbedJWK: false}) - - object, err = signer.Sign(payload) - if err != nil { - t.Error("Failed to sign payload") - } - - object, err = ParseSigned(object.FullSerialize()) - if err != nil { - t.Error("Failed to parse jws") - } - - jwk2, err := object.Signatures[0].protected.getJWK() - if err != nil { - t.Error("JWK is invalid in protected header") - } - if jwk2 != nil { - t.Error("JWK is set in protected header") - } -} - -func TestSignerOptionsEd(t *testing.T) { - key, _ := GenerateSigningTestKey(EdDSA) - opts := &SignerOptions{ - EmbedJWK: true, - } - opts.WithContentType("JWT") - opts.WithType("JWT") - sig, err := NewSigner(SigningKey{EdDSA, key}, opts) - if err != nil { - t.Error("Failed to create signer") - } - - if !reflect.DeepEqual(*opts, sig.Options()) { - t.Error("Signer options do not match") - } -} - -func TestSignerOptions(t *testing.T) { - key, _ := GenerateSigningTestKey(HS256) - opts := &SignerOptions{ - EmbedJWK: true, - } - opts.WithContentType("JWT") - opts.WithType("JWT") - sig, err := NewSigner(SigningKey{HS256, key}, opts) - if err != nil { - t.Error("Failed to create signer") - } - - if !reflect.DeepEqual(*opts, sig.Options()) { - t.Error("Signer options do not match") - } -} - -// Test that extra headers are generated and parsed in a round trip. -func TestSignerExtraHeaderInclusion(t *testing.T) { - var payload = []byte("Lorem ipsum dolor sit amet") - - key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Error("Failed to generate key") - } - - signer, err := NewSigner(SigningKey{ES256, key}, (&SignerOptions{}).WithContentType("foo/bar").WithHeader(HeaderKey("myCustomHeader"), "xyz")) - if err != nil { - t.Error("Failed to create signer", err) - } - - object, err := signer.Sign(payload) - if err != nil { - t.Error("Failed to sign payload") - } - - object, err = ParseSigned(object.FullSerialize()) - if err != nil { - t.Error("Failed to parse jws") - } - - correct := map[HeaderKey]interface{}{ - HeaderContentType: "foo/bar", - HeaderKey("myCustomHeader"): "xyz", - } - - if !reflect.DeepEqual(object.Signatures[0].Header.ExtraHeaders, correct) { - t.Errorf("Mismatch in extra headers: %#v", object.Signatures[0].Header.ExtraHeaders) - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/symmetric_test.go b/vendor/gopkg.in/square/go-jose.v2/symmetric_test.go deleted file mode 100644 index 67f535e3b5..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/symmetric_test.go +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * Copyright 2014 Square 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 jose - -import ( - "bytes" - "crypto/cipher" - "crypto/rand" - "io" - "testing" -) - -func TestInvalidSymmetricAlgorithms(t *testing.T) { - _, err := newSymmetricRecipient("XYZ", []byte{}) - if err != ErrUnsupportedAlgorithm { - t.Error("should not accept invalid algorithm") - } - - enc := &symmetricKeyCipher{} - _, err = enc.encryptKey([]byte{}, "XYZ") - if err != ErrUnsupportedAlgorithm { - t.Error("should not accept invalid algorithm") - } -} - -func TestAeadErrors(t *testing.T) { - aead := &aeadContentCipher{ - keyBytes: 16, - authtagBytes: 16, - getAead: func(key []byte) (cipher.AEAD, error) { - return nil, ErrCryptoFailure - }, - } - - parts, err := aead.encrypt([]byte{}, []byte{}, []byte{}) - if err != ErrCryptoFailure { - t.Error("should handle aead failure") - } - - _, err = aead.decrypt([]byte{}, []byte{}, parts) - if err != ErrCryptoFailure { - t.Error("should handle aead failure") - } -} - -func TestInvalidKey(t *testing.T) { - gcm := newAESGCM(16).(*aeadContentCipher) - _, err := gcm.getAead([]byte{}) - if err == nil { - t.Error("should not accept invalid key") - } -} - -func TestStaticKeyGen(t *testing.T) { - key := make([]byte, 32) - io.ReadFull(rand.Reader, key) - - gen := &staticKeyGenerator{key: key} - if gen.keySize() != len(key) { - t.Error("static key generator reports incorrect size") - } - - generated, _, err := gen.genKey() - if err != nil { - t.Error("static key generator should always succeed", err) - } - if !bytes.Equal(generated, key) { - t.Error("static key generator returns different data") - } -} - -func TestVectorsAESGCM(t *testing.T) { - // Source: http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-29#appendix-A.1 - plaintext := []byte{ - 84, 104, 101, 32, 116, 114, 117, 101, 32, 115, 105, 103, 110, 32, - 111, 102, 32, 105, 110, 116, 101, 108, 108, 105, 103, 101, 110, 99, - 101, 32, 105, 115, 32, 110, 111, 116, 32, 107, 110, 111, 119, 108, - 101, 100, 103, 101, 32, 98, 117, 116, 32, 105, 109, 97, 103, 105, - 110, 97, 116, 105, 111, 110, 46} - - aad := []byte{ - 101, 121, 74, 104, 98, 71, 99, 105, 79, 105, 74, 83, 85, 48, 69, - 116, 84, 48, 70, 70, 85, 67, 73, 115, 73, 109, 86, 117, 89, 121, 73, - 54, 73, 107, 69, 121, 78, 84, 90, 72, 81, 48, 48, 105, 102, 81} - - expectedCiphertext := []byte{ - 229, 236, 166, 241, 53, 191, 115, 196, 174, 43, 73, 109, 39, 122, - 233, 96, 140, 206, 120, 52, 51, 237, 48, 11, 190, 219, 186, 80, 111, - 104, 50, 142, 47, 167, 59, 61, 181, 127, 196, 21, 40, 82, 242, 32, - 123, 143, 168, 226, 73, 216, 176, 144, 138, 247, 106, 60, 16, 205, - 160, 109, 64, 63, 192} - - expectedAuthtag := []byte{ - 92, 80, 104, 49, 133, 25, 161, 215, 173, 101, 219, 211, 136, 91, 210, 145} - - // Mock random reader - randReader = bytes.NewReader([]byte{ - 177, 161, 244, 128, 84, 143, 225, 115, 63, 180, 3, 255, 107, 154, - 212, 246, 138, 7, 110, 91, 112, 46, 34, 105, 47, 130, 203, 46, 122, - 234, 64, 252, 227, 197, 117, 252, 2, 219, 233, 68, 180, 225, 77, 219}) - defer resetRandReader() - - enc := newAESGCM(32) - key, _, _ := randomKeyGenerator{size: 32}.genKey() - out, err := enc.encrypt(key, aad, plaintext) - if err != nil { - t.Error("Unable to encrypt:", err) - return - } - - if bytes.Compare(out.ciphertext, expectedCiphertext) != 0 { - t.Error("Ciphertext did not match") - } - if bytes.Compare(out.tag, expectedAuthtag) != 0 { - t.Error("Auth tag did not match") - } -} diff --git a/vendor/gopkg.in/square/go-jose.v2/utils_test.go b/vendor/gopkg.in/square/go-jose.v2/utils_test.go deleted file mode 100644 index 09440303df..0000000000 --- a/vendor/gopkg.in/square/go-jose.v2/utils_test.go +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * Copyright 2014 Square 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 jose - -import ( - "crypto/rand" - "encoding/base64" - "encoding/hex" - "math/big" - "regexp" -) - -// Reset random reader to original value -func resetRandReader() { - randReader = rand.Reader -} - -// Build big int from hex-encoded string. Strips whitespace (for testing). -func fromHexInt(base16 string) *big.Int { - re := regexp.MustCompile(`\s+`) - val, ok := new(big.Int).SetString(re.ReplaceAllString(base16, ""), 16) - if !ok { - panic("Invalid test data") - } - return val -} - -// Build big int from base64-encoded string. Strips whitespace (for testing). -func fromBase64Int(encoded string) *big.Int { - re := regexp.MustCompile(`\s+`) - val, err := base64.RawURLEncoding.DecodeString(re.ReplaceAllString(encoded, "")) - if err != nil { - panic("Invalid test data: " + err.Error()) - } - return new(big.Int).SetBytes(val) -} - -// Decode hex-encoded string into byte array. Strips whitespace (for testing). -func fromHexBytes(base16 string) []byte { - re := regexp.MustCompile(`\s+`) - val, err := hex.DecodeString(re.ReplaceAllString(base16, "")) - if err != nil { - panic("Invalid test data") - } - return val -} - -// Decode base64-encoded string into byte array. Strips whitespace (for testing). -func fromBase64Bytes(b64 string) []byte { - re := regexp.MustCompile(`\s+`) - val, err := base64.StdEncoding.DecodeString(re.ReplaceAllString(b64, "")) - if err != nil { - panic("Invalid test data") - } - return val -} diff --git a/vendor/gopkg.in/yaml.v2/.travis.yml b/vendor/gopkg.in/yaml.v2/.travis.yml index 004172a2e3..9f556934d8 100644 --- a/vendor/gopkg.in/yaml.v2/.travis.yml +++ b/vendor/gopkg.in/yaml.v2/.travis.yml @@ -4,6 +4,9 @@ go: - 1.4 - 1.5 - 1.6 + - 1.7 + - 1.8 + - 1.9 - tip go_import_path: gopkg.in/yaml.v2 diff --git a/images/grpc-fortune-teller/proto/fortune/doc.go b/vendor/gopkg.in/yaml.v2/NOTICE similarity index 79% rename from images/grpc-fortune-teller/proto/fortune/doc.go rename to vendor/gopkg.in/yaml.v2/NOTICE index 72244eda2a..866d74a7ad 100644 --- a/images/grpc-fortune-teller/proto/fortune/doc.go +++ b/vendor/gopkg.in/yaml.v2/NOTICE @@ -1,5 +1,4 @@ -/* -Copyright 2018 The Kubernetes Authors. +Copyright 2011-2016 Canonical Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -12,7 +11,3 @@ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -*/ - -// Package fortune acts as a placeholder f for generated *.pb.go files. -package fortune diff --git a/vendor/gopkg.in/yaml.v2/README.md b/vendor/gopkg.in/yaml.v2/README.md index 7a512d67c2..b50c6e8775 100644 --- a/vendor/gopkg.in/yaml.v2/README.md +++ b/vendor/gopkg.in/yaml.v2/README.md @@ -48,8 +48,6 @@ The yaml package is licensed under the Apache License 2.0. Please see the LICENS Example ------- -Some more examples can be found in the "examples" folder. - ```Go package main @@ -67,6 +65,8 @@ b: d: [3, 4] ` +// Note: struct fields must be public in order for unmarshal to +// correctly populate the data. type T struct { A string B struct { diff --git a/vendor/gopkg.in/yaml.v2/apic.go b/vendor/gopkg.in/yaml.v2/apic.go index 95ec014e8c..1f7e87e672 100644 --- a/vendor/gopkg.in/yaml.v2/apic.go +++ b/vendor/gopkg.in/yaml.v2/apic.go @@ -2,7 +2,6 @@ package yaml import ( "io" - "os" ) func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { @@ -48,9 +47,9 @@ func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err return n, nil } -// File read handler. -func yaml_file_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - return parser.input_file.Read(buffer) +// Reader read handler. +func yaml_reader_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { + return parser.input_reader.Read(buffer) } // Set a string input. @@ -64,12 +63,12 @@ func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { } // Set a file input. -func yaml_parser_set_input_file(parser *yaml_parser_t, file *os.File) { +func yaml_parser_set_input_reader(parser *yaml_parser_t, r io.Reader) { if parser.read_handler != nil { panic("must set the input source only once") } - parser.read_handler = yaml_file_read_handler - parser.input_file = file + parser.read_handler = yaml_reader_read_handler + parser.input_reader = r } // Set the source encoding. @@ -81,14 +80,13 @@ func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { } // Create a new emitter object. -func yaml_emitter_initialize(emitter *yaml_emitter_t) bool { +func yaml_emitter_initialize(emitter *yaml_emitter_t) { *emitter = yaml_emitter_t{ buffer: make([]byte, output_buffer_size), raw_buffer: make([]byte, 0, output_raw_buffer_size), states: make([]yaml_emitter_state_t, 0, initial_stack_size), events: make([]yaml_event_t, 0, initial_queue_size), } - return true } // Destroy an emitter object. @@ -102,9 +100,10 @@ func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { return nil } -// File write handler. -func yaml_file_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - _, err := emitter.output_file.Write(buffer) +// yaml_writer_write_handler uses emitter.output_writer to write the +// emitted text. +func yaml_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { + _, err := emitter.output_writer.Write(buffer) return err } @@ -118,12 +117,12 @@ func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]by } // Set a file output. -func yaml_emitter_set_output_file(emitter *yaml_emitter_t, file io.Writer) { +func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { if emitter.write_handler != nil { panic("must set the output target only once") } - emitter.write_handler = yaml_file_write_handler - emitter.output_file = file + emitter.write_handler = yaml_writer_write_handler + emitter.output_writer = w } // Set the output encoding. @@ -252,41 +251,41 @@ func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { // // Create STREAM-START. -func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) bool { +func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) { *event = yaml_event_t{ typ: yaml_STREAM_START_EVENT, encoding: encoding, } - return true } // Create STREAM-END. -func yaml_stream_end_event_initialize(event *yaml_event_t) bool { +func yaml_stream_end_event_initialize(event *yaml_event_t) { *event = yaml_event_t{ typ: yaml_STREAM_END_EVENT, } - return true } // Create DOCUMENT-START. -func yaml_document_start_event_initialize(event *yaml_event_t, version_directive *yaml_version_directive_t, - tag_directives []yaml_tag_directive_t, implicit bool) bool { +func yaml_document_start_event_initialize( + event *yaml_event_t, + version_directive *yaml_version_directive_t, + tag_directives []yaml_tag_directive_t, + implicit bool, +) { *event = yaml_event_t{ typ: yaml_DOCUMENT_START_EVENT, version_directive: version_directive, tag_directives: tag_directives, implicit: implicit, } - return true } // Create DOCUMENT-END. -func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) bool { +func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { *event = yaml_event_t{ typ: yaml_DOCUMENT_END_EVENT, implicit: implicit, } - return true } ///* @@ -348,7 +347,7 @@ func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { } // Create MAPPING-START. -func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) bool { +func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) { *event = yaml_event_t{ typ: yaml_MAPPING_START_EVENT, anchor: anchor, @@ -356,15 +355,13 @@ func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte implicit: implicit, style: yaml_style_t(style), } - return true } // Create MAPPING-END. -func yaml_mapping_end_event_initialize(event *yaml_event_t) bool { +func yaml_mapping_end_event_initialize(event *yaml_event_t) { *event = yaml_event_t{ typ: yaml_MAPPING_END_EVENT, } - return true } // Destroy an event object. @@ -471,7 +468,7 @@ func yaml_event_delete(event *yaml_event_t) { // } context // tag_directive *yaml_tag_directive_t // -// context.error = YAML_NO_ERROR // Eliminate a compliler warning. +// context.error = YAML_NO_ERROR // Eliminate a compiler warning. // // assert(document) // Non-NULL document object is expected. // diff --git a/vendor/gopkg.in/yaml.v2/decode.go b/vendor/gopkg.in/yaml.v2/decode.go index db1f5f2068..e4e56e28e0 100644 --- a/vendor/gopkg.in/yaml.v2/decode.go +++ b/vendor/gopkg.in/yaml.v2/decode.go @@ -4,6 +4,7 @@ import ( "encoding" "encoding/base64" "fmt" + "io" "math" "reflect" "strconv" @@ -22,19 +23,22 @@ type node struct { kind int line, column int tag string - value string - implicit bool - children []*node - anchors map[string]*node + // For an alias node, alias holds the resolved alias. + alias *node + value string + implicit bool + children []*node + anchors map[string]*node } // ---------------------------------------------------------------------------- // Parser, produces a node tree out of a libyaml event stream. type parser struct { - parser yaml_parser_t - event yaml_event_t - doc *node + parser yaml_parser_t + event yaml_event_t + doc *node + doneInit bool } func newParser(b []byte) *parser { @@ -42,21 +46,30 @@ func newParser(b []byte) *parser { if !yaml_parser_initialize(&p.parser) { panic("failed to initialize YAML emitter") } - if len(b) == 0 { b = []byte{'\n'} } - yaml_parser_set_input_string(&p.parser, b) + return &p +} - p.skip() - if p.event.typ != yaml_STREAM_START_EVENT { - panic("expected stream start event, got " + strconv.Itoa(int(p.event.typ))) +func newParserFromReader(r io.Reader) *parser { + p := parser{} + if !yaml_parser_initialize(&p.parser) { + panic("failed to initialize YAML emitter") } - p.skip() + yaml_parser_set_input_reader(&p.parser, r) return &p } +func (p *parser) init() { + if p.doneInit { + return + } + p.expect(yaml_STREAM_START_EVENT) + p.doneInit = true +} + func (p *parser) destroy() { if p.event.typ != yaml_NO_EVENT { yaml_event_delete(&p.event) @@ -64,16 +77,35 @@ func (p *parser) destroy() { yaml_parser_delete(&p.parser) } -func (p *parser) skip() { - if p.event.typ != yaml_NO_EVENT { - if p.event.typ == yaml_STREAM_END_EVENT { - failf("attempted to go past the end of stream; corrupted value?") +// expect consumes an event from the event stream and +// checks that it's of the expected type. +func (p *parser) expect(e yaml_event_type_t) { + if p.event.typ == yaml_NO_EVENT { + if !yaml_parser_parse(&p.parser, &p.event) { + p.fail() } - yaml_event_delete(&p.event) + } + if p.event.typ == yaml_STREAM_END_EVENT { + failf("attempted to go past the end of stream; corrupted value?") + } + if p.event.typ != e { + p.parser.problem = fmt.Sprintf("expected %s event but got %s", e, p.event.typ) + p.fail() + } + yaml_event_delete(&p.event) + p.event.typ = yaml_NO_EVENT +} + +// peek peeks at the next event in the event stream, +// puts the results into p.event and returns the event type. +func (p *parser) peek() yaml_event_type_t { + if p.event.typ != yaml_NO_EVENT { + return p.event.typ } if !yaml_parser_parse(&p.parser, &p.event) { p.fail() } + return p.event.typ } func (p *parser) fail() { @@ -81,6 +113,10 @@ func (p *parser) fail() { var line int if p.parser.problem_mark.line != 0 { line = p.parser.problem_mark.line + // Scanner errors don't iterate line before returning error + if p.parser.error == yaml_SCANNER_ERROR { + line++ + } } else if p.parser.context_mark.line != 0 { line = p.parser.context_mark.line } @@ -103,7 +139,8 @@ func (p *parser) anchor(n *node, anchor []byte) { } func (p *parser) parse() *node { - switch p.event.typ { + p.init() + switch p.peek() { case yaml_SCALAR_EVENT: return p.scalar() case yaml_ALIAS_EVENT: @@ -118,7 +155,7 @@ func (p *parser) parse() *node { // Happens when attempting to decode an empty buffer. return nil default: - panic("attempted to parse unknown event: " + strconv.Itoa(int(p.event.typ))) + panic("attempted to parse unknown event: " + p.event.typ.String()) } } @@ -134,19 +171,20 @@ func (p *parser) document() *node { n := p.node(documentNode) n.anchors = make(map[string]*node) p.doc = n - p.skip() + p.expect(yaml_DOCUMENT_START_EVENT) n.children = append(n.children, p.parse()) - if p.event.typ != yaml_DOCUMENT_END_EVENT { - panic("expected end of document event but got " + strconv.Itoa(int(p.event.typ))) - } - p.skip() + p.expect(yaml_DOCUMENT_END_EVENT) return n } func (p *parser) alias() *node { n := p.node(aliasNode) n.value = string(p.event.anchor) - p.skip() + n.alias = p.doc.anchors[n.value] + if n.alias == nil { + failf("unknown anchor '%s' referenced", n.value) + } + p.expect(yaml_ALIAS_EVENT) return n } @@ -156,29 +194,29 @@ func (p *parser) scalar() *node { n.tag = string(p.event.tag) n.implicit = p.event.implicit p.anchor(n, p.event.anchor) - p.skip() + p.expect(yaml_SCALAR_EVENT) return n } func (p *parser) sequence() *node { n := p.node(sequenceNode) p.anchor(n, p.event.anchor) - p.skip() - for p.event.typ != yaml_SEQUENCE_END_EVENT { + p.expect(yaml_SEQUENCE_START_EVENT) + for p.peek() != yaml_SEQUENCE_END_EVENT { n.children = append(n.children, p.parse()) } - p.skip() + p.expect(yaml_SEQUENCE_END_EVENT) return n } func (p *parser) mapping() *node { n := p.node(mappingNode) p.anchor(n, p.event.anchor) - p.skip() - for p.event.typ != yaml_MAPPING_END_EVENT { + p.expect(yaml_MAPPING_START_EVENT) + for p.peek() != yaml_MAPPING_END_EVENT { n.children = append(n.children, p.parse(), p.parse()) } - p.skip() + p.expect(yaml_MAPPING_END_EVENT) return n } @@ -187,7 +225,7 @@ func (p *parser) mapping() *node { type decoder struct { doc *node - aliases map[string]bool + aliases map[*node]bool mapType reflect.Type terrors []string strict bool @@ -198,11 +236,13 @@ var ( durationType = reflect.TypeOf(time.Duration(0)) defaultMapType = reflect.TypeOf(map[interface{}]interface{}{}) ifaceType = defaultMapType.Elem() + timeType = reflect.TypeOf(time.Time{}) + ptrTimeType = reflect.TypeOf(&time.Time{}) ) func newDecoder(strict bool) *decoder { d := &decoder{mapType: defaultMapType, strict: strict} - d.aliases = make(map[string]bool) + d.aliases = make(map[*node]bool) return d } @@ -251,7 +291,7 @@ func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) { // // If n holds a null value, prepare returns before doing anything. func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { - if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "" && n.implicit) { + if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "~" || n.value == "" && n.implicit) { return out, false, false } again := true @@ -308,16 +348,13 @@ func (d *decoder) document(n *node, out reflect.Value) (good bool) { } func (d *decoder) alias(n *node, out reflect.Value) (good bool) { - an, ok := d.doc.anchors[n.value] - if !ok { - failf("unknown anchor '%s' referenced", n.value) - } - if d.aliases[n.value] { + if d.aliases[n] { + // TODO this could actually be allowed in some circumstances. failf("anchor '%s' value contains itself", n.value) } - d.aliases[n.value] = true - good = d.unmarshal(an, out) - delete(d.aliases, n.value) + d.aliases[n] = true + good = d.unmarshal(n.alias, out) + delete(d.aliases, n) return good } @@ -329,7 +366,7 @@ func resetMap(out reflect.Value) { } } -func (d *decoder) scalar(n *node, out reflect.Value) (good bool) { +func (d *decoder) scalar(n *node, out reflect.Value) bool { var tag string var resolved interface{} if n.tag == "" && !n.implicit { @@ -353,9 +390,26 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) { } return true } - if s, ok := resolved.(string); ok && out.CanAddr() { - if u, ok := out.Addr().Interface().(encoding.TextUnmarshaler); ok { - err := u.UnmarshalText([]byte(s)) + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + // We've resolved to exactly the type we want, so use that. + out.Set(resolvedv) + return true + } + // Perhaps we can use the value as a TextUnmarshaler to + // set its value. + if out.CanAddr() { + u, ok := out.Addr().Interface().(encoding.TextUnmarshaler) + if ok { + var text []byte + if tag == yaml_BINARY_TAG { + text = []byte(resolved.(string)) + } else { + // We let any value be unmarshaled into TextUnmarshaler. + // That might be more lax than we'd like, but the + // TextUnmarshaler itself should bowl out any dubious values. + text = []byte(n.value) + } + err := u.UnmarshalText(text) if err != nil { fail(err) } @@ -366,46 +420,54 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) { case reflect.String: if tag == yaml_BINARY_TAG { out.SetString(resolved.(string)) - good = true - } else if resolved != nil { + return true + } + if resolved != nil { out.SetString(n.value) - good = true + return true } case reflect.Interface: if resolved == nil { out.Set(reflect.Zero(out.Type())) + } else if tag == yaml_TIMESTAMP_TAG { + // It looks like a timestamp but for backward compatibility + // reasons we set it as a string, so that code that unmarshals + // timestamp-like values into interface{} will continue to + // see a string and not a time.Time. + // TODO(v3) Drop this. + out.Set(reflect.ValueOf(n.value)) } else { out.Set(reflect.ValueOf(resolved)) } - good = true + return true case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: switch resolved := resolved.(type) { case int: if !out.OverflowInt(int64(resolved)) { out.SetInt(int64(resolved)) - good = true + return true } case int64: if !out.OverflowInt(resolved) { out.SetInt(resolved) - good = true + return true } case uint64: if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { out.SetInt(int64(resolved)) - good = true + return true } case float64: if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { out.SetInt(int64(resolved)) - good = true + return true } case string: if out.Type() == durationType { d, err := time.ParseDuration(resolved) if err == nil { out.SetInt(int64(d)) - good = true + return true } } } @@ -414,44 +476,49 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) { case int: if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { out.SetUint(uint64(resolved)) - good = true + return true } case int64: if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { out.SetUint(uint64(resolved)) - good = true + return true } case uint64: if !out.OverflowUint(uint64(resolved)) { out.SetUint(uint64(resolved)) - good = true + return true } case float64: if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { out.SetUint(uint64(resolved)) - good = true + return true } } case reflect.Bool: switch resolved := resolved.(type) { case bool: out.SetBool(resolved) - good = true + return true } case reflect.Float32, reflect.Float64: switch resolved := resolved.(type) { case int: out.SetFloat(float64(resolved)) - good = true + return true case int64: out.SetFloat(float64(resolved)) - good = true + return true case uint64: out.SetFloat(float64(resolved)) - good = true + return true case float64: out.SetFloat(resolved) - good = true + return true + } + case reflect.Struct: + if resolvedv := reflect.ValueOf(resolved); out.Type() == resolvedv.Type() { + out.Set(resolvedv) + return true } case reflect.Ptr: if out.Type().Elem() == reflect.TypeOf(resolved) { @@ -459,13 +526,11 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) { elem := reflect.New(out.Type().Elem()) elem.Elem().Set(reflect.ValueOf(resolved)) out.Set(elem) - good = true + return true } } - if !good { - d.terror(n, tag, out) - } - return good + d.terror(n, tag, out) + return false } func settableValueOf(i interface{}) reflect.Value { @@ -482,6 +547,10 @@ func (d *decoder) sequence(n *node, out reflect.Value) (good bool) { switch out.Kind() { case reflect.Slice: out.Set(reflect.MakeSlice(out.Type(), l, l)) + case reflect.Array: + if l != out.Len() { + failf("invalid array: want %d elements but got %d", out.Len(), l) + } case reflect.Interface: // No type hints. Will have to use a generic sequence. iface = out @@ -500,7 +569,9 @@ func (d *decoder) sequence(n *node, out reflect.Value) (good bool) { j++ } } - out.Set(out.Slice(0, j)) + if out.Kind() != reflect.Array { + out.Set(out.Slice(0, j)) + } if iface.IsValid() { iface.Set(out) } @@ -561,7 +632,7 @@ func (d *decoder) mapping(n *node, out reflect.Value) (good bool) { } e := reflect.New(et).Elem() if d.unmarshal(n.children[i+1], e) { - out.SetMapIndex(k, e) + d.setMapIndex(n.children[i+1], out, k, e) } } } @@ -569,6 +640,14 @@ func (d *decoder) mapping(n *node, out reflect.Value) (good bool) { return true } +func (d *decoder) setMapIndex(n *node, out, k, v reflect.Value) { + if d.strict && out.MapIndex(k) != zeroValue { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: key %#v already set in map", n.line+1, k.Interface())) + return + } + out.SetMapIndex(k, v) +} + func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { outt := out.Type() if outt.Elem() != mapItemType { @@ -616,6 +695,10 @@ func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { elemType = inlineMap.Type().Elem() } + var doneFields []bool + if d.strict { + doneFields = make([]bool, len(sinfo.FieldsList)) + } for i := 0; i < l; i += 2 { ni := n.children[i] if isMerge(ni) { @@ -626,6 +709,13 @@ func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { continue } if info, ok := sinfo.FieldsMap[name.String()]; ok { + if d.strict { + if doneFields[info.Id] { + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s already set in type %s", ni.line+1, name.String(), out.Type())) + continue + } + doneFields[info.Id] = true + } var field reflect.Value if info.Inline == nil { field = out.Field(info.Num) @@ -639,9 +729,9 @@ func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { } value := reflect.New(elemType).Elem() d.unmarshal(n.children[i+1], value) - inlineMap.SetMapIndex(name, value) + d.setMapIndex(n.children[i+1], inlineMap, name, value) } else if d.strict { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in struct %s", n.line+1, name.String(), out.Type())) + d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in type %s", ni.line+1, name.String(), out.Type())) } } return true diff --git a/vendor/gopkg.in/yaml.v2/decode_test.go b/vendor/gopkg.in/yaml.v2/decode_test.go deleted file mode 100644 index 713b1ee9c4..0000000000 --- a/vendor/gopkg.in/yaml.v2/decode_test.go +++ /dev/null @@ -1,1017 +0,0 @@ -package yaml_test - -import ( - "errors" - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "math" - "net" - "reflect" - "strings" - "time" -) - -var unmarshalIntTest = 123 - -var unmarshalTests = []struct { - data string - value interface{} -}{ - { - "", - &struct{}{}, - }, { - "{}", &struct{}{}, - }, { - "v: hi", - map[string]string{"v": "hi"}, - }, { - "v: hi", map[string]interface{}{"v": "hi"}, - }, { - "v: true", - map[string]string{"v": "true"}, - }, { - "v: true", - map[string]interface{}{"v": true}, - }, { - "v: 10", - map[string]interface{}{"v": 10}, - }, { - "v: 0b10", - map[string]interface{}{"v": 2}, - }, { - "v: 0xA", - map[string]interface{}{"v": 10}, - }, { - "v: 4294967296", - map[string]int64{"v": 4294967296}, - }, { - "v: 0.1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .1", - map[string]interface{}{"v": 0.1}, - }, { - "v: .Inf", - map[string]interface{}{"v": math.Inf(+1)}, - }, { - "v: -.Inf", - map[string]interface{}{"v": math.Inf(-1)}, - }, { - "v: -10", - map[string]interface{}{"v": -10}, - }, { - "v: -.1", - map[string]interface{}{"v": -0.1}, - }, - - // Simple values. - { - "123", - &unmarshalIntTest, - }, - - // Floats from spec - { - "canonical: 6.8523e+5", - map[string]interface{}{"canonical": 6.8523e+5}, - }, { - "expo: 685.230_15e+03", - map[string]interface{}{"expo": 685.23015e+03}, - }, { - "fixed: 685_230.15", - map[string]interface{}{"fixed": 685230.15}, - }, { - "neginf: -.inf", - map[string]interface{}{"neginf": math.Inf(-1)}, - }, { - "fixed: 685_230.15", - map[string]float64{"fixed": 685230.15}, - }, - //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported - //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails. - - // Bools from spec - { - "canonical: y", - map[string]interface{}{"canonical": true}, - }, { - "answer: NO", - map[string]interface{}{"answer": false}, - }, { - "logical: True", - map[string]interface{}{"logical": true}, - }, { - "option: on", - map[string]interface{}{"option": true}, - }, { - "option: on", - map[string]bool{"option": true}, - }, - // Ints from spec - { - "canonical: 685230", - map[string]interface{}{"canonical": 685230}, - }, { - "decimal: +685_230", - map[string]interface{}{"decimal": 685230}, - }, { - "octal: 02472256", - map[string]interface{}{"octal": 685230}, - }, { - "hexa: 0x_0A_74_AE", - map[string]interface{}{"hexa": 685230}, - }, { - "bin: 0b1010_0111_0100_1010_1110", - map[string]interface{}{"bin": 685230}, - }, { - "bin: -0b101010", - map[string]interface{}{"bin": -42}, - }, { - "decimal: +685_230", - map[string]int{"decimal": 685230}, - }, - - //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported - - // Nulls from spec - { - "empty:", - map[string]interface{}{"empty": nil}, - }, { - "canonical: ~", - map[string]interface{}{"canonical": nil}, - }, { - "english: null", - map[string]interface{}{"english": nil}, - }, { - "~: null key", - map[interface{}]string{nil: "null key"}, - }, { - "empty:", - map[string]*bool{"empty": nil}, - }, - - // Flow sequence - { - "seq: [A,B]", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq: [A,B,C,]", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq: [A,1,C]", - map[string][]int{"seq": []int{1}}, - }, { - "seq: [A,1,C]", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - // Block sequence - { - "seq:\n - A\n - B", - map[string]interface{}{"seq": []interface{}{"A", "B"}}, - }, { - "seq:\n - A\n - B\n - C", - map[string][]string{"seq": []string{"A", "B", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]string{"seq": []string{"A", "1", "C"}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string][]int{"seq": []int{1}}, - }, { - "seq:\n - A\n - 1\n - C", - map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, - }, - - // Literal block scalar - { - "scalar: | # Comment\n\n literal\n\n \ttext\n\n", - map[string]string{"scalar": "\nliteral\n\n\ttext\n"}, - }, - - // Folded block scalar - { - "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n", - map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"}, - }, - - // Map inside interface with no type hints. - { - "a: {b: c}", - map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - }, - - // Structs and type conversions. - { - "hello: world", - &struct{ Hello string }{"world"}, - }, { - "a: {b: c}", - &struct{ A struct{ B string } }{struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A *struct{ B string } }{&struct{ B string }{"c"}}, - }, { - "a: {b: c}", - &struct{ A map[string]string }{map[string]string{"b": "c"}}, - }, { - "a: {b: c}", - &struct{ A *map[string]string }{&map[string]string{"b": "c"}}, - }, { - "a:", - &struct{ A map[string]string }{}, - }, { - "a: 1", - &struct{ A int }{1}, - }, { - "a: 1", - &struct{ A float64 }{1}, - }, { - "a: 1.0", - &struct{ A int }{1}, - }, { - "a: 1.0", - &struct{ A uint }{1}, - }, { - "a: [1, 2]", - &struct{ A []int }{[]int{1, 2}}, - }, { - "a: 1", - &struct{ B int }{0}, - }, { - "a: 1", - &struct { - B int "a" - }{1}, - }, { - "a: y", - &struct{ A bool }{true}, - }, - - // Some cross type conversions - { - "v: 42", - map[string]uint{"v": 42}, - }, { - "v: -42", - map[string]uint{}, - }, { - "v: 4294967296", - map[string]uint64{"v": 4294967296}, - }, { - "v: -4294967296", - map[string]uint64{}, - }, - - // int - { - "int_max: 2147483647", - map[string]int{"int_max": math.MaxInt32}, - }, - { - "int_min: -2147483648", - map[string]int{"int_min": math.MinInt32}, - }, - { - "int_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int{}, - }, - - // int64 - { - "int64_max: 9223372036854775807", - map[string]int64{"int64_max": math.MaxInt64}, - }, - { - "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_max_base2": math.MaxInt64}, - }, - { - "int64_min: -9223372036854775808", - map[string]int64{"int64_min": math.MinInt64}, - }, - { - "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111", - map[string]int64{"int64_neg_base2": -math.MaxInt64}, - }, - { - "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1 - map[string]int64{}, - }, - - // uint - { - "uint_min: 0", - map[string]uint{"uint_min": 0}, - }, - { - "uint_max: 4294967295", - map[string]uint{"uint_max": math.MaxUint32}, - }, - { - "uint_underflow: -1", - map[string]uint{}, - }, - - // uint64 - { - "uint64_min: 0", - map[string]uint{"uint64_min": 0}, - }, - { - "uint64_max: 18446744073709551615", - map[string]uint64{"uint64_max": math.MaxUint64}, - }, - { - "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111", - map[string]uint64{"uint64_max_base2": math.MaxUint64}, - }, - { - "uint64_maxint64: 9223372036854775807", - map[string]uint64{"uint64_maxint64": math.MaxInt64}, - }, - { - "uint64_underflow: -1", - map[string]uint64{}, - }, - - // float32 - { - "float32_max: 3.40282346638528859811704183484516925440e+38", - map[string]float32{"float32_max": math.MaxFloat32}, - }, - { - "float32_nonzero: 1.401298464324817070923729583289916131280e-45", - map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32}, - }, - { - "float32_maxuint64: 18446744073709551615", - map[string]float32{"float32_maxuint64": float32(math.MaxUint64)}, - }, - { - "float32_maxuint64+1: 18446744073709551616", - map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)}, - }, - - // float64 - { - "float64_max: 1.797693134862315708145274237317043567981e+308", - map[string]float64{"float64_max": math.MaxFloat64}, - }, - { - "float64_nonzero: 4.940656458412465441765687928682213723651e-324", - map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64}, - }, - { - "float64_maxuint64: 18446744073709551615", - map[string]float64{"float64_maxuint64": float64(math.MaxUint64)}, - }, - { - "float64_maxuint64+1: 18446744073709551616", - map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)}, - }, - - // Overflow cases. - { - "v: 4294967297", - map[string]int32{}, - }, { - "v: 128", - map[string]int8{}, - }, - - // Quoted values. - { - "'1': '\"2\"'", - map[interface{}]interface{}{"1": "\"2\""}, - }, { - "v:\n- A\n- 'B\n\n C'\n", - map[string][]string{"v": []string{"A", "B\nC"}}, - }, - - // Explicit tags. - { - "v: !!float '1.1'", - map[string]interface{}{"v": 1.1}, - }, { - "v: !!null ''", - map[string]interface{}{"v": nil}, - }, { - "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'", - map[string]interface{}{"v": 1}, - }, - - // Non-specific tag (Issue #75) - { - "v: ! test", - map[string]interface{}{"v": "test"}, - }, - - // Anchors and aliases. - { - "a: &x 1\nb: &y 2\nc: *x\nd: *y\n", - &struct{ A, B, C, D int }{1, 2, 1, 2}, - }, { - "a: &a {c: 1}\nb: *a", - &struct { - A, B struct { - C int - } - }{struct{ C int }{1}, struct{ C int }{1}}, - }, { - "a: &a [1, 2]\nb: *a", - &struct{ B []int }{[]int{1, 2}}, - }, { - "b: *a\na: &a {c: 1}", - &struct { - A, B struct { - C int - } - }{struct{ C int }{1}, struct{ C int }{1}}, - }, - - // Bug #1133337 - { - "foo: ''", - map[string]*string{"foo": new(string)}, - }, { - "foo: null", - map[string]string{"foo": ""}, - }, { - "foo: null", - map[string]interface{}{"foo": nil}, - }, - - // Ignored field - { - "a: 1\nb: 2\n", - &struct { - A int - B int "-" - }{1, 0}, - }, - - // Bug #1191981 - { - "" + - "%YAML 1.1\n" + - "--- !!str\n" + - `"Generic line break (no glyph)\n\` + "\n" + - ` Generic line break (glyphed)\n\` + "\n" + - ` Line separator\u2028\` + "\n" + - ` Paragraph separator\u2029"` + "\n", - "" + - "Generic line break (no glyph)\n" + - "Generic line break (glyphed)\n" + - "Line separator\u2028Paragraph separator\u2029", - }, - - // Struct inlining - { - "a: 1\nb: 2\nc: 3\n", - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - }, - - // Map inlining - { - "a: 1\nb: 2\nc: 3\n", - &struct { - A int - C map[string]int `yaml:",inline"` - }{1, map[string]int{"b": 2, "c": 3}}, - }, - - // bug 1243827 - { - "a: -b_c", - map[string]interface{}{"a": "-b_c"}, - }, - { - "a: +b_c", - map[string]interface{}{"a": "+b_c"}, - }, - { - "a: 50cent_of_dollar", - map[string]interface{}{"a": "50cent_of_dollar"}, - }, - - // Duration - { - "a: 3s", - map[string]time.Duration{"a": 3 * time.Second}, - }, - - // Issue #24. - { - "a: <foo>", - map[string]string{"a": "<foo>"}, - }, - - // Base 60 floats are obsolete and unsupported. - { - "a: 1:1\n", - map[string]string{"a": "1:1"}, - }, - - // Binary data. - { - "a: !!binary gIGC\n", - map[string]string{"a": "\x80\x81\x82"}, - }, { - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - map[string]string{"a": strings.Repeat("\x90", 54)}, - }, { - "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n", - map[string]string{"a": strings.Repeat("\x00", 52)}, - }, - - // Ordered maps. - { - "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}", - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - }, - - // Issue #39. - { - "a:\n b:\n c: d\n", - map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}}, - }, - - // Custom map type. - { - "a: {b: c}", - M{"a": M{"b": "c"}}, - }, - - // Support encoding.TextUnmarshaler. - { - "a: 1.2.3.4\n", - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - }, - { - "a: 2015-02-24T18:19:39Z\n", - map[string]time.Time{"a": time.Unix(1424801979, 0).In(time.UTC)}, - }, - - // Encode empty lists as zero-length slices. - { - "a: []", - &struct{ A []int }{[]int{}}, - }, - - // UTF-16-LE - { - "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n\x00", - M{"ñoño": "very yes"}, - }, - // UTF-16-LE with surrogate. - { - "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \x00=\xd8\xd4\xdf\n\x00", - M{"ñoño": "very yes 🟔"}, - }, - - // UTF-16-BE - { - "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n", - M{"ñoño": "very yes"}, - }, - // UTF-16-BE with surrogate. - { - "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \xd8=\xdf\xd4\x00\n", - M{"ñoño": "very yes 🟔"}, - }, - - // YAML Float regex shouldn't match this - { - "a: 123456e1\n", - M{"a": "123456e1"}, - }, { - "a: 123456E1\n", - M{"a": "123456E1"}, - }, -} - -type M map[interface{}]interface{} - -type inlineB struct { - B int - inlineC `yaml:",inline"` -} - -type inlineC struct { - C int -} - -func (s *S) TestUnmarshal(c *C) { - for i, item := range unmarshalTests { - c.Logf("test %d: %q", i, item.data) - t := reflect.ValueOf(item.value).Type() - var value interface{} - switch t.Kind() { - case reflect.Map: - value = reflect.MakeMap(t).Interface() - case reflect.String: - value = reflect.New(t).Interface() - case reflect.Ptr: - value = reflect.New(t.Elem()).Interface() - default: - c.Fatalf("missing case for %s", t) - } - err := yaml.Unmarshal([]byte(item.data), value) - if _, ok := err.(*yaml.TypeError); !ok { - c.Assert(err, IsNil) - } - if t.Kind() == reflect.String { - c.Assert(*value.(*string), Equals, item.value) - } else { - c.Assert(value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalNaN(c *C) { - value := map[string]interface{}{} - err := yaml.Unmarshal([]byte("notanum: .NaN"), &value) - c.Assert(err, IsNil) - c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true) -} - -var unmarshalErrorTests = []struct { - data, error string -}{ - {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"}, - {"v: [A,", "yaml: line 1: did not find expected node content"}, - {"v:\n- [A,", "yaml: line 2: did not find expected node content"}, - {"a: *b\n", "yaml: unknown anchor 'b' referenced"}, - {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"}, - {"value: -", "yaml: block sequence entries are not allowed in this context"}, - {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"}, - {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`}, - {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`}, - {"%TAG !%79! tag:yaml.org,2002:\n---\nv: !%79!int '1'", "yaml: did not find expected whitespace"}, -} - -func (s *S) TestUnmarshalErrors(c *C) { - for _, item := range unmarshalErrorTests { - var value interface{} - err := yaml.Unmarshal([]byte(item.data), &value) - c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value)) - } -} - -var unmarshalerTests = []struct { - data, tag string - value interface{} -}{ - {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}}, - {"_: [1,A]", "!!seq", []interface{}{1, "A"}}, - {"_: 10", "!!int", 10}, - {"_: null", "!!null", nil}, - {`_: BAR!`, "!!str", "BAR!"}, - {`_: "BAR!"`, "!!str", "BAR!"}, - {"_: !!foo 'BAR!'", "!!foo", "BAR!"}, - {`_: ""`, "!!str", ""}, -} - -var unmarshalerResult = map[int]error{} - -type unmarshalerType struct { - value interface{} -} - -func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error { - if err := unmarshal(&o.value); err != nil { - return err - } - if i, ok := o.value.(int); ok { - if result, ok := unmarshalerResult[i]; ok { - return result - } - } - return nil -} - -type unmarshalerPointer struct { - Field *unmarshalerType "_" -} - -type unmarshalerValue struct { - Field unmarshalerType "_" -} - -func (s *S) TestUnmarshalerPointerField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerPointer{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - if item.value == nil { - c.Assert(obj.Field, IsNil) - } else { - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } - } -} - -func (s *S) TestUnmarshalerValueField(c *C) { - for _, item := range unmarshalerTests { - obj := &unmarshalerValue{} - err := yaml.Unmarshal([]byte(item.data), obj) - c.Assert(err, IsNil) - c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) - c.Assert(obj.Field.value, DeepEquals, item.value) - } -} - -func (s *S) TestUnmarshalerWholeDocument(c *C) { - obj := &unmarshalerType{} - err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj) - c.Assert(err, IsNil) - value, ok := obj.value.(map[interface{}]interface{}) - c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value)) - c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value) -} - -func (s *S) TestUnmarshalerTypeError(c *C) { - unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}} - unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}} - defer func() { - delete(unmarshalerResult, 2) - delete(unmarshalerResult, 4) - }() - - type T struct { - Before int - After int - M map[string]*unmarshalerType - } - var v T - data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " foo\n"+ - " bar\n"+ - " line 1: cannot unmarshal !!str `B` into int") - c.Assert(v.M["abc"], NotNil) - c.Assert(v.M["def"], IsNil) - c.Assert(v.M["ghi"], NotNil) - c.Assert(v.M["jkl"], IsNil) - - c.Assert(v.M["abc"].value, Equals, 1) - c.Assert(v.M["ghi"].value, Equals, 3) -} - -type proxyTypeError struct{} - -func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error { - var s string - var a int32 - var b int64 - if err := unmarshal(&s); err != nil { - panic(err) - } - if s == "a" { - if err := unmarshal(&b); err == nil { - panic("should have failed") - } - return unmarshal(&a) - } - if err := unmarshal(&a); err == nil { - panic("should have failed") - } - return unmarshal(&b) -} - -func (s *S) TestUnmarshalerTypeErrorProxying(c *C) { - type T struct { - Before int - After int - M map[string]*proxyTypeError - } - var v T - data := `{before: A, m: {abc: a, def: b}, after: B}` - err := yaml.Unmarshal([]byte(data), &v) - c.Assert(err, ErrorMatches, ""+ - "yaml: unmarshal errors:\n"+ - " line 1: cannot unmarshal !!str `A` into int\n"+ - " line 1: cannot unmarshal !!str `a` into int32\n"+ - " line 1: cannot unmarshal !!str `b` into int64\n"+ - " line 1: cannot unmarshal !!str `B` into int") -} - -type failingUnmarshaler struct{} - -var failingErr = errors.New("failingErr") - -func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { - return failingErr -} - -func (s *S) TestUnmarshalerError(c *C) { - err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{}) - c.Assert(err, Equals, failingErr) -} - -type sliceUnmarshaler []int - -func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { - var slice []int - err := unmarshal(&slice) - if err == nil { - *su = slice - return nil - } - - var intVal int - err = unmarshal(&intVal) - if err == nil { - *su = []int{intVal} - return nil - } - - return err -} - -func (s *S) TestUnmarshalerRetry(c *C) { - var su sliceUnmarshaler - err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su) - c.Assert(err, IsNil) - c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3})) - - err = yaml.Unmarshal([]byte("1"), &su) - c.Assert(err, IsNil) - c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1})) -} - -// From http://yaml.org/type/merge.html -var mergeTests = ` -anchors: - list: - - &CENTER { "x": 1, "y": 2 } - - &LEFT { "x": 0, "y": 2 } - - &BIG { "r": 10 } - - &SMALL { "r": 1 } - -# All the following maps are equal: - -plain: - # Explicit keys - "x": 1 - "y": 2 - "r": 10 - label: center/big - -mergeOne: - # Merge one map - << : *CENTER - "r": 10 - label: center/big - -mergeMultiple: - # Merge multiple maps - << : [ *CENTER, *BIG ] - label: center/big - -override: - # Override - << : [ *BIG, *LEFT, *SMALL ] - "x": 1 - label: center/big - -shortTag: - # Explicit short merge tag - !!merge "<<" : [ *CENTER, *BIG ] - label: center/big - -longTag: - # Explicit merge long tag - !<tag:yaml.org,2002:merge> "<<" : [ *CENTER, *BIG ] - label: center/big - -inlineMap: - # Inlined map - << : {"x": 1, "y": 2, "r": 10} - label: center/big - -inlineSequenceMap: - # Inlined map in sequence - << : [ *CENTER, {"r": 10} ] - label: center/big -` - -func (s *S) TestMerge(c *C) { - var want = map[interface{}]interface{}{ - "x": 1, - "y": 2, - "r": 10, - "label": "center/big", - } - - var m map[interface{}]interface{} - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, DeepEquals, want, Commentf("test %q failed", name)) - } -} - -func (s *S) TestMergeStruct(c *C) { - type Data struct { - X, Y, R int - Label string - } - want := Data{1, 2, 10, "center/big"} - - var m map[string]Data - err := yaml.Unmarshal([]byte(mergeTests), &m) - c.Assert(err, IsNil) - for name, test := range m { - if name == "anchors" { - continue - } - c.Assert(test, Equals, want, Commentf("test %q failed", name)) - } -} - -var unmarshalNullTests = []func() interface{}{ - func() interface{} { var v interface{}; v = "v"; return &v }, - func() interface{} { var s = "s"; return &s }, - func() interface{} { var s = "s"; sptr := &s; return &sptr }, - func() interface{} { var i = 1; return &i }, - func() interface{} { var i = 1; iptr := &i; return &iptr }, - func() interface{} { m := map[string]int{"s": 1}; return &m }, - func() interface{} { m := map[string]int{"s": 1}; return m }, -} - -func (s *S) TestUnmarshalNull(c *C) { - for _, test := range unmarshalNullTests { - item := test() - zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface() - err := yaml.Unmarshal([]byte("null"), item) - c.Assert(err, IsNil) - if reflect.TypeOf(item).Kind() == reflect.Map { - c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface()) - } else { - c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero) - } - } -} - -func (s *S) TestUnmarshalSliceOnPreset(c *C) { - // Issue #48. - v := struct{ A []int }{[]int{1}} - yaml.Unmarshal([]byte("a: [2]"), &v) - c.Assert(v.A, DeepEquals, []int{2}) -} - -func (s *S) TestUnmarshalStrict(c *C) { - v := struct{ A, B int }{} - - err := yaml.UnmarshalStrict([]byte("a: 1\nb: 2"), &v) - c.Check(err, IsNil) - err = yaml.Unmarshal([]byte("a: 1\nb: 2\nc: 3"), &v) - c.Check(err, IsNil) - err = yaml.UnmarshalStrict([]byte("a: 1\nb: 2\nc: 3"), &v) - c.Check(err, ErrorMatches, "yaml: unmarshal errors:\n line 1: field c not found in struct struct { A int; B int }") -} - -//var data []byte -//func init() { -// var err error -// data, err = ioutil.ReadFile("/tmp/file.yaml") -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkUnmarshal(c *C) { -// var err error -// for i := 0; i < c.N; i++ { -// var v map[string]interface{} -// err = yaml.Unmarshal(data, &v) -// } -// if err != nil { -// panic(err) -// } -//} -// -//func (s *S) BenchmarkMarshal(c *C) { -// var v map[string]interface{} -// yaml.Unmarshal(data, &v) -// c.ResetTimer() -// for i := 0; i < c.N; i++ { -// yaml.Marshal(&v) -// } -//} diff --git a/vendor/gopkg.in/yaml.v2/emitterc.go b/vendor/gopkg.in/yaml.v2/emitterc.go index 41de8b856c..a1c2cc5262 100644 --- a/vendor/gopkg.in/yaml.v2/emitterc.go +++ b/vendor/gopkg.in/yaml.v2/emitterc.go @@ -2,6 +2,7 @@ package yaml import ( "bytes" + "fmt" ) // Flush the buffer if needed. @@ -664,7 +665,7 @@ func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, return yaml_emitter_emit_mapping_start(emitter, event) default: return yaml_emitter_set_emitter_error(emitter, - "expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS") + fmt.Sprintf("expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, but got %v", event.typ)) } } @@ -842,7 +843,7 @@ func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event return true } -// Write an achor. +// Write an anchor. func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { if emitter.anchor_data.anchor == nil { return true @@ -995,9 +996,9 @@ func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { space_break = false preceded_by_whitespace = false - followed_by_whitespace = false - previous_space = false - previous_break = false + followed_by_whitespace = false + previous_space = false + previous_break = false ) emitter.scalar_data.value = value diff --git a/vendor/gopkg.in/yaml.v2/encode.go b/vendor/gopkg.in/yaml.v2/encode.go index 84f8499551..a14435e82f 100644 --- a/vendor/gopkg.in/yaml.v2/encode.go +++ b/vendor/gopkg.in/yaml.v2/encode.go @@ -3,12 +3,14 @@ package yaml import ( "encoding" "fmt" + "io" "reflect" "regexp" "sort" "strconv" "strings" "time" + "unicode/utf8" ) type encoder struct { @@ -16,25 +18,39 @@ type encoder struct { event yaml_event_t out []byte flow bool + // doneInit holds whether the initial stream_start_event has been + // emitted. + doneInit bool } -func newEncoder() (e *encoder) { - e = &encoder{} - e.must(yaml_emitter_initialize(&e.emitter)) +func newEncoder() *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) yaml_emitter_set_output_string(&e.emitter, &e.out) yaml_emitter_set_unicode(&e.emitter, true) - e.must(yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING)) - e.emit() - e.must(yaml_document_start_event_initialize(&e.event, nil, nil, true)) - e.emit() return e } -func (e *encoder) finish() { - e.must(yaml_document_end_event_initialize(&e.event, true)) +func newEncoderWithWriter(w io.Writer) *encoder { + e := &encoder{} + yaml_emitter_initialize(&e.emitter) + yaml_emitter_set_output_writer(&e.emitter, w) + yaml_emitter_set_unicode(&e.emitter, true) + return e +} + +func (e *encoder) init() { + if e.doneInit { + return + } + yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) e.emit() + e.doneInit = true +} + +func (e *encoder) finish() { e.emitter.open_ended = false - e.must(yaml_stream_end_event_initialize(&e.event)) + yaml_stream_end_event_initialize(&e.event) e.emit() } @@ -44,9 +60,7 @@ func (e *encoder) destroy() { func (e *encoder) emit() { // This will internally delete the e.event value. - if !yaml_emitter_emit(&e.emitter, &e.event) && e.event.typ != yaml_DOCUMENT_END_EVENT && e.event.typ != yaml_STREAM_END_EVENT { - e.must(false) - } + e.must(yaml_emitter_emit(&e.emitter, &e.event)) } func (e *encoder) must(ok bool) { @@ -59,13 +73,28 @@ func (e *encoder) must(ok bool) { } } +func (e *encoder) marshalDoc(tag string, in reflect.Value) { + e.init() + yaml_document_start_event_initialize(&e.event, nil, nil, true) + e.emit() + e.marshal(tag, in) + yaml_document_end_event_initialize(&e.event, true) + e.emit() +} + func (e *encoder) marshal(tag string, in reflect.Value) { - if !in.IsValid() { + if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() { e.nilv() return } iface := in.Interface() - if m, ok := iface.(Marshaler); ok { + switch m := iface.(type) { + case time.Time, *time.Time: + // Although time.Time implements TextMarshaler, + // we don't want to treat it as a string for YAML + // purposes because YAML has special support for + // timestamps. + case Marshaler: v, err := m.MarshalYAML() if err != nil { fail(err) @@ -75,31 +104,34 @@ func (e *encoder) marshal(tag string, in reflect.Value) { return } in = reflect.ValueOf(v) - } else if m, ok := iface.(encoding.TextMarshaler); ok { + case encoding.TextMarshaler: text, err := m.MarshalText() if err != nil { fail(err) } in = reflect.ValueOf(string(text)) + case nil: + e.nilv() + return } switch in.Kind() { case reflect.Interface: - if in.IsNil() { - e.nilv() - } else { - e.marshal(tag, in.Elem()) - } + e.marshal(tag, in.Elem()) case reflect.Map: e.mapv(tag, in) case reflect.Ptr: - if in.IsNil() { - e.nilv() + if in.Type() == ptrTimeType { + e.timev(tag, in.Elem()) } else { e.marshal(tag, in.Elem()) } case reflect.Struct: - e.structv(tag, in) - case reflect.Slice: + if in.Type() == timeType { + e.timev(tag, in) + } else { + e.structv(tag, in) + } + case reflect.Slice, reflect.Array: if in.Type().Elem() == mapItemType { e.itemsv(tag, in) } else { @@ -191,10 +223,10 @@ func (e *encoder) mappingv(tag string, f func()) { e.flow = false style = yaml_FLOW_MAPPING_STYLE } - e.must(yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) + yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) e.emit() f() - e.must(yaml_mapping_end_event_initialize(&e.event)) + yaml_mapping_end_event_initialize(&e.event) e.emit() } @@ -240,23 +272,36 @@ var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0 func (e *encoder) stringv(tag string, in reflect.Value) { var style yaml_scalar_style_t s := in.String() - rtag, rs := resolve("", s) - if rtag == yaml_BINARY_TAG { - if tag == "" || tag == yaml_STR_TAG { - tag = rtag - s = rs.(string) - } else if tag == yaml_BINARY_TAG { + canUsePlain := true + switch { + case !utf8.ValidString(s): + if tag == yaml_BINARY_TAG { failf("explicitly tagged !!binary data must be base64-encoded") - } else { + } + if tag != "" { failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) } + // It can't be encoded directly as YAML so use a binary tag + // and encode it as base64. + tag = yaml_BINARY_TAG + s = encodeBase64(s) + case tag == "": + // Check to see if it would resolve to a specific + // tag when encoded unquoted. If it doesn't, + // there's no need to quote it. + rtag, _ := resolve("", s) + canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s) } - if tag == "" && (rtag != yaml_STR_TAG || isBase60Float(s)) { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } else if strings.Contains(s, "\n") { + // Note: it's possible for user code to emit invalid YAML + // if they explicitly specify a tag and a string containing + // text that's incompatible with that tag. + switch { + case strings.Contains(s, "\n"): style = yaml_LITERAL_SCALAR_STYLE - } else { + case canUsePlain: style = yaml_PLAIN_SCALAR_STYLE + default: + style = yaml_DOUBLE_QUOTED_SCALAR_STYLE } e.emitScalar(s, "", tag, style) } @@ -281,9 +326,20 @@ func (e *encoder) uintv(tag string, in reflect.Value) { e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) } +func (e *encoder) timev(tag string, in reflect.Value) { + t := in.Interface().(time.Time) + s := t.Format(time.RFC3339Nano) + e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) +} + func (e *encoder) floatv(tag string, in reflect.Value) { - // FIXME: Handle 64 bits here. - s := strconv.FormatFloat(float64(in.Float()), 'g', -1, 32) + // Issue #352: When formatting, use the precision of the underlying value + precision := 64 + if in.Kind() == reflect.Float32 { + precision = 32 + } + + s := strconv.FormatFloat(in.Float(), 'g', -1, precision) switch s { case "+Inf": s = ".inf" diff --git a/vendor/gopkg.in/yaml.v2/encode_test.go b/vendor/gopkg.in/yaml.v2/encode_test.go deleted file mode 100644 index 84099bd385..0000000000 --- a/vendor/gopkg.in/yaml.v2/encode_test.go +++ /dev/null @@ -1,501 +0,0 @@ -package yaml_test - -import ( - "fmt" - "math" - "strconv" - "strings" - "time" - - . "gopkg.in/check.v1" - "gopkg.in/yaml.v2" - "net" - "os" -) - -var marshalIntTest = 123 - -var marshalTests = []struct { - value interface{} - data string -}{ - { - nil, - "null\n", - }, { - &struct{}{}, - "{}\n", - }, { - map[string]string{"v": "hi"}, - "v: hi\n", - }, { - map[string]interface{}{"v": "hi"}, - "v: hi\n", - }, { - map[string]string{"v": "true"}, - "v: \"true\"\n", - }, { - map[string]string{"v": "false"}, - "v: \"false\"\n", - }, { - map[string]interface{}{"v": true}, - "v: true\n", - }, { - map[string]interface{}{"v": false}, - "v: false\n", - }, { - map[string]interface{}{"v": 10}, - "v: 10\n", - }, { - map[string]interface{}{"v": -10}, - "v: -10\n", - }, { - map[string]uint{"v": 42}, - "v: 42\n", - }, { - map[string]interface{}{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]int64{"v": int64(4294967296)}, - "v: 4294967296\n", - }, { - map[string]uint64{"v": 4294967296}, - "v: 4294967296\n", - }, { - map[string]interface{}{"v": "10"}, - "v: \"10\"\n", - }, { - map[string]interface{}{"v": 0.1}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": float64(0.1)}, - "v: 0.1\n", - }, { - map[string]interface{}{"v": -0.1}, - "v: -0.1\n", - }, { - map[string]interface{}{"v": math.Inf(+1)}, - "v: .inf\n", - }, { - map[string]interface{}{"v": math.Inf(-1)}, - "v: -.inf\n", - }, { - map[string]interface{}{"v": math.NaN()}, - "v: .nan\n", - }, { - map[string]interface{}{"v": nil}, - "v: null\n", - }, { - map[string]interface{}{"v": ""}, - "v: \"\"\n", - }, { - map[string][]string{"v": []string{"A", "B"}}, - "v:\n- A\n- B\n", - }, { - map[string][]string{"v": []string{"A", "B\nC"}}, - "v:\n- A\n- |-\n B\n C\n", - }, { - map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}}, - "v:\n- A\n- 1\n- B:\n - 2\n - 3\n", - }, { - map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, - "a:\n b: c\n", - }, { - map[string]interface{}{"a": "-"}, - "a: '-'\n", - }, - - // Simple values. - { - &marshalIntTest, - "123\n", - }, - - // Structures - { - &struct{ Hello string }{"world"}, - "hello: world\n", - }, { - &struct { - A struct { - B string - } - }{struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{&struct{ B string }{"c"}}, - "a:\n b: c\n", - }, { - &struct { - A *struct { - B string - } - }{}, - "a: null\n", - }, { - &struct{ A int }{1}, - "a: 1\n", - }, { - &struct{ A []int }{[]int{1, 2}}, - "a:\n- 1\n- 2\n", - }, { - &struct { - B int "a" - }{1}, - "a: 1\n", - }, { - &struct{ A bool }{true}, - "a: true\n", - }, - - // Conditional flag - { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{1, 0}, - "a: 1\n", - }, { - &struct { - A int "a,omitempty" - B int "b,omitempty" - }{0, 0}, - "{}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{&struct{ X, y int }{1, 2}}, - "a: {x: 1}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{nil}, - "{}\n", - }, { - &struct { - A *struct{ X, y int } "a,omitempty,flow" - }{&struct{ X, y int }{}}, - "a: {x: 0}\n", - }, { - &struct { - A struct{ X, y int } "a,omitempty,flow" - }{struct{ X, y int }{1, 2}}, - "a: {x: 1}\n", - }, { - &struct { - A struct{ X, y int } "a,omitempty,flow" - }{struct{ X, y int }{0, 1}}, - "{}\n", - }, { - &struct { - A float64 "a,omitempty" - B float64 "b,omitempty" - }{1, 0}, - "a: 1\n", - }, - - // Flow flag - { - &struct { - A []int "a,flow" - }{[]int{1, 2}}, - "a: [1, 2]\n", - }, { - &struct { - A map[string]string "a,flow" - }{map[string]string{"b": "c", "d": "e"}}, - "a: {b: c, d: e}\n", - }, { - &struct { - A struct { - B, D string - } "a,flow" - }{struct{ B, D string }{"c", "e"}}, - "a: {b: c, d: e}\n", - }, - - // Unexported field - { - &struct { - u int - A int - }{0, 1}, - "a: 1\n", - }, - - // Ignored field - { - &struct { - A int - B int "-" - }{1, 2}, - "a: 1\n", - }, - - // Struct inlining - { - &struct { - A int - C inlineB `yaml:",inline"` - }{1, inlineB{2, inlineC{3}}}, - "a: 1\nb: 2\nc: 3\n", - }, - - // Map inlining - { - &struct { - A int - C map[string]int `yaml:",inline"` - }{1, map[string]int{"b": 2, "c": 3}}, - "a: 1\nb: 2\nc: 3\n", - }, - - // Duration - { - map[string]time.Duration{"a": 3 * time.Second}, - "a: 3s\n", - }, - - // Issue #24: bug in map merging logic. - { - map[string]string{"a": "<foo>"}, - "a: <foo>\n", - }, - - // Issue #34: marshal unsupported base 60 floats quoted for compatibility - // with old YAML 1.1 parsers. - { - map[string]string{"a": "1:1"}, - "a: \"1:1\"\n", - }, - - // Binary data. - { - map[string]string{"a": "\x00"}, - "a: \"\\0\"\n", - }, { - map[string]string{"a": "\x80\x81\x82"}, - "a: !!binary gIGC\n", - }, { - map[string]string{"a": strings.Repeat("\x90", 54)}, - "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", - }, - - // Ordered maps. - { - &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, - "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n", - }, - - // Encode unicode as utf-8 rather than in escaped form. - { - map[string]string{"a": "你好"}, - "a: 你好\n", - }, - - // Support encoding.TextMarshaler. - { - map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, - "a: 1.2.3.4\n", - }, - { - map[string]time.Time{"a": time.Unix(1424801979, 0)}, - "a: 2015-02-24T18:19:39Z\n", - }, - - // Ensure strings containing ": " are quoted (reported as PR #43, but not reproducible). - { - map[string]string{"a": "b: c"}, - "a: 'b: c'\n", - }, - - // Containing hash mark ('#') in string should be quoted - { - map[string]string{"a": "Hello #comment"}, - "a: 'Hello #comment'\n", - }, - { - map[string]string{"a": "你好 #comment"}, - "a: '你好 #comment'\n", - }, -} - -func (s *S) TestMarshal(c *C) { - defer os.Setenv("TZ", os.Getenv("TZ")) - os.Setenv("TZ", "UTC") - for _, item := range marshalTests { - data, err := yaml.Marshal(item.value) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, item.data) - } -} - -var marshalErrorTests = []struct { - value interface{} - error string - panic string -}{{ - value: &struct { - B int - inlineB ",inline" - }{1, inlineB{2, inlineC{3}}}, - panic: `Duplicated key 'b' in struct struct \{ B int; .*`, -}, { - value: &struct { - A int - B map[string]int ",inline" - }{1, map[string]int{"a": 2}}, - panic: `Can't have key "a" in inlined map; conflicts with struct field`, -}} - -func (s *S) TestMarshalErrors(c *C) { - for _, item := range marshalErrorTests { - if item.panic != "" { - c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic) - } else { - _, err := yaml.Marshal(item.value) - c.Assert(err, ErrorMatches, item.error) - } - } -} - -func (s *S) TestMarshalTypeCache(c *C) { - var data []byte - var err error - func() { - type T struct{ A int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - func() { - type T struct{ B int } - data, err = yaml.Marshal(&T{}) - c.Assert(err, IsNil) - }() - c.Assert(string(data), Equals, "b: 0\n") -} - -var marshalerTests = []struct { - data string - value interface{} -}{ - {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}}, - {"_:\n- 1\n- A\n", []interface{}{1, "A"}}, - {"_: 10\n", 10}, - {"_: null\n", nil}, - {"_: BAR!\n", "BAR!"}, -} - -type marshalerType struct { - value interface{} -} - -func (o marshalerType) MarshalText() ([]byte, error) { - panic("MarshalText called on type with MarshalYAML") -} - -func (o marshalerType) MarshalYAML() (interface{}, error) { - return o.value, nil -} - -type marshalerValue struct { - Field marshalerType "_" -} - -func (s *S) TestMarshaler(c *C) { - for _, item := range marshalerTests { - obj := &marshalerValue{} - obj.Field.value = item.value - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, string(item.data)) - } -} - -func (s *S) TestMarshalerWholeDocument(c *C) { - obj := &marshalerType{} - obj.value = map[string]string{"hello": "world!"} - data, err := yaml.Marshal(obj) - c.Assert(err, IsNil) - c.Assert(string(data), Equals, "hello: world!\n") -} - -type failingMarshaler struct{} - -func (ft *failingMarshaler) MarshalYAML() (interface{}, error) { - return nil, failingErr -} - -func (s *S) TestMarshalerError(c *C) { - _, err := yaml.Marshal(&failingMarshaler{}) - c.Assert(err, Equals, failingErr) -} - -func (s *S) TestSortedOutput(c *C) { - order := []interface{}{ - false, - true, - 1, - uint(1), - 1.0, - 1.1, - 1.2, - 2, - uint(2), - 2.0, - 2.1, - "", - ".1", - ".2", - ".a", - "1", - "2", - "a!10", - "a/2", - "a/10", - "a~10", - "ab/1", - "b/1", - "b/01", - "b/2", - "b/02", - "b/3", - "b/03", - "b1", - "b01", - "b3", - "c2.10", - "c10.2", - "d1", - "d12", - "d12a", - } - m := make(map[interface{}]int) - for _, k := range order { - m[k] = 1 - } - data, err := yaml.Marshal(m) - c.Assert(err, IsNil) - out := "\n" + string(data) - last := 0 - for i, k := range order { - repr := fmt.Sprint(k) - if s, ok := k.(string); ok { - if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil { - repr = `"` + repr + `"` - } - } - index := strings.Index(out, "\n"+repr+":") - if index == -1 { - c.Fatalf("%#v is not in the output: %#v", k, out) - } - if index < last { - c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out) - } - last = index - } -} diff --git a/vendor/gopkg.in/yaml.v2/example_embedded_test.go b/vendor/gopkg.in/yaml.v2/example_embedded_test.go deleted file mode 100644 index c8b241d549..0000000000 --- a/vendor/gopkg.in/yaml.v2/example_embedded_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package yaml_test - -import ( - "fmt" - "log" - - "gopkg.in/yaml.v2" -) - -// An example showing how to unmarshal embedded -// structs from YAML. - -type StructA struct { - A string `yaml:"a"` -} - -type StructB struct { - // Embedded structs are not treated as embedded in YAML by default. To do that, - // add the ",inline" annotation below - StructA `yaml:",inline"` - B string `yaml:"b"` -} - -var data = ` -a: a string from struct A -b: a string from struct B -` - -func ExampleUnmarshal_embedded() { - var b StructB - - err := yaml.Unmarshal([]byte(data), &b) - if err != nil { - log.Fatal("cannot unmarshal data: %v", err) - } - fmt.Println(b.A) - fmt.Println(b.B) - // Output: - // a string from struct A - // a string from struct B -} diff --git a/vendor/gopkg.in/yaml.v2/go.mod b/vendor/gopkg.in/yaml.v2/go.mod new file mode 100644 index 0000000000..1934e87694 --- /dev/null +++ b/vendor/gopkg.in/yaml.v2/go.mod @@ -0,0 +1,5 @@ +module "gopkg.in/yaml.v2" + +require ( + "gopkg.in/check.v1" v0.0.0-20161208181325-20d25e280405 +) diff --git a/vendor/gopkg.in/yaml.v2/readerc.go b/vendor/gopkg.in/yaml.v2/readerc.go index f450791717..7c1f5fac3d 100644 --- a/vendor/gopkg.in/yaml.v2/readerc.go +++ b/vendor/gopkg.in/yaml.v2/readerc.go @@ -93,9 +93,18 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { panic("read handler must be set") } + // [Go] This function was changed to guarantee the requested length size at EOF. + // The fact we need to do this is pretty awful, but the description above implies + // for that to be the case, and there are tests + // If the EOF flag is set and the raw buffer is empty, do nothing. if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { - return true + // [Go] ACTUALLY! Read the documentation of this function above. + // This is just broken. To return true, we need to have the + // given length in the buffer. Not doing that means every single + // check that calls this function to make sure the buffer has a + // given length is Go) panicking; or C) accessing invalid memory. + //return true } // Return if the buffer contains enough characters. @@ -389,6 +398,15 @@ func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { break } } + // [Go] Read the documentation of this function above. To return true, + // we need to have the given length in the buffer. Not doing that means + // every single check that calls this function to make sure the buffer + // has a given length is Go) panicking; or C) accessing invalid memory. + // This happens here due to the EOF above breaking early. + for buffer_len < length { + parser.buffer[buffer_len] = 0 + buffer_len++ + } parser.buffer = parser.buffer[:buffer_len] return true } diff --git a/vendor/gopkg.in/yaml.v2/resolve.go b/vendor/gopkg.in/yaml.v2/resolve.go index 232313cc08..6c151db6fb 100644 --- a/vendor/gopkg.in/yaml.v2/resolve.go +++ b/vendor/gopkg.in/yaml.v2/resolve.go @@ -6,7 +6,7 @@ import ( "regexp" "strconv" "strings" - "unicode/utf8" + "time" ) type resolveMapItem struct { @@ -75,7 +75,7 @@ func longTag(tag string) string { func resolvableTag(tag string) bool { switch tag { - case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG: + case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG, yaml_TIMESTAMP_TAG: return true } return false @@ -92,6 +92,19 @@ func resolve(tag string, in string) (rtag string, out interface{}) { switch tag { case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: return + case yaml_FLOAT_TAG: + if rtag == yaml_INT_TAG { + switch v := out.(type) { + case int64: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + case int: + rtag = yaml_FLOAT_TAG + out = float64(v) + return + } + } } failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) }() @@ -125,6 +138,15 @@ func resolve(tag string, in string) (rtag string, out interface{}) { case 'D', 'S': // Int, float, or timestamp. + // Only try values as a timestamp if the value is unquoted or there's an explicit + // !!timestamp tag. + if tag == "" || tag == yaml_TIMESTAMP_TAG { + t, ok := parseTimestamp(in) + if ok { + return yaml_TIMESTAMP_TAG, t + } + } + plain := strings.Replace(in, "_", "", -1) intv, err := strconv.ParseInt(plain, 0, 64) if err == nil { @@ -158,28 +180,20 @@ func resolve(tag string, in string) (rtag string, out interface{}) { return yaml_INT_TAG, uintv } } else if strings.HasPrefix(plain, "-0b") { - intv, err := strconv.ParseInt(plain[3:], 2, 64) + intv, err := strconv.ParseInt("-" + plain[3:], 2, 64) if err == nil { - if intv == int64(int(intv)) { - return yaml_INT_TAG, -int(intv) + if true || intv == int64(int(intv)) { + return yaml_INT_TAG, int(intv) } else { - return yaml_INT_TAG, -intv + return yaml_INT_TAG, intv } } } - // XXX Handle timestamps here. - default: panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") } } - if tag == yaml_BINARY_TAG { - return yaml_BINARY_TAG, in - } - if utf8.ValidString(in) { - return yaml_STR_TAG, in - } - return yaml_BINARY_TAG, encodeBase64(in) + return yaml_STR_TAG, in } // encodeBase64 encodes s as base64 that is broken up into multiple lines @@ -206,3 +220,39 @@ func encodeBase64(s string) string { } return string(out[:k]) } + +// This is a subset of the formats allowed by the regular expression +// defined at http://yaml.org/type/timestamp.html. +var allowedTimestampFormats = []string{ + "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields. + "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t". + "2006-1-2 15:4:5.999999999", // space separated with no time zone + "2006-1-2", // date only + // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5" + // from the set of examples. +} + +// parseTimestamp parses s as a timestamp string and +// returns the timestamp and reports whether it succeeded. +// Timestamp formats are defined at http://yaml.org/type/timestamp.html +func parseTimestamp(s string) (time.Time, bool) { + // TODO write code to check all the formats supported by + // http://yaml.org/type/timestamp.html instead of using time.Parse. + + // Quick check: all date formats start with YYYY-. + i := 0 + for ; i < len(s); i++ { + if c := s[i]; c < '0' || c > '9' { + break + } + } + if i != 4 || i == len(s) || s[i] != '-' { + return time.Time{}, false + } + for _, format := range allowedTimestampFormats { + if t, err := time.Parse(format, s); err == nil { + return t, true + } + } + return time.Time{}, false +} diff --git a/vendor/gopkg.in/yaml.v2/scannerc.go b/vendor/gopkg.in/yaml.v2/scannerc.go index 0744844558..077fd1dd2d 100644 --- a/vendor/gopkg.in/yaml.v2/scannerc.go +++ b/vendor/gopkg.in/yaml.v2/scannerc.go @@ -871,12 +871,6 @@ func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { required := parser.flow_level == 0 && parser.indent == parser.mark.column - // A simple key is required only when it is the first token in the current - // line. Therefore it is always allowed. But we add a check anyway. - if required && !parser.simple_key_allowed { - panic("should not happen") - } - // // If the current position may start a simple key, save it. // @@ -2475,6 +2469,10 @@ func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, si } } + if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { + return false + } + // Check if we are at the end of the scalar. if single { if parser.buffer[parser.buffer_pos] == '\'' { @@ -2487,10 +2485,6 @@ func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, si } // Consume blank characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { if is_blank(parser.buffer, parser.buffer_pos) { // Consume a space or a tab character. @@ -2592,19 +2586,10 @@ func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) b // Consume non-blank characters. for !is_blankz(parser.buffer, parser.buffer_pos) { - // Check for 'x:x' in the flow context. TODO: Fix the test "spec-08-13". - if parser.flow_level > 0 && - parser.buffer[parser.buffer_pos] == ':' && - !is_blankz(parser.buffer, parser.buffer_pos+1) { - yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", - start_mark, "found unexpected ':'") - return false - } - // Check for indicators that may end a plain scalar. if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || (parser.flow_level > 0 && - (parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == ':' || + (parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || parser.buffer[parser.buffer_pos] == '}')) { @@ -2656,10 +2641,10 @@ func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) b for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { if is_blank(parser.buffer, parser.buffer_pos) { - // Check for tab character that abuse indentation. + // Check for tab characters that abuse indentation. if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", - start_mark, "found a tab character that violate indentation") + start_mark, "found a tab character that violates indentation") return false } diff --git a/vendor/gopkg.in/yaml.v2/sorter.go b/vendor/gopkg.in/yaml.v2/sorter.go index 5958822f9c..4c45e660a8 100644 --- a/vendor/gopkg.in/yaml.v2/sorter.go +++ b/vendor/gopkg.in/yaml.v2/sorter.go @@ -51,6 +51,15 @@ func (l keyList) Less(i, j int) bool { } var ai, bi int var an, bn int64 + if ar[i] == '0' || br[i] == '0' { + for j := i-1; j >= 0 && unicode.IsDigit(ar[j]); j-- { + if ar[j] != '0' { + an = 1 + bn = 1 + break + } + } + } for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { an = an*10 + int64(ar[ai]-'0') } diff --git a/vendor/gopkg.in/yaml.v2/suite_test.go b/vendor/gopkg.in/yaml.v2/suite_test.go deleted file mode 100644 index c5cf1ed4f6..0000000000 --- a/vendor/gopkg.in/yaml.v2/suite_test.go +++ /dev/null @@ -1,12 +0,0 @@ -package yaml_test - -import ( - . "gopkg.in/check.v1" - "testing" -) - -func Test(t *testing.T) { TestingT(t) } - -type S struct{} - -var _ = Suite(&S{}) diff --git a/vendor/gopkg.in/yaml.v2/writerc.go b/vendor/gopkg.in/yaml.v2/writerc.go index 190362f25d..a2dde608cb 100644 --- a/vendor/gopkg.in/yaml.v2/writerc.go +++ b/vendor/gopkg.in/yaml.v2/writerc.go @@ -18,72 +18,9 @@ func yaml_emitter_flush(emitter *yaml_emitter_t) bool { return true } - // If the output encoding is UTF-8, we don't need to recode the buffer. - if emitter.encoding == yaml_UTF8_ENCODING { - if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { - return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) - } - emitter.buffer_pos = 0 - return true - } - - // Recode the buffer into the raw buffer. - var low, high int - if emitter.encoding == yaml_UTF16LE_ENCODING { - low, high = 0, 1 - } else { - high, low = 1, 0 - } - - pos := 0 - for pos < emitter.buffer_pos { - // See the "reader.c" code for more details on UTF-8 encoding. Note - // that we assume that the buffer contains a valid UTF-8 sequence. - - // Read the next UTF-8 character. - octet := emitter.buffer[pos] - - var w int - var value rune - switch { - case octet&0x80 == 0x00: - w, value = 1, rune(octet&0x7F) - case octet&0xE0 == 0xC0: - w, value = 2, rune(octet&0x1F) - case octet&0xF0 == 0xE0: - w, value = 3, rune(octet&0x0F) - case octet&0xF8 == 0xF0: - w, value = 4, rune(octet&0x07) - } - for k := 1; k < w; k++ { - octet = emitter.buffer[pos+k] - value = (value << 6) + (rune(octet) & 0x3F) - } - pos += w - - // Write the character. - if value < 0x10000 { - var b [2]byte - b[high] = byte(value >> 8) - b[low] = byte(value & 0xFF) - emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1]) - } else { - // Write the character using a surrogate pair (check "reader.c"). - var b [4]byte - value -= 0x10000 - b[high] = byte(0xD8 + (value >> 18)) - b[low] = byte((value >> 10) & 0xFF) - b[high+2] = byte(0xDC + ((value >> 8) & 0xFF)) - b[low+2] = byte(value & 0xFF) - emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1], b[2], b[3]) - } - } - - // Write the raw buffer. - if err := emitter.write_handler(emitter, emitter.raw_buffer); err != nil { + if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) } emitter.buffer_pos = 0 - emitter.raw_buffer = emitter.raw_buffer[:0] return true } diff --git a/vendor/gopkg.in/yaml.v2/yaml.go b/vendor/gopkg.in/yaml.v2/yaml.go index bf18884e0e..de85aa4cdb 100644 --- a/vendor/gopkg.in/yaml.v2/yaml.go +++ b/vendor/gopkg.in/yaml.v2/yaml.go @@ -9,6 +9,7 @@ package yaml import ( "errors" "fmt" + "io" "reflect" "strings" "sync" @@ -81,12 +82,58 @@ func Unmarshal(in []byte, out interface{}) (err error) { } // UnmarshalStrict is like Unmarshal except that any fields that are found -// in the data that do not have corresponding struct members will result in +// in the data that do not have corresponding struct members, or mapping +// keys that are duplicates, will result in // an error. func UnmarshalStrict(in []byte, out interface{}) (err error) { return unmarshal(in, out, true) } +// A Decorder reads and decodes YAML values from an input stream. +type Decoder struct { + strict bool + parser *parser +} + +// NewDecoder returns a new decoder that reads from r. +// +// The decoder introduces its own buffering and may read +// data from r beyond the YAML values requested. +func NewDecoder(r io.Reader) *Decoder { + return &Decoder{ + parser: newParserFromReader(r), + } +} + +// SetStrict sets whether strict decoding behaviour is enabled when +// decoding items in the data (see UnmarshalStrict). By default, decoding is not strict. +func (dec *Decoder) SetStrict(strict bool) { + dec.strict = strict +} + +// Decode reads the next YAML-encoded value from its input +// and stores it in the value pointed to by v. +// +// See the documentation for Unmarshal for details about the +// conversion of YAML into a Go value. +func (dec *Decoder) Decode(v interface{}) (err error) { + d := newDecoder(dec.strict) + defer handleErr(&err) + node := dec.parser.parse() + if node == nil { + return io.EOF + } + out := reflect.ValueOf(v) + if out.Kind() == reflect.Ptr && !out.IsNil() { + out = out.Elem() + } + d.unmarshal(node, out) + if len(d.terrors) > 0 { + return &TypeError{d.terrors} + } + return nil +} + func unmarshal(in []byte, out interface{}, strict bool) (err error) { defer handleErr(&err) d := newDecoder(strict) @@ -110,8 +157,8 @@ func unmarshal(in []byte, out interface{}, strict bool) (err error) { // of the generated document will reflect the structure of the value itself. // Maps and pointers (to struct, string, int, etc) are accepted as the in value. // -// Struct fields are only unmarshalled if they are exported (have an upper case -// first letter), and are unmarshalled using the field name lowercased as the +// Struct fields are only marshalled if they are exported (have an upper case +// first letter), and are marshalled using the field name lowercased as the // default key. Custom keys may be defined via the "yaml" name in the field // tag: the content preceding the first comma is used as the key, and the // following comma-separated options are used to tweak the marshalling process. @@ -125,7 +172,10 @@ func unmarshal(in []byte, out interface{}, strict bool) (err error) { // // omitempty Only include the field if it's not set to the zero // value for the type or to empty slices or maps. -// Does not apply to zero valued structs. +// Zero valued structs will be omitted if all their public +// fields are zero, unless they implement an IsZero +// method (see the IsZeroer interface type), in which +// case the field will be included if that method returns true. // // flow Marshal using a flow style (useful for structs, // sequences and maps). @@ -140,7 +190,7 @@ func unmarshal(in []byte, out interface{}, strict bool) (err error) { // For example: // // type T struct { -// F int "a,omitempty" +// F int `yaml:"a,omitempty"` // B int // } // yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" @@ -150,12 +200,47 @@ func Marshal(in interface{}) (out []byte, err error) { defer handleErr(&err) e := newEncoder() defer e.destroy() - e.marshal("", reflect.ValueOf(in)) + e.marshalDoc("", reflect.ValueOf(in)) e.finish() out = e.out return } +// An Encoder writes YAML values to an output stream. +type Encoder struct { + encoder *encoder +} + +// NewEncoder returns a new encoder that writes to w. +// The Encoder should be closed after use to flush all data +// to w. +func NewEncoder(w io.Writer) *Encoder { + return &Encoder{ + encoder: newEncoderWithWriter(w), + } +} + +// Encode writes the YAML encoding of v to the stream. +// If multiple items are encoded to the stream, the +// second and subsequent document will be preceded +// with a "---" document separator, but the first will not. +// +// See the documentation for Marshal for details about the conversion of Go +// values to YAML. +func (e *Encoder) Encode(v interface{}) (err error) { + defer handleErr(&err) + e.encoder.marshalDoc("", reflect.ValueOf(v)) + return nil +} + +// Close closes the encoder by writing any remaining data. +// It does not write a stream terminating string "...". +func (e *Encoder) Close() (err error) { + defer handleErr(&err) + e.encoder.finish() + return nil +} + func handleErr(err *error) { if v := recover(); v != nil { if e, ok := v.(yamlError); ok { @@ -211,6 +296,9 @@ type fieldInfo struct { Num int OmitEmpty bool Flow bool + // Id holds the unique field identifier, so we can cheaply + // check for field duplicates without maintaining an extra map. + Id int // Inline holds the field index if the field is part of an inlined struct. Inline []int @@ -290,6 +378,7 @@ func getStructInfo(st reflect.Type) (*structInfo, error) { } else { finfo.Inline = append([]int{i}, finfo.Inline...) } + finfo.Id = len(fieldsList) fieldsMap[finfo.Key] = finfo fieldsList = append(fieldsList, finfo) } @@ -311,11 +400,16 @@ func getStructInfo(st reflect.Type) (*structInfo, error) { return nil, errors.New(msg) } + info.Id = len(fieldsList) fieldsList = append(fieldsList, info) fieldsMap[info.Key] = info } - sinfo = &structInfo{fieldsMap, fieldsList, inlineMap} + sinfo = &structInfo{ + FieldsMap: fieldsMap, + FieldsList: fieldsList, + InlineMap: inlineMap, + } fieldMapMutex.Lock() structMap[st] = sinfo @@ -323,8 +417,23 @@ func getStructInfo(st reflect.Type) (*structInfo, error) { return sinfo, nil } +// IsZeroer is used to check whether an object is zero to +// determine whether it should be omitted when marshaling +// with the omitempty flag. One notable implementation +// is time.Time. +type IsZeroer interface { + IsZero() bool +} + func isZero(v reflect.Value) bool { - switch v.Kind() { + kind := v.Kind() + if z, ok := v.Interface().(IsZeroer); ok { + if (kind == reflect.Ptr || kind == reflect.Interface) && v.IsNil() { + return true + } + return z.IsZero() + } + switch kind { case reflect.String: return len(v.String()) == 0 case reflect.Interface, reflect.Ptr: diff --git a/vendor/gopkg.in/yaml.v2/yamlh.go b/vendor/gopkg.in/yaml.v2/yamlh.go index 3caeca0491..e25cee563b 100644 --- a/vendor/gopkg.in/yaml.v2/yamlh.go +++ b/vendor/gopkg.in/yaml.v2/yamlh.go @@ -1,6 +1,7 @@ package yaml import ( + "fmt" "io" ) @@ -239,6 +240,27 @@ const ( yaml_MAPPING_END_EVENT // A MAPPING-END event. ) +var eventStrings = []string{ + yaml_NO_EVENT: "none", + yaml_STREAM_START_EVENT: "stream start", + yaml_STREAM_END_EVENT: "stream end", + yaml_DOCUMENT_START_EVENT: "document start", + yaml_DOCUMENT_END_EVENT: "document end", + yaml_ALIAS_EVENT: "alias", + yaml_SCALAR_EVENT: "scalar", + yaml_SEQUENCE_START_EVENT: "sequence start", + yaml_SEQUENCE_END_EVENT: "sequence end", + yaml_MAPPING_START_EVENT: "mapping start", + yaml_MAPPING_END_EVENT: "mapping end", +} + +func (e yaml_event_type_t) String() string { + if e < 0 || int(e) >= len(eventStrings) { + return fmt.Sprintf("unknown event %d", e) + } + return eventStrings[e] +} + // The event structure. type yaml_event_t struct { @@ -521,9 +543,9 @@ type yaml_parser_t struct { read_handler yaml_read_handler_t // Read handler. - input_file io.Reader // File input data. - input []byte // String input data. - input_pos int + input_reader io.Reader // File input data. + input []byte // String input data. + input_pos int eof bool // EOF flag @@ -632,7 +654,7 @@ type yaml_emitter_t struct { write_handler yaml_write_handler_t // Write handler. output_buffer *[]byte // String output data. - output_file io.Writer // File output data. + output_writer io.Writer // File output data. buffer []byte // The working buffer. buffer_pos int // The current position of the buffer. diff --git a/vendor/k8s.io/api/admissionregistration/v1alpha1/BUILD b/vendor/k8s.io/api/admissionregistration/v1alpha1/BUILD deleted file mode 100644 index 417eab39ff..0000000000 --- a/vendor/k8s.io/api/admissionregistration/v1alpha1/BUILD +++ /dev/null @@ -1,44 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/admissionregistration/v1alpha1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/admissionregistration/v1beta1/BUILD b/vendor/k8s.io/api/admissionregistration/v1beta1/BUILD deleted file mode 100644 index dbcfadd2bf..0000000000 --- a/vendor/k8s.io/api/admissionregistration/v1beta1/BUILD +++ /dev/null @@ -1,44 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/admissionregistration/v1beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/apps/v1/BUILD b/vendor/k8s.io/api/apps/v1/BUILD deleted file mode 100644 index 7902387f59..0000000000 --- a/vendor/k8s.io/api/apps/v1/BUILD +++ /dev/null @@ -1,43 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/apps/v1", - visibility = ["//visibility:public"], - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/intstr:go_default_library", - ], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/apps/v1beta1/BUILD b/vendor/k8s.io/api/apps/v1beta1/BUILD deleted file mode 100644 index f40a41e3e2..0000000000 --- a/vendor/k8s.io/api/apps/v1beta1/BUILD +++ /dev/null @@ -1,47 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/apps/v1beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/intstr:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/apps/v1beta2/BUILD b/vendor/k8s.io/api/apps/v1beta2/BUILD deleted file mode 100644 index c13a6ff578..0000000000 --- a/vendor/k8s.io/api/apps/v1beta2/BUILD +++ /dev/null @@ -1,47 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/apps/v1beta2", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/intstr:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/authentication/v1/BUILD b/vendor/k8s.io/api/authentication/v1/BUILD deleted file mode 100644 index 26e557e469..0000000000 --- a/vendor/k8s.io/api/authentication/v1/BUILD +++ /dev/null @@ -1,46 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/authentication/v1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/types:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/authentication/v1beta1/BUILD b/vendor/k8s.io/api/authentication/v1beta1/BUILD deleted file mode 100644 index 998d793fef..0000000000 --- a/vendor/k8s.io/api/authentication/v1beta1/BUILD +++ /dev/null @@ -1,45 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/authentication/v1beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/authorization/v1/BUILD b/vendor/k8s.io/api/authorization/v1/BUILD deleted file mode 100644 index af9e74a635..0000000000 --- a/vendor/k8s.io/api/authorization/v1/BUILD +++ /dev/null @@ -1,45 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/authorization/v1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/authorization/v1beta1/BUILD b/vendor/k8s.io/api/authorization/v1beta1/BUILD deleted file mode 100644 index 06c953f2a9..0000000000 --- a/vendor/k8s.io/api/authorization/v1beta1/BUILD +++ /dev/null @@ -1,45 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/authorization/v1beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/autoscaling/v1/BUILD b/vendor/k8s.io/api/autoscaling/v1/BUILD deleted file mode 100644 index ccf587be09..0000000000 --- a/vendor/k8s.io/api/autoscaling/v1/BUILD +++ /dev/null @@ -1,46 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/autoscaling/v1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/resource:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/autoscaling/v2beta1/BUILD b/vendor/k8s.io/api/autoscaling/v2beta1/BUILD deleted file mode 100644 index 32fc333eb5..0000000000 --- a/vendor/k8s.io/api/autoscaling/v2beta1/BUILD +++ /dev/null @@ -1,46 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/autoscaling/v2beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/resource:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/batch/v1/BUILD b/vendor/k8s.io/api/batch/v1/BUILD deleted file mode 100644 index a7ca7a2326..0000000000 --- a/vendor/k8s.io/api/batch/v1/BUILD +++ /dev/null @@ -1,45 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/batch/v1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/batch/v1beta1/BUILD b/vendor/k8s.io/api/batch/v1beta1/BUILD deleted file mode 100644 index 3f0197b9c6..0000000000 --- a/vendor/k8s.io/api/batch/v1beta1/BUILD +++ /dev/null @@ -1,46 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/batch/v1beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/api/batch/v1:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/batch/v2alpha1/BUILD b/vendor/k8s.io/api/batch/v2alpha1/BUILD deleted file mode 100644 index 0fc0ab57ac..0000000000 --- a/vendor/k8s.io/api/batch/v2alpha1/BUILD +++ /dev/null @@ -1,46 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/batch/v2alpha1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/api/batch/v1:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/certificates/v1beta1/BUILD b/vendor/k8s.io/api/certificates/v1beta1/BUILD deleted file mode 100644 index 4c94dd0648..0000000000 --- a/vendor/k8s.io/api/certificates/v1beta1/BUILD +++ /dev/null @@ -1,45 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/certificates/v1beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/core/v1/BUILD b/vendor/k8s.io/api/core/v1/BUILD deleted file mode 100644 index 560ff5bd73..0000000000 --- a/vendor/k8s.io/api/core/v1/BUILD +++ /dev/null @@ -1,64 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "taint_test.go", - "toleration_test.go", - ], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "annotation_key_constants.go", - "doc.go", - "generated.pb.go", - "meta.go", - "objectreference.go", - "register.go", - "resource.go", - "taint.go", - "toleration.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/core/v1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/resource:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/types:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/intstr:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/core/v1/taint_test.go b/vendor/k8s.io/api/core/v1/taint_test.go deleted file mode 100644 index 22c7f9c4fe..0000000000 --- a/vendor/k8s.io/api/core/v1/taint_test.go +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright 2017 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 v1 - -import ( - "testing" -) - -func TestTaintToString(t *testing.T) { - testCases := []struct { - taint *Taint - expectedString string - }{ - { - taint: &Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectedString: "foo=bar:NoSchedule", - }, - { - taint: &Taint{ - Key: "foo", - Effect: TaintEffectNoSchedule, - }, - expectedString: "foo:NoSchedule", - }, - } - - for i, tc := range testCases { - if tc.expectedString != tc.taint.ToString() { - t.Errorf("[%v] expected taint %v converted to %s, got %s", i, tc.taint, tc.expectedString, tc.taint.ToString()) - } - } -} - -func TestMatchTaint(t *testing.T) { - testCases := []struct { - description string - taint *Taint - taintToMatch Taint - expectMatch bool - }{ - { - description: "two taints with the same key,value,effect should match", - taint: &Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - taintToMatch: Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectMatch: true, - }, - { - description: "two taints with the same key,effect but different value should match", - taint: &Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - taintToMatch: Taint{ - Key: "foo", - Value: "different-value", - Effect: TaintEffectNoSchedule, - }, - expectMatch: true, - }, - { - description: "two taints with the different key cannot match", - taint: &Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - taintToMatch: Taint{ - Key: "different-key", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectMatch: false, - }, - { - description: "two taints with the different effect cannot match", - taint: &Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - taintToMatch: Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectPreferNoSchedule, - }, - expectMatch: false, - }, - } - - for _, tc := range testCases { - if tc.expectMatch != tc.taint.MatchTaint(&tc.taintToMatch) { - t.Errorf("[%s] expect taint %s match taint %s", tc.description, tc.taint.ToString(), tc.taintToMatch.ToString()) - } - } -} diff --git a/vendor/k8s.io/api/core/v1/toleration_test.go b/vendor/k8s.io/api/core/v1/toleration_test.go deleted file mode 100644 index 3dd48f0877..0000000000 --- a/vendor/k8s.io/api/core/v1/toleration_test.go +++ /dev/null @@ -1,123 +0,0 @@ -/* -Copyright 2017 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 v1 - -import ( - "testing" -) - -func TestTolerationToleratesTaint(t *testing.T) { - - testCases := []struct { - description string - toleration Toleration - taint Taint - expectTolerated bool - }{ - { - description: "toleration and taint have the same key and effect, and operator is Exists, and taint has no value, expect tolerated", - toleration: Toleration{ - Key: "foo", - Operator: TolerationOpExists, - Effect: TaintEffectNoSchedule, - }, - taint: Taint{ - Key: "foo", - Effect: TaintEffectNoSchedule, - }, - expectTolerated: true, - }, - { - description: "toleration and taint have the same key and effect, and operator is Exists, and taint has some value, expect tolerated", - toleration: Toleration{ - Key: "foo", - Operator: TolerationOpExists, - Effect: TaintEffectNoSchedule, - }, - taint: Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectTolerated: true, - }, - { - description: "toleration and taint have the same effect, toleration has empty key and operator is Exists, means match all taints, expect tolerated", - toleration: Toleration{ - Key: "", - Operator: TolerationOpExists, - Effect: TaintEffectNoSchedule, - }, - taint: Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectTolerated: true, - }, - { - description: "toleration and taint have the same key, effect and value, and operator is Equal, expect tolerated", - toleration: Toleration{ - Key: "foo", - Operator: TolerationOpEqual, - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - taint: Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectTolerated: true, - }, - { - description: "toleration and taint have the same key and effect, but different values, and operator is Equal, expect not tolerated", - toleration: Toleration{ - Key: "foo", - Operator: TolerationOpEqual, - Value: "value1", - Effect: TaintEffectNoSchedule, - }, - taint: Taint{ - Key: "foo", - Value: "value2", - Effect: TaintEffectNoSchedule, - }, - expectTolerated: false, - }, - { - description: "toleration and taint have the same key and value, but different effects, and operator is Equal, expect not tolerated", - toleration: Toleration{ - Key: "foo", - Operator: TolerationOpEqual, - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - taint: Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoExecute, - }, - expectTolerated: false, - }, - } - for _, tc := range testCases { - if tolerated := tc.toleration.ToleratesTaint(&tc.taint); tc.expectTolerated != tolerated { - t.Errorf("[%s] expect %v, got %v: toleration %+v, taint %s", tc.description, tc.expectTolerated, tolerated, tc.toleration, tc.taint.ToString()) - } - } -} diff --git a/vendor/k8s.io/api/core/v1/types.go b/vendor/k8s.io/api/core/v1/types.go index 08ef4194ea..8a69833f54 100644 --- a/vendor/k8s.io/api/core/v1/types.go +++ b/vendor/k8s.io/api/core/v1/types.go @@ -1831,6 +1831,12 @@ type VolumeMount struct { type MountPropagationMode string const ( + // MountPropagationNone 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. + MountPropagationNone MountPropagationMode = "None" // MountPropagationHostToContainer 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 diff --git a/vendor/k8s.io/api/events/v1beta1/BUILD b/vendor/k8s.io/api/events/v1beta1/BUILD deleted file mode 100644 index 851874e78c..0000000000 --- a/vendor/k8s.io/api/events/v1beta1/BUILD +++ /dev/null @@ -1,42 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/events/v1beta1", - visibility = ["//visibility:public"], - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/extensions/v1beta1/BUILD b/vendor/k8s.io/api/extensions/v1beta1/BUILD deleted file mode 100644 index 360ad999c9..0000000000 --- a/vendor/k8s.io/api/extensions/v1beta1/BUILD +++ /dev/null @@ -1,49 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/extensions/v1beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/api/apps/v1beta1:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/resource:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/intstr:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/networking/v1/BUILD b/vendor/k8s.io/api/networking/v1/BUILD deleted file mode 100644 index beb3afcaf7..0000000000 --- a/vendor/k8s.io/api/networking/v1/BUILD +++ /dev/null @@ -1,46 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/networking/v1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/intstr:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/policy/v1beta1/BUILD b/vendor/k8s.io/api/policy/v1beta1/BUILD deleted file mode 100644 index d55d68e5d7..0000000000 --- a/vendor/k8s.io/api/policy/v1beta1/BUILD +++ /dev/null @@ -1,47 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/policy/v1beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/intstr:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/rbac/v1/BUILD b/vendor/k8s.io/api/rbac/v1/BUILD deleted file mode 100644 index 539afb7ae8..0000000000 --- a/vendor/k8s.io/api/rbac/v1/BUILD +++ /dev/null @@ -1,44 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/rbac/v1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/rbac/v1alpha1/BUILD b/vendor/k8s.io/api/rbac/v1alpha1/BUILD deleted file mode 100644 index 68d7cdfbb1..0000000000 --- a/vendor/k8s.io/api/rbac/v1alpha1/BUILD +++ /dev/null @@ -1,44 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/rbac/v1alpha1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/rbac/v1beta1/BUILD b/vendor/k8s.io/api/rbac/v1beta1/BUILD deleted file mode 100644 index c9aa763f41..0000000000 --- a/vendor/k8s.io/api/rbac/v1beta1/BUILD +++ /dev/null @@ -1,44 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/rbac/v1beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/scheduling/v1alpha1/BUILD b/vendor/k8s.io/api/scheduling/v1alpha1/BUILD deleted file mode 100644 index c8c1976647..0000000000 --- a/vendor/k8s.io/api/scheduling/v1alpha1/BUILD +++ /dev/null @@ -1,44 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/scheduling/v1alpha1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/settings/v1alpha1/BUILD b/vendor/k8s.io/api/settings/v1alpha1/BUILD deleted file mode 100644 index d7457427df..0000000000 --- a/vendor/k8s.io/api/settings/v1alpha1/BUILD +++ /dev/null @@ -1,45 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/settings/v1alpha1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/storage/v1/BUILD b/vendor/k8s.io/api/storage/v1/BUILD deleted file mode 100644 index 50a09f0eba..0000000000 --- a/vendor/k8s.io/api/storage/v1/BUILD +++ /dev/null @@ -1,43 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/storage/v1", - visibility = ["//visibility:public"], - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/storage/v1alpha1/BUILD b/vendor/k8s.io/api/storage/v1alpha1/BUILD deleted file mode 100644 index 98342a4262..0000000000 --- a/vendor/k8s.io/api/storage/v1alpha1/BUILD +++ /dev/null @@ -1,42 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/storage/v1alpha1", - visibility = ["//visibility:public"], - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/api/storage/v1beta1/BUILD b/vendor/k8s.io/api/storage/v1beta1/BUILD deleted file mode 100644 index e659e9de01..0000000000 --- a/vendor/k8s.io/api/storage/v1beta1/BUILD +++ /dev/null @@ -1,43 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/api/storage/v1beta1", - visibility = ["//visibility:public"], - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/api/core/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/apiextensions-apiserver/BUILD b/vendor/k8s.io/apiextensions-apiserver/BUILD deleted file mode 100644 index 8092fcb821..0000000000 --- a/vendor/k8s.io/apiextensions-apiserver/BUILD +++ /dev/null @@ -1,55 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_binary", - "go_library", -) - -go_binary( - name = "apiextensions-apiserver", - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["main.go"], - importpath = "k8s.io/apiextensions-apiserver", - deps = [ - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/k8s.io/apiextensions-apiserver/pkg/cmd/server:go_default_library", - "//vendor/k8s.io/apiserver/pkg/server:go_default_library", - "//vendor/k8s.io/apiserver/pkg/util/logs:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/examples/client-go:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/apiserver:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/internalclientset:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/client/informers/internalversion:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/internalversion:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/client/listers/apiextensions/v1beta1:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/cmd/server:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/controller/finalizer:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/controller/status:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/features:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresource:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/registry/customresourcedefinition:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/test/integration:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/BUILD b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/BUILD deleted file mode 100644 index b2ea73c41f..0000000000 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/BUILD +++ /dev/null @@ -1,52 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_library( - name = "go_default_library", - srcs = [ - "deepcopy.go", - "doc.go", - "helpers.go", - "register.go", - "types.go", - "types_jsonschema.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -go_test( - name = "go_default_test", - srcs = ["helpers_test.go"], - embed = [":go_default_library"], - deps = ["//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/fuzzer:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/install:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers_test.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers_test.go deleted file mode 100644 index 1abb498155..0000000000 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/helpers_test.go +++ /dev/null @@ -1,90 +0,0 @@ -/* -Copyright 2017 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 apiextensions - -import ( - "reflect" - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestCRDHasFinalizer(t *testing.T) { - tests := []struct { - name string - crd *CustomResourceDefinition - finalizerToCheck string - - expected bool - }{ - { - name: "missing", - crd: &CustomResourceDefinition{ - ObjectMeta: metav1.ObjectMeta{Finalizers: []string{"not-it"}}, - }, - finalizerToCheck: "it", - expected: false, - }, - { - name: "present", - crd: &CustomResourceDefinition{ - ObjectMeta: metav1.ObjectMeta{Finalizers: []string{"not-it", "it"}}, - }, - finalizerToCheck: "it", - expected: true, - }, - } - for _, tc := range tests { - actual := CRDHasFinalizer(tc.crd, tc.finalizerToCheck) - if tc.expected != actual { - t.Errorf("%v expected %v, got %v", tc.name, tc.expected, actual) - } - } -} - -func TestCRDRemoveFinalizer(t *testing.T) { - tests := []struct { - name string - crd *CustomResourceDefinition - finalizerToCheck string - - expected []string - }{ - { - name: "missing", - crd: &CustomResourceDefinition{ - ObjectMeta: metav1.ObjectMeta{Finalizers: []string{"not-it"}}, - }, - finalizerToCheck: "it", - expected: []string{"not-it"}, - }, - { - name: "present", - crd: &CustomResourceDefinition{ - ObjectMeta: metav1.ObjectMeta{Finalizers: []string{"not-it", "it"}}, - }, - finalizerToCheck: "it", - expected: []string{"not-it"}, - }, - } - for _, tc := range tests { - CRDRemoveFinalizer(tc.crd, tc.finalizerToCheck) - if !reflect.DeepEqual(tc.expected, tc.crd.Finalizers) { - t.Errorf("%v expected %v, got %v", tc.name, tc.expected, tc.crd.Finalizers) - } - } -} diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/BUILD b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/BUILD deleted file mode 100644 index 972732d4a4..0000000000 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/BUILD +++ /dev/null @@ -1,68 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_library( - name = "go_default_library", - srcs = [ - "conversion.go", - "deepcopy.go", - "defaults.go", - "doc.go", - "generated.pb.go", - "marshal.go", - "register.go", - "types.go", - "types_jsonschema.go", - "zz_generated.conversion.go", - "zz_generated.deepcopy.go", - "zz_generated.defaults.go", - ], - importpath = "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/json:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) - -go_test( - name = "go_default_test", - srcs = [ - "conversion_test.go", - "marshal_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - ], -) diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/conversion_test.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/conversion_test.go deleted file mode 100644 index a697dd9e3a..0000000000 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/conversion_test.go +++ /dev/null @@ -1,113 +0,0 @@ -/* -Copyright 2017 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 v1beta1 - -import ( - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/runtime" - - "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" -) - -func TestJSONConversion(t *testing.T) { - nilJSON := apiextensions.JSON(nil) - nullJSON := apiextensions.JSON("null") - stringJSON := apiextensions.JSON("foo") - boolJSON := apiextensions.JSON(true) - sliceJSON := apiextensions.JSON([]string{"foo", "bar", "baz"}) - - testCases := map[string]struct { - input *apiextensions.JSONSchemaProps - expected *JSONSchemaProps - }{ - "nil": { - input: &apiextensions.JSONSchemaProps{ - Default: nil, - }, - expected: &JSONSchemaProps{}, - }, - "aliased nil": { - input: &apiextensions.JSONSchemaProps{ - Default: &nilJSON, - }, - expected: &JSONSchemaProps{}, - }, - "null": { - input: &apiextensions.JSONSchemaProps{ - Default: &nullJSON, - }, - expected: &JSONSchemaProps{ - Default: &JSON{ - Raw: []byte(`"null"`), - }, - }, - }, - "string": { - input: &apiextensions.JSONSchemaProps{ - Default: &stringJSON, - }, - expected: &JSONSchemaProps{ - Default: &JSON{ - Raw: []byte(`"foo"`), - }, - }, - }, - "bool": { - input: &apiextensions.JSONSchemaProps{ - Default: &boolJSON, - }, - expected: &JSONSchemaProps{ - Default: &JSON{ - Raw: []byte(`true`), - }, - }, - }, - "slice": { - input: &apiextensions.JSONSchemaProps{ - Default: &sliceJSON, - }, - expected: &JSONSchemaProps{ - Default: &JSON{ - Raw: []byte(`["foo","bar","baz"]`), - }, - }, - }, - } - - scheme := runtime.NewScheme() - - // add internal and external types - if err := apiextensions.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - if err := AddToScheme(scheme); err != nil { - t.Fatal(err) - } - - for k, tc := range testCases { - external := &JSONSchemaProps{} - if err := scheme.Convert(tc.input, external, nil); err != nil { - t.Errorf("%s: unexpected error: %v", k, err) - } - - if !reflect.DeepEqual(external, tc.expected) { - t.Errorf("%s: expected\n\t%#v, got \n\t%#v", k, tc.expected, external) - } - } -} diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal_test.go b/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal_test.go deleted file mode 100644 index 0c6d4d4b52..0000000000 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/marshal_test.go +++ /dev/null @@ -1,150 +0,0 @@ -/* -Copyright 2017 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 v1beta1 - -import ( - "encoding/json" - "reflect" - "testing" -) - -type JSONSchemaPropsOrBoolHolder struct { - JSPoB JSONSchemaPropsOrBool `json:"val1"` - JSPoBOmitEmpty *JSONSchemaPropsOrBool `json:"val2,omitempty"` -} - -func TestJSONSchemaPropsOrBoolUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result JSONSchemaPropsOrBoolHolder - }{ - {`{}`, JSONSchemaPropsOrBoolHolder{}}, - - {`{"val1": {}}`, JSONSchemaPropsOrBoolHolder{JSPoB: JSONSchemaPropsOrBool{Schema: &JSONSchemaProps{}}}}, - {`{"val1": {"type":"string"}}`, JSONSchemaPropsOrBoolHolder{JSPoB: JSONSchemaPropsOrBool{Schema: &JSONSchemaProps{Type: "string"}}}}, - {`{"val1": false}`, JSONSchemaPropsOrBoolHolder{JSPoB: JSONSchemaPropsOrBool{}}}, - {`{"val1": true}`, JSONSchemaPropsOrBoolHolder{JSPoB: JSONSchemaPropsOrBool{Allows: true}}}, - - {`{"val2": {}}`, JSONSchemaPropsOrBoolHolder{JSPoBOmitEmpty: &JSONSchemaPropsOrBool{Schema: &JSONSchemaProps{}}}}, - {`{"val2": {"type":"string"}}`, JSONSchemaPropsOrBoolHolder{JSPoBOmitEmpty: &JSONSchemaPropsOrBool{Schema: &JSONSchemaProps{Type: "string"}}}}, - {`{"val2": false}`, JSONSchemaPropsOrBoolHolder{JSPoBOmitEmpty: &JSONSchemaPropsOrBool{}}}, - {`{"val2": true}`, JSONSchemaPropsOrBoolHolder{JSPoBOmitEmpty: &JSONSchemaPropsOrBool{Allows: true}}}, - } - - for _, c := range cases { - var result JSONSchemaPropsOrBoolHolder - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if !reflect.DeepEqual(result, c.result) { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) - } - } -} - -func TestStringArrayOrStringMarshalJSON(t *testing.T) { - cases := []struct { - input JSONSchemaPropsOrBoolHolder - result string - }{ - {JSONSchemaPropsOrBoolHolder{}, `{"val1":false}`}, - - {JSONSchemaPropsOrBoolHolder{JSPoB: JSONSchemaPropsOrBool{Schema: &JSONSchemaProps{}}}, `{"val1":{}}`}, - {JSONSchemaPropsOrBoolHolder{JSPoB: JSONSchemaPropsOrBool{Schema: &JSONSchemaProps{Type: "string"}}}, `{"val1":{"type":"string"}}`}, - {JSONSchemaPropsOrBoolHolder{JSPoB: JSONSchemaPropsOrBool{}}, `{"val1":false}`}, - {JSONSchemaPropsOrBoolHolder{JSPoB: JSONSchemaPropsOrBool{Allows: true}}, `{"val1":true}`}, - - {JSONSchemaPropsOrBoolHolder{JSPoBOmitEmpty: &JSONSchemaPropsOrBool{Schema: &JSONSchemaProps{}}}, `{"val1":false,"val2":{}}`}, - {JSONSchemaPropsOrBoolHolder{JSPoBOmitEmpty: &JSONSchemaPropsOrBool{Schema: &JSONSchemaProps{Type: "string"}}}, `{"val1":false,"val2":{"type":"string"}}`}, - {JSONSchemaPropsOrBoolHolder{JSPoBOmitEmpty: &JSONSchemaPropsOrBool{}}, `{"val1":false,"val2":false}`}, - {JSONSchemaPropsOrBoolHolder{JSPoBOmitEmpty: &JSONSchemaPropsOrBool{Allows: true}}, `{"val1":false,"val2":true}`}, - } - - for _, c := range cases { - result, err := json.Marshal(&c.input) - if err != nil { - t.Errorf("Unexpected error marshaling input '%v': %v", c.input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input '%v': expected: %q, got %q", c.input, c.result, string(result)) - } - } -} - -type JSONSchemaPropsOrArrayHolder struct { - JSPoA JSONSchemaPropsOrArray `json:"val1"` - JSPoAOmitEmpty *JSONSchemaPropsOrArray `json:"val2,omitempty"` -} - -func TestJSONSchemaPropsOrArrayUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result JSONSchemaPropsOrArrayHolder - }{ - {`{}`, JSONSchemaPropsOrArrayHolder{}}, - - {`{"val1": {}}`, JSONSchemaPropsOrArrayHolder{JSPoA: JSONSchemaPropsOrArray{Schema: &JSONSchemaProps{}}}}, - {`{"val1": {"type":"string"}}`, JSONSchemaPropsOrArrayHolder{JSPoA: JSONSchemaPropsOrArray{Schema: &JSONSchemaProps{Type: "string"}}}}, - {`{"val1": [{}]}`, JSONSchemaPropsOrArrayHolder{JSPoA: JSONSchemaPropsOrArray{JSONSchemas: []JSONSchemaProps{{}}}}}, - {`{"val1": [{},{"type":"string"}]}`, JSONSchemaPropsOrArrayHolder{JSPoA: JSONSchemaPropsOrArray{JSONSchemas: []JSONSchemaProps{{}, {Type: "string"}}}}}, - - {`{"val2": {}}`, JSONSchemaPropsOrArrayHolder{JSPoAOmitEmpty: &JSONSchemaPropsOrArray{Schema: &JSONSchemaProps{}}}}, - {`{"val2": {"type":"string"}}`, JSONSchemaPropsOrArrayHolder{JSPoAOmitEmpty: &JSONSchemaPropsOrArray{Schema: &JSONSchemaProps{Type: "string"}}}}, - {`{"val2": [{}]}`, JSONSchemaPropsOrArrayHolder{JSPoAOmitEmpty: &JSONSchemaPropsOrArray{JSONSchemas: []JSONSchemaProps{{}}}}}, - {`{"val2": [{},{"type":"string"}]}`, JSONSchemaPropsOrArrayHolder{JSPoAOmitEmpty: &JSONSchemaPropsOrArray{JSONSchemas: []JSONSchemaProps{{}, {Type: "string"}}}}}, - } - - for _, c := range cases { - var result JSONSchemaPropsOrArrayHolder - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if !reflect.DeepEqual(result, c.result) { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) - } - } -} - -func TestJSONSchemaPropsOrArrayMarshalJSON(t *testing.T) { - cases := []struct { - input JSONSchemaPropsOrArrayHolder - result string - }{ - {JSONSchemaPropsOrArrayHolder{}, `{"val1":null}`}, - - {JSONSchemaPropsOrArrayHolder{JSPoA: JSONSchemaPropsOrArray{Schema: &JSONSchemaProps{}}}, `{"val1":{}}`}, - {JSONSchemaPropsOrArrayHolder{JSPoA: JSONSchemaPropsOrArray{Schema: &JSONSchemaProps{Type: "string"}}}, `{"val1":{"type":"string"}}`}, - {JSONSchemaPropsOrArrayHolder{JSPoA: JSONSchemaPropsOrArray{JSONSchemas: []JSONSchemaProps{{}}}}, `{"val1":[{}]}`}, - {JSONSchemaPropsOrArrayHolder{JSPoA: JSONSchemaPropsOrArray{JSONSchemas: []JSONSchemaProps{{}, {Type: "string"}}}}, `{"val1":[{},{"type":"string"}]}`}, - - {JSONSchemaPropsOrArrayHolder{JSPoAOmitEmpty: &JSONSchemaPropsOrArray{}}, `{"val1":null,"val2":null}`}, - {JSONSchemaPropsOrArrayHolder{JSPoAOmitEmpty: &JSONSchemaPropsOrArray{Schema: &JSONSchemaProps{}}}, `{"val1":null,"val2":{}}`}, - {JSONSchemaPropsOrArrayHolder{JSPoAOmitEmpty: &JSONSchemaPropsOrArray{Schema: &JSONSchemaProps{Type: "string"}}}, `{"val1":null,"val2":{"type":"string"}}`}, - {JSONSchemaPropsOrArrayHolder{JSPoAOmitEmpty: &JSONSchemaPropsOrArray{JSONSchemas: []JSONSchemaProps{{}}}}, `{"val1":null,"val2":[{}]}`}, - {JSONSchemaPropsOrArrayHolder{JSPoAOmitEmpty: &JSONSchemaPropsOrArray{JSONSchemas: []JSONSchemaProps{{}, {Type: "string"}}}}, `{"val1":null,"val2":[{},{"type":"string"}]}`}, - } - - for i, c := range cases { - result, err := json.Marshal(&c.input) - if err != nil { - t.Errorf("%d: Unexpected error marshaling input '%v': %v", i, c.input, err) - } - if string(result) != c.result { - t.Errorf("%d: Failed to marshal input '%v': expected: %q, got %q", i, c.input, c.result, string(result)) - } - } -} diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/BUILD b/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/BUILD deleted file mode 100644 index c6312b7301..0000000000 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/BUILD +++ /dev/null @@ -1,40 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "clientset.go", - "doc.go", - ], - importpath = "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset", - deps = [ - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1:go_default_library", - "//vendor/k8s.io/client-go/discovery:go_default_library", - "//vendor/k8s.io/client-go/rest:go_default_library", - "//vendor/k8s.io/client-go/util/flowcontrol:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme:all-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme/BUILD b/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme/BUILD deleted file mode 100644 index 9906c9c1a1..0000000000 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme/BUILD +++ /dev/null @@ -1,35 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "register.go", - ], - importpath = "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme", - deps = [ - "//vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/BUILD b/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/BUILD deleted file mode 100644 index 054ceeca81..0000000000 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/BUILD +++ /dev/null @@ -1,42 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "apiextensions_client.go", - "customresourcedefinition.go", - "doc.go", - "generated_expansion.go", - ], - importpath = "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1", - deps = [ - "//vendor/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1:go_default_library", - "//vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/scheme:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/types:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/watch:go_default_library", - "//vendor/k8s.io/client-go/rest:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/typed/apiextensions/v1beta1/fake:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiextensions-apiserver/pkg/features/BUILD b/vendor/k8s.io/apiextensions-apiserver/pkg/features/BUILD deleted file mode 100644 index c6438cb40c..0000000000 --- a/vendor/k8s.io/apiextensions-apiserver/pkg/features/BUILD +++ /dev/null @@ -1,26 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = ["kube_features.go"], - importpath = "k8s.io/apiextensions-apiserver/pkg/features", - deps = ["//vendor/k8s.io/apiserver/pkg/util/feature:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/api/equality/BUILD b/vendor/k8s.io/apimachinery/pkg/api/equality/BUILD deleted file mode 100644 index 75051f35b0..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/equality/BUILD +++ /dev/null @@ -1,32 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = ["semantic.go"], - importpath = "k8s.io/apimachinery/pkg/api/equality", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/api/resource:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/fields:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/labels:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/api/errors/BUILD b/vendor/k8s.io/apimachinery/pkg/api/errors/BUILD deleted file mode 100644 index 785e9d8a6d..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/errors/BUILD +++ /dev/null @@ -1,47 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["errors_test.go"], - embed = [":go_default_library"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "errors.go", - ], - importpath = "k8s.io/apimachinery/pkg/api/errors", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/api/errors/errors_test.go b/vendor/k8s.io/apimachinery/pkg/api/errors/errors_test.go deleted file mode 100644 index 303a9d3f48..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/errors/errors_test.go +++ /dev/null @@ -1,222 +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 errors - -import ( - "errors" - "fmt" - "reflect" - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/validation/field" -) - -func resource(resource string) schema.GroupResource { - return schema.GroupResource{Group: "", Resource: resource} -} -func kind(kind string) schema.GroupKind { - return schema.GroupKind{Group: "", Kind: kind} -} - -func TestErrorNew(t *testing.T) { - err := NewAlreadyExists(resource("tests"), "1") - if !IsAlreadyExists(err) { - t.Errorf("expected to be %s", metav1.StatusReasonAlreadyExists) - } - if IsConflict(err) { - t.Errorf("expected to not be %s", metav1.StatusReasonConflict) - } - if IsNotFound(err) { - t.Errorf(fmt.Sprintf("expected to not be %s", metav1.StatusReasonNotFound)) - } - if IsInvalid(err) { - t.Errorf("expected to not be %s", metav1.StatusReasonInvalid) - } - if IsBadRequest(err) { - t.Errorf("expected to not be %s", metav1.StatusReasonBadRequest) - } - if IsForbidden(err) { - t.Errorf("expected to not be %s", metav1.StatusReasonForbidden) - } - if IsServerTimeout(err) { - t.Errorf("expected to not be %s", metav1.StatusReasonServerTimeout) - } - if IsMethodNotSupported(err) { - t.Errorf("expected to not be %s", metav1.StatusReasonMethodNotAllowed) - } - - if !IsConflict(NewConflict(resource("tests"), "2", errors.New("message"))) { - t.Errorf("expected to be conflict") - } - if !IsNotFound(NewNotFound(resource("tests"), "3")) { - t.Errorf("expected to be %s", metav1.StatusReasonNotFound) - } - if !IsInvalid(NewInvalid(kind("Test"), "2", nil)) { - t.Errorf("expected to be %s", metav1.StatusReasonInvalid) - } - if !IsBadRequest(NewBadRequest("reason")) { - t.Errorf("expected to be %s", metav1.StatusReasonBadRequest) - } - if !IsForbidden(NewForbidden(resource("tests"), "2", errors.New("reason"))) { - t.Errorf("expected to be %s", metav1.StatusReasonForbidden) - } - if !IsUnauthorized(NewUnauthorized("reason")) { - t.Errorf("expected to be %s", metav1.StatusReasonUnauthorized) - } - if !IsServerTimeout(NewServerTimeout(resource("tests"), "reason", 0)) { - t.Errorf("expected to be %s", metav1.StatusReasonServerTimeout) - } - if !IsMethodNotSupported(NewMethodNotSupported(resource("foos"), "delete")) { - t.Errorf("expected to be %s", metav1.StatusReasonMethodNotAllowed) - } - - if time, ok := SuggestsClientDelay(NewServerTimeout(resource("tests"), "doing something", 10)); time != 10 || !ok { - t.Errorf("unexpected %d", time) - } - if time, ok := SuggestsClientDelay(NewServerTimeout(resource("tests"), "doing something", 0)); time != 0 || !ok { - t.Errorf("unexpected %d", time) - } - if time, ok := SuggestsClientDelay(NewTimeoutError("test reason", 10)); time != 10 || !ok { - t.Errorf("unexpected %d", time) - } - if time, ok := SuggestsClientDelay(NewTooManyRequests("doing something", 10)); time != 10 || !ok { - t.Errorf("unexpected %d", time) - } - if time, ok := SuggestsClientDelay(NewTooManyRequests("doing something", 1)); time != 1 || !ok { - t.Errorf("unexpected %d", time) - } - if time, ok := SuggestsClientDelay(NewGenericServerResponse(429, "get", resource("tests"), "test", "doing something", 10, true)); time != 10 || !ok { - t.Errorf("unexpected %d", time) - } - if time, ok := SuggestsClientDelay(NewGenericServerResponse(500, "get", resource("tests"), "test", "doing something", 10, true)); time != 10 || !ok { - t.Errorf("unexpected %d", time) - } - if time, ok := SuggestsClientDelay(NewGenericServerResponse(429, "get", resource("tests"), "test", "doing something", 0, true)); time != 0 || ok { - t.Errorf("unexpected %d", time) - } -} - -func TestNewInvalid(t *testing.T) { - testCases := []struct { - Err *field.Error - Details *metav1.StatusDetails - }{ - { - field.Duplicate(field.NewPath("field[0].name"), "bar"), - &metav1.StatusDetails{ - Kind: "Kind", - Name: "name", - Causes: []metav1.StatusCause{{ - Type: metav1.CauseTypeFieldValueDuplicate, - Field: "field[0].name", - }}, - }, - }, - { - field.Invalid(field.NewPath("field[0].name"), "bar", "detail"), - &metav1.StatusDetails{ - Kind: "Kind", - Name: "name", - Causes: []metav1.StatusCause{{ - Type: metav1.CauseTypeFieldValueInvalid, - Field: "field[0].name", - }}, - }, - }, - { - field.NotFound(field.NewPath("field[0].name"), "bar"), - &metav1.StatusDetails{ - Kind: "Kind", - Name: "name", - Causes: []metav1.StatusCause{{ - Type: metav1.CauseTypeFieldValueNotFound, - Field: "field[0].name", - }}, - }, - }, - { - field.NotSupported(field.NewPath("field[0].name"), "bar", nil), - &metav1.StatusDetails{ - Kind: "Kind", - Name: "name", - Causes: []metav1.StatusCause{{ - Type: metav1.CauseTypeFieldValueNotSupported, - Field: "field[0].name", - }}, - }, - }, - { - field.Required(field.NewPath("field[0].name"), ""), - &metav1.StatusDetails{ - Kind: "Kind", - Name: "name", - Causes: []metav1.StatusCause{{ - Type: metav1.CauseTypeFieldValueRequired, - Field: "field[0].name", - }}, - }, - }, - } - for i, testCase := range testCases { - vErr, expected := testCase.Err, testCase.Details - expected.Causes[0].Message = vErr.ErrorBody() - err := NewInvalid(kind("Kind"), "name", field.ErrorList{vErr}) - status := err.ErrStatus - if status.Code != 422 || status.Reason != metav1.StatusReasonInvalid { - t.Errorf("%d: unexpected status: %#v", i, status) - } - if !reflect.DeepEqual(expected, status.Details) { - t.Errorf("%d: expected %#v, got %#v", i, expected, status.Details) - } - } -} - -func TestReasonForError(t *testing.T) { - if e, a := metav1.StatusReasonUnknown, ReasonForError(nil); e != a { - t.Errorf("unexpected reason type: %#v", a) - } -} - -type TestType struct{} - -func (obj *TestType) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } -func (obj *TestType) DeepCopyObject() runtime.Object { - if obj == nil { - return nil - } - clone := *obj - return &clone -} - -func TestFromObject(t *testing.T) { - table := []struct { - obj runtime.Object - message string - }{ - {&metav1.Status{Message: "foobar"}, "foobar"}, - {&TestType{}, "unexpected object: &{}"}, - } - - for _, item := range table { - if e, a := item.message, FromObject(item.obj).Error(); e != a { - t.Errorf("Expected %v, got %v", e, a) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/BUILD b/vendor/k8s.io/apimachinery/pkg/api/meta/BUILD deleted file mode 100644 index a02a1fb5b8..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/meta/BUILD +++ /dev/null @@ -1,72 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "meta_test.go", - "multirestmapper_test.go", - "priority_test.go", - "restmapper_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/github.com/google/gofuzz:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/diff:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "errors.go", - "firsthit_restmapper.go", - "help.go", - "interfaces.go", - "lazy.go", - "meta.go", - "multirestmapper.go", - "priority.go", - "restmapper.go", - "unstructured.go", - ], - importpath = "k8s.io/apimachinery/pkg/api/meta", - deps = [ - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/types:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/errors:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/api/meta/table:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/meta_test.go b/vendor/k8s.io/apimachinery/pkg/api/meta/meta_test.go deleted file mode 100644 index 4680bae9a8..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/meta/meta_test.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright 2017 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 meta - -import ( - "math/rand" - "reflect" - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" - "k8s.io/apimachinery/pkg/util/diff" - - fuzz "github.com/google/gofuzz" -) - -func TestAsPartialObjectMetadata(t *testing.T) { - f := fuzz.New().NilChance(.5).NumElements(0, 1).RandSource(rand.NewSource(1)) - - for i := 0; i < 100; i++ { - m := &metav1.ObjectMeta{} - f.Fuzz(m) - partial := AsPartialObjectMetadata(m) - if !reflect.DeepEqual(&partial.ObjectMeta, m) { - t.Fatalf("incomplete partial object metadata: %s", diff.ObjectReflectDiff(&partial.ObjectMeta, m)) - } - } - - for i := 0; i < 100; i++ { - m := &metav1beta1.PartialObjectMetadata{} - f.Fuzz(&m.ObjectMeta) - partial := AsPartialObjectMetadata(m) - if !reflect.DeepEqual(&partial.ObjectMeta, &m.ObjectMeta) { - t.Fatalf("incomplete partial object metadata: %s", diff.ObjectReflectDiff(&partial.ObjectMeta, &m.ObjectMeta)) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper_test.go b/vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper_test.go deleted file mode 100644 index b71ca468d3..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/meta/multirestmapper_test.go +++ /dev/null @@ -1,391 +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 meta - -import ( - "errors" - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func TestMultiRESTMapperResourceFor(t *testing.T) { - tcs := []struct { - name string - - mapper MultiRESTMapper - input schema.GroupVersionResource - result schema.GroupVersionResource - err error - }{ - { - name: "empty", - mapper: MultiRESTMapper{}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: schema.GroupVersionResource{}, - err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "ignore not found", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}}}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: schema.GroupVersionResource{}, - err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "accept first failure", - mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "unused"}}}}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: schema.GroupVersionResource{}, - err: errors.New("fail on this"), - }, - } - - for _, tc := range tcs { - actualResult, actualErr := tc.mapper.ResourceFor(tc.input) - if e, a := tc.result, actualResult; e != a { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - switch { - case tc.err == nil && actualErr == nil: - case tc.err == nil: - t.Errorf("%s: unexpected error: %v", tc.name, actualErr) - case actualErr == nil: - t.Errorf("%s: expected error: %v got nil", tc.name, tc.err) - case tc.err.Error() != actualErr.Error(): - t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr) - } - } -} - -func TestMultiRESTMapperResourcesFor(t *testing.T) { - tcs := []struct { - name string - - mapper MultiRESTMapper - input schema.GroupVersionResource - result []schema.GroupVersionResource - err error - }{ - { - name: "empty", - mapper: MultiRESTMapper{}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: nil, - err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "ignore not found", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}}}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: nil, - err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "accept first failure", - mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "unused"}}}}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: nil, - err: errors.New("fail on this"), - }, - { - name: "union and dedup", - mapper: MultiRESTMapper{ - fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "dupe"}, {Resource: "first"}}}, - fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "dupe"}, {Resource: "second"}}}, - }, - input: schema.GroupVersionResource{Resource: "foo"}, - result: []schema.GroupVersionResource{{Resource: "dupe"}, {Resource: "first"}, {Resource: "second"}}, - }, - { - name: "skip not and continue", - mapper: MultiRESTMapper{ - fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}}, - fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "first"}, {Resource: "second"}}}, - }, - input: schema.GroupVersionResource{Resource: "foo"}, - result: []schema.GroupVersionResource{{Resource: "first"}, {Resource: "second"}}, - }, - } - - for _, tc := range tcs { - actualResult, actualErr := tc.mapper.ResourcesFor(tc.input) - if e, a := tc.result, actualResult; !reflect.DeepEqual(e, a) { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - switch { - case tc.err == nil && actualErr == nil: - case tc.err == nil: - t.Errorf("%s: unexpected error: %v", tc.name, actualErr) - case actualErr == nil: - t.Errorf("%s: expected error: %v got nil", tc.name, tc.err) - case tc.err.Error() != actualErr.Error(): - t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr) - } - } -} - -func TestMultiRESTMapperKindsFor(t *testing.T) { - tcs := []struct { - name string - - mapper MultiRESTMapper - input schema.GroupVersionResource - result []schema.GroupVersionKind - err error - }{ - { - name: "empty", - mapper: MultiRESTMapper{}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: nil, - err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "ignore not found", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}}}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: nil, - err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "accept first failure", - mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "unused"}}}}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: nil, - err: errors.New("fail on this"), - }, - { - name: "union and dedup", - mapper: MultiRESTMapper{ - fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "dupe"}, {Kind: "first"}}}, - fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "dupe"}, {Kind: "second"}}}, - }, - input: schema.GroupVersionResource{Resource: "foo"}, - result: []schema.GroupVersionKind{{Kind: "dupe"}, {Kind: "first"}, {Kind: "second"}}, - }, - { - name: "skip not and continue", - mapper: MultiRESTMapper{ - fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}}, - fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "first"}, {Kind: "second"}}}, - }, - input: schema.GroupVersionResource{Resource: "foo"}, - result: []schema.GroupVersionKind{{Kind: "first"}, {Kind: "second"}}, - }, - } - - for _, tc := range tcs { - actualResult, actualErr := tc.mapper.KindsFor(tc.input) - if e, a := tc.result, actualResult; !reflect.DeepEqual(e, a) { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - switch { - case tc.err == nil && actualErr == nil: - case tc.err == nil: - t.Errorf("%s: unexpected error: %v", tc.name, actualErr) - case actualErr == nil: - t.Errorf("%s: expected error: %v got nil", tc.name, tc.err) - case tc.err.Error() != actualErr.Error(): - t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr) - } - } -} - -func TestMultiRESTMapperKindFor(t *testing.T) { - tcs := []struct { - name string - - mapper MultiRESTMapper - input schema.GroupVersionResource - result schema.GroupVersionKind - err error - }{ - { - name: "empty", - mapper: MultiRESTMapper{}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: schema.GroupVersionKind{}, - err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "ignore not found", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "IGNORE_THIS"}}}}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: schema.GroupVersionKind{}, - err: &NoResourceMatchError{PartialResource: schema.GroupVersionResource{Resource: "foo"}}, - }, - { - name: "accept first failure", - mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "unused"}}}}, - input: schema.GroupVersionResource{Resource: "foo"}, - result: schema.GroupVersionKind{}, - err: errors.New("fail on this"), - }, - } - - for _, tc := range tcs { - actualResult, actualErr := tc.mapper.KindFor(tc.input) - if e, a := tc.result, actualResult; e != a { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - switch { - case tc.err == nil && actualErr == nil: - case tc.err == nil: - t.Errorf("%s: unexpected error: %v", tc.name, actualErr) - case actualErr == nil: - t.Errorf("%s: expected error: %v got nil", tc.name, tc.err) - case tc.err.Error() != actualErr.Error(): - t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr) - } - } -} - -func TestMultiRESTMapperRESTMappings(t *testing.T) { - mapping1, mapping2 := &RESTMapping{}, &RESTMapping{} - tcs := []struct { - name string - - mapper MultiRESTMapper - groupKind schema.GroupKind - versions []string - result []*RESTMapping - err error - }{ - { - name: "empty with no versions", - mapper: MultiRESTMapper{}, - groupKind: schema.GroupKind{Kind: "Foo"}, - result: nil, - err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}}, - }, - { - name: "empty with one version", - mapper: MultiRESTMapper{}, - groupKind: schema.GroupKind{Kind: "Foo"}, - versions: []string{"v1beta"}, - result: nil, - err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1beta"}}, - }, - { - name: "empty with multi(two) vesions", - mapper: MultiRESTMapper{}, - groupKind: schema.GroupKind{Kind: "Foo"}, - versions: []string{"v1beta", "v2"}, - result: nil, - err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1beta", "v2"}}, - }, - { - name: "ignore not found with kind not exist", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "IGNORE_THIS"}}}}, - groupKind: schema.GroupKind{Kind: "Foo"}, - versions: nil, - result: nil, - err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}}, - }, - { - name: "ignore not found with version not exist", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1"}}}}, - groupKind: schema.GroupKind{Kind: "Foo"}, - versions: []string{"v1beta"}, - result: nil, - err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1beta"}}, - }, - { - name: "ignore not found with multi versions not exist", - mapper: MultiRESTMapper{fixedRESTMapper{err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1"}}}}, - groupKind: schema.GroupKind{Kind: "Foo"}, - versions: []string{"v1beta", "v2"}, - result: nil, - err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}, SearchedVersions: []string{"v1beta", "v2"}}, - }, - { - name: "accept first failure", - mapper: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{mappings: []*RESTMapping{mapping1}}}, - groupKind: schema.GroupKind{Kind: "Foo"}, - versions: []string{"v1beta"}, - result: nil, - err: errors.New("fail on this"), - }, - { - name: "return both", - mapper: MultiRESTMapper{fixedRESTMapper{mappings: []*RESTMapping{mapping1}}, fixedRESTMapper{mappings: []*RESTMapping{mapping2}}}, - groupKind: schema.GroupKind{Kind: "Foo"}, - versions: []string{"v1beta"}, - result: []*RESTMapping{mapping1, mapping2}, - }, - } - - for _, tc := range tcs { - actualResult, actualErr := tc.mapper.RESTMappings(tc.groupKind, tc.versions...) - if e, a := tc.result, actualResult; !reflect.DeepEqual(e, a) { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - switch { - case tc.err == nil && actualErr == nil: - case tc.err == nil: - t.Errorf("%s: unexpected error: %v", tc.name, actualErr) - case actualErr == nil: - t.Errorf("%s: expected error: %v got nil", tc.name, tc.err) - case tc.err.Error() != actualErr.Error(): - t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr) - } - } -} - -type fixedRESTMapper struct { - resourcesFor []schema.GroupVersionResource - kindsFor []schema.GroupVersionKind - resourceFor schema.GroupVersionResource - kindFor schema.GroupVersionKind - mappings []*RESTMapping - - err error -} - -func (m fixedRESTMapper) ResourceSingularizer(resource string) (singular string, err error) { - return "", m.err -} - -func (m fixedRESTMapper) ResourcesFor(resource schema.GroupVersionResource) ([]schema.GroupVersionResource, error) { - return m.resourcesFor, m.err -} - -func (m fixedRESTMapper) KindsFor(resource schema.GroupVersionResource) (gvk []schema.GroupVersionKind, err error) { - return m.kindsFor, m.err -} - -func (m fixedRESTMapper) ResourceFor(resource schema.GroupVersionResource) (schema.GroupVersionResource, error) { - return m.resourceFor, m.err -} - -func (m fixedRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) { - return m.kindFor, m.err -} - -func (m fixedRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (mapping *RESTMapping, err error) { - return nil, m.err -} - -func (m fixedRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) (mappings []*RESTMapping, err error) { - return m.mappings, m.err -} - -func (m fixedRESTMapper) ResourceIsValid(resource schema.GroupVersionResource) bool { - return false -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/priority_test.go b/vendor/k8s.io/apimachinery/pkg/api/meta/priority_test.go deleted file mode 100644 index 098d53bd51..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/meta/priority_test.go +++ /dev/null @@ -1,346 +0,0 @@ -/* -Copyright 2016 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 meta - -import ( - "errors" - "reflect" - "strings" - "testing" - - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func TestPriorityRESTMapperResourceForErrorHandling(t *testing.T) { - tcs := []struct { - name string - - delegate RESTMapper - resourcePatterns []schema.GroupVersionResource - result schema.GroupVersionResource - err string - }{ - { - name: "single hit", - delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{{Resource: "single-hit"}}}, - result: schema.GroupVersionResource{Resource: "single-hit"}, - }, - { - name: "ambiguous match", - delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{ - {Group: "one", Version: "a", Resource: "first"}, - {Group: "two", Version: "b", Resource: "second"}, - }}, - err: "matches multiple resources", - }, - { - name: "group selection", - delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{ - {Group: "one", Version: "a", Resource: "first"}, - {Group: "two", Version: "b", Resource: "second"}, - }}, - resourcePatterns: []schema.GroupVersionResource{ - {Group: "one", Version: AnyVersion, Resource: AnyResource}, - }, - result: schema.GroupVersionResource{Group: "one", Version: "a", Resource: "first"}, - }, - { - name: "empty match continues", - delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{ - {Group: "one", Version: "a", Resource: "first"}, - {Group: "two", Version: "b", Resource: "second"}, - }}, - resourcePatterns: []schema.GroupVersionResource{ - {Group: "fail", Version: AnyVersion, Resource: AnyResource}, - {Group: "one", Version: AnyVersion, Resource: AnyResource}, - }, - result: schema.GroupVersionResource{Group: "one", Version: "a", Resource: "first"}, - }, - { - name: "group followed by version selection", - delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{ - {Group: "one", Version: "a", Resource: "first"}, - {Group: "two", Version: "b", Resource: "second"}, - {Group: "one", Version: "c", Resource: "third"}, - }}, - resourcePatterns: []schema.GroupVersionResource{ - {Group: "one", Version: AnyVersion, Resource: AnyResource}, - {Group: AnyGroup, Version: "a", Resource: AnyResource}, - }, - result: schema.GroupVersionResource{Group: "one", Version: "a", Resource: "first"}, - }, - { - name: "resource selection", - delegate: fixedRESTMapper{resourcesFor: []schema.GroupVersionResource{ - {Group: "one", Version: "a", Resource: "first"}, - {Group: "one", Version: "a", Resource: "second"}, - }}, - resourcePatterns: []schema.GroupVersionResource{ - {Group: AnyGroup, Version: AnyVersion, Resource: "second"}, - }, - result: schema.GroupVersionResource{Group: "one", Version: "a", Resource: "second"}, - }, - } - - for _, tc := range tcs { - mapper := PriorityRESTMapper{Delegate: tc.delegate, ResourcePriority: tc.resourcePatterns} - - actualResult, actualErr := mapper.ResourceFor(schema.GroupVersionResource{}) - if e, a := tc.result, actualResult; e != a { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - if len(tc.err) == 0 && actualErr == nil { - continue - } - if len(tc.err) > 0 && actualErr == nil { - t.Errorf("%s: missing expected err: %v", tc.name, tc.err) - continue - } - if !strings.Contains(actualErr.Error(), tc.err) { - t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr) - } - } -} - -func TestPriorityRESTMapperKindForErrorHandling(t *testing.T) { - tcs := []struct { - name string - - delegate RESTMapper - kindPatterns []schema.GroupVersionKind - result schema.GroupVersionKind - err string - }{ - { - name: "single hit", - delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{{Kind: "single-hit"}}}, - result: schema.GroupVersionKind{Kind: "single-hit"}, - }, - { - name: "ambiguous match", - delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{ - {Group: "one", Version: "a", Kind: "first"}, - {Group: "two", Version: "b", Kind: "second"}, - }}, - err: "matches multiple kinds", - }, - { - name: "group selection", - delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{ - {Group: "one", Version: "a", Kind: "first"}, - {Group: "two", Version: "b", Kind: "second"}, - }}, - kindPatterns: []schema.GroupVersionKind{ - {Group: "one", Version: AnyVersion, Kind: AnyKind}, - }, - result: schema.GroupVersionKind{Group: "one", Version: "a", Kind: "first"}, - }, - { - name: "empty match continues", - delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{ - {Group: "one", Version: "a", Kind: "first"}, - {Group: "two", Version: "b", Kind: "second"}, - }}, - kindPatterns: []schema.GroupVersionKind{ - {Group: "fail", Version: AnyVersion, Kind: AnyKind}, - {Group: "one", Version: AnyVersion, Kind: AnyKind}, - }, - result: schema.GroupVersionKind{Group: "one", Version: "a", Kind: "first"}, - }, - { - name: "group followed by version selection", - delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{ - {Group: "one", Version: "a", Kind: "first"}, - {Group: "two", Version: "b", Kind: "second"}, - {Group: "one", Version: "c", Kind: "third"}, - }}, - kindPatterns: []schema.GroupVersionKind{ - {Group: "one", Version: AnyVersion, Kind: AnyKind}, - {Group: AnyGroup, Version: "a", Kind: AnyKind}, - }, - result: schema.GroupVersionKind{Group: "one", Version: "a", Kind: "first"}, - }, - { - name: "kind selection", - delegate: fixedRESTMapper{kindsFor: []schema.GroupVersionKind{ - {Group: "one", Version: "a", Kind: "first"}, - {Group: "one", Version: "a", Kind: "second"}, - }}, - kindPatterns: []schema.GroupVersionKind{ - {Group: AnyGroup, Version: AnyVersion, Kind: "second"}, - }, - result: schema.GroupVersionKind{Group: "one", Version: "a", Kind: "second"}, - }, - } - - for _, tc := range tcs { - mapper := PriorityRESTMapper{Delegate: tc.delegate, KindPriority: tc.kindPatterns} - - actualResult, actualErr := mapper.KindFor(schema.GroupVersionResource{}) - if e, a := tc.result, actualResult; e != a { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - if len(tc.err) == 0 && actualErr == nil { - continue - } - if len(tc.err) > 0 && actualErr == nil { - t.Errorf("%s: missing expected err: %v", tc.name, tc.err) - continue - } - if !strings.Contains(actualErr.Error(), tc.err) { - t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr) - } - } -} - -func TestPriorityRESTMapperRESTMapping(t *testing.T) { - mapping1 := &RESTMapping{ - GroupVersionKind: schema.GroupVersionKind{Kind: "Foo", Version: "v1alpha1"}, - } - mapping2 := &RESTMapping{ - GroupVersionKind: schema.GroupVersionKind{Kind: "Foo", Version: "v1"}, - } - mapping3 := &RESTMapping{ - GroupVersionKind: schema.GroupVersionKind{Group: "other", Kind: "Foo", Version: "v1"}, - } - allMappers := MultiRESTMapper{ - fixedRESTMapper{mappings: []*RESTMapping{mapping1}}, - fixedRESTMapper{mappings: []*RESTMapping{mapping2}}, - fixedRESTMapper{mappings: []*RESTMapping{mapping3}}, - } - tcs := []struct { - name string - - mapper PriorityRESTMapper - input schema.GroupKind - result *RESTMapping - err error - }{ - { - name: "empty", - mapper: PriorityRESTMapper{Delegate: MultiRESTMapper{}}, - input: schema.GroupKind{Kind: "Foo"}, - err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}}, - }, - { - name: "ignore not found", - mapper: PriorityRESTMapper{Delegate: MultiRESTMapper{fixedRESTMapper{err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "IGNORE_THIS"}}}}}, - input: schema.GroupKind{Kind: "Foo"}, - err: &NoKindMatchError{GroupKind: schema.GroupKind{Kind: "Foo"}}, - }, - { - name: "accept first failure", - mapper: PriorityRESTMapper{Delegate: MultiRESTMapper{fixedRESTMapper{err: errors.New("fail on this")}, fixedRESTMapper{mappings: []*RESTMapping{mapping1}}}}, - input: schema.GroupKind{Kind: "Foo"}, - err: errors.New("fail on this"), - }, - { - name: "return error for ambiguous", - mapper: PriorityRESTMapper{ - Delegate: allMappers, - }, - input: schema.GroupKind{Kind: "Foo"}, - err: &AmbiguousKindError{ - PartialKind: schema.GroupVersionKind{Kind: "Foo"}, - MatchingKinds: []schema.GroupVersionKind{ - {Kind: "Foo", Version: "v1alpha1"}, - {Kind: "Foo", Version: "v1"}, - {Group: "other", Kind: "Foo", Version: "v1"}, - }, - }, - }, - { - name: "accept only item", - mapper: PriorityRESTMapper{ - Delegate: fixedRESTMapper{mappings: []*RESTMapping{mapping1}}, - }, - input: schema.GroupKind{Kind: "Foo"}, - result: mapping1, - }, - { - name: "return single priority", - mapper: PriorityRESTMapper{ - Delegate: allMappers, - KindPriority: []schema.GroupVersionKind{{Version: "v1", Kind: AnyKind}, {Version: "v1alpha1", Kind: AnyKind}}, - }, - input: schema.GroupKind{Kind: "Foo"}, - result: mapping2, - }, - { - name: "return out of group match", - mapper: PriorityRESTMapper{ - Delegate: allMappers, - KindPriority: []schema.GroupVersionKind{{Group: AnyGroup, Version: "v1", Kind: AnyKind}, {Group: "other", Version: AnyVersion, Kind: AnyKind}}, - }, - input: schema.GroupKind{Kind: "Foo"}, - result: mapping3, - }, - } - - for _, tc := range tcs { - actualResult, actualErr := tc.mapper.RESTMapping(tc.input) - if e, a := tc.result, actualResult; !reflect.DeepEqual(e, a) { - t.Errorf("%s: expected %v, got %v", tc.name, e, a) - } - switch { - case tc.err == nil && actualErr == nil: - case tc.err == nil: - t.Errorf("%s: unexpected error: %v", tc.name, actualErr) - case actualErr == nil: - t.Errorf("%s: expected error: %v got nil", tc.name, tc.err) - case tc.err.Error() != actualErr.Error(): - t.Errorf("%s: expected %v, got %v", tc.name, tc.err, actualErr) - } - } -} - -func TestPriorityRESTMapperRESTMappingHonorsUserVersion(t *testing.T) { - mappingV2alpha1 := &RESTMapping{ - GroupVersionKind: schema.GroupVersionKind{Group: "Bar", Kind: "Foo", Version: "v2alpha1"}, - } - mappingV1 := &RESTMapping{ - GroupVersionKind: schema.GroupVersionKind{Group: "Bar", Kind: "Foo", Version: "v1"}, - } - - allMappers := MultiRESTMapper{ - fixedRESTMapper{mappings: []*RESTMapping{mappingV2alpha1}}, - fixedRESTMapper{mappings: []*RESTMapping{mappingV1}}, - } - - mapper := PriorityRESTMapper{ - Delegate: allMappers, - KindPriority: []schema.GroupVersionKind{{Group: "Bar", Version: "v2alpha1", Kind: AnyKind}, {Group: "Bar", Version: AnyVersion, Kind: AnyKind}}, - } - - outMapping1, err := mapper.RESTMapping(schema.GroupKind{Group: "Bar", Kind: "Foo"}, "v1") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if outMapping1 != mappingV1 { - t.Errorf("asked for version %v, expected mapping for %v, got mapping for %v", "v1", mappingV1.GroupVersionKind, outMapping1.GroupVersionKind) - } - - outMapping2, err := mapper.RESTMapping(schema.GroupKind{Group: "Bar", Kind: "Foo"}, "v2alpha1") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if outMapping2 != mappingV2alpha1 { - t.Errorf("asked for version %v, expected mapping for %v, got mapping for %v", "v2alpha1", mappingV2alpha1.GroupVersionKind, outMapping2.GroupVersionKind) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/meta/restmapper_test.go b/vendor/k8s.io/apimachinery/pkg/api/meta/restmapper_test.go deleted file mode 100644 index 1b1c70d657..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/meta/restmapper_test.go +++ /dev/null @@ -1,751 +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 meta - -import ( - "errors" - "reflect" - "strings" - "testing" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -type fakeConvertor struct{} - -func (fakeConvertor) Convert(in, out, context interface{}) error { - return nil -} - -func (fakeConvertor) ConvertToVersion(in runtime.Object, _ runtime.GroupVersioner) (runtime.Object, error) { - return in, nil -} - -func (fakeConvertor) ConvertFieldLabel(version, kind, label, value string) (string, string, error) { - return label, value, nil -} - -var validAccessor = resourceAccessor{} -var validConvertor = fakeConvertor{} - -func fakeInterfaces(version schema.GroupVersion) (*VersionInterfaces, error) { - return &VersionInterfaces{ObjectConvertor: validConvertor, MetadataAccessor: validAccessor}, nil -} - -var unmatchedErr = errors.New("no version") - -func unmatchedVersionInterfaces(version schema.GroupVersion) (*VersionInterfaces, error) { - return nil, unmatchedErr -} - -func TestRESTMapperVersionAndKindForResource(t *testing.T) { - testGroup := "test.group" - testVersion := "test" - testGroupVersion := schema.GroupVersion{Group: testGroup, Version: testVersion} - - testCases := []struct { - Resource schema.GroupVersionResource - GroupVersionToRegister schema.GroupVersion - ExpectedGVK schema.GroupVersionKind - Err bool - }{ - {Resource: schema.GroupVersionResource{Resource: "internalobjec"}, Err: true}, - {Resource: schema.GroupVersionResource{Resource: "internalObjec"}, Err: true}, - - {Resource: schema.GroupVersionResource{Resource: "internalobject"}, ExpectedGVK: testGroupVersion.WithKind("InternalObject")}, - {Resource: schema.GroupVersionResource{Resource: "internalobjects"}, ExpectedGVK: testGroupVersion.WithKind("InternalObject")}, - } - for i, testCase := range testCases { - mapper := NewDefaultRESTMapper([]schema.GroupVersion{testGroupVersion}, fakeInterfaces) - if len(testCase.ExpectedGVK.Kind) != 0 { - mapper.Add(testCase.ExpectedGVK, RESTScopeNamespace) - } - actualGVK, err := mapper.KindFor(testCase.Resource) - - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: unexpected error behavior %t: %v", i, testCase.Err, err) - continue - } - if err != nil { - continue - } - - if actualGVK != testCase.ExpectedGVK { - t.Errorf("%d: unexpected version and kind: e=%s a=%s", i, testCase.ExpectedGVK, actualGVK) - } - } -} - -func TestRESTMapperGroupForResource(t *testing.T) { - testCases := []struct { - Resource schema.GroupVersionResource - GroupVersionKind schema.GroupVersionKind - Err bool - }{ - {Resource: schema.GroupVersionResource{Resource: "myObject"}, GroupVersionKind: schema.GroupVersionKind{Group: "testapi", Version: "test", Kind: "MyObject"}}, - {Resource: schema.GroupVersionResource{Resource: "myobject"}, GroupVersionKind: schema.GroupVersionKind{Group: "testapi2", Version: "test", Kind: "MyObject"}}, - {Resource: schema.GroupVersionResource{Resource: "myObje"}, Err: true, GroupVersionKind: schema.GroupVersionKind{Group: "testapi", Version: "test", Kind: "MyObject"}}, - {Resource: schema.GroupVersionResource{Resource: "myobje"}, Err: true, GroupVersionKind: schema.GroupVersionKind{Group: "testapi", Version: "test", Kind: "MyObject"}}, - } - for i, testCase := range testCases { - mapper := NewDefaultRESTMapper([]schema.GroupVersion{testCase.GroupVersionKind.GroupVersion()}, fakeInterfaces) - mapper.Add(testCase.GroupVersionKind, RESTScopeNamespace) - - actualGVK, err := mapper.KindFor(testCase.Resource) - if testCase.Err { - if err == nil { - t.Errorf("%d: expected error", i) - } - } else if err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - } else if actualGVK != testCase.GroupVersionKind { - t.Errorf("%d: expected group %q, got %q", i, testCase.GroupVersionKind, actualGVK) - } - } -} - -func TestRESTMapperKindsFor(t *testing.T) { - testCases := []struct { - Name string - PreferredOrder []schema.GroupVersion - KindsToRegister []schema.GroupVersionKind - PartialResourceToRequest schema.GroupVersionResource - - ExpectedKinds []schema.GroupVersionKind - ExpectedKindErr string - }{ - { - // exact matches are preferred - Name: "groups, with group exact", - PreferredOrder: []schema.GroupVersion{ - {Group: "first-group-1", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group-1", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - PartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kind"}, - - ExpectedKinds: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - }, - - { - // group prefixes work - Name: "groups, with group prefix", - PreferredOrder: []schema.GroupVersion{ - {Group: "second-group", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - }, - PartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kind"}, - - ExpectedKinds: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - }, - - { - // group prefixes can be ambiguous - Name: "groups, with ambiguous group prefix", - PreferredOrder: []schema.GroupVersion{ - {Group: "first-group-1", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group-1", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - PartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kind"}, - - ExpectedKinds: []schema.GroupVersionKind{ - {Group: "first-group-1", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - ExpectedKindErr: " matches multiple kinds ", - }, - - { - Name: "ambiguous groups, with preference order", - PreferredOrder: []schema.GroupVersion{ - {Group: "second-group", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PartialResourceToRequest: schema.GroupVersionResource{Resource: "my-kinds"}, - - ExpectedKinds: []schema.GroupVersionKind{ - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - ExpectedKindErr: " matches multiple kinds ", - }, - - { - Name: "ambiguous groups, with explicit group match", - PreferredOrder: []schema.GroupVersion{ - {Group: "second-group", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kinds"}, - - ExpectedKinds: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - }, - - { - Name: "ambiguous groups, with ambiguous version match", - PreferredOrder: []schema.GroupVersion{ - {Group: "first-group", Version: "first-version"}, - {Group: "second-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PartialResourceToRequest: schema.GroupVersionResource{Version: "first-version", Resource: "my-kinds"}, - - ExpectedKinds: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - }, - ExpectedKindErr: " matches multiple kinds ", - }, - } - for _, testCase := range testCases { - tcName := testCase.Name - mapper := NewDefaultRESTMapper(testCase.PreferredOrder, fakeInterfaces) - for _, kind := range testCase.KindsToRegister { - mapper.Add(kind, RESTScopeNamespace) - } - - actualKinds, err := mapper.KindsFor(testCase.PartialResourceToRequest) - if err != nil { - t.Errorf("%s: unexpected error: %v", tcName, err) - continue - } - if !reflect.DeepEqual(testCase.ExpectedKinds, actualKinds) { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedKinds, actualKinds) - } - - singleKind, err := mapper.KindFor(testCase.PartialResourceToRequest) - if err == nil && len(testCase.ExpectedKindErr) != 0 { - t.Errorf("%s: expected error: %v", tcName, testCase.ExpectedKindErr) - continue - } - if err != nil { - if len(testCase.ExpectedKindErr) == 0 { - t.Errorf("%s: unexpected error: %v", tcName, err) - continue - } else { - if !strings.Contains(err.Error(), testCase.ExpectedKindErr) { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedKindErr, err) - continue - } - } - - } else { - if testCase.ExpectedKinds[0] != singleKind { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedKinds[0], singleKind) - } - - } - } -} - -func TestRESTMapperResourcesFor(t *testing.T) { - testCases := []struct { - Name string - PreferredOrder []schema.GroupVersion - KindsToRegister []schema.GroupVersionKind - PluralPartialResourceToRequest schema.GroupVersionResource - SingularPartialResourceToRequest schema.GroupVersionResource - - ExpectedResources []schema.GroupVersionResource - ExpectedResourceErr string - }{ - { - // exact matches are preferred - Name: "groups, with group exact", - PreferredOrder: []schema.GroupVersion{ - {Group: "first-group-1", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group-1", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - PluralPartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kinds"}, - SingularPartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kind"}, - - ExpectedResources: []schema.GroupVersionResource{ - {Group: "first-group", Version: "first-version", Resource: "my-kinds"}, - }, - }, - - { - // group prefixes work - Name: "groups, with group prefix", - PreferredOrder: []schema.GroupVersion{ - {Group: "second-group", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - }, - PluralPartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kinds"}, - SingularPartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kind"}, - - ExpectedResources: []schema.GroupVersionResource{ - {Group: "first-group", Version: "first-version", Resource: "my-kinds"}, - }, - }, - - { - // group prefixes can be ambiguous - Name: "groups, with ambiguous group prefix", - PreferredOrder: []schema.GroupVersion{ - {Group: "first-group-1", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group-1", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - }, - PluralPartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kinds"}, - SingularPartialResourceToRequest: schema.GroupVersionResource{Group: "first", Resource: "my-kind"}, - - ExpectedResources: []schema.GroupVersionResource{ - {Group: "first-group-1", Version: "first-version", Resource: "my-kinds"}, - {Group: "first-group", Version: "first-version", Resource: "my-kinds"}, - }, - ExpectedResourceErr: " matches multiple resources ", - }, - - { - Name: "ambiguous groups, with preference order", - PreferredOrder: []schema.GroupVersion{ - {Group: "second-group", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PluralPartialResourceToRequest: schema.GroupVersionResource{Resource: "my-kinds"}, - SingularPartialResourceToRequest: schema.GroupVersionResource{Resource: "my-kind"}, - - ExpectedResources: []schema.GroupVersionResource{ - {Group: "second-group", Version: "first-version", Resource: "my-kinds"}, - {Group: "first-group", Version: "first-version", Resource: "my-kinds"}, - }, - ExpectedResourceErr: " matches multiple resources ", - }, - - { - Name: "ambiguous groups, with explicit group match", - PreferredOrder: []schema.GroupVersion{ - {Group: "second-group", Version: "first-version"}, - {Group: "first-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PluralPartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kinds"}, - SingularPartialResourceToRequest: schema.GroupVersionResource{Group: "first-group", Resource: "my-kind"}, - - ExpectedResources: []schema.GroupVersionResource{ - {Group: "first-group", Version: "first-version", Resource: "my-kinds"}, - }, - }, - - { - Name: "ambiguous groups, with ambiguous version match", - PreferredOrder: []schema.GroupVersion{ - {Group: "first-group", Version: "first-version"}, - {Group: "second-group", Version: "first-version"}, - }, - KindsToRegister: []schema.GroupVersionKind{ - {Group: "first-group", Version: "first-version", Kind: "my-kind"}, - {Group: "first-group", Version: "first-version", Kind: "your-kind"}, - {Group: "second-group", Version: "first-version", Kind: "my-kind"}, - {Group: "second-group", Version: "first-version", Kind: "your-kind"}, - }, - PluralPartialResourceToRequest: schema.GroupVersionResource{Version: "first-version", Resource: "my-kinds"}, - SingularPartialResourceToRequest: schema.GroupVersionResource{Version: "first-version", Resource: "my-kind"}, - - ExpectedResources: []schema.GroupVersionResource{ - {Group: "first-group", Version: "first-version", Resource: "my-kinds"}, - {Group: "second-group", Version: "first-version", Resource: "my-kinds"}, - }, - ExpectedResourceErr: " matches multiple resources ", - }, - } - for _, testCase := range testCases { - tcName := testCase.Name - - for _, partialResource := range []schema.GroupVersionResource{testCase.PluralPartialResourceToRequest, testCase.SingularPartialResourceToRequest} { - mapper := NewDefaultRESTMapper(testCase.PreferredOrder, fakeInterfaces) - for _, kind := range testCase.KindsToRegister { - mapper.Add(kind, RESTScopeNamespace) - } - - actualResources, err := mapper.ResourcesFor(partialResource) - if err != nil { - t.Errorf("%s: unexpected error: %v", tcName, err) - continue - } - if !reflect.DeepEqual(testCase.ExpectedResources, actualResources) { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedResources, actualResources) - } - - singleResource, err := mapper.ResourceFor(partialResource) - if err == nil && len(testCase.ExpectedResourceErr) != 0 { - t.Errorf("%s: expected error: %v", tcName, testCase.ExpectedResourceErr) - continue - } - if err != nil { - if len(testCase.ExpectedResourceErr) == 0 { - t.Errorf("%s: unexpected error: %v", tcName, err) - continue - } else { - if !strings.Contains(err.Error(), testCase.ExpectedResourceErr) { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedResourceErr, err) - continue - } - } - - } else { - if testCase.ExpectedResources[0] != singleResource { - t.Errorf("%s: expected %v, got %v", tcName, testCase.ExpectedResources[0], singleResource) - } - - } - } - } -} - -func TestKindToResource(t *testing.T) { - testCases := []struct { - Kind string - Plural, Singular string - }{ - {Kind: "Pod", Plural: "pods", Singular: "pod"}, - - {Kind: "ReplicationController", Plural: "replicationcontrollers", Singular: "replicationcontroller"}, - - // Add "ies" when ending with "y" - {Kind: "ImageRepository", Plural: "imagerepositories", Singular: "imagerepository"}, - // Add "es" when ending with "s" - {Kind: "miss", Plural: "misses", Singular: "miss"}, - // Add "s" otherwise - {Kind: "lowercase", Plural: "lowercases", Singular: "lowercase"}, - } - for i, testCase := range testCases { - version := schema.GroupVersion{} - - plural, singular := UnsafeGuessKindToResource(version.WithKind(testCase.Kind)) - if singular != version.WithResource(testCase.Singular) || plural != version.WithResource(testCase.Plural) { - t.Errorf("%d: unexpected plural and singular: %v %v", i, plural, singular) - } - } -} - -func TestRESTMapperResourceSingularizer(t *testing.T) { - testGroupVersion := schema.GroupVersion{Group: "tgroup", Version: "test"} - - testCases := []struct { - Kind string - Plural string - Singular string - }{ - {Kind: "Pod", Plural: "pods", Singular: "pod"}, - {Kind: "ReplicationController", Plural: "replicationcontrollers", Singular: "replicationcontroller"}, - {Kind: "ImageRepository", Plural: "imagerepositories", Singular: "imagerepository"}, - {Kind: "Status", Plural: "statuses", Singular: "status"}, - - {Kind: "lowercase", Plural: "lowercases", Singular: "lowercase"}, - // TODO this test is broken. This updates to reflect actual behavior. Kinds are expected to be singular - // old (incorrect), comment: Don't add extra s if the original object is already plural - {Kind: "lowercases", Plural: "lowercaseses", Singular: "lowercases"}, - } - for i, testCase := range testCases { - mapper := NewDefaultRESTMapper([]schema.GroupVersion{testGroupVersion}, fakeInterfaces) - // create singular/plural mapping - mapper.Add(testGroupVersion.WithKind(testCase.Kind), RESTScopeNamespace) - - singular, err := mapper.ResourceSingularizer(testCase.Plural) - if err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - } - if singular != testCase.Singular { - t.Errorf("%d: mismatched singular: got %v, expected %v", i, singular, testCase.Singular) - } - } -} - -func TestRESTMapperRESTMapping(t *testing.T) { - testGroup := "tgroup" - testGroupVersion := schema.GroupVersion{Group: testGroup, Version: "test"} - internalGroupVersion := schema.GroupVersion{Group: testGroup, Version: "test"} - - testCases := []struct { - Kind string - APIGroupVersions []schema.GroupVersion - DefaultVersions []schema.GroupVersion - - Resource string - ExpectedGroupVersion *schema.GroupVersion - Err bool - }{ - {Kind: "Unknown", Err: true}, - {Kind: "InternalObject", Err: true}, - - {DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "Unknown", Err: true}, - - {DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: "internalobjects"}, - {DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: "internalobjects"}, - - {DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: "internalobjects"}, - - {DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{}, Resource: "internalobjects", ExpectedGroupVersion: &schema.GroupVersion{Group: testGroup, Version: "test"}}, - - {DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "test"}}, Resource: "internalobjects"}, - - // TODO: add test for a resource that exists in one version but not another - } - for i, testCase := range testCases { - mapper := NewDefaultRESTMapper(testCase.DefaultVersions, fakeInterfaces) - mapper.Add(internalGroupVersion.WithKind("InternalObject"), RESTScopeNamespace) - - preferredVersions := []string{} - for _, gv := range testCase.APIGroupVersions { - preferredVersions = append(preferredVersions, gv.Version) - } - gk := schema.GroupKind{Group: testGroup, Kind: testCase.Kind} - - mapping, err := mapper.RESTMapping(gk, preferredVersions...) - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: unexpected error behavior %t: %v", i, testCase.Err, err) - } - if hasErr { - continue - } - if mapping.Resource != testCase.Resource { - t.Errorf("%d: unexpected resource: %#v", i, mapping) - } - - if mapping.MetadataAccessor == nil || mapping.ObjectConvertor == nil { - t.Errorf("%d: missing codec and accessor: %#v", i, mapping) - } - - groupVersion := testCase.ExpectedGroupVersion - if groupVersion == nil { - groupVersion = &testCase.APIGroupVersions[0] - } - if mapping.GroupVersionKind.GroupVersion() != *groupVersion { - t.Errorf("%d: unexpected version: %#v", i, mapping) - } - - } -} - -func TestRESTMapperRESTMappingSelectsVersion(t *testing.T) { - expectedGroupVersion1 := schema.GroupVersion{Group: "tgroup", Version: "test1"} - expectedGroupVersion2 := schema.GroupVersion{Group: "tgroup", Version: "test2"} - expectedGroupVersion3 := schema.GroupVersion{Group: "tgroup", Version: "test3"} - internalObjectGK := schema.GroupKind{Group: "tgroup", Kind: "InternalObject"} - otherObjectGK := schema.GroupKind{Group: "tgroup", Kind: "OtherObject"} - - mapper := NewDefaultRESTMapper([]schema.GroupVersion{expectedGroupVersion1, expectedGroupVersion2}, fakeInterfaces) - mapper.Add(expectedGroupVersion1.WithKind("InternalObject"), RESTScopeNamespace) - mapper.Add(expectedGroupVersion2.WithKind("OtherObject"), RESTScopeNamespace) - - // pick default matching object kind based on search order - mapping, err := mapper.RESTMapping(otherObjectGK) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if mapping.Resource != "otherobjects" || mapping.GroupVersionKind.GroupVersion() != expectedGroupVersion2 { - t.Errorf("unexpected mapping: %#v", mapping) - } - - mapping, err = mapper.RESTMapping(internalObjectGK) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if mapping.Resource != "internalobjects" || mapping.GroupVersionKind.GroupVersion() != expectedGroupVersion1 { - t.Errorf("unexpected mapping: %#v", mapping) - } - - // mismatch of version - mapping, err = mapper.RESTMapping(internalObjectGK, expectedGroupVersion2.Version) - if err == nil { - t.Errorf("unexpected non-error") - } - mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion1.Version) - if err == nil { - t.Errorf("unexpected non-error") - } - - // not in the search versions - mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion3.Version) - if err == nil { - t.Errorf("unexpected non-error") - } - - // explicit search order - mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion3.Version, expectedGroupVersion1.Version) - if err == nil { - t.Errorf("unexpected non-error") - } - - mapping, err = mapper.RESTMapping(otherObjectGK, expectedGroupVersion3.Version, expectedGroupVersion2.Version) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if mapping.Resource != "otherobjects" || mapping.GroupVersionKind.GroupVersion() != expectedGroupVersion2 { - t.Errorf("unexpected mapping: %#v", mapping) - } -} - -func TestRESTMapperRESTMappings(t *testing.T) { - testGroup := "tgroup" - testGroupVersion := schema.GroupVersion{Group: testGroup, Version: "v1"} - - testCases := []struct { - Kind string - APIGroupVersions []schema.GroupVersion - DefaultVersions []schema.GroupVersion - AddGroupVersionKind []schema.GroupVersionKind - - ExpectedRESTMappings []*RESTMapping - Err bool - }{ - {Kind: "Unknown", Err: true}, - {Kind: "InternalObject", Err: true}, - - {DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "Unknown", Err: true}, - - // ask for specific version - not available - thus error - {DefaultVersions: []schema.GroupVersion{testGroupVersion}, Kind: "InternalObject", APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "v2"}}, Err: true}, - - // ask for specific version - available - check ExpectedRESTMappings - { - DefaultVersions: []schema.GroupVersion{testGroupVersion}, - Kind: "InternalObject", - APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "v2"}}, - AddGroupVersionKind: []schema.GroupVersionKind{schema.GroupVersion{Group: testGroup, Version: "v2"}.WithKind("InternalObject")}, - ExpectedRESTMappings: []*RESTMapping{{Resource: "internalobjects", GroupVersionKind: schema.GroupVersionKind{Group: testGroup, Version: "v2", Kind: "InternalObject"}}}, - }, - - // ask for specific versions - only one available - check ExpectedRESTMappings - { - DefaultVersions: []schema.GroupVersion{testGroupVersion}, - Kind: "InternalObject", - APIGroupVersions: []schema.GroupVersion{{Group: testGroup, Version: "v3"}, {Group: testGroup, Version: "v2"}}, - AddGroupVersionKind: []schema.GroupVersionKind{schema.GroupVersion{Group: testGroup, Version: "v2"}.WithKind("InternalObject")}, - ExpectedRESTMappings: []*RESTMapping{{Resource: "internalobjects", GroupVersionKind: schema.GroupVersionKind{Group: testGroup, Version: "v2", Kind: "InternalObject"}}}, - }, - - // do not ask for specific version - search through default versions - check ExpectedRESTMappings - { - DefaultVersions: []schema.GroupVersion{testGroupVersion, {Group: testGroup, Version: "v2"}}, - Kind: "InternalObject", - AddGroupVersionKind: []schema.GroupVersionKind{schema.GroupVersion{Group: testGroup, Version: "v1"}.WithKind("InternalObject"), schema.GroupVersion{Group: testGroup, Version: "v2"}.WithKind("InternalObject")}, - ExpectedRESTMappings: []*RESTMapping{{Resource: "internalobjects", GroupVersionKind: schema.GroupVersionKind{Group: testGroup, Version: "v1", Kind: "InternalObject"}}, {Resource: "internalobjects", GroupVersionKind: schema.GroupVersionKind{Group: testGroup, Version: "v2", Kind: "InternalObject"}}}, - }, - } - - for i, testCase := range testCases { - mapper := NewDefaultRESTMapper(testCase.DefaultVersions, fakeInterfaces) - for _, gvk := range testCase.AddGroupVersionKind { - mapper.Add(gvk, RESTScopeNamespace) - } - - preferredVersions := []string{} - for _, gv := range testCase.APIGroupVersions { - preferredVersions = append(preferredVersions, gv.Version) - } - gk := schema.GroupKind{Group: testGroup, Kind: testCase.Kind} - - mappings, err := mapper.RESTMappings(gk, preferredVersions...) - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: unexpected error behavior %t: %v", i, testCase.Err, err) - } - if hasErr { - continue - } - if len(mappings) != len(testCase.ExpectedRESTMappings) { - t.Errorf("%d: unexpected number = %d of rest mappings was returned, expected = %d", i, len(mappings), len(testCase.ExpectedRESTMappings)) - } - for j, mapping := range mappings { - exp := testCase.ExpectedRESTMappings[j] - if mapping.Resource != exp.Resource { - t.Errorf("%d - %d: unexpected resource: %#v", i, j, mapping) - } - if mapping.MetadataAccessor == nil || mapping.ObjectConvertor == nil { - t.Errorf("%d - %d: missing codec and accessor: %#v", i, j, mapping) - } - if mapping.GroupVersionKind != exp.GroupVersionKind { - t.Errorf("%d - %d: unexpected GroupVersionKind: %#v", i, j, mapping) - } - } - } -} - -func TestRESTMapperReportsErrorOnBadVersion(t *testing.T) { - expectedGroupVersion1 := schema.GroupVersion{Group: "tgroup", Version: "test1"} - expectedGroupVersion2 := schema.GroupVersion{Group: "tgroup", Version: "test2"} - internalObjectGK := schema.GroupKind{Group: "tgroup", Kind: "InternalObject"} - - mapper := NewDefaultRESTMapper([]schema.GroupVersion{expectedGroupVersion1, expectedGroupVersion2}, unmatchedVersionInterfaces) - mapper.Add(expectedGroupVersion1.WithKind("InternalObject"), RESTScopeNamespace) - _, err := mapper.RESTMapping(internalObjectGK, expectedGroupVersion1.Version) - if err == nil { - t.Errorf("unexpected non-error") - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/resource/BUILD b/vendor/k8s.io/apimachinery/pkg/api/resource/BUILD deleted file mode 100644 index 57f85fb24c..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/resource/BUILD +++ /dev/null @@ -1,69 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "amount_test.go", - "math_test.go", - "quantity_proto_test.go", - "quantity_test.go", - "scale_int_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/github.com/google/gofuzz:go_default_library", - "//vendor/github.com/spf13/pflag:go_default_library", - "//vendor/gopkg.in/inf.v0:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "amount.go", - "generated.pb.go", - "math.go", - "quantity.go", - "quantity_proto.go", - "scale_int.go", - "suffix.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/apimachinery/pkg/api/resource", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/spf13/pflag:go_default_library", - "//vendor/gopkg.in/inf.v0:go_default_library", - ], -) - -go_test( - name = "go_default_xtest", - srcs = ["quantity_example_test.go"], - deps = ["//vendor/k8s.io/apimachinery/pkg/api/resource:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/api/resource/amount_test.go b/vendor/k8s.io/apimachinery/pkg/api/resource/amount_test.go deleted file mode 100644 index dd070bad36..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/resource/amount_test.go +++ /dev/null @@ -1,133 +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 resource - -import ( - "testing" -) - -func TestInt64AmountAsInt64(t *testing.T) { - for _, test := range []struct { - value int64 - scale Scale - result int64 - ok bool - }{ - {100, 0, 100, true}, - {100, 1, 1000, true}, - {100, -5, 0, false}, - {100, 100, 0, false}, - } { - r, ok := int64Amount{value: test.value, scale: test.scale}.AsInt64() - if r != test.result { - t.Errorf("%v: unexpected result: %d", test, r) - } - if ok != test.ok { - t.Errorf("%v: unexpected ok: %t", test, ok) - } - } -} - -func TestInt64AmountAdd(t *testing.T) { - for _, test := range []struct { - a, b, c int64Amount - ok bool - }{ - {int64Amount{value: 100, scale: 1}, int64Amount{value: 10, scale: 2}, int64Amount{value: 200, scale: 1}, true}, - {int64Amount{value: 100, scale: 1}, int64Amount{value: 1, scale: 2}, int64Amount{value: 110, scale: 1}, true}, - {int64Amount{value: 100, scale: 1}, int64Amount{value: 1, scale: 100}, int64Amount{value: 1, scale: 100}, false}, - {int64Amount{value: -5, scale: 2}, int64Amount{value: 50, scale: 1}, int64Amount{value: 0, scale: 1}, true}, - {int64Amount{value: -5, scale: 2}, int64Amount{value: 5, scale: 2}, int64Amount{value: 0, scale: 2}, true}, - - {int64Amount{value: mostPositive, scale: -1}, int64Amount{value: 1, scale: -1}, int64Amount{value: 0, scale: -1}, false}, - {int64Amount{value: mostPositive, scale: -1}, int64Amount{value: 0, scale: -1}, int64Amount{value: mostPositive, scale: -1}, true}, - {int64Amount{value: mostPositive / 10, scale: 1}, int64Amount{value: 10, scale: 0}, int64Amount{value: mostPositive, scale: -1}, false}, - } { - c := test.a - ok := c.Add(test.b) - if ok != test.ok { - t.Errorf("%v: unexpected ok: %t", test, ok) - } - if ok { - if c != test.c { - t.Errorf("%v: unexpected result: %d", test, c) - } - } else { - if c != test.a { - t.Errorf("%v: overflow addition mutated source: %d", test, c) - } - } - - // addition is commutative - c = test.b - if ok := c.Add(test.a); ok != test.ok { - t.Errorf("%v: unexpected ok: %t", test, ok) - } - if ok { - if c != test.c { - t.Errorf("%v: unexpected result: %d", test, c) - } - } else { - if c != test.b { - t.Errorf("%v: overflow addition mutated source: %d", test, c) - } - } - } -} -func TestInt64AsCanonicalString(t *testing.T) { - for _, test := range []struct { - value int64 - scale Scale - result string - exponent int32 - }{ - {100, 0, "100", 0}, - {100, 1, "1", 3}, - {100, -1, "10", 0}, - {10800, -10, "1080", -9}, - } { - r, exp := int64Amount{value: test.value, scale: test.scale}.AsCanonicalBytes(nil) - if string(r) != test.result { - t.Errorf("%v: unexpected result: %s", test, r) - } - if exp != test.exponent { - t.Errorf("%v: unexpected exponent: %d", test, exp) - } - } -} - -func TestAmountSign(t *testing.T) { - table := []struct { - i int64Amount - expect int - }{ - {int64Amount{value: -50, scale: 1}, -1}, - {int64Amount{value: 0, scale: 1}, 0}, - {int64Amount{value: 300, scale: 1}, 1}, - {int64Amount{value: -50, scale: -8}, -1}, - {int64Amount{value: 50, scale: -8}, 1}, - {int64Amount{value: 0, scale: -8}, 0}, - {int64Amount{value: -50, scale: 0}, -1}, - {int64Amount{value: 50, scale: 0}, 1}, - {int64Amount{value: 0, scale: 0}, 0}, - } - for _, testCase := range table { - if result := testCase.i.Sign(); result != testCase.expect { - t.Errorf("i: %v, Expected: %v, Actual: %v", testCase.i, testCase.expect, result) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/resource/math_test.go b/vendor/k8s.io/apimachinery/pkg/api/resource/math_test.go deleted file mode 100644 index 070a0c237e..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/resource/math_test.go +++ /dev/null @@ -1,211 +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 resource - -import ( - "testing" -) - -func TestDetectOverflowAdd(t *testing.T) { - for _, test := range []struct { - a, b int64 - c int64 - ok bool - }{ - {0, 0, 0, true}, - {-1, 1, 0, true}, - {0, 1, 1, true}, - {2, 2, 4, true}, - {2, -2, 0, true}, - {-2, -2, -4, true}, - - {mostNegative, -1, 0, false}, - {mostNegative, 1, mostNegative + 1, true}, - {mostPositive, -1, mostPositive - 1, true}, - {mostPositive, 1, 0, false}, - - {mostNegative, mostPositive, -1, true}, - {mostPositive, mostNegative, -1, true}, - {mostPositive, mostPositive, 0, false}, - {mostNegative, mostNegative, 0, false}, - - {-mostPositive, mostNegative, 0, false}, - {mostNegative, -mostPositive, 0, false}, - {-mostPositive, -mostPositive, 0, false}, - } { - c, ok := int64Add(test.a, test.b) - if c != test.c { - t.Errorf("%v: unexpected result: %d", test, c) - } - if ok != test.ok { - t.Errorf("%v: unexpected overflow: %t", test, ok) - } - // addition is commutative - d, ok2 := int64Add(test.b, test.a) - if c != d || ok != ok2 { - t.Errorf("%v: not commutative: %d %t", test, d, ok2) - } - } -} - -func TestDetectOverflowMultiply(t *testing.T) { - for _, test := range []struct { - a, b int64 - c int64 - ok bool - }{ - {0, 0, 0, true}, - {-1, 1, -1, true}, - {-1, -1, 1, true}, - {1, 1, 1, true}, - {0, 1, 0, true}, - {1, 0, 0, true}, - {2, 2, 4, true}, - {2, -2, -4, true}, - {-2, -2, 4, true}, - - {mostNegative, -1, 0, false}, - {mostNegative, 1, mostNegative, true}, - {mostPositive, -1, -mostPositive, true}, - {mostPositive, 1, mostPositive, true}, - - {mostNegative, mostPositive, 0, false}, - {mostPositive, mostNegative, 0, false}, - {mostPositive, mostPositive, 1, false}, - {mostNegative, mostNegative, 0, false}, - - {-mostPositive, mostNegative, 0, false}, - {mostNegative, -mostPositive, 0, false}, - {-mostPositive, -mostPositive, 1, false}, - } { - c, ok := int64Multiply(test.a, test.b) - if c != test.c { - t.Errorf("%v: unexpected result: %d", test, c) - } - if ok != test.ok { - t.Errorf("%v: unexpected overflow: %t", test, ok) - } - // multiplication is commutative - d, ok2 := int64Multiply(test.b, test.a) - if c != d || ok != ok2 { - t.Errorf("%v: not commutative: %d %t", test, d, ok2) - } - } -} - -func TestDetectOverflowScale(t *testing.T) { - for _, a := range []int64{0, -1, 1, 10, -10, mostPositive, mostNegative, -mostPositive} { - for _, b := range []int64{1, 2, 10, 100, 1000, mostPositive} { - expect, expectOk := int64Multiply(a, b) - - c, ok := int64MultiplyScale(a, b) - if c != expect { - t.Errorf("%d*%d: unexpected result: %d", a, b, c) - } - if ok != expectOk { - t.Errorf("%d*%d: unexpected overflow: %t", a, b, ok) - } - } - for _, test := range []struct { - base int64 - fn func(a int64) (int64, bool) - }{ - {10, int64MultiplyScale10}, - {100, int64MultiplyScale100}, - {1000, int64MultiplyScale1000}, - } { - expect, expectOk := int64Multiply(a, test.base) - c, ok := test.fn(a) - if c != expect { - t.Errorf("%d*%d: unexpected result: %d", a, test.base, c) - } - if ok != expectOk { - t.Errorf("%d*%d: unexpected overflow: %t", a, test.base, ok) - } - } - } -} - -func TestRemoveInt64Factors(t *testing.T) { - for _, test := range []struct { - value int64 - max int64 - result int64 - scale int32 - }{ - {100, 10, 1, 2}, - {100, 10, 1, 2}, - {100, 100, 1, 1}, - {1, 10, 1, 0}, - } { - r, s := removeInt64Factors(test.value, test.max) - if r != test.result { - t.Errorf("%v: unexpected result: %d", test, r) - } - if s != test.scale { - t.Errorf("%v: unexpected scale: %d", test, s) - } - } -} - -func TestNegativeScaleInt64(t *testing.T) { - for _, test := range []struct { - base int64 - scale Scale - result int64 - exact bool - }{ - {1234567, 0, 1234567, true}, - {1234567, 1, 123457, false}, - {1234567, 2, 12346, false}, - {1234567, 3, 1235, false}, - {1234567, 4, 124, false}, - - {-1234567, 0, -1234567, true}, - {-1234567, 1, -123457, false}, - {-1234567, 2, -12346, false}, - {-1234567, 3, -1235, false}, - {-1234567, 4, -124, false}, - - {1000, 0, 1000, true}, - {1000, 1, 100, true}, - {1000, 2, 10, true}, - {1000, 3, 1, true}, - {1000, 4, 1, false}, - - {-1000, 0, -1000, true}, - {-1000, 1, -100, true}, - {-1000, 2, -10, true}, - {-1000, 3, -1, true}, - {-1000, 4, -1, false}, - - {0, 0, 0, true}, - {0, 1, 0, true}, - {0, 2, 0, true}, - - // negative scale is undefined behavior - {1000, -1, 1000, true}, - } { - result, exact := negativeScaleInt64(test.base, test.scale) - if result != test.result { - t.Errorf("%v: unexpected result: %d", test, result) - } - if exact != test.exact { - t.Errorf("%v: unexpected exact: %t", test, exact) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/resource/quantity_example_test.go b/vendor/k8s.io/apimachinery/pkg/api/resource/quantity_example_test.go deleted file mode 100644 index 56a7dbe0e0..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/resource/quantity_example_test.go +++ /dev/null @@ -1,59 +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 resource_test - -import ( - "fmt" - - "k8s.io/apimachinery/pkg/api/resource" -) - -func ExampleFormat() { - memorySize := resource.NewQuantity(5*1024*1024*1024, resource.BinarySI) - fmt.Printf("memorySize = %v\n", memorySize) - - diskSize := resource.NewQuantity(5*1000*1000*1000, resource.DecimalSI) - fmt.Printf("diskSize = %v\n", diskSize) - - cores := resource.NewMilliQuantity(5300, resource.DecimalSI) - fmt.Printf("cores = %v\n", cores) - - // Output: - // memorySize = 5Gi - // diskSize = 5G - // cores = 5300m -} - -func ExampleMustParse() { - memorySize := resource.MustParse("5Gi") - fmt.Printf("memorySize = %v (%v)\n", memorySize.Value(), memorySize.Format) - - diskSize := resource.MustParse("5G") - fmt.Printf("diskSize = %v (%v)\n", diskSize.Value(), diskSize.Format) - - cores := resource.MustParse("5300m") - fmt.Printf("milliCores = %v (%v)\n", cores.MilliValue(), cores.Format) - - cores2 := resource.MustParse("5.4") - fmt.Printf("milliCores = %v (%v)\n", cores2.MilliValue(), cores2.Format) - - // Output: - // memorySize = 5368709120 (BinarySI) - // diskSize = 5000000000 (DecimalSI) - // milliCores = 5300 (DecimalSI) - // milliCores = 5400 (DecimalSI) -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/resource/quantity_proto_test.go b/vendor/k8s.io/apimachinery/pkg/api/resource/quantity_proto_test.go deleted file mode 100644 index 574a3cf5d7..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/resource/quantity_proto_test.go +++ /dev/null @@ -1,103 +0,0 @@ -/* -Copyright 2017 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 resource - -import ( - "testing" - - inf "gopkg.in/inf.v0" -) - -func TestQuantityProtoMarshal(t *testing.T) { - // Test when d is nil - table := []struct { - quantity string - expect Quantity - }{ - {"0", Quantity{i: int64Amount{value: 0, scale: 0}, s: "0", Format: DecimalSI}}, - {"100m", Quantity{i: int64Amount{value: 100, scale: -3}, s: "100m", Format: DecimalSI}}, - {"50m", Quantity{i: int64Amount{value: 50, scale: -3}, s: "50m", Format: DecimalSI}}, - {"10000T", Quantity{i: int64Amount{value: 10000, scale: 12}, s: "10000T", Format: DecimalSI}}, - } - for _, testCase := range table { - q := MustParse(testCase.quantity) - // Won't currently get an error as MarshalTo can't return one - result, _ := q.Marshal() - q.MarshalTo(result) - if q.Cmp(testCase.expect) != 0 { - t.Errorf("Expected: %v, Actual: %v", testCase.expect, q) - } - } - // Test when i is {0,0} - table2 := []struct { - dec *inf.Dec - expect Quantity - }{ - {dec(0, 0).Dec, Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(0, 0).Dec}, s: "0", Format: DecimalSI}}, - {dec(10, 0).Dec, Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(10, 0).Dec}, s: "10", Format: DecimalSI}}, - {dec(-10, 0).Dec, Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(-10, 0).Dec}, s: "-10", Format: DecimalSI}}, - } - for _, testCase := range table2 { - q := Quantity{d: infDecAmount{testCase.dec}, Format: DecimalSI} - // Won't currently get an error as MarshalTo can't return one - result, _ := q.Marshal() - q.Unmarshal(result) - if q.Cmp(testCase.expect) != 0 { - t.Errorf("Expected: %v, Actual: %v", testCase.expect, q) - } - } -} - -func TestQuantityProtoUnmarshal(t *testing.T) { - // Test when d is nil - table := []struct { - input Quantity - expect string - }{ - {Quantity{i: int64Amount{value: 0, scale: 0}, s: "0", Format: DecimalSI}, "0"}, - {Quantity{i: int64Amount{value: 100, scale: -3}, s: "100m", Format: DecimalSI}, "100m"}, - {Quantity{i: int64Amount{value: 50, scale: -3}, s: "50m", Format: DecimalSI}, "50m"}, - {Quantity{i: int64Amount{value: 10000, scale: 12}, s: "10000T", Format: DecimalSI}, "10000T"}, - } - for _, testCase := range table { - var inputQ Quantity - expectQ := MustParse(testCase.expect) - inputByteArray, _ := testCase.input.Marshal() - inputQ.Unmarshal(inputByteArray) - if inputQ.Cmp(expectQ) != 0 { - t.Errorf("Expected: %v, Actual: %v", inputQ, expectQ) - } - } - // Test when i is {0,0} - table2 := []struct { - input Quantity - expect *inf.Dec - }{ - {Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(0, 0).Dec}, s: "0", Format: DecimalSI}, dec(0, 0).Dec}, - {Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(10, 0).Dec}, s: "10", Format: DecimalSI}, dec(10, 0).Dec}, - {Quantity{i: int64Amount{value: 0, scale: 0}, d: infDecAmount{dec(-10, 0).Dec}, s: "-10", Format: DecimalSI}, dec(-10, 0).Dec}, - } - for _, testCase := range table2 { - var inputQ Quantity - expectQ := Quantity{d: infDecAmount{testCase.expect}, Format: DecimalSI} - inputByteArray, _ := testCase.input.Marshal() - inputQ.Unmarshal(inputByteArray) - if inputQ.Cmp(expectQ) != 0 { - t.Errorf("Expected: %v, Actual: %v", inputQ, expectQ) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/resource/quantity_test.go b/vendor/k8s.io/apimachinery/pkg/api/resource/quantity_test.go deleted file mode 100644 index 74f091a380..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/resource/quantity_test.go +++ /dev/null @@ -1,1368 +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 resource - -import ( - "encoding/json" - "math/rand" - "strings" - "testing" - "unicode" - - fuzz "github.com/google/gofuzz" - "github.com/spf13/pflag" - - inf "gopkg.in/inf.v0" -) - -func amount(i int64, exponent int) infDecAmount { - // See the below test-- scale is the negative of an exponent. - return infDecAmount{inf.NewDec(i, inf.Scale(-exponent))} -} - -func dec(i int64, exponent int) infDecAmount { - // See the below test-- scale is the negative of an exponent. - return infDecAmount{inf.NewDec(i, inf.Scale(-exponent))} -} - -func decQuantity(i int64, exponent int, format Format) Quantity { - return Quantity{d: dec(i, exponent), Format: format} -} - -func intQuantity(i int64, exponent Scale, format Format) Quantity { - return Quantity{i: int64Amount{value: i, scale: exponent}, Format: format} -} - -func TestDec(t *testing.T) { - table := []struct { - got infDecAmount - expect string - }{ - {dec(1, 0), "1"}, - {dec(1, 1), "10"}, - {dec(5, 2), "500"}, - {dec(8, 3), "8000"}, - {dec(2, 0), "2"}, - {dec(1, -1), "0.1"}, - {dec(3, -2), "0.03"}, - {dec(4, -3), "0.004"}, - } - - for _, item := range table { - if e, a := item.expect, item.got.Dec.String(); e != a { - t.Errorf("expected %v, got %v", e, a) - } - } -} - -// TestQuantityParseZero ensures that when a 0 quantity is passed, its string value is 0 -func TestQuantityParseZero(t *testing.T) { - zero := MustParse("0") - if expected, actual := "0", zero.String(); expected != actual { - t.Errorf("Expected %v, actual %v", expected, actual) - } -} - -// TestQuantityParseNonNumericPanic ensures that when a non-numeric string is parsed -// it panics -func TestQuantityParseNonNumericPanic(t *testing.T) { - defer func() { - if r := recover(); r == nil { - t.Errorf("MustParse did not panic") - } - }() - _ = MustParse("Non-Numeric") -} - -// TestQuantityAddZeroPreservesSuffix verifies that a suffix is preserved -// independent of the order of operations when adding a zero and non-zero val -func TestQuantityAddZeroPreservesSuffix(t *testing.T) { - testValues := []string{"100m", "1Gi"} - zero := MustParse("0") - for _, testValue := range testValues { - value := MustParse(testValue) - v1 := *value.Copy() - // ensure non-zero + zero = non-zero (suffix preserved) - v1.Add(zero) - // ensure zero + non-zero = non-zero (suffix preserved) - v2 := *zero.Copy() - v2.Add(value) - - if v1.String() != testValue { - t.Errorf("Expected %v, actual %v", testValue, v1.String()) - continue - } - if v2.String() != testValue { - t.Errorf("Expected %v, actual %v", testValue, v2.String()) - } - } -} - -// TestQuantitySubZeroPreservesSuffix verifies that a suffix is preserved -// independent of the order of operations when subtracting a zero and non-zero val -func TestQuantitySubZeroPreservesSuffix(t *testing.T) { - testValues := []string{"100m", "1Gi"} - zero := MustParse("0") - for _, testValue := range testValues { - value := MustParse(testValue) - v1 := *value.Copy() - // ensure non-zero - zero = non-zero (suffix preserved) - v1.Sub(zero) - // ensure we preserved the input value - if v1.String() != testValue { - t.Errorf("Expected %v, actual %v", testValue, v1.String()) - } - - // ensure zero - non-zero = -non-zero (suffix preserved) - v2 := *zero.Copy() - v2.Sub(value) - negVal := *value.Copy() - negVal.Neg() - if v2.String() != negVal.String() { - t.Errorf("Expected %v, actual %v", negVal.String(), v2.String()) - } - } -} - -// TestQuantityCanocicalizeZero verifies that you get 0 as canonical value if internal value is 0, and not 0<suffix> -func TestQuantityCanocicalizeZero(t *testing.T) { - val := MustParse("1000m") - val.i.Sub(int64Amount{value: 1}) - zero := Quantity{i: val.i, Format: DecimalSI} - if expected, actual := "0", zero.String(); expected != actual { - t.Errorf("Expected %v, actual %v", expected, actual) - } -} - -func TestQuantityCmp(t *testing.T) { - // Test when d is nil - table := []struct { - x string - y string - expect int - }{ - {"0", "0", 0}, - {"100m", "50m", 1}, - {"50m", "100m", -1}, - {"10000T", "100Gi", 1}, - } - for _, testCase := range table { - q1 := MustParse(testCase.x) - q2 := MustParse(testCase.y) - if result := q1.Cmp(q2); result != testCase.expect { - t.Errorf("X: %v, Y: %v, Expected: %v, Actual: %v", testCase.x, testCase.y, testCase.expect, result) - } - } - // Test when i is {0,0} - table2 := []struct { - x *inf.Dec - y *inf.Dec - expect int - }{ - {dec(0, 0).Dec, dec(0, 0).Dec, 0}, - {nil, dec(0, 0).Dec, 0}, - {dec(0, 0).Dec, nil, 0}, - {nil, nil, 0}, - {nil, dec(10, 0).Dec, -1}, - {nil, dec(-10, 0).Dec, 1}, - {dec(10, 0).Dec, nil, 1}, - {dec(-10, 0).Dec, nil, -1}, - } - for _, testCase := range table2 { - q1 := Quantity{d: infDecAmount{testCase.x}, Format: DecimalSI} - q2 := Quantity{d: infDecAmount{testCase.y}, Format: DecimalSI} - if result := q1.Cmp(q2); result != testCase.expect { - t.Errorf("X: %v, Y: %v, Expected: %v, Actual: %v", testCase.x, testCase.y, testCase.expect, result) - } - } -} - -func TestParseQuantityString(t *testing.T) { - table := []struct { - input string - positive bool - value string - num, denom, suffix string - }{ - {"0.025Ti", true, "0.025", "0", "025", "Ti"}, - {"1.025Ti", true, "1.025", "1", "025", "Ti"}, - {"-1.025Ti", false, "-1.025", "1", "025", "Ti"}, - {".", true, ".", "0", "", ""}, - {"-.", false, "-.", "0", "", ""}, - {"1E-3", true, "1", "1", "", "E-3"}, - } - for _, test := range table { - positive, value, num, denom, suffix, err := parseQuantityString(test.input) - if err != nil { - t.Errorf("%s: error: %v", test.input, err) - continue - } - if positive != test.positive || value != test.value || num != test.num || denom != test.denom || suffix != test.suffix { - t.Errorf("%s: unmatched: %t %q %q %q %q", test.input, positive, value, num, denom, suffix) - } - } -} - -func TestQuantityParse(t *testing.T) { - if _, err := ParseQuantity(""); err == nil { - t.Errorf("expected empty string to return error") - } - - table := []struct { - input string - expect Quantity - }{ - {"0", decQuantity(0, 0, DecimalSI)}, - {"0n", decQuantity(0, 0, DecimalSI)}, - {"0u", decQuantity(0, 0, DecimalSI)}, - {"0m", decQuantity(0, 0, DecimalSI)}, - {"0Ki", decQuantity(0, 0, BinarySI)}, - {"0k", decQuantity(0, 0, DecimalSI)}, - {"0Mi", decQuantity(0, 0, BinarySI)}, - {"0M", decQuantity(0, 0, DecimalSI)}, - {"0Gi", decQuantity(0, 0, BinarySI)}, - {"0G", decQuantity(0, 0, DecimalSI)}, - {"0Ti", decQuantity(0, 0, BinarySI)}, - {"0T", decQuantity(0, 0, DecimalSI)}, - - // Quantity less numbers are allowed - {"1", decQuantity(1, 0, DecimalSI)}, - - // Binary suffixes - {"1Ki", decQuantity(1024, 0, BinarySI)}, - {"8Ki", decQuantity(8*1024, 0, BinarySI)}, - {"7Mi", decQuantity(7*1024*1024, 0, BinarySI)}, - {"6Gi", decQuantity(6*1024*1024*1024, 0, BinarySI)}, - {"5Ti", decQuantity(5*1024*1024*1024*1024, 0, BinarySI)}, - {"4Pi", decQuantity(4*1024*1024*1024*1024*1024, 0, BinarySI)}, - {"3Ei", decQuantity(3*1024*1024*1024*1024*1024*1024, 0, BinarySI)}, - - {"10Ti", decQuantity(10*1024*1024*1024*1024, 0, BinarySI)}, - {"100Ti", decQuantity(100*1024*1024*1024*1024, 0, BinarySI)}, - - // Decimal suffixes - {"5n", decQuantity(5, -9, DecimalSI)}, - {"4u", decQuantity(4, -6, DecimalSI)}, - {"3m", decQuantity(3, -3, DecimalSI)}, - {"9", decQuantity(9, 0, DecimalSI)}, - {"8k", decQuantity(8, 3, DecimalSI)}, - {"50k", decQuantity(5, 4, DecimalSI)}, - {"7M", decQuantity(7, 6, DecimalSI)}, - {"6G", decQuantity(6, 9, DecimalSI)}, - {"5T", decQuantity(5, 12, DecimalSI)}, - {"40T", decQuantity(4, 13, DecimalSI)}, - {"300T", decQuantity(3, 14, DecimalSI)}, - {"2P", decQuantity(2, 15, DecimalSI)}, - {"1E", decQuantity(1, 18, DecimalSI)}, - - // Decimal exponents - {"1E-3", decQuantity(1, -3, DecimalExponent)}, - {"1e3", decQuantity(1, 3, DecimalExponent)}, - {"1E6", decQuantity(1, 6, DecimalExponent)}, - {"1e9", decQuantity(1, 9, DecimalExponent)}, - {"1E12", decQuantity(1, 12, DecimalExponent)}, - {"1e15", decQuantity(1, 15, DecimalExponent)}, - {"1E18", decQuantity(1, 18, DecimalExponent)}, - - // Nonstandard but still parsable - {"1e14", decQuantity(1, 14, DecimalExponent)}, - {"1e13", decQuantity(1, 13, DecimalExponent)}, - {"1e3", decQuantity(1, 3, DecimalExponent)}, - {"100.035k", decQuantity(100035, 0, DecimalSI)}, - - // Things that look like floating point - {"0.001", decQuantity(1, -3, DecimalSI)}, - {"0.0005k", decQuantity(5, -1, DecimalSI)}, - {"0.005", decQuantity(5, -3, DecimalSI)}, - {"0.05", decQuantity(5, -2, DecimalSI)}, - {"0.5", decQuantity(5, -1, DecimalSI)}, - {"0.00050k", decQuantity(5, -1, DecimalSI)}, - {"0.00500", decQuantity(5, -3, DecimalSI)}, - {"0.05000", decQuantity(5, -2, DecimalSI)}, - {"0.50000", decQuantity(5, -1, DecimalSI)}, - {"0.5e0", decQuantity(5, -1, DecimalExponent)}, - {"0.5e-1", decQuantity(5, -2, DecimalExponent)}, - {"0.5e-2", decQuantity(5, -3, DecimalExponent)}, - {"0.5e0", decQuantity(5, -1, DecimalExponent)}, - {"10.035M", decQuantity(10035, 3, DecimalSI)}, - - {"1.2e3", decQuantity(12, 2, DecimalExponent)}, - {"1.3E+6", decQuantity(13, 5, DecimalExponent)}, - {"1.40e9", decQuantity(14, 8, DecimalExponent)}, - {"1.53E12", decQuantity(153, 10, DecimalExponent)}, - {"1.6e15", decQuantity(16, 14, DecimalExponent)}, - {"1.7E18", decQuantity(17, 17, DecimalExponent)}, - - {"9.01", decQuantity(901, -2, DecimalSI)}, - {"8.1k", decQuantity(81, 2, DecimalSI)}, - {"7.123456M", decQuantity(7123456, 0, DecimalSI)}, - {"6.987654321G", decQuantity(6987654321, 0, DecimalSI)}, - {"5.444T", decQuantity(5444, 9, DecimalSI)}, - {"40.1T", decQuantity(401, 11, DecimalSI)}, - {"300.2T", decQuantity(3002, 11, DecimalSI)}, - {"2.5P", decQuantity(25, 14, DecimalSI)}, - {"1.01E", decQuantity(101, 16, DecimalSI)}, - - // Things that saturate/round - {"3.001n", decQuantity(4, -9, DecimalSI)}, - {"1.1E-9", decQuantity(2, -9, DecimalExponent)}, - {"0.0000000001", decQuantity(1, -9, DecimalSI)}, - {"0.0000000005", decQuantity(1, -9, DecimalSI)}, - {"0.00000000050", decQuantity(1, -9, DecimalSI)}, - {"0.5e-9", decQuantity(1, -9, DecimalExponent)}, - {"0.9n", decQuantity(1, -9, DecimalSI)}, - {"0.00000012345", decQuantity(124, -9, DecimalSI)}, - {"0.00000012354", decQuantity(124, -9, DecimalSI)}, - {"9Ei", Quantity{d: maxAllowed, Format: BinarySI}}, - {"9223372036854775807Ki", Quantity{d: maxAllowed, Format: BinarySI}}, - {"12E", decQuantity(12, 18, DecimalSI)}, - - // We'll accept fractional binary stuff, too. - {"100.035Ki", decQuantity(10243584, -2, BinarySI)}, - {"0.5Mi", decQuantity(.5*1024*1024, 0, BinarySI)}, - {"0.05Gi", decQuantity(536870912, -1, BinarySI)}, - {"0.025Ti", decQuantity(274877906944, -1, BinarySI)}, - - // Things written by trolls - {"0.000000000001Ki", decQuantity(2, -9, DecimalSI)}, // rounds up, changes format - {".001", decQuantity(1, -3, DecimalSI)}, - {".0001k", decQuantity(100, -3, DecimalSI)}, - {"1.", decQuantity(1, 0, DecimalSI)}, - {"1.G", decQuantity(1, 9, DecimalSI)}, - } - - for _, asDec := range []bool{false, true} { - for _, item := range table { - got, err := ParseQuantity(item.input) - if err != nil { - t.Errorf("%v: unexpected error: %v", item.input, err) - continue - } - if asDec { - got.AsDec() - } - - if e, a := item.expect, got; e.Cmp(a) != 0 { - t.Errorf("%v: expected %v, got %v", item.input, e.String(), a.String()) - } - if e, a := item.expect.Format, got.Format; e != a { - t.Errorf("%v: expected %#v, got %#v", item.input, e, a) - } - - if asDec { - if i, ok := got.AsInt64(); i != 0 || ok { - t.Errorf("%v: expected inf.Dec to return false for AsInt64: %d", item.input, i) - } - continue - } - i, ok := item.expect.AsInt64() - if !ok { - continue - } - j, ok := got.AsInt64() - if !ok { - if got.d.Dec == nil && got.i.scale >= 0 { - t.Errorf("%v: is an int64Amount, but can't return AsInt64: %v", item.input, got) - } - continue - } - if i != j { - t.Errorf("%v: expected equivalent representation as int64: %d %d", item.input, i, j) - } - } - - for _, item := range table { - got, err := ParseQuantity(item.input) - if err != nil { - t.Errorf("%v: unexpected error: %v", item.input, err) - continue - } - - if asDec { - got.AsDec() - } - - // verify that we can decompose the input and get the same result by building up from the base. - positive, _, num, denom, suffix, err := parseQuantityString(item.input) - if err != nil { - t.Errorf("%v: unexpected error: %v", item.input, err) - continue - } - if got.Sign() >= 0 && !positive || got.Sign() < 0 && positive { - t.Errorf("%v: positive was incorrect: %t", item.input, positive) - continue - } - var value string - if !positive { - value = "-" - } - value += num - if len(denom) > 0 { - value += "." + denom - } - value += suffix - if len(value) == 0 { - t.Errorf("%v: did not parse correctly, %q %q %q", item.input, num, denom, suffix) - } - expected, err := ParseQuantity(value) - if err != nil { - t.Errorf("%v: unexpected error for %s: %v", item.input, value, err) - continue - } - if expected.Cmp(got) != 0 { - t.Errorf("%v: not the same as %s", item.input, value) - continue - } - } - - // Try the negative version of everything - desired := &inf.Dec{} - expect := Quantity{d: infDecAmount{Dec: desired}} - for _, item := range table { - got, err := ParseQuantity("-" + strings.TrimLeftFunc(item.input, unicode.IsSpace)) - if err != nil { - t.Errorf("-%v: unexpected error: %v", item.input, err) - continue - } - if asDec { - got.AsDec() - } - - expected := item.expect - desired.Neg(expected.AsDec()) - - if e, a := expect, got; e.Cmp(a) != 0 { - t.Errorf("%v: expected %s, got %s", item.input, e.String(), a.String()) - } - if e, a := expected.Format, got.Format; e != a { - t.Errorf("%v: expected %#v, got %#v", item.input, e, a) - } - } - - // Try everything with an explicit + - for _, item := range table { - got, err := ParseQuantity("+" + strings.TrimLeftFunc(item.input, unicode.IsSpace)) - if err != nil { - t.Errorf("-%v: unexpected error: %v", item.input, err) - continue - } - if asDec { - got.AsDec() - } - - if e, a := item.expect, got; e.Cmp(a) != 0 { - t.Errorf("%v(%t): expected %s, got %s", item.input, asDec, e.String(), a.String()) - } - if e, a := item.expect.Format, got.Format; e != a { - t.Errorf("%v: expected %#v, got %#v", item.input, e, a) - } - } - } - - invalid := []string{ - "1.1.M", - "1+1.0M", - "0.1mi", - "0.1am", - "aoeu", - ".5i", - "1i", - "-3.01i", - "-3.01e-", - - // trailing whitespace is forbidden - " 1", - "1 ", - } - for _, item := range invalid { - _, err := ParseQuantity(item) - if err == nil { - t.Errorf("%v parsed unexpectedly", item) - } - } -} - -func TestQuantityRoundUp(t *testing.T) { - table := []struct { - in string - scale Scale - expect Quantity - ok bool - }{ - {"9.01", -3, decQuantity(901, -2, DecimalSI), true}, - {"9.01", -2, decQuantity(901, -2, DecimalSI), true}, - {"9.01", -1, decQuantity(91, -1, DecimalSI), false}, - {"9.01", 0, decQuantity(10, 0, DecimalSI), false}, - {"9.01", 1, decQuantity(10, 0, DecimalSI), false}, - {"9.01", 2, decQuantity(100, 0, DecimalSI), false}, - - {"-9.01", -3, decQuantity(-901, -2, DecimalSI), true}, - {"-9.01", -2, decQuantity(-901, -2, DecimalSI), true}, - {"-9.01", -1, decQuantity(-91, -1, DecimalSI), false}, - {"-9.01", 0, decQuantity(-10, 0, DecimalSI), false}, - {"-9.01", 1, decQuantity(-10, 0, DecimalSI), false}, - {"-9.01", 2, decQuantity(-100, 0, DecimalSI), false}, - } - - for _, asDec := range []bool{false, true} { - for _, item := range table { - got, err := ParseQuantity(item.in) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - expect := *item.expect.Copy() - if asDec { - got.AsDec() - } - if ok := got.RoundUp(item.scale); ok != item.ok { - t.Errorf("%s(%d,%t): unexpected ok: %t", item.in, item.scale, asDec, ok) - } - if got.Cmp(expect) != 0 { - t.Errorf("%s(%d,%t): unexpected round: %s vs %s", item.in, item.scale, asDec, got.String(), expect.String()) - } - } - } -} - -func TestQuantityCmpInt64AndDec(t *testing.T) { - table := []struct { - a, b Quantity - cmp int - }{ - {intQuantity(901, -2, DecimalSI), intQuantity(901, -2, DecimalSI), 0}, - {intQuantity(90, -1, DecimalSI), intQuantity(901, -2, DecimalSI), -1}, - {intQuantity(901, -2, DecimalSI), intQuantity(900, -2, DecimalSI), 1}, - {intQuantity(0, 0, DecimalSI), intQuantity(0, 0, DecimalSI), 0}, - {intQuantity(0, 1, DecimalSI), intQuantity(0, -1, DecimalSI), 0}, - {intQuantity(0, -1, DecimalSI), intQuantity(0, 1, DecimalSI), 0}, - {intQuantity(800, -3, DecimalSI), intQuantity(1, 0, DecimalSI), -1}, - {intQuantity(800, -3, DecimalSI), intQuantity(79, -2, DecimalSI), 1}, - - {intQuantity(mostPositive, 0, DecimalSI), intQuantity(1, -1, DecimalSI), 1}, - {intQuantity(mostPositive, 1, DecimalSI), intQuantity(1, 0, DecimalSI), 1}, - {intQuantity(mostPositive, 1, DecimalSI), intQuantity(1, 1, DecimalSI), 1}, - {intQuantity(mostPositive, 1, DecimalSI), intQuantity(0, 1, DecimalSI), 1}, - {intQuantity(mostPositive, -16, DecimalSI), intQuantity(1, 3, DecimalSI), -1}, - - {intQuantity(mostNegative, 0, DecimalSI), intQuantity(0, 0, DecimalSI), -1}, - {intQuantity(mostNegative, -18, DecimalSI), intQuantity(-1, 0, DecimalSI), -1}, - {intQuantity(mostNegative, -19, DecimalSI), intQuantity(-1, 0, DecimalSI), 1}, - - {intQuantity(1*1000000*1000000*1000000, -17, DecimalSI), intQuantity(1, 1, DecimalSI), 0}, - {intQuantity(1*1000000*1000000*1000000, -17, DecimalSI), intQuantity(-10, 0, DecimalSI), 1}, - {intQuantity(-1*1000000*1000000*1000000, -17, DecimalSI), intQuantity(-10, 0, DecimalSI), 0}, - {intQuantity(1*1000000*1000000*1000000, -17, DecimalSI), intQuantity(1, 0, DecimalSI), 1}, - - {intQuantity(1*1000000*1000000*1000000+1, -17, DecimalSI), intQuantity(1, 1, DecimalSI), 1}, - {intQuantity(1*1000000*1000000*1000000-1, -17, DecimalSI), intQuantity(1, 1, DecimalSI), -1}, - } - - for _, item := range table { - if cmp := item.a.Cmp(item.b); cmp != item.cmp { - t.Errorf("%#v: unexpected Cmp: %d", item, cmp) - } - if cmp := item.b.Cmp(item.a); cmp != -item.cmp { - t.Errorf("%#v: unexpected inverted Cmp: %d", item, cmp) - } - } - - for _, item := range table { - a, b := *item.a.Copy(), *item.b.Copy() - a.AsDec() - if cmp := a.Cmp(b); cmp != item.cmp { - t.Errorf("%#v: unexpected Cmp: %d", item, cmp) - } - if cmp := b.Cmp(a); cmp != -item.cmp { - t.Errorf("%#v: unexpected inverted Cmp: %d", item, cmp) - } - } - - for _, item := range table { - a, b := *item.a.Copy(), *item.b.Copy() - b.AsDec() - if cmp := a.Cmp(b); cmp != item.cmp { - t.Errorf("%#v: unexpected Cmp: %d", item, cmp) - } - if cmp := b.Cmp(a); cmp != -item.cmp { - t.Errorf("%#v: unexpected inverted Cmp: %d", item, cmp) - } - } - - for _, item := range table { - a, b := *item.a.Copy(), *item.b.Copy() - a.AsDec() - b.AsDec() - if cmp := a.Cmp(b); cmp != item.cmp { - t.Errorf("%#v: unexpected Cmp: %d", item, cmp) - } - if cmp := b.Cmp(a); cmp != -item.cmp { - t.Errorf("%#v: unexpected inverted Cmp: %d", item, cmp) - } - } -} - -func TestQuantityNeg(t *testing.T) { - table := []struct { - a Quantity - out string - }{ - {intQuantity(901, -2, DecimalSI), "-9010m"}, - {decQuantity(901, -2, DecimalSI), "-9010m"}, - } - - for i, item := range table { - out := *item.a.Copy() - out.Neg() - if out.Cmp(item.a) == 0 { - t.Errorf("%d: negating an item should not mutate the source: %s", i, out.String()) - } - if out.String() != item.out { - t.Errorf("%d: negating did not equal exact value: %s", i, out.String()) - } - } -} - -func TestQuantityString(t *testing.T) { - table := []struct { - in Quantity - expect string - alternate string - }{ - {decQuantity(1024*1024*1024, 0, BinarySI), "1Gi", "1024Mi"}, - {decQuantity(300*1024*1024, 0, BinarySI), "300Mi", "307200Ki"}, - {decQuantity(6*1024, 0, BinarySI), "6Ki", ""}, - {decQuantity(1001*1024*1024*1024, 0, BinarySI), "1001Gi", "1025024Mi"}, - {decQuantity(1024*1024*1024*1024, 0, BinarySI), "1Ti", "1024Gi"}, - {decQuantity(5, 0, BinarySI), "5", "5000m"}, - {decQuantity(500, -3, BinarySI), "500m", "0.5"}, - {decQuantity(1, 9, DecimalSI), "1G", "1000M"}, - {decQuantity(1000, 6, DecimalSI), "1G", "0.001T"}, - {decQuantity(1000000, 3, DecimalSI), "1G", ""}, - {decQuantity(1000000000, 0, DecimalSI), "1G", ""}, - {decQuantity(1, -3, DecimalSI), "1m", "1000u"}, - {decQuantity(80, -3, DecimalSI), "80m", ""}, - {decQuantity(1080, -3, DecimalSI), "1080m", "1.08"}, - {decQuantity(108, -2, DecimalSI), "1080m", "1080000000n"}, - {decQuantity(10800, -4, DecimalSI), "1080m", ""}, - {decQuantity(300, 6, DecimalSI), "300M", ""}, - {decQuantity(1, 12, DecimalSI), "1T", ""}, - {decQuantity(1234567, 6, DecimalSI), "1234567M", ""}, - {decQuantity(1234567, -3, BinarySI), "1234567m", ""}, - {decQuantity(3, 3, DecimalSI), "3k", ""}, - {decQuantity(1025, 0, BinarySI), "1025", ""}, - {decQuantity(0, 0, DecimalSI), "0", ""}, - {decQuantity(0, 0, BinarySI), "0", ""}, - {decQuantity(1, 9, DecimalExponent), "1e9", ".001e12"}, - {decQuantity(1, -3, DecimalExponent), "1e-3", "0.001e0"}, - {decQuantity(1, -9, DecimalExponent), "1e-9", "1000e-12"}, - {decQuantity(80, -3, DecimalExponent), "80e-3", ""}, - {decQuantity(300, 6, DecimalExponent), "300e6", ""}, - {decQuantity(1, 12, DecimalExponent), "1e12", ""}, - {decQuantity(1, 3, DecimalExponent), "1e3", ""}, - {decQuantity(3, 3, DecimalExponent), "3e3", ""}, - {decQuantity(3, 3, DecimalSI), "3k", ""}, - {decQuantity(0, 0, DecimalExponent), "0", "00"}, - {decQuantity(1, -9, DecimalSI), "1n", ""}, - {decQuantity(80, -9, DecimalSI), "80n", ""}, - {decQuantity(1080, -9, DecimalSI), "1080n", ""}, - {decQuantity(108, -8, DecimalSI), "1080n", ""}, - {decQuantity(10800, -10, DecimalSI), "1080n", ""}, - {decQuantity(1, -6, DecimalSI), "1u", ""}, - {decQuantity(80, -6, DecimalSI), "80u", ""}, - {decQuantity(1080, -6, DecimalSI), "1080u", ""}, - } - for _, item := range table { - got := item.in.String() - if e, a := item.expect, got; e != a { - t.Errorf("%#v: expected %v, got %v", item.in, e, a) - } - q, err := ParseQuantity(item.expect) - if err != nil { - t.Errorf("%#v: unexpected error: %v", item.expect, err) - } - if len(q.s) == 0 || q.s != item.expect { - t.Errorf("%#v: did not copy canonical string on parse: %s", item.expect, q.s) - } - if len(item.alternate) == 0 { - continue - } - q, err = ParseQuantity(item.alternate) - if err != nil { - t.Errorf("%#v: unexpected error: %v", item.expect, err) - continue - } - if len(q.s) != 0 { - t.Errorf("%#v: unexpected nested string: %v", item.expect, q.s) - } - if q.String() != item.expect { - t.Errorf("%#v: unexpected alternate canonical: %v", item.expect, q.String()) - } - if len(q.s) == 0 || q.s != item.expect { - t.Errorf("%#v: did not set canonical string on ToString: %s", item.expect, q.s) - } - } - desired := &inf.Dec{} // Avoid modifying the values in the table. - for _, item := range table { - if item.in.Cmp(Quantity{}) == 0 { - // Don't expect it to print "-0" ever - continue - } - q := item.in - q.d = infDecAmount{desired.Neg(q.AsDec())} - if e, a := "-"+item.expect, q.String(); e != a { - t.Errorf("%#v: expected %v, got %v", item.in, e, a) - } - } -} - -func TestQuantityParseEmit(t *testing.T) { - table := []struct { - in string - expect string - }{ - {"1Ki", "1Ki"}, - {"1Mi", "1Mi"}, - {"1Gi", "1Gi"}, - {"1024Mi", "1Gi"}, - {"1000M", "1G"}, - {".001Ki", "1024m"}, - {".000001Ki", "1024u"}, - {".000000001Ki", "1024n"}, - {".000000000001Ki", "2n"}, - } - - for _, item := range table { - q, err := ParseQuantity(item.in) - if err != nil { - t.Errorf("Couldn't parse %v", item.in) - continue - } - if e, a := item.expect, q.String(); e != a { - t.Errorf("%#v: expected %v, got %v", item.in, e, a) - } - } - for _, item := range table { - q, err := ParseQuantity("-" + item.in) - if err != nil { - t.Errorf("Couldn't parse %v", item.in) - continue - } - if q.Cmp(Quantity{}) == 0 { - continue - } - if e, a := "-"+item.expect, q.String(); e != a { - t.Errorf("%#v: expected %v, got %v (%#v)", item.in, e, a, q.i) - } - } -} - -var fuzzer = fuzz.New().Funcs( - func(q *Quantity, c fuzz.Continue) { - q.i = Zero - if c.RandBool() { - q.Format = BinarySI - if c.RandBool() { - dec := &inf.Dec{} - q.d = infDecAmount{Dec: dec} - dec.SetScale(0) - dec.SetUnscaled(c.Int63()) - return - } - // Be sure to test cases like 1Mi - dec := &inf.Dec{} - q.d = infDecAmount{Dec: dec} - dec.SetScale(0) - dec.SetUnscaled(c.Int63n(1024) << uint(10*c.Intn(5))) - return - } - if c.RandBool() { - q.Format = DecimalSI - } else { - q.Format = DecimalExponent - } - if c.RandBool() { - dec := &inf.Dec{} - q.d = infDecAmount{Dec: dec} - dec.SetScale(inf.Scale(c.Intn(4))) - dec.SetUnscaled(c.Int63()) - return - } - // Be sure to test cases like 1M - dec := &inf.Dec{} - q.d = infDecAmount{Dec: dec} - dec.SetScale(inf.Scale(3 - c.Intn(15))) - dec.SetUnscaled(c.Int63n(1000)) - }, -) - -func TestQuantityDeepCopy(t *testing.T) { - // Test when d is nil - slice := []string{"0", "100m", "50m", "10000T"} - for _, testCase := range slice { - q := MustParse(testCase) - if result := q.DeepCopy(); result != q { - t.Errorf("Expected: %v, Actual: %v", q, result) - } - } - table := []*inf.Dec{ - dec(0, 0).Dec, - dec(10, 0).Dec, - dec(-10, 0).Dec, - } - // Test when i is {0,0} - for _, testCase := range table { - q := Quantity{d: infDecAmount{testCase}, Format: DecimalSI} - result := q.DeepCopy() - if q.d.Cmp(result.AsDec()) != 0 { - t.Errorf("Expected: %v, Actual: %v", q.String(), result.String()) - } - result = Quantity{d: infDecAmount{dec(2, 0).Dec}, Format: DecimalSI} - if q.d.Cmp(result.AsDec()) == 0 { - t.Errorf("Modifying result has affected q") - } - } -} - -func TestJSON(t *testing.T) { - for i := 0; i < 500; i++ { - q := &Quantity{} - fuzzer.Fuzz(q) - b, err := json.Marshal(q) - if err != nil { - t.Errorf("error encoding %v: %v", q, err) - continue - } - q2 := &Quantity{} - err = json.Unmarshal(b, q2) - if err != nil { - t.Logf("%d: %s", i, string(b)) - t.Errorf("%v: error decoding %v: %v", q, string(b), err) - } - if q2.Cmp(*q) != 0 { - t.Errorf("Expected equal: %v, %v (json was '%v')", q, q2, string(b)) - } - } -} - -func TestJSONWhitespace(t *testing.T) { - q := Quantity{} - testCases := []struct { - in string - expect string - }{ - {`" 1"`, "1"}, - {`"1 "`, "1"}, - {`1`, "1"}, - {` 1`, "1"}, - {`1 `, "1"}, - {`10`, "10"}, - {`-1`, "-1"}, - {` -1`, "-1"}, - } - for _, test := range testCases { - if err := json.Unmarshal([]byte(test.in), &q); err != nil { - t.Errorf("%q: %v", test.in, err) - } - if q.String() != test.expect { - t.Errorf("unexpected string: %q", q.String()) - } - } -} - -func TestMilliNewSet(t *testing.T) { - table := []struct { - value int64 - format Format - expect string - exact bool - }{ - {1, DecimalSI, "1m", true}, - {1000, DecimalSI, "1", true}, - {1234000, DecimalSI, "1234", true}, - {1024, BinarySI, "1024m", false}, // Format changes - {1000000, "invalidFormatDefaultsToExponent", "1e3", true}, - {1024 * 1024, BinarySI, "1048576m", false}, // Format changes - } - - for _, item := range table { - q := NewMilliQuantity(item.value, item.format) - if e, a := item.expect, q.String(); e != a { - t.Errorf("Expected %v, got %v; %#v", e, a, q) - } - if !item.exact { - continue - } - q2, err := ParseQuantity(q.String()) - if err != nil { - t.Errorf("Round trip failed on %v", q) - } - if e, a := item.value, q2.MilliValue(); e != a { - t.Errorf("Expected %v, got %v", e, a) - } - } - - for _, item := range table { - q := NewQuantity(0, item.format) - q.SetMilli(item.value) - if e, a := item.expect, q.String(); e != a { - t.Errorf("Set: Expected %v, got %v; %#v", e, a, q) - } - } -} - -func TestNewSet(t *testing.T) { - table := []struct { - value int64 - format Format - expect string - }{ - {1, DecimalSI, "1"}, - {1000, DecimalSI, "1k"}, - {1234000, DecimalSI, "1234k"}, - {1024, BinarySI, "1Ki"}, - {1000000, "invalidFormatDefaultsToExponent", "1e6"}, - {1024 * 1024, BinarySI, "1Mi"}, - } - - for _, asDec := range []bool{false, true} { - for _, item := range table { - q := NewQuantity(item.value, item.format) - if asDec { - q.ToDec() - } - if e, a := item.expect, q.String(); e != a { - t.Errorf("Expected %v, got %v; %#v", e, a, q) - } - q2, err := ParseQuantity(q.String()) - if err != nil { - t.Errorf("Round trip failed on %v", q) - } - if e, a := item.value, q2.Value(); e != a { - t.Errorf("Expected %v, got %v", e, a) - } - } - - for _, item := range table { - q := NewQuantity(0, item.format) - q.Set(item.value) - if asDec { - q.ToDec() - } - if e, a := item.expect, q.String(); e != a { - t.Errorf("Set: Expected %v, got %v; %#v", e, a, q) - } - } - } -} - -func TestNewScaledSet(t *testing.T) { - table := []struct { - value int64 - scale Scale - expect string - }{ - {1, Nano, "1n"}, - {1000, Nano, "1u"}, - {1, Micro, "1u"}, - {1000, Micro, "1m"}, - {1, Milli, "1m"}, - {1000, Milli, "1"}, - {1, 0, "1"}, - {0, Nano, "0"}, - {0, Micro, "0"}, - {0, Milli, "0"}, - {0, 0, "0"}, - } - - for _, item := range table { - q := NewScaledQuantity(item.value, item.scale) - if e, a := item.expect, q.String(); e != a { - t.Errorf("Expected %v, got %v; %#v", e, a, q) - } - q2, err := ParseQuantity(q.String()) - if err != nil { - t.Errorf("Round trip failed on %v", q) - } - if e, a := item.value, q2.ScaledValue(item.scale); e != a { - t.Errorf("Expected %v, got %v", e, a) - } - q3 := NewQuantity(0, DecimalSI) - q3.SetScaled(item.value, item.scale) - if q.Cmp(*q3) != 0 { - t.Errorf("Expected %v and %v to be equal", q, q3) - } - } -} - -func TestScaledValue(t *testing.T) { - table := []struct { - fromScale Scale - toScale Scale - expected int64 - }{ - {Nano, Nano, 1}, - {Nano, Micro, 1}, - {Nano, Milli, 1}, - {Nano, 0, 1}, - {Micro, Nano, 1000}, - {Micro, Micro, 1}, - {Micro, Milli, 1}, - {Micro, 0, 1}, - {Milli, Nano, 1000 * 1000}, - {Milli, Micro, 1000}, - {Milli, Milli, 1}, - {Milli, 0, 1}, - {0, Nano, 1000 * 1000 * 1000}, - {0, Micro, 1000 * 1000}, - {0, Milli, 1000}, - {0, 0, 1}, - } - - for _, item := range table { - q := NewScaledQuantity(1, item.fromScale) - if e, a := item.expected, q.ScaledValue(item.toScale); e != a { - t.Errorf("%v to %v: Expected %v, got %v", item.fromScale, item.toScale, e, a) - } - } -} - -func TestUninitializedNoCrash(t *testing.T) { - var q Quantity - - q.Value() - q.MilliValue() - q.Copy() - _ = q.String() - q.MarshalJSON() -} - -func TestCopy(t *testing.T) { - q := NewQuantity(5, DecimalSI) - c := q.Copy() - c.Set(6) - if q.Value() == 6 { - t.Errorf("Copy didn't") - } -} - -func TestQFlagSet(t *testing.T) { - qf := qFlag{&Quantity{}} - qf.Set("1Ki") - if e, a := "1Ki", qf.String(); e != a { - t.Errorf("Unexpected result %v != %v", e, a) - } -} - -func TestQFlagIsPFlag(t *testing.T) { - var pfv pflag.Value = qFlag{} - if e, a := "quantity", pfv.Type(); e != a { - t.Errorf("Unexpected result %v != %v", e, a) - } -} - -func TestSub(t *testing.T) { - tests := []struct { - a Quantity - b Quantity - expected Quantity - }{ - {decQuantity(10, 0, DecimalSI), decQuantity(1, 1, DecimalSI), decQuantity(0, 0, DecimalSI)}, - {decQuantity(10, 0, DecimalSI), decQuantity(1, 0, BinarySI), decQuantity(9, 0, DecimalSI)}, - {decQuantity(10, 0, BinarySI), decQuantity(1, 0, DecimalSI), decQuantity(9, 0, BinarySI)}, - {Quantity{Format: DecimalSI}, decQuantity(50, 0, DecimalSI), decQuantity(-50, 0, DecimalSI)}, - {decQuantity(50, 0, DecimalSI), Quantity{Format: DecimalSI}, decQuantity(50, 0, DecimalSI)}, - {Quantity{Format: DecimalSI}, Quantity{Format: DecimalSI}, decQuantity(0, 0, DecimalSI)}, - } - - for i, test := range tests { - test.a.Sub(test.b) - if test.a.Cmp(test.expected) != 0 { - t.Errorf("[%d] Expected %q, got %q", i, test.expected.String(), test.a.String()) - } - } -} - -func TestNeg(t *testing.T) { - tests := []struct { - a Quantity - b Quantity - expected Quantity - }{ - {a: intQuantity(0, 0, DecimalSI), expected: intQuantity(0, 0, DecimalSI)}, - {a: Quantity{}, expected: Quantity{}}, - {a: intQuantity(10, 0, BinarySI), expected: intQuantity(-10, 0, BinarySI)}, - {a: intQuantity(-10, 0, BinarySI), expected: intQuantity(10, 0, BinarySI)}, - {a: decQuantity(0, 0, DecimalSI), expected: intQuantity(0, 0, DecimalSI)}, - {a: decQuantity(10, 0, BinarySI), expected: intQuantity(-10, 0, BinarySI)}, - {a: decQuantity(-10, 0, BinarySI), expected: intQuantity(10, 0, BinarySI)}, - } - - for i, test := range tests { - a := test.a.Copy() - a.Neg() - // ensure value is same - if a.Cmp(test.expected) != 0 { - t.Errorf("[%d] Expected %q, got %q", i, test.expected.String(), a.String()) - } - } -} - -func TestAdd(t *testing.T) { - tests := []struct { - a Quantity - b Quantity - expected Quantity - }{ - {decQuantity(10, 0, DecimalSI), decQuantity(1, 1, DecimalSI), decQuantity(20, 0, DecimalSI)}, - {decQuantity(10, 0, DecimalSI), decQuantity(1, 0, BinarySI), decQuantity(11, 0, DecimalSI)}, - {decQuantity(10, 0, BinarySI), decQuantity(1, 0, DecimalSI), decQuantity(11, 0, BinarySI)}, - {Quantity{Format: DecimalSI}, decQuantity(50, 0, DecimalSI), decQuantity(50, 0, DecimalSI)}, - {decQuantity(50, 0, DecimalSI), Quantity{Format: DecimalSI}, decQuantity(50, 0, DecimalSI)}, - {Quantity{Format: DecimalSI}, Quantity{Format: DecimalSI}, decQuantity(0, 0, DecimalSI)}, - } - - for i, test := range tests { - test.a.Add(test.b) - if test.a.Cmp(test.expected) != 0 { - t.Errorf("[%d] Expected %q, got %q", i, test.expected.String(), test.a.String()) - } - } -} - -func TestAddSubRoundTrip(t *testing.T) { - for k := -10; k <= 10; k++ { - q := Quantity{Format: DecimalSI} - var order []int64 - for i := 0; i < 100; i++ { - j := rand.Int63() - order = append(order, j) - q.Add(*NewScaledQuantity(j, Scale(k))) - } - for _, j := range order { - q.Sub(*NewScaledQuantity(j, Scale(k))) - } - if !q.IsZero() { - t.Errorf("addition and subtraction did not cancel: %s", &q) - } - } -} - -func TestAddSubRoundTripAcrossScales(t *testing.T) { - q := Quantity{Format: DecimalSI} - var order []int64 - for i := 0; i < 100; i++ { - j := rand.Int63() - order = append(order, j) - q.Add(*NewScaledQuantity(j, Scale(j%20-10))) - } - for _, j := range order { - q.Sub(*NewScaledQuantity(j, Scale(j%20-10))) - } - if !q.IsZero() { - t.Errorf("addition and subtraction did not cancel: %s", &q) - } -} - -func TestNegateRoundTrip(t *testing.T) { - for _, asDec := range []bool{false, true} { - for k := -10; k <= 10; k++ { - for i := 0; i < 100; i++ { - j := rand.Int63() - q := *NewScaledQuantity(j, Scale(k)) - if asDec { - q.AsDec() - } - - b := q.Copy() - b.Neg() - b.Neg() - if b.Cmp(q) != 0 { - t.Errorf("double negation did not cancel: %s", &q) - } - } - } - } -} -func benchmarkQuantities() []Quantity { - return []Quantity{ - intQuantity(1024*1024*1024, 0, BinarySI), - intQuantity(1024*1024*1024*1024, 0, BinarySI), - intQuantity(1000000, 3, DecimalSI), - intQuantity(1000000000, 0, DecimalSI), - intQuantity(1, -3, DecimalSI), - intQuantity(80, -3, DecimalSI), - intQuantity(1080, -3, DecimalSI), - intQuantity(0, 0, BinarySI), - intQuantity(1, 9, DecimalExponent), - intQuantity(1, -9, DecimalSI), - intQuantity(1000000, 10, DecimalSI), - } -} - -func BenchmarkQuantityString(b *testing.B) { - values := benchmarkQuantities() - b.ResetTimer() - var s string - for i := 0; i < b.N; i++ { - q := values[i%len(values)] - q.s = "" - s = q.String() - } - b.StopTimer() - if len(s) == 0 { - b.Fatal(s) - } -} - -func BenchmarkQuantityStringPrecalc(b *testing.B) { - values := benchmarkQuantities() - for i := range values { - _ = values[i].String() - } - b.ResetTimer() - var s string - for i := 0; i < b.N; i++ { - q := values[i%len(values)] - s = q.String() - } - b.StopTimer() - if len(s) == 0 { - b.Fatal(s) - } -} - -func BenchmarkQuantityStringBinarySI(b *testing.B) { - values := benchmarkQuantities() - for i := range values { - values[i].Format = BinarySI - } - b.ResetTimer() - var s string - for i := 0; i < b.N; i++ { - q := values[i%len(values)] - q.s = "" - s = q.String() - } - b.StopTimer() - if len(s) == 0 { - b.Fatal(s) - } -} - -func BenchmarkQuantityMarshalJSON(b *testing.B) { - values := benchmarkQuantities() - b.ResetTimer() - for i := 0; i < b.N; i++ { - q := values[i%len(values)] - q.s = "" - if _, err := q.MarshalJSON(); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} - -func BenchmarkQuantityUnmarshalJSON(b *testing.B) { - values := benchmarkQuantities() - var json [][]byte - for _, v := range values { - data, _ := v.MarshalJSON() - json = append(json, data) - } - - b.ResetTimer() - for i := 0; i < b.N; i++ { - var q Quantity - if err := q.UnmarshalJSON(json[i%len(values)]); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} - -func BenchmarkParseQuantity(b *testing.B) { - values := benchmarkQuantities() - var strings []string - for _, v := range values { - strings = append(strings, v.String()) - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - if _, err := ParseQuantity(strings[i%len(values)]); err != nil { - b.Fatal(err) - } - } - b.StopTimer() -} - -func BenchmarkCanonicalize(b *testing.B) { - values := benchmarkQuantities() - b.ResetTimer() - buffer := make([]byte, 0, 100) - for i := 0; i < b.N; i++ { - s, _ := values[i%len(values)].CanonicalizeBytes(buffer) - if len(s) == 0 { - b.Fatal(s) - } - } - b.StopTimer() -} - -func BenchmarkQuantityRoundUp(b *testing.B) { - values := benchmarkQuantities() - b.ResetTimer() - for i := 0; i < b.N; i++ { - q := values[i%len(values)] - copied := q - copied.RoundUp(-3) - } - b.StopTimer() -} - -func BenchmarkQuantityCopy(b *testing.B) { - values := benchmarkQuantities() - b.ResetTimer() - for i := 0; i < b.N; i++ { - values[i%len(values)].Copy() - } - b.StopTimer() -} - -func BenchmarkQuantityAdd(b *testing.B) { - values := benchmarkQuantities() - base := &Quantity{} - b.ResetTimer() - for i := 0; i < b.N; i++ { - q := values[i%len(values)] - base.d.Dec = nil - base.i = int64Amount{value: 100} - base.Add(q) - } - b.StopTimer() -} - -func BenchmarkQuantityCmp(b *testing.B) { - values := benchmarkQuantities() - b.ResetTimer() - for i := 0; i < b.N; i++ { - q := values[i%len(values)] - if q.Cmp(q) != 0 { - b.Fatal(q) - } - } - b.StopTimer() -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/resource/scale_int_test.go b/vendor/k8s.io/apimachinery/pkg/api/resource/scale_int_test.go deleted file mode 100644 index b150fa514c..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/resource/scale_int_test.go +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package resource - -import ( - "math" - "math/big" - "testing" -) - -func TestScaledValueInternal(t *testing.T) { - tests := []struct { - unscaled *big.Int - scale int - newScale int - - want int64 - }{ - // remain scale - {big.NewInt(1000), 0, 0, 1000}, - - // scale down - {big.NewInt(1000), 0, -3, 1}, - {big.NewInt(1000), 3, 0, 1}, - {big.NewInt(0), 3, 0, 0}, - - // always round up - {big.NewInt(999), 3, 0, 1}, - {big.NewInt(500), 3, 0, 1}, - {big.NewInt(499), 3, 0, 1}, - {big.NewInt(1), 3, 0, 1}, - // large scaled value does not lose precision - {big.NewInt(0).Sub(maxInt64, bigOne), 1, 0, (math.MaxInt64-1)/10 + 1}, - // large intermediate result. - {big.NewInt(1).Exp(big.NewInt(10), big.NewInt(100), nil), 100, 0, 1}, - - // scale up - {big.NewInt(0), 0, 3, 0}, - {big.NewInt(1), 0, 3, 1000}, - {big.NewInt(1), -3, 0, 1000}, - {big.NewInt(1000), -3, 2, 100000000}, - {big.NewInt(0).Div(big.NewInt(math.MaxInt64), bigThousand), 0, 3, - (math.MaxInt64 / 1000) * 1000}, - } - - for i, tt := range tests { - old := (&big.Int{}).Set(tt.unscaled) - got := scaledValue(tt.unscaled, tt.scale, tt.newScale) - if got != tt.want { - t.Errorf("#%d: got = %v, want %v", i, got, tt.want) - } - if tt.unscaled.Cmp(old) != 0 { - t.Errorf("#%d: unscaled = %v, want %v", i, tt.unscaled, old) - } - } -} - -func BenchmarkScaledValueSmall(b *testing.B) { - s := big.NewInt(1000) - for i := 0; i < b.N; i++ { - scaledValue(s, 3, 0) - } -} - -func BenchmarkScaledValueLarge(b *testing.B) { - s := big.NewInt(math.MaxInt64) - s.Mul(s, big.NewInt(1000)) - for i := 0; i < b.N; i++ { - scaledValue(s, 10, 0) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/BUILD b/vendor/k8s.io/apimachinery/pkg/api/validation/BUILD deleted file mode 100644 index 2c6a0aa3d9..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/validation/BUILD +++ /dev/null @@ -1,53 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["objectmeta_test.go"], - embed = [":go_default_library"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "generic.go", - "objectmeta.go", - ], - importpath = "k8s.io/apimachinery/pkg/api/validation", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/api/equality:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/api/validation/path:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta_test.go b/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta_test.go deleted file mode 100644 index 9ec73b040c..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/api/validation/objectmeta_test.go +++ /dev/null @@ -1,500 +0,0 @@ -/* -Copyright 2017 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package validation - -import ( - "math/rand" - "reflect" - "strings" - "testing" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/validation/field" -) - -const ( - maxLengthErrMsg = "must be no more than" - namePartErrMsg = "name part must consist of" - nameErrMsg = "a qualified name must consist of" -) - -// Ensure custom name functions are allowed -func TestValidateObjectMetaCustomName(t *testing.T) { - errs := ValidateObjectMeta( - &metav1.ObjectMeta{Name: "test", GenerateName: "foo"}, - false, - func(s string, prefix bool) []string { - if s == "test" { - return nil - } - return []string{"name-gen"} - }, - field.NewPath("field")) - if len(errs) != 1 { - t.Fatalf("unexpected errors: %v", errs) - } - if !strings.Contains(errs[0].Error(), "name-gen") { - t.Errorf("unexpected error message: %v", errs) - } -} - -// Ensure namespace names follow dns label format -func TestValidateObjectMetaNamespaces(t *testing.T) { - errs := ValidateObjectMeta( - &metav1.ObjectMeta{Name: "test", Namespace: "foo.bar"}, - true, - func(s string, prefix bool) []string { - return nil - }, - field.NewPath("field")) - if len(errs) != 1 { - t.Fatalf("unexpected errors: %v", errs) - } - if !strings.Contains(errs[0].Error(), `Invalid value: "foo.bar"`) { - t.Errorf("unexpected error message: %v", errs) - } - maxLength := 63 - letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") - b := make([]rune, maxLength+1) - for i := range b { - b[i] = letters[rand.Intn(len(letters))] - } - errs = ValidateObjectMeta( - &metav1.ObjectMeta{Name: "test", Namespace: string(b)}, - true, - func(s string, prefix bool) []string { - return nil - }, - field.NewPath("field")) - if len(errs) != 2 { - t.Fatalf("unexpected errors: %v", errs) - } - if !strings.Contains(errs[0].Error(), "Invalid value") || !strings.Contains(errs[1].Error(), "Invalid value") { - t.Errorf("unexpected error message: %v", errs) - } -} - -func TestValidateObjectMetaOwnerReferences(t *testing.T) { - trueVar := true - falseVar := false - testCases := []struct { - description string - ownerReferences []metav1.OwnerReference - expectError bool - expectedErrorMessage string - }{ - { - description: "simple success - third party extension.", - ownerReferences: []metav1.OwnerReference{ - { - APIVersion: "customresourceVersion", - Kind: "customresourceKind", - Name: "name", - UID: "1", - }, - }, - expectError: false, - expectedErrorMessage: "", - }, - { - description: "simple failures - event shouldn't be set as an owner", - ownerReferences: []metav1.OwnerReference{ - { - APIVersion: "v1", - Kind: "Event", - Name: "name", - UID: "1", - }, - }, - expectError: true, - expectedErrorMessage: "is disallowed from being an owner", - }, - { - description: "simple controller ref success - one reference with Controller set", - ownerReferences: []metav1.OwnerReference{ - { - APIVersion: "customresourceVersion", - Kind: "customresourceKind", - Name: "name", - UID: "1", - Controller: &falseVar, - }, - { - APIVersion: "customresourceVersion", - Kind: "customresourceKind", - Name: "name", - UID: "2", - Controller: &trueVar, - }, - { - APIVersion: "customresourceVersion", - Kind: "customresourceKind", - Name: "name", - UID: "3", - Controller: &falseVar, - }, - { - APIVersion: "customresourceVersion", - Kind: "customresourceKind", - Name: "name", - UID: "4", - }, - }, - expectError: false, - expectedErrorMessage: "", - }, - { - description: "simple controller ref failure - two references with Controller set", - ownerReferences: []metav1.OwnerReference{ - { - APIVersion: "customresourceVersion", - Kind: "customresourceKind", - Name: "name", - UID: "1", - Controller: &falseVar, - }, - { - APIVersion: "customresourceVersion", - Kind: "customresourceKind", - Name: "name", - UID: "2", - Controller: &trueVar, - }, - { - APIVersion: "customresourceVersion", - Kind: "customresourceKind", - Name: "name", - UID: "3", - Controller: &trueVar, - }, - { - APIVersion: "customresourceVersion", - Kind: "customresourceKind", - Name: "name", - UID: "4", - }, - }, - expectError: true, - expectedErrorMessage: "Only one reference can have Controller set to true", - }, - } - - for _, tc := range testCases { - errs := ValidateObjectMeta( - &metav1.ObjectMeta{Name: "test", Namespace: "test", OwnerReferences: tc.ownerReferences}, - true, - func(s string, prefix bool) []string { - return nil - }, - field.NewPath("field")) - if len(errs) != 0 && !tc.expectError { - t.Errorf("unexpected error: %v in test case %v", errs, tc.description) - } - if len(errs) == 0 && tc.expectError { - t.Errorf("expect error in test case %v", tc.description) - } - if len(errs) != 0 && !strings.Contains(errs[0].Error(), tc.expectedErrorMessage) { - t.Errorf("unexpected error message: %v in test case %v", errs, tc.description) - } - } -} - -func TestValidateObjectMetaUpdateIgnoresCreationTimestamp(t *testing.T) { - if errs := ValidateObjectMetaUpdate( - &metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, - &metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(10, 0))}, - field.NewPath("field"), - ); len(errs) != 0 { - t.Fatalf("unexpected errors: %v", errs) - } - if errs := ValidateObjectMetaUpdate( - &metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(10, 0))}, - &metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, - field.NewPath("field"), - ); len(errs) != 0 { - t.Fatalf("unexpected errors: %v", errs) - } - if errs := ValidateObjectMetaUpdate( - &metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(10, 0))}, - &metav1.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: metav1.NewTime(time.Unix(11, 0))}, - field.NewPath("field"), - ); len(errs) != 0 { - t.Fatalf("unexpected errors: %v", errs) - } -} - -func TestValidateFinalizersUpdate(t *testing.T) { - testcases := map[string]struct { - Old metav1.ObjectMeta - New metav1.ObjectMeta - ExpectedErr string - }{ - "invalid adding finalizers": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a"}}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a", "y/b"}}, - ExpectedErr: "y/b", - }, - "invalid changing finalizers": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a"}}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/b"}}, - ExpectedErr: "x/b", - }, - "valid removing finalizers": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a", "y/b"}}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &metav1.Time{}, Finalizers: []string{"x/a"}}, - ExpectedErr: "", - }, - "valid adding finalizers for objects not being deleted": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Finalizers: []string{"x/a"}}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Finalizers: []string{"x/a", "y/b"}}, - ExpectedErr: "", - }, - } - for name, tc := range testcases { - errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field")) - if len(errs) == 0 { - if len(tc.ExpectedErr) != 0 { - t.Errorf("case: %q, expected error to contain %q", name, tc.ExpectedErr) - } - } else if e, a := tc.ExpectedErr, errs.ToAggregate().Error(); !strings.Contains(a, e) { - t.Errorf("case: %q, expected error to contain %q, got error %q", name, e, a) - } - } -} - -func TestValidateFinalizersPreventConflictingFinalizers(t *testing.T) { - testcases := map[string]struct { - ObjectMeta metav1.ObjectMeta - ExpectedErr string - }{ - "conflicting finalizers": { - ObjectMeta: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Finalizers: []string{metav1.FinalizerOrphanDependents, metav1.FinalizerDeleteDependents}}, - ExpectedErr: "cannot be both set", - }, - } - for name, tc := range testcases { - errs := ValidateObjectMeta(&tc.ObjectMeta, false, NameIsDNSSubdomain, field.NewPath("field")) - if len(errs) == 0 { - if len(tc.ExpectedErr) != 0 { - t.Errorf("case: %q, expected error to contain %q", name, tc.ExpectedErr) - } - } else if e, a := tc.ExpectedErr, errs.ToAggregate().Error(); !strings.Contains(a, e) { - t.Errorf("case: %q, expected error to contain %q, got error %q", name, e, a) - } - } -} - -func TestValidateObjectMetaUpdatePreventsDeletionFieldMutation(t *testing.T) { - now := metav1.NewTime(time.Unix(1000, 0).UTC()) - later := metav1.NewTime(time.Unix(2000, 0).UTC()) - gracePeriodShort := int64(30) - gracePeriodLong := int64(40) - - testcases := map[string]struct { - Old metav1.ObjectMeta - New metav1.ObjectMeta - ExpectedNew metav1.ObjectMeta - ExpectedErrs []string - }{ - "valid without deletion fields": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, - ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, - ExpectedErrs: []string{}, - }, - "valid with deletion fields": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort}, - ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort}, - ExpectedErrs: []string{}, - }, - - "invalid set deletionTimestamp": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now}, - ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now}, - ExpectedErrs: []string{"field.deletionTimestamp: Invalid value: 1970-01-01 00:16:40 +0000 UTC: field is immutable; may only be changed via deletion"}, - }, - "invalid clear deletionTimestamp": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, - ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now}, - ExpectedErrs: []string{}, // no errors, validation copies the old value - }, - "invalid change deletionTimestamp": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &later}, - ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now}, - ExpectedErrs: []string{}, // no errors, validation copies the old value - }, - - "invalid set deletionGracePeriodSeconds": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort}, - ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort}, - ExpectedErrs: []string{"field.deletionGracePeriodSeconds: Invalid value: 30: field is immutable; may only be changed via deletion"}, - }, - "invalid clear deletionGracePeriodSeconds": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1"}, - ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort}, - ExpectedErrs: []string{}, // no errors, validation copies the old value - }, - "invalid change deletionGracePeriodSeconds": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodLong}, - ExpectedNew: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodLong}, - ExpectedErrs: []string{"field.deletionGracePeriodSeconds: Invalid value: 40: field is immutable; may only be changed via deletion"}, - }, - } - - for k, tc := range testcases { - errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field")) - if len(errs) != len(tc.ExpectedErrs) { - t.Logf("%s: Expected: %#v", k, tc.ExpectedErrs) - t.Logf("%s: Got: %#v", k, errs) - t.Errorf("%s: expected %d errors, got %d", k, len(tc.ExpectedErrs), len(errs)) - continue - } - for i := range errs { - if errs[i].Error() != tc.ExpectedErrs[i] { - t.Errorf("%s: error #%d: expected %q, got %q", k, i, tc.ExpectedErrs[i], errs[i].Error()) - } - } - if !reflect.DeepEqual(tc.New, tc.ExpectedNew) { - t.Errorf("%s: Expected after validation:\n%#v\ngot\n%#v", k, tc.ExpectedNew, tc.New) - } - } -} - -func TestObjectMetaGenerationUpdate(t *testing.T) { - testcases := map[string]struct { - Old metav1.ObjectMeta - New metav1.ObjectMeta - ExpectedErrs []string - }{ - "invalid generation change - decremented": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 4}, - ExpectedErrs: []string{"field.generation: Invalid value: 4: must not be decremented"}, - }, - "valid generation change - incremented by one": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 1}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 2}, - ExpectedErrs: []string{}, - }, - "valid generation field - not updated": { - Old: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5}, - New: metav1.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5}, - ExpectedErrs: []string{}, - }, - } - - for k, tc := range testcases { - errList := []string{} - errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field")) - if len(errs) != len(tc.ExpectedErrs) { - t.Logf("%s: Expected: %#v", k, tc.ExpectedErrs) - for _, err := range errs { - errList = append(errList, err.Error()) - } - t.Logf("%s: Got: %#v", k, errList) - t.Errorf("%s: expected %d errors, got %d", k, len(tc.ExpectedErrs), len(errs)) - continue - } - for i := range errList { - if errList[i] != tc.ExpectedErrs[i] { - t.Errorf("%s: error #%d: expected %q, got %q", k, i, tc.ExpectedErrs[i], errList[i]) - } - } - } -} - -// Ensure trailing slash is allowed in generate name -func TestValidateObjectMetaTrimsTrailingSlash(t *testing.T) { - errs := ValidateObjectMeta( - &metav1.ObjectMeta{Name: "test", GenerateName: "foo-"}, - false, - NameIsDNSSubdomain, - field.NewPath("field")) - if len(errs) != 0 { - t.Fatalf("unexpected errors: %v", errs) - } -} - -func TestValidateAnnotations(t *testing.T) { - successCases := []map[string]string{ - {"simple": "bar"}, - {"now-with-dashes": "bar"}, - {"1-starts-with-num": "bar"}, - {"1234": "bar"}, - {"simple/simple": "bar"}, - {"now-with-dashes/simple": "bar"}, - {"now-with-dashes/now-with-dashes": "bar"}, - {"now.with.dots/simple": "bar"}, - {"now-with.dashes-and.dots/simple": "bar"}, - {"1-num.2-num/3-num": "bar"}, - {"1234/5678": "bar"}, - {"1.2.3.4/5678": "bar"}, - {"UpperCase123": "bar"}, - {"a": strings.Repeat("b", totalAnnotationSizeLimitB-1)}, - { - "a": strings.Repeat("b", totalAnnotationSizeLimitB/2-1), - "c": strings.Repeat("d", totalAnnotationSizeLimitB/2-1), - }, - } - for i := range successCases { - errs := ValidateAnnotations(successCases[i], field.NewPath("field")) - if len(errs) != 0 { - t.Errorf("case[%d] expected success, got %#v", i, errs) - } - } - - nameErrorCases := []struct { - annotations map[string]string - expect string - }{ - {map[string]string{"nospecialchars^=@": "bar"}, namePartErrMsg}, - {map[string]string{"cantendwithadash-": "bar"}, namePartErrMsg}, - {map[string]string{"only/one/slash": "bar"}, nameErrMsg}, - {map[string]string{strings.Repeat("a", 254): "bar"}, maxLengthErrMsg}, - } - for i := range nameErrorCases { - errs := ValidateAnnotations(nameErrorCases[i].annotations, field.NewPath("field")) - if len(errs) != 1 { - t.Errorf("case[%d]: expected failure", i) - } else { - if !strings.Contains(errs[0].Detail, nameErrorCases[i].expect) { - t.Errorf("case[%d]: error details do not include %q: %q", i, nameErrorCases[i].expect, errs[0].Detail) - } - } - } - totalSizeErrorCases := []map[string]string{ - {"a": strings.Repeat("b", totalAnnotationSizeLimitB)}, - { - "a": strings.Repeat("b", totalAnnotationSizeLimitB/2), - "c": strings.Repeat("d", totalAnnotationSizeLimitB/2), - }, - } - for i := range totalSizeErrorCases { - errs := ValidateAnnotations(totalSizeErrorCases[i], field.NewPath("field")) - if len(errs) != 1 { - t.Errorf("case[%d] expected failure", i) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/BUILD b/vendor/k8s.io/apimachinery/pkg/apimachinery/BUILD deleted file mode 100644 index b1071fb463..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apimachinery/BUILD +++ /dev/null @@ -1,45 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["types_test.go"], - embed = [":go_default_library"], - deps = ["//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "types.go", - ], - importpath = "k8s.io/apimachinery/pkg/apimachinery", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/apimachinery/announced:all-srcs", - "//staging/src/k8s.io/apimachinery/pkg/apimachinery/registered:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/BUILD b/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/BUILD deleted file mode 100644 index ea31914f7f..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/BUILD +++ /dev/null @@ -1,45 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["announced_test.go"], - embed = [":go_default_library"], - deps = ["//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "announced.go", - "group_factory.go", - ], - importpath = "k8s.io/apimachinery/pkg/apimachinery/announced", - deps = [ - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apimachinery:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apimachinery/registered:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/announced_test.go b/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/announced_test.go deleted file mode 100644 index 95882e5df5..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apimachinery/announced/announced_test.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright 2016 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 announced - -import ( - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/util/sets" -) - -func TestFactoryRegistry(t *testing.T) { - regA := make(APIGroupFactoryRegistry) - regB := make(APIGroupFactoryRegistry) - - if err := regA.AnnounceGroup(&GroupMetaFactoryArgs{ - GroupName: "foo", - VersionPreferenceOrder: []string{"v2", "v1"}, - RootScopedKinds: sets.NewString("namespaces"), - }); err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if err := regA.AnnounceGroupVersion(&GroupVersionFactoryArgs{ - GroupName: "foo", - VersionName: "v1", - }); err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if err := regA.AnnounceGroupVersion(&GroupVersionFactoryArgs{ - GroupName: "foo", - VersionName: "v2", - }); err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - if err := regB.AnnouncePreconstructedFactory(NewGroupMetaFactory( - &GroupMetaFactoryArgs{ - GroupName: "foo", - VersionPreferenceOrder: []string{"v2", "v1"}, - RootScopedKinds: sets.NewString("namespaces"), - }, - VersionToSchemeFunc{"v1": nil, "v2": nil}, - )); err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - if !reflect.DeepEqual(regA, regB) { - t.Errorf("Expected both ways of registering to be equivalent, but they were not.\n\n%#v\n\n%#v\n", regA, regB) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/registered/BUILD b/vendor/k8s.io/apimachinery/pkg/apimachinery/registered/BUILD deleted file mode 100644 index ba02a09389..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apimachinery/registered/BUILD +++ /dev/null @@ -1,43 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["registered_test.go"], - embed = [":go_default_library"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/apimachinery:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = ["registered.go"], - importpath = "k8s.io/apimachinery/pkg/apimachinery/registered", - deps = [ - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apimachinery:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/registered/registered_test.go b/vendor/k8s.io/apimachinery/pkg/apimachinery/registered/registered_test.go deleted file mode 100644 index 58fc0173e9..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apimachinery/registered/registered_test.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package registered - -import ( - "testing" - - "k8s.io/apimachinery/pkg/apimachinery" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func TestAllPreferredGroupVersions(t *testing.T) { - testCases := []struct { - groupMetas []apimachinery.GroupMeta - expect string - }{ - { - groupMetas: []apimachinery.GroupMeta{ - { - GroupVersion: schema.GroupVersion{Group: "group1", Version: "v1"}, - }, - { - GroupVersion: schema.GroupVersion{Group: "group2", Version: "v2"}, - }, - { - GroupVersion: schema.GroupVersion{Group: "", Version: "v1"}, - }, - }, - expect: "group1/v1,group2/v2,v1", - }, - { - groupMetas: []apimachinery.GroupMeta{ - { - GroupVersion: schema.GroupVersion{Group: "", Version: "v1"}, - }, - }, - expect: "v1", - }, - { - groupMetas: []apimachinery.GroupMeta{}, - expect: "", - }, - } - for _, testCase := range testCases { - m, err := NewAPIRegistrationManager("") - if err != nil { - t.Fatalf("Unexpected failure to make a manager: %v", err) - } - for _, groupMeta := range testCase.groupMetas { - m.RegisterGroup(groupMeta) - } - output := m.AllPreferredGroupVersions() - if testCase.expect != output { - t.Errorf("Error. expect: %s, got: %s", testCase.expect, output) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apimachinery/types_test.go b/vendor/k8s.io/apimachinery/pkg/apimachinery/types_test.go deleted file mode 100644 index ca858788ef..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apimachinery/types_test.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2016 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 apimachinery - -import ( - "testing" - - "k8s.io/apimachinery/pkg/runtime/schema" -) - -func TestAdd(t *testing.T) { - gm := GroupMeta{ - GroupVersion: schema.GroupVersion{ - Group: "test", - Version: "v1", - }, - GroupVersions: []schema.GroupVersion{{Group: "test", Version: "v1"}}, - } - - gm.AddVersionInterfaces(schema.GroupVersion{Group: "test", Version: "v1"}, nil) - if e, a := 1, len(gm.InterfacesByVersion); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - // GroupVersions is unchanged - if e, a := 1, len(gm.GroupVersions); e != a { - t.Errorf("expected %v, got %v", e, a) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/BUILD b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/BUILD deleted file mode 100644 index edb9a6ac6a..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/BUILD +++ /dev/null @@ -1,59 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "register_test.go", - "roundtrip_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/api/testing/roundtrip:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/fuzzer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/diff:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "conversion.go", - "doc.go", - "register.go", - "types.go", - "zz_generated.conversion.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/apimachinery/pkg/apis/meta/internalversion", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/fields:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/labels:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register_test.go deleted file mode 100644 index 8116f80743..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/register_test.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2017 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 internalversion - -import ( - "net/url" - "reflect" - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/diff" -) - -func TestListOptions(t *testing.T) { - // verify round trip conversion - ten := int64(10) - in := &metav1.ListOptions{ - LabelSelector: "a=1", - FieldSelector: "b=1", - ResourceVersion: "10", - TimeoutSeconds: &ten, - Watch: true, - } - out := &ListOptions{} - if err := scheme.Convert(in, out, nil); err != nil { - t.Fatal(err) - } - actual := &metav1.ListOptions{} - if err := scheme.Convert(out, actual, nil); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(in, actual) { - t.Errorf("unexpected: %s", diff.ObjectReflectDiff(in, actual)) - } - - // verify failing conversion - for i, failingObject := range []*metav1.ListOptions{ - {LabelSelector: "a!!!"}, - {FieldSelector: "a!!!"}, - } { - out = &ListOptions{} - if err := scheme.Convert(failingObject, out, nil); err == nil { - t.Errorf("%d: unexpected conversion: %#v", i, out) - } - } - - // verify kind registration - if gvks, unversioned, err := scheme.ObjectKinds(in); err != nil || unversioned || gvks[0] != metav1.SchemeGroupVersion.WithKind("ListOptions") { - t.Errorf("unexpected: %v %v %v", gvks[0], unversioned, err) - } - if gvks, unversioned, err := scheme.ObjectKinds(out); err != nil || unversioned || gvks[0] != SchemeGroupVersion.WithKind("ListOptions") { - t.Errorf("unexpected: %v %v %v", gvks[0], unversioned, err) - } - - actual = &metav1.ListOptions{} - if err := ParameterCodec.DecodeParameters(url.Values{"watch": []string{"1"}}, metav1.SchemeGroupVersion, actual); err != nil { - t.Fatal(err) - } - if !actual.Watch { - t.Errorf("unexpected watch decode: %#v", actual) - } - - // check ParameterCodec - query, err := ParameterCodec.EncodeParameters(in, metav1.SchemeGroupVersion) - if err != nil { - t.Fatal(err) - } - actual = &metav1.ListOptions{} - if err := ParameterCodec.DecodeParameters(query, metav1.SchemeGroupVersion, actual); err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(in, actual) { - t.Errorf("unexpected: %s", diff.ObjectReflectDiff(in, actual)) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/roundtrip_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/roundtrip_test.go deleted file mode 100644 index 725aa316d0..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/internalversion/roundtrip_test.go +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright 2017 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 internalversion - -import ( - "testing" - - "k8s.io/apimachinery/pkg/api/testing/roundtrip" - "k8s.io/apimachinery/pkg/apis/meta/fuzzer" -) - -func TestRoundTrip(t *testing.T) { - roundtrip.RoundTripTestForScheme(t, scheme, fuzzer.Funcs) -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/BUILD b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/BUILD deleted file mode 100644 index 186db1871e..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/BUILD +++ /dev/null @@ -1,101 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "controller_ref_test.go", - "duration_test.go", - "group_version_test.go", - "helpers_test.go", - "labels_test.go", - "micro_time_test.go", - "time_test.go", - "types_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/github.com/ghodss/yaml:go_default_library", - "//vendor/github.com/json-iterator/go:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/labels:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "controller_ref.go", - "conversion.go", - "doc.go", - "duration.go", - "generated.pb.go", - "group_version.go", - "helpers.go", - "labels.go", - "meta.go", - "micro_time.go", - "micro_time_proto.go", - "register.go", - "time.go", - "time_proto.go", - "types.go", - "types_swagger_doc_generated.go", - "watch.go", - "zz_generated.deepcopy.go", - "zz_generated.defaults.go", - ], - importpath = "k8s.io/apimachinery/pkg/apis/meta/v1", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/gogo/protobuf/sortkeys:go_default_library", - "//vendor/github.com/google/gofuzz:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/resource:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/fields:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/labels:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/selection:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/types:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/intstr:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/watch:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:all-srcs", - "//staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/validation:all-srcs", - ], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) - -go_test( - name = "go_default_xtest", - srcs = ["conversion_test.go"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/api/equality:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - ], -) diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref_test.go deleted file mode 100644 index add764a331..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/controller_ref_test.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright 2017 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 v1 - -import ( - "testing" - - "k8s.io/apimachinery/pkg/runtime/schema" -) - -type metaObj struct { - ObjectMeta - TypeMeta -} - -func TestNewControllerRef(t *testing.T) { - gvk := schema.GroupVersionKind{ - Group: "group", - Version: "v1", - Kind: "Kind", - } - obj1 := &metaObj{ - ObjectMeta: ObjectMeta{ - Name: "name", - UID: "uid1", - }, - } - controllerRef := NewControllerRef(obj1, gvk) - if controllerRef.UID != obj1.UID { - t.Errorf("Incorrect UID: %s", controllerRef.UID) - } - if controllerRef.Controller == nil || *controllerRef.Controller != true { - t.Error("Controller must be set to true") - } - if controllerRef.BlockOwnerDeletion == nil || *controllerRef.BlockOwnerDeletion != true { - t.Error("BlockOwnerDeletion must be set to true") - } - if controllerRef.APIVersion == "" || - controllerRef.Kind == "" || - controllerRef.Name == "" { - t.Errorf("All controllerRef fields must be set: %v", controllerRef) - } -} - -func TestGetControllerOf(t *testing.T) { - gvk := schema.GroupVersionKind{ - Group: "group", - Version: "v1", - Kind: "Kind", - } - obj1 := &metaObj{ - ObjectMeta: ObjectMeta{ - UID: "uid1", - Name: "name1", - }, - } - controllerRef := NewControllerRef(obj1, gvk) - var falseRef = false - obj2 := &metaObj{ - ObjectMeta: ObjectMeta{ - UID: "uid2", - Name: "name1", - OwnerReferences: []OwnerReference{ - { - Name: "owner1", - Controller: &falseRef, - }, - *controllerRef, - { - Name: "owner2", - Controller: &falseRef, - }, - }, - }, - } - - if GetControllerOf(obj1) != nil { - t.Error("GetControllerOf must return null") - } - c := GetControllerOf(obj2) - if c.Name != controllerRef.Name || c.UID != controllerRef.UID { - t.Errorf("Incorrect result of GetControllerOf: %v", c) - } -} - -func TestIsControlledBy(t *testing.T) { - gvk := schema.GroupVersionKind{ - Group: "group", - Version: "v1", - Kind: "Kind", - } - obj1 := &metaObj{ - ObjectMeta: ObjectMeta{ - UID: "uid1", - }, - } - obj2 := &metaObj{ - ObjectMeta: ObjectMeta{ - UID: "uid2", - OwnerReferences: []OwnerReference{ - *NewControllerRef(obj1, gvk), - }, - }, - } - obj3 := &metaObj{ - ObjectMeta: ObjectMeta{ - UID: "uid3", - OwnerReferences: []OwnerReference{ - *NewControllerRef(obj2, gvk), - }, - }, - } - if !IsControlledBy(obj2, obj1) || !IsControlledBy(obj3, obj2) { - t.Error("Incorrect IsControlledBy result: false") - } - if IsControlledBy(obj3, obj1) { - t.Error("Incorrect IsControlledBy result: true") - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/conversion_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/conversion_test.go deleted file mode 100644 index bc591584ef..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/conversion_test.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright 2017 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 v1_test - -import ( - "testing" - - apiequality "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestMapToLabelSelectorRoundTrip(t *testing.T) { - // We should be able to round-trip a map-only selector through LabelSelector. - inputs := []map[string]string{ - nil, - {}, - {"one": "foo"}, - {"one": "foo", "two": "bar"}, - } - for _, in := range inputs { - ls := &v1.LabelSelector{} - if err := v1.Convert_map_to_unversioned_LabelSelector(&in, ls, nil); err != nil { - t.Errorf("Convert_map_to_unversioned_LabelSelector(%#v): %v", in, err) - continue - } - out := map[string]string{} - if err := v1.Convert_unversioned_LabelSelector_to_map(ls, &out, nil); err != nil { - t.Errorf("Convert_unversioned_LabelSelector_to_map(%#v): %v", ls, err) - continue - } - if !apiequality.Semantic.DeepEqual(in, out) { - t.Errorf("map-selector conversion round-trip failed: got %v; want %v", out, in) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/duration_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/duration_test.go deleted file mode 100644 index 7230cb28ab..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/duration_test.go +++ /dev/null @@ -1,153 +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 v1 - -import ( - "encoding/json" - "testing" - "time" - - "github.com/ghodss/yaml" -) - -type DurationHolder struct { - D Duration `json:"d"` -} - -func TestDurationMarshalYAML(t *testing.T) { - cases := []struct { - input Duration - result string - }{ - {Duration{5 * time.Second}, "d: 5s\n"}, - {Duration{2 * time.Minute}, "d: 2m0s\n"}, - {Duration{time.Hour + 3*time.Millisecond}, "d: 1h0m0.003s\n"}, - } - - for _, c := range cases { - input := DurationHolder{c.input} - result, err := yaml.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input: %q: %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input: %q: expected %q, got %q", input, c.result, string(result)) - } - } -} - -func TestDurationUnmarshalYAML(t *testing.T) { - cases := []struct { - input string - result Duration - }{ - {"d: 0s\n", Duration{}}, - {"d: 5s\n", Duration{5 * time.Second}}, - {"d: 2m0s\n", Duration{2 * time.Minute}}, - {"d: 1h0m0.003s\n", Duration{time.Hour + 3*time.Millisecond}}, - - // Units with zero values can optionally be dropped - {"d: 2m\n", Duration{2 * time.Minute}}, - {"d: 1h0.003s\n", Duration{time.Hour + 3*time.Millisecond}}, - } - - for _, c := range cases { - var result DurationHolder - if err := yaml.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input %q: %v", c.input, err) - } - if result.D != c.result { - t.Errorf("Failed to unmarshal input %q: expected %q, got %q", c.input, c.result, result) - } - } -} - -func TestDurationMarshalJSON(t *testing.T) { - cases := []struct { - input Duration - result string - }{ - {Duration{5 * time.Second}, `{"d":"5s"}`}, - {Duration{2 * time.Minute}, `{"d":"2m0s"}`}, - {Duration{time.Hour + 3*time.Millisecond}, `{"d":"1h0m0.003s"}`}, - } - - for _, c := range cases { - input := DurationHolder{c.input} - result, err := json.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input: %q: %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input: %q: expected %q, got %q", input, c.result, string(result)) - } - } -} - -func TestDurationUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result Duration - }{ - {`{"d":"0s"}`, Duration{}}, - {`{"d":"5s"}`, Duration{5 * time.Second}}, - {`{"d":"2m0s"}`, Duration{2 * time.Minute}}, - {`{"d":"1h0m0.003s"}`, Duration{time.Hour + 3*time.Millisecond}}, - - // Units with zero values can optionally be dropped - {`{"d":"2m"}`, Duration{2 * time.Minute}}, - {`{"d":"1h0.003s"}`, Duration{time.Hour + 3*time.Millisecond}}, - } - - for _, c := range cases { - var result DurationHolder - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input %q: %v", c.input, err) - } - if result.D != c.result { - t.Errorf("Failed to unmarshal input %q: expected %q, got %q", c.input, c.result, result) - } - } -} - -func TestDurationMarshalJSONUnmarshalYAML(t *testing.T) { - cases := []struct { - input Duration - }{ - {Duration{}}, - {Duration{5 * time.Second}}, - {Duration{2 * time.Minute}}, - {Duration{time.Hour + 3*time.Millisecond}}, - } - - for i, c := range cases { - input := DurationHolder{c.input} - jsonMarshalled, err := json.Marshal(&input) - if err != nil { - t.Errorf("%d-1: Failed to marshal input: '%v': %v", i, input, err) - } - - var result DurationHolder - if err := yaml.Unmarshal(jsonMarshalled, &result); err != nil { - t.Errorf("%d-2: Failed to unmarshal '%+v': %v", i, string(jsonMarshalled), err) - } - - if input.D != result.D { - t.Errorf("%d-4: Failed to marshal input '%#v': got %#v", i, input, result) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/group_version_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/group_version_test.go deleted file mode 100644 index 1f7f07e81d..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/group_version_test.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1 - -import ( - "encoding/json" - "reflect" - "testing" - - jsoniter "github.com/json-iterator/go" -) - -type GroupVersionHolder struct { - GV GroupVersion `json:"val"` -} - -func TestGroupVersionUnmarshalJSON(t *testing.T) { - cases := []struct { - input []byte - expect GroupVersion - }{ - {[]byte(`{"val": "v1"}`), GroupVersion{"", "v1"}}, - {[]byte(`{"val": "extensions/v1beta1"}`), GroupVersion{"extensions", "v1beta1"}}, - } - - for _, c := range cases { - var result GroupVersionHolder - // test golang lib's JSON codec - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("JSON codec failed to unmarshal input '%v': %v", c.input, err) - } - if !reflect.DeepEqual(result.GV, c.expect) { - t.Errorf("JSON codec failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV) - } - // test the json-iterator codec - if err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(c.input, &result); err != nil { - t.Errorf("json-iterator codec failed to unmarshal input '%v': %v", c.input, err) - } - if !reflect.DeepEqual(result.GV, c.expect) { - t.Errorf("json-iterator codec failed to unmarshal input '%s': expected %+v, got %+v", c.input, c.expect, result.GV) - } - } -} - -func TestGroupVersionMarshalJSON(t *testing.T) { - cases := []struct { - input GroupVersion - expect []byte - }{ - {GroupVersion{"", "v1"}, []byte(`{"val":"v1"}`)}, - {GroupVersion{"extensions", "v1beta1"}, []byte(`{"val":"extensions/v1beta1"}`)}, - } - - for _, c := range cases { - input := GroupVersionHolder{c.input} - result, err := json.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input '%v': %v", input, err) - } - if !reflect.DeepEqual(result, c.expect) { - t.Errorf("Failed to marshal input '%+v': expected: %s, got: %s", input, c.expect, result) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers_test.go deleted file mode 100644 index fba6b158ed..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/helpers_test.go +++ /dev/null @@ -1,154 +0,0 @@ -/* -Copyright 2016 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 v1 - -import ( - "reflect" - "strings" - "testing" - - "k8s.io/apimachinery/pkg/labels" -) - -func TestLabelSelectorAsSelector(t *testing.T) { - matchLabels := map[string]string{"foo": "bar"} - matchExpressions := []LabelSelectorRequirement{{ - Key: "baz", - Operator: LabelSelectorOpIn, - Values: []string{"qux", "norf"}, - }} - mustParse := func(s string) labels.Selector { - out, e := labels.Parse(s) - if e != nil { - panic(e) - } - return out - } - tc := []struct { - in *LabelSelector - out labels.Selector - expectErr bool - }{ - {in: nil, out: labels.Nothing()}, - {in: &LabelSelector{}, out: labels.Everything()}, - { - in: &LabelSelector{MatchLabels: matchLabels}, - out: mustParse("foo=bar"), - }, - { - in: &LabelSelector{MatchExpressions: matchExpressions}, - out: mustParse("baz in (norf,qux)"), - }, - { - in: &LabelSelector{MatchLabels: matchLabels, MatchExpressions: matchExpressions}, - out: mustParse("baz in (norf,qux),foo=bar"), - }, - { - in: &LabelSelector{ - MatchExpressions: []LabelSelectorRequirement{{ - Key: "baz", - Operator: LabelSelectorOpExists, - Values: []string{"qux", "norf"}, - }}, - }, - expectErr: true, - }, - } - - for i, tc := range tc { - out, err := LabelSelectorAsSelector(tc.in) - if err == nil && tc.expectErr { - t.Errorf("[%v]expected error but got none.", i) - } - if err != nil && !tc.expectErr { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } - if !reflect.DeepEqual(out, tc.out) { - t.Errorf("[%v]expected:\n\t%+v\nbut got:\n\t%+v", i, tc.out, out) - } - } -} - -func TestLabelSelectorAsMap(t *testing.T) { - matchLabels := map[string]string{"foo": "bar"} - matchExpressions := func(operator LabelSelectorOperator, values []string) []LabelSelectorRequirement { - return []LabelSelectorRequirement{{ - Key: "baz", - Operator: operator, - Values: values, - }} - } - - tests := []struct { - in *LabelSelector - out map[string]string - errString string - }{ - {in: nil, out: nil}, - { - in: &LabelSelector{MatchLabels: matchLabels}, - out: map[string]string{"foo": "bar"}, - }, - { - in: &LabelSelector{MatchLabels: matchLabels, MatchExpressions: matchExpressions(LabelSelectorOpIn, []string{"norf"})}, - out: map[string]string{"foo": "bar", "baz": "norf"}, - }, - { - in: &LabelSelector{MatchExpressions: matchExpressions(LabelSelectorOpIn, []string{"norf"})}, - out: map[string]string{"baz": "norf"}, - }, - { - in: &LabelSelector{MatchLabels: matchLabels, MatchExpressions: matchExpressions(LabelSelectorOpIn, []string{"norf", "qux"})}, - out: map[string]string{"foo": "bar"}, - errString: "without a single value cannot be converted", - }, - { - in: &LabelSelector{MatchExpressions: matchExpressions(LabelSelectorOpNotIn, []string{"norf", "qux"})}, - out: map[string]string{}, - errString: "cannot be converted", - }, - { - in: &LabelSelector{MatchLabels: matchLabels, MatchExpressions: matchExpressions(LabelSelectorOpExists, []string{})}, - out: map[string]string{"foo": "bar"}, - errString: "cannot be converted", - }, - { - in: &LabelSelector{MatchExpressions: matchExpressions(LabelSelectorOpDoesNotExist, []string{})}, - out: map[string]string{}, - errString: "cannot be converted", - }, - } - - for i, tc := range tests { - out, err := LabelSelectorAsMap(tc.in) - if err == nil && len(tc.errString) > 0 { - t.Errorf("[%v]expected error but got none.", i) - continue - } - if err != nil && len(tc.errString) == 0 { - t.Errorf("[%v]did not expect error but got: %v", i, err) - continue - } - if err != nil && len(tc.errString) > 0 && !strings.Contains(err.Error(), tc.errString) { - t.Errorf("[%v]expected error with %q but got: %v", i, tc.errString, err) - continue - } - if !reflect.DeepEqual(out, tc.out) { - t.Errorf("[%v]expected:\n\t%+v\nbut got:\n\t%+v", i, tc.out, out) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/labels_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/labels_test.go deleted file mode 100644 index 918b1a294c..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/labels_test.go +++ /dev/null @@ -1,123 +0,0 @@ -/* -Copyright 2016 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 v1 - -import ( - "reflect" - "testing" -) - -func TestCloneSelectorAndAddLabel(t *testing.T) { - labels := map[string]string{ - "foo1": "bar1", - "foo2": "bar2", - "foo3": "bar3", - } - matchExpressions := []LabelSelectorRequirement{ - {Key: "foo", Operator: LabelSelectorOpIn, Values: []string{"foo"}}, - } - - cases := []struct { - labels map[string]string - labelKey string - labelValue string - want map[string]string - }{ - { - labels: labels, - want: labels, - }, - { - labels: labels, - labelKey: "foo4", - labelValue: "89", - want: map[string]string{ - "foo1": "bar1", - "foo2": "bar2", - "foo3": "bar3", - "foo4": "89", - }, - }, - { - labels: nil, - labelKey: "foo4", - labelValue: "12", - want: map[string]string{ - "foo4": "12", - }, - }, - } - - for _, tc := range cases { - ls_in := LabelSelector{MatchLabels: tc.labels, MatchExpressions: matchExpressions} - ls_out := LabelSelector{MatchLabels: tc.want, MatchExpressions: matchExpressions} - - got := CloneSelectorAndAddLabel(&ls_in, tc.labelKey, tc.labelValue) - if !reflect.DeepEqual(got, &ls_out) { - t.Errorf("got %v, want %v", got, tc.want) - } - } -} - -func TestAddLabelToSelector(t *testing.T) { - labels := map[string]string{ - "foo1": "bar1", - "foo2": "bar2", - "foo3": "bar3", - } - - cases := []struct { - labels map[string]string - labelKey string - labelValue string - want map[string]string - }{ - { - labels: labels, - want: labels, - }, - { - labels: labels, - labelKey: "foo4", - labelValue: "89", - want: map[string]string{ - "foo1": "bar1", - "foo2": "bar2", - "foo3": "bar3", - "foo4": "89", - }, - }, - { - labels: nil, - labelKey: "foo4", - labelValue: "12", - want: map[string]string{ - "foo4": "12", - }, - }, - } - - for _, tc := range cases { - ls_in := LabelSelector{MatchLabels: tc.labels} - ls_out := LabelSelector{MatchLabels: tc.want} - - got := AddLabelToSelector(&ls_in, tc.labelKey, tc.labelValue) - if !reflect.DeepEqual(got, &ls_out) { - t.Errorf("got %v, want %v", got, tc.want) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_test.go deleted file mode 100644 index 339610aeba..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/micro_time_test.go +++ /dev/null @@ -1,139 +0,0 @@ -/* -Copyright 2016 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 v1 - -import ( - "encoding/json" - "reflect" - "testing" - "time" - - "github.com/ghodss/yaml" -) - -type MicroTimeHolder struct { - T MicroTime `json:"t"` -} - -func TestMicroTimeMarshalYAML(t *testing.T) { - cases := []struct { - input MicroTime - result string - }{ - {MicroTime{}, "t: null\n"}, - {DateMicro(1998, time.May, 5, 1, 5, 5, 50, time.FixedZone("test", -4*60*60)), "t: 1998-05-05T05:05:05.000000Z\n"}, - {DateMicro(1998, time.May, 5, 5, 5, 5, 0, time.UTC), "t: 1998-05-05T05:05:05.000000Z\n"}, - } - - for _, c := range cases { - input := MicroTimeHolder{c.input} - result, err := yaml.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input: '%v': %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input: '%v': expected %+v, got %q", input, c.result, string(result)) - } - } -} - -func TestMicroTimeUnmarshalYAML(t *testing.T) { - cases := []struct { - input string - result MicroTime - }{ - {"t: null\n", MicroTime{}}, - {"t: 1998-05-05T05:05:05.000000Z\n", MicroTime{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Local()}}, - } - - for _, c := range cases { - var result MicroTimeHolder - if err := yaml.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if result.T != c.result { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) - } - } -} - -func TestMicroTimeMarshalJSON(t *testing.T) { - cases := []struct { - input MicroTime - result string - }{ - {MicroTime{}, "{\"t\":null}"}, - {DateMicro(1998, time.May, 5, 5, 5, 5, 50, time.UTC), "{\"t\":\"1998-05-05T05:05:05.000000Z\"}"}, - {DateMicro(1998, time.May, 5, 5, 5, 5, 0, time.UTC), "{\"t\":\"1998-05-05T05:05:05.000000Z\"}"}, - } - - for _, c := range cases { - input := MicroTimeHolder{c.input} - result, err := json.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input: '%v': %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input: '%v': expected %+v, got %q", input, c.result, string(result)) - } - } -} - -func TestMicroTimeUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result MicroTime - }{ - {"{\"t\":null}", MicroTime{}}, - {"{\"t\":\"1998-05-05T05:05:05.000000Z\"}", MicroTime{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Local()}}, - } - - for _, c := range cases { - var result MicroTimeHolder - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if result.T != c.result { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) - } - } -} - -func TestMicroTimeProto(t *testing.T) { - cases := []struct { - input MicroTime - }{ - {MicroTime{}}, - {DateMicro(1998, time.May, 5, 1, 5, 5, 50, time.Local)}, - {DateMicro(1998, time.May, 5, 5, 5, 5, 0, time.Local)}, - } - - for _, c := range cases { - input := c.input - data, err := input.Marshal() - if err != nil { - t.Fatalf("Failed to marshal input: '%v': %v", input, err) - } - time := MicroTime{} - if err := time.Unmarshal(data); err != nil { - t.Fatalf("Failed to unmarshal output: '%v': %v", input, err) - } - if !reflect.DeepEqual(input, time) { - t.Errorf("Marshal->Unmarshal is not idempotent: '%v' vs '%v'", input, time) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go deleted file mode 100644 index 9923958ee0..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/time_test.go +++ /dev/null @@ -1,197 +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 v1 - -import ( - "encoding/json" - "reflect" - "testing" - "time" - - "github.com/ghodss/yaml" -) - -type TimeHolder struct { - T Time `json:"t"` -} - -func TestTimeMarshalYAML(t *testing.T) { - cases := []struct { - input Time - result string - }{ - {Time{}, "t: null\n"}, - {Date(1998, time.May, 5, 1, 5, 5, 50, time.FixedZone("test", -4*60*60)), "t: 1998-05-05T05:05:05Z\n"}, - {Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC), "t: 1998-05-05T05:05:05Z\n"}, - } - - for _, c := range cases { - input := TimeHolder{c.input} - result, err := yaml.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input: '%v': %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input: '%v': expected %+v, got %q", input, c.result, string(result)) - } - } -} - -func TestTimeUnmarshalYAML(t *testing.T) { - cases := []struct { - input string - result Time - }{ - {"t: null\n", Time{}}, - {"t: 1998-05-05T05:05:05Z\n", Time{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Local()}}, - } - - for _, c := range cases { - var result TimeHolder - if err := yaml.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if result.T != c.result { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) - } - } -} - -func TestTimeMarshalJSON(t *testing.T) { - cases := []struct { - input Time - result string - }{ - {Time{}, "{\"t\":null}"}, - {Date(1998, time.May, 5, 5, 5, 5, 50, time.UTC), "{\"t\":\"1998-05-05T05:05:05Z\"}"}, - {Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC), "{\"t\":\"1998-05-05T05:05:05Z\"}"}, - } - - for _, c := range cases { - input := TimeHolder{c.input} - result, err := json.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input: '%v': %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input: '%v': expected %+v, got %q", input, c.result, string(result)) - } - } -} - -func TestTimeUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result Time - }{ - {"{\"t\":null}", Time{}}, - {"{\"t\":\"1998-05-05T05:05:05Z\"}", Time{Date(1998, time.May, 5, 5, 5, 5, 0, time.UTC).Local()}}, - } - - for _, c := range cases { - var result TimeHolder - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if result.T != c.result { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) - } - } -} - -func TestTimeMarshalJSONUnmarshalYAML(t *testing.T) { - cases := []struct { - input Time - }{ - {Time{}}, - {Date(1998, time.May, 5, 5, 5, 5, 50, time.Local).Rfc3339Copy()}, - {Date(1998, time.May, 5, 5, 5, 5, 0, time.Local).Rfc3339Copy()}, - } - - for i, c := range cases { - input := TimeHolder{c.input} - jsonMarshalled, err := json.Marshal(&input) - if err != nil { - t.Errorf("%d-1: Failed to marshal input: '%v': %v", i, input, err) - } - - var result TimeHolder - err = yaml.Unmarshal(jsonMarshalled, &result) - if err != nil { - t.Errorf("%d-2: Failed to unmarshal '%+v': %v", i, string(jsonMarshalled), err) - } - - iN, iO := input.T.Zone() - oN, oO := result.T.Zone() - if iN != oN || iO != oO { - t.Errorf("%d-3: Time zones differ before and after serialization %s:%d %s:%d", i, iN, iO, oN, oO) - } - - if input.T.UnixNano() != result.T.UnixNano() { - t.Errorf("%d-4: Failed to marshal input '%#v': got %#v", i, input, result) - } - } -} - -func TestTimeProto(t *testing.T) { - cases := []struct { - input Time - }{ - {Time{}}, - {Date(1998, time.May, 5, 1, 5, 5, 0, time.Local)}, - {Date(1998, time.May, 5, 5, 5, 5, 0, time.Local)}, - } - - for _, c := range cases { - input := c.input - data, err := input.Marshal() - if err != nil { - t.Fatalf("Failed to marshal input: '%v': %v", input, err) - } - time := Time{} - if err := time.Unmarshal(data); err != nil { - t.Fatalf("Failed to unmarshal output: '%v': %v", input, err) - } - if !reflect.DeepEqual(input, time) { - t.Errorf("Marshal->Unmarshal is not idempotent: '%v' vs '%v'", input, time) - } - } -} - -func TestTimeEqual(t *testing.T) { - t1 := NewTime(time.Now()) - cases := []struct { - name string - x *Time - y *Time - result bool - }{ - {"nil =? nil", nil, nil, true}, - {"!nil =? !nil", &t1, &t1, true}, - {"nil =? !nil", nil, &t1, false}, - {"!nil =? nil", &t1, nil, false}, - } - - for _, c := range cases { - t.Run(c.name, func(t *testing.T) { - result := c.x.Equal(c.y) - if result != c.result { - t.Errorf("Failed equality test for '%v', '%v': expected %+v, got %+v", c.x, c.y, c.result, result) - } - }) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_test.go deleted file mode 100644 index 116f7505a4..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/types_test.go +++ /dev/null @@ -1,134 +0,0 @@ -/* -Copyright 2016 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 v1 - -import ( - "encoding/json" - "reflect" - "testing" - - jsoniter "github.com/json-iterator/go" -) - -func TestVerbsUgorjiMarshalJSON(t *testing.T) { - cases := []struct { - input APIResource - result string - }{ - {APIResource{}, `{"name":"","singularName":"","namespaced":false,"kind":"","verbs":null}`}, - {APIResource{Verbs: Verbs([]string{})}, `{"name":"","singularName":"","namespaced":false,"kind":"","verbs":[]}`}, - {APIResource{Verbs: Verbs([]string{"delete"})}, `{"name":"","singularName":"","namespaced":false,"kind":"","verbs":["delete"]}`}, - } - - for i, c := range cases { - result, err := json.Marshal(&c.input) - if err != nil { - t.Errorf("[%d] Failed to marshal input: '%v': %v", i, c.input, err) - } - if string(result) != c.result { - t.Errorf("[%d] Failed to marshal input: '%v': expected '%v', got '%v'", i, c.input, c.result, string(result)) - } - } -} - -func TestVerbsUgorjiUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result APIResource - }{ - {`{}`, APIResource{}}, - {`{"verbs":null}`, APIResource{}}, - {`{"verbs":[]}`, APIResource{Verbs: Verbs([]string{})}}, - {`{"verbs":["delete"]}`, APIResource{Verbs: Verbs([]string{"delete"})}}, - } - - for i, c := range cases { - var result APIResource - if err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("[%d] Failed to unmarshal input '%v': %v", i, c.input, err) - } - if !reflect.DeepEqual(result, c.result) { - t.Errorf("[%d] Failed to unmarshal input '%v': expected %+v, got %+v", i, c.input, c.result, result) - } - } -} - -// TestUgorjiMarshalJSONWithOmit tests that we don't have regressions regarding nil and empty slices with "omit" -func TestUgorjiMarshalJSONWithOmit(t *testing.T) { - cases := []struct { - input LabelSelector - result string - }{ - {LabelSelector{}, `{}`}, - {LabelSelector{MatchExpressions: []LabelSelectorRequirement{}}, `{}`}, - {LabelSelector{MatchExpressions: []LabelSelectorRequirement{{}}}, `{"matchExpressions":[{"key":"","operator":""}]}`}, - } - - for i, c := range cases { - result, err := json.Marshal(&c.input) - if err != nil { - t.Errorf("[%d] Failed to marshal input: '%v': %v", i, c.input, err) - } - if string(result) != c.result { - t.Errorf("[%d] Failed to marshal input: '%v': expected '%v', got '%v'", i, c.input, c.result, string(result)) - } - } -} - -func TestVerbsUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result APIResource - }{ - {`{}`, APIResource{}}, - {`{"verbs":null}`, APIResource{}}, - {`{"verbs":[]}`, APIResource{Verbs: Verbs([]string{})}}, - {`{"verbs":["delete"]}`, APIResource{Verbs: Verbs([]string{"delete"})}}, - } - - for i, c := range cases { - var result APIResource - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("[%d] Failed to unmarshal input '%v': %v", i, c.input, err) - } - if !reflect.DeepEqual(result, c.result) { - t.Errorf("[%d] Failed to unmarshal input '%v': expected %+v, got %+v", i, c.input, c.result, result) - } - } -} - -func TestVerbsProto(t *testing.T) { - cases := []APIResource{ - {}, - {Verbs: Verbs([]string{})}, - {Verbs: Verbs([]string{"delete"})}, - } - - for _, input := range cases { - data, err := input.Marshal() - if err != nil { - t.Fatalf("Failed to marshal input: '%v': %v", input, err) - } - resource := APIResource{} - if err := resource.Unmarshal(data); err != nil { - t.Fatalf("Failed to unmarshal output: '%v': %v", input, err) - } - if !reflect.DeepEqual(input, resource) { - t.Errorf("Marshal->Unmarshal is not idempotent: '%v' vs '%v'", input, resource) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/BUILD b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/BUILD deleted file mode 100644 index 22c1acee07..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/BUILD +++ /dev/null @@ -1,53 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "helpers_test.go", - "unstructured_list_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/github.com/stretchr/testify/assert:go_default_library", - "//vendor/github.com/stretchr/testify/require:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "helpers.go", - "unstructured.go", - "unstructured_list.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/types:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/json:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers_test.go deleted file mode 100644 index 9e774d1c19..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/helpers_test.go +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright 2017 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 unstructured - -import ( - "io/ioutil" - "sync" - "testing" - - "github.com/stretchr/testify/assert" -) - -// TestCodecOfUnstructuredList tests that there are no data races in Encode(). -// i.e. that it does not mutate the object being encoded. -func TestCodecOfUnstructuredList(t *testing.T) { - var wg sync.WaitGroup - concurrency := 10 - list := UnstructuredList{ - Object: map[string]interface{}{}, - } - wg.Add(concurrency) - for i := 0; i < concurrency; i++ { - go func() { - defer wg.Done() - assert.NoError(t, UnstructuredJSONScheme.Encode(&list, ioutil.Discard)) - }() - } - wg.Wait() -} - -func TestRemoveNestedField(t *testing.T) { - obj := map[string]interface{}{ - "x": map[string]interface{}{ - "y": 1, - "a": "foo", - }, - } - RemoveNestedField(obj, "x", "a") - assert.Len(t, obj["x"], 1) - RemoveNestedField(obj, "x", "y") - assert.Empty(t, obj["x"]) - RemoveNestedField(obj, "x") - assert.Empty(t, obj) - RemoveNestedField(obj, "x") // Remove of a non-existent field - assert.Empty(t, obj) -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list_test.go deleted file mode 100644 index 04ada449b9..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured/unstructured_list_test.go +++ /dev/null @@ -1,86 +0,0 @@ -/* -Copyright 2017 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 unstructured - -import ( - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestUnstructuredList(t *testing.T) { - list := &UnstructuredList{ - Object: map[string]interface{}{"kind": "List", "apiVersion": "v1"}, - Items: []Unstructured{ - {Object: map[string]interface{}{"kind": "Pod", "apiVersion": "v1", "metadata": map[string]interface{}{"name": "test"}}}, - }, - } - content := list.UnstructuredContent() - items := content["items"].([]interface{}) - require.Len(t, items, 1) - val, found, err := NestedFieldCopy(items[0].(map[string]interface{}), "metadata", "name") - require.True(t, found) - require.NoError(t, err) - assert.Equal(t, "test", val) -} - -func TestNilDeletionTimestamp(t *testing.T) { - var u Unstructured - del := u.GetDeletionTimestamp() - if del != nil { - t.Errorf("unexpected non-nil deletion timestamp: %v", del) - } - u.SetDeletionTimestamp(u.GetDeletionTimestamp()) - del = u.GetDeletionTimestamp() - if del != nil { - t.Errorf("unexpected non-nil deletion timestamp: %v", del) - } - _, ok := u.Object["metadata"] - assert.False(t, ok) - - now := metav1.Now() - u.SetDeletionTimestamp(&now) - assert.Equal(t, now.Unix(), u.GetDeletionTimestamp().Unix()) - u.SetDeletionTimestamp(nil) - metadata := u.Object["metadata"].(map[string]interface{}) - _, ok = metadata["deletionTimestamp"] - assert.False(t, ok) -} - -func TestEmptyCreationTimestampIsOmitted(t *testing.T) { - var u Unstructured - now := metav1.Now() - - // set an initial creationTimestamp and ensure the field exists - u.SetCreationTimestamp(now) - metadata := u.Object["metadata"].(map[string]interface{}) - creationTimestamp, exists := metadata["creationTimestamp"] - if !exists { - t.Fatalf("unexpected missing creationTimestamp") - } - - // set an empty timestamp and ensure the field no longer exists - u.SetCreationTimestamp(metav1.Time{}) - metadata = u.Object["metadata"].(map[string]interface{}) - creationTimestamp, exists = metadata["creationTimestamp"] - if exists { - t.Errorf("unexpected creation timestamp field: %q", creationTimestamp) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/BUILD b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/BUILD deleted file mode 100644 index b7dbe0ad99..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/BUILD +++ /dev/null @@ -1,38 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["validation_test.go"], - embed = [":go_default_library"], - deps = ["//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["validation.go"], - importpath = "k8s.io/apimachinery/pkg/apis/meta/v1/validation", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation_test.go b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation_test.go deleted file mode 100644 index 9766fa7e73..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1/validation/validation_test.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2016 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package validation - -import ( - "strings" - "testing" - - "k8s.io/apimachinery/pkg/util/validation/field" -) - -func TestValidateLabels(t *testing.T) { - successCases := []map[string]string{ - {"simple": "bar"}, - {"now-with-dashes": "bar"}, - {"1-starts-with-num": "bar"}, - {"1234": "bar"}, - {"simple/simple": "bar"}, - {"now-with-dashes/simple": "bar"}, - {"now-with-dashes/now-with-dashes": "bar"}, - {"now.with.dots/simple": "bar"}, - {"now-with.dashes-and.dots/simple": "bar"}, - {"1-num.2-num/3-num": "bar"}, - {"1234/5678": "bar"}, - {"1.2.3.4/5678": "bar"}, - {"UpperCaseAreOK123": "bar"}, - {"goodvalue": "123_-.BaR"}, - } - for i := range successCases { - errs := ValidateLabels(successCases[i], field.NewPath("field")) - if len(errs) != 0 { - t.Errorf("case[%d] expected success, got %#v", i, errs) - } - } - - namePartErrMsg := "name part must consist of" - nameErrMsg := "a qualified name must consist of" - labelErrMsg := "a valid label must be an empty string or consist of" - maxLengthErrMsg := "must be no more than" - - labelNameErrorCases := []struct { - labels map[string]string - expect string - }{ - {map[string]string{"nospecialchars^=@": "bar"}, namePartErrMsg}, - {map[string]string{"cantendwithadash-": "bar"}, namePartErrMsg}, - {map[string]string{"only/one/slash": "bar"}, nameErrMsg}, - {map[string]string{strings.Repeat("a", 254): "bar"}, maxLengthErrMsg}, - } - for i := range labelNameErrorCases { - errs := ValidateLabels(labelNameErrorCases[i].labels, field.NewPath("field")) - if len(errs) != 1 { - t.Errorf("case[%d]: expected failure", i) - } else { - if !strings.Contains(errs[0].Detail, labelNameErrorCases[i].expect) { - t.Errorf("case[%d]: error details do not include %q: %q", i, labelNameErrorCases[i].expect, errs[0].Detail) - } - } - } - - labelValueErrorCases := []struct { - labels map[string]string - expect string - }{ - {map[string]string{"toolongvalue": strings.Repeat("a", 64)}, maxLengthErrMsg}, - {map[string]string{"backslashesinvalue": "some\\bad\\value"}, labelErrMsg}, - {map[string]string{"nocommasallowed": "bad,value"}, labelErrMsg}, - {map[string]string{"strangecharsinvalue": "?#$notsogood"}, labelErrMsg}, - } - for i := range labelValueErrorCases { - errs := ValidateLabels(labelValueErrorCases[i].labels, field.NewPath("field")) - if len(errs) != 1 { - t.Errorf("case[%d]: expected failure", i) - } else { - if !strings.Contains(errs[0].Detail, labelValueErrorCases[i].expect) { - t.Errorf("case[%d]: error details do not include %q: %q", i, labelValueErrorCases[i].expect, errs[0].Detail) - } - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/BUILD b/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/BUILD deleted file mode 100644 index 05f33c5b42..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1/BUILD +++ /dev/null @@ -1,45 +0,0 @@ -load("@io_bazel_rules_go//go:def.bzl", "go_library") - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) - -go_library( - name = "go_default_library", - srcs = [ - "conversion.go", - "deepcopy.go", - "doc.go", - "generated.pb.go", - "register.go", - "types.go", - "types_swagger_doc_generated.go", - "zz_generated.deepcopy.go", - "zz_generated.defaults.go", - ], - importpath = "k8s.io/apimachinery/pkg/apis/meta/v1beta1", - visibility = ["//visibility:public"], - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/conversion/BUILD b/vendor/k8s.io/apimachinery/pkg/conversion/BUILD deleted file mode 100644 index 0d2cee7294..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/conversion/BUILD +++ /dev/null @@ -1,49 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "converter_test.go", - "helper_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/github.com/google/gofuzz:go_default_library", - "//vendor/github.com/spf13/pflag:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/diff:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "converter.go", - "deep_equal.go", - "doc.go", - "helper.go", - ], - importpath = "k8s.io/apimachinery/pkg/conversion", - deps = ["//vendor/k8s.io/apimachinery/third_party/forked/golang/reflect:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/conversion/queryparams:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/conversion/converter_test.go b/vendor/k8s.io/apimachinery/pkg/conversion/converter_test.go deleted file mode 100644 index 5373c80983..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/conversion/converter_test.go +++ /dev/null @@ -1,826 +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 conversion - -import ( - "fmt" - "reflect" - "strconv" - "strings" - "testing" - - "github.com/google/gofuzz" - flag "github.com/spf13/pflag" - - "k8s.io/apimachinery/pkg/util/diff" -) - -var fuzzIters = flag.Int("fuzz-iters", 50, "How many fuzzing iterations to do.") - -// Test a weird version/kind embedding format. -type MyWeirdCustomEmbeddedVersionKindField struct { - ID string `json:"ID,omitempty"` - APIVersion string `json:"myVersionKey,omitempty"` - ObjectKind string `json:"myKindKey,omitempty"` - Z string `json:"Z,omitempty"` - Y uint64 `json:"Y,omitempty"` -} - -type TestType1 struct { - MyWeirdCustomEmbeddedVersionKindField `json:",inline"` - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` - C int8 `json:"C,omitempty"` - D int16 `json:"D,omitempty"` - E int32 `json:"E,omitempty"` - F int64 `json:"F,omitempty"` - G uint `json:"G,omitempty"` - H uint8 `json:"H,omitempty"` - I uint16 `json:"I,omitempty"` - J uint32 `json:"J,omitempty"` - K uint64 `json:"K,omitempty"` - L bool `json:"L,omitempty"` - M map[string]int `json:"M,omitempty"` - N map[string]TestType2 `json:"N,omitempty"` - O *TestType2 `json:"O,omitempty"` - P []TestType2 `json:"Q,omitempty"` -} - -type TestType2 struct { - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` -} - -type ExternalTestType2 struct { - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` -} -type ExternalTestType1 struct { - MyWeirdCustomEmbeddedVersionKindField `json:",inline"` - A string `json:"A,omitempty"` - B int `json:"B,omitempty"` - C int8 `json:"C,omitempty"` - D int16 `json:"D,omitempty"` - E int32 `json:"E,omitempty"` - F int64 `json:"F,omitempty"` - G uint `json:"G,omitempty"` - H uint8 `json:"H,omitempty"` - I uint16 `json:"I,omitempty"` - J uint32 `json:"J,omitempty"` - K uint64 `json:"K,omitempty"` - L bool `json:"L,omitempty"` - M map[string]int `json:"M,omitempty"` - N map[string]ExternalTestType2 `json:"N,omitempty"` - O *ExternalTestType2 `json:"O,omitempty"` - P []ExternalTestType2 `json:"Q,omitempty"` -} - -func testLogger(t *testing.T) DebugLogger { - // We don't set logger to eliminate rubbish logs in tests. - // If you want to switch it, simply switch it to: "return t" - return nil -} - -func TestConverter_byteSlice(t *testing.T) { - c := NewConverter(DefaultNameFunc) - src := []byte{1, 2, 3} - dest := []byte{} - err := c.Convert(&src, &dest, 0, nil) - if err != nil { - t.Fatalf("expected no error") - } - if e, a := src, dest; !reflect.DeepEqual(e, a) { - t.Errorf("expected %#v, got %#v", e, a) - } -} - -func TestConverter_MismatchedTypes(t *testing.T) { - c := NewConverter(DefaultNameFunc) - - err := c.RegisterConversionFunc( - func(in *[]string, out *int, s Scope) error { - if str, err := strconv.Atoi((*in)[0]); err != nil { - return err - } else { - *out = str - return nil - } - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - src := []string{"5"} - var dest *int - err = c.Convert(&src, &dest, 0, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if e, a := 5, *dest; e != a { - t.Errorf("expected %#v, got %#v", e, a) - } -} - -func TestConverter_DefaultConvert(t *testing.T) { - type A struct { - Foo string - Baz int - } - type B struct { - Bar string - Baz int - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - c.nameFunc = func(t reflect.Type) string { return "MyType" } - - // Ensure conversion funcs can call DefaultConvert to get default behavior, - // then fixup remaining fields manually - err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error { - if err := s.DefaultConvert(in, out, IgnoreMissingFields); err != nil { - return err - } - out.Bar = in.Foo - return nil - }) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - - x := A{"hello, intrepid test reader!", 3} - y := B{} - - err = c.Convert(&x, &y, 0, nil) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - if e, a := x.Foo, y.Bar; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := x.Baz, y.Baz; e != a { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestConverter_DeepCopy(t *testing.T) { - type A struct { - Foo *string - Bar []string - Baz interface{} - Qux map[string]string - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - - foo, baz := "foo", "baz" - x := A{ - Foo: &foo, - Bar: []string{"bar"}, - Baz: &baz, - Qux: map[string]string{"qux": "qux"}, - } - y := A{} - - if err := c.Convert(&x, &y, 0, nil); err != nil { - t.Fatalf("unexpected error %v", err) - } - *x.Foo = "foo2" - x.Bar[0] = "bar2" - *x.Baz.(*string) = "baz2" - x.Qux["qux"] = "qux2" - if e, a := *x.Foo, *y.Foo; e == a { - t.Errorf("expected difference between %v and %v", e, a) - } - if e, a := x.Bar, y.Bar; reflect.DeepEqual(e, a) { - t.Errorf("expected difference between %v and %v", e, a) - } - if e, a := *x.Baz.(*string), *y.Baz.(*string); e == a { - t.Errorf("expected difference between %v and %v", e, a) - } - if e, a := x.Qux, y.Qux; reflect.DeepEqual(e, a) { - t.Errorf("expected difference between %v and %v", e, a) - } -} - -func TestConverter_CallsRegisteredFunctions(t *testing.T) { - type A struct { - Foo string - Baz int - } - type B struct { - Bar string - Baz int - } - type C struct{} - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error { - out.Bar = in.Foo - return s.Convert(&in.Baz, &out.Baz, 0) - }) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - err = c.RegisterConversionFunc(func(in *B, out *A, s Scope) error { - out.Foo = in.Bar - return s.Convert(&in.Baz, &out.Baz, 0) - }) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - - x := A{"hello, intrepid test reader!", 3} - y := B{} - - err = c.Convert(&x, &y, 0, nil) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - if e, a := x.Foo, y.Bar; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := x.Baz, y.Baz; e != a { - t.Errorf("expected %v, got %v", e, a) - } - - z := B{"all your test are belong to us", 42} - w := A{} - - err = c.Convert(&z, &w, 0, nil) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - if e, a := z.Bar, w.Foo; e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := z.Baz, w.Baz; e != a { - t.Errorf("expected %v, got %v", e, a) - } - - err = c.RegisterConversionFunc(func(in *A, out *C, s Scope) error { - return fmt.Errorf("C can't store an A, silly") - }) - if err != nil { - t.Fatalf("unexpected error %v", err) - } - err = c.Convert(&A{}, &C{}, 0, nil) - if err == nil { - t.Errorf("unexpected non-error") - } -} - -func TestConverter_IgnoredConversion(t *testing.T) { - type A struct{} - type B struct{} - - count := 0 - c := NewConverter(DefaultNameFunc) - if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error { - count++ - return nil - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - if err := c.RegisterIgnoredConversion(&A{}, &B{}); err != nil { - t.Fatal(err) - } - a := A{} - b := B{} - if err := c.Convert(&a, &b, 0, nil); err != nil { - t.Errorf("%v", err) - } - if count != 0 { - t.Errorf("unexpected number of conversion invocations") - } -} - -func TestConverter_IgnoredConversionNested(t *testing.T) { - type C string - type A struct { - C C - } - type B struct { - C C - } - - c := NewConverter(DefaultNameFunc) - typed := C("") - if err := c.RegisterIgnoredConversion(&typed, &typed); err != nil { - t.Fatal(err) - } - a := A{C: C("test")} - b := B{C: C("other")} - if err := c.Convert(&a, &b, AllowDifferentFieldTypeNames, nil); err != nil { - t.Errorf("%v", err) - } - if b.C != C("other") { - t.Errorf("expected no conversion of field C: %#v", b) - } -} - -func TestConverter_GeneratedConversionOverriden(t *testing.T) { - type A struct{} - type B struct{} - c := NewConverter(DefaultNameFunc) - if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error { - return nil - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - if err := c.RegisterGeneratedConversionFunc(func(in *A, out *B, s Scope) error { - return fmt.Errorf("generated function should be overridden") - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - - a := A{} - b := B{} - if err := c.Convert(&a, &b, 0, nil); err != nil { - t.Errorf("%v", err) - } -} - -func TestConverter_WithConversionOverriden(t *testing.T) { - type A struct{} - type B struct{} - c := NewConverter(DefaultNameFunc) - if err := c.RegisterConversionFunc(func(in *A, out *B, s Scope) error { - return fmt.Errorf("conversion function should be overridden") - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - if err := c.RegisterGeneratedConversionFunc(func(in *A, out *B, s Scope) error { - return fmt.Errorf("generated function should be overridden") - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - - ext := NewConversionFuncs() - ext.Add(func(in *A, out *B, s Scope) error { - return nil - }) - newc := c.WithConversions(ext) - - a := A{} - b := B{} - if err := c.Convert(&a, &b, 0, nil); err == nil || err.Error() != "conversion function should be overridden" { - t.Errorf("unexpected error: %v", err) - } - if err := newc.Convert(&a, &b, 0, nil); err != nil { - t.Errorf("%v", err) - } -} - -func TestConverter_MapsStringArrays(t *testing.T) { - type A struct { - Foo string - Baz int - Other string - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - if err := c.RegisterConversionFunc(func(input *[]string, out *string, s Scope) error { - if len(*input) == 0 { - *out = "" - } - *out = (*input)[0] - return nil - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - - x := map[string][]string{ - "Foo": {"bar"}, - "Baz": {"1"}, - "Other": {"", "test"}, - "other": {"wrong"}, - } - y := A{"test", 2, "something"} - - if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames, nil); err == nil { - t.Error("unexpected non-error") - } - - if err := c.RegisterConversionFunc(func(input *[]string, out *int, s Scope) error { - if len(*input) == 0 { - *out = 0 - } - str := (*input)[0] - i, err := strconv.Atoi(str) - if err != nil { - return err - } - *out = i - return nil - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - - if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames, nil); err != nil { - t.Fatalf("unexpected error %v", err) - } - if !reflect.DeepEqual(y, A{"bar", 1, ""}) { - t.Errorf("unexpected result: %#v", y) - } -} - -func TestConverter_MapsStringArraysWithMappingKey(t *testing.T) { - type A struct { - Foo string `json:"test"` - Baz int - Other string - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - if err := c.RegisterConversionFunc(func(input *[]string, out *string, s Scope) error { - if len(*input) == 0 { - *out = "" - } - *out = (*input)[0] - return nil - }); err != nil { - t.Fatalf("unexpected error %v", err) - } - - x := map[string][]string{ - "Foo": {"bar"}, - "test": {"baz"}, - } - y := A{"", 0, ""} - - if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames|IgnoreMissingFields, &Meta{}); err != nil { - t.Fatalf("unexpected error %v", err) - } - if !reflect.DeepEqual(y, A{"bar", 0, ""}) { - t.Errorf("unexpected result: %#v", y) - } - - mapping := func(key string, sourceTag, destTag reflect.StructTag) (source string, dest string) { - if s := destTag.Get("json"); len(s) > 0 { - return strings.SplitN(s, ",", 2)[0], key - } - return key, key - } - - if err := c.Convert(&x, &y, AllowDifferentFieldTypeNames|IgnoreMissingFields, &Meta{KeyNameMapping: mapping}); err != nil { - t.Fatalf("unexpected error %v", err) - } - if !reflect.DeepEqual(y, A{"baz", 0, ""}) { - t.Errorf("unexpected result: %#v", y) - } -} - -func TestConverter_fuzz(t *testing.T) { - // Use the same types from the scheme test. - table := []struct { - from, to, check interface{} - }{ - {&TestType1{}, &ExternalTestType1{}, &TestType1{}}, - {&ExternalTestType1{}, &TestType1{}, &ExternalTestType1{}}, - } - - f := fuzz.New().NilChance(.5).NumElements(0, 100) - c := NewConverter(DefaultNameFunc) - c.nameFunc = func(t reflect.Type) string { - // Hide the fact that we don't have separate packages for these things. - return map[reflect.Type]string{ - reflect.TypeOf(TestType1{}): "TestType1", - reflect.TypeOf(ExternalTestType1{}): "TestType1", - reflect.TypeOf(TestType2{}): "TestType2", - reflect.TypeOf(ExternalTestType2{}): "TestType2", - }[t] - } - c.Debug = testLogger(t) - - for i, item := range table { - for j := 0; j < *fuzzIters; j++ { - f.Fuzz(item.from) - err := c.Convert(item.from, item.to, 0, nil) - if err != nil { - t.Errorf("(%v, %v): unexpected error: %v", i, j, err) - continue - } - err = c.Convert(item.to, item.check, 0, nil) - if err != nil { - t.Errorf("(%v, %v): unexpected error: %v", i, j, err) - continue - } - if e, a := item.from, item.check; !reflect.DeepEqual(e, a) { - t.Errorf("(%v, %v): unexpected diff: %v", i, j, diff.ObjectDiff(e, a)) - } - } - } -} - -func TestConverter_MapElemAddr(t *testing.T) { - type Foo struct { - A map[int]int - } - type Bar struct { - A map[string]string - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - err := c.RegisterConversionFunc( - func(in *int, out *string, s Scope) error { - *out = fmt.Sprintf("%v", *in) - return nil - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - err = c.RegisterConversionFunc( - func(in *string, out *int, s Scope) error { - if str, err := strconv.Atoi(*in); err != nil { - return err - } else { - *out = str - return nil - } - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - f := fuzz.New().NilChance(0).NumElements(3, 3) - first := Foo{} - second := Bar{} - f.Fuzz(&first) - err = c.Convert(&first, &second, AllowDifferentFieldTypeNames, nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - third := Foo{} - err = c.Convert(&second, &third, AllowDifferentFieldTypeNames, nil) - if e, a := first, third; !reflect.DeepEqual(e, a) { - t.Errorf("Unexpected diff: %v", diff.ObjectDiff(e, a)) - } -} - -func TestConverter_tags(t *testing.T) { - type Foo struct { - A string `test:"foo"` - } - type Bar struct { - A string `test:"bar"` - } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - err := c.RegisterConversionFunc( - func(in *string, out *string, s Scope) error { - if e, a := "foo", s.SrcTag().Get("test"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := "bar", s.DestTag().Get("test"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - return nil - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - err = c.Convert(&Foo{}, &Bar{}, AllowDifferentFieldTypeNames, nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestConverter_meta(t *testing.T) { - type Foo struct{ A string } - type Bar struct{ A string } - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - checks := 0 - err := c.RegisterConversionFunc( - func(in *Foo, out *Bar, s Scope) error { - if s.Meta() == nil { - t.Errorf("Meta did not get passed!") - } - checks++ - s.Convert(&in.A, &out.A, 0) - return nil - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - err = c.RegisterConversionFunc( - func(in *string, out *string, s Scope) error { - if s.Meta() == nil { - t.Errorf("Meta did not get passed a second time!") - } - checks++ - return nil - }, - ) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - err = c.Convert(&Foo{}, &Bar{}, 0, &Meta{}) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if checks != 2 { - t.Errorf("Registered functions did not get called.") - } -} - -func TestConverter_flags(t *testing.T) { - type Foo struct{ A string } - type Bar struct{ A string } - table := []struct { - from, to interface{} - flags FieldMatchingFlags - shouldSucceed bool - }{ - // Check that DestFromSource allows extra fields only in source. - { - from: &struct{ A string }{}, - to: &struct{ A, B string }{}, - flags: DestFromSource, - shouldSucceed: false, - }, { - from: &struct{ A, B string }{}, - to: &struct{ A string }{}, - flags: DestFromSource, - shouldSucceed: true, - }, - - // Check that SourceToDest allows for extra fields only in dest. - { - from: &struct{ A string }{}, - to: &struct{ A, B string }{}, - flags: SourceToDest, - shouldSucceed: true, - }, { - from: &struct{ A, B string }{}, - to: &struct{ A string }{}, - flags: SourceToDest, - shouldSucceed: false, - }, - - // Check that IgnoreMissingFields makes the above failure cases pass. - { - from: &struct{ A string }{}, - to: &struct{ A, B string }{}, - flags: DestFromSource | IgnoreMissingFields, - shouldSucceed: true, - }, { - from: &struct{ A, B string }{}, - to: &struct{ A string }{}, - flags: SourceToDest | IgnoreMissingFields, - shouldSucceed: true, - }, - - // Check that the field type name must match unless - // AllowDifferentFieldTypeNames is specified. - { - from: &struct{ A, B Foo }{}, - to: &struct{ A Bar }{}, - flags: DestFromSource, - shouldSucceed: false, - }, { - from: &struct{ A Foo }{}, - to: &struct{ A, B Bar }{}, - flags: SourceToDest, - shouldSucceed: false, - }, { - from: &struct{ A, B Foo }{}, - to: &struct{ A Bar }{}, - flags: DestFromSource | AllowDifferentFieldTypeNames, - shouldSucceed: true, - }, { - from: &struct{ A Foo }{}, - to: &struct{ A, B Bar }{}, - flags: SourceToDest | AllowDifferentFieldTypeNames, - shouldSucceed: true, - }, - } - f := fuzz.New().NilChance(.5).NumElements(0, 100) - c := NewConverter(DefaultNameFunc) - c.Debug = testLogger(t) - - for i, item := range table { - for j := 0; j < *fuzzIters; j++ { - f.Fuzz(item.from) - err := c.Convert(item.from, item.to, item.flags, nil) - if item.shouldSucceed && err != nil { - t.Errorf("(%v, %v): unexpected error: %v", i, j, err) - continue - } - if !item.shouldSucceed && err == nil { - t.Errorf("(%v, %v): unexpected non-error", i, j) - continue - } - } - } -} - -func TestConverter_FieldRename(t *testing.T) { - type WeirdMeta struct { - Name string - Type string - } - type NameMeta struct { - Name string - } - type TypeMeta struct { - Type string - } - type A struct { - WeirdMeta - } - type B struct { - TypeMeta - NameMeta - } - - c := NewConverter(DefaultNameFunc) - err := c.SetStructFieldCopy(WeirdMeta{}, "WeirdMeta", TypeMeta{}, "TypeMeta") - if err != nil { - t.Fatalf("unexpected error %v", err) - } - err = c.SetStructFieldCopy(WeirdMeta{}, "WeirdMeta", NameMeta{}, "NameMeta") - if err != nil { - t.Fatalf("unexpected error %v", err) - } - err = c.SetStructFieldCopy(TypeMeta{}, "TypeMeta", WeirdMeta{}, "WeirdMeta") - if err != nil { - t.Fatalf("unexpected error %v", err) - } - err = c.SetStructFieldCopy(NameMeta{}, "NameMeta", WeirdMeta{}, "WeirdMeta") - if err != nil { - t.Fatalf("unexpected error %v", err) - } - c.Debug = testLogger(t) - - aVal := &A{ - WeirdMeta: WeirdMeta{ - Name: "Foo", - Type: "Bar", - }, - } - - bVal := &B{ - TypeMeta: TypeMeta{"Bar"}, - NameMeta: NameMeta{"Foo"}, - } - - table := map[string]struct { - from, to, expect interface{} - flags FieldMatchingFlags - }{ - "to": { - aVal, - &B{}, - bVal, - AllowDifferentFieldTypeNames | SourceToDest | IgnoreMissingFields, - }, - "from": { - bVal, - &A{}, - aVal, - AllowDifferentFieldTypeNames | SourceToDest, - }, - "toDestFirst": { - aVal, - &B{}, - bVal, - AllowDifferentFieldTypeNames, - }, - "fromDestFirst": { - bVal, - &A{}, - aVal, - AllowDifferentFieldTypeNames | IgnoreMissingFields, - }, - } - - for name, item := range table { - err := c.Convert(item.from, item.to, item.flags, nil) - if err != nil { - t.Errorf("%v: unexpected error: %v", name, err) - continue - } - if e, a := item.expect, item.to; !reflect.DeepEqual(e, a) { - t.Errorf("%v: unexpected diff: %v", name, diff.ObjectDiff(e, a)) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/conversion/helper_test.go b/vendor/k8s.io/apimachinery/pkg/conversion/helper_test.go deleted file mode 100644 index 8c61a30a88..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/conversion/helper_test.go +++ /dev/null @@ -1,38 +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 conversion - -import "testing" - -func TestInvalidPtrValueKind(t *testing.T) { - var simple interface{} - switch obj := simple.(type) { - default: - _, err := EnforcePtr(obj) - if err == nil { - t.Errorf("Expected error on invalid kind") - } - } -} - -func TestEnforceNilPtr(t *testing.T) { - var nilPtr *struct{} - _, err := EnforcePtr(nilPtr) - if err == nil { - t.Errorf("Expected error on nil pointer") - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/BUILD b/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/BUILD deleted file mode 100644 index 81bacef706..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/BUILD +++ /dev/null @@ -1,39 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_library( - name = "go_default_library", - srcs = [ - "convert.go", - "doc.go", - ], - importpath = "k8s.io/apimachinery/pkg/conversion/queryparams", -) - -go_test( - name = "go_default_xtest", - srcs = ["convert_test.go"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion/queryparams:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert_test.go b/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert_test.go deleted file mode 100644 index b075debf1e..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/conversion/queryparams/convert_test.go +++ /dev/null @@ -1,215 +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 queryparams_test - -import ( - "net/url" - "reflect" - "testing" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/conversion/queryparams" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -type namedString string -type namedBool bool - -type bar struct { - Float1 float32 `json:"float1"` - Float2 float64 `json:"float2"` - Int1 int64 `json:"int1,omitempty"` - Int2 int32 `json:"int2,omitempty"` - Int3 int16 `json:"int3,omitempty"` - Str1 string `json:"str1,omitempty"` - Ignored int - Ignored2 string -} - -func (obj *bar) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } - -type foo struct { - Str string `json:"str"` - Integer int `json:"integer,omitempty"` - Slice []string `json:"slice,omitempty"` - Boolean bool `json:"boolean,omitempty"` - NamedStr namedString `json:"namedStr,omitempty"` - NamedBool namedBool `json:"namedBool,omitempty"` - Foobar bar `json:"foobar,omitempty"` - Testmap map[string]string `json:"testmap,omitempty"` -} - -func (obj *foo) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } - -type baz struct { - Ptr *int `json:"ptr"` - Bptr *bool `json:"bptr,omitempty"` -} - -func (obj *baz) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } - -// childStructs tests some of the types we serialize to query params for log API calls -// notably, the nested time struct -type childStructs struct { - Container string `json:"container,omitempty"` - Follow bool `json:"follow,omitempty"` - Previous bool `json:"previous,omitempty"` - SinceSeconds *int64 `json:"sinceSeconds,omitempty"` - SinceTime *metav1.Time `json:"sinceTime,omitempty"` - EmptyTime *metav1.Time `json:"emptyTime"` - NonPointerTime metav1.Time `json:"nonPointerTime"` -} - -func (obj *childStructs) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } - -func validateResult(t *testing.T, input interface{}, actual, expected url.Values) { - local := url.Values{} - for k, v := range expected { - local[k] = v - } - for k, v := range actual { - if ev, ok := local[k]; !ok || !reflect.DeepEqual(ev, v) { - if !ok { - t.Errorf("%#v: actual value key %s not found in expected map", input, k) - } else { - t.Errorf("%#v: values don't match: actual: %#v, expected: %#v", input, v, ev) - } - } - delete(local, k) - } - if len(local) > 0 { - t.Errorf("%#v: expected map has keys that were not found in actual map: %#v", input, local) - } -} - -func TestConvert(t *testing.T) { - sinceSeconds := int64(123) - sinceTime := metav1.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC) - - tests := []struct { - input interface{} - expected url.Values - }{ - { - input: &foo{ - Str: "hello", - }, - expected: url.Values{"str": {"hello"}}, - }, - { - input: &foo{ - Str: "test string", - Slice: []string{"one", "two", "three"}, - Integer: 234, - Boolean: true, - }, - expected: url.Values{"str": {"test string"}, "slice": {"one", "two", "three"}, "integer": {"234"}, "boolean": {"true"}}, - }, - { - input: &foo{ - Str: "named types", - NamedStr: "value1", - NamedBool: true, - }, - expected: url.Values{"str": {"named types"}, "namedStr": {"value1"}, "namedBool": {"true"}}, - }, - { - input: &foo{ - Str: "don't ignore embedded struct", - Foobar: bar{ - Float1: 5.0, - }, - }, - expected: url.Values{"str": {"don't ignore embedded struct"}, "float1": {"5"}, "float2": {"0"}}, - }, - { - // Ignore untagged fields - input: &bar{ - Float1: 23.5, - Float2: 100.7, - Int1: 1, - Int2: 2, - Int3: 3, - Ignored: 1, - Ignored2: "ignored", - }, - expected: url.Values{"float1": {"23.5"}, "float2": {"100.7"}, "int1": {"1"}, "int2": {"2"}, "int3": {"3"}}, - }, - { - // include fields that are not tagged omitempty - input: &foo{ - NamedStr: "named str", - }, - expected: url.Values{"str": {""}, "namedStr": {"named str"}}, - }, - { - input: &baz{ - Ptr: intp(5), - Bptr: boolp(true), - }, - expected: url.Values{"ptr": {"5"}, "bptr": {"true"}}, - }, - { - input: &baz{ - Bptr: boolp(true), - }, - expected: url.Values{"ptr": {""}, "bptr": {"true"}}, - }, - { - input: &baz{ - Ptr: intp(5), - }, - expected: url.Values{"ptr": {"5"}}, - }, - { - input: &childStructs{ - Container: "mycontainer", - Follow: true, - Previous: true, - SinceSeconds: &sinceSeconds, - SinceTime: &sinceTime, // test a custom marshaller - EmptyTime: nil, // test a nil custom marshaller without omitempty - NonPointerTime: sinceTime, - }, - expected: url.Values{"container": {"mycontainer"}, "follow": {"true"}, "previous": {"true"}, "sinceSeconds": {"123"}, "sinceTime": {"2000-01-01T12:34:56Z"}, "emptyTime": {""}, "nonPointerTime": {"2000-01-01T12:34:56Z"}}, - }, - { - input: &childStructs{ - Container: "mycontainer", - Follow: true, - Previous: true, - SinceSeconds: &sinceSeconds, - SinceTime: nil, // test a nil custom marshaller with omitempty - NonPointerTime: sinceTime, - }, - expected: url.Values{"container": {"mycontainer"}, "follow": {"true"}, "previous": {"true"}, "sinceSeconds": {"123"}, "emptyTime": {""}, "nonPointerTime": {"2000-01-01T12:34:56Z"}}, - }, - } - - for _, test := range tests { - result, err := queryparams.Convert(test.input) - if err != nil { - t.Errorf("Unexpected error while converting %#v: %v", test.input, err) - } - validateResult(t, test.input, result, test.expected) - } -} - -func intp(n int) *int { return &n } - -func boolp(b bool) *bool { return &b } diff --git a/vendor/k8s.io/apimachinery/pkg/fields/BUILD b/vendor/k8s.io/apimachinery/pkg/fields/BUILD deleted file mode 100644 index 383448e0fb..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/fields/BUILD +++ /dev/null @@ -1,41 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "fields_test.go", - "selector_test.go", - ], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "fields.go", - "requirements.go", - "selector.go", - ], - importpath = "k8s.io/apimachinery/pkg/fields", - deps = ["//vendor/k8s.io/apimachinery/pkg/selection:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/fields/fields_test.go b/vendor/k8s.io/apimachinery/pkg/fields/fields_test.go deleted file mode 100644 index 6965be6870..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/fields/fields_test.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fields - -import ( - "testing" -) - -func matches(t *testing.T, ls Set, want string) { - if ls.String() != want { - t.Errorf("Expected '%s', but got '%s'", want, ls.String()) - } -} - -func TestSetString(t *testing.T) { - matches(t, Set{"x": "y"}, "x=y") - matches(t, Set{"foo": "bar"}, "foo=bar") - matches(t, Set{"foo": "bar", "baz": "qup"}, "baz=qup,foo=bar") -} - -func TestFieldHas(t *testing.T) { - fieldHasTests := []struct { - Ls Fields - Key string - Has bool - }{ - {Set{"x": "y"}, "x", true}, - {Set{"x": ""}, "x", true}, - {Set{"x": "y"}, "foo", false}, - } - for _, lh := range fieldHasTests { - if has := lh.Ls.Has(lh.Key); has != lh.Has { - t.Errorf("%#v.Has(%#v) => %v, expected %v", lh.Ls, lh.Key, has, lh.Has) - } - } -} - -func TestFieldGet(t *testing.T) { - ls := Set{"x": "y"} - if ls.Get("x") != "y" { - t.Errorf("Set.Get is broken") - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/fields/selector_test.go b/vendor/k8s.io/apimachinery/pkg/fields/selector_test.go deleted file mode 100644 index 0aa66935cc..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/fields/selector_test.go +++ /dev/null @@ -1,397 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fields - -import ( - "reflect" - "testing" -) - -func TestSplitTerms(t *testing.T) { - testcases := map[string][]string{ - // Simple selectors - `a`: {`a`}, - `a=avalue`: {`a=avalue`}, - `a=avalue,b=bvalue`: {`a=avalue`, `b=bvalue`}, - `a=avalue,b==bvalue,c!=cvalue`: {`a=avalue`, `b==bvalue`, `c!=cvalue`}, - - // Empty terms - ``: nil, - `a=a,`: {`a=a`, ``}, - `,a=a`: {``, `a=a`}, - - // Escaped values - `k=\,,k2=v2`: {`k=\,`, `k2=v2`}, // escaped comma in value - `k=\\,k2=v2`: {`k=\\`, `k2=v2`}, // escaped backslash, unescaped comma - `k=\\\,,k2=v2`: {`k=\\\,`, `k2=v2`}, // escaped backslash and comma - `k=\a\b\`: {`k=\a\b\`}, // non-escape sequences - `k=\`: {`k=\`}, // orphan backslash - - // Multi-byte - `함=수,목=록`: {`함=수`, `목=록`}, - } - - for selector, expectedTerms := range testcases { - if terms := splitTerms(selector); !reflect.DeepEqual(terms, expectedTerms) { - t.Errorf("splitSelectors(`%s`): Expected\n%#v\ngot\n%#v", selector, expectedTerms, terms) - } - } -} - -func TestSplitTerm(t *testing.T) { - testcases := map[string]struct { - lhs string - op string - rhs string - ok bool - }{ - // Simple terms - `a=value`: {lhs: `a`, op: `=`, rhs: `value`, ok: true}, - `b==value`: {lhs: `b`, op: `==`, rhs: `value`, ok: true}, - `c!=value`: {lhs: `c`, op: `!=`, rhs: `value`, ok: true}, - - // Empty or invalid terms - ``: {lhs: ``, op: ``, rhs: ``, ok: false}, - `a`: {lhs: ``, op: ``, rhs: ``, ok: false}, - - // Escaped values - `k=\,`: {lhs: `k`, op: `=`, rhs: `\,`, ok: true}, - `k=\=`: {lhs: `k`, op: `=`, rhs: `\=`, ok: true}, - `k=\\\a\b\=\,\`: {lhs: `k`, op: `=`, rhs: `\\\a\b\=\,\`, ok: true}, - - // Multi-byte - `함=수`: {lhs: `함`, op: `=`, rhs: `수`, ok: true}, - } - - for term, expected := range testcases { - lhs, op, rhs, ok := splitTerm(term) - if lhs != expected.lhs || op != expected.op || rhs != expected.rhs || ok != expected.ok { - t.Errorf( - "splitTerm(`%s`): Expected\n%s,%s,%s,%v\nGot\n%s,%s,%s,%v", - term, - expected.lhs, expected.op, expected.rhs, expected.ok, - lhs, op, rhs, ok, - ) - } - } -} - -func TestEscapeValue(t *testing.T) { - // map values to their normalized escaped values - testcases := map[string]string{ - ``: ``, - `a`: `a`, - `=`: `\=`, - `,`: `\,`, - `\`: `\\`, - `\=\,\`: `\\\=\\\,\\`, - } - - for unescapedValue, escapedValue := range testcases { - actualEscaped := EscapeValue(unescapedValue) - if actualEscaped != escapedValue { - t.Errorf("EscapeValue(%s): expected %s, got %s", unescapedValue, escapedValue, actualEscaped) - } - - actualUnescaped, err := UnescapeValue(escapedValue) - if err != nil { - t.Errorf("UnescapeValue(%s): unexpected error %v", escapedValue, err) - } - if actualUnescaped != unescapedValue { - t.Errorf("UnescapeValue(%s): expected %s, got %s", escapedValue, unescapedValue, actualUnescaped) - } - } - - // test invalid escape sequences - invalidTestcases := []string{ - `\`, // orphan slash is invalid - `\\\`, // orphan slash is invalid - `\a`, // unrecognized escape sequence is invalid - } - for _, invalidValue := range invalidTestcases { - _, err := UnescapeValue(invalidValue) - if _, ok := err.(InvalidEscapeSequence); !ok || err == nil { - t.Errorf("UnescapeValue(%s): expected invalid escape sequence error, got %#v", invalidValue, err) - } - } -} - -func TestSelectorParse(t *testing.T) { - testGoodStrings := []string{ - "x=a,y=b,z=c", - "", - "x!=a,y=b", - `x=a||y\=b`, - `x=a\=\=b`, - } - testBadStrings := []string{ - "x=a||y=b", - "x==a==b", - "x=a,b", - "x in (a)", - "x in (a,b,c)", - "x", - } - for _, test := range testGoodStrings { - lq, err := ParseSelector(test) - if err != nil { - t.Errorf("%v: error %v (%#v)\n", test, err, err) - } - if test != lq.String() { - t.Errorf("%v restring gave: %v\n", test, lq.String()) - } - } - for _, test := range testBadStrings { - _, err := ParseSelector(test) - if err == nil { - t.Errorf("%v: did not get expected error\n", test) - } - } -} - -func TestDeterministicParse(t *testing.T) { - s1, err := ParseSelector("x=a,a=x") - s2, err2 := ParseSelector("a=x,x=a") - if err != nil || err2 != nil { - t.Errorf("Unexpected parse error") - } - if s1.String() != s2.String() { - t.Errorf("Non-deterministic parse") - } -} - -func expectMatch(t *testing.T, selector string, ls Set) { - lq, err := ParseSelector(selector) - if err != nil { - t.Errorf("Unable to parse %v as a selector\n", selector) - return - } - if !lq.Matches(ls) { - t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls) - } -} - -func expectNoMatch(t *testing.T, selector string, ls Set) { - lq, err := ParseSelector(selector) - if err != nil { - t.Errorf("Unable to parse %v as a selector\n", selector) - return - } - if lq.Matches(ls) { - t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls) - } -} - -func TestEverything(t *testing.T) { - if !Everything().Matches(Set{"x": "y"}) { - t.Errorf("Nil selector didn't match") - } - if !Everything().Empty() { - t.Errorf("Everything was not empty") - } -} - -func TestSelectorMatches(t *testing.T) { - expectMatch(t, "", Set{"x": "y"}) - expectMatch(t, "x=y", Set{"x": "y"}) - expectMatch(t, "x=y,z=w", Set{"x": "y", "z": "w"}) - expectMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "a"}) - expectMatch(t, "notin=in", Set{"notin": "in"}) // in and notin in exactMatch - expectNoMatch(t, "x=y", Set{"x": "z"}) - expectNoMatch(t, "x=y,z=w", Set{"x": "w", "z": "w"}) - expectNoMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "w"}) - - fieldset := Set{ - "foo": "bar", - "baz": "blah", - "complex": `=value\,\`, - } - expectMatch(t, "foo=bar", fieldset) - expectMatch(t, "baz=blah", fieldset) - expectMatch(t, "foo=bar,baz=blah", fieldset) - expectMatch(t, `foo=bar,baz=blah,complex=\=value\\\,\\`, fieldset) - expectNoMatch(t, "foo=blah", fieldset) - expectNoMatch(t, "baz=bar", fieldset) - expectNoMatch(t, "foo=bar,foobar=bar,baz=blah", fieldset) -} - -func TestOneTermEqualSelector(t *testing.T) { - if !OneTermEqualSelector("x", "y").Matches(Set{"x": "y"}) { - t.Errorf("No match when match expected.") - } - if OneTermEqualSelector("x", "y").Matches(Set{"x": "z"}) { - t.Errorf("Match when none expected.") - } -} - -func expectMatchDirect(t *testing.T, selector, ls Set) { - if !SelectorFromSet(selector).Matches(ls) { - t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls) - } -} - -func expectNoMatchDirect(t *testing.T, selector, ls Set) { - if SelectorFromSet(selector).Matches(ls) { - t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls) - } -} - -func TestSetMatches(t *testing.T) { - labelset := Set{ - "foo": "bar", - "baz": "blah", - } - expectMatchDirect(t, Set{}, labelset) - expectMatchDirect(t, Set{"foo": "bar"}, labelset) - expectMatchDirect(t, Set{"baz": "blah"}, labelset) - expectMatchDirect(t, Set{"foo": "bar", "baz": "blah"}, labelset) - expectNoMatchDirect(t, Set{"foo": "=blah"}, labelset) - expectNoMatchDirect(t, Set{"baz": "=bar"}, labelset) - expectNoMatchDirect(t, Set{"foo": "=bar", "foobar": "bar", "baz": "blah"}, labelset) -} - -func TestNilMapIsValid(t *testing.T) { - selector := Set(nil).AsSelector() - if selector == nil { - t.Errorf("Selector for nil set should be Everything") - } - if !selector.Empty() { - t.Errorf("Selector for nil set should be Empty") - } -} - -func TestSetIsEmpty(t *testing.T) { - if !(Set{}).AsSelector().Empty() { - t.Errorf("Empty set should be empty") - } - if !(andTerm(nil)).Empty() { - t.Errorf("Nil andTerm should be empty") - } - if (&hasTerm{}).Empty() { - t.Errorf("hasTerm should not be empty") - } - if (&notHasTerm{}).Empty() { - t.Errorf("notHasTerm should not be empty") - } - if !(andTerm{andTerm{}}).Empty() { - t.Errorf("Nested andTerm should be empty") - } - if (andTerm{&hasTerm{"a", "b"}}).Empty() { - t.Errorf("Nested andTerm should not be empty") - } -} - -func TestRequiresExactMatch(t *testing.T) { - testCases := map[string]struct { - S Selector - Label string - Value string - Found bool - }{ - "empty set": {Set{}.AsSelector(), "test", "", false}, - "empty hasTerm": {&hasTerm{}, "test", "", false}, - "skipped hasTerm": {&hasTerm{"a", "b"}, "test", "", false}, - "valid hasTerm": {&hasTerm{"test", "b"}, "test", "b", true}, - "valid hasTerm no value": {&hasTerm{"test", ""}, "test", "", true}, - "valid notHasTerm": {&notHasTerm{"test", "b"}, "test", "", false}, - "valid notHasTerm no value": {&notHasTerm{"test", ""}, "test", "", false}, - "nil andTerm": {andTerm(nil), "test", "", false}, - "empty andTerm": {andTerm{}, "test", "", false}, - "nested andTerm": {andTerm{andTerm{}}, "test", "", false}, - "nested andTerm matches": {andTerm{&hasTerm{"test", "b"}}, "test", "b", true}, - "andTerm with non-match": {andTerm{&hasTerm{}, &hasTerm{"test", "b"}}, "test", "b", true}, - } - for k, v := range testCases { - value, found := v.S.RequiresExactMatch(v.Label) - if value != v.Value { - t.Errorf("%s: expected value %s, got %s", k, v.Value, value) - } - if found != v.Found { - t.Errorf("%s: expected found %t, got %t", k, v.Found, found) - } - } -} - -func TestTransform(t *testing.T) { - testCases := []struct { - name string - selector string - transform func(field, value string) (string, string, error) - result string - isEmpty bool - }{ - { - name: "empty selector", - selector: "", - transform: func(field, value string) (string, string, error) { return field, value, nil }, - result: "", - isEmpty: true, - }, - { - name: "no-op transform", - selector: "a=b,c=d", - transform: func(field, value string) (string, string, error) { return field, value, nil }, - result: "a=b,c=d", - isEmpty: false, - }, - { - name: "transform one field", - selector: "a=b,c=d", - transform: func(field, value string) (string, string, error) { - if field == "a" { - return "e", "f", nil - } - return field, value, nil - }, - result: "e=f,c=d", - isEmpty: false, - }, - { - name: "remove field to make empty", - selector: "a=b", - transform: func(field, value string) (string, string, error) { return "", "", nil }, - result: "", - isEmpty: true, - }, - { - name: "remove only one field", - selector: "a=b,c=d,e=f", - transform: func(field, value string) (string, string, error) { - if field == "c" { - return "", "", nil - } - return field, value, nil - }, - result: "a=b,e=f", - isEmpty: false, - }, - } - - for i, tc := range testCases { - result, err := ParseAndTransformSelector(tc.selector, tc.transform) - if err != nil { - t.Errorf("[%d] unexpected error during Transform: %v", i, err) - } - if result.Empty() != tc.isEmpty { - t.Errorf("[%d] expected empty: %t, got: %t", i, tc.isEmpty, result.Empty()) - } - if result.String() != tc.result { - t.Errorf("[%d] unexpected result: %s", i, result.String()) - } - } - -} diff --git a/vendor/k8s.io/apimachinery/pkg/labels/BUILD b/vendor/k8s.io/apimachinery/pkg/labels/BUILD deleted file mode 100644 index a78764f72e..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/labels/BUILD +++ /dev/null @@ -1,50 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "labels_test.go", - "selector_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/selection:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "labels.go", - "selector.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/apimachinery/pkg/labels", - deps = [ - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/selection:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/labels/labels_test.go b/vendor/k8s.io/apimachinery/pkg/labels/labels_test.go deleted file mode 100644 index 2d4d761bc2..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/labels/labels_test.go +++ /dev/null @@ -1,231 +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 labels - -import ( - "testing" -) - -func matches(t *testing.T, ls Set, want string) { - if ls.String() != want { - t.Errorf("Expected '%s', but got '%s'", want, ls.String()) - } -} - -func TestSetString(t *testing.T) { - matches(t, Set{"x": "y"}, "x=y") - matches(t, Set{"foo": "bar"}, "foo=bar") - matches(t, Set{"foo": "bar", "baz": "qup"}, "baz=qup,foo=bar") - - // TODO: Make our label representation robust enough to handle labels - // with ",=!" characters in their names. -} - -func TestLabelHas(t *testing.T) { - labelHasTests := []struct { - Ls Labels - Key string - Has bool - }{ - {Set{"x": "y"}, "x", true}, - {Set{"x": ""}, "x", true}, - {Set{"x": "y"}, "foo", false}, - } - for _, lh := range labelHasTests { - if has := lh.Ls.Has(lh.Key); has != lh.Has { - t.Errorf("%#v.Has(%#v) => %v, expected %v", lh.Ls, lh.Key, has, lh.Has) - } - } -} - -func TestLabelGet(t *testing.T) { - ls := Set{"x": "y"} - if ls.Get("x") != "y" { - t.Errorf("Set.Get is broken") - } -} - -func TestLabelConflict(t *testing.T) { - tests := []struct { - labels1 map[string]string - labels2 map[string]string - conflict bool - }{ - { - labels1: map[string]string{}, - labels2: map[string]string{}, - conflict: false, - }, - { - labels1: map[string]string{"env": "test"}, - labels2: map[string]string{"infra": "true"}, - conflict: false, - }, - { - labels1: map[string]string{"env": "test"}, - labels2: map[string]string{"infra": "true", "env": "test"}, - conflict: false, - }, - { - labels1: map[string]string{"env": "test"}, - labels2: map[string]string{"env": "dev"}, - conflict: true, - }, - { - labels1: map[string]string{"env": "test", "infra": "false"}, - labels2: map[string]string{"infra": "true", "color": "blue"}, - conflict: true, - }, - } - for _, test := range tests { - conflict := Conflicts(Set(test.labels1), Set(test.labels2)) - if conflict != test.conflict { - t.Errorf("expected: %v but got: %v", test.conflict, conflict) - } - } -} - -func TestLabelMerge(t *testing.T) { - tests := []struct { - labels1 map[string]string - labels2 map[string]string - mergedLabels map[string]string - }{ - { - labels1: map[string]string{}, - labels2: map[string]string{}, - mergedLabels: map[string]string{}, - }, - { - labels1: map[string]string{"infra": "true"}, - labels2: map[string]string{}, - mergedLabels: map[string]string{"infra": "true"}, - }, - { - labels1: map[string]string{"infra": "true"}, - labels2: map[string]string{"env": "test", "color": "blue"}, - mergedLabels: map[string]string{"infra": "true", "env": "test", "color": "blue"}, - }, - } - for _, test := range tests { - mergedLabels := Merge(Set(test.labels1), Set(test.labels2)) - if !Equals(mergedLabels, test.mergedLabels) { - t.Errorf("expected: %v but got: %v", test.mergedLabels, mergedLabels) - } - } -} - -func TestLabelSelectorParse(t *testing.T) { - tests := []struct { - selector string - labels map[string]string - valid bool - }{ - { - selector: "", - labels: map[string]string{}, - valid: true, - }, - { - selector: "x=a", - labels: map[string]string{"x": "a"}, - valid: true, - }, - { - selector: "x=a,y=b,z=c", - labels: map[string]string{"x": "a", "y": "b", "z": "c"}, - valid: true, - }, - { - selector: " x = a , y = b , z = c ", - labels: map[string]string{"x": "a", "y": "b", "z": "c"}, - valid: true, - }, - { - selector: "color=green,env=test,service=front", - labels: map[string]string{"color": "green", "env": "test", "service": "front"}, - valid: true, - }, - { - selector: "color=green, env=test, service=front", - labels: map[string]string{"color": "green", "env": "test", "service": "front"}, - valid: true, - }, - { - selector: ",", - labels: map[string]string{}, - valid: false, - }, - { - selector: "x", - labels: map[string]string{}, - valid: false, - }, - { - selector: "x,y", - labels: map[string]string{}, - valid: false, - }, - { - selector: "x=$y", - labels: map[string]string{}, - valid: false, - }, - { - selector: "x!=y", - labels: map[string]string{}, - valid: false, - }, - { - selector: "x==y", - labels: map[string]string{}, - valid: false, - }, - { - selector: "x=a||y=b", - labels: map[string]string{}, - valid: false, - }, - { - selector: "x in (y)", - labels: map[string]string{}, - valid: false, - }, - { - selector: "x notin (y)", - labels: map[string]string{}, - valid: false, - }, - { - selector: "x y", - labels: map[string]string{}, - valid: false, - }, - } - for _, test := range tests { - labels, err := ConvertSelectorToLabelsMap(test.selector) - if test.valid && err != nil { - t.Errorf("selector: %s, expected no error but got: %s", test.selector, err) - } else if !test.valid && err == nil { - t.Errorf("selector: %s, expected an error", test.selector) - } - - if !Equals(Set(labels), test.labels) { - t.Errorf("expected: %s but got: %s", test.labels, labels) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/labels/selector_test.go b/vendor/k8s.io/apimachinery/pkg/labels/selector_test.go deleted file mode 100644 index 995317bd17..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/labels/selector_test.go +++ /dev/null @@ -1,575 +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 labels - -import ( - "reflect" - "strings" - "testing" - - "k8s.io/apimachinery/pkg/selection" - "k8s.io/apimachinery/pkg/util/sets" -) - -func TestSelectorParse(t *testing.T) { - testGoodStrings := []string{ - "x=a,y=b,z=c", - "", - "x!=a,y=b", - "x=", - "x= ", - "x=,z= ", - "x= ,z= ", - "!x", - "x>1", - "x>1,z<5", - } - testBadStrings := []string{ - "x=a||y=b", - "x==a==b", - "!x=a", - "x<a", - } - for _, test := range testGoodStrings { - lq, err := Parse(test) - if err != nil { - t.Errorf("%v: error %v (%#v)\n", test, err, err) - } - if strings.Replace(test, " ", "", -1) != lq.String() { - t.Errorf("%v restring gave: %v\n", test, lq.String()) - } - } - for _, test := range testBadStrings { - _, err := Parse(test) - if err == nil { - t.Errorf("%v: did not get expected error\n", test) - } - } -} - -func TestDeterministicParse(t *testing.T) { - s1, err := Parse("x=a,a=x") - s2, err2 := Parse("a=x,x=a") - if err != nil || err2 != nil { - t.Errorf("Unexpected parse error") - } - if s1.String() != s2.String() { - t.Errorf("Non-deterministic parse") - } -} - -func expectMatch(t *testing.T, selector string, ls Set) { - lq, err := Parse(selector) - if err != nil { - t.Errorf("Unable to parse %v as a selector\n", selector) - return - } - if !lq.Matches(ls) { - t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls) - } -} - -func expectNoMatch(t *testing.T, selector string, ls Set) { - lq, err := Parse(selector) - if err != nil { - t.Errorf("Unable to parse %v as a selector\n", selector) - return - } - if lq.Matches(ls) { - t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls) - } -} - -func TestEverything(t *testing.T) { - if !Everything().Matches(Set{"x": "y"}) { - t.Errorf("Nil selector didn't match") - } - if !Everything().Empty() { - t.Errorf("Everything was not empty") - } -} - -func TestSelectorMatches(t *testing.T) { - expectMatch(t, "", Set{"x": "y"}) - expectMatch(t, "x=y", Set{"x": "y"}) - expectMatch(t, "x=y,z=w", Set{"x": "y", "z": "w"}) - expectMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "a"}) - expectMatch(t, "notin=in", Set{"notin": "in"}) // in and notin in exactMatch - expectMatch(t, "x", Set{"x": "z"}) - expectMatch(t, "!x", Set{"y": "z"}) - expectMatch(t, "x>1", Set{"x": "2"}) - expectMatch(t, "x<1", Set{"x": "0"}) - expectNoMatch(t, "x=z", Set{}) - expectNoMatch(t, "x=y", Set{"x": "z"}) - expectNoMatch(t, "x=y,z=w", Set{"x": "w", "z": "w"}) - expectNoMatch(t, "x!=y,z!=w", Set{"x": "z", "z": "w"}) - expectNoMatch(t, "x", Set{"y": "z"}) - expectNoMatch(t, "!x", Set{"x": "z"}) - expectNoMatch(t, "x>1", Set{"x": "0"}) - expectNoMatch(t, "x<1", Set{"x": "2"}) - - labelset := Set{ - "foo": "bar", - "baz": "blah", - } - expectMatch(t, "foo=bar", labelset) - expectMatch(t, "baz=blah", labelset) - expectMatch(t, "foo=bar,baz=blah", labelset) - expectNoMatch(t, "foo=blah", labelset) - expectNoMatch(t, "baz=bar", labelset) - expectNoMatch(t, "foo=bar,foobar=bar,baz=blah", labelset) -} - -func expectMatchDirect(t *testing.T, selector, ls Set) { - if !SelectorFromSet(selector).Matches(ls) { - t.Errorf("Wanted %s to match '%s', but it did not.\n", selector, ls) - } -} - -func expectNoMatchDirect(t *testing.T, selector, ls Set) { - if SelectorFromSet(selector).Matches(ls) { - t.Errorf("Wanted '%s' to not match '%s', but it did.", selector, ls) - } -} - -func TestSetMatches(t *testing.T) { - labelset := Set{ - "foo": "bar", - "baz": "blah", - } - expectMatchDirect(t, Set{}, labelset) - expectMatchDirect(t, Set{"foo": "bar"}, labelset) - expectMatchDirect(t, Set{"baz": "blah"}, labelset) - expectMatchDirect(t, Set{"foo": "bar", "baz": "blah"}, labelset) - - //TODO: bad values not handled for the moment in SelectorFromSet - //expectNoMatchDirect(t, Set{"foo": "=blah"}, labelset) - //expectNoMatchDirect(t, Set{"baz": "=bar"}, labelset) - //expectNoMatchDirect(t, Set{"foo": "=bar", "foobar": "bar", "baz": "blah"}, labelset) -} - -func TestNilMapIsValid(t *testing.T) { - selector := Set(nil).AsSelector() - if selector == nil { - t.Errorf("Selector for nil set should be Everything") - } - if !selector.Empty() { - t.Errorf("Selector for nil set should be Empty") - } -} - -func TestSetIsEmpty(t *testing.T) { - if !(Set{}).AsSelector().Empty() { - t.Errorf("Empty set should be empty") - } - if !(NewSelector()).Empty() { - t.Errorf("Nil Selector should be empty") - } -} - -func TestLexer(t *testing.T) { - testcases := []struct { - s string - t Token - }{ - {"", EndOfStringToken}, - {",", CommaToken}, - {"notin", NotInToken}, - {"in", InToken}, - {"=", EqualsToken}, - {"==", DoubleEqualsToken}, - {">", GreaterThanToken}, - {"<", LessThanToken}, - //Note that Lex returns the longest valid token found - {"!", DoesNotExistToken}, - {"!=", NotEqualsToken}, - {"(", OpenParToken}, - {")", ClosedParToken}, - //Non-"special" characters are considered part of an identifier - {"~", IdentifierToken}, - {"||", IdentifierToken}, - } - for _, v := range testcases { - l := &Lexer{s: v.s, pos: 0} - token, lit := l.Lex() - if token != v.t { - t.Errorf("Got %d it should be %d for '%s'", token, v.t, v.s) - } - if v.t != ErrorToken && lit != v.s { - t.Errorf("Got '%s' it should be '%s'", lit, v.s) - } - } -} - -func min(l, r int) (m int) { - m = r - if l < r { - m = l - } - return m -} - -func TestLexerSequence(t *testing.T) { - testcases := []struct { - s string - t []Token - }{ - {"key in ( value )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, ClosedParToken}}, - {"key notin ( value )", []Token{IdentifierToken, NotInToken, OpenParToken, IdentifierToken, ClosedParToken}}, - {"key in ( value1, value2 )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, CommaToken, IdentifierToken, ClosedParToken}}, - {"key", []Token{IdentifierToken}}, - {"!key", []Token{DoesNotExistToken, IdentifierToken}}, - {"()", []Token{OpenParToken, ClosedParToken}}, - {"x in (),y", []Token{IdentifierToken, InToken, OpenParToken, ClosedParToken, CommaToken, IdentifierToken}}, - {"== != (), = notin", []Token{DoubleEqualsToken, NotEqualsToken, OpenParToken, ClosedParToken, CommaToken, EqualsToken, NotInToken}}, - {"key>2", []Token{IdentifierToken, GreaterThanToken, IdentifierToken}}, - {"key<1", []Token{IdentifierToken, LessThanToken, IdentifierToken}}, - } - for _, v := range testcases { - var literals []string - var tokens []Token - l := &Lexer{s: v.s, pos: 0} - for { - token, lit := l.Lex() - if token == EndOfStringToken { - break - } - tokens = append(tokens, token) - literals = append(literals, lit) - } - if len(tokens) != len(v.t) { - t.Errorf("Bad number of tokens for '%s %d, %d", v.s, len(tokens), len(v.t)) - } - for i := 0; i < min(len(tokens), len(v.t)); i++ { - if tokens[i] != v.t[i] { - t.Errorf("Test '%s': Mismatching in token type found '%v' it should be '%v'", v.s, tokens[i], v.t[i]) - } - } - } -} -func TestParserLookahead(t *testing.T) { - testcases := []struct { - s string - t []Token - }{ - {"key in ( value )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, ClosedParToken, EndOfStringToken}}, - {"key notin ( value )", []Token{IdentifierToken, NotInToken, OpenParToken, IdentifierToken, ClosedParToken, EndOfStringToken}}, - {"key in ( value1, value2 )", []Token{IdentifierToken, InToken, OpenParToken, IdentifierToken, CommaToken, IdentifierToken, ClosedParToken, EndOfStringToken}}, - {"key", []Token{IdentifierToken, EndOfStringToken}}, - {"!key", []Token{DoesNotExistToken, IdentifierToken, EndOfStringToken}}, - {"()", []Token{OpenParToken, ClosedParToken, EndOfStringToken}}, - {"", []Token{EndOfStringToken}}, - {"x in (),y", []Token{IdentifierToken, InToken, OpenParToken, ClosedParToken, CommaToken, IdentifierToken, EndOfStringToken}}, - {"== != (), = notin", []Token{DoubleEqualsToken, NotEqualsToken, OpenParToken, ClosedParToken, CommaToken, EqualsToken, NotInToken, EndOfStringToken}}, - {"key>2", []Token{IdentifierToken, GreaterThanToken, IdentifierToken, EndOfStringToken}}, - {"key<1", []Token{IdentifierToken, LessThanToken, IdentifierToken, EndOfStringToken}}, - } - for _, v := range testcases { - p := &Parser{l: &Lexer{s: v.s, pos: 0}, position: 0} - p.scan() - if len(p.scannedItems) != len(v.t) { - t.Errorf("Expected %d items found %d", len(v.t), len(p.scannedItems)) - } - for { - token, lit := p.lookahead(KeyAndOperator) - - token2, lit2 := p.consume(KeyAndOperator) - if token == EndOfStringToken { - break - } - if token != token2 || lit != lit2 { - t.Errorf("Bad values") - } - } - } -} - -func TestRequirementConstructor(t *testing.T) { - requirementConstructorTests := []struct { - Key string - Op selection.Operator - Vals sets.String - Success bool - }{ - {"x", selection.In, nil, false}, - {"x", selection.NotIn, sets.NewString(), false}, - {"x", selection.In, sets.NewString("foo"), true}, - {"x", selection.NotIn, sets.NewString("foo"), true}, - {"x", selection.Exists, nil, true}, - {"x", selection.DoesNotExist, nil, true}, - {"1foo", selection.In, sets.NewString("bar"), true}, - {"1234", selection.In, sets.NewString("bar"), true}, - {"y", selection.GreaterThan, sets.NewString("1"), true}, - {"z", selection.LessThan, sets.NewString("6"), true}, - {"foo", selection.GreaterThan, sets.NewString("bar"), false}, - {"barz", selection.LessThan, sets.NewString("blah"), false}, - {strings.Repeat("a", 254), selection.Exists, nil, false}, //breaks DNS rule that len(key) <= 253 - } - for _, rc := range requirementConstructorTests { - if _, err := NewRequirement(rc.Key, rc.Op, rc.Vals.List()); err == nil && !rc.Success { - t.Errorf("expected error with key:%#v op:%v vals:%v, got no error", rc.Key, rc.Op, rc.Vals) - } else if err != nil && rc.Success { - t.Errorf("expected no error with key:%#v op:%v vals:%v, got:%v", rc.Key, rc.Op, rc.Vals, err) - } - } -} - -func TestToString(t *testing.T) { - var req Requirement - toStringTests := []struct { - In *internalSelector - Out string - Valid bool - }{ - - {&internalSelector{ - getRequirement("x", selection.In, sets.NewString("abc", "def"), t), - getRequirement("y", selection.NotIn, sets.NewString("jkl"), t), - getRequirement("z", selection.Exists, nil, t)}, - "x in (abc,def),y notin (jkl),z", true}, - {&internalSelector{ - getRequirement("x", selection.NotIn, sets.NewString("abc", "def"), t), - getRequirement("y", selection.NotEquals, sets.NewString("jkl"), t), - getRequirement("z", selection.DoesNotExist, nil, t)}, - "x notin (abc,def),y!=jkl,!z", true}, - {&internalSelector{ - getRequirement("x", selection.In, sets.NewString("abc", "def"), t), - req}, // adding empty req for the trailing ',' - "x in (abc,def),", false}, - {&internalSelector{ - getRequirement("x", selection.NotIn, sets.NewString("abc"), t), - getRequirement("y", selection.In, sets.NewString("jkl", "mno"), t), - getRequirement("z", selection.NotIn, sets.NewString(""), t)}, - "x notin (abc),y in (jkl,mno),z notin ()", true}, - {&internalSelector{ - getRequirement("x", selection.Equals, sets.NewString("abc"), t), - getRequirement("y", selection.DoubleEquals, sets.NewString("jkl"), t), - getRequirement("z", selection.NotEquals, sets.NewString("a"), t), - getRequirement("z", selection.Exists, nil, t)}, - "x=abc,y==jkl,z!=a,z", true}, - {&internalSelector{ - getRequirement("x", selection.GreaterThan, sets.NewString("2"), t), - getRequirement("y", selection.LessThan, sets.NewString("8"), t), - getRequirement("z", selection.Exists, nil, t)}, - "x>2,y<8,z", true}, - } - for _, ts := range toStringTests { - if out := ts.In.String(); out == "" && ts.Valid { - t.Errorf("%#v.String() => '%v' expected no error", ts.In, out) - } else if out != ts.Out { - t.Errorf("%#v.String() => '%v' want '%v'", ts.In, out, ts.Out) - } - } -} - -func TestRequirementSelectorMatching(t *testing.T) { - var req Requirement - labelSelectorMatchingTests := []struct { - Set Set - Sel Selector - Match bool - }{ - {Set{"x": "foo", "y": "baz"}, &internalSelector{ - req, - }, false}, - {Set{"x": "foo", "y": "baz"}, &internalSelector{ - getRequirement("x", selection.In, sets.NewString("foo"), t), - getRequirement("y", selection.NotIn, sets.NewString("alpha"), t), - }, true}, - {Set{"x": "foo", "y": "baz"}, &internalSelector{ - getRequirement("x", selection.In, sets.NewString("foo"), t), - getRequirement("y", selection.In, sets.NewString("alpha"), t), - }, false}, - {Set{"y": ""}, &internalSelector{ - getRequirement("x", selection.NotIn, sets.NewString(""), t), - getRequirement("y", selection.Exists, nil, t), - }, true}, - {Set{"y": ""}, &internalSelector{ - getRequirement("x", selection.DoesNotExist, nil, t), - getRequirement("y", selection.Exists, nil, t), - }, true}, - {Set{"y": ""}, &internalSelector{ - getRequirement("x", selection.NotIn, sets.NewString(""), t), - getRequirement("y", selection.DoesNotExist, nil, t), - }, false}, - {Set{"y": "baz"}, &internalSelector{ - getRequirement("x", selection.In, sets.NewString(""), t), - }, false}, - {Set{"z": "2"}, &internalSelector{ - getRequirement("z", selection.GreaterThan, sets.NewString("1"), t), - }, true}, - {Set{"z": "v2"}, &internalSelector{ - getRequirement("z", selection.GreaterThan, sets.NewString("1"), t), - }, false}, - } - for _, lsm := range labelSelectorMatchingTests { - if match := lsm.Sel.Matches(lsm.Set); match != lsm.Match { - t.Errorf("%+v.Matches(%#v) => %v, want %v", lsm.Sel, lsm.Set, match, lsm.Match) - } - } -} - -func TestSetSelectorParser(t *testing.T) { - setSelectorParserTests := []struct { - In string - Out Selector - Match bool - Valid bool - }{ - {"", NewSelector(), true, true}, - {"\rx", internalSelector{ - getRequirement("x", selection.Exists, nil, t), - }, true, true}, - {"this-is-a-dns.domain.com/key-with-dash", internalSelector{ - getRequirement("this-is-a-dns.domain.com/key-with-dash", selection.Exists, nil, t), - }, true, true}, - {"this-is-another-dns.domain.com/key-with-dash in (so,what)", internalSelector{ - getRequirement("this-is-another-dns.domain.com/key-with-dash", selection.In, sets.NewString("so", "what"), t), - }, true, true}, - {"0.1.2.domain/99 notin (10.10.100.1, tick.tack.clock)", internalSelector{ - getRequirement("0.1.2.domain/99", selection.NotIn, sets.NewString("10.10.100.1", "tick.tack.clock"), t), - }, true, true}, - {"foo in (abc)", internalSelector{ - getRequirement("foo", selection.In, sets.NewString("abc"), t), - }, true, true}, - {"x notin\n (abc)", internalSelector{ - getRequirement("x", selection.NotIn, sets.NewString("abc"), t), - }, true, true}, - {"x notin \t (abc,def)", internalSelector{ - getRequirement("x", selection.NotIn, sets.NewString("abc", "def"), t), - }, true, true}, - {"x in (abc,def)", internalSelector{ - getRequirement("x", selection.In, sets.NewString("abc", "def"), t), - }, true, true}, - {"x in (abc,)", internalSelector{ - getRequirement("x", selection.In, sets.NewString("abc", ""), t), - }, true, true}, - {"x in ()", internalSelector{ - getRequirement("x", selection.In, sets.NewString(""), t), - }, true, true}, - {"x notin (abc,,def),bar,z in (),w", internalSelector{ - getRequirement("bar", selection.Exists, nil, t), - getRequirement("w", selection.Exists, nil, t), - getRequirement("x", selection.NotIn, sets.NewString("abc", "", "def"), t), - getRequirement("z", selection.In, sets.NewString(""), t), - }, true, true}, - {"x,y in (a)", internalSelector{ - getRequirement("y", selection.In, sets.NewString("a"), t), - getRequirement("x", selection.Exists, nil, t), - }, false, true}, - {"x=a", internalSelector{ - getRequirement("x", selection.Equals, sets.NewString("a"), t), - }, true, true}, - {"x>1", internalSelector{ - getRequirement("x", selection.GreaterThan, sets.NewString("1"), t), - }, true, true}, - {"x<7", internalSelector{ - getRequirement("x", selection.LessThan, sets.NewString("7"), t), - }, true, true}, - {"x=a,y!=b", internalSelector{ - getRequirement("x", selection.Equals, sets.NewString("a"), t), - getRequirement("y", selection.NotEquals, sets.NewString("b"), t), - }, true, true}, - {"x=a,y!=b,z in (h,i,j)", internalSelector{ - getRequirement("x", selection.Equals, sets.NewString("a"), t), - getRequirement("y", selection.NotEquals, sets.NewString("b"), t), - getRequirement("z", selection.In, sets.NewString("h", "i", "j"), t), - }, true, true}, - {"x=a||y=b", internalSelector{}, false, false}, - {"x,,y", nil, true, false}, - {",x,y", nil, true, false}, - {"x nott in (y)", nil, true, false}, - {"x notin ( )", internalSelector{ - getRequirement("x", selection.NotIn, sets.NewString(""), t), - }, true, true}, - {"x notin (, a)", internalSelector{ - getRequirement("x", selection.NotIn, sets.NewString("", "a"), t), - }, true, true}, - {"a in (xyz),", nil, true, false}, - {"a in (xyz)b notin ()", nil, true, false}, - {"a ", internalSelector{ - getRequirement("a", selection.Exists, nil, t), - }, true, true}, - {"a in (x,y,notin, z,in)", internalSelector{ - getRequirement("a", selection.In, sets.NewString("in", "notin", "x", "y", "z"), t), - }, true, true}, // operator 'in' inside list of identifiers - {"a in (xyz abc)", nil, false, false}, // no comma - {"a notin(", nil, true, false}, // bad formed - {"a (", nil, false, false}, // cpar - {"(", nil, false, false}, // opar - } - - for _, ssp := range setSelectorParserTests { - if sel, err := Parse(ssp.In); err != nil && ssp.Valid { - t.Errorf("Parse(%s) => %v expected no error", ssp.In, err) - } else if err == nil && !ssp.Valid { - t.Errorf("Parse(%s) => %+v expected error", ssp.In, sel) - } else if ssp.Match && !reflect.DeepEqual(sel, ssp.Out) { - t.Errorf("Parse(%s) => parse output '%#v' doesn't match '%#v' expected match", ssp.In, sel, ssp.Out) - } - } -} - -func getRequirement(key string, op selection.Operator, vals sets.String, t *testing.T) Requirement { - req, err := NewRequirement(key, op, vals.List()) - if err != nil { - t.Errorf("NewRequirement(%v, %v, %v) resulted in error:%v", key, op, vals, err) - return Requirement{} - } - return *req -} - -func TestAdd(t *testing.T) { - testCases := []struct { - name string - sel Selector - key string - operator selection.Operator - values []string - refSelector Selector - }{ - { - "keyInOperator", - internalSelector{}, - "key", - selection.In, - []string{"value"}, - internalSelector{Requirement{"key", selection.In, []string{"value"}}}, - }, - { - "keyEqualsOperator", - internalSelector{Requirement{"key", selection.In, []string{"value"}}}, - "key2", - selection.Equals, - []string{"value2"}, - internalSelector{ - Requirement{"key", selection.In, []string{"value"}}, - Requirement{"key2", selection.Equals, []string{"value2"}}, - }, - }, - } - for _, ts := range testCases { - req, err := NewRequirement(ts.key, ts.operator, ts.values) - if err != nil { - t.Errorf("%s - Unable to create labels.Requirement", ts.name) - } - ts.sel = ts.sel.Add(*req) - if !reflect.DeepEqual(ts.sel, ts.refSelector) { - t.Errorf("%s - Expected %v found %v", ts.name, ts.refSelector, ts.sel) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/BUILD b/vendor/k8s.io/apimachinery/pkg/runtime/BUILD deleted file mode 100644 index 7a53fbc41d..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/BUILD +++ /dev/null @@ -1,98 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["swagger_doc_generator_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "codec.go", - "codec_check.go", - "conversion.go", - "converter.go", - "doc.go", - "embedded.go", - "error.go", - "extension.go", - "generated.pb.go", - "helper.go", - "interfaces.go", - "register.go", - "scheme.go", - "scheme_builder.go", - "swagger_doc_generator.go", - "types.go", - "types_proto.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/apimachinery/pkg/runtime", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion/queryparams:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/errors:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/json:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library", - ], -) - -go_test( - name = "go_default_xtest", - srcs = [ - "conversion_test.go", - "converter_test.go", - "embedded_test.go", - "extension_test.go", - "scheme_test.go", - ], - deps = [ - "//vendor/github.com/google/gofuzz:go_default_library", - "//vendor/github.com/spf13/pflag:go_default_library", - "//vendor/github.com/stretchr/testify/assert:go_default_library", - "//vendor/github.com/stretchr/testify/require:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/testing:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/diff:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/json:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/schema:all-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/serializer:all-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/testing:all-srcs", - ], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/conversion_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/conversion_test.go deleted file mode 100644 index 33670415b4..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/conversion_test.go +++ /dev/null @@ -1,115 +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 runtime_test - -import ( - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - runtimetesting "k8s.io/apimachinery/pkg/runtime/testing" -) - -func TestStringMapConversion(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Group: "test.group", Version: "external"} - - scheme := runtime.NewScheme() - scheme.Log(t) - scheme.AddKnownTypeWithName(internalGV.WithKind("Complex"), &runtimetesting.InternalComplex{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("Complex"), &runtimetesting.ExternalComplex{}) - - testCases := map[string]struct { - input map[string][]string - errFn func(error) bool - expected runtime.Object - }{ - "ignores omitempty": { - input: map[string][]string{ - "String": {"not_used"}, - "string": {"value"}, - "int": {"1"}, - "Integer64": {"2"}, - }, - expected: &runtimetesting.ExternalComplex{String: "value", Integer: 1}, - }, - "returns error on bad int": { - input: map[string][]string{ - "int": {"a"}, - }, - errFn: func(err error) bool { return err != nil }, - expected: &runtimetesting.ExternalComplex{}, - }, - "parses int64": { - input: map[string][]string{ - "Int64": {"-1"}, - }, - expected: &runtimetesting.ExternalComplex{Int64: -1}, - }, - "returns error on bad int64": { - input: map[string][]string{ - "Int64": {"a"}, - }, - errFn: func(err error) bool { return err != nil }, - expected: &runtimetesting.ExternalComplex{}, - }, - "parses boolean true": { - input: map[string][]string{ - "bool": {"true"}, - }, - expected: &runtimetesting.ExternalComplex{Bool: true}, - }, - "parses boolean any value": { - input: map[string][]string{ - "bool": {"foo"}, - }, - expected: &runtimetesting.ExternalComplex{Bool: true}, - }, - "parses boolean false": { - input: map[string][]string{ - "bool": {"false"}, - }, - expected: &runtimetesting.ExternalComplex{Bool: false}, - }, - "parses boolean empty value": { - input: map[string][]string{ - "bool": {""}, - }, - expected: &runtimetesting.ExternalComplex{Bool: true}, - }, - "parses boolean no value": { - input: map[string][]string{ - "bool": {}, - }, - expected: &runtimetesting.ExternalComplex{Bool: false}, - }, - } - - for k, tc := range testCases { - out := &runtimetesting.ExternalComplex{} - if err := scheme.Convert(&tc.input, out, nil); (tc.errFn == nil && err != nil) || (tc.errFn != nil && !tc.errFn(err)) { - t.Errorf("%s: unexpected error: %v", k, err) - continue - } else if err != nil { - continue - } - if !reflect.DeepEqual(out, tc.expected) { - t.Errorf("%s: unexpected output: %#v", k, out) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/converter_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/converter_test.go deleted file mode 100644 index 7820b8cefd..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/converter_test.go +++ /dev/null @@ -1,597 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -// These tests are in a separate package to break cyclic dependency in tests. -// Unstructured type depends on unstructured converter package but we want to test how the converter handles -// the Unstructured type so we need to import both. - -package runtime_test - -import ( - encodingjson "encoding/json" - "fmt" - "reflect" - "strconv" - "testing" - "time" - - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/conversion" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/diff" - "k8s.io/apimachinery/pkg/util/json" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var simpleEquality = conversion.EqualitiesOrDie( - func(a, b time.Time) bool { - return a.UTC() == b.UTC() - }, -) - -// Definte a number of test types. -type A struct { - A int `json:"aa,omitempty"` - B string `json:"ab,omitempty"` - C bool `json:"ac,omitempty"` -} - -type B struct { - A A `json:"ba"` - B string `json:"bb"` - C map[string]string `json:"bc"` - D []string `json:"bd"` -} - -type C struct { - A []A `json:"ca"` - B `json:",inline"` - C string `json:"cc"` - D *int64 `json:"cd"` - E map[string]int `json:"ce"` - F []bool `json:"cf"` - G []int `json:"cg"` - H float32 `json:"ch"` - I []interface{} `json:"ci"` -} - -type D struct { - A []interface{} `json:"da"` -} - -type E struct { - A interface{} `json:"ea"` -} - -type F struct { - A string `json:"fa"` - B map[string]string `json:"fb"` - C []A `json:"fc"` - D int `json:"fd"` - E float32 `json:"fe"` - F []string `json:"ff"` - G []int `json:"fg"` - H []bool `json:"fh"` - I []float32 `json:"fi"` -} - -type G struct { - CustomValue1 CustomValue `json:"customValue1"` - CustomValue2 *CustomValue `json:"customValue2"` - CustomPointer1 CustomPointer `json:"customPointer1"` - CustomPointer2 *CustomPointer `json:"customPointer2"` -} - -type CustomValue struct { - data []byte -} - -// MarshalJSON has a value receiver on this type. -func (c CustomValue) MarshalJSON() ([]byte, error) { - return c.data, nil -} - -type CustomPointer struct { - data []byte -} - -// MarshalJSON has a pointer receiver on this type. -func (c *CustomPointer) MarshalJSON() ([]byte, error) { - return c.data, nil -} - -func doRoundTrip(t *testing.T, item interface{}) { - data, err := json.Marshal(item) - if err != nil { - t.Errorf("Error when marshaling object: %v", err) - return - } - - unstr := make(map[string]interface{}) - err = json.Unmarshal(data, &unstr) - if err != nil { - t.Errorf("Error when unmarshaling to unstructured: %v", err) - return - } - - data, err = json.Marshal(unstr) - if err != nil { - t.Errorf("Error when marshaling unstructured: %v", err) - return - } - unmarshalledObj := reflect.New(reflect.TypeOf(item).Elem()).Interface() - err = json.Unmarshal(data, unmarshalledObj) - if err != nil { - t.Errorf("Error when unmarshaling to object: %v", err) - return - } - if !reflect.DeepEqual(item, unmarshalledObj) { - t.Errorf("Object changed during JSON operations, diff: %v", diff.ObjectReflectDiff(item, unmarshalledObj)) - return - } - - // TODO: should be using mismatch detection but fails due to another error - newUnstr, err := runtime.DefaultUnstructuredConverter.ToUnstructured(item) - if err != nil { - t.Errorf("ToUnstructured failed: %v", err) - return - } - - newObj := reflect.New(reflect.TypeOf(item).Elem()).Interface() - err = runtime.NewTestUnstructuredConverter(simpleEquality).FromUnstructured(newUnstr, newObj) - if err != nil { - t.Errorf("FromUnstructured failed: %v", err) - return - } - - if !reflect.DeepEqual(item, newObj) { - t.Errorf("Object changed, diff: %v", diff.ObjectReflectDiff(item, newObj)) - } -} - -func TestRoundTrip(t *testing.T) { - intVal := int64(42) - testCases := []struct { - obj interface{} - }{ - { - obj: &unstructured.UnstructuredList{ - Object: map[string]interface{}{ - "kind": "List", - }, - // Not testing a list with nil Items because items is a non-optional field and hence - // is always marshaled into an empty array which is not equal to nil when unmarshalled and will fail. - // That is expected. - Items: []unstructured.Unstructured{}, - }, - }, - { - obj: &unstructured.UnstructuredList{ - Object: map[string]interface{}{ - "kind": "List", - }, - Items: []unstructured.Unstructured{ - { - Object: map[string]interface{}{ - "kind": "Pod", - }, - }, - }, - }, - }, - { - obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "kind": "Pod", - }, - }, - }, - { - obj: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": "v1", - "kind": "Foo", - "metadata": map[string]interface{}{ - "name": "foo1", - }, - }, - }, - }, - { - // This (among others) tests nil map, slice and pointer. - obj: &C{ - C: "ccc", - }, - }, - { - // This (among others) tests empty map and slice. - obj: &C{ - A: []A{}, - C: "ccc", - E: map[string]int{}, - I: []interface{}{}, - }, - }, - { - obj: &C{ - A: []A{ - { - A: 1, - B: "11", - C: true, - }, - { - A: 2, - B: "22", - C: false, - }, - }, - B: B{ - A: A{ - A: 3, - B: "33", - }, - B: "bbb", - C: map[string]string{ - "k1": "v1", - "k2": "v2", - }, - D: []string{"s1", "s2"}, - }, - C: "ccc", - D: &intVal, - E: map[string]int{ - "k1": 1, - "k2": 2, - }, - F: []bool{true, false, false}, - G: []int{1, 2, 5}, - H: 3.3, - I: []interface{}{nil, nil, nil}, - }, - }, - { - // Test slice of interface{} with empty slices. - obj: &D{ - A: []interface{}{[]interface{}{}, []interface{}{}}, - }, - }, - { - // Test slice of interface{} with different values. - obj: &D{ - A: []interface{}{3.0, "3.0", nil}, - }, - }, - } - - for i := range testCases { - t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { - doRoundTrip(t, testCases[i].obj) - }) - } -} - -// Verifies that: -// 1) serialized json -> object -// 2) serialized json -> map[string]interface{} -> object -// produces the same object. -func doUnrecognized(t *testing.T, jsonData string, item interface{}, expectedErr error) { - unmarshalledObj := reflect.New(reflect.TypeOf(item).Elem()).Interface() - err := json.Unmarshal([]byte(jsonData), unmarshalledObj) - if (err != nil) != (expectedErr != nil) { - t.Errorf("Unexpected error when unmarshaling to object: %v, expected: %v", err, expectedErr) - return - } - - unstr := make(map[string]interface{}) - err = json.Unmarshal([]byte(jsonData), &unstr) - if err != nil { - t.Errorf("Error when unmarshaling to unstructured: %v", err) - return - } - newObj := reflect.New(reflect.TypeOf(item).Elem()).Interface() - err = runtime.NewTestUnstructuredConverter(simpleEquality).FromUnstructured(unstr, newObj) - if (err != nil) != (expectedErr != nil) { - t.Errorf("Unexpected error in FromUnstructured: %v, expected: %v", err, expectedErr) - } - - if expectedErr == nil && !reflect.DeepEqual(unmarshalledObj, newObj) { - t.Errorf("Object changed, diff: %v", diff.ObjectReflectDiff(unmarshalledObj, newObj)) - } -} - -func TestUnrecognized(t *testing.T) { - testCases := []struct { - data string - obj interface{} - err error - }{ - { - data: "{\"da\":[3.0,\"3.0\",null]}", - obj: &D{}, - }, - { - data: "{\"ea\":[3.0,\"3.0\",null]}", - obj: &E{}, - }, - { - data: "{\"ea\":[null,null,null]}", - obj: &E{}, - }, - { - data: "{\"ea\":[[],[null]]}", - obj: &E{}, - }, - { - data: "{\"ea\":{\"a\":[],\"b\":null}}", - obj: &E{}, - }, - { - data: "{\"fa\":\"fa\",\"fb\":{\"a\":\"a\"}}", - obj: &F{}, - }, - { - data: "{\"fa\":\"fa\",\"fb\":{\"a\":null}}", - obj: &F{}, - }, - { - data: "{\"fc\":[null]}", - obj: &F{}, - }, - { - data: "{\"fc\":[{\"aa\":123,\"ab\":\"bbb\"}]}", - obj: &F{}, - }, - { - // Only unknown fields - data: "{\"fx\":[{\"aa\":123,\"ab\":\"bbb\"}],\"fz\":123}", - obj: &F{}, - }, - { - data: "{\"fc\":[{\"aa\":\"aaa\",\"ab\":\"bbb\"}]}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal string into Go value of type int"), - }, - { - data: "{\"fd\":123,\"fe\":3.5}", - obj: &F{}, - }, - { - data: "{\"ff\":[\"abc\"],\"fg\":[123],\"fh\":[true,false]}", - obj: &F{}, - }, - { - // Invalid string data - data: "{\"fa\":123}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number into Go value of type string"), - }, - { - // Invalid string data - data: "{\"fa\":13.5}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number into Go value of type string"), - }, - { - // Invalid string data - data: "{\"fa\":true}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal bool into Go value of type string"), - }, - { - // Invalid []string data - data: "{\"ff\":123}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number into Go value of type []string"), - }, - { - // Invalid []string data - data: "{\"ff\":3.5}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number into Go value of type []string"), - }, - { - // Invalid []string data - data: "{\"ff\":[123,345]}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number into Go value of type string"), - }, - { - // Invalid []int data - data: "{\"fg\":123}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number into Go value of type []int"), - }, - { - // Invalid []int data - data: "{\"fg\":\"abc\"}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal string into Go value of type []int"), - }, - { - // Invalid []int data - data: "{\"fg\":[\"abc\"]}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal string into Go value of type int"), - }, - { - // Invalid []int data - data: "{\"fg\":[3.5]}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number 3.5 into Go value of type int"), - }, - { - // Invalid []int data - data: "{\"fg\":[true,false]}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number 3.5 into Go value of type int"), - }, - { - // Invalid []bool data - data: "{\"fh\":123}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number into Go value of type []bool"), - }, - { - // Invalid []bool data - data: "{\"fh\":\"abc\"}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal string into Go value of type []bool"), - }, - { - // Invalid []bool data - data: "{\"fh\":[\"abc\"]}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal string into Go value of type bool"), - }, - { - // Invalid []bool data - data: "{\"fh\":[3.5]}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number into Go value of type bool"), - }, - { - // Invalid []bool data - data: "{\"fh\":[123]}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number into Go value of type bool"), - }, - { - // Invalid []float data - data: "{\"fi\":123}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal number into Go value of type []float32"), - }, - { - // Invalid []float data - data: "{\"fi\":\"abc\"}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal string into Go value of type []float32"), - }, - { - // Invalid []float data - data: "{\"fi\":[\"abc\"]}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal string into Go value of type float32"), - }, - { - // Invalid []float data - data: "{\"fi\":[true]}", - obj: &F{}, - err: fmt.Errorf("json: cannot unmarshal bool into Go value of type float32"), - }, - } - - for _, tc := range testCases { - t.Run(tc.data, func(t *testing.T) { - doUnrecognized(t, tc.data, tc.obj, tc.err) - }) - } -} - -func TestDeepCopyJSON(t *testing.T) { - src := map[string]interface{}{ - "a": nil, - "b": int64(123), - "c": map[string]interface{}{ - "a": "b", - }, - "d": []interface{}{ - int64(1), int64(2), - }, - "e": "estr", - "f": true, - "g": encodingjson.Number("123"), - } - deepCopy := runtime.DeepCopyJSON(src) - assert.Equal(t, src, deepCopy) -} - -func TestFloatIntConversion(t *testing.T) { - unstr := map[string]interface{}{"fd": float64(3)} - - var obj F - if err := runtime.NewTestUnstructuredConverter(simpleEquality).FromUnstructured(unstr, &obj); err != nil { - t.Errorf("Unexpected error in FromUnstructured: %v", err) - } - - data, err := json.Marshal(unstr) - if err != nil { - t.Fatalf("Error when marshaling unstructured: %v", err) - } - var unmarshalled F - if err := json.Unmarshal(data, &unmarshalled); err != nil { - t.Fatalf("Error when unmarshaling to object: %v", err) - } - - if !reflect.DeepEqual(obj, unmarshalled) { - t.Errorf("Incorrect conversion, diff: %v", diff.ObjectReflectDiff(obj, unmarshalled)) - } -} - -func TestCustomToUnstructured(t *testing.T) { - testcases := []struct { - Data string - Expected interface{} - }{ - {Data: `null`, Expected: nil}, - {Data: `true`, Expected: true}, - {Data: `false`, Expected: false}, - {Data: `[]`, Expected: []interface{}{}}, - {Data: `[1]`, Expected: []interface{}{int64(1)}}, - {Data: `{}`, Expected: map[string]interface{}{}}, - {Data: `{"a":1}`, Expected: map[string]interface{}{"a": int64(1)}}, - {Data: `0`, Expected: int64(0)}, - {Data: `0.0`, Expected: float64(0)}, - } - - for _, tc := range testcases { - tc := tc - t.Run(tc.Data, func(t *testing.T) { - t.Parallel() - result, err := runtime.NewTestUnstructuredConverter(simpleEquality).ToUnstructured(&G{ - CustomValue1: CustomValue{data: []byte(tc.Data)}, - CustomValue2: &CustomValue{data: []byte(tc.Data)}, - CustomPointer1: CustomPointer{data: []byte(tc.Data)}, - CustomPointer2: &CustomPointer{data: []byte(tc.Data)}, - }) - require.NoError(t, err) - for field, fieldResult := range result { - assert.Equal(t, tc.Expected, fieldResult, field) - } - }) - } -} - -func TestCustomToUnstructuredTopLevel(t *testing.T) { - // Only objects are supported at the top level - topLevelCases := []interface{}{ - &CustomValue{data: []byte(`{"a":1}`)}, - &CustomPointer{data: []byte(`{"a":1}`)}, - } - expected := map[string]interface{}{"a": int64(1)} - for i, obj := range topLevelCases { - obj := obj - t.Run(strconv.Itoa(i), func(t *testing.T) { - t.Parallel() - result, err := runtime.NewTestUnstructuredConverter(simpleEquality).ToUnstructured(obj) - require.NoError(t, err) - assert.Equal(t, expected, result) - }) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/embedded_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/embedded_test.go deleted file mode 100644 index 606e0e96ad..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/embedded_test.go +++ /dev/null @@ -1,256 +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 runtime_test - -import ( - "encoding/json" - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/runtime/serializer" - runtimetesting "k8s.io/apimachinery/pkg/runtime/testing" - "k8s.io/apimachinery/pkg/util/diff" -) - -func TestDecodeEmptyRawExtensionAsObject(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Group: "test.group", Version: "v1test"} - externalGVK := externalGV.WithKind("ObjectTest") - - s := runtime.NewScheme() - s.AddKnownTypes(internalGV, &runtimetesting.ObjectTest{}) - s.AddKnownTypeWithName(externalGVK, &runtimetesting.ObjectTestExternal{}) - - codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV) - - obj, gvk, err := codec.Decode([]byte(`{"kind":"`+externalGVK.Kind+`","apiVersion":"`+externalGV.String()+`","items":[{}]}`), nil, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - test := obj.(*runtimetesting.ObjectTest) - if unk, ok := test.Items[0].(*runtime.Unknown); !ok || unk.Kind != "" || unk.APIVersion != "" || string(unk.Raw) != "{}" || unk.ContentType != runtime.ContentTypeJSON { - t.Fatalf("unexpected object: %#v", test.Items[0]) - } - if *gvk != externalGVK { - t.Fatalf("unexpected kind: %#v", gvk) - } - - obj, gvk, err = codec.Decode([]byte(`{"kind":"`+externalGVK.Kind+`","apiVersion":"`+externalGV.String()+`","items":[{"kind":"Other","apiVersion":"v1"}]}`), nil, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - test = obj.(*runtimetesting.ObjectTest) - if unk, ok := test.Items[0].(*runtime.Unknown); !ok || unk.Kind != "" || unk.APIVersion != "" || string(unk.Raw) != `{"kind":"Other","apiVersion":"v1"}` || unk.ContentType != runtime.ContentTypeJSON { - t.Fatalf("unexpected object: %#v", test.Items[0]) - } - if *gvk != externalGVK { - t.Fatalf("unexpected kind: %#v", gvk) - } -} - -func TestArrayOfRuntimeObject(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Group: "test.group", Version: "v1test"} - - s := runtime.NewScheme() - s.AddKnownTypes(internalGV, &runtimetesting.EmbeddedTest{}) - s.AddKnownTypeWithName(externalGV.WithKind("EmbeddedTest"), &runtimetesting.EmbeddedTestExternal{}) - s.AddKnownTypes(internalGV, &runtimetesting.ObjectTest{}) - s.AddKnownTypeWithName(externalGV.WithKind("ObjectTest"), &runtimetesting.ObjectTestExternal{}) - - codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV) - - innerItems := []runtime.Object{ - &runtimetesting.EmbeddedTest{ID: "baz"}, - } - items := []runtime.Object{ - &runtimetesting.EmbeddedTest{ID: "foo"}, - &runtimetesting.EmbeddedTest{ID: "bar"}, - // TODO: until YAML is removed, this JSON must be in ascending key order to ensure consistent roundtrip serialization - &runtime.Unknown{ - Raw: []byte(`{"apiVersion":"unknown.group/unknown","foo":"bar","kind":"OtherTest"}`), - ContentType: runtime.ContentTypeJSON, - }, - &runtimetesting.ObjectTest{ - Items: runtime.NewEncodableList(codec, innerItems), - }, - } - internal := &runtimetesting.ObjectTest{ - Items: runtime.NewEncodableList(codec, items), - } - wire, err := runtime.Encode(codec, internal) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - t.Logf("Wire format is:\n%s\n", string(wire)) - - obj := &runtimetesting.ObjectTestExternal{} - if err := json.Unmarshal(wire, obj); err != nil { - t.Fatalf("unexpected error: %v", err) - } - t.Logf("exact wire is: %s", string(obj.Items[0].Raw)) - - items[3] = &runtimetesting.ObjectTest{Items: innerItems} - internal.Items = items - - decoded, err := runtime.Decode(codec, wire) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - list, err := meta.ExtractList(decoded) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if errs := runtime.DecodeList(list, codec); len(errs) > 0 { - t.Fatalf("unexpected error: %v", errs) - } - - list2, err := meta.ExtractList(list[3]) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if errs := runtime.DecodeList(list2, codec); len(errs) > 0 { - t.Fatalf("unexpected error: %v", errs) - } - if err := meta.SetList(list[3], list2); err != nil { - t.Fatalf("unexpected error: %v", err) - } - - // we want DecodeList to set type meta if possible, even on runtime.Unknown objects - internal.Items[2].(*runtime.Unknown).TypeMeta = runtime.TypeMeta{Kind: "OtherTest", APIVersion: "unknown.group/unknown"} - if e, a := internal.Items, list; !reflect.DeepEqual(e, a) { - t.Errorf("mismatched decoded: %s", diff.ObjectGoPrintSideBySide(e, a)) - } -} - -func TestNestedObject(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Group: "test.group", Version: "v1test"} - embeddedTestExternalGVK := externalGV.WithKind("EmbeddedTest") - - s := runtime.NewScheme() - s.AddKnownTypes(internalGV, &runtimetesting.EmbeddedTest{}) - s.AddKnownTypeWithName(embeddedTestExternalGVK, &runtimetesting.EmbeddedTestExternal{}) - - codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV) - - inner := &runtimetesting.EmbeddedTest{ - ID: "inner", - } - outer := &runtimetesting.EmbeddedTest{ - ID: "outer", - Object: runtime.NewEncodable(codec, inner), - } - - wire, err := runtime.Encode(codec, outer) - if err != nil { - t.Fatalf("Unexpected encode error '%v'", err) - } - - t.Logf("Wire format is:\n%v\n", string(wire)) - - decoded, err := runtime.Decode(codec, wire) - if err != nil { - t.Fatalf("Unexpected decode error %v", err) - } - - // for later tests - outer.Object = inner - - if e, a := outer, decoded; reflect.DeepEqual(e, a) { - t.Errorf("Expected unequal %#v %#v", e, a) - } - - obj, err := runtime.Decode(codec, decoded.(*runtimetesting.EmbeddedTest).Object.(*runtime.Unknown).Raw) - if err != nil { - t.Fatal(err) - } - decoded.(*runtimetesting.EmbeddedTest).Object = obj - if e, a := outer, decoded; !reflect.DeepEqual(e, a) { - t.Errorf("Expected equal %#v %#v", e, a) - } - - // test JSON decoding of the external object, which should preserve - // raw bytes - var externalViaJSON runtimetesting.EmbeddedTestExternal - err = json.Unmarshal(wire, &externalViaJSON) - if err != nil { - t.Fatalf("Unexpected decode error %v", err) - } - if externalViaJSON.Kind == "" || externalViaJSON.APIVersion == "" || externalViaJSON.ID != "outer" { - t.Errorf("Expected objects to have type info set, got %#v", externalViaJSON) - } - if len(externalViaJSON.EmptyObject.Raw) > 0 { - t.Errorf("Expected deserialization of empty nested objects into empty bytes, got %#v", externalViaJSON) - } - - // test JSON decoding, too, since Decode uses yaml unmarshalling. - // Generic Unmarshalling of JSON cannot load the nested objects because there is - // no default schema set. Consumers wishing to get direct JSON decoding must use - // the external representation - var decodedViaJSON runtimetesting.EmbeddedTest - err = json.Unmarshal(wire, &decodedViaJSON) - if err == nil { - t.Fatal("Expeceted decode error") - } - if _, ok := err.(*json.UnmarshalTypeError); !ok { - t.Fatalf("Unexpected decode error: %v", err) - } - if a := decodedViaJSON; a.Object != nil || a.EmptyObject != nil { - t.Errorf("Expected embedded objects to be nil: %#v", a) - } -} - -// TestDeepCopyOfRuntimeObject checks to make sure that runtime.Objects's can be passed through DeepCopy with fidelity -func TestDeepCopyOfRuntimeObject(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Group: "test.group", Version: "v1test"} - embeddedTestExternalGVK := externalGV.WithKind("EmbeddedTest") - - s := runtime.NewScheme() - s.AddKnownTypes(internalGV, &runtimetesting.EmbeddedTest{}) - s.AddKnownTypeWithName(embeddedTestExternalGVK, &runtimetesting.EmbeddedTestExternal{}) - - original := &runtimetesting.EmbeddedTest{ - ID: "outer", - Object: &runtimetesting.EmbeddedTest{ - ID: "inner", - }, - } - - codec := serializer.NewCodecFactory(s).LegacyCodec(externalGV) - - originalData, err := runtime.Encode(codec, original) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - t.Logf("originalRole = %v\n", string(originalData)) - - copyOfOriginal := original.DeepCopy() - copiedData, err := runtime.Encode(codec, copyOfOriginal) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - t.Logf("copyOfRole = %v\n", string(copiedData)) - - if !reflect.DeepEqual(original, copyOfOriginal) { - t.Errorf("expected \n%v\n, got \n%v", string(originalData), string(copiedData)) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/extension_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/extension_test.go deleted file mode 100644 index 5f9154ea6b..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/extension_test.go +++ /dev/null @@ -1,113 +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 runtime_test - -import ( - "bytes" - "encoding/json" - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/runtime" -) - -func TestEmbeddedRawExtensionMarshal(t *testing.T) { - type test struct { - Ext runtime.RawExtension - } - - extension := test{Ext: runtime.RawExtension{Raw: []byte(`{"foo":"bar"}`)}} - data, err := json.Marshal(extension) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if string(data) != `{"Ext":{"foo":"bar"}}` { - t.Errorf("unexpected data: %s", string(data)) - } -} -func TestEmbeddedRawExtensionUnmarshal(t *testing.T) { - type test struct { - Ext runtime.RawExtension - } - - testCases := map[string]struct { - orig test - }{ - "non-empty object": { - orig: test{Ext: runtime.RawExtension{Raw: []byte(`{"foo":"bar"}`)}}, - }, - "empty object": { - orig: test{Ext: runtime.RawExtension{}}, - }, - } - - for k, tc := range testCases { - new := test{} - data, _ := json.Marshal(tc.orig) - if err := json.Unmarshal(data, &new); err != nil { - t.Errorf("%s: umarshal error: %v", k, err) - } - if !reflect.DeepEqual(tc.orig, new) { - t.Errorf("%s: unmarshaled struct differs from original: %v %v", k, tc.orig, new) - } - } -} - -func TestEmbeddedRawExtensionRoundTrip(t *testing.T) { - type test struct { - Ext runtime.RawExtension - } - - testCases := map[string]struct { - orig test - }{ - "non-empty object": { - orig: test{Ext: runtime.RawExtension{Raw: []byte(`{"foo":"bar"}`)}}, - }, - "empty object": { - orig: test{Ext: runtime.RawExtension{}}, - }, - } - - for k, tc := range testCases { - new1 := test{} - new2 := test{} - data, err := json.Marshal(tc.orig) - if err != nil { - t.Errorf("1st marshal error: %v", err) - } - if err = json.Unmarshal(data, &new1); err != nil { - t.Errorf("1st unmarshal error: %v", err) - } - newData, err := json.Marshal(new1) - if err != nil { - t.Errorf("2st marshal error: %v", err) - } - if err = json.Unmarshal(newData, &new2); err != nil { - t.Errorf("2nd unmarshal error: %v", err) - } - if !bytes.Equal(data, newData) { - t.Errorf("%s: re-marshaled data differs from original: %v %v", k, data, newData) - } - if !reflect.DeepEqual(tc.orig, new1) { - t.Errorf("%s: unmarshaled struct differs from original: %v %v", k, tc.orig, new1) - } - if !reflect.DeepEqual(new1, new2) { - t.Errorf("%s: re-unmarshaled struct differs from original: %v %v", k, new1, new2) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/schema/BUILD b/vendor/k8s.io/apimachinery/pkg/runtime/schema/BUILD deleted file mode 100644 index e819772181..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/schema/BUILD +++ /dev/null @@ -1,43 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["group_version_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "generated.pb.go", - "group_version.go", - "interfaces.go", - ], - importpath = "k8s.io/apimachinery/pkg/runtime/schema", - deps = ["//vendor/github.com/gogo/protobuf/proto:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/schema/group_version_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/schema/group_version_test.go deleted file mode 100644 index 51f26df7fe..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/schema/group_version_test.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package schema - -import ( - "testing" -) - -func TestGroupVersionParse(t *testing.T) { - tests := []struct { - input string - out GroupVersion - err func(error) bool - }{ - {input: "v1", out: GroupVersion{Version: "v1"}}, - {input: "v2", out: GroupVersion{Version: "v2"}}, - {input: "/v1", out: GroupVersion{Version: "v1"}}, - {input: "v1/", out: GroupVersion{Group: "v1"}}, - {input: "/v1/", err: func(err error) bool { return err.Error() == "unexpected GroupVersion string: /v1/" }}, - {input: "v1/a", out: GroupVersion{Group: "v1", Version: "a"}}, - } - for i, test := range tests { - out, err := ParseGroupVersion(test.input) - if test.err == nil && err != nil || err == nil && test.err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - continue - } - if test.err != nil && !test.err(err) { - t.Errorf("%d: unexpected error: %v", i, err) - continue - } - if out != test.out { - t.Errorf("%d: unexpected output: %#v", i, out) - } - } -} - -func TestGroupResourceParse(t *testing.T) { - tests := []struct { - input string - out GroupResource - }{ - {input: "v1", out: GroupResource{Resource: "v1"}}, - {input: ".v1", out: GroupResource{Group: "v1"}}, - {input: "v1.", out: GroupResource{Resource: "v1"}}, - {input: "v1.a", out: GroupResource{Group: "a", Resource: "v1"}}, - {input: "b.v1.a", out: GroupResource{Group: "v1.a", Resource: "b"}}, - } - for i, test := range tests { - out := ParseGroupResource(test.input) - if out != test.out { - t.Errorf("%d: unexpected output: %#v", i, out) - } - } -} - -func TestParseResourceArg(t *testing.T) { - tests := []struct { - input string - gvr *GroupVersionResource - gr GroupResource - }{ - {input: "v1", gr: GroupResource{Resource: "v1"}}, - {input: ".v1", gr: GroupResource{Group: "v1"}}, - {input: "v1.", gr: GroupResource{Resource: "v1"}}, - {input: "v1.a", gr: GroupResource{Group: "a", Resource: "v1"}}, - {input: "b.v1.a", gvr: &GroupVersionResource{Group: "a", Version: "v1", Resource: "b"}, gr: GroupResource{Group: "v1.a", Resource: "b"}}, - } - for i, test := range tests { - gvr, gr := ParseResourceArg(test.input) - if (gvr != nil && test.gvr == nil) || (gvr == nil && test.gvr != nil) || (test.gvr != nil && *gvr != *test.gvr) { - t.Errorf("%d: unexpected output: %#v", i, gvr) - } - if gr != test.gr { - t.Errorf("%d: unexpected output: %#v", i, gr) - } - } -} - -func TestKindForGroupVersionKinds(t *testing.T) { - gvks := GroupVersions{ - GroupVersion{Group: "batch", Version: "v1"}, - GroupVersion{Group: "batch", Version: "v2alpha1"}, - GroupVersion{Group: "policy", Version: "v1beta1"}, - } - cases := []struct { - input []GroupVersionKind - target GroupVersionKind - ok bool - }{ - { - input: []GroupVersionKind{{Group: "batch", Version: "v2alpha1", Kind: "ScheduledJob"}}, - target: GroupVersionKind{Group: "batch", Version: "v2alpha1", Kind: "ScheduledJob"}, - ok: true, - }, - { - input: []GroupVersionKind{{Group: "batch", Version: "v3alpha1", Kind: "CronJob"}}, - target: GroupVersionKind{Group: "batch", Version: "v1", Kind: "CronJob"}, - ok: true, - }, - { - input: []GroupVersionKind{{Group: "policy", Version: "v1beta1", Kind: "PodDisruptionBudget"}}, - target: GroupVersionKind{Group: "policy", Version: "v1beta1", Kind: "PodDisruptionBudget"}, - ok: true, - }, - { - input: []GroupVersionKind{{Group: "apps", Version: "v1alpha1", Kind: "StatefulSet"}}, - target: GroupVersionKind{}, - ok: false, - }, - } - - for i, c := range cases { - target, ok := gvks.KindForGroupVersionKinds(c.input) - if c.target != target { - t.Errorf("%d: unexpected target: %v, expected %v", i, target, c.target) - } - if c.ok != ok { - t.Errorf("%d: unexpected ok: %v, expected %v", i, ok, c.ok) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/scheme_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/scheme_test.go deleted file mode 100644 index 0b76b5d711..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/scheme_test.go +++ /dev/null @@ -1,1035 +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 runtime_test - -import ( - "fmt" - "reflect" - "strings" - "testing" - - "github.com/google/gofuzz" - flag "github.com/spf13/pflag" - - "k8s.io/apimachinery/pkg/conversion" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/runtime/serializer" - runtimetesting "k8s.io/apimachinery/pkg/runtime/testing" - "k8s.io/apimachinery/pkg/util/diff" -) - -var fuzzIters = flag.Int("fuzz-iters", 50, "How many fuzzing iterations to do.") - -func TestScheme(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - internalGVK := internalGV.WithKind("Simple") - externalGV := schema.GroupVersion{Group: "test.group", Version: "testExternal"} - externalGVK := externalGV.WithKind("Simple") - - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(internalGVK, &runtimetesting.InternalSimple{}) - scheme.AddKnownTypeWithName(externalGVK, &runtimetesting.ExternalSimple{}) - - // If set, would clear TypeMeta during conversion. - //scheme.AddIgnoredConversionType(&TypeMeta{}, &TypeMeta{}) - - // test that scheme is an ObjectTyper - var _ runtime.ObjectTyper = scheme - - internalToExternalCalls := 0 - externalToInternalCalls := 0 - - // Register functions to verify that scope.Meta() gets set correctly. - err := scheme.AddConversionFuncs( - func(in *runtimetesting.InternalSimple, out *runtimetesting.ExternalSimple, scope conversion.Scope) error { - err := scope.Convert(&in.TypeMeta, &out.TypeMeta, 0) - if err != nil { - return err - } - err = scope.Convert(&in.TestString, &out.TestString, 0) - if err != nil { - return err - } - internalToExternalCalls++ - return nil - }, - func(in *runtimetesting.ExternalSimple, out *runtimetesting.InternalSimple, scope conversion.Scope) error { - err := scope.Convert(&in.TypeMeta, &out.TypeMeta, 0) - if err != nil { - return err - } - err = scope.Convert(&in.TestString, &out.TestString, 0) - if err != nil { - return err - } - externalToInternalCalls++ - return nil - }, - ) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - t.Run("Encode, Decode, DecodeInto, and DecodeToVersion", func(t *testing.T) { - simple := &runtimetesting.InternalSimple{ - TestString: "foo", - } - - codecs := serializer.NewCodecFactory(scheme) - codec := codecs.LegacyCodec(externalGV) - info, _ := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), runtime.ContentTypeJSON) - jsonserializer := info.Serializer - - obj := runtime.Object(simple) - data, err := runtime.Encode(codec, obj) - if err != nil { - t.Fatal(err) - } - - obj2, err := runtime.Decode(codec, data) - if err != nil { - t.Fatal(err) - } - if _, ok := obj2.(*runtimetesting.InternalSimple); !ok { - t.Fatalf("Got wrong type") - } - if e, a := simple, obj2; !reflect.DeepEqual(e, a) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", e, a) - } - - obj3 := &runtimetesting.InternalSimple{} - if err := runtime.DecodeInto(codec, data, obj3); err != nil { - t.Fatal(err) - } - // clearing TypeMeta is a function of the scheme, which we do not test here (ConvertToVersion - // does not automatically clear TypeMeta anymore). - simple.TypeMeta = runtime.TypeMeta{Kind: "Simple", APIVersion: externalGV.String()} - if e, a := simple, obj3; !reflect.DeepEqual(e, a) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", e, a) - } - - obj4, err := runtime.Decode(jsonserializer, data) - if err != nil { - t.Fatal(err) - } - if _, ok := obj4.(*runtimetesting.ExternalSimple); !ok { - t.Fatalf("Got wrong type") - } - }) - t.Run("Convert", func(t *testing.T) { - simple := &runtimetesting.InternalSimple{ - TestString: "foo", - } - - external := &runtimetesting.ExternalSimple{} - err = scheme.Convert(simple, external, nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if e, a := simple.TestString, external.TestString; e != a { - t.Errorf("Expected %q, got %q", e, a) - } - }) - t.Run("Convert internal to unstructured", func(t *testing.T) { - simple := &runtimetesting.InternalSimple{ - TestString: "foo", - } - - unstructuredObj := &runtimetesting.Unstructured{} - err = scheme.Convert(simple, unstructuredObj, nil) - if err == nil || !strings.Contains(err.Error(), "to Unstructured without providing a preferred version to convert to") { - t.Fatalf("Unexpected non-error: %v", err) - } - err = scheme.Convert(simple, unstructuredObj, externalGV) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if e, a := simple.TestString, unstructuredObj.Object["testString"].(string); e != a { - t.Errorf("Expected %q, got %q", e, a) - } - if e := unstructuredObj.GetObjectKind().GroupVersionKind(); e != externalGVK { - t.Errorf("Unexpected object kind: %#v", e) - } - if gvks, unversioned, err := scheme.ObjectKinds(unstructuredObj); err != nil || gvks[0] != externalGVK || unversioned { - t.Errorf("Scheme did not recognize unversioned: %v, %#v %t", err, gvks, unversioned) - } - }) - t.Run("Convert external to unstructured", func(t *testing.T) { - unstructuredObj := &runtimetesting.Unstructured{} - external := &runtimetesting.ExternalSimple{ - TestString: "foo", - } - - err = scheme.Convert(external, unstructuredObj, nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if e, a := external.TestString, unstructuredObj.Object["testString"].(string); e != a { - t.Errorf("Expected %q, got %q", e, a) - } - if e := unstructuredObj.GetObjectKind().GroupVersionKind(); e != externalGVK { - t.Errorf("Unexpected object kind: %#v", e) - } - }) - t.Run("Convert unstructured to unstructured", func(t *testing.T) { - uIn := &runtimetesting.Unstructured{Object: map[string]interface{}{ - "test": []interface{}{"other", "test"}, - }} - uOut := &runtimetesting.Unstructured{} - err = scheme.Convert(uIn, uOut, nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if !reflect.DeepEqual(uIn.Object, uOut.Object) { - t.Errorf("Unexpected object contents: %#v", uOut.Object) - } - }) - t.Run("Convert unstructured to structured", func(t *testing.T) { - unstructuredObj := &runtimetesting.Unstructured{ - Object: map[string]interface{}{ - "testString": "bla", - }, - } - unstructuredObj.SetGroupVersionKind(externalGV.WithKind("Simple")) - externalOut := &runtimetesting.ExternalSimple{} - err = scheme.Convert(unstructuredObj, externalOut, nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if externalOut.TestString != "bla" { - t.Errorf("Unexpected object contents: %#v", externalOut) - } - }) - t.Run("Encode and Convert should each have caused an increment", func(t *testing.T) { - if e, a := 3, internalToExternalCalls; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - }) - t.Run("DecodeInto and Decode should each have caused an increment because of a conversion", func(t *testing.T) { - if e, a := 2, externalToInternalCalls; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - }) - t.Run("Verify that unstructured types must have V and K set", func(t *testing.T) { - emptyObj := &runtimetesting.Unstructured{Object: make(map[string]interface{})} - if _, _, err := scheme.ObjectKinds(emptyObj); !runtime.IsMissingKind(err) { - t.Errorf("unexpected error: %v", err) - } - emptyObj.SetGroupVersionKind(schema.GroupVersionKind{Kind: "Test"}) - if _, _, err := scheme.ObjectKinds(emptyObj); !runtime.IsMissingVersion(err) { - t.Errorf("unexpected error: %v", err) - } - emptyObj.SetGroupVersionKind(schema.GroupVersionKind{Kind: "Test", Version: "v1"}) - if _, _, err := scheme.ObjectKinds(emptyObj); err != nil { - t.Errorf("unexpected error: %v", err) - } - }) -} - -func TestBadJSONRejection(t *testing.T) { - scheme := runtime.NewScheme() - codecs := serializer.NewCodecFactory(scheme) - info, _ := runtime.SerializerInfoForMediaType(codecs.SupportedMediaTypes(), runtime.ContentTypeJSON) - jsonserializer := info.Serializer - - badJSONMissingKind := []byte(`{ }`) - if _, err := runtime.Decode(jsonserializer, badJSONMissingKind); err == nil { - t.Errorf("Did not reject despite lack of kind field: %s", badJSONMissingKind) - } - badJSONUnknownType := []byte(`{"kind": "bar"}`) - if _, err1 := runtime.Decode(jsonserializer, badJSONUnknownType); err1 == nil { - t.Errorf("Did not reject despite use of unknown type: %s", badJSONUnknownType) - } - /*badJSONKindMismatch := []byte(`{"kind": "Pod"}`) - if err2 := DecodeInto(badJSONKindMismatch, &Node{}); err2 == nil { - t.Errorf("Kind is set but doesn't match the object type: %s", badJSONKindMismatch) - }*/ -} - -func TestExternalToInternalMapping(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Group: "test.group", Version: "testExternal"} - - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(internalGV.WithKind("OptionalExtensionType"), &runtimetesting.InternalOptionalExtensionType{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("OptionalExtensionType"), &runtimetesting.ExternalOptionalExtensionType{}) - - codec := serializer.NewCodecFactory(scheme).LegacyCodec(externalGV) - - table := []struct { - obj runtime.Object - encoded string - }{ - { - &runtimetesting.InternalOptionalExtensionType{Extension: nil}, - `{"kind":"OptionalExtensionType","apiVersion":"` + externalGV.String() + `"}`, - }, - } - - for i, item := range table { - gotDecoded, err := runtime.Decode(codec, []byte(item.encoded)) - if err != nil { - t.Errorf("unexpected error '%v' (%v)", err, item.encoded) - } else if e, a := item.obj, gotDecoded; !reflect.DeepEqual(e, a) { - t.Errorf("%d: unexpected objects:\n%s", i, diff.ObjectGoPrintSideBySide(e, a)) - } - } -} - -func TestExtensionMapping(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Group: "test.group", Version: "testExternal"} - - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(internalGV.WithKind("ExtensionType"), &runtimetesting.InternalExtensionType{}) - scheme.AddKnownTypeWithName(internalGV.WithKind("OptionalExtensionType"), &runtimetesting.InternalOptionalExtensionType{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("ExtensionType"), &runtimetesting.ExternalExtensionType{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("OptionalExtensionType"), &runtimetesting.ExternalOptionalExtensionType{}) - - // register external first when the object is the same in both schemes, so ObjectVersionAndKind reports the - // external version. - scheme.AddKnownTypeWithName(externalGV.WithKind("A"), &runtimetesting.ExtensionA{}) - scheme.AddKnownTypeWithName(externalGV.WithKind("B"), &runtimetesting.ExtensionB{}) - scheme.AddKnownTypeWithName(internalGV.WithKind("A"), &runtimetesting.ExtensionA{}) - scheme.AddKnownTypeWithName(internalGV.WithKind("B"), &runtimetesting.ExtensionB{}) - - codec := serializer.NewCodecFactory(scheme).LegacyCodec(externalGV) - - table := []struct { - obj runtime.Object - expected runtime.Object - encoded string - }{ - { - &runtimetesting.InternalExtensionType{ - Extension: runtime.NewEncodable(codec, &runtimetesting.ExtensionA{TestString: "foo"}), - }, - &runtimetesting.InternalExtensionType{ - Extension: &runtime.Unknown{ - Raw: []byte(`{"apiVersion":"test.group/testExternal","kind":"A","testString":"foo"}`), - ContentType: runtime.ContentTypeJSON, - }, - }, - // apiVersion is set in the serialized object for easier consumption by clients - `{"apiVersion":"` + externalGV.String() + `","kind":"ExtensionType","extension":{"apiVersion":"test.group/testExternal","kind":"A","testString":"foo"}} -`, - }, { - &runtimetesting.InternalExtensionType{Extension: runtime.NewEncodable(codec, &runtimetesting.ExtensionB{TestString: "bar"})}, - &runtimetesting.InternalExtensionType{ - Extension: &runtime.Unknown{ - Raw: []byte(`{"apiVersion":"test.group/testExternal","kind":"B","testString":"bar"}`), - ContentType: runtime.ContentTypeJSON, - }, - }, - // apiVersion is set in the serialized object for easier consumption by clients - `{"apiVersion":"` + externalGV.String() + `","kind":"ExtensionType","extension":{"apiVersion":"test.group/testExternal","kind":"B","testString":"bar"}} -`, - }, { - &runtimetesting.InternalExtensionType{Extension: nil}, - &runtimetesting.InternalExtensionType{ - Extension: nil, - }, - `{"apiVersion":"` + externalGV.String() + `","kind":"ExtensionType","extension":null} -`, - }, - } - - for i, item := range table { - gotEncoded, err := runtime.Encode(codec, item.obj) - if err != nil { - t.Errorf("unexpected error '%v' (%#v)", err, item.obj) - } else if e, a := item.encoded, string(gotEncoded); e != a { - t.Errorf("expected\n%#v\ngot\n%#v\n", e, a) - } - - gotDecoded, err := runtime.Decode(codec, []byte(item.encoded)) - if err != nil { - t.Errorf("unexpected error '%v' (%v)", err, item.encoded) - } else if e, a := item.expected, gotDecoded; !reflect.DeepEqual(e, a) { - t.Errorf("%d: unexpected objects:\n%s", i, diff.ObjectGoPrintSideBySide(e, a)) - } - } -} - -func TestEncode(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - internalGVK := internalGV.WithKind("Simple") - externalGV := schema.GroupVersion{Group: "test.group", Version: "testExternal"} - externalGVK := externalGV.WithKind("Simple") - - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(internalGVK, &runtimetesting.InternalSimple{}) - scheme.AddKnownTypeWithName(externalGVK, &runtimetesting.ExternalSimple{}) - - codec := serializer.NewCodecFactory(scheme).LegacyCodec(externalGV) - - test := &runtimetesting.InternalSimple{ - TestString: "I'm the same", - } - obj := runtime.Object(test) - data, err := runtime.Encode(codec, obj) - obj2, gvk, err2 := codec.Decode(data, nil, nil) - if err != nil || err2 != nil { - t.Fatalf("Failure: '%v' '%v'", err, err2) - } - if _, ok := obj2.(*runtimetesting.InternalSimple); !ok { - t.Fatalf("Got wrong type") - } - if !reflect.DeepEqual(obj2, test) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", test, obj2) - } - if *gvk != externalGVK { - t.Errorf("unexpected gvk returned by decode: %#v", *gvk) - } -} - -func TestUnversionedTypes(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - internalGVK := internalGV.WithKind("Simple") - externalGV := schema.GroupVersion{Group: "test.group", Version: "testExternal"} - externalGVK := externalGV.WithKind("Simple") - otherGV := schema.GroupVersion{Group: "group", Version: "other"} - - scheme := runtime.NewScheme() - scheme.AddUnversionedTypes(externalGV, &runtimetesting.InternalSimple{}) - scheme.AddKnownTypeWithName(internalGVK, &runtimetesting.InternalSimple{}) - scheme.AddKnownTypeWithName(externalGVK, &runtimetesting.ExternalSimple{}) - scheme.AddKnownTypeWithName(otherGV.WithKind("Simple"), &runtimetesting.ExternalSimple{}) - - codec := serializer.NewCodecFactory(scheme).LegacyCodec(externalGV) - - if unv, ok := scheme.IsUnversioned(&runtimetesting.InternalSimple{}); !unv || !ok { - t.Fatalf("type not unversioned and in scheme: %t %t", unv, ok) - } - - kinds, _, err := scheme.ObjectKinds(&runtimetesting.InternalSimple{}) - if err != nil { - t.Fatal(err) - } - kind := kinds[0] - if kind != externalGV.WithKind("InternalSimple") { - t.Fatalf("unexpected: %#v", kind) - } - - test := &runtimetesting.InternalSimple{ - TestString: "I'm the same", - } - obj := runtime.Object(test) - data, err := runtime.Encode(codec, obj) - if err != nil { - t.Fatal(err) - } - obj2, gvk, err := codec.Decode(data, nil, nil) - if err != nil { - t.Fatal(err) - } - if _, ok := obj2.(*runtimetesting.InternalSimple); !ok { - t.Fatalf("Got wrong type") - } - if !reflect.DeepEqual(obj2, test) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", test, obj2) - } - // object is serialized as an unversioned object (in the group and version it was defined in) - if *gvk != externalGV.WithKind("InternalSimple") { - t.Errorf("unexpected gvk returned by decode: %#v", *gvk) - } - - // when serialized to a different group, the object is kept in its preferred name - codec = serializer.NewCodecFactory(scheme).LegacyCodec(otherGV) - data, err = runtime.Encode(codec, obj) - if err != nil { - t.Fatal(err) - } - if string(data) != `{"apiVersion":"test.group/testExternal","kind":"InternalSimple","testString":"I'm the same"}`+"\n" { - t.Errorf("unexpected data: %s", data) - } -} - -// TestObjectFuzzer can randomly populate all the above objects. -var TestObjectFuzzer = fuzz.New().NilChance(.5).NumElements(1, 100).Funcs( - func(j *runtimetesting.MyWeirdCustomEmbeddedVersionKindField, c fuzz.Continue) { - // We have to customize the randomization of MyWeirdCustomEmbeddedVersionKindFields because their - // APIVersion and Kind must remain blank in memory. - j.APIVersion = "" - j.ObjectKind = "" - j.ID = c.RandString() - }, -) - -// Returns a new Scheme set up with the test objects. -func GetTestScheme() *runtime.Scheme { - internalGV := schema.GroupVersion{Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Version: "v1"} - alternateExternalGV := schema.GroupVersion{Group: "custom", Version: "v1"} - alternateInternalGV := schema.GroupVersion{Group: "custom", Version: runtime.APIVersionInternal} - differentExternalGV := schema.GroupVersion{Group: "other", Version: "v2"} - - s := runtime.NewScheme() - // Ordinarily, we wouldn't add TestType2, but because this is a test and - // both types are from the same package, we need to get it into the system - // so that converter will match it with ExternalType2. - s.AddKnownTypes(internalGV, &runtimetesting.TestType1{}, &runtimetesting.TestType2{}, &runtimetesting.ExternalInternalSame{}) - s.AddKnownTypes(externalGV, &runtimetesting.ExternalInternalSame{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType1"), &runtimetesting.ExternalTestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType2"), &runtimetesting.ExternalTestType2{}) - s.AddKnownTypeWithName(internalGV.WithKind("TestType3"), &runtimetesting.TestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType3"), &runtimetesting.ExternalTestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType4"), &runtimetesting.ExternalTestType1{}) - s.AddKnownTypeWithName(alternateInternalGV.WithKind("TestType3"), &runtimetesting.TestType1{}) - s.AddKnownTypeWithName(alternateExternalGV.WithKind("TestType3"), &runtimetesting.ExternalTestType1{}) - s.AddKnownTypeWithName(alternateExternalGV.WithKind("TestType5"), &runtimetesting.ExternalTestType1{}) - s.AddKnownTypeWithName(differentExternalGV.WithKind("TestType1"), &runtimetesting.ExternalTestType1{}) - s.AddUnversionedTypes(externalGV, &runtimetesting.UnversionedType{}) - - s.AddConversionFuncs(func(in *runtimetesting.TestType1, out *runtimetesting.ExternalTestType1, s conversion.Scope) { - out.A = in.A - }) - return s -} - -func TestKnownTypes(t *testing.T) { - s := GetTestScheme() - if len(s.KnownTypes(schema.GroupVersion{Group: "group", Version: "v2"})) != 0 { - t.Errorf("should have no known types for v2") - } - - types := s.KnownTypes(schema.GroupVersion{Version: "v1"}) - for _, s := range []string{"TestType1", "TestType2", "TestType3", "ExternalInternalSame"} { - if _, ok := types[s]; !ok { - t.Errorf("missing type %q", s) - } - } -} - -func TestAddKnownTypesIdemPotent(t *testing.T) { - s := runtime.NewScheme() - - gv := schema.GroupVersion{Group: "foo", Version: "v1"} - s.AddKnownTypes(gv, &runtimetesting.InternalSimple{}) - s.AddKnownTypes(gv, &runtimetesting.InternalSimple{}) - if len(s.KnownTypes(gv)) != 1 { - t.Errorf("expected only one %v type after double registration", gv) - } - if len(s.AllKnownTypes()) != 1 { - t.Errorf("expected only one type after double registration") - } - - s.AddKnownTypeWithName(gv.WithKind("InternalSimple"), &runtimetesting.InternalSimple{}) - s.AddKnownTypeWithName(gv.WithKind("InternalSimple"), &runtimetesting.InternalSimple{}) - if len(s.KnownTypes(gv)) != 1 { - t.Errorf("expected only one %v type after double registration with custom name", gv) - } - if len(s.AllKnownTypes()) != 1 { - t.Errorf("expected only one type after double registration with custom name") - } - - s.AddUnversionedTypes(gv, &runtimetesting.InternalSimple{}) - s.AddUnversionedTypes(gv, &runtimetesting.InternalSimple{}) - if len(s.KnownTypes(gv)) != 1 { - t.Errorf("expected only one %v type after double registration with custom name", gv) - } - if len(s.AllKnownTypes()) != 1 { - t.Errorf("expected only one type after double registration with custom name") - } - - kinds, _, err := s.ObjectKinds(&runtimetesting.InternalSimple{}) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if len(kinds) != 1 { - t.Errorf("expected only one kind for InternalSimple after double registration") - } -} - -// redefine InternalSimple with the same name, but obviously as a different type than in runtimetesting -type InternalSimple struct { - runtime.TypeMeta `json:",inline"` - TestString string `json:"testString"` -} - -func (s *InternalSimple) DeepCopyObject() runtime.Object { return nil } - -func TestConflictingAddKnownTypes(t *testing.T) { - s := runtime.NewScheme() - gv := schema.GroupVersion{Group: "foo", Version: "v1"} - - panicked := make(chan bool) - go func() { - defer func() { - if recover() != nil { - panicked <- true - } - }() - s.AddKnownTypeWithName(gv.WithKind("InternalSimple"), &runtimetesting.InternalSimple{}) - s.AddKnownTypeWithName(gv.WithKind("InternalSimple"), &runtimetesting.ExternalSimple{}) - panicked <- false - }() - if !<-panicked { - t.Errorf("Expected AddKnownTypesWithName to panic with conflicting type registrations") - } - - go func() { - defer func() { - if recover() != nil { - panicked <- true - } - }() - - s.AddUnversionedTypes(gv, &runtimetesting.InternalSimple{}) - s.AddUnversionedTypes(gv, &InternalSimple{}) - panicked <- false - }() - if !<-panicked { - t.Errorf("Expected AddUnversionedTypes to panic with conflicting type registrations") - } -} - -func TestConvertToVersionBasic(t *testing.T) { - s := GetTestScheme() - tt := &runtimetesting.TestType1{A: "I'm not a pointer object"} - other, err := s.ConvertToVersion(tt, schema.GroupVersion{Version: "v1"}) - if err != nil { - t.Fatalf("Failure: %v", err) - } - converted, ok := other.(*runtimetesting.ExternalTestType1) - if !ok { - t.Fatalf("Got wrong type: %T", other) - } - if tt.A != converted.A { - t.Fatalf("Failed to convert object correctly: %#v", converted) - } -} - -type testGroupVersioner struct { - target schema.GroupVersionKind - ok bool -} - -func (m testGroupVersioner) KindForGroupVersionKinds(kinds []schema.GroupVersionKind) (schema.GroupVersionKind, bool) { - return m.target, m.ok -} - -func TestConvertToVersion(t *testing.T) { - testCases := []struct { - scheme *runtime.Scheme - in runtime.Object - gv runtime.GroupVersioner - same bool - out runtime.Object - errFn func(error) bool - }{ - // errors if the type is not registered in the scheme - { - scheme: GetTestScheme(), - in: &runtimetesting.UnknownType{}, - errFn: func(err error) bool { return err != nil && runtime.IsNotRegisteredError(err) }, - }, - // errors if the group versioner returns no target - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: testGroupVersioner{}, - errFn: func(err error) bool { - return err != nil && strings.Contains(err.Error(), "is not suitable for converting") - }, - }, - // converts to internal - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: schema.GroupVersion{Version: runtime.APIVersionInternal}, - out: &runtimetesting.TestType1{A: "test"}, - }, - // converts from unstructured to internal - { - scheme: GetTestScheme(), - in: &runtimetesting.Unstructured{Object: map[string]interface{}{ - "apiVersion": "custom/v1", - "kind": "TestType3", - "A": "test", - }}, - gv: schema.GroupVersion{Version: runtime.APIVersionInternal}, - out: &runtimetesting.TestType1{A: "test"}, - }, - // converts from unstructured to external - { - scheme: GetTestScheme(), - in: &runtimetesting.Unstructured{Object: map[string]interface{}{ - "apiVersion": "custom/v1", - "kind": "TestType3", - "A": "test", - }}, - gv: schema.GroupVersion{Group: "custom", Version: "v1"}, - out: &runtimetesting.ExternalTestType1{MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "custom/v1", ObjectKind: "TestType3"}, A: "test"}, - }, - // prefers the best match - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: schema.GroupVersions{{Version: runtime.APIVersionInternal}, {Version: "v1"}}, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "v1", ObjectKind: "TestType1"}, - A: "test", - }, - }, - // unversioned type returned as-is - { - scheme: GetTestScheme(), - in: &runtimetesting.UnversionedType{A: "test"}, - gv: schema.GroupVersions{{Version: "v1"}}, - same: true, - out: &runtimetesting.UnversionedType{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "v1", ObjectKind: "UnversionedType"}, - A: "test", - }, - }, - // unversioned type returned when not included in the target types - { - scheme: GetTestScheme(), - in: &runtimetesting.UnversionedType{A: "test"}, - gv: schema.GroupVersions{{Group: "other", Version: "v2"}}, - same: true, - out: &runtimetesting.UnversionedType{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "v1", ObjectKind: "UnversionedType"}, - A: "test", - }, - }, - // detected as already being in the target version - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: schema.GroupVersions{{Version: "v1"}}, - same: true, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "v1", ObjectKind: "TestType1"}, - A: "test", - }, - }, - // detected as already being in the first target version - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: schema.GroupVersions{{Version: "v1"}, {Version: runtime.APIVersionInternal}}, - same: true, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "v1", ObjectKind: "TestType1"}, - A: "test", - }, - }, - // detected as already being in the first target version - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: schema.GroupVersions{{Version: "v1"}, {Version: runtime.APIVersionInternal}}, - same: true, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "v1", ObjectKind: "TestType1"}, - A: "test", - }, - }, - // the external type is registered in multiple groups, versions, and kinds, and can be targeted to all of them (1/3): different kind - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: testGroupVersioner{ok: true, target: schema.GroupVersionKind{Kind: "TestType3", Version: "v1"}}, - same: true, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "v1", ObjectKind: "TestType3"}, - A: "test", - }, - }, - // the external type is registered in multiple groups, versions, and kinds, and can be targeted to all of them (2/3): different gv - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: testGroupVersioner{ok: true, target: schema.GroupVersionKind{Kind: "TestType3", Group: "custom", Version: "v1"}}, - same: true, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "custom/v1", ObjectKind: "TestType3"}, - A: "test", - }, - }, - // the external type is registered in multiple groups, versions, and kinds, and can be targeted to all of them (3/3): different gvk - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: testGroupVersioner{ok: true, target: schema.GroupVersionKind{Group: "custom", Version: "v1", Kind: "TestType5"}}, - same: true, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "custom/v1", ObjectKind: "TestType5"}, - A: "test", - }, - }, - // multi group versioner recognizes multiple groups and forces the output to a particular version, copies because version differs - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: runtime.NewMultiGroupVersioner(schema.GroupVersion{Group: "other", Version: "v2"}, schema.GroupKind{Group: "custom", Kind: "TestType3"}, schema.GroupKind{Kind: "TestType1"}), - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "other/v2", ObjectKind: "TestType1"}, - A: "test", - }, - }, - // multi group versioner recognizes multiple groups and forces the output to a particular version, copies because version differs - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: runtime.NewMultiGroupVersioner(schema.GroupVersion{Group: "other", Version: "v2"}, schema.GroupKind{Kind: "TestType1"}, schema.GroupKind{Group: "custom", Kind: "TestType3"}), - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "other/v2", ObjectKind: "TestType1"}, - A: "test", - }, - }, - // multi group versioner is unable to find a match when kind AND group don't match (there is no TestType1 kind in group "other", and no kind "TestType5" in the default group) - { - scheme: GetTestScheme(), - in: &runtimetesting.TestType1{A: "test"}, - gv: runtime.NewMultiGroupVersioner(schema.GroupVersion{Group: "custom", Version: "v1"}, schema.GroupKind{Group: "other"}, schema.GroupKind{Kind: "TestType5"}), - errFn: func(err error) bool { - return err != nil && strings.Contains(err.Error(), "is not suitable for converting") - }, - }, - // multi group versioner recognizes multiple groups and forces the output to a particular version, performs no copy - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: runtime.NewMultiGroupVersioner(schema.GroupVersion{Group: "", Version: "v1"}, schema.GroupKind{Group: "custom", Kind: "TestType3"}, schema.GroupKind{Kind: "TestType1"}), - same: true, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "v1", ObjectKind: "TestType1"}, - A: "test", - }, - }, - // multi group versioner recognizes multiple groups and forces the output to a particular version, performs no copy - { - scheme: GetTestScheme(), - in: &runtimetesting.ExternalTestType1{A: "test"}, - gv: runtime.NewMultiGroupVersioner(schema.GroupVersion{Group: "", Version: "v1"}, schema.GroupKind{Kind: "TestType1"}, schema.GroupKind{Group: "custom", Kind: "TestType3"}), - same: true, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "v1", ObjectKind: "TestType1"}, - A: "test", - }, - }, - // group versioner can choose a particular target kind for a given input when kind is the same across group versions - { - scheme: GetTestScheme(), - in: &runtimetesting.TestType1{A: "test"}, - gv: testGroupVersioner{ok: true, target: schema.GroupVersionKind{Version: "v1", Kind: "TestType3"}}, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "v1", ObjectKind: "TestType3"}, - A: "test", - }, - }, - // group versioner can choose a different kind - { - scheme: GetTestScheme(), - in: &runtimetesting.TestType1{A: "test"}, - gv: testGroupVersioner{ok: true, target: schema.GroupVersionKind{Kind: "TestType5", Group: "custom", Version: "v1"}}, - out: &runtimetesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: runtimetesting.MyWeirdCustomEmbeddedVersionKindField{APIVersion: "custom/v1", ObjectKind: "TestType5"}, - A: "test", - }, - }, - } - for i, test := range testCases { - t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { - original := test.in.DeepCopyObject() - out, err := test.scheme.ConvertToVersion(test.in, test.gv) - switch { - case test.errFn != nil: - if !test.errFn(err) { - t.Fatalf("unexpected error: %v", err) - } - return - case err != nil: - t.Fatalf("unexpected error: %v", err) - } - if out == test.in { - t.Fatalf("ConvertToVersion should always copy out: %#v", out) - } - - if test.same { - if !reflect.DeepEqual(original, test.in) { - t.Fatalf("unexpected mutation of input: %s", diff.ObjectReflectDiff(original, test.in)) - } - if !reflect.DeepEqual(out, test.out) { - t.Fatalf("unexpected out: %s", diff.ObjectReflectDiff(out, test.out)) - } - unsafe, err := test.scheme.UnsafeConvertToVersion(test.in, test.gv) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !reflect.DeepEqual(unsafe, test.out) { - t.Fatalf("unexpected unsafe: %s", diff.ObjectReflectDiff(unsafe, test.out)) - } - if unsafe != test.in { - t.Fatalf("UnsafeConvertToVersion should return same object: %#v", unsafe) - } - return - } - if !reflect.DeepEqual(out, test.out) { - t.Fatalf("unexpected out: %s", diff.ObjectReflectDiff(out, test.out)) - } - }) - } -} - -func TestConvert(t *testing.T) { - testCases := []struct { - scheme *runtime.Scheme - in runtime.Object - into runtime.Object - gv runtime.GroupVersioner - out runtime.Object - errFn func(error) bool - }{ - // converts from internal to unstructured, given a target version - { - scheme: GetTestScheme(), - in: &runtimetesting.TestType1{A: "test"}, - into: &runtimetesting.Unstructured{}, - out: &runtimetesting.Unstructured{Object: map[string]interface{}{ - "myVersionKey": "custom/v1", - "myKindKey": "TestType3", - "A": "test", - }}, - gv: schema.GroupVersion{Group: "custom", Version: "v1"}, - }, - } - for i, test := range testCases { - t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { - err := test.scheme.Convert(test.in, test.into, test.gv) - switch { - case test.errFn != nil: - if !test.errFn(err) { - t.Fatalf("unexpected error: %v", err) - } - return - case err != nil: - t.Fatalf("unexpected error: %v", err) - return - } - - if !reflect.DeepEqual(test.into, test.out) { - t.Fatalf("unexpected out: %s", diff.ObjectReflectDiff(test.into, test.out)) - } - }) - } -} - -func TestMetaValues(t *testing.T) { - internalGV := schema.GroupVersion{Group: "test.group", Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Group: "test.group", Version: "externalVersion"} - - s := runtime.NewScheme() - s.AddKnownTypeWithName(internalGV.WithKind("Simple"), &runtimetesting.InternalSimple{}) - s.AddKnownTypeWithName(externalGV.WithKind("Simple"), &runtimetesting.ExternalSimple{}) - - internalToExternalCalls := 0 - externalToInternalCalls := 0 - - // Register functions to verify that scope.Meta() gets set correctly. - err := s.AddConversionFuncs( - func(in *runtimetesting.InternalSimple, out *runtimetesting.ExternalSimple, scope conversion.Scope) error { - t.Logf("internal -> external") - scope.Convert(&in.TestString, &out.TestString, 0) - internalToExternalCalls++ - return nil - }, - func(in *runtimetesting.ExternalSimple, out *runtimetesting.InternalSimple, scope conversion.Scope) error { - t.Logf("external -> internal") - scope.Convert(&in.TestString, &out.TestString, 0) - externalToInternalCalls++ - return nil - }, - ) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - simple := &runtimetesting.InternalSimple{ - TestString: "foo", - } - - s.Log(t) - - out, err := s.ConvertToVersion(simple, externalGV) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - internal, err := s.ConvertToVersion(out, internalGV) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - if e, a := simple, internal; !reflect.DeepEqual(e, a) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", e, a) - } - - if e, a := 1, internalToExternalCalls; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - if e, a := 1, externalToInternalCalls; e != a { - t.Errorf("Expected %v, got %v", e, a) - } -} - -func TestMetaValuesUnregisteredConvert(t *testing.T) { - type InternalSimple struct { - Version string `json:"apiVersion,omitempty"` - Kind string `json:"kind,omitempty"` - TestString string `json:"testString"` - } - type ExternalSimple struct { - Version string `json:"apiVersion,omitempty"` - Kind string `json:"kind,omitempty"` - TestString string `json:"testString"` - } - s := runtime.NewScheme() - // We deliberately don't register the types. - - internalToExternalCalls := 0 - - // Register functions to verify that scope.Meta() gets set correctly. - err := s.AddConversionFuncs( - func(in *InternalSimple, out *ExternalSimple, scope conversion.Scope) error { - scope.Convert(&in.TestString, &out.TestString, 0) - internalToExternalCalls++ - return nil - }, - ) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - simple := &InternalSimple{TestString: "foo"} - external := &ExternalSimple{} - err = s.Convert(simple, external, nil) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if e, a := simple.TestString, external.TestString; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - - // Verify that our conversion handler got called. - if e, a := 1, internalToExternalCalls; e != a { - t.Errorf("Expected %v, got %v", e, a) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/BUILD b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/BUILD deleted file mode 100644 index bc4cf8ec14..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/BUILD +++ /dev/null @@ -1,64 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["codec_test.go"], - embed = [":go_default_library"], - deps = [ - "//vendor/github.com/ghodss/yaml:go_default_library", - "//vendor/github.com/google/gofuzz:go_default_library", - "//vendor/github.com/spf13/pflag:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/conversion:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer/testing:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/diff:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "codec_factory.go", - "negotiated_codec.go", - "protobuf_extension.go", - ], - importpath = "k8s.io/apimachinery/pkg/runtime/serializer", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer/json:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/serializer/json:all-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/serializer/protobuf:all-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/serializer/recognizer:all-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/serializer/streaming:all-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/serializer/testing:all-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/serializer/versioning:all-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/serializer/yaml:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_test.go deleted file mode 100644 index d27da113a9..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/codec_test.go +++ /dev/null @@ -1,339 +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 serializer - -import ( - "encoding/json" - "fmt" - "log" - "os" - "reflect" - "strings" - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/conversion" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - serializertesting "k8s.io/apimachinery/pkg/runtime/serializer/testing" - "k8s.io/apimachinery/pkg/util/diff" - - "github.com/ghodss/yaml" - "github.com/google/gofuzz" - flag "github.com/spf13/pflag" -) - -var fuzzIters = flag.Int("fuzz-iters", 50, "How many fuzzing iterations to do.") - -type testMetaFactory struct{} - -func (testMetaFactory) Interpret(data []byte) (*schema.GroupVersionKind, error) { - findKind := struct { - APIVersion string `json:"myVersionKey,omitempty"` - ObjectKind string `json:"myKindKey,omitempty"` - }{} - // yaml is a superset of json, so we use it to decode here. That way, - // we understand both. - if err := yaml.Unmarshal(data, &findKind); err != nil { - return nil, fmt.Errorf("couldn't get version/kind: %v", err) - } - gv, err := schema.ParseGroupVersion(findKind.APIVersion) - if err != nil { - return nil, err - } - return &schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: findKind.ObjectKind}, nil -} - -// TestObjectFuzzer can randomly populate all the above objects. -var TestObjectFuzzer = fuzz.New().NilChance(.5).NumElements(1, 100).Funcs( - func(j *serializertesting.MyWeirdCustomEmbeddedVersionKindField, c fuzz.Continue) { - c.FuzzNoCustom(j) - j.APIVersion = "" - j.ObjectKind = "" - }, -) - -// Returns a new Scheme set up with the test objects. -func GetTestScheme() (*runtime.Scheme, runtime.Codec) { - internalGV := schema.GroupVersion{Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Version: "v1"} - externalGV2 := schema.GroupVersion{Version: "v2"} - - s := runtime.NewScheme() - // Ordinarily, we wouldn't add TestType2, but because this is a test and - // both types are from the same package, we need to get it into the system - // so that converter will match it with ExternalType2. - s.AddKnownTypes(internalGV, &serializertesting.TestType1{}, &serializertesting.TestType2{}, &serializertesting.ExternalInternalSame{}) - s.AddKnownTypes(externalGV, &serializertesting.ExternalInternalSame{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType1"), &serializertesting.ExternalTestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType2"), &serializertesting.ExternalTestType2{}) - s.AddKnownTypeWithName(internalGV.WithKind("TestType3"), &serializertesting.TestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("TestType3"), &serializertesting.ExternalTestType1{}) - s.AddKnownTypeWithName(externalGV2.WithKind("TestType1"), &serializertesting.ExternalTestType1{}) - - s.AddUnversionedTypes(externalGV, &metav1.Status{}) - - cf := newCodecFactory(s, newSerializersForScheme(s, testMetaFactory{})) - codec := cf.LegacyCodec(schema.GroupVersion{Version: "v1"}) - return s, codec -} - -var semantic = conversion.EqualitiesOrDie( - func(a, b serializertesting.MyWeirdCustomEmbeddedVersionKindField) bool { - a.APIVersion, a.ObjectKind = "", "" - b.APIVersion, b.ObjectKind = "", "" - return a == b - }, -) - -func runTest(t *testing.T, source interface{}) { - name := reflect.TypeOf(source).Elem().Name() - TestObjectFuzzer.Fuzz(source) - - _, codec := GetTestScheme() - data, err := runtime.Encode(codec, source.(runtime.Object)) - if err != nil { - t.Errorf("%v: %v (%#v)", name, err, source) - return - } - obj2, err := runtime.Decode(codec, data) - if err != nil { - t.Errorf("%v: %v (%v)", name, err, string(data)) - return - } - if !semantic.DeepEqual(source, obj2) { - t.Errorf("1: %v: diff: %v", name, diff.ObjectGoPrintSideBySide(source, obj2)) - return - } - obj3 := reflect.New(reflect.TypeOf(source).Elem()).Interface() - if err := runtime.DecodeInto(codec, data, obj3.(runtime.Object)); err != nil { - t.Errorf("2: %v: %v", name, err) - return - } - if !semantic.DeepEqual(source, obj3) { - t.Errorf("3: %v: diff: %v", name, diff.ObjectDiff(source, obj3)) - return - } -} - -func TestTypes(t *testing.T) { - table := []interface{}{ - &serializertesting.TestType1{}, - &serializertesting.ExternalInternalSame{}, - } - for _, item := range table { - // Try a few times, since runTest uses random values. - for i := 0; i < *fuzzIters; i++ { - runTest(t, item) - } - } -} - -func TestVersionedEncoding(t *testing.T) { - s, _ := GetTestScheme() - cf := newCodecFactory(s, newSerializersForScheme(s, testMetaFactory{})) - info, _ := runtime.SerializerInfoForMediaType(cf.SupportedMediaTypes(), runtime.ContentTypeJSON) - encoder := info.Serializer - - codec := cf.CodecForVersions(encoder, nil, schema.GroupVersion{Version: "v2"}, nil) - out, err := runtime.Encode(codec, &serializertesting.TestType1{}) - if err != nil { - t.Fatal(err) - } - if string(out) != `{"myVersionKey":"v2","myKindKey":"TestType1"}`+"\n" { - t.Fatal(string(out)) - } - - codec = cf.CodecForVersions(encoder, nil, schema.GroupVersion{Version: "v3"}, nil) - _, err = runtime.Encode(codec, &serializertesting.TestType1{}) - if err == nil { - t.Fatal(err) - } - - // unversioned encode with no versions is written directly to wire - codec = cf.CodecForVersions(encoder, nil, runtime.InternalGroupVersioner, nil) - out, err = runtime.Encode(codec, &serializertesting.TestType1{}) - if err != nil { - t.Fatal(err) - } - if string(out) != `{}`+"\n" { - t.Fatal(string(out)) - } -} - -func TestMultipleNames(t *testing.T) { - _, codec := GetTestScheme() - - obj, _, err := codec.Decode([]byte(`{"myKindKey":"TestType3","myVersionKey":"v1","A":"value"}`), nil, nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - internal := obj.(*serializertesting.TestType1) - if internal.A != "value" { - t.Fatalf("unexpected decoded object: %#v", internal) - } - - out, err := runtime.Encode(codec, internal) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !strings.Contains(string(out), `"myKindKey":"TestType1"`) { - t.Errorf("unexpected encoded output: %s", string(out)) - } -} - -func TestConvertTypesWhenDefaultNamesMatch(t *testing.T) { - internalGV := schema.GroupVersion{Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Version: "v1"} - - s := runtime.NewScheme() - // create two names internally, with TestType1 being preferred - s.AddKnownTypeWithName(internalGV.WithKind("TestType1"), &serializertesting.TestType1{}) - s.AddKnownTypeWithName(internalGV.WithKind("OtherType1"), &serializertesting.TestType1{}) - // create two names externally, with TestType1 being preferred - s.AddKnownTypeWithName(externalGV.WithKind("TestType1"), &serializertesting.ExternalTestType1{}) - s.AddKnownTypeWithName(externalGV.WithKind("OtherType1"), &serializertesting.ExternalTestType1{}) - - ext := &serializertesting.ExternalTestType1{} - ext.APIVersion = "v1" - ext.ObjectKind = "OtherType1" - ext.A = "test" - data, err := json.Marshal(ext) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - expect := &serializertesting.TestType1{A: "test"} - - codec := newCodecFactory(s, newSerializersForScheme(s, testMetaFactory{})).LegacyCodec(schema.GroupVersion{Version: "v1"}) - - obj, err := runtime.Decode(codec, data) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !semantic.DeepEqual(expect, obj) { - t.Errorf("unexpected object: %#v", obj) - } - - into := &serializertesting.TestType1{} - if err := runtime.DecodeInto(codec, data, into); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if !semantic.DeepEqual(expect, into) { - t.Errorf("unexpected object: %#v", obj) - } -} - -func TestEncode_Ptr(t *testing.T) { - _, codec := GetTestScheme() - tt := &serializertesting.TestType1{A: "I am a pointer object"} - data, err := runtime.Encode(codec, tt) - obj2, err2 := runtime.Decode(codec, data) - if err != nil || err2 != nil { - t.Fatalf("Failure: '%v' '%v'\n%s", err, err2, data) - } - if _, ok := obj2.(*serializertesting.TestType1); !ok { - t.Fatalf("Got wrong type") - } - if !semantic.DeepEqual(obj2, tt) { - t.Errorf("Expected:\n %#v,\n Got:\n %#v", tt, obj2) - } -} - -func TestBadJSONRejection(t *testing.T) { - log.SetOutput(os.Stderr) - _, codec := GetTestScheme() - badJSONs := [][]byte{ - []byte(`{"myVersionKey":"v1"}`), // Missing kind - []byte(`{"myVersionKey":"v1","myKindKey":"bar"}`), // Unknown kind - []byte(`{"myVersionKey":"bar","myKindKey":"TestType1"}`), // Unknown version - []byte(`{"myKindKey":"TestType1"}`), // Missing version - } - for _, b := range badJSONs { - if _, err := runtime.Decode(codec, b); err == nil { - t.Errorf("Did not reject bad json: %s", string(b)) - } - } - badJSONKindMismatch := []byte(`{"myVersionKey":"v1","myKindKey":"ExternalInternalSame"}`) - if err := runtime.DecodeInto(codec, badJSONKindMismatch, &serializertesting.TestType1{}); err == nil { - t.Errorf("Kind is set but doesn't match the object type: %s", badJSONKindMismatch) - } - if err := runtime.DecodeInto(codec, []byte(``), &serializertesting.TestType1{}); err != nil { - t.Errorf("Should allow empty decode: %v", err) - } - if _, _, err := codec.Decode([]byte(``), &schema.GroupVersionKind{Kind: "ExternalInternalSame"}, nil); err == nil { - t.Errorf("Did not give error for empty data with only kind default") - } - if _, _, err := codec.Decode([]byte(`{"myVersionKey":"v1"}`), &schema.GroupVersionKind{Kind: "ExternalInternalSame"}, nil); err != nil { - t.Errorf("Gave error for version and kind default") - } - if _, _, err := codec.Decode([]byte(`{"myKindKey":"ExternalInternalSame"}`), &schema.GroupVersionKind{Version: "v1"}, nil); err != nil { - t.Errorf("Gave error for version and kind default") - } - if _, _, err := codec.Decode([]byte(``), &schema.GroupVersionKind{Kind: "ExternalInternalSame", Version: "v1"}, nil); err != nil { - t.Errorf("Gave error for version and kind defaulted: %v", err) - } - if _, err := runtime.Decode(codec, []byte(``)); err == nil { - t.Errorf("Did not give error for empty data") - } -} - -// Returns a new Scheme set up with the test objects needed by TestDirectCodec. -func GetDirectCodecTestScheme() *runtime.Scheme { - internalGV := schema.GroupVersion{Version: runtime.APIVersionInternal} - externalGV := schema.GroupVersion{Version: "v1"} - - s := runtime.NewScheme() - // Ordinarily, we wouldn't add TestType2, but because this is a test and - // both types are from the same package, we need to get it into the system - // so that converter will match it with ExternalType2. - s.AddKnownTypes(internalGV, &serializertesting.TestType1{}) - s.AddKnownTypes(externalGV, &serializertesting.ExternalTestType1{}) - - s.AddUnversionedTypes(externalGV, &metav1.Status{}) - return s -} - -func TestDirectCodec(t *testing.T) { - s := GetDirectCodecTestScheme() - cf := newCodecFactory(s, newSerializersForScheme(s, testMetaFactory{})) - info, _ := runtime.SerializerInfoForMediaType(cf.SupportedMediaTypes(), runtime.ContentTypeJSON) - serializer := info.Serializer - df := DirectCodecFactory{cf} - ignoredGV, err := schema.ParseGroupVersion("ignored group/ignored version") - if err != nil { - t.Fatal(err) - } - directEncoder := df.EncoderForVersion(serializer, ignoredGV) - directDecoder := df.DecoderToVersion(serializer, ignoredGV) - out, err := runtime.Encode(directEncoder, &serializertesting.ExternalTestType1{}) - if err != nil { - t.Fatal(err) - } - if string(out) != `{"myVersionKey":"v1","myKindKey":"ExternalTestType1"}`+"\n" { - t.Fatal(string(out)) - } - a, _, err := directDecoder.Decode(out, nil, nil) - e := &serializertesting.ExternalTestType1{ - MyWeirdCustomEmbeddedVersionKindField: serializertesting.MyWeirdCustomEmbeddedVersionKindField{ - APIVersion: "v1", - ObjectKind: "ExternalTestType1", - }, - } - if !semantic.DeepEqual(e, a) { - t.Fatalf("expect %v, got %v", e, a) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/BUILD b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/BUILD deleted file mode 100644 index 7be13ed471..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/BUILD +++ /dev/null @@ -1,55 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["meta_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "json.go", - "meta.go", - ], - importpath = "k8s.io/apimachinery/pkg/runtime/serializer/json", - deps = [ - "//vendor/github.com/ghodss/yaml:go_default_library", - "//vendor/github.com/json-iterator/go:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/framer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/yaml:go_default_library", - ], -) - -go_test( - name = "go_default_xtest", - srcs = ["json_test.go"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer/json:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/diff:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json_test.go deleted file mode 100644 index c8ae5550c5..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/json_test.go +++ /dev/null @@ -1,293 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package json_test - -import ( - "fmt" - "reflect" - "strings" - "testing" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/runtime/serializer/json" - "k8s.io/apimachinery/pkg/util/diff" -) - -type testDecodable struct { - Other string - Value int `json:"value"` - gvk schema.GroupVersionKind -} - -func (d *testDecodable) GetObjectKind() schema.ObjectKind { return d } -func (d *testDecodable) SetGroupVersionKind(gvk schema.GroupVersionKind) { d.gvk = gvk } -func (d *testDecodable) GroupVersionKind() schema.GroupVersionKind { return d.gvk } -func (d *testDecodable) DeepCopyObject() runtime.Object { - panic("testDecodable does not support DeepCopy") -} - -func TestDecode(t *testing.T) { - testCases := []struct { - creater runtime.ObjectCreater - typer runtime.ObjectTyper - yaml bool - pretty bool - - data []byte - defaultGVK *schema.GroupVersionKind - into runtime.Object - - errFn func(error) bool - expectedObject runtime.Object - expectedGVK *schema.GroupVersionKind - }{ - { - data: []byte("{}"), - - expectedGVK: &schema.GroupVersionKind{}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "Object 'Kind' is missing in") }, - }, - { - data: []byte("{}"), - defaultGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - creater: &mockCreater{err: fmt.Errorf("fake error")}, - - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - errFn: func(err error) bool { return err.Error() == "fake error" }, - }, - { - data: []byte("{}"), - defaultGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - creater: &mockCreater{obj: &testDecodable{}}, - expectedObject: &testDecodable{}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - }, - - // version without group is not defaulted - { - data: []byte(`{"apiVersion":"blah"}`), - defaultGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - creater: &mockCreater{obj: &testDecodable{}}, - expectedObject: &testDecodable{}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "", Version: "blah"}, - }, - // group without version is defaulted - { - data: []byte(`{"apiVersion":"other/"}`), - defaultGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - creater: &mockCreater{obj: &testDecodable{}}, - expectedObject: &testDecodable{}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - }, - // group version, kind is defaulted - { - data: []byte(`{"apiVersion":"other1/blah1"}`), - defaultGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - creater: &mockCreater{obj: &testDecodable{}}, - expectedObject: &testDecodable{}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other1", Version: "blah1"}, - }, - // gvk all provided then not defaulted at all - { - data: []byte(`{"kind":"Test","apiVersion":"other/blah"}`), - defaultGVK: &schema.GroupVersionKind{Kind: "Test1", Group: "other1", Version: "blah1"}, - creater: &mockCreater{obj: &testDecodable{}}, - expectedObject: &testDecodable{}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - }, - //gvk defaulting if kind not provided in data and defaultGVK use into's kind - { - data: []byte(`{"apiVersion":"b1/c1"}`), - into: &testDecodable{gvk: schema.GroupVersionKind{Kind: "a3", Group: "b1", Version: "c1"}}, - typer: &mockTyper{gvk: &schema.GroupVersionKind{Kind: "a3", Group: "b1", Version: "c1"}}, - defaultGVK: nil, - creater: &mockCreater{obj: &testDecodable{}}, - expectedObject: &testDecodable{gvk: schema.GroupVersionKind{Kind: "a3", Group: "b1", Version: "c1"}}, - expectedGVK: &schema.GroupVersionKind{Kind: "a3", Group: "b1", Version: "c1"}, - }, - - // accept runtime.Unknown as into and bypass creator - { - data: []byte(`{}`), - into: &runtime.Unknown{}, - - expectedGVK: &schema.GroupVersionKind{}, - expectedObject: &runtime.Unknown{ - Raw: []byte(`{}`), - ContentType: runtime.ContentTypeJSON, - }, - }, - { - data: []byte(`{"test":"object"}`), - into: &runtime.Unknown{}, - - expectedGVK: &schema.GroupVersionKind{}, - expectedObject: &runtime.Unknown{ - Raw: []byte(`{"test":"object"}`), - ContentType: runtime.ContentTypeJSON, - }, - }, - { - data: []byte(`{"test":"object"}`), - into: &runtime.Unknown{}, - defaultGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedObject: &runtime.Unknown{ - TypeMeta: runtime.TypeMeta{APIVersion: "other/blah", Kind: "Test"}, - Raw: []byte(`{"test":"object"}`), - ContentType: runtime.ContentTypeJSON, - }, - }, - - // unregistered objects can be decoded into directly - { - data: []byte(`{"kind":"Test","apiVersion":"other/blah","value":1,"Other":"test"}`), - into: &testDecodable{}, - typer: &mockTyper{err: runtime.NewNotRegisteredErrForKind(schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"})}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedObject: &testDecodable{ - Other: "test", - Value: 1, - }, - }, - // registered types get defaulted by the into object kind - { - data: []byte(`{"value":1,"Other":"test"}`), - into: &testDecodable{}, - typer: &mockTyper{gvk: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedObject: &testDecodable{ - Other: "test", - Value: 1, - }, - }, - // registered types get defaulted by the into object kind even without version, but return an error - { - data: []byte(`{"value":1,"Other":"test"}`), - into: &testDecodable{}, - typer: &mockTyper{gvk: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: ""}}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: ""}, - errFn: func(err error) bool { return strings.Contains(err.Error(), "Object 'apiVersion' is missing in") }, - expectedObject: &testDecodable{ - Other: "test", - Value: 1, - }, - }, - - // runtime.VersionedObjects are decoded - { - data: []byte(`{"value":1,"Other":"test"}`), - into: &runtime.VersionedObjects{Objects: []runtime.Object{}}, - creater: &mockCreater{obj: &testDecodable{}}, - typer: &mockTyper{gvk: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}}, - defaultGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedObject: &runtime.VersionedObjects{ - Objects: []runtime.Object{ - &testDecodable{ - Other: "test", - Value: 1, - }, - }, - }, - }, - // runtime.VersionedObjects with an object are decoded into - { - data: []byte(`{"Other":"test"}`), - into: &runtime.VersionedObjects{Objects: []runtime.Object{&testDecodable{Value: 2}}}, - typer: &mockTyper{gvk: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}}, - expectedGVK: &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"}, - expectedObject: &runtime.VersionedObjects{ - Objects: []runtime.Object{ - &testDecodable{ - Other: "test", - Value: 2, - }, - }, - }, - }, - } - - for i, test := range testCases { - var s runtime.Serializer - if test.yaml { - s = json.NewYAMLSerializer(json.DefaultMetaFactory, test.creater, test.typer) - } else { - s = json.NewSerializer(json.DefaultMetaFactory, test.creater, test.typer, test.pretty) - } - obj, gvk, err := s.Decode([]byte(test.data), test.defaultGVK, test.into) - - if !reflect.DeepEqual(test.expectedGVK, gvk) { - t.Errorf("%d: unexpected GVK: %v", i, gvk) - } - - switch { - case err == nil && test.errFn != nil: - t.Errorf("%d: failed: %v", i, err) - continue - case err != nil && test.errFn == nil: - t.Errorf("%d: failed: %v", i, err) - continue - case err != nil: - if !test.errFn(err) { - t.Errorf("%d: failed: %v", i, err) - } - if obj != nil { - t.Errorf("%d: should have returned nil object", i) - } - continue - } - - if test.into != nil && test.into != obj { - t.Errorf("%d: expected into to be returned: %v", i, obj) - continue - } - - if !reflect.DeepEqual(test.expectedObject, obj) { - t.Errorf("%d: unexpected object:\n%s", i, diff.ObjectGoPrintSideBySide(test.expectedObject, obj)) - } - } -} - -type mockCreater struct { - apiVersion string - kind string - err error - obj runtime.Object -} - -func (c *mockCreater) New(kind schema.GroupVersionKind) (runtime.Object, error) { - c.apiVersion, c.kind = kind.GroupVersion().String(), kind.Kind - return c.obj, c.err -} - -type mockTyper struct { - gvk *schema.GroupVersionKind - err error -} - -func (t *mockTyper) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error) { - if t.gvk == nil { - return nil, false, t.err - } - return []schema.GroupVersionKind{*t.gvk}, false, t.err -} - -func (t *mockTyper) Recognizes(_ schema.GroupVersionKind) bool { - return false -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/meta_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/meta_test.go deleted file mode 100644 index f4e34a22d5..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/json/meta_test.go +++ /dev/null @@ -1,45 +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 json - -import "testing" - -func TestSimpleMetaFactoryInterpret(t *testing.T) { - factory := SimpleMetaFactory{} - gvk, err := factory.Interpret([]byte(`{"apiVersion":"1","kind":"object"}`)) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if gvk.Version != "1" || gvk.Kind != "object" { - t.Errorf("unexpected interpret: %#v", gvk) - } - - // no kind or version - gvk, err = factory.Interpret([]byte(`{}`)) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if gvk.Version != "" || gvk.Kind != "" { - t.Errorf("unexpected interpret: %#v", gvk) - } - - // unparsable - gvk, err = factory.Interpret([]byte(`{`)) - if err == nil { - t.Errorf("unexpected non-error") - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/BUILD b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/BUILD deleted file mode 100644 index 3eb91d8626..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/protobuf/BUILD +++ /dev/null @@ -1,35 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "protobuf.go", - ], - importpath = "k8s.io/apimachinery/pkg/runtime/serializer/protobuf", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/framer:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/BUILD b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/BUILD deleted file mode 100644 index de54abb3d2..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/BUILD +++ /dev/null @@ -1,32 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = ["recognizer.go"], - importpath = "k8s.io/apimachinery/pkg/runtime/serializer/recognizer", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/runtime/serializer/recognizer/testing:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/BUILD b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/BUILD deleted file mode 100644 index e0589fef78..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/BUILD +++ /dev/null @@ -1,41 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["streaming_test.go"], - embed = [":go_default_library"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/framer:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = ["streaming.go"], - importpath = "k8s.io/apimachinery/pkg/runtime/serializer/streaming", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming_test.go deleted file mode 100644 index 9cae6a32c4..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/streaming/streaming_test.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright 2016 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 streaming - -import ( - "bytes" - "io" - "io/ioutil" - "testing" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/framer" -) - -type fakeDecoder struct { - got []byte - obj runtime.Object - err error -} - -func (d *fakeDecoder) Decode(data []byte, gvk *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) { - d.got = data - return d.obj, nil, d.err -} - -func TestEmptyDecoder(t *testing.T) { - buf := bytes.NewBuffer([]byte{}) - d := &fakeDecoder{} - _, _, err := NewDecoder(ioutil.NopCloser(buf), d).Decode(nil, nil) - if err != io.EOF { - t.Fatal(err) - } -} - -func TestDecoder(t *testing.T) { - frames := [][]byte{ - make([]byte, 1025), - make([]byte, 1024*5), - make([]byte, 1024*1024*5), - make([]byte, 1025), - } - pr, pw := io.Pipe() - fw := framer.NewLengthDelimitedFrameWriter(pw) - go func() { - for i := range frames { - fw.Write(frames[i]) - } - pw.Close() - }() - - r := framer.NewLengthDelimitedFrameReader(pr) - d := &fakeDecoder{} - dec := NewDecoder(r, d) - if _, _, err := dec.Decode(nil, nil); err != nil || !bytes.Equal(d.got, frames[0]) { - t.Fatalf("unexpected %v %v", err, len(d.got)) - } - if _, _, err := dec.Decode(nil, nil); err != nil || !bytes.Equal(d.got, frames[1]) { - t.Fatalf("unexpected %v %v", err, len(d.got)) - } - if _, _, err := dec.Decode(nil, nil); err != ErrObjectTooLarge || !bytes.Equal(d.got, frames[1]) { - t.Fatalf("unexpected %v %v", err, len(d.got)) - } - if _, _, err := dec.Decode(nil, nil); err != nil || !bytes.Equal(d.got, frames[3]) { - t.Fatalf("unexpected %v %v", err, len(d.got)) - } - if _, _, err := dec.Decode(nil, nil); err != io.EOF { - t.Fatalf("unexpected %v %v", err, len(d.got)) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/BUILD b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/BUILD deleted file mode 100644 index 32e6863c97..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/BUILD +++ /dev/null @@ -1,41 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["versioning_test.go"], - embed = [":go_default_library"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/diff:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = ["versioning.go"], - importpath = "k8s.io/apimachinery/pkg/runtime/serializer/versioning", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning_test.go deleted file mode 100644 index 43c2426578..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/serializer/versioning/versioning_test.go +++ /dev/null @@ -1,381 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package versioning - -import ( - "fmt" - "io" - "io/ioutil" - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/diff" -) - -type testDecodable struct { - Other string - Value int `json:"value"` - gvk schema.GroupVersionKind -} - -func (d *testDecodable) GetObjectKind() schema.ObjectKind { return d } -func (d *testDecodable) SetGroupVersionKind(gvk schema.GroupVersionKind) { d.gvk = gvk } -func (d *testDecodable) GroupVersionKind() schema.GroupVersionKind { return d.gvk } -func (d *testDecodable) DeepCopyObject() runtime.Object { - // no real deepcopy because these tests check for pointer equality - return d -} - -type testNestedDecodable struct { - Other string - Value int `json:"value"` - - gvk schema.GroupVersionKind - nestedCalled bool - nestedErr error -} - -func (d *testNestedDecodable) GetObjectKind() schema.ObjectKind { return d } -func (d *testNestedDecodable) SetGroupVersionKind(gvk schema.GroupVersionKind) { d.gvk = gvk } -func (d *testNestedDecodable) GroupVersionKind() schema.GroupVersionKind { return d.gvk } -func (d *testNestedDecodable) DeepCopyObject() runtime.Object { - // no real deepcopy because these tests check for pointer equality - return d -} - -func (d *testNestedDecodable) EncodeNestedObjects(e runtime.Encoder) error { - d.nestedCalled = true - return d.nestedErr -} - -func (d *testNestedDecodable) DecodeNestedObjects(_ runtime.Decoder) error { - d.nestedCalled = true - return d.nestedErr -} - -func TestNestedDecode(t *testing.T) { - n := &testNestedDecodable{nestedErr: fmt.Errorf("unable to decode")} - decoder := &mockSerializer{obj: n} - codec := NewCodec(nil, decoder, nil, nil, nil, nil, nil, nil) - if _, _, err := codec.Decode([]byte(`{}`), nil, n); err != n.nestedErr { - t.Errorf("unexpected error: %v", err) - } - if !n.nestedCalled { - t.Errorf("did not invoke nested decoder") - } -} - -func TestNestedEncode(t *testing.T) { - n := &testNestedDecodable{nestedErr: fmt.Errorf("unable to decode")} - n2 := &testNestedDecodable{nestedErr: fmt.Errorf("unable to decode 2")} - encoder := &mockSerializer{obj: n} - codec := NewCodec( - encoder, nil, - &checkConvertor{obj: n2, groupVersion: schema.GroupVersion{Group: "other"}}, - nil, - &mockTyper{gvks: []schema.GroupVersionKind{{Kind: "test"}}}, - nil, - schema.GroupVersion{Group: "other"}, nil, - ) - if err := codec.Encode(n, ioutil.Discard); err != n2.nestedErr { - t.Errorf("unexpected error: %v", err) - } - if n.nestedCalled || !n2.nestedCalled { - t.Errorf("did not invoke correct nested decoder") - } -} - -func TestDecode(t *testing.T) { - gvk1 := &schema.GroupVersionKind{Kind: "Test", Group: "other", Version: "blah"} - decodable1 := &testDecodable{} - decodable2 := &testDecodable{} - decodable3 := &testDecodable{} - versionedDecodable1 := &runtime.VersionedObjects{Objects: []runtime.Object{decodable1}} - - testCases := []struct { - serializer runtime.Serializer - convertor runtime.ObjectConvertor - creater runtime.ObjectCreater - typer runtime.ObjectTyper - defaulter runtime.ObjectDefaulter - yaml bool - pretty bool - - encodes, decodes runtime.GroupVersioner - - defaultGVK *schema.GroupVersionKind - into runtime.Object - - errFn func(error) bool - expectedObject runtime.Object - sameObject runtime.Object - expectedGVK *schema.GroupVersionKind - }{ - { - serializer: &mockSerializer{actual: gvk1}, - convertor: &checkConvertor{groupVersion: schema.GroupVersion{Group: "other", Version: "__internal"}}, - expectedGVK: gvk1, - decodes: schema.GroupVersion{Group: "other", Version: "__internal"}, - }, - { - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - convertor: &checkConvertor{in: decodable1, obj: decodable2, groupVersion: schema.GroupVersion{Group: "other", Version: "__internal"}}, - expectedGVK: gvk1, - sameObject: decodable2, - decodes: schema.GroupVersion{Group: "other", Version: "__internal"}, - }, - // defaultGVK.Group is allowed to force a conversion to the destination group - { - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - defaultGVK: &schema.GroupVersionKind{Group: "force"}, - convertor: &checkConvertor{in: decodable1, obj: decodable2, groupVersion: schema.GroupVersion{Group: "force", Version: "__internal"}}, - expectedGVK: gvk1, - sameObject: decodable2, - decodes: schema.GroupVersion{Group: "force", Version: "__internal"}, - }, - // uses direct conversion for into when objects differ - { - into: decodable3, - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - convertor: &checkConvertor{in: decodable1, obj: decodable3, directConvert: true}, - expectedGVK: gvk1, - sameObject: decodable3, - }, - { - into: versionedDecodable1, - serializer: &mockSerializer{actual: gvk1, obj: decodable3}, - convertor: &checkConvertor{in: decodable3, obj: decodable1, directConvert: true}, - expectedGVK: gvk1, - sameObject: versionedDecodable1, - }, - // returns directly when serializer returns into - { - into: decodable3, - serializer: &mockSerializer{actual: gvk1, obj: decodable3}, - expectedGVK: gvk1, - sameObject: decodable3, - }, - // returns directly when serializer returns into - { - into: versionedDecodable1, - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - expectedGVK: gvk1, - sameObject: versionedDecodable1, - }, - - // runtime.VersionedObjects are decoded - { - into: &runtime.VersionedObjects{Objects: []runtime.Object{}}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - convertor: &checkConvertor{in: decodable1, obj: decodable2, groupVersion: schema.GroupVersion{Group: "other", Version: "__internal"}}, - expectedGVK: gvk1, - expectedObject: &runtime.VersionedObjects{Objects: []runtime.Object{decodable1, decodable2}}, - decodes: schema.GroupVersion{Group: "other", Version: "__internal"}, - }, - - // decode into the same version as the serialized object - { - decodes: schema.GroupVersions{gvk1.GroupVersion()}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - convertor: &checkConvertor{in: decodable1, obj: decodable1, groupVersion: schema.GroupVersions{{Group: "other", Version: "blah"}}}, - expectedGVK: gvk1, - expectedObject: decodable1, - }, - { - into: &runtime.VersionedObjects{Objects: []runtime.Object{}}, - decodes: schema.GroupVersions{gvk1.GroupVersion()}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - convertor: &checkConvertor{in: decodable1, obj: decodable1, groupVersion: schema.GroupVersions{{Group: "other", Version: "blah"}}}, - expectedGVK: gvk1, - expectedObject: &runtime.VersionedObjects{Objects: []runtime.Object{decodable1}}, - }, - - // codec with non matching version skips conversion altogether - { - decodes: schema.GroupVersions{{Group: "something", Version: "else"}}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - convertor: &checkConvertor{in: decodable1, obj: decodable1, groupVersion: schema.GroupVersions{{Group: "something", Version: "else"}}}, - expectedGVK: gvk1, - expectedObject: decodable1, - }, - { - into: &runtime.VersionedObjects{Objects: []runtime.Object{}}, - decodes: schema.GroupVersions{{Group: "something", Version: "else"}}, - - serializer: &mockSerializer{actual: gvk1, obj: decodable1}, - convertor: &checkConvertor{in: decodable1, obj: decodable1, groupVersion: schema.GroupVersions{{Group: "something", Version: "else"}}}, - expectedGVK: gvk1, - expectedObject: &runtime.VersionedObjects{Objects: []runtime.Object{decodable1}}, - }, - } - - for i, test := range testCases { - t.Logf("%d", i) - s := NewCodec(test.serializer, test.serializer, test.convertor, test.creater, test.typer, test.defaulter, test.encodes, test.decodes) - obj, gvk, err := s.Decode([]byte(`{}`), test.defaultGVK, test.into) - - if !reflect.DeepEqual(test.expectedGVK, gvk) { - t.Errorf("%d: unexpected GVK: %v", i, gvk) - } - - switch { - case err == nil && test.errFn != nil: - t.Errorf("%d: failed: %v", i, err) - continue - case err != nil && test.errFn == nil: - t.Errorf("%d: failed: %v", i, err) - continue - case err != nil: - if !test.errFn(err) { - t.Errorf("%d: failed: %v", i, err) - } - if obj != nil { - t.Errorf("%d: should have returned nil object", i) - } - continue - } - - if test.into != nil && test.into != obj { - t.Errorf("%d: expected into to be returned: %v", i, obj) - continue - } - - switch { - case test.expectedObject != nil: - if !reflect.DeepEqual(test.expectedObject, obj) { - t.Errorf("%d: unexpected object:\n%s", i, diff.ObjectGoPrintSideBySide(test.expectedObject, obj)) - } - case test.sameObject != nil: - if test.sameObject != obj { - t.Errorf("%d: unexpected object:\n%s", i, diff.ObjectGoPrintSideBySide(test.sameObject, obj)) - } - case obj != nil: - t.Errorf("%d: unexpected object: %#v", i, obj) - } - } -} - -type checkConvertor struct { - err error - in, obj runtime.Object - groupVersion runtime.GroupVersioner - directConvert bool -} - -func (c *checkConvertor) Convert(in, out, context interface{}) error { - if !c.directConvert { - return fmt.Errorf("unexpected call to Convert") - } - if c.in != nil && c.in != in { - return fmt.Errorf("unexpected in: %s", in) - } - if c.obj != nil && c.obj != out { - return fmt.Errorf("unexpected out: %s", out) - } - return c.err -} -func (c *checkConvertor) ConvertToVersion(in runtime.Object, outVersion runtime.GroupVersioner) (out runtime.Object, err error) { - if c.directConvert { - return nil, fmt.Errorf("unexpected call to ConvertToVersion") - } - if c.in != nil && c.in != in { - return nil, fmt.Errorf("unexpected in: %s", in) - } - if !reflect.DeepEqual(c.groupVersion, outVersion) { - return nil, fmt.Errorf("unexpected outversion: %s (%s)", outVersion, c.groupVersion) - } - return c.obj, c.err -} -func (c *checkConvertor) ConvertFieldLabel(version, kind, label, value string) (string, string, error) { - return "", "", fmt.Errorf("unexpected call to ConvertFieldLabel") -} - -type mockSerializer struct { - err error - obj runtime.Object - encodingObjGVK schema.GroupVersionKind - - defaults, actual *schema.GroupVersionKind - into runtime.Object -} - -func (s *mockSerializer) Decode(data []byte, defaults *schema.GroupVersionKind, into runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) { - s.defaults = defaults - s.into = into - return s.obj, s.actual, s.err -} - -func (s *mockSerializer) Encode(obj runtime.Object, w io.Writer) error { - s.obj = obj - s.encodingObjGVK = obj.GetObjectKind().GroupVersionKind() - return s.err -} - -type mockCreater struct { - err error - obj runtime.Object -} - -func (c *mockCreater) New(kind schema.GroupVersionKind) (runtime.Object, error) { - return c.obj, c.err -} - -type mockTyper struct { - gvks []schema.GroupVersionKind - unversioned bool - err error -} - -func (t *mockTyper) ObjectKinds(obj runtime.Object) ([]schema.GroupVersionKind, bool, error) { - return t.gvks, t.unversioned, t.err -} - -func (t *mockTyper) Recognizes(_ schema.GroupVersionKind) bool { - return true -} - -func TestDirectCodecEncode(t *testing.T) { - serializer := mockSerializer{} - typer := mockTyper{ - gvks: []schema.GroupVersionKind{ - { - Group: "wrong_group", - Kind: "some_kind", - }, - { - Group: "expected_group", - Kind: "some_kind", - }, - }, - } - - c := DirectEncoder{ - Version: schema.GroupVersion{Group: "expected_group"}, - Encoder: &serializer, - ObjectTyper: &typer, - } - c.Encode(&testDecodable{}, ioutil.Discard) - if e, a := "expected_group", serializer.encodingObjGVK.Group; e != a { - t.Errorf("expected group to be %v, got %v", e, a) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator_test.go b/vendor/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator_test.go deleted file mode 100644 index a6f338d311..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/runtime/swagger_doc_generator_test.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package runtime - -import ( - "testing" -) - -func TestFmtRawDoc(t *testing.T) { - tests := []struct { - t, expected string - }{ - {"aaa\n --- asd\n TODO: tooooodo\n toooodoooooo\n", "aaa"}, - {"aaa\nasd\n TODO: tooooodo\nbbbb\n --- toooodoooooo\n", "aaa asd bbbb"}, - {" TODO: tooooodo\n", ""}, - {"Par1\n\nPar2\n\n", "Par1\\n\\nPar2"}, - {"", ""}, - {" ", ""}, - {" \n", ""}, - {" \n\n ", ""}, - {"Example:\n\tl1\n\t\tl2\n", "Example:\\n\\tl1\\n\\t\\tl2"}, - } - - for _, test := range tests { - if o := fmtRawDoc(test.t); o != test.expected { - t.Fatalf("Expected: %q, got %q", test.expected, o) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/selection/BUILD b/vendor/k8s.io/apimachinery/pkg/selection/BUILD deleted file mode 100644 index 3790df9af2..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/selection/BUILD +++ /dev/null @@ -1,25 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = ["operator.go"], - importpath = "k8s.io/apimachinery/pkg/selection", -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/types/BUILD b/vendor/k8s.io/apimachinery/pkg/types/BUILD deleted file mode 100644 index 3db635c8a3..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/types/BUILD +++ /dev/null @@ -1,31 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "namespacedname.go", - "nodename.go", - "patch.go", - "uid.go", - ], - importpath = "k8s.io/apimachinery/pkg/types", -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/cache/BUILD b/vendor/k8s.io/apimachinery/pkg/util/cache/BUILD deleted file mode 100644 index 2fcbae3682..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/cache/BUILD +++ /dev/null @@ -1,43 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "cache_test.go", - "lruexpirecache_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/github.com/golang/groupcache/lru:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/clock:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "cache.go", - "lruexpirecache.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/cache", - deps = ["//vendor/github.com/hashicorp/golang-lru:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/cache/cache_test.go b/vendor/k8s.io/apimachinery/pkg/util/cache/cache_test.go deleted file mode 100644 index 42a58a93dc..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/cache/cache_test.go +++ /dev/null @@ -1,90 +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 cache - -import ( - "testing" -) - -const ( - maxTestCacheSize int = shardsCount * 2 -) - -func ExpectEntry(t *testing.T, cache Cache, index uint64, expectedValue interface{}) bool { - elem, found := cache.Get(index) - if !found { - t.Errorf("Expected to find entry with key %d", index) - return false - } else if elem != expectedValue { - t.Errorf("Expected to find %v, got %v", expectedValue, elem) - return false - } - return true -} - -func TestBasic(t *testing.T) { - cache := NewCache(maxTestCacheSize) - cache.Add(1, "xxx") - ExpectEntry(t, cache, 1, "xxx") -} - -func TestOverflow(t *testing.T) { - cache := NewCache(maxTestCacheSize) - for i := 0; i < maxTestCacheSize+1; i++ { - cache.Add(uint64(i), "xxx") - } - foundIndexes := make([]uint64, 0) - for i := 0; i < maxTestCacheSize+1; i++ { - _, found := cache.Get(uint64(i)) - if found { - foundIndexes = append(foundIndexes, uint64(i)) - } - } - if len(foundIndexes) != maxTestCacheSize { - t.Errorf("Expect to find %d elements, got %d %v", maxTestCacheSize, len(foundIndexes), foundIndexes) - } -} - -func TestOverwrite(t *testing.T) { - cache := NewCache(maxTestCacheSize) - cache.Add(1, "xxx") - ExpectEntry(t, cache, 1, "xxx") - cache.Add(1, "yyy") - ExpectEntry(t, cache, 1, "yyy") -} - -// TestEvict this test will fail sporatically depending on what add() -// selects for the randomKey to be evicted. Ensure that randomKey -// is never the key we most recently added. Since the chance of failure -// on each evict is 50%, if we do it 7 times, it should catch the problem -// if it exists >99% of the time. -func TestEvict(t *testing.T) { - cache := NewCache(shardsCount) - var found bool - for retry := 0; retry < 7; retry++ { - cache.Add(uint64(shardsCount), "xxx") - found = ExpectEntry(t, cache, uint64(shardsCount), "xxx") - if !found { - break - } - cache.Add(0, "xxx") - found = ExpectEntry(t, cache, 0, "xxx") - if !found { - break - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache_test.go b/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache_test.go deleted file mode 100644 index bd44f60d4c..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/cache/lruexpirecache_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2016 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 cache - -import ( - "testing" - "time" - - "k8s.io/apimachinery/pkg/util/clock" - - "github.com/golang/groupcache/lru" -) - -func expectEntry(t *testing.T, c *LRUExpireCache, key lru.Key, value interface{}) { - result, ok := c.Get(key) - if !ok || result != value { - t.Errorf("Expected cache[%v]: %v, got %v", key, value, result) - } -} - -func expectNotEntry(t *testing.T, c *LRUExpireCache, key lru.Key) { - if result, ok := c.Get(key); ok { - t.Errorf("Expected cache[%v] to be empty, got %v", key, result) - } -} - -func TestSimpleGet(t *testing.T) { - c := NewLRUExpireCache(10) - c.Add("long-lived", "12345", 10*time.Hour) - expectEntry(t, c, "long-lived", "12345") -} - -func TestExpiredGet(t *testing.T) { - fakeClock := clock.NewFakeClock(time.Now()) - c := NewLRUExpireCacheWithClock(10, fakeClock) - c.Add("short-lived", "12345", 1*time.Millisecond) - // ensure the entry expired - fakeClock.Step(2 * time.Millisecond) - expectNotEntry(t, c, "short-lived") -} - -func TestLRUOverflow(t *testing.T) { - c := NewLRUExpireCache(4) - c.Add("elem1", "1", 10*time.Hour) - c.Add("elem2", "2", 10*time.Hour) - c.Add("elem3", "3", 10*time.Hour) - c.Add("elem4", "4", 10*time.Hour) - c.Add("elem5", "5", 10*time.Hour) - expectNotEntry(t, c, "elem1") - expectEntry(t, c, "elem2", "2") - expectEntry(t, c, "elem3", "3") - expectEntry(t, c, "elem4", "4") - expectEntry(t, c, "elem5", "5") -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/clock/BUILD b/vendor/k8s.io/apimachinery/pkg/util/clock/BUILD deleted file mode 100644 index a9f6be4719..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/clock/BUILD +++ /dev/null @@ -1,32 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["clock_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["clock.go"], - importpath = "k8s.io/apimachinery/pkg/util/clock", -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/clock/clock_test.go b/vendor/k8s.io/apimachinery/pkg/util/clock/clock_test.go deleted file mode 100644 index 27d34605f5..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/clock/clock_test.go +++ /dev/null @@ -1,184 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package clock - -import ( - "testing" - "time" -) - -func TestFakeClock(t *testing.T) { - startTime := time.Now() - tc := NewFakeClock(startTime) - tc.Step(time.Second) - now := tc.Now() - if now.Sub(startTime) != time.Second { - t.Errorf("input: %s now=%s gap=%s expected=%s", startTime, now, now.Sub(startTime), time.Second) - } - - tt := tc.Now() - tc.SetTime(tt.Add(time.Hour)) - if tc.Now().Sub(tt) != time.Hour { - t.Errorf("input: %s now=%s gap=%s expected=%s", tt, tc.Now(), tc.Now().Sub(tt), time.Hour) - } -} - -func TestFakeClockSleep(t *testing.T) { - startTime := time.Now() - tc := NewFakeClock(startTime) - tc.Sleep(time.Duration(1) * time.Hour) - now := tc.Now() - if now.Sub(startTime) != time.Hour { - t.Errorf("Fake sleep failed, expected time to advance by one hour, instead, its %v", now.Sub(startTime)) - } -} - -func TestFakeAfter(t *testing.T) { - tc := NewFakeClock(time.Now()) - if tc.HasWaiters() { - t.Errorf("unexpected waiter?") - } - oneSec := tc.After(time.Second) - if !tc.HasWaiters() { - t.Errorf("unexpected lack of waiter?") - } - - oneOhOneSec := tc.After(time.Second + time.Millisecond) - twoSec := tc.After(2 * time.Second) - select { - case <-oneSec: - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - } - - tc.Step(999 * time.Millisecond) - select { - case <-oneSec: - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - } - - tc.Step(time.Millisecond) - select { - case <-oneSec: - // Expected! - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - t.Errorf("unexpected non-channel read") - } - tc.Step(time.Millisecond) - select { - case <-oneSec: - // should not double-trigger! - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - // Expected! - case <-twoSec: - t.Errorf("unexpected channel read") - default: - t.Errorf("unexpected non-channel read") - } -} - -func TestFakeTick(t *testing.T) { - tc := NewFakeClock(time.Now()) - if tc.HasWaiters() { - t.Errorf("unexpected waiter?") - } - oneSec := tc.Tick(time.Second) - if !tc.HasWaiters() { - t.Errorf("unexpected lack of waiter?") - } - - oneOhOneSec := tc.Tick(time.Second + time.Millisecond) - twoSec := tc.Tick(2 * time.Second) - select { - case <-oneSec: - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - } - - tc.Step(999 * time.Millisecond) // t=.999 - select { - case <-oneSec: - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - } - - tc.Step(time.Millisecond) // t=1.000 - select { - case <-oneSec: - // Expected! - case <-oneOhOneSec: - t.Errorf("unexpected channel read") - case <-twoSec: - t.Errorf("unexpected channel read") - default: - t.Errorf("unexpected non-channel read") - } - tc.Step(time.Millisecond) // t=1.001 - select { - case <-oneSec: - // should not double-trigger! - t.Errorf("unexpected channel read") - case <-oneOhOneSec: - // Expected! - case <-twoSec: - t.Errorf("unexpected channel read") - default: - t.Errorf("unexpected non-channel read") - } - - tc.Step(time.Second) // t=2.001 - tc.Step(time.Second) // t=3.001 - tc.Step(time.Second) // t=4.001 - tc.Step(time.Second) // t=5.001 - - // The one second ticker should not accumulate ticks - accumulatedTicks := 0 - drained := false - for !drained { - select { - case <-oneSec: - accumulatedTicks++ - default: - drained = true - } - } - if accumulatedTicks != 1 { - t.Errorf("unexpected number of accumulated ticks: %d", accumulatedTicks) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/diff/BUILD b/vendor/k8s.io/apimachinery/pkg/util/diff/BUILD deleted file mode 100644 index 3cd03b4357..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/diff/BUILD +++ /dev/null @@ -1,36 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["diff_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["diff.go"], - importpath = "k8s.io/apimachinery/pkg/util/diff", - deps = [ - "//vendor/github.com/davecgh/go-spew/spew:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/diff/diff_test.go b/vendor/k8s.io/apimachinery/pkg/util/diff/diff_test.go deleted file mode 100644 index 2b72c2f531..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/diff/diff_test.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright 2016 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 diff - -import ( - "testing" -) - -func TestObjectReflectDiff(t *testing.T) { - type struct1 struct{ A []int } - - testCases := map[string]struct { - a, b interface{} - out string - }{ - "map": { - a: map[string]int{}, - b: map[string]int{}, - }, - "detect nil map": { - a: map[string]int(nil), - b: map[string]int{}, - out: ` -object: - a: map[string]int(nil) - b: map[string]int{}`, - }, - "detect map changes": { - a: map[string]int{"test": 1, "other": 2}, - b: map[string]int{"test": 2, "third": 3}, - out: ` -object[other]: - a: 2 - b: <nil> -object[test]: - a: 1 - b: 2 -object[third]: - a: <nil> - b: 3`, - }, - "nil slice": {a: struct1{A: nil}, b: struct1{A: nil}}, - "empty slice": {a: struct1{A: []int{}}, b: struct1{A: []int{}}}, - "detect slice changes 1": {a: struct1{A: []int{1}}, b: struct1{A: []int{2}}, out: ` -object.A[0]: - a: 1 - b: 2`, - }, - "detect slice changes 2": {a: struct1{A: []int{}}, b: struct1{A: []int{2}}, out: ` -object.A[0]: - a: <nil> - b: 2`, - }, - "detect slice changes 3": {a: struct1{A: []int{1}}, b: struct1{A: []int{}}, out: ` -object.A[0]: - a: 1 - b: <nil>`, - }, - "detect nil vs empty slices": {a: struct1{A: nil}, b: struct1{A: []int{}}, out: ` -object.A: - a: []int(nil) - b: []int{}`, - }, - } - for name, test := range testCases { - expect := test.out - if len(expect) == 0 { - expect = "<no diffs>" - } - if actual := ObjectReflectDiff(test.a, test.b); actual != expect { - t.Errorf("%s: unexpected output: %s", name, actual) - } - } -} - -func TestStringDiff(t *testing.T) { - diff := StringDiff("aaabb", "aaacc") - expect := "aaa\n\nA: bb\n\nB: cc\n\n" - if diff != expect { - t.Errorf("diff returned %v", diff) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/errors/BUILD b/vendor/k8s.io/apimachinery/pkg/util/errors/BUILD deleted file mode 100644 index fa2b74a2c8..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/errors/BUILD +++ /dev/null @@ -1,35 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["errors_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "errors.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/errors", -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/errors/errors_test.go b/vendor/k8s.io/apimachinery/pkg/util/errors/errors_test.go deleted file mode 100644 index 0ad3967d28..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/errors/errors_test.go +++ /dev/null @@ -1,368 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package errors - -import ( - "fmt" - "reflect" - "sort" - "testing" -) - -func TestEmptyAggregate(t *testing.T) { - var slice []error - var agg Aggregate - var err error - - agg = NewAggregate(slice) - if agg != nil { - t.Errorf("expected nil, got %#v", agg) - } - err = NewAggregate(slice) - if err != nil { - t.Errorf("expected nil, got %#v", err) - } - - // This is not normally possible, but pedantry demands I test it. - agg = aggregate(slice) // empty aggregate - if s := agg.Error(); s != "" { - t.Errorf("expected empty string, got %q", s) - } - if s := agg.Errors(); len(s) != 0 { - t.Errorf("expected empty slice, got %#v", s) - } - err = agg.(error) - if s := err.Error(); s != "" { - t.Errorf("expected empty string, got %q", s) - } -} - -func TestAggregateWithNil(t *testing.T) { - var slice []error - slice = []error{nil} - var agg Aggregate - var err error - - agg = NewAggregate(slice) - if agg != nil { - t.Errorf("expected nil, got %#v", agg) - } - err = NewAggregate(slice) - if err != nil { - t.Errorf("expected nil, got %#v", err) - } - - // Append a non-nil error - slice = append(slice, fmt.Errorf("err")) - agg = NewAggregate(slice) - if agg == nil { - t.Errorf("expected non-nil") - } - if s := agg.Error(); s != "err" { - t.Errorf("expected 'err', got %q", s) - } - if s := agg.Errors(); len(s) != 1 { - t.Errorf("expected one-element slice, got %#v", s) - } - if s := agg.Errors()[0].Error(); s != "err" { - t.Errorf("expected 'err', got %q", s) - } - - err = agg.(error) - if err == nil { - t.Errorf("expected non-nil") - } - if s := err.Error(); s != "err" { - t.Errorf("expected 'err', got %q", s) - } -} - -func TestSingularAggregate(t *testing.T) { - var slice []error = []error{fmt.Errorf("err")} - var agg Aggregate - var err error - - agg = NewAggregate(slice) - if agg == nil { - t.Errorf("expected non-nil") - } - if s := agg.Error(); s != "err" { - t.Errorf("expected 'err', got %q", s) - } - if s := agg.Errors(); len(s) != 1 { - t.Errorf("expected one-element slice, got %#v", s) - } - if s := agg.Errors()[0].Error(); s != "err" { - t.Errorf("expected 'err', got %q", s) - } - - err = agg.(error) - if err == nil { - t.Errorf("expected non-nil") - } - if s := err.Error(); s != "err" { - t.Errorf("expected 'err', got %q", s) - } -} - -func TestPluralAggregate(t *testing.T) { - var slice []error = []error{fmt.Errorf("abc"), fmt.Errorf("123")} - var agg Aggregate - var err error - - agg = NewAggregate(slice) - if agg == nil { - t.Errorf("expected non-nil") - } - if s := agg.Error(); s != "[abc, 123]" { - t.Errorf("expected '[abc, 123]', got %q", s) - } - if s := agg.Errors(); len(s) != 2 { - t.Errorf("expected two-elements slice, got %#v", s) - } - if s := agg.Errors()[0].Error(); s != "abc" { - t.Errorf("expected '[abc, 123]', got %q", s) - } - - err = agg.(error) - if err == nil { - t.Errorf("expected non-nil") - } - if s := err.Error(); s != "[abc, 123]" { - t.Errorf("expected '[abc, 123]', got %q", s) - } -} - -func TestFilterOut(t *testing.T) { - testCases := []struct { - err error - filter []Matcher - expected error - }{ - { - nil, - []Matcher{}, - nil, - }, - { - aggregate{}, - []Matcher{}, - nil, - }, - { - aggregate{fmt.Errorf("abc")}, - []Matcher{}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{fmt.Errorf("abc")}, - []Matcher{func(err error) bool { return false }}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{fmt.Errorf("abc")}, - []Matcher{func(err error) bool { return true }}, - nil, - }, - { - aggregate{fmt.Errorf("abc")}, - []Matcher{func(err error) bool { return false }, func(err error) bool { return false }}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{fmt.Errorf("abc")}, - []Matcher{func(err error) bool { return false }, func(err error) bool { return true }}, - nil, - }, - { - aggregate{fmt.Errorf("abc"), fmt.Errorf("def"), fmt.Errorf("ghi")}, - []Matcher{func(err error) bool { return err.Error() == "def" }}, - aggregate{fmt.Errorf("abc"), fmt.Errorf("ghi")}, - }, - { - aggregate{aggregate{fmt.Errorf("abc")}}, - []Matcher{}, - aggregate{aggregate{fmt.Errorf("abc")}}, - }, - { - aggregate{aggregate{fmt.Errorf("abc"), aggregate{fmt.Errorf("def")}}}, - []Matcher{}, - aggregate{aggregate{fmt.Errorf("abc"), aggregate{fmt.Errorf("def")}}}, - }, - { - aggregate{aggregate{fmt.Errorf("abc"), aggregate{fmt.Errorf("def")}}}, - []Matcher{func(err error) bool { return err.Error() == "def" }}, - aggregate{aggregate{fmt.Errorf("abc")}}, - }, - } - for i, testCase := range testCases { - err := FilterOut(testCase.err, testCase.filter...) - if !reflect.DeepEqual(testCase.expected, err) { - t.Errorf("%d: expected %v, got %v", i, testCase.expected, err) - } - } -} - -func TestFlatten(t *testing.T) { - testCases := []struct { - agg Aggregate - expected Aggregate - }{ - { - nil, - nil, - }, - { - aggregate{}, - nil, - }, - { - aggregate{fmt.Errorf("abc")}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{fmt.Errorf("abc"), fmt.Errorf("def"), fmt.Errorf("ghi")}, - aggregate{fmt.Errorf("abc"), fmt.Errorf("def"), fmt.Errorf("ghi")}, - }, - { - aggregate{aggregate{fmt.Errorf("abc")}}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{aggregate{aggregate{fmt.Errorf("abc")}}}, - aggregate{fmt.Errorf("abc")}, - }, - { - aggregate{aggregate{fmt.Errorf("abc"), aggregate{fmt.Errorf("def")}}}, - aggregate{fmt.Errorf("abc"), fmt.Errorf("def")}, - }, - { - aggregate{aggregate{aggregate{fmt.Errorf("abc")}, fmt.Errorf("def"), aggregate{fmt.Errorf("ghi")}}}, - aggregate{fmt.Errorf("abc"), fmt.Errorf("def"), fmt.Errorf("ghi")}, - }, - } - for i, testCase := range testCases { - agg := Flatten(testCase.agg) - if !reflect.DeepEqual(testCase.expected, agg) { - t.Errorf("%d: expected %v, got %v", i, testCase.expected, agg) - } - } -} - -func TestCreateAggregateFromMessageCountMap(t *testing.T) { - testCases := []struct { - name string - mcm MessageCountMap - expected Aggregate - }{ - { - "input has single instance of one message", - MessageCountMap{"abc": 1}, - aggregate{fmt.Errorf("abc")}, - }, - { - "input has multiple messages", - MessageCountMap{"abc": 2, "ghi": 1}, - aggregate{fmt.Errorf("abc (repeated 2 times)"), fmt.Errorf("ghi")}, - }, - { - "input has multiple messages", - MessageCountMap{"ghi": 1, "abc": 2}, - aggregate{fmt.Errorf("abc (repeated 2 times)"), fmt.Errorf("ghi")}, - }, - } - - var expected, agg []error - for _, testCase := range testCases { - t.Run(testCase.name, func(t *testing.T) { - if testCase.expected != nil { - expected = testCase.expected.Errors() - sort.Slice(expected, func(i, j int) bool { return expected[i].Error() < expected[j].Error() }) - } - if testCase.mcm != nil { - agg = CreateAggregateFromMessageCountMap(testCase.mcm).Errors() - sort.Slice(agg, func(i, j int) bool { return agg[i].Error() < agg[j].Error() }) - } - if !reflect.DeepEqual(expected, agg) { - t.Errorf("expected %v, got %v", expected, agg) - } - }) - } -} - -func TestAggregateGoroutines(t *testing.T) { - testCases := []struct { - errs []error - expected map[string]bool // can't compare directly to Aggregate due to non-deterministic ordering - }{ - { - []error{}, - nil, - }, - { - []error{nil}, - nil, - }, - { - []error{nil, nil}, - nil, - }, - { - []error{fmt.Errorf("1")}, - map[string]bool{"1": true}, - }, - { - []error{fmt.Errorf("1"), nil}, - map[string]bool{"1": true}, - }, - { - []error{fmt.Errorf("1"), fmt.Errorf("267")}, - map[string]bool{"1": true, "267": true}, - }, - { - []error{fmt.Errorf("1"), nil, fmt.Errorf("1234")}, - map[string]bool{"1": true, "1234": true}, - }, - { - []error{nil, fmt.Errorf("1"), nil, fmt.Errorf("1234"), fmt.Errorf("22")}, - map[string]bool{"1": true, "1234": true, "22": true}, - }, - } - for i, testCase := range testCases { - funcs := make([]func() error, len(testCase.errs)) - for i := range testCase.errs { - err := testCase.errs[i] - funcs[i] = func() error { return err } - } - agg := AggregateGoroutines(funcs...) - if agg == nil { - if len(testCase.expected) > 0 { - t.Errorf("%d: expected %v, got nil", i, testCase.expected) - } - continue - } - if len(agg.Errors()) != len(testCase.expected) { - t.Errorf("%d: expected %d errors in aggregate, got %v", i, len(testCase.expected), agg) - continue - } - for _, err := range agg.Errors() { - if !testCase.expected[err.Error()] { - t.Errorf("%d: expected %v, got aggregate containing %v", i, testCase.expected, err) - } - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/framer/BUILD b/vendor/k8s.io/apimachinery/pkg/util/framer/BUILD deleted file mode 100644 index 3a323b1139..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/framer/BUILD +++ /dev/null @@ -1,32 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["framer_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["framer.go"], - importpath = "k8s.io/apimachinery/pkg/util/framer", -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/framer/framer_test.go b/vendor/k8s.io/apimachinery/pkg/util/framer/framer_test.go deleted file mode 100644 index b7ed00f538..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/framer/framer_test.go +++ /dev/null @@ -1,176 +0,0 @@ -/* -Copyright 2016 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 framer - -import ( - "bytes" - "io" - "io/ioutil" - "testing" -) - -func TestRead(t *testing.T) { - data := []byte{ - 0x00, 0x00, 0x00, 0x04, - 0x01, 0x02, 0x03, 0x04, - 0x00, 0x00, 0x00, 0x03, - 0x05, 0x06, 0x07, - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x01, - 0x08, - } - b := bytes.NewBuffer(data) - r := NewLengthDelimitedFrameReader(ioutil.NopCloser(b)) - buf := make([]byte, 1) - if n, err := r.Read(buf); err != io.ErrShortBuffer && n != 1 && bytes.Equal(buf, []byte{0x01}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - if n, err := r.Read(buf); err != io.ErrShortBuffer && n != 1 && bytes.Equal(buf, []byte{0x02}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - // read the remaining frame - buf = make([]byte, 2) - if n, err := r.Read(buf); err != nil && n != 2 && bytes.Equal(buf, []byte{0x03, 0x04}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - // read with buffer equal to frame - buf = make([]byte, 3) - if n, err := r.Read(buf); err != nil && n != 3 && bytes.Equal(buf, []byte{0x05, 0x06, 0x07}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - // read empty frame - buf = make([]byte, 3) - if n, err := r.Read(buf); err != nil && n != 0 && bytes.Equal(buf, []byte{}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - // read with larger buffer than frame - buf = make([]byte, 3) - if n, err := r.Read(buf); err != nil && n != 1 && bytes.Equal(buf, []byte{0x08}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - // read EOF - if n, err := r.Read(buf); err != io.EOF && n != 0 { - t.Fatalf("unexpected: %v %d", err, n) - } -} - -func TestReadLarge(t *testing.T) { - data := []byte{ - 0x00, 0x00, 0x00, 0x04, - 0x01, 0x02, 0x03, 0x04, - 0x00, 0x00, 0x00, 0x03, - 0x05, 0x06, 0x07, - 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x01, - 0x08, - } - b := bytes.NewBuffer(data) - r := NewLengthDelimitedFrameReader(ioutil.NopCloser(b)) - buf := make([]byte, 40) - if n, err := r.Read(buf); err != nil && n != 4 && bytes.Equal(buf, []byte{0x01, 0x02, 0x03, 0x04}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - if n, err := r.Read(buf); err != nil && n != 3 && bytes.Equal(buf, []byte{0x05, 0x06, 0x7}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - if n, err := r.Read(buf); err != nil && n != 0 && bytes.Equal(buf, []byte{}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - if n, err := r.Read(buf); err != nil && n != 1 && bytes.Equal(buf, []byte{0x08}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - // read EOF - if n, err := r.Read(buf); err != io.EOF && n != 0 { - t.Fatalf("unexpected: %v %d", err, n) - } -} -func TestReadInvalidFrame(t *testing.T) { - data := []byte{ - 0x00, 0x00, 0x00, 0x04, - 0x01, 0x02, - } - b := bytes.NewBuffer(data) - r := NewLengthDelimitedFrameReader(ioutil.NopCloser(b)) - buf := make([]byte, 1) - if n, err := r.Read(buf); err != io.ErrShortBuffer && n != 1 && bytes.Equal(buf, []byte{0x01}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - // read the remaining frame - buf = make([]byte, 3) - if n, err := r.Read(buf); err != io.ErrUnexpectedEOF && n != 1 && bytes.Equal(buf, []byte{0x02}) { - t.Fatalf("unexpected: %v %d %v", err, n, buf) - } - // read EOF - if n, err := r.Read(buf); err != io.EOF && n != 0 { - t.Fatalf("unexpected: %v %d", err, n) - } -} - -func TestJSONFrameReader(t *testing.T) { - b := bytes.NewBufferString("{\"test\":true}\n1\n[\"a\"]") - r := NewJSONFramedReader(ioutil.NopCloser(b)) - buf := make([]byte, 20) - if n, err := r.Read(buf); err != nil || n != 13 || string(buf[:n]) != `{"test":true}` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - if n, err := r.Read(buf); err != nil || n != 1 || string(buf[:n]) != `1` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - if n, err := r.Read(buf); err != nil || n != 5 || string(buf[:n]) != `["a"]` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - if n, err := r.Read(buf); err != io.EOF || n != 0 { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } -} - -func TestJSONFrameReaderShortBuffer(t *testing.T) { - b := bytes.NewBufferString("{\"test\":true}\n1\n[\"a\"]") - r := NewJSONFramedReader(ioutil.NopCloser(b)) - buf := make([]byte, 3) - - if n, err := r.Read(buf); err != io.ErrShortBuffer || n != 3 || string(buf[:n]) != `{"t` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - if n, err := r.Read(buf); err != io.ErrShortBuffer || n != 3 || string(buf[:n]) != `est` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - if n, err := r.Read(buf); err != io.ErrShortBuffer || n != 3 || string(buf[:n]) != `":t` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - if n, err := r.Read(buf); err != io.ErrShortBuffer || n != 3 || string(buf[:n]) != `rue` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - if n, err := r.Read(buf); err != nil || n != 1 || string(buf[:n]) != `}` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - - if n, err := r.Read(buf); err != nil || n != 1 || string(buf[:n]) != `1` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - - if n, err := r.Read(buf); err != io.ErrShortBuffer || n != 3 || string(buf[:n]) != `["a` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - if n, err := r.Read(buf); err != nil || n != 2 || string(buf[:n]) != `"]` { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } - - if n, err := r.Read(buf); err != io.EOF || n != 0 { - t.Fatalf("unexpected: %v %d %q", err, n, buf) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/BUILD b/vendor/k8s.io/apimachinery/pkg/util/httpstream/BUILD deleted file mode 100644 index 5d45073efd..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/BUILD +++ /dev/null @@ -1,38 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["httpstream_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "httpstream.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/httpstream", -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/util/httpstream/spdy:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/httpstream_test.go b/vendor/k8s.io/apimachinery/pkg/util/httpstream/httpstream_test.go deleted file mode 100644 index f7f9a3ebf4..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/httpstream_test.go +++ /dev/null @@ -1,125 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package httpstream - -import ( - "net/http" - "reflect" - "testing" -) - -type responseWriter struct { - header http.Header - statusCode *int -} - -func newResponseWriter() *responseWriter { - return &responseWriter{ - header: make(http.Header), - } -} - -func (r *responseWriter) Header() http.Header { - return r.header -} - -func (r *responseWriter) WriteHeader(code int) { - r.statusCode = &code -} - -func (r *responseWriter) Write([]byte) (int, error) { - return 0, nil -} - -func TestHandshake(t *testing.T) { - tests := map[string]struct { - clientProtocols []string - serverProtocols []string - expectedProtocol string - expectError bool - }{ - "no client protocols": { - clientProtocols: []string{}, - serverProtocols: []string{"a", "b"}, - expectedProtocol: "", - }, - "no common protocol": { - clientProtocols: []string{"c"}, - serverProtocols: []string{"a", "b"}, - expectedProtocol: "", - expectError: true, - }, - "common protocol": { - clientProtocols: []string{"b"}, - serverProtocols: []string{"a", "b"}, - expectedProtocol: "b", - }, - } - - for name, test := range tests { - req, err := http.NewRequest("GET", "http://www.example.com/", nil) - if err != nil { - t.Fatalf("%s: error creating request: %v", name, err) - } - - for _, p := range test.clientProtocols { - req.Header.Add(HeaderProtocolVersion, p) - } - - w := newResponseWriter() - negotiated, err := Handshake(req, w, test.serverProtocols) - - // verify negotiated protocol - if e, a := test.expectedProtocol, negotiated; e != a { - t.Errorf("%s: protocol: expected %q, got %q", name, e, a) - } - - if test.expectError { - if err == nil { - t.Errorf("%s: expected error but did not get one", name) - } - if w.statusCode == nil { - t.Errorf("%s: expected w.statusCode to be set", name) - } else if e, a := http.StatusForbidden, *w.statusCode; e != a { - t.Errorf("%s: w.statusCode: expected %d, got %d", name, e, a) - } - if e, a := test.serverProtocols, w.Header()[HeaderAcceptedProtocolVersions]; !reflect.DeepEqual(e, a) { - t.Errorf("%s: accepted server protocols: expected %v, got %v", name, e, a) - } - continue - } - if !test.expectError && err != nil { - t.Errorf("%s: unexpected error: %v", name, err) - continue - } - if w.statusCode != nil { - t.Errorf("%s: unexpected non-nil w.statusCode: %d", name, w.statusCode) - } - - if len(test.expectedProtocol) == 0 { - if len(w.Header()[HeaderProtocolVersion]) > 0 { - t.Errorf("%s: unexpected protocol version response header: %s", name, w.Header()[HeaderProtocolVersion]) - } - continue - } - - // verify response headers - if e, a := []string{test.expectedProtocol}, w.Header()[HeaderProtocolVersion]; !reflect.DeepEqual(e, a) { - t.Errorf("%s: protocol response header: expected %v, got %v", name, e, a) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/BUILD b/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/BUILD deleted file mode 100644 index 75d6ec0d14..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/BUILD +++ /dev/null @@ -1,56 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "connection_test.go", - "roundtripper_test.go", - "upgrade_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/github.com/elazarl/goproxy:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/httpstream:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "connection.go", - "roundtripper.go", - "upgrade.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/httpstream/spdy", - deps = [ - "//vendor/github.com/docker/spdystream:go_default_library", - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/errors:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/httpstream:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/net:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/third_party/forked/golang/netutil:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection_test.go b/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection_test.go deleted file mode 100644 index f94e2b3ba4..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/connection_test.go +++ /dev/null @@ -1,164 +0,0 @@ -/* -Copyright 2016 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 spdy - -import ( - "io" - "net" - "net/http" - "sync" - "testing" - "time" - - "k8s.io/apimachinery/pkg/util/httpstream" -) - -func runProxy(t *testing.T, backendUrl string, proxyUrl chan<- string, proxyDone chan<- struct{}) { - listener, err := net.Listen("tcp4", "localhost:0") - if err != nil { - t.Fatalf("error listening: %v", err) - } - defer listener.Close() - - proxyUrl <- listener.Addr().String() - - clientConn, err := listener.Accept() - if err != nil { - t.Errorf("proxy: error accepting client connection: %v", err) - return - } - - backendConn, err := net.Dial("tcp4", backendUrl) - if err != nil { - t.Errorf("proxy: error dialing backend: %v", err) - return - } - defer backendConn.Close() - - var wg sync.WaitGroup - wg.Add(2) - - go func() { - defer wg.Done() - io.Copy(backendConn, clientConn) - }() - - go func() { - defer wg.Done() - io.Copy(clientConn, backendConn) - }() - - wg.Wait() - - proxyDone <- struct{}{} -} - -func runServer(t *testing.T, backendUrl chan<- string, serverDone chan<- struct{}) { - listener, err := net.Listen("tcp4", "localhost:0") - if err != nil { - t.Fatalf("server: error listening: %v", err) - } - defer listener.Close() - - backendUrl <- listener.Addr().String() - - conn, err := listener.Accept() - if err != nil { - t.Errorf("server: error accepting connection: %v", err) - return - } - - streamChan := make(chan httpstream.Stream) - replySentChan := make(chan (<-chan struct{})) - spdyConn, err := NewServerConnection(conn, func(stream httpstream.Stream, replySent <-chan struct{}) error { - streamChan <- stream - replySentChan <- replySent - return nil - }) - if err != nil { - t.Errorf("server: error creating spdy connection: %v", err) - return - } - - stream := <-streamChan - replySent := <-replySentChan - <-replySent - - buf := make([]byte, 1) - _, err = stream.Read(buf) - if err != io.EOF { - t.Errorf("server: unexpected read error: %v", err) - return - } - - <-spdyConn.CloseChan() - raw := spdyConn.(*connection).conn - if err := raw.Wait(15 * time.Second); err != nil { - t.Errorf("server: timed out waiting for connection closure: %v", err) - } - - serverDone <- struct{}{} -} - -func TestConnectionCloseIsImmediateThroughAProxy(t *testing.T) { - serverDone := make(chan struct{}) - backendUrlChan := make(chan string) - go runServer(t, backendUrlChan, serverDone) - backendUrl := <-backendUrlChan - - proxyDone := make(chan struct{}) - proxyUrlChan := make(chan string) - go runProxy(t, backendUrl, proxyUrlChan, proxyDone) - proxyUrl := <-proxyUrlChan - - conn, err := net.Dial("tcp4", proxyUrl) - if err != nil { - t.Fatalf("client: error connecting to proxy: %v", err) - } - - spdyConn, err := NewClientConnection(conn) - if err != nil { - t.Fatalf("client: error creating spdy connection: %v", err) - } - - if _, err := spdyConn.CreateStream(http.Header{}); err != nil { - t.Fatalf("client: error creating stream: %v", err) - } - - spdyConn.Close() - raw := spdyConn.(*connection).conn - if err := raw.Wait(15 * time.Second); err != nil { - t.Fatalf("client: timed out waiting for connection closure: %v", err) - } - - expired := time.NewTimer(15 * time.Second) - defer expired.Stop() - i := 0 - for { - select { - case <-expired.C: - t.Fatalf("timed out waiting for proxy and/or server closure") - case <-serverDone: - i++ - case <-proxyDone: - i++ - } - if i == 2 { - break - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper_test.go b/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper_test.go deleted file mode 100644 index 887adbe8f6..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/roundtripper_test.go +++ /dev/null @@ -1,529 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package spdy - -import ( - "crypto/tls" - "crypto/x509" - "encoding/base64" - "fmt" - "io" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "sync/atomic" - "testing" - - "github.com/elazarl/goproxy" - - "k8s.io/apimachinery/pkg/util/httpstream" -) - -// be sure to unset environment variable https_proxy (if exported) before testing, otherwise the testing will fail unexpectedly. -func TestRoundTripAndNewConnection(t *testing.T) { - for _, redirect := range []bool{false, true} { - t.Run(fmt.Sprintf("redirect = %t", redirect), func(t *testing.T) { - localhostPool := x509.NewCertPool() - if !localhostPool.AppendCertsFromPEM(localhostCert) { - t.Errorf("error setting up localhostCert pool") - } - - httpsServerInvalidHostname := func(h http.Handler) *httptest.Server { - cert, err := tls.X509KeyPair(exampleCert, exampleKey) - if err != nil { - t.Errorf("https (invalid hostname): proxy_test: %v", err) - } - ts := httptest.NewUnstartedServer(h) - ts.TLS = &tls.Config{ - Certificates: []tls.Certificate{cert}, - } - ts.StartTLS() - return ts - } - - httpsServerValidHostname := func(h http.Handler) *httptest.Server { - cert, err := tls.X509KeyPair(localhostCert, localhostKey) - if err != nil { - t.Errorf("https (valid hostname): proxy_test: %v", err) - } - ts := httptest.NewUnstartedServer(h) - ts.TLS = &tls.Config{ - Certificates: []tls.Certificate{cert}, - } - ts.StartTLS() - return ts - } - - testCases := map[string]struct { - serverFunc func(http.Handler) *httptest.Server - proxyServerFunc func(http.Handler) *httptest.Server - proxyAuth *url.Userinfo - clientTLS *tls.Config - serverConnectionHeader string - serverUpgradeHeader string - serverStatusCode int - shouldError bool - }{ - "no headers": { - serverFunc: httptest.NewServer, - serverConnectionHeader: "", - serverUpgradeHeader: "", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: true, - }, - "no upgrade header": { - serverFunc: httptest.NewServer, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: true, - }, - "no connection header": { - serverFunc: httptest.NewServer, - serverConnectionHeader: "", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: true, - }, - "no switching protocol status code": { - serverFunc: httptest.NewServer, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusForbidden, - shouldError: true, - }, - "http": { - serverFunc: httptest.NewServer, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "https (invalid hostname + InsecureSkipVerify)": { - serverFunc: httpsServerInvalidHostname, - clientTLS: &tls.Config{InsecureSkipVerify: true}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "https (invalid hostname + hostname verification)": { - serverFunc: httpsServerInvalidHostname, - clientTLS: &tls.Config{InsecureSkipVerify: false}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: true, - }, - "https (valid hostname + RootCAs)": { - serverFunc: httpsServerValidHostname, - clientTLS: &tls.Config{RootCAs: localhostPool}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "proxied http->http": { - serverFunc: httptest.NewServer, - proxyServerFunc: httptest.NewServer, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "proxied https (invalid hostname + InsecureSkipVerify) -> http": { - serverFunc: httptest.NewServer, - proxyServerFunc: httpsServerInvalidHostname, - clientTLS: &tls.Config{InsecureSkipVerify: true}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "proxied https with auth (invalid hostname + InsecureSkipVerify) -> http": { - serverFunc: httptest.NewServer, - proxyServerFunc: httpsServerInvalidHostname, - proxyAuth: url.UserPassword("proxyuser", "proxypasswd"), - clientTLS: &tls.Config{InsecureSkipVerify: true}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "proxied https (invalid hostname + hostname verification) -> http": { - serverFunc: httptest.NewServer, - proxyServerFunc: httpsServerInvalidHostname, - clientTLS: &tls.Config{InsecureSkipVerify: false}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: true, // fails because the client doesn't trust the proxy - }, - "proxied https (valid hostname + RootCAs) -> http": { - serverFunc: httptest.NewServer, - proxyServerFunc: httpsServerValidHostname, - clientTLS: &tls.Config{RootCAs: localhostPool}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "proxied https with auth (valid hostname + RootCAs) -> http": { - serverFunc: httptest.NewServer, - proxyServerFunc: httpsServerValidHostname, - proxyAuth: url.UserPassword("proxyuser", "proxypasswd"), - clientTLS: &tls.Config{RootCAs: localhostPool}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "proxied https (invalid hostname + InsecureSkipVerify) -> https (invalid hostname)": { - serverFunc: httpsServerInvalidHostname, - proxyServerFunc: httpsServerInvalidHostname, - clientTLS: &tls.Config{InsecureSkipVerify: true}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, // works because the test proxy ignores TLS errors - }, - "proxied https with auth (invalid hostname + InsecureSkipVerify) -> https (invalid hostname)": { - serverFunc: httpsServerInvalidHostname, - proxyServerFunc: httpsServerInvalidHostname, - proxyAuth: url.UserPassword("proxyuser", "proxypasswd"), - clientTLS: &tls.Config{InsecureSkipVerify: true}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, // works because the test proxy ignores TLS errors - }, - "proxied https (invalid hostname + hostname verification) -> https (invalid hostname)": { - serverFunc: httpsServerInvalidHostname, - proxyServerFunc: httpsServerInvalidHostname, - clientTLS: &tls.Config{InsecureSkipVerify: false}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: true, // fails because the client doesn't trust the proxy - }, - "proxied https (valid hostname + RootCAs) -> https (valid hostname + RootCAs)": { - serverFunc: httpsServerValidHostname, - proxyServerFunc: httpsServerValidHostname, - clientTLS: &tls.Config{RootCAs: localhostPool}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - "proxied https with auth (valid hostname + RootCAs) -> https (valid hostname + RootCAs)": { - serverFunc: httpsServerValidHostname, - proxyServerFunc: httpsServerValidHostname, - proxyAuth: url.UserPassword("proxyuser", "proxypasswd"), - clientTLS: &tls.Config{RootCAs: localhostPool}, - serverConnectionHeader: "Upgrade", - serverUpgradeHeader: "SPDY/3.1", - serverStatusCode: http.StatusSwitchingProtocols, - shouldError: false, - }, - } - - for k, testCase := range testCases { - server := testCase.serverFunc(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if testCase.shouldError { - if e, a := httpstream.HeaderUpgrade, req.Header.Get(httpstream.HeaderConnection); e != a { - t.Fatalf("%s: Expected connection=upgrade header, got '%s", k, a) - } - - w.Header().Set(httpstream.HeaderConnection, testCase.serverConnectionHeader) - w.Header().Set(httpstream.HeaderUpgrade, testCase.serverUpgradeHeader) - w.WriteHeader(testCase.serverStatusCode) - - return - } - - streamCh := make(chan httpstream.Stream) - - responseUpgrader := NewResponseUpgrader() - spdyConn := responseUpgrader.UpgradeResponse(w, req, func(s httpstream.Stream, replySent <-chan struct{}) error { - streamCh <- s - return nil - }) - if spdyConn == nil { - t.Fatalf("%s: unexpected nil spdyConn", k) - } - defer spdyConn.Close() - - stream := <-streamCh - io.Copy(stream, stream) - })) - defer server.Close() - - serverURL, err := url.Parse(server.URL) - if err != nil { - t.Fatalf("%s: Error creating request: %s", k, err) - } - req, err := http.NewRequest("GET", server.URL, nil) - if err != nil { - t.Fatalf("%s: Error creating request: %s", k, err) - } - - spdyTransport := NewSpdyRoundTripper(testCase.clientTLS, redirect) - - var proxierCalled bool - var proxyCalledWithHost string - var proxyCalledWithAuth bool - var proxyCalledWithAuthHeader string - if testCase.proxyServerFunc != nil { - proxyHandler := goproxy.NewProxyHttpServer() - - proxyHandler.OnRequest().HandleConnectFunc(func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) { - proxyCalledWithHost = host - - proxyAuthHeaderName := "Proxy-Authorization" - _, proxyCalledWithAuth = ctx.Req.Header[proxyAuthHeaderName] - proxyCalledWithAuthHeader = ctx.Req.Header.Get(proxyAuthHeaderName) - return goproxy.OkConnect, host - }) - - proxy := testCase.proxyServerFunc(proxyHandler) - - spdyTransport.proxier = func(proxierReq *http.Request) (*url.URL, error) { - proxierCalled = true - proxyURL, err := url.Parse(proxy.URL) - if err != nil { - return nil, err - } - proxyURL.User = testCase.proxyAuth - return proxyURL, nil - } - defer proxy.Close() - } - - client := &http.Client{Transport: spdyTransport} - - resp, err := client.Do(req) - var conn httpstream.Connection - if err == nil { - conn, err = spdyTransport.NewConnection(resp) - } - haveErr := err != nil - if e, a := testCase.shouldError, haveErr; e != a { - t.Fatalf("%s: shouldError=%t, got %t: %v", k, e, a, err) - } - if testCase.shouldError { - continue - } - defer conn.Close() - - if resp.StatusCode != http.StatusSwitchingProtocols { - t.Fatalf("%s: expected http 101 switching protocols, got %d", k, resp.StatusCode) - } - - stream, err := conn.CreateStream(http.Header{}) - if err != nil { - t.Fatalf("%s: error creating client stream: %s", k, err) - } - - n, err := stream.Write([]byte("hello")) - if err != nil { - t.Fatalf("%s: error writing to stream: %s", k, err) - } - if n != 5 { - t.Fatalf("%s: Expected to write 5 bytes, but actually wrote %d", k, n) - } - - b := make([]byte, 5) - n, err = stream.Read(b) - if err != nil { - t.Fatalf("%s: error reading from stream: %s", k, err) - } - if n != 5 { - t.Fatalf("%s: Expected to read 5 bytes, but actually read %d", k, n) - } - if e, a := "hello", string(b[0:n]); e != a { - t.Fatalf("%s: expected '%s', got '%s'", k, e, a) - } - - if testCase.proxyServerFunc != nil { - if !proxierCalled { - t.Fatalf("%s: Expected to use a proxy but proxier in SpdyRoundTripper wasn't called", k) - } - if proxyCalledWithHost != serverURL.Host { - t.Fatalf("%s: Expected to see a call to the proxy for backend %q, got %q", k, serverURL.Host, proxyCalledWithHost) - } - } - - var expectedProxyAuth string - if testCase.proxyAuth != nil { - encodedCredentials := base64.StdEncoding.EncodeToString([]byte(testCase.proxyAuth.String())) - expectedProxyAuth = "Basic " + encodedCredentials - } - if len(expectedProxyAuth) == 0 && proxyCalledWithAuth { - t.Fatalf("%s: Proxy authorization unexpected, got %q", k, proxyCalledWithAuthHeader) - } - if proxyCalledWithAuthHeader != expectedProxyAuth { - t.Fatalf("%s: Expected to see a call to the proxy with credentials %q, got %q", k, testCase.proxyAuth, proxyCalledWithAuthHeader) - } - } - }) - } -} - -func TestRoundTripRedirects(t *testing.T) { - tests := []struct { - redirects int32 - expectSuccess bool - }{ - {0, true}, - {1, true}, - {10, true}, - {11, false}, - } - for _, test := range tests { - t.Run(fmt.Sprintf("with %d redirects", test.redirects), func(t *testing.T) { - var redirects int32 = 0 - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if redirects < test.redirects { - redirects = atomic.AddInt32(&redirects, 1) - http.Redirect(w, req, "redirect", http.StatusFound) - return - } - streamCh := make(chan httpstream.Stream) - - responseUpgrader := NewResponseUpgrader() - spdyConn := responseUpgrader.UpgradeResponse(w, req, func(s httpstream.Stream, replySent <-chan struct{}) error { - streamCh <- s - return nil - }) - if spdyConn == nil { - t.Fatalf("unexpected nil spdyConn") - } - defer spdyConn.Close() - - stream := <-streamCh - io.Copy(stream, stream) - })) - defer server.Close() - - req, err := http.NewRequest("GET", server.URL, nil) - if err != nil { - t.Fatalf("Error creating request: %s", err) - } - - spdyTransport := NewSpdyRoundTripper(nil, true) - client := &http.Client{Transport: spdyTransport} - - resp, err := client.Do(req) - if test.expectSuccess { - if err != nil { - t.Fatalf("error calling Do: %v", err) - } - } else { - if err == nil { - t.Fatalf("expecting an error") - } else if !strings.Contains(err.Error(), "too many redirects") { - t.Fatalf("expecting too many redirects, got %v", err) - } - return - } - - conn, err := spdyTransport.NewConnection(resp) - if err != nil { - t.Fatalf("error calling NewConnection: %v", err) - } - defer conn.Close() - - if resp.StatusCode != http.StatusSwitchingProtocols { - t.Fatalf("expected http 101 switching protocols, got %d", resp.StatusCode) - } - - stream, err := conn.CreateStream(http.Header{}) - if err != nil { - t.Fatalf("error creating client stream: %s", err) - } - - n, err := stream.Write([]byte("hello")) - if err != nil { - t.Fatalf("error writing to stream: %s", err) - } - if n != 5 { - t.Fatalf("Expected to write 5 bytes, but actually wrote %d", n) - } - - b := make([]byte, 5) - n, err = stream.Read(b) - if err != nil { - t.Fatalf("error reading from stream: %s", err) - } - if n != 5 { - t.Fatalf("Expected to read 5 bytes, but actually read %d", n) - } - if e, a := "hello", string(b[0:n]); e != a { - t.Fatalf("expected '%s', got '%s'", e, a) - } - }) - } -} - -// exampleCert was generated from crypto/tls/generate_cert.go with the following command: -// go run generate_cert.go --rsa-bits 512 --host example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h -var exampleCert = []byte(`-----BEGIN CERTIFICATE----- -MIIBdzCCASGgAwIBAgIRAOVTAdPnfbS5V85mfS90TfIwDQYJKoZIhvcNAQELBQAw -EjEQMA4GA1UEChMHQWNtZSBDbzAgFw03MDAxMDEwMDAwMDBaGA8yMDg0MDEyOTE2 -MDAwMFowEjEQMA4GA1UEChMHQWNtZSBDbzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgC -QQCoVSqeu8TBvF+70T7Jm4340YQNhds6IxjRoifenYodAO1dnKGrcbF266DJGunh -nIjQH7B12tduhl0fLK4Ezf7/AgMBAAGjUDBOMA4GA1UdDwEB/wQEAwICpDATBgNV -HSUEDDAKBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MBYGA1UdEQQPMA2CC2V4 -YW1wbGUuY29tMA0GCSqGSIb3DQEBCwUAA0EAk1kVa5uZ/AzwYDVcS9bpM/czwjjV -xq3VeSCfmNa2uNjbFvodmCRwZOHUvipAMGCUCV6j5vMrJ8eMj8tCQ36W9A== ------END CERTIFICATE-----`) - -var exampleKey = []byte(`-----BEGIN RSA PRIVATE KEY----- -MIIBOgIBAAJBAKhVKp67xMG8X7vRPsmbjfjRhA2F2zojGNGiJ96dih0A7V2coatx -sXbroMka6eGciNAfsHXa126GXR8srgTN/v8CAwEAAQJASdzdD7vKsUwMIejGCUb1 -fAnLTPfAY3lFCa+CmR89nE22dAoRDv+5RbnBsZ58BazPNJHrsVPRlfXB3OQmSQr0 -SQIhANoJhs+xOJE/i8nJv0uAbzKyiD1YkvRkta0GpUOULyAVAiEAxaQus3E/SuqD -P7y5NeJnE7X6XkyC35zrsJRkz7orE8MCIHdDjsI8pjyNDeGqwUCDWE/a6DrmIDwe -emHSqMN2YvChAiEAnxLCM9NWaenOsaIoP+J1rDuvw+4499nJKVqGuVrSCRkCIEqK -4KSchPMc3x8M/uhw9oWTtKFmjA/PPh0FsWCdKrEy ------END RSA PRIVATE KEY-----`) - -// localhostCert was generated from crypto/tls/generate_cert.go with the following command: -// go run generate_cert.go --rsa-bits 512 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h -var localhostCert = []byte(`-----BEGIN CERTIFICATE----- -MIIBjzCCATmgAwIBAgIRAKpi2WmTcFrVjxrl5n5YDUEwDQYJKoZIhvcNAQELBQAw -EjEQMA4GA1UEChMHQWNtZSBDbzAgFw03MDAxMDEwMDAwMDBaGA8yMDg0MDEyOTE2 -MDAwMFowEjEQMA4GA1UEChMHQWNtZSBDbzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgC -QQC9fEbRszP3t14Gr4oahV7zFObBI4TfA5i7YnlMXeLinb7MnvT4bkfOJzE6zktn -59zP7UiHs3l4YOuqrjiwM413AgMBAAGjaDBmMA4GA1UdDwEB/wQEAwICpDATBgNV -HSUEDDAKBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MC4GA1UdEQQnMCWCC2V4 -YW1wbGUuY29thwR/AAABhxAAAAAAAAAAAAAAAAAAAAABMA0GCSqGSIb3DQEBCwUA -A0EAUsVE6KMnza/ZbodLlyeMzdo7EM/5nb5ywyOxgIOCf0OOLHsPS9ueGLQX9HEG -//yjTXuhNcUugExIjM/AIwAZPQ== ------END CERTIFICATE-----`) - -// localhostKey is the private key for localhostCert. -var localhostKey = []byte(`-----BEGIN RSA PRIVATE KEY----- -MIIBOwIBAAJBAL18RtGzM/e3XgavihqFXvMU5sEjhN8DmLtieUxd4uKdvsye9Phu -R84nMTrOS2fn3M/tSIezeXhg66quOLAzjXcCAwEAAQJBAKcRxH9wuglYLBdI/0OT -BLzfWPZCEw1vZmMR2FF1Fm8nkNOVDPleeVGTWoOEcYYlQbpTmkGSxJ6ya+hqRi6x -goECIQDx3+X49fwpL6B5qpJIJMyZBSCuMhH4B7JevhGGFENi3wIhAMiNJN5Q3UkL -IuSvv03kaPR5XVQ99/UeEetUgGvBcABpAiBJSBzVITIVCGkGc7d+RCf49KTCIklv -bGWObufAR8Ni4QIgWpILjW8dkGg8GOUZ0zaNA6Nvt6TIv2UWGJ4v5PoV98kCIQDx -rIiZs5QbKdycsv9gQJzwQAogC8o04X3Zz3dsoX+h4A== ------END RSA PRIVATE KEY-----`) diff --git a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade_test.go b/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade_test.go deleted file mode 100644 index 5a514dd5bf..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/httpstream/spdy/upgrade_test.go +++ /dev/null @@ -1,93 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package spdy - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -func TestUpgradeResponse(t *testing.T) { - testCases := []struct { - connectionHeader string - upgradeHeader string - shouldError bool - }{ - { - connectionHeader: "", - upgradeHeader: "", - shouldError: true, - }, - { - connectionHeader: "Upgrade", - upgradeHeader: "", - shouldError: true, - }, - { - connectionHeader: "", - upgradeHeader: "SPDY/3.1", - shouldError: true, - }, - { - connectionHeader: "Upgrade", - upgradeHeader: "SPDY/3.1", - shouldError: false, - }, - } - - for i, testCase := range testCases { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - upgrader := NewResponseUpgrader() - conn := upgrader.UpgradeResponse(w, req, nil) - haveErr := conn == nil - if e, a := testCase.shouldError, haveErr; e != a { - t.Fatalf("%d: expected shouldErr=%t, got %t", i, testCase.shouldError, haveErr) - } - if haveErr { - return - } - if conn == nil { - t.Fatalf("%d: unexpected nil conn", i) - } - defer conn.Close() - })) - defer server.Close() - - req, err := http.NewRequest("GET", server.URL, nil) - if err != nil { - t.Fatalf("%d: error creating request: %s", i, err) - } - - req.Header.Set("Connection", testCase.connectionHeader) - req.Header.Set("Upgrade", testCase.upgradeHeader) - - client := &http.Client{} - resp, err := client.Do(req) - if err != nil { - t.Fatalf("%d: unexpected non-nil err from client.Do: %s", i, err) - } - - if testCase.shouldError { - continue - } - - if resp.StatusCode != http.StatusSwitchingProtocols { - t.Fatalf("%d: expected status 101 switching protocols, got %d", i, resp.StatusCode) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/intstr/BUILD b/vendor/k8s.io/apimachinery/pkg/util/intstr/BUILD deleted file mode 100644 index 73e62bcde8..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/intstr/BUILD +++ /dev/null @@ -1,47 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["intstr_test.go"], - embed = [":go_default_library"], - deps = ["//vendor/github.com/ghodss/yaml:go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "generated.pb.go", - "intstr.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/intstr", - deps = [ - "//vendor/github.com/gogo/protobuf/proto:go_default_library", - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/github.com/google/gofuzz:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) - -filegroup( - name = "go_default_library_protos", - srcs = ["generated.proto"], - visibility = ["//visibility:public"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr_test.go b/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr_test.go deleted file mode 100644 index 4faba46f8d..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/intstr/intstr_test.go +++ /dev/null @@ -1,176 +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 intstr - -import ( - "encoding/json" - "reflect" - "testing" - - "github.com/ghodss/yaml" -) - -func TestFromInt(t *testing.T) { - i := FromInt(93) - if i.Type != Int || i.IntVal != 93 { - t.Errorf("Expected IntVal=93, got %+v", i) - } -} - -func TestFromString(t *testing.T) { - i := FromString("76") - if i.Type != String || i.StrVal != "76" { - t.Errorf("Expected StrVal=\"76\", got %+v", i) - } -} - -type IntOrStringHolder struct { - IOrS IntOrString `json:"val"` -} - -func TestIntOrStringUnmarshalJSON(t *testing.T) { - cases := []struct { - input string - result IntOrString - }{ - {"{\"val\": 123}", FromInt(123)}, - {"{\"val\": \"123\"}", FromString("123")}, - } - - for _, c := range cases { - var result IntOrStringHolder - if err := json.Unmarshal([]byte(c.input), &result); err != nil { - t.Errorf("Failed to unmarshal input '%v': %v", c.input, err) - } - if result.IOrS != c.result { - t.Errorf("Failed to unmarshal input '%v': expected %+v, got %+v", c.input, c.result, result) - } - } -} - -func TestIntOrStringMarshalJSON(t *testing.T) { - cases := []struct { - input IntOrString - result string - }{ - {FromInt(123), "{\"val\":123}"}, - {FromString("123"), "{\"val\":\"123\"}"}, - } - - for _, c := range cases { - input := IntOrStringHolder{c.input} - result, err := json.Marshal(&input) - if err != nil { - t.Errorf("Failed to marshal input '%v': %v", input, err) - } - if string(result) != c.result { - t.Errorf("Failed to marshal input '%v': expected: %+v, got %q", input, c.result, string(result)) - } - } -} - -func TestIntOrStringMarshalJSONUnmarshalYAML(t *testing.T) { - cases := []struct { - input IntOrString - }{ - {FromInt(123)}, - {FromString("123")}, - } - - for _, c := range cases { - input := IntOrStringHolder{c.input} - jsonMarshalled, err := json.Marshal(&input) - if err != nil { - t.Errorf("1: Failed to marshal input: '%v': %v", input, err) - } - - var result IntOrStringHolder - err = yaml.Unmarshal(jsonMarshalled, &result) - if err != nil { - t.Errorf("2: Failed to unmarshal '%+v': %v", string(jsonMarshalled), err) - } - - if !reflect.DeepEqual(input, result) { - t.Errorf("3: Failed to marshal input '%+v': got %+v", input, result) - } - } -} - -func TestGetValueFromIntOrPercent(t *testing.T) { - tests := []struct { - input IntOrString - total int - roundUp bool - expectErr bool - expectVal int - }{ - { - input: FromInt(123), - expectErr: false, - expectVal: 123, - }, - { - input: FromString("90%"), - total: 100, - roundUp: true, - expectErr: false, - expectVal: 90, - }, - { - input: FromString("90%"), - total: 95, - roundUp: true, - expectErr: false, - expectVal: 86, - }, - { - input: FromString("90%"), - total: 95, - roundUp: false, - expectErr: false, - expectVal: 85, - }, - { - input: FromString("%"), - expectErr: true, - }, - { - input: FromString("90#"), - expectErr: true, - }, - { - input: FromString("#%"), - expectErr: true, - }, - } - - for i, test := range tests { - t.Logf("test case %d", i) - value, err := GetValueFromIntOrPercent(&test.input, test.total, test.roundUp) - if test.expectErr && err == nil { - t.Errorf("expected error, but got none") - continue - } - if !test.expectErr && err != nil { - t.Errorf("unexpected err: %v", err) - continue - } - if test.expectVal != value { - t.Errorf("expected %v, but got %v", test.expectVal, value) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/json/BUILD b/vendor/k8s.io/apimachinery/pkg/util/json/BUILD deleted file mode 100644 index c42821fc88..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/json/BUILD +++ /dev/null @@ -1,32 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_library( - name = "go_default_library", - srcs = ["json.go"], - importpath = "k8s.io/apimachinery/pkg/util/json", -) - -go_test( - name = "go_default_test", - srcs = ["json_test.go"], - embed = [":go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/json/json_test.go b/vendor/k8s.io/apimachinery/pkg/util/json/json_test.go deleted file mode 100644 index cd0c18bb2e..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/json/json_test.go +++ /dev/null @@ -1,319 +0,0 @@ -// +build go1.8 - -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package json - -import ( - "fmt" - "math" - "reflect" - "strconv" - "strings" - "testing" -) - -func TestEvaluateTypes(t *testing.T) { - testCases := []struct { - In string - Data interface{} - Out string - Err bool - }{ - // Invalid syntaxes - { - In: `x`, - Err: true, - }, - { - In: ``, - Err: true, - }, - - // Null - { - In: `null`, - Data: nil, - Out: `null`, - }, - // Booleans - { - In: `true`, - Data: true, - Out: `true`, - }, - { - In: `false`, - Data: false, - Out: `false`, - }, - - // Integers - { - In: `0`, - Data: int64(0), - Out: `0`, - }, - { - In: `-0`, - Data: int64(-0), - Out: `0`, - }, - { - In: `1`, - Data: int64(1), - Out: `1`, - }, - { - In: `2147483647`, - Data: int64(math.MaxInt32), - Out: `2147483647`, - }, - { - In: `-2147483648`, - Data: int64(math.MinInt32), - Out: `-2147483648`, - }, - { - In: `9223372036854775807`, - Data: int64(math.MaxInt64), - Out: `9223372036854775807`, - }, - { - In: `-9223372036854775808`, - Data: int64(math.MinInt64), - Out: `-9223372036854775808`, - }, - - // Int overflow - { - In: `9223372036854775808`, // MaxInt64 + 1 - Data: float64(9223372036854775808), - Out: `9223372036854776000`, - }, - { - In: `-9223372036854775809`, // MinInt64 - 1 - Data: float64(math.MinInt64), - Out: `-9223372036854776000`, - }, - - // Floats - { - In: `0.0`, - Data: float64(0), - Out: `0`, - }, - { - In: `-0.0`, - Data: float64(-0.0), - Out: `-0`, - }, - { - In: `0.5`, - Data: float64(0.5), - Out: `0.5`, - }, - { - In: `1e3`, - Data: float64(1e3), - Out: `1000`, - }, - { - In: `1.5`, - Data: float64(1.5), - Out: `1.5`, - }, - { - In: `-0.3`, - Data: float64(-.3), - Out: `-0.3`, - }, - { - // Largest representable float32 - In: `3.40282346638528859811704183484516925440e+38`, - Data: float64(math.MaxFloat32), - Out: strconv.FormatFloat(math.MaxFloat32, 'g', -1, 64), - }, - { - // Smallest float32 without losing precision - In: `1.175494351e-38`, - Data: float64(1.175494351e-38), - Out: `1.175494351e-38`, - }, - { - // float32 closest to zero - In: `1.401298464324817070923729583289916131280e-45`, - Data: float64(math.SmallestNonzeroFloat32), - Out: strconv.FormatFloat(math.SmallestNonzeroFloat32, 'g', -1, 64), - }, - { - // Largest representable float64 - In: `1.797693134862315708145274237317043567981e+308`, - Data: float64(math.MaxFloat64), - Out: strconv.FormatFloat(math.MaxFloat64, 'g', -1, 64), - }, - { - // Closest to zero without losing precision - In: `2.2250738585072014e-308`, - Data: float64(2.2250738585072014e-308), - Out: `2.2250738585072014e-308`, - }, - - { - // float64 closest to zero - In: `4.940656458412465441765687928682213723651e-324`, - Data: float64(math.SmallestNonzeroFloat64), - Out: strconv.FormatFloat(math.SmallestNonzeroFloat64, 'g', -1, 64), - }, - - { - // math.MaxFloat64 + 2 overflow - In: `1.7976931348623159e+308`, - Err: true, - }, - - // Strings - { - In: `""`, - Data: string(""), - Out: `""`, - }, - { - In: `"0"`, - Data: string("0"), - Out: `"0"`, - }, - { - In: `"A"`, - Data: string("A"), - Out: `"A"`, - }, - { - In: `"Iñtërnâtiônàlizætiøn"`, - Data: string("Iñtërnâtiônàlizætiøn"), - Out: `"Iñtërnâtiônàlizætiøn"`, - }, - - // Arrays - { - In: `[]`, - Data: []interface{}{}, - Out: `[]`, - }, - { - In: `[` + strings.Join([]string{ - `null`, - `true`, - `false`, - `0`, - `9223372036854775807`, - `0.0`, - `0.5`, - `1.0`, - `1.797693134862315708145274237317043567981e+308`, - `"0"`, - `"A"`, - `"Iñtërnâtiônàlizætiøn"`, - `[null,true,1,1.0,1.5]`, - `{"boolkey":true,"floatkey":1.0,"intkey":1,"nullkey":null}`, - }, ",") + `]`, - Data: []interface{}{ - nil, - true, - false, - int64(0), - int64(math.MaxInt64), - float64(0.0), - float64(0.5), - float64(1.0), - float64(math.MaxFloat64), - string("0"), - string("A"), - string("Iñtërnâtiônàlizætiøn"), - []interface{}{nil, true, int64(1), float64(1.0), float64(1.5)}, - map[string]interface{}{"nullkey": nil, "boolkey": true, "intkey": int64(1), "floatkey": float64(1.0)}, - }, - Out: `[` + strings.Join([]string{ - `null`, - `true`, - `false`, - `0`, - `9223372036854775807`, - `0`, - `0.5`, - `1`, - strconv.FormatFloat(math.MaxFloat64, 'g', -1, 64), - `"0"`, - `"A"`, - `"Iñtërnâtiônàlizætiøn"`, - `[null,true,1,1,1.5]`, - `{"boolkey":true,"floatkey":1,"intkey":1,"nullkey":null}`, // gets alphabetized by Marshal - }, ",") + `]`, - }, - - // Maps - { - In: `{}`, - Data: map[string]interface{}{}, - Out: `{}`, - }, - { - In: `{"boolkey":true,"floatkey":1.0,"intkey":1,"nullkey":null}`, - Data: map[string]interface{}{"nullkey": nil, "boolkey": true, "intkey": int64(1), "floatkey": float64(1.0)}, - Out: `{"boolkey":true,"floatkey":1,"intkey":1,"nullkey":null}`, // gets alphabetized by Marshal - }, - } - - for _, tc := range testCases { - inputJSON := fmt.Sprintf(`{"data":%s}`, tc.In) - expectedJSON := fmt.Sprintf(`{"data":%s}`, tc.Out) - m := map[string]interface{}{} - err := Unmarshal([]byte(inputJSON), &m) - if tc.Err && err != nil { - // Expected error - continue - } - if err != nil { - t.Errorf("%s: error decoding: %v", tc.In, err) - continue - } - if tc.Err { - t.Errorf("%s: expected error, got none", tc.In) - continue - } - data, ok := m["data"] - if !ok { - t.Errorf("%s: decoded object missing data key: %#v", tc.In, m) - continue - } - if !reflect.DeepEqual(tc.Data, data) { - t.Errorf("%s: expected\n\t%#v (%v), got\n\t%#v (%v)", tc.In, tc.Data, reflect.TypeOf(tc.Data), data, reflect.TypeOf(data)) - continue - } - - outputJSON, err := Marshal(m) - if err != nil { - t.Errorf("%s: error encoding: %v", tc.In, err) - continue - } - - if expectedJSON != string(outputJSON) { - t.Errorf("%s: expected\n\t%s, got\n\t%s", tc.In, expectedJSON, string(outputJSON)) - continue - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/BUILD b/vendor/k8s.io/apimachinery/pkg/util/mergepatch/BUILD deleted file mode 100644 index 0ddf97d1db..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/BUILD +++ /dev/null @@ -1,39 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["util_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "errors.go", - "util.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/mergepatch", - deps = [ - "//vendor/github.com/davecgh/go-spew/spew:go_default_library", - "//vendor/github.com/ghodss/yaml:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util_test.go b/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util_test.go deleted file mode 100644 index 1b37e3ef5e..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/mergepatch/util_test.go +++ /dev/null @@ -1,138 +0,0 @@ -/* -Copyright 2017 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 mergepatch - -import ( - "fmt" - "testing" -) - -func TestHasConflicts(t *testing.T) { - testCases := []struct { - A interface{} - B interface{} - Ret bool - }{ - {A: "hello", B: "hello", Ret: false}, - {A: "hello", B: "hell", Ret: true}, - {A: "hello", B: nil, Ret: true}, - {A: "hello", B: 1, Ret: true}, - {A: "hello", B: float64(1.0), Ret: true}, - {A: "hello", B: false, Ret: true}, - {A: 1, B: 1, Ret: false}, - {A: nil, B: nil, Ret: false}, - {A: false, B: false, Ret: false}, - {A: float64(3), B: float64(3), Ret: false}, - - {A: "hello", B: []interface{}{}, Ret: true}, - {A: []interface{}{1}, B: []interface{}{}, Ret: true}, - {A: []interface{}{}, B: []interface{}{}, Ret: false}, - {A: []interface{}{1}, B: []interface{}{1}, Ret: false}, - {A: map[string]interface{}{}, B: []interface{}{1}, Ret: true}, - - {A: map[string]interface{}{}, B: map[string]interface{}{"a": 1}, Ret: false}, - {A: map[string]interface{}{"a": 1}, B: map[string]interface{}{"a": 1}, Ret: false}, - {A: map[string]interface{}{"a": 1}, B: map[string]interface{}{"a": 2}, Ret: true}, - {A: map[string]interface{}{"a": 1}, B: map[string]interface{}{"b": 2}, Ret: false}, - - { - A: map[string]interface{}{"a": []interface{}{1}}, - B: map[string]interface{}{"a": []interface{}{1}}, - Ret: false, - }, - { - A: map[string]interface{}{"a": []interface{}{1}}, - B: map[string]interface{}{"a": []interface{}{}}, - Ret: true, - }, - { - A: map[string]interface{}{"a": []interface{}{1}}, - B: map[string]interface{}{"a": 1}, - Ret: true, - }, - - // Maps and lists with multiple entries. - { - A: map[string]interface{}{"a": 1, "b": 2}, - B: map[string]interface{}{"a": 1, "b": 0}, - Ret: true, - }, - { - A: map[string]interface{}{"a": 1, "b": 2}, - B: map[string]interface{}{"a": 1, "b": 2}, - Ret: false, - }, - { - A: map[string]interface{}{"a": 1, "b": 2}, - B: map[string]interface{}{"a": 1, "b": 0, "c": 3}, - Ret: true, - }, - { - A: map[string]interface{}{"a": 1, "b": 2}, - B: map[string]interface{}{"a": 1, "b": 2, "c": 3}, - Ret: false, - }, - { - A: map[string]interface{}{"a": []interface{}{1, 2}}, - B: map[string]interface{}{"a": []interface{}{1, 0}}, - Ret: true, - }, - { - A: map[string]interface{}{"a": []interface{}{1, 2}}, - B: map[string]interface{}{"a": []interface{}{1, 2}}, - Ret: false, - }, - - // Numeric types are not interchangeable. - // Callers are expected to ensure numeric types are consistent in 'left' and 'right'. - {A: int(0), B: int64(0), Ret: true}, - {A: int(0), B: float64(0), Ret: true}, - {A: int64(0), B: float64(0), Ret: true}, - // Other types are not interchangeable. - {A: int(0), B: "0", Ret: true}, - {A: int(0), B: nil, Ret: true}, - {A: int(0), B: false, Ret: true}, - {A: "true", B: true, Ret: true}, - {A: "null", B: nil, Ret: true}, - } - - for _, testCase := range testCases { - testStr := fmt.Sprintf("A = %#v, B = %#v", testCase.A, testCase.B) - // Run each test case multiple times if it passes because HasConflicts() - // uses map iteration, which returns keys in nondeterministic order. - for try := 0; try < 10; try++ { - out, err := HasConflicts(testCase.A, testCase.B) - if err != nil { - t.Errorf("%v: unexpected error: %v", testStr, err) - break - } - if out != testCase.Ret { - t.Errorf("%v: expected %t got %t", testStr, testCase.Ret, out) - break - } - out, err = HasConflicts(testCase.B, testCase.A) - if err != nil { - t.Errorf("%v: unexpected error: %v", testStr, err) - break - } - if out != testCase.Ret { - t.Errorf("%v: expected reversed %t got %t", testStr, testCase.Ret, out) - break - } - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/net/BUILD b/vendor/k8s.io/apimachinery/pkg/util/net/BUILD deleted file mode 100644 index 9d0fffb11f..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/net/BUILD +++ /dev/null @@ -1,50 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "http_test.go", - "interface_test.go", - "port_range_test.go", - "port_split_test.go", - "util_test.go", - ], - embed = [":go_default_library"], - deps = ["//vendor/github.com/spf13/pflag:go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "http.go", - "interface.go", - "port_range.go", - "port_split.go", - "util.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/net", - deps = [ - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/golang.org/x/net/http2:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/net/http.go b/vendor/k8s.io/apimachinery/pkg/util/net/http.go index bc2a531b9d..76eb8b4fa2 100644 --- a/vendor/k8s.io/apimachinery/pkg/util/net/http.go +++ b/vendor/k8s.io/apimachinery/pkg/util/net/http.go @@ -61,6 +61,9 @@ func JoinPreservingTrailingSlash(elem ...string) string { // differentiate probable errors in connection behavior between normal "this is // disconnected" should use the method. func IsProbableEOF(err error) bool { + if err == nil { + return false + } if uerr, ok := err.(*url.Error); ok { err = uerr.Err } diff --git a/vendor/k8s.io/apimachinery/pkg/util/net/http_test.go b/vendor/k8s.io/apimachinery/pkg/util/net/http_test.go deleted file mode 100644 index 98bd649717..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/net/http_test.go +++ /dev/null @@ -1,282 +0,0 @@ -// +build go1.8 - -/* -Copyright 2016 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 net - -import ( - "crypto/tls" - "fmt" - "net" - "net/http" - "net/url" - "os" - "reflect" - "testing" -) - -func TestGetClientIP(t *testing.T) { - ipString := "10.0.0.1" - ip := net.ParseIP(ipString) - invalidIPString := "invalidIPString" - testCases := []struct { - Request http.Request - ExpectedIP net.IP - }{ - { - Request: http.Request{}, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Real-Ip": {ipString}, - }, - }, - ExpectedIP: ip, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Real-Ip": {invalidIPString}, - }, - }, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Forwarded-For": {ipString}, - }, - }, - ExpectedIP: ip, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Forwarded-For": {invalidIPString}, - }, - }, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Forwarded-For": {invalidIPString + "," + ipString}, - }, - }, - ExpectedIP: ip, - }, - { - Request: http.Request{ - // RemoteAddr is in the form host:port - RemoteAddr: ipString + ":1234", - }, - ExpectedIP: ip, - }, - { - Request: http.Request{ - RemoteAddr: invalidIPString, - }, - }, - { - Request: http.Request{ - Header: map[string][]string{ - "X-Forwarded-For": {invalidIPString}, - }, - // RemoteAddr is in the form host:port - RemoteAddr: ipString, - }, - ExpectedIP: ip, - }, - } - - for i, test := range testCases { - if a, e := GetClientIP(&test.Request), test.ExpectedIP; reflect.DeepEqual(e, a) != true { - t.Fatalf("test case %d failed. expected: %v, actual: %v", i, e, a) - } - } -} - -func TestAppendForwardedForHeader(t *testing.T) { - testCases := []struct { - addr, forwarded, expected string - }{ - {"1.2.3.4:8000", "", "1.2.3.4"}, - {"1.2.3.4:8000", "8.8.8.8", "8.8.8.8, 1.2.3.4"}, - {"1.2.3.4:8000", "8.8.8.8, 1.2.3.4", "8.8.8.8, 1.2.3.4, 1.2.3.4"}, - {"1.2.3.4:8000", "foo,bar", "foo,bar, 1.2.3.4"}, - } - for i, test := range testCases { - req := &http.Request{ - RemoteAddr: test.addr, - Header: make(http.Header), - } - if test.forwarded != "" { - req.Header.Set("X-Forwarded-For", test.forwarded) - } - - AppendForwardedForHeader(req) - actual := req.Header.Get("X-Forwarded-For") - if actual != test.expected { - t.Errorf("[%d] Expected %q, Got %q", i, test.expected, actual) - } - } -} - -func TestProxierWithNoProxyCIDR(t *testing.T) { - testCases := []struct { - name string - noProxy string - url string - - expectedDelegated bool - }{ - { - name: "no env", - url: "https://192.168.143.1/api", - expectedDelegated: true, - }, - { - name: "no cidr", - noProxy: "192.168.63.1", - url: "https://192.168.143.1/api", - expectedDelegated: true, - }, - { - name: "hostname", - noProxy: "192.168.63.0/24,192.168.143.0/24", - url: "https://my-hostname/api", - expectedDelegated: true, - }, - { - name: "match second cidr", - noProxy: "192.168.63.0/24,192.168.143.0/24", - url: "https://192.168.143.1/api", - expectedDelegated: false, - }, - { - name: "match second cidr with host:port", - noProxy: "192.168.63.0/24,192.168.143.0/24", - url: "https://192.168.143.1:8443/api", - expectedDelegated: false, - }, - { - name: "IPv6 cidr", - noProxy: "2001:db8::/48", - url: "https://[2001:db8::1]/api", - expectedDelegated: false, - }, - { - name: "IPv6+port cidr", - noProxy: "2001:db8::/48", - url: "https://[2001:db8::1]:8443/api", - expectedDelegated: false, - }, - { - name: "IPv6, not matching cidr", - noProxy: "2001:db8::/48", - url: "https://[2001:db8:1::1]/api", - expectedDelegated: true, - }, - { - name: "IPv6+port, not matching cidr", - noProxy: "2001:db8::/48", - url: "https://[2001:db8:1::1]:8443/api", - expectedDelegated: true, - }, - } - - for _, test := range testCases { - os.Setenv("NO_PROXY", test.noProxy) - actualDelegated := false - proxyFunc := NewProxierWithNoProxyCIDR(func(req *http.Request) (*url.URL, error) { - actualDelegated = true - return nil, nil - }) - - req, err := http.NewRequest("GET", test.url, nil) - if err != nil { - t.Errorf("%s: unexpected err: %v", test.name, err) - continue - } - if _, err := proxyFunc(req); err != nil { - t.Errorf("%s: unexpected err: %v", test.name, err) - continue - } - - if test.expectedDelegated != actualDelegated { - t.Errorf("%s: expected %v, got %v", test.name, test.expectedDelegated, actualDelegated) - continue - } - } -} - -type fakeTLSClientConfigHolder struct { - called bool -} - -func (f *fakeTLSClientConfigHolder) TLSClientConfig() *tls.Config { - f.called = true - return nil -} -func (f *fakeTLSClientConfigHolder) RoundTrip(*http.Request) (*http.Response, error) { - return nil, nil -} - -func TestTLSClientConfigHolder(t *testing.T) { - rt := &fakeTLSClientConfigHolder{} - TLSClientConfig(rt) - - if !rt.called { - t.Errorf("didn't find tls config") - } -} - -func TestJoinPreservingTrailingSlash(t *testing.T) { - tests := []struct { - a string - b string - want string - }{ - // All empty - {"", "", ""}, - - // Empty a - {"", "/", "/"}, - {"", "foo", "foo"}, - {"", "/foo", "/foo"}, - {"", "/foo/", "/foo/"}, - - // Empty b - {"/", "", "/"}, - {"foo", "", "foo"}, - {"/foo", "", "/foo"}, - {"/foo/", "", "/foo/"}, - - // Both populated - {"/", "/", "/"}, - {"foo", "foo", "foo/foo"}, - {"/foo", "/foo", "/foo/foo"}, - {"/foo/", "/foo/", "/foo/foo/"}, - } - for _, tt := range tests { - name := fmt.Sprintf("%q+%q=%q", tt.a, tt.b, tt.want) - t.Run(name, func(t *testing.T) { - if got := JoinPreservingTrailingSlash(tt.a, tt.b); got != tt.want { - t.Errorf("JoinPreservingTrailingSlash() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/net/interface_test.go b/vendor/k8s.io/apimachinery/pkg/util/net/interface_test.go deleted file mode 100644 index 4799d43aea..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/net/interface_test.go +++ /dev/null @@ -1,725 +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 net - -import ( - "fmt" - "io/ioutil" - "net" - "os" - "strings" - "testing" -) - -const gatewayfirst = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0 -eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0 -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` -const gatewaylast = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0 -eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0 -` -const gatewaymiddle = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0 -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` -const noInternetConnection = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` -const nothing = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -` -const badDestination = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth3 00000000 0100FE0A 0003 0 0 1024 00000000 0 0 0 -eth3 0000FE0AA1 00000000 0001 0 0 0 0080FFFF 0 0 0 -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` -const badGateway = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth3 00000000 0100FE0AA1 0003 0 0 1024 00000000 0 0 0 -eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0 -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` -const route_Invalidhex = `Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT -eth3 00000000 0100FE0AA 0003 0 0 1024 00000000 0 0 0 -eth3 0000FE0A 00000000 0001 0 0 0 0080FFFF 0 0 0 -docker0 000011AC 00000000 0001 0 0 0 0000FFFF 0 0 0 -virbr0 007AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0 -` - -const v6gatewayfirst = `00000000000000000000000000000000 00 00000000000000000000000000000000 00 20010001000000000000000000000001 00000064 00000000 00000000 00000003 eth3 -20010002000000000000000000000000 40 00000000000000000000000000000000 00 00000000000000000000000000000000 00000100 00000000 00000000 00000001 eth3 -00000000000000000000000000000000 60 00000000000000000000000000000000 00 00000000000000000000000000000000 00000400 00000000 00000000 00200200 lo -` -const v6gatewaylast = `20010002000000000000000000000000 40 00000000000000000000000000000000 00 00000000000000000000000000000000 00000100 00000000 00000000 00000001 eth3 -00000000000000000000000000000000 60 00000000000000000000000000000000 00 00000000000000000000000000000000 00000400 00000000 00000000 00200200 lo -00000000000000000000000000000000 00 00000000000000000000000000000000 00 20010001000000000000000000000001 00000064 00000000 00000000 00000003 eth3 -` -const v6gatewaymiddle = `20010002000000000000000000000000 40 00000000000000000000000000000000 00 00000000000000000000000000000000 00000100 00000000 00000000 00000001 eth3 -00000000000000000000000000000000 00 00000000000000000000000000000000 00 20010001000000000000000000000001 00000064 00000000 00000000 00000003 eth3 -00000000000000000000000000000000 60 00000000000000000000000000000000 00 00000000000000000000000000000000 00000400 00000000 00000000 00200200 lo -` -const v6noDefaultRoutes = `00000000000000000000000000000000 60 00000000000000000000000000000000 00 00000000000000000000000000000000 00000400 00000000 00000000 00200200 lo -20010001000000000000000000000000 40 00000000000000000000000000000000 00 00000000000000000000000000000000 00000400 00000000 00000000 00000001 docker0 -20010002000000000000000000000000 40 00000000000000000000000000000000 00 00000000000000000000000000000000 00000100 00000000 00000000 00000001 eth3 -fe800000000000000000000000000000 40 00000000000000000000000000000000 00 00000000000000000000000000000000 00000100 00000000 00000000 00000001 eth3 -` -const v6nothing = `` -const v6badDestination = `2001000200000000 7a 00000000000000000000000000000000 00 00000000000000000000000000000000 00000400 00000000 00000000 00200200 lo -` -const v6badGateway = `00000000000000000000000000000000 00 00000000000000000000000000000000 00 200100010000000000000000000000000012 00000064 00000000 00000000 00000003 eth3 -` -const v6route_Invalidhex = `000000000000000000000000000000000 00 00000000000000000000000000000000 00 fe80000000000000021fcafffea0ec00 00000064 00000000 00000000 00000003 enp1s0f0 - -` - -const ( - flagUp = net.FlagUp | net.FlagBroadcast | net.FlagMulticast - flagDown = net.FlagBroadcast | net.FlagMulticast - flagLoopback = net.FlagUp | net.FlagLoopback - flagP2P = net.FlagUp | net.FlagPointToPoint -) - -func makeIntf(index int, name string, flags net.Flags) net.Interface { - mac := net.HardwareAddr{0, 0x32, 0x7d, 0x69, 0xf7, byte(0x30 + index)} - return net.Interface{ - Index: index, - MTU: 1500, - Name: name, - HardwareAddr: mac, - Flags: flags} -} - -var ( - downIntf = makeIntf(1, "eth3", flagDown) - loopbackIntf = makeIntf(1, "lo", flagLoopback) - p2pIntf = makeIntf(1, "lo", flagP2P) - upIntf = makeIntf(1, "eth3", flagUp) -) - -var ( - ipv4Route = Route{Interface: "eth3", Destination: net.ParseIP("0.0.0.0"), Gateway: net.ParseIP("10.254.0.1"), Family: familyIPv4} - ipv6Route = Route{Interface: "eth3", Destination: net.ParseIP("::"), Gateway: net.ParseIP("2001:1::1"), Family: familyIPv6} -) - -var ( - noRoutes = []Route{} - routeV4 = []Route{ipv4Route} - routeV6 = []Route{ipv6Route} - bothRoutes = []Route{ipv4Route, ipv6Route} -) - -func TestGetIPv4Routes(t *testing.T) { - testCases := []struct { - tcase string - route string - count int - expected *Route - errStrFrag string - }{ - {"gatewayfirst", gatewayfirst, 1, &ipv4Route, ""}, - {"gatewaymiddle", gatewaymiddle, 1, &ipv4Route, ""}, - {"gatewaylast", gatewaylast, 1, &ipv4Route, ""}, - {"no routes", nothing, 0, nil, ""}, - {"badDestination", badDestination, 0, nil, "invalid IPv4"}, - {"badGateway", badGateway, 0, nil, "invalid IPv4"}, - {"route_Invalidhex", route_Invalidhex, 0, nil, "odd length hex string"}, - {"no default routes", noInternetConnection, 0, nil, ""}, - } - for _, tc := range testCases { - r := strings.NewReader(tc.route) - routes, err := getIPv4DefaultRoutes(r) - if err != nil { - if !strings.Contains(err.Error(), tc.errStrFrag) { - t.Errorf("case[%s]: Error string %q does not contain %q", tc.tcase, err, tc.errStrFrag) - } - } else if tc.errStrFrag != "" { - t.Errorf("case[%s]: Error %q expected, but not seen", tc.tcase, tc.errStrFrag) - } else { - if tc.count != len(routes) { - t.Errorf("case[%s]: expected %d routes, have %v", tc.tcase, tc.count, routes) - } else if tc.count == 1 { - if !tc.expected.Gateway.Equal(routes[0].Gateway) { - t.Errorf("case[%s]: expected %v, got %v .err : %v", tc.tcase, tc.expected, routes, err) - } - if !routes[0].Destination.Equal(net.IPv4zero) { - t.Errorf("case[%s}: destination is not for default route (not zero)", tc.tcase) - } - - } - } - } -} - -func TestGetIPv6Routes(t *testing.T) { - testCases := []struct { - tcase string - route string - count int - expected *Route - errStrFrag string - }{ - {"v6 gatewayfirst", v6gatewayfirst, 1, &ipv6Route, ""}, - {"v6 gatewaymiddle", v6gatewaymiddle, 1, &ipv6Route, ""}, - {"v6 gatewaylast", v6gatewaylast, 1, &ipv6Route, ""}, - {"v6 no routes", v6nothing, 0, nil, ""}, - {"v6 badDestination", v6badDestination, 0, nil, "invalid IPv6"}, - {"v6 badGateway", v6badGateway, 0, nil, "invalid IPv6"}, - {"v6 route_Invalidhex", v6route_Invalidhex, 0, nil, "odd length hex string"}, - {"v6 no default routes", v6noDefaultRoutes, 0, nil, ""}, - } - for _, tc := range testCases { - r := strings.NewReader(tc.route) - routes, err := getIPv6DefaultRoutes(r) - if err != nil { - if !strings.Contains(err.Error(), tc.errStrFrag) { - t.Errorf("case[%s]: Error string %q does not contain %q", tc.tcase, err, tc.errStrFrag) - } - } else if tc.errStrFrag != "" { - t.Errorf("case[%s]: Error %q expected, but not seen", tc.tcase, tc.errStrFrag) - } else { - if tc.count != len(routes) { - t.Errorf("case[%s]: expected %d routes, have %v", tc.tcase, tc.count, routes) - } else if tc.count == 1 { - if !tc.expected.Gateway.Equal(routes[0].Gateway) { - t.Errorf("case[%s]: expected %v, got %v .err : %v", tc.tcase, tc.expected, routes, err) - } - if !routes[0].Destination.Equal(net.IPv6zero) { - t.Errorf("case[%s}: destination is not for default route (not zero)", tc.tcase) - } - } - } - } -} - -func TestParseIP(t *testing.T) { - testCases := []struct { - tcase string - ip string - family AddressFamily - success bool - expected net.IP - }{ - {"empty", "", familyIPv4, false, nil}, - {"too short", "AA", familyIPv4, false, nil}, - {"too long", "0011223344", familyIPv4, false, nil}, - {"invalid", "invalid!", familyIPv4, false, nil}, - {"zero", "00000000", familyIPv4, true, net.IP{0, 0, 0, 0}}, - {"ffff", "FFFFFFFF", familyIPv4, true, net.IP{0xff, 0xff, 0xff, 0xff}}, - {"valid v4", "12345678", familyIPv4, true, net.IP{120, 86, 52, 18}}, - {"valid v6", "fe800000000000000000000000000000", familyIPv6, true, net.IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, - {"v6 too short", "fe80000000000000021fcafffea0ec0", familyIPv6, false, nil}, - {"v6 too long", "fe80000000000000021fcafffea0ec002", familyIPv6, false, nil}, - } - for _, tc := range testCases { - ip, err := parseIP(tc.ip, tc.family) - if !ip.Equal(tc.expected) { - t.Errorf("case[%v]: expected %q, got %q . err : %v", tc.tcase, tc.expected, ip, err) - } - } -} - -func TestIsInterfaceUp(t *testing.T) { - testCases := []struct { - tcase string - intf *net.Interface - expected bool - }{ - {"up", &net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: net.FlagUp}, true}, - {"down", &net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: 0}, false}, - {"no interface", nil, false}, - } - for _, tc := range testCases { - it := isInterfaceUp(tc.intf) - if it != tc.expected { - t.Errorf("case[%v]: expected %v, got %v .", tc.tcase, tc.expected, it) - } - } -} - -type addrStruct struct{ val string } - -func (a addrStruct) Network() string { - return a.val -} -func (a addrStruct) String() string { - return a.val -} - -func TestFinalIP(t *testing.T) { - testCases := []struct { - tcase string - addr []net.Addr - family AddressFamily - expected net.IP - }{ - {"no ipv4", []net.Addr{addrStruct{val: "2001::5/64"}}, familyIPv4, nil}, - {"no ipv6", []net.Addr{addrStruct{val: "10.128.0.4/32"}}, familyIPv6, nil}, - {"invalidV4CIDR", []net.Addr{addrStruct{val: "10.20.30.40.50/24"}}, familyIPv4, nil}, - {"invalidV6CIDR", []net.Addr{addrStruct{val: "fe80::2f7:67fff:fe6e:2956/64"}}, familyIPv6, nil}, - {"loopback", []net.Addr{addrStruct{val: "127.0.0.1/24"}}, familyIPv4, nil}, - {"loopbackv6", []net.Addr{addrStruct{val: "::1/128"}}, familyIPv6, nil}, - {"link local v4", []net.Addr{addrStruct{val: "169.254.1.10/16"}}, familyIPv4, nil}, - {"link local v6", []net.Addr{addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}}, familyIPv6, nil}, - {"ip4", []net.Addr{addrStruct{val: "10.254.12.132/17"}}, familyIPv4, net.ParseIP("10.254.12.132")}, - {"ip6", []net.Addr{addrStruct{val: "2001::5/64"}}, familyIPv6, net.ParseIP("2001::5")}, - - {"no addresses", []net.Addr{}, familyIPv4, nil}, - } - for _, tc := range testCases { - ip, err := getMatchingGlobalIP(tc.addr, tc.family) - if !ip.Equal(tc.expected) { - t.Errorf("case[%v]: expected %v, got %v .err : %v", tc.tcase, tc.expected, ip, err) - } - } -} - -func TestAddrs(t *testing.T) { - var nw networkInterfacer = validNetworkInterface{} - intf := net.Interface{Index: 0, MTU: 0, Name: "eth3", HardwareAddr: nil, Flags: 0} - addrs, err := nw.Addrs(&intf) - if err != nil { - t.Errorf("expected no error got : %v", err) - } - if len(addrs) != 2 { - t.Errorf("expected addrs: 2 got null") - } -} - -// Has a valid IPv4 address (IPv6 is LLA) -type validNetworkInterface struct { -} - -func (_ validNetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) { - return &upIntf, nil -} -func (_ validNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}, addrStruct{val: "10.254.71.145/17"}} - return ifat, nil -} -func (_ validNetworkInterface) Interfaces() ([]net.Interface, error) { - return []net.Interface{upIntf}, nil -} - -// Both IPv4 and IPv6 addresses (expecting IPv4 to be used) -type v4v6NetworkInterface struct { -} - -func (_ v4v6NetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) { - return &upIntf, nil -} -func (_ v4v6NetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "2001::10/64"}, addrStruct{val: "10.254.71.145/17"}} - return ifat, nil -} -func (_ v4v6NetworkInterface) Interfaces() ([]net.Interface, error) { - return []net.Interface{upIntf}, nil -} - -// Interface with only IPv6 address -type ipv6NetworkInterface struct { -} - -func (_ ipv6NetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) { - return &upIntf, nil -} -func (_ ipv6NetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{addrStruct{val: "2001::200/64"}} - return ifat, nil -} - -func (_ ipv6NetworkInterface) Interfaces() ([]net.Interface, error) { - return []net.Interface{upIntf}, nil -} - -// Only with link local addresses -type networkInterfaceWithOnlyLinkLocals struct { -} - -func (_ networkInterfaceWithOnlyLinkLocals) InterfaceByName(intfName string) (*net.Interface, error) { - return &upIntf, nil -} -func (_ networkInterfaceWithOnlyLinkLocals) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{addrStruct{val: "169.254.162.166/16"}, addrStruct{val: "fe80::200/10"}} - return ifat, nil -} -func (_ networkInterfaceWithOnlyLinkLocals) Interfaces() ([]net.Interface, error) { - return []net.Interface{upIntf}, nil -} - -// Unable to get interface(s) -type failGettingNetworkInterface struct { -} - -func (_ failGettingNetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) { - return nil, fmt.Errorf("unable get Interface") -} -func (_ failGettingNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - return nil, nil -} -func (_ failGettingNetworkInterface) Interfaces() ([]net.Interface, error) { - return nil, fmt.Errorf("mock failed getting all interfaces") -} - -// No interfaces -type noNetworkInterface struct { -} - -func (_ noNetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) { - return nil, fmt.Errorf("no such network interface") -} -func (_ noNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - return nil, nil -} -func (_ noNetworkInterface) Interfaces() ([]net.Interface, error) { - return []net.Interface{}, nil -} - -// Interface is down -type downNetworkInterface struct { -} - -func (_ downNetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) { - return &downIntf, nil -} -func (_ downNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}, addrStruct{val: "10.254.71.145/17"}} - return ifat, nil -} -func (_ downNetworkInterface) Interfaces() ([]net.Interface, error) { - return []net.Interface{downIntf}, nil -} - -// Loopback interface -type loopbackNetworkInterface struct { -} - -func (_ loopbackNetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) { - return &loopbackIntf, nil -} -func (_ loopbackNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "::1/128"}, addrStruct{val: "127.0.0.1/8"}} - return ifat, nil -} -func (_ loopbackNetworkInterface) Interfaces() ([]net.Interface, error) { - return []net.Interface{loopbackIntf}, nil -} - -// Point to point interface -type p2pNetworkInterface struct { -} - -func (_ p2pNetworkInterface) InterfaceByName(intfName string) (*net.Interface, error) { - return &p2pIntf, nil -} -func (_ p2pNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "::1/128"}, addrStruct{val: "127.0.0.1/8"}} - return ifat, nil -} -func (_ p2pNetworkInterface) Interfaces() ([]net.Interface, error) { - return []net.Interface{p2pIntf}, nil -} - -// Unable to get IP addresses for interface -type networkInterfaceFailGetAddrs struct { -} - -func (_ networkInterfaceFailGetAddrs) InterfaceByName(intfName string) (*net.Interface, error) { - return &upIntf, nil -} -func (_ networkInterfaceFailGetAddrs) Addrs(intf *net.Interface) ([]net.Addr, error) { - return nil, fmt.Errorf("unable to get Addrs") -} -func (_ networkInterfaceFailGetAddrs) Interfaces() ([]net.Interface, error) { - return []net.Interface{upIntf}, nil -} - -// No addresses for interface -type networkInterfaceWithNoAddrs struct { -} - -func (_ networkInterfaceWithNoAddrs) InterfaceByName(intfName string) (*net.Interface, error) { - return &upIntf, nil -} -func (_ networkInterfaceWithNoAddrs) Addrs(intf *net.Interface) ([]net.Addr, error) { - ifat := []net.Addr{} - return ifat, nil -} -func (_ networkInterfaceWithNoAddrs) Interfaces() ([]net.Interface, error) { - return []net.Interface{upIntf}, nil -} - -// Invalid addresses for interface -type networkInterfaceWithInvalidAddr struct { -} - -func (_ networkInterfaceWithInvalidAddr) InterfaceByName(intfName string) (*net.Interface, error) { - return &upIntf, nil -} -func (_ networkInterfaceWithInvalidAddr) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{addrStruct{val: "10.20.30.40.50/24"}} - return ifat, nil -} -func (_ networkInterfaceWithInvalidAddr) Interfaces() ([]net.Interface, error) { - return []net.Interface{upIntf}, nil -} - -func TestGetIPFromInterface(t *testing.T) { - testCases := []struct { - tcase string - nwname string - family AddressFamily - nw networkInterfacer - expected net.IP - errStrFrag string - }{ - {"ipv4", "eth3", familyIPv4, validNetworkInterface{}, net.ParseIP("10.254.71.145"), ""}, - {"ipv6", "eth3", familyIPv6, ipv6NetworkInterface{}, net.ParseIP("2001::200"), ""}, - {"no ipv4", "eth3", familyIPv4, ipv6NetworkInterface{}, nil, ""}, - {"no ipv6", "eth3", familyIPv6, validNetworkInterface{}, nil, ""}, - {"I/F down", "eth3", familyIPv4, downNetworkInterface{}, nil, ""}, - {"I/F get fail", "eth3", familyIPv4, noNetworkInterface{}, nil, "no such network interface"}, - {"fail get addr", "eth3", familyIPv4, networkInterfaceFailGetAddrs{}, nil, "unable to get Addrs"}, - {"bad addr", "eth3", familyIPv4, networkInterfaceWithInvalidAddr{}, nil, "invalid CIDR"}, - } - for _, tc := range testCases { - ip, err := getIPFromInterface(tc.nwname, tc.family, tc.nw) - if err != nil { - if !strings.Contains(err.Error(), tc.errStrFrag) { - t.Errorf("case[%s]: Error string %q does not contain %q", tc.tcase, err, tc.errStrFrag) - } - } else if tc.errStrFrag != "" { - t.Errorf("case[%s]: Error %q expected, but not seen", tc.tcase, tc.errStrFrag) - } else if !ip.Equal(tc.expected) { - t.Errorf("case[%v]: expected %v, got %+v .err : %v", tc.tcase, tc.expected, ip, err) - } - } -} - -func TestChooseHostInterfaceFromRoute(t *testing.T) { - testCases := []struct { - tcase string - routes []Route - nw networkInterfacer - expected net.IP - }{ - {"ipv4", routeV4, validNetworkInterface{}, net.ParseIP("10.254.71.145")}, - {"ipv6", routeV6, ipv6NetworkInterface{}, net.ParseIP("2001::200")}, - {"prefer ipv4", bothRoutes, v4v6NetworkInterface{}, net.ParseIP("10.254.71.145")}, - {"all LLA", routeV4, networkInterfaceWithOnlyLinkLocals{}, nil}, - {"no routes", noRoutes, validNetworkInterface{}, nil}, - {"fail get IP", routeV4, networkInterfaceFailGetAddrs{}, nil}, - } - for _, tc := range testCases { - ip, err := chooseHostInterfaceFromRoute(tc.routes, tc.nw) - if !ip.Equal(tc.expected) { - t.Errorf("case[%v]: expected %v, got %+v .err : %v", tc.tcase, tc.expected, ip, err) - } - } -} - -func TestMemberOf(t *testing.T) { - testCases := []struct { - tcase string - ip net.IP - family AddressFamily - expected bool - }{ - {"ipv4 is 4", net.ParseIP("10.20.30.40"), familyIPv4, true}, - {"ipv4 is 6", net.ParseIP("10.10.10.10"), familyIPv6, false}, - {"ipv6 is 4", net.ParseIP("2001::100"), familyIPv4, false}, - {"ipv6 is 6", net.ParseIP("2001::100"), familyIPv6, true}, - } - for _, tc := range testCases { - if memberOf(tc.ip, tc.family) != tc.expected { - t.Errorf("case[%s]: expected %+v", tc.tcase, tc.expected) - } - } -} - -func TestGetIPFromHostInterfaces(t *testing.T) { - testCases := []struct { - tcase string - nw networkInterfacer - expected net.IP - errStrFrag string - }{ - {"fail get I/Fs", failGettingNetworkInterface{}, nil, "failed getting all interfaces"}, - {"no interfaces", noNetworkInterface{}, nil, "no interfaces"}, - {"I/F not up", downNetworkInterface{}, nil, "no acceptable"}, - {"loopback only", loopbackNetworkInterface{}, nil, "no acceptable"}, - {"P2P I/F only", p2pNetworkInterface{}, nil, "no acceptable"}, - {"fail get addrs", networkInterfaceFailGetAddrs{}, nil, "unable to get Addrs"}, - {"no addresses", networkInterfaceWithNoAddrs{}, nil, "no acceptable"}, - {"invalid addr", networkInterfaceWithInvalidAddr{}, nil, "invalid CIDR"}, - {"no matches", networkInterfaceWithOnlyLinkLocals{}, nil, "no acceptable"}, - {"ipv4", validNetworkInterface{}, net.ParseIP("10.254.71.145"), ""}, - {"ipv6", ipv6NetworkInterface{}, net.ParseIP("2001::200"), ""}, - } - - for _, tc := range testCases { - ip, err := chooseIPFromHostInterfaces(tc.nw) - if !ip.Equal(tc.expected) { - t.Errorf("case[%s]: expected %+v, got %+v with err : %v", tc.tcase, tc.expected, ip, err) - } - if err != nil && !strings.Contains(err.Error(), tc.errStrFrag) { - t.Errorf("case[%s]: unable to find %q in error string %q", tc.tcase, tc.errStrFrag, err.Error()) - } - } -} - -func makeRouteFile(content string, t *testing.T) (*os.File, error) { - routeFile, err := ioutil.TempFile("", "route") - if err != nil { - return nil, err - } - - if _, err := routeFile.Write([]byte(content)); err != nil { - return routeFile, err - } - err = routeFile.Close() - return routeFile, err -} - -func TestFailGettingIPv4Routes(t *testing.T) { - defer func() { v4File.name = ipv4RouteFile }() - - // Try failure to open file (should not occur, as caller ensures we have IPv4 route file, but being thorough) - v4File.name = "no-such-file" - errStrFrag := "no such file" - _, err := v4File.extract() - if err == nil { - t.Errorf("Expected error trying to read non-existent v4 route file") - } - if !strings.Contains(err.Error(), errStrFrag) { - t.Errorf("Unable to find %q in error string %q", errStrFrag, err.Error()) - } -} - -func TestFailGettingIPv6Routes(t *testing.T) { - defer func() { v6File.name = ipv6RouteFile }() - - // Try failure to open file (this would be ignored by caller) - v6File.name = "no-such-file" - errStrFrag := "no such file" - _, err := v6File.extract() - if err == nil { - t.Errorf("Expected error trying to read non-existent v6 route file") - } - if !strings.Contains(err.Error(), errStrFrag) { - t.Errorf("Unable to find %q in error string %q", errStrFrag, err.Error()) - } -} - -func TestGetAllDefaultRoutesFailNoV4RouteFile(t *testing.T) { - defer func() { v4File.name = ipv4RouteFile }() - - // Should not occur, as caller ensures we have IPv4 route file, but being thorough - v4File.name = "no-such-file" - errStrFrag := "no such file" - _, err := getAllDefaultRoutes() - if err == nil { - t.Errorf("Expected error trying to read non-existent v4 route file") - } - if !strings.Contains(err.Error(), errStrFrag) { - t.Errorf("Unable to find %q in error string %q", errStrFrag, err.Error()) - } -} - -func TestGetAllDefaultRoutes(t *testing.T) { - testCases := []struct { - tcase string - v4Info string - v6Info string - count int - expected []Route - errStrFrag string - }{ - {"no routes", noInternetConnection, v6noDefaultRoutes, 0, nil, "No default routes"}, - {"only v4 route", gatewayfirst, v6noDefaultRoutes, 1, routeV4, ""}, - {"only v6 route", noInternetConnection, v6gatewayfirst, 1, routeV6, ""}, - {"v4 and v6 routes", gatewayfirst, v6gatewayfirst, 2, bothRoutes, ""}, - } - defer func() { - v4File.name = ipv4RouteFile - v6File.name = ipv6RouteFile - }() - - for _, tc := range testCases { - routeFile, err := makeRouteFile(tc.v4Info, t) - if routeFile != nil { - defer os.Remove(routeFile.Name()) - } - if err != nil { - t.Errorf("case[%s]: test setup failure for IPv4 route file: %v", tc.tcase, err) - } - v4File.name = routeFile.Name() - v6routeFile, err := makeRouteFile(tc.v6Info, t) - if v6routeFile != nil { - defer os.Remove(v6routeFile.Name()) - } - if err != nil { - t.Errorf("case[%s]: test setup failure for IPv6 route file: %v", tc.tcase, err) - } - v6File.name = v6routeFile.Name() - - routes, err := getAllDefaultRoutes() - if err != nil { - if !strings.Contains(err.Error(), tc.errStrFrag) { - t.Errorf("case[%s]: Error string %q does not contain %q", tc.tcase, err, tc.errStrFrag) - } - } else if tc.errStrFrag != "" { - t.Errorf("case[%s]: Error %q expected, but not seen", tc.tcase, tc.errStrFrag) - } else { - if tc.count != len(routes) { - t.Errorf("case[%s]: expected %d routes, have %v", tc.tcase, tc.count, routes) - } - for i, expected := range tc.expected { - if !expected.Gateway.Equal(routes[i].Gateway) { - t.Errorf("case[%s]: at %d expected %v, got %v .err : %v", tc.tcase, i, tc.expected, routes, err) - } - zeroIP := net.IPv4zero - if expected.Family == familyIPv6 { - zeroIP = net.IPv6zero - } - if !routes[i].Destination.Equal(zeroIP) { - t.Errorf("case[%s}: at %d destination is not for default route (not %v)", tc.tcase, i, zeroIP) - } - } - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/net/port_range_test.go b/vendor/k8s.io/apimachinery/pkg/util/net/port_range_test.go deleted file mode 100644 index 897b8df61a..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/net/port_range_test.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package net - -import ( - "testing" - - flag "github.com/spf13/pflag" -) - -func TestPortRange(t *testing.T) { - testCases := []struct { - input string - success bool - expected string - included int - excluded int - }{ - {"100-200", true, "100-200", 200, 201}, - {" 100-200 ", true, "100-200", 200, 201}, - {"0-0", true, "0-0", 0, 1}, - {"", true, "", -1, 0}, - {"100", false, "", -1, -1}, - {"100 - 200", false, "", -1, -1}, - {"-100", false, "", -1, -1}, - {"100-", false, "", -1, -1}, - {"200-100", false, "", -1, -1}, - {"60000-70000", false, "", -1, -1}, - {"70000-80000", false, "", -1, -1}, - } - - for i := range testCases { - tc := &testCases[i] - pr := &PortRange{} - var f flag.Value = pr - err := f.Set(tc.input) - if err != nil && tc.success == true { - t.Errorf("expected success, got %q", err) - continue - } else if err == nil && tc.success == false { - t.Errorf("expected failure") - continue - } else if tc.success { - if f.String() != tc.expected { - t.Errorf("expected %q, got %q", tc.expected, f.String()) - } - if tc.included >= 0 && !pr.Contains(tc.included) { - t.Errorf("expected %q to include %d", f.String(), tc.included) - } - if tc.excluded >= 0 && pr.Contains(tc.excluded) { - t.Errorf("expected %q to exclude %d", f.String(), tc.excluded) - } - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/net/port_split_test.go b/vendor/k8s.io/apimachinery/pkg/util/net/port_split_test.go deleted file mode 100644 index e801bdbea0..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/net/port_split_test.go +++ /dev/null @@ -1,121 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package net - -import ( - "testing" -) - -func TestSplitSchemeNamePort(t *testing.T) { - table := []struct { - in string - name, port, scheme string - valid bool - normalized bool - }{ - { - in: "aoeu:asdf", - name: "aoeu", - port: "asdf", - valid: true, - normalized: true, - }, { - in: "http:aoeu:asdf", - scheme: "http", - name: "aoeu", - port: "asdf", - valid: true, - normalized: true, - }, { - in: "https:aoeu:", - scheme: "https", - name: "aoeu", - port: "", - valid: true, - normalized: false, - }, { - in: "https:aoeu:asdf", - scheme: "https", - name: "aoeu", - port: "asdf", - valid: true, - normalized: true, - }, { - in: "aoeu:", - name: "aoeu", - valid: true, - normalized: false, - }, { - in: "aoeu", - name: "aoeu", - valid: true, - normalized: true, - }, { - in: ":asdf", - valid: false, - }, { - in: "aoeu:asdf:htns", - valid: false, - }, { - in: "http::asdf", - valid: false, - }, { - in: "http::", - valid: false, - }, { - in: "", - valid: false, - }, - } - - for _, item := range table { - scheme, name, port, valid := SplitSchemeNamePort(item.in) - if e, a := item.scheme, scheme; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.name, name; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.port, port; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.valid, valid; e != a { - t.Errorf("%q: Wanted %t, got %t", item.in, e, a) - } - - // Make sure valid items round trip through JoinSchemeNamePort - if item.valid { - out := JoinSchemeNamePort(scheme, name, port) - if item.normalized && out != item.in { - t.Errorf("%q: Wanted %s, got %s", item.in, item.in, out) - } - scheme, name, port, valid := SplitSchemeNamePort(out) - if e, a := item.scheme, scheme; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.name, name; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.port, port; e != a { - t.Errorf("%q: Wanted %q, got %q", item.in, e, a) - } - if e, a := item.valid, valid; e != a { - t.Errorf("%q: Wanted %t, got %t", item.in, e, a) - } - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/net/util_test.go b/vendor/k8s.io/apimachinery/pkg/util/net/util_test.go deleted file mode 100644 index bcbef753b7..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/net/util_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2016 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 net - -import ( - "net" - "testing" -) - -func getIPNet(cidr string) *net.IPNet { - _, ipnet, _ := net.ParseCIDR(cidr) - return ipnet -} - -func TestIPNetEqual(t *testing.T) { - testCases := []struct { - ipnet1 *net.IPNet - ipnet2 *net.IPNet - expect bool - }{ - //null case - { - getIPNet("10.0.0.1/24"), - getIPNet(""), - false, - }, - { - getIPNet("10.0.0.0/24"), - getIPNet("10.0.0.0/24"), - true, - }, - { - getIPNet("10.0.0.0/24"), - getIPNet("10.0.0.1/24"), - true, - }, - { - getIPNet("10.0.0.0/25"), - getIPNet("10.0.0.0/24"), - false, - }, - { - getIPNet("10.0.1.0/24"), - getIPNet("10.0.0.0/24"), - false, - }, - } - - for _, tc := range testCases { - if tc.expect != IPNetEqual(tc.ipnet1, tc.ipnet2) { - t.Errorf("Expect equality of %s and %s be to %v", tc.ipnet1.String(), tc.ipnet2.String(), tc.expect) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/remotecommand/BUILD b/vendor/k8s.io/apimachinery/pkg/util/remotecommand/BUILD deleted file mode 100644 index 9919ad54a6..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/remotecommand/BUILD +++ /dev/null @@ -1,26 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = ["constants.go"], - importpath = "k8s.io/apimachinery/pkg/util/remotecommand", - deps = ["//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/runtime/BUILD b/vendor/k8s.io/apimachinery/pkg/util/runtime/BUILD deleted file mode 100644 index 6407b8bd26..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/runtime/BUILD +++ /dev/null @@ -1,33 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["runtime_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["runtime.go"], - importpath = "k8s.io/apimachinery/pkg/util/runtime", - deps = ["//vendor/github.com/golang/glog:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime_test.go b/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime_test.go deleted file mode 100644 index 9dff17ea53..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/runtime/runtime_test.go +++ /dev/null @@ -1,71 +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 runtime - -import ( - "fmt" - "testing" -) - -func TestHandleCrash(t *testing.T) { - defer func() { - if x := recover(); x == nil { - t.Errorf("Expected a panic to recover from") - } - }() - defer HandleCrash() - panic("Test Panic") -} - -func TestCustomHandleCrash(t *testing.T) { - old := PanicHandlers - defer func() { PanicHandlers = old }() - var result interface{} - PanicHandlers = []func(interface{}){ - func(r interface{}) { - result = r - }, - } - func() { - defer func() { - if x := recover(); x == nil { - t.Errorf("Expected a panic to recover from") - } - }() - defer HandleCrash() - panic("test") - }() - if result != "test" { - t.Errorf("did not receive custom handler") - } -} - -func TestCustomHandleError(t *testing.T) { - old := ErrorHandlers - defer func() { ErrorHandlers = old }() - var result error - ErrorHandlers = []func(error){ - func(err error) { - result = err - }, - } - err := fmt.Errorf("test") - HandleError(err) - if result != err { - t.Errorf("did not receive custom handler") - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/sets/BUILD b/vendor/k8s.io/apimachinery/pkg/util/sets/BUILD deleted file mode 100644 index ec2f234766..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/sets/BUILD +++ /dev/null @@ -1,71 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load("@io_kubernetes_build//defs:go.bzl", "go_genrule") -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_library( - name = "go_default_library", - srcs = [ - "byte.go", - "doc.go", - "empty.go", - "int.go", - "int64.go", - "string.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/sets", -) - -go_genrule( - name = "set-gen", - srcs = [ - "//hack/boilerplate:boilerplate.go.txt", - ], - outs = [ - "byte.go", - "doc.go", - "empty.go", - "int.go", - "int64.go", - "string.go", - ], - cmd = """ -$(location //vendor/k8s.io/code-generator/cmd/set-gen) \ - --input-dirs ./vendor/k8s.io/apimachinery/pkg/util/sets/types \ - --output-base $$(dirname $$(dirname $(location :byte.go))) \ - --go-header-file $(location //hack/boilerplate:boilerplate.go.txt) \ - --output-package sets - """, - go_deps = [ - "//vendor/k8s.io/apimachinery/pkg/util/sets/types:go_default_library", - ], - tools = [ - "//vendor/k8s.io/code-generator/cmd/set-gen", - ], -) - -go_test( - name = "go_default_test", - srcs = ["set_test.go"], - embed = [":go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/util/sets/types:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/sets/set_test.go b/vendor/k8s.io/apimachinery/pkg/util/sets/set_test.go deleted file mode 100644 index df722ec271..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/sets/set_test.go +++ /dev/null @@ -1,270 +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 sets - -import ( - "reflect" - "testing" -) - -func TestStringSet(t *testing.T) { - s := String{} - s2 := String{} - if len(s) != 0 { - t.Errorf("Expected len=0: %d", len(s)) - } - s.Insert("a", "b") - if len(s) != 2 { - t.Errorf("Expected len=2: %d", len(s)) - } - s.Insert("c") - if s.Has("d") { - t.Errorf("Unexpected contents: %#v", s) - } - if !s.Has("a") { - t.Errorf("Missing contents: %#v", s) - } - s.Delete("a") - if s.Has("a") { - t.Errorf("Unexpected contents: %#v", s) - } - s.Insert("a") - if s.HasAll("a", "b", "d") { - t.Errorf("Unexpected contents: %#v", s) - } - if !s.HasAll("a", "b") { - t.Errorf("Missing contents: %#v", s) - } - s2.Insert("a", "b", "d") - if s.IsSuperset(s2) { - t.Errorf("Unexpected contents: %#v", s) - } - s2.Delete("d") - if !s.IsSuperset(s2) { - t.Errorf("Missing contents: %#v", s) - } -} - -func TestStringSetDeleteMultiples(t *testing.T) { - s := String{} - s.Insert("a", "b", "c") - if len(s) != 3 { - t.Errorf("Expected len=3: %d", len(s)) - } - - s.Delete("a", "c") - if len(s) != 1 { - t.Errorf("Expected len=1: %d", len(s)) - } - if s.Has("a") { - t.Errorf("Unexpected contents: %#v", s) - } - if s.Has("c") { - t.Errorf("Unexpected contents: %#v", s) - } - if !s.Has("b") { - t.Errorf("Missing contents: %#v", s) - } - -} - -func TestNewStringSet(t *testing.T) { - s := NewString("a", "b", "c") - if len(s) != 3 { - t.Errorf("Expected len=3: %d", len(s)) - } - if !s.Has("a") || !s.Has("b") || !s.Has("c") { - t.Errorf("Unexpected contents: %#v", s) - } -} - -func TestStringSetList(t *testing.T) { - s := NewString("z", "y", "x", "a") - if !reflect.DeepEqual(s.List(), []string{"a", "x", "y", "z"}) { - t.Errorf("List gave unexpected result: %#v", s.List()) - } -} - -func TestStringSetDifference(t *testing.T) { - a := NewString("1", "2", "3") - b := NewString("1", "2", "4", "5") - c := a.Difference(b) - d := b.Difference(a) - if len(c) != 1 { - t.Errorf("Expected len=1: %d", len(c)) - } - if !c.Has("3") { - t.Errorf("Unexpected contents: %#v", c.List()) - } - if len(d) != 2 { - t.Errorf("Expected len=2: %d", len(d)) - } - if !d.Has("4") || !d.Has("5") { - t.Errorf("Unexpected contents: %#v", d.List()) - } -} - -func TestStringSetHasAny(t *testing.T) { - a := NewString("1", "2", "3") - - if !a.HasAny("1", "4") { - t.Errorf("expected true, got false") - } - - if a.HasAny("0", "4") { - t.Errorf("expected false, got true") - } -} - -func TestStringSetEquals(t *testing.T) { - // Simple case (order doesn't matter) - a := NewString("1", "2") - b := NewString("2", "1") - if !a.Equal(b) { - t.Errorf("Expected to be equal: %v vs %v", a, b) - } - - // It is a set; duplicates are ignored - b = NewString("2", "2", "1") - if !a.Equal(b) { - t.Errorf("Expected to be equal: %v vs %v", a, b) - } - - // Edge cases around empty sets / empty strings - a = NewString() - b = NewString() - if !a.Equal(b) { - t.Errorf("Expected to be equal: %v vs %v", a, b) - } - - b = NewString("1", "2", "3") - if a.Equal(b) { - t.Errorf("Expected to be not-equal: %v vs %v", a, b) - } - - b = NewString("1", "2", "") - if a.Equal(b) { - t.Errorf("Expected to be not-equal: %v vs %v", a, b) - } - - // Check for equality after mutation - a = NewString() - a.Insert("1") - if a.Equal(b) { - t.Errorf("Expected to be not-equal: %v vs %v", a, b) - } - - a.Insert("2") - if a.Equal(b) { - t.Errorf("Expected to be not-equal: %v vs %v", a, b) - } - - a.Insert("") - if !a.Equal(b) { - t.Errorf("Expected to be equal: %v vs %v", a, b) - } - - a.Delete("") - if a.Equal(b) { - t.Errorf("Expected to be not-equal: %v vs %v", a, b) - } -} - -func TestStringUnion(t *testing.T) { - tests := []struct { - s1 String - s2 String - expected String - }{ - { - NewString("1", "2", "3", "4"), - NewString("3", "4", "5", "6"), - NewString("1", "2", "3", "4", "5", "6"), - }, - { - NewString("1", "2", "3", "4"), - NewString(), - NewString("1", "2", "3", "4"), - }, - { - NewString(), - NewString("1", "2", "3", "4"), - NewString("1", "2", "3", "4"), - }, - { - NewString(), - NewString(), - NewString(), - }, - } - - for _, test := range tests { - union := test.s1.Union(test.s2) - if union.Len() != test.expected.Len() { - t.Errorf("Expected union.Len()=%d but got %d", test.expected.Len(), union.Len()) - } - - if !union.Equal(test.expected) { - t.Errorf("Expected union.Equal(expected) but not true. union:%v expected:%v", union.List(), test.expected.List()) - } - } -} - -func TestStringIntersection(t *testing.T) { - tests := []struct { - s1 String - s2 String - expected String - }{ - { - NewString("1", "2", "3", "4"), - NewString("3", "4", "5", "6"), - NewString("3", "4"), - }, - { - NewString("1", "2", "3", "4"), - NewString("1", "2", "3", "4"), - NewString("1", "2", "3", "4"), - }, - { - NewString("1", "2", "3", "4"), - NewString(), - NewString(), - }, - { - NewString(), - NewString("1", "2", "3", "4"), - NewString(), - }, - { - NewString(), - NewString(), - NewString(), - }, - } - - for _, test := range tests { - intersection := test.s1.Intersection(test.s2) - if intersection.Len() != test.expected.Len() { - t.Errorf("Expected intersection.Len()=%d but got %d", test.expected.Len(), intersection.Len()) - } - - if !intersection.Equal(test.expected) { - t.Errorf("Expected intersection.Equal(expected) but not true. intersection:%v expected:%v", intersection.List(), test.expected.List()) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/BUILD b/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/BUILD deleted file mode 100644 index 2d6088929e..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/BUILD +++ /dev/null @@ -1,60 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["patch_test.go"], - data = [ - "testdata/swagger-merge-item.json", - "testdata/swagger-precision-item.json", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/github.com/davecgh/go-spew/spew:go_default_library", - "//vendor/github.com/ghodss/yaml:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/json:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/mergepatch:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/strategicpatch/testing:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "errors.go", - "meta.go", - "patch.go", - "types.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/strategicpatch", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1/unstructured:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/json:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/mergepatch:go_default_library", - "//vendor/k8s.io/apimachinery/third_party/forked/golang/json:go_default_library", - "//vendor/k8s.io/kube-openapi/pkg/util/proto:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/util/strategicpatch/testing:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch_test.go b/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch_test.go deleted file mode 100644 index 4721803ccd..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/strategicpatch/patch_test.go +++ /dev/null @@ -1,6763 +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 strategicpatch - -import ( - "fmt" - "path/filepath" - "reflect" - "strings" - "testing" - - "github.com/davecgh/go-spew/spew" - "github.com/ghodss/yaml" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/json" - "k8s.io/apimachinery/pkg/util/mergepatch" - "k8s.io/apimachinery/pkg/util/sets" - sptest "k8s.io/apimachinery/pkg/util/strategicpatch/testing" -) - -var ( - fakeMergeItemSchema = sptest.Fake{Path: filepath.Join("testdata", "swagger-merge-item.json")} - fakePrecisionItemSchema = sptest.Fake{Path: filepath.Join("testdata", "swagger-precision-item.json")} -) - -type SortMergeListTestCases struct { - TestCases []SortMergeListTestCase -} - -type SortMergeListTestCase struct { - Description string - Original map[string]interface{} - Sorted map[string]interface{} -} - -type StrategicMergePatchTestCases struct { - TestCases []StrategicMergePatchTestCase -} - -type StrategicMergePatchTestCase struct { - Description string - StrategicMergePatchTestCaseData -} - -type StrategicMergePatchRawTestCase struct { - Description string - StrategicMergePatchRawTestCaseData -} - -type StrategicMergePatchTestCaseData struct { - // Original is the original object (last-applied config in annotation) - Original map[string]interface{} - // Modified is the modified object (new config we want) - Modified map[string]interface{} - // Current is the current object (live config in the server) - Current map[string]interface{} - // TwoWay is the expected two-way merge patch diff between original and modified - TwoWay map[string]interface{} - // ThreeWay is the expected three-way merge patch - ThreeWay map[string]interface{} - // Result is the expected object after applying the three-way patch on current object. - Result map[string]interface{} - // TwoWayResult is the expected object after applying the two-way patch on current object. - // If nil, Modified is used. - TwoWayResult map[string]interface{} -} - -// The meaning of each field is the same as StrategicMergePatchTestCaseData's. -// The difference is that all the fields in StrategicMergePatchRawTestCaseData are json-encoded data. -type StrategicMergePatchRawTestCaseData struct { - Original []byte - Modified []byte - Current []byte - TwoWay []byte - ThreeWay []byte - Result []byte - TwoWayResult []byte - ExpectedError string -} - -type MergeItem struct { - Name string `json:"name,omitempty"` - Value string `json:"value,omitempty"` - Other string `json:"other,omitempty"` - MergingList []MergeItem `json:"mergingList,omitempty" patchStrategy:"merge" patchMergeKey:"name"` - NonMergingList []MergeItem `json:"nonMergingList,omitempty"` - MergingIntList []int `json:"mergingIntList,omitempty" patchStrategy:"merge"` - NonMergingIntList []int `json:"nonMergingIntList,omitempty"` - MergeItemPtr *MergeItem `json:"mergeItemPtr,omitempty" patchStrategy:"merge" patchMergeKey:"name"` - SimpleMap map[string]string `json:"simpleMap,omitempty"` - ReplacingItem runtime.RawExtension `json:"replacingItem,omitempty" patchStrategy:"replace"` - RetainKeysMap RetainKeysMergeItem `json:"retainKeysMap,omitempty" patchStrategy:"retainKeys"` - RetainKeysMergingList []MergeItem `json:"retainKeysMergingList,omitempty" patchStrategy:"merge,retainKeys" patchMergeKey:"name"` -} - -type RetainKeysMergeItem struct { - Name string `json:"name,omitempty"` - Value string `json:"value,omitempty"` - Other string `json:"other,omitempty"` - SimpleMap map[string]string `json:"simpleMap,omitempty"` - MergingIntList []int `json:"mergingIntList,omitempty" patchStrategy:"merge"` - MergingList []MergeItem `json:"mergingList,omitempty" patchStrategy:"merge" patchMergeKey:"name"` - NonMergingList []MergeItem `json:"nonMergingList,omitempty"` -} - -var ( - mergeItem MergeItem - mergeItemStructSchema = PatchMetaFromStruct{T: GetTagStructTypeOrDie(mergeItem)} -) - -// These are test cases for SortMergeList, used to assert that it (recursively) -// sorts both merging and non merging lists correctly. -var sortMergeListTestCaseData = []byte(` -testCases: - - description: sort one list of maps - original: - mergingList: - - name: 1 - - name: 3 - - name: 2 - sorted: - mergingList: - - name: 1 - - name: 2 - - name: 3 - - description: sort lists of maps but not nested lists of maps - original: - mergingList: - - name: 2 - nonMergingList: - - name: 1 - - name: 3 - - name: 2 - - name: 1 - nonMergingList: - - name: 2 - - name: 1 - sorted: - mergingList: - - name: 1 - nonMergingList: - - name: 2 - - name: 1 - - name: 2 - nonMergingList: - - name: 1 - - name: 3 - - name: 2 - - description: sort lists of maps and nested lists of maps - original: - mergingList: - - name: 2 - mergingList: - - name: 1 - - name: 3 - - name: 2 - - name: 1 - mergingList: - - name: 2 - - name: 1 - sorted: - mergingList: - - name: 1 - mergingList: - - name: 1 - - name: 2 - - name: 2 - mergingList: - - name: 1 - - name: 2 - - name: 3 - - description: merging list should NOT sort when nested in non merging list - original: - nonMergingList: - - name: 2 - mergingList: - - name: 1 - - name: 3 - - name: 2 - - name: 1 - mergingList: - - name: 2 - - name: 1 - sorted: - nonMergingList: - - name: 2 - mergingList: - - name: 1 - - name: 3 - - name: 2 - - name: 1 - mergingList: - - name: 2 - - name: 1 - - description: sort very nested list of maps - fieldTypes: - original: - mergingList: - - mergingList: - - mergingList: - - name: 2 - - name: 1 - sorted: - mergingList: - - mergingList: - - mergingList: - - name: 1 - - name: 2 - - description: sort nested lists of ints - original: - mergingList: - - name: 2 - mergingIntList: - - 1 - - 3 - - 2 - - name: 1 - mergingIntList: - - 2 - - 1 - sorted: - mergingList: - - name: 1 - mergingIntList: - - 1 - - 2 - - name: 2 - mergingIntList: - - 1 - - 2 - - 3 - - description: sort nested pointers of ints - original: - mergeItemPtr: - - name: 2 - mergingIntList: - - 1 - - 3 - - 2 - - name: 1 - mergingIntList: - - 2 - - 1 - sorted: - mergeItemPtr: - - name: 1 - mergingIntList: - - 1 - - 2 - - name: 2 - mergingIntList: - - 1 - - 2 - - 3 - - description: sort merging list by pointer - original: - mergeItemPtr: - - name: 1 - - name: 3 - - name: 2 - sorted: - mergeItemPtr: - - name: 1 - - name: 2 - - name: 3 -`) - -func TestSortMergeLists(t *testing.T) { - mergeItemOpenapiSchema := PatchMetaFromOpenAPI{ - Schema: sptest.GetSchemaOrDie(fakeMergeItemSchema, "mergeItem"), - } - schemas := []LookupPatchMeta{ - mergeItemStructSchema, - mergeItemOpenapiSchema, - } - - tc := SortMergeListTestCases{} - err := yaml.Unmarshal(sortMergeListTestCaseData, &tc) - if err != nil { - t.Errorf("can't unmarshal test cases: %s\n", err) - return - } - - for _, schema := range schemas { - for _, c := range tc.TestCases { - temp := testObjectToJSONOrFail(t, c.Original) - got := sortJsonOrFail(t, temp, c.Description, schema) - expected := testObjectToJSONOrFail(t, c.Sorted) - if !reflect.DeepEqual(got, expected) { - t.Errorf("using %s error in test case: %s\ncannot sort object:\n%s\nexpected:\n%s\ngot:\n%s\n", - getSchemaType(schema), c.Description, mergepatch.ToYAMLOrError(c.Original), mergepatch.ToYAMLOrError(c.Sorted), jsonToYAMLOrError(got)) - } - } - } -} - -// These are test cases for StrategicMergePatch that cannot be generated using -// CreateTwoWayMergePatch because it may be one of the following cases: -// - not use the replace directive. -// - generate duplicate integers for a merging list patch. -// - generate empty merging lists. -// - use patch format from an old client. -var customStrategicMergePatchTestCaseData = []byte(` -testCases: - - description: unique scalars when merging lists - original: - mergingIntList: - - 1 - - 2 - twoWay: - mergingIntList: - - 2 - - 3 - modified: - mergingIntList: - - 1 - - 2 - - 3 - - description: delete map from nested map - original: - simpleMap: - key1: 1 - key2: 1 - twoWay: - simpleMap: - $patch: delete - modified: - simpleMap: - {} - - description: delete all items from merging list - original: - mergingList: - - name: 1 - - name: 2 - twoWay: - mergingList: - - $patch: replace - modified: - mergingList: [] - - description: merge empty merging lists - original: - mergingList: [] - twoWay: - mergingList: [] - modified: - mergingList: [] - - description: delete all keys from map - original: - name: 1 - value: 1 - twoWay: - $patch: replace - modified: {} - - description: add key and delete all keys from map - original: - name: 1 - value: 1 - twoWay: - other: a - $patch: replace - modified: - other: a - - description: delete all duplicate entries in a merging list - original: - mergingList: - - name: 1 - - name: 1 - - name: 2 - value: a - - name: 3 - - name: 3 - twoWay: - mergingList: - - name: 1 - $patch: delete - - name: 3 - $patch: delete - modified: - mergingList: - - name: 2 - value: a - - description: retainKeys map can add a field when no retainKeys directive present - original: - retainKeysMap: - name: foo - twoWay: - retainKeysMap: - value: bar - modified: - retainKeysMap: - name: foo - value: bar - - description: retainKeys map can change a field when no retainKeys directive present - original: - retainKeysMap: - name: foo - value: a - twoWay: - retainKeysMap: - value: b - modified: - retainKeysMap: - name: foo - value: b - - description: retainKeys map can delete a field when no retainKeys directive present - original: - retainKeysMap: - name: foo - value: a - twoWay: - retainKeysMap: - value: null - modified: - retainKeysMap: - name: foo - - description: retainKeys map merge an empty map - original: - retainKeysMap: - name: foo - value: a - twoWay: - retainKeysMap: {} - modified: - retainKeysMap: - name: foo - value: a - - description: retainKeys list can add a field when no retainKeys directive present - original: - retainKeysMergingList: - - name: bar - - name: foo - twoWay: - retainKeysMergingList: - - name: foo - value: a - modified: - retainKeysMergingList: - - name: bar - - name: foo - value: a - - description: retainKeys list can change a field when no retainKeys directive present - original: - retainKeysMergingList: - - name: bar - - name: foo - value: a - twoWay: - retainKeysMergingList: - - name: foo - value: b - modified: - retainKeysMergingList: - - name: bar - - name: foo - value: b - - description: retainKeys list can delete a field when no retainKeys directive present - original: - retainKeysMergingList: - - name: bar - - name: foo - value: a - twoWay: - retainKeysMergingList: - - name: foo - value: null - modified: - retainKeysMergingList: - - name: bar - - name: foo - - description: preserve the order from the patch in a merging list - original: - mergingList: - - name: 1 - - name: 2 - value: b - - name: 3 - twoWay: - mergingList: - - name: 3 - value: c - - name: 1 - value: a - - name: 2 - other: x - modified: - mergingList: - - name: 3 - value: c - - name: 1 - value: a - - name: 2 - value: b - other: x - - description: preserve the order from the patch in a merging list 2 - original: - mergingList: - - name: 1 - - name: 2 - value: b - - name: 3 - twoWay: - mergingList: - - name: 3 - value: c - - name: 1 - value: a - modified: - mergingList: - - name: 2 - value: b - - name: 3 - value: c - - name: 1 - value: a - - description: preserve the order from the patch in a merging int list - original: - mergingIntList: - - 1 - - 2 - - 3 - twoWay: - mergingIntList: - - 3 - - 1 - - 2 - modified: - mergingIntList: - - 3 - - 1 - - 2 - - description: preserve the order from the patch in a merging int list - original: - mergingIntList: - - 1 - - 2 - - 3 - twoWay: - mergingIntList: - - 3 - - 1 - modified: - mergingIntList: - - 2 - - 3 - - 1 -`) - -var customStrategicMergePatchRawTestCases = []StrategicMergePatchRawTestCase{ - { - Description: "$setElementOrder contains item that is not present in the list to be merged", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 3 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 3 - - name: 2 - - name: 1 -mergingList: - - name: 3 - value: 3 - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 3 - value: 3 - - name: 1 - value: 1 -`), - }, - }, - { - Description: "$setElementOrder contains item that is not present in the int list to be merged", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 3 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 3 - - 2 - - 1 -`), - Modified: []byte(` -mergingIntList: - - 3 - - 1 -`), - }, - }, - { - Description: "should check if order in $setElementOrder and patch list match", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 3 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 - - name: 3 -mergingList: - - name: 3 - value: 3 - - name: 1 - value: 1 -`), - ExpectedError: "doesn't match", - }, - }, - { - Description: "$setElementOrder contains item that is not present in the int list to be merged", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 3 - - 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 1 - - 2 - - 3 -mergingIntList: - - 3 - - 1 -`), - ExpectedError: "doesn't match", - }, - }, - { - Description: "missing merge key should error out", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - value: a -`), - TwoWay: []byte(` -mergingList: - - value: b -`), - ExpectedError: "does not contain declared merge key", - }, - }, -} - -func TestCustomStrategicMergePatch(t *testing.T) { - mergeItemOpenapiSchema := PatchMetaFromOpenAPI{ - Schema: sptest.GetSchemaOrDie(fakeMergeItemSchema, "mergeItem"), - } - schemas := []LookupPatchMeta{ - mergeItemStructSchema, - mergeItemOpenapiSchema, - } - - tc := StrategicMergePatchTestCases{} - err := yaml.Unmarshal(customStrategicMergePatchTestCaseData, &tc) - if err != nil { - t.Errorf("can't unmarshal test cases: %v\n", err) - return - } - - for _, schema := range schemas { - for _, c := range tc.TestCases { - original, expectedTwoWayPatch, _, expectedResult := twoWayTestCaseToJSONOrFail(t, c, schema) - testPatchApplication(t, original, expectedTwoWayPatch, expectedResult, c.Description, "", schema) - } - - for _, c := range customStrategicMergePatchRawTestCases { - original, expectedTwoWayPatch, _, expectedResult := twoWayRawTestCaseToJSONOrFail(t, c) - testPatchApplication(t, original, expectedTwoWayPatch, expectedResult, c.Description, c.ExpectedError, schema) - } - } -} - -// These are test cases for StrategicMergePatch, to assert that applying a patch -// yields the correct outcome. They are also test cases for CreateTwoWayMergePatch -// and CreateThreeWayMergePatch, to assert that they both generate the correct patch -// for the given set of input documents. -// -var createStrategicMergePatchTestCaseData = []byte(` -testCases: - - description: nil original - twoWay: - name: 1 - value: 1 - modified: - name: 1 - value: 1 - current: - name: 1 - other: a - threeWay: - value: 1 - result: - name: 1 - value: 1 - other: a - - description: nil patch - original: - name: 1 - twoWay: - {} - modified: - name: 1 - current: - name: 1 - threeWay: - {} - result: - name: 1 - - description: add field to map - original: - name: 1 - twoWay: - value: 1 - modified: - name: 1 - value: 1 - current: - name: 1 - other: a - threeWay: - value: 1 - result: - name: 1 - value: 1 - other: a - - description: add field to map with conflict - original: - name: 1 - twoWay: - value: 1 - modified: - name: 1 - value: 1 - current: - name: a - other: a - threeWay: - name: 1 - value: 1 - result: - name: 1 - value: 1 - other: a - - description: add field and delete field from map - original: - name: 1 - twoWay: - name: null - value: 1 - modified: - value: 1 - current: - name: 1 - other: a - threeWay: - name: null - value: 1 - result: - value: 1 - other: a - - description: add field and delete field from map with conflict - original: - name: 1 - twoWay: - name: null - value: 1 - modified: - value: 1 - current: - name: a - other: a - threeWay: - name: null - value: 1 - result: - value: 1 - other: a - - description: delete field from nested map - original: - simpleMap: - key1: 1 - key2: 1 - twoWay: - simpleMap: - key2: null - modified: - simpleMap: - key1: 1 - current: - simpleMap: - key1: 1 - key2: 1 - other: a - threeWay: - simpleMap: - key2: null - result: - simpleMap: - key1: 1 - other: a - - description: delete field from nested map with conflict - original: - simpleMap: - key1: 1 - key2: 1 - twoWay: - simpleMap: - key2: null - modified: - simpleMap: - key1: 1 - current: - simpleMap: - key1: a - key2: 1 - other: a - threeWay: - simpleMap: - key1: 1 - key2: null - result: - simpleMap: - key1: 1 - other: a - - description: delete all fields from map - original: - name: 1 - value: 1 - twoWay: - name: null - value: null - modified: {} - current: - name: 1 - value: 1 - other: a - threeWay: - name: null - value: null - result: - other: a - - description: delete all fields from map with conflict - original: - name: 1 - value: 1 - twoWay: - name: null - value: null - modified: {} - current: - name: 1 - value: a - other: a - threeWay: - name: null - value: null - result: - other: a - - description: add field and delete all fields from map - original: - name: 1 - value: 1 - twoWay: - name: null - value: null - other: a - modified: - other: a - current: - name: 1 - value: 1 - other: a - threeWay: - name: null - value: null - result: - other: a - - description: add field and delete all fields from map with conflict - original: - name: 1 - value: 1 - twoWay: - name: null - value: null - other: a - modified: - other: a - current: - name: 1 - value: 1 - other: b - threeWay: - name: null - value: null - other: a - result: - other: a - - description: replace list of scalars - original: - nonMergingIntList: - - 1 - - 2 - twoWay: - nonMergingIntList: - - 2 - - 3 - modified: - nonMergingIntList: - - 2 - - 3 - current: - nonMergingIntList: - - 1 - - 2 - threeWay: - nonMergingIntList: - - 2 - - 3 - result: - nonMergingIntList: - - 2 - - 3 - - description: replace list of scalars with conflict - original: - nonMergingIntList: - - 1 - - 2 - twoWay: - nonMergingIntList: - - 2 - - 3 - modified: - nonMergingIntList: - - 2 - - 3 - current: - nonMergingIntList: - - 1 - - 4 - threeWay: - nonMergingIntList: - - 2 - - 3 - result: - nonMergingIntList: - - 2 - - 3 - - description: delete all maps from merging list - original: - mergingList: - - name: 1 - - name: 2 - twoWay: - mergingList: - - name: 1 - $patch: delete - - name: 2 - $patch: delete - modified: - mergingList: [] - current: - mergingList: - - name: 1 - - name: 2 - threeWay: - mergingList: - - name: 1 - $patch: delete - - name: 2 - $patch: delete - result: - mergingList: [] - - description: delete all maps from merging list with conflict - original: - mergingList: - - name: 1 - - name: 2 - twoWay: - mergingList: - - name: 1 - $patch: delete - - name: 2 - $patch: delete - modified: - mergingList: [] - current: - mergingList: - - name: 1 - other: a - - name: 2 - other: b - threeWay: - mergingList: - - name: 1 - $patch: delete - - name: 2 - $patch: delete - result: - mergingList: [] - - description: delete all maps from empty merging list - original: - mergingList: - - name: 1 - - name: 2 - twoWay: - mergingList: - - name: 1 - $patch: delete - - name: 2 - $patch: delete - modified: - mergingList: [] - current: - mergingList: [] - threeWay: - mergingList: - - name: 1 - $patch: delete - - name: 2 - $patch: delete - result: - mergingList: [] - - description: merge empty merging lists - original: - mergingList: [] - twoWay: - {} - modified: - mergingList: [] - current: - mergingList: [] - threeWay: - {} - result: - mergingList: [] - - description: defined null values should propagate overwrite current fields (with conflict) - original: - name: 2 - twoWay: - name: 1 - value: 1 - other: null - twoWayResult: - name: 1 - value: 1 - modified: - name: 1 - value: 1 - other: null - current: - name: a - other: a - threeWay: - name: 1 - value: 1 - other: null - result: - name: 1 - value: 1 - - description: defined null values should propagate removing original fields - original: - name: original-name - value: original-value - current: - name: original-name - value: original-value - other: current-other - modified: - name: modified-name - value: null - twoWay: - name: modified-name - value: null - twoWayResult: - name: modified-name - threeWay: - name: modified-name - value: null - result: - name: modified-name - other: current-other - - description: nil patch with retainKeys map - original: - name: a - retainKeysMap: - name: foo - current: - name: a - value: b - retainKeysMap: - name: foo - modified: - name: a - retainKeysMap: - name: foo - twoWay: {} - threeWay: {} - result: - name: a - value: b - retainKeysMap: - name: foo - - description: retainKeys map with no change should not be present - original: - name: a - retainKeysMap: - name: foo - current: - name: a - other: c - retainKeysMap: - name: foo - modified: - name: a - value: b - retainKeysMap: - name: foo - twoWay: - value: b - threeWay: - value: b - result: - name: a - value: b - other: c - retainKeysMap: - name: foo -`) - -var strategicMergePatchRawTestCases = []StrategicMergePatchRawTestCase{ - { - Description: "delete items in lists of scalars", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 2 - - 3 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 1 - - 2 -$deleteFromPrimitiveList/mergingIntList: - - 3 -`), - Modified: []byte(` -mergingIntList: - - 1 - - 2 -`), - Current: []byte(` -mergingIntList: - - 1 - - 2 - - 3 - - 4 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 1 - - 2 -$deleteFromPrimitiveList/mergingIntList: - - 3 -`), - Result: []byte(` -mergingIntList: - - 1 - - 2 - - 4 -`), - }, - }, - { - Description: "delete all duplicate items in lists of scalars", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 2 - - 3 - - 3 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 1 - - 2 -$deleteFromPrimitiveList/mergingIntList: - - 3 -`), - Modified: []byte(` -mergingIntList: - - 1 - - 2 -`), - Current: []byte(` -mergingIntList: - - 1 - - 2 - - 3 - - 3 - - 4 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 1 - - 2 -$deleteFromPrimitiveList/mergingIntList: - - 3 -`), - Result: []byte(` -mergingIntList: - - 1 - - 2 - - 4 -`), - }, - }, - { - Description: "add and delete items in lists of scalars", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 2 - - 3 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 1 - - 2 - - 4 -$deleteFromPrimitiveList/mergingIntList: - - 3 -mergingIntList: - - 4 -`), - Modified: []byte(` -mergingIntList: - - 1 - - 2 - - 4 -`), - Current: []byte(` -mergingIntList: - - 1 - - 2 - - 3 - - 4 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 1 - - 2 - - 4 -$deleteFromPrimitiveList/mergingIntList: - - 3 -`), - Result: []byte(` -mergingIntList: - - 1 - - 2 - - 4 -`), - }, - }, - { - Description: "merge lists of maps", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 4 - - name: 1 - - name: 2 - - name: 3 -mergingList: - - name: 4 - value: 4 - - name: 3 - value: 3 -`), - Modified: []byte(` -mergingList: - - name: 4 - value: 4 - - name: 1 - - name: 2 - value: 2 - - name: 3 - value: 3 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 4 - - name: 1 - - name: 2 - - name: 3 -mergingList: - - name: 4 - value: 4 - - name: 3 - value: 3 -`), - Result: []byte(` -mergingList: - - name: 4 - value: 4 - - name: 1 - other: a - - name: 2 - value: 2 - other: b - - name: 3 - value: 3 -`), - }, - }, - { - Description: "merge lists of maps with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 - - name: 3 -mergingList: - - name: 3 - value: 3 -`), - Modified: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 - - name: 3 - value: 3 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 3 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 - - name: 3 -mergingList: - - name: 2 - value: 2 - - name: 3 - value: 3 -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b - - name: 3 - value: 3 -`), - }, - }, - { - Description: "add field to map in merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: 1 -`), - Result: []byte(` -mergingList: - - name: 1 - value: 1 - other: a - - name: 2 - value: 2 - other: b -`), - }, - }, - { - Description: "add field to map in merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: 1 -`), - Result: []byte(` -mergingList: - - name: 1 - value: 1 - other: a - - name: 2 - value: 2 - other: b -`), - }, - }, - { - Description: "add field to map in merging list with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 3 - value: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - Result: []byte(` -mergingList: - - name: 1 - value: 1 - other: a - - name: 2 - value: 2 - - name: 3 - value: 2 - other: b -`), - }, - }, - { - Description: "add duplicate field to map in merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - value: 1 - other: a - - name: 2 - value: 2 - other: b -`), - ThreeWay: []byte(`{}`), - Result: []byte(` -mergingList: - - name: 1 - value: 1 - other: a - - name: 2 - value: 2 - other: b -`), - }, - }, - { - Description: "add an item that already exists in current object in merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - value: a - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 - - name: 3 -mergingList: - - name: 3 -`), - Modified: []byte(` -mergingList: - - name: 1 - value: a - - name: 2 - - name: 3 -`), - Current: []byte(` -mergingList: - - name: 1 - value: a - other: x - - name: 2 - - name: 3 -`), - ThreeWay: []byte(`{}`), - Result: []byte(` -mergingList: - - name: 1 - value: a - other: x - - name: 2 - - name: 3 -`), - }, - }, - { - Description: "add duplicate field to map in merging list with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - value: 1 - other: a - - name: 2 - value: 3 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 2 - value: 2 -`), - Result: []byte(` -mergingList: - - name: 1 - value: 1 - other: a - - name: 2 - value: 2 - other: b -`), - }, - }, - { - Description: "replace map field value in merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: a -`), - Modified: []byte(` -mergingList: - - name: 1 - value: a - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - value: 1 - other: a - - name: 2 - value: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: a -`), - Result: []byte(` -mergingList: - - name: 1 - value: a - other: a - - name: 2 - value: 2 - other: b -`), - }, - }, - { - Description: "replace map field value in merging list with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: a -`), - Modified: []byte(` -mergingList: - - name: 1 - value: a - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - value: 3 - other: a - - name: 2 - value: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: a -`), - Result: []byte(` -mergingList: - - name: 1 - value: a - other: a - - name: 2 - value: 2 - other: b -`), - }, - }, - { - Description: "delete map from merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 2 -mergingList: - - name: 1 - $patch: delete -`), - Modified: []byte(` -mergingList: - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 2 -mergingList: - - name: 1 - $patch: delete -`), - Result: []byte(` -mergingList: - - name: 2 - other: b -`), - }, - }, - { - Description: "delete map from merging list with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 2 -mergingList: - - name: 1 - $patch: delete -`), - Modified: []byte(` -mergingList: - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 2 -mergingList: - - name: 1 - $patch: delete -`), - Result: []byte(` -mergingList: - - name: 2 - other: b -`), - }, - }, - { - Description: "delete missing map from merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 2 -mergingList: - - name: 1 - $patch: delete -`), - Modified: []byte(` -mergingList: - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 2 -mergingList: - - name: 1 - $patch: delete -`), - Result: []byte(` -mergingList: - - name: 2 - other: b -`), - }, - }, - { - Description: "delete missing map from merging list with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 2 -mergingList: - - name: 1 - $patch: delete -`), - Modified: []byte(` -mergingList: - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 3 - other: a -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 2 -mergingList: - - name: 2 - - name: 1 - $patch: delete -`), - Result: []byte(` -mergingList: - - name: 2 - - name: 3 - other: a -`), - }, - }, - { - Description: "add map and delete map from merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 3 -mergingList: - - name: 3 - - name: 1 - $patch: delete -`), - Modified: []byte(` -mergingList: - - name: 2 - - name: 3 -`), - Current: []byte(` -mergingList: - - name: 1 - - name: 2 - other: b - - name: 4 - other: c -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 3 -mergingList: - - name: 3 - - name: 1 - $patch: delete -`), - Result: []byte(` -mergingList: - - name: 2 - other: b - - name: 4 - other: c - - name: 3 -`), - }, - }, - { - Description: "add map and delete map from merging list with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 3 -mergingList: - - name: 3 - - name: 1 - $patch: delete -`), - Modified: []byte(` -mergingList: - - name: 2 - - name: 3 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 4 - other: c -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 3 -mergingList: - - name: 2 - - name: 3 - - name: 1 - $patch: delete -`), - Result: []byte(` -mergingList: - - name: 4 - other: c - - name: 2 - - name: 3 -`), - }, - }, - { - Description: "delete field from map in merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: null -`), - Modified: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - value: 1 - other: a - - name: 2 - value: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: null -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b -`), - }, - }, - { - Description: "delete field from map in merging list with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: null -`), - Modified: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - value: a - other: a - - name: 2 - value: 2 -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: null -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 -`), - }, - }, - { - Description: "delete missing field from map in merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: null -`), - Modified: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: null -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b -`), - }, - }, - { - Description: "delete missing field from map in merging list with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: null -`), - Modified: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - value: null - - name: 2 - value: 2 -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b -`), - }, - }, - { - Description: "replace non merging list nested in merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - nonMergingList: - - name: 1 - - name: 2 - value: 2 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - nonMergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - nonMergingList: - - name: 1 - value: 1 - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - nonMergingList: - - name: 1 - - name: 2 - value: 2 - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - nonMergingList: - - name: 1 - value: 1 -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - nonMergingList: - - name: 1 - value: 1 - - name: 2 - other: b -`), - }, - }, - { - Description: "replace non merging list nested in merging list with value conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - nonMergingList: - - name: 1 - - name: 2 - value: 2 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - nonMergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - nonMergingList: - - name: 1 - value: 1 - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - nonMergingList: - - name: 1 - value: c - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - nonMergingList: - - name: 1 - value: 1 -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - nonMergingList: - - name: 1 - value: 1 - - name: 2 - other: b -`), - }, - }, - { - Description: "replace non merging list nested in merging list with deletion conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - nonMergingList: - - name: 1 - - name: 2 - value: 2 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - nonMergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - nonMergingList: - - name: 1 - value: 1 - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - nonMergingList: - - name: 2 - value: 2 - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 1 - nonMergingList: - - name: 1 - value: 1 -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - nonMergingList: - - name: 1 - value: 1 - - name: 2 - other: b -`), - }, - }, - { - Description: "add field to map in merging list nested in merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - mergingList: - - name: 1 - - name: 2 - value: 2 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - $setElementOrder/mergingList: - - name: 1 - - name: 2 - name: 1 - mergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - mergingList: - - name: 1 - - name: 2 - value: 2 - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - $setElementOrder/mergingList: - - name: 1 - - name: 2 - name: 1 - mergingList: - - name: 1 - value: 1 -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 - - name: 2 - other: b -`), - }, - }, - { - Description: "add field to map in merging list nested in merging list with value conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - mergingList: - - name: 1 - - name: 2 - value: 2 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - $setElementOrder/mergingList: - - name: 1 - - name: 2 - name: 1 - mergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - mergingList: - - name: 1 - value: a - other: c - - name: 2 - value: b - other: d - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - $setElementOrder/mergingList: - - name: 1 - - name: 2 - name: 1 - mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - mergingList: - - name: 1 - value: 1 - other: c - - name: 2 - value: 2 - other: d - - name: 2 - other: b -`), - }, - }, - { - Description: "add field to map in merging list nested in merging list with deletion conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - mergingList: - - name: 1 - - name: 2 - value: 2 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - $setElementOrder/mergingList: - - name: 1 - - name: 2 - name: 1 - mergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - mergingList: - - name: 2 - value: 2 - other: d - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - $setElementOrder/mergingList: - - name: 1 - - name: 2 - name: 1 - mergingList: - - name: 1 - value: 1 -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - mergingList: - - name: 1 - value: 1 - - name: 2 - value: 2 - other: d - - name: 2 - other: b -`), - }, - }, - - { - Description: "add field to map in merging list nested in merging list with deletion conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - mergingList: - - name: 1 - - name: 2 - value: 2 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - $setElementOrder/mergingList: - - name: 2 - - name: 1 - name: 1 - mergingList: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergingList: - - name: 1 - mergingList: - - name: 2 - value: 2 - - name: 1 - value: 1 - - name: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - mergingList: - - name: 2 - value: 2 - other: d - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - $setElementOrder/mergingList: - - name: 2 - - name: 1 - name: 1 - mergingList: - - name: 1 - value: 1 -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - mergingList: - - name: 2 - value: 2 - other: d - - name: 1 - value: 1 - - name: 2 - other: b -`), - }, - }, - { - Description: "add map to merging list by pointer", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergeItemPtr: - - name: 1 -`), - TwoWay: []byte(` -$setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 -mergeItemPtr: - - name: 2 -`), - Modified: []byte(` -mergeItemPtr: - - name: 1 - - name: 2 -`), - Current: []byte(` -mergeItemPtr: - - name: 1 - other: a - - name: 3 -`), - ThreeWay: []byte(` -$setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 -mergeItemPtr: - - name: 2 -`), - Result: []byte(` -mergeItemPtr: - - name: 1 - other: a - - name: 2 - - name: 3 -`), - }, - }, - { - Description: "add map to merging list by pointer with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergeItemPtr: - - name: 1 -`), - TwoWay: []byte(` -$setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 -mergeItemPtr: - - name: 2 -`), - Modified: []byte(` -mergeItemPtr: - - name: 1 - - name: 2 -`), - Current: []byte(` -mergeItemPtr: - - name: 3 -`), - ThreeWay: []byte(` -$setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 -mergeItemPtr: - - name: 1 - - name: 2 -`), - Result: []byte(` -mergeItemPtr: - - name: 1 - - name: 2 - - name: 3 -`), - }, - }, - { - Description: "add field to map in merging list by pointer", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergeItemPtr: - - name: 1 - mergeItemPtr: - - name: 1 - - name: 2 - value: 2 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 -mergeItemPtr: - - $setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 - name: 1 - mergeItemPtr: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergeItemPtr: - - name: 1 - mergeItemPtr: - - name: 1 - value: 1 - - name: 2 - value: 2 - - name: 2 -`), - Current: []byte(` -mergeItemPtr: - - name: 1 - other: a - mergeItemPtr: - - name: 1 - other: a - - name: 2 - value: 2 - other: b - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 -mergeItemPtr: - - $setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 - name: 1 - mergeItemPtr: - - name: 1 - value: 1 -`), - Result: []byte(` -mergeItemPtr: - - name: 1 - other: a - mergeItemPtr: - - name: 1 - value: 1 - other: a - - name: 2 - value: 2 - other: b - - name: 2 - other: b -`), - }, - }, - { - Description: "add field to map in merging list by pointer with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergeItemPtr: - - name: 1 - mergeItemPtr: - - name: 1 - - name: 2 - value: 2 - - name: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 -mergeItemPtr: - - $setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 - name: 1 - mergeItemPtr: - - name: 1 - value: 1 -`), - Modified: []byte(` -mergeItemPtr: - - name: 1 - mergeItemPtr: - - name: 1 - value: 1 - - name: 2 - value: 2 - - name: 2 -`), - Current: []byte(` -mergeItemPtr: - - name: 1 - other: a - mergeItemPtr: - - name: 1 - value: a - - name: 2 - value: 2 - other: b - - name: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 -mergeItemPtr: - - $setElementOrder/mergeItemPtr: - - name: 1 - - name: 2 - name: 1 - mergeItemPtr: - - name: 1 - value: 1 -`), - Result: []byte(` -mergeItemPtr: - - name: 1 - other: a - mergeItemPtr: - - name: 1 - value: 1 - - name: 2 - value: 2 - other: b - - name: 2 - other: b -`), - }, - }, - { - Description: "merge lists of scalars", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: -- 1 -- 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: -- 1 -- 2 -- 3 -mergingIntList: -- 3 -`), - Modified: []byte(` -mergingIntList: -- 1 -- 2 -- 3 -`), - Current: []byte(` -mergingIntList: -- 1 -- 2 -- 4 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: -- 1 -- 2 -- 3 -mergingIntList: -- 3 -`), - Result: []byte(` -mergingIntList: -- 1 -- 2 -- 3 -- 4 -`), - }, - }, - { - Description: "add duplicate field to map in merging int list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 1 - - 2 - - 3 -mergingIntList: - - 3 -`), - Modified: []byte(` -mergingIntList: - - 1 - - 2 - - 3 -`), - Current: []byte(` -mergingIntList: - - 1 - - 2 - - 3 -`), - ThreeWay: []byte(`{}`), - Result: []byte(` -mergingIntList: - - 1 - - 2 - - 3 -`), - }, - }, - // test case for setElementOrder - { - Description: "add an item in a list of primitives and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: -- 1 -- 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: -- 3 -- 1 -- 2 -mergingIntList: -- 3 -`), - Modified: []byte(` -mergingIntList: -- 3 -- 1 -- 2 -`), - Current: []byte(` -mergingIntList: -- 1 -- 4 -- 2 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: -- 3 -- 1 -- 2 -mergingIntList: -- 3 -`), - Result: []byte(` -mergingIntList: -- 3 -- 1 -- 4 -- 2 -`), - }, - }, - { - Description: "delete an item in a list of primitives and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: -- 1 -- 2 -- 3 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: -- 2 -- 1 -$deleteFromPrimitiveList/mergingIntList: -- 3 -`), - Modified: []byte(` -mergingIntList: -- 2 -- 1 -`), - Current: []byte(` -mergingIntList: -- 1 -- 2 -- 3 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: -- 2 -- 1 -$deleteFromPrimitiveList/mergingIntList: -- 3 -`), - Result: []byte(` -mergingIntList: -- 2 -- 1 -`), - }, - }, - { - Description: "add an item in a list and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 3 - - name: 1 - - name: 2 -mergingList: - - name: 3 - value: 3 -`), - Modified: []byte(` -mergingList: - - name: 3 - value: 3 - - name: 1 - - name: 2 - value: 2 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 3 - - name: 1 - - name: 2 -mergingList: - - name: 3 - value: 3 -`), - Result: []byte(` -mergingList: - - name: 3 - value: 3 - - name: 1 - other: a - - name: 2 - value: 2 - other: b -`), - }, - }, - { - Description: "add multiple items in a list and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 4 - - name: 2 - - name: 3 -mergingList: - - name: 4 - value: 4 - - name: 3 - value: 3 -`), - Modified: []byte(` -mergingList: - - name: 1 - - name: 4 - value: 4 - - name: 2 - value: 2 - - name: 3 - value: 3 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 4 - - name: 2 - - name: 3 -mergingList: - - name: 4 - value: 4 - - name: 3 - value: 3 -`), - Result: []byte(` -mergingList: - - name: 1 - other: a - - name: 4 - value: 4 - - name: 2 - value: 2 - other: b - - name: 3 - value: 3 -`), - }, - }, - { - Description: "delete an item in a list and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 3 - value: 3 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 1 -mergingList: - - name: 3 - $patch: delete -`), - Modified: []byte(` -mergingList: - - name: 2 - value: 2 - - name: 1 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b - - name: 3 - value: 3 -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 1 -mergingList: - - name: 3 - $patch: delete -`), - Result: []byte(` -mergingList: - - name: 2 - value: 2 - other: b - - name: 1 - other: a -`), - }, - }, - { - Description: "change an item in a list and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 3 - value: 3 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 3 - - name: 1 -mergingList: - - name: 3 - value: x -`), - Modified: []byte(` -mergingList: - - name: 2 - value: 2 - - name: 3 - value: x - - name: 1 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b - - name: 3 - value: 3 -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 3 - - name: 1 -mergingList: - - name: 3 - value: x -`), - Result: []byte(` -mergingList: - - name: 2 - value: 2 - other: b - - name: 3 - value: x - - name: 1 - other: a -`), - }, - }, - { - Description: "add and delete an item in a list and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 3 - value: 3 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 4 - - name: 2 - - name: 1 -mergingList: - - name: 4 - value: 4 - - name: 3 - $patch: delete -`), - Modified: []byte(` -mergingList: - - name: 4 - value: 4 - - name: 2 - value: 2 - - name: 1 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - other: b - - name: 3 - value: 3 -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 4 - - name: 2 - - name: 1 -mergingList: - - name: 4 - value: 4 - - name: 3 - $patch: delete -`), - Result: []byte(` -mergingList: - - name: 4 - value: 4 - - name: 2 - value: 2 - other: b - - name: 1 - other: a -`), - }, - }, - { - Description: "set elements order in a list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 3 - value: 3 - - name: 4 - value: 4 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 4 - - name: 2 - - name: 3 - - name: 1 -`), - Modified: []byte(` -mergingList: - - name: 4 - value: 4 - - name: 2 - value: 2 - - name: 3 - value: 3 - - name: 1 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 3 - value: 3 - - name: 4 - value: 4 - - name: 2 - value: 2 -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 4 - - name: 2 - - name: 3 - - name: 1 -`), - Result: []byte(` -mergingList: - - name: 4 - value: 4 - - name: 2 - value: 2 - - name: 3 - value: 3 - - name: 1 - other: a -`), - }, - }, - { - Description: "set elements order in a list with server-only items", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 3 - value: 3 - - name: 4 - value: 4 - - name: 2 - value: 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 4 - - name: 2 - - name: 3 - - name: 1 -`), - Modified: []byte(` -mergingList: - - name: 4 - value: 4 - - name: 2 - value: 2 - - name: 3 - value: 3 - - name: 1 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 3 - value: 3 - - name: 4 - value: 4 - - name: 2 - value: 2 - - name: 9 -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 4 - - name: 2 - - name: 3 - - name: 1 -`), - Result: []byte(` -mergingList: - - name: 4 - value: 4 - - name: 2 - value: 2 - - name: 3 - value: 3 - - name: 1 - other: a - - name: 9 -`), - }, - }, - { - Description: "set elements order in a list with server-only items 2", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 - - name: 3 - value: 3 - - name: 4 - value: 4 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 1 - - name: 4 - - name: 3 -`), - Modified: []byte(` -mergingList: - - name: 2 - value: 2 - - name: 1 - - name: 4 - value: 4 - - name: 3 - value: 3 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - - name: 9 - - name: 3 - value: 3 - - name: 4 - value: 4 -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 1 - - name: 4 - - name: 3 -`), - Result: []byte(` -mergingList: - - name: 2 - value: 2 - - name: 1 - other: a - - name: 9 - - name: 4 - value: 4 - - name: 3 - value: 3 -`), - }, - }, - { - Description: "set elements order in a list with server-only items 3", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: - - name: 1 - - name: 2 - value: 2 - - name: 3 - value: 3 - - name: 4 - value: 4 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 1 - - name: 4 - - name: 3 -`), - Modified: []byte(` -mergingList: - - name: 2 - value: 2 - - name: 1 - - name: 4 - value: 4 - - name: 3 - value: 3 -`), - Current: []byte(` -mergingList: - - name: 1 - other: a - - name: 2 - value: 2 - - name: 7 - - name: 9 - - name: 8 - - name: 3 - value: 3 - - name: 4 - value: 4 -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 2 - - name: 1 - - name: 4 - - name: 3 -`), - Result: []byte(` -mergingList: - - name: 2 - value: 2 - - name: 1 - other: a - - name: 7 - - name: 9 - - name: 8 - - name: 4 - value: 4 - - name: 3 - value: 3 -`), - }, - }, - { - Description: "add an item in a int list and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 3 - - 1 - - 2 -mergingIntList: - - 3 -`), - Modified: []byte(` -mergingIntList: - - 3 - - 1 - - 2 -`), - Current: []byte(` -mergingIntList: - - 1 - - 2 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 3 - - 1 - - 2 -mergingIntList: - - 3 -`), - Result: []byte(` -mergingIntList: - - 3 - - 1 - - 2 -`), - }, - }, - { - Description: "add multiple items in a int list and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 1 - - 4 - - 2 - - 3 -mergingIntList: - - 4 - - 3 -`), - Modified: []byte(` -mergingIntList: - - 1 - - 4 - - 2 - - 3 -`), - Current: []byte(` -mergingIntList: - - 1 - - 2 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 1 - - 4 - - 2 - - 3 -mergingIntList: - - 4 - - 3 -`), - Result: []byte(` -mergingIntList: - - 1 - - 4 - - 2 - - 3 -`), - }, - }, - { - Description: "delete an item in a int list and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 3 - - 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 2 - - 1 -$deleteFromPrimitiveList/mergingIntList: - - 3 -`), - Modified: []byte(` -mergingIntList: - - 2 - - 1 -`), - Current: []byte(` -mergingIntList: - - 1 - - 2 - - 3 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 2 - - 1 -$deleteFromPrimitiveList/mergingIntList: - - 3 -`), - Result: []byte(` -mergingIntList: - - 2 - - 1 -`), - }, - }, - { - Description: "add and delete an item in a int list and preserve order", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 3 - - 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 4 - - 2 - - 1 -mergingIntList: - - 4 -$deleteFromPrimitiveList/mergingIntList: - - 3 -`), - Modified: []byte(` -mergingIntList: - - 4 - - 2 - - 1 -`), - Current: []byte(` -mergingIntList: - - 1 - - 2 - - 3 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 4 - - 2 - - 1 -mergingIntList: - - 4 -$deleteFromPrimitiveList/mergingIntList: - - 3 -`), - Result: []byte(` -mergingIntList: - - 4 - - 2 - - 1 -`), - }, - }, - { - Description: "set elements order in a int list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 3 - - 4 - - 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 4 - - 2 - - 3 - - 1 -`), - Modified: []byte(` -mergingIntList: - - 4 - - 2 - - 3 - - 1 -`), - Current: []byte(` -mergingIntList: - - 1 - - 3 - - 4 - - 2 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 4 - - 2 - - 3 - - 1 -`), - Result: []byte(` -mergingIntList: - - 4 - - 2 - - 3 - - 1 -`), - }, - }, - { - Description: "set elements order in a int list with server-only items", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 3 - - 4 - - 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 4 - - 2 - - 3 - - 1 -`), - Modified: []byte(` -mergingIntList: - - 4 - - 2 - - 3 - - 1 -`), - Current: []byte(` -mergingIntList: - - 1 - - 3 - - 4 - - 2 - - 9 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 4 - - 2 - - 3 - - 1 -`), - Result: []byte(` -mergingIntList: - - 4 - - 2 - - 3 - - 1 - - 9 -`), - }, - }, - { - Description: "set elements order in a int list with server-only items 2", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 2 - - 3 - - 4 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 2 - - 1 - - 4 - - 3 -`), - Modified: []byte(` -mergingIntList: - - 2 - - 1 - - 4 - - 3 -`), - Current: []byte(` -mergingIntList: - - 1 - - 2 - - 9 - - 3 - - 4 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 2 - - 1 - - 4 - - 3 -`), - Result: []byte(` -mergingIntList: - - 2 - - 1 - - 9 - - 4 - - 3 -`), - }, - }, - { - Description: "set elements order in a int list with server-only items 3", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: - - 1 - - 2 - - 3 - - 4 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: - - 2 - - 1 - - 4 - - 3 -`), - Modified: []byte(` -mergingIntList: - - 2 - - 1 - - 4 - - 3 -`), - Current: []byte(` -mergingIntList: - - 1 - - 2 - - 7 - - 9 - - 8 - - 3 - - 4 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: - - 2 - - 1 - - 4 - - 3 -`), - Result: []byte(` -mergingIntList: - - 2 - - 1 - - 7 - - 9 - - 8 - - 4 - - 3 -`), - }, - }, - { - // This test case is used just to demonstrate the behavior when dealing with a list with duplicate - Description: "behavior of set element order for a merging list with duplicate", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: -- name: 1 -- name: 2 - value: dup1 -- name: 3 -- name: 2 - value: dup2 -- name: 4 -`), - Current: []byte(` -mergingList: -- name: 1 -- name: 2 - value: dup1 -- name: 3 -- name: 2 - value: dup2 -- name: 4 -`), - Modified: []byte(` -mergingList: -- name: 2 - value: dup1 -- name: 1 -- name: 4 -- name: 3 -- name: 2 - value: dup2 -`), - TwoWay: []byte(` -$setElementOrder/mergingList: -- name: 2 -- name: 1 -- name: 4 -- name: 3 -- name: 2 -`), - TwoWayResult: []byte(` -mergingList: -- name: 2 - value: dup1 -- name: 2 - value: dup2 -- name: 1 -- name: 4 -- name: 3 -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: -- name: 2 -- name: 1 -- name: 4 -- name: 3 -- name: 2 -`), - Result: []byte(` -mergingList: -- name: 2 - value: dup1 -- name: 2 - value: dup2 -- name: 1 -- name: 4 -- name: 3 -`), - }, - }, - { - // This test case is used just to demonstrate the behavior when dealing with a list with duplicate - Description: "behavior of set element order for a merging int list with duplicate", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingIntList: -- 1 -- 2 -- 3 -- 2 -- 4 -`), - Current: []byte(` -mergingIntList: -- 1 -- 2 -- 3 -- 2 -- 4 -`), - Modified: []byte(` -mergingIntList: -- 2 -- 1 -- 4 -- 3 -- 2 -`), - TwoWay: []byte(` -$setElementOrder/mergingIntList: -- 2 -- 1 -- 4 -- 3 -- 2 -`), - TwoWayResult: []byte(` -mergingIntList: -- 2 -- 2 -- 1 -- 4 -- 3 -`), - ThreeWay: []byte(` -$setElementOrder/mergingIntList: -- 2 -- 1 -- 4 -- 3 -- 2 -`), - Result: []byte(` -mergingIntList: -- 2 -- 2 -- 1 -- 4 -- 3 -`), - }, - }, - { - Description: "retainKeys map should clear defaulted field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(`{}`), - Current: []byte(` -retainKeysMap: - value: foo -`), - Modified: []byte(` -retainKeysMap: - other: bar -`), - TwoWay: []byte(` -retainKeysMap: - other: bar -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - other - other: bar -`), - Result: []byte(` -retainKeysMap: - other: bar -`), - }, - }, - { - Description: "retainKeys map should clear defaulted field with conflict (discriminated union)", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(`{}`), - Current: []byte(` -retainKeysMap: - name: type1 - value: foo -`), - Modified: []byte(` -retainKeysMap: - name: type2 - other: bar -`), - TwoWay: []byte(` -retainKeysMap: - name: type2 - other: bar -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - other - name: type2 - other: bar -`), - Result: []byte(` -retainKeysMap: - name: type2 - other: bar -`), - }, - }, - { - Description: "retainKeys map adds a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo -`), - Current: []byte(` -retainKeysMap: - name: foo -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value - value: bar -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value - value: bar -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar -`), - }, - }, - { - Description: "retainKeys map adds a field and clear a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo -`), - Current: []byte(` -retainKeysMap: - name: foo - other: a -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value - value: bar -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value - value: bar -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar -`), - }, - }, - { - Description: "retainKeys map deletes a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - value: bar -`), - Current: []byte(` -retainKeysMap: - name: foo - value: bar -`), - Modified: []byte(` -retainKeysMap: - name: foo -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - value: null -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - value: null -`), - Result: []byte(` -retainKeysMap: - name: foo -`), - }, - }, - { - Description: "retainKeys map deletes a field and clears a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - value: bar -`), - Current: []byte(` -retainKeysMap: - name: foo - value: bar - other: a -`), - Modified: []byte(` -retainKeysMap: - name: foo -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - value: null -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - value: null -`), - Result: []byte(` -retainKeysMap: - name: foo -`), - }, - }, - { - Description: "retainKeys map clears a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - value: bar -`), - Current: []byte(` -retainKeysMap: - name: foo - value: bar - other: a -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar -`), - TwoWay: []byte(`{}`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar -`), - }, - }, - { - Description: "retainKeys map nested map with no change", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - simpleMap: - key1: a -`), - Current: []byte(` -retainKeysMap: - name: foo - simpleMap: - key1: a -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - simpleMap - - value - value: bar -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - simpleMap - - value - value: bar -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a -`), - }, - }, - { - Description: "retainKeys map adds a field in a nested map", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a -`), - Current: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a - key3: c -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a - key2: b -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - simpleMap - - value - simpleMap: - key2: b -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - simpleMap - - value - simpleMap: - key2: b -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a - key2: b - key3: c -`), - }, - }, - { - Description: "retainKeys map deletes a field in a nested map", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a - key2: b -`), - Current: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a - key2: b - key3: c -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - simpleMap - - value - simpleMap: - key2: null -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - simpleMap - - value - simpleMap: - key2: null -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a - key3: c -`), - }, - }, - { - Description: "retainKeys map changes a field in a nested map", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a - key2: b -`), - Current: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: a - key2: b - key3: c -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: x - key2: b -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - simpleMap - - value - simpleMap: - key1: x -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - simpleMap - - value - simpleMap: - key1: x -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: x - key2: b - key3: c -`), - }, - }, - { - Description: "retainKeys map changes a field in a nested map with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: old - key2: b -`), - Current: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: new - key2: b - key3: c -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: modified - key2: b -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - simpleMap - - value - simpleMap: - key1: modified -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - simpleMap - - value - simpleMap: - key1: modified -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar - simpleMap: - key1: modified - key2: b - key3: c -`), - }, - }, - { - Description: "retainKeys map replaces non-merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - value: bar - nonMergingList: - - name: a - - name: b -`), - Current: []byte(` -retainKeysMap: - name: foo - value: bar - nonMergingList: - - name: a - - name: b -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar - nonMergingList: - - name: a - - name: c - - name: b -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - nonMergingList - - value - nonMergingList: - - name: a - - name: c - - name: b -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - nonMergingList - - value - nonMergingList: - - name: a - - name: c - - name: b -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar - nonMergingList: - - name: a - - name: c - - name: b -`), - }, - }, - { - Description: "retainKeys map nested non-merging list with no change", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - nonMergingList: - - name: a - - name: b -`), - Current: []byte(` -retainKeysMap: - name: foo - nonMergingList: - - name: a - - name: b -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar - nonMergingList: - - name: a - - name: b -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - nonMergingList - - value - value: bar -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - nonMergingList - - value - value: bar -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar - nonMergingList: - - name: a - - name: b -`), - }, - }, - { - Description: "retainKeys map nested non-merging list with no change with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - nonMergingList: - - name: a - - name: b -`), - Current: []byte(` -retainKeysMap: - name: foo - nonMergingList: - - name: a - - name: b - - name: c -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar - nonMergingList: - - name: a - - name: b -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - nonMergingList - - value - value: bar -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - nonMergingList - - value - value: bar - nonMergingList: - - name: a - - name: b -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar - nonMergingList: - - name: a - - name: b -`), - }, - }, - { - Description: "retainKeys map deletes nested non-merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - nonMergingList: - - name: a - - name: b -`), - Current: []byte(` -retainKeysMap: - name: foo - nonMergingList: - - name: a - - name: b -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value - value: bar - nonMergingList: null -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value - value: bar - nonMergingList: null -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar -`), - }, - }, - { - Description: "retainKeys map delete nested non-merging list with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - nonMergingList: - - name: a - - name: b -`), - Current: []byte(` -retainKeysMap: - name: foo - nonMergingList: - - name: a - - name: b - - name: c -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value - value: bar - nonMergingList: null -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value - value: bar - nonMergingList: null -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar -`), - }, - }, - { - Description: "retainKeys map nested merging int list with no change", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 -`), - Current: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 - - 3 -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar - mergingIntList: - - 1 - - 2 -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingIntList - - name - - value - value: bar -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingIntList - - name - - value - $setElementOrder/mergingIntList: - - 1 - - 2 - value: bar -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar - mergingIntList: - - 1 - - 2 - - 3 -`), - }, - }, - { - Description: "retainKeys map adds an item in nested merging int list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 -`), - Current: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 - - 3 -`), - Modified: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 - - 4 -`), - TwoWay: []byte(` -retainKeysMap: - $setElementOrder/mergingIntList: - - 1 - - 2 - - 4 - $retainKeys: - - mergingIntList - - name - mergingIntList: - - 4 -`), - ThreeWay: []byte(` -retainKeysMap: - $setElementOrder/mergingIntList: - - 1 - - 2 - - 4 - $retainKeys: - - mergingIntList - - name - mergingIntList: - - 4 -`), - Result: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 - - 4 - - 3 -`), - }, - }, - { - Description: "retainKeys map deletes an item in nested merging int list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 - - 3 -`), - Current: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 - - 3 - - 4 -`), - Modified: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 3 -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingIntList - - name - $deleteFromPrimitiveList/mergingIntList: - - 2 - $setElementOrder/mergingIntList: - - 1 - - 3 -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingIntList - - name - $deleteFromPrimitiveList/mergingIntList: - - 2 - $setElementOrder/mergingIntList: - - 1 - - 3 -`), - Result: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 3 - - 4 -`), - }, - }, - { - Description: "retainKeys map adds an item and deletes an item in nested merging int list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 - - 3 -`), - Current: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 - - 3 - - 4 -`), - Modified: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 3 - - 5 -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingIntList - - name - mergingIntList: - - 5 - $deleteFromPrimitiveList/mergingIntList: - - 2 - $setElementOrder/mergingIntList: - - 1 - - 3 - - 5 -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingIntList - - name - mergingIntList: - - 5 - $deleteFromPrimitiveList/mergingIntList: - - 2 - $setElementOrder/mergingIntList: - - 1 - - 3 - - 5 -`), - Result: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 3 - - 5 - - 4 -`), - }, - }, - { - Description: "retainKeys map deletes nested merging int list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 - - 3 -`), - Current: []byte(` -retainKeysMap: - name: foo - mergingIntList: - - 1 - - 2 - - 3 -`), - Modified: []byte(` -retainKeysMap: - name: foo -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - mergingIntList: null -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - mergingIntList: null -`), - Result: []byte(` -retainKeysMap: - name: foo -`), - }, - }, - { - Description: "retainKeys map nested merging list with no change", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b -`), - Current: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b - - name: c -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar - mergingList: - - name: a - - name: b -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingList - - name - - value - value: bar -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingList - - name - - value - $setElementOrder/mergingList: - - name: a - - name: b - value: bar -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar - mergingList: - - name: a - - name: b - - name: c -`), - }, - }, - { - Description: "retainKeys map adds an item in nested merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b -`), - Current: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b - - name: x -`), - Modified: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b - - name: c -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingList - - name - $setElementOrder/mergingList: - - name: a - - name: b - - name: c - mergingList: - - name: c -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingList - - name - $setElementOrder/mergingList: - - name: a - - name: b - - name: c - mergingList: - - name: c -`), - Result: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b - - name: c - - name: x -`), - }, - }, - { - Description: "retainKeys map changes an item in nested merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b - value: foo -`), - Current: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b - value: foo - - name: x -`), - Modified: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b - value: bar -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingList - - name - $setElementOrder/mergingList: - - name: a - - name: b - mergingList: - - name: b - value: bar -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingList - - name - $setElementOrder/mergingList: - - name: a - - name: b - mergingList: - - name: b - value: bar -`), - Result: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b - value: bar - - name: x -`), - }, - }, - { - Description: "retainKeys map deletes nested merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b -`), - Current: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b -`), - Modified: []byte(` -retainKeysMap: - name: foo - value: bar -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value - value: bar - mergingList: null -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - name - - value - value: bar - mergingList: null -`), - Result: []byte(` -retainKeysMap: - name: foo - value: bar -`), - }, - }, - { - Description: "retainKeys map deletes an item in nested merging list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b -`), - Current: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: b - - name: x -`), - Modified: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a -`), - TwoWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingList - - name - $setElementOrder/mergingList: - - name: a - mergingList: - - name: b - $patch: delete -`), - ThreeWay: []byte(` -retainKeysMap: - $retainKeys: - - mergingList - - name - $setElementOrder/mergingList: - - name: a - mergingList: - - name: b - $patch: delete -`), - Result: []byte(` -retainKeysMap: - name: foo - mergingList: - - name: a - - name: x -`), - }, - }, - { - Description: "retainKeys list of maps clears a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a -`), - Current: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a - other: x -`), - Modified: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a -`), - TwoWay: []byte(`{}`), - ThreeWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo -`), - Result: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a -`), - }, - }, - { - Description: "retainKeys list of maps clears a field with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: old -`), - Current: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: new - other: x -`), - Modified: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: modified -`), - TwoWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo - value: modified -`), - ThreeWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo - value: modified -`), - Result: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: modified -`), - }, - }, - { - Description: "retainKeys list of maps changes a field and clear a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: old -`), - Current: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: old - other: x -`), - Modified: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: new -`), - TwoWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo - value: new -`), - ThreeWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo - value: new -`), - Result: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: new -`), - }, - }, - { - Description: "retainKeys list of maps changes a field and clear a field with conflict", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: old -`), - Current: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: modified - other: x -`), - Modified: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: new -`), - TwoWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo - value: new -`), - ThreeWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo - value: new -`), - Result: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: new -`), - }, - }, - { - Description: "retainKeys list of maps adds a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMergingList: -- name: bar -- name: foo -`), - Current: []byte(` -retainKeysMergingList: -- name: bar -- name: foo -`), - Modified: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a -`), - TwoWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo - value: a -`), - ThreeWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo - value: a -`), - Result: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a -`), - }, - }, - { - Description: "retainKeys list of maps adds a field and clear a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMergingList: -- name: bar -- name: foo -`), - Current: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - other: x -`), - Modified: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a -`), - TwoWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo - value: a -`), - ThreeWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - - value - name: foo - value: a -`), - Result: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a -`), - }, - }, - { - Description: "retainKeys list of maps deletes a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a -`), - Current: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a -`), - Modified: []byte(` -retainKeysMergingList: -- name: bar -- name: foo -`), - TwoWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - name: foo - value: null -`), - ThreeWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - name: foo - value: null -`), - Result: []byte(` -retainKeysMergingList: -- name: bar -- name: foo -`), - }, - }, - { - Description: "retainKeys list of maps deletes a field and clear a field", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a -`), - Current: []byte(` -retainKeysMergingList: -- name: bar -- name: foo - value: a - other: x -`), - Modified: []byte(` -retainKeysMergingList: -- name: bar -- name: foo -`), - TwoWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - name: foo - value: null -`), - ThreeWay: []byte(` -$setElementOrder/retainKeysMergingList: - - name: bar - - name: foo -retainKeysMergingList: -- $retainKeys: - - name - name: foo - value: null -`), - Result: []byte(` -retainKeysMergingList: -- name: bar -- name: foo -`), - }, - }, - { - Description: "delete and reorder in one list, reorder in another", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -mergingList: -- name: a - value: a -- name: b - value: b -mergeItemPtr: -- name: c - value: c -- name: d - value: d -`), - Current: []byte(` -mergingList: -- name: a - value: a -- name: b - value: b -mergeItemPtr: -- name: c - value: c -- name: d - value: d -`), - Modified: []byte(` -mergingList: -- name: b - value: b -mergeItemPtr: -- name: d - value: d -- name: c - value: c -`), - TwoWay: []byte(` -$setElementOrder/mergingList: -- name: b -$setElementOrder/mergeItemPtr: -- name: d -- name: c -mergingList: -- $patch: delete - name: a -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: -- name: b -$setElementOrder/mergeItemPtr: -- name: d -- name: c -mergingList: -- $patch: delete - name: a -`), - Result: []byte(` -mergingList: -- name: b - value: b -mergeItemPtr: -- name: d - value: d -- name: c - value: c -`), - }, - }, -} - -func TestStrategicMergePatch(t *testing.T) { - testStrategicMergePatchWithCustomArgumentsUsingStruct(t, "bad struct", - "{}", "{}", []byte("<THIS IS NOT A STRUCT>"), mergepatch.ErrBadArgKind(struct{}{}, []byte{})) - - mergeItemOpenapiSchema := PatchMetaFromOpenAPI{ - Schema: sptest.GetSchemaOrDie(fakeMergeItemSchema, "mergeItem"), - } - schemas := []LookupPatchMeta{ - mergeItemStructSchema, - mergeItemOpenapiSchema, - } - - tc := StrategicMergePatchTestCases{} - err := yaml.Unmarshal(createStrategicMergePatchTestCaseData, &tc) - if err != nil { - t.Errorf("can't unmarshal test cases: %s\n", err) - return - } - - for _, schema := range schemas { - testStrategicMergePatchWithCustomArguments(t, "bad original", - "<THIS IS NOT JSON>", "{}", schema, mergepatch.ErrBadJSONDoc) - testStrategicMergePatchWithCustomArguments(t, "bad patch", - "{}", "<THIS IS NOT JSON>", schema, mergepatch.ErrBadJSONDoc) - testStrategicMergePatchWithCustomArguments(t, "nil struct", - "{}", "{}", nil, mergepatch.ErrBadArgKind(struct{}{}, nil)) - - for _, c := range tc.TestCases { - testTwoWayPatch(t, c, schema) - testThreeWayPatch(t, c, schema) - } - - // run multiple times to exercise different map traversal orders - for i := 0; i < 10; i++ { - for _, c := range strategicMergePatchRawTestCases { - testTwoWayPatchForRawTestCase(t, c, schema) - testThreeWayPatchForRawTestCase(t, c, schema) - } - } - } -} - -func testStrategicMergePatchWithCustomArgumentsUsingStruct(t *testing.T, description, original, patch string, dataStruct interface{}, expected error) { - schema, actual := NewPatchMetaFromStruct(dataStruct) - // If actual is not nil, check error. If errors match, return. - if actual != nil { - checkErrorsEqual(t, description, expected, actual, schema) - return - } - testStrategicMergePatchWithCustomArguments(t, description, original, patch, schema, expected) -} - -func testStrategicMergePatchWithCustomArguments(t *testing.T, description, original, patch string, schema LookupPatchMeta, expected error) { - _, actual := StrategicMergePatch([]byte(original), []byte(patch), schema) - checkErrorsEqual(t, description, expected, actual, schema) -} - -func checkErrorsEqual(t *testing.T, description string, expected, actual error, schema LookupPatchMeta) { - if actual != expected { - if actual == nil { - t.Errorf("using %s expected error: %s\ndid not occur in test case: %s", getSchemaType(schema), expected, description) - return - } - - if expected == nil || actual.Error() != expected.Error() { - t.Errorf("using %s unexpected error: %s\noccurred in test case: %s", getSchemaType(schema), actual, description) - return - } - } -} - -func testTwoWayPatch(t *testing.T, c StrategicMergePatchTestCase, schema LookupPatchMeta) { - original, expectedPatch, modified, expectedResult := twoWayTestCaseToJSONOrFail(t, c, schema) - - actualPatch, err := CreateTwoWayMergePatchUsingLookupPatchMeta(original, modified, schema) - if err != nil { - t.Errorf("using %s error: %s\nin test case: %s\ncannot create two way patch: %s:\n%s\n", - getSchemaType(schema), err, c.Description, original, mergepatch.ToYAMLOrError(c.StrategicMergePatchTestCaseData)) - return - } - - testPatchCreation(t, expectedPatch, actualPatch, c.Description) - testPatchApplication(t, original, actualPatch, expectedResult, c.Description, "", schema) -} - -func testTwoWayPatchForRawTestCase(t *testing.T, c StrategicMergePatchRawTestCase, schema LookupPatchMeta) { - original, expectedPatch, modified, expectedResult := twoWayRawTestCaseToJSONOrFail(t, c) - - actualPatch, err := CreateTwoWayMergePatchUsingLookupPatchMeta(original, modified, schema) - if err != nil { - t.Errorf("error: %s\nin test case: %s\ncannot create two way patch:\noriginal:%s\ntwoWay:%s\nmodified:%s\ncurrent:%s\nthreeWay:%s\nresult:%s\n", - err, c.Description, c.Original, c.TwoWay, c.Modified, c.Current, c.ThreeWay, c.Result) - return - } - - testPatchCreation(t, expectedPatch, actualPatch, c.Description) - testPatchApplication(t, original, actualPatch, expectedResult, c.Description, c.ExpectedError, schema) -} - -func twoWayTestCaseToJSONOrFail(t *testing.T, c StrategicMergePatchTestCase, schema LookupPatchMeta) ([]byte, []byte, []byte, []byte) { - expectedResult := c.TwoWayResult - if expectedResult == nil { - expectedResult = c.Modified - } - return sortJsonOrFail(t, testObjectToJSONOrFail(t, c.Original), c.Description, schema), - sortJsonOrFail(t, testObjectToJSONOrFail(t, c.TwoWay), c.Description, schema), - sortJsonOrFail(t, testObjectToJSONOrFail(t, c.Modified), c.Description, schema), - sortJsonOrFail(t, testObjectToJSONOrFail(t, expectedResult), c.Description, schema) -} - -func twoWayRawTestCaseToJSONOrFail(t *testing.T, c StrategicMergePatchRawTestCase) ([]byte, []byte, []byte, []byte) { - expectedResult := c.TwoWayResult - if expectedResult == nil { - expectedResult = c.Modified - } - return yamlToJSONOrError(t, c.Original), - yamlToJSONOrError(t, c.TwoWay), - yamlToJSONOrError(t, c.Modified), - yamlToJSONOrError(t, expectedResult) -} - -func testThreeWayPatch(t *testing.T, c StrategicMergePatchTestCase, schema LookupPatchMeta) { - original, modified, current, expected, result := threeWayTestCaseToJSONOrFail(t, c, schema) - actual, err := CreateThreeWayMergePatch(original, modified, current, schema, false) - if err != nil { - if !mergepatch.IsConflict(err) { - t.Errorf("using %s error: %s\nin test case: %s\ncannot create three way patch:\n%s\n", - getSchemaType(schema), err, c.Description, mergepatch.ToYAMLOrError(c.StrategicMergePatchTestCaseData)) - return - } - - if !strings.Contains(c.Description, "conflict") { - t.Errorf("using %s unexpected conflict: %s\nin test case: %s\ncannot create three way patch:\n%s\n", - getSchemaType(schema), err, c.Description, mergepatch.ToYAMLOrError(c.StrategicMergePatchTestCaseData)) - return - } - - if len(c.Result) > 0 { - actual, err := CreateThreeWayMergePatch(original, modified, current, schema, true) - if err != nil { - t.Errorf("using %s error: %s\nin test case: %s\ncannot force three way patch application:\n%s\n", - getSchemaType(schema), err, c.Description, mergepatch.ToYAMLOrError(c.StrategicMergePatchTestCaseData)) - return - } - - testPatchCreation(t, expected, actual, c.Description) - testPatchApplication(t, current, actual, result, c.Description, "", schema) - } - - return - } - - if strings.Contains(c.Description, "conflict") || len(c.Result) < 1 { - t.Errorf("using %s error in test case: %s\nexpected conflict did not occur:\n%s\n", - getSchemaType(schema), c.Description, mergepatch.ToYAMLOrError(c.StrategicMergePatchTestCaseData)) - return - } - - testPatchCreation(t, expected, actual, c.Description) - testPatchApplication(t, current, actual, result, c.Description, "", schema) -} - -func testThreeWayPatchForRawTestCase(t *testing.T, c StrategicMergePatchRawTestCase, schema LookupPatchMeta) { - original, modified, current, expected, result := threeWayRawTestCaseToJSONOrFail(t, c) - actual, err := CreateThreeWayMergePatch(original, modified, current, schema, false) - if err != nil { - if !mergepatch.IsConflict(err) { - t.Errorf("using %s error: %s\nin test case: %s\ncannot create three way patch:\noriginal:%s\ntwoWay:%s\nmodified:%s\ncurrent:%s\nthreeWay:%s\nresult:%s\n", - getSchemaType(schema), err, c.Description, c.Original, c.TwoWay, c.Modified, c.Current, c.ThreeWay, c.Result) - return - } - - if !strings.Contains(c.Description, "conflict") { - t.Errorf("using %s unexpected conflict: %s\nin test case: %s\ncannot create three way patch:\noriginal:%s\ntwoWay:%s\nmodified:%s\ncurrent:%s\nthreeWay:%s\nresult:%s\n", - getSchemaType(schema), err, c.Description, c.Original, c.TwoWay, c.Modified, c.Current, c.ThreeWay, c.Result) - return - } - - if len(c.Result) > 0 { - actual, err := CreateThreeWayMergePatch(original, modified, current, schema, true) - if err != nil { - t.Errorf("using %s error: %s\nin test case: %s\ncannot force three way patch application:\noriginal:%s\ntwoWay:%s\nmodified:%s\ncurrent:%s\nthreeWay:%s\nresult:%s\n", - getSchemaType(schema), err, c.Description, c.Original, c.TwoWay, c.Modified, c.Current, c.ThreeWay, c.Result) - return - } - - testPatchCreation(t, expected, actual, c.Description) - testPatchApplication(t, current, actual, result, c.Description, c.ExpectedError, schema) - } - - return - } - - if strings.Contains(c.Description, "conflict") || len(c.Result) < 1 { - t.Errorf("using %s error: %s\nin test case: %s\nexpected conflict did not occur:\noriginal:%s\ntwoWay:%s\nmodified:%s\ncurrent:%s\nthreeWay:%s\nresult:%s\n", - getSchemaType(schema), err, c.Description, c.Original, c.TwoWay, c.Modified, c.Current, c.ThreeWay, c.Result) - return - } - - testPatchCreation(t, expected, actual, c.Description) - testPatchApplication(t, current, actual, result, c.Description, c.ExpectedError, schema) -} - -func threeWayTestCaseToJSONOrFail(t *testing.T, c StrategicMergePatchTestCase, schema LookupPatchMeta) ([]byte, []byte, []byte, []byte, []byte) { - return sortJsonOrFail(t, testObjectToJSONOrFail(t, c.Original), c.Description, schema), - sortJsonOrFail(t, testObjectToJSONOrFail(t, c.Modified), c.Description, schema), - sortJsonOrFail(t, testObjectToJSONOrFail(t, c.Current), c.Description, schema), - sortJsonOrFail(t, testObjectToJSONOrFail(t, c.ThreeWay), c.Description, schema), - sortJsonOrFail(t, testObjectToJSONOrFail(t, c.Result), c.Description, schema) -} - -func threeWayRawTestCaseToJSONOrFail(t *testing.T, c StrategicMergePatchRawTestCase) ([]byte, []byte, []byte, []byte, []byte) { - return yamlToJSONOrError(t, c.Original), - yamlToJSONOrError(t, c.Modified), - yamlToJSONOrError(t, c.Current), - yamlToJSONOrError(t, c.ThreeWay), - yamlToJSONOrError(t, c.Result) -} - -func testPatchCreation(t *testing.T, expected, actual []byte, description string) { - if !reflect.DeepEqual(actual, expected) { - t.Errorf("error in test case: %s\nexpected patch:\n%s\ngot:\n%s\n", - description, jsonToYAMLOrError(expected), jsonToYAMLOrError(actual)) - return - } -} - -func testPatchApplication(t *testing.T, original, patch, expected []byte, description, expectedError string, schema LookupPatchMeta) { - result, err := StrategicMergePatchUsingLookupPatchMeta(original, patch, schema) - if len(expectedError) != 0 { - if err != nil && strings.Contains(err.Error(), expectedError) { - return - } - t.Errorf("using %s expected error should contain:\n%s\nin test case: %s\nbut got:\n%s\n", getSchemaType(schema), expectedError, description, err) - } - if err != nil { - t.Errorf("using %s error: %s\nin test case: %s\ncannot apply patch:\n%s\nto original:\n%s\n", - getSchemaType(schema), err, description, jsonToYAMLOrError(patch), jsonToYAMLOrError(original)) - return - } - - if !reflect.DeepEqual(result, expected) { - format := "using error in test case: %s\npatch application failed:\noriginal:\n%s\npatch:\n%s\nexpected:\n%s\ngot:\n%s\n" - t.Errorf(format, description, - jsonToYAMLOrError(original), jsonToYAMLOrError(patch), - jsonToYAMLOrError(expected), jsonToYAMLOrError(result)) - return - } -} - -func testObjectToJSONOrFail(t *testing.T, o map[string]interface{}) []byte { - if o == nil { - return nil - } - - j, err := toJSON(o) - if err != nil { - t.Error(err) - } - return j -} - -func sortJsonOrFail(t *testing.T, j []byte, description string, schema LookupPatchMeta) []byte { - if j == nil { - return nil - } - r, err := sortMergeListsByName(j, schema) - if err != nil { - t.Errorf("using %s error: %s\n in test case: %s\ncannot sort object:\n%s\n", getSchemaType(schema), err, description, j) - return nil - } - - return r -} - -func getSchemaType(schema LookupPatchMeta) string { - return reflect.TypeOf(schema).String() -} - -func jsonToYAMLOrError(j []byte) string { - y, err := jsonToYAML(j) - if err != nil { - return err.Error() - } - - return string(y) -} - -func toJSON(v interface{}) ([]byte, error) { - j, err := json.Marshal(v) - if err != nil { - return nil, fmt.Errorf("json marshal failed: %v\n%v\n", err, spew.Sdump(v)) - } - - return j, nil -} - -func jsonToYAML(j []byte) ([]byte, error) { - y, err := yaml.JSONToYAML(j) - if err != nil { - return nil, fmt.Errorf("json to yaml failed: %v\n%v\n", err, j) - } - - return y, nil -} - -func yamlToJSON(y []byte) ([]byte, error) { - j, err := yaml.YAMLToJSON(y) - if err != nil { - return nil, fmt.Errorf("yaml to json failed: %v\n%v\n", err, y) - } - - return j, nil -} - -func yamlToJSONOrError(t *testing.T, y []byte) []byte { - j, err := yamlToJSON(y) - if err != nil { - t.Errorf("%v", err) - } - - return j -} - -type PrecisionItem struct { - Name string `json:"name,omitempty"` - Int32 int32 `json:"int32,omitempty"` - Int64 int64 `json:"int64,omitempty"` - Float32 float32 `json:"float32,omitempty"` - Float64 float64 `json:"float64,omitempty"` -} - -var ( - precisionItem PrecisionItem - precisionItemStructSchema = PatchMetaFromStruct{T: GetTagStructTypeOrDie(precisionItem)} -) - -func TestNumberConversion(t *testing.T) { - testcases := map[string]struct { - Old string - New string - ExpectedPatch string - ExpectedResult string - }{ - "empty": { - Old: `{}`, - New: `{}`, - ExpectedPatch: `{}`, - ExpectedResult: `{}`, - }, - "int32 medium": { - Old: `{"int32":1000000}`, - New: `{"int32":1000000,"name":"newname"}`, - ExpectedPatch: `{"name":"newname"}`, - ExpectedResult: `{"int32":1000000,"name":"newname"}`, - }, - "int32 max": { - Old: `{"int32":2147483647}`, - New: `{"int32":2147483647,"name":"newname"}`, - ExpectedPatch: `{"name":"newname"}`, - ExpectedResult: `{"int32":2147483647,"name":"newname"}`, - }, - "int64 medium": { - Old: `{"int64":1000000}`, - New: `{"int64":1000000,"name":"newname"}`, - ExpectedPatch: `{"name":"newname"}`, - ExpectedResult: `{"int64":1000000,"name":"newname"}`, - }, - "int64 max": { - Old: `{"int64":9223372036854775807}`, - New: `{"int64":9223372036854775807,"name":"newname"}`, - ExpectedPatch: `{"name":"newname"}`, - ExpectedResult: `{"int64":9223372036854775807,"name":"newname"}`, - }, - "float32 max": { - Old: `{"float32":3.4028234663852886e+38}`, - New: `{"float32":3.4028234663852886e+38,"name":"newname"}`, - ExpectedPatch: `{"name":"newname"}`, - ExpectedResult: `{"float32":3.4028234663852886e+38,"name":"newname"}`, - }, - "float64 max": { - Old: `{"float64":1.7976931348623157e+308}`, - New: `{"float64":1.7976931348623157e+308,"name":"newname"}`, - ExpectedPatch: `{"name":"newname"}`, - ExpectedResult: `{"float64":1.7976931348623157e+308,"name":"newname"}`, - }, - } - - precisionItemOpenapiSchema := PatchMetaFromOpenAPI{ - Schema: sptest.GetSchemaOrDie(fakePrecisionItemSchema, "precisionItem"), - } - precisionItemSchemas := []LookupPatchMeta{ - precisionItemStructSchema, - precisionItemOpenapiSchema, - } - - for _, schema := range precisionItemSchemas { - for k, tc := range testcases { - patch, err := CreateTwoWayMergePatchUsingLookupPatchMeta([]byte(tc.Old), []byte(tc.New), schema) - if err != nil { - t.Errorf("using %s in testcase %s: unexpected error %v", getSchemaType(schema), k, err) - continue - } - if tc.ExpectedPatch != string(patch) { - t.Errorf("using %s in testcase %s: expected %s, got %s", getSchemaType(schema), k, tc.ExpectedPatch, string(patch)) - continue - } - - result, err := StrategicMergePatchUsingLookupPatchMeta([]byte(tc.Old), patch, schema) - if err != nil { - t.Errorf("using %s in testcase %s: unexpected error %v", getSchemaType(schema), k, err) - continue - } - if tc.ExpectedResult != string(result) { - t.Errorf("using %s in testcase %s: expected %s, got %s", getSchemaType(schema), k, tc.ExpectedResult, string(result)) - continue - } - } - } -} - -var replaceRawExtensionPatchTestCases = []StrategicMergePatchRawTestCase{ - { - Description: "replace RawExtension field, rest unchanched", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -name: my-object -value: some-value -other: current-other -replacingItem: - Some: Generic - Yaml: Inside - The: RawExtension - Field: Period -`), - Current: []byte(` -name: my-object -value: some-value -other: current-other -mergingList: - - name: 1 - - name: 2 - - name: 3 -replacingItem: - Some: Generic - Yaml: Inside - The: RawExtension - Field: Period -`), - Modified: []byte(` -name: my-object -value: some-value -other: current-other -mergingList: - - name: 1 - - name: 2 - - name: 3 -replacingItem: - Newly: Modified - Yaml: Inside - The: RawExtension -`), - TwoWay: []byte(` -mergingList: - - name: 1 - - name: 2 - - name: 3 -replacingItem: - Newly: Modified - Yaml: Inside - The: RawExtension -`), - TwoWayResult: []byte(` -name: my-object -value: some-value -other: current-other -mergingList: - - name: 1 - - name: 2 - - name: 3 -replacingItem: - Newly: Modified - Yaml: Inside - The: RawExtension -`), - ThreeWay: []byte(` -replacingItem: - Newly: Modified - Yaml: Inside - The: RawExtension -`), - Result: []byte(` -name: my-object -value: some-value -other: current-other -mergingList: - - name: 1 - - name: 2 - - name: 3 -replacingItem: - Newly: Modified - Yaml: Inside - The: RawExtension -`), - }, - }, - { - Description: "replace RawExtension field and merge list", - StrategicMergePatchRawTestCaseData: StrategicMergePatchRawTestCaseData{ - Original: []byte(` -name: my-object -value: some-value -other: current-other -mergingList: - - name: 1 -replacingItem: - Some: Generic - Yaml: Inside - The: RawExtension - Field: Period -`), - Current: []byte(` -name: my-object -value: some-value -other: current-other -mergingList: - - name: 1 - - name: 3 -replacingItem: - Some: Generic - Yaml: Inside - The: RawExtension - Field: Period -`), - Modified: []byte(` -name: my-object -value: some-value -other: current-other -mergingList: - - name: 1 - - name: 2 -replacingItem: - Newly: Modified - Yaml: Inside - The: RawExtension -`), - TwoWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 2 -replacingItem: - Newly: Modified - Yaml: Inside - The: RawExtension -`), - TwoWayResult: []byte(` -name: my-object -value: some-value -other: current-other -mergingList: - - name: 1 - - name: 2 -replacingItem: - Newly: Modified - Yaml: Inside - The: RawExtension -`), - ThreeWay: []byte(` -$setElementOrder/mergingList: - - name: 1 - - name: 2 -mergingList: - - name: 2 -replacingItem: - Newly: Modified - Yaml: Inside - The: RawExtension -`), - Result: []byte(` -name: my-object -value: some-value -other: current-other -mergingList: - - name: 1 - - name: 2 - - name: 3 -replacingItem: - Newly: Modified - Yaml: Inside - The: RawExtension -`), - }, - }, -} - -func TestReplaceWithRawExtension(t *testing.T) { - mergeItemOpenapiSchema := PatchMetaFromOpenAPI{ - Schema: sptest.GetSchemaOrDie(fakeMergeItemSchema, "mergeItem"), - } - schemas := []LookupPatchMeta{ - mergeItemStructSchema, - mergeItemOpenapiSchema, - } - - for _, schema := range schemas { - for _, c := range replaceRawExtensionPatchTestCases { - testTwoWayPatchForRawTestCase(t, c, schema) - testThreeWayPatchForRawTestCase(t, c, schema) - } - } -} - -func TestUnknownField(t *testing.T) { - testcases := map[string]struct { - Original string - Current string - Modified string - - ExpectedTwoWay string - ExpectedTwoWayErr string - ExpectedTwoWayResult string - ExpectedThreeWay string - ExpectedThreeWayErr string - ExpectedThreeWayResult string - }{ - // cases we can successfully strategically merge - "no diff": { - Original: `{"array":[1,2,3],"complex":{"nested":true},"name":"foo","scalar":true}`, - Current: `{"array":[1,2,3],"complex":{"nested":true},"name":"foo","scalar":true}`, - Modified: `{"array":[1,2,3],"complex":{"nested":true},"name":"foo","scalar":true}`, - - ExpectedTwoWay: `{}`, - ExpectedTwoWayResult: `{"array":[1,2,3],"complex":{"nested":true},"name":"foo","scalar":true}`, - ExpectedThreeWay: `{}`, - ExpectedThreeWayResult: `{"array":[1,2,3],"complex":{"nested":true},"name":"foo","scalar":true}`, - }, - "added only": { - Original: `{"name":"foo"}`, - Current: `{"name":"foo"}`, - Modified: `{"name":"foo","scalar":true,"complex":{"nested":true},"array":[1,2,3]}`, - - ExpectedTwoWay: `{"array":[1,2,3],"complex":{"nested":true},"scalar":true}`, - ExpectedTwoWayResult: `{"array":[1,2,3],"complex":{"nested":true},"name":"foo","scalar":true}`, - ExpectedThreeWay: `{"array":[1,2,3],"complex":{"nested":true},"scalar":true}`, - ExpectedThreeWayResult: `{"array":[1,2,3],"complex":{"nested":true},"name":"foo","scalar":true}`, - }, - "removed only": { - Original: `{"name":"foo","scalar":true,"complex":{"nested":true}}`, - Current: `{"name":"foo","scalar":true,"complex":{"nested":true},"array":[1,2,3]}`, - Modified: `{"name":"foo"}`, - - ExpectedTwoWay: `{"complex":null,"scalar":null}`, - ExpectedTwoWayResult: `{"name":"foo"}`, - ExpectedThreeWay: `{"complex":null,"scalar":null}`, - ExpectedThreeWayResult: `{"array":[1,2,3],"name":"foo"}`, - }, - - // cases we cannot successfully strategically merge (expect errors) - "diff": { - Original: `{"array":[1,2,3],"complex":{"nested":true},"name":"foo","scalar":true}`, - Current: `{"array":[1,2,3],"complex":{"nested":true},"name":"foo","scalar":true}`, - Modified: `{"array":[1,2,3],"complex":{"nested":false},"name":"foo","scalar":true}`, - - ExpectedTwoWayErr: `unable to find api field`, - ExpectedThreeWayErr: `unable to find api field`, - }, - } - - mergeItemOpenapiSchema := PatchMetaFromOpenAPI{ - Schema: sptest.GetSchemaOrDie(fakeMergeItemSchema, "mergeItem"), - } - schemas := []LookupPatchMeta{ - mergeItemStructSchema, - mergeItemOpenapiSchema, - } - - for _, k := range sets.StringKeySet(testcases).List() { - tc := testcases[k] - for _, schema := range schemas { - func() { - twoWay, err := CreateTwoWayMergePatchUsingLookupPatchMeta([]byte(tc.Original), []byte(tc.Modified), schema) - if err != nil { - if len(tc.ExpectedTwoWayErr) == 0 { - t.Errorf("using %s in testcase %s: error making two-way patch: %v", getSchemaType(schema), k, err) - } - if !strings.Contains(err.Error(), tc.ExpectedTwoWayErr) { - t.Errorf("using %s in testcase %s: expected error making two-way patch to contain '%s', got %s", getSchemaType(schema), k, tc.ExpectedTwoWayErr, err) - } - return - } - - if string(twoWay) != tc.ExpectedTwoWay { - t.Errorf("using %s in testcase %s: expected two-way patch:\n\t%s\ngot\n\t%s", getSchemaType(schema), k, string(tc.ExpectedTwoWay), string(twoWay)) - return - } - - twoWayResult, err := StrategicMergePatchUsingLookupPatchMeta([]byte(tc.Original), twoWay, schema) - if err != nil { - t.Errorf("using %s in testcase %s: error applying two-way patch: %v", getSchemaType(schema), k, err) - return - } - if string(twoWayResult) != tc.ExpectedTwoWayResult { - t.Errorf("using %s in testcase %s: expected two-way result:\n\t%s\ngot\n\t%s", getSchemaType(schema), k, string(tc.ExpectedTwoWayResult), string(twoWayResult)) - return - } - }() - - func() { - threeWay, err := CreateThreeWayMergePatch([]byte(tc.Original), []byte(tc.Modified), []byte(tc.Current), schema, false) - if err != nil { - if len(tc.ExpectedThreeWayErr) == 0 { - t.Errorf("using %s in testcase %s: error making three-way patch: %v", getSchemaType(schema), k, err) - } else if !strings.Contains(err.Error(), tc.ExpectedThreeWayErr) { - t.Errorf("using %s in testcase %s: expected error making three-way patch to contain '%s', got %s", getSchemaType(schema), k, tc.ExpectedThreeWayErr, err) - } - return - } - - if string(threeWay) != tc.ExpectedThreeWay { - t.Errorf("using %s in testcase %s: expected three-way patch:\n\t%s\ngot\n\t%s", getSchemaType(schema), k, string(tc.ExpectedThreeWay), string(threeWay)) - return - } - - threeWayResult, err := StrategicMergePatch([]byte(tc.Current), threeWay, schema) - if err != nil { - t.Errorf("using %s in testcase %s: error applying three-way patch: %v", getSchemaType(schema), k, err) - return - } else if string(threeWayResult) != tc.ExpectedThreeWayResult { - t.Errorf("using %s in testcase %s: expected three-way result:\n\t%s\ngot\n\t%s", getSchemaType(schema), k, string(tc.ExpectedThreeWayResult), string(threeWayResult)) - return - } - }() - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/uuid/BUILD b/vendor/k8s.io/apimachinery/pkg/util/uuid/BUILD deleted file mode 100644 index 786d8fbe39..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/uuid/BUILD +++ /dev/null @@ -1,29 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = ["uuid.go"], - importpath = "k8s.io/apimachinery/pkg/util/uuid", - deps = [ - "//vendor/github.com/pborman/uuid:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/types:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/validation/BUILD b/vendor/k8s.io/apimachinery/pkg/util/validation/BUILD deleted file mode 100644 index db599cbb7a..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/validation/BUILD +++ /dev/null @@ -1,37 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["validation_test.go"], - embed = [":go_default_library"], - deps = ["//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["validation.go"], - importpath = "k8s.io/apimachinery/pkg/util/validation", - deps = ["//vendor/k8s.io/apimachinery/pkg/util/validation/field:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apimachinery/pkg/util/validation/field:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/validation/field/BUILD b/vendor/k8s.io/apimachinery/pkg/util/validation/field/BUILD deleted file mode 100644 index fc59dd81cd..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/validation/field/BUILD +++ /dev/null @@ -1,42 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "errors_test.go", - "path_test.go", - ], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "errors.go", - "path.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/validation/field", - deps = [ - "//vendor/k8s.io/apimachinery/pkg/util/errors:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors_test.go b/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors_test.go deleted file mode 100644 index fe747319bb..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/validation/field/errors_test.go +++ /dev/null @@ -1,175 +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 field - -import ( - "fmt" - "strings" - "testing" -) - -func TestMakeFuncs(t *testing.T) { - testCases := []struct { - fn func() *Error - expected ErrorType - }{ - { - func() *Error { return Invalid(NewPath("f"), "v", "d") }, - ErrorTypeInvalid, - }, - { - func() *Error { return NotSupported(NewPath("f"), "v", nil) }, - ErrorTypeNotSupported, - }, - { - func() *Error { return Duplicate(NewPath("f"), "v") }, - ErrorTypeDuplicate, - }, - { - func() *Error { return NotFound(NewPath("f"), "v") }, - ErrorTypeNotFound, - }, - { - func() *Error { return Required(NewPath("f"), "d") }, - ErrorTypeRequired, - }, - { - func() *Error { return InternalError(NewPath("f"), fmt.Errorf("e")) }, - ErrorTypeInternal, - }, - } - - for _, testCase := range testCases { - err := testCase.fn() - if err.Type != testCase.expected { - t.Errorf("expected Type %q, got %q", testCase.expected, err.Type) - } - } -} - -func TestErrorUsefulMessage(t *testing.T) { - { - s := Invalid(nil, nil, "").Error() - t.Logf("message: %v", s) - if !strings.Contains(s, "null") { - t.Errorf("error message did not contain 'null': %s", s) - } - } - - s := Invalid(NewPath("foo"), "bar", "deet").Error() - t.Logf("message: %v", s) - for _, part := range []string{"foo", "bar", "deet", ErrorTypeInvalid.String()} { - if !strings.Contains(s, part) { - t.Errorf("error message did not contain expected part '%v'", part) - } - } - - type complicated struct { - Baz int - Qux string - Inner interface{} - KV map[string]int - } - s = Invalid( - NewPath("foo"), - &complicated{ - Baz: 1, - Qux: "aoeu", - Inner: &complicated{Qux: "asdf"}, - KV: map[string]int{"Billy": 2}, - }, - "detail", - ).Error() - t.Logf("message: %v", s) - for _, part := range []string{ - "foo", ErrorTypeInvalid.String(), - "Baz", "Qux", "Inner", "KV", "detail", - "1", "aoeu", "Billy", "2", - // "asdf", TODO: re-enable once we have a better nested printer - } { - if !strings.Contains(s, part) { - t.Errorf("error message did not contain expected part '%v'", part) - } - } -} - -func TestToAggregate(t *testing.T) { - testCases := struct { - ErrList []ErrorList - NumExpectedErrs []int - }{ - []ErrorList{ - nil, - {}, - {Invalid(NewPath("f"), "v", "d")}, - {Invalid(NewPath("f"), "v", "d"), Invalid(NewPath("f"), "v", "d")}, - {Invalid(NewPath("f"), "v", "d"), InternalError(NewPath(""), fmt.Errorf("e"))}, - }, - []int{ - 0, - 0, - 1, - 1, - 2, - }, - } - - if len(testCases.ErrList) != len(testCases.NumExpectedErrs) { - t.Errorf("Mismatch: length of NumExpectedErrs does not match length of ErrList") - } - for i, tc := range testCases.ErrList { - agg := tc.ToAggregate() - numErrs := 0 - - if agg != nil { - numErrs = len(agg.Errors()) - } - if numErrs != testCases.NumExpectedErrs[i] { - t.Errorf("[%d] Expected %d, got %d", i, testCases.NumExpectedErrs[i], numErrs) - } - - if len(tc) == 0 { - if agg != nil { - t.Errorf("[%d] Expected nil, got %#v", i, agg) - } - } else if agg == nil { - t.Errorf("[%d] Expected non-nil", i) - } - } -} - -func TestErrListFilter(t *testing.T) { - list := ErrorList{ - Invalid(NewPath("test.field"), "", ""), - Invalid(NewPath("field.test"), "", ""), - Duplicate(NewPath("test"), "value"), - } - if len(list.Filter(NewErrorTypeMatcher(ErrorTypeDuplicate))) != 2 { - t.Errorf("should not filter") - } - if len(list.Filter(NewErrorTypeMatcher(ErrorTypeInvalid))) != 1 { - t.Errorf("should filter") - } -} - -func TestNotSupported(t *testing.T) { - notSupported := NotSupported(NewPath("f"), "v", []string{"a", "b", "c"}) - expected := `Unsupported value: "v": supported values: "a", "b", "c"` - if notSupported.ErrorBody() != expected { - t.Errorf("Expected: %s\n, but got: %s\n", expected, notSupported.ErrorBody()) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/validation/field/path_test.go b/vendor/k8s.io/apimachinery/pkg/util/validation/field/path_test.go deleted file mode 100644 index d2f568c36f..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/validation/field/path_test.go +++ /dev/null @@ -1,123 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package field - -import "testing" - -func TestPath(t *testing.T) { - testCases := []struct { - op func(*Path) *Path - expected string - }{ - { - func(p *Path) *Path { return p }, - "root", - }, - { - func(p *Path) *Path { return p.Child("first") }, - "root.first", - }, - { - func(p *Path) *Path { return p.Child("second") }, - "root.first.second", - }, - { - func(p *Path) *Path { return p.Index(0) }, - "root.first.second[0]", - }, - { - func(p *Path) *Path { return p.Child("third") }, - "root.first.second[0].third", - }, - { - func(p *Path) *Path { return p.Index(93) }, - "root.first.second[0].third[93]", - }, - { - func(p *Path) *Path { return p.parent }, - "root.first.second[0].third", - }, - { - func(p *Path) *Path { return p.parent }, - "root.first.second[0]", - }, - { - func(p *Path) *Path { return p.Key("key") }, - "root.first.second[0][key]", - }, - } - - root := NewPath("root") - p := root - for i, tc := range testCases { - p = tc.op(p) - if p.String() != tc.expected { - t.Errorf("[%d] Expected %q, got %q", i, tc.expected, p.String()) - } - if p.Root() != root { - t.Errorf("[%d] Wrong root: %#v", i, p.Root()) - } - } -} - -func TestPathMultiArg(t *testing.T) { - testCases := []struct { - op func(*Path) *Path - expected string - }{ - { - func(p *Path) *Path { return p }, - "root.first", - }, - { - func(p *Path) *Path { return p.Child("second", "third") }, - "root.first.second.third", - }, - { - func(p *Path) *Path { return p.Index(0) }, - "root.first.second.third[0]", - }, - { - func(p *Path) *Path { return p.parent }, - "root.first.second.third", - }, - { - func(p *Path) *Path { return p.parent }, - "root.first.second", - }, - { - func(p *Path) *Path { return p.parent }, - "root.first", - }, - { - func(p *Path) *Path { return p.parent }, - "root", - }, - } - - root := NewPath("root", "first") - p := root - for i, tc := range testCases { - p = tc.op(p) - if p.String() != tc.expected { - t.Errorf("[%d] Expected %q, got %q", i, tc.expected, p.String()) - } - if p.Root() != root.Root() { - t.Errorf("[%d] Wrong root: %#v", i, p.Root()) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/validation/validation_test.go b/vendor/k8s.io/apimachinery/pkg/util/validation/validation_test.go deleted file mode 100644 index 4c628bbc44..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/validation/validation_test.go +++ /dev/null @@ -1,513 +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 validation - -import ( - "strings" - "testing" - - "k8s.io/apimachinery/pkg/util/validation/field" -) - -func TestIsDNS1123Label(t *testing.T) { - goodValues := []string{ - "a", "ab", "abc", "a1", "a-1", "a--1--2--b", - "0", "01", "012", "1a", "1-a", "1--a--b--2", - strings.Repeat("a", 63), - } - for _, val := range goodValues { - if msgs := IsDNS1123Label(val); len(msgs) != 0 { - t.Errorf("expected true for '%s': %v", val, msgs) - } - } - - badValues := []string{ - "", "A", "ABC", "aBc", "A1", "A-1", "1-A", - "-", "a-", "-a", "1-", "-1", - "_", "a_", "_a", "a_b", "1_", "_1", "1_2", - ".", "a.", ".a", "a.b", "1.", ".1", "1.2", - " ", "a ", " a", "a b", "1 ", " 1", "1 2", - strings.Repeat("a", 64), - } - for _, val := range badValues { - if msgs := IsDNS1123Label(val); len(msgs) == 0 { - t.Errorf("expected false for '%s'", val) - } - } -} - -func TestIsDNS1123Subdomain(t *testing.T) { - goodValues := []string{ - "a", "ab", "abc", "a1", "a-1", "a--1--2--b", - "0", "01", "012", "1a", "1-a", "1--a--b--2", - "a.a", "ab.a", "abc.a", "a1.a", "a-1.a", "a--1--2--b.a", - "a.1", "ab.1", "abc.1", "a1.1", "a-1.1", "a--1--2--b.1", - "0.a", "01.a", "012.a", "1a.a", "1-a.a", "1--a--b--2", - "0.1", "01.1", "012.1", "1a.1", "1-a.1", "1--a--b--2.1", - "a.b.c.d.e", "aa.bb.cc.dd.ee", "1.2.3.4.5", "11.22.33.44.55", - strings.Repeat("a", 253), - } - for _, val := range goodValues { - if msgs := IsDNS1123Subdomain(val); len(msgs) != 0 { - t.Errorf("expected true for '%s': %v", val, msgs) - } - } - - badValues := []string{ - "", "A", "ABC", "aBc", "A1", "A-1", "1-A", - "-", "a-", "-a", "1-", "-1", - "_", "a_", "_a", "a_b", "1_", "_1", "1_2", - ".", "a.", ".a", "a..b", "1.", ".1", "1..2", - " ", "a ", " a", "a b", "1 ", " 1", "1 2", - "A.a", "aB.a", "ab.A", "A1.a", "a1.A", - "A.1", "aB.1", "A1.1", "1A.1", - "0.A", "01.A", "012.A", "1A.a", "1a.A", - "A.B.C.D.E", "AA.BB.CC.DD.EE", "a.B.c.d.e", "aa.bB.cc.dd.ee", - "a@b", "a,b", "a_b", "a;b", - "a:b", "a%b", "a?b", "a$b", - strings.Repeat("a", 254), - } - for _, val := range badValues { - if msgs := IsDNS1123Subdomain(val); len(msgs) == 0 { - t.Errorf("expected false for '%s'", val) - } - } -} - -func TestIsDNS1035Label(t *testing.T) { - goodValues := []string{ - "a", "ab", "abc", "a1", "a-1", "a--1--2--b", - strings.Repeat("a", 63), - } - for _, val := range goodValues { - if msgs := IsDNS1035Label(val); len(msgs) != 0 { - t.Errorf("expected true for '%s': %v", val, msgs) - } - } - - badValues := []string{ - "0", "01", "012", "1a", "1-a", "1--a--b--2", - "", "A", "ABC", "aBc", "A1", "A-1", "1-A", - "-", "a-", "-a", "1-", "-1", - "_", "a_", "_a", "a_b", "1_", "_1", "1_2", - ".", "a.", ".a", "a.b", "1.", ".1", "1.2", - " ", "a ", " a", "a b", "1 ", " 1", "1 2", - strings.Repeat("a", 64), - } - for _, val := range badValues { - if msgs := IsDNS1035Label(val); len(msgs) == 0 { - t.Errorf("expected false for '%s'", val) - } - } -} - -func TestIsCIdentifier(t *testing.T) { - goodValues := []string{ - "a", "ab", "abc", "a1", "_a", "a_", "a_b", "a_1", "a__1__2__b", "__abc_123", - "A", "AB", "AbC", "A1", "_A", "A_", "A_B", "A_1", "A__1__2__B", "__123_ABC", - } - for _, val := range goodValues { - if msgs := IsCIdentifier(val); len(msgs) != 0 { - t.Errorf("expected true for '%s': %v", val, msgs) - } - } - - badValues := []string{ - "", "1", "123", "1a", - "-", "a-", "-a", "1-", "-1", "1_", "1_2", - ".", "a.", ".a", "a.b", "1.", ".1", "1.2", - " ", "a ", " a", "a b", "1 ", " 1", "1 2", - "#a#", - } - for _, val := range badValues { - if msgs := IsCIdentifier(val); len(msgs) == 0 { - t.Errorf("expected false for '%s'", val) - } - } -} - -func TestIsValidPortNum(t *testing.T) { - goodValues := []int{1, 2, 1000, 16384, 32768, 65535} - for _, val := range goodValues { - if msgs := IsValidPortNum(val); len(msgs) != 0 { - t.Errorf("expected true for %d, got %v", val, msgs) - } - } - - badValues := []int{0, -1, 65536, 100000} - for _, val := range badValues { - if msgs := IsValidPortNum(val); len(msgs) == 0 { - t.Errorf("expected false for %d", val) - } - } -} - -func TestIsInRange(t *testing.T) { - goodValues := []struct { - value int - min int - max int - }{{1, 0, 10}, {5, 5, 20}, {25, 10, 25}} - for _, val := range goodValues { - if msgs := IsInRange(val.value, val.min, val.max); len(msgs) > 0 { - t.Errorf("expected no errors for %#v, but got %v", val, msgs) - } - } - - badValues := []struct { - value int - min int - max int - }{{1, 2, 10}, {5, -4, 2}, {25, 100, 120}} - for _, val := range badValues { - if msgs := IsInRange(val.value, val.min, val.max); len(msgs) == 0 { - t.Errorf("expected errors for %#v", val) - } - } -} - -func createGroupIDs(ids ...int64) []int64 { - var output []int64 - for _, id := range ids { - output = append(output, int64(id)) - } - return output -} - -func createUserIDs(ids ...int64) []int64 { - var output []int64 - for _, id := range ids { - output = append(output, int64(id)) - } - return output -} - -func TestIsValidGroupID(t *testing.T) { - goodValues := createGroupIDs(0, 1, 1000, 65535, 2147483647) - for _, val := range goodValues { - if msgs := IsValidGroupID(val); len(msgs) != 0 { - t.Errorf("expected true for '%d': %v", val, msgs) - } - } - - badValues := createGroupIDs(-1, -1003, 2147483648, 4147483647) - for _, val := range badValues { - if msgs := IsValidGroupID(val); len(msgs) == 0 { - t.Errorf("expected false for '%d'", val) - } - } -} - -func TestIsValidUserID(t *testing.T) { - goodValues := createUserIDs(0, 1, 1000, 65535, 2147483647) - for _, val := range goodValues { - if msgs := IsValidUserID(val); len(msgs) != 0 { - t.Errorf("expected true for '%d': %v", val, msgs) - } - } - - badValues := createUserIDs(-1, -1003, 2147483648, 4147483647) - for _, val := range badValues { - if msgs := IsValidUserID(val); len(msgs) == 0 { - t.Errorf("expected false for '%d'", val) - } - } -} - -func TestIsValidPortName(t *testing.T) { - goodValues := []string{"telnet", "re-mail-ck", "pop3", "a", "a-1", "1-a", "a-1-b-2-c", "1-a-2-b-3"} - for _, val := range goodValues { - if msgs := IsValidPortName(val); len(msgs) != 0 { - t.Errorf("expected true for %q: %v", val, msgs) - } - } - - badValues := []string{"longerthan15characters", "", strings.Repeat("a", 16), "12345", "1-2-3-4", "-begin", "end-", "two--hyphens", "whois++"} - for _, val := range badValues { - if msgs := IsValidPortName(val); len(msgs) == 0 { - t.Errorf("expected false for %q", val) - } - } -} - -func TestIsQualifiedName(t *testing.T) { - successCases := []string{ - "simple", - "now-with-dashes", - "1-starts-with-num", - "1234", - "simple/simple", - "now-with-dashes/simple", - "now-with-dashes/now-with-dashes", - "now.with.dots/simple", - "now-with.dashes-and.dots/simple", - "1-num.2-num/3-num", - "1234/5678", - "1.2.3.4/5678", - "Uppercase_Is_OK_123", - "example.com/Uppercase_Is_OK_123", - "requests.storage-foo", - strings.Repeat("a", 63), - strings.Repeat("a", 253) + "/" + strings.Repeat("b", 63), - } - for i := range successCases { - if errs := IsQualifiedName(successCases[i]); len(errs) != 0 { - t.Errorf("case[%d]: %q: expected success: %v", i, successCases[i], errs) - } - } - - errorCases := []string{ - "nospecialchars%^=@", - "cantendwithadash-", - "-cantstartwithadash-", - "only/one/slash", - "Example.com/abc", - "example_com/abc", - "example.com/", - "/simple", - strings.Repeat("a", 64), - strings.Repeat("a", 254) + "/abc", - } - for i := range errorCases { - if errs := IsQualifiedName(errorCases[i]); len(errs) == 0 { - t.Errorf("case[%d]: %q: expected failure", i, errorCases[i]) - } - } -} - -func TestIsValidLabelValue(t *testing.T) { - successCases := []string{ - "simple", - "now-with-dashes", - "1-starts-with-num", - "end-with-num-1", - "1234", // only num - strings.Repeat("a", 63), // to the limit - "", // empty value - } - for i := range successCases { - if errs := IsValidLabelValue(successCases[i]); len(errs) != 0 { - t.Errorf("case %s expected success: %v", successCases[i], errs) - } - } - - errorCases := []string{ - "nospecialchars%^=@", - "Tama-nui-te-rā.is.Māori.sun", - "\\backslashes\\are\\bad", - "-starts-with-dash", - "ends-with-dash-", - ".starts.with.dot", - "ends.with.dot.", - strings.Repeat("a", 64), // over the limit - } - for i := range errorCases { - if errs := IsValidLabelValue(errorCases[i]); len(errs) == 0 { - t.Errorf("case[%d] expected failure", i) - } - } -} - -func TestIsValidIP(t *testing.T) { - goodValues := []string{ - "::1", - "2a00:79e0:2:0:f1c3:e797:93c1:df80", - "::", - "2001:4860:4860::8888", - "::fff:1.1.1.1", - "1.1.1.1", - "1.1.1.01", - "255.0.0.1", - "1.0.0.0", - "0.0.0.0", - } - for _, val := range goodValues { - if msgs := IsValidIP(val); len(msgs) != 0 { - t.Errorf("expected true for %q: %v", val, msgs) - } - } - - badValues := []string{ - "[2001:db8:0:1]:80", - "myhost.mydomain", - "-1.0.0.0", - "[2001:db8:0:1]", - "a", - } - for _, val := range badValues { - if msgs := IsValidIP(val); len(msgs) == 0 { - t.Errorf("expected false for %q", val) - } - } -} - -func TestIsHTTPHeaderName(t *testing.T) { - goodValues := []string{ - // Common ones - "Accept-Encoding", "Host", "If-Modified-Since", "X-Forwarded-For", - // Weirdo, but still conforming names - "a", "ab", "abc", "a1", "-a", "a-", "a-b", "a-1", "a--1--2--b", "--abc-123", - "A", "AB", "AbC", "A1", "-A", "A-", "A-B", "A-1", "A--1--2--B", "--123-ABC", - } - for _, val := range goodValues { - if msgs := IsHTTPHeaderName(val); len(msgs) != 0 { - t.Errorf("expected true for '%s': %v", val, msgs) - } - } - - badValues := []string{ - "Host:", "X-Forwarded-For:", "X-@Home", - "", "_", "a_", "_a", "1_", "1_2", ".", "a.", ".a", "a.b", "1.", ".1", "1.2", - " ", "a ", " a", "a b", "1 ", " 1", "1 2", "#a#", "^", ",", ";", "=", "<", - "?", "@", "{", - } - for _, val := range badValues { - if msgs := IsHTTPHeaderName(val); len(msgs) == 0 { - t.Errorf("expected false for '%s'", val) - } - } -} - -func TestIsValidPercent(t *testing.T) { - goodValues := []string{ - "0%", - "00000%", - "1%", - "01%", - "99%", - "100%", - "101%", - } - for _, val := range goodValues { - if msgs := IsValidPercent(val); len(msgs) != 0 { - t.Errorf("expected true for %q: %v", val, msgs) - } - } - - badValues := []string{ - "", - "0", - "100", - "0.0%", - "99.9%", - "hundred", - " 1%", - "1% ", - "-0%", - "-1%", - "+1%", - } - for _, val := range badValues { - if msgs := IsValidPercent(val); len(msgs) == 0 { - t.Errorf("expected false for %q", val) - } - } -} - -func TestIsConfigMapKey(t *testing.T) { - successCases := []string{ - "a", - "good", - "good-good", - "still.good", - "this.is.also.good", - ".so.is.this", - "THIS_IS_GOOD", - "so_is_this_17", - } - - for i := range successCases { - if errs := IsConfigMapKey(successCases[i]); len(errs) != 0 { - t.Errorf("[%d] expected success: %v", i, errs) - } - } - - failureCases := []string{ - ".", - "..", - "..bad", - "b*d", - "bad!&bad", - } - - for i := range failureCases { - if errs := IsConfigMapKey(failureCases[i]); len(errs) == 0 { - t.Errorf("[%d] expected failure", i) - } - } -} - -func TestIsWildcardDNS1123Subdomain(t *testing.T) { - goodValues := []string{ - "*.example.com", - "*.bar.com", - "*.foo.bar.com", - } - for _, val := range goodValues { - if errs := IsWildcardDNS1123Subdomain(val); len(errs) != 0 { - t.Errorf("expected no errors for %q: %v", val, errs) - } - } - - badValues := []string{ - "*.*.bar.com", - "*.foo.*.com", - "*bar.com", - "f*.bar.com", - "*", - } - for _, val := range badValues { - if errs := IsWildcardDNS1123Subdomain(val); len(errs) == 0 { - t.Errorf("expected errors for %q", val) - } - } -} - -func TestIsFullyQualifiedName(t *testing.T) { - tests := []struct { - name string - targetName string - err string - }{ - { - name: "name needs to be fully qualified, i.e., contains at least 2 dots", - targetName: "k8s.io", - err: "should be a domain with at least three segments separated by dots", - }, - { - name: "name cannot be empty", - targetName: "", - err: "Required value", - }, - { - name: "name must conform to RFC 1123", - targetName: "A.B.C", - err: "a DNS-1123 subdomain must consist of lower case alphanumeric characters", - }, - } - for _, tc := range tests { - err := IsFullyQualifiedName(field.NewPath(""), tc.targetName).ToAggregate() - switch { - case tc.err == "" && err != nil: - t.Errorf("%q: unexpected error: %v", tc.name, err) - case tc.err != "" && err == nil: - t.Errorf("%q: unexpected no error, expected %s", tc.name, tc.err) - case tc.err != "" && err != nil && !strings.Contains(err.Error(), tc.err): - t.Errorf("%q: expected %s, got %v", tc.name, tc.err, err) - } - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/wait/BUILD b/vendor/k8s.io/apimachinery/pkg/util/wait/BUILD deleted file mode 100644 index c062f3818d..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/wait/BUILD +++ /dev/null @@ -1,37 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["wait_test.go"], - embed = [":go_default_library"], - deps = ["//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "wait.go", - ], - importpath = "k8s.io/apimachinery/pkg/util/wait", - deps = ["//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/wait/wait_test.go b/vendor/k8s.io/apimachinery/pkg/util/wait/wait_test.go deleted file mode 100644 index 2dfd287775..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/wait/wait_test.go +++ /dev/null @@ -1,501 +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 - -import ( - "errors" - "fmt" - "sync" - "sync/atomic" - "testing" - "time" - - "k8s.io/apimachinery/pkg/util/runtime" -) - -func TestUntil(t *testing.T) { - ch := make(chan struct{}) - close(ch) - Until(func() { - t.Fatal("should not have been invoked") - }, 0, ch) - - ch = make(chan struct{}) - called := make(chan struct{}) - go func() { - Until(func() { - called <- struct{}{} - }, 0, ch) - close(called) - }() - <-called - close(ch) - <-called -} - -func TestNonSlidingUntil(t *testing.T) { - ch := make(chan struct{}) - close(ch) - NonSlidingUntil(func() { - t.Fatal("should not have been invoked") - }, 0, ch) - - ch = make(chan struct{}) - called := make(chan struct{}) - go func() { - NonSlidingUntil(func() { - called <- struct{}{} - }, 0, ch) - close(called) - }() - <-called - close(ch) - <-called -} - -func TestUntilReturnsImmediately(t *testing.T) { - now := time.Now() - ch := make(chan struct{}) - Until(func() { - close(ch) - }, 30*time.Second, ch) - if now.Add(25 * time.Second).Before(time.Now()) { - t.Errorf("Until did not return immediately when the stop chan was closed inside the func") - } -} - -func TestJitterUntil(t *testing.T) { - ch := make(chan struct{}) - // if a channel is closed JitterUntil never calls function f - // and returns immediately - close(ch) - JitterUntil(func() { - t.Fatal("should not have been invoked") - }, 0, 1.0, true, ch) - - ch = make(chan struct{}) - called := make(chan struct{}) - go func() { - JitterUntil(func() { - called <- struct{}{} - }, 0, 1.0, true, ch) - close(called) - }() - <-called - close(ch) - <-called -} - -func TestJitterUntilReturnsImmediately(t *testing.T) { - now := time.Now() - ch := make(chan struct{}) - JitterUntil(func() { - close(ch) - }, 30*time.Second, 1.0, true, ch) - if now.Add(25 * time.Second).Before(time.Now()) { - t.Errorf("JitterUntil did not return immediately when the stop chan was closed inside the func") - } -} - -func TestJitterUntilRecoversPanic(t *testing.T) { - // Save and restore crash handlers - originalReallyCrash := runtime.ReallyCrash - originalHandlers := runtime.PanicHandlers - defer func() { - runtime.ReallyCrash = originalReallyCrash - runtime.PanicHandlers = originalHandlers - }() - - called := 0 - handled := 0 - - // Hook up a custom crash handler to ensure it is called when a jitter function panics - runtime.ReallyCrash = false - runtime.PanicHandlers = []func(interface{}){ - func(p interface{}) { - handled++ - }, - } - - ch := make(chan struct{}) - JitterUntil(func() { - called++ - if called > 2 { - close(ch) - return - } - panic("TestJitterUntilRecoversPanic") - }, time.Millisecond, 1.0, true, ch) - - if called != 3 { - t.Errorf("Expected panic recovers") - } -} - -func TestJitterUntilNegativeFactor(t *testing.T) { - now := time.Now() - ch := make(chan struct{}) - called := make(chan struct{}) - received := make(chan struct{}) - go func() { - JitterUntil(func() { - called <- struct{}{} - <-received - }, time.Second, -30.0, true, ch) - }() - // first loop - <-called - received <- struct{}{} - // second loop - <-called - close(ch) - received <- struct{}{} - - // it should take at most 2 seconds + some overhead, not 3 - if now.Add(3 * time.Second).Before(time.Now()) { - t.Errorf("JitterUntil did not returned after predefined period with negative jitter factor when the stop chan was closed inside the func") - } - -} - -func TestExponentialBackoff(t *testing.T) { - opts := Backoff{Factor: 1.0, Steps: 3} - - // waits up to steps - i := 0 - err := ExponentialBackoff(opts, func() (bool, error) { - i++ - return false, nil - }) - if err != ErrWaitTimeout || i != opts.Steps { - t.Errorf("unexpected error: %v", err) - } - - // returns immediately - i = 0 - err = ExponentialBackoff(opts, func() (bool, error) { - i++ - return true, nil - }) - if err != nil || i != 1 { - t.Errorf("unexpected error: %v", err) - } - - // returns immediately on error - testErr := fmt.Errorf("some other error") - err = ExponentialBackoff(opts, func() (bool, error) { - return false, testErr - }) - if err != testErr { - t.Errorf("unexpected error: %v", err) - } - - // invoked multiple times - i = 1 - err = ExponentialBackoff(opts, func() (bool, error) { - if i < opts.Steps { - i++ - return false, nil - } - return true, nil - }) - if err != nil || i != opts.Steps { - t.Errorf("unexpected error: %v", err) - } -} - -func TestPoller(t *testing.T) { - done := make(chan struct{}) - defer close(done) - w := poller(time.Millisecond, 2*time.Millisecond) - ch := w(done) - count := 0 -DRAIN: - for { - select { - case _, open := <-ch: - if !open { - break DRAIN - } - count++ - case <-time.After(ForeverTestTimeout): - t.Errorf("unexpected timeout after poll") - } - } - if count > 3 { - t.Errorf("expected up to three values, got %d", count) - } -} - -type fakePoller struct { - max int - used int32 // accessed with atomics - wg sync.WaitGroup -} - -func fakeTicker(max int, used *int32, doneFunc func()) WaitFunc { - return func(done <-chan struct{}) <-chan struct{} { - ch := make(chan struct{}) - go func() { - defer doneFunc() - defer close(ch) - for i := 0; i < max; i++ { - select { - case ch <- struct{}{}: - case <-done: - return - } - if used != nil { - atomic.AddInt32(used, 1) - } - } - }() - return ch - } -} - -func (fp *fakePoller) GetWaitFunc() WaitFunc { - fp.wg.Add(1) - return fakeTicker(fp.max, &fp.used, fp.wg.Done) -} - -func TestPoll(t *testing.T) { - invocations := 0 - f := ConditionFunc(func() (bool, error) { - invocations++ - return true, nil - }) - fp := fakePoller{max: 1} - if err := pollInternal(fp.GetWaitFunc(), f); err != nil { - t.Fatalf("unexpected error %v", err) - } - fp.wg.Wait() - if invocations != 1 { - t.Errorf("Expected exactly one invocation, got %d", invocations) - } - used := atomic.LoadInt32(&fp.used) - if used != 1 { - t.Errorf("Expected exactly one tick, got %d", used) - } -} - -func TestPollError(t *testing.T) { - expectedError := errors.New("Expected error") - f := ConditionFunc(func() (bool, error) { - return false, expectedError - }) - fp := fakePoller{max: 1} - if err := pollInternal(fp.GetWaitFunc(), f); err == nil || err != expectedError { - t.Fatalf("Expected error %v, got none %v", expectedError, err) - } - fp.wg.Wait() - used := atomic.LoadInt32(&fp.used) - if used != 1 { - t.Errorf("Expected exactly one tick, got %d", used) - } -} - -func TestPollImmediate(t *testing.T) { - invocations := 0 - f := ConditionFunc(func() (bool, error) { - invocations++ - return true, nil - }) - fp := fakePoller{max: 0} - if err := pollImmediateInternal(fp.GetWaitFunc(), f); err != nil { - t.Fatalf("unexpected error %v", err) - } - // We don't need to wait for fp.wg, as pollImmediate shouldn't call WaitFunc at all. - if invocations != 1 { - t.Errorf("Expected exactly one invocation, got %d", invocations) - } - used := atomic.LoadInt32(&fp.used) - if used != 0 { - t.Errorf("Expected exactly zero ticks, got %d", used) - } -} - -func TestPollImmediateError(t *testing.T) { - expectedError := errors.New("Expected error") - f := ConditionFunc(func() (bool, error) { - return false, expectedError - }) - fp := fakePoller{max: 0} - if err := pollImmediateInternal(fp.GetWaitFunc(), f); err == nil || err != expectedError { - t.Fatalf("Expected error %v, got none %v", expectedError, err) - } - // We don't need to wait for fp.wg, as pollImmediate shouldn't call WaitFunc at all. - used := atomic.LoadInt32(&fp.used) - if used != 0 { - t.Errorf("Expected exactly zero ticks, got %d", used) - } -} - -func TestPollForever(t *testing.T) { - ch := make(chan struct{}) - done := make(chan struct{}, 1) - complete := make(chan struct{}) - go func() { - f := ConditionFunc(func() (bool, error) { - ch <- struct{}{} - select { - case <-done: - return true, nil - default: - } - return false, nil - }) - - if err := PollInfinite(time.Microsecond, f); err != nil { - t.Fatalf("unexpected error %v", err) - } - - close(ch) - complete <- struct{}{} - }() - - // ensure the condition is opened - <-ch - - // ensure channel sends events - for i := 0; i < 10; i++ { - select { - case _, open := <-ch: - if !open { - t.Fatalf("did not expect channel to be closed") - } - case <-time.After(ForeverTestTimeout): - t.Fatalf("channel did not return at least once within the poll interval") - } - } - - // at most one poll notification should be sent once we return from the condition - done <- struct{}{} - go func() { - for i := 0; i < 2; i++ { - _, open := <-ch - if !open { - return - } - } - t.Fatalf("expected closed channel after two iterations") - }() - <-complete -} - -func TestWaitFor(t *testing.T) { - var invocations int - testCases := map[string]struct { - F ConditionFunc - Ticks int - Invoked int - Err bool - }{ - "invoked once": { - ConditionFunc(func() (bool, error) { - invocations++ - return true, nil - }), - 2, - 1, - false, - }, - "invoked and returns a timeout": { - ConditionFunc(func() (bool, error) { - invocations++ - return false, nil - }), - 2, - 3, // the contract of WaitFor() says the func is called once more at the end of the wait - true, - }, - "returns immediately on error": { - ConditionFunc(func() (bool, error) { - invocations++ - return false, errors.New("test") - }), - 2, - 1, - true, - }, - } - for k, c := range testCases { - invocations = 0 - ticker := fakeTicker(c.Ticks, nil, func() {}) - err := func() error { - done := make(chan struct{}) - defer close(done) - return WaitFor(ticker, c.F, done) - }() - switch { - case c.Err && err == nil: - t.Errorf("%s: Expected error, got nil", k) - continue - case !c.Err && err != nil: - t.Errorf("%s: Expected no error, got: %#v", k, err) - continue - } - if invocations != c.Invoked { - t.Errorf("%s: Expected %d invocations, got %d", k, c.Invoked, invocations) - } - } -} - -func TestWaitForWithDelay(t *testing.T) { - done := make(chan struct{}) - defer close(done) - WaitFor(poller(time.Millisecond, ForeverTestTimeout), func() (bool, error) { - time.Sleep(10 * time.Millisecond) - return true, nil - }, done) - // If polling goroutine doesn't see the done signal it will leak timers. - select { - case done <- struct{}{}: - case <-time.After(ForeverTestTimeout): - t.Errorf("expected an ack of the done signal.") - } -} - -func TestPollUntil(t *testing.T) { - stopCh := make(chan struct{}) - called := make(chan bool) - pollDone := make(chan struct{}) - - go func() { - PollUntil(time.Microsecond, ConditionFunc(func() (bool, error) { - called <- true - return false, nil - }), stopCh) - - close(pollDone) - }() - - // make sure we're called once - <-called - // this should trigger a "done" - close(stopCh) - - go func() { - // release the condition func if needed - for { - <-called - } - }() - - // make sure we finished the poll - <-pollDone -} diff --git a/vendor/k8s.io/apimachinery/pkg/util/yaml/BUILD b/vendor/k8s.io/apimachinery/pkg/util/yaml/BUILD deleted file mode 100644 index 596ea292a9..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/yaml/BUILD +++ /dev/null @@ -1,36 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["decoder_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["decoder.go"], - importpath = "k8s.io/apimachinery/pkg/util/yaml", - deps = [ - "//vendor/github.com/ghodss/yaml:go_default_library", - "//vendor/github.com/golang/glog:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder_test.go b/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder_test.go deleted file mode 100644 index 03e502ec69..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/util/yaml/decoder_test.go +++ /dev/null @@ -1,405 +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 yaml - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "math/rand" - "reflect" - "strings" - "testing" -) - -func TestYAMLDecoderReadBytesLength(t *testing.T) { - d := `--- -stuff: 1 - test-foo: 1 -` - testCases := []struct { - bufLen int - expectLen int - expectErr error - }{ - {len(d), len(d), nil}, - {len(d) + 10, len(d), nil}, - {len(d) - 10, len(d) - 10, io.ErrShortBuffer}, - } - - for i, testCase := range testCases { - r := NewDocumentDecoder(ioutil.NopCloser(bytes.NewReader([]byte(d)))) - b := make([]byte, testCase.bufLen) - n, err := r.Read(b) - if err != testCase.expectErr || n != testCase.expectLen { - t.Fatalf("%d: unexpected body: %d / %v", i, n, err) - } - } -} - -func TestYAMLDecoderCallsAfterErrShortBufferRestOfFrame(t *testing.T) { - d := `--- -stuff: 1 - test-foo: 1` - r := NewDocumentDecoder(ioutil.NopCloser(bytes.NewReader([]byte(d)))) - b := make([]byte, 12) - n, err := r.Read(b) - if err != io.ErrShortBuffer || n != 12 { - t.Fatalf("expected ErrShortBuffer: %d / %v", n, err) - } - expected := "---\nstuff: 1" - if string(b) != expected { - t.Fatalf("expected bytes read to be: %s got: %s", expected, string(b)) - } - b = make([]byte, 13) - n, err = r.Read(b) - if err != nil || n != 13 { - t.Fatalf("expected nil: %d / %v", n, err) - } - expected = "\n\ttest-foo: 1" - if string(b) != expected { - t.Fatalf("expected bytes read to be: '%s' got: '%s'", expected, string(b)) - } - b = make([]byte, 15) - n, err = r.Read(b) - if err != io.EOF || n != 0 { - t.Fatalf("expected EOF: %d / %v", n, err) - } -} - -func TestSplitYAMLDocument(t *testing.T) { - testCases := []struct { - input string - atEOF bool - expect string - adv int - }{ - {"foo", true, "foo", 3}, - {"fo", false, "", 0}, - - {"---", true, "---", 3}, - {"---\n", true, "---\n", 4}, - {"---\n", false, "", 0}, - - {"\n---\n", false, "", 5}, - {"\n---\n", true, "", 5}, - - {"abc\n---\ndef", true, "abc", 8}, - {"def", true, "def", 3}, - {"", true, "", 0}, - } - for i, testCase := range testCases { - adv, token, err := splitYAMLDocument([]byte(testCase.input), testCase.atEOF) - if err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - continue - } - if adv != testCase.adv { - t.Errorf("%d: advance did not match: %d %d", i, testCase.adv, adv) - } - if testCase.expect != string(token) { - t.Errorf("%d: token did not match: %q %q", i, testCase.expect, string(token)) - } - } -} - -func TestGuessJSON(t *testing.T) { - if r, _, isJSON := GuessJSONStream(bytes.NewReader([]byte(" \n{}")), 100); !isJSON { - t.Fatalf("expected stream to be JSON") - } else { - b := make([]byte, 30) - n, err := r.Read(b) - if err != nil || n != 4 { - t.Fatalf("unexpected body: %d / %v", n, err) - } - if string(b[:n]) != " \n{}" { - t.Fatalf("unexpected body: %q", string(b[:n])) - } - } -} - -func TestScanYAML(t *testing.T) { - s := bufio.NewScanner(bytes.NewReader([]byte(`--- -stuff: 1 - ---- - `))) - s.Split(splitYAMLDocument) - if !s.Scan() { - t.Fatalf("should have been able to scan") - } - t.Logf("scan: %s", s.Text()) - if !s.Scan() { - t.Fatalf("should have been able to scan") - } - t.Logf("scan: %s", s.Text()) - if s.Scan() { - t.Fatalf("scan should have been done") - } - if s.Err() != nil { - t.Fatalf("err should have been nil: %v", s.Err()) - } -} - -func TestDecodeYAML(t *testing.T) { - s := NewYAMLToJSONDecoder(bytes.NewReader([]byte(`--- -stuff: 1 - ---- - `))) - obj := generic{} - if err := s.Decode(&obj); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if fmt.Sprintf("%#v", obj) != `yaml.generic{"stuff":1}` { - t.Errorf("unexpected object: %#v", obj) - } - obj = generic{} - if err := s.Decode(&obj); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if len(obj) != 0 { - t.Fatalf("unexpected object: %#v", obj) - } - obj = generic{} - if err := s.Decode(&obj); err != io.EOF { - t.Fatalf("unexpected error: %v", err) - } -} - -func TestDecodeBrokenYAML(t *testing.T) { - s := NewYAMLOrJSONDecoder(bytes.NewReader([]byte(`--- -stuff: 1 - test-foo: 1 - ---- - `)), 100) - obj := generic{} - err := s.Decode(&obj) - if err == nil { - t.Fatal("expected error with yaml: violate, got no error") - } - fmt.Printf("err: %s\n", err.Error()) - if !strings.Contains(err.Error(), "yaml: line 2:") { - t.Fatalf("expected %q to have 'yaml: line 2:' found a tab character", err.Error()) - } -} - -func TestDecodeBrokenJSON(t *testing.T) { - s := NewYAMLOrJSONDecoder(bytes.NewReader([]byte(`{ - "foo": { - "stuff": 1 - "otherStuff": 2 - } -} - `)), 100) - obj := generic{} - err := s.Decode(&obj) - if err == nil { - t.Fatal("expected error with json: prefix, got no error") - } - if !strings.HasPrefix(err.Error(), "json: line 3:") { - t.Fatalf("expected %q to have 'json: line 3:' prefix", err.Error()) - } -} - -type generic map[string]interface{} - -func TestYAMLOrJSONDecoder(t *testing.T) { - testCases := []struct { - input string - buffer int - isJSON bool - err bool - out []generic - }{ - {` {"1":2}{"3":4}`, 2, true, false, []generic{ - {"1": 2}, - {"3": 4}, - }}, - {" \n{}", 3, true, false, []generic{ - {}, - }}, - {" \na: b", 2, false, false, []generic{ - {"a": "b"}, - }}, - {" \n{\"a\": \"b\"}", 2, false, true, []generic{ - {"a": "b"}, - }}, - {" \n{\"a\": \"b\"}", 3, true, false, []generic{ - {"a": "b"}, - }}, - {` {"a":"b"}`, 100, true, false, []generic{ - {"a": "b"}, - }}, - {"", 1, false, false, []generic{}}, - {"foo: bar\n---\nbaz: biz", 100, false, false, []generic{ - {"foo": "bar"}, - {"baz": "biz"}, - }}, - {"foo: bar\n---\n", 100, false, false, []generic{ - {"foo": "bar"}, - }}, - {"foo: bar\n---", 100, false, false, []generic{ - {"foo": "bar"}, - }}, - {"foo: bar\n--", 100, false, true, []generic{ - {"foo": "bar"}, - }}, - {"foo: bar\n-", 100, false, true, []generic{ - {"foo": "bar"}, - }}, - {"foo: bar\n", 100, false, false, []generic{ - {"foo": "bar"}, - }}, - } - for i, testCase := range testCases { - decoder := NewYAMLOrJSONDecoder(bytes.NewReader([]byte(testCase.input)), testCase.buffer) - objs := []generic{} - - var err error - for { - out := make(generic) - err = decoder.Decode(&out) - if err != nil { - break - } - objs = append(objs, out) - } - if err != io.EOF { - switch { - case testCase.err && err == nil: - t.Errorf("%d: unexpected non-error", i) - continue - case !testCase.err && err != nil: - t.Errorf("%d: unexpected error: %v", i, err) - continue - case err != nil: - continue - } - } - switch decoder.decoder.(type) { - case *YAMLToJSONDecoder: - if testCase.isJSON { - t.Errorf("%d: expected JSON decoder, got YAML", i) - } - case *json.Decoder: - if !testCase.isJSON { - t.Errorf("%d: expected YAML decoder, got JSON", i) - } - } - if fmt.Sprintf("%#v", testCase.out) != fmt.Sprintf("%#v", objs) { - t.Errorf("%d: objects were not equal: \n%#v\n%#v", i, testCase.out, objs) - } - } -} - -func TestReadSingleLongLine(t *testing.T) { - testReadLines(t, []int{128 * 1024}) -} - -func TestReadRandomLineLengths(t *testing.T) { - minLength := 100 - maxLength := 96 * 1024 - maxLines := 100 - - lineLengths := make([]int, maxLines) - for i := 0; i < maxLines; i++ { - lineLengths[i] = rand.Intn(maxLength-minLength) + minLength - } - - testReadLines(t, lineLengths) -} - -func testReadLines(t *testing.T, lineLengths []int) { - var ( - lines [][]byte - inputStream []byte - ) - for _, lineLength := range lineLengths { - inputLine := make([]byte, lineLength+1) - for i := 0; i < lineLength; i++ { - char := rand.Intn('z'-'A') + 'A' - inputLine[i] = byte(char) - } - inputLine[len(inputLine)-1] = '\n' - lines = append(lines, inputLine) - } - for _, line := range lines { - inputStream = append(inputStream, line...) - } - - // init Reader - reader := bufio.NewReader(bytes.NewReader(inputStream)) - lineReader := &LineReader{reader: reader} - - // read lines - var readLines [][]byte - for range lines { - bytes, err := lineReader.Read() - if err != nil && err != io.EOF { - t.Fatalf("failed to read lines: %v", err) - } - readLines = append(readLines, bytes) - } - - // validate - for i := range lines { - if len(lines[i]) != len(readLines[i]) { - t.Fatalf("expected line length: %d, but got %d", len(lines[i]), len(readLines[i])) - } - if !reflect.DeepEqual(lines[i], readLines[i]) { - t.Fatalf("expected line: %v, but got %v", lines[i], readLines[i]) - } - } -} - -func TestTypedJSONOrYamlErrors(t *testing.T) { - s := NewYAMLOrJSONDecoder(bytes.NewReader([]byte(`{ - "foo": { - "stuff": 1 - "otherStuff": 2 - } -} - `)), 100) - obj := generic{} - err := s.Decode(&obj) - if err == nil { - t.Fatal("expected error with json: prefix, got no error") - } - if _, ok := err.(JSONSyntaxError); !ok { - t.Fatalf("expected %q to be of type JSONSyntaxError", err.Error()) - } - - s = NewYAMLOrJSONDecoder(bytes.NewReader([]byte(`--- -stuff: 1 - test-foo: 1 - ---- - `)), 100) - obj = generic{} - err = s.Decode(&obj) - if err == nil { - t.Fatal("expected error with yaml: prefix, got no error") - } - if _, ok := err.(YAMLSyntaxError); !ok { - t.Fatalf("expected %q to be of type YAMLSyntaxError", err.Error()) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/version/BUILD b/vendor/k8s.io/apimachinery/pkg/version/BUILD deleted file mode 100644 index bdccf7b3a7..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/version/BUILD +++ /dev/null @@ -1,28 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "types.go", - ], - importpath = "k8s.io/apimachinery/pkg/version", -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/watch/BUILD b/vendor/k8s.io/apimachinery/pkg/watch/BUILD deleted file mode 100644 index 3106af8f1f..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/watch/BUILD +++ /dev/null @@ -1,69 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "filter.go", - "mux.go", - "streamwatcher.go", - "until.go", - "watch.go", - "zz_generated.deepcopy.go", - ], - importpath = "k8s.io/apimachinery/pkg/watch", - deps = [ - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/net:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library", - ], -) - -go_test( - name = "go_default_xtest", - srcs = [ - "filter_test.go", - "mux_test.go", - "streamwatcher_test.go", - "watch_test.go", - ], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/watch:go_default_library", - ], -) - -go_test( - name = "go_default_test", - srcs = ["until_test.go"], - embed = [":go_default_library"], - deps = [ - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/pkg/watch/filter_test.go b/vendor/k8s.io/apimachinery/pkg/watch/filter_test.go deleted file mode 100644 index 4b5ae898ac..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/watch/filter_test.go +++ /dev/null @@ -1,84 +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 watch_test - -import ( - "reflect" - "testing" - - . "k8s.io/apimachinery/pkg/watch" -) - -func TestFilter(t *testing.T) { - table := []Event{ - {Type: Added, Object: testType("foo")}, - {Type: Added, Object: testType("bar")}, - {Type: Added, Object: testType("baz")}, - {Type: Added, Object: testType("qux")}, - {Type: Added, Object: testType("zoo")}, - } - - source := NewFake() - filtered := Filter(source, func(e Event) (Event, bool) { - return e, e.Object.(testType)[0] != 'b' - }) - - go func() { - for _, item := range table { - source.Action(item.Type, item.Object) - } - source.Stop() - }() - - var got []string - for { - event, ok := <-filtered.ResultChan() - if !ok { - break - } - got = append(got, string(event.Object.(testType))) - } - - if e, a := []string{"foo", "qux", "zoo"}, got; !reflect.DeepEqual(e, a) { - t.Errorf("got %v, wanted %v", e, a) - } -} - -func TestFilterStop(t *testing.T) { - source := NewFake() - filtered := Filter(source, func(e Event) (Event, bool) { - return e, e.Object.(testType)[0] != 'b' - }) - - go func() { - source.Add(testType("foo")) - filtered.Stop() - }() - - var got []string - for { - event, ok := <-filtered.ResultChan() - if !ok { - break - } - got = append(got, string(event.Object.(testType))) - } - - if e, a := []string{"foo"}, got; !reflect.DeepEqual(e, a) { - t.Errorf("got %v, wanted %v", e, a) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/watch/mux_test.go b/vendor/k8s.io/apimachinery/pkg/watch/mux_test.go deleted file mode 100644 index 7029cf1f4b..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/watch/mux_test.go +++ /dev/null @@ -1,176 +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 watch_test - -import ( - "reflect" - "sync" - "testing" - "time" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/wait" - . "k8s.io/apimachinery/pkg/watch" -) - -type myType struct { - ID string - Value string -} - -func (obj *myType) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } -func (obj *myType) DeepCopyObject() runtime.Object { - if obj == nil { - return nil - } - clone := *obj - return &clone -} - -func TestBroadcaster(t *testing.T) { - table := []Event{ - {Type: Added, Object: &myType{"foo", "hello world 1"}}, - {Type: Added, Object: &myType{"bar", "hello world 2"}}, - {Type: Modified, Object: &myType{"foo", "goodbye world 3"}}, - {Type: Deleted, Object: &myType{"bar", "hello world 4"}}, - } - - // The broadcaster we're testing - m := NewBroadcaster(0, WaitIfChannelFull) - - // Add a bunch of watchers - const testWatchers = 2 - wg := sync.WaitGroup{} - wg.Add(testWatchers) - for i := 0; i < testWatchers; i++ { - // Verify that each watcher gets the events in the correct order - go func(watcher int, w Interface) { - tableLine := 0 - for { - event, ok := <-w.ResultChan() - if !ok { - break - } - if e, a := table[tableLine], event; !reflect.DeepEqual(e, a) { - t.Errorf("Watcher %v, line %v: Expected (%v, %#v), got (%v, %#v)", - watcher, tableLine, e.Type, e.Object, a.Type, a.Object) - } else { - t.Logf("Got (%v, %#v)", event.Type, event.Object) - } - tableLine++ - } - wg.Done() - }(i, m.Watch()) - } - - for i, item := range table { - t.Logf("Sending %v", i) - m.Action(item.Type, item.Object) - } - - m.Shutdown() - - wg.Wait() -} - -func TestBroadcasterWatcherClose(t *testing.T) { - m := NewBroadcaster(0, WaitIfChannelFull) - w := m.Watch() - w2 := m.Watch() - w.Stop() - m.Shutdown() - if _, open := <-w.ResultChan(); open { - t.Errorf("Stop didn't work?") - } - if _, open := <-w2.ResultChan(); open { - t.Errorf("Shutdown didn't work?") - } - // Extra stops don't hurt things - w.Stop() - w2.Stop() -} - -func TestBroadcasterWatcherStopDeadlock(t *testing.T) { - done := make(chan bool) - m := NewBroadcaster(0, WaitIfChannelFull) - go func(w0, w1 Interface) { - // We know Broadcaster is in the distribute loop once one watcher receives - // an event. Stop the other watcher while distribute is trying to - // send to it. - select { - case <-w0.ResultChan(): - w1.Stop() - case <-w1.ResultChan(): - w0.Stop() - } - close(done) - }(m.Watch(), m.Watch()) - m.Action(Added, &myType{}) - select { - case <-time.After(wait.ForeverTestTimeout): - t.Error("timeout: deadlocked") - case <-done: - } - m.Shutdown() -} - -func TestBroadcasterDropIfChannelFull(t *testing.T) { - m := NewBroadcaster(1, DropIfChannelFull) - - event1 := Event{Type: Added, Object: &myType{"foo", "hello world 1"}} - event2 := Event{Type: Added, Object: &myType{"bar", "hello world 2"}} - - // Add a couple watchers - watches := make([]Interface, 2) - for i := range watches { - watches[i] = m.Watch() - } - - // Send a couple events before closing the broadcast channel. - t.Log("Sending event 1") - m.Action(event1.Type, event1.Object) - t.Log("Sending event 2") - m.Action(event2.Type, event2.Object) - m.Shutdown() - - // Pull events from the queue. - wg := sync.WaitGroup{} - wg.Add(len(watches)) - for i := range watches { - // Verify that each watcher only gets the first event because its watch - // queue of length one was full from the first one. - go func(watcher int, w Interface) { - defer wg.Done() - e1, ok := <-w.ResultChan() - if !ok { - t.Errorf("Watcher %v failed to retrieve first event.", watcher) - } - if e, a := event1, e1; !reflect.DeepEqual(e, a) { - t.Errorf("Watcher %v: Expected (%v, %#v), got (%v, %#v)", - watcher, e.Type, e.Object, a.Type, a.Object) - } - t.Logf("Got (%v, %#v)", e1.Type, e1.Object) - e2, ok := <-w.ResultChan() - if ok { - t.Errorf("Watcher %v received second event (%v, %#v) even though it shouldn't have.", - watcher, e2.Type, e2.Object) - } - }(i, watches[i]) - } - wg.Wait() -} diff --git a/vendor/k8s.io/apimachinery/pkg/watch/streamwatcher_test.go b/vendor/k8s.io/apimachinery/pkg/watch/streamwatcher_test.go deleted file mode 100644 index 1e3029115f..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/watch/streamwatcher_test.go +++ /dev/null @@ -1,68 +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 watch_test - -import ( - "io" - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/runtime" - . "k8s.io/apimachinery/pkg/watch" -) - -type fakeDecoder struct { - items chan Event -} - -func (f fakeDecoder) Decode() (action EventType, object runtime.Object, err error) { - item, open := <-f.items - if !open { - return action, nil, io.EOF - } - return item.Type, item.Object, nil -} - -func (f fakeDecoder) Close() { - close(f.items) -} - -func TestStreamWatcher(t *testing.T) { - table := []Event{ - {Type: Added, Object: testType("foo")}, - } - - fd := fakeDecoder{make(chan Event, 5)} - sw := NewStreamWatcher(fd) - - for _, item := range table { - fd.items <- item - got, open := <-sw.ResultChan() - if !open { - t.Errorf("unexpected early close") - } - if e, a := item, got; !reflect.DeepEqual(e, a) { - t.Errorf("expected %v, got %v", e, a) - } - } - - sw.Stop() - _, open := <-sw.ResultChan() - if open { - t.Errorf("Unexpected failure to close") - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/watch/until_test.go b/vendor/k8s.io/apimachinery/pkg/watch/until_test.go deleted file mode 100644 index e872c36813..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/watch/until_test.go +++ /dev/null @@ -1,172 +0,0 @@ -/* -Copyright 2016 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 watch - -import ( - "errors" - "strings" - "testing" - "time" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/wait" -) - -type fakePod struct { - name string -} - -func (obj *fakePod) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } -func (obj *fakePod) DeepCopyObject() runtime.Object { panic("DeepCopyObject not supported by fakePod") } - -func TestUntil(t *testing.T) { - fw := NewFake() - go func() { - var obj *fakePod - fw.Add(obj) - fw.Modify(obj) - }() - conditions := []ConditionFunc{ - func(event Event) (bool, error) { return event.Type == Added, nil }, - func(event Event) (bool, error) { return event.Type == Modified, nil }, - } - - timeout := time.Minute - lastEvent, err := Until(timeout, fw, conditions...) - if err != nil { - t.Fatalf("expected nil error, got %#v", err) - } - if lastEvent == nil { - t.Fatal("expected an event") - } - if lastEvent.Type != Modified { - t.Fatalf("expected MODIFIED event type, got %v", lastEvent.Type) - } - if got, isPod := lastEvent.Object.(*fakePod); !isPod { - t.Fatalf("expected a pod event, got %#v", got) - } -} - -func TestUntilMultipleConditions(t *testing.T) { - fw := NewFake() - go func() { - var obj *fakePod - fw.Add(obj) - }() - conditions := []ConditionFunc{ - func(event Event) (bool, error) { return event.Type == Added, nil }, - func(event Event) (bool, error) { return event.Type == Added, nil }, - } - - timeout := time.Minute - lastEvent, err := Until(timeout, fw, conditions...) - if err != nil { - t.Fatalf("expected nil error, got %#v", err) - } - if lastEvent == nil { - t.Fatal("expected an event") - } - if lastEvent.Type != Added { - t.Fatalf("expected MODIFIED event type, got %v", lastEvent.Type) - } - if got, isPod := lastEvent.Object.(*fakePod); !isPod { - t.Fatalf("expected a pod event, got %#v", got) - } -} - -func TestUntilMultipleConditionsFail(t *testing.T) { - fw := NewFake() - go func() { - var obj *fakePod - fw.Add(obj) - }() - conditions := []ConditionFunc{ - func(event Event) (bool, error) { return event.Type == Added, nil }, - func(event Event) (bool, error) { return event.Type == Added, nil }, - func(event Event) (bool, error) { return event.Type == Deleted, nil }, - } - - timeout := 10 * time.Second - lastEvent, err := Until(timeout, fw, conditions...) - if err != wait.ErrWaitTimeout { - t.Fatalf("expected ErrWaitTimeout error, got %#v", err) - } - if lastEvent == nil { - t.Fatal("expected an event") - } - if lastEvent.Type != Added { - t.Fatalf("expected ADDED event type, got %v", lastEvent.Type) - } - if got, isPod := lastEvent.Object.(*fakePod); !isPod { - t.Fatalf("expected a pod event, got %#v", got) - } -} - -func TestUntilTimeout(t *testing.T) { - fw := NewFake() - go func() { - var obj *fakePod - fw.Add(obj) - fw.Modify(obj) - }() - conditions := []ConditionFunc{ - func(event Event) (bool, error) { - return event.Type == Added, nil - }, - func(event Event) (bool, error) { - return event.Type == Modified, nil - }, - } - - timeout := time.Duration(0) - lastEvent, err := Until(timeout, fw, conditions...) - if err != nil { - t.Fatalf("expected nil error, got %#v", err) - } - if lastEvent == nil { - t.Fatal("expected an event") - } - if lastEvent.Type != Modified { - t.Fatalf("expected MODIFIED event type, got %v", lastEvent.Type) - } - if got, isPod := lastEvent.Object.(*fakePod); !isPod { - t.Fatalf("expected a pod event, got %#v", got) - } -} - -func TestUntilErrorCondition(t *testing.T) { - fw := NewFake() - go func() { - var obj *fakePod - fw.Add(obj) - }() - expected := "something bad" - conditions := []ConditionFunc{ - func(event Event) (bool, error) { return event.Type == Added, nil }, - func(event Event) (bool, error) { return false, errors.New(expected) }, - } - - timeout := time.Minute - _, err := Until(timeout, fw, conditions...) - if err == nil { - t.Fatal("expected an error") - } - if !strings.Contains(err.Error(), expected) { - t.Fatalf("expected %q in error string, got %q", expected, err.Error()) - } -} diff --git a/vendor/k8s.io/apimachinery/pkg/watch/watch_test.go b/vendor/k8s.io/apimachinery/pkg/watch/watch_test.go deleted file mode 100644 index bdf7fedd4a..0000000000 --- a/vendor/k8s.io/apimachinery/pkg/watch/watch_test.go +++ /dev/null @@ -1,137 +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 watch_test - -import ( - "testing" - - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - . "k8s.io/apimachinery/pkg/watch" -) - -type testType string - -func (obj testType) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } -func (obj testType) DeepCopyObject() runtime.Object { return obj } - -func TestFake(t *testing.T) { - f := NewFake() - - table := []struct { - t EventType - s testType - }{ - {Added, testType("foo")}, - {Modified, testType("qux")}, - {Modified, testType("bar")}, - {Deleted, testType("bar")}, - {Error, testType("error: blah")}, - } - - // Prove that f implements Interface by phrasing this as a function. - consumer := func(w Interface) { - for _, expect := range table { - got, ok := <-w.ResultChan() - if !ok { - t.Fatalf("closed early") - } - if e, a := expect.t, got.Type; e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - if a, ok := got.Object.(testType); !ok || a != expect.s { - t.Fatalf("Expected %v, got %v", expect.s, a) - } - } - _, stillOpen := <-w.ResultChan() - if stillOpen { - t.Fatal("Never stopped") - } - } - - sender := func() { - f.Add(testType("foo")) - f.Action(Modified, testType("qux")) - f.Modify(testType("bar")) - f.Delete(testType("bar")) - f.Error(testType("error: blah")) - f.Stop() - } - - go sender() - consumer(f) -} - -func TestRaceFreeFake(t *testing.T) { - f := NewRaceFreeFake() - - table := []struct { - t EventType - s testType - }{ - {Added, testType("foo")}, - {Modified, testType("qux")}, - {Modified, testType("bar")}, - {Deleted, testType("bar")}, - {Error, testType("error: blah")}, - } - - // Prove that f implements Interface by phrasing this as a function. - consumer := func(w Interface) { - for _, expect := range table { - got, ok := <-w.ResultChan() - if !ok { - t.Fatalf("closed early") - } - if e, a := expect.t, got.Type; e != a { - t.Fatalf("Expected %v, got %v", e, a) - } - if a, ok := got.Object.(testType); !ok || a != expect.s { - t.Fatalf("Expected %v, got %v", expect.s, a) - } - } - _, stillOpen := <-w.ResultChan() - if stillOpen { - t.Fatal("Never stopped") - } - } - - sender := func() { - f.Add(testType("foo")) - f.Action(Modified, testType("qux")) - f.Modify(testType("bar")) - f.Delete(testType("bar")) - f.Error(testType("error: blah")) - f.Stop() - } - - go sender() - consumer(f) -} - -func TestEmpty(t *testing.T) { - w := NewEmptyWatch() - _, ok := <-w.ResultChan() - if ok { - t.Errorf("unexpected result channel result") - } - w.Stop() - _, ok = <-w.ResultChan() - if ok { - t.Errorf("unexpected result channel result") - } -} diff --git a/vendor/k8s.io/apimachinery/third_party/forked/golang/json/BUILD b/vendor/k8s.io/apimachinery/third_party/forked/golang/json/BUILD deleted file mode 100644 index 7ece664d06..0000000000 --- a/vendor/k8s.io/apimachinery/third_party/forked/golang/json/BUILD +++ /dev/null @@ -1,32 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_library( - name = "go_default_library", - srcs = ["fields.go"], - importpath = "k8s.io/apimachinery/third_party/forked/golang/json", -) - -go_test( - name = "go_default_test", - srcs = ["fields_test.go"], - embed = [":go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/third_party/forked/golang/json/fields_test.go b/vendor/k8s.io/apimachinery/third_party/forked/golang/json/fields_test.go deleted file mode 100644 index 33b78bc43c..0000000000 --- a/vendor/k8s.io/apimachinery/third_party/forked/golang/json/fields_test.go +++ /dev/null @@ -1,30 +0,0 @@ -package json - -import ( - "reflect" - "testing" -) - -func TestLookupPtrToStruct(t *testing.T) { - type Elem struct { - Key string - Value string - } - type Outer struct { - Inner []Elem `json:"inner" patchStrategy:"merge" patchMergeKey:"key"` - } - outer := &Outer{} - elemType, patchStrategies, patchMergeKey, err := LookupPatchMetadataForStruct(reflect.TypeOf(outer), "inner") - if err != nil { - t.Fatal(err) - } - if elemType != reflect.TypeOf([]Elem{}) { - t.Errorf("elemType = %v, want: %v", elemType, reflect.TypeOf([]Elem{})) - } - if !reflect.DeepEqual(patchStrategies, []string{"merge"}) { - t.Errorf("patchStrategies = %v, want: %v", patchStrategies, []string{"merge"}) - } - if patchMergeKey != "key" { - t.Errorf("patchMergeKey = %v, want: %v", patchMergeKey, "key") - } -} diff --git a/vendor/k8s.io/apimachinery/third_party/forked/golang/netutil/BUILD b/vendor/k8s.io/apimachinery/third_party/forked/golang/netutil/BUILD deleted file mode 100644 index 1df290578f..0000000000 --- a/vendor/k8s.io/apimachinery/third_party/forked/golang/netutil/BUILD +++ /dev/null @@ -1,25 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = ["addr.go"], - importpath = "k8s.io/apimachinery/third_party/forked/golang/netutil", -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/BUILD b/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/BUILD deleted file mode 100644 index 22c8ec0494..0000000000 --- a/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/BUILD +++ /dev/null @@ -1,32 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["deep_equal_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["deep_equal.go"], - importpath = "k8s.io/apimachinery/third_party/forked/golang/reflect", -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal_test.go b/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal_test.go deleted file mode 100644 index 4a06299309..0000000000 --- a/vendor/k8s.io/apimachinery/third_party/forked/golang/reflect/deep_equal_test.go +++ /dev/null @@ -1,137 +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 reflect - -import ( - "testing" -) - -func TestEqualities(t *testing.T) { - e := Equalities{} - type Bar struct { - X int - } - type Baz struct { - Y Bar - } - err := e.AddFuncs( - func(a, b int) bool { - return a+1 == b - }, - func(a, b Bar) bool { - return a.X*10 == b.X - }, - ) - if err != nil { - t.Fatalf("Unexpected: %v", err) - } - - type Foo struct { - X int - } - - table := []struct { - a, b interface{} - equal bool - }{ - {1, 2, true}, - {2, 1, false}, - {"foo", "fo", false}, - {"foo", "foo", true}, - {"foo", "foobar", false}, - {Foo{1}, Foo{2}, true}, - {Foo{2}, Foo{1}, false}, - {Bar{1}, Bar{10}, true}, - {&Bar{1}, &Bar{10}, true}, - {Baz{Bar{1}}, Baz{Bar{10}}, true}, - {[...]string{}, [...]string{"1", "2", "3"}, false}, - {[...]string{"1"}, [...]string{"1", "2", "3"}, false}, - {[...]string{"1", "2", "3"}, [...]string{}, false}, - {[...]string{"1", "2", "3"}, [...]string{"1", "2", "3"}, true}, - {map[string]int{"foo": 1}, map[string]int{}, false}, - {map[string]int{"foo": 1}, map[string]int{"foo": 2}, true}, - {map[string]int{"foo": 2}, map[string]int{"foo": 1}, false}, - {map[string]int{"foo": 1}, map[string]int{"foo": 2, "bar": 6}, false}, - {map[string]int{"foo": 1, "bar": 6}, map[string]int{"foo": 2}, false}, - {map[string]int{}, map[string]int(nil), true}, - {[]string(nil), []string(nil), true}, - {[]string{}, []string(nil), true}, - {[]string(nil), []string{}, true}, - {[]string{"1"}, []string(nil), false}, - {[]string{}, []string{"1", "2", "3"}, false}, - {[]string{"1"}, []string{"1", "2", "3"}, false}, - {[]string{"1", "2", "3"}, []string{}, false}, - } - - for _, item := range table { - if e, a := item.equal, e.DeepEqual(item.a, item.b); e != a { - t.Errorf("Expected (%+v == %+v) == %v, but got %v", item.a, item.b, e, a) - } - } -} - -func TestDerivates(t *testing.T) { - e := Equalities{} - type Bar struct { - X int - } - type Baz struct { - Y Bar - } - err := e.AddFuncs( - func(a, b int) bool { - return a+1 == b - }, - func(a, b Bar) bool { - return a.X*10 == b.X - }, - ) - if err != nil { - t.Fatalf("Unexpected: %v", err) - } - - type Foo struct { - X int - } - - table := []struct { - a, b interface{} - equal bool - }{ - {1, 2, true}, - {2, 1, false}, - {"foo", "fo", false}, - {"foo", "foo", true}, - {"foo", "foobar", false}, - {Foo{1}, Foo{2}, true}, - {Foo{2}, Foo{1}, false}, - {Bar{1}, Bar{10}, true}, - {&Bar{1}, &Bar{10}, true}, - {Baz{Bar{1}}, Baz{Bar{10}}, true}, - {[...]string{}, [...]string{"1", "2", "3"}, false}, - {[...]string{"1"}, [...]string{"1", "2", "3"}, false}, - {[...]string{"1", "2", "3"}, [...]string{}, false}, - {[...]string{"1", "2", "3"}, [...]string{"1", "2", "3"}, true}, - {map[string]int{"foo": 1}, map[string]int{}, false}, - {map[string]int{"foo": 1}, map[string]int{"foo": 2}, true}, - {map[string]int{"foo": 2}, map[string]int{"foo": 1}, false}, - {map[string]int{"foo": 1}, map[string]int{"foo": 2, "bar": 6}, true}, - {map[string]int{"foo": 1, "bar": 6}, map[string]int{"foo": 2}, false}, - {map[string]int{}, map[string]int(nil), true}, - {[]string(nil), []string(nil), true}, - {[]string{}, []string(nil), true}, - {[]string(nil), []string{}, true}, - {[]string{"1"}, []string(nil), false}, - {[]string{}, []string{"1", "2", "3"}, true}, - {[]string{"1"}, []string{"1", "2", "3"}, true}, - {[]string{"1", "2", "3"}, []string{}, false}, - } - - for _, item := range table { - if e, a := item.equal, e.DeepDerivative(item.a, item.b); e != a { - t.Errorf("Expected (%+v ~ %+v) == %v, but got %v", item.a, item.b, e, a) - } - } -} diff --git a/vendor/k8s.io/apiserver/pkg/authentication/authenticator/BUILD b/vendor/k8s.io/apiserver/pkg/authentication/authenticator/BUILD deleted file mode 100644 index 268bb29f1a..0000000000 --- a/vendor/k8s.io/apiserver/pkg/authentication/authenticator/BUILD +++ /dev/null @@ -1,26 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = ["interfaces.go"], - importpath = "k8s.io/apiserver/pkg/authentication/authenticator", - deps = ["//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/BUILD b/vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/BUILD deleted file mode 100644 index 3a60436e4f..0000000000 --- a/vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/BUILD +++ /dev/null @@ -1,33 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["util_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["util.go"], - importpath = "k8s.io/apiserver/pkg/authentication/serviceaccount", - deps = ["//vendor/k8s.io/apimachinery/pkg/api/validation:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/util_test.go b/vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/util_test.go deleted file mode 100644 index 14784b16cd..0000000000 --- a/vendor/k8s.io/apiserver/pkg/authentication/serviceaccount/util_test.go +++ /dev/null @@ -1,82 +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 serviceaccount - -import "testing" - -func TestMakeUsername(t *testing.T) { - - testCases := map[string]struct { - Namespace string - Name string - ExpectedErr bool - }{ - "valid": { - Namespace: "foo", - Name: "bar", - ExpectedErr: false, - }, - "empty": { - ExpectedErr: true, - }, - "empty namespace": { - Namespace: "", - Name: "foo", - ExpectedErr: true, - }, - "empty name": { - Namespace: "foo", - Name: "", - ExpectedErr: true, - }, - "extra segments": { - Namespace: "foo", - Name: "bar:baz", - ExpectedErr: true, - }, - "invalid chars in namespace": { - Namespace: "foo ", - Name: "bar", - ExpectedErr: true, - }, - "invalid chars in name": { - Namespace: "foo", - Name: "bar ", - ExpectedErr: true, - }, - } - - for k, tc := range testCases { - username := MakeUsername(tc.Namespace, tc.Name) - - namespace, name, err := SplitUsername(username) - if (err != nil) != tc.ExpectedErr { - t.Errorf("%s: Expected error=%v, got %v", k, tc.ExpectedErr, err) - continue - } - if err != nil { - continue - } - - if namespace != tc.Namespace { - t.Errorf("%s: Expected namespace %q, got %q", k, tc.Namespace, namespace) - } - if name != tc.Name { - t.Errorf("%s: Expected name %q, got %q", k, tc.Name, name) - } - } -} diff --git a/vendor/k8s.io/apiserver/pkg/authentication/user/BUILD b/vendor/k8s.io/apiserver/pkg/authentication/user/BUILD deleted file mode 100644 index f22095c254..0000000000 --- a/vendor/k8s.io/apiserver/pkg/authentication/user/BUILD +++ /dev/null @@ -1,28 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "user.go", - ], - importpath = "k8s.io/apiserver/pkg/authentication/user", -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiserver/pkg/features/BUILD b/vendor/k8s.io/apiserver/pkg/features/BUILD deleted file mode 100644 index 1d45a428ec..0000000000 --- a/vendor/k8s.io/apiserver/pkg/features/BUILD +++ /dev/null @@ -1,26 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = ["kube_features.go"], - importpath = "k8s.io/apiserver/pkg/features", - deps = ["//vendor/k8s.io/apiserver/pkg/util/feature:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiserver/pkg/server/BUILD b/vendor/k8s.io/apiserver/pkg/server/BUILD deleted file mode 100644 index c1073fc1d5..0000000000 --- a/vendor/k8s.io/apiserver/pkg/server/BUILD +++ /dev/null @@ -1,172 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = [ - "config_selfclient_test.go", - "config_test.go", - "genericapiserver_test.go", - ], - embed = [":go_default_library"], - deps = [ - "//vendor/github.com/stretchr/testify/assert:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/meta:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apimachinery:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/version:go_default_library", - "//vendor/k8s.io/apiserver/pkg/apis/example:go_default_library", - "//vendor/k8s.io/apiserver/pkg/apis/example/v1:go_default_library", - "//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library", - "//vendor/k8s.io/apiserver/pkg/authorization/authorizer:go_default_library", - "//vendor/k8s.io/apiserver/pkg/endpoints/discovery:go_default_library", - "//vendor/k8s.io/apiserver/pkg/endpoints/filters:go_default_library", - "//vendor/k8s.io/apiserver/pkg/endpoints/request:go_default_library", - "//vendor/k8s.io/apiserver/pkg/registry/rest:go_default_library", - "//vendor/k8s.io/apiserver/pkg/server/filters:go_default_library", - "//vendor/k8s.io/apiserver/pkg/server/healthz:go_default_library", - "//vendor/k8s.io/client-go/informers:go_default_library", - "//vendor/k8s.io/client-go/kubernetes/fake:go_default_library", - "//vendor/k8s.io/client-go/rest:go_default_library", - ], -) - -go_library( - name = "go_default_library", - srcs = [ - "config.go", - "config_selfclient.go", - "doc.go", - "genericapiserver.go", - "handler.go", - "healthz.go", - "hooks.go", - "plugins.go", - "serve.go", - "signal.go", - ] + select({ - "@io_bazel_rules_go//go/platform:android": [ - "signal_posix.go", - ], - "@io_bazel_rules_go//go/platform:darwin": [ - "signal_posix.go", - ], - "@io_bazel_rules_go//go/platform:dragonfly": [ - "signal_posix.go", - ], - "@io_bazel_rules_go//go/platform:freebsd": [ - "signal_posix.go", - ], - "@io_bazel_rules_go//go/platform:linux": [ - "signal_posix.go", - ], - "@io_bazel_rules_go//go/platform:nacl": [ - "signal_posix.go", - ], - "@io_bazel_rules_go//go/platform:netbsd": [ - "signal_posix.go", - ], - "@io_bazel_rules_go//go/platform:openbsd": [ - "signal_posix.go", - ], - "@io_bazel_rules_go//go/platform:plan9": [ - "signal_posix.go", - ], - "@io_bazel_rules_go//go/platform:solaris": [ - "signal_posix.go", - ], - "@io_bazel_rules_go//go/platform:windows": [ - "signal_windows.go", - ], - "//conditions:default": [], - }), - importpath = "k8s.io/apiserver/pkg/server", - deps = [ - "//vendor/github.com/coreos/go-systemd/daemon:go_default_library", - "//vendor/github.com/emicklei/go-restful:go_default_library", - "//vendor/github.com/emicklei/go-restful-swagger12:go_default_library", - "//vendor/github.com/go-openapi/spec:go_default_library", - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/github.com/pborman/uuid:go_default_library", - "//vendor/golang.org/x/net/http2:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/api/errors:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apimachinery:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apimachinery/registered:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/apis/meta/v1:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/schema:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/runtime/serializer:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/errors:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/sets:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/validation:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/waitgroup:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/version:go_default_library", - "//vendor/k8s.io/apiserver/pkg/admission:go_default_library", - "//vendor/k8s.io/apiserver/pkg/admission/plugin/initialization:go_default_library", - "//vendor/k8s.io/apiserver/pkg/admission/plugin/namespace/lifecycle:go_default_library", - "//vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/mutating:go_default_library", - "//vendor/k8s.io/apiserver/pkg/admission/plugin/webhook/validating:go_default_library", - "//vendor/k8s.io/apiserver/pkg/apis/apiserver/install:go_default_library", - "//vendor/k8s.io/apiserver/pkg/audit:go_default_library", - "//vendor/k8s.io/apiserver/pkg/audit/policy:go_default_library", - "//vendor/k8s.io/apiserver/pkg/authentication/authenticator:go_default_library", - "//vendor/k8s.io/apiserver/pkg/authentication/authenticatorfactory:go_default_library", - "//vendor/k8s.io/apiserver/pkg/authentication/request/union:go_default_library", - "//vendor/k8s.io/apiserver/pkg/authentication/user:go_default_library", - "//vendor/k8s.io/apiserver/pkg/authorization/authorizer:go_default_library", - "//vendor/k8s.io/apiserver/pkg/authorization/authorizerfactory:go_default_library", - "//vendor/k8s.io/apiserver/pkg/authorization/union:go_default_library", - "//vendor/k8s.io/apiserver/pkg/endpoints:go_default_library", - "//vendor/k8s.io/apiserver/pkg/endpoints/discovery:go_default_library", - "//vendor/k8s.io/apiserver/pkg/endpoints/filters:go_default_library", - "//vendor/k8s.io/apiserver/pkg/endpoints/handlers/responsewriters:go_default_library", - "//vendor/k8s.io/apiserver/pkg/endpoints/openapi:go_default_library", - "//vendor/k8s.io/apiserver/pkg/endpoints/request:go_default_library", - "//vendor/k8s.io/apiserver/pkg/features:go_default_library", - "//vendor/k8s.io/apiserver/pkg/registry/generic:go_default_library", - "//vendor/k8s.io/apiserver/pkg/registry/rest:go_default_library", - "//vendor/k8s.io/apiserver/pkg/server/filters:go_default_library", - "//vendor/k8s.io/apiserver/pkg/server/healthz:go_default_library", - "//vendor/k8s.io/apiserver/pkg/server/mux:go_default_library", - "//vendor/k8s.io/apiserver/pkg/server/routes:go_default_library", - "//vendor/k8s.io/apiserver/pkg/server/storage:go_default_library", - "//vendor/k8s.io/apiserver/pkg/util/feature:go_default_library", - "//vendor/k8s.io/client-go/informers:go_default_library", - "//vendor/k8s.io/client-go/rest:go_default_library", - "//vendor/k8s.io/client-go/util/cert:go_default_library", - "//vendor/k8s.io/kube-openapi/pkg/common:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apiserver/pkg/server/filters:all-srcs", - "//staging/src/k8s.io/apiserver/pkg/server/healthz:all-srcs", - "//staging/src/k8s.io/apiserver/pkg/server/httplog:all-srcs", - "//staging/src/k8s.io/apiserver/pkg/server/mux:all-srcs", - "//staging/src/k8s.io/apiserver/pkg/server/options:all-srcs", - "//staging/src/k8s.io/apiserver/pkg/server/resourceconfig:all-srcs", - "//staging/src/k8s.io/apiserver/pkg/server/routes:all-srcs", - "//staging/src/k8s.io/apiserver/pkg/server/storage:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiserver/pkg/server/config_selfclient_test.go b/vendor/k8s.io/apiserver/pkg/server/config_selfclient_test.go deleted file mode 100644 index fcf126b232..0000000000 --- a/vendor/k8s.io/apiserver/pkg/server/config_selfclient_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2016 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 server - -import ( - "net" - "testing" -) - -func TestLoopbackHostPort(t *testing.T) { - host, port, err := LoopbackHostPort("1.2.3.4:443") - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if host != "1.2.3.4" { - t.Fatalf("expected 1.2.3.4 as host, got %q", host) - } - if port != "443" { - t.Fatalf("expected 443 as port, got %q", port) - } - - host, port, err = LoopbackHostPort("0.0.0.0:443") - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() { - t.Fatalf("expected host to be loopback, got %q", host) - } - if port != "443" { - t.Fatalf("expected 443 as port, got %q", port) - } - - host, port, err = LoopbackHostPort("[ff06:0:0:0:0:0:0:c3]:443") - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if host != "ff06:0:0:0:0:0:0:c3" { - t.Fatalf("expected ff06:0:0:0:0:0:0:c3 as host, got %q", host) - } - if port != "443" { - t.Fatalf("expected 443 as port, got %q", port) - } - - host, port, err = LoopbackHostPort("[::]:443") - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() { - t.Fatalf("expected host to be loopback, got %q", host) - } - if port != "443" { - t.Fatalf("expected 443 as port, got %q", port) - } -} diff --git a/vendor/k8s.io/apiserver/pkg/server/config_test.go b/vendor/k8s.io/apiserver/pkg/server/config_test.go deleted file mode 100644 index 381318c8de..0000000000 --- a/vendor/k8s.io/apiserver/pkg/server/config_test.go +++ /dev/null @@ -1,153 +0,0 @@ -/* -Copyright 2017 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 server - -import ( - "fmt" - "io/ioutil" - "net" - "net/http" - "net/http/httptest" - "net/http/httputil" - "testing" - - "k8s.io/apimachinery/pkg/util/sets" - genericapirequest "k8s.io/apiserver/pkg/endpoints/request" - "k8s.io/apiserver/pkg/server/healthz" - "k8s.io/client-go/informers" - "k8s.io/client-go/kubernetes/fake" - "k8s.io/client-go/rest" -) - -func TestNewWithDelegate(t *testing.T) { - delegateConfig := NewConfig(codecs) - delegateConfig.PublicAddress = net.ParseIP("192.168.10.4") - delegateConfig.RequestContextMapper = genericapirequest.NewRequestContextMapper() - delegateConfig.LegacyAPIGroupPrefixes = sets.NewString("/api") - delegateConfig.LoopbackClientConfig = &rest.Config{} - delegateConfig.SwaggerConfig = DefaultSwaggerConfig() - clientset := fake.NewSimpleClientset() - if clientset == nil { - t.Fatal("unable to create fake client set") - } - - delegateConfig.HealthzChecks = append(delegateConfig.HealthzChecks, healthz.NamedCheck("delegate-health", func(r *http.Request) error { - return fmt.Errorf("delegate failed healthcheck") - })) - - sharedInformers := informers.NewSharedInformerFactory(clientset, delegateConfig.LoopbackClientConfig.Timeout) - delegateServer, err := delegateConfig.Complete(sharedInformers).New("test", EmptyDelegate) - if err != nil { - t.Fatal(err) - } - delegateServer.Handler.NonGoRestfulMux.HandleFunc("/foo", func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusForbidden) - }) - - delegateServer.AddPostStartHook("delegate-post-start-hook", func(context PostStartHookContext) error { - return nil - }) - - // this wires up swagger - delegateServer.PrepareRun() - - wrappingConfig := NewConfig(codecs) - wrappingConfig.PublicAddress = net.ParseIP("192.168.10.4") - wrappingConfig.RequestContextMapper = genericapirequest.NewRequestContextMapper() - wrappingConfig.LegacyAPIGroupPrefixes = sets.NewString("/api") - wrappingConfig.LoopbackClientConfig = &rest.Config{} - wrappingConfig.SwaggerConfig = DefaultSwaggerConfig() - - wrappingConfig.HealthzChecks = append(wrappingConfig.HealthzChecks, healthz.NamedCheck("wrapping-health", func(r *http.Request) error { - return fmt.Errorf("wrapping failed healthcheck") - })) - - sharedInformers = informers.NewSharedInformerFactory(clientset, wrappingConfig.LoopbackClientConfig.Timeout) - wrappingServer, err := wrappingConfig.Complete(sharedInformers).New("test", delegateServer) - if err != nil { - t.Fatal(err) - } - wrappingServer.Handler.NonGoRestfulMux.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusUnauthorized) - }) - - wrappingServer.AddPostStartHook("wrapping-post-start-hook", func(context PostStartHookContext) error { - return nil - }) - - stopCh := make(chan struct{}) - defer close(stopCh) - wrappingServer.PrepareRun() - wrappingServer.RunPostStartHooks(stopCh) - - server := httptest.NewServer(wrappingServer.Handler) - defer server.Close() - - checkPath(server.URL, http.StatusOK, `{ - "paths": [ - "/apis", - "/bar", - "/foo", - "/healthz", - "/healthz/delegate-health", - "/healthz/ping", - "/healthz/poststarthook/delegate-post-start-hook", - "/healthz/poststarthook/generic-apiserver-start-informers", - "/healthz/poststarthook/wrapping-post-start-hook", - "/healthz/wrapping-health", - "/swaggerapi" - ] -}`, t) - checkPath(server.URL+"/healthz", http.StatusInternalServerError, `[+]ping ok -[-]wrapping-health failed: reason withheld -[-]delegate-health failed: reason withheld -[+]poststarthook/generic-apiserver-start-informers ok -[+]poststarthook/delegate-post-start-hook ok -[+]poststarthook/wrapping-post-start-hook ok -healthz check failed -`, t) - - checkPath(server.URL+"/healthz/delegate-health", http.StatusInternalServerError, `internal server error: delegate failed healthcheck -`, t) - checkPath(server.URL+"/healthz/wrapping-health", http.StatusInternalServerError, `internal server error: wrapping failed healthcheck -`, t) - checkPath(server.URL+"/healthz/poststarthook/delegate-post-start-hook", http.StatusOK, `ok`, t) - checkPath(server.URL+"/healthz/poststarthook/wrapping-post-start-hook", http.StatusOK, `ok`, t) - checkPath(server.URL+"/foo", http.StatusForbidden, ``, t) - checkPath(server.URL+"/bar", http.StatusUnauthorized, ``, t) -} - -func checkPath(url string, expectedStatusCode int, expectedBody string, t *testing.T) { - resp, err := http.Get(url) - if err != nil { - t.Fatal(err) - } - dump, _ := httputil.DumpResponse(resp, true) - t.Log(string(dump)) - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Fatal(err) - } - - if e, a := expectedBody, string(body); e != a { - t.Errorf("%q expected %v, got %v", url, e, a) - } - if e, a := expectedStatusCode, resp.StatusCode; e != a { - t.Errorf("%q expected %v, got %v", url, e, a) - } -} diff --git a/vendor/k8s.io/apiserver/pkg/server/genericapiserver_test.go b/vendor/k8s.io/apiserver/pkg/server/genericapiserver_test.go deleted file mode 100644 index 18761881b3..0000000000 --- a/vendor/k8s.io/apiserver/pkg/server/genericapiserver_test.go +++ /dev/null @@ -1,581 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package server - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/http/httptest" - goruntime "runtime" - "strconv" - "sync" - "testing" - "time" - - // "github.com/go-openapi/spec" - "github.com/stretchr/testify/assert" - - "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/apimachinery/pkg/apimachinery" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/runtime/serializer" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/version" - "k8s.io/apiserver/pkg/apis/example" - examplev1 "k8s.io/apiserver/pkg/apis/example/v1" - "k8s.io/apiserver/pkg/authentication/user" - "k8s.io/apiserver/pkg/authorization/authorizer" - "k8s.io/apiserver/pkg/endpoints/discovery" - genericapifilters "k8s.io/apiserver/pkg/endpoints/filters" - apirequest "k8s.io/apiserver/pkg/endpoints/request" - "k8s.io/apiserver/pkg/registry/rest" - genericfilters "k8s.io/apiserver/pkg/server/filters" - "k8s.io/client-go/informers" - "k8s.io/client-go/kubernetes/fake" - restclient "k8s.io/client-go/rest" -) - -const ( - extensionsGroupName = "extensions" -) - -var ( - v1GroupVersion = schema.GroupVersion{Group: "", Version: "v1"} - - scheme = runtime.NewScheme() - codecs = serializer.NewCodecFactory(scheme) - parameterCodec = runtime.NewParameterCodec(scheme) -) - -func init() { - metav1.AddToGroupVersion(scheme, metav1.SchemeGroupVersion) - scheme.AddUnversionedTypes(v1GroupVersion, - &metav1.Status{}, - &metav1.APIVersions{}, - &metav1.APIGroupList{}, - &metav1.APIGroup{}, - &metav1.APIResourceList{}, - ) - example.AddToScheme(scheme) - examplev1.AddToScheme(scheme) -} - -// setUp is a convience function for setting up for (most) tests. -func setUp(t *testing.T) (Config, *assert.Assertions) { - config := NewConfig(codecs) - config.PublicAddress = net.ParseIP("192.168.10.4") - config.RequestContextMapper = apirequest.NewRequestContextMapper() - config.LegacyAPIGroupPrefixes = sets.NewString("/api") - config.LoopbackClientConfig = &restclient.Config{} - - clientset := fake.NewSimpleClientset() - if clientset == nil { - t.Fatal("unable to create fake client set") - } - - // TODO restore this test, but right now, eliminate our cycle - // config.OpenAPIConfig = DefaultOpenAPIConfig(testGetOpenAPIDefinitions, runtime.NewScheme()) - // config.OpenAPIConfig.Info = &spec.Info{ - // InfoProps: spec.InfoProps{ - // Title: "Kubernetes", - // Version: "unversioned", - // }, - // } - config.SwaggerConfig = DefaultSwaggerConfig() - sharedInformers := informers.NewSharedInformerFactory(clientset, config.LoopbackClientConfig.Timeout) - config.Complete(sharedInformers) - - return *config, assert.New(t) -} - -func newMaster(t *testing.T) (*GenericAPIServer, Config, *assert.Assertions) { - config, assert := setUp(t) - - s, err := config.Complete(nil).New("test", EmptyDelegate) - if err != nil { - t.Fatalf("Error in bringing up the server: %v", err) - } - return s, config, assert -} - -// TestNew verifies that the New function returns a GenericAPIServer -// using the configuration properly. -func TestNew(t *testing.T) { - s, config, assert := newMaster(t) - - // Verify many of the variables match their config counterparts - assert.Equal(s.legacyAPIGroupPrefixes, config.LegacyAPIGroupPrefixes) - assert.Equal(s.admissionControl, config.AdmissionControl) - assert.Equal(s.RequestContextMapper(), config.RequestContextMapper) - - // these values get defaulted - assert.Equal(net.JoinHostPort(config.PublicAddress.String(), "443"), s.ExternalAddress) - assert.NotNil(s.swaggerConfig) - assert.Equal("http://"+s.ExternalAddress, s.swaggerConfig.WebServicesUrl) -} - -// Verifies that AddGroupVersions works as expected. -func TestInstallAPIGroups(t *testing.T) { - config, assert := setUp(t) - - config.LegacyAPIGroupPrefixes = sets.NewString("/apiPrefix") - config.DiscoveryAddresses = discovery.DefaultAddresses{DefaultAddress: "ExternalAddress"} - - s, err := config.Complete(nil).New("test", EmptyDelegate) - if err != nil { - t.Fatalf("Error in bringing up the server: %v", err) - } - - testAPI := func(gv schema.GroupVersion) APIGroupInfo { - getter, noVerbs := testGetterStorage{}, testNoVerbsStorage{} - - scheme := runtime.NewScheme() - scheme.AddKnownTypeWithName(gv.WithKind("Getter"), getter.New()) - scheme.AddKnownTypeWithName(gv.WithKind("NoVerb"), noVerbs.New()) - scheme.AddKnownTypes(v1GroupVersion, &metav1.Status{}) - metav1.AddToGroupVersion(scheme, v1GroupVersion) - - interfacesFor := func(version schema.GroupVersion) (*meta.VersionInterfaces, error) { - return &meta.VersionInterfaces{ - ObjectConvertor: scheme, - MetadataAccessor: meta.NewAccessor(), - }, nil - } - - mapper := meta.NewDefaultRESTMapper([]schema.GroupVersion{gv}, interfacesFor) - for kind := range scheme.KnownTypes(gv) { - mapper.Add(gv.WithKind(kind), meta.RESTScopeNamespace) - } - groupMeta := apimachinery.GroupMeta{ - GroupVersion: gv, - GroupVersions: []schema.GroupVersion{gv}, - RESTMapper: mapper, - InterfacesFor: interfacesFor, - } - - return APIGroupInfo{ - GroupMeta: groupMeta, - VersionedResourcesStorageMap: map[string]map[string]rest.Storage{ - gv.Version: { - "getter": &testGetterStorage{Version: gv.Version}, - "noverbs": &testNoVerbsStorage{Version: gv.Version}, - }, - }, - OptionsExternalVersion: &schema.GroupVersion{Version: "v1"}, - ParameterCodec: parameterCodec, - NegotiatedSerializer: codecs, - Scheme: scheme, - } - } - - apis := []APIGroupInfo{ - testAPI(schema.GroupVersion{Group: "", Version: "v1"}), - testAPI(schema.GroupVersion{Group: extensionsGroupName, Version: "v1"}), - testAPI(schema.GroupVersion{Group: "batch", Version: "v1"}), - } - - err = s.InstallLegacyAPIGroup("/apiPrefix", &apis[0]) - assert.NoError(err) - groupPaths := []string{ - config.LegacyAPIGroupPrefixes.List()[0], // /apiPrefix - } - for _, api := range apis[1:] { - err = s.InstallAPIGroup(&api) - assert.NoError(err) - groupPaths = append(groupPaths, APIGroupPrefix+"/"+api.GroupMeta.GroupVersion.Group) // /apis/<group> - } - - server := httptest.NewServer(s.Handler) - defer server.Close() - - for i := range apis { - // should serve APIGroup at group path - info := &apis[i] - path := groupPaths[i] - resp, err := http.Get(server.URL + path) - if err != nil { - t.Errorf("[%d] unexpected error getting path %q path: %v", i, path, err) - continue - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("[%d] unexpected error reading body at path %q: %v", i, path, err) - continue - } - - t.Logf("[%d] json at %s: %s", i, path, string(body)) - - if i == 0 { - // legacy API returns APIVersions - group := metav1.APIVersions{} - err = json.Unmarshal(body, &group) - if err != nil { - t.Errorf("[%d] unexpected error parsing json body at path %q: %v", i, path, err) - continue - } - } else { - // API groups return APIGroup - group := metav1.APIGroup{} - err = json.Unmarshal(body, &group) - if err != nil { - t.Errorf("[%d] unexpected error parsing json body at path %q: %v", i, path, err) - continue - } - - if got, expected := group.Name, info.GroupMeta.GroupVersion.Group; got != expected { - t.Errorf("[%d] unexpected group name at path %q: got=%q expected=%q", i, path, got, expected) - continue - } - - if got, expected := group.PreferredVersion.Version, info.GroupMeta.GroupVersion.Version; got != expected { - t.Errorf("[%d] unexpected group version at path %q: got=%q expected=%q", i, path, got, expected) - continue - } - } - - // should serve APIResourceList at group path + /<group-version> - path = path + "/" + info.GroupMeta.GroupVersion.Version - resp, err = http.Get(server.URL + path) - if err != nil { - t.Errorf("[%d] unexpected error getting path %q path: %v", i, path, err) - continue - } - - body, err = ioutil.ReadAll(resp.Body) - if err != nil { - t.Errorf("[%d] unexpected error reading body at path %q: %v", i, path, err) - continue - } - - t.Logf("[%d] json at %s: %s", i, path, string(body)) - - resources := metav1.APIResourceList{} - err = json.Unmarshal(body, &resources) - if err != nil { - t.Errorf("[%d] unexpected error parsing json body at path %q: %v", i, path, err) - continue - } - - if got, expected := resources.GroupVersion, info.GroupMeta.GroupVersion.String(); got != expected { - t.Errorf("[%d] unexpected groupVersion at path %q: got=%q expected=%q", i, path, got, expected) - continue - } - - // the verbs should match the features of resources - for _, r := range resources.APIResources { - switch r.Name { - case "getter": - if got, expected := sets.NewString([]string(r.Verbs)...), sets.NewString("get"); !got.Equal(expected) { - t.Errorf("[%d] unexpected verbs for resource %s/%s: got=%v expected=%v", i, resources.GroupVersion, r.Name, got, expected) - } - case "noverbs": - if r.Verbs == nil { - t.Errorf("[%d] unexpected nil verbs slice. Expected: []string{}", i) - } - if got, expected := sets.NewString([]string(r.Verbs)...), sets.NewString(); !got.Equal(expected) { - t.Errorf("[%d] unexpected verbs for resource %s/%s: got=%v expected=%v", i, resources.GroupVersion, r.Name, got, expected) - } - } - } - } -} - -func TestPrepareRun(t *testing.T) { - s, config, assert := newMaster(t) - - assert.NotNil(config.SwaggerConfig) - - server := httptest.NewServer(s.Handler.Director) - defer server.Close() - done := make(chan struct{}) - - s.PrepareRun() - s.RunPostStartHooks(done) - - // swagger is installed in PrepareRun - resp, err := http.Get(server.URL + "/swaggerapi/") - assert.NoError(err) - assert.Equal(http.StatusOK, resp.StatusCode) - - // healthz checks are installed in PrepareRun - resp, err = http.Get(server.URL + "/healthz") - assert.NoError(err) - assert.Equal(http.StatusOK, resp.StatusCode) - resp, err = http.Get(server.URL + "/healthz/ping") - assert.NoError(err) - assert.Equal(http.StatusOK, resp.StatusCode) -} - -// TestCustomHandlerChain verifies the handler chain with custom handler chain builder functions. -func TestCustomHandlerChain(t *testing.T) { - config, _ := setUp(t) - - var protected, called bool - - config.BuildHandlerChainFunc = func(apiHandler http.Handler, c *Config) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - protected = true - apiHandler.ServeHTTP(w, req) - }) - } - handler := http.HandlerFunc(func(r http.ResponseWriter, req *http.Request) { - called = true - }) - - s, err := config.Complete(nil).New("test", EmptyDelegate) - if err != nil { - t.Fatalf("Error in bringing up the server: %v", err) - } - - s.Handler.NonGoRestfulMux.Handle("/nonswagger", handler) - s.Handler.NonGoRestfulMux.Handle("/secret", handler) - - type Test struct { - handler http.Handler - path string - protected bool - } - for i, test := range []Test{ - {s.Handler, "/nonswagger", true}, - {s.Handler, "/secret", true}, - } { - protected, called = false, false - - var w io.Reader - req, err := http.NewRequest("GET", test.path, w) - if err != nil { - t.Errorf("%d: Unexpected http error: %v", i, err) - continue - } - - test.handler.ServeHTTP(httptest.NewRecorder(), req) - - if !called { - t.Errorf("%d: Expected handler to be called.", i) - } - if test.protected != protected { - t.Errorf("%d: Expected protected=%v, got protected=%v.", i, test.protected, protected) - } - } -} - -// TestNotRestRoutesHaveAuth checks that special non-routes are behind authz/authn. -func TestNotRestRoutesHaveAuth(t *testing.T) { - config, _ := setUp(t) - - authz := mockAuthorizer{} - - config.LegacyAPIGroupPrefixes = sets.NewString("/apiPrefix") - config.Authorization.Authorizer = &authz - - config.EnableSwaggerUI = true - config.EnableIndex = true - config.EnableProfiling = true - config.SwaggerConfig = DefaultSwaggerConfig() - - kubeVersion := fakeVersion() - config.Version = &kubeVersion - - s, err := config.Complete(nil).New("test", EmptyDelegate) - if err != nil { - t.Fatalf("Error in bringing up the server: %v", err) - } - - for _, test := range []struct { - route string - }{ - {"/"}, - {"/swagger-ui/"}, - {"/debug/pprof/"}, - {"/version"}, - } { - resp := httptest.NewRecorder() - req, _ := http.NewRequest("GET", test.route, nil) - s.Handler.ServeHTTP(resp, req) - if resp.Code != 200 { - t.Errorf("route %q expected to work: code %d", test.route, resp.Code) - continue - } - - if authz.lastURI != test.route { - t.Errorf("route %q expected to go through authorization, last route did: %q", test.route, authz.lastURI) - } - } -} - -type mockAuthorizer struct { - lastURI string -} - -func (authz *mockAuthorizer) Authorize(a authorizer.Attributes) (authorized authorizer.Decision, reason string, err error) { - authz.lastURI = a.GetPath() - return authorizer.DecisionAllow, "", nil -} - -type mockAuthenticator struct { - lastURI string -} - -func (authn *mockAuthenticator) AuthenticateRequest(req *http.Request) (user.Info, bool, error) { - authn.lastURI = req.RequestURI - return &user.DefaultInfo{ - Name: "foo", - }, true, nil -} - -func decodeResponse(resp *http.Response, obj interface{}) error { - defer resp.Body.Close() - - data, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - if err := json.Unmarshal(data, obj); err != nil { - return err - } - return nil -} - -type testGetterStorage struct { - Version string -} - -func (p *testGetterStorage) New() runtime.Object { - return &metav1.APIGroup{ - TypeMeta: metav1.TypeMeta{ - Kind: "Getter", - APIVersion: p.Version, - }, - } -} - -func (p *testGetterStorage) Get(ctx apirequest.Context, name string, options *metav1.GetOptions) (runtime.Object, error) { - return nil, nil -} - -type testNoVerbsStorage struct { - Version string -} - -func (p *testNoVerbsStorage) New() runtime.Object { - return &metav1.APIGroup{ - TypeMeta: metav1.TypeMeta{ - Kind: "NoVerbs", - APIVersion: p.Version, - }, - } -} - -func fakeVersion() version.Info { - return version.Info{ - Major: "42", - Minor: "42", - GitVersion: "42", - GitCommit: "34973274ccef6ab4dfaaf86599792fa9c3fe4689", - GitTreeState: "Dirty", - BuildDate: time.Now().String(), - GoVersion: goruntime.Version(), - Compiler: goruntime.Compiler, - Platform: fmt.Sprintf("%s/%s", goruntime.GOOS, goruntime.GOARCH), - } -} - -// TestGracefulShutdown verifies server shutdown after request handler finish. -func TestGracefulShutdown(t *testing.T) { - config, _ := setUp(t) - - var graceShutdown bool - wg := sync.WaitGroup{} - wg.Add(1) - - config.BuildHandlerChainFunc = func(apiHandler http.Handler, c *Config) http.Handler { - handler := genericfilters.WithWaitGroup(apiHandler, c.RequestContextMapper, c.LongRunningFunc, c.HandlerChainWaitGroup) - handler = genericapifilters.WithRequestInfo(handler, c.RequestInfoResolver, c.RequestContextMapper) - handler = apirequest.WithRequestContext(handler, c.RequestContextMapper) - return handler - } - - handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - wg.Done() - time.Sleep(2 * time.Second) - w.WriteHeader(http.StatusOK) - graceShutdown = true - }) - - s, err := config.Complete(nil).New("test", EmptyDelegate) - if err != nil { - t.Fatalf("Error in bringing up the server: %v", err) - } - - s.Handler.NonGoRestfulMux.Handle("/test", handler) - - insecureServer := &http.Server{ - Addr: "0.0.0.0:0", - Handler: s.Handler, - } - stopCh := make(chan struct{}) - - ln, err := net.Listen("tcp", insecureServer.Addr) - if err != nil { - t.Errorf("failed to listen on %v: %v", insecureServer.Addr, err) - } - - // get port - serverPort := ln.Addr().(*net.TCPAddr).Port - err = RunServer(insecureServer, ln, 10*time.Second, stopCh) - if err != nil { - t.Errorf("RunServer err: %v", err) - } - - graceCh := make(chan struct{}) - // mock a client request - go func() { - resp, err := http.Get("http://127.0.0.1:" + strconv.Itoa(serverPort) + "/test") - if err != nil { - t.Errorf("Unexpected http error: %v", err) - } - if resp.StatusCode != http.StatusOK { - t.Errorf("Unexpected http status code: %v", resp.StatusCode) - } - close(graceCh) - }() - - // close stopCh after request sent to server to guarantee request handler is running. - wg.Wait() - close(stopCh) - // wait for wait group handler finish - s.HandlerChainWaitGroup.Wait() - - // check server all handlers finished. - if !graceShutdown { - t.Errorf("server shutdown not gracefully.") - } - // check client to make sure receive response. - select { - case <-graceCh: - t.Logf("server shutdown gracefully.") - case <-time.After(30 * time.Second): - t.Errorf("Timed out waiting for response.") - } -} diff --git a/vendor/k8s.io/apiserver/pkg/server/healthz/BUILD b/vendor/k8s.io/apiserver/pkg/server/healthz/BUILD deleted file mode 100644 index f4ccb49650..0000000000 --- a/vendor/k8s.io/apiserver/pkg/server/healthz/BUILD +++ /dev/null @@ -1,36 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["healthz_test.go"], - embed = [":go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = [ - "doc.go", - "healthz.go", - ], - importpath = "k8s.io/apiserver/pkg/server/healthz", - deps = ["//vendor/github.com/golang/glog:go_default_library"], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiserver/pkg/server/healthz/healthz_test.go b/vendor/k8s.io/apiserver/pkg/server/healthz/healthz_test.go deleted file mode 100644 index 99aae5a9ea..0000000000 --- a/vendor/k8s.io/apiserver/pkg/server/healthz/healthz_test.go +++ /dev/null @@ -1,112 +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 healthz - -import ( - "errors" - "fmt" - "net/http" - "net/http/httptest" - "reflect" - "testing" -) - -func TestInstallHandler(t *testing.T) { - mux := http.NewServeMux() - InstallHandler(mux) - req, err := http.NewRequest("GET", "http://example.com/healthz", nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - w := httptest.NewRecorder() - mux.ServeHTTP(w, req) - if w.Code != http.StatusOK { - t.Errorf("expected %v, got %v", http.StatusOK, w.Code) - } - if w.Body.String() != "ok" { - t.Errorf("expected %v, got %v", "ok", w.Body.String()) - } -} - -func TestMulitipleChecks(t *testing.T) { - tests := []struct { - path string - expectedResponse string - expectedStatus int - addBadCheck bool - }{ - {"/healthz?verbose", "[+]ping ok\nhealthz check passed\n", http.StatusOK, false}, - {"/healthz/ping", "ok", http.StatusOK, false}, - {"/healthz", "ok", http.StatusOK, false}, - {"/healthz?verbose", "[+]ping ok\n[-]bad failed: reason withheld\nhealthz check failed\n", http.StatusInternalServerError, true}, - {"/healthz/ping", "ok", http.StatusOK, true}, - {"/healthz/bad", "internal server error: this will fail\n", http.StatusInternalServerError, true}, - {"/healthz", "[+]ping ok\n[-]bad failed: reason withheld\nhealthz check failed\n", http.StatusInternalServerError, true}, - } - - for i, test := range tests { - mux := http.NewServeMux() - checks := []HealthzChecker{PingHealthz} - if test.addBadCheck { - checks = append(checks, NamedCheck("bad", func(_ *http.Request) error { - return errors.New("this will fail") - })) - } - InstallHandler(mux, checks...) - req, err := http.NewRequest("GET", fmt.Sprintf("http://example.com%v", test.path), nil) - if err != nil { - t.Fatalf("case[%d] Unexpected error: %v", i, err) - } - w := httptest.NewRecorder() - mux.ServeHTTP(w, req) - if w.Code != test.expectedStatus { - t.Errorf("case[%d] Expected: %v, got: %v", i, test.expectedStatus, w.Code) - } - if w.Body.String() != test.expectedResponse { - t.Errorf("case[%d] Expected:\n%v\ngot:\n%v\n", i, test.expectedResponse, w.Body.String()) - } - } -} - -func TestCheckerNames(t *testing.T) { - n1 := "n1" - n2 := "n2" - c1 := &healthzCheck{name: n1} - c2 := &healthzCheck{name: n2} - - testCases := []struct { - desc string - have []HealthzChecker - want []string - }{ - {"no checker", []HealthzChecker{}, []string{}}, - {"one checker", []HealthzChecker{c1}, []string{n1}}, - {"other checker", []HealthzChecker{c2}, []string{n2}}, - {"checker order", []HealthzChecker{c1, c2}, []string{n1, n2}}, - {"different checker order", []HealthzChecker{c2, c1}, []string{n2, n1}}, - } - - for _, tc := range testCases { - result := checkerNames(tc.have...) - t.Run(tc.desc, func(t *testing.T) { - if reflect.DeepEqual(tc.want, result) { - t.Errorf("want %#v, got %#v", tc.want, result) - } - }) - } - -} diff --git a/vendor/k8s.io/apiserver/pkg/util/feature/BUILD b/vendor/k8s.io/apiserver/pkg/util/feature/BUILD deleted file mode 100644 index 157aa49e6c..0000000000 --- a/vendor/k8s.io/apiserver/pkg/util/feature/BUILD +++ /dev/null @@ -1,40 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", - "go_test", -) - -go_test( - name = "go_default_test", - srcs = ["feature_gate_test.go"], - embed = [":go_default_library"], - deps = ["//vendor/github.com/spf13/pflag:go_default_library"], -) - -go_library( - name = "go_default_library", - srcs = ["feature_gate.go"], - importpath = "k8s.io/apiserver/pkg/util/feature", - deps = [ - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/github.com/spf13/pflag:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [ - ":package-srcs", - "//staging/src/k8s.io/apiserver/pkg/util/feature/testing:all-srcs", - ], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/apiserver/pkg/util/feature/feature_gate_test.go b/vendor/k8s.io/apiserver/pkg/util/feature/feature_gate_test.go deleted file mode 100644 index 392c875deb..0000000000 --- a/vendor/k8s.io/apiserver/pkg/util/feature/feature_gate_test.go +++ /dev/null @@ -1,191 +0,0 @@ -/* -Copyright 2016 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 feature - -import ( - "fmt" - "strings" - "testing" - - "github.com/spf13/pflag" -) - -func TestFeatureGateFlag(t *testing.T) { - // gates for testing - const testAlphaGate Feature = "TestAlpha" - const testBetaGate Feature = "TestBeta" - - tests := []struct { - arg string - expect map[Feature]bool - parseError string - }{ - { - arg: "", - expect: map[Feature]bool{ - allAlphaGate: false, - testAlphaGate: false, - testBetaGate: false, - }, - }, - { - arg: "fooBarBaz=maybeidk", - expect: map[Feature]bool{ - allAlphaGate: false, - testAlphaGate: false, - testBetaGate: false, - }, - parseError: "unrecognized key: fooBarBaz", - }, - { - arg: "AllAlpha=false", - expect: map[Feature]bool{ - allAlphaGate: false, - testAlphaGate: false, - testBetaGate: false, - }, - }, - { - arg: "AllAlpha=true", - expect: map[Feature]bool{ - allAlphaGate: true, - testAlphaGate: true, - testBetaGate: false, - }, - }, - { - arg: "AllAlpha=banana", - expect: map[Feature]bool{ - allAlphaGate: false, - testAlphaGate: false, - testBetaGate: false, - }, - parseError: "invalid value of AllAlpha", - }, - { - arg: "AllAlpha=false,TestAlpha=true", - expect: map[Feature]bool{ - allAlphaGate: false, - testAlphaGate: true, - testBetaGate: false, - }, - }, - { - arg: "TestAlpha=true,AllAlpha=false", - expect: map[Feature]bool{ - allAlphaGate: false, - testAlphaGate: true, - testBetaGate: false, - }, - }, - { - arg: "AllAlpha=true,TestAlpha=false", - expect: map[Feature]bool{ - allAlphaGate: true, - testAlphaGate: false, - testBetaGate: false, - }, - }, - { - arg: "TestAlpha=false,AllAlpha=true", - expect: map[Feature]bool{ - allAlphaGate: true, - testAlphaGate: false, - testBetaGate: false, - }, - }, - { - arg: "TestBeta=true,AllAlpha=false", - expect: map[Feature]bool{ - allAlphaGate: false, - testAlphaGate: false, - testBetaGate: true, - }, - }, - } - for i, test := range tests { - fs := pflag.NewFlagSet("testfeaturegateflag", pflag.ContinueOnError) - f := NewFeatureGate() - f.Add(map[Feature]FeatureSpec{ - testAlphaGate: {Default: false, PreRelease: Alpha}, - testBetaGate: {Default: false, PreRelease: Beta}, - }) - f.AddFlag(fs) - - err := fs.Parse([]string{fmt.Sprintf("--%s=%s", flagName, test.arg)}) - if test.parseError != "" { - if !strings.Contains(err.Error(), test.parseError) { - t.Errorf("%d: Parse() Expected %v, Got %v", i, test.parseError, err) - } - } else if err != nil { - t.Errorf("%d: Parse() Expected nil, Got %v", i, err) - } - for k, v := range test.expect { - if actual := f.enabled.Load().(map[Feature]bool)[k]; actual != v { - t.Errorf("%d: expected %s=%v, Got %v", i, k, v, actual) - } - } - } -} - -func TestFeatureGateOverride(t *testing.T) { - const testAlphaGate Feature = "TestAlpha" - const testBetaGate Feature = "TestBeta" - - // Don't parse the flag, assert defaults are used. - var f FeatureGate = NewFeatureGate() - f.Add(map[Feature]FeatureSpec{ - testAlphaGate: {Default: false, PreRelease: Alpha}, - testBetaGate: {Default: false, PreRelease: Beta}, - }) - - f.Set("TestAlpha=true,TestBeta=true") - if f.Enabled(testAlphaGate) != true { - t.Errorf("Expected true") - } - if f.Enabled(testBetaGate) != true { - t.Errorf("Expected true") - } - - f.Set("TestAlpha=false") - if f.Enabled(testAlphaGate) != false { - t.Errorf("Expected false") - } - if f.Enabled(testBetaGate) != true { - t.Errorf("Expected true") - } -} - -func TestFeatureGateFlagDefaults(t *testing.T) { - // gates for testing - const testAlphaGate Feature = "TestAlpha" - const testBetaGate Feature = "TestBeta" - - // Don't parse the flag, assert defaults are used. - var f FeatureGate = NewFeatureGate() - f.Add(map[Feature]FeatureSpec{ - testAlphaGate: {Default: false, PreRelease: Alpha}, - testBetaGate: {Default: true, PreRelease: Beta}, - }) - - if f.Enabled(testAlphaGate) != false { - t.Errorf("Expected false") - } - if f.Enabled(testBetaGate) != true { - t.Errorf("Expected true") - } -} diff --git a/vendor/k8s.io/apiserver/pkg/util/logs/BUILD b/vendor/k8s.io/apiserver/pkg/util/logs/BUILD deleted file mode 100644 index 069bb5aba8..0000000000 --- a/vendor/k8s.io/apiserver/pkg/util/logs/BUILD +++ /dev/null @@ -1,30 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load( - "@io_bazel_rules_go//go:def.bzl", - "go_library", -) - -go_library( - name = "go_default_library", - srcs = ["logs.go"], - importpath = "k8s.io/apiserver/pkg/util/logs", - deps = [ - "//vendor/github.com/golang/glog:go_default_library", - "//vendor/github.com/spf13/pflag:go_default_library", - "//vendor/k8s.io/apimachinery/pkg/util/wait:go_default_library", - ], -) - -filegroup( - name = "package-srcs", - srcs = glob(["**"]), - tags = ["automanaged"], - visibility = ["//visibility:private"], -) - -filegroup( - name = "all-srcs", - srcs = [":package-srcs"], - tags = ["automanaged"], -) diff --git a/vendor/k8s.io/client-go/discovery/discovery_client_test.go b/vendor/k8s.io/client-go/discovery/discovery_client_test.go deleted file mode 100644 index 6f4de6b481..0000000000 --- a/vendor/k8s.io/client-go/discovery/discovery_client_test.go +++ /dev/null @@ -1,864 +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 discovery_test - -import ( - "encoding/json" - "fmt" - "mime" - "net/http" - "net/http/httptest" - "reflect" - "testing" - - "github.com/gogo/protobuf/proto" - "github.com/googleapis/gnostic/OpenAPIv2" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/version" - . "k8s.io/client-go/discovery" - restclient "k8s.io/client-go/rest" -) - -func TestGetServerVersion(t *testing.T) { - expect := version.Info{ - Major: "foo", - Minor: "bar", - GitCommit: "baz", - } - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - output, err := json.Marshal(expect) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - defer server.Close() - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - - got, err := client.ServerVersion() - if err != nil { - t.Fatalf("unexpected encoding error: %v", err) - } - if e, a := expect, *got; !reflect.DeepEqual(e, a) { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestGetServerGroupsWithV1Server(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var obj interface{} - switch req.URL.Path { - case "/api": - obj = &metav1.APIVersions{ - Versions: []string{ - "v1", - }, - } - case "/apis": - obj = &metav1.APIGroupList{ - Groups: []metav1.APIGroup{ - { - Name: "extensions", - Versions: []metav1.GroupVersionForDiscovery{ - {GroupVersion: "extensions/v1beta1"}, - }, - }, - }, - } - default: - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(obj) - if err != nil { - t.Fatalf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - defer server.Close() - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - // ServerGroups should not return an error even if server returns error at /api and /apis - apiGroupList, err := client.ServerGroups() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - groupVersions := metav1.ExtractGroupVersions(apiGroupList) - if !reflect.DeepEqual(groupVersions, []string{"v1", "extensions/v1beta1"}) { - t.Errorf("expected: %q, got: %q", []string{"v1", "extensions/v1beta1"}, groupVersions) - } -} - -func TestGetServerGroupsWithBrokenServer(t *testing.T) { - for _, statusCode := range []int{http.StatusNotFound, http.StatusForbidden} { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(statusCode) - })) - defer server.Close() - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - // ServerGroups should not return an error even if server returns Not Found or Forbidden error at all end points - apiGroupList, err := client.ServerGroups() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - groupVersions := metav1.ExtractGroupVersions(apiGroupList) - if len(groupVersions) != 0 { - t.Errorf("expected empty list, got: %q", groupVersions) - } - } -} - -func TestGetServerResourcesWithV1Server(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var obj interface{} - switch req.URL.Path { - case "/api": - obj = &metav1.APIVersions{ - Versions: []string{ - "v1", - }, - } - default: - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(obj) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - defer server.Close() - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - // ServerResources should not return an error even if server returns error at /api/v1. - serverResources, err := client.ServerResources() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - gvs := groupVersions(serverResources) - if !sets.NewString(gvs...).Has("v1") { - t.Errorf("missing v1 in resource list: %v", serverResources) - } -} - -func TestGetServerResources(t *testing.T) { - stable := metav1.APIResourceList{ - GroupVersion: "v1", - APIResources: []metav1.APIResource{ - {Name: "pods", Namespaced: true, Kind: "Pod"}, - {Name: "services", Namespaced: true, Kind: "Service"}, - {Name: "namespaces", Namespaced: false, Kind: "Namespace"}, - }, - } - beta := metav1.APIResourceList{ - GroupVersion: "extensions/v1beta1", - APIResources: []metav1.APIResource{ - {Name: "deployments", Namespaced: true, Kind: "Deployment"}, - {Name: "ingresses", Namespaced: true, Kind: "Ingress"}, - {Name: "jobs", Namespaced: true, Kind: "Job"}, - }, - } - tests := []struct { - resourcesList *metav1.APIResourceList - path string - request string - expectErr bool - }{ - { - resourcesList: &stable, - path: "/api/v1", - request: "v1", - expectErr: false, - }, - { - resourcesList: &beta, - path: "/apis/extensions/v1beta1", - request: "extensions/v1beta1", - expectErr: false, - }, - { - resourcesList: &stable, - path: "/api/v1", - request: "foobar", - expectErr: true, - }, - } - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - var list interface{} - switch req.URL.Path { - case "/api/v1": - list = &stable - case "/apis/extensions/v1beta1": - list = &beta - case "/api": - list = &metav1.APIVersions{ - Versions: []string{ - "v1", - }, - } - case "/apis": - list = &metav1.APIGroupList{ - Groups: []metav1.APIGroup{ - { - Versions: []metav1.GroupVersionForDiscovery{ - {GroupVersion: "extensions/v1beta1"}, - }, - }, - }, - } - default: - t.Logf("unexpected request: %s", req.URL.Path) - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(list) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - defer server.Close() - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - for _, test := range tests { - got, err := client.ServerResourcesForGroupVersion(test.request) - if test.expectErr { - if err == nil { - t.Error("unexpected non-error") - } - continue - } - if err != nil { - t.Errorf("unexpected error: %v", err) - continue - } - if !reflect.DeepEqual(got, test.resourcesList) { - t.Errorf("expected:\n%v\ngot:\n%v\n", test.resourcesList, got) - } - } - - serverResources, err := client.ServerResources() - if err != nil { - t.Errorf("unexpected error: %v", err) - } - serverGroupVersions := sets.NewString(groupVersions(serverResources)...) - for _, api := range []string{"v1", "extensions/v1beta1"} { - if !serverGroupVersions.Has(api) { - t.Errorf("missing expected api %q in %v", api, serverResources) - } - } -} - -var returnedOpenAPI = openapi_v2.Document{ - Definitions: &openapi_v2.Definitions{ - AdditionalProperties: []*openapi_v2.NamedSchema{ - { - Name: "fake.type.1", - Value: &openapi_v2.Schema{ - Properties: &openapi_v2.Properties{ - AdditionalProperties: []*openapi_v2.NamedSchema{ - { - Name: "count", - Value: &openapi_v2.Schema{ - Type: &openapi_v2.TypeItem{ - Value: []string{"integer"}, - }, - }, - }, - }, - }, - }, - }, - { - Name: "fake.type.2", - Value: &openapi_v2.Schema{ - Properties: &openapi_v2.Properties{ - AdditionalProperties: []*openapi_v2.NamedSchema{ - { - Name: "count", - Value: &openapi_v2.Schema{ - Type: &openapi_v2.TypeItem{ - Value: []string{"array"}, - }, - Items: &openapi_v2.ItemsItem{ - Schema: []*openapi_v2.Schema{ - { - Type: &openapi_v2.TypeItem{ - Value: []string{"string"}, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, -} - -func openapiSchemaDeprecatedFakeServer(status int) (*httptest.Server, error) { - var sErr error - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if req.URL.Path == "/openapi/v2" { - // write the error status for the new endpoint request - w.WriteHeader(status) - return - } - if req.URL.Path != "/swagger-2.0.0.pb-v1" { - sErr = fmt.Errorf("Unexpected url %v", req.URL) - } - if req.Method != "GET" { - sErr = fmt.Errorf("Unexpected method %v", req.Method) - } - - mime.AddExtensionType(".pb-v1", "application/com.github.googleapis.gnostic.OpenAPIv2@68f4ded+protobuf") - - output, err := proto.Marshal(&returnedOpenAPI) - if err != nil { - sErr = err - return - } - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - return server, sErr -} - -func openapiSchemaFakeServer() (*httptest.Server, error) { - var sErr error - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if req.URL.Path != "/openapi/v2" { - sErr = fmt.Errorf("Unexpected url %v", req.URL) - } - if req.Method != "GET" { - sErr = fmt.Errorf("Unexpected method %v", req.Method) - } - decipherableFormat := req.Header.Get("Accept") - if decipherableFormat != "application/com.github.proto-openapi.spec.v2@v1.0+protobuf" { - sErr = fmt.Errorf("Unexpected accept mime type %v", decipherableFormat) - } - - mime.AddExtensionType(".pb-v1", "application/com.github.googleapis.gnostic.OpenAPIv2@68f4ded+protobuf") - - output, err := proto.Marshal(&returnedOpenAPI) - if err != nil { - sErr = err - return - } - w.WriteHeader(http.StatusOK) - w.Write(output) - })) - return server, sErr -} - -func TestGetOpenAPISchema(t *testing.T) { - server, err := openapiSchemaFakeServer() - if err != nil { - t.Errorf("unexpected error starting fake server: %v", err) - } - defer server.Close() - - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - got, err := client.OpenAPISchema() - if err != nil { - t.Fatalf("unexpected error getting openapi: %v", err) - } - if e, a := returnedOpenAPI, *got; !reflect.DeepEqual(e, a) { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestGetOpenAPISchemaForbiddenFallback(t *testing.T) { - server, err := openapiSchemaDeprecatedFakeServer(http.StatusForbidden) - if err != nil { - t.Errorf("unexpected error starting fake server: %v", err) - } - defer server.Close() - - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - got, err := client.OpenAPISchema() - if err != nil { - t.Fatalf("unexpected error getting openapi: %v", err) - } - if e, a := returnedOpenAPI, *got; !reflect.DeepEqual(e, a) { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestGetOpenAPISchemaNotFoundFallback(t *testing.T) { - server, err := openapiSchemaDeprecatedFakeServer(http.StatusNotFound) - if err != nil { - t.Errorf("unexpected error starting fake server: %v", err) - } - defer server.Close() - - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - got, err := client.OpenAPISchema() - if err != nil { - t.Fatalf("unexpected error getting openapi: %v", err) - } - if e, a := returnedOpenAPI, *got; !reflect.DeepEqual(e, a) { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestGetOpenAPISchemaNotAcceptableFallback(t *testing.T) { - server, err := openapiSchemaDeprecatedFakeServer(http.StatusNotAcceptable) - if err != nil { - t.Errorf("unexpected error starting fake server: %v", err) - } - defer server.Close() - - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - got, err := client.OpenAPISchema() - if err != nil { - t.Fatalf("unexpected error getting openapi: %v", err) - } - if e, a := returnedOpenAPI, *got; !reflect.DeepEqual(e, a) { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestServerPreferredResources(t *testing.T) { - stable := metav1.APIResourceList{ - GroupVersion: "v1", - APIResources: []metav1.APIResource{ - {Name: "pods", Namespaced: true, Kind: "Pod"}, - {Name: "services", Namespaced: true, Kind: "Service"}, - {Name: "namespaces", Namespaced: false, Kind: "Namespace"}, - }, - } - tests := []struct { - resourcesList []*metav1.APIResourceList - response func(w http.ResponseWriter, req *http.Request) - expectErr func(err error) bool - }{ - { - resourcesList: []*metav1.APIResourceList{&stable}, - expectErr: IsGroupDiscoveryFailedError, - response: func(w http.ResponseWriter, req *http.Request) { - var list interface{} - switch req.URL.Path { - case "/apis/extensions/v1beta1": - w.WriteHeader(http.StatusInternalServerError) - return - case "/api/v1": - list = &stable - case "/api": - list = &metav1.APIVersions{ - Versions: []string{ - "v1", - }, - } - case "/apis": - list = &metav1.APIGroupList{ - Groups: []metav1.APIGroup{ - { - Versions: []metav1.GroupVersionForDiscovery{ - {GroupVersion: "extensions/v1beta1"}, - }, - }, - }, - } - default: - t.Logf("unexpected request: %s", req.URL.Path) - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(list) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - }, - }, - { - resourcesList: nil, - expectErr: IsGroupDiscoveryFailedError, - response: func(w http.ResponseWriter, req *http.Request) { - var list interface{} - switch req.URL.Path { - case "/apis/extensions/v1beta1": - w.WriteHeader(http.StatusInternalServerError) - return - case "/api/v1": - w.WriteHeader(http.StatusInternalServerError) - case "/api": - list = &metav1.APIVersions{ - Versions: []string{ - "v1", - }, - } - case "/apis": - list = &metav1.APIGroupList{ - Groups: []metav1.APIGroup{ - { - Versions: []metav1.GroupVersionForDiscovery{ - {GroupVersion: "extensions/v1beta1"}, - }, - }, - }, - } - default: - t.Logf("unexpected request: %s", req.URL.Path) - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(list) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - }, - }, - } - for _, test := range tests { - server := httptest.NewServer(http.HandlerFunc(test.response)) - defer server.Close() - - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - resources, err := client.ServerPreferredResources() - if test.expectErr != nil { - if err == nil { - t.Error("unexpected non-error") - } - - continue - } - if err != nil { - t.Errorf("unexpected error: %v", err) - continue - } - got, err := GroupVersionResources(resources) - if err != nil { - t.Errorf("unexpected error: %v", err) - continue - } - expected, _ := GroupVersionResources(test.resourcesList) - if !reflect.DeepEqual(got, expected) { - t.Errorf("expected:\n%v\ngot:\n%v\n", test.resourcesList, got) - } - server.Close() - } -} - -func TestServerPreferredResourcesRetries(t *testing.T) { - stable := metav1.APIResourceList{ - GroupVersion: "v1", - APIResources: []metav1.APIResource{ - {Name: "pods", Namespaced: true, Kind: "Pod"}, - }, - } - beta := metav1.APIResourceList{ - GroupVersion: "extensions/v1", - APIResources: []metav1.APIResource{ - {Name: "deployments", Namespaced: true, Kind: "Deployment"}, - }, - } - - response := func(numErrors int) http.HandlerFunc { - var i = 0 - return func(w http.ResponseWriter, req *http.Request) { - var list interface{} - switch req.URL.Path { - case "/apis/extensions/v1beta1": - if i < numErrors { - i++ - w.WriteHeader(http.StatusInternalServerError) - return - } - list = &beta - case "/api/v1": - list = &stable - case "/api": - list = &metav1.APIVersions{ - Versions: []string{ - "v1", - }, - } - case "/apis": - list = &metav1.APIGroupList{ - Groups: []metav1.APIGroup{ - { - Name: "extensions", - Versions: []metav1.GroupVersionForDiscovery{ - {GroupVersion: "extensions/v1beta1"}, - }, - PreferredVersion: metav1.GroupVersionForDiscovery{ - GroupVersion: "extensions/v1beta1", - Version: "v1beta1", - }, - }, - }, - } - default: - t.Logf("unexpected request: %s", req.URL.Path) - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(list) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - } - } - tests := []struct { - responseErrors int - expectResources int - expectedError func(err error) bool - }{ - { - responseErrors: 1, - expectResources: 2, - expectedError: func(err error) bool { - return err == nil - }, - }, - { - responseErrors: 2, - expectResources: 1, - expectedError: IsGroupDiscoveryFailedError, - }, - } - - for i, tc := range tests { - server := httptest.NewServer(http.HandlerFunc(response(tc.responseErrors))) - defer server.Close() - - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - resources, err := client.ServerPreferredResources() - if !tc.expectedError(err) { - t.Errorf("case %d: unexpected error: %v", i, err) - } - got, err := GroupVersionResources(resources) - if err != nil { - t.Errorf("case %d: unexpected error: %v", i, err) - } - if len(got) != tc.expectResources { - t.Errorf("case %d: expect %d resources, got %#v", i, tc.expectResources, got) - } - server.Close() - } -} - -func TestServerPreferredNamespacedResources(t *testing.T) { - stable := metav1.APIResourceList{ - GroupVersion: "v1", - APIResources: []metav1.APIResource{ - {Name: "pods", Namespaced: true, Kind: "Pod"}, - {Name: "services", Namespaced: true, Kind: "Service"}, - {Name: "namespaces", Namespaced: false, Kind: "Namespace"}, - }, - } - batchv1 := metav1.APIResourceList{ - GroupVersion: "batch/v1", - APIResources: []metav1.APIResource{ - {Name: "jobs", Namespaced: true, Kind: "Job"}, - }, - } - batchv2alpha1 := metav1.APIResourceList{ - GroupVersion: "batch/v2alpha1", - APIResources: []metav1.APIResource{ - {Name: "jobs", Namespaced: true, Kind: "Job"}, - {Name: "cronjobs", Namespaced: true, Kind: "CronJob"}, - }, - } - batchv3alpha1 := metav1.APIResourceList{ - GroupVersion: "batch/v3alpha1", - APIResources: []metav1.APIResource{ - {Name: "jobs", Namespaced: true, Kind: "Job"}, - {Name: "cronjobs", Namespaced: true, Kind: "CronJob"}, - }, - } - tests := []struct { - response func(w http.ResponseWriter, req *http.Request) - expected map[schema.GroupVersionResource]struct{} - }{ - { - response: func(w http.ResponseWriter, req *http.Request) { - var list interface{} - switch req.URL.Path { - case "/api/v1": - list = &stable - case "/api": - list = &metav1.APIVersions{ - Versions: []string{ - "v1", - }, - } - default: - t.Logf("unexpected request: %s", req.URL.Path) - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(list) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - }, - expected: map[schema.GroupVersionResource]struct{}{ - {Group: "", Version: "v1", Resource: "pods"}: {}, - {Group: "", Version: "v1", Resource: "services"}: {}, - }, - }, - { - response: func(w http.ResponseWriter, req *http.Request) { - var list interface{} - switch req.URL.Path { - case "/apis": - list = &metav1.APIGroupList{ - Groups: []metav1.APIGroup{ - { - Name: "batch", - Versions: []metav1.GroupVersionForDiscovery{ - {GroupVersion: "batch/v1", Version: "v1"}, - {GroupVersion: "batch/v2alpha1", Version: "v2alpha1"}, - {GroupVersion: "batch/v3alpha1", Version: "v3alpha1"}, - }, - PreferredVersion: metav1.GroupVersionForDiscovery{GroupVersion: "batch/v1", Version: "v1"}, - }, - }, - } - case "/apis/batch/v1": - list = &batchv1 - case "/apis/batch/v2alpha1": - list = &batchv2alpha1 - case "/apis/batch/v3alpha1": - list = &batchv3alpha1 - default: - t.Logf("unexpected request: %s", req.URL.Path) - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(list) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - }, - expected: map[schema.GroupVersionResource]struct{}{ - {Group: "batch", Version: "v1", Resource: "jobs"}: {}, - {Group: "batch", Version: "v2alpha1", Resource: "cronjobs"}: {}, - }, - }, - { - response: func(w http.ResponseWriter, req *http.Request) { - var list interface{} - switch req.URL.Path { - case "/apis": - list = &metav1.APIGroupList{ - Groups: []metav1.APIGroup{ - { - Name: "batch", - Versions: []metav1.GroupVersionForDiscovery{ - {GroupVersion: "batch/v1", Version: "v1"}, - {GroupVersion: "batch/v2alpha1", Version: "v2alpha1"}, - {GroupVersion: "batch/v3alpha1", Version: "v3alpha1"}, - }, - PreferredVersion: metav1.GroupVersionForDiscovery{GroupVersion: "batch/v2alpha", Version: "v2alpha1"}, - }, - }, - } - case "/apis/batch/v1": - list = &batchv1 - case "/apis/batch/v2alpha1": - list = &batchv2alpha1 - case "/apis/batch/v3alpha1": - list = &batchv3alpha1 - default: - t.Logf("unexpected request: %s", req.URL.Path) - w.WriteHeader(http.StatusNotFound) - return - } - output, err := json.Marshal(list) - if err != nil { - t.Errorf("unexpected encoding error: %v", err) - return - } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - w.Write(output) - }, - expected: map[schema.GroupVersionResource]struct{}{ - {Group: "batch", Version: "v2alpha1", Resource: "jobs"}: {}, - {Group: "batch", Version: "v2alpha1", Resource: "cronjobs"}: {}, - }, - }, - } - for i, test := range tests { - server := httptest.NewServer(http.HandlerFunc(test.response)) - defer server.Close() - - client := NewDiscoveryClientForConfigOrDie(&restclient.Config{Host: server.URL}) - resources, err := client.ServerPreferredNamespacedResources() - if err != nil { - t.Errorf("[%d] unexpected error: %v", i, err) - continue - } - got, err := GroupVersionResources(resources) - if err != nil { - t.Errorf("[%d] unexpected error: %v", i, err) - continue - } - - if !reflect.DeepEqual(got, test.expected) { - t.Errorf("[%d] expected:\n%v\ngot:\n%v\n", i, test.expected, got) - } - server.Close() - } -} - -func groupVersions(resources []*metav1.APIResourceList) []string { - result := []string{} - for _, resourceList := range resources { - result = append(result, resourceList.GroupVersion) - } - return result -} diff --git a/vendor/k8s.io/client-go/discovery/fake/discovery_test.go b/vendor/k8s.io/client-go/discovery/fake/discovery_test.go deleted file mode 100644 index cfdcf1a23d..0000000000 --- a/vendor/k8s.io/client-go/discovery/fake/discovery_test.go +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright 2017 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 fake_test - -import ( - "testing" - - "k8s.io/apimachinery/pkg/version" - fakediscovery "k8s.io/client-go/discovery/fake" - fakeclientset "k8s.io/client-go/kubernetes/fake" -) - -func TestFakingServerVersion(t *testing.T) { - client := fakeclientset.NewSimpleClientset() - fakeDiscovery, ok := client.Discovery().(*fakediscovery.FakeDiscovery) - if !ok { - t.Fatalf("couldn't convert Discovery() to *FakeDiscovery") - } - - testGitCommit := "v1.0.0" - fakeDiscovery.FakedServerVersion = &version.Info{ - GitCommit: testGitCommit, - } - - sv, err := client.Discovery().ServerVersion() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if sv.GitCommit != testGitCommit { - t.Fatalf("unexpected faked discovery return value: %q", sv.GitCommit) - } -} diff --git a/vendor/k8s.io/client-go/discovery/helper_blackbox_test.go b/vendor/k8s.io/client-go/discovery/helper_blackbox_test.go deleted file mode 100644 index 9cd85cb168..0000000000 --- a/vendor/k8s.io/client-go/discovery/helper_blackbox_test.go +++ /dev/null @@ -1,184 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package discovery_test - -import ( - "bytes" - "encoding/json" - "errors" - "io" - "io/ioutil" - "net/http" - "strings" - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/client-go/discovery" - "k8s.io/client-go/kubernetes/scheme" - restclient "k8s.io/client-go/rest" - "k8s.io/client-go/rest/fake" -) - -func objBody(object interface{}) io.ReadCloser { - output, err := json.MarshalIndent(object, "", "") - if err != nil { - panic(err) - } - return ioutil.NopCloser(bytes.NewReader([]byte(output))) -} - -func TestServerSupportsVersion(t *testing.T) { - tests := []struct { - name string - requiredVersion schema.GroupVersion - serverVersions []string - expectErr func(err error) bool - sendErr error - statusCode int - }{ - { - name: "explicit version supported", - requiredVersion: schema.GroupVersion{Version: "v1"}, - serverVersions: []string{"/version1", v1.SchemeGroupVersion.String()}, - statusCode: http.StatusOK, - }, - { - name: "explicit version not supported on server", - requiredVersion: schema.GroupVersion{Version: "v1"}, - serverVersions: []string{"version1"}, - expectErr: func(err error) bool { return strings.Contains(err.Error(), `server does not support API version "v1"`) }, - statusCode: http.StatusOK, - }, - { - name: "connection refused error", - serverVersions: []string{"version1"}, - sendErr: errors.New("connection refused"), - expectErr: func(err error) bool { return strings.Contains(err.Error(), "connection refused") }, - statusCode: http.StatusOK, - }, - { - name: "discovery fails due to 404 Not Found errors and thus serverVersions is empty, use requested GroupVersion", - requiredVersion: schema.GroupVersion{Version: "version1"}, - statusCode: http.StatusNotFound, - }, - } - - for _, test := range tests { - fakeClient := &fake.RESTClient{ - NegotiatedSerializer: scheme.Codecs, - Resp: &http.Response{ - StatusCode: test.statusCode, - Body: objBody(&metav1.APIVersions{Versions: test.serverVersions}), - }, - Client: fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) { - if test.sendErr != nil { - return nil, test.sendErr - } - header := http.Header{} - header.Set("Content-Type", runtime.ContentTypeJSON) - return &http.Response{StatusCode: test.statusCode, Header: header, Body: objBody(&metav1.APIVersions{Versions: test.serverVersions})}, nil - }), - } - c := discovery.NewDiscoveryClientForConfigOrDie(&restclient.Config{}) - c.RESTClient().(*restclient.RESTClient).Client = fakeClient.Client - err := discovery.ServerSupportsVersion(c, test.requiredVersion) - if err == nil && test.expectErr != nil { - t.Errorf("expected error, got nil for [%s].", test.name) - } - if err != nil { - if test.expectErr == nil || !test.expectErr(err) { - t.Errorf("unexpected error for [%s]: %v.", test.name, err) - } - continue - } - } -} - -func TestFilteredBy(t *testing.T) { - all := discovery.ResourcePredicateFunc(func(gv string, r *metav1.APIResource) bool { - return true - }) - none := discovery.ResourcePredicateFunc(func(gv string, r *metav1.APIResource) bool { - return false - }) - onlyV2 := discovery.ResourcePredicateFunc(func(gv string, r *metav1.APIResource) bool { - return strings.HasSuffix(gv, "/v2") || gv == "v2" - }) - onlyBar := discovery.ResourcePredicateFunc(func(gv string, r *metav1.APIResource) bool { - return r.Kind == "Bar" - }) - - foo := []*metav1.APIResourceList{ - { - GroupVersion: "foo/v1", - APIResources: []metav1.APIResource{ - {Name: "bar", Kind: "Bar"}, - {Name: "test", Kind: "Test"}, - }, - }, - { - GroupVersion: "foo/v2", - APIResources: []metav1.APIResource{ - {Name: "bar", Kind: "Bar"}, - {Name: "test", Kind: "Test"}, - }, - }, - { - GroupVersion: "foo/v3", - APIResources: []metav1.APIResource{}, - }, - } - - tests := []struct { - input []*metav1.APIResourceList - pred discovery.ResourcePredicate - expectedResources []string - }{ - {nil, all, []string{}}, - {[]*metav1.APIResourceList{ - {GroupVersion: "foo/v1"}, - }, all, []string{}}, - {foo, all, []string{"foo/v1.bar", "foo/v1.test", "foo/v2.bar", "foo/v2.test"}}, - {foo, onlyV2, []string{"foo/v2.bar", "foo/v2.test"}}, - {foo, onlyBar, []string{"foo/v1.bar", "foo/v2.bar"}}, - {foo, none, []string{}}, - } - for i, test := range tests { - filtered := discovery.FilteredBy(test.pred, test.input) - - if expected, got := sets.NewString(test.expectedResources...), sets.NewString(stringify(filtered)...); !expected.Equal(got) { - t.Errorf("[%d] unexpected group versions: expected=%v, got=%v", i, test.expectedResources, stringify(filtered)) - } - } -} - -func stringify(rls []*metav1.APIResourceList) []string { - result := []string{} - for _, rl := range rls { - for _, r := range rl.APIResources { - result = append(result, rl.GroupVersion+"."+r.Name) - } - if len(rl.APIResources) == 0 { - result = append(result, rl.GroupVersion) - } - } - return result -} diff --git a/vendor/k8s.io/client-go/discovery/restmapper_test.go b/vendor/k8s.io/client-go/discovery/restmapper_test.go deleted file mode 100644 index 69ee7e6864..0000000000 --- a/vendor/k8s.io/client-go/discovery/restmapper_test.go +++ /dev/null @@ -1,384 +0,0 @@ -/* -Copyright 2016 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 discovery_test - -import ( - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/version" - . "k8s.io/client-go/discovery" - restclient "k8s.io/client-go/rest" - "k8s.io/client-go/rest/fake" - - "github.com/googleapis/gnostic/OpenAPIv2" - "github.com/stretchr/testify/assert" -) - -func TestRESTMapper(t *testing.T) { - resources := []*APIGroupResources{ - { - Group: metav1.APIGroup{ - Name: "extensions", - Versions: []metav1.GroupVersionForDiscovery{ - {Version: "v1beta"}, - }, - PreferredVersion: metav1.GroupVersionForDiscovery{Version: "v1beta"}, - }, - VersionedResources: map[string][]metav1.APIResource{ - "v1beta": { - {Name: "jobs", Namespaced: true, Kind: "Job"}, - {Name: "pods", Namespaced: true, Kind: "Pod"}, - }, - }, - }, - { - Group: metav1.APIGroup{ - Versions: []metav1.GroupVersionForDiscovery{ - {Version: "v1"}, - {Version: "v2"}, - }, - PreferredVersion: metav1.GroupVersionForDiscovery{Version: "v1"}, - }, - VersionedResources: map[string][]metav1.APIResource{ - "v1": { - {Name: "pods", Namespaced: true, Kind: "Pod"}, - }, - "v2": { - {Name: "pods", Namespaced: true, Kind: "Pod"}, - }, - }, - }, - - // This group tests finding and prioritizing resources that only exist in non-preferred versions - { - Group: metav1.APIGroup{ - Name: "unpreferred", - Versions: []metav1.GroupVersionForDiscovery{ - {Version: "v1"}, - {Version: "v2beta1"}, - {Version: "v2alpha1"}, - }, - PreferredVersion: metav1.GroupVersionForDiscovery{Version: "v1"}, - }, - VersionedResources: map[string][]metav1.APIResource{ - "v1": { - {Name: "broccoli", Namespaced: true, Kind: "Broccoli"}, - }, - "v2beta1": { - {Name: "broccoli", Namespaced: true, Kind: "Broccoli"}, - {Name: "peas", Namespaced: true, Kind: "Pea"}, - }, - "v2alpha1": { - {Name: "broccoli", Namespaced: true, Kind: "Broccoli"}, - {Name: "peas", Namespaced: true, Kind: "Pea"}, - }, - }, - }, - } - - restMapper := NewRESTMapper(resources, nil) - - kindTCs := []struct { - input schema.GroupVersionResource - want schema.GroupVersionKind - }{ - { - input: schema.GroupVersionResource{ - Resource: "pods", - }, - want: schema.GroupVersionKind{ - Version: "v1", - Kind: "Pod", - }, - }, - { - input: schema.GroupVersionResource{ - Version: "v1", - Resource: "pods", - }, - want: schema.GroupVersionKind{ - Version: "v1", - Kind: "Pod", - }, - }, - { - input: schema.GroupVersionResource{ - Version: "v2", - Resource: "pods", - }, - want: schema.GroupVersionKind{ - Version: "v2", - Kind: "Pod", - }, - }, - { - input: schema.GroupVersionResource{ - Resource: "pods", - }, - want: schema.GroupVersionKind{ - Version: "v1", - Kind: "Pod", - }, - }, - { - input: schema.GroupVersionResource{ - Resource: "jobs", - }, - want: schema.GroupVersionKind{ - Group: "extensions", - Version: "v1beta", - Kind: "Job", - }, - }, - { - input: schema.GroupVersionResource{ - Resource: "peas", - }, - want: schema.GroupVersionKind{ - Group: "unpreferred", - Version: "v2beta1", - Kind: "Pea", - }, - }, - } - - for _, tc := range kindTCs { - got, err := restMapper.KindFor(tc.input) - if err != nil { - t.Errorf("KindFor(%#v) unexpected error: %v", tc.input, err) - continue - } - - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("KindFor(%#v) = %#v, want %#v", tc.input, got, tc.want) - } - } - - resourceTCs := []struct { - input schema.GroupVersionResource - want schema.GroupVersionResource - }{ - { - input: schema.GroupVersionResource{ - Resource: "pods", - }, - want: schema.GroupVersionResource{ - Version: "v1", - Resource: "pods", - }, - }, - { - input: schema.GroupVersionResource{ - Version: "v1", - Resource: "pods", - }, - want: schema.GroupVersionResource{ - Version: "v1", - Resource: "pods", - }, - }, - { - input: schema.GroupVersionResource{ - Version: "v2", - Resource: "pods", - }, - want: schema.GroupVersionResource{ - Version: "v2", - Resource: "pods", - }, - }, - { - input: schema.GroupVersionResource{ - Resource: "pods", - }, - want: schema.GroupVersionResource{ - Version: "v1", - Resource: "pods", - }, - }, - { - input: schema.GroupVersionResource{ - Resource: "jobs", - }, - want: schema.GroupVersionResource{ - Group: "extensions", - Version: "v1beta", - Resource: "jobs", - }, - }, - } - - for _, tc := range resourceTCs { - got, err := restMapper.ResourceFor(tc.input) - if err != nil { - t.Errorf("ResourceFor(%#v) unexpected error: %v", tc.input, err) - continue - } - - if !reflect.DeepEqual(got, tc.want) { - t.Errorf("ResourceFor(%#v) = %#v, want %#v", tc.input, got, tc.want) - } - } -} - -func TestDeferredDiscoveryRESTMapper_CacheMiss(t *testing.T) { - assert := assert.New(t) - - cdc := fakeCachedDiscoveryInterface{fresh: false} - m := NewDeferredDiscoveryRESTMapper(&cdc, nil) - assert.False(cdc.fresh, "should NOT be fresh after instantiation") - assert.Zero(cdc.invalidateCalls, "should not have called Invalidate()") - - gvk, err := m.KindFor(schema.GroupVersionResource{ - Group: "a", - Version: "v1", - Resource: "foo", - }) - assert.NoError(err) - assert.True(cdc.fresh, "should be fresh after a cache-miss") - assert.Equal(cdc.invalidateCalls, 1, "should have called Invalidate() once") - assert.Equal(gvk.Kind, "Foo") - - gvk, err = m.KindFor(schema.GroupVersionResource{ - Group: "a", - Version: "v1", - Resource: "foo", - }) - assert.NoError(err) - assert.Equal(cdc.invalidateCalls, 1, "should NOT have called Invalidate() again") - - gvk, err = m.KindFor(schema.GroupVersionResource{ - Group: "a", - Version: "v1", - Resource: "bar", - }) - assert.Error(err) - assert.Equal(cdc.invalidateCalls, 1, "should NOT have called Invalidate() again after another cache-miss, but with fresh==true") - - cdc.fresh = false - gvk, err = m.KindFor(schema.GroupVersionResource{ - Group: "a", - Version: "v1", - Resource: "bar", - }) - assert.Error(err) - assert.Equal(cdc.invalidateCalls, 2, "should HAVE called Invalidate() again after another cache-miss, but with fresh==false") -} - -type fakeCachedDiscoveryInterface struct { - invalidateCalls int - fresh bool - enabledA bool -} - -var _ CachedDiscoveryInterface = &fakeCachedDiscoveryInterface{} - -func (c *fakeCachedDiscoveryInterface) Fresh() bool { - return c.fresh -} - -func (c *fakeCachedDiscoveryInterface) Invalidate() { - c.invalidateCalls = c.invalidateCalls + 1 - c.fresh = true - c.enabledA = true -} - -func (c *fakeCachedDiscoveryInterface) RESTClient() restclient.Interface { - return &fake.RESTClient{} -} - -func (c *fakeCachedDiscoveryInterface) ServerGroups() (*metav1.APIGroupList, error) { - if c.enabledA { - return &metav1.APIGroupList{ - Groups: []metav1.APIGroup{ - { - Name: "a", - Versions: []metav1.GroupVersionForDiscovery{ - { - GroupVersion: "a/v1", - Version: "v1", - }, - }, - PreferredVersion: metav1.GroupVersionForDiscovery{ - GroupVersion: "a/v1", - Version: "v1", - }, - }, - }, - }, nil - } - return &metav1.APIGroupList{}, nil -} - -func (c *fakeCachedDiscoveryInterface) ServerResourcesForGroupVersion(groupVersion string) (*metav1.APIResourceList, error) { - if c.enabledA && groupVersion == "a/v1" { - return &metav1.APIResourceList{ - GroupVersion: "a/v1", - APIResources: []metav1.APIResource{ - { - Name: "foo", - Kind: "Foo", - Namespaced: false, - }, - }, - }, nil - } - - return nil, errors.NewNotFound(schema.GroupResource{}, "") -} - -func (c *fakeCachedDiscoveryInterface) ServerResources() ([]*metav1.APIResourceList, error) { - if c.enabledA { - av1, _ := c.ServerResourcesForGroupVersion("a/v1") - return []*metav1.APIResourceList{av1}, nil - } - return []*metav1.APIResourceList{}, nil -} - -func (c *fakeCachedDiscoveryInterface) ServerPreferredResources() ([]*metav1.APIResourceList, error) { - if c.enabledA { - return []*metav1.APIResourceList{ - { - GroupVersion: "a/v1", - APIResources: []metav1.APIResource{ - { - Name: "foo", - Kind: "Foo", - Verbs: []string{}, - }, - }, - }, - }, nil - } - return nil, nil -} - -func (c *fakeCachedDiscoveryInterface) ServerPreferredNamespacedResources() ([]*metav1.APIResourceList, error) { - return nil, nil -} - -func (c *fakeCachedDiscoveryInterface) ServerVersion() (*version.Info, error) { - return &version.Info{}, nil -} - -func (c *fakeCachedDiscoveryInterface) OpenAPISchema() (*openapi_v2.Document, error) { - return &openapi_v2.Document{}, nil -} diff --git a/vendor/k8s.io/client-go/listers/extensions/v1beta1/daemonset_expansion_test.go b/vendor/k8s.io/client-go/listers/extensions/v1beta1/daemonset_expansion_test.go deleted file mode 100644 index 77180854ed..0000000000 --- a/vendor/k8s.io/client-go/listers/extensions/v1beta1/daemonset_expansion_test.go +++ /dev/null @@ -1,152 +0,0 @@ -/* -Copyright 2017 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 v1beta1 - -import ( - "testing" - - "k8s.io/api/core/v1" - extensions "k8s.io/api/extensions/v1beta1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/client-go/tools/cache" -) - -func TestDaemonSetLister(t *testing.T) { - store := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{"namespace": cache.MetaNamespaceIndexFunc}) - lister := NewDaemonSetLister(store) - testCases := []struct { - inDSs []*extensions.DaemonSet - list func() ([]*extensions.DaemonSet, error) - outDaemonSetNames sets.String - expectErr bool - }{ - // Basic listing - { - inDSs: []*extensions.DaemonSet{ - {ObjectMeta: metav1.ObjectMeta{Name: "basic"}}, - }, - list: func() ([]*extensions.DaemonSet, error) { - return lister.List(labels.Everything()) - }, - outDaemonSetNames: sets.NewString("basic"), - }, - // Listing multiple daemon sets - { - inDSs: []*extensions.DaemonSet{ - {ObjectMeta: metav1.ObjectMeta{Name: "basic"}}, - {ObjectMeta: metav1.ObjectMeta{Name: "complex"}}, - {ObjectMeta: metav1.ObjectMeta{Name: "complex2"}}, - }, - list: func() ([]*extensions.DaemonSet, error) { - return lister.List(labels.Everything()) - }, - outDaemonSetNames: sets.NewString("basic", "complex", "complex2"), - }, - // No pod labels - { - inDSs: []*extensions.DaemonSet{ - { - ObjectMeta: metav1.ObjectMeta{Name: "basic", Namespace: "ns"}, - Spec: extensions.DaemonSetSpec{ - Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "baz"}}, - }, - }, - }, - list: func() ([]*extensions.DaemonSet, error) { - pod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "pod1", Namespace: "ns"}, - } - return lister.GetPodDaemonSets(pod) - }, - outDaemonSetNames: sets.NewString(), - expectErr: true, - }, - // No DS selectors - { - inDSs: []*extensions.DaemonSet{ - { - ObjectMeta: metav1.ObjectMeta{Name: "basic", Namespace: "ns"}, - }, - }, - list: func() ([]*extensions.DaemonSet, error) { - pod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pod1", - Namespace: "ns", - Labels: map[string]string{"foo": "bar"}, - }, - } - return lister.GetPodDaemonSets(pod) - }, - outDaemonSetNames: sets.NewString(), - expectErr: true, - }, - // Matching labels to selectors and namespace - { - inDSs: []*extensions.DaemonSet{ - { - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: extensions.DaemonSetSpec{ - Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{Name: "bar", Namespace: "ns"}, - Spec: extensions.DaemonSetSpec{ - Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, - }, - }, - }, - list: func() ([]*extensions.DaemonSet, error) { - pod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pod1", - Labels: map[string]string{"foo": "bar"}, - Namespace: "ns", - }, - } - return lister.GetPodDaemonSets(pod) - }, - outDaemonSetNames: sets.NewString("bar"), - }, - } - for _, c := range testCases { - for _, r := range c.inDSs { - store.Add(r) - } - - daemonSets, err := c.list() - if err != nil && c.expectErr { - continue - } else if c.expectErr { - t.Error("Expected error, got none") - continue - } else if err != nil { - t.Errorf("Unexpected error %#v", err) - continue - } - daemonSetNames := make([]string, len(daemonSets)) - for ix := range daemonSets { - daemonSetNames[ix] = daemonSets[ix].Name - } - if !c.outDaemonSetNames.HasAll(daemonSetNames...) || len(daemonSetNames) != len(c.outDaemonSetNames) { - t.Errorf("Unexpected got controllers %+v expected %+v", daemonSetNames, c.outDaemonSetNames) - } - } -} diff --git a/vendor/k8s.io/client-go/plugin/pkg/client/auth/azure/azure_test.go b/vendor/k8s.io/client-go/plugin/pkg/client/auth/azure/azure_test.go deleted file mode 100644 index b420712bc1..0000000000 --- a/vendor/k8s.io/client-go/plugin/pkg/client/auth/azure/azure_test.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright 2017 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 azure - -import ( - "strconv" - "strings" - "sync" - "testing" - "time" - - "github.com/Azure/go-autorest/autorest/adal" -) - -func TestAzureTokenSource(t *testing.T) { - fakeAccessToken := "fake token 1" - fakeSource := fakeTokenSource{ - accessToken: fakeAccessToken, - expiresOn: strconv.FormatInt(time.Now().Add(3600*time.Second).Unix(), 10), - } - cfg := make(map[string]string) - persiter := &fakePersister{cache: make(map[string]string)} - tokenCache := newAzureTokenCache() - tokenSource := newAzureTokenSource(&fakeSource, tokenCache, cfg, persiter) - token, err := tokenSource.Token() - if err != nil { - t.Errorf("failed to retrieve the token form cache: %v", err) - } - - wantCacheLen := 1 - if len(tokenCache.cache) != wantCacheLen { - t.Errorf("Token() cache length error: got %v, want %v", len(tokenCache.cache), wantCacheLen) - } - - if token != tokenCache.cache[azureTokenKey] { - t.Error("Token() returned token != cached token") - } - - wantCfg := token2Cfg(token) - persistedCfg := persiter.Cache() - for k, v := range persistedCfg { - if strings.Compare(v, wantCfg[k]) != 0 { - t.Errorf("Token() persisted cfg %s: got %v, want %v", k, v, wantCfg[k]) - } - } - - fakeSource.accessToken = "fake token 2" - token, err = tokenSource.Token() - if err != nil { - t.Errorf("failed to retrieve the cached token: %v", err) - } - - if token.token.AccessToken != fakeAccessToken { - t.Errorf("Token() didn't return the cached token") - } -} - -type fakePersister struct { - lock sync.Mutex - cache map[string]string -} - -func (p *fakePersister) Persist(cache map[string]string) error { - p.lock.Lock() - defer p.lock.Unlock() - p.cache = map[string]string{} - for k, v := range cache { - p.cache[k] = v - } - return nil -} - -func (p *fakePersister) Cache() map[string]string { - ret := map[string]string{} - p.lock.Lock() - defer p.lock.Unlock() - for k, v := range p.cache { - ret[k] = v - } - return ret -} - -type fakeTokenSource struct { - expiresOn string - accessToken string -} - -func (ts *fakeTokenSource) Token() (*azureToken, error) { - return &azureToken{ - token: newFackeAzureToken(ts.accessToken, ts.expiresOn), - clientID: "fake", - tenantID: "fake", - apiserverID: "fake", - }, nil -} - -func token2Cfg(token *azureToken) map[string]string { - cfg := make(map[string]string) - cfg[cfgAccessToken] = token.token.AccessToken - cfg[cfgRefreshToken] = token.token.RefreshToken - cfg[cfgClientID] = token.clientID - cfg[cfgTenantID] = token.tenantID - cfg[cfgApiserverID] = token.apiserverID - cfg[cfgExpiresIn] = token.token.ExpiresIn - cfg[cfgExpiresOn] = token.token.ExpiresOn - return cfg -} - -func newFackeAzureToken(accessToken string, expiresOn string) adal.Token { - return adal.Token{ - AccessToken: accessToken, - RefreshToken: "fake", - ExpiresIn: "3600", - ExpiresOn: expiresOn, - NotBefore: expiresOn, - Resource: "fake", - Type: "fake", - } -} diff --git a/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec_test.go b/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec_test.go deleted file mode 100644 index 28137eb847..0000000000 --- a/vendor/k8s.io/client-go/plugin/pkg/client/auth/exec/exec_test.go +++ /dev/null @@ -1,413 +0,0 @@ -/* -Copyright 2018 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 exec - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/http/httptest" - "strings" - "testing" - "time" - - "k8s.io/client-go/pkg/apis/clientauthentication" - "k8s.io/client-go/tools/clientcmd/api" -) - -func TestCacheKey(t *testing.T) { - c1 := &api.ExecConfig{ - Command: "foo-bar", - Args: []string{"1", "2"}, - Env: []api.ExecEnvVar{ - {Name: "3", Value: "4"}, - {Name: "5", Value: "6"}, - {Name: "7", Value: "8"}, - }, - APIVersion: "client.authentication.k8s.io/v1alpha1", - } - c2 := &api.ExecConfig{ - Command: "foo-bar", - Args: []string{"1", "2"}, - Env: []api.ExecEnvVar{ - {Name: "3", Value: "4"}, - {Name: "5", Value: "6"}, - {Name: "7", Value: "8"}, - }, - APIVersion: "client.authentication.k8s.io/v1alpha1", - } - c3 := &api.ExecConfig{ - Command: "foo-bar", - Args: []string{"1", "2"}, - Env: []api.ExecEnvVar{ - {Name: "3", Value: "4"}, - {Name: "5", Value: "6"}, - }, - APIVersion: "client.authentication.k8s.io/v1alpha1", - } - key1 := cacheKey(c1) - key2 := cacheKey(c2) - key3 := cacheKey(c3) - if key1 != key2 { - t.Error("key1 and key2 didn't match") - } - if key1 == key3 { - t.Error("key1 and key3 matched") - } - if key2 == key3 { - t.Error("key2 and key3 matched") - } -} - -func compJSON(t *testing.T, got, want []byte) { - t.Helper() - gotJSON := &bytes.Buffer{} - wantJSON := &bytes.Buffer{} - - if err := json.Indent(gotJSON, got, "", " "); err != nil { - t.Errorf("got invalid JSON: %v", err) - } - if err := json.Indent(wantJSON, want, "", " "); err != nil { - t.Errorf("want invalid JSON: %v", err) - } - g := strings.TrimSpace(gotJSON.String()) - w := strings.TrimSpace(wantJSON.String()) - if g != w { - t.Errorf("wanted %q, got %q", w, g) - } -} - -func TestGetToken(t *testing.T) { - tests := []struct { - name string - config api.ExecConfig - output string - interactive bool - response *clientauthentication.Response - wantInput string - wantToken string - wantExpiry time.Time - wantErr bool - }{ - { - name: "basic-request", - config: api.ExecConfig{ - APIVersion: "client.authentication.k8s.io/v1alpha1", - }, - wantInput: `{ - "kind":"ExecCredential", - "apiVersion":"client.authentication.k8s.io/v1alpha1", - "spec": {} - }`, - output: `{ - "kind": "ExecCredential", - "apiVersion": "client.authentication.k8s.io/v1alpha1", - "status": { - "token": "foo-bar" - } - }`, - wantToken: "foo-bar", - }, - { - name: "interactive", - config: api.ExecConfig{ - APIVersion: "client.authentication.k8s.io/v1alpha1", - }, - interactive: true, - wantInput: `{ - "kind":"ExecCredential", - "apiVersion":"client.authentication.k8s.io/v1alpha1", - "spec": { - "interactive": true - } - }`, - output: `{ - "kind": "ExecCredential", - "apiVersion": "client.authentication.k8s.io/v1alpha1", - "status": { - "token": "foo-bar" - } - }`, - wantToken: "foo-bar", - }, - { - name: "response", - config: api.ExecConfig{ - APIVersion: "client.authentication.k8s.io/v1alpha1", - }, - response: &clientauthentication.Response{ - Header: map[string][]string{ - "WWW-Authenticate": {`Basic realm="Access to the staging site", charset="UTF-8"`}, - }, - Code: 401, - }, - wantInput: `{ - "kind":"ExecCredential", - "apiVersion":"client.authentication.k8s.io/v1alpha1", - "spec": { - "response": { - "header": { - "WWW-Authenticate": [ - "Basic realm=\"Access to the staging site\", charset=\"UTF-8\"" - ] - }, - "code": 401 - } - } - }`, - output: `{ - "kind": "ExecCredential", - "apiVersion": "client.authentication.k8s.io/v1alpha1", - "status": { - "token": "foo-bar" - } - }`, - wantToken: "foo-bar", - }, - { - name: "expiry", - config: api.ExecConfig{ - APIVersion: "client.authentication.k8s.io/v1alpha1", - }, - wantInput: `{ - "kind":"ExecCredential", - "apiVersion":"client.authentication.k8s.io/v1alpha1", - "spec": {} - }`, - output: `{ - "kind": "ExecCredential", - "apiVersion": "client.authentication.k8s.io/v1alpha1", - "status": { - "token": "foo-bar", - "expirationTimestamp": "2006-01-02T15:04:05Z" - } - }`, - wantExpiry: time.Date(2006, 01, 02, 15, 04, 05, 0, time.UTC), - wantToken: "foo-bar", - }, - { - name: "no-group-version", - config: api.ExecConfig{ - APIVersion: "client.authentication.k8s.io/v1alpha1", - }, - wantInput: `{ - "kind":"ExecCredential", - "apiVersion":"client.authentication.k8s.io/v1alpha1", - "spec": {} - }`, - output: `{ - "kind": "ExecCredential", - "status": { - "token": "foo-bar" - } - }`, - wantErr: true, - }, - { - name: "no-status", - config: api.ExecConfig{ - APIVersion: "client.authentication.k8s.io/v1alpha1", - }, - wantInput: `{ - "kind":"ExecCredential", - "apiVersion":"client.authentication.k8s.io/v1alpha1", - "spec": {} - }`, - output: `{ - "kind": "ExecCredential", - "apiVersion":"client.authentication.k8s.io/v1alpha1" - }`, - wantErr: true, - }, - { - name: "no-token", - config: api.ExecConfig{ - APIVersion: "client.authentication.k8s.io/v1alpha1", - }, - wantInput: `{ - "kind":"ExecCredential", - "apiVersion":"client.authentication.k8s.io/v1alpha1", - "spec": {} - }`, - output: `{ - "kind": "ExecCredential", - "apiVersion":"client.authentication.k8s.io/v1alpha1", - "status": {} - }`, - wantErr: true, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - c := test.config - - c.Command = "./testdata/test-plugin.sh" - c.Env = append(c.Env, api.ExecEnvVar{ - Name: "TEST_OUTPUT", - Value: test.output, - }) - - a, err := newAuthenticator(newCache(), &c) - if err != nil { - t.Fatal(err) - } - - stderr := &bytes.Buffer{} - a.stderr = stderr - a.interactive = test.interactive - a.environ = func() []string { return nil } - - token, err := a.getToken(test.response) - if err != nil { - if !test.wantErr { - t.Errorf("get token %v", err) - } - return - } - if test.wantErr { - t.Fatal("expected error getting token") - } - - if token != test.wantToken { - t.Errorf("expected token %q got %q", test.wantToken, token) - } - - if !a.exp.Equal(test.wantExpiry) { - t.Errorf("expected expiry %v got %v", test.wantExpiry, a.exp) - } - - compJSON(t, stderr.Bytes(), []byte(test.wantInput)) - }) - } -} - -func TestRoundTripper(t *testing.T) { - wantToken := "" - - n := time.Now() - now := func() time.Time { return n } - - env := []string{""} - environ := func() []string { - s := make([]string, len(env)) - copy(s, env) - return s - } - - setOutput := func(s string) { - env[0] = "TEST_OUTPUT=" + s - } - - handler := func(w http.ResponseWriter, r *http.Request) { - gotToken := "" - parts := strings.Split(r.Header.Get("Authorization"), " ") - if len(parts) > 1 && strings.EqualFold(parts[0], "bearer") { - gotToken = parts[1] - } - - if wantToken != gotToken { - http.Error(w, "Unauthorized", http.StatusUnauthorized) - return - } - fmt.Fprintln(w, "ok") - } - server := httptest.NewServer(http.HandlerFunc(handler)) - - c := api.ExecConfig{ - Command: "./testdata/test-plugin.sh", - APIVersion: "client.authentication.k8s.io/v1alpha1", - } - a, err := newAuthenticator(newCache(), &c) - if err != nil { - t.Fatal(err) - } - a.environ = environ - a.now = now - a.stderr = ioutil.Discard - - client := http.Client{ - Transport: a.WrapTransport(http.DefaultTransport), - } - - get := func(t *testing.T, statusCode int) { - t.Helper() - resp, err := client.Get(server.URL) - if err != nil { - t.Fatal(err) - } - defer resp.Body.Close() - if resp.StatusCode != statusCode { - t.Errorf("wanted status %d got %d", statusCode, resp.StatusCode) - } - } - - setOutput(`{ - "kind": "ExecCredential", - "apiVersion": "client.authentication.k8s.io/v1alpha1", - "status": { - "token": "token1" - } - }`) - wantToken = "token1" - get(t, http.StatusOK) - - setOutput(`{ - "kind": "ExecCredential", - "apiVersion": "client.authentication.k8s.io/v1alpha1", - "status": { - "token": "token2" - } - }`) - // Previous token should be cached - get(t, http.StatusOK) - - wantToken = "token2" - // Token is still cached, hits unauthorized but causes token to rotate. - get(t, http.StatusUnauthorized) - // Follow up request uses the rotated token. - get(t, http.StatusOK) - - setOutput(`{ - "kind": "ExecCredential", - "apiVersion": "client.authentication.k8s.io/v1alpha1", - "status": { - "token": "token3", - "expirationTimestamp": "` + now().Add(time.Hour).Format(time.RFC3339Nano) + `" - } - }`) - wantToken = "token3" - // Token is still cached, hit's unauthorized but causes rotation to token with an expiry. - get(t, http.StatusUnauthorized) - get(t, http.StatusOK) - - // Move time forward 2 hours, "token3" is now expired. - n = n.Add(time.Hour * 2) - setOutput(`{ - "kind": "ExecCredential", - "apiVersion": "client.authentication.k8s.io/v1alpha1", - "status": { - "token": "token4", - "expirationTimestamp": "` + now().Add(time.Hour).Format(time.RFC3339Nano) + `" - } - }`) - wantToken = "token4" - // Old token is expired, should refresh automatically without hitting a 401. - get(t, http.StatusOK) -} diff --git a/vendor/k8s.io/client-go/plugin/pkg/client/auth/gcp/gcp_test.go b/vendor/k8s.io/client-go/plugin/pkg/client/auth/gcp/gcp_test.go deleted file mode 100644 index 32271b252b..0000000000 --- a/vendor/k8s.io/client-go/plugin/pkg/client/auth/gcp/gcp_test.go +++ /dev/null @@ -1,497 +0,0 @@ -/* -Copyright 2016 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 gcp - -import ( - "fmt" - "io/ioutil" - "net/http" - "os" - "os/exec" - "reflect" - "strings" - "sync" - "testing" - "time" - - "golang.org/x/oauth2" -) - -type fakeOutput struct { - args []string - output string -} - -var ( - wantCmd []string - // Output for fakeExec, keyed by command - execOutputs = map[string]fakeOutput{ - "/default/no/args": { - args: []string{}, - output: `{ - "access_token": "faketoken", - "token_expiry": "2016-10-31T22:31:09.123000000Z" -}`}, - "/default/legacy/args": { - args: []string{"arg1", "arg2", "arg3"}, - output: `{ - "access_token": "faketoken", - "token_expiry": "2016-10-31T22:31:09.123000000Z" -}`}, - "/space in path/customkeys": { - args: []string{"can", "haz", "auth"}, - output: `{ - "token": "faketoken", - "token_expiry": { - "datetime": "2016-10-31 22:31:09.123" - } -}`}, - "missing/tokenkey/noargs": { - args: []string{}, - output: `{ - "broken": "faketoken", - "token_expiry": { - "datetime": "2016-10-31 22:31:09.123000000Z" - } -}`}, - "missing/expirykey/legacyargs": { - args: []string{"split", "on", "whitespace"}, - output: `{ - "access_token": "faketoken", - "expires": "2016-10-31T22:31:09.123000000Z" -}`}, - "invalid expiry/timestamp": { - args: []string{"foo", "--bar", "--baz=abc,def"}, - output: `{ - "access_token": "faketoken", - "token_expiry": "sometime soon, idk" -}`}, - "badjson": { - args: []string{}, - output: `{ - "access_token": "faketoken", - "token_expiry": "sometime soon, idk" - ------ -`}, - } -) - -func fakeExec(command string, args ...string) *exec.Cmd { - cs := []string{"-test.run=TestHelperProcess", "--", command} - cs = append(cs, args...) - cmd := exec.Command(os.Args[0], cs...) - cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} - return cmd -} - -func TestHelperProcess(t *testing.T) { - if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { - return - } - // Strip out the leading args used to exec into this function. - gotCmd := os.Args[3] - gotArgs := os.Args[4:] - output, ok := execOutputs[gotCmd] - if !ok { - fmt.Fprintf(os.Stdout, "unexpected call cmd=%q args=%v\n", gotCmd, gotArgs) - os.Exit(1) - } else if !reflect.DeepEqual(output.args, gotArgs) { - fmt.Fprintf(os.Stdout, "call cmd=%q got args %v, want: %v\n", gotCmd, gotArgs, output.args) - os.Exit(1) - } - fmt.Fprintf(os.Stdout, output.output) - os.Exit(0) -} - -func Test_isCmdTokenSource(t *testing.T) { - c1 := map[string]string{"cmd-path": "foo"} - if v := isCmdTokenSource(c1); !v { - t.Fatalf("cmd-path present in config (%+v), but got %v", c1, v) - } - - c2 := map[string]string{"cmd-args": "foo bar"} - if v := isCmdTokenSource(c2); v { - t.Fatalf("cmd-path not present in config (%+v), but got %v", c2, v) - } -} - -func Test_tokenSource_cmd(t *testing.T) { - if _, err := tokenSource(true, map[string]string{}); err == nil { - t.Fatalf("expected error, cmd-args not present in config") - } - - c := map[string]string{ - "cmd-path": "foo", - "cmd-args": "bar"} - ts, err := tokenSource(true, c) - if err != nil { - t.Fatalf("failed to return cmd token source: %+v", err) - } - if ts == nil { - t.Fatal("returned nil token source") - } - if _, ok := ts.(*commandTokenSource); !ok { - t.Fatalf("returned token source type:(%T) expected:(*commandTokenSource)", ts) - } -} - -func Test_tokenSource_cmdCannotBeUsedWithScopes(t *testing.T) { - c := map[string]string{ - "cmd-path": "foo", - "scopes": "A,B"} - if _, err := tokenSource(true, c); err == nil { - t.Fatal("expected error when scopes is used with cmd-path") - } -} - -func Test_tokenSource_applicationDefaultCredentials_fails(t *testing.T) { - // try to use empty ADC file - fakeTokenFile, err := ioutil.TempFile("", "adctoken") - if err != nil { - t.Fatalf("failed to create fake token file: +%v", err) - } - fakeTokenFile.Close() - defer os.Remove(fakeTokenFile.Name()) - - os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", fakeTokenFile.Name()) - defer os.Unsetenv("GOOGLE_APPLICATION_CREDENTIALS") - if _, err := tokenSource(false, map[string]string{}); err == nil { - t.Fatalf("expected error because specified ADC token file is not a JSON") - } -} - -func Test_tokenSource_applicationDefaultCredentials(t *testing.T) { - fakeTokenFile, err := ioutil.TempFile("", "adctoken") - if err != nil { - t.Fatalf("failed to create fake token file: +%v", err) - } - fakeTokenFile.Close() - defer os.Remove(fakeTokenFile.Name()) - if err := ioutil.WriteFile(fakeTokenFile.Name(), []byte(`{"type":"service_account"}`), 0600); err != nil { - t.Fatalf("failed to write to fake token file: %+v", err) - } - - os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", fakeTokenFile.Name()) - defer os.Unsetenv("GOOGLE_APPLICATION_CREDENTIALS") - ts, err := tokenSource(false, map[string]string{}) - if err != nil { - t.Fatalf("failed to get a token source: %+v", err) - } - if ts == nil { - t.Fatal("returned nil token source") - } -} - -func Test_parseScopes(t *testing.T) { - cases := []struct { - in map[string]string - out []string - }{ - { - map[string]string{}, - []string{ - "https://www.googleapis.com/auth/cloud-platform", - "https://www.googleapis.com/auth/userinfo.email"}, - }, - { - map[string]string{"scopes": ""}, - []string{}, - }, - { - map[string]string{"scopes": "A,B,C"}, - []string{"A", "B", "C"}, - }, - } - - for _, c := range cases { - got := parseScopes(c.in) - if !reflect.DeepEqual(got, c.out) { - t.Errorf("expected=%v, got=%v", c.out, got) - } - } -} - -func errEquiv(got, want error) bool { - if got == want { - return true - } - if got != nil && want != nil { - return strings.Contains(got.Error(), want.Error()) - } - return false -} - -func TestCmdTokenSource(t *testing.T) { - execCommand = fakeExec - fakeExpiry := time.Date(2016, 10, 31, 22, 31, 9, 123000000, time.UTC) - customFmt := "2006-01-02 15:04:05.999999999" - - tests := []struct { - name string - gcpConfig map[string]string - tok *oauth2.Token - newErr, tokenErr error - }{ - { - "default", - map[string]string{ - "cmd-path": "/default/no/args", - }, - &oauth2.Token{ - AccessToken: "faketoken", - TokenType: "Bearer", - Expiry: fakeExpiry, - }, - nil, - nil, - }, - { - "default legacy args", - map[string]string{ - "cmd-path": "/default/legacy/args arg1 arg2 arg3", - }, - &oauth2.Token{ - AccessToken: "faketoken", - TokenType: "Bearer", - Expiry: fakeExpiry, - }, - nil, - nil, - }, - - { - "custom keys", - map[string]string{ - "cmd-path": "/space in path/customkeys", - "cmd-args": "can haz auth", - "token-key": "{.token}", - "expiry-key": "{.token_expiry.datetime}", - "time-fmt": customFmt, - }, - &oauth2.Token{ - AccessToken: "faketoken", - TokenType: "Bearer", - Expiry: fakeExpiry, - }, - nil, - nil, - }, - { - "missing cmd", - map[string]string{ - "cmd-path": "", - }, - nil, - fmt.Errorf("missing access token cmd"), - nil, - }, - { - "missing token-key", - map[string]string{ - "cmd-path": "missing/tokenkey/noargs", - "token-key": "{.token}", - }, - nil, - nil, - fmt.Errorf("error parsing token-key %q", "{.token}"), - }, - - { - "missing expiry-key", - map[string]string{ - "cmd-path": "missing/expirykey/legacyargs split on whitespace", - "expiry-key": "{.expiry}", - }, - nil, - nil, - fmt.Errorf("error parsing expiry-key %q", "{.expiry}"), - }, - { - "invalid expiry timestamp", - map[string]string{ - "cmd-path": "invalid expiry/timestamp", - "cmd-args": "foo --bar --baz=abc,def", - }, - &oauth2.Token{ - AccessToken: "faketoken", - TokenType: "Bearer", - Expiry: time.Time{}, - }, - nil, - nil, - }, - { - "bad JSON", - map[string]string{ - "cmd-path": "badjson", - }, - nil, - nil, - fmt.Errorf("invalid character '-' after object key:value pair"), - }, - } - - for _, tc := range tests { - provider, err := newGCPAuthProvider("", tc.gcpConfig, nil /* persister */) - if !errEquiv(err, tc.newErr) { - t.Errorf("%q newGCPAuthProvider error: got %v, want %v", tc.name, err, tc.newErr) - continue - } - if err != nil { - continue - } - ts := provider.(*gcpAuthProvider).tokenSource.(*cachedTokenSource).source.(*commandTokenSource) - wantCmd = append([]string{ts.cmd}, ts.args...) - tok, err := ts.Token() - if !errEquiv(err, tc.tokenErr) { - t.Errorf("%q Token() error: got %v, want %v", tc.name, err, tc.tokenErr) - } - if !reflect.DeepEqual(tok, tc.tok) { - t.Errorf("%q Token() got %v, want %v", tc.name, tok, tc.tok) - } - } -} - -type fakePersister struct { - lk sync.Mutex - cache map[string]string -} - -func (f *fakePersister) Persist(cache map[string]string) error { - f.lk.Lock() - defer f.lk.Unlock() - f.cache = map[string]string{} - for k, v := range cache { - f.cache[k] = v - } - return nil -} - -func (f *fakePersister) read() map[string]string { - ret := map[string]string{} - f.lk.Lock() - defer f.lk.Unlock() - for k, v := range f.cache { - ret[k] = v - } - return ret -} - -type fakeTokenSource struct { - token *oauth2.Token - err error -} - -func (f *fakeTokenSource) Token() (*oauth2.Token, error) { - return f.token, f.err -} - -func TestCachedTokenSource(t *testing.T) { - tok := &oauth2.Token{AccessToken: "fakeaccesstoken"} - persister := &fakePersister{} - source := &fakeTokenSource{ - token: tok, - err: nil, - } - cache := map[string]string{ - "foo": "bar", - "baz": "bazinga", - } - ts, err := newCachedTokenSource("fakeaccesstoken", "", persister, source, cache) - if err != nil { - t.Fatal(err) - } - var wg sync.WaitGroup - wg.Add(10) - for i := 0; i < 10; i++ { - go func() { - _, err := ts.Token() - if err != nil { - t.Errorf("unexpected error: %s", err) - } - wg.Done() - }() - } - wg.Wait() - cache["access-token"] = "fakeaccesstoken" - cache["expiry"] = tok.Expiry.Format(time.RFC3339Nano) - if got := persister.read(); !reflect.DeepEqual(got, cache) { - t.Errorf("got cache %v, want %v", got, cache) - } -} - -type MockTransport struct { - res *http.Response -} - -func (t *MockTransport) RoundTrip(req *http.Request) (*http.Response, error) { - return t.res, nil -} - -func TestClearingCredentials(t *testing.T) { - - fakeExpiry := time.Now().Add(time.Hour) - - cache := map[string]string{ - "access-token": "fakeToken", - "expiry": fakeExpiry.String(), - } - - cts := cachedTokenSource{ - source: nil, - accessToken: cache["access-token"], - expiry: fakeExpiry, - persister: nil, - cache: nil, - } - - tests := []struct { - name string - res http.Response - cache map[string]string - }{ - { - "Unauthorized", - http.Response{StatusCode: 401}, - make(map[string]string), - }, - { - "Authorized", - http.Response{StatusCode: 200}, - cache, - }, - } - - persister := &fakePersister{} - req := http.Request{Header: http.Header{}} - - for _, tc := range tests { - authProvider := gcpAuthProvider{&cts, persister} - - fakeTransport := MockTransport{&tc.res} - - transport := (authProvider.WrapTransport(&fakeTransport)) - persister.Persist(cache) - - transport.RoundTrip(&req) - - if got := persister.read(); !reflect.DeepEqual(got, tc.cache) { - t.Errorf("got cache %v, want %v", got, tc.cache) - } - } - -} diff --git a/vendor/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc_test.go b/vendor/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc_test.go deleted file mode 100644 index c14a3a8490..0000000000 --- a/vendor/k8s.io/client-go/plugin/pkg/client/auth/oidc/oidc_test.go +++ /dev/null @@ -1,138 +0,0 @@ -/* -Copyright 2016 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 oidc - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "testing" - "time" -) - -func TestJSONTime(t *testing.T) { - data := `{ - "t1": 1493851263, - "t2": 1.493851263e9 - }` - - var v struct { - T1 jsonTime `json:"t1"` - T2 jsonTime `json:"t2"` - } - if err := json.Unmarshal([]byte(data), &v); err != nil { - t.Fatal(err) - } - wantT1 := time.Unix(1493851263, 0) - wantT2 := time.Unix(1493851263, 0) - gotT1 := time.Time(v.T1) - gotT2 := time.Time(v.T2) - - if !wantT1.Equal(gotT1) { - t.Errorf("t1 value: wanted %s got %s", wantT1, gotT1) - } - if !wantT2.Equal(gotT2) { - t.Errorf("t2 value: wanted %s got %s", wantT2, gotT2) - } -} - -func encodeJWT(header, payload, sig string) string { - e := func(s string) string { - return base64.RawURLEncoding.EncodeToString([]byte(s)) - } - return e(header) + "." + e(payload) + "." + e(sig) -} - -func TestExpired(t *testing.T) { - now := time.Now() - - nowFunc := func() time.Time { return now } - - tests := []struct { - name string - idToken string - wantErr bool - wantExpired bool - }{ - { - name: "valid", - idToken: encodeJWT( - "{}", - fmt.Sprintf(`{"exp":%d}`, now.Add(time.Hour).Unix()), - "blah", // signature isn't veified. - ), - }, - { - name: "expired", - idToken: encodeJWT( - "{}", - fmt.Sprintf(`{"exp":%d}`, now.Add(-time.Hour).Unix()), - "blah", // signature isn't veified. - ), - wantExpired: true, - }, - { - name: "bad exp claim", - idToken: encodeJWT( - "{}", - `{"exp":"foobar"}`, - "blah", // signature isn't veified. - ), - wantErr: true, - }, - { - name: "not an id token", - idToken: "notanidtoken", - wantErr: true, - }, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - valid, err := idTokenExpired(nowFunc, test.idToken) - if err != nil { - if !test.wantErr { - t.Errorf("parse error: %v", err) - } - return - } - if test.wantExpired == valid { - t.Errorf("wanted expired %t, got %t", test.wantExpired, !valid) - } - }) - } -} - -func TestClientCache(t *testing.T) { - cache := newClientCache() - - if _, ok := cache.getClient("issuer1", "id1"); ok { - t.Fatalf("got client before putting one in the cache") - } - - cli1 := new(oidcAuthProvider) - cli2 := new(oidcAuthProvider) - - gotcli := cache.setClient("issuer1", "id1", cli1) - if cli1 != gotcli { - t.Fatalf("set first client and got a different one") - } - - gotcli = cache.setClient("issuer1", "id1", cli2) - if cli1 != gotcli { - t.Fatalf("set a second client and didn't get the first") - } -} diff --git a/vendor/k8s.io/client-go/plugin/pkg/client/auth/openstack/openstack_test.go b/vendor/k8s.io/client-go/plugin/pkg/client/auth/openstack/openstack_test.go deleted file mode 100644 index 411bec70f7..0000000000 --- a/vendor/k8s.io/client-go/plugin/pkg/client/auth/openstack/openstack_test.go +++ /dev/null @@ -1,116 +0,0 @@ -/* -Copyright 2017 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 openstack - -import ( - "math/rand" - "net/http" - "testing" - "time" -) - -// testTokenGetter is a simple random token getter. -type testTokenGetter struct{} - -const LetterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - -func RandStringBytes(n int) string { - b := make([]byte, n) - for i := range b { - b[i] = LetterBytes[rand.Intn(len(LetterBytes))] - } - return string(b) -} - -func (*testTokenGetter) Token() (string, error) { - return RandStringBytes(32), nil -} - -// testRoundTripper is mocked roundtripper which responds with unauthorized when -// there is no authorization header, otherwise returns status ok. -type testRoundTripper struct{} - -func (trt *testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - authHeader := req.Header.Get("Authorization") - if authHeader == "" || authHeader == "Bearer " { - return &http.Response{ - StatusCode: http.StatusUnauthorized, - }, nil - } - return &http.Response{StatusCode: http.StatusOK}, nil -} - -func TestOpenstackAuthProvider(t *testing.T) { - trt := &tokenRoundTripper{ - RoundTripper: &testRoundTripper{}, - } - - tests := []struct { - name string - ttl time.Duration - interval time.Duration - same bool - }{ - { - name: "normal", - ttl: 2 * time.Second, - interval: 1 * time.Second, - same: true, - }, - { - name: "expire", - ttl: 1 * time.Second, - interval: 2 * time.Second, - same: false, - }, - } - - for _, test := range tests { - trt.tokenGetter = &cachedGetter{ - tokenGetter: &testTokenGetter{}, - ttl: test.ttl, - } - - req, err := http.NewRequest(http.MethodPost, "https://test-api-server.com", nil) - if err != nil { - t.Errorf("failed to new request: %s", err) - } - trt.RoundTrip(req) - header := req.Header.Get("Authorization") - if header == "" { - t.Errorf("expect to see token in header, but is absent") - } - - time.Sleep(test.interval) - - req, err = http.NewRequest(http.MethodPost, "https://test-api-server.com", nil) - if err != nil { - t.Errorf("failed to new request: %s", err) - } - trt.RoundTrip(req) - newHeader := req.Header.Get("Authorization") - if newHeader == "" { - t.Errorf("expect to see token in header, but is absent") - } - - same := newHeader == header - if same != test.same { - t.Errorf("expect to get %t when compare header, but saw %t", test.same, same) - } - } - -} diff --git a/vendor/k8s.io/client-go/rest/client_test.go b/vendor/k8s.io/client-go/rest/client_test.go deleted file mode 100644 index 2eae9be2d6..0000000000 --- a/vendor/k8s.io/client-go/rest/client_test.go +++ /dev/null @@ -1,343 +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 rest - -import ( - "net/http" - "net/http/httptest" - "net/url" - "os" - "reflect" - "testing" - "time" - - "fmt" - - "k8s.io/api/core/v1" - v1beta1 "k8s.io/api/extensions/v1beta1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/serializer" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/diff" - "k8s.io/client-go/kubernetes/scheme" - utiltesting "k8s.io/client-go/util/testing" -) - -type TestParam struct { - actualError error - expectingError bool - actualCreated bool - expCreated bool - expStatus *metav1.Status - testBody bool - testBodyErrorIsNotNil bool -} - -// TestSerializer makes sure that you're always able to decode metav1.Status -func TestSerializer(t *testing.T) { - gv := v1beta1.SchemeGroupVersion - contentConfig := ContentConfig{ - ContentType: "application/json", - GroupVersion: &gv, - NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}, - } - - serializer, err := createSerializers(contentConfig) - if err != nil { - t.Fatal(err) - } - // bytes based on actual return from API server when encoding an "unversioned" object - obj, err := runtime.Decode(serializer.Decoder, []byte(`{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Success"}`)) - t.Log(obj) - if err != nil { - t.Fatal(err) - } -} - -func TestDoRequestSuccess(t *testing.T) { - testServer, fakeHandler, status := testServerEnv(t, 200) - defer testServer.Close() - - c, err := restClient(testServer) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - body, err := c.Get().Prefix("test").Do().Raw() - - testParam := TestParam{actualError: err, expectingError: false, expCreated: true, - expStatus: status, testBody: true, testBodyErrorIsNotNil: false} - validate(testParam, t, body, fakeHandler) -} - -func TestDoRequestFailed(t *testing.T) { - status := &metav1.Status{ - Code: http.StatusNotFound, - Status: metav1.StatusFailure, - Reason: metav1.StatusReasonNotFound, - Message: " \"\" not found", - Details: &metav1.StatusDetails{}, - } - expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), status) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 404, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - defer testServer.Close() - - c, err := restClient(testServer) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - err = c.Get().Do().Error() - if err == nil { - t.Errorf("unexpected non-error") - } - ss, ok := err.(errors.APIStatus) - if !ok { - t.Errorf("unexpected error type %v", err) - } - actual := ss.Status() - if !reflect.DeepEqual(status, &actual) { - t.Errorf("Unexpected mis-match: %s", diff.ObjectReflectDiff(status, &actual)) - } -} - -func TestDoRawRequestFailed(t *testing.T) { - status := &metav1.Status{ - Code: http.StatusNotFound, - Status: metav1.StatusFailure, - Reason: metav1.StatusReasonNotFound, - Message: "the server could not find the requested resource", - Details: &metav1.StatusDetails{ - Causes: []metav1.StatusCause{ - {Type: metav1.CauseTypeUnexpectedServerResponse, Message: "unknown"}, - }, - }, - } - expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), status) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 404, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - defer testServer.Close() - - c, err := restClient(testServer) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - body, err := c.Get().Do().Raw() - - if err == nil || body == nil { - t.Errorf("unexpected non-error: %#v", body) - } - ss, ok := err.(errors.APIStatus) - if !ok { - t.Errorf("unexpected error type %v", err) - } - actual := ss.Status() - if !reflect.DeepEqual(status, &actual) { - t.Errorf("Unexpected mis-match: %s", diff.ObjectReflectDiff(status, &actual)) - } -} - -func TestDoRequestCreated(t *testing.T) { - testServer, fakeHandler, status := testServerEnv(t, 201) - defer testServer.Close() - - c, err := restClient(testServer) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - created := false - body, err := c.Get().Prefix("test").Do().WasCreated(&created).Raw() - - testParam := TestParam{actualError: err, expectingError: false, expCreated: true, - expStatus: status, testBody: false} - validate(testParam, t, body, fakeHandler) -} - -func TestDoRequestNotCreated(t *testing.T) { - testServer, fakeHandler, expectedStatus := testServerEnv(t, 202) - defer testServer.Close() - c, err := restClient(testServer) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - created := false - body, err := c.Get().Prefix("test").Do().WasCreated(&created).Raw() - testParam := TestParam{actualError: err, expectingError: false, expCreated: false, - expStatus: expectedStatus, testBody: false} - validate(testParam, t, body, fakeHandler) -} - -func TestDoRequestAcceptedNoContentReturned(t *testing.T) { - testServer, fakeHandler, _ := testServerEnv(t, 204) - defer testServer.Close() - - c, err := restClient(testServer) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - created := false - body, err := c.Get().Prefix("test").Do().WasCreated(&created).Raw() - testParam := TestParam{actualError: err, expectingError: false, expCreated: false, - testBody: false} - validate(testParam, t, body, fakeHandler) -} - -func TestBadRequest(t *testing.T) { - testServer, fakeHandler, _ := testServerEnv(t, 400) - defer testServer.Close() - c, err := restClient(testServer) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - created := false - body, err := c.Get().Prefix("test").Do().WasCreated(&created).Raw() - testParam := TestParam{actualError: err, expectingError: true, expCreated: false, - testBody: true} - validate(testParam, t, body, fakeHandler) -} - -func validate(testParam TestParam, t *testing.T, body []byte, fakeHandler *utiltesting.FakeHandler) { - switch { - case testParam.expectingError && testParam.actualError == nil: - t.Errorf("Expected error") - case !testParam.expectingError && testParam.actualError != nil: - t.Error(testParam.actualError) - } - if !testParam.expCreated { - if testParam.actualCreated { - t.Errorf("Expected object not to be created") - } - } - statusOut, err := runtime.Decode(scheme.Codecs.UniversalDeserializer(), body) - if testParam.testBody { - if testParam.testBodyErrorIsNotNil && err == nil { - t.Errorf("Expected Error") - } - if !testParam.testBodyErrorIsNotNil && err != nil { - t.Errorf("Unexpected Error: %v", err) - } - } - - if testParam.expStatus != nil { - if !reflect.DeepEqual(testParam.expStatus, statusOut) { - t.Errorf("Unexpected mis-match. Expected %#v. Saw %#v", testParam.expStatus, statusOut) - } - } - fakeHandler.ValidateRequest(t, "/"+v1.SchemeGroupVersion.String()+"/test", "GET", nil) - -} - -func TestHttpMethods(t *testing.T) { - testServer, _, _ := testServerEnv(t, 200) - defer testServer.Close() - c, _ := restClient(testServer) - - request := c.Post() - if request == nil { - t.Errorf("Post : Object returned should not be nil") - } - - request = c.Get() - if request == nil { - t.Errorf("Get: Object returned should not be nil") - } - - request = c.Put() - if request == nil { - t.Errorf("Put : Object returned should not be nil") - } - - request = c.Delete() - if request == nil { - t.Errorf("Delete : Object returned should not be nil") - } - - request = c.Patch(types.JSONPatchType) - if request == nil { - t.Errorf("Patch : Object returned should not be nil") - } -} - -func TestCreateBackoffManager(t *testing.T) { - - theUrl, _ := url.Parse("http://localhost") - - // 1 second base backoff + duration of 2 seconds -> exponential backoff for requests. - os.Setenv(envBackoffBase, "1") - os.Setenv(envBackoffDuration, "2") - backoff := readExpBackoffConfig() - backoff.UpdateBackoff(theUrl, nil, 500) - backoff.UpdateBackoff(theUrl, nil, 500) - if backoff.CalculateBackoff(theUrl)/time.Second != 2 { - t.Errorf("Backoff env not working.") - } - - // 0 duration -> no backoff. - os.Setenv(envBackoffBase, "1") - os.Setenv(envBackoffDuration, "0") - backoff.UpdateBackoff(theUrl, nil, 500) - backoff.UpdateBackoff(theUrl, nil, 500) - backoff = readExpBackoffConfig() - if backoff.CalculateBackoff(theUrl)/time.Second != 0 { - t.Errorf("Zero backoff duration, but backoff still occurring.") - } - - // No env -> No backoff. - os.Setenv(envBackoffBase, "") - os.Setenv(envBackoffDuration, "") - backoff = readExpBackoffConfig() - backoff.UpdateBackoff(theUrl, nil, 500) - backoff.UpdateBackoff(theUrl, nil, 500) - if backoff.CalculateBackoff(theUrl)/time.Second != 0 { - t.Errorf("Backoff should have been 0.") - } - -} - -func testServerEnv(t *testing.T, statusCode int) (*httptest.Server, *utiltesting.FakeHandler, *metav1.Status) { - status := &metav1.Status{TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Status"}, Status: fmt.Sprintf("%s", metav1.StatusSuccess)} - expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), status) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: statusCode, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - return testServer, &fakeHandler, status -} - -func restClient(testServer *httptest.Server) (*RESTClient, error) { - c, err := RESTClientFor(&Config{ - Host: testServer.URL, - ContentConfig: ContentConfig{ - GroupVersion: &v1.SchemeGroupVersion, - NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}, - }, - Username: "user", - Password: "pass", - }) - return c, err -} diff --git a/vendor/k8s.io/client-go/rest/config_test.go b/vendor/k8s.io/client-go/rest/config_test.go deleted file mode 100644 index a9495d792f..0000000000 --- a/vendor/k8s.io/client-go/rest/config_test.go +++ /dev/null @@ -1,376 +0,0 @@ -/* -Copyright 2016 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package rest - -import ( - "io" - "net" - "net/http" - "path/filepath" - "reflect" - "strings" - "testing" - - fuzz "github.com/google/gofuzz" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/diff" - "k8s.io/client-go/kubernetes/scheme" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "k8s.io/client-go/util/flowcontrol" - - "errors" - - "github.com/stretchr/testify/assert" -) - -func TestIsConfigTransportTLS(t *testing.T) { - testCases := []struct { - Config *Config - TransportTLS bool - }{ - { - Config: &Config{}, - TransportTLS: false, - }, - { - Config: &Config{ - Host: "https://localhost", - }, - TransportTLS: true, - }, - { - Config: &Config{ - Host: "localhost", - TLSClientConfig: TLSClientConfig{ - CertFile: "foo", - }, - }, - TransportTLS: true, - }, - { - Config: &Config{ - Host: "///:://localhost", - TLSClientConfig: TLSClientConfig{ - CertFile: "foo", - }, - }, - TransportTLS: false, - }, - { - Config: &Config{ - Host: "1.2.3.4:567", - TLSClientConfig: TLSClientConfig{ - Insecure: true, - }, - }, - TransportTLS: true, - }, - } - for _, testCase := range testCases { - if err := SetKubernetesDefaults(testCase.Config); err != nil { - t.Errorf("setting defaults failed for %#v: %v", testCase.Config, err) - continue - } - useTLS := IsConfigTransportTLS(*testCase.Config) - if testCase.TransportTLS != useTLS { - t.Errorf("expected %v for %#v", testCase.TransportTLS, testCase.Config) - } - } -} - -func TestSetKubernetesDefaultsUserAgent(t *testing.T) { - config := &Config{} - if err := SetKubernetesDefaults(config); err != nil { - t.Errorf("unexpected error: %v", err) - } - if !strings.Contains(config.UserAgent, "kubernetes/") { - t.Errorf("no user agent set: %#v", config) - } -} - -func TestAdjustVersion(t *testing.T) { - assert := assert.New(t) - assert.Equal("1.2.3", adjustVersion("1.2.3-alpha4")) - assert.Equal("1.2.3", adjustVersion("1.2.3-alpha")) - assert.Equal("1.2.3", adjustVersion("1.2.3")) - assert.Equal("unknown", adjustVersion("")) -} - -func TestAdjustCommit(t *testing.T) { - assert := assert.New(t) - assert.Equal("1234567", adjustCommit("1234567890")) - assert.Equal("123456", adjustCommit("123456")) - assert.Equal("unknown", adjustCommit("")) -} - -func TestAdjustCommand(t *testing.T) { - assert := assert.New(t) - assert.Equal("beans", adjustCommand(filepath.Join("home", "bob", "Downloads", "beans"))) - assert.Equal("beans", adjustCommand(filepath.Join(".", "beans"))) - assert.Equal("beans", adjustCommand("beans")) - assert.Equal("unknown", adjustCommand("")) -} - -func TestBuildUserAgent(t *testing.T) { - assert.New(t).Equal( - "lynx/nicest (beos/itanium) kubernetes/baaaaaaaaad", - buildUserAgent( - "lynx", "nicest", - "beos", "itanium", "baaaaaaaaad")) -} - -// This function untestable since it doesn't accept arguments. -func TestDefaultKubernetesUserAgent(t *testing.T) { - assert.New(t).Contains(DefaultKubernetesUserAgent(), "kubernetes") -} - -func TestRESTClientRequires(t *testing.T) { - if _, err := RESTClientFor(&Config{Host: "127.0.0.1", ContentConfig: ContentConfig{NegotiatedSerializer: scheme.Codecs}}); err == nil { - t.Errorf("unexpected non-error") - } - if _, err := RESTClientFor(&Config{Host: "127.0.0.1", ContentConfig: ContentConfig{GroupVersion: &v1.SchemeGroupVersion}}); err == nil { - t.Errorf("unexpected non-error") - } - if _, err := RESTClientFor(&Config{Host: "127.0.0.1", ContentConfig: ContentConfig{GroupVersion: &v1.SchemeGroupVersion, NegotiatedSerializer: scheme.Codecs}}); err != nil { - t.Errorf("unexpected error: %v", err) - } -} - -type fakeLimiter struct { - FakeSaturation float64 - FakeQPS float32 -} - -func (t *fakeLimiter) TryAccept() bool { - return true -} - -func (t *fakeLimiter) Saturation() float64 { - return t.FakeSaturation -} - -func (t *fakeLimiter) QPS() float32 { - return t.FakeQPS -} - -func (t *fakeLimiter) Stop() {} - -func (t *fakeLimiter) Accept() {} - -type fakeCodec struct{} - -func (c *fakeCodec) Decode([]byte, *schema.GroupVersionKind, runtime.Object) (runtime.Object, *schema.GroupVersionKind, error) { - return nil, nil, nil -} - -func (c *fakeCodec) Encode(obj runtime.Object, stream io.Writer) error { - return nil -} - -type fakeRoundTripper struct{} - -func (r *fakeRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { - return nil, nil -} - -var fakeWrapperFunc = func(http.RoundTripper) http.RoundTripper { - return &fakeRoundTripper{} -} - -type fakeNegotiatedSerializer struct{} - -func (n *fakeNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo { - return nil -} - -func (n *fakeNegotiatedSerializer) EncoderForVersion(serializer runtime.Encoder, gv runtime.GroupVersioner) runtime.Encoder { - return &fakeCodec{} -} - -func (n *fakeNegotiatedSerializer) DecoderToVersion(serializer runtime.Decoder, gv runtime.GroupVersioner) runtime.Decoder { - return &fakeCodec{} -} - -var fakeDialFunc = func(network, addr string) (net.Conn, error) { - return nil, fakeDialerError -} -var fakeDialerError = errors.New("fakedialer") - -type fakeAuthProviderConfigPersister struct{} - -func (fakeAuthProviderConfigPersister) Persist(map[string]string) error { - return fakeAuthProviderConfigPersisterError -} - -var fakeAuthProviderConfigPersisterError = errors.New("fakeAuthProviderConfigPersisterError") - -func TestAnonymousConfig(t *testing.T) { - f := fuzz.New().NilChance(0.0).NumElements(1, 1) - f.Funcs( - func(r *runtime.Codec, f fuzz.Continue) { - codec := &fakeCodec{} - f.Fuzz(codec) - *r = codec - }, - func(r *http.RoundTripper, f fuzz.Continue) { - roundTripper := &fakeRoundTripper{} - f.Fuzz(roundTripper) - *r = roundTripper - }, - func(fn *func(http.RoundTripper) http.RoundTripper, f fuzz.Continue) { - *fn = fakeWrapperFunc - }, - func(r *runtime.NegotiatedSerializer, f fuzz.Continue) { - serializer := &fakeNegotiatedSerializer{} - f.Fuzz(serializer) - *r = serializer - }, - func(r *flowcontrol.RateLimiter, f fuzz.Continue) { - limiter := &fakeLimiter{} - f.Fuzz(limiter) - *r = limiter - }, - // Authentication does not require fuzzer - func(r *AuthProviderConfigPersister, f fuzz.Continue) {}, - func(r *clientcmdapi.AuthProviderConfig, f fuzz.Continue) { - r.Config = map[string]string{} - }, - // Dial does not require fuzzer - func(r *func(network, addr string) (net.Conn, error), f fuzz.Continue) {}, - ) - for i := 0; i < 20; i++ { - original := &Config{} - f.Fuzz(original) - actual := AnonymousClientConfig(original) - expected := *original - - // this is the list of known security related fields, add to this list if a new field - // is added to Config, update AnonymousClientConfig to preserve the field otherwise. - expected.Impersonate = ImpersonationConfig{} - expected.BearerToken = "" - expected.Username = "" - expected.Password = "" - expected.AuthProvider = nil - expected.AuthConfigPersister = nil - expected.ExecProvider = nil - expected.TLSClientConfig.CertData = nil - expected.TLSClientConfig.CertFile = "" - expected.TLSClientConfig.KeyData = nil - expected.TLSClientConfig.KeyFile = "" - - // The DeepEqual cannot handle the func comparison, so we just verify if the - // function return the expected object. - if actual.WrapTransport == nil || !reflect.DeepEqual(expected.WrapTransport(nil), &fakeRoundTripper{}) { - t.Fatalf("AnonymousClientConfig dropped the WrapTransport field") - } else { - actual.WrapTransport = nil - expected.WrapTransport = nil - } - if actual.Dial != nil { - _, actualError := actual.Dial("", "") - _, expectedError := actual.Dial("", "") - if !reflect.DeepEqual(expectedError, actualError) { - t.Fatalf("CopyConfig dropped the Dial field") - } - } else { - actual.Dial = nil - expected.Dial = nil - } - - if !reflect.DeepEqual(*actual, expected) { - t.Fatalf("AnonymousClientConfig dropped unexpected fields, identify whether they are security related or not: %s", diff.ObjectGoPrintDiff(expected, actual)) - } - } -} - -func TestCopyConfig(t *testing.T) { - f := fuzz.New().NilChance(0.0).NumElements(1, 1) - f.Funcs( - func(r *runtime.Codec, f fuzz.Continue) { - codec := &fakeCodec{} - f.Fuzz(codec) - *r = codec - }, - func(r *http.RoundTripper, f fuzz.Continue) { - roundTripper := &fakeRoundTripper{} - f.Fuzz(roundTripper) - *r = roundTripper - }, - func(fn *func(http.RoundTripper) http.RoundTripper, f fuzz.Continue) { - *fn = fakeWrapperFunc - }, - func(r *runtime.NegotiatedSerializer, f fuzz.Continue) { - serializer := &fakeNegotiatedSerializer{} - f.Fuzz(serializer) - *r = serializer - }, - func(r *flowcontrol.RateLimiter, f fuzz.Continue) { - limiter := &fakeLimiter{} - f.Fuzz(limiter) - *r = limiter - }, - func(r *AuthProviderConfigPersister, f fuzz.Continue) { - *r = fakeAuthProviderConfigPersister{} - }, - func(r *func(network, addr string) (net.Conn, error), f fuzz.Continue) { - *r = fakeDialFunc - }, - ) - for i := 0; i < 20; i++ { - original := &Config{} - f.Fuzz(original) - actual := CopyConfig(original) - expected := *original - - // this is the list of known risky fields, add to this list if a new field - // is added to Config, update CopyConfig to preserve the field otherwise. - - // The DeepEqual cannot handle the func comparison, so we just verify if the - // function return the expected object. - if actual.WrapTransport == nil || !reflect.DeepEqual(expected.WrapTransport(nil), &fakeRoundTripper{}) { - t.Fatalf("CopyConfig dropped the WrapTransport field") - } else { - actual.WrapTransport = nil - expected.WrapTransport = nil - } - if actual.Dial != nil { - _, actualError := actual.Dial("", "") - _, expectedError := actual.Dial("", "") - if !reflect.DeepEqual(expectedError, actualError) { - t.Fatalf("CopyConfig dropped the Dial field") - } - } - actual.Dial = nil - expected.Dial = nil - if actual.AuthConfigPersister != nil { - actualError := actual.AuthConfigPersister.Persist(nil) - expectedError := actual.AuthConfigPersister.Persist(nil) - if !reflect.DeepEqual(expectedError, actualError) { - t.Fatalf("CopyConfig dropped the Dial field") - } - } - actual.AuthConfigPersister = nil - expected.AuthConfigPersister = nil - - if !reflect.DeepEqual(*actual, expected) { - t.Fatalf("CopyConfig dropped unexpected fields, identify whether they are security related or not: %s", diff.ObjectReflectDiff(expected, *actual)) - } - } -} diff --git a/vendor/k8s.io/client-go/rest/plugin_test.go b/vendor/k8s.io/client-go/rest/plugin_test.go deleted file mode 100644 index 070e537909..0000000000 --- a/vendor/k8s.io/client-go/rest/plugin_test.go +++ /dev/null @@ -1,311 +0,0 @@ -/* -Copyright 2016 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package rest - -import ( - "fmt" - "net/http" - "reflect" - "strconv" - "testing" - - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -func TestAuthPluginWrapTransport(t *testing.T) { - if err := RegisterAuthProviderPlugin("pluginA", pluginAProvider); err != nil { - t.Errorf("Unexpected error: failed to register pluginA: %v", err) - } - if err := RegisterAuthProviderPlugin("pluginB", pluginBProvider); err != nil { - t.Errorf("Unexpected error: failed to register pluginB: %v", err) - } - if err := RegisterAuthProviderPlugin("pluginFail", pluginFailProvider); err != nil { - t.Errorf("Unexpected error: failed to register pluginFail: %v", err) - } - testCases := []struct { - useWrapTransport bool - plugin string - expectErr bool - expectPluginA bool - expectPluginB bool - }{ - {false, "", false, false, false}, - {false, "pluginA", false, true, false}, - {false, "pluginB", false, false, true}, - {false, "pluginFail", true, false, false}, - {false, "pluginUnknown", true, false, false}, - } - for i, tc := range testCases { - c := Config{} - if tc.useWrapTransport { - // Specify an existing WrapTransport in the config to make sure that - // plugins play nicely. - c.WrapTransport = func(rt http.RoundTripper) http.RoundTripper { - return &wrapTransport{rt} - } - } - if len(tc.plugin) != 0 { - c.AuthProvider = &clientcmdapi.AuthProviderConfig{Name: tc.plugin} - } - tConfig, err := c.TransportConfig() - if err != nil { - // Unknown/bad plugins are expected to fail here. - if !tc.expectErr { - t.Errorf("%d. Did not expect errors loading Auth Plugin: %q. Got: %v", i, tc.plugin, err) - } - continue - } - var fullyWrappedTransport http.RoundTripper - fullyWrappedTransport = &emptyTransport{} - if tConfig.WrapTransport != nil { - fullyWrappedTransport = tConfig.WrapTransport(&emptyTransport{}) - } - res, err := fullyWrappedTransport.RoundTrip(&http.Request{}) - if err != nil { - t.Errorf("%d. Unexpected error in RoundTrip: %v", i, err) - continue - } - hasWrapTransport := res.Header.Get("wrapTransport") == "Y" - hasPluginA := res.Header.Get("pluginA") == "Y" - hasPluginB := res.Header.Get("pluginB") == "Y" - if hasWrapTransport != tc.useWrapTransport { - t.Errorf("%d. Expected Existing config.WrapTransport: %t; Got: %t", i, tc.useWrapTransport, hasWrapTransport) - } - if hasPluginA != tc.expectPluginA { - t.Errorf("%d. Expected Plugin A: %t; Got: %t", i, tc.expectPluginA, hasPluginA) - } - if hasPluginB != tc.expectPluginB { - t.Errorf("%d. Expected Plugin B: %t; Got: %t", i, tc.expectPluginB, hasPluginB) - } - } -} - -func TestAuthPluginPersist(t *testing.T) { - // register pluginA by a different name so we don't collide across tests. - if err := RegisterAuthProviderPlugin("pluginA2", pluginAProvider); err != nil { - t.Errorf("Unexpected error: failed to register pluginA: %v", err) - } - if err := RegisterAuthProviderPlugin("pluginPersist", pluginPersistProvider); err != nil { - t.Errorf("Unexpected error: failed to register pluginPersist: %v", err) - } - fooBarConfig := map[string]string{"foo": "bar"} - testCases := []struct { - plugin string - startingConfig map[string]string - expectedConfigAfterLogin map[string]string - expectedConfigAfterRoundTrip map[string]string - }{ - // non-persisting plugins should work fine without modifying config. - {"pluginA2", map[string]string{}, map[string]string{}, map[string]string{}}, - {"pluginA2", fooBarConfig, fooBarConfig, fooBarConfig}, - // plugins that persist config should be able to persist when they want. - { - "pluginPersist", - map[string]string{}, - map[string]string{ - "login": "Y", - }, - map[string]string{ - "login": "Y", - "roundTrips": "1", - }, - }, - { - "pluginPersist", - map[string]string{ - "login": "Y", - "roundTrips": "123", - }, - map[string]string{ - "login": "Y", - "roundTrips": "123", - }, - map[string]string{ - "login": "Y", - "roundTrips": "124", - }, - }, - } - for i, tc := range testCases { - cfg := &clientcmdapi.AuthProviderConfig{ - Name: tc.plugin, - Config: tc.startingConfig, - } - persister := &inMemoryPersister{make(map[string]string)} - persister.Persist(tc.startingConfig) - plugin, err := GetAuthProvider("127.0.0.1", cfg, persister) - if err != nil { - t.Errorf("%d. Unexpected error: failed to get plugin %q: %v", i, tc.plugin, err) - } - if err := plugin.Login(); err != nil { - t.Errorf("%d. Unexpected error calling Login() w/ plugin %q: %v", i, tc.plugin, err) - } - // Make sure the plugin persisted what we expect after Login(). - if !reflect.DeepEqual(persister.savedConfig, tc.expectedConfigAfterLogin) { - t.Errorf("%d. Unexpected persisted config after calling %s.Login(): \nGot:\n%v\nExpected:\n%v", - i, tc.plugin, persister.savedConfig, tc.expectedConfigAfterLogin) - } - if _, err := plugin.WrapTransport(&emptyTransport{}).RoundTrip(&http.Request{}); err != nil { - t.Errorf("%d. Unexpected error round-tripping w/ plugin %q: %v", i, tc.plugin, err) - } - // Make sure the plugin persisted what we expect after RoundTrip(). - if !reflect.DeepEqual(persister.savedConfig, tc.expectedConfigAfterRoundTrip) { - t.Errorf("%d. Unexpected persisted config after calling %s.WrapTransport.RoundTrip(): \nGot:\n%v\nExpected:\n%v", - i, tc.plugin, persister.savedConfig, tc.expectedConfigAfterLogin) - } - } - -} - -// emptyTransport provides an empty http.Response with an initialized header -// to allow wrapping RoundTrippers to set header values. -type emptyTransport struct{} - -func (*emptyTransport) RoundTrip(req *http.Request) (*http.Response, error) { - res := &http.Response{ - Header: make(map[string][]string), - } - return res, nil -} - -// wrapTransport sets "wrapTransport" = "Y" on the response. -type wrapTransport struct { - rt http.RoundTripper -} - -func (w *wrapTransport) RoundTrip(req *http.Request) (*http.Response, error) { - res, err := w.rt.RoundTrip(req) - if err != nil { - return nil, err - } - res.Header.Add("wrapTransport", "Y") - return res, nil -} - -// wrapTransportA sets "pluginA" = "Y" on the response. -type wrapTransportA struct { - rt http.RoundTripper -} - -func (w *wrapTransportA) RoundTrip(req *http.Request) (*http.Response, error) { - res, err := w.rt.RoundTrip(req) - if err != nil { - return nil, err - } - res.Header.Add("pluginA", "Y") - return res, nil -} - -type pluginA struct{} - -func (*pluginA) WrapTransport(rt http.RoundTripper) http.RoundTripper { - return &wrapTransportA{rt} -} - -func (*pluginA) Login() error { return nil } - -func pluginAProvider(string, map[string]string, AuthProviderConfigPersister) (AuthProvider, error) { - return &pluginA{}, nil -} - -// wrapTransportB sets "pluginB" = "Y" on the response. -type wrapTransportB struct { - rt http.RoundTripper -} - -func (w *wrapTransportB) RoundTrip(req *http.Request) (*http.Response, error) { - res, err := w.rt.RoundTrip(req) - if err != nil { - return nil, err - } - res.Header.Add("pluginB", "Y") - return res, nil -} - -type pluginB struct{} - -func (*pluginB) WrapTransport(rt http.RoundTripper) http.RoundTripper { - return &wrapTransportB{rt} -} - -func (*pluginB) Login() error { return nil } - -func pluginBProvider(string, map[string]string, AuthProviderConfigPersister) (AuthProvider, error) { - return &pluginB{}, nil -} - -// pluginFailProvider simulates a registered AuthPlugin that fails to load. -func pluginFailProvider(string, map[string]string, AuthProviderConfigPersister) (AuthProvider, error) { - return nil, fmt.Errorf("Failed to load AuthProvider") -} - -type inMemoryPersister struct { - savedConfig map[string]string -} - -func (i *inMemoryPersister) Persist(config map[string]string) error { - i.savedConfig = make(map[string]string) - for k, v := range config { - i.savedConfig[k] = v - } - return nil -} - -// wrapTransportPersist increments the "roundTrips" entry from the config when -// roundTrip is called. -type wrapTransportPersist struct { - rt http.RoundTripper - config map[string]string - persister AuthProviderConfigPersister -} - -func (w *wrapTransportPersist) RoundTrip(req *http.Request) (*http.Response, error) { - roundTrips := 0 - if rtVal, ok := w.config["roundTrips"]; ok { - var err error - roundTrips, err = strconv.Atoi(rtVal) - if err != nil { - return nil, err - } - } - roundTrips++ - w.config["roundTrips"] = fmt.Sprintf("%d", roundTrips) - if err := w.persister.Persist(w.config); err != nil { - return nil, err - } - return w.rt.RoundTrip(req) -} - -type pluginPersist struct { - config map[string]string - persister AuthProviderConfigPersister -} - -func (p *pluginPersist) WrapTransport(rt http.RoundTripper) http.RoundTripper { - return &wrapTransportPersist{rt, p.config, p.persister} -} - -// Login sets the config entry "login" to "Y". -func (p *pluginPersist) Login() error { - p.config["login"] = "Y" - p.persister.Persist(p.config) - return nil -} - -func pluginPersistProvider(_ string, config map[string]string, persister AuthProviderConfigPersister) (AuthProvider, error) { - return &pluginPersist{config, persister}, nil -} diff --git a/vendor/k8s.io/client-go/rest/request_test.go b/vendor/k8s.io/client-go/rest/request_test.go deleted file mode 100755 index fac6902557..0000000000 --- a/vendor/k8s.io/client-go/rest/request_test.go +++ /dev/null @@ -1,1789 +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 rest - -import ( - "bytes" - "context" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/http/httptest" - "net/url" - "os" - "reflect" - "strings" - "syscall" - "testing" - "time" - - "github.com/golang/glog" - - "k8s.io/api/core/v1" - apiequality "k8s.io/apimachinery/pkg/api/equality" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/runtime/serializer" - "k8s.io/apimachinery/pkg/runtime/serializer/streaming" - "k8s.io/apimachinery/pkg/util/clock" - "k8s.io/apimachinery/pkg/util/diff" - "k8s.io/apimachinery/pkg/util/httpstream" - "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/kubernetes/scheme" - restclientwatch "k8s.io/client-go/rest/watch" - "k8s.io/client-go/util/flowcontrol" - utiltesting "k8s.io/client-go/util/testing" -) - -func TestNewRequestSetsAccept(t *testing.T) { - r := NewRequest(nil, "get", &url.URL{Path: "/path/"}, "", ContentConfig{}, Serializers{}, nil, nil, 0) - if r.headers.Get("Accept") != "" { - t.Errorf("unexpected headers: %#v", r.headers) - } - r = NewRequest(nil, "get", &url.URL{Path: "/path/"}, "", ContentConfig{ContentType: "application/other"}, Serializers{}, nil, nil, 0) - if r.headers.Get("Accept") != "application/other, */*" { - t.Errorf("unexpected headers: %#v", r.headers) - } -} - -type clientFunc func(req *http.Request) (*http.Response, error) - -func (f clientFunc) Do(req *http.Request) (*http.Response, error) { - return f(req) -} - -func TestRequestSetsHeaders(t *testing.T) { - server := clientFunc(func(req *http.Request) (*http.Response, error) { - if req.Header.Get("Accept") != "application/other, */*" { - t.Errorf("unexpected headers: %#v", req.Header) - } - return &http.Response{ - StatusCode: http.StatusForbidden, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - }, nil - }) - config := defaultContentConfig() - config.ContentType = "application/other" - serializers := defaultSerializers(t) - r := NewRequest(server, "get", &url.URL{Path: "/path"}, "", config, serializers, nil, nil, 0) - - // Check if all "issue" methods are setting headers. - _ = r.Do() - _, _ = r.Watch() - _, _ = r.Stream() -} - -func TestRequestWithErrorWontChange(t *testing.T) { - gvCopy := v1.SchemeGroupVersion - original := Request{ - err: errors.New("test"), - content: ContentConfig{GroupVersion: &gvCopy}, - } - r := original - changed := r.Param("foo", "bar"). - AbsPath("/abs"). - Prefix("test"). - Suffix("testing"). - Namespace("new"). - Resource("foos"). - Name("bars"). - Body("foo"). - Timeout(time.Millisecond) - if changed != &r { - t.Errorf("returned request should point to the same object") - } - if !reflect.DeepEqual(changed, &original) { - t.Errorf("expected %#v, got %#v", &original, changed) - } -} - -func TestRequestPreservesBaseTrailingSlash(t *testing.T) { - r := &Request{baseURL: &url.URL{}, pathPrefix: "/path/"} - if s := r.URL().String(); s != "/path/" { - t.Errorf("trailing slash should be preserved: %s", s) - } -} - -func TestRequestAbsPathPreservesTrailingSlash(t *testing.T) { - r := (&Request{baseURL: &url.URL{}}).AbsPath("/foo/") - if s := r.URL().String(); s != "/foo/" { - t.Errorf("trailing slash should be preserved: %s", s) - } - - r = (&Request{baseURL: &url.URL{}}).AbsPath("/foo/") - if s := r.URL().String(); s != "/foo/" { - t.Errorf("trailing slash should be preserved: %s", s) - } -} - -func TestRequestAbsPathJoins(t *testing.T) { - r := (&Request{baseURL: &url.URL{}}).AbsPath("foo/bar", "baz") - if s := r.URL().String(); s != "foo/bar/baz" { - t.Errorf("trailing slash should be preserved: %s", s) - } -} - -func TestRequestSetsNamespace(t *testing.T) { - r := (&Request{ - baseURL: &url.URL{ - Path: "/", - }, - }).Namespace("foo") - if r.namespace == "" { - t.Errorf("namespace should be set: %#v", r) - } - - if s := r.URL().String(); s != "namespaces/foo" { - t.Errorf("namespace should be in path: %s", s) - } -} - -func TestRequestOrdersNamespaceInPath(t *testing.T) { - r := (&Request{ - baseURL: &url.URL{}, - pathPrefix: "/test/", - }).Name("bar").Resource("baz").Namespace("foo") - if s := r.URL().String(); s != "/test/namespaces/foo/baz/bar" { - t.Errorf("namespace should be in order in path: %s", s) - } -} - -func TestRequestOrdersSubResource(t *testing.T) { - r := (&Request{ - baseURL: &url.URL{}, - pathPrefix: "/test/", - }).Name("bar").Resource("baz").Namespace("foo").Suffix("test").SubResource("a", "b") - if s := r.URL().String(); s != "/test/namespaces/foo/baz/bar/a/b/test" { - t.Errorf("namespace should be in order in path: %s", s) - } -} - -func TestRequestSetTwiceError(t *testing.T) { - if (&Request{}).Name("bar").Name("baz").err == nil { - t.Errorf("setting name twice should result in error") - } - if (&Request{}).Namespace("bar").Namespace("baz").err == nil { - t.Errorf("setting namespace twice should result in error") - } - if (&Request{}).Resource("bar").Resource("baz").err == nil { - t.Errorf("setting resource twice should result in error") - } - if (&Request{}).SubResource("bar").SubResource("baz").err == nil { - t.Errorf("setting subresource twice should result in error") - } -} - -func TestInvalidSegments(t *testing.T) { - invalidSegments := []string{".", "..", "test/segment", "test%2bsegment"} - setters := map[string]func(string, *Request){ - "namespace": func(s string, r *Request) { r.Namespace(s) }, - "resource": func(s string, r *Request) { r.Resource(s) }, - "name": func(s string, r *Request) { r.Name(s) }, - "subresource": func(s string, r *Request) { r.SubResource(s) }, - } - for _, invalidSegment := range invalidSegments { - for setterName, setter := range setters { - r := &Request{} - setter(invalidSegment, r) - if r.err == nil { - t.Errorf("%s: %s: expected error, got none", setterName, invalidSegment) - } - } - } -} - -func TestRequestParam(t *testing.T) { - r := (&Request{}).Param("foo", "a") - if !reflect.DeepEqual(r.params, url.Values{"foo": []string{"a"}}) { - t.Errorf("should have set a param: %#v", r) - } - - r.Param("bar", "1") - r.Param("bar", "2") - if !reflect.DeepEqual(r.params, url.Values{"foo": []string{"a"}, "bar": []string{"1", "2"}}) { - t.Errorf("should have set a param: %#v", r) - } -} - -func TestRequestVersionedParams(t *testing.T) { - r := (&Request{content: ContentConfig{GroupVersion: &v1.SchemeGroupVersion}}).Param("foo", "a") - if !reflect.DeepEqual(r.params, url.Values{"foo": []string{"a"}}) { - t.Errorf("should have set a param: %#v", r) - } - r.VersionedParams(&v1.PodLogOptions{Follow: true, Container: "bar"}, scheme.ParameterCodec) - - if !reflect.DeepEqual(r.params, url.Values{ - "foo": []string{"a"}, - "container": []string{"bar"}, - "follow": []string{"true"}, - }) { - t.Errorf("should have set a param: %#v", r) - } -} - -func TestRequestVersionedParamsFromListOptions(t *testing.T) { - r := &Request{content: ContentConfig{GroupVersion: &v1.SchemeGroupVersion}} - r.VersionedParams(&metav1.ListOptions{ResourceVersion: "1"}, scheme.ParameterCodec) - if !reflect.DeepEqual(r.params, url.Values{ - "resourceVersion": []string{"1"}, - }) { - t.Errorf("should have set a param: %#v", r) - } - - var timeout int64 = 10 - r.VersionedParams(&metav1.ListOptions{ResourceVersion: "2", TimeoutSeconds: &timeout}, scheme.ParameterCodec) - if !reflect.DeepEqual(r.params, url.Values{ - "resourceVersion": []string{"1", "2"}, - "timeoutSeconds": []string{"10"}, - }) { - t.Errorf("should have set a param: %#v %v", r.params, r.err) - } -} - -func TestRequestURI(t *testing.T) { - r := (&Request{}).Param("foo", "a") - r.Prefix("other") - r.RequestURI("/test?foo=b&a=b&c=1&c=2") - if r.pathPrefix != "/test" { - t.Errorf("path is wrong: %#v", r) - } - if !reflect.DeepEqual(r.params, url.Values{"a": []string{"b"}, "foo": []string{"b"}, "c": []string{"1", "2"}}) { - t.Errorf("should have set a param: %#v", r) - } -} - -type NotAnAPIObject struct{} - -func (obj NotAnAPIObject) GroupVersionKind() *schema.GroupVersionKind { return nil } -func (obj NotAnAPIObject) SetGroupVersionKind(gvk *schema.GroupVersionKind) {} - -func defaultContentConfig() ContentConfig { - gvCopy := v1.SchemeGroupVersion - return ContentConfig{ - ContentType: "application/json", - GroupVersion: &gvCopy, - NegotiatedSerializer: serializer.DirectCodecFactory{CodecFactory: scheme.Codecs}, - } -} - -func defaultSerializers(t *testing.T) Serializers { - config := defaultContentConfig() - serializers, err := createSerializers(config) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - return *serializers -} - -func TestRequestBody(t *testing.T) { - // test unknown type - r := (&Request{}).Body([]string{"test"}) - if r.err == nil || r.body != nil { - t.Errorf("should have set err and left body nil: %#v", r) - } - - // test error set when failing to read file - f, err := ioutil.TempFile("", "test") - if err != nil { - t.Fatalf("unable to create temp file") - } - defer f.Close() - os.Remove(f.Name()) - r = (&Request{}).Body(f.Name()) - if r.err == nil || r.body != nil { - t.Errorf("should have set err and left body nil: %#v", r) - } - - // test unencodable api object - r = (&Request{content: defaultContentConfig()}).Body(&NotAnAPIObject{}) - if r.err == nil || r.body != nil { - t.Errorf("should have set err and left body nil: %#v", r) - } -} - -func TestResultIntoWithErrReturnsErr(t *testing.T) { - res := Result{err: errors.New("test")} - if err := res.Into(&v1.Pod{}); err != res.err { - t.Errorf("should have returned exact error from result") - } -} - -func TestResultIntoWithNoBodyReturnsErr(t *testing.T) { - res := Result{ - body: []byte{}, - decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), - } - if err := res.Into(&v1.Pod{}); err == nil || !strings.Contains(err.Error(), "0-length") { - t.Errorf("should have complained about 0 length body") - } -} - -func TestURLTemplate(t *testing.T) { - uri, _ := url.Parse("http://localhost") - r := NewRequest(nil, "POST", uri, "", ContentConfig{GroupVersion: &schema.GroupVersion{Group: "test"}}, Serializers{}, nil, nil, 0) - r.Prefix("pre1").Resource("r1").Namespace("ns").Name("nm").Param("p0", "v0") - full := r.URL() - if full.String() != "http://localhost/pre1/namespaces/ns/r1/nm?p0=v0" { - t.Errorf("unexpected initial URL: %s", full) - } - actualURL := r.finalURLTemplate() - actual := actualURL.String() - expected := "http://localhost/pre1/namespaces/%7Bnamespace%7D/r1/%7Bname%7D?p0=%7Bvalue%7D" - if actual != expected { - t.Errorf("unexpected URL template: %s %s", actual, expected) - } - if r.URL().String() != full.String() { - t.Errorf("creating URL template changed request: %s -> %s", full.String(), r.URL().String()) - } -} - -func TestTransformResponse(t *testing.T) { - invalid := []byte("aaaaa") - uri, _ := url.Parse("http://localhost") - testCases := []struct { - Response *http.Response - Data []byte - Created bool - Error bool - ErrFn func(err error) bool - }{ - {Response: &http.Response{StatusCode: 200}, Data: []byte{}}, - {Response: &http.Response{StatusCode: 201}, Data: []byte{}, Created: true}, - {Response: &http.Response{StatusCode: 199}, Error: true}, - {Response: &http.Response{StatusCode: 500}, Error: true}, - {Response: &http.Response{StatusCode: 422}, Error: true}, - {Response: &http.Response{StatusCode: 409}, Error: true}, - {Response: &http.Response{StatusCode: 404}, Error: true}, - {Response: &http.Response{StatusCode: 401}, Error: true}, - { - Response: &http.Response{ - StatusCode: 401, - Header: http.Header{"Content-Type": []string{"application/json"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), - }, - Error: true, - ErrFn: func(err error) bool { - return err.Error() != "aaaaa" && apierrors.IsUnauthorized(err) - }, - }, - { - Response: &http.Response{ - StatusCode: 401, - Header: http.Header{"Content-Type": []string{"text/any"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), - }, - Error: true, - ErrFn: func(err error) bool { - return strings.Contains(err.Error(), "server has asked for the client to provide") && apierrors.IsUnauthorized(err) - }, - }, - {Response: &http.Response{StatusCode: 403}, Error: true}, - {Response: &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid}, - {Response: &http.Response{StatusCode: 200, Body: ioutil.NopCloser(bytes.NewReader(invalid))}, Data: invalid}, - } - for i, test := range testCases { - r := NewRequest(nil, "", uri, "", defaultContentConfig(), defaultSerializers(t), nil, nil, 0) - if test.Response.Body == nil { - test.Response.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) - } - result := r.transformResponse(test.Response, &http.Request{}) - response, created, err := result.body, result.statusCode == http.StatusCreated, result.err - hasErr := err != nil - if hasErr != test.Error { - t.Errorf("%d: unexpected error: %t %v", i, test.Error, err) - } else if hasErr && test.Response.StatusCode > 399 { - status, ok := err.(apierrors.APIStatus) - if !ok { - t.Errorf("%d: response should have been transformable into APIStatus: %v", i, err) - continue - } - if int(status.Status().Code) != test.Response.StatusCode { - t.Errorf("%d: status code did not match response: %#v", i, status.Status()) - } - } - if test.ErrFn != nil && !test.ErrFn(err) { - t.Errorf("%d: error function did not match: %v", i, err) - } - if !(test.Data == nil && response == nil) && !apiequality.Semantic.DeepDerivative(test.Data, response) { - t.Errorf("%d: unexpected response: %#v %#v", i, test.Data, response) - } - if test.Created != created { - t.Errorf("%d: expected created %t, got %t", i, test.Created, created) - } - } -} - -type renegotiator struct { - called bool - contentType string - params map[string]string - decoder runtime.Decoder - err error -} - -func (r *renegotiator) invoke(contentType string, params map[string]string) (runtime.Decoder, error) { - r.called = true - r.contentType = contentType - r.params = params - return r.decoder, r.err -} - -func TestTransformResponseNegotiate(t *testing.T) { - invalid := []byte("aaaaa") - uri, _ := url.Parse("http://localhost") - testCases := []struct { - Response *http.Response - Data []byte - Created bool - Error bool - ErrFn func(err error) bool - - ContentType string - Called bool - ExpectContentType string - Decoder runtime.Decoder - NegotiateErr error - }{ - { - ContentType: "application/json", - Response: &http.Response{ - StatusCode: 401, - Header: http.Header{"Content-Type": []string{"application/json"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), - }, - Error: true, - ErrFn: func(err error) bool { - return err.Error() != "aaaaa" && apierrors.IsUnauthorized(err) - }, - }, - { - ContentType: "application/json", - Response: &http.Response{ - StatusCode: 401, - Header: http.Header{"Content-Type": []string{"application/protobuf"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), - }, - Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), - - Called: true, - ExpectContentType: "application/protobuf", - - Error: true, - ErrFn: func(err error) bool { - return err.Error() != "aaaaa" && apierrors.IsUnauthorized(err) - }, - }, - { - ContentType: "application/json", - Response: &http.Response{ - StatusCode: 500, - Header: http.Header{"Content-Type": []string{"application/,others"}}, - }, - Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), - - Error: true, - ErrFn: func(err error) bool { - return err.Error() == "Internal error occurred: mime: expected token after slash" && err.(apierrors.APIStatus).Status().Code == 500 - }, - }, - { - // no negotiation when no content type specified - Response: &http.Response{ - StatusCode: 200, - Header: http.Header{"Content-Type": []string{"text/any"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), - }, - Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), - }, - { - // no negotiation when no response content type specified - ContentType: "text/any", - Response: &http.Response{ - StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), - }, - Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), - }, - { - // unrecognized content type is not handled - ContentType: "application/json", - Response: &http.Response{ - StatusCode: 404, - Header: http.Header{"Content-Type": []string{"application/unrecognized"}}, - Body: ioutil.NopCloser(bytes.NewReader(invalid)), - }, - Decoder: scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), - - NegotiateErr: fmt.Errorf("aaaa"), - Called: true, - ExpectContentType: "application/unrecognized", - - Error: true, - ErrFn: func(err error) bool { - return err.Error() != "aaaaa" && apierrors.IsNotFound(err) - }, - }, - } - for i, test := range testCases { - serializers := defaultSerializers(t) - negotiator := &renegotiator{ - decoder: test.Decoder, - err: test.NegotiateErr, - } - serializers.RenegotiatedDecoder = negotiator.invoke - contentConfig := defaultContentConfig() - contentConfig.ContentType = test.ContentType - r := NewRequest(nil, "", uri, "", contentConfig, serializers, nil, nil, 0) - if test.Response.Body == nil { - test.Response.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) - } - result := r.transformResponse(test.Response, &http.Request{}) - _, err := result.body, result.err - hasErr := err != nil - if hasErr != test.Error { - t.Errorf("%d: unexpected error: %t %v", i, test.Error, err) - continue - } else if hasErr && test.Response.StatusCode > 399 { - status, ok := err.(apierrors.APIStatus) - if !ok { - t.Errorf("%d: response should have been transformable into APIStatus: %v", i, err) - continue - } - if int(status.Status().Code) != test.Response.StatusCode { - t.Errorf("%d: status code did not match response: %#v", i, status.Status()) - } - } - if test.ErrFn != nil && !test.ErrFn(err) { - t.Errorf("%d: error function did not match: %v", i, err) - } - if negotiator.called != test.Called { - t.Errorf("%d: negotiator called %t != %t", i, negotiator.called, test.Called) - } - if !test.Called { - continue - } - if negotiator.contentType != test.ExpectContentType { - t.Errorf("%d: unexpected content type: %s", i, negotiator.contentType) - } - } -} - -func TestTransformUnstructuredError(t *testing.T) { - testCases := []struct { - Req *http.Request - Res *http.Response - - Resource string - Name string - - ErrFn func(error) bool - Transformed error - }{ - { - Resource: "foo", - Name: "bar", - Req: &http.Request{ - Method: "POST", - }, - Res: &http.Response{ - StatusCode: http.StatusConflict, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, - ErrFn: apierrors.IsAlreadyExists, - }, - { - Resource: "foo", - Name: "bar", - Req: &http.Request{ - Method: "PUT", - }, - Res: &http.Response{ - StatusCode: http.StatusConflict, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, - ErrFn: apierrors.IsConflict, - }, - { - Resource: "foo", - Name: "bar", - Req: &http.Request{}, - Res: &http.Response{ - StatusCode: http.StatusNotFound, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, - ErrFn: apierrors.IsNotFound, - }, - { - Req: &http.Request{}, - Res: &http.Response{ - StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewReader(nil)), - }, - ErrFn: apierrors.IsBadRequest, - }, - { - // status in response overrides transformed result - Req: &http.Request{}, - Res: &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","status":"Failure","code":404}`)))}, - ErrFn: apierrors.IsBadRequest, - Transformed: &apierrors.StatusError{ - ErrStatus: metav1.Status{Status: metav1.StatusFailure, Code: http.StatusNotFound}, - }, - }, - { - // successful status is ignored - Req: &http.Request{}, - Res: &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","status":"Success","code":404}`)))}, - ErrFn: apierrors.IsBadRequest, - }, - { - // empty object does not change result - Req: &http.Request{}, - Res: &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{}`)))}, - ErrFn: apierrors.IsBadRequest, - }, - { - // we default apiVersion for backwards compatibility with old clients - // TODO: potentially remove in 1.7 - Req: &http.Request{}, - Res: &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","status":"Failure","code":404}`)))}, - ErrFn: apierrors.IsBadRequest, - Transformed: &apierrors.StatusError{ - ErrStatus: metav1.Status{Status: metav1.StatusFailure, Code: http.StatusNotFound}, - }, - }, - { - // we do not default kind - Req: &http.Request{}, - Res: &http.Response{StatusCode: http.StatusBadRequest, Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"status":"Failure","code":404}`)))}, - ErrFn: apierrors.IsBadRequest, - }, - } - - for i, testCase := range testCases { - r := &Request{ - content: defaultContentConfig(), - serializers: defaultSerializers(t), - resourceName: testCase.Name, - resource: testCase.Resource, - } - result := r.transformResponse(testCase.Res, testCase.Req) - err := result.err - if !testCase.ErrFn(err) { - t.Errorf("unexpected error: %v", err) - continue - } - if !apierrors.IsUnexpectedServerError(err) { - t.Errorf("%d: unexpected error type: %v", i, err) - } - if len(testCase.Name) != 0 && !strings.Contains(err.Error(), testCase.Name) { - t.Errorf("unexpected error string: %s", err) - } - if len(testCase.Resource) != 0 && !strings.Contains(err.Error(), testCase.Resource) { - t.Errorf("unexpected error string: %s", err) - } - - // verify Error() properly transforms the error - transformed := result.Error() - expect := testCase.Transformed - if expect == nil { - expect = err - } - if !reflect.DeepEqual(expect, transformed) { - t.Errorf("%d: unexpected Error(): %s", i, diff.ObjectReflectDiff(expect, transformed)) - } - - // verify result.Get properly transforms the error - if _, err := result.Get(); !reflect.DeepEqual(expect, err) { - t.Errorf("%d: unexpected error on Get(): %s", i, diff.ObjectReflectDiff(expect, err)) - } - - // verify result.Into properly handles the error - if err := result.Into(&v1.Pod{}); !reflect.DeepEqual(expect, err) { - t.Errorf("%d: unexpected error on Into(): %s", i, diff.ObjectReflectDiff(expect, err)) - } - - // verify result.Raw leaves the error in the untransformed state - if _, err := result.Raw(); !reflect.DeepEqual(result.err, err) { - t.Errorf("%d: unexpected error on Raw(): %s", i, diff.ObjectReflectDiff(expect, err)) - } - } -} - -func TestRequestWatch(t *testing.T) { - testCases := []struct { - Request *Request - Err bool - ErrFn func(error) bool - Empty bool - }{ - { - Request: &Request{err: errors.New("bail")}, - Err: true, - }, - { - Request: &Request{baseURL: &url.URL{}, pathPrefix: "%"}, - Err: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, errors.New("err") - }), - baseURL: &url.URL{}, - }, - Err: true, - }, - { - Request: &Request{ - content: defaultContentConfig(), - serializers: defaultSerializers(t), - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusForbidden, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - }, nil - }), - baseURL: &url.URL{}, - }, - Err: true, - ErrFn: func(err error) bool { - return apierrors.IsForbidden(err) - }, - }, - { - Request: &Request{ - content: defaultContentConfig(), - serializers: defaultSerializers(t), - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusUnauthorized, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - }, nil - }), - baseURL: &url.URL{}, - }, - Err: true, - ErrFn: func(err error) bool { - return apierrors.IsUnauthorized(err) - }, - }, - { - Request: &Request{ - content: defaultContentConfig(), - serializers: defaultSerializers(t), - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusUnauthorized, - Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &metav1.Status{ - Status: metav1.StatusFailure, - Reason: metav1.StatusReasonUnauthorized, - })))), - }, nil - }), - baseURL: &url.URL{}, - }, - Err: true, - ErrFn: func(err error) bool { - return apierrors.IsUnauthorized(err) - }, - }, - { - Request: &Request{ - serializers: defaultSerializers(t), - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, io.EOF - }), - baseURL: &url.URL{}, - }, - Empty: true, - }, - { - Request: &Request{ - serializers: defaultSerializers(t), - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, &url.Error{Err: io.EOF} - }), - baseURL: &url.URL{}, - }, - Empty: true, - }, - { - Request: &Request{ - serializers: defaultSerializers(t), - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, errors.New("http: can't write HTTP request on broken connection") - }), - baseURL: &url.URL{}, - }, - Empty: true, - }, - { - Request: &Request{ - serializers: defaultSerializers(t), - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, errors.New("foo: connection reset by peer") - }), - baseURL: &url.URL{}, - }, - Empty: true, - }, - } - for i, testCase := range testCases { - t.Logf("testcase %v", testCase.Request) - testCase.Request.backoffMgr = &NoBackoff{} - watch, err := testCase.Request.Watch() - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: expected %t, got %t: %v", i, testCase.Err, hasErr, err) - continue - } - if testCase.ErrFn != nil && !testCase.ErrFn(err) { - t.Errorf("%d: error not valid: %v", i, err) - } - if hasErr && watch != nil { - t.Errorf("%d: watch should be nil when error is returned", i) - continue - } - if testCase.Empty { - _, ok := <-watch.ResultChan() - if ok { - t.Errorf("%d: expected the watch to be empty: %#v", i, watch) - } - } - } -} - -func TestRequestStream(t *testing.T) { - testCases := []struct { - Request *Request - Err bool - ErrFn func(error) bool - }{ - { - Request: &Request{err: errors.New("bail")}, - Err: true, - }, - { - Request: &Request{baseURL: &url.URL{}, pathPrefix: "%"}, - Err: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, errors.New("err") - }), - baseURL: &url.URL{}, - }, - Err: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusUnauthorized, - Body: ioutil.NopCloser(bytes.NewReader([]byte(runtime.EncodeOrDie(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), &metav1.Status{ - Status: metav1.StatusFailure, - Reason: metav1.StatusReasonUnauthorized, - })))), - }, nil - }), - content: defaultContentConfig(), - serializers: defaultSerializers(t), - baseURL: &url.URL{}, - }, - Err: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: http.StatusBadRequest, - Body: ioutil.NopCloser(bytes.NewReader([]byte(`{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"a container name must be specified for pod kube-dns-v20-mz5cv, choose one of: [kubedns dnsmasq healthz]","reason":"BadRequest","code":400}`))), - }, nil - }), - content: defaultContentConfig(), - serializers: defaultSerializers(t), - baseURL: &url.URL{}, - }, - Err: true, - ErrFn: func(err error) bool { - if err.Error() == "a container name must be specified for pod kube-dns-v20-mz5cv, choose one of: [kubedns dnsmasq healthz]" { - return true - } - return false - }, - }, - } - for i, testCase := range testCases { - testCase.Request.backoffMgr = &NoBackoff{} - body, err := testCase.Request.Stream() - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: expected %t, got %t: %v", i, testCase.Err, hasErr, err) - } - if hasErr && body != nil { - t.Errorf("%d: body should be nil when error is returned", i) - } - - if hasErr { - if testCase.ErrFn != nil && !testCase.ErrFn(err) { - t.Errorf("unexpected error: %v", err) - } - } - } -} - -type fakeUpgradeConnection struct{} - -func (c *fakeUpgradeConnection) CreateStream(headers http.Header) (httpstream.Stream, error) { - return nil, nil -} -func (c *fakeUpgradeConnection) Close() error { - return nil -} -func (c *fakeUpgradeConnection) CloseChan() <-chan bool { - return make(chan bool) -} -func (c *fakeUpgradeConnection) SetIdleTimeout(timeout time.Duration) { -} - -type fakeUpgradeRoundTripper struct { - req *http.Request - conn httpstream.Connection -} - -func (f *fakeUpgradeRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - f.req = req - b := []byte{} - body := ioutil.NopCloser(bytes.NewReader(b)) - resp := &http.Response{ - StatusCode: 101, - Body: body, - } - return resp, nil -} - -func (f *fakeUpgradeRoundTripper) NewConnection(resp *http.Response) (httpstream.Connection, error) { - return f.conn, nil -} - -func TestRequestDo(t *testing.T) { - testCases := []struct { - Request *Request - Err bool - }{ - { - Request: &Request{err: errors.New("bail")}, - Err: true, - }, - { - Request: &Request{baseURL: &url.URL{}, pathPrefix: "%"}, - Err: true, - }, - { - Request: &Request{ - client: clientFunc(func(req *http.Request) (*http.Response, error) { - return nil, errors.New("err") - }), - baseURL: &url.URL{}, - }, - Err: true, - }, - } - for i, testCase := range testCases { - testCase.Request.backoffMgr = &NoBackoff{} - body, err := testCase.Request.Do().Raw() - hasErr := err != nil - if hasErr != testCase.Err { - t.Errorf("%d: expected %t, got %t: %v", i, testCase.Err, hasErr, err) - } - if hasErr && body != nil { - t.Errorf("%d: body should be nil when error is returned", i) - } - } -} - -func TestDoRequestNewWay(t *testing.T) { - reqBody := "request body" - expectedObj := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{ - Protocol: "TCP", - Port: 12345, - TargetPort: intstr.FromInt(12345), - }}}} - expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expectedObj) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 200, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - defer testServer.Close() - c := testRESTClient(t, testServer) - obj, err := c.Verb("POST"). - Prefix("foo", "bar"). - Suffix("baz"). - Timeout(time.Second). - Body([]byte(reqBody)). - Do().Get() - if err != nil { - t.Errorf("Unexpected error: %v %#v", err, err) - return - } - if obj == nil { - t.Error("nil obj") - } else if !apiequality.Semantic.DeepDerivative(expectedObj, obj) { - t.Errorf("Expected: %#v, got %#v", expectedObj, obj) - } - requestURL := defaultResourcePathWithPrefix("foo/bar", "", "", "baz") - requestURL += "?timeout=1s" - fakeHandler.ValidateRequest(t, requestURL, "POST", &reqBody) -} - -// This test assumes that the client implementation backs off exponentially, for an individual request. -func TestBackoffLifecycle(t *testing.T) { - count := 0 - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - count++ - t.Logf("Attempt %d", count) - if count == 5 || count == 9 { - w.WriteHeader(http.StatusOK) - return - } else { - w.WriteHeader(http.StatusGatewayTimeout) - return - } - })) - defer testServer.Close() - c := testRESTClient(t, testServer) - - // Test backoff recovery and increase. This correlates to the constants - // which are used in the server implementation returning StatusOK above. - seconds := []int{0, 1, 2, 4, 8, 0, 1, 2, 4, 0} - request := c.Verb("POST").Prefix("backofftest").Suffix("abc") - clock := clock.FakeClock{} - request.backoffMgr = &URLBackoff{ - // Use a fake backoff here to avoid flakes and speed the test up. - Backoff: flowcontrol.NewFakeBackOff( - time.Duration(1)*time.Second, - time.Duration(200)*time.Second, - &clock, - )} - - for _, sec := range seconds { - thisBackoff := request.backoffMgr.CalculateBackoff(request.URL()) - t.Logf("Current backoff %v", thisBackoff) - if thisBackoff != time.Duration(sec)*time.Second { - t.Errorf("Backoff is %v instead of %v", thisBackoff, sec) - } - now := clock.Now() - request.DoRaw() - elapsed := clock.Since(now) - if clock.Since(now) != thisBackoff { - t.Errorf("CalculatedBackoff not honored by clock: Expected time of %v, but got %v ", thisBackoff, elapsed) - } - } -} - -type testBackoffManager struct { - sleeps []time.Duration -} - -func (b *testBackoffManager) UpdateBackoff(actualUrl *url.URL, err error, responseCode int) { -} - -func (b *testBackoffManager) CalculateBackoff(actualUrl *url.URL) time.Duration { - return time.Duration(0) -} - -func (b *testBackoffManager) Sleep(d time.Duration) { - b.sleeps = append(b.sleeps, d) -} - -func TestCheckRetryClosesBody(t *testing.T) { - count := 0 - ch := make(chan struct{}) - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - count++ - t.Logf("attempt %d", count) - if count >= 5 { - w.WriteHeader(http.StatusOK) - close(ch) - return - } - w.Header().Set("Retry-After", "1") - http.Error(w, "Too many requests, please try again later.", http.StatusTooManyRequests) - })) - defer testServer.Close() - - backoffMgr := &testBackoffManager{} - expectedSleeps := []time.Duration{0, time.Second, 0, time.Second, 0, time.Second, 0, time.Second, 0} - - c := testRESTClient(t, testServer) - c.createBackoffMgr = func() BackoffManager { return backoffMgr } - _, err := c.Verb("POST"). - Prefix("foo", "bar"). - Suffix("baz"). - Timeout(time.Second). - Body([]byte(strings.Repeat("abcd", 1000))). - DoRaw() - if err != nil { - t.Fatalf("Unexpected error: %v %#v", err, err) - } - <-ch - if count != 5 { - t.Errorf("unexpected retries: %d", count) - } - if !reflect.DeepEqual(backoffMgr.sleeps, expectedSleeps) { - t.Errorf("unexpected sleeps, expected: %v, got: %v", expectedSleeps, backoffMgr.sleeps) - } -} - -func TestConnectionResetByPeerIsRetried(t *testing.T) { - count := 0 - backoff := &testBackoffManager{} - req := &Request{ - verb: "GET", - client: clientFunc(func(req *http.Request) (*http.Response, error) { - count++ - if count >= 3 { - return &http.Response{ - StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - }, nil - } - return nil, &net.OpError{Err: syscall.ECONNRESET} - }), - backoffMgr: backoff, - } - // We expect two retries of "connection reset by peer" and the success. - _, err := req.Do().Raw() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - // We have a sleep before each retry (including the initial one) and for - // every "retry-after" call - thus 5 together. - if len(backoff.sleeps) != 5 { - t.Errorf("Expected 5 retries, got: %d", len(backoff.sleeps)) - } -} - -func TestCheckRetryHandles429And5xx(t *testing.T) { - count := 0 - ch := make(chan struct{}) - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - data, err := ioutil.ReadAll(req.Body) - if err != nil { - t.Fatalf("unable to read request body: %v", err) - } - if !bytes.Equal(data, []byte(strings.Repeat("abcd", 1000))) { - t.Fatalf("retry did not send a complete body: %s", data) - } - t.Logf("attempt %d", count) - if count >= 4 { - w.WriteHeader(http.StatusOK) - close(ch) - return - } - w.Header().Set("Retry-After", "0") - w.WriteHeader([]int{http.StatusTooManyRequests, 500, 501, 504}[count]) - count++ - })) - defer testServer.Close() - - c := testRESTClient(t, testServer) - _, err := c.Verb("POST"). - Prefix("foo", "bar"). - Suffix("baz"). - Timeout(time.Second). - Body([]byte(strings.Repeat("abcd", 1000))). - DoRaw() - if err != nil { - t.Fatalf("Unexpected error: %v %#v", err, err) - } - <-ch - if count != 4 { - t.Errorf("unexpected retries: %d", count) - } -} - -func BenchmarkCheckRetryClosesBody(b *testing.B) { - count := 0 - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - count++ - if count%3 == 0 { - w.WriteHeader(http.StatusOK) - return - } - w.Header().Set("Retry-After", "0") - w.WriteHeader(http.StatusTooManyRequests) - })) - defer testServer.Close() - - c := testRESTClient(b, testServer) - r := c.Verb("POST"). - Prefix("foo", "bar"). - Suffix("baz"). - Timeout(time.Second). - Body([]byte(strings.Repeat("abcd", 1000))) - - for i := 0; i < b.N; i++ { - if _, err := r.DoRaw(); err != nil { - b.Fatalf("Unexpected error: %v %#v", err, err) - } - } -} - -func TestDoRequestNewWayReader(t *testing.T) { - reqObj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} - reqBodyExpected, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), reqObj) - expectedObj := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{ - Protocol: "TCP", - Port: 12345, - TargetPort: intstr.FromInt(12345), - }}}} - expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expectedObj) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 200, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - defer testServer.Close() - c := testRESTClient(t, testServer) - obj, err := c.Verb("POST"). - Resource("bar"). - Name("baz"). - Prefix("foo"). - Timeout(time.Second). - Body(bytes.NewBuffer(reqBodyExpected)). - Do().Get() - if err != nil { - t.Errorf("Unexpected error: %v %#v", err, err) - return - } - if obj == nil { - t.Error("nil obj") - } else if !apiequality.Semantic.DeepDerivative(expectedObj, obj) { - t.Errorf("Expected: %#v, got %#v", expectedObj, obj) - } - tmpStr := string(reqBodyExpected) - requestURL := defaultResourcePathWithPrefix("foo", "bar", "", "baz") - requestURL += "?timeout=1s" - fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr) -} - -func TestDoRequestNewWayObj(t *testing.T) { - reqObj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} - reqBodyExpected, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), reqObj) - expectedObj := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{ - Protocol: "TCP", - Port: 12345, - TargetPort: intstr.FromInt(12345), - }}}} - expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expectedObj) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 200, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - defer testServer.Close() - c := testRESTClient(t, testServer) - obj, err := c.Verb("POST"). - Suffix("baz"). - Name("bar"). - Resource("foo"). - Timeout(time.Second). - Body(reqObj). - Do().Get() - if err != nil { - t.Errorf("Unexpected error: %v %#v", err, err) - return - } - if obj == nil { - t.Error("nil obj") - } else if !apiequality.Semantic.DeepDerivative(expectedObj, obj) { - t.Errorf("Expected: %#v, got %#v", expectedObj, obj) - } - tmpStr := string(reqBodyExpected) - requestURL := defaultResourcePathWithPrefix("", "foo", "", "bar/baz") - requestURL += "?timeout=1s" - fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr) -} - -func TestDoRequestNewWayFile(t *testing.T) { - reqObj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} - reqBodyExpected, err := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), reqObj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - file, err := ioutil.TempFile("", "foo") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - defer file.Close() - defer os.Remove(file.Name()) - - _, err = file.Write(reqBodyExpected) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - expectedObj := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{ - Protocol: "TCP", - Port: 12345, - TargetPort: intstr.FromInt(12345), - }}}} - expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expectedObj) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 200, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - defer testServer.Close() - c := testRESTClient(t, testServer) - wasCreated := true - obj, err := c.Verb("POST"). - Prefix("foo/bar", "baz"). - Timeout(time.Second). - Body(file.Name()). - Do().WasCreated(&wasCreated).Get() - if err != nil { - t.Errorf("Unexpected error: %v %#v", err, err) - return - } - if obj == nil { - t.Error("nil obj") - } else if !apiequality.Semantic.DeepDerivative(expectedObj, obj) { - t.Errorf("Expected: %#v, got %#v", expectedObj, obj) - } - if wasCreated { - t.Errorf("expected object was created") - } - tmpStr := string(reqBodyExpected) - requestURL := defaultResourcePathWithPrefix("foo/bar/baz", "", "", "") - requestURL += "?timeout=1s" - fakeHandler.ValidateRequest(t, requestURL, "POST", &tmpStr) -} - -func TestWasCreated(t *testing.T) { - reqObj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} - reqBodyExpected, err := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), reqObj) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - expectedObj := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{ - Protocol: "TCP", - Port: 12345, - TargetPort: intstr.FromInt(12345), - }}}} - expectedBody, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expectedObj) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 201, - ResponseBody: string(expectedBody), - T: t, - } - testServer := httptest.NewServer(&fakeHandler) - defer testServer.Close() - c := testRESTClient(t, testServer) - wasCreated := false - obj, err := c.Verb("PUT"). - Prefix("foo/bar", "baz"). - Timeout(time.Second). - Body(reqBodyExpected). - Do().WasCreated(&wasCreated).Get() - if err != nil { - t.Errorf("Unexpected error: %v %#v", err, err) - return - } - if obj == nil { - t.Error("nil obj") - } else if !apiequality.Semantic.DeepDerivative(expectedObj, obj) { - t.Errorf("Expected: %#v, got %#v", expectedObj, obj) - } - if !wasCreated { - t.Errorf("Expected object was created") - } - - tmpStr := string(reqBodyExpected) - requestURL := defaultResourcePathWithPrefix("foo/bar/baz", "", "", "") - requestURL += "?timeout=1s" - fakeHandler.ValidateRequest(t, requestURL, "PUT", &tmpStr) -} - -func TestVerbs(t *testing.T) { - c := testRESTClient(t, nil) - if r := c.Post(); r.verb != "POST" { - t.Errorf("Post verb is wrong") - } - if r := c.Put(); r.verb != "PUT" { - t.Errorf("Put verb is wrong") - } - if r := c.Get(); r.verb != "GET" { - t.Errorf("Get verb is wrong") - } - if r := c.Delete(); r.verb != "DELETE" { - t.Errorf("Delete verb is wrong") - } -} - -func TestAbsPath(t *testing.T) { - for i, tc := range []struct { - configPrefix string - resourcePrefix string - absPath string - wantsAbsPath string - }{ - {"/", "", "", "/"}, - {"", "", "/", "/"}, - {"", "", "/api", "/api"}, - {"", "", "/api/", "/api/"}, - {"", "", "/apis", "/apis"}, - {"", "/foo", "/bar/foo", "/bar/foo"}, - {"", "/api/foo/123", "/bar/foo", "/bar/foo"}, - {"/p1", "", "", "/p1"}, - {"/p1", "", "/", "/p1/"}, - {"/p1", "", "/api", "/p1/api"}, - {"/p1", "", "/apis", "/p1/apis"}, - {"/p1", "/r1", "/apis", "/p1/apis"}, - {"/p1", "/api/r1", "/apis", "/p1/apis"}, - {"/p1/api/p2", "", "", "/p1/api/p2"}, - {"/p1/api/p2", "", "/", "/p1/api/p2/"}, - {"/p1/api/p2", "", "/api", "/p1/api/p2/api"}, - {"/p1/api/p2", "", "/api/", "/p1/api/p2/api/"}, - {"/p1/api/p2", "/r1", "/api/", "/p1/api/p2/api/"}, - {"/p1/api/p2", "/api/r1", "/api/", "/p1/api/p2/api/"}, - } { - u, _ := url.Parse("http://localhost:123" + tc.configPrefix) - r := NewRequest(nil, "POST", u, "", ContentConfig{GroupVersion: &schema.GroupVersion{Group: "test"}}, Serializers{}, nil, nil, 0).Prefix(tc.resourcePrefix).AbsPath(tc.absPath) - if r.pathPrefix != tc.wantsAbsPath { - t.Errorf("test case %d failed, unexpected path: %q, expected %q", i, r.pathPrefix, tc.wantsAbsPath) - } - } -} - -func TestUnacceptableParamNames(t *testing.T) { - table := []struct { - name string - testVal string - expectSuccess bool - }{ - // timeout is no longer "protected" - {"timeout", "42", true}, - } - - for _, item := range table { - c := testRESTClient(t, nil) - r := c.Get().setParam(item.name, item.testVal) - if e, a := item.expectSuccess, r.err == nil; e != a { - t.Errorf("expected %v, got %v (%v)", e, a, r.err) - } - } -} - -func TestBody(t *testing.T) { - const data = "test payload" - - obj := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} - bodyExpected, _ := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), obj) - - f, err := ioutil.TempFile("", "test_body") - if err != nil { - t.Fatalf("TempFile error: %v", err) - } - if _, err := f.WriteString(data); err != nil { - t.Fatalf("TempFile.WriteString error: %v", err) - } - f.Close() - defer os.Remove(f.Name()) - - var nilObject *v1.DeleteOptions - typedObject := interface{}(nilObject) - c := testRESTClient(t, nil) - tests := []struct { - input interface{} - expected string - headers map[string]string - }{ - {[]byte(data), data, nil}, - {f.Name(), data, nil}, - {strings.NewReader(data), data, nil}, - {obj, string(bodyExpected), map[string]string{"Content-Type": "application/json"}}, - {typedObject, "", nil}, - } - for i, tt := range tests { - r := c.Post().Body(tt.input) - if r.err != nil { - t.Errorf("%d: r.Body(%#v) error: %v", i, tt, r.err) - continue - } - if tt.headers != nil { - for k, v := range tt.headers { - if r.headers.Get(k) != v { - t.Errorf("%d: r.headers[%q] = %q; want %q", i, k, v, v) - } - } - } - - if r.body == nil { - if len(tt.expected) != 0 { - t.Errorf("%d: r.body = %q; want %q", i, r.body, tt.expected) - } - continue - } - buf := make([]byte, len(tt.expected)) - if _, err := r.body.Read(buf); err != nil { - t.Errorf("%d: r.body.Read error: %v", i, err) - continue - } - body := string(buf) - if body != tt.expected { - t.Errorf("%d: r.body = %q; want %q", i, body, tt.expected) - } - } -} - -func TestWatch(t *testing.T) { - var table = []struct { - t watch.EventType - obj runtime.Object - }{ - {watch.Added, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "first"}}}, - {watch.Modified, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "second"}}}, - {watch.Deleted, &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "last"}}}, - } - - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - flusher, ok := w.(http.Flusher) - if !ok { - panic("need flusher!") - } - - w.Header().Set("Transfer-Encoding", "chunked") - w.WriteHeader(http.StatusOK) - flusher.Flush() - - encoder := restclientwatch.NewEncoder(streaming.NewEncoder(w, scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion)), scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion)) - for _, item := range table { - if err := encoder.Encode(&watch.Event{Type: item.t, Object: item.obj}); err != nil { - panic(err) - } - flusher.Flush() - } - })) - defer testServer.Close() - - s := testRESTClient(t, testServer) - watching, err := s.Get().Prefix("path/to/watch/thing").Watch() - if err != nil { - t.Fatalf("Unexpected error") - } - - for _, item := range table { - got, ok := <-watching.ResultChan() - if !ok { - t.Fatalf("Unexpected early close") - } - if e, a := item.t, got.Type; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - if e, a := item.obj, got.Object; !apiequality.Semantic.DeepDerivative(e, a) { - t.Errorf("Expected %v, got %v", e, a) - } - } - - _, ok := <-watching.ResultChan() - if ok { - t.Fatal("Unexpected non-close") - } -} - -func TestStream(t *testing.T) { - expectedBody := "expected body" - - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - flusher, ok := w.(http.Flusher) - if !ok { - panic("need flusher!") - } - w.Header().Set("Transfer-Encoding", "chunked") - w.WriteHeader(http.StatusOK) - w.Write([]byte(expectedBody)) - flusher.Flush() - })) - defer testServer.Close() - - s := testRESTClient(t, testServer) - readCloser, err := s.Get().Prefix("path/to/stream/thing").Stream() - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - defer readCloser.Close() - buf := new(bytes.Buffer) - buf.ReadFrom(readCloser) - resultBody := buf.String() - - if expectedBody != resultBody { - t.Errorf("Expected %s, got %s", expectedBody, resultBody) - } -} - -func testRESTClient(t testing.TB, srv *httptest.Server) *RESTClient { - baseURL, _ := url.Parse("http://localhost") - if srv != nil { - var err error - baseURL, err = url.Parse(srv.URL) - if err != nil { - t.Fatalf("failed to parse test URL: %v", err) - } - } - versionedAPIPath := defaultResourcePathWithPrefix("", "", "", "") - client, err := NewRESTClient(baseURL, versionedAPIPath, defaultContentConfig(), 0, 0, nil, nil) - if err != nil { - t.Fatalf("failed to create a client: %v", err) - } - return client -} - -func TestDoContext(t *testing.T) { - receivedCh := make(chan struct{}) - block := make(chan struct{}) - testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - close(receivedCh) - <-block - w.WriteHeader(http.StatusOK) - })) - defer testServer.Close() - defer close(block) - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - go func() { - <-receivedCh - cancel() - }() - - c := testRESTClient(t, testServer) - _, err := c.Verb("GET"). - Context(ctx). - Prefix("foo"). - DoRaw() - if err == nil { - t.Fatal("Expected context cancellation error") - } -} - -func buildString(length int) string { - s := make([]byte, length) - for i := range s { - s[i] = 'a' - } - return string(s) -} - -func TestTruncateBody(t *testing.T) { - tests := []struct { - body string - want string - level string - }{ - // Anything below 8 is completely truncated - { - body: "Completely truncated below 8", - want: " [truncated 28 chars]", - level: "0", - }, - // Small strings are not truncated by high levels - { - body: "Small body never gets truncated", - want: "Small body never gets truncated", - level: "10", - }, - { - body: "Small body never gets truncated", - want: "Small body never gets truncated", - level: "8", - }, - // Strings are truncated to 1024 if level is less than 9. - { - body: buildString(2000), - level: "8", - want: fmt.Sprintf("%s [truncated 976 chars]", buildString(1024)), - }, - // Strings are truncated to 10240 if level is 9. - { - body: buildString(20000), - level: "9", - want: fmt.Sprintf("%s [truncated 9760 chars]", buildString(10240)), - }, - // Strings are not truncated if level is 10 or higher - { - body: buildString(20000), - level: "10", - want: buildString(20000), - }, - // Strings are not truncated if level is 10 or higher - { - body: buildString(20000), - level: "11", - want: buildString(20000), - }, - } - - l := flag.Lookup("v").Value.(flag.Getter).Get().(glog.Level) - for _, test := range tests { - flag.Set("v", test.level) - got := truncateBody(test.body) - if got != test.want { - t.Errorf("truncateBody(%v) = %v, want %v", test.body, got, test.want) - } - } - flag.Set("v", l.String()) -} - -func defaultResourcePathWithPrefix(prefix, resource, namespace, name string) string { - var path string - path = "/api/" + v1.SchemeGroupVersion.Version - - if prefix != "" { - path = path + "/" + prefix - } - if namespace != "" { - path = path + "/namespaces/" + namespace - } - // Resource names are lower case. - resource = strings.ToLower(resource) - if resource != "" { - path = path + "/" + resource - } - if name != "" { - path = path + "/" + name - } - return path -} diff --git a/vendor/k8s.io/client-go/rest/url_utils_test.go b/vendor/k8s.io/client-go/rest/url_utils_test.go deleted file mode 100644 index 6321678a40..0000000000 --- a/vendor/k8s.io/client-go/rest/url_utils_test.go +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright 2016 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package rest - -import ( - "path" - "testing" - - "k8s.io/api/core/v1" -) - -func TestValidatesHostParameter(t *testing.T) { - testCases := []struct { - Host string - APIPath string - - URL string - Err bool - }{ - {"127.0.0.1", "", "http://127.0.0.1/" + v1.SchemeGroupVersion.Version, false}, - {"127.0.0.1:8080", "", "http://127.0.0.1:8080/" + v1.SchemeGroupVersion.Version, false}, - {"foo.bar.com", "", "http://foo.bar.com/" + v1.SchemeGroupVersion.Version, false}, - {"http://host/prefix", "", "http://host/prefix/" + v1.SchemeGroupVersion.Version, false}, - {"http://host", "", "http://host/" + v1.SchemeGroupVersion.Version, false}, - {"http://host", "/", "http://host/" + v1.SchemeGroupVersion.Version, false}, - {"http://host", "/other", "http://host/other/" + v1.SchemeGroupVersion.Version, false}, - {"host/server", "", "", true}, - } - for i, testCase := range testCases { - u, versionedAPIPath, err := DefaultServerURL(testCase.Host, testCase.APIPath, v1.SchemeGroupVersion, false) - switch { - case err == nil && testCase.Err: - t.Errorf("expected error but was nil") - continue - case err != nil && !testCase.Err: - t.Errorf("unexpected error %v", err) - continue - case err != nil: - continue - } - u.Path = path.Join(u.Path, versionedAPIPath) - if e, a := testCase.URL, u.String(); e != a { - t.Errorf("%d: expected host %s, got %s", i, e, a) - continue - } - } -} diff --git a/vendor/k8s.io/client-go/rest/urlbackoff_test.go b/vendor/k8s.io/client-go/rest/urlbackoff_test.go deleted file mode 100644 index c5f439238d..0000000000 --- a/vendor/k8s.io/client-go/rest/urlbackoff_test.go +++ /dev/null @@ -1,79 +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 rest - -import ( - "net/url" - "testing" - "time" - - "k8s.io/client-go/util/flowcontrol" -) - -func parse(raw string) *url.URL { - theUrl, _ := url.Parse(raw) - return theUrl -} - -func TestURLBackoffFunctionalityCollisions(t *testing.T) { - myBackoff := &URLBackoff{ - Backoff: flowcontrol.NewBackOff(1*time.Second, 60*time.Second), - } - - // Add some noise and make sure backoff for a clean URL is zero. - myBackoff.UpdateBackoff(parse("http://100.200.300.400:8080"), nil, 500) - - myBackoff.UpdateBackoff(parse("http://1.2.3.4:8080"), nil, 500) - - if myBackoff.CalculateBackoff(parse("http://1.2.3.4:100")) > 0 { - t.Errorf("URLs are colliding in the backoff map!") - } -} - -// TestURLBackoffFunctionality generally tests the URLBackoff wrapper. We avoid duplicating tests from backoff and request. -func TestURLBackoffFunctionality(t *testing.T) { - myBackoff := &URLBackoff{ - Backoff: flowcontrol.NewBackOff(1*time.Second, 60*time.Second), - } - - // Now test that backoff increases, then recovers. - // 200 and 300 should both result in clearing the backoff. - // all others like 429 should result in increased backoff. - seconds := []int{0, - 1, 2, 4, 8, 0, - 1, 2} - returnCodes := []int{ - 429, 500, 501, 502, 300, - 500, 501, 502, - } - - if len(seconds) != len(returnCodes) { - t.Fatalf("responseCode to backoff arrays should be the same length... sanity check failed.") - } - - for i, sec := range seconds { - backoffSec := myBackoff.CalculateBackoff(parse("http://1.2.3.4:100")) - if backoffSec < time.Duration(sec)*time.Second || backoffSec > time.Duration(sec+5)*time.Second { - t.Errorf("Backoff out of range %v: %v %v", i, sec, backoffSec) - } - myBackoff.UpdateBackoff(parse("http://1.2.3.4:100/responseCodeForFuncTest"), nil, returnCodes[i]) - } - - if myBackoff.CalculateBackoff(parse("http://1.2.3.4:100")) == 0 { - t.Errorf("The final return code %v should have resulted in a backoff ! ", returnCodes[7]) - } -} diff --git a/vendor/k8s.io/client-go/rest/watch/decoder_test.go b/vendor/k8s.io/client-go/rest/watch/decoder_test.go deleted file mode 100644 index 2d29d437d5..0000000000 --- a/vendor/k8s.io/client-go/rest/watch/decoder_test.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 versioned_test - -import ( - "encoding/json" - "io" - "testing" - "time" - - "k8s.io/api/core/v1" - apiequality "k8s.io/apimachinery/pkg/api/equality" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/serializer" - runtimejson "k8s.io/apimachinery/pkg/runtime/serializer/json" - "k8s.io/apimachinery/pkg/runtime/serializer/streaming" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/kubernetes/scheme" - restclientwatch "k8s.io/client-go/rest/watch" -) - -// getDecoder mimics how k8s.io/client-go/rest.createSerializers creates a decoder -func getDecoder() runtime.Decoder { - jsonSerializer := runtimejson.NewSerializer(runtimejson.DefaultMetaFactory, scheme.Scheme, scheme.Scheme, false) - directCodecFactory := serializer.DirectCodecFactory{CodecFactory: scheme.Codecs} - return directCodecFactory.DecoderToVersion(jsonSerializer, v1.SchemeGroupVersion) -} - -func TestDecoder(t *testing.T) { - table := []watch.EventType{watch.Added, watch.Deleted, watch.Modified, watch.Error} - - for _, eventType := range table { - out, in := io.Pipe() - - decoder := restclientwatch.NewDecoder(streaming.NewDecoder(out, getDecoder()), getDecoder()) - - expect := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} - encoder := json.NewEncoder(in) - go func() { - data, err := runtime.Encode(scheme.Codecs.LegacyCodec(v1.SchemeGroupVersion), expect) - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - event := metav1.WatchEvent{ - Type: string(eventType), - Object: runtime.RawExtension{Raw: json.RawMessage(data)}, - } - if err := encoder.Encode(&event); err != nil { - t.Errorf("Unexpected error %v", err) - } - in.Close() - }() - - done := make(chan struct{}) - go func() { - action, got, err := decoder.Decode() - if err != nil { - t.Fatalf("Unexpected error %v", err) - } - if e, a := eventType, action; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - if e, a := expect, got; !apiequality.Semantic.DeepDerivative(e, a) { - t.Errorf("Expected %v, got %v", e, a) - } - t.Logf("Exited read") - close(done) - }() - <-done - - done = make(chan struct{}) - go func() { - _, _, err := decoder.Decode() - if err == nil { - t.Errorf("Unexpected nil error") - } - close(done) - }() - <-done - - decoder.Close() - } -} - -func TestDecoder_SourceClose(t *testing.T) { - out, in := io.Pipe() - decoder := restclientwatch.NewDecoder(streaming.NewDecoder(out, getDecoder()), getDecoder()) - - done := make(chan struct{}) - - go func() { - _, _, err := decoder.Decode() - if err == nil { - t.Errorf("Unexpected nil error") - } - close(done) - }() - - in.Close() - - select { - case <-done: - break - case <-time.After(wait.ForeverTestTimeout): - t.Error("Timeout") - } -} diff --git a/vendor/k8s.io/client-go/rest/watch/encoder_test.go b/vendor/k8s.io/client-go/rest/watch/encoder_test.go deleted file mode 100644 index 1388d1cc6d..0000000000 --- a/vendor/k8s.io/client-go/rest/watch/encoder_test.go +++ /dev/null @@ -1,84 +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 versioned_test - -import ( - "bytes" - "io/ioutil" - "testing" - - "k8s.io/api/core/v1" - apiequality "k8s.io/apimachinery/pkg/api/equality" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/serializer" - runtimejson "k8s.io/apimachinery/pkg/runtime/serializer/json" - "k8s.io/apimachinery/pkg/runtime/serializer/streaming" - "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/kubernetes/scheme" - restclientwatch "k8s.io/client-go/rest/watch" -) - -// getEncoder mimics how k8s.io/client-go/rest.createSerializers creates a encoder -func getEncoder() runtime.Encoder { - jsonSerializer := runtimejson.NewSerializer(runtimejson.DefaultMetaFactory, scheme.Scheme, scheme.Scheme, false) - directCodecFactory := serializer.DirectCodecFactory{CodecFactory: scheme.Codecs} - return directCodecFactory.EncoderForVersion(jsonSerializer, v1.SchemeGroupVersion) -} - -func TestEncodeDecodeRoundTrip(t *testing.T) { - testCases := []struct { - Type watch.EventType - Object runtime.Object - }{ - { - watch.Added, - &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}, - }, - { - watch.Modified, - &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}, - }, - { - watch.Deleted, - &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}, - }, - } - for i, testCase := range testCases { - buf := &bytes.Buffer{} - - encoder := restclientwatch.NewEncoder(streaming.NewEncoder(buf, getEncoder()), getEncoder()) - if err := encoder.Encode(&watch.Event{Type: testCase.Type, Object: testCase.Object}); err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - continue - } - - rc := ioutil.NopCloser(buf) - decoder := restclientwatch.NewDecoder(streaming.NewDecoder(rc, getDecoder()), getDecoder()) - event, obj, err := decoder.Decode() - if err != nil { - t.Errorf("%d: unexpected error: %v", i, err) - continue - } - if !apiequality.Semantic.DeepDerivative(testCase.Object, obj) { - t.Errorf("%d: expected %#v, got %#v", i, testCase.Object, obj) - } - if event != testCase.Type { - t.Errorf("%d: unexpected type: %#v", i, event) - } - } -} diff --git a/vendor/k8s.io/client-go/testing/fixture_test.go b/vendor/k8s.io/client-go/testing/fixture_test.go deleted file mode 100644 index 967e0aefa9..0000000000 --- a/vendor/k8s.io/client-go/testing/fixture_test.go +++ /dev/null @@ -1,192 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package testing - -import ( - "fmt" - "math/rand" - "strconv" - "sync" - "testing" - - "github.com/stretchr/testify/assert" - - "k8s.io/apimachinery/pkg/api/meta" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - runtime "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - serializer "k8s.io/apimachinery/pkg/runtime/serializer" - "k8s.io/apimachinery/pkg/watch" -) - -func getArbitraryResource(s schema.GroupVersionResource, name, namespace string) *unstructured.Unstructured { - return &unstructured.Unstructured{ - Object: map[string]interface{}{ - "kind": s.Resource, - "apiVersion": s.Version, - "metadata": map[string]interface{}{ - "name": name, - "namespace": namespace, - "generateName": "test_generateName", - "uid": "test_uid", - "resourceVersion": "test_resourceVersion", - "selfLink": "test_selfLink", - }, - "data": strconv.Itoa(rand.Int()), - }, - } -} - -func TestWatchCallNonNamespace(t *testing.T) { - testResource := schema.GroupVersionResource{Group: "", Version: "test_version", Resource: "test_kind"} - testObj := getArbitraryResource(testResource, "test_name", "test_namespace") - accessor, err := meta.Accessor(testObj) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - ns := accessor.GetNamespace() - scheme := runtime.NewScheme() - codecs := serializer.NewCodecFactory(scheme) - o := NewObjectTracker(scheme, codecs.UniversalDecoder()) - watch, err := o.Watch(testResource, ns) - go func() { - err := o.Create(testResource, testObj, ns) - if err != nil { - t.Errorf("test resource creation failed: %v", err) - } - }() - out := <-watch.ResultChan() - assert.Equal(t, testObj, out.Object, "watched object mismatch") -} - -func TestWatchCallAllNamespace(t *testing.T) { - testResource := schema.GroupVersionResource{Group: "", Version: "test_version", Resource: "test_kind"} - testObj := getArbitraryResource(testResource, "test_name", "test_namespace") - accessor, err := meta.Accessor(testObj) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - ns := accessor.GetNamespace() - scheme := runtime.NewScheme() - codecs := serializer.NewCodecFactory(scheme) - o := NewObjectTracker(scheme, codecs.UniversalDecoder()) - w, err := o.Watch(testResource, "test_namespace") - wAll, err := o.Watch(testResource, "") - go func() { - err := o.Create(testResource, testObj, ns) - assert.NoError(t, err, "test resource creation failed") - }() - out := <-w.ResultChan() - outAll := <-wAll.ResultChan() - assert.Equal(t, watch.Added, out.Type, "watch event mismatch") - assert.Equal(t, watch.Added, outAll.Type, "watch event mismatch") - assert.Equal(t, testObj, out.Object, "watched created object mismatch") - assert.Equal(t, testObj, outAll.Object, "watched created object mismatch") - go func() { - err := o.Update(testResource, testObj, ns) - assert.NoError(t, err, "test resource updating failed") - }() - out = <-w.ResultChan() - outAll = <-wAll.ResultChan() - assert.Equal(t, watch.Modified, out.Type, "watch event mismatch") - assert.Equal(t, watch.Modified, outAll.Type, "watch event mismatch") - assert.Equal(t, testObj, out.Object, "watched updated object mismatch") - assert.Equal(t, testObj, outAll.Object, "watched updated object mismatch") - go func() { - err := o.Delete(testResource, "test_namespace", "test_name") - assert.NoError(t, err, "test resource deletion failed") - }() - out = <-w.ResultChan() - outAll = <-wAll.ResultChan() - assert.Equal(t, watch.Deleted, out.Type, "watch event mismatch") - assert.Equal(t, watch.Deleted, outAll.Type, "watch event mismatch") - assert.Equal(t, testObj, out.Object, "watched deleted object mismatch") - assert.Equal(t, testObj, outAll.Object, "watched deleted object mismatch") -} - -func TestWatchCallMultipleInvocation(t *testing.T) { - cases := []struct { - name string - op watch.EventType - }{ - { - "foo", - watch.Added, - }, - { - "bar", - watch.Added, - }, - { - "bar", - watch.Modified, - }, - { - "foo", - watch.Deleted, - }, - { - "bar", - watch.Deleted, - }, - } - - scheme := runtime.NewScheme() - codecs := serializer.NewCodecFactory(scheme) - testResource := schema.GroupVersionResource{Group: "", Version: "test_version", Resource: "test_kind"} - - o := NewObjectTracker(scheme, codecs.UniversalDecoder()) - watchNamespaces := []string{ - "", - "", - "test_namespace", - "test_namespace", - } - var wg sync.WaitGroup - wg.Add(len(watchNamespaces)) - for idx, watchNamespace := range watchNamespaces { - i := idx - w, err := o.Watch(testResource, watchNamespace) - go func() { - assert.NoError(t, err, "watch invocation failed") - for _, c := range cases { - fmt.Printf("%#v %#v\n", c, i) - event := <-w.ResultChan() - accessor, err := meta.Accessor(event.Object) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - assert.Equal(t, c.op, event.Type, "watch event mismatched") - assert.Equal(t, c.name, accessor.GetName(), "watched object mismatch") - } - wg.Done() - }() - } - for _, c := range cases { - switch c.op { - case watch.Added: - obj := getArbitraryResource(testResource, c.name, "test_namespace") - o.Create(testResource, obj, "test_namespace") - case watch.Modified: - obj := getArbitraryResource(testResource, c.name, "test_namespace") - o.Update(testResource, obj, "test_namespace") - case watch.Deleted: - o.Delete(testResource, "test_namespace", c.name) - } - } - wg.Wait() -} diff --git a/vendor/k8s.io/client-go/tools/auth/clientauth_test.go b/vendor/k8s.io/client-go/tools/auth/clientauth_test.go deleted file mode 100644 index 11f7369de9..0000000000 --- a/vendor/k8s.io/client-go/tools/auth/clientauth_test.go +++ /dev/null @@ -1,69 +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 auth_test - -import ( - "io/ioutil" - "os" - "reflect" - "testing" - - clientauth "k8s.io/client-go/tools/auth" -) - -func TestLoadFromFile(t *testing.T) { - loadAuthInfoTests := []struct { - authData string - authInfo *clientauth.Info - expectErr bool - }{ - { - `{"user": "user", "password": "pass"}`, - &clientauth.Info{User: "user", Password: "pass"}, - false, - }, - { - "", nil, true, - }, - } - for _, loadAuthInfoTest := range loadAuthInfoTests { - tt := loadAuthInfoTest - aifile, err := ioutil.TempFile("", "testAuthInfo") - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if tt.authData != "missing" { - defer os.Remove(aifile.Name()) - defer aifile.Close() - _, err = aifile.WriteString(tt.authData) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - } else { - aifile.Close() - os.Remove(aifile.Name()) - } - authInfo, err := clientauth.LoadFromFile(aifile.Name()) - gotErr := err != nil - if gotErr != tt.expectErr { - t.Errorf("expected errorness: %v, actual errorness: %v", tt.expectErr, gotErr) - } - if !reflect.DeepEqual(authInfo, tt.authInfo) { - t.Errorf("Expected %v, got %v", tt.authInfo, authInfo) - } - } -} diff --git a/vendor/k8s.io/client-go/tools/cache/controller_test.go b/vendor/k8s.io/client-go/tools/cache/controller_test.go deleted file mode 100644 index 64aca8d7d0..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/controller_test.go +++ /dev/null @@ -1,405 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package cache - -import ( - "fmt" - "math/rand" - "sync" - "testing" - "time" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/apimachinery/pkg/watch" - fcache "k8s.io/client-go/tools/cache/testing" - - "github.com/google/gofuzz" -) - -func Example() { - // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() - - // This will hold the downstream state, as we know it. - downstream := NewStore(DeletionHandlingMetaNamespaceKeyFunc) - - // This will hold incoming changes. Note how we pass downstream in as a - // KeyLister, that way resync operations will result in the correct set - // of update/delete deltas. - fifo := NewDeltaFIFO(MetaNamespaceKeyFunc, downstream) - - // Let's do threadsafe output to get predictable test results. - deletionCounter := make(chan string, 1000) - - cfg := &Config{ - Queue: fifo, - ListerWatcher: source, - ObjectType: &v1.Pod{}, - FullResyncPeriod: time.Millisecond * 100, - RetryOnError: false, - - // Let's implement a simple controller that just deletes - // everything that comes in. - Process: func(obj interface{}) error { - // Obj is from the Pop method of the Queue we make above. - newest := obj.(Deltas).Newest() - - if newest.Type != Deleted { - // Update our downstream store. - err := downstream.Add(newest.Object) - if err != nil { - return err - } - - // Delete this object. - source.Delete(newest.Object.(runtime.Object)) - } else { - // Update our downstream store. - err := downstream.Delete(newest.Object) - if err != nil { - return err - } - - // fifo's KeyOf is easiest, because it handles - // DeletedFinalStateUnknown markers. - key, err := fifo.KeyOf(newest.Object) - if err != nil { - return err - } - - // Report this deletion. - deletionCounter <- key - } - return nil - }, - } - - // Create the controller and run it until we close stop. - stop := make(chan struct{}) - defer close(stop) - go New(cfg).Run(stop) - - // Let's add a few objects to the source. - testIDs := []string{"a-hello", "b-controller", "c-framework"} - for _, name := range testIDs { - // Note that these pods are not valid-- the fake source doesn't - // call validation or anything. - source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: name}}) - } - - // Let's wait for the controller to process the things we just added. - outputSet := sets.String{} - for i := 0; i < len(testIDs); i++ { - outputSet.Insert(<-deletionCounter) - } - - for _, key := range outputSet.List() { - fmt.Println(key) - } - // Output: - // a-hello - // b-controller - // c-framework -} - -func ExampleNewInformer() { - // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() - - // Let's do threadsafe output to get predictable test results. - deletionCounter := make(chan string, 1000) - - // Make a controller that immediately deletes anything added to it, and - // logs anything deleted. - _, controller := NewInformer( - source, - &v1.Pod{}, - time.Millisecond*100, - ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - source.Delete(obj.(runtime.Object)) - }, - DeleteFunc: func(obj interface{}) { - key, err := DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - key = "oops something went wrong with the key" - } - - // Report this deletion. - deletionCounter <- key - }, - }, - ) - - // Run the controller and run it until we close stop. - stop := make(chan struct{}) - defer close(stop) - go controller.Run(stop) - - // Let's add a few objects to the source. - testIDs := []string{"a-hello", "b-controller", "c-framework"} - for _, name := range testIDs { - // Note that these pods are not valid-- the fake source doesn't - // call validation or anything. - source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: name}}) - } - - // Let's wait for the controller to process the things we just added. - outputSet := sets.String{} - for i := 0; i < len(testIDs); i++ { - outputSet.Insert(<-deletionCounter) - } - - for _, key := range outputSet.List() { - fmt.Println(key) - } - // Output: - // a-hello - // b-controller - // c-framework -} - -func TestHammerController(t *testing.T) { - // This test executes a bunch of requests through the fake source and - // controller framework to make sure there's no locking/threading - // errors. If an error happens, it should hang forever or trigger the - // race detector. - - // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() - - // Let's do threadsafe output to get predictable test results. - outputSetLock := sync.Mutex{} - // map of key to operations done on the key - outputSet := map[string][]string{} - - recordFunc := func(eventType string, obj interface{}) { - key, err := DeletionHandlingMetaNamespaceKeyFunc(obj) - if err != nil { - t.Errorf("something wrong with key: %v", err) - key = "oops something went wrong with the key" - } - - // Record some output when items are deleted. - outputSetLock.Lock() - defer outputSetLock.Unlock() - outputSet[key] = append(outputSet[key], eventType) - } - - // Make a controller which just logs all the changes it gets. - _, controller := NewInformer( - source, - &v1.Pod{}, - time.Millisecond*100, - ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { recordFunc("add", obj) }, - UpdateFunc: func(oldObj, newObj interface{}) { recordFunc("update", newObj) }, - DeleteFunc: func(obj interface{}) { recordFunc("delete", obj) }, - }, - ) - - if controller.HasSynced() { - t.Errorf("Expected HasSynced() to return false before we started the controller") - } - - // Run the controller and run it until we close stop. - stop := make(chan struct{}) - go controller.Run(stop) - - // Let's wait for the controller to do its initial sync - wait.Poll(100*time.Millisecond, wait.ForeverTestTimeout, func() (bool, error) { - return controller.HasSynced(), nil - }) - if !controller.HasSynced() { - t.Errorf("Expected HasSynced() to return true after the initial sync") - } - - wg := sync.WaitGroup{} - const threads = 3 - wg.Add(threads) - for i := 0; i < threads; i++ { - go func() { - defer wg.Done() - // Let's add a few objects to the source. - currentNames := sets.String{} - rs := rand.NewSource(rand.Int63()) - f := fuzz.New().NilChance(.5).NumElements(0, 2).RandSource(rs) - r := rand.New(rs) // Mustn't use r and f concurrently! - for i := 0; i < 100; i++ { - var name string - var isNew bool - if currentNames.Len() == 0 || r.Intn(3) == 1 { - f.Fuzz(&name) - isNew = true - } else { - l := currentNames.List() - name = l[r.Intn(len(l))] - } - - pod := &v1.Pod{} - f.Fuzz(pod) - pod.ObjectMeta.Name = name - pod.ObjectMeta.Namespace = "default" - // Add, update, or delete randomly. - // Note that these pods are not valid-- the fake source doesn't - // call validation or perform any other checking. - if isNew { - currentNames.Insert(name) - source.Add(pod) - continue - } - switch r.Intn(2) { - case 0: - currentNames.Insert(name) - source.Modify(pod) - case 1: - currentNames.Delete(name) - source.Delete(pod) - } - } - }() - } - wg.Wait() - - // Let's wait for the controller to finish processing the things we just added. - // TODO: look in the queue to see how many items need to be processed. - time.Sleep(100 * time.Millisecond) - close(stop) - - // TODO: Verify that no goroutines were leaked here and that everything shut - // down cleanly. - - outputSetLock.Lock() - t.Logf("got: %#v", outputSet) -} - -func TestUpdate(t *testing.T) { - // This test is going to exercise the various paths that result in a - // call to update. - - // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() - - const ( - FROM = "from" - TO = "to" - ) - - // These are the transitions we expect to see; because this is - // asynchronous, there are a lot of valid possibilities. - type pair struct{ from, to string } - allowedTransitions := map[pair]bool{ - {FROM, TO}: true, - - // Because a resync can happen when we've already observed one - // of the above but before the item is deleted. - {TO, TO}: true, - // Because a resync could happen before we observe an update. - {FROM, FROM}: true, - } - - pod := func(name, check string, final bool) *v1.Pod { - p := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Labels: map[string]string{"check": check}, - }, - } - if final { - p.Labels["final"] = "true" - } - return p - } - deletePod := func(p *v1.Pod) bool { - return p.Labels["final"] == "true" - } - - tests := []func(string){ - func(name string) { - name = "a-" + name - source.Add(pod(name, FROM, false)) - source.Modify(pod(name, TO, true)) - }, - } - - const threads = 3 - - var testDoneWG sync.WaitGroup - testDoneWG.Add(threads * len(tests)) - - // Make a controller that deletes things once it observes an update. - // It calls Done() on the wait group on deletions so we can tell when - // everything we've added has been deleted. - watchCh := make(chan struct{}) - _, controller := NewInformer( - &testLW{ - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - watch, err := source.Watch(options) - close(watchCh) - return watch, err - }, - ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - return source.List(options) - }, - }, - &v1.Pod{}, - 0, - ResourceEventHandlerFuncs{ - UpdateFunc: func(oldObj, newObj interface{}) { - o, n := oldObj.(*v1.Pod), newObj.(*v1.Pod) - from, to := o.Labels["check"], n.Labels["check"] - if !allowedTransitions[pair{from, to}] { - t.Errorf("observed transition %q -> %q for %v", from, to, n.Name) - } - if deletePod(n) { - source.Delete(n) - } - }, - DeleteFunc: func(obj interface{}) { - testDoneWG.Done() - }, - }, - ) - - // Run the controller and run it until we close stop. - // Once Run() is called, calls to testDoneWG.Done() might start, so - // all testDoneWG.Add() calls must happen before this point - stop := make(chan struct{}) - go controller.Run(stop) - <-watchCh - - // run every test a few times, in parallel - var wg sync.WaitGroup - wg.Add(threads * len(tests)) - for i := 0; i < threads; i++ { - for j, f := range tests { - go func(name string, f func(string)) { - defer wg.Done() - f(name) - }(fmt.Sprintf("%v-%v", i, j), f) - } - } - wg.Wait() - - // Let's wait for the controller to process the things we just added. - testDoneWG.Wait() - close(stop) -} diff --git a/vendor/k8s.io/client-go/tools/cache/delta_fifo_test.go b/vendor/k8s.io/client-go/tools/cache/delta_fifo_test.go deleted file mode 100644 index 9f8e575804..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/delta_fifo_test.go +++ /dev/null @@ -1,492 +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 cache - -import ( - "fmt" - "reflect" - "testing" - "time" -) - -// helper function to reduce stuttering -func testPop(f *DeltaFIFO) testFifoObject { - return Pop(f).(Deltas).Newest().Object.(testFifoObject) -} - -// keyLookupFunc adapts a raw function to be a KeyLookup. -type keyLookupFunc func() []testFifoObject - -// ListKeys just calls kl. -func (kl keyLookupFunc) ListKeys() []string { - result := []string{} - for _, fifoObj := range kl() { - result = append(result, fifoObj.name) - } - return result -} - -// GetByKey returns the key if it exists in the list returned by kl. -func (kl keyLookupFunc) GetByKey(key string) (interface{}, bool, error) { - for _, v := range kl() { - if v.name == key { - return v, true, nil - } - } - return nil, false, nil -} - -func TestDeltaFIFO_basic(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil) - const amount = 500 - go func() { - for i := 0; i < amount; i++ { - f.Add(mkFifoObj(string([]rune{'a', rune(i)}), i+1)) - } - }() - go func() { - for u := uint64(0); u < amount; u++ { - f.Add(mkFifoObj(string([]rune{'b', rune(u)}), u+1)) - } - }() - - lastInt := int(0) - lastUint := uint64(0) - for i := 0; i < amount*2; i++ { - switch obj := testPop(f).val.(type) { - case int: - if obj <= lastInt { - t.Errorf("got %v (int) out of order, last was %v", obj, lastInt) - } - lastInt = obj - case uint64: - if obj <= lastUint { - t.Errorf("got %v (uint) out of order, last was %v", obj, lastUint) - } else { - lastUint = obj - } - default: - t.Fatalf("unexpected type %#v", obj) - } - } -} - -func TestDeltaFIFO_requeueOnPop(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil) - - f.Add(mkFifoObj("foo", 10)) - _, err := f.Pop(func(obj interface{}) error { - if obj.(Deltas)[0].Object.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return ErrRequeue{Err: nil} - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); !ok || err != nil { - t.Fatalf("object should have been requeued: %t %v", ok, err) - } - - _, err = f.Pop(func(obj interface{}) error { - if obj.(Deltas)[0].Object.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return ErrRequeue{Err: fmt.Errorf("test error")} - }) - if err == nil || err.Error() != "test error" { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); !ok || err != nil { - t.Fatalf("object should have been requeued: %t %v", ok, err) - } - - _, err = f.Pop(func(obj interface{}) error { - if obj.(Deltas)[0].Object.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return nil - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); ok || err != nil { - t.Fatalf("object should have been removed: %t %v", ok, err) - } -} - -func TestDeltaFIFO_addUpdate(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil) - f.Add(mkFifoObj("foo", 10)) - f.Update(mkFifoObj("foo", 12)) - f.Delete(mkFifoObj("foo", 15)) - - if e, a := []interface{}{mkFifoObj("foo", 15)}, f.List(); !reflect.DeepEqual(e, a) { - t.Errorf("Expected %+v, got %+v", e, a) - } - if e, a := []string{"foo"}, f.ListKeys(); !reflect.DeepEqual(e, a) { - t.Errorf("Expected %+v, got %+v", e, a) - } - - got := make(chan testFifoObject, 2) - go func() { - for { - obj := testPop(f) - t.Logf("got a thing %#v", obj) - t.Logf("D len: %v", len(f.queue)) - got <- obj - } - }() - - first := <-got - if e, a := 15, first.val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - select { - case unexpected := <-got: - t.Errorf("Got second value %v", unexpected.val) - case <-time.After(50 * time.Millisecond): - } - _, exists, _ := f.Get(mkFifoObj("foo", "")) - if exists { - t.Errorf("item did not get removed") - } -} - -func TestDeltaFIFO_enqueueingNoLister(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil) - f.Add(mkFifoObj("foo", 10)) - f.Update(mkFifoObj("bar", 15)) - f.Add(mkFifoObj("qux", 17)) - f.Delete(mkFifoObj("qux", 18)) - - // This delete does not enqueue anything because baz doesn't exist. - f.Delete(mkFifoObj("baz", 20)) - - expectList := []int{10, 15, 18} - for _, expect := range expectList { - if e, a := expect, testPop(f).val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - } - if e, a := 0, len(f.items); e != a { - t.Errorf("queue unexpectedly not empty: %v != %v\n%#v", e, a, f.items) - } -} - -func TestDeltaFIFO_enqueueingWithLister(t *testing.T) { - f := NewDeltaFIFO( - testFifoObjectKeyFunc, - keyLookupFunc(func() []testFifoObject { - return []testFifoObject{mkFifoObj("foo", 5), mkFifoObj("bar", 6), mkFifoObj("baz", 7)} - }), - ) - f.Add(mkFifoObj("foo", 10)) - f.Update(mkFifoObj("bar", 15)) - - // This delete does enqueue the deletion, because "baz" is in the key lister. - f.Delete(mkFifoObj("baz", 20)) - - expectList := []int{10, 15, 20} - for _, expect := range expectList { - if e, a := expect, testPop(f).val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - } - if e, a := 0, len(f.items); e != a { - t.Errorf("queue unexpectedly not empty: %v != %v", e, a) - } -} - -func TestDeltaFIFO_addReplace(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil) - f.Add(mkFifoObj("foo", 10)) - f.Replace([]interface{}{mkFifoObj("foo", 15)}, "0") - got := make(chan testFifoObject, 2) - go func() { - for { - got <- testPop(f) - } - }() - - first := <-got - if e, a := 15, first.val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - select { - case unexpected := <-got: - t.Errorf("Got second value %v", unexpected.val) - case <-time.After(50 * time.Millisecond): - } - _, exists, _ := f.Get(mkFifoObj("foo", "")) - if exists { - t.Errorf("item did not get removed") - } -} - -func TestDeltaFIFO_ResyncNonExisting(t *testing.T) { - f := NewDeltaFIFO( - testFifoObjectKeyFunc, - keyLookupFunc(func() []testFifoObject { - return []testFifoObject{mkFifoObj("foo", 5)} - }), - ) - f.Delete(mkFifoObj("foo", 10)) - f.Resync() - - deltas := f.items["foo"] - if len(deltas) != 1 { - t.Fatalf("unexpected deltas length: %v", deltas) - } - if deltas[0].Type != Deleted { - t.Errorf("unexpected delta: %v", deltas[0]) - } -} - -func TestDeltaFIFO_DeleteExistingNonPropagated(t *testing.T) { - f := NewDeltaFIFO( - testFifoObjectKeyFunc, - keyLookupFunc(func() []testFifoObject { - return []testFifoObject{} - }), - ) - f.Add(mkFifoObj("foo", 5)) - f.Delete(mkFifoObj("foo", 6)) - - deltas := f.items["foo"] - if len(deltas) != 2 { - t.Fatalf("unexpected deltas length: %v", deltas) - } - if deltas[len(deltas)-1].Type != Deleted { - t.Errorf("unexpected delta: %v", deltas[len(deltas)-1]) - } -} - -func TestDeltaFIFO_ReplaceMakesDeletions(t *testing.T) { - f := NewDeltaFIFO( - testFifoObjectKeyFunc, - keyLookupFunc(func() []testFifoObject { - return []testFifoObject{mkFifoObj("foo", 5), mkFifoObj("bar", 6), mkFifoObj("baz", 7)} - }), - ) - f.Delete(mkFifoObj("baz", 10)) - f.Replace([]interface{}{mkFifoObj("foo", 5)}, "0") - - expectedList := []Deltas{ - {{Deleted, mkFifoObj("baz", 10)}}, - {{Sync, mkFifoObj("foo", 5)}}, - // Since "bar" didn't have a delete event and wasn't in the Replace list - // it should get a tombstone key with the right Obj. - {{Deleted, DeletedFinalStateUnknown{Key: "bar", Obj: mkFifoObj("bar", 6)}}}, - } - - for _, expected := range expectedList { - cur := Pop(f).(Deltas) - if e, a := expected, cur; !reflect.DeepEqual(e, a) { - t.Errorf("Expected %#v, got %#v", e, a) - } - } -} - -func TestDeltaFIFO_UpdateResyncRace(t *testing.T) { - f := NewDeltaFIFO( - testFifoObjectKeyFunc, - keyLookupFunc(func() []testFifoObject { - return []testFifoObject{mkFifoObj("foo", 5)} - }), - ) - f.Update(mkFifoObj("foo", 6)) - f.Resync() - - expectedList := []Deltas{ - {{Updated, mkFifoObj("foo", 6)}}, - } - - for _, expected := range expectedList { - cur := Pop(f).(Deltas) - if e, a := expected, cur; !reflect.DeepEqual(e, a) { - t.Errorf("Expected %#v, got %#v", e, a) - } - } -} - -func TestDeltaFIFO_HasSyncedCorrectOnDeletion(t *testing.T) { - f := NewDeltaFIFO( - testFifoObjectKeyFunc, - keyLookupFunc(func() []testFifoObject { - return []testFifoObject{mkFifoObj("foo", 5), mkFifoObj("bar", 6), mkFifoObj("baz", 7)} - }), - ) - f.Replace([]interface{}{mkFifoObj("foo", 5)}, "0") - - expectedList := []Deltas{ - {{Sync, mkFifoObj("foo", 5)}}, - // Since "bar" didn't have a delete event and wasn't in the Replace list - // it should get a tombstone key with the right Obj. - {{Deleted, DeletedFinalStateUnknown{Key: "bar", Obj: mkFifoObj("bar", 6)}}}, - } - - for _, expected := range expectedList { - if f.HasSynced() { - t.Errorf("Expected HasSynced to be false") - } - cur := Pop(f).(Deltas) - if e, a := expected, cur; !reflect.DeepEqual(e, a) { - t.Errorf("Expected %#v, got %#v", e, a) - } - } - if f.HasSynced() { - t.Errorf("Expected HasSynced to be true") - } -} - -func TestDeltaFIFO_detectLineJumpers(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil) - - f.Add(mkFifoObj("foo", 10)) - f.Add(mkFifoObj("bar", 1)) - f.Add(mkFifoObj("foo", 11)) - f.Add(mkFifoObj("foo", 13)) - f.Add(mkFifoObj("zab", 30)) - - if e, a := 13, testPop(f).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - f.Add(mkFifoObj("foo", 14)) // ensure foo doesn't jump back in line - - if e, a := 1, testPop(f).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - if e, a := 30, testPop(f).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - if e, a := 14, testPop(f).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } -} - -func TestDeltaFIFO_addIfNotPresent(t *testing.T) { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil) - - f.Add(mkFifoObj("b", 3)) - b3 := Pop(f) - f.Add(mkFifoObj("c", 4)) - c4 := Pop(f) - if e, a := 0, len(f.items); e != a { - t.Fatalf("Expected %v, got %v items in queue", e, a) - } - - f.Add(mkFifoObj("a", 1)) - f.Add(mkFifoObj("b", 2)) - f.AddIfNotPresent(b3) - f.AddIfNotPresent(c4) - - if e, a := 3, len(f.items); a != e { - t.Fatalf("expected queue length %d, got %d", e, a) - } - - expectedValues := []int{1, 2, 4} - for _, expected := range expectedValues { - if actual := testPop(f).val; actual != expected { - t.Fatalf("expected value %d, got %d", expected, actual) - } - } -} - -func TestDeltaFIFO_KeyOf(t *testing.T) { - f := DeltaFIFO{keyFunc: testFifoObjectKeyFunc} - - table := []struct { - obj interface{} - key string - }{ - {obj: testFifoObject{name: "A"}, key: "A"}, - {obj: DeletedFinalStateUnknown{Key: "B", Obj: nil}, key: "B"}, - {obj: Deltas{{Object: testFifoObject{name: "C"}}}, key: "C"}, - {obj: Deltas{{Object: DeletedFinalStateUnknown{Key: "D", Obj: nil}}}, key: "D"}, - } - - for _, item := range table { - got, err := f.KeyOf(item.obj) - if err != nil { - t.Errorf("Unexpected error for %q: %v", item.obj, err) - continue - } - if e, a := item.key, got; e != a { - t.Errorf("Expected %v, got %v", e, a) - } - } -} - -func TestDeltaFIFO_HasSynced(t *testing.T) { - tests := []struct { - actions []func(f *DeltaFIFO) - expectedSynced bool - }{ - { - actions: []func(f *DeltaFIFO){}, - expectedSynced: false, - }, - { - actions: []func(f *DeltaFIFO){ - func(f *DeltaFIFO) { f.Add(mkFifoObj("a", 1)) }, - }, - expectedSynced: true, - }, - { - actions: []func(f *DeltaFIFO){ - func(f *DeltaFIFO) { f.Replace([]interface{}{}, "0") }, - }, - expectedSynced: true, - }, - { - actions: []func(f *DeltaFIFO){ - func(f *DeltaFIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - }, - expectedSynced: false, - }, - { - actions: []func(f *DeltaFIFO){ - func(f *DeltaFIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - func(f *DeltaFIFO) { Pop(f) }, - }, - expectedSynced: false, - }, - { - actions: []func(f *DeltaFIFO){ - func(f *DeltaFIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - func(f *DeltaFIFO) { Pop(f) }, - func(f *DeltaFIFO) { Pop(f) }, - }, - expectedSynced: true, - }, - } - - for i, test := range tests { - f := NewDeltaFIFO(testFifoObjectKeyFunc, nil) - - for _, action := range test.actions { - action(f) - } - if e, a := test.expectedSynced, f.HasSynced(); a != e { - t.Errorf("test case %v failed, expected: %v , got %v", i, e, a) - } - } -} diff --git a/vendor/k8s.io/client-go/tools/cache/expiration_cache_test.go b/vendor/k8s.io/client-go/tools/cache/expiration_cache_test.go deleted file mode 100644 index fac621cbc8..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/expiration_cache_test.go +++ /dev/null @@ -1,189 +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 cache - -import ( - "reflect" - "testing" - "time" - - "k8s.io/apimachinery/pkg/util/clock" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/wait" -) - -func TestTTLExpirationBasic(t *testing.T) { - testObj := testStoreObject{id: "foo", val: "bar"} - deleteChan := make(chan string, 1) - ttlStore := NewFakeExpirationStore( - testStoreKeyFunc, deleteChan, - &FakeExpirationPolicy{ - NeverExpire: sets.NewString(), - RetrieveKeyFunc: func(obj interface{}) (string, error) { - return obj.(*timestampedEntry).obj.(testStoreObject).id, nil - }, - }, - clock.RealClock{}, - ) - err := ttlStore.Add(testObj) - if err != nil { - t.Errorf("Unable to add obj %#v", testObj) - } - item, exists, err := ttlStore.Get(testObj) - if err != nil { - t.Errorf("Failed to get from store, %v", err) - } - if exists || item != nil { - t.Errorf("Got unexpected item %#v", item) - } - key, _ := testStoreKeyFunc(testObj) - select { - case delKey := <-deleteChan: - if delKey != key { - t.Errorf("Unexpected delete for key %s", key) - } - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("Unexpected timeout waiting on delete") - } - close(deleteChan) -} - -func TestReAddExpiredItem(t *testing.T) { - deleteChan := make(chan string, 1) - exp := &FakeExpirationPolicy{ - NeverExpire: sets.NewString(), - RetrieveKeyFunc: func(obj interface{}) (string, error) { - return obj.(*timestampedEntry).obj.(testStoreObject).id, nil - }, - } - ttlStore := NewFakeExpirationStore( - testStoreKeyFunc, deleteChan, exp, clock.RealClock{}) - testKey := "foo" - testObj := testStoreObject{id: testKey, val: "bar"} - err := ttlStore.Add(testObj) - if err != nil { - t.Errorf("Unable to add obj %#v", testObj) - } - - // This get will expire the item. - item, exists, err := ttlStore.Get(testObj) - if err != nil { - t.Errorf("Failed to get from store, %v", err) - } - if exists || item != nil { - t.Errorf("Got unexpected item %#v", item) - } - - key, _ := testStoreKeyFunc(testObj) - differentValue := "different_bar" - err = ttlStore.Add( - testStoreObject{id: testKey, val: differentValue}) - if err != nil { - t.Errorf("Failed to add second value") - } - - select { - case delKey := <-deleteChan: - if delKey != key { - t.Errorf("Unexpected delete for key %s", key) - } - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("Unexpected timeout waiting on delete") - } - exp.NeverExpire = sets.NewString(testKey) - item, exists, err = ttlStore.GetByKey(testKey) - if err != nil { - t.Errorf("Failed to get from store, %v", err) - } - if !exists || item == nil || item.(testStoreObject).val != differentValue { - t.Errorf("Got unexpected item %#v", item) - } - close(deleteChan) -} - -func TestTTLList(t *testing.T) { - testObjs := []testStoreObject{ - {id: "foo", val: "bar"}, - {id: "foo1", val: "bar1"}, - {id: "foo2", val: "bar2"}, - } - expireKeys := sets.NewString(testObjs[0].id, testObjs[2].id) - deleteChan := make(chan string, len(testObjs)) - defer close(deleteChan) - - ttlStore := NewFakeExpirationStore( - testStoreKeyFunc, deleteChan, - &FakeExpirationPolicy{ - NeverExpire: sets.NewString(testObjs[1].id), - RetrieveKeyFunc: func(obj interface{}) (string, error) { - return obj.(*timestampedEntry).obj.(testStoreObject).id, nil - }, - }, - clock.RealClock{}, - ) - for _, obj := range testObjs { - err := ttlStore.Add(obj) - if err != nil { - t.Errorf("Unable to add obj %#v", obj) - } - } - listObjs := ttlStore.List() - if len(listObjs) != 1 || !reflect.DeepEqual(listObjs[0], testObjs[1]) { - t.Errorf("List returned unexpected results %#v", listObjs) - } - - // Make sure all our deletes come through in an acceptable rate (1/100ms) - for expireKeys.Len() != 0 { - select { - case delKey := <-deleteChan: - if !expireKeys.Has(delKey) { - t.Errorf("Unexpected delete for key %s", delKey) - } - expireKeys.Delete(delKey) - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("Unexpected timeout waiting on delete") - return - } - } -} - -func TestTTLPolicy(t *testing.T) { - fakeTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) - ttl := 30 * time.Second - exactlyOnTTL := fakeTime.Add(-ttl) - expiredTime := fakeTime.Add(-(ttl + 1)) - - policy := TTLPolicy{ttl, clock.NewFakeClock(fakeTime)} - fakeTimestampedEntry := &timestampedEntry{obj: struct{}{}, timestamp: exactlyOnTTL} - if policy.IsExpired(fakeTimestampedEntry) { - t.Errorf("TTL cache should not expire entries exactly on ttl") - } - fakeTimestampedEntry.timestamp = fakeTime - if policy.IsExpired(fakeTimestampedEntry) { - t.Errorf("TTL Cache should not expire entries before ttl") - } - fakeTimestampedEntry.timestamp = expiredTime - if !policy.IsExpired(fakeTimestampedEntry) { - t.Errorf("TTL Cache should expire entries older than ttl") - } - for _, ttl = range []time.Duration{0, -1} { - policy.Ttl = ttl - if policy.IsExpired(fakeTimestampedEntry) { - t.Errorf("TTL policy should only expire entries when initialized with a ttl > 0") - } - } -} diff --git a/vendor/k8s.io/client-go/tools/cache/fifo_test.go b/vendor/k8s.io/client-go/tools/cache/fifo_test.go deleted file mode 100644 index afd311d788..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/fifo_test.go +++ /dev/null @@ -1,280 +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 cache - -import ( - "fmt" - "reflect" - "testing" - "time" -) - -func testFifoObjectKeyFunc(obj interface{}) (string, error) { - return obj.(testFifoObject).name, nil -} - -type testFifoObject struct { - name string - val interface{} -} - -func mkFifoObj(name string, val interface{}) testFifoObject { - return testFifoObject{name: name, val: val} -} - -func TestFIFO_basic(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - const amount = 500 - go func() { - for i := 0; i < amount; i++ { - f.Add(mkFifoObj(string([]rune{'a', rune(i)}), i+1)) - } - }() - go func() { - for u := uint64(0); u < amount; u++ { - f.Add(mkFifoObj(string([]rune{'b', rune(u)}), u+1)) - } - }() - - lastInt := int(0) - lastUint := uint64(0) - for i := 0; i < amount*2; i++ { - switch obj := Pop(f).(testFifoObject).val.(type) { - case int: - if obj <= lastInt { - t.Errorf("got %v (int) out of order, last was %v", obj, lastInt) - } - lastInt = obj - case uint64: - if obj <= lastUint { - t.Errorf("got %v (uint) out of order, last was %v", obj, lastUint) - } else { - lastUint = obj - } - default: - t.Fatalf("unexpected type %#v", obj) - } - } -} - -func TestFIFO_requeueOnPop(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - - f.Add(mkFifoObj("foo", 10)) - _, err := f.Pop(func(obj interface{}) error { - if obj.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return ErrRequeue{Err: nil} - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); !ok || err != nil { - t.Fatalf("object should have been requeued: %t %v", ok, err) - } - - _, err = f.Pop(func(obj interface{}) error { - if obj.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return ErrRequeue{Err: fmt.Errorf("test error")} - }) - if err == nil || err.Error() != "test error" { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); !ok || err != nil { - t.Fatalf("object should have been requeued: %t %v", ok, err) - } - - _, err = f.Pop(func(obj interface{}) error { - if obj.(testFifoObject).name != "foo" { - t.Fatalf("unexpected object: %#v", obj) - } - return nil - }) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if _, ok, err := f.GetByKey("foo"); ok || err != nil { - t.Fatalf("object should have been removed: %t %v", ok, err) - } -} - -func TestFIFO_addUpdate(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - f.Add(mkFifoObj("foo", 10)) - f.Update(mkFifoObj("foo", 15)) - - if e, a := []interface{}{mkFifoObj("foo", 15)}, f.List(); !reflect.DeepEqual(e, a) { - t.Errorf("Expected %+v, got %+v", e, a) - } - if e, a := []string{"foo"}, f.ListKeys(); !reflect.DeepEqual(e, a) { - t.Errorf("Expected %+v, got %+v", e, a) - } - - got := make(chan testFifoObject, 2) - go func() { - for { - got <- Pop(f).(testFifoObject) - } - }() - - first := <-got - if e, a := 15, first.val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - select { - case unexpected := <-got: - t.Errorf("Got second value %v", unexpected.val) - case <-time.After(50 * time.Millisecond): - } - _, exists, _ := f.Get(mkFifoObj("foo", "")) - if exists { - t.Errorf("item did not get removed") - } -} - -func TestFIFO_addReplace(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - f.Add(mkFifoObj("foo", 10)) - f.Replace([]interface{}{mkFifoObj("foo", 15)}, "15") - got := make(chan testFifoObject, 2) - go func() { - for { - got <- Pop(f).(testFifoObject) - } - }() - - first := <-got - if e, a := 15, first.val; e != a { - t.Errorf("Didn't get updated value (%v), got %v", e, a) - } - select { - case unexpected := <-got: - t.Errorf("Got second value %v", unexpected.val) - case <-time.After(50 * time.Millisecond): - } - _, exists, _ := f.Get(mkFifoObj("foo", "")) - if exists { - t.Errorf("item did not get removed") - } -} - -func TestFIFO_detectLineJumpers(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - - f.Add(mkFifoObj("foo", 10)) - f.Add(mkFifoObj("bar", 1)) - f.Add(mkFifoObj("foo", 11)) - f.Add(mkFifoObj("foo", 13)) - f.Add(mkFifoObj("zab", 30)) - - if e, a := 13, Pop(f).(testFifoObject).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - f.Add(mkFifoObj("foo", 14)) // ensure foo doesn't jump back in line - - if e, a := 1, Pop(f).(testFifoObject).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - if e, a := 30, Pop(f).(testFifoObject).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } - - if e, a := 14, Pop(f).(testFifoObject).val; a != e { - t.Fatalf("expected %d, got %d", e, a) - } -} - -func TestFIFO_addIfNotPresent(t *testing.T) { - f := NewFIFO(testFifoObjectKeyFunc) - - f.Add(mkFifoObj("a", 1)) - f.Add(mkFifoObj("b", 2)) - f.AddIfNotPresent(mkFifoObj("b", 3)) - f.AddIfNotPresent(mkFifoObj("c", 4)) - - if e, a := 3, len(f.items); a != e { - t.Fatalf("expected queue length %d, got %d", e, a) - } - - expectedValues := []int{1, 2, 4} - for _, expected := range expectedValues { - if actual := Pop(f).(testFifoObject).val; actual != expected { - t.Fatalf("expected value %d, got %d", expected, actual) - } - } -} - -func TestFIFO_HasSynced(t *testing.T) { - tests := []struct { - actions []func(f *FIFO) - expectedSynced bool - }{ - { - actions: []func(f *FIFO){}, - expectedSynced: false, - }, - { - actions: []func(f *FIFO){ - func(f *FIFO) { f.Add(mkFifoObj("a", 1)) }, - }, - expectedSynced: true, - }, - { - actions: []func(f *FIFO){ - func(f *FIFO) { f.Replace([]interface{}{}, "0") }, - }, - expectedSynced: true, - }, - { - actions: []func(f *FIFO){ - func(f *FIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - }, - expectedSynced: false, - }, - { - actions: []func(f *FIFO){ - func(f *FIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - func(f *FIFO) { Pop(f) }, - }, - expectedSynced: false, - }, - { - actions: []func(f *FIFO){ - func(f *FIFO) { f.Replace([]interface{}{mkFifoObj("a", 1), mkFifoObj("b", 2)}, "0") }, - func(f *FIFO) { Pop(f) }, - func(f *FIFO) { Pop(f) }, - }, - expectedSynced: true, - }, - } - - for i, test := range tests { - f := NewFIFO(testFifoObjectKeyFunc) - - for _, action := range test.actions { - action(f) - } - if e, a := test.expectedSynced, f.HasSynced(); a != e { - t.Errorf("test case %v failed, expected: %v , got %v", i, e, a) - } - } -} diff --git a/vendor/k8s.io/client-go/tools/cache/heap_test.go b/vendor/k8s.io/client-go/tools/cache/heap_test.go deleted file mode 100644 index c2e476988f..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/heap_test.go +++ /dev/null @@ -1,382 +0,0 @@ -/* -Copyright 2017 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 cache - -import ( - "sync" - "testing" - "time" -) - -func testHeapObjectKeyFunc(obj interface{}) (string, error) { - return obj.(testHeapObject).name, nil -} - -type testHeapObject struct { - name string - val interface{} -} - -func mkHeapObj(name string, val interface{}) testHeapObject { - return testHeapObject{name: name, val: val} -} - -func compareInts(val1 interface{}, val2 interface{}) bool { - first := val1.(testHeapObject).val.(int) - second := val2.(testHeapObject).val.(int) - return first < second -} - -// TestHeapBasic tests Heap invariant and synchronization. -func TestHeapBasic(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - var wg sync.WaitGroup - wg.Add(2) - const amount = 500 - var i, u int - // Insert items in the heap in opposite orders in two go routines. - go func() { - for i = amount; i > 0; i-- { - h.Add(mkHeapObj(string([]rune{'a', rune(i)}), i)) - } - wg.Done() - }() - go func() { - for u = 0; u < amount; u++ { - h.Add(mkHeapObj(string([]rune{'b', rune(u)}), u+1)) - } - wg.Done() - }() - // Wait for the two go routines to finish. - wg.Wait() - // Make sure that the numbers are popped in ascending order. - prevNum := 0 - for i := 0; i < amount*2; i++ { - obj, err := h.Pop() - num := obj.(testHeapObject).val.(int) - // All the items must be sorted. - if err != nil || prevNum > num { - t.Errorf("got %v out of order, last was %v", obj, prevNum) - } - prevNum = num - } -} - -// Tests Heap.Add and ensures that heap invariant is preserved after adding items. -func TestHeap_Add(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - h.Add(mkHeapObj("foo", 10)) - h.Add(mkHeapObj("bar", 1)) - h.Add(mkHeapObj("baz", 11)) - h.Add(mkHeapObj("zab", 30)) - h.Add(mkHeapObj("foo", 13)) // This updates "foo". - - item, err := h.Pop() - if e, a := 1, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } - item, err = h.Pop() - if e, a := 11, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } - h.Delete(mkHeapObj("baz", 11)) // Nothing is deleted. - h.Add(mkHeapObj("foo", 14)) // foo is updated. - item, err = h.Pop() - if e, a := 14, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } - item, err = h.Pop() - if e, a := 30, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } -} - -// TestHeap_BulkAdd tests Heap.BulkAdd functionality and ensures that all the -// items given to BulkAdd are added to the queue before Pop reads them. -func TestHeap_BulkAdd(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - const amount = 500 - // Insert items in the heap in opposite orders in a go routine. - go func() { - l := []interface{}{} - for i := amount; i > 0; i-- { - l = append(l, mkHeapObj(string([]rune{'a', rune(i)}), i)) - } - h.BulkAdd(l) - }() - prevNum := -1 - for i := 0; i < amount; i++ { - obj, err := h.Pop() - num := obj.(testHeapObject).val.(int) - // All the items must be sorted. - if err != nil || prevNum >= num { - t.Errorf("got %v out of order, last was %v", obj, prevNum) - } - prevNum = num - } -} - -// TestHeapEmptyPop tests that pop returns properly after heap is closed. -func TestHeapEmptyPop(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - go func() { - time.Sleep(1 * time.Second) - h.Close() - }() - _, err := h.Pop() - if err == nil || err.Error() != closedMsg { - t.Errorf("pop should have returned heap closed error: %v", err) - } -} - -// TestHeap_AddIfNotPresent tests Heap.AddIfNotPresent and ensures that heap -// invariant is preserved after adding items. -func TestHeap_AddIfNotPresent(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - h.AddIfNotPresent(mkHeapObj("foo", 10)) - h.AddIfNotPresent(mkHeapObj("bar", 1)) - h.AddIfNotPresent(mkHeapObj("baz", 11)) - h.AddIfNotPresent(mkHeapObj("zab", 30)) - h.AddIfNotPresent(mkHeapObj("foo", 13)) // This is not added. - - if len := len(h.data.items); len != 4 { - t.Errorf("unexpected number of items: %d", len) - } - if val := h.data.items["foo"].obj.(testHeapObject).val; val != 10 { - t.Errorf("unexpected value: %d", val) - } - item, err := h.Pop() - if e, a := 1, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } - item, err = h.Pop() - if e, a := 10, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } - // bar is already popped. Let's add another one. - h.AddIfNotPresent(mkHeapObj("bar", 14)) - item, err = h.Pop() - if e, a := 11, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } - item, err = h.Pop() - if e, a := 14, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } -} - -// TestHeap_Delete tests Heap.Delete and ensures that heap invariant is -// preserved after deleting items. -func TestHeap_Delete(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - h.Add(mkHeapObj("foo", 10)) - h.Add(mkHeapObj("bar", 1)) - h.Add(mkHeapObj("bal", 31)) - h.Add(mkHeapObj("baz", 11)) - - // Delete head. Delete should work with "key" and doesn't care about the value. - if err := h.Delete(mkHeapObj("bar", 200)); err != nil { - t.Fatalf("Failed to delete head.") - } - item, err := h.Pop() - if e, a := 10, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } - h.Add(mkHeapObj("zab", 30)) - h.Add(mkHeapObj("faz", 30)) - len := h.data.Len() - // Delete non-existing item. - if err = h.Delete(mkHeapObj("non-existent", 10)); err == nil || len != h.data.Len() { - t.Fatalf("Didn't expect any item removal") - } - // Delete tail. - if err = h.Delete(mkHeapObj("bal", 31)); err != nil { - t.Fatalf("Failed to delete tail.") - } - // Delete one of the items with value 30. - if err = h.Delete(mkHeapObj("zab", 30)); err != nil { - t.Fatalf("Failed to delete item.") - } - item, err = h.Pop() - if e, a := 11, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } - item, err = h.Pop() - if e, a := 30, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } - if h.data.Len() != 0 { - t.Fatalf("expected an empty heap.") - } -} - -// TestHeap_Update tests Heap.Update and ensures that heap invariant is -// preserved after adding items. -func TestHeap_Update(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - h.Add(mkHeapObj("foo", 10)) - h.Add(mkHeapObj("bar", 1)) - h.Add(mkHeapObj("bal", 31)) - h.Add(mkHeapObj("baz", 11)) - - // Update an item to a value that should push it to the head. - h.Update(mkHeapObj("baz", 0)) - if h.data.queue[0] != "baz" || h.data.items["baz"].index != 0 { - t.Fatalf("expected baz to be at the head") - } - item, err := h.Pop() - if e, a := 0, item.(testHeapObject).val; err != nil || a != e { - t.Fatalf("expected %d, got %d", e, a) - } - // Update bar to push it farther back in the queue. - h.Update(mkHeapObj("bar", 100)) - if h.data.queue[0] != "foo" || h.data.items["foo"].index != 0 { - t.Fatalf("expected foo to be at the head") - } -} - -// TestHeap_Get tests Heap.Get. -func TestHeap_Get(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - h.Add(mkHeapObj("foo", 10)) - h.Add(mkHeapObj("bar", 1)) - h.Add(mkHeapObj("bal", 31)) - h.Add(mkHeapObj("baz", 11)) - - // Get works with the key. - obj, exists, err := h.Get(mkHeapObj("baz", 0)) - if err != nil || exists == false || obj.(testHeapObject).val != 11 { - t.Fatalf("unexpected error in getting element") - } - // Get non-existing object. - _, exists, err = h.Get(mkHeapObj("non-existing", 0)) - if err != nil || exists == true { - t.Fatalf("didn't expect to get any object") - } -} - -// TestHeap_GetByKey tests Heap.GetByKey and is very similar to TestHeap_Get. -func TestHeap_GetByKey(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - h.Add(mkHeapObj("foo", 10)) - h.Add(mkHeapObj("bar", 1)) - h.Add(mkHeapObj("bal", 31)) - h.Add(mkHeapObj("baz", 11)) - - obj, exists, err := h.GetByKey("baz") - if err != nil || exists == false || obj.(testHeapObject).val != 11 { - t.Fatalf("unexpected error in getting element") - } - // Get non-existing object. - _, exists, err = h.GetByKey("non-existing") - if err != nil || exists == true { - t.Fatalf("didn't expect to get any object") - } -} - -// TestHeap_Close tests Heap.Close and Heap.IsClosed functions. -func TestHeap_Close(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - h.Add(mkHeapObj("foo", 10)) - h.Add(mkHeapObj("bar", 1)) - - if h.IsClosed() { - t.Fatalf("didn't expect heap to be closed") - } - h.Close() - if !h.IsClosed() { - t.Fatalf("expect heap to be closed") - } -} - -// TestHeap_List tests Heap.List function. -func TestHeap_List(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - list := h.List() - if len(list) != 0 { - t.Errorf("expected an empty list") - } - - items := map[string]int{ - "foo": 10, - "bar": 1, - "bal": 30, - "baz": 11, - "faz": 30, - } - for k, v := range items { - h.Add(mkHeapObj(k, v)) - } - list = h.List() - if len(list) != len(items) { - t.Errorf("expected %d items, got %d", len(items), len(list)) - } - for _, obj := range list { - heapObj := obj.(testHeapObject) - v, ok := items[heapObj.name] - if !ok || v != heapObj.val { - t.Errorf("unexpected item in the list: %v", heapObj) - } - } -} - -// TestHeap_ListKeys tests Heap.ListKeys function. Scenario is the same as -// TestHeap_list. -func TestHeap_ListKeys(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - list := h.ListKeys() - if len(list) != 0 { - t.Errorf("expected an empty list") - } - - items := map[string]int{ - "foo": 10, - "bar": 1, - "bal": 30, - "baz": 11, - "faz": 30, - } - for k, v := range items { - h.Add(mkHeapObj(k, v)) - } - list = h.ListKeys() - if len(list) != len(items) { - t.Errorf("expected %d items, got %d", len(items), len(list)) - } - for _, key := range list { - _, ok := items[key] - if !ok { - t.Errorf("unexpected item in the list: %v", key) - } - } -} - -// TestHeapAddAfterClose tests that heap returns an error if anything is added -// after it is closed. -func TestHeapAddAfterClose(t *testing.T) { - h := NewHeap(testHeapObjectKeyFunc, compareInts) - h.Close() - if err := h.Add(mkHeapObj("test", 1)); err == nil || err.Error() != closedMsg { - t.Errorf("expected heap closed error") - } - if err := h.AddIfNotPresent(mkHeapObj("test", 1)); err == nil || err.Error() != closedMsg { - t.Errorf("expected heap closed error") - } - if err := h.BulkAdd([]interface{}{mkHeapObj("test", 1)}); err == nil || err.Error() != closedMsg { - t.Errorf("expected heap closed error") - } -} diff --git a/vendor/k8s.io/client-go/tools/cache/index_test.go b/vendor/k8s.io/client-go/tools/cache/index_test.go deleted file mode 100644 index ecc104c0c5..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/index_test.go +++ /dev/null @@ -1,163 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package cache - -import ( - "strings" - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func testIndexFunc(obj interface{}) ([]string, error) { - pod := obj.(*v1.Pod) - return []string{pod.Labels["foo"]}, nil -} - -func TestGetIndexFuncValues(t *testing.T) { - index := NewIndexer(MetaNamespaceKeyFunc, Indexers{"testmodes": testIndexFunc}) - - pod1 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "one", Labels: map[string]string{"foo": "bar"}}} - pod2 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "two", Labels: map[string]string{"foo": "bar"}}} - pod3 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "tre", Labels: map[string]string{"foo": "biz"}}} - - index.Add(pod1) - index.Add(pod2) - index.Add(pod3) - - keys := index.ListIndexFuncValues("testmodes") - if len(keys) != 2 { - t.Errorf("Expected 2 keys but got %v", len(keys)) - } - - for _, key := range keys { - if key != "bar" && key != "biz" { - t.Errorf("Expected only 'bar' or 'biz' but got %s", key) - } - } -} - -func testUsersIndexFunc(obj interface{}) ([]string, error) { - pod := obj.(*v1.Pod) - usersString := pod.Annotations["users"] - - return strings.Split(usersString, ","), nil -} - -func TestMultiIndexKeys(t *testing.T) { - index := NewIndexer(MetaNamespaceKeyFunc, Indexers{"byUser": testUsersIndexFunc}) - - pod1 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "one", Annotations: map[string]string{"users": "ernie,bert"}}} - pod2 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "two", Annotations: map[string]string{"users": "bert,oscar"}}} - pod3 := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "tre", Annotations: map[string]string{"users": "ernie,elmo"}}} - - index.Add(pod1) - index.Add(pod2) - index.Add(pod3) - - erniePods, err := index.ByIndex("byUser", "ernie") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(erniePods) != 2 { - t.Errorf("Expected 2 pods but got %v", len(erniePods)) - } - for _, erniePod := range erniePods { - if erniePod.(*v1.Pod).Name != "one" && erniePod.(*v1.Pod).Name != "tre" { - t.Errorf("Expected only 'one' or 'tre' but got %s", erniePod.(*v1.Pod).Name) - } - } - - bertPods, err := index.ByIndex("byUser", "bert") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(bertPods) != 2 { - t.Errorf("Expected 2 pods but got %v", len(bertPods)) - } - for _, bertPod := range bertPods { - if bertPod.(*v1.Pod).Name != "one" && bertPod.(*v1.Pod).Name != "two" { - t.Errorf("Expected only 'one' or 'two' but got %s", bertPod.(*v1.Pod).Name) - } - } - - oscarPods, err := index.ByIndex("byUser", "oscar") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(oscarPods) != 1 { - t.Errorf("Expected 1 pods but got %v", len(erniePods)) - } - for _, oscarPod := range oscarPods { - if oscarPod.(*v1.Pod).Name != "two" { - t.Errorf("Expected only 'two' but got %s", oscarPod.(*v1.Pod).Name) - } - } - - ernieAndBertKeys, err := index.Index("byUser", pod1) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(ernieAndBertKeys) != 3 { - t.Errorf("Expected 3 pods but got %v", len(ernieAndBertKeys)) - } - for _, ernieAndBertKey := range ernieAndBertKeys { - if ernieAndBertKey.(*v1.Pod).Name != "one" && ernieAndBertKey.(*v1.Pod).Name != "two" && ernieAndBertKey.(*v1.Pod).Name != "tre" { - t.Errorf("Expected only 'one', 'two' or 'tre' but got %s", ernieAndBertKey.(*v1.Pod).Name) - } - } - - index.Delete(pod3) - erniePods, err = index.ByIndex("byUser", "ernie") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(erniePods) != 1 { - t.Errorf("Expected 1 pods but got %v", len(erniePods)) - } - for _, erniePod := range erniePods { - if erniePod.(*v1.Pod).Name != "one" { - t.Errorf("Expected only 'one' but got %s", erniePod.(*v1.Pod).Name) - } - } - - elmoPods, err := index.ByIndex("byUser", "elmo") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(elmoPods) != 0 { - t.Errorf("Expected 0 pods but got %v", len(elmoPods)) - } - - copyOfPod2 := pod2.DeepCopy() - copyOfPod2.Annotations["users"] = "oscar" - index.Update(copyOfPod2) - bertPods, err = index.ByIndex("byUser", "bert") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if len(bertPods) != 1 { - t.Errorf("Expected 1 pods but got %v", len(bertPods)) - } - for _, bertPod := range bertPods { - if bertPod.(*v1.Pod).Name != "one" { - t.Errorf("Expected only 'one' but got %s", bertPod.(*v1.Pod).Name) - } - } - -} diff --git a/vendor/k8s.io/client-go/tools/cache/mutation_detector_test.go b/vendor/k8s.io/client-go/tools/cache/mutation_detector_test.go deleted file mode 100644 index 41b6942f5b..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/mutation_detector_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// +build !race - -/* -Copyright 2016 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 cache - -import ( - "testing" - "time" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/watch" -) - -func TestMutationDetector(t *testing.T) { - fakeWatch := watch.NewFake() - lw := &testLW{ - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - return fakeWatch, nil - }, - ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - return &v1.PodList{}, nil - }, - } - pod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "anything", - Labels: map[string]string{"check": "foo"}, - }, - } - stopCh := make(chan struct{}) - defer close(stopCh) - addReceived := make(chan bool) - mutationFound := make(chan bool) - - informer := NewSharedInformer(lw, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) - informer.cacheMutationDetector = &defaultCacheMutationDetector{ - name: "name", - period: 1 * time.Second, - failureFunc: func(message string) { - mutationFound <- true - }, - } - informer.AddEventHandler( - ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - addReceived <- true - }, - }, - ) - go informer.Run(stopCh) - - fakeWatch.Add(pod) - - select { - case <-addReceived: - } - - pod.Labels["change"] = "true" - - select { - case <-mutationFound: - } - -} diff --git a/vendor/k8s.io/client-go/tools/cache/processor_listener_test.go b/vendor/k8s.io/client-go/tools/cache/processor_listener_test.go deleted file mode 100644 index 1da73420f0..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/processor_listener_test.go +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright 2016 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 cache - -import ( - "sync" - "testing" - "time" - - "k8s.io/apimachinery/pkg/util/wait" -) - -const ( - concurrencyLevel = 5 -) - -func BenchmarkListener(b *testing.B) { - var notification addNotification - - var swg sync.WaitGroup - swg.Add(b.N) - b.SetParallelism(concurrencyLevel) - // Preallocate enough space so that benchmark does not run out of it - pl := newProcessListener(&ResourceEventHandlerFuncs{ - AddFunc: func(obj interface{}) { - swg.Done() - }, - }, 0, 0, time.Now(), 1024*1024) - var wg wait.Group - defer wg.Wait() // Wait for .run and .pop to stop - defer close(pl.addCh) // Tell .run and .pop to stop - wg.Start(pl.run) - wg.Start(pl.pop) - - b.ReportAllocs() - b.ResetTimer() - b.RunParallel(func(pb *testing.PB) { - for pb.Next() { - pl.add(notification) - } - }) - swg.Wait() // Block until all notifications have been received - b.StopTimer() -} diff --git a/vendor/k8s.io/client-go/tools/cache/reflector_test.go b/vendor/k8s.io/client-go/tools/cache/reflector_test.go deleted file mode 100644 index bb06059f7e..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/reflector_test.go +++ /dev/null @@ -1,389 +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 cache - -import ( - "errors" - "fmt" - "math/rand" - "strconv" - "testing" - "time" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/apimachinery/pkg/watch" -) - -var nevererrc chan error - -type testLW struct { - ListFunc func(options metav1.ListOptions) (runtime.Object, error) - WatchFunc func(options metav1.ListOptions) (watch.Interface, error) -} - -func (t *testLW) List(options metav1.ListOptions) (runtime.Object, error) { - return t.ListFunc(options) -} -func (t *testLW) Watch(options metav1.ListOptions) (watch.Interface, error) { - return t.WatchFunc(options) -} - -func TestCloseWatchChannelOnError(t *testing.T) { - r := NewReflector(&testLW{}, &v1.Pod{}, NewStore(MetaNamespaceKeyFunc), 0) - pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "bar"}} - fw := watch.NewFake() - r.listerWatcher = &testLW{ - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - return fw, nil - }, - ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - return &v1.PodList{ListMeta: metav1.ListMeta{ResourceVersion: "1"}}, nil - }, - } - go r.ListAndWatch(wait.NeverStop) - fw.Error(pod) - select { - case _, ok := <-fw.ResultChan(): - if ok { - t.Errorf("Watch channel left open after cancellation") - } - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("the cancellation is at least %s late", wait.ForeverTestTimeout.String()) - break - } -} - -func TestRunUntil(t *testing.T) { - stopCh := make(chan struct{}) - store := NewStore(MetaNamespaceKeyFunc) - r := NewReflector(&testLW{}, &v1.Pod{}, store, 0) - fw := watch.NewFake() - r.listerWatcher = &testLW{ - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - return fw, nil - }, - ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - return &v1.PodList{ListMeta: metav1.ListMeta{ResourceVersion: "1"}}, nil - }, - } - go r.Run(stopCh) - // Synchronously add a dummy pod into the watch channel so we - // know the RunUntil go routine is in the watch handler. - fw.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "bar"}}) - close(stopCh) - select { - case _, ok := <-fw.ResultChan(): - if ok { - t.Errorf("Watch channel left open after stopping the watch") - } - case <-time.After(wait.ForeverTestTimeout): - t.Errorf("the cancellation is at least %s late", wait.ForeverTestTimeout.String()) - break - } -} - -func TestReflectorResyncChan(t *testing.T) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, time.Millisecond) - a, _ := g.resyncChan() - b := time.After(wait.ForeverTestTimeout) - select { - case <-a: - t.Logf("got timeout as expected") - case <-b: - t.Errorf("resyncChan() is at least 99 milliseconds late??") - } -} - -func BenchmarkReflectorResyncChanMany(b *testing.B) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 25*time.Millisecond) - // The improvement to this (calling the timer's Stop() method) makes - // this benchmark about 40% faster. - for i := 0; i < b.N; i++ { - g.resyncPeriod = time.Duration(rand.Float64() * float64(time.Millisecond) * 25) - _, stop := g.resyncChan() - stop() - } -} - -func TestReflectorWatchHandlerError(t *testing.T) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) - fw := watch.NewFake() - go func() { - fw.Stop() - }() - var resumeRV string - err := g.watchHandler(fw, &resumeRV, nevererrc, wait.NeverStop) - if err == nil { - t.Errorf("unexpected non-error") - } -} - -func TestReflectorWatchHandler(t *testing.T) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) - fw := watch.NewFake() - s.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}) - s.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "bar"}}) - go func() { - fw.Add(&v1.Service{ObjectMeta: metav1.ObjectMeta{Name: "rejected"}}) - fw.Delete(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}) - fw.Modify(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "bar", ResourceVersion: "55"}}) - fw.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "baz", ResourceVersion: "32"}}) - fw.Stop() - }() - var resumeRV string - err := g.watchHandler(fw, &resumeRV, nevererrc, wait.NeverStop) - if err != nil { - t.Errorf("unexpected error %v", err) - } - - mkPod := func(id string, rv string) *v1.Pod { - return &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: id, ResourceVersion: rv}} - } - - table := []struct { - Pod *v1.Pod - exists bool - }{ - {mkPod("foo", ""), false}, - {mkPod("rejected", ""), false}, - {mkPod("bar", "55"), true}, - {mkPod("baz", "32"), true}, - } - for _, item := range table { - obj, exists, _ := s.Get(item.Pod) - if e, a := item.exists, exists; e != a { - t.Errorf("%v: expected %v, got %v", item.Pod, e, a) - } - if !exists { - continue - } - if e, a := item.Pod.ResourceVersion, obj.(*v1.Pod).ResourceVersion; e != a { - t.Errorf("%v: expected %v, got %v", item.Pod, e, a) - } - } - - // RV should send the last version we see. - if e, a := "32", resumeRV; e != a { - t.Errorf("expected %v, got %v", e, a) - } - - // last sync resource version should be the last version synced with store - if e, a := "32", g.LastSyncResourceVersion(); e != a { - t.Errorf("expected %v, got %v", e, a) - } -} - -func TestReflectorStopWatch(t *testing.T) { - s := NewStore(MetaNamespaceKeyFunc) - g := NewReflector(&testLW{}, &v1.Pod{}, s, 0) - fw := watch.NewFake() - var resumeRV string - stopWatch := make(chan struct{}, 1) - stopWatch <- struct{}{} - err := g.watchHandler(fw, &resumeRV, nevererrc, stopWatch) - if err != errorStopRequested { - t.Errorf("expected stop error, got %q", err) - } -} - -func TestReflectorListAndWatch(t *testing.T) { - createdFakes := make(chan *watch.FakeWatcher) - - // The ListFunc says that it's at revision 1. Therefore, we expect our WatchFunc - // to get called at the beginning of the watch with 1, and again with 3 when we - // inject an error. - expectedRVs := []string{"1", "3"} - lw := &testLW{ - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - rv := options.ResourceVersion - fw := watch.NewFake() - if e, a := expectedRVs[0], rv; e != a { - t.Errorf("Expected rv %v, but got %v", e, a) - } - expectedRVs = expectedRVs[1:] - // channel is not buffered because the for loop below needs to block. But - // we don't want to block here, so report the new fake via a go routine. - go func() { createdFakes <- fw }() - return fw, nil - }, - ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - return &v1.PodList{ListMeta: metav1.ListMeta{ResourceVersion: "1"}}, nil - }, - } - s := NewFIFO(MetaNamespaceKeyFunc) - r := NewReflector(lw, &v1.Pod{}, s, 0) - go r.ListAndWatch(wait.NeverStop) - - ids := []string{"foo", "bar", "baz", "qux", "zoo"} - var fw *watch.FakeWatcher - for i, id := range ids { - if fw == nil { - fw = <-createdFakes - } - sendingRV := strconv.FormatUint(uint64(i+2), 10) - fw.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: id, ResourceVersion: sendingRV}}) - if sendingRV == "3" { - // Inject a failure. - fw.Stop() - fw = nil - } - } - - // Verify we received the right ids with the right resource versions. - for i, id := range ids { - pod := Pop(s).(*v1.Pod) - if e, a := id, pod.Name; e != a { - t.Errorf("%v: Expected %v, got %v", i, e, a) - } - if e, a := strconv.FormatUint(uint64(i+2), 10), pod.ResourceVersion; e != a { - t.Errorf("%v: Expected %v, got %v", i, e, a) - } - } - - if len(expectedRVs) != 0 { - t.Error("called watchStarter an unexpected number of times") - } -} - -func TestReflectorListAndWatchWithErrors(t *testing.T) { - mkPod := func(id string, rv string) *v1.Pod { - return &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: id, ResourceVersion: rv}} - } - mkList := func(rv string, pods ...*v1.Pod) *v1.PodList { - list := &v1.PodList{ListMeta: metav1.ListMeta{ResourceVersion: rv}} - for _, pod := range pods { - list.Items = append(list.Items, *pod) - } - return list - } - table := []struct { - list *v1.PodList - listErr error - events []watch.Event - watchErr error - }{ - { - list: mkList("1"), - events: []watch.Event{ - {Type: watch.Added, Object: mkPod("foo", "2")}, - {Type: watch.Added, Object: mkPod("bar", "3")}, - }, - }, { - list: mkList("3", mkPod("foo", "2"), mkPod("bar", "3")), - events: []watch.Event{ - {Type: watch.Deleted, Object: mkPod("foo", "4")}, - {Type: watch.Added, Object: mkPod("qux", "5")}, - }, - }, { - listErr: fmt.Errorf("a list error"), - }, { - list: mkList("5", mkPod("bar", "3"), mkPod("qux", "5")), - watchErr: fmt.Errorf("a watch error"), - }, { - list: mkList("5", mkPod("bar", "3"), mkPod("qux", "5")), - events: []watch.Event{ - {Type: watch.Added, Object: mkPod("baz", "6")}, - }, - }, { - list: mkList("6", mkPod("bar", "3"), mkPod("qux", "5"), mkPod("baz", "6")), - }, - } - - s := NewFIFO(MetaNamespaceKeyFunc) - for line, item := range table { - if item.list != nil { - // Test that the list is what currently exists in the store. - current := s.List() - checkMap := map[string]string{} - for _, item := range current { - pod := item.(*v1.Pod) - checkMap[pod.Name] = pod.ResourceVersion - } - for _, pod := range item.list.Items { - if e, a := pod.ResourceVersion, checkMap[pod.Name]; e != a { - t.Errorf("%v: expected %v, got %v for pod %v", line, e, a, pod.Name) - } - } - if e, a := len(item.list.Items), len(checkMap); e != a { - t.Errorf("%v: expected %v, got %v", line, e, a) - } - } - watchRet, watchErr := item.events, item.watchErr - lw := &testLW{ - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - if watchErr != nil { - return nil, watchErr - } - watchErr = fmt.Errorf("second watch") - fw := watch.NewFake() - go func() { - for _, e := range watchRet { - fw.Action(e.Type, e.Object) - } - fw.Stop() - }() - return fw, nil - }, - ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - return item.list, item.listErr - }, - } - r := NewReflector(lw, &v1.Pod{}, s, 0) - r.ListAndWatch(wait.NeverStop) - } -} - -func TestReflectorResync(t *testing.T) { - iteration := 0 - stopCh := make(chan struct{}) - rerr := errors.New("expected resync reached") - s := &FakeCustomStore{ - ResyncFunc: func() error { - iteration++ - if iteration == 2 { - return rerr - } - return nil - }, - } - - lw := &testLW{ - WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { - fw := watch.NewFake() - return fw, nil - }, - ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { - return &v1.PodList{ListMeta: metav1.ListMeta{ResourceVersion: "0"}}, nil - }, - } - resyncPeriod := 1 * time.Millisecond - r := NewReflector(lw, &v1.Pod{}, s, resyncPeriod) - if err := r.ListAndWatch(stopCh); err != nil { - // error from Resync is not propaged up to here. - t.Errorf("expected error %v", err) - } - if iteration != 2 { - t.Errorf("exactly 2 iterations were expected, got: %v", iteration) - } -} diff --git a/vendor/k8s.io/client-go/tools/cache/shared_informer_test.go b/vendor/k8s.io/client-go/tools/cache/shared_informer_test.go deleted file mode 100644 index 22e4a90ddd..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/shared_informer_test.go +++ /dev/null @@ -1,265 +0,0 @@ -/* -Copyright 2017 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 cache - -import ( - "fmt" - "sync" - "testing" - "time" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/clock" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/wait" - fcache "k8s.io/client-go/tools/cache/testing" -) - -type testListener struct { - lock sync.RWMutex - resyncPeriod time.Duration - expectedItemNames sets.String - receivedItemNames []string - name string -} - -func newTestListener(name string, resyncPeriod time.Duration, expected ...string) *testListener { - l := &testListener{ - resyncPeriod: resyncPeriod, - expectedItemNames: sets.NewString(expected...), - name: name, - } - return l -} - -func (l *testListener) OnAdd(obj interface{}) { - l.handle(obj) -} - -func (l *testListener) OnUpdate(old, new interface{}) { - l.handle(new) -} - -func (l *testListener) OnDelete(obj interface{}) { -} - -func (l *testListener) handle(obj interface{}) { - key, _ := MetaNamespaceKeyFunc(obj) - fmt.Printf("%s: handle: %v\n", l.name, key) - l.lock.Lock() - defer l.lock.Unlock() - - objectMeta, _ := meta.Accessor(obj) - l.receivedItemNames = append(l.receivedItemNames, objectMeta.GetName()) -} - -func (l *testListener) ok() bool { - fmt.Println("polling") - err := wait.PollImmediate(100*time.Millisecond, 2*time.Second, func() (bool, error) { - if l.satisfiedExpectations() { - return true, nil - } - return false, nil - }) - if err != nil { - return false - } - - // wait just a bit to allow any unexpected stragglers to come in - fmt.Println("sleeping") - time.Sleep(1 * time.Second) - fmt.Println("final check") - return l.satisfiedExpectations() -} - -func (l *testListener) satisfiedExpectations() bool { - l.lock.RLock() - defer l.lock.RUnlock() - - return len(l.receivedItemNames) == l.expectedItemNames.Len() && sets.NewString(l.receivedItemNames...).Equal(l.expectedItemNames) -} - -func TestListenerResyncPeriods(t *testing.T) { - // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() - source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1"}}) - source.Add(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod2"}}) - - // create the shared informer and resync every 1s - informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) - - clock := clock.NewFakeClock(time.Now()) - informer.clock = clock - informer.processor.clock = clock - - // listener 1, never resync - listener1 := newTestListener("listener1", 0, "pod1", "pod2") - informer.AddEventHandlerWithResyncPeriod(listener1, listener1.resyncPeriod) - - // listener 2, resync every 2s - listener2 := newTestListener("listener2", 2*time.Second, "pod1", "pod2") - informer.AddEventHandlerWithResyncPeriod(listener2, listener2.resyncPeriod) - - // listener 3, resync every 3s - listener3 := newTestListener("listener3", 3*time.Second, "pod1", "pod2") - informer.AddEventHandlerWithResyncPeriod(listener3, listener3.resyncPeriod) - listeners := []*testListener{listener1, listener2, listener3} - - stop := make(chan struct{}) - defer close(stop) - - go informer.Run(stop) - - // ensure all listeners got the initial List - for _, listener := range listeners { - if !listener.ok() { - t.Errorf("%s: expected %v, got %v", listener.name, listener.expectedItemNames, listener.receivedItemNames) - } - } - - // reset - for _, listener := range listeners { - listener.receivedItemNames = []string{} - } - - // advance so listener2 gets a resync - clock.Step(2 * time.Second) - - // make sure listener2 got the resync - if !listener2.ok() { - t.Errorf("%s: expected %v, got %v", listener2.name, listener2.expectedItemNames, listener2.receivedItemNames) - } - - // wait a bit to give errant items a chance to go to 1 and 3 - time.Sleep(1 * time.Second) - - // make sure listeners 1 and 3 got nothing - if len(listener1.receivedItemNames) != 0 { - t.Errorf("listener1: should not have resynced (got %d)", len(listener1.receivedItemNames)) - } - if len(listener3.receivedItemNames) != 0 { - t.Errorf("listener3: should not have resynced (got %d)", len(listener3.receivedItemNames)) - } - - // reset - for _, listener := range listeners { - listener.receivedItemNames = []string{} - } - - // advance so listener3 gets a resync - clock.Step(1 * time.Second) - - // make sure listener3 got the resync - if !listener3.ok() { - t.Errorf("%s: expected %v, got %v", listener3.name, listener3.expectedItemNames, listener3.receivedItemNames) - } - - // wait a bit to give errant items a chance to go to 1 and 2 - time.Sleep(1 * time.Second) - - // make sure listeners 1 and 2 got nothing - if len(listener1.receivedItemNames) != 0 { - t.Errorf("listener1: should not have resynced (got %d)", len(listener1.receivedItemNames)) - } - if len(listener2.receivedItemNames) != 0 { - t.Errorf("listener2: should not have resynced (got %d)", len(listener2.receivedItemNames)) - } -} - -func TestResyncCheckPeriod(t *testing.T) { - // source simulates an apiserver object endpoint. - source := fcache.NewFakeControllerSource() - - // create the shared informer and resync every 12 hours - informer := NewSharedInformer(source, &v1.Pod{}, 12*time.Hour).(*sharedIndexInformer) - - clock := clock.NewFakeClock(time.Now()) - informer.clock = clock - informer.processor.clock = clock - - // listener 1, never resync - listener1 := newTestListener("listener1", 0) - informer.AddEventHandlerWithResyncPeriod(listener1, listener1.resyncPeriod) - if e, a := 12*time.Hour, informer.resyncCheckPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - if e, a := time.Duration(0), informer.processor.listeners[0].resyncPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - - // listener 2, resync every minute - listener2 := newTestListener("listener2", 1*time.Minute) - informer.AddEventHandlerWithResyncPeriod(listener2, listener2.resyncPeriod) - if e, a := 1*time.Minute, informer.resyncCheckPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - if e, a := time.Duration(0), informer.processor.listeners[0].resyncPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - if e, a := 1*time.Minute, informer.processor.listeners[1].resyncPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - - // listener 3, resync every 55 seconds - listener3 := newTestListener("listener3", 55*time.Second) - informer.AddEventHandlerWithResyncPeriod(listener3, listener3.resyncPeriod) - if e, a := 55*time.Second, informer.resyncCheckPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - if e, a := time.Duration(0), informer.processor.listeners[0].resyncPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - if e, a := 1*time.Minute, informer.processor.listeners[1].resyncPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - if e, a := 55*time.Second, informer.processor.listeners[2].resyncPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - - // listener 4, resync every 5 seconds - listener4 := newTestListener("listener4", 5*time.Second) - informer.AddEventHandlerWithResyncPeriod(listener4, listener4.resyncPeriod) - if e, a := 5*time.Second, informer.resyncCheckPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - if e, a := time.Duration(0), informer.processor.listeners[0].resyncPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - if e, a := 1*time.Minute, informer.processor.listeners[1].resyncPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - if e, a := 55*time.Second, informer.processor.listeners[2].resyncPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } - if e, a := 5*time.Second, informer.processor.listeners[3].resyncPeriod; e != a { - t.Errorf("expected %d, got %d", e, a) - } -} - -// verify that https://github.com/kubernetes/kubernetes/issues/59822 is fixed -func TestSharedInformerInitializationRace(t *testing.T) { - source := fcache.NewFakeControllerSource() - informer := NewSharedInformer(source, &v1.Pod{}, 1*time.Second).(*sharedIndexInformer) - listener := newTestListener("raceListener", 0) - - stop := make(chan struct{}) - go informer.AddEventHandlerWithResyncPeriod(listener, listener.resyncPeriod) - go informer.Run(stop) - close(stop) -} diff --git a/vendor/k8s.io/client-go/tools/cache/store_test.go b/vendor/k8s.io/client-go/tools/cache/store_test.go deleted file mode 100644 index 52c9585a9b..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/store_test.go +++ /dev/null @@ -1,156 +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 cache - -import ( - "testing" - - "k8s.io/apimachinery/pkg/util/sets" -) - -// Test public interface -func doTestStore(t *testing.T, store Store) { - mkObj := func(id string, val string) testStoreObject { - return testStoreObject{id: id, val: val} - } - - store.Add(mkObj("foo", "bar")) - if item, ok, _ := store.Get(mkObj("foo", "")); !ok { - t.Errorf("didn't find inserted item") - } else { - if e, a := "bar", item.(testStoreObject).val; e != a { - t.Errorf("expected %v, got %v", e, a) - } - } - store.Update(mkObj("foo", "baz")) - if item, ok, _ := store.Get(mkObj("foo", "")); !ok { - t.Errorf("didn't find inserted item") - } else { - if e, a := "baz", item.(testStoreObject).val; e != a { - t.Errorf("expected %v, got %v", e, a) - } - } - store.Delete(mkObj("foo", "")) - if _, ok, _ := store.Get(mkObj("foo", "")); ok { - t.Errorf("found deleted item??") - } - - // Test List. - store.Add(mkObj("a", "b")) - store.Add(mkObj("c", "d")) - store.Add(mkObj("e", "e")) - { - found := sets.String{} - for _, item := range store.List() { - found.Insert(item.(testStoreObject).val) - } - if !found.HasAll("b", "d", "e") { - t.Errorf("missing items, found: %v", found) - } - if len(found) != 3 { - t.Errorf("extra items") - } - } - - // Test Replace. - store.Replace([]interface{}{ - mkObj("foo", "foo"), - mkObj("bar", "bar"), - }, "0") - - { - found := sets.String{} - for _, item := range store.List() { - found.Insert(item.(testStoreObject).val) - } - if !found.HasAll("foo", "bar") { - t.Errorf("missing items") - } - if len(found) != 2 { - t.Errorf("extra items") - } - } -} - -// Test public interface -func doTestIndex(t *testing.T, indexer Indexer) { - mkObj := func(id string, val string) testStoreObject { - return testStoreObject{id: id, val: val} - } - - // Test Index - expected := map[string]sets.String{} - expected["b"] = sets.NewString("a", "c") - expected["f"] = sets.NewString("e") - expected["h"] = sets.NewString("g") - indexer.Add(mkObj("a", "b")) - indexer.Add(mkObj("c", "b")) - indexer.Add(mkObj("e", "f")) - indexer.Add(mkObj("g", "h")) - { - for k, v := range expected { - found := sets.String{} - indexResults, err := indexer.Index("by_val", mkObj("", k)) - if err != nil { - t.Errorf("Unexpected error %v", err) - } - for _, item := range indexResults { - found.Insert(item.(testStoreObject).id) - } - items := v.List() - if !found.HasAll(items...) { - t.Errorf("missing items, index %s, expected %v but found %v", k, items, found.List()) - } - } - } -} - -func testStoreKeyFunc(obj interface{}) (string, error) { - return obj.(testStoreObject).id, nil -} - -func testStoreIndexFunc(obj interface{}) ([]string, error) { - return []string{obj.(testStoreObject).val}, nil -} - -func testStoreIndexers() Indexers { - indexers := Indexers{} - indexers["by_val"] = testStoreIndexFunc - return indexers -} - -type testStoreObject struct { - id string - val string -} - -func TestCache(t *testing.T) { - doTestStore(t, NewStore(testStoreKeyFunc)) -} - -func TestFIFOCache(t *testing.T) { - doTestStore(t, NewFIFO(testStoreKeyFunc)) -} - -func TestUndeltaStore(t *testing.T) { - nop := func([]interface{}) {} - doTestStore(t, NewUndeltaStore(nop, testStoreKeyFunc)) -} - -func TestIndex(t *testing.T) { - doTestIndex(t, NewIndexer(testStoreKeyFunc, testStoreIndexers())) -} diff --git a/vendor/k8s.io/client-go/tools/cache/undelta_store_test.go b/vendor/k8s.io/client-go/tools/cache/undelta_store_test.go deleted file mode 100644 index 6316442e68..0000000000 --- a/vendor/k8s.io/client-go/tools/cache/undelta_store_test.go +++ /dev/null @@ -1,131 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package cache - -import ( - "reflect" - "testing" -) - -// store_test.go checks that UndeltaStore conforms to the Store interface -// behavior. This test just tests that it calls the push func in addition. - -type testUndeltaObject struct { - name string - val interface{} -} - -func testUndeltaKeyFunc(obj interface{}) (string, error) { - return obj.(testUndeltaObject).name, nil -} - -/* -var ( - o1 interface{} = t{1} - o2 interface{} = t{2} - l1 []interface{} = []interface{}{t{1}} -) -*/ - -func TestUpdateCallsPush(t *testing.T) { - mkObj := func(name string, val interface{}) testUndeltaObject { - return testUndeltaObject{name: name, val: val} - } - - var got []interface{} - var callcount int = 0 - push := func(m []interface{}) { - callcount++ - got = m - } - - u := NewUndeltaStore(push, testUndeltaKeyFunc) - - u.Add(mkObj("a", 2)) - u.Update(mkObj("a", 1)) - if callcount != 2 { - t.Errorf("Expected 2 calls, got %d", callcount) - } - - l := []interface{}{mkObj("a", 1)} - if !reflect.DeepEqual(l, got) { - t.Errorf("Expected %#v, Got %#v", l, got) - } -} - -func TestDeleteCallsPush(t *testing.T) { - mkObj := func(name string, val interface{}) testUndeltaObject { - return testUndeltaObject{name: name, val: val} - } - - var got []interface{} - var callcount int = 0 - push := func(m []interface{}) { - callcount++ - got = m - } - - u := NewUndeltaStore(push, testUndeltaKeyFunc) - - u.Add(mkObj("a", 2)) - u.Delete(mkObj("a", "")) - if callcount != 2 { - t.Errorf("Expected 2 calls, got %d", callcount) - } - expected := []interface{}{} - if !reflect.DeepEqual(expected, got) { - t.Errorf("Expected %#v, Got %#v", expected, got) - } -} - -func TestReadsDoNotCallPush(t *testing.T) { - push := func(m []interface{}) { - t.Errorf("Unexpected call to push!") - } - - u := NewUndeltaStore(push, testUndeltaKeyFunc) - - // These should not call push. - _ = u.List() - _, _, _ = u.Get(testUndeltaObject{"a", ""}) -} - -func TestReplaceCallsPush(t *testing.T) { - mkObj := func(name string, val interface{}) testUndeltaObject { - return testUndeltaObject{name: name, val: val} - } - - var got []interface{} - var callcount int = 0 - push := func(m []interface{}) { - callcount++ - got = m - } - - u := NewUndeltaStore(push, testUndeltaKeyFunc) - - m := []interface{}{mkObj("a", 1)} - - u.Replace(m, "0") - if callcount != 1 { - t.Errorf("Expected 1 calls, got %d", callcount) - } - expected := []interface{}{mkObj("a", 1)} - if !reflect.DeepEqual(expected, got) { - t.Errorf("Expected %#v, Got %#v", expected, got) - } -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/helpers_test.go b/vendor/k8s.io/client-go/tools/clientcmd/api/helpers_test.go deleted file mode 100644 index 430208456d..0000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/helpers_test.go +++ /dev/null @@ -1,301 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package api - -import ( - "fmt" - "io/ioutil" - "os" - "reflect" - "testing" - - "github.com/ghodss/yaml" -) - -func newMergedConfig(certFile, certContent, keyFile, keyContent, caFile, caContent string, t *testing.T) Config { - if err := ioutil.WriteFile(certFile, []byte(certContent), 0644); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := ioutil.WriteFile(keyFile, []byte(keyContent), 0600); err != nil { - t.Errorf("unexpected error: %v", err) - } - if err := ioutil.WriteFile(caFile, []byte(caContent), 0644); err != nil { - t.Errorf("unexpected error: %v", err) - } - - return Config{ - AuthInfos: map[string]*AuthInfo{ - "red-user": {Token: "red-token", ClientCertificateData: []byte(certContent), ClientKeyData: []byte(keyContent)}, - "blue-user": {Token: "blue-token", ClientCertificate: certFile, ClientKey: keyFile}}, - Clusters: map[string]*Cluster{ - "cow-cluster": {Server: "http://cow.org:8080", CertificateAuthorityData: []byte(caContent)}, - "chicken-cluster": {Server: "http://chicken.org:8080", CertificateAuthority: caFile}}, - Contexts: map[string]*Context{ - "federal-context": {AuthInfo: "red-user", Cluster: "cow-cluster"}, - "shaker-context": {AuthInfo: "blue-user", Cluster: "chicken-cluster"}}, - CurrentContext: "federal-context", - } -} - -func TestMinifySuccess(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) - - if err := MinifyConfig(&mutatingConfig); err != nil { - t.Errorf("unexpected error: %v", err) - } - - if len(mutatingConfig.Contexts) > 1 { - t.Errorf("unexpected contexts: %v", mutatingConfig.Contexts) - } - if _, exists := mutatingConfig.Contexts["federal-context"]; !exists { - t.Errorf("missing context") - } - - if len(mutatingConfig.Clusters) > 1 { - t.Errorf("unexpected clusters: %v", mutatingConfig.Clusters) - } - if _, exists := mutatingConfig.Clusters["cow-cluster"]; !exists { - t.Errorf("missing cluster") - } - - if len(mutatingConfig.AuthInfos) > 1 { - t.Errorf("unexpected users: %v", mutatingConfig.AuthInfos) - } - if _, exists := mutatingConfig.AuthInfos["red-user"]; !exists { - t.Errorf("missing user") - } -} - -func TestMinifyMissingContext(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) - mutatingConfig.CurrentContext = "missing" - - errMsg := "cannot locate context missing" - - if err := MinifyConfig(&mutatingConfig); err == nil || err.Error() != errMsg { - t.Errorf("expected %v, got %v", errMsg, err) - } -} - -func TestMinifyMissingCluster(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) - delete(mutatingConfig.Clusters, mutatingConfig.Contexts[mutatingConfig.CurrentContext].Cluster) - - errMsg := "cannot locate cluster cow-cluster" - - if err := MinifyConfig(&mutatingConfig); err == nil || err.Error() != errMsg { - t.Errorf("expected %v, got %v", errMsg, err) - } -} - -func TestMinifyMissingAuthInfo(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - mutatingConfig := newMergedConfig(certFile.Name(), "cert", keyFile.Name(), "key", caFile.Name(), "ca", t) - delete(mutatingConfig.AuthInfos, mutatingConfig.Contexts[mutatingConfig.CurrentContext].AuthInfo) - - errMsg := "cannot locate user red-user" - - if err := MinifyConfig(&mutatingConfig); err == nil || err.Error() != errMsg { - t.Errorf("expected %v, got %v", errMsg, err) - } -} - -func TestFlattenSuccess(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - certData := "cert" - keyData := "key" - caData := "ca" - - unchangingCluster := "cow-cluster" - unchangingAuthInfo := "red-user" - changingCluster := "chicken-cluster" - changingAuthInfo := "blue-user" - - startingConfig := newMergedConfig(certFile.Name(), certData, keyFile.Name(), keyData, caFile.Name(), caData, t) - mutatingConfig := startingConfig - - if err := FlattenConfig(&mutatingConfig); err != nil { - t.Errorf("unexpected error: %v", err) - } - - if len(mutatingConfig.Contexts) != 2 { - t.Errorf("unexpected contexts: %v", mutatingConfig.Contexts) - } - if !reflect.DeepEqual(startingConfig.Contexts, mutatingConfig.Contexts) { - t.Errorf("expected %v, got %v", startingConfig.Contexts, mutatingConfig.Contexts) - } - - if len(mutatingConfig.Clusters) != 2 { - t.Errorf("unexpected clusters: %v", mutatingConfig.Clusters) - } - if !reflect.DeepEqual(startingConfig.Clusters[unchangingCluster], mutatingConfig.Clusters[unchangingCluster]) { - t.Errorf("expected %v, got %v", startingConfig.Clusters[unchangingCluster], mutatingConfig.Clusters[unchangingCluster]) - } - if len(mutatingConfig.Clusters[changingCluster].CertificateAuthority) != 0 { - t.Errorf("unexpected caFile") - } - if string(mutatingConfig.Clusters[changingCluster].CertificateAuthorityData) != caData { - t.Errorf("expected %v, got %v", caData, string(mutatingConfig.Clusters[changingCluster].CertificateAuthorityData)) - } - - if len(mutatingConfig.AuthInfos) != 2 { - t.Errorf("unexpected users: %v", mutatingConfig.AuthInfos) - } - if !reflect.DeepEqual(startingConfig.AuthInfos[unchangingAuthInfo], mutatingConfig.AuthInfos[unchangingAuthInfo]) { - t.Errorf("expected %v, got %v", startingConfig.AuthInfos[unchangingAuthInfo], mutatingConfig.AuthInfos[unchangingAuthInfo]) - } - if len(mutatingConfig.AuthInfos[changingAuthInfo].ClientCertificate) != 0 { - t.Errorf("unexpected caFile") - } - if string(mutatingConfig.AuthInfos[changingAuthInfo].ClientCertificateData) != certData { - t.Errorf("expected %v, got %v", certData, string(mutatingConfig.AuthInfos[changingAuthInfo].ClientCertificateData)) - } - if len(mutatingConfig.AuthInfos[changingAuthInfo].ClientKey) != 0 { - t.Errorf("unexpected caFile") - } - if string(mutatingConfig.AuthInfos[changingAuthInfo].ClientKeyData) != keyData { - t.Errorf("expected %v, got %v", keyData, string(mutatingConfig.AuthInfos[changingAuthInfo].ClientKeyData)) - } - -} - -func Example_minifyAndShorten() { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - certData := "cert" - keyData := "key" - caData := "ca" - - config := newMergedConfig(certFile.Name(), certData, keyFile.Name(), keyData, caFile.Name(), caData, nil) - - MinifyConfig(&config) - ShortenConfig(&config) - - output, _ := yaml.Marshal(config) - fmt.Printf("%s", string(output)) - // Output: - // clusters: - // cow-cluster: - // LocationOfOrigin: "" - // certificate-authority-data: REDACTED - // server: http://cow.org:8080 - // contexts: - // federal-context: - // LocationOfOrigin: "" - // cluster: cow-cluster - // user: red-user - // current-context: federal-context - // preferences: {} - // users: - // red-user: - // LocationOfOrigin: "" - // client-certificate-data: REDACTED - // client-key-data: REDACTED - // token: red-token -} - -func TestShortenSuccess(t *testing.T) { - certFile, _ := ioutil.TempFile("", "") - defer os.Remove(certFile.Name()) - keyFile, _ := ioutil.TempFile("", "") - defer os.Remove(keyFile.Name()) - caFile, _ := ioutil.TempFile("", "") - defer os.Remove(caFile.Name()) - - certData := "cert" - keyData := "key" - caData := "ca" - - unchangingCluster := "chicken-cluster" - unchangingAuthInfo := "blue-user" - changingCluster := "cow-cluster" - changingAuthInfo := "red-user" - - startingConfig := newMergedConfig(certFile.Name(), certData, keyFile.Name(), keyData, caFile.Name(), caData, t) - mutatingConfig := startingConfig - - ShortenConfig(&mutatingConfig) - - if len(mutatingConfig.Contexts) != 2 { - t.Errorf("unexpected contexts: %v", mutatingConfig.Contexts) - } - if !reflect.DeepEqual(startingConfig.Contexts, mutatingConfig.Contexts) { - t.Errorf("expected %v, got %v", startingConfig.Contexts, mutatingConfig.Contexts) - } - - redacted := string(redactedBytes) - if len(mutatingConfig.Clusters) != 2 { - t.Errorf("unexpected clusters: %v", mutatingConfig.Clusters) - } - if !reflect.DeepEqual(startingConfig.Clusters[unchangingCluster], mutatingConfig.Clusters[unchangingCluster]) { - t.Errorf("expected %v, got %v", startingConfig.Clusters[unchangingCluster], mutatingConfig.Clusters[unchangingCluster]) - } - if string(mutatingConfig.Clusters[changingCluster].CertificateAuthorityData) != redacted { - t.Errorf("expected %v, got %v", redacted, string(mutatingConfig.Clusters[changingCluster].CertificateAuthorityData)) - } - - if len(mutatingConfig.AuthInfos) != 2 { - t.Errorf("unexpected users: %v", mutatingConfig.AuthInfos) - } - if !reflect.DeepEqual(startingConfig.AuthInfos[unchangingAuthInfo], mutatingConfig.AuthInfos[unchangingAuthInfo]) { - t.Errorf("expected %v, got %v", startingConfig.AuthInfos[unchangingAuthInfo], mutatingConfig.AuthInfos[unchangingAuthInfo]) - } - if string(mutatingConfig.AuthInfos[changingAuthInfo].ClientCertificateData) != redacted { - t.Errorf("expected %v, got %v", redacted, string(mutatingConfig.AuthInfos[changingAuthInfo].ClientCertificateData)) - } - if string(mutatingConfig.AuthInfos[changingAuthInfo].ClientKeyData) != redacted { - t.Errorf("expected %v, got %v", redacted, string(mutatingConfig.AuthInfos[changingAuthInfo].ClientKeyData)) - } -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/api/types_test.go b/vendor/k8s.io/client-go/tools/clientcmd/api/types_test.go deleted file mode 100644 index bd34834521..0000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/api/types_test.go +++ /dev/null @@ -1,135 +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 api - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -func Example_emptyConfig() { - defaultConfig := NewConfig() - - output, err := yaml.Marshal(defaultConfig) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - - fmt.Printf("%v", string(output)) - // Output: - // clusters: {} - // contexts: {} - // current-context: "" - // preferences: {} - // users: {} -} - -func Example_ofOptionsConfig() { - defaultConfig := NewConfig() - defaultConfig.Preferences.Colors = true - defaultConfig.Clusters["alfa"] = &Cluster{ - Server: "https://alfa.org:8080", - InsecureSkipTLSVerify: true, - CertificateAuthority: "path/to/my/cert-ca-filename", - } - defaultConfig.Clusters["bravo"] = &Cluster{ - Server: "https://bravo.org:8080", - InsecureSkipTLSVerify: false, - } - defaultConfig.AuthInfos["white-mage-via-cert"] = &AuthInfo{ - ClientCertificate: "path/to/my/client-cert-filename", - ClientKey: "path/to/my/client-key-filename", - } - defaultConfig.AuthInfos["red-mage-via-token"] = &AuthInfo{ - Token: "my-secret-token", - } - defaultConfig.AuthInfos["black-mage-via-auth-provider"] = &AuthInfo{ - AuthProvider: &AuthProviderConfig{ - Name: "gcp", - Config: map[string]string{ - "foo": "bar", - "token": "s3cr3t-t0k3n", - }, - }, - } - defaultConfig.Contexts["bravo-as-black-mage"] = &Context{ - Cluster: "bravo", - AuthInfo: "black-mage-via-auth-provider", - Namespace: "yankee", - } - defaultConfig.Contexts["alfa-as-black-mage"] = &Context{ - Cluster: "alfa", - AuthInfo: "black-mage-via-auth-provider", - Namespace: "zulu", - } - defaultConfig.Contexts["alfa-as-white-mage"] = &Context{ - Cluster: "alfa", - AuthInfo: "white-mage-via-cert", - } - defaultConfig.CurrentContext = "alfa-as-white-mage" - - output, err := yaml.Marshal(defaultConfig) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - - fmt.Printf("%v", string(output)) - // Output: - // clusters: - // alfa: - // LocationOfOrigin: "" - // certificate-authority: path/to/my/cert-ca-filename - // insecure-skip-tls-verify: true - // server: https://alfa.org:8080 - // bravo: - // LocationOfOrigin: "" - // server: https://bravo.org:8080 - // contexts: - // alfa-as-black-mage: - // LocationOfOrigin: "" - // cluster: alfa - // namespace: zulu - // user: black-mage-via-auth-provider - // alfa-as-white-mage: - // LocationOfOrigin: "" - // cluster: alfa - // user: white-mage-via-cert - // bravo-as-black-mage: - // LocationOfOrigin: "" - // cluster: bravo - // namespace: yankee - // user: black-mage-via-auth-provider - // current-context: alfa-as-white-mage - // preferences: - // colors: true - // users: - // black-mage-via-auth-provider: - // LocationOfOrigin: "" - // auth-provider: - // config: - // foo: bar - // token: s3cr3t-t0k3n - // name: gcp - // red-mage-via-token: - // LocationOfOrigin: "" - // token: my-secret-token - // white-mage-via-cert: - // LocationOfOrigin: "" - // client-certificate: path/to/my/client-cert-filename - // client-key: path/to/my/client-key-filename -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/client_config_test.go b/vendor/k8s.io/client-go/tools/clientcmd/client_config_test.go deleted file mode 100644 index 0a9288bcf9..0000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/client_config_test.go +++ /dev/null @@ -1,528 +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 clientcmd - -import ( - "io/ioutil" - "os" - "reflect" - "strings" - "testing" - - "github.com/imdario/mergo" - restclient "k8s.io/client-go/rest" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -func TestOldMergoLib(t *testing.T) { - type T struct { - X string - } - dst := T{X: "one"} - src := T{X: "two"} - mergo.Merge(&dst, &src) - if dst.X != "two" { - // mergo.Merge changed in an incompatible way with - // - // https://github.com/imdario/mergo/commit/d304790b2ed594794496464fadd89d2bb266600a - // - // We have to stay with the old version which still does eager - // copying from src to dst in structs. - t.Errorf("mergo.Merge library found with incompatible, new behavior") - } -} - -func createValidTestConfig() *clientcmdapi.Config { - const ( - server = "https://anything.com:8080" - token = "the-token" - ) - - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: server, - } - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - Token: token, - } - config.Contexts["clean"] = &clientcmdapi.Context{ - Cluster: "clean", - AuthInfo: "clean", - } - config.CurrentContext = "clean" - - return config -} - -func createCAValidTestConfig() *clientcmdapi.Config { - - config := createValidTestConfig() - config.Clusters["clean"].CertificateAuthorityData = []byte{0, 0} - return config -} - -func TestInsecureOverridesCA(t *testing.T) { - config := createCAValidTestConfig() - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{ - ClusterInfo: clientcmdapi.Cluster{ - InsecureSkipTLSVerify: true, - }, - }, nil) - - actualCfg, err := clientBuilder.ClientConfig() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - matchBoolArg(true, actualCfg.Insecure, t) - matchStringArg("", actualCfg.TLSClientConfig.CAFile, t) - matchByteArg(nil, actualCfg.TLSClientConfig.CAData, t) -} - -func TestMergeContext(t *testing.T) { - const namespace = "overridden-namespace" - - config := createValidTestConfig() - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}, nil) - - _, overridden, err := clientBuilder.Namespace() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if overridden { - t.Error("Expected namespace to not be overridden") - } - - clientBuilder = NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{ - Context: clientcmdapi.Context{ - Namespace: namespace, - }, - }, nil) - - actual, overridden, err := clientBuilder.Namespace() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if !overridden { - t.Error("Expected namespace to be overridden") - } - - matchStringArg(namespace, actual, t) -} - -func TestCertificateData(t *testing.T) { - caData := []byte("ca-data") - certData := []byte("cert-data") - keyData := []byte("key-data") - - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "https://localhost:8443", - CertificateAuthorityData: caData, - } - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - ClientCertificateData: certData, - ClientKeyData: keyData, - } - config.Contexts["clean"] = &clientcmdapi.Context{ - Cluster: "clean", - AuthInfo: "clean", - } - config.CurrentContext = "clean" - - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}, nil) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - // Make sure cert data gets into config (will override file paths) - matchByteArg(caData, clientConfig.TLSClientConfig.CAData, t) - matchByteArg(certData, clientConfig.TLSClientConfig.CertData, t) - matchByteArg(keyData, clientConfig.TLSClientConfig.KeyData, t) -} - -func TestBasicAuthData(t *testing.T) { - username := "myuser" - password := "mypass" - - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "https://localhost:8443", - } - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - Username: username, - Password: password, - } - config.Contexts["clean"] = &clientcmdapi.Context{ - Cluster: "clean", - AuthInfo: "clean", - } - config.CurrentContext = "clean" - - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}, nil) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - // Make sure basic auth data gets into config - matchStringArg(username, clientConfig.Username, t) - matchStringArg(password, clientConfig.Password, t) -} - -func TestBasicTokenFile(t *testing.T) { - token := "exampletoken" - f, err := ioutil.TempFile("", "tokenfile") - if err != nil { - t.Errorf("Unexpected error: %v", err) - return - } - defer os.Remove(f.Name()) - if err := ioutil.WriteFile(f.Name(), []byte(token), 0644); err != nil { - t.Errorf("Unexpected error: %v", err) - return - } - - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "https://localhost:8443", - } - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - TokenFile: f.Name(), - } - config.Contexts["clean"] = &clientcmdapi.Context{ - Cluster: "clean", - AuthInfo: "clean", - } - config.CurrentContext = "clean" - - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}, nil) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - matchStringArg(token, clientConfig.BearerToken, t) -} - -func TestPrecedenceTokenFile(t *testing.T) { - token := "exampletoken" - f, err := ioutil.TempFile("", "tokenfile") - if err != nil { - t.Errorf("Unexpected error: %v", err) - return - } - defer os.Remove(f.Name()) - if err := ioutil.WriteFile(f.Name(), []byte(token), 0644); err != nil { - t.Errorf("Unexpected error: %v", err) - return - } - - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "https://localhost:8443", - } - expectedToken := "expected" - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - Token: expectedToken, - TokenFile: f.Name(), - } - config.Contexts["clean"] = &clientcmdapi.Context{ - Cluster: "clean", - AuthInfo: "clean", - } - config.CurrentContext = "clean" - - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}, nil) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - matchStringArg(expectedToken, clientConfig.BearerToken, t) -} - -func TestCreateClean(t *testing.T) { - config := createValidTestConfig() - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{}, nil) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - matchStringArg(config.Clusters["clean"].Server, clientConfig.Host, t) - matchStringArg("", clientConfig.APIPath, t) - matchBoolArg(config.Clusters["clean"].InsecureSkipTLSVerify, clientConfig.Insecure, t) - matchStringArg(config.AuthInfos["clean"].Token, clientConfig.BearerToken, t) -} - -func TestCreateCleanWithPrefix(t *testing.T) { - tt := []struct { - server string - host string - }{ - {"https://anything.com:8080/foo/bar", "https://anything.com:8080/foo/bar"}, - {"http://anything.com:8080/foo/bar", "http://anything.com:8080/foo/bar"}, - {"http://anything.com:8080/foo/bar/", "http://anything.com:8080/foo/bar/"}, - {"http://anything.com:8080/", "http://anything.com:8080/"}, - {"http://anything.com:8080//", "http://anything.com:8080//"}, - {"anything.com:8080/foo/bar", "anything.com:8080/foo/bar"}, - {"anything.com:8080", "anything.com:8080"}, - {"anything.com", "anything.com"}, - {"anything", "anything"}, - } - - tt = append(tt, struct{ server, host string }{"", "http://localhost:8080"}) - - for _, tc := range tt { - config := createValidTestConfig() - - cleanConfig := config.Clusters["clean"] - cleanConfig.Server = tc.server - config.Clusters["clean"] = cleanConfig - - clientBuilder := NewNonInteractiveClientConfig(*config, "clean", &ConfigOverrides{ - ClusterDefaults: clientcmdapi.Cluster{Server: "http://localhost:8080"}, - }, nil) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - matchStringArg(tc.host, clientConfig.Host, t) - } -} - -func TestCreateCleanDefault(t *testing.T) { - config := createValidTestConfig() - clientBuilder := NewDefaultClientConfig(*config, &ConfigOverrides{}) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - matchStringArg(config.Clusters["clean"].Server, clientConfig.Host, t) - matchBoolArg(config.Clusters["clean"].InsecureSkipTLSVerify, clientConfig.Insecure, t) - matchStringArg(config.AuthInfos["clean"].Token, clientConfig.BearerToken, t) -} - -func TestCreateCleanDefaultCluster(t *testing.T) { - config := createValidTestConfig() - clientBuilder := NewDefaultClientConfig(*config, &ConfigOverrides{ - ClusterDefaults: clientcmdapi.Cluster{Server: "http://localhost:8080"}, - }) - - clientConfig, err := clientBuilder.ClientConfig() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - matchStringArg(config.Clusters["clean"].Server, clientConfig.Host, t) - matchBoolArg(config.Clusters["clean"].InsecureSkipTLSVerify, clientConfig.Insecure, t) - matchStringArg(config.AuthInfos["clean"].Token, clientConfig.BearerToken, t) -} - -func TestCreateMissingContextNoDefault(t *testing.T) { - const expectedErrorContains = "Context was not found for specified context" - config := createValidTestConfig() - clientBuilder := NewNonInteractiveClientConfig(*config, "not-present", &ConfigOverrides{}, nil) - - _, err := clientBuilder.ClientConfig() - if err == nil { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestCreateMissingContext(t *testing.T) { - const expectedErrorContains = "context was not found for specified context: not-present" - config := createValidTestConfig() - clientBuilder := NewNonInteractiveClientConfig(*config, "not-present", &ConfigOverrides{ - ClusterDefaults: clientcmdapi.Cluster{Server: "http://localhost:8080"}, - }, nil) - - _, err := clientBuilder.ClientConfig() - if err == nil { - t.Fatalf("Expected error: %v", expectedErrorContains) - } - if !strings.Contains(err.Error(), expectedErrorContains) { - t.Fatalf("Expected error: %v, but got %v", expectedErrorContains, err) - } -} - -func TestInClusterClientConfigPrecedence(t *testing.T) { - tt := []struct { - overrides *ConfigOverrides - }{ - { - overrides: &ConfigOverrides{ - ClusterInfo: clientcmdapi.Cluster{ - Server: "https://host-from-overrides.com", - }, - }, - }, - { - overrides: &ConfigOverrides{ - AuthInfo: clientcmdapi.AuthInfo{ - Token: "https://host-from-overrides.com", - }, - }, - }, - { - overrides: &ConfigOverrides{ - ClusterInfo: clientcmdapi.Cluster{ - CertificateAuthority: "/path/to/ca-from-overrides.crt", - }, - }, - }, - { - overrides: &ConfigOverrides{ - ClusterInfo: clientcmdapi.Cluster{ - Server: "https://host-from-overrides.com", - }, - AuthInfo: clientcmdapi.AuthInfo{ - Token: "https://host-from-overrides.com", - }, - }, - }, - { - overrides: &ConfigOverrides{ - ClusterInfo: clientcmdapi.Cluster{ - Server: "https://host-from-overrides.com", - CertificateAuthority: "/path/to/ca-from-overrides.crt", - }, - }, - }, - { - overrides: &ConfigOverrides{ - ClusterInfo: clientcmdapi.Cluster{ - CertificateAuthority: "/path/to/ca-from-overrides.crt", - }, - AuthInfo: clientcmdapi.AuthInfo{ - Token: "https://host-from-overrides.com", - }, - }, - }, - { - overrides: &ConfigOverrides{ - ClusterInfo: clientcmdapi.Cluster{ - Server: "https://host-from-overrides.com", - CertificateAuthority: "/path/to/ca-from-overrides.crt", - }, - AuthInfo: clientcmdapi.AuthInfo{ - Token: "https://host-from-overrides.com", - }, - }, - }, - { - overrides: &ConfigOverrides{}, - }, - } - - for _, tc := range tt { - expectedServer := "https://host-from-cluster.com" - expectedToken := "token-from-cluster" - expectedCAFile := "/path/to/ca-from-cluster.crt" - - icc := &inClusterClientConfig{ - inClusterConfigProvider: func() (*restclient.Config, error) { - return &restclient.Config{ - Host: expectedServer, - BearerToken: expectedToken, - TLSClientConfig: restclient.TLSClientConfig{ - CAFile: expectedCAFile, - }, - }, nil - }, - overrides: tc.overrides, - } - - clientConfig, err := icc.ClientConfig() - if err != nil { - t.Fatalf("Unxpected error: %v", err) - } - - if overridenServer := tc.overrides.ClusterInfo.Server; len(overridenServer) > 0 { - expectedServer = overridenServer - } - if overridenToken := tc.overrides.AuthInfo.Token; len(overridenToken) > 0 { - expectedToken = overridenToken - } - if overridenCAFile := tc.overrides.ClusterInfo.CertificateAuthority; len(overridenCAFile) > 0 { - expectedCAFile = overridenCAFile - } - - if clientConfig.Host != expectedServer { - t.Errorf("Expected server %v, got %v", expectedServer, clientConfig.Host) - } - if clientConfig.BearerToken != expectedToken { - t.Errorf("Expected token %v, got %v", expectedToken, clientConfig.BearerToken) - } - if clientConfig.TLSClientConfig.CAFile != expectedCAFile { - t.Errorf("Expected Certificate Authority %v, got %v", expectedCAFile, clientConfig.TLSClientConfig.CAFile) - } - } -} - -func matchBoolArg(expected, got bool, t *testing.T) { - if expected != got { - t.Errorf("Expected %v, got %v", expected, got) - } -} - -func matchStringArg(expected, got string, t *testing.T) { - if expected != got { - t.Errorf("Expected %q, got %q", expected, got) - } -} - -func matchByteArg(expected, got []byte, t *testing.T) { - if !reflect.DeepEqual(expected, got) { - t.Errorf("Expected %v, got %v", expected, got) - } -} - -func TestNamespaceOverride(t *testing.T) { - config := &DirectClientConfig{ - overrides: &ConfigOverrides{ - Context: clientcmdapi.Context{ - Namespace: "foo", - }, - }, - } - - ns, overridden, err := config.Namespace() - - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if !overridden { - t.Errorf("Expected overridden = true") - } - - matchStringArg("foo", ns, t) -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/loader_test.go b/vendor/k8s.io/client-go/tools/clientcmd/loader_test.go deleted file mode 100644 index c2dbd019dd..0000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/loader_test.go +++ /dev/null @@ -1,594 +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 clientcmd - -import ( - "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" - "reflect" - "strings" - "testing" - - "github.com/ghodss/yaml" - - "k8s.io/apimachinery/pkg/runtime" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest" -) - -var ( - testConfigAlfa = clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "red-user": {Token: "red-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "cow-cluster": {Server: "http://cow.org:8080"}}, - Contexts: map[string]*clientcmdapi.Context{ - "federal-context": {AuthInfo: "red-user", Cluster: "cow-cluster", Namespace: "hammer-ns"}}, - } - testConfigBravo = clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "black-user": {Token: "black-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "pig-cluster": {Server: "http://pig.org:8080"}}, - Contexts: map[string]*clientcmdapi.Context{ - "queen-anne-context": {AuthInfo: "black-user", Cluster: "pig-cluster", Namespace: "saw-ns"}}, - } - testConfigCharlie = clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "green-user": {Token: "green-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "horse-cluster": {Server: "http://horse.org:8080"}}, - Contexts: map[string]*clientcmdapi.Context{ - "shaker-context": {AuthInfo: "green-user", Cluster: "horse-cluster", Namespace: "chisel-ns"}}, - } - testConfigDelta = clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "blue-user": {Token: "blue-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "chicken-cluster": {Server: "http://chicken.org:8080"}}, - Contexts: map[string]*clientcmdapi.Context{ - "gothic-context": {AuthInfo: "blue-user", Cluster: "chicken-cluster", Namespace: "plane-ns"}}, - } - - testConfigConflictAlfa = clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "red-user": {Token: "a-different-red-token"}, - "yellow-user": {Token: "yellow-token"}}, - Clusters: map[string]*clientcmdapi.Cluster{ - "cow-cluster": {Server: "http://a-different-cow.org:8080", InsecureSkipTLSVerify: true}, - "donkey-cluster": {Server: "http://donkey.org:8080", InsecureSkipTLSVerify: true}}, - CurrentContext: "federal-context", - } -) - -func TestNonExistentCommandLineFile(t *testing.T) { - loadingRules := ClientConfigLoadingRules{ - ExplicitPath: "bogus_file", - } - - _, err := loadingRules.Load() - if err == nil { - t.Fatalf("Expected error for missing command-line file, got none") - } - if !strings.Contains(err.Error(), "bogus_file") { - t.Fatalf("Expected error about 'bogus_file', got %s", err.Error()) - } -} - -func TestToleratingMissingFiles(t *testing.T) { - loadingRules := ClientConfigLoadingRules{ - Precedence: []string{"bogus1", "bogus2", "bogus3"}, - } - - _, err := loadingRules.Load() - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } -} - -func TestErrorReadingFile(t *testing.T) { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - - if err := ioutil.WriteFile(commandLineFile.Name(), []byte("bogus value"), 0644); err != nil { - t.Fatalf("Error creating tempfile: %v", err) - } - - loadingRules := ClientConfigLoadingRules{ - ExplicitPath: commandLineFile.Name(), - } - - _, err := loadingRules.Load() - if err == nil { - t.Fatalf("Expected error for unloadable file, got none") - } - if !strings.Contains(err.Error(), commandLineFile.Name()) { - t.Fatalf("Expected error about '%s', got %s", commandLineFile.Name(), err.Error()) - } -} - -func TestErrorReadingNonFile(t *testing.T) { - tmpdir, err := ioutil.TempDir("", "") - if err != nil { - t.Fatalf("Couldn't create tmpdir") - } - defer os.RemoveAll(tmpdir) - - loadingRules := ClientConfigLoadingRules{ - ExplicitPath: tmpdir, - } - - _, err = loadingRules.Load() - if err == nil { - t.Fatalf("Expected error for non-file, got none") - } - if !strings.Contains(err.Error(), tmpdir) { - t.Fatalf("Expected error about '%s', got %s", tmpdir, err.Error()) - } -} - -func TestConflictingCurrentContext(t *testing.T) { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") - defer os.Remove(envVarFile.Name()) - - mockCommandLineConfig := clientcmdapi.Config{ - CurrentContext: "any-context-value", - } - mockEnvVarConfig := clientcmdapi.Config{ - CurrentContext: "a-different-context", - } - - WriteToFile(mockCommandLineConfig, commandLineFile.Name()) - WriteToFile(mockEnvVarConfig, envVarFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - ExplicitPath: commandLineFile.Name(), - Precedence: []string{envVarFile.Name()}, - } - - mergedConfig, err := loadingRules.Load() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if mergedConfig.CurrentContext != mockCommandLineConfig.CurrentContext { - t.Errorf("expected %v, got %v", mockCommandLineConfig.CurrentContext, mergedConfig.CurrentContext) - } -} - -func TestLoadingEmptyMaps(t *testing.T) { - configFile, _ := ioutil.TempFile("", "") - defer os.Remove(configFile.Name()) - - mockConfig := clientcmdapi.Config{ - CurrentContext: "any-context-value", - } - - WriteToFile(mockConfig, configFile.Name()) - - config, err := LoadFromFile(configFile.Name()) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - if config.Clusters == nil { - t.Error("expected config.Clusters to be non-nil") - } - if config.AuthInfos == nil { - t.Error("expected config.AuthInfos to be non-nil") - } - if config.Contexts == nil { - t.Error("expected config.Contexts to be non-nil") - } -} - -func TestResolveRelativePaths(t *testing.T) { - pathResolutionConfig1 := clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "relative-user-1": {ClientCertificate: "relative/client/cert", ClientKey: "../relative/client/key"}, - "absolute-user-1": {ClientCertificate: "/absolute/client/cert", ClientKey: "/absolute/client/key"}, - "relative-cmd-1": {Exec: &clientcmdapi.ExecConfig{Command: "../relative/client/cmd"}}, - "absolute-cmd-1": {Exec: &clientcmdapi.ExecConfig{Command: "/absolute/client/cmd"}}, - "PATH-cmd-1": {Exec: &clientcmdapi.ExecConfig{Command: "cmd"}}, - }, - Clusters: map[string]*clientcmdapi.Cluster{ - "relative-server-1": {CertificateAuthority: "../relative/ca"}, - "absolute-server-1": {CertificateAuthority: "/absolute/ca"}, - }, - } - pathResolutionConfig2 := clientcmdapi.Config{ - AuthInfos: map[string]*clientcmdapi.AuthInfo{ - "relative-user-2": {ClientCertificate: "relative/client/cert2", ClientKey: "../relative/client/key2"}, - "absolute-user-2": {ClientCertificate: "/absolute/client/cert2", ClientKey: "/absolute/client/key2"}, - }, - Clusters: map[string]*clientcmdapi.Cluster{ - "relative-server-2": {CertificateAuthority: "../relative/ca2"}, - "absolute-server-2": {CertificateAuthority: "/absolute/ca2"}, - }, - } - - configDir1, _ := ioutil.TempDir("", "") - defer os.RemoveAll(configDir1) - configFile1 := path.Join(configDir1, ".kubeconfig") - configDir1, _ = filepath.Abs(configDir1) - - configDir2, _ := ioutil.TempDir("", "") - defer os.RemoveAll(configDir2) - configDir2, _ = ioutil.TempDir(configDir2, "") - configFile2 := path.Join(configDir2, ".kubeconfig") - configDir2, _ = filepath.Abs(configDir2) - - WriteToFile(pathResolutionConfig1, configFile1) - WriteToFile(pathResolutionConfig2, configFile2) - - loadingRules := ClientConfigLoadingRules{ - Precedence: []string{configFile1, configFile2}, - } - - mergedConfig, err := loadingRules.Load() - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - - foundClusterCount := 0 - for key, cluster := range mergedConfig.Clusters { - if key == "relative-server-1" { - foundClusterCount++ - matchStringArg(path.Join(configDir1, pathResolutionConfig1.Clusters["relative-server-1"].CertificateAuthority), cluster.CertificateAuthority, t) - } - if key == "relative-server-2" { - foundClusterCount++ - matchStringArg(path.Join(configDir2, pathResolutionConfig2.Clusters["relative-server-2"].CertificateAuthority), cluster.CertificateAuthority, t) - } - if key == "absolute-server-1" { - foundClusterCount++ - matchStringArg(pathResolutionConfig1.Clusters["absolute-server-1"].CertificateAuthority, cluster.CertificateAuthority, t) - } - if key == "absolute-server-2" { - foundClusterCount++ - matchStringArg(pathResolutionConfig2.Clusters["absolute-server-2"].CertificateAuthority, cluster.CertificateAuthority, t) - } - } - if foundClusterCount != 4 { - t.Errorf("Expected 4 clusters, found %v: %v", foundClusterCount, mergedConfig.Clusters) - } - - foundAuthInfoCount := 0 - for key, authInfo := range mergedConfig.AuthInfos { - if key == "relative-user-1" { - foundAuthInfoCount++ - matchStringArg(path.Join(configDir1, pathResolutionConfig1.AuthInfos["relative-user-1"].ClientCertificate), authInfo.ClientCertificate, t) - matchStringArg(path.Join(configDir1, pathResolutionConfig1.AuthInfos["relative-user-1"].ClientKey), authInfo.ClientKey, t) - } - if key == "relative-user-2" { - foundAuthInfoCount++ - matchStringArg(path.Join(configDir2, pathResolutionConfig2.AuthInfos["relative-user-2"].ClientCertificate), authInfo.ClientCertificate, t) - matchStringArg(path.Join(configDir2, pathResolutionConfig2.AuthInfos["relative-user-2"].ClientKey), authInfo.ClientKey, t) - } - if key == "absolute-user-1" { - foundAuthInfoCount++ - matchStringArg(pathResolutionConfig1.AuthInfos["absolute-user-1"].ClientCertificate, authInfo.ClientCertificate, t) - matchStringArg(pathResolutionConfig1.AuthInfos["absolute-user-1"].ClientKey, authInfo.ClientKey, t) - } - if key == "absolute-user-2" { - foundAuthInfoCount++ - matchStringArg(pathResolutionConfig2.AuthInfos["absolute-user-2"].ClientCertificate, authInfo.ClientCertificate, t) - matchStringArg(pathResolutionConfig2.AuthInfos["absolute-user-2"].ClientKey, authInfo.ClientKey, t) - } - if key == "relative-cmd-1" { - foundAuthInfoCount++ - matchStringArg(path.Join(configDir1, pathResolutionConfig1.AuthInfos[key].Exec.Command), authInfo.Exec.Command, t) - } - if key == "absolute-cmd-1" { - foundAuthInfoCount++ - matchStringArg(pathResolutionConfig1.AuthInfos[key].Exec.Command, authInfo.Exec.Command, t) - } - if key == "PATH-cmd-1" { - foundAuthInfoCount++ - matchStringArg(pathResolutionConfig1.AuthInfos[key].Exec.Command, authInfo.Exec.Command, t) - } - } - if foundAuthInfoCount != 7 { - t.Errorf("Expected 7 users, found %v: %v", foundAuthInfoCount, mergedConfig.AuthInfos) - } - -} - -func TestMigratingFile(t *testing.T) { - sourceFile, _ := ioutil.TempFile("", "") - defer os.Remove(sourceFile.Name()) - destinationFile, _ := ioutil.TempFile("", "") - // delete the file so that we'll write to it - os.Remove(destinationFile.Name()) - - WriteToFile(testConfigAlfa, sourceFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - MigrationRules: map[string]string{destinationFile.Name(): sourceFile.Name()}, - } - - if _, err := loadingRules.Load(); err != nil { - t.Errorf("unexpected error %v", err) - } - - // the load should have recreated this file - defer os.Remove(destinationFile.Name()) - - sourceContent, err := ioutil.ReadFile(sourceFile.Name()) - if err != nil { - t.Errorf("unexpected error %v", err) - } - destinationContent, err := ioutil.ReadFile(destinationFile.Name()) - if err != nil { - t.Errorf("unexpected error %v", err) - } - - if !reflect.DeepEqual(sourceContent, destinationContent) { - t.Errorf("source and destination do not match") - } -} - -func TestMigratingFileLeaveExistingFileAlone(t *testing.T) { - sourceFile, _ := ioutil.TempFile("", "") - defer os.Remove(sourceFile.Name()) - destinationFile, _ := ioutil.TempFile("", "") - defer os.Remove(destinationFile.Name()) - - WriteToFile(testConfigAlfa, sourceFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - MigrationRules: map[string]string{destinationFile.Name(): sourceFile.Name()}, - } - - if _, err := loadingRules.Load(); err != nil { - t.Errorf("unexpected error %v", err) - } - - destinationContent, err := ioutil.ReadFile(destinationFile.Name()) - if err != nil { - t.Errorf("unexpected error %v", err) - } - - if len(destinationContent) > 0 { - t.Errorf("destination should not have been touched") - } -} - -func TestMigratingFileSourceMissingSkip(t *testing.T) { - sourceFilename := "some-missing-file" - destinationFile, _ := ioutil.TempFile("", "") - // delete the file so that we'll write to it - os.Remove(destinationFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - MigrationRules: map[string]string{destinationFile.Name(): sourceFilename}, - } - - if _, err := loadingRules.Load(); err != nil { - t.Errorf("unexpected error %v", err) - } - - if _, err := os.Stat(destinationFile.Name()); !os.IsNotExist(err) { - t.Errorf("destination should not exist") - } -} - -func TestFileLocking(t *testing.T) { - f, _ := ioutil.TempFile("", "") - defer os.Remove(f.Name()) - - err := lockFile(f.Name()) - if err != nil { - t.Errorf("unexpected error while locking file: %v", err) - } - defer unlockFile(f.Name()) - - err = lockFile(f.Name()) - if err == nil { - t.Error("expected error while locking file.") - } -} - -func Example_noMergingOnExplicitPaths() { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") - defer os.Remove(envVarFile.Name()) - - WriteToFile(testConfigAlfa, commandLineFile.Name()) - WriteToFile(testConfigConflictAlfa, envVarFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - ExplicitPath: commandLineFile.Name(), - Precedence: []string{envVarFile.Name()}, - } - - mergedConfig, err := loadingRules.Load() - - json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - output, err := yaml.JSONToYAML(json) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - - fmt.Printf("%v", string(output)) - // Output: - // apiVersion: v1 - // clusters: - // - cluster: - // server: http://cow.org:8080 - // name: cow-cluster - // contexts: - // - context: - // cluster: cow-cluster - // namespace: hammer-ns - // user: red-user - // name: federal-context - // current-context: "" - // kind: Config - // preferences: {} - // users: - // - name: red-user - // user: - // token: red-token -} - -func Example_mergingSomeWithConflict() { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") - defer os.Remove(envVarFile.Name()) - - WriteToFile(testConfigAlfa, commandLineFile.Name()) - WriteToFile(testConfigConflictAlfa, envVarFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - Precedence: []string{commandLineFile.Name(), envVarFile.Name()}, - } - - mergedConfig, err := loadingRules.Load() - - json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - output, err := yaml.JSONToYAML(json) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - - fmt.Printf("%v", string(output)) - // Output: - // apiVersion: v1 - // clusters: - // - cluster: - // server: http://cow.org:8080 - // name: cow-cluster - // - cluster: - // insecure-skip-tls-verify: true - // server: http://donkey.org:8080 - // name: donkey-cluster - // contexts: - // - context: - // cluster: cow-cluster - // namespace: hammer-ns - // user: red-user - // name: federal-context - // current-context: federal-context - // kind: Config - // preferences: {} - // users: - // - name: red-user - // user: - // token: red-token - // - name: yellow-user - // user: - // token: yellow-token -} - -func Example_mergingEverythingNoConflicts() { - commandLineFile, _ := ioutil.TempFile("", "") - defer os.Remove(commandLineFile.Name()) - envVarFile, _ := ioutil.TempFile("", "") - defer os.Remove(envVarFile.Name()) - currentDirFile, _ := ioutil.TempFile("", "") - defer os.Remove(currentDirFile.Name()) - homeDirFile, _ := ioutil.TempFile("", "") - defer os.Remove(homeDirFile.Name()) - - WriteToFile(testConfigAlfa, commandLineFile.Name()) - WriteToFile(testConfigBravo, envVarFile.Name()) - WriteToFile(testConfigCharlie, currentDirFile.Name()) - WriteToFile(testConfigDelta, homeDirFile.Name()) - - loadingRules := ClientConfigLoadingRules{ - Precedence: []string{commandLineFile.Name(), envVarFile.Name(), currentDirFile.Name(), homeDirFile.Name()}, - } - - mergedConfig, err := loadingRules.Load() - - json, err := runtime.Encode(clientcmdlatest.Codec, mergedConfig) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - output, err := yaml.JSONToYAML(json) - if err != nil { - fmt.Printf("Unexpected error: %v", err) - } - - fmt.Printf("%v", string(output)) - // Output: - // apiVersion: v1 - // clusters: - // - cluster: - // server: http://chicken.org:8080 - // name: chicken-cluster - // - cluster: - // server: http://cow.org:8080 - // name: cow-cluster - // - cluster: - // server: http://horse.org:8080 - // name: horse-cluster - // - cluster: - // server: http://pig.org:8080 - // name: pig-cluster - // contexts: - // - context: - // cluster: cow-cluster - // namespace: hammer-ns - // user: red-user - // name: federal-context - // - context: - // cluster: chicken-cluster - // namespace: plane-ns - // user: blue-user - // name: gothic-context - // - context: - // cluster: pig-cluster - // namespace: saw-ns - // user: black-user - // name: queen-anne-context - // - context: - // cluster: horse-cluster - // namespace: chisel-ns - // user: green-user - // name: shaker-context - // current-context: "" - // kind: Config - // preferences: {} - // users: - // - name: black-user - // user: - // token: black-token - // - name: blue-user - // user: - // token: blue-token - // - name: green-user - // user: - // token: green-token - // - name: red-user - // user: - // token: red-token -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder_test.go b/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder_test.go deleted file mode 100644 index 8b0386764d..0000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/merged_client_builder_test.go +++ /dev/null @@ -1,328 +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 clientcmd - -import ( - "fmt" - "testing" - - restclient "k8s.io/client-go/rest" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -type testLoader struct { - ClientConfigLoader - - called bool - config *clientcmdapi.Config - err error -} - -func (l *testLoader) Load() (*clientcmdapi.Config, error) { - l.called = true - return l.config, l.err -} - -type testClientConfig struct { - config *restclient.Config - namespace string - namespaceSpecified bool - err error -} - -func (c *testClientConfig) RawConfig() (clientcmdapi.Config, error) { - return clientcmdapi.Config{}, fmt.Errorf("unexpected call") -} -func (c *testClientConfig) ClientConfig() (*restclient.Config, error) { - return c.config, c.err -} -func (c *testClientConfig) Namespace() (string, bool, error) { - return c.namespace, c.namespaceSpecified, c.err -} -func (c *testClientConfig) ConfigAccess() ConfigAccess { - return nil -} - -type testICC struct { - testClientConfig - - possible bool - called bool -} - -func (icc *testICC) Possible() bool { - icc.called = true - return icc.possible -} - -func TestInClusterConfig(t *testing.T) { - default1 := &DirectClientConfig{ - config: *createValidTestConfig(), - contextName: "clean", - overrides: &ConfigOverrides{}, - } - invalidDefaultConfig := clientcmdapi.NewConfig() - invalidDefaultConfig.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "http://localhost:8080", - } - invalidDefaultConfig.Contexts["other"] = &clientcmdapi.Context{ - Cluster: "clean", - } - invalidDefaultConfig.CurrentContext = "clean" - - defaultInvalid := &DirectClientConfig{ - config: *invalidDefaultConfig, - overrides: &ConfigOverrides{}, - } - if _, err := defaultInvalid.ClientConfig(); err == nil || !IsConfigurationInvalid(err) { - t.Fatal(err) - } - config1, err := default1.ClientConfig() - if err != nil { - t.Fatal(err) - } - config2 := &restclient.Config{Host: "config2"} - err1 := fmt.Errorf("unique error") - - testCases := map[string]struct { - clientConfig *testClientConfig - icc *testICC - defaultConfig *DirectClientConfig - - checkedICC bool - result *restclient.Config - err error - }{ - "in-cluster checked on other error": { - clientConfig: &testClientConfig{err: ErrEmptyConfig}, - icc: &testICC{}, - - checkedICC: true, - result: nil, - err: ErrEmptyConfig, - }, - - "in-cluster not checked on non-empty error": { - clientConfig: &testClientConfig{err: ErrEmptyCluster}, - icc: &testICC{}, - - checkedICC: false, - result: nil, - err: ErrEmptyCluster, - }, - - "in-cluster checked when config is default": { - defaultConfig: default1, - clientConfig: &testClientConfig{config: config1}, - icc: &testICC{}, - - checkedICC: true, - result: config1, - err: nil, - }, - - "in-cluster not checked when default config is invalid": { - defaultConfig: defaultInvalid, - clientConfig: &testClientConfig{config: config1}, - icc: &testICC{}, - - checkedICC: false, - result: config1, - err: nil, - }, - - "in-cluster not checked when config is not equal to default": { - defaultConfig: default1, - clientConfig: &testClientConfig{config: config2}, - icc: &testICC{}, - - checkedICC: false, - result: config2, - err: nil, - }, - - "in-cluster checked when config is not equal to default and error is empty": { - clientConfig: &testClientConfig{config: config2, err: ErrEmptyConfig}, - icc: &testICC{}, - - checkedICC: true, - result: config2, - err: ErrEmptyConfig, - }, - - "in-cluster error returned when config is empty": { - clientConfig: &testClientConfig{err: ErrEmptyConfig}, - icc: &testICC{ - possible: true, - testClientConfig: testClientConfig{ - err: err1, - }, - }, - - checkedICC: true, - result: nil, - err: err1, - }, - - "in-cluster config returned when config is empty": { - clientConfig: &testClientConfig{err: ErrEmptyConfig}, - icc: &testICC{ - possible: true, - testClientConfig: testClientConfig{ - config: config2, - }, - }, - - checkedICC: true, - result: config2, - err: nil, - }, - - "in-cluster not checked when standard default is invalid": { - defaultConfig: &DefaultClientConfig, - clientConfig: &testClientConfig{config: config2}, - icc: &testICC{}, - - checkedICC: false, - result: config2, - err: nil, - }, - } - - for name, test := range testCases { - c := &DeferredLoadingClientConfig{icc: test.icc} - c.loader = &ClientConfigLoadingRules{DefaultClientConfig: test.defaultConfig} - c.clientConfig = test.clientConfig - - cfg, err := c.ClientConfig() - if test.icc.called != test.checkedICC { - t.Errorf("%s: unexpected in-cluster-config call %t", name, test.icc.called) - } - if err != test.err || cfg != test.result { - t.Errorf("%s: unexpected result: %v %#v", name, err, cfg) - } - } -} - -func TestInClusterConfigNamespace(t *testing.T) { - err1 := fmt.Errorf("unique error") - - testCases := map[string]struct { - clientConfig *testClientConfig - icc *testICC - - checkedICC bool - result string - ok bool - err error - }{ - "in-cluster checked on empty error": { - clientConfig: &testClientConfig{err: ErrEmptyConfig}, - icc: &testICC{}, - - checkedICC: true, - err: ErrEmptyConfig, - }, - - "in-cluster not checked on non-empty error": { - clientConfig: &testClientConfig{err: ErrEmptyCluster}, - icc: &testICC{}, - - err: ErrEmptyCluster, - }, - - "in-cluster checked when config is default": { - clientConfig: &testClientConfig{}, - icc: &testICC{}, - - checkedICC: true, - }, - - "in-cluster not checked when config is not equal to default": { - clientConfig: &testClientConfig{namespace: "test", namespaceSpecified: true}, - icc: &testICC{}, - - result: "test", - ok: true, - }, - - "in-cluster checked when namespace is not specified, but is defaulted": { - clientConfig: &testClientConfig{namespace: "test", namespaceSpecified: false}, - icc: &testICC{}, - - checkedICC: true, - result: "test", - ok: false, - }, - - "in-cluster error returned when config is empty": { - clientConfig: &testClientConfig{err: ErrEmptyConfig}, - icc: &testICC{ - possible: true, - testClientConfig: testClientConfig{ - err: err1, - }, - }, - - checkedICC: true, - err: err1, - }, - - "in-cluster config returned when config is empty": { - clientConfig: &testClientConfig{err: ErrEmptyConfig}, - icc: &testICC{ - possible: true, - testClientConfig: testClientConfig{ - namespace: "test", - namespaceSpecified: true, - }, - }, - - checkedICC: true, - result: "test", - ok: true, - }, - - "in-cluster config returned when config is empty and namespace is defaulted but not explicitly set": { - clientConfig: &testClientConfig{err: ErrEmptyConfig}, - icc: &testICC{ - possible: true, - testClientConfig: testClientConfig{ - namespace: "test", - namespaceSpecified: false, - }, - }, - - checkedICC: true, - result: "test", - ok: false, - }, - } - - for name, test := range testCases { - c := &DeferredLoadingClientConfig{icc: test.icc} - c.clientConfig = test.clientConfig - - ns, ok, err := c.Namespace() - if test.icc.called != test.checkedICC { - t.Errorf("%s: unexpected in-cluster-config call %t", name, test.icc.called) - } - if err != test.err || ns != test.result || ok != test.ok { - t.Errorf("%s: unexpected result: %v %s %t", name, err, ns, ok) - } - } -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/overrides_test.go b/vendor/k8s.io/client-go/tools/clientcmd/overrides_test.go deleted file mode 100644 index 13a995cf52..0000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/overrides_test.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright 2017 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 clientcmd - -import ( - "testing" - - "github.com/spf13/pflag" -) - -func TestNamespacePrefixStrip(t *testing.T) { - testData := map[string]string{ - "namespaces/foo": "foo", - "NAMESPACES/foo": "foo", - "NameSpaces/foo": "foo", - "namespace/foo": "foo", - "NAMESPACE/foo": "foo", - "nameSpace/foo": "foo", - "ns/foo": "foo", - "NS/foo": "foo", - "namespaces/": "namespaces/", - "namespace/": "namespace/", - "ns/": "ns/", - } - - for before, after := range testData { - overrides := &ConfigOverrides{} - fs := &pflag.FlagSet{} - BindOverrideFlags(overrides, fs, RecommendedConfigOverrideFlags("")) - fs.Parse([]string{"--namespace", before}) - - if overrides.Context.Namespace != after { - t.Fatalf("Expected %s, got %s", after, overrides.Context.Namespace) - } - } -} diff --git a/vendor/k8s.io/client-go/tools/clientcmd/validation_test.go b/vendor/k8s.io/client-go/tools/clientcmd/validation_test.go deleted file mode 100644 index 4742b1a143..0000000000 --- a/vendor/k8s.io/client-go/tools/clientcmd/validation_test.go +++ /dev/null @@ -1,574 +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 clientcmd - -import ( - "io/ioutil" - "os" - "strings" - "testing" - - utilerrors "k8s.io/apimachinery/pkg/util/errors" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" -) - -func TestConfirmUsableBadInfoButOkConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - config.Clusters["missing ca"] = &clientcmdapi.Cluster{ - Server: "anything", - CertificateAuthority: "missing", - } - config.AuthInfos["error"] = &clientcmdapi.AuthInfo{ - Username: "anything", - Token: "here", - } - config.Contexts["dirty"] = &clientcmdapi.Context{ - Cluster: "missing ca", - AuthInfo: "error", - } - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "anything", - } - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - Token: "here", - } - config.Contexts["clean"] = &clientcmdapi.Context{ - Cluster: "clean", - AuthInfo: "clean", - } - - badValidation := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"unable to read certificate-authority"}, - } - okTest := configValidationTest{ - config: config, - } - - okTest.testConfirmUsable("clean", t) - badValidation.testConfig(t) -} - -func TestConfirmUsableBadInfoConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - config.Clusters["missing ca"] = &clientcmdapi.Cluster{ - Server: "anything", - CertificateAuthority: "missing", - } - config.AuthInfos["error"] = &clientcmdapi.AuthInfo{ - Username: "anything", - Token: "here", - } - config.Contexts["first"] = &clientcmdapi.Context{ - Cluster: "missing ca", - AuthInfo: "error", - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"unable to read certificate-authority"}, - } - - test.testConfirmUsable("first", t) -} - -func TestConfirmUsableEmptyConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"invalid configuration: no configuration has been provided"}, - } - - test.testConfirmUsable("", t) -} - -func TestConfirmUsableMissingConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"invalid configuration: no configuration has been provided"}, - } - - test.testConfirmUsable("not-here", t) -} - -func TestValidateEmptyConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"invalid configuration: no configuration has been provided"}, - } - - test.testConfig(t) -} - -func TestValidateMissingCurrentContextConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - config.CurrentContext = "anything" - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"context was not found for specified "}, - } - - test.testConfig(t) -} - -func TestIsContextNotFound(t *testing.T) { - config := clientcmdapi.NewConfig() - config.CurrentContext = "anything" - - err := Validate(*config) - if !IsContextNotFound(err) { - t.Errorf("Expected context not found, but got %v", err) - } - if !IsConfigurationInvalid(err) { - t.Errorf("Expected configuration invalid, but got %v", err) - } -} - -func TestIsEmptyConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - - err := Validate(*config) - if !IsEmptyConfig(err) { - t.Errorf("Expected context not found, but got %v", err) - } - if !IsConfigurationInvalid(err) { - t.Errorf("Expected configuration invalid, but got %v", err) - } -} - -func TestIsConfigurationInvalid(t *testing.T) { - if newErrConfigurationInvalid([]error{}) != nil { - t.Errorf("unexpected error") - } - if newErrConfigurationInvalid([]error{ErrNoContext}) == ErrNoContext { - t.Errorf("unexpected error") - } - if newErrConfigurationInvalid([]error{ErrNoContext, ErrNoContext}) == nil { - t.Errorf("unexpected error") - } - if !IsConfigurationInvalid(newErrConfigurationInvalid([]error{ErrNoContext, ErrNoContext})) { - t.Errorf("unexpected error") - } -} - -func TestValidateMissingReferencesConfig(t *testing.T) { - config := clientcmdapi.NewConfig() - config.CurrentContext = "anything" - config.Contexts["anything"] = &clientcmdapi.Context{Cluster: "missing", AuthInfo: "missing"} - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"user \"missing\" was not found for context \"anything\"", "cluster \"missing\" was not found for context \"anything\""}, - } - - test.testContext("anything", t) - test.testConfig(t) -} - -func TestValidateEmptyContext(t *testing.T) { - config := clientcmdapi.NewConfig() - config.CurrentContext = "anything" - config.Contexts["anything"] = &clientcmdapi.Context{} - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"user was not specified for context \"anything\"", "cluster was not specified for context \"anything\""}, - } - - test.testContext("anything", t) - test.testConfig(t) -} - -func TestValidateEmptyContextName(t *testing.T) { - config := clientcmdapi.NewConfig() - config.CurrentContext = "anything" - config.Contexts[""] = &clientcmdapi.Context{Cluster: "missing", AuthInfo: "missing"} - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"empty context name", "is not allowed"}, - } - - test.testContext("", t) - test.testConfig(t) -} - -func TestValidateEmptyClusterInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.Clusters["empty"] = clientcmdapi.NewCluster() - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"cluster has no server defined"}, - } - - test.testCluster("empty", t) - test.testConfig(t) -} - -func TestValidateClusterInfoErrEmptyCluster(t *testing.T) { - cluster := clientcmdapi.NewCluster() - errs := validateClusterInfo("", *cluster) - - if len(errs) != 1 { - t.Fatalf("unexpected errors: %v", errs) - } - if errs[0] != ErrEmptyCluster { - t.Errorf("unexpected error: %v", errs[0]) - } -} - -func TestValidateMissingCAFileClusterInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.Clusters["missing ca"] = &clientcmdapi.Cluster{ - Server: "anything", - CertificateAuthority: "missing", - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"unable to read certificate-authority"}, - } - - test.testCluster("missing ca", t) - test.testConfig(t) -} - -func TestValidateCleanClusterInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "anything", - } - test := configValidationTest{ - config: config, - } - - test.testCluster("clean", t) - test.testConfig(t) -} - -func TestValidateCleanWithCAClusterInfo(t *testing.T) { - tempFile, _ := ioutil.TempFile("", "") - defer os.Remove(tempFile.Name()) - - config := clientcmdapi.NewConfig() - config.Clusters["clean"] = &clientcmdapi.Cluster{ - Server: "anything", - CertificateAuthority: tempFile.Name(), - } - test := configValidationTest{ - config: config, - } - - test.testCluster("clean", t) - test.testConfig(t) -} - -func TestValidateEmptyAuthInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["error"] = &clientcmdapi.AuthInfo{} - test := configValidationTest{ - config: config, - } - - test.testAuthInfo("error", t) - test.testConfig(t) -} - -func TestValidateCertFilesNotFoundAuthInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["error"] = &clientcmdapi.AuthInfo{ - ClientCertificate: "missing", - ClientKey: "missing", - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"unable to read client-cert", "unable to read client-key"}, - } - - test.testAuthInfo("error", t) - test.testConfig(t) -} - -func TestValidateCertDataOverridesFiles(t *testing.T) { - tempFile, _ := ioutil.TempFile("", "") - defer os.Remove(tempFile.Name()) - - config := clientcmdapi.NewConfig() - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - ClientCertificate: tempFile.Name(), - ClientCertificateData: []byte("certdata"), - ClientKey: tempFile.Name(), - ClientKeyData: []byte("keydata"), - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"client-cert-data and client-cert are both specified", "client-key-data and client-key are both specified"}, - } - - test.testAuthInfo("clean", t) - test.testConfig(t) -} - -func TestValidateCleanCertFilesAuthInfo(t *testing.T) { - tempFile, _ := ioutil.TempFile("", "") - defer os.Remove(tempFile.Name()) - - config := clientcmdapi.NewConfig() - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - ClientCertificate: tempFile.Name(), - ClientKey: tempFile.Name(), - } - test := configValidationTest{ - config: config, - } - - test.testAuthInfo("clean", t) - test.testConfig(t) -} - -func TestValidateCleanTokenAuthInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["clean"] = &clientcmdapi.AuthInfo{ - Token: "any-value", - } - test := configValidationTest{ - config: config, - } - - test.testAuthInfo("clean", t) - test.testConfig(t) -} - -func TestValidateMultipleMethodsAuthInfo(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["error"] = &clientcmdapi.AuthInfo{ - Token: "token", - Username: "username", - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{"more than one authentication method", "token", "basicAuth"}, - } - - test.testAuthInfo("error", t) - test.testConfig(t) -} - -func TestValidateAuthInfoExec(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["user"] = &clientcmdapi.AuthInfo{ - Exec: &clientcmdapi.ExecConfig{ - Command: "/bin/example", - APIVersion: "clientauthentication.k8s.io/v1alpha1", - Args: []string{"hello", "world"}, - Env: []clientcmdapi.ExecEnvVar{ - {Name: "foo", Value: "bar"}, - }, - }, - } - test := configValidationTest{ - config: config, - } - - test.testAuthInfo("user", t) - test.testConfig(t) -} - -func TestValidateAuthInfoExecNoVersion(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["user"] = &clientcmdapi.AuthInfo{ - Exec: &clientcmdapi.ExecConfig{ - Command: "/bin/example", - }, - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{ - "apiVersion must be specified for user to use exec authentication plugin", - }, - } - - test.testAuthInfo("user", t) - test.testConfig(t) -} - -func TestValidateAuthInfoExecNoCommand(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["user"] = &clientcmdapi.AuthInfo{ - Exec: &clientcmdapi.ExecConfig{ - APIVersion: "clientauthentication.k8s.io/v1alpha1", - }, - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{ - "command must be specified for user to use exec authentication plugin", - }, - } - - test.testAuthInfo("user", t) - test.testConfig(t) -} - -func TestValidateAuthInfoExecWithAuthProvider(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["user"] = &clientcmdapi.AuthInfo{ - AuthProvider: &clientcmdapi.AuthProviderConfig{ - Name: "oidc", - }, - Exec: &clientcmdapi.ExecConfig{ - Command: "/bin/example", - APIVersion: "clientauthentication.k8s.io/v1alpha1", - }, - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{ - "authProvider cannot be provided in combination with an exec plugin for user", - }, - } - - test.testAuthInfo("user", t) - test.testConfig(t) -} - -func TestValidateAuthInfoExecInvalidEnv(t *testing.T) { - config := clientcmdapi.NewConfig() - config.AuthInfos["user"] = &clientcmdapi.AuthInfo{ - Exec: &clientcmdapi.ExecConfig{ - Command: "/bin/example", - APIVersion: "clientauthentication.k8s.io/v1alpha1", - Env: []clientcmdapi.ExecEnvVar{ - {Name: "foo"}, // No value - }, - }, - } - test := configValidationTest{ - config: config, - expectedErrorSubstring: []string{ - "env variable foo value must be specified for user to use exec authentication plugin", - }, - } - - test.testAuthInfo("user", t) - test.testConfig(t) -} - -type configValidationTest struct { - config *clientcmdapi.Config - expectedErrorSubstring []string -} - -func (c configValidationTest) testContext(contextName string, t *testing.T) { - errs := validateContext(contextName, *c.config.Contexts[contextName], *c.config) - - if len(c.expectedErrorSubstring) != 0 { - if len(errs) == 0 { - t.Errorf("Expected error containing: %v", c.expectedErrorSubstring) - } - for _, curr := range c.expectedErrorSubstring { - if len(errs) != 0 && !strings.Contains(utilerrors.NewAggregate(errs).Error(), curr) { - t.Errorf("Expected error containing: %v, but got %v", c.expectedErrorSubstring, utilerrors.NewAggregate(errs)) - } - } - - } else { - if len(errs) != 0 { - t.Errorf("Unexpected error: %v", utilerrors.NewAggregate(errs)) - } - } -} - -func (c configValidationTest) testConfirmUsable(contextName string, t *testing.T) { - err := ConfirmUsable(*c.config, contextName) - - if len(c.expectedErrorSubstring) != 0 { - if err == nil { - t.Errorf("Expected error containing: %v", c.expectedErrorSubstring) - } else { - for _, curr := range c.expectedErrorSubstring { - if err != nil && !strings.Contains(err.Error(), curr) { - t.Errorf("Expected error containing: %v, but got %v", c.expectedErrorSubstring, err) - } - } - } - } else { - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - } -} - -func (c configValidationTest) testConfig(t *testing.T) { - err := Validate(*c.config) - - if len(c.expectedErrorSubstring) != 0 { - if err == nil { - t.Errorf("Expected error containing: %v", c.expectedErrorSubstring) - } else { - for _, curr := range c.expectedErrorSubstring { - if err != nil && !strings.Contains(err.Error(), curr) { - t.Errorf("Expected error containing: %v, but got %v", c.expectedErrorSubstring, err) - } - } - if !IsConfigurationInvalid(err) { - t.Errorf("all errors should be configuration invalid: %v", err) - } - } - } else { - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - } -} - -func (c configValidationTest) testCluster(clusterName string, t *testing.T) { - errs := validateClusterInfo(clusterName, *c.config.Clusters[clusterName]) - - if len(c.expectedErrorSubstring) != 0 { - if len(errs) == 0 { - t.Errorf("Expected error containing: %v", c.expectedErrorSubstring) - } - for _, curr := range c.expectedErrorSubstring { - if len(errs) != 0 && !strings.Contains(utilerrors.NewAggregate(errs).Error(), curr) { - t.Errorf("Expected error containing: %v, but got %v", c.expectedErrorSubstring, utilerrors.NewAggregate(errs)) - } - } - - } else { - if len(errs) != 0 { - t.Errorf("Unexpected error: %v", utilerrors.NewAggregate(errs)) - } - } -} - -func (c configValidationTest) testAuthInfo(authInfoName string, t *testing.T) { - errs := validateAuthInfo(authInfoName, *c.config.AuthInfos[authInfoName]) - - if len(c.expectedErrorSubstring) != 0 { - if len(errs) == 0 { - t.Errorf("Expected error containing: %v", c.expectedErrorSubstring) - } - for _, curr := range c.expectedErrorSubstring { - if len(errs) != 0 && !strings.Contains(utilerrors.NewAggregate(errs).Error(), curr) { - t.Errorf("Expected error containing: %v, but got %v", c.expectedErrorSubstring, utilerrors.NewAggregate(errs)) - } - } - - } else { - if len(errs) != 0 { - t.Errorf("Unexpected error: %v", utilerrors.NewAggregate(errs)) - } - } -} diff --git a/vendor/k8s.io/client-go/tools/leaderelection/leaderelection_test.go b/vendor/k8s.io/client-go/tools/leaderelection/leaderelection_test.go deleted file mode 100644 index e99cf57afb..0000000000 --- a/vendor/k8s.io/client-go/tools/leaderelection/leaderelection_test.go +++ /dev/null @@ -1,292 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package leaderelection - -import ( - "fmt" - "sync" - "testing" - "time" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - fakecorev1 "k8s.io/client-go/kubernetes/typed/core/v1/fake" - core "k8s.io/client-go/testing" - rl "k8s.io/client-go/tools/leaderelection/resourcelock" - "k8s.io/client-go/tools/record" -) - -func createLockObject(objectType string, objectMeta metav1.ObjectMeta) (obj runtime.Object) { - switch objectType { - case "endpoints": - obj = &v1.Endpoints{ObjectMeta: objectMeta} - case "configmaps": - obj = &v1.ConfigMap{ObjectMeta: objectMeta} - default: - panic("unexpected objType:" + objectType) - } - return -} - -// Will test leader election using endpoints as the resource -func TestTryAcquireOrRenewEndpoints(t *testing.T) { - testTryAcquireOrRenew(t, "endpoints") -} - -func testTryAcquireOrRenew(t *testing.T, objectType string) { - future := time.Now().Add(1000 * time.Hour) - past := time.Now().Add(-1000 * time.Hour) - - tests := []struct { - observedRecord rl.LeaderElectionRecord - observedTime time.Time - reactors []struct { - verb string - reaction core.ReactionFunc - } - - expectSuccess bool - transitionLeader bool - outHolder string - }{ - // acquire from no object - { - reactors: []struct { - verb string - reaction core.ReactionFunc - }{ - { - verb: "get", - reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, nil, errors.NewNotFound(action.(core.GetAction).GetResource().GroupResource(), action.(core.GetAction).GetName()) - }, - }, - { - verb: "create", - reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, action.(core.CreateAction).GetObject(), nil - }, - }, - }, - expectSuccess: true, - outHolder: "baz", - }, - // acquire from unled object - { - reactors: []struct { - verb string - reaction core.ReactionFunc - }{ - { - verb: "get", - reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - objectMeta := metav1.ObjectMeta{ - Namespace: action.GetNamespace(), - Name: action.(core.GetAction).GetName(), - } - return true, createLockObject(objectType, objectMeta), nil - }, - }, - { - verb: "update", - reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, action.(core.CreateAction).GetObject(), nil - }, - }, - }, - - expectSuccess: true, - transitionLeader: true, - outHolder: "baz", - }, - // acquire from led, unacked object - { - reactors: []struct { - verb string - reaction core.ReactionFunc - }{ - { - verb: "get", - reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - objectMeta := metav1.ObjectMeta{ - Namespace: action.GetNamespace(), - Name: action.(core.GetAction).GetName(), - Annotations: map[string]string{ - rl.LeaderElectionRecordAnnotationKey: `{"holderIdentity":"bing"}`, - }, - } - return true, createLockObject(objectType, objectMeta), nil - }, - }, - { - verb: "update", - reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, action.(core.CreateAction).GetObject(), nil - }, - }, - }, - observedRecord: rl.LeaderElectionRecord{HolderIdentity: "bing"}, - observedTime: past, - - expectSuccess: true, - transitionLeader: true, - outHolder: "baz", - }, - // don't acquire from led, acked object - { - reactors: []struct { - verb string - reaction core.ReactionFunc - }{ - { - verb: "get", - reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - objectMeta := metav1.ObjectMeta{ - Namespace: action.GetNamespace(), - Name: action.(core.GetAction).GetName(), - Annotations: map[string]string{ - rl.LeaderElectionRecordAnnotationKey: `{"holderIdentity":"bing"}`, - }, - } - return true, createLockObject(objectType, objectMeta), nil - }, - }, - }, - observedTime: future, - - expectSuccess: false, - outHolder: "bing", - }, - // renew already acquired object - { - reactors: []struct { - verb string - reaction core.ReactionFunc - }{ - { - verb: "get", - reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - objectMeta := metav1.ObjectMeta{ - Namespace: action.GetNamespace(), - Name: action.(core.GetAction).GetName(), - Annotations: map[string]string{ - rl.LeaderElectionRecordAnnotationKey: `{"holderIdentity":"baz"}`, - }, - } - return true, createLockObject(objectType, objectMeta), nil - }, - }, - { - verb: "update", - reaction: func(action core.Action) (handled bool, ret runtime.Object, err error) { - return true, action.(core.CreateAction).GetObject(), nil - }, - }, - }, - observedTime: future, - observedRecord: rl.LeaderElectionRecord{HolderIdentity: "baz"}, - - expectSuccess: true, - outHolder: "baz", - }, - } - - for i, test := range tests { - // OnNewLeader is called async so we have to wait for it. - var wg sync.WaitGroup - wg.Add(1) - var reportedLeader string - var lock rl.Interface - - objectMeta := metav1.ObjectMeta{Namespace: "foo", Name: "bar"} - resourceLockConfig := rl.ResourceLockConfig{ - Identity: "baz", - EventRecorder: &record.FakeRecorder{}, - } - c := &fakecorev1.FakeCoreV1{Fake: &core.Fake{}} - for _, reactor := range test.reactors { - c.AddReactor(reactor.verb, objectType, reactor.reaction) - } - c.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { - t.Errorf("[%v] unreachable action. testclient called too many times: %+v", i, action) - return true, nil, fmt.Errorf("unreachable action") - }) - - switch objectType { - case "endpoints": - lock = &rl.EndpointsLock{ - EndpointsMeta: objectMeta, - LockConfig: resourceLockConfig, - Client: c, - } - case "configmaps": - lock = &rl.ConfigMapLock{ - ConfigMapMeta: objectMeta, - LockConfig: resourceLockConfig, - Client: c, - } - } - - lec := LeaderElectionConfig{ - Lock: lock, - LeaseDuration: 10 * time.Second, - Callbacks: LeaderCallbacks{ - OnNewLeader: func(l string) { - defer wg.Done() - reportedLeader = l - }, - }, - } - le := &LeaderElector{ - config: lec, - observedRecord: test.observedRecord, - observedTime: test.observedTime, - } - - if test.expectSuccess != le.tryAcquireOrRenew() { - t.Errorf("[%v]unexpected result of tryAcquireOrRenew: [succeeded=%v]", i, !test.expectSuccess) - } - - le.observedRecord.AcquireTime = metav1.Time{} - le.observedRecord.RenewTime = metav1.Time{} - if le.observedRecord.HolderIdentity != test.outHolder { - t.Errorf("[%v]expected holder:\n\t%+v\ngot:\n\t%+v", i, test.outHolder, le.observedRecord.HolderIdentity) - } - if len(test.reactors) != len(c.Actions()) { - t.Errorf("[%v]wrong number of api interactions", i) - } - if test.transitionLeader && le.observedRecord.LeaderTransitions != 1 { - t.Errorf("[%v]leader should have transitioned but did not", i) - } - if !test.transitionLeader && le.observedRecord.LeaderTransitions != 0 { - t.Errorf("[%v]leader should not have transitioned but did", i) - } - - le.maybeReportTransition() - wg.Wait() - if reportedLeader != test.outHolder { - t.Errorf("[%v]reported leader was not the new leader. expected %q, got %q", i, test.outHolder, reportedLeader) - } - } -} - -// Will test leader election using configmap as the resource -func TestTryAcquireOrRenewConfigMaps(t *testing.T) { - testTryAcquireOrRenew(t, "configmaps") -} diff --git a/vendor/k8s.io/client-go/tools/pager/pager_test.go b/vendor/k8s.io/client-go/tools/pager/pager_test.go deleted file mode 100644 index b905fc1fb6..0000000000 --- a/vendor/k8s.io/client-go/tools/pager/pager_test.go +++ /dev/null @@ -1,206 +0,0 @@ -/* -Copyright 2017 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 pager - -import ( - "fmt" - "reflect" - "testing" - - "golang.org/x/net/context" - "k8s.io/apimachinery/pkg/api/errors" - metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - metav1beta1 "k8s.io/apimachinery/pkg/apis/meta/v1beta1" - "k8s.io/apimachinery/pkg/runtime" -) - -func list(count int, rv string) *metainternalversion.List { - var list metainternalversion.List - for i := 0; i < count; i++ { - list.Items = append(list.Items, &metav1beta1.PartialObjectMetadata{ - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("%d", i), - }, - }) - } - list.ResourceVersion = rv - return &list -} - -type testPager struct { - t *testing.T - rv string - index int - remaining int - last int - continuing bool - done bool - expectPage int64 -} - -func (p *testPager) reset() { - p.continuing = false - p.remaining += p.index - p.index = 0 - p.last = 0 - p.done = false -} - -func (p *testPager) PagedList(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { - if p.done { - p.t.Errorf("did not expect additional call to paged list") - return nil, fmt.Errorf("unexpected list call") - } - expectedContinue := fmt.Sprintf("%s:%d", p.rv, p.last) - if options.Limit != p.expectPage || (p.continuing && options.Continue != expectedContinue) { - p.t.Errorf("invariant violated, expected limit %d and continue %s, got %#v", p.expectPage, expectedContinue, options) - return nil, fmt.Errorf("invariant violated") - } - var list metainternalversion.List - total := options.Limit - if total == 0 { - total = int64(p.remaining) - } - for i := int64(0); i < total; i++ { - if p.remaining <= 0 { - break - } - list.Items = append(list.Items, &metav1beta1.PartialObjectMetadata{ - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("%d", p.index), - }, - }) - p.remaining-- - p.index++ - } - p.last = p.index - if p.remaining > 0 { - list.Continue = fmt.Sprintf("%s:%d", p.rv, p.last) - p.continuing = true - } else { - p.done = true - } - list.ResourceVersion = p.rv - return &list, nil -} - -func (p *testPager) ExpiresOnSecondPage(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { - if p.continuing { - p.done = true - return nil, errors.NewResourceExpired("this list has expired") - } - return p.PagedList(ctx, options) -} - -func (p *testPager) ExpiresOnSecondPageThenFullList(ctx context.Context, options metav1.ListOptions) (runtime.Object, error) { - if p.continuing { - p.reset() - p.expectPage = 0 - return nil, errors.NewResourceExpired("this list has expired") - } - return p.PagedList(ctx, options) -} - -func TestListPager_List(t *testing.T) { - type fields struct { - PageSize int64 - PageFn ListPageFunc - FullListIfExpired bool - } - type args struct { - ctx context.Context - options metav1.ListOptions - } - tests := []struct { - name string - fields fields - args args - want runtime.Object - wantErr bool - isExpired bool - }{ - { - name: "empty page", - fields: fields{PageSize: 10, PageFn: (&testPager{t: t, expectPage: 10, remaining: 0, rv: "rv:20"}).PagedList}, - args: args{}, - want: list(0, "rv:20"), - }, - { - name: "one page", - fields: fields{PageSize: 10, PageFn: (&testPager{t: t, expectPage: 10, remaining: 9, rv: "rv:20"}).PagedList}, - args: args{}, - want: list(9, "rv:20"), - }, - { - name: "one full page", - fields: fields{PageSize: 10, PageFn: (&testPager{t: t, expectPage: 10, remaining: 10, rv: "rv:20"}).PagedList}, - args: args{}, - want: list(10, "rv:20"), - }, - { - name: "two pages", - fields: fields{PageSize: 10, PageFn: (&testPager{t: t, expectPage: 10, remaining: 11, rv: "rv:20"}).PagedList}, - args: args{}, - want: list(11, "rv:20"), - }, - { - name: "three pages", - fields: fields{PageSize: 10, PageFn: (&testPager{t: t, expectPage: 10, remaining: 21, rv: "rv:20"}).PagedList}, - args: args{}, - want: list(21, "rv:20"), - }, - { - name: "expires on second page", - fields: fields{PageSize: 10, PageFn: (&testPager{t: t, expectPage: 10, remaining: 21, rv: "rv:20"}).ExpiresOnSecondPage}, - args: args{}, - wantErr: true, - isExpired: true, - }, - { - name: "expires on second page and then lists", - fields: fields{ - FullListIfExpired: true, - PageSize: 10, - PageFn: (&testPager{t: t, expectPage: 10, remaining: 21, rv: "rv:20"}).ExpiresOnSecondPageThenFullList, - }, - args: args{}, - want: list(21, "rv:20"), - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - p := &ListPager{ - PageSize: tt.fields.PageSize, - PageFn: tt.fields.PageFn, - FullListIfExpired: tt.fields.FullListIfExpired, - } - got, err := p.List(tt.args.ctx, tt.args.options) - if (err != nil) != tt.wantErr { - t.Errorf("ListPager.List() error = %v, wantErr %v", err, tt.wantErr) - return - } - if tt.isExpired != errors.IsResourceExpired(err) { - t.Errorf("ListPager.List() error = %v, isExpired %v", err, tt.isExpired) - return - } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("ListPager.List() = %v, want %v", got, tt.want) - } - }) - } -} diff --git a/vendor/k8s.io/client-go/tools/record/event_test.go b/vendor/k8s.io/client-go/tools/record/event_test.go deleted file mode 100644 index 4fcebc3537..0000000000 --- a/vendor/k8s.io/client-go/tools/record/event_test.go +++ /dev/null @@ -1,924 +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 record - -import ( - "encoding/json" - "fmt" - "math/rand" - "net/http" - "strconv" - "testing" - "time" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - k8sruntime "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/clock" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/client-go/kubernetes/scheme" - restclient "k8s.io/client-go/rest" - ref "k8s.io/client-go/tools/reference" -) - -type testEventSink struct { - OnCreate func(e *v1.Event) (*v1.Event, error) - OnUpdate func(e *v1.Event) (*v1.Event, error) - OnPatch func(e *v1.Event, p []byte) (*v1.Event, error) -} - -// CreateEvent records the event for testing. -func (t *testEventSink) Create(e *v1.Event) (*v1.Event, error) { - if t.OnCreate != nil { - return t.OnCreate(e) - } - return e, nil -} - -// UpdateEvent records the event for testing. -func (t *testEventSink) Update(e *v1.Event) (*v1.Event, error) { - if t.OnUpdate != nil { - return t.OnUpdate(e) - } - return e, nil -} - -// PatchEvent records the event for testing. -func (t *testEventSink) Patch(e *v1.Event, p []byte) (*v1.Event, error) { - if t.OnPatch != nil { - return t.OnPatch(e, p) - } - return e, nil -} - -type OnCreateFunc func(*v1.Event) (*v1.Event, error) - -func OnCreateFactory(testCache map[string]*v1.Event, createEvent chan<- *v1.Event) OnCreateFunc { - return func(event *v1.Event) (*v1.Event, error) { - testCache[getEventKey(event)] = event - createEvent <- event - return event, nil - } -} - -type OnPatchFunc func(*v1.Event, []byte) (*v1.Event, error) - -func OnPatchFactory(testCache map[string]*v1.Event, patchEvent chan<- *v1.Event) OnPatchFunc { - return func(event *v1.Event, patch []byte) (*v1.Event, error) { - cachedEvent, found := testCache[getEventKey(event)] - if !found { - return nil, fmt.Errorf("unexpected error: couldn't find Event in testCache.") - } - originalData, err := json.Marshal(cachedEvent) - if err != nil { - return nil, fmt.Errorf("unexpected error: %v", err) - } - patched, err := strategicpatch.StrategicMergePatch(originalData, patch, event) - if err != nil { - return nil, fmt.Errorf("unexpected error: %v", err) - } - patchedObj := &v1.Event{} - err = json.Unmarshal(patched, patchedObj) - if err != nil { - return nil, fmt.Errorf("unexpected error: %v", err) - } - patchEvent <- patchedObj - return patchedObj, nil - } -} - -func TestEventf(t *testing.T) { - testPod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - SelfLink: "/api/version/pods/foo", - Name: "foo", - Namespace: "baz", - UID: "bar", - }, - } - testPod2 := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - SelfLink: "/api/version/pods/foo", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - }, - } - testRef, err := ref.GetPartialReference(scheme.Scheme, testPod, "spec.containers[2]") - if err != nil { - t.Fatal(err) - } - testRef2, err := ref.GetPartialReference(scheme.Scheme, testPod2, "spec.containers[3]") - if err != nil { - t.Fatal(err) - } - table := []struct { - obj k8sruntime.Object - eventtype string - reason string - messageFmt string - elements []interface{} - expect *v1.Event - expectLog string - expectUpdate bool - }{ - { - obj: testRef, - eventtype: v1.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 1, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testPod, - eventtype: v1.EventTypeNormal, - reason: "Killed", - messageFmt: "some other verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - }, - Reason: "Killed", - Message: "some other verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 1, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:""}): type: 'Normal' reason: 'Killed' some other verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef, - eventtype: v1.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 2, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: true, - }, - { - obj: testRef2, - eventtype: v1.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 1, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef, - eventtype: v1.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 3, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: true, - }, - { - obj: testRef2, - eventtype: v1.EventTypeNormal, - reason: "Stopped", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Stopped", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 1, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef2, - eventtype: v1.EventTypeNormal, - reason: "Stopped", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Stopped", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 2, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`, - expectUpdate: true, - }, - } - - testCache := map[string]*v1.Event{} - logCalled := make(chan struct{}) - createEvent := make(chan *v1.Event) - updateEvent := make(chan *v1.Event) - patchEvent := make(chan *v1.Event) - testEvents := testEventSink{ - OnCreate: OnCreateFactory(testCache, createEvent), - OnUpdate: func(event *v1.Event) (*v1.Event, error) { - updateEvent <- event - return event, nil - }, - OnPatch: OnPatchFactory(testCache, patchEvent), - } - eventBroadcaster := NewBroadcasterForTests(0) - sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) - - clock := clock.NewFakeClock(time.Now()) - recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock) - for index, item := range table { - clock.Step(1 * time.Second) - logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) { - if e, a := item.expectLog, fmt.Sprintf(formatter, args...); e != a { - t.Errorf("Expected '%v', got '%v'", e, a) - } - logCalled <- struct{}{} - }) - recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...) - - <-logCalled - - // validate event - if item.expectUpdate { - actualEvent := <-patchEvent - validateEvent(strconv.Itoa(index), actualEvent, item.expect, t) - } else { - actualEvent := <-createEvent - validateEvent(strconv.Itoa(index), actualEvent, item.expect, t) - } - logWatcher.Stop() - } - sinkWatcher.Stop() -} - -func recorderWithFakeClock(eventSource v1.EventSource, eventBroadcaster EventBroadcaster, clock clock.Clock) EventRecorder { - return &recorderImpl{scheme.Scheme, eventSource, eventBroadcaster.(*eventBroadcasterImpl).Broadcaster, clock} -} - -func TestWriteEventError(t *testing.T) { - type entry struct { - timesToSendError int - attemptsWanted int - err error - } - table := map[string]*entry{ - "giveUp1": { - timesToSendError: 1000, - attemptsWanted: 1, - err: &restclient.RequestConstructionError{}, - }, - "giveUp2": { - timesToSendError: 1000, - attemptsWanted: 1, - err: &errors.StatusError{}, - }, - "retry1": { - timesToSendError: 1000, - attemptsWanted: 12, - err: &errors.UnexpectedObjectError{}, - }, - "retry2": { - timesToSendError: 1000, - attemptsWanted: 12, - err: fmt.Errorf("A weird error"), - }, - "succeedEventually": { - timesToSendError: 2, - attemptsWanted: 2, - err: fmt.Errorf("A weird error"), - }, - } - - clock := clock.IntervalClock{Time: time.Now(), Duration: time.Second} - eventCorrelator := NewEventCorrelator(&clock) - randGen := rand.New(rand.NewSource(time.Now().UnixNano())) - - for caseName, ent := range table { - attempts := 0 - sink := &testEventSink{ - OnCreate: func(event *v1.Event) (*v1.Event, error) { - attempts++ - if attempts < ent.timesToSendError { - return nil, ent.err - } - return event, nil - }, - } - ev := &v1.Event{} - recordToSink(sink, ev, eventCorrelator, randGen, 0) - if attempts != ent.attemptsWanted { - t.Errorf("case %v: wanted %d, got %d attempts", caseName, ent.attemptsWanted, attempts) - } - } -} - -func TestUpdateExpiredEvent(t *testing.T) { - clock := clock.IntervalClock{Time: time.Now(), Duration: time.Second} - eventCorrelator := NewEventCorrelator(&clock) - randGen := rand.New(rand.NewSource(time.Now().UnixNano())) - - var createdEvent *v1.Event - - sink := &testEventSink{ - OnPatch: func(*v1.Event, []byte) (*v1.Event, error) { - return nil, &errors.StatusError{ - ErrStatus: metav1.Status{ - Code: http.StatusNotFound, - Reason: metav1.StatusReasonNotFound, - }} - }, - OnCreate: func(event *v1.Event) (*v1.Event, error) { - createdEvent = event - return event, nil - }, - } - - ev := &v1.Event{} - ev.ResourceVersion = "updated-resource-version" - ev.Count = 2 - recordToSink(sink, ev, eventCorrelator, randGen, 0) - - if createdEvent == nil { - t.Error("Event did not get created after patch failed") - return - } - - if createdEvent.ResourceVersion != "" { - t.Errorf("Event did not have its resource version cleared, was %s", createdEvent.ResourceVersion) - } -} - -func TestLotsOfEvents(t *testing.T) { - recorderCalled := make(chan struct{}) - loggerCalled := make(chan struct{}) - - // Fail each event a few times to ensure there's some load on the tested code. - var counts [1000]int - testEvents := testEventSink{ - OnCreate: func(event *v1.Event) (*v1.Event, error) { - num, err := strconv.Atoi(event.Message) - if err != nil { - t.Error(err) - return event, nil - } - counts[num]++ - if counts[num] < 5 { - return nil, fmt.Errorf("fake error") - } - recorderCalled <- struct{}{} - return event, nil - }, - } - - eventBroadcaster := NewBroadcasterForTests(0) - sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) - logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) { - loggerCalled <- struct{}{} - }) - recorder := eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "eventTest"}) - for i := 0; i < maxQueuedEvents; i++ { - // we want a unique object to stop spam filtering - ref := &v1.ObjectReference{ - Kind: "Pod", - Name: fmt.Sprintf("foo-%v", i), - Namespace: "baz", - UID: "bar", - APIVersion: "version", - } - // we need to vary the reason to prevent aggregation - go recorder.Eventf(ref, v1.EventTypeNormal, "Reason-"+string(i), strconv.Itoa(i)) - } - // Make sure no events were dropped by either of the listeners. - for i := 0; i < maxQueuedEvents; i++ { - <-recorderCalled - <-loggerCalled - } - // Make sure that every event was attempted 5 times - for i := 0; i < maxQueuedEvents; i++ { - if counts[i] < 5 { - t.Errorf("Only attempted to record event '%d' %d times.", i, counts[i]) - } - } - sinkWatcher.Stop() - logWatcher.Stop() -} - -func TestEventfNoNamespace(t *testing.T) { - testPod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - SelfLink: "/api/version/pods/foo", - Name: "foo", - UID: "bar", - }, - } - testRef, err := ref.GetPartialReference(scheme.Scheme, testPod, "spec.containers[2]") - if err != nil { - t.Fatal(err) - } - table := []struct { - obj k8sruntime.Object - eventtype string - reason string - messageFmt string - elements []interface{} - expect *v1.Event - expectLog string - expectUpdate bool - }{ - { - obj: testRef, - eventtype: v1.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "default", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 1, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: false, - }, - } - - testCache := map[string]*v1.Event{} - logCalled := make(chan struct{}) - createEvent := make(chan *v1.Event) - updateEvent := make(chan *v1.Event) - patchEvent := make(chan *v1.Event) - testEvents := testEventSink{ - OnCreate: OnCreateFactory(testCache, createEvent), - OnUpdate: func(event *v1.Event) (*v1.Event, error) { - updateEvent <- event - return event, nil - }, - OnPatch: OnPatchFactory(testCache, patchEvent), - } - eventBroadcaster := NewBroadcasterForTests(0) - sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) - - clock := clock.NewFakeClock(time.Now()) - recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock) - - for index, item := range table { - clock.Step(1 * time.Second) - logWatcher := eventBroadcaster.StartLogging(func(formatter string, args ...interface{}) { - if e, a := item.expectLog, fmt.Sprintf(formatter, args...); e != a { - t.Errorf("Expected '%v', got '%v'", e, a) - } - logCalled <- struct{}{} - }) - recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...) - - <-logCalled - - // validate event - if item.expectUpdate { - actualEvent := <-patchEvent - validateEvent(strconv.Itoa(index), actualEvent, item.expect, t) - } else { - actualEvent := <-createEvent - validateEvent(strconv.Itoa(index), actualEvent, item.expect, t) - } - - logWatcher.Stop() - } - sinkWatcher.Stop() -} - -func TestMultiSinkCache(t *testing.T) { - testPod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - SelfLink: "/api/version/pods/foo", - Name: "foo", - Namespace: "baz", - UID: "bar", - }, - } - testPod2 := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - SelfLink: "/api/version/pods/foo", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - }, - } - testRef, err := ref.GetPartialReference(scheme.Scheme, testPod, "spec.containers[2]") - if err != nil { - t.Fatal(err) - } - testRef2, err := ref.GetPartialReference(scheme.Scheme, testPod2, "spec.containers[3]") - if err != nil { - t.Fatal(err) - } - table := []struct { - obj k8sruntime.Object - eventtype string - reason string - messageFmt string - elements []interface{} - expect *v1.Event - expectLog string - expectUpdate bool - }{ - { - obj: testRef, - eventtype: v1.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 1, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testPod, - eventtype: v1.EventTypeNormal, - reason: "Killed", - messageFmt: "some other verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - }, - Reason: "Killed", - Message: "some other verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 1, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:""}): type: 'Normal' reason: 'Killed' some other verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef, - eventtype: v1.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 2, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: true, - }, - { - obj: testRef2, - eventtype: v1.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 1, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef, - eventtype: v1.EventTypeNormal, - reason: "Started", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "bar", - APIVersion: "version", - FieldPath: "spec.containers[2]", - }, - Reason: "Started", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 3, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"bar", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[2]"}): type: 'Normal' reason: 'Started' some verbose message: 1`, - expectUpdate: true, - }, - { - obj: testRef2, - eventtype: v1.EventTypeNormal, - reason: "Stopped", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Stopped", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 1, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`, - expectUpdate: false, - }, - { - obj: testRef2, - eventtype: v1.EventTypeNormal, - reason: "Stopped", - messageFmt: "some verbose message: %v", - elements: []interface{}{1}, - expect: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "baz", - }, - InvolvedObject: v1.ObjectReference{ - Kind: "Pod", - Name: "foo", - Namespace: "baz", - UID: "differentUid", - APIVersion: "version", - FieldPath: "spec.containers[3]", - }, - Reason: "Stopped", - Message: "some verbose message: 1", - Source: v1.EventSource{Component: "eventTest"}, - Count: 2, - Type: v1.EventTypeNormal, - }, - expectLog: `Event(v1.ObjectReference{Kind:"Pod", Namespace:"baz", Name:"foo", UID:"differentUid", APIVersion:"version", ResourceVersion:"", FieldPath:"spec.containers[3]"}): type: 'Normal' reason: 'Stopped' some verbose message: 1`, - expectUpdate: true, - }, - } - - testCache := map[string]*v1.Event{} - createEvent := make(chan *v1.Event) - updateEvent := make(chan *v1.Event) - patchEvent := make(chan *v1.Event) - testEvents := testEventSink{ - OnCreate: OnCreateFactory(testCache, createEvent), - OnUpdate: func(event *v1.Event) (*v1.Event, error) { - updateEvent <- event - return event, nil - }, - OnPatch: OnPatchFactory(testCache, patchEvent), - } - - testCache2 := map[string]*v1.Event{} - createEvent2 := make(chan *v1.Event) - updateEvent2 := make(chan *v1.Event) - patchEvent2 := make(chan *v1.Event) - testEvents2 := testEventSink{ - OnCreate: OnCreateFactory(testCache2, createEvent2), - OnUpdate: func(event *v1.Event) (*v1.Event, error) { - updateEvent2 <- event - return event, nil - }, - OnPatch: OnPatchFactory(testCache2, patchEvent2), - } - - eventBroadcaster := NewBroadcasterForTests(0) - clock := clock.NewFakeClock(time.Now()) - recorder := recorderWithFakeClock(v1.EventSource{Component: "eventTest"}, eventBroadcaster, clock) - - sinkWatcher := eventBroadcaster.StartRecordingToSink(&testEvents) - for index, item := range table { - clock.Step(1 * time.Second) - recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...) - - // validate event - if item.expectUpdate { - actualEvent := <-patchEvent - validateEvent(strconv.Itoa(index), actualEvent, item.expect, t) - } else { - actualEvent := <-createEvent - validateEvent(strconv.Itoa(index), actualEvent, item.expect, t) - } - } - - // Another StartRecordingToSink call should start to record events with new clean cache. - sinkWatcher2 := eventBroadcaster.StartRecordingToSink(&testEvents2) - for index, item := range table { - clock.Step(1 * time.Second) - recorder.Eventf(item.obj, item.eventtype, item.reason, item.messageFmt, item.elements...) - - // validate event - if item.expectUpdate { - actualEvent := <-patchEvent2 - validateEvent(strconv.Itoa(index), actualEvent, item.expect, t) - } else { - actualEvent := <-createEvent2 - validateEvent(strconv.Itoa(index), actualEvent, item.expect, t) - } - } - - sinkWatcher.Stop() - sinkWatcher2.Stop() -} diff --git a/vendor/k8s.io/client-go/tools/record/events_cache_test.go b/vendor/k8s.io/client-go/tools/record/events_cache_test.go deleted file mode 100644 index 6ccd16d827..0000000000 --- a/vendor/k8s.io/client-go/tools/record/events_cache_test.go +++ /dev/null @@ -1,287 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package record - -import ( - "reflect" - "strings" - "testing" - "time" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/clock" - "k8s.io/apimachinery/pkg/util/diff" -) - -func makeObjectReference(kind, name, namespace string) v1.ObjectReference { - return v1.ObjectReference{ - Kind: kind, - Name: name, - Namespace: namespace, - UID: "C934D34AFB20242", - APIVersion: "version", - FieldPath: "spec.containers{mycontainer}", - } -} - -func makeEvent(reason, message string, involvedObject v1.ObjectReference) v1.Event { - eventTime := metav1.Now() - event := v1.Event{ - Reason: reason, - Message: message, - InvolvedObject: involvedObject, - Source: v1.EventSource{ - Component: "kubelet", - Host: "kublet.node1", - }, - Count: 1, - FirstTimestamp: eventTime, - LastTimestamp: eventTime, - Type: v1.EventTypeNormal, - } - return event -} - -func makeEvents(num int, template v1.Event) []v1.Event { - events := []v1.Event{} - for i := 0; i < num; i++ { - events = append(events, template) - } - return events -} - -func makeUniqueEvents(num int) []v1.Event { - events := []v1.Event{} - kind := "Pod" - for i := 0; i < num; i++ { - reason := strings.Join([]string{"reason", string(i)}, "-") - message := strings.Join([]string{"message", string(i)}, "-") - name := strings.Join([]string{"pod", string(i)}, "-") - namespace := strings.Join([]string{"ns", string(i)}, "-") - involvedObject := makeObjectReference(kind, name, namespace) - events = append(events, makeEvent(reason, message, involvedObject)) - } - return events -} - -func makeSimilarEvents(num int, template v1.Event, messagePrefix string) []v1.Event { - events := makeEvents(num, template) - for i := range events { - events[i].Message = strings.Join([]string{messagePrefix, string(i), events[i].Message}, "-") - } - return events -} - -func setCount(event v1.Event, count int) v1.Event { - event.Count = int32(count) - return event -} - -func validateEvent(messagePrefix string, actualEvent *v1.Event, expectedEvent *v1.Event, t *testing.T) (*v1.Event, error) { - recvEvent := *actualEvent - expectCompression := expectedEvent.Count > 1 - t.Logf("%v - expectedEvent.Count is %d\n", messagePrefix, expectedEvent.Count) - // Just check that the timestamp was set. - if recvEvent.FirstTimestamp.IsZero() || recvEvent.LastTimestamp.IsZero() { - t.Errorf("%v - timestamp wasn't set: %#v", messagePrefix, recvEvent) - } - actualFirstTimestamp := recvEvent.FirstTimestamp - actualLastTimestamp := recvEvent.LastTimestamp - if actualFirstTimestamp.Equal(&actualLastTimestamp) { - if expectCompression { - t.Errorf("%v - FirstTimestamp (%q) and LastTimestamp (%q) must be different to indicate event compression happened, but were the same. Actual Event: %#v", messagePrefix, actualFirstTimestamp, actualLastTimestamp, recvEvent) - } - } else { - if expectedEvent.Count == 1 { - t.Errorf("%v - FirstTimestamp (%q) and LastTimestamp (%q) must be equal to indicate only one occurrence of the event, but were different. Actual Event: %#v", messagePrefix, actualFirstTimestamp, actualLastTimestamp, recvEvent) - } - } - // Temp clear time stamps for comparison because actual values don't matter for comparison - recvEvent.FirstTimestamp = expectedEvent.FirstTimestamp - recvEvent.LastTimestamp = expectedEvent.LastTimestamp - // Check that name has the right prefix. - if n, en := recvEvent.Name, expectedEvent.Name; !strings.HasPrefix(n, en) { - t.Errorf("%v - Name '%v' does not contain prefix '%v'", messagePrefix, n, en) - } - recvEvent.Name = expectedEvent.Name - if e, a := expectedEvent, &recvEvent; !reflect.DeepEqual(e, a) { - t.Errorf("%v - diff: %s", messagePrefix, diff.ObjectGoPrintDiff(e, a)) - } - recvEvent.FirstTimestamp = actualFirstTimestamp - recvEvent.LastTimestamp = actualLastTimestamp - return actualEvent, nil -} - -// TestDefaultEventFilterFunc ensures that no events are filtered -func TestDefaultEventFilterFunc(t *testing.T) { - event := makeEvent("end-of-world", "it was fun", makeObjectReference("Pod", "pod1", "other")) - if DefaultEventFilterFunc(&event) { - t.Fatalf("DefaultEventFilterFunc should always return false") - } -} - -// TestEventAggregatorByReasonFunc ensures that two events are aggregated if they vary only by event.message -func TestEventAggregatorByReasonFunc(t *testing.T) { - event1 := makeEvent("end-of-world", "it was fun", makeObjectReference("Pod", "pod1", "other")) - event2 := makeEvent("end-of-world", "it was awful", makeObjectReference("Pod", "pod1", "other")) - event3 := makeEvent("nevermind", "it was a bug", makeObjectReference("Pod", "pod1", "other")) - - aggKey1, localKey1 := EventAggregatorByReasonFunc(&event1) - aggKey2, localKey2 := EventAggregatorByReasonFunc(&event2) - aggKey3, _ := EventAggregatorByReasonFunc(&event3) - - if aggKey1 != aggKey2 { - t.Errorf("Expected %v equal %v", aggKey1, aggKey2) - } - if localKey1 == localKey2 { - t.Errorf("Expected %v to not equal %v", aggKey1, aggKey3) - } - if aggKey1 == aggKey3 { - t.Errorf("Expected %v to not equal %v", aggKey1, aggKey3) - } -} - -// TestEventAggregatorByReasonMessageFunc validates the proper output for an aggregate message -func TestEventAggregatorByReasonMessageFunc(t *testing.T) { - expectedPrefix := "(combined from similar events): " - event1 := makeEvent("end-of-world", "it was fun", makeObjectReference("Pod", "pod1", "other")) - actual := EventAggregatorByReasonMessageFunc(&event1) - if !strings.HasPrefix(actual, expectedPrefix) { - t.Errorf("Expected %v to begin with prefix %v", actual, expectedPrefix) - } -} - -// TestEventCorrelator validates proper counting, aggregation of events -func TestEventCorrelator(t *testing.T) { - firstEvent := makeEvent("first", "i am first", makeObjectReference("Pod", "my-pod", "my-ns")) - duplicateEvent := makeEvent("duplicate", "me again", makeObjectReference("Pod", "my-pod", "my-ns")) - uniqueEvent := makeEvent("unique", "snowflake", makeObjectReference("Pod", "my-pod", "my-ns")) - similarEvent := makeEvent("similar", "similar message", makeObjectReference("Pod", "my-pod", "my-ns")) - similarEvent.InvolvedObject.FieldPath = "spec.containers{container1}" - aggregateEvent := makeEvent(similarEvent.Reason, EventAggregatorByReasonMessageFunc(&similarEvent), similarEvent.InvolvedObject) - similarButDifferentContainerEvent := similarEvent - similarButDifferentContainerEvent.InvolvedObject.FieldPath = "spec.containers{container2}" - scenario := map[string]struct { - previousEvents []v1.Event - newEvent v1.Event - expectedEvent v1.Event - intervalSeconds int - expectedSkip bool - }{ - "create-a-single-event": { - previousEvents: []v1.Event{}, - newEvent: firstEvent, - expectedEvent: setCount(firstEvent, 1), - intervalSeconds: 5, - }, - "the-same-event-should-just-count": { - previousEvents: makeEvents(1, duplicateEvent), - newEvent: duplicateEvent, - expectedEvent: setCount(duplicateEvent, 2), - intervalSeconds: 5, - }, - "the-same-event-should-just-count-even-if-more-than-aggregate": { - previousEvents: makeEvents(defaultAggregateMaxEvents, duplicateEvent), - newEvent: duplicateEvent, - expectedEvent: setCount(duplicateEvent, defaultAggregateMaxEvents+1), - intervalSeconds: 30, // larger interval induces aggregation but not spam. - }, - "the-same-event-is-spam-if-happens-too-frequently": { - previousEvents: makeEvents(defaultSpamBurst+1, duplicateEvent), - newEvent: duplicateEvent, - expectedSkip: true, - intervalSeconds: 1, - }, - "create-many-unique-events": { - previousEvents: makeUniqueEvents(30), - newEvent: uniqueEvent, - expectedEvent: setCount(uniqueEvent, 1), - intervalSeconds: 5, - }, - "similar-events-should-aggregate-event": { - previousEvents: makeSimilarEvents(defaultAggregateMaxEvents-1, similarEvent, similarEvent.Message), - newEvent: similarEvent, - expectedEvent: setCount(aggregateEvent, 1), - intervalSeconds: 5, - }, - "similar-events-many-times-should-count-the-aggregate": { - previousEvents: makeSimilarEvents(defaultAggregateMaxEvents, similarEvent, similarEvent.Message), - newEvent: similarEvent, - expectedEvent: setCount(aggregateEvent, 2), - intervalSeconds: 5, - }, - "events-from-different-containers-do-not-aggregate": { - previousEvents: makeEvents(1, similarButDifferentContainerEvent), - newEvent: similarEvent, - expectedEvent: setCount(similarEvent, 1), - intervalSeconds: 5, - }, - "similar-events-whose-interval-is-greater-than-aggregate-interval-do-not-aggregate": { - previousEvents: makeSimilarEvents(defaultAggregateMaxEvents-1, similarEvent, similarEvent.Message), - newEvent: similarEvent, - expectedEvent: setCount(similarEvent, 1), - intervalSeconds: defaultAggregateIntervalInSeconds, - }, - } - - for testScenario, testInput := range scenario { - eventInterval := time.Duration(testInput.intervalSeconds) * time.Second - clock := clock.IntervalClock{Time: time.Now(), Duration: eventInterval} - correlator := NewEventCorrelator(&clock) - for i := range testInput.previousEvents { - event := testInput.previousEvents[i] - now := metav1.NewTime(clock.Now()) - event.FirstTimestamp = now - event.LastTimestamp = now - result, err := correlator.EventCorrelate(&event) - if err != nil { - t.Errorf("scenario %v: unexpected error playing back prevEvents %v", testScenario, err) - } - // if we are skipping the event, we can avoid updating state - if !result.Skip { - correlator.UpdateState(result.Event) - } - } - - // update the input to current clock value - now := metav1.NewTime(clock.Now()) - testInput.newEvent.FirstTimestamp = now - testInput.newEvent.LastTimestamp = now - result, err := correlator.EventCorrelate(&testInput.newEvent) - if err != nil { - t.Errorf("scenario %v: unexpected error correlating input event %v", testScenario, err) - } - - // verify we did not get skip from filter function unexpectedly... - if result.Skip != testInput.expectedSkip { - t.Errorf("scenario %v: expected skip %v, but got %v", testScenario, testInput.expectedSkip, result.Skip) - continue - } - - // we wanted to actually skip, so no event is needed to validate - if testInput.expectedSkip { - continue - } - - // validate event - _, err = validateEvent(testScenario, result.Event, &testInput.expectedEvent, t) - if err != nil { - t.Errorf("scenario %v: unexpected error validating result %v", testScenario, err) - } - } -} diff --git a/vendor/k8s.io/client-go/tools/remotecommand/v2_test.go b/vendor/k8s.io/client-go/tools/remotecommand/v2_test.go deleted file mode 100644 index e303f57a9e..0000000000 --- a/vendor/k8s.io/client-go/tools/remotecommand/v2_test.go +++ /dev/null @@ -1,228 +0,0 @@ -/* -Copyright 2016 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 remotecommand - -import ( - "errors" - "io" - "net/http" - "strings" - "testing" - "time" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/httpstream" - "k8s.io/apimachinery/pkg/util/wait" -) - -type fakeReader struct { - err error -} - -func (r *fakeReader) Read([]byte) (int, error) { return 0, r.err } - -type fakeWriter struct{} - -func (*fakeWriter) Write([]byte) (int, error) { return 0, nil } - -type fakeStreamCreator struct { - created map[string]bool - errors map[string]error -} - -var _ streamCreator = &fakeStreamCreator{} - -func (f *fakeStreamCreator) CreateStream(headers http.Header) (httpstream.Stream, error) { - streamType := headers.Get(v1.StreamType) - f.created[streamType] = true - return nil, f.errors[streamType] -} - -func TestV2CreateStreams(t *testing.T) { - tests := []struct { - name string - stdin bool - stdinError error - stdout bool - stdoutError error - stderr bool - stderrError error - errorError error - tty bool - expectError bool - }{ - { - name: "stdin error", - stdin: true, - stdinError: errors.New("stdin error"), - expectError: true, - }, - { - name: "stdout error", - stdout: true, - stdoutError: errors.New("stdout error"), - expectError: true, - }, - { - name: "stderr error", - stderr: true, - stderrError: errors.New("stderr error"), - expectError: true, - }, - { - name: "error stream error", - stdin: true, - stdout: true, - stderr: true, - errorError: errors.New("error stream error"), - expectError: true, - }, - { - name: "no errors", - stdin: true, - stdout: true, - stderr: true, - expectError: false, - }, - { - name: "no errors, stderr & tty set, don't expect stderr", - stdin: true, - stdout: true, - stderr: true, - tty: true, - expectError: false, - }, - } - for _, test := range tests { - conn := &fakeStreamCreator{ - created: make(map[string]bool), - errors: map[string]error{ - v1.StreamTypeStdin: test.stdinError, - v1.StreamTypeStdout: test.stdoutError, - v1.StreamTypeStderr: test.stderrError, - v1.StreamTypeError: test.errorError, - }, - } - - opts := StreamOptions{Tty: test.tty} - if test.stdin { - opts.Stdin = &fakeReader{} - } - if test.stdout { - opts.Stdout = &fakeWriter{} - } - if test.stderr { - opts.Stderr = &fakeWriter{} - } - - h := newStreamProtocolV2(opts).(*streamProtocolV2) - err := h.createStreams(conn) - - if test.expectError { - if err == nil { - t.Errorf("%s: expected error", test.name) - continue - } - if e, a := test.stdinError, err; test.stdinError != nil && e != a { - t.Errorf("%s: expected %v, got %v", test.name, e, a) - } - if e, a := test.stdoutError, err; test.stdoutError != nil && e != a { - t.Errorf("%s: expected %v, got %v", test.name, e, a) - } - if e, a := test.stderrError, err; test.stderrError != nil && e != a { - t.Errorf("%s: expected %v, got %v", test.name, e, a) - } - if e, a := test.errorError, err; test.errorError != nil && e != a { - t.Errorf("%s: expected %v, got %v", test.name, e, a) - } - continue - } - - if !test.expectError && err != nil { - t.Errorf("%s: unexpected error: %v", test.name, err) - continue - } - - if test.stdin && !conn.created[v1.StreamTypeStdin] { - t.Errorf("%s: expected stdin stream", test.name) - } - if test.stdout && !conn.created[v1.StreamTypeStdout] { - t.Errorf("%s: expected stdout stream", test.name) - } - if test.stderr { - if test.tty && conn.created[v1.StreamTypeStderr] { - t.Errorf("%s: unexpected stderr stream because tty is set", test.name) - } else if !test.tty && !conn.created[v1.StreamTypeStderr] { - t.Errorf("%s: expected stderr stream", test.name) - } - } - if !conn.created[v1.StreamTypeError] { - t.Errorf("%s: expected error stream", test.name) - } - - } -} - -func TestV2ErrorStreamReading(t *testing.T) { - tests := []struct { - name string - stream io.Reader - expectedError error - }{ - { - name: "error reading from stream", - stream: &fakeReader{errors.New("foo")}, - expectedError: errors.New("error reading from error stream: foo"), - }, - { - name: "stream returns an error", - stream: strings.NewReader("some error"), - expectedError: errors.New("error executing remote command: some error"), - }, - } - - for _, test := range tests { - h := newStreamProtocolV2(StreamOptions{}).(*streamProtocolV2) - h.errorStream = test.stream - - ch := watchErrorStream(h.errorStream, &errorDecoderV2{}) - if ch == nil { - t.Fatalf("%s: unexpected nil channel", test.name) - } - - var err error - select { - case err = <-ch: - case <-time.After(wait.ForeverTestTimeout): - t.Fatalf("%s: timed out", test.name) - } - - if test.expectedError != nil { - if err == nil { - t.Errorf("%s: expected an error", test.name) - } else if e, a := test.expectedError, err; e.Error() != a.Error() { - t.Errorf("%s: expected %q, got %q", test.name, e, a) - } - continue - } - - if test.expectedError == nil && err != nil { - t.Errorf("%s: unexpected error: %v", test.name, err) - continue - } - } -} diff --git a/vendor/k8s.io/client-go/tools/remotecommand/v4_test.go b/vendor/k8s.io/client-go/tools/remotecommand/v4_test.go deleted file mode 100644 index b8674918f2..0000000000 --- a/vendor/k8s.io/client-go/tools/remotecommand/v4_test.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright 2016 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 remotecommand - -import ( - "fmt" - "testing" -) - -func TestV4ErrorDecoder(t *testing.T) { - dec := errorDecoderV4{} - - type Test struct { - message string - err string - } - - for _, test := range []Test{ - { - message: "{}", - err: "error stream protocol error: unknown error", - }, - { - message: "{", - err: "error stream protocol error: unexpected end of JSON input in \"{\"", - }, - { - message: `{"status": "Success" }`, - err: "", - }, - { - message: `{"status": "Failure", "message": "foobar" }`, - err: "foobar", - }, - { - message: `{"status": "Failure", "message": "foobar", "reason": "NonZeroExitCode", "details": {"causes": [{"reason": "foo"}] } }`, - err: "error stream protocol error: no ExitCode cause given", - }, - { - message: `{"status": "Failure", "message": "foobar", "reason": "NonZeroExitCode", "details": {"causes": [{"reason": "ExitCode"}] } }`, - err: "error stream protocol error: invalid exit code value \"\"", - }, - { - message: `{"status": "Failure", "message": "foobar", "reason": "NonZeroExitCode", "details": {"causes": [{"reason": "ExitCode", "message": "42"}] } }`, - err: "command terminated with exit code 42", - }, - } { - err := dec.decode([]byte(test.message)) - want := test.err - if want == "" { - want = "<nil>" - } - if got := fmt.Sprintf("%v", err); got != want { - t.Errorf("wrong error for message %q: want=%q, got=%q", test.message, want, got) - } - } -} diff --git a/vendor/k8s.io/client-go/transport/cache.go b/vendor/k8s.io/client-go/transport/cache.go index 7c40848c79..83291c5753 100644 --- a/vendor/k8s.io/client-go/transport/cache.go +++ b/vendor/k8s.io/client-go/transport/cache.go @@ -44,6 +44,7 @@ type tlsCacheKey struct { certData string keyData string serverName string + dial string } func (t tlsCacheKey) String() string { @@ -51,7 +52,7 @@ func (t tlsCacheKey) String() string { if len(t.keyData) > 0 { keyText = "<redacted>" } - return fmt.Sprintf("insecure:%v, caData:%#v, certData:%#v, keyData:%s, serverName:%s", t.insecure, t.caData, t.certData, keyText, t.serverName) + return fmt.Sprintf("insecure:%v, caData:%#v, certData:%#v, keyData:%s, serverName:%s, dial:%s", t.insecure, t.caData, t.certData, keyText, t.serverName, t.dial) } func (c *tlsTransportCache) get(config *Config) (http.RoundTripper, error) { @@ -75,7 +76,7 @@ func (c *tlsTransportCache) get(config *Config) (http.RoundTripper, error) { return nil, err } // The options didn't require a custom TLS config - if tlsConfig == nil { + if tlsConfig == nil && config.Dial == nil { return http.DefaultTransport, nil } @@ -109,5 +110,6 @@ func tlsConfigKey(c *Config) (tlsCacheKey, error) { certData: string(c.TLS.CertData), keyData: string(c.TLS.KeyData), serverName: c.TLS.ServerName, + dial: fmt.Sprintf("%p", c.Dial), }, nil } diff --git a/vendor/k8s.io/client-go/transport/cache_test.go b/vendor/k8s.io/client-go/transport/cache_test.go deleted file mode 100644 index 81f428de0e..0000000000 --- a/vendor/k8s.io/client-go/transport/cache_test.go +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package transport - -import ( - "net/http" - "testing" -) - -func TestTLSConfigKey(t *testing.T) { - // Make sure config fields that don't affect the tls config don't affect the cache key - identicalConfigurations := map[string]*Config{ - "empty": {}, - "basic": {Username: "bob", Password: "password"}, - "bearer": {BearerToken: "token"}, - "user agent": {UserAgent: "useragent"}, - "transport": {Transport: http.DefaultTransport}, - "wrap transport": {WrapTransport: func(http.RoundTripper) http.RoundTripper { return nil }}, - } - for nameA, valueA := range identicalConfigurations { - for nameB, valueB := range identicalConfigurations { - keyA, err := tlsConfigKey(valueA) - if err != nil { - t.Errorf("Unexpected error for %q: %v", nameA, err) - continue - } - keyB, err := tlsConfigKey(valueB) - if err != nil { - t.Errorf("Unexpected error for %q: %v", nameB, err) - continue - } - if keyA != keyB { - t.Errorf("Expected identical cache keys for %q and %q, got:\n\t%s\n\t%s", nameA, nameB, keyA, keyB) - continue - } - } - } - - // Make sure config fields that affect the tls config affect the cache key - uniqueConfigurations := map[string]*Config{ - "no tls": {}, - "insecure": {TLS: TLSConfig{Insecure: true}}, - "cadata 1": {TLS: TLSConfig{CAData: []byte{1}}}, - "cadata 2": {TLS: TLSConfig{CAData: []byte{2}}}, - "cert 1, key 1": { - TLS: TLSConfig{ - CertData: []byte{1}, - KeyData: []byte{1}, - }, - }, - "cert 1, key 1, servername 1": { - TLS: TLSConfig{ - CertData: []byte{1}, - KeyData: []byte{1}, - ServerName: "1", - }, - }, - "cert 1, key 1, servername 2": { - TLS: TLSConfig{ - CertData: []byte{1}, - KeyData: []byte{1}, - ServerName: "2", - }, - }, - "cert 1, key 2": { - TLS: TLSConfig{ - CertData: []byte{1}, - KeyData: []byte{2}, - }, - }, - "cert 2, key 1": { - TLS: TLSConfig{ - CertData: []byte{2}, - KeyData: []byte{1}, - }, - }, - "cert 2, key 2": { - TLS: TLSConfig{ - CertData: []byte{2}, - KeyData: []byte{2}, - }, - }, - "cadata 1, cert 1, key 1": { - TLS: TLSConfig{ - CAData: []byte{1}, - CertData: []byte{1}, - KeyData: []byte{1}, - }, - }, - } - for nameA, valueA := range uniqueConfigurations { - for nameB, valueB := range uniqueConfigurations { - // Don't compare to ourselves - if nameA == nameB { - continue - } - - keyA, err := tlsConfigKey(valueA) - if err != nil { - t.Errorf("Unexpected error for %q: %v", nameA, err) - continue - } - keyB, err := tlsConfigKey(valueB) - if err != nil { - t.Errorf("Unexpected error for %q: %v", nameB, err) - continue - } - if keyA == keyB { - t.Errorf("Expected unique cache keys for %q and %q, got:\n\t%s\n\t%s", nameA, nameB, keyA, keyB) - continue - } - } - } -} diff --git a/vendor/k8s.io/client-go/transport/round_trippers_test.go b/vendor/k8s.io/client-go/transport/round_trippers_test.go deleted file mode 100644 index d5ffc6bde3..0000000000 --- a/vendor/k8s.io/client-go/transport/round_trippers_test.go +++ /dev/null @@ -1,218 +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 transport - -import ( - "net/http" - "reflect" - "strings" - "testing" -) - -type testRoundTripper struct { - Request *http.Request - Response *http.Response - Err error -} - -func (rt *testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { - rt.Request = req - return rt.Response, rt.Err -} - -func TestBearerAuthRoundTripper(t *testing.T) { - rt := &testRoundTripper{} - req := &http.Request{} - NewBearerAuthRoundTripper("test", rt).RoundTrip(req) - if rt.Request == nil { - t.Fatalf("unexpected nil request: %v", rt) - } - if rt.Request == req { - t.Fatalf("round tripper should have copied request object: %#v", rt.Request) - } - if rt.Request.Header.Get("Authorization") != "Bearer test" { - t.Errorf("unexpected authorization header: %#v", rt.Request) - } -} - -func TestBasicAuthRoundTripper(t *testing.T) { - for n, tc := range map[string]struct { - user string - pass string - }{ - "basic": {user: "user", pass: "pass"}, - "no pass": {user: "user"}, - } { - rt := &testRoundTripper{} - req := &http.Request{} - NewBasicAuthRoundTripper(tc.user, tc.pass, rt).RoundTrip(req) - if rt.Request == nil { - t.Fatalf("%s: unexpected nil request: %v", n, rt) - } - if rt.Request == req { - t.Fatalf("%s: round tripper should have copied request object: %#v", n, rt.Request) - } - if user, pass, found := rt.Request.BasicAuth(); !found || user != tc.user || pass != tc.pass { - t.Errorf("%s: unexpected authorization header: %#v", n, rt.Request) - } - } -} - -func TestUserAgentRoundTripper(t *testing.T) { - rt := &testRoundTripper{} - req := &http.Request{ - Header: make(http.Header), - } - req.Header.Set("User-Agent", "other") - NewUserAgentRoundTripper("test", rt).RoundTrip(req) - if rt.Request == nil { - t.Fatalf("unexpected nil request: %v", rt) - } - if rt.Request != req { - t.Fatalf("round tripper should not have copied request object: %#v", rt.Request) - } - if rt.Request.Header.Get("User-Agent") != "other" { - t.Errorf("unexpected user agent header: %#v", rt.Request) - } - - req = &http.Request{} - NewUserAgentRoundTripper("test", rt).RoundTrip(req) - if rt.Request == nil { - t.Fatalf("unexpected nil request: %v", rt) - } - if rt.Request == req { - t.Fatalf("round tripper should have copied request object: %#v", rt.Request) - } - if rt.Request.Header.Get("User-Agent") != "test" { - t.Errorf("unexpected user agent header: %#v", rt.Request) - } -} - -func TestImpersonationRoundTripper(t *testing.T) { - tcs := []struct { - name string - impersonationConfig ImpersonationConfig - expected map[string][]string - }{ - { - name: "all", - impersonationConfig: ImpersonationConfig{ - UserName: "user", - Groups: []string{"one", "two"}, - Extra: map[string][]string{ - "first": {"A", "a"}, - "second": {"B", "b"}, - }, - }, - expected: map[string][]string{ - ImpersonateUserHeader: {"user"}, - ImpersonateGroupHeader: {"one", "two"}, - ImpersonateUserExtraHeaderPrefix + "First": {"A", "a"}, - ImpersonateUserExtraHeaderPrefix + "Second": {"B", "b"}, - }, - }, - } - - for _, tc := range tcs { - rt := &testRoundTripper{} - req := &http.Request{ - Header: make(http.Header), - } - NewImpersonatingRoundTripper(tc.impersonationConfig, rt).RoundTrip(req) - - for k, v := range rt.Request.Header { - expected, ok := tc.expected[k] - if !ok { - t.Errorf("%v missing %v=%v", tc.name, k, v) - continue - } - if !reflect.DeepEqual(expected, v) { - t.Errorf("%v expected %v: %v, got %v", tc.name, k, expected, v) - } - } - for k, v := range tc.expected { - expected, ok := rt.Request.Header[k] - if !ok { - t.Errorf("%v missing %v=%v", tc.name, k, v) - continue - } - if !reflect.DeepEqual(expected, v) { - t.Errorf("%v expected %v: %v, got %v", tc.name, k, expected, v) - } - } - } -} - -func TestAuthProxyRoundTripper(t *testing.T) { - for n, tc := range map[string]struct { - username string - groups []string - extra map[string][]string - }{ - "allfields": { - username: "user", - groups: []string{"groupA", "groupB"}, - extra: map[string][]string{ - "one": {"alpha", "bravo"}, - "two": {"charlie", "delta"}, - }, - }, - } { - rt := &testRoundTripper{} - req := &http.Request{} - NewAuthProxyRoundTripper(tc.username, tc.groups, tc.extra, rt).RoundTrip(req) - if rt.Request == nil { - t.Errorf("%s: unexpected nil request: %v", n, rt) - continue - } - if rt.Request == req { - t.Errorf("%s: round tripper should have copied request object: %#v", n, rt.Request) - continue - } - - actualUsernames, ok := rt.Request.Header["X-Remote-User"] - if !ok { - t.Errorf("%s missing value", n) - continue - } - if e, a := []string{tc.username}, actualUsernames; !reflect.DeepEqual(e, a) { - t.Errorf("%s expected %v, got %v", n, e, a) - continue - } - actualGroups, ok := rt.Request.Header["X-Remote-Group"] - if !ok { - t.Errorf("%s missing value", n) - continue - } - if e, a := tc.groups, actualGroups; !reflect.DeepEqual(e, a) { - t.Errorf("%s expected %v, got %v", n, e, a) - continue - } - - actualExtra := map[string][]string{} - for key, values := range rt.Request.Header { - if strings.HasPrefix(strings.ToLower(key), strings.ToLower("X-Remote-Extra-")) { - extraKey := strings.ToLower(key[len("X-Remote-Extra-"):]) - actualExtra[extraKey] = append(actualExtra[key], values...) - } - } - if e, a := tc.extra, actualExtra; !reflect.DeepEqual(e, a) { - t.Errorf("%s expected %v, got %v", n, e, a) - continue - } - } -} diff --git a/vendor/k8s.io/client-go/transport/transport.go b/vendor/k8s.io/client-go/transport/transport.go index 15be0a3e6b..c2bb7ae5e4 100644 --- a/vendor/k8s.io/client-go/transport/transport.go +++ b/vendor/k8s.io/client-go/transport/transport.go @@ -52,7 +52,7 @@ func New(config *Config) (http.RoundTripper, error) { // TLSConfigFor returns a tls.Config that will provide the transport level security defined // by the provided Config. Will return nil if no transport level security is requested. func TLSConfigFor(c *Config) (*tls.Config, error) { - if !(c.HasCA() || c.HasCertAuth() || c.TLS.Insecure) { + if !(c.HasCA() || c.HasCertAuth() || c.TLS.Insecure || len(c.TLS.ServerName) > 0) { return nil, nil } if c.HasCA() && c.TLS.Insecure { diff --git a/vendor/k8s.io/client-go/transport/transport_test.go b/vendor/k8s.io/client-go/transport/transport_test.go deleted file mode 100644 index 4d2d78f86c..0000000000 --- a/vendor/k8s.io/client-go/transport/transport_test.go +++ /dev/null @@ -1,204 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package transport - -import ( - "net/http" - "testing" -) - -const ( - rootCACert = `-----BEGIN CERTIFICATE----- -MIIC4DCCAcqgAwIBAgIBATALBgkqhkiG9w0BAQswIzEhMB8GA1UEAwwYMTAuMTMu -MTI5LjEwNkAxNDIxMzU5MDU4MB4XDTE1MDExNTIxNTczN1oXDTE2MDExNTIxNTcz -OFowIzEhMB8GA1UEAwwYMTAuMTMuMTI5LjEwNkAxNDIxMzU5MDU4MIIBIjANBgkq -hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAunDRXGwsiYWGFDlWH6kjGun+PshDGeZX -xtx9lUnL8pIRWH3wX6f13PO9sktaOWW0T0mlo6k2bMlSLlSZgG9H6og0W6gLS3vq -s4VavZ6DbXIwemZG2vbRwsvR+t4G6Nbwelm6F8RFnA1Fwt428pavmNQ/wgYzo+T1 -1eS+HiN4ACnSoDSx3QRWcgBkB1g6VReofVjx63i0J+w8Q/41L9GUuLqquFxu6ZnH -60vTB55lHgFiDLjA1FkEz2dGvGh/wtnFlRvjaPC54JH2K1mPYAUXTreoeJtLJKX0 -ycoiyB24+zGCniUmgIsmQWRPaOPircexCp1BOeze82BT1LCZNTVaxQIDAQABoyMw -ITAOBgNVHQ8BAf8EBAMCAKQwDwYDVR0TAQH/BAUwAwEB/zALBgkqhkiG9w0BAQsD -ggEBADMxsUuAFlsYDpF4fRCzXXwrhbtj4oQwcHpbu+rnOPHCZupiafzZpDu+rw4x -YGPnCb594bRTQn4pAu3Ac18NbLD5pV3uioAkv8oPkgr8aUhXqiv7KdDiaWm6sbAL -EHiXVBBAFvQws10HMqMoKtO8f1XDNAUkWduakR/U6yMgvOPwS7xl0eUTqyRB6zGb -K55q2dejiFWaFqB/y78txzvz6UlOZKE44g2JAVoJVM6kGaxh33q8/FmrL4kuN3ut -W+MmJCVDvd4eEqPwbp7146ZWTqpIJ8lvA6wuChtqV8lhAPka2hD/LMqY8iXNmfXD -uml0obOEy+ON91k+SWTJ3ggmF/U= ------END CERTIFICATE-----` - - certData = `-----BEGIN CERTIFICATE----- -MIIC6jCCAdSgAwIBAgIBCzALBgkqhkiG9w0BAQswIzEhMB8GA1UEAwwYMTAuMTMu -MTI5LjEwNkAxNDIxMzU5MDU4MB4XDTE1MDExNTIyMDEzMVoXDTE2MDExNTIyMDEz -MlowGzEZMBcGA1UEAxMQb3BlbnNoaWZ0LWNsaWVudDCCASIwDQYJKoZIhvcNAQEB -BQADggEPADCCAQoCggEBAKtdhz0+uCLXw5cSYns9rU/XifFSpb/x24WDdrm72S/v -b9BPYsAStiP148buylr1SOuNi8sTAZmlVDDIpIVwMLff+o2rKYDicn9fjbrTxTOj -lI4pHJBH+JU3AJ0tbajupioh70jwFS0oYpwtneg2zcnE2Z4l6mhrj2okrc5Q1/X2 -I2HChtIU4JYTisObtin10QKJX01CLfYXJLa8upWzKZ4/GOcHG+eAV3jXWoXidtjb -1Usw70amoTZ6mIVCkiu1QwCoa8+ycojGfZhvqMsAp1536ZcCul+Na+AbCv4zKS7F -kQQaImVrXdUiFansIoofGlw/JNuoKK6ssVpS5Ic3pgcCAwEAAaM1MDMwDgYDVR0P -AQH/BAQDAgCgMBMGA1UdJQQMMAoGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAwCwYJ -KoZIhvcNAQELA4IBAQCKLREH7bXtXtZ+8vI6cjD7W3QikiArGqbl36bAhhWsJLp/ -p/ndKz39iFNaiZ3GlwIURWOOKx3y3GA0x9m8FR+Llthf0EQ8sUjnwaknWs0Y6DQ3 -jjPFZOpV3KPCFrdMJ3++E3MgwFC/Ih/N2ebFX9EcV9Vcc6oVWMdwT0fsrhu683rq -6GSR/3iVX1G/pmOiuaR0fNUaCyCfYrnI4zHBDgSfnlm3vIvN2lrsR/DQBakNL8DJ -HBgKxMGeUPoneBv+c8DMXIL0EhaFXRlBv9QW45/GiAIOuyFJ0i6hCtGZpJjq4OpQ -BRjCI+izPzFTjsxD4aORE+WOkyWFCGPWKfNejfw0 ------END CERTIFICATE-----` - - keyData = `-----BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAq12HPT64ItfDlxJiez2tT9eJ8VKlv/HbhYN2ubvZL+9v0E9i -wBK2I/Xjxu7KWvVI642LyxMBmaVUMMikhXAwt9/6jaspgOJyf1+NutPFM6OUjikc -kEf4lTcAnS1tqO6mKiHvSPAVLShinC2d6DbNycTZniXqaGuPaiStzlDX9fYjYcKG -0hTglhOKw5u2KfXRAolfTUIt9hcktry6lbMpnj8Y5wcb54BXeNdaheJ22NvVSzDv -RqahNnqYhUKSK7VDAKhrz7JyiMZ9mG+oywCnXnfplwK6X41r4BsK/jMpLsWRBBoi -ZWtd1SIVqewiih8aXD8k26gorqyxWlLkhzemBwIDAQABAoIBAD2XYRs3JrGHQUpU -FkdbVKZkvrSY0vAZOqBTLuH0zUv4UATb8487anGkWBjRDLQCgxH+jucPTrztekQK -aW94clo0S3aNtV4YhbSYIHWs1a0It0UdK6ID7CmdWkAj6s0T8W8lQT7C46mWYVLm -5mFnCTHi6aB42jZrqmEpC7sivWwuU0xqj3Ml8kkxQCGmyc9JjmCB4OrFFC8NNt6M -ObvQkUI6Z3nO4phTbpxkE1/9dT0MmPIF7GhHVzJMS+EyyRYUDllZ0wvVSOM3qZT0 -JMUaBerkNwm9foKJ1+dv2nMKZZbJajv7suUDCfU44mVeaEO+4kmTKSGCGjjTBGkr -7L1ySDECgYEA5ElIMhpdBzIivCuBIH8LlUeuzd93pqssO1G2Xg0jHtfM4tz7fyeI -cr90dc8gpli24dkSxzLeg3Tn3wIj/Bu64m2TpZPZEIlukYvgdgArmRIPQVxerYey -OkrfTNkxU1HXsYjLCdGcGXs5lmb+K/kuTcFxaMOs7jZi7La+jEONwf8CgYEAwCs/ -rUOOA0klDsWWisbivOiNPII79c9McZCNBqncCBfMUoiGe8uWDEO4TFHN60vFuVk9 -8PkwpCfvaBUX+ajvbafIfHxsnfk1M04WLGCeqQ/ym5Q4sQoQOcC1b1y9qc/xEWfg -nIUuia0ukYRpl7qQa3tNg+BNFyjypW8zukUAC/kCgYB1/Kojuxx5q5/oQVPrx73k -2bevD+B3c+DYh9MJqSCNwFtUpYIWpggPxoQan4LwdsmO0PKzocb/ilyNFj4i/vII -NToqSc/WjDFpaDIKyuu9oWfhECye45NqLWhb/6VOuu4QA/Nsj7luMhIBehnEAHW+ -GkzTKM8oD1PxpEG3nPKXYQKBgQC6AuMPRt3XBl1NkCrpSBy/uObFlFaP2Enpf39S -3OZ0Gv0XQrnSaL1kP8TMcz68rMrGX8DaWYsgytstR4W+jyy7WvZwsUu+GjTJ5aMG -77uEcEBpIi9CBzivfn7hPccE8ZgqPf+n4i6q66yxBJflW5xhvafJqDtW2LcPNbW/ -bvzdmQKBgExALRUXpq+5dbmkdXBHtvXdRDZ6rVmrnjy4nI5bPw+1GqQqk6uAR6B/ -F6NmLCQOO4PDG/cuatNHIr2FrwTmGdEL6ObLUGWn9Oer9gJhHVqqsY5I4sEPo4XX -stR0Yiw0buV6DL/moUO0HIM9Bjh96HJp+LxiIS6UCdIhMPp5HoQa ------END RSA PRIVATE KEY-----` -) - -func TestNew(t *testing.T) { - testCases := map[string]struct { - Config *Config - Err bool - TLS bool - Default bool - }{ - "default transport": { - Default: true, - Config: &Config{}, - }, - - "ca transport": { - TLS: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - }, - }, - }, - "bad ca file transport": { - Err: true, - Config: &Config{ - TLS: TLSConfig{ - CAFile: "invalid file", - }, - }, - }, - "ca data overriding bad ca file transport": { - TLS: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - CAFile: "invalid file", - }, - }, - }, - - "cert transport": { - TLS: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - CertData: []byte(certData), - KeyData: []byte(keyData), - }, - }, - }, - "bad cert data transport": { - Err: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - CertData: []byte(certData), - KeyData: []byte("bad key data"), - }, - }, - }, - "bad file cert transport": { - Err: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - CertData: []byte(certData), - KeyFile: "invalid file", - }, - }, - }, - "key data overriding bad file cert transport": { - TLS: true, - Config: &Config{ - TLS: TLSConfig{ - CAData: []byte(rootCACert), - CertData: []byte(certData), - KeyData: []byte(keyData), - KeyFile: "invalid file", - }, - }, - }, - } - for k, testCase := range testCases { - transport, err := New(testCase.Config) - switch { - case testCase.Err && err == nil: - t.Errorf("%s: unexpected non-error", k) - continue - case !testCase.Err && err != nil: - t.Errorf("%s: unexpected error: %v", k, err) - continue - } - - switch { - case testCase.Default && transport != http.DefaultTransport: - t.Errorf("%s: expected the default transport, got %#v", k, transport) - continue - case !testCase.Default && transport == http.DefaultTransport: - t.Errorf("%s: expected non-default transport, got %#v", k, transport) - continue - } - - // We only know how to check TLSConfig on http.Transports - if transport, ok := transport.(*http.Transport); ok { - switch { - case testCase.TLS && transport.TLSClientConfig == nil: - t.Errorf("%s: expected TLSClientConfig, got %#v", k, transport) - continue - case !testCase.TLS && transport.TLSClientConfig != nil: - t.Errorf("%s: expected no TLSClientConfig, got %#v", k, transport) - continue - } - } - } -} diff --git a/vendor/k8s.io/client-go/util/buffer/ring_growing_test.go b/vendor/k8s.io/client-go/util/buffer/ring_growing_test.go deleted file mode 100644 index 231b836c09..0000000000 --- a/vendor/k8s.io/client-go/util/buffer/ring_growing_test.go +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright 2017 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 buffer - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGrowth(t *testing.T) { - t.Parallel() - x := 10 - g := NewRingGrowing(1) - for i := 0; i < x; i++ { - assert.Equal(t, i, g.readable) - g.WriteOne(i) - } - read := 0 - for g.readable > 0 { - v, ok := g.ReadOne() - assert.True(t, ok) - assert.Equal(t, read, v) - read++ - } - assert.Equalf(t, x, read, "expected to have read %d items: %d", x, read) - assert.Zerof(t, g.readable, "expected readable to be zero: %d", g.readable) - assert.Equalf(t, g.n, 16, "expected N to be 16: %d", g.n) -} - -func TestEmpty(t *testing.T) { - t.Parallel() - g := NewRingGrowing(1) - _, ok := g.ReadOne() - assert.False(t, ok) -} diff --git a/vendor/k8s.io/client-go/util/cert/csr_test.go b/vendor/k8s.io/client-go/util/cert/csr_test.go deleted file mode 100644 index ed28f021ea..0000000000 --- a/vendor/k8s.io/client-go/util/cert/csr_test.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2016 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 cert - -import ( - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "io/ioutil" - "net" - "testing" -) - -func TestMakeCSR(t *testing.T) { - keyFile := "testdata/dontUseThisKey.pem" - subject := &pkix.Name{ - CommonName: "kube-worker", - } - dnsSANs := []string{"localhost"} - ipSANs := []net.IP{net.ParseIP("127.0.0.1")} - - keyData, err := ioutil.ReadFile(keyFile) - if err != nil { - t.Fatal(err) - } - key, err := ParsePrivateKeyPEM(keyData) - if err != nil { - t.Fatal(err) - } - csrPEM, err := MakeCSR(key, subject, dnsSANs, ipSANs) - if err != nil { - t.Error(err) - } - csrBlock, rest := pem.Decode(csrPEM) - if csrBlock == nil { - t.Error("Unable to decode MakeCSR result.") - } - if len(rest) != 0 { - t.Error("Found more than one PEM encoded block in the result.") - } - if csrBlock.Type != CertificateRequestBlockType { - t.Errorf("Found block type %q, wanted 'CERTIFICATE REQUEST'", csrBlock.Type) - } - csr, err := x509.ParseCertificateRequest(csrBlock.Bytes) - if err != nil { - t.Errorf("Found %v parsing MakeCSR result as a CertificateRequest.", err) - } - if csr.Subject.CommonName != subject.CommonName { - t.Errorf("Wanted %v, got %v", subject, csr.Subject) - } - if len(csr.DNSNames) != 1 { - t.Errorf("Wanted 1 DNS name in the result, got %d", len(csr.DNSNames)) - } else if csr.DNSNames[0] != dnsSANs[0] { - t.Errorf("Wanted %v, got %v", dnsSANs[0], csr.DNSNames[0]) - } - if len(csr.IPAddresses) != 1 { - t.Errorf("Wanted 1 IP address in the result, got %d", len(csr.IPAddresses)) - } else if csr.IPAddresses[0].String() != ipSANs[0].String() { - t.Errorf("Wanted %v, got %v", ipSANs[0], csr.IPAddresses[0]) - } -} diff --git a/vendor/k8s.io/client-go/util/cert/pem_test.go b/vendor/k8s.io/client-go/util/cert/pem_test.go deleted file mode 100644 index de3ce52537..0000000000 --- a/vendor/k8s.io/client-go/util/cert/pem_test.go +++ /dev/null @@ -1,197 +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 cert - -import ( - "io/ioutil" - "os" - "testing" -) - -const ( - // rsaPrivateKey is a RSA Private Key in PKCS#1 format - // openssl genrsa -out rsa2048.pem 2048 - rsaPrivateKey = `-----BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEA92mVjhBKOFsdxFzb/Pjq+7b5TJlODAdY5hK+WxLZTIrfhDPq -FWrGKdjSNiHbXrdEtwJh9V+RqPZVSN3aWy1224RgkyNdMJsXhJKuCC24ZKY8SXtW -xuTYmMRaMnCsv6QBGRTIbZ2EFbAObVM7lDyv1VqY3amZIWFQMlZ9CNpxDSPa5yi4 -3gopbXkne0oGNmey9X0qtpk7NMZIgAL6Zz4rZ30bcfC2ag6RLOFI2E/c4n8c38R8 -9MfXfLkj8/Cxo4JfI9NvRCpPOpFO8d/ZtWVUuIrBQN+Y7tkN2T60Qq/TkKXUrhDe -fwlTlktZVJ/GztLYU41b2GcWsh/XO+PH831rmwIDAQABAoIBAQCC9c6GDjVbM0/E -WurPMusfJjE7zII1d8YkspM0HfwLug6qKdikUYpnKC/NG4rEzfl/bbFwco/lgc6O -7W/hh2U8uQttlvCDA/Uk5YddKOZL0Hpk4vaB/SxxYK3luSKXpjY2knutGg2KdVCN -qdsFkkH4iyYTXuyBcMNEgedZQldI/kEujIH/L7FE+DF5TMzT4lHhozDoG+fy564q -qVGUZXJn0ubc3GaPn2QOLNNM44sfYA4UJCpKBXPu85bvNObjxVQO4WqwwxU1vRnL -UUsaGaelhSVJCo0dVPRvrfPPKZ09HTwpy40EkgQo6VriFc1EBoQDjENLbAJv9OfQ -aCc9wiZhAoGBAP/8oEy48Zbb0P8Vdy4djf5tfBW8yXFLWzXewJ4l3itKS1r42nbX -9q3cJsgRTQm8uRcMIpWxsc3n6zG+lREvTkoTB3ViI7+uQPiqA+BtWyNy7jzufFke -ONKZfg7QxxmYRWZBRnoNGNbMpNeERuLmhvQuom9D1WbhzAYJbfs/O4WTAoGBAPds -2FNDU0gaesFDdkIUGq1nIJqRQDW485LXZm4pFqBFxdOpbdWRuYT2XZjd3fD0XY98 -Nhkpb7NTMCuK3BdKcqIptt+cK+quQgYid0hhhgZbpCQ5AL6c6KgyjgpYlh2enzU9 -Zo3yg8ej1zbbA11sBlhX+5iO2P1u5DG+JHLwUUbZAoGAUwaU102EzfEtsA4+QW7E -hyjrfgFlNKHES4yb3K9bh57pIfBkqvcQwwMMcQdrfSUAw0DkVrjzel0mI1Q09QXq -1ould6UFAz55RC2gZEITtUOpkYmoOx9aPrQZ9qQwb1S77ZZuTVfCHqjxLhVxCFbM -npYhiQTvShciHTMhwMOZgpECgYAVV5EtVXBYltgh1YTc3EkUzgF087R7LdHsx6Gx -POATwRD4WfP8aQ58lpeqOPEM+LcdSlSMRRO6fyF3kAm+BJDwxfJdRWZQXumZB94M -I0VhRQRaj4Qt7PDwmTPBVrTUJzuKZxpyggm17b8Bn1Ch/VBqzGQKW8AB1E/grosM -UwhfuQKBgQC2JO/iqTQScHClf0qlItCJsBuVukFmSAVCkpOD8YdbdlPdOOwSk1wQ -C0eAlsC3BCMvkpidKQmra6IqIrvTGI6EFgkrb3aknWdup2w8j2udYCNqyE3W+fVe -p8FdYQ1FkACQ+daO5VlClL/9l0sGjKXlNKbpmJ2H4ngZmXj5uGmxuQ== ------END RSA PRIVATE KEY-----` - - // rsaPublicKey is a RSA Public Key in PEM encoded format - // openssl rsa -in rsa2048.pem -pubout -out rsa2048pub.pem - rsaPublicKey = `-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA92mVjhBKOFsdxFzb/Pjq -+7b5TJlODAdY5hK+WxLZTIrfhDPqFWrGKdjSNiHbXrdEtwJh9V+RqPZVSN3aWy12 -24RgkyNdMJsXhJKuCC24ZKY8SXtWxuTYmMRaMnCsv6QBGRTIbZ2EFbAObVM7lDyv -1VqY3amZIWFQMlZ9CNpxDSPa5yi43gopbXkne0oGNmey9X0qtpk7NMZIgAL6Zz4r -Z30bcfC2ag6RLOFI2E/c4n8c38R89MfXfLkj8/Cxo4JfI9NvRCpPOpFO8d/ZtWVU -uIrBQN+Y7tkN2T60Qq/TkKXUrhDefwlTlktZVJ/GztLYU41b2GcWsh/XO+PH831r -mwIDAQAB ------END PUBLIC KEY-----` - - // certificate is an x509 certificate in PEM encoded format - // openssl req -new -key rsa2048.pem -sha256 -nodes -x509 -days 1826 -out x509certificate.pem -subj "/C=US/CN=not-valid" - certificate = `-----BEGIN CERTIFICATE----- -MIIDFTCCAf2gAwIBAgIJAN8B8NOwtiUCMA0GCSqGSIb3DQEBCwUAMCExCzAJBgNV -BAYTAlVTMRIwEAYDVQQDDAlub3QtdmFsaWQwHhcNMTcwMzIyMDI1NjM2WhcNMjIw -MzIyMDI1NjM2WjAhMQswCQYDVQQGEwJVUzESMBAGA1UEAwwJbm90LXZhbGlkMIIB -IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA92mVjhBKOFsdxFzb/Pjq+7b5 -TJlODAdY5hK+WxLZTIrfhDPqFWrGKdjSNiHbXrdEtwJh9V+RqPZVSN3aWy1224Rg -kyNdMJsXhJKuCC24ZKY8SXtWxuTYmMRaMnCsv6QBGRTIbZ2EFbAObVM7lDyv1VqY -3amZIWFQMlZ9CNpxDSPa5yi43gopbXkne0oGNmey9X0qtpk7NMZIgAL6Zz4rZ30b -cfC2ag6RLOFI2E/c4n8c38R89MfXfLkj8/Cxo4JfI9NvRCpPOpFO8d/ZtWVUuIrB -QN+Y7tkN2T60Qq/TkKXUrhDefwlTlktZVJ/GztLYU41b2GcWsh/XO+PH831rmwID -AQABo1AwTjAdBgNVHQ4EFgQU1I5GfinLF7ta+dBJ6UWcrYaexLswHwYDVR0jBBgw -FoAU1I5GfinLF7ta+dBJ6UWcrYaexLswDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B -AQsFAAOCAQEAUl0wUD4y41juHFOVMYiziPYr1ShSpQXdwp8FfaHrzI5hsr8UMe8D -dzb9QzZ4bx3yZhiG3ahrSBh956thMTHrKTEwAfJIEXI4cuSVWQAaOJ4Em5SDFxQe -d0E6Ui2nGh1SFGF7oyuEXyzqgRMWFNDFw9HLUNgXaO18Zfouw8+K0BgbfEWEcSi1 -JLQbyhCjz088gltrliQGPWDFAg9cHBKtJhuTzZkvuqK1CLEmBhtzP1zFiGBfOJc8 -v+aKjAwrPUNX11cXOCPxBv2qXMetxaovBem6AI2hvypCInXaVQfP+yOLubzlTDjS -Y708SlY38hmS1uTwDpyLOn8AKkZ8jtx75g== ------END CERTIFICATE-----` - - // ecdsaPrivateKeyWithParams is a ECDSA Private Key with included EC Parameters block - // openssl ecparam -name prime256v1 -genkey -out ecdsa256params.pem - ecdsaPrivateKeyWithParams = `-----BEGIN EC PARAMETERS----- -BggqhkjOPQMBBw== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIAwSOWQqlMTZNqNF7tgua812Jxib1DVOgb2pHHyIEyNNoAoGCCqGSM49 -AwEHoUQDQgAEyxYNrs6a6tsNCFNYn+l+JDUZ0PnUZbcsDgJn2O62D1se8M5iQ5rY -iIv6RpxE3VHvlHEIvYgCZkG0jHszTUopBg== ------END EC PRIVATE KEY-----` - - // ecdsaPrivateKey is a ECDSA Private Key in ASN.1 format - // openssl ecparam -name prime256v1 -genkey -noout -out ecdsa256.pem - ecdsaPrivateKey = `-----BEGIN EC PRIVATE KEY----- -MHcCAQEEIP6Qw6dHDiLsSnLXUhQVTPE0fTQQrj3XSbiQAZPXnk5+oAoGCCqGSM49 -AwEHoUQDQgAEZZzi1u5f2/AEGFI/HYUhU+u6cTK1q2bbtE7r1JMK+/sQA5sNAp+7 -Vdc3psr1OaNzyTyuhTECyRdFKXm63cMnGg== ------END EC PRIVATE KEY-----` - - // ecdsaPublicKey is a ECDSA Public Key in PEM encoded format - // openssl ec -in ecdsa256.pem -pubout -out ecdsa256pub.pem - ecdsaPublicKey = `-----BEGIN PUBLIC KEY----- -MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZZzi1u5f2/AEGFI/HYUhU+u6cTK1 -q2bbtE7r1JMK+/sQA5sNAp+7Vdc3psr1OaNzyTyuhTECyRdFKXm63cMnGg== ------END PUBLIC KEY-----` -) - -func TestReadPrivateKey(t *testing.T) { - f, err := ioutil.TempFile("", "") - if err != nil { - t.Fatalf("error creating tmpfile: %v", err) - } - defer os.Remove(f.Name()) - - if _, err := PrivateKeyFromFile(f.Name()); err == nil { - t.Fatalf("Expected error reading key from empty file, got none") - } - - if err := ioutil.WriteFile(f.Name(), []byte(rsaPrivateKey), os.FileMode(0600)); err != nil { - t.Fatalf("error writing private key to tmpfile: %v", err) - } - if _, err := PrivateKeyFromFile(f.Name()); err != nil { - t.Fatalf("error reading private RSA key: %v", err) - } - - if err := ioutil.WriteFile(f.Name(), []byte(ecdsaPrivateKey), os.FileMode(0600)); err != nil { - t.Fatalf("error writing private key to tmpfile: %v", err) - } - if _, err := PrivateKeyFromFile(f.Name()); err != nil { - t.Fatalf("error reading private ECDSA key: %v", err) - } - - if err := ioutil.WriteFile(f.Name(), []byte(ecdsaPrivateKeyWithParams), os.FileMode(0600)); err != nil { - t.Fatalf("error writing private key to tmpfile: %v", err) - } - if _, err := PrivateKeyFromFile(f.Name()); err != nil { - t.Fatalf("error reading private ECDSA key with params: %v", err) - } -} - -func TestReadPublicKeys(t *testing.T) { - f, err := ioutil.TempFile("", "") - if err != nil { - t.Fatalf("error creating tmpfile: %v", err) - } - defer os.Remove(f.Name()) - - if _, err := PublicKeysFromFile(f.Name()); err == nil { - t.Fatalf("Expected error reading keys from empty file, got none") - } - - if err := ioutil.WriteFile(f.Name(), []byte(rsaPublicKey), os.FileMode(0600)); err != nil { - t.Fatalf("error writing public key to tmpfile: %v", err) - } - if keys, err := PublicKeysFromFile(f.Name()); err != nil { - t.Fatalf("error reading RSA public key: %v", err) - } else if len(keys) != 1 { - t.Fatalf("expected 1 key, got %d", len(keys)) - } - - if err := ioutil.WriteFile(f.Name(), []byte(ecdsaPublicKey), os.FileMode(0600)); err != nil { - t.Fatalf("error writing public key to tmpfile: %v", err) - } - if keys, err := PublicKeysFromFile(f.Name()); err != nil { - t.Fatalf("error reading ECDSA public key: %v", err) - } else if len(keys) != 1 { - t.Fatalf("expected 1 key, got %d", len(keys)) - } - - if err := ioutil.WriteFile(f.Name(), []byte(rsaPublicKey+"\n"+ecdsaPublicKey), os.FileMode(0600)); err != nil { - t.Fatalf("error writing public key to tmpfile: %v", err) - } - if keys, err := PublicKeysFromFile(f.Name()); err != nil { - t.Fatalf("error reading combined RSA/ECDSA public key file: %v", err) - } else if len(keys) != 2 { - t.Fatalf("expected 2 keys, got %d", len(keys)) - } - - if err := ioutil.WriteFile(f.Name(), []byte(certificate), os.FileMode(0600)); err != nil { - t.Fatalf("error writing certificate to tmpfile: %v", err) - } - if keys, err := PublicKeysFromFile(f.Name()); err != nil { - t.Fatalf("error reading public key from certificate file: %v", err) - } else if len(keys) != 1 { - t.Fatalf("expected 1 keys, got %d", len(keys)) - } - -} diff --git a/vendor/k8s.io/client-go/util/flowcontrol/backoff_test.go b/vendor/k8s.io/client-go/util/flowcontrol/backoff_test.go deleted file mode 100644 index 23a6cbfa30..0000000000 --- a/vendor/k8s.io/client-go/util/flowcontrol/backoff_test.go +++ /dev/null @@ -1,195 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package flowcontrol - -import ( - "testing" - "time" - - "k8s.io/apimachinery/pkg/util/clock" -) - -func TestSlowBackoff(t *testing.T) { - id := "_idSlow" - tc := clock.NewFakeClock(time.Now()) - step := time.Second - maxDuration := 50 * step - - b := NewFakeBackOff(step, maxDuration, tc) - cases := []time.Duration{0, 1, 2, 4, 8, 16, 32, 50, 50, 50} - for ix, c := range cases { - tc.Step(step) - w := b.Get(id) - if w != c*step { - t.Errorf("input: '%d': expected %s, got %s", ix, c*step, w) - } - b.Next(id, tc.Now()) - } - - //Now confirm that the Reset cancels backoff. - b.Next(id, tc.Now()) - b.Reset(id) - if b.Get(id) != 0 { - t.Errorf("Reset didn't clear the backoff.") - } - -} - -func TestBackoffReset(t *testing.T) { - id := "_idReset" - tc := clock.NewFakeClock(time.Now()) - step := time.Second - maxDuration := step * 5 - b := NewFakeBackOff(step, maxDuration, tc) - startTime := tc.Now() - - // get to backoff = maxDuration - for i := 0; i <= int(maxDuration/step); i++ { - tc.Step(step) - b.Next(id, tc.Now()) - } - - // backoff should be capped at maxDuration - if !b.IsInBackOffSince(id, tc.Now()) { - t.Errorf("expected to be in Backoff got %s", b.Get(id)) - } - - lastUpdate := tc.Now() - tc.Step(2*maxDuration + step) // time += 11s, 11 > 2*maxDuration - if b.IsInBackOffSince(id, lastUpdate) { - t.Errorf("expected to not be in Backoff after reset (start=%s, now=%s, lastUpdate=%s), got %s", startTime, tc.Now(), lastUpdate, b.Get(id)) - } -} - -func TestBackoffHightWaterMark(t *testing.T) { - id := "_idHiWaterMark" - tc := clock.NewFakeClock(time.Now()) - step := time.Second - maxDuration := 5 * step - b := NewFakeBackOff(step, maxDuration, tc) - - // get to backoff = maxDuration - for i := 0; i <= int(maxDuration/step); i++ { - tc.Step(step) - b.Next(id, tc.Now()) - } - - // backoff high watermark expires after 2*maxDuration - tc.Step(maxDuration + step) - b.Next(id, tc.Now()) - - if b.Get(id) != maxDuration { - t.Errorf("expected Backoff to stay at high watermark %s got %s", maxDuration, b.Get(id)) - } -} - -func TestBackoffGC(t *testing.T) { - id := "_idGC" - tc := clock.NewFakeClock(time.Now()) - step := time.Second - maxDuration := 5 * step - - b := NewFakeBackOff(step, maxDuration, tc) - - for i := 0; i <= int(maxDuration/step); i++ { - tc.Step(step) - b.Next(id, tc.Now()) - } - lastUpdate := tc.Now() - tc.Step(maxDuration + step) - b.GC() - _, found := b.perItemBackoff[id] - if !found { - t.Errorf("expected GC to skip entry, elapsed time=%s maxDuration=%s", tc.Now().Sub(lastUpdate), maxDuration) - } - - tc.Step(maxDuration + step) - b.GC() - r, found := b.perItemBackoff[id] - if found { - t.Errorf("expected GC of entry after %s got entry %v", tc.Now().Sub(lastUpdate), r) - } -} - -func TestIsInBackOffSinceUpdate(t *testing.T) { - id := "_idIsInBackOffSinceUpdate" - tc := clock.NewFakeClock(time.Now()) - step := time.Second - maxDuration := 10 * step - b := NewFakeBackOff(step, maxDuration, tc) - startTime := tc.Now() - - cases := []struct { - tick time.Duration - inBackOff bool - value int - }{ - {tick: 0, inBackOff: false, value: 0}, - {tick: 1, inBackOff: false, value: 1}, - {tick: 2, inBackOff: true, value: 2}, - {tick: 3, inBackOff: false, value: 2}, - {tick: 4, inBackOff: true, value: 4}, - {tick: 5, inBackOff: true, value: 4}, - {tick: 6, inBackOff: true, value: 4}, - {tick: 7, inBackOff: false, value: 4}, - {tick: 8, inBackOff: true, value: 8}, - {tick: 9, inBackOff: true, value: 8}, - {tick: 10, inBackOff: true, value: 8}, - {tick: 11, inBackOff: true, value: 8}, - {tick: 12, inBackOff: true, value: 8}, - {tick: 13, inBackOff: true, value: 8}, - {tick: 14, inBackOff: true, value: 8}, - {tick: 15, inBackOff: false, value: 8}, - {tick: 16, inBackOff: true, value: 10}, - {tick: 17, inBackOff: true, value: 10}, - {tick: 18, inBackOff: true, value: 10}, - {tick: 19, inBackOff: true, value: 10}, - {tick: 20, inBackOff: true, value: 10}, - {tick: 21, inBackOff: true, value: 10}, - {tick: 22, inBackOff: true, value: 10}, - {tick: 23, inBackOff: true, value: 10}, - {tick: 24, inBackOff: true, value: 10}, - {tick: 25, inBackOff: false, value: 10}, - {tick: 26, inBackOff: true, value: 10}, - {tick: 27, inBackOff: true, value: 10}, - {tick: 28, inBackOff: true, value: 10}, - {tick: 29, inBackOff: true, value: 10}, - {tick: 30, inBackOff: true, value: 10}, - {tick: 31, inBackOff: true, value: 10}, - {tick: 32, inBackOff: true, value: 10}, - {tick: 33, inBackOff: true, value: 10}, - {tick: 34, inBackOff: true, value: 10}, - {tick: 35, inBackOff: false, value: 10}, - {tick: 56, inBackOff: false, value: 0}, - {tick: 57, inBackOff: false, value: 1}, - } - - for _, c := range cases { - tc.SetTime(startTime.Add(c.tick * step)) - if c.inBackOff != b.IsInBackOffSinceUpdate(id, tc.Now()) { - t.Errorf("expected IsInBackOffSinceUpdate %v got %v at tick %s", c.inBackOff, b.IsInBackOffSinceUpdate(id, tc.Now()), c.tick*step) - } - - if c.inBackOff && (time.Duration(c.value)*step != b.Get(id)) { - t.Errorf("expected backoff value=%s got %s at tick %s", time.Duration(c.value)*step, b.Get(id), c.tick*step) - } - - if !c.inBackOff { - b.Next(id, tc.Now()) - } - } -} diff --git a/vendor/k8s.io/client-go/util/flowcontrol/throttle_test.go b/vendor/k8s.io/client-go/util/flowcontrol/throttle_test.go deleted file mode 100644 index 99cf64d649..0000000000 --- a/vendor/k8s.io/client-go/util/flowcontrol/throttle_test.go +++ /dev/null @@ -1,153 +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 flowcontrol - -import ( - "sync" - "testing" - "time" -) - -func TestMultithreadedThrottling(t *testing.T) { - // Bucket with 100QPS and no burst - r := NewTokenBucketRateLimiter(100, 1) - - // channel to collect 100 tokens - taken := make(chan bool, 100) - - // Set up goroutines to hammer the throttler - startCh := make(chan bool) - endCh := make(chan bool) - for i := 0; i < 10; i++ { - go func() { - // wait for the starting signal - <-startCh - for { - // get a token - r.Accept() - select { - // try to add it to the taken channel - case taken <- true: - continue - // if taken is full, notify and return - default: - endCh <- true - return - } - } - }() - } - - // record wall time - startTime := time.Now() - // take the initial capacity so all tokens are the result of refill - r.Accept() - // start the thundering herd - close(startCh) - // wait for the first signal that we collected 100 tokens - <-endCh - // record wall time - endTime := time.Now() - - // tolerate a 1% clock change because these things happen - if duration := endTime.Sub(startTime); duration < (time.Second * 99 / 100) { - // We shouldn't be able to get 100 tokens out of the bucket in less than 1 second of wall clock time, no matter what - t.Errorf("Expected it to take at least 1 second to get 100 tokens, took %v", duration) - } else { - t.Logf("Took %v to get 100 tokens", duration) - } -} - -func TestBasicThrottle(t *testing.T) { - r := NewTokenBucketRateLimiter(1, 3) - for i := 0; i < 3; i++ { - if !r.TryAccept() { - t.Error("unexpected false accept") - } - } - if r.TryAccept() { - t.Error("unexpected true accept") - } -} - -func TestIncrementThrottle(t *testing.T) { - r := NewTokenBucketRateLimiter(1, 1) - if !r.TryAccept() { - t.Error("unexpected false accept") - } - if r.TryAccept() { - t.Error("unexpected true accept") - } - - // Allow to refill - time.Sleep(2 * time.Second) - - if !r.TryAccept() { - t.Error("unexpected false accept") - } -} - -func TestThrottle(t *testing.T) { - r := NewTokenBucketRateLimiter(10, 5) - - // Should consume 5 tokens immediately, then - // the remaining 11 should take at least 1 second (0.1s each) - expectedFinish := time.Now().Add(time.Second * 1) - for i := 0; i < 16; i++ { - r.Accept() - } - if time.Now().Before(expectedFinish) { - t.Error("rate limit was not respected, finished too early") - } -} - -func TestAlwaysFake(t *testing.T) { - rl := NewFakeAlwaysRateLimiter() - if !rl.TryAccept() { - t.Error("TryAccept in AlwaysFake should return true.") - } - // If this will block the test will timeout - rl.Accept() -} - -func TestNeverFake(t *testing.T) { - rl := NewFakeNeverRateLimiter() - if rl.TryAccept() { - t.Error("TryAccept in NeverFake should return false.") - } - - finished := false - wg := sync.WaitGroup{} - wg.Add(1) - go func() { - rl.Accept() - finished = true - wg.Done() - }() - - // Wait some time to make sure it never finished. - time.Sleep(time.Second) - if finished { - t.Error("Accept should block forever in NeverFake.") - } - - rl.Stop() - wg.Wait() - if !finished { - t.Error("Stop should make Accept unblock in NeverFake.") - } -} diff --git a/vendor/k8s.io/client-go/util/integer/integer_test.go b/vendor/k8s.io/client-go/util/integer/integer_test.go deleted file mode 100644 index e9f586888c..0000000000 --- a/vendor/k8s.io/client-go/util/integer/integer_test.go +++ /dev/null @@ -1,244 +0,0 @@ -/* -Copyright 2016 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 integer - -import "testing" - -func TestIntMax(t *testing.T) { - tests := []struct { - nums []int - expectedMax int - }{ - { - nums: []int{-1, 0}, - expectedMax: 0, - }, - { - nums: []int{-1, -2}, - expectedMax: -1, - }, - { - nums: []int{0, 1}, - expectedMax: 1, - }, - { - nums: []int{1, 2}, - expectedMax: 2, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if max := IntMax(test.nums[0], test.nums[1]); max != test.expectedMax { - t.Errorf("expected %v, got %v", test.expectedMax, max) - } - } -} - -func TestIntMin(t *testing.T) { - tests := []struct { - nums []int - expectedMin int - }{ - { - nums: []int{-1, 0}, - expectedMin: -1, - }, - { - nums: []int{-1, -2}, - expectedMin: -2, - }, - { - nums: []int{0, 1}, - expectedMin: 0, - }, - { - nums: []int{1, 2}, - expectedMin: 1, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if min := IntMin(test.nums[0], test.nums[1]); min != test.expectedMin { - t.Errorf("expected %v, got %v", test.expectedMin, min) - } - } -} - -func TestInt32Max(t *testing.T) { - tests := []struct { - nums []int32 - expectedMax int32 - }{ - { - nums: []int32{-1, 0}, - expectedMax: 0, - }, - { - nums: []int32{-1, -2}, - expectedMax: -1, - }, - { - nums: []int32{0, 1}, - expectedMax: 1, - }, - { - nums: []int32{1, 2}, - expectedMax: 2, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if max := Int32Max(test.nums[0], test.nums[1]); max != test.expectedMax { - t.Errorf("expected %v, got %v", test.expectedMax, max) - } - } -} - -func TestInt32Min(t *testing.T) { - tests := []struct { - nums []int32 - expectedMin int32 - }{ - { - nums: []int32{-1, 0}, - expectedMin: -1, - }, - { - nums: []int32{-1, -2}, - expectedMin: -2, - }, - { - nums: []int32{0, 1}, - expectedMin: 0, - }, - { - nums: []int32{1, 2}, - expectedMin: 1, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if min := Int32Min(test.nums[0], test.nums[1]); min != test.expectedMin { - t.Errorf("expected %v, got %v", test.expectedMin, min) - } - } -} - -func TestInt64Max(t *testing.T) { - tests := []struct { - nums []int64 - expectedMax int64 - }{ - { - nums: []int64{-1, 0}, - expectedMax: 0, - }, - { - nums: []int64{-1, -2}, - expectedMax: -1, - }, - { - nums: []int64{0, 1}, - expectedMax: 1, - }, - { - nums: []int64{1, 2}, - expectedMax: 2, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if max := Int64Max(test.nums[0], test.nums[1]); max != test.expectedMax { - t.Errorf("expected %v, got %v", test.expectedMax, max) - } - } -} - -func TestInt64Min(t *testing.T) { - tests := []struct { - nums []int64 - expectedMin int64 - }{ - { - nums: []int64{-1, 0}, - expectedMin: -1, - }, - { - nums: []int64{-1, -2}, - expectedMin: -2, - }, - { - nums: []int64{0, 1}, - expectedMin: 0, - }, - { - nums: []int64{1, 2}, - expectedMin: 1, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if min := Int64Min(test.nums[0], test.nums[1]); min != test.expectedMin { - t.Errorf("expected %v, got %v", test.expectedMin, min) - } - } -} - -func TestRoundToInt32(t *testing.T) { - tests := []struct { - num float64 - exp int32 - }{ - { - num: 5.5, - exp: 6, - }, - { - num: -3.7, - exp: -4, - }, - { - num: 3.49, - exp: 3, - }, - { - num: -7.9, - exp: -8, - }, - { - num: -4.499999, - exp: -4, - }, - { - num: 0, - exp: 0, - }, - } - - for i, test := range tests { - t.Logf("executing scenario %d", i) - if got := RoundToInt32(test.num); got != test.exp { - t.Errorf("expected %d, got %d", test.exp, got) - } - } -} diff --git a/vendor/k8s.io/client-go/util/jsonpath/jsonpath_test.go b/vendor/k8s.io/client-go/util/jsonpath/jsonpath_test.go deleted file mode 100644 index 6c7277d10a..0000000000 --- a/vendor/k8s.io/client-go/util/jsonpath/jsonpath_test.go +++ /dev/null @@ -1,371 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package jsonpath - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "sort" - "strings" - "testing" -) - -type jsonpathTest struct { - name string - template string - input interface{} - expect string - expectError bool -} - -func testJSONPath(tests []jsonpathTest, allowMissingKeys bool, t *testing.T) { - for _, test := range tests { - j := New(test.name) - j.AllowMissingKeys(allowMissingKeys) - err := j.Parse(test.template) - if err != nil { - t.Errorf("in %s, parse %s error %v", test.name, test.template, err) - } - buf := new(bytes.Buffer) - err = j.Execute(buf, test.input) - if test.expectError { - if test.expectError && err == nil { - t.Errorf("in %s, expected execute error", test.name) - } - continue - } else if err != nil { - t.Errorf("in %s, execute error %v", test.name, err) - } - out := buf.String() - if out != test.expect { - t.Errorf(`in %s, expect to get "%s", got "%s"`, test.name, test.expect, out) - } - } -} - -// testJSONPathSortOutput test cases related to map, the results may print in random order -func testJSONPathSortOutput(tests []jsonpathTest, t *testing.T) { - for _, test := range tests { - j := New(test.name) - err := j.Parse(test.template) - if err != nil { - t.Errorf("in %s, parse %s error %v", test.name, test.template, err) - } - buf := new(bytes.Buffer) - err = j.Execute(buf, test.input) - if err != nil { - t.Errorf("in %s, execute error %v", test.name, err) - } - out := buf.String() - //since map is visited in random order, we need to sort the results. - sortedOut := strings.Fields(out) - sort.Strings(sortedOut) - sortedExpect := strings.Fields(test.expect) - sort.Strings(sortedExpect) - if !reflect.DeepEqual(sortedOut, sortedExpect) { - t.Errorf(`in %s, expect to get "%s", got "%s"`, test.name, test.expect, out) - } - } -} - -func testFailJSONPath(tests []jsonpathTest, t *testing.T) { - for _, test := range tests { - j := New(test.name) - err := j.Parse(test.template) - if err != nil { - t.Errorf("in %s, parse %s error %v", test.name, test.template, err) - } - buf := new(bytes.Buffer) - err = j.Execute(buf, test.input) - var out string - if err == nil { - out = "nil" - } else { - out = err.Error() - } - if out != test.expect { - t.Errorf("in %s, expect to get error %q, got %q", test.name, test.expect, out) - } - } -} - -type book struct { - Category string - Author string - Title string - Price float32 -} - -func (b book) String() string { - return fmt.Sprintf("{Category: %s, Author: %s, Title: %s, Price: %v}", b.Category, b.Author, b.Title, b.Price) -} - -type bicycle struct { - Color string - Price float32 - IsNew bool -} - -type empName string -type job string -type store struct { - Book []book - Bicycle []bicycle - Name string - Labels map[string]int - Employees map[empName]job -} - -func TestStructInput(t *testing.T) { - - storeData := store{ - Name: "jsonpath", - Book: []book{ - {"reference", "Nigel Rees", "Sayings of the Centurey", 8.95}, - {"fiction", "Evelyn Waugh", "Sword of Honour", 12.99}, - {"fiction", "Herman Melville", "Moby Dick", 8.99}, - }, - Bicycle: []bicycle{ - {"red", 19.95, true}, - {"green", 20.01, false}, - }, - Labels: map[string]int{ - "engieer": 10, - "web/html": 15, - "k8s-app": 20, - }, - Employees: map[empName]job{ - "jason": "manager", - "dan": "clerk", - }, - } - - storeTests := []jsonpathTest{ - {"plain", "hello jsonpath", nil, "hello jsonpath", false}, - {"recursive", "{..}", []int{1, 2, 3}, "[1 2 3]", false}, - {"filter", "{[?(@<5)]}", []int{2, 6, 3, 7}, "2 3", false}, - {"quote", `{"{"}`, nil, "{", false}, - {"union", "{[1,3,4]}", []int{0, 1, 2, 3, 4}, "1 3 4", false}, - {"array", "{[0:2]}", []string{"Monday", "Tudesday"}, "Monday Tudesday", false}, - {"variable", "hello {.Name}", storeData, "hello jsonpath", false}, - {"dict/", "{$.Labels.web/html}", storeData, "15", false}, - {"dict/", "{$.Employees.jason}", storeData, "manager", false}, - {"dict/", "{$.Employees.dan}", storeData, "clerk", false}, - {"dict-", "{.Labels.k8s-app}", storeData, "20", false}, - {"nest", "{.Bicycle[*].Color}", storeData, "red green", false}, - {"allarray", "{.Book[*].Author}", storeData, "Nigel Rees Evelyn Waugh Herman Melville", false}, - {"allfileds", "{.Bicycle.*}", storeData, "{red 19.95 true} {green 20.01 false}", false}, - {"recurfileds", "{..Price}", storeData, "8.95 12.99 8.99 19.95 20.01", false}, - {"lastarray", "{.Book[-1:]}", storeData, - "{Category: fiction, Author: Herman Melville, Title: Moby Dick, Price: 8.99}", false}, - {"recurarray", "{..Book[2]}", storeData, - "{Category: fiction, Author: Herman Melville, Title: Moby Dick, Price: 8.99}", false}, - {"bool", "{.Bicycle[?(@.IsNew==true)]}", storeData, "{red 19.95 true}", false}, - } - testJSONPath(storeTests, false, t) - - missingKeyTests := []jsonpathTest{ - {"nonexistent field", "{.hello}", storeData, "", false}, - } - testJSONPath(missingKeyTests, true, t) - - failStoreTests := []jsonpathTest{ - {"invalid identifier", "{hello}", storeData, "unrecognized identifier hello", false}, - {"nonexistent field", "{.hello}", storeData, "hello is not found", false}, - {"invalid array", "{.Labels[0]}", storeData, "map[string]int is not array or slice", false}, - {"invalid filter operator", "{.Book[?(@.Price<>10)]}", storeData, "unrecognized filter operator <>", false}, - {"redundant end", "{range .Labels.*}{@}{end}{end}", storeData, "not in range, nothing to end", false}, - } - testFailJSONPath(failStoreTests, t) -} - -func TestJSONInput(t *testing.T) { - var pointsJSON = []byte(`[ - {"id": "i1", "x":4, "y":-5}, - {"id": "i2", "x":-2, "y":-5, "z":1}, - {"id": "i3", "x": 8, "y": 3 }, - {"id": "i4", "x": -6, "y": -1 }, - {"id": "i5", "x": 0, "y": 2, "z": 1 }, - {"id": "i6", "x": 1, "y": 4 } - ]`) - var pointsData interface{} - err := json.Unmarshal(pointsJSON, &pointsData) - if err != nil { - t.Error(err) - } - pointsTests := []jsonpathTest{ - {"exists filter", "{[?(@.z)].id}", pointsData, "i2 i5", false}, - {"bracket key", "{[0]['id']}", pointsData, "i1", false}, - } - testJSONPath(pointsTests, false, t) -} - -// TestKubernetes tests some use cases from kubernetes -func TestKubernetes(t *testing.T) { - var input = []byte(`{ - "kind": "List", - "items":[ - { - "kind":"None", - "metadata":{ - "name":"127.0.0.1", - "labels":{ - "kubernetes.io/hostname":"127.0.0.1" - } - }, - "status":{ - "capacity":{"cpu":"4"}, - "ready": true, - "addresses":[{"type": "LegacyHostIP", "address":"127.0.0.1"}] - } - }, - { - "kind":"None", - "metadata":{ - "name":"127.0.0.2", - "labels":{ - "kubernetes.io/hostname":"127.0.0.2" - } - }, - "status":{ - "capacity":{"cpu":"8"}, - "ready": false, - "addresses":[ - {"type": "LegacyHostIP", "address":"127.0.0.2"}, - {"type": "another", "address":"127.0.0.3"} - ] - } - } - ], - "users":[ - { - "name": "myself", - "user": {} - }, - { - "name": "e2e", - "user": {"username": "admin", "password": "secret"} - } - ] - }`) - var nodesData interface{} - err := json.Unmarshal(input, &nodesData) - if err != nil { - t.Error(err) - } - - nodesTests := []jsonpathTest{ - {"range item", `{range .items[*]}{.metadata.name}, {end}{.kind}`, nodesData, "127.0.0.1, 127.0.0.2, List", false}, - {"range item with quote", `{range .items[*]}{.metadata.name}{"\t"}{end}`, nodesData, "127.0.0.1\t127.0.0.2\t", false}, - {"range addresss", `{.items[*].status.addresses[*].address}`, nodesData, - "127.0.0.1 127.0.0.2 127.0.0.3", false}, - {"double range", `{range .items[*]}{range .status.addresses[*]}{.address}, {end}{end}`, nodesData, - "127.0.0.1, 127.0.0.2, 127.0.0.3, ", false}, - {"item name", `{.items[*].metadata.name}`, nodesData, "127.0.0.1 127.0.0.2", false}, - {"union nodes capacity", `{.items[*]['metadata.name', 'status.capacity']}`, nodesData, - "127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8]", false}, - {"range nodes capacity", `{range .items[*]}[{.metadata.name}, {.status.capacity}] {end}`, nodesData, - "[127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]] ", false}, - {"user password", `{.users[?(@.name=="e2e")].user.password}`, &nodesData, "secret", false}, - {"hostname", `{.items[0].metadata.labels.kubernetes\.io/hostname}`, &nodesData, "127.0.0.1", false}, - {"hostname filter", `{.items[?(@.metadata.labels.kubernetes\.io/hostname=="127.0.0.1")].kind}`, &nodesData, "None", false}, - {"bool item", `{.items[?(@..ready==true)].metadata.name}`, &nodesData, "127.0.0.1", false}, - } - testJSONPath(nodesTests, false, t) - - randomPrintOrderTests := []jsonpathTest{ - {"recursive name", "{..name}", nodesData, `127.0.0.1 127.0.0.2 myself e2e`, false}, - } - testJSONPathSortOutput(randomPrintOrderTests, t) -} - -func TestFilterPartialMatchesSometimesMissingAnnotations(t *testing.T) { - // for https://issues.k8s.io/45546 - var input = []byte(`{ - "kind": "List", - "items": [ - { - "kind": "Pod", - "metadata": { - "name": "pod1", - "annotations": { - "color": "blue" - } - } - }, - { - "kind": "Pod", - "metadata": { - "name": "pod2" - } - }, - { - "kind": "Pod", - "metadata": { - "name": "pod3", - "annotations": { - "color": "green" - } - } - }, - { - "kind": "Pod", - "metadata": { - "name": "pod4", - "annotations": { - "color": "blue" - } - } - } - ] - }`) - var data interface{} - err := json.Unmarshal(input, &data) - if err != nil { - t.Fatal(err) - } - - testJSONPath( - []jsonpathTest{ - { - "filter, should only match a subset, some items don't have annotations, tolerate missing items", - `{.items[?(@.metadata.annotations.color=="blue")].metadata.name}`, - data, - "pod1 pod4", - false, // expect no error - }, - }, - true, // allow missing keys - t, - ) - - testJSONPath( - []jsonpathTest{ - { - "filter, should only match a subset, some items don't have annotations, error on missing items", - `{.items[?(@.metadata.annotations.color=="blue")].metadata.name}`, - data, - "", - true, // expect an error - }, - }, - false, // don't allow missing keys - t, - ) -} diff --git a/vendor/k8s.io/client-go/util/jsonpath/parser_test.go b/vendor/k8s.io/client-go/util/jsonpath/parser_test.go deleted file mode 100644 index 4f71a60ac7..0000000000 --- a/vendor/k8s.io/client-go/util/jsonpath/parser_test.go +++ /dev/null @@ -1,152 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package jsonpath - -import ( - "testing" -) - -type parserTest struct { - name string - text string - nodes []Node - shouldError bool -} - -var parserTests = []parserTest{ - {"plain", `hello jsonpath`, []Node{newText("hello jsonpath")}, false}, - {"variable", `hello {.jsonpath}`, - []Node{newText("hello "), newList(), newField("jsonpath")}, false}, - {"arrayfiled", `hello {['jsonpath']}`, - []Node{newText("hello "), newList(), newField("jsonpath")}, false}, - {"quote", `{"{"}`, []Node{newList(), newText("{")}, false}, - {"array", `{[1:3]}`, []Node{newList(), - newArray([3]ParamsEntry{{1, true}, {3, true}, {0, false}})}, false}, - {"allarray", `{.book[*].author}`, - []Node{newList(), newField("book"), - newArray([3]ParamsEntry{{0, false}, {0, false}, {0, false}}), newField("author")}, false}, - {"wildcard", `{.bicycle.*}`, - []Node{newList(), newField("bicycle"), newWildcard()}, false}, - {"filter", `{[?(@.price<3)]}`, - []Node{newList(), newFilter(newList(), newList(), "<"), - newList(), newField("price"), newList(), newInt(3)}, false}, - {"recursive", `{..}`, []Node{newList(), newRecursive()}, false}, - {"recurField", `{..price}`, - []Node{newList(), newRecursive(), newField("price")}, false}, - {"arraydict", `{['book.price']}`, []Node{newList(), - newField("book"), newField("price"), - }, false}, - {"union", `{['bicycle.price', 3, 'book.price']}`, []Node{newList(), newUnion([]*ListNode{}), - newList(), newField("bicycle"), newField("price"), - newList(), newArray([3]ParamsEntry{{3, true}, {4, true}, {0, false}}), - newList(), newField("book"), newField("price"), - }, false}, - {"range", `{range .items}{.name},{end}`, []Node{ - newList(), newIdentifier("range"), newField("items"), - newList(), newField("name"), newText(","), - newList(), newIdentifier("end"), - }, false}, - {"malformat input", `{\\\}`, []Node{}, true}, - {"paired parentheses in quotes", `{[?(@.status.nodeInfo.osImage == "()")]}`, - []Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("()")}, false}, - {"paired parentheses in double quotes and with double quotes escape", `{[?(@.status.nodeInfo.osImage == "(\"\")")]}`, - []Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("(\"\")")}, false}, - {"unregular parentheses in double quotes", `{[?(@.test == "())(")]}`, - []Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("test"), newList(), newText("())(")}, false}, - {"plain text in single quotes", `{[?(@.status.nodeInfo.osImage == 'Linux')]}`, - []Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("Linux")}, false}, - {"test filter suffix", `{[?(@.status.nodeInfo.osImage == "{[()]}")]}`, - []Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("{[()]}")}, false}, - {"double inside single", `{[?(@.status.nodeInfo.osImage == "''")]}`, - []Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("''")}, false}, - {"single inside double", `{[?(@.status.nodeInfo.osImage == '""')]}`, - []Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("\"\"")}, false}, - {"single containing escaped single", `{[?(@.status.nodeInfo.osImage == '\\\'')]}`, - []Node{newList(), newFilter(newList(), newList(), "=="), newList(), newField("status"), newField("nodeInfo"), newField("osImage"), newList(), newText("\\'")}, false}, -} - -func collectNode(nodes []Node, cur Node) []Node { - nodes = append(nodes, cur) - switch cur.Type() { - case NodeList: - for _, node := range cur.(*ListNode).Nodes { - nodes = collectNode(nodes, node) - } - case NodeFilter: - nodes = collectNode(nodes, cur.(*FilterNode).Left) - nodes = collectNode(nodes, cur.(*FilterNode).Right) - case NodeUnion: - for _, node := range cur.(*UnionNode).Nodes { - nodes = collectNode(nodes, node) - } - } - return nodes -} - -func TestParser(t *testing.T) { - for _, test := range parserTests { - parser, err := Parse(test.name, test.text) - if test.shouldError { - if err == nil { - t.Errorf("unexpected non-error when parsing %s", test.name) - } - continue - } - if err != nil { - t.Errorf("parse %s error %v", test.name, err) - } - result := collectNode([]Node{}, parser.Root)[1:] - if len(result) != len(test.nodes) { - t.Errorf("in %s, expect to get %d nodes, got %d nodes", test.name, len(test.nodes), len(result)) - t.Error(result) - } - for i, expect := range test.nodes { - if result[i].String() != expect.String() { - t.Errorf("in %s, %dth node, expect %v, got %v", test.name, i, expect, result[i]) - } - } - } -} - -type failParserTest struct { - name string - text string - err string -} - -func TestFailParser(t *testing.T) { - failParserTests := []failParserTest{ - {"unclosed action", "{.hello", "unclosed action"}, - {"unrecognized character", "{*}", "unrecognized character in action: U+002A '*'"}, - {"invalid number", "{+12.3.0}", "cannot parse number +12.3.0"}, - {"unterminated array", "{[1}", "unterminated array"}, - {"invalid index", "{[::-1]}", "invalid array index ::-1"}, - {"unterminated filter", "{[?(.price]}", "unterminated filter"}, - } - for _, test := range failParserTests { - _, err := Parse(test.name, test.text) - var out string - if err == nil { - out = "nil" - } else { - out = err.Error() - } - if out != test.err { - t.Errorf("in %s, expect to get error %v, got %v", test.name, test.err, out) - } - } -} diff --git a/vendor/k8s.io/client-go/util/retry/util_test.go b/vendor/k8s.io/client-go/util/retry/util_test.go deleted file mode 100644 index dbb4374fe1..0000000000 --- a/vendor/k8s.io/client-go/util/retry/util_test.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright 2016 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 retry - -import ( - "fmt" - "testing" - - "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/wait" -) - -func TestRetryOnConflict(t *testing.T) { - opts := wait.Backoff{Factor: 1.0, Steps: 3} - conflictErr := errors.NewConflict(schema.GroupResource{Resource: "test"}, "other", nil) - - // never returns - err := RetryOnConflict(opts, func() error { - return conflictErr - }) - if err != conflictErr { - t.Errorf("unexpected error: %v", err) - } - - // returns immediately - i := 0 - err = RetryOnConflict(opts, func() error { - i++ - return nil - }) - if err != nil || i != 1 { - t.Errorf("unexpected error: %v", err) - } - - // returns immediately on error - testErr := fmt.Errorf("some other error") - err = RetryOnConflict(opts, func() error { - return testErr - }) - if err != testErr { - t.Errorf("unexpected error: %v", err) - } - - // keeps retrying - i = 0 - err = RetryOnConflict(opts, func() error { - if i < 2 { - i++ - return errors.NewConflict(schema.GroupResource{Resource: "test"}, "other", nil) - } - return nil - }) - if err != nil || i != 2 { - t.Errorf("unexpected error: %v", err) - } -} diff --git a/vendor/k8s.io/client-go/util/workqueue/default_rate_limiters_test.go b/vendor/k8s.io/client-go/util/workqueue/default_rate_limiters_test.go deleted file mode 100644 index 91d34a3177..0000000000 --- a/vendor/k8s.io/client-go/util/workqueue/default_rate_limiters_test.go +++ /dev/null @@ -1,184 +0,0 @@ -/* -Copyright 2016 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 workqueue - -import ( - "testing" - "time" -) - -func TestItemExponentialFailureRateLimiter(t *testing.T) { - limiter := NewItemExponentialFailureRateLimiter(1*time.Millisecond, 1*time.Second) - - if e, a := 1*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 2*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 4*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 8*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 16*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5, limiter.NumRequeues("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - if e, a := 1*time.Millisecond, limiter.When("two"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 2*time.Millisecond, limiter.When("two"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 2, limiter.NumRequeues("two"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - limiter.Forget("one") - if e, a := 0, limiter.NumRequeues("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 1*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - -} - -func TestItemExponentialFailureRateLimiterOverFlow(t *testing.T) { - limiter := NewItemExponentialFailureRateLimiter(1*time.Millisecond, 1000*time.Second) - for i := 0; i < 5; i++ { - limiter.When("one") - } - if e, a := 32*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - for i := 0; i < 1000; i++ { - limiter.When("overflow1") - } - if e, a := 1000*time.Second, limiter.When("overflow1"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - limiter = NewItemExponentialFailureRateLimiter(1*time.Minute, 1000*time.Hour) - for i := 0; i < 2; i++ { - limiter.When("two") - } - if e, a := 4*time.Minute, limiter.When("two"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - for i := 0; i < 1000; i++ { - limiter.When("overflow2") - } - if e, a := 1000*time.Hour, limiter.When("overflow2"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - -} - -func TestItemFastSlowRateLimiter(t *testing.T) { - limiter := NewItemFastSlowRateLimiter(5*time.Millisecond, 10*time.Second, 3) - - if e, a := 5*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 10*time.Second, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 10*time.Second, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5, limiter.NumRequeues("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - if e, a := 5*time.Millisecond, limiter.When("two"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5*time.Millisecond, limiter.When("two"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 2, limiter.NumRequeues("two"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - limiter.Forget("one") - if e, a := 0, limiter.NumRequeues("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - -} - -func TestMaxOfRateLimiter(t *testing.T) { - limiter := NewMaxOfRateLimiter( - NewItemFastSlowRateLimiter(5*time.Millisecond, 3*time.Second, 3), - NewItemExponentialFailureRateLimiter(1*time.Millisecond, 1*time.Second), - ) - - if e, a := 5*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 3*time.Second, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 3*time.Second, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5, limiter.NumRequeues("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - if e, a := 5*time.Millisecond, limiter.When("two"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5*time.Millisecond, limiter.When("two"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 2, limiter.NumRequeues("two"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - limiter.Forget("one") - if e, a := 0, limiter.NumRequeues("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 5*time.Millisecond, limiter.When("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - -} diff --git a/vendor/k8s.io/client-go/util/workqueue/delaying_queue_test.go b/vendor/k8s.io/client-go/util/workqueue/delaying_queue_test.go deleted file mode 100644 index 3c8ebf13a3..0000000000 --- a/vendor/k8s.io/client-go/util/workqueue/delaying_queue_test.go +++ /dev/null @@ -1,255 +0,0 @@ -/* -Copyright 2016 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 workqueue - -import ( - "fmt" - "math/rand" - "reflect" - "testing" - "time" - - "k8s.io/apimachinery/pkg/util/clock" - "k8s.io/apimachinery/pkg/util/wait" -) - -func TestSimpleQueue(t *testing.T) { - fakeClock := clock.NewFakeClock(time.Now()) - q := newDelayingQueue(fakeClock, "") - - first := "foo" - - q.AddAfter(first, 50*time.Millisecond) - if err := waitForWaitingQueueToFill(q); err != nil { - t.Fatalf("unexpected err: %v", err) - } - - if q.Len() != 0 { - t.Errorf("should not have added") - } - - fakeClock.Step(60 * time.Millisecond) - - if err := waitForAdded(q, 1); err != nil { - t.Errorf("should have added") - } - item, _ := q.Get() - q.Done(item) - - // step past the next heartbeat - fakeClock.Step(10 * time.Second) - - err := wait.Poll(1*time.Millisecond, 30*time.Millisecond, func() (done bool, err error) { - if q.Len() > 0 { - return false, fmt.Errorf("added to queue") - } - - return false, nil - }) - if err != wait.ErrWaitTimeout { - t.Errorf("expected timeout, got: %v", err) - } - - if q.Len() != 0 { - t.Errorf("should not have added") - } -} - -func TestDeduping(t *testing.T) { - fakeClock := clock.NewFakeClock(time.Now()) - q := newDelayingQueue(fakeClock, "") - - first := "foo" - - q.AddAfter(first, 50*time.Millisecond) - if err := waitForWaitingQueueToFill(q); err != nil { - t.Fatalf("unexpected err: %v", err) - } - q.AddAfter(first, 70*time.Millisecond) - if err := waitForWaitingQueueToFill(q); err != nil { - t.Fatalf("unexpected err: %v", err) - } - if q.Len() != 0 { - t.Errorf("should not have added") - } - - // step past the first block, we should receive now - fakeClock.Step(60 * time.Millisecond) - if err := waitForAdded(q, 1); err != nil { - t.Errorf("should have added") - } - item, _ := q.Get() - q.Done(item) - - // step past the second add - fakeClock.Step(20 * time.Millisecond) - if q.Len() != 0 { - t.Errorf("should not have added") - } - - // test again, but this time the earlier should override - q.AddAfter(first, 50*time.Millisecond) - q.AddAfter(first, 30*time.Millisecond) - if err := waitForWaitingQueueToFill(q); err != nil { - t.Fatalf("unexpected err: %v", err) - } - if q.Len() != 0 { - t.Errorf("should not have added") - } - - fakeClock.Step(40 * time.Millisecond) - if err := waitForAdded(q, 1); err != nil { - t.Errorf("should have added") - } - item, _ = q.Get() - q.Done(item) - - // step past the second add - fakeClock.Step(20 * time.Millisecond) - if q.Len() != 0 { - t.Errorf("should not have added") - } - if q.Len() != 0 { - t.Errorf("should not have added") - } -} - -func TestAddTwoFireEarly(t *testing.T) { - fakeClock := clock.NewFakeClock(time.Now()) - q := newDelayingQueue(fakeClock, "") - - first := "foo" - second := "bar" - third := "baz" - - q.AddAfter(first, 1*time.Second) - q.AddAfter(second, 50*time.Millisecond) - if err := waitForWaitingQueueToFill(q); err != nil { - t.Fatalf("unexpected err: %v", err) - } - - if q.Len() != 0 { - t.Errorf("should not have added") - } - - fakeClock.Step(60 * time.Millisecond) - - if err := waitForAdded(q, 1); err != nil { - t.Fatalf("unexpected err: %v", err) - } - item, _ := q.Get() - if !reflect.DeepEqual(item, second) { - t.Errorf("expected %v, got %v", second, item) - } - - q.AddAfter(third, 2*time.Second) - - fakeClock.Step(1 * time.Second) - if err := waitForAdded(q, 1); err != nil { - t.Fatalf("unexpected err: %v", err) - } - item, _ = q.Get() - if !reflect.DeepEqual(item, first) { - t.Errorf("expected %v, got %v", first, item) - } - - fakeClock.Step(2 * time.Second) - if err := waitForAdded(q, 1); err != nil { - t.Fatalf("unexpected err: %v", err) - } - item, _ = q.Get() - if !reflect.DeepEqual(item, third) { - t.Errorf("expected %v, got %v", third, item) - } -} - -func TestCopyShifting(t *testing.T) { - fakeClock := clock.NewFakeClock(time.Now()) - q := newDelayingQueue(fakeClock, "") - - first := "foo" - second := "bar" - third := "baz" - - q.AddAfter(first, 1*time.Second) - q.AddAfter(second, 500*time.Millisecond) - q.AddAfter(third, 250*time.Millisecond) - if err := waitForWaitingQueueToFill(q); err != nil { - t.Fatalf("unexpected err: %v", err) - } - - if q.Len() != 0 { - t.Errorf("should not have added") - } - - fakeClock.Step(2 * time.Second) - - if err := waitForAdded(q, 3); err != nil { - t.Fatalf("unexpected err: %v", err) - } - actualFirst, _ := q.Get() - if !reflect.DeepEqual(actualFirst, third) { - t.Errorf("expected %v, got %v", third, actualFirst) - } - actualSecond, _ := q.Get() - if !reflect.DeepEqual(actualSecond, second) { - t.Errorf("expected %v, got %v", second, actualSecond) - } - actualThird, _ := q.Get() - if !reflect.DeepEqual(actualThird, first) { - t.Errorf("expected %v, got %v", first, actualThird) - } -} - -func BenchmarkDelayingQueue_AddAfter(b *testing.B) { - r := rand.New(rand.NewSource(time.Now().Unix())) - - fakeClock := clock.NewFakeClock(time.Now()) - q := newDelayingQueue(fakeClock, "") - - // Add items - for n := 0; n < b.N; n++ { - data := fmt.Sprintf("%d", n) - q.AddAfter(data, time.Duration(r.Int63n(int64(10*time.Minute)))) - } - - // Exercise item removal as well - fakeClock.Step(11 * time.Minute) - for n := 0; n < b.N; n++ { - _, _ = q.Get() - } -} - -func waitForAdded(q DelayingInterface, depth int) error { - return wait.Poll(1*time.Millisecond, 10*time.Second, func() (done bool, err error) { - if q.Len() == depth { - return true, nil - } - - return false, nil - }) -} - -func waitForWaitingQueueToFill(q DelayingInterface) error { - return wait.Poll(1*time.Millisecond, 10*time.Second, func() (done bool, err error) { - if len(q.(*delayingType).waitingForAddCh) == 0 { - return true, nil - } - - return false, nil - }) -} diff --git a/vendor/k8s.io/client-go/util/workqueue/queue_test.go b/vendor/k8s.io/client-go/util/workqueue/queue_test.go deleted file mode 100644 index 131f4a2a59..0000000000 --- a/vendor/k8s.io/client-go/util/workqueue/queue_test.go +++ /dev/null @@ -1,161 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package workqueue_test - -import ( - "sync" - "testing" - "time" - - "k8s.io/client-go/util/workqueue" -) - -func TestBasic(t *testing.T) { - // If something is seriously wrong this test will never complete. - q := workqueue.New() - - // Start producers - const producers = 50 - producerWG := sync.WaitGroup{} - producerWG.Add(producers) - for i := 0; i < producers; i++ { - go func(i int) { - defer producerWG.Done() - for j := 0; j < 50; j++ { - q.Add(i) - time.Sleep(time.Millisecond) - } - }(i) - } - - // Start consumers - const consumers = 10 - consumerWG := sync.WaitGroup{} - consumerWG.Add(consumers) - for i := 0; i < consumers; i++ { - go func(i int) { - defer consumerWG.Done() - for { - item, quit := q.Get() - if item == "added after shutdown!" { - t.Errorf("Got an item added after shutdown.") - } - if quit { - return - } - t.Logf("Worker %v: begin processing %v", i, item) - time.Sleep(3 * time.Millisecond) - t.Logf("Worker %v: done processing %v", i, item) - q.Done(item) - } - }(i) - } - - producerWG.Wait() - q.ShutDown() - q.Add("added after shutdown!") - consumerWG.Wait() -} - -func TestAddWhileProcessing(t *testing.T) { - q := workqueue.New() - - // Start producers - const producers = 50 - producerWG := sync.WaitGroup{} - producerWG.Add(producers) - for i := 0; i < producers; i++ { - go func(i int) { - defer producerWG.Done() - q.Add(i) - }(i) - } - - // Start consumers - const consumers = 10 - consumerWG := sync.WaitGroup{} - consumerWG.Add(consumers) - for i := 0; i < consumers; i++ { - go func(i int) { - defer consumerWG.Done() - // Every worker will re-add every item up to two times. - // This tests the dirty-while-processing case. - counters := map[interface{}]int{} - for { - item, quit := q.Get() - if quit { - return - } - counters[item]++ - if counters[item] < 2 { - q.Add(item) - } - q.Done(item) - } - }(i) - } - - producerWG.Wait() - q.ShutDown() - consumerWG.Wait() -} - -func TestLen(t *testing.T) { - q := workqueue.New() - q.Add("foo") - if e, a := 1, q.Len(); e != a { - t.Errorf("Expected %v, got %v", e, a) - } - q.Add("bar") - if e, a := 2, q.Len(); e != a { - t.Errorf("Expected %v, got %v", e, a) - } - q.Add("foo") // should not increase the queue length. - if e, a := 2, q.Len(); e != a { - t.Errorf("Expected %v, got %v", e, a) - } -} - -func TestReinsert(t *testing.T) { - q := workqueue.New() - q.Add("foo") - - // Start processing - i, _ := q.Get() - if i != "foo" { - t.Errorf("Expected %v, got %v", "foo", i) - } - - // Add it back while processing - q.Add(i) - - // Finish it up - q.Done(i) - - // It should be back on the queue - i, _ = q.Get() - if i != "foo" { - t.Errorf("Expected %v, got %v", "foo", i) - } - - // Finish that one up - q.Done(i) - - if a := q.Len(); a != 0 { - t.Errorf("Expected queue to be empty. Has %v items", a) - } -} diff --git a/vendor/k8s.io/client-go/util/workqueue/rate_limitting_queue_test.go b/vendor/k8s.io/client-go/util/workqueue/rate_limitting_queue_test.go deleted file mode 100644 index 32d7fc9068..0000000000 --- a/vendor/k8s.io/client-go/util/workqueue/rate_limitting_queue_test.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2016 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 workqueue - -import ( - "testing" - "time" - - "k8s.io/apimachinery/pkg/util/clock" -) - -func TestRateLimitingQueue(t *testing.T) { - limiter := NewItemExponentialFailureRateLimiter(1*time.Millisecond, 1*time.Second) - queue := NewRateLimitingQueue(limiter).(*rateLimitingType) - fakeClock := clock.NewFakeClock(time.Now()) - delayingQueue := &delayingType{ - Interface: New(), - clock: fakeClock, - heartbeat: fakeClock.Tick(maxWait), - stopCh: make(chan struct{}), - waitingForAddCh: make(chan *waitFor, 1000), - metrics: newRetryMetrics(""), - } - queue.DelayingInterface = delayingQueue - - queue.AddRateLimited("one") - waitEntry := <-delayingQueue.waitingForAddCh - if e, a := 1*time.Millisecond, waitEntry.readyAt.Sub(fakeClock.Now()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - queue.AddRateLimited("one") - waitEntry = <-delayingQueue.waitingForAddCh - if e, a := 2*time.Millisecond, waitEntry.readyAt.Sub(fakeClock.Now()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - if e, a := 2, queue.NumRequeues("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - queue.AddRateLimited("two") - waitEntry = <-delayingQueue.waitingForAddCh - if e, a := 1*time.Millisecond, waitEntry.readyAt.Sub(fakeClock.Now()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - queue.AddRateLimited("two") - waitEntry = <-delayingQueue.waitingForAddCh - if e, a := 2*time.Millisecond, waitEntry.readyAt.Sub(fakeClock.Now()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - - queue.Forget("one") - if e, a := 0, queue.NumRequeues("one"); e != a { - t.Errorf("expected %v, got %v", e, a) - } - queue.AddRateLimited("one") - waitEntry = <-delayingQueue.waitingForAddCh - if e, a := 1*time.Millisecond, waitEntry.readyAt.Sub(fakeClock.Now()); e != a { - t.Errorf("expected %v, got %v", e, a) - } - -} diff --git a/vendor/k8s.io/kube-openapi/OWNERS b/vendor/k8s.io/kube-openapi/OWNERS index 7c8ad60c56..e8c62bfa23 100755 --- a/vendor/k8s.io/kube-openapi/OWNERS +++ b/vendor/k8s.io/kube-openapi/OWNERS @@ -3,5 +3,9 @@ reviewers: - gmarek - mbohlool - philips +- seans3 +- apelisse approvers: - mbohlool +- lavalamp +- seans3 diff --git a/vendor/k8s.io/kube-openapi/code-of-conduct.md b/vendor/k8s.io/kube-openapi/code-of-conduct.md new file mode 100644 index 0000000000..0d15c00cf3 --- /dev/null +++ b/vendor/k8s.io/kube-openapi/code-of-conduct.md @@ -0,0 +1,3 @@ +# Kubernetes Community Code of Conduct + +Please refer to our [Kubernetes Community Code of Conduct](https://git.k8s.io/community/code-of-conduct.md) diff --git a/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go b/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go index 5f607c7670..61dbf4fc0e 100644 --- a/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go +++ b/vendor/k8s.io/kube-openapi/pkg/util/proto/document.go @@ -210,11 +210,18 @@ func (d *Definitions) parseKind(s *openapi_v2.Schema, path *Path) (Schema, error }, nil } +func (d *Definitions) parseArbitrary(s *openapi_v2.Schema, path *Path) (Schema, error) { + return &Arbitrary{ + BaseSchema: d.parseBaseSchema(s, path), + }, nil +} + // ParseSchema creates a walkable Schema from an openapi schema. While // this function is public, it doesn't leak through the interface. func (d *Definitions) ParseSchema(s *openapi_v2.Schema, path *Path) (Schema, error) { - if len(s.GetType().GetValue()) == 1 { - t := s.GetType().GetValue()[0] + objectTypes := s.GetType().GetValue() + if len(objectTypes) == 1 { + t := objectTypes[0] switch t { case object: return d.parseMap(s, path) @@ -229,6 +236,9 @@ func (d *Definitions) ParseSchema(s *openapi_v2.Schema, path *Path) (Schema, err if s.GetProperties() != nil { return d.parseKind(s, path) } + if len(objectTypes) == 0 || (len(objectTypes) == 1 && objectTypes[0] == "") { + return d.parseArbitrary(s, path) + } return d.parsePrimitive(s, path) } diff --git a/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi.go b/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi.go index 02ab06d6d5..f26b5ef881 100644 --- a/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi.go +++ b/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi.go @@ -58,6 +58,14 @@ type SchemaVisitor interface { VisitReference(Reference) } +// SchemaVisitorArbitrary is an additional visitor interface which handles +// arbitrary types. For backwards compatibility, it's a separate interface +// which is checked for at runtime. +type SchemaVisitorArbitrary interface { + SchemaVisitor + VisitArbitrary(*Arbitrary) +} + // Schema is the base definition of an openapi type. type Schema interface { // Giving a visitor here will let you visit the actual type. @@ -242,6 +250,23 @@ func (p *Primitive) GetName() string { return fmt.Sprintf("%s (%s)", p.Type, p.Format) } +// Arbitrary is a value of any type (primitive, object or array) +type Arbitrary struct { + BaseSchema +} + +var _ Schema = &Arbitrary{} + +func (a *Arbitrary) Accept(v SchemaVisitor) { + if visitor, ok := v.(SchemaVisitorArbitrary); ok { + visitor.VisitArbitrary(a) + } +} + +func (a *Arbitrary) GetName() string { + return "Arbitrary value (primitive, object or array)" +} + // Reference implementation depends on the type of document. type Reference interface { Schema diff --git a/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi_suite_test.go b/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi_suite_test.go deleted file mode 100644 index 24b5168e42..0000000000 --- a/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi_suite_test.go +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright 2017 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 proto_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/ginkgo/config" - . "github.com/onsi/ginkgo/types" - . "github.com/onsi/gomega" - - "fmt" - "testing" -) - -func TestOpenapi(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecsWithDefaultAndCustomReporters(t, "Openapi Suite", []Reporter{newlineReporter{}}) -} - -// Print a newline after the default newlineReporter due to issue -// https://github.com/jstemmer/go-junit-report/issues/31 -type newlineReporter struct{} - -func (newlineReporter) SpecSuiteWillBegin(config GinkgoConfigType, summary *SuiteSummary) {} - -func (newlineReporter) BeforeSuiteDidRun(setupSummary *SetupSummary) {} - -func (newlineReporter) AfterSuiteDidRun(setupSummary *SetupSummary) {} - -func (newlineReporter) SpecWillRun(specSummary *SpecSummary) {} - -func (newlineReporter) SpecDidComplete(specSummary *SpecSummary) {} - -// SpecSuiteDidEnd Prints a newline between "35 Passed | 0 Failed | 0 Pending | 0 Skipped" and "--- PASS:" -func (newlineReporter) SpecSuiteDidEnd(summary *SuiteSummary) { fmt.Printf("\n") } diff --git a/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi_test.go b/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi_test.go deleted file mode 100644 index 916abe0c0a..0000000000 --- a/vendor/k8s.io/kube-openapi/pkg/util/proto/openapi_test.go +++ /dev/null @@ -1,207 +0,0 @@ -/* -Copyright 2017 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 proto_test - -import ( - "path/filepath" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "k8s.io/kube-openapi/pkg/util/proto" - "k8s.io/kube-openapi/pkg/util/proto/testing" -) - -var fakeSchema = testing.Fake{Path: filepath.Join("testing", "swagger.json")} - -var _ = Describe("Reading apps/v1beta1/Deployment from openAPIData", func() { - var models proto.Models - BeforeEach(func() { - s, err := fakeSchema.OpenAPISchema() - Expect(err).To(BeNil()) - models, err = proto.NewOpenAPIData(s) - Expect(err).To(BeNil()) - }) - - model := "io.k8s.api.apps.v1beta1.Deployment" - var schema proto.Schema - It("should lookup the Schema by its model name", func() { - schema = models.LookupModel(model) - Expect(schema).ToNot(BeNil()) - }) - - var deployment *proto.Kind - It("should be a Kind", func() { - deployment = schema.(*proto.Kind) - Expect(deployment).ToNot(BeNil()) - }) - - It("should have a path", func() { - Expect(deployment.GetPath().Get()).To(Equal([]string{"io.k8s.api.apps.v1beta1.Deployment"})) - }) - - It("should have a kind key of type string", func() { - Expect(deployment.Fields).To(HaveKey("kind")) - key := deployment.Fields["kind"].(*proto.Primitive) - Expect(key).ToNot(BeNil()) - Expect(key.Type).To(Equal("string")) - Expect(key.GetPath().Get()).To(Equal([]string{"io.k8s.api.apps.v1beta1.Deployment", ".kind"})) - }) - - It("should have a apiVersion key of type string", func() { - Expect(deployment.Fields).To(HaveKey("apiVersion")) - key := deployment.Fields["apiVersion"].(*proto.Primitive) - Expect(key).ToNot(BeNil()) - Expect(key.Type).To(Equal("string")) - Expect(key.GetPath().Get()).To(Equal([]string{"io.k8s.api.apps.v1beta1.Deployment", ".apiVersion"})) - }) - - It("should have a metadata key of type Reference", func() { - Expect(deployment.Fields).To(HaveKey("metadata")) - key := deployment.Fields["metadata"].(proto.Reference) - Expect(key).ToNot(BeNil()) - Expect(key.Reference()).To(Equal("io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta")) - subSchema := key.SubSchema().(*proto.Kind) - Expect(subSchema).ToNot(BeNil()) - }) - - var status *proto.Kind - It("should have a status key of type Reference", func() { - Expect(deployment.Fields).To(HaveKey("status")) - key := deployment.Fields["status"].(proto.Reference) - Expect(key).ToNot(BeNil()) - Expect(key.Reference()).To(Equal("io.k8s.api.apps.v1beta1.DeploymentStatus")) - status = key.SubSchema().(*proto.Kind) - Expect(status).ToNot(BeNil()) - }) - - It("should have a valid DeploymentStatus", func() { - By("having availableReplicas key") - Expect(status.Fields).To(HaveKey("availableReplicas")) - replicas := status.Fields["availableReplicas"].(*proto.Primitive) - Expect(replicas).ToNot(BeNil()) - Expect(replicas.Type).To(Equal("integer")) - - By("having conditions key") - Expect(status.Fields).To(HaveKey("conditions")) - conditions := status.Fields["conditions"].(*proto.Array) - Expect(conditions).ToNot(BeNil()) - Expect(conditions.GetName()).To(Equal(`Array of Reference to "io.k8s.api.apps.v1beta1.DeploymentCondition"`)) - Expect(conditions.GetExtensions()).To(Equal(map[string]interface{}{ - "x-kubernetes-patch-merge-key": "type", - "x-kubernetes-patch-strategy": "merge", - })) - condition := conditions.SubType.(proto.Reference) - Expect(condition.Reference()).To(Equal("io.k8s.api.apps.v1beta1.DeploymentCondition")) - }) - - var spec *proto.Kind - It("should have a spec key of type Reference", func() { - Expect(deployment.Fields).To(HaveKey("spec")) - key := deployment.Fields["spec"].(proto.Reference) - Expect(key).ToNot(BeNil()) - Expect(key.Reference()).To(Equal("io.k8s.api.apps.v1beta1.DeploymentSpec")) - spec = key.SubSchema().(*proto.Kind) - Expect(spec).ToNot(BeNil()) - }) - - It("should have a spec with no gvk", func() { - _, found := spec.GetExtensions()["x-kubernetes-group-version-kind"] - Expect(found).To(BeFalse()) - }) - - It("should have a spec with a PodTemplateSpec sub-field", func() { - Expect(spec.Fields).To(HaveKey("template")) - key := spec.Fields["template"].(proto.Reference) - Expect(key).ToNot(BeNil()) - Expect(key.Reference()).To(Equal("io.k8s.api.core.v1.PodTemplateSpec")) - }) -}) - -var _ = Describe("Reading authorization.k8s.io/v1/SubjectAccessReview from openAPIData", func() { - var models proto.Models - BeforeEach(func() { - s, err := fakeSchema.OpenAPISchema() - Expect(err).To(BeNil()) - models, err = proto.NewOpenAPIData(s) - Expect(err).To(BeNil()) - }) - - model := "io.k8s.api.authorization.v1.LocalSubjectAccessReview" - var schema proto.Schema - It("should lookup the Schema by its model", func() { - schema = models.LookupModel(model) - Expect(schema).ToNot(BeNil()) - }) - - var sarspec *proto.Kind - It("should be a Kind and have a spec", func() { - sar := schema.(*proto.Kind) - Expect(sar).ToNot(BeNil()) - Expect(sar.Fields).To(HaveKey("spec")) - specRef := sar.Fields["spec"].(proto.Reference) - Expect(specRef).ToNot(BeNil()) - Expect(specRef.Reference()).To(Equal("io.k8s.api.authorization.v1.SubjectAccessReviewSpec")) - sarspec = specRef.SubSchema().(*proto.Kind) - Expect(sarspec).ToNot(BeNil()) - }) - - It("should have a valid SubjectAccessReviewSpec", func() { - Expect(sarspec.Fields).To(HaveKey("extra")) - extra := sarspec.Fields["extra"].(*proto.Map) - Expect(extra).ToNot(BeNil()) - Expect(extra.GetName()).To(Equal("Map of Array of string")) - Expect(extra.GetPath().Get()).To(Equal([]string{"io.k8s.api.authorization.v1.SubjectAccessReviewSpec", ".extra"})) - array := extra.SubType.(*proto.Array) - Expect(array).ToNot(BeNil()) - Expect(array.GetName()).To(Equal("Array of string")) - Expect(array.GetPath().Get()).To(Equal([]string{"io.k8s.api.authorization.v1.SubjectAccessReviewSpec", ".extra"})) - str := array.SubType.(*proto.Primitive) - Expect(str).ToNot(BeNil()) - Expect(str.Type).To(Equal("string")) - Expect(str.GetName()).To(Equal("string")) - Expect(str.GetPath().Get()).To(Equal([]string{"io.k8s.api.authorization.v1.SubjectAccessReviewSpec", ".extra"})) - }) -}) - -var _ = Describe("Path", func() { - It("can be created by NewPath", func() { - path := proto.NewPath("key") - Expect(path.String()).To(Equal("key")) - }) - It("can create and print complex paths", func() { - key := proto.NewPath("key") - array := key.ArrayPath(12) - field := array.FieldPath("subKey") - - Expect(field.String()).To(Equal("key[12].subKey")) - }) - It("has a length", func() { - key := proto.NewPath("key") - array := key.ArrayPath(12) - field := array.FieldPath("subKey") - - Expect(field.Len()).To(Equal(3)) - }) - It("can look like an array", func() { - key := proto.NewPath("key") - array := key.ArrayPath(12) - field := array.FieldPath("subKey") - - Expect(field.Get()).To(Equal([]string{"key", "[12]", ".subKey"})) - }) -}) diff --git a/vendor/k8s.io/kubernetes/CHANGELOG-1.10.md b/vendor/k8s.io/kubernetes/CHANGELOG-1.10.md index 4bfb6ba20a..a8425414bc 100644 --- a/vendor/k8s.io/kubernetes/CHANGELOG-1.10.md +++ b/vendor/k8s.io/kubernetes/CHANGELOG-1.10.md @@ -1,75 +1,296 @@ <!-- BEGIN MUNGE: GENERATED_TOC --> -- [v1.10.0](#v1100) - - [Downloads for v1.10.0](#downloads-for-v1100) +- [v1.10.2](#v1102) + - [Downloads for v1.10.2](#downloads-for-v1102) - [Client Binaries](#client-binaries) - [Server Binaries](#server-binaries) - [Node Binaries](#node-binaries) -- [Release 1.10](#release-110) -- [v1.10.0-rc.1](#v1100-rc1) - - [Downloads for v1.10.0-rc.1](#downloads-for-v1100-rc1) + - [Changelog since v1.10.1](#changelog-since-v1101) + - [Other notable changes](#other-notable-changes) +- [v1.10.1](#v1101) + - [Downloads for v1.10.1](#downloads-for-v1101) - [Client Binaries](#client-binaries-1) - [Server Binaries](#server-binaries-1) - [Node Binaries](#node-binaries-1) - - [Changelog since v1.10.0-beta.4](#changelog-since-v1100-beta4) - - [Other notable changes](#other-notable-changes) -- [v1.10.0-beta.4](#v1100-beta4) - - [Downloads for v1.10.0-beta.4](#downloads-for-v1100-beta4) + - [Changelog since v1.10.0](#changelog-since-v1100) + - [Other notable changes](#other-notable-changes-1) +- [v1.10.0](#v1100) + - [Downloads for v1.10.0](#downloads-for-v1100) - [Client Binaries](#client-binaries-2) - [Server Binaries](#server-binaries-2) - [Node Binaries](#node-binaries-2) - - [Changelog since v1.10.0-beta.3](#changelog-since-v1100-beta3) - - [Other notable changes](#other-notable-changes-1) -- [v1.10.0-beta.3](#v1100-beta3) - - [Downloads for v1.10.0-beta.3](#downloads-for-v1100-beta3) + - [Major Themes](#major-themes) + - [Node](#node) + - [Storage](#storage) + - [Windows](#windows) + - [OpenStack](#openstack) + - [API-machinery](#api-machinery) + - [Auth](#auth) + - [Azure](#azure) + - [CLI](#cli) + - [Network](#network) + - [Before Upgrading](#before-upgrading) + - [Known Issues](#known-issues) + - [Deprecations](#deprecations) + - [Other Notable Changes](#other-notable-changes-2) + - [Apps](#apps) + - [AWS](#aws) + - [Auth](#auth-1) + - [CLI](#cli-1) + - [Cluster Lifecycle](#cluster-lifecycle) + - [GCP](#gcp) + - [Instrumentation](#instrumentation) + - [Node](#node-1) + - [OpenStack](#openstack-1) + - [Scalability](#scalability) + - [Storage](#storage-1) + - [Windows](#windows-1) + - [Autoscaling](#autoscaling) + - [API-Machinery](#api-machinery-1) + - [Network](#network-1) + - [Azure](#azure-1) + - [Scheduling](#scheduling) + - [Other changes](#other-changes) + - [Non-user-facing Changes](#non-user-facing-changes) + - [External Dependencies](#external-dependencies) +- [v1.10.0-rc.1](#v1100-rc1) + - [Downloads for v1.10.0-rc.1](#downloads-for-v1100-rc1) - [Client Binaries](#client-binaries-3) - [Server Binaries](#server-binaries-3) - [Node Binaries](#node-binaries-3) - - [Changelog since v1.10.0-beta.2](#changelog-since-v1100-beta2) - - [Other notable changes](#other-notable-changes-2) -- [v1.10.0-beta.2](#v1100-beta2) - - [Downloads for v1.10.0-beta.2](#downloads-for-v1100-beta2) + - [Changelog since v1.10.0-beta.4](#changelog-since-v1100-beta4) + - [Other notable changes](#other-notable-changes-3) +- [v1.10.0-beta.4](#v1100-beta4) + - [Downloads for v1.10.0-beta.4](#downloads-for-v1100-beta4) - [Client Binaries](#client-binaries-4) - [Server Binaries](#server-binaries-4) - [Node Binaries](#node-binaries-4) + - [Changelog since v1.10.0-beta.3](#changelog-since-v1100-beta3) + - [Other notable changes](#other-notable-changes-4) +- [v1.10.0-beta.3](#v1100-beta3) + - [Downloads for v1.10.0-beta.3](#downloads-for-v1100-beta3) + - [Client Binaries](#client-binaries-5) + - [Server Binaries](#server-binaries-5) + - [Node Binaries](#node-binaries-5) + - [Changelog since v1.10.0-beta.2](#changelog-since-v1100-beta2) + - [Other notable changes](#other-notable-changes-5) +- [v1.10.0-beta.2](#v1100-beta2) + - [Downloads for v1.10.0-beta.2](#downloads-for-v1100-beta2) + - [Client Binaries](#client-binaries-6) + - [Server Binaries](#server-binaries-6) + - [Node Binaries](#node-binaries-6) - [Changelog since v1.10.0-beta.1](#changelog-since-v1100-beta1) - [Action Required](#action-required) - - [Other notable changes](#other-notable-changes-3) + - [Other notable changes](#other-notable-changes-6) - [v1.10.0-beta.1](#v1100-beta1) - [Downloads for v1.10.0-beta.1](#downloads-for-v1100-beta1) - - [Client Binaries](#client-binaries-5) - - [Server Binaries](#server-binaries-5) - - [Node Binaries](#node-binaries-5) + - [Client Binaries](#client-binaries-7) + - [Server Binaries](#server-binaries-7) + - [Node Binaries](#node-binaries-7) - [Changelog since v1.10.0-alpha.3](#changelog-since-v1100-alpha3) - [Action Required](#action-required-1) - - [Other notable changes](#other-notable-changes-4) + - [Other notable changes](#other-notable-changes-7) - [v1.10.0-alpha.3](#v1100-alpha3) - [Downloads for v1.10.0-alpha.3](#downloads-for-v1100-alpha3) - - [Client Binaries](#client-binaries-6) - - [Server Binaries](#server-binaries-6) - - [Node Binaries](#node-binaries-6) + - [Client Binaries](#client-binaries-8) + - [Server Binaries](#server-binaries-8) + - [Node Binaries](#node-binaries-8) - [Changelog since v1.10.0-alpha.2](#changelog-since-v1100-alpha2) - - [Other notable changes](#other-notable-changes-5) + - [Other notable changes](#other-notable-changes-8) - [v1.10.0-alpha.2](#v1100-alpha2) - [Downloads for v1.10.0-alpha.2](#downloads-for-v1100-alpha2) - - [Client Binaries](#client-binaries-7) - - [Server Binaries](#server-binaries-7) - - [Node Binaries](#node-binaries-7) + - [Client Binaries](#client-binaries-9) + - [Server Binaries](#server-binaries-9) + - [Node Binaries](#node-binaries-9) - [Changelog since v1.10.0-alpha.1](#changelog-since-v1100-alpha1) - [Action Required](#action-required-2) - - [Other notable changes](#other-notable-changes-6) + - [Other notable changes](#other-notable-changes-9) - [v1.10.0-alpha.1](#v1100-alpha1) - [Downloads for v1.10.0-alpha.1](#downloads-for-v1100-alpha1) - - [Client Binaries](#client-binaries-8) - - [Server Binaries](#server-binaries-8) - - [Node Binaries](#node-binaries-8) + - [Client Binaries](#client-binaries-10) + - [Server Binaries](#server-binaries-10) + - [Node Binaries](#node-binaries-10) - [Changelog since v1.9.0](#changelog-since-v190) - [Action Required](#action-required-3) - - [Other notable changes](#other-notable-changes-7) + - [Other notable changes](#other-notable-changes-10) <!-- END MUNGE: GENERATED_TOC --> <!-- NEW RELEASE NOTES ENTRY --> +# v1.10.2 + +[Documentation](https://docs.k8s.io) & [Examples](https://releases.k8s.io/release-1.10/examples) + +## Downloads for v1.10.2 + + +filename | sha256 hash +-------- | ----------- +[kubernetes.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes.tar.gz) | `1ff377ad005a5548f872f7534328dcc332c683e527f432708eddcc549a6ab880` +[kubernetes-src.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-src.tar.gz) | `175a33ad6dec11e86e022b57e5e3f11280c70a04a309b1b915f030697e789d89` + +### Client Binaries + +filename | sha256 hash +-------- | ----------- +[kubernetes-client-darwin-386.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-client-darwin-386.tar.gz) | `95722e24ce02e4844563686f91773b053cf01ed66a46284a85f127a73528ae4c` +[kubernetes-client-darwin-amd64.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-client-darwin-amd64.tar.gz) | `3b5829a446b9eadae573c4d4e51dc69c1fe0af9453a88d0371095dd6560622bf` +[kubernetes-client-linux-386.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-client-linux-386.tar.gz) | `8a5d3d031e09b511be77efd8701841a46265204c99549ef99f7849f162022e32` +[kubernetes-client-linux-amd64.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-client-linux-amd64.tar.gz) | `84ca93bf6c427ad0cbef4f053c25deb3b267fea05aaa996b14f6b34db670e764` +[kubernetes-client-linux-arm.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-client-linux-arm.tar.gz) | `aa3775972d7f8e5ee833ad8f19c09fd42c908e51b5f80ea843983ce5741b4e3b` +[kubernetes-client-linux-arm64.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-client-linux-arm64.tar.gz) | `e7b272d498c5b914fa6918be6851979c79f7adc14c5778120e42f4cba1e9fbde` +[kubernetes-client-linux-ppc64le.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-client-linux-ppc64le.tar.gz) | `7913ba72de496e8a1cc38a2e7efa156f9b5fe8c3cad37a2056a406d852f4b0e2` +[kubernetes-client-linux-s390x.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-client-linux-s390x.tar.gz) | `87a4c565d1d782351f320b38a9a76c4a9141efd4fa4559f7abe98769ba9ccbba` +[kubernetes-client-windows-386.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-client-windows-386.tar.gz) | `1dfe9684bfaed00a185bdb791e292d078a6be23c7acc2941492fc11ad9a4f68d` +[kubernetes-client-windows-amd64.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-client-windows-amd64.tar.gz) | `3d6396737ca6f9e272348cd31f150a636d5cd90fae341712cdb9d809c2eab3e7` + +### Server Binaries + +filename | sha256 hash +-------- | ----------- +[kubernetes-server-linux-amd64.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-server-linux-amd64.tar.gz) | `350e48201e97c79639764e2380f3943aac944d602ad472f506be3f48923679d2` +[kubernetes-server-linux-arm.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-server-linux-arm.tar.gz) | `75425973f22d846896f293a2d416ea697d44511d35aa6c7dd777c8f6227e6655` +[kubernetes-server-linux-arm64.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-server-linux-arm64.tar.gz) | `85cdbfbeb12ad35d814e3e29c962daeb6d4995d694df4ff5fbc7aeddd96366d5` +[kubernetes-server-linux-ppc64le.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-server-linux-ppc64le.tar.gz) | `c75f906ec1397c7fc2d5a0a0edde25b789c122088dfb39d1a28adeec40e1ca49` +[kubernetes-server-linux-s390x.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-server-linux-s390x.tar.gz) | `af23a78f51906b84836e44300336348d7df99807e3b25cf46e8c406001433299` + +### Node Binaries + +filename | sha256 hash +-------- | ----------- +[kubernetes-node-linux-amd64.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-node-linux-amd64.tar.gz) | `9a8e88688de9ee5e32aab445d00e119d6d918bb28b238e75670055a37efac777` +[kubernetes-node-linux-arm.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-node-linux-arm.tar.gz) | `9ab0bec58796e9b48aded1deb8bdb64e9a030b0e5b38a22421d5f9d54326bcf5` +[kubernetes-node-linux-arm64.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-node-linux-arm64.tar.gz) | `aaf5e103e1cdcc2e8c4cb3485091dac6eaf2381bafaf8cb0c23fc77e4611adce` +[kubernetes-node-linux-ppc64le.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-node-linux-ppc64le.tar.gz) | `868d754868686db1d3900e48f12e3a79f94d7fed73d2827be8a1105f75787c6d` +[kubernetes-node-linux-s390x.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-node-linux-s390x.tar.gz) | `e4d0e3a647edf1c145171716f038f4eff652565f4fa12e57fca106d244579cd6` +[kubernetes-node-windows-amd64.tar.gz](https://dl.k8s.io/v1.10.2/kubernetes-node-windows-amd64.tar.gz) | `a25add831d97f2f4edc9e3ee02334e1831fe2ca165d901b9319546452bf01eca` + +## Changelog since v1.10.1 + +### Other notable changes + +* kubeadm upgrade no longer races leading to unexpected upgrade behavior on pod restarts ([#62655](https://github.com/kubernetes/kubernetes/pull/62655), [@stealthybox](https://github.com/stealthybox)) + * kubeadm upgrade now successfully upgrades etcd and the controlplane to use TLS + * kubeadm upgrade now supports external etcd setups + * kubeadm upgrade can now rollback and restore etcd after an upgrade failure +* Update version of Istio addon from 0.5.1 to 0.6.0. ([#61911](https://github.com/kubernetes/kubernetes/pull/61911), [@ostromart](https://github.com/ostromart)) + * See https://istio.io/about/notes/0.6.html for full Isto release notes. +* removed unsafe double RLock in cpumanager ([#62464](https://github.com/kubernetes/kubernetes/pull/62464), [@choury](https://github.com/choury)) +* Fix in vSphere Cloud Provider to handle upgrades from kubernetes version less than v1.9.4 to v1.9.4 and above. ([#62919](https://github.com/kubernetes/kubernetes/pull/62919), [@abrarshivani](https://github.com/abrarshivani)) +* Remove METADATA_AGENT_VERSION configuration option. ([#63000](https://github.com/kubernetes/kubernetes/pull/63000), [@kawych](https://github.com/kawych)) +* Fix in vSphere Cloud Provider to report disk is detach when VM is not found. ([#62220](https://github.com/kubernetes/kubernetes/pull/62220), [@abrarshivani](https://github.com/abrarshivani)) +* Restores ability to enable/disable resource within an API GroupVersion individually. ([#62116](https://github.com/kubernetes/kubernetes/pull/62116), [@deads2k](https://github.com/deads2k)) +* Fixes the kubernetes.default.svc loopback service resolution to use a loopback configuration. ([#62649](https://github.com/kubernetes/kubernetes/pull/62649), [@liggitt](https://github.com/liggitt)) +* Fix the liveness probe to use `/bin/bash -c` instead of `/bin/bash c`. ([#63033](https://github.com/kubernetes/kubernetes/pull/63033), [@bmoyles0117](https://github.com/bmoyles0117)) +* Fix error where config map for Metadata Agent was not created by addon manager. ([#62909](https://github.com/kubernetes/kubernetes/pull/62909), [@kawych](https://github.com/kawych)) +* GCE: Fix for internal load balancer management resulting in backend services with outdated instance group links. ([#62887](https://github.com/kubernetes/kubernetes/pull/62887), [@nicksardo](https://github.com/nicksardo)) +* respect fstype in Windows for azure disk ([#61267](https://github.com/kubernetes/kubernetes/pull/61267), [@andyzhangx](https://github.com/andyzhangx)) +* Update kube-dns to Version 1.14.10. Major changes: ([#62676](https://github.com/kubernetes/kubernetes/pull/62676), [@MrHohn](https://github.com/MrHohn)) + * - Fix a bug in DNS resolution for externalName services + * and PTR records that need to query from upstream nameserver. +* Fix machineID getting for vmss nodes when using instance metadata ([#62611](https://github.com/kubernetes/kubernetes/pull/62611), [@feiskyer](https://github.com/feiskyer)) +* GCE: Bump GLBC version to 1.1.1 - fixing an issue of handling multiple certs with identical certificates ([#62751](https://github.com/kubernetes/kubernetes/pull/62751), [@nicksardo](https://github.com/nicksardo)) +* fix nsenter GetFileType issue in containerized kubelet ([#62467](https://github.com/kubernetes/kubernetes/pull/62467), [@andyzhangx](https://github.com/andyzhangx)) +* fix WaitForAttach failure issue for azure disk ([#62612](https://github.com/kubernetes/kubernetes/pull/62612), [@andyzhangx](https://github.com/andyzhangx)) +* Pod affinity `nodeSelectorTerm.matchExpressions` may now be empty, and works as previously documented: nil or empty `matchExpressions` matches no objects in scheduler. ([#62448](https://github.com/kubernetes/kubernetes/pull/62448), [@k82cn](https://github.com/k82cn)) +* Fix user visible files creation for windows ([#62375](https://github.com/kubernetes/kubernetes/pull/62375), [@feiskyer](https://github.com/feiskyer)) +* Resolves forbidden error when the `daemon-set-controller` cluster role access `controllerrevisions` resources. ([#62146](https://github.com/kubernetes/kubernetes/pull/62146), [@frodenas](https://github.com/frodenas)) +* fixes configuration error when upgrading kubeadm from 1.9 to 1.10+ ([#62568](https://github.com/kubernetes/kubernetes/pull/62568), [@liztio](https://github.com/liztio)) + * enforces kubeadm upgrading kubernetes from the same major and minor versions as the kubeadm binary. +* Bugfix allowing use of IP-aliases with custom-mode network in GCE setup scripts. ([#62172](https://github.com/kubernetes/kubernetes/pull/62172), [@shyamjvs](https://github.com/shyamjvs)) +* Ensure expected load balancer is selected for Azure ([#62450](https://github.com/kubernetes/kubernetes/pull/62450), [@feiskyer](https://github.com/feiskyer)) +* fix the issue that default azure disk fsypte(ext4) does not work on Windows ([#62250](https://github.com/kubernetes/kubernetes/pull/62250), [@andyzhangx](https://github.com/andyzhangx)) +* gitRepo volumes in pods no longer require git 1.8.5 or newer, older git versions are supported too now. ([#62394](https://github.com/kubernetes/kubernetes/pull/62394), [@jsafrane](https://github.com/jsafrane)) +* Fixes issue where PersistentVolume.NodeAffinity.NodeSelectorTerms were ANDed instead of ORed. ([#62556](https://github.com/kubernetes/kubernetes/pull/62556), [@msau42](https://github.com/msau42)) +* Cluster Autoscaler 1.2.1 (release notes: https://github.com/kubernetes/autoscaler/releases/tag/cluster-autoscaler-1.2.1) ([#62457](https://github.com/kubernetes/kubernetes/pull/62457), [@mwielgus](https://github.com/mwielgus)) +* Return error if get NodeStageSecret and NodePublishSecret failed in CSI volume plugin ([#61096](https://github.com/kubernetes/kubernetes/pull/61096), [@mlmhl](https://github.com/mlmhl)) +* fix incompatible file type checking on Windows ([#62154](https://github.com/kubernetes/kubernetes/pull/62154), [@dixudx](https://github.com/dixudx)) + + + +# v1.10.1 + +[Documentation](https://docs.k8s.io) & [Examples](https://releases.k8s.io/release-1.10/examples) + +## Downloads for v1.10.1 + + +filename | sha256 hash +-------- | ----------- +[kubernetes.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes.tar.gz) | `877f83d7475eade8104388799a842d1002f5ef8f284154bed229a25862ed2bde` +[kubernetes-src.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-src.tar.gz) | `7c0f5b80e89e1a7bd5cd859d505bfafbcf873ad99be9ac22b422d9ef732a5d4c` + +### Client Binaries + +filename | sha256 hash +-------- | ----------- +[kubernetes-client-darwin-386.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-client-darwin-386.tar.gz) | `e7eca1569c705752ab8aef07623d2a9a3b8d798c71b702b4d5c18892d455349d` +[kubernetes-client-darwin-amd64.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-client-darwin-amd64.tar.gz) | `68c5080b85c2ab5340268e21585e309eacef64fcd175b869194b4d6b0bec2467` +[kubernetes-client-linux-386.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-client-linux-386.tar.gz) | `bd08ce097e25e970eea3f13d02e322770a036eed8a63ac6fb1364f6ad1283e5c` +[kubernetes-client-linux-amd64.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-client-linux-amd64.tar.gz) | `f638cf6121e25762e2f6f36bca9818206778942465f0ea6e3ba59cfcc9c2738a` +[kubernetes-client-linux-arm.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-client-linux-arm.tar.gz) | `7d395f3c0f27a14c9980f930a2b8c4b56528a09c477a5121b71ff54c17b61f73` +[kubernetes-client-linux-arm64.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-client-linux-arm64.tar.gz) | `75fd5b1eeb082df201abc91e7a98b280817692c52f723ed2ff8234097eaff841` +[kubernetes-client-linux-ppc64le.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-client-linux-ppc64le.tar.gz) | `56b4102881c3945765bbc94efa035628a522911a4ddb2a80e63255bbe989db2d` +[kubernetes-client-linux-s390x.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-client-linux-s390x.tar.gz) | `f4e6f10f265a2cf9b71fad9ce2ddb28d577cc79643321e31318261f140d612e1` +[kubernetes-client-windows-386.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-client-windows-386.tar.gz) | `86c591895cfee141b147d58d13af2c75cfb03a0ae615a70300a63a3a45132243` +[kubernetes-client-windows-amd64.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-client-windows-amd64.tar.gz) | `b2caa7e6a192c1333614b3aae412cdbbc764431c1e59ace53ca6792aa7ec6496` + +### Server Binaries + +filename | sha256 hash +-------- | ----------- +[kubernetes-server-linux-amd64.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-server-linux-amd64.tar.gz) | `c66ad48fb37c6bd31e86f7633742eab7ccb136cd7268f1f642ca52fdb814f1a5` +[kubernetes-server-linux-arm.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-server-linux-arm.tar.gz) | `8ef4a278639f3335c033d385e57a286043b7172dc7613403f841f05486dc731a` +[kubernetes-server-linux-arm64.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-server-linux-arm64.tar.gz) | `5987762c352155a5d378760e91af55c6180bdb25be1bf3799e9317d9435ab05a` +[kubernetes-server-linux-ppc64le.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-server-linux-ppc64le.tar.gz) | `014409580ccc492caaee30e1136e88b4580608b1eedf2c9da96488a05b586110` +[kubernetes-server-linux-s390x.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-server-linux-s390x.tar.gz) | `dc2fb6e1f53e11fc161b617ceef09f4117e54e18ade24401813c934283e8ee6f` + +### Node Binaries + +filename | sha256 hash +-------- | ----------- +[kubernetes-node-linux-amd64.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-node-linux-amd64.tar.gz) | `6398c87906dbd37ccd881ca4169713c512a7bd04e336f4c81d2497c460be855f` +[kubernetes-node-linux-arm.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-node-linux-arm.tar.gz) | `54e24107ac1f98fa75ce3c603c4f8c3edcf7277046deaff2cef55521147ac956` +[kubernetes-node-linux-arm64.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-node-linux-arm64.tar.gz) | `7d9c8aa2ee5f2d6207a6bac9e32639ea14fe830e6bb57f2ab4fc4ad47b6772c4` +[kubernetes-node-linux-ppc64le.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-node-linux-ppc64le.tar.gz) | `339ce8cb3e703fd2252e6978bfbdd2c26d46516ed8ef4f548e2e1fd2b7d4b49e` +[kubernetes-node-linux-s390x.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-node-linux-s390x.tar.gz) | `896396437d74a8a1c8c310de1666cc95d4d5bbee67c201c400c383e9fb6818f2` +[kubernetes-node-windows-amd64.tar.gz](https://dl.k8s.io/v1.10.1/kubernetes-node-windows-amd64.tar.gz) | `9932e75059ffb8c9a7400ffd5620fb114fcd53961651f97b943298bb8a7dd24a` + +## Changelog since v1.10.0 + +### Other notable changes + +* Fix panic create/update CRD when mutating/validating webhook configured. ([#61404](https://github.com/kubernetes/kubernetes/pull/61404), [@hzxuzhonghu](https://github.com/hzxuzhonghu)) +* Add support to ingest log entries to Stackdriver against new "k8s_container" and "k8s_node" resources. ([#62076](https://github.com/kubernetes/kubernetes/pull/62076), [@qingling128](https://github.com/qingling128)) +* new dhcp-domain parameter to be used for figuring out the hostname of a node ([#61890](https://github.com/kubernetes/kubernetes/pull/61890), [@dims](https://github.com/dims)) +* Extend the Stackdriver Metadata Agent by adding a new Deployment for ingesting unscheduled pods, and services. ([#62043](https://github.com/kubernetes/kubernetes/pull/62043), [@supriyagarg](https://github.com/supriyagarg)) +* Fixed a panic in `kubectl run --attach ...` when the api server failed to create the runtime object (due to name conflict, PSP restriction, etc.) ([#61713](https://github.com/kubernetes/kubernetes/pull/61713), [@mountkin](https://github.com/mountkin)) +* Fix a bug that fluentd doesn't inject container logs for CRI container runtimes (containerd, cri-o etc.) into elasticsearch on GCE. ([#61818](https://github.com/kubernetes/kubernetes/pull/61818), [@Random-Liu](https://github.com/Random-Liu)) +* fix local volume issue on Windows ([#62012](https://github.com/kubernetes/kubernetes/pull/62012), [@andyzhangx](https://github.com/andyzhangx)) +* Fixed bug in rbd-nbd utility when nbd is used. ([#62168](https://github.com/kubernetes/kubernetes/pull/62168), [@piontec](https://github.com/piontec)) +* GCE: Updates GLBC version to 1.0.1 which includes a fix which prevents multi-cluster ingress objects from creating full load balancers. ([#62075](https://github.com/kubernetes/kubernetes/pull/62075), [@nicksardo](https://github.com/nicksardo)) +* Fix GCE etcd scripts to pass in all required parameters for the etcd migration utility to correctly perform HA upgrades and downgrades ([#61960](https://github.com/kubernetes/kubernetes/pull/61960), [@jpbetz](https://github.com/jpbetz)) +* Update kube-dns to Version 1.14.9. Major changes: ([#61908](https://github.com/kubernetes/kubernetes/pull/61908), [@MrHohn](https://github.com/MrHohn)) + * - Fix for kube-dns returns NXDOMAIN when not yet synced with apiserver. + * - Don't generate empty record for externalName service. + * - Add validation for upstreamNameserver port. + * - Update go version to 1.9.3. +* kubectl: improves compatibility with older servers when creating/updating API objects ([#61949](https://github.com/kubernetes/kubernetes/pull/61949), [@liggitt](https://github.com/liggitt)) +* Bound cloud allocator to 10 retries with 100 ms delay between retries. ([#61375](https://github.com/kubernetes/kubernetes/pull/61375), [@satyasm](https://github.com/satyasm)) +* Fixed [#61123](https://github.com/kubernetes/kubernetes/pull/61123) by triggering syncer.Update on all cases including when a syncer is created ([#61124](https://github.com/kubernetes/kubernetes/pull/61124), [@satyasm](https://github.com/satyasm)) + * on a new add event. +* Add ipset and udevadm to the hyperkube base image. ([#61357](https://github.com/kubernetes/kubernetes/pull/61357), [@rphillips](https://github.com/rphillips)) +* kubectl: restore the ability to show resource kinds when displaying multiple objects ([#61985](https://github.com/kubernetes/kubernetes/pull/61985), [@liggitt](https://github.com/liggitt)) +* Remove 'system' prefix from Metadata Agent rbac configuration ([#61394](https://github.com/kubernetes/kubernetes/pull/61394), [@kawych](https://github.com/kawych)) +* Ensure cloudprovider.InstanceNotFound is reported when the VM is not found on Azure ([#61531](https://github.com/kubernetes/kubernetes/pull/61531), [@feiskyer](https://github.com/feiskyer)) +* kubectl: fixes issue with `-o yaml` and `-o json` omitting kind and apiVersion when used with `--dry-run` ([#61808](https://github.com/kubernetes/kubernetes/pull/61808), [@liggitt](https://github.com/liggitt)) +* Bump Heapster to v1.5.2 ([#61396](https://github.com/kubernetes/kubernetes/pull/61396), [@kawych](https://github.com/kawych)) +* Support new NODE_OS_DISTRIBUTION 'custom' on GCE ([#61235](https://github.com/kubernetes/kubernetes/pull/61235), [@yguo0905](https://github.com/yguo0905)) +* Fix mounting of UNIX sockets(and other special files) in subpaths ([#61480](https://github.com/kubernetes/kubernetes/pull/61480), [@gnufied](https://github.com/gnufied)) +* [fluentd-gcp addon] Update event-exporter image to have the latest base image. ([#61727](https://github.com/kubernetes/kubernetes/pull/61727), [@crassirostris](https://github.com/crassirostris)) + + + # v1.10.0 [Documentation](https://docs.k8s.io) & [Examples](https://releases.k8s.io/release-1.10/examples) @@ -118,7 +339,6 @@ filename | sha256 hash [kubernetes-node-linux-s390x.tar.gz](https://dl.k8s.io/v1.10.0/kubernetes-node-linux-s390x.tar.gz) | `afe35c2854f35939be75ccfb0ec81399acf4043ae7cf19dd6fbe6386288972c2` [kubernetes-node-windows-amd64.tar.gz](https://dl.k8s.io/v1.10.0/kubernetes-node-windows-amd64.tar.gz) | `eac14e3420ca9769e067cbf929b5383cd77d56e460880a30c0df1bbfbb5a43db` -# Release 1.10 ## Major Themes ### Node @@ -133,7 +353,7 @@ This release brings additional power to both local storage and Persistent Volume On the Persistent Volumes side, this release [Prevents deletion of Persistent Volume Claims that are used by a pod](https://github.com/kubernetes/features/issues/498) and [Persistent Volumes that are bound to a Persistent Volume Claim](https://github.com/kubernetes/features/issues/499), making it impossible to delete storage that is in use by a pod. -This release also includes [Topology Aware Volume Scheduling](https://github.com/kubernetes/features/issues/490) for local persistent volumes and beta support for [Out-of-tree CSI Volume Plugins](https://github.com/kubernetes/features/issues/178). +This release also includes [Topology Aware Volume Scheduling](https://github.com/kubernetes/features/issues/490) for local persistent volumes, the stable release of [Detailed storage metrics of internal state](https://github.com/kubernetes/features/issues/496), and beta support for [Out-of-tree CSI Volume Plugins](https://github.com/kubernetes/features/issues/178). ### Windows @@ -165,6 +385,8 @@ In terms of networking, Kubernetes 1.10 is about control. Users now have beta su ## Before Upgrading +* If you need to downgrade from 1.10 to 1.9.x, downgrade to v1.9.6 to ensure PV and PVC objects can be deleted properly. + * In-place node upgrades to this release from versions 1.7.14, 1.8.9, and 1.9.4 are not supported if using subpath volumes with PVCs. Such pods should be drained from the node first. * The minimum supported version of Docker is now 1.11; if you are using Docker 1.10 or below, be sure to upgrade Docker before upgrading Kubernetes. ([#57845](https://github.com/kubernetes/kubernetes/pull/57845), [@yujuhong](https://github.com/yujuhong)) @@ -196,6 +418,39 @@ kind: KubeProxyConfiguration ** SupportIPVSProxyMode: true** ``` +If your cluster was installed by kubeadm, you should edit the `featureGates` field in the `kubeadm-config` ConfigMap. You can do this using `kubectl -n kube-system edit cm kubeadm-config` before upgrading. For example: + +kubeadm-config Before: + +``` +apiVersion: v1 +kind: ConfigMap +metadata: + name: kubeadm-config +data: + MasterConfiguration: | + kubeProxy: + config: + featureGates: "SupportIPVSProxyMode=true" +``` + +kubeadm-config After: + +``` +apiVersion: v1 +kind: ConfigMap +metadata: + name: kubeadm-config +data: + MasterConfiguration: | + kubeProxy: + config: + featureGates: + SupportIPVSProxyMode: true +``` + +If no featureGates was specified in `kubeadm-config`, just change `featureGates: ""` to `featureGates: {}`. + ([#57962](https://github.com/kubernetes/kubernetes/pull/57962), [@xiangpengzhao](https://github.com/xiangpengzhao)) * The `kubeletconfig` API group has graduated from alpha to beta, and the name has changed to `kubelet.config.k8s.io`. Please use `kubelet.config.k8s.io/v1beta1`, as `kubeletconfig/v1alpha1` is no longer available. ([#53833](https://github.com/kubernetes/kubernetes/pull/53833), [@mtaufen](https://github.com/mtaufen)) @@ -256,12 +511,16 @@ kind: KubeProxyConfiguration ## Known Issues +* If you need to downgrade from 1.10 to 1.9.x, downgrade to v1.9.6 to ensure PV and PVC objects can be deleted properly. + * Use of subPath module with hostPath volumes can cause issues during reconstruction ([#61446](https://github.com/kubernetes/kubernetes/issues/61446)) and with containerized kubelets ([#61456](https://github.com/kubernetes/kubernetes/issues/61456)). The workaround for this issue is to specify the complete path in the hostPath volume. Use of subPathmounts nested within atomic writer volumes (configmap, secret, downwardAPI, projected) does not work ([#61545](https://github.com/kubernetes/kubernetes/issues/61545)), and socket files cannot be loaded from a subPath ([#62377](https://github.com/kubernetes/kubernetes/issues/61377)). Work on these issues is ongoing. * Kubeadm is currently omitting etcd certificates in a self-hosted deployment; this will be fixed in a point relelase. ([#61322](https://github.com/kubernetes/kubernetes/issues/61322)) * Some users, especially those with very large clusters, may see higher memory usage by the kube-controller-manager in 1.10. ([#61041](https://github.com/kubernetes/kubernetes/issues/61041)) +* Due to an issue in ingress-gce controller in 1.10.0, creating multi-cluster ingresses with [kubemci CLI](https://github.com/GoogleCloudPlatform/k8s-multicluster-ingress) fails. This will be fixed in 1.10.1 release. ([GoogleCloudPlatform/k8s-multicluster-ingress#175](https://github.com/GoogleCloudPlatform/k8s-multicluster-ingress/issues/175)) + ## Deprecations * etcd2 as a backend is deprecated and support will be removed in Kubernetes 1.13. @@ -286,7 +545,7 @@ kind: KubeProxyConfiguration * The `PodSecurityPolicy` API has been moved to the `policy/v1beta1` API group. The `PodSecurityPolicy` API in the `extensions/v1beta1` API group is deprecated and will be removed in a future release. Authorizations for using pod security policy resources should change to reference the `policy` API group after upgrading to 1.11. ([#54933](https://github.com/kubernetes/kubernetes/pull/54933), [@php-coder](https://github.com/php-coder)) -* Add `--enable-admission-plugin` `--disable-admission-plugin` flags and deprecate `--admission-control`. When using the separate flag, the order in which they're specified doesn't matter. ([#58123](https://github.com/kubernetes/kubernetes/pull/58123), [@hzxuzhonghu](https://github.com/hzxuzhonghu)) +* Add `--enable-admission-plugins` `--disable-admission-plugins` flags and deprecate `--admission-control`. When using the separate flag, the order in which they're specified doesn't matter. ([#58123](https://github.com/kubernetes/kubernetes/pull/58123), [@hzxuzhonghu](https://github.com/hzxuzhonghu)) * The kubelet --docker-disable-shared-pid flag, which runs docker containers with a process namespace that is shared between all containers in a pod, is now deprecated and will be removed in a future release. It is replaced by `v1.Pod.Spec.ShareProcessNamespace`, which configures this behavior. This field is alpha and can be enabled with --feature-gates=PodShareProcessNamespace=true. ([#58093](https://github.com/kubernetes/kubernetes/pull/58093), [@verb](https://github.com/verb)) @@ -412,7 +671,7 @@ Accept: application/com.github.proto-openapi.spec.v2@v1.0+protobuf Accept-Encodi * Added docker-logins config to kubernetes-worker charm. ([#56217](https://github.com/kubernetes/kubernetes/pull/56217), [@Cynerva](https://github.com/Cynerva)) -* Add ability to control primary GID of containers through Pod Spec at Pod level and Per Container SecurityContext level. ([#52077](https://github.com/kubernetes/kubernetes/pull/52077)) +* Add ability to control primary GID of containers through Pod Spec at Pod level and Per Container SecurityContext level. ([#52077](https://github.com/kubernetes/kubernetes/pull/52077), [@krmayankk](https://github.com/krmayankk)) ### CLI @@ -536,6 +795,7 @@ And point to the file using the --config flag, as in * [stable] [containerd](https://github.com/containerd/containerd): containerd v1.1 natively supports CRI v1alpha2 now, so users can use Kubernetes v1.10 with containerd v1.1 directly, without having to use the intermediate cri-containerd daemon. [All Kubernetes 1.10 tests passed](https://k8s-testgrid.appspot.com/sig-node-containerd). [@Random-Liu] * [stable] [cri-o](https://github.com/kubernetes-incubator/cri-o): cri-o v1.10 updated CRI version to v1alpha2 and made several bug and stability fixes. [@mrunalp] * [stable] [frakti](https://github.com/kubernetes/frakti): frakti v1.10 implemented GCE Persistent Disk as a high performance volume, fixed several bugs, added ARM64 support, and passed all CRI validation conformance tests and node e2e conformance tests. [@resouer] + * [alpha] CRI now supports specifying the GID of the container at both LinuxSandboxSecurityContext and LinuxContainerSecurityContext in addition to specifying the UID. Support is implemented for dockershim. [@krmayankk] * Fixed race conditions around devicemanager Allocate() and endpoint deletion. ([#60856](https://github.com/kubernetes/kubernetes/pull/60856), [@jiayingz](https://github.com/jiayingz)) @@ -561,17 +821,552 @@ And point to the file using the --config flag, as in * The DevicePlugins feature has graduated to beta, and is now enabled by default; users should focus on moving to the v1beta API if possible. ([#60170](https://github.com/kubernetes/kubernetes/pull/60170), [@jiayingz](https://github.com/jiayingz)) -This will be used to track release notes for Kubernetes 1.10. -- [v1.10.0-rc.1](#v1100-rc1) -- [v1.10.0-beta.4](#v1100-beta4) -- [v1.10.0-beta.3](#v1100-beta3) -- [v1.10.0-beta.2](#v1100-beta2) -- [v1.10.0-beta.1](#v1100-beta1) -- [v1.10.0-alpha.3](#v1100-alpha3) -- [v1.10.0-alpha.2](#v1100-alpha2) -- [v1.10.0-alpha.1](#v1100-alpha1) +* Per-cpu metrics have been disabled by default for to improve scalability. ([#60106](https://github.com/kubernetes/kubernetes/pull/60106), [@dashpole](https://github.com/dashpole)) + +* When the `PodShareProcessNamespace` alpha feature is enabled, setting `pod.Spec.ShareProcessNamespace` to `true` will cause a single process namespace to be shared between all containers in a pod. ([#58716](https://github.com/kubernetes/kubernetes/pull/58716), [@verb](https://github.com/verb)) + +* Resource quotas on extended resources such as GPUs are now supported. ([#57302](https://github.com/kubernetes/kubernetes/pull/57302), [@lichuqiang](https://github.com/lichuqiang)) + +* If the TaintNodesByCondition is enabled, a node will be tainted when it is under PID pressure. ([#60008](https://github.com/kubernetes/kubernetes/pull/60008), [@k82cn](https://github.com/k82cn)) + +* The Kubelet Summary API will now include total usage of pods through the "pods" SystemContainer. ([#57802](https://github.com/kubernetes/kubernetes/pull/57802), [@dashpole](https://github.com/dashpole)) + +* vSphere Cloud Provider supports VMs provisioned on vSphere v6.5. ([#59519](https://github.com/kubernetes/kubernetes/pull/59519), [@abrarshivani](https://github.com/abrarshivani)) + +* Created k8s.gcr.io image repo alias to pull images from the closest regional repo. Replaces gcr.io/google_containers. ([#57824](https://github.com/kubernetes/kubernetes/pull/57824), [@thockin](https://github.com/thockin)) + +* Fix the bug where kubelet in the standalone mode would wait for the update from the apiserver source, even if there wasn't one. ([#59276](https://github.com/kubernetes/kubernetes/pull/59276), [@roboll](https://github.com/roboll)) + +* Changes secret, configMap, downwardAPI and projected volumes to mount read-only, instead of allowing applications to write data and then reverting it automatically. Until version 1.11, setting the feature gate ReadOnlyAPIDataVolumes=false will preserve the old behavior. ([#58720](https://github.com/kubernetes/kubernetes/pull/58720), [@joelsmith](https://github.com/joelsmith)) + +* Fixes a bug where kubelet crashes trying to free memory under memory pressure. ([#58574](https://github.com/kubernetes/kubernetes/pull/58574), [@yastij](https://github.com/yastij)) + +* New alpha feature limits the number of processes running in a pod. Cluster administrators will be able to place limits by using the new kubelet command line parameter --pod-max-pids. Note that since this is a alpha feature they will need to enable the "SupportPodPidsLimit" feature. By default, we do not set any maximum limit, If an administrator wants to enable this, they should enable SupportPodPidsLimit=true in the --feature-gates= parameter to kubelet and specify the limit using the --pod-max-pids parameter. The limit set is the total count of all processes running in all containers in the pod. ([#57973](https://github.com/kubernetes/kubernetes/pull/57973),[@dims](https://github.com/dims)) + +* Fixes bug finding master replicas in GCE when running multiple Kubernetes clusters. ([#58561](https://github.com/kubernetes/kubernetes/pull/58561), [@jesseshieh](https://github.com/jesseshieh)) + +* --tls-min-version on kubelet and kube-apiserver allow for configuring minimum TLS versions ([#58528](https://github.com/kubernetes/kubernetes/pull/58528), [@deads2k](https://github.com/deads2k)) + +* Fix a bug affecting nested data volumes such as secret, configmap, etc. ([#57422](https://github.com/kubernetes/kubernetes/pull/57422), [@joelsmith](https://github.com/joelsmith)) + +* kubelet will no longer attempt to remove images being used by running containers when garbage collecting. ([#57020](https://github.com/kubernetes/kubernetes/pull/57020), [@dixudx](https://github.com/dixudx)) + +* Allow kubernetes components to react to SIGTERM signal and shutdown gracefully. ([#57756](https://github.com/kubernetes/kubernetes/pull/57756), [@mborsz](https://github.com/mborsz)) + +* Fixed garbage collection and resource quota issue when the controller-manager uses --leader-elect=false ([#57340](https://github.com/kubernetes/kubernetes/pull/57340), [@jmcmeek](https://github.com/jmcmeek)) + +* Fixed issue creating docker secrets with kubectl 1.9 for accessing docker private registries. ([#57463](https://github.com/kubernetes/kubernetes/pull/57463), [@dims](https://github.com/dims)) + +* The CPU Manager feature is now beta, and is enabled by default, but the default policy is no-op so no action is required. ([#55977](https://github.com/kubernetes/kubernetes/pull/55977), [@ConnorDoyle](https://github.com/ConnorDoyle)) + +### OpenStack + +* Fixed a bug in the OpenStack cloud provider where dual stack deployments (IPv4 and IPv6) did not work well when using kubenet as the network plugin. ([#59749](https://github.com/kubernetes/kubernetes/pull/59749), [@zioproto](https://github.com/zioproto)) + +* Fixed a bug that tries to use the octavia client to query flip. ([#59075](https://github.com/kubernetes/kubernetes/pull/59075), [@jrperritt](https://github.com/jrperritt)) + +* Kubernetes now registers metadata.hostname as node name for OpenStack nodes, eliminating a problem with invalid node names. ([#58502](https://github.com/kubernetes/kubernetes/pull/58502), [@dixudx](https://github.com/dixudx)) + +* Authentication information for OpenStack cloud provider can now be specified as environment variables. When we convert the OpenStack cloud provider to run in an external process, we can now use the kubernetes Secrets capability to inject the OS_* variables. This way we can specify the cloud configuration as a configmap, and specify secrets for the userid/password information. The configmap is mounted as a file, and the secrets are made available as environment variables. The external controller itself runs as a pod/daemonset. For backward compatibility, we preload all the OS_* variables, and if anything is in the config file, then that overrides the environment variables. ([#58300](https://github.com/kubernetes/kubernetes/pull/58300), [@dims](https://github.com/dims)) + +* Fixed issue when using OpenStack config drive for node metadata. Since we need to run commands such as blkid, we need to ensure that api server and kube controller are running in the privileged mode. ([#57561](https://github.com/kubernetes/kubernetes/pull/57561), [@dims](https://github.com/dims)) + +* Orphaned routes are properly removed from terminated instances. ([#56258](https://github.com/kubernetes/kubernetes/pull/56258), [@databus23](https://github.com/databus23)) + +* OpenStack Cinder will now detach properly when Nova is shut down. ([#56846](https://github.com/kubernetes/kubernetes/pull/56846), [@zetaab](https://github.com/zetaab)) +### Scalability + +* Added the ability to limit the increase in apiserver memory usage when audit logging with buffering is enabled. ([#61118](https://github.com/kubernetes/kubernetes/pull/61118), [@shyamjvs](https://github.com/shyamjvs)) + +* Upgrade to etcd client 3.2.13 and grpc 1.7.5 to improve HA etcd cluster stability. ([#57480](https://github.com/kubernetes/kubernetes/pull/57480), [@jpbetz](https://github.com/jpbetz)) + +### Storage + +* Fixes CVE-2017-1002101 - See [https://issue.k8s.io/60813](https://issue.k8s.io/60813) for details on this **major security fix**. ([#61044](https://github.com/kubernetes/kubernetes/pull/61044), [@liggitt](https://github.com/liggitt)) + +* Fixed missing error checking that could cause kubelet to crash in a race condition. ([#60962](https://github.com/kubernetes/kubernetes/pull/60962), [@technicianted](https://github.com/technicianted)) + +* Fixed a regression that prevented using `subPath` volume mounts with secret, configMap, projected, and downwardAPI volumes. ([#61080](https://github.com/kubernetes/kubernetes/pull/61080), [@liggitt](https://github.com/liggitt)) + +* K8s supports cephfs fuse mount. ([#55866](https://github.com/kubernetes/kubernetes/pull/55866), [@zhangxiaoyu-zidif](https://github.com/zhangxiaoyu-zidif)) + +* Use GiB unit for creating and resizing volumes for Glusterfs. ([#56581](https://github.com/kubernetes/kubernetes/pull/56581), [@gnufied](https://github.com/gnufied)) + +* Adding support for Block Volume type to rbd plugin. ([#56651](https://github.com/kubernetes/kubernetes/pull/56651), [@sbezverk](https://github.com/sbezverk)) + +* Add FSType for CSI volume source to specify filesystems (alpha defaults to ext4) ([#58209](https://github.com/kubernetes/kubernetes/pull/58209), [@NickrenREN](https://github.com/NickrenREN)) + +* Enabled File system resize of mounted volumes. ([#58794](https://github.com/kubernetes/kubernetes/pull/58794), [@gnufied](https://github.com/gnufied)) + +* The Local Volume Plugin has been updated to support Block volumeMode PVs. With this change, it is now possible to create local volume PVs for raw block devices. ([#59303](https://github.com/kubernetes/kubernetes/pull/59303), [@dhirajh](https://github.com/dhirajh)) + +* Fixed an issue where Portworx volume driver wasn't passing namespace and annotations to the Portworx Create API. ([#59607](https://github.com/kubernetes/kubernetes/pull/59607), [@harsh-px](https://github.com/harsh-px)) + +* Addressed breaking changes introduced by new 0.2.0 release of CSI spec. Specifically, csi.Version was removed from all API calls and CcontrollerProbe and NodeProbe were consolidated into a single Probe API call. ([#59209](https://github.com/kubernetes/kubernetes/pull/59209), [@sbezverk](https://github.com/sbezverk)) + +* GCE PD volume plugin now supports block volumes. ([#58710](https://github.com/kubernetes/kubernetes/pull/58710), [@screeley44](https://github.com/screeley44)) +* Implements MountDevice and UnmountDevice for the CSI Plugin, the functions will call through to NodeStageVolume/NodeUnstageVolume for CSI plugins. ([#60115](https://github.com/kubernetes/kubernetes/pull/60115), [@davidz627](https://github.com/davidz627)) + +* The LocalStorageCapacityIsolation feature is beta and enabled by default. The LocalStorageCapacityIsolation feature added a new resource type ResourceEphemeralStorage "ephemeral-storage" so that this resource can be allocated, limited, and consumed as the same way as CPU/memory. All the features related to resource management (resource request/limit, quota, limitrange) are available for local ephemeral storage. This local ephemeral storage represents the storage for root file system, which will be consumed by containers' writable layer and logs. Some volumes such as emptyDir might also consume this storage. ([#60159](https://github.com/kubernetes/kubernetes/pull/60159), [@jingxu97](https://github.com/jingxu97)) + +* VolumeScheduling and LocalPersistentVolume features are beta and enabled by default. The PersistentVolume NodeAffinity alpha annotation is deprecated and will be removed in a future release. ([#59391](https://github.com/kubernetes/kubernetes/pull/59391), [@msau42](https://github.com/msau42)) + +* K8s now supports rbd-nbd for Ceph rbd volume mounts. ([#58916](https://github.com/kubernetes/kubernetes/pull/58916), [@ianchakeres](https://github.com/ianchakeres)) + +* CSI now allows credentials to be specified on CreateVolume/DeleteVolume, ControllerPublishVolume/ControllerUnpublishVolume, and NodePublishVolume/NodeUnpublishVolume operations. Before this change all API calls had to fetch key/value stored in secret and use it to authenticate/authorize these operations. With this change API calls receive key/value as a input parameter so they not need to know where and how credentials were stored and fetched. Main goal was to make these API calls CO (Container Orchestrator) agnostic. ([#60118](https://github.com/kubernetes/kubernetes/pull/60118), [@sbezverk](https://github.com/sbezverk)) + +* StorageOS volume plugin has been updated to support mount options and environments where the kubelet runs in a container and the device location should be specified. ([#58816](https://github.com/kubernetes/kubernetes/pull/58816), [@croomes](https://github.com/croomes)) + +* Get parent dir via canonical absolute path when trying to judge mount-point, fixing a problem that caused an NFS volume with improper permissions to get stuck in `TERMINATING` status. ([#58433](https://github.com/kubernetes/kubernetes/pull/58433), [@yue9944882](https://github.com/yue9944882)) + +* Clusters with GCE feature 'DiskAlphaAPI' enabled can now dynamically provision GCE PD volumes. ([#59447](https://github.com/kubernetes/kubernetes/pull/59447), [@verult](https://github.com/verult)) + +* Added `keyring` parameter for Ceph RBD provisioner. ([#58287](https://github.com/kubernetes/kubernetes/pull/58287), [@madddi](https://github.com/madddi)) + +* Added xfsprogs to hyperkube container image. ([#56937](https://github.com/kubernetes/kubernetes/pull/56937), [@redbaron](https://github.com/redbaron)) + +* Improved messages user gets during and after volume resizing is done, providing a clear message to the user explaining what to do when resizing is finished. ([#58415](https://github.com/kubernetes/kubernetes/pull/58415), [@gnufied](https://github.com/gnufied)) + +* MountPropagation feature is now beta. As consequence, all volume mounts in containers are now "rslave" on Linux by default. To make this default work in all Linux environments you should have entire mount tree marked as shareable via "mount --make-rshared /". All Linux distributions that use systemd already have root directory mounted as rshared and hence they need not do anything. In Linux environments without systemd we recommend running "mount --make-rshared /" during boot, before docker is started. ([#59252](https://github.com/kubernetes/kubernetes/pull/59252), [@jsafrane](https://github.com/jsafrane)) + +* Volume metrics support for vSphere Cloud Provider has been added. You can now monitor available space, capacity, and used space on volumes created using vSphere. ([#59328](https://github.com/kubernetes/kubernetes/pull/59328), [@divyenpatel](https://github.com/divyenpatel)) + +* Emit number of bound and unbound persistent volumes as Metrics. This PR adds four kinds of Volume Metrics for kube-controller-manager: bound PVC numbers, unbound PVC numbers, bound PV numbers and unbound PV numbers. The PVC metrics use namespace as dimension and the PV metrics use StorageClassName as its dimension. With these metrics we can better monitor the use of volumes in the cluster. ([#57872](https://github.com/kubernetes/kubernetes/pull/57872), [@mlmhl](https://github.com/mlmhl)) + +* Add windows config to Kubelet CRI so that WindowsContainerResources can be managed. ([#57076](https://github.com/kubernetes/kubernetes/pull/57076), [@feiskyer](https://github.com/feiskyer)) + +* PersistentVolumes that are bound to a PersistentVolumeClaim will not be deleted. ([#58743](https://github.com/kubernetes/kubernetes/pull/58743), [@NickrenREN](https://github.com/NickrenREN)) + +* The VolumeAttachment API is now available as V1beta1, and is enabled by default. The Alpha API is deprecated and will be removed in a future release. ([#58462](https://github.com/kubernetes/kubernetes/pull/58462), [@NickrenREN](https://github.com/NickrenREN)) + +* Add storage-backend configuration option to kubernetes-master charm. ([#58830](https://github.com/kubernetes/kubernetes/pull/58830), [@wwwtyro](https://github.com/wwwtyro)) + +* Fixed dynamic provisioning of GCE PDs to round to the next GB (base 1000) instead of GiB (base 1024). ([#56600](https://github.com/kubernetes/kubernetes/pull/56600), [@edisonxiang](https://github.com/edisonxiang)) + +* PersistentVolume flexVolume sources can now reference secrets in a namespace other than the PersistentVolumeClaim's namespace. ([#56460](https://github.com/kubernetes/kubernetes/pull/56460), [@liggitt](https://github.com/liggitt)) + +### Windows + +* kubelet and kube-proxy can now be run as native Windows services. ([#60144](https://github.com/kubernetes/kubernetes/pull/60144), [@alinbalutoiu](https://github.com/alinbalutoiu)) + +* WindowsContainerResources is set now for windows containers. ([#59333](https://github.com/kubernetes/kubernetes/pull/59333), [@feiskyer](https://github.com/feiskyer)) + +* Disable mount propagation for windows containers (because it is not supported by the OS). ([#60275](https://github.com/kubernetes/kubernetes/pull/60275), [@feiskyer](https://github.com/feiskyer)) + +* Fix image file system stats for windows nodes. ([#59743](https://github.com/kubernetes/kubernetes/pull/59743), [@feiskyer](https://github.com/feiskyer)) + +* Kubernetes will now return an error if New-SmbGlobalMapping failed when mounting an azure file on Windows. ([#59540](https://github.com/kubernetes/kubernetes/pull/59540), [@andyzhangx](https://github.com/andyzhangx)) + +* Kubernetes now uses the more reliable GlobalMemoryStatusEx to get total physical memory on windows nodes. ([#57124](https://github.com/kubernetes/kubernetes/pull/57124), [@JiangtianLi](https://github.com/JiangtianLi)) + +* Windows containers now support experimental Hyper-V isolation by setting annotation `experimental.windows.kubernetes.io/isolation-type=hyperv` and feature gates HyperVContainer. At the moment this function only supports one container per pod. ([#58751]([https://github.com/kubernetes/kubernetes/pull/58751](https://github.com/kubernetes/kubernetes/pull/58751)), [@feiskyer](https://github.com/feiskyer)) + +* Get windows kernel version directly from registry rather than windows.getVersion(). ([#58498](https://github.com/kubernetes/kubernetes/pull/58498), [@feiskyer](https://github.com/feiskyer)) + +* Fixed controller manager crash when using mixed case names in a vSphere cloud provider environment. ([#57286](https://github.com/kubernetes/kubernetes/pull/57286), [@rohitjogvmw](https://github.com/rohitjogvmw)) + +* Flexvolume is now [enabled on Windows nodes](https://github.com/andyzhangx/Demo/tree/master/windows/flexvolume). ([#56921](https://github.com/kubernetes/kubernetes/pull/56921), [@andyzhangx](https://github.com/andyzhangx)) + +### Autoscaling + +* The getSubnetIDForLB() returns subnet id rather than net id. ([#58208](https://github.com/kubernetes/kubernetes/pull/58208), [@FengyunPan](https://github.com/FengyunPan)) + +* `kubectl scale` can now scale any resource (kube, CRD, aggregate) conforming to the standard scale endpoint ([#58298](https://github.com/kubernetes/kubernetes/pull/58298), [@p0lyn0mial](https://github.com/p0lyn0mial)) + +* Cluster Autoscaler has been updated to Version 1.2.0, which includes fixes around GPUs and base image change. See [https://github.com/kubernetes/autoscaler/releases/tag/cluster-autoscaler-](https://github.com/kubernetes/autoscaler/releases/tag/cluster-autoscaler-1.1.2)1.2.0for details. ([#60842](https://github.com/kubernetes/kubernetes/pull/60842), [@mwielgus](https://github.com/mwielgus)) + +* Allows HorizontalPodAutoscaler to use global metrics not associated with any Kubernetes object (for example metrics from a hosting service running outside of the Kubernetes cluster). ([#60096](https://github.com/kubernetes/kubernetes/pull/60096), [@MaciekPytel](https://github.com/MaciekPytel)) + +* fluentd-gcp resources can be modified via a ScalingPolicy. ([#59657](https://github.com/kubernetes/kubernetes/pull/59657), [@x13n](https://github.com/x13n)) + +* Added anti-affinity to kube-dns pods. Otherwise the "no single point of failure" setting doesn't actually work (a single node failure can still take down the entire cluster). ([#57683](https://github.com/kubernetes/kubernetes/pull/57683), [@vainu-arto](https://github.com/vainu-arto)) + +### API-Machinery + +* Fixed webhooks to use the scheme provided in clientConfig, instead of defaulting to http. ([#60943](https://github.com/kubernetes/kubernetes/pull/60943), [@jennybuckley](https://github.com/jennybuckley)) + +* The webhook admission controller in a custom apiserver now works off-the-shelf. ([#60995](https://github.com/kubernetes/kubernetes/pull/60995), [@caesarxuchao](https://github.com/caesarxuchao)) + +* Upgrade the default etcd server version to 3.1.12 to pick up critical etcd "mvcc "unsynced" watcher restore operation" fix. ([#60998](https://github.com/kubernetes/kubernetes/pull/60998), [@jpbetz](https://github.com/jpbetz)) + +* Fixed bug allowing garbage collector to enter a broken state that could only be fixed by restarting the controller-manager. ([#61201](https://github.com/kubernetes/kubernetes/pull/61201), [@jennybuckley](https://github.com/jennybuckley)) + +* kube-apiserver: The external hostname no longer longer use the cloud provider API to select a default. It can be set explicitly using --external-hostname, if needed. If there is no default, AdvertiseAddress or os.Hostname() will be used, in that order. ([#56812](https://github.com/kubernetes/kubernetes/pull/56812), [@dims](https://github.com/dims)) + +* Custom resources can be listed with a set of grouped resources (category) by specifying the categories in the [CustomResourceDefinition spec](https://kubernetes.io/docs/tasks/access-kubernetes-api/extend-api-custom-resource-definitions/#categories). Example: They can be used with `kubectl get important`, where `important` is a category. ([#59561](https://github.com/kubernetes/kubernetes/pull/59561), [@nikhita](https://github.com/nikhita)) + +* Fixed an issue making it possible to create a situation in which two webhooks make it impossible to delete each other. ValidatingWebhooks and MutatingWebhooks will not be called on admission requests for ValidatingWebhookConfiguration and MutatingWebhookConfiguration objects in the admissionregistration.k8s.io group ([#59840](https://github.com/kubernetes/kubernetes/pull/59840), [@jennybuckley](https://github.com/jennybuckley)) + +* Fixed potential deadlock when deleting CustomResourceDefinition for custom resources with finalizers. ([#60542](https://github.com/kubernetes/kubernetes/pull/60542), [@liggitt](https://github.com/liggitt)) + +* A buffered audit backend can be used with other audit backends. ([#60076](https://github.com/kubernetes/kubernetes/pull/60076), [@crassirostris](https://github.com/crassirostris)) + +* Introduced `--http2-max-streams-per-connection` command line flag on api-servers and set default to 1000 for aggregated API servers. ([#60054](https://github.com/kubernetes/kubernetes/pull/60054), [@MikeSpreitzer](https://github.com/MikeSpreitzer)) + +* APIserver backed by etcdv3 exports metric shows number of resources per kind. ([#59757](https://github.com/kubernetes/kubernetes/pull/59757), [@gmarek](https://github.com/gmarek)) + +* Add `kubectl create job --from-cronjob` command. ([#60084](https://github.com/kubernetes/kubernetes/pull/60084), [@soltysh](https://github.com/soltysh)) + +* `/status` and `/scale` subresources have been added for custom resources. See [https://github.com/kubernetes/kubernetes/pull/55168](https://github.com/kubernetes/kubernetes/pull/55168) for more details. ([#55168](https://github.com/kubernetes/kubernetes/pull/55168), [@nikhita](https://github.com/nikhita)) + +* Restores the ability of older clients to delete and scale jobs with initContainers. ([#59880](https://github.com/kubernetes/kubernetes/pull/59880), [@liggitt](https://github.com/liggitt)) + +* Fixed a race condition causing apiserver crashes during etcd healthchecking. ([#60069](https://github.com/kubernetes/kubernetes/pull/60069), [@wojtek-t](https://github.com/wojtek-t)) + +* Fixed a race condition in k8s.io/client-go/tools/cache.SharedInformer that could violate the sequential delivery guarantee and cause panics on shutdown in Kubernetes 1.8.* and 1.9.*. ([#59828](https://github.com/kubernetes/kubernetes/pull/59828), [@krousey](https://github.com/krousey)) + +* Add automatic etcd 3.2->3.1 and 3.1->3.0 minor version rollback support to gcr.io/google_container/etcd images. For HA clusters, all members must be stopped before performing a rollback. ([#59298](https://github.com/kubernetes/kubernetes/pull/59298), [@jpbetz](https://github.com/jpbetz)) + +* The `meta.k8s.io/v1alpha1` objects for retrieving tabular responses from the server (`Table`) or fetching just the `ObjectMeta` for an object (as `PartialObjectMetadata`) are now beta as part of `meta.k8s.io/v1beta1` and configurations must be changed to use the new API. Clients may request alternate representations of normal Kubernetes objects by passing an `Accept` header like `application/json;as=Table;g=meta.k8s.io;v=v1beta1` or `application/json;as=PartialObjectMetadata;g=meta.k8s.io;v1=v1beta1`. Older servers will ignore this representation or return an error if it is not available. Clients may request fallback to the normal object by adding a non-qualified mime-type to their `Accept` header like `application/json` - the server will then respond with either the alternate representation if it is supported or the fallback mime-type which is the normal object response. ([#59059](https://github.com/kubernetes/kubernetes/pull/59059), [@smarterclayton]([https://github.com/smarterclayton](https://github.com/smarterclayton) )) + +* kube-apiserver now uses SSH tunnels for webhooks if the webhook is not directly routable from apiserver's network environment. ([#58644](https://github.com/kubernetes/kubernetes/pull/58644), [@yguo0905](https://github.com/yguo0905)) + +* Access to externally managed IP addresses via the kube-apiserver service proxy subresource is no longer allowed by default. This can be re-enabled via the `ServiceProxyAllowExternalIPs` feature gate, but will be disallowed completely in 1.11 ([#57265](https://github.com/kubernetes/kubernetes/pull/57265), [@brendandburns](https://github.com/brendandburns)) + +* The apiregistration.k8s.io (aggregation) is now generally available. Users should transition from the v1beta1 API to the v1 API. ([#58393](https://github.com/kubernetes/kubernetes/pull/58393), [@deads2k](https://github.com/deads2k)) + +* Fixes an issue where the resourceVersion of an object in a DELETE watch event was not the resourceVersion of the delete itself, but of the last update to the object. This could disrupt the ability of clients clients to re-establish watches properly. ([#58547](https://github.com/kubernetes/kubernetes/pull/58547), [@liggitt](https://github.com/liggitt)) + +* kube-apiserver: requests to endpoints handled by unavailable extension API servers (as indicated by an `Available` condition of `false` in the registered APIService) now return `503` errors instead of `404` errors. ([#58070](https://github.com/kubernetes/kubernetes/pull/58070), [@weekface](https://github.com/weekface)) + +* Custom resources can now be submitted to and received from the API server in application/yaml format, consistent with other API resources. ([#58260](https://github.com/kubernetes/kubernetes/pull/58260), [@liggitt](https://github.com/liggitt)) + +### Network + +* Fixed kube-proxy to work correctly with iptables 1.6.2 and later. ([#60978](https://github.com/kubernetes/kubernetes/pull/60978), [@danwinship](https://github.com/danwinship)) + +* Makes the kube-dns addon optional so that users can deploy their own DNS solution. ([#57113](https://github.com/kubernetes/kubernetes/pull/57113), [@wwwtyro]([https://github.com/wwwtyro](https://github.com/wwwtyro) )) + +* `kubectl port-forward` now supports specifying a service to port forward to, as in `kubectl port-forward svc/myservice 8443:443`. Additional support has also been added for looking up targetPort for a service, as well as enabling using svc/name to select a pod. ([#59809](https://github.com/kubernetes/kubernetes/pull/59809), [@phsiao](https://github.com/phsiao)) +* [Make NodePort IP addres](https://github.com/kubernetes/website/pull/7631/files)[ses configurabl](https://github.com/kubernetes/website/pull/7631/files)[e](https://github.com/kubernetes/website/pull/7631/files). ([#58052](https://github.com/kubernetes/kubernetes/pull/58052), [@m1093782566](https://github.com/m1093782566)) + +* Fixed the issue in kube-proxy iptables/ipvs mode to properly handle incorrect IP version. ([#56880](https://github.com/kubernetes/kubernetes/pull/56880), [@MrHohn](https://github.com/MrHohn)) +* Kubeadm: CoreDNS supports migration of the kube-dns configuration to CoreDNS configuration when upgrading the service discovery from kube-dns to CoreDNS as part of Beta. ([#58828](https://github.com/kubernetes/kubernetes/pull/58828), [@rajansandeep](https://github.com/rajansandeep)) + +* Adds BETA support for `DNSConfig` field in PodSpec and `DNSPolicy=None`, so configurable pod resolve.conf is now enabled by default. ([#59771](https://github.com/kubernetes/kubernetes/pull/59771), [@MrHohn](https://github.com/MrHohn)) +* Removed some redundant rules created by the iptables proxier to improve performance on systems with very many services. ([#57461](https://github.com/kubernetes/kubernetes/pull/57461), [@danwinship](https://github.com/danwinship)) + +* Fix an issue where port forwarding doesn't forward local TCP6 ports to the pod ([#57457](https://github.com/kubernetes/kubernetes/pull/57457), [@vfreex](https://github.com/vfreex)) +* Correctly handle transient connection reset errors on GET requests from client library. ([#58520](https://github.com/kubernetes/kubernetes/pull/58520), [@porridge](https://github.com/porridge)) + +* GCE: Allows existing internal load balancers to continue using a subnetwork that may have been wrongfully chosen due to a bug choosing subnetworks on automatic networks. ([#57861](https://github.com/kubernetes/kubernetes/pull/57861), [@nicksardo](https://github.com/nicksardo)) +### Azure + +* Set node external IP for azure node when disabling UseInstanceMetadata. ([#60959](https://github.com/kubernetes/kubernetes/pull/60959), [@feiskyer](https://github.com/feiskyer)) + +* Changed default azure file/dir mode to 0755. ([#56551](https://github.com/kubernetes/kubernetes/pull/56551), [@andyzhangx](https://github.com/andyzhangx)) + +* Fixed azure file plugin failure issue on Windows after node restart. ([#60625](https://github.com/kubernetes/kubernetes/pull/60625), [@andyzhangx](https://github.com/andyzhangx))([#60623](https://github.com/kubernetes/kubernetes/pull/60623), [@feiskyer](https://github.com/feiskyer)) + +* Fixed race condition issue when detaching azure disk, preventing `Multi-Attach error`s when scheduling one pod from one node to another. ([#60183](https://github.com/kubernetes/kubernetes/pull/60183), [@andyzhangx](https://github.com/andyzhangx)) + +* Add AzureDisk support for vmss nodes. ([#59716]([https://github.com/kubernetes/kubernetes/pull/59716](https://github.com/kubernetes/kubernetes/pull/59716)), [@feiskyer](https://github.com/feiskyer)) + +* Map correct vmset name for Azure internal load balancers. ([#59747](https://github.com/kubernetes/kubernetes/pull/59747), [@feiskyer](https://github.com/feiskyer)) + +* Node's providerID will now follow the Azure resource ID format (`azure:///subscriptions/<id>/resourceGroups/<rg>/providers/Microsoft.Compute/virtualMachines/<node-name>` rather than `azure://d84a1c30-0c9f-11e8-8a34-000d3a919531`) when useInstanceMetadata is enabled ([#59539](https://github.com/kubernetes/kubernetes/pull/59539), [@feiskyer](https://github.com/feiskyer)) + +* Azure public IP is now correctly removed after a service is deleted. ([#59340](https://github.com/kubernetes/kubernetes/pull/59340), [@feiskyer](https://github.com/feiskyer)) + +* Added PV size grow feature for azure filesystems. ([#57017](https://github.com/kubernetes/kubernetes/pull/57017), [@andyzhangx](https://github.com/andyzhangx)) + +* Ensured IP is set for Azure internal load balancer. ([#59083](https://github.com/kubernetes/kubernetes/pull/59083), [@feiskyer](https://github.com/feiskyer)) + +* Set fsGroup by securityContext.fsGroup in azure file. However,f user both sets gid=xxx in mountOptions in azure storage class and securityContext.fsGroup, gid=xxx setting in mountOptions takes precedence. ([#58316](https://github.com/kubernetes/kubernetes/pull/58316), [@andyzhangx](https://github.com/andyzhangx)) + +* If an Azure disk is not found, K8s will immediately detach it. ([#58345](https://github.com/kubernetes/kubernetes/pull/58345), [@rootfs](https://github.com/rootfs)) +* Instrumented the Azure cloud provider for Prometheus monitoring. ([#58204](https://github.com/kubernetes/kubernetes/pull/58204), [@cosmincojocar](https://github.com/cosmincojocar)) + +* Fixed device name change issues for azure disk. ([#57953](https://github.com/kubernetes/kubernetes/pull/57953), [@andyzhangx](https://github.com/andyzhangx)) ([#57549](https://github.com/kubernetes/kubernetes/pull/57549), [@andyzhangx](https://github.com/andyzhangx)) + +* Support multiple scale sets in Azure cloud provider. ([#57543](https://github.com/kubernetes/kubernetes/pull/57543), [@feiskyer](https://github.com/feiskyer)) + +* Support LoadBalancer for Azure Virtual Machine Scale Sets ([#57131](https://github.com/kubernetes/kubernetes/pull/57131), [@feiskyer](https://github.com/feiskyer)) + +* Fixed incorrect error info when creating an azure file PVC failed. ([#56550](https://github.com/kubernetes/kubernetes/pull/56550), [@andyzhangx](https://github.com/andyzhangx)) + +* Added mount options support for azure disk. For example: + +``` +kind: StorageClass +apiVersion: storage.k8s.io/v1 +metadata: + name: hdd +provisioner: kubernetes.io/azure-disk +mountOptions: + - barrier=1 + - acl +parameters: + skuname: Standard_LRS + kind: Managed + fstype: ext3 +``` + +([#56147](https://github.com/kubernetes/kubernetes/pull/56147), [@andyzhangx](https://github.com/andyzhangx)) + +### Scheduling + +* Fixed a bug the in scheduler cache by using Pod UID as the cache key instead of namespace/name ([#61069](https://github.com/kubernetes/kubernetes/pull/61069), [@anfernee](https://github.com/anfernee)) + +* When `TaintNodesByCondition` is enabled, added `node.kubernetes.io/unschedulable:NoSchedule` ([#61161](https://github.com/kubernetes/kubernetes/pull/61161), [@k82cn](https://github.com/k82cn)) + +* kube-scheduler: Support extender managed extended resources in kube-scheduler ([#60332](https://github.com/kubernetes/kubernetes/pull/60332), [@yguo0905](https://github.com/yguo0905)) + +* Updated priority of mirror pod according to PriorityClassName. ([#58485](https://github.com/kubernetes/kubernetes/pull/58485), [@k82cn](https://github.com/k82cn)) + +* kube-scheduler: restores default leader election behavior. Setting the `--leader-elect` command line parameter to `true` ([#60524](https://github.com/kubernetes/kubernetes/pull/60524), [@dims](https://github.com/dims)) + +* All pods with priorityClassName system-node-critical and system-cluster-critical will be critical pods while preserving backwards compatibility. ([#58835](https://github.com/kubernetes/kubernetes/pull/58835), [@ravisantoshgudimetla](https://github.com/ravisantoshgudimetla)) +* Priority admission controller picks a global default with the lowest priority value if more than one such default PriorityClass exists. ([#59991](https://github.com/kubernetes/kubernetes/pull/59991), [@bsalamat](https://github.com/bsalamat)) +* Disallow PriorityClass names with 'system-' prefix for user defined priority classes. ([#59382](https://github.com/kubernetes/kubernetes/pull/59382), [@bsalamat](https://github.com/bsalamat)) +* kube-scheduler: Use default predicates/prioritizers if they are unspecified in the policy config. ([#59363](https://github.com/kubernetes/kubernetes/pull/59363), [@yguo0905](https://github.com/yguo0905)) + +* Scheduler should be able to read from config file if configmap is not present. ([#59386](https://github.com/kubernetes/kubernetes/pull/59386), [@ravisantoshgudimetla](https://github.com/ravisantoshgudimetla)) +* Add apiserver metric for current inflight-request usage. ([#58342](https://github.com/kubernetes/kubernetes/pull/58342), [@gmarek](https://github.com/gmarek)) + +* Stability: Make Pod delete event handling of scheduler more robust. ([#58712](https://github.com/kubernetes/kubernetes/pull/58712), [@bsalamat](https://github.com/bsalamat))* Allow scheduler set AlwaysCheckAllPredicates, short circuit all predicates if one predicate fails can greatly improve the scheduling performance. ([#56926](https://github.com/kubernetes/kubernetes/pull/56926), [@wgliang](https://github.com/wgliang)) + +* GCE: support passing kube-scheduler policy config via SCHEDULER_POLICY_CONFIG. This allows us to specify a customized scheduler policy configuration. ([#57425](https://github.com/kubernetes/kubernetes/pull/57425), [@yguo0905](https://github.com/yguo0905)) + +* Returns an error for non overcommitable resources if they don't have limit field set in container spec to prevent users from creating invalid configurations. ([#57170](https://github.com/kubernetes/kubernetes/pull/57170), [@jiayingz](https://github.com/jiayingz)) + +* GCE: Fixed ILB creation on automatic networks with manually created subnetworks. ([#57351](https://github.com/kubernetes/kubernetes/pull/57351), [@nicksardo](https://github.com/nicksardo)) + +* Multiple Performance Improvements to the MatchInterPodAffinity predicate ([#57476](https://github.com/kubernetes/kubernetes/pull/57476), [@misterikkit](https://github.com/misterikkit))([#57477](https://github.com/kubernetes/kubernetes/pull/57477), [@misterikkit](https://github.com/misterikkit)) + +* The calico-node addon tolerates all NoExecute and NoSchedule taints by default. So Calico components can even be scheduled on tainted nodes. ([#57122](https://github.com/kubernetes/kubernetes/pull/57122), [@caseydavenport](https://github.com/caseydavenport)) +* The scheduler skips pods that use a PVC that either does not exist or is being deleted. ([#55957](https://github.com/kubernetes/kubernetes/pull/55957), [@jsafrane](https://github.com/jsafrane)) + +### Other changes + +* Updated dashboard version to v1.8.3, which keeps auto-generated certs in memory. ([#57326](https://github.com/kubernetes/kubernetes/pull/57326), [@floreks](https://github.com/floreks)) + +* fluentd-gcp addon: Fixed bug with reporting metrics in event-exporter. ([#60126](https://github.com/kubernetes/kubernetes/pull/60126), [@serathius](https://github.com/serathius)) + +* Avoid hook errors when effecting label changes on kubernetes-worker charm. ([#59803](https://github.com/kubernetes/kubernetes/pull/59803), [@wwwtyro](https://github.com/wwwtyro)) + +* Fixed charm issue where docker login would run prior to daemon options being set. ([#59396](https://github.com/kubernetes/kubernetes/pull/59396), [@kwmonroe](https://github.com/kwmonroe)) + +* Implementers of the cloud provider interface will note the addition of a context to this interface. Trivial code modification will be necessary for a cloud provider to continue to compile. ([#59287](https://github.com/kubernetes/kubernetes/pull/59287), [@cheftako](https://github.com/cheftako)) + +* Added configurable etcd quota backend bytes in GCE. ([#59259](https://github.com/kubernetes/kubernetes/pull/59259), [@wojtek-t](https://github.com/wojtek-t)) + +* GCP: allow a master to not include a metadata concealment firewall rule (if it's not running the metadata proxy). ([#58104](https://github.com/kubernetes/kubernetes/pull/58104), [@ihmccreery](https://github.com/ihmccreery)) + +* Fixed issue with kubernetes-worker option allow-privileged not properly handling the value True with a capital T. ([#59116](https://github.com/kubernetes/kubernetes/pull/59116), [@hyperbolic2346](https://github.com/hyperbolic2346)) + +* Controller-manager --service-sync-period flag has been removed. (It was never used in the code and should have no user impact.) ([#59359](https://github.com/kubernetes/kubernetes/pull/59359), [@khenidak](https://github.com/khenidak)) + +* [fluentd-gcp addon] Switch to the image provided by Stackdriver. The Stackdriver Logging Agent container image uses fluentd v0.14.25. ([#59128](https://github.com/kubernetes/kubernetes/pull/59128), [@bmoyles0117](https://github.com/bmoyles0117)) + +## Non-user-facing Changes + +* CRI now uses moutpoint as image filesystem identifier instead of UUID. ([#59475](https://github.com/kubernetes/kubernetes/pull/59475), [@Random-Liu](https://github.com/Random-Liu)) + +* GCE: support Cloud TPU API in cloud provider ([#58029](https://github.com/kubernetes/kubernetes/pull/58029), [@yguo0905](https://github.com/yguo0905)) + +* kubelet now notifies systemd that it has finished starting, if systemd is available and running. ([#60654](https://github.com/kubernetes/kubernetes/pull/60654), [@dcbw](https://github.com/dcbw)) + +* Do not count failed pods as unready in HPA controller ([#60648](https://github.com/kubernetes/kubernetes/pull/60648), [@bskiba](https://github.com/bskiba)) + +* fixed foreground deletion of podtemplates ([#60683](https://github.com/kubernetes/kubernetes/pull/60683), [@nilebox](https://github.com/nilebox)) + +* Conformance tests are added for the DaemonSet kinds in the apps/v1 group version. Deprecated versions of DaemonSet will not be tested for conformance, and conformance is only applicable to release 1.10 and later. ([#60456](https://github.com/kubernetes/kubernetes/pull/60456), [@kow3ns](https://github.com/kow3ns)) + +* Log audit backend can now be configured to perform batching before writing events to disk. ([#60237](https://github.com/kubernetes/kubernetes/pull/60237), [@crassirostris](https://github.com/crassirostris)) + +* New conformance tests added for the Garbage Collector ([#60116](https://github.com/kubernetes/kubernetes/pull/60116), [@jennybuckley](https://github.com/jennybuckley)) + +* Fixes a bug where character devices are not recongized by the kubelet ([#60440](https://github.com/kubernetes/kubernetes/pull/60440), [@andrewsykim](https://github.com/andrewsykim)) + +* StatefulSet in apps/v1 is now included in Conformance Tests. ([#60336](https://github.com/kubernetes/kubernetes/pull/60336), [@enisoc](https://github.com/enisoc)) + +* dockertools: disable memory swap on Linux. ([#59404](https://github.com/kubernetes/kubernetes/pull/59404), [@ohmystack](https://github.com/ohmystack)) + +* Increase timeout of integration tests ([#60458](https://github.com/kubernetes/kubernetes/pull/60458), [@jennybuckley](https://github.com/jennybuckley)) + +* force node name lowercase on static pod name generating ([#59849](https://github.com/kubernetes/kubernetes/pull/59849), [@yue9944882]([https://github.com/yue9944882](https://github.com/yue9944882)) + +* fix device name change issue for azure disk ([#60346](https://github.com/kubernetes/kubernetes/pull/60346), [@andyzhangx](https://github.com/andyzhangx)) + +* Additional changes to iptables kube-proxy backend to improve performance on clusters with very large numbers of services. ([#60306](https://github.com/kubernetes/kubernetes/pull/60306), [@danwinship](https://github.com/danwinship)) + +* add spelling checking script ([#59463](https://github.com/kubernetes/kubernetes/pull/59463), [@dixudx](https://github.com/dixudx)) + +* Use consts as predicate name in handlers ([#59952](https://github.com/kubernetes/kubernetes/pull/59952), [@resouer](https://github.com/resouer)) + +* Fix instanceID for vmss nodes. ([#59857](https://github.com/kubernetes/kubernetes/pull/59857), [@feiskyer](https://github.com/feiskyer)) + +* Increase allowed lag for ssh key sync loop in tunneler to allow for one failure ([#60068](https://github.com/kubernetes/kubernetes/pull/60068), [@wojtek-t](https://github.com/wojtek-t)) + +* Set an upper bound (5 minutes) on how long the Kubelet will wait before exiting when the client cert from disk is missing or invalid. This prevents the Kubelet from waiting forever without attempting to bootstrap a new client credentials. ([#59316](https://github.com/kubernetes/kubernetes/pull/59316), [@smarterclayton](https://github.com/smarterclayton)) + +* Add ipset binary for IPVS to hyperkube docker image ([#57648](https://github.com/kubernetes/kubernetes/pull/57648), [@Fsero](https://github.com/Fsero)) + +* Making sure CSI E2E test runs on a local cluster ([#60017](https://github.com/kubernetes/kubernetes/pull/60017), [@sbezverk](https://github.com/sbezverk)) + +* Fix kubelet PVC stale metrics ([#59170](https://github.com/kubernetes/kubernetes/pull/59170), [@cofyc](https://github.com/cofyc)) + +* Separate current ARM rate limiter into read/write ([#59830](https://github.com/kubernetes/kubernetes/pull/59830), [@khenidak](https://github.com/khenidak)) + +* Improve control over how ARM rate limiter is used within Azure cloud provider, add generic cache for Azure VM/LB/NSG/RouteTable ([#59520](https://github.com/kubernetes/kubernetes/pull/59520), [@feiskyer](https://github.com/feiskyer)) + +* fix typo ([#59619](https://github.com/kubernetes/kubernetes/pull/59619), [@jianliao82](https://github.com/jianliao82)) + +* DaemonSet, Deployment, ReplicaSet, and StatefulSet objects are now persisted in etcd in apps/v1 format ([#58854](https://github.com/kubernetes/kubernetes/pull/58854), [@liggitt](https://github.com/liggitt)) + +* YAMLDecoder Read now tracks rest of buffer on io.ErrShortBuffer ([#58817](https://github.com/kubernetes/kubernetes/pull/58817), [@karlhungus](https://github.com/karlhungus)) + +* Prevent kubelet from getting wedged if initialization of modules returns an error. ([#59020](https://github.com/kubernetes/kubernetes/pull/59020), [@brendandburns](https://github.com/brendandburns)) + +* Fixed a race condition inside kubernetes-worker that would result in a temporary error situation. ([#59005](https://github.com/kubernetes/kubernetes/pull/59005), [@hyperbolic2346](https://github.com/hyperbolic2346)) + +* Fix regression in the CRI: do not add a default hostname on short image names ([#58955](https://github.com/kubernetes/kubernetes/pull/58955), [@runcom](https://github.com/runcom)) + +* use containing API group when resolving shortname from discovery ([#58741](https://github.com/kubernetes/kubernetes/pull/58741), [@dixudx](https://github.com/dixudx)) + +* remove spaces from kubectl describe hpa ([#56331](https://github.com/kubernetes/kubernetes/pull/56331), [@shiywang](https://github.com/shiywang)) + +* fluentd-es addon: multiline stacktraces are now grouped into one entry automatically ([#58063](https://github.com/kubernetes/kubernetes/pull/58063), [@monotek](https://github.com/monotek)) + +* Default scheduler code is moved out of the plugin directory. ([#57852](https://github.com/kubernetes/kubernetes/pull/57852), [@misterikkit](https://github.com/misterikkit)) + +* CDK nginx ingress is now handled via a daemon set. ([#57530](https://github.com/kubernetes/kubernetes/pull/57530), [@hyperbolic2346](https://github.com/hyperbolic2346)) + +* Move local PV negative scheduling tests to integration ([#57570](https://github.com/kubernetes/kubernetes/pull/57570), [@sbezverk](https://github.com/sbezverk)) + +* Only create Privileged PSP binding during e2e tests if RBAC is enabled. ([#56382](https://github.com/kubernetes/kubernetes/pull/56382), [@mikkeloscar](https://github.com/mikkeloscar)) + +* ignore nonexistent ns net file error when deleting container network in case a retry ([#57697](https://github.com/kubernetes/kubernetes/pull/57697), [@dixudx](https://github.com/dixudx)) + +* Use old dns-ip mechanism with older cdk-addons. ([#57403](https://github.com/kubernetes/kubernetes/pull/57403), [@wwwtyro](https://github.com/wwwtyro)) + +* Retry 'connection refused' errors when setting up clusters on GCE. ([#57394](https://github.com/kubernetes/kubernetes/pull/57394), [@mborsz](https://github.com/mborsz)) + +* YAMLDecoder Read now returns the number of bytes read ([#57000](https://github.com/kubernetes/kubernetes/pull/57000), [@sel](https://github.com/sel)) + +* Drop hacks used for Mesos integration that was already removed from main kubernetes repository ([#56754](https://github.com/kubernetes/kubernetes/pull/56754), [@dims](https://github.com/dims)) + +* Compare correct file names for volume detach operation ([#57053](https://github.com/kubernetes/kubernetes/pull/57053), [@prashima](https://github.com/prashima)) + +* Fixed documentation typo in IPVS README. ([#56578](https://github.com/kubernetes/kubernetes/pull/56578), [@shift](https://github.com/shift)) + +* The ConfigOK node condition has been renamed to KubeletConfigOk. ([#59905](https://github.com/kubernetes/kubernetes/pull/59905), [@mtaufen](https://github.com/mtaufen)) + +* Adding pkg/kubelet/apis/deviceplugin/v1beta1 API. ([#59588](https://github.com/kubernetes/kubernetes/pull/59588), [@jiayingz](https://github.com/jiayingz)) + +* Fixes volume predicate handler for equiv class ([#59335](https://github.com/kubernetes/kubernetes/pull/59335), [@resouer](https://github.com/resouer)) + +* Bugfix: vSphere Cloud Provider (VCP) does not need any special service account anymore. ([#59440](https://github.com/kubernetes/kubernetes/pull/59440), [@rohitjogvmw](https://github.com/rohitjogvmw)) + +* fix the error prone account creation method of blob disk ([#59739](https://github.com/kubernetes/kubernetes/pull/59739), [@andyzhangx](https://github.com/andyzhangx)) + +* Updated kubernetes-worker to request new security tokens when the aws cloud provider changes the registered node name. ([#59730](https://github.com/kubernetes/kubernetes/pull/59730), [@hyperbolic2346](https://github.com/hyperbolic2346)) + +* Pod priority can be specified ins PodSpec even when the feature is disabled, but it will be effective only when the feature is enabled. ([#59291](https://github.com/kubernetes/kubernetes/pull/59291), [@bsalamat](https://github.com/bsalamat))* Add generic cache for Azure VMSS ([#59652](https://github.com/kubernetes/kubernetes/pull/59652), [@feiskyer](https://github.com/feiskyer)) + +* fix the create azure file pvc failure if there is no storage account in current resource group ([#56557](https://github.com/kubernetes/kubernetes/pull/56557), [@andyzhangx](https://github.com/andyzhangx)) + +* Implement envelope service with gRPC, so that KMS providers can be pulled out from API server. ([#55684](https://github.com/kubernetes/kubernetes/pull/55684), [@wu-qiang](https://github.com/wu-qiang)) + +* Enable golint for `pkg/scheduler` and fix the golint errors in it. ([#58437](https://github.com/kubernetes/kubernetes/pull/58437), [@tossmilestone](https://github.com/tossmilestone)) + +* Ensure euqiv hash calculation is per schedule ([#59245](https://github.com/kubernetes/kubernetes/pull/59245), [@resouer](https://github.com/resouer)) + +* Upped the timeout for apiserver communication in the juju kubernetes-worker charm. ([#59219](https://github.com/kubernetes/kubernetes/pull/59219), [@hyperbolic2346](https://github.com/hyperbolic2346)) + +* kubeadm init: skip checking cri socket in preflight checks ([#58802](https://github.com/kubernetes/kubernetes/pull/58802), [@dixudx](https://github.com/dixudx)) + +* Configurable etcd compaction frequency in GCE ([#59106](https://github.com/kubernetes/kubernetes/pull/59106), [@wojtek-t](https://github.com/wojtek-t)) + +* Fixed a bug which caused the apiserver reboot failure in the presence of malfunctioning webhooks. ([#59073](https://github.com/kubernetes/kubernetes/pull/59073), [@caesarxuchao](https://github.com/caesarxuchao)) + +* GCE: Apiserver uses `InternalIP` as the most preferred kubelet address type by default. ([#59019](https://github.com/kubernetes/kubernetes/pull/59019), [@MrHohn](https://github.com/MrHohn)) + +* CRI: Add a call to reopen log file for a container. ([#58899](https://github.com/kubernetes/kubernetes/pull/58899), [@yujuhong](https://github.com/yujuhong)) + +* The alpha KubeletConfigFile feature gate has been removed, because it was redundant with the Kubelet's --config flag. It is no longer necessary to set this gate to use the flag. The --config flag is still considered alpha. ([#58978](https://github.com/kubernetes/kubernetes/pull/58978), [@mtaufen](https://github.com/mtaufen)) + +* Fixing extra_sans option on master and load balancer. ([#58843](https://github.com/kubernetes/kubernetes/pull/58843), [@hyperbolic2346](https://github.com/hyperbolic2346)) + +* Ensure config has been created before attempting to launch ingress. ([#58756](https://github.com/kubernetes/kubernetes/pull/58756), [@wwwtyro](https://github.com/wwwtyro)) + +* Support metrics API in `kubectl top` commands. ([#56206](https://github.com/kubernetes/kubernetes/pull/56206), [@brancz](https://github.com/brancz)) + +* Bump GCE metadata proxy to v0.1.9 to pick up security fixes. ([#58221](https://github.com/kubernetes/kubernetes/pull/58221), [@ihmccreery](https://github.com/ihmccreery)) + +* "ExternalTrafficLocalOnly" has been removed from feature gate. It has been a GA feature since v1.7. ([#56948](https://github.com/kubernetes/kubernetes/pull/56948), [@MrHohn](https://github.com/MrHohn)) +* feat(fakeclient): push event on watched channel on add/update/delete ([#57504](https://github.com/kubernetes/kubernetes/pull/57504), [@yue9944882](https://github.com/yue9944882)) + +* Fixes a possible deadlock preventing quota from being recalculated ([#58107](https://github.com/kubernetes/kubernetes/pull/58107), [@ironcladlou](https://github.com/ironcladlou)) + +* Bump metadata proxy version to v0.1.7 to pick up security fix. ([#57762](https://github.com/kubernetes/kubernetes/pull/57762), [@ihmccreery](https://github.com/ihmccreery)) + +* The kubelet uses a new release 3.1 of the pause container with the Docker runtime. This version will clean up orphaned zombie processes that it inherits. ([#57517](https://github.com/kubernetes/kubernetes/pull/57517), [@verb](https://github.com/verb)) + +* Add cache for VM get operation in azure cloud provider ([#57432](https://github.com/kubernetes/kubernetes/pull/57432), [@karataliu](https://github.com/karataliu)) + +* Configurable liveness probe initial delays for etcd and kube-apiserver in GCE ([#57749](https://github.com/kubernetes/kubernetes/pull/57749), [@wojtek-t](https://github.com/wojtek-t)) + +* Fixed garbage collection hang ([#57503](https://github.com/kubernetes/kubernetes/pull/57503), [@liggitt](https://github.com/liggitt) + +* Improve scheduler performance of MatchInterPodAffinity predicate. ([#57478](https://github.com/kubernetes/kubernetes/pull/57478), [@misterikkit](https://github.com/misterikkit)) + +* Add the path '/version/' to the `system:discovery` cluster role. ([#57368](https://github.com/kubernetes/kubernetes/pull/57368), [@brendandburns](https://github.com/brendandburns)) + +* adding predicates ordering for the kubernetes scheduler. ([#57168](https://github.com/kubernetes/kubernetes/pull/57168), [@yastij](https://github.com/yastij)) + +* Fix ipvs proxier nodeport ethassumption ([#56685](https://github.com/kubernetes/kubernetes/pull/56685), [@m1093782566](https://github.com/m1093782566)) + +* Fix Heapster configuration and Metrics Server configuration to enable overriding default resource requirements. ([#56965](https://github.com/kubernetes/kubernetes/pull/56965), [@kawych](https://github.com/kawych)) + +* Improved event generation in volume mount, attach, and extend operations ([#56872](https://github.com/kubernetes/kubernetes/pull/56872), [@davidz627](https://github.com/davidz627)) + +* Remove ScrubDNS interface from cloudprovider. ([#56955](https://github.com/kubernetes/kubernetes/pull/56955), [@feiskyer](https://github.com/feiskyer)) + +* Fixed a garbage collection race condition where objects with ownerRefs pointing to cluster-scoped objects could be deleted incorrectly. ([#57211](https://github.com/kubernetes/kubernetes/pull/57211), [@liggitt](https://github.com/liggitt)) + +* api-server provides specific events when unable to repair a service cluster ip or node port ([#54304](https://github.com/kubernetes/kubernetes/pull/54304), [@frodenas](https://github.com/frodenas)) + +* delete useless params containerized ([#56146](https://github.com/kubernetes/kubernetes/pull/56146), [@jiulongzaitian](https://github.com/jiulongzaitian)) + +* dockershim now makes an Image's Labels available in the Info field of ImageStatusResponse ([#58036](https://github.com/kubernetes/kubernetes/pull/58036), [@shlevy](https://github.com/shlevy)) + +* Support GetLabelsForVolume in OpenStack Provider ([#58871](https://github.com/kubernetes/kubernetes/pull/58871), [@edisonxiang](https://github.com/edisonxiang)) + +* Add "nominatedNodeName" field to PodStatus. This field is set when a pod preempts other pods on the node. ([#58990](https://github.com/kubernetes/kubernetes/pull/58990), [@bsalamat](https://github.com/bsalamat))* Fix the PersistentVolumeLabel controller from initializing the PV labels when it's not the next pending initializer. ([#56831](https://github.com/kubernetes/kubernetes/pull/56831), [@jhorwit2](https://github.com/jhorwit2)) + +* Rename StorageProtection to StorageObjectInUseProtection ([#59901](https://github.com/kubernetes/kubernetes/pull/59901), [@NickrenREN](https://github.com/NickrenREN)) + +* Add support for cloud-controller-manager in local-up-cluster.sh ([#57757](https://github.com/kubernetes/kubernetes/pull/57757), [@dims](https://github.com/dims)) + +* GCE: A role and clusterrole will now be provided with GCE/GKE for allowing the cloud-provider to post warning events on all services and watching configmaps in the kube-system namespace. No user action is required. ([#59686](https://github.com/kubernetes/kubernetes/pull/59686), [@nicksardo](https://github.com/nicksardo)) + +* Wait for kubedns to be ready when collecting the cluster IP. ([#57337](https://github.com/kubernetes/kubernetes/pull/57337), [@wwwtyro](https://github.com/wwwtyro)) +## External Dependencies +* The supported etcd server version is 3.1.12, as compared to 3.0.17 in v1.9 ([#60988](https://github.com/kubernetes/kubernetes/pull/60988)) +* The validated docker versions are the same as for v1.9: 1.11.2 to 1.13.1 and 17.03.x ([ref](https://github.com/kubernetes/kubernetes/blob/master/test/e2e_node/system/docker_validator_test.go)) +* The Go version is go1.9.3, as compared to go1.9.2 in v1.9. ([#59012](https://github.com/kubernetes/kubernetes/pull/59012)) +* The minimum supported go is the same as for v1.9: go1.9.1. ([#55301](https://github.com/kubernetes/kubernetes/pull/55301)) +* CNI is the same as v1.9: v0.6.0 ([#51250](https://github.com/kubernetes/kubernetes/pull/51250)) +* CSI is updated to 0.2.0 as compared to 0.1.0 in v1.9. ([#60736](https://github.com/kubernetes/kubernetes/pull/60736)) +* The dashboard add-on has been updated to v1.8.3, as compared to 1.8.0 in v1.9. ([#57326](https://github.com/kubernetes/kubernetes/pull/57326)) +* Heapster has is the same as v1.9: v1.5.0. It will be upgraded in v1.11. ([ref](https://github.com/kubernetes/kubernetes/blob/master/cluster/addons/cluster-monitoring/google/heapster-controller.yaml)) +* Cluster Autoscaler has been updated to v1.2.0. ([#60842](https://github.com/kubernetes/kubernetes/pull/60842), [@mwielgus](https://github.com/mwielgus)) +* Updates kube-dns to v1.14.8 ([#57918](https://github.com/kubernetes/kubernetes/pull/57918), [@rramkumar1](https://github.com/rramkumar1)) +* Influxdb is unchanged from v1.9: v1.3.3 ([#53319](https://github.com/kubernetes/kubernetes/pull/53319)) +* Grafana is unchanged from v1.9: v4.4.3 ([#53319](https://github.com/kubernetes/kubernetes/pull/53319)) +* CAdvisor is v0.29.1 ([#60867](https://github.com/kubernetes/kubernetes/pull/60867)) +* fluentd-gcp-scaler is v0.3.0 ([#61269](https://github.com/kubernetes/kubernetes/pull/61269)) +* Updated fluentd in fluentd-es-image to fluentd v1.1.0 ([#58525](https://github.com/kubernetes/kubernetes/pull/58525), [@monotek](https://github.com/monotek)) +* fluentd-elasticsearch is v2.0.4 ([#58525](https://github.com/kubernetes/kubernetes/pull/58525)) +* Updated fluentd-gcp to v3.0.0. ([#60722](https://github.com/kubernetes/kubernetes/pull/60722)) +* Ingress glbc is v1.0.0 ([#61302](https://github.com/kubernetes/kubernetes/pull/61302)) +* OIDC authentication is coreos/go-oidc v2 ([#58544](https://github.com/kubernetes/kubernetes/pull/58544)) +* Updated fluentd-gcp updated to v2.0.11. ([#56927](https://github.com/kubernetes/kubernetes/pull/56927), [@x13n](https://github.com/x13n)) +* Calico has been updated to v2.6.7 ([#59130](https://github.com/kubernetes/kubernetes/pull/59130), [@caseydavenport](https://github.com/caseydavenport)) # v1.10.0-rc.1 @@ -995,8 +1790,8 @@ filename | sha256 hash * Add AWS cloud provider option to use an assumed IAM role ([#59668](https://github.com/kubernetes/kubernetes/pull/59668), [@brycecarman](https://github.com/brycecarman)) * `kubectl port-forward` now supports specifying a service to port forward to: `kubectl port-forward svc/myservice 8443:443` ([#59809](https://github.com/kubernetes/kubernetes/pull/59809), [@phsiao](https://github.com/phsiao)) * Fix kubelet PVC stale metrics ([#59170](https://github.com/kubernetes/kubernetes/pull/59170), [@cofyc](https://github.com/cofyc)) -* - Separate current ARM rate limiter into read/write ([#59830](https://github.com/kubernetes/kubernetes/pull/59830), [@khenidak](https://github.com/khenidak)) - * - Improve control over how ARM rate limiter is used within Azure cloud provider +* Separate current ARM rate limiter into read/write ([#59830](https://github.com/kubernetes/kubernetes/pull/59830), [@khenidak](https://github.com/khenidak)) + * Improve control over how ARM rate limiter is used within Azure cloud provider * The ConfigOK node condition has been renamed to KubeletConfigOk. ([#59905](https://github.com/kubernetes/kubernetes/pull/59905), [@mtaufen](https://github.com/mtaufen)) * fluentd-gcp resources can be modified via a ScalingPolicy ([#59657](https://github.com/kubernetes/kubernetes/pull/59657), [@x13n](https://github.com/x13n)) * Adding pkg/kubelet/apis/deviceplugin/v1beta1 API. ([#59588](https://github.com/kubernetes/kubernetes/pull/59588), [@jiayingz](https://github.com/jiayingz)) @@ -1014,12 +1809,12 @@ filename | sha256 hash * Eviction thresholds set to 0% or 100% are now ignored. ([#59681](https://github.com/kubernetes/kubernetes/pull/59681), [@mtaufen](https://github.com/mtaufen)) * [advanced audit] support subresources wildcard matching. ([#55306](https://github.com/kubernetes/kubernetes/pull/55306), [@hzxuzhonghu](https://github.com/hzxuzhonghu)) * CronJobs can be accessed through cj alias ([#59499](https://github.com/kubernetes/kubernetes/pull/59499), [@soltysh](https://github.com/soltysh)) -* N/A ([#58275](https://github.com/kubernetes/kubernetes/pull/58275), [@carmark](https://github.com/carmark)) +* fix typo in resource_allocation.go ([#58275](https://github.com/kubernetes/kubernetes/pull/58275), [@carmark](https://github.com/carmark)) * fix the error prone account creation method of blob disk ([#59739](https://github.com/kubernetes/kubernetes/pull/59739), [@andyzhangx](https://github.com/andyzhangx)) * Add automatic etcd 3.2->3.1 and 3.1->3.0 minor version rollback support to gcr.io/google_container/etcd images. For HA clusters, all members must be stopped before performing a rollback. ([#59298](https://github.com/kubernetes/kubernetes/pull/59298), [@jpbetz](https://github.com/jpbetz)) * `kubeadm init` can now omit the tainting of the master node if configured to do so in `kubeadm.yaml`. ([#55479](https://github.com/kubernetes/kubernetes/pull/55479), [@ijc](https://github.com/ijc)) * Updated kubernetes-worker to request new security tokens when the aws cloud provider changes the registered node name. ([#59730](https://github.com/kubernetes/kubernetes/pull/59730), [@hyperbolic2346](https://github.com/hyperbolic2346)) -* 1. Controller-manager --service-sync-period flag is removed (was never used in the code). ([#59359](https://github.com/kubernetes/kubernetes/pull/59359), [@khenidak](https://github.com/khenidak)) +* Controller-manager --service-sync-period flag is removed (was never used in the code). ([#59359](https://github.com/kubernetes/kubernetes/pull/59359), [@khenidak](https://github.com/khenidak)) * Pod priority can be specified ins PodSpec even when the feature is disabled, but it will be effective only when the feature is enabled. ([#59291](https://github.com/kubernetes/kubernetes/pull/59291), [@bsalamat](https://github.com/bsalamat)) * kubeadm: Enable auditing behind a feature gate. ([#59067](https://github.com/kubernetes/kubernetes/pull/59067), [@chuckha](https://github.com/chuckha)) * Map correct vmset name for Azure internal load balancers ([#59747](https://github.com/kubernetes/kubernetes/pull/59747), [@feiskyer](https://github.com/feiskyer)) @@ -1257,9 +2052,9 @@ filename | sha256 hash * Correctly handle transient connection reset errors on GET requests from client library. ([#58520](https://github.com/kubernetes/kubernetes/pull/58520), [@porridge](https://github.com/porridge)) * Authentication information for OpenStack cloud provider can now be specified as environment variables ([#58300](https://github.com/kubernetes/kubernetes/pull/58300), [@dims](https://github.com/dims)) * Bump GCE metadata proxy to v0.1.9 to pick up security fixes. ([#58221](https://github.com/kubernetes/kubernetes/pull/58221), [@ihmccreery](https://github.com/ihmccreery)) -* - kubeadm now supports CIDR notations in NO_PROXY environment variable ([#53895](https://github.com/kubernetes/kubernetes/pull/53895), [@kad](https://github.com/kad)) +* kubeadm now supports CIDR notations in NO_PROXY environment variable ([#53895](https://github.com/kubernetes/kubernetes/pull/53895), [@kad](https://github.com/kad)) * kubeadm now accept `--apiserver-extra-args`, `--controller-manager-extra-args` and `--scheduler-extra-args` to override / specify additional flags for control plane components ([#58080](https://github.com/kubernetes/kubernetes/pull/58080), [@simonferquel](https://github.com/simonferquel)) -* Add `--enable-admission-plugin` `--disable-admission-plugin` flags and deprecate `--admission-control`. ([#58123](https://github.com/kubernetes/kubernetes/pull/58123), [@hzxuzhonghu](https://github.com/hzxuzhonghu)) +* Add `--enable-admission-plugins` `--disable-admission-plugins` flags and deprecate `--admission-control`. ([#58123](https://github.com/kubernetes/kubernetes/pull/58123), [@hzxuzhonghu](https://github.com/hzxuzhonghu)) * Afterwards, don't care about the orders specified in the flags. * "ExternalTrafficLocalOnly" has been removed from feature gate. It has been a GA feature since v1.7. ([#56948](https://github.com/kubernetes/kubernetes/pull/56948), [@MrHohn](https://github.com/MrHohn)) * GCP: allow a master to not include a metadata concealment firewall rule (if it's not running the metadata proxy). ([#58104](https://github.com/kubernetes/kubernetes/pull/58104), [@ihmccreery](https://github.com/ihmccreery)) diff --git a/vendor/k8s.io/kubernetes/pkg/api/service/util_test.go b/vendor/k8s.io/kubernetes/pkg/api/service/util_test.go deleted file mode 100644 index 46790a170b..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/api/service/util_test.go +++ /dev/null @@ -1,216 +0,0 @@ -/* -Copyright 2016 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 service - -import ( - "strings" - "testing" - - api "k8s.io/kubernetes/pkg/apis/core" - netsets "k8s.io/kubernetes/pkg/util/net/sets" -) - -func TestGetLoadBalancerSourceRanges(t *testing.T) { - checkError := func(v string) { - annotations := make(map[string]string) - annotations[api.AnnotationLoadBalancerSourceRangesKey] = v - svc := api.Service{} - svc.Annotations = annotations - _, err := GetLoadBalancerSourceRanges(&svc) - if err == nil { - t.Errorf("Expected error parsing: %q", v) - } - svc = api.Service{} - svc.Spec.LoadBalancerSourceRanges = strings.Split(v, ",") - _, err = GetLoadBalancerSourceRanges(&svc) - if err == nil { - t.Errorf("Expected error parsing: %q", v) - } - } - checkError("10.0.0.1/33") - checkError("foo.bar") - checkError("10.0.0.1/32,*") - checkError("10.0.0.1/32,") - checkError("10.0.0.1/32, ") - checkError("10.0.0.1") - - checkOK := func(v string) netsets.IPNet { - annotations := make(map[string]string) - annotations[api.AnnotationLoadBalancerSourceRangesKey] = v - svc := api.Service{} - svc.Annotations = annotations - cidrs, err := GetLoadBalancerSourceRanges(&svc) - if err != nil { - t.Errorf("Unexpected error parsing: %q", v) - } - svc = api.Service{} - svc.Spec.LoadBalancerSourceRanges = strings.Split(v, ",") - cidrs, err = GetLoadBalancerSourceRanges(&svc) - if err != nil { - t.Errorf("Unexpected error parsing: %q", v) - } - return cidrs - } - cidrs := checkOK("192.168.0.1/32") - if len(cidrs) != 1 { - t.Errorf("Expected exactly one CIDR: %v", cidrs.StringSlice()) - } - cidrs = checkOK("192.168.0.1/32,192.168.0.1/32") - if len(cidrs) != 1 { - t.Errorf("Expected exactly one CIDR (after de-dup): %v", cidrs.StringSlice()) - } - cidrs = checkOK("192.168.0.1/32,192.168.0.2/32") - if len(cidrs) != 2 { - t.Errorf("Expected two CIDRs: %v", cidrs.StringSlice()) - } - cidrs = checkOK(" 192.168.0.1/32 , 192.168.0.2/32 ") - if len(cidrs) != 2 { - t.Errorf("Expected two CIDRs: %v", cidrs.StringSlice()) - } - // check LoadBalancerSourceRanges not specified - svc := api.Service{} - cidrs, err := GetLoadBalancerSourceRanges(&svc) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if len(cidrs) != 1 { - t.Errorf("Expected exactly one CIDR: %v", cidrs.StringSlice()) - } - if !IsAllowAll(cidrs) { - t.Errorf("Expected default to be allow-all: %v", cidrs.StringSlice()) - } - // check SourceRanges annotation is empty - annotations := make(map[string]string) - annotations[api.AnnotationLoadBalancerSourceRangesKey] = "" - svc = api.Service{} - svc.Annotations = annotations - cidrs, err = GetLoadBalancerSourceRanges(&svc) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if len(cidrs) != 1 { - t.Errorf("Expected exactly one CIDR: %v", cidrs.StringSlice()) - } - if !IsAllowAll(cidrs) { - t.Errorf("Expected default to be allow-all: %v", cidrs.StringSlice()) - } -} - -func TestAllowAll(t *testing.T) { - checkAllowAll := func(allowAll bool, cidrs ...string) { - ipnets, err := netsets.ParseIPNets(cidrs...) - if err != nil { - t.Errorf("Unexpected error parsing cidrs: %v", cidrs) - } - if allowAll != IsAllowAll(ipnets) { - t.Errorf("IsAllowAll did not return expected value for %v", cidrs) - } - } - checkAllowAll(false, "10.0.0.1/32") - checkAllowAll(false, "10.0.0.1/32", "10.0.0.2/32") - checkAllowAll(false, "10.0.0.1/32", "10.0.0.1/32") - - checkAllowAll(true, "0.0.0.0/0") - checkAllowAll(true, "192.168.0.0/0") - checkAllowAll(true, "192.168.0.1/32", "0.0.0.0/0") -} - -func TestRequestsOnlyLocalTraffic(t *testing.T) { - checkRequestsOnlyLocalTraffic := func(requestsOnlyLocalTraffic bool, service *api.Service) { - res := RequestsOnlyLocalTraffic(service) - if res != requestsOnlyLocalTraffic { - t.Errorf("Expected requests OnlyLocal traffic = %v, got %v", - requestsOnlyLocalTraffic, res) - } - } - - checkRequestsOnlyLocalTraffic(false, &api.Service{}) - checkRequestsOnlyLocalTraffic(false, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeClusterIP, - }, - }) - checkRequestsOnlyLocalTraffic(false, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeNodePort, - }, - }) - checkRequestsOnlyLocalTraffic(false, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeNodePort, - ExternalTrafficPolicy: api.ServiceExternalTrafficPolicyTypeCluster, - }, - }) - checkRequestsOnlyLocalTraffic(true, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeNodePort, - ExternalTrafficPolicy: api.ServiceExternalTrafficPolicyTypeLocal, - }, - }) - checkRequestsOnlyLocalTraffic(false, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeLoadBalancer, - ExternalTrafficPolicy: api.ServiceExternalTrafficPolicyTypeCluster, - }, - }) - checkRequestsOnlyLocalTraffic(true, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeLoadBalancer, - ExternalTrafficPolicy: api.ServiceExternalTrafficPolicyTypeLocal, - }, - }) -} - -func TestNeedsHealthCheck(t *testing.T) { - checkNeedsHealthCheck := func(needsHealthCheck bool, service *api.Service) { - res := NeedsHealthCheck(service) - if res != needsHealthCheck { - t.Errorf("Expected needs health check = %v, got %v", - needsHealthCheck, res) - } - } - - checkNeedsHealthCheck(false, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeClusterIP, - }, - }) - checkNeedsHealthCheck(false, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeNodePort, - ExternalTrafficPolicy: api.ServiceExternalTrafficPolicyTypeCluster, - }, - }) - checkNeedsHealthCheck(false, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeNodePort, - ExternalTrafficPolicy: api.ServiceExternalTrafficPolicyTypeLocal, - }, - }) - checkNeedsHealthCheck(false, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeLoadBalancer, - ExternalTrafficPolicy: api.ServiceExternalTrafficPolicyTypeCluster, - }, - }) - checkNeedsHealthCheck(true, &api.Service{ - Spec: api.ServiceSpec{ - Type: api.ServiceTypeLoadBalancer, - ExternalTrafficPolicy: api.ServiceExternalTrafficPolicyTypeLocal, - }, - }) -} diff --git a/vendor/k8s.io/kubernetes/pkg/api/v1/pod/util_test.go b/vendor/k8s.io/kubernetes/pkg/api/v1/pod/util_test.go deleted file mode 100644 index 5310bc3285..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/api/v1/pod/util_test.go +++ /dev/null @@ -1,522 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package pod - -import ( - "reflect" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/validation/field" -) - -func TestFindPort(t *testing.T) { - testCases := []struct { - name string - containers []v1.Container - port intstr.IntOrString - expected int - pass bool - }{{ - name: "valid int, no ports", - containers: []v1.Container{{}}, - port: intstr.FromInt(93), - expected: 93, - pass: true, - }, { - name: "valid int, with ports", - containers: []v1.Container{{Ports: []v1.ContainerPort{{ - Name: "", - ContainerPort: 11, - Protocol: "TCP", - }, { - Name: "p", - ContainerPort: 22, - Protocol: "TCP", - }}}}, - port: intstr.FromInt(93), - expected: 93, - pass: true, - }, { - name: "valid str, no ports", - containers: []v1.Container{{}}, - port: intstr.FromString("p"), - expected: 0, - pass: false, - }, { - name: "valid str, one ctr with ports", - containers: []v1.Container{{Ports: []v1.ContainerPort{{ - Name: "", - ContainerPort: 11, - Protocol: "UDP", - }, { - Name: "p", - ContainerPort: 22, - Protocol: "TCP", - }, { - Name: "q", - ContainerPort: 33, - Protocol: "TCP", - }}}}, - port: intstr.FromString("q"), - expected: 33, - pass: true, - }, { - name: "valid str, two ctr with ports", - containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ - Name: "", - ContainerPort: 11, - Protocol: "UDP", - }, { - Name: "p", - ContainerPort: 22, - Protocol: "TCP", - }, { - Name: "q", - ContainerPort: 33, - Protocol: "TCP", - }}}}, - port: intstr.FromString("q"), - expected: 33, - pass: true, - }, { - name: "valid str, two ctr with same port", - containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ - Name: "", - ContainerPort: 11, - Protocol: "UDP", - }, { - Name: "p", - ContainerPort: 22, - Protocol: "TCP", - }, { - Name: "q", - ContainerPort: 22, - Protocol: "TCP", - }}}}, - port: intstr.FromString("q"), - expected: 22, - pass: true, - }, { - name: "valid str, invalid protocol", - containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ - Name: "a", - ContainerPort: 11, - Protocol: "snmp", - }, - }}}, - port: intstr.FromString("a"), - expected: 0, - pass: false, - }, { - name: "valid hostPort", - containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ - Name: "a", - ContainerPort: 11, - HostPort: 81, - Protocol: "TCP", - }, - }}}, - port: intstr.FromString("a"), - expected: 11, - pass: true, - }, - { - name: "invalid hostPort", - containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ - Name: "a", - ContainerPort: 11, - HostPort: -1, - Protocol: "TCP", - }, - }}}, - port: intstr.FromString("a"), - expected: 11, - pass: true, - //this should fail but passes. - }, - { - name: "invalid ContainerPort", - containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ - Name: "a", - ContainerPort: -1, - Protocol: "TCP", - }, - }}}, - port: intstr.FromString("a"), - expected: -1, - pass: true, - //this should fail but passes - }, - { - name: "HostIP Address", - containers: []v1.Container{{}, {Ports: []v1.ContainerPort{{ - Name: "a", - ContainerPort: 11, - HostIP: "192.168.1.1", - Protocol: "TCP", - }, - }}}, - port: intstr.FromString("a"), - expected: 11, - pass: true, - }, - } - - for _, tc := range testCases { - port, err := FindPort(&v1.Pod{Spec: v1.PodSpec{Containers: tc.containers}}, - &v1.ServicePort{Protocol: "TCP", TargetPort: tc.port}) - if err != nil && tc.pass { - t.Errorf("unexpected error for %s: %v", tc.name, err) - } - if err == nil && !tc.pass { - t.Errorf("unexpected non-error for %s: %d", tc.name, port) - } - if port != tc.expected { - t.Errorf("wrong result for %s: expected %d, got %d", tc.name, tc.expected, port) - } - } -} - -func TestPodSecrets(t *testing.T) { - // Stub containing all possible secret references in a pod. - // The names of the referenced secrets match struct paths detected by reflection. - pod := &v1.Pod{ - Spec: v1.PodSpec{ - Containers: []v1.Container{{ - EnvFrom: []v1.EnvFromSource{{ - SecretRef: &v1.SecretEnvSource{ - LocalObjectReference: v1.LocalObjectReference{ - Name: "Spec.Containers[*].EnvFrom[*].SecretRef"}}}}, - Env: []v1.EnvVar{{ - ValueFrom: &v1.EnvVarSource{ - SecretKeyRef: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: "Spec.Containers[*].Env[*].ValueFrom.SecretKeyRef"}}}}}}}, - ImagePullSecrets: []v1.LocalObjectReference{{ - Name: "Spec.ImagePullSecrets"}}, - InitContainers: []v1.Container{{ - EnvFrom: []v1.EnvFromSource{{ - SecretRef: &v1.SecretEnvSource{ - LocalObjectReference: v1.LocalObjectReference{ - Name: "Spec.InitContainers[*].EnvFrom[*].SecretRef"}}}}, - Env: []v1.EnvVar{{ - ValueFrom: &v1.EnvVarSource{ - SecretKeyRef: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{ - Name: "Spec.InitContainers[*].Env[*].ValueFrom.SecretKeyRef"}}}}}}}, - Volumes: []v1.Volume{{ - VolumeSource: v1.VolumeSource{ - AzureFile: &v1.AzureFileVolumeSource{ - SecretName: "Spec.Volumes[*].VolumeSource.AzureFile.SecretName"}}}, { - VolumeSource: v1.VolumeSource{ - CephFS: &v1.CephFSVolumeSource{ - SecretRef: &v1.LocalObjectReference{ - Name: "Spec.Volumes[*].VolumeSource.CephFS.SecretRef"}}}}, { - VolumeSource: v1.VolumeSource{ - FlexVolume: &v1.FlexVolumeSource{ - SecretRef: &v1.LocalObjectReference{ - Name: "Spec.Volumes[*].VolumeSource.FlexVolume.SecretRef"}}}}, { - VolumeSource: v1.VolumeSource{ - Projected: &v1.ProjectedVolumeSource{ - Sources: []v1.VolumeProjection{{ - Secret: &v1.SecretProjection{ - LocalObjectReference: v1.LocalObjectReference{ - Name: "Spec.Volumes[*].VolumeSource.Projected.Sources[*].Secret"}}}}}}}, { - VolumeSource: v1.VolumeSource{ - RBD: &v1.RBDVolumeSource{ - SecretRef: &v1.LocalObjectReference{ - Name: "Spec.Volumes[*].VolumeSource.RBD.SecretRef"}}}}, { - VolumeSource: v1.VolumeSource{ - Secret: &v1.SecretVolumeSource{ - SecretName: "Spec.Volumes[*].VolumeSource.Secret.SecretName"}}}, { - VolumeSource: v1.VolumeSource{ - Secret: &v1.SecretVolumeSource{ - SecretName: "Spec.Volumes[*].VolumeSource.Secret"}}}, { - VolumeSource: v1.VolumeSource{ - ScaleIO: &v1.ScaleIOVolumeSource{ - SecretRef: &v1.LocalObjectReference{ - Name: "Spec.Volumes[*].VolumeSource.ScaleIO.SecretRef"}}}}, { - VolumeSource: v1.VolumeSource{ - ISCSI: &v1.ISCSIVolumeSource{ - SecretRef: &v1.LocalObjectReference{ - Name: "Spec.Volumes[*].VolumeSource.ISCSI.SecretRef"}}}}, { - VolumeSource: v1.VolumeSource{ - StorageOS: &v1.StorageOSVolumeSource{ - SecretRef: &v1.LocalObjectReference{ - Name: "Spec.Volumes[*].VolumeSource.StorageOS.SecretRef"}}}}}, - }, - } - extractedNames := sets.NewString() - VisitPodSecretNames(pod, func(name string) bool { - extractedNames.Insert(name) - return true - }) - - // excludedSecretPaths holds struct paths to fields with "secret" in the name that are not actually references to secret API objects - excludedSecretPaths := sets.NewString( - "Spec.Volumes[*].VolumeSource.CephFS.SecretFile", - ) - // expectedSecretPaths holds struct paths to fields with "secret" in the name that are references to secret API objects. - // every path here should be represented as an example in the Pod stub above, with the secret name set to the path. - expectedSecretPaths := sets.NewString( - "Spec.Containers[*].EnvFrom[*].SecretRef", - "Spec.Containers[*].Env[*].ValueFrom.SecretKeyRef", - "Spec.ImagePullSecrets", - "Spec.InitContainers[*].EnvFrom[*].SecretRef", - "Spec.InitContainers[*].Env[*].ValueFrom.SecretKeyRef", - "Spec.Volumes[*].VolumeSource.AzureFile.SecretName", - "Spec.Volumes[*].VolumeSource.CephFS.SecretRef", - "Spec.Volumes[*].VolumeSource.FlexVolume.SecretRef", - "Spec.Volumes[*].VolumeSource.Projected.Sources[*].Secret", - "Spec.Volumes[*].VolumeSource.RBD.SecretRef", - "Spec.Volumes[*].VolumeSource.Secret", - "Spec.Volumes[*].VolumeSource.Secret.SecretName", - "Spec.Volumes[*].VolumeSource.ScaleIO.SecretRef", - "Spec.Volumes[*].VolumeSource.ISCSI.SecretRef", - "Spec.Volumes[*].VolumeSource.StorageOS.SecretRef", - ) - secretPaths := collectSecretPaths(t, nil, "", reflect.TypeOf(&v1.Pod{})) - secretPaths = secretPaths.Difference(excludedSecretPaths) - if missingPaths := expectedSecretPaths.Difference(secretPaths); len(missingPaths) > 0 { - t.Logf("Missing expected secret paths:\n%s", strings.Join(missingPaths.List(), "\n")) - t.Error("Missing expected secret paths. Verify VisitPodSecretNames() is correctly finding the missing paths, then correct expectedSecretPaths") - } - if extraPaths := secretPaths.Difference(expectedSecretPaths); len(extraPaths) > 0 { - t.Logf("Extra secret paths:\n%s", strings.Join(extraPaths.List(), "\n")) - t.Error("Extra fields with 'secret' in the name found. Verify VisitPodSecretNames() is including these fields if appropriate, then correct expectedSecretPaths") - } - - if missingNames := expectedSecretPaths.Difference(extractedNames); len(missingNames) > 0 { - t.Logf("Missing expected secret names:\n%s", strings.Join(missingNames.List(), "\n")) - t.Error("Missing expected secret names. Verify the pod stub above includes these references, then verify VisitPodSecretNames() is correctly finding the missing names") - } - if extraNames := extractedNames.Difference(expectedSecretPaths); len(extraNames) > 0 { - t.Logf("Extra secret names:\n%s", strings.Join(extraNames.List(), "\n")) - t.Error("Extra secret names extracted. Verify VisitPodSecretNames() is correctly extracting secret names") - } -} - -// collectSecretPaths traverses the object, computing all the struct paths that lead to fields with "secret" in the name. -func collectSecretPaths(t *testing.T, path *field.Path, name string, tp reflect.Type) sets.String { - secretPaths := sets.NewString() - - if tp.Kind() == reflect.Ptr { - secretPaths.Insert(collectSecretPaths(t, path, name, tp.Elem()).List()...) - return secretPaths - } - - if strings.Contains(strings.ToLower(name), "secret") { - secretPaths.Insert(path.String()) - } - - switch tp.Kind() { - case reflect.Ptr: - secretPaths.Insert(collectSecretPaths(t, path, name, tp.Elem()).List()...) - case reflect.Struct: - for i := 0; i < tp.NumField(); i++ { - field := tp.Field(i) - secretPaths.Insert(collectSecretPaths(t, path.Child(field.Name), field.Name, field.Type).List()...) - } - case reflect.Interface: - t.Errorf("cannot find secret fields in interface{} field %s", path.String()) - case reflect.Map: - secretPaths.Insert(collectSecretPaths(t, path.Key("*"), "", tp.Elem()).List()...) - case reflect.Slice: - secretPaths.Insert(collectSecretPaths(t, path.Key("*"), "", tp.Elem()).List()...) - default: - // all primitive types - } - - return secretPaths -} - -func newPod(now metav1.Time, ready bool, beforeSec int) *v1.Pod { - conditionStatus := v1.ConditionFalse - if ready { - conditionStatus = v1.ConditionTrue - } - return &v1.Pod{ - Status: v1.PodStatus{ - Conditions: []v1.PodCondition{ - { - Type: v1.PodReady, - LastTransitionTime: metav1.NewTime(now.Time.Add(-1 * time.Duration(beforeSec) * time.Second)), - Status: conditionStatus, - }, - }, - }, - } -} - -func TestIsPodAvailable(t *testing.T) { - now := metav1.Now() - tests := []struct { - pod *v1.Pod - minReadySeconds int32 - expected bool - }{ - { - pod: newPod(now, false, 0), - minReadySeconds: 0, - expected: false, - }, - { - pod: newPod(now, true, 0), - minReadySeconds: 1, - expected: false, - }, - { - pod: newPod(now, true, 0), - minReadySeconds: 0, - expected: true, - }, - { - pod: newPod(now, true, 51), - minReadySeconds: 50, - expected: true, - }, - } - - for i, test := range tests { - isAvailable := IsPodAvailable(test.pod, test.minReadySeconds, now) - if isAvailable != test.expected { - t.Errorf("[tc #%d] expected available pod: %t, got: %t", i, test.expected, isAvailable) - } - } -} - -func TestGetContainerStatus(t *testing.T) { - type ExpectedStruct struct { - status v1.ContainerStatus - exists bool - } - - tests := []struct { - status []v1.ContainerStatus - name string - expected ExpectedStruct - desc string - }{ - { - status: []v1.ContainerStatus{{Name: "test1", Ready: false, Image: "image1"}, {Name: "test2", Ready: true, Image: "image1"}}, - name: "test1", - expected: ExpectedStruct{status: v1.ContainerStatus{Name: "test1", Ready: false, Image: "image1"}, exists: true}, - desc: "retrieve ContainerStatus with Name=\"test1\"", - }, - { - status: []v1.ContainerStatus{{Name: "test2", Ready: false, Image: "image2"}}, - name: "test1", - expected: ExpectedStruct{status: v1.ContainerStatus{}, exists: false}, - desc: "no matching ContainerStatus with Name=\"test1\"", - }, - { - status: []v1.ContainerStatus{{Name: "test3", Ready: false, Image: "image3"}}, - name: "", - expected: ExpectedStruct{status: v1.ContainerStatus{}, exists: false}, - desc: "retrieve an empty ContainerStatus with container name empty", - }, - { - status: nil, - name: "", - expected: ExpectedStruct{status: v1.ContainerStatus{}, exists: false}, - desc: "retrieve an empty ContainerStatus with status nil", - }, - } - - for _, test := range tests { - resultStatus, exists := GetContainerStatus(test.status, test.name) - assert.Equal(t, test.expected.status, resultStatus, "GetContainerStatus: "+test.desc) - assert.Equal(t, test.expected.exists, exists, "GetContainerStatus: "+test.desc) - - resultStatus = GetExistingContainerStatus(test.status, test.name) - assert.Equal(t, test.expected.status, resultStatus, "GetExistingContainerStatus: "+test.desc) - } -} - -func TestUpdatePodCondition(t *testing.T) { - time := metav1.Now() - - podStatus := v1.PodStatus{ - Conditions: []v1.PodCondition{ - { - Type: v1.PodReady, - Status: v1.ConditionTrue, - Reason: "successfully", - Message: "sync pod successfully", - LastProbeTime: time, - LastTransitionTime: metav1.NewTime(time.Add(1000)), - }, - }, - } - tests := []struct { - status *v1.PodStatus - conditions v1.PodCondition - expected bool - desc string - }{ - { - status: &podStatus, - conditions: v1.PodCondition{ - Type: v1.PodReady, - Status: v1.ConditionTrue, - Reason: "successfully", - Message: "sync pod successfully", - LastProbeTime: time, - LastTransitionTime: metav1.NewTime(time.Add(1000))}, - expected: false, - desc: "all equal, no update", - }, - { - status: &podStatus, - conditions: v1.PodCondition{ - Type: v1.PodScheduled, - Status: v1.ConditionTrue, - Reason: "successfully", - Message: "sync pod successfully", - LastProbeTime: time, - LastTransitionTime: metav1.NewTime(time.Add(1000))}, - expected: true, - desc: "not equal Type, should get updated", - }, - { - status: &podStatus, - conditions: v1.PodCondition{ - Type: v1.PodReady, - Status: v1.ConditionFalse, - Reason: "successfully", - Message: "sync pod successfully", - LastProbeTime: time, - LastTransitionTime: metav1.NewTime(time.Add(1000))}, - expected: true, - desc: "not equal Status, should get updated", - }, - } - - for _, test := range tests { - var resultStatus bool - resultStatus = UpdatePodCondition(test.status, &test.conditions) - - assert.Equal(t, test.expected, resultStatus, test.desc) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/helper/helpers_test.go b/vendor/k8s.io/kubernetes/pkg/apis/core/helper/helpers_test.go deleted file mode 100644 index 03e01f8083..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/helper/helpers_test.go +++ /dev/null @@ -1,491 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package helper - -import ( - "reflect" - "testing" - - "k8s.io/apimachinery/pkg/api/resource" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/kubernetes/pkg/apis/core" -) - -func TestSemantic(t *testing.T) { - table := []struct { - a, b interface{} - shouldEqual bool - }{ - {resource.MustParse("0"), resource.Quantity{}, true}, - {resource.Quantity{}, resource.MustParse("0"), true}, - {resource.Quantity{}, resource.MustParse("1m"), false}, - { - resource.NewQuantity(5, resource.BinarySI), - resource.NewQuantity(5, resource.DecimalSI), - true, - }, - {resource.MustParse("2m"), resource.MustParse("1m"), false}, - } - - for index, item := range table { - if e, a := item.shouldEqual, Semantic.DeepEqual(item.a, item.b); e != a { - t.Errorf("case[%d], expected %v, got %v.", index, e, a) - } - } -} - -func TestIsStandardResource(t *testing.T) { - testCases := []struct { - input string - output bool - }{ - {"cpu", true}, - {"memory", true}, - {"disk", false}, - {"blah", false}, - {"x.y.z", false}, - {"hugepages-2Mi", true}, - {"requests.hugepages-2Mi", true}, - } - for i, tc := range testCases { - if IsStandardResourceName(tc.input) != tc.output { - t.Errorf("case[%d], input: %s, expected: %t, got: %t", i, tc.input, tc.output, !tc.output) - } - } -} - -func TestIsStandardContainerResource(t *testing.T) { - testCases := []struct { - input string - output bool - }{ - {"cpu", true}, - {"memory", true}, - {"disk", false}, - {"hugepages-2Mi", true}, - } - for i, tc := range testCases { - if IsStandardContainerResourceName(tc.input) != tc.output { - t.Errorf("case[%d], input: %s, expected: %t, got: %t", i, tc.input, tc.output, !tc.output) - } - } -} - -func TestAddToNodeAddresses(t *testing.T) { - testCases := []struct { - existing []core.NodeAddress - toAdd []core.NodeAddress - expected []core.NodeAddress - }{ - { - existing: []core.NodeAddress{}, - toAdd: []core.NodeAddress{}, - expected: []core.NodeAddress{}, - }, - { - existing: []core.NodeAddress{}, - toAdd: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - {Type: core.NodeHostName, Address: "localhost"}, - }, - expected: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - {Type: core.NodeHostName, Address: "localhost"}, - }, - }, - { - existing: []core.NodeAddress{}, - toAdd: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - }, - expected: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - }, - }, - { - existing: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - {Type: core.NodeInternalIP, Address: "10.1.1.1"}, - }, - toAdd: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - {Type: core.NodeHostName, Address: "localhost"}, - }, - expected: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - {Type: core.NodeInternalIP, Address: "10.1.1.1"}, - {Type: core.NodeHostName, Address: "localhost"}, - }, - }, - } - - for i, tc := range testCases { - AddToNodeAddresses(&tc.existing, tc.toAdd...) - if !Semantic.DeepEqual(tc.expected, tc.existing) { - t.Errorf("case[%d], expected: %v, got: %v", i, tc.expected, tc.existing) - } - } -} - -func TestGetAccessModesFromString(t *testing.T) { - modes := GetAccessModesFromString("ROX") - if !containsAccessMode(modes, core.ReadOnlyMany) { - t.Errorf("Expected mode %s, but got %+v", core.ReadOnlyMany, modes) - } - - modes = GetAccessModesFromString("ROX,RWX") - if !containsAccessMode(modes, core.ReadOnlyMany) { - t.Errorf("Expected mode %s, but got %+v", core.ReadOnlyMany, modes) - } - if !containsAccessMode(modes, core.ReadWriteMany) { - t.Errorf("Expected mode %s, but got %+v", core.ReadWriteMany, modes) - } - - modes = GetAccessModesFromString("RWO,ROX,RWX") - if !containsAccessMode(modes, core.ReadOnlyMany) { - t.Errorf("Expected mode %s, but got %+v", core.ReadOnlyMany, modes) - } - if !containsAccessMode(modes, core.ReadWriteMany) { - t.Errorf("Expected mode %s, but got %+v", core.ReadWriteMany, modes) - } -} - -func TestRemoveDuplicateAccessModes(t *testing.T) { - modes := []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, core.ReadOnlyMany, core.ReadOnlyMany, core.ReadOnlyMany, - } - modes = removeDuplicateAccessModes(modes) - if len(modes) != 2 { - t.Errorf("Expected 2 distinct modes in set but found %v", len(modes)) - } -} - -func TestNodeSelectorRequirementsAsSelector(t *testing.T) { - matchExpressions := []core.NodeSelectorRequirement{{ - Key: "foo", - Operator: core.NodeSelectorOpIn, - Values: []string{"bar", "baz"}, - }} - mustParse := func(s string) labels.Selector { - out, e := labels.Parse(s) - if e != nil { - panic(e) - } - return out - } - tc := []struct { - in []core.NodeSelectorRequirement - out labels.Selector - expectErr bool - }{ - {in: nil, out: labels.Nothing()}, - {in: []core.NodeSelectorRequirement{}, out: labels.Nothing()}, - { - in: matchExpressions, - out: mustParse("foo in (baz,bar)"), - }, - { - in: []core.NodeSelectorRequirement{{ - Key: "foo", - Operator: core.NodeSelectorOpExists, - Values: []string{"bar", "baz"}, - }}, - expectErr: true, - }, - { - in: []core.NodeSelectorRequirement{{ - Key: "foo", - Operator: core.NodeSelectorOpGt, - Values: []string{"1"}, - }}, - out: mustParse("foo>1"), - }, - { - in: []core.NodeSelectorRequirement{{ - Key: "bar", - Operator: core.NodeSelectorOpLt, - Values: []string{"7"}, - }}, - out: mustParse("bar<7"), - }, - } - - for i, tc := range tc { - out, err := NodeSelectorRequirementsAsSelector(tc.in) - if err == nil && tc.expectErr { - t.Errorf("[%v]expected error but got none.", i) - } - if err != nil && !tc.expectErr { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } - if !reflect.DeepEqual(out, tc.out) { - t.Errorf("[%v]expected:\n\t%+v\nbut got:\n\t%+v", i, tc.out, out) - } - } -} - -func TestSysctlsFromPodAnnotation(t *testing.T) { - type Test struct { - annotation string - expectValue []core.Sysctl - expectErr bool - } - for i, test := range []Test{ - { - annotation: "", - expectValue: nil, - }, - { - annotation: "foo.bar", - expectErr: true, - }, - { - annotation: "=123", - expectErr: true, - }, - { - annotation: "foo.bar=", - expectValue: []core.Sysctl{{Name: "foo.bar", Value: ""}}, - }, - { - annotation: "foo.bar=42", - expectValue: []core.Sysctl{{Name: "foo.bar", Value: "42"}}, - }, - { - annotation: "foo.bar=42,", - expectErr: true, - }, - { - annotation: "foo.bar=42,abc.def=1", - expectValue: []core.Sysctl{{Name: "foo.bar", Value: "42"}, {Name: "abc.def", Value: "1"}}, - }, - } { - sysctls, err := SysctlsFromPodAnnotation(test.annotation) - if test.expectErr && err == nil { - t.Errorf("[%v]expected error but got none", i) - } else if !test.expectErr && err != nil { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } else if !reflect.DeepEqual(sysctls, test.expectValue) { - t.Errorf("[%v]expect value %v but got %v", i, test.expectValue, sysctls) - } - } -} - -// TODO: remove when alpha support for topology constraints is removed -func TestGetNodeAffinityFromAnnotations(t *testing.T) { - testCases := []struct { - annotations map[string]string - expectErr bool - }{ - { - annotations: nil, - expectErr: false, - }, - { - annotations: map[string]string{}, - expectErr: false, - }, - { - annotations: map[string]string{ - core.AlphaStorageNodeAffinityAnnotation: `{ - "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [ - { "matchExpressions": [ - { "key": "test-key1", - "operator": "In", - "values": ["test-value1", "test-value2"] - }, - { "key": "test-key2", - "operator": "In", - "values": ["test-value1", "test-value2"] - } - ]} - ]} - }`, - }, - expectErr: false, - }, - { - annotations: map[string]string{ - core.AlphaStorageNodeAffinityAnnotation: `[{ - "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [ - { "matchExpressions": [ - { "key": "test-key1", - "operator": "In", - "values": ["test-value1", "test-value2"] - }, - { "key": "test-key2", - "operator": "In", - "values": ["test-value1", "test-value2"] - } - ]} - ]} - }]`, - }, - expectErr: true, - }, - { - annotations: map[string]string{ - core.AlphaStorageNodeAffinityAnnotation: `{ - "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": - "matchExpressions": [ - { "key": "test-key1", - "operator": "In", - "values": ["test-value1", "test-value2"] - }, - { "key": "test-key2", - "operator": "In", - "values": ["test-value1", "test-value2"] - } - ]} - } - }`, - }, - expectErr: true, - }, - } - - for i, tc := range testCases { - _, err := GetStorageNodeAffinityFromAnnotation(tc.annotations) - if err == nil && tc.expectErr { - t.Errorf("[%v]expected error but got none.", i) - } - if err != nil && !tc.expectErr { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } - } -} - -func TestIsHugePageResourceName(t *testing.T) { - testCases := []struct { - name core.ResourceName - result bool - }{ - { - name: core.ResourceName("hugepages-2Mi"), - result: true, - }, - { - name: core.ResourceName("hugepages-1Gi"), - result: true, - }, - { - name: core.ResourceName("cpu"), - result: false, - }, - { - name: core.ResourceName("memory"), - result: false, - }, - } - for _, testCase := range testCases { - if testCase.result != IsHugePageResourceName(testCase.name) { - t.Errorf("resource: %v expected result: %v", testCase.name, testCase.result) - } - } -} - -func TestHugePageResourceName(t *testing.T) { - testCases := []struct { - pageSize resource.Quantity - name core.ResourceName - }{ - { - pageSize: resource.MustParse("2Mi"), - name: core.ResourceName("hugepages-2Mi"), - }, - { - pageSize: resource.MustParse("1Gi"), - name: core.ResourceName("hugepages-1Gi"), - }, - { - // verify we do not regress our canonical representation - pageSize: *resource.NewQuantity(int64(2097152), resource.BinarySI), - name: core.ResourceName("hugepages-2Mi"), - }, - } - for _, testCase := range testCases { - if result := HugePageResourceName(testCase.pageSize); result != testCase.name { - t.Errorf("pageSize: %v, expected: %v, but got: %v", testCase.pageSize.String(), testCase.name, result.String()) - } - } -} - -func TestHugePageSizeFromResourceName(t *testing.T) { - testCases := []struct { - name core.ResourceName - expectErr bool - pageSize resource.Quantity - }{ - { - name: core.ResourceName("hugepages-2Mi"), - pageSize: resource.MustParse("2Mi"), - expectErr: false, - }, - { - name: core.ResourceName("hugepages-1Gi"), - pageSize: resource.MustParse("1Gi"), - expectErr: false, - }, - { - name: core.ResourceName("hugepages-bad"), - expectErr: true, - }, - } - for _, testCase := range testCases { - value, err := HugePageSizeFromResourceName(testCase.name) - if testCase.expectErr && err == nil { - t.Errorf("Expected an error for %v", testCase.name) - } else if !testCase.expectErr && err != nil { - t.Errorf("Unexpected error for %v, got %v", testCase.name, err) - } else if testCase.pageSize.Value() != value.Value() { - t.Errorf("Unexpected pageSize for resource %v got %v", testCase.name, value.String()) - } - } -} - -func TestIsOvercommitAllowed(t *testing.T) { - testCases := []struct { - name core.ResourceName - allowed bool - }{ - { - name: core.ResourceCPU, - allowed: true, - }, - { - name: core.ResourceMemory, - allowed: true, - }, - { - name: core.ResourceNvidiaGPU, - allowed: false, - }, - { - name: HugePageResourceName(resource.MustParse("2Mi")), - allowed: false, - }, - } - for _, testCase := range testCases { - if testCase.allowed != IsOvercommitAllowed(testCase.name) { - t.Errorf("Unexpected result for %v", testCase.name) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/install/install_test.go b/vendor/k8s.io/kubernetes/pkg/apis/core/install/install_test.go deleted file mode 100644 index b580c56c4f..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/install/install_test.go +++ /dev/null @@ -1,140 +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 install - -import ( - "encoding/json" - "reflect" - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/kubernetes/pkg/api/legacyscheme" - internal "k8s.io/kubernetes/pkg/apis/core" -) - -func TestResourceVersioner(t *testing.T) { - g, err := legacyscheme.Registry.Group(v1.GroupName) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - intf, err := g.DefaultInterfacesFor(v1.SchemeGroupVersion) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - accessor := intf.MetadataAccessor - - pod := internal.Pod{ObjectMeta: metav1.ObjectMeta{ResourceVersion: "10"}} - version, err := accessor.ResourceVersion(&pod) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if version != "10" { - t.Errorf("unexpected version %v", version) - } - - podList := internal.PodList{ListMeta: metav1.ListMeta{ResourceVersion: "10"}} - version, err = accessor.ResourceVersion(&podList) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if version != "10" { - t.Errorf("unexpected version %v", version) - } -} - -func TestCodec(t *testing.T) { - pod := internal.Pod{} - // We do want to use package registered rather than testapi here, because we - // want to test if the package install and package registered work as expected. - data, err := runtime.Encode(legacyscheme.Codecs.LegacyCodec(legacyscheme.Registry.GroupOrDie(internal.GroupName).GroupVersion), &pod) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - other := internal.Pod{} - if err := json.Unmarshal(data, &other); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if other.APIVersion != legacyscheme.Registry.GroupOrDie(internal.GroupName).GroupVersion.Version || other.Kind != "Pod" { - t.Errorf("unexpected unmarshalled object %#v", other) - } -} - -func TestInterfacesFor(t *testing.T) { - if _, err := legacyscheme.Registry.GroupOrDie(internal.GroupName).InterfacesFor(internal.SchemeGroupVersion); err == nil { - t.Fatalf("unexpected non-error: %v", err) - } - for i, version := range legacyscheme.Registry.GroupOrDie(internal.GroupName).GroupVersions { - if vi, err := legacyscheme.Registry.GroupOrDie(internal.GroupName).InterfacesFor(version); err != nil || vi == nil { - t.Fatalf("%d: unexpected result: %v", i, err) - } - } -} - -func TestRESTMapper(t *testing.T) { - gv := schema.GroupVersion{Group: "", Version: "v1"} - rcGVK := gv.WithKind("ReplicationController") - podTemplateGVK := gv.WithKind("PodTemplate") - - if gvk, err := legacyscheme.Registry.RESTMapper().KindFor(internal.SchemeGroupVersion.WithResource("replicationcontrollers")); err != nil || gvk != rcGVK { - t.Errorf("unexpected version mapping: %v %v", gvk, err) - } - - if m, err := legacyscheme.Registry.GroupOrDie(internal.GroupName).RESTMapper.RESTMapping(podTemplateGVK.GroupKind(), ""); err != nil || m.GroupVersionKind != podTemplateGVK || m.Resource != "podtemplates" { - t.Errorf("unexpected version mapping: %#v %v", m, err) - } - - for _, version := range legacyscheme.Registry.GroupOrDie(internal.GroupName).GroupVersions { - mapping, err := legacyscheme.Registry.GroupOrDie(internal.GroupName).RESTMapper.RESTMapping(rcGVK.GroupKind(), version.Version) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if mapping.Resource != "replicationControllers" && mapping.Resource != "replicationcontrollers" { - t.Errorf("incorrect resource name: %#v", mapping) - } - if mapping.GroupVersionKind.GroupVersion() != version { - t.Errorf("incorrect version: %v", mapping) - } - - interfaces, _ := legacyscheme.Registry.GroupOrDie(internal.GroupName).InterfacesFor(version) - if mapping.ObjectConvertor != interfaces.ObjectConvertor { - t.Errorf("unexpected: %#v, expected: %#v", mapping, interfaces) - } - - rc := &internal.ReplicationController{ObjectMeta: metav1.ObjectMeta{Name: "foo"}} - name, err := mapping.MetadataAccessor.Name(rc) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if name != "foo" { - t.Errorf("unable to retrieve object meta with: %v", mapping.MetadataAccessor) - } - } -} - -func TestUnversioned(t *testing.T) { - for _, obj := range []runtime.Object{ - &metav1.Status{}, - } { - if unversioned, ok := legacyscheme.Scheme.IsUnversioned(obj); !unversioned || !ok { - t.Errorf("%v is expected to be unversioned", reflect.TypeOf(obj)) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/pods/helpers_test.go b/vendor/k8s.io/kubernetes/pkg/apis/core/pods/helpers_test.go deleted file mode 100644 index 9db95a014b..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/pods/helpers_test.go +++ /dev/null @@ -1,87 +0,0 @@ -/* -Copyright 2017 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 pods - -import ( - "testing" -) - -func TestConvertDownwardAPIFieldLabel(t *testing.T) { - testCases := []struct { - version string - label string - value string - expectedErr bool - expectedLabel string - expectedValue string - }{ - { - version: "v2", - label: "metadata.name", - value: "test-pod", - expectedErr: true, - }, - { - version: "v1", - label: "invalid-label", - value: "value", - expectedErr: true, - }, - { - version: "v1", - label: "metadata.name", - value: "test-pod", - expectedLabel: "metadata.name", - expectedValue: "test-pod", - }, - { - version: "v1", - label: "metadata.annotations", - value: "myValue", - expectedLabel: "metadata.annotations", - expectedValue: "myValue", - }, - { - version: "v1", - label: "metadata.annotations['myKey']", - value: "myValue", - expectedLabel: "metadata.annotations['myKey']", - expectedValue: "myValue", - }, - { - version: "v1", - label: "spec.host", - value: "127.0.0.1", - expectedLabel: "spec.nodeName", - expectedValue: "127.0.0.1", - }, - } - for _, tc := range testCases { - label, value, err := ConvertDownwardAPIFieldLabel(tc.version, tc.label, tc.value) - if err != nil { - if tc.expectedErr { - continue - } - t.Errorf("ConvertDownwardAPIFieldLabel(%s, %s, %s) failed: %s", - tc.version, tc.label, tc.value, err) - } - if tc.expectedLabel != label || tc.expectedValue != value { - t.Errorf("ConvertDownwardAPIFieldLabel(%s, %s, %s) = (%s, %s, nil), expected (%s, %s, nil)", - tc.version, tc.label, tc.value, label, value, tc.expectedLabel, tc.expectedValue) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/taint_test.go b/vendor/k8s.io/kubernetes/pkg/apis/core/taint_test.go deleted file mode 100644 index baa9404e08..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/taint_test.go +++ /dev/null @@ -1,120 +0,0 @@ -/* -Copyright 2017 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 core - -import "testing" - -func TestTaintToString(t *testing.T) { - testCases := []struct { - taint *Taint - expectedString string - }{ - { - taint: &Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectedString: "foo=bar:NoSchedule", - }, - { - taint: &Taint{ - Key: "foo", - Effect: TaintEffectNoSchedule, - }, - expectedString: "foo:NoSchedule", - }, - } - - for i, tc := range testCases { - if tc.expectedString != tc.taint.ToString() { - t.Errorf("[%v] expected taint %v converted to %s, got %s", i, tc.taint, tc.expectedString, tc.taint.ToString()) - } - } -} - -func TestMatchTaint(t *testing.T) { - testCases := []struct { - description string - taint *Taint - taintToMatch Taint - expectMatch bool - }{ - { - description: "two taints with the same key,value,effect should match", - taint: &Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - taintToMatch: Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectMatch: true, - }, - { - description: "two taints with the same key,effect but different value should match", - taint: &Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - taintToMatch: Taint{ - Key: "foo", - Value: "different-value", - Effect: TaintEffectNoSchedule, - }, - expectMatch: true, - }, - { - description: "two taints with the different key cannot match", - taint: &Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - taintToMatch: Taint{ - Key: "different-key", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectMatch: false, - }, - { - description: "two taints with the different effect cannot match", - taint: &Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - taintToMatch: Taint{ - Key: "foo", - Value: "bar", - Effect: TaintEffectPreferNoSchedule, - }, - expectMatch: false, - }, - } - - for _, tc := range testCases { - if tc.expectMatch != tc.taint.MatchTaint(tc.taintToMatch) { - t.Errorf("[%s] expect taint %s match taint %s", tc.description, tc.taint.ToString(), tc.taintToMatch.ToString()) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/toleration_test.go b/vendor/k8s.io/kubernetes/pkg/apis/core/toleration_test.go deleted file mode 100644 index ec7a8dec13..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/toleration_test.go +++ /dev/null @@ -1,136 +0,0 @@ -/* -Copyright 2017 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 core - -import "testing" - -func TestMatchToleration(t *testing.T) { - - tolerationSeconds := int64(5) - tolerationToMatchSeconds := int64(3) - testCases := []struct { - description string - toleration *Toleration - tolerationToMatch *Toleration - expectMatch bool - }{ - { - description: "two taints with the same key,operator,value,effect should match", - toleration: &Toleration{ - Key: "foo", - Operator: "Exists", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - tolerationToMatch: &Toleration{ - Key: "foo", - Operator: "Exists", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectMatch: true, - }, - { - description: "two taints with the different key cannot match", - toleration: &Toleration{ - Key: "foo", - Operator: "Exists", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - tolerationToMatch: &Toleration{ - Key: "different-key", - Operator: "Exists", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectMatch: false, - }, - { - description: "two taints with the different operator cannot match", - toleration: &Toleration{ - Key: "foo", - Operator: "Exists", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - tolerationToMatch: &Toleration{ - Key: "foo", - Operator: "different-operator", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - expectMatch: false, - }, - { - description: "two taints with the different value cannot match", - toleration: &Toleration{ - Key: "foo", - Operator: "Exists", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - tolerationToMatch: &Toleration{ - Key: "foo", - Operator: "Exists", - Value: "different-value", - Effect: TaintEffectNoSchedule, - }, - expectMatch: false, - }, - { - description: "two taints with the different effect cannot match", - toleration: &Toleration{ - Key: "foo", - Operator: "Exists", - Value: "bar", - Effect: TaintEffectNoSchedule, - }, - tolerationToMatch: &Toleration{ - Key: "foo", - Operator: "Exists", - Value: "bar", - Effect: TaintEffectPreferNoSchedule, - }, - expectMatch: false, - }, - { - description: "two taints with the different tolerationSeconds should match", - toleration: &Toleration{ - Key: "foo", - Operator: "Exists", - Value: "bar", - Effect: TaintEffectNoSchedule, - TolerationSeconds: &tolerationSeconds, - }, - tolerationToMatch: &Toleration{ - Key: "foo", - Operator: "Exists", - Value: "bar", - Effect: TaintEffectNoSchedule, - TolerationSeconds: &tolerationToMatchSeconds, - }, - expectMatch: true, - }, - } - - for _, tc := range testCases { - if actual := tc.toleration.MatchToleration(tc.tolerationToMatch); actual != tc.expectMatch { - t.Errorf("[%s] expect: %v , got: %v", tc.description, tc.expectMatch, !tc.expectMatch) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/types.go b/vendor/k8s.io/kubernetes/pkg/apis/core/types.go index 8b183deb7c..e1b3853b6d 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/types.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/core/types.go @@ -1711,6 +1711,12 @@ type VolumeMount struct { type MountPropagationMode string const ( + // MountPropagationNone 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. + MountPropagationNone MountPropagationMode = "None" // MountPropagationHostToContainer 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 diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/v1/conversion_test.go b/vendor/k8s.io/kubernetes/pkg/apis/core/v1/conversion_test.go deleted file mode 100644 index e6d2bbdc56..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/v1/conversion_test.go +++ /dev/null @@ -1,348 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1_test - -import ( - "encoding/json" - "math/rand" - "net/url" - "reflect" - "testing" - "time" - - "k8s.io/api/core/v1" - extensionsv1beta1 "k8s.io/api/extensions/v1beta1" - apiequality "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/resource" - "k8s.io/apimachinery/pkg/api/testing/fuzzer" - metafuzzer "k8s.io/apimachinery/pkg/apis/meta/fuzzer" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/diff" - "k8s.io/kubernetes/pkg/api/legacyscheme" - "k8s.io/kubernetes/pkg/apis/core" - corefuzzer "k8s.io/kubernetes/pkg/apis/core/fuzzer" - corev1 "k8s.io/kubernetes/pkg/apis/core/v1" - "k8s.io/kubernetes/pkg/apis/extensions" - utilpointer "k8s.io/kubernetes/pkg/util/pointer" - - // enforce that all types are installed - _ "k8s.io/kubernetes/pkg/api/testapi" -) - -func TestPodLogOptions(t *testing.T) { - sinceSeconds := int64(1) - sinceTime := metav1.NewTime(time.Date(2000, 1, 1, 12, 34, 56, 0, time.UTC).Local()) - tailLines := int64(2) - limitBytes := int64(3) - - versionedLogOptions := &v1.PodLogOptions{ - Container: "mycontainer", - Follow: true, - Previous: true, - SinceSeconds: &sinceSeconds, - SinceTime: &sinceTime, - Timestamps: true, - TailLines: &tailLines, - LimitBytes: &limitBytes, - } - unversionedLogOptions := &core.PodLogOptions{ - Container: "mycontainer", - Follow: true, - Previous: true, - SinceSeconds: &sinceSeconds, - SinceTime: &sinceTime, - Timestamps: true, - TailLines: &tailLines, - LimitBytes: &limitBytes, - } - expectedParameters := url.Values{ - "container": {"mycontainer"}, - "follow": {"true"}, - "previous": {"true"}, - "sinceSeconds": {"1"}, - "sinceTime": {"2000-01-01T12:34:56Z"}, - "timestamps": {"true"}, - "tailLines": {"2"}, - "limitBytes": {"3"}, - } - - codec := runtime.NewParameterCodec(legacyscheme.Scheme) - - // unversioned -> query params - { - actualParameters, err := codec.EncodeParameters(unversionedLogOptions, v1.SchemeGroupVersion) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(actualParameters, expectedParameters) { - t.Fatalf("Expected\n%#v\ngot\n%#v", expectedParameters, actualParameters) - } - } - - // versioned -> query params - { - actualParameters, err := codec.EncodeParameters(versionedLogOptions, v1.SchemeGroupVersion) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(actualParameters, expectedParameters) { - t.Fatalf("Expected\n%#v\ngot\n%#v", expectedParameters, actualParameters) - } - } - - // query params -> versioned - { - convertedLogOptions := &v1.PodLogOptions{} - err := codec.DecodeParameters(expectedParameters, v1.SchemeGroupVersion, convertedLogOptions) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(convertedLogOptions, versionedLogOptions) { - t.Fatalf("Unexpected deserialization:\n%s", diff.ObjectGoPrintSideBySide(versionedLogOptions, convertedLogOptions)) - } - } - - // query params -> unversioned - { - convertedLogOptions := &core.PodLogOptions{} - err := codec.DecodeParameters(expectedParameters, v1.SchemeGroupVersion, convertedLogOptions) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(convertedLogOptions, unversionedLogOptions) { - t.Fatalf("Unexpected deserialization:\n%s", diff.ObjectGoPrintSideBySide(unversionedLogOptions, convertedLogOptions)) - } - } -} - -// TestPodSpecConversion tests that v1.ServiceAccount is an alias for -// ServiceAccountName. -func TestPodSpecConversion(t *testing.T) { - name, other := "foo", "bar" - - // Test internal -> v1. Should have both alias (DeprecatedServiceAccount) - // and new field (ServiceAccountName). - i := &core.PodSpec{ - ServiceAccountName: name, - } - v := v1.PodSpec{} - if err := legacyscheme.Scheme.Convert(i, &v, nil); err != nil { - t.Fatalf("unexpected error: %v", err) - } - if v.ServiceAccountName != name { - t.Fatalf("want v1.ServiceAccountName %q, got %q", name, v.ServiceAccountName) - } - if v.DeprecatedServiceAccount != name { - t.Fatalf("want v1.DeprecatedServiceAccount %q, got %q", name, v.DeprecatedServiceAccount) - } - - // Test v1 -> internal. Either DeprecatedServiceAccount, ServiceAccountName, - // or both should translate to ServiceAccountName. ServiceAccountName wins - // if both are set. - testCases := []*v1.PodSpec{ - // New - {ServiceAccountName: name}, - // Alias - {DeprecatedServiceAccount: name}, - // Both: same - {ServiceAccountName: name, DeprecatedServiceAccount: name}, - // Both: different - {ServiceAccountName: name, DeprecatedServiceAccount: other}, - } - for k, v := range testCases { - got := core.PodSpec{} - err := legacyscheme.Scheme.Convert(v, &got, nil) - if err != nil { - t.Fatalf("unexpected error for case %d: %v", k, err) - } - if got.ServiceAccountName != name { - t.Fatalf("want core.ServiceAccountName %q, got %q", name, got.ServiceAccountName) - } - } -} - -func TestResourceListConversion(t *testing.T) { - bigMilliQuantity := resource.NewQuantity(resource.MaxMilliValue, resource.DecimalSI) - bigMilliQuantity.Add(resource.MustParse("12345m")) - - tests := []struct { - input v1.ResourceList - expected core.ResourceList - }{ - { // No changes necessary. - input: v1.ResourceList{ - v1.ResourceMemory: resource.MustParse("30M"), - v1.ResourceCPU: resource.MustParse("100m"), - v1.ResourceStorage: resource.MustParse("1G"), - }, - expected: core.ResourceList{ - core.ResourceMemory: resource.MustParse("30M"), - core.ResourceCPU: resource.MustParse("100m"), - core.ResourceStorage: resource.MustParse("1G"), - }, - }, - { // Nano-scale values should be rounded up to milli-scale. - input: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("3.000023m"), - v1.ResourceMemory: resource.MustParse("500.000050m"), - }, - expected: core.ResourceList{ - core.ResourceCPU: resource.MustParse("4m"), - core.ResourceMemory: resource.MustParse("501m"), - }, - }, - { // Large values should still be accurate. - input: v1.ResourceList{ - v1.ResourceCPU: *bigMilliQuantity.Copy(), - v1.ResourceStorage: *bigMilliQuantity.Copy(), - }, - expected: core.ResourceList{ - core.ResourceCPU: *bigMilliQuantity.Copy(), - core.ResourceStorage: *bigMilliQuantity.Copy(), - }, - }, - } - - for i, test := range tests { - output := core.ResourceList{} - - // defaulting is a separate step from conversion that is applied when reading from the API or from etcd. - // perform that step explicitly. - corev1.SetDefaults_ResourceList(&test.input) - - err := legacyscheme.Scheme.Convert(&test.input, &output, nil) - if err != nil { - t.Fatalf("unexpected error for case %d: %v", i, err) - } - if !apiequality.Semantic.DeepEqual(test.expected, output) { - t.Errorf("unexpected conversion for case %d: Expected\n%+v;\nGot\n%+v", i, test.expected, output) - } - } -} - -func TestReplicationControllerConversion(t *testing.T) { - // If we start with a RC, we should always have round-trip fidelity. - inputs := []*v1.ReplicationController{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "name", - Namespace: "namespace", - }, - Spec: v1.ReplicationControllerSpec{ - Replicas: utilpointer.Int32Ptr(1), - MinReadySeconds: 32, - Selector: map[string]string{"foo": "bar", "bar": "foo"}, - Template: &v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"foo": "bar", "bar": "foo"}, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - Name: "container", - Image: "image", - }, - }, - }, - }, - }, - Status: v1.ReplicationControllerStatus{ - Replicas: 1, - FullyLabeledReplicas: 2, - ReadyReplicas: 3, - AvailableReplicas: 4, - ObservedGeneration: 5, - Conditions: []v1.ReplicationControllerCondition{ - { - Type: v1.ReplicationControllerReplicaFailure, - Status: v1.ConditionTrue, - LastTransitionTime: metav1.NewTime(time.Unix(123456789, 0)), - Reason: "Reason", - Message: "Message", - }, - }, - }, - }, - } - - // Add some fuzzed RCs. - apiObjectFuzzer := fuzzer.FuzzerFor(fuzzer.MergeFuzzerFuncs(metafuzzer.Funcs, corefuzzer.Funcs), rand.NewSource(152), legacyscheme.Codecs) - for i := 0; i < 100; i++ { - rc := &v1.ReplicationController{} - apiObjectFuzzer.Fuzz(rc) - // Sometimes the fuzzer decides to leave Spec.Template nil. - // We can't support that because Spec.Template is not a pointer in RS, - // so it will round-trip as non-nil but empty. - if rc.Spec.Template == nil { - rc.Spec.Template = &v1.PodTemplateSpec{} - } - // Sometimes the fuzzer decides to insert an empty label key. - // This doesn't round-trip properly because it's invalid. - if rc.Spec.Selector != nil { - delete(rc.Spec.Selector, "") - } - inputs = append(inputs, rc) - } - - // Round-trip the input RCs before converting to RS. - for i := range inputs { - inputs[i] = roundTrip(t, inputs[i]).(*v1.ReplicationController) - } - - for _, in := range inputs { - rs := &extensions.ReplicaSet{} - // Use in.DeepCopy() to avoid sharing pointers with `in`. - if err := corev1.Convert_v1_ReplicationController_to_extensions_ReplicaSet(in.DeepCopy(), rs, nil); err != nil { - t.Errorf("can't convert RC to RS: %v", err) - continue - } - // Round-trip RS before converting back to RC. - rs = roundTripRS(t, rs) - out := &v1.ReplicationController{} - if err := corev1.Convert_extensions_ReplicaSet_to_v1_ReplicationController(rs, out, nil); err != nil { - t.Errorf("can't convert RS to RC: %v", err) - continue - } - if !apiequality.Semantic.DeepEqual(in, out) { - instr, _ := json.MarshalIndent(in, "", " ") - outstr, _ := json.MarshalIndent(out, "", " ") - t.Errorf("RC-RS conversion round-trip failed:\nin:\n%s\nout:\n%s", instr, outstr) - } - } -} - -func roundTripRS(t *testing.T, rs *extensions.ReplicaSet) *extensions.ReplicaSet { - codec := legacyscheme.Codecs.LegacyCodec(extensionsv1beta1.SchemeGroupVersion) - data, err := runtime.Encode(codec, rs) - if err != nil { - t.Errorf("%v\n %#v", err, rs) - return nil - } - obj2, err := runtime.Decode(codec, data) - if err != nil { - t.Errorf("%v\nData: %s\nSource: %#v", err, string(data), rs) - return nil - } - obj3 := &extensions.ReplicaSet{} - err = legacyscheme.Scheme.Convert(obj2, obj3, nil) - if err != nil { - t.Errorf("%v\nSource: %#v", err, obj2) - return nil - } - return obj3 -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/v1/defaults_test.go b/vendor/k8s.io/kubernetes/pkg/apis/core/v1/defaults_test.go deleted file mode 100644 index fceab578f2..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/v1/defaults_test.go +++ /dev/null @@ -1,1386 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package v1_test - -import ( - "fmt" - "reflect" - "testing" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/intstr" - utilfeature "k8s.io/apiserver/pkg/util/feature" - "k8s.io/kubernetes/pkg/api/legacyscheme" - corev1 "k8s.io/kubernetes/pkg/apis/core/v1" - utilpointer "k8s.io/kubernetes/pkg/util/pointer" - - // enforce that all types are installed - _ "k8s.io/kubernetes/pkg/api/testapi" -) - -func roundTrip(t *testing.T, obj runtime.Object) runtime.Object { - codec := legacyscheme.Codecs.LegacyCodec(corev1.SchemeGroupVersion) - data, err := runtime.Encode(codec, obj) - if err != nil { - t.Errorf("%v\n %#v", err, obj) - return nil - } - obj2, err := runtime.Decode(codec, data) - if err != nil { - t.Errorf("%v\nData: %s\nSource: %#v", err, string(data), obj) - return nil - } - obj3 := reflect.New(reflect.TypeOf(obj).Elem()).Interface().(runtime.Object) - err = legacyscheme.Scheme.Convert(obj2, obj3, nil) - if err != nil { - t.Errorf("%v\nSource: %#v", err, obj2) - return nil - } - return obj3 -} - -func TestSetDefaultReplicationController(t *testing.T) { - tests := []struct { - rc *v1.ReplicationController - expectLabels bool - expectSelector bool - }{ - { - rc: &v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Template: &v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: true, - expectSelector: true, - }, - { - rc: &v1.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "bar": "foo", - }, - }, - Spec: v1.ReplicationControllerSpec{ - Template: &v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: false, - expectSelector: true, - }, - { - rc: &v1.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "bar": "foo", - }, - }, - Spec: v1.ReplicationControllerSpec{ - Selector: map[string]string{ - "some": "other", - }, - Template: &v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: false, - expectSelector: false, - }, - { - rc: &v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Selector: map[string]string{ - "some": "other", - }, - Template: &v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectLabels: true, - expectSelector: false, - }, - } - - for _, test := range tests { - rc := test.rc - obj2 := roundTrip(t, runtime.Object(rc)) - rc2, ok := obj2.(*v1.ReplicationController) - if !ok { - t.Errorf("unexpected object: %v", rc2) - t.FailNow() - } - if test.expectSelector != reflect.DeepEqual(rc2.Spec.Selector, rc2.Spec.Template.Labels) { - if test.expectSelector { - t.Errorf("expected: %v, got: %v", rc2.Spec.Template.Labels, rc2.Spec.Selector) - } else { - t.Errorf("unexpected equality: %v", rc.Spec.Selector) - } - } - if test.expectLabels != reflect.DeepEqual(rc2.Labels, rc2.Spec.Template.Labels) { - if test.expectLabels { - t.Errorf("expected: %v, got: %v", rc2.Spec.Template.Labels, rc2.Labels) - } else { - t.Errorf("unexpected equality: %v", rc.Labels) - } - } - } -} - -func TestSetDefaultReplicationControllerReplicas(t *testing.T) { - tests := []struct { - rc v1.ReplicationController - expectReplicas int32 - }{ - { - rc: v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Template: &v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectReplicas: 1, - }, - { - rc: v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Replicas: utilpointer.Int32Ptr(0), - Template: &v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectReplicas: 0, - }, - { - rc: v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Replicas: utilpointer.Int32Ptr(3), - Template: &v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - }, - }, - expectReplicas: 3, - }, - } - - for _, test := range tests { - rc := &test.rc - obj2 := roundTrip(t, runtime.Object(rc)) - rc2, ok := obj2.(*v1.ReplicationController) - if !ok { - t.Errorf("unexpected object: %v", rc2) - t.FailNow() - } - if rc2.Spec.Replicas == nil { - t.Errorf("unexpected nil Replicas") - } else if test.expectReplicas != *rc2.Spec.Replicas { - t.Errorf("expected: %d replicas, got: %d", test.expectReplicas, *rc2.Spec.Replicas) - } - } -} - -type InitContainerValidator func(got, expected *v1.Container) error - -func TestSetDefaultReplicationControllerInitContainers(t *testing.T) { - assertEnvFieldRef := func(got, expected *v1.Container) error { - if len(got.Env) != len(expected.Env) { - return fmt.Errorf("different number of env: got <%v>, expected <%v>", len(got.Env), len(expected.Env)) - } - - for j := range got.Env { - ge := &got.Env[j] - ee := &expected.Env[j] - - if ge.Name != ee.Name { - return fmt.Errorf("different name of env: got <%v>, expected <%v>", ge.Name, ee.Name) - } - - if ge.ValueFrom.FieldRef.APIVersion != ee.ValueFrom.FieldRef.APIVersion { - return fmt.Errorf("different api version of FieldRef <%v>: got <%v>, expected <%v>", - ge.Name, ge.ValueFrom.FieldRef.APIVersion, ee.ValueFrom.FieldRef.APIVersion) - } - } - return nil - } - - assertImagePullPolicy := func(got, expected *v1.Container) error { - if got.ImagePullPolicy != expected.ImagePullPolicy { - return fmt.Errorf("different image pull poicy: got <%v>, expected <%v>", got.ImagePullPolicy, expected.ImagePullPolicy) - } - return nil - } - - assertContainerPort := func(got, expected *v1.Container) error { - if len(got.Ports) != len(expected.Ports) { - return fmt.Errorf("different number of ports: got <%v>, expected <%v>", len(got.Ports), len(expected.Ports)) - } - - for i := range got.Ports { - gp := &got.Ports[i] - ep := &expected.Ports[i] - - if gp.Name != ep.Name { - return fmt.Errorf("different name of port: got <%v>, expected <%v>", gp.Name, ep.Name) - } - - if gp.Protocol != ep.Protocol { - return fmt.Errorf("different port protocol <%v>: got <%v>, expected <%v>", gp.Name, gp.Protocol, ep.Protocol) - } - } - - return nil - } - - assertResource := func(got, expected *v1.Container) error { - if len(got.Resources.Limits) != len(expected.Resources.Limits) { - return fmt.Errorf("different number of resources.Limits: got <%v>, expected <%v>", len(got.Resources.Limits), (expected.Resources.Limits)) - } - - for k, v := range got.Resources.Limits { - if ev, found := expected.Resources.Limits[v1.ResourceName(k)]; !found { - return fmt.Errorf("failed to find resource <%v> in expected resources.Limits.", k) - } else { - if ev.Value() != v.Value() { - return fmt.Errorf("different resource.Limits: got <%v>, expected <%v>.", v.Value(), ev.Value()) - } - } - } - - if len(got.Resources.Requests) != len(expected.Resources.Requests) { - return fmt.Errorf("different number of resources.Requests: got <%v>, expected <%v>", len(got.Resources.Requests), (expected.Resources.Requests)) - } - - for k, v := range got.Resources.Requests { - if ev, found := expected.Resources.Requests[v1.ResourceName(k)]; !found { - return fmt.Errorf("failed to find resource <%v> in expected resources.Requests.", k) - } else { - if ev.Value() != v.Value() { - return fmt.Errorf("different resource.Requests: got <%v>, expected <%v>.", v.Value(), ev.Value()) - } - } - } - - return nil - } - - assertProb := func(got, expected *v1.Container) error { - // Assert LivenessProbe - if got.LivenessProbe.Handler.HTTPGet.Path != expected.LivenessProbe.Handler.HTTPGet.Path || - got.LivenessProbe.Handler.HTTPGet.Scheme != expected.LivenessProbe.Handler.HTTPGet.Scheme || - got.LivenessProbe.FailureThreshold != expected.LivenessProbe.FailureThreshold || - got.LivenessProbe.SuccessThreshold != expected.LivenessProbe.SuccessThreshold || - got.LivenessProbe.PeriodSeconds != expected.LivenessProbe.PeriodSeconds || - got.LivenessProbe.TimeoutSeconds != expected.LivenessProbe.TimeoutSeconds { - return fmt.Errorf("different LivenessProbe: got <%v>, expected <%v>", got.LivenessProbe, expected.LivenessProbe) - } - - // Assert ReadinessProbe - if got.ReadinessProbe.Handler.HTTPGet.Path != expected.ReadinessProbe.Handler.HTTPGet.Path || - got.ReadinessProbe.Handler.HTTPGet.Scheme != expected.ReadinessProbe.Handler.HTTPGet.Scheme || - got.ReadinessProbe.FailureThreshold != expected.ReadinessProbe.FailureThreshold || - got.ReadinessProbe.SuccessThreshold != expected.ReadinessProbe.SuccessThreshold || - got.ReadinessProbe.PeriodSeconds != expected.ReadinessProbe.PeriodSeconds || - got.ReadinessProbe.TimeoutSeconds != expected.ReadinessProbe.TimeoutSeconds { - return fmt.Errorf("different ReadinessProbe: got <%v>, expected <%v>", got.ReadinessProbe, expected.ReadinessProbe) - } - - return nil - } - - assertLifeCycle := func(got, expected *v1.Container) error { - if got.Lifecycle.PostStart.HTTPGet.Path != expected.Lifecycle.PostStart.HTTPGet.Path || - got.Lifecycle.PostStart.HTTPGet.Scheme != expected.Lifecycle.PostStart.HTTPGet.Scheme { - return fmt.Errorf("different LifeCycle: got <%v>, expected <%v>", got.Lifecycle, expected.Lifecycle) - } - - return nil - } - - cpu, _ := resource.ParseQuantity("100m") - mem, _ := resource.ParseQuantity("100Mi") - - tests := []struct { - name string - rc v1.ReplicationController - expected []v1.Container - validators []InitContainerValidator - }{ - { - name: "imagePullIPolicy", - rc: v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Template: &v1.PodTemplateSpec{ - Spec: v1.PodSpec{ - InitContainers: []v1.Container{ - { - Name: "install", - Image: "busybox", - }, - }, - }, - }, - }, - }, - expected: []v1.Container{ - { - ImagePullPolicy: v1.PullAlways, - }, - }, - validators: []InitContainerValidator{assertImagePullPolicy}, - }, - { - name: "FieldRef", - rc: v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Template: &v1.PodTemplateSpec{ - Spec: v1.PodSpec{ - InitContainers: []v1.Container{ - { - Name: "fun", - Image: "alpine", - Env: []v1.EnvVar{ - { - Name: "MY_POD_IP", - ValueFrom: &v1.EnvVarSource{ - FieldRef: &v1.ObjectFieldSelector{ - APIVersion: "", - FieldPath: "status.podIP", - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - expected: []v1.Container{ - { - Env: []v1.EnvVar{ - { - Name: "MY_POD_IP", - ValueFrom: &v1.EnvVarSource{ - FieldRef: &v1.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "status.podIP", - }, - }, - }, - }, - }, - }, - validators: []InitContainerValidator{assertEnvFieldRef}, - }, - { - name: "ContainerPort", - rc: v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Template: &v1.PodTemplateSpec{ - Spec: v1.PodSpec{ - InitContainers: []v1.Container{ - { - Name: "fun", - Image: "alpine", - Ports: []v1.ContainerPort{ - { - Name: "default", - }, - }, - }, - }, - }, - }, - }, - }, - expected: []v1.Container{ - { - Ports: []v1.ContainerPort{ - { - Name: "default", - Protocol: v1.ProtocolTCP, - }, - }, - }, - }, - validators: []InitContainerValidator{assertContainerPort}, - }, - { - name: "Resources", - rc: v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Template: &v1.PodTemplateSpec{ - Spec: v1.PodSpec{ - InitContainers: []v1.Container{ - { - Name: "fun", - Image: "alpine", - Resources: v1.ResourceRequirements{ - Limits: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("100m"), - v1.ResourceMemory: resource.MustParse("100Mi"), - }, - Requests: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("100m"), - v1.ResourceMemory: resource.MustParse("100Mi"), - }, - }, - }, - }, - }, - }, - }, - }, - expected: []v1.Container{ - { - Resources: v1.ResourceRequirements{ - Limits: v1.ResourceList{ - v1.ResourceCPU: cpu, - v1.ResourceMemory: mem, - }, - Requests: v1.ResourceList{ - v1.ResourceCPU: cpu, - v1.ResourceMemory: mem, - }, - }, - }, - }, - validators: []InitContainerValidator{assertResource}, - }, - { - name: "Probe", - rc: v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Template: &v1.PodTemplateSpec{ - Spec: v1.PodSpec{ - InitContainers: []v1.Container{ - { - Name: "fun", - Image: "alpine", - LivenessProbe: &v1.Probe{ - Handler: v1.Handler{ - HTTPGet: &v1.HTTPGetAction{ - Host: "localhost", - }, - }, - }, - ReadinessProbe: &v1.Probe{ - Handler: v1.Handler{ - HTTPGet: &v1.HTTPGetAction{ - Host: "localhost", - }, - }, - }, - }, - }, - }, - }, - }, - }, - expected: []v1.Container{ - { - LivenessProbe: &v1.Probe{ - Handler: v1.Handler{ - HTTPGet: &v1.HTTPGetAction{ - Path: "/", - Scheme: v1.URISchemeHTTP, - }, - }, - TimeoutSeconds: 1, - PeriodSeconds: 10, - SuccessThreshold: 1, - FailureThreshold: 3, - }, - ReadinessProbe: &v1.Probe{ - Handler: v1.Handler{ - HTTPGet: &v1.HTTPGetAction{ - Path: "/", - Scheme: v1.URISchemeHTTP, - }, - }, - TimeoutSeconds: 1, - PeriodSeconds: 10, - SuccessThreshold: 1, - FailureThreshold: 3, - }, - }, - }, - validators: []InitContainerValidator{assertProb}, - }, - { - name: "LifeCycle", - rc: v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Template: &v1.PodTemplateSpec{ - Spec: v1.PodSpec{ - InitContainers: []v1.Container{ - { - Name: "fun", - Image: "alpine", - Ports: []v1.ContainerPort{ - { - Name: "default", - }, - }, - Lifecycle: &v1.Lifecycle{ - PostStart: &v1.Handler{ - HTTPGet: &v1.HTTPGetAction{ - Host: "localhost", - }, - }, - PreStop: &v1.Handler{ - HTTPGet: &v1.HTTPGetAction{ - Host: "localhost", - }, - }, - }, - }, - }, - }, - }, - }, - }, - expected: []v1.Container{ - { - Lifecycle: &v1.Lifecycle{ - PostStart: &v1.Handler{ - HTTPGet: &v1.HTTPGetAction{ - Path: "/", - Scheme: v1.URISchemeHTTP, - }, - }, - PreStop: &v1.Handler{ - HTTPGet: &v1.HTTPGetAction{ - Path: "/", - Scheme: v1.URISchemeHTTP, - }, - }, - }, - }, - }, - validators: []InitContainerValidator{assertLifeCycle}, - }, - } - - assertInitContainers := func(got, expected []v1.Container, validators []InitContainerValidator) error { - if len(got) != len(expected) { - return fmt.Errorf("different number of init container: got <%d>, expected <%d>", - len(got), len(expected)) - } - - for i := range got { - g := &got[i] - e := &expected[i] - - for _, validator := range validators { - if err := validator(g, e); err != nil { - return err - } - } - } - - return nil - } - - for _, test := range tests { - rc := &test.rc - obj2 := roundTrip(t, runtime.Object(rc)) - rc2, ok := obj2.(*v1.ReplicationController) - if !ok { - t.Errorf("unexpected object: %v", rc2) - t.FailNow() - } - - if err := assertInitContainers(rc2.Spec.Template.Spec.InitContainers, test.expected, test.validators); err != nil { - t.Errorf("test %v failed: %v", test.name, err) - } - } -} - -func TestSetDefaultService(t *testing.T) { - svc := &v1.Service{} - obj2 := roundTrip(t, runtime.Object(svc)) - svc2 := obj2.(*v1.Service) - if svc2.Spec.SessionAffinity != v1.ServiceAffinityNone { - t.Errorf("Expected default session affinity type:%s, got: %s", v1.ServiceAffinityNone, svc2.Spec.SessionAffinity) - } - if svc2.Spec.SessionAffinityConfig != nil { - t.Errorf("Expected empty session affinity config when session affinity type: %s, got: %v", v1.ServiceAffinityNone, svc2.Spec.SessionAffinityConfig) - } - if svc2.Spec.Type != v1.ServiceTypeClusterIP { - t.Errorf("Expected default type:%s, got: %s", v1.ServiceTypeClusterIP, svc2.Spec.Type) - } -} - -func TestSetDefaultServiceSessionAffinityConfig(t *testing.T) { - testCases := map[string]v1.Service{ - "SessionAffinityConfig is empty": { - Spec: v1.ServiceSpec{ - SessionAffinity: v1.ServiceAffinityClientIP, - SessionAffinityConfig: nil, - }, - }, - "ClientIP is empty": { - Spec: v1.ServiceSpec{ - SessionAffinity: v1.ServiceAffinityClientIP, - SessionAffinityConfig: &v1.SessionAffinityConfig{ - ClientIP: nil, - }, - }, - }, - "TimeoutSeconds is empty": { - Spec: v1.ServiceSpec{ - SessionAffinity: v1.ServiceAffinityClientIP, - SessionAffinityConfig: &v1.SessionAffinityConfig{ - ClientIP: &v1.ClientIPConfig{ - TimeoutSeconds: nil, - }, - }, - }, - }, - } - for name, test := range testCases { - obj2 := roundTrip(t, runtime.Object(&test)) - svc2 := obj2.(*v1.Service) - if svc2.Spec.SessionAffinityConfig == nil || svc2.Spec.SessionAffinityConfig.ClientIP == nil || svc2.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds == nil { - t.Fatalf("Case: %s, unexpected empty SessionAffinityConfig/ClientIP/TimeoutSeconds when session affinity type: %s, got: %v", name, v1.ServiceAffinityClientIP, svc2.Spec.SessionAffinityConfig) - } - if *svc2.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds != v1.DefaultClientIPServiceAffinitySeconds { - t.Errorf("Case: %s, default TimeoutSeconds should be %d when session affinity type: %s, got: %d", name, v1.DefaultClientIPServiceAffinitySeconds, v1.ServiceAffinityClientIP, *svc2.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds) - } - } -} - -func TestSetDefaultSecretVolumeSource(t *testing.T) { - s := v1.PodSpec{} - s.Volumes = []v1.Volume{ - { - VolumeSource: v1.VolumeSource{ - Secret: &v1.SecretVolumeSource{}, - }, - }, - } - pod := &v1.Pod{ - Spec: s, - } - output := roundTrip(t, runtime.Object(pod)) - pod2 := output.(*v1.Pod) - defaultMode := pod2.Spec.Volumes[0].VolumeSource.Secret.DefaultMode - expectedMode := v1.SecretVolumeSourceDefaultMode - - if defaultMode == nil || *defaultMode != expectedMode { - t.Errorf("Expected secret DefaultMode %v, got %v", expectedMode, defaultMode) - } -} - -func TestSetDefaultConfigMapVolumeSource(t *testing.T) { - s := v1.PodSpec{} - s.Volumes = []v1.Volume{ - { - VolumeSource: v1.VolumeSource{ - ConfigMap: &v1.ConfigMapVolumeSource{}, - }, - }, - } - pod := &v1.Pod{ - Spec: s, - } - output := roundTrip(t, runtime.Object(pod)) - pod2 := output.(*v1.Pod) - defaultMode := pod2.Spec.Volumes[0].VolumeSource.ConfigMap.DefaultMode - expectedMode := v1.ConfigMapVolumeSourceDefaultMode - - if defaultMode == nil || *defaultMode != expectedMode { - t.Errorf("Expected v1.ConfigMap DefaultMode %v, got %v", expectedMode, defaultMode) - } -} - -func TestSetDefaultDownwardAPIVolumeSource(t *testing.T) { - s := v1.PodSpec{} - s.Volumes = []v1.Volume{ - { - VolumeSource: v1.VolumeSource{ - DownwardAPI: &v1.DownwardAPIVolumeSource{}, - }, - }, - } - pod := &v1.Pod{ - Spec: s, - } - output := roundTrip(t, runtime.Object(pod)) - pod2 := output.(*v1.Pod) - defaultMode := pod2.Spec.Volumes[0].VolumeSource.DownwardAPI.DefaultMode - expectedMode := v1.DownwardAPIVolumeSourceDefaultMode - - if defaultMode == nil || *defaultMode != expectedMode { - t.Errorf("Expected DownwardAPI DefaultMode %v, got %v", expectedMode, defaultMode) - } -} - -func TestSetDefaultProjectedVolumeSource(t *testing.T) { - s := v1.PodSpec{} - s.Volumes = []v1.Volume{ - { - VolumeSource: v1.VolumeSource{ - Projected: &v1.ProjectedVolumeSource{}, - }, - }, - } - pod := &v1.Pod{ - Spec: s, - } - output := roundTrip(t, runtime.Object(pod)) - pod2 := output.(*v1.Pod) - defaultMode := pod2.Spec.Volumes[0].VolumeSource.Projected.DefaultMode - expectedMode := v1.ProjectedVolumeSourceDefaultMode - - if defaultMode == nil || *defaultMode != expectedMode { - t.Errorf("Expected v1.ProjectedVolumeSource DefaultMode %v, got %v", expectedMode, defaultMode) - } -} - -func TestSetDefaultSecret(t *testing.T) { - s := &v1.Secret{} - obj2 := roundTrip(t, runtime.Object(s)) - s2 := obj2.(*v1.Secret) - - if s2.Type != v1.SecretTypeOpaque { - t.Errorf("Expected secret type %v, got %v", v1.SecretTypeOpaque, s2.Type) - } -} - -func TestSetDefaultPersistentVolume(t *testing.T) { - pv := &v1.PersistentVolume{} - obj2 := roundTrip(t, runtime.Object(pv)) - pv2 := obj2.(*v1.PersistentVolume) - - if pv2.Status.Phase != v1.VolumePending { - t.Errorf("Expected volume phase %v, got %v", v1.VolumePending, pv2.Status.Phase) - } - if pv2.Spec.PersistentVolumeReclaimPolicy != v1.PersistentVolumeReclaimRetain { - t.Errorf("Expected pv reclaim policy %v, got %v", v1.PersistentVolumeReclaimRetain, pv2.Spec.PersistentVolumeReclaimPolicy) - } - - // When feature gate is disabled, field should not be defaulted - defaultMode := v1.PersistentVolumeFilesystem - outputMode := pv2.Spec.VolumeMode - if outputMode != nil { - t.Errorf("Expected VolumeMode to not be defaulted, got: %+v", outputMode) - } - - // When feature gate is enabled, field should be defaulted - err := utilfeature.DefaultFeatureGate.Set("BlockVolume=true") - if err != nil { - t.Fatalf("Failed to enable feature gate for BlockVolume: %v", err) - } - obj3 := roundTrip(t, runtime.Object(pv)).(*v1.PersistentVolume) - outputMode3 := obj3.Spec.VolumeMode - - if outputMode3 == nil { - t.Errorf("Expected VolumeMode to be defaulted to: %+v, got: nil", defaultMode) - } else if *outputMode3 != defaultMode { - t.Errorf("Expected VolumeMode to be defaulted to: %+v, got: %+v", defaultMode, outputMode3) - } - - err = utilfeature.DefaultFeatureGate.Set("BlockVolume=false") - if err != nil { - t.Fatalf("Failed to disable feature gate for BlockVolume: %v", err) - } - -} - -func TestSetDefaultPersistentVolumeClaim(t *testing.T) { - pvc := &v1.PersistentVolumeClaim{} - obj2 := roundTrip(t, runtime.Object(pvc)) - pvc2 := obj2.(*v1.PersistentVolumeClaim) - - if pvc2.Status.Phase != v1.ClaimPending { - t.Errorf("Expected claim phase %v, got %v", v1.ClaimPending, pvc2.Status.Phase) - } - - // When feature gate is disabled, field should not be defaulted - defaultMode := v1.PersistentVolumeFilesystem - outputMode := pvc2.Spec.VolumeMode - if outputMode != nil { - t.Errorf("Expected VolumeMode to not be defaulted, got: %+v", outputMode) - } - - // When feature gate is enabled, field should be defaulted - err := utilfeature.DefaultFeatureGate.Set("BlockVolume=true") - if err != nil { - t.Fatalf("Failed to enable feature gate for BlockVolume: %v", err) - } - obj3 := roundTrip(t, runtime.Object(pvc)).(*v1.PersistentVolumeClaim) - outputMode3 := obj3.Spec.VolumeMode - - if outputMode3 == nil { - t.Errorf("Expected VolumeMode to be defaulted to: %+v, got: nil", defaultMode) - } else if *outputMode3 != defaultMode { - t.Errorf("Expected VolumeMode to be defaulted to: %+v, got: %+v", defaultMode, outputMode3) - } - - err = utilfeature.DefaultFeatureGate.Set("BlockVolume=false") - if err != nil { - t.Fatalf("Failed to disable feature gate for BlockVolume: %v", err) - } -} - -func TestSetDefaulEndpointsProtocol(t *testing.T) { - in := &v1.Endpoints{Subsets: []v1.EndpointSubset{ - {Ports: []v1.EndpointPort{{}, {Protocol: "UDP"}, {}}}, - }} - obj := roundTrip(t, runtime.Object(in)) - out := obj.(*v1.Endpoints) - - for i := range out.Subsets { - for j := range out.Subsets[i].Ports { - if in.Subsets[i].Ports[j].Protocol == "" { - if out.Subsets[i].Ports[j].Protocol != v1.ProtocolTCP { - t.Errorf("Expected protocol %s, got %s", v1.ProtocolTCP, out.Subsets[i].Ports[j].Protocol) - } - } else { - if out.Subsets[i].Ports[j].Protocol != in.Subsets[i].Ports[j].Protocol { - t.Errorf("Expected protocol %s, got %s", in.Subsets[i].Ports[j].Protocol, out.Subsets[i].Ports[j].Protocol) - } - } - } - } -} - -func TestSetDefaulServiceTargetPort(t *testing.T) { - in := &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{Port: 1234}}}} - obj := roundTrip(t, runtime.Object(in)) - out := obj.(*v1.Service) - if out.Spec.Ports[0].TargetPort != intstr.FromInt(1234) { - t.Errorf("Expected TargetPort to be defaulted, got %v", out.Spec.Ports[0].TargetPort) - } - - in = &v1.Service{Spec: v1.ServiceSpec{Ports: []v1.ServicePort{{Port: 1234, TargetPort: intstr.FromInt(5678)}}}} - obj = roundTrip(t, runtime.Object(in)) - out = obj.(*v1.Service) - if out.Spec.Ports[0].TargetPort != intstr.FromInt(5678) { - t.Errorf("Expected TargetPort to be unchanged, got %v", out.Spec.Ports[0].TargetPort) - } -} - -func TestSetDefaultServicePort(t *testing.T) { - // Unchanged if set. - in := &v1.Service{Spec: v1.ServiceSpec{ - Ports: []v1.ServicePort{ - {Protocol: "UDP", Port: 9376, TargetPort: intstr.FromString("p")}, - {Protocol: "UDP", Port: 8675, TargetPort: intstr.FromInt(309)}, - }, - }} - out := roundTrip(t, runtime.Object(in)).(*v1.Service) - if out.Spec.Ports[0].Protocol != v1.ProtocolUDP { - t.Errorf("Expected protocol %s, got %s", v1.ProtocolUDP, out.Spec.Ports[0].Protocol) - } - if out.Spec.Ports[0].TargetPort != intstr.FromString("p") { - t.Errorf("Expected port %v, got %v", in.Spec.Ports[0].Port, out.Spec.Ports[0].TargetPort) - } - if out.Spec.Ports[1].Protocol != v1.ProtocolUDP { - t.Errorf("Expected protocol %s, got %s", v1.ProtocolUDP, out.Spec.Ports[1].Protocol) - } - if out.Spec.Ports[1].TargetPort != intstr.FromInt(309) { - t.Errorf("Expected port %v, got %v", in.Spec.Ports[1].Port, out.Spec.Ports[1].TargetPort) - } - - // Defaulted. - in = &v1.Service{Spec: v1.ServiceSpec{ - Ports: []v1.ServicePort{ - {Protocol: "", Port: 9376, TargetPort: intstr.FromString("")}, - {Protocol: "", Port: 8675, TargetPort: intstr.FromInt(0)}, - }, - }} - out = roundTrip(t, runtime.Object(in)).(*v1.Service) - if out.Spec.Ports[0].Protocol != v1.ProtocolTCP { - t.Errorf("Expected protocol %s, got %s", v1.ProtocolTCP, out.Spec.Ports[0].Protocol) - } - if out.Spec.Ports[0].TargetPort != intstr.FromInt(int(in.Spec.Ports[0].Port)) { - t.Errorf("Expected port %v, got %v", in.Spec.Ports[0].Port, out.Spec.Ports[0].TargetPort) - } - if out.Spec.Ports[1].Protocol != v1.ProtocolTCP { - t.Errorf("Expected protocol %s, got %s", v1.ProtocolTCP, out.Spec.Ports[1].Protocol) - } - if out.Spec.Ports[1].TargetPort != intstr.FromInt(int(in.Spec.Ports[1].Port)) { - t.Errorf("Expected port %v, got %v", in.Spec.Ports[1].Port, out.Spec.Ports[1].TargetPort) - } -} - -func TestSetDefaulServiceExternalTraffic(t *testing.T) { - in := &v1.Service{} - obj := roundTrip(t, runtime.Object(in)) - out := obj.(*v1.Service) - if out.Spec.ExternalTrafficPolicy != "" { - t.Errorf("Expected ExternalTrafficPolicy to be empty, got %v", out.Spec.ExternalTrafficPolicy) - } - - in = &v1.Service{Spec: v1.ServiceSpec{Type: v1.ServiceTypeNodePort}} - obj = roundTrip(t, runtime.Object(in)) - out = obj.(*v1.Service) - if out.Spec.ExternalTrafficPolicy != v1.ServiceExternalTrafficPolicyTypeCluster { - t.Errorf("Expected ExternalTrafficPolicy to be %v, got %v", v1.ServiceExternalTrafficPolicyTypeCluster, out.Spec.ExternalTrafficPolicy) - } - - in = &v1.Service{Spec: v1.ServiceSpec{Type: v1.ServiceTypeLoadBalancer}} - obj = roundTrip(t, runtime.Object(in)) - out = obj.(*v1.Service) - if out.Spec.ExternalTrafficPolicy != v1.ServiceExternalTrafficPolicyTypeCluster { - t.Errorf("Expected ExternalTrafficPolicy to be %v, got %v", v1.ServiceExternalTrafficPolicyTypeCluster, out.Spec.ExternalTrafficPolicy) - } -} - -func TestSetDefaultNamespace(t *testing.T) { - s := &v1.Namespace{} - obj2 := roundTrip(t, runtime.Object(s)) - s2 := obj2.(*v1.Namespace) - - if s2.Status.Phase != v1.NamespaceActive { - t.Errorf("Expected phase %v, got %v", v1.NamespaceActive, s2.Status.Phase) - } -} - -func TestSetDefaultPodSpecHostNetwork(t *testing.T) { - portNum := int32(8080) - s := v1.PodSpec{} - s.HostNetwork = true - s.Containers = []v1.Container{ - { - Ports: []v1.ContainerPort{ - { - ContainerPort: portNum, - }, - }, - }, - } - s.InitContainers = []v1.Container{ - { - Ports: []v1.ContainerPort{ - { - ContainerPort: portNum, - }, - }, - }, - } - pod := &v1.Pod{ - Spec: s, - } - obj2 := roundTrip(t, runtime.Object(pod)) - pod2 := obj2.(*v1.Pod) - s2 := pod2.Spec - - hostPortNum := s2.Containers[0].Ports[0].HostPort - if hostPortNum != portNum { - t.Errorf("Expected container port to be defaulted, was made %d instead of %d", hostPortNum, portNum) - } - - hostPortNum = s2.InitContainers[0].Ports[0].HostPort - if hostPortNum != portNum { - t.Errorf("Expected container port to be defaulted, was made %d instead of %d", hostPortNum, portNum) - } -} - -func TestSetDefaultNodeExternalID(t *testing.T) { - name := "node0" - n := &v1.Node{} - n.Name = name - obj2 := roundTrip(t, runtime.Object(n)) - n2 := obj2.(*v1.Node) - if n2.Spec.ExternalID != name { - t.Errorf("Expected default External ID: %s, got: %s", name, n2.Spec.ExternalID) - } - if n2.Spec.ProviderID != "" { - t.Errorf("Expected empty default Cloud Provider ID, got: %s", n2.Spec.ProviderID) - } -} - -func TestSetDefaultNodeStatusAllocatable(t *testing.T) { - capacity := v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("1000m"), - v1.ResourceMemory: resource.MustParse("10G"), - } - allocatable := v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("500m"), - v1.ResourceMemory: resource.MustParse("5G"), - } - tests := []struct { - capacity v1.ResourceList - allocatable v1.ResourceList - expectedAllocatable v1.ResourceList - }{{ // Everything set, no defaulting. - capacity: capacity, - allocatable: allocatable, - expectedAllocatable: allocatable, - }, { // Allocatable set, no defaulting. - capacity: nil, - allocatable: allocatable, - expectedAllocatable: allocatable, - }, { // Capacity set, allocatable defaults to capacity. - capacity: capacity, - allocatable: nil, - expectedAllocatable: capacity, - }, { // Nothing set, allocatable "defaults" to capacity. - capacity: nil, - allocatable: nil, - expectedAllocatable: nil, - }} - - copyResourceList := func(rl v1.ResourceList) v1.ResourceList { - if rl == nil { - return nil - } - copy := make(v1.ResourceList, len(rl)) - for k, v := range rl { - copy[k] = *v.Copy() - } - return copy - } - - resourceListsEqual := func(a v1.ResourceList, b v1.ResourceList) bool { - if len(a) != len(b) { - return false - } - for k, v := range a { - vb, found := b[k] - if !found { - return false - } - if v.Cmp(vb) != 0 { - return false - } - } - return true - } - - for i, testcase := range tests { - node := v1.Node{ - Status: v1.NodeStatus{ - Capacity: copyResourceList(testcase.capacity), - Allocatable: copyResourceList(testcase.allocatable), - }, - } - node2 := roundTrip(t, runtime.Object(&node)).(*v1.Node) - actual := node2.Status.Allocatable - expected := testcase.expectedAllocatable - if !resourceListsEqual(expected, actual) { - t.Errorf("[%d] Expected v1.NodeStatus.Allocatable: %+v; Got: %+v", i, expected, actual) - } - } -} - -func TestSetDefaultObjectFieldSelectorAPIVersion(t *testing.T) { - s := v1.PodSpec{ - Containers: []v1.Container{ - { - Env: []v1.EnvVar{ - { - ValueFrom: &v1.EnvVarSource{ - FieldRef: &v1.ObjectFieldSelector{}, - }, - }, - }, - }, - }, - } - pod := &v1.Pod{ - Spec: s, - } - obj2 := roundTrip(t, runtime.Object(pod)) - pod2 := obj2.(*v1.Pod) - s2 := pod2.Spec - - apiVersion := s2.Containers[0].Env[0].ValueFrom.FieldRef.APIVersion - if apiVersion != "v1" { - t.Errorf("Expected default APIVersion v1, got: %v", apiVersion) - } -} - -func TestSetMinimumScalePod(t *testing.T) { - // verify we default if limits are specified (and that request=0 is preserved) - s := v1.PodSpec{} - s.Containers = []v1.Container{ - { - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceMemory: resource.MustParse("1n"), - }, - Limits: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("2n"), - }, - }, - }, - } - s.InitContainers = []v1.Container{ - { - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceMemory: resource.MustParse("1n"), - }, - Limits: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("2n"), - }, - }, - }, - } - pod := &v1.Pod{ - Spec: s, - } - corev1.SetObjectDefaults_Pod(pod) - - if expect := resource.MustParse("1m"); expect.Cmp(pod.Spec.Containers[0].Resources.Requests[v1.ResourceMemory]) != 0 { - t.Errorf("did not round resources: %#v", pod.Spec.Containers[0].Resources) - } - if expect := resource.MustParse("1m"); expect.Cmp(pod.Spec.InitContainers[0].Resources.Requests[v1.ResourceMemory]) != 0 { - t.Errorf("did not round resources: %#v", pod.Spec.InitContainers[0].Resources) - } -} - -func TestSetDefaultRequestsPod(t *testing.T) { - // verify we default if limits are specified (and that request=0 is preserved) - s := v1.PodSpec{} - s.Containers = []v1.Container{ - { - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceMemory: resource.MustParse("0"), - }, - Limits: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("100m"), - v1.ResourceMemory: resource.MustParse("1Gi"), - }, - }, - }, - } - s.InitContainers = []v1.Container{ - { - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceMemory: resource.MustParse("0"), - }, - Limits: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("100m"), - v1.ResourceMemory: resource.MustParse("1Gi"), - }, - }, - }, - } - pod := &v1.Pod{ - Spec: s, - } - output := roundTrip(t, runtime.Object(pod)) - pod2 := output.(*v1.Pod) - defaultRequest := pod2.Spec.Containers[0].Resources.Requests - if requestValue := defaultRequest[v1.ResourceCPU]; requestValue.String() != "100m" { - t.Errorf("Expected request cpu: %s, got: %s", "100m", requestValue.String()) - } - if requestValue := defaultRequest[v1.ResourceMemory]; requestValue.String() != "0" { - t.Errorf("Expected request memory: %s, got: %s", "0", requestValue.String()) - } - defaultRequest = pod2.Spec.InitContainers[0].Resources.Requests - if requestValue := defaultRequest[v1.ResourceCPU]; requestValue.String() != "100m" { - t.Errorf("Expected request cpu: %s, got: %s", "100m", requestValue.String()) - } - if requestValue := defaultRequest[v1.ResourceMemory]; requestValue.String() != "0" { - t.Errorf("Expected request memory: %s, got: %s", "0", requestValue.String()) - } - - // verify we do nothing if no limits are specified - s = v1.PodSpec{} - s.Containers = []v1.Container{{}} - s.InitContainers = []v1.Container{{}} - pod = &v1.Pod{ - Spec: s, - } - output = roundTrip(t, runtime.Object(pod)) - pod2 = output.(*v1.Pod) - defaultRequest = pod2.Spec.Containers[0].Resources.Requests - if requestValue := defaultRequest[v1.ResourceCPU]; requestValue.String() != "0" { - t.Errorf("Expected 0 request value, got: %s", requestValue.String()) - } - defaultRequest = pod2.Spec.InitContainers[0].Resources.Requests - if requestValue := defaultRequest[v1.ResourceCPU]; requestValue.String() != "0" { - t.Errorf("Expected 0 request value, got: %s", requestValue.String()) - } -} - -func TestDefaultRequestIsNotSetForReplicationController(t *testing.T) { - s := v1.PodSpec{} - s.Containers = []v1.Container{ - { - Resources: v1.ResourceRequirements{ - Limits: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("100m"), - }, - }, - }, - } - rc := &v1.ReplicationController{ - Spec: v1.ReplicationControllerSpec{ - Replicas: utilpointer.Int32Ptr(3), - Template: &v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "foo": "bar", - }, - }, - Spec: s, - }, - }, - } - output := roundTrip(t, runtime.Object(rc)) - rc2 := output.(*v1.ReplicationController) - defaultRequest := rc2.Spec.Template.Spec.Containers[0].Resources.Requests - requestValue := defaultRequest[v1.ResourceCPU] - if requestValue.String() != "0" { - t.Errorf("Expected 0 request value, got: %s", requestValue.String()) - } -} - -func TestSetDefaultLimitRangeItem(t *testing.T) { - limitRange := &v1.LimitRange{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test-defaults", - }, - Spec: v1.LimitRangeSpec{ - Limits: []v1.LimitRangeItem{{ - Type: v1.LimitTypeContainer, - Max: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("100m"), - }, - Min: v1.ResourceList{ - v1.ResourceMemory: resource.MustParse("100Mi"), - }, - Default: v1.ResourceList{}, - DefaultRequest: v1.ResourceList{}, - }}, - }, - } - - output := roundTrip(t, runtime.Object(limitRange)) - limitRange2 := output.(*v1.LimitRange) - defaultLimit := limitRange2.Spec.Limits[0].Default - defaultRequest := limitRange2.Spec.Limits[0].DefaultRequest - - // verify that default cpu was set to the max - defaultValue := defaultLimit[v1.ResourceCPU] - if defaultValue.String() != "100m" { - t.Errorf("Expected default cpu: %s, got: %s", "100m", defaultValue.String()) - } - // verify that default request was set to the limit - requestValue := defaultRequest[v1.ResourceCPU] - if requestValue.String() != "100m" { - t.Errorf("Expected request cpu: %s, got: %s", "100m", requestValue.String()) - } - // verify that if a min is provided, it will be the default if no limit is specified - requestMinValue := defaultRequest[v1.ResourceMemory] - if requestMinValue.String() != "100Mi" { - t.Errorf("Expected request memory: %s, got: %s", "100Mi", requestMinValue.String()) - } -} - -func TestSetDefaultProbe(t *testing.T) { - originalProbe := v1.Probe{} - expectedProbe := v1.Probe{ - InitialDelaySeconds: 0, - TimeoutSeconds: 1, - PeriodSeconds: 10, - SuccessThreshold: 1, - FailureThreshold: 3, - } - - pod := &v1.Pod{ - Spec: v1.PodSpec{ - Containers: []v1.Container{{LivenessProbe: &originalProbe}}, - }, - } - - output := roundTrip(t, runtime.Object(pod)).(*v1.Pod) - actualProbe := *output.Spec.Containers[0].LivenessProbe - if actualProbe != expectedProbe { - t.Errorf("Expected probe: %+v\ngot: %+v\n", expectedProbe, actualProbe) - } -} - -func TestSetDefaultSchedulerName(t *testing.T) { - pod := &v1.Pod{} - - output := roundTrip(t, runtime.Object(pod)).(*v1.Pod) - if output.Spec.SchedulerName != v1.DefaultSchedulerName { - t.Errorf("Expected scheduler name: %+v\ngot: %+v\n", v1.DefaultSchedulerName, output.Spec.SchedulerName) - } -} - -func TestSetDefaultHostPathVolumeSource(t *testing.T) { - s := v1.PodSpec{} - s.Volumes = []v1.Volume{ - { - VolumeSource: v1.VolumeSource{ - HostPath: &v1.HostPathVolumeSource{Path: "foo"}, - }, - }, - } - pod := &v1.Pod{ - Spec: s, - } - output := roundTrip(t, runtime.Object(pod)) - pod2 := output.(*v1.Pod) - defaultType := pod2.Spec.Volumes[0].VolumeSource.HostPath.Type - expectedType := v1.HostPathUnset - - if defaultType == nil || *defaultType != expectedType { - t.Errorf("Expected v1.HostPathVolumeSource default type %v, got %v", expectedType, defaultType) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/v1/helper/helpers_test.go b/vendor/k8s.io/kubernetes/pkg/apis/core/v1/helper/helpers_test.go deleted file mode 100644 index be1ecfaf93..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/v1/helper/helpers_test.go +++ /dev/null @@ -1,655 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package helper - -import ( - "fmt" - "reflect" - "testing" - - "k8s.io/api/core/v1" - apiequality "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" -) - -func TestIsDefaultNamespaceResource(t *testing.T) { - testCases := []struct { - resourceName v1.ResourceName - expectVal bool - }{ - { - resourceName: "pod.alpha.kubernetes.io/opaque-int-resource-foo", - expectVal: true, - }, - { - resourceName: "kubernetes.io/resource-foo", - expectVal: true, - }, - { - resourceName: "foo", - expectVal: true, - }, - { - resourceName: "a/b", - expectVal: false, - }, - { - resourceName: "", - expectVal: true, - }, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("resourceName input=%s, expected value=%v", tc.resourceName, tc.expectVal), func(t *testing.T) { - t.Parallel() - v := IsDefaultNamespaceResource(tc.resourceName) - if v != tc.expectVal { - t.Errorf("Got %v but expected %v", v, tc.expectVal) - } - }) - } -} - -func TestHugePageSizeFromResourceName(t *testing.T) { - expected100m, _ := resource.ParseQuantity("100m") - testCases := []struct { - resourceName v1.ResourceName - expectVal resource.Quantity - expectErr bool - }{ - { - resourceName: "pod.alpha.kubernetes.io/opaque-int-resource-foo", - expectVal: resource.Quantity{}, - expectErr: true, - }, - { - resourceName: "hugepages-", - expectVal: resource.Quantity{}, - expectErr: true, - }, - { - resourceName: "hugepages-100m", - expectVal: expected100m, - expectErr: false, - }, - { - resourceName: "", - expectVal: resource.Quantity{}, - expectErr: true, - }, - } - - for i, tc := range testCases { - t.Run(fmt.Sprintf("resourceName input=%s, expected value=%v", tc.resourceName, tc.expectVal), func(t *testing.T) { - t.Parallel() - v, err := HugePageSizeFromResourceName(tc.resourceName) - if err == nil && tc.expectErr { - t.Errorf("[%v]expected error but got none.", i) - } - if err != nil && !tc.expectErr { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } - if v != tc.expectVal { - t.Errorf("Got %v but expected %v", v, tc.expectVal) - } - }) - } -} - -func TestIsOvercommitAllowed(t *testing.T) { - testCases := []struct { - resourceName v1.ResourceName - expectVal bool - }{ - { - resourceName: "pod.alpha.kubernetes.io/opaque-int-resource-foo", - expectVal: true, - }, - { - resourceName: "kubernetes.io/resource-foo", - expectVal: true, - }, - { - resourceName: "alpha.kubernetes.io/nvidia-gpu", - expectVal: false, - }, - { - resourceName: "hugepages-100m", - expectVal: false, - }, - { - resourceName: "", - expectVal: true, - }, - } - - for _, tc := range testCases { - t.Run(fmt.Sprintf("resourceName input=%s, expected value=%v", tc.resourceName, tc.expectVal), func(t *testing.T) { - t.Parallel() - v := IsOvercommitAllowed(tc.resourceName) - if v != tc.expectVal { - t.Errorf("Got %v but expected %v", v, tc.expectVal) - } - }) - } -} - -func TestAddToNodeAddresses(t *testing.T) { - testCases := []struct { - existing []v1.NodeAddress - toAdd []v1.NodeAddress - expected []v1.NodeAddress - }{ - { - existing: []v1.NodeAddress{}, - toAdd: []v1.NodeAddress{}, - expected: []v1.NodeAddress{}, - }, - { - existing: []v1.NodeAddress{}, - toAdd: []v1.NodeAddress{ - {Type: v1.NodeExternalIP, Address: "1.1.1.1"}, - {Type: v1.NodeHostName, Address: "localhost"}, - }, - expected: []v1.NodeAddress{ - {Type: v1.NodeExternalIP, Address: "1.1.1.1"}, - {Type: v1.NodeHostName, Address: "localhost"}, - }, - }, - { - existing: []v1.NodeAddress{}, - toAdd: []v1.NodeAddress{ - {Type: v1.NodeExternalIP, Address: "1.1.1.1"}, - {Type: v1.NodeExternalIP, Address: "1.1.1.1"}, - }, - expected: []v1.NodeAddress{ - {Type: v1.NodeExternalIP, Address: "1.1.1.1"}, - }, - }, - { - existing: []v1.NodeAddress{ - {Type: v1.NodeExternalIP, Address: "1.1.1.1"}, - {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, - }, - toAdd: []v1.NodeAddress{ - {Type: v1.NodeExternalIP, Address: "1.1.1.1"}, - {Type: v1.NodeHostName, Address: "localhost"}, - }, - expected: []v1.NodeAddress{ - {Type: v1.NodeExternalIP, Address: "1.1.1.1"}, - {Type: v1.NodeInternalIP, Address: "10.1.1.1"}, - {Type: v1.NodeHostName, Address: "localhost"}, - }, - }, - } - - for i, tc := range testCases { - AddToNodeAddresses(&tc.existing, tc.toAdd...) - if !apiequality.Semantic.DeepEqual(tc.expected, tc.existing) { - t.Errorf("case[%d], expected: %v, got: %v", i, tc.expected, tc.existing) - } - } -} - -func TestGetAccessModesFromString(t *testing.T) { - modes := GetAccessModesFromString("ROX") - if !containsAccessMode(modes, v1.ReadOnlyMany) { - t.Errorf("Expected mode %s, but got %+v", v1.ReadOnlyMany, modes) - } - - modes = GetAccessModesFromString("ROX,RWX") - if !containsAccessMode(modes, v1.ReadOnlyMany) { - t.Errorf("Expected mode %s, but got %+v", v1.ReadOnlyMany, modes) - } - if !containsAccessMode(modes, v1.ReadWriteMany) { - t.Errorf("Expected mode %s, but got %+v", v1.ReadWriteMany, modes) - } - - modes = GetAccessModesFromString("RWO,ROX,RWX") - if !containsAccessMode(modes, v1.ReadOnlyMany) { - t.Errorf("Expected mode %s, but got %+v", v1.ReadOnlyMany, modes) - } - if !containsAccessMode(modes, v1.ReadWriteMany) { - t.Errorf("Expected mode %s, but got %+v", v1.ReadWriteMany, modes) - } -} - -func TestRemoveDuplicateAccessModes(t *testing.T) { - modes := []v1.PersistentVolumeAccessMode{ - v1.ReadWriteOnce, v1.ReadOnlyMany, v1.ReadOnlyMany, v1.ReadOnlyMany, - } - modes = removeDuplicateAccessModes(modes) - if len(modes) != 2 { - t.Errorf("Expected 2 distinct modes in set but found %v", len(modes)) - } -} - -func TestNodeSelectorRequirementsAsSelector(t *testing.T) { - matchExpressions := []v1.NodeSelectorRequirement{{ - Key: "foo", - Operator: v1.NodeSelectorOpIn, - Values: []string{"bar", "baz"}, - }} - mustParse := func(s string) labels.Selector { - out, e := labels.Parse(s) - if e != nil { - panic(e) - } - return out - } - tc := []struct { - in []v1.NodeSelectorRequirement - out labels.Selector - expectErr bool - }{ - {in: nil, out: labels.Nothing()}, - {in: []v1.NodeSelectorRequirement{}, out: labels.Nothing()}, - { - in: matchExpressions, - out: mustParse("foo in (baz,bar)"), - }, - { - in: []v1.NodeSelectorRequirement{{ - Key: "foo", - Operator: v1.NodeSelectorOpExists, - Values: []string{"bar", "baz"}, - }}, - expectErr: true, - }, - { - in: []v1.NodeSelectorRequirement{{ - Key: "foo", - Operator: v1.NodeSelectorOpGt, - Values: []string{"1"}, - }}, - out: mustParse("foo>1"), - }, - { - in: []v1.NodeSelectorRequirement{{ - Key: "bar", - Operator: v1.NodeSelectorOpLt, - Values: []string{"7"}, - }}, - out: mustParse("bar<7"), - }, - } - - for i, tc := range tc { - out, err := NodeSelectorRequirementsAsSelector(tc.in) - if err == nil && tc.expectErr { - t.Errorf("[%v]expected error but got none.", i) - } - if err != nil && !tc.expectErr { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } - if !reflect.DeepEqual(out, tc.out) { - t.Errorf("[%v]expected:\n\t%+v\nbut got:\n\t%+v", i, tc.out, out) - } - } -} - -func TestTolerationsTolerateTaintsWithFilter(t *testing.T) { - testCases := []struct { - description string - tolerations []v1.Toleration - taints []v1.Taint - applyFilter taintsFilterFunc - expectTolerated bool - }{ - { - description: "empty tolerations tolerate empty taints", - tolerations: []v1.Toleration{}, - taints: []v1.Taint{}, - applyFilter: func(t *v1.Taint) bool { return true }, - expectTolerated: true, - }, - { - description: "non-empty tolerations tolerate empty taints", - tolerations: []v1.Toleration{ - { - Key: "foo", - Operator: "Exists", - Effect: v1.TaintEffectNoSchedule, - }, - }, - taints: []v1.Taint{}, - applyFilter: func(t *v1.Taint) bool { return true }, - expectTolerated: true, - }, - { - description: "tolerations match all taints, expect tolerated", - tolerations: []v1.Toleration{ - { - Key: "foo", - Operator: "Exists", - Effect: v1.TaintEffectNoSchedule, - }, - }, - taints: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - applyFilter: func(t *v1.Taint) bool { return true }, - expectTolerated: true, - }, - { - description: "tolerations don't match taints, but no taints apply to the filter, expect tolerated", - tolerations: []v1.Toleration{ - { - Key: "foo", - Operator: "Exists", - Effect: v1.TaintEffectNoSchedule, - }, - }, - taints: []v1.Taint{ - { - Key: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - }, - applyFilter: func(t *v1.Taint) bool { return false }, - expectTolerated: true, - }, - { - description: "no filterFunc indicated, means all taints apply to the filter, tolerations don't match taints, expect untolerated", - tolerations: []v1.Toleration{ - { - Key: "foo", - Operator: "Exists", - Effect: v1.TaintEffectNoSchedule, - }, - }, - taints: []v1.Taint{ - { - Key: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - }, - applyFilter: nil, - expectTolerated: false, - }, - { - description: "tolerations match taints, expect tolerated", - tolerations: []v1.Toleration{ - { - Key: "foo", - Operator: "Exists", - Effect: v1.TaintEffectNoExecute, - }, - }, - taints: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoExecute, - }, - { - Key: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - }, - applyFilter: func(t *v1.Taint) bool { return t.Effect == v1.TaintEffectNoExecute }, - expectTolerated: true, - }, - } - - for _, tc := range testCases { - if tc.expectTolerated != TolerationsTolerateTaintsWithFilter(tc.tolerations, tc.taints, tc.applyFilter) { - filteredTaints := []v1.Taint{} - for _, taint := range tc.taints { - if tc.applyFilter != nil && !tc.applyFilter(&taint) { - continue - } - filteredTaints = append(filteredTaints, taint) - } - t.Errorf("[%s] expect tolerations %+v tolerate filtered taints %+v in taints %+v", tc.description, tc.tolerations, filteredTaints, tc.taints) - } - } -} - -func TestGetAvoidPodsFromNode(t *testing.T) { - controllerFlag := true - testCases := []struct { - node *v1.Node - expectValue v1.AvoidPods - expectErr bool - }{ - { - node: &v1.Node{}, - expectValue: v1.AvoidPods{}, - expectErr: false, - }, - { - node: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - v1.PreferAvoidPodsAnnotationKey: ` - { - "preferAvoidPods": [ - { - "podSignature": { - "podController": { - "apiVersion": "v1", - "kind": "ReplicationController", - "name": "foo", - "uid": "abcdef123456", - "controller": true - } - }, - "reason": "some reason", - "message": "some message" - } - ] - }`, - }, - }, - }, - expectValue: v1.AvoidPods{ - PreferAvoidPods: []v1.PreferAvoidPodsEntry{ - { - PodSignature: v1.PodSignature{ - PodController: &metav1.OwnerReference{ - APIVersion: "v1", - Kind: "ReplicationController", - Name: "foo", - UID: "abcdef123456", - Controller: &controllerFlag, - }, - }, - Reason: "some reason", - Message: "some message", - }, - }, - }, - expectErr: false, - }, - { - node: &v1.Node{ - // Missing end symbol of "podController" and "podSignature" - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - v1.PreferAvoidPodsAnnotationKey: ` - { - "preferAvoidPods": [ - { - "podSignature": { - "podController": { - "kind": "ReplicationController", - "apiVersion": "v1" - "reason": "some reason", - "message": "some message" - } - ] - }`, - }, - }, - }, - expectValue: v1.AvoidPods{}, - expectErr: true, - }, - } - - for i, tc := range testCases { - v, err := GetAvoidPodsFromNodeAnnotations(tc.node.Annotations) - if err == nil && tc.expectErr { - t.Errorf("[%v]expected error but got none.", i) - } - if err != nil && !tc.expectErr { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } - if !reflect.DeepEqual(tc.expectValue, v) { - t.Errorf("[%v]expect value %v but got %v with %v", i, tc.expectValue, v, v.PreferAvoidPods[0].PodSignature.PodController.Controller) - } - } -} - -func TestSysctlsFromPodAnnotation(t *testing.T) { - type Test struct { - annotation string - expectValue []v1.Sysctl - expectErr bool - } - for i, test := range []Test{ - { - annotation: "", - expectValue: nil, - }, - { - annotation: "foo.bar", - expectErr: true, - }, - { - annotation: "=123", - expectErr: true, - }, - { - annotation: "foo.bar=", - expectValue: []v1.Sysctl{{Name: "foo.bar", Value: ""}}, - }, - { - annotation: "foo.bar=42", - expectValue: []v1.Sysctl{{Name: "foo.bar", Value: "42"}}, - }, - { - annotation: "foo.bar=42,", - expectErr: true, - }, - { - annotation: "foo.bar=42,abc.def=1", - expectValue: []v1.Sysctl{{Name: "foo.bar", Value: "42"}, {Name: "abc.def", Value: "1"}}, - }, - } { - sysctls, err := SysctlsFromPodAnnotation(test.annotation) - if test.expectErr && err == nil { - t.Errorf("[%v]expected error but got none", i) - } else if !test.expectErr && err != nil { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } else if !reflect.DeepEqual(sysctls, test.expectValue) { - t.Errorf("[%v]expect value %v but got %v", i, test.expectValue, sysctls) - } - } -} - -// TODO: remove when alpha support for topology constraints is removed -func TestGetNodeAffinityFromAnnotations(t *testing.T) { - testCases := []struct { - annotations map[string]string - expectErr bool - }{ - { - annotations: nil, - expectErr: false, - }, - { - annotations: map[string]string{}, - expectErr: false, - }, - { - annotations: map[string]string{ - v1.AlphaStorageNodeAffinityAnnotation: `{ - "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [ - { "matchExpressions": [ - { "key": "test-key1", - "operator": "In", - "values": ["test-value1", "test-value2"] - }, - { "key": "test-key2", - "operator": "In", - "values": ["test-value1", "test-value2"] - } - ]} - ]} - }`, - }, - expectErr: false, - }, - { - annotations: map[string]string{ - v1.AlphaStorageNodeAffinityAnnotation: `[{ - "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": [ - { "matchExpressions": [ - { "key": "test-key1", - "operator": "In", - "values": ["test-value1", "test-value2"] - }, - { "key": "test-key2", - "operator": "In", - "values": ["test-value1", "test-value2"] - } - ]} - ]} - }]`, - }, - expectErr: true, - }, - { - annotations: map[string]string{ - v1.AlphaStorageNodeAffinityAnnotation: `{ - "requiredDuringSchedulingIgnoredDuringExecution": { - "nodeSelectorTerms": - "matchExpressions": [ - { "key": "test-key1", - "operator": "In", - "values": ["test-value1", "test-value2"] - }, - { "key": "test-key2", - "operator": "In", - "values": ["test-value1", "test-value2"] - } - ]} - } - }`, - }, - expectErr: true, - }, - } - - for i, tc := range testCases { - _, err := GetStorageNodeAffinityFromAnnotation(tc.annotations) - if err == nil && tc.expectErr { - t.Errorf("[%v]expected error but got none.", i) - } - if err != nil && !tc.expectErr { - t.Errorf("[%v]did not expect error but got: %v", i, err) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/validation/events_test.go b/vendor/k8s.io/kubernetes/pkg/apis/core/validation/events_test.go deleted file mode 100644 index 1db7463f97..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/validation/events_test.go +++ /dev/null @@ -1,392 +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 validation - -import ( - "testing" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/kubernetes/pkg/apis/core" -) - -func TestValidateEvent(t *testing.T) { - table := []struct { - *core.Event - valid bool - }{ - { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test1", - Namespace: "foo", - }, - InvolvedObject: core.ObjectReference{ - Namespace: "bar", - Kind: "Pod", - }, - }, - false, - }, { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test2", - Namespace: "aoeu-_-aoeu", - }, - InvolvedObject: core.ObjectReference{ - Namespace: "aoeu-_-aoeu", - Kind: "Pod", - }, - }, - false, - }, { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test3", - Namespace: metav1.NamespaceDefault, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "v1", - Kind: "Node", - }, - }, - true, - }, { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test4", - Namespace: metav1.NamespaceDefault, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "v1", - Kind: "Namespace", - }, - }, - true, - }, { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test5", - Namespace: metav1.NamespaceDefault, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "extensions/v1beta1", - Kind: "NoKind", - Namespace: metav1.NamespaceDefault, - }, - }, - true, - }, { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test6", - Namespace: metav1.NamespaceDefault, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "extensions/v1beta1", - Kind: "Job", - Namespace: "foo", - }, - }, - false, - }, { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test7", - Namespace: metav1.NamespaceDefault, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "extensions/v1beta1", - Kind: "Job", - Namespace: metav1.NamespaceDefault, - }, - }, - true, - }, { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test8", - Namespace: metav1.NamespaceDefault, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "other/v1beta1", - Kind: "Job", - Namespace: "foo", - }, - }, - false, - }, { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test9", - Namespace: "foo", - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "other/v1beta1", - Kind: "Job", - Namespace: "foo", - }, - }, - true, - }, { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test10", - Namespace: metav1.NamespaceDefault, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "extensions", - Kind: "Job", - Namespace: "foo", - }, - }, - false, - }, { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test11", - Namespace: "foo", - }, - InvolvedObject: core.ObjectReference{ - // must register in v1beta1 to be true - APIVersion: "extensions/v1beta1", - Kind: "Job", - Namespace: "foo", - }, - }, - true, - }, - { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test12", - Namespace: "foo", - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "other/v1beta1", - Kind: "FooBar", - Namespace: "bar", - }, - }, - false, - }, - { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test13", - Namespace: "", - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "other/v1beta1", - Kind: "FooBar", - Namespace: "bar", - }, - }, - false, - }, - { - &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test14", - Namespace: "foo", - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "other/v1beta1", - Kind: "FooBar", - Namespace: "", - }, - }, - false, - }, - } - - for _, item := range table { - if e, a := item.valid, len(ValidateEvent(item.Event)) == 0; e != a { - t.Errorf("%v: expected %v, got %v: %v", item.Event.Name, e, a, ValidateEvent(item.Event)) - } - } -} - -func TestValidateNewEvent(t *testing.T) { - someTime := metav1.MicroTime{Time: time.Unix(1505828956, 0)} - table := []struct { - *core.Event - valid bool - msg string - }{ - { - Event: &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test", - Namespace: metav1.NamespaceDefault, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "v1", - Kind: "Node", - }, - EventTime: someTime, - }, - valid: false, - msg: "Old Event with EventTime should trigger new validation and fail", - }, - { - Event: &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test", - Namespace: metav1.NamespaceSystem, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "v1", - Kind: "Node", - }, - EventTime: someTime, - ReportingController: "k8s.io/my-controller", - ReportingInstance: "node-xyz", - Action: "Do", - Reason: "Because", - }, - valid: true, - msg: "Valid new Event", - }, - { - Event: &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test", - Namespace: metav1.NamespaceSystem, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "v1", - Kind: "Node", - }, - EventTime: someTime, - ReportingController: "my-contr@ller", - ReportingInstance: "node-xyz", - Action: "Do", - Reason: "Because", - }, - valid: false, - msg: "not qualified reportingController", - }, - { - Event: &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test", - Namespace: metav1.NamespaceSystem, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "v1", - Kind: "Node", - }, - EventTime: someTime, - ReportingController: "k8s.io/my-controller", - ReportingInstance: "node-xyzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", - Action: "Do", - Reason: "Because", - }, - valid: false, - msg: "too long reporting instance", - }, - { - Event: &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test", - Namespace: metav1.NamespaceSystem, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "v1", - Kind: "Node", - }, - EventTime: someTime, - ReportingController: "k8s.io/my-controller", - ReportingInstance: "node-xyz", - Action: "Do", - }, - valid: false, - msg: "missing reason", - }, - { - Event: &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test", - Namespace: metav1.NamespaceSystem, - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "v1", - Kind: "Node", - }, - EventTime: someTime, - ReportingController: "k8s.io/my-controller", - ReportingInstance: "node-xyz", - Reason: "Because", - }, - valid: false, - msg: "missing action", - }, - { - Event: &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test", - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "v1", - Kind: "Node", - }, - EventTime: someTime, - ReportingController: "k8s.io/my-controller", - ReportingInstance: "node-xyz", - Reason: "Because", - }, - valid: false, - msg: "missing namespace", - }, - { - Event: &core.Event{ - ObjectMeta: metav1.ObjectMeta{ - Name: "test", - }, - InvolvedObject: core.ObjectReference{ - APIVersion: "v1", - Kind: "Node", - }, - EventTime: someTime, - ReportingController: "k8s.io/my-controller", - ReportingInstance: "node-xyz", - Action: "Do", - Reason: "Because", - Message: `zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz -zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz -zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz -zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz -zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz -zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz -zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz -zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz -zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz -zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz -zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz`, - }, - valid: false, - msg: "too long message", - }, - } - - for _, item := range table { - if e, a := item.valid, len(ValidateEvent(item.Event)) == 0; e != a { - t.Errorf("%v: expected %v, got %v: %v", item.msg, e, a, ValidateEvent(item.Event)) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/validation/validation.go b/vendor/k8s.io/kubernetes/pkg/apis/core/validation/validation.go index 5b54d6fe64..8d12dad078 100644 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/validation/validation.go +++ b/vendor/k8s.io/kubernetes/pkg/apis/core/validation/validation.go @@ -1140,7 +1140,7 @@ func validateMountPropagation(mountPropagation *core.MountPropagationMode, conta return allErrs } - supportedMountPropagations := sets.NewString(string(core.MountPropagationBidirectional), string(core.MountPropagationHostToContainer)) + supportedMountPropagations := sets.NewString(string(core.MountPropagationBidirectional), string(core.MountPropagationHostToContainer), string(core.MountPropagationNone)) if !supportedMountPropagations.Has(string(*mountPropagation)) { allErrs = append(allErrs, field.NotSupported(fldPath, *mountPropagation, supportedMountPropagations.List())) } @@ -1383,9 +1383,6 @@ func validateLocalVolumeSource(ls *core.LocalVolumeSource, fldPath *field.Path) return allErrs } - if !path.IsAbs(ls.Path) { - allErrs = append(allErrs, field.Invalid(fldPath, ls.Path, "must be an absolute path")) - } allErrs = append(allErrs, validatePathNoBacksteps(ls.Path, fldPath.Child("path"))...) return allErrs } @@ -3017,9 +3014,6 @@ func ValidateNodeSelectorRequirement(rq core.NodeSelectorRequirement, fldPath *f func ValidateNodeSelectorTerm(term core.NodeSelectorTerm, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} - if len(term.MatchExpressions) == 0 { - return append(allErrs, field.Required(fldPath.Child("matchExpressions"), "must have at least one node selector requirement")) - } for j, req := range term.MatchExpressions { allErrs = append(allErrs, ValidateNodeSelectorRequirement(req, fldPath.Child("matchExpressions").Index(j))...) } diff --git a/vendor/k8s.io/kubernetes/pkg/apis/core/validation/validation_test.go b/vendor/k8s.io/kubernetes/pkg/apis/core/validation/validation_test.go deleted file mode 100644 index a48c04f7c5..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/core/validation/validation_test.go +++ /dev/null @@ -1,12688 +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 validation - -import ( - "bytes" - "fmt" - "math" - "reflect" - "strings" - "testing" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/apimachinery/pkg/util/validation" - "k8s.io/apimachinery/pkg/util/validation/field" - utilfeature "k8s.io/apiserver/pkg/util/feature" - utilfeaturetesting "k8s.io/apiserver/pkg/util/feature/testing" - "k8s.io/kubernetes/pkg/api/legacyscheme" - _ "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/apis/core" - "k8s.io/kubernetes/pkg/apis/core/helper" - "k8s.io/kubernetes/pkg/capabilities" - "k8s.io/kubernetes/pkg/features" - "k8s.io/kubernetes/pkg/security/apparmor" -) - -const ( - dnsLabelErrMsg = "a DNS-1123 label must consist of" - dnsSubdomainLabelErrMsg = "a DNS-1123 subdomain" - envVarNameErrMsg = "a valid environment variable name must consist of" -) - -func newHostPathType(pathType string) *core.HostPathType { - hostPathType := new(core.HostPathType) - *hostPathType = core.HostPathType(pathType) - return hostPathType -} - -func testVolume(name string, namespace string, spec core.PersistentVolumeSpec) *core.PersistentVolume { - objMeta := metav1.ObjectMeta{Name: name} - if namespace != "" { - objMeta.Namespace = namespace - } - - return &core.PersistentVolume{ - ObjectMeta: objMeta, - Spec: spec, - } -} - -func testVolumeWithAlphaNodeAffinity(t *testing.T, name string, namespace string, affinity *core.NodeAffinity, spec core.PersistentVolumeSpec) *core.PersistentVolume { - objMeta := metav1.ObjectMeta{Name: name} - if namespace != "" { - objMeta.Namespace = namespace - } - - objMeta.Annotations = map[string]string{} - err := helper.StorageNodeAffinityToAlphaAnnotation(objMeta.Annotations, affinity) - if err != nil { - t.Fatalf("Failed to get node affinity annotation: %v", err) - } - - return &core.PersistentVolume{ - ObjectMeta: objMeta, - Spec: spec, - } -} - -func TestValidatePersistentVolumes(t *testing.T) { - validMode := core.PersistentVolumeFilesystem - scenarios := map[string]struct { - isExpectedFailure bool - volume *core.PersistentVolume - }{ - "good-volume": { - isExpectedFailure: false, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }), - }, - "good-volume-with-capacity-unit": { - isExpectedFailure: false, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10Gi"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }), - }, - "good-volume-without-capacity-unit": { - isExpectedFailure: false, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }), - }, - "good-volume-with-storage-class": { - isExpectedFailure: false, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - StorageClassName: "valid", - }), - }, - "good-volume-with-retain-policy": { - isExpectedFailure: false, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - PersistentVolumeReclaimPolicy: core.PersistentVolumeReclaimRetain, - }), - }, - "invalid-accessmode": { - isExpectedFailure: true, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{"fakemode"}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }), - }, - "invalid-reclaimpolicy": { - isExpectedFailure: true, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - PersistentVolumeReclaimPolicy: "fakeReclaimPolicy", - }), - }, - "unexpected-namespace": { - isExpectedFailure: true, - volume: testVolume("foo", "unexpected-namespace", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }), - }, - "missing-volume-source": { - isExpectedFailure: true, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - }), - }, - "bad-name": { - isExpectedFailure: true, - volume: testVolume("123*Bad(Name", "unexpected-namespace", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }), - }, - "missing-name": { - isExpectedFailure: true, - volume: testVolume("", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }), - }, - "missing-capacity": { - isExpectedFailure: true, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }), - }, - "bad-volume-zero-capacity": { - isExpectedFailure: true, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("0"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }), - }, - "missing-accessmodes": { - isExpectedFailure: true, - volume: testVolume("goodname", "missing-accessmodes", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }), - }, - "too-many-sources": { - isExpectedFailure: true, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("5G"), - }, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - GCEPersistentDisk: &core.GCEPersistentDiskVolumeSource{PDName: "foo", FSType: "ext4"}, - }, - }), - }, - "host mount of / with recycle reclaim policy": { - isExpectedFailure: true, - volume: testVolume("bad-recycle-do-not-want", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - PersistentVolumeReclaimPolicy: core.PersistentVolumeReclaimRecycle, - }), - }, - "host mount of / with recycle reclaim policy 2": { - isExpectedFailure: true, - volume: testVolume("bad-recycle-do-not-want", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/a/..", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - PersistentVolumeReclaimPolicy: core.PersistentVolumeReclaimRecycle, - }), - }, - "invalid-storage-class-name": { - isExpectedFailure: true, - volume: testVolume("invalid-storage-class-name", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - StorageClassName: "-invalid-", - }), - }, - // VolumeMode alpha feature disabled - // TODO: remove when no longer alpha - "alpha disabled valid volume mode": { - isExpectedFailure: true, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - StorageClassName: "valid", - VolumeMode: &validMode, - }), - }, - "bad-hostpath-volume-backsteps": { - isExpectedFailure: true, - volume: testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo/..", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - StorageClassName: "backstep-hostpath", - }), - }, - "volume-node-affinity": { - isExpectedFailure: false, - volume: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")), - }, - "volume-empty-node-affinity": { - isExpectedFailure: true, - volume: testVolumeWithNodeAffinity(&core.VolumeNodeAffinity{}), - }, - "volume-bad-node-affinity": { - isExpectedFailure: true, - volume: testVolumeWithNodeAffinity( - &core.VolumeNodeAffinity{ - Required: &core.NodeSelector{ - NodeSelectorTerms: []core.NodeSelectorTerm{ - { - MatchExpressions: []core.NodeSelectorRequirement{ - { - Operator: core.NodeSelectorOpIn, - Values: []string{"test-label-value"}, - }, - }, - }, - }, - }, - }), - }, - } - - for name, scenario := range scenarios { - errs := ValidatePersistentVolume(scenario.volume) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } - -} - -func TestValidatePersistentVolumeSourceUpdate(t *testing.T) { - validVolume := testVolume("foo", "", core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("1G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - StorageClassName: "valid", - }) - validPvSourceNoUpdate := validVolume.DeepCopy() - invalidPvSourceUpdateType := validVolume.DeepCopy() - invalidPvSourceUpdateType.Spec.PersistentVolumeSource = core.PersistentVolumeSource{ - FlexVolume: &core.FlexPersistentVolumeSource{ - Driver: "kubernetes.io/blue", - FSType: "ext4", - }, - } - invalidPvSourceUpdateDeep := validVolume.DeepCopy() - invalidPvSourceUpdateDeep.Spec.PersistentVolumeSource = core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/updated", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - } - scenarios := map[string]struct { - isExpectedFailure bool - oldVolume *core.PersistentVolume - newVolume *core.PersistentVolume - }{ - "condition-no-update": { - isExpectedFailure: false, - oldVolume: validVolume, - newVolume: validPvSourceNoUpdate, - }, - "condition-update-source-type": { - isExpectedFailure: true, - oldVolume: validVolume, - newVolume: invalidPvSourceUpdateType, - }, - "condition-update-source-deep": { - isExpectedFailure: true, - oldVolume: validVolume, - newVolume: invalidPvSourceUpdateDeep, - }, - } - for name, scenario := range scenarios { - errs := ValidatePersistentVolumeUpdate(scenario.newVolume, scenario.oldVolume) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } -} - -func testLocalVolume(path string, affinity *core.VolumeNodeAffinity) core.PersistentVolumeSpec { - return core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - Local: &core.LocalVolumeSource{ - Path: path, - }, - }, - NodeAffinity: affinity, - StorageClassName: "test-storage-class", - } -} - -func TestValidateLocalVolumes(t *testing.T) { - scenarios := map[string]struct { - isExpectedFailure bool - volume *core.PersistentVolume - }{ - "alpha valid local volume": { - isExpectedFailure: false, - volume: testVolumeWithAlphaNodeAffinity( - t, - "valid-local-volume", - "", - &core.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{ - NodeSelectorTerms: []core.NodeSelectorTerm{ - { - MatchExpressions: []core.NodeSelectorRequirement{ - { - Key: "test-label-key", - Operator: core.NodeSelectorOpIn, - Values: []string{"test-label-value"}, - }, - }, - }, - }, - }, - }, - testLocalVolume("/foo", nil)), - }, - "alpha invalid local volume nil annotations": { - isExpectedFailure: true, - volume: testVolume( - "invalid-local-volume-nil-annotations", - "", - testLocalVolume("/foo", nil)), - }, - "alpha invalid local volume empty affinity": { - isExpectedFailure: true, - volume: testVolumeWithAlphaNodeAffinity( - t, - "invalid-local-volume-empty-affinity", - "", - &core.NodeAffinity{}, - testLocalVolume("/foo", nil)), - }, - "alpha invalid local volume preferred affinity": { - isExpectedFailure: true, - volume: testVolumeWithAlphaNodeAffinity( - t, - "invalid-local-volume-preferred-affinity", - "", - &core.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{ - NodeSelectorTerms: []core.NodeSelectorTerm{ - { - MatchExpressions: []core.NodeSelectorRequirement{ - { - Key: "test-label-key", - Operator: core.NodeSelectorOpIn, - Values: []string{"test-label-value"}, - }, - }, - }, - }, - }, - PreferredDuringSchedulingIgnoredDuringExecution: []core.PreferredSchedulingTerm{ - { - Weight: 10, - Preference: core.NodeSelectorTerm{ - MatchExpressions: []core.NodeSelectorRequirement{ - { - Key: "test-label-key", - Operator: core.NodeSelectorOpIn, - Values: []string{"test-label-value"}, - }, - }, - }, - }, - }, - }, - testLocalVolume("/foo", nil)), - }, - "alpha and beta local volume": { - isExpectedFailure: true, - volume: testVolumeWithAlphaNodeAffinity( - t, - "invalid-alpha-beta-local-volume", - "", - &core.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{ - NodeSelectorTerms: []core.NodeSelectorTerm{ - { - MatchExpressions: []core.NodeSelectorRequirement{ - { - Key: "test-label-key", - Operator: core.NodeSelectorOpIn, - Values: []string{"test-label-value"}, - }, - }, - }, - }, - }, - }, - testLocalVolume("/foo", simpleVolumeNodeAffinity("foo", "bar"))), - }, - "valid local volume": { - isExpectedFailure: false, - volume: testVolume("valid-local-volume", "", - testLocalVolume("/foo", simpleVolumeNodeAffinity("foo", "bar"))), - }, - "invalid local volume no node affinity": { - isExpectedFailure: true, - volume: testVolume("invalid-local-volume-no-node-affinity", "", - testLocalVolume("/foo", nil)), - }, - "invalid local volume empty path": { - isExpectedFailure: true, - volume: testVolume("invalid-local-volume-empty-path", "", - testLocalVolume("", simpleVolumeNodeAffinity("foo", "bar"))), - }, - "invalid-local-volume-backsteps": { - isExpectedFailure: true, - volume: testVolume("foo", "", - testLocalVolume("/foo/..", simpleVolumeNodeAffinity("foo", "bar"))), - }, - "invalid-local-volume-relative-path": { - isExpectedFailure: true, - volume: testVolume("foo", "", - testLocalVolume("foo", simpleVolumeNodeAffinity("foo", "bar"))), - }, - } - - for name, scenario := range scenarios { - errs := ValidatePersistentVolume(scenario.volume) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } -} - -func TestValidateLocalVolumesDisabled(t *testing.T) { - scenarios := map[string]struct { - isExpectedFailure bool - volume *core.PersistentVolume - }{ - "alpha disabled valid local volume": { - isExpectedFailure: true, - volume: testVolumeWithAlphaNodeAffinity( - t, - "valid-local-volume", - "", - &core.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{ - NodeSelectorTerms: []core.NodeSelectorTerm{ - { - MatchExpressions: []core.NodeSelectorRequirement{ - { - Key: "test-label-key", - Operator: core.NodeSelectorOpIn, - Values: []string{"test-label-value"}, - }, - }, - }, - }, - }, - }, - testLocalVolume("/foo", nil)), - }, - "feature disabled valid local volume": { - isExpectedFailure: true, - volume: testVolume("valid-local-volume", "", - testLocalVolume("/foo", simpleVolumeNodeAffinity("foo", "bar"))), - }, - } - - utilfeature.DefaultFeatureGate.Set("PersistentLocalVolumes=false") - for name, scenario := range scenarios { - errs := ValidatePersistentVolume(scenario.volume) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } - utilfeature.DefaultFeatureGate.Set("PersistentLocalVolumes=true") - - utilfeature.DefaultFeatureGate.Set("VolumeScheduling=false") - for name, scenario := range scenarios { - errs := ValidatePersistentVolume(scenario.volume) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } - utilfeature.DefaultFeatureGate.Set("VolumeScheduling=true") -} - -func testVolumeWithNodeAffinity(affinity *core.VolumeNodeAffinity) *core.PersistentVolume { - return testVolume("test-affinity-volume", "", - core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - GCEPersistentDisk: &core.GCEPersistentDiskVolumeSource{ - PDName: "foo", - }, - }, - StorageClassName: "test-storage-class", - NodeAffinity: affinity, - }) -} - -func simpleVolumeNodeAffinity(key, value string) *core.VolumeNodeAffinity { - return &core.VolumeNodeAffinity{ - Required: &core.NodeSelector{ - NodeSelectorTerms: []core.NodeSelectorTerm{ - { - MatchExpressions: []core.NodeSelectorRequirement{ - { - Key: key, - Operator: core.NodeSelectorOpIn, - Values: []string{value}, - }, - }, - }, - }, - }, - } -} - -func TestValidateVolumeNodeAffinityUpdate(t *testing.T) { - scenarios := map[string]struct { - isExpectedFailure bool - oldPV *core.PersistentVolume - newPV *core.PersistentVolume - }{ - "nil-nothing-changed": { - isExpectedFailure: false, - oldPV: testVolumeWithNodeAffinity(nil), - newPV: testVolumeWithNodeAffinity(nil), - }, - "affinity-nothing-changed": { - isExpectedFailure: false, - oldPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")), - newPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")), - }, - "affinity-changed": { - isExpectedFailure: true, - oldPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")), - newPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar2")), - }, - "nil-to-obj": { - isExpectedFailure: false, - oldPV: testVolumeWithNodeAffinity(nil), - newPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")), - }, - "obj-to-nil": { - isExpectedFailure: true, - oldPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")), - newPV: testVolumeWithNodeAffinity(nil), - }, - } - - for name, scenario := range scenarios { - errs := ValidatePersistentVolumeUpdate(scenario.newPV, scenario.oldPV) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } -} - -func testVolumeClaim(name string, namespace string, spec core.PersistentVolumeClaimSpec) *core.PersistentVolumeClaim { - return &core.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, - Spec: spec, - } -} - -func testVolumeClaimWithStatus( - name, namespace string, - spec core.PersistentVolumeClaimSpec, - status core.PersistentVolumeClaimStatus) *core.PersistentVolumeClaim { - return &core.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, - Spec: spec, - Status: status, - } -} - -func testVolumeClaimStorageClass(name string, namespace string, annval string, spec core.PersistentVolumeClaimSpec) *core.PersistentVolumeClaim { - annotations := map[string]string{ - v1.BetaStorageClassAnnotation: annval, - } - - return &core.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - Annotations: annotations, - }, - Spec: spec, - } -} - -func testVolumeClaimAnnotation(name string, namespace string, ann string, annval string, spec core.PersistentVolumeClaimSpec) *core.PersistentVolumeClaim { - annotations := map[string]string{ - ann: annval, - } - - return &core.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - Annotations: annotations, - }, - Spec: spec, - } -} - -func testVolumeClaimStorageClassInSpec(name, namespace, scName string, spec core.PersistentVolumeClaimSpec) *core.PersistentVolumeClaim { - spec.StorageClassName = &scName - return &core.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Spec: spec, - } -} - -func testVolumeClaimStorageClassInAnnotationAndSpec(name, namespace, scNameInAnn, scName string, spec core.PersistentVolumeClaimSpec) *core.PersistentVolumeClaim { - spec.StorageClassName = &scName - return &core.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - Annotations: map[string]string{v1.BetaStorageClassAnnotation: scNameInAnn}, - }, - Spec: spec, - } -} - -func TestValidatePersistentVolumeClaim(t *testing.T) { - invalidClassName := "-invalid-" - validClassName := "valid" - validMode := core.PersistentVolumeFilesystem - scenarios := map[string]struct { - isExpectedFailure bool - claim *core.PersistentVolumeClaim - }{ - "good-claim": { - isExpectedFailure: false, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - Selector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: "Exists", - }, - }, - }, - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - StorageClassName: &validClassName, - }), - }, - "invalid-claim-zero-capacity": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - Selector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: "Exists", - }, - }, - }, - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("0G"), - }, - }, - StorageClassName: &validClassName, - }), - }, - "invalid-label-selector": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - Selector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: "InvalidOp", - Values: []string{"value1", "value2"}, - }, - }, - }, - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }), - }, - "invalid-accessmode": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{"fakemode"}, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }), - }, - "missing-namespace": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }), - }, - "no-access-modes": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }), - }, - "no-resource-requests": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - }, - }), - }, - "invalid-resource-requests": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - }, - }, - }), - }, - "negative-storage-request": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - Selector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: "Exists", - }, - }, - }, - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("-10G"), - }, - }, - }), - }, - "zero-storage-request": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - Selector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: "Exists", - }, - }, - }, - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("0G"), - }, - }, - }), - }, - "invalid-storage-class-name": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - Selector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: "Exists", - }, - }, - }, - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - StorageClassName: &invalidClassName, - }), - }, - // VolumeMode alpha feature disabled - // TODO: remove when no longer alpha - "disabled alpha valid volume mode": { - isExpectedFailure: true, - claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - Selector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: "Exists", - }, - }, - }, - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - StorageClassName: &validClassName, - VolumeMode: &validMode, - }), - }, - } - - for name, scenario := range scenarios { - errs := ValidatePersistentVolumeClaim(scenario.claim) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } -} - -func TestAlphaPVVolumeModeUpdate(t *testing.T) { - block := core.PersistentVolumeBlock - file := core.PersistentVolumeFilesystem - - scenarios := map[string]struct { - isExpectedFailure bool - oldPV *core.PersistentVolume - newPV *core.PersistentVolume - enableBlock bool - }{ - "valid-update-volume-mode-block-to-block": { - isExpectedFailure: false, - oldPV: createTestVolModePV(&block), - newPV: createTestVolModePV(&block), - enableBlock: true, - }, - "valid-update-volume-mode-file-to-file": { - isExpectedFailure: false, - oldPV: createTestVolModePV(&file), - newPV: createTestVolModePV(&file), - enableBlock: true, - }, - "invalid-update-volume-mode-to-block": { - isExpectedFailure: true, - oldPV: createTestVolModePV(&file), - newPV: createTestVolModePV(&block), - enableBlock: true, - }, - "invalid-update-volume-mode-to-file": { - isExpectedFailure: true, - oldPV: createTestVolModePV(&block), - newPV: createTestVolModePV(&file), - enableBlock: true, - }, - "invalid-update-blocksupport-disabled": { - isExpectedFailure: true, - oldPV: createTestVolModePV(&block), - newPV: createTestVolModePV(&block), - enableBlock: false, - }, - "invalid-update-volume-mode-nil-to-file": { - isExpectedFailure: true, - oldPV: createTestVolModePV(nil), - newPV: createTestVolModePV(&file), - enableBlock: true, - }, - "invalid-update-volume-mode-nil-to-block": { - isExpectedFailure: true, - oldPV: createTestVolModePV(nil), - newPV: createTestVolModePV(&block), - enableBlock: true, - }, - "invalid-update-volume-mode-file-to-nil": { - isExpectedFailure: true, - oldPV: createTestVolModePV(&file), - newPV: createTestVolModePV(nil), - enableBlock: true, - }, - "invalid-update-volume-mode-block-to-nil": { - isExpectedFailure: true, - oldPV: createTestVolModePV(&block), - newPV: createTestVolModePV(nil), - enableBlock: true, - }, - "invalid-update-volume-mode-nil-to-nil": { - isExpectedFailure: false, - oldPV: createTestVolModePV(nil), - newPV: createTestVolModePV(nil), - enableBlock: true, - }, - "invalid-update-volume-mode-empty-to-mode": { - isExpectedFailure: true, - oldPV: createTestPV(), - newPV: createTestVolModePV(&block), - enableBlock: true, - }, - } - - for name, scenario := range scenarios { - // ensure we have a resource version specified for updates - toggleBlockVolumeFeature(scenario.enableBlock, t) - errs := ValidatePersistentVolumeUpdate(scenario.newPV, scenario.oldPV) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } -} - -func TestValidatePersistentVolumeClaimUpdate(t *testing.T) { - block := core.PersistentVolumeBlock - file := core.PersistentVolumeFilesystem - - validClaim := testVolumeClaimWithStatus("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }, core.PersistentVolumeClaimStatus{ - Phase: core.ClaimBound, - }) - - validClaimStorageClass := testVolumeClaimStorageClass("foo", "ns", "fast", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }) - validClaimAnnotation := testVolumeClaimAnnotation("foo", "ns", "description", "foo-description", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }) - validUpdateClaim := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - VolumeName: "volume", - }) - invalidUpdateClaimResources := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("20G"), - }, - }, - VolumeName: "volume", - }) - invalidUpdateClaimAccessModes := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - VolumeName: "volume", - }) - validClaimVolumeModeFile := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - }, - VolumeMode: &file, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - VolumeName: "volume", - }) - validClaimVolumeModeBlock := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - }, - VolumeMode: &block, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - VolumeName: "volume", - }) - invalidClaimVolumeModeNil := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - }, - VolumeMode: nil, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - VolumeName: "volume", - }) - invalidUpdateClaimStorageClass := testVolumeClaimStorageClass("foo", "ns", "fast2", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - VolumeName: "volume", - }) - validUpdateClaimMutableAnnotation := testVolumeClaimAnnotation("foo", "ns", "description", "updated-or-added-foo-description", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - VolumeName: "volume", - }) - validAddClaimAnnotation := testVolumeClaimAnnotation("foo", "ns", "description", "updated-or-added-foo-description", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - VolumeName: "volume", - }) - validSizeUpdate := testVolumeClaimWithStatus("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("15G"), - }, - }, - }, core.PersistentVolumeClaimStatus{ - Phase: core.ClaimBound, - }) - - invalidSizeUpdate := testVolumeClaimWithStatus("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("5G"), - }, - }, - }, core.PersistentVolumeClaimStatus{ - Phase: core.ClaimBound, - }) - - unboundSizeUpdate := testVolumeClaimWithStatus("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("12G"), - }, - }, - }, core.PersistentVolumeClaimStatus{ - Phase: core.ClaimPending, - }) - - validClaimStorageClassInSpec := testVolumeClaimStorageClassInSpec("foo", "ns", "fast", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }) - - invalidClaimStorageClassInSpec := testVolumeClaimStorageClassInSpec("foo", "ns", "fast2", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }) - - validClaimStorageClassInAnnotationAndSpec := testVolumeClaimStorageClassInAnnotationAndSpec( - "foo", "ns", "fast", "fast", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }) - - invalidClaimStorageClassInAnnotationAndSpec := testVolumeClaimStorageClassInAnnotationAndSpec( - "foo", "ns", "fast2", "fast", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }) - - scenarios := map[string]struct { - isExpectedFailure bool - oldClaim *core.PersistentVolumeClaim - newClaim *core.PersistentVolumeClaim - enableResize bool - enableBlock bool - }{ - "valid-update-volumeName-only": { - isExpectedFailure: false, - oldClaim: validClaim, - newClaim: validUpdateClaim, - enableResize: false, - enableBlock: false, - }, - "valid-no-op-update": { - isExpectedFailure: false, - oldClaim: validUpdateClaim, - newClaim: validUpdateClaim, - enableResize: false, - enableBlock: false, - }, - "invalid-update-change-resources-on-bound-claim": { - isExpectedFailure: true, - oldClaim: validUpdateClaim, - newClaim: invalidUpdateClaimResources, - enableResize: false, - enableBlock: false, - }, - "invalid-update-change-access-modes-on-bound-claim": { - isExpectedFailure: true, - oldClaim: validUpdateClaim, - newClaim: invalidUpdateClaimAccessModes, - enableResize: false, - enableBlock: false, - }, - "valid-update-volume-mode-block-to-block": { - isExpectedFailure: false, - oldClaim: validClaimVolumeModeBlock, - newClaim: validClaimVolumeModeBlock, - enableResize: false, - enableBlock: true, - }, - "valid-update-volume-mode-file-to-file": { - isExpectedFailure: false, - oldClaim: validClaimVolumeModeFile, - newClaim: validClaimVolumeModeFile, - enableResize: false, - enableBlock: true, - }, - "invalid-update-volume-mode-to-block": { - isExpectedFailure: true, - oldClaim: validClaimVolumeModeFile, - newClaim: validClaimVolumeModeBlock, - enableResize: false, - enableBlock: true, - }, - "invalid-update-volume-mode-to-file": { - isExpectedFailure: true, - oldClaim: validClaimVolumeModeBlock, - newClaim: validClaimVolumeModeFile, - enableResize: false, - enableBlock: true, - }, - "invalid-update-volume-mode-nil-to-file": { - isExpectedFailure: true, - oldClaim: invalidClaimVolumeModeNil, - newClaim: validClaimVolumeModeFile, - enableResize: false, - enableBlock: true, - }, - "invalid-update-volume-mode-nil-to-block": { - isExpectedFailure: true, - oldClaim: invalidClaimVolumeModeNil, - newClaim: validClaimVolumeModeBlock, - enableResize: false, - enableBlock: true, - }, - "invalid-update-volume-mode-block-to-nil": { - isExpectedFailure: true, - oldClaim: validClaimVolumeModeBlock, - newClaim: invalidClaimVolumeModeNil, - enableResize: false, - enableBlock: true, - }, - "invalid-update-volume-mode-file-to-nil": { - isExpectedFailure: true, - oldClaim: validClaimVolumeModeFile, - newClaim: invalidClaimVolumeModeNil, - enableResize: false, - enableBlock: true, - }, - "invalid-update-volume-mode-empty-to-mode": { - isExpectedFailure: true, - oldClaim: validClaim, - newClaim: validClaimVolumeModeBlock, - enableResize: false, - enableBlock: true, - }, - "invalid-update-volume-mode-mode-to-empty": { - isExpectedFailure: true, - oldClaim: validClaimVolumeModeBlock, - newClaim: validClaim, - enableResize: false, - enableBlock: true, - }, - "invalid-update-blocksupport-disabled": { - isExpectedFailure: true, - oldClaim: validClaimVolumeModeFile, - newClaim: validClaimVolumeModeFile, - enableResize: false, - enableBlock: false, - }, - "invalid-update-change-storage-class-annotation-after-creation": { - isExpectedFailure: true, - oldClaim: validClaimStorageClass, - newClaim: invalidUpdateClaimStorageClass, - enableResize: false, - enableBlock: false, - }, - "valid-update-mutable-annotation": { - isExpectedFailure: false, - oldClaim: validClaimAnnotation, - newClaim: validUpdateClaimMutableAnnotation, - enableResize: false, - enableBlock: false, - }, - "valid-update-add-annotation": { - isExpectedFailure: false, - oldClaim: validClaim, - newClaim: validAddClaimAnnotation, - enableResize: false, - enableBlock: false, - }, - "valid-size-update-resize-disabled": { - isExpectedFailure: true, - oldClaim: validClaim, - newClaim: validSizeUpdate, - enableResize: false, - enableBlock: false, - }, - "valid-size-update-resize-enabled": { - isExpectedFailure: false, - oldClaim: validClaim, - newClaim: validSizeUpdate, - enableResize: true, - enableBlock: false, - }, - "invalid-size-update-resize-enabled": { - isExpectedFailure: true, - oldClaim: validClaim, - newClaim: invalidSizeUpdate, - enableResize: true, - enableBlock: false, - }, - "unbound-size-update-resize-enabled": { - isExpectedFailure: true, - oldClaim: validClaim, - newClaim: unboundSizeUpdate, - enableResize: true, - enableBlock: false, - }, - "valid-upgrade-storage-class-annotation-to-spec": { - isExpectedFailure: false, - oldClaim: validClaimStorageClass, - newClaim: validClaimStorageClassInSpec, - enableResize: false, - enableBlock: false, - }, - "invalid-upgrade-storage-class-annotation-to-spec": { - isExpectedFailure: true, - oldClaim: validClaimStorageClass, - newClaim: invalidClaimStorageClassInSpec, - enableResize: false, - enableBlock: false, - }, - "valid-upgrade-storage-class-annotation-to-annotation-and-spec": { - isExpectedFailure: false, - oldClaim: validClaimStorageClass, - newClaim: validClaimStorageClassInAnnotationAndSpec, - enableResize: false, - enableBlock: false, - }, - "invalid-upgrade-storage-class-annotation-to-annotation-and-spec": { - isExpectedFailure: true, - oldClaim: validClaimStorageClass, - newClaim: invalidClaimStorageClassInAnnotationAndSpec, - enableResize: false, - enableBlock: false, - }, - "invalid-upgrade-storage-class-in-spec": { - isExpectedFailure: true, - oldClaim: validClaimStorageClassInSpec, - newClaim: invalidClaimStorageClassInSpec, - enableResize: false, - enableBlock: false, - }, - "invalid-downgrade-storage-class-spec-to-annotation": { - isExpectedFailure: true, - oldClaim: validClaimStorageClassInSpec, - newClaim: validClaimStorageClass, - enableResize: false, - enableBlock: false, - }, - } - - for name, scenario := range scenarios { - // ensure we have a resource version specified for updates - togglePVExpandFeature(scenario.enableResize, t) - toggleBlockVolumeFeature(scenario.enableBlock, t) - scenario.oldClaim.ResourceVersion = "1" - scenario.newClaim.ResourceVersion = "1" - errs := ValidatePersistentVolumeClaimUpdate(scenario.newClaim, scenario.oldClaim) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } -} - -func toggleBlockVolumeFeature(toggleFlag bool, t *testing.T) { - if toggleFlag { - // Enable alpha feature BlockVolume - err := utilfeature.DefaultFeatureGate.Set("BlockVolume=true") - if err != nil { - t.Errorf("Failed to enable feature gate for BlockVolume: %v", err) - return - } - } else { - err := utilfeature.DefaultFeatureGate.Set("BlockVolume=false") - if err != nil { - t.Errorf("Failed to disable feature gate for BlockVolume: %v", err) - return - } - } -} - -func togglePVExpandFeature(toggleFlag bool, t *testing.T) { - if toggleFlag { - // Enable alpha feature LocalStorageCapacityIsolation - err := utilfeature.DefaultFeatureGate.Set("ExpandPersistentVolumes=true") - if err != nil { - t.Errorf("Failed to enable feature gate for ExpandPersistentVolumes: %v", err) - return - } - } else { - err := utilfeature.DefaultFeatureGate.Set("ExpandPersistentVolumes=false") - if err != nil { - t.Errorf("Failed to disable feature gate for ExpandPersistentVolumes: %v", err) - return - } - } -} - -func TestValidateKeyToPath(t *testing.T) { - testCases := []struct { - kp core.KeyToPath - ok bool - errtype field.ErrorType - }{ - { - kp: core.KeyToPath{Key: "k", Path: "p"}, - ok: true, - }, - { - kp: core.KeyToPath{Key: "k", Path: "p/p/p/p"}, - ok: true, - }, - { - kp: core.KeyToPath{Key: "k", Path: "p/..p/p../p..p"}, - ok: true, - }, - { - kp: core.KeyToPath{Key: "k", Path: "p", Mode: newInt32(0644)}, - ok: true, - }, - { - kp: core.KeyToPath{Key: "", Path: "p"}, - ok: false, - errtype: field.ErrorTypeRequired, - }, - { - kp: core.KeyToPath{Key: "k", Path: ""}, - ok: false, - errtype: field.ErrorTypeRequired, - }, - { - kp: core.KeyToPath{Key: "k", Path: "..p"}, - ok: false, - errtype: field.ErrorTypeInvalid, - }, - { - kp: core.KeyToPath{Key: "k", Path: "../p"}, - ok: false, - errtype: field.ErrorTypeInvalid, - }, - { - kp: core.KeyToPath{Key: "k", Path: "p/../p"}, - ok: false, - errtype: field.ErrorTypeInvalid, - }, - { - kp: core.KeyToPath{Key: "k", Path: "p/.."}, - ok: false, - errtype: field.ErrorTypeInvalid, - }, - { - kp: core.KeyToPath{Key: "k", Path: "p", Mode: newInt32(01000)}, - ok: false, - errtype: field.ErrorTypeInvalid, - }, - { - kp: core.KeyToPath{Key: "k", Path: "p", Mode: newInt32(-1)}, - ok: false, - errtype: field.ErrorTypeInvalid, - }, - } - - for i, tc := range testCases { - errs := validateKeyToPath(&tc.kp, field.NewPath("field")) - if tc.ok && len(errs) > 0 { - t.Errorf("[%d] unexpected errors: %v", i, errs) - } else if !tc.ok && len(errs) == 0 { - t.Errorf("[%d] expected error type %v", i, tc.errtype) - } else if len(errs) > 1 { - t.Errorf("[%d] expected only one error, got %d", i, len(errs)) - } else if !tc.ok { - if errs[0].Type != tc.errtype { - t.Errorf("[%d] expected error type %v, got %v", i, tc.errtype, errs[0].Type) - } - } - } -} - -func TestValidateNFSVolumeSource(t *testing.T) { - testCases := []struct { - name string - nfs *core.NFSVolumeSource - errtype field.ErrorType - errfield string - errdetail string - }{ - { - name: "missing server", - nfs: &core.NFSVolumeSource{Server: "", Path: "/tmp"}, - errtype: field.ErrorTypeRequired, - errfield: "server", - }, - { - name: "missing path", - nfs: &core.NFSVolumeSource{Server: "my-server", Path: ""}, - errtype: field.ErrorTypeRequired, - errfield: "path", - }, - { - name: "abs path", - nfs: &core.NFSVolumeSource{Server: "my-server", Path: "tmp"}, - errtype: field.ErrorTypeInvalid, - errfield: "path", - errdetail: "must be an absolute path", - }, - } - - for i, tc := range testCases { - errs := validateNFSVolumeSource(tc.nfs, field.NewPath("field")) - - if len(errs) > 0 && tc.errtype == "" { - t.Errorf("[%d: %q] unexpected error(s): %v", i, tc.name, errs) - } else if len(errs) == 0 && tc.errtype != "" { - t.Errorf("[%d: %q] expected error type %v", i, tc.name, tc.errtype) - } else if len(errs) >= 1 { - if errs[0].Type != tc.errtype { - t.Errorf("[%d: %q] expected error type %v, got %v", i, tc.name, tc.errtype, errs[0].Type) - } else if !strings.HasSuffix(errs[0].Field, "."+tc.errfield) { - t.Errorf("[%d: %q] expected error on field %q, got %q", i, tc.name, tc.errfield, errs[0].Field) - } else if !strings.Contains(errs[0].Detail, tc.errdetail) { - t.Errorf("[%d: %q] expected error detail %q, got %q", i, tc.name, tc.errdetail, errs[0].Detail) - } - } - } -} - -func TestValidateGlusterfs(t *testing.T) { - testCases := []struct { - name string - gfs *core.GlusterfsVolumeSource - errtype field.ErrorType - errfield string - }{ - { - name: "missing endpointname", - gfs: &core.GlusterfsVolumeSource{EndpointsName: "", Path: "/tmp"}, - errtype: field.ErrorTypeRequired, - errfield: "endpoints", - }, - { - name: "missing path", - gfs: &core.GlusterfsVolumeSource{EndpointsName: "my-endpoint", Path: ""}, - errtype: field.ErrorTypeRequired, - errfield: "path", - }, - { - name: "missing endpintname and path", - gfs: &core.GlusterfsVolumeSource{EndpointsName: "", Path: ""}, - errtype: field.ErrorTypeRequired, - errfield: "endpoints", - }, - } - - for i, tc := range testCases { - errs := validateGlusterfsVolumeSource(tc.gfs, field.NewPath("field")) - - if len(errs) > 0 && tc.errtype == "" { - t.Errorf("[%d: %q] unexpected error(s): %v", i, tc.name, errs) - } else if len(errs) == 0 && tc.errtype != "" { - t.Errorf("[%d: %q] expected error type %v", i, tc.name, tc.errtype) - } else if len(errs) >= 1 { - if errs[0].Type != tc.errtype { - t.Errorf("[%d: %q] expected error type %v, got %v", i, tc.name, tc.errtype, errs[0].Type) - } else if !strings.HasSuffix(errs[0].Field, "."+tc.errfield) { - t.Errorf("[%d: %q] expected error on field %q, got %q", i, tc.name, tc.errfield, errs[0].Field) - } - } - } -} - -func TestValidateCSIVolumeSource(t *testing.T) { - testCases := []struct { - name string - csi *core.CSIPersistentVolumeSource - errtype field.ErrorType - errfield string - }{ - { - name: "all required fields ok", - csi: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123", ReadOnly: true}, - }, - { - name: "with default values ok", - csi: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123"}, - }, - { - name: "missing driver name", - csi: &core.CSIPersistentVolumeSource{VolumeHandle: "test-123"}, - errtype: field.ErrorTypeRequired, - errfield: "driver", - }, - { - name: "missing volume handle", - csi: &core.CSIPersistentVolumeSource{Driver: "my-driver"}, - errtype: field.ErrorTypeRequired, - errfield: "volumeHandle", - }, - { - name: "driver name: ok no punctuations", - csi: &core.CSIPersistentVolumeSource{Driver: "comgooglestoragecsigcepd", VolumeHandle: "test-123"}, - }, - { - name: "driver name: ok dot only", - csi: &core.CSIPersistentVolumeSource{Driver: "io.kubernetes.storage.csi.flex", VolumeHandle: "test-123"}, - }, - { - name: "driver name: ok dash only", - csi: &core.CSIPersistentVolumeSource{Driver: "io-kubernetes-storage-csi-flex", VolumeHandle: "test-123"}, - }, - { - name: "driver name: ok underscore only", - csi: &core.CSIPersistentVolumeSource{Driver: "io_kubernetes_storage_csi_flex", VolumeHandle: "test-123"}, - }, - { - name: "driver name: ok dot underscores", - csi: &core.CSIPersistentVolumeSource{Driver: "io.kubernetes.storage_csi.flex", VolumeHandle: "test-123"}, - }, - { - name: "driver name: ok beginnin with number", - csi: &core.CSIPersistentVolumeSource{Driver: "2io.kubernetes.storage_csi.flex", VolumeHandle: "test-123"}, - }, - { - name: "driver name: ok ending with number", - csi: &core.CSIPersistentVolumeSource{Driver: "io.kubernetes.storage_csi.flex2", VolumeHandle: "test-123"}, - }, - { - name: "driver name: ok dot dash underscores", - csi: &core.CSIPersistentVolumeSource{Driver: "io.kubernetes-storage.csi_flex", VolumeHandle: "test-123"}, - }, - { - name: "driver name: invalid length 0", - csi: &core.CSIPersistentVolumeSource{Driver: "", VolumeHandle: "test-123"}, - errtype: field.ErrorTypeRequired, - errfield: "driver", - }, - { - name: "driver name: invalid length 1", - csi: &core.CSIPersistentVolumeSource{Driver: "a", VolumeHandle: "test-123"}, - errtype: field.ErrorTypeInvalid, - errfield: "driver", - }, - { - name: "driver name: invalid length > 63", - csi: &core.CSIPersistentVolumeSource{Driver: "comgooglestoragecsigcepdcomgooglestoragecsigcepdcomgooglestoragecsigcepdcomgooglestoragecsigcepd", VolumeHandle: "test-123"}, - errtype: field.ErrorTypeTooLong, - errfield: "driver", - }, - { - name: "driver name: invalid start char", - csi: &core.CSIPersistentVolumeSource{Driver: "_comgooglestoragecsigcepd", VolumeHandle: "test-123"}, - errtype: field.ErrorTypeInvalid, - errfield: "driver", - }, - { - name: "driver name: invalid end char", - csi: &core.CSIPersistentVolumeSource{Driver: "comgooglestoragecsigcepd/", VolumeHandle: "test-123"}, - errtype: field.ErrorTypeInvalid, - errfield: "driver", - }, - { - name: "driver name: invalid separators", - csi: &core.CSIPersistentVolumeSource{Driver: "com/google/storage/csi~gcepd", VolumeHandle: "test-123"}, - errtype: field.ErrorTypeInvalid, - errfield: "driver", - }, - } - - err := utilfeature.DefaultFeatureGate.Set("CSIPersistentVolume=true") - if err != nil { - t.Errorf("Failed to enable feature gate for CSIPersistentVolumes: %v", err) - return - } - - for i, tc := range testCases { - errs := validateCSIPersistentVolumeSource(tc.csi, field.NewPath("field")) - - if len(errs) > 0 && tc.errtype == "" { - t.Errorf("[%d: %q] unexpected error(s): %v", i, tc.name, errs) - } else if len(errs) == 0 && tc.errtype != "" { - t.Errorf("[%d: %q] expected error type %v", i, tc.name, tc.errtype) - } else if len(errs) >= 1 { - if errs[0].Type != tc.errtype { - t.Errorf("[%d: %q] expected error type %v, got %v", i, tc.name, tc.errtype, errs[0].Type) - } else if !strings.HasSuffix(errs[0].Field, "."+tc.errfield) { - t.Errorf("[%d: %q] expected error on field %q, got %q", i, tc.name, tc.errfield, errs[0].Field) - } - } - } - err = utilfeature.DefaultFeatureGate.Set("CSIPersistentVolume=false") - if err != nil { - t.Errorf("Failed to disable feature gate for CSIPersistentVolumes: %v", err) - return - } - -} - -// helper -func newInt32(val int) *int32 { - p := new(int32) - *p = int32(val) - return p -} - -// This test is a little too top-to-bottom. Ideally we would test each volume -// type on its own, but we want to also make sure that the logic works through -// the one-of wrapper, so we just do it all in one place. -func TestValidateVolumes(t *testing.T) { - validInitiatorName := "iqn.2015-02.example.com:init" - invalidInitiatorName := "2015-02.example.com:init" - testCases := []struct { - name string - vol core.Volume - errtype field.ErrorType - errfield string - errdetail string - }{ - // EmptyDir and basic volume names - { - name: "valid alpha name", - vol: core.Volume{ - Name: "empty", - VolumeSource: core.VolumeSource{ - EmptyDir: &core.EmptyDirVolumeSource{}, - }, - }, - }, - { - name: "valid num name", - vol: core.Volume{ - Name: "123", - VolumeSource: core.VolumeSource{ - EmptyDir: &core.EmptyDirVolumeSource{}, - }, - }, - }, - { - name: "valid alphanum name", - vol: core.Volume{ - Name: "empty-123", - VolumeSource: core.VolumeSource{ - EmptyDir: &core.EmptyDirVolumeSource{}, - }, - }, - }, - { - name: "valid numalpha name", - vol: core.Volume{ - Name: "123-empty", - VolumeSource: core.VolumeSource{ - EmptyDir: &core.EmptyDirVolumeSource{}, - }, - }, - }, - { - name: "zero-length name", - vol: core.Volume{ - Name: "", - VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}, - }, - errtype: field.ErrorTypeRequired, - errfield: "name", - }, - { - name: "name > 63 characters", - vol: core.Volume{ - Name: strings.Repeat("a", 64), - VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}, - }, - errtype: field.ErrorTypeInvalid, - errfield: "name", - errdetail: "must be no more than", - }, - { - name: "name not a DNS label", - vol: core.Volume{ - Name: "a.b.c", - VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}, - }, - errtype: field.ErrorTypeInvalid, - errfield: "name", - errdetail: dnsLabelErrMsg, - }, - // More than one source field specified. - { - name: "more than one source", - vol: core.Volume{ - Name: "dups", - VolumeSource: core.VolumeSource{ - EmptyDir: &core.EmptyDirVolumeSource{}, - HostPath: &core.HostPathVolumeSource{ - Path: "/mnt/path", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }, - errtype: field.ErrorTypeForbidden, - errfield: "hostPath", - errdetail: "may not specify more than 1 volume", - }, - // HostPath Default - { - name: "default HostPath", - vol: core.Volume{ - Name: "hostpath", - VolumeSource: core.VolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/mnt/path", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }, - }, - // HostPath Supported - { - name: "valid HostPath", - vol: core.Volume{ - Name: "hostpath", - VolumeSource: core.VolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/mnt/path", - Type: newHostPathType(string(core.HostPathSocket)), - }, - }, - }, - }, - // HostPath Invalid - { - name: "invalid HostPath", - vol: core.Volume{ - Name: "hostpath", - VolumeSource: core.VolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/mnt/path", - Type: newHostPathType("invalid"), - }, - }, - }, - errtype: field.ErrorTypeNotSupported, - errfield: "type", - }, - { - name: "invalid HostPath backsteps", - vol: core.Volume{ - Name: "hostpath", - VolumeSource: core.VolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/mnt/path/..", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "path", - errdetail: "must not contain '..'", - }, - // GcePersistentDisk - { - name: "valid GcePersistentDisk", - vol: core.Volume{ - Name: "gce-pd", - VolumeSource: core.VolumeSource{ - GCEPersistentDisk: &core.GCEPersistentDiskVolumeSource{ - PDName: "my-PD", - FSType: "ext4", - Partition: 1, - ReadOnly: false, - }, - }, - }, - }, - // AWSElasticBlockStore - { - name: "valid AWSElasticBlockStore", - vol: core.Volume{ - Name: "aws-ebs", - VolumeSource: core.VolumeSource{ - AWSElasticBlockStore: &core.AWSElasticBlockStoreVolumeSource{ - VolumeID: "my-PD", - FSType: "ext4", - Partition: 1, - ReadOnly: false, - }, - }, - }, - }, - // GitRepo - { - name: "valid GitRepo", - vol: core.Volume{ - Name: "git-repo", - VolumeSource: core.VolumeSource{ - GitRepo: &core.GitRepoVolumeSource{ - Repository: "my-repo", - Revision: "hashstring", - Directory: "target", - }, - }, - }, - }, - { - name: "valid GitRepo in .", - vol: core.Volume{ - Name: "git-repo-dot", - VolumeSource: core.VolumeSource{ - GitRepo: &core.GitRepoVolumeSource{ - Repository: "my-repo", - Directory: ".", - }, - }, - }, - }, - { - name: "valid GitRepo with .. in name", - vol: core.Volume{ - Name: "git-repo-dot-dot-foo", - VolumeSource: core.VolumeSource{ - GitRepo: &core.GitRepoVolumeSource{ - Repository: "my-repo", - Directory: "..foo", - }, - }, - }, - }, - { - name: "GitRepo starts with ../", - vol: core.Volume{ - Name: "gitrepo", - VolumeSource: core.VolumeSource{ - GitRepo: &core.GitRepoVolumeSource{ - Repository: "foo", - Directory: "../dots/bar", - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "gitRepo.directory", - errdetail: `must not contain '..'`, - }, - { - name: "GitRepo contains ..", - vol: core.Volume{ - Name: "gitrepo", - VolumeSource: core.VolumeSource{ - GitRepo: &core.GitRepoVolumeSource{ - Repository: "foo", - Directory: "dots/../bar", - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "gitRepo.directory", - errdetail: `must not contain '..'`, - }, - { - name: "GitRepo absolute target", - vol: core.Volume{ - Name: "gitrepo", - VolumeSource: core.VolumeSource{ - GitRepo: &core.GitRepoVolumeSource{ - Repository: "foo", - Directory: "/abstarget", - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "gitRepo.directory", - }, - // ISCSI - { - name: "valid ISCSI", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "iqn.2015-02.example.com:test", - Lun: 1, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - }, - { - name: "valid IQN: eui format", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "eui.0123456789ABCDEF", - Lun: 1, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - }, - { - name: "valid IQN: naa format", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "naa.62004567BA64678D0123456789ABCDEF", - Lun: 1, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - }, - { - name: "empty portal", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "", - IQN: "iqn.2015-02.example.com:test", - Lun: 1, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "iscsi.targetPortal", - }, - { - name: "empty iqn", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "", - Lun: 1, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "iscsi.iqn", - }, - { - name: "invalid IQN: iqn format", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "iqn.2015-02.example.com:test;ls;", - Lun: 1, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "iscsi.iqn", - }, - { - name: "invalid IQN: eui format", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "eui.0123456789ABCDEFGHIJ", - Lun: 1, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "iscsi.iqn", - }, - { - name: "invalid IQN: naa format", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "naa.62004567BA_4-78D.123456789ABCDEF", - Lun: 1, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "iscsi.iqn", - }, - { - name: "valid initiatorName", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "iqn.2015-02.example.com:test", - Lun: 1, - InitiatorName: &validInitiatorName, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - }, - { - name: "invalid initiatorName", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "iqn.2015-02.example.com:test", - Lun: 1, - InitiatorName: &invalidInitiatorName, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "iscsi.initiatorname", - }, - { - name: "empty secret", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "iqn.2015-02.example.com:test", - Lun: 1, - FSType: "ext4", - ReadOnly: false, - DiscoveryCHAPAuth: true, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "iscsi.secretRef", - }, - { - name: "empty secret", - vol: core.Volume{ - Name: "iscsi", - VolumeSource: core.VolumeSource{ - ISCSI: &core.ISCSIVolumeSource{ - TargetPortal: "127.0.0.1", - IQN: "iqn.2015-02.example.com:test", - Lun: 1, - FSType: "ext4", - ReadOnly: false, - SessionCHAPAuth: true, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "iscsi.secretRef", - }, - // Secret - { - name: "valid Secret", - vol: core.Volume{ - Name: "secret", - VolumeSource: core.VolumeSource{ - Secret: &core.SecretVolumeSource{ - SecretName: "my-secret", - }, - }, - }, - }, - { - name: "valid Secret with defaultMode", - vol: core.Volume{ - Name: "secret", - VolumeSource: core.VolumeSource{ - Secret: &core.SecretVolumeSource{ - SecretName: "my-secret", - DefaultMode: newInt32(0644), - }, - }, - }, - }, - { - name: "valid Secret with projection and mode", - vol: core.Volume{ - Name: "secret", - VolumeSource: core.VolumeSource{ - Secret: &core.SecretVolumeSource{ - SecretName: "my-secret", - Items: []core.KeyToPath{{ - Key: "key", - Path: "filename", - Mode: newInt32(0644), - }}, - }, - }, - }, - }, - { - name: "valid Secret with subdir projection", - vol: core.Volume{ - Name: "secret", - VolumeSource: core.VolumeSource{ - Secret: &core.SecretVolumeSource{ - SecretName: "my-secret", - Items: []core.KeyToPath{{ - Key: "key", - Path: "dir/filename", - }}, - }, - }, - }, - }, - { - name: "secret with missing path", - vol: core.Volume{ - Name: "secret", - VolumeSource: core.VolumeSource{ - Secret: &core.SecretVolumeSource{ - SecretName: "s", - Items: []core.KeyToPath{{Key: "key", Path: ""}}, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "secret.items[0].path", - }, - { - name: "secret with leading ..", - vol: core.Volume{ - Name: "secret", - VolumeSource: core.VolumeSource{ - Secret: &core.SecretVolumeSource{ - SecretName: "s", - Items: []core.KeyToPath{{Key: "key", Path: "../foo"}}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "secret.items[0].path", - }, - { - name: "secret with .. inside", - vol: core.Volume{ - Name: "secret", - VolumeSource: core.VolumeSource{ - Secret: &core.SecretVolumeSource{ - SecretName: "s", - Items: []core.KeyToPath{{Key: "key", Path: "foo/../bar"}}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "secret.items[0].path", - }, - { - name: "secret with invalid positive defaultMode", - vol: core.Volume{ - Name: "secret", - VolumeSource: core.VolumeSource{ - Secret: &core.SecretVolumeSource{ - SecretName: "s", - DefaultMode: newInt32(01000), - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "secret.defaultMode", - }, - { - name: "secret with invalid negative defaultMode", - vol: core.Volume{ - Name: "secret", - VolumeSource: core.VolumeSource{ - Secret: &core.SecretVolumeSource{ - SecretName: "s", - DefaultMode: newInt32(-1), - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "secret.defaultMode", - }, - // ConfigMap - { - name: "valid ConfigMap", - vol: core.Volume{ - Name: "cfgmap", - VolumeSource: core.VolumeSource{ - ConfigMap: &core.ConfigMapVolumeSource{ - LocalObjectReference: core.LocalObjectReference{ - Name: "my-cfgmap", - }, - }, - }, - }, - }, - { - name: "valid ConfigMap with defaultMode", - vol: core.Volume{ - Name: "cfgmap", - VolumeSource: core.VolumeSource{ - ConfigMap: &core.ConfigMapVolumeSource{ - LocalObjectReference: core.LocalObjectReference{ - Name: "my-cfgmap", - }, - DefaultMode: newInt32(0644), - }, - }, - }, - }, - { - name: "valid ConfigMap with projection and mode", - vol: core.Volume{ - Name: "cfgmap", - VolumeSource: core.VolumeSource{ - ConfigMap: &core.ConfigMapVolumeSource{ - LocalObjectReference: core.LocalObjectReference{ - Name: "my-cfgmap"}, - Items: []core.KeyToPath{{ - Key: "key", - Path: "filename", - Mode: newInt32(0644), - }}, - }, - }, - }, - }, - { - name: "valid ConfigMap with subdir projection", - vol: core.Volume{ - Name: "cfgmap", - VolumeSource: core.VolumeSource{ - ConfigMap: &core.ConfigMapVolumeSource{ - LocalObjectReference: core.LocalObjectReference{ - Name: "my-cfgmap"}, - Items: []core.KeyToPath{{ - Key: "key", - Path: "dir/filename", - }}, - }, - }, - }, - }, - { - name: "configmap with missing path", - vol: core.Volume{ - Name: "cfgmap", - VolumeSource: core.VolumeSource{ - ConfigMap: &core.ConfigMapVolumeSource{ - LocalObjectReference: core.LocalObjectReference{Name: "c"}, - Items: []core.KeyToPath{{Key: "key", Path: ""}}, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "configMap.items[0].path", - }, - { - name: "configmap with leading ..", - vol: core.Volume{ - Name: "cfgmap", - VolumeSource: core.VolumeSource{ - ConfigMap: &core.ConfigMapVolumeSource{ - LocalObjectReference: core.LocalObjectReference{Name: "c"}, - Items: []core.KeyToPath{{Key: "key", Path: "../foo"}}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "configMap.items[0].path", - }, - { - name: "configmap with .. inside", - vol: core.Volume{ - Name: "cfgmap", - VolumeSource: core.VolumeSource{ - ConfigMap: &core.ConfigMapVolumeSource{ - LocalObjectReference: core.LocalObjectReference{Name: "c"}, - Items: []core.KeyToPath{{Key: "key", Path: "foo/../bar"}}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "configMap.items[0].path", - }, - { - name: "configmap with invalid positive defaultMode", - vol: core.Volume{ - Name: "cfgmap", - VolumeSource: core.VolumeSource{ - ConfigMap: &core.ConfigMapVolumeSource{ - LocalObjectReference: core.LocalObjectReference{Name: "c"}, - DefaultMode: newInt32(01000), - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "configMap.defaultMode", - }, - { - name: "configmap with invalid negative defaultMode", - vol: core.Volume{ - Name: "cfgmap", - VolumeSource: core.VolumeSource{ - ConfigMap: &core.ConfigMapVolumeSource{ - LocalObjectReference: core.LocalObjectReference{Name: "c"}, - DefaultMode: newInt32(-1), - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "configMap.defaultMode", - }, - // Glusterfs - { - name: "valid Glusterfs", - vol: core.Volume{ - Name: "glusterfs", - VolumeSource: core.VolumeSource{ - Glusterfs: &core.GlusterfsVolumeSource{ - EndpointsName: "host1", - Path: "path", - ReadOnly: false, - }, - }, - }, - }, - { - name: "empty hosts", - vol: core.Volume{ - Name: "glusterfs", - VolumeSource: core.VolumeSource{ - Glusterfs: &core.GlusterfsVolumeSource{ - EndpointsName: "", - Path: "path", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "glusterfs.endpoints", - }, - { - name: "empty path", - vol: core.Volume{ - Name: "glusterfs", - VolumeSource: core.VolumeSource{ - Glusterfs: &core.GlusterfsVolumeSource{ - EndpointsName: "host", - Path: "", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "glusterfs.path", - }, - // Flocker - { - name: "valid Flocker -- datasetUUID", - vol: core.Volume{ - Name: "flocker", - VolumeSource: core.VolumeSource{ - Flocker: &core.FlockerVolumeSource{ - DatasetUUID: "d846b09d-223d-43df-ab5b-d6db2206a0e4", - }, - }, - }, - }, - { - name: "valid Flocker -- datasetName", - vol: core.Volume{ - Name: "flocker", - VolumeSource: core.VolumeSource{ - Flocker: &core.FlockerVolumeSource{ - DatasetName: "datasetName", - }, - }, - }, - }, - { - name: "both empty", - vol: core.Volume{ - Name: "flocker", - VolumeSource: core.VolumeSource{ - Flocker: &core.FlockerVolumeSource{ - DatasetName: "", - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "flocker", - }, - { - name: "both specified", - vol: core.Volume{ - Name: "flocker", - VolumeSource: core.VolumeSource{ - Flocker: &core.FlockerVolumeSource{ - DatasetName: "datasetName", - DatasetUUID: "d846b09d-223d-43df-ab5b-d6db2206a0e4", - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "flocker", - }, - { - name: "slash in flocker datasetName", - vol: core.Volume{ - Name: "flocker", - VolumeSource: core.VolumeSource{ - Flocker: &core.FlockerVolumeSource{ - DatasetName: "foo/bar", - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "flocker.datasetName", - errdetail: "must not contain '/'", - }, - // RBD - { - name: "valid RBD", - vol: core.Volume{ - Name: "rbd", - VolumeSource: core.VolumeSource{ - RBD: &core.RBDVolumeSource{ - CephMonitors: []string{"foo"}, - RBDImage: "bar", - FSType: "ext4", - }, - }, - }, - }, - { - name: "empty rbd monitors", - vol: core.Volume{ - Name: "rbd", - VolumeSource: core.VolumeSource{ - RBD: &core.RBDVolumeSource{ - CephMonitors: []string{}, - RBDImage: "bar", - FSType: "ext4", - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "rbd.monitors", - }, - { - name: "empty image", - vol: core.Volume{ - Name: "rbd", - VolumeSource: core.VolumeSource{ - RBD: &core.RBDVolumeSource{ - CephMonitors: []string{"foo"}, - RBDImage: "", - FSType: "ext4", - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "rbd.image", - }, - // Cinder - { - name: "valid Cinder", - vol: core.Volume{ - Name: "cinder", - VolumeSource: core.VolumeSource{ - Cinder: &core.CinderVolumeSource{ - VolumeID: "29ea5088-4f60-4757-962e-dba678767887", - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - }, - // CephFS - { - name: "valid CephFS", - vol: core.Volume{ - Name: "cephfs", - VolumeSource: core.VolumeSource{ - CephFS: &core.CephFSVolumeSource{ - Monitors: []string{"foo"}, - }, - }, - }, - }, - { - name: "empty cephfs monitors", - vol: core.Volume{ - Name: "cephfs", - VolumeSource: core.VolumeSource{ - CephFS: &core.CephFSVolumeSource{ - Monitors: []string{}, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "cephfs.monitors", - }, - // DownwardAPI - { - name: "valid DownwardAPI", - vol: core.Volume{ - Name: "downwardapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - Items: []core.DownwardAPIVolumeFile{ - { - Path: "labels", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }, - { - Path: "labels with subscript", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels['key']", - }, - }, - { - Path: "labels with complex subscript", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels['test.example.com/key']", - }, - }, - { - Path: "annotations", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.annotations", - }, - }, - { - Path: "annotations with subscript", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.annotations['key']", - }, - }, - { - Path: "annotations with complex subscript", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.annotations['TEST.EXAMPLE.COM/key']", - }, - }, - { - Path: "namespace", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.namespace", - }, - }, - { - Path: "name", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.name", - }, - }, - { - Path: "path/with/subdirs", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }, - { - Path: "path/./withdot", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }, - { - Path: "path/with/embedded..dotdot", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }, - { - Path: "path/with/leading/..dotdot", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }, - { - Path: "cpu_limit", - ResourceFieldRef: &core.ResourceFieldSelector{ - ContainerName: "test-container", - Resource: "limits.cpu", - }, - }, - { - Path: "cpu_request", - ResourceFieldRef: &core.ResourceFieldSelector{ - ContainerName: "test-container", - Resource: "requests.cpu", - }, - }, - { - Path: "memory_limit", - ResourceFieldRef: &core.ResourceFieldSelector{ - ContainerName: "test-container", - Resource: "limits.memory", - }, - }, - { - Path: "memory_request", - ResourceFieldRef: &core.ResourceFieldSelector{ - ContainerName: "test-container", - Resource: "requests.memory", - }, - }, - }, - }, - }, - }, - }, - { - name: "downapi valid defaultMode", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - DefaultMode: newInt32(0644), - }, - }, - }, - }, - { - name: "downapi valid item mode", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - Items: []core.DownwardAPIVolumeFile{{ - Mode: newInt32(0644), - Path: "path", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }}, - }, - }, - }, - }, - { - name: "downapi invalid positive item mode", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - Items: []core.DownwardAPIVolumeFile{{ - Mode: newInt32(01000), - Path: "path", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "downwardAPI.mode", - }, - { - name: "downapi invalid negative item mode", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - Items: []core.DownwardAPIVolumeFile{{ - Mode: newInt32(-1), - Path: "path", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "downwardAPI.mode", - }, - { - name: "downapi empty metatada path", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - Items: []core.DownwardAPIVolumeFile{{ - Path: "", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }}, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "downwardAPI.path", - }, - { - name: "downapi absolute path", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - Items: []core.DownwardAPIVolumeFile{{ - Path: "/absolutepath", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "downwardAPI.path", - }, - { - name: "downapi dot dot path", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - Items: []core.DownwardAPIVolumeFile{{ - Path: "../../passwd", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "downwardAPI.path", - errdetail: `must not contain '..'`, - }, - { - name: "downapi dot dot file name", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - Items: []core.DownwardAPIVolumeFile{{ - Path: "..badFileName", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "downwardAPI.path", - errdetail: `must not start with '..'`, - }, - { - name: "downapi dot dot first level dirent", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - Items: []core.DownwardAPIVolumeFile{{ - Path: "..badDirName/goodFileName", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - }}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "downwardAPI.path", - errdetail: `must not start with '..'`, - }, - { - name: "downapi fieldRef and ResourceFieldRef together", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - Items: []core.DownwardAPIVolumeFile{{ - Path: "test", - FieldRef: &core.ObjectFieldSelector{ - APIVersion: "v1", - FieldPath: "metadata.labels", - }, - ResourceFieldRef: &core.ResourceFieldSelector{ - ContainerName: "test-container", - Resource: "requests.memory", - }, - }}, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "downwardAPI", - errdetail: "fieldRef and resourceFieldRef can not be specified simultaneously", - }, - { - name: "downapi invalid positive defaultMode", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - DefaultMode: newInt32(01000), - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "downwardAPI.defaultMode", - }, - { - name: "downapi invalid negative defaultMode", - vol: core.Volume{ - Name: "downapi", - VolumeSource: core.VolumeSource{ - DownwardAPI: &core.DownwardAPIVolumeSource{ - DefaultMode: newInt32(-1), - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "downwardAPI.defaultMode", - }, - // FC - { - name: "FC valid targetWWNs and lun", - vol: core.Volume{ - Name: "fc", - VolumeSource: core.VolumeSource{ - FC: &core.FCVolumeSource{ - TargetWWNs: []string{"some_wwn"}, - Lun: newInt32(1), - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - }, - { - name: "FC valid wwids", - vol: core.Volume{ - Name: "fc", - VolumeSource: core.VolumeSource{ - FC: &core.FCVolumeSource{ - WWIDs: []string{"some_wwid"}, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - }, - { - name: "FC empty targetWWNs and wwids", - vol: core.Volume{ - Name: "fc", - VolumeSource: core.VolumeSource{ - FC: &core.FCVolumeSource{ - TargetWWNs: []string{}, - Lun: newInt32(1), - WWIDs: []string{}, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "fc.targetWWNs", - errdetail: "must specify either targetWWNs or wwids", - }, - { - name: "FC invalid: both targetWWNs and wwids simultaneously", - vol: core.Volume{ - Name: "fc", - VolumeSource: core.VolumeSource{ - FC: &core.FCVolumeSource{ - TargetWWNs: []string{"some_wwn"}, - Lun: newInt32(1), - WWIDs: []string{"some_wwid"}, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "fc.targetWWNs", - errdetail: "targetWWNs and wwids can not be specified simultaneously", - }, - { - name: "FC valid targetWWNs and empty lun", - vol: core.Volume{ - Name: "fc", - VolumeSource: core.VolumeSource{ - FC: &core.FCVolumeSource{ - TargetWWNs: []string{"wwn"}, - Lun: nil, - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "fc.lun", - errdetail: "lun is required if targetWWNs is specified", - }, - { - name: "FC valid targetWWNs and invalid lun", - vol: core.Volume{ - Name: "fc", - VolumeSource: core.VolumeSource{ - FC: &core.FCVolumeSource{ - TargetWWNs: []string{"wwn"}, - Lun: newInt32(256), - FSType: "ext4", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "fc.lun", - errdetail: validation.InclusiveRangeError(0, 255), - }, - // FlexVolume - { - name: "valid FlexVolume", - vol: core.Volume{ - Name: "flex-volume", - VolumeSource: core.VolumeSource{ - FlexVolume: &core.FlexVolumeSource{ - Driver: "kubernetes.io/blue", - FSType: "ext4", - }, - }, - }, - }, - // AzureFile - { - name: "valid AzureFile", - vol: core.Volume{ - Name: "azure-file", - VolumeSource: core.VolumeSource{ - AzureFile: &core.AzureFileVolumeSource{ - SecretName: "key", - ShareName: "share", - ReadOnly: false, - }, - }, - }, - }, - { - name: "AzureFile empty secret", - vol: core.Volume{ - Name: "azure-file", - VolumeSource: core.VolumeSource{ - AzureFile: &core.AzureFileVolumeSource{ - SecretName: "", - ShareName: "share", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "azureFile.secretName", - }, - { - name: "AzureFile empty share", - vol: core.Volume{ - Name: "azure-file", - VolumeSource: core.VolumeSource{ - AzureFile: &core.AzureFileVolumeSource{ - SecretName: "name", - ShareName: "", - ReadOnly: false, - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "azureFile.shareName", - }, - // Quobyte - { - name: "valid Quobyte", - vol: core.Volume{ - Name: "quobyte", - VolumeSource: core.VolumeSource{ - Quobyte: &core.QuobyteVolumeSource{ - Registry: "registry:7861", - Volume: "volume", - ReadOnly: false, - User: "root", - Group: "root", - }, - }, - }, - }, - { - name: "empty registry quobyte", - vol: core.Volume{ - Name: "quobyte", - VolumeSource: core.VolumeSource{ - Quobyte: &core.QuobyteVolumeSource{ - Volume: "/test", - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "quobyte.registry", - }, - { - name: "wrong format registry quobyte", - vol: core.Volume{ - Name: "quobyte", - VolumeSource: core.VolumeSource{ - Quobyte: &core.QuobyteVolumeSource{ - Registry: "registry7861", - Volume: "/test", - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "quobyte.registry", - }, - { - name: "wrong format multiple registries quobyte", - vol: core.Volume{ - Name: "quobyte", - VolumeSource: core.VolumeSource{ - Quobyte: &core.QuobyteVolumeSource{ - Registry: "registry:7861,reg2", - Volume: "/test", - }, - }, - }, - errtype: field.ErrorTypeInvalid, - errfield: "quobyte.registry", - }, - { - name: "empty volume quobyte", - vol: core.Volume{ - Name: "quobyte", - VolumeSource: core.VolumeSource{ - Quobyte: &core.QuobyteVolumeSource{ - Registry: "registry:7861", - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "quobyte.volume", - }, - // AzureDisk - { - name: "valid AzureDisk", - vol: core.Volume{ - Name: "azure-disk", - VolumeSource: core.VolumeSource{ - AzureDisk: &core.AzureDiskVolumeSource{ - DiskName: "foo", - DataDiskURI: "https://blob/vhds/bar.vhd", - }, - }, - }, - }, - { - name: "AzureDisk empty disk name", - vol: core.Volume{ - Name: "azure-disk", - VolumeSource: core.VolumeSource{ - AzureDisk: &core.AzureDiskVolumeSource{ - DiskName: "", - DataDiskURI: "https://blob/vhds/bar.vhd", - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "azureDisk.diskName", - }, - { - name: "AzureDisk empty disk uri", - vol: core.Volume{ - Name: "azure-disk", - VolumeSource: core.VolumeSource{ - AzureDisk: &core.AzureDiskVolumeSource{ - DiskName: "foo", - DataDiskURI: "", - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "azureDisk.diskURI", - }, - // ScaleIO - { - name: "valid scaleio volume", - vol: core.Volume{ - Name: "scaleio-volume", - VolumeSource: core.VolumeSource{ - ScaleIO: &core.ScaleIOVolumeSource{ - Gateway: "http://abcd/efg", - System: "test-system", - VolumeName: "test-vol-1", - }, - }, - }, - }, - { - name: "ScaleIO with empty name", - vol: core.Volume{ - Name: "scaleio-volume", - VolumeSource: core.VolumeSource{ - ScaleIO: &core.ScaleIOVolumeSource{ - Gateway: "http://abcd/efg", - System: "test-system", - VolumeName: "", - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "scaleIO.volumeName", - }, - { - name: "ScaleIO with empty gateway", - vol: core.Volume{ - Name: "scaleio-volume", - VolumeSource: core.VolumeSource{ - ScaleIO: &core.ScaleIOVolumeSource{ - Gateway: "", - System: "test-system", - VolumeName: "test-vol-1", - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "scaleIO.gateway", - }, - { - name: "ScaleIO with empty system", - vol: core.Volume{ - Name: "scaleio-volume", - VolumeSource: core.VolumeSource{ - ScaleIO: &core.ScaleIOVolumeSource{ - Gateway: "http://agc/efg/gateway", - System: "", - VolumeName: "test-vol-1", - }, - }, - }, - errtype: field.ErrorTypeRequired, - errfield: "scaleIO.system", - }, - } - - for i, tc := range testCases { - names, errs := ValidateVolumes([]core.Volume{tc.vol}, field.NewPath("field")) - if len(errs) > 0 && tc.errtype == "" { - t.Errorf("[%d: %q] unexpected error(s): %v", i, tc.name, errs) - } else if len(errs) > 1 { - t.Errorf("[%d: %q] expected 1 error, got %d: %v", i, tc.name, len(errs), errs) - } else if len(errs) == 0 && tc.errtype != "" { - t.Errorf("[%d: %q] expected error type %v", i, tc.name, tc.errtype) - } else if len(errs) == 1 { - if errs[0].Type != tc.errtype { - t.Errorf("[%d: %q] expected error type %v, got %v", i, tc.name, tc.errtype, errs[0].Type) - } else if !strings.HasSuffix(errs[0].Field, "."+tc.errfield) { - t.Errorf("[%d: %q] expected error on field %q, got %q", i, tc.name, tc.errfield, errs[0].Field) - } else if !strings.Contains(errs[0].Detail, tc.errdetail) { - t.Errorf("[%d: %q] expected error detail %q, got %q", i, tc.name, tc.errdetail, errs[0].Detail) - } - } else { - if len(names) != 1 || !IsMatchedVolume(tc.vol.Name, names) { - t.Errorf("[%d: %q] wrong names result: %v", i, tc.name, names) - } - } - } - - dupsCase := []core.Volume{ - {Name: "abc", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}, - {Name: "abc", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}, - } - _, errs := ValidateVolumes(dupsCase, field.NewPath("field")) - if len(errs) == 0 { - t.Errorf("expected error") - } else if len(errs) != 1 { - t.Errorf("expected 1 error, got %d: %v", len(errs), errs) - } else if errs[0].Type != field.ErrorTypeDuplicate { - t.Errorf("expected error type %v, got %v", field.ErrorTypeDuplicate, errs[0].Type) - } - - // Validate HugePages medium type for EmptyDir when HugePages feature is enabled/disabled - hugePagesCase := core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{Medium: core.StorageMediumHugePages}} - - // Enable alpha feature HugePages - err := utilfeature.DefaultFeatureGate.Set("HugePages=true") - if err != nil { - t.Errorf("Failed to enable feature gate for HugePages: %v", err) - } - if errs := validateVolumeSource(&hugePagesCase, field.NewPath("field").Index(0), "working"); len(errs) != 0 { - t.Errorf("Unexpected error when HugePages feature is enabled.") - } - - // Disable alpha feature HugePages - err = utilfeature.DefaultFeatureGate.Set("HugePages=false") - if err != nil { - t.Errorf("Failed to disable feature gate for HugePages: %v", err) - } - if errs := validateVolumeSource(&hugePagesCase, field.NewPath("field").Index(0), "failing"); len(errs) == 0 { - t.Errorf("Expected error when HugePages feature is disabled got nothing.") - } - -} - -func TestAlphaHugePagesIsolation(t *testing.T) { - successCases := []core.Pod{ - { // Basic fields. - ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"), - }, - Limits: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"), - }, - }, - }, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - } - failureCases := []core.Pod{ - { // Basic fields. - ObjectMeta: metav1.ObjectMeta{Name: "hugepages-requireCpuOrMemory", Namespace: "ns"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"), - }, - Limits: core.ResourceList{ - core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"), - }, - }, - }, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - { // Basic fields. - ObjectMeta: metav1.ObjectMeta{Name: "hugepages-shared", Namespace: "ns"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"), - }, - Limits: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("hugepages-2Mi"): resource.MustParse("2Gi"), - }, - }, - }, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - { // Basic fields. - ObjectMeta: metav1.ObjectMeta{Name: "hugepages-multiple", Namespace: "ns"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("hugepages-1Gi"): resource.MustParse("2Gi"), - }, - Limits: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"), - core.ResourceName("hugepages-1Gi"): resource.MustParse("2Gi"), - }, - }, - }, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - } - // Enable alpha feature HugePages - err := utilfeature.DefaultFeatureGate.Set("HugePages=true") - if err != nil { - t.Errorf("Failed to enable feature gate for HugePages: %v", err) - return - } - for i := range successCases { - pod := &successCases[i] - if errs := ValidatePod(pod); len(errs) != 0 { - t.Errorf("Unexpected error for case[%d], err: %v", i, errs) - } - } - for i := range failureCases { - pod := &failureCases[i] - if errs := ValidatePod(pod); len(errs) == 0 { - t.Errorf("Expected error for case[%d], pod: %v", i, pod.Name) - } - } - // Disable alpha feature HugePages - err = utilfeature.DefaultFeatureGate.Set("HugePages=false") - if err != nil { - t.Errorf("Failed to disable feature gate for HugePages: %v", err) - return - } - // Disable alpha feature HugePages and ensure all success cases fail - for i := range successCases { - pod := &successCases[i] - if errs := ValidatePod(pod); len(errs) == 0 { - t.Errorf("Expected error for case[%d], pod: %v", i, pod.Name) - } - } -} - -func TestAlphaPVCVolumeMode(t *testing.T) { - // Enable alpha feature BlockVolume for PVC - err := utilfeature.DefaultFeatureGate.Set("BlockVolume=true") - if err != nil { - t.Errorf("Failed to enable feature gate for BlockVolume: %v", err) - return - } - - block := core.PersistentVolumeBlock - file := core.PersistentVolumeFilesystem - fake := core.PersistentVolumeMode("fake") - empty := core.PersistentVolumeMode("") - - // Success Cases - successCasesPVC := map[string]*core.PersistentVolumeClaim{ - "valid block value": createTestVolModePVC(&block), - "valid filesystem value": createTestVolModePVC(&file), - "valid nil value": createTestVolModePVC(nil), - } - for k, v := range successCasesPVC { - if errs := ValidatePersistentVolumeClaim(v); len(errs) != 0 { - t.Errorf("expected success for %s", k) - } - } - - // Error Cases - errorCasesPVC := map[string]*core.PersistentVolumeClaim{ - "invalid value": createTestVolModePVC(&fake), - "empty value": createTestVolModePVC(&empty), - } - for k, v := range errorCasesPVC { - if errs := ValidatePersistentVolumeClaim(v); len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - } -} - -func TestAlphaPVVolumeMode(t *testing.T) { - // Enable alpha feature BlockVolume for PV - err := utilfeature.DefaultFeatureGate.Set("BlockVolume=true") - if err != nil { - t.Errorf("Failed to enable feature gate for BlockVolume: %v", err) - return - } - - block := core.PersistentVolumeBlock - file := core.PersistentVolumeFilesystem - fake := core.PersistentVolumeMode("fake") - empty := core.PersistentVolumeMode("") - - // Success Cases - successCasesPV := map[string]*core.PersistentVolume{ - "valid block value": createTestVolModePV(&block), - "valid filesystem value": createTestVolModePV(&file), - "valid nil value": createTestVolModePV(nil), - } - for k, v := range successCasesPV { - if errs := ValidatePersistentVolume(v); len(errs) != 0 { - t.Errorf("expected success for %s", k) - } - } - - // Error Cases - errorCasesPV := map[string]*core.PersistentVolume{ - "invalid value": createTestVolModePV(&fake), - "empty value": createTestVolModePV(&empty), - } - for k, v := range errorCasesPV { - if errs := ValidatePersistentVolume(v); len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - } -} - -func createTestVolModePVC(vmode *core.PersistentVolumeMode) *core.PersistentVolumeClaim { - validName := "valid-storage-class" - - pvc := core.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "default", - }, - Spec: core.PersistentVolumeClaimSpec{ - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - StorageClassName: &validName, - VolumeMode: vmode, - }, - } - return &pvc -} - -func createTestVolModePV(vmode *core.PersistentVolumeMode) *core.PersistentVolume { - - // PersistentVolume with VolumeMode set (valid and invalid) - pv := core.PersistentVolume{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "", - }, - Spec: core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - StorageClassName: "test-storage-class", - VolumeMode: vmode, - }, - } - return &pv -} - -func createTestPV() *core.PersistentVolume { - - // PersistentVolume with VolumeMode set (valid and invalid) - pv := core.PersistentVolume{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "", - }, - Spec: core.PersistentVolumeSpec{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce}, - PersistentVolumeSource: core.PersistentVolumeSource{ - HostPath: &core.HostPathVolumeSource{ - Path: "/foo", - Type: newHostPathType(string(core.HostPathDirectory)), - }, - }, - StorageClassName: "test-storage-class", - }, - } - return &pv -} - -func TestAlphaLocalStorageCapacityIsolation(t *testing.T) { - - testCases := []core.VolumeSource{ - {EmptyDir: &core.EmptyDirVolumeSource{SizeLimit: resource.NewQuantity(int64(5), resource.BinarySI)}}, - } - // Enable alpha feature LocalStorageCapacityIsolation - err := utilfeature.DefaultFeatureGate.Set("LocalStorageCapacityIsolation=true") - if err != nil { - t.Errorf("Failed to enable feature gate for LocalStorageCapacityIsolation: %v", err) - return - } - for _, tc := range testCases { - if errs := validateVolumeSource(&tc, field.NewPath("spec"), "tmpvol"); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - // Disable alpha feature LocalStorageCapacityIsolation - err = utilfeature.DefaultFeatureGate.Set("LocalStorageCapacityIsolation=false") - if err != nil { - t.Errorf("Failed to disable feature gate for LocalStorageCapacityIsolation: %v", err) - return - } - for _, tc := range testCases { - if errs := validateVolumeSource(&tc, field.NewPath("spec"), "tmpvol"); len(errs) == 0 { - t.Errorf("expected failure: %v", errs) - } - } - - containerLimitCase := core.ResourceRequirements{ - Limits: core.ResourceList{ - core.ResourceEphemeralStorage: *resource.NewMilliQuantity( - int64(40000), - resource.BinarySI), - }, - } - // Enable alpha feature LocalStorageCapacityIsolation - err = utilfeature.DefaultFeatureGate.Set("LocalStorageCapacityIsolation=true") - if err != nil { - t.Errorf("Failed to enable feature gate for LocalStorageCapacityIsolation: %v", err) - return - } - if errs := ValidateResourceRequirements(&containerLimitCase, field.NewPath("resources")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - // Disable alpha feature LocalStorageCapacityIsolation - err = utilfeature.DefaultFeatureGate.Set("LocalStorageCapacityIsolation=false") - if err != nil { - t.Errorf("Failed to disable feature gate for LocalStorageCapacityIsolation: %v", err) - return - } - if errs := ValidateResourceRequirements(&containerLimitCase, field.NewPath("resources")); len(errs) == 0 { - t.Errorf("expected failure: %v", errs) - } - -} - -func TestValidateResourceQuotaWithAlphaLocalStorageCapacityIsolation(t *testing.T) { - spec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourceCPU: resource.MustParse("100"), - core.ResourceMemory: resource.MustParse("10000"), - core.ResourceRequestsCPU: resource.MustParse("100"), - core.ResourceRequestsMemory: resource.MustParse("10000"), - core.ResourceLimitsCPU: resource.MustParse("100"), - core.ResourceLimitsMemory: resource.MustParse("10000"), - core.ResourcePods: resource.MustParse("10"), - core.ResourceServices: resource.MustParse("0"), - core.ResourceReplicationControllers: resource.MustParse("10"), - core.ResourceQuotas: resource.MustParse("10"), - core.ResourceConfigMaps: resource.MustParse("10"), - core.ResourceSecrets: resource.MustParse("10"), - core.ResourceEphemeralStorage: resource.MustParse("10000"), - core.ResourceRequestsEphemeralStorage: resource.MustParse("10000"), - core.ResourceLimitsEphemeralStorage: resource.MustParse("10000"), - }, - } - resourceQuota := &core.ResourceQuota{ - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: spec, - } - - // Enable alpha feature LocalStorageCapacityIsolation - err := utilfeature.DefaultFeatureGate.Set("LocalStorageCapacityIsolation=true") - if err != nil { - t.Errorf("Failed to enable feature gate for LocalStorageCapacityIsolation: %v", err) - return - } - if errs := ValidateResourceQuota(resourceQuota); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - // Disable alpha feature LocalStorageCapacityIsolation - err = utilfeature.DefaultFeatureGate.Set("LocalStorageCapacityIsolation=false") - if err != nil { - t.Errorf("Failed to disable feature gate for LocalStorageCapacityIsolation: %v", err) - return - } - errs := ValidateResourceQuota(resourceQuota) - if len(errs) == 0 { - t.Errorf("expected failure for %s", resourceQuota.Name) - } - expectedErrMes := "ResourceEphemeralStorage field disabled by feature-gate for ResourceQuota" - for i := range errs { - if !strings.Contains(errs[i].Detail, expectedErrMes) { - t.Errorf("[%s]: expected error detail either empty or %s, got %s", resourceQuota.Name, expectedErrMes, errs[i].Detail) - } - } -} - -func TestValidatePorts(t *testing.T) { - successCase := []core.ContainerPort{ - {Name: "abc", ContainerPort: 80, HostPort: 80, Protocol: "TCP"}, - {Name: "easy", ContainerPort: 82, Protocol: "TCP"}, - {Name: "as", ContainerPort: 83, Protocol: "UDP"}, - {Name: "do-re-me", ContainerPort: 84, Protocol: "UDP"}, - {ContainerPort: 85, Protocol: "TCP"}, - } - if errs := validateContainerPorts(successCase, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - nonCanonicalCase := []core.ContainerPort{ - {ContainerPort: 80, Protocol: "TCP"}, - } - if errs := validateContainerPorts(nonCanonicalCase, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - errorCases := map[string]struct { - P []core.ContainerPort - T field.ErrorType - F string - D string - }{ - "name > 15 characters": { - []core.ContainerPort{{Name: strings.Repeat("a", 16), ContainerPort: 80, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "name", "15", - }, - "name contains invalid characters": { - []core.ContainerPort{{Name: "a.b.c", ContainerPort: 80, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "name", "alpha-numeric", - }, - "name is a number": { - []core.ContainerPort{{Name: "80", ContainerPort: 80, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "name", "at least one letter", - }, - "name not unique": { - []core.ContainerPort{ - {Name: "abc", ContainerPort: 80, Protocol: "TCP"}, - {Name: "abc", ContainerPort: 81, Protocol: "TCP"}, - }, - field.ErrorTypeDuplicate, - "[1].name", "", - }, - "zero container port": { - []core.ContainerPort{{ContainerPort: 0, Protocol: "TCP"}}, - field.ErrorTypeRequired, - "containerPort", "", - }, - "invalid container port": { - []core.ContainerPort{{ContainerPort: 65536, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "containerPort", "between", - }, - "invalid host port": { - []core.ContainerPort{{ContainerPort: 80, HostPort: 65536, Protocol: "TCP"}}, - field.ErrorTypeInvalid, - "hostPort", "between", - }, - "invalid protocol case": { - []core.ContainerPort{{ContainerPort: 80, Protocol: "tcp"}}, - field.ErrorTypeNotSupported, - "protocol", `supported values: "TCP", "UDP"`, - }, - "invalid protocol": { - []core.ContainerPort{{ContainerPort: 80, Protocol: "ICMP"}}, - field.ErrorTypeNotSupported, - "protocol", `supported values: "TCP", "UDP"`, - }, - "protocol required": { - []core.ContainerPort{{Name: "abc", ContainerPort: 80}}, - field.ErrorTypeRequired, - "protocol", "", - }, - } - for k, v := range errorCases { - errs := validateContainerPorts(v.P, field.NewPath("field")) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - if errs[i].Type != v.T { - t.Errorf("%s: expected error to have type %q: %q", k, v.T, errs[i].Type) - } - if !strings.Contains(errs[i].Field, v.F) { - t.Errorf("%s: expected error field %q: %q", k, v.F, errs[i].Field) - } - if !strings.Contains(errs[i].Detail, v.D) { - t.Errorf("%s: expected error detail %q, got %q", k, v.D, errs[i].Detail) - } - } - } -} - -func TestLocalStorageEnvWithFeatureGate(t *testing.T) { - testCases := []core.EnvVar{ - { - Name: "ephemeral-storage-limits", - ValueFrom: &core.EnvVarSource{ - ResourceFieldRef: &core.ResourceFieldSelector{ - ContainerName: "test-container", - Resource: "limits.ephemeral-storage", - }, - }, - }, - { - Name: "ephemeral-storage-requests", - ValueFrom: &core.EnvVarSource{ - ResourceFieldRef: &core.ResourceFieldSelector{ - ContainerName: "test-container", - Resource: "requests.ephemeral-storage", - }, - }, - }, - } - // Enable alpha feature LocalStorageCapacityIsolation - err := utilfeature.DefaultFeatureGate.Set("LocalStorageCapacityIsolation=true") - if err != nil { - t.Errorf("Failed to enable feature gate for LocalStorageCapacityIsolation: %v", err) - return - } - for _, testCase := range testCases { - if errs := validateEnvVarValueFrom(testCase, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success, got: %v", errs) - } - } - - // Disable alpha feature LocalStorageCapacityIsolation - err = utilfeature.DefaultFeatureGate.Set("LocalStorageCapacityIsolation=false") - if err != nil { - t.Errorf("Failed to disable feature gate for LocalStorageCapacityIsolation: %v", err) - return - } - for _, testCase := range testCases { - if errs := validateEnvVarValueFrom(testCase, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %v", testCase.Name) - } - } -} - -func TestValidateEnv(t *testing.T) { - successCase := []core.EnvVar{ - {Name: "abc", Value: "value"}, - {Name: "ABC", Value: "value"}, - {Name: "AbC_123", Value: "value"}, - {Name: "abc", Value: ""}, - {Name: "a.b.c", Value: "value"}, - {Name: "a-b-c", Value: "value"}, - { - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "metadata.annotations['key']", - }, - }, - }, - { - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "metadata.labels['key']", - }, - }, - }, - { - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "metadata.name", - }, - }, - }, - { - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "metadata.namespace", - }, - }, - }, - { - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "metadata.uid", - }, - }, - }, - { - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "spec.nodeName", - }, - }, - }, - { - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "spec.serviceAccountName", - }, - }, - }, - { - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "status.hostIP", - }, - }, - }, - { - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "status.podIP", - }, - }, - }, - { - Name: "secret_value", - ValueFrom: &core.EnvVarSource{ - SecretKeyRef: &core.SecretKeySelector{ - LocalObjectReference: core.LocalObjectReference{ - Name: "some-secret", - }, - Key: "secret-key", - }, - }, - }, - { - Name: "ENV_VAR_1", - ValueFrom: &core.EnvVarSource{ - ConfigMapKeyRef: &core.ConfigMapKeySelector{ - LocalObjectReference: core.LocalObjectReference{ - Name: "some-config-map", - }, - Key: "some-key", - }, - }, - }, - } - if errs := ValidateEnv(successCase, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success, got: %v", errs) - } - - errorCases := []struct { - name string - envs []core.EnvVar - expectedError string - }{ - { - name: "zero-length name", - envs: []core.EnvVar{{Name: ""}}, - expectedError: "[0].name: Required value", - }, - { - name: "illegal character", - envs: []core.EnvVar{{Name: "a!b"}}, - expectedError: `[0].name: Invalid value: "a!b": ` + envVarNameErrMsg, - }, - { - name: "dot only", - envs: []core.EnvVar{{Name: "."}}, - expectedError: `[0].name: Invalid value: ".": must not be`, - }, - { - name: "double dots only", - envs: []core.EnvVar{{Name: ".."}}, - expectedError: `[0].name: Invalid value: "..": must not be`, - }, - { - name: "leading double dots", - envs: []core.EnvVar{{Name: "..abc"}}, - expectedError: `[0].name: Invalid value: "..abc": must not start with`, - }, - { - name: "value and valueFrom specified", - envs: []core.EnvVar{{ - Name: "abc", - Value: "foo", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "metadata.name", - }, - }, - }}, - expectedError: "[0].valueFrom: Invalid value: \"\": may not be specified when `value` is not empty", - }, - { - name: "valueFrom without a source", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{}, - }}, - expectedError: "[0].valueFrom: Invalid value: \"\": must specify one of: `fieldRef`, `resourceFieldRef`, `configMapKeyRef` or `secretKeyRef`", - }, - { - name: "valueFrom.fieldRef and valueFrom.secretKeyRef specified", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "metadata.name", - }, - SecretKeyRef: &core.SecretKeySelector{ - LocalObjectReference: core.LocalObjectReference{ - Name: "a-secret", - }, - Key: "a-key", - }, - }, - }}, - expectedError: "[0].valueFrom: Invalid value: \"\": may not have more than one field specified at a time", - }, - { - name: "valueFrom.fieldRef and valueFrom.configMapKeyRef set", - envs: []core.EnvVar{{ - Name: "some_var_name", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "metadata.name", - }, - ConfigMapKeyRef: &core.ConfigMapKeySelector{ - LocalObjectReference: core.LocalObjectReference{ - Name: "some-config-map", - }, - Key: "some-key", - }, - }, - }}, - expectedError: `[0].valueFrom: Invalid value: "": may not have more than one field specified at a time`, - }, - { - name: "valueFrom.fieldRef and valueFrom.secretKeyRef specified", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - FieldPath: "metadata.name", - }, - SecretKeyRef: &core.SecretKeySelector{ - LocalObjectReference: core.LocalObjectReference{ - Name: "a-secret", - }, - Key: "a-key", - }, - ConfigMapKeyRef: &core.ConfigMapKeySelector{ - LocalObjectReference: core.LocalObjectReference{ - Name: "some-config-map", - }, - Key: "some-key", - }, - }, - }}, - expectedError: `[0].valueFrom: Invalid value: "": may not have more than one field specified at a time`, - }, - { - name: "valueFrom.secretKeyRef.name invalid", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - SecretKeyRef: &core.SecretKeySelector{ - LocalObjectReference: core.LocalObjectReference{ - Name: "$%^&*#", - }, - Key: "a-key", - }, - }, - }}, - }, - { - name: "valueFrom.configMapKeyRef.name invalid", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - ConfigMapKeyRef: &core.ConfigMapKeySelector{ - LocalObjectReference: core.LocalObjectReference{ - Name: "$%^&*#", - }, - Key: "some-key", - }, - }, - }}, - }, - { - name: "missing FieldPath on ObjectFieldSelector", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.fieldPath: Required value`, - }, - { - name: "missing APIVersion on ObjectFieldSelector", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - FieldPath: "metadata.name", - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.apiVersion: Required value`, - }, - { - name: "invalid fieldPath", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - FieldPath: "metadata.whoops", - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.fieldPath: Invalid value: "metadata.whoops": error converting fieldPath`, - }, - { - name: "metadata.name with subscript", - envs: []core.EnvVar{{ - Name: "labels", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - FieldPath: "metadata.name['key']", - APIVersion: "v1", - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.fieldPath: Invalid value: "metadata.name['key']": error converting fieldPath: field label does not support subscript`, - }, - { - name: "metadata.labels without subscript", - envs: []core.EnvVar{{ - Name: "labels", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - FieldPath: "metadata.labels", - APIVersion: "v1", - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.fieldPath: Unsupported value: "metadata.labels": supported values: "metadata.name", "metadata.namespace", "metadata.uid", "spec.nodeName", "spec.serviceAccountName", "status.hostIP", "status.podIP"`, - }, - { - name: "metadata.annotations without subscript", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - FieldPath: "metadata.annotations", - APIVersion: "v1", - }, - }, - }}, - expectedError: `[0].valueFrom.fieldRef.fieldPath: Unsupported value: "metadata.annotations": supported values: "metadata.name", "metadata.namespace", "metadata.uid", "spec.nodeName", "spec.serviceAccountName", "status.hostIP", "status.podIP"`, - }, - { - name: "metadata.annotations with invalid key", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - FieldPath: "metadata.annotations['invalid~key']", - APIVersion: "v1", - }, - }, - }}, - expectedError: `field[0].valueFrom.fieldRef: Invalid value: "invalid~key"`, - }, - { - name: "metadata.labels with invalid key", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - FieldPath: "metadata.labels['Www.k8s.io/test']", - APIVersion: "v1", - }, - }, - }}, - expectedError: `field[0].valueFrom.fieldRef: Invalid value: "Www.k8s.io/test"`, - }, - { - name: "unsupported fieldPath", - envs: []core.EnvVar{{ - Name: "abc", - ValueFrom: &core.EnvVarSource{ - FieldRef: &core.ObjectFieldSelector{ - FieldPath: "status.phase", - APIVersion: legacyscheme.Registry.GroupOrDie(core.GroupName).GroupVersion.String(), - }, - }, - }}, - expectedError: `valueFrom.fieldRef.fieldPath: Unsupported value: "status.phase": supported values: "metadata.name", "metadata.namespace", "metadata.uid", "spec.nodeName", "spec.serviceAccountName", "status.hostIP", "status.podIP"`, - }, - } - for _, tc := range errorCases { - if errs := ValidateEnv(tc.envs, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %s", tc.name) - } else { - for i := range errs { - str := errs[i].Error() - if str != "" && !strings.Contains(str, tc.expectedError) { - t.Errorf("%s: expected error detail either empty or %q, got %q", tc.name, tc.expectedError, str) - } - } - } - } -} - -func TestValidateEnvFrom(t *testing.T) { - successCase := []core.EnvFromSource{ - { - ConfigMapRef: &core.ConfigMapEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "abc"}, - }, - }, - { - Prefix: "pre_", - ConfigMapRef: &core.ConfigMapEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "abc"}, - }, - }, - { - Prefix: "a.b", - ConfigMapRef: &core.ConfigMapEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "abc"}, - }, - }, - { - SecretRef: &core.SecretEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "abc"}, - }, - }, - { - Prefix: "pre_", - SecretRef: &core.SecretEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "abc"}, - }, - }, - { - Prefix: "a.b", - SecretRef: &core.SecretEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "abc"}, - }, - }, - } - if errs := ValidateEnvFrom(successCase, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - errorCases := []struct { - name string - envs []core.EnvFromSource - expectedError string - }{ - { - name: "zero-length name", - envs: []core.EnvFromSource{ - { - ConfigMapRef: &core.ConfigMapEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: ""}}, - }, - }, - expectedError: "field[0].configMapRef.name: Required value", - }, - { - name: "invalid name", - envs: []core.EnvFromSource{ - { - ConfigMapRef: &core.ConfigMapEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "$"}}, - }, - }, - expectedError: "field[0].configMapRef.name: Invalid value", - }, - { - name: "invalid prefix", - envs: []core.EnvFromSource{ - { - Prefix: "a!b", - ConfigMapRef: &core.ConfigMapEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "abc"}}, - }, - }, - expectedError: `field[0].prefix: Invalid value: "a!b": ` + envVarNameErrMsg, - }, - { - name: "zero-length name", - envs: []core.EnvFromSource{ - { - SecretRef: &core.SecretEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: ""}}, - }, - }, - expectedError: "field[0].secretRef.name: Required value", - }, - { - name: "invalid name", - envs: []core.EnvFromSource{ - { - SecretRef: &core.SecretEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "&"}}, - }, - }, - expectedError: "field[0].secretRef.name: Invalid value", - }, - { - name: "invalid prefix", - envs: []core.EnvFromSource{ - { - Prefix: "a!b", - SecretRef: &core.SecretEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "abc"}}, - }, - }, - expectedError: `field[0].prefix: Invalid value: "a!b": ` + envVarNameErrMsg, - }, - { - name: "no refs", - envs: []core.EnvFromSource{ - {}, - }, - expectedError: "field: Invalid value: \"\": must specify one of: `configMapRef` or `secretRef`", - }, - { - name: "multiple refs", - envs: []core.EnvFromSource{ - { - SecretRef: &core.SecretEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "abc"}}, - ConfigMapRef: &core.ConfigMapEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "abc"}}, - }, - }, - expectedError: "field: Invalid value: \"\": may not have more than one field specified at a time", - }, - { - name: "invalid secret ref name", - envs: []core.EnvFromSource{ - { - SecretRef: &core.SecretEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "$%^&*#"}}, - }, - }, - expectedError: "field[0].secretRef.name: Invalid value: \"$%^&*#\": " + dnsSubdomainLabelErrMsg, - }, - { - name: "invalid config ref name", - envs: []core.EnvFromSource{ - { - ConfigMapRef: &core.ConfigMapEnvSource{ - LocalObjectReference: core.LocalObjectReference{Name: "$%^&*#"}}, - }, - }, - expectedError: "field[0].configMapRef.name: Invalid value: \"$%^&*#\": " + dnsSubdomainLabelErrMsg, - }, - } - for _, tc := range errorCases { - if errs := ValidateEnvFrom(tc.envs, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %s", tc.name) - } else { - for i := range errs { - str := errs[i].Error() - if str != "" && !strings.Contains(str, tc.expectedError) { - t.Errorf("%s: expected error detail either empty or %q, got %q", tc.name, tc.expectedError, str) - } - } - } - } -} - -func TestValidateVolumeMounts(t *testing.T) { - volumes := []core.Volume{ - {Name: "abc", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim1"}}}, - {Name: "abc-123", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim2"}}}, - {Name: "123", VolumeSource: core.VolumeSource{HostPath: &core.HostPathVolumeSource{Path: "/foo/baz", Type: newHostPathType(string(core.HostPathUnset))}}}, - } - vols, v1err := ValidateVolumes(volumes, field.NewPath("field")) - if len(v1err) > 0 { - t.Errorf("Invalid test volume - expected success %v", v1err) - return - } - container := core.Container{ - SecurityContext: nil, - } - propagation := core.MountPropagationBidirectional - - successCase := []core.VolumeMount{ - {Name: "abc", MountPath: "/foo"}, - {Name: "123", MountPath: "/bar"}, - {Name: "abc-123", MountPath: "/baz"}, - {Name: "abc-123", MountPath: "/baa", SubPath: ""}, - {Name: "abc-123", MountPath: "/bab", SubPath: "baz"}, - {Name: "abc-123", MountPath: "d:", SubPath: ""}, - {Name: "abc-123", MountPath: "F:", SubPath: ""}, - {Name: "abc-123", MountPath: "G:\\mount", SubPath: ""}, - {Name: "abc-123", MountPath: "/bac", SubPath: ".baz"}, - {Name: "abc-123", MountPath: "/bad", SubPath: "..baz"}, - } - goodVolumeDevices := []core.VolumeDevice{ - {Name: "xyz", DevicePath: "/foofoo"}, - {Name: "uvw", DevicePath: "/foofoo/share/test"}, - } - if errs := ValidateVolumeMounts(successCase, GetVolumeDeviceMap(goodVolumeDevices), vols, &container, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - errorCases := map[string][]core.VolumeMount{ - "empty name": {{Name: "", MountPath: "/foo"}}, - "name not found": {{Name: "", MountPath: "/foo"}}, - "empty mountpath": {{Name: "abc", MountPath: ""}}, - "mountpath collision": {{Name: "foo", MountPath: "/path/a"}, {Name: "bar", MountPath: "/path/a"}}, - "absolute subpath": {{Name: "abc", MountPath: "/bar", SubPath: "/baz"}}, - "subpath in ..": {{Name: "abc", MountPath: "/bar", SubPath: "../baz"}}, - "subpath contains ..": {{Name: "abc", MountPath: "/bar", SubPath: "baz/../bat"}}, - "subpath ends in ..": {{Name: "abc", MountPath: "/bar", SubPath: "./.."}}, - "disabled MountPropagation feature gate": {{Name: "abc", MountPath: "/bar", MountPropagation: &propagation}}, - "name exists in volumeDevice": {{Name: "xyz", MountPath: "/bar"}}, - "mountpath exists in volumeDevice": {{Name: "uvw", MountPath: "/mnt/exists"}}, - "both exist in volumeDevice": {{Name: "xyz", MountPath: "/mnt/exists"}}, - } - badVolumeDevice := []core.VolumeDevice{ - {Name: "xyz", DevicePath: "/mnt/exists"}, - } - - for k, v := range errorCases { - if errs := ValidateVolumeMounts(v, GetVolumeDeviceMap(badVolumeDevice), vols, &container, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - } -} - -func TestValidateDisabledSubpath(t *testing.T) { - utilfeature.DefaultFeatureGate.Set("VolumeSubpath=false") - defer utilfeature.DefaultFeatureGate.Set("VolumeSubpath=true") - - volumes := []core.Volume{ - {Name: "abc", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim1"}}}, - {Name: "abc-123", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim2"}}}, - {Name: "123", VolumeSource: core.VolumeSource{HostPath: &core.HostPathVolumeSource{Path: "/foo/baz", Type: newHostPathType(string(core.HostPathUnset))}}}, - } - vols, v1err := ValidateVolumes(volumes, field.NewPath("field")) - if len(v1err) > 0 { - t.Errorf("Invalid test volume - expected success %v", v1err) - return - } - - container := core.Container{ - SecurityContext: nil, - } - - goodVolumeDevices := []core.VolumeDevice{ - {Name: "xyz", DevicePath: "/foofoo"}, - {Name: "uvw", DevicePath: "/foofoo/share/test"}, - } - - cases := map[string]struct { - mounts []core.VolumeMount - expectError bool - }{ - "subpath not specified": { - []core.VolumeMount{ - { - Name: "abc-123", - MountPath: "/bab", - }, - }, - false, - }, - "subpath specified": { - []core.VolumeMount{ - { - Name: "abc-123", - MountPath: "/bab", - SubPath: "baz", - }, - }, - true, - }, - } - - for name, test := range cases { - errs := ValidateVolumeMounts(test.mounts, GetVolumeDeviceMap(goodVolumeDevices), vols, &container, field.NewPath("field")) - - if len(errs) != 0 && !test.expectError { - t.Errorf("test %v failed: %+v", name, errs) - } - - if len(errs) == 0 && test.expectError { - t.Errorf("test %v failed, expected error", name) - } - } -} - -func TestValidateMountPropagation(t *testing.T) { - bTrue := true - bFalse := false - privilegedContainer := &core.Container{ - SecurityContext: &core.SecurityContext{ - Privileged: &bTrue, - }, - } - nonPrivilegedContainer := &core.Container{ - SecurityContext: &core.SecurityContext{ - Privileged: &bFalse, - }, - } - defaultContainer := &core.Container{} - - propagationBidirectional := core.MountPropagationBidirectional - propagationHostToContainer := core.MountPropagationHostToContainer - propagationInvalid := core.MountPropagationMode("invalid") - - tests := []struct { - mount core.VolumeMount - container *core.Container - expectError bool - }{ - { - // implicitly non-privileged container + no propagation - core.VolumeMount{Name: "foo", MountPath: "/foo"}, - defaultContainer, - false, - }, - { - // implicitly non-privileged container + HostToContainer - core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationHostToContainer}, - defaultContainer, - false, - }, - { - // error: implicitly non-privileged container + Bidirectional - core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationBidirectional}, - defaultContainer, - true, - }, - { - // explicitly non-privileged container + no propagation - core.VolumeMount{Name: "foo", MountPath: "/foo"}, - nonPrivilegedContainer, - false, - }, - { - // explicitly non-privileged container + HostToContainer - core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationHostToContainer}, - nonPrivilegedContainer, - false, - }, - { - // explicitly non-privileged container + HostToContainer - core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationBidirectional}, - nonPrivilegedContainer, - true, - }, - { - // privileged container + no propagation - core.VolumeMount{Name: "foo", MountPath: "/foo"}, - privilegedContainer, - false, - }, - { - // privileged container + HostToContainer - core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationHostToContainer}, - privilegedContainer, - false, - }, - { - // privileged container + Bidirectional - core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationBidirectional}, - privilegedContainer, - false, - }, - { - // error: privileged container + invalid mount propagation - core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationInvalid}, - privilegedContainer, - true, - }, - { - // no container + Bidirectional - core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationBidirectional}, - nil, - false, - }, - } - - // Enable MountPropagation for this test - priorityEnabled := utilfeature.DefaultFeatureGate.Enabled("MountPropagation") - defer func() { - var err error - // restoring the old value - if priorityEnabled { - err = utilfeature.DefaultFeatureGate.Set("MountPropagation=true") - } else { - err = utilfeature.DefaultFeatureGate.Set("MountPropagation=false") - } - if err != nil { - t.Errorf("Failed to restore feature gate for MountPropagation: %v", err) - } - }() - err := utilfeature.DefaultFeatureGate.Set("MountPropagation=true") - if err != nil { - t.Errorf("Failed to enable feature gate for MountPropagation: %v", err) - return - } - - volumes := []core.Volume{ - {Name: "foo", VolumeSource: core.VolumeSource{HostPath: &core.HostPathVolumeSource{Path: "/foo/baz", Type: newHostPathType(string(core.HostPathUnset))}}}, - } - vols2, v2err := ValidateVolumes(volumes, field.NewPath("field")) - if len(v2err) > 0 { - t.Errorf("Invalid test volume - expected success %v", v2err) - return - } - for i, test := range tests { - errs := ValidateVolumeMounts([]core.VolumeMount{test.mount}, nil, vols2, test.container, field.NewPath("field")) - if test.expectError && len(errs) == 0 { - t.Errorf("test %d expected error, got none", i) - } - if !test.expectError && len(errs) != 0 { - t.Errorf("test %d expected success, got error: %v", i, errs) - } - } -} - -func TestAlphaValidateVolumeDevices(t *testing.T) { - volumes := []core.Volume{ - {Name: "abc", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim1"}}}, - {Name: "abc-123", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim2"}}}, - {Name: "def", VolumeSource: core.VolumeSource{HostPath: &core.HostPathVolumeSource{Path: "/foo/baz", Type: newHostPathType(string(core.HostPathUnset))}}}, - } - - vols, v1err := ValidateVolumes(volumes, field.NewPath("field")) - if len(v1err) > 0 { - t.Errorf("Invalid test volumes - expected success %v", v1err) - return - } - - disabledAlphaVolDevice := []core.VolumeDevice{ - {Name: "abc", DevicePath: "/foo"}, - } - - successCase := []core.VolumeDevice{ - {Name: "abc", DevicePath: "/foo"}, - {Name: "abc-123", DevicePath: "/usr/share/test"}, - } - goodVolumeMounts := []core.VolumeMount{ - {Name: "xyz", MountPath: "/foofoo"}, - {Name: "ghi", MountPath: "/foo/usr/share/test"}, - } - - errorCases := map[string][]core.VolumeDevice{ - "empty name": {{Name: "", DevicePath: "/foo"}}, - "duplicate name": {{Name: "abc", DevicePath: "/foo"}, {Name: "abc", DevicePath: "/foo/bar"}}, - "name not found": {{Name: "not-found", DevicePath: "/usr/share/test"}}, - "name found but invalid source": {{Name: "def", DevicePath: "/usr/share/test"}}, - "empty devicepath": {{Name: "abc", DevicePath: ""}}, - "relative devicepath": {{Name: "abc-123", DevicePath: "baz"}}, - "duplicate devicepath": {{Name: "abc", DevicePath: "/foo"}, {Name: "abc-123", DevicePath: "/foo"}}, - "no backsteps": {{Name: "def", DevicePath: "/baz/../"}}, - "name exists in volumemounts": {{Name: "abc", DevicePath: "/baz/../"}}, - "path exists in volumemounts": {{Name: "xyz", DevicePath: "/this/path/exists"}}, - "both exist in volumemounts": {{Name: "abc", DevicePath: "/this/path/exists"}}, - } - badVolumeMounts := []core.VolumeMount{ - {Name: "abc", MountPath: "/foo"}, - {Name: "abc-123", MountPath: "/this/path/exists"}, - } - - // enable Alpha BlockVolume - err1 := utilfeature.DefaultFeatureGate.Set("BlockVolume=true") - if err1 != nil { - t.Errorf("Failed to enable feature gate for BlockVolume: %v", err1) - return - } - // Success Cases: - // Validate normal success cases - only PVC volumeSource - if errs := ValidateVolumeDevices(successCase, GetVolumeMountMap(goodVolumeMounts), vols, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - // Error Cases: - // Validate normal error cases - only PVC volumeSource - for k, v := range errorCases { - if errs := ValidateVolumeDevices(v, GetVolumeMountMap(badVolumeMounts), vols, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - } - - // disable Alpha BlockVolume - err2 := utilfeature.DefaultFeatureGate.Set("BlockVolume=false") - if err2 != nil { - t.Errorf("Failed to disable feature gate for BlockVolume: %v", err2) - return - } - if errs := ValidateVolumeDevices(disabledAlphaVolDevice, GetVolumeMountMap(goodVolumeMounts), vols, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure: %v", errs) - } -} - -func TestValidateProbe(t *testing.T) { - handler := core.Handler{Exec: &core.ExecAction{Command: []string{"echo"}}} - // These fields must be positive. - positiveFields := [...]string{"InitialDelaySeconds", "TimeoutSeconds", "PeriodSeconds", "SuccessThreshold", "FailureThreshold"} - successCases := []*core.Probe{nil} - for _, field := range positiveFields { - probe := &core.Probe{Handler: handler} - reflect.ValueOf(probe).Elem().FieldByName(field).SetInt(10) - successCases = append(successCases, probe) - } - - for _, p := range successCases { - if errs := validateProbe(p, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []*core.Probe{{TimeoutSeconds: 10, InitialDelaySeconds: 10}} - for _, field := range positiveFields { - probe := &core.Probe{Handler: handler} - reflect.ValueOf(probe).Elem().FieldByName(field).SetInt(-10) - errorCases = append(errorCases, probe) - } - for _, p := range errorCases { - if errs := validateProbe(p, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %v", p) - } - } -} - -func TestValidateHandler(t *testing.T) { - successCases := []core.Handler{ - {Exec: &core.ExecAction{Command: []string{"echo"}}}, - {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromInt(1), Host: "", Scheme: "HTTP"}}, - {HTTPGet: &core.HTTPGetAction{Path: "/foo", Port: intstr.FromInt(65535), Host: "host", Scheme: "HTTP"}}, - {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP"}}, - {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []core.HTTPHeader{{Name: "Host", Value: "foo.example.com"}}}}, - {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []core.HTTPHeader{{Name: "X-Forwarded-For", Value: "1.2.3.4"}, {Name: "X-Forwarded-For", Value: "5.6.7.8"}}}}, - } - for _, h := range successCases { - if errs := validateHandler(&h, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []core.Handler{ - {}, - {Exec: &core.ExecAction{Command: []string{}}}, - {HTTPGet: &core.HTTPGetAction{Path: "", Port: intstr.FromInt(0), Host: ""}}, - {HTTPGet: &core.HTTPGetAction{Path: "/foo", Port: intstr.FromInt(65536), Host: "host"}}, - {HTTPGet: &core.HTTPGetAction{Path: "", Port: intstr.FromString(""), Host: ""}}, - {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []core.HTTPHeader{{Name: "Host:", Value: "foo.example.com"}}}}, - {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []core.HTTPHeader{{Name: "X_Forwarded_For", Value: "foo.example.com"}}}}, - } - for _, h := range errorCases { - if errs := validateHandler(&h, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %#v", h) - } - } -} - -func TestValidatePullPolicy(t *testing.T) { - type T struct { - Container core.Container - ExpectedPolicy core.PullPolicy - } - testCases := map[string]T{ - "NotPresent1": { - core.Container{Name: "abc", Image: "image:latest", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - core.PullIfNotPresent, - }, - "NotPresent2": { - core.Container{Name: "abc1", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - core.PullIfNotPresent, - }, - "Always1": { - core.Container{Name: "123", Image: "image:latest", ImagePullPolicy: "Always"}, - core.PullAlways, - }, - "Always2": { - core.Container{Name: "1234", Image: "image", ImagePullPolicy: "Always"}, - core.PullAlways, - }, - "Never1": { - core.Container{Name: "abc-123", Image: "image:latest", ImagePullPolicy: "Never"}, - core.PullNever, - }, - "Never2": { - core.Container{Name: "abc-1234", Image: "image", ImagePullPolicy: "Never"}, - core.PullNever, - }, - } - for k, v := range testCases { - ctr := &v.Container - errs := validatePullPolicy(ctr.ImagePullPolicy, field.NewPath("field")) - if len(errs) != 0 { - t.Errorf("case[%s] expected success, got %#v", k, errs) - } - if ctr.ImagePullPolicy != v.ExpectedPolicy { - t.Errorf("case[%s] expected policy %v, got %v", k, v.ExpectedPolicy, ctr.ImagePullPolicy) - } - } -} - -func getResourceLimits(cpu, memory string) core.ResourceList { - res := core.ResourceList{} - res[core.ResourceCPU] = resource.MustParse(cpu) - res[core.ResourceMemory] = resource.MustParse(memory) - return res -} - -func TestValidateContainers(t *testing.T) { - volumeDevices := make(map[string]core.VolumeSource) - capabilities.SetForTests(capabilities.Capabilities{ - AllowPrivileged: true, - }) - - successCase := []core.Container{ - {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - // backwards compatibility to ensure containers in pod template spec do not check for this - {Name: "def", Image: " ", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - {Name: "ghi", Image: " some ", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - {Name: "123", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - {Name: "abc-123", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - { - Name: "life-123", - Image: "image", - Lifecycle: &core.Lifecycle{ - PreStop: &core.Handler{ - Exec: &core.ExecAction{Command: []string{"ls", "-l"}}, - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - { - Name: "resources-test", - Image: "image", - Resources: core.ResourceRequirements{ - Limits: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("my.org/resource"): resource.MustParse("10"), - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - { - Name: "resources-test-with-gpu-with-request", - Image: "image", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName(core.ResourceNvidiaGPU): resource.MustParse("1"), - }, - Limits: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName(core.ResourceNvidiaGPU): resource.MustParse("1"), - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - { - Name: "resources-test-with-gpu-without-request", - Image: "image", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - }, - Limits: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName(core.ResourceNvidiaGPU): resource.MustParse("1"), - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - { - Name: "resources-request-limit-simple", - Image: "image", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("8"), - }, - Limits: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - { - Name: "resources-request-limit-edge", - Image: "image", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("my.org/resource"): resource.MustParse("10"), - }, - Limits: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("my.org/resource"): resource.MustParse("10"), - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - { - Name: "resources-request-limit-partials", - Image: "image", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("9.5"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - }, - Limits: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName("my.org/resource"): resource.MustParse("10"), - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - { - Name: "resources-request", - Image: "image", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("9.5"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - { - Name: "same-host-port-different-protocol", - Image: "image", - Ports: []core.ContainerPort{ - {ContainerPort: 80, HostPort: 80, Protocol: "TCP"}, - {ContainerPort: 80, HostPort: 80, Protocol: "UDP"}, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - { - Name: "fallback-to-logs-termination-message", - Image: "image", - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "FallbackToLogsOnError", - }, - { - Name: "file-termination-message", - Image: "image", - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - { - Name: "env-from-source", - Image: "image", - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - EnvFrom: []core.EnvFromSource{ - { - ConfigMapRef: &core.ConfigMapEnvSource{ - LocalObjectReference: core.LocalObjectReference{ - Name: "test", - }, - }, - }, - }, - }, - {Name: "abc-1234", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File", SecurityContext: fakeValidSecurityContext(true)}, - } - if errs := validateContainers(successCase, volumeDevices, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - capabilities.SetForTests(capabilities.Capabilities{ - AllowPrivileged: false, - }) - errorCases := map[string][]core.Container{ - "zero-length name": {{Name: "", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - "zero-length-image": {{Name: "abc", Image: "", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - "name > 63 characters": {{Name: strings.Repeat("a", 64), Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - "name not a DNS label": {{Name: "a.b.c", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - "name not unique": { - {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - }, - "zero-length image": {{Name: "abc", Image: "", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - "host port not unique": { - {Name: "abc", Image: "image", Ports: []core.ContainerPort{{ContainerPort: 80, HostPort: 80, Protocol: "TCP"}}, - ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - {Name: "def", Image: "image", Ports: []core.ContainerPort{{ContainerPort: 81, HostPort: 80, Protocol: "TCP"}}, - ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - }, - "invalid env var name": { - {Name: "abc", Image: "image", Env: []core.EnvVar{{Name: "ev!1"}}, ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - }, - "unknown volume name": { - {Name: "abc", Image: "image", VolumeMounts: []core.VolumeMount{{Name: "anything", MountPath: "/foo"}}, - ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}, - }, - "invalid lifecycle, no exec command.": { - { - Name: "life-123", - Image: "image", - Lifecycle: &core.Lifecycle{ - PreStop: &core.Handler{ - Exec: &core.ExecAction{}, - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "invalid lifecycle, no http path.": { - { - Name: "life-123", - Image: "image", - Lifecycle: &core.Lifecycle{ - PreStop: &core.Handler{ - HTTPGet: &core.HTTPGetAction{}, - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "invalid lifecycle, no tcp socket port.": { - { - Name: "life-123", - Image: "image", - Lifecycle: &core.Lifecycle{ - PreStop: &core.Handler{ - TCPSocket: &core.TCPSocketAction{}, - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "invalid lifecycle, zero tcp socket port.": { - { - Name: "life-123", - Image: "image", - Lifecycle: &core.Lifecycle{ - PreStop: &core.Handler{ - TCPSocket: &core.TCPSocketAction{ - Port: intstr.FromInt(0), - }, - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "invalid lifecycle, no action.": { - { - Name: "life-123", - Image: "image", - Lifecycle: &core.Lifecycle{ - PreStop: &core.Handler{}, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "invalid liveness probe, no tcp socket port.": { - { - Name: "life-123", - Image: "image", - LivenessProbe: &core.Probe{ - Handler: core.Handler{ - TCPSocket: &core.TCPSocketAction{}, - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "invalid liveness probe, no action.": { - { - Name: "life-123", - Image: "image", - LivenessProbe: &core.Probe{ - Handler: core.Handler{}, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "invalid message termination policy": { - { - Name: "life-123", - Image: "image", - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "Unknown", - }, - }, - "empty message termination policy": { - { - Name: "life-123", - Image: "image", - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "", - }, - }, - "privilege disabled": { - {Name: "abc", Image: "image", SecurityContext: fakeValidSecurityContext(true)}, - }, - "invalid compute resource": { - { - Name: "abc-123", - Image: "image", - Resources: core.ResourceRequirements{ - Limits: core.ResourceList{ - "disk": resource.MustParse("10G"), - }, - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "Resource CPU invalid": { - { - Name: "abc-123", - Image: "image", - Resources: core.ResourceRequirements{ - Limits: getResourceLimits("-10", "0"), - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "Resource Requests CPU invalid": { - { - Name: "abc-123", - Image: "image", - Resources: core.ResourceRequirements{ - Requests: getResourceLimits("-10", "0"), - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "Resource Memory invalid": { - { - Name: "abc-123", - Image: "image", - Resources: core.ResourceRequirements{ - Limits: getResourceLimits("0", "-10"), - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "Resource GPU limit must match request": { - { - Name: "gpu-resource-request-limit", - Image: "image", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName(core.ResourceNvidiaGPU): resource.MustParse("0"), - }, - Limits: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName(core.ResourceNvidiaGPU): resource.MustParse("1"), - }, - }, - TerminationMessagePolicy: "File", - ImagePullPolicy: "IfNotPresent", - }, - }, - "Resource GPU invalid setting only request": { - { - Name: "gpu-resource-request-limit", - Image: "image", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName(core.ResourceNvidiaGPU): resource.MustParse("1"), - }, - }, - TerminationMessagePolicy: "File", - ImagePullPolicy: "IfNotPresent", - }, - }, - "Request limit simple invalid": { - { - Name: "abc-123", - Image: "image", - Resources: core.ResourceRequirements{ - Limits: getResourceLimits("5", "3"), - Requests: getResourceLimits("6", "3"), - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "Request limit multiple invalid": { - { - Name: "abc-123", - Image: "image", - Resources: core.ResourceRequirements{ - Limits: getResourceLimits("5", "3"), - Requests: getResourceLimits("6", "4"), - }, - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - }, - }, - "Invalid env from": { - { - Name: "env-from-source", - Image: "image", - ImagePullPolicy: "IfNotPresent", - TerminationMessagePolicy: "File", - EnvFrom: []core.EnvFromSource{ - { - ConfigMapRef: &core.ConfigMapEnvSource{ - LocalObjectReference: core.LocalObjectReference{ - Name: "$%^&*#", - }, - }, - }, - }, - }, - }, - } - for k, v := range errorCases { - if errs := validateContainers(v, volumeDevices, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - } -} - -func TestValidateRestartPolicy(t *testing.T) { - successCases := []core.RestartPolicy{ - core.RestartPolicyAlways, - core.RestartPolicyOnFailure, - core.RestartPolicyNever, - } - for _, policy := range successCases { - if errs := validateRestartPolicy(&policy, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []core.RestartPolicy{"", "newpolicy"} - - for k, policy := range errorCases { - if errs := validateRestartPolicy(&policy, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %d", k) - } - } -} - -func TestValidateDNSPolicy(t *testing.T) { - customDNSEnabled := utilfeature.DefaultFeatureGate.Enabled("CustomPodDNS") - defer func() { - // Restoring the old value. - if err := utilfeature.DefaultFeatureGate.Set(fmt.Sprintf("CustomPodDNS=%v", customDNSEnabled)); err != nil { - t.Errorf("Failed to restore CustomPodDNS feature gate: %v", err) - } - }() - if err := utilfeature.DefaultFeatureGate.Set("CustomPodDNS=true"); err != nil { - t.Errorf("Failed to enable CustomPodDNS feature gate: %v", err) - } - - successCases := []core.DNSPolicy{core.DNSClusterFirst, core.DNSDefault, core.DNSPolicy(core.DNSClusterFirst), core.DNSNone} - for _, policy := range successCases { - if errs := validateDNSPolicy(&policy, field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := []core.DNSPolicy{core.DNSPolicy("invalid")} - for _, policy := range errorCases { - if errs := validateDNSPolicy(&policy, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %v", policy) - } - } -} - -func TestValidatePodDNSConfig(t *testing.T) { - customDNSEnabled := utilfeature.DefaultFeatureGate.Enabled("CustomPodDNS") - defer func() { - // Restoring the old value. - if err := utilfeature.DefaultFeatureGate.Set(fmt.Sprintf("CustomPodDNS=%v", customDNSEnabled)); err != nil { - t.Errorf("Failed to restore CustomPodDNS feature gate: %v", err) - } - }() - if err := utilfeature.DefaultFeatureGate.Set("CustomPodDNS=true"); err != nil { - t.Errorf("Failed to enable CustomPodDNS feature gate: %v", err) - } - - generateTestSearchPathFunc := func(numChars int) string { - res := "" - for i := 0; i < numChars; i++ { - res = res + "a" - } - return res - } - testOptionValue := "2" - testDNSNone := core.DNSNone - testDNSClusterFirst := core.DNSClusterFirst - - testCases := []struct { - desc string - dnsConfig *core.PodDNSConfig - dnsPolicy *core.DNSPolicy - expectedError bool - }{ - { - desc: "valid: empty DNSConfig", - dnsConfig: &core.PodDNSConfig{}, - expectedError: false, - }, - { - desc: "valid: 1 option", - dnsConfig: &core.PodDNSConfig{ - Options: []core.PodDNSConfigOption{ - {Name: "ndots", Value: &testOptionValue}, - }, - }, - expectedError: false, - }, - { - desc: "valid: 1 nameserver", - dnsConfig: &core.PodDNSConfig{ - Nameservers: []string{"127.0.0.1"}, - }, - expectedError: false, - }, - { - desc: "valid: DNSNone with 1 nameserver", - dnsConfig: &core.PodDNSConfig{ - Nameservers: []string{"127.0.0.1"}, - }, - dnsPolicy: &testDNSNone, - expectedError: false, - }, - { - desc: "valid: 1 search path", - dnsConfig: &core.PodDNSConfig{ - Searches: []string{"custom"}, - }, - expectedError: false, - }, - { - desc: "valid: 3 nameservers and 6 search paths", - dnsConfig: &core.PodDNSConfig{ - Nameservers: []string{"127.0.0.1", "10.0.0.10", "8.8.8.8"}, - Searches: []string{"custom", "mydomain.com", "local", "cluster.local", "svc.cluster.local", "default.svc.cluster.local"}, - }, - expectedError: false, - }, - { - desc: "valid: 256 characters in search path list", - dnsConfig: &core.PodDNSConfig{ - // We can have 256 - (6 - 1) = 251 characters in total for 6 search paths. - Searches: []string{ - generateTestSearchPathFunc(1), - generateTestSearchPathFunc(50), - generateTestSearchPathFunc(50), - generateTestSearchPathFunc(50), - generateTestSearchPathFunc(50), - generateTestSearchPathFunc(50), - }, - }, - expectedError: false, - }, - { - desc: "valid: ipv6 nameserver", - dnsConfig: &core.PodDNSConfig{ - Nameservers: []string{"FE80::0202:B3FF:FE1E:8329"}, - }, - expectedError: false, - }, - { - desc: "invalid: 4 nameservers", - dnsConfig: &core.PodDNSConfig{ - Nameservers: []string{"127.0.0.1", "10.0.0.10", "8.8.8.8", "1.2.3.4"}, - }, - expectedError: true, - }, - { - desc: "invalid: 7 search paths", - dnsConfig: &core.PodDNSConfig{ - Searches: []string{"custom", "mydomain.com", "local", "cluster.local", "svc.cluster.local", "default.svc.cluster.local", "exceeded"}, - }, - expectedError: true, - }, - { - desc: "invalid: 257 characters in search path list", - dnsConfig: &core.PodDNSConfig{ - // We can have 256 - (6 - 1) = 251 characters in total for 6 search paths. - Searches: []string{ - generateTestSearchPathFunc(2), - generateTestSearchPathFunc(50), - generateTestSearchPathFunc(50), - generateTestSearchPathFunc(50), - generateTestSearchPathFunc(50), - generateTestSearchPathFunc(50), - }, - }, - expectedError: true, - }, - { - desc: "invalid search path", - dnsConfig: &core.PodDNSConfig{ - Searches: []string{"custom?"}, - }, - expectedError: true, - }, - { - desc: "invalid nameserver", - dnsConfig: &core.PodDNSConfig{ - Nameservers: []string{"invalid"}, - }, - expectedError: true, - }, - { - desc: "invalid empty option name", - dnsConfig: &core.PodDNSConfig{ - Options: []core.PodDNSConfigOption{ - {Value: &testOptionValue}, - }, - }, - expectedError: true, - }, - { - desc: "invalid: DNSNone with 0 nameserver", - dnsConfig: &core.PodDNSConfig{ - Searches: []string{"custom"}, - }, - dnsPolicy: &testDNSNone, - expectedError: true, - }, - } - - for _, tc := range testCases { - if tc.dnsPolicy == nil { - tc.dnsPolicy = &testDNSClusterFirst - } - - errs := validatePodDNSConfig(tc.dnsConfig, tc.dnsPolicy, field.NewPath("dnsConfig")) - if len(errs) != 0 && !tc.expectedError { - t.Errorf("%v: validatePodDNSConfig(%v) = %v, want nil", tc.desc, tc.dnsConfig, errs) - } else if len(errs) == 0 && tc.expectedError { - t.Errorf("%v: validatePodDNSConfig(%v) = nil, want error", tc.desc, tc.dnsConfig) - } - } -} - -func TestValidatePodSpec(t *testing.T) { - activeDeadlineSeconds := int64(30) - activeDeadlineSecondsMax := int64(math.MaxInt32) - - minUserID := int64(0) - maxUserID := int64(2147483647) - minGroupID := int64(0) - maxGroupID := int64(2147483647) - - defer utilfeaturetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PodPriority, true)() - defer utilfeaturetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PodShareProcessNamespace, true)() - - successCases := []core.PodSpec{ - { // Populate basic fields, leave defaults for most. - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - { // Populate all fields. - Volumes: []core.Volume{ - {Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}, - }, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - InitContainers: []core.Container{{Name: "ictr", Image: "iimage", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - NodeSelector: map[string]string{ - "key": "value", - }, - NodeName: "foobar", - DNSPolicy: core.DNSClusterFirst, - ActiveDeadlineSeconds: &activeDeadlineSeconds, - ServiceAccountName: "acct", - }, - { // Populate all fields with larger active deadline. - Volumes: []core.Volume{ - {Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}, - }, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - InitContainers: []core.Container{{Name: "ictr", Image: "iimage", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - NodeSelector: map[string]string{ - "key": "value", - }, - NodeName: "foobar", - DNSPolicy: core.DNSClusterFirst, - ActiveDeadlineSeconds: &activeDeadlineSecondsMax, - ServiceAccountName: "acct", - }, - { // Populate HostNetwork. - Containers: []core.Container{ - {Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File", - Ports: []core.ContainerPort{ - {HostPort: 8080, ContainerPort: 8080, Protocol: "TCP"}}, - }, - }, - SecurityContext: &core.PodSecurityContext{ - HostNetwork: true, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - { // Populate RunAsUser SupplementalGroups FSGroup with minID 0 - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - SecurityContext: &core.PodSecurityContext{ - SupplementalGroups: []int64{minGroupID}, - RunAsUser: &minUserID, - FSGroup: &minGroupID, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - { // Populate RunAsUser SupplementalGroups FSGroup with maxID 2147483647 - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - SecurityContext: &core.PodSecurityContext{ - SupplementalGroups: []int64{maxGroupID}, - RunAsUser: &maxUserID, - FSGroup: &maxGroupID, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - { // Populate HostIPC. - SecurityContext: &core.PodSecurityContext{ - HostIPC: true, - }, - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - { // Populate HostPID. - SecurityContext: &core.PodSecurityContext{ - HostPID: true, - }, - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - { // Populate Affinity. - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - { // Populate HostAliases. - HostAliases: []core.HostAlias{{IP: "12.34.56.78", Hostnames: []string{"host1", "host2"}}}, - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - { // Populate HostAliases with `foo.bar` hostnames. - HostAliases: []core.HostAlias{{IP: "12.34.56.78", Hostnames: []string{"host1.foo", "host2.bar"}}}, - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - { // Populate HostAliases with HostNetwork. - HostAliases: []core.HostAlias{{IP: "12.34.56.78", Hostnames: []string{"host1.foo", "host2.bar"}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - SecurityContext: &core.PodSecurityContext{ - HostNetwork: true, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - { // Populate PriorityClassName. - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - PriorityClassName: "valid-name", - }, - { // Populate ShareProcessNamespace - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - SecurityContext: &core.PodSecurityContext{ - ShareProcessNamespace: &[]bool{true}[0], - }, - }, - } - for i := range successCases { - if errs := ValidatePodSpec(&successCases[i], field.NewPath("field")); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - activeDeadlineSeconds = int64(0) - activeDeadlineSecondsTooLarge := int64(math.MaxInt32 + 1) - - minUserID = int64(-1) - maxUserID = int64(2147483648) - minGroupID = int64(-1) - maxGroupID = int64(2147483648) - - failureCases := map[string]core.PodSpec{ - "bad volume": { - Volumes: []core.Volume{{}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - "no containers": { - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "bad container": { - Containers: []core.Container{{}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "bad init container": { - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - InitContainers: []core.Container{{}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "bad DNS policy": { - DNSPolicy: core.DNSPolicy("invalid"), - RestartPolicy: core.RestartPolicyAlways, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - "bad service account name": { - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - ServiceAccountName: "invalidName", - }, - "bad restart policy": { - RestartPolicy: "UnknowPolicy", - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - "with hostNetwork hostPort not equal to containerPort": { - Containers: []core.Container{ - {Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", Ports: []core.ContainerPort{ - {HostPort: 8080, ContainerPort: 2600, Protocol: "TCP"}}, - }, - }, - SecurityContext: &core.PodSecurityContext{ - HostNetwork: true, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "with hostAliases with invalid IP": { - SecurityContext: &core.PodSecurityContext{ - HostNetwork: false, - }, - HostAliases: []core.HostAlias{{IP: "999.999.999.999", Hostnames: []string{"host1", "host2"}}}, - }, - "with hostAliases with invalid hostname": { - SecurityContext: &core.PodSecurityContext{ - HostNetwork: false, - }, - HostAliases: []core.HostAlias{{IP: "12.34.56.78", Hostnames: []string{"@#$^#@#$"}}}, - }, - "bad supplementalGroups large than math.MaxInt32": { - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - SecurityContext: &core.PodSecurityContext{ - HostNetwork: false, - SupplementalGroups: []int64{maxGroupID, 1234}, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "bad supplementalGroups less than 0": { - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - SecurityContext: &core.PodSecurityContext{ - HostNetwork: false, - SupplementalGroups: []int64{minGroupID, 1234}, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "bad runAsUser large than math.MaxInt32": { - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - SecurityContext: &core.PodSecurityContext{ - HostNetwork: false, - RunAsUser: &maxUserID, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "bad runAsUser less than 0": { - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - SecurityContext: &core.PodSecurityContext{ - HostNetwork: false, - RunAsUser: &minUserID, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "bad fsGroup large than math.MaxInt32": { - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - SecurityContext: &core.PodSecurityContext{ - HostNetwork: false, - FSGroup: &maxGroupID, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "bad fsGroup less than 0": { - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - SecurityContext: &core.PodSecurityContext{ - HostNetwork: false, - FSGroup: &minGroupID, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "bad-active-deadline-seconds": { - Volumes: []core.Volume{ - {Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}, - }, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - NodeSelector: map[string]string{ - "key": "value", - }, - NodeName: "foobar", - DNSPolicy: core.DNSClusterFirst, - ActiveDeadlineSeconds: &activeDeadlineSeconds, - }, - "active-deadline-seconds-too-large": { - Volumes: []core.Volume{ - {Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}, - }, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - NodeSelector: map[string]string{ - "key": "value", - }, - NodeName: "foobar", - DNSPolicy: core.DNSClusterFirst, - ActiveDeadlineSeconds: &activeDeadlineSecondsTooLarge, - }, - "bad nodeName": { - NodeName: "node name", - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - "bad PriorityClassName": { - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - PriorityClassName: "InvalidName", - }, - "ShareProcessNamespace and HostPID both set": { - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - SecurityContext: &core.PodSecurityContext{ - HostPID: true, - ShareProcessNamespace: &[]bool{true}[0], - }, - }, - } - for k, v := range failureCases { - if errs := ValidatePodSpec(&v, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure for %q", k) - } - } - - // original value will be restored by previous defer - utilfeaturetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PodShareProcessNamespace, false) - - featuregatedCases := map[string]core.PodSpec{ - "set ShareProcessNamespace": { - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - SecurityContext: &core.PodSecurityContext{ - ShareProcessNamespace: &[]bool{true}[0], - }, - }, - } - for k, v := range featuregatedCases { - if errs := ValidatePodSpec(&v, field.NewPath("field")); len(errs) == 0 { - t.Errorf("expected failure due to gated feature: %q", k) - } - } -} - -func extendPodSpecwithTolerations(in core.PodSpec, tolerations []core.Toleration) core.PodSpec { - var out core.PodSpec - out.Containers = in.Containers - out.RestartPolicy = in.RestartPolicy - out.DNSPolicy = in.DNSPolicy - out.Tolerations = tolerations - return out -} - -func TestValidatePod(t *testing.T) { - validPodSpec := func(affinity *core.Affinity) core.PodSpec { - spec := core.PodSpec{ - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - } - if affinity != nil { - spec.Affinity = affinity - } - return spec - } - - successCases := []core.Pod{ - { // Basic fields. - ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"}, - Spec: core.PodSpec{ - Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - { // Just about everything. - ObjectMeta: metav1.ObjectMeta{Name: "abc.123.do-re-mi", Namespace: "ns"}, - Spec: core.PodSpec{ - Volumes: []core.Volume{ - {Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}, - }, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - NodeSelector: map[string]string{ - "key": "value", - }, - NodeName: "foobar", - }, - }, - { // Serialized node affinity requirements. - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec( - // TODO: Uncomment and move this block and move inside NodeAffinity once - // RequiredDuringSchedulingRequiredDuringExecution is implemented - // RequiredDuringSchedulingRequiredDuringExecution: &core.NodeSelector{ - // NodeSelectorTerms: []core.NodeSelectorTerm{ - // { - // MatchExpressions: []core.NodeSelectorRequirement{ - // { - // Key: "key1", - // Operator: core.NodeSelectorOpExists - // }, - // }, - // }, - // }, - // }, - &core.Affinity{ - NodeAffinity: &core.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{ - NodeSelectorTerms: []core.NodeSelectorTerm{ - { - MatchExpressions: []core.NodeSelectorRequirement{ - { - Key: "key2", - Operator: core.NodeSelectorOpIn, - Values: []string{"value1", "value2"}, - }, - }, - }, - }, - }, - PreferredDuringSchedulingIgnoredDuringExecution: []core.PreferredSchedulingTerm{ - { - Weight: 10, - Preference: core.NodeSelectorTerm{ - MatchExpressions: []core.NodeSelectorRequirement{ - { - Key: "foo", - Operator: core.NodeSelectorOpIn, - Values: []string{"bar"}, - }, - }, - }, - }, - }, - }, - }, - ), - }, - { // Serialized pod affinity in affinity requirements in annotations. - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - // TODO: Uncomment and move this block into Annotations map once - // RequiredDuringSchedulingRequiredDuringExecution is implemented - // "requiredDuringSchedulingRequiredDuringExecution": [{ - // "labelSelector": { - // "matchExpressions": [{ - // "key": "key2", - // "operator": "In", - // "values": ["value1", "value2"] - // }] - // }, - // "namespaces":["ns"], - // "topologyKey": "zone" - // }] - }, - Spec: validPodSpec(&core.Affinity{ - PodAffinity: &core.PodAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: []core.PodAffinityTerm{ - { - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpIn, - Values: []string{"value1", "value2"}, - }, - }, - }, - TopologyKey: "zone", - Namespaces: []string{"ns"}, - }, - }, - PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{ - { - Weight: 10, - PodAffinityTerm: core.PodAffinityTerm{ - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpNotIn, - Values: []string{"value1", "value2"}, - }, - }, - }, - Namespaces: []string{"ns"}, - TopologyKey: "region", - }, - }, - }, - }, - }), - }, - { // Serialized pod anti affinity with different Label Operators in affinity requirements in annotations. - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - // TODO: Uncomment and move this block into Annotations map once - // RequiredDuringSchedulingRequiredDuringExecution is implemented - // "requiredDuringSchedulingRequiredDuringExecution": [{ - // "labelSelector": { - // "matchExpressions": [{ - // "key": "key2", - // "operator": "In", - // "values": ["value1", "value2"] - // }] - // }, - // "namespaces":["ns"], - // "topologyKey": "zone" - // }] - }, - Spec: validPodSpec(&core.Affinity{ - PodAntiAffinity: &core.PodAntiAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: []core.PodAffinityTerm{ - { - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpExists, - }, - }, - }, - TopologyKey: "zone", - Namespaces: []string{"ns"}, - }, - }, - PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{ - { - Weight: 10, - PodAffinityTerm: core.PodAffinityTerm{ - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpDoesNotExist, - }, - }, - }, - Namespaces: []string{"ns"}, - TopologyKey: "region", - }, - }, - }, - }, - }), - }, - { // populate forgiveness tolerations with exists operator in annotations. - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "Exists", Value: "", Effect: "NoExecute", TolerationSeconds: &[]int64{60}[0]}}), - }, - { // populate forgiveness tolerations with equal operator in annotations. - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "Equal", Value: "bar", Effect: "NoExecute", TolerationSeconds: &[]int64{60}[0]}}), - }, - { // populate tolerations equal operator in annotations. - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "Equal", Value: "bar", Effect: "NoSchedule"}}), - }, - { // populate tolerations exists operator in annotations. - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(nil), - }, - { // empty key with Exists operator is OK for toleration, empty toleration key means match all taint keys. - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Operator: "Exists", Effect: "NoSchedule"}}), - }, - { // empty operator is OK for toleration, defaults to Equal. - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Value: "bar", Effect: "NoSchedule"}}), - }, - { // empty effect is OK for toleration, empty toleration effect means match all taint effects. - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "Equal", Value: "bar"}}), - }, - { // negative tolerationSeconds is OK for toleration. - ObjectMeta: metav1.ObjectMeta{ - Name: "pod-forgiveness-invalid", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "node.kubernetes.io/not-ready", Operator: "Exists", Effect: "NoExecute", TolerationSeconds: &[]int64{-2}[0]}}), - }, - { // docker default seccomp profile - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SeccompPodAnnotationKey: "docker/default", - }, - }, - Spec: validPodSpec(nil), - }, - { // unconfined seccomp profile - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SeccompPodAnnotationKey: "unconfined", - }, - }, - Spec: validPodSpec(nil), - }, - { // localhost seccomp profile - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SeccompPodAnnotationKey: "localhost/foo", - }, - }, - Spec: validPodSpec(nil), - }, - { // localhost seccomp profile for a container - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SeccompContainerAnnotationKeyPrefix + "foo": "localhost/foo", - }, - }, - Spec: validPodSpec(nil), - }, - { // default AppArmor profile for a container - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - apparmor.ContainerAnnotationKeyPrefix + "ctr": apparmor.ProfileRuntimeDefault, - }, - }, - Spec: validPodSpec(nil), - }, - { // default AppArmor profile for an init container - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - apparmor.ContainerAnnotationKeyPrefix + "init-ctr": apparmor.ProfileRuntimeDefault, - }, - }, - Spec: core.PodSpec{ - InitContainers: []core.Container{{Name: "init-ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - { // localhost AppArmor profile for a container - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - apparmor.ContainerAnnotationKeyPrefix + "ctr": apparmor.ProfileNamePrefix + "foo", - }, - }, - Spec: validPodSpec(nil), - }, - { // syntactically valid sysctls - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SysctlsPodAnnotationKey: "kernel.shmmni=32768,kernel.shmmax=1000000000", - core.UnsafeSysctlsPodAnnotationKey: "knet.ipv4.route.min_pmtu=1000", - }, - }, - Spec: validPodSpec(nil), - }, - { // valid extended resources for init container - ObjectMeta: metav1.ObjectMeta{Name: "valid-extended", Namespace: "ns"}, - Spec: core.PodSpec{ - InitContainers: []core.Container{ - { - Name: "valid-extended", - Image: "image", - ImagePullPolicy: "IfNotPresent", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("10"), - }, - Limits: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("10"), - }, - }, - TerminationMessagePolicy: "File", - }, - }, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - { // valid extended resources for regular container - ObjectMeta: metav1.ObjectMeta{Name: "valid-extended", Namespace: "ns"}, - Spec: core.PodSpec{ - InitContainers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - Containers: []core.Container{ - { - Name: "valid-extended", - Image: "image", - ImagePullPolicy: "IfNotPresent", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("10"), - }, - Limits: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("10"), - }, - }, - TerminationMessagePolicy: "File", - }, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - } - for _, pod := range successCases { - if errs := ValidatePod(&pod); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]struct { - spec core.Pod - expectedError string - }{ - "bad name": { - expectedError: "metadata.name", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: "ns"}, - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - }, - }, - "image whitespace": { - expectedError: "spec.containers[0].image", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "ns"}, - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "ctr", Image: " ", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - }, - }, - "image leading and trailing whitespace": { - expectedError: "spec.containers[0].image", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "ns"}, - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "ctr", Image: " something ", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - }, - }, - "bad namespace": { - expectedError: "metadata.namespace", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: ""}, - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - }, - }, - "bad spec": { - expectedError: "spec.containers[0].name", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "ns"}, - Spec: core.PodSpec{ - Containers: []core.Container{{}}, - }, - }, - }, - "bad label": { - expectedError: "NoUppercaseOrSpecialCharsLike=Equals", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Namespace: "ns", - Labels: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - }, - }, - "invalid node selector requirement in node affinity, operator can't be null": { - expectedError: "spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[0].matchExpressions[0].operator", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - NodeAffinity: &core.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{ - NodeSelectorTerms: []core.NodeSelectorTerm{ - { - MatchExpressions: []core.NodeSelectorRequirement{ - { - Key: "key1", - }, - }, - }, - }, - }, - }, - }), - }, - }, - "invalid preferredSchedulingTerm in node affinity, weight should be in range 1-100": { - expectedError: "must be in the range 1-100", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - NodeAffinity: &core.NodeAffinity{ - PreferredDuringSchedulingIgnoredDuringExecution: []core.PreferredSchedulingTerm{ - { - Weight: 199, - Preference: core.NodeSelectorTerm{ - MatchExpressions: []core.NodeSelectorRequirement{ - { - Key: "foo", - Operator: core.NodeSelectorOpIn, - Values: []string{"bar"}, - }, - }, - }, - }, - }, - }, - }), - }, - }, - "invalid requiredDuringSchedulingIgnoredDuringExecution node selector, nodeSelectorTerms must have at least one term": { - expectedError: "spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - NodeAffinity: &core.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{ - NodeSelectorTerms: []core.NodeSelectorTerm{}, - }, - }, - }), - }, - }, - "invalid requiredDuringSchedulingIgnoredDuringExecution node selector term, matchExpressions must have at least one node selector requirement": { - expectedError: "spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[0].matchExpressions", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - NodeAffinity: &core.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{ - NodeSelectorTerms: []core.NodeSelectorTerm{ - { - MatchExpressions: []core.NodeSelectorRequirement{}, - }, - }, - }, - }, - }), - }, - }, - "invalid weight in preferredDuringSchedulingIgnoredDuringExecution in pod affinity annotations, weight should be in range 1-100": { - expectedError: "must be in the range 1-100", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - PodAffinity: &core.PodAffinity{ - PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{ - { - Weight: 109, - PodAffinityTerm: core.PodAffinityTerm{ - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpNotIn, - Values: []string{"value1", "value2"}, - }, - }, - }, - Namespaces: []string{"ns"}, - TopologyKey: "region", - }, - }, - }, - }, - }), - }, - }, - "invalid labelSelector in preferredDuringSchedulingIgnoredDuringExecution in podaffinity annotations, values should be empty if the operator is Exists": { - expectedError: "spec.affinity.podAntiAffinity.preferredDuringSchedulingIgnoredDuringExecution[0].podAffinityTerm.matchExpressions.matchExpressions[0].values", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - PodAntiAffinity: &core.PodAntiAffinity{ - PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{ - { - Weight: 10, - PodAffinityTerm: core.PodAffinityTerm{ - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpExists, - Values: []string{"value1", "value2"}, - }, - }, - }, - Namespaces: []string{"ns"}, - TopologyKey: "region", - }, - }, - }, - }, - }), - }, - }, - "invalid name space in preferredDuringSchedulingIgnoredDuringExecution in podaffinity annotations, name space shouldbe valid": { - expectedError: "spec.affinity.podAffinity.preferredDuringSchedulingIgnoredDuringExecution[0].podAffinityTerm.namespace", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - PodAffinity: &core.PodAffinity{ - PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{ - { - Weight: 10, - PodAffinityTerm: core.PodAffinityTerm{ - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpExists, - }, - }, - }, - Namespaces: []string{"INVALID_NAMESPACE"}, - TopologyKey: "region", - }, - }, - }, - }, - }), - }, - }, - "invalid hard pod affinity, empty topologyKey is not allowed for hard pod affinity": { - expectedError: "can not be empty", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - PodAffinity: &core.PodAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: []core.PodAffinityTerm{ - { - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpIn, - Values: []string{"value1", "value2"}, - }, - }, - }, - Namespaces: []string{"ns"}, - }, - }, - }, - }), - }, - }, - "invalid hard pod anti-affinity, empty topologyKey is not allowed for hard pod anti-affinity": { - expectedError: "can not be empty", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - PodAntiAffinity: &core.PodAntiAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: []core.PodAffinityTerm{ - { - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpIn, - Values: []string{"value1", "value2"}, - }, - }, - }, - Namespaces: []string{"ns"}, - }, - }, - }, - }), - }, - }, - "invalid soft pod affinity, empty topologyKey is not allowed for soft pod affinity": { - expectedError: "can not be empty", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - PodAffinity: &core.PodAffinity{ - PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{ - { - Weight: 10, - PodAffinityTerm: core.PodAffinityTerm{ - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpNotIn, - Values: []string{"value1", "value2"}, - }, - }, - }, - Namespaces: []string{"ns"}, - }, - }, - }, - }, - }), - }, - }, - "invalid soft pod anti-affinity, empty topologyKey is not allowed for soft pod anti-affinity": { - expectedError: "can not be empty", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: validPodSpec(&core.Affinity{ - PodAntiAffinity: &core.PodAntiAffinity{ - PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{ - { - Weight: 10, - PodAffinityTerm: core.PodAffinityTerm{ - LabelSelector: &metav1.LabelSelector{ - MatchExpressions: []metav1.LabelSelectorRequirement{ - { - Key: "key2", - Operator: metav1.LabelSelectorOpNotIn, - Values: []string{"value1", "value2"}, - }, - }, - }, - Namespaces: []string{"ns"}, - }, - }, - }, - }, - }), - }, - }, - "invalid toleration key": { - expectedError: "spec.tolerations[0].key", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "nospecialchars^=@", Operator: "Equal", Value: "bar", Effect: "NoSchedule"}}), - }, - }, - "invalid toleration operator": { - expectedError: "spec.tolerations[0].operator", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "In", Value: "bar", Effect: "NoSchedule"}}), - }, - }, - "value must be empty when `operator` is 'Exists'": { - expectedError: "spec.tolerations[0].operator", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "Exists", Value: "bar", Effect: "NoSchedule"}}), - }, - }, - - "operator must be 'Exists' when `key` is empty": { - expectedError: "spec.tolerations[0].operator", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Operator: "Equal", Value: "bar", Effect: "NoSchedule"}}), - }, - }, - "effect must be 'NoExecute' when `TolerationSeconds` is set": { - expectedError: "spec.tolerations[0].effect", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pod-forgiveness-invalid", - Namespace: "ns", - }, - Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "node.kubernetes.io/not-ready", Operator: "Exists", Effect: "NoSchedule", TolerationSeconds: &[]int64{20}[0]}}), - }, - }, - "must be a valid pod seccomp profile": { - expectedError: "must be a valid seccomp profile", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SeccompPodAnnotationKey: "foo", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "must be a valid container seccomp profile": { - expectedError: "must be a valid seccomp profile", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SeccompContainerAnnotationKeyPrefix + "foo": "foo", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "must be a non-empty container name in seccomp annotation": { - expectedError: "name part must be non-empty", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SeccompContainerAnnotationKeyPrefix: "foo", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "must be a non-empty container profile in seccomp annotation": { - expectedError: "must be a valid seccomp profile", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SeccompContainerAnnotationKeyPrefix + "foo": "", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "must be a relative path in a node-local seccomp profile annotation": { - expectedError: "must be a relative path", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SeccompPodAnnotationKey: "localhost//foo", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "must not start with '../'": { - expectedError: "must not contain '..'", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SeccompPodAnnotationKey: "localhost/../foo", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "AppArmor profile must apply to a container": { - expectedError: "metadata.annotations[container.apparmor.security.beta.kubernetes.io/fake-ctr]", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - apparmor.ContainerAnnotationKeyPrefix + "ctr": apparmor.ProfileRuntimeDefault, - apparmor.ContainerAnnotationKeyPrefix + "init-ctr": apparmor.ProfileRuntimeDefault, - apparmor.ContainerAnnotationKeyPrefix + "fake-ctr": apparmor.ProfileRuntimeDefault, - }, - }, - Spec: core.PodSpec{ - InitContainers: []core.Container{{Name: "init-ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - }, - "AppArmor profile format must be valid": { - expectedError: "invalid AppArmor profile name", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - apparmor.ContainerAnnotationKeyPrefix + "ctr": "bad-name", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "only default AppArmor profile may start with runtime/": { - expectedError: "invalid AppArmor profile name", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - apparmor.ContainerAnnotationKeyPrefix + "ctr": "runtime/foo", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "invalid sysctl annotation": { - expectedError: "metadata.annotations[security.alpha.kubernetes.io/sysctls]", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SysctlsPodAnnotationKey: "foo:", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "invalid comma-separated sysctl annotation": { - expectedError: "not of the format sysctl_name=value", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SysctlsPodAnnotationKey: "kernel.msgmax,", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "invalid unsafe sysctl annotation": { - expectedError: "metadata.annotations[security.alpha.kubernetes.io/sysctls]", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SysctlsPodAnnotationKey: "foo:", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "intersecting safe sysctls and unsafe sysctls annotations": { - expectedError: "can not be safe and unsafe", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Annotations: map[string]string{ - core.SysctlsPodAnnotationKey: "kernel.shmmax=10000000", - core.UnsafeSysctlsPodAnnotationKey: "kernel.shmmax=10000000", - }, - }, - Spec: validPodSpec(nil), - }, - }, - "invalid extended resource requirement: request must be == limit": { - expectedError: "must be equal to example.com/a", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Name: "invalid", - Image: "image", - ImagePullPolicy: "IfNotPresent", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("2"), - }, - Limits: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("1"), - }, - }, - }, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - }, - "invalid extended resource requirement without limit": { - expectedError: "Limit must be set", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Name: "invalid", - Image: "image", - ImagePullPolicy: "IfNotPresent", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("2"), - }, - }, - }, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - }, - "invalid fractional extended resource in container request": { - expectedError: "must be an integer", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Name: "invalid", - Image: "image", - ImagePullPolicy: "IfNotPresent", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("500m"), - }, - }, - }, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - }, - "invalid fractional extended resource in init container request": { - expectedError: "must be an integer", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"}, - Spec: core.PodSpec{ - InitContainers: []core.Container{ - { - Name: "invalid", - Image: "image", - ImagePullPolicy: "IfNotPresent", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("500m"), - }, - }, - }, - }, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - }, - "invalid fractional extended resource in container limit": { - expectedError: "must be an integer", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Name: "invalid", - Image: "image", - ImagePullPolicy: "IfNotPresent", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("5"), - }, - Limits: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("2.5"), - }, - }, - }, - }, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - }, - "invalid fractional extended resource in init container limit": { - expectedError: "must be an integer", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"}, - Spec: core.PodSpec{ - InitContainers: []core.Container{ - { - Name: "invalid", - Image: "image", - ImagePullPolicy: "IfNotPresent", - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("2.5"), - }, - Limits: core.ResourceList{ - core.ResourceName("example.com/a"): resource.MustParse("2.5"), - }, - }, - }, - }, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - }, - "mirror-pod present without nodeName": { - expectedError: "mirror", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns", Annotations: map[string]string{core.MirrorPodAnnotationKey: ""}}, - Spec: core.PodSpec{ - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - }, - "mirror-pod populated without nodeName": { - expectedError: "mirror", - spec: core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns", Annotations: map[string]string{core.MirrorPodAnnotationKey: "foo"}}, - Spec: core.PodSpec{ - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - }, - }, - } - for k, v := range errorCases { - if errs := ValidatePod(&v.spec); len(errs) == 0 { - t.Errorf("expected failure for %q", k) - } else if v.expectedError == "" { - t.Errorf("missing expectedError for %q, got %q", k, errs.ToAggregate().Error()) - } else if actualError := errs.ToAggregate().Error(); !strings.Contains(actualError, v.expectedError) { - t.Errorf("expected error for %q to contain %q, got %q", k, v.expectedError, actualError) - } - } -} - -func TestValidatePodUpdate(t *testing.T) { - var ( - activeDeadlineSecondsZero = int64(0) - activeDeadlineSecondsNegative = int64(-30) - activeDeadlineSecondsPositive = int64(30) - activeDeadlineSecondsLarger = int64(31) - - now = metav1.Now() - grace = int64(30) - grace2 = int64(31) - ) - - tests := []struct { - new core.Pod - old core.Pod - err string - test string - }{ - {core.Pod{}, core.Pod{}, "", "nothing"}, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "bar"}, - }, - "metadata.name", - "ids", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "bar": "foo", - }, - }, - }, - "", - "labels", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Annotations: map[string]string{ - "foo": "bar", - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Annotations: map[string]string{ - "bar": "foo", - }, - }, - }, - "", - "annotations", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V1", - }, - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V2", - }, - { - Image: "bar:V2", - }, - }, - }, - }, - "may not add or remove containers", - "less containers", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V1", - }, - { - Image: "bar:V2", - }, - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V2", - }, - }, - }, - }, - "may not add or remove containers", - "more containers", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - InitContainers: []core.Container{ - { - Image: "foo:V1", - }, - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - InitContainers: []core.Container{ - { - Image: "foo:V2", - }, - { - Image: "bar:V2", - }, - }, - }, - }, - "may not add or remove containers", - "more init containers", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}}, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo", DeletionTimestamp: &now}, - Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}}, - }, - "", - "deletion timestamp removed", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo", DeletionTimestamp: &now}, - Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}}, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}}, - }, - "metadata.deletionTimestamp", - "deletion timestamp added", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &grace}, - Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}}, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &grace2}, - Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}}, - }, - "metadata.deletionGracePeriodSeconds", - "deletion grace period seconds changed", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V1", - }, - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V2", - }, - }, - }, - }, - "", - "image change", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - InitContainers: []core.Container{ - { - Image: "foo:V1", - }, - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - InitContainers: []core.Container{ - { - Image: "foo:V2", - }, - }, - }, - }, - "", - "init container image change", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - {}, - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V2", - }, - }, - }, - }, - "spec.containers[0].image", - "image change to empty", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - InitContainers: []core.Container{ - {}, - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - InitContainers: []core.Container{ - { - Image: "foo:V2", - }, - }, - }, - }, - "spec.initContainers[0].image", - "init container image change to empty", - }, - { - core.Pod{ - Spec: core.PodSpec{}, - }, - core.Pod{ - Spec: core.PodSpec{}, - }, - "", - "activeDeadlineSeconds no change, nil", - }, - { - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - "", - "activeDeadlineSeconds no change, set", - }, - { - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - core.Pod{}, - "", - "activeDeadlineSeconds change to positive from nil", - }, - { - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsLarger, - }, - }, - "", - "activeDeadlineSeconds change to smaller positive", - }, - { - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsLarger, - }, - }, - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - "spec.activeDeadlineSeconds", - "activeDeadlineSeconds change to larger positive", - }, - - { - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsNegative, - }, - }, - core.Pod{}, - "spec.activeDeadlineSeconds", - "activeDeadlineSeconds change to negative from nil", - }, - { - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsNegative, - }, - }, - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - "spec.activeDeadlineSeconds", - "activeDeadlineSeconds change to negative from positive", - }, - { - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsZero, - }, - }, - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - "", - "activeDeadlineSeconds change to zero from positive", - }, - { - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsZero, - }, - }, - core.Pod{}, - "", - "activeDeadlineSeconds change to zero from nil", - }, - { - core.Pod{}, - core.Pod{ - Spec: core.PodSpec{ - ActiveDeadlineSeconds: &activeDeadlineSecondsPositive, - }, - }, - "spec.activeDeadlineSeconds", - "activeDeadlineSeconds change to nil from positive", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V1", - Resources: core.ResourceRequirements{ - Limits: getResourceLimits("100m", "0"), - }, - }, - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V2", - Resources: core.ResourceRequirements{ - Limits: getResourceLimits("1000m", "0"), - }, - }, - }, - }, - }, - "spec: Forbidden: pod updates may not change fields", - "cpu change", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V1", - Ports: []core.ContainerPort{ - {HostPort: 8080, ContainerPort: 80}, - }, - }, - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, - Spec: core.PodSpec{ - Containers: []core.Container{ - { - Image: "foo:V2", - Ports: []core.ContainerPort{ - {HostPort: 8000, ContainerPort: 80}, - }, - }, - }, - }, - }, - "spec: Forbidden: pod updates may not change fields", - "port change", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "foo": "bar", - }, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{ - "Bar": "foo", - }, - }, - }, - "", - "bad label change", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{{Key: "key1", Value: "value2"}}, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{{Key: "key1", Value: "value1"}}, - }, - }, - "spec.tolerations: Forbidden", - "existing toleration value modified in pod spec updates", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{{Key: "key1", Value: "value2", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: nil}}, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{{Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{10}[0]}}, - }, - }, - "spec.tolerations: Forbidden", - "existing toleration value modified in pod spec updates with modified tolerationSeconds", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{{Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{10}[0]}}, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{{Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{20}[0]}}, - }}, - "", - "modified tolerationSeconds in existing toleration value in pod spec updates", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - Tolerations: []core.Toleration{{Key: "key1", Value: "value2"}}, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "", - Tolerations: []core.Toleration{{Key: "key1", Value: "value1"}}, - }, - }, - "spec.tolerations: Forbidden", - "toleration modified in updates to an unscheduled pod", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{{Key: "key1", Value: "value1"}}, - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{{Key: "key1", Value: "value1"}}, - }, - }, - "", - "tolerations unmodified in updates to a scheduled pod", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{ - {Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{20}[0]}, - {Key: "key2", Value: "value2", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{30}[0]}, - }, - }}, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{{Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{10}[0]}}, - }, - }, - "", - "added valid new toleration to existing tolerations in pod spec updates", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: core.PodSpec{ - NodeName: "node1", - Tolerations: []core.Toleration{ - {Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{20}[0]}, - {Key: "key2", Value: "value2", Operator: "Equal", Effect: "NoSchedule", TolerationSeconds: &[]int64{30}[0]}, - }, - }}, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", Tolerations: []core.Toleration{{Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{10}[0]}}, - }}, - "spec.tolerations[1].effect", - "added invalid new toleration to existing tolerations in pod spec updates", - }, - { - core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: core.PodSpec{NodeName: "foo"}}, - core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}}, - "spec: Forbidden: pod updates may not change fields", - "removed nodeName from pod spec", - }, - { - core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Annotations: map[string]string{core.MirrorPodAnnotationKey: ""}}, Spec: core.PodSpec{NodeName: "foo"}}, - core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: core.PodSpec{NodeName: "foo"}}, - "metadata.annotations[kubernetes.io/config.mirror]", - "added mirror pod annotation", - }, - { - core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: core.PodSpec{NodeName: "foo"}}, - core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Annotations: map[string]string{core.MirrorPodAnnotationKey: ""}}, Spec: core.PodSpec{NodeName: "foo"}}, - "metadata.annotations[kubernetes.io/config.mirror]", - "removed mirror pod annotation", - }, - { - core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Annotations: map[string]string{core.MirrorPodAnnotationKey: "foo"}}, Spec: core.PodSpec{NodeName: "foo"}}, - core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Annotations: map[string]string{core.MirrorPodAnnotationKey: "bar"}}, Spec: core.PodSpec{NodeName: "foo"}}, - "metadata.annotations[kubernetes.io/config.mirror]", - "changed mirror pod annotation", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - PriorityClassName: "bar-priority", - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - PriorityClassName: "foo-priority", - }, - }, - "spec: Forbidden: pod updates", - "changed priority class name", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - PriorityClassName: "", - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - PriorityClassName: "foo-priority", - }, - }, - "spec: Forbidden: pod updates", - "removed priority class name", - }, - } - - for _, test := range tests { - test.new.ObjectMeta.ResourceVersion = "1" - test.old.ObjectMeta.ResourceVersion = "1" - errs := ValidatePodUpdate(&test.new, &test.old) - if test.err == "" { - if len(errs) != 0 { - t.Errorf("unexpected invalid: %s (%+v)\nA: %+v\nB: %+v", test.test, errs, test.new, test.old) - } - } else { - if len(errs) == 0 { - t.Errorf("unexpected valid: %s\nA: %+v\nB: %+v", test.test, test.new, test.old) - } else if actualErr := errs.ToAggregate().Error(); !strings.Contains(actualErr, test.err) { - t.Errorf("unexpected error message: %s\nExpected error: %s\nActual error: %s", test.test, test.err, actualErr) - } - } - } -} - -func TestValidatePodStatusUpdate(t *testing.T) { - tests := []struct { - new core.Pod - old core.Pod - err string - test string - }{ - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - }, - Status: core.PodStatus{ - NominatedNodeName: "node1", - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - }, - Status: core.PodStatus{}, - }, - "", - "removed nominatedNodeName", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - }, - Status: core.PodStatus{ - NominatedNodeName: "node1", - }, - }, - "", - "add valid nominatedNodeName", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - }, - Status: core.PodStatus{ - NominatedNodeName: "Node1", - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - }, - }, - "nominatedNodeName", - "Add invalid nominatedNodeName", - }, - { - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - }, - Status: core.PodStatus{ - NominatedNodeName: "node1", - }, - }, - core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.PodSpec{ - NodeName: "node1", - }, - Status: core.PodStatus{ - NominatedNodeName: "node2", - }, - }, - "", - "Update nominatedNodeName", - }, - } - - for _, test := range tests { - test.new.ObjectMeta.ResourceVersion = "1" - test.old.ObjectMeta.ResourceVersion = "1" - errs := ValidatePodStatusUpdate(&test.new, &test.old) - if test.err == "" { - if len(errs) != 0 { - t.Errorf("unexpected invalid: %s (%+v)\nA: %+v\nB: %+v", test.test, errs, test.new, test.old) - } - } else { - if len(errs) == 0 { - t.Errorf("unexpected valid: %s\nA: %+v\nB: %+v", test.test, test.new, test.old) - } else if actualErr := errs.ToAggregate().Error(); !strings.Contains(actualErr, test.err) { - t.Errorf("unexpected error message: %s\nExpected error: %s\nActual error: %s", test.test, test.err, actualErr) - } - } - } -} - -func makeValidService() core.Service { - return core.Service{ - ObjectMeta: metav1.ObjectMeta{ - Name: "valid", - Namespace: "valid", - Labels: map[string]string{}, - Annotations: map[string]string{}, - ResourceVersion: "1", - }, - Spec: core.ServiceSpec{ - Selector: map[string]string{"key": "val"}, - SessionAffinity: "None", - Type: core.ServiceTypeClusterIP, - Ports: []core.ServicePort{{Name: "p", Protocol: "TCP", Port: 8675, TargetPort: intstr.FromInt(8675)}}, - }, - } -} - -func TestValidateService(t *testing.T) { - testCases := []struct { - name string - tweakSvc func(svc *core.Service) // given a basic valid service, each test case can customize it - numErrs int - }{ - { - name: "missing namespace", - tweakSvc: func(s *core.Service) { - s.Namespace = "" - }, - numErrs: 1, - }, - { - name: "invalid namespace", - tweakSvc: func(s *core.Service) { - s.Namespace = "-123" - }, - numErrs: 1, - }, - { - name: "missing name", - tweakSvc: func(s *core.Service) { - s.Name = "" - }, - numErrs: 1, - }, - { - name: "invalid name", - tweakSvc: func(s *core.Service) { - s.Name = "-123" - }, - numErrs: 1, - }, - { - name: "too long name", - tweakSvc: func(s *core.Service) { - s.Name = strings.Repeat("a", 64) - }, - numErrs: 1, - }, - { - name: "invalid generateName", - tweakSvc: func(s *core.Service) { - s.GenerateName = "-123" - }, - numErrs: 1, - }, - { - name: "too long generateName", - tweakSvc: func(s *core.Service) { - s.GenerateName = strings.Repeat("a", 64) - }, - numErrs: 1, - }, - { - name: "invalid label", - tweakSvc: func(s *core.Service) { - s.Labels["NoUppercaseOrSpecialCharsLike=Equals"] = "bar" - }, - numErrs: 1, - }, - { - name: "invalid annotation", - tweakSvc: func(s *core.Service) { - s.Annotations["NoSpecialCharsLike=Equals"] = "bar" - }, - numErrs: 1, - }, - { - name: "nil selector", - tweakSvc: func(s *core.Service) { - s.Spec.Selector = nil - }, - numErrs: 0, - }, - { - name: "invalid selector", - tweakSvc: func(s *core.Service) { - s.Spec.Selector["NoSpecialCharsLike=Equals"] = "bar" - }, - numErrs: 1, - }, - { - name: "missing session affinity", - tweakSvc: func(s *core.Service) { - s.Spec.SessionAffinity = "" - }, - numErrs: 1, - }, - { - name: "missing type", - tweakSvc: func(s *core.Service) { - s.Spec.Type = "" - }, - numErrs: 1, - }, - { - name: "missing ports", - tweakSvc: func(s *core.Service) { - s.Spec.Ports = nil - }, - numErrs: 1, - }, - { - name: "missing ports but headless", - tweakSvc: func(s *core.Service) { - s.Spec.Ports = nil - s.Spec.ClusterIP = core.ClusterIPNone - }, - numErrs: 0, - }, - { - name: "empty port[0] name", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Name = "" - }, - numErrs: 0, - }, - { - name: "empty port[1] name", - tweakSvc: func(s *core.Service) { - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "", Protocol: "TCP", Port: 12345, TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "empty multi-port port[0] name", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Name = "" - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "p", Protocol: "TCP", Port: 12345, TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "invalid port name", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Name = "INVALID" - }, - numErrs: 1, - }, - { - name: "missing protocol", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Protocol = "" - }, - numErrs: 1, - }, - { - name: "invalid protocol", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Protocol = "INVALID" - }, - numErrs: 1, - }, - { - name: "invalid cluster ip", - tweakSvc: func(s *core.Service) { - s.Spec.ClusterIP = "invalid" - }, - numErrs: 1, - }, - { - name: "missing port", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Port = 0 - }, - numErrs: 1, - }, - { - name: "invalid port", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Port = 65536 - }, - numErrs: 1, - }, - { - name: "invalid TargetPort int", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].TargetPort = intstr.FromInt(65536) - }, - numErrs: 1, - }, - { - name: "valid port headless", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Port = 11722 - s.Spec.Ports[0].TargetPort = intstr.FromInt(11722) - s.Spec.ClusterIP = core.ClusterIPNone - }, - numErrs: 0, - }, - { - name: "invalid port headless 1", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Port = 11722 - s.Spec.Ports[0].TargetPort = intstr.FromInt(11721) - s.Spec.ClusterIP = core.ClusterIPNone - }, - // in the v1 API, targetPorts on headless services were tolerated. - // once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility. - // numErrs: 1, - numErrs: 0, - }, - { - name: "invalid port headless 2", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Port = 11722 - s.Spec.Ports[0].TargetPort = intstr.FromString("target") - s.Spec.ClusterIP = core.ClusterIPNone - }, - // in the v1 API, targetPorts on headless services were tolerated. - // once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility. - // numErrs: 1, - numErrs: 0, - }, - { - name: "invalid publicIPs localhost", - tweakSvc: func(s *core.Service) { - s.Spec.ExternalIPs = []string{"127.0.0.1"} - }, - numErrs: 1, - }, - { - name: "invalid publicIPs unspecified", - tweakSvc: func(s *core.Service) { - s.Spec.ExternalIPs = []string{"0.0.0.0"} - }, - numErrs: 1, - }, - { - name: "invalid publicIPs loopback", - tweakSvc: func(s *core.Service) { - s.Spec.ExternalIPs = []string{"127.0.0.1"} - }, - numErrs: 1, - }, - { - name: "invalid publicIPs host", - tweakSvc: func(s *core.Service) { - s.Spec.ExternalIPs = []string{"myhost.mydomain"} - }, - numErrs: 1, - }, - { - name: "dup port name", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Name = "p" - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "p", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "valid load balancer protocol UDP 1", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.Ports[0].Protocol = "UDP" - }, - numErrs: 0, - }, - { - name: "valid load balancer protocol UDP 2", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.Ports[0] = core.ServicePort{Name: "q", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(12345)} - }, - numErrs: 0, - }, - { - name: "invalid load balancer with mix protocol", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "valid 1", - tweakSvc: func(s *core.Service) { - // do nothing - }, - numErrs: 0, - }, - { - name: "valid 2", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].Protocol = "UDP" - s.Spec.Ports[0].TargetPort = intstr.FromInt(12345) - }, - numErrs: 0, - }, - { - name: "valid 3", - tweakSvc: func(s *core.Service) { - s.Spec.Ports[0].TargetPort = intstr.FromString("http") - }, - numErrs: 0, - }, - { - name: "valid cluster ip - none ", - tweakSvc: func(s *core.Service) { - s.Spec.ClusterIP = "None" - }, - numErrs: 0, - }, - { - name: "valid cluster ip - empty", - tweakSvc: func(s *core.Service) { - s.Spec.ClusterIP = "" - s.Spec.Ports[0].TargetPort = intstr.FromString("http") - }, - numErrs: 0, - }, - { - name: "valid type - cluster", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeClusterIP - }, - numErrs: 0, - }, - { - name: "valid type - loadbalancer", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - }, - numErrs: 0, - }, - { - name: "valid type loadbalancer 2 ports", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "valid external load balancer 2 ports", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "duplicate nodeports", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)}) - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "r", Port: 2, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(2)}) - }, - numErrs: 1, - }, - { - name: "duplicate nodeports (different protocols)", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)}) - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "r", Port: 2, Protocol: "UDP", NodePort: 1, TargetPort: intstr.FromInt(2)}) - }, - numErrs: 0, - }, - { - name: "invalid duplicate ports (with same protocol)", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeClusterIP - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}) - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "r", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(80)}) - }, - numErrs: 1, - }, - { - name: "valid duplicate ports (with different protocols)", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeClusterIP - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}) - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "r", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(80)}) - }, - numErrs: 0, - }, - { - name: "valid type - cluster", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeClusterIP - }, - numErrs: 0, - }, - { - name: "valid type - nodeport", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeNodePort - }, - numErrs: 0, - }, - { - name: "valid type - loadbalancer", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - }, - numErrs: 0, - }, - { - name: "valid type loadbalancer 2 ports", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "valid type loadbalancer with NodePort", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "valid type=NodePort service with NodePort", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "valid type=NodePort service without NodePort", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "valid cluster service without NodePort", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeClusterIP - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - name: "invalid cluster service with NodePort", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeClusterIP - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "invalid public service with duplicate NodePort", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "p1", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)}) - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "p2", Port: 2, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(2)}) - }, - numErrs: 1, - }, - { - name: "valid type=LoadBalancer", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 0, - }, - { - // For now we open firewalls, and its insecure if we open 10250, remove this - // when we have better protections in place. - name: "invalid port type=LoadBalancer", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "kubelet", Port: 10250, Protocol: "TCP", TargetPort: intstr.FromInt(12345)}) - }, - numErrs: 1, - }, - { - name: "valid LoadBalancer source range annotation", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Annotations[core.AnnotationLoadBalancerSourceRangesKey] = "1.2.3.4/8, 5.6.7.8/16" - }, - numErrs: 0, - }, - { - name: "empty LoadBalancer source range annotation", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Annotations[core.AnnotationLoadBalancerSourceRangesKey] = "" - }, - numErrs: 0, - }, - { - name: "invalid LoadBalancer source range annotation (hostname)", - tweakSvc: func(s *core.Service) { - s.Annotations[core.AnnotationLoadBalancerSourceRangesKey] = "foo.bar" - }, - numErrs: 2, - }, - { - name: "invalid LoadBalancer source range annotation (invalid CIDR)", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Annotations[core.AnnotationLoadBalancerSourceRangesKey] = "1.2.3.4/33" - }, - numErrs: 1, - }, - { - name: "invalid source range for non LoadBalancer type service", - tweakSvc: func(s *core.Service) { - s.Spec.LoadBalancerSourceRanges = []string{"1.2.3.4/8", "5.6.7.8/16"} - }, - numErrs: 1, - }, - { - name: "valid LoadBalancer source range", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.LoadBalancerSourceRanges = []string{"1.2.3.4/8", "5.6.7.8/16"} - }, - numErrs: 0, - }, - { - name: "empty LoadBalancer source range", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.LoadBalancerSourceRanges = []string{" "} - }, - numErrs: 1, - }, - { - name: "invalid LoadBalancer source range", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.LoadBalancerSourceRanges = []string{"foo.bar"} - }, - numErrs: 1, - }, - { - name: "valid ExternalName", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeExternalName - s.Spec.ClusterIP = "" - s.Spec.ExternalName = "foo.bar.example.com" - }, - numErrs: 0, - }, - { - name: "invalid ExternalName clusterIP (valid IP)", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeExternalName - s.Spec.ClusterIP = "1.2.3.4" - s.Spec.ExternalName = "foo.bar.example.com" - }, - numErrs: 1, - }, - { - name: "invalid ExternalName clusterIP (None)", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeExternalName - s.Spec.ClusterIP = "None" - s.Spec.ExternalName = "foo.bar.example.com" - }, - numErrs: 1, - }, - { - name: "invalid ExternalName (not a DNS name)", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeExternalName - s.Spec.ClusterIP = "" - s.Spec.ExternalName = "-123" - }, - numErrs: 1, - }, - { - name: "LoadBalancer type cannot have None ClusterIP", - tweakSvc: func(s *core.Service) { - s.Spec.ClusterIP = "None" - s.Spec.Type = core.ServiceTypeLoadBalancer - }, - numErrs: 1, - }, - { - name: "invalid node port with clusterIP None", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeNodePort - s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)}) - s.Spec.ClusterIP = "None" - }, - numErrs: 1, - }, - // ESIPP section begins. - { - name: "invalid externalTraffic field", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.ExternalTrafficPolicy = "invalid" - }, - numErrs: 1, - }, - { - name: "nagative healthCheckNodePort field", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal - s.Spec.HealthCheckNodePort = -1 - }, - numErrs: 1, - }, - { - name: "nagative healthCheckNodePort field", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal - s.Spec.HealthCheckNodePort = 31100 - }, - numErrs: 0, - }, - // ESIPP section ends. - { - name: "invalid timeoutSeconds field", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeClusterIP - s.Spec.SessionAffinity = core.ServiceAffinityClientIP - s.Spec.SessionAffinityConfig = &core.SessionAffinityConfig{ - ClientIP: &core.ClientIPConfig{ - TimeoutSeconds: newInt32(-1), - }, - } - }, - numErrs: 1, - }, - { - name: "sessionAffinityConfig can't be set when session affinity is None", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.SessionAffinity = core.ServiceAffinityNone - s.Spec.SessionAffinityConfig = &core.SessionAffinityConfig{ - ClientIP: &core.ClientIPConfig{ - TimeoutSeconds: newInt32(90), - }, - } - }, - numErrs: 1, - }, - } - - for _, tc := range testCases { - svc := makeValidService() - tc.tweakSvc(&svc) - errs := ValidateService(&svc) - if len(errs) != tc.numErrs { - t.Errorf("Unexpected error list for case %q: %v", tc.name, errs.ToAggregate()) - } - } -} - -func TestValidateServiceExternalTrafficFieldsCombination(t *testing.T) { - testCases := []struct { - name string - tweakSvc func(svc *core.Service) // Given a basic valid service, each test case can customize it. - numErrs int - }{ - { - name: "valid loadBalancer service with externalTrafficPolicy and healthCheckNodePort set", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal - s.Spec.HealthCheckNodePort = 34567 - }, - numErrs: 0, - }, - { - name: "valid nodePort service with externalTrafficPolicy set", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeNodePort - s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal - }, - numErrs: 0, - }, - { - name: "valid clusterIP service with none of externalTrafficPolicy and healthCheckNodePort set", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeClusterIP - }, - numErrs: 0, - }, - { - name: "cannot set healthCheckNodePort field on loadBalancer service with externalTrafficPolicy!=Local", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeLoadBalancer - s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeCluster - s.Spec.HealthCheckNodePort = 34567 - }, - numErrs: 1, - }, - { - name: "cannot set healthCheckNodePort field on nodePort service", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeNodePort - s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal - s.Spec.HealthCheckNodePort = 34567 - }, - numErrs: 1, - }, - { - name: "cannot set externalTrafficPolicy or healthCheckNodePort fields on clusterIP service", - tweakSvc: func(s *core.Service) { - s.Spec.Type = core.ServiceTypeClusterIP - s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal - s.Spec.HealthCheckNodePort = 34567 - }, - numErrs: 2, - }, - } - - for _, tc := range testCases { - svc := makeValidService() - tc.tweakSvc(&svc) - errs := ValidateServiceExternalTrafficFieldsCombination(&svc) - if len(errs) != tc.numErrs { - t.Errorf("Unexpected error list for case %q: %v", tc.name, errs.ToAggregate()) - } - } -} - -func TestValidateReplicationControllerStatus(t *testing.T) { - tests := []struct { - name string - - replicas int32 - fullyLabeledReplicas int32 - readyReplicas int32 - availableReplicas int32 - observedGeneration int64 - - expectedErr bool - }{ - { - name: "valid status", - replicas: 3, - fullyLabeledReplicas: 3, - readyReplicas: 2, - availableReplicas: 1, - observedGeneration: 2, - expectedErr: false, - }, - { - name: "invalid replicas", - replicas: -1, - fullyLabeledReplicas: 3, - readyReplicas: 2, - availableReplicas: 1, - observedGeneration: 2, - expectedErr: true, - }, - { - name: "invalid fullyLabeledReplicas", - replicas: 3, - fullyLabeledReplicas: -1, - readyReplicas: 2, - availableReplicas: 1, - observedGeneration: 2, - expectedErr: true, - }, - { - name: "invalid readyReplicas", - replicas: 3, - fullyLabeledReplicas: 3, - readyReplicas: -1, - availableReplicas: 1, - observedGeneration: 2, - expectedErr: true, - }, - { - name: "invalid availableReplicas", - replicas: 3, - fullyLabeledReplicas: 3, - readyReplicas: 3, - availableReplicas: -1, - observedGeneration: 2, - expectedErr: true, - }, - { - name: "invalid observedGeneration", - replicas: 3, - fullyLabeledReplicas: 3, - readyReplicas: 3, - availableReplicas: 3, - observedGeneration: -1, - expectedErr: true, - }, - { - name: "fullyLabeledReplicas greater than replicas", - replicas: 3, - fullyLabeledReplicas: 4, - readyReplicas: 3, - availableReplicas: 3, - observedGeneration: 1, - expectedErr: true, - }, - { - name: "readyReplicas greater than replicas", - replicas: 3, - fullyLabeledReplicas: 3, - readyReplicas: 4, - availableReplicas: 3, - observedGeneration: 1, - expectedErr: true, - }, - { - name: "availableReplicas greater than replicas", - replicas: 3, - fullyLabeledReplicas: 3, - readyReplicas: 3, - availableReplicas: 4, - observedGeneration: 1, - expectedErr: true, - }, - { - name: "availableReplicas greater than readyReplicas", - replicas: 3, - fullyLabeledReplicas: 3, - readyReplicas: 2, - availableReplicas: 3, - observedGeneration: 1, - expectedErr: true, - }, - } - - for _, test := range tests { - status := core.ReplicationControllerStatus{ - Replicas: test.replicas, - FullyLabeledReplicas: test.fullyLabeledReplicas, - ReadyReplicas: test.readyReplicas, - AvailableReplicas: test.availableReplicas, - ObservedGeneration: test.observedGeneration, - } - - if hasErr := len(ValidateReplicationControllerStatus(status, field.NewPath("status"))) > 0; hasErr != test.expectedErr { - t.Errorf("%s: expected error: %t, got error: %t", test.name, test.expectedErr, hasErr) - } - } -} - -func TestValidateReplicationControllerStatusUpdate(t *testing.T) { - validSelector := map[string]string{"a": "b"} - validPodTemplate := core.PodTemplate{ - Template: core.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: validSelector, - }, - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - }, - } - type rcUpdateTest struct { - old core.ReplicationController - update core.ReplicationController - } - successCases := []rcUpdateTest{ - { - old: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - Status: core.ReplicationControllerStatus{ - Replicas: 2, - }, - }, - update: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Replicas: 3, - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - Status: core.ReplicationControllerStatus{ - Replicas: 4, - }, - }, - }, - } - for _, successCase := range successCases { - successCase.old.ObjectMeta.ResourceVersion = "1" - successCase.update.ObjectMeta.ResourceVersion = "1" - if errs := ValidateReplicationControllerStatusUpdate(&successCase.update, &successCase.old); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - errorCases := map[string]rcUpdateTest{ - "negative replicas": { - old: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - Status: core.ReplicationControllerStatus{ - Replicas: 3, - }, - }, - update: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Replicas: 2, - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - Status: core.ReplicationControllerStatus{ - Replicas: -3, - }, - }, - }, - } - for testName, errorCase := range errorCases { - if errs := ValidateReplicationControllerStatusUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 { - t.Errorf("expected failure: %s", testName) - } - } - -} - -func TestValidateReplicationControllerUpdate(t *testing.T) { - validSelector := map[string]string{"a": "b"} - validPodTemplate := core.PodTemplate{ - Template: core.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: validSelector, - }, - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - }, - } - readWriteVolumePodTemplate := core.PodTemplate{ - Template: core.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: validSelector, - }, - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - Volumes: []core.Volume{{Name: "gcepd", VolumeSource: core.VolumeSource{GCEPersistentDisk: &core.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}}, - }, - }, - } - invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - invalidPodTemplate := core.PodTemplate{ - Template: core.PodTemplateSpec{ - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - ObjectMeta: metav1.ObjectMeta{ - Labels: invalidSelector, - }, - }, - } - type rcUpdateTest struct { - old core.ReplicationController - update core.ReplicationController - } - successCases := []rcUpdateTest{ - { - old: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Replicas: 3, - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - }, - { - old: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Replicas: 1, - Selector: validSelector, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - }, - } - for _, successCase := range successCases { - successCase.old.ObjectMeta.ResourceVersion = "1" - successCase.update.ObjectMeta.ResourceVersion = "1" - if errs := ValidateReplicationControllerUpdate(&successCase.update, &successCase.old); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - errorCases := map[string]rcUpdateTest{ - "more than one read/write": { - old: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Replicas: 2, - Selector: validSelector, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - }, - "invalid selector": { - old: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Replicas: 2, - Selector: invalidSelector, - Template: &validPodTemplate.Template, - }, - }, - }, - "invalid pod": { - old: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Replicas: 2, - Selector: validSelector, - Template: &invalidPodTemplate.Template, - }, - }, - }, - "negative replicas": { - old: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - update: core.ReplicationController{ - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Replicas: -1, - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - }, - } - for testName, errorCase := range errorCases { - if errs := ValidateReplicationControllerUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 { - t.Errorf("expected failure: %s", testName) - } - } -} - -func TestValidateReplicationController(t *testing.T) { - validSelector := map[string]string{"a": "b"} - validPodTemplate := core.PodTemplate{ - Template: core.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: validSelector, - }, - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - }, - } - readWriteVolumePodTemplate := core.PodTemplate{ - Template: core.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: validSelector, - }, - Spec: core.PodSpec{ - Volumes: []core.Volume{{Name: "gcepd", VolumeSource: core.VolumeSource{GCEPersistentDisk: &core.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}}, - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - }, - } - invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - invalidPodTemplate := core.PodTemplate{ - Template: core.PodTemplateSpec{ - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyAlways, - DNSPolicy: core.DNSClusterFirst, - }, - ObjectMeta: metav1.ObjectMeta{ - Labels: invalidSelector, - }, - }, - } - successCases := []core.ReplicationController{ - { - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{Name: "abc-123", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{Name: "abc-123", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Replicas: 1, - Selector: validSelector, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateReplicationController(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]core.ReplicationController{ - "zero-length ID": { - ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - "missing-namespace": { - ObjectMeta: metav1.ObjectMeta{Name: "abc-123"}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - "empty selector": { - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Template: &validPodTemplate.Template, - }, - }, - "selector_doesnt_match": { - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: map[string]string{"foo": "bar"}, - Template: &validPodTemplate.Template, - }, - }, - "invalid manifest": { - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - }, - }, - "read-write persistent disk with > 1 pod": { - ObjectMeta: metav1.ObjectMeta{Name: "abc"}, - Spec: core.ReplicationControllerSpec{ - Replicas: 2, - Selector: validSelector, - Template: &readWriteVolumePodTemplate.Template, - }, - }, - "negative_replicas": { - ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault}, - Spec: core.ReplicationControllerSpec{ - Replicas: -1, - Selector: validSelector, - }, - }, - "invalid_label": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc-123", - Namespace: metav1.NamespaceDefault, - Labels: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - "invalid_label 2": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc-123", - Namespace: metav1.NamespaceDefault, - Labels: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: core.ReplicationControllerSpec{ - Template: &invalidPodTemplate.Template, - }, - }, - "invalid_annotation": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc-123", - Namespace: metav1.NamespaceDefault, - Annotations: map[string]string{ - "NoUppercaseOrSpecialCharsLike=Equals": "bar", - }, - }, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &validPodTemplate.Template, - }, - }, - "invalid restart policy 1": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc-123", - Namespace: metav1.NamespaceDefault, - }, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &core.PodTemplateSpec{ - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyOnFailure, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - ObjectMeta: metav1.ObjectMeta{ - Labels: validSelector, - }, - }, - }, - }, - "invalid restart policy 2": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc-123", - Namespace: metav1.NamespaceDefault, - }, - Spec: core.ReplicationControllerSpec{ - Selector: validSelector, - Template: &core.PodTemplateSpec{ - Spec: core.PodSpec{ - RestartPolicy: core.RestartPolicyNever, - DNSPolicy: core.DNSClusterFirst, - Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}}, - }, - ObjectMeta: metav1.ObjectMeta{ - Labels: validSelector, - }, - }, - }, - }, - } - for k, v := range errorCases { - errs := ValidateReplicationController(&v) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - field := errs[i].Field - if !strings.HasPrefix(field, "spec.template.") && - field != "metadata.name" && - field != "metadata.namespace" && - field != "spec.selector" && - field != "spec.template" && - field != "GCEPersistentDisk.ReadOnly" && - field != "spec.replicas" && - field != "spec.template.labels" && - field != "metadata.annotations" && - field != "metadata.labels" && - field != "status.replicas" { - t.Errorf("%s: missing prefix for: %v", k, errs[i]) - } - } - } -} - -func TestValidateNode(t *testing.T) { - validSelector := map[string]string{"a": "b"} - invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - successCases := []core.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Labels: validSelector, - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "something"}, - }, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("my.org/gpu"): resource.MustParse("10"), - core.ResourceName("hugepages-2Mi"): resource.MustParse("10Gi"), - core.ResourceName("hugepages-1Gi"): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "something"}, - }, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "dedicated-node1", - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "something"}, - }, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - // Add a valid taint to a node - Taints: []core.Taint{{Key: "GPU", Value: "true", Effect: "NoSchedule"}}, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Annotations: map[string]string{ - core.PreferAvoidPodsAnnotationKey: ` - { - "preferAvoidPods": [ - { - "podSignature": { - "podController": { - "apiVersion": "v1", - "kind": "ReplicationController", - "name": "foo", - "uid": "abcdef123456", - "controller": true - } - }, - "reason": "some reason", - "message": "some message" - } - ] - }`, - }, - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "something"}, - }, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "something"}, - }, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - PodCIDR: "192.168.0.0/16", - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateNode(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]core.Node{ - "zero-length Name": { - ObjectMeta: metav1.ObjectMeta{ - Name: "", - Labels: validSelector, - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{}, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - }, - }, - "invalid-labels": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc-123", - Labels: invalidSelector, - }, - Status: core.NodeStatus{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - }, - }, - "missing-external-id": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc-123", - Labels: validSelector, - }, - Status: core.NodeStatus{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - }, - }, - }, - "missing-taint-key": { - ObjectMeta: metav1.ObjectMeta{ - Name: "dedicated-node1", - }, - Spec: core.NodeSpec{ - ExternalID: "external", - // Add a taint with an empty key to a node - Taints: []core.Taint{{Key: "", Value: "special-user-1", Effect: "NoSchedule"}}, - }, - }, - "bad-taint-key": { - ObjectMeta: metav1.ObjectMeta{ - Name: "dedicated-node1", - }, - Spec: core.NodeSpec{ - ExternalID: "external", - // Add a taint with an invalid key to a node - Taints: []core.Taint{{Key: "NoUppercaseOrSpecialCharsLike=Equals", Value: "special-user-1", Effect: "NoSchedule"}}, - }, - }, - "bad-taint-value": { - ObjectMeta: metav1.ObjectMeta{ - Name: "dedicated-node2", - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "something"}, - }, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - // Add a taint with a bad value to a node - Taints: []core.Taint{{Key: "dedicated", Value: "some\\bad\\value", Effect: "NoSchedule"}}, - }, - }, - "missing-taint-effect": { - ObjectMeta: metav1.ObjectMeta{ - Name: "dedicated-node3", - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "something"}, - }, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - // Add a taint with an empty effect to a node - Taints: []core.Taint{{Key: "dedicated", Value: "special-user-3", Effect: ""}}, - }, - }, - "invalid-taint-effect": { - ObjectMeta: metav1.ObjectMeta{ - Name: "dedicated-node3", - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "something"}, - }, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - // Add a taint with NoExecute effect to a node - Taints: []core.Taint{{Key: "dedicated", Value: "special-user-3", Effect: "NoScheduleNoAdmit"}}, - }, - }, - "duplicated-taints-with-same-key-effect": { - ObjectMeta: metav1.ObjectMeta{ - Name: "dedicated-node1", - }, - Spec: core.NodeSpec{ - ExternalID: "external", - // Add two taints to the node with the same key and effect; should be rejected. - Taints: []core.Taint{ - {Key: "dedicated", Value: "special-user-1", Effect: "NoSchedule"}, - {Key: "dedicated", Value: "special-user-2", Effect: "NoSchedule"}, - }, - }, - }, - "missing-podSignature": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc-123", - Annotations: map[string]string{ - core.PreferAvoidPodsAnnotationKey: ` - { - "preferAvoidPods": [ - { - "reason": "some reason", - "message": "some message" - } - ] - }`, - }, - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{}, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - }, - }, - "invalid-podController": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc-123", - Annotations: map[string]string{ - core.PreferAvoidPodsAnnotationKey: ` - { - "preferAvoidPods": [ - { - "podSignature": { - "podController": { - "apiVersion": "v1", - "kind": "ReplicationController", - "name": "foo", - "uid": "abcdef123456", - "controller": false - } - }, - "reason": "some reason", - "message": "some message" - } - ] - }`, - }, - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{}, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - }, - }, - "multiple-pre-allocated-hugepages": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Labels: validSelector, - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "something"}, - }, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("my.org/gpu"): resource.MustParse("10"), - core.ResourceName("hugepages-2Mi"): resource.MustParse("10Gi"), - core.ResourceName("hugepages-1Gi"): resource.MustParse("10Gi"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - }, - }, - "invalid-pod-cidr": { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "something"}, - }, - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("0"), - }, - }, - Spec: core.NodeSpec{ - ExternalID: "external", - PodCIDR: "192.168.0.0", - }, - }, - } - for k, v := range errorCases { - errs := ValidateNode(&v) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - field := errs[i].Field - expectedFields := map[string]bool{ - "metadata.name": true, - "metadata.labels": true, - "metadata.annotations": true, - "metadata.namespace": true, - "spec.externalID": true, - "spec.taints[0].key": true, - "spec.taints[0].value": true, - "spec.taints[0].effect": true, - "metadata.annotations.scheduler.alpha.kubernetes.io/preferAvoidPods[0].PodSignature": true, - "metadata.annotations.scheduler.alpha.kubernetes.io/preferAvoidPods[0].PodSignature.PodController.Controller": true, - } - if val, ok := expectedFields[field]; ok { - if !val { - t.Errorf("%s: missing prefix for: %v", k, errs[i]) - } - } - } - } -} - -func TestValidateNodeUpdate(t *testing.T) { - tests := []struct { - oldNode core.Node - node core.Node - valid bool - }{ - {core.Node{}, core.Node{}, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo"}}, - core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "bar"}, - }, false}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "bar"}, - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"bar": "foo"}, - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.NodeSpec{ - PodCIDR: "", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.NodeSpec{ - PodCIDR: "192.168.0.0/16", - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.NodeSpec{ - PodCIDR: "192.123.0.0/16", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.NodeSpec{ - PodCIDR: "192.168.0.0/16", - }, - }, false}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Status: core.NodeStatus{ - Capacity: core.ResourceList{ - core.ResourceCPU: resource.MustParse("10000"), - core.ResourceMemory: resource.MustParse("100"), - }, - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Status: core.NodeStatus{ - Capacity: core.ResourceList{ - core.ResourceCPU: resource.MustParse("100"), - core.ResourceMemory: resource.MustParse("10000"), - }, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"bar": "foo"}, - }, - Status: core.NodeStatus{ - Capacity: core.ResourceList{ - core.ResourceCPU: resource.MustParse("10000"), - core.ResourceMemory: resource.MustParse("100"), - }, - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"bar": "fooobaz"}, - }, - Status: core.NodeStatus{ - Capacity: core.ResourceList{ - core.ResourceCPU: resource.MustParse("100"), - core.ResourceMemory: resource.MustParse("10000"), - }, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"bar": "foo"}, - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "1.2.3.4"}, - }, - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"bar": "fooobaz"}, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"foo": "baz"}, - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Labels: map[string]string{"Foo": "baz"}, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.NodeSpec{ - Unschedulable: false, - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.NodeSpec{ - Unschedulable: true, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.NodeSpec{ - Unschedulable: false, - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - }, - }, - }, false}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Spec: core.NodeSpec{ - Unschedulable: false, - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - Status: core.NodeStatus{ - Addresses: []core.NodeAddress{ - {Type: core.NodeExternalIP, Address: "1.1.1.1"}, - {Type: core.NodeInternalIP, Address: "10.1.1.1"}, - }, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Annotations: map[string]string{ - core.PreferAvoidPodsAnnotationKey: ` - { - "preferAvoidPods": [ - { - "podSignature": { - "podController": { - "apiVersion": "v1", - "kind": "ReplicationController", - "name": "foo", - "uid": "abcdef123456", - "controller": true - } - }, - "reason": "some reason", - "message": "some message" - } - ] - }`, - }, - }, - Spec: core.NodeSpec{ - Unschedulable: false, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Annotations: map[string]string{ - core.PreferAvoidPodsAnnotationKey: ` - { - "preferAvoidPods": [ - { - "reason": "some reason", - "message": "some message" - } - ] - }`, - }, - }, - }, false}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Annotations: map[string]string{ - core.PreferAvoidPodsAnnotationKey: ` - { - "preferAvoidPods": [ - { - "podSignature": { - "podController": { - "apiVersion": "v1", - "kind": "ReplicationController", - "name": "foo", - "uid": "abcdef123456", - "controller": false - } - }, - "reason": "some reason", - "message": "some message" - } - ] - }`, - }, - }, - }, false}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "valid-extended-resources", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "valid-extended-resources", - }, - Status: core.NodeStatus{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("example.com/a"): resource.MustParse("5"), - core.ResourceName("example.com/b"): resource.MustParse("10"), - }, - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "invalid-fractional-extended-capacity", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "invalid-fractional-extended-capacity", - }, - Status: core.NodeStatus{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("example.com/a"): resource.MustParse("500m"), - }, - }, - }, false}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "invalid-fractional-extended-allocatable", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "invalid-fractional-extended-allocatable", - }, - Status: core.NodeStatus{ - Capacity: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("example.com/a"): resource.MustParse("5"), - }, - Allocatable: core.ResourceList{ - core.ResourceName(core.ResourceCPU): resource.MustParse("10"), - core.ResourceName(core.ResourceMemory): resource.MustParse("10G"), - core.ResourceName("example.com/a"): resource.MustParse("4.5"), - }, - }, - }, false}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "update-provider-id-when-not-set", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "update-provider-id-when-not-set", - }, - Spec: core.NodeSpec{ - ProviderID: "provider:///new", - }, - }, true}, - {core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "update-provider-id-when-set", - }, - Spec: core.NodeSpec{ - ProviderID: "provider:///old", - }, - }, core.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: "update-provider-id-when-set", - }, - Spec: core.NodeSpec{ - ProviderID: "provider:///new", - }, - }, false}, - } - for i, test := range tests { - test.oldNode.ObjectMeta.ResourceVersion = "1" - test.node.ObjectMeta.ResourceVersion = "1" - errs := ValidateNodeUpdate(&test.node, &test.oldNode) - if test.valid && len(errs) > 0 { - t.Errorf("%d: Unexpected error: %v", i, errs) - t.Logf("%#v vs %#v", test.oldNode.ObjectMeta, test.node.ObjectMeta) - } - if !test.valid && len(errs) == 0 { - t.Errorf("%d: Unexpected non-error", i) - } - } -} - -func TestValidateServiceUpdate(t *testing.T) { - testCases := []struct { - name string - tweakSvc func(oldSvc, newSvc *core.Service) // given basic valid services, each test case can customize them - numErrs int - }{ - { - name: "no change", - tweakSvc: func(oldSvc, newSvc *core.Service) { - // do nothing - }, - numErrs: 0, - }, - { - name: "change name", - tweakSvc: func(oldSvc, newSvc *core.Service) { - newSvc.Name += "2" - }, - numErrs: 1, - }, - { - name: "change namespace", - tweakSvc: func(oldSvc, newSvc *core.Service) { - newSvc.Namespace += "2" - }, - numErrs: 1, - }, - { - name: "change label valid", - tweakSvc: func(oldSvc, newSvc *core.Service) { - newSvc.Labels["key"] = "other-value" - }, - numErrs: 0, - }, - { - name: "add label", - tweakSvc: func(oldSvc, newSvc *core.Service) { - newSvc.Labels["key2"] = "value2" - }, - numErrs: 0, - }, - { - name: "change cluster IP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "8.6.7.5" - }, - numErrs: 1, - }, - { - name: "remove cluster IP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "" - }, - numErrs: 1, - }, - { - name: "change affinity", - tweakSvc: func(oldSvc, newSvc *core.Service) { - newSvc.Spec.SessionAffinity = "ClientIP" - newSvc.Spec.SessionAffinityConfig = &core.SessionAffinityConfig{ - ClientIP: &core.ClientIPConfig{ - TimeoutSeconds: newInt32(90), - }, - } - }, - numErrs: 0, - }, - { - name: "remove affinity", - tweakSvc: func(oldSvc, newSvc *core.Service) { - newSvc.Spec.SessionAffinity = "" - }, - numErrs: 1, - }, - { - name: "change type", - tweakSvc: func(oldSvc, newSvc *core.Service) { - newSvc.Spec.Type = core.ServiceTypeLoadBalancer - }, - numErrs: 0, - }, - { - name: "remove type", - tweakSvc: func(oldSvc, newSvc *core.Service) { - newSvc.Spec.Type = "" - }, - numErrs: 1, - }, - { - name: "change type -> nodeport", - tweakSvc: func(oldSvc, newSvc *core.Service) { - newSvc.Spec.Type = core.ServiceTypeNodePort - }, - numErrs: 0, - }, - { - name: "add loadBalancerSourceRanges", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeLoadBalancer - newSvc.Spec.Type = core.ServiceTypeLoadBalancer - newSvc.Spec.LoadBalancerSourceRanges = []string{"10.0.0.0/8"} - }, - numErrs: 0, - }, - { - name: "update loadBalancerSourceRanges", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeLoadBalancer - oldSvc.Spec.LoadBalancerSourceRanges = []string{"10.0.0.0/8"} - newSvc.Spec.Type = core.ServiceTypeLoadBalancer - newSvc.Spec.LoadBalancerSourceRanges = []string{"10.100.0.0/16"} - }, - numErrs: 0, - }, - { - name: "LoadBalancer type cannot have None ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - newSvc.Spec.ClusterIP = "None" - newSvc.Spec.Type = core.ServiceTypeLoadBalancer - }, - numErrs: 1, - }, - { - name: "`None` ClusterIP cannot be changed", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.ClusterIP = "None" - newSvc.Spec.ClusterIP = "1.2.3.4" - }, - numErrs: 1, - }, - { - name: "`None` ClusterIP cannot be removed", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.ClusterIP = "None" - newSvc.Spec.ClusterIP = "" - }, - numErrs: 1, - }, - { - name: "Service with ClusterIP type cannot change its set ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeClusterIP - newSvc.Spec.Type = core.ServiceTypeClusterIP - - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 1, - }, - { - name: "Service with ClusterIP type can change its empty ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeClusterIP - newSvc.Spec.Type = core.ServiceTypeClusterIP - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "Service with ClusterIP type cannot change its set ClusterIP when changing type to NodePort", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeClusterIP - newSvc.Spec.Type = core.ServiceTypeNodePort - - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 1, - }, - { - name: "Service with ClusterIP type can change its empty ClusterIP when changing type to NodePort", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeClusterIP - newSvc.Spec.Type = core.ServiceTypeNodePort - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "Service with ClusterIP type cannot change its ClusterIP when changing type to LoadBalancer", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeClusterIP - newSvc.Spec.Type = core.ServiceTypeLoadBalancer - - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 1, - }, - { - name: "Service with ClusterIP type can change its empty ClusterIP when changing type to LoadBalancer", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeClusterIP - newSvc.Spec.Type = core.ServiceTypeLoadBalancer - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "Service with NodePort type cannot change its set ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeNodePort - newSvc.Spec.Type = core.ServiceTypeNodePort - - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 1, - }, - { - name: "Service with NodePort type can change its empty ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeNodePort - newSvc.Spec.Type = core.ServiceTypeNodePort - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "Service with NodePort type cannot change its set ClusterIP when changing type to ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeNodePort - newSvc.Spec.Type = core.ServiceTypeClusterIP - - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 1, - }, - { - name: "Service with NodePort type can change its empty ClusterIP when changing type to ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeNodePort - newSvc.Spec.Type = core.ServiceTypeClusterIP - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "Service with NodePort type cannot change its set ClusterIP when changing type to LoadBalancer", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeNodePort - newSvc.Spec.Type = core.ServiceTypeLoadBalancer - - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 1, - }, - { - name: "Service with NodePort type can change its empty ClusterIP when changing type to LoadBalancer", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeNodePort - newSvc.Spec.Type = core.ServiceTypeLoadBalancer - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "Service with LoadBalancer type cannot change its set ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeLoadBalancer - newSvc.Spec.Type = core.ServiceTypeLoadBalancer - - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 1, - }, - { - name: "Service with LoadBalancer type can change its empty ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeLoadBalancer - newSvc.Spec.Type = core.ServiceTypeLoadBalancer - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "Service with LoadBalancer type cannot change its set ClusterIP when changing type to ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeLoadBalancer - newSvc.Spec.Type = core.ServiceTypeClusterIP - - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 1, - }, - { - name: "Service with LoadBalancer type can change its empty ClusterIP when changing type to ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeLoadBalancer - newSvc.Spec.Type = core.ServiceTypeClusterIP - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "Service with LoadBalancer type cannot change its set ClusterIP when changing type to NodePort", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeLoadBalancer - newSvc.Spec.Type = core.ServiceTypeNodePort - - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 1, - }, - { - name: "Service with LoadBalancer type can change its empty ClusterIP when changing type to NodePort", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeLoadBalancer - newSvc.Spec.Type = core.ServiceTypeNodePort - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "Service with ExternalName type can change its empty ClusterIP when changing type to ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeExternalName - newSvc.Spec.Type = core.ServiceTypeClusterIP - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "Service with ExternalName type can change its set ClusterIP when changing type to ClusterIP", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeExternalName - newSvc.Spec.Type = core.ServiceTypeClusterIP - - oldSvc.Spec.ClusterIP = "1.2.3.4" - newSvc.Spec.ClusterIP = "1.2.3.5" - }, - numErrs: 0, - }, - { - name: "invalid node port with clusterIP None", - tweakSvc: func(oldSvc, newSvc *core.Service) { - oldSvc.Spec.Type = core.ServiceTypeNodePort - newSvc.Spec.Type = core.ServiceTypeNodePort - - oldSvc.Spec.Ports = append(oldSvc.Spec.Ports, core.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)}) - newSvc.Spec.Ports = append(newSvc.Spec.Ports, core.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)}) - - oldSvc.Spec.ClusterIP = "" - newSvc.Spec.ClusterIP = "None" - }, - numErrs: 1, - }, - } - - for _, tc := range testCases { - oldSvc := makeValidService() - newSvc := makeValidService() - tc.tweakSvc(&oldSvc, &newSvc) - errs := ValidateServiceUpdate(&newSvc, &oldSvc) - if len(errs) != tc.numErrs { - t.Errorf("Unexpected error list for case %q: %v", tc.name, errs.ToAggregate()) - } - } -} - -func TestValidateResourceNames(t *testing.T) { - table := []struct { - input string - success bool - expect string - }{ - {"memory", true, ""}, - {"cpu", true, ""}, - {"storage", true, ""}, - {"requests.cpu", true, ""}, - {"requests.memory", true, ""}, - {"requests.storage", true, ""}, - {"limits.cpu", true, ""}, - {"limits.memory", true, ""}, - {"network", false, ""}, - {"disk", false, ""}, - {"", false, ""}, - {".", false, ""}, - {"..", false, ""}, - {"my.favorite.app.co/12345", true, ""}, - {"my.favorite.app.co/_12345", false, ""}, - {"my.favorite.app.co/12345_", false, ""}, - {"kubernetes.io/..", false, ""}, - {"kubernetes.io/" + strings.Repeat("a", 63), true, ""}, - {"kubernetes.io/" + strings.Repeat("a", 64), false, ""}, - {"kubernetes.io//", false, ""}, - {"kubernetes.io", false, ""}, - {"kubernetes.io/will/not/work/", false, ""}, - } - for k, item := range table { - err := validateResourceName(item.input, field.NewPath("field")) - if len(err) != 0 && item.success { - t.Errorf("expected no failure for input %q", item.input) - } else if len(err) == 0 && !item.success { - t.Errorf("expected failure for input %q", item.input) - for i := range err { - detail := err[i].Detail - if detail != "" && !strings.Contains(detail, item.expect) { - t.Errorf("%d: expected error detail either empty or %s, got %s", k, item.expect, detail) - } - } - } - } -} - -func getResourceList(cpu, memory string) core.ResourceList { - res := core.ResourceList{} - if cpu != "" { - res[core.ResourceCPU] = resource.MustParse(cpu) - } - if memory != "" { - res[core.ResourceMemory] = resource.MustParse(memory) - } - return res -} - -func getStorageResourceList(storage string) core.ResourceList { - res := core.ResourceList{} - if storage != "" { - res[core.ResourceStorage] = resource.MustParse(storage) - } - return res -} - -func getLocalStorageResourceList(ephemeralStorage string) core.ResourceList { - res := core.ResourceList{} - if ephemeralStorage != "" { - res[core.ResourceEphemeralStorage] = resource.MustParse(ephemeralStorage) - } - return res -} - -func TestValidateLimitRangeForLocalStorage(t *testing.T) { - testCases := []struct { - name string - spec core.LimitRangeSpec - }{ - { - name: "all-fields-valid", - spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePod, - Max: getLocalStorageResourceList("10000Mi"), - Min: getLocalStorageResourceList("100Mi"), - MaxLimitRequestRatio: getLocalStorageResourceList(""), - }, - { - Type: core.LimitTypeContainer, - Max: getLocalStorageResourceList("10000Mi"), - Min: getLocalStorageResourceList("100Mi"), - Default: getLocalStorageResourceList("500Mi"), - DefaultRequest: getLocalStorageResourceList("200Mi"), - MaxLimitRequestRatio: getLocalStorageResourceList(""), - }, - }, - }, - }, - } - - // Enable alpha feature LocalStorageCapacityIsolation - err := utilfeature.DefaultFeatureGate.Set("LocalStorageCapacityIsolation=true") - if err != nil { - t.Errorf("Failed to enable feature gate for LocalStorageCapacityIsolation: %v", err) - return - } - - for _, testCase := range testCases { - limitRange := &core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: testCase.name, Namespace: "foo"}, Spec: testCase.spec} - if errs := ValidateLimitRange(limitRange); len(errs) != 0 { - t.Errorf("Case %v, unexpected error: %v", testCase.name, errs) - } - } - - // Disable alpha feature LocalStorageCapacityIsolation - err = utilfeature.DefaultFeatureGate.Set("LocalStorageCapacityIsolation=false") - if err != nil { - t.Errorf("Failed to disable feature gate for LocalStorageCapacityIsolation: %v", err) - return - } - for _, testCase := range testCases { - limitRange := &core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: testCase.name, Namespace: "foo"}, Spec: testCase.spec} - if errs := ValidateLimitRange(limitRange); len(errs) == 0 { - t.Errorf("Case %v, expected feature gate unable error but actually no error", testCase.name) - } - } - -} - -func TestValidateLimitRange(t *testing.T) { - successCases := []struct { - name string - spec core.LimitRangeSpec - }{ - { - name: "all-fields-valid", - spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePod, - Max: getResourceList("100m", "10000Mi"), - Min: getResourceList("5m", "100Mi"), - MaxLimitRequestRatio: getResourceList("10", ""), - }, - { - Type: core.LimitTypeContainer, - Max: getResourceList("100m", "10000Mi"), - Min: getResourceList("5m", "100Mi"), - Default: getResourceList("50m", "500Mi"), - DefaultRequest: getResourceList("10m", "200Mi"), - MaxLimitRequestRatio: getResourceList("10", ""), - }, - { - Type: core.LimitTypePersistentVolumeClaim, - Max: getStorageResourceList("10Gi"), - Min: getStorageResourceList("5Gi"), - }, - }, - }, - }, - { - name: "pvc-min-only", - spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePersistentVolumeClaim, - Min: getStorageResourceList("5Gi"), - }, - }, - }, - }, - { - name: "pvc-max-only", - spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePersistentVolumeClaim, - Max: getStorageResourceList("10Gi"), - }, - }, - }, - }, - { - name: "all-fields-valid-big-numbers", - spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypeContainer, - Max: getResourceList("100m", "10000T"), - Min: getResourceList("5m", "100Mi"), - Default: getResourceList("50m", "500Mi"), - DefaultRequest: getResourceList("10m", "200Mi"), - MaxLimitRequestRatio: getResourceList("10", ""), - }, - }, - }, - }, - { - name: "thirdparty-fields-all-valid-standard-container-resources", - spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: "thirdparty.com/foo", - Max: getResourceList("100m", "10000T"), - Min: getResourceList("5m", "100Mi"), - Default: getResourceList("50m", "500Mi"), - DefaultRequest: getResourceList("10m", "200Mi"), - MaxLimitRequestRatio: getResourceList("10", ""), - }, - }, - }, - }, - { - name: "thirdparty-fields-all-valid-storage-resources", - spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: "thirdparty.com/foo", - Max: getStorageResourceList("10000T"), - Min: getStorageResourceList("100Mi"), - Default: getStorageResourceList("500Mi"), - DefaultRequest: getStorageResourceList("200Mi"), - MaxLimitRequestRatio: getStorageResourceList(""), - }, - }, - }, - }, - } - - for _, successCase := range successCases { - limitRange := &core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: successCase.name, Namespace: "foo"}, Spec: successCase.spec} - if errs := ValidateLimitRange(limitRange); len(errs) != 0 { - t.Errorf("Case %v, unexpected error: %v", successCase.name, errs) - } - } - - errorCases := map[string]struct { - R core.LimitRange - D string - }{ - "zero-length-name": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: "foo"}, Spec: core.LimitRangeSpec{}}, - "name or generateName is required", - }, - "zero-length-namespace": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: ""}, Spec: core.LimitRangeSpec{}}, - "", - }, - "invalid-name": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "^Invalid", Namespace: "foo"}, Spec: core.LimitRangeSpec{}}, - dnsSubdomainLabelErrMsg, - }, - "invalid-namespace": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "^Invalid"}, Spec: core.LimitRangeSpec{}}, - dnsLabelErrMsg, - }, - "duplicate-limit-type": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePod, - Max: getResourceList("100m", "10000m"), - Min: getResourceList("0m", "100m"), - }, - { - Type: core.LimitTypePod, - Min: getResourceList("0m", "100m"), - }, - }, - }}, - "", - }, - "default-limit-type-pod": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePod, - Max: getResourceList("100m", "10000m"), - Min: getResourceList("0m", "100m"), - Default: getResourceList("10m", "100m"), - }, - }, - }}, - "may not be specified when `type` is 'Pod'", - }, - "default-request-limit-type-pod": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePod, - Max: getResourceList("100m", "10000m"), - Min: getResourceList("0m", "100m"), - DefaultRequest: getResourceList("10m", "100m"), - }, - }, - }}, - "may not be specified when `type` is 'Pod'", - }, - "min value 100m is greater than max value 10m": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePod, - Max: getResourceList("10m", ""), - Min: getResourceList("100m", ""), - }, - }, - }}, - "min value 100m is greater than max value 10m", - }, - "invalid spec default outside range": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypeContainer, - Max: getResourceList("1", ""), - Min: getResourceList("100m", ""), - Default: getResourceList("2000m", ""), - }, - }, - }}, - "default value 2 is greater than max value 1", - }, - "invalid spec default request outside range": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypeContainer, - Max: getResourceList("1", ""), - Min: getResourceList("100m", ""), - DefaultRequest: getResourceList("2000m", ""), - }, - }, - }}, - "default request value 2 is greater than max value 1", - }, - "invalid spec default request more than default": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypeContainer, - Max: getResourceList("2", ""), - Min: getResourceList("100m", ""), - Default: getResourceList("500m", ""), - DefaultRequest: getResourceList("800m", ""), - }, - }, - }}, - "default request value 800m is greater than default limit value 500m", - }, - "invalid spec maxLimitRequestRatio less than 1": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePod, - MaxLimitRequestRatio: getResourceList("800m", ""), - }, - }, - }}, - "ratio 800m is less than 1", - }, - "invalid spec maxLimitRequestRatio greater than max/min": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypeContainer, - Max: getResourceList("", "2Gi"), - Min: getResourceList("", "512Mi"), - MaxLimitRequestRatio: getResourceList("", "10"), - }, - }, - }}, - "ratio 10 is greater than max/min = 4.000000", - }, - "invalid non standard limit type": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: "foo", - Max: getStorageResourceList("10000T"), - Min: getStorageResourceList("100Mi"), - Default: getStorageResourceList("500Mi"), - DefaultRequest: getStorageResourceList("200Mi"), - MaxLimitRequestRatio: getStorageResourceList(""), - }, - }, - }}, - "must be a standard limit type or fully qualified", - }, - "min and max values missing, one required": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePersistentVolumeClaim, - }, - }, - }}, - "either minimum or maximum storage value is required, but neither was provided", - }, - "invalid min greater than max": { - core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{ - Limits: []core.LimitRangeItem{ - { - Type: core.LimitTypePersistentVolumeClaim, - Min: getStorageResourceList("10Gi"), - Max: getStorageResourceList("1Gi"), - }, - }, - }}, - "min value 10Gi is greater than max value 1Gi", - }, - } - - for k, v := range errorCases { - errs := ValidateLimitRange(&v.R) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - detail := errs[i].Detail - if !strings.Contains(detail, v.D) { - t.Errorf("[%s]: expected error detail either empty or %q, got %q", k, v.D, detail) - } - } - } - -} - -func TestValidatePersistentVolumeClaimStatusUpdate(t *testing.T) { - validClaim := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }) - validConditionUpdate := testVolumeClaimWithStatus("foo", "ns", core.PersistentVolumeClaimSpec{ - AccessModes: []core.PersistentVolumeAccessMode{ - core.ReadWriteOnce, - core.ReadOnlyMany, - }, - Resources: core.ResourceRequirements{ - Requests: core.ResourceList{ - core.ResourceName(core.ResourceStorage): resource.MustParse("10G"), - }, - }, - }, core.PersistentVolumeClaimStatus{ - Phase: core.ClaimPending, - Conditions: []core.PersistentVolumeClaimCondition{ - {Type: core.PersistentVolumeClaimResizing, Status: core.ConditionTrue}, - }, - }) - scenarios := map[string]struct { - isExpectedFailure bool - oldClaim *core.PersistentVolumeClaim - newClaim *core.PersistentVolumeClaim - enableResize bool - }{ - "condition-update-with-disabled-feature-gate": { - isExpectedFailure: true, - oldClaim: validClaim, - newClaim: validConditionUpdate, - enableResize: false, - }, - "condition-update-with-enabled-feature-gate": { - isExpectedFailure: false, - oldClaim: validClaim, - newClaim: validConditionUpdate, - enableResize: true, - }, - } - for name, scenario := range scenarios { - // ensure we have a resource version specified for updates - togglePVExpandFeature(scenario.enableResize, t) - scenario.oldClaim.ResourceVersion = "1" - scenario.newClaim.ResourceVersion = "1" - errs := ValidatePersistentVolumeClaimStatusUpdate(scenario.newClaim, scenario.oldClaim) - if len(errs) == 0 && scenario.isExpectedFailure { - t.Errorf("Unexpected success for scenario: %s", name) - } - if len(errs) > 0 && !scenario.isExpectedFailure { - t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs) - } - } -} - -func TestValidateResourceQuota(t *testing.T) { - spec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourceCPU: resource.MustParse("100"), - core.ResourceMemory: resource.MustParse("10000"), - core.ResourceRequestsCPU: resource.MustParse("100"), - core.ResourceRequestsMemory: resource.MustParse("10000"), - core.ResourceLimitsCPU: resource.MustParse("100"), - core.ResourceLimitsMemory: resource.MustParse("10000"), - core.ResourcePods: resource.MustParse("10"), - core.ResourceServices: resource.MustParse("0"), - core.ResourceReplicationControllers: resource.MustParse("10"), - core.ResourceQuotas: resource.MustParse("10"), - core.ResourceConfigMaps: resource.MustParse("10"), - core.ResourceSecrets: resource.MustParse("10"), - }, - } - - terminatingSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourceCPU: resource.MustParse("100"), - core.ResourceLimitsCPU: resource.MustParse("200"), - }, - Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeTerminating}, - } - - nonTerminatingSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourceCPU: resource.MustParse("100"), - }, - Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeNotTerminating}, - } - - bestEffortSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourcePods: resource.MustParse("100"), - }, - Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeBestEffort}, - } - - nonBestEffortSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourceCPU: resource.MustParse("100"), - }, - Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeNotBestEffort}, - } - - // storage is not yet supported as a quota tracked resource - invalidQuotaResourceSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourceStorage: resource.MustParse("10"), - }, - } - - negativeSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourceCPU: resource.MustParse("-100"), - core.ResourceMemory: resource.MustParse("-10000"), - core.ResourcePods: resource.MustParse("-10"), - core.ResourceServices: resource.MustParse("-10"), - core.ResourceReplicationControllers: resource.MustParse("-10"), - core.ResourceQuotas: resource.MustParse("-10"), - core.ResourceConfigMaps: resource.MustParse("-10"), - core.ResourceSecrets: resource.MustParse("-10"), - }, - } - - fractionalComputeSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourceCPU: resource.MustParse("100m"), - }, - } - - fractionalPodSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourcePods: resource.MustParse(".1"), - core.ResourceServices: resource.MustParse(".5"), - core.ResourceReplicationControllers: resource.MustParse("1.25"), - core.ResourceQuotas: resource.MustParse("2.5"), - }, - } - - invalidTerminatingScopePairsSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourceCPU: resource.MustParse("100"), - }, - Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeTerminating, core.ResourceQuotaScopeNotTerminating}, - } - - invalidBestEffortScopePairsSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourcePods: resource.MustParse("100"), - }, - Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeBestEffort, core.ResourceQuotaScopeNotBestEffort}, - } - - invalidScopeNameSpec := core.ResourceQuotaSpec{ - Hard: core.ResourceList{ - core.ResourceCPU: resource.MustParse("100"), - }, - Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScope("foo")}, - } - - successCases := []core.ResourceQuota{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: spec, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: fractionalComputeSpec, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: terminatingSpec, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: nonTerminatingSpec, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: bestEffortSpec, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "abc", - Namespace: "foo", - }, - Spec: nonBestEffortSpec, - }, - } - - for _, successCase := range successCases { - if errs := ValidateResourceQuota(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - - errorCases := map[string]struct { - R core.ResourceQuota - D string - }{ - "zero-length Name": { - core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: "foo"}, Spec: spec}, - "name or generateName is required", - }, - "zero-length Namespace": { - core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: ""}, Spec: spec}, - "", - }, - "invalid Name": { - core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "^Invalid", Namespace: "foo"}, Spec: spec}, - dnsSubdomainLabelErrMsg, - }, - "invalid Namespace": { - core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "^Invalid"}, Spec: spec}, - dnsLabelErrMsg, - }, - "negative-limits": { - core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: negativeSpec}, - isNegativeErrorMsg, - }, - "fractional-api-resource": { - core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: fractionalPodSpec}, - isNotIntegerErrorMsg, - }, - "invalid-quota-resource": { - core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidQuotaResourceSpec}, - isInvalidQuotaResource, - }, - "invalid-quota-terminating-pair": { - core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidTerminatingScopePairsSpec}, - "conflicting scopes", - }, - "invalid-quota-besteffort-pair": { - core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidBestEffortScopePairsSpec}, - "conflicting scopes", - }, - "invalid-quota-scope-name": { - core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidScopeNameSpec}, - "unsupported scope", - }, - } - for k, v := range errorCases { - errs := ValidateResourceQuota(&v.R) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - for i := range errs { - if !strings.Contains(errs[i].Detail, v.D) { - t.Errorf("[%s]: expected error detail either empty or %s, got %s", k, v.D, errs[i].Detail) - } - } - } -} - -func TestValidateNamespace(t *testing.T) { - validLabels := map[string]string{"a": "b"} - invalidLabels := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"} - successCases := []core.Namespace{ - { - ObjectMeta: metav1.ObjectMeta{Name: "abc", Labels: validLabels}, - }, - { - ObjectMeta: metav1.ObjectMeta{Name: "abc-123"}, - Spec: core.NamespaceSpec{ - Finalizers: []core.FinalizerName{"example.com/something", "example.com/other"}, - }, - }, - } - for _, successCase := range successCases { - if errs := ValidateNamespace(&successCase); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - } - errorCases := map[string]struct { - R core.Namespace - D string - }{ - "zero-length name": { - core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ""}}, - "", - }, - "defined-namespace": { - core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "abc-123", Namespace: "makesnosense"}}, - "", - }, - "invalid-labels": { - core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "abc", Labels: invalidLabels}}, - "", - }, - } - for k, v := range errorCases { - errs := ValidateNamespace(&v.R) - if len(errs) == 0 { - t.Errorf("expected failure for %s", k) - } - } -} - -func TestValidateNamespaceFinalizeUpdate(t *testing.T) { - tests := []struct { - oldNamespace core.Namespace - namespace core.Namespace - valid bool - }{ - {core.Namespace{}, core.Namespace{}, true}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo"}}, - core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo"}, - Spec: core.NamespaceSpec{ - Finalizers: []core.FinalizerName{"Foo"}, - }, - }, false}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo"}, - Spec: core.NamespaceSpec{ - Finalizers: []core.FinalizerName{"foo.com/bar"}, - }, - }, - core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo"}, - Spec: core.NamespaceSpec{ - Finalizers: []core.FinalizerName{"foo.com/bar", "what.com/bar"}, - }, - }, true}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "fooemptyfinalizer"}, - Spec: core.NamespaceSpec{ - Finalizers: []core.FinalizerName{"foo.com/bar"}, - }, - }, - core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "fooemptyfinalizer"}, - Spec: core.NamespaceSpec{ - Finalizers: []core.FinalizerName{"", "foo.com/bar", "what.com/bar"}, - }, - }, false}, - } - for i, test := range tests { - test.namespace.ObjectMeta.ResourceVersion = "1" - test.oldNamespace.ObjectMeta.ResourceVersion = "1" - errs := ValidateNamespaceFinalizeUpdate(&test.namespace, &test.oldNamespace) - if test.valid && len(errs) > 0 { - t.Errorf("%d: Unexpected error: %v", i, errs) - t.Logf("%#v vs %#v", test.oldNamespace, test.namespace) - } - if !test.valid && len(errs) == 0 { - t.Errorf("%d: Unexpected non-error", i) - } - } -} - -func TestValidateNamespaceStatusUpdate(t *testing.T) { - now := metav1.Now() - - tests := []struct { - oldNamespace core.Namespace - namespace core.Namespace - valid bool - }{ - {core.Namespace{}, core.Namespace{ - Status: core.NamespaceStatus{ - Phase: core.NamespaceActive, - }, - }, true}, - // Cannot set deletionTimestamp via status update - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo"}}, - core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - DeletionTimestamp: &now}, - Status: core.NamespaceStatus{ - Phase: core.NamespaceTerminating, - }, - }, false}, - // Can update phase via status update - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - DeletionTimestamp: &now}}, - core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - DeletionTimestamp: &now}, - Status: core.NamespaceStatus{ - Phase: core.NamespaceTerminating, - }, - }, true}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo"}}, - core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo"}, - Status: core.NamespaceStatus{ - Phase: core.NamespaceTerminating, - }, - }, false}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo"}}, - core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "bar"}, - Status: core.NamespaceStatus{ - Phase: core.NamespaceTerminating, - }, - }, false}, - } - for i, test := range tests { - test.namespace.ObjectMeta.ResourceVersion = "1" - test.oldNamespace.ObjectMeta.ResourceVersion = "1" - errs := ValidateNamespaceStatusUpdate(&test.namespace, &test.oldNamespace) - if test.valid && len(errs) > 0 { - t.Errorf("%d: Unexpected error: %v", i, errs) - t.Logf("%#v vs %#v", test.oldNamespace.ObjectMeta, test.namespace.ObjectMeta) - } - if !test.valid && len(errs) == 0 { - t.Errorf("%d: Unexpected non-error", i) - } - } -} - -func TestValidateNamespaceUpdate(t *testing.T) { - tests := []struct { - oldNamespace core.Namespace - namespace core.Namespace - valid bool - }{ - {core.Namespace{}, core.Namespace{}, true}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo1"}}, - core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "bar1"}, - }, false}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo2", - Labels: map[string]string{"foo": "bar"}, - }, - }, core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo2", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo3", - }, - }, core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo3", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo4", - Labels: map[string]string{"bar": "foo"}, - }, - }, core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo4", - Labels: map[string]string{"foo": "baz"}, - }, - }, true}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo5", - Labels: map[string]string{"foo": "baz"}, - }, - }, core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo5", - Labels: map[string]string{"Foo": "baz"}, - }, - }, true}, - {core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo6", - Labels: map[string]string{"foo": "baz"}, - }, - }, core.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo6", - Labels: map[string]string{"Foo": "baz"}, - }, - Spec: core.NamespaceSpec{ - Finalizers: []core.FinalizerName{"kubernetes"}, - }, - Status: core.NamespaceStatus{ - Phase: core.NamespaceTerminating, - }, - }, true}, - } - for i, test := range tests { - test.namespace.ObjectMeta.ResourceVersion = "1" - test.oldNamespace.ObjectMeta.ResourceVersion = "1" - errs := ValidateNamespaceUpdate(&test.namespace, &test.oldNamespace) - if test.valid && len(errs) > 0 { - t.Errorf("%d: Unexpected error: %v", i, errs) - t.Logf("%#v vs %#v", test.oldNamespace.ObjectMeta, test.namespace.ObjectMeta) - } - if !test.valid && len(errs) == 0 { - t.Errorf("%d: Unexpected non-error", i) - } - } -} - -func TestValidateSecret(t *testing.T) { - // Opaque secret validation - validSecret := func() core.Secret { - return core.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"}, - Data: map[string][]byte{ - "data-1": []byte("bar"), - }, - } - } - - var ( - emptyName = validSecret() - invalidName = validSecret() - emptyNs = validSecret() - invalidNs = validSecret() - overMaxSize = validSecret() - invalidKey = validSecret() - leadingDotKey = validSecret() - dotKey = validSecret() - doubleDotKey = validSecret() - ) - - emptyName.Name = "" - invalidName.Name = "NoUppercaseOrSpecialCharsLike=Equals" - emptyNs.Namespace = "" - invalidNs.Namespace = "NoUppercaseOrSpecialCharsLike=Equals" - overMaxSize.Data = map[string][]byte{ - "over": make([]byte, core.MaxSecretSize+1), - } - invalidKey.Data["a*b"] = []byte("whoops") - leadingDotKey.Data[".key"] = []byte("bar") - dotKey.Data["."] = []byte("bar") - doubleDotKey.Data[".."] = []byte("bar") - - // kubernetes.io/service-account-token secret validation - validServiceAccountTokenSecret := func() core.Secret { - return core.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: "bar", - Annotations: map[string]string{ - core.ServiceAccountNameKey: "foo", - }, - }, - Type: core.SecretTypeServiceAccountToken, - Data: map[string][]byte{ - "data-1": []byte("bar"), - }, - } - } - - var ( - emptyTokenAnnotation = validServiceAccountTokenSecret() - missingTokenAnnotation = validServiceAccountTokenSecret() - missingTokenAnnotations = validServiceAccountTokenSecret() - ) - emptyTokenAnnotation.Annotations[core.ServiceAccountNameKey] = "" - delete(missingTokenAnnotation.Annotations, core.ServiceAccountNameKey) - missingTokenAnnotations.Annotations = nil - - tests := map[string]struct { - secret core.Secret - valid bool - }{ - "valid": {validSecret(), true}, - "empty name": {emptyName, false}, - "invalid name": {invalidName, false}, - "empty namespace": {emptyNs, false}, - "invalid namespace": {invalidNs, false}, - "over max size": {overMaxSize, false}, - "invalid key": {invalidKey, false}, - "valid service-account-token secret": {validServiceAccountTokenSecret(), true}, - "empty service-account-token annotation": {emptyTokenAnnotation, false}, - "missing service-account-token annotation": {missingTokenAnnotation, false}, - "missing service-account-token annotations": {missingTokenAnnotations, false}, - "leading dot key": {leadingDotKey, true}, - "dot key": {dotKey, false}, - "double dot key": {doubleDotKey, false}, - } - - for name, tc := range tests { - errs := ValidateSecret(&tc.secret) - if tc.valid && len(errs) > 0 { - t.Errorf("%v: Unexpected error: %v", name, errs) - } - if !tc.valid && len(errs) == 0 { - t.Errorf("%v: Unexpected non-error", name) - } - } -} - -func TestValidateDockerConfigSecret(t *testing.T) { - validDockerSecret := func() core.Secret { - return core.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"}, - Type: core.SecretTypeDockercfg, - Data: map[string][]byte{ - core.DockerConfigKey: []byte(`{"https://index.docker.io/v1/": {"auth": "Y2x1ZWRyb29sZXIwMDAxOnBhc3N3b3Jk","email": "fake@example.com"}}`), - }, - } - } - validDockerSecret2 := func() core.Secret { - return core.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"}, - Type: core.SecretTypeDockerConfigJson, - Data: map[string][]byte{ - core.DockerConfigJsonKey: []byte(`{"auths":{"https://index.docker.io/v1/": {"auth": "Y2x1ZWRyb29sZXIwMDAxOnBhc3N3b3Jk","email": "fake@example.com"}}}`), - }, - } - } - - var ( - missingDockerConfigKey = validDockerSecret() - emptyDockerConfigKey = validDockerSecret() - invalidDockerConfigKey = validDockerSecret() - missingDockerConfigKey2 = validDockerSecret2() - emptyDockerConfigKey2 = validDockerSecret2() - invalidDockerConfigKey2 = validDockerSecret2() - ) - - delete(missingDockerConfigKey.Data, core.DockerConfigKey) - emptyDockerConfigKey.Data[core.DockerConfigKey] = []byte("") - invalidDockerConfigKey.Data[core.DockerConfigKey] = []byte("bad") - delete(missingDockerConfigKey2.Data, core.DockerConfigJsonKey) - emptyDockerConfigKey2.Data[core.DockerConfigJsonKey] = []byte("") - invalidDockerConfigKey2.Data[core.DockerConfigJsonKey] = []byte("bad") - - tests := map[string]struct { - secret core.Secret - valid bool - }{ - "valid dockercfg": {validDockerSecret(), true}, - "missing dockercfg": {missingDockerConfigKey, false}, - "empty dockercfg": {emptyDockerConfigKey, false}, - "invalid dockercfg": {invalidDockerConfigKey, false}, - "valid config.json": {validDockerSecret2(), true}, - "missing config.json": {missingDockerConfigKey2, false}, - "empty config.json": {emptyDockerConfigKey2, false}, - "invalid config.json": {invalidDockerConfigKey2, false}, - } - - for name, tc := range tests { - errs := ValidateSecret(&tc.secret) - if tc.valid && len(errs) > 0 { - t.Errorf("%v: Unexpected error: %v", name, errs) - } - if !tc.valid && len(errs) == 0 { - t.Errorf("%v: Unexpected non-error", name) - } - } -} - -func TestValidateBasicAuthSecret(t *testing.T) { - validBasicAuthSecret := func() core.Secret { - return core.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"}, - Type: core.SecretTypeBasicAuth, - Data: map[string][]byte{ - core.BasicAuthUsernameKey: []byte("username"), - core.BasicAuthPasswordKey: []byte("password"), - }, - } - } - - var ( - missingBasicAuthUsernamePasswordKeys = validBasicAuthSecret() - ) - - delete(missingBasicAuthUsernamePasswordKeys.Data, core.BasicAuthUsernameKey) - delete(missingBasicAuthUsernamePasswordKeys.Data, core.BasicAuthPasswordKey) - - tests := map[string]struct { - secret core.Secret - valid bool - }{ - "valid": {validBasicAuthSecret(), true}, - "missing username and password": {missingBasicAuthUsernamePasswordKeys, false}, - } - - for name, tc := range tests { - errs := ValidateSecret(&tc.secret) - if tc.valid && len(errs) > 0 { - t.Errorf("%v: Unexpected error: %v", name, errs) - } - if !tc.valid && len(errs) == 0 { - t.Errorf("%v: Unexpected non-error", name) - } - } -} - -func TestValidateSSHAuthSecret(t *testing.T) { - validSSHAuthSecret := func() core.Secret { - return core.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"}, - Type: core.SecretTypeSSHAuth, - Data: map[string][]byte{ - core.SSHAuthPrivateKey: []byte("foo-bar-baz"), - }, - } - } - - missingSSHAuthPrivateKey := validSSHAuthSecret() - - delete(missingSSHAuthPrivateKey.Data, core.SSHAuthPrivateKey) - - tests := map[string]struct { - secret core.Secret - valid bool - }{ - "valid": {validSSHAuthSecret(), true}, - "missing private key": {missingSSHAuthPrivateKey, false}, - } - - for name, tc := range tests { - errs := ValidateSecret(&tc.secret) - if tc.valid && len(errs) > 0 { - t.Errorf("%v: Unexpected error: %v", name, errs) - } - if !tc.valid && len(errs) == 0 { - t.Errorf("%v: Unexpected non-error", name) - } - } -} - -func TestValidateEndpoints(t *testing.T) { - successCases := map[string]core.Endpoints{ - "simple endpoint": { - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}, {IP: "10.10.2.2"}}, - Ports: []core.EndpointPort{{Name: "a", Port: 8675, Protocol: "TCP"}, {Name: "b", Port: 309, Protocol: "TCP"}}, - }, - { - Addresses: []core.EndpointAddress{{IP: "10.10.3.3"}}, - Ports: []core.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}, {Name: "b", Port: 76, Protocol: "TCP"}}, - }, - }, - }, - "empty subsets": { - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - }, - "no name required for singleton port": { - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []core.EndpointPort{{Port: 8675, Protocol: "TCP"}}, - }, - }, - }, - "empty ports": { - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "10.10.3.3"}}, - }, - }, - }, - } - - for k, v := range successCases { - if errs := ValidateEndpoints(&v); len(errs) != 0 { - t.Errorf("Expected success for %s, got %v", k, errs) - } - } - - errorCases := map[string]struct { - endpoints core.Endpoints - errorType field.ErrorType - errorDetail string - }{ - "missing namespace": { - endpoints: core.Endpoints{ObjectMeta: metav1.ObjectMeta{Name: "mysvc"}}, - errorType: "FieldValueRequired", - }, - "missing name": { - endpoints: core.Endpoints{ObjectMeta: metav1.ObjectMeta{Namespace: "namespace"}}, - errorType: "FieldValueRequired", - }, - "invalid namespace": { - endpoints: core.Endpoints{ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "no@#invalid.;chars\"allowed"}}, - errorType: "FieldValueInvalid", - errorDetail: dnsLabelErrMsg, - }, - "invalid name": { - endpoints: core.Endpoints{ObjectMeta: metav1.ObjectMeta{Name: "-_Invliad^&Characters", Namespace: "namespace"}}, - errorType: "FieldValueInvalid", - errorDetail: dnsSubdomainLabelErrMsg, - }, - "empty addresses": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Ports: []core.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueRequired", - }, - "invalid IP": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "[2001:0db8:85a3:0042:1000:8a2e:0370:7334]"}}, - Ports: []core.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "must be a valid IP address", - }, - "Multiple ports, one without name": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []core.EndpointPort{{Port: 8675, Protocol: "TCP"}, {Name: "b", Port: 309, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueRequired", - }, - "Invalid port number": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []core.EndpointPort{{Name: "a", Port: 66000, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "between", - }, - "Invalid protocol": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []core.EndpointPort{{Name: "a", Port: 93, Protocol: "Protocol"}}, - }, - }, - }, - errorType: "FieldValueNotSupported", - }, - "Address missing IP": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{}}, - Ports: []core.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "must be a valid IP address", - }, - "Port missing number": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []core.EndpointPort{{Name: "a", Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "between", - }, - "Port missing protocol": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}}, - Ports: []core.EndpointPort{{Name: "a", Port: 93}}, - }, - }, - }, - errorType: "FieldValueRequired", - }, - "Address is loopback": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "127.0.0.1"}}, - Ports: []core.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "loopback", - }, - "Address is link-local": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "169.254.169.254"}}, - Ports: []core.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "link-local", - }, - "Address is link-local multicast": { - endpoints: core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"}, - Subsets: []core.EndpointSubset{ - { - Addresses: []core.EndpointAddress{{IP: "224.0.0.1"}}, - Ports: []core.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}}, - }, - }, - }, - errorType: "FieldValueInvalid", - errorDetail: "link-local multicast", - }, - } - - for k, v := range errorCases { - if errs := ValidateEndpoints(&v.endpoints); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) { - t.Errorf("[%s] Expected error type %s with detail %q, got %v", k, v.errorType, v.errorDetail, errs) - } - } -} - -func TestValidateTLSSecret(t *testing.T) { - successCases := map[string]core.Secret{ - "empty certificate chain": { - ObjectMeta: metav1.ObjectMeta{Name: "tls-cert", Namespace: "namespace"}, - Data: map[string][]byte{ - core.TLSCertKey: []byte("public key"), - core.TLSPrivateKeyKey: []byte("private key"), - }, - }, - } - for k, v := range successCases { - if errs := ValidateSecret(&v); len(errs) != 0 { - t.Errorf("Expected success for %s, got %v", k, errs) - } - } - errorCases := map[string]struct { - secrets core.Secret - errorType field.ErrorType - errorDetail string - }{ - "missing public key": { - secrets: core.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: "tls-cert"}, - Data: map[string][]byte{ - core.TLSCertKey: []byte("public key"), - }, - }, - errorType: "FieldValueRequired", - }, - "missing private key": { - secrets: core.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: "tls-cert"}, - Data: map[string][]byte{ - core.TLSCertKey: []byte("public key"), - }, - }, - errorType: "FieldValueRequired", - }, - } - for k, v := range errorCases { - if errs := ValidateSecret(&v.secrets); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) { - t.Errorf("[%s] Expected error type %s with detail %q, got %v", k, v.errorType, v.errorDetail, errs) - } - } -} - -func TestValidateSecurityContext(t *testing.T) { - runAsUser := int64(1) - fullValidSC := func() *core.SecurityContext { - return &core.SecurityContext{ - Privileged: boolPtr(false), - Capabilities: &core.Capabilities{ - Add: []core.Capability{"foo"}, - Drop: []core.Capability{"bar"}, - }, - SELinuxOptions: &core.SELinuxOptions{ - User: "user", - Role: "role", - Type: "type", - Level: "level", - }, - RunAsUser: &runAsUser, - } - } - - //setup data - allSettings := fullValidSC() - noCaps := fullValidSC() - noCaps.Capabilities = nil - - noSELinux := fullValidSC() - noSELinux.SELinuxOptions = nil - - noPrivRequest := fullValidSC() - noPrivRequest.Privileged = nil - - noRunAsUser := fullValidSC() - noRunAsUser.RunAsUser = nil - - successCases := map[string]struct { - sc *core.SecurityContext - }{ - "all settings": {allSettings}, - "no capabilities": {noCaps}, - "no selinux": {noSELinux}, - "no priv request": {noPrivRequest}, - "no run as user": {noRunAsUser}, - } - for k, v := range successCases { - if errs := ValidateSecurityContext(v.sc, field.NewPath("field")); len(errs) != 0 { - t.Errorf("[%s] Expected success, got %v", k, errs) - } - } - - privRequestWithGlobalDeny := fullValidSC() - privRequestWithGlobalDeny.Privileged = boolPtr(true) - - negativeRunAsUser := fullValidSC() - negativeUser := int64(-1) - negativeRunAsUser.RunAsUser = &negativeUser - - privWithoutEscalation := fullValidSC() - privWithoutEscalation.Privileged = boolPtr(true) - privWithoutEscalation.AllowPrivilegeEscalation = boolPtr(false) - - capSysAdminWithoutEscalation := fullValidSC() - capSysAdminWithoutEscalation.Capabilities.Add = []core.Capability{"CAP_SYS_ADMIN"} - capSysAdminWithoutEscalation.AllowPrivilegeEscalation = boolPtr(false) - - errorCases := map[string]struct { - sc *core.SecurityContext - errorType field.ErrorType - errorDetail string - capAllowPriv bool - }{ - "request privileged when capabilities forbids": { - sc: privRequestWithGlobalDeny, - errorType: "FieldValueForbidden", - errorDetail: "disallowed by cluster policy", - }, - "negative RunAsUser": { - sc: negativeRunAsUser, - errorType: "FieldValueInvalid", - errorDetail: "must be between", - }, - "with CAP_SYS_ADMIN and allowPrivilegeEscalation false": { - sc: capSysAdminWithoutEscalation, - errorType: "FieldValueInvalid", - errorDetail: "cannot set `allowPrivilegeEscalation` to false and `capabilities.Add` CAP_SYS_ADMIN", - }, - "with privileged and allowPrivilegeEscalation false": { - sc: privWithoutEscalation, - errorType: "FieldValueInvalid", - errorDetail: "cannot set `allowPrivilegeEscalation` to false and `privileged` to true", - capAllowPriv: true, - }, - } - for k, v := range errorCases { - capabilities.SetForTests(capabilities.Capabilities{ - AllowPrivileged: v.capAllowPriv, - }) - if errs := ValidateSecurityContext(v.sc, field.NewPath("field")); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) { - t.Errorf("[%s] Expected error type %q with detail %q, got %v", k, v.errorType, v.errorDetail, errs) - } - } -} - -func fakeValidSecurityContext(priv bool) *core.SecurityContext { - return &core.SecurityContext{ - Privileged: &priv, - } -} - -func TestValidPodLogOptions(t *testing.T) { - now := metav1.Now() - negative := int64(-1) - zero := int64(0) - positive := int64(1) - tests := []struct { - opt core.PodLogOptions - errs int - }{ - {core.PodLogOptions{}, 0}, - {core.PodLogOptions{Previous: true}, 0}, - {core.PodLogOptions{Follow: true}, 0}, - {core.PodLogOptions{TailLines: &zero}, 0}, - {core.PodLogOptions{TailLines: &negative}, 1}, - {core.PodLogOptions{TailLines: &positive}, 0}, - {core.PodLogOptions{LimitBytes: &zero}, 1}, - {core.PodLogOptions{LimitBytes: &negative}, 1}, - {core.PodLogOptions{LimitBytes: &positive}, 0}, - {core.PodLogOptions{SinceSeconds: &negative}, 1}, - {core.PodLogOptions{SinceSeconds: &positive}, 0}, - {core.PodLogOptions{SinceSeconds: &zero}, 1}, - {core.PodLogOptions{SinceTime: &now}, 0}, - } - for i, test := range tests { - errs := ValidatePodLogOptions(&test.opt) - if test.errs != len(errs) { - t.Errorf("%d: Unexpected errors: %v", i, errs) - } - } -} - -func TestValidateConfigMap(t *testing.T) { - newConfigMap := func(name, namespace string, data map[string]string, binaryData map[string][]byte) core.ConfigMap { - return core.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - }, - Data: data, - BinaryData: binaryData, - } - } - - var ( - validConfigMap = newConfigMap("validname", "validns", map[string]string{"key": "value"}, map[string][]byte{"bin": []byte("value")}) - maxKeyLength = newConfigMap("validname", "validns", map[string]string{strings.Repeat("a", 253): "value"}, nil) - - emptyName = newConfigMap("", "validns", nil, nil) - invalidName = newConfigMap("NoUppercaseOrSpecialCharsLike=Equals", "validns", nil, nil) - emptyNs = newConfigMap("validname", "", nil, nil) - invalidNs = newConfigMap("validname", "NoUppercaseOrSpecialCharsLike=Equals", nil, nil) - invalidKey = newConfigMap("validname", "validns", map[string]string{"a*b": "value"}, nil) - leadingDotKey = newConfigMap("validname", "validns", map[string]string{".ab": "value"}, nil) - dotKey = newConfigMap("validname", "validns", map[string]string{".": "value"}, nil) - doubleDotKey = newConfigMap("validname", "validns", map[string]string{"..": "value"}, nil) - overMaxKeyLength = newConfigMap("validname", "validns", map[string]string{strings.Repeat("a", 254): "value"}, nil) - overMaxSize = newConfigMap("validname", "validns", map[string]string{"key": strings.Repeat("a", v1.MaxSecretSize+1)}, nil) - duplicatedKey = newConfigMap("validname", "validns", map[string]string{"key": "value1"}, map[string][]byte{"key": []byte("value2")}) - binDataInvalidKey = newConfigMap("validname", "validns", nil, map[string][]byte{"a*b": []byte("value")}) - binDataLeadingDotKey = newConfigMap("validname", "validns", nil, map[string][]byte{".ab": []byte("value")}) - binDataDotKey = newConfigMap("validname", "validns", nil, map[string][]byte{".": []byte("value")}) - binDataDoubleDotKey = newConfigMap("validname", "validns", nil, map[string][]byte{"..": []byte("value")}) - binDataOverMaxKeyLength = newConfigMap("validname", "validns", nil, map[string][]byte{strings.Repeat("a", 254): []byte("value")}) - binDataOverMaxSize = newConfigMap("validname", "validns", nil, map[string][]byte{"bin": bytes.Repeat([]byte("a"), v1.MaxSecretSize+1)}) - binNonUtf8Value = newConfigMap("validname", "validns", nil, map[string][]byte{"key": {0, 0xFE, 0, 0xFF}}) - ) - - tests := map[string]struct { - cfg core.ConfigMap - isValid bool - }{ - "valid": {validConfigMap, true}, - "max key length": {maxKeyLength, true}, - "leading dot key": {leadingDotKey, true}, - "empty name": {emptyName, false}, - "invalid name": {invalidName, false}, - "invalid key": {invalidKey, false}, - "empty namespace": {emptyNs, false}, - "invalid namespace": {invalidNs, false}, - "dot key": {dotKey, false}, - "double dot key": {doubleDotKey, false}, - "over max key length": {overMaxKeyLength, false}, - "over max size": {overMaxSize, false}, - "duplicated key": {duplicatedKey, false}, - "binary data invalid key": {binDataInvalidKey, false}, - "binary data leading dot key": {binDataLeadingDotKey, true}, - "binary data dot key": {binDataDotKey, false}, - "binary data double dot key": {binDataDoubleDotKey, false}, - "binary data over max key length": {binDataOverMaxKeyLength, false}, - "binary data max size": {binDataOverMaxSize, false}, - "binary data non utf-8 bytes": {binNonUtf8Value, true}, - } - - for name, tc := range tests { - errs := ValidateConfigMap(&tc.cfg) - if tc.isValid && len(errs) > 0 { - t.Errorf("%v: unexpected error: %v", name, errs) - } - if !tc.isValid && len(errs) == 0 { - t.Errorf("%v: unexpected non-error", name) - } - } -} - -func TestValidateConfigMapUpdate(t *testing.T) { - newConfigMap := func(version, name, namespace string, data map[string]string) core.ConfigMap { - return core.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: namespace, - ResourceVersion: version, - }, - Data: data, - } - } - - var ( - validConfigMap = newConfigMap("1", "validname", "validns", map[string]string{"key": "value"}) - noVersion = newConfigMap("", "validname", "validns", map[string]string{"key": "value"}) - ) - - cases := []struct { - name string - newCfg core.ConfigMap - oldCfg core.ConfigMap - isValid bool - }{ - { - name: "valid", - newCfg: validConfigMap, - oldCfg: validConfigMap, - isValid: true, - }, - { - name: "invalid", - newCfg: noVersion, - oldCfg: validConfigMap, - isValid: false, - }, - } - - for _, tc := range cases { - errs := ValidateConfigMapUpdate(&tc.newCfg, &tc.oldCfg) - if tc.isValid && len(errs) > 0 { - t.Errorf("%v: unexpected error: %v", tc.name, errs) - } - if !tc.isValid && len(errs) == 0 { - t.Errorf("%v: unexpected non-error", tc.name) - } - } -} - -func TestValidateHasLabel(t *testing.T) { - successCase := metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Labels: map[string]string{ - "other": "blah", - "foo": "bar", - }, - } - if errs := ValidateHasLabel(successCase, field.NewPath("field"), "foo", "bar"); len(errs) != 0 { - t.Errorf("expected success: %v", errs) - } - - missingCase := metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Labels: map[string]string{ - "other": "blah", - }, - } - if errs := ValidateHasLabel(missingCase, field.NewPath("field"), "foo", "bar"); len(errs) == 0 { - t.Errorf("expected failure") - } - - wrongValueCase := metav1.ObjectMeta{ - Name: "123", - Namespace: "ns", - Labels: map[string]string{ - "other": "blah", - "foo": "notbar", - }, - } - if errs := ValidateHasLabel(wrongValueCase, field.NewPath("field"), "foo", "bar"); len(errs) == 0 { - t.Errorf("expected failure") - } -} - -func TestIsValidSysctlName(t *testing.T) { - valid := []string{ - "a.b.c.d", - "a", - "a_b", - "a-b", - "abc", - "abc.def", - } - invalid := []string{ - "", - "*", - "ä", - "a_", - "_", - "__", - "_a", - "_a._b", - "-", - ".", - "a.", - ".a", - "a.b.", - "a*.b", - "a*b", - "*a", - "a.*", - "*", - "abc*", - "a.abc*", - "a.b.*", - "Abc", - func(n int) string { - x := make([]byte, n) - for i := range x { - x[i] = byte('a') - } - return string(x) - }(256), - } - for _, s := range valid { - if !IsValidSysctlName(s) { - t.Errorf("%q expected to be a valid sysctl name", s) - } - } - for _, s := range invalid { - if IsValidSysctlName(s) { - t.Errorf("%q expected to be an invalid sysctl name", s) - } - } -} - -func TestValidateSysctls(t *testing.T) { - valid := []string{ - "net.foo.bar", - "kernel.shmmax", - } - invalid := []string{ - "i..nvalid", - "_invalid", - } - - sysctls := make([]core.Sysctl, len(valid)) - for i, sysctl := range valid { - sysctls[i].Name = sysctl - } - errs := validateSysctls(sysctls, field.NewPath("foo")) - if len(errs) != 0 { - t.Errorf("unexpected validation errors: %v", errs) - } - - sysctls = make([]core.Sysctl, len(invalid)) - for i, sysctl := range invalid { - sysctls[i].Name = sysctl - } - errs = validateSysctls(sysctls, field.NewPath("foo")) - if len(errs) != 2 { - t.Errorf("expected 2 validation errors. Got: %v", errs) - } else { - if got, expected := errs[0].Error(), "foo"; !strings.Contains(got, expected) { - t.Errorf("unexpected errors: expected=%q, got=%q", expected, got) - } - if got, expected := errs[1].Error(), "foo"; !strings.Contains(got, expected) { - t.Errorf("unexpected errors: expected=%q, got=%q", expected, got) - } - } -} - -func newNodeNameEndpoint(nodeName string) *core.Endpoints { - ep := &core.Endpoints{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: metav1.NamespaceDefault, - ResourceVersion: "1", - }, - Subsets: []core.EndpointSubset{ - { - NotReadyAddresses: []core.EndpointAddress{}, - Ports: []core.EndpointPort{{Name: "https", Port: 443, Protocol: "TCP"}}, - Addresses: []core.EndpointAddress{ - { - IP: "8.8.8.8", - Hostname: "zookeeper1", - NodeName: &nodeName}}}}} - return ep -} - -func TestEndpointAddressNodeNameUpdateRestrictions(t *testing.T) { - oldEndpoint := newNodeNameEndpoint("kubernetes-node-setup-by-backend") - updatedEndpoint := newNodeNameEndpoint("kubernetes-changed-nodename") - // Check that NodeName cannot be changed during update (if already set) - errList := ValidateEndpoints(updatedEndpoint) - errList = append(errList, ValidateEndpointsUpdate(updatedEndpoint, oldEndpoint)...) - if len(errList) == 0 { - t.Error("Endpoint should not allow changing of Subset.Addresses.NodeName on update") - } -} - -func TestEndpointAddressNodeNameInvalidDNSSubdomain(t *testing.T) { - // Check NodeName DNS validation - endpoint := newNodeNameEndpoint("illegal*.nodename") - errList := ValidateEndpoints(endpoint) - if len(errList) == 0 { - t.Error("Endpoint should reject invalid NodeName") - } -} - -func TestEndpointAddressNodeNameCanBeAnIPAddress(t *testing.T) { - endpoint := newNodeNameEndpoint("10.10.1.1") - errList := ValidateEndpoints(endpoint) - if len(errList) != 0 { - t.Error("Endpoint should accept a NodeName that is an IP address") - } -} - -func TestValidateFlexVolumeSource(t *testing.T) { - testcases := map[string]struct { - source *core.FlexVolumeSource - expectedErrs map[string]string - }{ - "valid": { - source: &core.FlexVolumeSource{Driver: "foo"}, - expectedErrs: map[string]string{}, - }, - "valid with options": { - source: &core.FlexVolumeSource{Driver: "foo", Options: map[string]string{"foo": "bar"}}, - expectedErrs: map[string]string{}, - }, - "no driver": { - source: &core.FlexVolumeSource{Driver: ""}, - expectedErrs: map[string]string{"driver": "Required value"}, - }, - "reserved option keys": { - source: &core.FlexVolumeSource{ - Driver: "foo", - Options: map[string]string{ - // valid options - "myns.io": "A", - "myns.io/bar": "A", - "myns.io/kubernetes.io": "A", - - // invalid options - "KUBERNETES.IO": "A", - "kubernetes.io": "A", - "kubernetes.io/": "A", - "kubernetes.io/foo": "A", - - "alpha.kubernetes.io": "A", - "alpha.kubernetes.io/": "A", - "alpha.kubernetes.io/foo": "A", - - "k8s.io": "A", - "k8s.io/": "A", - "k8s.io/foo": "A", - - "alpha.k8s.io": "A", - "alpha.k8s.io/": "A", - "alpha.k8s.io/foo": "A", - }, - }, - expectedErrs: map[string]string{ - "options[KUBERNETES.IO]": "reserved", - "options[kubernetes.io]": "reserved", - "options[kubernetes.io/]": "reserved", - "options[kubernetes.io/foo]": "reserved", - "options[alpha.kubernetes.io]": "reserved", - "options[alpha.kubernetes.io/]": "reserved", - "options[alpha.kubernetes.io/foo]": "reserved", - "options[k8s.io]": "reserved", - "options[k8s.io/]": "reserved", - "options[k8s.io/foo]": "reserved", - "options[alpha.k8s.io]": "reserved", - "options[alpha.k8s.io/]": "reserved", - "options[alpha.k8s.io/foo]": "reserved", - }, - }, - } - - for k, tc := range testcases { - errs := validateFlexVolumeSource(tc.source, nil) - for _, err := range errs { - expectedErr, ok := tc.expectedErrs[err.Field] - if !ok { - t.Errorf("%s: unexpected err on field %s: %v", k, err.Field, err) - continue - } - if !strings.Contains(err.Error(), expectedErr) { - t.Errorf("%s: expected err on field %s to contain '%s', was %v", k, err.Field, expectedErr, err.Error()) - continue - } - } - if len(errs) != len(tc.expectedErrs) { - t.Errorf("%s: expected errs %#v, got %#v", k, tc.expectedErrs, errs) - continue - } - } -} - -func TestValidateOrSetClientIPAffinityConfig(t *testing.T) { - successCases := map[string]*core.SessionAffinityConfig{ - "non-empty config, valid timeout: 1": { - ClientIP: &core.ClientIPConfig{ - TimeoutSeconds: newInt32(1), - }, - }, - "non-empty config, valid timeout: core.MaxClientIPServiceAffinitySeconds-1": { - ClientIP: &core.ClientIPConfig{ - TimeoutSeconds: newInt32(int(core.MaxClientIPServiceAffinitySeconds - 1)), - }, - }, - "non-empty config, valid timeout: core.MaxClientIPServiceAffinitySeconds": { - ClientIP: &core.ClientIPConfig{ - TimeoutSeconds: newInt32(int(core.MaxClientIPServiceAffinitySeconds)), - }, - }, - } - - for name, test := range successCases { - if errs := validateClientIPAffinityConfig(test, field.NewPath("field")); len(errs) != 0 { - t.Errorf("case: %s, expected success: %v", name, errs) - } - } - - errorCases := map[string]*core.SessionAffinityConfig{ - "empty session affinity config": nil, - "empty client IP config": { - ClientIP: nil, - }, - "empty timeoutSeconds": { - ClientIP: &core.ClientIPConfig{ - TimeoutSeconds: nil, - }, - }, - "non-empty config, invalid timeout: core.MaxClientIPServiceAffinitySeconds+1": { - ClientIP: &core.ClientIPConfig{ - TimeoutSeconds: newInt32(int(core.MaxClientIPServiceAffinitySeconds + 1)), - }, - }, - "non-empty config, invalid timeout: -1": { - ClientIP: &core.ClientIPConfig{ - TimeoutSeconds: newInt32(-1), - }, - }, - "non-empty config, invalid timeout: 0": { - ClientIP: &core.ClientIPConfig{ - TimeoutSeconds: newInt32(0), - }, - }, - } - - for name, test := range errorCases { - if errs := validateClientIPAffinityConfig(test, field.NewPath("field")); len(errs) == 0 { - t.Errorf("case: %v, expected failures: %v", name, errs) - } - } -} - -func boolPtr(b bool) *bool { - return &b -} diff --git a/vendor/k8s.io/kubernetes/pkg/apis/extensions/helpers_test.go b/vendor/k8s.io/kubernetes/pkg/apis/extensions/helpers_test.go deleted file mode 100644 index 29ae139ec9..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/apis/extensions/helpers_test.go +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright 2016 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 extensions - -import ( - "reflect" - "testing" -) - -func TestPodAnnotationsFromSysctls(t *testing.T) { - type Test struct { - sysctls []string - expectedValue string - } - for _, test := range []Test{ - {sysctls: []string{"a.b"}, expectedValue: "a.b"}, - {sysctls: []string{"a.b", "c.d"}, expectedValue: "a.b,c.d"}, - {sysctls: []string{"a.b", "a.b"}, expectedValue: "a.b,a.b"}, - {sysctls: []string{}, expectedValue: ""}, - {sysctls: nil, expectedValue: ""}, - } { - a := PodAnnotationsFromSysctls(test.sysctls) - if a != test.expectedValue { - t.Errorf("wrong value for %v: got=%q wanted=%q", test.sysctls, a, test.expectedValue) - } - } -} - -func TestSysctlsFromPodSecurityPolicyAnnotation(t *testing.T) { - type Test struct { - expectedValue []string - annotation string - } - for _, test := range []Test{ - {annotation: "a.b", expectedValue: []string{"a.b"}}, - {annotation: "a.b,c.d", expectedValue: []string{"a.b", "c.d"}}, - {annotation: "a.b,a.b", expectedValue: []string{"a.b", "a.b"}}, - {annotation: "", expectedValue: []string{}}, - } { - sysctls, err := SysctlsFromPodSecurityPolicyAnnotation(test.annotation) - if err != nil { - t.Errorf("error for %q: %v", test.annotation, err) - } - if !reflect.DeepEqual(sysctls, test.expectedValue) { - t.Errorf("wrong value for %q: got=%v wanted=%v", test.annotation, sysctls, test.expectedValue) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/capabilities/capabilities_test.go b/vendor/k8s.io/kubernetes/pkg/capabilities/capabilities_test.go deleted file mode 100644 index ea4434d061..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/capabilities/capabilities_test.go +++ /dev/null @@ -1,50 +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 capabilities - -import ( - "reflect" - "testing" -) - -func TestGet(t *testing.T) { - defaultCap := Capabilities{ - AllowPrivileged: false, - PrivilegedSources: PrivilegedSources{ - HostNetworkSources: []string{}, - HostPIDSources: []string{}, - HostIPCSources: []string{}, - }, - } - - res := Get() - if !reflect.DeepEqual(defaultCap, res) { - t.Fatalf("expected Capabilities: %#v, got a non-default: %#v", defaultCap, res) - } - - cap := Capabilities{ - PrivilegedSources: PrivilegedSources{ - HostNetworkSources: []string{"A", "B"}, - }, - } - SetForTests(cap) - - res = Get() - if !reflect.DeepEqual(cap, res) { - t.Fatalf("expected Capabilities: %#v , got a different: %#v", cap, res) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/controller_ref_manager_test.go b/vendor/k8s.io/kubernetes/pkg/controller/controller_ref_manager_test.go deleted file mode 100644 index 4e6acb7cf3..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/controller/controller_ref_manager_test.go +++ /dev/null @@ -1,181 +0,0 @@ -/* -Copyright 2017 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 controller - -import ( - "reflect" - "testing" - - "k8s.io/api/core/v1" - "k8s.io/api/extensions/v1beta1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/types" -) - -var ( - productionLabel = map[string]string{"type": "production"} - testLabel = map[string]string{"type": "testing"} - productionLabelSelector = labels.Set{"type": "production"}.AsSelector() - testLabelSelector = labels.Set{"type": "testing"}.AsSelector() - controllerUID = "123" -) - -func newPod(podName string, label map[string]string, owner metav1.Object) *v1.Pod { - pod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: podName, - Labels: label, - Namespace: metav1.NamespaceDefault, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - Image: "foo/bar", - }, - }, - }, - } - if owner != nil { - pod.OwnerReferences = []metav1.OwnerReference{*metav1.NewControllerRef(owner, v1beta1.SchemeGroupVersion.WithKind("Fake"))} - } - return pod -} - -func TestClaimPods(t *testing.T) { - controllerKind := schema.GroupVersionKind{} - type test struct { - name string - manager *PodControllerRefManager - pods []*v1.Pod - filters []func(*v1.Pod) bool - claimed []*v1.Pod - released []*v1.Pod - } - var tests = []test{ - { - name: "Claim pods with correct label", - manager: NewPodControllerRefManager(&FakePodControl{}, - &v1.ReplicationController{}, - productionLabelSelector, - controllerKind, - func() error { return nil }), - pods: []*v1.Pod{newPod("pod1", productionLabel, nil), newPod("pod2", testLabel, nil)}, - claimed: []*v1.Pod{newPod("pod1", productionLabel, nil)}, - }, - func() test { - controller := v1.ReplicationController{} - controller.UID = types.UID(controllerUID) - now := metav1.Now() - controller.DeletionTimestamp = &now - return test{ - name: "Controller marked for deletion can not claim pods", - manager: NewPodControllerRefManager(&FakePodControl{}, - &controller, - productionLabelSelector, - controllerKind, - func() error { return nil }), - pods: []*v1.Pod{newPod("pod1", productionLabel, nil), newPod("pod2", productionLabel, nil)}, - claimed: nil, - } - }(), - func() test { - controller := v1.ReplicationController{} - controller.UID = types.UID(controllerUID) - now := metav1.Now() - controller.DeletionTimestamp = &now - return test{ - name: "Controller marked for deletion can not claim new pods", - manager: NewPodControllerRefManager(&FakePodControl{}, - &controller, - productionLabelSelector, - controllerKind, - func() error { return nil }), - pods: []*v1.Pod{newPod("pod1", productionLabel, &controller), newPod("pod2", productionLabel, nil)}, - claimed: []*v1.Pod{newPod("pod1", productionLabel, &controller)}, - } - }(), - func() test { - controller := v1.ReplicationController{} - controller2 := v1.ReplicationController{} - controller.UID = types.UID(controllerUID) - controller2.UID = types.UID("AAAAA") - return test{ - name: "Controller can not claim pods owned by another controller", - manager: NewPodControllerRefManager(&FakePodControl{}, - &controller, - productionLabelSelector, - controllerKind, - func() error { return nil }), - pods: []*v1.Pod{newPod("pod1", productionLabel, &controller), newPod("pod2", productionLabel, &controller2)}, - claimed: []*v1.Pod{newPod("pod1", productionLabel, &controller)}, - } - }(), - func() test { - controller := v1.ReplicationController{} - controller.UID = types.UID(controllerUID) - return test{ - name: "Controller releases claimed pods when selector doesn't match", - manager: NewPodControllerRefManager(&FakePodControl{}, - &controller, - productionLabelSelector, - controllerKind, - func() error { return nil }), - pods: []*v1.Pod{newPod("pod1", productionLabel, &controller), newPod("pod2", testLabel, &controller)}, - claimed: []*v1.Pod{newPod("pod1", productionLabel, &controller)}, - } - }(), - func() test { - controller := v1.ReplicationController{} - controller.UID = types.UID(controllerUID) - podToDelete1 := newPod("pod1", productionLabel, &controller) - podToDelete2 := newPod("pod2", productionLabel, nil) - now := metav1.Now() - podToDelete1.DeletionTimestamp = &now - podToDelete2.DeletionTimestamp = &now - - return test{ - name: "Controller does not claim orphaned pods marked for deletion", - manager: NewPodControllerRefManager(&FakePodControl{}, - &controller, - productionLabelSelector, - controllerKind, - func() error { return nil }), - pods: []*v1.Pod{podToDelete1, podToDelete2}, - claimed: []*v1.Pod{podToDelete1}, - } - }(), - } - for _, test := range tests { - claimed, err := test.manager.ClaimPods(test.pods) - if err != nil { - t.Errorf("Test case `%s`, unexpected error: %v", test.name, err) - } else if !reflect.DeepEqual(test.claimed, claimed) { - t.Errorf("Test case `%s`, claimed wrong pods. Expected %v, got %v", test.name, podToStringSlice(test.claimed), podToStringSlice(claimed)) - } - - } -} - -func podToStringSlice(pods []*v1.Pod) []string { - var names []string - for _, pod := range pods { - names = append(names, pod.Name) - } - return names -} diff --git a/vendor/k8s.io/kubernetes/pkg/controller/controller_utils_test.go b/vendor/k8s.io/kubernetes/pkg/controller/controller_utils_test.go deleted file mode 100644 index f3599ba6d7..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/controller/controller_utils_test.go +++ /dev/null @@ -1,821 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package controller - -import ( - "encoding/json" - "fmt" - "math" - "math/rand" - "net/http/httptest" - "sort" - "sync" - "testing" - "time" - - "k8s.io/api/core/v1" - extensions "k8s.io/api/extensions/v1beta1" - apiequality "k8s.io/apimachinery/pkg/api/equality" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/clock" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/uuid" - clientset "k8s.io/client-go/kubernetes" - "k8s.io/client-go/kubernetes/fake" - restclient "k8s.io/client-go/rest" - "k8s.io/client-go/tools/cache" - "k8s.io/client-go/tools/record" - utiltesting "k8s.io/client-go/util/testing" - "k8s.io/kubernetes/pkg/api/legacyscheme" - "k8s.io/kubernetes/pkg/api/testapi" - _ "k8s.io/kubernetes/pkg/apis/core/install" - "k8s.io/kubernetes/pkg/controller/testutil" - "k8s.io/kubernetes/pkg/securitycontext" - - "github.com/stretchr/testify/assert" -) - -// NewFakeControllerExpectationsLookup creates a fake store for PodExpectations. -func NewFakeControllerExpectationsLookup(ttl time.Duration) (*ControllerExpectations, *clock.FakeClock) { - fakeTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) - fakeClock := clock.NewFakeClock(fakeTime) - ttlPolicy := &cache.TTLPolicy{Ttl: ttl, Clock: fakeClock} - ttlStore := cache.NewFakeExpirationStore( - ExpKeyFunc, nil, ttlPolicy, fakeClock) - return &ControllerExpectations{ttlStore}, fakeClock -} - -func newReplicationController(replicas int) *v1.ReplicationController { - rc := &v1.ReplicationController{ - TypeMeta: metav1.TypeMeta{APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String()}, - ObjectMeta: metav1.ObjectMeta{ - UID: uuid.NewUUID(), - Name: "foobar", - Namespace: metav1.NamespaceDefault, - ResourceVersion: "18", - }, - Spec: v1.ReplicationControllerSpec{ - Replicas: func() *int32 { i := int32(replicas); return &i }(), - Selector: map[string]string{"foo": "bar"}, - Template: &v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "name": "foo", - "type": "production", - }, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - Image: "foo/bar", - TerminationMessagePath: v1.TerminationMessagePathDefault, - ImagePullPolicy: v1.PullIfNotPresent, - SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), - }, - }, - RestartPolicy: v1.RestartPolicyAlways, - DNSPolicy: v1.DNSDefault, - NodeSelector: map[string]string{ - "baz": "blah", - }, - }, - }, - }, - } - return rc -} - -// create count pods with the given phase for the given rc (same selectors and namespace), and add them to the store. -func newPodList(store cache.Store, count int, status v1.PodPhase, rc *v1.ReplicationController) *v1.PodList { - pods := []v1.Pod{} - for i := 0; i < count; i++ { - newPod := v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("pod%d", i), - Labels: rc.Spec.Selector, - Namespace: rc.Namespace, - }, - Status: v1.PodStatus{Phase: status}, - } - if store != nil { - store.Add(&newPod) - } - pods = append(pods, newPod) - } - return &v1.PodList{ - Items: pods, - } -} - -func newReplicaSet(name string, replicas int) *extensions.ReplicaSet { - return &extensions.ReplicaSet{ - TypeMeta: metav1.TypeMeta{APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String()}, - ObjectMeta: metav1.ObjectMeta{ - UID: uuid.NewUUID(), - Name: name, - Namespace: metav1.NamespaceDefault, - ResourceVersion: "18", - }, - Spec: extensions.ReplicaSetSpec{ - Replicas: func() *int32 { i := int32(replicas); return &i }(), - Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"foo": "bar"}}, - Template: v1.PodTemplateSpec{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - "name": "foo", - "type": "production", - }, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - Image: "foo/bar", - TerminationMessagePath: v1.TerminationMessagePathDefault, - ImagePullPolicy: v1.PullIfNotPresent, - SecurityContext: securitycontext.ValidSecurityContextWithContainerDefaults(), - }, - }, - RestartPolicy: v1.RestartPolicyAlways, - DNSPolicy: v1.DNSDefault, - NodeSelector: map[string]string{ - "baz": "blah", - }, - }, - }, - }, - } -} - -func TestControllerExpectations(t *testing.T) { - ttl := 30 * time.Second - e, fakeClock := NewFakeControllerExpectationsLookup(ttl) - // In practice we can't really have add and delete expectations since we only either create or - // delete replicas in one rc pass, and the rc goes to sleep soon after until the expectations are - // either fulfilled or timeout. - adds, dels := 10, 30 - rc := newReplicationController(1) - - // RC fires off adds and deletes at apiserver, then sets expectations - rcKey, err := KeyFunc(rc) - assert.NoError(t, err, "Couldn't get key for object %#v: %v", rc, err) - - e.SetExpectations(rcKey, adds, dels) - var wg sync.WaitGroup - for i := 0; i < adds+1; i++ { - wg.Add(1) - go func() { - // In prod this can happen either because of a failed create by the rc - // or after having observed a create via informer - e.CreationObserved(rcKey) - wg.Done() - }() - } - wg.Wait() - - // There are still delete expectations - assert.False(t, e.SatisfiedExpectations(rcKey), "Rc will sync before expectations are met") - - for i := 0; i < dels+1; i++ { - wg.Add(1) - go func() { - e.DeletionObserved(rcKey) - wg.Done() - }() - } - wg.Wait() - - // Expectations have been surpassed - podExp, exists, err := e.GetExpectations(rcKey) - assert.NoError(t, err, "Could not get expectations for rc, exists %v and err %v", exists, err) - assert.True(t, exists, "Could not get expectations for rc, exists %v and err %v", exists, err) - - add, del := podExp.GetExpectations() - assert.Equal(t, int64(-1), add, "Unexpected pod expectations %#v", podExp) - assert.Equal(t, int64(-1), del, "Unexpected pod expectations %#v", podExp) - assert.True(t, e.SatisfiedExpectations(rcKey), "Expectations are met but the rc will not sync") - - // Next round of rc sync, old expectations are cleared - e.SetExpectations(rcKey, 1, 2) - podExp, exists, err = e.GetExpectations(rcKey) - assert.NoError(t, err, "Could not get expectations for rc, exists %v and err %v", exists, err) - assert.True(t, exists, "Could not get expectations for rc, exists %v and err %v", exists, err) - add, del = podExp.GetExpectations() - - assert.Equal(t, int64(1), add, "Unexpected pod expectations %#v", podExp) - assert.Equal(t, int64(2), del, "Unexpected pod expectations %#v", podExp) - - // Expectations have expired because of ttl - fakeClock.Step(ttl + 1) - assert.True(t, e.SatisfiedExpectations(rcKey), - "Expectations should have expired but didn't") -} - -func TestUIDExpectations(t *testing.T) { - uidExp := NewUIDTrackingControllerExpectations(NewControllerExpectations()) - rcList := []*v1.ReplicationController{ - newReplicationController(2), - newReplicationController(1), - newReplicationController(0), - newReplicationController(5), - } - rcToPods := map[string][]string{} - rcKeys := []string{} - for i := range rcList { - rc := rcList[i] - rcName := fmt.Sprintf("rc-%v", i) - rc.Name = rcName - rc.Spec.Selector[rcName] = rcName - podList := newPodList(nil, 5, v1.PodRunning, rc) - rcKey, err := KeyFunc(rc) - if err != nil { - t.Fatalf("Couldn't get key for object %#v: %v", rc, err) - } - rcKeys = append(rcKeys, rcKey) - rcPodNames := []string{} - for i := range podList.Items { - p := &podList.Items[i] - p.Name = fmt.Sprintf("%v-%v", p.Name, rc.Name) - rcPodNames = append(rcPodNames, PodKey(p)) - } - rcToPods[rcKey] = rcPodNames - uidExp.ExpectDeletions(rcKey, rcPodNames) - } - for i := range rcKeys { - j := rand.Intn(i + 1) - rcKeys[i], rcKeys[j] = rcKeys[j], rcKeys[i] - } - for _, rcKey := range rcKeys { - assert.False(t, uidExp.SatisfiedExpectations(rcKey), - "Controller %v satisfied expectations before deletion", rcKey) - - for _, p := range rcToPods[rcKey] { - uidExp.DeletionObserved(rcKey, p) - } - - assert.True(t, uidExp.SatisfiedExpectations(rcKey), - "Controller %v didn't satisfy expectations after deletion", rcKey) - - uidExp.DeleteExpectations(rcKey) - - assert.Nil(t, uidExp.GetUIDs(rcKey), - "Failed to delete uid expectations for %v", rcKey) - } -} - -func TestCreatePods(t *testing.T) { - ns := metav1.NamespaceDefault - body := runtime.EncodeOrDie(testapi.Default.Codec(), &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "empty_pod"}}) - fakeHandler := utiltesting.FakeHandler{ - StatusCode: 200, - ResponseBody: string(body), - } - testServer := httptest.NewServer(&fakeHandler) - defer testServer.Close() - clientset := clientset.NewForConfigOrDie(&restclient.Config{Host: testServer.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion}}) - - podControl := RealPodControl{ - KubeClient: clientset, - Recorder: &record.FakeRecorder{}, - } - - controllerSpec := newReplicationController(1) - - // Make sure createReplica sends a POST to the apiserver with a pod from the controllers pod template - err := podControl.CreatePods(ns, controllerSpec.Spec.Template, controllerSpec) - assert.NoError(t, err, "unexpected error: %v", err) - - expectedPod := v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Labels: controllerSpec.Spec.Template.Labels, - GenerateName: fmt.Sprintf("%s-", controllerSpec.Name), - }, - Spec: controllerSpec.Spec.Template.Spec, - } - fakeHandler.ValidateRequest(t, testapi.Default.ResourcePath("pods", metav1.NamespaceDefault, ""), "POST", nil) - var actualPod = &v1.Pod{} - err = json.Unmarshal([]byte(fakeHandler.RequestBody), actualPod) - assert.NoError(t, err, "unexpected error: %v", err) - assert.True(t, apiequality.Semantic.DeepDerivative(&expectedPod, actualPod), - "Body: %s", fakeHandler.RequestBody) -} - -func TestActivePodFiltering(t *testing.T) { - // This rc is not needed by the test, only the newPodList to give the pods labels/a namespace. - rc := newReplicationController(0) - podList := newPodList(nil, 5, v1.PodRunning, rc) - podList.Items[0].Status.Phase = v1.PodSucceeded - podList.Items[1].Status.Phase = v1.PodFailed - expectedNames := sets.NewString() - for _, pod := range podList.Items[2:] { - expectedNames.Insert(pod.Name) - } - - var podPointers []*v1.Pod - for i := range podList.Items { - podPointers = append(podPointers, &podList.Items[i]) - } - got := FilterActivePods(podPointers) - gotNames := sets.NewString() - for _, pod := range got { - gotNames.Insert(pod.Name) - } - - assert.Equal(t, 0, expectedNames.Difference(gotNames).Len(), - "expected %v, got %v", expectedNames.List(), gotNames.List()) - assert.Equal(t, 0, gotNames.Difference(expectedNames).Len(), - "expected %v, got %v", expectedNames.List(), gotNames.List()) -} - -func TestSortingActivePods(t *testing.T) { - numPods := 9 - // This rc is not needed by the test, only the newPodList to give the pods labels/a namespace. - rc := newReplicationController(0) - podList := newPodList(nil, numPods, v1.PodRunning, rc) - - pods := make([]*v1.Pod, len(podList.Items)) - for i := range podList.Items { - pods[i] = &podList.Items[i] - } - // pods[0] is not scheduled yet. - pods[0].Spec.NodeName = "" - pods[0].Status.Phase = v1.PodPending - // pods[1] is scheduled but pending. - pods[1].Spec.NodeName = "bar" - pods[1].Status.Phase = v1.PodPending - // pods[2] is unknown. - pods[2].Spec.NodeName = "foo" - pods[2].Status.Phase = v1.PodUnknown - // pods[3] is running but not ready. - pods[3].Spec.NodeName = "foo" - pods[3].Status.Phase = v1.PodRunning - // pods[4] is running and ready but without LastTransitionTime. - now := metav1.Now() - pods[4].Spec.NodeName = "foo" - pods[4].Status.Phase = v1.PodRunning - pods[4].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue}} - pods[4].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} - // pods[5] is running and ready and with LastTransitionTime. - pods[5].Spec.NodeName = "foo" - pods[5].Status.Phase = v1.PodRunning - pods[5].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: now}} - pods[5].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} - // pods[6] is running ready for a longer time than pods[5]. - then := metav1.Time{Time: now.AddDate(0, -1, 0)} - pods[6].Spec.NodeName = "foo" - pods[6].Status.Phase = v1.PodRunning - pods[6].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}} - pods[6].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 3}, {RestartCount: 0}} - // pods[7] has lower container restart count than pods[6]. - pods[7].Spec.NodeName = "foo" - pods[7].Status.Phase = v1.PodRunning - pods[7].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}} - pods[7].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 2}, {RestartCount: 1}} - pods[7].CreationTimestamp = now - // pods[8] is older than pods[7]. - pods[8].Spec.NodeName = "foo" - pods[8].Status.Phase = v1.PodRunning - pods[8].Status.Conditions = []v1.PodCondition{{Type: v1.PodReady, Status: v1.ConditionTrue, LastTransitionTime: then}} - pods[8].Status.ContainerStatuses = []v1.ContainerStatus{{RestartCount: 2}, {RestartCount: 1}} - pods[8].CreationTimestamp = then - - getOrder := func(pods []*v1.Pod) []string { - names := make([]string, len(pods)) - for i := range pods { - names[i] = pods[i].Name - } - return names - } - - expected := getOrder(pods) - - for i := 0; i < 20; i++ { - idx := rand.Perm(numPods) - randomizedPods := make([]*v1.Pod, numPods) - for j := 0; j < numPods; j++ { - randomizedPods[j] = pods[idx[j]] - } - sort.Sort(ActivePods(randomizedPods)) - actual := getOrder(randomizedPods) - - assert.EqualValues(t, expected, actual, "expected %v, got %v", expected, actual) - } -} - -func TestActiveReplicaSetsFiltering(t *testing.T) { - var replicaSets []*extensions.ReplicaSet - replicaSets = append(replicaSets, newReplicaSet("zero", 0)) - replicaSets = append(replicaSets, nil) - replicaSets = append(replicaSets, newReplicaSet("foo", 1)) - replicaSets = append(replicaSets, newReplicaSet("bar", 2)) - expectedNames := sets.NewString() - for _, rs := range replicaSets[2:] { - expectedNames.Insert(rs.Name) - } - - got := FilterActiveReplicaSets(replicaSets) - gotNames := sets.NewString() - for _, rs := range got { - gotNames.Insert(rs.Name) - } - - assert.Equal(t, 0, expectedNames.Difference(gotNames).Len(), - "expected %v, got %v", expectedNames.List(), gotNames.List()) - assert.Equal(t, 0, gotNames.Difference(expectedNames).Len(), - "expected %v, got %v", expectedNames.List(), gotNames.List()) -} - -func TestComputeHash(t *testing.T) { - collisionCount := int32(1) - otherCollisionCount := int32(2) - maxCollisionCount := int32(math.MaxInt32) - tests := []struct { - name string - template *v1.PodTemplateSpec - collisionCount *int32 - otherCollisionCount *int32 - }{ - { - name: "simple", - template: &v1.PodTemplateSpec{}, - collisionCount: &collisionCount, - otherCollisionCount: &otherCollisionCount, - }, - { - name: "using math.MaxInt64", - template: &v1.PodTemplateSpec{}, - collisionCount: nil, - otherCollisionCount: &maxCollisionCount, - }, - } - - for _, test := range tests { - hash := ComputeHash(test.template, test.collisionCount) - otherHash := ComputeHash(test.template, test.otherCollisionCount) - - assert.NotEqual(t, hash, otherHash, "expected different hashes but got the same: %d", hash) - } -} - -func TestRemoveTaintOffNode(t *testing.T) { - tests := []struct { - name string - nodeHandler *testutil.FakeNodeHandler - nodeName string - taintsToRemove []*v1.Taint - expectedTaints []v1.Taint - requestCount int - }{ - { - name: "remove one taint from node", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToRemove: []*v1.Taint{ - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - expectedTaints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - }, - requestCount: 4, - }, - { - name: "remove multiple taints from node", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - {Key: "key3", Value: "value3", Effect: "NoSchedule"}, - {Key: "key4", Value: "value4", Effect: "NoExecute"}, - }, - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToRemove: []*v1.Taint{ - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - {Key: "key3", Value: "value3", Effect: "NoSchedule"}, - }, - expectedTaints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key4", Value: "value4", Effect: "NoExecute"}, - }, - requestCount: 4, - }, - { - name: "remove no-exist taints from node", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToRemove: []*v1.Taint{ - {Key: "key3", Value: "value3", Effect: "NoSchedule"}, - }, - expectedTaints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - requestCount: 2, - }, - { - name: "remove taint from node without taints", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToRemove: []*v1.Taint{ - {Key: "key3", Value: "value3", Effect: "NoSchedule"}, - }, - expectedTaints: nil, - requestCount: 2, - }, - { - name: "remove empty taint list from node without taints", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToRemove: []*v1.Taint{}, - expectedTaints: nil, - requestCount: 2, - }, - { - name: "remove empty taint list from node", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToRemove: []*v1.Taint{}, - expectedTaints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - requestCount: 2, - }, - } - for _, test := range tests { - node, _ := test.nodeHandler.Get(test.nodeName, metav1.GetOptions{}) - err := RemoveTaintOffNode(test.nodeHandler, test.nodeName, node, test.taintsToRemove...) - assert.NoError(t, err, "%s: RemoveTaintOffNode() error = %v", test.name, err) - - node, _ = test.nodeHandler.Get(test.nodeName, metav1.GetOptions{}) - assert.EqualValues(t, test.expectedTaints, node.Spec.Taints, - "%s: failed to remove taint off node: expected %+v, got %+v", - test.name, test.expectedTaints, node.Spec.Taints) - - assert.Equal(t, test.requestCount, test.nodeHandler.RequestCount, - "%s: unexpected request count: expected %+v, got %+v", - test.name, test.requestCount, test.nodeHandler.RequestCount) - } -} - -func TestAddOrUpdateTaintOnNode(t *testing.T) { - tests := []struct { - name string - nodeHandler *testutil.FakeNodeHandler - nodeName string - taintsToAdd []*v1.Taint - expectedTaints []v1.Taint - requestCount int - }{ - { - name: "add one taint on node", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - }, - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToAdd: []*v1.Taint{ - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - expectedTaints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - requestCount: 3, - }, - { - name: "add multiple taints to node", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToAdd: []*v1.Taint{ - {Key: "key3", Value: "value3", Effect: "NoSchedule"}, - {Key: "key4", Value: "value4", Effect: "NoExecute"}, - }, - expectedTaints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - {Key: "key3", Value: "value3", Effect: "NoSchedule"}, - {Key: "key4", Value: "value4", Effect: "NoExecute"}, - }, - requestCount: 3, - }, - { - name: "add exist taints to node", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToAdd: []*v1.Taint{ - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - expectedTaints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - requestCount: 2, - }, - { - name: "add taint to node without taints", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToAdd: []*v1.Taint{ - {Key: "key3", Value: "value3", Effect: "NoSchedule"}, - }, - expectedTaints: []v1.Taint{ - {Key: "key3", Value: "value3", Effect: "NoSchedule"}, - }, - requestCount: 3, - }, - { - name: "add empty taint list to node without taints", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToAdd: []*v1.Taint{}, - expectedTaints: nil, - requestCount: 1, - }, - { - name: "add empty taint list to node", - nodeHandler: &testutil.FakeNodeHandler{ - Existing: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "node1", - }, - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - }, - }, - }, - Clientset: fake.NewSimpleClientset(&v1.PodList{Items: []v1.Pod{*testutil.NewPod("pod0", "node0")}}), - }, - nodeName: "node1", - taintsToAdd: []*v1.Taint{}, - expectedTaints: []v1.Taint{ - {Key: "key1", Value: "value1", Effect: "NoSchedule"}, - {Key: "key2", Value: "value2", Effect: "NoExecute"}, - }, - requestCount: 1, - }, - } - for _, test := range tests { - err := AddOrUpdateTaintOnNode(test.nodeHandler, test.nodeName, test.taintsToAdd...) - assert.NoError(t, err, "%s: AddOrUpdateTaintOnNode() error = %v", test.name, err) - - node, _ := test.nodeHandler.Get(test.nodeName, metav1.GetOptions{}) - assert.EqualValues(t, test.expectedTaints, node.Spec.Taints, - "%s: failed to add taint to node: expected %+v, got %+v", - test.name, test.expectedTaints, node.Spec.Taints) - - assert.Equal(t, test.requestCount, test.nodeHandler.RequestCount, - "%s: unexpected request count: expected %+v, got %+v", - test.name, test.requestCount, test.nodeHandler.RequestCount) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/fieldpath/fieldpath_test.go b/vendor/k8s.io/kubernetes/pkg/fieldpath/fieldpath_test.go deleted file mode 100644 index aa87f02a8e..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/fieldpath/fieldpath_test.go +++ /dev/null @@ -1,241 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package fieldpath - -import ( - "strings" - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestExtractFieldPathAsString(t *testing.T) { - cases := []struct { - name string - fieldPath string - obj interface{} - expectedValue string - expectedMessageFragment string - }{ - { - name: "not an API object", - fieldPath: "metadata.name", - obj: "", - }, - { - name: "ok - namespace", - fieldPath: "metadata.namespace", - obj: &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "object-namespace", - }, - }, - expectedValue: "object-namespace", - }, - { - name: "ok - name", - fieldPath: "metadata.name", - obj: &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "object-name", - }, - }, - expectedValue: "object-name", - }, - { - name: "ok - labels", - fieldPath: "metadata.labels", - obj: &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"key": "value"}, - }, - }, - expectedValue: "key=\"value\"", - }, - { - name: "ok - labels bslash n", - fieldPath: "metadata.labels", - obj: &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{"key": "value\n"}, - }, - }, - expectedValue: "key=\"value\\n\"", - }, - { - name: "ok - annotations", - fieldPath: "metadata.annotations", - obj: &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{"builder": "john-doe"}, - }, - }, - expectedValue: "builder=\"john-doe\"", - }, - { - name: "ok - annotation", - fieldPath: "metadata.annotations['spec.pod.beta.kubernetes.io/statefulset-index']", - obj: &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{"spec.pod.beta.kubernetes.io/statefulset-index": "1"}, - }, - }, - expectedValue: "1", - }, - { - name: "ok - annotation", - fieldPath: "metadata.annotations['Www.k8s.io/test']", - obj: &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{"Www.k8s.io/test": "1"}, - }, - }, - expectedValue: "1", - }, - { - name: "invalid expression", - fieldPath: "metadata.whoops", - obj: &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "object-namespace", - }, - }, - expectedMessageFragment: "unsupported fieldPath", - }, - { - name: "invalid annotation key", - fieldPath: "metadata.annotations['invalid~key']", - obj: &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{"foo": "bar"}, - }, - }, - expectedMessageFragment: "invalid key subscript in metadata.annotations", - }, - { - name: "invalid label key", - fieldPath: "metadata.labels['Www.k8s.io/test']", - obj: &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{"foo": "bar"}, - }, - }, - expectedMessageFragment: "invalid key subscript in metadata.labels", - }, - } - - for _, tc := range cases { - actual, err := ExtractFieldPathAsString(tc.obj, tc.fieldPath) - if err != nil { - if tc.expectedMessageFragment != "" { - if !strings.Contains(err.Error(), tc.expectedMessageFragment) { - t.Errorf("%v: unexpected error message: %q, expected to contain %q", tc.name, err, tc.expectedMessageFragment) - } - } else { - t.Errorf("%v: unexpected error: %v", tc.name, err) - } - } else if tc.expectedMessageFragment != "" { - t.Errorf("%v: expected error: %v", tc.name, tc.expectedMessageFragment) - } else if e := tc.expectedValue; e != "" && e != actual { - t.Errorf("%v: unexpected result; got %q, expected %q", tc.name, actual, e) - } - } -} - -func TestSplitMaybeSubscriptedPath(t *testing.T) { - cases := []struct { - fieldPath string - expectedPath string - expectedSubscript string - expectedOK bool - }{ - { - fieldPath: "metadata.annotations['key']", - expectedPath: "metadata.annotations", - expectedSubscript: "key", - expectedOK: true, - }, - { - fieldPath: "metadata.annotations['a[b']c']", - expectedPath: "metadata.annotations", - expectedSubscript: "a[b']c", - expectedOK: true, - }, - { - fieldPath: "metadata.labels['['key']", - expectedPath: "metadata.labels", - expectedSubscript: "['key", - expectedOK: true, - }, - { - fieldPath: "metadata.labels['key']']", - expectedPath: "metadata.labels", - expectedSubscript: "key']", - expectedOK: true, - }, - { - fieldPath: "metadata.labels['']", - expectedPath: "metadata.labels", - expectedSubscript: "", - expectedOK: true, - }, - { - fieldPath: "metadata.labels[' ']", - expectedPath: "metadata.labels", - expectedSubscript: " ", - expectedOK: true, - }, - { - fieldPath: "metadata.labels[ 'key' ]", - expectedOK: false, - }, - { - fieldPath: "metadata.labels[]", - expectedOK: false, - }, - { - fieldPath: "metadata.labels[']", - expectedOK: false, - }, - { - fieldPath: "metadata.labels['key']foo", - expectedOK: false, - }, - { - fieldPath: "['key']", - expectedOK: false, - }, - { - fieldPath: "metadata.labels", - expectedOK: false, - }, - } - for _, tc := range cases { - path, subscript, ok := SplitMaybeSubscriptedPath(tc.fieldPath) - if !ok { - if tc.expectedOK { - t.Errorf("SplitMaybeSubscriptedPath(%q) expected to return (_, _, true)", tc.fieldPath) - } - continue - } - if path != tc.expectedPath || subscript != tc.expectedSubscript { - t.Errorf("SplitMaybeSubscriptedPath(%q) = (%q, %q, true), expect (%q, %q, true)", - tc.fieldPath, path, subscript, tc.expectedPath, tc.expectedSubscript) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/active_deadline_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/active_deadline_test.go deleted file mode 100644 index 32fbd6c331..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/active_deadline_test.go +++ /dev/null @@ -1,95 +0,0 @@ -/* -Copyright 2016 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 kubelet - -import ( - "testing" - "time" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/clock" - "k8s.io/client-go/tools/record" -) - -// mockPodStatusProvider returns the status on the specified pod -type mockPodStatusProvider struct { - pods []*v1.Pod -} - -// GetPodStatus returns the status on the associated pod with matching uid (if found) -func (m *mockPodStatusProvider) GetPodStatus(uid types.UID) (v1.PodStatus, bool) { - for _, pod := range m.pods { - if pod.UID == uid { - return pod.Status, true - } - } - return v1.PodStatus{}, false -} - -// TestActiveDeadlineHandler verifies the active deadline handler functions as expected. -func TestActiveDeadlineHandler(t *testing.T) { - pods := newTestPods(4) - fakeClock := clock.NewFakeClock(time.Now()) - podStatusProvider := &mockPodStatusProvider{pods: pods} - fakeRecorder := &record.FakeRecorder{} - handler, err := newActiveDeadlineHandler(podStatusProvider, fakeRecorder, fakeClock) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - now := metav1.Now() - startTime := metav1.NewTime(now.Time.Add(-1 * time.Minute)) - - // this pod has exceeded its active deadline - exceededActiveDeadlineSeconds := int64(30) - pods[0].Status.StartTime = &startTime - pods[0].Spec.ActiveDeadlineSeconds = &exceededActiveDeadlineSeconds - - // this pod has not exceeded its active deadline - notYetActiveDeadlineSeconds := int64(120) - pods[1].Status.StartTime = &startTime - pods[1].Spec.ActiveDeadlineSeconds = &notYetActiveDeadlineSeconds - - // this pod has no deadline - pods[2].Status.StartTime = &startTime - pods[2].Spec.ActiveDeadlineSeconds = nil - - testCases := []struct { - pod *v1.Pod - expected bool - }{{pods[0], true}, {pods[1], false}, {pods[2], false}, {pods[3], false}} - - for i, testCase := range testCases { - if actual := handler.ShouldSync(testCase.pod); actual != testCase.expected { - t.Errorf("[%d] ShouldSync expected %#v, got %#v", i, testCase.expected, actual) - } - actual := handler.ShouldEvict(testCase.pod) - if actual.Evict != testCase.expected { - t.Errorf("[%d] ShouldEvict.Evict expected %#v, got %#v", i, testCase.expected, actual.Evict) - } - if testCase.expected { - if actual.Reason != reason { - t.Errorf("[%d] ShouldEvict.Reason expected %#v, got %#v", i, message, actual.Reason) - } - if actual.Message != message { - t.Errorf("[%d] ShouldEvict.Message expected %#v, got %#v", i, message, actual.Message) - } - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/cache_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/cache_test.go deleted file mode 100644 index b1dc1bd239..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/cache_test.go +++ /dev/null @@ -1,210 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package container - -import ( - "fmt" - "strconv" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "k8s.io/apimachinery/pkg/types" -) - -func newTestCache() *cache { - c := NewCache() - return c.(*cache) -} - -func TestCacheNotInitialized(t *testing.T) { - cache := newTestCache() - // If the global timestamp is not set, always return nil. - d := cache.getIfNewerThan(types.UID("1234"), time.Time{}) - assert.True(t, d == nil, "should return nil since cache is not initialized") -} - -func getTestPodIDAndStatus(numContainers int) (types.UID, *PodStatus) { - id := types.UID(strconv.FormatInt(time.Now().UnixNano(), 10)) - name := fmt.Sprintf("cache-foo-%s", string(id)) - namespace := "ns" - var status *PodStatus - if numContainers > 0 { - status = &PodStatus{ID: id, Name: name, Namespace: namespace} - } else { - status = &PodStatus{ID: id} - } - for i := 0; i < numContainers; i++ { - status.ContainerStatuses = append(status.ContainerStatuses, &ContainerStatus{Name: string(i)}) - } - return id, status -} - -func TestGetIfNewerThanWhenPodExists(t *testing.T) { - cache := newTestCache() - timestamp := time.Now() - - cases := []struct { - cacheTime time.Time - modified time.Time - expected bool - }{ - { - // Both the global cache timestamp and the modified time are newer - // than the timestamp. - cacheTime: timestamp.Add(time.Second), - modified: timestamp, - expected: true, - }, - { - // Global cache timestamp is newer, but the pod entry modified - // time is older than the given timestamp. This means that the - // entry is up-to-date even though it hasn't changed for a while. - cacheTime: timestamp.Add(time.Second), - modified: timestamp.Add(-time.Second * 10), - expected: true, - }, - { - // Global cache timestamp is older, but the pod entry modified - // time is newer than the given timestamp. This means that the - // entry is up-to-date but the rest of the cache are still being - // updated. - cacheTime: timestamp.Add(-time.Second), - modified: timestamp.Add(time.Second * 3), - expected: true, - }, - { - // Both the global cache timestamp and the modified time are older - // than the given timestamp. - cacheTime: timestamp.Add(-time.Second), - modified: timestamp.Add(-time.Second), - expected: false, - }, - } - for i, c := range cases { - podID, status := getTestPodIDAndStatus(2) - cache.UpdateTime(c.cacheTime) - cache.Set(podID, status, nil, c.modified) - d := cache.getIfNewerThan(podID, timestamp) - assert.Equal(t, c.expected, d != nil, "test[%d]", i) - } -} - -func TestGetPodNewerThanWhenPodDoesNotExist(t *testing.T) { - cache := newTestCache() - cacheTime := time.Now() - cache.UpdateTime(cacheTime) - podID := types.UID("1234") - - cases := []struct { - timestamp time.Time - expected bool - }{ - { - timestamp: cacheTime.Add(-time.Second), - expected: true, - }, - { - timestamp: cacheTime.Add(time.Second), - expected: false, - }, - } - for i, c := range cases { - d := cache.getIfNewerThan(podID, c.timestamp) - assert.Equal(t, c.expected, d != nil, "test[%d]", i) - } -} - -func TestCacheSetAndGet(t *testing.T) { - cache := NewCache() - cases := []struct { - numContainers int - error error - }{ - {numContainers: 3, error: nil}, - {numContainers: 2, error: fmt.Errorf("unable to get status")}, - {numContainers: 0, error: nil}, - } - for i, c := range cases { - podID, status := getTestPodIDAndStatus(c.numContainers) - cache.Set(podID, status, c.error, time.Time{}) - // Read back the status and error stored in cache and make sure they - // match the original ones. - actualStatus, actualErr := cache.Get(podID) - assert.Equal(t, status, actualStatus, "test[%d]", i) - assert.Equal(t, c.error, actualErr, "test[%d]", i) - } -} - -func TestCacheGetPodDoesNotExist(t *testing.T) { - cache := NewCache() - podID, status := getTestPodIDAndStatus(0) - // If the pod does not exist in cache, cache should return an status - // object with id filled. - actualStatus, actualErr := cache.Get(podID) - assert.Equal(t, status, actualStatus) - assert.Equal(t, nil, actualErr) -} - -func TestDelete(t *testing.T) { - cache := &cache{pods: map[types.UID]*data{}} - // Write a new pod status into the cache. - podID, status := getTestPodIDAndStatus(3) - cache.Set(podID, status, nil, time.Time{}) - actualStatus, actualErr := cache.Get(podID) - assert.Equal(t, status, actualStatus) - assert.Equal(t, nil, actualErr) - // Delete the pod from cache, and verify that we get an empty status. - cache.Delete(podID) - expectedStatus := &PodStatus{ID: podID} - actualStatus, actualErr = cache.Get(podID) - assert.Equal(t, expectedStatus, actualStatus) - assert.Equal(t, nil, actualErr) -} - -func verifyNotification(t *testing.T, ch chan *data, expectNotification bool) { - if expectNotification { - assert.True(t, len(ch) > 0, "Did not receive notification") - } else { - assert.True(t, len(ch) < 1, "Should not have triggered the notification") - } - // Drain the channel. - for i := 0; i < len(ch); i++ { - <-ch - } -} - -func TestRegisterNotification(t *testing.T) { - cache := newTestCache() - cacheTime := time.Now() - cache.UpdateTime(cacheTime) - - podID, status := getTestPodIDAndStatus(1) - ch := cache.subscribe(podID, cacheTime.Add(time.Second)) - verifyNotification(t, ch, false) - cache.Set(podID, status, nil, cacheTime.Add(time.Second)) - // The Set operation should've triggered the notification. - verifyNotification(t, ch, true) - - podID, _ = getTestPodIDAndStatus(1) - - ch = cache.subscribe(podID, cacheTime.Add(time.Second)) - verifyNotification(t, ch, false) - cache.UpdateTime(cacheTime.Add(time.Second * 2)) - // The advance of cache timestamp should've triggered the notification. - verifyNotification(t, ch, true) -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/helpers_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/helpers_test.go deleted file mode 100644 index 14d9d6e6c8..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/helpers_test.go +++ /dev/null @@ -1,322 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package container - -import ( - "reflect" - "testing" - - "github.com/stretchr/testify/assert" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestEnvVarsToMap(t *testing.T) { - vars := []EnvVar{ - { - Name: "foo", - Value: "bar", - }, - { - Name: "zoo", - Value: "baz", - }, - } - - varMap := EnvVarsToMap(vars) - - if e, a := len(vars), len(varMap); e != a { - t.Errorf("Unexpected map length; expected: %d, got %d", e, a) - } - - if a := varMap["foo"]; a != "bar" { - t.Errorf("Unexpected value of key 'foo': %v", a) - } - - if a := varMap["zoo"]; a != "baz" { - t.Errorf("Unexpected value of key 'zoo': %v", a) - } -} - -func TestExpandCommandAndArgs(t *testing.T) { - cases := []struct { - name string - container *v1.Container - envs []EnvVar - expectedCommand []string - expectedArgs []string - }{ - { - name: "none", - container: &v1.Container{}, - }, - { - name: "command expanded", - container: &v1.Container{ - Command: []string{"foo", "$(VAR_TEST)", "$(VAR_TEST2)"}, - }, - envs: []EnvVar{ - { - Name: "VAR_TEST", - Value: "zoo", - }, - { - Name: "VAR_TEST2", - Value: "boo", - }, - }, - expectedCommand: []string{"foo", "zoo", "boo"}, - }, - { - name: "args expanded", - container: &v1.Container{ - Args: []string{"zap", "$(VAR_TEST)", "$(VAR_TEST2)"}, - }, - envs: []EnvVar{ - { - Name: "VAR_TEST", - Value: "hap", - }, - { - Name: "VAR_TEST2", - Value: "trap", - }, - }, - expectedArgs: []string{"zap", "hap", "trap"}, - }, - { - name: "both expanded", - container: &v1.Container{ - Command: []string{"$(VAR_TEST2)--$(VAR_TEST)", "foo", "$(VAR_TEST3)"}, - Args: []string{"foo", "$(VAR_TEST)", "$(VAR_TEST2)"}, - }, - envs: []EnvVar{ - { - Name: "VAR_TEST", - Value: "zoo", - }, - { - Name: "VAR_TEST2", - Value: "boo", - }, - { - Name: "VAR_TEST3", - Value: "roo", - }, - }, - expectedCommand: []string{"boo--zoo", "foo", "roo"}, - expectedArgs: []string{"foo", "zoo", "boo"}, - }, - } - - for _, tc := range cases { - actualCommand, actualArgs := ExpandContainerCommandAndArgs(tc.container, tc.envs) - - if e, a := tc.expectedCommand, actualCommand; !reflect.DeepEqual(e, a) { - t.Errorf("%v: unexpected command; expected %v, got %v", tc.name, e, a) - } - - if e, a := tc.expectedArgs, actualArgs; !reflect.DeepEqual(e, a) { - t.Errorf("%v: unexpected args; expected %v, got %v", tc.name, e, a) - } - - } -} - -func TestShouldContainerBeRestarted(t *testing.T) { - pod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - UID: "12345678", - Name: "foo", - Namespace: "new", - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - {Name: "no-history"}, - {Name: "alive"}, - {Name: "succeed"}, - {Name: "failed"}, - {Name: "unknown"}, - }, - }, - } - podStatus := &PodStatus{ - ID: pod.UID, - Name: pod.Name, - Namespace: pod.Namespace, - ContainerStatuses: []*ContainerStatus{ - { - Name: "alive", - State: ContainerStateRunning, - }, - { - Name: "succeed", - State: ContainerStateExited, - ExitCode: 0, - }, - { - Name: "failed", - State: ContainerStateExited, - ExitCode: 1, - }, - { - Name: "alive", - State: ContainerStateExited, - ExitCode: 2, - }, - { - Name: "unknown", - State: ContainerStateUnknown, - }, - { - Name: "failed", - State: ContainerStateExited, - ExitCode: 3, - }, - }, - } - policies := []v1.RestartPolicy{ - v1.RestartPolicyNever, - v1.RestartPolicyOnFailure, - v1.RestartPolicyAlways, - } - expected := map[string][]bool{ - "no-history": {true, true, true}, - "alive": {false, false, false}, - "succeed": {false, false, true}, - "failed": {false, true, true}, - "unknown": {true, true, true}, - } - for _, c := range pod.Spec.Containers { - for i, policy := range policies { - pod.Spec.RestartPolicy = policy - e := expected[c.Name][i] - r := ShouldContainerBeRestarted(&c, pod, podStatus) - if r != e { - t.Errorf("Restart for container %q with restart policy %q expected %t, got %t", - c.Name, policy, e, r) - } - } - } -} - -func TestHasPrivilegedContainer(t *testing.T) { - newBoolPtr := func(b bool) *bool { - return &b - } - tests := map[string]struct { - securityContext *v1.SecurityContext - expected bool - }{ - "nil security context": { - securityContext: nil, - expected: false, - }, - "nil privileged": { - securityContext: &v1.SecurityContext{}, - expected: false, - }, - "false privileged": { - securityContext: &v1.SecurityContext{Privileged: newBoolPtr(false)}, - expected: false, - }, - "true privileged": { - securityContext: &v1.SecurityContext{Privileged: newBoolPtr(true)}, - expected: true, - }, - } - - for k, v := range tests { - pod := &v1.Pod{ - Spec: v1.PodSpec{ - Containers: []v1.Container{ - {SecurityContext: v.securityContext}, - }, - }, - } - actual := HasPrivilegedContainer(pod) - if actual != v.expected { - t.Errorf("%s expected %t but got %t", k, v.expected, actual) - } - } - // Test init containers as well. - for k, v := range tests { - pod := &v1.Pod{ - Spec: v1.PodSpec{ - InitContainers: []v1.Container{ - {SecurityContext: v.securityContext}, - }, - }, - } - actual := HasPrivilegedContainer(pod) - if actual != v.expected { - t.Errorf("%s expected %t but got %t", k, v.expected, actual) - } - } -} - -func TestMakePortMappings(t *testing.T) { - port := func(name string, protocol v1.Protocol, containerPort, hostPort int32, ip string) v1.ContainerPort { - return v1.ContainerPort{ - Name: name, - Protocol: protocol, - ContainerPort: containerPort, - HostPort: hostPort, - HostIP: ip, - } - } - portMapping := func(name string, protocol v1.Protocol, containerPort, hostPort int, ip string) PortMapping { - return PortMapping{ - Name: name, - Protocol: protocol, - ContainerPort: containerPort, - HostPort: hostPort, - HostIP: ip, - } - } - - tests := []struct { - container *v1.Container - expectedPortMappings []PortMapping - }{ - { - &v1.Container{ - Name: "fooContainer", - Ports: []v1.ContainerPort{ - port("", v1.ProtocolTCP, 80, 8080, "127.0.0.1"), - port("", v1.ProtocolTCP, 443, 4343, "192.168.0.1"), - port("foo", v1.ProtocolUDP, 555, 5555, ""), - // Duplicated, should be ignored. - port("foo", v1.ProtocolUDP, 888, 8888, ""), - // Duplicated, should be ignored. - port("", v1.ProtocolTCP, 80, 8888, ""), - }, - }, - []PortMapping{ - portMapping("fooContainer-TCP:80", v1.ProtocolTCP, 80, 8080, "127.0.0.1"), - portMapping("fooContainer-TCP:443", v1.ProtocolTCP, 443, 4343, "192.168.0.1"), - portMapping("fooContainer-foo", v1.ProtocolUDP, 555, 5555, ""), - }, - }, - } - - for i, tt := range tests { - actual := MakePortMappings(tt.container) - assert.Equal(t, tt.expectedPortMappings, actual, "[%d]", i) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/ref_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/ref_test.go deleted file mode 100644 index 705f202fda..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/ref_test.go +++ /dev/null @@ -1,213 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package container - -import ( - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/kubernetes/pkg/api/legacyscheme" - _ "k8s.io/kubernetes/pkg/apis/core/install" -) - -func TestFieldPath(t *testing.T) { - pod := &v1.Pod{Spec: v1.PodSpec{Containers: []v1.Container{ - {Name: "foo"}, - {Name: "bar"}, - {Name: ""}, - {Name: "baz"}, - }}} - table := map[string]struct { - pod *v1.Pod - container *v1.Container - path string - success bool - }{ - "basic": {pod, &v1.Container{Name: "foo"}, "spec.containers{foo}", true}, - "basic2": {pod, &v1.Container{Name: "baz"}, "spec.containers{baz}", true}, - "emptyName": {pod, &v1.Container{Name: ""}, "spec.containers[2]", true}, - "basicSamePointer": {pod, &pod.Spec.Containers[0], "spec.containers{foo}", true}, - "missing": {pod, &v1.Container{Name: "qux"}, "", false}, - } - - for name, item := range table { - res, err := fieldPath(item.pod, item.container) - if item.success == false { - if err == nil { - t.Errorf("%v: unexpected non-error", name) - } - continue - } - if err != nil { - t.Errorf("%v: unexpected error: %v", name, err) - continue - } - if e, a := item.path, res; e != a { - t.Errorf("%v: wanted %v, got %v", name, e, a) - } - } -} - -func TestGenerateContainerRef(t *testing.T) { - var ( - okPod = v1.Pod{ - TypeMeta: metav1.TypeMeta{ - Kind: "Pod", - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - }, - ObjectMeta: metav1.ObjectMeta{ - Name: "ok", - Namespace: "test-ns", - UID: "bar", - ResourceVersion: "42", - SelfLink: "/api/" + legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String() + "/pods/foo", - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - Name: "by-name", - }, - {}, - }, - }, - } - noSelfLinkPod = okPod - defaultedSelfLinkPod = okPod - ) - noSelfLinkPod.Kind = "" - noSelfLinkPod.APIVersion = "" - noSelfLinkPod.ObjectMeta.SelfLink = "" - defaultedSelfLinkPod.ObjectMeta.SelfLink = "/api/" + legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String() + "/pods/ok" - - cases := []struct { - name string - pod *v1.Pod - container *v1.Container - expected *v1.ObjectReference - success bool - }{ - { - name: "by-name", - pod: &okPod, - container: &v1.Container{ - Name: "by-name", - }, - expected: &v1.ObjectReference{ - Kind: "Pod", - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - Name: "ok", - Namespace: "test-ns", - UID: "bar", - ResourceVersion: "42", - FieldPath: ".spec.containers{by-name}", - }, - success: true, - }, - { - name: "no-name", - pod: &okPod, - container: &v1.Container{}, - expected: &v1.ObjectReference{ - Kind: "Pod", - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - Name: "ok", - Namespace: "test-ns", - UID: "bar", - ResourceVersion: "42", - FieldPath: ".spec.containers[1]", - }, - success: true, - }, - { - name: "no-selflink", - pod: &noSelfLinkPod, - container: &v1.Container{}, - expected: nil, - success: false, - }, - { - name: "defaulted-selflink", - pod: &defaultedSelfLinkPod, - container: &v1.Container{ - Name: "by-name", - }, - expected: &v1.ObjectReference{ - Kind: "Pod", - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - Name: "ok", - Namespace: "test-ns", - UID: "bar", - ResourceVersion: "42", - FieldPath: ".spec.containers{by-name}", - }, - success: true, - }, - { - name: "implicitly-required", - pod: &okPod, - container: &v1.Container{ - Name: "net", - }, - expected: &v1.ObjectReference{ - Kind: "Pod", - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - Name: "ok", - Namespace: "test-ns", - UID: "bar", - ResourceVersion: "42", - FieldPath: "implicitly required container net", - }, - success: true, - }, - } - - for _, tc := range cases { - actual, err := GenerateContainerRef(tc.pod, tc.container) - if err != nil { - if tc.success { - t.Errorf("%v: unexpected error: %v", tc.name, err) - } - - continue - } - - if !tc.success { - t.Errorf("%v: unexpected success", tc.name) - continue - } - - if e, a := tc.expected.Kind, actual.Kind; e != a { - t.Errorf("%v: kind: expected %v, got %v", tc.name, e, a) - } - if e, a := tc.expected.APIVersion, actual.APIVersion; e != a { - t.Errorf("%v: apiVersion: expected %v, got %v", tc.name, e, a) - } - if e, a := tc.expected.Name, actual.Name; e != a { - t.Errorf("%v: name: expected %v, got %v", tc.name, e, a) - } - if e, a := tc.expected.Namespace, actual.Namespace; e != a { - t.Errorf("%v: namespace: expected %v, got %v", tc.name, e, a) - } - if e, a := tc.expected.UID, actual.UID; e != a { - t.Errorf("%v: uid: expected %v, got %v", tc.name, e, a) - } - if e, a := tc.expected.ResourceVersion, actual.ResourceVersion; e != a { - t.Errorf("%v: kind: expected %v, got %v", tc.name, e, a) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache_test.go deleted file mode 100644 index 4fc4da8bf3..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/runtime_cache_test.go +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package container_test - -import ( - "reflect" - "testing" - "time" - - . "k8s.io/kubernetes/pkg/kubelet/container" - ctest "k8s.io/kubernetes/pkg/kubelet/container/testing" -) - -func comparePods(t *testing.T, expected []*ctest.FakePod, actual []*Pod) { - if len(expected) != len(actual) { - t.Errorf("expected %d pods, got %d instead", len(expected), len(actual)) - } - for i := range expected { - if !reflect.DeepEqual(expected[i].Pod, actual[i]) { - t.Errorf("expected %#v, got %#v", expected[i].Pod, actual[i]) - } - } -} - -func TestGetPods(t *testing.T) { - runtime := &ctest.FakeRuntime{} - expected := []*ctest.FakePod{{Pod: &Pod{ID: "1111"}}, {Pod: &Pod{ID: "2222"}}, {Pod: &Pod{ID: "3333"}}} - runtime.PodList = expected - cache := NewTestRuntimeCache(runtime) - actual, err := cache.GetPods() - if err != nil { - t.Errorf("unexpected error %v", err) - } - - comparePods(t, expected, actual) -} - -func TestForceUpdateIfOlder(t *testing.T) { - runtime := &ctest.FakeRuntime{} - cache := NewTestRuntimeCache(runtime) - - // Cache old pods. - oldpods := []*ctest.FakePod{{Pod: &Pod{ID: "1111"}}} - runtime.PodList = oldpods - cache.UpdateCacheWithLock() - - // Update the runtime to new pods. - newpods := []*ctest.FakePod{{Pod: &Pod{ID: "1111"}}, {Pod: &Pod{ID: "2222"}}, {Pod: &Pod{ID: "3333"}}} - runtime.PodList = newpods - - // An older timestamp should not force an update. - cache.ForceUpdateIfOlder(time.Now().Add(-20 * time.Minute)) - actual := cache.GetCachedPods() - comparePods(t, oldpods, actual) - - // A newer timestamp should force an update. - cache.ForceUpdateIfOlder(time.Now().Add(20 * time.Second)) - actual = cache.GetCachedPods() - comparePods(t, newpods, actual) -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/container/sync_result_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/container/sync_result_test.go deleted file mode 100644 index 56f191d3d5..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/container/sync_result_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package container - -import ( - "errors" - "testing" -) - -func TestPodSyncResult(t *testing.T) { - okResults := []*SyncResult{ - NewSyncResult(StartContainer, "container_0"), - NewSyncResult(SetupNetwork, "pod"), - } - errResults := []*SyncResult{ - NewSyncResult(KillContainer, "container_1"), - NewSyncResult(TeardownNetwork, "pod"), - } - errResults[0].Fail(errors.New("error_0"), "message_0") - errResults[1].Fail(errors.New("error_1"), "message_1") - - // If the PodSyncResult doesn't contain error result, it should not be error - result := PodSyncResult{} - result.AddSyncResult(okResults...) - if result.Error() != nil { - t.Errorf("PodSyncResult should not be error: %v", result) - } - - // If the PodSyncResult contains error result, it should be error - result = PodSyncResult{} - result.AddSyncResult(okResults...) - result.AddSyncResult(errResults...) - if result.Error() == nil { - t.Errorf("PodSyncResult should be error: %q", result) - } - - // If the PodSyncResult is failed, it should be error - result = PodSyncResult{} - result.AddSyncResult(okResults...) - result.Fail(errors.New("error")) - if result.Error() == nil { - t.Errorf("PodSyncResult should be error: %q", result) - } - - // If the PodSyncResult is added an error PodSyncResult, it should be error - errResult := PodSyncResult{} - errResult.AddSyncResult(errResults...) - result = PodSyncResult{} - result.AddSyncResult(okResults...) - result.AddPodSyncResult(errResult) - if result.Error() == nil { - t.Errorf("PodSyncResult should be error: %q", result) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet.go index c4e88c0cb1..40b694663e 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet.go @@ -237,6 +237,7 @@ type Dependencies struct { DockerClientConfig *dockershim.ClientConfig EventClient v1core.EventsGetter HeartbeatClient v1core.CoreV1Interface + OnHeartbeatFailure func() KubeClient clientset.Interface ExternalKubeClient clientset.Interface Mounter mount.Interface @@ -493,6 +494,7 @@ func NewMainKubelet(kubeCfg *kubeletconfiginternal.KubeletConfiguration, nodeName: nodeName, kubeClient: kubeDeps.KubeClient, heartbeatClient: kubeDeps.HeartbeatClient, + onRepeatedHeartbeatFailure: kubeDeps.OnHeartbeatFailure, rootDirectory: rootDirectory, resyncInterval: kubeCfg.SyncFrequency.Duration, sourcesReady: config.NewSourcesReady(kubeDeps.PodConfig.SeenAllSources), @@ -935,6 +937,9 @@ type Kubelet struct { iptClient utilipt.Interface rootDirectory string + // onRepeatedHeartbeatFailure is called when a heartbeat operation fails more than once. optional. + onRepeatedHeartbeatFailure func() + // podWorkers handle syncing Pods in response to events. podWorkers PodWorkers diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_getters_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_getters_test.go deleted file mode 100644 index 8eb04e36af..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_getters_test.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright 2016 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 kubelet - -import ( - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestKubeletDirs(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - root := kubelet.rootDirectory - - var exp, got string - - got = kubelet.getPodsDir() - exp = filepath.Join(root, "pods") - assert.Equal(t, exp, got) - - got = kubelet.getPluginsDir() - exp = filepath.Join(root, "plugins") - assert.Equal(t, exp, got) - - got = kubelet.getPluginDir("foobar") - exp = filepath.Join(root, "plugins/foobar") - assert.Equal(t, exp, got) - - got = kubelet.getPodDir("abc123") - exp = filepath.Join(root, "pods/abc123") - assert.Equal(t, exp, got) - - got = kubelet.getPodVolumesDir("abc123") - exp = filepath.Join(root, "pods/abc123/volumes") - assert.Equal(t, exp, got) - - got = kubelet.getPodVolumeDir("abc123", "plugin", "foobar") - exp = filepath.Join(root, "pods/abc123/volumes/plugin/foobar") - assert.Equal(t, exp, got) - - got = kubelet.getPodPluginsDir("abc123") - exp = filepath.Join(root, "pods/abc123/plugins") - assert.Equal(t, exp, got) - - got = kubelet.getPodPluginDir("abc123", "foobar") - exp = filepath.Join(root, "pods/abc123/plugins/foobar") - assert.Equal(t, exp, got) - - got = kubelet.getPodContainerDir("abc123", "def456") - exp = filepath.Join(root, "pods/abc123/containers/def456") - assert.Equal(t, exp, got) -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_network_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_network_test.go deleted file mode 100644 index edc91af2b2..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_network_test.go +++ /dev/null @@ -1,206 +0,0 @@ -/* -Copyright 2016 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 kubelet - -import ( - "fmt" - "net" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNetworkHostGetsPodNotFound(t *testing.T) { - testKubelet := newTestKubelet(t, true) - defer testKubelet.Cleanup() - nh := networkHost{testKubelet.kubelet} - - actualPod, _ := nh.GetPodByName("", "") - if actualPod != nil { - t.Fatalf("Was expected nil, received %v instead", actualPod) - } -} - -func TestNetworkHostGetsKubeClient(t *testing.T) { - testKubelet := newTestKubelet(t, true) - defer testKubelet.Cleanup() - nh := networkHost{testKubelet.kubelet} - - if nh.GetKubeClient() != testKubelet.fakeKubeClient { - t.Fatalf("NetworkHost client does not match testKubelet's client") - } -} - -func TestNetworkHostGetsRuntime(t *testing.T) { - testKubelet := newTestKubelet(t, true) - defer testKubelet.Cleanup() - nh := networkHost{testKubelet.kubelet} - - if nh.GetRuntime() != testKubelet.fakeRuntime { - t.Fatalf("NetworkHost runtime does not match testKubelet's runtime") - } -} - -func TestNetworkHostSupportsLegacyFeatures(t *testing.T) { - testKubelet := newTestKubelet(t, true) - defer testKubelet.Cleanup() - nh := networkHost{testKubelet.kubelet} - - if nh.SupportsLegacyFeatures() == false { - t.Fatalf("SupportsLegacyFeatures should not be false") - } -} - -func TestNoOpHostGetsName(t *testing.T) { - nh := NoOpLegacyHost{} - pod, err := nh.GetPodByName("", "") - if pod != nil && err != true { - t.Fatalf("noOpLegacyHost getpodbyname expected to be nil and true") - } -} - -func TestNoOpHostGetsKubeClient(t *testing.T) { - nh := NoOpLegacyHost{} - if nh.GetKubeClient() != nil { - t.Fatalf("noOpLegacyHost client expected to be nil") - } -} - -func TestNoOpHostGetsRuntime(t *testing.T) { - nh := NoOpLegacyHost{} - if nh.GetRuntime() != nil { - t.Fatalf("noOpLegacyHost runtime expected to be nil") - } -} - -func TestNoOpHostSupportsLegacyFeatures(t *testing.T) { - nh := NoOpLegacyHost{} - if nh.SupportsLegacyFeatures() != false { - t.Fatalf("noOpLegacyHost legacy features expected to be false") - } -} - -func TestNodeIPParam(t *testing.T) { - type test struct { - nodeIP string - success bool - testName string - } - tests := []test{ - { - nodeIP: "", - success: false, - testName: "IP not set", - }, - { - nodeIP: "127.0.0.1", - success: false, - testName: "IPv4 loopback address", - }, - { - nodeIP: "::1", - success: false, - testName: "IPv6 loopback address", - }, - { - nodeIP: "224.0.0.1", - success: false, - testName: "multicast IPv4 address", - }, - { - nodeIP: "ff00::1", - success: false, - testName: "multicast IPv6 address", - }, - { - nodeIP: "169.254.0.1", - success: false, - testName: "IPv4 link-local unicast address", - }, - { - nodeIP: "fe80::0202:b3ff:fe1e:8329", - success: false, - testName: "IPv6 link-local unicast address", - }, - { - nodeIP: "0.0.0.0", - success: false, - testName: "Unspecified IPv4 address", - }, - { - nodeIP: "::", - success: false, - testName: "Unspecified IPv6 address", - }, - { - nodeIP: "1.2.3.4", - success: false, - testName: "IPv4 address that doesn't belong to host", - }, - } - addrs, err := net.InterfaceAddrs() - if err != nil { - assert.Error(t, err, fmt.Sprintf( - "Unable to obtain a list of the node's unicast interface addresses.")) - } - for _, addr := range addrs { - var ip net.IP - switch v := addr.(type) { - case *net.IPNet: - ip = v.IP - case *net.IPAddr: - ip = v.IP - } - if ip.IsLoopback() || ip.IsLinkLocalUnicast() { - break - } - successTest := test{ - nodeIP: ip.String(), - success: true, - testName: fmt.Sprintf("Success test case for address %s", ip.String()), - } - tests = append(tests, successTest) - } - for _, test := range tests { - err := validateNodeIP(net.ParseIP(test.nodeIP)) - if test.success { - assert.NoError(t, err, "test %s", test.testName) - } else { - assert.Error(t, err, fmt.Sprintf("test %s", test.testName)) - } - } -} - -func TestGetIPTablesMark(t *testing.T) { - tests := []struct { - bit int - expect string - }{ - { - 14, - "0x00004000/0x00004000", - }, - { - 15, - "0x00008000/0x00008000", - }, - } - for _, tc := range tests { - res := getIPTablesMark(tc.bit) - assert.Equal(t, tc.expect, res, "input %d", tc.bit) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status.go index 85e7ca7d17..1907ee3110 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status.go @@ -371,6 +371,9 @@ func (kl *Kubelet) syncNodeStatus() { func (kl *Kubelet) updateNodeStatus() error { for i := 0; i < nodeStatusUpdateRetry; i++ { if err := kl.tryUpdateNodeStatus(i); err != nil { + if i > 0 && kl.onRepeatedHeartbeatFailure != nil { + kl.onRepeatedHeartbeatFailure() + } glog.Errorf("Error updating node status, will retry: %v", err) } else { return nil diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status_test.go deleted file mode 100644 index af3dc0d656..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_node_status_test.go +++ /dev/null @@ -1,1418 +0,0 @@ -/* -Copyright 2016 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 kubelet - -import ( - "encoding/json" - "fmt" - "net" - goruntime "runtime" - "sort" - "strconv" - "sync/atomic" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - cadvisorapi "github.com/google/cadvisor/info/v1" - cadvisorapiv2 "github.com/google/cadvisor/info/v2" - "k8s.io/api/core/v1" - apiequality "k8s.io/apimachinery/pkg/api/equality" - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/diff" - "k8s.io/apimachinery/pkg/util/rand" - "k8s.io/apimachinery/pkg/util/strategicpatch" - "k8s.io/apimachinery/pkg/util/uuid" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes/fake" - v1core "k8s.io/client-go/kubernetes/typed/core/v1" - "k8s.io/client-go/rest" - core "k8s.io/client-go/testing" - fakecloud "k8s.io/kubernetes/pkg/cloudprovider/providers/fake" - kubeletapis "k8s.io/kubernetes/pkg/kubelet/apis" - "k8s.io/kubernetes/pkg/kubelet/cm" - kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" - "k8s.io/kubernetes/pkg/kubelet/util/sliceutils" - "k8s.io/kubernetes/pkg/version" - "k8s.io/kubernetes/pkg/volume/util" -) - -const ( - maxImageTagsForTest = 20 -) - -// generateTestingImageList generate randomly generated image list and corresponding expectedImageList. -func generateTestingImageList(count int) ([]kubecontainer.Image, []v1.ContainerImage) { - // imageList is randomly generated image list - var imageList []kubecontainer.Image - for ; count > 0; count-- { - imageItem := kubecontainer.Image{ - ID: string(uuid.NewUUID()), - RepoTags: generateImageTags(), - Size: rand.Int63nRange(minImgSize, maxImgSize+1), - } - imageList = append(imageList, imageItem) - } - - // expectedImageList is generated by imageList according to size and maxImagesInNodeStatus - // 1. sort the imageList by size - sort.Sort(sliceutils.ByImageSize(imageList)) - // 2. convert sorted imageList to v1.ContainerImage list - var expectedImageList []v1.ContainerImage - for _, kubeImage := range imageList { - apiImage := v1.ContainerImage{ - Names: kubeImage.RepoTags[0:maxNamesPerImageInNodeStatus], - SizeBytes: kubeImage.Size, - } - - expectedImageList = append(expectedImageList, apiImage) - } - // 3. only returns the top maxImagesInNodeStatus images in expectedImageList - return imageList, expectedImageList[0:maxImagesInNodeStatus] -} - -func generateImageTags() []string { - var tagList []string - // Generate > maxNamesPerImageInNodeStatus tags so that the test can verify - // that kubelet report up to maxNamesPerImageInNodeStatus tags. - count := rand.IntnRange(maxNamesPerImageInNodeStatus+1, maxImageTagsForTest+1) - for ; count > 0; count-- { - tagList = append(tagList, "k8s.gcr.io:v"+strconv.Itoa(count)) - } - return tagList -} - -func applyNodeStatusPatch(originalNode *v1.Node, patch []byte) (*v1.Node, error) { - original, err := json.Marshal(originalNode) - if err != nil { - return nil, fmt.Errorf("failed to marshal original node %#v: %v", originalNode, err) - } - updated, err := strategicpatch.StrategicMergePatch(original, patch, v1.Node{}) - if err != nil { - return nil, fmt.Errorf("failed to apply strategic merge patch %q on node %#v: %v", - patch, originalNode, err) - } - updatedNode := &v1.Node{} - if err := json.Unmarshal(updated, updatedNode); err != nil { - return nil, fmt.Errorf("failed to unmarshal updated node %q: %v", updated, err) - } - return updatedNode, nil -} - -type localCM struct { - cm.ContainerManager - allocatableReservation v1.ResourceList - capacity v1.ResourceList -} - -func (lcm *localCM) GetNodeAllocatableReservation() v1.ResourceList { - return lcm.allocatableReservation -} - -func (lcm *localCM) GetCapacity() v1.ResourceList { - return lcm.capacity -} - -func TestNodeStatusWithCloudProviderNodeIP(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubelet.kubeClient = nil // ensure only the heartbeat client is used - kubelet.hostname = testKubeletHostname - - existingNode := v1.Node{ - ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname, Annotations: make(map[string]string)}, - Spec: v1.NodeSpec{}, - } - - // TODO : is it possible to mock validateNodeIP() to avoid relying on the host interface addresses ? - addrs, err := net.InterfaceAddrs() - assert.NoError(t, err) - for _, addr := range addrs { - var ip net.IP - switch v := addr.(type) { - case *net.IPNet: - ip = v.IP - case *net.IPAddr: - ip = v.IP - } - if ip != nil && !ip.IsLoopback() && ip.To4() != nil { - kubelet.nodeIP = ip - break - } - } - assert.NotNil(t, kubelet.nodeIP) - - fakeCloud := &fakecloud.FakeCloud{ - Addresses: []v1.NodeAddress{ - { - Type: v1.NodeExternalIP, - Address: "132.143.154.163", - }, - { - Type: v1.NodeExternalIP, - Address: kubelet.nodeIP.String(), - }, - { - Type: v1.NodeInternalIP, - Address: "132.143.154.164", - }, - { - Type: v1.NodeInternalIP, - Address: kubelet.nodeIP.String(), - }, - { - Type: v1.NodeInternalIP, - Address: "132.143.154.165", - }, - { - Type: v1.NodeHostName, - Address: testKubeletHostname, - }, - }, - Err: nil, - } - kubelet.cloud = fakeCloud - - kubelet.setNodeAddress(&existingNode) - - expectedAddresses := []v1.NodeAddress{ - { - Type: v1.NodeExternalIP, - Address: kubelet.nodeIP.String(), - }, - { - Type: v1.NodeInternalIP, - Address: kubelet.nodeIP.String(), - }, - { - Type: v1.NodeHostName, - Address: testKubeletHostname, - }, - } - assert.True(t, apiequality.Semantic.DeepEqual(expectedAddresses, existingNode.Status.Addresses), "%s", diff.ObjectDiff(expectedAddresses, existingNode.Status.Addresses)) -} - -func TestUpdateNewNodeStatus(t *testing.T) { - // generate one more than maxImagesInNodeStatus in inputImageList - inputImageList, expectedImageList := generateTestingImageList(maxImagesInNodeStatus + 1) - testKubelet := newTestKubeletWithImageList( - t, inputImageList, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubelet.kubeClient = nil // ensure only the heartbeat client is used - kubelet.containerManager = &localCM{ - ContainerManager: cm.NewStubContainerManager(), - allocatableReservation: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(200, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(100E6, resource.BinarySI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(2000, resource.BinarySI), - }, - capacity: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), - }, - } - kubeClient := testKubelet.fakeKubeClient - existingNode := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}} - kubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{existingNode}}).ReactionChain - machineInfo := &cadvisorapi.MachineInfo{ - MachineID: "123", - SystemUUID: "abc", - BootID: "1b3", - NumCores: 2, - MemoryCapacity: 10E9, // 10G - } - mockCadvisor := testKubelet.fakeCadvisor - mockCadvisor.On("Start").Return(nil) - mockCadvisor.On("MachineInfo").Return(machineInfo, nil) - versionInfo := &cadvisorapi.VersionInfo{ - KernelVersion: "3.16.0-0.bpo.4-amd64", - ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", - } - mockCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 400, - Capacity: 5000, - Available: 600, - }, nil) - mockCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 400, - Capacity: 5000, - Available: 600, - }, nil) - mockCadvisor.On("VersionInfo").Return(versionInfo, nil) - maxAge := 0 * time.Second - options := cadvisorapiv2.RequestOptions{IdType: cadvisorapiv2.TypeName, Count: 2, Recursive: false, MaxAge: &maxAge} - mockCadvisor.On("ContainerInfoV2", "/", options).Return(map[string]cadvisorapiv2.ContainerInfo{}, nil) - kubelet.machineInfo = machineInfo - - expectedNode := &v1.Node{ - ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}, - Spec: v1.NodeSpec{}, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ - { - Type: v1.NodeOutOfDisk, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientDisk", - Message: fmt.Sprintf("kubelet has sufficient disk space available"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodeMemoryPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientMemory", - Message: fmt.Sprintf("kubelet has sufficient memory available"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodeDiskPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasNoDiskPressure", - Message: fmt.Sprintf("kubelet has no disk pressure"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodePIDPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientPID", - Message: fmt.Sprintf("kubelet has sufficient PID available"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodeReady, - Status: v1.ConditionTrue, - Reason: "KubeletReady", - Message: fmt.Sprintf("kubelet is posting ready status"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - }, - NodeInfo: v1.NodeSystemInfo{ - MachineID: "123", - SystemUUID: "abc", - BootID: "1b3", - KernelVersion: "3.16.0-0.bpo.4-amd64", - OSImage: "Debian GNU/Linux 7 (wheezy)", - OperatingSystem: goruntime.GOOS, - Architecture: goruntime.GOARCH, - ContainerRuntimeVersion: "test://1.5.0", - KubeletVersion: version.Get().String(), - KubeProxyVersion: version.Get().String(), - }, - Capacity: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), - }, - Allocatable: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(1800, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(9900E6, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(3000, resource.BinarySI), - }, - Addresses: []v1.NodeAddress{ - {Type: v1.NodeInternalIP, Address: "127.0.0.1"}, - {Type: v1.NodeHostName, Address: testKubeletHostname}, - }, - Images: expectedImageList, - }, - } - - kubelet.updateRuntimeUp() - assert.NoError(t, kubelet.updateNodeStatus()) - actions := kubeClient.Actions() - require.Len(t, actions, 2) - require.True(t, actions[1].Matches("patch", "nodes")) - require.Equal(t, actions[1].GetSubresource(), "status") - - updatedNode, err := applyNodeStatusPatch(&existingNode, actions[1].(core.PatchActionImpl).GetPatch()) - assert.NoError(t, err) - for i, cond := range updatedNode.Status.Conditions { - assert.False(t, cond.LastHeartbeatTime.IsZero(), "LastHeartbeatTime for %v condition is zero", cond.Type) - assert.False(t, cond.LastTransitionTime.IsZero(), "LastTransitionTime for %v condition is zero", cond.Type) - updatedNode.Status.Conditions[i].LastHeartbeatTime = metav1.Time{} - updatedNode.Status.Conditions[i].LastTransitionTime = metav1.Time{} - } - - // Version skew workaround. See: https://github.com/kubernetes/kubernetes/issues/16961 - assert.Equal(t, v1.NodeReady, updatedNode.Status.Conditions[len(updatedNode.Status.Conditions)-1].Type, - "NotReady should be last") - assert.Len(t, updatedNode.Status.Images, maxImagesInNodeStatus) - assert.True(t, apiequality.Semantic.DeepEqual(expectedNode, updatedNode), "%s", diff.ObjectDiff(expectedNode, updatedNode)) -} - -func TestUpdateExistingNodeStatus(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubelet.kubeClient = nil // ensure only the heartbeat client is used - kubelet.containerManager = &localCM{ - ContainerManager: cm.NewStubContainerManager(), - allocatableReservation: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(200, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(100E6, resource.BinarySI), - }, - capacity: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(20E9, resource.BinarySI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), - }, - } - - kubeClient := testKubelet.fakeKubeClient - existingNode := v1.Node{ - ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}, - Spec: v1.NodeSpec{}, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ - { - Type: v1.NodeOutOfDisk, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientDisk", - Message: fmt.Sprintf("kubelet has sufficient disk space available"), - LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), - LastTransitionTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - Type: v1.NodeMemoryPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientMemory", - Message: fmt.Sprintf("kubelet has sufficient memory available"), - LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), - LastTransitionTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - Type: v1.NodeDiskPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientDisk", - Message: fmt.Sprintf("kubelet has sufficient disk space available"), - LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), - LastTransitionTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - Type: v1.NodePIDPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientPID", - Message: fmt.Sprintf("kubelet has sufficient PID available"), - LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), - LastTransitionTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), - }, - { - Type: v1.NodeReady, - Status: v1.ConditionTrue, - Reason: "KubeletReady", - Message: fmt.Sprintf("kubelet is posting ready status"), - LastHeartbeatTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), - LastTransitionTime: metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC), - }, - }, - Capacity: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(3000, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(20E9, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - }, - Allocatable: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(2800, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(19900E6, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - }, - }, - } - kubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{existingNode}}).ReactionChain - mockCadvisor := testKubelet.fakeCadvisor - mockCadvisor.On("Start").Return(nil) - machineInfo := &cadvisorapi.MachineInfo{ - MachineID: "123", - SystemUUID: "abc", - BootID: "1b3", - NumCores: 2, - MemoryCapacity: 20E9, - } - mockCadvisor.On("MachineInfo").Return(machineInfo, nil) - versionInfo := &cadvisorapi.VersionInfo{ - KernelVersion: "3.16.0-0.bpo.4-amd64", - ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", - } - mockCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 400, - Capacity: 5000, - Available: 600, - }, nil) - mockCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 400, - Capacity: 5000, - Available: 600, - }, nil) - mockCadvisor.On("VersionInfo").Return(versionInfo, nil) - maxAge := 0 * time.Second - options := cadvisorapiv2.RequestOptions{IdType: cadvisorapiv2.TypeName, Count: 2, Recursive: false, MaxAge: &maxAge} - mockCadvisor.On("ContainerInfoV2", "/", options).Return(map[string]cadvisorapiv2.ContainerInfo{}, nil) - kubelet.machineInfo = machineInfo - - expectedNode := &v1.Node{ - ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}, - Spec: v1.NodeSpec{}, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ - { - Type: v1.NodeOutOfDisk, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientDisk", - Message: fmt.Sprintf("kubelet has sufficient disk space available"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodeMemoryPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientMemory", - Message: fmt.Sprintf("kubelet has sufficient memory available"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodeDiskPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientDisk", - Message: fmt.Sprintf("kubelet has sufficient disk space available"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodePIDPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientPID", - Message: fmt.Sprintf("kubelet has sufficient PID available"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodeReady, - Status: v1.ConditionTrue, - Reason: "KubeletReady", - Message: fmt.Sprintf("kubelet is posting ready status"), - LastHeartbeatTime: metav1.Time{}, // placeholder - LastTransitionTime: metav1.Time{}, // placeholder - }, - }, - NodeInfo: v1.NodeSystemInfo{ - MachineID: "123", - SystemUUID: "abc", - BootID: "1b3", - KernelVersion: "3.16.0-0.bpo.4-amd64", - OSImage: "Debian GNU/Linux 7 (wheezy)", - OperatingSystem: goruntime.GOOS, - Architecture: goruntime.GOARCH, - ContainerRuntimeVersion: "test://1.5.0", - KubeletVersion: version.Get().String(), - KubeProxyVersion: version.Get().String(), - }, - Capacity: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(20E9, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), - }, - Allocatable: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(1800, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(19900E6, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(5000, resource.BinarySI), - }, - Addresses: []v1.NodeAddress{ - {Type: v1.NodeInternalIP, Address: "127.0.0.1"}, - {Type: v1.NodeHostName, Address: testKubeletHostname}, - }, - // images will be sorted from max to min in node status. - Images: []v1.ContainerImage{ - { - Names: []string{"k8s.gcr.io:v1", "k8s.gcr.io:v2"}, - SizeBytes: 123, - }, - { - Names: []string{"k8s.gcr.io:v3", "k8s.gcr.io:v4"}, - SizeBytes: 456, - }, - }, - }, - } - - kubelet.updateRuntimeUp() - assert.NoError(t, kubelet.updateNodeStatus()) - - actions := kubeClient.Actions() - assert.Len(t, actions, 2) - - assert.IsType(t, core.PatchActionImpl{}, actions[1]) - patchAction := actions[1].(core.PatchActionImpl) - - updatedNode, err := applyNodeStatusPatch(&existingNode, patchAction.GetPatch()) - require.NoError(t, err) - - for i, cond := range updatedNode.Status.Conditions { - old := metav1.Date(2012, 1, 1, 0, 0, 0, 0, time.UTC).Time - // Expect LastHearbeat to be updated to Now, while LastTransitionTime to be the same. - assert.NotEqual(t, old, cond.LastHeartbeatTime.Rfc3339Copy().UTC(), "LastHeartbeatTime for condition %v", cond.Type) - assert.EqualValues(t, old, cond.LastTransitionTime.Rfc3339Copy().UTC(), "LastTransitionTime for condition %v", cond.Type) - - updatedNode.Status.Conditions[i].LastHeartbeatTime = metav1.Time{} - updatedNode.Status.Conditions[i].LastTransitionTime = metav1.Time{} - } - - // Version skew workaround. See: https://github.com/kubernetes/kubernetes/issues/16961 - assert.Equal(t, v1.NodeReady, updatedNode.Status.Conditions[len(updatedNode.Status.Conditions)-1].Type, - "NodeReady should be the last condition") - assert.True(t, apiequality.Semantic.DeepEqual(expectedNode, updatedNode), "%s", diff.ObjectDiff(expectedNode, updatedNode)) -} - -func TestUpdateExistingNodeStatusTimeout(t *testing.T) { - attempts := int64(0) - - // set up a listener that hangs connections - ln, err := net.Listen("tcp", "127.0.0.1:0") - assert.NoError(t, err) - defer ln.Close() - go func() { - // accept connections and just let them hang - for { - _, err := ln.Accept() - if err != nil { - t.Log(err) - return - } - t.Log("accepted connection") - atomic.AddInt64(&attempts, 1) - } - }() - - config := &rest.Config{ - Host: "http://" + ln.Addr().String(), - QPS: -1, - Timeout: time.Second, - } - assert.NoError(t, err) - - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubelet.kubeClient = nil // ensure only the heartbeat client is used - kubelet.heartbeatClient, err = v1core.NewForConfig(config) - kubelet.containerManager = &localCM{ - ContainerManager: cm.NewStubContainerManager(), - allocatableReservation: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(200, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(100E6, resource.BinarySI), - }, - capacity: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(20E9, resource.BinarySI), - }, - } - - // should return an error, but not hang - assert.Error(t, kubelet.updateNodeStatus()) - - // should have attempted multiple times - if actualAttempts := atomic.LoadInt64(&attempts); actualAttempts != nodeStatusUpdateRetry { - t.Errorf("Expected %d attempts, got %d", nodeStatusUpdateRetry, actualAttempts) - } -} - -func TestUpdateNodeStatusWithRuntimeStateError(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubelet.kubeClient = nil // ensure only the heartbeat client is used - kubelet.containerManager = &localCM{ - ContainerManager: cm.NewStubContainerManager(), - allocatableReservation: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(200, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(100E6, resource.BinarySI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(10E9, resource.BinarySI), - }, - capacity: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(20E9, resource.BinarySI), - }, - } - - clock := testKubelet.fakeClock - kubeClient := testKubelet.fakeKubeClient - existingNode := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}} - kubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{existingNode}}).ReactionChain - mockCadvisor := testKubelet.fakeCadvisor - mockCadvisor.On("Start").Return(nil) - machineInfo := &cadvisorapi.MachineInfo{ - MachineID: "123", - SystemUUID: "abc", - BootID: "1b3", - NumCores: 2, - MemoryCapacity: 10E9, - } - mockCadvisor.On("MachineInfo").Return(machineInfo, nil) - versionInfo := &cadvisorapi.VersionInfo{ - KernelVersion: "3.16.0-0.bpo.4-amd64", - ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", - } - - mockCadvisor.On("VersionInfo").Return(versionInfo, nil) - maxAge := 0 * time.Second - options := cadvisorapiv2.RequestOptions{IdType: cadvisorapiv2.TypeName, Count: 2, Recursive: false, MaxAge: &maxAge} - mockCadvisor.On("ContainerInfoV2", "/", options).Return(map[string]cadvisorapiv2.ContainerInfo{}, nil) - mockCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 400, - Capacity: 10E9, - }, nil) - mockCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 400, - Capacity: 20E9, - }, nil) - - kubelet.machineInfo = machineInfo - - expectedNode := &v1.Node{ - ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}, - Spec: v1.NodeSpec{}, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ - { - Type: v1.NodeOutOfDisk, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientDisk", - Message: fmt.Sprintf("kubelet has sufficient disk space available"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodeMemoryPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientMemory", - Message: fmt.Sprintf("kubelet has sufficient memory available"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodeDiskPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasNoDiskPressure", - Message: fmt.Sprintf("kubelet has no disk pressure"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - { - Type: v1.NodePIDPressure, - Status: v1.ConditionFalse, - Reason: "KubeletHasSufficientPID", - Message: fmt.Sprintf("kubelet has sufficient PID available"), - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - }, - {}, //placeholder - }, - NodeInfo: v1.NodeSystemInfo{ - MachineID: "123", - SystemUUID: "abc", - BootID: "1b3", - KernelVersion: "3.16.0-0.bpo.4-amd64", - OSImage: "Debian GNU/Linux 7 (wheezy)", - OperatingSystem: goruntime.GOOS, - Architecture: goruntime.GOARCH, - ContainerRuntimeVersion: "test://1.5.0", - KubeletVersion: version.Get().String(), - KubeProxyVersion: version.Get().String(), - }, - Capacity: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(20E9, resource.BinarySI), - }, - Allocatable: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(1800, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(9900E6, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(10E9, resource.BinarySI), - }, - Addresses: []v1.NodeAddress{ - {Type: v1.NodeInternalIP, Address: "127.0.0.1"}, - {Type: v1.NodeHostName, Address: testKubeletHostname}, - }, - Images: []v1.ContainerImage{ - { - Names: []string{"k8s.gcr.io:v1", "k8s.gcr.io:v2"}, - SizeBytes: 123, - }, - { - Names: []string{"k8s.gcr.io:v3", "k8s.gcr.io:v4"}, - SizeBytes: 456, - }, - }, - }, - } - - checkNodeStatus := func(status v1.ConditionStatus, reason string) { - kubeClient.ClearActions() - assert.NoError(t, kubelet.updateNodeStatus()) - actions := kubeClient.Actions() - require.Len(t, actions, 2) - require.True(t, actions[1].Matches("patch", "nodes")) - require.Equal(t, actions[1].GetSubresource(), "status") - - updatedNode, err := applyNodeStatusPatch(&existingNode, actions[1].(core.PatchActionImpl).GetPatch()) - require.NoError(t, err, "can't apply node status patch") - - for i, cond := range updatedNode.Status.Conditions { - assert.False(t, cond.LastHeartbeatTime.IsZero(), "LastHeartbeatTime for %v condition is zero", cond.Type) - assert.False(t, cond.LastTransitionTime.IsZero(), "LastTransitionTime for %v condition is zero", cond.Type) - updatedNode.Status.Conditions[i].LastHeartbeatTime = metav1.Time{} - updatedNode.Status.Conditions[i].LastTransitionTime = metav1.Time{} - } - - // Version skew workaround. See: https://github.com/kubernetes/kubernetes/issues/16961 - lastIndex := len(updatedNode.Status.Conditions) - 1 - - assert.Equal(t, v1.NodeReady, updatedNode.Status.Conditions[lastIndex].Type, "NodeReady should be the last condition") - assert.NotEmpty(t, updatedNode.Status.Conditions[lastIndex].Message) - - updatedNode.Status.Conditions[lastIndex].Message = "" - expectedNode.Status.Conditions[lastIndex] = v1.NodeCondition{ - Type: v1.NodeReady, - Status: status, - Reason: reason, - LastHeartbeatTime: metav1.Time{}, - LastTransitionTime: metav1.Time{}, - } - assert.True(t, apiequality.Semantic.DeepEqual(expectedNode, updatedNode), "%s", diff.ObjectDiff(expectedNode, updatedNode)) - } - - // TODO(random-liu): Refactor the unit test to be table driven test. - // Should report kubelet not ready if the runtime check is out of date - clock.SetTime(time.Now().Add(-maxWaitForContainerRuntime)) - kubelet.updateRuntimeUp() - checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") - - // Should report kubelet ready if the runtime check is updated - clock.SetTime(time.Now()) - kubelet.updateRuntimeUp() - checkNodeStatus(v1.ConditionTrue, "KubeletReady") - - // Should report kubelet not ready if the runtime check is out of date - clock.SetTime(time.Now().Add(-maxWaitForContainerRuntime)) - kubelet.updateRuntimeUp() - checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") - - // Should report kubelet not ready if the runtime check failed - fakeRuntime := testKubelet.fakeRuntime - // Inject error into fake runtime status check, node should be NotReady - fakeRuntime.StatusErr = fmt.Errorf("injected runtime status error") - clock.SetTime(time.Now()) - kubelet.updateRuntimeUp() - checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") - - fakeRuntime.StatusErr = nil - - // Should report node not ready if runtime status is nil. - fakeRuntime.RuntimeStatus = nil - kubelet.updateRuntimeUp() - checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") - - // Should report node not ready if runtime status is empty. - fakeRuntime.RuntimeStatus = &kubecontainer.RuntimeStatus{} - kubelet.updateRuntimeUp() - checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") - - // Should report node not ready if RuntimeReady is false. - fakeRuntime.RuntimeStatus = &kubecontainer.RuntimeStatus{ - Conditions: []kubecontainer.RuntimeCondition{ - {Type: kubecontainer.RuntimeReady, Status: false}, - {Type: kubecontainer.NetworkReady, Status: true}, - }, - } - kubelet.updateRuntimeUp() - checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") - - // Should report node ready if RuntimeReady is true. - fakeRuntime.RuntimeStatus = &kubecontainer.RuntimeStatus{ - Conditions: []kubecontainer.RuntimeCondition{ - {Type: kubecontainer.RuntimeReady, Status: true}, - {Type: kubecontainer.NetworkReady, Status: true}, - }, - } - kubelet.updateRuntimeUp() - checkNodeStatus(v1.ConditionTrue, "KubeletReady") - - // Should report node not ready if NetworkReady is false. - fakeRuntime.RuntimeStatus = &kubecontainer.RuntimeStatus{ - Conditions: []kubecontainer.RuntimeCondition{ - {Type: kubecontainer.RuntimeReady, Status: true}, - {Type: kubecontainer.NetworkReady, Status: false}, - }, - } - kubelet.updateRuntimeUp() - checkNodeStatus(v1.ConditionFalse, "KubeletNotReady") -} - -func TestUpdateNodeStatusError(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubelet.kubeClient = nil // ensure only the heartbeat client is used - // No matching node for the kubelet - testKubelet.fakeKubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{}}).ReactionChain - assert.Error(t, kubelet.updateNodeStatus()) - assert.Len(t, testKubelet.fakeKubeClient.Actions(), nodeStatusUpdateRetry) -} - -func TestRegisterWithApiServer(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubeClient := testKubelet.fakeKubeClient - kubeClient.AddReactor("create", "nodes", func(action core.Action) (bool, runtime.Object, error) { - // Return an error on create. - return true, &v1.Node{}, &apierrors.StatusError{ - ErrStatus: metav1.Status{Reason: metav1.StatusReasonAlreadyExists}, - } - }) - kubeClient.AddReactor("get", "nodes", func(action core.Action) (bool, runtime.Object, error) { - // Return an existing (matching) node on get. - return true, &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Name: testKubeletHostname, - Labels: map[string]string{ - kubeletapis.LabelHostname: testKubeletHostname, - kubeletapis.LabelOS: goruntime.GOOS, - kubeletapis.LabelArch: goruntime.GOARCH, - }, - }, - Spec: v1.NodeSpec{ExternalID: testKubeletHostname}, - }, nil - }) - kubeClient.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { - return true, nil, fmt.Errorf("no reaction implemented for %s", action) - }) - machineInfo := &cadvisorapi.MachineInfo{ - MachineID: "123", - SystemUUID: "abc", - BootID: "1b3", - NumCores: 2, - MemoryCapacity: 1024, - } - mockCadvisor := testKubelet.fakeCadvisor - mockCadvisor.On("MachineInfo").Return(machineInfo, nil) - versionInfo := &cadvisorapi.VersionInfo{ - KernelVersion: "3.16.0-0.bpo.4-amd64", - ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", - DockerVersion: "1.5.0", - } - mockCadvisor.On("VersionInfo").Return(versionInfo, nil) - mockCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 400, - Capacity: 1000, - Available: 600, - }, nil) - mockCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 9, - Capacity: 10, - }, nil) - kubelet.machineInfo = machineInfo - - done := make(chan struct{}) - go func() { - kubelet.registerWithAPIServer() - done <- struct{}{} - }() - select { - case <-time.After(wait.ForeverTestTimeout): - assert.Fail(t, "timed out waiting for registration") - case <-done: - return - } -} - -func TestTryRegisterWithApiServer(t *testing.T) { - alreadyExists := &apierrors.StatusError{ - ErrStatus: metav1.Status{Reason: metav1.StatusReasonAlreadyExists}, - } - - conflict := &apierrors.StatusError{ - ErrStatus: metav1.Status{Reason: metav1.StatusReasonConflict}, - } - - newNode := func(cmad bool, externalID string) *v1.Node { - node := &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - kubeletapis.LabelHostname: testKubeletHostname, - kubeletapis.LabelOS: goruntime.GOOS, - kubeletapis.LabelArch: goruntime.GOARCH, - }, - }, - Spec: v1.NodeSpec{ - ExternalID: externalID, - }, - } - - if cmad { - node.Annotations = make(map[string]string) - node.Annotations[util.ControllerManagedAttachAnnotation] = "true" - } - - return node - } - - cases := []struct { - name string - newNode *v1.Node - existingNode *v1.Node - createError error - getError error - patchError error - deleteError error - expectedResult bool - expectedActions int - testSavedNode bool - savedNodeIndex int - savedNodeCMAD bool - }{ - { - name: "success case - new node", - newNode: &v1.Node{}, - expectedResult: true, - expectedActions: 1, - }, - { - name: "success case - existing node - no change in CMAD", - newNode: newNode(true, "a"), - createError: alreadyExists, - existingNode: newNode(true, "a"), - expectedResult: true, - expectedActions: 2, - }, - { - name: "success case - existing node - CMAD disabled", - newNode: newNode(false, "a"), - createError: alreadyExists, - existingNode: newNode(true, "a"), - expectedResult: true, - expectedActions: 3, - testSavedNode: true, - savedNodeIndex: 2, - savedNodeCMAD: false, - }, - { - name: "success case - existing node - CMAD enabled", - newNode: newNode(true, "a"), - createError: alreadyExists, - existingNode: newNode(false, "a"), - expectedResult: true, - expectedActions: 3, - testSavedNode: true, - savedNodeIndex: 2, - savedNodeCMAD: true, - }, - { - name: "success case - external ID changed", - newNode: newNode(false, "b"), - createError: alreadyExists, - existingNode: newNode(false, "a"), - expectedResult: false, - expectedActions: 3, - }, - { - name: "create failed", - newNode: newNode(false, "b"), - createError: conflict, - expectedResult: false, - expectedActions: 1, - }, - { - name: "get existing node failed", - newNode: newNode(false, "a"), - createError: alreadyExists, - getError: conflict, - expectedResult: false, - expectedActions: 2, - }, - { - name: "update existing node failed", - newNode: newNode(false, "a"), - createError: alreadyExists, - existingNode: newNode(true, "a"), - patchError: conflict, - expectedResult: false, - expectedActions: 3, - }, - { - name: "delete existing node failed", - newNode: newNode(false, "b"), - createError: alreadyExists, - existingNode: newNode(false, "a"), - deleteError: conflict, - expectedResult: false, - expectedActions: 3, - }, - } - - notImplemented := func(action core.Action) (bool, runtime.Object, error) { - return true, nil, fmt.Errorf("no reaction implemented for %s", action) - } - - for _, tc := range cases { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled is a don't-care for this test */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubeClient := testKubelet.fakeKubeClient - - kubeClient.AddReactor("create", "nodes", func(action core.Action) (bool, runtime.Object, error) { - return true, nil, tc.createError - }) - kubeClient.AddReactor("get", "nodes", func(action core.Action) (bool, runtime.Object, error) { - // Return an existing (matching) node on get. - return true, tc.existingNode, tc.getError - }) - kubeClient.AddReactor("patch", "nodes", func(action core.Action) (bool, runtime.Object, error) { - if action.GetSubresource() == "status" { - return true, nil, tc.patchError - } - return notImplemented(action) - }) - kubeClient.AddReactor("delete", "nodes", func(action core.Action) (bool, runtime.Object, error) { - return true, nil, tc.deleteError - }) - kubeClient.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { - return notImplemented(action) - }) - - result := kubelet.tryRegisterWithAPIServer(tc.newNode) - require.Equal(t, tc.expectedResult, result, "test [%s]", tc.name) - - actions := kubeClient.Actions() - assert.Len(t, actions, tc.expectedActions, "test [%s]", tc.name) - - if tc.testSavedNode { - var savedNode *v1.Node - - t.Logf("actions: %v: %+v", len(actions), actions) - action := actions[tc.savedNodeIndex] - if action.GetVerb() == "create" { - createAction := action.(core.CreateAction) - obj := createAction.GetObject() - require.IsType(t, &v1.Node{}, obj) - savedNode = obj.(*v1.Node) - } else if action.GetVerb() == "patch" { - patchAction := action.(core.PatchActionImpl) - var err error - savedNode, err = applyNodeStatusPatch(tc.existingNode, patchAction.GetPatch()) - require.NoError(t, err) - } - - actualCMAD, _ := strconv.ParseBool(savedNode.Annotations[util.ControllerManagedAttachAnnotation]) - assert.Equal(t, tc.savedNodeCMAD, actualCMAD, "test [%s]", tc.name) - } - } -} - -func TestUpdateNewNodeStatusTooLargeReservation(t *testing.T) { - // generate one more than maxImagesInNodeStatus in inputImageList - inputImageList, _ := generateTestingImageList(maxImagesInNodeStatus + 1) - testKubelet := newTestKubeletWithImageList( - t, inputImageList, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubelet.kubeClient = nil // ensure only the heartbeat client is used - kubelet.containerManager = &localCM{ - ContainerManager: cm.NewStubContainerManager(), - allocatableReservation: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(40000, resource.DecimalSI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(1000, resource.BinarySI), - }, - capacity: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(3000, resource.BinarySI), - }, - } - kubeClient := testKubelet.fakeKubeClient - existingNode := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}} - kubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{existingNode}}).ReactionChain - machineInfo := &cadvisorapi.MachineInfo{ - MachineID: "123", - SystemUUID: "abc", - BootID: "1b3", - NumCores: 2, - MemoryCapacity: 10E9, // 10G - } - mockCadvisor := testKubelet.fakeCadvisor - mockCadvisor.On("Start").Return(nil) - mockCadvisor.On("MachineInfo").Return(machineInfo, nil) - versionInfo := &cadvisorapi.VersionInfo{ - KernelVersion: "3.16.0-0.bpo.4-amd64", - ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", - } - mockCadvisor.On("VersionInfo").Return(versionInfo, nil) - maxAge := 0 * time.Second - options := cadvisorapiv2.RequestOptions{IdType: cadvisorapiv2.TypeName, Count: 2, Recursive: false, MaxAge: &maxAge} - mockCadvisor.On("ContainerInfoV2", "/", options).Return(map[string]cadvisorapiv2.ContainerInfo{}, nil) - mockCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 400, - Capacity: 3000, - Available: 600, - }, nil) - mockCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 400, - Capacity: 3000, - Available: 600, - }, nil) - kubelet.machineInfo = machineInfo - - expectedNode := &v1.Node{ - ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}, - Spec: v1.NodeSpec{}, - Status: v1.NodeStatus{ - Capacity: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(2000, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(3000, resource.BinarySI), - }, - Allocatable: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(0, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(10E9, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(0, resource.DecimalSI), - v1.ResourceEphemeralStorage: *resource.NewQuantity(2000, resource.BinarySI), - }, - }, - } - - kubelet.updateRuntimeUp() - assert.NoError(t, kubelet.updateNodeStatus()) - actions := kubeClient.Actions() - require.Len(t, actions, 2) - require.True(t, actions[1].Matches("patch", "nodes")) - require.Equal(t, actions[1].GetSubresource(), "status") - - updatedNode, err := applyNodeStatusPatch(&existingNode, actions[1].(core.PatchActionImpl).GetPatch()) - assert.NoError(t, err) - assert.True(t, apiequality.Semantic.DeepEqual(expectedNode.Status.Allocatable, updatedNode.Status.Allocatable), "%s", diff.ObjectDiff(expectedNode.Status.Allocatable, updatedNode.Status.Allocatable)) -} - -func TestUpdateDefaultLabels(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - testKubelet.kubelet.kubeClient = nil // ensure only the heartbeat client is used - - cases := []struct { - name string - initialNode *v1.Node - existingNode *v1.Node - needsUpdate bool - finalLabels map[string]string - }{ - { - name: "make sure default labels exist", - initialNode: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - }, - }, - }, - existingNode: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{}, - }, - }, - needsUpdate: true, - finalLabels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - }, - }, - { - name: "make sure default labels are up to date", - initialNode: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - }, - }, - }, - existingNode: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - kubeletapis.LabelHostname: "old-hostname", - kubeletapis.LabelZoneFailureDomain: "old-zone-failure-domain", - kubeletapis.LabelZoneRegion: "old-zone-region", - kubeletapis.LabelInstanceType: "old-instance-type", - kubeletapis.LabelOS: "old-os", - kubeletapis.LabelArch: "old-arch", - }, - }, - }, - needsUpdate: true, - finalLabels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - }, - }, - { - name: "make sure existing labels do not get deleted", - initialNode: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - }, - }, - }, - existingNode: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - "please-persist": "foo", - }, - }, - }, - needsUpdate: false, - finalLabels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - "please-persist": "foo", - }, - }, - { - name: "make sure existing labels do not get deleted when initial node has no opinion", - initialNode: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{}, - }, - }, - existingNode: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - "please-persist": "foo", - }, - }, - }, - needsUpdate: false, - finalLabels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - "please-persist": "foo", - }, - }, - { - name: "no update needed", - initialNode: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - }, - }, - }, - existingNode: &v1.Node{ - ObjectMeta: metav1.ObjectMeta{ - Labels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - }, - }, - }, - needsUpdate: false, - finalLabels: map[string]string{ - kubeletapis.LabelHostname: "new-hostname", - kubeletapis.LabelZoneFailureDomain: "new-zone-failure-domain", - kubeletapis.LabelZoneRegion: "new-zone-region", - kubeletapis.LabelInstanceType: "new-instance-type", - kubeletapis.LabelOS: "new-os", - kubeletapis.LabelArch: "new-arch", - }, - }, - } - - for _, tc := range cases { - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - - needsUpdate := kubelet.updateDefaultLabels(tc.initialNode, tc.existingNode) - assert.Equal(t, tc.needsUpdate, needsUpdate, tc.name) - assert.Equal(t, tc.finalLabels, tc.existingNode.Labels, tc.name) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods.go index 1b96da8169..287f9ec05a 100644 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods.go +++ b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods.go @@ -110,23 +110,6 @@ func (kl *Kubelet) makeGPUDevices(pod *v1.Pod, container *v1.Container) ([]kubec return devices, nil } -func makeAbsolutePath(goos, path string) string { - if goos != "windows" { - return "/" + path - } - // These are all for windows - // If there is a colon, give up. - if strings.Contains(path, ":") { - return path - } - // If there is a slash, but no drive, add 'c:' - if strings.HasPrefix(path, "/") || strings.HasPrefix(path, "\\") { - return "c:" + path - } - // Otherwise, add 'c:\' - return "c:\\" + path -} - // makeBlockVolumes maps the raw block devices specified in the path of the container // Experimental func (kl *Kubelet) makeBlockVolumes(pod *v1.Pod, container *v1.Container, podVolumes kubecontainer.VolumeMap, blkutil volumepathhandler.BlockVolumePathHandler) ([]kubecontainer.DeviceInfo, error) { @@ -239,6 +222,7 @@ func makeMounts(pod *v1.Pod, podDir string, container *v1.Container, hostName, h VolumePath: volumePath, PodDir: podDir, ContainerName: container.Name, + ReadOnly: mount.ReadOnly || vol.Mounter.GetAttributes().ReadOnly, }) if err != nil { // Don't pass detailed error back to the user because it could give information about host filesystem @@ -255,7 +239,7 @@ func makeMounts(pod *v1.Pod, podDir string, container *v1.Container, hostName, h } } if !filepath.IsAbs(containerPath) { - containerPath = makeAbsolutePath(runtime.GOOS, containerPath) + containerPath = volumeutil.MakeAbsolutePath(runtime.GOOS, containerPath) } propagation, err := translateMountPropagation(mount.MountPropagation) @@ -301,12 +285,14 @@ func translateMountPropagation(mountMode *v1.MountPropagationMode) (runtimeapi.M } switch { case mountMode == nil: - // HostToContainer is the default - return runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER, nil + // PRIVATE is the default + return runtimeapi.MountPropagation_PROPAGATION_PRIVATE, nil case *mountMode == v1.MountPropagationHostToContainer: return runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER, nil case *mountMode == v1.MountPropagationBidirectional: return runtimeapi.MountPropagation_PROPAGATION_BIDIRECTIONAL, nil + case *mountMode == v1.MountPropagationNone: + return runtimeapi.MountPropagation_PROPAGATION_PRIVATE, nil default: return 0, fmt.Errorf("invalid MountPropagation mode: %q", mountMode) } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods_test.go deleted file mode 100644 index 92552f5227..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods_test.go +++ /dev/null @@ -1,2551 +0,0 @@ -/* -Copyright 2016 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 kubelet - -import ( - "bytes" - "errors" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "sort" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - utilfeature "k8s.io/apiserver/pkg/util/feature" - core "k8s.io/client-go/testing" - "k8s.io/client-go/tools/record" - // TODO: remove this import if - // api.Registry.GroupOrDie(v1.GroupName).GroupVersion.String() is changed - // to "v1"? - "k8s.io/kubernetes/pkg/api/legacyscheme" - _ "k8s.io/kubernetes/pkg/apis/core/install" - runtimeapi "k8s.io/kubernetes/pkg/kubelet/apis/cri/runtime/v1alpha2" - kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" - containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" - "k8s.io/kubernetes/pkg/kubelet/server/portforward" - "k8s.io/kubernetes/pkg/kubelet/server/remotecommand" - "k8s.io/kubernetes/pkg/util/mount" - volumetest "k8s.io/kubernetes/pkg/volume/testing" -) - -func TestMakeAbsolutePath(t *testing.T) { - tests := []struct { - goos string - path string - expectedPath string - name string - }{ - { - goos: "linux", - path: "non-absolute/path", - expectedPath: "/non-absolute/path", - name: "basic linux", - }, - { - goos: "windows", - path: "some\\path", - expectedPath: "c:\\some\\path", - name: "basic windows", - }, - { - goos: "windows", - path: "/some/path", - expectedPath: "c:/some/path", - name: "linux path on windows", - }, - { - goos: "windows", - path: "\\some\\path", - expectedPath: "c:\\some\\path", - name: "windows path no drive", - }, - { - goos: "windows", - path: "\\:\\some\\path", - expectedPath: "\\:\\some\\path", - name: "windows path with colon", - }, - } - for _, test := range tests { - path := makeAbsolutePath(test.goos, test.path) - if path != test.expectedPath { - t.Errorf("[%s] Expected %s saw %s", test.name, test.expectedPath, path) - } - } -} - -func TestMakeMounts(t *testing.T) { - bTrue := true - propagationHostToContainer := v1.MountPropagationHostToContainer - propagationBidirectional := v1.MountPropagationBidirectional - - testCases := map[string]struct { - container v1.Container - podVolumes kubecontainer.VolumeMap - expectErr bool - expectedErrMsg string - expectedMounts []kubecontainer.Mount - }{ - "valid mounts in unprivileged container": { - podVolumes: kubecontainer.VolumeMap{ - "disk": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/mnt/disk"}}, - "disk4": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/mnt/host"}}, - "disk5": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/var/lib/kubelet/podID/volumes/empty/disk5"}}, - }, - container: v1.Container{ - Name: "container1", - VolumeMounts: []v1.VolumeMount{ - { - MountPath: "/etc/hosts", - Name: "disk", - ReadOnly: false, - MountPropagation: &propagationHostToContainer, - }, - { - MountPath: "/mnt/path3", - Name: "disk", - ReadOnly: true, - }, - { - MountPath: "/mnt/path4", - Name: "disk4", - ReadOnly: false, - }, - { - MountPath: "/mnt/path5", - Name: "disk5", - ReadOnly: false, - }, - }, - }, - expectedMounts: []kubecontainer.Mount{ - { - Name: "disk", - ContainerPath: "/etc/hosts", - HostPath: "/mnt/disk", - ReadOnly: false, - SELinuxRelabel: false, - Propagation: runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER, - }, - { - Name: "disk", - ContainerPath: "/mnt/path3", - HostPath: "/mnt/disk", - ReadOnly: true, - SELinuxRelabel: false, - Propagation: runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER, - }, - { - Name: "disk4", - ContainerPath: "/mnt/path4", - HostPath: "/mnt/host", - ReadOnly: false, - SELinuxRelabel: false, - Propagation: runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER, - }, - { - Name: "disk5", - ContainerPath: "/mnt/path5", - HostPath: "/var/lib/kubelet/podID/volumes/empty/disk5", - ReadOnly: false, - SELinuxRelabel: false, - Propagation: runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER, - }, - }, - expectErr: false, - }, - "valid mounts in privileged container": { - podVolumes: kubecontainer.VolumeMap{ - "disk": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/mnt/disk"}}, - "disk4": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/mnt/host"}}, - "disk5": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/var/lib/kubelet/podID/volumes/empty/disk5"}}, - }, - container: v1.Container{ - Name: "container1", - VolumeMounts: []v1.VolumeMount{ - { - MountPath: "/etc/hosts", - Name: "disk", - ReadOnly: false, - MountPropagation: &propagationBidirectional, - }, - { - MountPath: "/mnt/path3", - Name: "disk", - ReadOnly: true, - MountPropagation: &propagationHostToContainer, - }, - { - MountPath: "/mnt/path4", - Name: "disk4", - ReadOnly: false, - }, - }, - SecurityContext: &v1.SecurityContext{ - Privileged: &bTrue, - }, - }, - expectedMounts: []kubecontainer.Mount{ - { - Name: "disk", - ContainerPath: "/etc/hosts", - HostPath: "/mnt/disk", - ReadOnly: false, - SELinuxRelabel: false, - Propagation: runtimeapi.MountPropagation_PROPAGATION_BIDIRECTIONAL, - }, - { - Name: "disk", - ContainerPath: "/mnt/path3", - HostPath: "/mnt/disk", - ReadOnly: true, - SELinuxRelabel: false, - Propagation: runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER, - }, - { - Name: "disk4", - ContainerPath: "/mnt/path4", - HostPath: "/mnt/host", - ReadOnly: false, - SELinuxRelabel: false, - Propagation: runtimeapi.MountPropagation_PROPAGATION_HOST_TO_CONTAINER, - }, - }, - expectErr: false, - }, - "invalid absolute SubPath": { - podVolumes: kubecontainer.VolumeMap{ - "disk": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/mnt/disk"}}, - }, - container: v1.Container{ - VolumeMounts: []v1.VolumeMount{ - { - MountPath: "/mnt/path3", - SubPath: "/must/not/be/absolute", - Name: "disk", - ReadOnly: true, - }, - }, - }, - expectErr: true, - expectedErrMsg: "error SubPath `/must/not/be/absolute` must not be an absolute path", - }, - "invalid SubPath with backsteps": { - podVolumes: kubecontainer.VolumeMap{ - "disk": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/mnt/disk"}}, - }, - container: v1.Container{ - VolumeMounts: []v1.VolumeMount{ - { - MountPath: "/mnt/path3", - SubPath: "no/backsteps/../allowed", - Name: "disk", - ReadOnly: true, - }, - }, - }, - expectErr: true, - expectedErrMsg: "unable to provision SubPath `no/backsteps/../allowed`: must not contain '..'", - }, - "volume doesn't exist": { - podVolumes: kubecontainer.VolumeMap{}, - container: v1.Container{ - VolumeMounts: []v1.VolumeMount{ - { - MountPath: "/mnt/path3", - Name: "disk", - ReadOnly: true, - }, - }, - }, - expectErr: true, - expectedErrMsg: "cannot find volume \"disk\" to mount into container \"\"", - }, - "volume mounter is nil": { - podVolumes: kubecontainer.VolumeMap{ - "disk": kubecontainer.VolumeInfo{}, - }, - container: v1.Container{ - VolumeMounts: []v1.VolumeMount{ - { - MountPath: "/mnt/path3", - Name: "disk", - ReadOnly: true, - }, - }, - }, - expectErr: true, - expectedErrMsg: "cannot find volume \"disk\" to mount into container \"\"", - }, - } - - for name, tc := range testCases { - t.Run(name, func(t *testing.T) { - fm := &mount.FakeMounter{} - pod := v1.Pod{ - Spec: v1.PodSpec{ - HostNetwork: true, - }, - } - // test makeMounts with enabled mount propagation - err := utilfeature.DefaultFeatureGate.Set("MountPropagation=true") - if err != nil { - t.Errorf("Failed to enable feature gate for MountPropagation: %v", err) - return - } - - mounts, _, err := makeMounts(&pod, "/pod", &tc.container, "fakepodname", "", "", tc.podVolumes, fm) - - // validate only the error if we expect an error - if tc.expectErr { - if err == nil || err.Error() != tc.expectedErrMsg { - t.Fatalf("expected error message `%s` but got `%v`", tc.expectedErrMsg, err) - } - return - } - - // otherwise validate the mounts - if err != nil { - t.Fatal(err) - } - - assert.Equal(t, tc.expectedMounts, mounts, "mounts of container %+v", tc.container) - - // test makeMounts with disabled mount propagation - err = utilfeature.DefaultFeatureGate.Set("MountPropagation=false") - if err != nil { - t.Errorf("Failed to enable feature gate for MountPropagation: %v", err) - return - } - mounts, _, err = makeMounts(&pod, "/pod", &tc.container, "fakepodname", "", "", tc.podVolumes, fm) - if !tc.expectErr { - expectedPrivateMounts := []kubecontainer.Mount{} - for _, mount := range tc.expectedMounts { - // all mounts are expected to be private when mount - // propagation is disabled - mount.Propagation = runtimeapi.MountPropagation_PROPAGATION_PRIVATE - expectedPrivateMounts = append(expectedPrivateMounts, mount) - } - assert.Equal(t, expectedPrivateMounts, mounts, "mounts of container %+v", tc.container) - } - }) - } -} - -func TestDisabledSubpath(t *testing.T) { - fm := &mount.FakeMounter{} - pod := v1.Pod{ - Spec: v1.PodSpec{ - HostNetwork: true, - }, - } - podVolumes := kubecontainer.VolumeMap{ - "disk": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "/mnt/disk"}}, - } - - cases := map[string]struct { - container v1.Container - expectError bool - }{ - "subpath not specified": { - v1.Container{ - VolumeMounts: []v1.VolumeMount{ - { - MountPath: "/mnt/path3", - Name: "disk", - ReadOnly: true, - }, - }, - }, - false, - }, - "subpath specified": { - v1.Container{ - VolumeMounts: []v1.VolumeMount{ - { - MountPath: "/mnt/path3", - SubPath: "/must/not/be/absolute", - Name: "disk", - ReadOnly: true, - }, - }, - }, - true, - }, - } - - utilfeature.DefaultFeatureGate.Set("VolumeSubpath=false") - defer utilfeature.DefaultFeatureGate.Set("VolumeSubpath=true") - - for name, test := range cases { - _, _, err := makeMounts(&pod, "/pod", &test.container, "fakepodname", "", "", podVolumes, fm) - if err != nil && !test.expectError { - t.Errorf("test %v failed: %v", name, err) - } - if err == nil && test.expectError { - t.Errorf("test %v failed: expected error", name) - } - } -} - -func TestMakeBlockVolumes(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - testCases := map[string]struct { - container v1.Container - podVolumes kubecontainer.VolumeMap - expectErr bool - expectedErrMsg string - expectedDevices []kubecontainer.DeviceInfo - }{ - "valid volumeDevices in container": { - podVolumes: kubecontainer.VolumeMap{ - "disk1": kubecontainer.VolumeInfo{BlockVolumeMapper: &stubBlockVolume{dirPath: "/dev/", volName: "sda"}}, - "disk2": kubecontainer.VolumeInfo{BlockVolumeMapper: &stubBlockVolume{dirPath: "/dev/disk/by-path/", volName: "diskPath"}, ReadOnly: true}, - "disk3": kubecontainer.VolumeInfo{BlockVolumeMapper: &stubBlockVolume{dirPath: "/dev/disk/by-id/", volName: "diskUuid"}}, - "disk4": kubecontainer.VolumeInfo{BlockVolumeMapper: &stubBlockVolume{dirPath: "/var/lib/", volName: "rawdisk"}, ReadOnly: true}, - }, - container: v1.Container{ - Name: "container1", - VolumeDevices: []v1.VolumeDevice{ - { - DevicePath: "/dev/sda", - Name: "disk1", - }, - { - DevicePath: "/dev/xvda", - Name: "disk2", - }, - { - DevicePath: "/dev/xvdb", - Name: "disk3", - }, - { - DevicePath: "/mnt/rawdisk", - Name: "disk4", - }, - }, - }, - expectedDevices: []kubecontainer.DeviceInfo{ - { - PathInContainer: "/dev/sda", - PathOnHost: "/dev/sda", - Permissions: "mrw", - }, - { - PathInContainer: "/dev/xvda", - PathOnHost: "/dev/disk/by-path/diskPath", - Permissions: "r", - }, - { - PathInContainer: "/dev/xvdb", - PathOnHost: "/dev/disk/by-id/diskUuid", - Permissions: "mrw", - }, - { - PathInContainer: "/mnt/rawdisk", - PathOnHost: "/var/lib/rawdisk", - Permissions: "r", - }, - }, - expectErr: false, - }, - "invalid absolute Path": { - podVolumes: kubecontainer.VolumeMap{ - "disk": kubecontainer.VolumeInfo{BlockVolumeMapper: &stubBlockVolume{dirPath: "/dev/", volName: "sda"}}, - }, - container: v1.Container{ - VolumeDevices: []v1.VolumeDevice{ - { - DevicePath: "must/be/absolute", - Name: "disk", - }, - }, - }, - expectErr: true, - expectedErrMsg: "error DevicePath `must/be/absolute` must be an absolute path", - }, - "volume doesn't exist": { - podVolumes: kubecontainer.VolumeMap{}, - container: v1.Container{ - VolumeDevices: []v1.VolumeDevice{ - { - DevicePath: "/dev/sdaa", - Name: "disk", - }, - }, - }, - expectErr: true, - expectedErrMsg: "cannot find volume \"disk\" to pass into container \"\"", - }, - "volume BlockVolumeMapper is nil": { - podVolumes: kubecontainer.VolumeMap{ - "disk": kubecontainer.VolumeInfo{}, - }, - container: v1.Container{ - VolumeDevices: []v1.VolumeDevice{ - { - DevicePath: "/dev/sdzz", - Name: "disk", - }, - }, - }, - expectErr: true, - expectedErrMsg: "cannot find volume \"disk\" to pass into container \"\"", - }, - } - - for name, tc := range testCases { - t.Run(name, func(t *testing.T) { - pod := v1.Pod{ - Spec: v1.PodSpec{ - HostNetwork: true, - }, - } - blkutil := volumetest.NewBlockVolumePathHandler() - blkVolumes, err := kubelet.makeBlockVolumes(&pod, &tc.container, tc.podVolumes, blkutil) - // validate only the error if we expect an error - if tc.expectErr { - if err == nil || err.Error() != tc.expectedErrMsg { - t.Fatalf("expected error message `%s` but got `%v`", tc.expectedErrMsg, err) - } - return - } - // otherwise validate the devices - if err != nil { - t.Fatal(err) - } - assert.Equal(t, tc.expectedDevices, blkVolumes, "devices of container %+v", tc.container) - }) - } -} - -func TestNodeHostsFileContent(t *testing.T) { - testCases := []struct { - hostsFileName string - hostAliases []v1.HostAlias - rawHostsFileContent string - expectedHostsFileContent string - }{ - { - "hosts_test_file1", - []v1.HostAlias{}, - `# hosts file for testing. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -123.45.67.89 some.domain -`, - `# hosts file for testing. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -123.45.67.89 some.domain -`, - }, - { - "hosts_test_file2", - []v1.HostAlias{}, - `# another hosts file for testing. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -12.34.56.78 another.domain -`, - `# another hosts file for testing. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -12.34.56.78 another.domain -`, - }, - { - "hosts_test_file1_with_host_aliases", - []v1.HostAlias{ - {IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}}, - }, - `# hosts file for testing. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -123.45.67.89 some.domain -`, - `# hosts file for testing. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -123.45.67.89 some.domain - -# Entries added by HostAliases. -123.45.67.89 foo -123.45.67.89 bar -123.45.67.89 baz -`, - }, - { - "hosts_test_file2_with_host_aliases", - []v1.HostAlias{ - {IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}}, - {IP: "456.78.90.123", Hostnames: []string{"park", "doo", "boo"}}, - }, - `# another hosts file for testing. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -12.34.56.78 another.domain -`, - `# another hosts file for testing. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -12.34.56.78 another.domain - -# Entries added by HostAliases. -123.45.67.89 foo -123.45.67.89 bar -123.45.67.89 baz -456.78.90.123 park -456.78.90.123 doo -456.78.90.123 boo -`, - }, - } - - for _, testCase := range testCases { - tmpdir, err := writeHostsFile(testCase.hostsFileName, testCase.rawHostsFileContent) - require.NoError(t, err, "could not create a temp hosts file") - defer os.RemoveAll(tmpdir) - - actualContent, fileReadErr := nodeHostsFileContent(filepath.Join(tmpdir, testCase.hostsFileName), testCase.hostAliases) - require.NoError(t, fileReadErr, "could not create read hosts file") - assert.Equal(t, testCase.expectedHostsFileContent, string(actualContent), "hosts file content not expected") - } -} - -// writeHostsFile will write a hosts file into a temporary dir, and return that dir. -// Caller is responsible for deleting the dir and its contents. -func writeHostsFile(filename string, cfg string) (string, error) { - tmpdir, err := ioutil.TempDir("", "kubelet=kubelet_pods_test.go=") - if err != nil { - return "", err - } - return tmpdir, ioutil.WriteFile(filepath.Join(tmpdir, filename), []byte(cfg), 0644) -} - -func TestManagedHostsFileContent(t *testing.T) { - testCases := []struct { - hostIP string - hostName string - hostDomainName string - hostAliases []v1.HostAlias - expectedContent string - }{ - { - "123.45.67.89", - "podFoo", - "", - []v1.HostAlias{}, - `# Kubernetes-managed hosts file. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -123.45.67.89 podFoo -`, - }, - { - "203.0.113.1", - "podFoo", - "domainFoo", - []v1.HostAlias{}, - `# Kubernetes-managed hosts file. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -203.0.113.1 podFoo.domainFoo podFoo -`, - }, - { - "203.0.113.1", - "podFoo", - "domainFoo", - []v1.HostAlias{ - {IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}}, - }, - `# Kubernetes-managed hosts file. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -203.0.113.1 podFoo.domainFoo podFoo - -# Entries added by HostAliases. -123.45.67.89 foo -123.45.67.89 bar -123.45.67.89 baz -`, - }, - { - "203.0.113.1", - "podFoo", - "domainFoo", - []v1.HostAlias{ - {IP: "123.45.67.89", Hostnames: []string{"foo", "bar", "baz"}}, - {IP: "456.78.90.123", Hostnames: []string{"park", "doo", "boo"}}, - }, - `# Kubernetes-managed hosts file. -127.0.0.1 localhost -::1 localhost ip6-localhost ip6-loopback -fe00::0 ip6-localnet -fe00::0 ip6-mcastprefix -fe00::1 ip6-allnodes -fe00::2 ip6-allrouters -203.0.113.1 podFoo.domainFoo podFoo - -# Entries added by HostAliases. -123.45.67.89 foo -123.45.67.89 bar -123.45.67.89 baz -456.78.90.123 park -456.78.90.123 doo -456.78.90.123 boo -`, - }, - } - - for _, testCase := range testCases { - actualContent := managedHostsFileContent(testCase.hostIP, testCase.hostName, testCase.hostDomainName, testCase.hostAliases) - assert.Equal(t, testCase.expectedContent, string(actualContent), "hosts file content not expected") - } -} - -func TestRunInContainerNoSuchPod(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - fakeRuntime := testKubelet.fakeRuntime - fakeRuntime.PodList = []*containertest.FakePod{} - - podName := "podFoo" - podNamespace := "nsFoo" - containerName := "containerFoo" - output, err := kubelet.RunInContainer( - kubecontainer.GetPodFullName(&v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: podName, Namespace: podNamespace}}), - "", - containerName, - []string{"ls"}) - assert.Error(t, err) - assert.Nil(t, output, "output should be nil") -} - -func TestRunInContainer(t *testing.T) { - for _, testError := range []error{nil, errors.New("bar")} { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - fakeRuntime := testKubelet.fakeRuntime - fakeCommandRunner := containertest.FakeContainerCommandRunner{ - Err: testError, - Stdout: "foo", - } - kubelet.runner = &fakeCommandRunner - - containerID := kubecontainer.ContainerID{Type: "test", ID: "abc1234"} - fakeRuntime.PodList = []*containertest.FakePod{ - {Pod: &kubecontainer.Pod{ - ID: "12345678", - Name: "podFoo", - Namespace: "nsFoo", - Containers: []*kubecontainer.Container{ - {Name: "containerFoo", - ID: containerID, - }, - }, - }}, - } - cmd := []string{"ls"} - actualOutput, err := kubelet.RunInContainer("podFoo_nsFoo", "", "containerFoo", cmd) - assert.Equal(t, containerID, fakeCommandRunner.ContainerID, "(testError=%v) ID", testError) - assert.Equal(t, cmd, fakeCommandRunner.Cmd, "(testError=%v) command", testError) - // this isn't 100% foolproof as a bug in a real ContainerCommandRunner where it fails to copy to stdout/stderr wouldn't be caught by this test - assert.Equal(t, "foo", string(actualOutput), "(testError=%v) output", testError) - assert.Equal(t, err, testError, "(testError=%v) err", testError) - } -} - -type testServiceLister struct { - services []*v1.Service -} - -func (ls testServiceLister) List(labels.Selector) ([]*v1.Service, error) { - return ls.services, nil -} - -type envs []kubecontainer.EnvVar - -func (e envs) Len() int { - return len(e) -} - -func (e envs) Swap(i, j int) { e[i], e[j] = e[j], e[i] } - -func (e envs) Less(i, j int) bool { return e[i].Name < e[j].Name } - -func buildService(name, namespace, clusterIP, protocol string, port int) *v1.Service { - return &v1.Service{ - ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, - Spec: v1.ServiceSpec{ - Ports: []v1.ServicePort{{ - Protocol: v1.Protocol(protocol), - Port: int32(port), - }}, - ClusterIP: clusterIP, - }, - } -} - -func TestMakeEnvironmentVariables(t *testing.T) { - trueVal := true - services := []*v1.Service{ - buildService("kubernetes", metav1.NamespaceDefault, "1.2.3.1", "TCP", 8081), - buildService("test", "test1", "1.2.3.3", "TCP", 8083), - buildService("kubernetes", "test2", "1.2.3.4", "TCP", 8084), - buildService("test", "test2", "1.2.3.5", "TCP", 8085), - buildService("test", "test2", "None", "TCP", 8085), - buildService("test", "test2", "", "TCP", 8085), - buildService("kubernetes", "kubernetes", "1.2.3.6", "TCP", 8086), - buildService("not-special", "kubernetes", "1.2.3.8", "TCP", 8088), - buildService("not-special", "kubernetes", "None", "TCP", 8088), - buildService("not-special", "kubernetes", "", "TCP", 8088), - } - - testCases := []struct { - name string // the name of the test case - ns string // the namespace to generate environment for - container *v1.Container // the container to use - masterServiceNs string // the namespace to read master service info from - nilLister bool // whether the lister should be nil - configMap *v1.ConfigMap // an optional ConfigMap to pull from - secret *v1.Secret // an optional Secret to pull from - expectedEnvs []kubecontainer.EnvVar // a set of expected environment vars - expectedError bool // does the test fail - expectedEvent string // does the test emit an event - }{ - { - name: "api server = Y, kubelet = Y", - ns: "test1", - container: &v1.Container{ - Env: []v1.EnvVar{ - {Name: "FOO", Value: "BAR"}, - {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, - {Name: "TEST_SERVICE_PORT", Value: "8083"}, - {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, - {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, - {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, - {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, - {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, - }, - }, - masterServiceNs: metav1.NamespaceDefault, - nilLister: false, - expectedEnvs: []kubecontainer.EnvVar{ - {Name: "FOO", Value: "BAR"}, - {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, - {Name: "TEST_SERVICE_PORT", Value: "8083"}, - {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, - {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, - {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, - {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, - {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, - {Name: "KUBERNETES_SERVICE_PORT", Value: "8081"}, - {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"}, - {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"}, - {Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"}, - {Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"}, - {Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"}, - {Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"}, - }, - }, - { - name: "api server = Y, kubelet = N", - ns: "test1", - container: &v1.Container{ - Env: []v1.EnvVar{ - {Name: "FOO", Value: "BAR"}, - {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, - {Name: "TEST_SERVICE_PORT", Value: "8083"}, - {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, - {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, - {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, - {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, - {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, - }, - }, - masterServiceNs: metav1.NamespaceDefault, - nilLister: true, - expectedEnvs: []kubecontainer.EnvVar{ - {Name: "FOO", Value: "BAR"}, - {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, - {Name: "TEST_SERVICE_PORT", Value: "8083"}, - {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, - {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, - {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, - {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, - {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, - }, - }, - { - name: "api server = N; kubelet = Y", - ns: "test1", - container: &v1.Container{ - Env: []v1.EnvVar{ - {Name: "FOO", Value: "BAZ"}, - }, - }, - masterServiceNs: metav1.NamespaceDefault, - nilLister: false, - expectedEnvs: []kubecontainer.EnvVar{ - {Name: "FOO", Value: "BAZ"}, - {Name: "TEST_SERVICE_HOST", Value: "1.2.3.3"}, - {Name: "TEST_SERVICE_PORT", Value: "8083"}, - {Name: "TEST_PORT", Value: "tcp://1.2.3.3:8083"}, - {Name: "TEST_PORT_8083_TCP", Value: "tcp://1.2.3.3:8083"}, - {Name: "TEST_PORT_8083_TCP_PROTO", Value: "tcp"}, - {Name: "TEST_PORT_8083_TCP_PORT", Value: "8083"}, - {Name: "TEST_PORT_8083_TCP_ADDR", Value: "1.2.3.3"}, - {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.1"}, - {Name: "KUBERNETES_SERVICE_PORT", Value: "8081"}, - {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.1:8081"}, - {Name: "KUBERNETES_PORT_8081_TCP", Value: "tcp://1.2.3.1:8081"}, - {Name: "KUBERNETES_PORT_8081_TCP_PROTO", Value: "tcp"}, - {Name: "KUBERNETES_PORT_8081_TCP_PORT", Value: "8081"}, - {Name: "KUBERNETES_PORT_8081_TCP_ADDR", Value: "1.2.3.1"}, - }, - }, - { - name: "master service in pod ns", - ns: "test2", - container: &v1.Container{ - Env: []v1.EnvVar{ - {Name: "FOO", Value: "ZAP"}, - }, - }, - masterServiceNs: "kubernetes", - nilLister: false, - expectedEnvs: []kubecontainer.EnvVar{ - {Name: "FOO", Value: "ZAP"}, - {Name: "TEST_SERVICE_HOST", Value: "1.2.3.5"}, - {Name: "TEST_SERVICE_PORT", Value: "8085"}, - {Name: "TEST_PORT", Value: "tcp://1.2.3.5:8085"}, - {Name: "TEST_PORT_8085_TCP", Value: "tcp://1.2.3.5:8085"}, - {Name: "TEST_PORT_8085_TCP_PROTO", Value: "tcp"}, - {Name: "TEST_PORT_8085_TCP_PORT", Value: "8085"}, - {Name: "TEST_PORT_8085_TCP_ADDR", Value: "1.2.3.5"}, - {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.4"}, - {Name: "KUBERNETES_SERVICE_PORT", Value: "8084"}, - {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.4:8084"}, - {Name: "KUBERNETES_PORT_8084_TCP", Value: "tcp://1.2.3.4:8084"}, - {Name: "KUBERNETES_PORT_8084_TCP_PROTO", Value: "tcp"}, - {Name: "KUBERNETES_PORT_8084_TCP_PORT", Value: "8084"}, - {Name: "KUBERNETES_PORT_8084_TCP_ADDR", Value: "1.2.3.4"}, - }, - }, - { - name: "pod in master service ns", - ns: "kubernetes", - container: &v1.Container{}, - masterServiceNs: "kubernetes", - nilLister: false, - expectedEnvs: []kubecontainer.EnvVar{ - {Name: "NOT_SPECIAL_SERVICE_HOST", Value: "1.2.3.8"}, - {Name: "NOT_SPECIAL_SERVICE_PORT", Value: "8088"}, - {Name: "NOT_SPECIAL_PORT", Value: "tcp://1.2.3.8:8088"}, - {Name: "NOT_SPECIAL_PORT_8088_TCP", Value: "tcp://1.2.3.8:8088"}, - {Name: "NOT_SPECIAL_PORT_8088_TCP_PROTO", Value: "tcp"}, - {Name: "NOT_SPECIAL_PORT_8088_TCP_PORT", Value: "8088"}, - {Name: "NOT_SPECIAL_PORT_8088_TCP_ADDR", Value: "1.2.3.8"}, - {Name: "KUBERNETES_SERVICE_HOST", Value: "1.2.3.6"}, - {Name: "KUBERNETES_SERVICE_PORT", Value: "8086"}, - {Name: "KUBERNETES_PORT", Value: "tcp://1.2.3.6:8086"}, - {Name: "KUBERNETES_PORT_8086_TCP", Value: "tcp://1.2.3.6:8086"}, - {Name: "KUBERNETES_PORT_8086_TCP_PROTO", Value: "tcp"}, - {Name: "KUBERNETES_PORT_8086_TCP_PORT", Value: "8086"}, - {Name: "KUBERNETES_PORT_8086_TCP_ADDR", Value: "1.2.3.6"}, - }, - }, - { - name: "downward api pod", - ns: "downward-api", - container: &v1.Container{ - Env: []v1.EnvVar{ - { - Name: "POD_NAME", - ValueFrom: &v1.EnvVarSource{ - FieldRef: &v1.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - FieldPath: "metadata.name", - }, - }, - }, - { - Name: "POD_NAMESPACE", - ValueFrom: &v1.EnvVarSource{ - FieldRef: &v1.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - FieldPath: "metadata.namespace", - }, - }, - }, - { - Name: "POD_NODE_NAME", - ValueFrom: &v1.EnvVarSource{ - FieldRef: &v1.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - FieldPath: "spec.nodeName", - }, - }, - }, - { - Name: "POD_SERVICE_ACCOUNT_NAME", - ValueFrom: &v1.EnvVarSource{ - FieldRef: &v1.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - FieldPath: "spec.serviceAccountName", - }, - }, - }, - { - Name: "POD_IP", - ValueFrom: &v1.EnvVarSource{ - FieldRef: &v1.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - FieldPath: "status.podIP", - }, - }, - }, - { - Name: "HOST_IP", - ValueFrom: &v1.EnvVarSource{ - FieldRef: &v1.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - FieldPath: "status.hostIP", - }, - }, - }, - }, - }, - masterServiceNs: "nothing", - nilLister: true, - expectedEnvs: []kubecontainer.EnvVar{ - {Name: "POD_NAME", Value: "dapi-test-pod-name"}, - {Name: "POD_NAMESPACE", Value: "downward-api"}, - {Name: "POD_NODE_NAME", Value: "node-name"}, - {Name: "POD_SERVICE_ACCOUNT_NAME", Value: "special"}, - {Name: "POD_IP", Value: "1.2.3.4"}, - {Name: "HOST_IP", Value: testKubeletHostIP}, - }, - }, - { - name: "env expansion", - ns: "test1", - container: &v1.Container{ - Env: []v1.EnvVar{ - { - Name: "TEST_LITERAL", - Value: "test-test-test", - }, - { - Name: "POD_NAME", - ValueFrom: &v1.EnvVarSource{ - FieldRef: &v1.ObjectFieldSelector{ - APIVersion: legacyscheme.Registry.GroupOrDie(v1.GroupName).GroupVersion.String(), - FieldPath: "metadata.name", - }, - }, - }, - { - Name: "OUT_OF_ORDER_TEST", - Value: "$(OUT_OF_ORDER_TARGET)", - }, - { - Name: "OUT_OF_ORDER_TARGET", - Value: "FOO", - }, - { - Name: "EMPTY_VAR", - }, - { - Name: "EMPTY_TEST", - Value: "foo-$(EMPTY_VAR)", - }, - { - Name: "POD_NAME_TEST2", - Value: "test2-$(POD_NAME)", - }, - { - Name: "POD_NAME_TEST3", - Value: "$(POD_NAME_TEST2)-3", - }, - { - Name: "LITERAL_TEST", - Value: "literal-$(TEST_LITERAL)", - }, - { - Name: "SERVICE_VAR_TEST", - Value: "$(TEST_SERVICE_HOST):$(TEST_SERVICE_PORT)", - }, - { - Name: "TEST_UNDEFINED", - Value: "$(UNDEFINED_VAR)", - }, - }, - }, - masterServiceNs: "nothing", - nilLister: false, - expectedEnvs: []kubecontainer.EnvVar{ - { - Name: "TEST_LITERAL", - Value: "test-test-test", - }, - { - Name: "POD_NAME", - Value: "dapi-test-pod-name", - }, - { - Name: "POD_NAME_TEST2", - Value: "test2-dapi-test-pod-name", - }, - { - Name: "POD_NAME_TEST3", - Value: "test2-dapi-test-pod-name-3", - }, - { - Name: "LITERAL_TEST", - Value: "literal-test-test-test", - }, - { - Name: "TEST_SERVICE_HOST", - Value: "1.2.3.3", - }, - { - Name: "TEST_SERVICE_PORT", - Value: "8083", - }, - { - Name: "TEST_PORT", - Value: "tcp://1.2.3.3:8083", - }, - { - Name: "TEST_PORT_8083_TCP", - Value: "tcp://1.2.3.3:8083", - }, - { - Name: "TEST_PORT_8083_TCP_PROTO", - Value: "tcp", - }, - { - Name: "TEST_PORT_8083_TCP_PORT", - Value: "8083", - }, - { - Name: "TEST_PORT_8083_TCP_ADDR", - Value: "1.2.3.3", - }, - { - Name: "SERVICE_VAR_TEST", - Value: "1.2.3.3:8083", - }, - { - Name: "OUT_OF_ORDER_TEST", - Value: "$(OUT_OF_ORDER_TARGET)", - }, - { - Name: "OUT_OF_ORDER_TARGET", - Value: "FOO", - }, - { - Name: "TEST_UNDEFINED", - Value: "$(UNDEFINED_VAR)", - }, - { - Name: "EMPTY_VAR", - }, - { - Name: "EMPTY_TEST", - Value: "foo-", - }, - }, - }, - { - name: "configmapkeyref_missing_optional", - ns: "test", - container: &v1.Container{ - Env: []v1.EnvVar{ - { - Name: "POD_NAME", - ValueFrom: &v1.EnvVarSource{ - ConfigMapKeyRef: &v1.ConfigMapKeySelector{ - LocalObjectReference: v1.LocalObjectReference{Name: "missing-config-map"}, - Key: "key", - Optional: &trueVal, - }, - }, - }, - }, - }, - masterServiceNs: "nothing", - expectedEnvs: nil, - }, - { - name: "configmapkeyref_missing_key_optional", - ns: "test", - container: &v1.Container{ - Env: []v1.EnvVar{ - { - Name: "POD_NAME", - ValueFrom: &v1.EnvVarSource{ - ConfigMapKeyRef: &v1.ConfigMapKeySelector{ - LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}, - Key: "key", - Optional: &trueVal, - }, - }, - }, - }, - }, - masterServiceNs: "nothing", - nilLister: true, - configMap: &v1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "test1", - Name: "test-configmap", - }, - Data: map[string]string{ - "a": "b", - }, - }, - expectedEnvs: nil, - }, - { - name: "secretkeyref_missing_optional", - ns: "test", - container: &v1.Container{ - Env: []v1.EnvVar{ - { - Name: "POD_NAME", - ValueFrom: &v1.EnvVarSource{ - SecretKeyRef: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{Name: "missing-secret"}, - Key: "key", - Optional: &trueVal, - }, - }, - }, - }, - }, - masterServiceNs: "nothing", - expectedEnvs: nil, - }, - { - name: "secretkeyref_missing_key_optional", - ns: "test", - container: &v1.Container{ - Env: []v1.EnvVar{ - { - Name: "POD_NAME", - ValueFrom: &v1.EnvVarSource{ - SecretKeyRef: &v1.SecretKeySelector{ - LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}, - Key: "key", - Optional: &trueVal, - }, - }, - }, - }, - }, - masterServiceNs: "nothing", - nilLister: true, - secret: &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "test1", - Name: "test-secret", - }, - Data: map[string][]byte{ - "a": []byte("b"), - }, - }, - expectedEnvs: nil, - }, - { - name: "configmap", - ns: "test1", - container: &v1.Container{ - EnvFrom: []v1.EnvFromSource{ - { - ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}, - }, - { - Prefix: "p_", - ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}, - }, - }, - Env: []v1.EnvVar{ - { - Name: "TEST_LITERAL", - Value: "test-test-test", - }, - { - Name: "EXPANSION_TEST", - Value: "$(REPLACE_ME)", - }, - { - Name: "DUPE_TEST", - Value: "ENV_VAR", - }, - }, - }, - masterServiceNs: "nothing", - nilLister: false, - configMap: &v1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "test1", - Name: "test-configmap", - }, - Data: map[string]string{ - "REPLACE_ME": "FROM_CONFIG_MAP", - "DUPE_TEST": "CONFIG_MAP", - }, - }, - expectedEnvs: []kubecontainer.EnvVar{ - { - Name: "TEST_LITERAL", - Value: "test-test-test", - }, - { - Name: "TEST_SERVICE_HOST", - Value: "1.2.3.3", - }, - { - Name: "TEST_SERVICE_PORT", - Value: "8083", - }, - { - Name: "TEST_PORT", - Value: "tcp://1.2.3.3:8083", - }, - { - Name: "TEST_PORT_8083_TCP", - Value: "tcp://1.2.3.3:8083", - }, - { - Name: "TEST_PORT_8083_TCP_PROTO", - Value: "tcp", - }, - { - Name: "TEST_PORT_8083_TCP_PORT", - Value: "8083", - }, - { - Name: "TEST_PORT_8083_TCP_ADDR", - Value: "1.2.3.3", - }, - { - Name: "REPLACE_ME", - Value: "FROM_CONFIG_MAP", - }, - { - Name: "EXPANSION_TEST", - Value: "FROM_CONFIG_MAP", - }, - { - Name: "DUPE_TEST", - Value: "ENV_VAR", - }, - { - Name: "p_REPLACE_ME", - Value: "FROM_CONFIG_MAP", - }, - { - Name: "p_DUPE_TEST", - Value: "CONFIG_MAP", - }, - }, - }, - { - name: "configmap_missing", - ns: "test1", - container: &v1.Container{ - EnvFrom: []v1.EnvFromSource{ - {ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}}, - }, - }, - masterServiceNs: "nothing", - expectedError: true, - }, - { - name: "configmap_missing_optional", - ns: "test", - container: &v1.Container{ - EnvFrom: []v1.EnvFromSource{ - {ConfigMapRef: &v1.ConfigMapEnvSource{ - Optional: &trueVal, - LocalObjectReference: v1.LocalObjectReference{Name: "missing-config-map"}}}, - }, - }, - masterServiceNs: "nothing", - expectedEnvs: nil, - }, - { - name: "configmap_invalid_keys", - ns: "test", - container: &v1.Container{ - EnvFrom: []v1.EnvFromSource{ - {ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}}, - }, - }, - masterServiceNs: "nothing", - configMap: &v1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "test1", - Name: "test-configmap", - }, - Data: map[string]string{ - "1234": "abc", - "1z": "abc", - "key": "value", - }, - }, - expectedEnvs: []kubecontainer.EnvVar{ - { - Name: "key", - Value: "value", - }, - }, - expectedEvent: "Warning InvalidEnvironmentVariableNames Keys [1234, 1z] from the EnvFrom configMap test/test-config-map were skipped since they are considered invalid environment variable names.", - }, - { - name: "configmap_invalid_keys_valid", - ns: "test", - container: &v1.Container{ - EnvFrom: []v1.EnvFromSource{ - { - Prefix: "p_", - ConfigMapRef: &v1.ConfigMapEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-config-map"}}, - }, - }, - }, - masterServiceNs: "", - configMap: &v1.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "test1", - Name: "test-configmap", - }, - Data: map[string]string{ - "1234": "abc", - }, - }, - expectedEnvs: []kubecontainer.EnvVar{ - { - Name: "p_1234", - Value: "abc", - }, - }, - }, - { - name: "secret", - ns: "test1", - container: &v1.Container{ - EnvFrom: []v1.EnvFromSource{ - { - SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}, - }, - { - Prefix: "p_", - SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}, - }, - }, - Env: []v1.EnvVar{ - { - Name: "TEST_LITERAL", - Value: "test-test-test", - }, - { - Name: "EXPANSION_TEST", - Value: "$(REPLACE_ME)", - }, - { - Name: "DUPE_TEST", - Value: "ENV_VAR", - }, - }, - }, - masterServiceNs: "nothing", - nilLister: false, - secret: &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "test1", - Name: "test-secret", - }, - Data: map[string][]byte{ - "REPLACE_ME": []byte("FROM_SECRET"), - "DUPE_TEST": []byte("SECRET"), - }, - }, - expectedEnvs: []kubecontainer.EnvVar{ - { - Name: "TEST_LITERAL", - Value: "test-test-test", - }, - { - Name: "TEST_SERVICE_HOST", - Value: "1.2.3.3", - }, - { - Name: "TEST_SERVICE_PORT", - Value: "8083", - }, - { - Name: "TEST_PORT", - Value: "tcp://1.2.3.3:8083", - }, - { - Name: "TEST_PORT_8083_TCP", - Value: "tcp://1.2.3.3:8083", - }, - { - Name: "TEST_PORT_8083_TCP_PROTO", - Value: "tcp", - }, - { - Name: "TEST_PORT_8083_TCP_PORT", - Value: "8083", - }, - { - Name: "TEST_PORT_8083_TCP_ADDR", - Value: "1.2.3.3", - }, - { - Name: "REPLACE_ME", - Value: "FROM_SECRET", - }, - { - Name: "EXPANSION_TEST", - Value: "FROM_SECRET", - }, - { - Name: "DUPE_TEST", - Value: "ENV_VAR", - }, - { - Name: "p_REPLACE_ME", - Value: "FROM_SECRET", - }, - { - Name: "p_DUPE_TEST", - Value: "SECRET", - }, - }, - }, - { - name: "secret_missing", - ns: "test1", - container: &v1.Container{ - EnvFrom: []v1.EnvFromSource{ - {SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}}, - }, - }, - masterServiceNs: "nothing", - expectedError: true, - }, - { - name: "secret_missing_optional", - ns: "test", - container: &v1.Container{ - EnvFrom: []v1.EnvFromSource{ - {SecretRef: &v1.SecretEnvSource{ - LocalObjectReference: v1.LocalObjectReference{Name: "missing-secret"}, - Optional: &trueVal}}, - }, - }, - masterServiceNs: "nothing", - expectedEnvs: nil, - }, - { - name: "secret_invalid_keys", - ns: "test", - container: &v1.Container{ - EnvFrom: []v1.EnvFromSource{ - {SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}}, - }, - }, - masterServiceNs: "nothing", - secret: &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "test1", - Name: "test-secret", - }, - Data: map[string][]byte{ - "1234": []byte("abc"), - "1z": []byte("abc"), - "key.1": []byte("value"), - }, - }, - expectedEnvs: []kubecontainer.EnvVar{ - { - Name: "key.1", - Value: "value", - }, - }, - expectedEvent: "Warning InvalidEnvironmentVariableNames Keys [1234, 1z] from the EnvFrom secret test/test-secret were skipped since they are considered invalid environment variable names.", - }, - { - name: "secret_invalid_keys_valid", - ns: "test", - container: &v1.Container{ - EnvFrom: []v1.EnvFromSource{ - { - Prefix: "p_", - SecretRef: &v1.SecretEnvSource{LocalObjectReference: v1.LocalObjectReference{Name: "test-secret"}}, - }, - }, - }, - masterServiceNs: "", - secret: &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "test1", - Name: "test-secret", - }, - Data: map[string][]byte{ - "1234.name": []byte("abc"), - }, - }, - expectedEnvs: []kubecontainer.EnvVar{ - { - Name: "p_1234.name", - Value: "abc", - }, - }, - }, - } - - for _, tc := range testCases { - fakeRecorder := record.NewFakeRecorder(1) - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - testKubelet.kubelet.recorder = fakeRecorder - defer testKubelet.Cleanup() - kl := testKubelet.kubelet - kl.masterServiceNamespace = tc.masterServiceNs - if tc.nilLister { - kl.serviceLister = nil - } else { - kl.serviceLister = testServiceLister{services} - } - - testKubelet.fakeKubeClient.AddReactor("get", "configmaps", func(action core.Action) (bool, runtime.Object, error) { - var err error - if tc.configMap == nil { - err = apierrors.NewNotFound(action.GetResource().GroupResource(), "configmap-name") - } - return true, tc.configMap, err - }) - testKubelet.fakeKubeClient.AddReactor("get", "secrets", func(action core.Action) (bool, runtime.Object, error) { - var err error - if tc.secret == nil { - err = apierrors.NewNotFound(action.GetResource().GroupResource(), "secret-name") - } - return true, tc.secret, err - }) - - testKubelet.fakeKubeClient.AddReactor("get", "secrets", func(action core.Action) (bool, runtime.Object, error) { - var err error - if tc.secret == nil { - err = errors.New("no secret defined") - } - return true, tc.secret, err - }) - - testPod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: tc.ns, - Name: "dapi-test-pod-name", - }, - Spec: v1.PodSpec{ - ServiceAccountName: "special", - NodeName: "node-name", - }, - } - podIP := "1.2.3.4" - - result, err := kl.makeEnvironmentVariables(testPod, tc.container, podIP) - select { - case e := <-fakeRecorder.Events: - assert.Equal(t, tc.expectedEvent, e) - default: - assert.Equal(t, "", tc.expectedEvent) - } - if tc.expectedError { - assert.Error(t, err, tc.name) - } else { - assert.NoError(t, err, "[%s]", tc.name) - - sort.Sort(envs(result)) - sort.Sort(envs(tc.expectedEnvs)) - assert.Equal(t, tc.expectedEnvs, result, "[%s] env entries", tc.name) - } - } -} - -func waitingState(cName string) v1.ContainerStatus { - return v1.ContainerStatus{ - Name: cName, - State: v1.ContainerState{ - Waiting: &v1.ContainerStateWaiting{}, - }, - } -} -func waitingStateWithLastTermination(cName string) v1.ContainerStatus { - return v1.ContainerStatus{ - Name: cName, - State: v1.ContainerState{ - Waiting: &v1.ContainerStateWaiting{}, - }, - LastTerminationState: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{ - ExitCode: 0, - }, - }, - } -} -func runningState(cName string) v1.ContainerStatus { - return v1.ContainerStatus{ - Name: cName, - State: v1.ContainerState{ - Running: &v1.ContainerStateRunning{}, - }, - } -} -func stoppedState(cName string) v1.ContainerStatus { - return v1.ContainerStatus{ - Name: cName, - State: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{}, - }, - } -} -func succeededState(cName string) v1.ContainerStatus { - return v1.ContainerStatus{ - Name: cName, - State: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{ - ExitCode: 0, - }, - }, - } -} -func failedState(cName string) v1.ContainerStatus { - return v1.ContainerStatus{ - Name: cName, - State: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{ - ExitCode: -1, - }, - }, - } -} - -func TestPodPhaseWithRestartAlways(t *testing.T) { - desiredState := v1.PodSpec{ - NodeName: "machine", - Containers: []v1.Container{ - {Name: "containerA"}, - {Name: "containerB"}, - }, - RestartPolicy: v1.RestartPolicyAlways, - } - - tests := []struct { - pod *v1.Pod - status v1.PodPhase - test string - }{ - {&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"}, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - runningState("containerB"), - }, - }, - }, - v1.PodRunning, - "all running", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - stoppedState("containerA"), - stoppedState("containerB"), - }, - }, - }, - v1.PodRunning, - "all stopped with restart always", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - stoppedState("containerB"), - }, - }, - }, - v1.PodRunning, - "mixed state #1 with restart always", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - }, - }, - }, - v1.PodPending, - "mixed state #2 with restart always", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - waitingState("containerB"), - }, - }, - }, - v1.PodPending, - "mixed state #3 with restart always", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - waitingStateWithLastTermination("containerB"), - }, - }, - }, - v1.PodRunning, - "backoff crashloop container with restart always", - }, - } - for _, test := range tests { - status := getPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses) - assert.Equal(t, test.status, status, "[test %s]", test.test) - } -} - -func TestPodPhaseWithRestartNever(t *testing.T) { - desiredState := v1.PodSpec{ - NodeName: "machine", - Containers: []v1.Container{ - {Name: "containerA"}, - {Name: "containerB"}, - }, - RestartPolicy: v1.RestartPolicyNever, - } - - tests := []struct { - pod *v1.Pod - status v1.PodPhase - test string - }{ - {&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"}, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - runningState("containerB"), - }, - }, - }, - v1.PodRunning, - "all running with restart never", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - succeededState("containerA"), - succeededState("containerB"), - }, - }, - }, - v1.PodSucceeded, - "all succeeded with restart never", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - failedState("containerA"), - failedState("containerB"), - }, - }, - }, - v1.PodFailed, - "all failed with restart never", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - succeededState("containerB"), - }, - }, - }, - v1.PodRunning, - "mixed state #1 with restart never", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - }, - }, - }, - v1.PodPending, - "mixed state #2 with restart never", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - waitingState("containerB"), - }, - }, - }, - v1.PodPending, - "mixed state #3 with restart never", - }, - } - for _, test := range tests { - status := getPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses) - assert.Equal(t, test.status, status, "[test %s]", test.test) - } -} - -func TestPodPhaseWithRestartOnFailure(t *testing.T) { - desiredState := v1.PodSpec{ - NodeName: "machine", - Containers: []v1.Container{ - {Name: "containerA"}, - {Name: "containerB"}, - }, - RestartPolicy: v1.RestartPolicyOnFailure, - } - - tests := []struct { - pod *v1.Pod - status v1.PodPhase - test string - }{ - {&v1.Pod{Spec: desiredState, Status: v1.PodStatus{}}, v1.PodPending, "waiting"}, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - runningState("containerB"), - }, - }, - }, - v1.PodRunning, - "all running with restart onfailure", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - succeededState("containerA"), - succeededState("containerB"), - }, - }, - }, - v1.PodSucceeded, - "all succeeded with restart onfailure", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - failedState("containerA"), - failedState("containerB"), - }, - }, - }, - v1.PodRunning, - "all failed with restart never", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - succeededState("containerB"), - }, - }, - }, - v1.PodRunning, - "mixed state #1 with restart onfailure", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - }, - }, - }, - v1.PodPending, - "mixed state #2 with restart onfailure", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - waitingState("containerB"), - }, - }, - }, - v1.PodPending, - "mixed state #3 with restart onfailure", - }, - { - &v1.Pod{ - Spec: desiredState, - Status: v1.PodStatus{ - ContainerStatuses: []v1.ContainerStatus{ - runningState("containerA"), - waitingStateWithLastTermination("containerB"), - }, - }, - }, - v1.PodRunning, - "backoff crashloop container with restart onfailure", - }, - } - for _, test := range tests { - status := getPhase(&test.pod.Spec, test.pod.Status.ContainerStatuses) - assert.Equal(t, test.status, status, "[test %s]", test.test) - } -} - -type fakeReadWriteCloser struct{} - -func (f *fakeReadWriteCloser) Write(data []byte) (int, error) { - return 0, nil -} - -func (f *fakeReadWriteCloser) Read(data []byte) (int, error) { - return 0, nil -} - -func (f *fakeReadWriteCloser) Close() error { - return nil -} - -func TestExec(t *testing.T) { - const ( - podName = "podFoo" - podNamespace = "nsFoo" - podUID types.UID = "12345678" - containerID = "containerFoo" - tty = true - ) - var ( - podFullName = kubecontainer.GetPodFullName(podWithUIDNameNs(podUID, podName, podNamespace)) - command = []string{"ls"} - stdin = &bytes.Buffer{} - stdout = &fakeReadWriteCloser{} - stderr = &fakeReadWriteCloser{} - ) - - testcases := []struct { - description string - podFullName string - container string - expectError bool - }{{ - description: "success case", - podFullName: podFullName, - container: containerID, - }, { - description: "no such pod", - podFullName: "bar" + podFullName, - container: containerID, - expectError: true, - }, { - description: "no such container", - podFullName: podFullName, - container: "containerBar", - expectError: true, - }} - - for _, tc := range testcases { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - testKubelet.fakeRuntime.PodList = []*containertest.FakePod{ - {Pod: &kubecontainer.Pod{ - ID: podUID, - Name: podName, - Namespace: podNamespace, - Containers: []*kubecontainer.Container{ - {Name: containerID, - ID: kubecontainer.ContainerID{Type: "test", ID: containerID}, - }, - }, - }}, - } - - { // No streaming case - description := "no streaming - " + tc.description - redirect, err := kubelet.GetExec(tc.podFullName, podUID, tc.container, command, remotecommand.Options{}) - assert.Error(t, err, description) - assert.Nil(t, redirect, description) - - err = kubelet.ExecInContainer(tc.podFullName, podUID, tc.container, command, stdin, stdout, stderr, tty, nil, 0) - assert.Error(t, err, description) - } - { // Direct streaming case - description := "direct streaming - " + tc.description - fakeRuntime := &containertest.FakeDirectStreamingRuntime{FakeRuntime: testKubelet.fakeRuntime} - kubelet.containerRuntime = fakeRuntime - - redirect, err := kubelet.GetExec(tc.podFullName, podUID, tc.container, command, remotecommand.Options{}) - assert.NoError(t, err, description) - assert.Nil(t, redirect, description) - - err = kubelet.ExecInContainer(tc.podFullName, podUID, tc.container, command, stdin, stdout, stderr, tty, nil, 0) - if tc.expectError { - assert.Error(t, err, description) - } else { - assert.NoError(t, err, description) - assert.Equal(t, fakeRuntime.Args.ContainerID.ID, containerID, description+": ID") - assert.Equal(t, fakeRuntime.Args.Cmd, command, description+": Command") - assert.Equal(t, fakeRuntime.Args.Stdin, stdin, description+": Stdin") - assert.Equal(t, fakeRuntime.Args.Stdout, stdout, description+": Stdout") - assert.Equal(t, fakeRuntime.Args.Stderr, stderr, description+": Stderr") - assert.Equal(t, fakeRuntime.Args.TTY, tty, description+": TTY") - } - } - { // Indirect streaming case - description := "indirect streaming - " + tc.description - fakeRuntime := &containertest.FakeIndirectStreamingRuntime{FakeRuntime: testKubelet.fakeRuntime} - kubelet.containerRuntime = fakeRuntime - - redirect, err := kubelet.GetExec(tc.podFullName, podUID, tc.container, command, remotecommand.Options{}) - if tc.expectError { - assert.Error(t, err, description) - } else { - assert.NoError(t, err, description) - assert.Equal(t, containertest.FakeHost, redirect.Host, description+": redirect") - } - - err = kubelet.ExecInContainer(tc.podFullName, podUID, tc.container, command, stdin, stdout, stderr, tty, nil, 0) - assert.Error(t, err, description) - } - } -} - -func TestPortForward(t *testing.T) { - const ( - podName = "podFoo" - podNamespace = "nsFoo" - podUID types.UID = "12345678" - port int32 = 5000 - ) - var ( - stream = &fakeReadWriteCloser{} - ) - - testcases := []struct { - description string - podName string - expectError bool - }{{ - description: "success case", - podName: podName, - }, { - description: "no such pod", - podName: "bar", - expectError: true, - }} - - for _, tc := range testcases { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - testKubelet.fakeRuntime.PodList = []*containertest.FakePod{ - {Pod: &kubecontainer.Pod{ - ID: podUID, - Name: podName, - Namespace: podNamespace, - Containers: []*kubecontainer.Container{ - {Name: "foo", - ID: kubecontainer.ContainerID{Type: "test", ID: "foo"}, - }, - }, - }}, - } - - podFullName := kubecontainer.GetPodFullName(podWithUIDNameNs(podUID, tc.podName, podNamespace)) - { // No streaming case - description := "no streaming - " + tc.description - redirect, err := kubelet.GetPortForward(tc.podName, podNamespace, podUID, portforward.V4Options{}) - assert.Error(t, err, description) - assert.Nil(t, redirect, description) - - err = kubelet.PortForward(podFullName, podUID, port, stream) - assert.Error(t, err, description) - } - { // Direct streaming case - description := "direct streaming - " + tc.description - fakeRuntime := &containertest.FakeDirectStreamingRuntime{FakeRuntime: testKubelet.fakeRuntime} - kubelet.containerRuntime = fakeRuntime - - redirect, err := kubelet.GetPortForward(tc.podName, podNamespace, podUID, portforward.V4Options{}) - assert.NoError(t, err, description) - assert.Nil(t, redirect, description) - - err = kubelet.PortForward(podFullName, podUID, port, stream) - if tc.expectError { - assert.Error(t, err, description) - } else { - assert.NoError(t, err, description) - require.Equal(t, fakeRuntime.Args.Pod.ID, podUID, description+": Pod UID") - require.Equal(t, fakeRuntime.Args.Port, port, description+": Port") - require.Equal(t, fakeRuntime.Args.Stream, stream, description+": stream") - } - } - { // Indirect streaming case - description := "indirect streaming - " + tc.description - fakeRuntime := &containertest.FakeIndirectStreamingRuntime{FakeRuntime: testKubelet.fakeRuntime} - kubelet.containerRuntime = fakeRuntime - - redirect, err := kubelet.GetPortForward(tc.podName, podNamespace, podUID, portforward.V4Options{}) - if tc.expectError { - assert.Error(t, err, description) - } else { - assert.NoError(t, err, description) - assert.Equal(t, containertest.FakeHost, redirect.Host, description+": redirect") - } - - err = kubelet.PortForward(podFullName, podUID, port, stream) - assert.Error(t, err, description) - } - } -} - -func TestHasHostMountPVC(t *testing.T) { - tests := map[string]struct { - pvError error - pvcError error - expected bool - podHasPVC bool - pvcIsHostPath bool - }{ - "no pvc": {podHasPVC: false, expected: false}, - "error fetching pvc": { - podHasPVC: true, - pvcError: fmt.Errorf("foo"), - expected: false, - }, - "error fetching pv": { - podHasPVC: true, - pvError: fmt.Errorf("foo"), - expected: false, - }, - "host path pvc": { - podHasPVC: true, - pvcIsHostPath: true, - expected: true, - }, - "non host path pvc": { - podHasPVC: true, - pvcIsHostPath: false, - expected: false, - }, - } - - for k, v := range tests { - testKubelet := newTestKubelet(t, false) - defer testKubelet.Cleanup() - pod := &v1.Pod{ - Spec: v1.PodSpec{}, - } - - volumeToReturn := &v1.PersistentVolume{ - Spec: v1.PersistentVolumeSpec{}, - } - - if v.podHasPVC { - pod.Spec.Volumes = []v1.Volume{ - { - VolumeSource: v1.VolumeSource{ - PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{}, - }, - }, - } - - if v.pvcIsHostPath { - volumeToReturn.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{ - HostPath: &v1.HostPathVolumeSource{}, - } - } - - } - - testKubelet.fakeKubeClient.AddReactor("get", "persistentvolumeclaims", func(action core.Action) (bool, runtime.Object, error) { - return true, &v1.PersistentVolumeClaim{ - Spec: v1.PersistentVolumeClaimSpec{ - VolumeName: "foo", - }, - }, v.pvcError - }) - testKubelet.fakeKubeClient.AddReactor("get", "persistentvolumes", func(action core.Action) (bool, runtime.Object, error) { - return true, volumeToReturn, v.pvError - }) - - actual := testKubelet.kubelet.hasHostMountPVC(pod) - if actual != v.expected { - t.Errorf("%s expected %t but got %t", k, v.expected, actual) - } - - } -} - -func TestHasNonNamespacedCapability(t *testing.T) { - createPodWithCap := func(caps []v1.Capability) *v1.Pod { - pod := &v1.Pod{ - Spec: v1.PodSpec{ - Containers: []v1.Container{{}}, - }, - } - - if len(caps) > 0 { - pod.Spec.Containers[0].SecurityContext = &v1.SecurityContext{ - Capabilities: &v1.Capabilities{ - Add: caps, - }, - } - } - return pod - } - - nilCaps := createPodWithCap([]v1.Capability{v1.Capability("foo")}) - nilCaps.Spec.Containers[0].SecurityContext = nil - - tests := map[string]struct { - pod *v1.Pod - expected bool - }{ - "nil security contxt": {createPodWithCap(nil), false}, - "nil caps": {nilCaps, false}, - "namespaced cap": {createPodWithCap([]v1.Capability{v1.Capability("foo")}), false}, - "non-namespaced cap MKNOD": {createPodWithCap([]v1.Capability{v1.Capability("MKNOD")}), true}, - "non-namespaced cap SYS_TIME": {createPodWithCap([]v1.Capability{v1.Capability("SYS_TIME")}), true}, - "non-namespaced cap SYS_MODULE": {createPodWithCap([]v1.Capability{v1.Capability("SYS_MODULE")}), true}, - } - - for k, v := range tests { - actual := hasNonNamespacedCapability(v.pod) - if actual != v.expected { - t.Errorf("%s failed, expected %t but got %t", k, v.expected, actual) - } - } -} - -func TestHasHostVolume(t *testing.T) { - pod := &v1.Pod{ - Spec: v1.PodSpec{ - Volumes: []v1.Volume{ - { - VolumeSource: v1.VolumeSource{ - HostPath: &v1.HostPathVolumeSource{}, - }, - }, - }, - }, - } - - result := hasHostVolume(pod) - if !result { - t.Errorf("expected host volume to enable host user namespace") - } - - pod.Spec.Volumes[0].VolumeSource.HostPath = nil - result = hasHostVolume(pod) - if result { - t.Errorf("expected nil host volume to not enable host user namespace") - } -} - -func TestHasHostNamespace(t *testing.T) { - tests := map[string]struct { - ps v1.PodSpec - expected bool - }{ - "nil psc": { - ps: v1.PodSpec{}, - expected: false}, - - "host pid true": { - ps: v1.PodSpec{ - HostPID: true, - SecurityContext: &v1.PodSecurityContext{}, - }, - expected: true, - }, - "host ipc true": { - ps: v1.PodSpec{ - HostIPC: true, - SecurityContext: &v1.PodSecurityContext{}, - }, - expected: true, - }, - "host net true": { - ps: v1.PodSpec{ - HostNetwork: true, - SecurityContext: &v1.PodSecurityContext{}, - }, - expected: true, - }, - "no host ns": { - ps: v1.PodSpec{ - SecurityContext: &v1.PodSecurityContext{}, - }, - expected: false, - }, - } - - for k, v := range tests { - pod := &v1.Pod{ - Spec: v.ps, - } - actual := hasHostNamespace(pod) - if actual != v.expected { - t.Errorf("%s failed, expected %t but got %t", k, v.expected, actual) - } - } -} - -func TestTruncatePodHostname(t *testing.T) { - for c, test := range map[string]struct { - input string - output string - }{ - "valid hostname": { - input: "test.pod.hostname", - output: "test.pod.hostname", - }, - "too long hostname": { - input: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567.", // 8*9=72 chars - output: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.1234567", //8*8-1=63 chars - }, - "hostname end with .": { - input: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456.1234567.", // 8*9-1=71 chars - output: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456", //8*8-2=62 chars - }, - "hostname end with -": { - input: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456-1234567.", // 8*9-1=71 chars - output: "1234567.1234567.1234567.1234567.1234567.1234567.1234567.123456", //8*8-2=62 chars - }, - } { - t.Logf("TestCase: %q", c) - output, err := truncatePodHostnameIfNeeded("test-pod", test.input) - assert.NoError(t, err) - assert.Equal(t, test.output, output) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods_windows_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods_windows_test.go deleted file mode 100644 index cc16b358fb..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_pods_windows_test.go +++ /dev/null @@ -1,102 +0,0 @@ -// +build windows - -/* -Copyright 2017 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 kubelet - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "k8s.io/api/core/v1" - kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" - "k8s.io/kubernetes/pkg/util/mount" -) - -func TestMakeMountsWindows(t *testing.T) { - container := v1.Container{ - VolumeMounts: []v1.VolumeMount{ - { - MountPath: "c:/etc/hosts", - Name: "disk", - ReadOnly: false, - }, - { - MountPath: "c:/mnt/path3", - Name: "disk", - ReadOnly: true, - }, - { - MountPath: "c:/mnt/path4", - Name: "disk4", - ReadOnly: false, - }, - { - MountPath: "c:/mnt/path5", - Name: "disk5", - ReadOnly: false, - }, - }, - } - - podVolumes := kubecontainer.VolumeMap{ - "disk": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "c:/mnt/disk"}}, - "disk4": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "c:/mnt/host"}}, - "disk5": kubecontainer.VolumeInfo{Mounter: &stubVolume{path: "c:/var/lib/kubelet/podID/volumes/empty/disk5"}}, - } - - pod := v1.Pod{ - Spec: v1.PodSpec{ - HostNetwork: true, - }, - } - - fm := &mount.FakeMounter{} - mounts, _, _ := makeMounts(&pod, "/pod", &container, "fakepodname", "", "", podVolumes, fm) - - expectedMounts := []kubecontainer.Mount{ - { - Name: "disk", - ContainerPath: "c:/etc/hosts", - HostPath: "c:/mnt/disk", - ReadOnly: false, - SELinuxRelabel: false, - }, - { - Name: "disk", - ContainerPath: "c:/mnt/path3", - HostPath: "c:/mnt/disk", - ReadOnly: true, - SELinuxRelabel: false, - }, - { - Name: "disk4", - ContainerPath: "c:/mnt/path4", - HostPath: "c:/mnt/host", - ReadOnly: false, - SELinuxRelabel: false, - }, - { - Name: "disk5", - ContainerPath: "c:/mnt/path5", - HostPath: "c:/var/lib/kubelet/podID/volumes/empty/disk5", - ReadOnly: false, - SELinuxRelabel: false, - }, - } - assert.Equal(t, expectedMounts, mounts, "mounts of container %+v", container) -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_resources_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_resources_test.go deleted file mode 100644 index c5833b2566..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_resources_test.go +++ /dev/null @@ -1,111 +0,0 @@ -/* -Copyright 2016 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 kubelet - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - cadvisorapi "github.com/google/cadvisor/info/v1" - cadvisorapiv2 "github.com/google/cadvisor/info/v2" - "k8s.io/api/core/v1" - apiequality "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestPodResourceLimitsDefaulting(t *testing.T) { - cpuCores := resource.MustParse("10") - memoryCapacity := resource.MustParse("10Gi") - tk := newTestKubelet(t, true) - defer tk.Cleanup() - tk.fakeCadvisor.On("VersionInfo").Return(&cadvisorapi.VersionInfo{}, nil) - tk.fakeCadvisor.On("MachineInfo").Return(&cadvisorapi.MachineInfo{ - NumCores: int(cpuCores.Value()), - MemoryCapacity: uint64(memoryCapacity.Value()), - }, nil) - tk.fakeCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) - tk.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) - tk.kubelet.nodeInfo = &testNodeInfo{ - nodes: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: string(tk.kubelet.nodeName), - }, - Status: v1.NodeStatus{ - Allocatable: v1.ResourceList{ - v1.ResourceCPU: resource.MustParse("6"), - v1.ResourceMemory: resource.MustParse("4Gi"), - }, - }, - }, - }, - } - cases := []struct { - pod *v1.Pod - expected *v1.Pod - }{ - { - pod: getPod("0", "0"), - expected: getPod("6", "4Gi"), - }, - { - pod: getPod("1", "0"), - expected: getPod("1", "4Gi"), - }, - { - pod: getPod("", ""), - expected: getPod("6", "4Gi"), - }, - { - pod: getPod("0", "1Mi"), - expected: getPod("6", "1Mi"), - }, - } - as := assert.New(t) - for idx, tc := range cases { - actual, _, err := tk.kubelet.defaultPodLimitsForDownwardAPI(tc.pod, nil) - as.Nil(err, "failed to default pod limits: %v", err) - if !apiequality.Semantic.DeepEqual(tc.expected, actual) { - as.Fail("test case [%d] failed. Expected: %+v, Got: %+v", idx, tc.expected, actual) - } - } -} - -func getPod(cpuLimit, memoryLimit string) *v1.Pod { - resources := v1.ResourceRequirements{} - if cpuLimit != "" || memoryLimit != "" { - resources.Limits = make(v1.ResourceList) - } - if cpuLimit != "" { - resources.Limits[v1.ResourceCPU] = resource.MustParse(cpuLimit) - } - if memoryLimit != "" { - resources.Limits[v1.ResourceMemory] = resource.MustParse(memoryLimit) - } - return &v1.Pod{ - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - Name: "foo", - Resources: resources, - }, - }, - }, - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_test.go deleted file mode 100644 index b849f91daf..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_test.go +++ /dev/null @@ -1,2239 +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 kubelet - -import ( - "fmt" - "io/ioutil" - "os" - "sort" - "testing" - "time" - - cadvisorapi "github.com/google/cadvisor/info/v1" - cadvisorapiv2 "github.com/google/cadvisor/info/v2" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/clock" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/kubernetes/fake" - "k8s.io/client-go/tools/record" - "k8s.io/client-go/util/flowcontrol" - "k8s.io/kubernetes/pkg/capabilities" - "k8s.io/kubernetes/pkg/kubelet/apis/kubeletconfig" - cadvisortest "k8s.io/kubernetes/pkg/kubelet/cadvisor/testing" - "k8s.io/kubernetes/pkg/kubelet/cm" - "k8s.io/kubernetes/pkg/kubelet/config" - "k8s.io/kubernetes/pkg/kubelet/configmap" - kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" - containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" - "k8s.io/kubernetes/pkg/kubelet/eviction" - "k8s.io/kubernetes/pkg/kubelet/gpu" - "k8s.io/kubernetes/pkg/kubelet/images" - "k8s.io/kubernetes/pkg/kubelet/lifecycle" - "k8s.io/kubernetes/pkg/kubelet/logs" - "k8s.io/kubernetes/pkg/kubelet/network" - nettest "k8s.io/kubernetes/pkg/kubelet/network/testing" - "k8s.io/kubernetes/pkg/kubelet/pleg" - kubepod "k8s.io/kubernetes/pkg/kubelet/pod" - podtest "k8s.io/kubernetes/pkg/kubelet/pod/testing" - proberesults "k8s.io/kubernetes/pkg/kubelet/prober/results" - probetest "k8s.io/kubernetes/pkg/kubelet/prober/testing" - "k8s.io/kubernetes/pkg/kubelet/secret" - serverstats "k8s.io/kubernetes/pkg/kubelet/server/stats" - "k8s.io/kubernetes/pkg/kubelet/stats" - "k8s.io/kubernetes/pkg/kubelet/status" - statustest "k8s.io/kubernetes/pkg/kubelet/status/testing" - kubetypes "k8s.io/kubernetes/pkg/kubelet/types" - "k8s.io/kubernetes/pkg/kubelet/util/queue" - kubeletvolume "k8s.io/kubernetes/pkg/kubelet/volumemanager" - "k8s.io/kubernetes/pkg/scheduler/schedulercache" - "k8s.io/kubernetes/pkg/util/mount" - "k8s.io/kubernetes/pkg/volume" - _ "k8s.io/kubernetes/pkg/volume/host_path" - volumetest "k8s.io/kubernetes/pkg/volume/testing" - "k8s.io/kubernetes/pkg/volume/util" -) - -func init() { - utilruntime.ReallyCrash = true -} - -const ( - testKubeletHostname = "127.0.0.1" - testKubeletHostIP = "127.0.0.1" - - // TODO(harry) any global place for these two? - // Reasonable size range of all container images. 90%ile of images on dockerhub drops into this range. - minImgSize int64 = 23 * 1024 * 1024 - maxImgSize int64 = 1000 * 1024 * 1024 -) - -// fakeImageGCManager is a fake image gc manager for testing. It will return image -// list from fake runtime directly instead of caching it. -type fakeImageGCManager struct { - fakeImageService kubecontainer.ImageService - images.ImageGCManager -} - -func (f *fakeImageGCManager) GetImageList() ([]kubecontainer.Image, error) { - return f.fakeImageService.ListImages() -} - -type TestKubelet struct { - kubelet *Kubelet - fakeRuntime *containertest.FakeRuntime - fakeCadvisor *cadvisortest.Mock - fakeKubeClient *fake.Clientset - fakeMirrorClient *podtest.FakeMirrorClient - fakeClock *clock.FakeClock - mounter mount.Interface - volumePlugin *volumetest.FakeVolumePlugin -} - -func (tk *TestKubelet) Cleanup() { - if tk.kubelet != nil { - os.RemoveAll(tk.kubelet.rootDirectory) - } -} - -func (tk *TestKubelet) chainMock() { - tk.fakeCadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) - tk.fakeCadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{}, nil) -} - -// newTestKubelet returns test kubelet with two images. -func newTestKubelet(t *testing.T, controllerAttachDetachEnabled bool) *TestKubelet { - imageList := []kubecontainer.Image{ - { - ID: "abc", - RepoTags: []string{"k8s.gcr.io:v1", "k8s.gcr.io:v2"}, - Size: 123, - }, - { - ID: "efg", - RepoTags: []string{"k8s.gcr.io:v3", "k8s.gcr.io:v4"}, - Size: 456, - }, - } - return newTestKubeletWithImageList(t, imageList, controllerAttachDetachEnabled) -} - -func newTestKubeletWithImageList( - t *testing.T, - imageList []kubecontainer.Image, - controllerAttachDetachEnabled bool) *TestKubelet { - fakeRuntime := &containertest.FakeRuntime{} - fakeRuntime.RuntimeType = "test" - fakeRuntime.VersionInfo = "1.5.0" - fakeRuntime.ImageList = imageList - // Set ready conditions by default. - fakeRuntime.RuntimeStatus = &kubecontainer.RuntimeStatus{ - Conditions: []kubecontainer.RuntimeCondition{ - {Type: "RuntimeReady", Status: true}, - {Type: "NetworkReady", Status: true}, - }, - } - - fakeRecorder := &record.FakeRecorder{} - fakeKubeClient := &fake.Clientset{} - kubelet := &Kubelet{} - kubelet.recorder = fakeRecorder - kubelet.kubeClient = fakeKubeClient - kubelet.heartbeatClient = fakeKubeClient.CoreV1() - kubelet.os = &containertest.FakeOS{} - kubelet.mounter = &mount.FakeMounter{} - - kubelet.hostname = testKubeletHostname - kubelet.nodeName = types.NodeName(testKubeletHostname) - kubelet.runtimeState = newRuntimeState(maxWaitForContainerRuntime) - kubelet.runtimeState.setNetworkState(nil) - kubelet.networkPlugin, _ = network.InitNetworkPlugin([]network.NetworkPlugin{}, "", nettest.NewFakeHost(nil), kubeletconfig.HairpinNone, "", 1440) - if tempDir, err := ioutil.TempDir("/tmp", "kubelet_test."); err != nil { - t.Fatalf("can't make a temp rootdir: %v", err) - } else { - kubelet.rootDirectory = tempDir - } - if err := os.MkdirAll(kubelet.rootDirectory, 0750); err != nil { - t.Fatalf("can't mkdir(%q): %v", kubelet.rootDirectory, err) - } - kubelet.sourcesReady = config.NewSourcesReady(func(_ sets.String) bool { return true }) - kubelet.masterServiceNamespace = metav1.NamespaceDefault - kubelet.serviceLister = testServiceLister{} - kubelet.nodeInfo = testNodeInfo{ - nodes: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: string(kubelet.nodeName), - }, - Status: v1.NodeStatus{ - Conditions: []v1.NodeCondition{ - { - Type: v1.NodeReady, - Status: v1.ConditionTrue, - Reason: "Ready", - Message: "Node ready", - }, - }, - Addresses: []v1.NodeAddress{ - { - Type: v1.NodeInternalIP, - Address: testKubeletHostIP, - }, - }, - }, - }, - }, - } - kubelet.recorder = fakeRecorder - if err := kubelet.setupDataDirs(); err != nil { - t.Fatalf("can't initialize kubelet data dirs: %v", err) - } - kubelet.daemonEndpoints = &v1.NodeDaemonEndpoints{} - - mockCadvisor := &cadvisortest.Mock{} - kubelet.cadvisor = mockCadvisor - - fakeMirrorClient := podtest.NewFakeMirrorClient() - secretManager := secret.NewSimpleSecretManager(kubelet.kubeClient) - kubelet.secretManager = secretManager - configMapManager := configmap.NewSimpleConfigMapManager(kubelet.kubeClient) - kubelet.configMapManager = configMapManager - kubelet.podManager = kubepod.NewBasicPodManager(fakeMirrorClient, kubelet.secretManager, kubelet.configMapManager) - kubelet.statusManager = status.NewManager(fakeKubeClient, kubelet.podManager, &statustest.FakePodDeletionSafetyProvider{}) - - kubelet.containerRuntime = fakeRuntime - kubelet.runtimeCache = containertest.NewFakeRuntimeCache(kubelet.containerRuntime) - kubelet.reasonCache = NewReasonCache() - kubelet.podCache = containertest.NewFakeCache(kubelet.containerRuntime) - kubelet.podWorkers = &fakePodWorkers{ - syncPodFn: kubelet.syncPod, - cache: kubelet.podCache, - t: t, - } - - kubelet.probeManager = probetest.FakeManager{} - kubelet.livenessManager = proberesults.NewManager() - - kubelet.containerManager = cm.NewStubContainerManager() - fakeNodeRef := &v1.ObjectReference{ - Kind: "Node", - Name: testKubeletHostname, - UID: types.UID(testKubeletHostname), - Namespace: "", - } - - volumeStatsAggPeriod := time.Second * 10 - kubelet.resourceAnalyzer = serverstats.NewResourceAnalyzer(kubelet, volumeStatsAggPeriod) - - kubelet.StatsProvider = stats.NewCadvisorStatsProvider( - kubelet.cadvisor, - kubelet.resourceAnalyzer, - kubelet.podManager, - kubelet.runtimeCache, - fakeRuntime) - fakeImageGCPolicy := images.ImageGCPolicy{ - HighThresholdPercent: 90, - LowThresholdPercent: 80, - } - imageGCManager, err := images.NewImageGCManager(fakeRuntime, kubelet.StatsProvider, fakeRecorder, fakeNodeRef, fakeImageGCPolicy, "") - assert.NoError(t, err) - kubelet.imageManager = &fakeImageGCManager{ - fakeImageService: fakeRuntime, - ImageGCManager: imageGCManager, - } - kubelet.containerLogManager = logs.NewStubContainerLogManager() - containerGCPolicy := kubecontainer.ContainerGCPolicy{ - MinAge: time.Duration(0), - MaxPerPodContainer: 1, - MaxContainers: -1, - } - containerGC, err := kubecontainer.NewContainerGC(fakeRuntime, containerGCPolicy, kubelet.sourcesReady) - assert.NoError(t, err) - kubelet.containerGC = containerGC - - fakeClock := clock.NewFakeClock(time.Now()) - kubelet.backOff = flowcontrol.NewBackOff(time.Second, time.Minute) - kubelet.backOff.Clock = fakeClock - kubelet.podKillingCh = make(chan *kubecontainer.PodPair, 20) - kubelet.resyncInterval = 10 * time.Second - kubelet.workQueue = queue.NewBasicWorkQueue(fakeClock) - // Relist period does not affect the tests. - kubelet.pleg = pleg.NewGenericPLEG(fakeRuntime, 100, time.Hour, nil, clock.RealClock{}) - kubelet.clock = fakeClock - kubelet.setNodeStatusFuncs = kubelet.defaultNodeStatusFuncs() - - nodeRef := &v1.ObjectReference{ - Kind: "Node", - Name: string(kubelet.nodeName), - UID: types.UID(kubelet.nodeName), - Namespace: "", - } - // setup eviction manager - evictionManager, evictionAdmitHandler := eviction.NewManager(kubelet.resourceAnalyzer, eviction.Config{}, killPodNow(kubelet.podWorkers, fakeRecorder), kubelet.imageManager, kubelet.containerGC, fakeRecorder, nodeRef, kubelet.clock) - - kubelet.evictionManager = evictionManager - kubelet.admitHandlers.AddPodAdmitHandler(evictionAdmitHandler) - // Add this as cleanup predicate pod admitter - kubelet.admitHandlers.AddPodAdmitHandler(lifecycle.NewPredicateAdmitHandler(kubelet.getNodeAnyWay, lifecycle.NewAdmissionFailureHandlerStub(), kubelet.containerManager.UpdatePluginResources)) - - plug := &volumetest.FakeVolumePlugin{PluginName: "fake", Host: nil} - var prober volume.DynamicPluginProber = nil // TODO (#51147) inject mock - kubelet.volumePluginMgr, err = - NewInitializedVolumePluginMgr(kubelet, kubelet.secretManager, kubelet.configMapManager, []volume.VolumePlugin{plug}, prober) - require.NoError(t, err, "Failed to initialize VolumePluginMgr") - - kubelet.mounter = &mount.FakeMounter{} - kubelet.volumeManager = kubeletvolume.NewVolumeManager( - controllerAttachDetachEnabled, - kubelet.nodeName, - kubelet.podManager, - kubelet.statusManager, - fakeKubeClient, - kubelet.volumePluginMgr, - fakeRuntime, - kubelet.mounter, - kubelet.getPodsDir(), - kubelet.recorder, - false, /* experimentalCheckNodeCapabilitiesBeforeMount*/ - false /* keepTerminatedPodVolumes */) - - // enable active deadline handler - activeDeadlineHandler, err := newActiveDeadlineHandler(kubelet.statusManager, kubelet.recorder, kubelet.clock) - require.NoError(t, err, "Can't initialize active deadline handler") - - kubelet.AddPodSyncLoopHandler(activeDeadlineHandler) - kubelet.AddPodSyncHandler(activeDeadlineHandler) - kubelet.gpuManager = gpu.NewGPUManagerStub() - return &TestKubelet{kubelet, fakeRuntime, mockCadvisor, fakeKubeClient, fakeMirrorClient, fakeClock, nil, plug} -} - -func newTestPods(count int) []*v1.Pod { - pods := make([]*v1.Pod, count) - for i := 0; i < count; i++ { - pods[i] = &v1.Pod{ - Spec: v1.PodSpec{ - HostNetwork: true, - }, - ObjectMeta: metav1.ObjectMeta{ - UID: types.UID(10000 + i), - Name: fmt.Sprintf("pod%d", i), - }, - } - } - return pods -} - -func TestSyncLoopAbort(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubelet.runtimeState.setRuntimeSync(time.Now()) - // The syncLoop waits on time.After(resyncInterval), set it really big so that we don't race for - // the channel close - kubelet.resyncInterval = time.Second * 30 - - ch := make(chan kubetypes.PodUpdate) - close(ch) - - // sanity check (also prevent this test from hanging in the next step) - ok := kubelet.syncLoopIteration(ch, kubelet, make(chan time.Time), make(chan time.Time), make(chan *pleg.PodLifecycleEvent, 1)) - require.False(t, ok, "Expected syncLoopIteration to return !ok since update chan was closed") - - // this should terminate immediately; if it hangs then the syncLoopIteration isn't aborting properly - kubelet.syncLoop(ch, kubelet) -} - -func TestSyncPodsStartPod(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - fakeRuntime := testKubelet.fakeRuntime - pods := []*v1.Pod{ - podWithUIDNameNsSpec("12345678", "foo", "new", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "bar"}, - }, - }), - } - kubelet.podManager.SetPods(pods) - kubelet.HandlePodSyncs(pods) - fakeRuntime.AssertStartedPods([]string{string(pods[0].UID)}) -} - -func TestSyncPodsDeletesWhenSourcesAreReady(t *testing.T) { - ready := false - - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - fakeRuntime := testKubelet.fakeRuntime - kubelet := testKubelet.kubelet - kubelet.sourcesReady = config.NewSourcesReady(func(_ sets.String) bool { return ready }) - - fakeRuntime.PodList = []*containertest.FakePod{ - {Pod: &kubecontainer.Pod{ - ID: "12345678", - Name: "foo", - Namespace: "new", - Containers: []*kubecontainer.Container{ - {Name: "bar"}, - }, - }}, - } - kubelet.HandlePodCleanups() - // Sources are not ready yet. Don't remove any pods. - fakeRuntime.AssertKilledPods([]string{}) - - ready = true - kubelet.HandlePodCleanups() - - // Sources are ready. Remove unwanted pods. - fakeRuntime.AssertKilledPods([]string{"12345678"}) -} - -type testNodeLister struct { - nodes []*v1.Node -} - -type testNodeInfo struct { - nodes []*v1.Node -} - -func (ls testNodeInfo) GetNodeInfo(id string) (*v1.Node, error) { - for _, node := range ls.nodes { - if node.Name == id { - return node, nil - } - } - return nil, fmt.Errorf("Node with name: %s does not exist", id) -} - -func (ls testNodeLister) List(selector labels.Selector) ([]*v1.Node, error) { - return ls.nodes, nil -} - -func checkPodStatus(t *testing.T, kl *Kubelet, pod *v1.Pod, phase v1.PodPhase) { - status, found := kl.statusManager.GetPodStatus(pod.UID) - require.True(t, found, "Status of pod %q is not found in the status map", pod.UID) - require.Equal(t, phase, status.Phase) -} - -// Tests that we handle port conflicts correctly by setting the failed status in status map. -func TestHandlePortConflicts(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kl := testKubelet.kubelet - - kl.nodeInfo = testNodeInfo{nodes: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{Name: string(kl.nodeName)}, - Status: v1.NodeStatus{ - Allocatable: v1.ResourceList{ - v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), - }, - }, - }, - }} - - spec := v1.PodSpec{NodeName: string(kl.nodeName), Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 80}}}}} - pods := []*v1.Pod{ - podWithUIDNameNsSpec("123456789", "newpod", "foo", spec), - podWithUIDNameNsSpec("987654321", "oldpod", "foo", spec), - } - // Make sure the Pods are in the reverse order of creation time. - pods[1].CreationTimestamp = metav1.NewTime(time.Now()) - pods[0].CreationTimestamp = metav1.NewTime(time.Now().Add(1 * time.Second)) - // The newer pod should be rejected. - notfittingPod := pods[0] - fittingPod := pods[1] - - kl.HandlePodAdditions(pods) - - // Check pod status stored in the status map. - checkPodStatus(t, kl, notfittingPod, v1.PodFailed) - checkPodStatus(t, kl, fittingPod, v1.PodPending) -} - -// Tests that we handle host name conflicts correctly by setting the failed status in status map. -func TestHandleHostNameConflicts(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kl := testKubelet.kubelet - - kl.nodeInfo = testNodeInfo{nodes: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{Name: "127.0.0.1"}, - Status: v1.NodeStatus{ - Allocatable: v1.ResourceList{ - v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), - }, - }, - }, - }} - - // default NodeName in test is 127.0.0.1 - pods := []*v1.Pod{ - podWithUIDNameNsSpec("123456789", "notfittingpod", "foo", v1.PodSpec{NodeName: "127.0.0.2"}), - podWithUIDNameNsSpec("987654321", "fittingpod", "foo", v1.PodSpec{NodeName: "127.0.0.1"}), - } - - notfittingPod := pods[0] - fittingPod := pods[1] - - kl.HandlePodAdditions(pods) - - // Check pod status stored in the status map. - checkPodStatus(t, kl, notfittingPod, v1.PodFailed) - checkPodStatus(t, kl, fittingPod, v1.PodPending) -} - -// Tests that we handle not matching labels selector correctly by setting the failed status in status map. -func TestHandleNodeSelector(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kl := testKubelet.kubelet - nodes := []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname, Labels: map[string]string{"key": "B"}}, - Status: v1.NodeStatus{ - Allocatable: v1.ResourceList{ - v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), - }, - }, - }, - } - kl.nodeInfo = testNodeInfo{nodes: nodes} - pods := []*v1.Pod{ - podWithUIDNameNsSpec("123456789", "podA", "foo", v1.PodSpec{NodeSelector: map[string]string{"key": "A"}}), - podWithUIDNameNsSpec("987654321", "podB", "foo", v1.PodSpec{NodeSelector: map[string]string{"key": "B"}}), - } - // The first pod should be rejected. - notfittingPod := pods[0] - fittingPod := pods[1] - - kl.HandlePodAdditions(pods) - - // Check pod status stored in the status map. - checkPodStatus(t, kl, notfittingPod, v1.PodFailed) - checkPodStatus(t, kl, fittingPod, v1.PodPending) -} - -// Tests that we handle exceeded resources correctly by setting the failed status in status map. -func TestHandleMemExceeded(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kl := testKubelet.kubelet - nodes := []*v1.Node{ - {ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}, - Status: v1.NodeStatus{Capacity: v1.ResourceList{}, Allocatable: v1.ResourceList{ - v1.ResourceCPU: *resource.NewMilliQuantity(10, resource.DecimalSI), - v1.ResourceMemory: *resource.NewQuantity(100, resource.BinarySI), - v1.ResourcePods: *resource.NewQuantity(40, resource.DecimalSI), - }}}, - } - kl.nodeInfo = testNodeInfo{nodes: nodes} - - spec := v1.PodSpec{NodeName: string(kl.nodeName), - Containers: []v1.Container{{Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceMemory: resource.MustParse("90"), - }, - }}}, - } - pods := []*v1.Pod{ - podWithUIDNameNsSpec("123456789", "newpod", "foo", spec), - podWithUIDNameNsSpec("987654321", "oldpod", "foo", spec), - } - // Make sure the Pods are in the reverse order of creation time. - pods[1].CreationTimestamp = metav1.NewTime(time.Now()) - pods[0].CreationTimestamp = metav1.NewTime(time.Now().Add(1 * time.Second)) - // The newer pod should be rejected. - notfittingPod := pods[0] - fittingPod := pods[1] - - kl.HandlePodAdditions(pods) - - // Check pod status stored in the status map. - checkPodStatus(t, kl, notfittingPod, v1.PodFailed) - checkPodStatus(t, kl, fittingPod, v1.PodPending) -} - -// Tests that we handle result of interface UpdatePluginResources correctly -// by setting corresponding status in status map. -func TestHandlePluginResources(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kl := testKubelet.kubelet - - adjustedResource := v1.ResourceName("domain1.com/adjustedResource") - emptyResource := v1.ResourceName("domain2.com/emptyResource") - missingResource := v1.ResourceName("domain2.com/missingResource") - failedResource := v1.ResourceName("domain2.com/failedResource") - resourceQuantity0 := *resource.NewQuantity(int64(0), resource.DecimalSI) - resourceQuantity1 := *resource.NewQuantity(int64(1), resource.DecimalSI) - resourceQuantity2 := *resource.NewQuantity(int64(2), resource.DecimalSI) - resourceQuantityInvalid := *resource.NewQuantity(int64(-1), resource.DecimalSI) - allowedPodQuantity := *resource.NewQuantity(int64(10), resource.DecimalSI) - nodes := []*v1.Node{ - {ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}, - Status: v1.NodeStatus{Capacity: v1.ResourceList{}, Allocatable: v1.ResourceList{ - adjustedResource: resourceQuantity1, - emptyResource: resourceQuantity0, - v1.ResourcePods: allowedPodQuantity, - }}}, - } - kl.nodeInfo = testNodeInfo{nodes: nodes} - - updatePluginResourcesFunc := func(node *schedulercache.NodeInfo, attrs *lifecycle.PodAdmitAttributes) error { - // Maps from resourceName to the value we use to set node.allocatableResource[resourceName]. - // A resource with invalid value (< 0) causes the function to return an error - // to emulate resource Allocation failure. - // Resources not contained in this map will have their node.allocatableResource - // quantity unchanged. - updateResourceMap := map[v1.ResourceName]resource.Quantity{ - adjustedResource: resourceQuantity2, - emptyResource: resourceQuantity0, - failedResource: resourceQuantityInvalid, - } - pod := attrs.Pod - allocatableResource := node.AllocatableResource() - newAllocatableResource := allocatableResource.Clone() - for _, container := range pod.Spec.Containers { - for resource := range container.Resources.Requests { - newQuantity, exist := updateResourceMap[resource] - if !exist { - continue - } - if newQuantity.Value() < 0 { - return fmt.Errorf("Allocation failed") - } - newAllocatableResource.ScalarResources[resource] = newQuantity.Value() - } - } - node.SetAllocatableResource(newAllocatableResource) - return nil - } - - // add updatePluginResourcesFunc to admission handler, to test it's behavior. - kl.admitHandlers = lifecycle.PodAdmitHandlers{} - kl.admitHandlers.AddPodAdmitHandler(lifecycle.NewPredicateAdmitHandler(kl.getNodeAnyWay, lifecycle.NewAdmissionFailureHandlerStub(), updatePluginResourcesFunc)) - - // pod requiring adjustedResource can be successfully allocated because updatePluginResourcesFunc - // adjusts node.allocatableResource for this resource to a sufficient value. - fittingPodSpec := v1.PodSpec{NodeName: string(kl.nodeName), - Containers: []v1.Container{{Resources: v1.ResourceRequirements{ - Limits: v1.ResourceList{ - adjustedResource: resourceQuantity2, - }, - Requests: v1.ResourceList{ - adjustedResource: resourceQuantity2, - }, - }}}, - } - // pod requiring emptyResource (extended resources with 0 allocatable) will - // not pass PredicateAdmit. - emptyPodSpec := v1.PodSpec{NodeName: string(kl.nodeName), - Containers: []v1.Container{{Resources: v1.ResourceRequirements{ - Limits: v1.ResourceList{ - emptyResource: resourceQuantity2, - }, - Requests: v1.ResourceList{ - emptyResource: resourceQuantity2, - }, - }}}, - } - // pod requiring missingResource will pass PredicateAdmit. - // - // Extended resources missing in node status are ignored in PredicateAdmit. - // This is required to support extended resources that are not managed by - // device plugin, such as cluster-level resources. - missingPodSpec := v1.PodSpec{NodeName: string(kl.nodeName), - Containers: []v1.Container{{Resources: v1.ResourceRequirements{ - Limits: v1.ResourceList{ - missingResource: resourceQuantity2, - }, - Requests: v1.ResourceList{ - missingResource: resourceQuantity2, - }, - }}}, - } - // pod requiring failedResource will fail with the resource failed to be allocated. - failedPodSpec := v1.PodSpec{NodeName: string(kl.nodeName), - Containers: []v1.Container{{Resources: v1.ResourceRequirements{ - Limits: v1.ResourceList{ - failedResource: resourceQuantity1, - }, - Requests: v1.ResourceList{ - failedResource: resourceQuantity1, - }, - }}}, - } - - fittingPod := podWithUIDNameNsSpec("1", "fittingpod", "foo", fittingPodSpec) - emptyPod := podWithUIDNameNsSpec("2", "emptypod", "foo", emptyPodSpec) - missingPod := podWithUIDNameNsSpec("3", "missingpod", "foo", missingPodSpec) - failedPod := podWithUIDNameNsSpec("4", "failedpod", "foo", failedPodSpec) - - kl.HandlePodAdditions([]*v1.Pod{fittingPod, emptyPod, missingPod, failedPod}) - - // Check pod status stored in the status map. - checkPodStatus(t, kl, fittingPod, v1.PodPending) - checkPodStatus(t, kl, emptyPod, v1.PodFailed) - checkPodStatus(t, kl, missingPod, v1.PodPending) - checkPodStatus(t, kl, failedPod, v1.PodFailed) -} - -// TODO(filipg): This test should be removed once StatusSyncer can do garbage collection without external signal. -func TestPurgingObsoleteStatusMapEntries(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - versionInfo := &cadvisorapi.VersionInfo{ - KernelVersion: "3.16.0-0.bpo.4-amd64", - ContainerOsVersion: "Debian GNU/Linux 7 (wheezy)", - DockerVersion: "1.5.0", - } - testKubelet.fakeCadvisor.On("VersionInfo").Return(versionInfo, nil) - - kl := testKubelet.kubelet - pods := []*v1.Pod{ - {ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: "1234"}, Spec: v1.PodSpec{Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 80}}}}}}, - {ObjectMeta: metav1.ObjectMeta{Name: "pod2", UID: "4567"}, Spec: v1.PodSpec{Containers: []v1.Container{{Ports: []v1.ContainerPort{{HostPort: 80}}}}}}, - } - podToTest := pods[1] - // Run once to populate the status map. - kl.HandlePodAdditions(pods) - if _, found := kl.statusManager.GetPodStatus(podToTest.UID); !found { - t.Fatalf("expected to have status cached for pod2") - } - // Sync with empty pods so that the entry in status map will be removed. - kl.podManager.SetPods([]*v1.Pod{}) - kl.HandlePodCleanups() - if _, found := kl.statusManager.GetPodStatus(podToTest.UID); found { - t.Fatalf("expected to not have status cached for pod2") - } -} - -func TestValidateContainerLogStatus(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - containerName := "x" - testCases := []struct { - statuses []v1.ContainerStatus - success bool // whether getting logs for the container should succeed. - pSuccess bool // whether getting logs for the previous container should succeed. - }{ - { - statuses: []v1.ContainerStatus{ - { - Name: containerName, - State: v1.ContainerState{ - Running: &v1.ContainerStateRunning{}, - }, - LastTerminationState: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{ContainerID: "docker://fakeid"}, - }, - }, - }, - success: true, - pSuccess: true, - }, - { - statuses: []v1.ContainerStatus{ - { - Name: containerName, - State: v1.ContainerState{ - Running: &v1.ContainerStateRunning{}, - }, - }, - }, - success: true, - pSuccess: false, - }, - { - statuses: []v1.ContainerStatus{ - { - Name: containerName, - State: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{}, - }, - }, - }, - success: false, - pSuccess: false, - }, - { - statuses: []v1.ContainerStatus{ - { - Name: containerName, - State: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{ContainerID: "docker://fakeid"}, - }, - }, - }, - success: true, - pSuccess: false, - }, - { - statuses: []v1.ContainerStatus{ - { - Name: containerName, - State: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{}, - }, - LastTerminationState: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{}, - }, - }, - }, - success: false, - pSuccess: false, - }, - { - statuses: []v1.ContainerStatus{ - { - Name: containerName, - State: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{}, - }, - LastTerminationState: v1.ContainerState{ - Terminated: &v1.ContainerStateTerminated{ContainerID: "docker://fakeid"}, - }, - }, - }, - success: true, - pSuccess: true, - }, - { - statuses: []v1.ContainerStatus{ - { - Name: containerName, - State: v1.ContainerState{ - Waiting: &v1.ContainerStateWaiting{}, - }, - }, - }, - success: false, - pSuccess: false, - }, - { - statuses: []v1.ContainerStatus{ - { - Name: containerName, - State: v1.ContainerState{Waiting: &v1.ContainerStateWaiting{Reason: "ErrImagePull"}}, - }, - }, - success: false, - pSuccess: false, - }, - { - statuses: []v1.ContainerStatus{ - { - Name: containerName, - State: v1.ContainerState{Waiting: &v1.ContainerStateWaiting{Reason: "ErrImagePullBackOff"}}, - }, - }, - success: false, - pSuccess: false, - }, - } - - for i, tc := range testCases { - // Access the log of the most recent container - previous := false - podStatus := &v1.PodStatus{ContainerStatuses: tc.statuses} - _, err := kubelet.validateContainerLogStatus("podName", podStatus, containerName, previous) - if !tc.success { - assert.Error(t, err, fmt.Sprintf("[case %d] error", i)) - } else { - assert.NoError(t, err, "[case %d] error", i) - } - // Access the log of the previous, terminated container - previous = true - _, err = kubelet.validateContainerLogStatus("podName", podStatus, containerName, previous) - if !tc.pSuccess { - assert.Error(t, err, fmt.Sprintf("[case %d] error", i)) - } else { - assert.NoError(t, err, "[case %d] error", i) - } - // Access the log of a container that's not in the pod - _, err = kubelet.validateContainerLogStatus("podName", podStatus, "blah", false) - assert.Error(t, err, fmt.Sprintf("[case %d] invalid container name should cause an error", i)) - } -} - -func TestCreateMirrorPod(t *testing.T) { - for _, updateType := range []kubetypes.SyncPodType{kubetypes.SyncPodCreate, kubetypes.SyncPodUpdate} { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - - kl := testKubelet.kubelet - manager := testKubelet.fakeMirrorClient - pod := podWithUIDNameNs("12345678", "bar", "foo") - pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = "file" - pods := []*v1.Pod{pod} - kl.podManager.SetPods(pods) - err := kl.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: updateType, - }) - assert.NoError(t, err) - podFullName := kubecontainer.GetPodFullName(pod) - assert.True(t, manager.HasPod(podFullName), "Expected mirror pod %q to be created", podFullName) - assert.Equal(t, 1, manager.NumOfPods(), "Expected only 1 mirror pod %q, got %+v", podFullName, manager.GetPods()) - } -} - -func TestDeleteOutdatedMirrorPod(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - - kl := testKubelet.kubelet - manager := testKubelet.fakeMirrorClient - pod := podWithUIDNameNsSpec("12345678", "foo", "ns", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "1234", Image: "foo"}, - }, - }) - pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = "file" - - // Mirror pod has an outdated spec. - mirrorPod := podWithUIDNameNsSpec("11111111", "foo", "ns", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "1234", Image: "bar"}, - }, - }) - mirrorPod.Annotations[kubetypes.ConfigSourceAnnotationKey] = "api" - mirrorPod.Annotations[kubetypes.ConfigMirrorAnnotationKey] = "mirror" - - pods := []*v1.Pod{pod, mirrorPod} - kl.podManager.SetPods(pods) - err := kl.syncPod(syncPodOptions{ - pod: pod, - mirrorPod: mirrorPod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.NoError(t, err) - name := kubecontainer.GetPodFullName(pod) - creates, deletes := manager.GetCounts(name) - if creates != 1 || deletes != 1 { - t.Errorf("expected 1 creation and 1 deletion of %q, got %d, %d", name, creates, deletes) - } -} - -func TestDeleteOrphanedMirrorPods(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - - kl := testKubelet.kubelet - manager := testKubelet.fakeMirrorClient - orphanPods := []*v1.Pod{ - { - ObjectMeta: metav1.ObjectMeta{ - UID: "12345678", - Name: "pod1", - Namespace: "ns", - Annotations: map[string]string{ - kubetypes.ConfigSourceAnnotationKey: "api", - kubetypes.ConfigMirrorAnnotationKey: "mirror", - }, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - UID: "12345679", - Name: "pod2", - Namespace: "ns", - Annotations: map[string]string{ - kubetypes.ConfigSourceAnnotationKey: "api", - kubetypes.ConfigMirrorAnnotationKey: "mirror", - }, - }, - }, - } - - kl.podManager.SetPods(orphanPods) - // Sync with an empty pod list to delete all mirror pods. - kl.HandlePodCleanups() - assert.Len(t, manager.GetPods(), 0, "Expected 0 mirror pods") - for _, pod := range orphanPods { - name := kubecontainer.GetPodFullName(pod) - creates, deletes := manager.GetCounts(name) - if creates != 0 || deletes != 1 { - t.Errorf("expected 0 creation and one deletion of %q, got %d, %d", name, creates, deletes) - } - } -} - -func TestGetContainerInfoForMirrorPods(t *testing.T) { - // pods contain one static and one mirror pod with the same name but - // different UIDs. - pods := []*v1.Pod{ - { - ObjectMeta: metav1.ObjectMeta{ - UID: "1234", - Name: "qux", - Namespace: "ns", - Annotations: map[string]string{ - kubetypes.ConfigSourceAnnotationKey: "file", - }, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo"}, - }, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - UID: "5678", - Name: "qux", - Namespace: "ns", - Annotations: map[string]string{ - kubetypes.ConfigSourceAnnotationKey: "api", - kubetypes.ConfigMirrorAnnotationKey: "mirror", - }, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo"}, - }, - }, - }, - } - - containerID := "ab2cdf" - containerPath := fmt.Sprintf("/docker/%v", containerID) - containerInfo := cadvisorapi.ContainerInfo{ - ContainerReference: cadvisorapi.ContainerReference{ - Name: containerPath, - }, - } - - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - fakeRuntime := testKubelet.fakeRuntime - mockCadvisor := testKubelet.fakeCadvisor - cadvisorReq := &cadvisorapi.ContainerInfoRequest{} - mockCadvisor.On("DockerContainer", containerID, cadvisorReq).Return(containerInfo, nil) - kubelet := testKubelet.kubelet - - fakeRuntime.PodList = []*containertest.FakePod{ - {Pod: &kubecontainer.Pod{ - ID: "1234", - Name: "qux", - Namespace: "ns", - Containers: []*kubecontainer.Container{ - { - Name: "foo", - ID: kubecontainer.ContainerID{Type: "test", ID: containerID}, - }, - }, - }}, - } - - kubelet.podManager.SetPods(pods) - // Use the mirror pod UID to retrieve the stats. - stats, err := kubelet.GetContainerInfo("qux_ns", "5678", "foo", cadvisorReq) - assert.NoError(t, err) - require.NotNil(t, stats) - mockCadvisor.AssertExpectations(t) -} - -func TestHostNetworkAllowed(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - - kubelet := testKubelet.kubelet - - capabilities.SetForTests(capabilities.Capabilities{ - PrivilegedSources: capabilities.PrivilegedSources{ - HostNetworkSources: []string{kubetypes.ApiserverSource, kubetypes.FileSource}, - }, - }) - pod := podWithUIDNameNsSpec("12345678", "foo", "new", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo"}, - }, - HostNetwork: true, - }) - pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = kubetypes.FileSource - - kubelet.podManager.SetPods([]*v1.Pod{pod}) - err := kubelet.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.NoError(t, err, "expected pod infra creation to succeed") -} - -func TestHostNetworkDisallowed(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - - kubelet := testKubelet.kubelet - - capabilities.SetForTests(capabilities.Capabilities{ - PrivilegedSources: capabilities.PrivilegedSources{ - HostNetworkSources: []string{}, - }, - }) - pod := podWithUIDNameNsSpec("12345678", "foo", "new", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo"}, - }, - HostNetwork: true, - }) - pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = kubetypes.FileSource - - err := kubelet.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.Error(t, err, "expected pod infra creation to fail") -} - -func TestHostPIDAllowed(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - - kubelet := testKubelet.kubelet - - capabilities.SetForTests(capabilities.Capabilities{ - PrivilegedSources: capabilities.PrivilegedSources{ - HostPIDSources: []string{kubetypes.ApiserverSource, kubetypes.FileSource}, - }, - }) - pod := podWithUIDNameNsSpec("12345678", "foo", "new", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo"}, - }, - HostPID: true, - }) - pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = kubetypes.FileSource - - kubelet.podManager.SetPods([]*v1.Pod{pod}) - err := kubelet.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.NoError(t, err, "expected pod infra creation to succeed") -} - -func TestHostPIDDisallowed(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - - kubelet := testKubelet.kubelet - - capabilities.SetForTests(capabilities.Capabilities{ - PrivilegedSources: capabilities.PrivilegedSources{ - HostPIDSources: []string{}, - }, - }) - pod := podWithUIDNameNsSpec("12345678", "foo", "new", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo"}, - }, - HostPID: true, - }) - pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = kubetypes.FileSource - - err := kubelet.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.Error(t, err, "expected pod infra creation to fail") -} - -func TestHostIPCAllowed(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - - kubelet := testKubelet.kubelet - - capabilities.SetForTests(capabilities.Capabilities{ - PrivilegedSources: capabilities.PrivilegedSources{ - HostIPCSources: []string{kubetypes.ApiserverSource, kubetypes.FileSource}, - }, - }) - pod := podWithUIDNameNsSpec("12345678", "foo", "new", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo"}, - }, - HostIPC: true, - }) - pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = kubetypes.FileSource - - kubelet.podManager.SetPods([]*v1.Pod{pod}) - err := kubelet.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.NoError(t, err, "expected pod infra creation to succeed") -} - -func TestHostIPCDisallowed(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - - kubelet := testKubelet.kubelet - - capabilities.SetForTests(capabilities.Capabilities{ - PrivilegedSources: capabilities.PrivilegedSources{ - HostIPCSources: []string{}, - }, - }) - pod := podWithUIDNameNsSpec("12345678", "foo", "new", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo"}, - }, - HostIPC: true, - }) - pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = kubetypes.FileSource - - err := kubelet.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.Error(t, err, "expected pod infra creation to fail") -} - -func TestPrivilegeContainerAllowed(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - - kubelet := testKubelet.kubelet - - capabilities.SetForTests(capabilities.Capabilities{ - AllowPrivileged: true, - }) - privileged := true - pod := podWithUIDNameNsSpec("12345678", "foo", "new", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo", SecurityContext: &v1.SecurityContext{Privileged: &privileged}}, - }, - }) - - kubelet.podManager.SetPods([]*v1.Pod{pod}) - err := kubelet.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.NoError(t, err, "expected pod infra creation to succeed") -} - -func TestPrivilegedContainerDisallowed(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kubelet := testKubelet.kubelet - - capabilities.SetForTests(capabilities.Capabilities{ - AllowPrivileged: false, - }) - privileged := true - pod := podWithUIDNameNsSpec("12345678", "foo", "new", v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo", SecurityContext: &v1.SecurityContext{Privileged: &privileged}}, - }, - }) - - err := kubelet.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.Error(t, err, "expected pod infra creation to fail") -} - -func TestNetworkErrorsWithoutHostNetwork(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kubelet := testKubelet.kubelet - - kubelet.runtimeState.setNetworkState(fmt.Errorf("simulated network error")) - capabilities.SetForTests(capabilities.Capabilities{ - PrivilegedSources: capabilities.PrivilegedSources{ - HostNetworkSources: []string{kubetypes.ApiserverSource, kubetypes.FileSource}, - }, - }) - - pod := podWithUIDNameNsSpec("12345678", "hostnetwork", "new", v1.PodSpec{ - HostNetwork: false, - - Containers: []v1.Container{ - {Name: "foo"}, - }, - }) - - kubelet.podManager.SetPods([]*v1.Pod{pod}) - err := kubelet.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.Error(t, err, "expected pod with hostNetwork=false to fail when network in error") - - pod.Annotations[kubetypes.ConfigSourceAnnotationKey] = kubetypes.FileSource - pod.Spec.HostNetwork = true - err = kubelet.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodUpdate, - }) - assert.NoError(t, err, "expected pod with hostNetwork=true to succeed when network in error") -} - -func TestFilterOutTerminatedPods(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - pods := newTestPods(5) - now := metav1.NewTime(time.Now()) - pods[0].Status.Phase = v1.PodFailed - pods[1].Status.Phase = v1.PodSucceeded - // The pod is terminating, should not filter out. - pods[2].Status.Phase = v1.PodRunning - pods[2].DeletionTimestamp = &now - pods[2].Status.ContainerStatuses = []v1.ContainerStatus{ - {State: v1.ContainerState{ - Running: &v1.ContainerStateRunning{ - StartedAt: now, - }, - }}, - } - pods[3].Status.Phase = v1.PodPending - pods[4].Status.Phase = v1.PodRunning - - expected := []*v1.Pod{pods[2], pods[3], pods[4]} - kubelet.podManager.SetPods(pods) - actual := kubelet.filterOutTerminatedPods(pods) - assert.Equal(t, expected, actual) -} - -func TestSyncPodsSetStatusToFailedForPodsThatRunTooLong(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - fakeRuntime := testKubelet.fakeRuntime - testKubelet.fakeCadvisor.On("MachineInfo").Return(&cadvisorapi.MachineInfo{}, nil) - kubelet := testKubelet.kubelet - - now := metav1.Now() - startTime := metav1.NewTime(now.Time.Add(-1 * time.Minute)) - exceededActiveDeadlineSeconds := int64(30) - - pods := []*v1.Pod{ - { - ObjectMeta: metav1.ObjectMeta{ - UID: "12345678", - Name: "bar", - Namespace: "new", - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo"}, - }, - ActiveDeadlineSeconds: &exceededActiveDeadlineSeconds, - }, - Status: v1.PodStatus{ - StartTime: &startTime, - }, - }, - } - - fakeRuntime.PodList = []*containertest.FakePod{ - {Pod: &kubecontainer.Pod{ - ID: "12345678", - Name: "bar", - Namespace: "new", - Containers: []*kubecontainer.Container{ - {Name: "foo"}, - }, - }}, - } - - // Let the pod worker sets the status to fail after this sync. - kubelet.HandlePodUpdates(pods) - status, found := kubelet.statusManager.GetPodStatus(pods[0].UID) - assert.True(t, found, "expected to found status for pod %q", pods[0].UID) - assert.Equal(t, v1.PodFailed, status.Phase) -} - -func TestSyncPodsDoesNotSetPodsThatDidNotRunTooLongToFailed(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - fakeRuntime := testKubelet.fakeRuntime - testKubelet.chainMock() - - kubelet := testKubelet.kubelet - - now := metav1.Now() - startTime := metav1.NewTime(now.Time.Add(-1 * time.Minute)) - exceededActiveDeadlineSeconds := int64(300) - - pods := []*v1.Pod{ - { - ObjectMeta: metav1.ObjectMeta{ - UID: "12345678", - Name: "bar", - Namespace: "new", - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - {Name: "foo"}, - }, - ActiveDeadlineSeconds: &exceededActiveDeadlineSeconds, - }, - Status: v1.PodStatus{ - StartTime: &startTime, - }, - }, - } - - fakeRuntime.PodList = []*containertest.FakePod{ - {Pod: &kubecontainer.Pod{ - ID: "12345678", - Name: "bar", - Namespace: "new", - Containers: []*kubecontainer.Container{ - {Name: "foo"}, - }, - }}, - } - - kubelet.podManager.SetPods(pods) - kubelet.HandlePodUpdates(pods) - status, found := kubelet.statusManager.GetPodStatus(pods[0].UID) - assert.True(t, found, "expected to found status for pod %q", pods[0].UID) - assert.NotEqual(t, v1.PodFailed, status.Phase) -} - -func podWithUIDNameNs(uid types.UID, name, namespace string) *v1.Pod { - return &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - UID: uid, - Name: name, - Namespace: namespace, - Annotations: map[string]string{}, - }, - } -} - -func podWithUIDNameNsSpec(uid types.UID, name, namespace string, spec v1.PodSpec) *v1.Pod { - pod := podWithUIDNameNs(uid, name, namespace) - pod.Spec = spec - return pod -} - -func TestDeletePodDirsForDeletedPods(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kl := testKubelet.kubelet - pods := []*v1.Pod{ - podWithUIDNameNs("12345678", "pod1", "ns"), - podWithUIDNameNs("12345679", "pod2", "ns"), - } - - kl.podManager.SetPods(pods) - // Sync to create pod directories. - kl.HandlePodSyncs(kl.podManager.GetPods()) - for i := range pods { - assert.True(t, dirExists(kl.getPodDir(pods[i].UID)), "Expected directory to exist for pod %d", i) - } - - // Pod 1 has been deleted and no longer exists. - kl.podManager.SetPods([]*v1.Pod{pods[0]}) - kl.HandlePodCleanups() - assert.True(t, dirExists(kl.getPodDir(pods[0].UID)), "Expected directory to exist for pod 0") - assert.False(t, dirExists(kl.getPodDir(pods[1].UID)), "Expected directory to be deleted for pod 1") -} - -func syncAndVerifyPodDir(t *testing.T, testKubelet *TestKubelet, pods []*v1.Pod, podsToCheck []*v1.Pod, shouldExist bool) { - kl := testKubelet.kubelet - - kl.podManager.SetPods(pods) - kl.HandlePodSyncs(pods) - kl.HandlePodCleanups() - for i, pod := range podsToCheck { - exist := dirExists(kl.getPodDir(pod.UID)) - assert.Equal(t, shouldExist, exist, "directory of pod %d", i) - } -} - -func TestDoesNotDeletePodDirsForTerminatedPods(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kl := testKubelet.kubelet - pods := []*v1.Pod{ - podWithUIDNameNs("12345678", "pod1", "ns"), - podWithUIDNameNs("12345679", "pod2", "ns"), - podWithUIDNameNs("12345680", "pod3", "ns"), - } - - syncAndVerifyPodDir(t, testKubelet, pods, pods, true) - // Pod 1 failed, and pod 2 succeeded. None of the pod directories should be - // deleted. - kl.statusManager.SetPodStatus(pods[1], v1.PodStatus{Phase: v1.PodFailed}) - kl.statusManager.SetPodStatus(pods[2], v1.PodStatus{Phase: v1.PodSucceeded}) - syncAndVerifyPodDir(t, testKubelet, pods, pods, true) -} - -func TestDoesNotDeletePodDirsIfContainerIsRunning(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - runningPod := &kubecontainer.Pod{ - ID: "12345678", - Name: "pod1", - Namespace: "ns", - } - apiPod := podWithUIDNameNs(runningPod.ID, runningPod.Name, runningPod.Namespace) - - // Sync once to create pod directory; confirm that the pod directory has - // already been created. - pods := []*v1.Pod{apiPod} - syncAndVerifyPodDir(t, testKubelet, pods, []*v1.Pod{apiPod}, true) - - // Pretend the pod is deleted from apiserver, but is still active on the node. - // The pod directory should not be removed. - pods = []*v1.Pod{} - testKubelet.fakeRuntime.PodList = []*containertest.FakePod{{runningPod, ""}} - syncAndVerifyPodDir(t, testKubelet, pods, []*v1.Pod{apiPod}, true) - - // The pod is deleted and also not active on the node. The pod directory - // should be removed. - pods = []*v1.Pod{} - testKubelet.fakeRuntime.PodList = []*containertest.FakePod{} - syncAndVerifyPodDir(t, testKubelet, pods, []*v1.Pod{apiPod}, false) -} - -func TestGetPodsToSync(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - clock := testKubelet.fakeClock - pods := newTestPods(5) - - exceededActiveDeadlineSeconds := int64(30) - notYetActiveDeadlineSeconds := int64(120) - startTime := metav1.NewTime(clock.Now()) - pods[0].Status.StartTime = &startTime - pods[0].Spec.ActiveDeadlineSeconds = &exceededActiveDeadlineSeconds - pods[1].Status.StartTime = &startTime - pods[1].Spec.ActiveDeadlineSeconds = &notYetActiveDeadlineSeconds - pods[2].Status.StartTime = &startTime - pods[2].Spec.ActiveDeadlineSeconds = &exceededActiveDeadlineSeconds - - kubelet.podManager.SetPods(pods) - kubelet.workQueue.Enqueue(pods[2].UID, 0) - kubelet.workQueue.Enqueue(pods[3].UID, 30*time.Second) - kubelet.workQueue.Enqueue(pods[4].UID, 2*time.Minute) - - clock.Step(1 * time.Minute) - - expected := []*v1.Pod{pods[2], pods[3], pods[0]} - podsToSync := kubelet.getPodsToSync() - sort.Sort(podsByUID(expected)) - sort.Sort(podsByUID(podsToSync)) - assert.Equal(t, expected, podsToSync) -} - -func TestGenerateAPIPodStatusWithSortedContainers(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kubelet := testKubelet.kubelet - numContainers := 10 - expectedOrder := []string{} - cStatuses := []*kubecontainer.ContainerStatus{} - specContainerList := []v1.Container{} - for i := 0; i < numContainers; i++ { - id := fmt.Sprintf("%v", i) - containerName := fmt.Sprintf("%vcontainer", id) - expectedOrder = append(expectedOrder, containerName) - cStatus := &kubecontainer.ContainerStatus{ - ID: kubecontainer.BuildContainerID("test", id), - Name: containerName, - } - // Rearrange container statuses - if i%2 == 0 { - cStatuses = append(cStatuses, cStatus) - } else { - cStatuses = append([]*kubecontainer.ContainerStatus{cStatus}, cStatuses...) - } - specContainerList = append(specContainerList, v1.Container{Name: containerName}) - } - pod := podWithUIDNameNs("uid1", "foo", "test") - pod.Spec = v1.PodSpec{ - Containers: specContainerList, - } - - status := &kubecontainer.PodStatus{ - ID: pod.UID, - Name: pod.Name, - Namespace: pod.Namespace, - ContainerStatuses: cStatuses, - } - for i := 0; i < 5; i++ { - apiStatus := kubelet.generateAPIPodStatus(pod, status) - for i, c := range apiStatus.ContainerStatuses { - if expectedOrder[i] != c.Name { - t.Fatalf("Container status not sorted, expected %v at index %d, but found %v", expectedOrder[i], i, c.Name) - } - } - } -} - -func verifyContainerStatuses(t *testing.T, statuses []v1.ContainerStatus, state, lastTerminationState map[string]v1.ContainerState, message string) { - for _, s := range statuses { - assert.Equal(t, s.State, state[s.Name], "%s: state", message) - assert.Equal(t, s.LastTerminationState, lastTerminationState[s.Name], "%s: last terminated state", message) - } -} - -// Test generateAPIPodStatus with different reason cache and old api pod status. -func TestGenerateAPIPodStatusWithReasonCache(t *testing.T) { - // The following waiting reason and message are generated in convertStatusToAPIStatus() - startWaitingReason := "ContainerCreating" - initWaitingReason := "PodInitializing" - testTimestamp := time.Unix(123456789, 987654321) - testErrorReason := fmt.Errorf("test-error") - emptyContainerID := (&kubecontainer.ContainerID{}).String() - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kubelet := testKubelet.kubelet - pod := podWithUIDNameNs("12345678", "foo", "new") - pod.Spec = v1.PodSpec{RestartPolicy: v1.RestartPolicyOnFailure} - - podStatus := &kubecontainer.PodStatus{ - ID: pod.UID, - Name: pod.Name, - Namespace: pod.Namespace, - } - tests := []struct { - containers []v1.Container - statuses []*kubecontainer.ContainerStatus - reasons map[string]error - oldStatuses []v1.ContainerStatus - expectedState map[string]v1.ContainerState - // Only set expectedInitState when it is different from expectedState - expectedInitState map[string]v1.ContainerState - expectedLastTerminationState map[string]v1.ContainerState - }{ - // For container with no historical record, State should be Waiting, LastTerminationState should be retrieved from - // old status from apiserver. - { - containers: []v1.Container{{Name: "without-old-record"}, {Name: "with-old-record"}}, - statuses: []*kubecontainer.ContainerStatus{}, - reasons: map[string]error{}, - oldStatuses: []v1.ContainerStatus{{ - Name: "with-old-record", - LastTerminationState: v1.ContainerState{Terminated: &v1.ContainerStateTerminated{}}, - }}, - expectedState: map[string]v1.ContainerState{ - "without-old-record": {Waiting: &v1.ContainerStateWaiting{ - Reason: startWaitingReason, - }}, - "with-old-record": {Waiting: &v1.ContainerStateWaiting{ - Reason: startWaitingReason, - }}, - }, - expectedInitState: map[string]v1.ContainerState{ - "without-old-record": {Waiting: &v1.ContainerStateWaiting{ - Reason: initWaitingReason, - }}, - "with-old-record": {Waiting: &v1.ContainerStateWaiting{ - Reason: initWaitingReason, - }}, - }, - expectedLastTerminationState: map[string]v1.ContainerState{ - "with-old-record": {Terminated: &v1.ContainerStateTerminated{}}, - }, - }, - // For running container, State should be Running, LastTerminationState should be retrieved from latest terminated status. - { - containers: []v1.Container{{Name: "running"}}, - statuses: []*kubecontainer.ContainerStatus{ - { - Name: "running", - State: kubecontainer.ContainerStateRunning, - StartedAt: testTimestamp, - }, - { - Name: "running", - State: kubecontainer.ContainerStateExited, - ExitCode: 1, - }, - }, - reasons: map[string]error{}, - oldStatuses: []v1.ContainerStatus{}, - expectedState: map[string]v1.ContainerState{ - "running": {Running: &v1.ContainerStateRunning{ - StartedAt: metav1.NewTime(testTimestamp), - }}, - }, - expectedLastTerminationState: map[string]v1.ContainerState{ - "running": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 1, - ContainerID: emptyContainerID, - }}, - }, - }, - // For terminated container: - // * If there is no recent start error record, State should be Terminated, LastTerminationState should be retrieved from - // second latest terminated status; - // * If there is recent start error record, State should be Waiting, LastTerminationState should be retrieved from latest - // terminated status; - // * If ExitCode = 0, restart policy is RestartPolicyOnFailure, the container shouldn't be restarted. No matter there is - // recent start error or not, State should be Terminated, LastTerminationState should be retrieved from second latest - // terminated status. - { - containers: []v1.Container{{Name: "without-reason"}, {Name: "with-reason"}}, - statuses: []*kubecontainer.ContainerStatus{ - { - Name: "without-reason", - State: kubecontainer.ContainerStateExited, - ExitCode: 1, - }, - { - Name: "with-reason", - State: kubecontainer.ContainerStateExited, - ExitCode: 2, - }, - { - Name: "without-reason", - State: kubecontainer.ContainerStateExited, - ExitCode: 3, - }, - { - Name: "with-reason", - State: kubecontainer.ContainerStateExited, - ExitCode: 4, - }, - { - Name: "succeed", - State: kubecontainer.ContainerStateExited, - ExitCode: 0, - }, - { - Name: "succeed", - State: kubecontainer.ContainerStateExited, - ExitCode: 5, - }, - }, - reasons: map[string]error{"with-reason": testErrorReason, "succeed": testErrorReason}, - oldStatuses: []v1.ContainerStatus{}, - expectedState: map[string]v1.ContainerState{ - "without-reason": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 1, - ContainerID: emptyContainerID, - }}, - "with-reason": {Waiting: &v1.ContainerStateWaiting{Reason: testErrorReason.Error()}}, - "succeed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 0, - ContainerID: emptyContainerID, - }}, - }, - expectedLastTerminationState: map[string]v1.ContainerState{ - "without-reason": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 3, - ContainerID: emptyContainerID, - }}, - "with-reason": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 2, - ContainerID: emptyContainerID, - }}, - "succeed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 5, - ContainerID: emptyContainerID, - }}, - }, - }, - } - - for i, test := range tests { - kubelet.reasonCache = NewReasonCache() - for n, e := range test.reasons { - kubelet.reasonCache.add(pod.UID, n, e, "") - } - pod.Spec.Containers = test.containers - pod.Status.ContainerStatuses = test.oldStatuses - podStatus.ContainerStatuses = test.statuses - apiStatus := kubelet.generateAPIPodStatus(pod, podStatus) - verifyContainerStatuses(t, apiStatus.ContainerStatuses, test.expectedState, test.expectedLastTerminationState, fmt.Sprintf("case %d", i)) - } - - // Everything should be the same for init containers - for i, test := range tests { - kubelet.reasonCache = NewReasonCache() - for n, e := range test.reasons { - kubelet.reasonCache.add(pod.UID, n, e, "") - } - pod.Spec.InitContainers = test.containers - pod.Status.InitContainerStatuses = test.oldStatuses - podStatus.ContainerStatuses = test.statuses - apiStatus := kubelet.generateAPIPodStatus(pod, podStatus) - expectedState := test.expectedState - if test.expectedInitState != nil { - expectedState = test.expectedInitState - } - verifyContainerStatuses(t, apiStatus.InitContainerStatuses, expectedState, test.expectedLastTerminationState, fmt.Sprintf("case %d", i)) - } -} - -// Test generateAPIPodStatus with different restart policies. -func TestGenerateAPIPodStatusWithDifferentRestartPolicies(t *testing.T) { - testErrorReason := fmt.Errorf("test-error") - emptyContainerID := (&kubecontainer.ContainerID{}).String() - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kubelet := testKubelet.kubelet - pod := podWithUIDNameNs("12345678", "foo", "new") - containers := []v1.Container{{Name: "succeed"}, {Name: "failed"}} - podStatus := &kubecontainer.PodStatus{ - ID: pod.UID, - Name: pod.Name, - Namespace: pod.Namespace, - ContainerStatuses: []*kubecontainer.ContainerStatus{ - { - Name: "succeed", - State: kubecontainer.ContainerStateExited, - ExitCode: 0, - }, - { - Name: "failed", - State: kubecontainer.ContainerStateExited, - ExitCode: 1, - }, - { - Name: "succeed", - State: kubecontainer.ContainerStateExited, - ExitCode: 2, - }, - { - Name: "failed", - State: kubecontainer.ContainerStateExited, - ExitCode: 3, - }, - }, - } - kubelet.reasonCache.add(pod.UID, "succeed", testErrorReason, "") - kubelet.reasonCache.add(pod.UID, "failed", testErrorReason, "") - for c, test := range []struct { - restartPolicy v1.RestartPolicy - expectedState map[string]v1.ContainerState - expectedLastTerminationState map[string]v1.ContainerState - // Only set expectedInitState when it is different from expectedState - expectedInitState map[string]v1.ContainerState - // Only set expectedInitLastTerminationState when it is different from expectedLastTerminationState - expectedInitLastTerminationState map[string]v1.ContainerState - }{ - { - restartPolicy: v1.RestartPolicyNever, - expectedState: map[string]v1.ContainerState{ - "succeed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 0, - ContainerID: emptyContainerID, - }}, - "failed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 1, - ContainerID: emptyContainerID, - }}, - }, - expectedLastTerminationState: map[string]v1.ContainerState{ - "succeed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 2, - ContainerID: emptyContainerID, - }}, - "failed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 3, - ContainerID: emptyContainerID, - }}, - }, - }, - { - restartPolicy: v1.RestartPolicyOnFailure, - expectedState: map[string]v1.ContainerState{ - "succeed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 0, - ContainerID: emptyContainerID, - }}, - "failed": {Waiting: &v1.ContainerStateWaiting{Reason: testErrorReason.Error()}}, - }, - expectedLastTerminationState: map[string]v1.ContainerState{ - "succeed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 2, - ContainerID: emptyContainerID, - }}, - "failed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 1, - ContainerID: emptyContainerID, - }}, - }, - }, - { - restartPolicy: v1.RestartPolicyAlways, - expectedState: map[string]v1.ContainerState{ - "succeed": {Waiting: &v1.ContainerStateWaiting{Reason: testErrorReason.Error()}}, - "failed": {Waiting: &v1.ContainerStateWaiting{Reason: testErrorReason.Error()}}, - }, - expectedLastTerminationState: map[string]v1.ContainerState{ - "succeed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 0, - ContainerID: emptyContainerID, - }}, - "failed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 1, - ContainerID: emptyContainerID, - }}, - }, - // If the init container is terminated with exit code 0, it won't be restarted even when the - // restart policy is RestartAlways. - expectedInitState: map[string]v1.ContainerState{ - "succeed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 0, - ContainerID: emptyContainerID, - }}, - "failed": {Waiting: &v1.ContainerStateWaiting{Reason: testErrorReason.Error()}}, - }, - expectedInitLastTerminationState: map[string]v1.ContainerState{ - "succeed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 2, - ContainerID: emptyContainerID, - }}, - "failed": {Terminated: &v1.ContainerStateTerminated{ - ExitCode: 1, - ContainerID: emptyContainerID, - }}, - }, - }, - } { - pod.Spec.RestartPolicy = test.restartPolicy - // Test normal containers - pod.Spec.Containers = containers - apiStatus := kubelet.generateAPIPodStatus(pod, podStatus) - expectedState, expectedLastTerminationState := test.expectedState, test.expectedLastTerminationState - verifyContainerStatuses(t, apiStatus.ContainerStatuses, expectedState, expectedLastTerminationState, fmt.Sprintf("case %d", c)) - pod.Spec.Containers = nil - - // Test init containers - pod.Spec.InitContainers = containers - apiStatus = kubelet.generateAPIPodStatus(pod, podStatus) - if test.expectedInitState != nil { - expectedState = test.expectedInitState - } - if test.expectedInitLastTerminationState != nil { - expectedLastTerminationState = test.expectedInitLastTerminationState - } - verifyContainerStatuses(t, apiStatus.InitContainerStatuses, expectedState, expectedLastTerminationState, fmt.Sprintf("case %d", c)) - pod.Spec.InitContainers = nil - } -} - -// testPodAdmitHandler is a lifecycle.PodAdmitHandler for testing. -type testPodAdmitHandler struct { - // list of pods to reject. - podsToReject []*v1.Pod -} - -// Admit rejects all pods in the podsToReject list with a matching UID. -func (a *testPodAdmitHandler) Admit(attrs *lifecycle.PodAdmitAttributes) lifecycle.PodAdmitResult { - for _, podToReject := range a.podsToReject { - if podToReject.UID == attrs.Pod.UID { - return lifecycle.PodAdmitResult{Admit: false, Reason: "Rejected", Message: "Pod is rejected"} - } - } - return lifecycle.PodAdmitResult{Admit: true} -} - -// Test verifies that the kubelet invokes an admission handler during HandlePodAdditions. -func TestHandlePodAdditionsInvokesPodAdmitHandlers(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - testKubelet.chainMock() - kl := testKubelet.kubelet - kl.nodeInfo = testNodeInfo{nodes: []*v1.Node{ - { - ObjectMeta: metav1.ObjectMeta{Name: string(kl.nodeName)}, - Status: v1.NodeStatus{ - Allocatable: v1.ResourceList{ - v1.ResourcePods: *resource.NewQuantity(110, resource.DecimalSI), - }, - }, - }, - }} - - pods := []*v1.Pod{ - { - ObjectMeta: metav1.ObjectMeta{ - UID: "123456789", - Name: "podA", - Namespace: "foo", - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - UID: "987654321", - Name: "podB", - Namespace: "foo", - }, - }, - } - podToReject := pods[0] - podToAdmit := pods[1] - podsToReject := []*v1.Pod{podToReject} - - kl.admitHandlers.AddPodAdmitHandler(&testPodAdmitHandler{podsToReject: podsToReject}) - - kl.HandlePodAdditions(pods) - - // Check pod status stored in the status map. - checkPodStatus(t, kl, podToReject, v1.PodFailed) - checkPodStatus(t, kl, podToAdmit, v1.PodPending) -} - -// testPodSyncLoopHandler is a lifecycle.PodSyncLoopHandler that is used for testing. -type testPodSyncLoopHandler struct { - // list of pods to sync - podsToSync []*v1.Pod -} - -// ShouldSync evaluates if the pod should be synced from the kubelet. -func (a *testPodSyncLoopHandler) ShouldSync(pod *v1.Pod) bool { - for _, podToSync := range a.podsToSync { - if podToSync.UID == pod.UID { - return true - } - } - return false -} - -// TestGetPodsToSyncInvokesPodSyncLoopHandlers ensures that the get pods to sync routine invokes the handler. -func TestGetPodsToSyncInvokesPodSyncLoopHandlers(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - pods := newTestPods(5) - expected := []*v1.Pod{pods[0]} - kubelet.AddPodSyncLoopHandler(&testPodSyncLoopHandler{expected}) - kubelet.podManager.SetPods(pods) - - podsToSync := kubelet.getPodsToSync() - sort.Sort(podsByUID(expected)) - sort.Sort(podsByUID(podsToSync)) - assert.Equal(t, expected, podsToSync) -} - -// testPodSyncHandler is a lifecycle.PodSyncHandler that is used for testing. -type testPodSyncHandler struct { - // list of pods to evict. - podsToEvict []*v1.Pod - // the reason for the eviction - reason string - // the message for the eviction - message string -} - -// ShouldEvict evaluates if the pod should be evicted from the kubelet. -func (a *testPodSyncHandler) ShouldEvict(pod *v1.Pod) lifecycle.ShouldEvictResponse { - for _, podToEvict := range a.podsToEvict { - if podToEvict.UID == pod.UID { - return lifecycle.ShouldEvictResponse{Evict: true, Reason: a.reason, Message: a.message} - } - } - return lifecycle.ShouldEvictResponse{Evict: false} -} - -// TestGenerateAPIPodStatusInvokesPodSyncHandlers invokes the handlers and reports the proper status -func TestGenerateAPIPodStatusInvokesPodSyncHandlers(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - pod := newTestPods(1)[0] - podsToEvict := []*v1.Pod{pod} - kubelet.AddPodSyncHandler(&testPodSyncHandler{podsToEvict, "Evicted", "because"}) - status := &kubecontainer.PodStatus{ - ID: pod.UID, - Name: pod.Name, - Namespace: pod.Namespace, - } - apiStatus := kubelet.generateAPIPodStatus(pod, status) - require.Equal(t, v1.PodFailed, apiStatus.Phase) - require.Equal(t, "Evicted", apiStatus.Reason) - require.Equal(t, "because", apiStatus.Message) -} - -func TestSyncPodKillPod(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kl := testKubelet.kubelet - pod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - UID: "12345678", - Name: "bar", - Namespace: "foo", - }, - } - pods := []*v1.Pod{pod} - kl.podManager.SetPods(pods) - gracePeriodOverride := int64(0) - err := kl.syncPod(syncPodOptions{ - pod: pod, - podStatus: &kubecontainer.PodStatus{}, - updateType: kubetypes.SyncPodKill, - killPodOptions: &KillPodOptions{ - PodStatusFunc: func(p *v1.Pod, podStatus *kubecontainer.PodStatus) v1.PodStatus { - return v1.PodStatus{ - Phase: v1.PodFailed, - Reason: "reason", - Message: "message", - } - }, - PodTerminationGracePeriodSecondsOverride: &gracePeriodOverride, - }, - }) - require.NoError(t, err) - - // Check pod status stored in the status map. - checkPodStatus(t, kl, pod, v1.PodFailed) -} - -func waitForVolumeUnmount( - volumeManager kubeletvolume.VolumeManager, - pod *v1.Pod) error { - var podVolumes kubecontainer.VolumeMap - err := retryWithExponentialBackOff( - time.Duration(50*time.Millisecond), - func() (bool, error) { - // Verify volumes detached - podVolumes = volumeManager.GetMountedVolumesForPod( - util.GetUniquePodName(pod)) - - if len(podVolumes) != 0 { - return false, nil - } - - return true, nil - }, - ) - - if err != nil { - return fmt.Errorf( - "Expected volumes to be unmounted. But some volumes are still mounted: %#v", podVolumes) - } - - return nil -} - -func waitForVolumeDetach( - volumeName v1.UniqueVolumeName, - volumeManager kubeletvolume.VolumeManager) error { - attachedVolumes := []v1.UniqueVolumeName{} - err := retryWithExponentialBackOff( - time.Duration(50*time.Millisecond), - func() (bool, error) { - // Verify volumes detached - volumeAttached := volumeManager.VolumeIsAttached(volumeName) - return !volumeAttached, nil - }, - ) - - if err != nil { - return fmt.Errorf( - "Expected volumes to be detached. But some volumes are still attached: %#v", attachedVolumes) - } - - return nil -} - -func retryWithExponentialBackOff(initialDuration time.Duration, fn wait.ConditionFunc) error { - backoff := wait.Backoff{ - Duration: initialDuration, - Factor: 3, - Jitter: 0, - Steps: 6, - } - return wait.ExponentialBackoff(backoff, fn) -} - -func simulateVolumeInUseUpdate( - volumeName v1.UniqueVolumeName, - stopCh <-chan struct{}, - volumeManager kubeletvolume.VolumeManager) { - ticker := time.NewTicker(100 * time.Millisecond) - defer ticker.Stop() - for { - select { - case <-ticker.C: - volumeManager.MarkVolumesAsReportedInUse( - []v1.UniqueVolumeName{volumeName}) - case <-stopCh: - return - } - } -} - -func runVolumeManager(kubelet *Kubelet) chan struct{} { - stopCh := make(chan struct{}) - go kubelet.volumeManager.Run(kubelet.sourcesReady, stopCh) - return stopCh -} - -// Sort pods by UID. -type podsByUID []*v1.Pod - -func (p podsByUID) Len() int { return len(p) } -func (p podsByUID) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -func (p podsByUID) Less(i, j int) bool { return p[i].UID < p[j].UID } diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_volumes_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_volumes_test.go deleted file mode 100644 index dc2c89a660..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/kubelet_volumes_test.go +++ /dev/null @@ -1,470 +0,0 @@ -/* -Copyright 2016 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 kubelet - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/assert" - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - core "k8s.io/client-go/testing" - "k8s.io/kubernetes/pkg/volume" - volumetest "k8s.io/kubernetes/pkg/volume/testing" - "k8s.io/kubernetes/pkg/volume/util" -) - -func TestListVolumesForPod(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - - pod := podWithUIDNameNsSpec("12345678", "foo", "test", v1.PodSpec{ - Volumes: []v1.Volume{ - { - Name: "vol1", - VolumeSource: v1.VolumeSource{ - GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ - PDName: "fake-device1", - }, - }, - }, - { - Name: "vol2", - VolumeSource: v1.VolumeSource{ - GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ - PDName: "fake-device2", - }, - }, - }, - }, - }) - - stopCh := runVolumeManager(kubelet) - defer close(stopCh) - - kubelet.podManager.SetPods([]*v1.Pod{pod}) - err := kubelet.volumeManager.WaitForAttachAndMount(pod) - assert.NoError(t, err) - - podName := util.GetUniquePodName(pod) - - volumesToReturn, volumeExsit := kubelet.ListVolumesForPod(types.UID(podName)) - assert.True(t, volumeExsit, "expected to find volumes for pod %q", podName) - - outerVolumeSpecName1 := "vol1" - assert.NotNil(t, volumesToReturn[outerVolumeSpecName1], "key %s", outerVolumeSpecName1) - - outerVolumeSpecName2 := "vol2" - assert.NotNil(t, volumesToReturn[outerVolumeSpecName2], "key %s", outerVolumeSpecName2) - -} - -func TestPodVolumesExist(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - - pods := []*v1.Pod{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "pod1", - UID: "pod1uid", - }, - Spec: v1.PodSpec{ - Volumes: []v1.Volume{ - { - Name: "vol1", - VolumeSource: v1.VolumeSource{ - GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ - PDName: "fake-device1", - }, - }, - }, - }, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "pod2", - UID: "pod2uid", - }, - Spec: v1.PodSpec{ - Volumes: []v1.Volume{ - { - Name: "vol2", - VolumeSource: v1.VolumeSource{ - GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ - PDName: "fake-device2", - }, - }, - }, - }, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "pod3", - UID: "pod3uid", - }, - Spec: v1.PodSpec{ - Volumes: []v1.Volume{ - { - Name: "vol3", - VolumeSource: v1.VolumeSource{ - GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ - PDName: "fake-device3", - }, - }, - }, - }, - }, - }, - } - - stopCh := runVolumeManager(kubelet) - defer close(stopCh) - - kubelet.podManager.SetPods(pods) - for _, pod := range pods { - err := kubelet.volumeManager.WaitForAttachAndMount(pod) - assert.NoError(t, err) - } - - for _, pod := range pods { - podVolumesExist := kubelet.podVolumesExist(pod.UID) - assert.True(t, podVolumesExist, "pod %q", pod.UID) - } -} - -func TestVolumeAttachAndMountControllerDisabled(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - - pod := podWithUIDNameNsSpec("12345678", "foo", "test", v1.PodSpec{ - Volumes: []v1.Volume{ - { - Name: "vol1", - VolumeSource: v1.VolumeSource{ - GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ - PDName: "fake-device", - }, - }, - }, - }, - }) - - stopCh := runVolumeManager(kubelet) - defer close(stopCh) - - kubelet.podManager.SetPods([]*v1.Pod{pod}) - err := kubelet.volumeManager.WaitForAttachAndMount(pod) - assert.NoError(t, err) - - podVolumes := kubelet.volumeManager.GetMountedVolumesForPod( - util.GetUniquePodName(pod)) - - expectedPodVolumes := []string{"vol1"} - assert.Len(t, podVolumes, len(expectedPodVolumes), "Volumes for pod %+v", pod) - for _, name := range expectedPodVolumes { - assert.Contains(t, podVolumes, name, "Volumes for pod %+v", pod) - } - assert.True(t, testKubelet.volumePlugin.GetNewAttacherCallCount() >= 1, "Expected plugin NewAttacher to be called at least once") - assert.NoError(t, volumetest.VerifyWaitForAttachCallCount( - 1 /* expectedWaitForAttachCallCount */, testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifyAttachCallCount( - 1 /* expectedAttachCallCount */, testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifyMountDeviceCallCount( - 1 /* expectedMountDeviceCallCount */, testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifySetUpCallCount( - 1 /* expectedSetUpCallCount */, testKubelet.volumePlugin)) -} - -func TestVolumeUnmountAndDetachControllerDisabled(t *testing.T) { - testKubelet := newTestKubelet(t, false /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - - pod := podWithUIDNameNsSpec("12345678", "foo", "test", v1.PodSpec{ - Volumes: []v1.Volume{ - { - Name: "vol1", - VolumeSource: v1.VolumeSource{ - GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ - PDName: "fake-device", - }, - }, - }, - }, - }) - - stopCh := runVolumeManager(kubelet) - defer close(stopCh) - - // Add pod - kubelet.podManager.SetPods([]*v1.Pod{pod}) - - // Verify volumes attached - err := kubelet.volumeManager.WaitForAttachAndMount(pod) - assert.NoError(t, err) - - podVolumes := kubelet.volumeManager.GetMountedVolumesForPod( - util.GetUniquePodName(pod)) - - expectedPodVolumes := []string{"vol1"} - assert.Len(t, podVolumes, len(expectedPodVolumes), "Volumes for pod %+v", pod) - for _, name := range expectedPodVolumes { - assert.Contains(t, podVolumes, name, "Volumes for pod %+v", pod) - } - - assert.True(t, testKubelet.volumePlugin.GetNewAttacherCallCount() >= 1, "Expected plugin NewAttacher to be called at least once") - assert.NoError(t, volumetest.VerifyWaitForAttachCallCount( - 1 /* expectedWaitForAttachCallCount */, testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifyAttachCallCount( - 1 /* expectedAttachCallCount */, testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifyMountDeviceCallCount( - 1 /* expectedMountDeviceCallCount */, testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifySetUpCallCount( - 1 /* expectedSetUpCallCount */, testKubelet.volumePlugin)) - - // Remove pod - kubelet.podManager.SetPods([]*v1.Pod{}) - - assert.NoError(t, waitForVolumeUnmount(kubelet.volumeManager, pod)) - - // Verify volumes unmounted - podVolumes = kubelet.volumeManager.GetMountedVolumesForPod( - util.GetUniquePodName(pod)) - - assert.Len(t, podVolumes, 0, - "Expected volumes to be unmounted and detached. But some volumes are still mounted: %#v", podVolumes) - - assert.NoError(t, volumetest.VerifyTearDownCallCount( - 1 /* expectedTearDownCallCount */, testKubelet.volumePlugin)) - - // Verify volumes detached and no longer reported as in use - assert.NoError(t, waitForVolumeDetach(v1.UniqueVolumeName("fake/vol1"), kubelet.volumeManager)) - assert.True(t, testKubelet.volumePlugin.GetNewAttacherCallCount() >= 1, "Expected plugin NewAttacher to be called at least once") - assert.NoError(t, volumetest.VerifyDetachCallCount( - 1 /* expectedDetachCallCount */, testKubelet.volumePlugin)) -} - -func TestVolumeAttachAndMountControllerEnabled(t *testing.T) { - testKubelet := newTestKubelet(t, true /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubeClient := testKubelet.fakeKubeClient - kubeClient.AddReactor("get", "nodes", - func(action core.Action) (bool, runtime.Object, error) { - return true, &v1.Node{ - ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}, - Status: v1.NodeStatus{ - VolumesAttached: []v1.AttachedVolume{ - { - Name: "fake/vol1", - DevicePath: "fake/path", - }, - }}, - Spec: v1.NodeSpec{ExternalID: testKubeletHostname}, - }, nil - }) - kubeClient.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { - return true, nil, fmt.Errorf("no reaction implemented for %s", action) - }) - - pod := podWithUIDNameNsSpec("12345678", "foo", "test", v1.PodSpec{ - Volumes: []v1.Volume{ - { - Name: "vol1", - VolumeSource: v1.VolumeSource{ - GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ - PDName: "fake-device", - }, - }, - }, - }, - }) - - stopCh := runVolumeManager(kubelet) - defer close(stopCh) - - kubelet.podManager.SetPods([]*v1.Pod{pod}) - - // Fake node status update - go simulateVolumeInUseUpdate( - v1.UniqueVolumeName("fake/vol1"), - stopCh, - kubelet.volumeManager) - - assert.NoError(t, kubelet.volumeManager.WaitForAttachAndMount(pod)) - - podVolumes := kubelet.volumeManager.GetMountedVolumesForPod( - util.GetUniquePodName(pod)) - - expectedPodVolumes := []string{"vol1"} - assert.Len(t, podVolumes, len(expectedPodVolumes), "Volumes for pod %+v", pod) - for _, name := range expectedPodVolumes { - assert.Contains(t, podVolumes, name, "Volumes for pod %+v", pod) - } - assert.True(t, testKubelet.volumePlugin.GetNewAttacherCallCount() >= 1, "Expected plugin NewAttacher to be called at least once") - assert.NoError(t, volumetest.VerifyWaitForAttachCallCount( - 1 /* expectedWaitForAttachCallCount */, testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifyZeroAttachCalls(testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifyMountDeviceCallCount( - 1 /* expectedMountDeviceCallCount */, testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifySetUpCallCount( - 1 /* expectedSetUpCallCount */, testKubelet.volumePlugin)) -} - -func TestVolumeUnmountAndDetachControllerEnabled(t *testing.T) { - testKubelet := newTestKubelet(t, true /* controllerAttachDetachEnabled */) - defer testKubelet.Cleanup() - kubelet := testKubelet.kubelet - kubeClient := testKubelet.fakeKubeClient - kubeClient.AddReactor("get", "nodes", - func(action core.Action) (bool, runtime.Object, error) { - return true, &v1.Node{ - ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}, - Status: v1.NodeStatus{ - VolumesAttached: []v1.AttachedVolume{ - { - Name: "fake/vol1", - DevicePath: "fake/path", - }, - }}, - Spec: v1.NodeSpec{ExternalID: testKubeletHostname}, - }, nil - }) - kubeClient.AddReactor("*", "*", func(action core.Action) (bool, runtime.Object, error) { - return true, nil, fmt.Errorf("no reaction implemented for %s", action) - }) - - pod := podWithUIDNameNsSpec("12345678", "foo", "test", v1.PodSpec{ - Volumes: []v1.Volume{ - { - Name: "vol1", - VolumeSource: v1.VolumeSource{ - GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{ - PDName: "fake-device", - }, - }, - }, - }, - }) - - stopCh := runVolumeManager(kubelet) - defer close(stopCh) - - // Add pod - kubelet.podManager.SetPods([]*v1.Pod{pod}) - - // Fake node status update - go simulateVolumeInUseUpdate( - v1.UniqueVolumeName("fake/vol1"), - stopCh, - kubelet.volumeManager) - - // Verify volumes attached - assert.NoError(t, kubelet.volumeManager.WaitForAttachAndMount(pod)) - - podVolumes := kubelet.volumeManager.GetMountedVolumesForPod( - util.GetUniquePodName(pod)) - - expectedPodVolumes := []string{"vol1"} - assert.Len(t, podVolumes, len(expectedPodVolumes), "Volumes for pod %+v", pod) - for _, name := range expectedPodVolumes { - assert.Contains(t, podVolumes, name, "Volumes for pod %+v", pod) - } - - assert.True(t, testKubelet.volumePlugin.GetNewAttacherCallCount() >= 1, "Expected plugin NewAttacher to be called at least once") - assert.NoError(t, volumetest.VerifyWaitForAttachCallCount( - 1 /* expectedWaitForAttachCallCount */, testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifyZeroAttachCalls(testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifyMountDeviceCallCount( - 1 /* expectedMountDeviceCallCount */, testKubelet.volumePlugin)) - assert.NoError(t, volumetest.VerifySetUpCallCount( - 1 /* expectedSetUpCallCount */, testKubelet.volumePlugin)) - - // Remove pod - kubelet.podManager.SetPods([]*v1.Pod{}) - - assert.NoError(t, waitForVolumeUnmount(kubelet.volumeManager, pod)) - - // Verify volumes unmounted - podVolumes = kubelet.volumeManager.GetMountedVolumesForPod( - util.GetUniquePodName(pod)) - - assert.Len(t, podVolumes, 0, - "Expected volumes to be unmounted and detached. But some volumes are still mounted: %#v", podVolumes) - - assert.NoError(t, volumetest.VerifyTearDownCallCount( - 1 /* expectedTearDownCallCount */, testKubelet.volumePlugin)) - - // Verify volumes detached and no longer reported as in use - assert.NoError(t, waitForVolumeDetach(v1.UniqueVolumeName("fake/vol1"), kubelet.volumeManager)) - assert.True(t, testKubelet.volumePlugin.GetNewAttacherCallCount() >= 1, "Expected plugin NewAttacher to be called at least once") - assert.NoError(t, volumetest.VerifyZeroDetachCallCount(testKubelet.volumePlugin)) -} - -type stubVolume struct { - path string - volume.MetricsNil -} - -func (f *stubVolume) GetPath() string { - return f.path -} - -func (f *stubVolume) GetAttributes() volume.Attributes { - return volume.Attributes{} -} - -func (f *stubVolume) CanMount() error { - return nil -} - -func (f *stubVolume) SetUp(fsGroup *int64) error { - return nil -} - -func (f *stubVolume) SetUpAt(dir string, fsGroup *int64) error { - return nil -} - -type stubBlockVolume struct { - dirPath string - volName string -} - -func (f *stubBlockVolume) GetGlobalMapPath(spec *volume.Spec) (string, error) { - return "", nil -} - -func (f *stubBlockVolume) GetPodDeviceMapPath() (string, string) { - return f.dirPath, f.volName -} - -func (f *stubBlockVolume) SetUpDevice() (string, error) { - return "", nil -} -func (f *stubBlockVolume) TearDownDevice(mapPath string, devicePath string) error { - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/oom_watcher_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/oom_watcher_test.go deleted file mode 100644 index 6fd0287e57..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/oom_watcher_test.go +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package kubelet - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "k8s.io/api/core/v1" - "k8s.io/client-go/tools/record" - cadvisortest "k8s.io/kubernetes/pkg/kubelet/cadvisor/testing" -) - -func TestBasic(t *testing.T) { - fakeRecorder := &record.FakeRecorder{} - mockCadvisor := &cadvisortest.Fake{} - node := &v1.ObjectReference{} - oomWatcher := NewOOMWatcher(mockCadvisor, fakeRecorder) - assert.NoError(t, oomWatcher.Start(node)) - - // TODO: Improve this test once cadvisor exports events.EventChannel as an interface - // and thereby allow using a mock version of cadvisor. -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/pod_container_deletor_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/pod_container_deletor_test.go deleted file mode 100644 index 196a66607b..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/pod_container_deletor_test.go +++ /dev/null @@ -1,203 +0,0 @@ -/* -Copyright 2016 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 kubelet - -import ( - "reflect" - "testing" - "time" - - kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" -) - -func TestGetContainersToDeleteInPodWithFilter(t *testing.T) { - pod := kubecontainer.PodStatus{ - ContainerStatuses: []*kubecontainer.ContainerStatus{ - { - ID: kubecontainer.ContainerID{Type: "test", ID: "1"}, - Name: "foo", - CreatedAt: time.Now(), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "2"}, - Name: "bar", - CreatedAt: time.Now().Add(time.Second), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "3"}, - Name: "bar", - CreatedAt: time.Now().Add(2 * time.Second), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "4"}, - Name: "bar", - CreatedAt: time.Now().Add(3 * time.Second), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "5"}, - Name: "bar", - CreatedAt: time.Now().Add(4 * time.Second), - State: kubecontainer.ContainerStateRunning, - }, - }, - } - - testCases := []struct { - containersToKeep int - expectedContainersToDelete containerStatusbyCreatedList - }{ - { - 0, - []*kubecontainer.ContainerStatus{pod.ContainerStatuses[3], pod.ContainerStatuses[2], pod.ContainerStatuses[1]}, - }, - { - 1, - []*kubecontainer.ContainerStatus{pod.ContainerStatuses[2], pod.ContainerStatuses[1]}, - }, - { - 2, - []*kubecontainer.ContainerStatus{pod.ContainerStatuses[1]}, - }, - } - - for _, test := range testCases { - candidates := getContainersToDeleteInPod("4", &pod, test.containersToKeep) - if !reflect.DeepEqual(candidates, test.expectedContainersToDelete) { - t.Errorf("expected %v got %v", test.expectedContainersToDelete, candidates) - } - } -} - -func TestGetContainersToDeleteInPod(t *testing.T) { - pod := kubecontainer.PodStatus{ - ContainerStatuses: []*kubecontainer.ContainerStatus{ - { - ID: kubecontainer.ContainerID{Type: "test", ID: "1"}, - Name: "foo", - CreatedAt: time.Now(), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "2"}, - Name: "bar", - CreatedAt: time.Now().Add(time.Second), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "3"}, - Name: "bar", - CreatedAt: time.Now().Add(2 * time.Second), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "4"}, - Name: "bar", - CreatedAt: time.Now().Add(3 * time.Second), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "5"}, - Name: "bar", - CreatedAt: time.Now().Add(4 * time.Second), - State: kubecontainer.ContainerStateRunning, - }, - }, - } - - testCases := []struct { - containersToKeep int - expectedContainersToDelete containerStatusbyCreatedList - }{ - { - 0, - []*kubecontainer.ContainerStatus{pod.ContainerStatuses[3], pod.ContainerStatuses[2], pod.ContainerStatuses[1], pod.ContainerStatuses[0]}, - }, - { - 1, - []*kubecontainer.ContainerStatus{pod.ContainerStatuses[2], pod.ContainerStatuses[1], pod.ContainerStatuses[0]}, - }, - { - 2, - []*kubecontainer.ContainerStatus{pod.ContainerStatuses[1], pod.ContainerStatuses[0]}, - }, - } - - for _, test := range testCases { - candidates := getContainersToDeleteInPod("", &pod, test.containersToKeep) - if !reflect.DeepEqual(candidates, test.expectedContainersToDelete) { - t.Errorf("expected %v got %v", test.expectedContainersToDelete, candidates) - } - } -} - -func TestGetContainersToDeleteInPodWithNoMatch(t *testing.T) { - pod := kubecontainer.PodStatus{ - ContainerStatuses: []*kubecontainer.ContainerStatus{ - { - ID: kubecontainer.ContainerID{Type: "test", ID: "1"}, - Name: "foo", - CreatedAt: time.Now(), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "2"}, - Name: "bar", - CreatedAt: time.Now().Add(time.Second), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "3"}, - Name: "bar", - CreatedAt: time.Now().Add(2 * time.Second), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "4"}, - Name: "bar", - CreatedAt: time.Now().Add(3 * time.Second), - State: kubecontainer.ContainerStateExited, - }, - { - ID: kubecontainer.ContainerID{Type: "test", ID: "5"}, - Name: "bar", - CreatedAt: time.Now().Add(4 * time.Second), - State: kubecontainer.ContainerStateRunning, - }, - }, - } - - testCases := []struct { - filterID string - expectedContainersToDelete containerStatusbyCreatedList - }{ - { - "abc", - []*kubecontainer.ContainerStatus{}, - }, - } - - for _, test := range testCases { - candidates := getContainersToDeleteInPod(test.filterID, &pod, len(pod.ContainerStatuses)) - if !reflect.DeepEqual(candidates, test.expectedContainersToDelete) { - t.Errorf("expected %v got %v", test.expectedContainersToDelete, candidates) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/pod_workers_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/pod_workers_test.go deleted file mode 100644 index ff13baa99c..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/pod_workers_test.go +++ /dev/null @@ -1,355 +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 kubelet - -import ( - "reflect" - "sync" - "testing" - "time" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/clock" - "k8s.io/client-go/tools/record" - kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" - containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" - kubetypes "k8s.io/kubernetes/pkg/kubelet/types" - "k8s.io/kubernetes/pkg/kubelet/util/queue" -) - -// fakePodWorkers runs sync pod function in serial, so we can have -// deterministic behaviour in testing. -type fakePodWorkers struct { - syncPodFn syncPodFnType - cache kubecontainer.Cache - t TestingInterface -} - -func (f *fakePodWorkers) UpdatePod(options *UpdatePodOptions) { - status, err := f.cache.Get(options.Pod.UID) - if err != nil { - f.t.Errorf("Unexpected error: %v", err) - } - if err := f.syncPodFn(syncPodOptions{ - mirrorPod: options.MirrorPod, - pod: options.Pod, - podStatus: status, - updateType: options.UpdateType, - killPodOptions: options.KillPodOptions, - }); err != nil { - f.t.Errorf("Unexpected error: %v", err) - } -} - -func (f *fakePodWorkers) ForgetNonExistingPodWorkers(desiredPods map[types.UID]empty) {} - -func (f *fakePodWorkers) ForgetWorker(uid types.UID) {} - -type TestingInterface interface { - Errorf(format string, args ...interface{}) -} - -func newPod(uid, name string) *v1.Pod { - return &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - UID: types.UID(uid), - Name: name, - }, - } -} - -// syncPodRecord is a record of a sync pod call -type syncPodRecord struct { - name string - updateType kubetypes.SyncPodType -} - -func createPodWorkers() (*podWorkers, map[types.UID][]syncPodRecord) { - lock := sync.Mutex{} - processed := make(map[types.UID][]syncPodRecord) - fakeRecorder := &record.FakeRecorder{} - fakeRuntime := &containertest.FakeRuntime{} - fakeCache := containertest.NewFakeCache(fakeRuntime) - podWorkers := newPodWorkers( - func(options syncPodOptions) error { - func() { - lock.Lock() - defer lock.Unlock() - pod := options.pod - processed[pod.UID] = append(processed[pod.UID], syncPodRecord{ - name: pod.Name, - updateType: options.updateType, - }) - }() - return nil - }, - fakeRecorder, - queue.NewBasicWorkQueue(&clock.RealClock{}), - time.Second, - time.Second, - fakeCache, - ) - return podWorkers, processed -} - -func drainWorkers(podWorkers *podWorkers, numPods int) { - for { - stillWorking := false - podWorkers.podLock.Lock() - for i := 0; i < numPods; i++ { - if podWorkers.isWorking[types.UID(string(i))] { - stillWorking = true - } - } - podWorkers.podLock.Unlock() - if !stillWorking { - break - } - time.Sleep(50 * time.Millisecond) - } -} - -func TestUpdatePod(t *testing.T) { - podWorkers, processed := createPodWorkers() - - numPods := 20 - for i := 0; i < numPods; i++ { - for j := i; j < numPods; j++ { - podWorkers.UpdatePod(&UpdatePodOptions{ - Pod: newPod(string(j), string(i)), - UpdateType: kubetypes.SyncPodCreate, - }) - } - } - drainWorkers(podWorkers, numPods) - - if len(processed) != numPods { - t.Errorf("Not all pods processed: %v", len(processed)) - return - } - for i := 0; i < numPods; i++ { - uid := types.UID(i) - if len(processed[uid]) < 1 || len(processed[uid]) > i+1 { - t.Errorf("Pod %v processed %v times", i, len(processed[uid])) - continue - } - - // PodWorker guarantees the first and the last event will be processed - first := 0 - last := len(processed[uid]) - 1 - if processed[uid][first].name != string(0) { - t.Errorf("Pod %v: incorrect order %v, %v", i, first, processed[uid][first]) - - } - if processed[uid][last].name != string(i) { - t.Errorf("Pod %v: incorrect order %v, %v", i, last, processed[uid][last]) - } - } -} - -func TestUpdatePodDoesNotForgetSyncPodKill(t *testing.T) { - podWorkers, processed := createPodWorkers() - numPods := 20 - for i := 0; i < numPods; i++ { - pod := newPod(string(i), string(i)) - podWorkers.UpdatePod(&UpdatePodOptions{ - Pod: pod, - UpdateType: kubetypes.SyncPodCreate, - }) - podWorkers.UpdatePod(&UpdatePodOptions{ - Pod: pod, - UpdateType: kubetypes.SyncPodKill, - }) - podWorkers.UpdatePod(&UpdatePodOptions{ - Pod: pod, - UpdateType: kubetypes.SyncPodUpdate, - }) - } - drainWorkers(podWorkers, numPods) - if len(processed) != numPods { - t.Errorf("Not all pods processed: %v", len(processed)) - return - } - for i := 0; i < numPods; i++ { - uid := types.UID(i) - // each pod should be processed two times (create, kill, but not update) - syncPodRecords := processed[uid] - if len(syncPodRecords) < 2 { - t.Errorf("Pod %v processed %v times, but expected at least 2", i, len(syncPodRecords)) - continue - } - if syncPodRecords[0].updateType != kubetypes.SyncPodCreate { - t.Errorf("Pod %v event was %v, but expected %v", i, syncPodRecords[0].updateType, kubetypes.SyncPodCreate) - } - if syncPodRecords[1].updateType != kubetypes.SyncPodKill { - t.Errorf("Pod %v event was %v, but expected %v", i, syncPodRecords[1].updateType, kubetypes.SyncPodKill) - } - } -} - -func TestForgetNonExistingPodWorkers(t *testing.T) { - podWorkers, _ := createPodWorkers() - - numPods := 20 - for i := 0; i < numPods; i++ { - podWorkers.UpdatePod(&UpdatePodOptions{ - Pod: newPod(string(i), "name"), - UpdateType: kubetypes.SyncPodUpdate, - }) - } - drainWorkers(podWorkers, numPods) - - if len(podWorkers.podUpdates) != numPods { - t.Errorf("Incorrect number of open channels %v", len(podWorkers.podUpdates)) - } - - desiredPods := map[types.UID]empty{} - desiredPods[types.UID(2)] = empty{} - desiredPods[types.UID(14)] = empty{} - podWorkers.ForgetNonExistingPodWorkers(desiredPods) - if len(podWorkers.podUpdates) != 2 { - t.Errorf("Incorrect number of open channels %v", len(podWorkers.podUpdates)) - } - if _, exists := podWorkers.podUpdates[types.UID(2)]; !exists { - t.Errorf("No updates channel for pod 2") - } - if _, exists := podWorkers.podUpdates[types.UID(14)]; !exists { - t.Errorf("No updates channel for pod 14") - } - - podWorkers.ForgetNonExistingPodWorkers(map[types.UID]empty{}) - if len(podWorkers.podUpdates) != 0 { - t.Errorf("Incorrect number of open channels %v", len(podWorkers.podUpdates)) - } -} - -type simpleFakeKubelet struct { - pod *v1.Pod - mirrorPod *v1.Pod - podStatus *kubecontainer.PodStatus - wg sync.WaitGroup -} - -func (kl *simpleFakeKubelet) syncPod(options syncPodOptions) error { - kl.pod, kl.mirrorPod, kl.podStatus = options.pod, options.mirrorPod, options.podStatus - return nil -} - -func (kl *simpleFakeKubelet) syncPodWithWaitGroup(options syncPodOptions) error { - kl.pod, kl.mirrorPod, kl.podStatus = options.pod, options.mirrorPod, options.podStatus - kl.wg.Done() - return nil -} - -// byContainerName sort the containers in a running pod by their names. -type byContainerName kubecontainer.Pod - -func (b byContainerName) Len() int { return len(b.Containers) } - -func (b byContainerName) Swap(i, j int) { - b.Containers[i], b.Containers[j] = b.Containers[j], b.Containers[i] -} - -func (b byContainerName) Less(i, j int) bool { - return b.Containers[i].Name < b.Containers[j].Name -} - -// TestFakePodWorkers verifies that the fakePodWorkers behaves the same way as the real podWorkers -// for their invocation of the syncPodFn. -func TestFakePodWorkers(t *testing.T) { - fakeRecorder := &record.FakeRecorder{} - fakeRuntime := &containertest.FakeRuntime{} - fakeCache := containertest.NewFakeCache(fakeRuntime) - - kubeletForRealWorkers := &simpleFakeKubelet{} - kubeletForFakeWorkers := &simpleFakeKubelet{} - - realPodWorkers := newPodWorkers(kubeletForRealWorkers.syncPodWithWaitGroup, fakeRecorder, queue.NewBasicWorkQueue(&clock.RealClock{}), time.Second, time.Second, fakeCache) - fakePodWorkers := &fakePodWorkers{kubeletForFakeWorkers.syncPod, fakeCache, t} - - tests := []struct { - pod *v1.Pod - mirrorPod *v1.Pod - }{ - { - &v1.Pod{}, - &v1.Pod{}, - }, - { - podWithUIDNameNs("12345678", "foo", "new"), - podWithUIDNameNs("12345678", "fooMirror", "new"), - }, - { - podWithUIDNameNs("98765", "bar", "new"), - podWithUIDNameNs("98765", "barMirror", "new"), - }, - } - - for i, tt := range tests { - kubeletForRealWorkers.wg.Add(1) - realPodWorkers.UpdatePod(&UpdatePodOptions{ - Pod: tt.pod, - MirrorPod: tt.mirrorPod, - UpdateType: kubetypes.SyncPodUpdate, - }) - fakePodWorkers.UpdatePod(&UpdatePodOptions{ - Pod: tt.pod, - MirrorPod: tt.mirrorPod, - UpdateType: kubetypes.SyncPodUpdate, - }) - - kubeletForRealWorkers.wg.Wait() - - if !reflect.DeepEqual(kubeletForRealWorkers.pod, kubeletForFakeWorkers.pod) { - t.Errorf("%d: Expected: %#v, Actual: %#v", i, kubeletForRealWorkers.pod, kubeletForFakeWorkers.pod) - } - - if !reflect.DeepEqual(kubeletForRealWorkers.mirrorPod, kubeletForFakeWorkers.mirrorPod) { - t.Errorf("%d: Expected: %#v, Actual: %#v", i, kubeletForRealWorkers.mirrorPod, kubeletForFakeWorkers.mirrorPod) - } - - if !reflect.DeepEqual(kubeletForRealWorkers.podStatus, kubeletForFakeWorkers.podStatus) { - t.Errorf("%d: Expected: %#v, Actual: %#v", i, kubeletForRealWorkers.podStatus, kubeletForFakeWorkers.podStatus) - } - } -} - -// TestKillPodNowFunc tests the blocking kill pod function works with pod workers as expected. -func TestKillPodNowFunc(t *testing.T) { - fakeRecorder := &record.FakeRecorder{} - podWorkers, processed := createPodWorkers() - killPodFunc := killPodNow(podWorkers, fakeRecorder) - pod := newPod("test", "test") - gracePeriodOverride := int64(0) - err := killPodFunc(pod, v1.PodStatus{Phase: v1.PodFailed, Reason: "reason", Message: "message"}, &gracePeriodOverride) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if len(processed) != 1 { - t.Errorf("len(processed) expected: %v, actual: %v", 1, len(processed)) - return - } - syncPodRecords := processed[pod.UID] - if len(syncPodRecords) != 1 { - t.Errorf("Pod processed %v times, but expected %v", len(syncPodRecords), 1) - } - if syncPodRecords[0].updateType != kubetypes.SyncPodKill { - t.Errorf("Pod update type was %v, but expected %v", syncPodRecords[0].updateType, kubetypes.SyncPodKill) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/reason_cache_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/reason_cache_test.go deleted file mode 100644 index 53f2b70b75..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/reason_cache_test.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright 2016 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 kubelet - -import ( - "testing" - - "k8s.io/apimachinery/pkg/types" - kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" -) - -func TestReasonCache(t *testing.T) { - // Create test sync result - syncResult := kubecontainer.PodSyncResult{} - results := []*kubecontainer.SyncResult{ - // reason cache should be set for SyncResult with StartContainer action and error - kubecontainer.NewSyncResult(kubecontainer.StartContainer, "container_1"), - // reason cache should not be set for SyncResult with StartContainer action but without error - kubecontainer.NewSyncResult(kubecontainer.StartContainer, "container_2"), - // reason cache should not be set for SyncResult with other actions - kubecontainer.NewSyncResult(kubecontainer.KillContainer, "container_3"), - } - results[0].Fail(kubecontainer.ErrRunContainer, "message_1") - results[2].Fail(kubecontainer.ErrKillContainer, "message_3") - syncResult.AddSyncResult(results...) - uid := types.UID("pod_1") - - reasonCache := NewReasonCache() - reasonCache.Update(uid, syncResult) - assertReasonInfo(t, reasonCache, uid, results[0], true) - assertReasonInfo(t, reasonCache, uid, results[1], false) - assertReasonInfo(t, reasonCache, uid, results[2], false) - - reasonCache.Remove(uid, results[0].Target.(string)) - assertReasonInfo(t, reasonCache, uid, results[0], false) -} - -func assertReasonInfo(t *testing.T, cache *ReasonCache, uid types.UID, result *kubecontainer.SyncResult, found bool) { - name := result.Target.(string) - actualReason, ok := cache.Get(uid, name) - if ok && !found { - t.Fatalf("unexpected cache hit: %v, %q", actualReason.Err, actualReason.Message) - } - if !ok && found { - t.Fatalf("corresponding reason info not found") - } - if !found { - return - } - reason := result.Error - message := result.Message - if actualReason.Err != reason || actualReason.Message != message { - t.Errorf("expected %v %q, got %v %q", reason, message, actualReason.Err, actualReason.Message) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/runonce_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/runonce_test.go deleted file mode 100644 index c9f01a744a..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/runonce_test.go +++ /dev/null @@ -1,175 +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 kubelet - -import ( - "os" - "testing" - "time" - - cadvisorapi "github.com/google/cadvisor/info/v1" - cadvisorapiv2 "github.com/google/cadvisor/info/v2" - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/clock" - "k8s.io/client-go/kubernetes/fake" - "k8s.io/client-go/tools/record" - utiltesting "k8s.io/client-go/util/testing" - "k8s.io/kubernetes/pkg/kubelet/apis/kubeletconfig" - cadvisortest "k8s.io/kubernetes/pkg/kubelet/cadvisor/testing" - "k8s.io/kubernetes/pkg/kubelet/cm" - "k8s.io/kubernetes/pkg/kubelet/configmap" - kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" - containertest "k8s.io/kubernetes/pkg/kubelet/container/testing" - "k8s.io/kubernetes/pkg/kubelet/eviction" - "k8s.io/kubernetes/pkg/kubelet/network" - nettest "k8s.io/kubernetes/pkg/kubelet/network/testing" - kubepod "k8s.io/kubernetes/pkg/kubelet/pod" - podtest "k8s.io/kubernetes/pkg/kubelet/pod/testing" - "k8s.io/kubernetes/pkg/kubelet/secret" - "k8s.io/kubernetes/pkg/kubelet/server/stats" - "k8s.io/kubernetes/pkg/kubelet/status" - statustest "k8s.io/kubernetes/pkg/kubelet/status/testing" - "k8s.io/kubernetes/pkg/kubelet/volumemanager" - "k8s.io/kubernetes/pkg/util/mount" - "k8s.io/kubernetes/pkg/volume" - volumetest "k8s.io/kubernetes/pkg/volume/testing" -) - -func TestRunOnce(t *testing.T) { - cadvisor := &cadvisortest.Mock{} - cadvisor.On("MachineInfo").Return(&cadvisorapi.MachineInfo{}, nil) - cadvisor.On("ImagesFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 400, - Capacity: 1000, - Available: 600, - }, nil) - cadvisor.On("RootFsInfo").Return(cadvisorapiv2.FsInfo{ - Usage: 9, - Capacity: 10, - }, nil) - fakeSecretManager := secret.NewFakeManager() - fakeConfigMapManager := configmap.NewFakeManager() - podManager := kubepod.NewBasicPodManager( - podtest.NewFakeMirrorClient(), fakeSecretManager, fakeConfigMapManager) - fakeRuntime := &containertest.FakeRuntime{} - basePath, err := utiltesting.MkTmpdir("kubelet") - if err != nil { - t.Fatalf("can't make a temp rootdir %v", err) - } - defer os.RemoveAll(basePath) - kb := &Kubelet{ - rootDirectory: basePath, - recorder: &record.FakeRecorder{}, - cadvisor: cadvisor, - nodeInfo: testNodeInfo{}, - statusManager: status.NewManager(nil, podManager, &statustest.FakePodDeletionSafetyProvider{}), - podManager: podManager, - os: &containertest.FakeOS{}, - containerRuntime: fakeRuntime, - reasonCache: NewReasonCache(), - clock: clock.RealClock{}, - kubeClient: &fake.Clientset{}, - hostname: testKubeletHostname, - nodeName: testKubeletHostname, - runtimeState: newRuntimeState(time.Second), - } - kb.containerManager = cm.NewStubContainerManager() - - plug := &volumetest.FakeVolumePlugin{PluginName: "fake", Host: nil} - kb.volumePluginMgr, err = - NewInitializedVolumePluginMgr(kb, fakeSecretManager, fakeConfigMapManager, []volume.VolumePlugin{plug}, nil /* prober */) - if err != nil { - t.Fatalf("failed to initialize VolumePluginMgr: %v", err) - } - kb.volumeManager = volumemanager.NewVolumeManager( - true, - kb.nodeName, - kb.podManager, - kb.statusManager, - kb.kubeClient, - kb.volumePluginMgr, - fakeRuntime, - kb.mounter, - kb.getPodsDir(), - kb.recorder, - false, /* experimentalCheckNodeCapabilitiesBeforeMount */ - false /* keepTerminatedPodVolumes */) - - kb.networkPlugin, _ = network.InitNetworkPlugin([]network.NetworkPlugin{}, "", nettest.NewFakeHost(nil), kubeletconfig.HairpinNone, "", network.UseDefaultMTU) - // TODO: Factor out "StatsProvider" from Kubelet so we don't have a cyclic dependency - volumeStatsAggPeriod := time.Second * 10 - kb.resourceAnalyzer = stats.NewResourceAnalyzer(kb, volumeStatsAggPeriod) - nodeRef := &v1.ObjectReference{ - Kind: "Node", - Name: string(kb.nodeName), - UID: types.UID(kb.nodeName), - Namespace: "", - } - fakeKillPodFunc := func(pod *v1.Pod, podStatus v1.PodStatus, gracePeriodOverride *int64) error { - return nil - } - evictionManager, evictionAdmitHandler := eviction.NewManager(kb.resourceAnalyzer, eviction.Config{}, fakeKillPodFunc, nil, nil, kb.recorder, nodeRef, kb.clock) - - kb.evictionManager = evictionManager - kb.admitHandlers.AddPodAdmitHandler(evictionAdmitHandler) - kb.mounter = &mount.FakeMounter{} - if err := kb.setupDataDirs(); err != nil { - t.Errorf("Failed to init data dirs: %v", err) - } - - pods := []*v1.Pod{ - { - ObjectMeta: metav1.ObjectMeta{ - UID: "12345678", - Name: "foo", - Namespace: "new", - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - {Name: "bar"}, - }, - }, - }, - } - podManager.SetPods(pods) - // The original test here is totally meaningless, because fakeruntime will always return an empty podStatus. While - // the original logic of isPodRunning happens to return true when podstatus is empty, so the test can always pass. - // Now the logic in isPodRunning is changed, to let the test pass, we set the podstatus directly in fake runtime. - // This is also a meaningless test, because the isPodRunning will also always return true after setting this. However, - // because runonce is never used in kubernetes now, we should deprioritize the cleanup work. - // TODO(random-liu) Fix the test, make it meaningful. - fakeRuntime.PodStatus = kubecontainer.PodStatus{ - ContainerStatuses: []*kubecontainer.ContainerStatus{ - { - Name: "bar", - State: kubecontainer.ContainerStateRunning, - }, - }, - } - results, err := kb.runOnce(pods, time.Millisecond) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - if results[0].Err != nil { - t.Errorf("unexpected run pod error: %v", results[0].Err) - } - if results[0].Pod.Name != "foo" { - t.Errorf("unexpected pod: %q", results[0].Pod.Name) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/types/labels_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/types/labels_test.go deleted file mode 100644 index 8c17caaa55..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/types/labels_test.go +++ /dev/null @@ -1,119 +0,0 @@ -/* -Copyright 2017 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 types - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestGetContainerName(t *testing.T) { - var cases = []struct { - labels map[string]string - containerName string - }{ - { - labels: map[string]string{ - "io.kubernetes.container.name": "c1", - }, - containerName: "c1", - }, - { - labels: map[string]string{ - "io.kubernetes.container.name": "c2", - }, - containerName: "c2", - }, - } - for _, data := range cases { - containerName := GetContainerName(data.labels) - assert.Equal(t, data.containerName, containerName) - } -} - -func TestGetPodName(t *testing.T) { - var cases = []struct { - labels map[string]string - podName string - }{ - { - labels: map[string]string{ - "io.kubernetes.pod.name": "p1", - }, - podName: "p1", - }, - { - labels: map[string]string{ - "io.kubernetes.pod.name": "p2", - }, - podName: "p2", - }, - } - for _, data := range cases { - podName := GetPodName(data.labels) - assert.Equal(t, data.podName, podName) - } -} - -func TestGetPodUID(t *testing.T) { - var cases = []struct { - labels map[string]string - podUID string - }{ - { - labels: map[string]string{ - "io.kubernetes.pod.uid": "uid1", - }, - podUID: "uid1", - }, - { - labels: map[string]string{ - "io.kubernetes.pod.uid": "uid2", - }, - podUID: "uid2", - }, - } - for _, data := range cases { - podUID := GetPodUID(data.labels) - assert.Equal(t, data.podUID, podUID) - } -} - -func TestGetPodNamespace(t *testing.T) { - var cases = []struct { - labels map[string]string - podNamespace string - }{ - { - labels: map[string]string{ - "io.kubernetes.pod.namespace": "ns1", - }, - podNamespace: "ns1", - }, - { - labels: map[string]string{ - "io.kubernetes.pod.namespace": "ns2", - }, - podNamespace: "ns2", - }, - } - for _, data := range cases { - podNamespace := GetPodNamespace(data.labels) - assert.Equal(t, data.podNamespace, podNamespace) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/types/pod_update_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/types/pod_update_test.go deleted file mode 100644 index 849995452f..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/types/pod_update_test.go +++ /dev/null @@ -1,178 +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 types - -import ( - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestGetValidatedSources(t *testing.T) { - // Empty. - sources, err := GetValidatedSources([]string{""}) - require.NoError(t, err) - require.Len(t, sources, 0) - - // Success. - sources, err = GetValidatedSources([]string{FileSource, ApiserverSource}) - require.NoError(t, err) - require.Len(t, sources, 2) - - // All. - sources, err = GetValidatedSources([]string{AllSource}) - require.NoError(t, err) - require.Len(t, sources, 3) - - // Unknown source. - sources, err = GetValidatedSources([]string{"taco"}) - require.Error(t, err) -} - -func TestGetPodSource(t *testing.T) { - cases := []struct { - pod v1.Pod - expected string - errExpected bool - }{ - { - pod: v1.Pod{}, - expected: "", - errExpected: true, - }, - { - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - "kubernetes.io/config.source": "host-ipc-sources", - }, - }, - }, - expected: "host-ipc-sources", - errExpected: false, - }, - } - for i, data := range cases { - source, err := GetPodSource(&data.pod) - if data.errExpected { - assert.Error(t, err) - } else { - assert.NoError(t, err) - } - assert.Equal(t, data.expected, source, "test[%d]", i) - t.Logf("Test case [%d]", i) - } -} - -func TestString(t *testing.T) { - cases := []struct { - sp SyncPodType - expected string - }{ - { - sp: SyncPodCreate, - expected: "create", - }, - { - sp: SyncPodUpdate, - expected: "update", - }, - { - sp: SyncPodSync, - expected: "sync", - }, - { - sp: SyncPodKill, - expected: "kill", - }, - { - sp: 50, - expected: "unknown", - }, - } - for i, data := range cases { - syncPodString := data.sp.String() - assert.Equal(t, data.expected, syncPodString, "test[%d]", i) - t.Logf("Test case [%d]", i) - } -} - -func TestIsCriticalPod(t *testing.T) { - cases := []struct { - pod v1.Pod - expected bool - }{ - { - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pod1", - Namespace: "ns", - Annotations: map[string]string{ - "scheduler.alpha.kubernetes.io/critical-pod": "", - }, - }, - }, - expected: false, - }, - { - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pod2", - Namespace: "ns", - Annotations: map[string]string{ - "scheduler.alpha.kubernetes.io/critical-pod": "abc", - }, - }, - }, - expected: false, - }, - { - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pod3", - Namespace: "kube-system", - Annotations: map[string]string{ - "scheduler.alpha.kubernetes.io/critical-pod": "abc", - }, - }, - }, - expected: false, - }, - { - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: "pod4", - Namespace: "kube-system", - Annotations: map[string]string{ - "scheduler.alpha.kubernetes.io/critical-pod": "", - }, - }, - }, - expected: true, - }, - } - for i, data := range cases { - actual := IsCriticalPod(&data.pod) - if actual != data.expected { - t.Errorf("IsCriticalPod result wrong:\nexpected: %v\nactual: %v for test[%d] with Annotations: %v", - data.expected, actual, i, data.pod.Annotations) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/types/types_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/types/types_test.go deleted file mode 100644 index 179100a856..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/types/types_test.go +++ /dev/null @@ -1,138 +0,0 @@ -/* -Copyright 2016 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 types - -import ( - "reflect" - "testing" - - "github.com/stretchr/testify/assert" - "k8s.io/api/core/v1" -) - -func TestConvertToTimestamp(t *testing.T) { - timestamp := "2017-02-17T15:34:49.830882016+08:00" - convertedTimeStamp := ConvertToTimestamp(timestamp).GetString() - assert.Equal(t, timestamp, convertedTimeStamp) -} - -func TestLen(t *testing.T) { - var cases = []struct { - statuses SortedContainerStatuses - expected int - }{ - { - statuses: SortedContainerStatuses{{Name: "first"}}, - expected: 1, - }, - { - statuses: SortedContainerStatuses{{Name: "first"}, {Name: "second"}}, - expected: 2, - }, - } - for _, data := range cases { - assert.Equal(t, data.expected, data.statuses.Len()) - } -} - -func TestSwap(t *testing.T) { - var cases = []struct { - statuses SortedContainerStatuses - expected SortedContainerStatuses - }{ - { - statuses: SortedContainerStatuses{{Name: "first"}, {Name: "second"}}, - expected: SortedContainerStatuses{{Name: "second"}, {Name: "first"}}, - }, - } - for _, data := range cases { - data.statuses.Swap(0, 1) - if !reflect.DeepEqual(data.statuses, data.expected) { - t.Errorf( - "failed Swap:\n\texpected: %v\n\t actual: %v", - data.expected, - data.statuses, - ) - } - } -} - -func TestLess(t *testing.T) { - var cases = []struct { - statuses SortedContainerStatuses - expected bool - }{ - { - statuses: SortedContainerStatuses{{Name: "first"}, {Name: "second"}}, - expected: true, - }, - { - statuses: SortedContainerStatuses{{Name: "second"}, {Name: "first"}}, - expected: false, - }, - } - for _, data := range cases { - actual := data.statuses.Less(0, 1) - if actual != data.expected { - t.Errorf( - "failed Less:\n\texpected: %t\n\t actual: %t", - data.expected, - actual, - ) - } - } -} - -func TestSortInitContainerStatuses(t *testing.T) { - pod := v1.Pod{ - Spec: v1.PodSpec{}, - } - var cases = []struct { - containers []v1.Container - statuses []v1.ContainerStatus - sortedStatuses []v1.ContainerStatus - }{ - { - containers: []v1.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - statuses: []v1.ContainerStatus{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - sortedStatuses: []v1.ContainerStatus{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - }, - { - containers: []v1.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - statuses: []v1.ContainerStatus{{Name: "second"}, {Name: "first"}, {Name: "fourth"}, {Name: "third"}}, - sortedStatuses: []v1.ContainerStatus{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - }, - { - containers: []v1.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - statuses: []v1.ContainerStatus{{Name: "fourth"}, {Name: "first"}}, - sortedStatuses: []v1.ContainerStatus{{Name: "first"}, {Name: "fourth"}}, - }, - { - containers: []v1.Container{{Name: "first"}, {Name: "second"}, {Name: "third"}, {Name: "fourth"}}, - statuses: []v1.ContainerStatus{{Name: "first"}, {Name: "third"}}, - sortedStatuses: []v1.ContainerStatus{{Name: "first"}, {Name: "third"}}, - }, - } - for _, data := range cases { - pod.Spec.InitContainers = data.containers - SortInitContainerStatuses(&pod, data.statuses) - if !reflect.DeepEqual(data.statuses, data.sortedStatuses) { - t.Errorf("SortInitContainerStatuses result wrong:\nContainers order: %v\nExpected order: %v\nReturne order: %v", - data.containers, data.sortedStatuses, data.statuses) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/resources_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/resources_test.go deleted file mode 100644 index 7507daeb04..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/util/format/resources_test.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright 2016 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 format - -import ( - "testing" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" -) - -func TestResourceList(t *testing.T) { - resourceList := v1.ResourceList{} - resourceList[v1.ResourceCPU] = resource.MustParse("100m") - resourceList[v1.ResourceMemory] = resource.MustParse("5Gi") - actual := ResourceList(resourceList) - expected := "cpu=100m,memory=5Gi" - if actual != expected { - t.Errorf("Unexpected result, actual: %v, expected: %v", actual, expected) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/util/sliceutils/sliceutils_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/util/sliceutils/sliceutils_test.go deleted file mode 100644 index bf56bde231..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/util/sliceutils/sliceutils_test.go +++ /dev/null @@ -1,222 +0,0 @@ -/* -Copyright 2017 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 sliceutils - -import ( - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" - "time" -) - -func TestStringInSlice(t *testing.T) { - fooTests := []struct { - s string - list []string - er bool - }{ - {"first", []string{"first", "second"}, true}, - {"FIRST", []string{"first", "second"}, false}, - {"third", []string{"first", "second"}, false}, - {"first", nil, false}, - - {"", []string{"first", "second"}, false}, - {"", []string{"first", "second", ""}, true}, - {"", nil, false}, - } - - for _, fooTest := range fooTests { - r := StringInSlice(fooTest.s, fooTest.list) - if r != fooTest.er { - t.Errorf("returned %t but expected %t for s=%s & list=%s", r, fooTest.er, fooTest.s, fooTest.list) - } - } -} - -func buildPodsByCreationTime() PodsByCreationTime { - return []*v1.Pod{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "foo1", - Namespace: v1.NamespaceDefault, - CreationTimestamp: metav1.Time{ - Time: time.Now(), - }, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "foo2", - Namespace: v1.NamespaceDefault, - CreationTimestamp: metav1.Time{ - Time: time.Now().Add(time.Hour * 1), - }, - }, - }, - { - ObjectMeta: metav1.ObjectMeta{ - Name: "foo3", - Namespace: v1.NamespaceDefault, - CreationTimestamp: metav1.Time{ - Time: time.Now().Add(time.Hour * 2), - }, - }, - }, - } -} - -func TestPodsByCreationTimeLen(t *testing.T) { - fooTests := []struct { - pods PodsByCreationTime - el int - }{ - {[]*v1.Pod{}, 0}, - {buildPodsByCreationTime(), 3}, - {[]*v1.Pod{nil, {}}, 2}, - {nil, 0}, - } - - for _, fooTest := range fooTests { - r := fooTest.pods.Len() - if r != fooTest.el { - t.Errorf("returned %d but expected %d for the len of PodsByCreationTime=%s", r, fooTest.el, fooTest.pods) - } - } -} - -func TestPodsByCreationTimeSwap(t *testing.T) { - fooTests := []struct { - pods PodsByCreationTime - i int - j int - }{ - {buildPodsByCreationTime(), 0, 1}, - {buildPodsByCreationTime(), 2, 1}, - } - - for _, fooTest := range fooTests { - fooi := fooTest.pods[fooTest.i] - fooj := fooTest.pods[fooTest.j] - fooTest.pods.Swap(fooTest.i, fooTest.j) - if fooi.GetName() != fooTest.pods[fooTest.j].GetName() || fooj.GetName() != fooTest.pods[fooTest.i].GetName() { - t.Errorf("failed to swap for %v", fooTest) - } - } -} - -func TestPodsByCreationTimeLess(t *testing.T) { - fooTests := []struct { - pods PodsByCreationTime - i int - j int - er bool - }{ - // ascending order - {buildPodsByCreationTime(), 0, 2, true}, - {buildPodsByCreationTime(), 1, 0, false}, - } - - for _, fooTest := range fooTests { - r := fooTest.pods.Less(fooTest.i, fooTest.j) - if r != fooTest.er { - t.Errorf("returned %t but expected %t for the foo=%s", r, fooTest.er, fooTest.pods) - } - } -} - -func buildByImageSize() ByImageSize { - return []kubecontainer.Image{ - { - ID: "1", - RepoTags: []string{"foo-tag11", "foo-tag12"}, - RepoDigests: []string{"foo-rd11", "foo-rd12"}, - Size: 1, - }, - { - ID: "2", - RepoTags: []string{"foo-tag21", "foo-tag22"}, - RepoDigests: []string{"foo-rd21", "foo-rd22"}, - Size: 2, - }, - { - ID: "3", - RepoTags: []string{"foo-tag31", "foo-tag32"}, - RepoDigests: []string{"foo-rd31", "foo-rd32"}, - Size: 3, - }, - } -} - -func TestByImageSizeLen(t *testing.T) { - fooTests := []struct { - images ByImageSize - el int - }{ - {[]kubecontainer.Image{}, 0}, - {buildByImageSize(), 3}, - {nil, 0}, - } - - for _, fooTest := range fooTests { - r := fooTest.images.Len() - if r != fooTest.el { - t.Errorf("returned %d but expected %d for the len of ByImageSize=%v", r, fooTest.el, fooTest.images) - } - } -} - -func TestByImageSizeSwap(t *testing.T) { - fooTests := []struct { - images ByImageSize - i int - j int - }{ - {buildByImageSize(), 0, 1}, - {buildByImageSize(), 2, 1}, - } - - for _, fooTest := range fooTests { - fooi := fooTest.images[fooTest.i] - fooj := fooTest.images[fooTest.j] - fooTest.images.Swap(fooTest.i, fooTest.j) - if fooi.ID != fooTest.images[fooTest.j].ID || fooj.ID != fooTest.images[fooTest.i].ID { - t.Errorf("failed to swap for %v", fooTest) - } - } -} - -func TestByImageSizeLess(t *testing.T) { - fooTests := []struct { - images ByImageSize - i int - j int - er bool - }{ - // descending order - {buildByImageSize(), 0, 2, false}, - {buildByImageSize(), 1, 0, true}, - } - - for _, fooTest := range fooTests { - r := fooTest.images.Less(fooTest.i, fooTest.j) - if r != fooTest.er { - t.Errorf("returned %t but expected %t for the foo=%v", r, fooTest.er, fooTest.images) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/kubelet/util/util_test.go b/vendor/k8s.io/kubernetes/pkg/kubelet/util/util_test.go deleted file mode 100644 index f2853b3c30..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/kubelet/util/util_test.go +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright 2017 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 util - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestParseEndpoint(t *testing.T) { - tests := []struct { - endpoint string - expectError bool - expectedProtocol string - expectedAddr string - }{ - { - endpoint: "unix:///tmp/s1.sock", - expectedProtocol: "unix", - expectedAddr: "/tmp/s1.sock", - }, - { - endpoint: "tcp://localhost:15880", - expectedProtocol: "tcp", - expectedAddr: "localhost:15880", - }, - { - endpoint: "tcp1://abc", - expectedProtocol: "tcp1", - expectError: true, - }, - { - endpoint: "a b c", - expectError: true, - }, - } - - for _, test := range tests { - protocol, addr, err := parseEndpoint(test.endpoint) - assert.Equal(t, test.expectedProtocol, protocol) - if test.expectError { - assert.NotNil(t, err, "Expect error during parsing %q", test.endpoint) - continue - } - assert.Nil(t, err, "Expect no error during parsing %q", test.endpoint) - assert.Equal(t, test.expectedAddr, addr) - } - -} diff --git a/vendor/k8s.io/kubernetes/pkg/master/client_ca_hook_test.go b/vendor/k8s.io/kubernetes/pkg/master/client_ca_hook_test.go deleted file mode 100644 index 64aa61712c..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/master/client_ca_hook_test.go +++ /dev/null @@ -1,223 +0,0 @@ -/* -Copyright 2017 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 master - -import ( - "reflect" - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/util/diff" - clienttesting "k8s.io/client-go/testing" - api "k8s.io/kubernetes/pkg/apis/core" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" -) - -func TestWriteClientCAs(t *testing.T) { - tests := []struct { - name string - hook ClientCARegistrationHook - preexistingObjs []runtime.Object - expectedConfigMaps map[string]*api.ConfigMap - expectUpdate bool - }{ - { - name: "basic", - hook: ClientCARegistrationHook{ - ClientCA: []byte("foo"), - RequestHeaderUsernameHeaders: []string{"alfa", "bravo", "charlie"}, - RequestHeaderGroupHeaders: []string{"delta"}, - RequestHeaderExtraHeaderPrefixes: []string{"echo", "foxtrot"}, - RequestHeaderCA: []byte("bar"), - RequestHeaderAllowedNames: []string{"first", "second"}, - }, - expectedConfigMaps: map[string]*api.ConfigMap{ - "extension-apiserver-authentication": { - ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: "extension-apiserver-authentication"}, - Data: map[string]string{ - "client-ca-file": "foo", - "requestheader-username-headers": `["alfa","bravo","charlie"]`, - "requestheader-group-headers": `["delta"]`, - "requestheader-extra-headers-prefix": `["echo","foxtrot"]`, - "requestheader-client-ca-file": "bar", - "requestheader-allowed-names": `["first","second"]`, - }, - }, - }, - }, - { - name: "skip extension-apiserver-authentication", - hook: ClientCARegistrationHook{ - RequestHeaderCA: []byte("bar"), - RequestHeaderAllowedNames: []string{"first", "second"}, - }, - expectedConfigMaps: map[string]*api.ConfigMap{ - "extension-apiserver-authentication": { - ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: "extension-apiserver-authentication"}, - Data: map[string]string{ - "requestheader-username-headers": `null`, - "requestheader-group-headers": `null`, - "requestheader-extra-headers-prefix": `null`, - "requestheader-client-ca-file": "bar", - "requestheader-allowed-names": `["first","second"]`, - }, - }, - }, - }, - { - name: "skip extension-apiserver-authentication", - hook: ClientCARegistrationHook{ - ClientCA: []byte("foo"), - }, - expectedConfigMaps: map[string]*api.ConfigMap{ - "extension-apiserver-authentication": { - ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: "extension-apiserver-authentication"}, - Data: map[string]string{ - "client-ca-file": "foo", - }, - }, - }, - }, - { - name: "empty allowed names", - hook: ClientCARegistrationHook{ - RequestHeaderCA: []byte("bar"), - }, - expectedConfigMaps: map[string]*api.ConfigMap{ - "extension-apiserver-authentication": { - ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: "extension-apiserver-authentication"}, - Data: map[string]string{ - "requestheader-username-headers": `null`, - "requestheader-group-headers": `null`, - "requestheader-extra-headers-prefix": `null`, - "requestheader-client-ca-file": "bar", - "requestheader-allowed-names": `null`, - }, - }, - }, - }, - { - name: "overwrite extension-apiserver-authentication", - hook: ClientCARegistrationHook{ - ClientCA: []byte("foo"), - }, - preexistingObjs: []runtime.Object{ - &api.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: "extension-apiserver-authentication"}, - Data: map[string]string{ - "client-ca-file": "other", - }, - }, - }, - expectedConfigMaps: map[string]*api.ConfigMap{ - "extension-apiserver-authentication": { - ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: "extension-apiserver-authentication"}, - Data: map[string]string{ - "client-ca-file": "foo", - }, - }, - }, - expectUpdate: true, - }, - { - name: "overwrite extension-apiserver-authentication requestheader", - hook: ClientCARegistrationHook{ - RequestHeaderUsernameHeaders: []string{}, - RequestHeaderGroupHeaders: []string{}, - RequestHeaderExtraHeaderPrefixes: []string{}, - RequestHeaderCA: []byte("bar"), - RequestHeaderAllowedNames: []string{}, - }, - preexistingObjs: []runtime.Object{ - &api.ConfigMap{ - ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: "extension-apiserver-authentication"}, - Data: map[string]string{ - "requestheader-username-headers": `null`, - "requestheader-group-headers": `null`, - "requestheader-extra-headers-prefix": `null`, - "requestheader-client-ca-file": "something", - "requestheader-allowed-names": `null`, - }, - }, - }, - expectedConfigMaps: map[string]*api.ConfigMap{ - "extension-apiserver-authentication": { - ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: "extension-apiserver-authentication"}, - Data: map[string]string{ - "requestheader-username-headers": `[]`, - "requestheader-group-headers": `[]`, - "requestheader-extra-headers-prefix": `[]`, - "requestheader-client-ca-file": "bar", - "requestheader-allowed-names": `[]`, - }, - }, - }, - expectUpdate: true, - }, - { - name: "namespace exists", - hook: ClientCARegistrationHook{ - ClientCA: []byte("foo"), - }, - preexistingObjs: []runtime.Object{ - &api.Namespace{ObjectMeta: metav1.ObjectMeta{Name: metav1.NamespaceSystem}}, - }, - expectedConfigMaps: map[string]*api.ConfigMap{ - "extension-apiserver-authentication": { - ObjectMeta: metav1.ObjectMeta{Namespace: metav1.NamespaceSystem, Name: "extension-apiserver-authentication"}, - Data: map[string]string{ - "client-ca-file": "foo", - }, - }, - }, - }, - } - - for _, test := range tests { - client := fake.NewSimpleClientset(test.preexistingObjs...) - test.hook.tryToWriteClientCAs(client.Core()) - - actualConfigMaps, updated := getFinalConfiMaps(client) - if !reflect.DeepEqual(test.expectedConfigMaps, actualConfigMaps) { - t.Errorf("%s: %v", test.name, diff.ObjectReflectDiff(test.expectedConfigMaps, actualConfigMaps)) - continue - } - if test.expectUpdate != updated { - t.Errorf("%s: expected %v, got %v", test.name, test.expectUpdate, updated) - continue - } - } -} - -func getFinalConfiMaps(client *fake.Clientset) (map[string]*api.ConfigMap, bool) { - ret := map[string]*api.ConfigMap{} - updated := false - - for _, action := range client.Actions() { - if action.Matches("create", "configmaps") { - obj := action.(clienttesting.CreateAction).GetObject().(*api.ConfigMap) - ret[obj.Name] = obj - } - if action.Matches("update", "configmaps") { - updated = true - obj := action.(clienttesting.UpdateAction).GetObject().(*api.ConfigMap) - ret[obj.Name] = obj - } - } - return ret, updated -} diff --git a/vendor/k8s.io/kubernetes/pkg/master/controller_test.go b/vendor/k8s.io/kubernetes/pkg/master/controller_test.go deleted file mode 100644 index ec7d63158e..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/master/controller_test.go +++ /dev/null @@ -1,948 +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 master - -import ( - "net" - "reflect" - "testing" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/intstr" - core "k8s.io/client-go/testing" - api "k8s.io/kubernetes/pkg/apis/core" - "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/fake" - "k8s.io/kubernetes/pkg/master/reconcilers" -) - -func TestReconcileEndpoints(t *testing.T) { - ns := metav1.NamespaceDefault - om := func(name string) metav1.ObjectMeta { - return metav1.ObjectMeta{Namespace: ns, Name: name} - } - reconcile_tests := []struct { - testName string - serviceName string - ip string - endpointPorts []api.EndpointPort - additionalMasters int - endpoints *api.EndpointsList - expectUpdate *api.Endpoints // nil means none expected - expectCreate *api.Endpoints // nil means none expected - }{ - { - testName: "no existing endpoints", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - endpoints: nil, - expectCreate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "existing endpoints satisfy", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - }, - { - testName: "existing endpoints satisfy but too many", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}, {IP: "4.3.2.1"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "existing endpoints satisfy but too many + extra masters", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - additionalMasters: 3, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "1.2.3.4"}, - {IP: "4.3.2.1"}, - {IP: "4.3.2.2"}, - {IP: "4.3.2.3"}, - {IP: "4.3.2.4"}, - }, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "1.2.3.4"}, - {IP: "4.3.2.2"}, - {IP: "4.3.2.3"}, - {IP: "4.3.2.4"}, - }, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "existing endpoints satisfy but too many + extra masters + delete first", - serviceName: "foo", - ip: "4.3.2.4", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - additionalMasters: 3, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "1.2.3.4"}, - {IP: "4.3.2.1"}, - {IP: "4.3.2.2"}, - {IP: "4.3.2.3"}, - {IP: "4.3.2.4"}, - }, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "4.3.2.1"}, - {IP: "4.3.2.2"}, - {IP: "4.3.2.3"}, - {IP: "4.3.2.4"}, - }, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "existing endpoints satisfy and endpoint addresses length less than master count", - serviceName: "foo", - ip: "4.3.2.2", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - additionalMasters: 3, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "4.3.2.1"}, - {IP: "4.3.2.2"}, - }, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: nil, - }, - { - testName: "existing endpoints current IP missing and address length less than master count", - serviceName: "foo", - ip: "4.3.2.2", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - additionalMasters: 3, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "4.3.2.1"}, - }, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{ - {IP: "4.3.2.1"}, - {IP: "4.3.2.2"}, - }, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "existing endpoints wrong name", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("bar"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectCreate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "existing endpoints wrong IP", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "4.3.2.1"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "existing endpoints wrong port", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 9090, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "existing endpoints wrong protocol", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "UDP"}}, - }}, - }}, - }, - expectUpdate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "existing endpoints wrong port name", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{{Name: "baz", Port: 8080, Protocol: "TCP"}}, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "baz", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "existing endpoints extra service ports satisfy", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{ - {Name: "foo", Port: 8080, Protocol: "TCP"}, - {Name: "bar", Port: 1000, Protocol: "TCP"}, - {Name: "baz", Port: 1010, Protocol: "TCP"}, - }, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{ - {Name: "foo", Port: 8080, Protocol: "TCP"}, - {Name: "bar", Port: 1000, Protocol: "TCP"}, - {Name: "baz", Port: 1010, Protocol: "TCP"}, - }, - }}, - }}, - }, - }, - { - testName: "existing endpoints extra service ports missing port", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{ - {Name: "foo", Port: 8080, Protocol: "TCP"}, - {Name: "bar", Port: 1000, Protocol: "TCP"}, - }, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{ - {Name: "foo", Port: 8080, Protocol: "TCP"}, - {Name: "bar", Port: 1000, Protocol: "TCP"}, - }, - }}, - }, - }, - } - for _, test := range reconcile_tests { - fakeClient := fake.NewSimpleClientset() - if test.endpoints != nil { - fakeClient = fake.NewSimpleClientset(test.endpoints) - } - reconciler := reconcilers.NewMasterCountEndpointReconciler(test.additionalMasters+1, fakeClient.Core()) - err := reconciler.ReconcileEndpoints(test.serviceName, net.ParseIP(test.ip), test.endpointPorts, true) - if err != nil { - t.Errorf("case %q: unexpected error: %v", test.testName, err) - } - - updates := []core.UpdateAction{} - for _, action := range fakeClient.Actions() { - if action.GetVerb() != "update" { - continue - } - updates = append(updates, action.(core.UpdateAction)) - } - if test.expectUpdate != nil { - if len(updates) != 1 { - t.Errorf("case %q: unexpected updates: %v", test.testName, updates) - } else if e, a := test.expectUpdate, updates[0].GetObject(); !reflect.DeepEqual(e, a) { - t.Errorf("case %q: expected update:\n%#v\ngot:\n%#v\n", test.testName, e, a) - } - } - if test.expectUpdate == nil && len(updates) > 0 { - t.Errorf("case %q: no update expected, yet saw: %v", test.testName, updates) - } - - creates := []core.CreateAction{} - for _, action := range fakeClient.Actions() { - if action.GetVerb() != "create" { - continue - } - creates = append(creates, action.(core.CreateAction)) - } - if test.expectCreate != nil { - if len(creates) != 1 { - t.Errorf("case %q: unexpected creates: %v", test.testName, creates) - } else if e, a := test.expectCreate, creates[0].GetObject(); !reflect.DeepEqual(e, a) { - t.Errorf("case %q: expected create:\n%#v\ngot:\n%#v\n", test.testName, e, a) - } - } - if test.expectCreate == nil && len(creates) > 0 { - t.Errorf("case %q: no create expected, yet saw: %v", test.testName, creates) - } - - } - - non_reconcile_tests := []struct { - testName string - serviceName string - ip string - endpointPorts []api.EndpointPort - additionalMasters int - endpoints *api.EndpointsList - expectUpdate *api.Endpoints // nil means none expected - expectCreate *api.Endpoints // nil means none expected - }{ - { - testName: "existing endpoints extra service ports missing port no update", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{ - {Name: "foo", Port: 8080, Protocol: "TCP"}, - {Name: "bar", Port: 1000, Protocol: "TCP"}, - }, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: nil, - }, - { - testName: "existing endpoints extra service ports, wrong ports, wrong IP", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{ - {Name: "foo", Port: 8080, Protocol: "TCP"}, - {Name: "bar", Port: 1000, Protocol: "TCP"}, - }, - endpoints: &api.EndpointsList{ - Items: []api.Endpoints{{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "4.3.2.1"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }}, - }, - expectUpdate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - { - testName: "no existing endpoints", - serviceName: "foo", - ip: "1.2.3.4", - endpointPorts: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - endpoints: nil, - expectCreate: &api.Endpoints{ - ObjectMeta: om("foo"), - Subsets: []api.EndpointSubset{{ - Addresses: []api.EndpointAddress{{IP: "1.2.3.4"}}, - Ports: []api.EndpointPort{{Name: "foo", Port: 8080, Protocol: "TCP"}}, - }}, - }, - }, - } - for _, test := range non_reconcile_tests { - fakeClient := fake.NewSimpleClientset() - if test.endpoints != nil { - fakeClient = fake.NewSimpleClientset(test.endpoints) - } - reconciler := reconcilers.NewMasterCountEndpointReconciler(test.additionalMasters+1, fakeClient.Core()) - err := reconciler.ReconcileEndpoints(test.serviceName, net.ParseIP(test.ip), test.endpointPorts, false) - if err != nil { - t.Errorf("case %q: unexpected error: %v", test.testName, err) - } - - updates := []core.UpdateAction{} - for _, action := range fakeClient.Actions() { - if action.GetVerb() != "update" { - continue - } - updates = append(updates, action.(core.UpdateAction)) - } - if test.expectUpdate != nil { - if len(updates) != 1 { - t.Errorf("case %q: unexpected updates: %v", test.testName, updates) - } else if e, a := test.expectUpdate, updates[0].GetObject(); !reflect.DeepEqual(e, a) { - t.Errorf("case %q: expected update:\n%#v\ngot:\n%#v\n", test.testName, e, a) - } - } - if test.expectUpdate == nil && len(updates) > 0 { - t.Errorf("case %q: no update expected, yet saw: %v", test.testName, updates) - } - - creates := []core.CreateAction{} - for _, action := range fakeClient.Actions() { - if action.GetVerb() != "create" { - continue - } - creates = append(creates, action.(core.CreateAction)) - } - if test.expectCreate != nil { - if len(creates) != 1 { - t.Errorf("case %q: unexpected creates: %v", test.testName, creates) - } else if e, a := test.expectCreate, creates[0].GetObject(); !reflect.DeepEqual(e, a) { - t.Errorf("case %q: expected create:\n%#v\ngot:\n%#v\n", test.testName, e, a) - } - } - if test.expectCreate == nil && len(creates) > 0 { - t.Errorf("case %q: no create expected, yet saw: %v", test.testName, creates) - } - - } - -} - -func TestCreateOrUpdateMasterService(t *testing.T) { - ns := metav1.NamespaceDefault - om := func(name string) metav1.ObjectMeta { - return metav1.ObjectMeta{Namespace: ns, Name: name} - } - - create_tests := []struct { - testName string - serviceName string - servicePorts []api.ServicePort - serviceType api.ServiceType - expectCreate *api.Service // nil means none expected - }{ - { - testName: "service does not exist", - serviceName: "foo", - servicePorts: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - serviceType: api.ServiceTypeClusterIP, - expectCreate: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - }, - } - for _, test := range create_tests { - master := Controller{} - fakeClient := fake.NewSimpleClientset() - master.ServiceClient = fakeClient.Core() - master.CreateOrUpdateMasterServiceIfNeeded(test.serviceName, net.ParseIP("1.2.3.4"), test.servicePorts, test.serviceType, false) - creates := []core.CreateAction{} - for _, action := range fakeClient.Actions() { - if action.GetVerb() == "create" { - creates = append(creates, action.(core.CreateAction)) - } - } - if test.expectCreate != nil { - if len(creates) != 1 { - t.Errorf("case %q: unexpected creations: %v", test.testName, creates) - } else { - obj := creates[0].GetObject() - if e, a := test.expectCreate.Spec, obj.(*api.Service).Spec; !reflect.DeepEqual(e, a) { - t.Errorf("case %q: expected create:\n%#v\ngot:\n%#v\n", test.testName, e, a) - } - } - } - if test.expectCreate == nil && len(creates) > 1 { - t.Errorf("case %q: no create expected, yet saw: %v", test.testName, creates) - } - } - - reconcile_tests := []struct { - testName string - serviceName string - servicePorts []api.ServicePort - serviceType api.ServiceType - service *api.Service - expectUpdate *api.Service // nil means none expected - }{ - { - testName: "service definition wrong port", - serviceName: "foo", - servicePorts: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - serviceType: api.ServiceTypeClusterIP, - service: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8000, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - expectUpdate: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - }, - { - testName: "service definition missing port", - serviceName: "foo", - servicePorts: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - {Name: "baz", Port: 1000, Protocol: "TCP", TargetPort: intstr.FromInt(1000)}, - }, - serviceType: api.ServiceTypeClusterIP, - service: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - expectUpdate: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - {Name: "baz", Port: 1000, Protocol: "TCP", TargetPort: intstr.FromInt(1000)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - }, - { - testName: "service definition incorrect port", - serviceName: "foo", - servicePorts: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - serviceType: api.ServiceTypeClusterIP, - service: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "bar", Port: 1000, Protocol: "UDP", TargetPort: intstr.FromInt(1000)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - expectUpdate: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - }, - { - testName: "service definition incorrect port name", - serviceName: "foo", - servicePorts: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - serviceType: api.ServiceTypeClusterIP, - service: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 1000, Protocol: "UDP", TargetPort: intstr.FromInt(1000)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - expectUpdate: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - }, - { - testName: "service definition incorrect target port", - serviceName: "foo", - servicePorts: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - serviceType: api.ServiceTypeClusterIP, - service: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(1000)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - expectUpdate: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - }, - { - testName: "service definition incorrect protocol", - serviceName: "foo", - servicePorts: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - serviceType: api.ServiceTypeClusterIP, - service: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "UDP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - expectUpdate: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - }, - { - testName: "service definition has incorrect type", - serviceName: "foo", - servicePorts: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - serviceType: api.ServiceTypeClusterIP, - service: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeNodePort, - }, - }, - expectUpdate: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - }, - { - testName: "service definition satisfies", - serviceName: "foo", - servicePorts: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - serviceType: api.ServiceTypeClusterIP, - service: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - expectUpdate: nil, - }, - } - for _, test := range reconcile_tests { - master := Controller{} - fakeClient := fake.NewSimpleClientset(test.service) - master.ServiceClient = fakeClient.Core() - err := master.CreateOrUpdateMasterServiceIfNeeded(test.serviceName, net.ParseIP("1.2.3.4"), test.servicePorts, test.serviceType, true) - if err != nil { - t.Errorf("case %q: unexpected error: %v", test.testName, err) - } - updates := []core.UpdateAction{} - for _, action := range fakeClient.Actions() { - if action.GetVerb() == "update" { - updates = append(updates, action.(core.UpdateAction)) - } - } - if test.expectUpdate != nil { - if len(updates) != 1 { - t.Errorf("case %q: unexpected updates: %v", test.testName, updates) - } else { - obj := updates[0].GetObject() - if e, a := test.expectUpdate.Spec, obj.(*api.Service).Spec; !reflect.DeepEqual(e, a) { - t.Errorf("case %q: expected update:\n%#v\ngot:\n%#v\n", test.testName, e, a) - } - } - } - if test.expectUpdate == nil && len(updates) > 0 { - t.Errorf("case %q: no update expected, yet saw: %v", test.testName, updates) - } - } - - non_reconcile_tests := []struct { - testName string - serviceName string - servicePorts []api.ServicePort - serviceType api.ServiceType - service *api.Service - expectUpdate *api.Service // nil means none expected - }{ - { - testName: "service definition wrong port, no expected update", - serviceName: "foo", - servicePorts: []api.ServicePort{ - {Name: "foo", Port: 8080, Protocol: "TCP", TargetPort: intstr.FromInt(8080)}, - }, - serviceType: api.ServiceTypeClusterIP, - service: &api.Service{ - ObjectMeta: om("foo"), - Spec: api.ServiceSpec{ - Ports: []api.ServicePort{ - {Name: "foo", Port: 1000, Protocol: "TCP", TargetPort: intstr.FromInt(1000)}, - }, - Selector: nil, - ClusterIP: "1.2.3.4", - SessionAffinity: api.ServiceAffinityClientIP, - Type: api.ServiceTypeClusterIP, - }, - }, - expectUpdate: nil, - }, - } - for _, test := range non_reconcile_tests { - master := Controller{} - fakeClient := fake.NewSimpleClientset(test.service) - master.ServiceClient = fakeClient.Core() - err := master.CreateOrUpdateMasterServiceIfNeeded(test.serviceName, net.ParseIP("1.2.3.4"), test.servicePorts, test.serviceType, false) - if err != nil { - t.Errorf("case %q: unexpected error: %v", test.testName, err) - } - updates := []core.UpdateAction{} - for _, action := range fakeClient.Actions() { - if action.GetVerb() == "update" { - updates = append(updates, action.(core.UpdateAction)) - } - } - if test.expectUpdate != nil { - if len(updates) != 1 { - t.Errorf("case %q: unexpected updates: %v", test.testName, updates) - } else { - obj := updates[0].GetObject() - if e, a := test.expectUpdate.Spec, obj.(*api.Service).Spec; !reflect.DeepEqual(e, a) { - t.Errorf("case %q: expected update:\n%#v\ngot:\n%#v\n", test.testName, e, a) - } - } - } - if test.expectUpdate == nil && len(updates) > 0 { - t.Errorf("case %q: no update expected, yet saw: %v", test.testName, updates) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/master/import_known_versions_test.go b/vendor/k8s.io/kubernetes/pkg/master/import_known_versions_test.go deleted file mode 100644 index e6a69e7d6f..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/master/import_known_versions_test.go +++ /dev/null @@ -1,187 +0,0 @@ -/* -Copyright 2016 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 master - -import ( - "encoding/json" - "reflect" - "strings" - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - "k8s.io/apimachinery/pkg/util/intstr" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/kubernetes/pkg/api/legacyscheme" -) - -func TestGroupVersions(t *testing.T) { - // legacyUnsuffixedGroups contains the groups released prior to deciding that kubernetes API groups should be dns-suffixed - // new groups should be suffixed with ".k8s.io" (https://github.com/kubernetes/kubernetes/pull/31887#issuecomment-244462396) - legacyUnsuffixedGroups := sets.NewString( - "", - "apps", - "autoscaling", - "batch", - "componentconfig", - "extensions", - "policy", - ) - - // No new groups should be added to the legacyUnsuffixedGroups exclusion list - if len(legacyUnsuffixedGroups) != 7 { - t.Errorf("No additional unnamespaced groups should be created") - } - - for _, gv := range legacyscheme.Registry.RegisteredGroupVersions() { - if !strings.HasSuffix(gv.Group, ".k8s.io") && !legacyUnsuffixedGroups.Has(gv.Group) { - t.Errorf("Group %s does not have the standard kubernetes API group suffix of .k8s.io", gv.Group) - } - } -} - -func TestTypeTags(t *testing.T) { - for gvk, knownType := range legacyscheme.Scheme.AllKnownTypes() { - if gvk.Version == runtime.APIVersionInternal { - ensureNoTags(t, gvk, knownType, nil) - } else { - ensureTags(t, gvk, knownType, nil) - } - } -} - -// These types are registered in external versions, and therefore include json tags, -// but are also registered in internal versions (or referenced from internal types), -// so we explicitly allow tags for them -var typesAllowedTags = map[reflect.Type]bool{ - reflect.TypeOf(intstr.IntOrString{}): true, - reflect.TypeOf(metav1.Time{}): true, - reflect.TypeOf(metav1.MicroTime{}): true, - reflect.TypeOf(metav1.Duration{}): true, - reflect.TypeOf(metav1.TypeMeta{}): true, - reflect.TypeOf(metav1.ListMeta{}): true, - reflect.TypeOf(metav1.ObjectMeta{}): true, - reflect.TypeOf(metav1.OwnerReference{}): true, - reflect.TypeOf(metav1.LabelSelector{}): true, - reflect.TypeOf(metav1.GetOptions{}): true, - reflect.TypeOf(metav1.ExportOptions{}): true, - reflect.TypeOf(metav1.ListOptions{}): true, - reflect.TypeOf(metav1.DeleteOptions{}): true, - reflect.TypeOf(metav1.GroupVersionKind{}): true, - reflect.TypeOf(metav1.GroupVersionResource{}): true, - reflect.TypeOf(metav1.Status{}): true, -} - -func ensureNoTags(t *testing.T, gvk schema.GroupVersionKind, tp reflect.Type, parents []reflect.Type) { - if _, ok := typesAllowedTags[tp]; ok { - return - } - - parents = append(parents, tp) - - switch tp.Kind() { - case reflect.Map, reflect.Slice, reflect.Ptr: - ensureNoTags(t, gvk, tp.Elem(), parents) - - case reflect.String, reflect.Bool, reflect.Float32, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uintptr, reflect.Uint32, reflect.Uint64, reflect.Interface: - // no-op - - case reflect.Struct: - for i := 0; i < tp.NumField(); i++ { - f := tp.Field(i) - if f.PkgPath != "" { - continue // Ignore unexported fields - } - jsonTag := f.Tag.Get("json") - protoTag := f.Tag.Get("protobuf") - if len(jsonTag) > 0 || len(protoTag) > 0 { - t.Errorf("Internal types should not have json or protobuf tags. %#v has tag on field %v: %v", gvk, f.Name, f.Tag) - for i, tp := range parents { - t.Logf("%s%v:", strings.Repeat(" ", i), tp) - } - } - - ensureNoTags(t, gvk, f.Type, parents) - } - - default: - t.Errorf("Unexpected type %v in %#v", tp.Kind(), gvk) - for i, tp := range parents { - t.Logf("%s%v:", strings.Repeat(" ", i), tp) - } - } -} - -var ( - marshalerType = reflect.TypeOf((*json.Marshaler)(nil)).Elem() - unmarshalerType = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() -) - -// These fields are limited exceptions to the standard JSON naming structure. -// Additions should only be made if a non-standard field name was released and cannot be changed for compatibility reasons. -var allowedNonstandardJSONNames = map[reflect.Type]string{ - reflect.TypeOf(v1.DaemonEndpoint{}): "Port", -} - -func ensureTags(t *testing.T, gvk schema.GroupVersionKind, tp reflect.Type, parents []reflect.Type) { - // This type handles its own encoding/decoding and doesn't need json tags - if tp.Implements(marshalerType) && (tp.Implements(unmarshalerType) || reflect.PtrTo(tp).Implements(unmarshalerType)) { - return - } - - parents = append(parents, tp) - - switch tp.Kind() { - case reflect.Map, reflect.Slice, reflect.Ptr: - ensureTags(t, gvk, tp.Elem(), parents) - - case reflect.String, reflect.Bool, reflect.Float32, reflect.Int, reflect.Int32, reflect.Int64, reflect.Uint8, reflect.Uintptr, reflect.Uint32, reflect.Uint64, reflect.Interface: - // no-op - - case reflect.Struct: - for i := 0; i < tp.NumField(); i++ { - f := tp.Field(i) - jsonTag := f.Tag.Get("json") - if len(jsonTag) == 0 { - t.Errorf("External types should have json tags. %#v tags on field %v are: %s", gvk, f.Name, f.Tag) - for i, tp := range parents { - t.Logf("%s%v", strings.Repeat(" ", i), tp) - } - } - - jsonTagName := strings.Split(jsonTag, ",")[0] - if len(jsonTagName) > 0 && (jsonTagName[0] < 'a' || jsonTagName[0] > 'z') && jsonTagName != "-" && allowedNonstandardJSONNames[tp] != jsonTagName { - t.Errorf("External types should have json names starting with lowercase letter. %#v has json tag on field %v with name %s", gvk, f.Name, jsonTagName) - t.Log(tp) - t.Log(allowedNonstandardJSONNames[tp]) - for i, tp := range parents { - t.Logf("%s%v", strings.Repeat(" ", i), tp) - } - } - - ensureTags(t, gvk, f.Type, parents) - } - - default: - t.Errorf("Unexpected type %v in %#v", tp.Kind(), gvk) - for i, tp := range parents { - t.Logf("%s%v:", strings.Repeat(" ", i), tp) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/master/master_openapi_test.go b/vendor/k8s.io/kubernetes/pkg/master/master_openapi_test.go deleted file mode 100644 index d640582a3e..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/master/master_openapi_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// +build !race - -/* -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 master - -// This test file is separated from master_test.go so we would be able to disable -// race check for it. TestValidOpenAPISpec will became extremely slow if -race -// flag exists, and will cause the tests to timeout. - -import ( - "net/http" - "net/http/httptest" - "testing" - - apirequest "k8s.io/apiserver/pkg/endpoints/request" - genericapiserver "k8s.io/apiserver/pkg/server" - "k8s.io/kubernetes/pkg/api/legacyscheme" - openapigen "k8s.io/kubernetes/pkg/generated/openapi" - - "github.com/go-openapi/loads" - "github.com/go-openapi/spec" - "github.com/go-openapi/strfmt" - "github.com/go-openapi/validate" -) - -// TestValidOpenAPISpec verifies that the open api is added -// at the proper endpoint and the spec is valid. -func TestValidOpenAPISpec(t *testing.T) { - etcdserver, config, sharedInformers, assert := setUp(t) - defer etcdserver.Terminate(t) - - config.GenericConfig.EnableIndex = true - config.GenericConfig.OpenAPIConfig = genericapiserver.DefaultOpenAPIConfig(openapigen.GetOpenAPIDefinitions, legacyscheme.Scheme) - config.GenericConfig.OpenAPIConfig.Info = &spec.Info{ - InfoProps: spec.InfoProps{ - Title: "Kubernetes", - Version: "unversioned", - }, - } - config.GenericConfig.SwaggerConfig = genericapiserver.DefaultSwaggerConfig() - - master, err := config.Complete(sharedInformers).New(genericapiserver.EmptyDelegate) - if err != nil { - t.Fatalf("Error in bringing up the master: %v", err) - } - - // make sure swagger.json is not registered before calling PrepareRun. - server := httptest.NewServer(apirequest.WithRequestContext(master.GenericAPIServer.Handler.Director, master.GenericAPIServer.RequestContextMapper())) - defer server.Close() - resp, err := http.Get(server.URL + "/swagger.json") - if !assert.NoError(err) { - t.Errorf("unexpected error: %v", err) - } - assert.Equal(http.StatusNotFound, resp.StatusCode) - - master.GenericAPIServer.PrepareRun() - - resp, err = http.Get(server.URL + "/swagger.json") - if !assert.NoError(err) { - t.Errorf("unexpected error: %v", err) - } - assert.Equal(http.StatusOK, resp.StatusCode) - - // as json schema - var sch spec.Schema - if assert.NoError(decodeResponse(resp, &sch)) { - validator := validate.NewSchemaValidator(spec.MustLoadSwagger20Schema(), nil, "", strfmt.Default) - res := validator.Validate(&sch) - assert.NoError(res.AsError()) - } - - // Validate OpenApi spec - doc, err := loads.Spec(server.URL + "/swagger.json") - if assert.NoError(err) { - validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default) - res, warns := validator.Validate(doc) - assert.NoError(res.AsError()) - if !warns.IsValid() { - t.Logf("Open API spec on root has some warnings : %v", warns) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/master/master_test.go b/vendor/k8s.io/kubernetes/pkg/master/master_test.go deleted file mode 100644 index bb4681e3b7..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/master/master_test.go +++ /dev/null @@ -1,360 +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 master - -import ( - "crypto/tls" - "encoding/json" - "io/ioutil" - "net" - "net/http" - "net/http/httptest" - "reflect" - "strings" - "testing" - - certificatesapiv1beta1 "k8s.io/api/certificates/v1beta1" - apiv1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - utilnet "k8s.io/apimachinery/pkg/util/net" - "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/version" - genericapirequest "k8s.io/apiserver/pkg/endpoints/request" - genericapiserver "k8s.io/apiserver/pkg/server" - "k8s.io/apiserver/pkg/server/options" - serverstorage "k8s.io/apiserver/pkg/server/storage" - etcdtesting "k8s.io/apiserver/pkg/storage/etcd/testing" - "k8s.io/client-go/informers" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/kubernetes/fake" - restclient "k8s.io/client-go/rest" - "k8s.io/kubernetes/pkg/api/legacyscheme" - "k8s.io/kubernetes/pkg/api/testapi" - "k8s.io/kubernetes/pkg/apis/apps" - "k8s.io/kubernetes/pkg/apis/autoscaling" - "k8s.io/kubernetes/pkg/apis/batch" - "k8s.io/kubernetes/pkg/apis/certificates" - api "k8s.io/kubernetes/pkg/apis/core" - "k8s.io/kubernetes/pkg/apis/extensions" - "k8s.io/kubernetes/pkg/apis/rbac" - "k8s.io/kubernetes/pkg/apis/storage" - kubeletclient "k8s.io/kubernetes/pkg/kubelet/client" - "k8s.io/kubernetes/pkg/master/reconcilers" - certificatesrest "k8s.io/kubernetes/pkg/registry/certificates/rest" - corerest "k8s.io/kubernetes/pkg/registry/core/rest" - "k8s.io/kubernetes/pkg/registry/registrytest" - kubeversion "k8s.io/kubernetes/pkg/version" - - "github.com/stretchr/testify/assert" -) - -// setUp is a convience function for setting up for (most) tests. -func setUp(t *testing.T) (*etcdtesting.EtcdTestServer, Config, informers.SharedInformerFactory, *assert.Assertions) { - server, storageConfig := etcdtesting.NewUnsecuredEtcd3TestClientServer(t) - - config := &Config{ - GenericConfig: genericapiserver.NewConfig(legacyscheme.Codecs), - ExtraConfig: ExtraConfig{ - APIResourceConfigSource: DefaultAPIResourceConfigSource(), - APIServerServicePort: 443, - MasterCount: 1, - EndpointReconcilerType: reconcilers.MasterCountReconcilerType, - }, - } - - resourceEncoding := serverstorage.NewDefaultResourceEncodingConfig(legacyscheme.Registry) - resourceEncoding.SetVersionEncoding(api.GroupName, legacyscheme.Registry.GroupOrDie(api.GroupName).GroupVersion, schema.GroupVersion{Group: api.GroupName, Version: runtime.APIVersionInternal}) - resourceEncoding.SetVersionEncoding(autoscaling.GroupName, *testapi.Autoscaling.GroupVersion(), schema.GroupVersion{Group: autoscaling.GroupName, Version: runtime.APIVersionInternal}) - resourceEncoding.SetVersionEncoding(batch.GroupName, *testapi.Batch.GroupVersion(), schema.GroupVersion{Group: batch.GroupName, Version: runtime.APIVersionInternal}) - // FIXME (soltysh): this GroupVersionResource override should be configurable - resourceEncoding.SetResourceEncoding(schema.GroupResource{Group: "batch", Resource: "cronjobs"}, schema.GroupVersion{Group: batch.GroupName, Version: "v1beta1"}, schema.GroupVersion{Group: batch.GroupName, Version: runtime.APIVersionInternal}) - resourceEncoding.SetResourceEncoding(schema.GroupResource{Group: "storage.k8s.io", Resource: "volumeattachments"}, schema.GroupVersion{Group: storage.GroupName, Version: "v1beta1"}, schema.GroupVersion{Group: storage.GroupName, Version: runtime.APIVersionInternal}) - - resourceEncoding.SetVersionEncoding(apps.GroupName, *testapi.Apps.GroupVersion(), schema.GroupVersion{Group: apps.GroupName, Version: runtime.APIVersionInternal}) - resourceEncoding.SetVersionEncoding(extensions.GroupName, *testapi.Extensions.GroupVersion(), schema.GroupVersion{Group: extensions.GroupName, Version: runtime.APIVersionInternal}) - resourceEncoding.SetVersionEncoding(rbac.GroupName, *testapi.Rbac.GroupVersion(), schema.GroupVersion{Group: rbac.GroupName, Version: runtime.APIVersionInternal}) - resourceEncoding.SetVersionEncoding(certificates.GroupName, *testapi.Certificates.GroupVersion(), schema.GroupVersion{Group: certificates.GroupName, Version: runtime.APIVersionInternal}) - storageFactory := serverstorage.NewDefaultStorageFactory(*storageConfig, testapi.StorageMediaType(), legacyscheme.Codecs, resourceEncoding, DefaultAPIResourceConfigSource(), nil) - - etcdOptions := options.NewEtcdOptions(storageConfig) - // unit tests don't need watch cache and it leaks lots of goroutines with etcd testing functions during unit tests - etcdOptions.EnableWatchCache = false - err := etcdOptions.ApplyWithStorageFactoryTo(storageFactory, config.GenericConfig) - if err != nil { - t.Fatal(err) - } - - kubeVersion := kubeversion.Get() - config.GenericConfig.Version = &kubeVersion - config.ExtraConfig.StorageFactory = storageFactory - config.GenericConfig.LoopbackClientConfig = &restclient.Config{APIPath: "/api", ContentConfig: restclient.ContentConfig{NegotiatedSerializer: legacyscheme.Codecs}} - config.GenericConfig.PublicAddress = net.ParseIP("192.168.10.4") - config.GenericConfig.LegacyAPIGroupPrefixes = sets.NewString("/api") - config.GenericConfig.RequestContextMapper = genericapirequest.NewRequestContextMapper() - config.GenericConfig.LoopbackClientConfig = &restclient.Config{APIPath: "/api", ContentConfig: restclient.ContentConfig{NegotiatedSerializer: legacyscheme.Codecs}} - config.GenericConfig.EnableMetrics = true - config.ExtraConfig.EnableCoreControllers = false - config.ExtraConfig.KubeletClientConfig = kubeletclient.KubeletClientConfig{Port: 10250} - config.ExtraConfig.ProxyTransport = utilnet.SetTransportDefaults(&http.Transport{ - Dial: func(network, addr string) (net.Conn, error) { return nil, nil }, - TLSClientConfig: &tls.Config{}, - }) - - clientset, err := kubernetes.NewForConfig(config.GenericConfig.LoopbackClientConfig) - if err != nil { - t.Fatalf("unable to create client set due to %v", err) - } - sharedInformers := informers.NewSharedInformerFactory(clientset, config.GenericConfig.LoopbackClientConfig.Timeout) - - return server, *config, sharedInformers, assert.New(t) -} - -// TestLegacyRestStorageStrategies ensures that all Storage objects which are using the generic registry Store have -// their various strategies properly wired up. This surfaced as a bug where strategies defined Export functions, but -// they were never used outside of unit tests because the export strategies were not assigned inside the Store. -func TestLegacyRestStorageStrategies(t *testing.T) { - _, etcdserver, masterCfg, _ := newMaster(t) - defer etcdserver.Terminate(t) - - storageProvider := corerest.LegacyRESTStorageProvider{ - StorageFactory: masterCfg.ExtraConfig.StorageFactory, - ProxyTransport: masterCfg.ExtraConfig.ProxyTransport, - KubeletClientConfig: masterCfg.ExtraConfig.KubeletClientConfig, - EventTTL: masterCfg.ExtraConfig.EventTTL, - ServiceIPRange: masterCfg.ExtraConfig.ServiceIPRange, - ServiceNodePortRange: masterCfg.ExtraConfig.ServiceNodePortRange, - LoopbackClientConfig: masterCfg.GenericConfig.LoopbackClientConfig, - } - - _, apiGroupInfo, err := storageProvider.NewLegacyRESTStorage(masterCfg.GenericConfig.RESTOptionsGetter) - if err != nil { - t.Errorf("failed to create legacy REST storage: %v", err) - } - - // Any new stores with export logic will need to be added here: - exceptions := registrytest.StrategyExceptions{ - // Only these stores should have an export strategy defined: - HasExportStrategy: []string{ - "secrets", - "limitRanges", - "nodes", - "podTemplates", - }, - } - - strategyErrors := registrytest.ValidateStorageStrategies(apiGroupInfo.VersionedResourcesStorageMap["v1"], exceptions) - for _, err := range strategyErrors { - t.Error(err) - } -} - -func TestCertificatesRestStorageStrategies(t *testing.T) { - _, etcdserver, masterCfg, _ := newMaster(t) - defer etcdserver.Terminate(t) - - certStorageProvider := certificatesrest.RESTStorageProvider{} - apiGroupInfo, _ := certStorageProvider.NewRESTStorage(masterCfg.ExtraConfig.APIResourceConfigSource, masterCfg.GenericConfig.RESTOptionsGetter) - - exceptions := registrytest.StrategyExceptions{ - HasExportStrategy: []string{ - "certificatesigningrequests", - }, - } - - strategyErrors := registrytest.ValidateStorageStrategies( - apiGroupInfo.VersionedResourcesStorageMap[certificatesapiv1beta1.SchemeGroupVersion.Version], exceptions) - for _, err := range strategyErrors { - t.Error(err) - } -} - -func newMaster(t *testing.T) (*Master, *etcdtesting.EtcdTestServer, Config, *assert.Assertions) { - etcdserver, config, sharedInformers, assert := setUp(t) - - master, err := config.Complete(sharedInformers).New(genericapiserver.EmptyDelegate) - if err != nil { - t.Fatalf("Error in bringing up the master: %v", err) - } - - return master, etcdserver, config, assert -} - -// TestVersion tests /version -func TestVersion(t *testing.T) { - s, etcdserver, _, _ := newMaster(t) - defer etcdserver.Terminate(t) - - req, _ := http.NewRequest("GET", "/version", nil) - resp := httptest.NewRecorder() - s.GenericAPIServer.Handler.ServeHTTP(resp, req) - if resp.Code != 200 { - t.Fatalf("expected http 200, got: %d", resp.Code) - } - - var info version.Info - err := json.NewDecoder(resp.Body).Decode(&info) - if err != nil { - t.Errorf("unexpected error: %v", err) - } - - if !reflect.DeepEqual(kubeversion.Get(), info) { - t.Errorf("Expected %#v, Got %#v", kubeversion.Get(), info) - } -} - -type fakeEndpointReconciler struct{} - -func (*fakeEndpointReconciler) ReconcileEndpoints(serviceName string, ip net.IP, endpointPorts []api.EndpointPort, reconcilePorts bool) error { - return nil -} - -func makeNodeList(nodes []string, nodeResources apiv1.NodeResources) *apiv1.NodeList { - list := apiv1.NodeList{ - Items: make([]apiv1.Node, len(nodes)), - } - for i := range nodes { - list.Items[i].Name = nodes[i] - list.Items[i].Status.Capacity = nodeResources.Capacity - } - return &list -} - -// TestGetNodeAddresses verifies that proper results are returned -// when requesting node addresses. -func TestGetNodeAddresses(t *testing.T) { - assert := assert.New(t) - - fakeNodeClient := fake.NewSimpleClientset(makeNodeList([]string{"node1", "node2"}, apiv1.NodeResources{})).Core().Nodes() - addressProvider := nodeAddressProvider{fakeNodeClient} - - // Fail case (no addresses associated with nodes) - nodes, _ := fakeNodeClient.List(metav1.ListOptions{}) - addrs, err := addressProvider.externalAddresses() - - assert.Error(err, "addresses should have caused an error as there are no addresses.") - assert.Equal([]string(nil), addrs) - - // Pass case with External type IP - nodes, _ = fakeNodeClient.List(metav1.ListOptions{}) - for index := range nodes.Items { - nodes.Items[index].Status.Addresses = []apiv1.NodeAddress{{Type: apiv1.NodeExternalIP, Address: "127.0.0.1"}} - fakeNodeClient.Update(&nodes.Items[index]) - } - addrs, err = addressProvider.externalAddresses() - assert.NoError(err, "addresses should not have returned an error.") - assert.Equal([]string{"127.0.0.1", "127.0.0.1"}, addrs) -} - -func decodeResponse(resp *http.Response, obj interface{}) error { - defer resp.Body.Close() - - data, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - if err := json.Unmarshal(data, obj); err != nil { - return err - } - return nil -} - -// Because we need to be backwards compatible with release 1.1, at endpoints -// that exist in release 1.1, the responses should have empty APIVersion. -func TestAPIVersionOfDiscoveryEndpoints(t *testing.T) { - master, etcdserver, _, assert := newMaster(t) - defer etcdserver.Terminate(t) - - server := httptest.NewServer(genericapirequest.WithRequestContext(master.GenericAPIServer.Handler.GoRestfulContainer.ServeMux, master.GenericAPIServer.RequestContextMapper())) - - // /api exists in release-1.1 - resp, err := http.Get(server.URL + "/api") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - apiVersions := metav1.APIVersions{} - assert.NoError(decodeResponse(resp, &apiVersions)) - assert.Equal(apiVersions.APIVersion, "") - - // /api/v1 exists in release-1.1 - resp, err = http.Get(server.URL + "/api/v1") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - resourceList := metav1.APIResourceList{} - assert.NoError(decodeResponse(resp, &resourceList)) - assert.Equal(resourceList.APIVersion, "") - - // /apis exists in release-1.1 - resp, err = http.Get(server.URL + "/apis") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - groupList := metav1.APIGroupList{} - assert.NoError(decodeResponse(resp, &groupList)) - assert.Equal(groupList.APIVersion, "") - - // /apis/extensions exists in release-1.1 - resp, err = http.Get(server.URL + "/apis/extensions") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - group := metav1.APIGroup{} - assert.NoError(decodeResponse(resp, &group)) - assert.Equal(group.APIVersion, "") - - // /apis/extensions/v1beta1 exists in release-1.1 - resp, err = http.Get(server.URL + "/apis/extensions/v1beta1") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - resourceList = metav1.APIResourceList{} - assert.NoError(decodeResponse(resp, &resourceList)) - assert.Equal(resourceList.APIVersion, "") - - // /apis/autoscaling doesn't exist in release-1.1, so the APIVersion field - // should be non-empty in the results returned by the server. - resp, err = http.Get(server.URL + "/apis/autoscaling") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - group = metav1.APIGroup{} - assert.NoError(decodeResponse(resp, &group)) - assert.Equal(group.APIVersion, "v1") - - // apis/autoscaling/v1 doesn't exist in release-1.1, so the APIVersion field - // should be non-empty in the results returned by the server. - - resp, err = http.Get(server.URL + "/apis/autoscaling/v1") - if err != nil { - t.Errorf("unexpected error: %v", err) - } - resourceList = metav1.APIResourceList{} - assert.NoError(decodeResponse(resp, &resourceList)) - assert.Equal(resourceList.APIVersion, "v1") - -} - -func TestNoAlphaVersionsEnabledByDefault(t *testing.T) { - config := DefaultAPIResourceConfigSource() - for gv, enable := range config.GroupVersionConfigs { - if enable && strings.Contains(gv.Version, "alpha") { - t.Errorf("Alpha API version %s enabled by default", gv.String()) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/scheduler/scheduler_test.go b/vendor/k8s.io/kubernetes/pkg/scheduler/scheduler_test.go deleted file mode 100644 index 4debe5217c..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/scheduler/scheduler_test.go +++ /dev/null @@ -1,838 +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 scheduler - -import ( - "errors" - "fmt" - "reflect" - "testing" - "time" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/diff" - "k8s.io/apimachinery/pkg/util/wait" - utilfeature "k8s.io/apiserver/pkg/util/feature" - clientcache "k8s.io/client-go/tools/cache" - "k8s.io/client-go/tools/record" - "k8s.io/kubernetes/pkg/api/legacyscheme" - "k8s.io/kubernetes/pkg/controller/volume/persistentvolume" - "k8s.io/kubernetes/pkg/scheduler/algorithm" - "k8s.io/kubernetes/pkg/scheduler/algorithm/predicates" - "k8s.io/kubernetes/pkg/scheduler/core" - "k8s.io/kubernetes/pkg/scheduler/schedulercache" - schedulertesting "k8s.io/kubernetes/pkg/scheduler/testing" - "k8s.io/kubernetes/pkg/scheduler/util" - "k8s.io/kubernetes/pkg/scheduler/volumebinder" -) - -type fakeBinder struct { - b func(binding *v1.Binding) error -} - -func (fb fakeBinder) Bind(binding *v1.Binding) error { return fb.b(binding) } - -type fakePodConditionUpdater struct{} - -func (fc fakePodConditionUpdater) Update(pod *v1.Pod, podCondition *v1.PodCondition) error { - return nil -} - -type fakePodPreemptor struct{} - -func (fp fakePodPreemptor) GetUpdatedPod(pod *v1.Pod) (*v1.Pod, error) { - return pod, nil -} - -func (fp fakePodPreemptor) DeletePod(pod *v1.Pod) error { - return nil -} - -func (fp fakePodPreemptor) SetNominatedNodeName(pod *v1.Pod, nomNodeName string) error { - return nil -} - -func (fp fakePodPreemptor) RemoveNominatedNodeName(pod *v1.Pod) error { - return nil -} - -func podWithID(id, desiredHost string) *v1.Pod { - return &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: id, - UID: types.UID(id), - SelfLink: util.Test.SelfLink(string(v1.ResourcePods), id), - }, - Spec: v1.PodSpec{ - NodeName: desiredHost, - }, - } -} - -func deletingPod(id string) *v1.Pod { - deletionTimestamp := metav1.Now() - return &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: id, - UID: types.UID(id), - SelfLink: util.Test.SelfLink(string(v1.ResourcePods), id), - DeletionTimestamp: &deletionTimestamp, - }, - Spec: v1.PodSpec{ - NodeName: "", - }, - } -} - -func podWithPort(id, desiredHost string, port int) *v1.Pod { - pod := podWithID(id, desiredHost) - pod.Spec.Containers = []v1.Container{ - {Name: "ctr", Ports: []v1.ContainerPort{{HostPort: int32(port)}}}, - } - return pod -} - -func podWithResources(id, desiredHost string, limits v1.ResourceList, requests v1.ResourceList) *v1.Pod { - pod := podWithID(id, desiredHost) - pod.Spec.Containers = []v1.Container{ - {Name: "ctr", Resources: v1.ResourceRequirements{Limits: limits, Requests: requests}}, - } - return pod -} - -type mockScheduler struct { - machine string - err error -} - -func (es mockScheduler) Schedule(pod *v1.Pod, ml algorithm.NodeLister) (string, error) { - return es.machine, es.err -} - -func (es mockScheduler) Predicates() map[string]algorithm.FitPredicate { - return nil -} -func (es mockScheduler) Prioritizers() []algorithm.PriorityConfig { - return nil -} - -func (es mockScheduler) Preempt(pod *v1.Pod, nodeLister algorithm.NodeLister, scheduleErr error) (*v1.Node, []*v1.Pod, []*v1.Pod, error) { - return nil, nil, nil, nil -} - -func TestScheduler(t *testing.T) { - eventBroadcaster := record.NewBroadcaster() - eventBroadcaster.StartLogging(t.Logf).Stop() - errS := errors.New("scheduler") - errB := errors.New("binder") - testNode := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}} - - table := []struct { - injectBindError error - sendPod *v1.Pod - algo algorithm.ScheduleAlgorithm - expectErrorPod *v1.Pod - expectForgetPod *v1.Pod - expectAssumedPod *v1.Pod - expectError error - expectBind *v1.Binding - eventReason string - }{ - { - sendPod: podWithID("foo", ""), - algo: mockScheduler{testNode.Name, nil}, - expectBind: &v1.Binding{ObjectMeta: metav1.ObjectMeta{Name: "foo", UID: types.UID("foo")}, Target: v1.ObjectReference{Kind: "Node", Name: testNode.Name}}, - expectAssumedPod: podWithID("foo", testNode.Name), - eventReason: "Scheduled", - }, { - sendPod: podWithID("foo", ""), - algo: mockScheduler{testNode.Name, errS}, - expectError: errS, - expectErrorPod: podWithID("foo", ""), - eventReason: "FailedScheduling", - }, { - sendPod: podWithID("foo", ""), - algo: mockScheduler{testNode.Name, nil}, - expectBind: &v1.Binding{ObjectMeta: metav1.ObjectMeta{Name: "foo", UID: types.UID("foo")}, Target: v1.ObjectReference{Kind: "Node", Name: testNode.Name}}, - expectAssumedPod: podWithID("foo", testNode.Name), - injectBindError: errB, - expectError: errB, - expectErrorPod: podWithID("foo", testNode.Name), - expectForgetPod: podWithID("foo", testNode.Name), - eventReason: "FailedScheduling", - }, { - sendPod: deletingPod("foo"), - algo: mockScheduler{"", nil}, - eventReason: "FailedScheduling", - }, - } - - for i, item := range table { - var gotError error - var gotPod *v1.Pod - var gotForgetPod *v1.Pod - var gotAssumedPod *v1.Pod - var gotBinding *v1.Binding - configurator := &FakeConfigurator{ - Config: &Config{ - SchedulerCache: &schedulertesting.FakeCache{ - ForgetFunc: func(pod *v1.Pod) { - gotForgetPod = pod - }, - AssumeFunc: func(pod *v1.Pod) { - gotAssumedPod = pod - }, - }, - NodeLister: schedulertesting.FakeNodeLister( - []*v1.Node{&testNode}, - ), - Algorithm: item.algo, - GetBinder: func(pod *v1.Pod) Binder { - return fakeBinder{func(b *v1.Binding) error { - gotBinding = b - return item.injectBindError - }} - }, - PodConditionUpdater: fakePodConditionUpdater{}, - Error: func(p *v1.Pod, err error) { - gotPod = p - gotError = err - }, - NextPod: func() *v1.Pod { - return item.sendPod - }, - Recorder: eventBroadcaster.NewRecorder(legacyscheme.Scheme, v1.EventSource{Component: "scheduler"}), - VolumeBinder: volumebinder.NewFakeVolumeBinder(&persistentvolume.FakeVolumeBinderConfig{AllBound: true}), - }, - } - - s, _ := NewFromConfigurator(configurator, nil...) - called := make(chan struct{}) - events := eventBroadcaster.StartEventWatcher(func(e *v1.Event) { - if e, a := item.eventReason, e.Reason; e != a { - t.Errorf("%v: expected %v, got %v", i, e, a) - } - close(called) - }) - s.scheduleOne() - <-called - if e, a := item.expectAssumedPod, gotAssumedPod; !reflect.DeepEqual(e, a) { - t.Errorf("%v: assumed pod: wanted %v, got %v", i, e, a) - } - if e, a := item.expectErrorPod, gotPod; !reflect.DeepEqual(e, a) { - t.Errorf("%v: error pod: wanted %v, got %v", i, e, a) - } - if e, a := item.expectForgetPod, gotForgetPod; !reflect.DeepEqual(e, a) { - t.Errorf("%v: forget pod: wanted %v, got %v", i, e, a) - } - if e, a := item.expectError, gotError; !reflect.DeepEqual(e, a) { - t.Errorf("%v: error: wanted %v, got %v", i, e, a) - } - if e, a := item.expectBind, gotBinding; !reflect.DeepEqual(e, a) { - t.Errorf("%v: error: %s", i, diff.ObjectDiff(e, a)) - } - events.Stop() - } -} - -func TestSchedulerNoPhantomPodAfterExpire(t *testing.T) { - stop := make(chan struct{}) - defer close(stop) - queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc) - scache := schedulercache.New(100*time.Millisecond, stop) - pod := podWithPort("pod.Name", "", 8080) - node := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}} - scache.AddNode(&node) - nodeLister := schedulertesting.FakeNodeLister([]*v1.Node{&node}) - predicateMap := map[string]algorithm.FitPredicate{"PodFitsHostPorts": predicates.PodFitsHostPorts} - scheduler, bindingChan, _ := setupTestSchedulerWithOnePodOnNode(t, queuedPodStore, scache, nodeLister, predicateMap, pod, &node) - - waitPodExpireChan := make(chan struct{}) - timeout := make(chan struct{}) - go func() { - for { - select { - case <-timeout: - return - default: - } - pods, err := scache.List(labels.Everything()) - if err != nil { - t.Fatalf("cache.List failed: %v", err) - } - if len(pods) == 0 { - close(waitPodExpireChan) - return - } - time.Sleep(100 * time.Millisecond) - } - }() - // waiting for the assumed pod to expire - select { - case <-waitPodExpireChan: - case <-time.After(wait.ForeverTestTimeout): - close(timeout) - t.Fatalf("timeout timeout in waiting pod expire after %v", wait.ForeverTestTimeout) - } - - // We use conflicted pod ports to incur fit predicate failure if first pod not removed. - secondPod := podWithPort("bar", "", 8080) - queuedPodStore.Add(secondPod) - scheduler.scheduleOne() - select { - case b := <-bindingChan: - expectBinding := &v1.Binding{ - ObjectMeta: metav1.ObjectMeta{Name: "bar", UID: types.UID("bar")}, - Target: v1.ObjectReference{Kind: "Node", Name: node.Name}, - } - if !reflect.DeepEqual(expectBinding, b) { - t.Errorf("binding want=%v, get=%v", expectBinding, b) - } - case <-time.After(wait.ForeverTestTimeout): - t.Fatalf("timeout in binding after %v", wait.ForeverTestTimeout) - } -} - -func TestSchedulerNoPhantomPodAfterDelete(t *testing.T) { - stop := make(chan struct{}) - defer close(stop) - queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc) - scache := schedulercache.New(10*time.Minute, stop) - firstPod := podWithPort("pod.Name", "", 8080) - node := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}} - scache.AddNode(&node) - nodeLister := schedulertesting.FakeNodeLister([]*v1.Node{&node}) - predicateMap := map[string]algorithm.FitPredicate{"PodFitsHostPorts": predicates.PodFitsHostPorts} - scheduler, bindingChan, errChan := setupTestSchedulerWithOnePodOnNode(t, queuedPodStore, scache, nodeLister, predicateMap, firstPod, &node) - - // We use conflicted pod ports to incur fit predicate failure. - secondPod := podWithPort("bar", "", 8080) - queuedPodStore.Add(secondPod) - // queuedPodStore: [bar:8080] - // cache: [(assumed)foo:8080] - - scheduler.scheduleOne() - select { - case err := <-errChan: - expectErr := &core.FitError{ - Pod: secondPod, - NumAllNodes: 1, - FailedPredicates: core.FailedPredicateMap{node.Name: []algorithm.PredicateFailureReason{predicates.ErrPodNotFitsHostPorts}}, - } - if !reflect.DeepEqual(expectErr, err) { - t.Errorf("err want=%v, get=%v", expectErr, err) - } - case <-time.After(wait.ForeverTestTimeout): - t.Fatalf("timeout in fitting after %v", wait.ForeverTestTimeout) - } - - // We mimic the workflow of cache behavior when a pod is removed by user. - // Note: if the schedulercache timeout would be super short, the first pod would expire - // and would be removed itself (without any explicit actions on schedulercache). Even in that case, - // explicitly AddPod will as well correct the behavior. - firstPod.Spec.NodeName = node.Name - if err := scache.AddPod(firstPod); err != nil { - t.Fatalf("err: %v", err) - } - if err := scache.RemovePod(firstPod); err != nil { - t.Fatalf("err: %v", err) - } - - queuedPodStore.Add(secondPod) - scheduler.scheduleOne() - select { - case b := <-bindingChan: - expectBinding := &v1.Binding{ - ObjectMeta: metav1.ObjectMeta{Name: "bar", UID: types.UID("bar")}, - Target: v1.ObjectReference{Kind: "Node", Name: node.Name}, - } - if !reflect.DeepEqual(expectBinding, b) { - t.Errorf("binding want=%v, get=%v", expectBinding, b) - } - case <-time.After(wait.ForeverTestTimeout): - t.Fatalf("timeout in binding after %v", wait.ForeverTestTimeout) - } -} - -// Scheduler should preserve predicate constraint even if binding was longer -// than cache ttl -func TestSchedulerErrorWithLongBinding(t *testing.T) { - stop := make(chan struct{}) - defer close(stop) - - firstPod := podWithPort("foo", "", 8080) - conflictPod := podWithPort("bar", "", 8080) - pods := map[string]*v1.Pod{firstPod.Name: firstPod, conflictPod.Name: conflictPod} - for _, test := range []struct { - Expected map[string]bool - CacheTTL time.Duration - BindingDuration time.Duration - }{ - { - Expected: map[string]bool{firstPod.Name: true}, - CacheTTL: 100 * time.Millisecond, - BindingDuration: 300 * time.Millisecond, - }, - { - Expected: map[string]bool{firstPod.Name: true}, - CacheTTL: 10 * time.Second, - BindingDuration: 300 * time.Millisecond, - }, - } { - queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc) - scache := schedulercache.New(test.CacheTTL, stop) - - node := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}} - scache.AddNode(&node) - - nodeLister := schedulertesting.FakeNodeLister([]*v1.Node{&node}) - predicateMap := map[string]algorithm.FitPredicate{"PodFitsHostPorts": predicates.PodFitsHostPorts} - - scheduler, bindingChan := setupTestSchedulerLongBindingWithRetry( - queuedPodStore, scache, nodeLister, predicateMap, stop, test.BindingDuration) - scheduler.Run() - queuedPodStore.Add(firstPod) - queuedPodStore.Add(conflictPod) - - resultBindings := map[string]bool{} - waitChan := time.After(5 * time.Second) - for finished := false; !finished; { - select { - case b := <-bindingChan: - resultBindings[b.Name] = true - p := pods[b.Name] - p.Spec.NodeName = b.Target.Name - scache.AddPod(p) - case <-waitChan: - finished = true - } - } - if !reflect.DeepEqual(resultBindings, test.Expected) { - t.Errorf("Result binding are not equal to expected. %v != %v", resultBindings, test.Expected) - } - } -} - -// queuedPodStore: pods queued before processing. -// cache: scheduler cache that might contain assumed pods. -func setupTestSchedulerWithOnePodOnNode(t *testing.T, queuedPodStore *clientcache.FIFO, scache schedulercache.Cache, - nodeLister schedulertesting.FakeNodeLister, predicateMap map[string]algorithm.FitPredicate, pod *v1.Pod, node *v1.Node) (*Scheduler, chan *v1.Binding, chan error) { - - scheduler, bindingChan, errChan := setupTestScheduler(queuedPodStore, scache, nodeLister, predicateMap, nil) - - queuedPodStore.Add(pod) - // queuedPodStore: [foo:8080] - // cache: [] - - scheduler.scheduleOne() - // queuedPodStore: [] - // cache: [(assumed)foo:8080] - - select { - case b := <-bindingChan: - expectBinding := &v1.Binding{ - ObjectMeta: metav1.ObjectMeta{Name: pod.Name, UID: types.UID(pod.Name)}, - Target: v1.ObjectReference{Kind: "Node", Name: node.Name}, - } - if !reflect.DeepEqual(expectBinding, b) { - t.Errorf("binding want=%v, get=%v", expectBinding, b) - } - case <-time.After(wait.ForeverTestTimeout): - t.Fatalf("timeout after %v", wait.ForeverTestTimeout) - } - return scheduler, bindingChan, errChan -} - -func TestSchedulerFailedSchedulingReasons(t *testing.T) { - stop := make(chan struct{}) - defer close(stop) - queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc) - scache := schedulercache.New(10*time.Minute, stop) - - // Design the baseline for the pods, and we will make nodes that dont fit it later. - var cpu = int64(4) - var mem = int64(500) - podWithTooBigResourceRequests := podWithResources("bar", "", v1.ResourceList{ - v1.ResourceCPU: *(resource.NewQuantity(cpu, resource.DecimalSI)), - v1.ResourceMemory: *(resource.NewQuantity(mem, resource.DecimalSI)), - }, v1.ResourceList{ - v1.ResourceCPU: *(resource.NewQuantity(cpu, resource.DecimalSI)), - v1.ResourceMemory: *(resource.NewQuantity(mem, resource.DecimalSI)), - }) - - // create several nodes which cannot schedule the above pod - nodes := []*v1.Node{} - for i := 0; i < 100; i++ { - uid := fmt.Sprintf("machine%v", i) - node := v1.Node{ - ObjectMeta: metav1.ObjectMeta{Name: uid, UID: types.UID(uid)}, - Status: v1.NodeStatus{ - Capacity: v1.ResourceList{ - v1.ResourceCPU: *(resource.NewQuantity(cpu/2, resource.DecimalSI)), - v1.ResourceMemory: *(resource.NewQuantity(mem/5, resource.DecimalSI)), - v1.ResourcePods: *(resource.NewQuantity(10, resource.DecimalSI)), - }, - Allocatable: v1.ResourceList{ - v1.ResourceCPU: *(resource.NewQuantity(cpu/2, resource.DecimalSI)), - v1.ResourceMemory: *(resource.NewQuantity(mem/5, resource.DecimalSI)), - v1.ResourcePods: *(resource.NewQuantity(10, resource.DecimalSI)), - }}, - } - scache.AddNode(&node) - nodes = append(nodes, &node) - } - nodeLister := schedulertesting.FakeNodeLister(nodes) - predicateMap := map[string]algorithm.FitPredicate{ - "PodFitsResources": predicates.PodFitsResources, - } - - // Create expected failure reasons for all the nodes. Hopefully they will get rolled up into a non-spammy summary. - failedPredicatesMap := core.FailedPredicateMap{} - for _, node := range nodes { - failedPredicatesMap[node.Name] = []algorithm.PredicateFailureReason{ - predicates.NewInsufficientResourceError(v1.ResourceCPU, 4000, 0, 2000), - predicates.NewInsufficientResourceError(v1.ResourceMemory, 500, 0, 100), - } - } - scheduler, _, errChan := setupTestScheduler(queuedPodStore, scache, nodeLister, predicateMap, nil) - - queuedPodStore.Add(podWithTooBigResourceRequests) - scheduler.scheduleOne() - select { - case err := <-errChan: - expectErr := &core.FitError{ - Pod: podWithTooBigResourceRequests, - NumAllNodes: len(nodes), - FailedPredicates: failedPredicatesMap, - } - if len(fmt.Sprint(expectErr)) > 150 { - t.Errorf("message is too spammy ! %v ", len(fmt.Sprint(expectErr))) - } - if !reflect.DeepEqual(expectErr, err) { - t.Errorf("\n err \nWANT=%+v,\nGOT=%+v", expectErr, err) - } - case <-time.After(wait.ForeverTestTimeout): - t.Fatalf("timeout after %v", wait.ForeverTestTimeout) - } -} - -// queuedPodStore: pods queued before processing. -// scache: scheduler cache that might contain assumed pods. -func setupTestScheduler(queuedPodStore *clientcache.FIFO, scache schedulercache.Cache, nodeLister schedulertesting.FakeNodeLister, predicateMap map[string]algorithm.FitPredicate, recorder record.EventRecorder) (*Scheduler, chan *v1.Binding, chan error) { - algo := core.NewGenericScheduler( - scache, - nil, - nil, - predicateMap, - algorithm.EmptyPredicateMetadataProducer, - []algorithm.PriorityConfig{}, - algorithm.EmptyPriorityMetadataProducer, - []algorithm.SchedulerExtender{}, - nil, - schedulertesting.FakePersistentVolumeClaimLister{}, - false) - bindingChan := make(chan *v1.Binding, 1) - errChan := make(chan error, 1) - configurator := &FakeConfigurator{ - Config: &Config{ - SchedulerCache: scache, - NodeLister: nodeLister, - Algorithm: algo, - GetBinder: func(pod *v1.Pod) Binder { - return fakeBinder{func(b *v1.Binding) error { - bindingChan <- b - return nil - }} - }, - NextPod: func() *v1.Pod { - return clientcache.Pop(queuedPodStore).(*v1.Pod) - }, - Error: func(p *v1.Pod, err error) { - errChan <- err - }, - Recorder: &record.FakeRecorder{}, - PodConditionUpdater: fakePodConditionUpdater{}, - PodPreemptor: fakePodPreemptor{}, - VolumeBinder: volumebinder.NewFakeVolumeBinder(&persistentvolume.FakeVolumeBinderConfig{AllBound: true}), - }, - } - - if recorder != nil { - configurator.Config.Recorder = recorder - } - - sched, _ := NewFromConfigurator(configurator, nil...) - - return sched, bindingChan, errChan -} - -func setupTestSchedulerLongBindingWithRetry(queuedPodStore *clientcache.FIFO, scache schedulercache.Cache, nodeLister schedulertesting.FakeNodeLister, predicateMap map[string]algorithm.FitPredicate, stop chan struct{}, bindingTime time.Duration) (*Scheduler, chan *v1.Binding) { - algo := core.NewGenericScheduler( - scache, - nil, - nil, - predicateMap, - algorithm.EmptyPredicateMetadataProducer, - []algorithm.PriorityConfig{}, - algorithm.EmptyPriorityMetadataProducer, - []algorithm.SchedulerExtender{}, - nil, - schedulertesting.FakePersistentVolumeClaimLister{}, - false) - bindingChan := make(chan *v1.Binding, 2) - configurator := &FakeConfigurator{ - Config: &Config{ - SchedulerCache: scache, - NodeLister: nodeLister, - Algorithm: algo, - GetBinder: func(pod *v1.Pod) Binder { - return fakeBinder{func(b *v1.Binding) error { - time.Sleep(bindingTime) - bindingChan <- b - return nil - }} - }, - WaitForCacheSync: func() bool { - return true - }, - NextPod: func() *v1.Pod { - return clientcache.Pop(queuedPodStore).(*v1.Pod) - }, - Error: func(p *v1.Pod, err error) { - queuedPodStore.AddIfNotPresent(p) - }, - Recorder: &record.FakeRecorder{}, - PodConditionUpdater: fakePodConditionUpdater{}, - PodPreemptor: fakePodPreemptor{}, - StopEverything: stop, - VolumeBinder: volumebinder.NewFakeVolumeBinder(&persistentvolume.FakeVolumeBinderConfig{AllBound: true}), - }, - } - - sched, _ := NewFromConfigurator(configurator, nil...) - - return sched, bindingChan -} - -func setupTestSchedulerWithVolumeBinding(fakeVolumeBinder *volumebinder.VolumeBinder, stop <-chan struct{}, broadcaster record.EventBroadcaster) (*Scheduler, chan *v1.Binding, chan error) { - testNode := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}} - nodeLister := schedulertesting.FakeNodeLister([]*v1.Node{&testNode}) - queuedPodStore := clientcache.NewFIFO(clientcache.MetaNamespaceKeyFunc) - queuedPodStore.Add(podWithID("foo", "")) - scache := schedulercache.New(10*time.Minute, stop) - scache.AddNode(&testNode) - - predicateMap := map[string]algorithm.FitPredicate{ - predicates.CheckVolumeBindingPred: predicates.NewVolumeBindingPredicate(fakeVolumeBinder), - } - - recorder := broadcaster.NewRecorder(legacyscheme.Scheme, v1.EventSource{Component: "scheduler"}) - s, bindingChan, errChan := setupTestScheduler(queuedPodStore, scache, nodeLister, predicateMap, recorder) - s.config.VolumeBinder = fakeVolumeBinder - return s, bindingChan, errChan -} - -// This is a workaround because golint complains that errors cannot -// end with punctuation. However, the real predicate error message does -// end with a period. -func makePredicateError(failReason string) error { - s := fmt.Sprintf("0/1 nodes are available: %v.", failReason) - return fmt.Errorf(s) -} - -func TestSchedulerWithVolumeBinding(t *testing.T) { - order := []string{predicates.CheckVolumeBindingPred, predicates.GeneralPred} - predicates.SetPredicatesOrdering(order) - findErr := fmt.Errorf("find err") - assumeErr := fmt.Errorf("assume err") - bindErr := fmt.Errorf("bind err") - - eventBroadcaster := record.NewBroadcaster() - eventBroadcaster.StartLogging(t.Logf).Stop() - - // This can be small because we wait for pod to finish scheduling first - chanTimeout := 2 * time.Second - - utilfeature.DefaultFeatureGate.Set("VolumeScheduling=true") - defer utilfeature.DefaultFeatureGate.Set("VolumeScheduling=false") - - table := map[string]struct { - expectError error - expectPodBind *v1.Binding - expectAssumeCalled bool - expectBindCalled bool - eventReason string - volumeBinderConfig *persistentvolume.FakeVolumeBinderConfig - }{ - "all-bound": { - volumeBinderConfig: &persistentvolume.FakeVolumeBinderConfig{ - AllBound: true, - FindUnboundSatsified: true, - FindBoundSatsified: true, - }, - expectAssumeCalled: true, - expectPodBind: &v1.Binding{ObjectMeta: metav1.ObjectMeta{Name: "foo", UID: types.UID("foo")}, Target: v1.ObjectReference{Kind: "Node", Name: "machine1"}}, - - eventReason: "Scheduled", - }, - "bound,invalid-pv-affinity": { - volumeBinderConfig: &persistentvolume.FakeVolumeBinderConfig{ - AllBound: true, - FindUnboundSatsified: true, - FindBoundSatsified: false, - }, - eventReason: "FailedScheduling", - expectError: makePredicateError("1 node(s) had volume node affinity conflict"), - }, - "unbound,no-matches": { - volumeBinderConfig: &persistentvolume.FakeVolumeBinderConfig{ - FindUnboundSatsified: false, - FindBoundSatsified: true, - }, - eventReason: "FailedScheduling", - expectError: makePredicateError("1 node(s) didn't find available persistent volumes to bind"), - }, - "bound-and-unbound-unsatisfied": { - volumeBinderConfig: &persistentvolume.FakeVolumeBinderConfig{ - FindUnboundSatsified: false, - FindBoundSatsified: false, - }, - eventReason: "FailedScheduling", - expectError: makePredicateError("1 node(s) didn't find available persistent volumes to bind, 1 node(s) had volume node affinity conflict"), - }, - "unbound,found-matches": { - volumeBinderConfig: &persistentvolume.FakeVolumeBinderConfig{ - FindUnboundSatsified: true, - FindBoundSatsified: true, - AssumeBindingRequired: true, - }, - expectAssumeCalled: true, - expectBindCalled: true, - eventReason: "FailedScheduling", - expectError: fmt.Errorf("Volume binding started, waiting for completion"), - }, - "unbound,found-matches,already-bound": { - volumeBinderConfig: &persistentvolume.FakeVolumeBinderConfig{ - FindUnboundSatsified: true, - FindBoundSatsified: true, - AssumeBindingRequired: false, - }, - expectAssumeCalled: true, - expectBindCalled: false, - eventReason: "FailedScheduling", - expectError: fmt.Errorf("Volume binding started, waiting for completion"), - }, - "predicate-error": { - volumeBinderConfig: &persistentvolume.FakeVolumeBinderConfig{ - FindErr: findErr, - }, - eventReason: "FailedScheduling", - expectError: findErr, - }, - "assume-error": { - volumeBinderConfig: &persistentvolume.FakeVolumeBinderConfig{ - FindUnboundSatsified: true, - FindBoundSatsified: true, - AssumeErr: assumeErr, - }, - expectAssumeCalled: true, - eventReason: "FailedScheduling", - expectError: assumeErr, - }, - "bind-error": { - volumeBinderConfig: &persistentvolume.FakeVolumeBinderConfig{ - FindUnboundSatsified: true, - FindBoundSatsified: true, - AssumeBindingRequired: true, - BindErr: bindErr, - }, - expectAssumeCalled: true, - expectBindCalled: true, - eventReason: "FailedScheduling", - expectError: bindErr, - }, - } - - for name, item := range table { - stop := make(chan struct{}) - fakeVolumeBinder := volumebinder.NewFakeVolumeBinder(item.volumeBinderConfig) - internalBinder, ok := fakeVolumeBinder.Binder.(*persistentvolume.FakeVolumeBinder) - if !ok { - t.Fatalf("Failed to get fake volume binder") - } - s, bindingChan, errChan := setupTestSchedulerWithVolumeBinding(fakeVolumeBinder, stop, eventBroadcaster) - - eventChan := make(chan struct{}) - events := eventBroadcaster.StartEventWatcher(func(e *v1.Event) { - if e, a := item.eventReason, e.Reason; e != a { - t.Errorf("%v: expected %v, got %v", name, e, a) - } - close(eventChan) - }) - - go fakeVolumeBinder.Run(s.bindVolumesWorker, stop) - - s.scheduleOne() - - // Wait for pod to succeed or fail scheduling - select { - case <-eventChan: - case <-time.After(wait.ForeverTestTimeout): - t.Fatalf("%v: scheduling timeout after %v", name, wait.ForeverTestTimeout) - } - - events.Stop() - - // Wait for scheduling to return an error - select { - case err := <-errChan: - if item.expectError == nil || !reflect.DeepEqual(item.expectError.Error(), err.Error()) { - t.Errorf("%v: \n err \nWANT=%+v,\nGOT=%+v", name, item.expectError, err) - } - case <-time.After(chanTimeout): - if item.expectError != nil { - t.Errorf("%v: did not receive error after %v", name, chanTimeout) - } - } - - // Wait for pod to succeed binding - select { - case b := <-bindingChan: - if !reflect.DeepEqual(item.expectPodBind, b) { - t.Errorf("%v: \n err \nWANT=%+v,\nGOT=%+v", name, item.expectPodBind, b) - } - case <-time.After(chanTimeout): - if item.expectPodBind != nil { - t.Errorf("%v: did not receive pod binding after %v", name, chanTimeout) - } - } - - if item.expectAssumeCalled != internalBinder.AssumeCalled { - t.Errorf("%v: expectedAssumeCall %v", name, item.expectAssumeCalled) - } - - if item.expectBindCalled != internalBinder.BindCalled { - t.Errorf("%v: expectedBindCall %v", name, item.expectBindCalled) - } - - close(stop) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/security/apparmor/validate_test.go b/vendor/k8s.io/kubernetes/pkg/security/apparmor/validate_test.go deleted file mode 100644 index 54da00e557..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/security/apparmor/validate_test.go +++ /dev/null @@ -1,198 +0,0 @@ -/* -Copyright 2016 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 apparmor - -import ( - "errors" - "fmt" - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "github.com/stretchr/testify/assert" -) - -func TestGetAppArmorFS(t *testing.T) { - // This test only passes on systems running AppArmor with the default configuration. - // The test should be manually run if modifying the getAppArmorFS function. - t.Skip() - - const expectedPath = "/sys/kernel/security/apparmor" - actualPath, err := getAppArmorFS() - assert.NoError(t, err) - assert.Equal(t, expectedPath, actualPath) -} - -func TestValidateHost(t *testing.T) { - // This test only passes on systems running AppArmor with the default configuration. - // The test should be manually run if modifying the getAppArmorFS function. - t.Skip() - - assert.NoError(t, validateHost("docker")) - assert.Error(t, validateHost("rkt")) -} - -func TestValidateProfile(t *testing.T) { - loadedProfiles := map[string]bool{ - "docker-default": true, - "foo-bar": true, - "baz": true, - "/usr/sbin/ntpd": true, - "/usr/lib/connman/scripts/dhclient-script": true, - "/usr/lib/NetworkManager/nm-dhcp-client.action": true, - "/usr/bin/evince-previewer//sanitized_helper": true, - } - tests := []struct { - profile string - expectValid bool - }{ - {"", true}, - {ProfileRuntimeDefault, true}, - {ProfileNameUnconfined, true}, - {"baz", false}, // Missing local prefix. - {ProfileNamePrefix + "/usr/sbin/ntpd", true}, - {ProfileNamePrefix + "foo-bar", true}, - {ProfileNamePrefix + "unloaded", false}, // Not loaded. - {ProfileNamePrefix + "", false}, - } - - for _, test := range tests { - err := validateProfile(test.profile, loadedProfiles) - if test.expectValid { - assert.NoError(t, err, "Profile %s should be valid", test.profile) - } else { - assert.Error(t, err, fmt.Sprintf("Profile %s should not be valid", test.profile)) - } - } -} - -func TestValidateBadHost(t *testing.T) { - hostErr := errors.New("expected host error") - v := &validator{ - validateHostErr: hostErr, - } - - tests := []struct { - profile string - expectValid bool - }{ - {"", true}, - {ProfileRuntimeDefault, false}, - {ProfileNamePrefix + "docker-default", false}, - } - - for _, test := range tests { - err := v.Validate(getPodWithProfile(test.profile)) - if test.expectValid { - assert.NoError(t, err, "Pod with profile %q should be valid", test.profile) - } else { - assert.Equal(t, hostErr, err, "Pod with profile %q should trigger a host validation error", test.profile) - } - } -} - -func TestValidateValidHost(t *testing.T) { - v := &validator{ - appArmorFS: "./testdata/", - } - - tests := []struct { - profile string - expectValid bool - }{ - {"", true}, - {ProfileRuntimeDefault, true}, - {ProfileNamePrefix + "docker-default", true}, - {ProfileNamePrefix + "foo-container", true}, - {ProfileNamePrefix + "/usr/sbin/ntpd", true}, - {"docker-default", false}, - {ProfileNamePrefix + "foo", false}, - {ProfileNamePrefix + "", false}, - } - - for _, test := range tests { - err := v.Validate(getPodWithProfile(test.profile)) - if test.expectValid { - assert.NoError(t, err, "Pod with profile %q should be valid", test.profile) - } else { - assert.Error(t, err, fmt.Sprintf("Pod with profile %q should trigger a validation error", test.profile)) - } - } - - // Test multi-container pod. - pod := &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: map[string]string{ - ContainerAnnotationKeyPrefix + "init": ProfileNamePrefix + "foo-container", - ContainerAnnotationKeyPrefix + "test1": ProfileRuntimeDefault, - ContainerAnnotationKeyPrefix + "test2": ProfileNamePrefix + "docker-default", - }, - }, - Spec: v1.PodSpec{ - InitContainers: []v1.Container{ - {Name: "init"}, - }, - Containers: []v1.Container{ - {Name: "test1"}, - {Name: "test2"}, - {Name: "no-profile"}, - }, - }, - } - assert.NoError(t, v.Validate(pod), "Multi-container pod should validate") - for k, val := range pod.Annotations { - pod.Annotations[k] = val + "-bad" - assert.Error(t, v.Validate(pod), fmt.Sprintf("Multi-container pod with invalid profile %s:%s", k, pod.Annotations[k])) - pod.Annotations[k] = val // Restore. - } -} - -func TestParseProfileName(t *testing.T) { - tests := []struct{ line, expected string }{ - {"foo://bar/baz (kill)", "foo://bar/baz"}, - {"foo-bar (enforce)", "foo-bar"}, - {"/usr/foo/bar/baz (complain)", "/usr/foo/bar/baz"}, - } - for _, test := range tests { - name := parseProfileName(test.line) - assert.Equal(t, test.expected, name, "Parsing %s", test.line) - } -} - -func getPodWithProfile(profile string) *v1.Pod { - annotations := map[string]string{ - ContainerAnnotationKeyPrefix + "test": profile, - } - if profile == "" { - annotations = map[string]string{ - "foo": "bar", - } - } - return &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Annotations: annotations, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - Name: "test", - }, - }, - }, - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/serviceaccount/claims_test.go b/vendor/k8s.io/kubernetes/pkg/serviceaccount/claims_test.go deleted file mode 100644 index aec036f8d6..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/serviceaccount/claims_test.go +++ /dev/null @@ -1,184 +0,0 @@ -/* -Copyright 2018 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 serviceaccount - -import ( - "encoding/json" - "fmt" - "testing" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/kubernetes/pkg/apis/core" - - "gopkg.in/square/go-jose.v2/jwt" -) - -func init() { - now = func() time.Time { - // epoch time: 1514764800 - return time.Date(2018, time.January, 1, 0, 0, 0, 0, time.UTC) - } -} - -func TestClaims(t *testing.T) { - sa := core.ServiceAccount{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "myns", - Name: "mysvcacct", - UID: "mysvcacct-uid", - }, - } - pod := &core.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "myns", - Name: "mypod", - UID: "mypod-uid", - }, - } - sec := &core.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: "myns", - Name: "mysecret", - UID: "mysecret-uid", - }, - } - cs := []struct { - // input - sa core.ServiceAccount - pod *core.Pod - sec *core.Secret - exp int64 - aud []string - // desired - sc *jwt.Claims - pc *privateClaims - }{ - { - // pod and secret - sa: sa, - pod: pod, - sec: sec, - // really fast - exp: 0, - // nil audience - aud: nil, - - sc: &jwt.Claims{ - Subject: "system:serviceaccount:myns:mysvcacct", - IssuedAt: jwt.NumericDate(1514764800), - NotBefore: jwt.NumericDate(1514764800), - Expiry: jwt.NumericDate(1514764800), - }, - pc: &privateClaims{ - Kubernetes: kubernetes{ - Namespace: "myns", - Svcacct: ref{Name: "mysvcacct", UID: "mysvcacct-uid"}, - Pod: &ref{Name: "mypod", UID: "mypod-uid"}, - }, - }, - }, - { - // pod - sa: sa, - pod: pod, - // empty audience - aud: []string{}, - exp: 100, - - sc: &jwt.Claims{ - Subject: "system:serviceaccount:myns:mysvcacct", - IssuedAt: jwt.NumericDate(1514764800), - NotBefore: jwt.NumericDate(1514764800), - Expiry: jwt.NumericDate(1514764800 + 100), - }, - pc: &privateClaims{ - Kubernetes: kubernetes{ - Namespace: "myns", - Svcacct: ref{Name: "mysvcacct", UID: "mysvcacct-uid"}, - Pod: &ref{Name: "mypod", UID: "mypod-uid"}, - }, - }, - }, - { - // secret - sa: sa, - sec: sec, - exp: 100, - // single member audience - aud: []string{"1"}, - - sc: &jwt.Claims{ - Subject: "system:serviceaccount:myns:mysvcacct", - Audience: []string{"1"}, - IssuedAt: jwt.NumericDate(1514764800), - NotBefore: jwt.NumericDate(1514764800), - Expiry: jwt.NumericDate(1514764800 + 100), - }, - pc: &privateClaims{ - Kubernetes: kubernetes{ - Namespace: "myns", - Svcacct: ref{Name: "mysvcacct", UID: "mysvcacct-uid"}, - Secret: &ref{Name: "mysecret", UID: "mysecret-uid"}, - }, - }, - }, - { - // no obj binding - sa: sa, - exp: 100, - // multimember audience - aud: []string{"1", "2"}, - - sc: &jwt.Claims{ - Subject: "system:serviceaccount:myns:mysvcacct", - Audience: []string{"1", "2"}, - IssuedAt: jwt.NumericDate(1514764800), - NotBefore: jwt.NumericDate(1514764800), - Expiry: jwt.NumericDate(1514764800 + 100), - }, - pc: &privateClaims{ - Kubernetes: kubernetes{ - Namespace: "myns", - Svcacct: ref{Name: "mysvcacct", UID: "mysvcacct-uid"}, - }, - }, - }, - } - for i, c := range cs { - t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) { - // comparing json spews has the benefit over - // reflect.DeepEqual that we are also asserting that - // claims structs are json serializable - spew := func(obj interface{}) string { - b, err := json.Marshal(obj) - if err != nil { - t.Fatalf("err, couldn't marshal claims: %v", err) - } - return string(b) - } - - sc, pc := Claims(c.sa, c.pod, c.sec, c.exp, c.aud) - if spew(sc) != spew(c.sc) { - t.Errorf("standard claims differed\n\tsaw:\t%s\n\twant:\t%s", spew(sc), spew(c.sc)) - } - if spew(pc) != spew(c.pc) { - t.Errorf("private claims differed\n\tsaw: %s\n\twant: %s", spew(pc), spew(c.pc)) - } - }) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/serviceaccount/jwt_test.go b/vendor/k8s.io/kubernetes/pkg/serviceaccount/jwt_test.go deleted file mode 100644 index a8cffd9f39..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/serviceaccount/jwt_test.go +++ /dev/null @@ -1,325 +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 serviceaccount_test - -import ( - "reflect" - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - apiserverserviceaccount "k8s.io/apiserver/pkg/authentication/serviceaccount" - clientset "k8s.io/client-go/kubernetes" - "k8s.io/client-go/kubernetes/fake" - certutil "k8s.io/client-go/util/cert" - serviceaccountcontroller "k8s.io/kubernetes/pkg/controller/serviceaccount" - "k8s.io/kubernetes/pkg/serviceaccount" -) - -const otherPublicKey = `-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArXz0QkIG1B5Bj2/W69GH -rsm5e+RC3kE+VTgocge0atqlLBek35tRqLgUi3AcIrBZ/0YctMSWDVcRt5fkhWwe -Lqjj6qvAyNyOkrkBi1NFDpJBjYJtuKHgRhNxXbOzTSNpdSKXTfOkzqv56MwHOP25 -yP/NNAODUtr92D5ySI5QX8RbXW+uDn+ixul286PBW/BCrE4tuS88dA0tYJPf8LCu -sqQOwlXYH/rNUg4Pyl9xxhR5DIJR0OzNNfChjw60zieRIt2LfM83fXhwk8IxRGkc -gPZm7ZsipmfbZK2Tkhnpsa4QxDg7zHJPMsB5kxRXW0cQipXcC3baDyN9KBApNXa0 -PwIDAQAB ------END PUBLIC KEY-----` - -const rsaPublicKey = `-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA249XwEo9k4tM8fMxV7zx -OhcrP+WvXn917koM5Qr2ZXs4vo26e4ytdlrV0bQ9SlcLpQVSYjIxNfhTZdDt+ecI -zshKuv1gKIxbbLQMOuK1eA/4HALyEkFgmS/tleLJrhc65tKPMGD+pKQ/xhmzRuCG -51RoiMgbQxaCyYxGfNLpLAZK9L0Tctv9a0mJmGIYnIOQM4kC1A1I1n3EsXMWmeJU -j7OTh/AjjCnMnkgvKT2tpKxYQ59PgDgU8Ssc7RDSmSkLxnrv+OrN80j6xrw0OjEi -B4Ycr0PqfzZcvy8efTtFQ/Jnc4Bp1zUtFXt7+QeevePtQ2EcyELXE0i63T1CujRM -WwIDAQAB ------END PUBLIC KEY----- -` - -const rsaPrivateKey = `-----BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEA249XwEo9k4tM8fMxV7zxOhcrP+WvXn917koM5Qr2ZXs4vo26 -e4ytdlrV0bQ9SlcLpQVSYjIxNfhTZdDt+ecIzshKuv1gKIxbbLQMOuK1eA/4HALy -EkFgmS/tleLJrhc65tKPMGD+pKQ/xhmzRuCG51RoiMgbQxaCyYxGfNLpLAZK9L0T -ctv9a0mJmGIYnIOQM4kC1A1I1n3EsXMWmeJUj7OTh/AjjCnMnkgvKT2tpKxYQ59P -gDgU8Ssc7RDSmSkLxnrv+OrN80j6xrw0OjEiB4Ycr0PqfzZcvy8efTtFQ/Jnc4Bp -1zUtFXt7+QeevePtQ2EcyELXE0i63T1CujRMWwIDAQABAoIBAHJx8GqyCBDNbqk7 -e7/hI9iE1S10Wwol5GH2RWxqX28cYMKq+8aE2LI1vPiXO89xOgelk4DN6urX6xjK -ZBF8RRIMQy/e/O2F4+3wl+Nl4vOXV1u6iVXMsD6JRg137mqJf1Fr9elg1bsaRofL -Q7CxPoB8dhS+Qb+hj0DhlqhgA9zG345CQCAds0ZYAZe8fP7bkwrLqZpMn7Dz9WVm -++YgYYKjuE95kPuup/LtWfA9rJyE/Fws8/jGvRSpVn1XglMLSMKhLd27sE8ZUSV0 -2KUzbfRGE0+AnRULRrjpYaPu0XQ2JjdNvtkjBnv27RB89W9Gklxq821eH1Y8got8 -FZodjxECgYEA93pz7AQZ2xDs67d1XLCzpX84GxKzttirmyj3OIlxgzVHjEMsvw8v -sjFiBU5xEEQDosrBdSknnlJqyiq1YwWG/WDckr13d8G2RQWoySN7JVmTQfXcLoTu -YGRiiTuoEi3ab3ZqrgGrFgX7T/cHuasbYvzCvhM2b4VIR3aSxU2DTUMCgYEA4x7J -T/ErP6GkU5nKstu/mIXwNzayEO1BJvPYsy7i7EsxTm3xe/b8/6cYOz5fvJLGH5mT -Q8YvuLqBcMwZardrYcwokD55UvNLOyfADDFZ6l3WntIqbA640Ok2g1X4U8J09xIq -ZLIWK1yWbbvi4QCeN5hvWq47e8sIj5QHjIIjRwkCgYEAyNqjltxFN9zmzPDa2d24 -EAvOt3pYTYBQ1t9KtqImdL0bUqV6fZ6PsWoPCgt+DBuHb+prVPGP7Bkr/uTmznU/ -+AlTO+12NsYLbr2HHagkXE31DEXE7CSLa8RNjN/UKtz4Ohq7vnowJvG35FCz/mb3 -FUHbtHTXa2+bGBUOTf/5Hw0CgYBxw0r9EwUhw1qnUYJ5op7OzFAtp+T7m4ul8kCa -SCL8TxGsgl+SQ34opE775dtYfoBk9a0RJqVit3D8yg71KFjOTNAIqHJm/Vyyjc+h -i9rJDSXiuczsAVfLtPVMRfS0J9QkqeG4PIfkQmVLI/CZ2ZBmsqEcX+eFs4ZfPLun -Qsxe2QKBgGuPilIbLeIBDIaPiUI0FwU8v2j8CEQBYvoQn34c95hVQsig/o5z7zlo -UsO0wlTngXKlWdOcCs1kqEhTLrstf48djDxAYAxkw40nzeJOt7q52ib/fvf4/UBy -X024wzbiw1q07jFCyfQmODzURAx1VNT7QVUMdz/N8vy47/H40AZJ ------END RSA PRIVATE KEY----- -` - -// openssl ecparam -name prime256v1 -genkey -noout -out ecdsa256.pem -const ecdsaPrivateKey = `-----BEGIN EC PRIVATE KEY----- -MHcCAQEEIEZmTmUhuanLjPA2CLquXivuwBDHTt5XYwgIr/kA1LtRoAoGCCqGSM49 -AwEHoUQDQgAEH6cuzP8XuD5wal6wf9M6xDljTOPLX2i8uIp/C/ASqiIGUeeKQtX0 -/IR3qCXyThP/dbCiHrF3v1cuhBOHY8CLVg== ------END EC PRIVATE KEY-----` - -// openssl ec -in ecdsa256.pem -pubout -out ecdsa256pub.pem -const ecdsaPublicKey = `-----BEGIN PUBLIC KEY----- -MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEH6cuzP8XuD5wal6wf9M6xDljTOPL -X2i8uIp/C/ASqiIGUeeKQtX0/IR3qCXyThP/dbCiHrF3v1cuhBOHY8CLVg== ------END PUBLIC KEY-----` - -func getPrivateKey(data string) interface{} { - key, _ := certutil.ParsePrivateKeyPEM([]byte(data)) - return key -} - -func getPublicKey(data string) interface{} { - keys, _ := certutil.ParsePublicKeysPEM([]byte(data)) - return keys[0] -} -func TestTokenGenerateAndValidate(t *testing.T) { - expectedUserName := "system:serviceaccount:test:my-service-account" - expectedUserUID := "12345" - - // Related API objects - serviceAccount := &v1.ServiceAccount{ - ObjectMeta: metav1.ObjectMeta{ - Name: "my-service-account", - UID: "12345", - Namespace: "test", - }, - } - rsaSecret := &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: "my-rsa-secret", - Namespace: "test", - }, - } - ecdsaSecret := &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: "my-ecdsa-secret", - Namespace: "test", - }, - } - - // Generate the RSA token - rsaGenerator := serviceaccount.JWTTokenGenerator(serviceaccount.LegacyIssuer, getPrivateKey(rsaPrivateKey)) - rsaToken, err := rsaGenerator.GenerateToken(serviceaccount.LegacyClaims(*serviceAccount, *rsaSecret)) - if err != nil { - t.Fatalf("error generating token: %v", err) - } - if len(rsaToken) == 0 { - t.Fatalf("no token generated") - } - rsaSecret.Data = map[string][]byte{ - "token": []byte(rsaToken), - } - - // Generate the ECDSA token - ecdsaGenerator := serviceaccount.JWTTokenGenerator(serviceaccount.LegacyIssuer, getPrivateKey(ecdsaPrivateKey)) - ecdsaToken, err := ecdsaGenerator.GenerateToken(serviceaccount.LegacyClaims(*serviceAccount, *ecdsaSecret)) - if err != nil { - t.Fatalf("error generating token: %v", err) - } - if len(ecdsaToken) == 0 { - t.Fatalf("no token generated") - } - ecdsaSecret.Data = map[string][]byte{ - "token": []byte(ecdsaToken), - } - - // Generate signer with same keys as RSA signer but different issuer - badIssuerGenerator := serviceaccount.JWTTokenGenerator("foo", getPrivateKey(rsaPrivateKey)) - badIssuerToken, err := badIssuerGenerator.GenerateToken(serviceaccount.LegacyClaims(*serviceAccount, *rsaSecret)) - if err != nil { - t.Fatalf("error generating token: %v", err) - } - - testCases := map[string]struct { - Client clientset.Interface - Keys []interface{} - Token string - - ExpectedErr bool - ExpectedOK bool - ExpectedUserName string - ExpectedUserUID string - ExpectedGroups []string - }{ - "no keys": { - Token: rsaToken, - Client: nil, - Keys: []interface{}{}, - ExpectedErr: false, - ExpectedOK: false, - }, - "invalid keys (rsa)": { - Token: rsaToken, - Client: nil, - Keys: []interface{}{getPublicKey(otherPublicKey), getPublicKey(ecdsaPublicKey)}, - ExpectedErr: true, - ExpectedOK: false, - }, - "invalid keys (ecdsa)": { - Token: ecdsaToken, - Client: nil, - Keys: []interface{}{getPublicKey(otherPublicKey), getPublicKey(rsaPublicKey)}, - ExpectedErr: true, - ExpectedOK: false, - }, - "valid key (rsa)": { - Token: rsaToken, - Client: nil, - Keys: []interface{}{getPublicKey(rsaPublicKey)}, - ExpectedErr: false, - ExpectedOK: true, - ExpectedUserName: expectedUserName, - ExpectedUserUID: expectedUserUID, - ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"}, - }, - "valid key, invalid issuer (rsa)": { - Token: badIssuerToken, - Client: nil, - Keys: []interface{}{getPublicKey(rsaPublicKey)}, - ExpectedErr: false, - ExpectedOK: false, - }, - "valid key (ecdsa)": { - Token: ecdsaToken, - Client: nil, - Keys: []interface{}{getPublicKey(ecdsaPublicKey)}, - ExpectedErr: false, - ExpectedOK: true, - ExpectedUserName: expectedUserName, - ExpectedUserUID: expectedUserUID, - ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"}, - }, - "rotated keys (rsa)": { - Token: rsaToken, - Client: nil, - Keys: []interface{}{getPublicKey(otherPublicKey), getPublicKey(ecdsaPublicKey), getPublicKey(rsaPublicKey)}, - ExpectedErr: false, - ExpectedOK: true, - ExpectedUserName: expectedUserName, - ExpectedUserUID: expectedUserUID, - ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"}, - }, - "rotated keys (ecdsa)": { - Token: ecdsaToken, - Client: nil, - Keys: []interface{}{getPublicKey(otherPublicKey), getPublicKey(rsaPublicKey), getPublicKey(ecdsaPublicKey)}, - ExpectedErr: false, - ExpectedOK: true, - ExpectedUserName: expectedUserName, - ExpectedUserUID: expectedUserUID, - ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"}, - }, - "valid lookup": { - Token: rsaToken, - Client: fake.NewSimpleClientset(serviceAccount, rsaSecret, ecdsaSecret), - Keys: []interface{}{getPublicKey(rsaPublicKey)}, - ExpectedErr: false, - ExpectedOK: true, - ExpectedUserName: expectedUserName, - ExpectedUserUID: expectedUserUID, - ExpectedGroups: []string{"system:serviceaccounts", "system:serviceaccounts:test"}, - }, - "invalid secret lookup": { - Token: rsaToken, - Client: fake.NewSimpleClientset(serviceAccount), - Keys: []interface{}{getPublicKey(rsaPublicKey)}, - ExpectedErr: true, - ExpectedOK: false, - }, - "invalid serviceaccount lookup": { - Token: rsaToken, - Client: fake.NewSimpleClientset(rsaSecret, ecdsaSecret), - Keys: []interface{}{getPublicKey(rsaPublicKey)}, - ExpectedErr: true, - ExpectedOK: false, - }, - } - - for k, tc := range testCases { - getter := serviceaccountcontroller.NewGetterFromClient(tc.Client) - authenticator := serviceaccount.JWTTokenAuthenticator(serviceaccount.LegacyIssuer, tc.Keys, serviceaccount.NewLegacyValidator(tc.Client != nil, getter)) - - // An invalid, non-JWT token should always fail - if _, ok, err := authenticator.AuthenticateToken("invalid token"); err != nil || ok { - t.Errorf("%s: Expected err=nil, ok=false for non-JWT token", k) - continue - } - - user, ok, err := authenticator.AuthenticateToken(tc.Token) - if (err != nil) != tc.ExpectedErr { - t.Errorf("%s: Expected error=%v, got %v", k, tc.ExpectedErr, err) - continue - } - - if ok != tc.ExpectedOK { - t.Errorf("%s: Expected ok=%v, got %v", k, tc.ExpectedOK, ok) - continue - } - - if err != nil || !ok { - continue - } - - if user.GetName() != tc.ExpectedUserName { - t.Errorf("%s: Expected username=%v, got %v", k, tc.ExpectedUserName, user.GetName()) - continue - } - if user.GetUID() != tc.ExpectedUserUID { - t.Errorf("%s: Expected userUID=%v, got %v", k, tc.ExpectedUserUID, user.GetUID()) - continue - } - if !reflect.DeepEqual(user.GetGroups(), tc.ExpectedGroups) { - t.Errorf("%s: Expected groups=%v, got %v", k, tc.ExpectedGroups, user.GetGroups()) - continue - } - } -} - -func TestMakeSplitUsername(t *testing.T) { - username := apiserverserviceaccount.MakeUsername("ns", "name") - ns, name, err := apiserverserviceaccount.SplitUsername(username) - if err != nil { - t.Errorf("Unexpected error %v", err) - } - if ns != "ns" || name != "name" { - t.Errorf("Expected ns/name, got %s/%s", ns, name) - } - - invalid := []string{"test", "system:serviceaccount", "system:serviceaccount:", "system:serviceaccount:ns", "system:serviceaccount:ns:name:extra"} - for _, n := range invalid { - _, _, err := apiserverserviceaccount.SplitUsername("test") - if err == nil { - t.Errorf("Expected error for %s", n) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/serviceaccount/util_test.go b/vendor/k8s.io/kubernetes/pkg/serviceaccount/util_test.go deleted file mode 100644 index 88888e2e44..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/serviceaccount/util_test.go +++ /dev/null @@ -1,103 +0,0 @@ -/* -Copyright 2018 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 serviceaccount - -import ( - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestIsServiceAccountToken(t *testing.T) { - - secretIns := &v1.Secret{ - ObjectMeta: metav1.ObjectMeta{ - Name: "token-secret-1", - Namespace: "default", - UID: "23456", - ResourceVersion: "1", - Annotations: map[string]string{ - v1.ServiceAccountNameKey: "default", - v1.ServiceAccountUIDKey: "12345", - }, - }, - Type: v1.SecretTypeServiceAccountToken, - Data: map[string][]byte{ - "token": []byte("ABC"), - "ca.crt": []byte("CA Data"), - "namespace": []byte("default"), - }, - } - - saIns := &v1.ServiceAccount{ - ObjectMeta: metav1.ObjectMeta{ - Name: "default", - UID: "12345", - Namespace: "default", - ResourceVersion: "1", - }, - } - - saInsNameNotEqual := &v1.ServiceAccount{ - ObjectMeta: metav1.ObjectMeta{ - Name: "non-default", - UID: "12345", - Namespace: "default", - ResourceVersion: "1", - }, - } - - saInsUIDNotEqual := &v1.ServiceAccount{ - ObjectMeta: metav1.ObjectMeta{ - Name: "default", - UID: "67890", - Namespace: "default", - ResourceVersion: "1", - }, - } - - tests := map[string]struct { - secret *v1.Secret - sa *v1.ServiceAccount - expect bool - }{ - "correct service account": { - secret: secretIns, - sa: saIns, - expect: true, - }, - "service account name not equal": { - secret: secretIns, - sa: saInsNameNotEqual, - expect: false, - }, - "service account uid not equal": { - secret: secretIns, - sa: saInsUIDNotEqual, - expect: false, - }, - } - - for k, v := range tests { - actual := IsServiceAccountToken(v.secret, v.sa) - if actual != v.expect { - t.Errorf("%s failed, expected %t but received %t", k, v.expect, actual) - } - } - -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/file/file_test.go b/vendor/k8s.io/kubernetes/pkg/util/file/file_test.go deleted file mode 100644 index 43eb2ed1d1..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/file/file_test.go +++ /dev/null @@ -1,149 +0,0 @@ -/* -Copyright 2017 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 file - -import ( - "os" - "path/filepath" - "sort" - "testing" - - "github.com/spf13/afero" - "github.com/stretchr/testify/assert" -) - -func RecoverEnv(wd, tmpDir string) { - os.Chdir(wd) - os.RemoveAll(tmpDir) -} - -func TestFileUtils(t *testing.T) { - fs := &afero.Afero{Fs: afero.NewOsFs()} - // Create tmp dir - tmpDir, err := fs.TempDir(os.TempDir(), "util_file_test_") - if err != nil { - t.Fatal("Failed to test: failed to create temp dir.") - } - - // create tmp file - tmpFile, err := fs.TempFile(tmpDir, "test_file_exists_") - if err != nil { - t.Fatal("Failed to test: failed to create temp file.") - } - - // create tmp sym link - tmpSymlinkName := filepath.Join(tmpDir, "test_file_exists_sym_link") - err = os.Symlink(tmpFile.Name(), tmpSymlinkName) - if err != nil { - t.Fatal("Failed to test: failed to create sym link.") - } - - // create tmp sub dir - tmpSubDir, err := fs.TempDir(tmpDir, "sub_") - if err != nil { - t.Fatal("Failed to test: failed to create temp sub dir.") - } - - // record the current dir - currentDir, err := os.Getwd() - if err != nil { - t.Fatal("Failed to test: failed to get current dir.") - } - - // change the work dir to temp dir - err = os.Chdir(tmpDir) - if err != nil { - t.Fatal("Failed to test: failed to change work dir.") - } - - // recover test environment - defer RecoverEnv(currentDir, tmpDir) - - t.Run("TestFileExists", func(t *testing.T) { - tests := []struct { - name string - fileName string - expectedError bool - expectedValue bool - }{ - {"file_not_exists", filepath.Join(tmpDir, "file_not_exist_case"), false, false}, - {"file_exists", tmpFile.Name(), false, true}, - } - - for _, test := range tests { - realValued, realError := FileExists(test.fileName) - if test.expectedError { - assert.Errorf(t, realError, "Failed to test with '%s': %s", test.fileName, test.name) - } else { - assert.EqualValuesf(t, test.expectedValue, realValued, "Failed to test with '%s': %s", test.fileName, test.name) - } - } - }) - - t.Run("TestFileOrSymlinkExists", func(t *testing.T) { - tests := []struct { - name string - fileName string - expectedError bool - expectedValue bool - }{ - {"file_not_exists", filepath.Join(tmpDir, "file_not_exist_case"), false, false}, - {"file_exists", tmpFile.Name(), false, true}, - {"symlink_exists", tmpSymlinkName, false, true}, - } - - for _, test := range tests { - realValued, realError := FileOrSymlinkExists(test.fileName) - if test.expectedError { - assert.Errorf(t, realError, "Failed to test with '%s': %s", test.fileName, test.name) - } else { - assert.EqualValuesf(t, test.expectedValue, realValued, "Failed to test with '%s': %s", test.fileName, test.name) - } - } - }) - - t.Run("TestReadDirNoStat", func(t *testing.T) { - _, tmpFileSimpleName := filepath.Split(tmpFile.Name()) - _, tmpSymlinkSimpleName := filepath.Split(tmpSymlinkName) - _, tmpSubDirSimpleName := filepath.Split(tmpSubDir) - - tests := []struct { - name string - dirName string - expectedError bool - expectedValue []string - }{ - {"dir_not_exists", filepath.Join(tmpDir, "file_not_exist_case"), true, []string{}}, - {"dir_is_empty", "", false, []string{tmpFileSimpleName, tmpSymlinkSimpleName, tmpSubDirSimpleName}}, - {"dir_exists", tmpDir, false, []string{tmpFileSimpleName, tmpSymlinkSimpleName, tmpSubDirSimpleName}}, - } - - for _, test := range tests { - realValued, realError := ReadDirNoStat(test.dirName) - - // execute sort action before compare - sort.Strings(realValued) - sort.Strings(test.expectedValue) - - if test.expectedError { - assert.Errorf(t, realError, "Failed to test with '%s': %s", test.dirName, test.name) - } else { - assert.EqualValuesf(t, test.expectedValue, realValued, "Failed to test with '%s': %s", test.dirName, test.name) - } - } - }) -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/hash/hash_test.go b/vendor/k8s.io/kubernetes/pkg/util/hash/hash_test.go deleted file mode 100644 index abce506a50..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/hash/hash_test.go +++ /dev/null @@ -1,147 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package hash - -import ( - "fmt" - "hash/adler32" - "testing" - - "github.com/davecgh/go-spew/spew" -) - -type A struct { - x int - y string -} - -type B struct { - x []int - y map[string]bool -} - -type C struct { - x int - y string -} - -func (c C) String() string { - return fmt.Sprintf("%d:%s", c.x, c.y) -} - -func TestDeepHashObject(t *testing.T) { - successCases := []func() interface{}{ - func() interface{} { return 8675309 }, - func() interface{} { return "Jenny, I got your number" }, - func() interface{} { return []string{"eight", "six", "seven"} }, - func() interface{} { return [...]int{5, 3, 0, 9} }, - func() interface{} { return map[int]string{8: "8", 6: "6", 7: "7"} }, - func() interface{} { return map[string]int{"5": 5, "3": 3, "0": 0, "9": 9} }, - func() interface{} { return A{867, "5309"} }, - func() interface{} { return &A{867, "5309"} }, - func() interface{} { - return B{[]int{8, 6, 7}, map[string]bool{"5": true, "3": true, "0": true, "9": true}} - }, - func() interface{} { return map[A]bool{{8675309, "Jenny"}: true, {9765683, "!Jenny"}: false} }, - func() interface{} { return map[C]bool{{8675309, "Jenny"}: true, {9765683, "!Jenny"}: false} }, - func() interface{} { return map[*A]bool{{8675309, "Jenny"}: true, {9765683, "!Jenny"}: false} }, - func() interface{} { return map[*C]bool{{8675309, "Jenny"}: true, {9765683, "!Jenny"}: false} }, - } - - for _, tc := range successCases { - hasher1 := adler32.New() - DeepHashObject(hasher1, tc()) - hash1 := hasher1.Sum32() - DeepHashObject(hasher1, tc()) - hash2 := hasher1.Sum32() - if hash1 != hash2 { - t.Fatalf("hash of the same object (%q) produced different results: %d vs %d", toString(tc()), hash1, hash2) - } - for i := 0; i < 100; i++ { - hasher2 := adler32.New() - - DeepHashObject(hasher1, tc()) - hash1a := hasher1.Sum32() - DeepHashObject(hasher2, tc()) - hash2a := hasher2.Sum32() - - if hash1a != hash1 { - t.Errorf("repeated hash of the same object (%q) produced different results: %d vs %d", toString(tc()), hash1, hash1a) - } - if hash2a != hash2 { - t.Errorf("repeated hash of the same object (%q) produced different results: %d vs %d", toString(tc()), hash2, hash2a) - } - if hash1a != hash2a { - t.Errorf("hash of the same object produced (%q) different results: %d vs %d", toString(tc()), hash1a, hash2a) - } - } - } -} - -func toString(obj interface{}) string { - return spew.Sprintf("%#v", obj) -} - -type wheel struct { - radius uint32 -} - -type unicycle struct { - primaryWheel *wheel - licencePlateID string - tags map[string]string -} - -func TestDeepObjectPointer(t *testing.T) { - // Arrange - wheel1 := wheel{radius: 17} - wheel2 := wheel{radius: 22} - wheel3 := wheel{radius: 17} - - myUni1 := unicycle{licencePlateID: "blah", primaryWheel: &wheel1, tags: map[string]string{"color": "blue", "name": "john"}} - myUni2 := unicycle{licencePlateID: "blah", primaryWheel: &wheel2, tags: map[string]string{"color": "blue", "name": "john"}} - myUni3 := unicycle{licencePlateID: "blah", primaryWheel: &wheel3, tags: map[string]string{"color": "blue", "name": "john"}} - - // Run it more than once to verify determinism of hasher. - for i := 0; i < 100; i++ { - hasher1 := adler32.New() - hasher2 := adler32.New() - hasher3 := adler32.New() - // Act - DeepHashObject(hasher1, myUni1) - hash1 := hasher1.Sum32() - DeepHashObject(hasher1, myUni1) - hash1a := hasher1.Sum32() - DeepHashObject(hasher2, myUni2) - hash2 := hasher2.Sum32() - DeepHashObject(hasher3, myUni3) - hash3 := hasher3.Sum32() - - // Assert - if hash1 != hash1a { - t.Errorf("repeated hash of the same object produced different results: %d vs %d", hash1, hash1a) - } - - if hash1 == hash2 { - t.Errorf("hash1 (%d) and hash2(%d) must be different because they have different values for wheel size", hash1, hash2) - } - - if hash1 != hash3 { - t.Errorf("hash1 (%d) and hash3(%d) must be the same because although they point to different objects, they have the same values for wheel size", hash1, hash3) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/BUILD b/vendor/k8s.io/kubernetes/pkg/util/mount/BUILD index 3b2a78a565..9040cd93b2 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/BUILD +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/BUILD @@ -102,6 +102,7 @@ go_test( ] + select({ "@io_bazel_rules_go//go/platform:linux": [ "//vendor/github.com/golang/glog:go_default_library", + "//vendor/k8s.io/utils/exec:go_default_library", ], "@io_bazel_rules_go//go/platform:windows": [ "//vendor/github.com/stretchr/testify/assert:go_default_library", diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/exec_mount_test.go b/vendor/k8s.io/kubernetes/pkg/util/mount/exec_mount_test.go deleted file mode 100644 index 248f49631b..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/exec_mount_test.go +++ /dev/null @@ -1,165 +0,0 @@ -// +build linux - -/* -Copyright 2017 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 mount - -import ( - "fmt" - "os" - "reflect" - "strings" - "testing" -) - -var ( - sourcePath = "/mnt/srv" - destinationPath = "/mnt/dst" - fsType = "xfs" - mountOptions = []string{"vers=1", "foo=bar"} -) - -func TestMount(t *testing.T) { - exec := NewFakeExec(func(cmd string, args ...string) ([]byte, error) { - if cmd != "mount" { - t.Errorf("expected mount command, got %q", cmd) - } - // mount -t fstype -o options source target - expectedArgs := []string{"-t", fsType, "-o", strings.Join(mountOptions, ","), sourcePath, destinationPath} - if !reflect.DeepEqual(expectedArgs, args) { - t.Errorf("expected arguments %q, got %q", strings.Join(expectedArgs, " "), strings.Join(args, " ")) - } - return nil, nil - }) - - wrappedMounter := &fakeMounter{t} - mounter := NewExecMounter(exec, wrappedMounter) - - mounter.Mount(sourcePath, destinationPath, fsType, mountOptions) -} - -func TestBindMount(t *testing.T) { - cmdCount := 0 - exec := NewFakeExec(func(cmd string, args ...string) ([]byte, error) { - cmdCount++ - if cmd != "mount" { - t.Errorf("expected mount command, got %q", cmd) - } - var expectedArgs []string - switch cmdCount { - case 1: - // mount -t fstype -o "bind" source target - expectedArgs = []string{"-t", fsType, "-o", "bind", sourcePath, destinationPath} - case 2: - // mount -t fstype -o "remount,opts" source target - expectedArgs = []string{"-t", fsType, "-o", "remount," + strings.Join(mountOptions, ","), sourcePath, destinationPath} - } - if !reflect.DeepEqual(expectedArgs, args) { - t.Errorf("expected arguments %q, got %q", strings.Join(expectedArgs, " "), strings.Join(args, " ")) - } - return nil, nil - }) - - wrappedMounter := &fakeMounter{t} - mounter := NewExecMounter(exec, wrappedMounter) - bindOptions := append(mountOptions, "bind") - mounter.Mount(sourcePath, destinationPath, fsType, bindOptions) -} - -func TestUnmount(t *testing.T) { - exec := NewFakeExec(func(cmd string, args ...string) ([]byte, error) { - if cmd != "umount" { - t.Errorf("expected unmount command, got %q", cmd) - } - // unmount $target - expectedArgs := []string{destinationPath} - if !reflect.DeepEqual(expectedArgs, args) { - t.Errorf("expected arguments %q, got %q", strings.Join(expectedArgs, " "), strings.Join(args, " ")) - } - return nil, nil - }) - - wrappedMounter := &fakeMounter{t} - mounter := NewExecMounter(exec, wrappedMounter) - - mounter.Unmount(destinationPath) -} - -/* Fake wrapped mounter */ -type fakeMounter struct { - t *testing.T -} - -func (fm *fakeMounter) Mount(source string, target string, fstype string, options []string) error { - // Mount() of wrapped mounter should never be called. We call exec instead. - fm.t.Errorf("Unexpected wrapped mount call") - return fmt.Errorf("Unexpected wrapped mount call") -} - -func (fm *fakeMounter) Unmount(target string) error { - // umount() of wrapped mounter should never be called. We call exec instead. - fm.t.Errorf("Unexpected wrapped mount call") - return fmt.Errorf("Unexpected wrapped mount call") -} - -func (fm *fakeMounter) List() ([]MountPoint, error) { - return nil, nil -} -func (fm *fakeMounter) IsMountPointMatch(mp MountPoint, dir string) bool { - return false -} -func (fm *fakeMounter) IsNotMountPoint(file string) (bool, error) { - return false, nil -} -func (fm *fakeMounter) IsLikelyNotMountPoint(file string) (bool, error) { - return false, nil -} -func (fm *fakeMounter) DeviceOpened(pathname string) (bool, error) { - return false, nil -} -func (fm *fakeMounter) PathIsDevice(pathname string) (bool, error) { - return false, nil -} -func (fm *fakeMounter) GetDeviceNameFromMount(mountPath, pluginDir string) (string, error) { - return "", nil -} -func (fm *fakeMounter) MakeRShared(path string) error { - return nil -} -func (fm *fakeMounter) MakeFile(pathname string) error { - return nil -} -func (fm *fakeMounter) MakeDir(pathname string) error { - return nil -} -func (fm *fakeMounter) ExistsPath(pathname string) bool { - return false -} -func (fm *fakeMounter) GetFileType(pathname string) (FileType, error) { - return FileTypeFile, nil -} -func (fm *fakeMounter) PrepareSafeSubpath(subPath Subpath) (newHostPath string, cleanupAction func(), err error) { - return subPath.Path, nil, nil -} - -func (fm *fakeMounter) CleanSubPaths(podDir string, volumeName string) error { - return nil -} - -func (fm *fakeMounter) SafeMakeDir(pathname string, base string, perm os.FileMode) error { - return nil -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/fake.go b/vendor/k8s.io/kubernetes/pkg/util/mount/fake.go index 4bc32ff21c..c4cf35080f 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/fake.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/fake.go @@ -58,8 +58,10 @@ func (f *FakeMounter) Mount(source string, target string, fstype string, options f.mutex.Lock() defer f.mutex.Unlock() - // find 'bind' option + opts := []string{} + for _, option := range options { + // find 'bind' option if option == "bind" { // This is a bind-mount. In order to mimic linux behaviour, we must // use the original device of the bind-mount as the real source. @@ -78,7 +80,11 @@ func (f *FakeMounter) Mount(source string, target string, fstype string, options break } } - break + } + // find 'ro' option + if option == "ro" { + // reuse MountPoint.Opts field to mark mount as readonly + opts = append(opts, "ro") } } @@ -88,7 +94,7 @@ func (f *FakeMounter) Mount(source string, target string, fstype string, options absTarget = target } - f.MountPoints = append(f.MountPoints, MountPoint{Device: source, Path: absTarget, Type: fstype}) + f.MountPoints = append(f.MountPoints, MountPoint{Device: source, Path: absTarget, Type: fstype, Opts: opts}) glog.V(5).Infof("Fake mounter: mounted %s to %s", source, absTarget) f.Log = append(f.Log, FakeAction{Action: FakeActionMount, Target: absTarget, Source: source, FSType: fstype}) return nil diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/mount.go b/vendor/k8s.io/kubernetes/pkg/util/mount/mount.go index f30db7692e..64f0070fac 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/mount.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/mount.go @@ -19,6 +19,7 @@ limitations under the License. package mount import ( + "fmt" "os" "path/filepath" "strings" @@ -123,6 +124,8 @@ type Subpath struct { PodDir string // Name of the container ContainerName string + // True if the mount needs to be readonly + ReadOnly bool } // Exec executes command where mount utilities are. This can be either the host, @@ -281,7 +284,13 @@ func IsNotMountPoint(mounter Interface, file string) (bool, error) { // The list equals: // options - 'bind' + 'remount' (no duplicate) func isBind(options []string) (bool, []string) { - bindRemountOpts := []string{"remount"} + // Because we have an FD opened on the subpath bind mount, the "bind" option + // needs to be included, otherwise the mount target will error as busy if you + // remount as readonly. + // + // As a consequence, all read only bind mounts will no longer change the underlying + // volume mount to be read only. + bindRemountOpts := []string{"bind", "remount"} bind := false if len(options) != 0 { @@ -337,3 +346,37 @@ func startsWithBackstep(rel string) bool { // normalize to / and check for ../ return rel == ".." || strings.HasPrefix(filepath.ToSlash(rel), "../") } + +// getFileType checks for file/directory/socket and block/character devices +func getFileType(pathname string) (FileType, error) { + var pathType FileType + info, err := os.Stat(pathname) + if os.IsNotExist(err) { + return pathType, fmt.Errorf("path %q does not exist", pathname) + } + // err in call to os.Stat + if err != nil { + return pathType, err + } + + // checks whether the mode is the target mode + isSpecificMode := func(mode, targetMode os.FileMode) bool { + return mode&targetMode == targetMode + } + + mode := info.Mode() + if mode.IsDir() { + return FileTypeDirectory, nil + } else if mode.IsRegular() { + return FileTypeFile, nil + } else if isSpecificMode(mode, os.ModeSocket) { + return FileTypeSocket, nil + } else if isSpecificMode(mode, os.ModeDevice) { + if isSpecificMode(mode, os.ModeCharDevice) { + return FileTypeCharDev, nil + } + return FileTypeBlockDev, nil + } + + return pathType, fmt.Errorf("only recognise file, directory, socket, block device and character device") +} diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux.go b/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux.go index 012b32673f..3656801569 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux.go @@ -423,31 +423,7 @@ func (mounter *Mounter) MakeRShared(path string) error { } func (mounter *Mounter) GetFileType(pathname string) (FileType, error) { - var pathType FileType - finfo, err := os.Stat(pathname) - if os.IsNotExist(err) { - return pathType, fmt.Errorf("path %q does not exist", pathname) - } - // err in call to os.Stat - if err != nil { - return pathType, err - } - - mode := finfo.Sys().(*syscall.Stat_t).Mode - switch mode & syscall.S_IFMT { - case syscall.S_IFSOCK: - return FileTypeSocket, nil - case syscall.S_IFBLK: - return FileTypeBlockDev, nil - case syscall.S_IFCHR: - return FileTypeCharDev, nil - case syscall.S_IFDIR: - return FileTypeDirectory, nil - case syscall.S_IFREG: - return FileTypeFile, nil - } - - return pathType, fmt.Errorf("only recognise file, directory, socket, block device and character device") + return getFileType(pathname) } func (mounter *Mounter) MakeDir(pathname string) error { @@ -801,8 +777,13 @@ func doBindSubPath(mounter Interface, subpath Subpath, kubeletPid int) (hostPath mountSource := fmt.Sprintf("/proc/%d/fd/%v", kubeletPid, fd) // Do the bind mount + options := []string{"bind"} + if subpath.ReadOnly { + options = append(options, "ro") + } + glog.V(5).Infof("bind mounting %q at %q", mountSource, bindPathTarget) - if err = mounter.Mount(mountSource, bindPathTarget, "" /*fstype*/, []string{"bind"}); err != nil { + if err = mounter.Mount(mountSource, bindPathTarget, "" /*fstype*/, options); err != nil { return "", fmt.Errorf("error mounting %s: %s", subpath.Path, err) } diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux_test.go b/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux_test.go deleted file mode 100644 index 5eb512bd70..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_linux_test.go +++ /dev/null @@ -1,1661 +0,0 @@ -// +build linux - -/* -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 mount - -import ( - "fmt" - "io/ioutil" - "net" - "os" - "path/filepath" - "reflect" - "syscall" - "testing" - - "strconv" - - "github.com/golang/glog" -) - -func TestReadProcMountsFrom(t *testing.T) { - successCase := - `/dev/0 /path/to/0 type0 flags 0 0 -/dev/1 /path/to/1 type1 flags 1 1 -/dev/2 /path/to/2 type2 flags,1,2=3 2 2 -` - // NOTE: readProcMountsFrom has been updated to using fnv.New32a() - mounts, err := parseProcMounts([]byte(successCase)) - if err != nil { - t.Errorf("expected success, got %v", err) - } - if len(mounts) != 3 { - t.Fatalf("expected 3 mounts, got %d", len(mounts)) - } - mp := MountPoint{"/dev/0", "/path/to/0", "type0", []string{"flags"}, 0, 0} - if !mountPointsEqual(&mounts[0], &mp) { - t.Errorf("got unexpected MountPoint[0]: %#v", mounts[0]) - } - mp = MountPoint{"/dev/1", "/path/to/1", "type1", []string{"flags"}, 1, 1} - if !mountPointsEqual(&mounts[1], &mp) { - t.Errorf("got unexpected MountPoint[1]: %#v", mounts[1]) - } - mp = MountPoint{"/dev/2", "/path/to/2", "type2", []string{"flags", "1", "2=3"}, 2, 2} - if !mountPointsEqual(&mounts[2], &mp) { - t.Errorf("got unexpected MountPoint[2]: %#v", mounts[2]) - } - - errorCases := []string{ - "/dev/0 /path/to/mount\n", - "/dev/1 /path/to/mount type flags a 0\n", - "/dev/2 /path/to/mount type flags 0 b\n", - } - for _, ec := range errorCases { - _, err := parseProcMounts([]byte(ec)) - if err == nil { - t.Errorf("expected error") - } - } -} - -func mountPointsEqual(a, b *MountPoint) bool { - if a.Device != b.Device || a.Path != b.Path || a.Type != b.Type || !reflect.DeepEqual(a.Opts, b.Opts) || a.Pass != b.Pass || a.Freq != b.Freq { - return false - } - return true -} - -func TestGetMountRefs(t *testing.T) { - fm := &FakeMounter{ - MountPoints: []MountPoint{ - {Device: "/dev/sdb", Path: "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd"}, - {Device: "/dev/sdb", Path: "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd-in-pod"}, - {Device: "/dev/sdc", Path: "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd2"}, - {Device: "/dev/sdc", Path: "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod1"}, - {Device: "/dev/sdc", Path: "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod2"}, - }, - } - - tests := []struct { - mountPath string - expectedRefs []string - }{ - { - "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd-in-pod", - []string{ - "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd", - }, - }, - { - "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod1", - []string{ - "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod2", - "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd2", - }, - }, - } - - for i, test := range tests { - if refs, err := GetMountRefs(fm, test.mountPath); err != nil || !setEquivalent(test.expectedRefs, refs) { - t.Errorf("%d. getMountRefs(%q) = %v, %v; expected %v, nil", i, test.mountPath, refs, err, test.expectedRefs) - } - } -} - -func setEquivalent(set1, set2 []string) bool { - map1 := make(map[string]bool) - map2 := make(map[string]bool) - for _, s := range set1 { - map1[s] = true - } - for _, s := range set2 { - map2[s] = true - } - - for s := range map1 { - if !map2[s] { - return false - } - } - for s := range map2 { - if !map1[s] { - return false - } - } - return true -} - -func TestGetDeviceNameFromMount(t *testing.T) { - fm := &FakeMounter{ - MountPoints: []MountPoint{ - {Device: "/dev/disk/by-path/prefix-lun-1", - Path: "/mnt/111"}, - {Device: "/dev/disk/by-path/prefix-lun-1", - Path: "/mnt/222"}, - }, - } - - tests := []struct { - mountPath string - expectedDevice string - expectedRefs int - }{ - { - "/mnt/222", - "/dev/disk/by-path/prefix-lun-1", - 2, - }, - } - - for i, test := range tests { - if device, refs, err := GetDeviceNameFromMount(fm, test.mountPath); err != nil || test.expectedRefs != refs || test.expectedDevice != device { - t.Errorf("%d. GetDeviceNameFromMount(%s) = (%s, %d), %v; expected (%s,%d), nil", i, test.mountPath, device, refs, err, test.expectedDevice, test.expectedRefs) - } - } -} - -func TestGetMountRefsByDev(t *testing.T) { - fm := &FakeMounter{ - MountPoints: []MountPoint{ - {Device: "/dev/sdb", Path: "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd"}, - {Device: "/dev/sdb", Path: "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd-in-pod"}, - {Device: "/dev/sdc", Path: "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd2"}, - {Device: "/dev/sdc", Path: "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod1"}, - {Device: "/dev/sdc", Path: "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod2"}, - }, - } - - tests := []struct { - mountPath string - expectedRefs []string - }{ - { - "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd", - []string{ - "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd-in-pod", - }, - }, - { - "/var/lib/kubelet/plugins/kubernetes.io/gce-pd/mounts/gce-pd2", - []string{ - "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod1", - "/var/lib/kubelet/pods/some-pod/volumes/kubernetes.io~gce-pd/gce-pd2-in-pod2", - }, - }, - } - - for i, test := range tests { - - if refs, err := GetMountRefsByDev(fm, test.mountPath); err != nil || !setEquivalent(test.expectedRefs, refs) { - t.Errorf("%d. getMountRefsByDev(%q) = %v, %v; expected %v, nil", i, test.mountPath, refs, err, test.expectedRefs) - } - } -} - -func writeFile(content string) (string, string, error) { - tempDir, err := ioutil.TempDir("", "mounter_shared_test") - if err != nil { - return "", "", err - } - filename := filepath.Join(tempDir, "mountinfo") - err = ioutil.WriteFile(filename, []byte(content), 0600) - if err != nil { - os.RemoveAll(tempDir) - return "", "", err - } - return tempDir, filename, nil -} - -func TestIsSharedSuccess(t *testing.T) { - successMountInfo := - `62 0 253:0 / / rw,relatime shared:1 - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered -76 62 8:1 / /boot rw,relatime shared:29 - ext4 /dev/sda1 rw,seclabel,data=ordered -78 62 0:41 / /tmp rw,nosuid,nodev shared:30 - tmpfs tmpfs rw,seclabel -80 62 0:42 / /var/lib/nfs/rpc_pipefs rw,relatime shared:31 - rpc_pipefs sunrpc rw -82 62 0:43 / /var/lib/foo rw,relatime shared:32 - tmpfs tmpfs rw -83 63 0:44 / /var/lib/bar rw,relatime - tmpfs tmpfs rw -227 62 253:0 /var/lib/docker/devicemapper /var/lib/docker/devicemapper rw,relatime - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered -224 62 253:0 /var/lib/docker/devicemapper/test/shared /var/lib/docker/devicemapper/test/shared rw,relatime master:1 shared:44 - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered -` - tempDir, filename, err := writeFile(successMountInfo) - if err != nil { - t.Fatalf("cannot create temporary file: %v", err) - } - defer os.RemoveAll(tempDir) - - tests := []struct { - name string - path string - expectedResult bool - }{ - { - // /var/lib/kubelet is a directory on mount '/' that is shared - // This is the most common case. - "shared", - "/var/lib/kubelet", - true, - }, - { - // 8a2a... is a directory on mount /var/lib/docker/devicemapper - // that is private. - "private", - "/var/lib/docker/devicemapper/mnt/8a2a5c19eefb06d6f851dfcb240f8c113427f5b49b19658b5c60168e88267693/", - false, - }, - { - // 'directory' is a directory on mount - // /var/lib/docker/devicemapper/test/shared that is shared, but one - // of its parent is private. - "nested-shared", - "/var/lib/docker/devicemapper/test/shared/my/test/directory", - true, - }, - { - // /var/lib/foo is a mount point and it's shared - "shared-mount", - "/var/lib/foo", - true, - }, - { - // /var/lib/bar is a mount point and it's private - "private-mount", - "/var/lib/bar", - false, - }, - } - for _, test := range tests { - ret, err := isShared(test.path, filename) - if err != nil { - t.Errorf("test %s got unexpected error: %v", test.name, err) - } - if ret != test.expectedResult { - t.Errorf("test %s expected %v, got %v", test.name, test.expectedResult, ret) - } - } -} - -func TestIsSharedFailure(t *testing.T) { - errorTests := []struct { - name string - content string - }{ - { - // the first line is too short - name: "too-short-line", - content: `62 0 253:0 / / rw,relatime -76 62 8:1 / /boot rw,relatime shared:29 - ext4 /dev/sda1 rw,seclabel,data=ordered -78 62 0:41 / /tmp rw,nosuid,nodev shared:30 - tmpfs tmpfs rw,seclabel -80 62 0:42 / /var/lib/nfs/rpc_pipefs rw,relatime shared:31 - rpc_pipefs sunrpc rw -227 62 253:0 /var/lib/docker/devicemapper /var/lib/docker/devicemapper rw,relatime - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered -224 62 253:0 /var/lib/docker/devicemapper/test/shared /var/lib/docker/devicemapper/test/shared rw,relatime master:1 shared:44 - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered -`, - }, - { - // there is no root mount - name: "no-root-mount", - content: `76 62 8:1 / /boot rw,relatime shared:29 - ext4 /dev/sda1 rw,seclabel,data=ordered -78 62 0:41 / /tmp rw,nosuid,nodev shared:30 - tmpfs tmpfs rw,seclabel -80 62 0:42 / /var/lib/nfs/rpc_pipefs rw,relatime shared:31 - rpc_pipefs sunrpc rw -227 62 253:0 /var/lib/docker/devicemapper /var/lib/docker/devicemapper rw,relatime - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered -224 62 253:0 /var/lib/docker/devicemapper/test/shared /var/lib/docker/devicemapper/test/shared rw,relatime master:1 shared:44 - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered -`, - }, - } - for _, test := range errorTests { - tempDir, filename, err := writeFile(test.content) - if err != nil { - t.Fatalf("cannot create temporary file: %v", err) - } - defer os.RemoveAll(tempDir) - - _, err = isShared("/", filename) - if err == nil { - t.Errorf("test %q: expected error, got none", test.name) - } - } -} - -func TestPathWithinBase(t *testing.T) { - tests := []struct { - name string - fullPath string - basePath string - expected bool - }{ - { - name: "good subpath", - fullPath: "/a/b/c", - basePath: "/a", - expected: true, - }, - { - name: "good subpath 2", - fullPath: "/a/b/c", - basePath: "/a/b", - expected: true, - }, - { - name: "good subpath end slash", - fullPath: "/a/b/c/", - basePath: "/a/b", - expected: true, - }, - { - name: "good subpath backticks", - fullPath: "/a/b/../c", - basePath: "/a", - expected: true, - }, - { - name: "good subpath equal", - fullPath: "/a/b/c", - basePath: "/a/b/c", - expected: true, - }, - { - name: "good subpath equal 2", - fullPath: "/a/b/c/", - basePath: "/a/b/c", - expected: true, - }, - { - name: "good subpath root", - fullPath: "/a", - basePath: "/", - expected: true, - }, - { - name: "bad subpath parent", - fullPath: "/a/b/c", - basePath: "/a/b/c/d", - expected: false, - }, - { - name: "bad subpath outside", - fullPath: "/b/c", - basePath: "/a/b/c", - expected: false, - }, - { - name: "bad subpath prefix", - fullPath: "/a/b/cd", - basePath: "/a/b/c", - expected: false, - }, - { - name: "bad subpath backticks", - fullPath: "/a/../b", - basePath: "/a", - expected: false, - }, - { - name: "configmap subpath", - fullPath: "/var/lib/kubelet/pods/uuid/volumes/kubernetes.io~configmap/config/..timestamp/file.txt", - basePath: "/var/lib/kubelet/pods/uuid/volumes/kubernetes.io~configmap/config", - expected: true, - }, - } - for _, test := range tests { - if pathWithinBase(test.fullPath, test.basePath) != test.expected { - t.Errorf("test %q failed: expected %v", test.name, test.expected) - } - - } -} - -func TestSafeMakeDir(t *testing.T) { - defaultPerm := os.FileMode(0750) + os.ModeDir - tests := []struct { - name string - // Function that prepares directory structure for the test under given - // base. - prepare func(base string) error - path string - checkPath string - perm os.FileMode - expectError bool - }{ - { - "directory-does-not-exist", - func(base string) error { - return nil - }, - "test/directory", - "test/directory", - defaultPerm, - false, - }, - { - "directory-with-sgid", - func(base string) error { - return nil - }, - "test/directory", - "test/directory", - os.FileMode(0777) + os.ModeDir + os.ModeSetgid, - false, - }, - { - "directory-with-suid", - func(base string) error { - return nil - }, - "test/directory", - "test/directory", - os.FileMode(0777) + os.ModeDir + os.ModeSetuid, - false, - }, - { - "directory-with-sticky-bit", - func(base string) error { - return nil - }, - "test/directory", - "test/directory", - os.FileMode(0777) + os.ModeDir + os.ModeSticky, - false, - }, - { - "directory-exists", - func(base string) error { - return os.MkdirAll(filepath.Join(base, "test/directory"), 0750) - }, - "test/directory", - "test/directory", - defaultPerm, - false, - }, - { - "create-base", - func(base string) error { - return nil - }, - "", - "", - defaultPerm, - false, - }, - { - "escape-base-using-dots", - func(base string) error { - return nil - }, - "..", - "", - defaultPerm, - true, - }, - { - "escape-base-using-dots-2", - func(base string) error { - return nil - }, - "test/../../..", - "", - defaultPerm, - true, - }, - { - "follow-symlinks", - func(base string) error { - if err := os.MkdirAll(filepath.Join(base, "destination"), defaultPerm); err != nil { - return err - } - return os.Symlink("destination", filepath.Join(base, "test")) - }, - "test/directory", - "destination/directory", - defaultPerm, - false, - }, - { - "follow-symlink-loop", - func(base string) error { - return os.Symlink("test", filepath.Join(base, "test")) - }, - "test/directory", - "", - defaultPerm, - true, - }, - { - "follow-symlink-multiple follow", - func(base string) error { - /* test1/dir points to test2 and test2/dir points to test1 */ - if err := os.MkdirAll(filepath.Join(base, "test1"), defaultPerm); err != nil { - return err - } - if err := os.MkdirAll(filepath.Join(base, "test2"), defaultPerm); err != nil { - return err - } - if err := os.Symlink(filepath.Join(base, "test2"), filepath.Join(base, "test1/dir")); err != nil { - return err - } - if err := os.Symlink(filepath.Join(base, "test1"), filepath.Join(base, "test2/dir")); err != nil { - return err - } - return nil - }, - "test1/dir/dir/dir/dir/dir/dir/dir/foo", - "test2/foo", - defaultPerm, - false, - }, - { - "danglink-symlink", - func(base string) error { - return os.Symlink("non-existing", filepath.Join(base, "test")) - }, - "test/directory", - "", - defaultPerm, - true, - }, - { - "non-directory", - func(base string) error { - return ioutil.WriteFile(filepath.Join(base, "test"), []byte{}, defaultPerm) - }, - "test/directory", - "", - defaultPerm, - true, - }, - { - "non-directory-final", - func(base string) error { - return ioutil.WriteFile(filepath.Join(base, "test"), []byte{}, defaultPerm) - }, - "test", - "", - defaultPerm, - true, - }, - { - "escape-with-relative-symlink", - func(base string) error { - if err := os.MkdirAll(filepath.Join(base, "dir"), defaultPerm); err != nil { - return err - } - if err := os.MkdirAll(filepath.Join(base, "exists"), defaultPerm); err != nil { - return err - } - return os.Symlink("../exists", filepath.Join(base, "dir/test")) - }, - "dir/test", - "", - defaultPerm, - false, - }, - { - "escape-with-relative-symlink-not-exists", - func(base string) error { - if err := os.MkdirAll(filepath.Join(base, "dir"), defaultPerm); err != nil { - return err - } - return os.Symlink("../not-exists", filepath.Join(base, "dir/test")) - }, - "dir/test", - "", - defaultPerm, - true, - }, - { - "escape-with-symlink", - func(base string) error { - return os.Symlink("/", filepath.Join(base, "test")) - }, - "test/directory", - "", - defaultPerm, - true, - }, - } - - for _, test := range tests { - glog.V(4).Infof("test %q", test.name) - base, err := ioutil.TempDir("", "safe-make-dir-"+test.name+"-") - if err != nil { - t.Fatalf(err.Error()) - } - test.prepare(base) - pathToCreate := filepath.Join(base, test.path) - err = doSafeMakeDir(pathToCreate, base, test.perm) - if err != nil && !test.expectError { - t.Errorf("test %q: %s", test.name, err) - } - if err != nil { - glog.Infof("got error: %s", err) - } - if err == nil && test.expectError { - t.Errorf("test %q: expected error, got none", test.name) - } - - if test.checkPath != "" { - st, err := os.Stat(filepath.Join(base, test.checkPath)) - if err != nil { - t.Errorf("test %q: cannot read path %s", test.name, test.checkPath) - } - if st.Mode() != test.perm { - t.Errorf("test %q: expected permissions %o, got %o", test.name, test.perm, st.Mode()) - } - } - - os.RemoveAll(base) - } -} - -func validateDirEmpty(dir string) error { - files, err := ioutil.ReadDir(dir) - if err != nil { - return err - } - - if len(files) != 0 { - return fmt.Errorf("Directory %q is not empty", dir) - } - return nil -} - -func validateDirExists(dir string) error { - _, err := ioutil.ReadDir(dir) - if err != nil { - return err - } - return nil -} - -func validateDirNotExists(dir string) error { - _, err := ioutil.ReadDir(dir) - if os.IsNotExist(err) { - return nil - } - if err != nil { - return err - } - return fmt.Errorf("dir %q still exists", dir) -} - -func validateFileExists(file string) error { - if _, err := os.Stat(file); err != nil { - return err - } - return nil -} - -func TestRemoveEmptyDirs(t *testing.T) { - defaultPerm := os.FileMode(0750) - tests := []struct { - name string - // Function that prepares directory structure for the test under given - // base. - prepare func(base string) error - // Function that validates directory structure after the test - validate func(base string) error - baseDir string - endDir string - expectError bool - }{ - { - name: "all-empty", - prepare: func(base string) error { - return os.MkdirAll(filepath.Join(base, "a/b/c"), defaultPerm) - }, - validate: func(base string) error { - return validateDirEmpty(filepath.Join(base, "a")) - }, - baseDir: "a", - endDir: "a/b/c", - expectError: false, - }, - { - name: "dir-not-empty", - prepare: func(base string) error { - if err := os.MkdirAll(filepath.Join(base, "a/b/c"), defaultPerm); err != nil { - return err - } - return os.Mkdir(filepath.Join(base, "a/b/d"), defaultPerm) - }, - validate: func(base string) error { - if err := validateDirNotExists(filepath.Join(base, "a/b/c")); err != nil { - return err - } - return validateDirExists(filepath.Join(base, "a/b")) - }, - baseDir: "a", - endDir: "a/b/c", - expectError: false, - }, - { - name: "path-not-within-base", - prepare: func(base string) error { - return os.MkdirAll(filepath.Join(base, "a/b/c"), defaultPerm) - }, - validate: func(base string) error { - return validateDirExists(filepath.Join(base, "a")) - }, - baseDir: "a", - endDir: "b/c", - expectError: true, - }, - { - name: "path-already-deleted", - prepare: func(base string) error { - return nil - }, - validate: func(base string) error { - return nil - }, - baseDir: "a", - endDir: "a/b/c", - expectError: false, - }, - { - name: "path-not-dir", - prepare: func(base string) error { - if err := os.MkdirAll(filepath.Join(base, "a/b"), defaultPerm); err != nil { - return err - } - return ioutil.WriteFile(filepath.Join(base, "a/b", "c"), []byte{}, defaultPerm) - }, - validate: func(base string) error { - if err := validateDirExists(filepath.Join(base, "a/b")); err != nil { - return err - } - return validateFileExists(filepath.Join(base, "a/b/c")) - }, - baseDir: "a", - endDir: "a/b/c", - expectError: true, - }, - } - - for _, test := range tests { - glog.V(4).Infof("test %q", test.name) - base, err := ioutil.TempDir("", "remove-empty-dirs-"+test.name+"-") - if err != nil { - t.Fatalf(err.Error()) - } - if err = test.prepare(base); err != nil { - os.RemoveAll(base) - t.Fatalf("failed to prepare test %q: %v", test.name, err.Error()) - } - - err = removeEmptyDirs(filepath.Join(base, test.baseDir), filepath.Join(base, test.endDir)) - if err != nil && !test.expectError { - t.Errorf("test %q failed: %v", test.name, err) - } - if err == nil && test.expectError { - t.Errorf("test %q failed: expected error, got success", test.name) - } - - if err = test.validate(base); err != nil { - t.Errorf("test %q failed validation: %v", test.name, err) - } - - os.RemoveAll(base) - } -} - -func TestCleanSubPaths(t *testing.T) { - defaultPerm := os.FileMode(0750) - testVol := "vol1" - - tests := []struct { - name string - // Function that prepares directory structure for the test under given - // base. - prepare func(base string) ([]MountPoint, error) - // Function that validates directory structure after the test - validate func(base string) error - expectError bool - }{ - { - name: "not-exists", - prepare: func(base string) ([]MountPoint, error) { - return nil, nil - }, - validate: func(base string) error { - return nil - }, - expectError: false, - }, - { - name: "subpath-not-mount", - prepare: func(base string) ([]MountPoint, error) { - return nil, os.MkdirAll(filepath.Join(base, containerSubPathDirectoryName, testVol, "container1", "0"), defaultPerm) - }, - validate: func(base string) error { - return validateDirNotExists(filepath.Join(base, containerSubPathDirectoryName)) - }, - expectError: false, - }, - { - name: "subpath-file", - prepare: func(base string) ([]MountPoint, error) { - path := filepath.Join(base, containerSubPathDirectoryName, testVol, "container1") - if err := os.MkdirAll(path, defaultPerm); err != nil { - return nil, err - } - return nil, ioutil.WriteFile(filepath.Join(path, "0"), []byte{}, defaultPerm) - }, - validate: func(base string) error { - return validateDirNotExists(filepath.Join(base, containerSubPathDirectoryName)) - }, - expectError: false, - }, - { - name: "subpath-container-not-dir", - prepare: func(base string) ([]MountPoint, error) { - path := filepath.Join(base, containerSubPathDirectoryName, testVol) - if err := os.MkdirAll(path, defaultPerm); err != nil { - return nil, err - } - return nil, ioutil.WriteFile(filepath.Join(path, "container1"), []byte{}, defaultPerm) - }, - validate: func(base string) error { - return validateDirExists(filepath.Join(base, containerSubPathDirectoryName, testVol)) - }, - expectError: true, - }, - { - name: "subpath-multiple-container-not-dir", - prepare: func(base string) ([]MountPoint, error) { - path := filepath.Join(base, containerSubPathDirectoryName, testVol) - if err := os.MkdirAll(filepath.Join(path, "container1"), defaultPerm); err != nil { - return nil, err - } - return nil, ioutil.WriteFile(filepath.Join(path, "container2"), []byte{}, defaultPerm) - }, - validate: func(base string) error { - path := filepath.Join(base, containerSubPathDirectoryName, testVol) - if err := validateDirNotExists(filepath.Join(path, "container1")); err != nil { - return err - } - return validateFileExists(filepath.Join(path, "container2")) - }, - expectError: true, - }, - { - name: "subpath-mount", - prepare: func(base string) ([]MountPoint, error) { - path := filepath.Join(base, containerSubPathDirectoryName, testVol, "container1", "0") - if err := os.MkdirAll(path, defaultPerm); err != nil { - return nil, err - } - mounts := []MountPoint{{Device: "/dev/sdb", Path: path}} - return mounts, nil - }, - validate: func(base string) error { - return validateDirNotExists(filepath.Join(base, containerSubPathDirectoryName)) - }, - }, - { - name: "subpath-mount-multiple", - prepare: func(base string) ([]MountPoint, error) { - path := filepath.Join(base, containerSubPathDirectoryName, testVol, "container1", "0") - path2 := filepath.Join(base, containerSubPathDirectoryName, testVol, "container1", "1") - path3 := filepath.Join(base, containerSubPathDirectoryName, testVol, "container2", "1") - if err := os.MkdirAll(path, defaultPerm); err != nil { - return nil, err - } - if err := os.MkdirAll(path2, defaultPerm); err != nil { - return nil, err - } - if err := os.MkdirAll(path3, defaultPerm); err != nil { - return nil, err - } - mounts := []MountPoint{ - {Device: "/dev/sdb", Path: path}, - {Device: "/dev/sdb", Path: path3}, - } - return mounts, nil - }, - validate: func(base string) error { - return validateDirNotExists(filepath.Join(base, containerSubPathDirectoryName)) - }, - }, - { - name: "subpath-mount-multiple-vols", - prepare: func(base string) ([]MountPoint, error) { - path := filepath.Join(base, containerSubPathDirectoryName, testVol, "container1", "0") - path2 := filepath.Join(base, containerSubPathDirectoryName, "vol2", "container1", "1") - if err := os.MkdirAll(path, defaultPerm); err != nil { - return nil, err - } - if err := os.MkdirAll(path2, defaultPerm); err != nil { - return nil, err - } - mounts := []MountPoint{ - {Device: "/dev/sdb", Path: path}, - } - return mounts, nil - }, - validate: func(base string) error { - baseSubdir := filepath.Join(base, containerSubPathDirectoryName) - if err := validateDirNotExists(filepath.Join(baseSubdir, testVol)); err != nil { - return err - } - return validateDirExists(baseSubdir) - }, - }, - } - - for _, test := range tests { - glog.V(4).Infof("test %q", test.name) - base, err := ioutil.TempDir("", "clean-subpaths-"+test.name+"-") - if err != nil { - t.Fatalf(err.Error()) - } - mounts, err := test.prepare(base) - if err != nil { - os.RemoveAll(base) - t.Fatalf("failed to prepare test %q: %v", test.name, err.Error()) - } - - fm := &FakeMounter{MountPoints: mounts} - - err = doCleanSubPaths(fm, base, testVol) - if err != nil && !test.expectError { - t.Errorf("test %q failed: %v", test.name, err) - } - if err == nil && test.expectError { - t.Errorf("test %q failed: expected error, got success", test.name) - } - if err = test.validate(base); err != nil { - t.Errorf("test %q failed validation: %v", test.name, err) - } - - os.RemoveAll(base) - } -} - -var ( - testVol = "vol1" - testPod = "pod0" - testContainer = "container0" - testSubpath = 1 -) - -func setupFakeMounter(testMounts []string) *FakeMounter { - mounts := []MountPoint{} - for _, mountPoint := range testMounts { - mounts = append(mounts, MountPoint{Device: "/foo", Path: mountPoint}) - } - return &FakeMounter{MountPoints: mounts} -} - -func getTestPaths(base string) (string, string) { - return filepath.Join(base, testVol), - filepath.Join(base, testPod, containerSubPathDirectoryName, testVol, testContainer, strconv.Itoa(testSubpath)) -} - -func TestBindSubPath(t *testing.T) { - defaultPerm := os.FileMode(0750) - - tests := []struct { - name string - // Function that prepares directory structure for the test under given - // base. - prepare func(base string) ([]string, string, string, error) - expectError bool - }{ - { - name: "subpath-dir", - prepare: func(base string) ([]string, string, string, error) { - volpath, _ := getTestPaths(base) - subpath := filepath.Join(volpath, "dir0") - return nil, volpath, subpath, os.MkdirAll(subpath, defaultPerm) - }, - expectError: false, - }, - { - name: "subpath-dir-symlink", - prepare: func(base string) ([]string, string, string, error) { - volpath, _ := getTestPaths(base) - subpath := filepath.Join(volpath, "dir0") - if err := os.MkdirAll(subpath, defaultPerm); err != nil { - return nil, "", "", err - } - subpathLink := filepath.Join(volpath, "dirLink") - return nil, volpath, subpath, os.Symlink(subpath, subpathLink) - }, - expectError: false, - }, - { - name: "subpath-file", - prepare: func(base string) ([]string, string, string, error) { - volpath, _ := getTestPaths(base) - subpath := filepath.Join(volpath, "file0") - if err := os.MkdirAll(volpath, defaultPerm); err != nil { - return nil, "", "", err - } - return nil, volpath, subpath, ioutil.WriteFile(subpath, []byte{}, defaultPerm) - }, - expectError: false, - }, - { - name: "subpath-not-exists", - prepare: func(base string) ([]string, string, string, error) { - volpath, _ := getTestPaths(base) - subpath := filepath.Join(volpath, "file0") - return nil, volpath, subpath, nil - }, - expectError: true, - }, - { - name: "subpath-outside", - prepare: func(base string) ([]string, string, string, error) { - volpath, _ := getTestPaths(base) - subpath := filepath.Join(volpath, "dir0") - if err := os.MkdirAll(volpath, defaultPerm); err != nil { - return nil, "", "", err - } - return nil, volpath, subpath, os.Symlink(base, subpath) - }, - expectError: true, - }, - { - name: "subpath-symlink-child-outside", - prepare: func(base string) ([]string, string, string, error) { - volpath, _ := getTestPaths(base) - subpathDir := filepath.Join(volpath, "dir0") - subpath := filepath.Join(subpathDir, "child0") - if err := os.MkdirAll(subpathDir, defaultPerm); err != nil { - return nil, "", "", err - } - return nil, volpath, subpath, os.Symlink(base, subpath) - }, - expectError: true, - }, - { - name: "subpath-child-outside-exists", - prepare: func(base string) ([]string, string, string, error) { - volpath, _ := getTestPaths(base) - subpathDir := filepath.Join(volpath, "dir0") - child := filepath.Join(base, "child0") - subpath := filepath.Join(subpathDir, "child0") - if err := os.MkdirAll(volpath, defaultPerm); err != nil { - return nil, "", "", err - } - // touch file outside - if err := ioutil.WriteFile(child, []byte{}, defaultPerm); err != nil { - return nil, "", "", err - } - - // create symlink for subpath dir - return nil, volpath, subpath, os.Symlink(base, subpathDir) - }, - expectError: true, - }, - { - name: "subpath-child-outside-not-exists", - prepare: func(base string) ([]string, string, string, error) { - volpath, _ := getTestPaths(base) - subpathDir := filepath.Join(volpath, "dir0") - subpath := filepath.Join(subpathDir, "child0") - if err := os.MkdirAll(volpath, defaultPerm); err != nil { - return nil, "", "", err - } - // create symlink for subpath dir - return nil, volpath, subpath, os.Symlink(base, subpathDir) - }, - expectError: true, - }, - { - name: "subpath-child-outside-exists-middle-dir-symlink", - prepare: func(base string) ([]string, string, string, error) { - volpath, _ := getTestPaths(base) - subpathDir := filepath.Join(volpath, "dir0") - symlinkDir := filepath.Join(subpathDir, "linkDir0") - child := filepath.Join(base, "child0") - subpath := filepath.Join(symlinkDir, "child0") - if err := os.MkdirAll(subpathDir, defaultPerm); err != nil { - return nil, "", "", err - } - // touch file outside - if err := ioutil.WriteFile(child, []byte{}, defaultPerm); err != nil { - return nil, "", "", err - } - - // create symlink for middle dir - return nil, volpath, subpath, os.Symlink(base, symlinkDir) - }, - expectError: true, - }, - { - name: "subpath-backstepping", - prepare: func(base string) ([]string, string, string, error) { - volpath, _ := getTestPaths(base) - subpath := filepath.Join(volpath, "dir0") - symlinkBase := filepath.Join(volpath, "..") - if err := os.MkdirAll(volpath, defaultPerm); err != nil { - return nil, "", "", err - } - - // create symlink for subpath - return nil, volpath, subpath, os.Symlink(symlinkBase, subpath) - }, - expectError: true, - }, - { - name: "subpath-mountdir-already-exists", - prepare: func(base string) ([]string, string, string, error) { - volpath, subpathMount := getTestPaths(base) - if err := os.MkdirAll(subpathMount, defaultPerm); err != nil { - return nil, "", "", err - } - - subpath := filepath.Join(volpath, "dir0") - return nil, volpath, subpath, os.MkdirAll(subpath, defaultPerm) - }, - expectError: false, - }, - { - name: "subpath-mount-already-exists", - prepare: func(base string) ([]string, string, string, error) { - volpath, subpathMount := getTestPaths(base) - mounts := []string{subpathMount} - if err := os.MkdirAll(subpathMount, defaultPerm); err != nil { - return nil, "", "", err - } - - subpath := filepath.Join(volpath, "dir0") - return mounts, volpath, subpath, os.MkdirAll(subpath, defaultPerm) - }, - expectError: false, - }, - { - name: "subpath-mounting-unix-socket", - prepare: func(base string) ([]string, string, string, error) { - volpath, subpathMount := getTestPaths(base) - mounts := []string{subpathMount} - if err := os.MkdirAll(volpath, defaultPerm); err != nil { - return nil, "", "", err - } - - if err := os.MkdirAll(subpathMount, defaultPerm); err != nil { - return nil, "", "", err - } - - testSocketFile := filepath.Join(volpath, "mount_test.sock") - _, err := net.Listen("unix", testSocketFile) - return mounts, volpath, testSocketFile, err - }, - expectError: false, - }, - { - name: "subpath-mounting-fifo", - prepare: func(base string) ([]string, string, string, error) { - volpath, subpathMount := getTestPaths(base) - mounts := []string{subpathMount} - if err := os.MkdirAll(volpath, defaultPerm); err != nil { - return nil, "", "", err - } - - if err := os.MkdirAll(subpathMount, defaultPerm); err != nil { - return nil, "", "", err - } - - testFifo := filepath.Join(volpath, "mount_test.fifo") - err := syscall.Mkfifo(testFifo, 0) - return mounts, volpath, testFifo, err - }, - expectError: false, - }, - } - - for _, test := range tests { - glog.V(4).Infof("test %q", test.name) - base, err := ioutil.TempDir("", "bind-subpath-"+test.name+"-") - if err != nil { - t.Fatalf(err.Error()) - } - mounts, volPath, subPath, err := test.prepare(base) - if err != nil { - os.RemoveAll(base) - t.Fatalf("failed to prepare test %q: %v", test.name, err.Error()) - } - - fm := setupFakeMounter(mounts) - - subpath := Subpath{ - VolumeMountIndex: testSubpath, - Path: subPath, - VolumeName: testVol, - VolumePath: volPath, - PodDir: filepath.Join(base, "pod0"), - ContainerName: testContainer, - } - - _, subpathMount := getTestPaths(base) - bindPathTarget, err := doBindSubPath(fm, subpath, 1) - if test.expectError { - if err == nil { - t.Errorf("test %q failed: expected error, got success", test.name) - } - if bindPathTarget != "" { - t.Errorf("test %q failed: expected empty bindPathTarget, got %v", test.name, bindPathTarget) - } - if err = validateDirNotExists(subpathMount); err != nil { - t.Errorf("test %q failed: %v", test.name, err) - } - } - if !test.expectError { - if err != nil { - t.Errorf("test %q failed: %v", test.name, err) - } - if bindPathTarget != subpathMount { - t.Errorf("test %q failed: expected bindPathTarget %v, got %v", test.name, subpathMount, bindPathTarget) - } - if err = validateFileExists(subpathMount); err != nil { - t.Errorf("test %q failed: %v", test.name, err) - } - } - - os.RemoveAll(base) - } -} - -func TestParseMountInfo(t *testing.T) { - info := - `62 0 253:0 / / rw,relatime shared:1 - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered -78 62 0:41 / /tmp rw,nosuid,nodev shared:30 - tmpfs tmpfs rw,seclabel -80 62 0:42 / /var/lib/nfs/rpc_pipefs rw,relatime shared:31 - rpc_pipefs sunrpc rw -82 62 0:43 / /var/lib/foo rw,relatime shared:32 - tmpfs tmpfs rw -83 63 0:44 / /var/lib/bar rw,relatime - tmpfs tmpfs rw -227 62 253:0 /var/lib/docker/devicemapper /var/lib/docker/devicemapper rw,relatime - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered -224 62 253:0 /var/lib/docker/devicemapper/test/shared /var/lib/docker/devicemapper/test/shared rw,relatime master:1 shared:44 - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered -76 17 8:1 / /mnt/stateful_partition rw,nosuid,nodev,noexec,relatime - ext4 /dev/sda1 rw,commit=30,data=ordered -80 17 8:1 /var /var rw,nosuid,nodev,noexec,relatime shared:30 - ext4 /dev/sda1 rw,commit=30,data=ordered -189 80 8:1 /var/lib/kubelet /var/lib/kubelet rw,relatime shared:30 - ext4 /dev/sda1 rw,commit=30,data=ordered -818 77 8:40 / /var/lib/kubelet/pods/c25464af-e52e-11e7-ab4d-42010a800002/volumes/kubernetes.io~gce-pd/vol1 rw,relatime shared:290 - ext4 /dev/sdc rw,data=ordered -819 78 8:48 / /var/lib/kubelet/pods/c25464af-e52e-11e7-ab4d-42010a800002/volumes/kubernetes.io~gce-pd/vol1 rw,relatime shared:290 - ext4 /dev/sdd rw,data=ordered -900 100 8:48 /dir1 /var/lib/kubelet/pods/c25464af-e52e-11e7-ab4d-42010a800002/volume-subpaths/vol1/subpath1/0 rw,relatime shared:290 - ext4 /dev/sdd rw,data=ordered -901 101 8:1 /dir1 /var/lib/kubelet/pods/c25464af-e52e-11e7-ab4d-42010a800002/volume-subpaths/vol1/subpath1/1 rw,relatime shared:290 - ext4 /dev/sdd rw,data=ordered -902 102 8:1 /var/lib/kubelet/pods/d4076f24-e53a-11e7-ba15-42010a800002/volumes/kubernetes.io~empty-dir/vol1/dir1 /var/lib/kubelet/pods/d4076f24-e53a-11e7-ba15-42010a800002/volume-subpaths/vol1/subpath1/0 rw,relatime shared:30 - ext4 /dev/sda1 rw,commit=30,data=ordered -903 103 8:1 /var/lib/kubelet/pods/d4076f24-e53a-11e7-ba15-42010a800002/volumes/kubernetes.io~empty-dir/vol2/dir1 /var/lib/kubelet/pods/d4076f24-e53a-11e7-ba15-42010a800002/volume-subpaths/vol1/subpath1/1 rw,relatime shared:30 - ext4 /dev/sda1 rw,commit=30,data=ordered -178 25 253:0 /etc/bar /var/lib/kubelet/pods/12345/volume-subpaths/vol1/subpath1/0 rw,relatime shared:1 - ext4 /dev/sdb2 rw,errors=remount-ro,data=ordered -698 186 0:41 /tmp1/dir1 /var/lib/kubelet/pods/41135147-e697-11e7-9342-42010a800002/volume-subpaths/vol1/subpath1/0 rw shared:26 - tmpfs tmpfs rw -918 77 8:50 / /var/lib/kubelet/pods/2345/volumes/kubernetes.io~gce-pd/vol1 rw,relatime shared:290 - ext4 /dev/sdc rw,data=ordered -919 78 8:58 / /var/lib/kubelet/pods/2345/volumes/kubernetes.io~gce-pd/vol1 rw,relatime shared:290 - ext4 /dev/sdd rw,data=ordered -920 100 8:50 /dir1 /var/lib/kubelet/pods/2345/volume-subpaths/vol1/subpath1/0 rw,relatime shared:290 - ext4 /dev/sdc rw,data=ordered -150 23 1:58 / /media/nfs_vol rw,relatime shared:89 - nfs4 172.18.4.223:/srv/nfs rw,vers=4.0,rsize=524288,wsize=524288,namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=172.18.4.223,local_lock=none,addr=172.18.4.223 -151 24 1:58 / /media/nfs_bindmount rw,relatime shared:89 - nfs4 172.18.4.223:/srv/nfs/foo rw,vers=4.0,rsize=524288,wsize=524288,namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=172.18.4.223,local_lock=none,addr=172.18.4.223 -134 23 0:58 / /var/lib/kubelet/pods/43219158-e5e1-11e7-a392-0e858b8eaf40/volumes/kubernetes.io~nfs/nfs1 rw,relatime shared:89 - nfs4 172.18.4.223:/srv/nfs rw,vers=4.0,rsize=524288,wsize=524288,namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=172.18.4.223,local_lock=none,addr=172.18.4.223 -187 23 0:58 / /var/lib/kubelet/pods/1fc5ea21-eff4-11e7-ac80-0e858b8eaf40/volumes/kubernetes.io~nfs/nfs2 rw,relatime shared:96 - nfs4 172.18.4.223:/srv/nfs2 rw,vers=4.0,rsize=524288,wsize=524288,namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=172.18.4.223,local_lock=none,addr=172.18.4.223 -188 24 0:58 / /var/lib/kubelet/pods/43219158-e5e1-11e7-a392-0e858b8eaf40/volume-subpaths/nfs1/subpath1/0 rw,relatime shared:89 - nfs4 172.18.4.223:/srv/nfs/foo rw,vers=4.0,rsize=524288,wsize=524288,namlen=255,hard,proto=tcp,port=0,timeo=600,retrans=2,sec=sys,clientaddr=172.18.4.223,local_lock=none,addr=172.18.4.223 -347 60 0:71 / /var/lib/kubelet/pods/13195d46-f9fa-11e7-bbf1-5254007a695a/volumes/kubernetes.io~nfs/vol2 rw,relatime shared:170 - nfs 172.17.0.3:/exports/2 rw,vers=3,rsize=1048576,wsize=1048576,namlen=255,hard,proto=tcp,timeo=600,retrans=2,sec=sys,mountaddr=172.17.0.3,mountvers=3,mountport=20048,mountproto=udp,local_lock=none,addr=172.17.0.3 -` - tempDir, filename, err := writeFile(info) - if err != nil { - t.Fatalf("cannot create temporary file: %v", err) - } - defer os.RemoveAll(tempDir) - - tests := []struct { - name string - mountPoint string - expectedInfo mountInfo - }{ - { - "simple bind mount", - "/var/lib/kubelet", - mountInfo{ - mountPoint: "/var/lib/kubelet", - optional: []string{"shared:30"}, - }, - }, - } - - infos, err := parseMountInfo(filename) - if err != nil { - t.Fatalf("Cannot parse %s: %s", filename, err) - } - - for _, test := range tests { - found := false - for _, info := range infos { - if info.mountPoint == test.mountPoint { - found = true - if !reflect.DeepEqual(info, test.expectedInfo) { - t.Errorf("Test case %q:\n expected: %+v\n got: %+v", test.name, test.expectedInfo, info) - } - break - } - } - if !found { - t.Errorf("Test case %q: mountPoint %s not found", test.name, test.mountPoint) - } - } -} - -func TestSafeOpen(t *testing.T) { - defaultPerm := os.FileMode(0750) - - tests := []struct { - name string - // Function that prepares directory structure for the test under given - // base. - prepare func(base string) error - path string - expectError bool - }{ - { - "directory-does-not-exist", - func(base string) error { - return nil - }, - "test/directory", - true, - }, - { - "directory-exists", - func(base string) error { - return os.MkdirAll(filepath.Join(base, "test/directory"), 0750) - }, - "test/directory", - false, - }, - { - "escape-base-using-dots", - func(base string) error { - return nil - }, - "..", - true, - }, - { - "escape-base-using-dots-2", - func(base string) error { - return os.MkdirAll(filepath.Join(base, "test"), 0750) - }, - "test/../../..", - true, - }, - { - "symlink", - func(base string) error { - if err := os.MkdirAll(filepath.Join(base, "destination"), defaultPerm); err != nil { - return err - } - return os.Symlink("destination", filepath.Join(base, "test")) - }, - "test", - true, - }, - { - "symlink-nested", - func(base string) error { - if err := os.MkdirAll(filepath.Join(base, "dir1/dir2"), defaultPerm); err != nil { - return err - } - return os.Symlink("dir1", filepath.Join(base, "dir1/dir2/test")) - }, - "test", - true, - }, - { - "symlink-loop", - func(base string) error { - return os.Symlink("test", filepath.Join(base, "test")) - }, - "test", - true, - }, - { - "symlink-not-exists", - func(base string) error { - return os.Symlink("non-existing", filepath.Join(base, "test")) - }, - "test", - true, - }, - { - "non-directory", - func(base string) error { - return ioutil.WriteFile(filepath.Join(base, "test"), []byte{}, defaultPerm) - }, - "test/directory", - true, - }, - { - "non-directory-final", - func(base string) error { - return ioutil.WriteFile(filepath.Join(base, "test"), []byte{}, defaultPerm) - }, - "test", - false, - }, - { - "escape-with-relative-symlink", - func(base string) error { - if err := os.MkdirAll(filepath.Join(base, "dir"), defaultPerm); err != nil { - return err - } - if err := os.MkdirAll(filepath.Join(base, "exists"), defaultPerm); err != nil { - return err - } - return os.Symlink("../exists", filepath.Join(base, "dir/test")) - }, - "dir/test", - true, - }, - { - "escape-with-relative-symlink-not-exists", - func(base string) error { - if err := os.MkdirAll(filepath.Join(base, "dir"), defaultPerm); err != nil { - return err - } - return os.Symlink("../not-exists", filepath.Join(base, "dir/test")) - }, - "dir/test", - true, - }, - { - "escape-with-symlink", - func(base string) error { - return os.Symlink("/", filepath.Join(base, "test")) - }, - "test", - true, - }, - { - "mounting-unix-socket", - func(base string) error { - testSocketFile := filepath.Join(base, "mount_test.sock") - _, err := net.Listen("unix", testSocketFile) - if err != nil { - return fmt.Errorf("Error preparing socket file %s with %v", testSocketFile, err) - } - return nil - }, - "mount_test.sock", - false, - }, - { - "mounting-unix-socket-in-middle", - func(base string) error { - testSocketFile := filepath.Join(base, "mount_test.sock") - _, err := net.Listen("unix", testSocketFile) - if err != nil { - return fmt.Errorf("Error preparing socket file %s with %v", testSocketFile, err) - } - return nil - }, - "mount_test.sock/bar", - true, - }, - } - - for _, test := range tests { - glog.V(4).Infof("test %q", test.name) - base, err := ioutil.TempDir("", "safe-open-"+test.name+"-") - if err != nil { - t.Fatalf(err.Error()) - } - test.prepare(base) - pathToCreate := filepath.Join(base, test.path) - fd, err := doSafeOpen(pathToCreate, base) - if err != nil && !test.expectError { - t.Errorf("test %q: %s", test.name, err) - } - if err != nil { - glog.Infof("got error: %s", err) - } - if err == nil && test.expectError { - t.Errorf("test %q: expected error, got none", test.name) - } - - syscall.Close(fd) - os.RemoveAll(base) - } -} - -func TestFindExistingPrefix(t *testing.T) { - defaultPerm := os.FileMode(0750) - tests := []struct { - name string - // Function that prepares directory structure for the test under given - // base. - prepare func(base string) error - path string - expectedPath string - expectedDirs []string - expectError bool - }{ - { - "directory-does-not-exist", - func(base string) error { - return nil - }, - "directory", - "", - []string{"directory"}, - false, - }, - { - "directory-exists", - func(base string) error { - return os.MkdirAll(filepath.Join(base, "test/directory"), 0750) - }, - "test/directory", - "test/directory", - []string{}, - false, - }, - { - "follow-symlinks", - func(base string) error { - if err := os.MkdirAll(filepath.Join(base, "destination/directory"), defaultPerm); err != nil { - return err - } - return os.Symlink("destination", filepath.Join(base, "test")) - }, - "test/directory", - "test/directory", - []string{}, - false, - }, - { - "follow-symlink-loop", - func(base string) error { - return os.Symlink("test", filepath.Join(base, "test")) - }, - "test/directory", - "", - nil, - true, - }, - { - "follow-symlink-multiple follow", - func(base string) error { - /* test1/dir points to test2 and test2/dir points to test1 */ - if err := os.MkdirAll(filepath.Join(base, "test1"), defaultPerm); err != nil { - return err - } - if err := os.MkdirAll(filepath.Join(base, "test2"), defaultPerm); err != nil { - return err - } - if err := os.Symlink(filepath.Join(base, "test2"), filepath.Join(base, "test1/dir")); err != nil { - return err - } - if err := os.Symlink(filepath.Join(base, "test1"), filepath.Join(base, "test2/dir")); err != nil { - return err - } - return nil - }, - "test1/dir/dir/foo/bar", - "test1/dir/dir", - []string{"foo", "bar"}, - false, - }, - { - "danglink-symlink", - func(base string) error { - return os.Symlink("non-existing", filepath.Join(base, "test")) - }, - // OS returns IsNotExist error both for dangling symlink and for - // non-existing directory. - "test/directory", - "", - []string{"test", "directory"}, - false, - }, - { - "with-fifo-in-middle", - func(base string) error { - testFifo := filepath.Join(base, "mount_test.fifo") - return syscall.Mkfifo(testFifo, 0) - }, - "mount_test.fifo/directory", - "", - nil, - true, - }, - } - - for _, test := range tests { - glog.V(4).Infof("test %q", test.name) - base, err := ioutil.TempDir("", "find-prefix-"+test.name+"-") - if err != nil { - t.Fatalf(err.Error()) - } - test.prepare(base) - path := filepath.Join(base, test.path) - existingPath, dirs, err := findExistingPrefix(base, path) - if err != nil && !test.expectError { - t.Errorf("test %q: %s", test.name, err) - } - if err != nil { - glog.Infof("got error: %s", err) - } - if err == nil && test.expectError { - t.Errorf("test %q: expected error, got none", test.name) - } - - fullExpectedPath := filepath.Join(base, test.expectedPath) - if existingPath != fullExpectedPath { - t.Errorf("test %q: expected path %q, got %q", test.name, fullExpectedPath, existingPath) - } - if !reflect.DeepEqual(dirs, test.expectedDirs) { - t.Errorf("test %q: expected dirs %v, got %v", test.name, test.expectedDirs, dirs) - } - os.RemoveAll(base) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_windows.go b/vendor/k8s.io/kubernetes/pkg/util/mount/mount_windows.go index 12e1bca118..0384ba179f 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_windows.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/mount_windows.go @@ -201,31 +201,7 @@ func (mounter *Mounter) MakeRShared(path string) error { // GetFileType checks for sockets/block/character devices func (mounter *Mounter) GetFileType(pathname string) (FileType, error) { - var pathType FileType - info, err := os.Stat(pathname) - if os.IsNotExist(err) { - return pathType, fmt.Errorf("path %q does not exist", pathname) - } - // err in call to os.Stat - if err != nil { - return pathType, err - } - - mode := info.Sys().(*syscall.Win32FileAttributeData).FileAttributes - switch mode & syscall.S_IFMT { - case syscall.S_IFSOCK: - return FileTypeSocket, nil - case syscall.S_IFBLK: - return FileTypeBlockDev, nil - case syscall.S_IFCHR: - return FileTypeCharDev, nil - case syscall.S_IFDIR: - return FileTypeDirectory, nil - case syscall.S_IFREG: - return FileTypeFile, nil - } - - return pathType, fmt.Errorf("only recognise file, directory, socket, block device and character device") + return getFileType(pathname) } // MakeFile creates a new directory diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_windows_test.go b/vendor/k8s.io/kubernetes/pkg/util/mount/mount_windows_test.go deleted file mode 100644 index e31217e975..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/mount_windows_test.go +++ /dev/null @@ -1,553 +0,0 @@ -// +build windows - -/* -Copyright 2017 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 mount - -import ( - "fmt" - "os" - "os/exec" - "path/filepath" - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestNormalizeWindowsPath(t *testing.T) { - path := `/var/lib/kubelet/pods/146f8428-83e7-11e7-8dd4-000d3a31dac4/volumes/kubernetes.io~azure-disk` - normalizedPath := normalizeWindowsPath(path) - if normalizedPath != `c:\var\lib\kubelet\pods\146f8428-83e7-11e7-8dd4-000d3a31dac4\volumes\kubernetes.io~azure-disk` { - t.Errorf("normizeWindowsPath test failed, normalizedPath : %q", normalizedPath) - } - - path = `/var/lib/kubelet/pods/146f8428-83e7-11e7-8dd4-000d3a31dac4\volumes\kubernetes.io~azure-disk` - normalizedPath = normalizeWindowsPath(path) - if normalizedPath != `c:\var\lib\kubelet\pods\146f8428-83e7-11e7-8dd4-000d3a31dac4\volumes\kubernetes.io~azure-disk` { - t.Errorf("normizeWindowsPath test failed, normalizedPath : %q", normalizedPath) - } - - path = `/` - normalizedPath = normalizeWindowsPath(path) - if normalizedPath != `c:\` { - t.Errorf("normizeWindowsPath test failed, normalizedPath : %q", normalizedPath) - } -} - -func TestValidateDiskNumber(t *testing.T) { - diskNum := "0" - if err := ValidateDiskNumber(diskNum); err != nil { - t.Errorf("TestValidateDiskNumber test failed, disk number : %s", diskNum) - } - - diskNum = "99" - if err := ValidateDiskNumber(diskNum); err != nil { - t.Errorf("TestValidateDiskNumber test failed, disk number : %s", diskNum) - } - - diskNum = "ab" - if err := ValidateDiskNumber(diskNum); err == nil { - t.Errorf("TestValidateDiskNumber test failed, disk number : %s", diskNum) - } - - diskNum = "100" - if err := ValidateDiskNumber(diskNum); err == nil { - t.Errorf("TestValidateDiskNumber test failed, disk number : %s", diskNum) - } -} - -func makeLink(link, target string) error { - if output, err := exec.Command("cmd", "/c", "mklink", "/D", link, target).CombinedOutput(); err != nil { - return fmt.Errorf("mklink failed: %v, link(%q) target(%q) output: %q", err, link, target, string(output)) - } - return nil -} - -func removeLink(link string) error { - if output, err := exec.Command("cmd", "/c", "rmdir", link).CombinedOutput(); err != nil { - return fmt.Errorf("rmdir failed: %v, output: %q", err, string(output)) - } - return nil -} - -func setEquivalent(set1, set2 []string) bool { - map1 := make(map[string]bool) - map2 := make(map[string]bool) - for _, s := range set1 { - map1[s] = true - } - for _, s := range set2 { - map2[s] = true - } - - for s := range map1 { - if !map2[s] { - return false - } - } - for s := range map2 { - if !map1[s] { - return false - } - } - return true -} - -// this func must run in admin mode, otherwise it will fail -func TestGetMountRefs(t *testing.T) { - fm := &FakeMounter{MountPoints: []MountPoint{}} - mountPath := `c:\secondmountpath` - expectedRefs := []string{`c:\`, `c:\firstmountpath`, mountPath} - - // remove symbolic links first - for i := 1; i < len(expectedRefs); i++ { - removeLink(expectedRefs[i]) - } - - // create symbolic links - for i := 1; i < len(expectedRefs); i++ { - if err := makeLink(expectedRefs[i], expectedRefs[i-1]); err != nil { - t.Errorf("makeLink failed: %v", err) - } - } - - if refs, err := GetMountRefs(fm, mountPath); err != nil || !setEquivalent(expectedRefs, refs) { - t.Errorf("getMountRefs(%q) = %v, error: %v; expected %v", mountPath, refs, err, expectedRefs) - } - - // remove symbolic links - for i := 1; i < len(expectedRefs); i++ { - if err := removeLink(expectedRefs[i]); err != nil { - t.Errorf("removeLink failed: %v", err) - } - } -} - -func TestDoSafeMakeDir(t *testing.T) { - const testingVolumePath = `c:\tmp\DoSafeMakeDirTest` - os.MkdirAll(testingVolumePath, 0755) - defer os.RemoveAll(testingVolumePath) - - tests := []struct { - volumePath string - subPath string - expectError bool - symlinkTarget string - }{ - { - volumePath: testingVolumePath, - subPath: ``, - expectError: true, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `x`), - expectError: false, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a\b\c\d`), - expectError: false, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `symlink`), - expectError: false, - symlinkTarget: `c:\tmp`, - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `symlink\c\d`), - expectError: true, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `symlink\y926`), - expectError: true, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a\b\symlink`), - expectError: false, - symlinkTarget: `c:\tmp`, - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a\x\symlink`), - expectError: false, - symlinkTarget: filepath.Join(testingVolumePath, `a`), - }, - } - - for _, test := range tests { - if len(test.volumePath) > 0 && len(test.subPath) > 0 && len(test.symlinkTarget) > 0 { - // make all parent sub directories - if parent := filepath.Dir(test.subPath); parent != "." { - os.MkdirAll(parent, 0755) - } - - // make last element as symlink - linkPath := test.subPath - if _, err := os.Stat(linkPath); err != nil && os.IsNotExist(err) { - if err := makeLink(linkPath, test.symlinkTarget); err != nil { - t.Fatalf("unexpected error: %v", fmt.Errorf("mklink link(%q) target(%q) error: %q", linkPath, test.symlinkTarget, err)) - } - } - } - - err := doSafeMakeDir(test.subPath, test.volumePath, os.FileMode(0755)) - if test.expectError { - assert.NotNil(t, err, "Expect error during doSafeMakeDir(%s, %s)", test.subPath, test.volumePath) - continue - } - assert.Nil(t, err, "Expect no error during doSafeMakeDir(%s, %s)", test.subPath, test.volumePath) - if _, err := os.Stat(test.subPath); os.IsNotExist(err) { - t.Errorf("subPath should exists after doSafeMakeDir(%s, %s)", test.subPath, test.volumePath) - } - } -} - -func TestLockAndCheckSubPath(t *testing.T) { - const testingVolumePath = `c:\tmp\LockAndCheckSubPathTest` - - tests := []struct { - volumePath string - subPath string - expectedHandleCount int - expectError bool - symlinkTarget string - }{ - { - volumePath: `c:\`, - subPath: ``, - expectedHandleCount: 0, - expectError: false, - symlinkTarget: "", - }, - { - volumePath: ``, - subPath: `a`, - expectedHandleCount: 0, - expectError: false, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a`), - expectedHandleCount: 1, - expectError: false, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a\b\c\d`), - expectedHandleCount: 4, - expectError: false, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `symlink`), - expectedHandleCount: 0, - expectError: true, - symlinkTarget: `c:\tmp`, - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a\b\c\symlink`), - expectedHandleCount: 0, - expectError: true, - symlinkTarget: `c:\tmp`, - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a\b\c\d\symlink`), - expectedHandleCount: 2, - expectError: false, - symlinkTarget: filepath.Join(testingVolumePath, `a\b`), - }, - } - - for _, test := range tests { - if len(test.volumePath) > 0 && len(test.subPath) > 0 { - os.MkdirAll(test.volumePath, 0755) - if len(test.symlinkTarget) == 0 { - // make all intermediate sub directories - os.MkdirAll(test.subPath, 0755) - } else { - // make all parent sub directories - if parent := filepath.Dir(test.subPath); parent != "." { - os.MkdirAll(parent, 0755) - } - - // make last element as symlink - linkPath := test.subPath - if _, err := os.Stat(linkPath); err != nil && os.IsNotExist(err) { - if err := makeLink(linkPath, test.symlinkTarget); err != nil { - t.Fatalf("unexpected error: %v", fmt.Errorf("mklink link(%q) target(%q) error: %q", linkPath, test.symlinkTarget, err)) - } - } - } - } - - fileHandles, err := lockAndCheckSubPath(test.volumePath, test.subPath) - unlockPath(fileHandles) - assert.Equal(t, test.expectedHandleCount, len(fileHandles)) - if test.expectError { - assert.NotNil(t, err, "Expect error during LockAndCheckSubPath(%s, %s)", test.volumePath, test.subPath) - continue - } - assert.Nil(t, err, "Expect no error during LockAndCheckSubPath(%s, %s)", test.volumePath, test.subPath) - } - - // remove dir will happen after closing all file handles - assert.Nil(t, os.RemoveAll(testingVolumePath), "Expect no error during remove dir %s", testingVolumePath) -} - -func TestLockAndCheckSubPathWithoutSymlink(t *testing.T) { - const testingVolumePath = `c:\tmp\LockAndCheckSubPathWithoutSymlinkTest` - - tests := []struct { - volumePath string - subPath string - expectedHandleCount int - expectError bool - symlinkTarget string - }{ - { - volumePath: `c:\`, - subPath: ``, - expectedHandleCount: 0, - expectError: false, - symlinkTarget: "", - }, - { - volumePath: ``, - subPath: `a`, - expectedHandleCount: 0, - expectError: false, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a`), - expectedHandleCount: 1, - expectError: false, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a\b\c\d`), - expectedHandleCount: 4, - expectError: false, - symlinkTarget: "", - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `symlink`), - expectedHandleCount: 1, - expectError: true, - symlinkTarget: `c:\tmp`, - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a\b\c\symlink`), - expectedHandleCount: 4, - expectError: true, - symlinkTarget: `c:\tmp`, - }, - { - volumePath: testingVolumePath, - subPath: filepath.Join(testingVolumePath, `a\b\c\d\symlink`), - expectedHandleCount: 5, - expectError: true, - symlinkTarget: filepath.Join(testingVolumePath, `a\b`), - }, - } - - for _, test := range tests { - if len(test.volumePath) > 0 && len(test.subPath) > 0 { - os.MkdirAll(test.volumePath, 0755) - if len(test.symlinkTarget) == 0 { - // make all intermediate sub directories - os.MkdirAll(test.subPath, 0755) - } else { - // make all parent sub directories - if parent := filepath.Dir(test.subPath); parent != "." { - os.MkdirAll(parent, 0755) - } - - // make last element as symlink - linkPath := test.subPath - if _, err := os.Stat(linkPath); err != nil && os.IsNotExist(err) { - if err := makeLink(linkPath, test.symlinkTarget); err != nil { - t.Fatalf("unexpected error: %v", fmt.Errorf("mklink link(%q) target(%q) error: %q", linkPath, test.symlinkTarget, err)) - } - } - } - } - - fileHandles, err := lockAndCheckSubPathWithoutSymlink(test.volumePath, test.subPath) - unlockPath(fileHandles) - assert.Equal(t, test.expectedHandleCount, len(fileHandles)) - if test.expectError { - assert.NotNil(t, err, "Expect error during LockAndCheckSubPath(%s, %s)", test.volumePath, test.subPath) - continue - } - assert.Nil(t, err, "Expect no error during LockAndCheckSubPath(%s, %s)", test.volumePath, test.subPath) - } - - // remove dir will happen after closing all file handles - assert.Nil(t, os.RemoveAll(testingVolumePath), "Expect no error during remove dir %s", testingVolumePath) -} - -func TestFindExistingPrefix(t *testing.T) { - const testingVolumePath = `c:\tmp\FindExistingPrefixTest` - - tests := []struct { - base string - pathname string - expectError bool - expectedExistingPath string - expectedToCreateDirs []string - createSubPathBeforeTest bool - }{ - { - base: `c:\tmp\a`, - pathname: `c:\tmp\b`, - expectError: true, - expectedExistingPath: "", - expectedToCreateDirs: []string{}, - createSubPathBeforeTest: false, - }, - { - base: ``, - pathname: `c:\tmp\b`, - expectError: true, - expectedExistingPath: "", - expectedToCreateDirs: []string{}, - createSubPathBeforeTest: false, - }, - { - base: `c:\tmp\a`, - pathname: `d:\tmp\b`, - expectError: true, - expectedExistingPath: "", - expectedToCreateDirs: []string{}, - createSubPathBeforeTest: false, - }, - { - base: testingVolumePath, - pathname: testingVolumePath, - expectError: false, - expectedExistingPath: testingVolumePath, - expectedToCreateDirs: []string{}, - createSubPathBeforeTest: false, - }, - { - base: testingVolumePath, - pathname: filepath.Join(testingVolumePath, `a\b`), - expectError: false, - expectedExistingPath: filepath.Join(testingVolumePath, `a\b`), - expectedToCreateDirs: []string{}, - createSubPathBeforeTest: true, - }, - { - base: testingVolumePath, - pathname: filepath.Join(testingVolumePath, `a\b\c\`), - expectError: false, - expectedExistingPath: filepath.Join(testingVolumePath, `a\b`), - expectedToCreateDirs: []string{`c`}, - createSubPathBeforeTest: false, - }, - { - base: testingVolumePath, - pathname: filepath.Join(testingVolumePath, `a\b\c\d`), - expectError: false, - expectedExistingPath: filepath.Join(testingVolumePath, `a\b`), - expectedToCreateDirs: []string{`c`, `d`}, - createSubPathBeforeTest: false, - }, - } - - for _, test := range tests { - if test.createSubPathBeforeTest { - os.MkdirAll(test.pathname, 0755) - } - - existingPath, toCreate, err := findExistingPrefix(test.base, test.pathname) - if test.expectError { - assert.NotNil(t, err, "Expect error during findExistingPrefix(%s, %s)", test.base, test.pathname) - continue - } - assert.Nil(t, err, "Expect no error during findExistingPrefix(%s, %s)", test.base, test.pathname) - - assert.Equal(t, test.expectedExistingPath, existingPath, "Expect result not equal with findExistingPrefix(%s, %s) return: %q, expected: %q", - test.base, test.pathname, existingPath, test.expectedExistingPath) - - assert.Equal(t, test.expectedToCreateDirs, toCreate, "Expect result not equal with findExistingPrefix(%s, %s) return: %q, expected: %q", - test.base, test.pathname, toCreate, test.expectedToCreateDirs) - - } - // remove dir will happen after closing all file handles - assert.Nil(t, os.RemoveAll(testingVolumePath), "Expect no error during remove dir %s", testingVolumePath) -} - -func TestPathWithinBase(t *testing.T) { - tests := []struct { - fullPath string - basePath string - expectedResult bool - }{ - { - fullPath: `c:\tmp\a\b\c`, - basePath: `c:\tmp`, - expectedResult: true, - }, - { - fullPath: `c:\tmp1`, - basePath: `c:\tmp2`, - expectedResult: false, - }, - { - fullPath: `c:\tmp`, - basePath: `c:\tmp`, - expectedResult: true, - }, - { - fullPath: `c:\tmp`, - basePath: `c:\tmp\a\b\c`, - expectedResult: false, - }, - { - fullPath: `c:\kubelet\pods\uuid\volumes\kubernetes.io~configmap\config\..timestamp\file.txt`, - basePath: `c:\kubelet\pods\uuid\volumes\kubernetes.io~configmap\config`, - expectedResult: true, - }, - } - - for _, test := range tests { - result := pathWithinBase(test.fullPath, test.basePath) - assert.Equal(t, result, test.expectedResult, "Expect result not equal with pathWithinBase(%s, %s) return: %q, expected: %q", - test.fullPath, test.basePath, result, test.expectedResult) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go b/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go index dd2ad3c640..b887b1a3ef 100644 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go +++ b/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount.go @@ -235,8 +235,13 @@ func (n *NsenterMounter) MakeRShared(path string) error { func (mounter *NsenterMounter) GetFileType(pathname string) (FileType, error) { var pathType FileType - outputBytes, err := mounter.ne.Exec("stat", []string{"-L", `--printf "%F"`, pathname}).CombinedOutput() + outputBytes, err := mounter.ne.Exec("stat", []string{"-L", "--printf=%F", pathname}).CombinedOutput() if err != nil { + if strings.Contains(string(outputBytes), "No such file") { + err = fmt.Errorf("%s does not exist", pathname) + } else { + err = fmt.Errorf("stat %s error: %v", pathname, string(outputBytes)) + } return pathType, err } diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_test.go b/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_test.go deleted file mode 100644 index 2aee4ad5f9..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/nsenter_mount_test.go +++ /dev/null @@ -1,191 +0,0 @@ -// +build linux - -/* -Copyright 2017 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 mount - -import ( - "io/ioutil" - "os" - "path" - "strconv" - "testing" -) - -func TestParseFindMnt(t *testing.T) { - tests := []struct { - input string - target string - expectError bool - }{ - { - // standard mount name, e.g. for AWS - "/var/lib/kubelet/plugins/kubernetes.io/aws-ebs/mounts/aws/us-east-1d/vol-020f82b0759f72389 ext4\n", - "/var/lib/kubelet/plugins/kubernetes.io/aws-ebs/mounts/aws/us-east-1d/vol-020f82b0759f72389", - false, - }, - { - // mount name with space, e.g. vSphere - "/var/lib/kubelet/plugins/kubernetes.io/vsphere-volume/mounts/[datastore1] kubevols/kubernetes-dynamic-pvc-4aacaa9b-6ba5-11e7-8f64-0050569f1b82.vmdk ext2\n", - "/var/lib/kubelet/plugins/kubernetes.io/vsphere-volume/mounts/[datastore1] kubevols/kubernetes-dynamic-pvc-4aacaa9b-6ba5-11e7-8f64-0050569f1b82.vmdk", - false, - }, - { - // hypotetic mount with several spaces - "/var/lib/kubelet/plugins/kubernetes.io/vsphere-volume/mounts/[ d a t a s t o r e 1 ] kubevols/kubernetes-dynamic-pvc-4aacaa9b-6ba5-11e7-8f64-0050569f1b82.vmdk ext2\n", - "/var/lib/kubelet/plugins/kubernetes.io/vsphere-volume/mounts/[ d a t a s t o r e 1 ] kubevols/kubernetes-dynamic-pvc-4aacaa9b-6ba5-11e7-8f64-0050569f1b82.vmdk", - false, - }, - { - // invalid output - no filesystem type - "/var/lib/kubelet/plugins/kubernetes.io/vsphere-volume/mounts/blabla", - "", - true, - }, - } - - for i, test := range tests { - target, err := parseFindMnt(test.input) - if test.expectError && err == nil { - t.Errorf("test %d expected error, got nil", i) - } - if !test.expectError && err != nil { - t.Errorf("test %d returned error: %s", i, err) - } - if target != test.target { - t.Errorf("test %d expected %q, got %q", i, test.target, target) - } - } -} - -func TestGetPidOnHost(t *testing.T) { - tempDir, err := ioutil.TempDir("", "get_pid_on_host_tests") - if err != nil { - t.Fatalf(err.Error()) - } - defer os.RemoveAll(tempDir) - - tests := []struct { - name string - procFile string - expectedPid int - expectError bool - }{ - { - name: "valid status file", - procFile: `Name: cat -Umask: 0002 -State: R (running) -Tgid: 15041 -Ngid: 0 -Pid: 15041 -PPid: 22699 -TracerPid: 0 -Uid: 1000 1000 1000 1000 -Gid: 1000 1000 1000 1000 -FDSize: 256 -Groups: 10 135 156 157 158 973 984 1000 1001 -NStgid: 15041 -NSpid: 15041 -NSpgid: 15041 -NSsid: 22699 -VmPeak: 115016 kB -VmSize: 115016 kB -VmLck: 0 kB -VmPin: 0 kB -VmHWM: 816 kB -VmRSS: 816 kB -RssAnon: 64 kB -RssFile: 752 kB -RssShmem: 0 kB -VmData: 312 kB -VmStk: 136 kB -VmExe: 32 kB -VmLib: 2060 kB -VmPTE: 44 kB -VmPMD: 12 kB -VmSwap: 0 kB -HugetlbPages: 0 kB -Threads: 1 -SigQ: 2/60752 -SigPnd: 0000000000000000 -ShdPnd: 0000000000000000 -SigBlk: 0000000000000000 -SigIgn: 0000000000000000 -SigCgt: 0000000000000000 -CapInh: 0000000000000000 -CapPrm: 0000000000000000 -CapEff: 0000000000000000 -CapBnd: 0000003fffffffff -CapAmb: 0000000000000000 -NoNewPrivs: 0 -Seccomp: 0 -Cpus_allowed: ff -Cpus_allowed_list: 0-7 -Mems_allowed: 00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001 -Mems_allowed_list: 0 -voluntary_ctxt_switches: 0 -nonvoluntary_ctxt_switches: 0 -`, - expectedPid: 15041, - }, - { - name: "no Pid:", - procFile: `Name: cat -Umask: 0002 -State: R (running) -Tgid: 15041 -Ngid: 0 -PPid: 22699 -`, - expectedPid: 0, - expectError: true, - }, - { - name: "invalid Pid:", - procFile: `Name: cat -Umask: 0002 -State: R (running) -Tgid: 15041 -Ngid: 0 -Pid: invalid -PPid: 22699 -`, - expectedPid: 0, - expectError: true, - }, - } - - for i, test := range tests { - filename := path.Join(tempDir, strconv.Itoa(i)) - err := ioutil.WriteFile(filename, []byte(test.procFile), 0666) - if err != nil { - t.Fatalf(err.Error()) - } - mounter := NsenterMounter{} - pid, err := mounter.getPidOnHost(filename) - if err != nil && !test.expectError { - t.Errorf("Test %q: unexpected error: %s", test.name, err) - } - if err == nil && test.expectError { - t.Errorf("Test %q: expected error, got none", test.name) - } - if pid != test.expectedPid { - t.Errorf("Test %q: expected pid %d, got %d", test.name, test.expectedPid, pid) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/mount/safe_format_and_mount_test.go b/vendor/k8s.io/kubernetes/pkg/util/mount/safe_format_and_mount_test.go deleted file mode 100644 index 20bfeb9f62..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/mount/safe_format_and_mount_test.go +++ /dev/null @@ -1,242 +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 mount - -import ( - "fmt" - "io/ioutil" - "os" - "runtime" - "testing" - - fakeexec "k8s.io/utils/exec/testing" -) - -type ErrorMounter struct { - *FakeMounter - errIndex int - err []error -} - -func (mounter *ErrorMounter) Mount(source string, target string, fstype string, options []string) error { - i := mounter.errIndex - mounter.errIndex++ - if mounter.err != nil && mounter.err[i] != nil { - return mounter.err[i] - } - return mounter.FakeMounter.Mount(source, target, fstype, options) -} - -type ExecArgs struct { - command string - args []string - output string - err error -} - -func TestSafeFormatAndMount(t *testing.T) { - if runtime.GOOS == "darwin" || runtime.GOOS == "windows" { - t.Skipf("not supported on GOOS=%s", runtime.GOOS) - } - mntDir, err := ioutil.TempDir(os.TempDir(), "mount") - if err != nil { - t.Fatalf("failed to create tmp dir: %v", err) - } - defer os.RemoveAll(mntDir) - tests := []struct { - description string - fstype string - mountOptions []string - execScripts []ExecArgs - mountErrs []error - expectedError error - }{ - { - description: "Test a read only mount", - fstype: "ext4", - mountOptions: []string{"ro"}, - }, - { - description: "Test a normal mount", - fstype: "ext4", - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - }, - }, - { - description: "Test 'fsck' fails with exit status 4", - fstype: "ext4", - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", &fakeexec.FakeExitError{Status: 4}}, - }, - expectedError: fmt.Errorf("'fsck' found errors on device /dev/foo but could not correct them: ."), - }, - { - description: "Test 'fsck' fails with exit status 1 (errors found and corrected)", - fstype: "ext4", - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", &fakeexec.FakeExitError{Status: 1}}, - }, - }, - { - description: "Test 'fsck' fails with exit status other than 1 and 4 (likely unformatted device)", - fstype: "ext4", - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", &fakeexec.FakeExitError{Status: 8}}, - }, - }, - { - description: "Test that 'blkid' is called and fails", - fstype: "ext4", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'")}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "DEVNAME=/dev/foo\nTYPE=ext4\n", nil}, - }, - expectedError: fmt.Errorf("unknown filesystem type '(null)'"), - }, - { - description: "Test that 'blkid' is called and confirms unformatted disk, format fails", - fstype: "ext4", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'")}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &fakeexec.FakeExitError{Status: 2}}, - {"mkfs.ext4", []string{"-F", "/dev/foo"}, "", fmt.Errorf("formatting failed")}, - }, - expectedError: fmt.Errorf("formatting failed"), - }, - { - description: "Test that 'blkid' is called and confirms unformatted disk, format passes, second mount fails", - fstype: "ext4", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'"), fmt.Errorf("Still cannot mount")}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &fakeexec.FakeExitError{Status: 2}}, - {"mkfs.ext4", []string{"-F", "/dev/foo"}, "", nil}, - }, - expectedError: fmt.Errorf("Still cannot mount"), - }, - { - description: "Test that 'blkid' is called and confirms unformatted disk, format passes, second mount passes", - fstype: "ext4", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'"), nil}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &fakeexec.FakeExitError{Status: 2}}, - {"mkfs.ext4", []string{"-F", "/dev/foo"}, "", nil}, - }, - expectedError: nil, - }, - { - description: "Test that 'blkid' is called and confirms unformatted disk, format passes, second mount passes with ext3", - fstype: "ext3", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'"), nil}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &fakeexec.FakeExitError{Status: 2}}, - {"mkfs.ext3", []string{"-F", "/dev/foo"}, "", nil}, - }, - expectedError: nil, - }, - { - description: "test that none ext4 fs does not get called with ext4 options.", - fstype: "xfs", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'"), nil}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &fakeexec.FakeExitError{Status: 2}}, - {"mkfs.xfs", []string{"/dev/foo"}, "", nil}, - }, - expectedError: nil, - }, - { - description: "Test that 'blkid' is called and reports ext4 partition", - fstype: "ext3", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'")}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "DEVNAME=/dev/foo\nPTTYPE=dos\n", nil}, - }, - expectedError: fmt.Errorf("failed to mount the volume as \"ext3\", it already contains unknown data, probably partitions. Mount error: unknown filesystem type '(null)'"), - }, - { - description: "Test that 'blkid' is called but has some usage or other errors (an exit code of 4 is returned)", - fstype: "xfs", - mountErrs: []error{fmt.Errorf("unknown filesystem type '(null)'"), nil}, - execScripts: []ExecArgs{ - {"fsck", []string{"-a", "/dev/foo"}, "", nil}, - {"blkid", []string{"-p", "-s", "TYPE", "-s", "PTTYPE", "-o", "export", "/dev/foo"}, "", &fakeexec.FakeExitError{Status: 4}}, - {"mkfs.xfs", []string{"/dev/foo"}, "", nil}, - }, - expectedError: fmt.Errorf("exit 4"), - }, - } - - for _, test := range tests { - execCallCount := 0 - execCallback := func(cmd string, args ...string) ([]byte, error) { - if len(test.execScripts) <= execCallCount { - t.Errorf("Unexpected command: %s %v", cmd, args) - return nil, nil - } - script := test.execScripts[execCallCount] - execCallCount++ - if script.command != cmd { - t.Errorf("Unexpected command %s. Expecting %s", cmd, script.command) - } - for j := range args { - if args[j] != script.args[j] { - t.Errorf("Unexpected args %v. Expecting %v", args, script.args) - } - } - return []byte(script.output), script.err - } - - fakeMounter := ErrorMounter{&FakeMounter{}, 0, test.mountErrs} - fakeExec := NewFakeExec(execCallback) - mounter := SafeFormatAndMount{ - Interface: &fakeMounter, - Exec: fakeExec, - } - - device := "/dev/foo" - dest := mntDir - err := mounter.FormatAndMount(device, dest, test.fstype, test.mountOptions) - if test.expectedError == nil { - if err != nil { - t.Errorf("test \"%s\" unexpected non-error: %v", test.description, err) - } - - // Check that something was mounted on the directory - isNotMountPoint, err := fakeMounter.IsLikelyNotMountPoint(dest) - if err != nil || isNotMountPoint { - t.Errorf("test \"%s\" the directory was not mounted", test.description) - } - - //check that the correct device was mounted - mountedDevice, _, err := GetDeviceNameFromMount(fakeMounter.FakeMounter, dest) - if err != nil || mountedDevice != device { - t.Errorf("test \"%s\" the correct device was not mounted", test.description) - } - } else { - if err == nil || test.expectedError.Error() != err.Error() { - t.Errorf("test \"%s\" unexpected error: \n [%v]. \nExpecting [%v]", test.description, err, test.expectedError) - } - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/net/net_test.go b/vendor/k8s.io/kubernetes/pkg/util/net/net_test.go deleted file mode 100644 index c2d2f30f77..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/net/net_test.go +++ /dev/null @@ -1,286 +0,0 @@ -/* -Copyright 2018 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 net - -import ( - "net" - "reflect" - "testing" -) - -func TestIsIPv6String(t *testing.T) { - testCases := []struct { - ip string - expectIPv6 bool - }{ - { - ip: "127.0.0.1", - expectIPv6: false, - }, - { - ip: "192.168.0.0", - expectIPv6: false, - }, - { - ip: "1.2.3.4", - expectIPv6: false, - }, - { - ip: "bad ip", - expectIPv6: false, - }, - { - ip: "::1", - expectIPv6: true, - }, - { - ip: "fd00::600d:f00d", - expectIPv6: true, - }, - { - ip: "2001:db8::5", - expectIPv6: true, - }, - } - for i := range testCases { - isIPv6 := IsIPv6String(testCases[i].ip) - if isIPv6 != testCases[i].expectIPv6 { - t.Errorf("[%d] Expect ipv6 %v, got %v", i+1, testCases[i].expectIPv6, isIPv6) - } - } -} - -func TestIsIPv6(t *testing.T) { - testCases := []struct { - ip net.IP - expectIPv6 bool - }{ - { - ip: net.IPv4zero, - expectIPv6: false, - }, - { - ip: net.IPv4bcast, - expectIPv6: false, - }, - { - ip: net.ParseIP("127.0.0.1"), - expectIPv6: false, - }, - { - ip: net.ParseIP("10.20.40.40"), - expectIPv6: false, - }, - { - ip: net.ParseIP("172.17.3.0"), - expectIPv6: false, - }, - { - ip: nil, - expectIPv6: false, - }, - { - ip: net.IPv6loopback, - expectIPv6: true, - }, - { - ip: net.IPv6zero, - expectIPv6: true, - }, - { - ip: net.ParseIP("fd00::600d:f00d"), - expectIPv6: true, - }, - { - ip: net.ParseIP("2001:db8::5"), - expectIPv6: true, - }, - } - for i := range testCases { - isIPv6 := IsIPv6(testCases[i].ip) - if isIPv6 != testCases[i].expectIPv6 { - t.Errorf("[%d] Expect ipv6 %v, got %v", i+1, testCases[i].expectIPv6, isIPv6) - } - } -} - -func TestIsIPv6CIDR(t *testing.T) { - testCases := []struct { - desc string - cidr string - expectResult bool - }{ - { - desc: "ipv4 CIDR 1", - cidr: "10.0.0.0/8", - expectResult: false, - }, - { - desc: "ipv4 CIDR 2", - cidr: "192.168.0.0/16", - expectResult: false, - }, - { - desc: "ipv6 CIDR 1", - cidr: "::/1", - expectResult: true, - }, - { - desc: "ipv6 CIDR 2", - cidr: "2000::/10", - expectResult: true, - }, - { - desc: "ipv6 CIDR 3", - cidr: "2001:db8::/32", - expectResult: true, - }, - } - - for _, tc := range testCases { - res := IsIPv6CIDR(tc.cidr) - if res != tc.expectResult { - t.Errorf("%v: want IsIPv6CIDR=%v, got %v", tc.desc, tc.expectResult, res) - } - } -} - -func TestFilterIncorrectIPVersion(t *testing.T) { - testCases := []struct { - desc string - isIPv6 bool - ipStrings []string - expectCorrects []string - expectIncorrects []string - }{ - { - desc: "all ipv4 strings in ipv4 mode", - isIPv6: false, - ipStrings: []string{"10.0.0.1", "192.168.0.1", "127.0.0.1"}, - expectCorrects: []string{"10.0.0.1", "192.168.0.1", "127.0.0.1"}, - expectIncorrects: nil, - }, - { - desc: "all ipv6 strings in ipv4 mode", - isIPv6: false, - ipStrings: []string{"::1", "fd00::600d:f00d", "2001:db8::5"}, - expectCorrects: nil, - expectIncorrects: []string{"::1", "fd00::600d:f00d", "2001:db8::5"}, - }, - { - desc: "mixed versions in ipv4 mode", - isIPv6: false, - ipStrings: []string{"10.0.0.1", "192.168.0.1", "127.0.0.1", "::1", "fd00::600d:f00d", "2001:db8::5"}, - expectCorrects: []string{"10.0.0.1", "192.168.0.1", "127.0.0.1"}, - expectIncorrects: []string{"::1", "fd00::600d:f00d", "2001:db8::5"}, - }, - { - desc: "all ipv4 strings in ipv6 mode", - isIPv6: true, - ipStrings: []string{"10.0.0.1", "192.168.0.1", "127.0.0.1"}, - expectCorrects: nil, - expectIncorrects: []string{"10.0.0.1", "192.168.0.1", "127.0.0.1"}, - }, - { - desc: "all ipv6 strings in ipv6 mode", - isIPv6: true, - ipStrings: []string{"::1", "fd00::600d:f00d", "2001:db8::5"}, - expectCorrects: []string{"::1", "fd00::600d:f00d", "2001:db8::5"}, - expectIncorrects: nil, - }, - { - desc: "mixed versions in ipv6 mode", - isIPv6: true, - ipStrings: []string{"10.0.0.1", "192.168.0.1", "127.0.0.1", "::1", "fd00::600d:f00d", "2001:db8::5"}, - expectCorrects: []string{"::1", "fd00::600d:f00d", "2001:db8::5"}, - expectIncorrects: []string{"10.0.0.1", "192.168.0.1", "127.0.0.1"}, - }, - } - - for _, tc := range testCases { - corrects, incorrects := FilterIncorrectIPVersion(tc.ipStrings, tc.isIPv6) - if !reflect.DeepEqual(tc.expectCorrects, corrects) { - t.Errorf("%v: want corrects=%v, got %v", tc.desc, tc.expectCorrects, corrects) - } - if !reflect.DeepEqual(tc.expectIncorrects, incorrects) { - t.Errorf("%v: want incorrects=%v, got %v", tc.desc, tc.expectIncorrects, incorrects) - } - } -} - -func TestFilterIncorrectCIDRVersion(t *testing.T) { - testCases := []struct { - desc string - isIPv6 bool - cidrStrings []string - expectCorrects []string - expectIncorrects []string - }{ - { - desc: "all ipv4 strings in ipv4 mode", - isIPv6: false, - cidrStrings: []string{"0.0.0.0/1", "1.0.0.0/1"}, - expectCorrects: []string{"0.0.0.0/1", "1.0.0.0/1"}, - expectIncorrects: nil, - }, - { - desc: "all ipv6 strings in ipv4 mode", - isIPv6: false, - cidrStrings: []string{"2001:db8::/32", "2001:0db8:0123:4567::/64"}, - expectCorrects: nil, - expectIncorrects: []string{"2001:db8::/32", "2001:0db8:0123:4567::/64"}, - }, - { - desc: "mixed versions in ipv4 mode", - isIPv6: false, - cidrStrings: []string{"0.0.0.0/1", "1.0.0.0/1", "2001:db8::/32", "2001:0db8:0123:4567::/64"}, - expectCorrects: []string{"0.0.0.0/1", "1.0.0.0/1"}, - expectIncorrects: []string{"2001:db8::/32", "2001:0db8:0123:4567::/64"}, - }, - { - desc: "all ipv4 strings in ipv6 mode", - isIPv6: true, - cidrStrings: []string{"0.0.0.0/1", "1.0.0.0/1"}, - expectCorrects: nil, - expectIncorrects: []string{"0.0.0.0/1", "1.0.0.0/1"}, - }, - { - desc: "all ipv6 strings in ipv6 mode", - isIPv6: true, - cidrStrings: []string{"2001:db8::/32", "2001:0db8:0123:4567::/64"}, - expectCorrects: []string{"2001:db8::/32", "2001:0db8:0123:4567::/64"}, - expectIncorrects: nil, - }, - { - desc: "mixed versions in ipv6 mode", - isIPv6: true, - cidrStrings: []string{"0.0.0.0/1", "1.0.0.0/1", "2001:db8::/32", "2001:0db8:0123:4567::/64"}, - expectCorrects: []string{"2001:db8::/32", "2001:0db8:0123:4567::/64"}, - expectIncorrects: []string{"0.0.0.0/1", "1.0.0.0/1"}, - }, - } - - for _, tc := range testCases { - corrects, incorrects := FilterIncorrectCIDRVersion(tc.cidrStrings, tc.isIPv6) - if !reflect.DeepEqual(tc.expectCorrects, corrects) { - t.Errorf("%v: want corrects=%v, got %v", tc.desc, tc.expectCorrects, corrects) - } - if !reflect.DeepEqual(tc.expectIncorrects, incorrects) { - t.Errorf("%v: want incorrects=%v, got %v", tc.desc, tc.expectIncorrects, incorrects) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/net/sets/ipnet_test.go b/vendor/k8s.io/kubernetes/pkg/util/net/sets/ipnet_test.go deleted file mode 100644 index 524bd685bf..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/net/sets/ipnet_test.go +++ /dev/null @@ -1,155 +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 sets - -import ( - "net" - "reflect" - "sort" - "testing" -) - -func parseIPNet(s string) *net.IPNet { - _, net, err := net.ParseCIDR(s) - if err != nil { - panic(err) - } - return net -} - -func TestIPNets(t *testing.T) { - s := IPNet{} - s2 := IPNet{} - if len(s) != 0 { - t.Errorf("Expected len=0: %d", len(s)) - } - a := parseIPNet("1.0.0.0/8") - b := parseIPNet("2.0.0.0/8") - c := parseIPNet("3.0.0.0/8") - d := parseIPNet("4.0.0.0/8") - - s.Insert(a, b) - if len(s) != 2 { - t.Errorf("Expected len=2: %d", len(s)) - } - s.Insert(c) - if s.Has(d) { - t.Errorf("Unexpected contents: %#v", s) - } - if !s.Has(a) { - t.Errorf("Missing contents: %#v", s) - } - s.Delete(a) - if s.Has(a) { - t.Errorf("Unexpected contents: %#v", s) - } - s.Insert(a) - if s.HasAll(a, b, d) { - t.Errorf("Unexpected contents: %#v", s) - } - if !s.HasAll(a, b) { - t.Errorf("Missing contents: %#v", s) - } - s2.Insert(a, b, d) - if s.IsSuperset(s2) { - t.Errorf("Unexpected contents: %#v", s) - } - s2.Delete(d) - if !s.IsSuperset(s2) { - t.Errorf("Missing contents: %#v", s) - } -} - -func TestIPNetSetDeleteMultiples(t *testing.T) { - s := IPNet{} - a := parseIPNet("1.0.0.0/8") - b := parseIPNet("2.0.0.0/8") - c := parseIPNet("3.0.0.0/8") - - s.Insert(a, b, c) - if len(s) != 3 { - t.Errorf("Expected len=3: %d", len(s)) - } - - s.Delete(a, c) - if len(s) != 1 { - t.Errorf("Expected len=1: %d", len(s)) - } - if s.Has(a) { - t.Errorf("Unexpected contents: %#v", s) - } - if s.Has(c) { - t.Errorf("Unexpected contents: %#v", s) - } - if !s.Has(b) { - t.Errorf("Missing contents: %#v", s) - } -} - -func TestNewIPSet(t *testing.T) { - s, err := ParseIPNets("1.0.0.0/8", "2.0.0.0/8", "3.0.0.0/8") - if err != nil { - t.Errorf("error parsing IPNets: %v", err) - } - if len(s) != 3 { - t.Errorf("Expected len=3: %d", len(s)) - } - a := parseIPNet("1.0.0.0/8") - b := parseIPNet("2.0.0.0/8") - c := parseIPNet("3.0.0.0/8") - - if !s.Has(a) || !s.Has(b) || !s.Has(c) { - t.Errorf("Unexpected contents: %#v", s) - } -} - -func TestIPNetSetDifference(t *testing.T) { - l, err := ParseIPNets("1.0.0.0/8", "2.0.0.0/8", "3.0.0.0/8") - if err != nil { - t.Errorf("error parsing IPNets: %v", err) - } - r, err := ParseIPNets("1.0.0.0/8", "2.0.0.0/8", "4.0.0.0/8", "5.0.0.0/8") - if err != nil { - t.Errorf("error parsing IPNets: %v", err) - } - c := l.Difference(r) - d := r.Difference(l) - if len(c) != 1 { - t.Errorf("Expected len=1: %d", len(c)) - } - if !c.Has(parseIPNet("3.0.0.0/8")) { - t.Errorf("Unexpected contents: %#v", c) - } - if len(d) != 2 { - t.Errorf("Expected len=2: %d", len(d)) - } - if !d.Has(parseIPNet("4.0.0.0/8")) || !d.Has(parseIPNet("5.0.0.0/8")) { - t.Errorf("Unexpected contents: %#v", d) - } -} - -func TestIPNetSetList(t *testing.T) { - s, err := ParseIPNets("3.0.0.0/8", "1.0.0.0/8", "2.0.0.0/8") - if err != nil { - t.Errorf("error parsing IPNets: %v", err) - } - l := s.StringSlice() - sort.Strings(l) - if !reflect.DeepEqual(l, []string{"1.0.0.0/8", "2.0.0.0/8", "3.0.0.0/8"}) { - t.Errorf("List gave unexpected result: %#v", l) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/parsers/parsers_test.go b/vendor/k8s.io/kubernetes/pkg/util/parsers/parsers_test.go deleted file mode 100644 index c3e004fbd9..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/parsers/parsers_test.go +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright 2016 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 parsers - -import ( - "testing" -) - -// Based on Docker test case removed in: -// https://github.com/docker/docker/commit/4352da7803d182a6013a5238ce20a7c749db979a -func TestParseImageName(t *testing.T) { - testCases := []struct { - Input string - Repo string - Tag string - Digest string - }{ - {Input: "root", Repo: "docker.io/library/root", Tag: "latest"}, - {Input: "root:tag", Repo: "docker.io/library/root", Tag: "tag"}, - {Input: "root@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", Repo: "docker.io/library/root", Digest: "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, - {Input: "user/repo", Repo: "docker.io/user/repo", Tag: "latest"}, - {Input: "user/repo:tag", Repo: "docker.io/user/repo", Tag: "tag"}, - {Input: "user/repo@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", Repo: "docker.io/user/repo", Digest: "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, - {Input: "url:5000/repo", Repo: "url:5000/repo", Tag: "latest"}, - {Input: "url:5000/repo:tag", Repo: "url:5000/repo", Tag: "tag"}, - {Input: "url:5000/repo@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", Repo: "url:5000/repo", Digest: "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, - } - for _, testCase := range testCases { - repo, tag, digest, err := ParseImageName(testCase.Input) - if err != nil { - t.Errorf("ParseImageName(%s) failed: %v", testCase.Input, err) - } else if repo != testCase.Repo || tag != testCase.Tag || digest != testCase.Digest { - t.Errorf("Expected repo: %q, tag: %q and digest: %q, got %q, %q and %q", testCase.Repo, testCase.Tag, testCase.Digest, - repo, tag, digest) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/pointer/pointer_test.go b/vendor/k8s.io/kubernetes/pkg/util/pointer/pointer_test.go deleted file mode 100644 index 59a6bd5d14..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/pointer/pointer_test.go +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright 2017 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 pointer - -import ( - "testing" -) - -func TestAllPtrFieldsNil(t *testing.T) { - testCases := []struct { - obj interface{} - expected bool - }{ - {struct{}{}, true}, - {struct{ Foo int }{12345}, true}, - {&struct{ Foo int }{12345}, true}, - {struct{ Foo *int }{nil}, true}, - {&struct{ Foo *int }{nil}, true}, - {struct { - Foo int - Bar *int - }{12345, nil}, true}, - {&struct { - Foo int - Bar *int - }{12345, nil}, true}, - {struct { - Foo *int - Bar *int - }{nil, nil}, true}, - {&struct { - Foo *int - Bar *int - }{nil, nil}, true}, - {struct{ Foo *int }{new(int)}, false}, - {&struct{ Foo *int }{new(int)}, false}, - {struct { - Foo *int - Bar *int - }{nil, new(int)}, false}, - {&struct { - Foo *int - Bar *int - }{nil, new(int)}, false}, - {(*struct{})(nil), true}, - } - for i, tc := range testCases { - if AllPtrFieldsNil(tc.obj) != tc.expected { - t.Errorf("case[%d]: expected %t, got %t", i, tc.expected, !tc.expected) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/util/taints/taints_test.go b/vendor/k8s.io/kubernetes/pkg/util/taints/taints_test.go deleted file mode 100644 index 110d78f787..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/util/taints/taints_test.go +++ /dev/null @@ -1,687 +0,0 @@ -/* -Copyright 2016 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 taints - -import ( - "reflect" - "strings" - "testing" - - "k8s.io/api/core/v1" - api "k8s.io/kubernetes/pkg/apis/core" - - "github.com/spf13/pflag" -) - -func TestTaintsVar(t *testing.T) { - cases := []struct { - f string - err bool - t []api.Taint - }{ - { - f: "", - t: []api.Taint(nil), - }, - { - f: "--t=foo=bar:NoSchedule", - t: []api.Taint{{Key: "foo", Value: "bar", Effect: "NoSchedule"}}, - }, - { - f: "--t=foo=bar:NoSchedule,bing=bang:PreferNoSchedule", - t: []api.Taint{ - {Key: "foo", Value: "bar", Effect: api.TaintEffectNoSchedule}, - {Key: "bing", Value: "bang", Effect: api.TaintEffectPreferNoSchedule}, - }, - }, - { - f: "--t=dedicated-for=user1:NoExecute", - t: []api.Taint{{Key: "dedicated-for", Value: "user1", Effect: "NoExecute"}}, - }, - } - - for i, c := range cases { - args := append([]string{"test"}, strings.Fields(c.f)...) - cli := pflag.NewFlagSet("test", pflag.ContinueOnError) - var taints []api.Taint - cli.Var(NewTaintsVar(&taints), "t", "bar") - - err := cli.Parse(args) - if err == nil && c.err { - t.Errorf("[%v] expected error", i) - continue - } - if err != nil && !c.err { - t.Errorf("[%v] unexpected error: %v", i, err) - continue - } - if !reflect.DeepEqual(c.t, taints) { - t.Errorf("[%v] unexpected taints:\n\texpected:\n\t\t%#v\n\tgot:\n\t\t%#v", i, c.t, taints) - } - } - -} - -func TestAddOrUpdateTaint(t *testing.T) { - node := &v1.Node{} - - taint := &v1.Taint{ - Key: "foo", - Value: "bar", - Effect: v1.TaintEffectNoSchedule, - } - - checkResult := func(testCaseName string, newNode *v1.Node, expectedTaint *v1.Taint, result, expectedResult bool, err error) { - if err != nil { - t.Errorf("[%s] should not raise error but got %v", testCaseName, err) - } - if result != expectedResult { - t.Errorf("[%s] should return %t, but got: %t", testCaseName, expectedResult, result) - } - if len(newNode.Spec.Taints) != 1 || !reflect.DeepEqual(newNode.Spec.Taints[0], *expectedTaint) { - t.Errorf("[%s] node should only have one taint: %v, but got: %v", testCaseName, *expectedTaint, newNode.Spec.Taints) - } - } - - // Add a new Taint. - newNode, result, err := AddOrUpdateTaint(node, taint) - checkResult("Add New Taint", newNode, taint, result, true, err) - - // Update a Taint. - taint.Value = "bar_1" - newNode, result, err = AddOrUpdateTaint(node, taint) - checkResult("Update Taint", newNode, taint, result, true, err) - - // Add a duplicate Taint. - node = newNode - newNode, result, err = AddOrUpdateTaint(node, taint) - checkResult("Add Duplicate Taint", newNode, taint, result, false, err) -} - -func TestTaintExists(t *testing.T) { - testingTaints := []v1.Taint{ - { - Key: "foo_1", - Value: "bar_1", - Effect: v1.TaintEffectNoExecute, - }, - { - Key: "foo_2", - Value: "bar_2", - Effect: v1.TaintEffectNoSchedule, - }, - } - - cases := []struct { - name string - taintToFind *v1.Taint - expectedResult bool - }{ - { - name: "taint exists", - taintToFind: &v1.Taint{Key: "foo_1", Value: "bar_1", Effect: v1.TaintEffectNoExecute}, - expectedResult: true, - }, - { - name: "different key", - taintToFind: &v1.Taint{Key: "no_such_key", Value: "bar_1", Effect: v1.TaintEffectNoExecute}, - expectedResult: false, - }, - { - name: "different effect", - taintToFind: &v1.Taint{Key: "foo_1", Value: "bar_1", Effect: v1.TaintEffectNoSchedule}, - expectedResult: false, - }, - } - - for _, c := range cases { - result := TaintExists(testingTaints, c.taintToFind) - - if result != c.expectedResult { - t.Errorf("[%s] unexpected results: %v", c.name, result) - continue - } - } -} - -func TestRemoveTaint(t *testing.T) { - cases := []struct { - name string - node *v1.Node - taintToRemove *v1.Taint - expectedTaints []v1.Taint - expectedResult bool - }{ - { - name: "remove taint unsuccessfully", - node: &v1.Node{ - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - }, - }, - taintToRemove: &v1.Taint{ - Key: "foo_1", - Effect: v1.TaintEffectNoSchedule, - }, - expectedTaints: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedResult: false, - }, - { - name: "remove taint successfully", - node: &v1.Node{ - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - }, - }, - taintToRemove: &v1.Taint{ - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - expectedTaints: []v1.Taint{}, - expectedResult: true, - }, - { - name: "remove taint from node with no taint", - node: &v1.Node{ - Spec: v1.NodeSpec{ - Taints: []v1.Taint{}, - }, - }, - taintToRemove: &v1.Taint{ - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - expectedTaints: []v1.Taint{}, - expectedResult: false, - }, - } - - for _, c := range cases { - newNode, result, err := RemoveTaint(c.node, c.taintToRemove) - if err != nil { - t.Errorf("[%s] should not raise error but got: %v", c.name, err) - } - if result != c.expectedResult { - t.Errorf("[%s] should return %t, but got: %t", c.name, c.expectedResult, result) - } - if !reflect.DeepEqual(newNode.Spec.Taints, c.expectedTaints) { - t.Errorf("[%s] the new node object should have taints %v, but got: %v", c.name, c.expectedTaints, newNode.Spec.Taints) - } - } -} - -func TestDeleteTaint(t *testing.T) { - cases := []struct { - name string - taints []v1.Taint - taintToDelete *v1.Taint - expectedTaints []v1.Taint - expectedResult bool - }{ - { - name: "delete taint with different name", - taints: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - taintToDelete: &v1.Taint{Key: "foo_1", Effect: v1.TaintEffectNoSchedule}, - expectedTaints: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedResult: false, - }, - { - name: "delete taint with different effect", - taints: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - taintToDelete: &v1.Taint{Key: "foo", Effect: v1.TaintEffectNoExecute}, - expectedTaints: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedResult: false, - }, - { - name: "delete taint successfully", - taints: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - taintToDelete: &v1.Taint{Key: "foo", Effect: v1.TaintEffectNoSchedule}, - expectedTaints: []v1.Taint{}, - expectedResult: true, - }, - { - name: "delete taint from empty taint array", - taints: []v1.Taint{}, - taintToDelete: &v1.Taint{Key: "foo", Effect: v1.TaintEffectNoSchedule}, - expectedTaints: []v1.Taint{}, - expectedResult: false, - }, - } - - for _, c := range cases { - taints, result := DeleteTaint(c.taints, c.taintToDelete) - if result != c.expectedResult { - t.Errorf("[%s] should return %t, but got: %t", c.name, c.expectedResult, result) - } - if !reflect.DeepEqual(taints, c.expectedTaints) { - t.Errorf("[%s] the result taints should be %v, but got: %v", c.name, c.expectedTaints, taints) - } - } -} - -func TestDeleteTaintByKey(t *testing.T) { - cases := []struct { - name string - taints []v1.Taint - taintKey string - expectedTaints []v1.Taint - expectedResult bool - }{ - { - name: "delete taint unsuccessfully", - taints: []v1.Taint{ - { - Key: "foo", - Value: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - }, - taintKey: "foo_1", - expectedTaints: []v1.Taint{ - { - Key: "foo", - Value: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedResult: false, - }, - { - name: "delete taint successfully", - taints: []v1.Taint{ - { - Key: "foo", - Value: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - }, - taintKey: "foo", - expectedTaints: []v1.Taint{}, - expectedResult: true, - }, - { - name: "delete taint from empty taint array", - taints: []v1.Taint{}, - taintKey: "foo", - expectedTaints: []v1.Taint{}, - expectedResult: false, - }, - } - - for _, c := range cases { - taints, result := DeleteTaintsByKey(c.taints, c.taintKey) - if result != c.expectedResult { - t.Errorf("[%s] should return %t, but got: %t", c.name, c.expectedResult, result) - } - if !reflect.DeepEqual(c.expectedTaints, taints) { - t.Errorf("[%s] the result taints should be %v, but got: %v", c.name, c.expectedTaints, taints) - } - } -} - -func TestCheckIfTaintsAlreadyExists(t *testing.T) { - oldTaints := []v1.Taint{ - { - Key: "foo_1", - Value: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - { - Key: "foo_2", - Value: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - { - Key: "foo_3", - Value: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - } - - cases := []struct { - name string - taintsToCheck []v1.Taint - expectedResult string - }{ - { - name: "empty array", - taintsToCheck: []v1.Taint{}, - expectedResult: "", - }, - { - name: "no match", - taintsToCheck: []v1.Taint{ - { - Key: "foo_1", - Effect: v1.TaintEffectNoExecute, - }, - }, - expectedResult: "", - }, - { - name: "match one taint", - taintsToCheck: []v1.Taint{ - { - Key: "foo_2", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedResult: "foo_2", - }, - { - name: "match two taints", - taintsToCheck: []v1.Taint{ - { - Key: "foo_2", - Effect: v1.TaintEffectNoSchedule, - }, - { - Key: "foo_3", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedResult: "foo_2,foo_3", - }, - } - - for _, c := range cases { - result := CheckIfTaintsAlreadyExists(oldTaints, c.taintsToCheck) - if result != c.expectedResult { - t.Errorf("[%s] should return '%s', but got: '%s'", c.name, c.expectedResult, result) - } - } -} - -func TestReorganizeTaints(t *testing.T) { - node := &v1.Node{ - Spec: v1.NodeSpec{ - Taints: []v1.Taint{ - { - Key: "foo", - Value: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - }, - }, - } - - cases := []struct { - name string - overwrite bool - taintsToAdd []v1.Taint - taintsToDelete []v1.Taint - expectedTaints []v1.Taint - expectedOperation string - expectedErr bool - }{ - { - name: "no changes with overwrite is true", - overwrite: true, - taintsToAdd: []v1.Taint{}, - taintsToDelete: []v1.Taint{}, - expectedTaints: node.Spec.Taints, - expectedOperation: MODIFIED, - expectedErr: false, - }, - { - name: "no changes with overwrite is false", - overwrite: false, - taintsToAdd: []v1.Taint{}, - taintsToDelete: []v1.Taint{}, - expectedTaints: node.Spec.Taints, - expectedOperation: UNTAINTED, - expectedErr: false, - }, - { - name: "add new taint", - overwrite: false, - taintsToAdd: []v1.Taint{ - { - Key: "foo_1", - Effect: v1.TaintEffectNoExecute, - }, - }, - taintsToDelete: []v1.Taint{}, - expectedTaints: append([]v1.Taint{{Key: "foo_1", Effect: v1.TaintEffectNoExecute}}, node.Spec.Taints...), - expectedOperation: TAINTED, - expectedErr: false, - }, - { - name: "delete taint with effect", - overwrite: false, - taintsToAdd: []v1.Taint{}, - taintsToDelete: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedTaints: []v1.Taint{}, - expectedOperation: UNTAINTED, - expectedErr: false, - }, - { - name: "delete taint with no effect", - overwrite: false, - taintsToAdd: []v1.Taint{}, - taintsToDelete: []v1.Taint{ - { - Key: "foo", - }, - }, - expectedTaints: []v1.Taint{}, - expectedOperation: UNTAINTED, - expectedErr: false, - }, - { - name: "delete non-exist taint", - overwrite: false, - taintsToAdd: []v1.Taint{}, - taintsToDelete: []v1.Taint{ - { - Key: "foo_1", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedTaints: node.Spec.Taints, - expectedOperation: UNTAINTED, - expectedErr: true, - }, - { - name: "add new taint and delete old one", - overwrite: false, - taintsToAdd: []v1.Taint{ - { - Key: "foo_1", - Effect: v1.TaintEffectNoSchedule, - }, - }, - taintsToDelete: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedTaints: []v1.Taint{ - { - Key: "foo_1", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedOperation: MODIFIED, - expectedErr: false, - }, - } - - for _, c := range cases { - operation, taints, err := ReorganizeTaints(node, c.overwrite, c.taintsToAdd, c.taintsToDelete) - if c.expectedErr && err == nil { - t.Errorf("[%s] expect to see an error, but did not get one", c.name) - } else if !c.expectedErr && err != nil { - t.Errorf("[%s] expect not to see an error, but got one: %v", c.name, err) - } - - if !reflect.DeepEqual(c.expectedTaints, taints) { - t.Errorf("[%s] expect to see taint list %#v, but got: %#v", c.name, c.expectedTaints, taints) - } - - if c.expectedOperation != operation { - t.Errorf("[%s] expect to see operation %s, but got: %s", c.name, c.expectedOperation, operation) - } - } -} - -func TestParseTaints(t *testing.T) { - cases := []struct { - name string - spec []string - expectedTaints []v1.Taint - expectedTaintsToRemove []v1.Taint - expectedErr bool - }{ - { - name: "invalid spec format", - spec: []string{"foo=abc"}, - expectedErr: true, - }, - { - name: "invalid spec effect for adding taint", - spec: []string{"foo=abc:invalid_effect"}, - expectedErr: true, - }, - { - name: "invalid spec effect for deleting taint", - spec: []string{"foo:invalid_effect-"}, - expectedErr: true, - }, - { - name: "add new taints", - spec: []string{"foo=abc:NoSchedule", "bar=abc:NoSchedule"}, - expectedTaints: []v1.Taint{ - { - Key: "foo", - Value: "abc", - Effect: v1.TaintEffectNoSchedule, - }, - { - Key: "bar", - Value: "abc", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedErr: false, - }, - { - name: "delete taints", - spec: []string{"foo:NoSchedule-", "bar:NoSchedule-"}, - expectedTaintsToRemove: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - { - Key: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedErr: false, - }, - { - name: "add taints and delete taints", - spec: []string{"foo=abc:NoSchedule", "bar=abc:NoSchedule", "foo:NoSchedule-", "bar:NoSchedule-"}, - expectedTaints: []v1.Taint{ - { - Key: "foo", - Value: "abc", - Effect: v1.TaintEffectNoSchedule, - }, - { - Key: "bar", - Value: "abc", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedTaintsToRemove: []v1.Taint{ - { - Key: "foo", - Effect: v1.TaintEffectNoSchedule, - }, - { - Key: "bar", - Effect: v1.TaintEffectNoSchedule, - }, - }, - expectedErr: false, - }, - } - - for _, c := range cases { - taints, taintsToRemove, err := ParseTaints(c.spec) - if c.expectedErr && err == nil { - t.Errorf("[%s] expected error, but got nothing", c.name) - } - if !c.expectedErr && err != nil { - t.Errorf("[%s] expected no error, but got: %v", c.name, err) - } - if !reflect.DeepEqual(c.expectedTaints, taints) { - t.Errorf("[%s] expected returen taints as %v, but got: %v", c.name, c.expectedTaints, taints) - } - if !reflect.DeepEqual(c.expectedTaintsToRemove, taintsToRemove) { - t.Errorf("[%s] expected return taints to be removed as %v, but got: %v", c.name, c.expectedTaintsToRemove, taintsToRemove) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/metrics_du_test.go b/vendor/k8s.io/kubernetes/pkg/volume/metrics_du_test.go deleted file mode 100644 index 3bee08bf1e..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/volume/metrics_du_test.go +++ /dev/null @@ -1,112 +0,0 @@ -// +build linux - -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package volume_test - -import ( - "io/ioutil" - "os" - "path/filepath" - "testing" - - "golang.org/x/sys/unix" - utiltesting "k8s.io/client-go/util/testing" - . "k8s.io/kubernetes/pkg/volume" - volumetest "k8s.io/kubernetes/pkg/volume/testing" -) - -func getExpectedBlockSize(path string) int64 { - statfs := &unix.Statfs_t{} - err := unix.Statfs(path, statfs) - if err != nil { - return 0 - } - - return int64(statfs.Bsize) -} - -// TestMetricsDuGetCapacity tests that MetricsDu can read disk usage -// for path -func TestMetricsDuGetCapacity(t *testing.T) { - tmpDir, err := utiltesting.MkTmpdir("metrics_du_test") - if err != nil { - t.Fatalf("Can't make a tmp dir: %v", err) - } - defer os.RemoveAll(tmpDir) - metrics := NewMetricsDu(tmpDir) - - expectedEmptyDirUsage, err := volumetest.FindEmptyDirectoryUsageOnTmpfs() - if err != nil { - t.Errorf("Unexpected error finding expected empty directory usage on tmpfs: %v", err) - } - - actual, err := metrics.GetMetrics() - if err != nil { - t.Errorf("Unexpected error when calling GetMetrics %v", err) - } - if e, a := expectedEmptyDirUsage.Value(), actual.Used.Value(); e != a { - t.Errorf("Unexpected value for empty directory; expected %v, got %v", e, a) - } - - // TODO(pwittroc): Figure out a way to test these values for correctness, maybe by formatting and mounting a file - // as a filesystem - if a := actual.Capacity.Value(); a <= 0 { - t.Errorf("Expected Capacity %d to be greater than 0.", a) - } - if a := actual.Available.Value(); a <= 0 { - t.Errorf("Expected Available %d to be greater than 0.", a) - } - - // Write a file and expect Used to increase - ioutil.WriteFile(filepath.Join(tmpDir, "f1"), []byte("Hello World"), os.ModeTemporary) - actual, err = metrics.GetMetrics() - if err != nil { - t.Errorf("Unexpected error when calling GetMetrics %v", err) - } - if e, a := (expectedEmptyDirUsage.Value() + getExpectedBlockSize(filepath.Join(tmpDir, "f1"))), actual.Used.Value(); e != a { - t.Errorf("Unexpected Used for directory with file. Expected %v, got %d.", e, a) - } -} - -// TestMetricsDuRequireInit tests that if MetricsDu is not initialized with a path, GetMetrics -// returns an error -func TestMetricsDuRequirePath(t *testing.T) { - metrics := NewMetricsDu("") - actual, err := metrics.GetMetrics() - expected := &Metrics{} - if !volumetest.MetricsEqualIgnoreTimestamp(actual, expected) { - t.Errorf("Expected empty Metrics from uninitialized MetricsDu, actual %v", *actual) - } - if err == nil { - t.Errorf("Expected error when calling GetMetrics on uninitialized MetricsDu, actual nil") - } -} - -// TestMetricsDuRealDirectory tests that if MetricsDu is initialized to a non-existent path, GetMetrics -// returns an error -func TestMetricsDuRequireRealDirectory(t *testing.T) { - metrics := NewMetricsDu("/not/a/real/directory") - actual, err := metrics.GetMetrics() - expected := &Metrics{} - if !volumetest.MetricsEqualIgnoreTimestamp(actual, expected) { - t.Errorf("Expected empty Metrics from incorrectly initialized MetricsDu, actual %v", *actual) - } - if err == nil { - t.Errorf("Expected error when calling GetMetrics on incorrectly initialized MetricsDu, actual nil") - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/metrics_nil_test.go b/vendor/k8s.io/kubernetes/pkg/volume/metrics_nil_test.go deleted file mode 100644 index e6a25d1ff6..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/volume/metrics_nil_test.go +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package volume - -import ( - "testing" -) - -func TestMetricsNilGetCapacity(t *testing.T) { - metrics := &MetricsNil{} - actual, err := metrics.GetMetrics() - expected := &Metrics{} - if *actual != *expected { - t.Errorf("Expected empty Metrics, actual %v", *actual) - } - if err == nil { - t.Errorf("Expected error when calling GetMetrics, actual nil") - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/metrics_statfs_test.go b/vendor/k8s.io/kubernetes/pkg/volume/metrics_statfs_test.go deleted file mode 100644 index 751991e6fe..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/volume/metrics_statfs_test.go +++ /dev/null @@ -1,67 +0,0 @@ -/* -Copyright 2016 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 volume_test - -import ( - "os" - "testing" - - utiltesting "k8s.io/client-go/util/testing" - . "k8s.io/kubernetes/pkg/volume" - volumetest "k8s.io/kubernetes/pkg/volume/testing" -) - -func TestGetMetricsStatFS(t *testing.T) { - metrics := NewMetricsStatFS("") - actual, err := metrics.GetMetrics() - expected := &Metrics{} - if !volumetest.MetricsEqualIgnoreTimestamp(actual, expected) { - t.Errorf("Expected empty Metrics from uninitialized MetricsStatFS, actual %v", *actual) - } - if err == nil { - t.Errorf("Expected error when calling GetMetrics on uninitialized MetricsStatFS, actual nil") - } - - metrics = NewMetricsStatFS("/not/a/real/directory") - actual, err = metrics.GetMetrics() - if !volumetest.MetricsEqualIgnoreTimestamp(actual, expected) { - t.Errorf("Expected empty Metrics from incorrectly initialized MetricsStatFS, actual %v", *actual) - } - if err == nil { - t.Errorf("Expected error when calling GetMetrics on incorrectly initialized MetricsStatFS, actual nil") - } - - tmpDir, err := utiltesting.MkTmpdir("metric_statfs_test") - if err != nil { - t.Fatalf("Can't make a tmp dir: %v", err) - } - defer os.RemoveAll(tmpDir) - - metrics = NewMetricsStatFS(tmpDir) - actual, err = metrics.GetMetrics() - if err != nil { - t.Errorf("Unexpected error when calling GetMetrics %v", err) - } - - if a := actual.Capacity.Value(); a <= 0 { - t.Errorf("Expected Capacity %d to be greater than 0.", a) - } - if a := actual.Available.Value(); a <= 0 { - t.Errorf("Expected Available %d to be greater than 0.", a) - } - -} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/plugins_test.go b/vendor/k8s.io/kubernetes/pkg/volume/plugins_test.go deleted file mode 100644 index 167a47e6fa..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/volume/plugins_test.go +++ /dev/null @@ -1,167 +0,0 @@ -/* -Copyright 2015 The Kubernetes Authors. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package volume - -import ( - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" -) - -const testPluginName = "kubernetes.io/testPlugin" - -func TestSpecSourceConverters(t *testing.T) { - v := &v1.Volume{ - Name: "foo", - VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}, - } - - converted := NewSpecFromVolume(v) - if converted.Volume.EmptyDir == nil { - t.Errorf("Unexpected nil EmptyDir: %#v", converted) - } - if v.Name != converted.Name() { - t.Errorf("Expected %v but got %v", converted.Name(), v.Name) - } - - pv := &v1.PersistentVolume{ - ObjectMeta: metav1.ObjectMeta{Name: "bar"}, - Spec: v1.PersistentVolumeSpec{ - PersistentVolumeSource: v1.PersistentVolumeSource{AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{}}, - }, - } - - converted = NewSpecFromPersistentVolume(pv, false) - if converted.PersistentVolume.Spec.AWSElasticBlockStore == nil { - t.Errorf("Unexpected nil AWSElasticBlockStore: %#v", converted) - } - if pv.Name != converted.Name() { - t.Errorf("Expected %v but got %v", converted.Name(), pv.Name) - } -} - -type testPlugins struct { -} - -func (plugin *testPlugins) Init(host VolumeHost) error { - return nil -} - -func (plugin *testPlugins) GetPluginName() string { - return testPluginName -} - -func (plugin *testPlugins) GetVolumeName(spec *Spec) (string, error) { - return "", nil -} - -func (plugin *testPlugins) CanSupport(spec *Spec) bool { - return true -} - -func (plugin *testPlugins) RequiresRemount() bool { - return false -} - -func (plugin *testPlugins) SupportsMountOption() bool { - return false -} - -func (plugin *testPlugins) SupportsBulkVolumeVerification() bool { - return false -} - -func (plugin *testPlugins) NewMounter(spec *Spec, podRef *v1.Pod, opts VolumeOptions) (Mounter, error) { - return nil, nil -} - -func (plugin *testPlugins) NewUnmounter(name string, podUID types.UID) (Unmounter, error) { - return nil, nil -} - -func (plugin *testPlugins) ConstructVolumeSpec(volumeName, mountPath string) (*Spec, error) { - return nil, nil -} - -func newTestPlugin() []VolumePlugin { - return []VolumePlugin{&testPlugins{}} -} - -func TestVolumePluginMgrFunc(t *testing.T) { - vpm := VolumePluginMgr{} - var prober DynamicPluginProber = nil // TODO (#51147) inject mock - vpm.InitPlugins(newTestPlugin(), prober, nil) - - plug, err := vpm.FindPluginByName(testPluginName) - if err != nil { - t.Errorf("Can't find the plugin by name") - } - if plug.GetPluginName() != testPluginName { - t.Errorf("Wrong name: %s", plug.GetPluginName()) - } - - plug, err = vpm.FindPluginBySpec(nil) - if err == nil { - t.Errorf("Should return error if volume spec is nil") - } - - volumeSpec := &Spec{} - plug, err = vpm.FindPluginBySpec(volumeSpec) - if err != nil { - t.Errorf("Should return test plugin if volume spec is not nil") - } -} - -func Test_ValidatePodTemplate(t *testing.T) { - pod := &v1.Pod{ - Spec: v1.PodSpec{ - Volumes: []v1.Volume{ - { - Name: "vol", - VolumeSource: v1.VolumeSource{}, - }, - }, - }, - } - var want error - if got := ValidateRecyclerPodTemplate(pod); got != want { - t.Errorf("isPodTemplateValid(%v) returned (%v), want (%v)", pod.String(), got.Error(), want) - } - - // Check that the default recycle pod template is valid - pod = NewPersistentVolumeRecyclerPodTemplate() - want = nil - if got := ValidateRecyclerPodTemplate(pod); got != want { - t.Errorf("isPodTemplateValid(%v) returned (%v), want (%v)", pod.String(), got.Error(), want) - } - - pod = &v1.Pod{ - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - Name: "pv-recycler", - }, - }, - }, - } - // want = an error - if got := ValidateRecyclerPodTemplate(pod); got == nil { - t.Errorf("isPodTemplateValid(%v) returned (%v), want (%v)", pod.String(), got, "Error: pod specification does not contain any volume(s).") - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer.go b/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer.go index b134589287..0613bef6d9 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer.go @@ -230,7 +230,7 @@ func validatePayload(payload map[string]FileProjection) (map[string]FileProjecti return nil, err } - cleanPayload[path.Clean(k)] = content + cleanPayload[filepath.Clean(k)] = content } return cleanPayload, nil diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer_test.go b/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer_test.go deleted file mode 100644 index d80e5ca4cb..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/atomic_writer_test.go +++ /dev/null @@ -1,813 +0,0 @@ -// +build linux - -/* -Copyright 2016 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 util - -import ( - "encoding/base64" - "io/ioutil" - "os" - "path" - "path/filepath" - "reflect" - "strings" - "testing" - - "k8s.io/apimachinery/pkg/util/sets" - utiltesting "k8s.io/client-go/util/testing" -) - -func TestNewAtomicWriter(t *testing.T) { - targetDir, err := utiltesting.MkTmpdir("atomic-write") - if err != nil { - t.Fatalf("unexpected error creating tmp dir: %v", err) - } - defer os.RemoveAll(targetDir) - - _, err = NewAtomicWriter(targetDir, "-test-") - if err != nil { - t.Fatalf("unexpected error creating writer for existing target dir: %v", err) - } - - nonExistentDir, err := utiltesting.MkTmpdir("atomic-write") - if err != nil { - t.Fatalf("unexpected error creating tmp dir: %v", err) - } - err = os.Remove(nonExistentDir) - if err != nil { - t.Fatalf("unexpected error ensuring dir %v does not exist: %v", nonExistentDir, err) - } - - _, err = NewAtomicWriter(nonExistentDir, "-test-") - if err == nil { - t.Fatalf("unexpected success creating writer for nonexistent target dir: %v", err) - } -} - -func TestValidatePath(t *testing.T) { - maxPath := strings.Repeat("a", maxPathLength+1) - maxFile := strings.Repeat("a", maxFileNameLength+1) - - cases := []struct { - name string - path string - valid bool - }{ - { - name: "valid 1", - path: "i/am/well/behaved.txt", - valid: true, - }, - { - name: "valid 2", - path: "keepyourheaddownandfollowtherules.txt", - valid: true, - }, - { - name: "max path length", - path: maxPath, - valid: false, - }, - { - name: "max file length", - path: maxFile, - valid: false, - }, - { - name: "absolute failure", - path: "/dev/null", - valid: false, - }, - { - name: "reserved path", - path: "..sneaky.txt", - valid: false, - }, - { - name: "contains doubledot 1", - path: "hello/there/../../../../../../etc/passwd", - valid: false, - }, - { - name: "contains doubledot 2", - path: "hello/../etc/somethingbad", - valid: false, - }, - { - name: "empty", - path: "", - valid: false, - }, - } - - for _, tc := range cases { - err := validatePath(tc.path) - if tc.valid && err != nil { - t.Errorf("%v: unexpected failure: %v", tc.name, err) - continue - } - - if !tc.valid && err == nil { - t.Errorf("%v: unexpected success", tc.name) - } - } -} - -func TestPathsToRemove(t *testing.T) { - cases := []struct { - name string - payload1 map[string]FileProjection - payload2 map[string]FileProjection - expected sets.String - }{ - { - name: "simple", - payload1: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - "bar.txt": {Mode: 0644, Data: []byte("bar")}, - }, - payload2: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - }, - expected: sets.NewString("bar.txt"), - }, - { - name: "simple 2", - payload1: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - "zip/bar.txt": {Mode: 0644, Data: []byte("zip/b}ar")}, - }, - payload2: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - }, - expected: sets.NewString("zip/bar.txt", "zip"), - }, - { - name: "subdirs 1", - payload1: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - "zip/zap/bar.txt": {Mode: 0644, Data: []byte("zip/bar")}, - }, - payload2: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - }, - expected: sets.NewString("zip/zap/bar.txt", "zip", "zip/zap"), - }, - { - name: "subdirs 2", - payload1: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - "zip/1/2/3/4/bar.txt": {Mode: 0644, Data: []byte("zip/b}ar")}, - }, - payload2: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - }, - expected: sets.NewString("zip/1/2/3/4/bar.txt", "zip", "zip/1", "zip/1/2", "zip/1/2/3", "zip/1/2/3/4"), - }, - { - name: "subdirs 3", - payload1: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - "zip/1/2/3/4/bar.txt": {Mode: 0644, Data: []byte("zip/b}ar")}, - "zap/a/b/c/bar.txt": {Mode: 0644, Data: []byte("zap/bar")}, - }, - payload2: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - }, - expected: sets.NewString("zip/1/2/3/4/bar.txt", "zip", "zip/1", "zip/1/2", "zip/1/2/3", "zip/1/2/3/4", "zap", "zap/a", "zap/a/b", "zap/a/b/c", "zap/a/b/c/bar.txt"), - }, - { - name: "subdirs 4", - payload1: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - "zap/1/2/3/4/bar.txt": {Mode: 0644, Data: []byte("zip/bar")}, - "zap/1/2/c/bar.txt": {Mode: 0644, Data: []byte("zap/bar")}, - "zap/1/2/magic.txt": {Mode: 0644, Data: []byte("indigo")}, - }, - payload2: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - "zap/1/2/magic.txt": {Mode: 0644, Data: []byte("indigo")}, - }, - expected: sets.NewString("zap/1/2/3/4/bar.txt", "zap/1/2/3", "zap/1/2/3/4", "zap/1/2/3/4/bar.txt", "zap/1/2/c", "zap/1/2/c/bar.txt"), - }, - { - name: "subdirs 5", - payload1: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - "zap/1/2/3/4/bar.txt": {Mode: 0644, Data: []byte("zip/bar")}, - "zap/1/2/c/bar.txt": {Mode: 0644, Data: []byte("zap/bar")}, - }, - payload2: map[string]FileProjection{ - "foo.txt": {Mode: 0644, Data: []byte("foo")}, - "zap/1/2/magic.txt": {Mode: 0644, Data: []byte("indigo")}, - }, - expected: sets.NewString("zap/1/2/3/4/bar.txt", "zap/1/2/3", "zap/1/2/3/4", "zap/1/2/3/4/bar.txt", "zap/1/2/c", "zap/1/2/c/bar.txt"), - }, - } - - for _, tc := range cases { - targetDir, err := utiltesting.MkTmpdir("atomic-write") - if err != nil { - t.Errorf("%v: unexpected error creating tmp dir: %v", tc.name, err) - continue - } - defer os.RemoveAll(targetDir) - - writer := &AtomicWriter{targetDir: targetDir, logContext: "-test-"} - err = writer.Write(tc.payload1) - if err != nil { - t.Errorf("%v: unexpected error writing: %v", tc.name, err) - continue - } - - dataDirPath := path.Join(targetDir, dataDirName) - oldTsDir, err := os.Readlink(dataDirPath) - if err != nil && os.IsNotExist(err) { - t.Errorf("Data symlink does not exist: %v", dataDirPath) - continue - } else if err != nil { - t.Errorf("Unable to read symlink %v: %v", dataDirPath, err) - continue - } - - actual, err := writer.pathsToRemove(tc.payload2, path.Join(targetDir, oldTsDir)) - if err != nil { - t.Errorf("%v: unexpected error determining paths to remove: %v", tc.name, err) - continue - } - - if e, a := tc.expected, actual; !e.Equal(a) { - t.Errorf("%v: unexpected paths to remove:\nexpected: %v\n got: %v", tc.name, e, a) - } - } -} - -func TestWriteOnce(t *testing.T) { - // $1 if you can tell me what this binary is - encodedMysteryBinary := `f0VMRgIBAQAAAAAAAAAAAAIAPgABAAAAeABAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAEAAOAAB -AAAAAAAAAAEAAAAFAAAAAAAAAAAAAAAAAEAAAAAAAAAAQAAAAAAAfQAAAAAAAAB9AAAAAAAAAAAA -IAAAAAAAsDyZDwU=` - - mysteryBinaryBytes := make([]byte, base64.StdEncoding.DecodedLen(len(encodedMysteryBinary))) - numBytes, err := base64.StdEncoding.Decode(mysteryBinaryBytes, []byte(encodedMysteryBinary)) - if err != nil { - t.Fatalf("Unexpected error decoding binary payload: %v", err) - } - - if numBytes != 125 { - t.Fatalf("Unexpected decoded binary size: expected 125, got %v", numBytes) - } - - cases := []struct { - name string - payload map[string]FileProjection - success bool - }{ - { - name: "invalid payload 1", - payload: map[string]FileProjection{ - "foo": {Mode: 0644, Data: []byte("foo")}, - "..bar": {Mode: 0644, Data: []byte("bar")}, - "binary.bin": {Mode: 0644, Data: mysteryBinaryBytes}, - }, - success: false, - }, - { - name: "invalid payload 2", - payload: map[string]FileProjection{ - "foo/../bar": {Mode: 0644, Data: []byte("foo")}, - }, - success: false, - }, - { - name: "basic 1", - payload: map[string]FileProjection{ - "foo": {Mode: 0644, Data: []byte("foo")}, - "bar": {Mode: 0644, Data: []byte("bar")}, - }, - success: true, - }, - { - name: "basic 2", - payload: map[string]FileProjection{ - "binary.bin": {Mode: 0644, Data: mysteryBinaryBytes}, - ".binary.bin": {Mode: 0644, Data: mysteryBinaryBytes}, - }, - success: true, - }, - { - name: "basic mode 1", - payload: map[string]FileProjection{ - "foo": {Mode: 0777, Data: []byte("foo")}, - "bar": {Mode: 0400, Data: []byte("bar")}, - }, - success: true, - }, - { - name: "dotfiles", - payload: map[string]FileProjection{ - "foo": {Mode: 0644, Data: []byte("foo")}, - "bar": {Mode: 0644, Data: []byte("bar")}, - ".dotfile": {Mode: 0644, Data: []byte("dotfile")}, - ".dotfile.file": {Mode: 0644, Data: []byte("dotfile.file")}, - }, - success: true, - }, - { - name: "dotfiles mode", - payload: map[string]FileProjection{ - "foo": {Mode: 0407, Data: []byte("foo")}, - "bar": {Mode: 0440, Data: []byte("bar")}, - ".dotfile": {Mode: 0777, Data: []byte("dotfile")}, - ".dotfile.file": {Mode: 0666, Data: []byte("dotfile.file")}, - }, - success: true, - }, - { - name: "subdirectories 1", - payload: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt")}, - }, - success: true, - }, - { - name: "subdirectories mode 1", - payload: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0400, Data: []byte("foo/bar")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt")}, - }, - success: true, - }, - { - name: "subdirectories 2", - payload: map[string]FileProjection{ - "foo//bar.txt": {Mode: 0644, Data: []byte("foo//bar")}, - "bar///bar/zab.txt": {Mode: 0644, Data: []byte("bar/../bar/zab.txt")}, - }, - success: true, - }, - { - name: "subdirectories 3", - payload: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt")}, - "foo/blaz/bar.txt": {Mode: 0644, Data: []byte("foo/blaz/bar")}, - "bar/zib/zab.txt": {Mode: 0644, Data: []byte("bar/zib/zab.txt")}, - }, - success: true, - }, - { - name: "kitchen sink", - payload: map[string]FileProjection{ - "foo.log": {Mode: 0644, Data: []byte("foo")}, - "bar.zap": {Mode: 0644, Data: []byte("bar")}, - ".dotfile": {Mode: 0644, Data: []byte("dotfile")}, - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt")}, - "foo/blaz/bar.txt": {Mode: 0644, Data: []byte("foo/blaz/bar")}, - "bar/zib/zab.txt": {Mode: 0400, Data: []byte("bar/zib/zab.txt")}, - "1/2/3/4/5/6/7/8/9/10/.dotfile.lib": {Mode: 0777, Data: []byte("1-2-3-dotfile")}, - }, - success: true, - }, - } - - for _, tc := range cases { - targetDir, err := utiltesting.MkTmpdir("atomic-write") - if err != nil { - t.Errorf("%v: unexpected error creating tmp dir: %v", tc.name, err) - continue - } - defer os.RemoveAll(targetDir) - - writer := &AtomicWriter{targetDir: targetDir, logContext: "-test-"} - err = writer.Write(tc.payload) - if err != nil && tc.success { - t.Errorf("%v: unexpected error writing payload: %v", tc.name, err) - continue - } else if err == nil && !tc.success { - t.Errorf("%v: unexpected success", tc.name) - continue - } else if err != nil { - continue - } - - checkVolumeContents(targetDir, tc.name, tc.payload, t) - } -} - -func TestUpdate(t *testing.T) { - cases := []struct { - name string - first map[string]FileProjection - next map[string]FileProjection - shouldWrite bool - }{ - { - name: "update", - first: map[string]FileProjection{ - "foo": {Mode: 0644, Data: []byte("foo")}, - "bar": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{ - "foo": {Mode: 0644, Data: []byte("foo2")}, - "bar": {Mode: 0640, Data: []byte("bar2")}, - }, - shouldWrite: true, - }, - { - name: "no update", - first: map[string]FileProjection{ - "foo": {Mode: 0644, Data: []byte("foo")}, - "bar": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{ - "foo": {Mode: 0644, Data: []byte("foo")}, - "bar": {Mode: 0644, Data: []byte("bar")}, - }, - shouldWrite: false, - }, - { - name: "no update 2", - first: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar")}, - }, - shouldWrite: false, - }, - { - name: "add 1", - first: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar")}, - "blu/zip.txt": {Mode: 0644, Data: []byte("zip")}, - }, - shouldWrite: true, - }, - { - name: "add 2", - first: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar")}, - "blu/two/2/3/4/5/zip.txt": {Mode: 0644, Data: []byte("zip")}, - }, - shouldWrite: true, - }, - { - name: "add 3", - first: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar")}, - "bar/2/3/4/5/zip.txt": {Mode: 0644, Data: []byte("zip")}, - }, - shouldWrite: true, - }, - { - name: "delete 1", - first: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - }, - shouldWrite: true, - }, - { - name: "delete 2", - first: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/1/2/3/zab.txt": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - }, - shouldWrite: true, - }, - { - name: "delete 3", - first: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/1/2/sip.txt": {Mode: 0644, Data: []byte("sip")}, - "bar/1/2/3/zab.txt": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/1/2/sip.txt": {Mode: 0644, Data: []byte("sip")}, - }, - shouldWrite: true, - }, - { - name: "delete 4", - first: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/1/2/sip.txt": {Mode: 0644, Data: []byte("sip")}, - "bar/1/2/3/4/5/6zab.txt": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/1/2/sip.txt": {Mode: 0644, Data: []byte("sip")}, - }, - shouldWrite: true, - }, - { - name: "delete all", - first: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - "bar/1/2/sip.txt": {Mode: 0644, Data: []byte("sip")}, - "bar/1/2/3/4/5/6zab.txt": {Mode: 0644, Data: []byte("bar")}, - }, - next: map[string]FileProjection{}, - shouldWrite: true, - }, - { - name: "add and delete 1", - first: map[string]FileProjection{ - "foo/bar.txt": {Mode: 0644, Data: []byte("foo")}, - }, - next: map[string]FileProjection{ - "bar/baz.txt": {Mode: 0644, Data: []byte("baz")}, - }, - shouldWrite: true, - }, - } - - for _, tc := range cases { - targetDir, err := utiltesting.MkTmpdir("atomic-write") - if err != nil { - t.Errorf("%v: unexpected error creating tmp dir: %v", tc.name, err) - continue - } - defer os.RemoveAll(targetDir) - - writer := &AtomicWriter{targetDir: targetDir, logContext: "-test-"} - - err = writer.Write(tc.first) - if err != nil { - t.Errorf("%v: unexpected error writing: %v", tc.name, err) - continue - } - - checkVolumeContents(targetDir, tc.name, tc.first, t) - if !tc.shouldWrite { - continue - } - - err = writer.Write(tc.next) - if err != nil { - if tc.shouldWrite { - t.Errorf("%v: unexpected error writing: %v", tc.name, err) - continue - } - } else if !tc.shouldWrite { - t.Errorf("%v: unexpected success", tc.name) - continue - } - - checkVolumeContents(targetDir, tc.name, tc.next, t) - } -} - -func TestMultipleUpdates(t *testing.T) { - cases := []struct { - name string - payloads []map[string]FileProjection - }{ - { - name: "update 1", - payloads: []map[string]FileProjection{ - { - "foo": {Mode: 0644, Data: []byte("foo")}, - "bar": {Mode: 0644, Data: []byte("bar")}, - }, - { - "foo": {Mode: 0400, Data: []byte("foo2")}, - "bar": {Mode: 0400, Data: []byte("bar2")}, - }, - { - "foo": {Mode: 0600, Data: []byte("foo3")}, - "bar": {Mode: 0600, Data: []byte("bar3")}, - }, - }, - }, - { - name: "update 2", - payloads: []map[string]FileProjection{ - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt")}, - }, - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar2")}, - "bar/zab.txt": {Mode: 0400, Data: []byte("bar/zab.txt2")}, - }, - }, - }, - { - name: "clear sentinel", - payloads: []map[string]FileProjection{ - { - "foo": {Mode: 0644, Data: []byte("foo")}, - "bar": {Mode: 0644, Data: []byte("bar")}, - }, - { - "foo": {Mode: 0644, Data: []byte("foo2")}, - "bar": {Mode: 0644, Data: []byte("bar2")}, - }, - { - "foo": {Mode: 0644, Data: []byte("foo3")}, - "bar": {Mode: 0644, Data: []byte("bar3")}, - }, - { - "foo": {Mode: 0644, Data: []byte("foo4")}, - "bar": {Mode: 0644, Data: []byte("bar4")}, - }, - }, - }, - { - name: "subdirectories 2", - payloads: []map[string]FileProjection{ - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt")}, - "foo/blaz/bar.txt": {Mode: 0644, Data: []byte("foo/blaz/bar")}, - "bar/zib/zab.txt": {Mode: 0644, Data: []byte("bar/zib/zab.txt")}, - }, - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar2")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt2")}, - "foo/blaz/bar.txt": {Mode: 0644, Data: []byte("foo/blaz/bar2")}, - "bar/zib/zab.txt": {Mode: 0644, Data: []byte("bar/zib/zab.txt2")}, - }, - }, - }, - { - name: "add 1", - payloads: []map[string]FileProjection{ - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar")}, - "bar//zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt")}, - "foo/blaz/bar.txt": {Mode: 0644, Data: []byte("foo/blaz/bar")}, - "bar/zib////zib/zab.txt": {Mode: 0644, Data: []byte("bar/zib/zab.txt")}, - }, - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar2")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt2")}, - "foo/blaz/bar.txt": {Mode: 0644, Data: []byte("foo/blaz/bar2")}, - "bar/zib/zab.txt": {Mode: 0644, Data: []byte("bar/zib/zab.txt2")}, - "add/new/keys.txt": {Mode: 0644, Data: []byte("addNewKeys")}, - }, - }, - }, - { - name: "add 2", - payloads: []map[string]FileProjection{ - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar2")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt2")}, - "foo/blaz/bar.txt": {Mode: 0644, Data: []byte("foo/blaz/bar2")}, - "bar/zib/zab.txt": {Mode: 0644, Data: []byte("bar/zib/zab.txt2")}, - "add/new/keys.txt": {Mode: 0644, Data: []byte("addNewKeys")}, - }, - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar2")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt2")}, - "foo/blaz/bar.txt": {Mode: 0644, Data: []byte("foo/blaz/bar2")}, - "bar/zib/zab.txt": {Mode: 0644, Data: []byte("bar/zib/zab.txt2")}, - "add/new/keys.txt": {Mode: 0644, Data: []byte("addNewKeys")}, - "add/new/keys2.txt": {Mode: 0644, Data: []byte("addNewKeys2")}, - "add/new/keys3.txt": {Mode: 0644, Data: []byte("addNewKeys3")}, - }, - }, - }, - { - name: "remove 1", - payloads: []map[string]FileProjection{ - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar")}, - "bar//zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt")}, - "foo/blaz/bar.txt": {Mode: 0644, Data: []byte("foo/blaz/bar")}, - "zip/zap/zup/fop.txt": {Mode: 0644, Data: []byte("zip/zap/zup/fop.txt")}, - }, - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar2")}, - "bar/zab.txt": {Mode: 0644, Data: []byte("bar/zab.txt2")}, - }, - { - "foo/bar.txt": {Mode: 0644, Data: []byte("foo/bar")}, - }, - }, - }, - } - - for _, tc := range cases { - targetDir, err := utiltesting.MkTmpdir("atomic-write") - if err != nil { - t.Errorf("%v: unexpected error creating tmp dir: %v", tc.name, err) - continue - } - defer os.RemoveAll(targetDir) - - writer := &AtomicWriter{targetDir: targetDir, logContext: "-test-"} - - for _, payload := range tc.payloads { - writer.Write(payload) - - checkVolumeContents(targetDir, tc.name, payload, t) - } - } -} - -func checkVolumeContents(targetDir, tcName string, payload map[string]FileProjection, t *testing.T) { - dataDirPath := path.Join(targetDir, dataDirName) - // use filepath.Walk to reconstruct the payload, then deep equal - observedPayload := make(map[string]FileProjection) - visitor := func(path string, info os.FileInfo, err error) error { - if info.IsDir() { - return nil - } - - relativePath := strings.TrimPrefix(path, dataDirPath) - relativePath = strings.TrimPrefix(relativePath, "/") - if strings.HasPrefix(relativePath, "..") { - return nil - } - - content, err := ioutil.ReadFile(path) - if err != nil { - return err - } - fileInfo, err := os.Stat(path) - if err != nil { - return err - } - mode := int32(fileInfo.Mode()) - - observedPayload[relativePath] = FileProjection{Data: content, Mode: mode} - - return nil - } - - d, err := ioutil.ReadDir(targetDir) - if err != nil { - t.Errorf("Unable to read dir %v: %v", targetDir, err) - return - } - for _, info := range d { - if strings.HasPrefix(info.Name(), "..") { - continue - } - if info.Mode()&os.ModeSymlink != 0 { - p := path.Join(targetDir, info.Name()) - actual, err := os.Readlink(p) - if err != nil { - t.Errorf("Unable to read symlink %v: %v", p, err) - continue - } - if err := filepath.Walk(path.Join(targetDir, actual), visitor); err != nil { - t.Errorf("%v: unexpected error walking directory: %v", tcName, err) - } - } - } - - cleanPathPayload := make(map[string]FileProjection, len(payload)) - for k, v := range payload { - cleanPathPayload[path.Clean(k)] = v - } - - if !reflect.DeepEqual(cleanPathPayload, observedPayload) { - t.Errorf("%v: payload and observed payload do not match.", tcName) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_linux_test.go b/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_linux_test.go deleted file mode 100644 index 6ee7891a80..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/device_util_linux_test.go +++ /dev/null @@ -1,160 +0,0 @@ -// +build linux - -/* -Copyright 2016 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 util - -import ( - "errors" - "os" - "reflect" - "testing" - "time" -) - -type mockOsIOHandler struct{} - -func (handler *mockOsIOHandler) ReadDir(dirname string) ([]os.FileInfo, error) { - switch dirname { - case "/sys/block/dm-1/slaves": - f1 := &fakeFileInfo{ - name: "sda", - } - f2 := &fakeFileInfo{ - name: "sdb", - } - return []os.FileInfo{f1, f2}, nil - case "/sys/block/": - f1 := &fakeFileInfo{ - name: "sda", - } - f2 := &fakeFileInfo{ - name: "dm-1", - } - return []os.FileInfo{f1, f2}, nil - } - return nil, nil -} - -func (handler *mockOsIOHandler) Lstat(name string) (os.FileInfo, error) { - links := map[string]string{ - "/sys/block/dm-1/slaves/sda": "sda", - "/dev/sda": "sda", - } - if dev, ok := links[name]; ok { - return &fakeFileInfo{name: dev}, nil - } - return nil, errors.New("Not Implemented for Mock") -} - -func (handler *mockOsIOHandler) EvalSymlinks(path string) (string, error) { - links := map[string]string{ - "/returns/a/dev": "/dev/sde", - "/returns/non/dev": "/sys/block", - "/dev/disk/by-path/127.0.0.1:3260-eui.02004567A425678D-lun-0": "/dev/sda", - "/dev/disk/by-path/127.0.0.3:3260-eui.03004567A425678D-lun-0": "/dev/sdb", - "/dev/dm-2": "/dev/dm-2", - "/dev/dm-3": "/dev/dm-3", - "/dev/sdc": "/dev/sdc", - "/dev/sde": "/dev/sde", - } - return links[path], nil -} - -func (handler *mockOsIOHandler) WriteFile(filename string, data []byte, perm os.FileMode) error { - return errors.New("Not Implemented for Mock") -} - -type fakeFileInfo struct { - name string -} - -func (fi *fakeFileInfo) Name() string { - return fi.name -} - -func (fi *fakeFileInfo) Size() int64 { - return 0 -} - -func (fi *fakeFileInfo) Mode() os.FileMode { - return 777 -} - -func (fi *fakeFileInfo) ModTime() time.Time { - return time.Now() -} -func (fi *fakeFileInfo) IsDir() bool { - return false -} - -func (fi *fakeFileInfo) Sys() interface{} { - return nil -} - -func TestFindMultipathDeviceForDevice(t *testing.T) { - mockDeviceUtil := NewDeviceHandler(&mockOsIOHandler{}) - dev := mockDeviceUtil.FindMultipathDeviceForDevice("/dev/disk/by-path/127.0.0.1:3260-eui.02004567A425678D-lun-0") - if dev != "/dev/dm-1" { - t.Fatalf("mpio device not found dm-1 expected got [%s]", dev) - } - dev = mockDeviceUtil.FindMultipathDeviceForDevice("/dev/disk/by-path/empty") - if dev != "" { - t.Fatalf("mpio device not found '' expected got [%s]", dev) - } -} - -func TestFindDeviceForPath(t *testing.T) { - io := &mockOsIOHandler{} - - disk, err := findDeviceForPath("/dev/sde", io) - if err != nil { - t.Fatalf("error finding device for path /dev/sde:%v", err) - } - if disk != "sde" { - t.Fatalf("disk [%s] didn't match expected sde", disk) - } - disk, err = findDeviceForPath("/returns/a/dev", io) - if err != nil { - t.Fatalf("error finding device for path /returns/a/dev:%v", err) - } - if disk != "sde" { - t.Fatalf("disk [%s] didn't match expected sde", disk) - } - _, err = findDeviceForPath("/returns/non/dev", io) - if err == nil { - t.Fatalf("link is to incorrect dev") - } - - _, err = findDeviceForPath("/path/doesnt/exist", &osIOHandler{}) - if err == nil { - t.Fatalf("path shouldn't exist but still doesn't give an error") - } - -} - -func TestFindSlaveDevicesOnMultipath(t *testing.T) { - mockDeviceUtil := NewDeviceHandler(&mockOsIOHandler{}) - devices := mockDeviceUtil.FindSlaveDevicesOnMultipath("/dev/dm-1") - if !reflect.DeepEqual(devices, []string{"/dev/sda", "/dev/sdb"}) { - t.Fatalf("failed to find devices managed by mpio device. /dev/sda, /dev/sdb expected got [%s]", devices) - } - dev := mockDeviceUtil.FindSlaveDevicesOnMultipath("/dev/sdc") - if len(dev) != 0 { - t.Fatalf("mpio device not found '' expected got [%s]", dev) - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/nested_volumes_test.go b/vendor/k8s.io/kubernetes/pkg/volume/util/nested_volumes_test.go deleted file mode 100644 index 936c09cdae..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/nested_volumes_test.go +++ /dev/null @@ -1,233 +0,0 @@ -/* -Copyright 2018 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 util - -import ( - "io/ioutil" - "os" - "path" - "testing" - - "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "k8s.io/apimachinery/pkg/util/sets" -) - -type testCases struct { - name string - err bool - expected sets.String - volname string - pod v1.Pod -} - -func TestGetNestedMountpoints(t *testing.T) { - var ( - testNamespace = "test_namespace" - testPodUID = types.UID("test_pod_uid") - ) - - tc := []testCases{ - { - name: "Simple Pod", - err: false, - expected: sets.NewString(), - volname: "vol1", - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: testNamespace, - UID: testPodUID, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - VolumeMounts: []v1.VolumeMount{ - {MountPath: "/dir", Name: "vol1"}, - }, - }, - }, - }, - }, - }, - { - name: "Simple Nested Pod", - err: false, - expected: sets.NewString("nested"), - volname: "vol1", - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: testNamespace, - UID: testPodUID, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - VolumeMounts: []v1.VolumeMount{ - {MountPath: "/dir", Name: "vol1"}, - {MountPath: "/dir/nested", Name: "vol2"}, - }, - }, - }, - }, - }, - }, - { - name: "Unsorted Nested Pod", - err: false, - expected: sets.NewString("nested", "nested2"), - volname: "vol1", - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: testNamespace, - UID: testPodUID, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - VolumeMounts: []v1.VolumeMount{ - {MountPath: "/dir/nested/double", Name: "vol3"}, - {MountPath: "/ignore", Name: "vol4"}, - {MountPath: "/dir/nested", Name: "vol2"}, - {MountPath: "/ignore2", Name: "vol5"}, - {MountPath: "/dir", Name: "vol1"}, - {MountPath: "/dir/nested2", Name: "vol3"}, - }, - }, - }, - }, - }, - }, - { - name: "Multiple vol1 mounts Pod", - err: false, - expected: sets.NewString("nested", "nested2"), - volname: "vol1", - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: testNamespace, - UID: testPodUID, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - VolumeMounts: []v1.VolumeMount{ - {MountPath: "/dir", Name: "vol1"}, - {MountPath: "/dir/nested", Name: "vol2"}, - {MountPath: "/ignore", Name: "vol4"}, - {MountPath: "/other", Name: "vol1"}, - {MountPath: "/other/nested2", Name: "vol3"}, - }, - }, - }, - }, - }, - }, - { - name: "Big Pod", - err: false, - volname: "vol1", - expected: sets.NewString("sub1/sub2/sub3", "sub1/sub2/sub4", "sub1/sub2/sub6", "sub"), - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: testNamespace, - UID: testPodUID, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - VolumeMounts: []v1.VolumeMount{ - {MountPath: "/mnt", Name: "vol1"}, - {MountPath: "/ignore", Name: "vol2"}, - {MountPath: "/mnt/sub1/sub2/sub3", Name: "vol3"}, - {MountPath: "/mnt/sub1/sub2/sub4", Name: "vol4"}, - {MountPath: "/mnt/sub1/sub2/sub4/skip", Name: "vol5"}, - {MountPath: "/mnt/sub1/sub2/sub4/skip2", Name: "vol5a"}, - {MountPath: "/mnt/sub1/sub2/sub6", Name: "vol6"}, - {MountPath: "/mnt7", Name: "vol7"}, - }, - }, - }, - InitContainers: []v1.Container{ - { - VolumeMounts: []v1.VolumeMount{ - {MountPath: "/mnt/dir", Name: "vol1"}, - {MountPath: "/mnt/dir_ignore", Name: "vol8"}, - {MountPath: "/ignore", Name: "vol9"}, - {MountPath: "/mnt/dir/sub", Name: "vol11"}, - }, - }, - }, - }, - }, - }, - { - name: "Naughty Pod", - err: true, - expected: nil, - volname: "vol1", - pod: v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: testNamespace, - UID: testPodUID, - }, - Spec: v1.PodSpec{ - Containers: []v1.Container{ - { - VolumeMounts: []v1.VolumeMount{ - {MountPath: "foo/../../dir", Name: "vol1"}, - {MountPath: "foo/../../dir/skip", Name: "vol10"}, - }, - }, - }, - }, - }, - }, - } - for _, test := range tc { - dir, err := ioutil.TempDir("", "TestMakeNestedMountpoints.") - if err != nil { - t.Errorf("Unexpected error trying to create temp directory: %v", err) - return - } - defer os.RemoveAll(dir) - - rootdir := path.Join(dir, "vol") - err = os.Mkdir(rootdir, 0755) - if err != nil { - t.Errorf("Unexpected error trying to create temp root directory: %v", err) - return - } - - dirs, err := getNestedMountpoints(test.volname, rootdir, test.pod) - if test.err { - if err == nil { - t.Errorf("%v: expected error, got nil", test.name) - } - continue - } else { - if err != nil { - t.Errorf("%v: expected no error, got %v", test.name, err) - continue - } - } - actual := sets.NewString(dirs...) - if !test.expected.Equal(actual) { - t.Errorf("%v: unexpected nested directories created:\nexpected: %v\n got: %v", test.name, test.expected, actual) - } - } -} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/recyclerclient/recycler_client_test.go b/vendor/k8s.io/kubernetes/pkg/volume/util/recyclerclient/recycler_client_test.go deleted file mode 100644 index 64e04fbcc2..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/recyclerclient/recycler_client_test.go +++ /dev/null @@ -1,235 +0,0 @@ -/* -Copyright 2018 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 recyclerclient - -import ( - "fmt" - "testing" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/watch" - api "k8s.io/kubernetes/pkg/apis/core" -) - -type testcase struct { - // Input of the test - name string - existingPod *v1.Pod - createPod *v1.Pod - // eventSequence is list of events that are simulated during recycling. It - // can be either event generated by a recycler pod or a state change of - // the pod. (see newPodEvent and newEvent below). - eventSequence []watch.Event - - // Expected output. - // expectedEvents is list of events that were sent to the volume that was - // recycled. - expectedEvents []mockEvent - expectedError string -} - -func newPodEvent(eventtype watch.EventType, name string, phase v1.PodPhase, message string) watch.Event { - return watch.Event{ - Type: eventtype, - Object: newPod(name, phase, message), - } -} - -func newEvent(eventtype, message string) watch.Event { - return watch.Event{ - Type: watch.Added, - Object: &v1.Event{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: metav1.NamespaceDefault, - }, - Reason: "MockEvent", - Message: message, - Type: eventtype, - }, - } -} - -func newPod(name string, phase v1.PodPhase, message string) *v1.Pod { - return &v1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Namespace: metav1.NamespaceDefault, - Name: name, - }, - Status: v1.PodStatus{ - Phase: phase, - Message: message, - }, - } -} - -func TestRecyclerPod(t *testing.T) { - tests := []testcase{ - { - // Test recycler success with some events - name: "RecyclerSuccess", - createPod: newPod("podRecyclerSuccess", v1.PodPending, ""), - eventSequence: []watch.Event{ - // Pod gets Running and Succeeded - newPodEvent(watch.Added, "podRecyclerSuccess", v1.PodPending, ""), - newEvent(v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerSuccess to 127.0.0.1"), - newEvent(v1.EventTypeNormal, "pulling image \"k8s.gcr.io/busybox\""), - newEvent(v1.EventTypeNormal, "Successfully pulled image \"k8s.gcr.io/busybox\""), - newEvent(v1.EventTypeNormal, "Created container with docker id 83d929aeac82"), - newEvent(v1.EventTypeNormal, "Started container with docker id 83d929aeac82"), - newPodEvent(watch.Modified, "podRecyclerSuccess", v1.PodRunning, ""), - newPodEvent(watch.Modified, "podRecyclerSuccess", v1.PodSucceeded, ""), - }, - expectedEvents: []mockEvent{ - {v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerSuccess to 127.0.0.1"}, - {v1.EventTypeNormal, "pulling image \"k8s.gcr.io/busybox\""}, - {v1.EventTypeNormal, "Successfully pulled image \"k8s.gcr.io/busybox\""}, - {v1.EventTypeNormal, "Created container with docker id 83d929aeac82"}, - {v1.EventTypeNormal, "Started container with docker id 83d929aeac82"}, - }, - expectedError: "", - }, - { - // Test recycler failure with some events - name: "RecyclerFailure", - createPod: newPod("podRecyclerFailure", v1.PodPending, ""), - eventSequence: []watch.Event{ - // Pod gets Running and Succeeded - newPodEvent(watch.Added, "podRecyclerFailure", v1.PodPending, ""), - newEvent(v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerFailure to 127.0.0.1"), - newEvent(v1.EventTypeWarning, "Unable to mount volumes for pod \"recycler-for-podRecyclerFailure_default(3c9809e5-347c-11e6-a79b-3c970e965218)\": timeout expired waiting for volumes to attach/mount"), - newEvent(v1.EventTypeWarning, "Error syncing pod, skipping: timeout expired waiting for volumes to attach/mount for pod \"default\"/\"recycler-for-podRecyclerFailure\". list of unattached/unmounted"), - newPodEvent(watch.Modified, "podRecyclerFailure", v1.PodRunning, ""), - newPodEvent(watch.Modified, "podRecyclerFailure", v1.PodFailed, "Pod was active on the node longer than specified deadline"), - }, - expectedEvents: []mockEvent{ - {v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerFailure to 127.0.0.1"}, - {v1.EventTypeWarning, "Unable to mount volumes for pod \"recycler-for-podRecyclerFailure_default(3c9809e5-347c-11e6-a79b-3c970e965218)\": timeout expired waiting for volumes to attach/mount"}, - {v1.EventTypeWarning, "Error syncing pod, skipping: timeout expired waiting for volumes to attach/mount for pod \"default\"/\"recycler-for-podRecyclerFailure\". list of unattached/unmounted"}, - }, - expectedError: "failed to recycle volume: Pod was active on the node longer than specified deadline", - }, - { - // Recycler pod gets deleted - name: "RecyclerDeleted", - createPod: newPod("podRecyclerDeleted", v1.PodPending, ""), - eventSequence: []watch.Event{ - // Pod gets Running and Succeeded - newPodEvent(watch.Added, "podRecyclerDeleted", v1.PodPending, ""), - newEvent(v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerDeleted to 127.0.0.1"), - newPodEvent(watch.Deleted, "podRecyclerDeleted", v1.PodPending, ""), - }, - expectedEvents: []mockEvent{ - {v1.EventTypeNormal, "Successfully assigned recycler-for-podRecyclerDeleted to 127.0.0.1"}, - }, - expectedError: "failed to recycle volume: recycler pod was deleted", - }, - { - // Another recycler pod is already running - name: "RecyclerRunning", - existingPod: newPod("podOldRecycler", v1.PodRunning, ""), - createPod: newPod("podNewRecycler", v1.PodFailed, "mock message"), - eventSequence: []watch.Event{}, - expectedError: "old recycler pod found, will retry later", - }, - } - - for _, test := range tests { - t.Logf("Test %q", test.name) - client := &mockRecyclerClient{ - events: test.eventSequence, - pod: test.existingPod, - } - err := internalRecycleVolumeByWatchingPodUntilCompletion(test.createPod.Name, test.createPod, client) - receivedError := "" - if err != nil { - receivedError = err.Error() - } - if receivedError != test.expectedError { - t.Errorf("Test %q failed, expected error %q, got %q", test.name, test.expectedError, receivedError) - continue - } - if !client.deletedCalled { - t.Errorf("Test %q failed, expected deferred client.Delete to be called on recycler pod", test.name) - continue - } - for i, expectedEvent := range test.expectedEvents { - if len(client.receivedEvents) <= i { - t.Errorf("Test %q failed, expected event %d: %q not received", test.name, i, expectedEvent.message) - continue - } - receivedEvent := client.receivedEvents[i] - if expectedEvent.eventtype != receivedEvent.eventtype { - t.Errorf("Test %q failed, event %d does not match: expected eventtype %q, got %q", test.name, i, expectedEvent.eventtype, receivedEvent.eventtype) - } - if expectedEvent.message != receivedEvent.message { - t.Errorf("Test %q failed, event %d does not match: expected message %q, got %q", test.name, i, expectedEvent.message, receivedEvent.message) - } - } - for i := len(test.expectedEvents); i < len(client.receivedEvents); i++ { - t.Errorf("Test %q failed, unexpected event received: %s, %q", test.name, client.receivedEvents[i].eventtype, client.receivedEvents[i].message) - } - } -} - -type mockRecyclerClient struct { - pod *v1.Pod - deletedCalled bool - receivedEvents []mockEvent - events []watch.Event -} - -type mockEvent struct { - eventtype, message string -} - -func (c *mockRecyclerClient) CreatePod(pod *v1.Pod) (*v1.Pod, error) { - if c.pod == nil { - c.pod = pod - return c.pod, nil - } - // Simulate "already exists" error - return nil, errors.NewAlreadyExists(api.Resource("pods"), pod.Name) -} - -func (c *mockRecyclerClient) GetPod(name, namespace string) (*v1.Pod, error) { - if c.pod != nil { - return c.pod, nil - } else { - return nil, fmt.Errorf("pod does not exist") - } -} - -func (c *mockRecyclerClient) DeletePod(name, namespace string) error { - c.deletedCalled = true - return nil -} - -func (c *mockRecyclerClient) WatchPod(name, namespace string, stopChannel chan struct{}) (<-chan watch.Event, error) { - eventCh := make(chan watch.Event, 0) - go func() { - for _, e := range c.events { - eventCh <- e - } - }() - return eventCh, nil -} - -func (c *mockRecyclerClient) Event(eventtype, message string) { - c.receivedEvents = append(c.receivedEvents, mockEvent{eventtype, message}) -} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/resize_util_test.go b/vendor/k8s.io/kubernetes/pkg/volume/util/resize_util_test.go deleted file mode 100644 index 28fb859eca..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/resize_util_test.go +++ /dev/null @@ -1,167 +0,0 @@ -/* -Copyright 2018 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 util - -import ( - "reflect" - "testing" - "time" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -type conditionMergeTestCase struct { - description string - pvc *v1.PersistentVolumeClaim - newConditions []v1.PersistentVolumeClaimCondition - finalCondtions []v1.PersistentVolumeClaimCondition -} - -func TestMergeResizeCondition(t *testing.T) { - currentTime := metav1.Now() - - pvc := getPVC([]v1.PersistentVolumeClaimCondition{ - { - Type: v1.PersistentVolumeClaimResizing, - Status: v1.ConditionTrue, - LastTransitionTime: currentTime, - }, - }) - - noConditionPVC := getPVC([]v1.PersistentVolumeClaimCondition{}) - - conditionFalseTime := metav1.Now() - newTime := metav1.NewTime(time.Now().Add(1 * time.Hour)) - - testCases := []conditionMergeTestCase{ - { - description: "when removing all conditions", - pvc: pvc.DeepCopy(), - newConditions: []v1.PersistentVolumeClaimCondition{}, - finalCondtions: []v1.PersistentVolumeClaimCondition{}, - }, - { - description: "adding new condition", - pvc: pvc.DeepCopy(), - newConditions: []v1.PersistentVolumeClaimCondition{ - { - Type: v1.PersistentVolumeClaimFileSystemResizePending, - Status: v1.ConditionTrue, - }, - }, - finalCondtions: []v1.PersistentVolumeClaimCondition{ - { - Type: v1.PersistentVolumeClaimFileSystemResizePending, - Status: v1.ConditionTrue, - }, - }, - }, - { - description: "adding same condition with new timestamp", - pvc: pvc.DeepCopy(), - newConditions: []v1.PersistentVolumeClaimCondition{ - { - Type: v1.PersistentVolumeClaimResizing, - Status: v1.ConditionTrue, - LastTransitionTime: newTime, - }, - }, - finalCondtions: []v1.PersistentVolumeClaimCondition{ - { - Type: v1.PersistentVolumeClaimResizing, - Status: v1.ConditionTrue, - LastTransitionTime: currentTime, - }, - }, - }, - { - description: "adding same condition but with different status", - pvc: pvc.DeepCopy(), - newConditions: []v1.PersistentVolumeClaimCondition{ - { - Type: v1.PersistentVolumeClaimResizing, - Status: v1.ConditionFalse, - LastTransitionTime: conditionFalseTime, - }, - }, - finalCondtions: []v1.PersistentVolumeClaimCondition{ - { - Type: v1.PersistentVolumeClaimResizing, - Status: v1.ConditionFalse, - LastTransitionTime: conditionFalseTime, - }, - }, - }, - { - description: "when no condition exists on pvc", - pvc: noConditionPVC.DeepCopy(), - newConditions: []v1.PersistentVolumeClaimCondition{ - { - Type: v1.PersistentVolumeClaimResizing, - Status: v1.ConditionTrue, - LastTransitionTime: currentTime, - }, - }, - finalCondtions: []v1.PersistentVolumeClaimCondition{ - { - Type: v1.PersistentVolumeClaimResizing, - Status: v1.ConditionTrue, - LastTransitionTime: currentTime, - }, - }, - }, - } - - for _, testcase := range testCases { - updatePVC := MergeResizeConditionOnPVC(testcase.pvc, testcase.newConditions) - - updateConditions := updatePVC.Status.Conditions - if !reflect.DeepEqual(updateConditions, testcase.finalCondtions) { - t.Errorf("Expected updated conditions for test %s to be %v but got %v", - testcase.description, - testcase.finalCondtions, updateConditions) - } - } - -} - -func getPVC(conditions []v1.PersistentVolumeClaimCondition) *v1.PersistentVolumeClaim { - pvc := &v1.PersistentVolumeClaim{ - ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "resize"}, - Spec: v1.PersistentVolumeClaimSpec{ - AccessModes: []v1.PersistentVolumeAccessMode{ - v1.ReadWriteOnce, - v1.ReadOnlyMany, - }, - Resources: v1.ResourceRequirements{ - Requests: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): resource.MustParse("2Gi"), - }, - }, - }, - Status: v1.PersistentVolumeClaimStatus{ - Phase: v1.ClaimBound, - Conditions: conditions, - Capacity: v1.ResourceList{ - v1.ResourceStorage: resource.MustParse("2Gi"), - }, - }, - } - return pvc -} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/util.go b/vendor/k8s.io/kubernetes/pkg/volume/util/util.go index 518103414c..febb81373c 100644 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/util.go +++ b/vendor/k8s.io/kubernetes/pkg/volume/util/util.go @@ -21,6 +21,7 @@ import ( "io/ioutil" "os" "path" + "path/filepath" "strings" "syscall" @@ -289,10 +290,12 @@ func checkAlphaNodeAffinity(pv *v1.PersistentVolume, nodeLabels map[string]strin if err != nil { return fmt.Errorf("Failed to parse MatchExpressions: %v", err) } - if !selector.Matches(labels.Set(nodeLabels)) { - return fmt.Errorf("NodeSelectorTerm %+v does not match node labels", term.MatchExpressions) + if selector.Matches(labels.Set(nodeLabels)) { + // Terms are ORed, so only one needs to match + return nil } } + return fmt.Errorf("No matching NodeSelectorTerms") } return nil } @@ -310,10 +313,12 @@ func checkVolumeNodeAffinity(pv *v1.PersistentVolume, nodeLabels map[string]stri if err != nil { return fmt.Errorf("Failed to parse MatchExpressions: %v", err) } - if !selector.Matches(labels.Set(nodeLabels)) { - return fmt.Errorf("NodeSelectorTerm %+v does not match node labels", term.MatchExpressions) + if selector.Matches(labels.Set(nodeLabels)) { + // Terms are ORed, so only one needs to match + return nil } } + return fmt.Errorf("No matching NodeSelectorTerms") } return nil } @@ -749,3 +754,21 @@ func CheckVolumeModeFilesystem(volumeSpec *volume.Spec) (bool, error) { } return true, nil } + +// MakeAbsolutePath convert path to absolute path according to GOOS +func MakeAbsolutePath(goos, path string) string { + if goos != "windows" { + return filepath.Clean("/" + path) + } + // These are all for windows + // If there is a colon, give up. + if strings.Contains(path, ":") { + return path + } + // If there is a slash, but no drive, add 'c:' + if strings.HasPrefix(path, "/") || strings.HasPrefix(path, "\\") { + return "c:" + path + } + // Otherwise, add 'c:\' + return "c:\\" + path +} diff --git a/vendor/k8s.io/kubernetes/pkg/volume/util/util_test.go b/vendor/k8s.io/kubernetes/pkg/volume/util/util_test.go deleted file mode 100644 index ae4e6587d4..0000000000 --- a/vendor/k8s.io/kubernetes/pkg/volume/util/util_test.go +++ /dev/null @@ -1,1091 +0,0 @@ -/* -Copyright 2017 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 util - -import ( - "io/ioutil" - "os" - "testing" - - "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/util/sets" - utiltesting "k8s.io/client-go/util/testing" - // util.go uses api.Codecs.LegacyCodec so import this package to do some - // resource initialization. - "hash/fnv" - - _ "k8s.io/kubernetes/pkg/apis/core/install" - "k8s.io/kubernetes/pkg/apis/core/v1/helper" - "k8s.io/kubernetes/pkg/util/mount" - - "reflect" - "strings" - - "k8s.io/apimachinery/pkg/api/resource" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - - "k8s.io/kubernetes/pkg/util/slice" - "k8s.io/kubernetes/pkg/volume" -) - -var nodeLabels map[string]string = map[string]string{ - "test-key1": "test-value1", - "test-key2": "test-value2", -} - -func TestCheckAlphaNodeAffinity(t *testing.T) { - type affinityTest struct { - name string - expectSuccess bool - pv *v1.PersistentVolume - } - - cases := []affinityTest{ - { - name: "valid-no-constraints", - expectSuccess: true, - pv: testVolumeWithAlphaNodeAffinity(t, &v1.NodeAffinity{}), - }, - { - name: "valid-constraints", - expectSuccess: true, - pv: testVolumeWithAlphaNodeAffinity(t, &v1.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{ - NodeSelectorTerms: []v1.NodeSelectorTerm{ - { - MatchExpressions: []v1.NodeSelectorRequirement{ - { - Key: "test-key1", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value1", "test-value3"}, - }, - { - Key: "test-key2", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value0", "test-value2"}, - }, - }, - }, - }, - }, - }), - }, - { - name: "invalid-key", - expectSuccess: false, - pv: testVolumeWithAlphaNodeAffinity(t, &v1.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{ - NodeSelectorTerms: []v1.NodeSelectorTerm{ - { - MatchExpressions: []v1.NodeSelectorRequirement{ - { - Key: "test-key1", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value1", "test-value3"}, - }, - { - Key: "test-key3", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value0", "test-value2"}, - }, - }, - }, - }, - }, - }), - }, - { - name: "invalid-values", - expectSuccess: false, - pv: testVolumeWithAlphaNodeAffinity(t, &v1.NodeAffinity{ - RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{ - NodeSelectorTerms: []v1.NodeSelectorTerm{ - { - MatchExpressions: []v1.NodeSelectorRequirement{ - { - Key: "test-key1", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value3", "test-value4"}, - }, - { - Key: "test-key2", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value0", "test-value2"}, - }, - }, - }, - }, - }, - }), - }, - } - - for _, c := range cases { - err := CheckNodeAffinity(c.pv, nodeLabels) - - if err != nil && c.expectSuccess { - t.Errorf("CheckTopology %v returned error: %v", c.name, err) - } - if err == nil && !c.expectSuccess { - t.Errorf("CheckTopology %v returned success, expected error", c.name) - } - } -} - -func TestCheckVolumeNodeAffinity(t *testing.T) { - type affinityTest struct { - name string - expectSuccess bool - pv *v1.PersistentVolume - } - - cases := []affinityTest{ - { - name: "valid-nil", - expectSuccess: true, - pv: testVolumeWithNodeAffinity(t, nil), - }, - { - name: "valid-no-constraints", - expectSuccess: true, - pv: testVolumeWithNodeAffinity(t, &v1.VolumeNodeAffinity{}), - }, - { - name: "valid-constraints", - expectSuccess: true, - pv: testVolumeWithNodeAffinity(t, &v1.VolumeNodeAffinity{ - Required: &v1.NodeSelector{ - NodeSelectorTerms: []v1.NodeSelectorTerm{ - { - MatchExpressions: []v1.NodeSelectorRequirement{ - { - Key: "test-key1", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value1", "test-value3"}, - }, - { - Key: "test-key2", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value0", "test-value2"}, - }, - }, - }, - }, - }, - }), - }, - { - name: "invalid-key", - expectSuccess: false, - pv: testVolumeWithNodeAffinity(t, &v1.VolumeNodeAffinity{ - Required: &v1.NodeSelector{ - NodeSelectorTerms: []v1.NodeSelectorTerm{ - { - MatchExpressions: []v1.NodeSelectorRequirement{ - { - Key: "test-key1", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value1", "test-value3"}, - }, - { - Key: "test-key3", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value0", "test-value2"}, - }, - }, - }, - }, - }, - }), - }, - { - name: "invalid-values", - expectSuccess: false, - pv: testVolumeWithNodeAffinity(t, &v1.VolumeNodeAffinity{ - Required: &v1.NodeSelector{ - NodeSelectorTerms: []v1.NodeSelectorTerm{ - { - MatchExpressions: []v1.NodeSelectorRequirement{ - { - Key: "test-key1", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value3", "test-value4"}, - }, - { - Key: "test-key2", - Operator: v1.NodeSelectorOpIn, - Values: []string{"test-value0", "test-value2"}, - }, - }, - }, - }, - }, - }), - }, - } - - for _, c := range cases { - err := CheckNodeAffinity(c.pv, nodeLabels) - - if err != nil && c.expectSuccess { - t.Errorf("CheckTopology %v returned error: %v", c.name, err) - } - if err == nil && !c.expectSuccess { - t.Errorf("CheckTopology %v returned success, expected error", c.name) - } - } -} - -func testVolumeWithAlphaNodeAffinity(t *testing.T, affinity *v1.NodeAffinity) *v1.PersistentVolume { - objMeta := metav1.ObjectMeta{Name: "test-constraints"} - objMeta.Annotations = map[string]string{} - err := helper.StorageNodeAffinityToAlphaAnnotation(objMeta.Annotations, affinity) - if err != nil { - t.Fatalf("Failed to get node affinity annotation: %v", err) - } - - return &v1.PersistentVolume{ - ObjectMeta: objMeta, - } -} - -func testVolumeWithNodeAffinity(t *testing.T, affinity *v1.VolumeNodeAffinity) *v1.PersistentVolume { - objMeta := metav1.ObjectMeta{Name: "test-constraints"} - return &v1.PersistentVolume{ - ObjectMeta: objMeta, - Spec: v1.PersistentVolumeSpec{ - NodeAffinity: affinity, - }, - } -} - -func TestLoadPodFromFile(t *testing.T) { - tests := []struct { - name string - content string - expectError bool - }{ - { - "yaml", - ` -apiVersion: v1 -kind: Pod -metadata: - name: testpod -spec: - containers: - - image: k8s.gcr.io/busybox -`, - false, - }, - - { - "json", - ` -{ - "apiVersion": "v1", - "kind": "Pod", - "metadata": { - "name": "testpod" - }, - "spec": { - "containers": [ - { - "image": "k8s.gcr.io/busybox" - } - ] - } -}`, - false, - }, - - { - "invalid pod", - ` -apiVersion: v1 -kind: Pod -metadata: - name: testpod -spec: - - image: k8s.gcr.io/busybox -`, - true, - }, - } - - for _, test := range tests { - tempFile, err := ioutil.TempFile("", "podfile") - defer os.Remove(tempFile.Name()) - if err != nil { - t.Fatalf("cannot create temporary file: %v", err) - } - if _, err = tempFile.Write([]byte(test.content)); err != nil { - t.Fatalf("cannot save temporary file: %v", err) - } - if err = tempFile.Close(); err != nil { - t.Fatalf("cannot close temporary file: %v", err) - } - - pod, err := LoadPodFromFile(tempFile.Name()) - if test.expectError { - if err == nil { - t.Errorf("test %q expected error, got nil", test.name) - } - } else { - // no error expected - if err != nil { - t.Errorf("error loading pod %q: %v", test.name, err) - } - if pod == nil { - t.Errorf("test %q expected pod, got nil", test.name) - } - } - } -} -func TestZonesToSet(t *testing.T) { - functionUnderTest := "ZonesToSet" - // First part: want an error - sliceOfZones := []string{"", ",", "us-east-1a, , us-east-1d", ", us-west-1b", "us-west-2b,"} - for _, zones := range sliceOfZones { - if got, err := ZonesToSet(zones); err == nil { - t.Errorf("%v(%v) returned (%v), want (%v)", functionUnderTest, zones, got, "an error") - } - } - - // Second part: want no error - tests := []struct { - zones string - want sets.String - }{ - { - zones: "us-east-1a", - want: sets.String{"us-east-1a": sets.Empty{}}, - }, - { - zones: "us-east-1a, us-west-2a", - want: sets.String{ - "us-east-1a": sets.Empty{}, - "us-west-2a": sets.Empty{}, - }, - }, - } - for _, tt := range tests { - if got, err := ZonesToSet(tt.zones); err != nil || !got.Equal(tt.want) { - t.Errorf("%v(%v) returned (%v), want (%v)", functionUnderTest, tt.zones, got, tt.want) - } - } -} - -func TestDoUnmountMountPoint(t *testing.T) { - - tmpDir1, err1 := utiltesting.MkTmpdir("umount_test1") - if err1 != nil { - t.Fatalf("error creating temp dir: %v", err1) - } - defer os.RemoveAll(tmpDir1) - - tmpDir2, err2 := utiltesting.MkTmpdir("umount_test2") - if err2 != nil { - t.Fatalf("error creating temp dir: %v", err2) - } - defer os.RemoveAll(tmpDir2) - - // Second part: want no error - tests := []struct { - mountPath string - corruptedMnt bool - }{ - { - mountPath: tmpDir1, - corruptedMnt: true, - }, - { - mountPath: tmpDir2, - corruptedMnt: false, - }, - } - - fake := &mount.FakeMounter{} - - for _, tt := range tests { - err := doUnmountMountPoint(tt.mountPath, fake, false, tt.corruptedMnt) - if err != nil { - t.Errorf("err Expected nil, but got: %v", err) - } - } -} - -func TestCalculateTimeoutForVolume(t *testing.T) { - pv := &v1.PersistentVolume{ - Spec: v1.PersistentVolumeSpec{ - Capacity: v1.ResourceList{ - v1.ResourceName(v1.ResourceStorage): resource.MustParse("500M"), - }, - }, - } - - timeout := CalculateTimeoutForVolume(50, 30, pv) - if timeout != 50 { - t.Errorf("Expected 50 for timeout but got %v", timeout) - } - - pv.Spec.Capacity[v1.ResourceStorage] = resource.MustParse("2Gi") - timeout = CalculateTimeoutForVolume(50, 30, pv) - if timeout != 60 { - t.Errorf("Expected 60 for timeout but got %v", timeout) - } - - pv.Spec.Capacity[v1.ResourceStorage] = resource.MustParse("150Gi") - timeout = CalculateTimeoutForVolume(50, 30, pv) - if timeout != 4500 { - t.Errorf("Expected 4500 for timeout but got %v", timeout) - } -} - -func TestGenerateVolumeName(t *testing.T) { - - // Normal operation, no truncate - v1 := GenerateVolumeName("kubernetes", "pv-cinder-abcde", 255) - if v1 != "kubernetes-dynamic-pv-cinder-abcde" { - t.Errorf("Expected kubernetes-dynamic-pv-cinder-abcde, got %s", v1) - } - - // Truncate trailing "6789-dynamic" - prefix := strings.Repeat("0123456789", 9) // 90 characters prefix + 8 chars. of "-dynamic" - v2 := GenerateVolumeName(prefix, "pv-cinder-abcde", 100) - expect := prefix[:84] + "-pv-cinder-abcde" - if v2 != expect { - t.Errorf("Expected %s, got %s", expect, v2) - } - - // Truncate really long cluster name - prefix = strings.Repeat("0123456789", 1000) // 10000 characters prefix - v3 := GenerateVolumeName(prefix, "pv-cinder-abcde", 100) - if v3 != expect { - t.Errorf("Expected %s, got %s", expect, v3) - } -} - -func TestMountOptionFromSpec(t *testing.T) { - scenarios := map[string]struct { - volume *volume.Spec - expectedMountList []string - systemOptions []string - }{ - "volume-with-mount-options": { - volume: createVolumeSpecWithMountOption("good-mount-opts", "ro,nfsvers=3", v1.PersistentVolumeSpec{ - PersistentVolumeSource: v1.PersistentVolumeSource{ - NFS: &v1.NFSVolumeSource{Server: "localhost", Path: "/srv", ReadOnly: false}, - }, - }), - expectedMountList: []string{"ro", "nfsvers=3"}, - systemOptions: nil, - }, - "volume-with-bad-mount-options": { - volume: createVolumeSpecWithMountOption("good-mount-opts", "", v1.PersistentVolumeSpec{ - PersistentVolumeSource: v1.PersistentVolumeSource{ - NFS: &v1.NFSVolumeSource{Server: "localhost", Path: "/srv", ReadOnly: false}, - }, - }), - expectedMountList: []string{}, - systemOptions: nil, - }, - "vol-with-sys-opts": { - volume: createVolumeSpecWithMountOption("good-mount-opts", "ro,nfsvers=3", v1.PersistentVolumeSpec{ - PersistentVolumeSource: v1.PersistentVolumeSource{ - NFS: &v1.NFSVolumeSource{Server: "localhost", Path: "/srv", ReadOnly: false}, - }, - }), - expectedMountList: []string{"ro", "nfsvers=3", "fsid=100", "hard"}, - systemOptions: []string{"fsid=100", "hard"}, - }, - "vol-with-sys-opts-with-dup": { - volume: createVolumeSpecWithMountOption("good-mount-opts", "ro,nfsvers=3", v1.PersistentVolumeSpec{ - PersistentVolumeSource: v1.PersistentVolumeSource{ - NFS: &v1.NFSVolumeSource{Server: "localhost", Path: "/srv", ReadOnly: false}, - }, - }), - expectedMountList: []string{"ro", "nfsvers=3", "fsid=100"}, - systemOptions: []string{"fsid=100", "ro"}, - }, - } - - for name, scenario := range scenarios { - mountOptions := MountOptionFromSpec(scenario.volume, scenario.systemOptions...) - if !reflect.DeepEqual(slice.SortStrings(mountOptions), slice.SortStrings(scenario.expectedMountList)) { - t.Errorf("for %s expected mount options : %v got %v", name, scenario.expectedMountList, mountOptions) - } - } -} - -func createVolumeSpecWithMountOption(name string, mountOptions string, spec v1.PersistentVolumeSpec) *volume.Spec { - annotations := map[string]string{ - v1.MountOptionAnnotation: mountOptions, - } - objMeta := metav1.ObjectMeta{ - Name: name, - Annotations: annotations, - } - - pv := &v1.PersistentVolume{ - ObjectMeta: objMeta, - Spec: spec, - } - return &volume.Spec{PersistentVolume: pv} -} - -func checkFnv32(t *testing.T, s string, expected uint32) { - h := fnv.New32() - h.Write([]byte(s)) - h.Sum32() - - if h.Sum32() != expected { - t.Fatalf("hash of %q was %v, expected %v", s, h.Sum32(), expected) - } -} - -func TestChooseZoneForVolume(t *testing.T) { - checkFnv32(t, "henley", 1180403676) - // 1180403676 mod 3 == 0, so the offset from "henley" is 0, which makes it easier to verify this by inspection - - // A few others - checkFnv32(t, "henley-", 2652299129) - checkFnv32(t, "henley-a", 1459735322) - checkFnv32(t, "", 2166136261) - - tests := []struct { - Zones sets.String - VolumeName string - Expected string - }{ - // Test for PVC names that don't have a dash - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley", - Expected: "a", // hash("henley") == 0 - }, - // Tests for PVC names that end in - number, but don't look like statefulset PVCs - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-0", - Expected: "a", // hash("henley") == 0 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-1", - Expected: "b", // hash("henley") + 1 == 1 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-2", - Expected: "c", // hash("henley") + 2 == 2 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-3", - Expected: "a", // hash("henley") + 3 == 3 === 0 mod 3 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-4", - Expected: "b", // hash("henley") + 4 == 4 === 1 mod 3 - }, - // Tests for PVC names that are edge cases - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-", - Expected: "c", // hash("henley-") = 2652299129 === 2 mod 3 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-a", - Expected: "c", // hash("henley-a") = 1459735322 === 2 mod 3 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium--1", - Expected: "c", // hash("") + 1 == 2166136261 + 1 === 2 mod 3 - }, - // Tests for PVC names for simple StatefulSet cases - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-1", - Expected: "b", // hash("henley") + 1 == 1 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "loud-henley-1", - Expected: "b", // hash("henley") + 1 == 1 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "quiet-henley-2", - Expected: "c", // hash("henley") + 2 == 2 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-2", - Expected: "c", // hash("henley") + 2 == 2 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-3", - Expected: "a", // hash("henley") + 3 == 3 === 0 mod 3 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-4", - Expected: "b", // hash("henley") + 4 == 4 === 1 mod 3 - }, - // Tests for statefulsets (or claims) with dashes in the names - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-alpha-henley-2", - Expected: "c", // hash("henley") + 2 == 2 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-beta-henley-3", - Expected: "a", // hash("henley") + 3 == 3 === 0 mod 3 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-gamma-henley-4", - Expected: "b", // hash("henley") + 4 == 4 === 1 mod 3 - }, - // Tests for statefulsets name ending in - - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--2", - Expected: "a", // hash("") + 2 == 0 mod 3 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--3", - Expected: "b", // hash("") + 3 == 1 mod 3 - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--4", - Expected: "c", // hash("") + 4 == 2 mod 3 - }, - } - - for _, test := range tests { - actual := ChooseZoneForVolume(test.Zones, test.VolumeName) - - if actual != test.Expected { - t.Errorf("Test %v failed, expected zone %q, actual %q", test, test.Expected, actual) - } - } -} - -func TestChooseZonesForVolume(t *testing.T) { - checkFnv32(t, "henley", 1180403676) - // 1180403676 mod 3 == 0, so the offset from "henley" is 0, which makes it easier to verify this by inspection - - // A few others - checkFnv32(t, "henley-", 2652299129) - checkFnv32(t, "henley-a", 1459735322) - checkFnv32(t, "", 2166136261) - - tests := []struct { - Zones sets.String - VolumeName string - NumZones uint32 - Expected sets.String - }{ - // Test for PVC names that don't have a dash - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley", - NumZones: 1, - Expected: sets.NewString("a" /* hash("henley") == 0 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley", - NumZones: 2, - Expected: sets.NewString("a" /* hash("henley") == 0 */, "b"), - }, - // Tests for PVC names that end in - number, but don't look like statefulset PVCs - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-0", - NumZones: 1, - Expected: sets.NewString("a" /* hash("henley") == 0 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-0", - NumZones: 2, - Expected: sets.NewString("a" /* hash("henley") == 0 */, "b"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-1", - NumZones: 1, - Expected: sets.NewString("b" /* hash("henley") + 1 == 1 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-1", - NumZones: 2, - Expected: sets.NewString("c" /* hash("henley") + 1 + 1(startingIndex) == 2 */, "a"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-2", - NumZones: 1, - Expected: sets.NewString("c" /* hash("henley") + 2 == 2 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-2", - NumZones: 2, - Expected: sets.NewString("b" /* hash("henley") + 2 + 2(startingIndex) == 4 */, "c"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-3", - NumZones: 1, - Expected: sets.NewString("a" /* hash("henley") + 3 == 3 === 0 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-3", - NumZones: 2, - Expected: sets.NewString("a" /* hash("henley") + 3 + 3(startingIndex) == 6 */, "b"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-4", - NumZones: 1, - Expected: sets.NewString("b" /* hash("henley") + 4 == 4 === 1 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-4", - NumZones: 2, - Expected: sets.NewString("c" /* hash("henley") + 4 + 4(startingIndex) == 8 */, "a"), - }, - // Tests for PVC names that are edge cases - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-", - NumZones: 1, - Expected: sets.NewString("c" /* hash("henley-") = 2652299129 === 2 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-", - NumZones: 2, - Expected: sets.NewString("c" /* hash("henley-") = 2652299129 === 2 mod 3 = 2 */, "a"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-a", - NumZones: 1, - Expected: sets.NewString("c" /* hash("henley-a") = 1459735322 === 2 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "henley-a", - NumZones: 2, - Expected: sets.NewString("c" /* hash("henley-a") = 1459735322 === 2 mod 3 = 2 */, "a"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium--1", - NumZones: 1, - Expected: sets.NewString("c" /* hash("") + 1 == 2166136261 + 1 === 2 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium--1", - NumZones: 2, - Expected: sets.NewString("a" /* hash("") + 1 + 1(startingIndex) == 2166136261 + 1 + 1 === 3 mod 3 = 0 */, "b"), - }, - // Tests for PVC names for simple StatefulSet cases - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-1", - NumZones: 1, - Expected: sets.NewString("b" /* hash("henley") + 1 == 1 */), - }, - // Tests for PVC names for simple StatefulSet cases - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-1", - NumZones: 2, - Expected: sets.NewString("c" /* hash("henley") + 1 + 1(startingIndex) == 2 */, "a"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "loud-henley-1", - NumZones: 1, - Expected: sets.NewString("b" /* hash("henley") + 1 == 1 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "loud-henley-1", - NumZones: 2, - Expected: sets.NewString("c" /* hash("henley") + 1 + 1(startingIndex) == 2 */, "a"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "quiet-henley-2", - NumZones: 1, - Expected: sets.NewString("c" /* hash("henley") + 2 == 2 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "quiet-henley-2", - NumZones: 2, - Expected: sets.NewString("b" /* hash("henley") + 2 + 2(startingIndex) == 4 */, "c"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-2", - NumZones: 1, - Expected: sets.NewString("c" /* hash("henley") + 2 == 2 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-2", - NumZones: 2, - Expected: sets.NewString("b" /* hash("henley") + 2 + 2(startingIndex) == 4 */, "c"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-3", - NumZones: 1, - Expected: sets.NewString("a" /* hash("henley") + 3 == 3 === 0 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-3", - NumZones: 2, - Expected: sets.NewString("a" /* hash("henley") + 3 + 3(startingIndex) == 6 === 6 mod 3 = 0 */, "b"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-4", - NumZones: 1, - Expected: sets.NewString("b" /* hash("henley") + 4 == 4 === 1 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley-4", - NumZones: 2, - Expected: sets.NewString("c" /* hash("henley") + 4 + 4(startingIndex) == 8 === 2 mod 3 */, "a"), - }, - // Tests for statefulsets (or claims) with dashes in the names - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-alpha-henley-2", - NumZones: 1, - Expected: sets.NewString("c" /* hash("henley") + 2 == 2 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-alpha-henley-2", - NumZones: 2, - Expected: sets.NewString("b" /* hash("henley") + 2 + 2(startingIndex) == 4 */, "c"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-beta-henley-3", - NumZones: 1, - Expected: sets.NewString("a" /* hash("henley") + 3 == 3 === 0 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-beta-henley-3", - NumZones: 2, - Expected: sets.NewString("a" /* hash("henley") + 3 + 3(startingIndex) == 6 === 0 mod 3 */, "b"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-gamma-henley-4", - NumZones: 1, - Expected: sets.NewString("b" /* hash("henley") + 4 == 4 === 1 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-gamma-henley-4", - NumZones: 2, - Expected: sets.NewString("c" /* hash("henley") + 4 + 4(startingIndex) == 8 === 2 mod 3 */, "a"), - }, - // Tests for statefulsets name ending in - - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--2", - NumZones: 1, - Expected: sets.NewString("a" /* hash("") + 2 == 0 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--2", - NumZones: 2, - Expected: sets.NewString("c" /* hash("") + 2 + 2(startingIndex) == 2 mod 3 */, "a"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--3", - NumZones: 1, - Expected: sets.NewString("b" /* hash("") + 3 == 1 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--3", - NumZones: 2, - Expected: sets.NewString("b" /* hash("") + 3 + 3(startingIndex) == 1 mod 3 */, "c"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--4", - NumZones: 1, - Expected: sets.NewString("c" /* hash("") + 4 == 2 mod 3 */), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--4", - NumZones: 2, - Expected: sets.NewString("a" /* hash("") + 4 + 4(startingIndex) == 0 mod 3 */, "b"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--4", - NumZones: 3, - Expected: sets.NewString("c" /* hash("") + 4 == 2 mod 3 */, "a", "b"), - }, - { - Zones: sets.NewString("a", "b", "c"), - VolumeName: "medium-henley--4", - NumZones: 4, - Expected: sets.NewString("c" /* hash("") + 4 + 9(startingIndex) == 2 mod 3 */, "a", "b", "c"), - }, - { - Zones: sets.NewString("a", "b", "c", "d", "e", "f", "g", "h", "i"), - VolumeName: "henley-0", - NumZones: 2, - Expected: sets.NewString("a" /* hash("henley") == 0 */, "b"), - }, - { - Zones: sets.NewString("a", "b", "c", "d", "e", "f", "g", "h", "i"), - VolumeName: "henley-1", - NumZones: 2, - Expected: sets.NewString("c" /* hash("henley") == 0 + 2 */, "d"), - }, - { - Zones: sets.NewString("a", "b", "c", "d", "e", "f", "g", "h", "i"), - VolumeName: "henley-2", - NumZones: 2, - Expected: sets.NewString("e" /* hash("henley") == 0 + 2 + 2(startingIndex) */, "f"), - }, - { - Zones: sets.NewString("a", "b", "c", "d", "e", "f", "g", "h", "i"), - VolumeName: "henley-3", - NumZones: 2, - Expected: sets.NewString("g" /* hash("henley") == 0 + 2 + 4(startingIndex) */, "h"), - }, - { - Zones: sets.NewString("a", "b", "c", "d", "e", "f", "g", "h", "i"), - VolumeName: "henley-0", - NumZones: 3, - Expected: sets.NewString("a" /* hash("henley") == 0 */, "b", "c"), - }, - { - Zones: sets.NewString("a", "b", "c", "d", "e", "f", "g", "h", "i"), - VolumeName: "henley-1", - NumZones: 3, - Expected: sets.NewString("d" /* hash("henley") == 0 + 1 + 2(startingIndex) */, "e", "f"), - }, - { - Zones: sets.NewString("a", "b", "c", "d", "e", "f", "g", "h", "i"), - VolumeName: "henley-2", - NumZones: 3, - Expected: sets.NewString("g" /* hash("henley") == 0 + 2 + 4(startingIndex) */, "h", "i"), - }, - { - Zones: sets.NewString("a", "b", "c", "d", "e", "f", "g", "h", "i"), - VolumeName: "henley-3", - NumZones: 3, - Expected: sets.NewString("a" /* hash("henley") == 0 + 3 + 6(startingIndex) */, "b", "c"), - }, - } - - for _, test := range tests { - actual := ChooseZonesForVolume(test.Zones, test.VolumeName, test.NumZones) - - if !actual.Equal(test.Expected) { - t.Errorf("Test %v failed, expected zone %#v, actual %#v", test, test.Expected, actual) - } - } -} - -func TestValidateZone(t *testing.T) { - functionUnderTest := "ValidateZone" - - // First part: want an error - errCases := []string{"", " "} - for _, errCase := range errCases { - if got := ValidateZone(errCase); got == nil { - t.Errorf("%v(%v) returned (%v), want (%v)", functionUnderTest, errCase, got, "an error") - } - } - - // Second part: want no error - succCases := []string{" us-east-1a "} - for _, succCase := range succCases { - if got := ValidateZone(succCase); got != nil { - t.Errorf("%v(%v) returned (%v), want (%v)", functionUnderTest, succCase, got, nil) - } - } -} - -func TestGetWindowsPath(t *testing.T) { - tests := []struct { - path string - expectedPath string - }{ - { - path: `/var/lib/kubelet/pods/146f8428-83e7-11e7-8dd4-000d3a31dac4/volumes/kubernetes.io~disk`, - expectedPath: `c:\var\lib\kubelet\pods\146f8428-83e7-11e7-8dd4-000d3a31dac4\volumes\kubernetes.io~disk`, - }, - { - path: `\var/lib/kubelet/pods/146f8428-83e7-11e7-8dd4-000d3a31dac4\volumes\kubernetes.io~disk`, - expectedPath: `c:\var\lib\kubelet\pods\146f8428-83e7-11e7-8dd4-000d3a31dac4\volumes\kubernetes.io~disk`, - }, - { - path: `/`, - expectedPath: `c:\`, - }, - { - path: ``, - expectedPath: ``, - }, - } - - for _, test := range tests { - result := GetWindowsPath(test.path) - if result != test.expectedPath { - t.Errorf("GetWindowsPath(%v) returned (%v), want (%v)", test.path, result, test.expectedPath) - } - } -} diff --git a/vendor/k8s.io/kubernetes/third_party/forked/golang/expansion/expand_test.go b/vendor/k8s.io/kubernetes/third_party/forked/golang/expansion/expand_test.go deleted file mode 100644 index 948c36ffe6..0000000000 --- a/vendor/k8s.io/kubernetes/third_party/forked/golang/expansion/expand_test.go +++ /dev/null @@ -1,284 +0,0 @@ -package expansion - -import ( - "testing" -api "k8s.io/kubernetes/pkg/apis/core" -) - -func TestMapReference(t *testing.T) { - envs := []api.EnvVar{ - { - Name: "FOO", - Value: "bar", - }, - { - Name: "ZOO", - Value: "$(FOO)-1", - }, - { - Name: "BLU", - Value: "$(ZOO)-2", - }, - } - - declaredEnv := map[string]string{ - "FOO": "bar", - "ZOO": "$(FOO)-1", - "BLU": "$(ZOO)-2", - } - - serviceEnv := map[string]string{} - - mapping := MappingFuncFor(declaredEnv, serviceEnv) - - for _, env := range envs { - declaredEnv[env.Name] = Expand(env.Value, mapping) - } - - expectedEnv := map[string]string{ - "FOO": "bar", - "ZOO": "bar-1", - "BLU": "bar-1-2", - } - - for k, v := range expectedEnv { - if e, a := v, declaredEnv[k]; e != a { - t.Errorf("Expected %v, got %v", e, a) - } else { - delete(declaredEnv, k) - } - } - - if len(declaredEnv) != 0 { - t.Errorf("Unexpected keys in declared env: %v", declaredEnv) - } -} - -func TestMapping(t *testing.T) { - context := map[string]string{ - "VAR_A": "A", - "VAR_B": "B", - "VAR_C": "C", - "VAR_REF": "$(VAR_A)", - "VAR_EMPTY": "", - } - mapping := MappingFuncFor(context) - - doExpansionTest(t, mapping) -} - -func TestMappingDual(t *testing.T) { - context := map[string]string{ - "VAR_A": "A", - "VAR_EMPTY": "", - } - context2 := map[string]string{ - "VAR_B": "B", - "VAR_C": "C", - "VAR_REF": "$(VAR_A)", - } - mapping := MappingFuncFor(context, context2) - - doExpansionTest(t, mapping) -} - -func doExpansionTest(t *testing.T, mapping func(string) string) { - cases := []struct { - name string - input string - expected string - }{ - { - name: "whole string", - input: "$(VAR_A)", - expected: "A", - }, - { - name: "repeat", - input: "$(VAR_A)-$(VAR_A)", - expected: "A-A", - }, - { - name: "beginning", - input: "$(VAR_A)-1", - expected: "A-1", - }, - { - name: "middle", - input: "___$(VAR_B)___", - expected: "___B___", - }, - { - name: "end", - input: "___$(VAR_C)", - expected: "___C", - }, - { - name: "compound", - input: "$(VAR_A)_$(VAR_B)_$(VAR_C)", - expected: "A_B_C", - }, - { - name: "escape & expand", - input: "$$(VAR_B)_$(VAR_A)", - expected: "$(VAR_B)_A", - }, - { - name: "compound escape", - input: "$$(VAR_A)_$$(VAR_B)", - expected: "$(VAR_A)_$(VAR_B)", - }, - { - name: "mixed in escapes", - input: "f000-$$VAR_A", - expected: "f000-$VAR_A", - }, - { - name: "backslash escape ignored", - input: "foo\\$(VAR_C)bar", - expected: "foo\\Cbar", - }, - { - name: "backslash escape ignored", - input: "foo\\\\$(VAR_C)bar", - expected: "foo\\\\Cbar", - }, - { - name: "lots of backslashes", - input: "foo\\\\\\\\$(VAR_A)bar", - expected: "foo\\\\\\\\Abar", - }, - { - name: "nested var references", - input: "$(VAR_A$(VAR_B))", - expected: "$(VAR_A$(VAR_B))", - }, - { - name: "nested var references second type", - input: "$(VAR_A$(VAR_B)", - expected: "$(VAR_A$(VAR_B)", - }, - { - name: "value is a reference", - input: "$(VAR_REF)", - expected: "$(VAR_A)", - }, - { - name: "value is a reference x 2", - input: "%%$(VAR_REF)--$(VAR_REF)%%", - expected: "%%$(VAR_A)--$(VAR_A)%%", - }, - { - name: "empty var", - input: "foo$(VAR_EMPTY)bar", - expected: "foobar", - }, - { - name: "unterminated expression", - input: "foo$(VAR_Awhoops!", - expected: "foo$(VAR_Awhoops!", - }, - { - name: "expression without operator", - input: "f00__(VAR_A)__", - expected: "f00__(VAR_A)__", - }, - { - name: "shell special vars pass through", - input: "$?_boo_$!", - expected: "$?_boo_$!", - }, - { - name: "bare operators are ignored", - input: "$VAR_A", - expected: "$VAR_A", - }, - { - name: "undefined vars are passed through", - input: "$(VAR_DNE)", - expected: "$(VAR_DNE)", - }, - { - name: "multiple (even) operators, var undefined", - input: "$$$$$$(BIG_MONEY)", - expected: "$$$(BIG_MONEY)", - }, - { - name: "multiple (even) operators, var defined", - input: "$$$$$$(VAR_A)", - expected: "$$$(VAR_A)", - }, - { - name: "multiple (odd) operators, var undefined", - input: "$$$$$$$(GOOD_ODDS)", - expected: "$$$$(GOOD_ODDS)", - }, - { - name: "multiple (odd) operators, var defined", - input: "$$$$$$$(VAR_A)", - expected: "$$$A", - }, - { - name: "missing open expression", - input: "$VAR_A)", - expected: "$VAR_A)", - }, - { - name: "shell syntax ignored", - input: "${VAR_A}", - expected: "${VAR_A}", - }, - { - name: "trailing incomplete expression not consumed", - input: "$(VAR_B)_______$(A", - expected: "B_______$(A", - }, - { - name: "trailing incomplete expression, no content, is not consumed", - input: "$(VAR_C)_______$(", - expected: "C_______$(", - }, - { - name: "operator at end of input string is preserved", - input: "$(VAR_A)foobarzab$", - expected: "Afoobarzab$", - }, - { - name: "shell escaped incomplete expr", - input: "foo-\\$(VAR_A", - expected: "foo-\\$(VAR_A", - }, - { - name: "lots of $( in middle", - input: "--$($($($($--", - expected: "--$($($($($--", - }, - { - name: "lots of $( in beginning", - input: "$($($($($--foo$(", - expected: "$($($($($--foo$(", - }, - { - name: "lots of $( at end", - input: "foo0--$($($($(", - expected: "foo0--$($($($(", - }, - { - name: "escaped operators in variable names are not escaped", - input: "$(foo$$var)", - expected: "$(foo$$var)", - }, - { - name: "newline not expanded", - input: "\n", - expected: "\n", - }, - } - - for _, tc := range cases { - expanded := Expand(tc.input, mapping) - if e, a := tc.expected, expanded; e != a { - t.Errorf("%v: expected %q, got %q", tc.name, e, a) - } - } -} diff --git a/vendor/k8s.io/utils/.travis.yml b/vendor/k8s.io/utils/.travis.yml index a94480fbab..d39066ccf8 100644 --- a/vendor/k8s.io/utils/.travis.yml +++ b/vendor/k8s.io/utils/.travis.yml @@ -1,7 +1,5 @@ language: go go: - - 1.6.x - - 1.7.x - 1.8.x - 1.9.x go_import_path: k8s.io/utils diff --git a/vendor/k8s.io/utils/README.md b/vendor/k8s.io/utils/README.md index 5ede8710ae..3765eed268 100644 --- a/vendor/k8s.io/utils/README.md +++ b/vendor/k8s.io/utils/README.md @@ -41,7 +41,10 @@ an existing package to this repository. the [FakeExec](exec/testing/fake_exec.go) struct. - [Temp](/temp) provides an interface to create temporary directories. It also - provides a [FakeDir](temp/temptesting) implementation to replace in tests. + provides a [FakeDir](temp/temptest) implementation to replace in tests. + +- [Clock](/clock) provides an interface for time-based operations. It allows + mocking time for testing. [Build Status]: https://travis-ci.org/kubernetes/utils.svg?branch=master [Go standard libs]: https://golang.org/pkg/#stdlib diff --git a/vendor/k8s.io/utils/code-of-conduct.md b/vendor/k8s.io/utils/code-of-conduct.md index 622d4c1d1c..0d15c00cf3 100644 --- a/vendor/k8s.io/utils/code-of-conduct.md +++ b/vendor/k8s.io/utils/code-of-conduct.md @@ -1,5 +1,3 @@ -## Kubernetes Community Code of Conduct +# Kubernetes Community Code of Conduct -Kubernetes follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md). - -[![Analytics](https://kubernetes-site.appspot.com/UA-36037335-10/GitHub/code-of-conduct.md?pixel)]() +Please refer to our [Kubernetes Community Code of Conduct](https://git.k8s.io/community/code-of-conduct.md) diff --git a/vendor/k8s.io/utils/exec/exec.go b/vendor/k8s.io/utils/exec/exec.go index 3b23eceb1c..07735d8814 100644 --- a/vendor/k8s.io/utils/exec/exec.go +++ b/vendor/k8s.io/utils/exec/exec.go @@ -17,6 +17,7 @@ limitations under the License. package exec import ( + "context" "io" osexec "os/exec" "syscall" @@ -33,6 +34,13 @@ type Interface interface { // This follows the pattern of package os/exec. Command(cmd string, args ...string) Cmd + // CommandContext returns a Cmd instance which can be used to run a single command. + // + // The provided context is used to kill the process if the context becomes done + // before the command completes on its own. For example, a timeout can be set in + // the context. + CommandContext(ctx context.Context, cmd string, args ...string) Cmd + // LookPath wraps os/exec.LookPath LookPath(file string) (string, error) } @@ -82,6 +90,11 @@ func (executor *executor) Command(cmd string, args ...string) Cmd { return (*cmdWrapper)(osexec.Command(cmd, args...)) } +// CommandContext is part of the Interface interface. +func (executor *executor) CommandContext(ctx context.Context, cmd string, args ...string) Cmd { + return (*cmdWrapper)(osexec.CommandContext(ctx, cmd, args...)) +} + // LookPath is part of the Interface interface func (executor *executor) LookPath(file string) (string, error) { return osexec.LookPath(file) @@ -110,52 +123,52 @@ func (cmd *cmdWrapper) SetStderr(out io.Writer) { // Run is part of the Cmd interface. func (cmd *cmdWrapper) Run() error { - return (*osexec.Cmd)(cmd).Run() + err := (*osexec.Cmd)(cmd).Run() + return handleError(err) } // CombinedOutput is part of the Cmd interface. func (cmd *cmdWrapper) CombinedOutput() ([]byte, error) { out, err := (*osexec.Cmd)(cmd).CombinedOutput() - if err != nil { - return out, handleError(err) - } - return out, nil + return out, handleError(err) } func (cmd *cmdWrapper) Output() ([]byte, error) { out, err := (*osexec.Cmd)(cmd).Output() - if err != nil { - return out, handleError(err) - } - return out, nil + return out, handleError(err) } // Stop is part of the Cmd interface. func (cmd *cmdWrapper) Stop() { c := (*osexec.Cmd)(cmd) - if c.ProcessState.Exited() { + + if c.Process == nil { return } + c.Process.Signal(syscall.SIGTERM) + time.AfterFunc(10*time.Second, func() { - if c.ProcessState.Exited() { - return + if !c.ProcessState.Exited() { + c.Process.Signal(syscall.SIGKILL) } - c.Process.Signal(syscall.SIGKILL) }) } func handleError(err error) error { - if ee, ok := err.(*osexec.ExitError); ok { - // Force a compile fail if exitErrorWrapper can't convert to ExitError. - var x ExitError = &ExitErrorWrapper{ee} - return x + if err == nil { + return nil } - if ee, ok := err.(*osexec.Error); ok { - if ee.Err == osexec.ErrNotFound { + + switch e := err.(type) { + case *osexec.ExitError: + return &ExitErrorWrapper{e} + case *osexec.Error: + if e.Err == osexec.ErrNotFound { return ErrExecutableNotFound } } + return err } @@ -165,7 +178,7 @@ type ExitErrorWrapper struct { *osexec.ExitError } -var _ ExitError = ExitErrorWrapper{} +var _ ExitError = &ExitErrorWrapper{} // ExitStatus is part of the ExitError interface. func (eew ExitErrorWrapper) ExitStatus() int { diff --git a/vendor/k8s.io/utils/exec/exec_test.go b/vendor/k8s.io/utils/exec/exec_test.go deleted file mode 100644 index bd91587905..0000000000 --- a/vendor/k8s.io/utils/exec/exec_test.go +++ /dev/null @@ -1,103 +0,0 @@ -/* -Copyright 2017 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 exec - -import ( - osexec "os/exec" - "testing" -) - -func TestExecutorNoArgs(t *testing.T) { - ex := New() - - cmd := ex.Command("true") - out, err := cmd.CombinedOutput() - if err != nil { - t.Errorf("expected success, got %v", err) - } - if len(out) != 0 { - t.Errorf("expected no output, got %q", string(out)) - } - - cmd = ex.Command("false") - out, err = cmd.CombinedOutput() - if err == nil { - t.Errorf("expected failure, got nil error") - } - if len(out) != 0 { - t.Errorf("expected no output, got %q", string(out)) - } - ee, ok := err.(ExitError) - if !ok { - t.Errorf("expected an ExitError, got %+v", err) - } - if ee.Exited() { - if code := ee.ExitStatus(); code != 1 { - t.Errorf("expected exit status 1, got %d", code) - } - } - - cmd = ex.Command("/does/not/exist") - out, err = cmd.CombinedOutput() - if err == nil { - t.Errorf("expected failure, got nil error") - } - if ee, ok := err.(ExitError); ok { - t.Errorf("expected non-ExitError, got %+v", ee) - } -} - -func TestExecutorWithArgs(t *testing.T) { - ex := New() - - cmd := ex.Command("echo", "stdout") - out, err := cmd.CombinedOutput() - if err != nil { - t.Errorf("expected success, got %+v", err) - } - if string(out) != "stdout\n" { - t.Errorf("unexpected output: %q", string(out)) - } - - cmd = ex.Command("/bin/sh", "-c", "echo stderr > /dev/stderr") - out, err = cmd.CombinedOutput() - if err != nil { - t.Errorf("expected success, got %+v", err) - } - if string(out) != "stderr\n" { - t.Errorf("unexpected output: %q", string(out)) - } -} - -func TestLookPath(t *testing.T) { - ex := New() - - shExpected, _ := osexec.LookPath("sh") - sh, _ := ex.LookPath("sh") - if sh != shExpected { - t.Errorf("unexpected result for LookPath: got %s, expected %s", sh, shExpected) - } -} - -func TestExecutableNotFound(t *testing.T) { - exec := New() - cmd := exec.Command("fake_executable_name") - _, err := cmd.CombinedOutput() - if err != ErrExecutableNotFound { - t.Errorf("Expected error ErrExecutableNotFound but got %v", err) - } -} diff --git a/vendor/k8s.io/utils/exec/new_test.go b/vendor/k8s.io/utils/exec/new_test.go deleted file mode 100644 index dba9bb3502..0000000000 --- a/vendor/k8s.io/utils/exec/new_test.go +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright 2017 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 exec_test - -import ( - "bytes" - "fmt" - - "k8s.io/utils/exec" -) - -func ExampleNew() { - exec := exec.New() - - cmd := exec.Command("echo", "Bonjour!") - buff := bytes.Buffer{} - cmd.SetStdout(&buff) - if err := cmd.Run(); err != nil { - panic(err) - } - fmt.Println(buff.String()) - // Output: Bonjour! -} From 333f37e554f7986bc1a6ac0462d5f014c1747e1e Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes <aledbf@gmail.com> Date: Sat, 26 May 2018 12:48:59 -0400 Subject: [PATCH 2/6] Add setting to customize the number of e2e nodes --- Makefile | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 3e21b33462..f4e11e19be 100644 --- a/Makefile +++ b/Makefile @@ -24,7 +24,13 @@ GOOS?=linux DOCKER?=docker SED_I?=sed -i GOHOSTOS ?= $(shell go env GOHOSTOS) + +# e2e settings +# Allow limiting the scope of the e2e tests. By default run everything FOCUS?=.* +# number of parallel test +E2E_NODES?=3 + ifeq ($(GOHOSTOS),darwin) SED_I=sed -i '' @@ -158,7 +164,15 @@ lua-test: e2e-test: @ginkgo version || go get -u github.com/onsi/ginkgo/ginkgo @ginkgo build ./test/e2e - @KUBECONFIG=${HOME}/.kube/config ginkgo -randomizeSuites -randomizeAllSpecs -flakeAttempts=2 --focus=$(FOCUS) -p -trace -nodes=2 ./test/e2e/e2e.test + @KUBECONFIG=${HOME}/.kube/config ginkgo \ + -randomizeSuites \ + -randomizeAllSpecs \ + -flakeAttempts=2 \ + --focus=$(FOCUS) \ + -p \ + -trace \ + -nodes=$(E2E_NODES) \ + ./test/e2e/e2e.test .PHONY: cover cover: From 8a0ed4f78731e8e103eb6667604c8e4ae86a99e2 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes <aledbf@gmail.com> Date: Sat, 26 May 2018 12:56:08 -0400 Subject: [PATCH 3/6] Do not run qemu static register automatically --- Makefile | 7 +++++-- images/nginx/Makefile | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index f4e11e19be..6f9fb5ef99 100644 --- a/Makefile +++ b/Makefile @@ -115,8 +115,6 @@ ifeq ($(ARCH),amd64) $(SED_I) "/CROSS_BUILD_/d" $(DOCKERFILE) else # When cross-building, only the placeholder "CROSS_BUILD_" should be removed - # Register /usr/bin/qemu-ARCH-static as the handler for ARM binaries in the kernel - $(DOCKER) run --rm --privileged multiarch/qemu-user-static:register --reset curl -sSL https://github.com/multiarch/qemu-user-static/releases/download/$(QEMUVERSION)/x86_64_qemu-$(QEMUARCH)-static.tar.gz | tar -xz -C $(TEMP_DIR)/rootfs $(SED_I) "s/CROSS_BUILD_//g" $(DOCKERFILE) endif @@ -128,6 +126,11 @@ ifeq ($(ARCH), amd64) $(DOCKER) tag $(MULTI_ARCH_IMG):$(TAG) $(IMAGE):$(TAG) endif +.PHONY: register-qemu +register-qemu: + # Register /usr/bin/qemu-ARCH-static as the handler for binaries in multiple platforms + $(DOCKER) run --rm --privileged multiarch/qemu-user-static:register --reset + .PHONY: push push: .push-$(ARCH) diff --git a/images/nginx/Makefile b/images/nginx/Makefile index 6c0428c0e4..191aa63845 100644 --- a/images/nginx/Makefile +++ b/images/nginx/Makefile @@ -76,8 +76,6 @@ ifeq ($(ARCH),amd64) cd $(TEMP_DIR) && $(SED_I) "/CROSS_BUILD_/d" Dockerfile else # When cross-building, only the placeholder "CROSS_BUILD_" should be removed - # Register /usr/bin/qemu-ARCH-static as the handler for ARM binaries in the kernel - $(DOCKER) run --rm --privileged multiarch/qemu-user-static:register --reset curl -sSL https://github.com/multiarch/qemu-user-static/releases/download/$(QEMUVERSION)/x86_64_qemu-$(QEMUARCH)-static.tar.gz | tar -xz -C $(TEMP_DIR) cd $(TEMP_DIR) && $(SED_I) "s/CROSS_BUILD_//g" Dockerfile endif @@ -89,6 +87,11 @@ ifeq ($(ARCH), amd64) $(DOCKER) tag $(MULTI_ARCH_IMG):$(TAG) $(IMAGE):$(TAG) endif +.PHONY: register-qemu +register-qemu: + # Register /usr/bin/qemu-ARCH-static as the handler for binaries in multiple platforms + $(DOCKER) run --rm --privileged multiarch/qemu-user-static:register --reset + push: .push-$(ARCH) .push-$(ARCH): .container-$(ARCH) $(DOCKER) push $(MULTI_ARCH_IMG):$(TAG) From 5dd1b1319c62e3e9e19e851f7e95419f3d33dd87 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes <aledbf@gmail.com> Date: Sat, 26 May 2018 16:15:31 -0400 Subject: [PATCH 4/6] Fix ClusterRoleBinding for e2e tests --- test/manifests/ingress-controller/mandatory.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/manifests/ingress-controller/mandatory.yaml b/test/manifests/ingress-controller/mandatory.yaml index 15af034c20..e09e7dddcb 100644 --- a/test/manifests/ingress-controller/mandatory.yaml +++ b/test/manifests/ingress-controller/mandatory.yaml @@ -181,7 +181,7 @@ rules: apiVersion: rbac.authorization.k8s.io/v1beta1 kind: RoleBinding metadata: - name: nginx-ingress-role-nisa-binding + name: nginx-ingress-role-${NAMESPACE} roleRef: apiGroup: rbac.authorization.k8s.io kind: Role @@ -196,7 +196,7 @@ subjects: apiVersion: rbac.authorization.k8s.io/v1beta1 kind: ClusterRoleBinding metadata: - name: nginx-ingress-clusterrole-nisa-binding + name: nginx-ingress-clusterrole-${NAMESPACE} roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole @@ -205,6 +205,7 @@ subjects: - kind: ServiceAccount name: nginx-ingress-serviceaccount namespace: ${NAMESPACE} + --- apiVersion: extensions/v1beta1 From 564f2a9fe4d1b4d65ea00a8cc234e0c233414dae Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes <aledbf@gmail.com> Date: Sat, 26 May 2018 16:27:21 -0400 Subject: [PATCH 5/6] Add retries to auth test checks --- test/e2e/annotations/auth.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/e2e/annotations/auth.go b/test/e2e/annotations/auth.go index 0f2b340466..31cc1f5042 100644 --- a/test/e2e/annotations/auth.go +++ b/test/e2e/annotations/auth.go @@ -20,6 +20,7 @@ import ( "fmt" "net/http" "os/exec" + "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -58,6 +59,7 @@ var _ = framework.IngressNginxDescribe("Annotations - Auth", func() { resp, body, errs := gorequest.New(). Get(f.IngressController.HTTPURL). + Retry(10, 1*time.Second, http.StatusNotFound). Set("Host", host). End() @@ -90,6 +92,7 @@ var _ = framework.IngressNginxDescribe("Annotations - Auth", func() { resp, body, errs := gorequest.New(). Get(f.IngressController.HTTPURL). + Retry(10, 1*time.Second, http.StatusNotFound). Set("Host", host). End() @@ -127,6 +130,7 @@ var _ = framework.IngressNginxDescribe("Annotations - Auth", func() { resp, body, errs := gorequest.New(). Get(f.IngressController.HTTPURL). + Retry(10, 1*time.Second, http.StatusNotFound). Set("Host", host). End() @@ -164,6 +168,7 @@ var _ = framework.IngressNginxDescribe("Annotations - Auth", func() { resp, body, errs := gorequest.New(). Get(f.IngressController.HTTPURL). + Retry(10, 1*time.Second, http.StatusNotFound). Set("Host", host). SetBasicAuth("user", "pass"). End() @@ -202,6 +207,7 @@ var _ = framework.IngressNginxDescribe("Annotations - Auth", func() { resp, _, errs := gorequest.New(). Get(f.IngressController.HTTPURL). + Retry(10, 1*time.Second, http.StatusNotFound). Set("Host", host). SetBasicAuth("foo", "bar"). End() @@ -251,6 +257,7 @@ var _ = framework.IngressNginxDescribe("Annotations - Auth", func() { resp, _, errs := gorequest.New(). Get(f.IngressController.HTTPURL). + Retry(10, 1*time.Second, http.StatusNotFound). Set("Host", host). SetBasicAuth("foo", "bar"). End() From 2c226ef0fb43a2e9b2df68fb0a07796a5f5caf14 Mon Sep 17 00:00:00 2001 From: Manuel de Brito Fontes <aledbf@gmail.com> Date: Sat, 26 May 2018 17:11:15 -0400 Subject: [PATCH 6/6] Fix influxdb test flake --- test/e2e/annotations/influxdb.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/test/e2e/annotations/influxdb.go b/test/e2e/annotations/influxdb.go index f72825ba52..0adfd4657d 100644 --- a/test/e2e/annotations/influxdb.go +++ b/test/e2e/annotations/influxdb.go @@ -31,6 +31,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" + "k8s.io/apimachinery/pkg/util/wait" "k8s.io/ingress-nginx/test/e2e/framework" ) @@ -77,12 +78,20 @@ var _ = framework.IngressNginxDescribe("Annotations - influxdb", func() { Expect(res.StatusCode).Should(Equal(http.StatusOK)) time.Sleep(5 * time.Second) - measurements, err := extractInfluxDBMeasurements(f) + + var measurements string + err = wait.PollImmediate(time.Second, time.Minute, func() (bool, error) { + measurements, err = extractInfluxDBMeasurements(f) + if err != nil { + return false, nil + } + return true, nil + }) + Expect(err).NotTo(HaveOccurred()) var results map[string][]map[string]interface{} json.Unmarshal([]byte(measurements), &results) - Expect(err).NotTo(HaveOccurred()) Expect(len(measurements)).ShouldNot(Equal(0)) for _, elem := range results["results"] { Expect(len(elem)).ShouldNot(Equal(0))